JavascriptArray.cpp 492 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766
  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. namespace Js
  11. {
  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. #if defined(TARGET_64)
  27. const Var JavascriptArray::MissingItem = (Var)0x8000000280000002;
  28. uint JavascriptNativeIntArray::allocationBuckets[][AllocationBucketsInfoSize] =
  29. {
  30. // See comments above on how to read this
  31. {2, 0, 0},
  32. {6, 0, 0},
  33. {8, 0, 0},
  34. };
  35. uint JavascriptArray::allocationBuckets[][AllocationBucketsInfoSize] =
  36. {
  37. // See comments above on how to read this
  38. {4, 0, 0},
  39. {6, 0, 0},
  40. {8, 0, 0},
  41. };
  42. #else
  43. const Var JavascriptArray::MissingItem = (Var)0x80000002;
  44. uint JavascriptNativeIntArray::allocationBuckets[][AllocationBucketsInfoSize] =
  45. {
  46. // See comments above on how to read this
  47. { 3, 0, 0 },
  48. { 7, 0, 0 },
  49. { 8, 0, 0 },
  50. };
  51. uint JavascriptArray::allocationBuckets[][AllocationBucketsInfoSize] =
  52. {
  53. // See comments above on how to read this
  54. { 4, 0, 0 },
  55. { 8, 0, 0 },
  56. };
  57. #endif
  58. const int32 JavascriptNativeIntArray::MissingItem = 0x80000002;
  59. static const uint64 FloatMissingItemPattern = 0x8000000280000002ull;
  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::Is(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::Is(Var aValue)
  398. {
  399. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  400. return JavascriptArray::Is(typeId);
  401. }
  402. bool JavascriptArray::Is(TypeId typeId)
  403. {
  404. return typeId >= TypeIds_ArrayFirst && typeId <= TypeIds_ArrayLast;
  405. }
  406. bool JavascriptArray::IsVarArray(Var aValue)
  407. {
  408. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  409. return JavascriptArray::IsVarArray(typeId);
  410. }
  411. bool JavascriptArray::IsVarArray(TypeId typeId)
  412. {
  413. return typeId == TypeIds_Array;
  414. }
  415. template<typename T>
  416. bool JavascriptArray::IsMissingItemAt(uint32 index) const
  417. {
  418. SparseArraySegment<T>* headSeg = SparseArraySegment<T>::From(this->head);
  419. return SparseArraySegment<T>::IsMissingItem(&headSeg->elements[index]);
  420. }
  421. bool JavascriptArray::IsMissingItem(uint32 index)
  422. {
  423. if (!(this->head->left <= index && index < (this->head->left+ this->head->length)))
  424. {
  425. return false;
  426. }
  427. bool isIntArray = false, isFloatArray = false;
  428. this->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
  429. if (isIntArray)
  430. {
  431. return IsMissingItemAt<int32>(index);
  432. }
  433. else if (isFloatArray)
  434. {
  435. return IsMissingItemAt<double>(index);
  436. }
  437. else
  438. {
  439. return IsMissingItemAt<Var>(index);
  440. }
  441. }
  442. JavascriptArray* JavascriptArray::FromVar(Var aValue)
  443. {
  444. AssertOrFailFastMsg(Is(aValue), "Ensure var is actually a 'JavascriptArray'");
  445. return static_cast<JavascriptArray *>(aValue);
  446. }
  447. JavascriptArray* JavascriptArray::UnsafeFromVar(Var aValue)
  448. {
  449. AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptArray'");
  450. return static_cast<JavascriptArray *>(aValue);
  451. }
  452. // Get JavascriptArray* from a Var, which is either a JavascriptArray* or ESArray*.
  453. JavascriptArray* JavascriptArray::FromAnyArray(Var aValue)
  454. {
  455. AssertOrFailFastMsg(Is(aValue) || ES5Array::Is(aValue), "Ensure var is actually a 'JavascriptArray' or 'ES5Array'");
  456. return static_cast<JavascriptArray *>(RecyclableObject::FromVar(aValue));
  457. }
  458. JavascriptArray* JavascriptArray::UnsafeFromAnyArray(Var aValue)
  459. {
  460. AssertMsg(Is(aValue) || ES5Array::Is(aValue), "Ensure var is actually a 'JavascriptArray' or 'ES5Array'");
  461. return static_cast<JavascriptArray *>(RecyclableObject::UnsafeFromVar(aValue));
  462. }
  463. // Check if a Var is a direct-accessible (fast path) JavascriptArray.
  464. bool JavascriptArray::IsDirectAccessArray(Var aValue)
  465. {
  466. return RecyclableObject::Is(aValue) &&
  467. (VirtualTableInfo<JavascriptArray>::HasVirtualTable(aValue) ||
  468. VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(aValue) ||
  469. VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(aValue));
  470. }
  471. bool JavascriptArray::IsInlineSegment(SparseArraySegmentBase *seg, JavascriptArray *pArr)
  472. {
  473. if (seg == nullptr)
  474. {
  475. return false;
  476. }
  477. SparseArraySegmentBase* inlineHeadSegment = nullptr;
  478. if (JavascriptNativeArray::Is(pArr))
  479. {
  480. if (JavascriptNativeFloatArray::Is(pArr))
  481. {
  482. inlineHeadSegment = DetermineInlineHeadSegmentPointer<JavascriptNativeFloatArray, 0, true>((JavascriptNativeFloatArray*)pArr);
  483. }
  484. else
  485. {
  486. AssertOrFailFast(JavascriptNativeIntArray::Is(pArr));
  487. inlineHeadSegment = DetermineInlineHeadSegmentPointer<JavascriptNativeIntArray, 0, true>((JavascriptNativeIntArray*)pArr);
  488. }
  489. Assert(inlineHeadSegment);
  490. return (seg == inlineHeadSegment);
  491. }
  492. // This will result in false positives. It is used because DetermineInlineHeadSegmentPointer
  493. // does not handle Arrays that change type e.g. from JavascriptNativeIntArray to JavascriptArray
  494. // This conversion in particular is problematic because JavascriptNativeIntArray is larger than JavascriptArray
  495. // so the returned head segment ptr never equals pArr->head. So we will default to using this and deal with
  496. // false positives. It is better than always doing a hard copy.
  497. return pArr->head != nullptr && HasInlineHeadSegment(pArr->head->length);
  498. }
  499. DynamicObjectFlags JavascriptArray::GetFlags() const
  500. {
  501. return GetArrayFlags();
  502. }
  503. DynamicObjectFlags JavascriptArray::GetFlags_Unchecked() const // do not use except in extreme circumstances
  504. {
  505. return GetArrayFlags_Unchecked();
  506. }
  507. void JavascriptArray::SetFlags(const DynamicObjectFlags flags)
  508. {
  509. SetArrayFlags(flags);
  510. }
  511. DynamicType * JavascriptArray::GetInitialType(ScriptContext * scriptContext)
  512. {
  513. return scriptContext->GetLibrary()->GetArrayType();
  514. }
  515. JavascriptArray *JavascriptArray::GetArrayForArrayOrObjectWithArray(const Var var)
  516. {
  517. bool isObjectWithArray;
  518. TypeId arrayTypeId;
  519. return GetArrayForArrayOrObjectWithArray(var, &isObjectWithArray, &arrayTypeId);
  520. }
  521. JavascriptArray *JavascriptArray::GetArrayForArrayOrObjectWithArray(
  522. const Var var,
  523. bool *const isObjectWithArrayRef,
  524. TypeId *const arrayTypeIdRef)
  525. {
  526. // This is a helper function used by jitted code. The array checks done here match the array checks done by jitted code
  527. // (see Lowerer::GenerateArrayTest) to minimize bailouts.
  528. Assert(var);
  529. Assert(isObjectWithArrayRef);
  530. Assert(arrayTypeIdRef);
  531. *isObjectWithArrayRef = false;
  532. *arrayTypeIdRef = TypeIds_Undefined;
  533. if(!RecyclableObject::Is(var))
  534. {
  535. return nullptr;
  536. }
  537. JavascriptArray *array = nullptr;
  538. INT_PTR vtable = VirtualTableInfoBase::GetVirtualTable(var);
  539. if(vtable == VirtualTableInfo<DynamicObject>::Address)
  540. {
  541. ArrayObject* objectArray = DynamicObject::FromVar(var)->GetObjectArray();
  542. array = (objectArray && Is(objectArray)) ? FromVar(objectArray) : nullptr;
  543. if(!array)
  544. {
  545. return nullptr;
  546. }
  547. *isObjectWithArrayRef = true;
  548. vtable = VirtualTableInfoBase::GetVirtualTable(array);
  549. }
  550. if(vtable == VirtualTableInfo<JavascriptArray>::Address)
  551. {
  552. *arrayTypeIdRef = TypeIds_Array;
  553. }
  554. else if(vtable == VirtualTableInfo<JavascriptNativeIntArray>::Address)
  555. {
  556. *arrayTypeIdRef = TypeIds_NativeIntArray;
  557. }
  558. else if(vtable == VirtualTableInfo<JavascriptNativeFloatArray>::Address)
  559. {
  560. *arrayTypeIdRef = TypeIds_NativeFloatArray;
  561. }
  562. else
  563. {
  564. return nullptr;
  565. }
  566. if(!array)
  567. {
  568. array = FromVar(var);
  569. }
  570. return array;
  571. }
  572. const SparseArraySegmentBase *JavascriptArray::Jit_GetArrayHeadSegmentForArrayOrObjectWithArray(const Var var)
  573. {
  574. // This is a helper function used by jitted code
  575. JavascriptArray *const array = GetArrayForArrayOrObjectWithArray(var);
  576. return array ? array->head : nullptr;
  577. }
  578. uint32 JavascriptArray::Jit_GetArrayHeadSegmentLength(const SparseArraySegmentBase *const headSegment)
  579. {
  580. // This is a helper function used by jitted code
  581. return headSegment ? headSegment->length : 0;
  582. }
  583. bool JavascriptArray::Jit_OperationInvalidatedArrayHeadSegment(
  584. const SparseArraySegmentBase *const headSegmentBeforeOperation,
  585. const uint32 headSegmentLengthBeforeOperation,
  586. const Var varAfterOperation)
  587. {
  588. // This is a helper function used by jitted code
  589. Assert(varAfterOperation);
  590. if(!headSegmentBeforeOperation)
  591. {
  592. return false;
  593. }
  594. const SparseArraySegmentBase *const headSegmentAfterOperation =
  595. Jit_GetArrayHeadSegmentForArrayOrObjectWithArray(varAfterOperation);
  596. return
  597. headSegmentAfterOperation != headSegmentBeforeOperation ||
  598. headSegmentAfterOperation->length != headSegmentLengthBeforeOperation;
  599. }
  600. uint32 JavascriptArray::Jit_GetArrayLength(const Var var)
  601. {
  602. // This is a helper function used by jitted code
  603. bool isObjectWithArray;
  604. TypeId arrayTypeId;
  605. JavascriptArray *const array = GetArrayForArrayOrObjectWithArray(var, &isObjectWithArray, &arrayTypeId);
  606. return array && !isObjectWithArray ? array->GetLength() : 0;
  607. }
  608. bool JavascriptArray::Jit_OperationInvalidatedArrayLength(const uint32 lengthBeforeOperation, const Var varAfterOperation)
  609. {
  610. // This is a helper function used by jitted code
  611. return Jit_GetArrayLength(varAfterOperation) != lengthBeforeOperation;
  612. }
  613. DynamicObjectFlags JavascriptArray::Jit_GetArrayFlagsForArrayOrObjectWithArray(const Var var)
  614. {
  615. // This is a helper function used by jitted code
  616. JavascriptArray *const array = GetArrayForArrayOrObjectWithArray(var);
  617. return array && array->UsesObjectArrayOrFlagsAsFlags() ? array->GetFlags() : DynamicObjectFlags::None;
  618. }
  619. bool JavascriptArray::Jit_OperationCreatedFirstMissingValue(
  620. const DynamicObjectFlags flagsBeforeOperation,
  621. const Var varAfterOperation)
  622. {
  623. // This is a helper function used by jitted code
  624. Assert(varAfterOperation);
  625. return
  626. !!(flagsBeforeOperation & DynamicObjectFlags::HasNoMissingValues) &&
  627. !(Jit_GetArrayFlagsForArrayOrObjectWithArray(varAfterOperation) & DynamicObjectFlags::HasNoMissingValues);
  628. }
  629. bool JavascriptArray::HasNoMissingValues() const
  630. {
  631. return !!(GetFlags() & DynamicObjectFlags::HasNoMissingValues);
  632. }
  633. bool JavascriptArray::HasNoMissingValues_Unchecked() const // do not use except in extreme circumstances
  634. {
  635. return !!(GetFlags_Unchecked() & DynamicObjectFlags::HasNoMissingValues);
  636. }
  637. void JavascriptArray::SetHasNoMissingValues(const bool hasNoMissingValues)
  638. {
  639. SetFlags(
  640. hasNoMissingValues
  641. ? GetFlags() | DynamicObjectFlags::HasNoMissingValues
  642. : GetFlags() & ~DynamicObjectFlags::HasNoMissingValues);
  643. }
  644. template<class T>
  645. bool JavascriptArray::IsMissingHeadSegmentItemImpl(const uint32 index) const
  646. {
  647. Assert(index < head->length);
  648. return SparseArraySegment<T>::IsMissingItem(&SparseArraySegment<T>::From(head)->elements[index]);
  649. }
  650. bool JavascriptArray::IsMissingHeadSegmentItem(const uint32 index) const
  651. {
  652. return IsMissingHeadSegmentItemImpl<Var>(index);
  653. }
  654. #if ENABLE_COPYONACCESS_ARRAY
  655. void JavascriptCopyOnAccessNativeIntArray::ConvertCopyOnAccessSegment()
  656. {
  657. Assert(this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->IsValidIndex(::Math::PointerCastToIntegral<uint32>(this->GetHead())));
  658. SparseArraySegment<int32> *seg = this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->GetSegmentByIndex(::Math::PointerCastToIntegral<byte>(this->GetHead()));
  659. SparseArraySegment<int32> *newSeg = SparseArraySegment<int32>::AllocateLiteralHeadSegment(this->GetRecycler(), seg->length);
  660. #if ENABLE_DEBUG_CONFIG_OPTIONS
  661. if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::CopyOnAccessArrayPhase))
  662. {
  663. Output::Print(_u("Convert copy-on-access array: index(%d) length(%d)\n"), this->GetHead(), seg->length);
  664. Output::Flush();
  665. }
  666. #endif
  667. newSeg->CopySegment(this->GetRecycler(), newSeg, 0, seg, 0, seg->length);
  668. this->SetHeadAndLastUsedSegment(newSeg);
  669. VirtualTableInfo<JavascriptNativeIntArray>::SetVirtualTable(this);
  670. this->type = JavascriptNativeIntArray::GetInitialType(this->GetScriptContext());
  671. ArrayCallSiteInfo *arrayInfo = this->GetArrayCallSiteInfo();
  672. if (arrayInfo && !arrayInfo->isNotCopyOnAccessArray)
  673. {
  674. arrayInfo->isNotCopyOnAccessArray = 1;
  675. }
  676. }
  677. uint32 JavascriptCopyOnAccessNativeIntArray::GetNextIndex(uint32 index) const
  678. {
  679. if (this->length == 0 || (index != Js::JavascriptArray::InvalidIndex && index >= this->length))
  680. {
  681. return Js::JavascriptArray::InvalidIndex;
  682. }
  683. else if (index == Js::JavascriptArray::InvalidIndex)
  684. {
  685. return 0;
  686. }
  687. else
  688. {
  689. return index + 1;
  690. }
  691. }
  692. BOOL JavascriptCopyOnAccessNativeIntArray::DirectGetItemAt(uint32 index, int* outVal)
  693. {
  694. Assert(this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->IsValidIndex(::Math::PointerCastToIntegral<uint32>(this->GetHead())));
  695. SparseArraySegment<int32> *seg = this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->GetSegmentByIndex(::Math::PointerCastToIntegral<byte>(this->GetHead()));
  696. if (this->length == 0 || index == Js::JavascriptArray::InvalidIndex || index >= this->length)
  697. {
  698. return FALSE;
  699. }
  700. else
  701. {
  702. *outVal = seg->elements[index];
  703. return TRUE;
  704. }
  705. }
  706. #endif
  707. bool JavascriptNativeIntArray::IsMissingHeadSegmentItem(const uint32 index) const
  708. {
  709. return IsMissingHeadSegmentItemImpl<int32>(index);
  710. }
  711. bool JavascriptNativeFloatArray::IsMissingHeadSegmentItem(const uint32 index) const
  712. {
  713. return IsMissingHeadSegmentItemImpl<double>(index);
  714. }
  715. void JavascriptArray::InternalFillFromPrototype(JavascriptArray *dstArray, uint32 dstIndex, JavascriptArray *srcArray, uint32 start, uint32 end, uint32 count)
  716. {
  717. RecyclableObject* prototype = srcArray->GetPrototype();
  718. while (start + count != end && !JavascriptOperators::IsNull(prototype))
  719. {
  720. ForEachOwnMissingArrayIndexOfObject(srcArray, dstArray, prototype, start, end, dstIndex, [&](uint32 index, Var value) {
  721. uint32 n = dstIndex + (index - start);
  722. dstArray->SetItem(n, value, PropertyOperation_None);
  723. count++;
  724. });
  725. prototype = prototype->GetPrototype();
  726. }
  727. }
  728. /* static */
  729. bool JavascriptArray::HasInlineHeadSegment(uint32 length)
  730. {
  731. return length <= SparseArraySegmentBase::INLINE_CHUNK_SIZE;
  732. }
  733. Var JavascriptArray::OP_NewScArray(uint32 elementCount, ScriptContext* scriptContext)
  734. {
  735. // Called only to create array literals: size is known.
  736. return scriptContext->GetLibrary()->CreateArrayLiteral(elementCount);
  737. }
  738. Var JavascriptArray::OP_NewScArrayWithElements(uint32 elementCount, Var *elements, ScriptContext* scriptContext)
  739. {
  740. // Called only to create array literals: size is known.
  741. JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(elementCount);
  742. SparseArraySegment<Var> *head = SparseArraySegment<Var>::From(arr->head);
  743. Assert(elementCount <= head->length);
  744. CopyArray(head->elements, head->length, elements, elementCount);
  745. #ifdef VALIDATE_ARRAY
  746. arr->ValidateArray();
  747. #endif
  748. return arr;
  749. }
  750. Var JavascriptArray::OP_NewScArrayWithMissingValues(uint32 elementCount, ScriptContext* scriptContext)
  751. {
  752. // Called only to create array literals: size is known.
  753. JavascriptArray *const array = static_cast<JavascriptArray *>(OP_NewScArray(elementCount, scriptContext));
  754. array->SetHasNoMissingValues(false);
  755. SparseArraySegment<Var> *head = SparseArraySegment<Var>::From(array->head);
  756. head->FillSegmentBuffer(0, elementCount);
  757. return array;
  758. }
  759. #if ENABLE_PROFILE_INFO
  760. Var JavascriptArray::ProfiledNewScArray(uint32 elementCount, ScriptContext *scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
  761. {
  762. if (arrayInfo->IsNativeIntArray())
  763. {
  764. JavascriptNativeIntArray *arr = scriptContext->GetLibrary()->CreateNativeIntArrayLiteral(elementCount);
  765. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  766. return arr;
  767. }
  768. if (arrayInfo->IsNativeFloatArray())
  769. {
  770. JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(elementCount);
  771. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  772. return arr;
  773. }
  774. JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(elementCount);
  775. return arr;
  776. }
  777. #endif
  778. Var JavascriptArray::OP_NewScIntArray(AuxArray<int32> *ints, ScriptContext* scriptContext)
  779. {
  780. uint32 count = ints->count;
  781. JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(count);
  782. SparseArraySegment<Var> *head = SparseArraySegment<Var>::From(arr->head);
  783. Assert(count > 0 && count == head->length);
  784. for (uint i = 0; i < count; i++)
  785. {
  786. head->elements[i] = JavascriptNumber::ToVar(ints->elements[i], scriptContext);
  787. }
  788. return arr;
  789. }
  790. #if ENABLE_PROFILE_INFO
  791. Var JavascriptArray::ProfiledNewScIntArray(AuxArray<int32> *ints, ScriptContext* scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
  792. {
  793. // Called only to create array literals: size is known.
  794. uint32 count = ints->count;
  795. if (arrayInfo->IsNativeIntArray())
  796. {
  797. JavascriptNativeIntArray *arr;
  798. #if ENABLE_COPYONACCESS_ARRAY
  799. JavascriptLibrary *lib = scriptContext->GetLibrary();
  800. FunctionBody *functionBody = weakFuncRef->Get();
  801. if (JavascriptLibrary::IsCopyOnAccessArrayCallSite(lib, arrayInfo, count))
  802. {
  803. Assert(lib->cacheForCopyOnAccessArraySegments);
  804. arr = scriptContext->GetLibrary()->CreateCopyOnAccessNativeIntArrayLiteral(arrayInfo, functionBody, ints);
  805. }
  806. else
  807. #endif
  808. {
  809. arr = scriptContext->GetLibrary()->CreateNativeIntArrayLiteral(count);
  810. SparseArraySegment<int32> *head = SparseArraySegment<int32>::From(arr->head);
  811. Assert(count > 0 && count == head->length);
  812. CopyArray(head->elements, head->length, ints->elements, count);
  813. }
  814. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  815. return arr;
  816. }
  817. if (arrayInfo->IsNativeFloatArray())
  818. {
  819. JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(count);
  820. SparseArraySegment<double> *head = SparseArraySegment<double>::From(arr->head);
  821. Assert(count > 0 && count == head->length);
  822. for (uint i = 0; i < count; i++)
  823. {
  824. head->elements[i] = (double)ints->elements[i];
  825. }
  826. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  827. return arr;
  828. }
  829. return OP_NewScIntArray(ints, scriptContext);
  830. }
  831. #endif
  832. Var JavascriptArray::OP_NewScFltArray(AuxArray<double> *doubles, ScriptContext* scriptContext)
  833. {
  834. uint32 count = doubles->count;
  835. JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(count);
  836. SparseArraySegment<Var> *head = SparseArraySegment<Var>::From(arr->head);
  837. Assert(count > 0 && count == head->length);
  838. for (uint i = 0; i < count; i++)
  839. {
  840. double dval = doubles->elements[i];
  841. int32 ival;
  842. if (JavascriptNumber::TryGetInt32Value(dval, &ival) && !TaggedInt::IsOverflow(ival))
  843. {
  844. head->elements[i] = TaggedInt::ToVarUnchecked(ival);
  845. }
  846. else
  847. {
  848. head->elements[i] = JavascriptNumber::ToVarNoCheck(dval, scriptContext);
  849. }
  850. }
  851. return arr;
  852. }
  853. #if ENABLE_PROFILE_INFO
  854. Var JavascriptArray::ProfiledNewScFltArray(AuxArray<double> *doubles, ScriptContext* scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
  855. {
  856. // Called only to create array literals: size is known.
  857. if (arrayInfo->IsNativeFloatArray())
  858. {
  859. arrayInfo->SetIsNotNativeIntArray();
  860. uint32 count = doubles->count;
  861. JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(count);
  862. SparseArraySegment<double> *head = SparseArraySegment<double>::From(arr->head);
  863. Assert(count > 0 && count == head->length);
  864. CopyArray(head->elements, head->length, doubles->elements, count);
  865. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  866. return arr;
  867. }
  868. return OP_NewScFltArray(doubles, scriptContext);
  869. }
  870. Var JavascriptArray::ProfiledNewInstance(RecyclableObject* function, CallInfo callInfo, ...)
  871. {
  872. ARGUMENTS(args, callInfo);
  873. Assert(JavascriptFunction::Is(function) &&
  874. JavascriptFunction::FromVar(function)->GetFunctionInfo() == &JavascriptArray::EntryInfo::NewInstance);
  875. Assert(callInfo.Count >= 2);
  876. ArrayCallSiteInfo *arrayInfo = (ArrayCallSiteInfo*)args[0];
  877. JavascriptArray* pNew = nullptr;
  878. if (callInfo.Count == 2)
  879. {
  880. // Exactly one argument, which is the array length if it's a uint32.
  881. Var firstArgument = args[1];
  882. int elementCount;
  883. if (TaggedInt::Is(firstArgument))
  884. {
  885. elementCount = TaggedInt::ToInt32(firstArgument);
  886. if (elementCount < 0)
  887. {
  888. JavascriptError::ThrowRangeError(function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  889. }
  890. if (arrayInfo && arrayInfo->IsNativeArray())
  891. {
  892. if (arrayInfo->IsNativeIntArray())
  893. {
  894. pNew = function->GetLibrary()->CreateNativeIntArray(elementCount);
  895. }
  896. else
  897. {
  898. pNew = function->GetLibrary()->CreateNativeFloatArray(elementCount);
  899. }
  900. }
  901. else
  902. {
  903. pNew = function->GetLibrary()->CreateArray(elementCount);
  904. }
  905. }
  906. else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
  907. {
  908. // Non-tagged-int number: make sure the double value is really a uint32.
  909. double value = JavascriptNumber::GetValue(firstArgument);
  910. uint32 uvalue = JavascriptConversion::ToUInt32(value);
  911. if (value != uvalue)
  912. {
  913. JavascriptError::ThrowRangeError(function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  914. }
  915. if (arrayInfo && arrayInfo->IsNativeArray())
  916. {
  917. if (arrayInfo->IsNativeIntArray())
  918. {
  919. pNew = function->GetLibrary()->CreateNativeIntArray(uvalue);
  920. }
  921. else
  922. {
  923. pNew = function->GetLibrary()->CreateNativeFloatArray(uvalue);
  924. }
  925. }
  926. else
  927. {
  928. pNew = function->GetLibrary()->CreateArray(uvalue);
  929. }
  930. }
  931. else
  932. {
  933. //
  934. // First element is not int/double
  935. // create an array of length 1.
  936. // Set first element as the passed Var
  937. //
  938. pNew = function->GetLibrary()->CreateArray(1);
  939. pNew->DirectSetItemAt<Var>(0, firstArgument);
  940. }
  941. }
  942. else
  943. {
  944. // Called with a list of initial element values.
  945. // Create an array of the appropriate length and walk the list.
  946. if (arrayInfo && arrayInfo->IsNativeArray())
  947. {
  948. if (arrayInfo->IsNativeIntArray())
  949. {
  950. pNew = function->GetLibrary()->CreateNativeIntArray(callInfo.Count - 1);
  951. }
  952. else
  953. {
  954. pNew = function->GetLibrary()->CreateNativeFloatArray(callInfo.Count - 1);
  955. }
  956. }
  957. else
  958. {
  959. pNew = function->GetLibrary()->CreateArray(callInfo.Count - 1);
  960. }
  961. pNew->FillFromArgs(callInfo.Count - 1, 0, args.Values, arrayInfo);
  962. }
  963. #ifdef VALIDATE_ARRAY
  964. pNew->ValidateArray();
  965. #endif
  966. return pNew;
  967. }
  968. #endif
  969. Var JavascriptArray::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
  970. {
  971. ARGUMENTS(args, callInfo);
  972. return NewInstance(function, args);
  973. }
  974. Var JavascriptArray::NewInstance(RecyclableObject* function, Arguments args)
  975. {
  976. // Call to new Array(), possibly under another name.
  977. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  978. // SkipDefaultNewObject function flag should have prevented the default object
  979. // being created, except when call true a host dispatch.
  980. const CallInfo &callInfo = args.Info;
  981. Var newTarget = args.GetNewTarget();
  982. bool isCtorSuperCall = JavascriptOperators::GetAndAssertIsConstructorSuperCall(args);
  983. ScriptContext* scriptContext = function->GetScriptContext();
  984. JavascriptArray* pNew = nullptr;
  985. if (callInfo.Count < 2)
  986. {
  987. // No arguments passed to Array(), so create with the default size (0).
  988. pNew = CreateArrayFromConstructorNoArg(function, scriptContext);
  989. return isCtorSuperCall ?
  990. JavascriptOperators::OrdinaryCreateFromConstructor(RecyclableObject::FromVar(newTarget), pNew, nullptr, scriptContext) :
  991. pNew;
  992. }
  993. if (callInfo.Count == 2)
  994. {
  995. // Exactly one argument, which is the array length if it's a uint32.
  996. Var firstArgument = args[1];
  997. int elementCount;
  998. if (TaggedInt::Is(firstArgument))
  999. {
  1000. elementCount = TaggedInt::ToInt32(firstArgument);
  1001. if (elementCount < 0)
  1002. {
  1003. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  1004. }
  1005. pNew = CreateArrayFromConstructor(function, elementCount, scriptContext);
  1006. }
  1007. else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
  1008. {
  1009. // Non-tagged-int number: make sure the double value is really a uint32.
  1010. double value = JavascriptNumber::GetValue(firstArgument);
  1011. uint32 uvalue = JavascriptConversion::ToUInt32(value);
  1012. if (value != uvalue)
  1013. {
  1014. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  1015. }
  1016. pNew = CreateArrayFromConstructor(function, uvalue, scriptContext);
  1017. }
  1018. else
  1019. {
  1020. //
  1021. // First element is not int/double
  1022. // create an array of length 1.
  1023. // Set first element as the passed Var
  1024. //
  1025. pNew = CreateArrayFromConstructor(function, 1, scriptContext);
  1026. JavascriptOperators::SetItem(pNew, pNew, 0u, firstArgument, scriptContext, PropertyOperation_ThrowIfNotExtensible);
  1027. // If we were passed an uninitialized JavascriptArray as the this argument,
  1028. // we need to set the length. We must do this _after_ setting the first
  1029. // element as the array may have side effects such as a setter for property
  1030. // named '0' which would make the previous length of the array observable.
  1031. // If we weren't passed a JavascriptArray as the this argument, this is no-op.
  1032. pNew->SetLength(1);
  1033. }
  1034. }
  1035. else
  1036. {
  1037. // Called with a list of initial element values.
  1038. // Create an array of the appropriate length and walk the list.
  1039. pNew = CreateArrayFromConstructor(function, callInfo.Count - 1, scriptContext);
  1040. pNew->JavascriptArray::FillFromArgs(callInfo.Count - 1, 0, args.Values);
  1041. }
  1042. #ifdef VALIDATE_ARRAY
  1043. pNew->ValidateArray();
  1044. #endif
  1045. return isCtorSuperCall ?
  1046. JavascriptOperators::OrdinaryCreateFromConstructor(RecyclableObject::FromVar(newTarget), pNew, nullptr, scriptContext) :
  1047. pNew;
  1048. }
  1049. JavascriptArray* JavascriptArray::CreateArrayFromConstructor(RecyclableObject* constructor, uint32 length, ScriptContext* scriptContext)
  1050. {
  1051. JavascriptLibrary* library = constructor->GetLibrary();
  1052. // Create the Array object we'll return - this is the only way to create an object which is an exotic Array object.
  1053. // Note: We need to use the library from the ScriptContext of the constructor, not the currently executing function.
  1054. // This is for the case where a built-in @@create method from a different JavascriptLibrary is installed on
  1055. // constructor.
  1056. return library->CreateArray(length);
  1057. }
  1058. JavascriptArray* JavascriptArray::CreateArrayFromConstructorNoArg(RecyclableObject* constructor, ScriptContext* scriptContext)
  1059. {
  1060. JavascriptLibrary* library = constructor->GetLibrary();
  1061. return library->CreateArray();
  1062. }
  1063. #if ENABLE_PROFILE_INFO
  1064. Var JavascriptArray::ProfiledNewInstanceNoArg(RecyclableObject *function, ScriptContext *scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
  1065. {
  1066. Assert(JavascriptFunction::Is(function) &&
  1067. JavascriptFunction::FromVar(function)->GetFunctionInfo() == &JavascriptArray::EntryInfo::NewInstance);
  1068. if (arrayInfo->IsNativeIntArray())
  1069. {
  1070. JavascriptNativeIntArray *arr = scriptContext->GetLibrary()->CreateNativeIntArray();
  1071. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  1072. return arr;
  1073. }
  1074. if (arrayInfo->IsNativeFloatArray())
  1075. {
  1076. JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArray();
  1077. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  1078. return arr;
  1079. }
  1080. return scriptContext->GetLibrary()->CreateArray();
  1081. }
  1082. #endif
  1083. Var JavascriptNativeIntArray::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
  1084. {
  1085. ARGUMENTS(args, callInfo);
  1086. return NewInstance(function, args);
  1087. }
  1088. Var JavascriptNativeIntArray::NewInstance(RecyclableObject* function, Arguments args)
  1089. {
  1090. Assert(!PHASE_OFF1(NativeArrayPhase));
  1091. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1092. const CallInfo &callInfo = args.Info;
  1093. if (callInfo.Count < 2)
  1094. {
  1095. // No arguments passed to Array(), so create with the default size (0).
  1096. return function->GetLibrary()->CreateNativeIntArray();
  1097. }
  1098. JavascriptArray* pNew = nullptr;
  1099. if (callInfo.Count == 2)
  1100. {
  1101. // Exactly one argument, which is the array length if it's a uint32.
  1102. Var firstArgument = args[1];
  1103. int elementCount;
  1104. if (TaggedInt::Is(firstArgument))
  1105. {
  1106. elementCount = TaggedInt::ToInt32(firstArgument);
  1107. if (elementCount < 0)
  1108. {
  1109. JavascriptError::ThrowRangeError(
  1110. function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  1111. }
  1112. pNew = function->GetLibrary()->CreateNativeIntArray(elementCount);
  1113. }
  1114. else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
  1115. {
  1116. // Non-tagged-int number: make sure the double value is really a uint32.
  1117. double value = JavascriptNumber::GetValue(firstArgument);
  1118. uint32 uvalue = JavascriptConversion::ToUInt32(value);
  1119. if (value != uvalue)
  1120. {
  1121. JavascriptError::ThrowRangeError(
  1122. function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  1123. }
  1124. pNew = function->GetLibrary()->CreateNativeIntArray(uvalue);
  1125. }
  1126. else
  1127. {
  1128. //
  1129. // First element is not int/double
  1130. // create an array of length 1.
  1131. // Set first element as the passed Var
  1132. //
  1133. pNew = function->GetLibrary()->CreateArray(1);
  1134. pNew->DirectSetItemAt<Var>(0, firstArgument);
  1135. }
  1136. }
  1137. else
  1138. {
  1139. // Called with a list of initial element values.
  1140. // Create an array of the appropriate length and walk the list.
  1141. JavascriptNativeIntArray *arr = function->GetLibrary()->CreateNativeIntArray(callInfo.Count - 1);
  1142. pNew = arr->FillFromArgs(callInfo.Count - 1, 0, args.Values);
  1143. }
  1144. #ifdef VALIDATE_ARRAY
  1145. pNew->ValidateArray();
  1146. #endif
  1147. return pNew;
  1148. }
  1149. Var JavascriptNativeFloatArray::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
  1150. {
  1151. ARGUMENTS(args, callInfo);
  1152. return NewInstance(function, args);
  1153. }
  1154. Var JavascriptNativeFloatArray::NewInstance(RecyclableObject* function, Arguments args)
  1155. {
  1156. Assert(!PHASE_OFF1(NativeArrayPhase));
  1157. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1158. const CallInfo &callInfo = args.Info;
  1159. if (callInfo.Count < 2)
  1160. {
  1161. // No arguments passed to Array(), so create with the default size (0).
  1162. return function->GetLibrary()->CreateNativeFloatArray();
  1163. }
  1164. JavascriptArray* pNew = nullptr;
  1165. if (callInfo.Count == 2)
  1166. {
  1167. // Exactly one argument, which is the array length if it's a uint32.
  1168. Var firstArgument = args[1];
  1169. int elementCount;
  1170. if (TaggedInt::Is(firstArgument))
  1171. {
  1172. elementCount = TaggedInt::ToInt32(firstArgument);
  1173. if (elementCount < 0)
  1174. {
  1175. JavascriptError::ThrowRangeError(
  1176. function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  1177. }
  1178. pNew = function->GetLibrary()->CreateNativeFloatArray(elementCount);
  1179. }
  1180. else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
  1181. {
  1182. // Non-tagged-int number: make sure the double value is really a uint32.
  1183. double value = JavascriptNumber::GetValue(firstArgument);
  1184. uint32 uvalue = JavascriptConversion::ToUInt32(value);
  1185. if (value != uvalue)
  1186. {
  1187. JavascriptError::ThrowRangeError(
  1188. function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  1189. }
  1190. pNew = function->GetLibrary()->CreateNativeFloatArray(uvalue);
  1191. }
  1192. else
  1193. {
  1194. //
  1195. // First element is not int/double
  1196. // create an array of length 1.
  1197. // Set first element as the passed Var
  1198. //
  1199. pNew = function->GetLibrary()->CreateArray(1);
  1200. pNew->DirectSetItemAt<Var>(0, firstArgument);
  1201. }
  1202. }
  1203. else
  1204. {
  1205. // Called with a list of initial element values.
  1206. // Create an array of the appropriate length and walk the list.
  1207. JavascriptNativeFloatArray *arr = function->GetLibrary()->CreateNativeFloatArray(callInfo.Count - 1);
  1208. pNew = arr->FillFromArgs(callInfo.Count - 1, 0, args.Values);
  1209. }
  1210. #ifdef VALIDATE_ARRAY
  1211. pNew->ValidateArray();
  1212. #endif
  1213. return pNew;
  1214. }
  1215. #if ENABLE_PROFILE_INFO
  1216. JavascriptArray * JavascriptNativeIntArray::FillFromArgs(uint length, uint start, Var *args, ArrayCallSiteInfo *arrayInfo, bool dontCreateNewArray)
  1217. #else
  1218. JavascriptArray * JavascriptNativeIntArray::FillFromArgs(uint length, uint start, Var *args, bool dontCreateNewArray)
  1219. #endif
  1220. {
  1221. uint i;
  1222. for (i = start; i < length; i++)
  1223. {
  1224. Var item = args[i + 1];
  1225. bool isTaggedInt = TaggedInt::Is(item);
  1226. bool isTaggedIntMissingValue = false;
  1227. #ifdef TARGET_64
  1228. if (isTaggedInt)
  1229. {
  1230. int32 iValue = TaggedInt::ToInt32(item);
  1231. isTaggedIntMissingValue = Js::SparseArraySegment<int32>::IsMissingItem(&iValue);
  1232. }
  1233. #endif
  1234. if (isTaggedInt && !isTaggedIntMissingValue)
  1235. {
  1236. // This is taggedInt case and we verified that item is not missing value in AMD64.
  1237. this->DirectSetItemAt(i, TaggedInt::ToInt32(item));
  1238. }
  1239. else if (!isTaggedIntMissingValue && JavascriptNumber::Is_NoTaggedIntCheck(item))
  1240. {
  1241. double dvalue = JavascriptNumber::GetValue(item);
  1242. int32 ivalue;
  1243. if (JavascriptNumber::TryGetInt32Value(dvalue, &ivalue) && !Js::SparseArraySegment<int32>::IsMissingItem(&ivalue))
  1244. {
  1245. this->DirectSetItemAt(i, ivalue);
  1246. }
  1247. else
  1248. {
  1249. #if ENABLE_PROFILE_INFO
  1250. if (arrayInfo)
  1251. {
  1252. arrayInfo->SetIsNotNativeIntArray();
  1253. }
  1254. #endif
  1255. if (HasInlineHeadSegment(length) && i < this->head->length && !dontCreateNewArray)
  1256. {
  1257. // Avoid shrinking the number of elements in the head segment. We can still create a new
  1258. // array here, so go ahead.
  1259. JavascriptNativeFloatArray *fArr =
  1260. this->GetScriptContext()->GetLibrary()->CreateNativeFloatArrayLiteral(length);
  1261. return fArr->JavascriptNativeFloatArray::FillFromArgs(length, 0, args);
  1262. }
  1263. JavascriptNativeFloatArray *fArr = JavascriptNativeIntArray::ToNativeFloatArray(this);
  1264. fArr->DirectSetItemAt(i, dvalue);
  1265. #if ENABLE_PROFILE_INFO
  1266. return fArr->JavascriptNativeFloatArray::FillFromArgs(length, i + 1, args, arrayInfo, dontCreateNewArray);
  1267. #else
  1268. return fArr->JavascriptNativeFloatArray::FillFromArgs(length, i + 1, args, dontCreateNewArray);
  1269. #endif
  1270. }
  1271. }
  1272. else
  1273. {
  1274. #if ENABLE_PROFILE_INFO
  1275. if (arrayInfo)
  1276. {
  1277. arrayInfo->SetIsNotNativeArray();
  1278. }
  1279. #endif
  1280. #pragma prefast(suppress:6237, "The right hand side condition does not have any side effects.")
  1281. if (sizeof(int32) < sizeof(Var) && HasInlineHeadSegment(length) && i < this->head->length && !dontCreateNewArray)
  1282. {
  1283. // Avoid shrinking the number of elements in the head segment. We can still create a new
  1284. // array here, so go ahead.
  1285. JavascriptArray *arr = this->GetScriptContext()->GetLibrary()->CreateArrayLiteral(length);
  1286. return arr->JavascriptArray::FillFromArgs(length, 0, args);
  1287. }
  1288. JavascriptArray *arr = JavascriptNativeIntArray::ToVarArray(this);
  1289. #if ENABLE_PROFILE_INFO
  1290. return arr->JavascriptArray::FillFromArgs(length, i, args, nullptr, dontCreateNewArray);
  1291. #else
  1292. return arr->JavascriptArray::FillFromArgs(length, i, args, dontCreateNewArray);
  1293. #endif
  1294. }
  1295. }
  1296. return this;
  1297. }
  1298. #if ENABLE_PROFILE_INFO
  1299. JavascriptArray * JavascriptNativeFloatArray::FillFromArgs(uint length, uint start, Var *args, ArrayCallSiteInfo *arrayInfo, bool dontCreateNewArray)
  1300. #else
  1301. JavascriptArray * JavascriptNativeFloatArray::FillFromArgs(uint length, uint start, Var *args, bool dontCreateNewArray)
  1302. #endif
  1303. {
  1304. uint i;
  1305. for (i = start; i < length; i++)
  1306. {
  1307. Var item = args[i + 1];
  1308. if (TaggedInt::Is(item))
  1309. {
  1310. this->DirectSetItemAt(i, TaggedInt::ToDouble(item));
  1311. }
  1312. else if (JavascriptNumber::Is_NoTaggedIntCheck(item))
  1313. {
  1314. this->DirectSetItemAt(i, JavascriptNumber::GetValue(item));
  1315. }
  1316. else
  1317. {
  1318. JavascriptArray *arr = JavascriptNativeFloatArray::ToVarArray(this);
  1319. #if ENABLE_PROFILE_INFO
  1320. if (arrayInfo)
  1321. {
  1322. arrayInfo->SetIsNotNativeArray();
  1323. }
  1324. return arr->JavascriptArray::FillFromArgs(length, i, args, nullptr, dontCreateNewArray);
  1325. #else
  1326. return arr->JavascriptArray::FillFromArgs(length, i, args, dontCreateNewArray);
  1327. #endif
  1328. }
  1329. }
  1330. return this;
  1331. }
  1332. #if ENABLE_PROFILE_INFO
  1333. JavascriptArray * JavascriptArray::FillFromArgs(uint length, uint start, Var *args, ArrayCallSiteInfo *arrayInfo, bool dontCreateNewArray)
  1334. #else
  1335. JavascriptArray * JavascriptArray::FillFromArgs(uint length, uint start, Var *args, bool dontCreateNewArray)
  1336. #endif
  1337. {
  1338. uint32 i;
  1339. for (i = start; i < length; i++)
  1340. {
  1341. Var item = args[i + 1];
  1342. this->DirectSetItemAt(i, item);
  1343. }
  1344. return this;
  1345. }
  1346. DynamicType * JavascriptNativeIntArray::GetInitialType(ScriptContext * scriptContext)
  1347. {
  1348. return scriptContext->GetLibrary()->GetNativeIntArrayType();
  1349. }
  1350. #if ENABLE_COPYONACCESS_ARRAY
  1351. DynamicType * JavascriptCopyOnAccessNativeIntArray::GetInitialType(ScriptContext * scriptContext)
  1352. {
  1353. return scriptContext->GetLibrary()->GetCopyOnAccessNativeIntArrayType();
  1354. }
  1355. #endif
  1356. JavascriptNativeFloatArray *JavascriptNativeIntArray::ToNativeFloatArray(JavascriptNativeIntArray *intArray)
  1357. {
  1358. #if ENABLE_PROFILE_INFO
  1359. ArrayCallSiteInfo *arrayInfo = intArray->GetArrayCallSiteInfo();
  1360. if (arrayInfo)
  1361. {
  1362. #if DBG
  1363. Js::JavascriptStackWalker walker(intArray->GetScriptContext());
  1364. Js::JavascriptFunction* caller = nullptr;
  1365. bool foundScriptCaller = false;
  1366. while(walker.GetCaller(&caller))
  1367. {
  1368. if(caller != nullptr && Js::ScriptFunction::Test(caller))
  1369. {
  1370. foundScriptCaller = true;
  1371. break;
  1372. }
  1373. }
  1374. if(foundScriptCaller)
  1375. {
  1376. Assert(caller);
  1377. Assert(caller->GetFunctionBody());
  1378. if(PHASE_TRACE(Js::NativeArrayConversionPhase, caller->GetFunctionBody()))
  1379. {
  1380. Output::Print(_u("Conversion: Int array to Float array ArrayCreationFunctionNumber:%2d CallSiteNumber:%2d \n"), arrayInfo->functionNumber, arrayInfo->callSiteNumber);
  1381. Output::Flush();
  1382. }
  1383. }
  1384. else
  1385. {
  1386. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1387. {
  1388. Output::Print(_u("Conversion: Int array to Float array across ScriptContexts"));
  1389. Output::Flush();
  1390. }
  1391. }
  1392. #else
  1393. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1394. {
  1395. Output::Print(_u("Conversion: Int array to Float array"));
  1396. Output::Flush();
  1397. }
  1398. #endif
  1399. arrayInfo->SetIsNotNativeIntArray();
  1400. }
  1401. #endif
  1402. ScriptContext *scriptContext = intArray->GetScriptContext();
  1403. // Code below has potential to throw due to OOM or SO. Just FailFast on those cases
  1404. AutoDisableInterrupt failFastError(scriptContext->GetThreadContext());
  1405. // Grow the segments
  1406. Recycler *recycler = scriptContext->GetRecycler();
  1407. SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
  1408. for (seg = intArray->head; seg; seg = nextSeg)
  1409. {
  1410. nextSeg = seg->next;
  1411. uint32 size = seg->size;
  1412. if (size == 0)
  1413. {
  1414. continue;
  1415. }
  1416. uint32 left = seg->left;
  1417. uint32 length = seg->length;
  1418. int i;
  1419. int32 ival;
  1420. // The old segment will have size/2 and length capped by the new size.
  1421. uint32 newSegSize = seg->size >> 1;
  1422. if (seg == intArray->head || seg->length > (newSegSize >> 1))
  1423. {
  1424. // Some live elements are being pushed out of this segment, so allocate a new one.
  1425. SparseArraySegment<double> *newSeg =
  1426. SparseArraySegment<double>::AllocateSegment(recycler, left, length, nextSeg);
  1427. Assert(newSeg != nullptr);
  1428. Assert((prevSeg == nullptr) == (seg == intArray->head));
  1429. newSeg->next = nextSeg;
  1430. intArray->LinkSegments((SparseArraySegment<double>*)prevSeg, newSeg);
  1431. if (intArray->GetLastUsedSegment() == seg)
  1432. {
  1433. intArray->SetLastUsedSegment(newSeg);
  1434. }
  1435. prevSeg = newSeg;
  1436. SegmentBTree * segmentMap = intArray->GetSegmentMap();
  1437. if (segmentMap)
  1438. {
  1439. segmentMap->SwapSegment(left, seg, newSeg);
  1440. }
  1441. // Fill the new segment with the overflow.
  1442. for (i = 0; (uint)i < newSeg->length; i++)
  1443. {
  1444. ival = ((SparseArraySegment<int32>*)seg)->elements[i /*+ seg->length*/];
  1445. if (ival == JavascriptNativeIntArray::MissingItem)
  1446. {
  1447. continue;
  1448. }
  1449. newSeg->elements[i] = (double)ival;
  1450. }
  1451. }
  1452. else
  1453. {
  1454. seg->size = newSegSize >> 1;
  1455. seg->CheckLengthvsSize();
  1456. // Now convert the contents that will remain in the old segment.
  1457. for (i = seg->length - 1; i >= 0; i--)
  1458. {
  1459. ival = ((SparseArraySegment<int32>*)seg)->elements[i];
  1460. if (ival == JavascriptNativeIntArray::MissingItem)
  1461. {
  1462. ((SparseArraySegment<double>*)seg)->elements[i] = (double)JavascriptNativeFloatArray::MissingItem;
  1463. }
  1464. else
  1465. {
  1466. ((SparseArraySegment<double>*)seg)->elements[i] = (double)ival;
  1467. }
  1468. }
  1469. prevSeg = seg;
  1470. }
  1471. }
  1472. if (intArray->GetType() == scriptContext->GetLibrary()->GetNativeIntArrayType())
  1473. {
  1474. intArray->type = scriptContext->GetLibrary()->GetNativeFloatArrayType();
  1475. }
  1476. else
  1477. {
  1478. if (intArray->GetDynamicType()->GetIsLocked())
  1479. {
  1480. DynamicTypeHandler *typeHandler = intArray->GetDynamicType()->GetTypeHandler();
  1481. if (typeHandler->IsPathTypeHandler())
  1482. {
  1483. // We can't allow a type with the new type ID to be promoted to the old type.
  1484. // So go to a dictionary type handler, which will orphan the new type.
  1485. // This should be a corner case, so the inability to share the new type is unlikely to matter.
  1486. // If it does matter, try building a path from the new type's built-in root.
  1487. static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(intArray);
  1488. }
  1489. else
  1490. {
  1491. intArray->ChangeType();
  1492. }
  1493. }
  1494. intArray->GetType()->SetTypeId(TypeIds_NativeFloatArray);
  1495. }
  1496. if (CrossSite::IsCrossSiteObjectTyped(intArray))
  1497. {
  1498. Assert(VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::HasVirtualTable(intArray));
  1499. VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::SetVirtualTable(intArray);
  1500. }
  1501. else
  1502. {
  1503. Assert(VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(intArray));
  1504. VirtualTableInfo<JavascriptNativeFloatArray>::SetVirtualTable(intArray);
  1505. }
  1506. failFastError.Completed();
  1507. return (JavascriptNativeFloatArray*)intArray;
  1508. }
  1509. /*
  1510. * JavascriptArray::ChangeArrayTypeToNativeArray<double>
  1511. * - Converts the Var Array's type to NativeFloat.
  1512. * - Sets the VirtualTable to "JavascriptNativeFloatArray"
  1513. */
  1514. template<>
  1515. void JavascriptArray::ChangeArrayTypeToNativeArray<double>(JavascriptArray * varArray, ScriptContext * scriptContext)
  1516. {
  1517. AssertMsg(!JavascriptNativeArray::Is(varArray), "Ensure that the incoming Array is a Var array");
  1518. if (varArray->GetType() == scriptContext->GetLibrary()->GetArrayType())
  1519. {
  1520. varArray->type = scriptContext->GetLibrary()->GetNativeFloatArrayType();
  1521. }
  1522. else
  1523. {
  1524. if (varArray->GetDynamicType()->GetIsLocked())
  1525. {
  1526. DynamicTypeHandler *typeHandler = varArray->GetDynamicType()->GetTypeHandler();
  1527. if (typeHandler->IsPathTypeHandler())
  1528. {
  1529. // We can't allow a type with the new type ID to be promoted to the old type.
  1530. // So go to a dictionary type handler, which will orphan the new type.
  1531. // This should be a corner case, so the inability to share the new type is unlikely to matter.
  1532. // If it does matter, try building a path from the new type's built-in root.
  1533. static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(varArray);
  1534. }
  1535. else
  1536. {
  1537. varArray->ChangeType();
  1538. }
  1539. }
  1540. varArray->GetType()->SetTypeId(TypeIds_NativeFloatArray);
  1541. }
  1542. if (CrossSite::IsCrossSiteObjectTyped(varArray))
  1543. {
  1544. Assert(VirtualTableInfo<CrossSiteObject<JavascriptArray>>::HasVirtualTable(varArray));
  1545. VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::SetVirtualTable(varArray);
  1546. }
  1547. else
  1548. {
  1549. Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(varArray));
  1550. VirtualTableInfo<JavascriptNativeFloatArray>::SetVirtualTable(varArray);
  1551. }
  1552. }
  1553. /*
  1554. * JavascriptArray::ChangeArrayTypeToNativeArray<int32>
  1555. * - Converts the Var Array's type to NativeInt.
  1556. * - Sets the VirtualTable to "JavascriptNativeIntArray"
  1557. */
  1558. template<>
  1559. void JavascriptArray::ChangeArrayTypeToNativeArray<int32>(JavascriptArray * varArray, ScriptContext * scriptContext)
  1560. {
  1561. AssertMsg(!JavascriptNativeArray::Is(varArray), "Ensure that the incoming Array is a Var array");
  1562. if (varArray->GetType() == scriptContext->GetLibrary()->GetArrayType())
  1563. {
  1564. varArray->type = scriptContext->GetLibrary()->GetNativeIntArrayType();
  1565. }
  1566. else
  1567. {
  1568. if (varArray->GetDynamicType()->GetIsLocked())
  1569. {
  1570. DynamicTypeHandler *typeHandler = varArray->GetDynamicType()->GetTypeHandler();
  1571. if (typeHandler->IsPathTypeHandler())
  1572. {
  1573. // We can't allow a type with the new type ID to be promoted to the old type.
  1574. // So go to a dictionary type handler, which will orphan the new type.
  1575. // This should be a corner case, so the inability to share the new type is unlikely to matter.
  1576. // If it does matter, try building a path from the new type's built-in root.
  1577. static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(varArray);
  1578. }
  1579. else
  1580. {
  1581. varArray->ChangeType();
  1582. }
  1583. }
  1584. varArray->GetType()->SetTypeId(TypeIds_NativeIntArray);
  1585. }
  1586. if (CrossSite::IsCrossSiteObjectTyped(varArray))
  1587. {
  1588. Assert(VirtualTableInfo<CrossSiteObject<JavascriptArray>>::HasVirtualTable(varArray));
  1589. VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::SetVirtualTable(varArray);
  1590. }
  1591. else
  1592. {
  1593. Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(varArray));
  1594. VirtualTableInfo<JavascriptNativeIntArray>::SetVirtualTable(varArray);
  1595. }
  1596. }
  1597. template<>
  1598. int32 JavascriptArray::GetNativeValue<int32>(Js::Var ival, ScriptContext * scriptContext)
  1599. {
  1600. return JavascriptConversion::ToInt32(ival, scriptContext);
  1601. }
  1602. template <>
  1603. double JavascriptArray::GetNativeValue<double>(Var ival, ScriptContext * scriptContext)
  1604. {
  1605. return JavascriptConversion::ToNumber(ival, scriptContext);
  1606. }
  1607. /*
  1608. * JavascriptArray::ConvertToNativeArrayInPlace
  1609. * In place conversion of all Var elements to Native Int/Double elements in an array.
  1610. * We do not update the DynamicProfileInfo of the array here.
  1611. */
  1612. template<typename NativeArrayType, typename T>
  1613. NativeArrayType *JavascriptArray::ConvertToNativeArrayInPlace(JavascriptArray *varArray)
  1614. {
  1615. AssertMsg(!JavascriptNativeArray::Is(varArray), "Ensure that the incoming Array is a Var array");
  1616. ScriptContext *scriptContext = varArray->GetScriptContext();
  1617. SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
  1618. for (seg = varArray->head; seg; seg = nextSeg)
  1619. {
  1620. nextSeg = seg->next;
  1621. uint32 size = seg->size;
  1622. if (size == 0)
  1623. {
  1624. continue;
  1625. }
  1626. int i;
  1627. Var ival;
  1628. uint32 growFactor = sizeof(Var) / sizeof(T);
  1629. AssertMsg(growFactor == 1, "We support only in place conversion of Var array to Native Array");
  1630. // Now convert the contents that will remain in the old segment.
  1631. for (i = seg->length - 1; i >= 0; i--)
  1632. {
  1633. ival = ((SparseArraySegment<Var>*)seg)->elements[i];
  1634. if (ival == JavascriptArray::MissingItem)
  1635. {
  1636. ((SparseArraySegment<T>*)seg)->elements[i] = NativeArrayType::MissingItem;
  1637. }
  1638. else
  1639. {
  1640. ((SparseArraySegment<T>*)seg)->elements[i] = GetNativeValue<T>(ival, scriptContext);
  1641. }
  1642. }
  1643. prevSeg = seg;
  1644. }
  1645. // Update the type of the Array
  1646. ChangeArrayTypeToNativeArray<T>(varArray, scriptContext);
  1647. return (NativeArrayType*)varArray;
  1648. }
  1649. JavascriptArray *JavascriptNativeIntArray::ConvertToVarArray(JavascriptNativeIntArray *intArray)
  1650. {
  1651. #if ENABLE_COPYONACCESS_ARRAY
  1652. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(intArray);
  1653. #endif
  1654. ScriptContext *scriptContext = intArray->GetScriptContext();
  1655. Recycler *recycler = scriptContext->GetRecycler();
  1656. SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
  1657. // Code below has potential to throw due to OOM or SO. Just FailFast on those cases
  1658. AutoDisableInterrupt failFastError(scriptContext->GetThreadContext());
  1659. for (seg = intArray->head; seg; seg = nextSeg)
  1660. {
  1661. nextSeg = seg->next;
  1662. uint32 size = seg->size;
  1663. if (size == 0)
  1664. {
  1665. continue;
  1666. }
  1667. uint32 left = seg->left;
  1668. uint32 length = seg->length;
  1669. int i;
  1670. int32 ival;
  1671. // Shrink?
  1672. uint32 growFactor = sizeof(Var) / sizeof(int32);
  1673. if ((growFactor != 1 && (seg == intArray->head || seg->length > (seg->size / growFactor))) ||
  1674. (seg->next == nullptr && SparseArraySegmentBase::IsLeafSegment(seg, recycler)))
  1675. {
  1676. // Some live elements are being pushed out of this segment, so allocate a new one.
  1677. // And/or the old segment is not scanned by the recycler, so we need a new one to hold vars.
  1678. SparseArraySegment<Var> *newSeg =
  1679. SparseArraySegment<Var>::AllocateSegment(recycler, left, length, nextSeg);
  1680. AnalysisAssert(newSeg);
  1681. Assert((prevSeg == nullptr) == (seg == intArray->head));
  1682. newSeg->next = nextSeg;
  1683. intArray->LinkSegments((SparseArraySegment<Var>*)prevSeg, newSeg);
  1684. if (intArray->GetLastUsedSegment() == seg)
  1685. {
  1686. intArray->SetLastUsedSegment(newSeg);
  1687. }
  1688. prevSeg = newSeg;
  1689. SegmentBTree * segmentMap = intArray->GetSegmentMap();
  1690. if (segmentMap)
  1691. {
  1692. segmentMap->SwapSegment(left, seg, newSeg);
  1693. }
  1694. // Fill the new segment with the overflow.
  1695. for (i = 0; (uint)i < newSeg->length; i++)
  1696. {
  1697. ival = ((SparseArraySegment<int32>*)seg)->elements[i];
  1698. if (ival == JavascriptNativeIntArray::MissingItem)
  1699. {
  1700. continue;
  1701. }
  1702. newSeg->elements[i] = JavascriptNumber::ToVar(ival, scriptContext);
  1703. }
  1704. }
  1705. else
  1706. {
  1707. seg->size = seg->size / growFactor;
  1708. seg->CheckLengthvsSize();
  1709. // Now convert the contents that will remain in the old segment.
  1710. // Walk backward in case we're growing the element size.
  1711. for (i = seg->length - 1; i >= 0; i--)
  1712. {
  1713. ival = ((SparseArraySegment<int32>*)seg)->elements[i];
  1714. if (ival == JavascriptNativeIntArray::MissingItem)
  1715. {
  1716. ((SparseArraySegment<Var>*)seg)->elements[i] = (Var)JavascriptArray::MissingItem;
  1717. }
  1718. else
  1719. {
  1720. ((SparseArraySegment<Var>*)seg)->elements[i] = JavascriptNumber::ToVar(ival, scriptContext);
  1721. }
  1722. }
  1723. prevSeg = seg;
  1724. }
  1725. }
  1726. if (intArray->GetType() == scriptContext->GetLibrary()->GetNativeIntArrayType())
  1727. {
  1728. intArray->type = scriptContext->GetLibrary()->GetArrayType();
  1729. }
  1730. else
  1731. {
  1732. if (intArray->GetDynamicType()->GetIsLocked())
  1733. {
  1734. DynamicTypeHandler *typeHandler = intArray->GetDynamicType()->GetTypeHandler();
  1735. if (typeHandler->IsPathTypeHandler())
  1736. {
  1737. // We can't allow a type with the new type ID to be promoted to the old type.
  1738. // So go to a dictionary type handler, which will orphan the new type.
  1739. // This should be a corner case, so the inability to share the new type is unlikely to matter.
  1740. // If it does matter, try building a path from the new type's built-in root.
  1741. static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(intArray);
  1742. }
  1743. else
  1744. {
  1745. intArray->ChangeType();
  1746. }
  1747. }
  1748. intArray->GetType()->SetTypeId(TypeIds_Array);
  1749. }
  1750. if (CrossSite::IsCrossSiteObjectTyped(intArray))
  1751. {
  1752. Assert(VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::HasVirtualTable(intArray));
  1753. VirtualTableInfo<CrossSiteObject<JavascriptArray>>::SetVirtualTable(intArray);
  1754. }
  1755. else
  1756. {
  1757. Assert(VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(intArray));
  1758. VirtualTableInfo<JavascriptArray>::SetVirtualTable(intArray);
  1759. }
  1760. failFastError.Completed();
  1761. return intArray;
  1762. }
  1763. JavascriptArray *JavascriptNativeIntArray::ToVarArray(JavascriptNativeIntArray *intArray)
  1764. {
  1765. #if ENABLE_PROFILE_INFO
  1766. ArrayCallSiteInfo *arrayInfo = intArray->GetArrayCallSiteInfo();
  1767. if (arrayInfo)
  1768. {
  1769. #if DBG
  1770. Js::JavascriptStackWalker walker(intArray->GetScriptContext());
  1771. Js::JavascriptFunction* caller = nullptr;
  1772. bool foundScriptCaller = false;
  1773. while(walker.GetCaller(&caller))
  1774. {
  1775. if(caller != nullptr && Js::ScriptFunction::Test(caller))
  1776. {
  1777. foundScriptCaller = true;
  1778. break;
  1779. }
  1780. }
  1781. if(foundScriptCaller)
  1782. {
  1783. Assert(caller);
  1784. Assert(caller->GetFunctionBody());
  1785. if(PHASE_TRACE(Js::NativeArrayConversionPhase, caller->GetFunctionBody()))
  1786. {
  1787. Output::Print(_u("Conversion: Int array to Var array ArrayCreationFunctionNumber:%2d CallSiteNumber:%2d \n"), arrayInfo->functionNumber, arrayInfo->callSiteNumber);
  1788. Output::Flush();
  1789. }
  1790. }
  1791. else
  1792. {
  1793. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1794. {
  1795. Output::Print(_u("Conversion: Int array to Var array across ScriptContexts"));
  1796. Output::Flush();
  1797. }
  1798. }
  1799. #else
  1800. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1801. {
  1802. Output::Print(_u("Conversion: Int array to Var array"));
  1803. Output::Flush();
  1804. }
  1805. #endif
  1806. arrayInfo->SetIsNotNativeArray();
  1807. }
  1808. #endif
  1809. intArray->ClearArrayCallSiteIndex();
  1810. return ConvertToVarArray(intArray);
  1811. }
  1812. DynamicType * JavascriptNativeFloatArray::GetInitialType(ScriptContext * scriptContext)
  1813. {
  1814. return scriptContext->GetLibrary()->GetNativeFloatArrayType();
  1815. }
  1816. /*
  1817. * JavascriptNativeFloatArray::ConvertToVarArray
  1818. * This function only converts all Float elements to Var elements in an array.
  1819. * DynamicProfileInfo of the array is not updated in this function.
  1820. */
  1821. JavascriptArray *JavascriptNativeFloatArray::ConvertToVarArray(JavascriptNativeFloatArray *fArray)
  1822. {
  1823. // We can't be growing the size of the element.
  1824. Assert(sizeof(double) >= sizeof(Var));
  1825. uint32 shrinkFactor = sizeof(double) / sizeof(Var);
  1826. ScriptContext *scriptContext = fArray->GetScriptContext();
  1827. Recycler *recycler = scriptContext->GetRecycler();
  1828. SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
  1829. // Code below has potential to throw due to OOM or SO. Just FailFast on those cases
  1830. AutoDisableInterrupt failFastError(scriptContext->GetThreadContext());
  1831. for (seg = fArray->head; seg; seg = nextSeg)
  1832. {
  1833. nextSeg = seg->next;
  1834. if (seg->size == 0)
  1835. {
  1836. continue;
  1837. }
  1838. uint32 left = seg->left;
  1839. uint32 length = seg->length;
  1840. SparseArraySegment<Var> *newSeg;
  1841. if (seg->next == nullptr && SparseArraySegmentBase::IsLeafSegment(seg, recycler))
  1842. {
  1843. // The old segment is not scanned by the recycler, so we need a new one to hold vars.
  1844. newSeg =
  1845. SparseArraySegment<Var>::AllocateSegment(recycler, left, length, nextSeg);
  1846. Assert((prevSeg == nullptr) == (seg == fArray->head));
  1847. newSeg->next = nextSeg;
  1848. fArray->LinkSegments((SparseArraySegment<Var>*)prevSeg, newSeg);
  1849. if (fArray->GetLastUsedSegment() == seg)
  1850. {
  1851. fArray->SetLastUsedSegment(newSeg);
  1852. }
  1853. prevSeg = newSeg;
  1854. SegmentBTree * segmentMap = fArray->GetSegmentMap();
  1855. if (segmentMap)
  1856. {
  1857. segmentMap->SwapSegment(left, seg, newSeg);
  1858. }
  1859. }
  1860. else
  1861. {
  1862. newSeg = (SparseArraySegment<Var>*)seg;
  1863. prevSeg = seg;
  1864. if (shrinkFactor != 1)
  1865. {
  1866. uint32 newSize = seg->size * shrinkFactor;
  1867. uint32 limit;
  1868. if (seg->next)
  1869. {
  1870. limit = seg->next->left;
  1871. }
  1872. else
  1873. {
  1874. limit = JavascriptArray::MaxArrayLength;
  1875. }
  1876. seg->size = min(newSize, limit - seg->left);
  1877. seg->CheckLengthvsSize();
  1878. }
  1879. }
  1880. uint32 i;
  1881. for (i = 0; i < seg->length; i++)
  1882. {
  1883. if (SparseArraySegment<double>::IsMissingItem(&((SparseArraySegment<double>*)seg)->elements[i]))
  1884. {
  1885. if (seg == newSeg)
  1886. {
  1887. newSeg->elements[i] = (Var)JavascriptArray::MissingItem;
  1888. }
  1889. Assert(newSeg->elements[i] == (Var)JavascriptArray::MissingItem);
  1890. }
  1891. else if (*(uint64*)&(((SparseArraySegment<double>*)seg)->elements[i]) == 0ull)
  1892. {
  1893. newSeg->elements[i] = TaggedInt::ToVarUnchecked(0);
  1894. }
  1895. else
  1896. {
  1897. int32 ival;
  1898. double dval = ((SparseArraySegment<double>*)seg)->elements[i];
  1899. if (JavascriptNumber::TryGetInt32Value(dval, &ival) && !TaggedInt::IsOverflow(ival))
  1900. {
  1901. newSeg->elements[i] = TaggedInt::ToVarUnchecked(ival);
  1902. }
  1903. else
  1904. {
  1905. newSeg->elements[i] = JavascriptNumber::ToVarWithCheck(dval, scriptContext);
  1906. }
  1907. }
  1908. }
  1909. if (seg == newSeg && shrinkFactor != 1)
  1910. {
  1911. // Fill the remaining slots.
  1912. newSeg->FillSegmentBuffer(i, seg->size);
  1913. }
  1914. }
  1915. if (fArray->GetType() == scriptContext->GetLibrary()->GetNativeFloatArrayType())
  1916. {
  1917. fArray->type = scriptContext->GetLibrary()->GetArrayType();
  1918. }
  1919. else
  1920. {
  1921. if (fArray->GetDynamicType()->GetIsLocked())
  1922. {
  1923. DynamicTypeHandler *typeHandler = fArray->GetDynamicType()->GetTypeHandler();
  1924. if (typeHandler->IsPathTypeHandler())
  1925. {
  1926. // We can't allow a type with the new type ID to be promoted to the old type.
  1927. // So go to a dictionary type handler, which will orphan the new type.
  1928. // This should be a corner case, so the inability to share the new type is unlikely to matter.
  1929. // If it does matter, try building a path from the new type's built-in root.
  1930. static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(fArray);
  1931. }
  1932. else
  1933. {
  1934. fArray->ChangeType();
  1935. }
  1936. }
  1937. fArray->GetType()->SetTypeId(TypeIds_Array);
  1938. }
  1939. if (CrossSite::IsCrossSiteObjectTyped(fArray))
  1940. {
  1941. Assert(VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::HasVirtualTable(fArray));
  1942. VirtualTableInfo<CrossSiteObject<JavascriptArray>>::SetVirtualTable(fArray);
  1943. }
  1944. else
  1945. {
  1946. Assert(VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(fArray));
  1947. VirtualTableInfo<JavascriptArray>::SetVirtualTable(fArray);
  1948. }
  1949. failFastError.Completed();
  1950. return fArray;
  1951. }
  1952. JavascriptArray *JavascriptNativeFloatArray::ToVarArray(JavascriptNativeFloatArray *fArray)
  1953. {
  1954. #if ENABLE_PROFILE_INFO
  1955. ArrayCallSiteInfo *arrayInfo = fArray->GetArrayCallSiteInfo();
  1956. if (arrayInfo)
  1957. {
  1958. #if DBG
  1959. Js::JavascriptStackWalker walker(fArray->GetScriptContext());
  1960. Js::JavascriptFunction* caller = nullptr;
  1961. bool foundScriptCaller = false;
  1962. while(walker.GetCaller(&caller))
  1963. {
  1964. if(caller != nullptr && Js::ScriptFunction::Test(caller))
  1965. {
  1966. foundScriptCaller = true;
  1967. break;
  1968. }
  1969. }
  1970. if(foundScriptCaller)
  1971. {
  1972. Assert(caller);
  1973. Assert(caller->GetFunctionBody());
  1974. if(PHASE_TRACE(Js::NativeArrayConversionPhase, caller->GetFunctionBody()))
  1975. {
  1976. Output::Print(_u("Conversion: Float array to Var array ArrayCreationFunctionNumber:%2d CallSiteNumber:%2d \n"), arrayInfo->functionNumber, arrayInfo->callSiteNumber);
  1977. Output::Flush();
  1978. }
  1979. }
  1980. else
  1981. {
  1982. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1983. {
  1984. Output::Print(_u("Conversion: Float array to Var array across ScriptContexts"));
  1985. Output::Flush();
  1986. }
  1987. }
  1988. #else
  1989. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1990. {
  1991. Output::Print(_u("Conversion: Float array to Var array"));
  1992. Output::Flush();
  1993. }
  1994. #endif
  1995. if(fArray->GetScriptContext()->IsScriptContextInNonDebugMode())
  1996. {
  1997. Assert(!arrayInfo->IsNativeIntArray());
  1998. }
  1999. arrayInfo->SetIsNotNativeArray();
  2000. }
  2001. #endif
  2002. fArray->ClearArrayCallSiteIndex();
  2003. return ConvertToVarArray(fArray);
  2004. }
  2005. // Convert Var to index in the Array.
  2006. // Note: Spec calls out a few rules for these parameters:
  2007. // 1. if (arg > length) { return length; }
  2008. // clamp to length, not length-1
  2009. // 2. if (arg < 0) { return max(0, length + arg); }
  2010. // treat negative arg as index from the end of the array (with -1 mapping to length-1)
  2011. // Effectively, this function will return a value between 0 and length, inclusive.
  2012. int64 JavascriptArray::GetIndexFromVar(Js::Var arg, int64 length, ScriptContext* scriptContext)
  2013. {
  2014. int64 index;
  2015. if (TaggedInt::Is(arg))
  2016. {
  2017. int intValue = TaggedInt::ToInt32(arg);
  2018. if (intValue < 0)
  2019. {
  2020. index = max<int64>(0, length + intValue);
  2021. }
  2022. else
  2023. {
  2024. index = intValue;
  2025. }
  2026. if (index > length)
  2027. {
  2028. index = length;
  2029. }
  2030. }
  2031. else
  2032. {
  2033. double doubleValue = JavascriptConversion::ToInteger(arg, scriptContext);
  2034. // Handle the Number.POSITIVE_INFINITY case
  2035. if (doubleValue > length)
  2036. {
  2037. return length;
  2038. }
  2039. index = NumberUtilities::TryToInt64(doubleValue);
  2040. if (index < 0)
  2041. {
  2042. index = max<int64>(0, index + length);
  2043. }
  2044. }
  2045. return index;
  2046. }
  2047. TypeId JavascriptArray::OP_SetNativeIntElementC(JavascriptNativeIntArray *arr, uint32 index, Var value, ScriptContext *scriptContext)
  2048. {
  2049. int32 iValue;
  2050. double dValue;
  2051. TypeId typeId = arr->TrySetNativeIntArrayItem(value, &iValue, &dValue);
  2052. if (typeId == TypeIds_NativeIntArray)
  2053. {
  2054. arr->SetArrayLiteralItem(index, iValue);
  2055. }
  2056. else if (typeId == TypeIds_NativeFloatArray)
  2057. {
  2058. arr->SetArrayLiteralItem(index, dValue);
  2059. }
  2060. else
  2061. {
  2062. arr->SetArrayLiteralItem(index, value);
  2063. }
  2064. return typeId;
  2065. }
  2066. TypeId JavascriptArray::OP_SetNativeFloatElementC(JavascriptNativeFloatArray *arr, uint32 index, Var value, ScriptContext *scriptContext)
  2067. {
  2068. double dValue;
  2069. TypeId typeId = arr->TrySetNativeFloatArrayItem(value, &dValue);
  2070. if (typeId == TypeIds_NativeFloatArray)
  2071. {
  2072. arr->SetArrayLiteralItem(index, dValue);
  2073. }
  2074. else
  2075. {
  2076. arr->SetArrayLiteralItem(index, value);
  2077. }
  2078. return typeId;
  2079. }
  2080. template<typename T>
  2081. void JavascriptArray::SetArrayLiteralItem(uint32 index, T value)
  2082. {
  2083. SparseArraySegment<T> * segment = SparseArraySegment<T>::From(this->head);
  2084. Assert(segment->left == 0);
  2085. Assert(index < segment->length);
  2086. segment->elements[index] = value;
  2087. }
  2088. void JavascriptNativeIntArray::SetIsPrototype()
  2089. {
  2090. // Force the array to be non-native to simplify inspection, filling from proto, etc.
  2091. ToVarArray(this);
  2092. __super::SetIsPrototype();
  2093. }
  2094. void JavascriptNativeFloatArray::SetIsPrototype()
  2095. {
  2096. // Force the array to be non-native to simplify inspection, filling from proto, etc.
  2097. ToVarArray(this);
  2098. __super::SetIsPrototype();
  2099. }
  2100. #if ENABLE_PROFILE_INFO
  2101. ArrayCallSiteInfo *JavascriptNativeArray::GetArrayCallSiteInfo()
  2102. {
  2103. RecyclerWeakReference<FunctionBody> *weakRef = this->weakRefToFuncBody;
  2104. if (weakRef)
  2105. {
  2106. FunctionBody *functionBody = weakRef->Get();
  2107. if (functionBody)
  2108. {
  2109. if (functionBody->HasDynamicProfileInfo())
  2110. {
  2111. Js::ProfileId profileId = this->GetArrayCallSiteIndex();
  2112. if (profileId < functionBody->GetProfiledArrayCallSiteCount())
  2113. {
  2114. return functionBody->GetAnyDynamicProfileInfo()->GetArrayCallSiteInfo(functionBody, profileId);
  2115. }
  2116. }
  2117. }
  2118. else
  2119. {
  2120. this->ClearArrayCallSiteIndex();
  2121. }
  2122. }
  2123. return nullptr;
  2124. }
  2125. void JavascriptNativeArray::SetArrayProfileInfo(RecyclerWeakReference<FunctionBody> *weakRef, ArrayCallSiteInfo *arrayInfo)
  2126. {
  2127. Assert(weakRef);
  2128. FunctionBody *functionBody = weakRef->Get();
  2129. if (functionBody && functionBody->HasDynamicProfileInfo())
  2130. {
  2131. ArrayCallSiteInfo *baseInfo = functionBody->GetAnyDynamicProfileInfo()->GetArrayCallSiteInfo(functionBody, 0);
  2132. Js::ProfileId index = (Js::ProfileId)(arrayInfo - baseInfo);
  2133. Assert(index < functionBody->GetProfiledArrayCallSiteCount());
  2134. SetArrayCallSite(index, weakRef);
  2135. }
  2136. }
  2137. void JavascriptNativeArray::CopyArrayProfileInfo(Js::JavascriptNativeArray* baseArray)
  2138. {
  2139. if (baseArray->weakRefToFuncBody)
  2140. {
  2141. if (baseArray->weakRefToFuncBody->Get())
  2142. {
  2143. SetArrayCallSite(baseArray->GetArrayCallSiteIndex(), baseArray->weakRefToFuncBody);
  2144. }
  2145. else
  2146. {
  2147. baseArray->ClearArrayCallSiteIndex();
  2148. }
  2149. }
  2150. }
  2151. #endif
  2152. Var JavascriptNativeArray::FindMinOrMax(Js::ScriptContext * scriptContext, bool findMax)
  2153. {
  2154. if (JavascriptNativeIntArray::Is(this))
  2155. {
  2156. return this->FindMinOrMax<int32, false>(scriptContext, findMax);
  2157. }
  2158. else
  2159. {
  2160. return this->FindMinOrMax<double, true>(scriptContext, findMax);
  2161. }
  2162. }
  2163. template <typename T, bool checkNaNAndNegZero>
  2164. Var JavascriptNativeArray::FindMinOrMax(Js::ScriptContext * scriptContext, bool findMax)
  2165. {
  2166. AssertMsg(this->HasNoMissingValues(), "Fastpath is only for arrays with one segment and no missing values");
  2167. uint len = this->GetLength();
  2168. Js::SparseArraySegment<T>* headSegment = ((Js::SparseArraySegment<T>*)this->GetHead());
  2169. uint headSegLen = headSegment->length;
  2170. Assert(headSegLen == len);
  2171. if (headSegment->next == nullptr)
  2172. {
  2173. T currentRes = headSegment->elements[0];
  2174. for (uint i = 0; i < headSegLen; i++)
  2175. {
  2176. T compare = headSegment->elements[i];
  2177. if (checkNaNAndNegZero && JavascriptNumber::IsNan(double(compare)))
  2178. {
  2179. return scriptContext->GetLibrary()->GetNaN();
  2180. }
  2181. if (findMax ? currentRes < compare : currentRes > compare ||
  2182. (checkNaNAndNegZero && compare == 0 && Js::JavascriptNumber::IsNegZero(double(currentRes))))
  2183. {
  2184. currentRes = compare;
  2185. }
  2186. }
  2187. return Js::JavascriptNumber::ToVarNoCheck(currentRes, scriptContext);
  2188. }
  2189. else
  2190. {
  2191. AssertMsg(false, "FindMinOrMax currently supports native arrays with only one segment");
  2192. Throw::FatalInternalError();
  2193. }
  2194. }
  2195. SparseArraySegmentBase * JavascriptArray::GetLastUsedSegment() const
  2196. {
  2197. return HasSegmentMap() ?
  2198. PointerValue(segmentUnion.segmentBTreeRoot->lastUsedSegment) :
  2199. PointerValue(segmentUnion.lastUsedSegment);
  2200. }
  2201. void JavascriptArray::SetHeadAndLastUsedSegment(SparseArraySegmentBase * segment)
  2202. {
  2203. Assert(!HasSegmentMap());
  2204. this->head = this->segmentUnion.lastUsedSegment = segment;
  2205. }
  2206. void JavascriptArray::SetLastUsedSegment(SparseArraySegmentBase * segment)
  2207. {
  2208. if (HasSegmentMap())
  2209. {
  2210. this->segmentUnion.segmentBTreeRoot->lastUsedSegment = segment;
  2211. }
  2212. else
  2213. {
  2214. this->segmentUnion.lastUsedSegment = segment;
  2215. }
  2216. }
  2217. bool JavascriptArray::HasSegmentMap() const
  2218. {
  2219. return !!(GetFlags() & DynamicObjectFlags::HasSegmentMap);
  2220. }
  2221. SegmentBTreeRoot * JavascriptArray::GetSegmentMap() const
  2222. {
  2223. return (HasSegmentMap() ? segmentUnion.segmentBTreeRoot : nullptr);
  2224. }
  2225. void JavascriptArray::SetSegmentMap(SegmentBTreeRoot * segmentMap)
  2226. {
  2227. Assert(!HasSegmentMap());
  2228. SparseArraySegmentBase * lastUsedSeg = this->segmentUnion.lastUsedSegment;
  2229. SetFlags(GetFlags() | DynamicObjectFlags::HasSegmentMap);
  2230. segmentUnion.segmentBTreeRoot = segmentMap;
  2231. segmentMap->lastUsedSegment = lastUsedSeg;
  2232. }
  2233. void JavascriptArray::ClearSegmentMap()
  2234. {
  2235. if (HasSegmentMap())
  2236. {
  2237. SetFlags(GetFlags() & ~DynamicObjectFlags::HasSegmentMap);
  2238. SparseArraySegmentBase * lastUsedSeg = segmentUnion.segmentBTreeRoot->lastUsedSegment;
  2239. segmentUnion.segmentBTreeRoot = nullptr;
  2240. segmentUnion.lastUsedSegment = lastUsedSeg;
  2241. }
  2242. }
  2243. SegmentBTreeRoot * JavascriptArray::BuildSegmentMap()
  2244. {
  2245. Recycler* recycler = GetRecycler();
  2246. SegmentBTreeRoot* tmpSegmentMap = AllocatorNewStruct(Recycler, recycler, SegmentBTreeRoot);
  2247. ForEachSegment([recycler, tmpSegmentMap](SparseArraySegmentBase * current)
  2248. {
  2249. tmpSegmentMap->Add(recycler, current);
  2250. return false;
  2251. });
  2252. // There could be OOM during building segment map. Save to array only after its successful completion.
  2253. SetSegmentMap(tmpSegmentMap);
  2254. return tmpSegmentMap;
  2255. }
  2256. void JavascriptArray::TryAddToSegmentMap(Recycler* recycler, SparseArraySegmentBase* seg)
  2257. {
  2258. SegmentBTreeRoot * savedSegmentMap = GetSegmentMap();
  2259. if (savedSegmentMap)
  2260. {
  2261. //
  2262. // We could OOM and throw when adding to segmentMap, resulting in a corrupted segmentMap on this
  2263. // array. Set segmentMap to null temporarily to protect from this. It will be restored correctly
  2264. // if adding segment succeeds.
  2265. //
  2266. ClearSegmentMap();
  2267. savedSegmentMap->Add(recycler, seg);
  2268. SetSegmentMap(savedSegmentMap);
  2269. }
  2270. }
  2271. void JavascriptArray::InvalidateLastUsedSegment()
  2272. {
  2273. this->SetLastUsedSegment(this->head);
  2274. }
  2275. DescriptorFlags JavascriptArray::GetSetter(PropertyId propertyId, Var *setterValue, PropertyValueInfo* info, ScriptContext* requestContext)
  2276. {
  2277. DescriptorFlags flags;
  2278. if (GetSetterBuiltIns(propertyId, info, &flags))
  2279. {
  2280. return flags;
  2281. }
  2282. return __super::GetSetter(propertyId, setterValue, info, requestContext);
  2283. }
  2284. DescriptorFlags JavascriptArray::GetSetter(JavascriptString* propertyNameString, Var *setterValue, PropertyValueInfo* info, ScriptContext* requestContext)
  2285. {
  2286. DescriptorFlags flags;
  2287. PropertyRecord const* propertyRecord;
  2288. this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
  2289. if (propertyRecord != nullptr && GetSetterBuiltIns(propertyRecord->GetPropertyId(), info, &flags))
  2290. {
  2291. return flags;
  2292. }
  2293. return __super::GetSetter(propertyNameString, setterValue, info, requestContext);
  2294. }
  2295. bool JavascriptArray::GetSetterBuiltIns(PropertyId propertyId, PropertyValueInfo* info, DescriptorFlags* descriptorFlags)
  2296. {
  2297. if (propertyId == PropertyIds::length)
  2298. {
  2299. PropertyValueInfo::SetNoCache(info, this);
  2300. *descriptorFlags = WritableData;
  2301. return true;
  2302. }
  2303. return false;
  2304. }
  2305. SparseArraySegmentBase * JavascriptArray::GetBeginLookupSegment(uint32 index, const bool useSegmentMap) const
  2306. {
  2307. SparseArraySegmentBase *seg = nullptr;
  2308. SparseArraySegmentBase * lastUsedSeg = this->GetLastUsedSegment();
  2309. if (lastUsedSeg != nullptr && lastUsedSeg->left <= index)
  2310. {
  2311. seg = lastUsedSeg;
  2312. if(index - lastUsedSeg->left < lastUsedSeg->size)
  2313. {
  2314. return seg;
  2315. }
  2316. }
  2317. SegmentBTreeRoot * segmentMap = GetSegmentMap();
  2318. if(!useSegmentMap || !segmentMap)
  2319. {
  2320. return seg ? seg : PointerValue(this->head);
  2321. }
  2322. if(seg)
  2323. {
  2324. // If indexes are being accessed sequentially, check the segment after the last-used segment before checking the
  2325. // segment map, as it is likely to hit
  2326. SparseArraySegmentBase *const nextSeg = seg->next;
  2327. if(nextSeg)
  2328. {
  2329. if(index < nextSeg->left)
  2330. {
  2331. return seg;
  2332. }
  2333. else if(index - nextSeg->left < nextSeg->size)
  2334. {
  2335. return nextSeg;
  2336. }
  2337. }
  2338. }
  2339. SparseArraySegmentBase *matchOrNextSeg;
  2340. segmentMap->Find(index, seg, matchOrNextSeg);
  2341. return seg ? seg : matchOrNextSeg;
  2342. }
  2343. uint32 JavascriptArray::GetNextIndex(uint32 index) const
  2344. {
  2345. if (JavascriptNativeIntArray::Is((Var)this))
  2346. {
  2347. return this->GetNextIndexHelper<int32>(index);
  2348. }
  2349. else if (JavascriptNativeFloatArray::Is((Var)this))
  2350. {
  2351. return this->GetNextIndexHelper<double>(index);
  2352. }
  2353. return this->GetNextIndexHelper<Var>(index);
  2354. }
  2355. template<typename T>
  2356. uint32 JavascriptArray::GetNextIndexHelper(uint32 index) const
  2357. {
  2358. AssertMsg(this->head, "array head should never be null");
  2359. uint candidateIndex;
  2360. if (index == JavascriptArray::InvalidIndex)
  2361. {
  2362. candidateIndex = head->left;
  2363. }
  2364. else
  2365. {
  2366. candidateIndex = index + 1;
  2367. }
  2368. SparseArraySegment<T>* current = (SparseArraySegment<T>*)this->GetBeginLookupSegment(candidateIndex);
  2369. while (current != nullptr)
  2370. {
  2371. if ((current->left <= candidateIndex) && ((candidateIndex - current->left) < current->length))
  2372. {
  2373. for (uint i = candidateIndex - current->left; i < current->length; i++)
  2374. {
  2375. if (!SparseArraySegment<T>::IsMissingItem(&current->elements[i]))
  2376. {
  2377. return i + current->left;
  2378. }
  2379. }
  2380. }
  2381. current = SparseArraySegment<T>::From(current->next);
  2382. if (current != NULL)
  2383. {
  2384. if (candidateIndex < current->left)
  2385. {
  2386. candidateIndex = current->left;
  2387. }
  2388. }
  2389. }
  2390. return JavascriptArray::InvalidIndex;
  2391. }
  2392. // If new length > length, we just reset the length
  2393. // If new length < length, we need to remove the rest of the elements and segment
  2394. void JavascriptArray::SetLength(uint32 newLength)
  2395. {
  2396. if (newLength == length)
  2397. return;
  2398. if (head == EmptySegment)
  2399. {
  2400. // Do nothing to the segment.
  2401. }
  2402. else if (newLength == 0)
  2403. {
  2404. this->ClearElements(head, 0);
  2405. head->length = 0;
  2406. head->next = nullptr;
  2407. SetHasNoMissingValues();
  2408. ClearSegmentMap();
  2409. this->InvalidateLastUsedSegment();
  2410. }
  2411. else if (newLength < length)
  2412. {
  2413. // _ _ 2 3 _ _ 6 7 _ _
  2414. // SetLength(0)
  2415. // 0 <= left -> set *prev = null
  2416. // SetLength(2)
  2417. // 2 <= left -> set *prev = null
  2418. // SetLength(3)
  2419. // 3 !<= left; 3 <= right -> truncate to length - 1
  2420. // SetLength(5)
  2421. // 5 <=
  2422. SparseArraySegmentBase* next = GetBeginLookupSegment(newLength - 1); // head, or next.left < newLength
  2423. Field(SparseArraySegmentBase*)* prev = &head;
  2424. while(next != nullptr)
  2425. {
  2426. if (newLength <= next->left)
  2427. {
  2428. ClearSegmentMap(); // truncate segments, null out segmentMap
  2429. *prev = nullptr;
  2430. break;
  2431. }
  2432. else if (newLength <= (next->left + next->length))
  2433. {
  2434. if (next->next)
  2435. {
  2436. ClearSegmentMap(); // Will truncate segments, null out segmentMap
  2437. }
  2438. uint32 newSegmentLength = newLength - next->left;
  2439. this->ClearElements(next, newSegmentLength);
  2440. next->next = nullptr;
  2441. next->length = newSegmentLength;
  2442. next->CheckLengthvsSize();
  2443. break;
  2444. }
  2445. else
  2446. {
  2447. prev = &next->next;
  2448. next = next->next;
  2449. }
  2450. }
  2451. this->InvalidateLastUsedSegment();
  2452. }
  2453. this->length = newLength;
  2454. #ifdef VALIDATE_ARRAY
  2455. ValidateArray();
  2456. #endif
  2457. }
  2458. BOOL JavascriptArray::SetLength(Var newLength)
  2459. {
  2460. ScriptContext *scriptContext;
  2461. if(TaggedInt::Is(newLength))
  2462. {
  2463. int32 lenValue = TaggedInt::ToInt32(newLength);
  2464. if (lenValue < 0)
  2465. {
  2466. scriptContext = GetScriptContext();
  2467. if (scriptContext->GetThreadContext()->RecordImplicitException())
  2468. {
  2469. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  2470. }
  2471. }
  2472. else
  2473. {
  2474. this->SetLength(lenValue);
  2475. }
  2476. return TRUE;
  2477. }
  2478. scriptContext = GetScriptContext();
  2479. uint32 uintValue = JavascriptConversion::ToUInt32(newLength, scriptContext);
  2480. double dblValue = JavascriptConversion::ToNumber(newLength, scriptContext);
  2481. if (dblValue == uintValue)
  2482. {
  2483. this->SetLength(uintValue);
  2484. }
  2485. else
  2486. {
  2487. ThreadContext* threadContext = scriptContext->GetThreadContext();
  2488. ImplicitCallFlags flags = threadContext->GetImplicitCallFlags();
  2489. if (flags != ImplicitCall_None && threadContext->IsDisableImplicitCall())
  2490. {
  2491. // We couldn't execute the implicit call(s) needed to convert the newLength to an integer.
  2492. // Do nothing and let the jitted code bail out.
  2493. return TRUE;
  2494. }
  2495. if (threadContext->RecordImplicitException())
  2496. {
  2497. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  2498. }
  2499. }
  2500. return TRUE;
  2501. }
  2502. void JavascriptArray::ClearElements(SparseArraySegmentBase *seg, uint32 newSegmentLength)
  2503. {
  2504. SparseArraySegment<Var>::ClearElements(((SparseArraySegment<Var>*)seg)->elements + newSegmentLength, seg->length - newSegmentLength);
  2505. }
  2506. void JavascriptNativeIntArray::ClearElements(SparseArraySegmentBase *seg, uint32 newSegmentLength)
  2507. {
  2508. SparseArraySegment<int32>::ClearElements(((SparseArraySegment<int32>*)seg)->elements + newSegmentLength, seg->length - newSegmentLength);
  2509. }
  2510. void JavascriptNativeFloatArray::ClearElements(SparseArraySegmentBase *seg, uint32 newSegmentLength)
  2511. {
  2512. SparseArraySegment<double>::ClearElements(((SparseArraySegment<double>*)seg)->elements + newSegmentLength, seg->length - newSegmentLength);
  2513. }
  2514. Var JavascriptArray::DirectGetItem(uint32 index)
  2515. {
  2516. SparseArraySegment<Var> *seg = (SparseArraySegment<Var>*)this->GetLastUsedSegment();
  2517. uint32 offset = index - seg->left;
  2518. if (index >= seg->left && offset < seg->length)
  2519. {
  2520. if (!SparseArraySegment<Var>::IsMissingItem(&seg->elements[offset]))
  2521. {
  2522. return seg->elements[offset];
  2523. }
  2524. }
  2525. Var element = nullptr;
  2526. if (DirectGetItemAtFull(index, &element))
  2527. {
  2528. return element;
  2529. }
  2530. return GetType()->GetLibrary()->GetUndefined();
  2531. }
  2532. Var JavascriptNativeIntArray::DirectGetItem(uint32 index)
  2533. {
  2534. #if ENABLE_COPYONACCESS_ARRAY
  2535. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  2536. #endif
  2537. SparseArraySegment<int32> *seg = (SparseArraySegment<int32>*)this->GetLastUsedSegment();
  2538. uint32 offset = index - seg->left;
  2539. if (index >= seg->left && offset < seg->length)
  2540. {
  2541. if (!SparseArraySegment<int32>::IsMissingItem(&seg->elements[offset]))
  2542. {
  2543. return JavascriptNumber::ToVar(seg->elements[offset], GetScriptContext());
  2544. }
  2545. }
  2546. Var element = nullptr;
  2547. if (DirectGetItemAtFull(index, &element))
  2548. {
  2549. return element;
  2550. }
  2551. return GetType()->GetLibrary()->GetUndefined();
  2552. }
  2553. DescriptorFlags JavascriptNativeIntArray::GetItemSetter(uint32 index, Var* setterValue, ScriptContext* requestContext)
  2554. {
  2555. #if ENABLE_COPYONACCESS_ARRAY
  2556. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  2557. #endif
  2558. int32 value = 0;
  2559. return this->DirectGetItemAt(index, &value) ? WritableData : None;
  2560. }
  2561. Var JavascriptNativeFloatArray::DirectGetItem(uint32 index)
  2562. {
  2563. SparseArraySegment<double> *seg = (SparseArraySegment<double>*)this->GetLastUsedSegment();
  2564. uint32 offset = index - seg->left;
  2565. if (index >= seg->left && offset < seg->length)
  2566. {
  2567. if (!SparseArraySegment<double>::IsMissingItem(&seg->elements[offset]))
  2568. {
  2569. return JavascriptNumber::ToVarWithCheck(seg->elements[offset], GetScriptContext());
  2570. }
  2571. }
  2572. Var element = nullptr;
  2573. if (DirectGetItemAtFull(index, &element))
  2574. {
  2575. return element;
  2576. }
  2577. return GetType()->GetLibrary()->GetUndefined();
  2578. }
  2579. Var JavascriptArray::DirectGetItem(JavascriptString *propName, ScriptContext* scriptContext)
  2580. {
  2581. PropertyRecord const * propertyRecord;
  2582. scriptContext->GetOrAddPropertyRecord(propName, &propertyRecord);
  2583. return JavascriptOperators::GetProperty(this, propertyRecord->GetPropertyId(), scriptContext, NULL);
  2584. }
  2585. BOOL JavascriptArray::DirectGetItemAtFull(uint32 index, Var* outVal)
  2586. {
  2587. if (this->DirectGetItemAt(index, outVal))
  2588. {
  2589. return TRUE;
  2590. }
  2591. ScriptContext* requestContext = type->GetScriptContext();
  2592. return JavascriptOperators::GetItem(this, this->GetPrototype(), index, outVal, requestContext);
  2593. }
  2594. //
  2595. // Link prev and current. If prev is NULL, make current the head segment.
  2596. //
  2597. void JavascriptArray::LinkSegmentsCommon(SparseArraySegmentBase* prev, SparseArraySegmentBase* current)
  2598. {
  2599. if (prev)
  2600. {
  2601. prev->next = current;
  2602. }
  2603. else
  2604. {
  2605. Assert(current);
  2606. head = current;
  2607. }
  2608. }
  2609. template<typename T>
  2610. BOOL JavascriptArray::DirectDeleteItemAt(uint32 itemIndex)
  2611. {
  2612. if (itemIndex >= length)
  2613. {
  2614. return true;
  2615. }
  2616. SparseArraySegment<T>* next = (SparseArraySegment<T>*)GetBeginLookupSegment(itemIndex);
  2617. while(next != nullptr && next->left <= itemIndex)
  2618. {
  2619. uint32 limit = next->left + next->length;
  2620. if (itemIndex < limit)
  2621. {
  2622. next->SetElement(GetRecycler(), itemIndex, SparseArraySegment<T>::GetMissingItem());
  2623. if(itemIndex - next->left == next->length - 1)
  2624. {
  2625. --next->length;
  2626. next->CheckLengthvsSize();
  2627. }
  2628. else if(next == head)
  2629. {
  2630. SetHasNoMissingValues(false);
  2631. }
  2632. break;
  2633. }
  2634. next = SparseArraySegment<T>::From(next->next);
  2635. }
  2636. #ifdef VALIDATE_ARRAY
  2637. ValidateArray();
  2638. #endif
  2639. return true;
  2640. }
  2641. template <> Var JavascriptArray::ConvertToIndex(BigIndex idxDest, ScriptContext* scriptContext)
  2642. {
  2643. return idxDest.ToNumber(scriptContext);
  2644. }
  2645. template <> uint32 JavascriptArray::ConvertToIndex(BigIndex idxDest, ScriptContext* scriptContext)
  2646. {
  2647. // Note this is only for setting Array length which is a uint32
  2648. return idxDest.IsSmallIndex() ? idxDest.GetSmallIndex() : UINT_MAX;
  2649. }
  2650. template <> Var JavascriptArray::ConvertToIndex(uint32 idxDest, ScriptContext* scriptContext)
  2651. {
  2652. return JavascriptNumber::ToVar(idxDest, scriptContext);
  2653. }
  2654. void JavascriptArray::ThrowErrorOnFailure(BOOL succeeded, ScriptContext* scriptContext, uint32 index)
  2655. {
  2656. if (!succeeded)
  2657. {
  2658. JavascriptError::ThrowTypeError(scriptContext, JSERR_CantRedefineProp, JavascriptConversion::ToString(JavascriptNumber::ToVar(index, scriptContext), scriptContext)->GetSz());
  2659. }
  2660. }
  2661. void JavascriptArray::ThrowErrorOnFailure(BOOL succeeded, ScriptContext* scriptContext, BigIndex index)
  2662. {
  2663. if (!succeeded)
  2664. {
  2665. uint64 i = (uint64)(index.IsSmallIndex() ? index.GetSmallIndex() : index.GetBigIndex());
  2666. JavascriptError::ThrowTypeError(scriptContext, JSERR_CantRedefineProp, JavascriptConversion::ToString(JavascriptNumber::ToVar(i, scriptContext), scriptContext)->GetSz());
  2667. }
  2668. }
  2669. BOOL JavascriptArray::SetArrayLikeObjects(RecyclableObject* pDestObj, uint32 idxDest, Var aItem)
  2670. {
  2671. return pDestObj->SetItem(idxDest, aItem, Js::PropertyOperation_ThrowIfNotExtensible);
  2672. }
  2673. uint64 JavascriptArray::OP_GetLength(Var obj, ScriptContext *scriptContext)
  2674. {
  2675. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  2676. {
  2677. // Casting to uint64 is okay as ToLength will always be >= 0.
  2678. return (uint64)JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
  2679. }
  2680. else
  2681. {
  2682. return (uint64)JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
  2683. }
  2684. }
  2685. template<typename T>
  2686. void JavascriptArray::TryGetArrayAndLength(Var arg,
  2687. ScriptContext *scriptContext,
  2688. PCWSTR methodName,
  2689. __out JavascriptArray** array,
  2690. __out RecyclableObject** obj,
  2691. __out T * length)
  2692. {
  2693. Assert(array != nullptr);
  2694. Assert(obj != nullptr);
  2695. Assert(length != nullptr);
  2696. *array = JavascriptOperators::TryFromVar<JavascriptArray>(arg);
  2697. if (*array && !(*array)->IsCrossSiteObject())
  2698. {
  2699. #if ENABLE_COPYONACCESS_ARRAY
  2700. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(*array);
  2701. #endif
  2702. *obj = *array;
  2703. *length = (*array)->length;
  2704. }
  2705. else
  2706. {
  2707. if (!JavascriptConversion::ToObject(arg, scriptContext, obj))
  2708. {
  2709. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, methodName);
  2710. }
  2711. *length = OP_GetLength(*obj, scriptContext);
  2712. *array = nullptr;
  2713. }
  2714. }
  2715. BOOL JavascriptArray::SetArrayLikeObjects(RecyclableObject* pDestObj, BigIndex idxDest, Var aItem)
  2716. {
  2717. ScriptContext* scriptContext = pDestObj->GetScriptContext();
  2718. if (idxDest.IsSmallIndex())
  2719. {
  2720. return pDestObj->SetItem(idxDest.GetSmallIndex(), aItem, Js::PropertyOperation_ThrowIfNotExtensible);
  2721. }
  2722. PropertyRecord const * propertyRecord;
  2723. JavascriptOperators::GetPropertyIdForInt(idxDest.GetBigIndex(), scriptContext, &propertyRecord);
  2724. return pDestObj->SetProperty(propertyRecord->GetPropertyId(), aItem, PropertyOperation_ThrowIfNotExtensible, nullptr);
  2725. }
  2726. template<typename T>
  2727. void JavascriptArray::ConcatArgs(RecyclableObject* pDestObj, TypeId* remoteTypeIds,
  2728. Js::Arguments& args, ScriptContext* scriptContext, uint start, BigIndex startIdxDest,
  2729. ConcatSpreadableState previousItemSpreadableState /*= ConcatSpreadableState_NotChecked*/, BigIndex *firstPromotedItemLength /* = nullptr */)
  2730. {
  2731. // This never gets called.
  2732. Throw::InternalError();
  2733. }
  2734. //
  2735. // Helper for EntryConcat. Concat args or elements of arg arrays into dest array.
  2736. //
  2737. template<typename T>
  2738. void JavascriptArray::ConcatArgs(RecyclableObject* pDestObj, TypeId* remoteTypeIds,
  2739. Js::Arguments& args, ScriptContext* scriptContext, uint start, uint startIdxDest,
  2740. ConcatSpreadableState previousItemSpreadableState /*= ConcatSpreadableState_NotChecked*/, BigIndex *firstPromotedItemLength /* = nullptr */)
  2741. {
  2742. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  2743. JavascriptArray* pDestArray = JavascriptOperators::TryFromVar<JavascriptArray>(pDestObj);
  2744. if (pDestArray)
  2745. {
  2746. // ConcatArgs function expects to work on the Var array so we are ensuring it.
  2747. pDestArray = EnsureNonNativeArray(pDestArray);
  2748. SET_SECOND_OBJECT_FOR_MUTATION(jsReentLock, pDestArray);
  2749. }
  2750. AssertOrFailFast(scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled()); // ConcatSpreadable is enabled already - not going back.
  2751. T idxDest = startIdxDest;
  2752. for (uint idxArg = start; idxArg < args.Info.Count; idxArg++)
  2753. {
  2754. Var aItem = args[idxArg];
  2755. SETOBJECT_FOR_MUTATION(jsReentLock, aItem);
  2756. bool spreadable = previousItemSpreadableState == ConcatSpreadableState_CheckedAndTrue;
  2757. if (previousItemSpreadableState == ConcatSpreadableState_NotChecked)
  2758. {
  2759. JS_REENTRANT(jsReentLock, spreadable = !!JavascriptOperators::IsConcatSpreadable(aItem));
  2760. }
  2761. // Reset the state for the next item in the array
  2762. previousItemSpreadableState = ConcatSpreadableState_NotChecked;
  2763. if (!spreadable)
  2764. {
  2765. JS_REENTRANT(jsReentLock, JavascriptArray::SetConcatItem<T>(aItem, idxArg, pDestArray, pDestObj, idxDest, scriptContext));
  2766. ++idxDest;
  2767. continue;
  2768. }
  2769. if (pDestArray && JavascriptArray::IsDirectAccessArray(aItem) && JavascriptArray::IsDirectAccessArray(pDestArray)
  2770. && BigIndex(idxDest + JavascriptArray::UnsafeFromVar(aItem)->length).IsSmallIndex() && !JavascriptArray::UnsafeFromVar(aItem)->IsFillFromPrototypes()) // Fast path
  2771. {
  2772. JavascriptNativeIntArray *pIntItemArray = JavascriptOperators::TryFromVar<JavascriptNativeIntArray>(aItem);
  2773. if (pIntItemArray)
  2774. {
  2775. JS_REENTRANT_NO_MUTATE(jsReentLock, CopyNativeIntArrayElementsToVar(pDestArray, BigIndex(idxDest).GetSmallIndex(), pIntItemArray));
  2776. idxDest = idxDest + pIntItemArray->length;
  2777. }
  2778. else
  2779. {
  2780. JavascriptNativeFloatArray *pFloatItemArray = JavascriptOperators::TryFromVar<JavascriptNativeFloatArray>(aItem);
  2781. if (pFloatItemArray)
  2782. {
  2783. JS_REENTRANT_NO_MUTATE(jsReentLock, CopyNativeFloatArrayElementsToVar(pDestArray, BigIndex(idxDest).GetSmallIndex(), pFloatItemArray));
  2784. idxDest = idxDest + pFloatItemArray->length;
  2785. }
  2786. else
  2787. {
  2788. JavascriptArray* pItemArray = JavascriptArray::UnsafeFromVar(aItem);
  2789. JS_REENTRANT(jsReentLock, CopyArrayElements(pDestArray, BigIndex(idxDest).GetSmallIndex(), pItemArray));
  2790. idxDest = idxDest + pItemArray->length;
  2791. }
  2792. }
  2793. }
  2794. else
  2795. {
  2796. AssertOrFailFast(RecyclableObject::Is(aItem));
  2797. //CONSIDER: enumerating remote array instead of walking all indices
  2798. BigIndex length;
  2799. if (firstPromotedItemLength != nullptr)
  2800. {
  2801. length = *firstPromotedItemLength;
  2802. }
  2803. else
  2804. {
  2805. JS_REENTRANT(jsReentLock, length = OP_GetLength(aItem, scriptContext));
  2806. }
  2807. if (PromoteToBigIndex(length, idxDest))
  2808. {
  2809. // This is a special case for spreadable objects. We do not pre-calculate the length
  2810. // in EntryConcat like we do with Arrays because a getProperty on an object Length
  2811. // is observable. The result is we have to check for overflows separately for
  2812. // spreadable objects and promote to a bigger index type when we find them.
  2813. JS_REENTRANT(jsReentLock, ConcatArgs<BigIndex>(pDestObj, remoteTypeIds, args, scriptContext, idxArg, idxDest, ConcatSpreadableState_CheckedAndTrue, &length));
  2814. return;
  2815. }
  2816. if (length + idxDest > FiftyThirdPowerOfTwoMinusOne) // 2^53-1: from ECMA 22.1.3.1 Array.prototype.concat(...arguments)
  2817. {
  2818. JavascriptError::ThrowTypeError(scriptContext, JSERR_IllegalArraySizeAndLength);
  2819. }
  2820. RecyclableObject* itemObject = RecyclableObject::FromVar(aItem);
  2821. Var subItem;
  2822. uint32 lengthToUin32Max = length.IsSmallIndex() ? length.GetSmallIndex() : MaxArrayLength;
  2823. for (uint32 idxSubItem = 0u; idxSubItem < lengthToUin32Max; ++idxSubItem)
  2824. {
  2825. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(itemObject, idxSubItem));
  2826. if (hasItem)
  2827. {
  2828. JS_REENTRANT(jsReentLock, subItem = JavascriptOperators::GetItem(itemObject, idxSubItem, scriptContext));
  2829. if (pDestArray)
  2830. {
  2831. pDestArray->GenericDirectSetItemAt(idxDest, subItem);
  2832. }
  2833. else
  2834. {
  2835. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(SetArrayLikeObjects(pDestObj, idxDest, subItem), scriptContext, idxDest));
  2836. }
  2837. }
  2838. ++idxDest;
  2839. }
  2840. for (BigIndex idxSubItem = MaxArrayLength; idxSubItem < length; ++idxSubItem)
  2841. {
  2842. PropertyRecord const * propertyRecord;
  2843. JavascriptOperators::GetPropertyIdForInt(idxSubItem.GetBigIndex(), scriptContext, &propertyRecord);
  2844. JS_REENTRANT(jsReentLock, BOOL hasProp = JavascriptOperators::HasProperty(itemObject, propertyRecord->GetPropertyId()));
  2845. if (hasProp)
  2846. {
  2847. JS_REENTRANT(jsReentLock, subItem = JavascriptOperators::GetProperty(itemObject, propertyRecord->GetPropertyId(), scriptContext));
  2848. if (pDestArray)
  2849. {
  2850. pDestArray->GenericDirectSetItemAt(idxDest, subItem);
  2851. }
  2852. else
  2853. {
  2854. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(SetArrayLikeObjects(pDestObj, idxDest, subItem), scriptContext, idxSubItem));
  2855. }
  2856. }
  2857. ++idxDest;
  2858. }
  2859. }
  2860. firstPromotedItemLength = nullptr;
  2861. }
  2862. if (!pDestArray)
  2863. {
  2864. JS_REENTRANT(jsReentLock, pDestObj->SetProperty(PropertyIds::length, ConvertToIndex<T, Var>(idxDest, scriptContext), Js::PropertyOperation_None, nullptr));
  2865. }
  2866. else if (pDestArray->GetLength() != ConvertToIndex<T, uint32>(idxDest, scriptContext))
  2867. {
  2868. pDestArray->SetLength(ConvertToIndex<T, uint32>(idxDest, scriptContext));
  2869. }
  2870. }
  2871. bool JavascriptArray::PromoteToBigIndex(BigIndex lhs, BigIndex rhs)
  2872. {
  2873. return false; // already a big index
  2874. }
  2875. bool JavascriptArray::PromoteToBigIndex(BigIndex lhs, uint32 rhs)
  2876. {
  2877. ::Math::RecordOverflowPolicy destLengthOverflow;
  2878. if (lhs.IsSmallIndex())
  2879. {
  2880. UInt32Math::Add(lhs.GetSmallIndex(), rhs, destLengthOverflow);
  2881. return destLengthOverflow.HasOverflowed();
  2882. }
  2883. return true;
  2884. }
  2885. JavascriptArray* JavascriptArray::ConcatIntArgs(JavascriptNativeIntArray* pDestArray, TypeId *remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext)
  2886. {
  2887. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  2888. SET_SECOND_OBJECT_FOR_MUTATION(jsReentLock, pDestArray);
  2889. AssertOrFailFast(scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled());
  2890. Assert(pDestArray->GetTypeId() == TypeIds_NativeIntArray);
  2891. uint idxDest = 0u;
  2892. for (uint idxArg = 0; idxArg < args.Info.Count; idxArg++)
  2893. {
  2894. Var aItem = args[idxArg];
  2895. SETOBJECT_FOR_MUTATION(jsReentLock, aItem);
  2896. bool spreadable = false;
  2897. JS_REENTRANT(jsReentLock, spreadable = !!JavascriptOperators::IsConcatSpreadable(aItem));
  2898. if (!JavascriptNativeIntArray::Is(pDestArray))
  2899. {
  2900. JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest,
  2901. spreadable ? ConcatSpreadableState_CheckedAndTrue : ConcatSpreadableState_CheckedAndFalse));
  2902. return pDestArray;
  2903. }
  2904. if (!spreadable)
  2905. {
  2906. JS_REENTRANT(jsReentLock, pDestArray->SetItem(idxDest, aItem, PropertyOperation_ThrowIfNotExtensible));
  2907. idxDest++;
  2908. if (!JavascriptNativeIntArray::Is(pDestArray)) // SetItem could convert pDestArray to a var array if aItem is not an integer if so fall back
  2909. {
  2910. JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest, ConcatSpreadableState_NotChecked));
  2911. return pDestArray;
  2912. }
  2913. continue;
  2914. }
  2915. JavascriptNativeIntArray * pItemArray = JavascriptOperators::TryFromVar<JavascriptNativeIntArray>(aItem);
  2916. if (pItemArray && !pItemArray->IsFillFromPrototypes()) // Fast path
  2917. {
  2918. JS_REENTRANT_NO_MUTATE(jsReentLock, bool converted = CopyNativeIntArrayElements(pDestArray, idxDest, pItemArray));
  2919. idxDest = idxDest + pItemArray->length;
  2920. if (converted)
  2921. {
  2922. // Copying the last array forced a conversion, so switch over to the var version
  2923. // to finish.
  2924. JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest, ConcatSpreadableState_NotChecked));
  2925. return pDestArray;
  2926. }
  2927. }
  2928. else if (!JavascriptArray::IsAnyArray(aItem) && remoteTypeIds[idxArg] != TypeIds_Array)
  2929. {
  2930. if (TaggedInt::Is(aItem))
  2931. {
  2932. pDestArray->DirectSetItemAt(idxDest, TaggedInt::ToInt32(aItem));
  2933. }
  2934. else
  2935. {
  2936. #if DBG
  2937. int32 int32Value;
  2938. Assert(
  2939. JavascriptNumber::TryGetInt32Value(JavascriptNumber::GetValue(aItem), &int32Value) &&
  2940. !SparseArraySegment<int32>::IsMissingItem(&int32Value));
  2941. #endif
  2942. pDestArray->DirectSetItemAt(idxDest, static_cast<int32>(JavascriptNumber::GetValue(aItem)));
  2943. }
  2944. ++idxDest;
  2945. }
  2946. else
  2947. {
  2948. JavascriptArray *pVarDestArray = JavascriptNativeIntArray::ConvertToVarArray(pDestArray);
  2949. BigIndex length;
  2950. JS_REENTRANT(jsReentLock, length = OP_GetLength(aItem, scriptContext),
  2951. ConcatArgs<uint>(pVarDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest, ConcatSpreadableState_CheckedAndTrue, &length));
  2952. return pVarDestArray;
  2953. }
  2954. }
  2955. if (pDestArray->GetLength() != idxDest)
  2956. {
  2957. pDestArray->SetLength(idxDest);
  2958. }
  2959. return pDestArray;
  2960. }
  2961. JavascriptArray* JavascriptArray::ConcatFloatArgs(JavascriptNativeFloatArray* pDestArray, TypeId *remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext)
  2962. {
  2963. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  2964. SET_SECOND_OBJECT_FOR_MUTATION(jsReentLock, pDestArray);
  2965. AssertOrFailFast(scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled());
  2966. uint idxDest = 0u;
  2967. for (uint idxArg = 0; idxArg < args.Info.Count; idxArg++)
  2968. {
  2969. Var aItem = args[idxArg];
  2970. SETOBJECT_FOR_MUTATION(jsReentLock, aItem);
  2971. bool spreadable = false;
  2972. JS_REENTRANT(jsReentLock, spreadable = !!JavascriptOperators::IsConcatSpreadable(aItem));
  2973. if (!JavascriptNativeFloatArray::Is(pDestArray))
  2974. {
  2975. JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest,
  2976. spreadable ? ConcatSpreadableState_CheckedAndTrue : ConcatSpreadableState_CheckedAndFalse));
  2977. return pDestArray;
  2978. }
  2979. if (!spreadable)
  2980. {
  2981. JS_REENTRANT(jsReentLock, pDestArray->SetItem(idxDest, aItem, PropertyOperation_ThrowIfNotExtensible));
  2982. idxDest = idxDest + 1;
  2983. if (!JavascriptNativeFloatArray::Is(pDestArray)) // SetItem could convert pDestArray to a var array if aItem is not an integer if so fall back
  2984. {
  2985. JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest, ConcatSpreadableState_NotChecked));
  2986. return pDestArray;
  2987. }
  2988. continue;
  2989. }
  2990. bool converted = false;
  2991. if (JavascriptArray::IsAnyArray(aItem) || remoteTypeIds[idxArg] == TypeIds_Array)
  2992. {
  2993. bool isFillFromPrototypes = JavascriptArray::UnsafeFromVar(aItem)->IsFillFromPrototypes();
  2994. JavascriptNativeIntArray * pIntItemArray = JavascriptOperators::TryFromVar<JavascriptNativeIntArray>(aItem);
  2995. if (pIntItemArray && !isFillFromPrototypes) // Fast path
  2996. {
  2997. JS_REENTRANT_NO_MUTATE(jsReentLock, converted = CopyNativeIntArrayElementsToFloat(pDestArray, idxDest, pIntItemArray));
  2998. idxDest = idxDest + pIntItemArray->length;
  2999. }
  3000. else
  3001. {
  3002. JavascriptNativeFloatArray * pFloatItemArray = JavascriptOperators::TryFromVar<JavascriptNativeFloatArray>(aItem);
  3003. if (pFloatItemArray && !isFillFromPrototypes)
  3004. {
  3005. JS_REENTRANT_NO_MUTATE(jsReentLock, converted = CopyNativeFloatArrayElements(pDestArray, idxDest, pFloatItemArray));
  3006. idxDest = idxDest + pFloatItemArray->length;
  3007. }
  3008. else
  3009. {
  3010. JavascriptArray *pVarDestArray = JavascriptNativeFloatArray::ConvertToVarArray(pDestArray);
  3011. BigIndex length;
  3012. JS_REENTRANT(jsReentLock, length = OP_GetLength(aItem, scriptContext),
  3013. ConcatArgs<uint>(pVarDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest, ConcatSpreadableState_CheckedAndTrue, &length));
  3014. return pVarDestArray;
  3015. }
  3016. }
  3017. if (converted)
  3018. {
  3019. // Copying the last array forced a conversion, so switch over to the var version
  3020. // to finish.
  3021. JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest, ConcatSpreadableState_NotChecked));
  3022. return pDestArray;
  3023. }
  3024. }
  3025. else
  3026. {
  3027. if (TaggedInt::Is(aItem))
  3028. {
  3029. pDestArray->DirectSetItemAt(idxDest, (double)TaggedInt::ToInt32(aItem));
  3030. }
  3031. else
  3032. {
  3033. Assert(JavascriptNumber::Is(aItem));
  3034. pDestArray->DirectSetItemAt(idxDest, JavascriptNumber::GetValue(aItem));
  3035. }
  3036. ++idxDest;
  3037. }
  3038. }
  3039. if (pDestArray->GetLength() != idxDest)
  3040. {
  3041. pDestArray->SetLength(idxDest);
  3042. }
  3043. return pDestArray;
  3044. }
  3045. bool JavascriptArray::BoxConcatItem(Var aItem, uint idxArg, ScriptContext *scriptContext)
  3046. {
  3047. return idxArg == 0 && !JavascriptOperators::IsObject(aItem);
  3048. }
  3049. Var JavascriptArray::EntryConcat(RecyclableObject* function, CallInfo callInfo, ...)
  3050. {
  3051. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  3052. ARGUMENTS(args, callInfo);
  3053. ScriptContext* scriptContext = function->GetScriptContext();
  3054. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3055. Assert(!(callInfo.Flags & CallFlags_New));
  3056. if (args.Info.Count == 0)
  3057. {
  3058. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.concat"));
  3059. }
  3060. //
  3061. // Compute the destination ScriptArray size:
  3062. // - Each item, flattening only one level if a ScriptArray.
  3063. //
  3064. uint32 cDestLength = 0;
  3065. JavascriptArray * pDestArray = NULL;
  3066. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault + (args.Info.Count * sizeof(TypeId*)));
  3067. TypeId* remoteTypeIds = (TypeId*)_alloca(args.Info.Count * sizeof(TypeId*));
  3068. bool isInt = true;
  3069. bool isFloat = true;
  3070. ::Math::RecordOverflowPolicy destLengthOverflow;
  3071. for (uint idxArg = 0; idxArg < args.Info.Count; idxArg++)
  3072. {
  3073. Var aItem = args[idxArg];
  3074. #if ENABLE_COPYONACCESS_ARRAY
  3075. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(aItem);
  3076. #endif
  3077. if (DynamicObject::IsAnyArray(aItem)) // Get JavascriptArray or ES5Array length
  3078. {
  3079. JavascriptArray * pItemArray = JavascriptArray::FromAnyArray(aItem);
  3080. if (isFloat)
  3081. {
  3082. if (!JavascriptNativeIntArray::Is(pItemArray))
  3083. {
  3084. isInt = false;
  3085. if (!JavascriptNativeFloatArray::Is(pItemArray))
  3086. {
  3087. isFloat = false;
  3088. }
  3089. }
  3090. }
  3091. cDestLength = UInt32Math::Add(cDestLength, pItemArray->GetLength(), destLengthOverflow);
  3092. }
  3093. else // Get remote array or object length
  3094. {
  3095. // We already checked for types derived from JavascriptArray. These are types that should behave like array
  3096. // i.e. proxy to array and remote array.
  3097. if (JavascriptOperators::IsArray(aItem))
  3098. {
  3099. // Don't try to preserve nativeness of remote arrays. The extra complexity is probably not
  3100. // worth it.
  3101. isInt = false;
  3102. isFloat = false;
  3103. if (!JavascriptProxy::Is(aItem))
  3104. {
  3105. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  3106. {
  3107. JS_REENTRANT(jsReentLock,
  3108. int64 len = JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(aItem, scriptContext), scriptContext));
  3109. // clipping to MaxArrayLength will overflow when added to cDestLength which we catch below
  3110. cDestLength = UInt32Math::Add(cDestLength, len < MaxArrayLength ? (uint32)len : MaxArrayLength, destLengthOverflow);
  3111. }
  3112. else
  3113. {
  3114. JS_REENTRANT(jsReentLock,
  3115. uint len = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(aItem, scriptContext), scriptContext));
  3116. cDestLength = UInt32Math::Add(cDestLength, len, destLengthOverflow);
  3117. }
  3118. }
  3119. remoteTypeIds[idxArg] = TypeIds_Array; // Mark remote array, no matter remote JavascriptArray or ES5Array.
  3120. }
  3121. else
  3122. {
  3123. if (isFloat)
  3124. {
  3125. if (BoxConcatItem(aItem, idxArg, scriptContext))
  3126. {
  3127. // A primitive will be boxed, so we have to create a var array for the result.
  3128. isInt = false;
  3129. isFloat = false;
  3130. }
  3131. else if (!TaggedInt::Is(aItem))
  3132. {
  3133. if (!JavascriptNumber::Is(aItem))
  3134. {
  3135. isInt = false;
  3136. isFloat = false;
  3137. }
  3138. else if (isInt)
  3139. {
  3140. int32 int32Value;
  3141. if(!JavascriptNumber::TryGetInt32Value(JavascriptNumber::GetValue(aItem), &int32Value) ||
  3142. SparseArraySegment<int32>::IsMissingItem(&int32Value))
  3143. {
  3144. isInt = false;
  3145. }
  3146. }
  3147. }
  3148. else if(isInt)
  3149. {
  3150. int32 int32Value = TaggedInt::ToInt32(aItem);
  3151. if(SparseArraySegment<int32>::IsMissingItem(&int32Value))
  3152. {
  3153. isInt = false;
  3154. }
  3155. }
  3156. }
  3157. remoteTypeIds[idxArg] = TypeIds_Limit;
  3158. cDestLength = UInt32Math::Add(cDestLength, 1, destLengthOverflow);
  3159. }
  3160. }
  3161. }
  3162. if (destLengthOverflow.HasOverflowed())
  3163. {
  3164. cDestLength = MaxArrayLength;
  3165. isInt = false;
  3166. isFloat = false;
  3167. }
  3168. //
  3169. // Create the destination array
  3170. //
  3171. RecyclableObject* pDestObj = nullptr;
  3172. bool isArray = false;
  3173. JS_REENTRANT_NO_MUTATE(jsReentLock, pDestObj = ArraySpeciesCreate(args[0], 0, scriptContext));
  3174. if (pDestObj)
  3175. {
  3176. #if ENABLE_COPYONACCESS_ARRAY
  3177. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pDestObj);
  3178. #endif
  3179. // Check the thing that species create made. If it's a native array that can't handle the source
  3180. // data, convert it. If it's a more conservative kind of array than the source data, indicate that
  3181. // so that the data will be converted on copy.
  3182. if (isInt)
  3183. {
  3184. if (JavascriptNativeIntArray::Is(pDestObj))
  3185. {
  3186. isArray = true;
  3187. }
  3188. else
  3189. {
  3190. isInt = false;
  3191. isFloat = JavascriptNativeFloatArray::Is(pDestObj);
  3192. isArray = JavascriptArray::Is(pDestObj);
  3193. }
  3194. }
  3195. else if (isFloat)
  3196. {
  3197. JavascriptNativeIntArray *nativeIntArray = JavascriptOperators::TryFromVar<JavascriptNativeIntArray>(pDestObj);
  3198. if (nativeIntArray)
  3199. {
  3200. JavascriptNativeIntArray::ToNativeFloatArray(nativeIntArray);
  3201. isArray = true;
  3202. }
  3203. else
  3204. {
  3205. isFloat = JavascriptNativeFloatArray::Is(pDestObj);
  3206. isArray = JavascriptArray::Is(pDestObj);
  3207. }
  3208. }
  3209. else
  3210. {
  3211. JavascriptNativeIntArray *nativeIntArray = JavascriptOperators::TryFromVar<Js::JavascriptNativeIntArray>(pDestObj);
  3212. if (nativeIntArray)
  3213. {
  3214. JavascriptNativeIntArray::ToVarArray(nativeIntArray);
  3215. isArray = true;
  3216. }
  3217. else
  3218. {
  3219. JavascriptNativeFloatArray *nativeFloatArray = JavascriptOperators::TryFromVar<Js::JavascriptNativeFloatArray>(pDestObj);
  3220. if (nativeFloatArray)
  3221. {
  3222. JavascriptNativeFloatArray::ToVarArray(nativeFloatArray);
  3223. isArray = true;
  3224. }
  3225. else
  3226. {
  3227. isArray = JavascriptArray::Is(pDestObj);
  3228. }
  3229. }
  3230. }
  3231. }
  3232. if (pDestObj == nullptr || isArray)
  3233. {
  3234. if (isInt)
  3235. {
  3236. JavascriptNativeIntArray *pIntArray = isArray ? JavascriptNativeIntArray::FromVar(pDestObj) : scriptContext->GetLibrary()->CreateNativeIntArray(cDestLength);
  3237. pIntArray->EnsureHead<int32>();
  3238. JS_REENTRANT(jsReentLock, pDestArray = ConcatIntArgs(pIntArray, remoteTypeIds, args, scriptContext));
  3239. }
  3240. else if (isFloat)
  3241. {
  3242. JavascriptNativeFloatArray *pFArray = isArray ? JavascriptNativeFloatArray::FromVar(pDestObj) : scriptContext->GetLibrary()->CreateNativeFloatArray(cDestLength);
  3243. pFArray->EnsureHead<double>();
  3244. JS_REENTRANT(jsReentLock, pDestArray = ConcatFloatArgs(pFArray, remoteTypeIds, args, scriptContext));
  3245. }
  3246. else
  3247. {
  3248. pDestArray = isArray ? JavascriptArray::FromVar(pDestObj) : scriptContext->GetLibrary()->CreateArray(cDestLength);
  3249. // if the constructor has changed then we no longer specialize for ints and floats
  3250. pDestArray->EnsureHead<Var>();
  3251. JS_REENTRANT(jsReentLock, ConcatArgsCallingHelper(pDestArray, remoteTypeIds, args, scriptContext, destLengthOverflow));
  3252. }
  3253. //
  3254. // Return the new array instance.
  3255. //
  3256. #ifdef VALIDATE_ARRAY
  3257. pDestArray->ValidateArray();
  3258. #endif
  3259. return pDestArray;
  3260. }
  3261. Assert(pDestObj);
  3262. JS_REENTRANT(jsReentLock, ConcatArgsCallingHelper(pDestObj, remoteTypeIds, args, scriptContext, destLengthOverflow));
  3263. return pDestObj;
  3264. }
  3265. void JavascriptArray::ConcatArgsCallingHelper(RecyclableObject* pDestObj, TypeId* remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext, ::Math::RecordOverflowPolicy &destLengthOverflow)
  3266. {
  3267. if (destLengthOverflow.HasOverflowed())
  3268. {
  3269. ConcatArgs<BigIndex>(pDestObj, remoteTypeIds, args, scriptContext);
  3270. }
  3271. else
  3272. {
  3273. // Use faster uint32 version if no overflow
  3274. ConcatArgs<uint32>(pDestObj, remoteTypeIds, args, scriptContext);
  3275. }
  3276. }
  3277. template<typename T>
  3278. /* static */ void JavascriptArray::SetConcatItem(Var aItem, uint idxArg, JavascriptArray* pDestArray, RecyclableObject* pDestObj, T idxDest, ScriptContext *scriptContext)
  3279. {
  3280. if (BoxConcatItem(aItem, idxArg, scriptContext))
  3281. {
  3282. // bug# 725784: ES5: not calling ToObject in Step 1 of 15.4.4.4
  3283. RecyclableObject* pObj = nullptr;
  3284. if (FALSE == JavascriptConversion::ToObject(aItem, scriptContext, &pObj))
  3285. {
  3286. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.concat"));
  3287. }
  3288. if (pDestArray)
  3289. {
  3290. pDestArray->GenericDirectSetItemAt(idxDest, pObj);
  3291. }
  3292. else
  3293. {
  3294. SetArrayLikeObjects(pDestObj, idxDest, pObj);
  3295. }
  3296. }
  3297. else
  3298. {
  3299. if (pDestArray)
  3300. {
  3301. pDestArray->GenericDirectSetItemAt(idxDest, aItem);
  3302. }
  3303. else
  3304. {
  3305. SetArrayLikeObjects(pDestObj, idxDest, aItem);
  3306. }
  3307. }
  3308. }
  3309. int64 JavascriptArray::GetFromLastIndex(Var arg, int64 length, ScriptContext *scriptContext)
  3310. {
  3311. int64 fromIndex;
  3312. if (TaggedInt::Is(arg))
  3313. {
  3314. int intValue = TaggedInt::ToInt32(arg);
  3315. if (intValue >= 0)
  3316. {
  3317. fromIndex = min<int64>(intValue, length - 1);
  3318. }
  3319. else if ((uint32)-intValue > length)
  3320. {
  3321. return length;
  3322. }
  3323. else
  3324. {
  3325. fromIndex = intValue + length;
  3326. }
  3327. }
  3328. else
  3329. {
  3330. double value = JavascriptConversion::ToInteger(arg, scriptContext);
  3331. if (value >= 0)
  3332. {
  3333. fromIndex = (int64)min(value, (double)(length - 1));
  3334. }
  3335. else if (value + length < 0)
  3336. {
  3337. return length;
  3338. }
  3339. else
  3340. {
  3341. fromIndex = (int64)(value + length);
  3342. }
  3343. }
  3344. return fromIndex;
  3345. }
  3346. // includesAlgorithm specifies to follow ES7 Array.prototype.includes semantics instead of Array.prototype.indexOf
  3347. // Differences
  3348. // 1. Returns boolean true or false value instead of the search hit index
  3349. // 2. Follows SameValueZero algorithm instead of StrictEquals
  3350. // 3. Missing values are scanned if the search value is undefined
  3351. template <bool includesAlgorithm>
  3352. Var JavascriptArray::IndexOfHelper(Arguments const & args, ScriptContext *scriptContext)
  3353. {
  3354. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3355. SETOBJECT_FOR_MUTATION(jsReentLock, args[0]);
  3356. RecyclableObject* obj = nullptr;
  3357. JavascriptArray* pArr = nullptr;
  3358. BigIndex length;
  3359. Var trueValue = scriptContext->GetLibrary()->GetTrue();
  3360. Var falseValue = scriptContext->GetLibrary()->GetFalse();
  3361. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.indexOf"), &pArr, &obj, &length));
  3362. Var search;
  3363. uint32 fromIndex = 0;
  3364. uint64 fromIndex64 = 0;
  3365. // The evaluation of method arguments may change the type of the array. Hence, we do that prior to the actual helper method calls.
  3366. // The if clause of the conditional statement below applies to an JavascriptArray or TypedArray instances. The rest of the conditional
  3367. // clauses apply to an ES5Array or other valid Javascript objects.
  3368. if ((pArr || TypedArrayBase::Is(obj)) && (length.IsSmallIndex() || length.IsUint32Max()))
  3369. {
  3370. uint32 len = length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex();
  3371. JS_REENTRANT(jsReentLock, BOOL gotParam = GetParamForIndexOf(len, args, search, fromIndex, scriptContext));
  3372. if (!gotParam)
  3373. {
  3374. return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
  3375. }
  3376. }
  3377. else if (length.IsSmallIndex())
  3378. {
  3379. JS_REENTRANT(jsReentLock, BOOL gotParam = GetParamForIndexOf(length.GetSmallIndex(), args, search, fromIndex, scriptContext));
  3380. if (!gotParam)
  3381. {
  3382. return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
  3383. }
  3384. }
  3385. else
  3386. {
  3387. JS_REENTRANT(jsReentLock, BOOL gotParam = GetParamForIndexOf(length.GetBigIndex(), args, search, fromIndex64, scriptContext));
  3388. if (!gotParam)
  3389. {
  3390. return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
  3391. }
  3392. }
  3393. // Side effects (such as defining a property in a ToPrimitive call) during evaluation of fromIndex argument may convert the array to an ES5 array.
  3394. if (pArr && !JavascriptArray::Is(obj))
  3395. {
  3396. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  3397. pArr = nullptr;
  3398. }
  3399. if (pArr)
  3400. {
  3401. if (length.IsSmallIndex() || length.IsUint32Max())
  3402. {
  3403. uint32 len = length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex();
  3404. JS_REENTRANT(jsReentLock, int32 index = pArr->HeadSegmentIndexOfHelper(search, fromIndex, len, includesAlgorithm, scriptContext));
  3405. // If we found the search value in the head segment, or if we determined there is no need to search other segments,
  3406. // we stop right here.
  3407. if (index != -1 || fromIndex == -1)
  3408. {
  3409. if (includesAlgorithm)
  3410. {
  3411. //Array.prototype.includes
  3412. return (index == -1) ? falseValue : trueValue;
  3413. }
  3414. else
  3415. {
  3416. //Array.prototype.indexOf
  3417. return JavascriptNumber::ToVar(index, scriptContext);
  3418. }
  3419. }
  3420. // If we really must search other segments, let's do it now. We'll have to search the slow way (dealing with holes, etc.).
  3421. switch (pArr->GetTypeId())
  3422. {
  3423. case Js::TypeIds_Array:
  3424. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(pArr, search, fromIndex, len, scriptContext));
  3425. case Js::TypeIds_NativeIntArray:
  3426. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(JavascriptNativeIntArray::UnsafeFromVar(pArr), search, fromIndex, len, scriptContext));
  3427. case Js::TypeIds_NativeFloatArray:
  3428. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(JavascriptNativeFloatArray::UnsafeFromVar(pArr), search, fromIndex, len, scriptContext));
  3429. default:
  3430. AssertMsg(FALSE, "invalid array typeid");
  3431. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(pArr, search, fromIndex, len, scriptContext));
  3432. }
  3433. }
  3434. }
  3435. // source object is not a JavascriptArray but source could be a TypedArray
  3436. TypedArrayBase * typedArrayObj = JavascriptOperators::TryFromVar<Js::TypedArrayBase>(obj);
  3437. if (typedArrayObj)
  3438. {
  3439. if (length.IsSmallIndex() || length.IsUint32Max())
  3440. {
  3441. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(typedArrayObj, search, fromIndex, length.GetSmallIndex(), scriptContext));
  3442. }
  3443. }
  3444. if (length.IsSmallIndex())
  3445. {
  3446. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(obj, search, fromIndex, length.GetSmallIndex(), scriptContext));
  3447. }
  3448. else
  3449. {
  3450. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(obj, search, fromIndex64, length.GetBigIndex(), scriptContext));
  3451. }
  3452. }
  3453. // Array.prototype.indexOf as defined in ES6.0 (final) Section 22.1.3.11
  3454. Var JavascriptArray::EntryIndexOf(RecyclableObject* function, CallInfo callInfo, ...)
  3455. {
  3456. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  3457. ARGUMENTS(args, callInfo);
  3458. ScriptContext* scriptContext = function->GetScriptContext();
  3459. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3460. Assert(!(callInfo.Flags & CallFlags_New));
  3461. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_indexOf);
  3462. JS_REENTRANT_UNLOCK(jsReentLock, Var returnValue = IndexOfHelper<false>(args, scriptContext));
  3463. //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
  3464. Assert(returnValue != scriptContext->GetLibrary()->GetTrue() && returnValue != scriptContext->GetLibrary()->GetFalse());
  3465. return returnValue;
  3466. }
  3467. Var JavascriptArray::EntryIncludes(RecyclableObject* function, CallInfo callInfo, ...)
  3468. {
  3469. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  3470. ARGUMENTS(args, callInfo);
  3471. ScriptContext* scriptContext = function->GetScriptContext();
  3472. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3473. Assert(!(callInfo.Flags & CallFlags_New));
  3474. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_includes);
  3475. JS_REENTRANT(jsReentLock, Var returnValue = IndexOfHelper<true>(args, scriptContext));
  3476. Assert(returnValue == scriptContext->GetLibrary()->GetTrue() || returnValue == scriptContext->GetLibrary()->GetFalse());
  3477. return returnValue;
  3478. }
  3479. template<typename T>
  3480. BOOL JavascriptArray::GetParamForIndexOf(T length, Arguments const& args, Var& search, T& fromIndex, ScriptContext * scriptContext)
  3481. {
  3482. if (length == 0)
  3483. {
  3484. return false;
  3485. }
  3486. if (args.Info.Count > 2)
  3487. {
  3488. fromIndex = GetFromIndex(args[2], length, scriptContext);
  3489. if (fromIndex >= length)
  3490. {
  3491. return false;
  3492. }
  3493. search = args[1];
  3494. }
  3495. else
  3496. {
  3497. fromIndex = 0;
  3498. search = args.Info.Count > 1 ? args[1] : scriptContext->GetLibrary()->GetUndefined();
  3499. }
  3500. return true;
  3501. }
  3502. template <>
  3503. BOOL JavascriptArray::TemplatedGetItem(RecyclableObject * obj, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3504. {
  3505. // Note: Sometime cross site array go down this path to get the marshalling
  3506. Assert(!VirtualTableInfo<JavascriptArray>::HasVirtualTable(obj)
  3507. && !VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(obj)
  3508. && !VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(obj));
  3509. if (checkHasItem && !JavascriptOperators::HasItem(obj, index))
  3510. {
  3511. return FALSE;
  3512. }
  3513. return JavascriptOperators::GetItem(obj, index, element, scriptContext);
  3514. }
  3515. template <>
  3516. BOOL JavascriptArray::TemplatedGetItem(RecyclableObject * obj, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3517. {
  3518. // Note: Sometime cross site array go down this path to get the marshalling
  3519. Assert(!VirtualTableInfo<JavascriptArray>::HasVirtualTable(obj)
  3520. && !VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(obj)
  3521. && !VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(obj));
  3522. PropertyRecord const * propertyRecord;
  3523. JavascriptOperators::GetPropertyIdForInt(index, scriptContext, &propertyRecord);
  3524. if (checkHasItem && !JavascriptOperators::HasProperty(obj, propertyRecord->GetPropertyId()))
  3525. {
  3526. return FALSE;
  3527. }
  3528. *element = JavascriptOperators::GetProperty(obj, propertyRecord->GetPropertyId(), scriptContext);
  3529. return *element != scriptContext->GetLibrary()->GetUndefined();
  3530. }
  3531. template <>
  3532. BOOL JavascriptArray::TemplatedGetItem(JavascriptArray *pArr, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3533. {
  3534. Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(pArr)
  3535. || VirtualTableInfo<CrossSiteObject<JavascriptArray>>::HasVirtualTable(pArr));
  3536. return pArr->JavascriptArray::DirectGetItemAtFull(index, element);
  3537. }
  3538. template <>
  3539. BOOL JavascriptArray::TemplatedGetItem(JavascriptArray *pArr, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3540. {
  3541. // This should never get called.
  3542. Assert(false);
  3543. Throw::InternalError();
  3544. }
  3545. template <>
  3546. BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeIntArray *pArr, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3547. {
  3548. Assert(VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(pArr)
  3549. || VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::HasVirtualTable(pArr));
  3550. return pArr->JavascriptNativeIntArray::DirectGetItemAtFull(index, element);
  3551. }
  3552. template <>
  3553. BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeIntArray *pArr, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3554. {
  3555. // This should never get called.
  3556. Assert(false);
  3557. Throw::InternalError();
  3558. }
  3559. template <>
  3560. BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeFloatArray *pArr, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3561. {
  3562. Assert(VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(pArr)
  3563. || VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::HasVirtualTable(pArr));
  3564. return pArr->JavascriptNativeFloatArray::DirectGetItemAtFull(index, element);
  3565. }
  3566. template <>
  3567. BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeFloatArray *pArr, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3568. {
  3569. // This should never get called.
  3570. Assert(false);
  3571. Throw::InternalError();
  3572. }
  3573. template <>
  3574. BOOL JavascriptArray::TemplatedGetItem(TypedArrayBase * typedArrayBase, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3575. {
  3576. // We need to do explicit check for items since length value may not actually match the actual TypedArray length.
  3577. // User could add a length property to a TypedArray instance which lies and returns a different value from the underlying length.
  3578. // Since this method can be called via Array.prototype.indexOf with .apply or .call passing a TypedArray as this parameter
  3579. // we don't know whether or not length == typedArrayBase->GetLength().
  3580. if (checkHasItem && !typedArrayBase->HasItem(index))
  3581. {
  3582. return false;
  3583. }
  3584. *element = typedArrayBase->DirectGetItem(index);
  3585. return true;
  3586. }
  3587. template <>
  3588. BOOL JavascriptArray::TemplatedGetItem(TypedArrayBase * typedArrayBase, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3589. {
  3590. // This should never get called.
  3591. Assert(false);
  3592. Throw::InternalError();
  3593. }
  3594. template <bool includesAlgorithm, typename T, typename P>
  3595. Var JavascriptArray::TemplatedIndexOfHelper(T * pArr, Var search, P fromIndex, P toIndex, ScriptContext * scriptContext)
  3596. {
  3597. Var element = nullptr;
  3598. bool isSearchTaggedInt = TaggedInt::Is(search);
  3599. bool doUndefinedSearch = includesAlgorithm && JavascriptOperators::GetTypeId(search) == TypeIds_Undefined;
  3600. Var trueValue = scriptContext->GetLibrary()->GetTrue();
  3601. Var falseValue = scriptContext->GetLibrary()->GetFalse();
  3602. //Consider: enumerating instead of walking all indices
  3603. for (P i = fromIndex; i < toIndex; i++)
  3604. {
  3605. if (!TryTemplatedGetItem(pArr, i, &element, scriptContext, !includesAlgorithm))
  3606. {
  3607. if (doUndefinedSearch)
  3608. {
  3609. return trueValue;
  3610. }
  3611. continue;
  3612. }
  3613. if (isSearchTaggedInt && TaggedInt::Is(element))
  3614. {
  3615. if (element == search)
  3616. {
  3617. return includesAlgorithm? trueValue : JavascriptNumber::ToVar(i, scriptContext);
  3618. }
  3619. continue;
  3620. }
  3621. if (includesAlgorithm)
  3622. {
  3623. //Array.prototype.includes
  3624. if (JavascriptConversion::SameValueZero(element, search))
  3625. {
  3626. return trueValue;
  3627. }
  3628. }
  3629. else
  3630. {
  3631. //Array.prototype.indexOf
  3632. if (JavascriptOperators::StrictEqual(element, search, scriptContext))
  3633. {
  3634. return JavascriptNumber::ToVar(i, scriptContext);
  3635. }
  3636. }
  3637. }
  3638. return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
  3639. }
  3640. int32 JavascriptArray::HeadSegmentIndexOfHelper(Var search, uint32 &fromIndex, uint32 toIndex, bool includesAlgorithm, ScriptContext * scriptContext)
  3641. {
  3642. Assert(Is(GetTypeId()) && !JavascriptNativeArray::Is(GetTypeId()));
  3643. if (!HasNoMissingValues() || fromIndex >= GetHead()->length)
  3644. {
  3645. return -1;
  3646. }
  3647. bool isSearchTaggedInt = TaggedInt::Is(search);
  3648. // We need to cast head segment to SparseArraySegment<Var> to have access to GetElement (onSparseArraySegment<T>). Because there are separate overloads of this
  3649. // virtual method on JavascriptNativeIntArray and JavascriptNativeFloatArray, we know this version of this method will only be called for true JavascriptArray, and not for
  3650. // either of the derived native arrays, so the elements of each segment used here must be Vars. Hence, the cast is safe.
  3651. SparseArraySegment<Var>* head = static_cast<SparseArraySegment<Var>*>(GetHead());
  3652. uint32 toIndexTrimmed = toIndex <= head->length ? toIndex : head->length;
  3653. for (uint32 i = fromIndex; i < toIndexTrimmed; i++)
  3654. {
  3655. Var element = head->GetElement(i);
  3656. if (isSearchTaggedInt && TaggedInt::Is(element))
  3657. {
  3658. if (search == element)
  3659. {
  3660. return i;
  3661. }
  3662. }
  3663. else if (includesAlgorithm && JavascriptConversion::SameValueZero(element, search))
  3664. {
  3665. //Array.prototype.includes
  3666. return i;
  3667. }
  3668. else if (JavascriptOperators::StrictEqual(element, search, scriptContext))
  3669. {
  3670. //Array.prototype.indexOf
  3671. return i;
  3672. }
  3673. }
  3674. // Element not found in the head segment. Keep looking only if the range of indices extends past
  3675. // the head segment.
  3676. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3677. return -1;
  3678. }
  3679. template<typename T>
  3680. bool AreAllBytesEqual(T value)
  3681. {
  3682. byte* bValue = (byte*)&value;
  3683. byte firstByte = *bValue++;
  3684. for (int i = 1; i < sizeof(T); ++i)
  3685. {
  3686. if (*bValue++ != firstByte)
  3687. {
  3688. return false;
  3689. }
  3690. }
  3691. return true;
  3692. }
  3693. template<>
  3694. void JavascriptArray::CopyValueToSegmentBuferNoCheck(Field(double)* buffer, uint32 length, double value)
  3695. {
  3696. if (JavascriptNumber::IsZero(value) && !JavascriptNumber::IsNegZero(value))
  3697. {
  3698. memset(buffer, 0, sizeof(double) * length);
  3699. }
  3700. else
  3701. {
  3702. for (uint32 i = 0; i < length; i++)
  3703. {
  3704. buffer[i] = value;
  3705. }
  3706. }
  3707. }
  3708. template<>
  3709. void JavascriptArray::CopyValueToSegmentBuferNoCheck(Field(int32)* buffer, uint32 length, int32 value)
  3710. {
  3711. if (value == 0 || AreAllBytesEqual(value))
  3712. {
  3713. memset(buffer, *(byte*)&value, sizeof(int32)* length);
  3714. }
  3715. else
  3716. {
  3717. for (uint32 i = 0; i < length; i++)
  3718. {
  3719. buffer[i] = value;
  3720. }
  3721. }
  3722. }
  3723. template<>
  3724. void JavascriptArray::CopyValueToSegmentBuferNoCheck(Field(Js::Var)* buffer, uint32 length, Js::Var value)
  3725. {
  3726. for (uint32 i = 0; i < length; i++)
  3727. {
  3728. buffer[i] = value;
  3729. }
  3730. }
  3731. int32 JavascriptNativeIntArray::HeadSegmentIndexOfHelper(Var search, uint32 &fromIndex, uint32 toIndex, bool includesAlgorithm, ScriptContext * scriptContext)
  3732. {
  3733. // We proceed largely in the same manner as in JavascriptArray's version of this method (see comments there for more information),
  3734. // 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:
  3735. // 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
  3736. // the search value is some other kind of Var, we can return -1 without ever iterating over the elements.
  3737. // 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.
  3738. // Instead we can use simple C++ equality (which in case of such values is equivalent to strict equality in JavaScript).
  3739. if (!HasNoMissingValues() || fromIndex >= GetHead()->length)
  3740. {
  3741. return -1;
  3742. }
  3743. bool isSearchTaggedInt = TaggedInt::Is(search);
  3744. if (!isSearchTaggedInt && !JavascriptNumber::Is_NoTaggedIntCheck(search))
  3745. {
  3746. // The value can't be in the array, but it could be in a prototype, and we can only guarantee that
  3747. // the head segment has no gaps.
  3748. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3749. return -1;
  3750. }
  3751. int32 searchAsInt32;
  3752. if (isSearchTaggedInt)
  3753. {
  3754. searchAsInt32 = TaggedInt::ToInt32(search);
  3755. }
  3756. else if (!JavascriptNumber::TryGetInt32Value<true>(JavascriptNumber::GetValue(search), &searchAsInt32))
  3757. {
  3758. // The value can't be in the array, but it could be in a prototype, and we can only guarantee that
  3759. // the head segment has no gaps.
  3760. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3761. return -1;
  3762. }
  3763. // We need to cast head segment to SparseArraySegment<int32> to have access to GetElement (onSparseArraySegment<T>). Because there are separate overloads of this
  3764. // virtual method on JavascriptNativeIntArray and JavascriptNativeFloatArray, we know this version of this method will only be called for true JavascriptNativeIntArray, and not for
  3765. // the other two, so the elements of each segment used here must be int32's. Hence, the cast is safe.
  3766. SparseArraySegment<int32> * head = static_cast<SparseArraySegment<int32>*>(GetHead());
  3767. uint32 toIndexTrimmed = toIndex <= head->length ? toIndex : head->length;
  3768. for (uint32 i = fromIndex; i < toIndexTrimmed; i++)
  3769. {
  3770. int32 element = head->GetElement(i);
  3771. if (searchAsInt32 == element)
  3772. {
  3773. return i;
  3774. }
  3775. }
  3776. // Element not found in the head segment. Keep looking only if the range of indices extends past
  3777. // the head segment.
  3778. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3779. return -1;
  3780. }
  3781. int32 JavascriptNativeFloatArray::HeadSegmentIndexOfHelper(Var search, uint32 &fromIndex, uint32 toIndex, bool includesAlgorithm, ScriptContext * scriptContext)
  3782. {
  3783. // We proceed largely in the same manner as in JavascriptArray's version of this method (see comments there for more information),
  3784. // except when we can further optimize thanks to the knowledge that all elements in the array are doubles. This allows for two additional optimizations:
  3785. // 1. Only tagged ints or JavascriptNumbers can be strict equal to some element in the array (all doubles). Thus, if
  3786. // the search value is some other kind of Var, we can return -1 without ever iterating over the elements.
  3787. // 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.
  3788. // Instead we can use simple C++ equality (which in case of such values is equivalent to strict equality in JavaScript).
  3789. if (!HasNoMissingValues() || fromIndex >= GetHead()->length)
  3790. {
  3791. return -1;
  3792. }
  3793. bool isSearchTaggedInt = TaggedInt::Is(search);
  3794. if (!isSearchTaggedInt && !JavascriptNumber::Is_NoTaggedIntCheck(search))
  3795. {
  3796. // The value can't be in the array, but it could be in a prototype, and we can only guarantee that
  3797. // the head segment has no gaps.
  3798. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3799. return -1;
  3800. }
  3801. double searchAsDouble = isSearchTaggedInt ? TaggedInt::ToDouble(search) : JavascriptNumber::GetValue(search);
  3802. // We need to cast head segment to SparseArraySegment<double> to have access to GetElement (SparseArraySegment). We know the
  3803. // segment's elements are all Vars so the cast is safe. It would have been more convenient here if JavascriptArray
  3804. // used SparseArraySegment<Var>, instead of SparseArraySegmentBase.
  3805. SparseArraySegment<double> * head = static_cast<SparseArraySegment<double>*>(GetHead());
  3806. uint32 toIndexTrimmed = toIndex <= head->length ? toIndex : head->length;
  3807. bool matchNaN = includesAlgorithm && JavascriptNumber::IsNan(searchAsDouble);
  3808. for (uint32 i = fromIndex; i < toIndexTrimmed; i++)
  3809. {
  3810. double element = head->GetElement(i);
  3811. if (element == searchAsDouble)
  3812. {
  3813. return i;
  3814. }
  3815. //NaN != NaN we expect to match for NaN in Array.prototype.includes algorithm
  3816. if (matchNaN && JavascriptNumber::IsNan(element))
  3817. {
  3818. return i;
  3819. }
  3820. }
  3821. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3822. return -1;
  3823. }
  3824. Var JavascriptArray::EntryJoin(RecyclableObject* function, CallInfo callInfo, ...)
  3825. {
  3826. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  3827. ARGUMENTS(args, callInfo);
  3828. ScriptContext* scriptContext = function->GetScriptContext();
  3829. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3830. Assert(!(callInfo.Flags & CallFlags_New));
  3831. if (args.Info.Count == 0)
  3832. {
  3833. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.join"));
  3834. }
  3835. SETOBJECT_FOR_MUTATION(jsReentLock, args[0]);
  3836. JavascriptString* separator;
  3837. if (args.Info.Count >= 2)
  3838. {
  3839. TypeId typeId = JavascriptOperators::GetTypeId(args[1]);
  3840. //ES5 15.4.4.5 If separator is undefined, let separator be the single-character String ",".
  3841. if (TypeIds_Undefined != typeId)
  3842. {
  3843. JS_REENTRANT(jsReentLock, separator = JavascriptConversion::ToString(args[1], scriptContext));
  3844. }
  3845. else
  3846. {
  3847. separator = scriptContext->GetLibrary()->GetCommaDisplayString();
  3848. }
  3849. }
  3850. else
  3851. {
  3852. separator = scriptContext->GetLibrary()->GetCommaDisplayString();
  3853. }
  3854. JS_REENTRANT_UNLOCK(jsReentLock, return JoinHelper(args[0], separator, scriptContext));
  3855. }
  3856. JavascriptString* JavascriptArray::JoinToString(Var value, ScriptContext* scriptContext)
  3857. {
  3858. TypeId typeId = JavascriptOperators::GetTypeId(value);
  3859. if (typeId <= TypeIds_UndefinedOrNull)
  3860. {
  3861. return scriptContext->GetLibrary()->GetEmptyString();
  3862. }
  3863. else
  3864. {
  3865. return JavascriptConversion::ToString(value, scriptContext);
  3866. }
  3867. }
  3868. JavascriptString* JavascriptArray::JoinHelper(Var thisArg, JavascriptString* separator, ScriptContext* scriptContext)
  3869. {
  3870. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3871. SETOBJECT_FOR_MUTATION(jsReentLock, thisArg);
  3872. JavascriptArray * arr = JavascriptOperators::TryFromVar<JavascriptArray>(thisArg);
  3873. JavascriptProxy * proxy = JavascriptOperators::TryFromVar<JavascriptProxy>(thisArg);
  3874. bool isArray = arr && (scriptContext == arr->GetScriptContext());
  3875. bool isProxy = proxy && (scriptContext == proxy->GetScriptContext());
  3876. Var target = NULL;
  3877. bool isTargetObjectPushed = false;
  3878. // if we are visiting a proxy object, track that we have visited the target object as well so the next time w
  3879. // call the join helper for the target of this proxy, we will return above.
  3880. if (isProxy)
  3881. {
  3882. Assert(proxy);
  3883. target = proxy->GetTarget();
  3884. if (target != nullptr)
  3885. {
  3886. // If we end up joining same array, instead of going in infinite loop, return the empty string
  3887. if (scriptContext->CheckObject(target))
  3888. {
  3889. return scriptContext->GetLibrary()->GetEmptyString();
  3890. }
  3891. else
  3892. {
  3893. scriptContext->PushObject(target);
  3894. isTargetObjectPushed = true;
  3895. }
  3896. }
  3897. }
  3898. // If we end up joining same array, instead of going in infinite loop, return the empty string
  3899. else if (scriptContext->CheckObject(thisArg))
  3900. {
  3901. return scriptContext->GetLibrary()->GetEmptyString();
  3902. }
  3903. if (!isTargetObjectPushed)
  3904. {
  3905. scriptContext->PushObject(thisArg);
  3906. }
  3907. JavascriptString* res = nullptr;
  3908. TryFinally([&]()
  3909. {
  3910. if (isArray)
  3911. {
  3912. #if ENABLE_COPYONACCESS_ARRAY
  3913. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray(thisArg);
  3914. #endif
  3915. switch (arr->GetTypeId())
  3916. {
  3917. case Js::TypeIds_Array:
  3918. JS_REENTRANT(jsReentLock, res = JoinArrayHelper(arr, separator, scriptContext));
  3919. break;
  3920. case Js::TypeIds_NativeIntArray:
  3921. JS_REENTRANT(jsReentLock, res = JoinArrayHelper(JavascriptNativeIntArray::UnsafeFromVar(arr), separator, scriptContext));
  3922. break;
  3923. case Js::TypeIds_NativeFloatArray:
  3924. JS_REENTRANT(jsReentLock, res = JoinArrayHelper(JavascriptNativeFloatArray::UnsafeFromVar(arr), separator, scriptContext));
  3925. break;
  3926. }
  3927. }
  3928. else if (RecyclableObject::Is(thisArg))
  3929. {
  3930. JS_REENTRANT(jsReentLock, res = JoinOtherHelper(RecyclableObject::FromVar(thisArg), separator, scriptContext));
  3931. }
  3932. else
  3933. {
  3934. JS_REENTRANT(jsReentLock, res = JoinOtherHelper(scriptContext->GetLibrary()->CreateNumberObject(thisArg), separator, scriptContext));
  3935. }
  3936. },
  3937. [&](bool/*hasException*/)
  3938. {
  3939. Var top = scriptContext->PopObject();
  3940. if (isProxy)
  3941. {
  3942. AssertMsg(top == target, "Unmatched operation stack");
  3943. }
  3944. else
  3945. {
  3946. AssertMsg(top == thisArg, "Unmatched operation stack");
  3947. }
  3948. });
  3949. if (res == nullptr)
  3950. {
  3951. res = scriptContext->GetLibrary()->GetEmptyString();
  3952. }
  3953. return res;
  3954. }
  3955. static const charcount_t Join_MaxEstimatedAppendCount = static_cast<charcount_t>((64 << 20) / sizeof(void *)); // 64 MB worth of pointers
  3956. template <typename T>
  3957. JavascriptString* JavascriptArray::JoinArrayHelper(T * arr, JavascriptString* separator, ScriptContext* scriptContext)
  3958. {
  3959. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3960. SETOBJECT_FOR_MUTATION(jsReentLock, arr);
  3961. Assert(VirtualTableInfo<T>::HasVirtualTable(arr) || VirtualTableInfo<CrossSiteObject<T>>::HasVirtualTable(arr));
  3962. const uint32 arrLength = arr->length;
  3963. switch(arrLength)
  3964. {
  3965. default:
  3966. {
  3967. CaseDefault:
  3968. bool hasSeparator = (separator->GetLength() != 0);
  3969. const charcount_t estimatedAppendCount =
  3970. min(
  3971. Join_MaxEstimatedAppendCount,
  3972. static_cast<charcount_t>(arrLength + (hasSeparator ? arrLength - 1 : 0)));
  3973. CompoundString *const cs =
  3974. CompoundString::NewWithPointerCapacity(estimatedAppendCount, scriptContext->GetLibrary());
  3975. Var item;
  3976. BOOL gotItem;
  3977. JS_REENTRANT(jsReentLock, gotItem = TemplatedGetItem(arr, 0u, &item, scriptContext));
  3978. if (gotItem)
  3979. {
  3980. JS_REENTRANT(jsReentLock, cs->Append(JavascriptArray::JoinToString(item, scriptContext)));
  3981. }
  3982. for (uint32 i = 1; i < arrLength; i++)
  3983. {
  3984. if (hasSeparator)
  3985. {
  3986. cs->Append(separator);
  3987. }
  3988. JS_REENTRANT(jsReentLock, gotItem = TryTemplatedGetItem(arr, i, &item, scriptContext));
  3989. if (gotItem)
  3990. {
  3991. JS_REENTRANT(jsReentLock, cs->Append(JavascriptArray::JoinToString(item, scriptContext)));
  3992. }
  3993. }
  3994. return cs;
  3995. }
  3996. case 2:
  3997. {
  3998. bool hasSeparator = (separator->GetLength() != 0);
  3999. BOOL gotItem;
  4000. if(hasSeparator)
  4001. {
  4002. goto CaseDefault;
  4003. }
  4004. JavascriptString *res = nullptr;
  4005. Var item;
  4006. JS_REENTRANT(jsReentLock, gotItem = TemplatedGetItem(arr, 0u, &item, scriptContext));
  4007. if (gotItem)
  4008. {
  4009. JS_REENTRANT(jsReentLock, res = JavascriptArray::JoinToString(item, scriptContext));
  4010. }
  4011. JS_REENTRANT(jsReentLock, gotItem = TryTemplatedGetItem(arr, 1u, &item, scriptContext));
  4012. if (gotItem)
  4013. {
  4014. JS_REENTRANT(jsReentLock, JavascriptString *const itemString = JavascriptArray::JoinToString(item, scriptContext));
  4015. return res ? ConcatString::New(res, itemString) : itemString;
  4016. }
  4017. if(res)
  4018. {
  4019. return res;
  4020. }
  4021. goto Case0;
  4022. }
  4023. case 1:
  4024. {
  4025. Var item;
  4026. BOOL gotItem;
  4027. JS_REENTRANT(jsReentLock, gotItem = TemplatedGetItem(arr, 0u, &item, scriptContext));
  4028. if (gotItem)
  4029. {
  4030. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::JoinToString(item, scriptContext));
  4031. }
  4032. // fall through
  4033. }
  4034. case 0:
  4035. Case0:
  4036. return scriptContext->GetLibrary()->GetEmptyString();
  4037. }
  4038. }
  4039. JavascriptString* JavascriptArray::JoinOtherHelper(RecyclableObject* object, JavascriptString* separator, ScriptContext* scriptContext)
  4040. {
  4041. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4042. SETOBJECT_FOR_MUTATION(jsReentLock, object);
  4043. // In ES6-mode, we always load the length property from the object instead of using the internal slot.
  4044. // Even for arrays, this is now observable via proxies.
  4045. // If source object is not an array, we fall back to this behavior anyway.
  4046. JS_REENTRANT(jsReentLock,
  4047. int64 cSrcLength = (int64)OP_GetLength(object, scriptContext));
  4048. switch (cSrcLength)
  4049. {
  4050. default:
  4051. {
  4052. CaseDefault:
  4053. bool hasSeparator = (separator->GetLength() != 0);
  4054. BOOL gotItem;
  4055. const charcount_t estimatedAppendCount =
  4056. min(
  4057. Join_MaxEstimatedAppendCount,
  4058. static_cast<charcount_t>(cSrcLength + (hasSeparator ? cSrcLength - 1 : 0)));
  4059. CompoundString *const cs =
  4060. CompoundString::NewWithPointerCapacity(estimatedAppendCount, scriptContext->GetLibrary());
  4061. Var value;
  4062. JS_REENTRANT(jsReentLock, gotItem = JavascriptOperators::GetItem(object, 0u, &value, scriptContext));
  4063. if (gotItem)
  4064. {
  4065. JS_REENTRANT(jsReentLock, cs->Append(JavascriptArray::JoinToString(value, scriptContext)));
  4066. }
  4067. for (uint32 i = 1; i < cSrcLength; i++)
  4068. {
  4069. if (hasSeparator)
  4070. {
  4071. cs->Append(separator);
  4072. }
  4073. JS_REENTRANT(jsReentLock, gotItem = JavascriptOperators::GetItem(object, i, &value, scriptContext));
  4074. if (gotItem)
  4075. {
  4076. JS_REENTRANT(jsReentLock, cs->Append(JavascriptArray::JoinToString(value, scriptContext)));
  4077. }
  4078. }
  4079. return cs;
  4080. }
  4081. case 2:
  4082. {
  4083. bool hasSeparator = (separator->GetLength() != 0);
  4084. BOOL gotItem;
  4085. if(hasSeparator)
  4086. {
  4087. goto CaseDefault;
  4088. }
  4089. JavascriptString *res = nullptr;
  4090. Var value;
  4091. JS_REENTRANT(jsReentLock, gotItem = JavascriptOperators::GetItem(object, 0u, &value, scriptContext));
  4092. if (gotItem)
  4093. {
  4094. JS_REENTRANT(jsReentLock, res = JavascriptArray::JoinToString(value, scriptContext));
  4095. }
  4096. JS_REENTRANT(jsReentLock, gotItem = JavascriptOperators::GetItem(object, 1u, &value, scriptContext));
  4097. if (gotItem)
  4098. {
  4099. JS_REENTRANT(jsReentLock, JavascriptString *const valueString = JavascriptArray::JoinToString(value, scriptContext));
  4100. return res ? ConcatString::New(res, valueString) : valueString;
  4101. }
  4102. if(res)
  4103. {
  4104. return res;
  4105. }
  4106. goto Case0;
  4107. }
  4108. case 1:
  4109. {
  4110. Var value;
  4111. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(object, 0u, &value, scriptContext));
  4112. if (gotItem)
  4113. {
  4114. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::JoinToString(value, scriptContext));
  4115. }
  4116. // fall through
  4117. }
  4118. case 0:
  4119. Case0:
  4120. return scriptContext->GetLibrary()->GetEmptyString();
  4121. }
  4122. }
  4123. Var JavascriptArray::EntryLastIndexOf(RecyclableObject* function, CallInfo callInfo, ...)
  4124. {
  4125. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  4126. ARGUMENTS(args, callInfo);
  4127. ScriptContext* scriptContext = function->GetScriptContext();
  4128. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4129. SETOBJECT_FOR_MUTATION(jsReentLock, args[0]);
  4130. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_lastIndexOf);
  4131. Assert(!(callInfo.Flags & CallFlags_New));
  4132. int64 length;
  4133. JavascriptArray * pArr = nullptr;
  4134. RecyclableObject* obj = nullptr;
  4135. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.lastIndexOf"), &pArr, &obj, &length));
  4136. Var search;
  4137. int64 fromIndex;
  4138. JS_REENTRANT(jsReentLock,
  4139. BOOL gotParam = GetParamForLastIndexOf(length, args, search, fromIndex, scriptContext));
  4140. if (!gotParam)
  4141. {
  4142. return TaggedInt::ToVarUnchecked(-1);
  4143. }
  4144. // Side effects (such as defining a property in a ToPrimitive call) during evaluation of fromIndex argument may convert the array to an ES5 array.
  4145. if (pArr && !JavascriptArray::Is(obj))
  4146. {
  4147. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  4148. pArr = nullptr;
  4149. }
  4150. if (pArr)
  4151. {
  4152. switch (pArr->GetTypeId())
  4153. {
  4154. case Js::TypeIds_Array:
  4155. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(pArr, search, fromIndex, scriptContext));
  4156. case Js::TypeIds_NativeIntArray:
  4157. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(JavascriptNativeIntArray::UnsafeFromVar(pArr), search, fromIndex, scriptContext));
  4158. case Js::TypeIds_NativeFloatArray:
  4159. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(JavascriptNativeFloatArray::UnsafeFromVar(pArr), search, fromIndex, scriptContext));
  4160. default:
  4161. AssertMsg(FALSE, "invalid array typeid");
  4162. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(pArr, search, fromIndex, scriptContext));
  4163. }
  4164. }
  4165. // source object is not a JavascriptArray but source could be a TypedArray
  4166. TypedArrayBase * typedArrayObj = JavascriptOperators::TryFromVar<Js::TypedArrayBase>(obj);
  4167. if (typedArrayObj)
  4168. {
  4169. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(typedArrayObj, search, fromIndex, scriptContext));
  4170. }
  4171. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(obj, search, fromIndex, scriptContext));
  4172. }
  4173. // Array.prototype.lastIndexOf as described in ES6.0 (draft 22) Section 22.1.3.14
  4174. BOOL JavascriptArray::GetParamForLastIndexOf(int64 length, Arguments const & args, Var& search, int64& fromIndex, ScriptContext * scriptContext)
  4175. {
  4176. if (length == 0)
  4177. {
  4178. return false;
  4179. }
  4180. if (args.Info.Count > 2)
  4181. {
  4182. fromIndex = GetFromLastIndex(args[2], length, scriptContext);
  4183. if (fromIndex >= length)
  4184. {
  4185. return false;
  4186. }
  4187. search = args[1];
  4188. }
  4189. else
  4190. {
  4191. search = args.Info.Count > 1 ? args[1] : scriptContext->GetLibrary()->GetUndefined();
  4192. fromIndex = length - 1;
  4193. }
  4194. return true;
  4195. }
  4196. template <typename T>
  4197. Var JavascriptArray::LastIndexOfHelper(T* pArr, Var search, int64 fromIndex, ScriptContext * scriptContext)
  4198. {
  4199. Var element = nullptr;
  4200. bool isSearchTaggedInt = TaggedInt::Is(search);
  4201. // First handle the indices > 2^32
  4202. while (fromIndex >= MaxArrayLength)
  4203. {
  4204. Var index = JavascriptNumber::ToVar(fromIndex, scriptContext);
  4205. if (JavascriptOperators::OP_HasItem(pArr, index, scriptContext))
  4206. {
  4207. element = JavascriptOperators::OP_GetElementI(pArr, index, scriptContext);
  4208. if (isSearchTaggedInt && TaggedInt::Is(element))
  4209. {
  4210. if (element == search)
  4211. {
  4212. return index;
  4213. }
  4214. fromIndex--;
  4215. continue;
  4216. }
  4217. if (JavascriptOperators::StrictEqual(element, search, scriptContext))
  4218. {
  4219. return index;
  4220. }
  4221. }
  4222. fromIndex--;
  4223. }
  4224. Assert(fromIndex < MaxArrayLength);
  4225. // fromIndex now has to be < MaxArrayLength so casting to uint32 is safe
  4226. uint32 end = static_cast<uint32>(fromIndex);
  4227. for (uint32 i = 0; i <= end; i++)
  4228. {
  4229. uint32 index = end - i;
  4230. if (!TryTemplatedGetItem(pArr, index, &element, scriptContext))
  4231. {
  4232. continue;
  4233. }
  4234. if (isSearchTaggedInt && TaggedInt::Is(element))
  4235. {
  4236. if (element == search)
  4237. {
  4238. return JavascriptNumber::ToVar(index, scriptContext);
  4239. }
  4240. continue;
  4241. }
  4242. if (JavascriptOperators::StrictEqual(element, search, scriptContext))
  4243. {
  4244. return JavascriptNumber::ToVar(index, scriptContext);
  4245. }
  4246. }
  4247. return TaggedInt::ToVarUnchecked(-1);
  4248. }
  4249. /*
  4250. * PopWithNoDst
  4251. * - For pop calls that do not return a value, we only need to decrement the length of the array.
  4252. */
  4253. void JavascriptNativeArray::PopWithNoDst(Var nativeArray)
  4254. {
  4255. Assert(JavascriptNativeArray::Is(nativeArray));
  4256. JavascriptArray * arr = JavascriptArray::FromVar(nativeArray);
  4257. // we will bailout on length 0
  4258. Assert(arr->GetLength() != 0);
  4259. uint32 index = arr->GetLength() - 1;
  4260. arr->SetLength(index);
  4261. }
  4262. /*
  4263. * JavascriptNativeIntArray::Pop
  4264. * - Returns int32 value from the array.
  4265. * - Returns missing item when the element is not available in the array object.
  4266. * - It doesn't walk up the prototype chain.
  4267. * - Length is decremented only if it pops an int32 element, in all other cases - we bail out from the jitted code.
  4268. * - This api cannot cause any implicit call and hence do not need implicit call bailout test around this api
  4269. */
  4270. int32 JavascriptNativeIntArray::Pop(ScriptContext * scriptContext, Var object)
  4271. {
  4272. Assert(JavascriptNativeIntArray::Is(object));
  4273. JavascriptNativeIntArray * arr = JavascriptNativeIntArray::FromVar(object);
  4274. Assert(arr->GetLength() != 0);
  4275. uint32 index = arr->length - 1;
  4276. int32 element = Js::JavascriptOperators::OP_GetNativeIntElementI_UInt32(object, index, scriptContext);
  4277. //If it is a missing item, then don't update the length - Pre-op Bail out will happen.
  4278. if(!SparseArraySegment<int32>::IsMissingItem(&element))
  4279. {
  4280. arr->SetLength(index);
  4281. }
  4282. return element;
  4283. }
  4284. /*
  4285. * JavascriptNativeFloatArray::Pop
  4286. * - Returns double value from the array.
  4287. * - Returns missing item when the element is not available in the array object.
  4288. * - It doesn't walk up the prototype chain.
  4289. * - Length is decremented only if it pops a double element, in all other cases - we bail out from the jitted code.
  4290. * - This api cannot cause any implicit call and hence do not need implicit call bailout test around this api
  4291. */
  4292. double JavascriptNativeFloatArray::Pop(ScriptContext * scriptContext, Var object)
  4293. {
  4294. Assert(JavascriptNativeFloatArray::Is(object));
  4295. JavascriptNativeFloatArray * arr = JavascriptNativeFloatArray::FromVar(object);
  4296. Assert(arr->GetLength() != 0);
  4297. uint32 index = arr->length - 1;
  4298. double element = Js::JavascriptOperators::OP_GetNativeFloatElementI_UInt32(object, index, scriptContext);
  4299. // If it is a missing item then don't update the length - Pre-op Bail out will happen.
  4300. if(!SparseArraySegment<double>::IsMissingItem(&element))
  4301. {
  4302. arr->SetLength(index);
  4303. }
  4304. return element;
  4305. }
  4306. /*
  4307. * JavascriptArray::Pop
  4308. * - Calls the generic Pop API, which can find elements from the prototype chain, when it is not available in the array object.
  4309. * - This API may cause implicit calls. Handles Array and non-array objects
  4310. */
  4311. Var JavascriptArray::Pop(ScriptContext * scriptContext, Var object)
  4312. {
  4313. if (JavascriptArray::Is(object))
  4314. {
  4315. return EntryPopJavascriptArray(scriptContext, JavascriptArray::FromVar(object));
  4316. }
  4317. else
  4318. {
  4319. return EntryPopNonJavascriptArray(scriptContext, object);
  4320. }
  4321. }
  4322. Var JavascriptArray::EntryPopJavascriptArray(ScriptContext * scriptContext, JavascriptArray* arr)
  4323. {
  4324. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4325. SETOBJECT_FOR_MUTATION(jsReentLock, arr);
  4326. uint32 length = arr->length;
  4327. if (length == 0)
  4328. {
  4329. // If length is 0, return 'undefined'
  4330. return scriptContext->GetLibrary()->GetUndefined();
  4331. }
  4332. uint32 index = length - 1;
  4333. Var element;
  4334. JS_REENTRANT(jsReentLock, BOOL gotItem = arr->DirectGetItemAtFull(index, &element));
  4335. if (!gotItem)
  4336. {
  4337. element = scriptContext->GetLibrary()->GetUndefined();
  4338. }
  4339. else
  4340. {
  4341. element = CrossSite::MarshalVar(scriptContext, element, arr->GetScriptContext());
  4342. }
  4343. arr->SetLength(index); // SetLength will clear element at index
  4344. #ifdef VALIDATE_ARRAY
  4345. arr->ValidateArray();
  4346. #endif
  4347. return element;
  4348. }
  4349. Var JavascriptArray::EntryPopNonJavascriptArray(ScriptContext * scriptContext, Var object)
  4350. {
  4351. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4352. RecyclableObject* dynamicObject = nullptr;
  4353. if (FALSE == JavascriptConversion::ToObject(object, scriptContext, &dynamicObject))
  4354. {
  4355. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.pop"));
  4356. }
  4357. SETOBJECT_FOR_MUTATION(jsReentLock, dynamicObject);
  4358. JS_REENTRANT(jsReentLock, BigIndex length = OP_GetLength(dynamicObject, scriptContext));
  4359. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.pop"));
  4360. if (length == 0u)
  4361. {
  4362. // Set length = 0
  4363. JS_REENTRANT(jsReentLock,
  4364. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, TaggedInt::ToVarUnchecked(0), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  4365. return scriptContext->GetLibrary()->GetUndefined();
  4366. }
  4367. BigIndex index = length;
  4368. --index;
  4369. Var element;
  4370. if (index.IsSmallIndex())
  4371. {
  4372. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(dynamicObject, index.GetSmallIndex(), &element, scriptContext));
  4373. if (!gotItem)
  4374. {
  4375. element = scriptContext->GetLibrary()->GetUndefined();
  4376. }
  4377. JS_REENTRANT(jsReentLock,
  4378. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, index.GetSmallIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig)),
  4379. // Set the new length
  4380. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(index.GetSmallIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  4381. }
  4382. else
  4383. {
  4384. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(dynamicObject, index.GetBigIndex(), &element, scriptContext));
  4385. if (!gotItem)
  4386. {
  4387. element = scriptContext->GetLibrary()->GetUndefined();
  4388. }
  4389. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, index.GetBigIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig)),
  4390. // Set the new length
  4391. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(index.GetBigIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  4392. }
  4393. return element;
  4394. }
  4395. Var JavascriptArray::EntryPop(RecyclableObject* function, CallInfo callInfo, ...)
  4396. {
  4397. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  4398. ARGUMENTS(args, callInfo);
  4399. ScriptContext* scriptContext = function->GetScriptContext();
  4400. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4401. SETOBJECT_FOR_MUTATION(jsReentLock, args[0]);
  4402. Assert(!(callInfo.Flags & CallFlags_New));
  4403. if (args.Info.Count == 0)
  4404. {
  4405. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.pop"));
  4406. }
  4407. if (JavascriptArray::Is(args[0]))
  4408. {
  4409. JS_REENTRANT_UNLOCK(jsReentLock, return EntryPopJavascriptArray(scriptContext, JavascriptArray::FromVar(args.Values[0])));
  4410. }
  4411. else
  4412. {
  4413. JS_REENTRANT_UNLOCK(jsReentLock, return EntryPopNonJavascriptArray(scriptContext, args.Values[0]));
  4414. }
  4415. }
  4416. /*
  4417. * JavascriptNativeIntArray::Push
  4418. * Pushes Int element in a native Int Array.
  4419. * We call the generic Push, if the array is not native Int or we have a really big array.
  4420. */
  4421. Var JavascriptNativeIntArray::Push(ScriptContext * scriptContext, Var array, int value)
  4422. {
  4423. // Handle non crossSite native int arrays here length within MaxArrayLength.
  4424. // JavascriptArray::Push will handle other cases.
  4425. if (JavascriptNativeIntArray::IsNonCrossSite(array))
  4426. {
  4427. JavascriptNativeIntArray * nativeIntArray = JavascriptNativeIntArray::UnsafeFromVar(array);
  4428. Assert(!nativeIntArray->IsCrossSiteObject());
  4429. uint32 n = nativeIntArray->length;
  4430. if(n < JavascriptArray::MaxArrayLength)
  4431. {
  4432. nativeIntArray->SetItem(n, value);
  4433. n++;
  4434. AssertMsg(n == nativeIntArray->length, "Wrong update to the length of the native Int array");
  4435. return JavascriptNumber::ToVar(n, scriptContext);
  4436. }
  4437. }
  4438. return JavascriptArray::Push(scriptContext, array, JavascriptNumber::ToVar(value, scriptContext));
  4439. }
  4440. /*
  4441. * JavascriptNativeFloatArray::Push
  4442. * Pushes Float element in a native Int Array.
  4443. * We call the generic Push, if the array is not native Float or we have a really big array.
  4444. */
  4445. Var JavascriptNativeFloatArray::Push(ScriptContext * scriptContext, Var * array, double value)
  4446. {
  4447. // Handle non crossSite native int arrays here length within MaxArrayLength.
  4448. // JavascriptArray::Push will handle other cases.
  4449. if(JavascriptNativeFloatArray::IsNonCrossSite(array))
  4450. {
  4451. JavascriptNativeFloatArray * nativeFloatArray = JavascriptNativeFloatArray::UnsafeFromVar(array);
  4452. Assert(!nativeFloatArray->IsCrossSiteObject());
  4453. uint32 n = nativeFloatArray->length;
  4454. if(n < JavascriptArray::MaxArrayLength)
  4455. {
  4456. nativeFloatArray->SetItem(n, value);
  4457. n++;
  4458. AssertMsg(n == nativeFloatArray->length, "Wrong update to the length of the native Float array");
  4459. return JavascriptNumber::ToVar(n, scriptContext);
  4460. }
  4461. }
  4462. return JavascriptArray::Push(scriptContext, array, JavascriptNumber::ToVarNoCheck(value, scriptContext));
  4463. }
  4464. /*
  4465. * JavascriptArray::Push
  4466. * Pushes Var element in a Var Array.
  4467. */
  4468. Var JavascriptArray::Push(ScriptContext * scriptContext, Var object, Var value)
  4469. {
  4470. Var args[2];
  4471. args[0] = object;
  4472. args[1] = value;
  4473. if (JavascriptArray::Is(object))
  4474. {
  4475. return EntryPushJavascriptArray(scriptContext, args, 2);
  4476. }
  4477. else
  4478. {
  4479. return EntryPushNonJavascriptArray(scriptContext, args, 2);
  4480. }
  4481. }
  4482. /*
  4483. * EntryPushNonJavascriptArray
  4484. * - Handles Entry push calls, when Objects are not javascript arrays
  4485. */
  4486. Var JavascriptArray::EntryPushNonJavascriptArray(ScriptContext * scriptContext, Var * args, uint argCount)
  4487. {
  4488. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4489. RecyclableObject* obj = nullptr;
  4490. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  4491. {
  4492. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.push"));
  4493. }
  4494. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  4495. JS_REENTRANT_UNLOCK(jsReentLock, Var length = JavascriptOperators::OP_GetLength(obj, scriptContext));
  4496. if(JavascriptOperators::GetTypeId(length) == TypeIds_Undefined && scriptContext->GetThreadContext()->IsDisableImplicitCall() &&
  4497. scriptContext->GetThreadContext()->GetImplicitCallFlags() != Js::ImplicitCall_None)
  4498. {
  4499. return length;
  4500. }
  4501. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.push"));
  4502. BigIndex n;
  4503. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  4504. {
  4505. n = (uint64) JavascriptConversion::ToLength(length, scriptContext);
  4506. }
  4507. else
  4508. {
  4509. n = JavascriptConversion::ToUInt32(length, scriptContext);
  4510. }
  4511. // First handle "small" indices.
  4512. uint index;
  4513. for (index=1; index < argCount && n < JavascriptArray::MaxArrayLength; ++index, ++n)
  4514. {
  4515. JS_REENTRANT(jsReentLock,
  4516. BOOL setItem = JavascriptOperators::SetItem(obj, obj, n.GetSmallIndex(), args[index], scriptContext, PropertyOperation_ThrowIfNotExtensible));
  4517. if (h.IsThrowTypeError(setItem))
  4518. {
  4519. if (scriptContext->GetThreadContext()->RecordImplicitException())
  4520. {
  4521. h.ThrowTypeErrorOnFailure();
  4522. }
  4523. else
  4524. {
  4525. return nullptr;
  4526. }
  4527. }
  4528. }
  4529. // Use BigIndex if we need to push indices >= MaxArrayLength
  4530. if (index < argCount)
  4531. {
  4532. BigIndex big = n;
  4533. for (; index < argCount; ++index, ++big)
  4534. {
  4535. JS_REENTRANT(jsReentLock, BOOL setItem = big.SetItem(obj, args[index], PropertyOperation_ThrowIfNotExtensible));
  4536. if (h.IsThrowTypeError(setItem))
  4537. {
  4538. if(scriptContext->GetThreadContext()->RecordImplicitException())
  4539. {
  4540. h.ThrowTypeErrorOnFailure();
  4541. }
  4542. else
  4543. {
  4544. return nullptr;
  4545. }
  4546. }
  4547. }
  4548. // Set the new length; for objects it is all right for this to be >= MaxArrayLength
  4549. JS_REENTRANT(jsReentLock,
  4550. BOOL setLength = JavascriptOperators::SetProperty(obj, obj, PropertyIds::length, big.ToNumber(scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  4551. if (h.IsThrowTypeError(setLength))
  4552. {
  4553. if(scriptContext->GetThreadContext()->RecordImplicitException())
  4554. {
  4555. h.ThrowTypeErrorOnFailure();
  4556. }
  4557. else
  4558. {
  4559. return nullptr;
  4560. }
  4561. }
  4562. return big.ToNumber(scriptContext);
  4563. }
  4564. else
  4565. {
  4566. // Set the new length
  4567. Var lengthAsNUmberVar = JavascriptNumber::ToVar(n.IsSmallIndex() ? n.GetSmallIndex() : n.GetBigIndex(), scriptContext);
  4568. JS_REENTRANT(jsReentLock,
  4569. BOOL setLength = JavascriptOperators::SetProperty(obj, obj, PropertyIds::length, lengthAsNUmberVar, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  4570. if (h.IsThrowTypeError(setLength))
  4571. {
  4572. if(scriptContext->GetThreadContext()->RecordImplicitException())
  4573. {
  4574. h.ThrowTypeErrorOnFailure();
  4575. }
  4576. else
  4577. {
  4578. return nullptr;
  4579. }
  4580. }
  4581. return lengthAsNUmberVar;
  4582. }
  4583. }
  4584. /*
  4585. * JavascriptArray::EntryPushJavascriptArray
  4586. * Pushes Var element in a Var Array.
  4587. * Returns the length of the array.
  4588. */
  4589. Var JavascriptArray::EntryPushJavascriptArray(ScriptContext * scriptContext, Var * args, uint argCount)
  4590. {
  4591. JavascriptArray * arr = JavascriptArray::FromAnyArray(args[0]);
  4592. uint n = arr->length;
  4593. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.push"));
  4594. // Fast Path for one push for small indexes
  4595. if (argCount == 2 && n < JavascriptArray::MaxArrayLength)
  4596. {
  4597. // Set Item is overridden by CrossSiteObject, so no need to check for IsCrossSiteObject()
  4598. h.ThrowTypeErrorOnFailure(arr->SetItem(n, args[1], PropertyOperation_None));
  4599. return JavascriptNumber::ToVar(n + 1, scriptContext);
  4600. }
  4601. // Fast Path for multiple push for small indexes
  4602. if (JavascriptArray::MaxArrayLength - argCount + 1 > n && JavascriptArray::IsVarArray(arr) && scriptContext == arr->GetScriptContext())
  4603. {
  4604. uint index;
  4605. for (index = 1; index < argCount; ++index, ++n)
  4606. {
  4607. Assert(n != JavascriptArray::MaxArrayLength);
  4608. // Set Item is overridden by CrossSiteObject, so no need to check for IsCrossSiteObject()
  4609. arr->JavascriptArray::DirectSetItemAt(n, args[index]);
  4610. }
  4611. return JavascriptNumber::ToVar(n, scriptContext);
  4612. }
  4613. return EntryPushJavascriptArrayNoFastPath(scriptContext, args, argCount);
  4614. }
  4615. Var JavascriptArray::EntryPushJavascriptArrayNoFastPath(ScriptContext * scriptContext, Var * args, uint argCount)
  4616. {
  4617. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4618. JavascriptArray * arr = JavascriptArray::FromAnyArray(args[0]);
  4619. SETOBJECT_FOR_MUTATION(jsReentLock, arr);
  4620. uint n = arr->length;
  4621. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.push"));
  4622. // First handle "small" indices.
  4623. uint index;
  4624. for (index = 1; index < argCount && n < JavascriptArray::MaxArrayLength; ++index, ++n)
  4625. {
  4626. // Set Item is overridden by CrossSiteObject, so no need to check for IsCrossSiteObject()
  4627. h.ThrowTypeErrorOnFailure(arr->SetItem(n, args[index], PropertyOperation_None));
  4628. }
  4629. // Use BigIndex if we need to push indices >= MaxArrayLength
  4630. if (index < argCount)
  4631. {
  4632. // Not supporting native array with BigIndex.
  4633. arr = EnsureNonNativeArray(arr);
  4634. Assert(n == JavascriptArray::MaxArrayLength);
  4635. for (BigIndex big = n; index < argCount; ++index, ++big)
  4636. {
  4637. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(big.SetItem(arr, args[index])));
  4638. }
  4639. #ifdef VALIDATE_ARRAY
  4640. arr->ValidateArray();
  4641. #endif
  4642. // This is where we should set the length, but for arrays it cannot be >= MaxArrayLength
  4643. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  4644. }
  4645. #ifdef VALIDATE_ARRAY
  4646. arr->ValidateArray();
  4647. #endif
  4648. return JavascriptNumber::ToVar(n, scriptContext);
  4649. }
  4650. /*
  4651. * JavascriptArray::EntryPush
  4652. * Handles Push calls(Script Function)
  4653. */
  4654. Var JavascriptArray::EntryPush(RecyclableObject* function, CallInfo callInfo, ...)
  4655. {
  4656. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  4657. ARGUMENTS(args, callInfo);
  4658. ScriptContext* scriptContext = function->GetScriptContext();
  4659. Assert(!(callInfo.Flags & CallFlags_New));
  4660. if (args.Info.Count == 0)
  4661. {
  4662. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.push"));
  4663. }
  4664. if (JavascriptArray::Is(args[0]))
  4665. {
  4666. return EntryPushJavascriptArray(scriptContext, args.Values, args.Info.Count);
  4667. }
  4668. else
  4669. {
  4670. return EntryPushNonJavascriptArray(scriptContext, args.Values, args.Info.Count);
  4671. }
  4672. }
  4673. template <typename T>
  4674. void JavascriptArray::CopyHeadIfInlinedHeadSegment(JavascriptArray *array, Recycler *recycler)
  4675. {
  4676. if (JavascriptArray::IsInlineSegment(array->head, array))
  4677. {
  4678. AnalysisAssert(array->head);
  4679. SparseArraySegment<T>* newHeadSeg = array->ReallocNonLeafSegment((SparseArraySegment<T>*)PointerValue(array->head), array->head->next);
  4680. array->head = newHeadSeg;
  4681. }
  4682. }
  4683. template <typename T>
  4684. void JavascriptArray::ReallocateNonLeafLastSegmentIfLeaf(JavascriptArray * arr, Recycler * recycler)
  4685. {
  4686. 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.
  4687. // TODO: Consider utilizing lastUsedSegment once we fix CopyHeadIfInlinedHeadSegment in that respect.
  4688. SparseArraySegmentBase *lastSeg = nullptr;
  4689. SparseArraySegmentBase *seg = arr->head;
  4690. while (seg)
  4691. {
  4692. lastSeg = seg;
  4693. seg = seg->next;
  4694. }
  4695. if (SparseArraySegmentBase::IsLeafSegment(lastSeg, recycler))
  4696. {
  4697. AnalysisAssert(lastSeg);
  4698. arr->ReallocNonLeafSegment((SparseArraySegment<T>*)lastSeg, lastSeg->next, true /*forceNonLeaf*/);
  4699. }
  4700. }
  4701. Var JavascriptArray::EntryReverse(RecyclableObject* function, CallInfo callInfo, ...)
  4702. {
  4703. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  4704. ARGUMENTS(args, callInfo);
  4705. ScriptContext* scriptContext = function->GetScriptContext();
  4706. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4707. Assert(!(callInfo.Flags & CallFlags_New));
  4708. if (args.Info.Count == 0)
  4709. {
  4710. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reverse"));
  4711. }
  4712. BigIndex length = 0u;
  4713. JavascriptArray* pArr = nullptr;
  4714. RecyclableObject* obj = nullptr;
  4715. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.reverse"), &pArr, &obj, &length));
  4716. if (length.IsSmallIndex())
  4717. {
  4718. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReverseHelper(pArr, nullptr, obj, length.GetSmallIndex(), scriptContext));
  4719. }
  4720. 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
  4721. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReverseHelper(pArr, nullptr, obj, length.GetBigIndex(), scriptContext));
  4722. }
  4723. bool JavascriptArray::HasAnyES5ArrayInPrototypeChain(JavascriptArray *arr, bool forceCheckProtoChain)
  4724. {
  4725. Assert(arr != nullptr);
  4726. #if ENABLE_COPYONACCESS_ARRAY
  4727. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(arr);
  4728. #endif
  4729. bool hasAnyES5Array = false;
  4730. // If there is no gap (unless forced) we are not filling from the prototype - so no point checking for ES5Array.
  4731. if (forceCheckProtoChain || arr->IsFillFromPrototypes())
  4732. {
  4733. RecyclableObject* prototype = arr->GetPrototype();
  4734. while (!JavascriptOperators::IsNull(prototype))
  4735. {
  4736. RecyclableObject* protoObj = prototype;
  4737. if (!(DynamicObject::IsAnyArray(protoObj) || JavascriptOperators::IsObject(protoObj))
  4738. || JavascriptProxy::Is(protoObj)
  4739. || protoObj->IsExternal())
  4740. {
  4741. hasAnyES5Array = true;
  4742. break;
  4743. }
  4744. if (DynamicObject::IsAnyArray(protoObj))
  4745. {
  4746. if (ES5Array::Is(protoObj))
  4747. {
  4748. hasAnyES5Array = true;
  4749. break;
  4750. }
  4751. }
  4752. else if (DynamicType::Is(protoObj->GetTypeId()))
  4753. {
  4754. DynamicObject* dynobj = DynamicObject::UnsafeFromVar(protoObj);
  4755. ArrayObject* objectArray = dynobj->GetObjectArray();
  4756. if (objectArray != nullptr && ES5Array::Is(objectArray))
  4757. {
  4758. hasAnyES5Array = true;
  4759. break;
  4760. }
  4761. }
  4762. prototype = prototype->GetPrototype();
  4763. }
  4764. }
  4765. return hasAnyES5Array;
  4766. }
  4767. // Array.prototype.reverse as described in ES6.0 (draft 22) Section 22.1.3.20
  4768. template <typename T>
  4769. Var JavascriptArray::ReverseHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, ScriptContext* scriptContext)
  4770. {
  4771. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4772. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  4773. T middle = length / 2;
  4774. Var lowerValue = nullptr, upperValue = nullptr;
  4775. T lowerExists, upperExists;
  4776. const char16* methodName;
  4777. bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
  4778. if (isTypedArrayEntryPoint)
  4779. {
  4780. methodName = _u("[TypedArray].prototype.reverse");
  4781. }
  4782. else
  4783. {
  4784. methodName = _u("Array.prototype.reverse");
  4785. }
  4786. // If we came from Array.prototype.map and source object is not a JavascriptArray, source could be a TypedArray
  4787. if (!isTypedArrayEntryPoint && pArr == nullptr && TypedArrayBase::Is(obj))
  4788. {
  4789. typedArrayBase = TypedArrayBase::UnsafeFromVar(obj);
  4790. }
  4791. ThrowTypeErrorOnFailureHelper h(scriptContext, methodName);
  4792. bool useNoSideEffectReverse = pArr != nullptr && !HasAnyES5ArrayInPrototypeChain(pArr);
  4793. if (useNoSideEffectReverse)
  4794. {
  4795. Recycler * recycler = scriptContext->GetRecycler();
  4796. if (length <= 1)
  4797. {
  4798. return pArr;
  4799. }
  4800. if (pArr->IsFillFromPrototypes())
  4801. {
  4802. // For odd-length arrays, the middle element is unchanged,
  4803. // so we cannot fill it from the prototypes.
  4804. if (length % 2 == 0)
  4805. {
  4806. pArr->FillFromPrototypes(0, (uint32)length);
  4807. }
  4808. else
  4809. {
  4810. middle = length / 2;
  4811. pArr->FillFromPrototypes(0, (uint32)middle);
  4812. pArr->FillFromPrototypes(1 + (uint32)middle, (uint32)length);
  4813. }
  4814. }
  4815. // As we have already established that the FillFromPrototype should not change the bound of the array.
  4816. if (length != (T)pArr->length)
  4817. {
  4818. Js::Throw::FatalInternalError();
  4819. }
  4820. if (pArr->HasNoMissingValues() && pArr->head && pArr->head->next)
  4821. {
  4822. // This function currently does not track missing values in the head segment if there are multiple segments
  4823. pArr->SetHasNoMissingValues(false);
  4824. }
  4825. // Above FillFromPrototypes call can change the length of the array. Our segment calculation below will
  4826. // not work with the stale length. Update the length.
  4827. // Note : since we are reversing the whole segment below - the functionality is not spec compliant already.
  4828. length = pArr->length;
  4829. SparseArraySegmentBase *prevSeg = nullptr;
  4830. SparseArraySegmentBase *nextSeg = nullptr;
  4831. SparseArraySegmentBase *pinPrevSeg = nullptr;
  4832. bool isIntArray = false;
  4833. bool isFloatArray = false;
  4834. pArr->ClearSegmentMap(); // Just dump the segment map on reverse
  4835. if (JavascriptNativeIntArray::Is(pArr))
  4836. {
  4837. isIntArray = true;
  4838. }
  4839. else if (JavascriptNativeFloatArray::Is(pArr))
  4840. {
  4841. isFloatArray = true;
  4842. }
  4843. // Code below has potential to throw due to OOM or SO. Just FailFast on those cases
  4844. AutoDisableInterrupt failFastOnError(scriptContext->GetThreadContext());
  4845. // During the loop below we are going to reverse the segments list. The head segment will become the last segment.
  4846. // 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
  4847. // be the head and that can create issue down the line. Create new segment if it is an inilined segment.
  4848. if (pArr->head && (pArr->head->next || (pArr->head->left + pArr->head->length) < length))
  4849. {
  4850. if (isIntArray)
  4851. {
  4852. CopyHeadIfInlinedHeadSegment<int32>(pArr, recycler);
  4853. if (pArr->head->next)
  4854. {
  4855. ReallocateNonLeafLastSegmentIfLeaf<int32>(pArr, recycler);
  4856. }
  4857. }
  4858. else if (isFloatArray)
  4859. {
  4860. CopyHeadIfInlinedHeadSegment<double>(pArr, recycler);
  4861. if (pArr->head->next)
  4862. {
  4863. ReallocateNonLeafLastSegmentIfLeaf<double>(pArr, recycler);
  4864. }
  4865. }
  4866. else
  4867. {
  4868. CopyHeadIfInlinedHeadSegment<Var>(pArr, recycler);
  4869. }
  4870. }
  4871. SparseArraySegmentBase* seg = pArr->head;
  4872. while (seg)
  4873. {
  4874. nextSeg = seg->next;
  4875. // If seg.length == 0, it is possible that (seg.left + seg.length == prev.left + prev.length),
  4876. // resulting in 2 segments sharing the same "left".
  4877. if (seg->length > 0)
  4878. {
  4879. if (isIntArray)
  4880. {
  4881. ((SparseArraySegment<int32>*)seg)->ReverseSegment(recycler);
  4882. }
  4883. else if (isFloatArray)
  4884. {
  4885. ((SparseArraySegment<double>*)seg)->ReverseSegment(recycler);
  4886. }
  4887. else
  4888. {
  4889. ((SparseArraySegment<Var>*)seg)->ReverseSegment(recycler);
  4890. }
  4891. if (((uint32)length) < (seg->left + seg->length))
  4892. {
  4893. Js::Throw::FatalInternalError();
  4894. }
  4895. seg->left = ((uint32)length) - (seg->left + seg->length);
  4896. seg->next = prevSeg;
  4897. // Make sure size doesn't overlap with next segment.
  4898. // An easy fix is to just truncate the size...
  4899. seg->EnsureSizeInBound();
  4900. // If the last segment is a leaf, then we may be losing our last scanned pointer to its previous
  4901. // segment. Hold onto it with pinPrevSeg until we reallocate below.
  4902. pinPrevSeg = prevSeg;
  4903. prevSeg = seg;
  4904. }
  4905. seg = nextSeg;
  4906. }
  4907. pArr->head = prevSeg;
  4908. if (isIntArray)
  4909. {
  4910. pArr->EnsureHeadStartsFromZero<int32>(recycler);
  4911. }
  4912. else if (isFloatArray)
  4913. {
  4914. pArr->EnsureHeadStartsFromZero<double>(recycler);
  4915. }
  4916. else
  4917. {
  4918. pArr->EnsureHeadStartsFromZero<Var>(recycler);
  4919. }
  4920. pArr->InvalidateLastUsedSegment(); // lastUsedSegment might be 0-length and discarded above
  4921. #ifdef VALIDATE_ARRAY
  4922. pArr->ValidateArray();
  4923. #endif
  4924. failFastOnError.Completed();
  4925. }
  4926. else if (typedArrayBase)
  4927. {
  4928. Assert(length <= JavascriptArray::MaxArrayLength);
  4929. if (typedArrayBase->GetLength() == length)
  4930. {
  4931. // If typedArrayBase->length == length then we know that the TypedArray will have all items < length
  4932. // and we won't have to check that the elements exist or not.
  4933. for (uint32 lower = 0; lower < (uint32)middle; lower++)
  4934. {
  4935. uint32 upper = (uint32)length - lower - 1;
  4936. lowerValue = typedArrayBase->DirectGetItem(lower);
  4937. upperValue = typedArrayBase->DirectGetItem(upper);
  4938. // We still have to call HasItem even though we know the TypedArray has both lower and upper because
  4939. // there may be a proxy handler trapping HasProperty.
  4940. lowerExists = typedArrayBase->HasItem(lower);
  4941. upperExists = typedArrayBase->HasItem(upper);
  4942. JS_REENTRANT(jsReentLock,
  4943. h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(lower, upperValue)),
  4944. h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(upper, lowerValue)));
  4945. }
  4946. }
  4947. else
  4948. {
  4949. Assert(middle <= UINT_MAX);
  4950. for (uint32 lower = 0; lower < (uint32)middle; lower++)
  4951. {
  4952. uint32 upper = (uint32)length - lower - 1;
  4953. lowerValue = typedArrayBase->DirectGetItem(lower);
  4954. upperValue = typedArrayBase->DirectGetItem(upper);
  4955. lowerExists = typedArrayBase->HasItem(lower);
  4956. upperExists = typedArrayBase->HasItem(upper);
  4957. if (lowerExists)
  4958. {
  4959. if (upperExists)
  4960. {
  4961. JS_REENTRANT(jsReentLock,
  4962. h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(lower, upperValue)),
  4963. h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(upper, lowerValue)));
  4964. }
  4965. else
  4966. {
  4967. // This will always fail for a TypedArray if lower < length
  4968. h.ThrowTypeErrorOnFailure(typedArrayBase->DeleteItem(lower, PropertyOperation_ThrowOnDeleteIfNotConfig));
  4969. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(upper, lowerValue)));
  4970. }
  4971. }
  4972. else
  4973. {
  4974. if (upperExists)
  4975. {
  4976. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(lower, upperValue)));
  4977. // This will always fail for a TypedArray if upper < length
  4978. h.ThrowTypeErrorOnFailure(typedArrayBase->DeleteItem(upper, PropertyOperation_ThrowOnDeleteIfNotConfig));
  4979. }
  4980. }
  4981. }
  4982. }
  4983. }
  4984. else
  4985. {
  4986. for (T lower = 0; lower < middle; lower++)
  4987. {
  4988. T upper = length - lower - 1;
  4989. JS_REENTRANT(jsReentLock,
  4990. lowerExists = JavascriptOperators::HasItem(obj, lower) && JavascriptOperators::GetItem(obj, lower, &lowerValue, scriptContext),
  4991. upperExists = JavascriptOperators::HasItem(obj, upper) && JavascriptOperators::GetItem(obj, upper, &upperValue, scriptContext));
  4992. if (lowerExists)
  4993. {
  4994. if (upperExists)
  4995. {
  4996. JS_REENTRANT(jsReentLock,
  4997. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, lower, upperValue, scriptContext, PropertyOperation_ThrowIfNotExtensible)),
  4998. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, upper, lowerValue, scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  4999. }
  5000. else
  5001. {
  5002. JS_REENTRANT(jsReentLock,
  5003. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(obj, lower, PropertyOperation_ThrowOnDeleteIfNotConfig)),
  5004. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, upper, lowerValue, scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  5005. }
  5006. }
  5007. else
  5008. {
  5009. if (upperExists)
  5010. {
  5011. JS_REENTRANT(jsReentLock,
  5012. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, lower, upperValue, scriptContext, PropertyOperation_ThrowIfNotExtensible)),
  5013. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(obj, upper, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  5014. }
  5015. }
  5016. }
  5017. }
  5018. return obj;
  5019. }
  5020. template<typename T>
  5021. void JavascriptArray::ShiftHelper(JavascriptArray* pArr, ScriptContext * scriptContext)
  5022. {
  5023. Recycler * recycler = scriptContext->GetRecycler();
  5024. SparseArraySegment<T>* next = SparseArraySegment<T>::From(pArr->head->next);
  5025. while (next)
  5026. {
  5027. next->left--;
  5028. next = SparseArraySegment<T>::From(next->next);
  5029. }
  5030. // head and next might overlap as the next segment left is decremented
  5031. next = SparseArraySegment<T>::From(pArr->head->next);
  5032. if (next && (pArr->head->size > next->left))
  5033. {
  5034. AssertMsg(pArr->head->left == 0, "Array always points to a head starting at index 0");
  5035. AssertMsg(pArr->head->size == next->left + 1, "Shift next->left overlaps current segment by more than 1 element");
  5036. SparseArraySegment<T> *head = SparseArraySegment<T>::From(pArr->head);
  5037. SparseArraySegment<T> *oldHead = head;
  5038. bool isInlineSegment = JavascriptArray::IsInlineSegment(head, pArr);
  5039. bool nextIsInlineSegment = JavascriptArray::IsInlineSegment(next, pArr);
  5040. // Merge the two adjacent segments
  5041. if (next->length != 0)
  5042. {
  5043. uint32 offset = head->size - 1;
  5044. // There is room for one unshifted element in head segment.
  5045. // Hence it's enough if we grow the head segment by next->length - 1
  5046. if (next->next)
  5047. {
  5048. // If we have a next->next, we can't grow pass the left of that
  5049. // If the array had a segment map before, the next->next might just be right after next as well.
  5050. // So we just need to grow to the end of the next segment
  5051. // TODO: merge that segment too?
  5052. Assert(next->next->left >= head->size);
  5053. uint32 maxGrowSize = next->next->left - head->size;
  5054. if (maxGrowSize != 0)
  5055. {
  5056. head = head->GrowByMinMax(recycler, next->length - 1, maxGrowSize); //-1 is to account for unshift
  5057. }
  5058. else
  5059. {
  5060. // The next segment is only of length one, so we already have space in the header to copy that
  5061. Assert(next->length == 1);
  5062. }
  5063. }
  5064. else
  5065. {
  5066. head = head->GrowByMin(recycler, next->length - 1); //-1 is to account for unshift
  5067. }
  5068. MoveArray(head->elements + offset, next->elements, next->length);
  5069. head->length = offset + next->length;
  5070. head->CheckLengthvsSize();
  5071. pArr->head = head;
  5072. if (isInlineSegment && oldHead != head)
  5073. {
  5074. pArr->ClearElements(oldHead, 0);
  5075. }
  5076. }
  5077. head->next = next->next;
  5078. if (nextIsInlineSegment)
  5079. {
  5080. pArr->ClearElements(next, 0);
  5081. }
  5082. pArr->InvalidateLastUsedSegment();
  5083. }
  5084. #ifdef VALIDATE_ARRAY
  5085. pArr->ValidateArray();
  5086. #endif
  5087. }
  5088. Var JavascriptArray::EntryShift(RecyclableObject* function, CallInfo callInfo, ...)
  5089. {
  5090. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  5091. ARGUMENTS(args, callInfo);
  5092. ScriptContext* scriptContext = function->GetScriptContext();
  5093. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  5094. SETOBJECT_FOR_MUTATION(jsReentLock, args[0]);
  5095. Assert(!(callInfo.Flags & CallFlags_New));
  5096. Var res = scriptContext->GetLibrary()->GetUndefined();
  5097. if (args.Info.Count == 0)
  5098. {
  5099. return res;
  5100. }
  5101. bool useNoSideEffectShift = JavascriptArray::Is(args[0])
  5102. && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject()
  5103. && !HasAnyES5ArrayInPrototypeChain(JavascriptArray::UnsafeFromVar(args[0]));
  5104. if (useNoSideEffectShift)
  5105. {
  5106. JavascriptArray * pArr = JavascriptArray::UnsafeFromVar(args[0]);
  5107. if (pArr->length == 0)
  5108. {
  5109. return res;
  5110. }
  5111. uint32 length = pArr->length;
  5112. if(pArr->IsFillFromPrototypes())
  5113. {
  5114. pArr->FillFromPrototypes(0, pArr->length); // We need find all missing value from [[proto]] object
  5115. }
  5116. // As we have already established that the FillFromPrototype should not change the bound of the array.
  5117. if (length != pArr->length)
  5118. {
  5119. Js::Throw::FatalInternalError();
  5120. }
  5121. if(pArr->HasNoMissingValues() && pArr->head && pArr->head->next)
  5122. {
  5123. // This function currently does not track missing values in the head segment if there are multiple segments
  5124. pArr->SetHasNoMissingValues(false);
  5125. }
  5126. pArr->length--;
  5127. pArr->ClearSegmentMap(); // Dump segmentMap on shift (before any allocation)
  5128. Recycler * recycler = scriptContext->GetRecycler();
  5129. bool isIntArray = false;
  5130. bool isFloatArray = false;
  5131. if(JavascriptNativeIntArray::Is(pArr))
  5132. {
  5133. isIntArray = true;
  5134. }
  5135. else if(JavascriptNativeFloatArray::Is(pArr))
  5136. {
  5137. isFloatArray = true;
  5138. }
  5139. // Code below has potential to throw due to OOM or SO. Just FailFast on those cases
  5140. AutoDisableInterrupt failFastOnError(scriptContext->GetThreadContext());
  5141. if (pArr->head->length != 0)
  5142. {
  5143. if(isIntArray)
  5144. {
  5145. int32 nativeResult = SparseArraySegment<int32>::From(pArr->head)->GetElement(0);
  5146. if(SparseArraySegment<int32>::IsMissingItem(&nativeResult))
  5147. {
  5148. res = scriptContext->GetLibrary()->GetUndefined();
  5149. }
  5150. else
  5151. {
  5152. res = Js::JavascriptNumber::ToVar(nativeResult, scriptContext);
  5153. }
  5154. SparseArraySegment<int32>::From(pArr->head)->RemoveElement(recycler, 0);
  5155. }
  5156. else if (isFloatArray)
  5157. {
  5158. double nativeResult = SparseArraySegment<double>::From(pArr->head)->GetElement(0);
  5159. if(SparseArraySegment<double>::IsMissingItem(&nativeResult))
  5160. {
  5161. res = scriptContext->GetLibrary()->GetUndefined();
  5162. }
  5163. else
  5164. {
  5165. res = Js::JavascriptNumber::ToVarNoCheck(nativeResult, scriptContext);
  5166. }
  5167. SparseArraySegment<double>::From(pArr->head)->RemoveElement(recycler, 0);
  5168. }
  5169. else
  5170. {
  5171. res = SparseArraySegment<Var>::From(pArr->head)->GetElement(0);
  5172. if(SparseArraySegment<Var>::IsMissingItem(&res))
  5173. {
  5174. res = scriptContext->GetLibrary()->GetUndefined();
  5175. }
  5176. else
  5177. {
  5178. res = CrossSite::MarshalVar(scriptContext, res);
  5179. }
  5180. SparseArraySegment<Var>::From(pArr->head)->RemoveElement(recycler, 0);
  5181. }
  5182. }
  5183. if(isIntArray)
  5184. {
  5185. ShiftHelper<int32>(pArr, scriptContext);
  5186. }
  5187. else if (isFloatArray)
  5188. {
  5189. ShiftHelper<double>(pArr, scriptContext);
  5190. }
  5191. else
  5192. {
  5193. ShiftHelper<Var>(pArr, scriptContext);
  5194. }
  5195. failFastOnError.Completed();
  5196. }
  5197. else
  5198. {
  5199. RecyclableObject* dynamicObject = nullptr;
  5200. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &dynamicObject))
  5201. {
  5202. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.shift"));
  5203. }
  5204. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.shift"));
  5205. JS_REENTRANT(jsReentLock, BigIndex length = OP_GetLength(dynamicObject, scriptContext));
  5206. if (length == 0u)
  5207. {
  5208. // If length is 0, return 'undefined'
  5209. JS_REENTRANT(jsReentLock,
  5210. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, TaggedInt::ToVarUnchecked(0), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  5211. return scriptContext->GetLibrary()->GetUndefined();
  5212. }
  5213. JS_REENTRANT(jsReentLock,
  5214. BOOL gotItem = JavascriptOperators::GetItem(dynamicObject, 0u, &res, scriptContext));
  5215. if (!gotItem)
  5216. {
  5217. res = scriptContext->GetLibrary()->GetUndefined();
  5218. }
  5219. --length;
  5220. uint32 lengthToUin32Max = length.IsSmallIndex() ? length.GetSmallIndex() : MaxArrayLength;
  5221. for (uint32 i = 0u; i < lengthToUin32Max; i++)
  5222. {
  5223. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(dynamicObject, i + 1));
  5224. if (hasItem)
  5225. {
  5226. Var element = nullptr;
  5227. JS_REENTRANT(jsReentLock,
  5228. element = JavascriptOperators::GetItem(dynamicObject, i + 1, scriptContext),
  5229. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(dynamicObject, dynamicObject, i, element, scriptContext, PropertyOperation_ThrowIfNotExtensible, /*skipPrototypeCheck*/ true)));
  5230. }
  5231. else
  5232. {
  5233. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, i, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  5234. }
  5235. }
  5236. for (uint64 i = MaxArrayLength; length > i; i++)
  5237. {
  5238. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(dynamicObject, i + 1));
  5239. if (hasItem)
  5240. {
  5241. Var element = nullptr;
  5242. JS_REENTRANT(jsReentLock,
  5243. element = JavascriptOperators::GetItem(dynamicObject, i + 1, scriptContext),
  5244. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(dynamicObject, dynamicObject, i, element, scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  5245. }
  5246. else
  5247. {
  5248. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, i, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  5249. }
  5250. }
  5251. if (length.IsSmallIndex())
  5252. {
  5253. JS_REENTRANT(jsReentLock,
  5254. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, length.GetSmallIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig)),
  5255. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(length.GetSmallIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  5256. }
  5257. else
  5258. {
  5259. JS_REENTRANT(jsReentLock,
  5260. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, length.GetBigIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig)),
  5261. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(length.GetBigIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  5262. }
  5263. }
  5264. return res;
  5265. }
  5266. Js::JavascriptArray* JavascriptArray::CreateNewArrayHelper(uint32 len, bool isIntArray, bool isFloatArray, Js::JavascriptArray* baseArray, ScriptContext* scriptContext)
  5267. {
  5268. if (isIntArray)
  5269. {
  5270. Js::JavascriptNativeIntArray *pnewArr = scriptContext->GetLibrary()->CreateNativeIntArray(len);
  5271. pnewArr->EnsureHead<int32>();
  5272. #if ENABLE_PROFILE_INFO
  5273. pnewArr->CopyArrayProfileInfo(Js::JavascriptNativeIntArray::UnsafeFromVar(baseArray));
  5274. #endif
  5275. return pnewArr;
  5276. }
  5277. else if (isFloatArray)
  5278. {
  5279. Js::JavascriptNativeFloatArray *pnewArr = scriptContext->GetLibrary()->CreateNativeFloatArray(len);
  5280. pnewArr->EnsureHead<double>();
  5281. #if ENABLE_PROFILE_INFO
  5282. pnewArr->CopyArrayProfileInfo(Js::JavascriptNativeFloatArray::UnsafeFromVar(baseArray));
  5283. #endif
  5284. return pnewArr;
  5285. }
  5286. else
  5287. {
  5288. JavascriptArray *pnewArr = pnewArr = scriptContext->GetLibrary()->CreateArray(len);
  5289. pnewArr->EnsureHead<Var>();
  5290. return pnewArr;
  5291. }
  5292. }
  5293. template<typename T>
  5294. void JavascriptArray::SliceHelper(JavascriptArray* pArr, JavascriptArray* pnewArr, uint32 start, uint32 newLen)
  5295. {
  5296. JS_REENTRANCY_LOCK(jsReentLock, pArr->GetScriptContext()->GetThreadContext());
  5297. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  5298. SparseArraySegment<T>* headSeg = SparseArraySegment<T>::From(pArr->head);
  5299. SparseArraySegment<T>* pnewHeadSeg = SparseArraySegment<T>::From(pnewArr->head);
  5300. // Fill the newly created sliced array
  5301. CopyArray(pnewHeadSeg->elements, newLen, headSeg->elements + start, newLen);
  5302. pnewHeadSeg->length = newLen;
  5303. pnewHeadSeg->CheckLengthvsSize();
  5304. Assert(pnewHeadSeg->length <= pnewHeadSeg->size);
  5305. // Prototype lookup for missing elements
  5306. if (!pArr->HasNoMissingValues())
  5307. {
  5308. for (uint32 i = 0; i < newLen; i++)
  5309. {
  5310. if (!(pArr->head->left <= (i + start) && (i + start) < (pArr->head->left + pArr->head->length)))
  5311. {
  5312. break;
  5313. }
  5314. // array type might be changed in the below call to DirectGetItemAtFull
  5315. // need recheck array type before checking array item [i + start]
  5316. if (pArr->IsMissingItem(i + start))
  5317. {
  5318. Var element;
  5319. pnewArr->SetHasNoMissingValues(false);
  5320. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(i + start, &element));
  5321. if (gotItem)
  5322. {
  5323. JS_REENTRANT(jsReentLock, pnewArr->SetItem(i, element, PropertyOperation_None));
  5324. }
  5325. }
  5326. }
  5327. }
  5328. #ifdef DBG
  5329. else
  5330. {
  5331. for (uint32 i = 0; i < newLen; i++)
  5332. {
  5333. AssertMsg(!SparseArraySegment<T>::IsMissingItem(&headSeg->elements[i+start]), "Array marked incorrectly as having missing value");
  5334. }
  5335. }
  5336. #endif
  5337. }
  5338. // If the creating profile data has changed, convert it to the type of array indicated
  5339. // in the profile
  5340. void JavascriptArray::GetArrayTypeAndConvert(bool* isIntArray, bool* isFloatArray)
  5341. {
  5342. JavascriptNativeIntArray* nativeIntArray = JavascriptOperators::TryFromVar<JavascriptNativeIntArray>(this);
  5343. if (nativeIntArray)
  5344. {
  5345. #if ENABLE_PROFILE_INFO
  5346. ArrayCallSiteInfo* info = nativeIntArray->GetArrayCallSiteInfo();
  5347. if(!info || info->IsNativeIntArray())
  5348. {
  5349. *isIntArray = true;
  5350. }
  5351. else if(info->IsNativeFloatArray())
  5352. {
  5353. JavascriptNativeIntArray::ToNativeFloatArray(nativeIntArray);
  5354. *isFloatArray = true;
  5355. }
  5356. else
  5357. {
  5358. JavascriptNativeIntArray::ToVarArray(nativeIntArray);
  5359. }
  5360. #else
  5361. *isIntArray = true;
  5362. #endif
  5363. }
  5364. else
  5365. {
  5366. JavascriptNativeFloatArray* nativeFloatArray = JavascriptOperators::TryFromVar<JavascriptNativeFloatArray>(this);
  5367. if (nativeFloatArray)
  5368. {
  5369. #if ENABLE_PROFILE_INFO
  5370. ArrayCallSiteInfo* info = nativeFloatArray->GetArrayCallSiteInfo();
  5371. if (info && !info->IsNativeArray())
  5372. {
  5373. JavascriptNativeFloatArray::ToVarArray(nativeFloatArray);
  5374. }
  5375. else
  5376. {
  5377. *isFloatArray = true;
  5378. }
  5379. #else
  5380. *isFloatArray = true;
  5381. #endif
  5382. }
  5383. }
  5384. }
  5385. Var JavascriptArray::EntrySlice(RecyclableObject* function, CallInfo callInfo, ...)
  5386. {
  5387. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  5388. ARGUMENTS(args, callInfo);
  5389. ScriptContext* scriptContext = function->GetScriptContext();
  5390. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  5391. Assert(!(callInfo.Flags & CallFlags_New));
  5392. Var res = scriptContext->GetLibrary()->GetUndefined();
  5393. if (args.Info.Count == 0)
  5394. {
  5395. return res;
  5396. }
  5397. BigIndex length;
  5398. JavascriptArray* pArr = nullptr;
  5399. RecyclableObject* obj = nullptr;
  5400. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.slice"), &pArr, &obj, &length));
  5401. if (length.IsSmallIndex())
  5402. {
  5403. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  5404. }
  5405. Assert(pArr == nullptr || length.IsUint32Max());
  5406. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  5407. }
  5408. // Array.prototype.slice as described in ES6.0 (draft 22) Section 22.1.3.22
  5409. template <typename T>
  5410. Var JavascriptArray::SliceHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  5411. {
  5412. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  5413. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  5414. JavascriptArray* newArr = nullptr;
  5415. RecyclableObject* newObj = nullptr;
  5416. bool isIntArray = false;
  5417. bool isFloatArray = false;
  5418. bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
  5419. bool isBuiltinArrayCtor = true;
  5420. T startT = 0;
  5421. T newLenT = length;
  5422. T endT = length;
  5423. #if ENABLE_COPYONACCESS_ARRAY
  5424. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pArr);
  5425. #endif
  5426. if (args.Info.Count > 1)
  5427. {
  5428. JS_REENTRANT(jsReentLock, startT = GetFromIndex(args[1], length, scriptContext));
  5429. if (args.Info.Count > 2 && JavascriptOperators::GetTypeId(args[2]) != TypeIds_Undefined)
  5430. {
  5431. JS_REENTRANT(jsReentLock, endT = GetFromIndex(args[2], length, scriptContext));
  5432. }
  5433. newLenT = endT > startT ? endT - startT : 0;
  5434. }
  5435. // 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.
  5436. if (pArr && !JavascriptArray::Is(obj))
  5437. {
  5438. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  5439. pArr = nullptr;
  5440. }
  5441. if (TypedArrayBase::IsDetachedTypedArray(obj))
  5442. {
  5443. JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("Array.prototype.slice"));
  5444. }
  5445. // If we came from Array.prototype.slice and source object is not a JavascriptArray, source could be a TypedArray
  5446. if (!isTypedArrayEntryPoint && pArr == nullptr && TypedArrayBase::Is(obj))
  5447. {
  5448. typedArrayBase = TypedArrayBase::UnsafeFromVar(obj);
  5449. }
  5450. // 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
  5451. // and use it to construct the return object.
  5452. if (isTypedArrayEntryPoint)
  5453. {
  5454. JS_REENTRANT(jsReentLock,
  5455. RecyclableObject* constructor = JavascriptOperators::SpeciesConstructor(typedArrayBase, TypedArrayBase::GetDefaultConstructor(args[0], scriptContext), scriptContext));
  5456. isBuiltinArrayCtor = false;
  5457. AssertAndFailFast(pArr == nullptr);
  5458. Assert(JavascriptOperators::IsConstructor(constructor));
  5459. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(newLenT, scriptContext) };
  5460. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  5461. JS_REENTRANT(jsReentLock, newObj = RecyclableObject::FromVar(TypedArrayBase::TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), (uint32)newLenT, scriptContext)));
  5462. }
  5463. else if (pArr != nullptr)
  5464. {
  5465. JS_REENTRANT_NO_MUTATE(jsReentLock, newObj = ArraySpeciesCreate(pArr, newLenT, scriptContext, &isIntArray, &isFloatArray, &isBuiltinArrayCtor));
  5466. }
  5467. // skip the typed array and "pure" array case, we still need to handle special arrays like es5array, remote array, and proxy of array.
  5468. else
  5469. {
  5470. JS_REENTRANT_NO_MUTATE(jsReentLock, newObj = ArraySpeciesCreate(obj, newLenT, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor));
  5471. }
  5472. // If we didn't create a new object above we will create a new array here.
  5473. // This is the pre-ES6 behavior or the case of calling Array.prototype.slice with a constructor argument that is not a constructor function.
  5474. if (newObj == nullptr)
  5475. {
  5476. if (pArr)
  5477. {
  5478. pArr->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
  5479. }
  5480. if (newLenT > JavascriptArray::MaxArrayLength)
  5481. {
  5482. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  5483. }
  5484. newArr = CreateNewArrayHelper(static_cast<uint32>(newLenT), isIntArray, isFloatArray, pArr, scriptContext);
  5485. #if ENABLE_COPYONACCESS_ARRAY
  5486. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  5487. #endif
  5488. newObj = newArr;
  5489. SET_SECOND_OBJECT_FOR_MUTATION(jsReentLock, newArr);
  5490. }
  5491. else
  5492. {
  5493. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  5494. newArr = JavascriptOperators::TryFromVar<JavascriptArray>(newObj);
  5495. if (newArr)
  5496. {
  5497. #if ENABLE_COPYONACCESS_ARRAY
  5498. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  5499. #endif
  5500. }
  5501. }
  5502. uint32 start = (uint32) startT;
  5503. uint32 newLen = (uint32) newLenT;
  5504. // We at least have to have newObj as a valid object
  5505. Assert(newObj);
  5506. // Bail out early if the new object will have zero length.
  5507. if (newLen == 0)
  5508. {
  5509. return newObj;
  5510. }
  5511. // The ArraySpeciesCreate call above could have converted the source array into an ES5Array. If this happens
  5512. // we will process the array elements like an ES5Array.
  5513. if (pArr && !JavascriptArray::Is(obj))
  5514. {
  5515. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  5516. pArr = nullptr;
  5517. }
  5518. if (pArr)
  5519. {
  5520. if (HasAnyES5ArrayInPrototypeChain(pArr))
  5521. {
  5522. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceObjectHelper(obj, start, 0u, newArr, newObj, newLen, scriptContext));
  5523. }
  5524. // If we constructed a new Array object, we have some nice helpers here
  5525. if (newArr && isBuiltinArrayCtor)
  5526. {
  5527. if (JavascriptArray::IsDirectAccessArray(newArr))
  5528. {
  5529. if (((start + newLen) <= pArr->head->length) && newLen <= newArr->head->size) //Fast Path
  5530. {
  5531. if (isIntArray)
  5532. {
  5533. JS_REENTRANT(jsReentLock, SliceHelper<int32>(pArr, newArr, start, newLen));
  5534. }
  5535. else if (isFloatArray)
  5536. {
  5537. JS_REENTRANT(jsReentLock, SliceHelper<double>(pArr, newArr, start, newLen));
  5538. }
  5539. else
  5540. {
  5541. JS_REENTRANT(jsReentLock, SliceHelper<Var>(pArr, newArr, start, newLen));
  5542. }
  5543. }
  5544. else
  5545. {
  5546. if (isIntArray)
  5547. {
  5548. JS_REENTRANT(jsReentLock, CopyNativeIntArrayElements(JavascriptNativeIntArray::FromVar(newArr), 0, JavascriptNativeIntArray::FromVar(pArr), start, start + newLen));
  5549. }
  5550. else if (isFloatArray)
  5551. {
  5552. JS_REENTRANT(jsReentLock, CopyNativeFloatArrayElements(JavascriptNativeFloatArray::FromVar(newArr), 0, JavascriptNativeFloatArray::FromVar(pArr), start, start + newLen));
  5553. }
  5554. else
  5555. {
  5556. JS_REENTRANT(jsReentLock, CopyArrayElements(newArr, 0u, pArr, start, start + newLen));
  5557. }
  5558. }
  5559. }
  5560. else
  5561. {
  5562. AssertMsg(CONFIG_FLAG(ForceES5Array), "newArr can only be ES5Array when it is forced");
  5563. Var element;
  5564. for (uint32 i = 0; i < newLen; i++)
  5565. {
  5566. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(i + start, &element));
  5567. if (!gotItem)
  5568. {
  5569. continue;
  5570. }
  5571. newArr->SetItem(i, element, PropertyOperation_None);
  5572. // Side-effects in the prototype lookup may have changed the source array into an ES5Array. If this happens
  5573. // we will process the rest of the array elements like an ES5Array.
  5574. if (!JavascriptArray::Is(obj))
  5575. {
  5576. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  5577. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceObjectHelper(obj, start, i + 1, newArr, newObj, newLen, scriptContext));
  5578. }
  5579. }
  5580. }
  5581. }
  5582. else
  5583. {
  5584. // The constructed object isn't an array, we'll need to use normal object manipulation
  5585. Var element;
  5586. for (uint32 i = 0; i < newLen; i++)
  5587. {
  5588. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(i + start, &element));
  5589. if (!gotItem)
  5590. {
  5591. continue;
  5592. }
  5593. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i));
  5594. // Side-effects in the prototype lookup may have changed the source array into an ES5Array. If this happens
  5595. // we will process the rest of the array elements like an ES5Array.
  5596. if (!JavascriptArray::Is(obj))
  5597. {
  5598. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  5599. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceObjectHelper(obj, start, i + 1, newArr, newObj, newLen, scriptContext));
  5600. }
  5601. }
  5602. }
  5603. }
  5604. else if (typedArrayBase)
  5605. {
  5606. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  5607. // 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)
  5608. TypedArrayBase* newTypedArray = JavascriptOperators::TryFromVar<Js::TypedArrayBase>(newObj);
  5609. if (!newTypedArray)
  5610. {
  5611. AssertAndFailFast(newArr != nullptr);
  5612. }
  5613. Var element;
  5614. for (uint32 i = 0; i < newLen; i++)
  5615. {
  5616. // We only need to call HasItem in the case that we are called from Array.prototype.slice
  5617. if (!isTypedArrayEntryPoint && !typedArrayBase->HasItem(i + start))
  5618. {
  5619. continue;
  5620. }
  5621. element = typedArrayBase->DirectGetItem(i + start);
  5622. // The object we got back from the constructor might not be a TypedArray. In fact, it could be any object.
  5623. if (newTypedArray)
  5624. {
  5625. JS_REENTRANT(jsReentLock, newTypedArray->DirectSetItem(i, element));
  5626. }
  5627. else
  5628. {
  5629. newArr->SetItem(i, element, PropertyOperation_None);
  5630. }
  5631. }
  5632. }
  5633. else
  5634. {
  5635. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceObjectHelper(obj, start, 0u, newArr, newObj, newLen, scriptContext));;
  5636. }
  5637. if (!isTypedArrayEntryPoint)
  5638. {
  5639. JS_REENTRANT(jsReentLock, JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(newLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  5640. }
  5641. #ifdef VALIDATE_ARRAY
  5642. JavascriptArray * jsArr = JavascriptOperators::TryFromVar<JavascriptArray>(newObj);
  5643. if (jsArr)
  5644. {
  5645. jsArr->ValidateArray();
  5646. }
  5647. #endif
  5648. return newObj;
  5649. }
  5650. Var JavascriptArray::SliceObjectHelper(RecyclableObject* obj, uint32 sliceStart, uint32 start, JavascriptArray* newArr, RecyclableObject* newObj, uint32 newLen, ScriptContext* scriptContext)
  5651. {
  5652. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  5653. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  5654. for (uint32 i = start; i < newLen; i++)
  5655. {
  5656. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, i + sliceStart));
  5657. if (hasItem)
  5658. {
  5659. JS_REENTRANT(jsReentLock, Var element = JavascriptOperators::GetItem(obj, i + sliceStart, scriptContext));
  5660. if (newArr != nullptr)
  5661. {
  5662. newArr->SetItem(i, element, PropertyOperation_None);
  5663. }
  5664. else
  5665. {
  5666. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i));
  5667. }
  5668. }
  5669. }
  5670. JS_REENTRANT(jsReentLock,
  5671. JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(newLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  5672. #ifdef VALIDATE_ARRAY
  5673. JavascriptArray * jsArr = JavascriptOperators::TryFromVar<JavascriptArray>(newObj);
  5674. if (jsArr)
  5675. {
  5676. jsArr->ValidateArray();
  5677. }
  5678. #endif
  5679. return newObj;
  5680. }
  5681. struct CompareVarsInfo
  5682. {
  5683. ScriptContext* scriptContext;
  5684. RecyclableObject* compFn;
  5685. };
  5686. int __cdecl compareVars(void* cvInfoV, const void* aRef, const void* bRef)
  5687. {
  5688. CompareVarsInfo* cvInfo=(CompareVarsInfo*)cvInfoV;
  5689. ScriptContext* requestContext=cvInfo->scriptContext;
  5690. RecyclableObject* compFn=cvInfo->compFn;
  5691. AssertMsg(*(Var*)aRef, "No null expected in sort");
  5692. AssertMsg(*(Var*)bRef, "No null expected in sort");
  5693. if (compFn != nullptr)
  5694. {
  5695. ScriptContext* scriptContext = compFn->GetScriptContext();
  5696. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  5697. CallFlags flags = CallFlags_Value;
  5698. Var undefined = scriptContext->GetLibrary()->GetUndefined();
  5699. Var retVal;
  5700. if (requestContext != scriptContext)
  5701. {
  5702. Var leftVar = CrossSite::MarshalVar(scriptContext, *(Var*)aRef);
  5703. Var rightVar = CrossSite::MarshalVar(scriptContext, *(Var*)bRef);
  5704. retVal = CALL_FUNCTION(scriptContext->GetThreadContext(), compFn, CallInfo(flags, 3), undefined, leftVar, rightVar);
  5705. }
  5706. else
  5707. {
  5708. retVal = CALL_FUNCTION(scriptContext->GetThreadContext(), compFn, CallInfo(flags, 3), undefined, *(Var*)aRef, *(Var*)bRef);
  5709. }
  5710. if (TaggedInt::Is(retVal))
  5711. {
  5712. return TaggedInt::ToInt32(retVal);
  5713. }
  5714. double dblResult;
  5715. if (JavascriptNumber::Is_NoTaggedIntCheck(retVal))
  5716. {
  5717. dblResult = JavascriptNumber::GetValue(retVal);
  5718. }
  5719. else
  5720. {
  5721. dblResult = JavascriptConversion::ToNumber_Full(retVal, scriptContext);
  5722. }
  5723. if (dblResult < 0)
  5724. {
  5725. return -1;
  5726. }
  5727. return (dblResult > 0) ? 1 : 0;
  5728. }
  5729. else
  5730. {
  5731. JavascriptString* pStr1 = JavascriptConversion::ToString(*(Var*)aRef, requestContext);
  5732. JavascriptString* pStr2 = JavascriptConversion::ToString(*(Var*)bRef, requestContext);
  5733. return JavascriptString::strcmp(pStr1, pStr2);
  5734. }
  5735. }
  5736. static void hybridSort(__inout_ecount(length) Field(Var) *elements, uint32 length, CompareVarsInfo* compareInfo)
  5737. {
  5738. // The cost of memory moves starts to be more expensive than additional comparer calls (given a simple comparer)
  5739. // for arrays of more than 512 elements.
  5740. if (length > 512)
  5741. {
  5742. qsort_s(elements, length, compareVars, compareInfo);
  5743. return;
  5744. }
  5745. for (int i = 1; i < (int)length; i++)
  5746. {
  5747. if (compareVars(compareInfo, elements + i, elements + i - 1) < 0) {
  5748. // binary search for the left-most element greater than value:
  5749. int first = 0;
  5750. int last = i - 1;
  5751. while (first <= last)
  5752. {
  5753. int middle = (first + last) / 2;
  5754. if (compareVars(compareInfo, elements + i, elements + middle) < 0)
  5755. {
  5756. last = middle - 1;
  5757. }
  5758. else
  5759. {
  5760. first = middle + 1;
  5761. }
  5762. }
  5763. // insert value right before first:
  5764. Var value = elements[i];
  5765. MoveArray(elements + first + 1, elements + first, (i - first));
  5766. elements[first] = value;
  5767. }
  5768. }
  5769. }
  5770. void JavascriptArray::Sort(RecyclableObject* compFn)
  5771. {
  5772. JS_REENTRANCY_LOCK(jsReentLock, this->GetScriptContext()->GetThreadContext());
  5773. if (length <= 1)
  5774. {
  5775. return;
  5776. }
  5777. SETOBJECT_FOR_MUTATION(jsReentLock, this);
  5778. this->EnsureHead<Var>();
  5779. ScriptContext* scriptContext = this->GetScriptContext();
  5780. Recycler* recycler = scriptContext->GetRecycler();
  5781. CompareVarsInfo cvInfo;
  5782. cvInfo.scriptContext = scriptContext;
  5783. cvInfo.compFn = compFn;
  5784. Assert(head != nullptr);
  5785. // Just dump the segment map on sort
  5786. ClearSegmentMap();
  5787. uint32 countUndefined = 0;
  5788. SparseArraySegment<Var>* startSeg = SparseArraySegment<Var>::From(head);
  5789. // Sort may have side effects on the array. Setting a dummy head so that original array is not affected
  5790. uint32 saveLength = length;
  5791. // that if compare function tries to modify the array it won't AV.
  5792. head = const_cast<SparseArraySegmentBase*>(EmptySegment);
  5793. SetFlags(DynamicObjectFlags::None);
  5794. this->InvalidateLastUsedSegment();
  5795. length = 0;
  5796. TryFinally([&]()
  5797. {
  5798. //The array is a continuous array if there is only one segment
  5799. if (startSeg->next == nullptr
  5800. // If this flag is specified, we want to improve the consistency of our array sorts
  5801. // by removing missing values from all kinds of arrays before sorting (done here by
  5802. // using the copy-to-one-segment path for array sorts) and by using a stronger sort
  5803. // comparer than the spec requires (done in CompareElements).
  5804. && !CONFIG_FLAG(StrongArraySort)
  5805. ) // Single segment fast path
  5806. {
  5807. if (compFn != nullptr)
  5808. {
  5809. countUndefined = startSeg->RemoveUndefined(scriptContext);
  5810. #ifdef VALIDATE_ARRAY
  5811. ValidateSegment(startSeg);
  5812. #endif
  5813. JS_REENTRANT(jsReentLock, hybridSort(startSeg->elements, startSeg->length, &cvInfo));
  5814. startSeg->CheckLengthvsSize();
  5815. }
  5816. else
  5817. {
  5818. JS_REENTRANT(jsReentLock, countUndefined = sort(startSeg->elements, &startSeg->length, scriptContext));
  5819. }
  5820. head = startSeg;
  5821. }
  5822. else
  5823. {
  5824. SparseArraySegment<Var>* allElements = SparseArraySegment<Var>::AllocateSegment(recycler, 0, 0, nullptr);
  5825. SparseArraySegment<Var>* next = startSeg;
  5826. uint32 nextIndex = 0;
  5827. // copy all the elements to single segment
  5828. while (next)
  5829. {
  5830. countUndefined += next->RemoveUndefined(scriptContext);
  5831. if (next->length != 0)
  5832. {
  5833. allElements = SparseArraySegment<Var>::CopySegment(recycler, allElements, nextIndex, next, next->left, next->length);
  5834. }
  5835. next = SparseArraySegment<Var>::From(next->next);
  5836. nextIndex = allElements->length;
  5837. #ifdef VALIDATE_ARRAY
  5838. ValidateSegment(allElements);
  5839. #endif
  5840. }
  5841. if (compFn != nullptr)
  5842. {
  5843. JS_REENTRANT(jsReentLock, hybridSort(allElements->elements, allElements->length, &cvInfo));
  5844. }
  5845. else
  5846. {
  5847. JS_REENTRANT(jsReentLock, sort(allElements->elements, &allElements->length, scriptContext));
  5848. allElements->CheckLengthvsSize();
  5849. }
  5850. head = allElements;
  5851. head->next = nullptr;
  5852. }
  5853. },
  5854. [&](bool hasException)
  5855. {
  5856. length = saveLength;
  5857. ClearSegmentMap(); // Dump the segmentMap again in case user compare function rebuilds it
  5858. if (hasException)
  5859. {
  5860. head = startSeg;
  5861. this->InvalidateLastUsedSegment();
  5862. }
  5863. });
  5864. #if DEBUG
  5865. {
  5866. uint32 countNull = 0;
  5867. uint32 index = head->length - 1;
  5868. while (countNull < head->length)
  5869. {
  5870. if (SparseArraySegment<Var>::From(head)->elements[index] != NULL)
  5871. {
  5872. break;
  5873. }
  5874. index--;
  5875. countNull++;
  5876. }
  5877. AssertMsg(countNull == 0, "No null expected at the end");
  5878. }
  5879. #endif
  5880. if (countUndefined != 0)
  5881. {
  5882. // fill undefined at the end
  5883. uint32 newLength = head->length + countUndefined;
  5884. if (newLength > head->size)
  5885. {
  5886. SparseArraySegmentBase *oldHead = head;
  5887. bool isInlineSegment = JavascriptArray::IsInlineSegment(head, this);
  5888. head = SparseArraySegment<Var>::From(head)->GrowByMin(recycler, newLength - head->size);
  5889. if (isInlineSegment)
  5890. {
  5891. this->ClearElements(oldHead, 0);
  5892. }
  5893. }
  5894. Var undefined = scriptContext->GetLibrary()->GetUndefined();
  5895. for (uint32 i = head->length; i < newLength; i++)
  5896. {
  5897. SparseArraySegment<Var>::From(head)->elements[i] = undefined;
  5898. }
  5899. head->length = newLength;
  5900. head->CheckLengthvsSize();
  5901. }
  5902. SetHasNoMissingValues();
  5903. this->InvalidateLastUsedSegment();
  5904. #ifdef VALIDATE_ARRAY
  5905. ValidateArray();
  5906. #endif
  5907. return;
  5908. }
  5909. uint32 JavascriptArray::sort(__inout_ecount(*len) Field(Var) *orig, uint32 *len, ScriptContext *scriptContext)
  5910. {
  5911. uint32 count = 0, countUndefined = 0;
  5912. Element *elements = RecyclerNewArrayZ(scriptContext->GetRecycler(), Element, *len);
  5913. RecyclableObject *undefined = scriptContext->GetLibrary()->GetUndefined();
  5914. //
  5915. // Create the Elements array
  5916. //
  5917. for (uint32 i = 0; i < *len; ++i)
  5918. {
  5919. if (!SparseArraySegment<Var>::IsMissingItem(&orig[i]))
  5920. {
  5921. if (!JavascriptOperators::IsUndefinedObject(orig[i], undefined))
  5922. {
  5923. elements[count].Value = orig[i];
  5924. elements[count].StringValue = JavascriptConversion::ToString(orig[i], scriptContext);
  5925. count++;
  5926. }
  5927. else
  5928. {
  5929. countUndefined++;
  5930. }
  5931. }
  5932. }
  5933. if (count > 0)
  5934. {
  5935. SortElements(elements, 0, count - 1);
  5936. for (uint32 i = 0; i < count; ++i)
  5937. {
  5938. orig[i] = elements[i].Value;
  5939. }
  5940. }
  5941. for (uint32 i = count + countUndefined; i < *len; ++i)
  5942. {
  5943. orig[i] = SparseArraySegment<Var>::GetMissingItem();
  5944. }
  5945. *len = count; // set the correct length
  5946. return countUndefined;
  5947. }
  5948. int __cdecl JavascriptArray::CompareElements(void* context, const void* elem1, const void* elem2)
  5949. {
  5950. const Element* element1 = static_cast<const Element*>(elem1);
  5951. const Element* element2 = static_cast<const Element*>(elem2);
  5952. Assert(element1 != NULL);
  5953. Assert(element2 != NULL);
  5954. if (!CONFIG_FLAG(StrongArraySort))
  5955. {
  5956. return JavascriptString::strcmp(element1->StringValue, element2->StringValue);
  5957. }
  5958. else
  5959. {
  5960. int str_cmp = JavascriptString::strcmp(element1->StringValue, element2->StringValue);
  5961. if (str_cmp != 0)
  5962. {
  5963. return str_cmp;
  5964. }
  5965. // If they are equal, we get to a slightly more complex problem. We want to make a very
  5966. // predictable sort here, regardless of the structure of the array. To achieve this, we
  5967. // need to get an order for every pair of non-identical elements, else there will be an
  5968. // identifiable difference between sparse and dense array sorts in some cases.
  5969. // Handle a common set of equivalent nodes first for speed/convenience
  5970. if (element1->Value == element2->Value)
  5971. {
  5972. return 0;
  5973. }
  5974. // Easy way to do most remaining cases is to just compare the type ids if they differ.
  5975. if (JavascriptOperators::GetTypeId(element1->Value) != JavascriptOperators::GetTypeId(element2->Value))
  5976. {
  5977. return JavascriptOperators::GetTypeId(element1->Value) - JavascriptOperators::GetTypeId(element2->Value);
  5978. }
  5979. // Further comparisons are possible, but get increasingly complex, and aren't necessary
  5980. // for the cases on hand.
  5981. return 0;
  5982. }
  5983. }
  5984. void JavascriptArray::SortElements(Element* elements, uint32 left, uint32 right)
  5985. {
  5986. // Note: use write barrier policy of Field(Var)
  5987. qsort_s<Element, Field(Var)>(elements, right - left + 1, CompareElements, this);
  5988. }
  5989. Var JavascriptArray::EntrySort(RecyclableObject* function, CallInfo callInfo, ...)
  5990. {
  5991. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  5992. ARGUMENTS(args, callInfo);
  5993. ScriptContext* scriptContext = function->GetScriptContext();
  5994. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  5995. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.sort"));
  5996. Assert(!(callInfo.Flags & CallFlags_New));
  5997. AssertMsg(args.Info.Count >= 1, "Should have at least one argument");
  5998. RecyclableObject* compFn = NULL;
  5999. if (args.Info.Count > 1)
  6000. {
  6001. if (JavascriptConversion::IsCallable(args[1]))
  6002. {
  6003. compFn = RecyclableObject::FromVar(args[1]);
  6004. }
  6005. else
  6006. {
  6007. TypeId typeId = JavascriptOperators::GetTypeId(args[1]);
  6008. // Use default comparer:
  6009. // - In ES5 mode if the argument is undefined.
  6010. bool useDefaultComparer = typeId == TypeIds_Undefined;
  6011. if (!useDefaultComparer)
  6012. {
  6013. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.sort"));
  6014. }
  6015. }
  6016. }
  6017. SETOBJECT_FOR_MUTATION(jsReentLock, args[0]);
  6018. bool useNoSideEffectSort = JavascriptArray::Is(args[0])
  6019. && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject()
  6020. && !HasAnyES5ArrayInPrototypeChain(JavascriptArray::UnsafeFromVar(args[0]));
  6021. if (useNoSideEffectSort)
  6022. {
  6023. JavascriptArray *arr = JavascriptArray::UnsafeFromVar(args[0]);
  6024. if (arr->length <= 1)
  6025. {
  6026. return args[0];
  6027. }
  6028. uint32 length = arr->length;
  6029. if(arr->IsFillFromPrototypes())
  6030. {
  6031. arr->FillFromPrototypes(0, arr->length); // We need find all missing value from [[proto]] object
  6032. }
  6033. // As we have already established that the FillFromPrototype should not change the bound of the array.
  6034. if (length != arr->length)
  6035. {
  6036. Js::Throw::FatalInternalError();
  6037. }
  6038. EnsureNonNativeArray(arr);
  6039. JS_REENTRANT(jsReentLock, arr->Sort(compFn));
  6040. }
  6041. else
  6042. {
  6043. RecyclableObject* pObj = nullptr;
  6044. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &pObj))
  6045. {
  6046. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.sort"));
  6047. }
  6048. JS_REENTRANT(jsReentLock,
  6049. uint32 len = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(pObj, scriptContext), scriptContext));
  6050. JavascriptArray* sortArray = scriptContext->GetLibrary()->CreateArray(len);
  6051. sortArray->EnsureHead<Var>();
  6052. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.sort"));
  6053. BEGIN_TEMP_ALLOCATOR(tempAlloc, scriptContext, _u("Runtime"))
  6054. {
  6055. JsUtil::List<uint32, ArenaAllocator>* indexList = JsUtil::List<uint32, ArenaAllocator>::New(tempAlloc);
  6056. for (uint32 i = 0; i < len; i++)
  6057. {
  6058. Var item;
  6059. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(pObj, i, &item, scriptContext));
  6060. if (gotItem)
  6061. {
  6062. indexList->Add(i);
  6063. sortArray->DirectSetItemAt(i, item);
  6064. }
  6065. }
  6066. if (indexList->Count() > 0)
  6067. {
  6068. if (sortArray->length > 1)
  6069. {
  6070. JS_REENTRANT(jsReentLock, sortArray->FillFromPrototypes(0, sortArray->length)); // We need find all missing value from [[proto]] object
  6071. }
  6072. JS_REENTRANT(jsReentLock, sortArray->Sort(compFn));
  6073. uint32 removeIndex = sortArray->head->length;
  6074. for (uint32 i = 0; i < removeIndex; i++)
  6075. {
  6076. AssertMsg(!SparseArraySegment<Var>::IsMissingItem(&SparseArraySegment<Var>::From(sortArray->head)->elements[i]), "No gaps expected in sorted array");
  6077. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(pObj, pObj, i, SparseArraySegment<Var>::From(sortArray->head)->elements[i], scriptContext)));
  6078. }
  6079. for (int i = 0; i < indexList->Count(); i++)
  6080. {
  6081. uint32 value = indexList->Item(i);
  6082. if (value >= removeIndex)
  6083. {
  6084. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure((JavascriptOperators::DeleteItem(pObj, value))));
  6085. }
  6086. }
  6087. }
  6088. }
  6089. END_TEMP_ALLOCATOR(tempAlloc, scriptContext);
  6090. }
  6091. return args[0];
  6092. }
  6093. Var JavascriptArray::EntrySplice(RecyclableObject* function, CallInfo callInfo, ...)
  6094. {
  6095. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  6096. ARGUMENTS(args, callInfo);
  6097. ScriptContext* scriptContext = function->GetScriptContext();
  6098. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6099. Assert(!(callInfo.Flags & CallFlags_New));
  6100. AssertMsg(args.Info.Count >= 1, "Should have at least one argument");
  6101. JavascriptArray* pArr = 0;
  6102. RecyclableObject* pObj = 0;
  6103. uint64 start = 0u;
  6104. uint64 deleteLen = 0u;
  6105. uint64 length = 0u;
  6106. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.splice"), &pArr, &pObj, &length));
  6107. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  6108. switch (args.Info.Count)
  6109. {
  6110. case 1:
  6111. start = length;
  6112. deleteLen = 0u;
  6113. break;
  6114. case 2:
  6115. JS_REENTRANT(jsReentLock, start = GetFromIndex(args[1], length, scriptContext));
  6116. deleteLen = length - start;
  6117. break;
  6118. default:
  6119. JS_REENTRANT(jsReentLock, start = GetFromIndex(args[1], length, scriptContext),
  6120. deleteLen = GetFromIndex(args[2], (length - start), scriptContext, false));
  6121. break;
  6122. }
  6123. // 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.
  6124. if (pArr && !JavascriptArray::Is(pObj))
  6125. {
  6126. AssertOrFailFastMsg(ES5Array::Is(pObj), "The array should have been converted to an ES5Array");
  6127. pArr = nullptr;
  6128. }
  6129. Var* insertArgs = args.Info.Count > 3 ? &args.Values[3] : nullptr;
  6130. uint32 insertLen = args.Info.Count > 3 ? args.Info.Count - 3 : 0;
  6131. // Force check the prototype as we may insert values more than current elements
  6132. if (pArr != nullptr && !HasAnyES5ArrayInPrototypeChain(pArr, true /*forceCheckProtoChain*/))
  6133. {
  6134. // Since we get the length from an array and that cannot be more than uint32.
  6135. _Analysis_assume_(length <= UINT_MAX);
  6136. JS_REENTRANT_UNLOCK(jsReentLock,
  6137. return TryArraySplice(pArr, (uint32)start, (uint32)length, (uint32)deleteLen, insertArgs, insertLen, scriptContext));
  6138. }
  6139. uint64 newLen = (length - deleteLen) + insertLen;
  6140. if (newLen > UINT_MAX || length > UINT_MAX || (length + insertLen) > UINT_MAX)
  6141. {
  6142. JS_REENTRANT_UNLOCK(jsReentLock,
  6143. return ObjectSpliceHelper<uint64>(pObj, length, start, deleteLen, (Var*)insertArgs, insertLen, scriptContext, nullptr));
  6144. }
  6145. else
  6146. {
  6147. JS_REENTRANT_UNLOCK(jsReentLock,
  6148. return ObjectSpliceHelper<uint32>(pObj, (uint32)length, (uint32)start, (uint32)deleteLen, (Var*)insertArgs, insertLen, scriptContext, nullptr));
  6149. }
  6150. }
  6151. inline BOOL JavascriptArray::IsSingleSegmentArray() const
  6152. {
  6153. return nullptr == head->next;
  6154. }
  6155. template<typename T>
  6156. void JavascriptArray::ArraySegmentSpliceHelper(
  6157. JavascriptArray *pnewArr, SparseArraySegment<T> *seg, Field(SparseArraySegment<T>*) *prev,
  6158. uint32 start, uint32 deleteLen, Var* insertArgs, uint32 insertLen, Recycler *recycler)
  6159. {
  6160. // book keeping variables
  6161. uint32 relativeStart = start - seg->left; // This will be different from start when head->left is non zero -
  6162. //(Missing elements at the beginning)
  6163. uint32 headDeleteLen = min(start + deleteLen , seg->left + seg->length) - start; // actual number of elements to delete in
  6164. // head if deleteLen overflows the length of head
  6165. uint32 newHeadLen = seg->length - headDeleteLen + insertLen; // new length of the head after splice
  6166. // Save the deleted elements
  6167. if (headDeleteLen != 0)
  6168. {
  6169. SparseArraySegmentBase *oldHead = pnewArr->head;
  6170. bool isInlineSegment = JavascriptArray::IsInlineSegment(oldHead, pnewArr);
  6171. pnewArr->InvalidateLastUsedSegment();
  6172. pnewArr->head = SparseArraySegment<T>::CopySegment(recycler, SparseArraySegment<T>::From(pnewArr->head), 0, seg, start, headDeleteLen);
  6173. if (isInlineSegment && oldHead != pnewArr->head)
  6174. {
  6175. pnewArr->ClearElements(oldHead, 0);
  6176. }
  6177. }
  6178. if (newHeadLen != 0)
  6179. {
  6180. if (seg->size < newHeadLen)
  6181. {
  6182. if (seg->next)
  6183. {
  6184. // If we have "next", require that we haven't adjusted next segments left yet.
  6185. seg = seg->GrowByMinMax(recycler, newHeadLen - seg->size, seg->next->left - deleteLen + insertLen - seg->left - seg->size);
  6186. }
  6187. else
  6188. {
  6189. seg = seg->GrowByMin(recycler, newHeadLen - seg->size);
  6190. }
  6191. #ifdef VALIDATE_ARRAY
  6192. ValidateSegment(seg);
  6193. #endif
  6194. }
  6195. // Move the elements if necessary
  6196. if (headDeleteLen != insertLen)
  6197. {
  6198. uint32 noElementsToMove = seg->length - (relativeStart + headDeleteLen);
  6199. MoveArray(seg->elements + relativeStart + insertLen,
  6200. seg->elements + relativeStart + headDeleteLen,
  6201. noElementsToMove);
  6202. if (newHeadLen < seg->length) // truncate if necessary
  6203. {
  6204. seg->Truncate(seg->left + newHeadLen); // set end elements to null so that when we introduce null elements we are safe
  6205. }
  6206. seg->length = newHeadLen;
  6207. seg->CheckLengthvsSize();
  6208. }
  6209. // Copy the new elements
  6210. if (insertLen > 0)
  6211. {
  6212. Assert(!VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(pnewArr) &&
  6213. !VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(pnewArr));
  6214. // inserted elements starts at argument 3 of splice(start, deleteNumber, insertelem1, insertelem2, insertelem3, ...);
  6215. CopyArray(seg->elements + relativeStart, insertLen,
  6216. reinterpret_cast<const T*>(insertArgs), insertLen);
  6217. }
  6218. *prev = seg;
  6219. }
  6220. else
  6221. {
  6222. *prev = SparseArraySegment<T>::From(seg->next);
  6223. }
  6224. }
  6225. template<typename T>
  6226. void JavascriptArray::ArraySpliceHelper(JavascriptArray* pnewArr, JavascriptArray* pArr, uint32 start, uint32 deleteLen, Var* insertArgs, uint32 insertLen, ScriptContext *scriptContext)
  6227. {
  6228. // Skip pnewArr->EnsureHead(): we don't use existing segment at all.
  6229. Recycler *recycler = scriptContext->GetRecycler();
  6230. Field(SparseArraySegmentBase*)* prevSeg = &pArr->head; // holds the next pointer of previous
  6231. Field(SparseArraySegmentBase*)* prevPrevSeg = &pArr->head; // this holds the previous pointer to prevSeg dirty trick.
  6232. SparseArraySegmentBase* savePrev = nullptr;
  6233. Assert(pArr->head); // We should never have a null head.
  6234. pArr->EnsureHead<T>();
  6235. SparseArraySegment<T>* startSeg = SparseArraySegment<T>::From(pArr->head);
  6236. const uint32 limit = start + deleteLen;
  6237. uint32 rightLimit;
  6238. if (UInt32Math::Add(startSeg->left, startSeg->size, &rightLimit))
  6239. {
  6240. rightLimit = JavascriptArray::MaxArrayLength;
  6241. }
  6242. // Find out the segment to start delete
  6243. while (startSeg && (rightLimit <= start))
  6244. {
  6245. savePrev = startSeg;
  6246. prevPrevSeg = prevSeg;
  6247. prevSeg = &startSeg->next;
  6248. startSeg = SparseArraySegment<T>::From(startSeg->next);
  6249. if (startSeg)
  6250. {
  6251. if (UInt32Math::Add(startSeg->left, startSeg->size, &rightLimit))
  6252. {
  6253. rightLimit = JavascriptArray::MaxArrayLength;
  6254. }
  6255. }
  6256. }
  6257. bool hasInlineSegment = JavascriptArray::IsInlineSegment(startSeg, pArr);
  6258. if (startSeg)
  6259. {
  6260. // Delete Phase
  6261. if (startSeg->left <= start && (startSeg->left + startSeg->length) >= limit)
  6262. {
  6263. // All splice happens in one segment.
  6264. SparseArraySegmentBase *nextSeg = startSeg->next;
  6265. // Splice the segment first, which might OOM throw but the array would be intact.
  6266. JavascriptArray::ArraySegmentSpliceHelper(
  6267. pnewArr, startSeg, SparseArraySegment<T>::AddressFrom(prevSeg),
  6268. start, deleteLen, insertArgs, insertLen, recycler);
  6269. while (nextSeg)
  6270. {
  6271. // adjust next segments left
  6272. nextSeg->left = nextSeg->left - deleteLen + insertLen;
  6273. if (nextSeg->next == nullptr)
  6274. {
  6275. nextSeg->EnsureSizeInBound();
  6276. }
  6277. nextSeg = nextSeg->next;
  6278. }
  6279. if (*prevSeg)
  6280. {
  6281. (*prevSeg)->EnsureSizeInBound();
  6282. }
  6283. return;
  6284. }
  6285. else
  6286. {
  6287. SparseArraySegment<T>* newHeadSeg = nullptr; // pnewArr->head is null
  6288. Field(SparseArraySegmentBase*)* prevNewHeadSeg = &pnewArr->head;
  6289. // delete till deleteLen and reuse segments for new array if it is possible.
  6290. // 3 steps -
  6291. //1. delete 1st segment (which may be partial delete)
  6292. // 2. delete next n complete segments
  6293. // 3. delete last segment (which again may be partial delete)
  6294. // Step (1) -- WOOB 1116297: When left >= start, step (1) is skipped, resulting in pNewArr->head->left != 0. We need to touch up pNewArr.
  6295. if (startSeg->left < start)
  6296. {
  6297. if (start < startSeg->left + startSeg->length)
  6298. {
  6299. uint32 headDeleteLen = startSeg->left + startSeg->length - start;
  6300. if (startSeg->next)
  6301. {
  6302. // We know the new segment will have a next segment, so allocate it as non-leaf.
  6303. newHeadSeg = SparseArraySegment<T>::template AllocateSegmentImpl<false>(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
  6304. }
  6305. else
  6306. {
  6307. newHeadSeg = SparseArraySegment<T>::AllocateSegment(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
  6308. }
  6309. newHeadSeg = SparseArraySegment<T>::CopySegment(recycler, newHeadSeg, 0, startSeg, start, headDeleteLen);
  6310. newHeadSeg->next = nullptr;
  6311. *prevNewHeadSeg = newHeadSeg;
  6312. prevNewHeadSeg = &newHeadSeg->next;
  6313. startSeg->Truncate(start);
  6314. }
  6315. savePrev = startSeg;
  6316. prevPrevSeg = prevSeg;
  6317. prevSeg = &startSeg->next;
  6318. startSeg = SparseArraySegment<T>::From(startSeg->next);
  6319. }
  6320. // Step (2) first we should do a hard copy if we have an inline head Segment
  6321. else if (hasInlineSegment && nullptr != startSeg)
  6322. {
  6323. // start should be in between left and left + length
  6324. if (startSeg->left <= start && start < startSeg->left + startSeg->length)
  6325. {
  6326. uint32 headDeleteLen = startSeg->left + startSeg->length - start;
  6327. if (startSeg->next)
  6328. {
  6329. // We know the new segment will have a next segment, so allocate it as non-leaf.
  6330. newHeadSeg = SparseArraySegment<T>::template AllocateSegmentImpl<false>(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
  6331. }
  6332. else
  6333. {
  6334. newHeadSeg = SparseArraySegment<T>::AllocateSegment(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
  6335. }
  6336. newHeadSeg = SparseArraySegment<T>::CopySegment(recycler, newHeadSeg, 0, startSeg, start, headDeleteLen);
  6337. *prevNewHeadSeg = newHeadSeg;
  6338. prevNewHeadSeg = &newHeadSeg->next;
  6339. // Remove the entire segment from the original array
  6340. *prevSeg = startSeg->next;
  6341. pArr->ClearElements(startSeg, 0);
  6342. startSeg = SparseArraySegment<T>::From(startSeg->next);
  6343. }
  6344. // if we have an inline head segment with 0 elements, remove it
  6345. else if (startSeg->left == 0 && startSeg->length == 0)
  6346. {
  6347. Assert(startSeg->size != 0);
  6348. *prevSeg = startSeg->next;
  6349. startSeg = SparseArraySegment<T>::From(startSeg->next);
  6350. }
  6351. }
  6352. // Step (2) proper
  6353. SparseArraySegmentBase *temp = nullptr;
  6354. while (startSeg && (startSeg->left + startSeg->length) <= limit)
  6355. {
  6356. temp = startSeg->next;
  6357. // move that entire segment to new array
  6358. startSeg->left = startSeg->left - start;
  6359. startSeg->next = nullptr;
  6360. *prevNewHeadSeg = startSeg;
  6361. prevNewHeadSeg = &startSeg->next;
  6362. // Remove the entire segment from the original array
  6363. *prevSeg = temp;
  6364. startSeg = (SparseArraySegment<T>*)temp;
  6365. }
  6366. // Step(2) above could delete the original head segment entirely, causing current head not
  6367. // starting from 0. Then if any of the following throw, we have a corrupted array. Need
  6368. // protection here.
  6369. bool dummyHeadNodeInserted = false;
  6370. if (!savePrev && (!startSeg || startSeg->left != 0))
  6371. {
  6372. Assert(pArr->head == startSeg);
  6373. pArr->EnsureHeadStartsFromZero<T>(recycler);
  6374. Assert(pArr->head && pArr->head->next == startSeg);
  6375. savePrev = pArr->head;
  6376. prevPrevSeg = prevSeg;
  6377. prevSeg = &pArr->head->next;
  6378. dummyHeadNodeInserted = true;
  6379. }
  6380. // Step (3)
  6381. if (startSeg && (startSeg->left < limit))
  6382. {
  6383. // copy the first part of the last segment to be deleted to new array
  6384. uint32 headDeleteLen = start + deleteLen - startSeg->left ;
  6385. newHeadSeg = SparseArraySegment<T>::AllocateSegment(recycler, startSeg->left - start, headDeleteLen, (SparseArraySegmentBase *)nullptr);
  6386. newHeadSeg = SparseArraySegment<T>::CopySegment(recycler, newHeadSeg, startSeg->left - start, startSeg, startSeg->left, headDeleteLen);
  6387. newHeadSeg->next = nullptr;
  6388. *prevNewHeadSeg = newHeadSeg;
  6389. prevNewHeadSeg = &newHeadSeg->next;
  6390. // move the last segment
  6391. MoveArray(startSeg->elements, startSeg->elements + headDeleteLen, startSeg->length - headDeleteLen);
  6392. startSeg->left = startSeg->left + headDeleteLen; // We are moving the left ahead to point to the right index
  6393. startSeg->length = startSeg->length - headDeleteLen;
  6394. startSeg->CheckLengthvsSize();
  6395. startSeg->Truncate(startSeg->left + startSeg->length);
  6396. startSeg->EnsureSizeInBound(); // Just truncated, size might exceed next.left
  6397. }
  6398. if (startSeg && ((startSeg->left - deleteLen + insertLen) == 0) && dummyHeadNodeInserted)
  6399. {
  6400. Assert(start + insertLen == 0);
  6401. // Remove the dummy head node to preserve array consistency.
  6402. pArr->head = startSeg;
  6403. savePrev = nullptr;
  6404. prevSeg = &pArr->head;
  6405. }
  6406. while (startSeg)
  6407. {
  6408. startSeg->left = startSeg->left - deleteLen + insertLen ;
  6409. if (startSeg->next == nullptr)
  6410. {
  6411. startSeg->EnsureSizeInBound();
  6412. }
  6413. startSeg = SparseArraySegment<T>::From(startSeg->next);
  6414. }
  6415. }
  6416. }
  6417. // The size of pnewArr head allocated in above step 1 might exceed next.left concatenated in step 2/3.
  6418. pnewArr->head->EnsureSizeInBound();
  6419. if (savePrev)
  6420. {
  6421. savePrev->EnsureSizeInBound();
  6422. }
  6423. // insert elements
  6424. if (insertLen > 0)
  6425. {
  6426. Assert(!JavascriptNativeIntArray::Is(pArr) && !JavascriptNativeFloatArray::Is(pArr));
  6427. // InsertPhase
  6428. SparseArraySegment<T> *segInsert = nullptr;
  6429. // see if we are just about the right of the previous segment
  6430. Assert(!savePrev || savePrev->left <= start);
  6431. if (savePrev && (start - savePrev->left < savePrev->size))
  6432. {
  6433. segInsert = (SparseArraySegment<T>*)savePrev;
  6434. uint32 spaceLeft = segInsert->size - (start - segInsert->left);
  6435. if(spaceLeft < insertLen)
  6436. {
  6437. SparseArraySegment<T> *oldSegInsert = segInsert;
  6438. bool isInlineSegment = JavascriptArray::IsInlineSegment(segInsert, pArr);
  6439. if (!segInsert->next)
  6440. {
  6441. segInsert = segInsert->GrowByMin(recycler, insertLen - spaceLeft);
  6442. }
  6443. else
  6444. {
  6445. segInsert = segInsert->GrowByMinMax(recycler, insertLen - spaceLeft, segInsert->next->left - segInsert->left - segInsert->size);
  6446. }
  6447. if (isInlineSegment)
  6448. {
  6449. pArr->ClearElements(oldSegInsert, 0);
  6450. }
  6451. }
  6452. *prevPrevSeg = segInsert;
  6453. segInsert->length = start + insertLen - segInsert->left;
  6454. segInsert->CheckLengthvsSize();
  6455. }
  6456. else
  6457. {
  6458. segInsert = SparseArraySegment<T>::AllocateSegment(recycler, start, insertLen, *prevSeg);
  6459. segInsert->next = *prevSeg;
  6460. *prevSeg = segInsert;
  6461. savePrev = segInsert;
  6462. }
  6463. uint32 relativeStart = start - segInsert->left;
  6464. // inserted elements starts at argument 3 of splice(start, deleteNumber, insertelem1, insertelem2, insertelem3, ...);
  6465. CopyArray(segInsert->elements + relativeStart, insertLen,
  6466. reinterpret_cast<const T*>(insertArgs), insertLen);
  6467. }
  6468. }
  6469. Var JavascriptArray::TryArraySplice(JavascriptArray* pArr, uint32 start, uint32 len, uint32 deleteLen,
  6470. Var* insertArgs, uint32 insertLen, ScriptContext *scriptContext)
  6471. {
  6472. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6473. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  6474. Assert(pArr != nullptr);
  6475. RecyclableObject* newObj = nullptr;
  6476. Recycler *recycler = scriptContext->GetRecycler();
  6477. ::Math::RecordOverflowPolicy newLenOverflow;
  6478. uint32 newLen = UInt32Math::Add(len - deleteLen, insertLen, newLenOverflow); // new length of the array after splice
  6479. // If we have missing values then convert to not native array for now
  6480. // In future, we could support this scenario.
  6481. if (deleteLen == insertLen)
  6482. {
  6483. JS_REENTRANT(jsReentLock, pArr->FillFromPrototypes(start, start + deleteLen));
  6484. }
  6485. else if (len)
  6486. {
  6487. JS_REENTRANT(jsReentLock, pArr->FillFromPrototypes(start, len));
  6488. }
  6489. //
  6490. // If newLen overflowed, pre-process to prevent pushing sparse array segments or elements out of
  6491. // max array length, which would result in tons of index overflow and difficult to fix.
  6492. //
  6493. if (newLenOverflow.HasOverflowed())
  6494. {
  6495. pArr = EnsureNonNativeArray(pArr);
  6496. BigIndex dstIndex = MaxArrayLength;
  6497. uint32 maxInsertLen = MaxArrayLength - start;
  6498. if (insertLen > maxInsertLen)
  6499. {
  6500. // Copy overflowing insertArgs to properties
  6501. for (uint32 i = maxInsertLen; i < insertLen; i++)
  6502. {
  6503. pArr->GenericDirectSetItemAt(dstIndex, insertArgs[i]);
  6504. ++dstIndex;
  6505. }
  6506. insertLen = maxInsertLen; // update
  6507. // Truncate elements on the right to properties
  6508. if (start + deleteLen < len)
  6509. {
  6510. pArr->TruncateToProperties(dstIndex, start + deleteLen);
  6511. }
  6512. }
  6513. else
  6514. {
  6515. // Truncate would-overflow elements to properties
  6516. pArr->TruncateToProperties(dstIndex, MaxArrayLength - insertLen + deleteLen);
  6517. }
  6518. len = pArr->length; // update
  6519. newLen = len - deleteLen + insertLen;
  6520. Assert(newLen == MaxArrayLength);
  6521. }
  6522. if (insertArgs)
  6523. {
  6524. pArr = EnsureNonNativeArray(pArr);
  6525. }
  6526. bool isIntArray = false;
  6527. bool isFloatArray = false;
  6528. bool isBuiltinArrayCtor = true;
  6529. JavascriptArray *newArr = nullptr;
  6530. // Just dump the segment map on splice (before any possible allocation and throw)
  6531. pArr->ClearSegmentMap();
  6532. // If the source object is an Array exotic object (Array.isArray) we should try to load the constructor property
  6533. // and use it to construct the return object.
  6534. JS_REENTRANT_NO_MUTATE(jsReentLock, newObj = ArraySpeciesCreate(pArr, deleteLen, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor));
  6535. if (newObj != nullptr)
  6536. {
  6537. pArr = EnsureNonNativeArray(pArr);
  6538. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  6539. newArr = JavascriptOperators::TryFromVar<JavascriptArray>(newObj);
  6540. if (newArr)
  6541. {
  6542. #if ENABLE_COPYONACCESS_ARRAY
  6543. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  6544. #endif
  6545. SET_SECOND_OBJECT_FOR_MUTATION(jsReentLock, newArr);
  6546. }
  6547. }
  6548. else
  6549. // This is the ES5 case, pArr['constructor'] doesn't exist, or pArr['constructor'] is the builtin Array constructor
  6550. {
  6551. pArr->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
  6552. newArr = CreateNewArrayHelper(deleteLen, isIntArray, isFloatArray, pArr, scriptContext);
  6553. #if ENABLE_COPYONACCESS_ARRAY
  6554. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  6555. #endif
  6556. }
  6557. // If return object is a JavascriptArray, we can use all the array splice helpers
  6558. if (newArr && isBuiltinArrayCtor && len == pArr->length)
  6559. {
  6560. // Code below has potential to throw due to OOM or SO. Just FailFast on those cases
  6561. AutoDisableInterrupt failFastOnError(scriptContext->GetThreadContext());
  6562. // Array has a single segment (need not start at 0) and splice start lies in the range
  6563. // of that segment we optimize splice - Fast path.
  6564. if (pArr->IsSingleSegmentArray() && pArr->head->HasIndex(start))
  6565. {
  6566. SparseArraySegmentBase *oldHead = pArr->head;
  6567. bool isInlineSegment = JavascriptArray::IsInlineSegment(oldHead, pArr);
  6568. if (isIntArray)
  6569. {
  6570. ArraySegmentSpliceHelper<int32>(newArr,
  6571. SparseArraySegment<int32>::From(pArr->head),
  6572. SparseArraySegment<int32>::AddressFrom(&pArr->head),
  6573. start, deleteLen, insertArgs, insertLen, recycler);
  6574. }
  6575. else if (isFloatArray)
  6576. {
  6577. ArraySegmentSpliceHelper<double>(newArr,
  6578. SparseArraySegment<double>::From(pArr->head),
  6579. SparseArraySegment<double>::AddressFrom(&pArr->head),
  6580. start, deleteLen, insertArgs, insertLen, recycler);
  6581. }
  6582. else
  6583. {
  6584. ArraySegmentSpliceHelper<Var>(newArr,
  6585. SparseArraySegment<Var>::From(pArr->head),
  6586. SparseArraySegment<Var>::AddressFrom(&pArr->head),
  6587. start, deleteLen, insertArgs, insertLen, recycler);
  6588. }
  6589. if (isInlineSegment && oldHead != pArr->head)
  6590. {
  6591. pArr->ClearElements(oldHead, 0);
  6592. }
  6593. // Since the start index is within the bounds of the original array's head segment, it will not acquire any new
  6594. // missing values. If the original array had missing values in the head segment, some of them may have been
  6595. // copied into the array that will be returned; otherwise, the array that is returned will also not have any
  6596. // missing values.
  6597. newArr->SetHasNoMissingValues(pArr->HasNoMissingValues());
  6598. }
  6599. else
  6600. {
  6601. if (isIntArray)
  6602. {
  6603. ArraySpliceHelper<int32>(newArr, pArr, start, deleteLen, insertArgs, insertLen, scriptContext);
  6604. }
  6605. else if (isFloatArray)
  6606. {
  6607. ArraySpliceHelper<double>(newArr, pArr, start, deleteLen, insertArgs, insertLen, scriptContext);
  6608. }
  6609. else
  6610. {
  6611. ArraySpliceHelper<Var>(newArr, pArr, start, deleteLen, insertArgs, insertLen, scriptContext);
  6612. }
  6613. // This function currently does not track missing values in the head segment if there are multiple segments
  6614. pArr->SetHasNoMissingValues(false);
  6615. newArr->SetHasNoMissingValues(false);
  6616. }
  6617. if (isIntArray)
  6618. {
  6619. pArr->EnsureHeadStartsFromZero<int32>(recycler);
  6620. newArr->EnsureHeadStartsFromZero<int32>(recycler);
  6621. }
  6622. else if (isFloatArray)
  6623. {
  6624. pArr->EnsureHeadStartsFromZero<double>(recycler);
  6625. newArr->EnsureHeadStartsFromZero<double>(recycler);
  6626. }
  6627. else
  6628. {
  6629. pArr->EnsureHeadStartsFromZero<Var>(recycler);
  6630. newArr->EnsureHeadStartsFromZero<Var>(recycler);
  6631. }
  6632. pArr->InvalidateLastUsedSegment();
  6633. // it is possible for valueOf accessors for the start or deleteLen
  6634. // arguments to modify the size of the array. Since the resulting size of the array
  6635. // is based on the cached value of length, this might lead to us having to trim
  6636. // excess array segments at the end of the splice operation, which SetLength() will do.
  6637. // However, this is also slower than performing the simple length assignment, so we only
  6638. // do it if we can detect the array length changing.
  6639. if (pArr->length != len)
  6640. {
  6641. pArr->SetLength(newLen);
  6642. }
  6643. else
  6644. {
  6645. pArr->length = newLen;
  6646. }
  6647. if (newArr->length != deleteLen)
  6648. {
  6649. newArr->SetLength(deleteLen);
  6650. }
  6651. else
  6652. {
  6653. newArr->length = deleteLen;
  6654. }
  6655. failFastOnError.Completed();
  6656. newArr->InvalidateLastUsedSegment();
  6657. #ifdef VALIDATE_ARRAY
  6658. newArr->ValidateArray();
  6659. pArr->ValidateArray();
  6660. #endif
  6661. if (newLenOverflow.HasOverflowed())
  6662. {
  6663. // ES5 15.4.4.12 16: If new len overflowed, SetLength throws
  6664. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  6665. }
  6666. return newArr;
  6667. }
  6668. if (newLenOverflow.HasOverflowed())
  6669. {
  6670. JS_REENTRANT_UNLOCK(jsReentLock, return ObjectSpliceHelper<uint64>(pArr, len, start, deleteLen, insertArgs, insertLen, scriptContext, newObj));
  6671. }
  6672. else // Use uint32 version if no overflow
  6673. {
  6674. JS_REENTRANT_UNLOCK(jsReentLock, return ObjectSpliceHelper<uint32>(pArr, len, start, deleteLen, insertArgs, insertLen, scriptContext, newObj));
  6675. }
  6676. }
  6677. template<typename T>
  6678. RecyclableObject* JavascriptArray::ObjectSpliceHelper(RecyclableObject* pObj, T len, T start,
  6679. T deleteLen, Var* insertArgs, uint32 insertLen, ScriptContext *scriptContext, RecyclableObject* pNewObj)
  6680. {
  6681. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6682. SETOBJECT_FOR_MUTATION(jsReentLock, pObj);
  6683. JavascriptArray *pnewArr = nullptr;
  6684. if (pNewObj == nullptr)
  6685. {
  6686. JS_REENTRANT_NO_MUTATE(jsReentLock, pNewObj = ArraySpeciesCreate(pObj, deleteLen, scriptContext));
  6687. if (pNewObj == nullptr)
  6688. {
  6689. if (deleteLen > UINT_MAX)
  6690. {
  6691. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  6692. }
  6693. pnewArr = scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(deleteLen));
  6694. pnewArr->EnsureHead<Var>();
  6695. pNewObj = pnewArr;
  6696. }
  6697. }
  6698. pnewArr = JavascriptOperators::TryFromVar<JavascriptArray>(pNewObj);
  6699. if (pnewArr)
  6700. {
  6701. #if ENABLE_COPYONACCESS_ARRAY
  6702. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pnewArr);
  6703. #endif
  6704. SET_SECOND_OBJECT_FOR_MUTATION(jsReentLock, pnewArr);
  6705. }
  6706. // copy elements to delete to new array
  6707. if (pnewArr != nullptr)
  6708. {
  6709. for (uint32 i = 0; i < deleteLen; i++)
  6710. {
  6711. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(pObj, start + i));
  6712. if (hasItem)
  6713. {
  6714. JS_REENTRANT(jsReentLock, Var element = JavascriptOperators::GetItem(pObj, start + i, scriptContext));
  6715. pnewArr->SetItem(i, element, PropertyOperation_None);
  6716. }
  6717. }
  6718. }
  6719. else
  6720. {
  6721. BigIndex k = 0u;
  6722. for (T i = 0u; i < deleteLen; i++)
  6723. {
  6724. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(pObj, start + i));
  6725. if (hasItem)
  6726. {
  6727. Var element = nullptr;
  6728. JS_REENTRANT(jsReentLock, element = JavascriptOperators::GetItem(pObj, start + i, scriptContext),
  6729. ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(pNewObj, k, element), scriptContext, k));
  6730. }
  6731. ++k;
  6732. }
  6733. }
  6734. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.splice"));
  6735. // Now we need reserve room if it is necessary
  6736. if (insertLen > deleteLen) // Might overflow max array length
  6737. {
  6738. // Unshift [start + deleteLen, len) to start + insertLen
  6739. JS_REENTRANT(jsReentLock, Unshift<BigIndex, T>(pObj, start + insertLen, start + deleteLen, len, scriptContext));
  6740. }
  6741. else if (insertLen < deleteLen) // Won't overflow max array length
  6742. {
  6743. T j = 0;
  6744. for (T i = start + deleteLen; i < len; i++)
  6745. {
  6746. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(pObj, i));
  6747. if (hasItem)
  6748. {
  6749. Var element = nullptr;
  6750. JS_REENTRANT(jsReentLock, element = JavascriptOperators::GetItem(pObj, i, scriptContext),
  6751. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(pObj, pObj, start + insertLen + j, element, scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  6752. }
  6753. else
  6754. {
  6755. JS_REENTRANT(jsReentLock,
  6756. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(pObj, start + insertLen + j, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  6757. }
  6758. j++;
  6759. }
  6760. // Clean up the rest
  6761. for (T i = len; i > len - deleteLen + insertLen; i--)
  6762. {
  6763. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(pObj, i - 1, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  6764. }
  6765. }
  6766. if (insertLen > 0)
  6767. {
  6768. T dstIndex = start; // insert index might overflow max array length
  6769. for (uint32 i = 0; i < insertLen; i++)
  6770. {
  6771. JS_REENTRANT(jsReentLock,
  6772. h.ThrowTypeErrorOnFailure(IndexTrace<BigIndex>::SetItem(pObj, dstIndex, insertArgs[i], PropertyOperation_ThrowIfNotExtensible)));
  6773. ++dstIndex;
  6774. }
  6775. }
  6776. // Set up new length
  6777. T newLen = T(len - deleteLen) + insertLen;
  6778. JS_REENTRANT(jsReentLock,
  6779. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(pObj, pObj, PropertyIds::length, IndexTrace<BigIndex>::ToNumber(newLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)),
  6780. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(pNewObj, pNewObj, PropertyIds::length, IndexTrace<BigIndex>::ToNumber(deleteLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  6781. #ifdef VALIDATE_ARRAY
  6782. if (pnewArr)
  6783. {
  6784. pnewArr->ValidateArray();
  6785. }
  6786. #endif
  6787. return pNewObj;
  6788. }
  6789. Var JavascriptArray::EntryToLocaleString(RecyclableObject* function, CallInfo callInfo, ...)
  6790. {
  6791. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  6792. ARGUMENTS(args, callInfo);
  6793. ScriptContext* scriptContext = function->GetScriptContext();
  6794. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6795. SETOBJECT_FOR_MUTATION(jsReentLock, args[0]);
  6796. Assert(!(callInfo.Flags & CallFlags_New));
  6797. if (args.Info.Count == 0)
  6798. {
  6799. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedObject, _u("Array.prototype.toLocaleString"));
  6800. }
  6801. if (JavascriptArray::IsDirectAccessArray(args[0]))
  6802. {
  6803. JavascriptArray* arr = JavascriptArray::UnsafeFromVar(args[0]);
  6804. JS_REENTRANT_UNLOCK(jsReentLock, return ToLocaleString(arr, scriptContext));
  6805. }
  6806. else
  6807. {
  6808. if (TypedArrayBase::IsDetachedTypedArray(args[0]))
  6809. {
  6810. JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("Array.prototype.toLocalString"));
  6811. }
  6812. RecyclableObject* obj = nullptr;
  6813. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  6814. {
  6815. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.toLocaleString"));
  6816. }
  6817. JS_REENTRANT_UNLOCK(jsReentLock, return ToLocaleString(obj, scriptContext));
  6818. }
  6819. }
  6820. //
  6821. // Unshift object elements [start, end) to toIndex, asserting toIndex > start.
  6822. //
  6823. template<typename T, typename P>
  6824. void JavascriptArray::Unshift(RecyclableObject* obj, const T& toIndex, P start, P end, ScriptContext* scriptContext)
  6825. {
  6826. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6827. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  6828. typedef IndexTrace<T> index_trace;
  6829. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.unshift"));
  6830. if (start < end)
  6831. {
  6832. T newEnd = (end - start - 1);// newEnd - 1
  6833. T dst = toIndex + newEnd;
  6834. for (P i = end; i > start; --i)
  6835. {
  6836. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, i - 1));
  6837. if (hasItem)
  6838. {
  6839. Var element = nullptr;
  6840. JS_REENTRANT(jsReentLock, element = JavascriptOperators::GetItem(obj, i - 1, scriptContext),
  6841. h.ThrowTypeErrorOnFailure(index_trace::SetItem(obj, dst, element, PropertyOperation_ThrowIfNotExtensible)));
  6842. }
  6843. else
  6844. {
  6845. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(index_trace::DeleteItem(obj, dst, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  6846. }
  6847. --dst;
  6848. }
  6849. }
  6850. }
  6851. template<typename T>
  6852. void JavascriptArray::GrowArrayHeadHelperForUnshift(JavascriptArray* pArr, uint32 unshiftElements, ScriptContext * scriptContext)
  6853. {
  6854. SparseArraySegmentBase* nextToHeadSeg = pArr->head->next;
  6855. Recycler* recycler = scriptContext->GetRecycler();
  6856. SparseArraySegmentBase *oldHead = pArr->head;
  6857. bool isInlineSegment = JavascriptArray::IsInlineSegment(oldHead, pArr);
  6858. if (nextToHeadSeg == nullptr)
  6859. {
  6860. pArr->EnsureHead<T>();
  6861. pArr->head = SparseArraySegment<T>::From(pArr->head)->GrowByMin(recycler, unshiftElements);
  6862. }
  6863. else
  6864. {
  6865. pArr->head = SparseArraySegment<T>::From(pArr->head)->GrowByMinMax(recycler, unshiftElements, ((nextToHeadSeg->left + unshiftElements) - pArr->head->left - pArr->head->size));
  6866. }
  6867. if (isInlineSegment)
  6868. {
  6869. pArr->ClearElements(oldHead, 0);
  6870. }
  6871. }
  6872. template<typename T>
  6873. void JavascriptArray::UnshiftHelper(JavascriptArray* pArr, uint32 unshiftElements, Js::Var * elements)
  6874. {
  6875. SparseArraySegment<T>* head = SparseArraySegment<T>::From(pArr->head);
  6876. // Make enough room in the head segment to insert new elements at the front
  6877. MoveArray(head->elements + unshiftElements, head->elements, pArr->head->length);
  6878. uint32 oldHeadLength = head->length;
  6879. head->length += unshiftElements;
  6880. head->CheckLengthvsSize();
  6881. /* Set head segment as the last used segment */
  6882. pArr->InvalidateLastUsedSegment();
  6883. bool hasNoMissingValues = pArr->HasNoMissingValues();
  6884. /* Set HasNoMissingValues to false -> Since we shifted elements right, we might have missing values after the memmove */
  6885. if(unshiftElements > oldHeadLength)
  6886. {
  6887. pArr->SetHasNoMissingValues(false);
  6888. }
  6889. #if ENABLE_PROFILE_INFO
  6890. pArr->FillFromArgs(unshiftElements, 0, elements, nullptr, true/*dontCreateNewArray*/);
  6891. #else
  6892. pArr->FillFromArgs(unshiftElements, 0, elements, true/*dontCreateNewArray*/);
  6893. #endif
  6894. // Setting back to the old value
  6895. pArr->SetHasNoMissingValues(hasNoMissingValues);
  6896. }
  6897. Var JavascriptArray::EntryUnshift(RecyclableObject* function, CallInfo callInfo, ...)
  6898. {
  6899. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  6900. ARGUMENTS(args, callInfo);
  6901. ScriptContext* scriptContext = function->GetScriptContext();
  6902. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6903. SETOBJECT_FOR_MUTATION(jsReentLock, args[0]);
  6904. Assert(!(callInfo.Flags & CallFlags_New));
  6905. Var res = scriptContext->GetLibrary()->GetUndefined();
  6906. if (args.Info.Count == 0)
  6907. {
  6908. return res;
  6909. }
  6910. JavascriptArray * pArr = nullptr;
  6911. if (JavascriptArray::Is(args[0])
  6912. && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
  6913. {
  6914. #if ENABLE_COPYONACCESS_ARRAY
  6915. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
  6916. #endif
  6917. pArr = JavascriptArray::FromVar(args[0]);
  6918. }
  6919. uint32 unshiftElements = args.Info.Count - 1;
  6920. // forceCheckProtoChain - since the array expand to accommodate new items thus we have to check if we have accessor on the proto chain.
  6921. bool useNoSideEffectUnshift = pArr != nullptr && (unshiftElements == 0 || !HasAnyES5ArrayInPrototypeChain(pArr, true /*forceCheckProtoChain*/));
  6922. if (useNoSideEffectUnshift)
  6923. {
  6924. if (unshiftElements > 0)
  6925. {
  6926. uint32 length = pArr->length;
  6927. if (pArr->IsFillFromPrototypes())
  6928. {
  6929. pArr->FillFromPrototypes(0, pArr->length); // We need find all missing value from [[proto]] object
  6930. }
  6931. // As we have already established that the FillFromPrototype should not change the bound of the array.
  6932. if (length != pArr->length)
  6933. {
  6934. Js::Throw::FatalInternalError();
  6935. }
  6936. // Pre-process: truncate overflowing elements to properties
  6937. bool newLenOverflowed = false;
  6938. uint32 maxLen = MaxArrayLength - unshiftElements;
  6939. if (pArr->length > maxLen)
  6940. {
  6941. newLenOverflowed = true;
  6942. // Ensure the array is non-native when overflow happens
  6943. EnsureNonNativeArray(pArr);
  6944. pArr->TruncateToProperties(MaxArrayLength, maxLen);
  6945. Assert(pArr->length + unshiftElements == MaxArrayLength);
  6946. }
  6947. pArr->ClearSegmentMap(); // Dump segmentMap on unshift (before any possible allocation and throw)
  6948. Assert(pArr->length <= MaxArrayLength - unshiftElements);
  6949. bool isIntArray = false;
  6950. bool isFloatArray = false;
  6951. if (JavascriptNativeIntArray::Is(pArr))
  6952. {
  6953. isIntArray = true;
  6954. }
  6955. else if (JavascriptNativeFloatArray::Is(pArr))
  6956. {
  6957. isFloatArray = true;
  6958. }
  6959. // If we need to grow head segment and there is already a next segment, then allocate the new head segment upfront
  6960. // If there is OOM in array allocation, then array consistency is maintained.
  6961. if (pArr->head->size < pArr->head->length + unshiftElements)
  6962. {
  6963. if (isIntArray)
  6964. {
  6965. GrowArrayHeadHelperForUnshift<int32>(pArr, unshiftElements, scriptContext);
  6966. }
  6967. else if (isFloatArray)
  6968. {
  6969. GrowArrayHeadHelperForUnshift<double>(pArr, unshiftElements, scriptContext);
  6970. }
  6971. else
  6972. {
  6973. GrowArrayHeadHelperForUnshift<Var>(pArr, unshiftElements, scriptContext);
  6974. }
  6975. }
  6976. SparseArraySegmentBase* renumberSeg = pArr->head->next;
  6977. while (renumberSeg)
  6978. {
  6979. renumberSeg->left += unshiftElements;
  6980. if (renumberSeg->next == nullptr)
  6981. {
  6982. // last segment can shift its left + size beyond MaxArrayLength, so truncate if so
  6983. renumberSeg->EnsureSizeInBound();
  6984. }
  6985. renumberSeg = renumberSeg->next;
  6986. }
  6987. try
  6988. {
  6989. if (isIntArray)
  6990. {
  6991. UnshiftHelper<int32>(pArr, unshiftElements, args.Values);
  6992. }
  6993. else if (isFloatArray)
  6994. {
  6995. UnshiftHelper<double>(pArr, unshiftElements, args.Values);
  6996. }
  6997. else
  6998. {
  6999. UnshiftHelper<Var>(pArr, unshiftElements, args.Values);
  7000. }
  7001. }
  7002. catch (...)
  7003. {
  7004. Js::Throw::FatalInternalError();
  7005. }
  7006. pArr->InvalidateLastUsedSegment();
  7007. pArr->length += unshiftElements;
  7008. #ifdef VALIDATE_ARRAY
  7009. pArr->ValidateArray();
  7010. #endif
  7011. if (newLenOverflowed) // ES5: throw if new "length" exceeds max array length
  7012. {
  7013. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  7014. }
  7015. }
  7016. res = JavascriptNumber::ToVar(pArr->length, scriptContext);
  7017. }
  7018. else
  7019. {
  7020. RecyclableObject* dynamicObject = nullptr;
  7021. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &dynamicObject))
  7022. {
  7023. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.unshift"));
  7024. }
  7025. JS_REENTRANT(jsReentLock, BigIndex length = OP_GetLength(dynamicObject, scriptContext));
  7026. if (unshiftElements > 0)
  7027. {
  7028. uint32 MaxSpaceUint32 = MaxArrayLength - unshiftElements;
  7029. // Note: end will always be a smallIndex either it is less than length in which case it is MaxSpaceUint32
  7030. // or MaxSpaceUint32 is greater than length meaning length is a uint32 number
  7031. BigIndex end = length > MaxSpaceUint32 ? MaxSpaceUint32 : length;
  7032. if (end < length)
  7033. {
  7034. // Unshift [end, length) to MaxArrayLength
  7035. // MaxArrayLength + (length - MaxSpaceUint32 - 1) = length + unshiftElements -1
  7036. if (length.IsSmallIndex())
  7037. {
  7038. JS_REENTRANT(jsReentLock, Unshift<BigIndex>(dynamicObject, MaxArrayLength, end.GetSmallIndex(), length.GetSmallIndex(), scriptContext));
  7039. }
  7040. else
  7041. {
  7042. JS_REENTRANT(jsReentLock, Unshift<BigIndex, uint64>(dynamicObject, MaxArrayLength, (uint64)end.GetSmallIndex(), length.GetBigIndex(), scriptContext));
  7043. }
  7044. }
  7045. // Unshift [0, end) to unshiftElements
  7046. // unshiftElements + (MaxSpaceUint32 - 0 - 1) = MaxArrayLength -1 therefore this unshift covers up to MaxArrayLength - 1
  7047. JS_REENTRANT(jsReentLock, Unshift<uint32>(dynamicObject, unshiftElements, (uint32)0, end.GetSmallIndex(), scriptContext));
  7048. for (uint32 i = 0; i < unshiftElements; i++)
  7049. {
  7050. JS_REENTRANT(jsReentLock,
  7051. JavascriptOperators::SetItem(dynamicObject, dynamicObject, i, args[i + 1], scriptContext, PropertyOperation_ThrowIfNotExtensible, true));
  7052. }
  7053. }
  7054. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.unshift"));
  7055. //ES6 - update 'length' even if unshiftElements == 0;
  7056. BigIndex newLen = length + unshiftElements;
  7057. res = JavascriptNumber::ToVar(newLen.IsSmallIndex() ? newLen.GetSmallIndex() : newLen.GetBigIndex(), scriptContext);
  7058. JS_REENTRANT(jsReentLock,
  7059. BOOL setLength = JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, res, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  7060. h.ThrowTypeErrorOnFailure(setLength);
  7061. }
  7062. return res;
  7063. }
  7064. Var JavascriptArray::EntryToString(RecyclableObject* function, CallInfo callInfo, ...)
  7065. {
  7066. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7067. ARGUMENTS(args, callInfo);
  7068. ScriptContext* scriptContext = function->GetScriptContext();
  7069. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7070. Assert(!(callInfo.Flags & CallFlags_New));
  7071. if (args.Info.Count == 0)
  7072. {
  7073. JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedObject);
  7074. }
  7075. // ES5 15.4.4.2: call join, or built-in Object.prototype.toString
  7076. RecyclableObject* obj = nullptr;
  7077. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  7078. {
  7079. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.toString"));
  7080. }
  7081. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  7082. // In ES5 we could be calling a user defined join, even on array. We must [[Get]] join at runtime.
  7083. JS_REENTRANT(jsReentLock, Var join = JavascriptOperators::GetPropertyNoCache(obj, PropertyIds::join, scriptContext));
  7084. if (JavascriptConversion::IsCallable(join))
  7085. {
  7086. RecyclableObject* func = RecyclableObject::FromVar(join);
  7087. // We need to record implicit call here, because marked the Array.toString as no side effect,
  7088. // but if we call user code here which may have side effect
  7089. ThreadContext * threadContext = scriptContext->GetThreadContext();
  7090. JS_REENTRANT(jsReentLock,
  7091. Var result = threadContext->ExecuteImplicitCall(func, ImplicitCall_ToPrimitive, [=]() -> Js::Var
  7092. {
  7093. // Stack object should have a pre-op bail on implicit call. We shouldn't see them here.
  7094. Assert(!ThreadContext::IsOnStack(obj));
  7095. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7096. CallFlags flags = CallFlags_Value;
  7097. return CALL_FUNCTION(threadContext, func, CallInfo(flags, 1), obj);
  7098. }));
  7099. if(!result)
  7100. {
  7101. // There was an implicit call and implicit calls are disabled. This would typically cause a bailout.
  7102. Assert(threadContext->IsDisableImplicitCall());
  7103. result = scriptContext->GetLibrary()->GetNull();
  7104. }
  7105. return result;
  7106. }
  7107. else
  7108. {
  7109. // call built-in Object.prototype.toString
  7110. JS_REENTRANT_UNLOCK(jsReentLock,
  7111. return CALL_ENTRYPOINT(scriptContext->GetThreadContext(), JavascriptObject::EntryToString, function, CallInfo(1), obj));
  7112. }
  7113. }
  7114. #if DEBUG
  7115. BOOL JavascriptArray::GetIndex(const char16* propName, uint32 *pIndex)
  7116. {
  7117. uint32 lu, luDig;
  7118. int32 cch = (int32)wcslen(propName);
  7119. char16* pch = const_cast<char16 *>(propName);
  7120. lu = *pch - '0';
  7121. if (lu > 9)
  7122. return FALSE;
  7123. if (0 == lu)
  7124. {
  7125. *pIndex = 0;
  7126. return 1 == cch;
  7127. }
  7128. while ((luDig = *++pch - '0') < 10)
  7129. {
  7130. // If we overflow 32 bits, ignore the item
  7131. if (lu > 0x19999999)
  7132. return FALSE;
  7133. lu *= 10;
  7134. if(lu > (ULONG_MAX - luDig))
  7135. return FALSE;
  7136. lu += luDig;
  7137. }
  7138. if (pch - propName != cch)
  7139. return FALSE;
  7140. if (lu == JavascriptArray::InvalidIndex)
  7141. {
  7142. // 0xFFFFFFFF is not treated as an array index so that the length can be
  7143. // capped at 32 bits.
  7144. return FALSE;
  7145. }
  7146. *pIndex = lu;
  7147. return TRUE;
  7148. }
  7149. #endif
  7150. JavascriptString* JavascriptArray::GetLocaleSeparator(ScriptContext* scriptContext)
  7151. {
  7152. #ifdef ENABLE_GLOBALIZATION
  7153. LCID lcid = GetUserDefaultLCID();
  7154. int count = 0;
  7155. char16 szSeparator[6];
  7156. // According to the document for GetLocaleInfo this is a sufficient buffer size.
  7157. count = GetLocaleInfoW(lcid, LOCALE_SLIST, szSeparator, 5);
  7158. if( !count)
  7159. {
  7160. AssertMsg(FALSE, "GetLocaleInfo failed");
  7161. return scriptContext->GetLibrary()->GetCommaSpaceDisplayString();
  7162. }
  7163. else
  7164. {
  7165. // Append ' ' if necessary
  7166. if( count < 2 || szSeparator[count-2] != ' ')
  7167. {
  7168. szSeparator[count-1] = ' ';
  7169. szSeparator[count] = '\0';
  7170. }
  7171. return JavascriptString::NewCopyBuffer(szSeparator, count, scriptContext);
  7172. }
  7173. #else
  7174. // xplat-todo: Support locale-specific separator
  7175. return scriptContext->GetLibrary()->GetCommaSpaceDisplayString();
  7176. #endif
  7177. }
  7178. template <typename T>
  7179. JavascriptString* JavascriptArray::ToLocaleString(T* arr, ScriptContext* scriptContext)
  7180. {
  7181. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7182. SETOBJECT_FOR_MUTATION(jsReentLock, arr);
  7183. uint32 length = 0;
  7184. TypedArrayBase * typedArray = JavascriptOperators::TryFromVar<Js::TypedArrayBase>(arr);
  7185. if (typedArray)
  7186. {
  7187. // For a TypedArray use the actual length of the array.
  7188. length = typedArray->GetLength();
  7189. }
  7190. else
  7191. {
  7192. //For anything else, use the "length" property if present.
  7193. JS_REENTRANT(jsReentLock, length = ItemTrace<T>::GetLength(arr, scriptContext));
  7194. }
  7195. if (length == 0 || scriptContext->CheckObject(arr))
  7196. {
  7197. return scriptContext->GetLibrary()->GetEmptyString();
  7198. }
  7199. JavascriptString* res = scriptContext->GetLibrary()->GetEmptyString();
  7200. bool pushedObject = false;
  7201. TryFinally([&]()
  7202. {
  7203. scriptContext->PushObject(arr);
  7204. pushedObject = true;
  7205. Var element;
  7206. JS_REENTRANT(jsReentLock, BOOL gotItem = ItemTrace<T>::GetItem(arr, 0, &element, scriptContext));
  7207. if (gotItem)
  7208. {
  7209. JS_REENTRANT(jsReentLock, res = JavascriptArray::ToLocaleStringHelper(element, scriptContext));
  7210. }
  7211. if (length > 1)
  7212. {
  7213. JavascriptString* separator = GetLocaleSeparator(scriptContext);
  7214. for (uint32 i = 1; i < length; i++)
  7215. {
  7216. res = JavascriptString::Concat(res, separator);
  7217. JS_REENTRANT(jsReentLock, gotItem = ItemTrace<T>::GetItem(arr, i, &element, scriptContext));
  7218. if (gotItem)
  7219. {
  7220. JS_REENTRANT(jsReentLock, res = JavascriptString::Concat(res, JavascriptArray::ToLocaleStringHelper(element, scriptContext)));
  7221. }
  7222. }
  7223. }
  7224. },
  7225. [&](bool/*hasException*/)
  7226. {
  7227. if (pushedObject)
  7228. {
  7229. Var top = scriptContext->PopObject();
  7230. AssertMsg(top == arr, "Unmatched operation stack");
  7231. }
  7232. });
  7233. if (res == nullptr)
  7234. {
  7235. res = scriptContext->GetLibrary()->GetEmptyString();
  7236. }
  7237. return res;
  7238. }
  7239. Var JavascriptArray::EntryIsArray(RecyclableObject* function, CallInfo callInfo, ...)
  7240. {
  7241. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7242. ARGUMENTS(args, callInfo);
  7243. ScriptContext* scriptContext = function->GetScriptContext();
  7244. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7245. Assert(!(callInfo.Flags & CallFlags_New));
  7246. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Constructor_isArray);
  7247. if (args.Info.Count < 2)
  7248. {
  7249. return scriptContext->GetLibrary()->GetFalse();
  7250. }
  7251. #if ENABLE_COPYONACCESS_ARRAY
  7252. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[1]);
  7253. #endif
  7254. if (JavascriptOperators::IsArray(args[1]))
  7255. {
  7256. return scriptContext->GetLibrary()->GetTrue();
  7257. }
  7258. return scriptContext->GetLibrary()->GetFalse();
  7259. }
  7260. ///----------------------------------------------------------------------------
  7261. /// Find() calls the given predicate callback on each element of the array, in
  7262. /// order, and returns the first element that makes the predicate return true,
  7263. /// as described in (ES6.0: S22.1.3.8).
  7264. ///----------------------------------------------------------------------------
  7265. Var JavascriptArray::EntryFind(RecyclableObject* function, CallInfo callInfo, ...)
  7266. {
  7267. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7268. ARGUMENTS(args, callInfo);
  7269. ScriptContext* scriptContext = function->GetScriptContext();
  7270. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7271. Assert(!(callInfo.Flags & CallFlags_New));
  7272. if (args.Info.Count == 0)
  7273. {
  7274. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.find"));
  7275. }
  7276. int64 length;
  7277. JavascriptArray * pArr = nullptr;
  7278. RecyclableObject* obj = nullptr;
  7279. JS_REENTRANT_UNLOCK(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.find"), &pArr, &obj, &length));
  7280. return JavascriptArray::FindHelper<false>(pArr, nullptr, obj, length, args, scriptContext);
  7281. }
  7282. template <bool findIndex>
  7283. Var JavascriptArray::FindHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
  7284. {
  7285. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7286. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  7287. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  7288. {
  7289. // typedArrayBase is only non-null if and only if we came here via the TypedArray entrypoint
  7290. if (typedArrayBase != nullptr)
  7291. {
  7292. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, findIndex ? _u("[TypedArray].prototype.findIndex") : _u("[TypedArray].prototype.find"));
  7293. }
  7294. else
  7295. {
  7296. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, findIndex ? _u("Array.prototype.findIndex") : _u("Array.prototype.find"));
  7297. }
  7298. }
  7299. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  7300. Var thisArg;
  7301. if (args.Info.Count > 2)
  7302. {
  7303. thisArg = args[2];
  7304. }
  7305. else
  7306. {
  7307. thisArg = scriptContext->GetLibrary()->GetUndefined();
  7308. }
  7309. // If we came from Array.prototype.find/findIndex and source object is not a JavascriptArray, source could be a TypedArray
  7310. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  7311. {
  7312. typedArrayBase = TypedArrayBase::UnsafeFromVar(obj);
  7313. }
  7314. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7315. CallFlags flags = CallFlags_Value;
  7316. Var element = nullptr;
  7317. Var testResult = nullptr;
  7318. if (pArr)
  7319. {
  7320. Var undefined = scriptContext->GetLibrary()->GetUndefined();
  7321. Assert(length <= UINT_MAX);
  7322. for (uint32 k = 0; k < (uint32)length; k++)
  7323. {
  7324. element = undefined;
  7325. JS_REENTRANT(jsReentLock, pArr->DirectGetItemAtFull(k, &element));
  7326. Var index = JavascriptNumber::ToVar(k, scriptContext);
  7327. JS_REENTRANT(jsReentLock,
  7328. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7329. element,
  7330. index,
  7331. pArr));
  7332. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7333. {
  7334. return findIndex ? index : element;
  7335. }
  7336. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  7337. // we will process the rest of the array elements like an ES5Array.
  7338. if (!JavascriptArray::Is(obj))
  7339. {
  7340. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  7341. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FindObjectHelper<findIndex>(obj, length, k + 1, callBackFn, thisArg, scriptContext));
  7342. }
  7343. }
  7344. }
  7345. else if (typedArrayBase)
  7346. {
  7347. Assert(length <= UINT_MAX);
  7348. for (uint32 k = 0; k < (uint32)length; k++)
  7349. {
  7350. // Spec does not ask to call HasItem, so we need to go to visit the whole length
  7351. element = typedArrayBase->DirectGetItem(k);
  7352. Var index = JavascriptNumber::ToVar(k, scriptContext);
  7353. JS_REENTRANT(jsReentLock,
  7354. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7355. element,
  7356. index,
  7357. typedArrayBase));
  7358. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7359. {
  7360. return findIndex ? index : element;
  7361. }
  7362. }
  7363. }
  7364. else
  7365. {
  7366. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FindObjectHelper<findIndex>(obj, length, 0u, callBackFn, thisArg, scriptContext));
  7367. }
  7368. return findIndex ? JavascriptNumber::ToVar(-1, scriptContext) : scriptContext->GetLibrary()->GetUndefined();
  7369. }
  7370. template <bool findIndex>
  7371. Var JavascriptArray::FindObjectHelper(RecyclableObject* obj, int64 length, int64 start, RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
  7372. {
  7373. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7374. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  7375. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7376. CallFlags flags = CallFlags_Value;
  7377. Var element = nullptr;
  7378. Var testResult = nullptr;
  7379. for (int64 k = start; k < length; k++)
  7380. {
  7381. JS_REENTRANT(jsReentLock, element = JavascriptOperators::GetItem(obj, (uint64)k, scriptContext));
  7382. Var index = JavascriptNumber::ToVar(k, scriptContext);
  7383. JS_REENTRANT(jsReentLock,
  7384. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7385. element,
  7386. index,
  7387. obj));
  7388. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7389. {
  7390. return findIndex ? index : element;
  7391. }
  7392. }
  7393. return findIndex ? JavascriptNumber::ToVar(-1, scriptContext) : scriptContext->GetLibrary()->GetUndefined();
  7394. }
  7395. ///----------------------------------------------------------------------------
  7396. /// FindIndex() calls the given predicate callback on each element of the
  7397. /// array, in order, and returns the index of the first element that makes the
  7398. /// predicate return true, as described in (ES6.0: S22.1.3.9).
  7399. ///----------------------------------------------------------------------------
  7400. Var JavascriptArray::EntryFindIndex(RecyclableObject* function, CallInfo callInfo, ...)
  7401. {
  7402. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7403. ARGUMENTS(args, callInfo);
  7404. ScriptContext* scriptContext = function->GetScriptContext();
  7405. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7406. Assert(!(callInfo.Flags & CallFlags_New));
  7407. if (args.Info.Count == 0)
  7408. {
  7409. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.findIndex"));
  7410. }
  7411. int64 length;
  7412. JavascriptArray * pArr = nullptr;
  7413. RecyclableObject* obj = nullptr;
  7414. JS_REENTRANT_UNLOCK(jsReentLock,
  7415. TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.findIndex"), &pArr, &obj, &length));
  7416. return JavascriptArray::FindHelper<true>(pArr, nullptr, obj, length, args, scriptContext);
  7417. }
  7418. ///----------------------------------------------------------------------------
  7419. /// Entries() returns a new ArrayIterator object configured to return key-
  7420. /// value pairs matching the elements of the this array/array-like object,
  7421. /// as described in (ES6.0: S22.1.3.4).
  7422. ///----------------------------------------------------------------------------
  7423. Var JavascriptArray::EntryEntries(RecyclableObject* function, CallInfo callInfo, ...)
  7424. {
  7425. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7426. ARGUMENTS(args, callInfo);
  7427. ScriptContext* scriptContext = function->GetScriptContext();
  7428. #ifdef ENABLE_JS_BUILTINS
  7429. Assert(!scriptContext->IsJsBuiltInEnabled());
  7430. #endif
  7431. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7432. Assert(!(callInfo.Flags & CallFlags_New));
  7433. if (args.Info.Count == 0)
  7434. {
  7435. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.entries"));
  7436. }
  7437. RecyclableObject* thisObj = nullptr;
  7438. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &thisObj))
  7439. {
  7440. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.entries"));
  7441. }
  7442. #if ENABLE_COPYONACCESS_ARRAY
  7443. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(thisObj);
  7444. #endif
  7445. JS_REENTRANT_UNLOCK(jsReentLock,
  7446. return scriptContext->GetLibrary()->CreateArrayIterator(thisObj, JavascriptArrayIteratorKind::KeyAndValue));
  7447. }
  7448. ///----------------------------------------------------------------------------
  7449. /// Keys() returns a new ArrayIterator object configured to return the keys
  7450. /// of the this array/array-like object, as described in (ES6.0: S22.1.3.13).
  7451. ///----------------------------------------------------------------------------
  7452. Var JavascriptArray::EntryKeys(RecyclableObject* function, CallInfo callInfo, ...)
  7453. {
  7454. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7455. ARGUMENTS(args, callInfo);
  7456. ScriptContext* scriptContext = function->GetScriptContext();
  7457. #ifdef ENABLE_JS_BUILTINS
  7458. Assert(!scriptContext->IsJsBuiltInEnabled());
  7459. #endif
  7460. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7461. Assert(!(callInfo.Flags & CallFlags_New));
  7462. if (args.Info.Count == 0)
  7463. {
  7464. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.keys"));
  7465. }
  7466. RecyclableObject* thisObj = nullptr;
  7467. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &thisObj))
  7468. {
  7469. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.keys"));
  7470. }
  7471. #if ENABLE_COPYONACCESS_ARRAY
  7472. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(thisObj);
  7473. #endif
  7474. JS_REENTRANT_UNLOCK(jsReentLock,
  7475. return scriptContext->GetLibrary()->CreateArrayIterator(thisObj, JavascriptArrayIteratorKind::Key));
  7476. }
  7477. ///----------------------------------------------------------------------------
  7478. /// Values() returns a new ArrayIterator object configured to return the values
  7479. /// of the this array/array-like object, as described in (ES6.0: S22.1.3.29).
  7480. ///----------------------------------------------------------------------------
  7481. Var JavascriptArray::EntryValues(RecyclableObject* function, CallInfo callInfo, ...)
  7482. {
  7483. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7484. ARGUMENTS(args, callInfo);
  7485. ScriptContext* scriptContext = function->GetScriptContext();
  7486. #ifdef ENABLE_JS_BUILTINS
  7487. Assert(!scriptContext->IsJsBuiltInEnabled());
  7488. #endif
  7489. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7490. Assert(!(callInfo.Flags & CallFlags_New));
  7491. if (args.Info.Count == 0)
  7492. {
  7493. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.values"));
  7494. }
  7495. RecyclableObject* thisObj = nullptr;
  7496. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &thisObj))
  7497. {
  7498. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.values"));
  7499. }
  7500. #if ENABLE_COPYONACCESS_ARRAY
  7501. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(thisObj);
  7502. #endif
  7503. JS_REENTRANT_UNLOCK(jsReentLock,
  7504. return scriptContext->GetLibrary()->CreateArrayIterator(thisObj, JavascriptArrayIteratorKind::Value));
  7505. }
  7506. Var JavascriptArray::EntryEvery(RecyclableObject* function, CallInfo callInfo, ...)
  7507. {
  7508. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7509. ARGUMENTS(args, callInfo);
  7510. ScriptContext* scriptContext = function->GetScriptContext();
  7511. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7512. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.every"));
  7513. Assert(!(callInfo.Flags & CallFlags_New));
  7514. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_every);
  7515. if (args.Info.Count == 0)
  7516. {
  7517. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.every"));
  7518. }
  7519. BigIndex length;
  7520. JavascriptArray* pArr = nullptr;
  7521. RecyclableObject* obj = nullptr;
  7522. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.every"), &pArr, &obj, &length));
  7523. if (length.IsSmallIndex())
  7524. {
  7525. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::EveryHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  7526. }
  7527. 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
  7528. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::EveryHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  7529. }
  7530. // Array.prototype.every as described by ES6.0 (draft 22) Section 22.1.3.5
  7531. template <typename T>
  7532. Var JavascriptArray::EveryHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  7533. {
  7534. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7535. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  7536. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  7537. {
  7538. // typedArrayBase is only non-null if and only if we came here via the TypedArray entrypoint
  7539. if (typedArrayBase != nullptr)
  7540. {
  7541. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.every"));
  7542. }
  7543. else
  7544. {
  7545. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.every"));
  7546. }
  7547. }
  7548. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  7549. Var thisArg = nullptr;
  7550. if (args.Info.Count > 2)
  7551. {
  7552. thisArg = args[2];
  7553. }
  7554. else
  7555. {
  7556. thisArg = scriptContext->GetLibrary()->GetUndefined();
  7557. }
  7558. // If we came from Array.prototype.map and source object is not a JavascriptArray, source could be a TypedArray
  7559. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  7560. {
  7561. typedArrayBase = TypedArrayBase::UnsafeFromVar(obj);
  7562. }
  7563. Var element = nullptr;
  7564. Var testResult = nullptr;
  7565. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7566. CallFlags flags = CallFlags_Value;
  7567. if (typedArrayBase)
  7568. {
  7569. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  7570. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  7571. for (uint32 k = 0; k < end; k++)
  7572. {
  7573. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  7574. element = typedArrayBase->DirectGetItem(k);
  7575. JS_REENTRANT(jsReentLock,
  7576. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7577. element,
  7578. JavascriptNumber::ToVar(k, scriptContext),
  7579. typedArrayBase));
  7580. if (!JavascriptConversion::ToBoolean(testResult, scriptContext))
  7581. {
  7582. return scriptContext->GetLibrary()->GetFalse();
  7583. }
  7584. }
  7585. }
  7586. else
  7587. {
  7588. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::EveryObjectHelper<T>(obj, length, 0u, callBackFn, thisArg, scriptContext));
  7589. }
  7590. return scriptContext->GetLibrary()->GetTrue();
  7591. }
  7592. template <typename T>
  7593. Var JavascriptArray::EveryObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
  7594. {
  7595. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7596. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  7597. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7598. CallFlags flags = CallFlags_Value;
  7599. Var element = nullptr;
  7600. Var testResult = nullptr;
  7601. for (T k = start; k < length; k++)
  7602. {
  7603. // According to es6 spec, we need to call Has first before calling Get
  7604. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  7605. if (hasItem)
  7606. {
  7607. JS_REENTRANT(jsReentLock,
  7608. element = JavascriptOperators::GetItem(obj, k, scriptContext),
  7609. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7610. element,
  7611. JavascriptNumber::ToVar(k, scriptContext),
  7612. obj));
  7613. if (!JavascriptConversion::ToBoolean(testResult, scriptContext))
  7614. {
  7615. return scriptContext->GetLibrary()->GetFalse();
  7616. }
  7617. }
  7618. }
  7619. return scriptContext->GetLibrary()->GetTrue();
  7620. }
  7621. Var JavascriptArray::EntrySome(RecyclableObject* function, CallInfo callInfo, ...)
  7622. {
  7623. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7624. ARGUMENTS(args, callInfo);
  7625. ScriptContext* scriptContext = function->GetScriptContext();
  7626. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7627. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.some"));
  7628. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_some);
  7629. Assert(!(callInfo.Flags & CallFlags_New));
  7630. if (args.Info.Count == 0)
  7631. {
  7632. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.some"));
  7633. }
  7634. BigIndex length;
  7635. JavascriptArray* pArr = nullptr;
  7636. RecyclableObject* obj = nullptr;
  7637. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.some"), &pArr, &obj, &length));
  7638. if (length.IsSmallIndex())
  7639. {
  7640. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SomeHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  7641. }
  7642. 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
  7643. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SomeHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  7644. }
  7645. // Array.prototype.some as described in ES6.0 (draft 22) Section 22.1.3.23
  7646. template <typename T>
  7647. Var JavascriptArray::SomeHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  7648. {
  7649. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7650. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  7651. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  7652. {
  7653. // We are in the TypedArray version of this API if and only if typedArrayBase != nullptr
  7654. if (typedArrayBase != nullptr)
  7655. {
  7656. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.some"));
  7657. }
  7658. else
  7659. {
  7660. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.some"));
  7661. }
  7662. }
  7663. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  7664. Var thisArg = nullptr;
  7665. if (args.Info.Count > 2)
  7666. {
  7667. thisArg = args[2];
  7668. }
  7669. else
  7670. {
  7671. thisArg = scriptContext->GetLibrary()->GetUndefined();
  7672. }
  7673. // If we came from Array.prototype.some and source object is not a JavascriptArray, source could be a TypedArray
  7674. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  7675. {
  7676. typedArrayBase = TypedArrayBase::UnsafeFromVar(obj);
  7677. }
  7678. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7679. CallFlags flags = CallFlags_Value;
  7680. Var element = nullptr;
  7681. Var testResult = nullptr;
  7682. if (typedArrayBase)
  7683. {
  7684. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  7685. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  7686. for (uint32 k = 0; k < end; k++)
  7687. {
  7688. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  7689. element = typedArrayBase->DirectGetItem(k);
  7690. JS_REENTRANT_UNLOCK(jsReentLock,
  7691. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7692. element,
  7693. JavascriptNumber::ToVar(k, scriptContext),
  7694. typedArrayBase));
  7695. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7696. {
  7697. return scriptContext->GetLibrary()->GetTrue();
  7698. }
  7699. }
  7700. }
  7701. else
  7702. {
  7703. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SomeObjectHelper<T>(obj, length, 0u, callBackFn, thisArg, scriptContext));
  7704. }
  7705. return scriptContext->GetLibrary()->GetFalse();
  7706. }
  7707. template <typename T>
  7708. Var JavascriptArray::SomeObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
  7709. {
  7710. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7711. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  7712. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7713. CallFlags flags = CallFlags_Value;
  7714. Var element = nullptr;
  7715. Var testResult = nullptr;
  7716. for (T k = start; k < length; k++)
  7717. {
  7718. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  7719. if (hasItem)
  7720. {
  7721. JS_REENTRANT_UNLOCK(jsReentLock,
  7722. element = JavascriptOperators::GetItem(obj, k, scriptContext),
  7723. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7724. element,
  7725. JavascriptNumber::ToVar(k, scriptContext),
  7726. obj));
  7727. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7728. {
  7729. return scriptContext->GetLibrary()->GetTrue();
  7730. }
  7731. }
  7732. }
  7733. return scriptContext->GetLibrary()->GetFalse();
  7734. }
  7735. Var JavascriptArray::EntryForEach(RecyclableObject* function, CallInfo callInfo, ...)
  7736. {
  7737. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7738. ARGUMENTS(args, callInfo);
  7739. ScriptContext* scriptContext = function->GetScriptContext();
  7740. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7741. SETOBJECT_FOR_MUTATION(jsReentLock, args[0]);
  7742. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.forEach"));
  7743. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_forEach)
  7744. Assert(!(callInfo.Flags & CallFlags_New));
  7745. if (args.Info.Count == 0)
  7746. {
  7747. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.forEach"));
  7748. }
  7749. BigIndex length;
  7750. JavascriptArray* pArr = nullptr;
  7751. RecyclableObject* dynamicObject = nullptr;
  7752. RecyclableObject* callBackFn = nullptr;
  7753. Var thisArg = nullptr;
  7754. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.forEach"), &pArr, &dynamicObject, &length));
  7755. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  7756. {
  7757. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.forEach"));
  7758. }
  7759. callBackFn = RecyclableObject::FromVar(args[1]);
  7760. if (args.Info.Count > 2)
  7761. {
  7762. thisArg = args[2];
  7763. }
  7764. else
  7765. {
  7766. thisArg = scriptContext->GetLibrary()->GetUndefined();
  7767. }
  7768. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7769. CallFlags flags = CallFlags_Value;
  7770. auto fn32 = [dynamicObject, callBackFn, flags, thisArg,
  7771. scriptContext](uint32 k, Var element)
  7772. {
  7773. CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7774. element,
  7775. JavascriptNumber::ToVar(k, scriptContext),
  7776. dynamicObject);
  7777. };
  7778. auto fn64 = [dynamicObject, callBackFn, flags, thisArg,
  7779. scriptContext](uint64 k, Var element)
  7780. {
  7781. CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7782. element,
  7783. JavascriptNumber::ToVar(k, scriptContext),
  7784. dynamicObject);
  7785. };
  7786. if (pArr)
  7787. {
  7788. Assert(pArr == dynamicObject);
  7789. JS_REENTRANT(jsReentLock, pArr->ForEachItemInRange<true>(0, length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex(), scriptContext, fn32));
  7790. }
  7791. else
  7792. {
  7793. if (length.IsSmallIndex())
  7794. {
  7795. JS_REENTRANT(jsReentLock, TemplatedForEachItemInRange<true>(dynamicObject, 0u, length.GetSmallIndex(), scriptContext, fn32));
  7796. }
  7797. else
  7798. {
  7799. JS_REENTRANT(jsReentLock, TemplatedForEachItemInRange<true>(dynamicObject, 0ui64, length.GetBigIndex(), scriptContext, fn64));
  7800. }
  7801. }
  7802. return scriptContext->GetLibrary()->GetUndefined();
  7803. }
  7804. Var JavascriptArray::EntryCopyWithin(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. Assert(!(callInfo.Flags & CallFlags_New));
  7811. RecyclableObject* obj = nullptr;
  7812. JavascriptArray* pArr = nullptr;
  7813. int64 length;
  7814. JS_REENTRANT_UNLOCK(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.copyWithin"), &pArr, &obj, &length));
  7815. return JavascriptArray::CopyWithinHelper(pArr, nullptr, obj, length, args, scriptContext);
  7816. }
  7817. // Array.prototype.copyWithin as defined in ES6.0 (draft 22) Section 22.1.3.3
  7818. Var JavascriptArray::CopyWithinHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
  7819. {
  7820. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7821. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  7822. Assert(args.Info.Count > 0);
  7823. bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
  7824. JavascriptLibrary* library = scriptContext->GetLibrary();
  7825. int64 fromVal = 0;
  7826. int64 toVal = 0;
  7827. int64 finalVal = length;
  7828. // If we came from Array.prototype.copyWithin and source object is not a JavascriptArray, source could be a TypedArray
  7829. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  7830. {
  7831. typedArrayBase = TypedArrayBase::UnsafeFromVar(obj);
  7832. }
  7833. if (args.Info.Count > 1)
  7834. {
  7835. JS_REENTRANT(jsReentLock, toVal = JavascriptArray::GetIndexFromVar(args[1], length, scriptContext));
  7836. if (args.Info.Count > 2)
  7837. {
  7838. JS_REENTRANT(jsReentLock, fromVal = JavascriptArray::GetIndexFromVar(args[2], length, scriptContext));
  7839. if (args.Info.Count > 3 && args[3] != library->GetUndefined())
  7840. {
  7841. JS_REENTRANT(jsReentLock, finalVal = JavascriptArray::GetIndexFromVar(args[3], length, scriptContext));
  7842. }
  7843. }
  7844. }
  7845. // If count would be negative or zero, we won't do anything so go ahead and return early.
  7846. if (finalVal <= fromVal || length <= toVal)
  7847. {
  7848. return obj;
  7849. }
  7850. // Make sure we won't underflow during the count calculation
  7851. Assert(finalVal > fromVal && length > toVal);
  7852. int64 count = min(finalVal - fromVal, length - toVal);
  7853. // We shouldn't have made it here if the count was going to be zero
  7854. Assert(count > 0);
  7855. // If we entered via TypedArray.prototype.copyWithin, then we can copy by bytes. Otherwise, if the user called
  7856. // Array.prototype.copyWithin on a typed array instance, then the typed array might be responsible for not
  7857. // writing torn values, which memmove does not guarantee.
  7858. if (isTypedArrayEntryPoint)
  7859. {
  7860. Assert(typedArrayBase);
  7861. // Re-validate the typed array, which could have become detached due to reentrant script.
  7862. if (typedArrayBase->IsDetachedBuffer())
  7863. {
  7864. JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("[TypedArray].prototype.copyWithin"));
  7865. }
  7866. AssertOrFailFast(length == typedArrayBase->GetLength());
  7867. uint32 bytesPerElement = typedArrayBase->GetBytesPerElement();
  7868. byte *buffer = typedArrayBase->GetByteBuffer();
  7869. size_t fromByteIndex = static_cast<size_t>(fromVal) * bytesPerElement;
  7870. size_t toByteIndex = static_cast<size_t>(toVal) * bytesPerElement;
  7871. size_t byteCount = static_cast<size_t>(count) * bytesPerElement;
  7872. Assert(typedArrayBase->GetByteLength() >= byteCount);
  7873. Assert(fromByteIndex <= typedArrayBase->GetByteLength() - byteCount);
  7874. Assert(toByteIndex <= typedArrayBase->GetByteLength() - byteCount);
  7875. memmove(&buffer[toByteIndex], &buffer[fromByteIndex], byteCount);
  7876. return obj;
  7877. }
  7878. int direction;
  7879. if (fromVal < toVal && toVal < (fromVal + count))
  7880. {
  7881. direction = -1;
  7882. fromVal += count - 1;
  7883. toVal += count - 1;
  7884. }
  7885. else
  7886. {
  7887. direction = 1;
  7888. }
  7889. // Side effects (such as defining a property in a ToPrimitive call) during evaluation of arguments may convert the array to an ES5 array.
  7890. if (pArr && !JavascriptArray::Is(obj))
  7891. {
  7892. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  7893. pArr = nullptr;
  7894. }
  7895. // If we are going to copy elements from or to indices > 2^32-1 we'll execute this (slightly slower path)
  7896. // It's possible to optimize here so that we use the normal code below except for the > 2^32-1 indices
  7897. if ((direction == -1 && (fromVal >= MaxArrayLength || toVal >= MaxArrayLength))
  7898. || (((fromVal + count) > MaxArrayLength) || ((toVal + count) > MaxArrayLength)))
  7899. {
  7900. while (count > 0)
  7901. {
  7902. Var index = JavascriptNumber::ToVar(fromVal, scriptContext);
  7903. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::OP_HasItem(obj, index, scriptContext));
  7904. if (hasItem)
  7905. {
  7906. Var val = nullptr;
  7907. JS_REENTRANT(jsReentLock,
  7908. val = JavascriptOperators::OP_GetElementI(obj, index, scriptContext),
  7909. JavascriptOperators::OP_SetElementI(obj, JavascriptNumber::ToVar(toVal, scriptContext), val, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  7910. }
  7911. else
  7912. {
  7913. JavascriptOperators::OP_DeleteElementI(obj, JavascriptNumber::ToVar(toVal, scriptContext), scriptContext, PropertyOperation_ThrowOnDeleteIfNotConfig);
  7914. }
  7915. fromVal += direction;
  7916. toVal += direction;
  7917. count--;
  7918. }
  7919. }
  7920. else
  7921. {
  7922. Assert(fromVal < MaxArrayLength);
  7923. Assert(toVal < MaxArrayLength);
  7924. Assert(direction == -1 || (fromVal + count < MaxArrayLength && toVal + count < MaxArrayLength));
  7925. uint32 fromIndex = static_cast<uint32>(fromVal);
  7926. uint32 toIndex = static_cast<uint32>(toVal);
  7927. while (count > 0)
  7928. {
  7929. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, fromIndex));
  7930. if (hasItem)
  7931. {
  7932. if (typedArrayBase)
  7933. {
  7934. Var val = typedArrayBase->DirectGetItem(fromIndex);
  7935. JS_REENTRANT(jsReentLock, typedArrayBase->DirectSetItem(toIndex, val));
  7936. }
  7937. else if (pArr)
  7938. {
  7939. JS_REENTRANT(jsReentLock, Var val = pArr->DirectGetItem(fromIndex));
  7940. pArr->SetItem(toIndex, val, Js::PropertyOperation_ThrowIfNotExtensible);
  7941. if (!JavascriptArray::Is(obj))
  7942. {
  7943. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  7944. pArr = nullptr;
  7945. }
  7946. }
  7947. else
  7948. {
  7949. Var val = nullptr;
  7950. JS_REENTRANT(jsReentLock,
  7951. val = JavascriptOperators::OP_GetElementI_UInt32(obj, fromIndex, scriptContext),
  7952. JavascriptOperators::OP_SetElementI_UInt32(obj, toIndex, val, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  7953. }
  7954. }
  7955. else
  7956. {
  7957. JS_REENTRANT(jsReentLock, obj->DeleteItem(toIndex, PropertyOperation_ThrowOnDeleteIfNotConfig));
  7958. }
  7959. fromIndex += direction;
  7960. toIndex += direction;
  7961. count--;
  7962. }
  7963. }
  7964. return obj;
  7965. }
  7966. Var JavascriptArray::EntryFill(RecyclableObject* function, CallInfo callInfo, ...)
  7967. {
  7968. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7969. ARGUMENTS(args, callInfo);
  7970. ScriptContext* scriptContext = function->GetScriptContext();
  7971. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7972. Assert(!(callInfo.Flags & CallFlags_New));
  7973. RecyclableObject* obj = nullptr;
  7974. JavascriptArray* pArr = nullptr;
  7975. int64 length;
  7976. JS_REENTRANT_UNLOCK(jsReentLock,
  7977. TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.fill"), &pArr, &obj, &length));
  7978. return JavascriptArray::FillHelper(pArr, nullptr, obj, length, args, scriptContext);
  7979. }
  7980. // Array.prototype.fill as defined in ES6.0 (draft 22) Section 22.1.3.6
  7981. Var JavascriptArray::FillHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
  7982. {
  7983. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7984. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  7985. Assert(args.Info.Count > 0);
  7986. JavascriptLibrary* library = scriptContext->GetLibrary();
  7987. // If we came from Array.prototype.fill and source object is not a JavascriptArray, source could be a TypedArray
  7988. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  7989. {
  7990. typedArrayBase = TypedArrayBase::UnsafeFromVar(obj);
  7991. }
  7992. Var fillValue;
  7993. if (args.Info.Count > 1)
  7994. {
  7995. fillValue = args[1];
  7996. }
  7997. else
  7998. {
  7999. fillValue = library->GetUndefined();
  8000. }
  8001. int64 k = 0;
  8002. int64 finalVal = length;
  8003. if (args.Info.Count > 2)
  8004. {
  8005. JS_REENTRANT_UNLOCK(jsReentLock, k = JavascriptArray::GetIndexFromVar(args[2], length, scriptContext));
  8006. if (args.Info.Count > 3 && !JavascriptOperators::IsUndefinedObject(args[3]))
  8007. {
  8008. JS_REENTRANT_UNLOCK(jsReentLock, finalVal = JavascriptArray::GetIndexFromVar(args[3], length, scriptContext));
  8009. }
  8010. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  8011. // we will process the array elements like an ES5Array.
  8012. if (pArr && !JavascriptArray::Is(obj))
  8013. {
  8014. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  8015. pArr = nullptr;
  8016. }
  8017. }
  8018. if (k < MaxArrayLength)
  8019. {
  8020. int64 end = min<int64>(finalVal, MaxArrayLength);
  8021. uint32 u32k = static_cast<uint32>(k);
  8022. while (u32k < end)
  8023. {
  8024. if (typedArrayBase)
  8025. {
  8026. JS_REENTRANT(jsReentLock, typedArrayBase->DirectSetItem(u32k, fillValue));
  8027. }
  8028. else if (pArr)
  8029. {
  8030. pArr->SetItem(u32k, fillValue, PropertyOperation_ThrowIfNotExtensible);
  8031. }
  8032. else
  8033. {
  8034. JS_REENTRANT(jsReentLock,
  8035. JavascriptOperators::OP_SetElementI_UInt32(obj, u32k, fillValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible));
  8036. }
  8037. u32k++;
  8038. }
  8039. BigIndex dstIndex = MaxArrayLength;
  8040. for (int64 i = end; i < finalVal; ++i)
  8041. {
  8042. if (pArr)
  8043. {
  8044. pArr->GenericDirectSetItemAt(dstIndex, fillValue);
  8045. ++dstIndex;
  8046. }
  8047. else
  8048. {
  8049. JS_REENTRANT(jsReentLock,
  8050. JavascriptOperators::OP_SetElementI(obj, JavascriptNumber::ToVar(i, scriptContext), fillValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible));
  8051. }
  8052. }
  8053. }
  8054. else
  8055. {
  8056. BigIndex dstIndex = static_cast<uint64>(k);
  8057. for (int64 i = k; i < finalVal; i++)
  8058. {
  8059. if (pArr)
  8060. {
  8061. pArr->GenericDirectSetItemAt(dstIndex, fillValue);
  8062. ++dstIndex;
  8063. }
  8064. else
  8065. {
  8066. JS_REENTRANT(jsReentLock,
  8067. JavascriptOperators::OP_SetElementI(obj, JavascriptNumber::ToVar(i, scriptContext), fillValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible));
  8068. }
  8069. }
  8070. }
  8071. return obj;
  8072. }
  8073. // Array.prototype.map as defined by ES6.0 (Final) 22.1.3.15
  8074. Var JavascriptArray::EntryMap(RecyclableObject* function, CallInfo callInfo, ...)
  8075. {
  8076. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8077. ARGUMENTS(args, callInfo);
  8078. ScriptContext* scriptContext = function->GetScriptContext();
  8079. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8080. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.map"));
  8081. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_map);
  8082. Assert(!(callInfo.Flags & CallFlags_New));
  8083. if (args.Info.Count == 0)
  8084. {
  8085. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.map"));
  8086. }
  8087. BigIndex length;
  8088. JavascriptArray* pArr = nullptr;
  8089. RecyclableObject* obj = nullptr;
  8090. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.map"), &pArr, &obj, &length));
  8091. if (length.IsSmallIndex())
  8092. {
  8093. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::MapHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  8094. }
  8095. 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
  8096. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::MapHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  8097. }
  8098. template<typename T>
  8099. Var JavascriptArray::MapHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  8100. {
  8101. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8102. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  8103. RecyclableObject* newObj = nullptr;
  8104. JavascriptArray* newArr = nullptr;
  8105. bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
  8106. bool isBuiltinArrayCtor = true;
  8107. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  8108. {
  8109. if (isTypedArrayEntryPoint)
  8110. {
  8111. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.map"));
  8112. }
  8113. else
  8114. {
  8115. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.map"));
  8116. }
  8117. }
  8118. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  8119. Var thisArg;
  8120. if (args.Info.Count > 2)
  8121. {
  8122. thisArg = args[2];
  8123. }
  8124. else
  8125. {
  8126. thisArg = scriptContext->GetLibrary()->GetUndefined();
  8127. }
  8128. // If we came from Array.prototype.map and source object is not a JavascriptArray, source could be a TypedArray
  8129. if (!isTypedArrayEntryPoint && pArr == nullptr && TypedArrayBase::Is(obj))
  8130. {
  8131. typedArrayBase = TypedArrayBase::UnsafeFromVar(obj);
  8132. }
  8133. // 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
  8134. // and use it to construct the return object.
  8135. if (isTypedArrayEntryPoint)
  8136. {
  8137. JS_REENTRANT(jsReentLock,
  8138. RecyclableObject* constructor = JavascriptOperators::SpeciesConstructor(
  8139. typedArrayBase, TypedArrayBase::GetDefaultConstructor(args[0], scriptContext), scriptContext));
  8140. isBuiltinArrayCtor = false;
  8141. Assert(JavascriptOperators::IsConstructor(constructor));
  8142. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(length, scriptContext) };
  8143. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  8144. JS_REENTRANT(jsReentLock, newObj = RecyclableObject::FromVar(TypedArrayBase::TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), (uint32)length, scriptContext)));
  8145. }
  8146. // skip the typed array and "pure" array case, we still need to handle special arrays like es5array, remote array, and proxy of array.
  8147. else if (pArr == nullptr || scriptContext->GetConfig()->IsES6SpeciesEnabled())
  8148. {
  8149. JS_REENTRANT_NO_MUTATE(jsReentLock, newObj = ArraySpeciesCreate(obj, length, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor));
  8150. }
  8151. if (newObj == nullptr)
  8152. {
  8153. if (length > UINT_MAX)
  8154. {
  8155. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  8156. }
  8157. newArr = scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(length));
  8158. newArr->EnsureHead<Var>();
  8159. newObj = newArr;
  8160. }
  8161. else
  8162. {
  8163. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  8164. newArr = JavascriptOperators::TryFromVar<JavascriptArray>(newObj);
  8165. if (newArr)
  8166. {
  8167. #if ENABLE_COPYONACCESS_ARRAY
  8168. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  8169. #endif
  8170. SET_SECOND_OBJECT_FOR_MUTATION(jsReentLock, newArr);
  8171. }
  8172. }
  8173. Var element = nullptr;
  8174. Var mappedValue = nullptr;
  8175. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8176. CallFlags callBackFnflags = CallFlags_Value;
  8177. CallInfo callBackFnInfo = CallInfo(callBackFnflags, 4);
  8178. // We at least have to have newObj as a valid object
  8179. Assert(newObj);
  8180. // The ArraySpeciesCreate call above could have converted the source array into an ES5Array. If this happens
  8181. // we will process the array elements like an ES5Array.
  8182. if (pArr && !JavascriptArray::Is(obj))
  8183. {
  8184. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  8185. pArr = nullptr;
  8186. }
  8187. if (pArr != nullptr)
  8188. {
  8189. // If source is a JavascriptArray, newObj may or may not be an array based on what was in source's constructor property
  8190. Assert(length <= UINT_MAX);
  8191. for (uint32 k = 0; k < (uint32)length; k++)
  8192. {
  8193. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(k, &element));
  8194. if (!gotItem)
  8195. {
  8196. continue;
  8197. }
  8198. JS_REENTRANT(jsReentLock,
  8199. mappedValue = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, callBackFnInfo, thisArg,
  8200. element,
  8201. JavascriptNumber::ToVar(k, scriptContext),
  8202. pArr));
  8203. // If newArr is a valid pointer, then we constructed an array to return. Otherwise we need to do generic object operations
  8204. if (newArr && isBuiltinArrayCtor)
  8205. {
  8206. newArr->DirectSetItemAt(k, mappedValue);
  8207. }
  8208. else
  8209. {
  8210. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, k, mappedValue), scriptContext, k));
  8211. }
  8212. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  8213. // we will process the rest of the array elements like an ES5Array.
  8214. if (!JavascriptArray::Is(obj))
  8215. {
  8216. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  8217. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::MapObjectHelper<T>(obj, length, k + 1, newObj, newArr, isBuiltinArrayCtor, callBackFn, thisArg, scriptContext));
  8218. }
  8219. }
  8220. }
  8221. else if (typedArrayBase != nullptr)
  8222. {
  8223. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  8224. // Source is a TypedArray, we may have tried to call a constructor, but newObj may not be a TypedArray (or an array either)
  8225. TypedArrayBase* newTypedArray = JavascriptOperators::TryFromVar<Js::TypedArrayBase>(newObj);
  8226. if (!newTypedArray)
  8227. {
  8228. AssertAndFailFast(newArr != nullptr);
  8229. }
  8230. Assert(length <= UINT_MAX);
  8231. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  8232. for (uint32 k = 0; k < end; k++)
  8233. {
  8234. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  8235. element = typedArrayBase->DirectGetItem(k);
  8236. JS_REENTRANT(jsReentLock,
  8237. mappedValue = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, callBackFnInfo, thisArg,
  8238. element,
  8239. JavascriptNumber::ToVar(k, scriptContext),
  8240. obj));
  8241. // If newObj is a TypedArray, set the mappedValue directly, otherwise it should be an array, set that item to that array
  8242. if (newTypedArray)
  8243. {
  8244. JS_REENTRANT(jsReentLock, newTypedArray->DirectSetItem(k, mappedValue));
  8245. }
  8246. else
  8247. {
  8248. newArr->SetItem(k, mappedValue, PropertyOperation_None);
  8249. }
  8250. }
  8251. }
  8252. else
  8253. {
  8254. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::MapObjectHelper<T>(obj, length, 0u, newObj, newArr, isBuiltinArrayCtor, callBackFn, thisArg, scriptContext));
  8255. }
  8256. #ifdef VALIDATE_ARRAY
  8257. if (JavascriptArray::Is(newObj))
  8258. {
  8259. newArr->ValidateArray();
  8260. }
  8261. #endif
  8262. return newObj;
  8263. }
  8264. template<typename T>
  8265. Var JavascriptArray::MapObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* newObj, JavascriptArray* newArr,
  8266. bool isBuiltinArrayCtor, RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
  8267. {
  8268. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8269. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  8270. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8271. CallFlags callBackFnflags = CallFlags_Value;
  8272. CallInfo callBackFnInfo = CallInfo(callBackFnflags, 4);
  8273. Var element = nullptr;
  8274. Var mappedValue = nullptr;
  8275. for (T k = start; k < length; k++)
  8276. {
  8277. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  8278. if (hasItem)
  8279. {
  8280. JS_REENTRANT(jsReentLock,
  8281. element = JavascriptOperators::GetItem(obj, k, scriptContext),
  8282. mappedValue = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, callBackFnInfo, thisArg,
  8283. element,
  8284. JavascriptNumber::ToVar(k, scriptContext),
  8285. obj));
  8286. if (newArr && isBuiltinArrayCtor)
  8287. {
  8288. newArr->SetItem((uint32)k, mappedValue, PropertyOperation_None);
  8289. }
  8290. else
  8291. {
  8292. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, BigIndex(k), mappedValue), scriptContext, BigIndex(k)));
  8293. }
  8294. }
  8295. }
  8296. #ifdef VALIDATE_ARRAY
  8297. if (JavascriptArray::Is(newObj))
  8298. {
  8299. newArr->ValidateArray();
  8300. }
  8301. #endif
  8302. return newObj;
  8303. }
  8304. Var JavascriptArray::EntryFilter(RecyclableObject* function, CallInfo callInfo, ...)
  8305. {
  8306. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8307. ARGUMENTS(args, callInfo);
  8308. ScriptContext* scriptContext = function->GetScriptContext();
  8309. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8310. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.filter"));
  8311. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_filter);
  8312. Assert(!(callInfo.Flags & CallFlags_New));
  8313. if (args.Info.Count == 0)
  8314. {
  8315. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.filter"));
  8316. }
  8317. BigIndex length;
  8318. JavascriptArray* pArr = nullptr;
  8319. RecyclableObject* obj = nullptr;
  8320. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.filter"), &pArr, &obj, &length));
  8321. if (length.IsSmallIndex())
  8322. {
  8323. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FilterHelper(pArr, obj, length.GetSmallIndex(), args, scriptContext));
  8324. }
  8325. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FilterHelper(pArr, obj, length.GetBigIndex(), args, scriptContext));
  8326. }
  8327. template <typename T>
  8328. Var JavascriptArray::FilterHelper(JavascriptArray* pArr, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  8329. {
  8330. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8331. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  8332. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  8333. {
  8334. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.filter"));
  8335. }
  8336. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  8337. Var thisArg = nullptr;
  8338. if (args.Info.Count > 2)
  8339. {
  8340. thisArg = args[2];
  8341. }
  8342. else
  8343. {
  8344. thisArg = scriptContext->GetLibrary()->GetUndefined();
  8345. }
  8346. // 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.
  8347. bool isBuiltinArrayCtor = true;
  8348. JS_REENTRANT_NO_MUTATE(jsReentLock, RecyclableObject* newObj = ArraySpeciesCreate(obj, 0, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor));
  8349. JavascriptArray* newArr = nullptr;
  8350. if (newObj == nullptr)
  8351. {
  8352. newArr = scriptContext->GetLibrary()->CreateArray(0);
  8353. newArr->EnsureHead<Var>();
  8354. newObj = newArr;
  8355. }
  8356. else
  8357. {
  8358. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  8359. newArr = JavascriptOperators::TryFromVar<JavascriptArray>(newObj);
  8360. if (newArr)
  8361. {
  8362. #if ENABLE_COPYONACCESS_ARRAY
  8363. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  8364. #endif
  8365. SET_SECOND_OBJECT_FOR_MUTATION(jsReentLock, newArr);
  8366. }
  8367. }
  8368. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FilterObjectHelper<T>(obj, length, 0u, newArr, newObj, 0u, callBackFn, thisArg, scriptContext));
  8369. }
  8370. template <typename T>
  8371. Var JavascriptArray::FilterObjectHelper(RecyclableObject* obj, T length, T start, JavascriptArray* newArr, RecyclableObject* newObj, T newStart,
  8372. RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
  8373. {
  8374. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8375. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  8376. Var element = nullptr;
  8377. Var selected = nullptr;
  8378. BigIndex i = BigIndex(newStart);
  8379. for (T k = start; k < length; k++)
  8380. {
  8381. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  8382. if (hasItem)
  8383. {
  8384. JS_REENTRANT(jsReentLock,
  8385. element = JavascriptOperators::GetItem(obj, k, scriptContext),
  8386. selected = CALL_ENTRYPOINT(scriptContext->GetThreadContext(),
  8387. callBackFn->GetEntryPoint(), callBackFn, CallInfo(CallFlags_Value, 4),
  8388. thisArg,
  8389. element,
  8390. JavascriptNumber::ToVar(k, scriptContext),
  8391. obj));
  8392. if (JavascriptConversion::ToBoolean(selected, scriptContext))
  8393. {
  8394. if (newArr)
  8395. {
  8396. newArr->GenericDirectSetItemAt(i, element);
  8397. }
  8398. else
  8399. {
  8400. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i));
  8401. }
  8402. ++i;
  8403. }
  8404. }
  8405. }
  8406. #ifdef VALIDATE_ARRAY
  8407. if (newArr)
  8408. {
  8409. newArr->ValidateArray();
  8410. }
  8411. #endif
  8412. return newObj;
  8413. }
  8414. Var JavascriptArray::EntryReduce(RecyclableObject* function, CallInfo callInfo, ...)
  8415. {
  8416. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8417. ARGUMENTS(args, callInfo);
  8418. ScriptContext* scriptContext = function->GetScriptContext();
  8419. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8420. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.reduce"));
  8421. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_reduce);
  8422. Assert(!(callInfo.Flags & CallFlags_New));
  8423. if (args.Info.Count == 0)
  8424. {
  8425. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reduce"));
  8426. }
  8427. BigIndex length;
  8428. JavascriptArray * pArr = nullptr;
  8429. RecyclableObject* obj = nullptr;
  8430. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.reduce"), &pArr, &obj, &length));
  8431. if (length.IsSmallIndex())
  8432. {
  8433. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  8434. }
  8435. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  8436. }
  8437. // Array.prototype.reduce as described in ES6.0 (draft 22) Section 22.1.3.18
  8438. template <typename T>
  8439. Var JavascriptArray::ReduceHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  8440. {
  8441. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8442. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  8443. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  8444. {
  8445. if (typedArrayBase != nullptr)
  8446. {
  8447. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.reduce"));
  8448. }
  8449. else
  8450. {
  8451. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.reduce"));
  8452. }
  8453. }
  8454. // If we came from Array.prototype.reduce and source object is not a JavascriptArray, source could be a TypedArray
  8455. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  8456. {
  8457. typedArrayBase = TypedArrayBase::UnsafeFromVar(obj);
  8458. }
  8459. T k = 0;
  8460. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  8461. Var accumulator = nullptr;
  8462. Var element = nullptr;
  8463. if (args.Info.Count > 2)
  8464. {
  8465. accumulator = args[2];
  8466. }
  8467. else
  8468. {
  8469. if (length == 0)
  8470. {
  8471. JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
  8472. }
  8473. bool bPresent = false;
  8474. if (typedArrayBase)
  8475. {
  8476. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  8477. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  8478. for (; k < end && bPresent == false; k++)
  8479. {
  8480. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  8481. element = typedArrayBase->DirectGetItem((uint32)k);
  8482. bPresent = true;
  8483. accumulator = element;
  8484. }
  8485. }
  8486. else
  8487. {
  8488. for (; k < length && bPresent == false; k++)
  8489. {
  8490. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  8491. if (hasItem)
  8492. {
  8493. JS_REENTRANT(jsReentLock, accumulator = JavascriptOperators::GetItem(obj, k, scriptContext));
  8494. bPresent = true;
  8495. }
  8496. }
  8497. }
  8498. if (bPresent == false)
  8499. {
  8500. JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
  8501. }
  8502. }
  8503. Assert(accumulator);
  8504. Var undefinedValue = scriptContext->GetLibrary()->GetUndefined();
  8505. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8506. CallFlags flags = CallFlags_Value;
  8507. if (typedArrayBase)
  8508. {
  8509. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  8510. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  8511. for (; k < end; k++)
  8512. {
  8513. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  8514. element = typedArrayBase->DirectGetItem((uint32)k);
  8515. JS_REENTRANT(jsReentLock,
  8516. accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 5), undefinedValue,
  8517. accumulator,
  8518. element,
  8519. JavascriptNumber::ToVar(k, scriptContext),
  8520. typedArrayBase));
  8521. }
  8522. }
  8523. else
  8524. {
  8525. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceObjectHelper<T>(obj, length, k, callBackFn, accumulator, scriptContext));
  8526. }
  8527. return accumulator;
  8528. }
  8529. template <typename T>
  8530. Var JavascriptArray::ReduceObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* callBackFn, Var accumulator, ScriptContext* scriptContext)
  8531. {
  8532. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8533. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  8534. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8535. CallFlags flags = CallFlags_Value;
  8536. Var element = nullptr;
  8537. for (T k = start; k < length; k++)
  8538. {
  8539. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  8540. if (hasItem)
  8541. {
  8542. JS_REENTRANT(jsReentLock,
  8543. element = JavascriptOperators::GetItem(obj, k, scriptContext),
  8544. accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 5), scriptContext->GetLibrary()->GetUndefined(),
  8545. accumulator,
  8546. element,
  8547. JavascriptNumber::ToVar(k, scriptContext),
  8548. obj));
  8549. }
  8550. }
  8551. return accumulator;
  8552. }
  8553. Var JavascriptArray::EntryReduceRight(RecyclableObject* function, CallInfo callInfo, ...)
  8554. {
  8555. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8556. ARGUMENTS(args, callInfo);
  8557. ScriptContext* scriptContext = function->GetScriptContext();
  8558. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8559. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.reduceRight"));
  8560. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_reduceRight);
  8561. Assert(!(callInfo.Flags & CallFlags_New));
  8562. if (args.Info.Count == 0)
  8563. {
  8564. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reduceRight"));
  8565. }
  8566. BigIndex length;
  8567. JavascriptArray * pArr = nullptr;
  8568. RecyclableObject* obj = nullptr;
  8569. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.reduceRight"), &pArr, &obj, &length));
  8570. if (length.IsSmallIndex())
  8571. {
  8572. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceRightHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  8573. }
  8574. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceRightHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  8575. }
  8576. // Array.prototype.reduceRight as described in ES6.0 (draft 22) Section 22.1.3.19
  8577. template <typename T>
  8578. Var JavascriptArray::ReduceRightHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  8579. {
  8580. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8581. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  8582. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  8583. {
  8584. if (typedArrayBase != nullptr)
  8585. {
  8586. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.reduceRight"));
  8587. }
  8588. else
  8589. {
  8590. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.reduceRight"));
  8591. }
  8592. }
  8593. // If we came from Array.prototype.reduceRight and source object is not a JavascriptArray, source could be a TypedArray
  8594. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  8595. {
  8596. typedArrayBase = TypedArrayBase::UnsafeFromVar(obj);
  8597. }
  8598. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  8599. Var accumulator = nullptr;
  8600. Var element = nullptr;
  8601. T k = 0;
  8602. T index = 0;
  8603. if (args.Info.Count > 2)
  8604. {
  8605. accumulator = args[2];
  8606. }
  8607. else
  8608. {
  8609. if (length == 0)
  8610. {
  8611. JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
  8612. }
  8613. bool bPresent = false;
  8614. if (typedArrayBase)
  8615. {
  8616. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  8617. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  8618. for (; k < end && bPresent == false; k++)
  8619. {
  8620. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  8621. index = length - k - 1;
  8622. element = typedArrayBase->DirectGetItem((uint32)index);
  8623. bPresent = true;
  8624. accumulator = element;
  8625. }
  8626. }
  8627. else
  8628. {
  8629. for (; k < length && bPresent == false; k++)
  8630. {
  8631. index = length - k - 1;
  8632. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, index));
  8633. if (hasItem)
  8634. {
  8635. JS_REENTRANT(jsReentLock, accumulator = JavascriptOperators::GetItem(obj, index, scriptContext));
  8636. bPresent = true;
  8637. }
  8638. }
  8639. }
  8640. if (bPresent == false)
  8641. {
  8642. JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
  8643. }
  8644. }
  8645. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8646. CallFlags flags = CallFlags_Value;
  8647. Var undefinedValue = scriptContext->GetLibrary()->GetUndefined();
  8648. if (typedArrayBase)
  8649. {
  8650. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  8651. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  8652. for (; k < end; k++)
  8653. {
  8654. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  8655. index = length - k - 1;
  8656. element = typedArrayBase->DirectGetItem((uint32)index);
  8657. JS_REENTRANT(jsReentLock,
  8658. accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 5), undefinedValue,
  8659. accumulator,
  8660. element,
  8661. JavascriptNumber::ToVar(index, scriptContext),
  8662. typedArrayBase));
  8663. }
  8664. }
  8665. else
  8666. {
  8667. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceRightObjectHelper<T>(obj, length, k, callBackFn, accumulator, scriptContext));
  8668. }
  8669. return accumulator;
  8670. }
  8671. template <typename T>
  8672. Var JavascriptArray::ReduceRightObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* callBackFn, Var accumulator, ScriptContext* scriptContext)
  8673. {
  8674. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8675. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  8676. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8677. CallFlags flags = CallFlags_Value;
  8678. Var element = nullptr;
  8679. T index = 0;
  8680. for (T k = start; k < length; k++)
  8681. {
  8682. index = length - k - 1;
  8683. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, index));
  8684. if (hasItem)
  8685. {
  8686. JS_REENTRANT(jsReentLock,
  8687. element = JavascriptOperators::GetItem(obj, index, scriptContext),
  8688. accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(),
  8689. callBackFn, CallInfo(flags, 5), scriptContext->GetLibrary()->GetUndefined(),
  8690. accumulator,
  8691. element,
  8692. JavascriptNumber::ToVar(index, scriptContext),
  8693. obj));
  8694. }
  8695. }
  8696. return accumulator;
  8697. }
  8698. Var JavascriptArray::EntryFrom(RecyclableObject* function, CallInfo callInfo, ...)
  8699. {
  8700. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8701. ARGUMENTS(args, callInfo);
  8702. ScriptContext* scriptContext = function->GetScriptContext();
  8703. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8704. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.from"));
  8705. Assert(!(callInfo.Flags & CallFlags_New));
  8706. JavascriptLibrary* library = scriptContext->GetLibrary();
  8707. RecyclableObject* constructor = nullptr;
  8708. if (JavascriptOperators::IsConstructor(args[0]))
  8709. {
  8710. constructor = RecyclableObject::FromVar(args[0]);
  8711. }
  8712. RecyclableObject* items = nullptr;
  8713. if (args.Info.Count < 2 || !JavascriptConversion::ToObject(args[1], scriptContext, &items))
  8714. {
  8715. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedObject, _u("Array.from"));
  8716. }
  8717. JavascriptArray* itemsArr = JavascriptOperators::TryFromVar<JavascriptArray>(items);
  8718. if (itemsArr)
  8719. {
  8720. #if ENABLE_COPYONACCESS_ARRAY
  8721. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(itemsArr);
  8722. #endif
  8723. }
  8724. SETOBJECT_FOR_MUTATION(jsReentLock, itemsArr);
  8725. bool mapping = false;
  8726. JavascriptFunction* mapFn = nullptr;
  8727. Var mapFnThisArg = nullptr;
  8728. if (args.Info.Count >= 3 && !JavascriptOperators::IsUndefinedObject(args[2]))
  8729. {
  8730. if (!JavascriptFunction::Is(args[2]))
  8731. {
  8732. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.from"));
  8733. }
  8734. mapFn = JavascriptFunction::FromVar(args[2]);
  8735. if (args.Info.Count >= 4)
  8736. {
  8737. mapFnThisArg = args[3];
  8738. }
  8739. else
  8740. {
  8741. mapFnThisArg = library->GetUndefined();
  8742. }
  8743. mapping = true;
  8744. }
  8745. RecyclableObject* newObj = nullptr;
  8746. JavascriptArray* newArr = nullptr;
  8747. JS_REENTRANT(jsReentLock, RecyclableObject* iterator = JavascriptOperators::GetIterator(items, scriptContext, true /* optional */));
  8748. if (iterator != nullptr)
  8749. {
  8750. if (constructor)
  8751. {
  8752. Js::Var constructorArgs[] = { constructor };
  8753. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  8754. JS_REENTRANT(jsReentLock, newObj = RecyclableObject::FromVar(JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext)));
  8755. newArr = JavascriptOperators::TryFromVar<JavascriptArray>(newObj);
  8756. if (newArr)
  8757. {
  8758. #if ENABLE_COPYONACCESS_ARRAY
  8759. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  8760. #endif
  8761. }
  8762. }
  8763. else
  8764. {
  8765. newArr = scriptContext->GetLibrary()->CreateArray(0);
  8766. newArr->EnsureHead<Var>();
  8767. newObj = newArr;
  8768. }
  8769. uint32 k = 0;
  8770. JS_REENTRANT(jsReentLock, JavascriptOperators::DoIteratorStepAndValue(iterator, scriptContext, [&](Var nextValue) {
  8771. if (mapping)
  8772. {
  8773. Assert(mapFn != nullptr);
  8774. Assert(mapFnThisArg != nullptr);
  8775. Var kVar = JavascriptNumber::ToVar(k, scriptContext);
  8776. nextValue = CALL_FUNCTION(scriptContext->GetThreadContext(), mapFn, CallInfo(CallFlags_Value, 3), mapFnThisArg, nextValue, kVar);
  8777. }
  8778. if (newArr)
  8779. {
  8780. newArr->SetItem(k, nextValue, PropertyOperation_None);
  8781. }
  8782. else
  8783. {
  8784. ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, k, nextValue), scriptContext, k);
  8785. }
  8786. k++;
  8787. }));
  8788. JS_REENTRANT(jsReentLock, JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(k, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  8789. }
  8790. else
  8791. {
  8792. JS_REENTRANT(jsReentLock, int64 len = (int64)OP_GetLength(items, scriptContext));
  8793. if (constructor)
  8794. {
  8795. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(len, scriptContext) };
  8796. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  8797. JS_REENTRANT(jsReentLock, newObj = RecyclableObject::FromVar(JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext)));
  8798. newArr = JavascriptOperators::TryFromVar<JavascriptArray>(newObj);
  8799. if (newArr)
  8800. {
  8801. #if ENABLE_COPYONACCESS_ARRAY
  8802. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  8803. #endif
  8804. }
  8805. }
  8806. else
  8807. {
  8808. // Abstract operation ArrayCreate throws RangeError if length argument is > 2^32 -1
  8809. if (len > MaxArrayLength)
  8810. {
  8811. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect, _u("Array.from"));
  8812. }
  8813. // Static cast len should be valid (len < 2^32) or we would throw above
  8814. newArr = scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(len));
  8815. newArr->EnsureHead<Var>();
  8816. newObj = newArr;
  8817. }
  8818. uint32 k = 0;
  8819. for ( ; k < len; k++)
  8820. {
  8821. Var kValue;
  8822. if (itemsArr)
  8823. {
  8824. JS_REENTRANT(jsReentLock, kValue = itemsArr->DirectGetItem(k));
  8825. }
  8826. else
  8827. {
  8828. JS_REENTRANT(jsReentLock, kValue = JavascriptOperators::OP_GetElementI_UInt32(items, k, scriptContext));
  8829. }
  8830. if (mapping)
  8831. {
  8832. Assert(mapFn != nullptr);
  8833. Assert(mapFnThisArg != nullptr);
  8834. Var kVar = JavascriptNumber::ToVar(k, scriptContext);
  8835. JS_REENTRANT(jsReentLock, kValue = CALL_FUNCTION(scriptContext->GetThreadContext(), mapFn, CallInfo(CallFlags_Value, 3), mapFnThisArg, kValue, kVar));
  8836. }
  8837. if (newArr)
  8838. {
  8839. newArr->SetItem(k, kValue, PropertyOperation_None);
  8840. }
  8841. else
  8842. {
  8843. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, k, kValue), scriptContext, k));
  8844. }
  8845. }
  8846. JS_REENTRANT(jsReentLock, JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(len, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  8847. }
  8848. return newObj;
  8849. }
  8850. Var JavascriptArray::EntryOf(RecyclableObject* function, CallInfo callInfo, ...)
  8851. {
  8852. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8853. ARGUMENTS(args, callInfo);
  8854. ScriptContext* scriptContext = function->GetScriptContext();
  8855. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8856. Assert(!(callInfo.Flags & CallFlags_New));
  8857. if (args.Info.Count == 0)
  8858. {
  8859. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.of"));
  8860. }
  8861. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::OfHelper(false, args, scriptContext));
  8862. }
  8863. Var JavascriptArray::EntryGetterSymbolSpecies(RecyclableObject* function, CallInfo callInfo, ...)
  8864. {
  8865. ARGUMENTS(args, callInfo);
  8866. Assert(args.Info.Count > 0);
  8867. return args[0];
  8868. }
  8869. // Array.of and %TypedArray%.of as described in ES6.0 (draft 22) Section 22.1.2.2 and 22.2.2.2
  8870. Var JavascriptArray::OfHelper(bool isTypedArrayEntryPoint, Arguments& args, ScriptContext* scriptContext)
  8871. {
  8872. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8873. Assert(args.Info.Count > 0);
  8874. // args.Info.Count cannot equal zero or we would have thrown above so no chance of underflowing
  8875. uint32 len = args.Info.Count - 1;
  8876. Var newObj = nullptr;
  8877. JavascriptArray* newArr = nullptr;
  8878. TypedArrayBase* newTypedArray = nullptr;
  8879. bool isBuiltinArrayCtor = true;
  8880. if (JavascriptOperators::IsConstructor(args[0]))
  8881. {
  8882. RecyclableObject* constructor = RecyclableObject::FromVar(args[0]);
  8883. isBuiltinArrayCtor = (constructor == scriptContext->GetLibrary()->GetArrayConstructor());
  8884. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(len, scriptContext) };
  8885. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  8886. if (isTypedArrayEntryPoint)
  8887. {
  8888. JS_REENTRANT(jsReentLock, newObj = TypedArrayBase::TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), len, scriptContext));
  8889. }
  8890. else
  8891. {
  8892. JS_REENTRANT(jsReentLock, newObj = JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext));
  8893. }
  8894. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  8895. newArr = JavascriptOperators::TryFromVar<JavascriptArray>(newObj);
  8896. if (newArr)
  8897. {
  8898. #if ENABLE_COPYONACCESS_ARRAY
  8899. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  8900. #endif
  8901. SETOBJECT_FOR_MUTATION(jsReentLock, newArr);
  8902. }
  8903. else if (TypedArrayBase::Is(newObj))
  8904. {
  8905. newTypedArray = TypedArrayBase::UnsafeFromVar(newObj);
  8906. }
  8907. }
  8908. else
  8909. {
  8910. // We only throw when the constructor property is not a constructor function in the TypedArray version
  8911. if (isTypedArrayEntryPoint)
  8912. {
  8913. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedFunction, _u("[TypedArray].of"));
  8914. }
  8915. newArr = scriptContext->GetLibrary()->CreateArray(len);
  8916. newArr->EnsureHead<Var>();
  8917. newObj = newArr;
  8918. }
  8919. // At least we have a new object of some kind
  8920. Assert(newObj);
  8921. if (isBuiltinArrayCtor)
  8922. {
  8923. for (uint32 k = 0; k < len; k++)
  8924. {
  8925. Var kValue = args[k + 1];
  8926. newArr->DirectSetItemAt(k, kValue);
  8927. }
  8928. }
  8929. else if (newTypedArray)
  8930. {
  8931. for (uint32 k = 0; k < len; k++)
  8932. {
  8933. Var kValue = args[k + 1];
  8934. JS_REENTRANT(jsReentLock, newTypedArray->DirectSetItem(k, kValue));
  8935. }
  8936. }
  8937. else
  8938. {
  8939. for (uint32 k = 0; k < len; k++)
  8940. {
  8941. Var kValue = args[k + 1];
  8942. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(RecyclableObject::FromVar(newObj), k, kValue), scriptContext, k));
  8943. }
  8944. }
  8945. if (!isTypedArrayEntryPoint)
  8946. {
  8947. // Set length if we are in the Array version of the function
  8948. JS_REENTRANT(jsReentLock, JavascriptOperators::OP_SetProperty(newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(len, scriptContext), scriptContext, nullptr, PropertyOperation_ThrowIfNotExtensible));
  8949. }
  8950. return newObj;
  8951. }
  8952. JavascriptString* JavascriptArray::ToLocaleStringHelper(Var value, ScriptContext* scriptContext)
  8953. {
  8954. TypeId typeId = JavascriptOperators::GetTypeId(value);
  8955. if (typeId <= TypeIds_UndefinedOrNull)
  8956. {
  8957. return scriptContext->GetLibrary()->GetEmptyString();
  8958. }
  8959. else
  8960. {
  8961. return JavascriptConversion::ToLocaleString(value, scriptContext);
  8962. }
  8963. }
  8964. inline BOOL JavascriptArray::IsFullArray() const
  8965. {
  8966. if (head && head->length == length)
  8967. {
  8968. AssertMsg(head->next == 0 && head->left == 0, "Invalid Array");
  8969. return true;
  8970. }
  8971. return (0 == length);
  8972. }
  8973. /*
  8974. * IsFillFromPrototypes
  8975. * - Check the array has no missing values and only head segment.
  8976. * - Also ensure if the lengths match.
  8977. */
  8978. bool JavascriptArray::IsFillFromPrototypes()
  8979. {
  8980. return !(this->head->next == nullptr && this->HasNoMissingValues() && this->length == this->head->length);
  8981. }
  8982. // Fill all missing value in the array and fill it from prototype between startIndex and limitIndex
  8983. // typically startIndex = 0 and limitIndex = length. From start of the array till end of the array.
  8984. void JavascriptArray::FillFromPrototypes(uint32 startIndex, uint32 limitIndex)
  8985. {
  8986. if (startIndex >= limitIndex)
  8987. {
  8988. return;
  8989. }
  8990. RecyclableObject* prototype = this->GetPrototype();
  8991. // Fill all missing values by walking through prototype
  8992. while (!JavascriptOperators::IsNull(prototype))
  8993. {
  8994. ForEachOwnMissingArrayIndexOfObject(this, nullptr, prototype, startIndex, limitIndex,0, [this](uint32 index, Var value) {
  8995. this->SetItem(index, value, PropertyOperation_None);
  8996. });
  8997. prototype = prototype->GetPrototype();
  8998. }
  8999. #ifdef VALIDATE_ARRAY
  9000. ValidateArray();
  9001. #endif
  9002. }
  9003. //
  9004. // JavascriptArray requires head->left == 0 for fast path Get.
  9005. //
  9006. template<typename T>
  9007. void JavascriptArray::EnsureHeadStartsFromZero(Recycler * recycler)
  9008. {
  9009. if (head == nullptr || head->left != 0)
  9010. {
  9011. // This is used to fix up altered arrays.
  9012. // any SegmentMap would be invalid at this point.
  9013. ClearSegmentMap();
  9014. //
  9015. // We could OOM and throw when allocating new empty head, resulting in a corrupted array. Need
  9016. // some protection here. Save the head and switch this array to EmptySegment. Will be restored
  9017. // correctly if allocating new segment succeeds.
  9018. //
  9019. SparseArraySegment<T>* savedHead = SparseArraySegment<T>::From(this->head);
  9020. SparseArraySegment<T>* savedLastUsedSegment = (SparseArraySegment<T>*)this->GetLastUsedSegment();
  9021. SetHeadAndLastUsedSegment(const_cast<SparseArraySegmentBase*>(EmptySegment));
  9022. SparseArraySegment<T> *newSeg = SparseArraySegment<T>::AllocateSegment(recycler, 0, 0, savedHead);
  9023. newSeg->next = savedHead;
  9024. this->head = newSeg;
  9025. SetHasNoMissingValues();
  9026. this->SetLastUsedSegment(savedLastUsedSegment);
  9027. }
  9028. }
  9029. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  9030. void JavascriptArray::CheckForceES5Array()
  9031. {
  9032. if (Configuration::Global.flags.ForceES5Array)
  9033. {
  9034. // There's a bad interaction with the jitted code for native array creation here.
  9035. // ForceES5Array doesn't interact well with native arrays
  9036. if (PHASE_OFF1(NativeArrayPhase))
  9037. {
  9038. GetTypeHandler()->ConvertToTypeWithItemAttributes(this);
  9039. }
  9040. }
  9041. }
  9042. #endif
  9043. #if DBG
  9044. void JavascriptArray::DoTypeMutation()
  9045. {
  9046. // Type transition
  9047. uint32 random1 = static_cast<uint32>(rand());
  9048. if (random1 % 2 == 0)
  9049. {
  9050. if (JavascriptNativeIntArray::Is(this))
  9051. {
  9052. uint32 random2 = static_cast<uint32>(rand());
  9053. if (random2 % 2 == 0)
  9054. {
  9055. JavascriptNativeIntArray::ToNativeFloatArray(static_cast<JavascriptNativeIntArray*>(this));
  9056. }
  9057. else
  9058. {
  9059. JavascriptNativeIntArray::ToVarArray(static_cast<JavascriptNativeIntArray*>(this));
  9060. }
  9061. }
  9062. else if (JavascriptNativeFloatArray::Is(this))
  9063. {
  9064. JavascriptNativeFloatArray::ToVarArray(static_cast<JavascriptNativeFloatArray*>(this));
  9065. }
  9066. }
  9067. }
  9068. #endif
  9069. template <typename Fn>
  9070. void JavascriptArray::ForEachOwnMissingArrayIndexOfObject(JavascriptArray *baseArray, JavascriptArray *destArray, RecyclableObject* obj, uint32 startIndex, uint32 limitIndex, uint32 destIndex, Fn fn)
  9071. {
  9072. JS_REENTRANCY_LOCK(jsReentLock, baseArray->GetScriptContext()->GetThreadContext());
  9073. SETOBJECT_FOR_MUTATION(jsReentLock, baseArray);
  9074. SET_SECOND_OBJECT_FOR_MUTATION(jsReentLock, destArray);
  9075. Assert(DynamicObject::IsAnyArray(obj) || JavascriptOperators::IsObject(obj));
  9076. Var oldValue;
  9077. JavascriptArray* arr = nullptr;
  9078. if (DynamicObject::IsAnyArray(obj))
  9079. {
  9080. arr = JavascriptArray::UnsafeFromAnyArray(obj);
  9081. }
  9082. else if (DynamicType::Is(obj->GetTypeId()))
  9083. {
  9084. DynamicObject* dynobj = DynamicObject::UnsafeFromVar(obj);
  9085. ArrayObject* objectArray = dynobj->GetObjectArray();
  9086. arr = (objectArray && JavascriptArray::IsAnyArray(objectArray)) ? JavascriptArray::UnsafeFromAnyArray(objectArray) : nullptr;
  9087. }
  9088. if (arr != nullptr)
  9089. {
  9090. if (JavascriptArray::Is(arr))
  9091. {
  9092. arr = EnsureNonNativeArray(arr);
  9093. ArrayElementEnumerator e(arr, startIndex, limitIndex);
  9094. while(e.MoveNext<Var>())
  9095. {
  9096. uint32 index = e.GetIndex();
  9097. if (!baseArray->DirectGetVarItemAt(index, &oldValue, baseArray->GetScriptContext()))
  9098. {
  9099. uint32 n = destIndex + (index - startIndex);
  9100. if (destArray == nullptr || !destArray->DirectGetItemAt(n, &oldValue))
  9101. {
  9102. JS_REENTRANT(jsReentLock, fn(index, e.GetItem<Var>()));
  9103. }
  9104. }
  9105. }
  9106. }
  9107. else
  9108. {
  9109. ScriptContext* scriptContext = obj->GetScriptContext();
  9110. Assert(ES5Array::Is(arr));
  9111. ES5Array* es5Array = ES5Array::FromVar(arr);
  9112. ES5ArrayIndexStaticEnumerator<true> e(es5Array);
  9113. while (e.MoveNext())
  9114. {
  9115. uint32 index = e.GetIndex();
  9116. if (index < startIndex) continue;
  9117. else if (index >= limitIndex) break;
  9118. if (!baseArray->DirectGetVarItemAt(index, &oldValue, baseArray->GetScriptContext()))
  9119. {
  9120. uint32 n = destIndex + (index - startIndex);
  9121. if (destArray == nullptr || !destArray->DirectGetItemAt(n, &oldValue))
  9122. {
  9123. Var value = nullptr;
  9124. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetOwnItem(obj, index, &value, scriptContext));
  9125. if (gotItem)
  9126. {
  9127. JS_REENTRANT(jsReentLock, fn(index, value));
  9128. }
  9129. }
  9130. }
  9131. }
  9132. }
  9133. }
  9134. }
  9135. //
  9136. // ArrayElementEnumerator to enumerate array elements (not including elements from prototypes).
  9137. //
  9138. JavascriptArray::ArrayElementEnumerator::ArrayElementEnumerator(JavascriptArray* arr, uint32 start, uint32 end)
  9139. : start(start), end(min(end, arr->length))
  9140. {
  9141. Init(arr);
  9142. }
  9143. //
  9144. // Initialize this enumerator and prepare for the first MoveNext.
  9145. //
  9146. void JavascriptArray::ArrayElementEnumerator::Init(JavascriptArray* arr)
  9147. {
  9148. // Find start segment
  9149. seg = (arr ? arr->GetBeginLookupSegment(start) : nullptr);
  9150. while (seg && (seg->left + seg->length <= start))
  9151. {
  9152. seg = seg->next;
  9153. }
  9154. // Set start index and endIndex
  9155. if (seg)
  9156. {
  9157. if (seg->left >= end)
  9158. {
  9159. seg = nullptr;
  9160. }
  9161. else
  9162. {
  9163. // set index to be at target index - 1, so MoveNext will move to target
  9164. index = max(seg->left, start) - seg->left - 1;
  9165. endIndex = min(end - seg->left, seg->length);
  9166. }
  9167. }
  9168. }
  9169. //
  9170. // Move to the next element if available.
  9171. //
  9172. template<typename T>
  9173. inline bool JavascriptArray::ArrayElementEnumerator::MoveNext()
  9174. {
  9175. while (seg)
  9176. {
  9177. // Look for next non-null item in current segment
  9178. while (++index < endIndex)
  9179. {
  9180. if (!SparseArraySegment<T>::IsMissingItem(&((SparseArraySegment<T>*)seg)->elements[index]))
  9181. {
  9182. return true;
  9183. }
  9184. }
  9185. // Move to next segment
  9186. seg = seg->next;
  9187. if (seg)
  9188. {
  9189. if (seg->left >= end)
  9190. {
  9191. seg = nullptr;
  9192. break;
  9193. }
  9194. else
  9195. {
  9196. index = static_cast<uint32>(-1);
  9197. endIndex = min(end - seg->left, seg->length);
  9198. }
  9199. }
  9200. }
  9201. return false;
  9202. }
  9203. //
  9204. // Get current array element index.
  9205. //
  9206. uint32 JavascriptArray::ArrayElementEnumerator::GetIndex() const
  9207. {
  9208. Assert(seg && index < seg->length && index < endIndex);
  9209. return seg->left + index;
  9210. }
  9211. //
  9212. // Get current array element value.
  9213. //
  9214. template<typename T>
  9215. T JavascriptArray::ArrayElementEnumerator::GetItem() const
  9216. {
  9217. Assert(seg && index < seg->length && index < endIndex &&
  9218. !SparseArraySegment<T>::IsMissingItem(&((SparseArraySegment<T>*)seg)->elements[index]));
  9219. return ((SparseArraySegment<T>*)seg)->elements[index];
  9220. }
  9221. //
  9222. // Construct a BigIndex initialized to a given uint32 (small index).
  9223. //
  9224. JavascriptArray::BigIndex::BigIndex(uint32 initIndex)
  9225. : index(initIndex), bigIndex(InvalidIndex)
  9226. {
  9227. //ok if initIndex == InvalidIndex
  9228. }
  9229. //
  9230. // Construct a BigIndex initialized to a given uint64 (large or small index).
  9231. //
  9232. JavascriptArray::BigIndex::BigIndex(uint64 initIndex)
  9233. : index(InvalidIndex), bigIndex(initIndex)
  9234. {
  9235. if (bigIndex < InvalidIndex) // if it's actually small index
  9236. {
  9237. index = static_cast<uint32>(bigIndex);
  9238. bigIndex = InvalidIndex;
  9239. }
  9240. }
  9241. bool JavascriptArray::BigIndex::IsUint32Max() const
  9242. {
  9243. return index == InvalidIndex && bigIndex == InvalidIndex;
  9244. }
  9245. bool JavascriptArray::BigIndex::IsSmallIndex() const
  9246. {
  9247. return index < InvalidIndex;
  9248. }
  9249. uint32 JavascriptArray::BigIndex::GetSmallIndex() const
  9250. {
  9251. Assert(IsSmallIndex());
  9252. return index;
  9253. }
  9254. uint64 JavascriptArray::BigIndex::GetBigIndex() const
  9255. {
  9256. Assert(!IsSmallIndex());
  9257. return bigIndex;
  9258. }
  9259. //
  9260. // Convert this index value to a JS number
  9261. //
  9262. Var JavascriptArray::BigIndex::ToNumber(ScriptContext* scriptContext) const
  9263. {
  9264. if (IsSmallIndex())
  9265. {
  9266. return small_index::ToNumber(index, scriptContext);
  9267. }
  9268. else
  9269. {
  9270. return JavascriptNumber::ToVar(bigIndex, scriptContext);
  9271. }
  9272. }
  9273. //
  9274. // Increment this index by 1.
  9275. //
  9276. const JavascriptArray::BigIndex& JavascriptArray::BigIndex::operator++()
  9277. {
  9278. if (IsSmallIndex())
  9279. {
  9280. ++index;
  9281. // If index reaches InvalidIndex, we will start to use bigIndex which is initially InvalidIndex.
  9282. }
  9283. else
  9284. {
  9285. bigIndex = bigIndex + 1;
  9286. }
  9287. return *this;
  9288. }
  9289. //
  9290. // Decrement this index by 1.
  9291. //
  9292. const JavascriptArray::BigIndex& JavascriptArray::BigIndex::operator--()
  9293. {
  9294. if (IsSmallIndex())
  9295. {
  9296. --index;
  9297. }
  9298. else
  9299. {
  9300. Assert(index == InvalidIndex && bigIndex >= InvalidIndex);
  9301. --bigIndex;
  9302. if (bigIndex < InvalidIndex)
  9303. {
  9304. index = InvalidIndex - 1;
  9305. bigIndex = InvalidIndex;
  9306. }
  9307. }
  9308. return *this;
  9309. }
  9310. JavascriptArray::BigIndex JavascriptArray::BigIndex::operator+(const BigIndex& delta) const
  9311. {
  9312. if (delta.IsSmallIndex())
  9313. {
  9314. return operator+(delta.GetSmallIndex());
  9315. }
  9316. if (IsSmallIndex())
  9317. {
  9318. return index + delta.GetBigIndex();
  9319. }
  9320. return bigIndex + delta.GetBigIndex();
  9321. }
  9322. //
  9323. // Get a new BigIndex representing this + delta.
  9324. //
  9325. JavascriptArray::BigIndex JavascriptArray::BigIndex::operator+(uint32 delta) const
  9326. {
  9327. if (IsSmallIndex())
  9328. {
  9329. uint32 newIndex;
  9330. if (UInt32Math::Add(index, delta, &newIndex))
  9331. {
  9332. return static_cast<uint64>(index) + static_cast<uint64>(delta);
  9333. }
  9334. else
  9335. {
  9336. return newIndex; // ok if newIndex == InvalidIndex
  9337. }
  9338. }
  9339. else
  9340. {
  9341. return bigIndex + static_cast<uint64>(delta);
  9342. }
  9343. }
  9344. bool JavascriptArray::BigIndex::operator==(const BigIndex& rhs) const
  9345. {
  9346. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9347. {
  9348. return this->GetSmallIndex() == rhs.GetSmallIndex();
  9349. }
  9350. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9351. {
  9352. // if lhs is big promote rhs
  9353. return this->GetBigIndex() == (uint64) rhs.GetSmallIndex();
  9354. }
  9355. else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
  9356. {
  9357. // if rhs is big promote lhs
  9358. return ((uint64)this->GetSmallIndex()) == rhs.GetBigIndex();
  9359. }
  9360. return this->GetBigIndex() == rhs.GetBigIndex();
  9361. }
  9362. bool JavascriptArray::BigIndex::operator> (const BigIndex& rhs) const
  9363. {
  9364. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9365. {
  9366. return this->GetSmallIndex() > rhs.GetSmallIndex();
  9367. }
  9368. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9369. {
  9370. // if lhs is big promote rhs
  9371. return this->GetBigIndex() > (uint64)rhs.GetSmallIndex();
  9372. }
  9373. else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
  9374. {
  9375. // if rhs is big promote lhs
  9376. return ((uint64)this->GetSmallIndex()) > rhs.GetBigIndex();
  9377. }
  9378. return this->GetBigIndex() > rhs.GetBigIndex();
  9379. }
  9380. bool JavascriptArray::BigIndex::operator< (const BigIndex& rhs) const
  9381. {
  9382. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9383. {
  9384. return this->GetSmallIndex() < rhs.GetSmallIndex();
  9385. }
  9386. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9387. {
  9388. // if lhs is big promote rhs
  9389. return this->GetBigIndex() < (uint64)rhs.GetSmallIndex();
  9390. }
  9391. else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
  9392. {
  9393. // if rhs is big promote lhs
  9394. return ((uint64)this->GetSmallIndex()) < rhs.GetBigIndex();
  9395. }
  9396. return this->GetBigIndex() < rhs.GetBigIndex();
  9397. }
  9398. bool JavascriptArray::BigIndex::operator<=(const BigIndex& rhs) const
  9399. {
  9400. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9401. {
  9402. return this->GetSmallIndex() <= rhs.GetSmallIndex();
  9403. }
  9404. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9405. {
  9406. // if lhs is big promote rhs
  9407. return this->GetBigIndex() <= (uint64)rhs.GetSmallIndex();
  9408. }
  9409. else if (!rhs.IsSmallIndex() && !this->IsSmallIndex())
  9410. {
  9411. // if rhs is big promote lhs
  9412. return ((uint64)this->GetSmallIndex()) <= rhs.GetBigIndex();
  9413. }
  9414. return this->GetBigIndex() <= rhs.GetBigIndex();
  9415. }
  9416. bool JavascriptArray::BigIndex::operator>=(const BigIndex& rhs) const
  9417. {
  9418. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9419. {
  9420. return this->GetSmallIndex() >= rhs.GetSmallIndex();
  9421. }
  9422. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9423. {
  9424. // if lhs is big promote rhs
  9425. return this->GetBigIndex() >= (uint64)rhs.GetSmallIndex();
  9426. }
  9427. else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
  9428. {
  9429. // if rhs is big promote lhs
  9430. return ((uint64)this->GetSmallIndex()) >= rhs.GetBigIndex();
  9431. }
  9432. return this->GetBigIndex() >= rhs.GetBigIndex();
  9433. }
  9434. BOOL JavascriptArray::BigIndex::GetItem(JavascriptArray* arr, Var* outVal) const
  9435. {
  9436. if (IsSmallIndex())
  9437. {
  9438. return small_index::GetItem(arr, index, outVal);
  9439. }
  9440. else
  9441. {
  9442. ScriptContext* scriptContext = arr->GetScriptContext();
  9443. PropertyRecord const * propertyRecord;
  9444. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9445. return arr->GetProperty(arr, propertyRecord->GetPropertyId(), outVal, NULL, scriptContext);
  9446. }
  9447. }
  9448. BOOL JavascriptArray::BigIndex::SetItem(JavascriptArray* arr, Var newValue) const
  9449. {
  9450. if (IsSmallIndex())
  9451. {
  9452. return small_index::SetItem(arr, index, newValue);
  9453. }
  9454. else
  9455. {
  9456. ScriptContext* scriptContext = arr->GetScriptContext();
  9457. PropertyRecord const * propertyRecord;
  9458. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9459. return arr->SetProperty(propertyRecord->GetPropertyId(), newValue, PropertyOperation_None, NULL);
  9460. }
  9461. }
  9462. void JavascriptArray::BigIndex::SetItemIfNotExist(JavascriptArray* arr, Var newValue) const
  9463. {
  9464. if (IsSmallIndex())
  9465. {
  9466. small_index::SetItemIfNotExist(arr, index, newValue);
  9467. }
  9468. else
  9469. {
  9470. ScriptContext* scriptContext = arr->GetScriptContext();
  9471. PropertyRecord const * propertyRecord;
  9472. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9473. Var oldValue;
  9474. PropertyId propertyId = propertyRecord->GetPropertyId();
  9475. if (!arr->GetProperty(arr, propertyId, &oldValue, NULL, scriptContext))
  9476. {
  9477. arr->SetProperty(propertyId, newValue, PropertyOperation_None, NULL);
  9478. }
  9479. }
  9480. }
  9481. BOOL JavascriptArray::BigIndex::DeleteItem(JavascriptArray* arr) const
  9482. {
  9483. if (IsSmallIndex())
  9484. {
  9485. return small_index::DeleteItem(arr, index);
  9486. }
  9487. else
  9488. {
  9489. ScriptContext* scriptContext = arr->GetScriptContext();
  9490. PropertyRecord const * propertyRecord;
  9491. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9492. return arr->DeleteProperty(propertyRecord->GetPropertyId(), PropertyOperation_None);
  9493. }
  9494. }
  9495. BOOL JavascriptArray::BigIndex::SetItem(RecyclableObject* obj, Var newValue, PropertyOperationFlags flags) const
  9496. {
  9497. if (IsSmallIndex())
  9498. {
  9499. return small_index::SetItem(obj, index, newValue, flags);
  9500. }
  9501. else
  9502. {
  9503. ScriptContext* scriptContext = obj->GetScriptContext();
  9504. PropertyRecord const * propertyRecord;
  9505. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9506. return JavascriptOperators::SetProperty(obj, obj, propertyRecord->GetPropertyId(), newValue, scriptContext, flags);
  9507. }
  9508. }
  9509. BOOL JavascriptArray::BigIndex::DeleteItem(RecyclableObject* obj, PropertyOperationFlags flags) const
  9510. {
  9511. if (IsSmallIndex())
  9512. {
  9513. return small_index::DeleteItem(obj, index, flags);
  9514. }
  9515. else
  9516. {
  9517. PropertyRecord const * propertyRecord;
  9518. JavascriptOperators::GetPropertyIdForInt(bigIndex, obj->GetScriptContext(), &propertyRecord);
  9519. return JavascriptOperators::DeleteProperty(obj, propertyRecord->GetPropertyId(), flags);
  9520. }
  9521. }
  9522. //
  9523. // Truncate the array at start and clone the truncated span as properties starting at dstIndex (asserting dstIndex >= MaxArrayLength).
  9524. //
  9525. void JavascriptArray::TruncateToProperties(const BigIndex& dstIndex, uint32 start)
  9526. {
  9527. Assert(!dstIndex.IsSmallIndex());
  9528. typedef IndexTrace<BigIndex> index_trace;
  9529. BigIndex dst = dstIndex;
  9530. uint32 i = start;
  9531. ArrayElementEnumerator e(this, start);
  9532. while(e.MoveNext<Var>())
  9533. {
  9534. // delete all items not enumerated
  9535. while (i < e.GetIndex())
  9536. {
  9537. index_trace::DeleteItem(this, dst);
  9538. ++i;
  9539. ++dst;
  9540. }
  9541. // Copy over the item
  9542. index_trace::SetItem(this, dst, e.GetItem<Var>());
  9543. ++i;
  9544. ++dst;
  9545. }
  9546. // Delete the rest till length
  9547. while (i < this->length)
  9548. {
  9549. index_trace::DeleteItem(this, dst);
  9550. ++i;
  9551. ++dst;
  9552. }
  9553. // Elements moved, truncate the array at start
  9554. SetLength(start);
  9555. }
  9556. //
  9557. // Copy a srcArray elements (including elements from prototypes) to a dstArray starting from an index.
  9558. //
  9559. void JavascriptArray::InternalCopyArrayElements(JavascriptArray* dstArray, const uint32 dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
  9560. {
  9561. Assert(start < end && end <= srcArray->length);
  9562. uint32 count = 0;
  9563. // iterate on the array itself
  9564. ArrayElementEnumerator e(srcArray, start, end);
  9565. while(e.MoveNext<Var>())
  9566. {
  9567. uint32 n = dstIndex + (e.GetIndex() - start);
  9568. dstArray->DirectSetItemAt(n, e.GetItem<Var>());
  9569. count++;
  9570. }
  9571. // iterate on the array's prototypes only if not all elements found
  9572. if (start + count != end)
  9573. {
  9574. InternalFillFromPrototype(dstArray, dstIndex, srcArray, start, end, count);
  9575. }
  9576. }
  9577. //
  9578. // Faster small_index overload of CopyArrayElements, asserting the uint32 dstIndex won't overflow.
  9579. //
  9580. void JavascriptArray::CopyArrayElements(JavascriptArray* dstArray, uint32 dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
  9581. {
  9582. end = min(end, srcArray->length);
  9583. if (start < end)
  9584. {
  9585. Assert(end - start <= MaxArrayLength - dstIndex);
  9586. InternalCopyArrayElements(dstArray, dstIndex, srcArray, start, end);
  9587. }
  9588. }
  9589. template <typename T>
  9590. void JavascriptArray::CopyAnyArrayElementsToVar(JavascriptArray* dstArray, T dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
  9591. {
  9592. #if ENABLE_COPYONACCESS_ARRAY
  9593. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(srcArray);
  9594. #endif
  9595. #if ENABLE_COPYONACCESS_ARRAY
  9596. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(dstArray);
  9597. #endif
  9598. JavascriptNativeIntArray * nativeIntArray = JavascriptOperators::TryFromVar<JavascriptNativeIntArray>(srcArray);
  9599. if (nativeIntArray)
  9600. {
  9601. CopyNativeIntArrayElementsToVar(dstArray, dstIndex, nativeIntArray, start, end);
  9602. }
  9603. else
  9604. {
  9605. JavascriptNativeFloatArray * nativeFloatArray = JavascriptOperators::TryFromVar<JavascriptNativeFloatArray>(srcArray);
  9606. if (nativeFloatArray)
  9607. {
  9608. CopyNativeFloatArrayElementsToVar(dstArray, dstIndex, nativeFloatArray, start, end);
  9609. }
  9610. else
  9611. {
  9612. CopyArrayElements(dstArray, dstIndex, srcArray, start, end);
  9613. }
  9614. }
  9615. }
  9616. //
  9617. // Faster small_index overload of CopyArrayElements, asserting the uint32 dstIndex won't overflow.
  9618. //
  9619. void JavascriptArray::CopyNativeIntArrayElementsToVar(JavascriptArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
  9620. {
  9621. end = min(end, srcArray->length);
  9622. if (start < end)
  9623. {
  9624. Assert(end - start <= MaxArrayLength - dstIndex);
  9625. InternalCopyNativeIntArrayElements(dstArray, dstIndex, srcArray, start, end);
  9626. }
  9627. }
  9628. bool JavascriptArray::CopyNativeIntArrayElements(JavascriptNativeIntArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
  9629. {
  9630. end = min(end, srcArray->length);
  9631. if (start >= end)
  9632. {
  9633. return false;
  9634. }
  9635. Assert(end - start <= MaxArrayLength - dstIndex);
  9636. Assert(start < end && end <= srcArray->length);
  9637. uint32 count = 0;
  9638. // iterate on the array itself
  9639. ArrayElementEnumerator e(srcArray, start, end);
  9640. while(e.MoveNext<int32>())
  9641. {
  9642. uint n = dstIndex + (e.GetIndex() - start);
  9643. dstArray->DirectSetItemAt(n, e.GetItem<int32>());
  9644. count++;
  9645. }
  9646. // iterate on the array's prototypes only if not all elements found
  9647. if (start + count != end)
  9648. {
  9649. JavascriptArray *varArray = JavascriptNativeIntArray::ToVarArray(dstArray);
  9650. InternalFillFromPrototype(varArray, dstIndex, srcArray, start, end, count);
  9651. return true;
  9652. }
  9653. return false;
  9654. }
  9655. bool JavascriptArray::CopyNativeIntArrayElementsToFloat(JavascriptNativeFloatArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
  9656. {
  9657. end = min(end, srcArray->length);
  9658. if (start >= end)
  9659. {
  9660. return false;
  9661. }
  9662. Assert(end - start <= MaxArrayLength - dstIndex);
  9663. Assert(start < end && end <= srcArray->length);
  9664. uint32 count = 0;
  9665. // iterate on the array itself
  9666. ArrayElementEnumerator e(srcArray, start, end);
  9667. while(e.MoveNext<int32>())
  9668. {
  9669. uint n = dstIndex + (e.GetIndex() - start);
  9670. dstArray->DirectSetItemAt(n, (double)e.GetItem<int32>());
  9671. count++;
  9672. }
  9673. // iterate on the array's prototypes only if not all elements found
  9674. if (start + count != end)
  9675. {
  9676. JavascriptArray *varArray = JavascriptNativeFloatArray::ToVarArray(dstArray);
  9677. InternalFillFromPrototype(varArray, dstIndex, srcArray, start, end, count);
  9678. return true;
  9679. }
  9680. return false;
  9681. }
  9682. //
  9683. // Faster small_index overload of CopyArrayElements, asserting the uint32 dstIndex won't overflow.
  9684. //
  9685. void JavascriptArray::CopyNativeFloatArrayElementsToVar(JavascriptArray* dstArray, uint32 dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
  9686. {
  9687. end = min(end, srcArray->length);
  9688. if (start < end)
  9689. {
  9690. Assert(end - start <= MaxArrayLength - dstIndex);
  9691. InternalCopyNativeFloatArrayElements(dstArray, dstIndex, srcArray, start, end);
  9692. }
  9693. }
  9694. bool JavascriptArray::CopyNativeFloatArrayElements(JavascriptNativeFloatArray* dstArray, uint32 dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
  9695. {
  9696. end = min(end, srcArray->length);
  9697. if (start >= end)
  9698. {
  9699. return false;
  9700. }
  9701. Assert(end - start <= MaxArrayLength - dstIndex);
  9702. Assert(start < end && end <= srcArray->length);
  9703. uint32 count = 0;
  9704. // iterate on the array itself
  9705. ArrayElementEnumerator e(srcArray, start, end);
  9706. while(e.MoveNext<double>())
  9707. {
  9708. uint n = dstIndex + (e.GetIndex() - start);
  9709. dstArray->DirectSetItemAt(n, e.GetItem<double>());
  9710. count++;
  9711. }
  9712. // iterate on the array's prototypes only if not all elements found
  9713. if (start + count != end)
  9714. {
  9715. JavascriptArray *varArray = JavascriptNativeFloatArray::ToVarArray(dstArray);
  9716. InternalFillFromPrototype(varArray, dstIndex, srcArray, start, end, count);
  9717. return true;
  9718. }
  9719. return false;
  9720. }
  9721. JavascriptArray *JavascriptArray::EnsureNonNativeArray(JavascriptArray *arr)
  9722. {
  9723. #if ENABLE_COPYONACCESS_ARRAY
  9724. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(arr);
  9725. #endif
  9726. if (JavascriptNativeIntArray::Is(arr))
  9727. {
  9728. arr = JavascriptNativeIntArray::ToVarArray((JavascriptNativeIntArray*)arr);
  9729. }
  9730. else if (JavascriptNativeFloatArray::Is(arr))
  9731. {
  9732. arr = JavascriptNativeFloatArray::ToVarArray((JavascriptNativeFloatArray*)arr);
  9733. }
  9734. return arr;
  9735. }
  9736. BOOL JavascriptNativeIntArray::DirectGetItemAtFull(uint32 index, Var* outVal)
  9737. {
  9738. ScriptContext* requestContext = type->GetScriptContext();
  9739. if (JavascriptConversion::PropertyQueryFlagsToBoolean(JavascriptNativeIntArray::GetItemQuery(this, index, outVal, requestContext)))
  9740. {
  9741. return TRUE;
  9742. }
  9743. return JavascriptOperators::GetItem(this, this->GetPrototype(), index, outVal, requestContext);
  9744. }
  9745. BOOL JavascriptNativeFloatArray::DirectGetItemAtFull(uint32 index, Var* outVal)
  9746. {
  9747. ScriptContext* requestContext = type->GetScriptContext();
  9748. if (JavascriptConversion::PropertyQueryFlagsToBoolean(JavascriptNativeFloatArray::GetItemQuery(this, index, outVal, requestContext)))
  9749. {
  9750. return TRUE;
  9751. }
  9752. return JavascriptOperators::GetItem(this, this->GetPrototype(), index, outVal, requestContext);
  9753. }
  9754. void JavascriptArray::InternalCopyNativeIntArrayElements(JavascriptArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
  9755. {
  9756. Assert(start < end && end <= srcArray->length);
  9757. uint32 count = 0;
  9758. // iterate on the array itself
  9759. ScriptContext *scriptContext = dstArray->GetScriptContext();
  9760. ArrayElementEnumerator e(srcArray, start, end);
  9761. while(e.MoveNext<int32>())
  9762. {
  9763. uint32 n = dstIndex + (e.GetIndex() - start);
  9764. dstArray->DirectSetItemAt(n, JavascriptNumber::ToVar(e.GetItem<int32>(), scriptContext));
  9765. count++;
  9766. }
  9767. // iterate on the array's prototypes only if not all elements found
  9768. if (start + count != end)
  9769. {
  9770. InternalFillFromPrototype(dstArray, dstIndex, srcArray, start, end, count);
  9771. }
  9772. }
  9773. void JavascriptArray::InternalCopyNativeFloatArrayElements(JavascriptArray* dstArray, uint32 dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
  9774. {
  9775. Assert(start < end && end <= srcArray->length);
  9776. uint32 count = 0;
  9777. // iterate on the array itself
  9778. ScriptContext *scriptContext = dstArray->GetScriptContext();
  9779. ArrayElementEnumerator e(srcArray, start, end);
  9780. while(e.MoveNext<double>())
  9781. {
  9782. uint32 n = dstIndex + (e.GetIndex() - start);
  9783. dstArray->DirectSetItemAt(n, JavascriptNumber::ToVarWithCheck(e.GetItem<double>(), scriptContext));
  9784. count++;
  9785. }
  9786. // iterate on the array's prototypes only if not all elements found
  9787. if (start + count != end)
  9788. {
  9789. InternalFillFromPrototype(dstArray, dstIndex, srcArray, start, end, count);
  9790. }
  9791. }
  9792. Var JavascriptArray::SpreadArrayArgs(Var arrayToSpread, const Js::AuxArray<uint32> *spreadIndices, ScriptContext *scriptContext)
  9793. {
  9794. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  9795. SETOBJECT_FOR_MUTATION(jsReentLock, arrayToSpread);
  9796. // At this stage we have an array literal with some arguments to be spread.
  9797. // First we need to calculate the real size of the final literal.
  9798. #if ENABLE_COPYONACCESS_ARRAY
  9799. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(arrayToSpread);
  9800. #endif
  9801. JavascriptArray *array = FromVar(arrayToSpread);
  9802. uint32 arrayLength = array->GetLength();
  9803. uint32 actualLength = arrayLength;
  9804. for (unsigned i = 0; i < spreadIndices->count; ++i)
  9805. {
  9806. JS_REENTRANT(jsReentLock,
  9807. actualLength = UInt32Math::Add(actualLength - 1, GetSpreadArgLen(array->DirectGetItem(spreadIndices->elements[i]), scriptContext)));
  9808. }
  9809. JavascriptArray *result = FromVar(OP_NewScArrayWithMissingValues(actualLength, scriptContext));
  9810. // Now we copy each element and expand the spread parameters inline.
  9811. for (unsigned i = 0, spreadArrIndex = 0, resultIndex = 0; i < arrayLength && resultIndex < actualLength; ++i)
  9812. {
  9813. uint32 spreadIndex = spreadIndices->elements[spreadArrIndex]; // The index of the next element to be spread.
  9814. // 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.
  9815. auto needArraySlowCopy = [&](Var instance) {
  9816. JavascriptArray *arr = JavascriptOperators::TryFromVar<JavascriptArray>(instance);
  9817. if (arr)
  9818. {
  9819. JS_REENTRANT_UNLOCK(jsReentLock, return arr->IsCrossSiteObject() || arr->IsFillFromPrototypes());
  9820. }
  9821. return false;
  9822. };
  9823. // Designed to have interchangeable arguments with CopyAnyArrayElementsToVar.
  9824. auto slowCopy = [&scriptContext, &needArraySlowCopy
  9825. ](JavascriptArray *dstArray, unsigned dstIndex, Var srcArray, uint32 start, uint32 end) {
  9826. Assert(needArraySlowCopy(srcArray) || ArgumentsObject::Is(srcArray) || TypedArrayBase::Is(srcArray) || JavascriptString::Is(srcArray));
  9827. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  9828. RecyclableObject *propertyObject;
  9829. if (!JavascriptOperators::GetPropertyObject(srcArray, scriptContext, &propertyObject))
  9830. {
  9831. JavascriptError::ThrowTypeError(scriptContext, JSERR_InvalidSpreadArgument);
  9832. }
  9833. for (uint32 j = start; j < end; j++)
  9834. {
  9835. Var element;
  9836. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(srcArray, propertyObject, j, &element, scriptContext));
  9837. if (!gotItem)
  9838. {
  9839. // Copy across missing values as undefined as per 12.2.5.2 SpreadElement : ... AssignmentExpression 5f.
  9840. element = scriptContext->GetLibrary()->GetUndefined();
  9841. }
  9842. dstArray->DirectSetItemAt(dstIndex++, element);
  9843. }
  9844. };
  9845. if (i < spreadIndex)
  9846. {
  9847. // Any non-spread elements can be copied in bulk.
  9848. if (needArraySlowCopy(array))
  9849. {
  9850. slowCopy(result, resultIndex, (Var)array, i, spreadIndex);
  9851. }
  9852. else
  9853. {
  9854. JS_REENTRANT(jsReentLock, CopyAnyArrayElementsToVar(result, resultIndex, array, i, spreadIndex));
  9855. }
  9856. resultIndex += spreadIndex - i;
  9857. i = spreadIndex - 1;
  9858. continue;
  9859. }
  9860. else if (i > spreadIndex)
  9861. {
  9862. // Any non-spread elements terminating the array can also be copied in bulk.
  9863. Assert(spreadArrIndex == spreadIndices->count - 1);
  9864. if (needArraySlowCopy(array))
  9865. {
  9866. slowCopy(result, resultIndex, array, i, arrayLength);
  9867. }
  9868. else
  9869. {
  9870. JS_REENTRANT(jsReentLock, CopyAnyArrayElementsToVar(result, resultIndex, array, i, arrayLength));
  9871. }
  9872. break;
  9873. }
  9874. else
  9875. {
  9876. JS_REENTRANT(jsReentLock, Var instance = array->DirectGetItem(i));
  9877. if (SpreadArgument::Is(instance))
  9878. {
  9879. SpreadArgument* spreadArgument = SpreadArgument::FromVar(instance);
  9880. uint32 len = spreadArgument->GetArgumentSpreadCount();
  9881. const Var* spreadItems = spreadArgument->GetArgumentSpread();
  9882. for (uint32 j = 0; j < len; j++)
  9883. {
  9884. result->DirectSetItemAt(resultIndex++, spreadItems[j]);
  9885. }
  9886. }
  9887. else
  9888. {
  9889. Assert(JavascriptOperators::IsUndefinedObject(instance));
  9890. result->DirectSetItemAt(resultIndex++, instance);
  9891. }
  9892. if (spreadArrIndex < spreadIndices->count - 1)
  9893. {
  9894. spreadArrIndex++;
  9895. }
  9896. }
  9897. }
  9898. AssertMsg(arrayLength == array->GetLength(), "Array's length should not have changed");
  9899. return result;
  9900. }
  9901. uint32 JavascriptArray::GetSpreadArgLen(Var spreadArg, ScriptContext *scriptContext)
  9902. {
  9903. // A spread argument can be anything that returns a 'length' property, even if that
  9904. // property is null or undefined.
  9905. spreadArg = CrossSite::MarshalVar(scriptContext, spreadArg);
  9906. JavascriptArray *arr = JavascriptOperators::TryFromVar<JavascriptArray>(spreadArg);
  9907. if (arr)
  9908. {
  9909. return arr->GetLength();
  9910. }
  9911. TypedArrayBase *tarr = JavascriptOperators::TryFromVar<Js::TypedArrayBase>(spreadArg);
  9912. if (tarr)
  9913. {
  9914. return tarr->GetLength();
  9915. }
  9916. if (SpreadArgument::Is(spreadArg))
  9917. {
  9918. SpreadArgument *spreadFunctionArgs = SpreadArgument::FromVar(spreadArg);
  9919. return spreadFunctionArgs->GetArgumentSpreadCount();
  9920. }
  9921. AssertMsg(false, "LdCustomSpreadIteratorList should have converted the arg to one of the above types");
  9922. Throw::FatalInternalError();
  9923. }
  9924. #ifdef VALIDATE_ARRAY
  9925. class ArraySegmentsVisitor
  9926. {
  9927. private:
  9928. SparseArraySegmentBase* seg;
  9929. public:
  9930. ArraySegmentsVisitor(SparseArraySegmentBase* head)
  9931. : seg(head)
  9932. {
  9933. }
  9934. void operator()(SparseArraySegmentBase* s)
  9935. {
  9936. Assert(seg == s);
  9937. if (seg)
  9938. {
  9939. seg = seg->next;
  9940. }
  9941. }
  9942. };
  9943. void JavascriptArray::ValidateArrayCommon()
  9944. {
  9945. SparseArraySegmentBase * lastUsedSegment = this->GetLastUsedSegment();
  9946. AssertMsg(this != nullptr && head && lastUsedSegment, "Array should not be null");
  9947. AssertMsg(head->left == 0, "Array always should have a segment starting at zero");
  9948. // Simple segments validation
  9949. bool foundLastUsedSegment = false;
  9950. SparseArraySegmentBase *seg = head;
  9951. while(seg != nullptr)
  9952. {
  9953. if (seg == lastUsedSegment)
  9954. {
  9955. foundLastUsedSegment = true;
  9956. }
  9957. AssertMsg(seg->length <= seg->size , "Length greater than size not possible");
  9958. SparseArraySegmentBase* next = seg->next;
  9959. if (next != nullptr)
  9960. {
  9961. AssertMsg(seg->left < next->left, "Segment is adjacent to or overlaps with next segment");
  9962. AssertMsg(seg->size <= (next->left - seg->left), "Segment is adjacent to or overlaps with next segment");
  9963. AssertMsg(!SparseArraySegmentBase::IsLeafSegment(seg, this->GetScriptContext()->GetRecycler()), "Leaf segment with a next pointer");
  9964. }
  9965. else
  9966. {
  9967. AssertMsg(seg->length <= MaxArrayLength - seg->left, "Segment index range overflow");
  9968. AssertMsg(seg->left + seg->length <= this->length, "Segment index range exceeds array length");
  9969. }
  9970. seg = next;
  9971. }
  9972. AssertMsg(foundLastUsedSegment || HasSegmentMap(), "Corrupt lastUsedSegment in array header");
  9973. // Validate segmentMap if present
  9974. if (HasSegmentMap())
  9975. {
  9976. ArraySegmentsVisitor visitor(head);
  9977. GetSegmentMap()->Walk(visitor);
  9978. }
  9979. }
  9980. void JavascriptArray::ValidateArray()
  9981. {
  9982. if (!Js::Configuration::Global.flags.ArrayValidate)
  9983. {
  9984. return;
  9985. }
  9986. ValidateArrayCommon();
  9987. // Detailed segments validation
  9988. JavascriptArray::ValidateVarSegment(SparseArraySegment<Var>::From(head));
  9989. }
  9990. void JavascriptNativeIntArray::ValidateArray()
  9991. {
  9992. if (!Js::Configuration::Global.flags.ArrayValidate)
  9993. {
  9994. #if DBG
  9995. SparseArraySegmentBase *seg = head;
  9996. while (seg)
  9997. {
  9998. if (seg->next != nullptr)
  9999. {
  10000. AssertMsg(!SparseArraySegmentBase::IsLeafSegment(seg, this->GetScriptContext()->GetRecycler()), "Leaf segment with a next pointer");
  10001. }
  10002. seg = seg->next;
  10003. }
  10004. #endif
  10005. return;
  10006. }
  10007. ValidateArrayCommon();
  10008. // Detailed segments validation
  10009. JavascriptArray::ValidateSegment<int32>(SparseArraySegment<int32>::From(head));
  10010. }
  10011. void JavascriptNativeFloatArray::ValidateArray()
  10012. {
  10013. if (!Js::Configuration::Global.flags.ArrayValidate)
  10014. {
  10015. #if DBG
  10016. SparseArraySegmentBase *seg = head;
  10017. while (seg)
  10018. {
  10019. if (seg->next != nullptr)
  10020. {
  10021. AssertMsg(!SparseArraySegmentBase::IsLeafSegment(seg, this->GetScriptContext()->GetRecycler()), "Leaf segment with a next pointer");
  10022. }
  10023. seg = seg->next;
  10024. }
  10025. #endif
  10026. return;
  10027. }
  10028. ValidateArrayCommon();
  10029. // Detailed segments validation
  10030. JavascriptArray::ValidateSegment<double>(SparseArraySegment<double>::From(head));
  10031. }
  10032. void JavascriptArray::ValidateVarSegment(SparseArraySegment<Var>* seg)
  10033. {
  10034. if (!Js::Configuration::Global.flags.ArrayValidate)
  10035. {
  10036. return;
  10037. }
  10038. int32 inspect;
  10039. double inspectDouble;
  10040. while (seg)
  10041. {
  10042. uint32 i = 0;
  10043. for (i = 0; i < seg->length; i++)
  10044. {
  10045. if (SparseArraySegment<Var>::IsMissingItem(&seg->elements[i]))
  10046. {
  10047. continue;
  10048. }
  10049. if (TaggedInt::Is(seg->elements[i]))
  10050. {
  10051. inspect = TaggedInt::ToInt32(seg->elements[i]);
  10052. }
  10053. else if (JavascriptNumber::Is_NoTaggedIntCheck(seg->elements[i]))
  10054. {
  10055. inspectDouble = JavascriptNumber::GetValue(seg->elements[i]);
  10056. }
  10057. else
  10058. {
  10059. AssertMsg(RecyclableObject::Is(seg->elements[i]), "Invalid entry in segment");
  10060. }
  10061. }
  10062. ValidateSegment(seg);
  10063. seg = SparseArraySegment<Var>::From(seg->next);
  10064. }
  10065. }
  10066. template<typename T>
  10067. void JavascriptArray::ValidateSegment(SparseArraySegment<T>* seg)
  10068. {
  10069. if (!Js::Configuration::Global.flags.ArrayValidate)
  10070. {
  10071. return;
  10072. }
  10073. while (seg)
  10074. {
  10075. uint32 i = seg->length;
  10076. while (i < seg->size)
  10077. {
  10078. AssertMsg(SparseArraySegment<T>::IsMissingItem(&seg->elements[i]), "Non missing value the end of the segment");
  10079. i++;
  10080. }
  10081. seg = SparseArraySegment<T>::From(seg->next);
  10082. }
  10083. }
  10084. #endif
  10085. template <typename T>
  10086. void JavascriptArray::InitBoxedInlineSegments(SparseArraySegment<T> * dst, SparseArraySegment<T> * src, bool deepCopy)
  10087. {
  10088. // Don't copy the segment map, we will build it again
  10089. SetFlags(GetFlags() & ~DynamicObjectFlags::HasSegmentMap);
  10090. SetHeadAndLastUsedSegment(dst);
  10091. // Copy head segment data
  10092. dst->left = src->left;
  10093. dst->length = src->length;
  10094. dst->size = src->size;
  10095. dst->CheckLengthvsSize();
  10096. CopyArray(dst->elements, dst->size, src->elements, src->size);
  10097. if (!deepCopy)
  10098. {
  10099. // Without a deep copy, point to the existing next segment
  10100. dst->next = src->next;
  10101. }
  10102. else
  10103. {
  10104. // When deepCopy is true, make a separate copy of each segment. While this involves data
  10105. // duplication, it allows the new object to have a separate lifetime without sharing data.
  10106. AutoDisableInterrupt failFastError(GetScriptContext()->GetThreadContext());
  10107. do
  10108. {
  10109. if (src->next != nullptr)
  10110. {
  10111. // Allocate a new segment in the destination and copy from src
  10112. src = SparseArraySegment<T>::From(src->next);
  10113. dst->next = dst->AllocateSegment(GetRecycler(), src->left, src->length, src->size, src->next);
  10114. dst = SparseArraySegment<T>::From(dst->next);
  10115. CopyArray(dst->elements, dst->size, src->elements, src->size);
  10116. }
  10117. else
  10118. {
  10119. // Terminate the loop
  10120. dst->next = nullptr;
  10121. dst = nullptr;
  10122. }
  10123. } while (dst != nullptr);
  10124. failFastError.Completed();
  10125. }
  10126. }
  10127. JavascriptArray::JavascriptArray(JavascriptArray * instance, bool boxHead, bool deepCopy)
  10128. : ArrayObject(instance)
  10129. {
  10130. if (boxHead)
  10131. {
  10132. InitBoxedInlineSegments(DetermineInlineHeadSegmentPointer<JavascriptArray, 0, true>(this), SparseArraySegment<Var>::From(instance->head), false);
  10133. }
  10134. else
  10135. {
  10136. SetFlags(GetFlags() & ~DynamicObjectFlags::HasSegmentMap);
  10137. head = instance->head;
  10138. SetLastUsedSegment(instance->GetLastUsedSegment());
  10139. }
  10140. }
  10141. template <typename T>
  10142. T * JavascriptArray::BoxStackInstance(T * instance, bool deepCopy)
  10143. {
  10144. Assert(ThreadContext::IsOnStack(instance));
  10145. // On the stack, the we reserved a pointer before the object as to store the boxed value
  10146. T ** boxedInstanceRef = ((T **)instance) - 1;
  10147. T * boxedInstance = *boxedInstanceRef;
  10148. if (boxedInstance)
  10149. {
  10150. return boxedInstance;
  10151. }
  10152. const size_t inlineSlotsSize = instance->GetTypeHandler()->GetInlineSlotsSize();
  10153. if (ThreadContext::IsOnStack(instance->head))
  10154. {
  10155. boxedInstance = RecyclerNewPlusZ(instance->GetRecycler(),
  10156. inlineSlotsSize + sizeof(Js::SparseArraySegmentBase) + instance->head->size * sizeof(typename T::TElement),
  10157. T, instance, true, deepCopy);
  10158. }
  10159. else if(inlineSlotsSize)
  10160. {
  10161. boxedInstance = RecyclerNewPlusZ(instance->GetRecycler(), inlineSlotsSize, T, instance, false, false);
  10162. }
  10163. else
  10164. {
  10165. boxedInstance = RecyclerNew(instance->GetRecycler(), T, instance, false, false);
  10166. }
  10167. *boxedInstanceRef = boxedInstance;
  10168. return boxedInstance;
  10169. }
  10170. JavascriptArray *
  10171. JavascriptArray::BoxStackInstance(JavascriptArray * instance, bool deepCopy)
  10172. {
  10173. return BoxStackInstance<JavascriptArray>(instance, deepCopy);
  10174. }
  10175. #if ENABLE_TTD
  10176. void JavascriptArray::MarkVisitKindSpecificPtrs(TTD::SnapshotExtractor* extractor)
  10177. {
  10178. TTDAssert(this->GetTypeId() == Js::TypeIds_Array || this->GetTypeId() == Js::TypeIds_ES5Array, "Should only be used on basic arrays (or called as super from ES5Array.");
  10179. ScriptContext* ctx = this->GetScriptContext();
  10180. uint32 index = Js::JavascriptArray::InvalidIndex;
  10181. while(true)
  10182. {
  10183. index = this->GetNextIndex(index);
  10184. if(index == Js::JavascriptArray::InvalidIndex) // End of array
  10185. {
  10186. break;
  10187. }
  10188. Js::Var aval = nullptr;
  10189. if(this->DirectGetVarItemAt(index, &aval, ctx))
  10190. {
  10191. extractor->MarkVisitVar(aval);
  10192. }
  10193. }
  10194. }
  10195. void JavascriptArray::ProcessCorePaths()
  10196. {
  10197. TTDAssert(this->GetTypeId() == Js::TypeIds_Array, "Should only be used on basic arrays.");
  10198. ScriptContext* ctx = this->GetScriptContext();
  10199. uint32 index = Js::JavascriptArray::InvalidIndex;
  10200. while(true)
  10201. {
  10202. index = this->GetNextIndex(index);
  10203. if(index == Js::JavascriptArray::InvalidIndex) // End of array
  10204. {
  10205. break;
  10206. }
  10207. Js::Var aval = nullptr;
  10208. if(this->DirectGetVarItemAt(index, &aval, ctx))
  10209. {
  10210. TTD::UtilSupport::TTAutoString pathExt;
  10211. ctx->TTDWellKnownInfo->BuildArrayIndexBuffer(index, pathExt);
  10212. ctx->TTDWellKnownInfo->EnqueueNewPathVarAsNeeded(this, aval, pathExt.GetStrValue());
  10213. }
  10214. }
  10215. }
  10216. TTD::NSSnapObjects::SnapObjectType JavascriptArray::GetSnapTag_TTD() const
  10217. {
  10218. return TTD::NSSnapObjects::SnapObjectType::SnapArrayObject;
  10219. }
  10220. void JavascriptArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  10221. {
  10222. TTDAssert(this->GetTypeId() == Js::TypeIds_Array, "Should only be used on basic Js arrays.");
  10223. TTD::NSSnapObjects::SnapArrayInfo<TTD::TTDVar>* sai = TTD::NSSnapObjects::ExtractArrayValues<TTD::TTDVar>(this, alloc);
  10224. TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayInfo<TTD::TTDVar>*, TTD::NSSnapObjects::SnapObjectType::SnapArrayObject>(objData, sai);
  10225. }
  10226. #endif
  10227. JavascriptNativeArray::JavascriptNativeArray(JavascriptNativeArray * instance) :
  10228. JavascriptArray(instance, false, false),
  10229. weakRefToFuncBody(instance->weakRefToFuncBody)
  10230. {
  10231. }
  10232. JavascriptNativeIntArray::JavascriptNativeIntArray(JavascriptNativeIntArray * instance, bool boxHead, bool deepCopy) :
  10233. JavascriptNativeArray(instance)
  10234. {
  10235. if (boxHead)
  10236. {
  10237. InitBoxedInlineSegments(DetermineInlineHeadSegmentPointer<JavascriptNativeIntArray, 0, true>(this), SparseArraySegment<int>::From(instance->head), deepCopy);
  10238. }
  10239. else
  10240. {
  10241. // Base class ctor should have copied these
  10242. Assert(head == instance->head);
  10243. Assert(segmentUnion.lastUsedSegment == instance->GetLastUsedSegment());
  10244. }
  10245. }
  10246. JavascriptNativeIntArray *
  10247. JavascriptNativeIntArray::BoxStackInstance(JavascriptNativeIntArray * instance, bool deepCopy)
  10248. {
  10249. return JavascriptArray::BoxStackInstance<JavascriptNativeIntArray>(instance, deepCopy);
  10250. }
  10251. #if ENABLE_TTD
  10252. TTD::NSSnapObjects::SnapObjectType JavascriptNativeIntArray::GetSnapTag_TTD() const
  10253. {
  10254. return TTD::NSSnapObjects::SnapObjectType::SnapNativeIntArrayObject;
  10255. }
  10256. void JavascriptNativeIntArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  10257. {
  10258. TTD::NSSnapObjects::SnapArrayInfo<int32>* sai = TTD::NSSnapObjects::ExtractArrayValues<int32>(this, alloc);
  10259. TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayInfo<int32>*, TTD::NSSnapObjects::SnapObjectType::SnapNativeIntArrayObject>(objData, sai);
  10260. }
  10261. #if ENABLE_COPYONACCESS_ARRAY
  10262. TTD::NSSnapObjects::SnapObjectType JavascriptCopyOnAccessNativeIntArray::GetSnapTag_TTD() const
  10263. {
  10264. return TTD::NSSnapObjects::SnapObjectType::Invalid;
  10265. }
  10266. void JavascriptCopyOnAccessNativeIntArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  10267. {
  10268. TTDAssert(false, "Not implemented yet!!!");
  10269. }
  10270. #endif
  10271. #endif
  10272. JavascriptNativeFloatArray::JavascriptNativeFloatArray(JavascriptNativeFloatArray * instance, bool boxHead, bool deepCopy) :
  10273. JavascriptNativeArray(instance)
  10274. {
  10275. if (boxHead)
  10276. {
  10277. InitBoxedInlineSegments(DetermineInlineHeadSegmentPointer<JavascriptNativeFloatArray, 0, true>(this), SparseArraySegment<double>::From(instance->head), deepCopy);
  10278. }
  10279. else
  10280. {
  10281. // Base class ctor should have copied these
  10282. Assert(head == instance->head);
  10283. Assert(segmentUnion.lastUsedSegment == instance->GetLastUsedSegment());
  10284. }
  10285. }
  10286. JavascriptNativeFloatArray *
  10287. JavascriptNativeFloatArray::BoxStackInstance(JavascriptNativeFloatArray * instance, bool deepCopy)
  10288. {
  10289. return JavascriptArray::BoxStackInstance<JavascriptNativeFloatArray>(instance, deepCopy);
  10290. }
  10291. #if ENABLE_TTD
  10292. TTD::NSSnapObjects::SnapObjectType JavascriptNativeFloatArray::GetSnapTag_TTD() const
  10293. {
  10294. return TTD::NSSnapObjects::SnapObjectType::SnapNativeFloatArrayObject;
  10295. }
  10296. void JavascriptNativeFloatArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  10297. {
  10298. TTDAssert(this->GetTypeId() == Js::TypeIds_NativeFloatArray, "Should only be used on native float arrays.");
  10299. TTD::NSSnapObjects::SnapArrayInfo<double>* sai = TTD::NSSnapObjects::ExtractArrayValues<double>(this, alloc);
  10300. TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayInfo<double>*, TTD::NSSnapObjects::SnapObjectType::SnapNativeFloatArrayObject>(objData, sai);
  10301. }
  10302. #endif
  10303. template<typename T>
  10304. RecyclableObject*
  10305. JavascriptArray::ArraySpeciesCreate(Var originalArray, T length, ScriptContext* scriptContext, bool *pIsIntArray, bool *pIsFloatArray, bool *pIsBuiltinArrayCtor)
  10306. {
  10307. if (originalArray == nullptr || !scriptContext->GetConfig()->IsES6SpeciesEnabled())
  10308. {
  10309. return nullptr;
  10310. }
  10311. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  10312. SETOBJECT_FOR_MUTATION(jsReentLock, originalArray);
  10313. if (JavascriptArray::Is(originalArray)
  10314. && !DynamicObject::UnsafeFromVar(originalArray)->GetDynamicType()->GetTypeHandler()->GetIsNotPathTypeHandlerOrHasUserDefinedCtor()
  10315. && DynamicObject::UnsafeFromVar(originalArray)->GetPrototype() == scriptContext->GetLibrary()->GetArrayPrototype()
  10316. && !scriptContext->GetLibrary()->GetArrayObjectHasUserDefinedSpecies())
  10317. {
  10318. return nullptr;
  10319. }
  10320. Var constructor = scriptContext->GetLibrary()->GetUndefined();
  10321. if (JavascriptOperators::IsArray(originalArray))
  10322. {
  10323. JS_REENTRANT(jsReentLock, BOOL getProp = JavascriptOperators::GetProperty(RecyclableObject::UnsafeFromVar(originalArray), PropertyIds::constructor, &constructor, scriptContext));
  10324. if (!getProp)
  10325. {
  10326. return nullptr;
  10327. }
  10328. if (JavascriptOperators::IsConstructor(constructor))
  10329. {
  10330. ScriptContext* constructorScriptContext = RecyclableObject::UnsafeFromVar(constructor)->GetScriptContext();
  10331. if (constructorScriptContext != scriptContext)
  10332. {
  10333. if (constructorScriptContext->GetLibrary()->GetArrayConstructor() == constructor)
  10334. {
  10335. constructor = scriptContext->GetLibrary()->GetUndefined();
  10336. }
  10337. }
  10338. }
  10339. if (JavascriptOperators::IsObject(constructor))
  10340. {
  10341. JS_REENTRANT(jsReentLock, getProp = JavascriptOperators::GetProperty((RecyclableObject*)constructor, PropertyIds::_symbolSpecies, &constructor, scriptContext));
  10342. if (!getProp)
  10343. {
  10344. if (pIsBuiltinArrayCtor != nullptr)
  10345. {
  10346. *pIsBuiltinArrayCtor = false;
  10347. }
  10348. return nullptr;
  10349. }
  10350. if (constructor == scriptContext->GetLibrary()->GetNull())
  10351. {
  10352. constructor = scriptContext->GetLibrary()->GetUndefined();
  10353. }
  10354. }
  10355. }
  10356. if (constructor == scriptContext->GetLibrary()->GetUndefined() || constructor == scriptContext->GetLibrary()->GetArrayConstructor())
  10357. {
  10358. if (length > UINT_MAX)
  10359. {
  10360. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  10361. }
  10362. if (nullptr == pIsIntArray)
  10363. {
  10364. return scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(length));
  10365. }
  10366. else
  10367. {
  10368. // If the constructor function is the built-in Array constructor, we can be smart and create the right type of native array.
  10369. JavascriptArray* pArr = JavascriptArray::FromVar(originalArray);
  10370. pArr->GetArrayTypeAndConvert(pIsIntArray, pIsFloatArray);
  10371. return CreateNewArrayHelper(static_cast<uint32>(length), *pIsIntArray, *pIsFloatArray, pArr, scriptContext);
  10372. }
  10373. }
  10374. if (!JavascriptOperators::IsConstructor(constructor))
  10375. {
  10376. JavascriptError::ThrowTypeError(scriptContext, JSERR_NotAConstructor, _u("constructor[Symbol.species]"));
  10377. }
  10378. if (pIsBuiltinArrayCtor != nullptr)
  10379. {
  10380. *pIsBuiltinArrayCtor = false;
  10381. }
  10382. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(length, scriptContext) };
  10383. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  10384. AssertOrFailFast(Js::RecyclableObject::Is(constructor));
  10385. ThreadContext* threadContext = scriptContext->GetThreadContext();
  10386. Var scObject = threadContext->ExecuteImplicitCall((RecyclableObject*)constructor, ImplicitCall_Accessor, [&]()->Js::Var
  10387. {
  10388. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext));
  10389. });
  10390. return RecyclableObject::FromVar(scObject);
  10391. }
  10392. /*static*/
  10393. PropertyId const JavascriptArray::specialPropertyIds[] =
  10394. {
  10395. PropertyIds::length
  10396. };
  10397. BOOL JavascriptArray::DeleteProperty(PropertyId propertyId, PropertyOperationFlags flags)
  10398. {
  10399. if (propertyId == PropertyIds::length)
  10400. {
  10401. return false;
  10402. }
  10403. return DynamicObject::DeleteProperty(propertyId, flags);
  10404. }
  10405. BOOL JavascriptArray::DeleteProperty(JavascriptString *propertyNameString, PropertyOperationFlags flags)
  10406. {
  10407. if (BuiltInPropertyRecords::length.Equals(propertyNameString))
  10408. {
  10409. return false;
  10410. }
  10411. return DynamicObject::DeleteProperty(propertyNameString, flags);
  10412. }
  10413. PropertyQueryFlags JavascriptArray::HasPropertyQuery(PropertyId propertyId)
  10414. {
  10415. if (propertyId == PropertyIds::length)
  10416. {
  10417. return PropertyQueryFlags::Property_Found;
  10418. }
  10419. ScriptContext* scriptContext = GetScriptContext();
  10420. uint32 index;
  10421. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10422. {
  10423. return JavascriptConversion::BooleanToPropertyQueryFlags(this->HasItem(index));
  10424. }
  10425. return DynamicObject::HasPropertyQuery(propertyId);
  10426. }
  10427. BOOL JavascriptArray::IsEnumerable(PropertyId propertyId)
  10428. {
  10429. if (propertyId == PropertyIds::length)
  10430. {
  10431. return false;
  10432. }
  10433. return DynamicObject::IsEnumerable(propertyId);
  10434. }
  10435. BOOL JavascriptArray::IsConfigurable(PropertyId propertyId)
  10436. {
  10437. if (propertyId == PropertyIds::length)
  10438. {
  10439. return false;
  10440. }
  10441. return DynamicObject::IsConfigurable(propertyId);
  10442. }
  10443. //
  10444. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10445. // handling and only check instance objectArray for numeric propertyIds.
  10446. //
  10447. BOOL JavascriptArray::SetEnumerable(PropertyId propertyId, BOOL value)
  10448. {
  10449. if (propertyId == PropertyIds::length)
  10450. {
  10451. Assert(!value); // Can't change array length enumerable
  10452. return true;
  10453. }
  10454. ScriptContext* scriptContext = this->GetScriptContext();
  10455. uint32 index;
  10456. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10457. {
  10458. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10459. ->SetEnumerable(this, propertyId, value);
  10460. }
  10461. return __super::SetEnumerable(propertyId, value);
  10462. }
  10463. //
  10464. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10465. // handling and only check instance objectArray for numeric propertyIds.
  10466. //
  10467. BOOL JavascriptArray::SetWritable(PropertyId propertyId, BOOL value)
  10468. {
  10469. ScriptContext* scriptContext = this->GetScriptContext();
  10470. uint32 index;
  10471. bool setLengthNonWritable = (propertyId == PropertyIds::length && !value);
  10472. if (setLengthNonWritable || scriptContext->IsNumericPropertyId(propertyId, &index))
  10473. {
  10474. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10475. ->SetWritable(this, propertyId, value);
  10476. }
  10477. return __super::SetWritable(propertyId, value);
  10478. }
  10479. //
  10480. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10481. // handling and only check instance objectArray for numeric propertyIds.
  10482. //
  10483. BOOL JavascriptArray::SetConfigurable(PropertyId propertyId, BOOL value)
  10484. {
  10485. if (propertyId == PropertyIds::length)
  10486. {
  10487. Assert(!value); // Can't change array length configurable
  10488. return true;
  10489. }
  10490. ScriptContext* scriptContext = this->GetScriptContext();
  10491. uint32 index;
  10492. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10493. {
  10494. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10495. ->SetConfigurable(this, propertyId, value);
  10496. }
  10497. return __super::SetConfigurable(propertyId, value);
  10498. }
  10499. //
  10500. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10501. // handling and only check instance objectArray for numeric propertyIds.
  10502. //
  10503. BOOL JavascriptArray::SetAttributes(PropertyId propertyId, PropertyAttributes attributes)
  10504. {
  10505. ScriptContext* scriptContext = this->GetScriptContext();
  10506. // SetAttributes on "length" is not expected. DefineOwnProperty uses SetWritable. If this is
  10507. // changed, we need to handle it here.
  10508. Assert(propertyId != PropertyIds::length);
  10509. uint32 index;
  10510. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10511. {
  10512. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10513. ->SetItemAttributes(this, index, attributes);
  10514. }
  10515. return __super::SetAttributes(propertyId, attributes);
  10516. }
  10517. //
  10518. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10519. // handling and only check instance objectArray for numeric propertyIds.
  10520. //
  10521. BOOL JavascriptArray::SetAccessors(PropertyId propertyId, Var getter, Var setter, PropertyOperationFlags flags)
  10522. {
  10523. ScriptContext* scriptContext = this->GetScriptContext();
  10524. uint32 index;
  10525. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10526. {
  10527. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10528. ->SetItemAccessors(this, index, getter, setter);
  10529. }
  10530. return __super::SetAccessors(propertyId, getter, setter, flags);
  10531. }
  10532. //
  10533. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10534. // handling and only check instance objectArray for numeric propertyIds.
  10535. //
  10536. BOOL JavascriptArray::SetItemWithAttributes(uint32 index, Var value, PropertyAttributes attributes)
  10537. {
  10538. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10539. ->SetItemWithAttributes(this, index, value, attributes);
  10540. }
  10541. //
  10542. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10543. // handling and only check instance objectArray for numeric propertyIds.
  10544. //
  10545. BOOL JavascriptArray::SetItemAttributes(uint32 index, PropertyAttributes attributes)
  10546. {
  10547. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10548. ->SetItemAttributes(this, index, attributes);
  10549. }
  10550. //
  10551. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10552. // handling and only check instance objectArray for numeric propertyIds.
  10553. //
  10554. BOOL JavascriptArray::SetItemAccessors(uint32 index, Var getter, Var setter)
  10555. {
  10556. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10557. ->SetItemAccessors(this, index, getter, setter);
  10558. }
  10559. // Check if this objectArray isFrozen.
  10560. BOOL JavascriptArray::IsObjectArrayFrozen()
  10561. {
  10562. // If this is still a JavascriptArray, it's not frozen.
  10563. return false;
  10564. }
  10565. JavascriptEnumerator * JavascriptArray::GetIndexEnumerator(EnumeratorFlags flags, ScriptContext* requestContext)
  10566. {
  10567. #if ENABLE_COPYONACCESS_ARRAY
  10568. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10569. #endif
  10570. if (!!(flags & EnumeratorFlags::SnapShotSemantics))
  10571. {
  10572. return RecyclerNew(GetRecycler(), JavascriptArrayIndexSnapshotEnumerator, this, flags, requestContext);
  10573. }
  10574. return RecyclerNew(GetRecycler(), JavascriptArrayIndexEnumerator, this, flags, requestContext);
  10575. }
  10576. BOOL JavascriptArray::GetNonIndexEnumerator(JavascriptStaticEnumerator * enumerator, ScriptContext* requestContext)
  10577. {
  10578. #if ENABLE_COPYONACCESS_ARRAY
  10579. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10580. #endif
  10581. return enumerator->Initialize(nullptr, nullptr, this, EnumeratorFlags::SnapShotSemantics, requestContext, nullptr);
  10582. }
  10583. BOOL JavascriptArray::IsItemEnumerable(uint32 index)
  10584. {
  10585. return true;
  10586. }
  10587. //
  10588. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10589. // handling and only check instance objectArray for numeric propertyIds.
  10590. //
  10591. BOOL JavascriptArray::PreventExtensions()
  10592. {
  10593. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)->PreventExtensions(this);
  10594. }
  10595. //
  10596. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10597. // handling and only check instance objectArray for numeric propertyIds.
  10598. //
  10599. BOOL JavascriptArray::Seal()
  10600. {
  10601. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)->Seal(this);
  10602. }
  10603. //
  10604. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10605. // handling and only check instance objectArray for numeric propertyIds.
  10606. //
  10607. BOOL JavascriptArray::Freeze()
  10608. {
  10609. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)->Freeze(this);
  10610. }
  10611. BOOL JavascriptArray::GetSpecialPropertyName(uint32 index, JavascriptString ** propertyName, ScriptContext * requestContext)
  10612. {
  10613. if (index == 0)
  10614. {
  10615. *propertyName = requestContext->GetPropertyString(PropertyIds::length);
  10616. return true;
  10617. }
  10618. return false;
  10619. }
  10620. // Returns the number of special non-enumerable properties this type has.
  10621. uint JavascriptArray::GetSpecialPropertyCount() const
  10622. {
  10623. return _countof(specialPropertyIds);
  10624. }
  10625. // Returns the list of special non-enumerable properties for the type.
  10626. PropertyId const * JavascriptArray::GetSpecialPropertyIds() const
  10627. {
  10628. return specialPropertyIds;
  10629. }
  10630. PropertyQueryFlags JavascriptArray::GetPropertyReferenceQuery(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  10631. {
  10632. return JavascriptArray::GetPropertyQuery(originalInstance, propertyId, value, info, requestContext);
  10633. }
  10634. PropertyQueryFlags JavascriptArray::GetPropertyQuery(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  10635. {
  10636. if (GetPropertyBuiltIns(propertyId, value))
  10637. {
  10638. return PropertyQueryFlags::Property_Found;
  10639. }
  10640. ScriptContext* scriptContext = GetScriptContext();
  10641. uint32 index;
  10642. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10643. {
  10644. return JavascriptConversion::BooleanToPropertyQueryFlags(this->GetItem(this, index, value, scriptContext));
  10645. }
  10646. return DynamicObject::GetPropertyQuery(originalInstance, propertyId, value, info, requestContext);
  10647. }
  10648. PropertyQueryFlags JavascriptArray::GetPropertyQuery(Var originalInstance, JavascriptString* propertyNameString, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  10649. {
  10650. AssertMsg(!PropertyRecord::IsPropertyNameNumeric(propertyNameString->GetString(), propertyNameString->GetLength()),
  10651. "Numeric property names should have been converted to uint or PropertyRecord*");
  10652. PropertyRecord const* propertyRecord;
  10653. this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
  10654. if (propertyRecord != nullptr && GetPropertyBuiltIns(propertyRecord->GetPropertyId(), value))
  10655. {
  10656. return PropertyQueryFlags::Property_Found;
  10657. }
  10658. return DynamicObject::GetPropertyQuery(originalInstance, propertyNameString, value, info, requestContext);
  10659. }
  10660. BOOL JavascriptArray::GetPropertyBuiltIns(PropertyId propertyId, Var* value)
  10661. {
  10662. //
  10663. // length being accessed. Return array length
  10664. //
  10665. if (propertyId == PropertyIds::length)
  10666. {
  10667. *value = JavascriptNumber::ToVar(this->GetLength(), GetScriptContext());
  10668. return true;
  10669. }
  10670. return false;
  10671. }
  10672. PropertyQueryFlags JavascriptArray::HasItemQuery(uint32 index)
  10673. {
  10674. Var value;
  10675. return JavascriptConversion::BooleanToPropertyQueryFlags(this->DirectGetItemAt<Var>(index, &value));
  10676. }
  10677. PropertyQueryFlags JavascriptArray::GetItemQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10678. {
  10679. return JavascriptConversion::BooleanToPropertyQueryFlags(this->DirectGetItemAt<Var>(index, value));
  10680. }
  10681. PropertyQueryFlags JavascriptArray::GetItemReferenceQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10682. {
  10683. return JavascriptConversion::BooleanToPropertyQueryFlags(this->DirectGetItemAt<Var>(index, value));
  10684. }
  10685. BOOL JavascriptArray::DirectGetVarItemAt(uint32 index, Var *value, ScriptContext *requestContext)
  10686. {
  10687. return this->DirectGetItemAt<Var>(index, value);
  10688. }
  10689. PropertyQueryFlags JavascriptNativeIntArray::HasItemQuery(uint32 index)
  10690. {
  10691. #if ENABLE_COPYONACCESS_ARRAY
  10692. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10693. #endif
  10694. int32 value;
  10695. return JavascriptConversion::BooleanToPropertyQueryFlags(this->DirectGetItemAt<int32>(index, &value));
  10696. }
  10697. PropertyQueryFlags JavascriptNativeFloatArray::HasItemQuery(uint32 index)
  10698. {
  10699. double dvalue;
  10700. return JavascriptConversion::BooleanToPropertyQueryFlags(this->DirectGetItemAt<double>(index, &dvalue));
  10701. }
  10702. PropertyQueryFlags JavascriptNativeIntArray::GetItemQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10703. {
  10704. #if ENABLE_COPYONACCESS_ARRAY
  10705. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10706. #endif
  10707. return JavascriptConversion::BooleanToPropertyQueryFlags(JavascriptNativeIntArray::DirectGetVarItemAt(index, value, requestContext));
  10708. }
  10709. BOOL JavascriptNativeIntArray::DirectGetVarItemAt(uint32 index, Var *value, ScriptContext *requestContext)
  10710. {
  10711. int32 intvalue;
  10712. if (!this->DirectGetItemAt<int32>(index, &intvalue))
  10713. {
  10714. return FALSE;
  10715. }
  10716. *value = JavascriptNumber::ToVar(intvalue, requestContext);
  10717. return TRUE;
  10718. }
  10719. PropertyQueryFlags JavascriptNativeIntArray::GetItemReferenceQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10720. {
  10721. return JavascriptNativeIntArray::GetItemQuery(originalInstance, index, value, requestContext);
  10722. }
  10723. PropertyQueryFlags JavascriptNativeFloatArray::GetItemQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10724. {
  10725. return JavascriptConversion::BooleanToPropertyQueryFlags(JavascriptNativeFloatArray::DirectGetVarItemAt(index, value, requestContext));
  10726. }
  10727. BOOL JavascriptNativeFloatArray::DirectGetVarItemAt(uint32 index, Var *value, ScriptContext *requestContext)
  10728. {
  10729. double dvalue;
  10730. int32 ivalue;
  10731. if (!this->DirectGetItemAt<double>(index, &dvalue))
  10732. {
  10733. return FALSE;
  10734. }
  10735. if (*(uint64*)&dvalue == 0ull)
  10736. {
  10737. *value = TaggedInt::ToVarUnchecked(0);
  10738. }
  10739. else if (JavascriptNumber::TryGetInt32Value(dvalue, &ivalue) && !TaggedInt::IsOverflow(ivalue))
  10740. {
  10741. *value = TaggedInt::ToVarUnchecked(ivalue);
  10742. }
  10743. else
  10744. {
  10745. *value = JavascriptNumber::ToVarWithCheck(dvalue, requestContext);
  10746. }
  10747. return TRUE;
  10748. }
  10749. PropertyQueryFlags JavascriptNativeFloatArray::GetItemReferenceQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10750. {
  10751. return JavascriptNativeFloatArray::GetItemQuery(originalInstance, index, value, requestContext);
  10752. }
  10753. BOOL JavascriptArray::SetProperty(PropertyId propertyId, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)
  10754. {
  10755. #if ENABLE_COPYONACCESS_ARRAY
  10756. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10757. #endif
  10758. uint32 indexValue;
  10759. if (propertyId == PropertyIds::length)
  10760. {
  10761. return this->SetLength(value);
  10762. }
  10763. else if (GetScriptContext()->IsNumericPropertyId(propertyId, &indexValue))
  10764. {
  10765. // Call this or subclass method
  10766. return SetItem(indexValue, value, flags);
  10767. }
  10768. else
  10769. {
  10770. return DynamicObject::SetProperty(propertyId, value, flags, info);
  10771. }
  10772. }
  10773. BOOL JavascriptArray::SetProperty(JavascriptString* propertyNameString, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)
  10774. {
  10775. AssertMsg(!PropertyRecord::IsPropertyNameNumeric(propertyNameString->GetString(), propertyNameString->GetLength()),
  10776. "Numeric property names should have been converted to uint or PropertyRecord*");
  10777. #if ENABLE_COPYONACCESS_ARRAY
  10778. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10779. #endif
  10780. PropertyRecord const* propertyRecord;
  10781. this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
  10782. if (propertyRecord != nullptr && propertyRecord->GetPropertyId() == PropertyIds::length)
  10783. {
  10784. return this->SetLength(value);
  10785. }
  10786. return DynamicObject::SetProperty(propertyNameString, value, flags, info);
  10787. }
  10788. BOOL JavascriptArray::SetPropertyWithAttributes(PropertyId propertyId, Var value, PropertyAttributes attributes, PropertyValueInfo* info, PropertyOperationFlags flags, SideEffects possibleSideEffects)
  10789. {
  10790. #if ENABLE_COPYONACCESS_ARRAY
  10791. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10792. #endif
  10793. ScriptContext* scriptContext = GetScriptContext();
  10794. if (propertyId == PropertyIds::length)
  10795. {
  10796. Assert(attributes == PropertyWritable);
  10797. Assert(IsWritable(propertyId) && !IsConfigurable(propertyId) && !IsEnumerable(propertyId));
  10798. return this->SetLength(value);
  10799. }
  10800. uint32 index;
  10801. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10802. {
  10803. // Call this or subclass method
  10804. return SetItemWithAttributes(index, value, attributes);
  10805. }
  10806. return __super::SetPropertyWithAttributes(propertyId, value, attributes, info, flags, possibleSideEffects);
  10807. }
  10808. BOOL JavascriptArray::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
  10809. {
  10810. this->DirectSetItemAt(index, value);
  10811. return true;
  10812. }
  10813. BOOL JavascriptNativeIntArray::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
  10814. {
  10815. int32 iValue;
  10816. double dValue;
  10817. #if ENABLE_COPYONACCESS_ARRAY
  10818. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10819. #endif
  10820. TypeId typeId = this->TrySetNativeIntArrayItem(value, &iValue, &dValue);
  10821. if (typeId == TypeIds_NativeIntArray)
  10822. {
  10823. this->SetItem(index, iValue);
  10824. }
  10825. else if (typeId == TypeIds_NativeFloatArray)
  10826. {
  10827. reinterpret_cast<JavascriptNativeFloatArray*>(this)->DirectSetItemAt<double>(index, dValue);
  10828. }
  10829. else
  10830. {
  10831. this->DirectSetItemAt<Var>(index, value);
  10832. }
  10833. return TRUE;
  10834. }
  10835. TypeId JavascriptNativeIntArray::TrySetNativeIntArrayItem(Var value, int32 *iValue, double *dValue)
  10836. {
  10837. if (TaggedInt::Is(value))
  10838. {
  10839. int32 i = TaggedInt::ToInt32(value);
  10840. if (i != JavascriptNativeIntArray::MissingItem)
  10841. {
  10842. *iValue = i;
  10843. return TypeIds_NativeIntArray;
  10844. }
  10845. }
  10846. if (JavascriptNumber::Is_NoTaggedIntCheck(value))
  10847. {
  10848. bool isInt32;
  10849. int32 i;
  10850. double d = JavascriptNumber::GetValue(value);
  10851. if (JavascriptNumber::TryGetInt32OrUInt32Value(d, &i, &isInt32))
  10852. {
  10853. if (isInt32 && i != JavascriptNativeIntArray::MissingItem)
  10854. {
  10855. *iValue = i;
  10856. return TypeIds_NativeIntArray;
  10857. }
  10858. }
  10859. else
  10860. {
  10861. *dValue = d;
  10862. JavascriptNativeIntArray::ToNativeFloatArray(this);
  10863. return TypeIds_NativeFloatArray;
  10864. }
  10865. }
  10866. JavascriptNativeIntArray::ToVarArray(this);
  10867. return TypeIds_Array;
  10868. }
  10869. BOOL JavascriptNativeIntArray::SetItem(uint32 index, int32 iValue)
  10870. {
  10871. if (iValue == JavascriptNativeIntArray::MissingItem)
  10872. {
  10873. JavascriptArray *varArr = JavascriptNativeIntArray::ToVarArray(this);
  10874. varArr->DirectSetItemAt(index, JavascriptNumber::ToVar(iValue, GetScriptContext()));
  10875. return TRUE;
  10876. }
  10877. this->DirectSetItemAt(index, iValue);
  10878. return TRUE;
  10879. }
  10880. BOOL JavascriptNativeFloatArray::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
  10881. {
  10882. double dValue;
  10883. TypeId typeId = this->TrySetNativeFloatArrayItem(value, &dValue);
  10884. if (typeId == TypeIds_NativeFloatArray)
  10885. {
  10886. this->SetItem(index, dValue);
  10887. }
  10888. else
  10889. {
  10890. this->DirectSetItemAt(index, value);
  10891. }
  10892. return TRUE;
  10893. }
  10894. TypeId JavascriptNativeFloatArray::TrySetNativeFloatArrayItem(Var value, double *dValue)
  10895. {
  10896. if (TaggedInt::Is(value))
  10897. {
  10898. *dValue = (double)TaggedInt::ToInt32(value);
  10899. return TypeIds_NativeFloatArray;
  10900. }
  10901. else if (JavascriptNumber::Is_NoTaggedIntCheck(value))
  10902. {
  10903. *dValue = JavascriptNumber::GetValue(value);
  10904. return TypeIds_NativeFloatArray;
  10905. }
  10906. JavascriptNativeFloatArray::ToVarArray(this);
  10907. return TypeIds_Array;
  10908. }
  10909. BOOL JavascriptNativeFloatArray::SetItem(uint32 index, double dValue)
  10910. {
  10911. if (*(uint64*)&dValue == *(uint64*)&JavascriptNativeFloatArray::MissingItem)
  10912. {
  10913. JavascriptArray *varArr = JavascriptNativeFloatArray::ToVarArray(this);
  10914. varArr->DirectSetItemAt(index, JavascriptNumber::ToVarNoCheck(dValue, GetScriptContext()));
  10915. return TRUE;
  10916. }
  10917. this->DirectSetItemAt<double>(index, dValue);
  10918. return TRUE;
  10919. }
  10920. BOOL JavascriptArray::DeleteItem(uint32 index, PropertyOperationFlags flags)
  10921. {
  10922. return this->DirectDeleteItemAt<Var>(index);
  10923. }
  10924. BOOL JavascriptNativeIntArray::DeleteItem(uint32 index, PropertyOperationFlags flags)
  10925. {
  10926. return this->DirectDeleteItemAt<int32>(index);
  10927. }
  10928. BOOL JavascriptNativeFloatArray::DeleteItem(uint32 index, PropertyOperationFlags flags)
  10929. {
  10930. return this->DirectDeleteItemAt<double>(index);
  10931. }
  10932. BOOL JavascriptArray::GetEnumerator(JavascriptStaticEnumerator * enumerator, EnumeratorFlags flags, ScriptContext* requestContext, ForInCache * forInCache)
  10933. {
  10934. #if ENABLE_COPYONACCESS_ARRAY
  10935. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10936. #endif
  10937. return enumerator->Initialize(nullptr, this, this, flags, requestContext, forInCache);
  10938. }
  10939. BOOL JavascriptArray::GetDiagValueString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext)
  10940. {
  10941. stringBuilder->Append(_u('['));
  10942. if (this->length < 10)
  10943. {
  10944. auto funcPtr = [&]()
  10945. {
  10946. ENTER_PINNED_SCOPE(JavascriptString, valueStr);
  10947. valueStr = JavascriptArray::JoinHelper(this, GetLibrary()->GetCommaDisplayString(), requestContext);
  10948. stringBuilder->Append(valueStr->GetString(), valueStr->GetLength());
  10949. LEAVE_PINNED_SCOPE();
  10950. };
  10951. if (!requestContext->GetThreadContext()->IsScriptActive())
  10952. {
  10953. BEGIN_JS_RUNTIME_CALL(requestContext);
  10954. {
  10955. funcPtr();
  10956. }
  10957. END_JS_RUNTIME_CALL(requestContext);
  10958. }
  10959. else
  10960. {
  10961. funcPtr();
  10962. }
  10963. }
  10964. else
  10965. {
  10966. stringBuilder->AppendCppLiteral(_u("..."));
  10967. }
  10968. stringBuilder->Append(_u(']'));
  10969. return TRUE;
  10970. }
  10971. BOOL JavascriptArray::GetDiagTypeString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext)
  10972. {
  10973. stringBuilder->AppendCppLiteral(_u("Object, (Array)"));
  10974. return TRUE;
  10975. }
  10976. bool JavascriptNativeArray::Is(Var aValue)
  10977. {
  10978. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  10979. return JavascriptNativeArray::Is(typeId);
  10980. }
  10981. bool JavascriptNativeArray::Is(TypeId typeId)
  10982. {
  10983. return JavascriptNativeIntArray::Is(typeId) || JavascriptNativeFloatArray::Is(typeId);
  10984. }
  10985. JavascriptNativeArray* JavascriptNativeArray::FromVar(Var aValue)
  10986. {
  10987. AssertOrFailFastMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeArray'");
  10988. return static_cast<JavascriptNativeArray *>(aValue);
  10989. }
  10990. JavascriptNativeArray* JavascriptNativeArray::UnsafeFromVar(Var aValue)
  10991. {
  10992. AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeArray'");
  10993. return static_cast<JavascriptNativeArray *>(aValue);
  10994. }
  10995. bool JavascriptNativeIntArray::Is(Var aValue)
  10996. {
  10997. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  10998. return JavascriptNativeIntArray::Is(typeId);
  10999. }
  11000. #if ENABLE_COPYONACCESS_ARRAY
  11001. bool JavascriptCopyOnAccessNativeIntArray::Is(Var aValue)
  11002. {
  11003. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  11004. return JavascriptCopyOnAccessNativeIntArray::Is(typeId);
  11005. }
  11006. #endif
  11007. bool JavascriptNativeIntArray::Is(TypeId typeId)
  11008. {
  11009. return typeId == TypeIds_NativeIntArray;
  11010. }
  11011. #if ENABLE_COPYONACCESS_ARRAY
  11012. bool JavascriptCopyOnAccessNativeIntArray::Is(TypeId typeId)
  11013. {
  11014. return typeId == TypeIds_CopyOnAccessNativeIntArray;
  11015. }
  11016. #endif
  11017. bool JavascriptNativeIntArray::IsNonCrossSite(Var aValue)
  11018. {
  11019. bool ret = !TaggedInt::Is(aValue) && VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(aValue);
  11020. Assert(ret == (JavascriptNativeIntArray::Is(aValue) && !JavascriptNativeIntArray::FromVar(aValue)->IsCrossSiteObject()));
  11021. return ret;
  11022. }
  11023. JavascriptNativeIntArray* JavascriptNativeIntArray::FromVar(Var aValue)
  11024. {
  11025. AssertOrFailFastMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeIntArray'");
  11026. return static_cast<JavascriptNativeIntArray *>(aValue);
  11027. }
  11028. JavascriptNativeIntArray* JavascriptNativeIntArray::UnsafeFromVar(Var aValue)
  11029. {
  11030. AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeIntArray'");
  11031. return static_cast<JavascriptNativeIntArray *>(aValue);
  11032. }
  11033. #if ENABLE_COPYONACCESS_ARRAY
  11034. JavascriptCopyOnAccessNativeIntArray* JavascriptCopyOnAccessNativeIntArray::FromVar(Var aValue)
  11035. {
  11036. AssertOrFailFastMsg(Is(aValue), "Ensure var is actually a 'JavascriptCopyOnAccessNativeIntArray'");
  11037. return static_cast<JavascriptCopyOnAccessNativeIntArray *>(aValue);
  11038. }
  11039. JavascriptCopyOnAccessNativeIntArray* JavascriptCopyOnAccessNativeIntArray::UnsafeFromVar(Var aValue)
  11040. {
  11041. AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptCopyOnAccessNativeIntArray'");
  11042. return static_cast<JavascriptCopyOnAccessNativeIntArray *>(aValue);
  11043. }
  11044. #endif
  11045. bool JavascriptNativeFloatArray::Is(Var aValue)
  11046. {
  11047. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  11048. return JavascriptNativeFloatArray::Is(typeId);
  11049. }
  11050. bool JavascriptNativeFloatArray::Is(TypeId typeId)
  11051. {
  11052. return typeId == TypeIds_NativeFloatArray;
  11053. }
  11054. bool JavascriptNativeFloatArray::IsNonCrossSite(Var aValue)
  11055. {
  11056. bool ret = !TaggedInt::Is(aValue) && VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(aValue);
  11057. Assert(ret == (JavascriptNativeFloatArray::Is(aValue) && !JavascriptNativeFloatArray::FromVar(aValue)->IsCrossSiteObject()));
  11058. return ret;
  11059. }
  11060. JavascriptNativeFloatArray* JavascriptNativeFloatArray::FromVar(Var aValue)
  11061. {
  11062. AssertOrFailFastMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeFloatArray'");
  11063. return static_cast<JavascriptNativeFloatArray *>(RecyclableObject::FromVar(aValue));
  11064. }
  11065. JavascriptNativeFloatArray* JavascriptNativeFloatArray::UnsafeFromVar(Var aValue)
  11066. {
  11067. AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeFloatArray'");
  11068. return static_cast<JavascriptNativeFloatArray *>(RecyclableObject::UnsafeFromVar(aValue));
  11069. }
  11070. template int Js::JavascriptArray::GetParamForIndexOf<unsigned int>(unsigned int, Js::Arguments const&, void*&, unsigned int&, Js::ScriptContext*);
  11071. template bool Js::JavascriptArray::ArrayElementEnumerator::MoveNext<void*>();
  11072. template void Js::JavascriptArray::SetArrayLiteralItem<void*>(unsigned int, void*);
  11073. template void* Js::JavascriptArray::TemplatedIndexOfHelper<false, Js::TypedArrayBase, unsigned int>(Js::TypedArrayBase*, void*, unsigned int, unsigned int, Js::ScriptContext*);
  11074. template void* Js::JavascriptArray::TemplatedIndexOfHelper<true, Js::TypedArrayBase, unsigned int>(Js::TypedArrayBase*, void*, unsigned int, unsigned int, Js::ScriptContext*);
  11075. } //namespace Js