JavascriptArray.cpp 491 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724
  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(_M_X64_OR_ARM64)
  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->length <= index)
  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. AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptArray'");
  445. return static_cast<JavascriptArray *>(RecyclableObject::FromVar(aValue));
  446. }
  447. // Get JavascriptArray* from a Var, which is either a JavascriptArray* or ESArray*.
  448. JavascriptArray* JavascriptArray::FromAnyArray(Var aValue)
  449. {
  450. AssertMsg(Is(aValue) || ES5Array::Is(aValue), "Ensure var is actually a 'JavascriptArray' or 'ES5Array'");
  451. return static_cast<JavascriptArray *>(RecyclableObject::FromVar(aValue));
  452. }
  453. // Check if a Var is a direct-accessible (fast path) JavascriptArray.
  454. bool JavascriptArray::IsDirectAccessArray(Var aValue)
  455. {
  456. return RecyclableObject::Is(aValue) &&
  457. (VirtualTableInfo<JavascriptArray>::HasVirtualTable(aValue) ||
  458. VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(aValue) ||
  459. VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(aValue));
  460. }
  461. bool JavascriptArray::IsInlineSegment(SparseArraySegmentBase *seg, JavascriptArray *pArr)
  462. {
  463. if (seg == nullptr)
  464. {
  465. return false;
  466. }
  467. SparseArraySegmentBase* inlineHeadSegment = nullptr;
  468. if (JavascriptNativeArray::Is(pArr))
  469. {
  470. if (JavascriptNativeFloatArray::Is(pArr))
  471. {
  472. inlineHeadSegment = DetermineInlineHeadSegmentPointer<JavascriptNativeFloatArray, 0, true>((JavascriptNativeFloatArray*)pArr);
  473. }
  474. else
  475. {
  476. AssertOrFailFast(JavascriptNativeIntArray::Is(pArr));
  477. inlineHeadSegment = DetermineInlineHeadSegmentPointer<JavascriptNativeIntArray, 0, true>((JavascriptNativeIntArray*)pArr);
  478. }
  479. Assert(inlineHeadSegment);
  480. return (seg == inlineHeadSegment);
  481. }
  482. // This will result in false positives. It is used because DetermineInlineHeadSegmentPointer
  483. // does not handle Arrays that change type e.g. from JavascriptNativeIntArray to JavascriptArray
  484. // This conversion in particular is problematic because JavascriptNativeIntArray is larger than JavascriptArray
  485. // so the returned head segment ptr never equals pArr->head. So we will default to using this and deal with
  486. // false positives. It is better than always doing a hard copy.
  487. return pArr->head != nullptr && HasInlineHeadSegment(pArr->head->length);
  488. }
  489. DynamicObjectFlags JavascriptArray::GetFlags() const
  490. {
  491. return GetArrayFlags();
  492. }
  493. DynamicObjectFlags JavascriptArray::GetFlags_Unchecked() const // do not use except in extreme circumstances
  494. {
  495. return GetArrayFlags_Unchecked();
  496. }
  497. void JavascriptArray::SetFlags(const DynamicObjectFlags flags)
  498. {
  499. SetArrayFlags(flags);
  500. }
  501. DynamicType * JavascriptArray::GetInitialType(ScriptContext * scriptContext)
  502. {
  503. return scriptContext->GetLibrary()->GetArrayType();
  504. }
  505. JavascriptArray *JavascriptArray::GetArrayForArrayOrObjectWithArray(const Var var)
  506. {
  507. bool isObjectWithArray;
  508. TypeId arrayTypeId;
  509. return GetArrayForArrayOrObjectWithArray(var, &isObjectWithArray, &arrayTypeId);
  510. }
  511. JavascriptArray *JavascriptArray::GetArrayForArrayOrObjectWithArray(
  512. const Var var,
  513. bool *const isObjectWithArrayRef,
  514. TypeId *const arrayTypeIdRef)
  515. {
  516. // This is a helper function used by jitted code. The array checks done here match the array checks done by jitted code
  517. // (see Lowerer::GenerateArrayTest) to minimize bailouts.
  518. Assert(var);
  519. Assert(isObjectWithArrayRef);
  520. Assert(arrayTypeIdRef);
  521. *isObjectWithArrayRef = false;
  522. *arrayTypeIdRef = TypeIds_Undefined;
  523. if(!RecyclableObject::Is(var))
  524. {
  525. return nullptr;
  526. }
  527. JavascriptArray *array = nullptr;
  528. INT_PTR vtable = VirtualTableInfoBase::GetVirtualTable(var);
  529. if(vtable == VirtualTableInfo<DynamicObject>::Address)
  530. {
  531. ArrayObject* objectArray = DynamicObject::FromVar(var)->GetObjectArray();
  532. array = (objectArray && Is(objectArray)) ? FromVar(objectArray) : nullptr;
  533. if(!array)
  534. {
  535. return nullptr;
  536. }
  537. *isObjectWithArrayRef = true;
  538. vtable = VirtualTableInfoBase::GetVirtualTable(array);
  539. }
  540. if(vtable == VirtualTableInfo<JavascriptArray>::Address)
  541. {
  542. *arrayTypeIdRef = TypeIds_Array;
  543. }
  544. else if(vtable == VirtualTableInfo<JavascriptNativeIntArray>::Address)
  545. {
  546. *arrayTypeIdRef = TypeIds_NativeIntArray;
  547. }
  548. else if(vtable == VirtualTableInfo<JavascriptNativeFloatArray>::Address)
  549. {
  550. *arrayTypeIdRef = TypeIds_NativeFloatArray;
  551. }
  552. else
  553. {
  554. return nullptr;
  555. }
  556. if(!array)
  557. {
  558. array = FromVar(var);
  559. }
  560. return array;
  561. }
  562. const SparseArraySegmentBase *JavascriptArray::Jit_GetArrayHeadSegmentForArrayOrObjectWithArray(const Var var)
  563. {
  564. // This is a helper function used by jitted code
  565. JavascriptArray *const array = GetArrayForArrayOrObjectWithArray(var);
  566. return array ? array->head : nullptr;
  567. }
  568. uint32 JavascriptArray::Jit_GetArrayHeadSegmentLength(const SparseArraySegmentBase *const headSegment)
  569. {
  570. // This is a helper function used by jitted code
  571. return headSegment ? headSegment->length : 0;
  572. }
  573. bool JavascriptArray::Jit_OperationInvalidatedArrayHeadSegment(
  574. const SparseArraySegmentBase *const headSegmentBeforeOperation,
  575. const uint32 headSegmentLengthBeforeOperation,
  576. const Var varAfterOperation)
  577. {
  578. // This is a helper function used by jitted code
  579. Assert(varAfterOperation);
  580. if(!headSegmentBeforeOperation)
  581. {
  582. return false;
  583. }
  584. const SparseArraySegmentBase *const headSegmentAfterOperation =
  585. Jit_GetArrayHeadSegmentForArrayOrObjectWithArray(varAfterOperation);
  586. return
  587. headSegmentAfterOperation != headSegmentBeforeOperation ||
  588. headSegmentAfterOperation->length != headSegmentLengthBeforeOperation;
  589. }
  590. uint32 JavascriptArray::Jit_GetArrayLength(const Var var)
  591. {
  592. // This is a helper function used by jitted code
  593. bool isObjectWithArray;
  594. TypeId arrayTypeId;
  595. JavascriptArray *const array = GetArrayForArrayOrObjectWithArray(var, &isObjectWithArray, &arrayTypeId);
  596. return array && !isObjectWithArray ? array->GetLength() : 0;
  597. }
  598. bool JavascriptArray::Jit_OperationInvalidatedArrayLength(const uint32 lengthBeforeOperation, const Var varAfterOperation)
  599. {
  600. // This is a helper function used by jitted code
  601. return Jit_GetArrayLength(varAfterOperation) != lengthBeforeOperation;
  602. }
  603. DynamicObjectFlags JavascriptArray::Jit_GetArrayFlagsForArrayOrObjectWithArray(const Var var)
  604. {
  605. // This is a helper function used by jitted code
  606. JavascriptArray *const array = GetArrayForArrayOrObjectWithArray(var);
  607. return array && array->UsesObjectArrayOrFlagsAsFlags() ? array->GetFlags() : DynamicObjectFlags::None;
  608. }
  609. bool JavascriptArray::Jit_OperationCreatedFirstMissingValue(
  610. const DynamicObjectFlags flagsBeforeOperation,
  611. const Var varAfterOperation)
  612. {
  613. // This is a helper function used by jitted code
  614. Assert(varAfterOperation);
  615. return
  616. !!(flagsBeforeOperation & DynamicObjectFlags::HasNoMissingValues) &&
  617. !(Jit_GetArrayFlagsForArrayOrObjectWithArray(varAfterOperation) & DynamicObjectFlags::HasNoMissingValues);
  618. }
  619. bool JavascriptArray::HasNoMissingValues() const
  620. {
  621. return !!(GetFlags() & DynamicObjectFlags::HasNoMissingValues);
  622. }
  623. bool JavascriptArray::HasNoMissingValues_Unchecked() const // do not use except in extreme circumstances
  624. {
  625. return !!(GetFlags_Unchecked() & DynamicObjectFlags::HasNoMissingValues);
  626. }
  627. void JavascriptArray::SetHasNoMissingValues(const bool hasNoMissingValues)
  628. {
  629. SetFlags(
  630. hasNoMissingValues
  631. ? GetFlags() | DynamicObjectFlags::HasNoMissingValues
  632. : GetFlags() & ~DynamicObjectFlags::HasNoMissingValues);
  633. }
  634. template<class T>
  635. bool JavascriptArray::IsMissingHeadSegmentItemImpl(const uint32 index) const
  636. {
  637. Assert(index < head->length);
  638. return SparseArraySegment<T>::IsMissingItem(&SparseArraySegment<T>::From(head)->elements[index]);
  639. }
  640. bool JavascriptArray::IsMissingHeadSegmentItem(const uint32 index) const
  641. {
  642. return IsMissingHeadSegmentItemImpl<Var>(index);
  643. }
  644. #if ENABLE_COPYONACCESS_ARRAY
  645. void JavascriptCopyOnAccessNativeIntArray::ConvertCopyOnAccessSegment()
  646. {
  647. Assert(this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->IsValidIndex(::Math::PointerCastToIntegral<uint32>(this->GetHead())));
  648. SparseArraySegment<int32> *seg = this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->GetSegmentByIndex(::Math::PointerCastToIntegral<byte>(this->GetHead()));
  649. SparseArraySegment<int32> *newSeg = SparseArraySegment<int32>::AllocateLiteralHeadSegment(this->GetRecycler(), seg->length);
  650. #if ENABLE_DEBUG_CONFIG_OPTIONS
  651. if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::CopyOnAccessArrayPhase))
  652. {
  653. Output::Print(_u("Convert copy-on-access array: index(%d) length(%d)\n"), this->GetHead(), seg->length);
  654. Output::Flush();
  655. }
  656. #endif
  657. newSeg->CopySegment(this->GetRecycler(), newSeg, 0, seg, 0, seg->length);
  658. this->SetHeadAndLastUsedSegment(newSeg);
  659. VirtualTableInfo<JavascriptNativeIntArray>::SetVirtualTable(this);
  660. this->type = JavascriptNativeIntArray::GetInitialType(this->GetScriptContext());
  661. ArrayCallSiteInfo *arrayInfo = this->GetArrayCallSiteInfo();
  662. if (arrayInfo && !arrayInfo->isNotCopyOnAccessArray)
  663. {
  664. arrayInfo->isNotCopyOnAccessArray = 1;
  665. }
  666. }
  667. uint32 JavascriptCopyOnAccessNativeIntArray::GetNextIndex(uint32 index) const
  668. {
  669. if (this->length == 0 || (index != Js::JavascriptArray::InvalidIndex && index >= this->length))
  670. {
  671. return Js::JavascriptArray::InvalidIndex;
  672. }
  673. else if (index == Js::JavascriptArray::InvalidIndex)
  674. {
  675. return 0;
  676. }
  677. else
  678. {
  679. return index + 1;
  680. }
  681. }
  682. BOOL JavascriptCopyOnAccessNativeIntArray::DirectGetItemAt(uint32 index, int* outVal)
  683. {
  684. Assert(this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->IsValidIndex(::Math::PointerCastToIntegral<uint32>(this->GetHead())));
  685. SparseArraySegment<int32> *seg = this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->GetSegmentByIndex(::Math::PointerCastToIntegral<byte>(this->GetHead()));
  686. if (this->length == 0 || index == Js::JavascriptArray::InvalidIndex || index >= this->length)
  687. {
  688. return FALSE;
  689. }
  690. else
  691. {
  692. *outVal = seg->elements[index];
  693. return TRUE;
  694. }
  695. }
  696. #endif
  697. bool JavascriptNativeIntArray::IsMissingHeadSegmentItem(const uint32 index) const
  698. {
  699. return IsMissingHeadSegmentItemImpl<int32>(index);
  700. }
  701. bool JavascriptNativeFloatArray::IsMissingHeadSegmentItem(const uint32 index) const
  702. {
  703. return IsMissingHeadSegmentItemImpl<double>(index);
  704. }
  705. void JavascriptArray::InternalFillFromPrototype(JavascriptArray *dstArray, uint32 dstIndex, JavascriptArray *srcArray, uint32 start, uint32 end, uint32 count)
  706. {
  707. RecyclableObject* prototype = srcArray->GetPrototype();
  708. while (start + count != end && JavascriptOperators::GetTypeId(prototype) != TypeIds_Null)
  709. {
  710. ForEachOwnMissingArrayIndexOfObject(srcArray, dstArray, prototype, start, end, dstIndex, [&](uint32 index, Var value) {
  711. uint32 n = dstIndex + (index - start);
  712. dstArray->SetItem(n, value, PropertyOperation_None);
  713. count++;
  714. });
  715. prototype = prototype->GetPrototype();
  716. }
  717. }
  718. /* static */
  719. bool JavascriptArray::HasInlineHeadSegment(uint32 length)
  720. {
  721. return length <= SparseArraySegmentBase::INLINE_CHUNK_SIZE;
  722. }
  723. Var JavascriptArray::OP_NewScArray(uint32 elementCount, ScriptContext* scriptContext)
  724. {
  725. // Called only to create array literals: size is known.
  726. return scriptContext->GetLibrary()->CreateArrayLiteral(elementCount);
  727. }
  728. Var JavascriptArray::OP_NewScArrayWithElements(uint32 elementCount, Var *elements, ScriptContext* scriptContext)
  729. {
  730. // Called only to create array literals: size is known.
  731. JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(elementCount);
  732. SparseArraySegment<Var> *head = SparseArraySegment<Var>::From(arr->head);
  733. Assert(elementCount <= head->length);
  734. CopyArray(head->elements, head->length, elements, elementCount);
  735. #ifdef VALIDATE_ARRAY
  736. arr->ValidateArray();
  737. #endif
  738. return arr;
  739. }
  740. Var JavascriptArray::OP_NewScArrayWithMissingValues(uint32 elementCount, ScriptContext* scriptContext)
  741. {
  742. // Called only to create array literals: size is known.
  743. JavascriptArray *const array = static_cast<JavascriptArray *>(OP_NewScArray(elementCount, scriptContext));
  744. array->SetHasNoMissingValues(false);
  745. SparseArraySegment<Var> *head = SparseArraySegment<Var>::From(array->head);
  746. head->FillSegmentBuffer(0, elementCount);
  747. return array;
  748. }
  749. #if ENABLE_PROFILE_INFO
  750. Var JavascriptArray::ProfiledNewScArray(uint32 elementCount, ScriptContext *scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
  751. {
  752. if (arrayInfo->IsNativeIntArray())
  753. {
  754. JavascriptNativeIntArray *arr = scriptContext->GetLibrary()->CreateNativeIntArrayLiteral(elementCount);
  755. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  756. return arr;
  757. }
  758. if (arrayInfo->IsNativeFloatArray())
  759. {
  760. JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(elementCount);
  761. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  762. return arr;
  763. }
  764. JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(elementCount);
  765. return arr;
  766. }
  767. #endif
  768. Var JavascriptArray::OP_NewScIntArray(AuxArray<int32> *ints, ScriptContext* scriptContext)
  769. {
  770. uint32 count = ints->count;
  771. JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(count);
  772. SparseArraySegment<Var> *head = SparseArraySegment<Var>::From(arr->head);
  773. Assert(count > 0 && count == head->length);
  774. for (uint i = 0; i < count; i++)
  775. {
  776. head->elements[i] = JavascriptNumber::ToVar(ints->elements[i], scriptContext);
  777. }
  778. return arr;
  779. }
  780. #if ENABLE_PROFILE_INFO
  781. Var JavascriptArray::ProfiledNewScIntArray(AuxArray<int32> *ints, ScriptContext* scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
  782. {
  783. // Called only to create array literals: size is known.
  784. uint32 count = ints->count;
  785. if (arrayInfo->IsNativeIntArray())
  786. {
  787. JavascriptNativeIntArray *arr;
  788. #if ENABLE_COPYONACCESS_ARRAY
  789. JavascriptLibrary *lib = scriptContext->GetLibrary();
  790. FunctionBody *functionBody = weakFuncRef->Get();
  791. if (JavascriptLibrary::IsCopyOnAccessArrayCallSite(lib, arrayInfo, count))
  792. {
  793. Assert(lib->cacheForCopyOnAccessArraySegments);
  794. arr = scriptContext->GetLibrary()->CreateCopyOnAccessNativeIntArrayLiteral(arrayInfo, functionBody, ints);
  795. }
  796. else
  797. #endif
  798. {
  799. arr = scriptContext->GetLibrary()->CreateNativeIntArrayLiteral(count);
  800. SparseArraySegment<int32> *head = SparseArraySegment<int32>::From(arr->head);
  801. Assert(count > 0 && count == head->length);
  802. CopyArray(head->elements, head->length, ints->elements, count);
  803. }
  804. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  805. return arr;
  806. }
  807. if (arrayInfo->IsNativeFloatArray())
  808. {
  809. JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(count);
  810. SparseArraySegment<double> *head = SparseArraySegment<double>::From(arr->head);
  811. Assert(count > 0 && count == head->length);
  812. for (uint i = 0; i < count; i++)
  813. {
  814. head->elements[i] = (double)ints->elements[i];
  815. }
  816. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  817. return arr;
  818. }
  819. return OP_NewScIntArray(ints, scriptContext);
  820. }
  821. #endif
  822. Var JavascriptArray::OP_NewScFltArray(AuxArray<double> *doubles, ScriptContext* scriptContext)
  823. {
  824. uint32 count = doubles->count;
  825. JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(count);
  826. SparseArraySegment<Var> *head = SparseArraySegment<Var>::From(arr->head);
  827. Assert(count > 0 && count == head->length);
  828. for (uint i = 0; i < count; i++)
  829. {
  830. double dval = doubles->elements[i];
  831. int32 ival;
  832. if (JavascriptNumber::TryGetInt32Value(dval, &ival) && !TaggedInt::IsOverflow(ival))
  833. {
  834. head->elements[i] = TaggedInt::ToVarUnchecked(ival);
  835. }
  836. else
  837. {
  838. head->elements[i] = JavascriptNumber::ToVarNoCheck(dval, scriptContext);
  839. }
  840. }
  841. return arr;
  842. }
  843. #if ENABLE_PROFILE_INFO
  844. Var JavascriptArray::ProfiledNewScFltArray(AuxArray<double> *doubles, ScriptContext* scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
  845. {
  846. // Called only to create array literals: size is known.
  847. if (arrayInfo->IsNativeFloatArray())
  848. {
  849. arrayInfo->SetIsNotNativeIntArray();
  850. uint32 count = doubles->count;
  851. JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(count);
  852. SparseArraySegment<double> *head = SparseArraySegment<double>::From(arr->head);
  853. Assert(count > 0 && count == head->length);
  854. CopyArray(head->elements, head->length, doubles->elements, count);
  855. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  856. return arr;
  857. }
  858. return OP_NewScFltArray(doubles, scriptContext);
  859. }
  860. Var JavascriptArray::ProfiledNewInstance(RecyclableObject* function, CallInfo callInfo, ...)
  861. {
  862. ARGUMENTS(args, callInfo);
  863. Assert(JavascriptFunction::Is(function) &&
  864. JavascriptFunction::FromVar(function)->GetFunctionInfo() == &JavascriptArray::EntryInfo::NewInstance);
  865. Assert(callInfo.Count >= 2);
  866. ArrayCallSiteInfo *arrayInfo = (ArrayCallSiteInfo*)args[0];
  867. JavascriptArray* pNew = nullptr;
  868. if (callInfo.Count == 2)
  869. {
  870. // Exactly one argument, which is the array length if it's a uint32.
  871. Var firstArgument = args[1];
  872. int elementCount;
  873. if (TaggedInt::Is(firstArgument))
  874. {
  875. elementCount = TaggedInt::ToInt32(firstArgument);
  876. if (elementCount < 0)
  877. {
  878. JavascriptError::ThrowRangeError(function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  879. }
  880. if (arrayInfo && arrayInfo->IsNativeArray())
  881. {
  882. if (arrayInfo->IsNativeIntArray())
  883. {
  884. pNew = function->GetLibrary()->CreateNativeIntArray(elementCount);
  885. }
  886. else
  887. {
  888. pNew = function->GetLibrary()->CreateNativeFloatArray(elementCount);
  889. }
  890. }
  891. else
  892. {
  893. pNew = function->GetLibrary()->CreateArray(elementCount);
  894. }
  895. }
  896. else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
  897. {
  898. // Non-tagged-int number: make sure the double value is really a uint32.
  899. double value = JavascriptNumber::GetValue(firstArgument);
  900. uint32 uvalue = JavascriptConversion::ToUInt32(value);
  901. if (value != uvalue)
  902. {
  903. JavascriptError::ThrowRangeError(function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  904. }
  905. if (arrayInfo && arrayInfo->IsNativeArray())
  906. {
  907. if (arrayInfo->IsNativeIntArray())
  908. {
  909. pNew = function->GetLibrary()->CreateNativeIntArray(uvalue);
  910. }
  911. else
  912. {
  913. pNew = function->GetLibrary()->CreateNativeFloatArray(uvalue);
  914. }
  915. }
  916. else
  917. {
  918. pNew = function->GetLibrary()->CreateArray(uvalue);
  919. }
  920. }
  921. else
  922. {
  923. //
  924. // First element is not int/double
  925. // create an array of length 1.
  926. // Set first element as the passed Var
  927. //
  928. pNew = function->GetLibrary()->CreateArray(1);
  929. pNew->DirectSetItemAt<Var>(0, firstArgument);
  930. }
  931. }
  932. else
  933. {
  934. // Called with a list of initial element values.
  935. // Create an array of the appropriate length and walk the list.
  936. if (arrayInfo && arrayInfo->IsNativeArray())
  937. {
  938. if (arrayInfo->IsNativeIntArray())
  939. {
  940. pNew = function->GetLibrary()->CreateNativeIntArray(callInfo.Count - 1);
  941. }
  942. else
  943. {
  944. pNew = function->GetLibrary()->CreateNativeFloatArray(callInfo.Count - 1);
  945. }
  946. }
  947. else
  948. {
  949. pNew = function->GetLibrary()->CreateArray(callInfo.Count - 1);
  950. }
  951. pNew->FillFromArgs(callInfo.Count - 1, 0, args.Values, arrayInfo);
  952. }
  953. #ifdef VALIDATE_ARRAY
  954. pNew->ValidateArray();
  955. #endif
  956. return pNew;
  957. }
  958. #endif
  959. Var JavascriptArray::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
  960. {
  961. ARGUMENTS(args, callInfo);
  962. return NewInstance(function, args);
  963. }
  964. Var JavascriptArray::NewInstance(RecyclableObject* function, Arguments args)
  965. {
  966. // Call to new Array(), possibly under another name.
  967. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  968. // SkipDefaultNewObject function flag should have prevented the default object
  969. // being created, except when call true a host dispatch.
  970. const CallInfo &callInfo = args.Info;
  971. Var newTarget = callInfo.Flags & CallFlags_NewTarget ? args.Values[args.Info.Count] : args[0];
  972. bool isCtorSuperCall = (callInfo.Flags & CallFlags_New) && newTarget != nullptr && !JavascriptOperators::IsUndefined(newTarget);
  973. Assert( isCtorSuperCall || !(callInfo.Flags & CallFlags_New) || args[0] == nullptr
  974. || JavascriptOperators::GetTypeId(args[0]) == TypeIds_HostDispatch);
  975. ScriptContext* scriptContext = function->GetScriptContext();
  976. JavascriptArray* pNew = nullptr;
  977. if (callInfo.Count < 2)
  978. {
  979. // No arguments passed to Array(), so create with the default size (0).
  980. pNew = CreateArrayFromConstructorNoArg(function, scriptContext);
  981. return isCtorSuperCall ?
  982. JavascriptOperators::OrdinaryCreateFromConstructor(RecyclableObject::FromVar(newTarget), pNew, nullptr, scriptContext) :
  983. pNew;
  984. }
  985. if (callInfo.Count == 2)
  986. {
  987. // Exactly one argument, which is the array length if it's a uint32.
  988. Var firstArgument = args[1];
  989. int elementCount;
  990. if (TaggedInt::Is(firstArgument))
  991. {
  992. elementCount = TaggedInt::ToInt32(firstArgument);
  993. if (elementCount < 0)
  994. {
  995. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  996. }
  997. pNew = CreateArrayFromConstructor(function, elementCount, scriptContext);
  998. }
  999. else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
  1000. {
  1001. // Non-tagged-int number: make sure the double value is really a uint32.
  1002. double value = JavascriptNumber::GetValue(firstArgument);
  1003. uint32 uvalue = JavascriptConversion::ToUInt32(value);
  1004. if (value != uvalue)
  1005. {
  1006. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  1007. }
  1008. pNew = CreateArrayFromConstructor(function, uvalue, scriptContext);
  1009. }
  1010. else
  1011. {
  1012. //
  1013. // First element is not int/double
  1014. // create an array of length 1.
  1015. // Set first element as the passed Var
  1016. //
  1017. pNew = CreateArrayFromConstructor(function, 1, scriptContext);
  1018. JavascriptOperators::SetItem(pNew, pNew, 0u, firstArgument, scriptContext, PropertyOperation_ThrowIfNotExtensible);
  1019. // If we were passed an uninitialized JavascriptArray as the this argument,
  1020. // we need to set the length. We must do this _after_ setting the first
  1021. // element as the array may have side effects such as a setter for property
  1022. // named '0' which would make the previous length of the array observable.
  1023. // If we weren't passed a JavascriptArray as the this argument, this is no-op.
  1024. pNew->SetLength(1);
  1025. }
  1026. }
  1027. else
  1028. {
  1029. // Called with a list of initial element values.
  1030. // Create an array of the appropriate length and walk the list.
  1031. pNew = CreateArrayFromConstructor(function, callInfo.Count - 1, scriptContext);
  1032. pNew->JavascriptArray::FillFromArgs(callInfo.Count - 1, 0, args.Values);
  1033. }
  1034. #ifdef VALIDATE_ARRAY
  1035. pNew->ValidateArray();
  1036. #endif
  1037. return isCtorSuperCall ?
  1038. JavascriptOperators::OrdinaryCreateFromConstructor(RecyclableObject::FromVar(newTarget), pNew, nullptr, scriptContext) :
  1039. pNew;
  1040. }
  1041. JavascriptArray* JavascriptArray::CreateArrayFromConstructor(RecyclableObject* constructor, uint32 length, ScriptContext* scriptContext)
  1042. {
  1043. JavascriptLibrary* library = constructor->GetLibrary();
  1044. // Create the Array object we'll return - this is the only way to create an object which is an exotic Array object.
  1045. // Note: We need to use the library from the ScriptContext of the constructor, not the currently executing function.
  1046. // This is for the case where a built-in @@create method from a different JavascriptLibrary is installed on
  1047. // constructor.
  1048. return library->CreateArray(length);
  1049. }
  1050. JavascriptArray* JavascriptArray::CreateArrayFromConstructorNoArg(RecyclableObject* constructor, ScriptContext* scriptContext)
  1051. {
  1052. JavascriptLibrary* library = constructor->GetLibrary();
  1053. return library->CreateArray();
  1054. }
  1055. #if ENABLE_PROFILE_INFO
  1056. Var JavascriptArray::ProfiledNewInstanceNoArg(RecyclableObject *function, ScriptContext *scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
  1057. {
  1058. Assert(JavascriptFunction::Is(function) &&
  1059. JavascriptFunction::FromVar(function)->GetFunctionInfo() == &JavascriptArray::EntryInfo::NewInstance);
  1060. if (arrayInfo->IsNativeIntArray())
  1061. {
  1062. JavascriptNativeIntArray *arr = scriptContext->GetLibrary()->CreateNativeIntArray();
  1063. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  1064. return arr;
  1065. }
  1066. if (arrayInfo->IsNativeFloatArray())
  1067. {
  1068. JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArray();
  1069. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  1070. return arr;
  1071. }
  1072. return scriptContext->GetLibrary()->CreateArray();
  1073. }
  1074. #endif
  1075. Var JavascriptNativeIntArray::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
  1076. {
  1077. ARGUMENTS(args, callInfo);
  1078. return NewInstance(function, args);
  1079. }
  1080. Var JavascriptNativeIntArray::NewInstance(RecyclableObject* function, Arguments args)
  1081. {
  1082. Assert(!PHASE_OFF1(NativeArrayPhase));
  1083. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1084. const CallInfo &callInfo = args.Info;
  1085. if (callInfo.Count < 2)
  1086. {
  1087. // No arguments passed to Array(), so create with the default size (0).
  1088. return function->GetLibrary()->CreateNativeIntArray();
  1089. }
  1090. JavascriptArray* pNew = nullptr;
  1091. if (callInfo.Count == 2)
  1092. {
  1093. // Exactly one argument, which is the array length if it's a uint32.
  1094. Var firstArgument = args[1];
  1095. int elementCount;
  1096. if (TaggedInt::Is(firstArgument))
  1097. {
  1098. elementCount = TaggedInt::ToInt32(firstArgument);
  1099. if (elementCount < 0)
  1100. {
  1101. JavascriptError::ThrowRangeError(
  1102. function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  1103. }
  1104. pNew = function->GetLibrary()->CreateNativeIntArray(elementCount);
  1105. }
  1106. else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
  1107. {
  1108. // Non-tagged-int number: make sure the double value is really a uint32.
  1109. double value = JavascriptNumber::GetValue(firstArgument);
  1110. uint32 uvalue = JavascriptConversion::ToUInt32(value);
  1111. if (value != uvalue)
  1112. {
  1113. JavascriptError::ThrowRangeError(
  1114. function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  1115. }
  1116. pNew = function->GetLibrary()->CreateNativeIntArray(uvalue);
  1117. }
  1118. else
  1119. {
  1120. //
  1121. // First element is not int/double
  1122. // create an array of length 1.
  1123. // Set first element as the passed Var
  1124. //
  1125. pNew = function->GetLibrary()->CreateArray(1);
  1126. pNew->DirectSetItemAt<Var>(0, firstArgument);
  1127. }
  1128. }
  1129. else
  1130. {
  1131. // Called with a list of initial element values.
  1132. // Create an array of the appropriate length and walk the list.
  1133. JavascriptNativeIntArray *arr = function->GetLibrary()->CreateNativeIntArray(callInfo.Count - 1);
  1134. pNew = arr->FillFromArgs(callInfo.Count - 1, 0, args.Values);
  1135. }
  1136. #ifdef VALIDATE_ARRAY
  1137. pNew->ValidateArray();
  1138. #endif
  1139. return pNew;
  1140. }
  1141. Var JavascriptNativeFloatArray::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
  1142. {
  1143. ARGUMENTS(args, callInfo);
  1144. return NewInstance(function, args);
  1145. }
  1146. Var JavascriptNativeFloatArray::NewInstance(RecyclableObject* function, Arguments args)
  1147. {
  1148. Assert(!PHASE_OFF1(NativeArrayPhase));
  1149. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1150. const CallInfo &callInfo = args.Info;
  1151. if (callInfo.Count < 2)
  1152. {
  1153. // No arguments passed to Array(), so create with the default size (0).
  1154. return function->GetLibrary()->CreateNativeFloatArray();
  1155. }
  1156. JavascriptArray* pNew = nullptr;
  1157. if (callInfo.Count == 2)
  1158. {
  1159. // Exactly one argument, which is the array length if it's a uint32.
  1160. Var firstArgument = args[1];
  1161. int elementCount;
  1162. if (TaggedInt::Is(firstArgument))
  1163. {
  1164. elementCount = TaggedInt::ToInt32(firstArgument);
  1165. if (elementCount < 0)
  1166. {
  1167. JavascriptError::ThrowRangeError(
  1168. function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  1169. }
  1170. pNew = function->GetLibrary()->CreateNativeFloatArray(elementCount);
  1171. }
  1172. else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
  1173. {
  1174. // Non-tagged-int number: make sure the double value is really a uint32.
  1175. double value = JavascriptNumber::GetValue(firstArgument);
  1176. uint32 uvalue = JavascriptConversion::ToUInt32(value);
  1177. if (value != uvalue)
  1178. {
  1179. JavascriptError::ThrowRangeError(
  1180. function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  1181. }
  1182. pNew = function->GetLibrary()->CreateNativeFloatArray(uvalue);
  1183. }
  1184. else
  1185. {
  1186. //
  1187. // First element is not int/double
  1188. // create an array of length 1.
  1189. // Set first element as the passed Var
  1190. //
  1191. pNew = function->GetLibrary()->CreateArray(1);
  1192. pNew->DirectSetItemAt<Var>(0, firstArgument);
  1193. }
  1194. }
  1195. else
  1196. {
  1197. // Called with a list of initial element values.
  1198. // Create an array of the appropriate length and walk the list.
  1199. JavascriptNativeFloatArray *arr = function->GetLibrary()->CreateNativeFloatArray(callInfo.Count - 1);
  1200. pNew = arr->FillFromArgs(callInfo.Count - 1, 0, args.Values);
  1201. }
  1202. #ifdef VALIDATE_ARRAY
  1203. pNew->ValidateArray();
  1204. #endif
  1205. return pNew;
  1206. }
  1207. #if ENABLE_PROFILE_INFO
  1208. JavascriptArray * JavascriptNativeIntArray::FillFromArgs(uint length, uint start, Var *args, ArrayCallSiteInfo *arrayInfo, bool dontCreateNewArray)
  1209. #else
  1210. JavascriptArray * JavascriptNativeIntArray::FillFromArgs(uint length, uint start, Var *args, bool dontCreateNewArray)
  1211. #endif
  1212. {
  1213. uint i;
  1214. for (i = start; i < length; i++)
  1215. {
  1216. Var item = args[i + 1];
  1217. bool isTaggedInt = TaggedInt::Is(item);
  1218. bool isTaggedIntMissingValue = false;
  1219. #ifdef _M_AMD64
  1220. if (isTaggedInt)
  1221. {
  1222. int32 iValue = TaggedInt::ToInt32(item);
  1223. isTaggedIntMissingValue = Js::SparseArraySegment<int32>::IsMissingItem(&iValue);
  1224. }
  1225. #endif
  1226. if (isTaggedInt && !isTaggedIntMissingValue)
  1227. {
  1228. // This is taggedInt case and we verified that item is not missing value in AMD64.
  1229. this->DirectSetItemAt(i, TaggedInt::ToInt32(item));
  1230. }
  1231. else if (!isTaggedIntMissingValue && JavascriptNumber::Is_NoTaggedIntCheck(item))
  1232. {
  1233. double dvalue = JavascriptNumber::GetValue(item);
  1234. int32 ivalue;
  1235. if (JavascriptNumber::TryGetInt32Value(dvalue, &ivalue) && !Js::SparseArraySegment<int32>::IsMissingItem(&ivalue))
  1236. {
  1237. this->DirectSetItemAt(i, ivalue);
  1238. }
  1239. else
  1240. {
  1241. #if ENABLE_PROFILE_INFO
  1242. if (arrayInfo)
  1243. {
  1244. arrayInfo->SetIsNotNativeIntArray();
  1245. }
  1246. #endif
  1247. if (HasInlineHeadSegment(length) && i < this->head->length && !dontCreateNewArray)
  1248. {
  1249. // Avoid shrinking the number of elements in the head segment. We can still create a new
  1250. // array here, so go ahead.
  1251. JavascriptNativeFloatArray *fArr =
  1252. this->GetScriptContext()->GetLibrary()->CreateNativeFloatArrayLiteral(length);
  1253. return fArr->JavascriptNativeFloatArray::FillFromArgs(length, 0, args);
  1254. }
  1255. JavascriptNativeFloatArray *fArr = JavascriptNativeIntArray::ToNativeFloatArray(this);
  1256. fArr->DirectSetItemAt(i, dvalue);
  1257. #if ENABLE_PROFILE_INFO
  1258. return fArr->JavascriptNativeFloatArray::FillFromArgs(length, i + 1, args, arrayInfo, dontCreateNewArray);
  1259. #else
  1260. return fArr->JavascriptNativeFloatArray::FillFromArgs(length, i + 1, args, dontCreateNewArray);
  1261. #endif
  1262. }
  1263. }
  1264. else
  1265. {
  1266. #if ENABLE_PROFILE_INFO
  1267. if (arrayInfo)
  1268. {
  1269. arrayInfo->SetIsNotNativeArray();
  1270. }
  1271. #endif
  1272. #pragma prefast(suppress:6237, "The right hand side condition does not have any side effects.")
  1273. if (sizeof(int32) < sizeof(Var) && HasInlineHeadSegment(length) && i < this->head->length && !dontCreateNewArray)
  1274. {
  1275. // Avoid shrinking the number of elements in the head segment. We can still create a new
  1276. // array here, so go ahead.
  1277. JavascriptArray *arr = this->GetScriptContext()->GetLibrary()->CreateArrayLiteral(length);
  1278. return arr->JavascriptArray::FillFromArgs(length, 0, args);
  1279. }
  1280. JavascriptArray *arr = JavascriptNativeIntArray::ToVarArray(this);
  1281. #if ENABLE_PROFILE_INFO
  1282. return arr->JavascriptArray::FillFromArgs(length, i, args, nullptr, dontCreateNewArray);
  1283. #else
  1284. return arr->JavascriptArray::FillFromArgs(length, i, args, dontCreateNewArray);
  1285. #endif
  1286. }
  1287. }
  1288. return this;
  1289. }
  1290. #if ENABLE_PROFILE_INFO
  1291. JavascriptArray * JavascriptNativeFloatArray::FillFromArgs(uint length, uint start, Var *args, ArrayCallSiteInfo *arrayInfo, bool dontCreateNewArray)
  1292. #else
  1293. JavascriptArray * JavascriptNativeFloatArray::FillFromArgs(uint length, uint start, Var *args, bool dontCreateNewArray)
  1294. #endif
  1295. {
  1296. uint i;
  1297. for (i = start; i < length; i++)
  1298. {
  1299. Var item = args[i + 1];
  1300. if (TaggedInt::Is(item))
  1301. {
  1302. this->DirectSetItemAt(i, TaggedInt::ToDouble(item));
  1303. }
  1304. else if (JavascriptNumber::Is_NoTaggedIntCheck(item))
  1305. {
  1306. this->DirectSetItemAt(i, JavascriptNumber::GetValue(item));
  1307. }
  1308. else
  1309. {
  1310. JavascriptArray *arr = JavascriptNativeFloatArray::ToVarArray(this);
  1311. #if ENABLE_PROFILE_INFO
  1312. if (arrayInfo)
  1313. {
  1314. arrayInfo->SetIsNotNativeArray();
  1315. }
  1316. return arr->JavascriptArray::FillFromArgs(length, i, args, nullptr, dontCreateNewArray);
  1317. #else
  1318. return arr->JavascriptArray::FillFromArgs(length, i, args, dontCreateNewArray);
  1319. #endif
  1320. }
  1321. }
  1322. return this;
  1323. }
  1324. #if ENABLE_PROFILE_INFO
  1325. JavascriptArray * JavascriptArray::FillFromArgs(uint length, uint start, Var *args, ArrayCallSiteInfo *arrayInfo, bool dontCreateNewArray)
  1326. #else
  1327. JavascriptArray * JavascriptArray::FillFromArgs(uint length, uint start, Var *args, bool dontCreateNewArray)
  1328. #endif
  1329. {
  1330. uint32 i;
  1331. for (i = start; i < length; i++)
  1332. {
  1333. Var item = args[i + 1];
  1334. this->DirectSetItemAt(i, item);
  1335. }
  1336. return this;
  1337. }
  1338. DynamicType * JavascriptNativeIntArray::GetInitialType(ScriptContext * scriptContext)
  1339. {
  1340. return scriptContext->GetLibrary()->GetNativeIntArrayType();
  1341. }
  1342. #if ENABLE_COPYONACCESS_ARRAY
  1343. DynamicType * JavascriptCopyOnAccessNativeIntArray::GetInitialType(ScriptContext * scriptContext)
  1344. {
  1345. return scriptContext->GetLibrary()->GetCopyOnAccessNativeIntArrayType();
  1346. }
  1347. #endif
  1348. JavascriptNativeFloatArray *JavascriptNativeIntArray::ToNativeFloatArray(JavascriptNativeIntArray *intArray)
  1349. {
  1350. #if ENABLE_PROFILE_INFO
  1351. ArrayCallSiteInfo *arrayInfo = intArray->GetArrayCallSiteInfo();
  1352. if (arrayInfo)
  1353. {
  1354. #if DBG
  1355. Js::JavascriptStackWalker walker(intArray->GetScriptContext());
  1356. Js::JavascriptFunction* caller = NULL;
  1357. bool foundScriptCaller = false;
  1358. while(walker.GetCaller(&caller))
  1359. {
  1360. if(caller != NULL && Js::ScriptFunction::Is(caller))
  1361. {
  1362. foundScriptCaller = true;
  1363. break;
  1364. }
  1365. }
  1366. if(foundScriptCaller)
  1367. {
  1368. Assert(caller);
  1369. Assert(caller->GetFunctionBody());
  1370. if(PHASE_TRACE(Js::NativeArrayConversionPhase, caller->GetFunctionBody()))
  1371. {
  1372. Output::Print(_u("Conversion: Int array to Float array ArrayCreationFunctionNumber:%2d CallSiteNumber:%2d \n"), arrayInfo->functionNumber, arrayInfo->callSiteNumber);
  1373. Output::Flush();
  1374. }
  1375. }
  1376. else
  1377. {
  1378. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1379. {
  1380. Output::Print(_u("Conversion: Int array to Float array across ScriptContexts"));
  1381. Output::Flush();
  1382. }
  1383. }
  1384. #else
  1385. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1386. {
  1387. Output::Print(_u("Conversion: Int array to Float array"));
  1388. Output::Flush();
  1389. }
  1390. #endif
  1391. arrayInfo->SetIsNotNativeIntArray();
  1392. }
  1393. #endif
  1394. // Grow the segments
  1395. // Code below has potential to throw due to OOM or SO. Just FailFast on those cases
  1396. AutoFailFastOnError failFastError;
  1397. ScriptContext *scriptContext = intArray->GetScriptContext();
  1398. Recycler *recycler = scriptContext->GetRecycler();
  1399. SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
  1400. for (seg = intArray->head; seg; seg = nextSeg)
  1401. {
  1402. nextSeg = seg->next;
  1403. uint32 size = seg->size;
  1404. if (size == 0)
  1405. {
  1406. continue;
  1407. }
  1408. uint32 left = seg->left;
  1409. uint32 length = seg->length;
  1410. int i;
  1411. int32 ival;
  1412. // The old segment will have size/2 and length capped by the new size.
  1413. uint32 newSegSize = seg->size >> 1;
  1414. if (seg == intArray->head || seg->length > (newSegSize >> 1))
  1415. {
  1416. // Some live elements are being pushed out of this segment, so allocate a new one.
  1417. SparseArraySegment<double> *newSeg =
  1418. SparseArraySegment<double>::AllocateSegment(recycler, left, length, nextSeg);
  1419. Assert(newSeg != nullptr);
  1420. Assert((prevSeg == nullptr) == (seg == intArray->head));
  1421. newSeg->next = nextSeg;
  1422. intArray->LinkSegments((SparseArraySegment<double>*)prevSeg, newSeg);
  1423. if (intArray->GetLastUsedSegment() == seg)
  1424. {
  1425. intArray->SetLastUsedSegment(newSeg);
  1426. }
  1427. prevSeg = newSeg;
  1428. SegmentBTree * segmentMap = intArray->GetSegmentMap();
  1429. if (segmentMap)
  1430. {
  1431. segmentMap->SwapSegment(left, seg, newSeg);
  1432. }
  1433. // Fill the new segment with the overflow.
  1434. for (i = 0; (uint)i < newSeg->length; i++)
  1435. {
  1436. ival = ((SparseArraySegment<int32>*)seg)->elements[i /*+ seg->length*/];
  1437. if (ival == JavascriptNativeIntArray::MissingItem)
  1438. {
  1439. continue;
  1440. }
  1441. newSeg->elements[i] = (double)ival;
  1442. }
  1443. }
  1444. else
  1445. {
  1446. seg->size = newSegSize >> 1;
  1447. seg->CheckLengthvsSize();
  1448. // Now convert the contents that will remain in the old segment.
  1449. for (i = seg->length - 1; i >= 0; i--)
  1450. {
  1451. ival = ((SparseArraySegment<int32>*)seg)->elements[i];
  1452. if (ival == JavascriptNativeIntArray::MissingItem)
  1453. {
  1454. ((SparseArraySegment<double>*)seg)->elements[i] = (double)JavascriptNativeFloatArray::MissingItem;
  1455. }
  1456. else
  1457. {
  1458. ((SparseArraySegment<double>*)seg)->elements[i] = (double)ival;
  1459. }
  1460. }
  1461. prevSeg = seg;
  1462. }
  1463. }
  1464. if (intArray->GetType() == scriptContext->GetLibrary()->GetNativeIntArrayType())
  1465. {
  1466. intArray->type = scriptContext->GetLibrary()->GetNativeFloatArrayType();
  1467. }
  1468. else
  1469. {
  1470. if (intArray->GetDynamicType()->GetIsLocked())
  1471. {
  1472. DynamicTypeHandler *typeHandler = intArray->GetDynamicType()->GetTypeHandler();
  1473. if (typeHandler->IsPathTypeHandler())
  1474. {
  1475. // We can't allow a type with the new type ID to be promoted to the old type.
  1476. // So go to a dictionary type handler, which will orphan the new type.
  1477. // This should be a corner case, so the inability to share the new type is unlikely to matter.
  1478. // If it does matter, try building a path from the new type's built-in root.
  1479. static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(intArray);
  1480. }
  1481. else
  1482. {
  1483. intArray->ChangeType();
  1484. }
  1485. }
  1486. intArray->GetType()->SetTypeId(TypeIds_NativeFloatArray);
  1487. }
  1488. if (CrossSite::IsCrossSiteObjectTyped(intArray))
  1489. {
  1490. Assert(VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::HasVirtualTable(intArray));
  1491. VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::SetVirtualTable(intArray);
  1492. }
  1493. else
  1494. {
  1495. Assert(VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(intArray));
  1496. VirtualTableInfo<JavascriptNativeFloatArray>::SetVirtualTable(intArray);
  1497. }
  1498. failFastError.Completed();
  1499. return (JavascriptNativeFloatArray*)intArray;
  1500. }
  1501. /*
  1502. * JavascriptArray::ChangeArrayTypeToNativeArray<double>
  1503. * - Converts the Var Array's type to NativeFloat.
  1504. * - Sets the VirtualTable to "JavascriptNativeFloatArray"
  1505. */
  1506. template<>
  1507. void JavascriptArray::ChangeArrayTypeToNativeArray<double>(JavascriptArray * varArray, ScriptContext * scriptContext)
  1508. {
  1509. AssertMsg(!JavascriptNativeArray::Is(varArray), "Ensure that the incoming Array is a Var array");
  1510. if (varArray->GetType() == scriptContext->GetLibrary()->GetArrayType())
  1511. {
  1512. varArray->type = scriptContext->GetLibrary()->GetNativeFloatArrayType();
  1513. }
  1514. else
  1515. {
  1516. if (varArray->GetDynamicType()->GetIsLocked())
  1517. {
  1518. DynamicTypeHandler *typeHandler = varArray->GetDynamicType()->GetTypeHandler();
  1519. if (typeHandler->IsPathTypeHandler())
  1520. {
  1521. // We can't allow a type with the new type ID to be promoted to the old type.
  1522. // So go to a dictionary type handler, which will orphan the new type.
  1523. // This should be a corner case, so the inability to share the new type is unlikely to matter.
  1524. // If it does matter, try building a path from the new type's built-in root.
  1525. static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(varArray);
  1526. }
  1527. else
  1528. {
  1529. varArray->ChangeType();
  1530. }
  1531. }
  1532. varArray->GetType()->SetTypeId(TypeIds_NativeFloatArray);
  1533. }
  1534. if (CrossSite::IsCrossSiteObjectTyped(varArray))
  1535. {
  1536. Assert(VirtualTableInfo<CrossSiteObject<JavascriptArray>>::HasVirtualTable(varArray));
  1537. VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::SetVirtualTable(varArray);
  1538. }
  1539. else
  1540. {
  1541. Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(varArray));
  1542. VirtualTableInfo<JavascriptNativeFloatArray>::SetVirtualTable(varArray);
  1543. }
  1544. }
  1545. /*
  1546. * JavascriptArray::ChangeArrayTypeToNativeArray<int32>
  1547. * - Converts the Var Array's type to NativeInt.
  1548. * - Sets the VirtualTable to "JavascriptNativeIntArray"
  1549. */
  1550. template<>
  1551. void JavascriptArray::ChangeArrayTypeToNativeArray<int32>(JavascriptArray * varArray, ScriptContext * scriptContext)
  1552. {
  1553. AssertMsg(!JavascriptNativeArray::Is(varArray), "Ensure that the incoming Array is a Var array");
  1554. if (varArray->GetType() == scriptContext->GetLibrary()->GetArrayType())
  1555. {
  1556. varArray->type = scriptContext->GetLibrary()->GetNativeIntArrayType();
  1557. }
  1558. else
  1559. {
  1560. if (varArray->GetDynamicType()->GetIsLocked())
  1561. {
  1562. DynamicTypeHandler *typeHandler = varArray->GetDynamicType()->GetTypeHandler();
  1563. if (typeHandler->IsPathTypeHandler())
  1564. {
  1565. // We can't allow a type with the new type ID to be promoted to the old type.
  1566. // So go to a dictionary type handler, which will orphan the new type.
  1567. // This should be a corner case, so the inability to share the new type is unlikely to matter.
  1568. // If it does matter, try building a path from the new type's built-in root.
  1569. static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(varArray);
  1570. }
  1571. else
  1572. {
  1573. varArray->ChangeType();
  1574. }
  1575. }
  1576. varArray->GetType()->SetTypeId(TypeIds_NativeIntArray);
  1577. }
  1578. if (CrossSite::IsCrossSiteObjectTyped(varArray))
  1579. {
  1580. Assert(VirtualTableInfo<CrossSiteObject<JavascriptArray>>::HasVirtualTable(varArray));
  1581. VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::SetVirtualTable(varArray);
  1582. }
  1583. else
  1584. {
  1585. Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(varArray));
  1586. VirtualTableInfo<JavascriptNativeIntArray>::SetVirtualTable(varArray);
  1587. }
  1588. }
  1589. template<>
  1590. int32 JavascriptArray::GetNativeValue<int32>(Js::Var ival, ScriptContext * scriptContext)
  1591. {
  1592. return JavascriptConversion::ToInt32(ival, scriptContext);
  1593. }
  1594. template <>
  1595. double JavascriptArray::GetNativeValue<double>(Var ival, ScriptContext * scriptContext)
  1596. {
  1597. return JavascriptConversion::ToNumber(ival, scriptContext);
  1598. }
  1599. /*
  1600. * JavascriptArray::ConvertToNativeArrayInPlace
  1601. * In place conversion of all Var elements to Native Int/Double elements in an array.
  1602. * We do not update the DynamicProfileInfo of the array here.
  1603. */
  1604. template<typename NativeArrayType, typename T>
  1605. NativeArrayType *JavascriptArray::ConvertToNativeArrayInPlace(JavascriptArray *varArray)
  1606. {
  1607. AssertMsg(!JavascriptNativeArray::Is(varArray), "Ensure that the incoming Array is a Var array");
  1608. ScriptContext *scriptContext = varArray->GetScriptContext();
  1609. SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
  1610. for (seg = varArray->head; seg; seg = nextSeg)
  1611. {
  1612. nextSeg = seg->next;
  1613. uint32 size = seg->size;
  1614. if (size == 0)
  1615. {
  1616. continue;
  1617. }
  1618. int i;
  1619. Var ival;
  1620. uint32 growFactor = sizeof(Var) / sizeof(T);
  1621. AssertMsg(growFactor == 1, "We support only in place conversion of Var array to Native Array");
  1622. // Now convert the contents that will remain in the old segment.
  1623. for (i = seg->length - 1; i >= 0; i--)
  1624. {
  1625. ival = ((SparseArraySegment<Var>*)seg)->elements[i];
  1626. if (ival == JavascriptArray::MissingItem)
  1627. {
  1628. ((SparseArraySegment<T>*)seg)->elements[i] = NativeArrayType::MissingItem;
  1629. }
  1630. else
  1631. {
  1632. ((SparseArraySegment<T>*)seg)->elements[i] = GetNativeValue<T>(ival, scriptContext);
  1633. }
  1634. }
  1635. prevSeg = seg;
  1636. }
  1637. // Update the type of the Array
  1638. ChangeArrayTypeToNativeArray<T>(varArray, scriptContext);
  1639. return (NativeArrayType*)varArray;
  1640. }
  1641. JavascriptArray *JavascriptNativeIntArray::ConvertToVarArray(JavascriptNativeIntArray *intArray)
  1642. {
  1643. #if ENABLE_COPYONACCESS_ARRAY
  1644. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(intArray);
  1645. #endif
  1646. ScriptContext *scriptContext = intArray->GetScriptContext();
  1647. Recycler *recycler = scriptContext->GetRecycler();
  1648. SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
  1649. // Code below has potential to throw due to OOM or SO. Just FailFast on those cases
  1650. AutoFailFastOnError failFastError;
  1651. for (seg = intArray->head; seg; seg = nextSeg)
  1652. {
  1653. nextSeg = seg->next;
  1654. uint32 size = seg->size;
  1655. if (size == 0)
  1656. {
  1657. continue;
  1658. }
  1659. uint32 left = seg->left;
  1660. uint32 length = seg->length;
  1661. int i;
  1662. int32 ival;
  1663. // Shrink?
  1664. uint32 growFactor = sizeof(Var) / sizeof(int32);
  1665. if ((growFactor != 1 && (seg == intArray->head || seg->length > (seg->size / growFactor))) ||
  1666. (seg->next == nullptr && SparseArraySegmentBase::IsLeafSegment(seg, recycler)))
  1667. {
  1668. // Some live elements are being pushed out of this segment, so allocate a new one.
  1669. // And/or the old segment is not scanned by the recycler, so we need a new one to hold vars.
  1670. SparseArraySegment<Var> *newSeg =
  1671. SparseArraySegment<Var>::AllocateSegment(recycler, left, length, nextSeg);
  1672. AnalysisAssert(newSeg);
  1673. Assert((prevSeg == nullptr) == (seg == intArray->head));
  1674. newSeg->next = nextSeg;
  1675. intArray->LinkSegments((SparseArraySegment<Var>*)prevSeg, newSeg);
  1676. if (intArray->GetLastUsedSegment() == seg)
  1677. {
  1678. intArray->SetLastUsedSegment(newSeg);
  1679. }
  1680. prevSeg = newSeg;
  1681. SegmentBTree * segmentMap = intArray->GetSegmentMap();
  1682. if (segmentMap)
  1683. {
  1684. segmentMap->SwapSegment(left, seg, newSeg);
  1685. }
  1686. // Fill the new segment with the overflow.
  1687. for (i = 0; (uint)i < newSeg->length; i++)
  1688. {
  1689. ival = ((SparseArraySegment<int32>*)seg)->elements[i];
  1690. if (ival == JavascriptNativeIntArray::MissingItem)
  1691. {
  1692. continue;
  1693. }
  1694. newSeg->elements[i] = JavascriptNumber::ToVar(ival, scriptContext);
  1695. }
  1696. }
  1697. else
  1698. {
  1699. seg->size = seg->size / growFactor;
  1700. seg->CheckLengthvsSize();
  1701. // Now convert the contents that will remain in the old segment.
  1702. // Walk backward in case we're growing the element size.
  1703. for (i = seg->length - 1; i >= 0; i--)
  1704. {
  1705. ival = ((SparseArraySegment<int32>*)seg)->elements[i];
  1706. if (ival == JavascriptNativeIntArray::MissingItem)
  1707. {
  1708. ((SparseArraySegment<Var>*)seg)->elements[i] = (Var)JavascriptArray::MissingItem;
  1709. }
  1710. else
  1711. {
  1712. ((SparseArraySegment<Var>*)seg)->elements[i] = JavascriptNumber::ToVar(ival, scriptContext);
  1713. }
  1714. }
  1715. prevSeg = seg;
  1716. }
  1717. }
  1718. if (intArray->GetType() == scriptContext->GetLibrary()->GetNativeIntArrayType())
  1719. {
  1720. intArray->type = scriptContext->GetLibrary()->GetArrayType();
  1721. }
  1722. else
  1723. {
  1724. if (intArray->GetDynamicType()->GetIsLocked())
  1725. {
  1726. DynamicTypeHandler *typeHandler = intArray->GetDynamicType()->GetTypeHandler();
  1727. if (typeHandler->IsPathTypeHandler())
  1728. {
  1729. // We can't allow a type with the new type ID to be promoted to the old type.
  1730. // So go to a dictionary type handler, which will orphan the new type.
  1731. // This should be a corner case, so the inability to share the new type is unlikely to matter.
  1732. // If it does matter, try building a path from the new type's built-in root.
  1733. static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(intArray);
  1734. }
  1735. else
  1736. {
  1737. intArray->ChangeType();
  1738. }
  1739. }
  1740. intArray->GetType()->SetTypeId(TypeIds_Array);
  1741. }
  1742. if (CrossSite::IsCrossSiteObjectTyped(intArray))
  1743. {
  1744. Assert(VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::HasVirtualTable(intArray));
  1745. VirtualTableInfo<CrossSiteObject<JavascriptArray>>::SetVirtualTable(intArray);
  1746. }
  1747. else
  1748. {
  1749. Assert(VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(intArray));
  1750. VirtualTableInfo<JavascriptArray>::SetVirtualTable(intArray);
  1751. }
  1752. failFastError.Completed();
  1753. return intArray;
  1754. }
  1755. JavascriptArray *JavascriptNativeIntArray::ToVarArray(JavascriptNativeIntArray *intArray)
  1756. {
  1757. #if ENABLE_PROFILE_INFO
  1758. ArrayCallSiteInfo *arrayInfo = intArray->GetArrayCallSiteInfo();
  1759. if (arrayInfo)
  1760. {
  1761. #if DBG
  1762. Js::JavascriptStackWalker walker(intArray->GetScriptContext());
  1763. Js::JavascriptFunction* caller = NULL;
  1764. bool foundScriptCaller = false;
  1765. while(walker.GetCaller(&caller))
  1766. {
  1767. if(caller != NULL && Js::ScriptFunction::Is(caller))
  1768. {
  1769. foundScriptCaller = true;
  1770. break;
  1771. }
  1772. }
  1773. if(foundScriptCaller)
  1774. {
  1775. Assert(caller);
  1776. Assert(caller->GetFunctionBody());
  1777. if(PHASE_TRACE(Js::NativeArrayConversionPhase, caller->GetFunctionBody()))
  1778. {
  1779. Output::Print(_u("Conversion: Int array to Var array ArrayCreationFunctionNumber:%2d CallSiteNumber:%2d \n"), arrayInfo->functionNumber, arrayInfo->callSiteNumber);
  1780. Output::Flush();
  1781. }
  1782. }
  1783. else
  1784. {
  1785. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1786. {
  1787. Output::Print(_u("Conversion: Int array to Var array across ScriptContexts"));
  1788. Output::Flush();
  1789. }
  1790. }
  1791. #else
  1792. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1793. {
  1794. Output::Print(_u("Conversion: Int array to Var array"));
  1795. Output::Flush();
  1796. }
  1797. #endif
  1798. arrayInfo->SetIsNotNativeArray();
  1799. }
  1800. #endif
  1801. intArray->ClearArrayCallSiteIndex();
  1802. return ConvertToVarArray(intArray);
  1803. }
  1804. DynamicType * JavascriptNativeFloatArray::GetInitialType(ScriptContext * scriptContext)
  1805. {
  1806. return scriptContext->GetLibrary()->GetNativeFloatArrayType();
  1807. }
  1808. /*
  1809. * JavascriptNativeFloatArray::ConvertToVarArray
  1810. * This function only converts all Float elements to Var elements in an array.
  1811. * DynamicProfileInfo of the array is not updated in this function.
  1812. */
  1813. JavascriptArray *JavascriptNativeFloatArray::ConvertToVarArray(JavascriptNativeFloatArray *fArray)
  1814. {
  1815. // We can't be growing the size of the element.
  1816. Assert(sizeof(double) >= sizeof(Var));
  1817. uint32 shrinkFactor = sizeof(double) / sizeof(Var);
  1818. ScriptContext *scriptContext = fArray->GetScriptContext();
  1819. Recycler *recycler = scriptContext->GetRecycler();
  1820. SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
  1821. // Code below has potential to throw due to OOM or SO. Just FailFast on those cases
  1822. AutoFailFastOnError failFastError;
  1823. for (seg = fArray->head; seg; seg = nextSeg)
  1824. {
  1825. nextSeg = seg->next;
  1826. if (seg->size == 0)
  1827. {
  1828. continue;
  1829. }
  1830. uint32 left = seg->left;
  1831. uint32 length = seg->length;
  1832. SparseArraySegment<Var> *newSeg;
  1833. if (seg->next == nullptr && SparseArraySegmentBase::IsLeafSegment(seg, recycler))
  1834. {
  1835. // The old segment is not scanned by the recycler, so we need a new one to hold vars.
  1836. newSeg =
  1837. SparseArraySegment<Var>::AllocateSegment(recycler, left, length, nextSeg);
  1838. Assert((prevSeg == nullptr) == (seg == fArray->head));
  1839. newSeg->next = nextSeg;
  1840. fArray->LinkSegments((SparseArraySegment<Var>*)prevSeg, newSeg);
  1841. if (fArray->GetLastUsedSegment() == seg)
  1842. {
  1843. fArray->SetLastUsedSegment(newSeg);
  1844. }
  1845. prevSeg = newSeg;
  1846. SegmentBTree * segmentMap = fArray->GetSegmentMap();
  1847. if (segmentMap)
  1848. {
  1849. segmentMap->SwapSegment(left, seg, newSeg);
  1850. }
  1851. }
  1852. else
  1853. {
  1854. newSeg = (SparseArraySegment<Var>*)seg;
  1855. prevSeg = seg;
  1856. if (shrinkFactor != 1)
  1857. {
  1858. uint32 newSize = seg->size * shrinkFactor;
  1859. uint32 limit;
  1860. if (seg->next)
  1861. {
  1862. limit = seg->next->left;
  1863. }
  1864. else
  1865. {
  1866. limit = JavascriptArray::MaxArrayLength;
  1867. }
  1868. seg->size = min(newSize, limit - seg->left);
  1869. seg->CheckLengthvsSize();
  1870. }
  1871. }
  1872. uint32 i;
  1873. for (i = 0; i < seg->length; i++)
  1874. {
  1875. if (SparseArraySegment<double>::IsMissingItem(&((SparseArraySegment<double>*)seg)->elements[i]))
  1876. {
  1877. if (seg == newSeg)
  1878. {
  1879. newSeg->elements[i] = (Var)JavascriptArray::MissingItem;
  1880. }
  1881. Assert(newSeg->elements[i] == (Var)JavascriptArray::MissingItem);
  1882. }
  1883. else if (*(uint64*)&(((SparseArraySegment<double>*)seg)->elements[i]) == 0ull)
  1884. {
  1885. newSeg->elements[i] = TaggedInt::ToVarUnchecked(0);
  1886. }
  1887. else
  1888. {
  1889. int32 ival;
  1890. double dval = ((SparseArraySegment<double>*)seg)->elements[i];
  1891. if (JavascriptNumber::TryGetInt32Value(dval, &ival) && !TaggedInt::IsOverflow(ival))
  1892. {
  1893. newSeg->elements[i] = TaggedInt::ToVarUnchecked(ival);
  1894. }
  1895. else
  1896. {
  1897. newSeg->elements[i] = JavascriptNumber::ToVarWithCheck(dval, scriptContext);
  1898. }
  1899. }
  1900. }
  1901. if (seg == newSeg && shrinkFactor != 1)
  1902. {
  1903. // Fill the remaining slots.
  1904. newSeg->FillSegmentBuffer(i, seg->size);
  1905. }
  1906. }
  1907. if (fArray->GetType() == scriptContext->GetLibrary()->GetNativeFloatArrayType())
  1908. {
  1909. fArray->type = scriptContext->GetLibrary()->GetArrayType();
  1910. }
  1911. else
  1912. {
  1913. if (fArray->GetDynamicType()->GetIsLocked())
  1914. {
  1915. DynamicTypeHandler *typeHandler = fArray->GetDynamicType()->GetTypeHandler();
  1916. if (typeHandler->IsPathTypeHandler())
  1917. {
  1918. // We can't allow a type with the new type ID to be promoted to the old type.
  1919. // So go to a dictionary type handler, which will orphan the new type.
  1920. // This should be a corner case, so the inability to share the new type is unlikely to matter.
  1921. // If it does matter, try building a path from the new type's built-in root.
  1922. static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(fArray);
  1923. }
  1924. else
  1925. {
  1926. fArray->ChangeType();
  1927. }
  1928. }
  1929. fArray->GetType()->SetTypeId(TypeIds_Array);
  1930. }
  1931. if (CrossSite::IsCrossSiteObjectTyped(fArray))
  1932. {
  1933. Assert(VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::HasVirtualTable(fArray));
  1934. VirtualTableInfo<CrossSiteObject<JavascriptArray>>::SetVirtualTable(fArray);
  1935. }
  1936. else
  1937. {
  1938. Assert(VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(fArray));
  1939. VirtualTableInfo<JavascriptArray>::SetVirtualTable(fArray);
  1940. }
  1941. failFastError.Completed();
  1942. return fArray;
  1943. }
  1944. JavascriptArray *JavascriptNativeFloatArray::ToVarArray(JavascriptNativeFloatArray *fArray)
  1945. {
  1946. #if ENABLE_PROFILE_INFO
  1947. ArrayCallSiteInfo *arrayInfo = fArray->GetArrayCallSiteInfo();
  1948. if (arrayInfo)
  1949. {
  1950. #if DBG
  1951. Js::JavascriptStackWalker walker(fArray->GetScriptContext());
  1952. Js::JavascriptFunction* caller = NULL;
  1953. bool foundScriptCaller = false;
  1954. while(walker.GetCaller(&caller))
  1955. {
  1956. if(caller != NULL && Js::ScriptFunction::Is(caller))
  1957. {
  1958. foundScriptCaller = true;
  1959. break;
  1960. }
  1961. }
  1962. if(foundScriptCaller)
  1963. {
  1964. Assert(caller);
  1965. Assert(caller->GetFunctionBody());
  1966. if(PHASE_TRACE(Js::NativeArrayConversionPhase, caller->GetFunctionBody()))
  1967. {
  1968. Output::Print(_u("Conversion: Float array to Var array ArrayCreationFunctionNumber:%2d CallSiteNumber:%2d \n"), arrayInfo->functionNumber, arrayInfo->callSiteNumber);
  1969. Output::Flush();
  1970. }
  1971. }
  1972. else
  1973. {
  1974. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1975. {
  1976. Output::Print(_u("Conversion: Float array to Var array across ScriptContexts"));
  1977. Output::Flush();
  1978. }
  1979. }
  1980. #else
  1981. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1982. {
  1983. Output::Print(_u("Conversion: Float array to Var array"));
  1984. Output::Flush();
  1985. }
  1986. #endif
  1987. if(fArray->GetScriptContext()->IsScriptContextInNonDebugMode())
  1988. {
  1989. Assert(!arrayInfo->IsNativeIntArray());
  1990. }
  1991. arrayInfo->SetIsNotNativeArray();
  1992. }
  1993. #endif
  1994. fArray->ClearArrayCallSiteIndex();
  1995. return ConvertToVarArray(fArray);
  1996. }
  1997. // Convert Var to index in the Array.
  1998. // Note: Spec calls out a few rules for these parameters:
  1999. // 1. if (arg > length) { return length; }
  2000. // clamp to length, not length-1
  2001. // 2. if (arg < 0) { return max(0, length + arg); }
  2002. // treat negative arg as index from the end of the array (with -1 mapping to length-1)
  2003. // Effectively, this function will return a value between 0 and length, inclusive.
  2004. int64 JavascriptArray::GetIndexFromVar(Js::Var arg, int64 length, ScriptContext* scriptContext)
  2005. {
  2006. int64 index;
  2007. if (TaggedInt::Is(arg))
  2008. {
  2009. int intValue = TaggedInt::ToInt32(arg);
  2010. if (intValue < 0)
  2011. {
  2012. index = max<int64>(0, length + intValue);
  2013. }
  2014. else
  2015. {
  2016. index = intValue;
  2017. }
  2018. if (index > length)
  2019. {
  2020. index = length;
  2021. }
  2022. }
  2023. else
  2024. {
  2025. double doubleValue = JavascriptConversion::ToInteger(arg, scriptContext);
  2026. // Handle the Number.POSITIVE_INFINITY case
  2027. if (doubleValue > length)
  2028. {
  2029. return length;
  2030. }
  2031. index = NumberUtilities::TryToInt64(doubleValue);
  2032. if (index < 0)
  2033. {
  2034. index = max<int64>(0, index + length);
  2035. }
  2036. }
  2037. return index;
  2038. }
  2039. TypeId JavascriptArray::OP_SetNativeIntElementC(JavascriptNativeIntArray *arr, uint32 index, Var value, ScriptContext *scriptContext)
  2040. {
  2041. int32 iValue;
  2042. double dValue;
  2043. TypeId typeId = arr->TrySetNativeIntArrayItem(value, &iValue, &dValue);
  2044. if (typeId == TypeIds_NativeIntArray)
  2045. {
  2046. arr->SetArrayLiteralItem(index, iValue);
  2047. }
  2048. else if (typeId == TypeIds_NativeFloatArray)
  2049. {
  2050. arr->SetArrayLiteralItem(index, dValue);
  2051. }
  2052. else
  2053. {
  2054. arr->SetArrayLiteralItem(index, value);
  2055. }
  2056. return typeId;
  2057. }
  2058. TypeId JavascriptArray::OP_SetNativeFloatElementC(JavascriptNativeFloatArray *arr, uint32 index, Var value, ScriptContext *scriptContext)
  2059. {
  2060. double dValue;
  2061. TypeId typeId = arr->TrySetNativeFloatArrayItem(value, &dValue);
  2062. if (typeId == TypeIds_NativeFloatArray)
  2063. {
  2064. arr->SetArrayLiteralItem(index, dValue);
  2065. }
  2066. else
  2067. {
  2068. arr->SetArrayLiteralItem(index, value);
  2069. }
  2070. return typeId;
  2071. }
  2072. template<typename T>
  2073. void JavascriptArray::SetArrayLiteralItem(uint32 index, T value)
  2074. {
  2075. SparseArraySegment<T> * segment = SparseArraySegment<T>::From(this->head);
  2076. Assert(segment->left == 0);
  2077. Assert(index < segment->length);
  2078. segment->elements[index] = value;
  2079. }
  2080. void JavascriptNativeIntArray::SetIsPrototype()
  2081. {
  2082. // Force the array to be non-native to simplify inspection, filling from proto, etc.
  2083. ToVarArray(this);
  2084. __super::SetIsPrototype();
  2085. }
  2086. void JavascriptNativeFloatArray::SetIsPrototype()
  2087. {
  2088. // Force the array to be non-native to simplify inspection, filling from proto, etc.
  2089. ToVarArray(this);
  2090. __super::SetIsPrototype();
  2091. }
  2092. #if ENABLE_PROFILE_INFO
  2093. ArrayCallSiteInfo *JavascriptNativeArray::GetArrayCallSiteInfo()
  2094. {
  2095. RecyclerWeakReference<FunctionBody> *weakRef = this->weakRefToFuncBody;
  2096. if (weakRef)
  2097. {
  2098. FunctionBody *functionBody = weakRef->Get();
  2099. if (functionBody)
  2100. {
  2101. if (functionBody->HasDynamicProfileInfo())
  2102. {
  2103. Js::ProfileId profileId = this->GetArrayCallSiteIndex();
  2104. if (profileId < functionBody->GetProfiledArrayCallSiteCount())
  2105. {
  2106. return functionBody->GetAnyDynamicProfileInfo()->GetArrayCallSiteInfo(functionBody, profileId);
  2107. }
  2108. }
  2109. }
  2110. else
  2111. {
  2112. this->ClearArrayCallSiteIndex();
  2113. }
  2114. }
  2115. return nullptr;
  2116. }
  2117. void JavascriptNativeArray::SetArrayProfileInfo(RecyclerWeakReference<FunctionBody> *weakRef, ArrayCallSiteInfo *arrayInfo)
  2118. {
  2119. Assert(weakRef);
  2120. FunctionBody *functionBody = weakRef->Get();
  2121. if (functionBody && functionBody->HasDynamicProfileInfo())
  2122. {
  2123. ArrayCallSiteInfo *baseInfo = functionBody->GetAnyDynamicProfileInfo()->GetArrayCallSiteInfo(functionBody, 0);
  2124. Js::ProfileId index = (Js::ProfileId)(arrayInfo - baseInfo);
  2125. Assert(index < functionBody->GetProfiledArrayCallSiteCount());
  2126. SetArrayCallSite(index, weakRef);
  2127. }
  2128. }
  2129. void JavascriptNativeArray::CopyArrayProfileInfo(Js::JavascriptNativeArray* baseArray)
  2130. {
  2131. if (baseArray->weakRefToFuncBody)
  2132. {
  2133. if (baseArray->weakRefToFuncBody->Get())
  2134. {
  2135. SetArrayCallSite(baseArray->GetArrayCallSiteIndex(), baseArray->weakRefToFuncBody);
  2136. }
  2137. else
  2138. {
  2139. baseArray->ClearArrayCallSiteIndex();
  2140. }
  2141. }
  2142. }
  2143. #endif
  2144. Var JavascriptNativeArray::FindMinOrMax(Js::ScriptContext * scriptContext, bool findMax)
  2145. {
  2146. if (JavascriptNativeIntArray::Is(this))
  2147. {
  2148. return this->FindMinOrMax<int32, false>(scriptContext, findMax);
  2149. }
  2150. else
  2151. {
  2152. return this->FindMinOrMax<double, true>(scriptContext, findMax);
  2153. }
  2154. }
  2155. template <typename T, bool checkNaNAndNegZero>
  2156. Var JavascriptNativeArray::FindMinOrMax(Js::ScriptContext * scriptContext, bool findMax)
  2157. {
  2158. AssertMsg(this->HasNoMissingValues(), "Fastpath is only for arrays with one segment and no missing values");
  2159. uint len = this->GetLength();
  2160. Js::SparseArraySegment<T>* headSegment = ((Js::SparseArraySegment<T>*)this->GetHead());
  2161. uint headSegLen = headSegment->length;
  2162. Assert(headSegLen == len);
  2163. if (headSegment->next == nullptr)
  2164. {
  2165. T currentRes = headSegment->elements[0];
  2166. for (uint i = 0; i < headSegLen; i++)
  2167. {
  2168. T compare = headSegment->elements[i];
  2169. if (checkNaNAndNegZero && JavascriptNumber::IsNan(double(compare)))
  2170. {
  2171. return scriptContext->GetLibrary()->GetNaN();
  2172. }
  2173. if (findMax ? currentRes < compare : currentRes > compare ||
  2174. (checkNaNAndNegZero && compare == 0 && Js::JavascriptNumber::IsNegZero(double(currentRes))))
  2175. {
  2176. currentRes = compare;
  2177. }
  2178. }
  2179. return Js::JavascriptNumber::ToVarNoCheck(currentRes, scriptContext);
  2180. }
  2181. else
  2182. {
  2183. AssertMsg(false, "FindMinOrMax currently supports native arrays with only one segment");
  2184. Throw::FatalInternalError();
  2185. }
  2186. }
  2187. SparseArraySegmentBase * JavascriptArray::GetLastUsedSegment() const
  2188. {
  2189. return HasSegmentMap() ?
  2190. PointerValue(segmentUnion.segmentBTreeRoot->lastUsedSegment) :
  2191. PointerValue(segmentUnion.lastUsedSegment);
  2192. }
  2193. void JavascriptArray::SetHeadAndLastUsedSegment(SparseArraySegmentBase * segment)
  2194. {
  2195. Assert(!HasSegmentMap());
  2196. this->head = this->segmentUnion.lastUsedSegment = segment;
  2197. }
  2198. void JavascriptArray::SetLastUsedSegment(SparseArraySegmentBase * segment)
  2199. {
  2200. if (HasSegmentMap())
  2201. {
  2202. this->segmentUnion.segmentBTreeRoot->lastUsedSegment = segment;
  2203. }
  2204. else
  2205. {
  2206. this->segmentUnion.lastUsedSegment = segment;
  2207. }
  2208. }
  2209. bool JavascriptArray::HasSegmentMap() const
  2210. {
  2211. return !!(GetFlags() & DynamicObjectFlags::HasSegmentMap);
  2212. }
  2213. SegmentBTreeRoot * JavascriptArray::GetSegmentMap() const
  2214. {
  2215. return (HasSegmentMap() ? segmentUnion.segmentBTreeRoot : nullptr);
  2216. }
  2217. void JavascriptArray::SetSegmentMap(SegmentBTreeRoot * segmentMap)
  2218. {
  2219. Assert(!HasSegmentMap());
  2220. SparseArraySegmentBase * lastUsedSeg = this->segmentUnion.lastUsedSegment;
  2221. SetFlags(GetFlags() | DynamicObjectFlags::HasSegmentMap);
  2222. segmentUnion.segmentBTreeRoot = segmentMap;
  2223. segmentMap->lastUsedSegment = lastUsedSeg;
  2224. }
  2225. void JavascriptArray::ClearSegmentMap()
  2226. {
  2227. if (HasSegmentMap())
  2228. {
  2229. SetFlags(GetFlags() & ~DynamicObjectFlags::HasSegmentMap);
  2230. SparseArraySegmentBase * lastUsedSeg = segmentUnion.segmentBTreeRoot->lastUsedSegment;
  2231. segmentUnion.segmentBTreeRoot = nullptr;
  2232. segmentUnion.lastUsedSegment = lastUsedSeg;
  2233. }
  2234. }
  2235. SegmentBTreeRoot * JavascriptArray::BuildSegmentMap()
  2236. {
  2237. Recycler* recycler = GetRecycler();
  2238. SegmentBTreeRoot* tmpSegmentMap = AllocatorNewStruct(Recycler, recycler, SegmentBTreeRoot);
  2239. ForEachSegment([recycler, tmpSegmentMap](SparseArraySegmentBase * current)
  2240. {
  2241. tmpSegmentMap->Add(recycler, current);
  2242. return false;
  2243. });
  2244. // There could be OOM during building segment map. Save to array only after its successful completion.
  2245. SetSegmentMap(tmpSegmentMap);
  2246. return tmpSegmentMap;
  2247. }
  2248. void JavascriptArray::TryAddToSegmentMap(Recycler* recycler, SparseArraySegmentBase* seg)
  2249. {
  2250. SegmentBTreeRoot * savedSegmentMap = GetSegmentMap();
  2251. if (savedSegmentMap)
  2252. {
  2253. //
  2254. // We could OOM and throw when adding to segmentMap, resulting in a corrupted segmentMap on this
  2255. // array. Set segmentMap to null temporarily to protect from this. It will be restored correctly
  2256. // if adding segment succeeds.
  2257. //
  2258. ClearSegmentMap();
  2259. savedSegmentMap->Add(recycler, seg);
  2260. SetSegmentMap(savedSegmentMap);
  2261. }
  2262. }
  2263. void JavascriptArray::InvalidateLastUsedSegment()
  2264. {
  2265. this->SetLastUsedSegment(this->head);
  2266. }
  2267. DescriptorFlags JavascriptArray::GetSetter(PropertyId propertyId, Var *setterValue, PropertyValueInfo* info, ScriptContext* requestContext)
  2268. {
  2269. DescriptorFlags flags;
  2270. if (GetSetterBuiltIns(propertyId, info, &flags))
  2271. {
  2272. return flags;
  2273. }
  2274. return __super::GetSetter(propertyId, setterValue, info, requestContext);
  2275. }
  2276. DescriptorFlags JavascriptArray::GetSetter(JavascriptString* propertyNameString, Var *setterValue, PropertyValueInfo* info, ScriptContext* requestContext)
  2277. {
  2278. DescriptorFlags flags;
  2279. PropertyRecord const* propertyRecord;
  2280. this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
  2281. if (propertyRecord != nullptr && GetSetterBuiltIns(propertyRecord->GetPropertyId(), info, &flags))
  2282. {
  2283. return flags;
  2284. }
  2285. return __super::GetSetter(propertyNameString, setterValue, info, requestContext);
  2286. }
  2287. bool JavascriptArray::GetSetterBuiltIns(PropertyId propertyId, PropertyValueInfo* info, DescriptorFlags* descriptorFlags)
  2288. {
  2289. if (propertyId == PropertyIds::length)
  2290. {
  2291. PropertyValueInfo::SetNoCache(info, this);
  2292. *descriptorFlags = WritableData;
  2293. return true;
  2294. }
  2295. return false;
  2296. }
  2297. SparseArraySegmentBase * JavascriptArray::GetBeginLookupSegment(uint32 index, const bool useSegmentMap) const
  2298. {
  2299. SparseArraySegmentBase *seg = nullptr;
  2300. SparseArraySegmentBase * lastUsedSeg = this->GetLastUsedSegment();
  2301. if (lastUsedSeg != nullptr && lastUsedSeg->left <= index)
  2302. {
  2303. seg = lastUsedSeg;
  2304. if(index - lastUsedSeg->left < lastUsedSeg->size)
  2305. {
  2306. return seg;
  2307. }
  2308. }
  2309. SegmentBTreeRoot * segmentMap = GetSegmentMap();
  2310. if(!useSegmentMap || !segmentMap)
  2311. {
  2312. return seg ? seg : PointerValue(this->head);
  2313. }
  2314. if(seg)
  2315. {
  2316. // If indexes are being accessed sequentially, check the segment after the last-used segment before checking the
  2317. // segment map, as it is likely to hit
  2318. SparseArraySegmentBase *const nextSeg = seg->next;
  2319. if(nextSeg)
  2320. {
  2321. if(index < nextSeg->left)
  2322. {
  2323. return seg;
  2324. }
  2325. else if(index - nextSeg->left < nextSeg->size)
  2326. {
  2327. return nextSeg;
  2328. }
  2329. }
  2330. }
  2331. SparseArraySegmentBase *matchOrNextSeg;
  2332. segmentMap->Find(index, seg, matchOrNextSeg);
  2333. return seg ? seg : matchOrNextSeg;
  2334. }
  2335. uint32 JavascriptArray::GetNextIndex(uint32 index) const
  2336. {
  2337. if (JavascriptNativeIntArray::Is((Var)this))
  2338. {
  2339. return this->GetNextIndexHelper<int32>(index);
  2340. }
  2341. else if (JavascriptNativeFloatArray::Is((Var)this))
  2342. {
  2343. return this->GetNextIndexHelper<double>(index);
  2344. }
  2345. return this->GetNextIndexHelper<Var>(index);
  2346. }
  2347. template<typename T>
  2348. uint32 JavascriptArray::GetNextIndexHelper(uint32 index) const
  2349. {
  2350. AssertMsg(this->head, "array head should never be null");
  2351. uint candidateIndex;
  2352. if (index == JavascriptArray::InvalidIndex)
  2353. {
  2354. candidateIndex = head->left;
  2355. }
  2356. else
  2357. {
  2358. candidateIndex = index + 1;
  2359. }
  2360. SparseArraySegment<T>* current = (SparseArraySegment<T>*)this->GetBeginLookupSegment(candidateIndex);
  2361. while (current != nullptr)
  2362. {
  2363. if ((current->left <= candidateIndex) && ((candidateIndex - current->left) < current->length))
  2364. {
  2365. for (uint i = candidateIndex - current->left; i < current->length; i++)
  2366. {
  2367. if (!SparseArraySegment<T>::IsMissingItem(&current->elements[i]))
  2368. {
  2369. return i + current->left;
  2370. }
  2371. }
  2372. }
  2373. current = SparseArraySegment<T>::From(current->next);
  2374. if (current != NULL)
  2375. {
  2376. if (candidateIndex < current->left)
  2377. {
  2378. candidateIndex = current->left;
  2379. }
  2380. }
  2381. }
  2382. return JavascriptArray::InvalidIndex;
  2383. }
  2384. // If new length > length, we just reset the length
  2385. // If new length < length, we need to remove the rest of the elements and segment
  2386. void JavascriptArray::SetLength(uint32 newLength)
  2387. {
  2388. if (newLength == length)
  2389. return;
  2390. if (head == EmptySegment)
  2391. {
  2392. // Do nothing to the segment.
  2393. }
  2394. else if (newLength == 0)
  2395. {
  2396. this->ClearElements(head, 0);
  2397. head->length = 0;
  2398. head->next = nullptr;
  2399. SetHasNoMissingValues();
  2400. ClearSegmentMap();
  2401. this->InvalidateLastUsedSegment();
  2402. }
  2403. else if (newLength < length)
  2404. {
  2405. // _ _ 2 3 _ _ 6 7 _ _
  2406. // SetLength(0)
  2407. // 0 <= left -> set *prev = null
  2408. // SetLength(2)
  2409. // 2 <= left -> set *prev = null
  2410. // SetLength(3)
  2411. // 3 !<= left; 3 <= right -> truncate to length - 1
  2412. // SetLength(5)
  2413. // 5 <=
  2414. SparseArraySegmentBase* next = GetBeginLookupSegment(newLength - 1); // head, or next.left < newLength
  2415. Field(SparseArraySegmentBase*)* prev = &head;
  2416. while(next != nullptr)
  2417. {
  2418. if (newLength <= next->left)
  2419. {
  2420. ClearSegmentMap(); // truncate segments, null out segmentMap
  2421. *prev = nullptr;
  2422. break;
  2423. }
  2424. else if (newLength <= (next->left + next->length))
  2425. {
  2426. if (next->next)
  2427. {
  2428. ClearSegmentMap(); // Will truncate segments, null out segmentMap
  2429. }
  2430. uint32 newSegmentLength = newLength - next->left;
  2431. this->ClearElements(next, newSegmentLength);
  2432. next->next = nullptr;
  2433. next->length = newSegmentLength;
  2434. next->CheckLengthvsSize();
  2435. break;
  2436. }
  2437. else
  2438. {
  2439. prev = &next->next;
  2440. next = next->next;
  2441. }
  2442. }
  2443. this->InvalidateLastUsedSegment();
  2444. }
  2445. this->length = newLength;
  2446. #ifdef VALIDATE_ARRAY
  2447. ValidateArray();
  2448. #endif
  2449. }
  2450. BOOL JavascriptArray::SetLength(Var newLength)
  2451. {
  2452. ScriptContext *scriptContext;
  2453. if(TaggedInt::Is(newLength))
  2454. {
  2455. int32 lenValue = TaggedInt::ToInt32(newLength);
  2456. if (lenValue < 0)
  2457. {
  2458. scriptContext = GetScriptContext();
  2459. if (scriptContext->GetThreadContext()->RecordImplicitException())
  2460. {
  2461. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  2462. }
  2463. }
  2464. else
  2465. {
  2466. this->SetLength(lenValue);
  2467. }
  2468. return TRUE;
  2469. }
  2470. scriptContext = GetScriptContext();
  2471. uint32 uintValue = JavascriptConversion::ToUInt32(newLength, scriptContext);
  2472. double dblValue = JavascriptConversion::ToNumber(newLength, scriptContext);
  2473. if (dblValue == uintValue)
  2474. {
  2475. this->SetLength(uintValue);
  2476. }
  2477. else
  2478. {
  2479. ThreadContext* threadContext = scriptContext->GetThreadContext();
  2480. ImplicitCallFlags flags = threadContext->GetImplicitCallFlags();
  2481. if (flags != ImplicitCall_None && threadContext->IsDisableImplicitCall())
  2482. {
  2483. // We couldn't execute the implicit call(s) needed to convert the newLength to an integer.
  2484. // Do nothing and let the jitted code bail out.
  2485. return TRUE;
  2486. }
  2487. if (threadContext->RecordImplicitException())
  2488. {
  2489. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  2490. }
  2491. }
  2492. return TRUE;
  2493. }
  2494. void JavascriptArray::ClearElements(SparseArraySegmentBase *seg, uint32 newSegmentLength)
  2495. {
  2496. SparseArraySegment<Var>::ClearElements(((SparseArraySegment<Var>*)seg)->elements + newSegmentLength, seg->length - newSegmentLength);
  2497. }
  2498. void JavascriptNativeIntArray::ClearElements(SparseArraySegmentBase *seg, uint32 newSegmentLength)
  2499. {
  2500. SparseArraySegment<int32>::ClearElements(((SparseArraySegment<int32>*)seg)->elements + newSegmentLength, seg->length - newSegmentLength);
  2501. }
  2502. void JavascriptNativeFloatArray::ClearElements(SparseArraySegmentBase *seg, uint32 newSegmentLength)
  2503. {
  2504. SparseArraySegment<double>::ClearElements(((SparseArraySegment<double>*)seg)->elements + newSegmentLength, seg->length - newSegmentLength);
  2505. }
  2506. Var JavascriptArray::DirectGetItem(uint32 index)
  2507. {
  2508. SparseArraySegment<Var> *seg = (SparseArraySegment<Var>*)this->GetLastUsedSegment();
  2509. uint32 offset = index - seg->left;
  2510. if (index >= seg->left && offset < seg->length)
  2511. {
  2512. if (!SparseArraySegment<Var>::IsMissingItem(&seg->elements[offset]))
  2513. {
  2514. return seg->elements[offset];
  2515. }
  2516. }
  2517. Var element = nullptr;
  2518. if (DirectGetItemAtFull(index, &element))
  2519. {
  2520. return element;
  2521. }
  2522. return GetType()->GetLibrary()->GetUndefined();
  2523. }
  2524. Var JavascriptNativeIntArray::DirectGetItem(uint32 index)
  2525. {
  2526. #if ENABLE_COPYONACCESS_ARRAY
  2527. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  2528. #endif
  2529. SparseArraySegment<int32> *seg = (SparseArraySegment<int32>*)this->GetLastUsedSegment();
  2530. uint32 offset = index - seg->left;
  2531. if (index >= seg->left && offset < seg->length)
  2532. {
  2533. if (!SparseArraySegment<int32>::IsMissingItem(&seg->elements[offset]))
  2534. {
  2535. return JavascriptNumber::ToVar(seg->elements[offset], GetScriptContext());
  2536. }
  2537. }
  2538. Var element = nullptr;
  2539. if (DirectGetItemAtFull(index, &element))
  2540. {
  2541. return element;
  2542. }
  2543. return GetType()->GetLibrary()->GetUndefined();
  2544. }
  2545. DescriptorFlags JavascriptNativeIntArray::GetItemSetter(uint32 index, Var* setterValue, ScriptContext* requestContext)
  2546. {
  2547. #if ENABLE_COPYONACCESS_ARRAY
  2548. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  2549. #endif
  2550. int32 value = 0;
  2551. return this->DirectGetItemAt(index, &value) ? WritableData : None;
  2552. }
  2553. Var JavascriptNativeFloatArray::DirectGetItem(uint32 index)
  2554. {
  2555. SparseArraySegment<double> *seg = (SparseArraySegment<double>*)this->GetLastUsedSegment();
  2556. uint32 offset = index - seg->left;
  2557. if (index >= seg->left && offset < seg->length)
  2558. {
  2559. if (!SparseArraySegment<double>::IsMissingItem(&seg->elements[offset]))
  2560. {
  2561. return JavascriptNumber::ToVarWithCheck(seg->elements[offset], GetScriptContext());
  2562. }
  2563. }
  2564. Var element = nullptr;
  2565. if (DirectGetItemAtFull(index, &element))
  2566. {
  2567. return element;
  2568. }
  2569. return GetType()->GetLibrary()->GetUndefined();
  2570. }
  2571. Var JavascriptArray::DirectGetItem(JavascriptString *propName, ScriptContext* scriptContext)
  2572. {
  2573. PropertyRecord const * propertyRecord;
  2574. scriptContext->GetOrAddPropertyRecord(propName->GetString(), propName->GetLength(), &propertyRecord);
  2575. return JavascriptOperators::GetProperty(this, propertyRecord->GetPropertyId(), scriptContext, NULL);
  2576. }
  2577. BOOL JavascriptArray::DirectGetItemAtFull(uint32 index, Var* outVal)
  2578. {
  2579. if (this->DirectGetItemAt(index, outVal))
  2580. {
  2581. return TRUE;
  2582. }
  2583. ScriptContext* requestContext = type->GetScriptContext();
  2584. return JavascriptOperators::GetItem(this, this->GetPrototype(), index, outVal, requestContext);
  2585. }
  2586. //
  2587. // Link prev and current. If prev is NULL, make current the head segment.
  2588. //
  2589. void JavascriptArray::LinkSegmentsCommon(SparseArraySegmentBase* prev, SparseArraySegmentBase* current)
  2590. {
  2591. if (prev)
  2592. {
  2593. prev->next = current;
  2594. }
  2595. else
  2596. {
  2597. Assert(current);
  2598. head = current;
  2599. }
  2600. }
  2601. template<typename T>
  2602. BOOL JavascriptArray::DirectDeleteItemAt(uint32 itemIndex)
  2603. {
  2604. if (itemIndex >= length)
  2605. {
  2606. return true;
  2607. }
  2608. SparseArraySegment<T>* next = (SparseArraySegment<T>*)GetBeginLookupSegment(itemIndex);
  2609. while(next != nullptr && next->left <= itemIndex)
  2610. {
  2611. uint32 limit = next->left + next->length;
  2612. if (itemIndex < limit)
  2613. {
  2614. next->SetElement(GetRecycler(), itemIndex, SparseArraySegment<T>::GetMissingItem());
  2615. if(itemIndex - next->left == next->length - 1)
  2616. {
  2617. --next->length;
  2618. next->CheckLengthvsSize();
  2619. }
  2620. else if(next == head)
  2621. {
  2622. SetHasNoMissingValues(false);
  2623. }
  2624. break;
  2625. }
  2626. next = SparseArraySegment<T>::From(next->next);
  2627. }
  2628. #ifdef VALIDATE_ARRAY
  2629. ValidateArray();
  2630. #endif
  2631. return true;
  2632. }
  2633. template <> Var JavascriptArray::ConvertToIndex(BigIndex idxDest, ScriptContext* scriptContext)
  2634. {
  2635. return idxDest.ToNumber(scriptContext);
  2636. }
  2637. template <> uint32 JavascriptArray::ConvertToIndex(BigIndex idxDest, ScriptContext* scriptContext)
  2638. {
  2639. // Note this is only for setting Array length which is a uint32
  2640. return idxDest.IsSmallIndex() ? idxDest.GetSmallIndex() : UINT_MAX;
  2641. }
  2642. template <> Var JavascriptArray::ConvertToIndex(uint32 idxDest, ScriptContext* scriptContext)
  2643. {
  2644. return JavascriptNumber::ToVar(idxDest, scriptContext);
  2645. }
  2646. void JavascriptArray::ThrowErrorOnFailure(BOOL succeeded, ScriptContext* scriptContext, uint32 index)
  2647. {
  2648. if (!succeeded)
  2649. {
  2650. JavascriptError::ThrowTypeError(scriptContext, JSERR_CantRedefineProp, JavascriptConversion::ToString(JavascriptNumber::ToVar(index, scriptContext), scriptContext)->GetSz());
  2651. }
  2652. }
  2653. void JavascriptArray::ThrowErrorOnFailure(BOOL succeeded, ScriptContext* scriptContext, BigIndex index)
  2654. {
  2655. if (!succeeded)
  2656. {
  2657. uint64 i = (uint64)(index.IsSmallIndex() ? index.GetSmallIndex() : index.GetBigIndex());
  2658. JavascriptError::ThrowTypeError(scriptContext, JSERR_CantRedefineProp, JavascriptConversion::ToString(JavascriptNumber::ToVar(i, scriptContext), scriptContext)->GetSz());
  2659. }
  2660. }
  2661. BOOL JavascriptArray::SetArrayLikeObjects(RecyclableObject* pDestObj, uint32 idxDest, Var aItem)
  2662. {
  2663. return pDestObj->SetItem(idxDest, aItem, Js::PropertyOperation_ThrowIfNotExtensible);
  2664. }
  2665. uint64 JavascriptArray::OP_GetLength(Var obj, ScriptContext *scriptContext)
  2666. {
  2667. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  2668. {
  2669. // Casting to uint64 is okay as ToLength will always be >= 0.
  2670. return (uint64)JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
  2671. }
  2672. else
  2673. {
  2674. return (uint64)JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
  2675. }
  2676. }
  2677. template<typename T>
  2678. void JavascriptArray::TryGetArrayAndLength(Var arg,
  2679. ScriptContext *scriptContext,
  2680. PCWSTR methodName,
  2681. __out JavascriptArray** array,
  2682. __out RecyclableObject** obj,
  2683. __out T * length)
  2684. {
  2685. Assert(array != nullptr);
  2686. Assert(obj != nullptr);
  2687. Assert(length != nullptr);
  2688. if (JavascriptArray::Is(arg) && !JavascriptArray::FromVar(arg)->IsCrossSiteObject())
  2689. {
  2690. #if ENABLE_COPYONACCESS_ARRAY
  2691. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(arg);
  2692. #endif
  2693. *array = JavascriptArray::FromVar(arg);
  2694. *obj = *array;
  2695. *length = (*array)->length;
  2696. }
  2697. else
  2698. {
  2699. if (!JavascriptConversion::ToObject(arg, scriptContext, obj))
  2700. {
  2701. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, methodName);
  2702. }
  2703. *length = OP_GetLength(*obj, scriptContext);
  2704. *array = nullptr;
  2705. }
  2706. }
  2707. BOOL JavascriptArray::SetArrayLikeObjects(RecyclableObject* pDestObj, BigIndex idxDest, Var aItem)
  2708. {
  2709. ScriptContext* scriptContext = pDestObj->GetScriptContext();
  2710. if (idxDest.IsSmallIndex())
  2711. {
  2712. return pDestObj->SetItem(idxDest.GetSmallIndex(), aItem, Js::PropertyOperation_ThrowIfNotExtensible);
  2713. }
  2714. PropertyRecord const * propertyRecord;
  2715. JavascriptOperators::GetPropertyIdForInt(idxDest.GetBigIndex(), scriptContext, &propertyRecord);
  2716. return pDestObj->SetProperty(propertyRecord->GetPropertyId(), aItem, PropertyOperation_ThrowIfNotExtensible, nullptr);
  2717. }
  2718. template<typename T>
  2719. void JavascriptArray::ConcatArgs(RecyclableObject* pDestObj, TypeId* remoteTypeIds,
  2720. Js::Arguments& args, ScriptContext* scriptContext, uint start, BigIndex startIdxDest,
  2721. BOOL FirstPromotedItemIsSpreadable, BigIndex FirstPromotedItemLength, bool spreadableCheckedAndTrue)
  2722. {
  2723. // This never gets called.
  2724. Throw::InternalError();
  2725. }
  2726. //
  2727. // Helper for EntryConcat. Concat args or elements of arg arrays into dest array.
  2728. //
  2729. template<typename T>
  2730. void JavascriptArray::ConcatArgs(RecyclableObject* pDestObj, TypeId* remoteTypeIds,
  2731. Js::Arguments& args, ScriptContext* scriptContext, uint start, uint startIdxDest,
  2732. BOOL firstPromotedItemIsSpreadable, BigIndex firstPromotedItemLength, bool spreadableCheckedAndTrue)
  2733. {
  2734. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  2735. JavascriptArray* pDestArray = nullptr;
  2736. if (JavascriptArray::Is(pDestObj))
  2737. {
  2738. pDestArray = JavascriptArray::FromVar(pDestObj);
  2739. }
  2740. T idxDest = startIdxDest;
  2741. for (uint idxArg = start; idxArg < args.Info.Count; idxArg++)
  2742. {
  2743. Var aItem = args[idxArg];
  2744. bool spreadable = spreadableCheckedAndTrue;
  2745. if (!spreadable && scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled())
  2746. {
  2747. // firstPromotedItemIsSpreadable is ONLY used to resume after a type promotion from uint32 to uint64
  2748. // we do this because calls to IsConcatSpreadable are observable (a big deal for proxies) and we don't
  2749. // want to do the work a second time as soon as we record the length we clear the flag.
  2750. JS_REENTRANT(jsReentLock, spreadable = firstPromotedItemIsSpreadable || JavascriptOperators::IsConcatSpreadable(aItem));
  2751. if (!spreadable)
  2752. {
  2753. JS_REENTRANT(jsReentLock, JavascriptArray::SetConcatItem<T>(aItem, idxArg, pDestArray, pDestObj, idxDest, scriptContext));
  2754. ++idxDest;
  2755. continue;
  2756. }
  2757. }
  2758. else
  2759. {
  2760. spreadableCheckedAndTrue = false; // if it was `true`, reset after the first use
  2761. }
  2762. if (pDestArray && JavascriptArray::IsDirectAccessArray(aItem) && JavascriptArray::IsDirectAccessArray(pDestArray)
  2763. && BigIndex(idxDest + JavascriptArray::FromVar(aItem)->length).IsSmallIndex() && !JavascriptArray::FromVar(aItem)->IsFillFromPrototypes()) // Fast path
  2764. {
  2765. if (JavascriptNativeIntArray::Is(aItem))
  2766. {
  2767. JavascriptNativeIntArray *pItemArray = JavascriptNativeIntArray::FromVar(aItem);
  2768. JS_REENTRANT(jsReentLock, CopyNativeIntArrayElementsToVar(pDestArray, BigIndex(idxDest).GetSmallIndex(), pItemArray));
  2769. idxDest = idxDest + pItemArray->length;
  2770. }
  2771. else if (JavascriptNativeFloatArray::Is(aItem))
  2772. {
  2773. JavascriptNativeFloatArray *pItemArray = JavascriptNativeFloatArray::FromVar(aItem);
  2774. JS_REENTRANT(jsReentLock, CopyNativeFloatArrayElementsToVar(pDestArray, BigIndex(idxDest).GetSmallIndex(), pItemArray));
  2775. idxDest = idxDest + pItemArray->length;
  2776. }
  2777. else
  2778. {
  2779. JavascriptArray* pItemArray = JavascriptArray::FromVar(aItem);
  2780. JS_REENTRANT(jsReentLock, CopyArrayElements(pDestArray, BigIndex(idxDest).GetSmallIndex(), pItemArray));
  2781. idxDest = idxDest + pItemArray->length;
  2782. }
  2783. }
  2784. else
  2785. {
  2786. // Flatten if other array or remote array (marked with TypeIds_Array)
  2787. if (DynamicObject::IsAnyArray(aItem) || remoteTypeIds[idxArg] == TypeIds_Array || spreadable)
  2788. {
  2789. //CONSIDER: enumerating remote array instead of walking all indices
  2790. BigIndex length;
  2791. if (firstPromotedItemIsSpreadable)
  2792. {
  2793. firstPromotedItemIsSpreadable = false;
  2794. length = firstPromotedItemLength;
  2795. }
  2796. else
  2797. {
  2798. JS_REENTRANT(jsReentLock, length = OP_GetLength(aItem, scriptContext));
  2799. }
  2800. if (PromoteToBigIndex(length,idxDest))
  2801. {
  2802. // This is a special case for spreadable objects. We do not pre-calculate the length
  2803. // in EntryConcat like we do with Arrays because a getProperty on an object Length
  2804. // is observable. The result is we have to check for overflows separately for
  2805. // spreadable objects and promote to a bigger index type when we find them.
  2806. ConcatArgs<BigIndex>(pDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest, /*firstPromotedItemIsSpreadable*/true, length);
  2807. return;
  2808. }
  2809. if (length + idxDest > FiftyThirdPowerOfTwoMinusOne) // 2^53-1: from ECMA 22.1.3.1 Array.prototype.concat(...arguments)
  2810. {
  2811. JavascriptError::ThrowTypeError(scriptContext, JSERR_IllegalArraySizeAndLength);
  2812. }
  2813. RecyclableObject* itemObject = RecyclableObject::FromVar(aItem);
  2814. Var subItem;
  2815. uint32 lengthToUin32Max = length.IsSmallIndex() ? length.GetSmallIndex() : MaxArrayLength;
  2816. for (uint32 idxSubItem = 0u; idxSubItem < lengthToUin32Max; ++idxSubItem)
  2817. {
  2818. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(itemObject, idxSubItem));
  2819. if (hasItem)
  2820. {
  2821. JS_REENTRANT(jsReentLock, subItem = JavascriptOperators::GetItem(itemObject, idxSubItem, scriptContext));
  2822. if (pDestArray)
  2823. {
  2824. pDestArray->GenericDirectSetItemAt(idxDest, subItem);
  2825. }
  2826. else
  2827. {
  2828. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(SetArrayLikeObjects(pDestObj, idxDest, subItem), scriptContext, idxDest));
  2829. }
  2830. }
  2831. ++idxDest;
  2832. }
  2833. for (BigIndex idxSubItem = MaxArrayLength; idxSubItem < length; ++idxSubItem)
  2834. {
  2835. PropertyRecord const * propertyRecord;
  2836. JavascriptOperators::GetPropertyIdForInt(idxSubItem.GetBigIndex(), scriptContext, &propertyRecord);
  2837. JS_REENTRANT(jsReentLock, BOOL hasProp = JavascriptOperators::HasProperty(itemObject, propertyRecord->GetPropertyId()));
  2838. if (hasProp)
  2839. {
  2840. JS_REENTRANT(jsReentLock, subItem = JavascriptOperators::GetProperty(itemObject, propertyRecord->GetPropertyId(), scriptContext));
  2841. if (pDestArray)
  2842. {
  2843. pDestArray->GenericDirectSetItemAt(idxDest, subItem);
  2844. }
  2845. else
  2846. {
  2847. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(SetArrayLikeObjects(pDestObj, idxDest, subItem), scriptContext, idxSubItem));
  2848. }
  2849. }
  2850. ++idxDest;
  2851. }
  2852. }
  2853. else // concat 1 item
  2854. {
  2855. JS_REENTRANT(jsReentLock, JavascriptArray::SetConcatItem<T>(aItem, idxArg, pDestArray, pDestObj, idxDest, scriptContext));
  2856. ++idxDest;
  2857. }
  2858. }
  2859. }
  2860. if (!pDestArray)
  2861. {
  2862. JS_REENTRANT(jsReentLock, pDestObj->SetProperty(PropertyIds::length, ConvertToIndex<T, Var>(idxDest, scriptContext), Js::PropertyOperation_None, nullptr));
  2863. }
  2864. else if (pDestArray->GetLength() != ConvertToIndex<T, uint32>(idxDest, scriptContext))
  2865. {
  2866. pDestArray->SetLength(ConvertToIndex<T, uint32>(idxDest, scriptContext));
  2867. }
  2868. }
  2869. bool JavascriptArray::PromoteToBigIndex(BigIndex lhs, BigIndex rhs)
  2870. {
  2871. return false; // already a big index
  2872. }
  2873. bool JavascriptArray::PromoteToBigIndex(BigIndex lhs, uint32 rhs)
  2874. {
  2875. ::Math::RecordOverflowPolicy destLengthOverflow;
  2876. if (lhs.IsSmallIndex())
  2877. {
  2878. UInt32Math::Add(lhs.GetSmallIndex(), rhs, destLengthOverflow);
  2879. return destLengthOverflow.HasOverflowed();
  2880. }
  2881. return true;
  2882. }
  2883. JavascriptArray* JavascriptArray::ConcatIntArgs(JavascriptNativeIntArray* pDestArray, TypeId *remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext)
  2884. {
  2885. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  2886. uint idxDest = 0u;
  2887. for (uint idxArg = 0; idxArg < args.Info.Count; idxArg++)
  2888. {
  2889. Var aItem = args[idxArg];
  2890. bool spreadableCheckedAndTrue = false;
  2891. if (scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled())
  2892. {
  2893. JS_REENTRANT(jsReentLock, spreadableCheckedAndTrue = !scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled() || JavascriptOperators::IsConcatSpreadable(aItem));
  2894. if (!JavascriptNativeIntArray::Is(pDestArray))
  2895. {
  2896. ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest, spreadableCheckedAndTrue);
  2897. return pDestArray;
  2898. }
  2899. if(!spreadableCheckedAndTrue)
  2900. {
  2901. JS_REENTRANT(jsReentLock, pDestArray->SetItem(idxDest, aItem, PropertyOperation_ThrowIfNotExtensible));
  2902. idxDest = idxDest + 1;
  2903. if (!JavascriptNativeIntArray::Is(pDestArray)) // SetItem could convert pDestArray to a var array if aItem is not an integer if so fall back
  2904. {
  2905. JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest));
  2906. return pDestArray;
  2907. }
  2908. continue;
  2909. }
  2910. }
  2911. if (JavascriptNativeIntArray::Is(aItem) && !JavascriptNativeIntArray::FromVar(aItem)->IsFillFromPrototypes()) // Fast path
  2912. {
  2913. JavascriptNativeIntArray* pItemArray = JavascriptNativeIntArray::FromVar(aItem);
  2914. JS_REENTRANT(jsReentLock, bool converted = CopyNativeIntArrayElements(pDestArray, idxDest, pItemArray));
  2915. idxDest = idxDest + pItemArray->length;
  2916. if (converted)
  2917. {
  2918. // Copying the last array forced a conversion, so switch over to the var version
  2919. // to finish.
  2920. JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest));
  2921. return pDestArray;
  2922. }
  2923. }
  2924. else if (!JavascriptArray::IsAnyArray(aItem) && remoteTypeIds[idxArg] != TypeIds_Array)
  2925. {
  2926. if (TaggedInt::Is(aItem))
  2927. {
  2928. pDestArray->DirectSetItemAt(idxDest, TaggedInt::ToInt32(aItem));
  2929. }
  2930. else
  2931. {
  2932. #if DBG
  2933. int32 int32Value;
  2934. Assert(
  2935. JavascriptNumber::TryGetInt32Value(JavascriptNumber::GetValue(aItem), &int32Value) &&
  2936. !SparseArraySegment<int32>::IsMissingItem(&int32Value));
  2937. #endif
  2938. pDestArray->DirectSetItemAt(idxDest, static_cast<int32>(JavascriptNumber::GetValue(aItem)));
  2939. }
  2940. ++idxDest;
  2941. }
  2942. else
  2943. {
  2944. JavascriptArray *pVarDestArray = JavascriptNativeIntArray::ConvertToVarArray(pDestArray);
  2945. BigIndex length;
  2946. JS_REENTRANT(jsReentLock, length = OP_GetLength(aItem, scriptContext),
  2947. ConcatArgs<uint>(pVarDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest, spreadableCheckedAndTrue, length));
  2948. return pVarDestArray;
  2949. }
  2950. }
  2951. if (pDestArray->GetLength() != idxDest)
  2952. {
  2953. pDestArray->SetLength(idxDest);
  2954. }
  2955. return pDestArray;
  2956. }
  2957. JavascriptArray* JavascriptArray::ConcatFloatArgs(JavascriptNativeFloatArray* pDestArray, TypeId *remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext)
  2958. {
  2959. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  2960. uint idxDest = 0u;
  2961. for (uint idxArg = 0; idxArg < args.Info.Count; idxArg++)
  2962. {
  2963. Var aItem = args[idxArg];
  2964. bool spreadableCheckedAndTrue = false;
  2965. if (scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled())
  2966. {
  2967. JS_REENTRANT(jsReentLock, spreadableCheckedAndTrue = !scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled() || JavascriptOperators::IsConcatSpreadable(aItem));
  2968. if (!JavascriptNativeFloatArray::Is(pDestArray))
  2969. {
  2970. ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest, spreadableCheckedAndTrue);
  2971. return pDestArray;
  2972. }
  2973. if (!spreadableCheckedAndTrue)
  2974. {
  2975. JS_REENTRANT(jsReentLock, pDestArray->SetItem(idxDest, aItem, PropertyOperation_ThrowIfNotExtensible));
  2976. idxDest = idxDest + 1;
  2977. if (!JavascriptNativeFloatArray::Is(pDestArray)) // SetItem could convert pDestArray to a var array if aItem is not an integer if so fall back
  2978. {
  2979. JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest));
  2980. return pDestArray;
  2981. }
  2982. continue;
  2983. }
  2984. }
  2985. bool converted = false;
  2986. if (JavascriptArray::IsAnyArray(aItem) || remoteTypeIds[idxArg] == TypeIds_Array)
  2987. {
  2988. if (JavascriptNativeIntArray::Is(aItem) && !JavascriptArray::FromVar(aItem)->IsFillFromPrototypes()) // Fast path
  2989. {
  2990. JavascriptNativeIntArray *pIntArray = JavascriptNativeIntArray::FromVar(aItem);
  2991. JS_REENTRANT(jsReentLock, converted = CopyNativeIntArrayElementsToFloat(pDestArray, idxDest, pIntArray));
  2992. idxDest = idxDest + pIntArray->length;
  2993. }
  2994. else if (JavascriptNativeFloatArray::Is(aItem) && !JavascriptArray::FromVar(aItem)->IsFillFromPrototypes())
  2995. {
  2996. JavascriptNativeFloatArray* pItemArray = JavascriptNativeFloatArray::FromVar(aItem);
  2997. JS_REENTRANT(jsReentLock, converted = CopyNativeFloatArrayElements(pDestArray, idxDest, pItemArray));
  2998. idxDest = idxDest + pItemArray->length;
  2999. }
  3000. else
  3001. {
  3002. JavascriptArray *pVarDestArray = JavascriptNativeFloatArray::ConvertToVarArray(pDestArray);
  3003. BigIndex length;
  3004. JS_REENTRANT(jsReentLock, length = OP_GetLength(aItem, scriptContext),
  3005. ConcatArgs<uint>(pVarDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest, spreadableCheckedAndTrue, length));
  3006. return pVarDestArray;
  3007. }
  3008. if (converted)
  3009. {
  3010. // Copying the last array forced a conversion, so switch over to the var version
  3011. // to finish.
  3012. JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest));
  3013. return pDestArray;
  3014. }
  3015. }
  3016. else
  3017. {
  3018. if (TaggedInt::Is(aItem))
  3019. {
  3020. pDestArray->DirectSetItemAt(idxDest, (double)TaggedInt::ToInt32(aItem));
  3021. }
  3022. else
  3023. {
  3024. Assert(JavascriptNumber::Is(aItem));
  3025. pDestArray->DirectSetItemAt(idxDest, JavascriptNumber::GetValue(aItem));
  3026. }
  3027. ++idxDest;
  3028. }
  3029. }
  3030. if (pDestArray->GetLength() != idxDest)
  3031. {
  3032. pDestArray->SetLength(idxDest);
  3033. }
  3034. return pDestArray;
  3035. }
  3036. bool JavascriptArray::BoxConcatItem(Var aItem, uint idxArg, ScriptContext *scriptContext)
  3037. {
  3038. return idxArg == 0 && !JavascriptOperators::IsObject(aItem);
  3039. }
  3040. Var JavascriptArray::EntryConcat(RecyclableObject* function, CallInfo callInfo, ...)
  3041. {
  3042. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  3043. ARGUMENTS(args, callInfo);
  3044. ScriptContext* scriptContext = function->GetScriptContext();
  3045. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3046. Assert(!(callInfo.Flags & CallFlags_New));
  3047. if (args.Info.Count == 0)
  3048. {
  3049. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.concat"));
  3050. }
  3051. //
  3052. // Compute the destination ScriptArray size:
  3053. // - Each item, flattening only one level if a ScriptArray.
  3054. //
  3055. uint32 cDestLength = 0;
  3056. JavascriptArray * pDestArray = NULL;
  3057. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault + (args.Info.Count * sizeof(TypeId*)));
  3058. TypeId* remoteTypeIds = (TypeId*)_alloca(args.Info.Count * sizeof(TypeId*));
  3059. bool isInt = true;
  3060. bool isFloat = true;
  3061. ::Math::RecordOverflowPolicy destLengthOverflow;
  3062. for (uint idxArg = 0; idxArg < args.Info.Count; idxArg++)
  3063. {
  3064. Var aItem = args[idxArg];
  3065. #if ENABLE_COPYONACCESS_ARRAY
  3066. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(aItem);
  3067. #endif
  3068. if (DynamicObject::IsAnyArray(aItem)) // Get JavascriptArray or ES5Array length
  3069. {
  3070. JavascriptArray * pItemArray = JavascriptArray::FromAnyArray(aItem);
  3071. if (isFloat)
  3072. {
  3073. if (!JavascriptNativeIntArray::Is(pItemArray))
  3074. {
  3075. isInt = false;
  3076. if (!JavascriptNativeFloatArray::Is(pItemArray))
  3077. {
  3078. isFloat = false;
  3079. }
  3080. }
  3081. }
  3082. cDestLength = UInt32Math::Add(cDestLength, pItemArray->GetLength(), destLengthOverflow);
  3083. }
  3084. else // Get remote array or object length
  3085. {
  3086. // We already checked for types derived from JavascriptArray. These are types that should behave like array
  3087. // i.e. proxy to array and remote array.
  3088. if (JavascriptOperators::IsArray(aItem))
  3089. {
  3090. // Don't try to preserve nativeness of remote arrays. The extra complexity is probably not
  3091. // worth it.
  3092. isInt = false;
  3093. isFloat = false;
  3094. if (!JavascriptProxy::Is(aItem))
  3095. {
  3096. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  3097. {
  3098. JS_REENTRANT(jsReentLock,
  3099. int64 len = JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(aItem, scriptContext), scriptContext));
  3100. // clipping to MaxArrayLength will overflow when added to cDestLength which we catch below
  3101. cDestLength = UInt32Math::Add(cDestLength, len < MaxArrayLength ? (uint32)len : MaxArrayLength, destLengthOverflow);
  3102. }
  3103. else
  3104. {
  3105. JS_REENTRANT(jsReentLock,
  3106. uint len = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(aItem, scriptContext), scriptContext));
  3107. cDestLength = UInt32Math::Add(cDestLength, len, destLengthOverflow);
  3108. }
  3109. }
  3110. remoteTypeIds[idxArg] = TypeIds_Array; // Mark remote array, no matter remote JavascriptArray or ES5Array.
  3111. }
  3112. else
  3113. {
  3114. if (isFloat)
  3115. {
  3116. if (BoxConcatItem(aItem, idxArg, scriptContext))
  3117. {
  3118. // A primitive will be boxed, so we have to create a var array for the result.
  3119. isInt = false;
  3120. isFloat = false;
  3121. }
  3122. else if (!TaggedInt::Is(aItem))
  3123. {
  3124. if (!JavascriptNumber::Is(aItem))
  3125. {
  3126. isInt = false;
  3127. isFloat = false;
  3128. }
  3129. else if (isInt)
  3130. {
  3131. int32 int32Value;
  3132. if(!JavascriptNumber::TryGetInt32Value(JavascriptNumber::GetValue(aItem), &int32Value) ||
  3133. SparseArraySegment<int32>::IsMissingItem(&int32Value))
  3134. {
  3135. isInt = false;
  3136. }
  3137. }
  3138. }
  3139. else if(isInt)
  3140. {
  3141. int32 int32Value = TaggedInt::ToInt32(aItem);
  3142. if(SparseArraySegment<int32>::IsMissingItem(&int32Value))
  3143. {
  3144. isInt = false;
  3145. }
  3146. }
  3147. }
  3148. remoteTypeIds[idxArg] = TypeIds_Limit;
  3149. cDestLength = UInt32Math::Add(cDestLength, 1, destLengthOverflow);
  3150. }
  3151. }
  3152. }
  3153. if (destLengthOverflow.HasOverflowed())
  3154. {
  3155. cDestLength = MaxArrayLength;
  3156. isInt = false;
  3157. isFloat = false;
  3158. }
  3159. //
  3160. // Create the destination array
  3161. //
  3162. RecyclableObject* pDestObj = nullptr;
  3163. bool isArray = false;
  3164. JS_REENTRANT(jsReentLock, pDestObj = ArraySpeciesCreate(args[0], 0, scriptContext));
  3165. if (pDestObj)
  3166. {
  3167. #if ENABLE_COPYONACCESS_ARRAY
  3168. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pDestObj);
  3169. #endif
  3170. // Check the thing that species create made. If it's a native array that can't handle the source
  3171. // data, convert it. If it's a more conservative kind of array than the source data, indicate that
  3172. // so that the data will be converted on copy.
  3173. if (isInt)
  3174. {
  3175. if (JavascriptNativeIntArray::Is(pDestObj))
  3176. {
  3177. isArray = true;
  3178. }
  3179. else
  3180. {
  3181. isInt = false;
  3182. isFloat = JavascriptNativeFloatArray::Is(pDestObj);
  3183. isArray = JavascriptArray::Is(pDestObj);
  3184. }
  3185. }
  3186. else if (isFloat)
  3187. {
  3188. if (JavascriptNativeIntArray::Is(pDestObj))
  3189. {
  3190. JavascriptNativeIntArray::ToNativeFloatArray(JavascriptNativeIntArray::FromVar(pDestObj));
  3191. isArray = true;
  3192. }
  3193. else
  3194. {
  3195. isFloat = JavascriptNativeFloatArray::Is(pDestObj);
  3196. isArray = JavascriptArray::Is(pDestObj);
  3197. }
  3198. }
  3199. else
  3200. {
  3201. if (JavascriptNativeIntArray::Is(pDestObj))
  3202. {
  3203. JavascriptNativeIntArray::ToVarArray(JavascriptNativeIntArray::FromVar(pDestObj));
  3204. isArray = true;
  3205. }
  3206. else if (JavascriptNativeFloatArray::Is(pDestObj))
  3207. {
  3208. JavascriptNativeFloatArray::ToVarArray(JavascriptNativeFloatArray::FromVar(pDestObj));
  3209. isArray = true;
  3210. }
  3211. else
  3212. {
  3213. isArray = JavascriptArray::Is(pDestObj);
  3214. }
  3215. }
  3216. }
  3217. if (pDestObj == nullptr || isArray)
  3218. {
  3219. if (isInt)
  3220. {
  3221. JavascriptNativeIntArray *pIntArray = isArray ? JavascriptNativeIntArray::FromVar(pDestObj) : scriptContext->GetLibrary()->CreateNativeIntArray(cDestLength);
  3222. pIntArray->EnsureHead<int32>();
  3223. JS_REENTRANT(jsReentLock, pDestArray = ConcatIntArgs(pIntArray, remoteTypeIds, args, scriptContext));
  3224. }
  3225. else if (isFloat)
  3226. {
  3227. JavascriptNativeFloatArray *pFArray = isArray ? JavascriptNativeFloatArray::FromVar(pDestObj) : scriptContext->GetLibrary()->CreateNativeFloatArray(cDestLength);
  3228. pFArray->EnsureHead<double>();
  3229. JS_REENTRANT(jsReentLock, pDestArray = ConcatFloatArgs(pFArray, remoteTypeIds, args, scriptContext));
  3230. }
  3231. else
  3232. {
  3233. pDestArray = isArray ? JavascriptArray::FromVar(pDestObj) : scriptContext->GetLibrary()->CreateArray(cDestLength);
  3234. // if the constructor has changed then we no longer specialize for ints and floats
  3235. pDestArray->EnsureHead<Var>();
  3236. JS_REENTRANT(jsReentLock, ConcatArgsCallingHelper(pDestArray, remoteTypeIds, args, scriptContext, destLengthOverflow));
  3237. }
  3238. //
  3239. // Return the new array instance.
  3240. //
  3241. #ifdef VALIDATE_ARRAY
  3242. pDestArray->ValidateArray();
  3243. #endif
  3244. return pDestArray;
  3245. }
  3246. Assert(pDestObj);
  3247. JS_REENTRANT(jsReentLock, ConcatArgsCallingHelper(pDestObj, remoteTypeIds, args, scriptContext, destLengthOverflow));
  3248. return pDestObj;
  3249. }
  3250. void JavascriptArray::ConcatArgsCallingHelper(RecyclableObject* pDestObj, TypeId* remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext, ::Math::RecordOverflowPolicy &destLengthOverflow)
  3251. {
  3252. if (destLengthOverflow.HasOverflowed())
  3253. {
  3254. ConcatArgs<BigIndex>(pDestObj, remoteTypeIds, args, scriptContext);
  3255. }
  3256. else
  3257. {
  3258. // Use faster uint32 version if no overflow
  3259. ConcatArgs<uint32>(pDestObj, remoteTypeIds, args, scriptContext);
  3260. }
  3261. }
  3262. template<typename T>
  3263. /* static */ void JavascriptArray::SetConcatItem(Var aItem, uint idxArg, JavascriptArray* pDestArray, RecyclableObject* pDestObj, T idxDest, ScriptContext *scriptContext)
  3264. {
  3265. if (BoxConcatItem(aItem, idxArg, scriptContext))
  3266. {
  3267. // bug# 725784: ES5: not calling ToObject in Step 1 of 15.4.4.4
  3268. RecyclableObject* pObj = nullptr;
  3269. if (FALSE == JavascriptConversion::ToObject(aItem, scriptContext, &pObj))
  3270. {
  3271. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.concat"));
  3272. }
  3273. if (pDestArray)
  3274. {
  3275. pDestArray->GenericDirectSetItemAt(idxDest, pObj);
  3276. }
  3277. else
  3278. {
  3279. SetArrayLikeObjects(pDestObj, idxDest, pObj);
  3280. }
  3281. }
  3282. else
  3283. {
  3284. if (pDestArray)
  3285. {
  3286. pDestArray->GenericDirectSetItemAt(idxDest, aItem);
  3287. }
  3288. else
  3289. {
  3290. SetArrayLikeObjects(pDestObj, idxDest, aItem);
  3291. }
  3292. }
  3293. }
  3294. int64 JavascriptArray::GetFromLastIndex(Var arg, int64 length, ScriptContext *scriptContext)
  3295. {
  3296. int64 fromIndex;
  3297. if (TaggedInt::Is(arg))
  3298. {
  3299. int intValue = TaggedInt::ToInt32(arg);
  3300. if (intValue >= 0)
  3301. {
  3302. fromIndex = min<int64>(intValue, length - 1);
  3303. }
  3304. else if ((uint32)-intValue > length)
  3305. {
  3306. return length;
  3307. }
  3308. else
  3309. {
  3310. fromIndex = intValue + length;
  3311. }
  3312. }
  3313. else
  3314. {
  3315. double value = JavascriptConversion::ToInteger(arg, scriptContext);
  3316. if (value >= 0)
  3317. {
  3318. fromIndex = (int64)min(value, (double)(length - 1));
  3319. }
  3320. else if (value + length < 0)
  3321. {
  3322. return length;
  3323. }
  3324. else
  3325. {
  3326. fromIndex = (int64)(value + length);
  3327. }
  3328. }
  3329. return fromIndex;
  3330. }
  3331. // includesAlgorithm specifies to follow ES7 Array.prototype.includes semantics instead of Array.prototype.indexOf
  3332. // Differences
  3333. // 1. Returns boolean true or false value instead of the search hit index
  3334. // 2. Follows SameValueZero algorithm instead of StrictEquals
  3335. // 3. Missing values are scanned if the search value is undefined
  3336. template <bool includesAlgorithm>
  3337. Var JavascriptArray::IndexOfHelper(Arguments const & args, ScriptContext *scriptContext)
  3338. {
  3339. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3340. RecyclableObject* obj = nullptr;
  3341. JavascriptArray* pArr = nullptr;
  3342. BigIndex length;
  3343. Var trueValue = scriptContext->GetLibrary()->GetTrue();
  3344. Var falseValue = scriptContext->GetLibrary()->GetFalse();
  3345. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.indexOf"), &pArr, &obj, &length));
  3346. Var search = nullptr;
  3347. uint32 fromIndex = 0;
  3348. uint64 fromIndex64 = 0;
  3349. // The evaluation of method arguments may change the type of the array. Hence, we do that prior to the actual helper method calls.
  3350. // The if clause of the conditional statement below applies to an JavascriptArray or TypedArray instances. The rest of the conditional
  3351. // clauses apply to an ES5Array or other valid Javascript objects.
  3352. if ((pArr || TypedArrayBase::Is(obj)) && (length.IsSmallIndex() || length.IsUint32Max()))
  3353. {
  3354. uint32 len = length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex();
  3355. JS_REENTRANT(jsReentLock, BOOL gotParam = GetParamForIndexOf(len, args, search, fromIndex, scriptContext));
  3356. if (!gotParam)
  3357. {
  3358. return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
  3359. }
  3360. }
  3361. else if (length.IsSmallIndex())
  3362. {
  3363. JS_REENTRANT(jsReentLock, BOOL gotParam = GetParamForIndexOf(length.GetSmallIndex(), args, search, fromIndex, scriptContext));
  3364. if (!gotParam)
  3365. {
  3366. return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
  3367. }
  3368. }
  3369. else
  3370. {
  3371. JS_REENTRANT(jsReentLock, BOOL gotParam = GetParamForIndexOf(length.GetBigIndex(), args, search, fromIndex64, scriptContext));
  3372. if (!gotParam)
  3373. {
  3374. return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
  3375. }
  3376. }
  3377. // Side effects (such as defining a property in a ToPrimitive call) during evaluation of fromIndex argument may convert the array to an ES5 array.
  3378. if (pArr && !JavascriptArray::Is(obj))
  3379. {
  3380. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  3381. pArr = nullptr;
  3382. }
  3383. if (pArr)
  3384. {
  3385. if (length.IsSmallIndex() || length.IsUint32Max())
  3386. {
  3387. uint32 len = length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex();
  3388. JS_REENTRANT(jsReentLock, int32 index = pArr->HeadSegmentIndexOfHelper(search, fromIndex, len, includesAlgorithm, scriptContext));
  3389. // If we found the search value in the head segment, or if we determined there is no need to search other segments,
  3390. // we stop right here.
  3391. if (index != -1 || fromIndex == -1)
  3392. {
  3393. if (includesAlgorithm)
  3394. {
  3395. //Array.prototype.includes
  3396. return (index == -1) ? falseValue : trueValue;
  3397. }
  3398. else
  3399. {
  3400. //Array.prototype.indexOf
  3401. return JavascriptNumber::ToVar(index, scriptContext);
  3402. }
  3403. }
  3404. // If we really must search other segments, let's do it now. We'll have to search the slow way (dealing with holes, etc.).
  3405. switch (pArr->GetTypeId())
  3406. {
  3407. case Js::TypeIds_Array:
  3408. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(pArr, search, fromIndex, len, scriptContext));
  3409. case Js::TypeIds_NativeIntArray:
  3410. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(JavascriptNativeIntArray::FromVar(pArr), search, fromIndex, len, scriptContext));
  3411. case Js::TypeIds_NativeFloatArray:
  3412. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(JavascriptNativeFloatArray::FromVar(pArr), search, fromIndex, len, scriptContext));
  3413. default:
  3414. AssertMsg(FALSE, "invalid array typeid");
  3415. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(pArr, search, fromIndex, len, scriptContext));
  3416. }
  3417. }
  3418. }
  3419. // source object is not a JavascriptArray but source could be a TypedArray
  3420. if (TypedArrayBase::Is(obj))
  3421. {
  3422. if (length.IsSmallIndex() || length.IsUint32Max())
  3423. {
  3424. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(TypedArrayBase::FromVar(obj), search, fromIndex, length.GetSmallIndex(), scriptContext));
  3425. }
  3426. }
  3427. if (length.IsSmallIndex())
  3428. {
  3429. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(obj, search, fromIndex, length.GetSmallIndex(), scriptContext));
  3430. }
  3431. else
  3432. {
  3433. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(obj, search, fromIndex64, length.GetBigIndex(), scriptContext));
  3434. }
  3435. }
  3436. // Array.prototype.indexOf as defined in ES6.0 (final) Section 22.1.3.11
  3437. Var JavascriptArray::EntryIndexOf(RecyclableObject* function, CallInfo callInfo, ...)
  3438. {
  3439. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  3440. ARGUMENTS(args, callInfo);
  3441. ScriptContext* scriptContext = function->GetScriptContext();
  3442. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3443. Assert(!(callInfo.Flags & CallFlags_New));
  3444. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_indexOf);
  3445. JS_REENTRANT_UNLOCK(jsReentLock, Var returnValue = IndexOfHelper<false>(args, scriptContext));
  3446. //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
  3447. Assert(returnValue != scriptContext->GetLibrary()->GetTrue() && returnValue != scriptContext->GetLibrary()->GetFalse());
  3448. return returnValue;
  3449. }
  3450. Var JavascriptArray::EntryIncludes(RecyclableObject* function, CallInfo callInfo, ...)
  3451. {
  3452. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  3453. ARGUMENTS(args, callInfo);
  3454. ScriptContext* scriptContext = function->GetScriptContext();
  3455. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3456. Assert(!(callInfo.Flags & CallFlags_New));
  3457. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_includes);
  3458. JS_REENTRANT(jsReentLock, Var returnValue = IndexOfHelper<true>(args, scriptContext));
  3459. Assert(returnValue == scriptContext->GetLibrary()->GetTrue() || returnValue == scriptContext->GetLibrary()->GetFalse());
  3460. return returnValue;
  3461. }
  3462. template<typename T>
  3463. BOOL JavascriptArray::GetParamForIndexOf(T length, Arguments const& args, Var& search, T& fromIndex, ScriptContext * scriptContext)
  3464. {
  3465. if (length == 0)
  3466. {
  3467. return false;
  3468. }
  3469. if (args.Info.Count > 2)
  3470. {
  3471. fromIndex = GetFromIndex(args[2], length, scriptContext);
  3472. if (fromIndex >= length)
  3473. {
  3474. return false;
  3475. }
  3476. search = args[1];
  3477. }
  3478. else
  3479. {
  3480. fromIndex = 0;
  3481. search = args.Info.Count > 1 ? args[1] : scriptContext->GetLibrary()->GetUndefined();
  3482. }
  3483. return true;
  3484. }
  3485. template <>
  3486. BOOL JavascriptArray::TemplatedGetItem(RecyclableObject * obj, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3487. {
  3488. // Note: Sometime cross site array go down this path to get the marshalling
  3489. Assert(!VirtualTableInfo<JavascriptArray>::HasVirtualTable(obj)
  3490. && !VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(obj)
  3491. && !VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(obj));
  3492. if (checkHasItem && !JavascriptOperators::HasItem(obj, index))
  3493. {
  3494. return FALSE;
  3495. }
  3496. return JavascriptOperators::GetItem(obj, index, element, scriptContext);
  3497. }
  3498. template <>
  3499. BOOL JavascriptArray::TemplatedGetItem(RecyclableObject * obj, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3500. {
  3501. // Note: Sometime cross site array go down this path to get the marshalling
  3502. Assert(!VirtualTableInfo<JavascriptArray>::HasVirtualTable(obj)
  3503. && !VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(obj)
  3504. && !VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(obj));
  3505. PropertyRecord const * propertyRecord;
  3506. JavascriptOperators::GetPropertyIdForInt(index, scriptContext, &propertyRecord);
  3507. if (checkHasItem && !JavascriptOperators::HasProperty(obj, propertyRecord->GetPropertyId()))
  3508. {
  3509. return FALSE;
  3510. }
  3511. *element = JavascriptOperators::GetProperty(obj, propertyRecord->GetPropertyId(), scriptContext);
  3512. return *element != scriptContext->GetLibrary()->GetUndefined();
  3513. }
  3514. template <>
  3515. BOOL JavascriptArray::TemplatedGetItem(JavascriptArray *pArr, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3516. {
  3517. Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(pArr)
  3518. || VirtualTableInfo<CrossSiteObject<JavascriptArray>>::HasVirtualTable(pArr));
  3519. return pArr->JavascriptArray::DirectGetItemAtFull(index, element);
  3520. }
  3521. template <>
  3522. BOOL JavascriptArray::TemplatedGetItem(JavascriptArray *pArr, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3523. {
  3524. // This should never get called.
  3525. Assert(false);
  3526. Throw::InternalError();
  3527. }
  3528. template <>
  3529. BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeIntArray *pArr, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3530. {
  3531. Assert(VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(pArr)
  3532. || VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::HasVirtualTable(pArr));
  3533. return pArr->JavascriptNativeIntArray::DirectGetItemAtFull(index, element);
  3534. }
  3535. template <>
  3536. BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeIntArray *pArr, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3537. {
  3538. // This should never get called.
  3539. Assert(false);
  3540. Throw::InternalError();
  3541. }
  3542. template <>
  3543. BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeFloatArray *pArr, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3544. {
  3545. Assert(VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(pArr)
  3546. || VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::HasVirtualTable(pArr));
  3547. return pArr->JavascriptNativeFloatArray::DirectGetItemAtFull(index, element);
  3548. }
  3549. template <>
  3550. BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeFloatArray *pArr, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3551. {
  3552. // This should never get called.
  3553. Assert(false);
  3554. Throw::InternalError();
  3555. }
  3556. template <>
  3557. BOOL JavascriptArray::TemplatedGetItem(TypedArrayBase * typedArrayBase, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3558. {
  3559. // We need to do explicit check for items since length value may not actually match the actual TypedArray length.
  3560. // User could add a length property to a TypedArray instance which lies and returns a different value from the underlying length.
  3561. // Since this method can be called via Array.prototype.indexOf with .apply or .call passing a TypedArray as this parameter
  3562. // we don't know whether or not length == typedArrayBase->GetLength().
  3563. if (checkHasItem && !typedArrayBase->HasItem(index))
  3564. {
  3565. return false;
  3566. }
  3567. *element = typedArrayBase->DirectGetItem(index);
  3568. return true;
  3569. }
  3570. template <>
  3571. BOOL JavascriptArray::TemplatedGetItem(TypedArrayBase * typedArrayBase, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3572. {
  3573. // This should never get called.
  3574. Assert(false);
  3575. Throw::InternalError();
  3576. }
  3577. template <bool includesAlgorithm, typename T, typename P>
  3578. Var JavascriptArray::TemplatedIndexOfHelper(T * pArr, Var search, P fromIndex, P toIndex, ScriptContext * scriptContext)
  3579. {
  3580. Var element = nullptr;
  3581. bool isSearchTaggedInt = TaggedInt::Is(search);
  3582. bool doUndefinedSearch = includesAlgorithm && JavascriptOperators::GetTypeId(search) == TypeIds_Undefined;
  3583. Var trueValue = scriptContext->GetLibrary()->GetTrue();
  3584. Var falseValue = scriptContext->GetLibrary()->GetFalse();
  3585. //Consider: enumerating instead of walking all indices
  3586. for (P i = fromIndex; i < toIndex; i++)
  3587. {
  3588. if (!TryTemplatedGetItem(pArr, i, &element, scriptContext, !includesAlgorithm))
  3589. {
  3590. if (doUndefinedSearch)
  3591. {
  3592. return trueValue;
  3593. }
  3594. continue;
  3595. }
  3596. if (isSearchTaggedInt && TaggedInt::Is(element))
  3597. {
  3598. if (element == search)
  3599. {
  3600. return includesAlgorithm? trueValue : JavascriptNumber::ToVar(i, scriptContext);
  3601. }
  3602. continue;
  3603. }
  3604. if (includesAlgorithm)
  3605. {
  3606. //Array.prototype.includes
  3607. if (JavascriptConversion::SameValueZero(element, search))
  3608. {
  3609. return trueValue;
  3610. }
  3611. }
  3612. else
  3613. {
  3614. //Array.prototype.indexOf
  3615. if (JavascriptOperators::StrictEqual(element, search, scriptContext))
  3616. {
  3617. return JavascriptNumber::ToVar(i, scriptContext);
  3618. }
  3619. }
  3620. }
  3621. return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
  3622. }
  3623. int32 JavascriptArray::HeadSegmentIndexOfHelper(Var search, uint32 &fromIndex, uint32 toIndex, bool includesAlgorithm, ScriptContext * scriptContext)
  3624. {
  3625. Assert(Is(GetTypeId()) && !JavascriptNativeArray::Is(GetTypeId()));
  3626. if (!HasNoMissingValues() || fromIndex >= GetHead()->length)
  3627. {
  3628. return -1;
  3629. }
  3630. bool isSearchTaggedInt = TaggedInt::Is(search);
  3631. // We need to cast head segment to SparseArraySegment<Var> to have access to GetElement (onSparseArraySegment<T>). Because there are separate overloads of this
  3632. // virtual method on JavascriptNativeIntArray and JavascriptNativeFloatArray, we know this version of this method will only be called for true JavascriptArray, and not for
  3633. // either of the derived native arrays, so the elements of each segment used here must be Vars. Hence, the cast is safe.
  3634. SparseArraySegment<Var>* head = static_cast<SparseArraySegment<Var>*>(GetHead());
  3635. uint32 toIndexTrimmed = toIndex <= head->length ? toIndex : head->length;
  3636. for (uint32 i = fromIndex; i < toIndexTrimmed; i++)
  3637. {
  3638. Var element = head->GetElement(i);
  3639. if (isSearchTaggedInt && TaggedInt::Is(element))
  3640. {
  3641. if (search == element)
  3642. {
  3643. return i;
  3644. }
  3645. }
  3646. else if (includesAlgorithm && JavascriptConversion::SameValueZero(element, search))
  3647. {
  3648. //Array.prototype.includes
  3649. return i;
  3650. }
  3651. else if (JavascriptOperators::StrictEqual(element, search, scriptContext))
  3652. {
  3653. //Array.prototype.indexOf
  3654. return i;
  3655. }
  3656. }
  3657. // Element not found in the head segment. Keep looking only if the range of indices extends past
  3658. // the head segment.
  3659. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3660. return -1;
  3661. }
  3662. template<typename T>
  3663. bool AreAllBytesEqual(T value)
  3664. {
  3665. byte* bValue = (byte*)&value;
  3666. byte firstByte = *bValue++;
  3667. for (int i = 1; i < sizeof(T); ++i)
  3668. {
  3669. if (*bValue++ != firstByte)
  3670. {
  3671. return false;
  3672. }
  3673. }
  3674. return true;
  3675. }
  3676. template<>
  3677. void JavascriptArray::CopyValueToSegmentBuferNoCheck(Field(double)* buffer, uint32 length, double value)
  3678. {
  3679. if (JavascriptNumber::IsZero(value) && !JavascriptNumber::IsNegZero(value))
  3680. {
  3681. memset(buffer, 0, sizeof(double) * length);
  3682. }
  3683. else
  3684. {
  3685. for (uint32 i = 0; i < length; i++)
  3686. {
  3687. buffer[i] = value;
  3688. }
  3689. }
  3690. }
  3691. template<>
  3692. void JavascriptArray::CopyValueToSegmentBuferNoCheck(Field(int32)* buffer, uint32 length, int32 value)
  3693. {
  3694. if (value == 0 || AreAllBytesEqual(value))
  3695. {
  3696. memset(buffer, *(byte*)&value, sizeof(int32)* length);
  3697. }
  3698. else
  3699. {
  3700. for (uint32 i = 0; i < length; i++)
  3701. {
  3702. buffer[i] = value;
  3703. }
  3704. }
  3705. }
  3706. template<>
  3707. void JavascriptArray::CopyValueToSegmentBuferNoCheck(Field(Js::Var)* buffer, uint32 length, Js::Var value)
  3708. {
  3709. for (uint32 i = 0; i < length; i++)
  3710. {
  3711. buffer[i] = value;
  3712. }
  3713. }
  3714. int32 JavascriptNativeIntArray::HeadSegmentIndexOfHelper(Var search, uint32 &fromIndex, uint32 toIndex, bool includesAlgorithm, ScriptContext * scriptContext)
  3715. {
  3716. // We proceed largely in the same manner as in JavascriptArray's version of this method (see comments there for more information),
  3717. // 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:
  3718. // 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
  3719. // the search value is some other kind of Var, we can return -1 without ever iterating over the elements.
  3720. // 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.
  3721. // Instead we can use simple C++ equality (which in case of such values is equivalent to strict equality in JavaScript).
  3722. if (!HasNoMissingValues() || fromIndex >= GetHead()->length)
  3723. {
  3724. return -1;
  3725. }
  3726. bool isSearchTaggedInt = TaggedInt::Is(search);
  3727. if (!isSearchTaggedInt && !JavascriptNumber::Is_NoTaggedIntCheck(search))
  3728. {
  3729. // The value can't be in the array, but it could be in a prototype, and we can only guarantee that
  3730. // the head segment has no gaps.
  3731. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3732. return -1;
  3733. }
  3734. int32 searchAsInt32;
  3735. if (isSearchTaggedInt)
  3736. {
  3737. searchAsInt32 = TaggedInt::ToInt32(search);
  3738. }
  3739. else if (!JavascriptNumber::TryGetInt32Value<true>(JavascriptNumber::GetValue(search), &searchAsInt32))
  3740. {
  3741. // The value can't be in the array, but it could be in a prototype, and we can only guarantee that
  3742. // the head segment has no gaps.
  3743. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3744. return -1;
  3745. }
  3746. // We need to cast head segment to SparseArraySegment<int32> to have access to GetElement (onSparseArraySegment<T>). Because there are separate overloads of this
  3747. // virtual method on JavascriptNativeIntArray and JavascriptNativeFloatArray, we know this version of this method will only be called for true JavascriptNativeIntArray, and not for
  3748. // the other two, so the elements of each segment used here must be int32's. Hence, the cast is safe.
  3749. SparseArraySegment<int32> * head = static_cast<SparseArraySegment<int32>*>(GetHead());
  3750. uint32 toIndexTrimmed = toIndex <= head->length ? toIndex : head->length;
  3751. for (uint32 i = fromIndex; i < toIndexTrimmed; i++)
  3752. {
  3753. int32 element = head->GetElement(i);
  3754. if (searchAsInt32 == element)
  3755. {
  3756. return i;
  3757. }
  3758. }
  3759. // Element not found in the head segment. Keep looking only if the range of indices extends past
  3760. // the head segment.
  3761. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3762. return -1;
  3763. }
  3764. int32 JavascriptNativeFloatArray::HeadSegmentIndexOfHelper(Var search, uint32 &fromIndex, uint32 toIndex, bool includesAlgorithm, ScriptContext * scriptContext)
  3765. {
  3766. // We proceed largely in the same manner as in JavascriptArray's version of this method (see comments there for more information),
  3767. // except when we can further optimize thanks to the knowledge that all elements in the array are doubles. This allows for two additional optimizations:
  3768. // 1. Only tagged ints or JavascriptNumbers can be strict equal to some element in the array (all doubles). Thus, if
  3769. // the search value is some other kind of Var, we can return -1 without ever iterating over the elements.
  3770. // 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.
  3771. // Instead we can use simple C++ equality (which in case of such values is equivalent to strict equality in JavaScript).
  3772. if (!HasNoMissingValues() || fromIndex >= GetHead()->length)
  3773. {
  3774. return -1;
  3775. }
  3776. bool isSearchTaggedInt = TaggedInt::Is(search);
  3777. if (!isSearchTaggedInt && !JavascriptNumber::Is_NoTaggedIntCheck(search))
  3778. {
  3779. // The value can't be in the array, but it could be in a prototype, and we can only guarantee that
  3780. // the head segment has no gaps.
  3781. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3782. return -1;
  3783. }
  3784. double searchAsDouble = isSearchTaggedInt ? TaggedInt::ToDouble(search) : JavascriptNumber::GetValue(search);
  3785. // We need to cast head segment to SparseArraySegment<double> to have access to GetElement (SparseArraySegment). We know the
  3786. // segment's elements are all Vars so the cast is safe. It would have been more convenient here if JavascriptArray
  3787. // used SparseArraySegment<Var>, instead of SparseArraySegmentBase.
  3788. SparseArraySegment<double> * head = static_cast<SparseArraySegment<double>*>(GetHead());
  3789. uint32 toIndexTrimmed = toIndex <= head->length ? toIndex : head->length;
  3790. bool matchNaN = includesAlgorithm && JavascriptNumber::IsNan(searchAsDouble);
  3791. for (uint32 i = fromIndex; i < toIndexTrimmed; i++)
  3792. {
  3793. double element = head->GetElement(i);
  3794. if (element == searchAsDouble)
  3795. {
  3796. return i;
  3797. }
  3798. //NaN != NaN we expect to match for NaN in Array.prototype.includes algorithm
  3799. if (matchNaN && JavascriptNumber::IsNan(element))
  3800. {
  3801. return i;
  3802. }
  3803. }
  3804. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3805. return -1;
  3806. }
  3807. Var JavascriptArray::EntryJoin(RecyclableObject* function, CallInfo callInfo, ...)
  3808. {
  3809. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  3810. ARGUMENTS(args, callInfo);
  3811. ScriptContext* scriptContext = function->GetScriptContext();
  3812. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3813. Assert(!(callInfo.Flags & CallFlags_New));
  3814. if (args.Info.Count == 0)
  3815. {
  3816. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.join"));
  3817. }
  3818. JavascriptString* separator;
  3819. if (args.Info.Count >= 2)
  3820. {
  3821. TypeId typeId = JavascriptOperators::GetTypeId(args[1]);
  3822. //ES5 15.4.4.5 If separator is undefined, let separator be the single-character String ",".
  3823. if (TypeIds_Undefined != typeId)
  3824. {
  3825. JS_REENTRANT(jsReentLock, separator = JavascriptConversion::ToString(args[1], scriptContext));
  3826. }
  3827. else
  3828. {
  3829. separator = scriptContext->GetLibrary()->GetCommaDisplayString();
  3830. }
  3831. }
  3832. else
  3833. {
  3834. separator = scriptContext->GetLibrary()->GetCommaDisplayString();
  3835. }
  3836. JS_REENTRANT_UNLOCK(jsReentLock, return JoinHelper(args[0], separator, scriptContext));
  3837. }
  3838. JavascriptString* JavascriptArray::JoinToString(Var value, ScriptContext* scriptContext)
  3839. {
  3840. TypeId typeId = JavascriptOperators::GetTypeId(value);
  3841. if (typeId == TypeIds_Null || typeId == TypeIds_Undefined)
  3842. {
  3843. return scriptContext->GetLibrary()->GetEmptyString();
  3844. }
  3845. else
  3846. {
  3847. return JavascriptConversion::ToString(value, scriptContext);
  3848. }
  3849. }
  3850. JavascriptString* JavascriptArray::JoinHelper(Var thisArg, JavascriptString* separator, ScriptContext* scriptContext)
  3851. {
  3852. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3853. bool isArray = JavascriptArray::Is(thisArg) && (scriptContext == JavascriptArray::FromVar(thisArg)->GetScriptContext());
  3854. bool isProxy = JavascriptProxy::Is(thisArg) && (scriptContext == JavascriptProxy::FromVar(thisArg)->GetScriptContext());
  3855. Var target = NULL;
  3856. bool isTargetObjectPushed = false;
  3857. // if we are visiting a proxy object, track that we have visited the target object as well so the next time w
  3858. // call the join helper for the target of this proxy, we will return above.
  3859. if (isProxy)
  3860. {
  3861. JavascriptProxy* proxy = JavascriptProxy::FromVar(thisArg);
  3862. Assert(proxy);
  3863. target = proxy->GetTarget();
  3864. if (target != nullptr)
  3865. {
  3866. // If we end up joining same array, instead of going in infinite loop, return the empty string
  3867. if (scriptContext->CheckObject(target))
  3868. {
  3869. return scriptContext->GetLibrary()->GetEmptyString();
  3870. }
  3871. else
  3872. {
  3873. scriptContext->PushObject(target);
  3874. isTargetObjectPushed = true;
  3875. }
  3876. }
  3877. }
  3878. // If we end up joining same array, instead of going in infinite loop, return the empty string
  3879. else if (scriptContext->CheckObject(thisArg))
  3880. {
  3881. return scriptContext->GetLibrary()->GetEmptyString();
  3882. }
  3883. if (!isTargetObjectPushed)
  3884. {
  3885. scriptContext->PushObject(thisArg);
  3886. }
  3887. JavascriptString* res = nullptr;
  3888. TryFinally([&]()
  3889. {
  3890. if (isArray)
  3891. {
  3892. #if ENABLE_COPYONACCESS_ARRAY
  3893. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray(thisArg);
  3894. #endif
  3895. JavascriptArray * arr = JavascriptArray::FromVar(thisArg);
  3896. switch (arr->GetTypeId())
  3897. {
  3898. case Js::TypeIds_Array:
  3899. JS_REENTRANT(jsReentLock, res = JoinArrayHelper(arr, separator, scriptContext));
  3900. break;
  3901. case Js::TypeIds_NativeIntArray:
  3902. JS_REENTRANT(jsReentLock, res = JoinArrayHelper(JavascriptNativeIntArray::FromVar(arr), separator, scriptContext));
  3903. break;
  3904. case Js::TypeIds_NativeFloatArray:
  3905. JS_REENTRANT(jsReentLock, res = JoinArrayHelper(JavascriptNativeFloatArray::FromVar(arr), separator, scriptContext));
  3906. break;
  3907. }
  3908. }
  3909. else if (RecyclableObject::Is(thisArg))
  3910. {
  3911. JS_REENTRANT(jsReentLock, res = JoinOtherHelper(RecyclableObject::FromVar(thisArg), separator, scriptContext));
  3912. }
  3913. else
  3914. {
  3915. JS_REENTRANT(jsReentLock, res = JoinOtherHelper(scriptContext->GetLibrary()->CreateNumberObject(thisArg), separator, scriptContext));
  3916. }
  3917. },
  3918. [&](bool/*hasException*/)
  3919. {
  3920. Var top = scriptContext->PopObject();
  3921. if (isProxy)
  3922. {
  3923. AssertMsg(top == target, "Unmatched operation stack");
  3924. }
  3925. else
  3926. {
  3927. AssertMsg(top == thisArg, "Unmatched operation stack");
  3928. }
  3929. });
  3930. if (res == nullptr)
  3931. {
  3932. res = scriptContext->GetLibrary()->GetEmptyString();
  3933. }
  3934. return res;
  3935. }
  3936. static const charcount_t Join_MaxEstimatedAppendCount = static_cast<charcount_t>((64 << 20) / sizeof(void *)); // 64 MB worth of pointers
  3937. template <typename T>
  3938. JavascriptString* JavascriptArray::JoinArrayHelper(T * arr, JavascriptString* separator, ScriptContext* scriptContext)
  3939. {
  3940. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3941. Assert(VirtualTableInfo<T>::HasVirtualTable(arr) || VirtualTableInfo<CrossSiteObject<T>>::HasVirtualTable(arr));
  3942. const uint32 arrLength = arr->length;
  3943. switch(arrLength)
  3944. {
  3945. default:
  3946. {
  3947. CaseDefault:
  3948. bool hasSeparator = (separator->GetLength() != 0);
  3949. const charcount_t estimatedAppendCount =
  3950. min(
  3951. Join_MaxEstimatedAppendCount,
  3952. static_cast<charcount_t>(arrLength + (hasSeparator ? arrLength - 1 : 0)));
  3953. CompoundString *const cs =
  3954. CompoundString::NewWithPointerCapacity(estimatedAppendCount, scriptContext->GetLibrary());
  3955. Var item = nullptr;
  3956. BOOL gotItem;
  3957. JS_REENTRANT(jsReentLock, gotItem = TemplatedGetItem(arr, 0u, &item, scriptContext));
  3958. if (gotItem)
  3959. {
  3960. JS_REENTRANT(jsReentLock, cs->Append(JavascriptArray::JoinToString(item, scriptContext)));
  3961. }
  3962. for (uint32 i = 1; i < arrLength; i++)
  3963. {
  3964. if (hasSeparator)
  3965. {
  3966. cs->Append(separator);
  3967. }
  3968. JS_REENTRANT(jsReentLock, gotItem = TryTemplatedGetItem(arr, i, &item, scriptContext));
  3969. if (gotItem)
  3970. {
  3971. JS_REENTRANT(jsReentLock, cs->Append(JavascriptArray::JoinToString(item, scriptContext)));
  3972. }
  3973. }
  3974. return cs;
  3975. }
  3976. case 2:
  3977. {
  3978. bool hasSeparator = (separator->GetLength() != 0);
  3979. BOOL gotItem;
  3980. if(hasSeparator)
  3981. {
  3982. goto CaseDefault;
  3983. }
  3984. JavascriptString *res = nullptr;
  3985. Var item = nullptr;
  3986. JS_REENTRANT(jsReentLock, gotItem = TemplatedGetItem(arr, 0u, &item, scriptContext));
  3987. if (gotItem)
  3988. {
  3989. JS_REENTRANT(jsReentLock, res = JavascriptArray::JoinToString(item, scriptContext));
  3990. }
  3991. JS_REENTRANT(jsReentLock, gotItem = TryTemplatedGetItem(arr, 1u, &item, scriptContext));
  3992. if (gotItem)
  3993. {
  3994. JS_REENTRANT(jsReentLock, JavascriptString *const itemString = JavascriptArray::JoinToString(item, scriptContext));
  3995. return res ? ConcatString::New(res, itemString) : itemString;
  3996. }
  3997. if(res)
  3998. {
  3999. return res;
  4000. }
  4001. goto Case0;
  4002. }
  4003. case 1:
  4004. {
  4005. Var item = nullptr;
  4006. BOOL gotItem;
  4007. JS_REENTRANT(jsReentLock, gotItem = TemplatedGetItem(arr, 0u, &item, scriptContext));
  4008. if (gotItem)
  4009. {
  4010. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::JoinToString(item, scriptContext));
  4011. }
  4012. // fall through
  4013. }
  4014. case 0:
  4015. Case0:
  4016. return scriptContext->GetLibrary()->GetEmptyString();
  4017. }
  4018. }
  4019. JavascriptString* JavascriptArray::JoinOtherHelper(RecyclableObject* object, JavascriptString* separator, ScriptContext* scriptContext)
  4020. {
  4021. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4022. // In ES6-mode, we always load the length property from the object instead of using the internal slot.
  4023. // Even for arrays, this is now observable via proxies.
  4024. // If source object is not an array, we fall back to this behavior anyway.
  4025. JS_REENTRANT(jsReentLock,
  4026. int64 cSrcLength = (int64)OP_GetLength(object, scriptContext));
  4027. switch (cSrcLength)
  4028. {
  4029. default:
  4030. {
  4031. CaseDefault:
  4032. bool hasSeparator = (separator->GetLength() != 0);
  4033. BOOL gotItem;
  4034. const charcount_t estimatedAppendCount =
  4035. min(
  4036. Join_MaxEstimatedAppendCount,
  4037. static_cast<charcount_t>(cSrcLength + (hasSeparator ? cSrcLength - 1 : 0)));
  4038. CompoundString *const cs =
  4039. CompoundString::NewWithPointerCapacity(estimatedAppendCount, scriptContext->GetLibrary());
  4040. Var value = nullptr;
  4041. JS_REENTRANT(jsReentLock, gotItem = JavascriptOperators::GetItem(object, 0u, &value, scriptContext));
  4042. if (gotItem)
  4043. {
  4044. JS_REENTRANT(jsReentLock, cs->Append(JavascriptArray::JoinToString(value, scriptContext)));
  4045. }
  4046. for (uint32 i = 1; i < cSrcLength; i++)
  4047. {
  4048. if (hasSeparator)
  4049. {
  4050. cs->Append(separator);
  4051. }
  4052. JS_REENTRANT(jsReentLock, gotItem = JavascriptOperators::GetItem(object, i, &value, scriptContext));
  4053. if (gotItem)
  4054. {
  4055. JS_REENTRANT(jsReentLock, cs->Append(JavascriptArray::JoinToString(value, scriptContext)));
  4056. }
  4057. }
  4058. return cs;
  4059. }
  4060. case 2:
  4061. {
  4062. bool hasSeparator = (separator->GetLength() != 0);
  4063. BOOL gotItem;
  4064. if(hasSeparator)
  4065. {
  4066. goto CaseDefault;
  4067. }
  4068. JavascriptString *res = nullptr;
  4069. Var value = nullptr;
  4070. JS_REENTRANT(jsReentLock, gotItem = JavascriptOperators::GetItem(object, 0u, &value, scriptContext));
  4071. if (gotItem)
  4072. {
  4073. JS_REENTRANT(jsReentLock, res = JavascriptArray::JoinToString(value, scriptContext));
  4074. }
  4075. JS_REENTRANT(jsReentLock, gotItem = JavascriptOperators::GetItem(object, 1u, &value, scriptContext));
  4076. if (gotItem)
  4077. {
  4078. JS_REENTRANT(jsReentLock, JavascriptString *const valueString = JavascriptArray::JoinToString(value, scriptContext));
  4079. return res ? ConcatString::New(res, valueString) : valueString;
  4080. }
  4081. if(res)
  4082. {
  4083. return res;
  4084. }
  4085. goto Case0;
  4086. }
  4087. case 1:
  4088. {
  4089. Var value = nullptr;
  4090. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(object, 0u, &value, scriptContext));
  4091. if (gotItem)
  4092. {
  4093. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::JoinToString(value, scriptContext));
  4094. }
  4095. // fall through
  4096. }
  4097. case 0:
  4098. Case0:
  4099. return scriptContext->GetLibrary()->GetEmptyString();
  4100. }
  4101. }
  4102. Var JavascriptArray::EntryLastIndexOf(RecyclableObject* function, CallInfo callInfo, ...)
  4103. {
  4104. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  4105. ARGUMENTS(args, callInfo);
  4106. ScriptContext* scriptContext = function->GetScriptContext();
  4107. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4108. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_lastIndexOf);
  4109. Assert(!(callInfo.Flags & CallFlags_New));
  4110. int64 length;
  4111. JavascriptArray * pArr = nullptr;
  4112. RecyclableObject* obj = nullptr;
  4113. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.lastIndexOf"), &pArr, &obj, &length));
  4114. Var search = nullptr;
  4115. int64 fromIndex;
  4116. JS_REENTRANT(jsReentLock,
  4117. BOOL gotParam = GetParamForLastIndexOf(length, args, search, fromIndex, scriptContext));
  4118. if (!gotParam)
  4119. {
  4120. return TaggedInt::ToVarUnchecked(-1);
  4121. }
  4122. // Side effects (such as defining a property in a ToPrimitive call) during evaluation of fromIndex argument may convert the array to an ES5 array.
  4123. if (pArr && !JavascriptArray::Is(obj))
  4124. {
  4125. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  4126. pArr = nullptr;
  4127. }
  4128. if (pArr)
  4129. {
  4130. switch (pArr->GetTypeId())
  4131. {
  4132. case Js::TypeIds_Array:
  4133. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(pArr, search, fromIndex, scriptContext));
  4134. case Js::TypeIds_NativeIntArray:
  4135. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(JavascriptNativeIntArray::FromVar(pArr), search, fromIndex, scriptContext));
  4136. case Js::TypeIds_NativeFloatArray:
  4137. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(JavascriptNativeFloatArray::FromVar(pArr), search, fromIndex, scriptContext));
  4138. default:
  4139. AssertMsg(FALSE, "invalid array typeid");
  4140. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(pArr, search, fromIndex, scriptContext));
  4141. }
  4142. }
  4143. // source object is not a JavascriptArray but source could be a TypedArray
  4144. if (TypedArrayBase::Is(obj))
  4145. {
  4146. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(TypedArrayBase::FromVar(obj), search, fromIndex, scriptContext));
  4147. }
  4148. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(obj, search, fromIndex, scriptContext));
  4149. }
  4150. // Array.prototype.lastIndexOf as described in ES6.0 (draft 22) Section 22.1.3.14
  4151. BOOL JavascriptArray::GetParamForLastIndexOf(int64 length, Arguments const & args, Var& search, int64& fromIndex, ScriptContext * scriptContext)
  4152. {
  4153. if (length == 0)
  4154. {
  4155. return false;
  4156. }
  4157. if (args.Info.Count > 2)
  4158. {
  4159. fromIndex = GetFromLastIndex(args[2], length, scriptContext);
  4160. if (fromIndex >= length)
  4161. {
  4162. return false;
  4163. }
  4164. search = args[1];
  4165. }
  4166. else
  4167. {
  4168. search = args.Info.Count > 1 ? args[1] : scriptContext->GetLibrary()->GetUndefined();
  4169. fromIndex = length - 1;
  4170. }
  4171. return true;
  4172. }
  4173. template <typename T>
  4174. Var JavascriptArray::LastIndexOfHelper(T* pArr, Var search, int64 fromIndex, ScriptContext * scriptContext)
  4175. {
  4176. Var element = nullptr;
  4177. bool isSearchTaggedInt = TaggedInt::Is(search);
  4178. // First handle the indices > 2^32
  4179. while (fromIndex >= MaxArrayLength)
  4180. {
  4181. Var index = JavascriptNumber::ToVar(fromIndex, scriptContext);
  4182. if (JavascriptOperators::OP_HasItem(pArr, index, scriptContext))
  4183. {
  4184. element = JavascriptOperators::OP_GetElementI(pArr, index, scriptContext);
  4185. if (isSearchTaggedInt && TaggedInt::Is(element))
  4186. {
  4187. if (element == search)
  4188. {
  4189. return index;
  4190. }
  4191. fromIndex--;
  4192. continue;
  4193. }
  4194. if (JavascriptOperators::StrictEqual(element, search, scriptContext))
  4195. {
  4196. return index;
  4197. }
  4198. }
  4199. fromIndex--;
  4200. }
  4201. Assert(fromIndex < MaxArrayLength);
  4202. // fromIndex now has to be < MaxArrayLength so casting to uint32 is safe
  4203. uint32 end = static_cast<uint32>(fromIndex);
  4204. for (uint32 i = 0; i <= end; i++)
  4205. {
  4206. uint32 index = end - i;
  4207. if (!TryTemplatedGetItem(pArr, index, &element, scriptContext))
  4208. {
  4209. continue;
  4210. }
  4211. if (isSearchTaggedInt && TaggedInt::Is(element))
  4212. {
  4213. if (element == search)
  4214. {
  4215. return JavascriptNumber::ToVar(index, scriptContext);
  4216. }
  4217. continue;
  4218. }
  4219. if (JavascriptOperators::StrictEqual(element, search, scriptContext))
  4220. {
  4221. return JavascriptNumber::ToVar(index, scriptContext);
  4222. }
  4223. }
  4224. return TaggedInt::ToVarUnchecked(-1);
  4225. }
  4226. /*
  4227. * PopWithNoDst
  4228. * - For pop calls that do not return a value, we only need to decrement the length of the array.
  4229. */
  4230. void JavascriptNativeArray::PopWithNoDst(Var nativeArray)
  4231. {
  4232. Assert(JavascriptNativeArray::Is(nativeArray));
  4233. JavascriptArray * arr = JavascriptArray::FromVar(nativeArray);
  4234. // we will bailout on length 0
  4235. Assert(arr->GetLength() != 0);
  4236. uint32 index = arr->GetLength() - 1;
  4237. arr->SetLength(index);
  4238. }
  4239. /*
  4240. * JavascriptNativeIntArray::Pop
  4241. * - Returns int32 value from the array.
  4242. * - Returns missing item when the element is not available in the array object.
  4243. * - It doesn't walk up the prototype chain.
  4244. * - Length is decremented only if it pops an int32 element, in all other cases - we bail out from the jitted code.
  4245. * - This api cannot cause any implicit call and hence do not need implicit call bailout test around this api
  4246. */
  4247. int32 JavascriptNativeIntArray::Pop(ScriptContext * scriptContext, Var object)
  4248. {
  4249. Assert(JavascriptNativeIntArray::Is(object));
  4250. JavascriptNativeIntArray * arr = JavascriptNativeIntArray::FromVar(object);
  4251. Assert(arr->GetLength() != 0);
  4252. uint32 index = arr->length - 1;
  4253. int32 element = Js::JavascriptOperators::OP_GetNativeIntElementI_UInt32(object, index, scriptContext);
  4254. //If it is a missing item, then don't update the length - Pre-op Bail out will happen.
  4255. if(!SparseArraySegment<int32>::IsMissingItem(&element))
  4256. {
  4257. arr->SetLength(index);
  4258. }
  4259. return element;
  4260. }
  4261. /*
  4262. * JavascriptNativeFloatArray::Pop
  4263. * - Returns double value from the array.
  4264. * - Returns missing item when the element is not available in the array object.
  4265. * - It doesn't walk up the prototype chain.
  4266. * - Length is decremented only if it pops a double element, in all other cases - we bail out from the jitted code.
  4267. * - This api cannot cause any implicit call and hence do not need implicit call bailout test around this api
  4268. */
  4269. double JavascriptNativeFloatArray::Pop(ScriptContext * scriptContext, Var object)
  4270. {
  4271. Assert(JavascriptNativeFloatArray::Is(object));
  4272. JavascriptNativeFloatArray * arr = JavascriptNativeFloatArray::FromVar(object);
  4273. Assert(arr->GetLength() != 0);
  4274. uint32 index = arr->length - 1;
  4275. double element = Js::JavascriptOperators::OP_GetNativeFloatElementI_UInt32(object, index, scriptContext);
  4276. // If it is a missing item then don't update the length - Pre-op Bail out will happen.
  4277. if(!SparseArraySegment<double>::IsMissingItem(&element))
  4278. {
  4279. arr->SetLength(index);
  4280. }
  4281. return element;
  4282. }
  4283. /*
  4284. * JavascriptArray::Pop
  4285. * - Calls the generic Pop API, which can find elements from the prototype chain, when it is not available in the array object.
  4286. * - This API may cause implicit calls. Handles Array and non-array objects
  4287. */
  4288. Var JavascriptArray::Pop(ScriptContext * scriptContext, Var object)
  4289. {
  4290. if (JavascriptArray::Is(object))
  4291. {
  4292. return EntryPopJavascriptArray(scriptContext, JavascriptArray::FromVar(object));
  4293. }
  4294. else
  4295. {
  4296. return EntryPopNonJavascriptArray(scriptContext, object);
  4297. }
  4298. }
  4299. Var JavascriptArray::EntryPopJavascriptArray(ScriptContext * scriptContext, JavascriptArray* arr)
  4300. {
  4301. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4302. uint32 length = arr->length;
  4303. if (length == 0)
  4304. {
  4305. // If length is 0, return 'undefined'
  4306. return scriptContext->GetLibrary()->GetUndefined();
  4307. }
  4308. uint32 index = length - 1;
  4309. Var element = nullptr;
  4310. JS_REENTRANT(jsReentLock, BOOL gotItem = arr->DirectGetItemAtFull(index, &element));
  4311. if (!gotItem)
  4312. {
  4313. element = scriptContext->GetLibrary()->GetUndefined();
  4314. }
  4315. else
  4316. {
  4317. element = CrossSite::MarshalVar(scriptContext, element);
  4318. }
  4319. arr->SetLength(index); // SetLength will clear element at index
  4320. #ifdef VALIDATE_ARRAY
  4321. arr->ValidateArray();
  4322. #endif
  4323. return element;
  4324. }
  4325. Var JavascriptArray::EntryPopNonJavascriptArray(ScriptContext * scriptContext, Var object)
  4326. {
  4327. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4328. RecyclableObject* dynamicObject = nullptr;
  4329. if (FALSE == JavascriptConversion::ToObject(object, scriptContext, &dynamicObject))
  4330. {
  4331. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.pop"));
  4332. }
  4333. JS_REENTRANT(jsReentLock, BigIndex length = OP_GetLength(dynamicObject, scriptContext));
  4334. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.pop"));
  4335. if (length == 0u)
  4336. {
  4337. // Set length = 0
  4338. JS_REENTRANT(jsReentLock,
  4339. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, TaggedInt::ToVarUnchecked(0), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  4340. return scriptContext->GetLibrary()->GetUndefined();
  4341. }
  4342. BigIndex index = length;
  4343. --index;
  4344. Var element = nullptr;
  4345. if (index.IsSmallIndex())
  4346. {
  4347. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(dynamicObject, index.GetSmallIndex(), &element, scriptContext));
  4348. if (!gotItem)
  4349. {
  4350. element = scriptContext->GetLibrary()->GetUndefined();
  4351. }
  4352. JS_REENTRANT(jsReentLock,
  4353. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, index.GetSmallIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig)),
  4354. // Set the new length
  4355. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(index.GetSmallIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  4356. }
  4357. else
  4358. {
  4359. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(dynamicObject, index.GetBigIndex(), &element, scriptContext));
  4360. if (!gotItem)
  4361. {
  4362. element = scriptContext->GetLibrary()->GetUndefined();
  4363. }
  4364. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, index.GetBigIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig)),
  4365. // Set the new length
  4366. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(index.GetBigIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  4367. }
  4368. return element;
  4369. }
  4370. Var JavascriptArray::EntryPop(RecyclableObject* function, CallInfo callInfo, ...)
  4371. {
  4372. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  4373. ARGUMENTS(args, callInfo);
  4374. ScriptContext* scriptContext = function->GetScriptContext();
  4375. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4376. Assert(!(callInfo.Flags & CallFlags_New));
  4377. if (args.Info.Count == 0)
  4378. {
  4379. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.pop"));
  4380. }
  4381. if (JavascriptArray::Is(args[0]))
  4382. {
  4383. JS_REENTRANT_UNLOCK(jsReentLock, return EntryPopJavascriptArray(scriptContext, JavascriptArray::FromVar(args.Values[0])));
  4384. }
  4385. else
  4386. {
  4387. JS_REENTRANT_UNLOCK(jsReentLock, return EntryPopNonJavascriptArray(scriptContext, args.Values[0]));
  4388. }
  4389. }
  4390. /*
  4391. * JavascriptNativeIntArray::Push
  4392. * Pushes Int element in a native Int Array.
  4393. * We call the generic Push, if the array is not native Int or we have a really big array.
  4394. */
  4395. Var JavascriptNativeIntArray::Push(ScriptContext * scriptContext, Var array, int value)
  4396. {
  4397. // Handle non crossSite native int arrays here length within MaxArrayLength.
  4398. // JavascriptArray::Push will handle other cases.
  4399. if (JavascriptNativeIntArray::IsNonCrossSite(array))
  4400. {
  4401. JavascriptNativeIntArray * nativeIntArray = JavascriptNativeIntArray::FromVar(array);
  4402. Assert(!nativeIntArray->IsCrossSiteObject());
  4403. uint32 n = nativeIntArray->length;
  4404. if(n < JavascriptArray::MaxArrayLength)
  4405. {
  4406. nativeIntArray->SetItem(n, value);
  4407. n++;
  4408. AssertMsg(n == nativeIntArray->length, "Wrong update to the length of the native Int array");
  4409. return JavascriptNumber::ToVar(n, scriptContext);
  4410. }
  4411. }
  4412. return JavascriptArray::Push(scriptContext, array, JavascriptNumber::ToVar(value, scriptContext));
  4413. }
  4414. /*
  4415. * JavascriptNativeFloatArray::Push
  4416. * Pushes Float element in a native Int Array.
  4417. * We call the generic Push, if the array is not native Float or we have a really big array.
  4418. */
  4419. Var JavascriptNativeFloatArray::Push(ScriptContext * scriptContext, Var * array, double value)
  4420. {
  4421. // Handle non crossSite native int arrays here length within MaxArrayLength.
  4422. // JavascriptArray::Push will handle other cases.
  4423. if(JavascriptNativeFloatArray::IsNonCrossSite(array))
  4424. {
  4425. JavascriptNativeFloatArray * nativeFloatArray = JavascriptNativeFloatArray::FromVar(array);
  4426. Assert(!nativeFloatArray->IsCrossSiteObject());
  4427. uint32 n = nativeFloatArray->length;
  4428. if(n < JavascriptArray::MaxArrayLength)
  4429. {
  4430. nativeFloatArray->SetItem(n, value);
  4431. n++;
  4432. AssertMsg(n == nativeFloatArray->length, "Wrong update to the length of the native Float array");
  4433. return JavascriptNumber::ToVar(n, scriptContext);
  4434. }
  4435. }
  4436. return JavascriptArray::Push(scriptContext, array, JavascriptNumber::ToVarNoCheck(value, scriptContext));
  4437. }
  4438. /*
  4439. * JavascriptArray::Push
  4440. * Pushes Var element in a Var Array.
  4441. */
  4442. Var JavascriptArray::Push(ScriptContext * scriptContext, Var object, Var value)
  4443. {
  4444. Var args[2];
  4445. args[0] = object;
  4446. args[1] = value;
  4447. if (JavascriptArray::Is(object))
  4448. {
  4449. return EntryPushJavascriptArray(scriptContext, args, 2);
  4450. }
  4451. else
  4452. {
  4453. return EntryPushNonJavascriptArray(scriptContext, args, 2);
  4454. }
  4455. }
  4456. /*
  4457. * EntryPushNonJavascriptArray
  4458. * - Handles Entry push calls, when Objects are not javascript arrays
  4459. */
  4460. Var JavascriptArray::EntryPushNonJavascriptArray(ScriptContext * scriptContext, Var * args, uint argCount)
  4461. {
  4462. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4463. RecyclableObject* obj = nullptr;
  4464. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  4465. {
  4466. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.push"));
  4467. }
  4468. JS_REENTRANT_UNLOCK(jsReentLock, Var length = JavascriptOperators::OP_GetLength(obj, scriptContext));
  4469. if(JavascriptOperators::GetTypeId(length) == TypeIds_Undefined && scriptContext->GetThreadContext()->IsDisableImplicitCall() &&
  4470. scriptContext->GetThreadContext()->GetImplicitCallFlags() != Js::ImplicitCall_None)
  4471. {
  4472. return length;
  4473. }
  4474. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.push"));
  4475. BigIndex n;
  4476. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  4477. {
  4478. n = (uint64) JavascriptConversion::ToLength(length, scriptContext);
  4479. }
  4480. else
  4481. {
  4482. n = JavascriptConversion::ToUInt32(length, scriptContext);
  4483. }
  4484. // First handle "small" indices.
  4485. uint index;
  4486. for (index=1; index < argCount && n < JavascriptArray::MaxArrayLength; ++index, ++n)
  4487. {
  4488. JS_REENTRANT(jsReentLock,
  4489. BOOL setItem = JavascriptOperators::SetItem(obj, obj, n.GetSmallIndex(), args[index], scriptContext, PropertyOperation_ThrowIfNotExtensible));
  4490. if (h.IsThrowTypeError(setItem))
  4491. {
  4492. if (scriptContext->GetThreadContext()->RecordImplicitException())
  4493. {
  4494. h.ThrowTypeErrorOnFailure();
  4495. }
  4496. else
  4497. {
  4498. return nullptr;
  4499. }
  4500. }
  4501. }
  4502. // Use BigIndex if we need to push indices >= MaxArrayLength
  4503. if (index < argCount)
  4504. {
  4505. BigIndex big = n;
  4506. for (; index < argCount; ++index, ++big)
  4507. {
  4508. JS_REENTRANT(jsReentLock, BOOL setItem = big.SetItem(obj, args[index], PropertyOperation_ThrowIfNotExtensible));
  4509. if (h.IsThrowTypeError(setItem))
  4510. {
  4511. if(scriptContext->GetThreadContext()->RecordImplicitException())
  4512. {
  4513. h.ThrowTypeErrorOnFailure();
  4514. }
  4515. else
  4516. {
  4517. return nullptr;
  4518. }
  4519. }
  4520. }
  4521. // Set the new length; for objects it is all right for this to be >= MaxArrayLength
  4522. JS_REENTRANT(jsReentLock,
  4523. BOOL setLength = JavascriptOperators::SetProperty(obj, obj, PropertyIds::length, big.ToNumber(scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  4524. if (h.IsThrowTypeError(setLength))
  4525. {
  4526. if(scriptContext->GetThreadContext()->RecordImplicitException())
  4527. {
  4528. h.ThrowTypeErrorOnFailure();
  4529. }
  4530. else
  4531. {
  4532. return nullptr;
  4533. }
  4534. }
  4535. return big.ToNumber(scriptContext);
  4536. }
  4537. else
  4538. {
  4539. // Set the new length
  4540. Var lengthAsNUmberVar = JavascriptNumber::ToVar(n.IsSmallIndex() ? n.GetSmallIndex() : n.GetBigIndex(), scriptContext);
  4541. JS_REENTRANT(jsReentLock,
  4542. BOOL setLength = JavascriptOperators::SetProperty(obj, obj, PropertyIds::length, lengthAsNUmberVar, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  4543. if (h.IsThrowTypeError(setLength))
  4544. {
  4545. if(scriptContext->GetThreadContext()->RecordImplicitException())
  4546. {
  4547. h.ThrowTypeErrorOnFailure();
  4548. }
  4549. else
  4550. {
  4551. return nullptr;
  4552. }
  4553. }
  4554. return lengthAsNUmberVar;
  4555. }
  4556. }
  4557. /*
  4558. * JavascriptArray::EntryPushJavascriptArray
  4559. * Pushes Var element in a Var Array.
  4560. * Returns the length of the array.
  4561. */
  4562. Var JavascriptArray::EntryPushJavascriptArray(ScriptContext * scriptContext, Var * args, uint argCount)
  4563. {
  4564. JavascriptArray * arr = JavascriptArray::FromAnyArray(args[0]);
  4565. uint n = arr->length;
  4566. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.push"));
  4567. // Fast Path for one push for small indexes
  4568. if (argCount == 2 && n < JavascriptArray::MaxArrayLength)
  4569. {
  4570. // Set Item is overridden by CrossSiteObject, so no need to check for IsCrossSiteObject()
  4571. h.ThrowTypeErrorOnFailure(arr->SetItem(n, args[1], PropertyOperation_None));
  4572. return JavascriptNumber::ToVar(n + 1, scriptContext);
  4573. }
  4574. // Fast Path for multiple push for small indexes
  4575. if (JavascriptArray::MaxArrayLength - argCount + 1 > n && JavascriptArray::IsVarArray(arr) && scriptContext == arr->GetScriptContext())
  4576. {
  4577. uint index;
  4578. for (index = 1; index < argCount; ++index, ++n)
  4579. {
  4580. Assert(n != JavascriptArray::MaxArrayLength);
  4581. // Set Item is overridden by CrossSiteObject, so no need to check for IsCrossSiteObject()
  4582. arr->JavascriptArray::DirectSetItemAt(n, args[index]);
  4583. }
  4584. return JavascriptNumber::ToVar(n, scriptContext);
  4585. }
  4586. return EntryPushJavascriptArrayNoFastPath(scriptContext, args, argCount);
  4587. }
  4588. Var JavascriptArray::EntryPushJavascriptArrayNoFastPath(ScriptContext * scriptContext, Var * args, uint argCount)
  4589. {
  4590. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4591. JavascriptArray * arr = JavascriptArray::FromAnyArray(args[0]);
  4592. uint n = arr->length;
  4593. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.push"));
  4594. // First handle "small" indices.
  4595. uint index;
  4596. for (index = 1; index < argCount && n < JavascriptArray::MaxArrayLength; ++index, ++n)
  4597. {
  4598. // Set Item is overridden by CrossSiteObject, so no need to check for IsCrossSiteObject()
  4599. h.ThrowTypeErrorOnFailure(arr->SetItem(n, args[index], PropertyOperation_None));
  4600. }
  4601. // Use BigIndex if we need to push indices >= MaxArrayLength
  4602. if (index < argCount)
  4603. {
  4604. // Not supporting native array with BigIndex.
  4605. arr = EnsureNonNativeArray(arr);
  4606. Assert(n == JavascriptArray::MaxArrayLength);
  4607. for (BigIndex big = n; index < argCount; ++index, ++big)
  4608. {
  4609. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(big.SetItem(arr, args[index])));
  4610. }
  4611. #ifdef VALIDATE_ARRAY
  4612. arr->ValidateArray();
  4613. #endif
  4614. // This is where we should set the length, but for arrays it cannot be >= MaxArrayLength
  4615. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  4616. }
  4617. #ifdef VALIDATE_ARRAY
  4618. arr->ValidateArray();
  4619. #endif
  4620. return JavascriptNumber::ToVar(n, scriptContext);
  4621. }
  4622. /*
  4623. * JavascriptArray::EntryPush
  4624. * Handles Push calls(Script Function)
  4625. */
  4626. Var JavascriptArray::EntryPush(RecyclableObject* function, CallInfo callInfo, ...)
  4627. {
  4628. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  4629. ARGUMENTS(args, callInfo);
  4630. ScriptContext* scriptContext = function->GetScriptContext();
  4631. Assert(!(callInfo.Flags & CallFlags_New));
  4632. if (args.Info.Count == 0)
  4633. {
  4634. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.push"));
  4635. }
  4636. if (JavascriptArray::Is(args[0]))
  4637. {
  4638. return EntryPushJavascriptArray(scriptContext, args.Values, args.Info.Count);
  4639. }
  4640. else
  4641. {
  4642. return EntryPushNonJavascriptArray(scriptContext, args.Values, args.Info.Count);
  4643. }
  4644. }
  4645. template <typename T>
  4646. void JavascriptArray::CopyHeadIfInlinedHeadSegment(JavascriptArray *array, Recycler *recycler)
  4647. {
  4648. if (JavascriptArray::IsInlineSegment(array->head, array))
  4649. {
  4650. AnalysisAssert(array->head);
  4651. SparseArraySegment<T>* newHeadSeg = array->ReallocNonLeafSegment((SparseArraySegment<T>*)PointerValue(array->head), array->head->next);
  4652. array->head = newHeadSeg;
  4653. }
  4654. }
  4655. template <typename T>
  4656. void JavascriptArray::ReallocateNonLeafLastSegmentIfLeaf(JavascriptArray * arr, Recycler * recycler)
  4657. {
  4658. 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.
  4659. // TODO: Consider utilizing lastUsedSegment once we fix CopyHeadIfInlinedHeadSegment in that respect.
  4660. SparseArraySegmentBase *lastSeg = nullptr;
  4661. SparseArraySegmentBase *seg = arr->head;
  4662. while (seg)
  4663. {
  4664. lastSeg = seg;
  4665. seg = seg->next;
  4666. }
  4667. if (SparseArraySegmentBase::IsLeafSegment(lastSeg, recycler))
  4668. {
  4669. AnalysisAssert(lastSeg);
  4670. arr->ReallocNonLeafSegment((SparseArraySegment<T>*)lastSeg, lastSeg->next, true /*forceNonLeaf*/);
  4671. }
  4672. }
  4673. Var JavascriptArray::EntryReverse(RecyclableObject* function, CallInfo callInfo, ...)
  4674. {
  4675. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  4676. ARGUMENTS(args, callInfo);
  4677. ScriptContext* scriptContext = function->GetScriptContext();
  4678. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4679. Assert(!(callInfo.Flags & CallFlags_New));
  4680. if (args.Info.Count == 0)
  4681. {
  4682. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reverse"));
  4683. }
  4684. BigIndex length = 0u;
  4685. JavascriptArray* pArr = nullptr;
  4686. RecyclableObject* obj = nullptr;
  4687. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.reverse"), &pArr, &obj, &length));
  4688. if (length.IsSmallIndex())
  4689. {
  4690. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReverseHelper(pArr, nullptr, obj, length.GetSmallIndex(), scriptContext));
  4691. }
  4692. 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
  4693. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReverseHelper(pArr, nullptr, obj, length.GetBigIndex(), scriptContext));
  4694. }
  4695. bool JavascriptArray::HasAnyES5ArrayInPrototypeChain(JavascriptArray *arr, bool forceCheckProtoChain)
  4696. {
  4697. Assert(arr != nullptr);
  4698. #if ENABLE_COPYONACCESS_ARRAY
  4699. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(arr);
  4700. #endif
  4701. bool hasAnyES5Array = false;
  4702. // If there is no gap (unless forced) we are not filling from the prototype - so no point checking for ES5Array.
  4703. if (forceCheckProtoChain || arr->IsFillFromPrototypes())
  4704. {
  4705. RecyclableObject* prototype = arr->GetPrototype();
  4706. while (JavascriptOperators::GetTypeId(prototype) != TypeIds_Null)
  4707. {
  4708. RecyclableObject* protoObj = prototype;
  4709. if (!(DynamicObject::IsAnyArray(protoObj) || JavascriptOperators::IsObject(protoObj))
  4710. || JavascriptProxy::Is(protoObj)
  4711. || protoObj->IsExternal())
  4712. {
  4713. hasAnyES5Array = true;
  4714. break;
  4715. }
  4716. if (DynamicObject::IsAnyArray(protoObj))
  4717. {
  4718. if (ES5Array::Is(protoObj))
  4719. {
  4720. hasAnyES5Array = true;
  4721. break;
  4722. }
  4723. }
  4724. else if (DynamicType::Is(protoObj->GetTypeId()))
  4725. {
  4726. DynamicObject* dynobj = DynamicObject::FromVar(protoObj);
  4727. ArrayObject* objectArray = dynobj->GetObjectArray();
  4728. if (objectArray != nullptr && ES5Array::Is(objectArray))
  4729. {
  4730. hasAnyES5Array = true;
  4731. break;
  4732. }
  4733. }
  4734. prototype = prototype->GetPrototype();
  4735. }
  4736. }
  4737. return hasAnyES5Array;
  4738. }
  4739. // Array.prototype.reverse as described in ES6.0 (draft 22) Section 22.1.3.20
  4740. template <typename T>
  4741. Var JavascriptArray::ReverseHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, ScriptContext* scriptContext)
  4742. {
  4743. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4744. T middle = length / 2;
  4745. Var lowerValue = nullptr, upperValue = nullptr;
  4746. T lowerExists, upperExists;
  4747. const char16* methodName;
  4748. bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
  4749. if (isTypedArrayEntryPoint)
  4750. {
  4751. methodName = _u("[TypedArray].prototype.reverse");
  4752. }
  4753. else
  4754. {
  4755. methodName = _u("Array.prototype.reverse");
  4756. }
  4757. // If we came from Array.prototype.map and source object is not a JavascriptArray, source could be a TypedArray
  4758. if (!isTypedArrayEntryPoint && pArr == nullptr && TypedArrayBase::Is(obj))
  4759. {
  4760. typedArrayBase = TypedArrayBase::FromVar(obj);
  4761. }
  4762. ThrowTypeErrorOnFailureHelper h(scriptContext, methodName);
  4763. bool useNoSideEffectReverse = pArr != nullptr && !HasAnyES5ArrayInPrototypeChain(pArr);
  4764. if (useNoSideEffectReverse)
  4765. {
  4766. Recycler * recycler = scriptContext->GetRecycler();
  4767. if (length <= 1)
  4768. {
  4769. return pArr;
  4770. }
  4771. if (pArr->IsFillFromPrototypes())
  4772. {
  4773. // For odd-length arrays, the middle element is unchanged,
  4774. // so we cannot fill it from the prototypes.
  4775. if (length % 2 == 0)
  4776. {
  4777. JS_REENTRANT(jsReentLock, pArr->FillFromPrototypes(0, (uint32)length));
  4778. }
  4779. else
  4780. {
  4781. middle = length / 2;
  4782. JS_REENTRANT(jsReentLock,
  4783. pArr->FillFromPrototypes(0, (uint32)middle),
  4784. pArr->FillFromPrototypes(1 + (uint32)middle, (uint32)length));
  4785. }
  4786. }
  4787. // As we have already established that the FillFromPrototype should not change the bound of the array.
  4788. if (length != (T)pArr->length)
  4789. {
  4790. Js::Throw::FatalInternalError();
  4791. }
  4792. if (pArr->HasNoMissingValues() && pArr->head && pArr->head->next)
  4793. {
  4794. // This function currently does not track missing values in the head segment if there are multiple segments
  4795. pArr->SetHasNoMissingValues(false);
  4796. }
  4797. // Above FillFromPrototypes call can change the length of the array. Our segment calculation below will
  4798. // not work with the stale length. Update the length.
  4799. // Note : since we are reversing the whole segment below - the functionality is not spec compliant already.
  4800. length = pArr->length;
  4801. SparseArraySegmentBase *prevSeg = nullptr;
  4802. SparseArraySegmentBase *nextSeg = nullptr;
  4803. SparseArraySegmentBase *pinPrevSeg = nullptr;
  4804. bool isIntArray = false;
  4805. bool isFloatArray = false;
  4806. pArr->ClearSegmentMap(); // Just dump the segment map on reverse
  4807. if (JavascriptNativeIntArray::Is(pArr))
  4808. {
  4809. isIntArray = true;
  4810. }
  4811. else if (JavascriptNativeFloatArray::Is(pArr))
  4812. {
  4813. isFloatArray = true;
  4814. }
  4815. // During the loop below we are going to reverse the segments list. The head segment will become the last segment.
  4816. // We have to verify that the current head segment is not the inlined segement, otherwise due to shuffling below, the inlined segment will no longer
  4817. // be the head and that can create issue down the line. Create new segment if it is an inlined segment.
  4818. if (pArr->head && pArr->head->next)
  4819. {
  4820. if (isIntArray)
  4821. {
  4822. CopyHeadIfInlinedHeadSegment<int32>(pArr, recycler);
  4823. ReallocateNonLeafLastSegmentIfLeaf<int32>(pArr, recycler);
  4824. }
  4825. else if (isFloatArray)
  4826. {
  4827. CopyHeadIfInlinedHeadSegment<double>(pArr, recycler);
  4828. ReallocateNonLeafLastSegmentIfLeaf<double>(pArr, recycler);
  4829. }
  4830. else
  4831. {
  4832. CopyHeadIfInlinedHeadSegment<Var>(pArr, recycler);
  4833. }
  4834. }
  4835. SparseArraySegmentBase* seg = pArr->head;
  4836. while (seg)
  4837. {
  4838. nextSeg = seg->next;
  4839. // If seg.length == 0, it is possible that (seg.left + seg.length == prev.left + prev.length),
  4840. // resulting in 2 segments sharing the same "left".
  4841. if (seg->length > 0)
  4842. {
  4843. if (isIntArray)
  4844. {
  4845. ((SparseArraySegment<int32>*)seg)->ReverseSegment(recycler);
  4846. }
  4847. else if (isFloatArray)
  4848. {
  4849. ((SparseArraySegment<double>*)seg)->ReverseSegment(recycler);
  4850. }
  4851. else
  4852. {
  4853. ((SparseArraySegment<Var>*)seg)->ReverseSegment(recycler);
  4854. }
  4855. seg->left = ((uint32)length) > (seg->left + seg->length) ? ((uint32)length) - (seg->left + seg->length) : 0;
  4856. seg->next = prevSeg;
  4857. // Make sure size doesn't overlap with next segment.
  4858. // An easy fix is to just truncate the size...
  4859. seg->EnsureSizeInBound();
  4860. // If the last segment is a leaf, then we may be losing our last scanned pointer to its previous
  4861. // segment. Hold onto it with pinPrevSeg until we reallocate below.
  4862. pinPrevSeg = prevSeg;
  4863. prevSeg = seg;
  4864. }
  4865. seg = nextSeg;
  4866. }
  4867. pArr->head = prevSeg;
  4868. if (isIntArray)
  4869. {
  4870. pArr->EnsureHeadStartsFromZero<int32>(recycler);
  4871. }
  4872. else if (isFloatArray)
  4873. {
  4874. pArr->EnsureHeadStartsFromZero<double>(recycler);
  4875. }
  4876. else
  4877. {
  4878. pArr->EnsureHeadStartsFromZero<Var>(recycler);
  4879. }
  4880. pArr->InvalidateLastUsedSegment(); // lastUsedSegment might be 0-length and discarded above
  4881. #ifdef VALIDATE_ARRAY
  4882. pArr->ValidateArray();
  4883. #endif
  4884. }
  4885. else if (typedArrayBase)
  4886. {
  4887. Assert(length <= JavascriptArray::MaxArrayLength);
  4888. if (typedArrayBase->GetLength() == length)
  4889. {
  4890. // If typedArrayBase->length == length then we know that the TypedArray will have all items < length
  4891. // and we won't have to check that the elements exist or not.
  4892. for (uint32 lower = 0; lower < (uint32)middle; lower++)
  4893. {
  4894. uint32 upper = (uint32)length - lower - 1;
  4895. lowerValue = typedArrayBase->DirectGetItem(lower);
  4896. upperValue = typedArrayBase->DirectGetItem(upper);
  4897. // We still have to call HasItem even though we know the TypedArray has both lower and upper because
  4898. // there may be a proxy handler trapping HasProperty.
  4899. lowerExists = typedArrayBase->HasItem(lower);
  4900. upperExists = typedArrayBase->HasItem(upper);
  4901. JS_REENTRANT(jsReentLock,
  4902. h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(lower, upperValue)),
  4903. h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(upper, lowerValue)));
  4904. }
  4905. }
  4906. else
  4907. {
  4908. Assert(middle <= UINT_MAX);
  4909. for (uint32 lower = 0; lower < (uint32)middle; lower++)
  4910. {
  4911. uint32 upper = (uint32)length - lower - 1;
  4912. lowerValue = typedArrayBase->DirectGetItem(lower);
  4913. upperValue = typedArrayBase->DirectGetItem(upper);
  4914. lowerExists = typedArrayBase->HasItem(lower);
  4915. upperExists = typedArrayBase->HasItem(upper);
  4916. if (lowerExists)
  4917. {
  4918. if (upperExists)
  4919. {
  4920. JS_REENTRANT(jsReentLock,
  4921. h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(lower, upperValue)),
  4922. h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(upper, lowerValue)));
  4923. }
  4924. else
  4925. {
  4926. // This will always fail for a TypedArray if lower < length
  4927. h.ThrowTypeErrorOnFailure(typedArrayBase->DeleteItem(lower, PropertyOperation_ThrowOnDeleteIfNotConfig));
  4928. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(upper, lowerValue)));
  4929. }
  4930. }
  4931. else
  4932. {
  4933. if (upperExists)
  4934. {
  4935. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(lower, upperValue)));
  4936. // This will always fail for a TypedArray if upper < length
  4937. h.ThrowTypeErrorOnFailure(typedArrayBase->DeleteItem(upper, PropertyOperation_ThrowOnDeleteIfNotConfig));
  4938. }
  4939. }
  4940. }
  4941. }
  4942. }
  4943. else
  4944. {
  4945. for (T lower = 0; lower < middle; lower++)
  4946. {
  4947. T upper = length - lower - 1;
  4948. JS_REENTRANT(jsReentLock,
  4949. lowerExists = JavascriptOperators::HasItem(obj, lower) && JavascriptOperators::GetItem(obj, lower, &lowerValue, scriptContext),
  4950. upperExists = JavascriptOperators::HasItem(obj, upper) && JavascriptOperators::GetItem(obj, upper, &upperValue, scriptContext));
  4951. if (lowerExists)
  4952. {
  4953. if (upperExists)
  4954. {
  4955. JS_REENTRANT(jsReentLock,
  4956. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, lower, upperValue, scriptContext, PropertyOperation_ThrowIfNotExtensible)),
  4957. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, upper, lowerValue, scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  4958. }
  4959. else
  4960. {
  4961. JS_REENTRANT(jsReentLock,
  4962. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(obj, lower, PropertyOperation_ThrowOnDeleteIfNotConfig)),
  4963. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, upper, lowerValue, scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  4964. }
  4965. }
  4966. else
  4967. {
  4968. if (upperExists)
  4969. {
  4970. JS_REENTRANT(jsReentLock,
  4971. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, lower, upperValue, scriptContext, PropertyOperation_ThrowIfNotExtensible)),
  4972. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(obj, upper, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  4973. }
  4974. }
  4975. }
  4976. }
  4977. return obj;
  4978. }
  4979. template<typename T>
  4980. void JavascriptArray::ShiftHelper(JavascriptArray* pArr, ScriptContext * scriptContext)
  4981. {
  4982. Recycler * recycler = scriptContext->GetRecycler();
  4983. SparseArraySegment<T>* next = SparseArraySegment<T>::From(pArr->head->next);
  4984. while (next)
  4985. {
  4986. next->left--;
  4987. next = SparseArraySegment<T>::From(next->next);
  4988. }
  4989. // head and next might overlap as the next segment left is decremented
  4990. next = SparseArraySegment<T>::From(pArr->head->next);
  4991. if (next && (pArr->head->size > next->left))
  4992. {
  4993. AssertMsg(pArr->head->left == 0, "Array always points to a head starting at index 0");
  4994. AssertMsg(pArr->head->size == next->left + 1, "Shift next->left overlaps current segment by more than 1 element");
  4995. SparseArraySegment<T> *head = SparseArraySegment<T>::From(pArr->head);
  4996. SparseArraySegment<T> *oldHead = head;
  4997. bool isInlineSegment = JavascriptArray::IsInlineSegment(head, pArr);
  4998. bool nextIsInlineSegment = JavascriptArray::IsInlineSegment(next, pArr);
  4999. // Merge the two adjacent segments
  5000. if (next->length != 0)
  5001. {
  5002. uint32 offset = head->size - 1;
  5003. // There is room for one unshifted element in head segment.
  5004. // Hence it's enough if we grow the head segment by next->length - 1
  5005. if (next->next)
  5006. {
  5007. // If we have a next->next, we can't grow pass the left of that
  5008. // If the array had a segment map before, the next->next might just be right after next as well.
  5009. // So we just need to grow to the end of the next segment
  5010. // TODO: merge that segment too?
  5011. Assert(next->next->left >= head->size);
  5012. uint32 maxGrowSize = next->next->left - head->size;
  5013. if (maxGrowSize != 0)
  5014. {
  5015. head = head->GrowByMinMax(recycler, next->length - 1, maxGrowSize); //-1 is to account for unshift
  5016. }
  5017. else
  5018. {
  5019. // The next segment is only of length one, so we already have space in the header to copy that
  5020. Assert(next->length == 1);
  5021. }
  5022. }
  5023. else
  5024. {
  5025. head = head->GrowByMin(recycler, next->length - 1); //-1 is to account for unshift
  5026. }
  5027. MoveArray(head->elements + offset, next->elements, next->length);
  5028. head->length = offset + next->length;
  5029. head->CheckLengthvsSize();
  5030. pArr->head = head;
  5031. if (isInlineSegment && oldHead != head)
  5032. {
  5033. pArr->ClearElements(oldHead, 0);
  5034. }
  5035. }
  5036. head->next = next->next;
  5037. if (nextIsInlineSegment)
  5038. {
  5039. pArr->ClearElements(next, 0);
  5040. }
  5041. pArr->InvalidateLastUsedSegment();
  5042. }
  5043. #ifdef VALIDATE_ARRAY
  5044. pArr->ValidateArray();
  5045. #endif
  5046. }
  5047. Var JavascriptArray::EntryShift(RecyclableObject* function, CallInfo callInfo, ...)
  5048. {
  5049. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  5050. ARGUMENTS(args, callInfo);
  5051. ScriptContext* scriptContext = function->GetScriptContext();
  5052. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  5053. Assert(!(callInfo.Flags & CallFlags_New));
  5054. Var res = scriptContext->GetLibrary()->GetUndefined();
  5055. if (args.Info.Count == 0)
  5056. {
  5057. return res;
  5058. }
  5059. bool useNoSideEffectShift = JavascriptArray::Is(args[0])
  5060. && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject()
  5061. && !HasAnyES5ArrayInPrototypeChain(JavascriptArray::FromVar(args[0]));
  5062. if (useNoSideEffectShift)
  5063. {
  5064. JavascriptArray * pArr = JavascriptArray::FromVar(args[0]);
  5065. if (pArr->length == 0)
  5066. {
  5067. return res;
  5068. }
  5069. uint32 length = pArr->length;
  5070. if(pArr->IsFillFromPrototypes())
  5071. {
  5072. JS_REENTRANT(jsReentLock, pArr->FillFromPrototypes(0, pArr->length)); // We need find all missing value from [[proto]] object
  5073. }
  5074. // As we have already established that the FillFromPrototype should not change the bound of the array.
  5075. if (length != pArr->length)
  5076. {
  5077. Js::Throw::FatalInternalError();
  5078. }
  5079. if(pArr->HasNoMissingValues() && pArr->head && pArr->head->next)
  5080. {
  5081. // This function currently does not track missing values in the head segment if there are multiple segments
  5082. pArr->SetHasNoMissingValues(false);
  5083. }
  5084. pArr->length--;
  5085. pArr->ClearSegmentMap(); // Dump segmentMap on shift (before any allocation)
  5086. Recycler * recycler = scriptContext->GetRecycler();
  5087. bool isIntArray = false;
  5088. bool isFloatArray = false;
  5089. if(JavascriptNativeIntArray::Is(pArr))
  5090. {
  5091. isIntArray = true;
  5092. }
  5093. else if(JavascriptNativeFloatArray::Is(pArr))
  5094. {
  5095. isFloatArray = true;
  5096. }
  5097. if (pArr->head->length != 0)
  5098. {
  5099. if(isIntArray)
  5100. {
  5101. int32 nativeResult = SparseArraySegment<int32>::From(pArr->head)->GetElement(0);
  5102. if(SparseArraySegment<int32>::IsMissingItem(&nativeResult))
  5103. {
  5104. res = scriptContext->GetLibrary()->GetUndefined();
  5105. }
  5106. else
  5107. {
  5108. res = Js::JavascriptNumber::ToVar(nativeResult, scriptContext);
  5109. }
  5110. SparseArraySegment<int32>::From(pArr->head)->RemoveElement(recycler, 0);
  5111. }
  5112. else if (isFloatArray)
  5113. {
  5114. double nativeResult = SparseArraySegment<double>::From(pArr->head)->GetElement(0);
  5115. if(SparseArraySegment<double>::IsMissingItem(&nativeResult))
  5116. {
  5117. res = scriptContext->GetLibrary()->GetUndefined();
  5118. }
  5119. else
  5120. {
  5121. res = Js::JavascriptNumber::ToVarNoCheck(nativeResult, scriptContext);
  5122. }
  5123. SparseArraySegment<double>::From(pArr->head)->RemoveElement(recycler, 0);
  5124. }
  5125. else
  5126. {
  5127. res = SparseArraySegment<Var>::From(pArr->head)->GetElement(0);
  5128. if(SparseArraySegment<Var>::IsMissingItem(&res))
  5129. {
  5130. res = scriptContext->GetLibrary()->GetUndefined();
  5131. }
  5132. else
  5133. {
  5134. res = CrossSite::MarshalVar(scriptContext, res);
  5135. }
  5136. SparseArraySegment<Var>::From(pArr->head)->RemoveElement(recycler, 0);
  5137. }
  5138. }
  5139. if(isIntArray)
  5140. {
  5141. ShiftHelper<int32>(pArr, scriptContext);
  5142. }
  5143. else if (isFloatArray)
  5144. {
  5145. ShiftHelper<double>(pArr, scriptContext);
  5146. }
  5147. else
  5148. {
  5149. ShiftHelper<Var>(pArr, scriptContext);
  5150. }
  5151. }
  5152. else
  5153. {
  5154. RecyclableObject* dynamicObject = nullptr;
  5155. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &dynamicObject))
  5156. {
  5157. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.shift"));
  5158. }
  5159. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.shift"));
  5160. JS_REENTRANT(jsReentLock, BigIndex length = OP_GetLength(dynamicObject, scriptContext));
  5161. if (length == 0u)
  5162. {
  5163. // If length is 0, return 'undefined'
  5164. JS_REENTRANT(jsReentLock,
  5165. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, TaggedInt::ToVarUnchecked(0), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  5166. return scriptContext->GetLibrary()->GetUndefined();
  5167. }
  5168. JS_REENTRANT(jsReentLock,
  5169. BOOL gotItem = JavascriptOperators::GetItem(dynamicObject, 0u, &res, scriptContext));
  5170. if (!gotItem)
  5171. {
  5172. res = scriptContext->GetLibrary()->GetUndefined();
  5173. }
  5174. --length;
  5175. uint32 lengthToUin32Max = length.IsSmallIndex() ? length.GetSmallIndex() : MaxArrayLength;
  5176. for (uint32 i = 0u; i < lengthToUin32Max; i++)
  5177. {
  5178. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(dynamicObject, i + 1));
  5179. if (hasItem)
  5180. {
  5181. Var element = nullptr;
  5182. JS_REENTRANT(jsReentLock,
  5183. element = JavascriptOperators::GetItem(dynamicObject, i + 1, scriptContext),
  5184. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(dynamicObject, dynamicObject, i, element, scriptContext, PropertyOperation_ThrowIfNotExtensible, /*skipPrototypeCheck*/ true)));
  5185. }
  5186. else
  5187. {
  5188. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, i, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  5189. }
  5190. }
  5191. for (uint64 i = MaxArrayLength; length > i; i++)
  5192. {
  5193. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(dynamicObject, i + 1));
  5194. if (hasItem)
  5195. {
  5196. Var element = nullptr;
  5197. JS_REENTRANT(jsReentLock,
  5198. element = JavascriptOperators::GetItem(dynamicObject, i + 1, scriptContext),
  5199. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(dynamicObject, dynamicObject, i, element, scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  5200. }
  5201. else
  5202. {
  5203. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, i, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  5204. }
  5205. }
  5206. if (length.IsSmallIndex())
  5207. {
  5208. JS_REENTRANT(jsReentLock,
  5209. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, length.GetSmallIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig)),
  5210. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(length.GetSmallIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  5211. }
  5212. else
  5213. {
  5214. JS_REENTRANT(jsReentLock,
  5215. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, length.GetBigIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig)),
  5216. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(length.GetBigIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  5217. }
  5218. }
  5219. return res;
  5220. }
  5221. Js::JavascriptArray* JavascriptArray::CreateNewArrayHelper(uint32 len, bool isIntArray, bool isFloatArray, Js::JavascriptArray* baseArray, ScriptContext* scriptContext)
  5222. {
  5223. if (isIntArray)
  5224. {
  5225. Js::JavascriptNativeIntArray *pnewArr = scriptContext->GetLibrary()->CreateNativeIntArray(len);
  5226. pnewArr->EnsureHead<int32>();
  5227. #if ENABLE_PROFILE_INFO
  5228. pnewArr->CopyArrayProfileInfo(Js::JavascriptNativeIntArray::FromVar(baseArray));
  5229. #endif
  5230. return pnewArr;
  5231. }
  5232. else if (isFloatArray)
  5233. {
  5234. Js::JavascriptNativeFloatArray *pnewArr = scriptContext->GetLibrary()->CreateNativeFloatArray(len);
  5235. pnewArr->EnsureHead<double>();
  5236. #if ENABLE_PROFILE_INFO
  5237. pnewArr->CopyArrayProfileInfo(Js::JavascriptNativeFloatArray::FromVar(baseArray));
  5238. #endif
  5239. return pnewArr;
  5240. }
  5241. else
  5242. {
  5243. JavascriptArray *pnewArr = pnewArr = scriptContext->GetLibrary()->CreateArray(len);
  5244. pnewArr->EnsureHead<Var>();
  5245. return pnewArr;
  5246. }
  5247. }
  5248. template<typename T>
  5249. void JavascriptArray::SliceHelper(JavascriptArray* pArr, JavascriptArray* pnewArr, uint32 start, uint32 newLen)
  5250. {
  5251. JS_REENTRANCY_LOCK(jsReentLock, pArr->GetScriptContext()->GetThreadContext());
  5252. SparseArraySegment<T>* headSeg = SparseArraySegment<T>::From(pArr->head);
  5253. SparseArraySegment<T>* pnewHeadSeg = SparseArraySegment<T>::From(pnewArr->head);
  5254. // Fill the newly created sliced array
  5255. CopyArray(pnewHeadSeg->elements, newLen, headSeg->elements + start, newLen);
  5256. pnewHeadSeg->length = newLen;
  5257. pnewHeadSeg->CheckLengthvsSize();
  5258. Assert(pnewHeadSeg->length <= pnewHeadSeg->size);
  5259. // Prototype lookup for missing elements
  5260. if (!pArr->HasNoMissingValues())
  5261. {
  5262. for (uint32 i = 0; i < newLen && (i + start) < pArr->length; i++)
  5263. {
  5264. // array type might be changed in the below call to DirectGetItemAtFull
  5265. // need recheck array type before checking array item [i + start]
  5266. if (pArr->IsMissingItem(i + start))
  5267. {
  5268. Var element = nullptr;
  5269. pnewArr->SetHasNoMissingValues(false);
  5270. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(i + start, &element));
  5271. if (gotItem)
  5272. {
  5273. JS_REENTRANT(jsReentLock, pnewArr->SetItem(i, element, PropertyOperation_None));
  5274. }
  5275. }
  5276. }
  5277. }
  5278. #ifdef DBG
  5279. else
  5280. {
  5281. for (uint32 i = 0; i < newLen; i++)
  5282. {
  5283. AssertMsg(!SparseArraySegment<T>::IsMissingItem(&headSeg->elements[i+start]), "Array marked incorrectly as having missing value");
  5284. }
  5285. }
  5286. #endif
  5287. }
  5288. // If the creating profile data has changed, convert it to the type of array indicated
  5289. // in the profile
  5290. void JavascriptArray::GetArrayTypeAndConvert(bool* isIntArray, bool* isFloatArray)
  5291. {
  5292. if (JavascriptNativeIntArray::Is(this))
  5293. {
  5294. #if ENABLE_PROFILE_INFO
  5295. JavascriptNativeIntArray* nativeIntArray = JavascriptNativeIntArray::FromVar(this);
  5296. ArrayCallSiteInfo* info = nativeIntArray->GetArrayCallSiteInfo();
  5297. if(!info || info->IsNativeIntArray())
  5298. {
  5299. *isIntArray = true;
  5300. }
  5301. else if(info->IsNativeFloatArray())
  5302. {
  5303. JavascriptNativeIntArray::ToNativeFloatArray(nativeIntArray);
  5304. *isFloatArray = true;
  5305. }
  5306. else
  5307. {
  5308. JavascriptNativeIntArray::ToVarArray(nativeIntArray);
  5309. }
  5310. #else
  5311. *isIntArray = true;
  5312. #endif
  5313. }
  5314. else if (JavascriptNativeFloatArray::Is(this))
  5315. {
  5316. #if ENABLE_PROFILE_INFO
  5317. JavascriptNativeFloatArray* nativeFloatArray = JavascriptNativeFloatArray::FromVar(this);
  5318. ArrayCallSiteInfo* info = nativeFloatArray->GetArrayCallSiteInfo();
  5319. if(info && !info->IsNativeArray())
  5320. {
  5321. JavascriptNativeFloatArray::ToVarArray(nativeFloatArray);
  5322. }
  5323. else
  5324. {
  5325. *isFloatArray = true;
  5326. }
  5327. #else
  5328. *isFloatArray = true;
  5329. #endif
  5330. }
  5331. }
  5332. Var JavascriptArray::EntrySlice(RecyclableObject* function, CallInfo callInfo, ...)
  5333. {
  5334. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  5335. ARGUMENTS(args, callInfo);
  5336. ScriptContext* scriptContext = function->GetScriptContext();
  5337. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  5338. Assert(!(callInfo.Flags & CallFlags_New));
  5339. Var res = scriptContext->GetLibrary()->GetUndefined();
  5340. if (args.Info.Count == 0)
  5341. {
  5342. return res;
  5343. }
  5344. BigIndex length;
  5345. JavascriptArray* pArr = nullptr;
  5346. RecyclableObject* obj = nullptr;
  5347. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.slice"), &pArr, &obj, &length));
  5348. if (length.IsSmallIndex())
  5349. {
  5350. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  5351. }
  5352. Assert(pArr == nullptr || length.IsUint32Max());
  5353. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  5354. }
  5355. // Array.prototype.slice as described in ES6.0 (draft 22) Section 22.1.3.22
  5356. template <typename T>
  5357. Var JavascriptArray::SliceHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  5358. {
  5359. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  5360. JavascriptArray* newArr = nullptr;
  5361. RecyclableObject* newObj = nullptr;
  5362. bool isIntArray = false;
  5363. bool isFloatArray = false;
  5364. bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
  5365. bool isBuiltinArrayCtor = true;
  5366. T startT = 0;
  5367. T newLenT = length;
  5368. T endT = length;
  5369. #if ENABLE_COPYONACCESS_ARRAY
  5370. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pArr);
  5371. #endif
  5372. if (args.Info.Count > 1)
  5373. {
  5374. JS_REENTRANT(jsReentLock, startT = GetFromIndex(args[1], length, scriptContext));
  5375. if (args.Info.Count > 2 && JavascriptOperators::GetTypeId(args[2]) != TypeIds_Undefined)
  5376. {
  5377. JS_REENTRANT(jsReentLock, endT = GetFromIndex(args[2], length, scriptContext));
  5378. }
  5379. newLenT = endT > startT ? endT - startT : 0;
  5380. }
  5381. // 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.
  5382. if (pArr && !JavascriptArray::Is(obj))
  5383. {
  5384. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  5385. pArr = nullptr;
  5386. }
  5387. if (TypedArrayBase::IsDetachedTypedArray(obj))
  5388. {
  5389. JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("Array.prototype.slice"));
  5390. }
  5391. // If we came from Array.prototype.slice and source object is not a JavascriptArray, source could be a TypedArray
  5392. if (!isTypedArrayEntryPoint && pArr == nullptr && TypedArrayBase::Is(obj))
  5393. {
  5394. typedArrayBase = TypedArrayBase::FromVar(obj);
  5395. }
  5396. // 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
  5397. // and use it to construct the return object.
  5398. if (isTypedArrayEntryPoint)
  5399. {
  5400. JS_REENTRANT(jsReentLock,
  5401. Var constructor = JavascriptOperators::SpeciesConstructor(typedArrayBase, TypedArrayBase::GetDefaultConstructor(args[0], scriptContext), scriptContext));
  5402. isBuiltinArrayCtor = false;
  5403. AssertAndFailFast(pArr == nullptr);
  5404. Assert(JavascriptOperators::IsConstructor(constructor));
  5405. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(newLenT, scriptContext) };
  5406. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  5407. JS_REENTRANT(jsReentLock, newObj = RecyclableObject::FromVar(TypedArrayBase::TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), (uint32)newLenT, scriptContext)));
  5408. }
  5409. else if (pArr != nullptr)
  5410. {
  5411. JS_REENTRANT(jsReentLock, newObj = ArraySpeciesCreate(pArr, newLenT, scriptContext, &isIntArray, &isFloatArray, &isBuiltinArrayCtor));
  5412. }
  5413. // skip the typed array and "pure" array case, we still need to handle special arrays like es5array, remote array, and proxy of array.
  5414. else
  5415. {
  5416. JS_REENTRANT(jsReentLock, newObj = ArraySpeciesCreate(obj, newLenT, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor));
  5417. }
  5418. // If we didn't create a new object above we will create a new array here.
  5419. // This is the pre-ES6 behavior or the case of calling Array.prototype.slice with a constructor argument that is not a constructor function.
  5420. if (newObj == nullptr)
  5421. {
  5422. if (pArr)
  5423. {
  5424. pArr->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
  5425. }
  5426. if (newLenT > JavascriptArray::MaxArrayLength)
  5427. {
  5428. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  5429. }
  5430. newArr = CreateNewArrayHelper(static_cast<uint32>(newLenT), isIntArray, isFloatArray, pArr, scriptContext);
  5431. #if ENABLE_COPYONACCESS_ARRAY
  5432. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  5433. #endif
  5434. newObj = newArr;
  5435. }
  5436. else
  5437. {
  5438. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  5439. if (JavascriptArray::Is(newObj))
  5440. {
  5441. #if ENABLE_COPYONACCESS_ARRAY
  5442. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
  5443. #endif
  5444. newArr = JavascriptArray::FromVar(newObj);
  5445. }
  5446. }
  5447. uint32 start = (uint32) startT;
  5448. uint32 newLen = (uint32) newLenT;
  5449. // We at least have to have newObj as a valid object
  5450. Assert(newObj);
  5451. // Bail out early if the new object will have zero length.
  5452. if (newLen == 0)
  5453. {
  5454. return newObj;
  5455. }
  5456. // The ArraySpeciesCreate call above could have converted the source array into an ES5Array. If this happens
  5457. // we will process the array elements like an ES5Array.
  5458. if (pArr && !JavascriptArray::Is(obj))
  5459. {
  5460. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  5461. pArr = nullptr;
  5462. }
  5463. if (pArr)
  5464. {
  5465. if (HasAnyES5ArrayInPrototypeChain(pArr))
  5466. {
  5467. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceObjectHelper(obj, start, 0u, newArr, newObj, newLen, scriptContext));
  5468. }
  5469. // If we constructed a new Array object, we have some nice helpers here
  5470. if (newArr && isBuiltinArrayCtor)
  5471. {
  5472. if (JavascriptArray::IsDirectAccessArray(newArr))
  5473. {
  5474. if (((start + newLen) <= pArr->head->length) && newLen <= newArr->head->size) //Fast Path
  5475. {
  5476. if (isIntArray)
  5477. {
  5478. JS_REENTRANT(jsReentLock, SliceHelper<int32>(pArr, newArr, start, newLen));
  5479. }
  5480. else if (isFloatArray)
  5481. {
  5482. JS_REENTRANT(jsReentLock, SliceHelper<double>(pArr, newArr, start, newLen));
  5483. }
  5484. else
  5485. {
  5486. JS_REENTRANT(jsReentLock, SliceHelper<Var>(pArr, newArr, start, newLen));
  5487. }
  5488. }
  5489. else
  5490. {
  5491. if (isIntArray)
  5492. {
  5493. JS_REENTRANT(jsReentLock, CopyNativeIntArrayElements(JavascriptNativeIntArray::FromVar(newArr), 0, JavascriptNativeIntArray::FromVar(pArr), start, start + newLen));
  5494. }
  5495. else if (isFloatArray)
  5496. {
  5497. JS_REENTRANT(jsReentLock, CopyNativeFloatArrayElements(JavascriptNativeFloatArray::FromVar(newArr), 0, JavascriptNativeFloatArray::FromVar(pArr), start, start + newLen));
  5498. }
  5499. else
  5500. {
  5501. JS_REENTRANT(jsReentLock, CopyArrayElements(newArr, 0u, pArr, start, start + newLen));
  5502. }
  5503. }
  5504. }
  5505. else
  5506. {
  5507. AssertMsg(CONFIG_FLAG(ForceES5Array), "newArr can only be ES5Array when it is forced");
  5508. Var element = nullptr;
  5509. for (uint32 i = 0; i < newLen; i++)
  5510. {
  5511. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(i + start, &element));
  5512. if (!gotItem)
  5513. {
  5514. continue;
  5515. }
  5516. newArr->SetItem(i, element, PropertyOperation_None);
  5517. // Side-effects in the prototype lookup may have changed the source array into an ES5Array. If this happens
  5518. // we will process the rest of the array elements like an ES5Array.
  5519. if (!JavascriptArray::Is(obj))
  5520. {
  5521. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  5522. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceObjectHelper(obj, start, i + 1, newArr, newObj, newLen, scriptContext));
  5523. }
  5524. }
  5525. }
  5526. }
  5527. else
  5528. {
  5529. // The constructed object isn't an array, we'll need to use normal object manipulation
  5530. Var element = nullptr;
  5531. for (uint32 i = 0; i < newLen; i++)
  5532. {
  5533. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(i + start, &element));
  5534. if (!gotItem)
  5535. {
  5536. continue;
  5537. }
  5538. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i));
  5539. // Side-effects in the prototype lookup may have changed the source array into an ES5Array. If this happens
  5540. // we will process the rest of the array elements like an ES5Array.
  5541. if (!JavascriptArray::Is(obj))
  5542. {
  5543. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  5544. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceObjectHelper(obj, start, i + 1, newArr, newObj, newLen, scriptContext));
  5545. }
  5546. }
  5547. }
  5548. }
  5549. else if (typedArrayBase)
  5550. {
  5551. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  5552. // 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)
  5553. TypedArrayBase* newTypedArray = nullptr;
  5554. if (TypedArrayBase::Is(newObj))
  5555. {
  5556. newTypedArray = TypedArrayBase::FromVar(newObj);
  5557. }
  5558. else
  5559. {
  5560. AssertAndFailFast(newArr != nullptr);
  5561. }
  5562. Var element;
  5563. for (uint32 i = 0; i < newLen; i++)
  5564. {
  5565. // We only need to call HasItem in the case that we are called from Array.prototype.slice
  5566. if (!isTypedArrayEntryPoint && !typedArrayBase->HasItem(i + start))
  5567. {
  5568. continue;
  5569. }
  5570. element = typedArrayBase->DirectGetItem(i + start);
  5571. // The object we got back from the constructor might not be a TypedArray. In fact, it could be any object.
  5572. if (newTypedArray)
  5573. {
  5574. JS_REENTRANT(jsReentLock, newTypedArray->DirectSetItem(i, element));
  5575. }
  5576. else
  5577. {
  5578. newArr->SetItem(i, element, PropertyOperation_None);
  5579. }
  5580. }
  5581. }
  5582. else
  5583. {
  5584. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceObjectHelper(obj, start, 0u, newArr, newObj, newLen, scriptContext));;
  5585. }
  5586. if (!isTypedArrayEntryPoint)
  5587. {
  5588. JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(newLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible);
  5589. }
  5590. #ifdef VALIDATE_ARRAY
  5591. if (JavascriptArray::Is(newObj))
  5592. {
  5593. JavascriptArray::FromVar(newObj)->ValidateArray();
  5594. }
  5595. #endif
  5596. return newObj;
  5597. }
  5598. Var JavascriptArray::SliceObjectHelper(RecyclableObject* obj, uint32 sliceStart, uint32 start, JavascriptArray* newArr, RecyclableObject* newObj, uint32 newLen, ScriptContext* scriptContext)
  5599. {
  5600. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  5601. for (uint32 i = start; i < newLen; i++)
  5602. {
  5603. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, i + sliceStart));
  5604. if (hasItem)
  5605. {
  5606. JS_REENTRANT(jsReentLock, Var element = JavascriptOperators::GetItem(obj, i + sliceStart, scriptContext));
  5607. if (newArr != nullptr)
  5608. {
  5609. newArr->SetItem(i, element, PropertyOperation_None);
  5610. }
  5611. else
  5612. {
  5613. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i));
  5614. }
  5615. }
  5616. }
  5617. JS_REENTRANT(jsReentLock,
  5618. JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(newLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  5619. #ifdef VALIDATE_ARRAY
  5620. if (JavascriptArray::Is(newObj))
  5621. {
  5622. JavascriptArray::FromVar(newObj)->ValidateArray();
  5623. }
  5624. #endif
  5625. return newObj;
  5626. }
  5627. struct CompareVarsInfo
  5628. {
  5629. ScriptContext* scriptContext;
  5630. RecyclableObject* compFn;
  5631. };
  5632. int __cdecl compareVars(void* cvInfoV, const void* aRef, const void* bRef)
  5633. {
  5634. CompareVarsInfo* cvInfo=(CompareVarsInfo*)cvInfoV;
  5635. ScriptContext* requestContext=cvInfo->scriptContext;
  5636. RecyclableObject* compFn=cvInfo->compFn;
  5637. AssertMsg(*(Var*)aRef, "No null expected in sort");
  5638. AssertMsg(*(Var*)bRef, "No null expected in sort");
  5639. if (compFn != nullptr)
  5640. {
  5641. ScriptContext* scriptContext = compFn->GetScriptContext();
  5642. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  5643. CallFlags flags = CallFlags_Value;
  5644. Var undefined = scriptContext->GetLibrary()->GetUndefined();
  5645. Var retVal;
  5646. if (requestContext != scriptContext)
  5647. {
  5648. Var leftVar = CrossSite::MarshalVar(scriptContext, *(Var*)aRef);
  5649. Var rightVar = CrossSite::MarshalVar(scriptContext, *(Var*)bRef);
  5650. retVal = CALL_FUNCTION(scriptContext->GetThreadContext(), compFn, CallInfo(flags, 3), undefined, leftVar, rightVar);
  5651. }
  5652. else
  5653. {
  5654. retVal = CALL_FUNCTION(scriptContext->GetThreadContext(), compFn, CallInfo(flags, 3), undefined, *(Var*)aRef, *(Var*)bRef);
  5655. }
  5656. if (TaggedInt::Is(retVal))
  5657. {
  5658. return TaggedInt::ToInt32(retVal);
  5659. }
  5660. double dblResult;
  5661. if (JavascriptNumber::Is_NoTaggedIntCheck(retVal))
  5662. {
  5663. dblResult = JavascriptNumber::GetValue(retVal);
  5664. }
  5665. else
  5666. {
  5667. dblResult = JavascriptConversion::ToNumber_Full(retVal, scriptContext);
  5668. }
  5669. if (dblResult < 0)
  5670. {
  5671. return -1;
  5672. }
  5673. return (dblResult > 0) ? 1 : 0;
  5674. }
  5675. else
  5676. {
  5677. JavascriptString* pStr1 = JavascriptConversion::ToString(*(Var*)aRef, requestContext);
  5678. JavascriptString* pStr2 = JavascriptConversion::ToString(*(Var*)bRef, requestContext);
  5679. return JavascriptString::strcmp(pStr1, pStr2);
  5680. }
  5681. }
  5682. static void hybridSort(__inout_ecount(length) Field(Var) *elements, uint32 length, CompareVarsInfo* compareInfo)
  5683. {
  5684. // The cost of memory moves starts to be more expensive than additional comparer calls (given a simple comparer)
  5685. // for arrays of more than 512 elements.
  5686. if (length > 512)
  5687. {
  5688. qsort_s(elements, length, compareVars, compareInfo);
  5689. return;
  5690. }
  5691. for (int i = 1; i < (int)length; i++)
  5692. {
  5693. if (compareVars(compareInfo, elements + i, elements + i - 1) < 0) {
  5694. // binary search for the left-most element greater than value:
  5695. int first = 0;
  5696. int last = i - 1;
  5697. while (first <= last)
  5698. {
  5699. int middle = (first + last) / 2;
  5700. if (compareVars(compareInfo, elements + i, elements + middle) < 0)
  5701. {
  5702. last = middle - 1;
  5703. }
  5704. else
  5705. {
  5706. first = middle + 1;
  5707. }
  5708. }
  5709. // insert value right before first:
  5710. Var value = elements[i];
  5711. MoveArray(elements + first + 1, elements + first, (i - first));
  5712. elements[first] = value;
  5713. }
  5714. }
  5715. }
  5716. void JavascriptArray::Sort(RecyclableObject* compFn)
  5717. {
  5718. JS_REENTRANCY_LOCK(jsReentLock, this->GetScriptContext()->GetThreadContext());
  5719. if (length <= 1)
  5720. {
  5721. return;
  5722. }
  5723. this->EnsureHead<Var>();
  5724. ScriptContext* scriptContext = this->GetScriptContext();
  5725. Recycler* recycler = scriptContext->GetRecycler();
  5726. CompareVarsInfo cvInfo;
  5727. cvInfo.scriptContext = scriptContext;
  5728. cvInfo.compFn = compFn;
  5729. Assert(head != nullptr);
  5730. // Just dump the segment map on sort
  5731. ClearSegmentMap();
  5732. uint32 countUndefined = 0;
  5733. SparseArraySegment<Var>* startSeg = SparseArraySegment<Var>::From(head);
  5734. // Sort may have side effects on the array. Setting a dummy head so that original array is not affected
  5735. uint32 saveLength = length;
  5736. // that if compare function tries to modify the array it won't AV.
  5737. head = const_cast<SparseArraySegmentBase*>(EmptySegment);
  5738. SetFlags(DynamicObjectFlags::None);
  5739. this->InvalidateLastUsedSegment();
  5740. length = 0;
  5741. TryFinally([&]()
  5742. {
  5743. //The array is a continuous array if there is only one segment
  5744. if (startSeg->next == nullptr) // Single segment fast path
  5745. {
  5746. if (compFn != nullptr)
  5747. {
  5748. countUndefined = startSeg->RemoveUndefined(scriptContext);
  5749. #ifdef VALIDATE_ARRAY
  5750. ValidateSegment(startSeg);
  5751. #endif
  5752. JS_REENTRANT(jsReentLock, hybridSort(startSeg->elements, startSeg->length, &cvInfo));
  5753. startSeg->CheckLengthvsSize();
  5754. }
  5755. else
  5756. {
  5757. JS_REENTRANT(jsReentLock, countUndefined = sort(startSeg->elements, &startSeg->length, scriptContext));
  5758. }
  5759. head = startSeg;
  5760. }
  5761. else
  5762. {
  5763. SparseArraySegment<Var>* allElements = SparseArraySegment<Var>::AllocateSegment(recycler, 0, 0, nullptr);
  5764. SparseArraySegment<Var>* next = startSeg;
  5765. uint32 nextIndex = 0;
  5766. // copy all the elements to single segment
  5767. while (next)
  5768. {
  5769. countUndefined += next->RemoveUndefined(scriptContext);
  5770. if (next->length != 0)
  5771. {
  5772. allElements = SparseArraySegment<Var>::CopySegment(recycler, allElements, nextIndex, next, next->left, next->length);
  5773. }
  5774. next = SparseArraySegment<Var>::From(next->next);
  5775. nextIndex = allElements->length;
  5776. #ifdef VALIDATE_ARRAY
  5777. ValidateSegment(allElements);
  5778. #endif
  5779. }
  5780. if (compFn != nullptr)
  5781. {
  5782. JS_REENTRANT(jsReentLock, hybridSort(allElements->elements, allElements->length, &cvInfo));
  5783. }
  5784. else
  5785. {
  5786. JS_REENTRANT(jsReentLock, sort(allElements->elements, &allElements->length, scriptContext));
  5787. allElements->CheckLengthvsSize();
  5788. }
  5789. head = allElements;
  5790. head->next = nullptr;
  5791. }
  5792. },
  5793. [&](bool hasException)
  5794. {
  5795. length = saveLength;
  5796. ClearSegmentMap(); // Dump the segmentMap again in case user compare function rebuilds it
  5797. if (hasException)
  5798. {
  5799. head = startSeg;
  5800. this->InvalidateLastUsedSegment();
  5801. }
  5802. });
  5803. #if DEBUG
  5804. {
  5805. uint32 countNull = 0;
  5806. uint32 index = head->length - 1;
  5807. while (countNull < head->length)
  5808. {
  5809. if (SparseArraySegment<Var>::From(head)->elements[index] != NULL)
  5810. {
  5811. break;
  5812. }
  5813. index--;
  5814. countNull++;
  5815. }
  5816. AssertMsg(countNull == 0, "No null expected at the end");
  5817. }
  5818. #endif
  5819. if (countUndefined != 0)
  5820. {
  5821. // fill undefined at the end
  5822. uint32 newLength = head->length + countUndefined;
  5823. if (newLength > head->size)
  5824. {
  5825. SparseArraySegmentBase *oldHead = head;
  5826. bool isInlineSegment = JavascriptArray::IsInlineSegment(head, this);
  5827. head = SparseArraySegment<Var>::From(head)->GrowByMin(recycler, newLength - head->size);
  5828. if (isInlineSegment)
  5829. {
  5830. this->ClearElements(oldHead, 0);
  5831. }
  5832. }
  5833. Var undefined = scriptContext->GetLibrary()->GetUndefined();
  5834. for (uint32 i = head->length; i < newLength; i++)
  5835. {
  5836. SparseArraySegment<Var>::From(head)->elements[i] = undefined;
  5837. }
  5838. head->length = newLength;
  5839. head->CheckLengthvsSize();
  5840. }
  5841. SetHasNoMissingValues();
  5842. this->InvalidateLastUsedSegment();
  5843. #ifdef VALIDATE_ARRAY
  5844. ValidateArray();
  5845. #endif
  5846. return;
  5847. }
  5848. uint32 JavascriptArray::sort(__inout_ecount(*len) Field(Var) *orig, uint32 *len, ScriptContext *scriptContext)
  5849. {
  5850. uint32 count = 0, countUndefined = 0;
  5851. Element *elements = RecyclerNewArrayZ(scriptContext->GetRecycler(), Element, *len);
  5852. RecyclableObject *undefined = scriptContext->GetLibrary()->GetUndefined();
  5853. //
  5854. // Create the Elements array
  5855. //
  5856. for (uint32 i = 0; i < *len; ++i)
  5857. {
  5858. if (!SparseArraySegment<Var>::IsMissingItem(&orig[i]))
  5859. {
  5860. if (!JavascriptOperators::IsUndefinedObject(orig[i], undefined))
  5861. {
  5862. elements[count].Value = orig[i];
  5863. elements[count].StringValue = JavascriptConversion::ToString(orig[i], scriptContext);
  5864. count++;
  5865. }
  5866. else
  5867. {
  5868. countUndefined++;
  5869. }
  5870. }
  5871. }
  5872. if (count > 0)
  5873. {
  5874. SortElements(elements, 0, count - 1);
  5875. for (uint32 i = 0; i < count; ++i)
  5876. {
  5877. orig[i] = elements[i].Value;
  5878. }
  5879. }
  5880. for (uint32 i = count + countUndefined; i < *len; ++i)
  5881. {
  5882. orig[i] = SparseArraySegment<Var>::GetMissingItem();
  5883. }
  5884. *len = count; // set the correct length
  5885. return countUndefined;
  5886. }
  5887. int __cdecl JavascriptArray::CompareElements(void* context, const void* elem1, const void* elem2)
  5888. {
  5889. const Element* element1 = static_cast<const Element*>(elem1);
  5890. const Element* element2 = static_cast<const Element*>(elem2);
  5891. Assert(element1 != NULL);
  5892. Assert(element2 != NULL);
  5893. return JavascriptString::strcmp(element1->StringValue, element2->StringValue);
  5894. }
  5895. void JavascriptArray::SortElements(Element* elements, uint32 left, uint32 right)
  5896. {
  5897. // Note: use write barrier policy of Field(Var)
  5898. qsort_s<Element, Field(Var)>(elements, right - left + 1, CompareElements, this);
  5899. }
  5900. Var JavascriptArray::EntrySort(RecyclableObject* function, CallInfo callInfo, ...)
  5901. {
  5902. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  5903. ARGUMENTS(args, callInfo);
  5904. ScriptContext* scriptContext = function->GetScriptContext();
  5905. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  5906. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.sort"));
  5907. Assert(!(callInfo.Flags & CallFlags_New));
  5908. AssertMsg(args.Info.Count >= 1, "Should have at least one argument");
  5909. RecyclableObject* compFn = NULL;
  5910. if (args.Info.Count > 1)
  5911. {
  5912. if (JavascriptConversion::IsCallable(args[1]))
  5913. {
  5914. compFn = RecyclableObject::FromVar(args[1]);
  5915. }
  5916. else
  5917. {
  5918. TypeId typeId = JavascriptOperators::GetTypeId(args[1]);
  5919. // Use default comparer:
  5920. // - In ES5 mode if the argument is undefined.
  5921. bool useDefaultComparer = typeId == TypeIds_Undefined;
  5922. if (!useDefaultComparer)
  5923. {
  5924. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.sort"));
  5925. }
  5926. }
  5927. }
  5928. bool useNoSideEffectSort = JavascriptArray::Is(args[0])
  5929. && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject()
  5930. && !HasAnyES5ArrayInPrototypeChain(JavascriptArray::FromVar(args[0]));
  5931. if (useNoSideEffectSort)
  5932. {
  5933. JavascriptArray *arr = JavascriptArray::FromVar(args[0]);
  5934. if (arr->length <= 1)
  5935. {
  5936. return args[0];
  5937. }
  5938. uint32 length = arr->length;
  5939. if(arr->IsFillFromPrototypes())
  5940. {
  5941. JS_REENTRANT(jsReentLock, arr->FillFromPrototypes(0, arr->length)); // We need find all missing value from [[proto]] object
  5942. }
  5943. // As we have already established that the FillFromPrototype should not change the bound of the array.
  5944. if (length != arr->length)
  5945. {
  5946. Js::Throw::FatalInternalError();
  5947. }
  5948. // Maintain nativity of the array only for the following cases (To favor inplace conversions - keeps the conversion cost less):
  5949. // - int cases for X86 and
  5950. // - FloatArray for AMD64
  5951. // We convert the entire array back and forth once here O(n), rather than doing the costly conversion down the call stack which is O(nlogn)
  5952. #if defined(_M_X64_OR_ARM64)
  5953. if(compFn && JavascriptNativeFloatArray::Is(arr))
  5954. {
  5955. arr = JavascriptNativeFloatArray::ConvertToVarArray((JavascriptNativeFloatArray*)arr);
  5956. JS_REENTRANT(jsReentLock, arr->Sort(compFn));
  5957. arr = arr->ConvertToNativeArrayInPlace<JavascriptNativeFloatArray, double>(arr);
  5958. }
  5959. else
  5960. {
  5961. EnsureNonNativeArray(arr);
  5962. JS_REENTRANT(jsReentLock, arr->Sort(compFn));
  5963. }
  5964. #else
  5965. if(compFn && JavascriptNativeIntArray::Is(arr))
  5966. {
  5967. //EnsureNonNativeArray(arr);
  5968. arr = JavascriptNativeIntArray::ConvertToVarArray((JavascriptNativeIntArray*)arr);
  5969. JS_REENTRANT(jsReentLock, arr->Sort(compFn));
  5970. arr = arr->ConvertToNativeArrayInPlace<JavascriptNativeIntArray, int32>(arr);
  5971. }
  5972. else
  5973. {
  5974. EnsureNonNativeArray(arr);
  5975. JS_REENTRANT(jsReentLock, arr->Sort(compFn));
  5976. }
  5977. #endif
  5978. }
  5979. else
  5980. {
  5981. RecyclableObject* pObj = nullptr;
  5982. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &pObj))
  5983. {
  5984. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.sort"));
  5985. }
  5986. JS_REENTRANT(jsReentLock,
  5987. uint32 len = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(pObj, scriptContext), scriptContext));
  5988. JavascriptArray* sortArray = scriptContext->GetLibrary()->CreateArray(len);
  5989. sortArray->EnsureHead<Var>();
  5990. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.sort"));
  5991. BEGIN_TEMP_ALLOCATOR(tempAlloc, scriptContext, _u("Runtime"))
  5992. {
  5993. JsUtil::List<uint32, ArenaAllocator>* indexList = JsUtil::List<uint32, ArenaAllocator>::New(tempAlloc);
  5994. for (uint32 i = 0; i < len; i++)
  5995. {
  5996. Var item = nullptr;
  5997. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(pObj, i, &item, scriptContext));
  5998. if (gotItem)
  5999. {
  6000. indexList->Add(i);
  6001. sortArray->DirectSetItemAt(i, item);
  6002. }
  6003. }
  6004. if (indexList->Count() > 0)
  6005. {
  6006. if (sortArray->length > 1)
  6007. {
  6008. JS_REENTRANT(jsReentLock, sortArray->FillFromPrototypes(0, sortArray->length)); // We need find all missing value from [[proto]] object
  6009. }
  6010. JS_REENTRANT(jsReentLock, sortArray->Sort(compFn));
  6011. uint32 removeIndex = sortArray->head->length;
  6012. for (uint32 i = 0; i < removeIndex; i++)
  6013. {
  6014. AssertMsg(!SparseArraySegment<Var>::IsMissingItem(&SparseArraySegment<Var>::From(sortArray->head)->elements[i]), "No gaps expected in sorted array");
  6015. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(pObj, pObj, i, SparseArraySegment<Var>::From(sortArray->head)->elements[i], scriptContext)));
  6016. }
  6017. for (int i = 0; i < indexList->Count(); i++)
  6018. {
  6019. uint32 value = indexList->Item(i);
  6020. if (value >= removeIndex)
  6021. {
  6022. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure((JavascriptOperators::DeleteItem(pObj, value))));
  6023. }
  6024. }
  6025. }
  6026. }
  6027. END_TEMP_ALLOCATOR(tempAlloc, scriptContext);
  6028. }
  6029. return args[0];
  6030. }
  6031. Var JavascriptArray::EntrySplice(RecyclableObject* function, CallInfo callInfo, ...)
  6032. {
  6033. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  6034. ARGUMENTS(args, callInfo);
  6035. ScriptContext* scriptContext = function->GetScriptContext();
  6036. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6037. Assert(!(callInfo.Flags & CallFlags_New));
  6038. AssertMsg(args.Info.Count >= 1, "Should have at least one argument");
  6039. JavascriptArray* pArr = 0;
  6040. RecyclableObject* pObj = 0;
  6041. uint64 start = 0u;
  6042. uint64 deleteLen = 0u;
  6043. uint64 length = 0u;
  6044. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.splice"), &pArr, &pObj, &length));
  6045. switch (args.Info.Count)
  6046. {
  6047. case 1:
  6048. start = length;
  6049. deleteLen = 0u;
  6050. break;
  6051. case 2:
  6052. JS_REENTRANT(jsReentLock, start = GetFromIndex(args[1], length, scriptContext));
  6053. deleteLen = length - start;
  6054. break;
  6055. default:
  6056. JS_REENTRANT(jsReentLock, start = GetFromIndex(args[1], length, scriptContext),
  6057. deleteLen = GetFromIndex(args[2], (length - start), scriptContext, false));
  6058. break;
  6059. }
  6060. // 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.
  6061. if (pArr && !JavascriptArray::Is(pObj))
  6062. {
  6063. AssertOrFailFastMsg(ES5Array::Is(pObj), "The array should have been converted to an ES5Array");
  6064. pArr = nullptr;
  6065. }
  6066. Var* insertArgs = args.Info.Count > 3 ? &args.Values[3] : nullptr;
  6067. uint32 insertLen = args.Info.Count > 3 ? args.Info.Count - 3 : 0;
  6068. // Force check the prototype as we may insert values more than current elements
  6069. if (pArr != nullptr && !HasAnyES5ArrayInPrototypeChain(pArr, true /*forceCheckProtoChain*/))
  6070. {
  6071. // Since we get the length from an array and that cannot be more than uint32.
  6072. _Analysis_assume_(length <= UINT_MAX);
  6073. JS_REENTRANT_UNLOCK(jsReentLock,
  6074. return TryArraySplice(pArr, (uint32)start, (uint32)length, (uint32)deleteLen, insertArgs, insertLen, scriptContext));
  6075. }
  6076. uint64 newLen = (length - deleteLen) + insertLen;
  6077. if (newLen > UINT_MAX || length > UINT_MAX || (length + insertLen) > UINT_MAX)
  6078. {
  6079. JS_REENTRANT_UNLOCK(jsReentLock,
  6080. return ObjectSpliceHelper<uint64>(pObj, length, start, deleteLen, (Var*)insertArgs, insertLen, scriptContext, nullptr));
  6081. }
  6082. else
  6083. {
  6084. JS_REENTRANT_UNLOCK(jsReentLock,
  6085. return ObjectSpliceHelper<uint32>(pObj, (uint32)length, (uint32)start, (uint32)deleteLen, (Var*)insertArgs, insertLen, scriptContext, nullptr));
  6086. }
  6087. }
  6088. inline BOOL JavascriptArray::IsSingleSegmentArray() const
  6089. {
  6090. return nullptr == head->next;
  6091. }
  6092. template<typename T>
  6093. void JavascriptArray::ArraySegmentSpliceHelper(JavascriptArray *pnewArr, SparseArraySegment<T> *seg, SparseArraySegment<T> **prev,
  6094. uint32 start, uint32 deleteLen, Var* insertArgs, uint32 insertLen, Recycler *recycler)
  6095. {
  6096. // book keeping variables
  6097. uint32 relativeStart = start - seg->left; // This will be different from start when head->left is non zero -
  6098. //(Missing elements at the beginning)
  6099. uint32 headDeleteLen = min(start + deleteLen , seg->left + seg->length) - start; // actual number of elements to delete in
  6100. // head if deleteLen overflows the length of head
  6101. uint32 newHeadLen = seg->length - headDeleteLen + insertLen; // new length of the head after splice
  6102. // Save the deleted elements
  6103. if (headDeleteLen != 0)
  6104. {
  6105. SparseArraySegmentBase *oldHead = pnewArr->head;
  6106. bool isInlineSegment = JavascriptArray::IsInlineSegment(oldHead, pnewArr);
  6107. pnewArr->InvalidateLastUsedSegment();
  6108. pnewArr->head = SparseArraySegment<T>::CopySegment(recycler, SparseArraySegment<T>::From(pnewArr->head), 0, seg, start, headDeleteLen);
  6109. if (isInlineSegment && oldHead != pnewArr->head)
  6110. {
  6111. pnewArr->ClearElements(oldHead, 0);
  6112. }
  6113. }
  6114. if (newHeadLen != 0)
  6115. {
  6116. if (seg->size < newHeadLen)
  6117. {
  6118. if (seg->next)
  6119. {
  6120. // If we have "next", require that we haven't adjusted next segments left yet.
  6121. seg = seg->GrowByMinMax(recycler, newHeadLen - seg->size, seg->next->left - deleteLen + insertLen - seg->left - seg->size);
  6122. }
  6123. else
  6124. {
  6125. seg = seg->GrowByMin(recycler, newHeadLen - seg->size);
  6126. }
  6127. #ifdef VALIDATE_ARRAY
  6128. ValidateSegment(seg);
  6129. #endif
  6130. }
  6131. // Move the elements if necessary
  6132. if (headDeleteLen != insertLen)
  6133. {
  6134. uint32 noElementsToMove = seg->length - (relativeStart + headDeleteLen);
  6135. MoveArray(seg->elements + relativeStart + insertLen,
  6136. seg->elements + relativeStart + headDeleteLen,
  6137. noElementsToMove);
  6138. if (newHeadLen < seg->length) // truncate if necessary
  6139. {
  6140. seg->Truncate(seg->left + newHeadLen); // set end elements to null so that when we introduce null elements we are safe
  6141. }
  6142. seg->length = newHeadLen;
  6143. seg->CheckLengthvsSize();
  6144. }
  6145. // Copy the new elements
  6146. if (insertLen > 0)
  6147. {
  6148. Assert(!VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(pnewArr) &&
  6149. !VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(pnewArr));
  6150. // inserted elements starts at argument 3 of splice(start, deleteNumber, insertelem1, insertelem2, insertelem3, ...);
  6151. CopyArray(seg->elements + relativeStart, insertLen,
  6152. reinterpret_cast<const T*>(insertArgs), insertLen);
  6153. }
  6154. *prev = seg;
  6155. }
  6156. else
  6157. {
  6158. *prev = SparseArraySegment<T>::From(seg->next);
  6159. }
  6160. }
  6161. template<typename T>
  6162. void JavascriptArray::ArraySpliceHelper(JavascriptArray* pnewArr, JavascriptArray* pArr, uint32 start, uint32 deleteLen, Var* insertArgs, uint32 insertLen, ScriptContext *scriptContext)
  6163. {
  6164. // Skip pnewArr->EnsureHead(): we don't use existing segment at all.
  6165. Recycler *recycler = scriptContext->GetRecycler();
  6166. Field(SparseArraySegmentBase*)* prevSeg = &pArr->head; // holds the next pointer of previous
  6167. Field(SparseArraySegmentBase*)* prevPrevSeg = &pArr->head; // this holds the previous pointer to prevSeg dirty trick.
  6168. SparseArraySegmentBase* savePrev = nullptr;
  6169. Assert(pArr->head); // We should never have a null head.
  6170. pArr->EnsureHead<T>();
  6171. SparseArraySegment<T>* startSeg = SparseArraySegment<T>::From(pArr->head);
  6172. const uint32 limit = start + deleteLen;
  6173. uint32 rightLimit;
  6174. if (UInt32Math::Add(startSeg->left, startSeg->size, &rightLimit))
  6175. {
  6176. rightLimit = JavascriptArray::MaxArrayLength;
  6177. }
  6178. // Find out the segment to start delete
  6179. while (startSeg && (rightLimit <= start))
  6180. {
  6181. savePrev = startSeg;
  6182. prevPrevSeg = prevSeg;
  6183. prevSeg = &startSeg->next;
  6184. startSeg = SparseArraySegment<T>::From(startSeg->next);
  6185. if (startSeg)
  6186. {
  6187. if (UInt32Math::Add(startSeg->left, startSeg->size, &rightLimit))
  6188. {
  6189. rightLimit = JavascriptArray::MaxArrayLength;
  6190. }
  6191. }
  6192. }
  6193. bool hasInlineSegment = JavascriptArray::IsInlineSegment(startSeg, pArr);
  6194. if (startSeg)
  6195. {
  6196. // Delete Phase
  6197. if (startSeg->left <= start && (startSeg->left + startSeg->length) >= limit)
  6198. {
  6199. // All splice happens in one segment.
  6200. SparseArraySegmentBase *nextSeg = startSeg->next;
  6201. // Splice the segment first, which might OOM throw but the array would be intact.
  6202. JavascriptArray::ArraySegmentSpliceHelper(pnewArr, (SparseArraySegment<T>*)startSeg, (SparseArraySegment<T>**)prevSeg, start, deleteLen, insertArgs, insertLen, recycler);
  6203. while (nextSeg)
  6204. {
  6205. // adjust next segments left
  6206. nextSeg->left = nextSeg->left - deleteLen + insertLen;
  6207. if (nextSeg->next == nullptr)
  6208. {
  6209. nextSeg->EnsureSizeInBound();
  6210. }
  6211. nextSeg = nextSeg->next;
  6212. }
  6213. if (*prevSeg)
  6214. {
  6215. (*prevSeg)->EnsureSizeInBound();
  6216. }
  6217. return;
  6218. }
  6219. else
  6220. {
  6221. SparseArraySegment<T>* newHeadSeg = nullptr; // pnewArr->head is null
  6222. Field(SparseArraySegmentBase*)* prevNewHeadSeg = &pnewArr->head;
  6223. // delete till deleteLen and reuse segments for new array if it is possible.
  6224. // 3 steps -
  6225. //1. delete 1st segment (which may be partial delete)
  6226. // 2. delete next n complete segments
  6227. // 3. delete last segment (which again may be partial delete)
  6228. // Step (1) -- WOOB 1116297: When left >= start, step (1) is skipped, resulting in pNewArr->head->left != 0. We need to touch up pNewArr.
  6229. if (startSeg->left < start)
  6230. {
  6231. if (start < startSeg->left + startSeg->length)
  6232. {
  6233. uint32 headDeleteLen = startSeg->left + startSeg->length - start;
  6234. if (startSeg->next)
  6235. {
  6236. // We know the new segment will have a next segment, so allocate it as non-leaf.
  6237. newHeadSeg = SparseArraySegment<T>::template AllocateSegmentImpl<false>(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
  6238. }
  6239. else
  6240. {
  6241. newHeadSeg = SparseArraySegment<T>::AllocateSegment(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
  6242. }
  6243. newHeadSeg = SparseArraySegment<T>::CopySegment(recycler, newHeadSeg, 0, startSeg, start, headDeleteLen);
  6244. newHeadSeg->next = nullptr;
  6245. *prevNewHeadSeg = newHeadSeg;
  6246. prevNewHeadSeg = &newHeadSeg->next;
  6247. startSeg->Truncate(start);
  6248. }
  6249. savePrev = startSeg;
  6250. prevPrevSeg = prevSeg;
  6251. prevSeg = &startSeg->next;
  6252. startSeg = SparseArraySegment<T>::From(startSeg->next);
  6253. }
  6254. // Step (2) first we should do a hard copy if we have an inline head Segment
  6255. else if (hasInlineSegment && nullptr != startSeg)
  6256. {
  6257. // start should be in between left and left + length
  6258. if (startSeg->left <= start && start < startSeg->left + startSeg->length)
  6259. {
  6260. uint32 headDeleteLen = startSeg->left + startSeg->length - start;
  6261. if (startSeg->next)
  6262. {
  6263. // We know the new segment will have a next segment, so allocate it as non-leaf.
  6264. newHeadSeg = SparseArraySegment<T>::template AllocateSegmentImpl<false>(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
  6265. }
  6266. else
  6267. {
  6268. newHeadSeg = SparseArraySegment<T>::AllocateSegment(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
  6269. }
  6270. newHeadSeg = SparseArraySegment<T>::CopySegment(recycler, newHeadSeg, 0, startSeg, start, headDeleteLen);
  6271. *prevNewHeadSeg = newHeadSeg;
  6272. prevNewHeadSeg = &newHeadSeg->next;
  6273. // Remove the entire segment from the original array
  6274. *prevSeg = startSeg->next;
  6275. pArr->ClearElements(startSeg, 0);
  6276. startSeg = SparseArraySegment<T>::From(startSeg->next);
  6277. }
  6278. // if we have an inline head segment with 0 elements, remove it
  6279. else if (startSeg->left == 0 && startSeg->length == 0)
  6280. {
  6281. Assert(startSeg->size != 0);
  6282. *prevSeg = startSeg->next;
  6283. startSeg = SparseArraySegment<T>::From(startSeg->next);
  6284. }
  6285. }
  6286. // Step (2) proper
  6287. SparseArraySegmentBase *temp = nullptr;
  6288. while (startSeg && (startSeg->left + startSeg->length) <= limit)
  6289. {
  6290. temp = startSeg->next;
  6291. // move that entire segment to new array
  6292. startSeg->left = startSeg->left - start;
  6293. startSeg->next = nullptr;
  6294. *prevNewHeadSeg = startSeg;
  6295. prevNewHeadSeg = &startSeg->next;
  6296. // Remove the entire segment from the original array
  6297. *prevSeg = temp;
  6298. startSeg = (SparseArraySegment<T>*)temp;
  6299. }
  6300. // Step(2) above could delete the original head segment entirely, causing current head not
  6301. // starting from 0. Then if any of the following throw, we have a corrupted array. Need
  6302. // protection here.
  6303. bool dummyHeadNodeInserted = false;
  6304. if (!savePrev && (!startSeg || startSeg->left != 0))
  6305. {
  6306. Assert(pArr->head == startSeg);
  6307. pArr->EnsureHeadStartsFromZero<T>(recycler);
  6308. Assert(pArr->head && pArr->head->next == startSeg);
  6309. savePrev = pArr->head;
  6310. prevPrevSeg = prevSeg;
  6311. prevSeg = &pArr->head->next;
  6312. dummyHeadNodeInserted = true;
  6313. }
  6314. // Step (3)
  6315. if (startSeg && (startSeg->left < limit))
  6316. {
  6317. // copy the first part of the last segment to be deleted to new array
  6318. uint32 headDeleteLen = start + deleteLen - startSeg->left ;
  6319. newHeadSeg = SparseArraySegment<T>::AllocateSegment(recycler, startSeg->left - start, headDeleteLen, (SparseArraySegmentBase *)nullptr);
  6320. newHeadSeg = SparseArraySegment<T>::CopySegment(recycler, newHeadSeg, startSeg->left - start, startSeg, startSeg->left, headDeleteLen);
  6321. newHeadSeg->next = nullptr;
  6322. *prevNewHeadSeg = newHeadSeg;
  6323. prevNewHeadSeg = &newHeadSeg->next;
  6324. // move the last segment
  6325. MoveArray(startSeg->elements, startSeg->elements + headDeleteLen, startSeg->length - headDeleteLen);
  6326. startSeg->left = startSeg->left + headDeleteLen; // We are moving the left ahead to point to the right index
  6327. startSeg->length = startSeg->length - headDeleteLen;
  6328. startSeg->CheckLengthvsSize();
  6329. startSeg->Truncate(startSeg->left + startSeg->length);
  6330. startSeg->EnsureSizeInBound(); // Just truncated, size might exceed next.left
  6331. }
  6332. if (startSeg && ((startSeg->left - deleteLen + insertLen) == 0) && dummyHeadNodeInserted)
  6333. {
  6334. Assert(start + insertLen == 0);
  6335. // Remove the dummy head node to preserve array consistency.
  6336. pArr->head = startSeg;
  6337. savePrev = nullptr;
  6338. prevSeg = &pArr->head;
  6339. }
  6340. while (startSeg)
  6341. {
  6342. startSeg->left = startSeg->left - deleteLen + insertLen ;
  6343. if (startSeg->next == nullptr)
  6344. {
  6345. startSeg->EnsureSizeInBound();
  6346. }
  6347. startSeg = SparseArraySegment<T>::From(startSeg->next);
  6348. }
  6349. }
  6350. }
  6351. // The size of pnewArr head allocated in above step 1 might exceed next.left concatenated in step 2/3.
  6352. pnewArr->head->EnsureSizeInBound();
  6353. if (savePrev)
  6354. {
  6355. savePrev->EnsureSizeInBound();
  6356. }
  6357. // insert elements
  6358. if (insertLen > 0)
  6359. {
  6360. Assert(!JavascriptNativeIntArray::Is(pArr) && !JavascriptNativeFloatArray::Is(pArr));
  6361. // InsertPhase
  6362. SparseArraySegment<T> *segInsert = nullptr;
  6363. // see if we are just about the right of the previous segment
  6364. Assert(!savePrev || savePrev->left <= start);
  6365. if (savePrev && (start - savePrev->left < savePrev->size))
  6366. {
  6367. segInsert = (SparseArraySegment<T>*)savePrev;
  6368. uint32 spaceLeft = segInsert->size - (start - segInsert->left);
  6369. if(spaceLeft < insertLen)
  6370. {
  6371. SparseArraySegment<T> *oldSegInsert = segInsert;
  6372. bool isInlineSegment = JavascriptArray::IsInlineSegment(segInsert, pArr);
  6373. if (!segInsert->next)
  6374. {
  6375. segInsert = segInsert->GrowByMin(recycler, insertLen - spaceLeft);
  6376. }
  6377. else
  6378. {
  6379. segInsert = segInsert->GrowByMinMax(recycler, insertLen - spaceLeft, segInsert->next->left - segInsert->left - segInsert->size);
  6380. }
  6381. if (isInlineSegment)
  6382. {
  6383. pArr->ClearElements(oldSegInsert, 0);
  6384. }
  6385. }
  6386. *prevPrevSeg = segInsert;
  6387. segInsert->length = start + insertLen - segInsert->left;
  6388. segInsert->CheckLengthvsSize();
  6389. }
  6390. else
  6391. {
  6392. segInsert = SparseArraySegment<T>::AllocateSegment(recycler, start, insertLen, *prevSeg);
  6393. segInsert->next = *prevSeg;
  6394. *prevSeg = segInsert;
  6395. savePrev = segInsert;
  6396. }
  6397. uint32 relativeStart = start - segInsert->left;
  6398. // inserted elements starts at argument 3 of splice(start, deleteNumber, insertelem1, insertelem2, insertelem3, ...);
  6399. CopyArray(segInsert->elements + relativeStart, insertLen,
  6400. reinterpret_cast<const T*>(insertArgs), insertLen);
  6401. }
  6402. }
  6403. Var JavascriptArray::TryArraySplice(JavascriptArray* pArr, uint32 start, uint32 len, uint32 deleteLen,
  6404. Var* insertArgs, uint32 insertLen, ScriptContext *scriptContext)
  6405. {
  6406. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6407. Assert(pArr != nullptr);
  6408. RecyclableObject* newObj = nullptr;
  6409. Recycler *recycler = scriptContext->GetRecycler();
  6410. ::Math::RecordOverflowPolicy newLenOverflow;
  6411. uint32 newLen = UInt32Math::Add(len - deleteLen, insertLen, newLenOverflow); // new length of the array after splice
  6412. // If we have missing values then convert to not native array for now
  6413. // In future, we could support this scenario.
  6414. if (deleteLen == insertLen)
  6415. {
  6416. JS_REENTRANT(jsReentLock, pArr->FillFromPrototypes(start, start + deleteLen));
  6417. }
  6418. else if (len)
  6419. {
  6420. JS_REENTRANT(jsReentLock, pArr->FillFromPrototypes(start, len));
  6421. }
  6422. //
  6423. // If newLen overflowed, pre-process to prevent pushing sparse array segments or elements out of
  6424. // max array length, which would result in tons of index overflow and difficult to fix.
  6425. //
  6426. if (newLenOverflow.HasOverflowed())
  6427. {
  6428. pArr = EnsureNonNativeArray(pArr);
  6429. BigIndex dstIndex = MaxArrayLength;
  6430. uint32 maxInsertLen = MaxArrayLength - start;
  6431. if (insertLen > maxInsertLen)
  6432. {
  6433. // Copy overflowing insertArgs to properties
  6434. for (uint32 i = maxInsertLen; i < insertLen; i++)
  6435. {
  6436. pArr->GenericDirectSetItemAt(dstIndex, insertArgs[i]);
  6437. ++dstIndex;
  6438. }
  6439. insertLen = maxInsertLen; // update
  6440. // Truncate elements on the right to properties
  6441. if (start + deleteLen < len)
  6442. {
  6443. pArr->TruncateToProperties(dstIndex, start + deleteLen);
  6444. }
  6445. }
  6446. else
  6447. {
  6448. // Truncate would-overflow elements to properties
  6449. pArr->TruncateToProperties(dstIndex, MaxArrayLength - insertLen + deleteLen);
  6450. }
  6451. len = pArr->length; // update
  6452. newLen = len - deleteLen + insertLen;
  6453. Assert(newLen == MaxArrayLength);
  6454. }
  6455. if (insertArgs)
  6456. {
  6457. pArr = EnsureNonNativeArray(pArr);
  6458. }
  6459. bool isIntArray = false;
  6460. bool isFloatArray = false;
  6461. bool isBuiltinArrayCtor = true;
  6462. JavascriptArray *newArr = nullptr;
  6463. // Just dump the segment map on splice (before any possible allocation and throw)
  6464. pArr->ClearSegmentMap();
  6465. // If the source object is an Array exotic object (Array.isArray) we should try to load the constructor property
  6466. // and use it to construct the return object.
  6467. JS_REENTRANT(jsReentLock, newObj = ArraySpeciesCreate(pArr, deleteLen, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor));
  6468. if (newObj != nullptr)
  6469. {
  6470. pArr = EnsureNonNativeArray(pArr);
  6471. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  6472. if (JavascriptArray::Is(newObj))
  6473. {
  6474. #if ENABLE_COPYONACCESS_ARRAY
  6475. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
  6476. #endif
  6477. newArr = JavascriptArray::FromVar(newObj);
  6478. }
  6479. }
  6480. else
  6481. // This is the ES5 case, pArr['constructor'] doesn't exist, or pArr['constructor'] is the builtin Array constructor
  6482. {
  6483. pArr->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
  6484. newArr = CreateNewArrayHelper(deleteLen, isIntArray, isFloatArray, pArr, scriptContext);
  6485. #if ENABLE_COPYONACCESS_ARRAY
  6486. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  6487. #endif
  6488. }
  6489. // If return object is a JavascriptArray, we can use all the array splice helpers
  6490. if (newArr && isBuiltinArrayCtor && len == pArr->length)
  6491. {
  6492. // Code below has potential to throw due to OOM or SO. Just FailFast on those cases
  6493. AutoFailFastOnError failFastOnError;
  6494. // Array has a single segment (need not start at 0) and splice start lies in the range
  6495. // of that segment we optimize splice - Fast path.
  6496. if (pArr->IsSingleSegmentArray() && pArr->head->HasIndex(start))
  6497. {
  6498. SparseArraySegmentBase *oldHead = pArr->head;
  6499. bool isInlineSegment = JavascriptArray::IsInlineSegment(oldHead, pArr);
  6500. if (isIntArray)
  6501. {
  6502. ArraySegmentSpliceHelper<int32>(newArr, SparseArraySegment<int32>::From(pArr->head), (SparseArraySegment<int32>**)&pArr->head, start, deleteLen, insertArgs, insertLen, recycler);
  6503. }
  6504. else if (isFloatArray)
  6505. {
  6506. ArraySegmentSpliceHelper<double>(newArr, SparseArraySegment<double>::From(pArr->head), (SparseArraySegment<double>**)&pArr->head, start, deleteLen, insertArgs, insertLen, recycler);
  6507. }
  6508. else
  6509. {
  6510. ArraySegmentSpliceHelper<Var>(newArr, SparseArraySegment<Var>::From(pArr->head), (SparseArraySegment<Var>**)&pArr->head, start, deleteLen, insertArgs, insertLen, recycler);
  6511. }
  6512. if (isInlineSegment && oldHead != pArr->head)
  6513. {
  6514. pArr->ClearElements(oldHead, 0);
  6515. }
  6516. // Since the start index is within the bounds of the original array's head segment, it will not acquire any new
  6517. // missing values. If the original array had missing values in the head segment, some of them may have been
  6518. // copied into the array that will be returned; otherwise, the array that is returned will also not have any
  6519. // missing values.
  6520. newArr->SetHasNoMissingValues(pArr->HasNoMissingValues());
  6521. }
  6522. else
  6523. {
  6524. if (isIntArray)
  6525. {
  6526. ArraySpliceHelper<int32>(newArr, pArr, start, deleteLen, insertArgs, insertLen, scriptContext);
  6527. }
  6528. else if (isFloatArray)
  6529. {
  6530. ArraySpliceHelper<double>(newArr, pArr, start, deleteLen, insertArgs, insertLen, scriptContext);
  6531. }
  6532. else
  6533. {
  6534. ArraySpliceHelper<Var>(newArr, pArr, start, deleteLen, insertArgs, insertLen, scriptContext);
  6535. }
  6536. // This function currently does not track missing values in the head segment if there are multiple segments
  6537. pArr->SetHasNoMissingValues(false);
  6538. newArr->SetHasNoMissingValues(false);
  6539. }
  6540. if (isIntArray)
  6541. {
  6542. pArr->EnsureHeadStartsFromZero<int32>(recycler);
  6543. newArr->EnsureHeadStartsFromZero<int32>(recycler);
  6544. }
  6545. else if (isFloatArray)
  6546. {
  6547. pArr->EnsureHeadStartsFromZero<double>(recycler);
  6548. newArr->EnsureHeadStartsFromZero<double>(recycler);
  6549. }
  6550. else
  6551. {
  6552. pArr->EnsureHeadStartsFromZero<Var>(recycler);
  6553. newArr->EnsureHeadStartsFromZero<Var>(recycler);
  6554. }
  6555. pArr->InvalidateLastUsedSegment();
  6556. // it is possible for valueOf accessors for the start or deleteLen
  6557. // arguments to modify the size of the array. Since the resulting size of the array
  6558. // is based on the cached value of length, this might lead to us having to trim
  6559. // excess array segments at the end of the splice operation, which SetLength() will do.
  6560. // However, this is also slower than performing the simple length assignment, so we only
  6561. // do it if we can detect the array length changing.
  6562. if (pArr->length != len)
  6563. {
  6564. pArr->SetLength(newLen);
  6565. }
  6566. else
  6567. {
  6568. pArr->length = newLen;
  6569. }
  6570. if (newArr->length != deleteLen)
  6571. {
  6572. newArr->SetLength(deleteLen);
  6573. }
  6574. else
  6575. {
  6576. newArr->length = deleteLen;
  6577. }
  6578. failFastOnError.Completed();
  6579. newArr->InvalidateLastUsedSegment();
  6580. #ifdef VALIDATE_ARRAY
  6581. newArr->ValidateArray();
  6582. pArr->ValidateArray();
  6583. #endif
  6584. if (newLenOverflow.HasOverflowed())
  6585. {
  6586. // ES5 15.4.4.12 16: If new len overflowed, SetLength throws
  6587. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  6588. }
  6589. return newArr;
  6590. }
  6591. if (newLenOverflow.HasOverflowed())
  6592. {
  6593. JS_REENTRANT_UNLOCK(jsReentLock, return ObjectSpliceHelper<uint64>(pArr, len, start, deleteLen, insertArgs, insertLen, scriptContext, newObj));
  6594. }
  6595. else // Use uint32 version if no overflow
  6596. {
  6597. JS_REENTRANT_UNLOCK(jsReentLock, return ObjectSpliceHelper<uint32>(pArr, len, start, deleteLen, insertArgs, insertLen, scriptContext, newObj));
  6598. }
  6599. }
  6600. template<typename T>
  6601. RecyclableObject* JavascriptArray::ObjectSpliceHelper(RecyclableObject* pObj, T len, T start,
  6602. T deleteLen, Var* insertArgs, uint32 insertLen, ScriptContext *scriptContext, RecyclableObject* pNewObj)
  6603. {
  6604. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6605. JavascriptArray *pnewArr = nullptr;
  6606. if (pNewObj == nullptr)
  6607. {
  6608. JS_REENTRANT(jsReentLock, pNewObj = ArraySpeciesCreate(pObj, deleteLen, scriptContext));
  6609. if (pNewObj == nullptr)
  6610. {
  6611. if (deleteLen > UINT_MAX)
  6612. {
  6613. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  6614. }
  6615. pnewArr = scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(deleteLen));
  6616. pnewArr->EnsureHead<Var>();
  6617. pNewObj = pnewArr;
  6618. }
  6619. }
  6620. if (JavascriptArray::Is(pNewObj))
  6621. {
  6622. #if ENABLE_COPYONACCESS_ARRAY
  6623. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pNewObj);
  6624. #endif
  6625. pnewArr = JavascriptArray::FromVar(pNewObj);
  6626. }
  6627. // copy elements to delete to new array
  6628. if (pnewArr != nullptr)
  6629. {
  6630. for (uint32 i = 0; i < deleteLen; i++)
  6631. {
  6632. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(pObj, start + i));
  6633. if (hasItem)
  6634. {
  6635. JS_REENTRANT(jsReentLock, Var element = JavascriptOperators::GetItem(pObj, start + i, scriptContext));
  6636. pnewArr->SetItem(i, element, PropertyOperation_None);
  6637. }
  6638. }
  6639. }
  6640. else
  6641. {
  6642. BigIndex k = 0u;
  6643. for (T i = 0u; i < deleteLen; i++)
  6644. {
  6645. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(pObj, start + i));
  6646. if (hasItem)
  6647. {
  6648. Var element = nullptr;
  6649. JS_REENTRANT(jsReentLock, element = JavascriptOperators::GetItem(pObj, start + i, scriptContext),
  6650. ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(pNewObj, k, element), scriptContext, k));
  6651. }
  6652. ++k;
  6653. }
  6654. }
  6655. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.splice"));
  6656. // Now we need reserve room if it is necessary
  6657. if (insertLen > deleteLen) // Might overflow max array length
  6658. {
  6659. // Unshift [start + deleteLen, len) to start + insertLen
  6660. JS_REENTRANT(jsReentLock, Unshift<BigIndex, T>(pObj, start + insertLen, start + deleteLen, len, scriptContext));
  6661. }
  6662. else if (insertLen < deleteLen) // Won't overflow max array length
  6663. {
  6664. T j = 0;
  6665. for (T i = start + deleteLen; i < len; i++)
  6666. {
  6667. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(pObj, i));
  6668. if (hasItem)
  6669. {
  6670. Var element = nullptr;
  6671. JS_REENTRANT(jsReentLock, element = JavascriptOperators::GetItem(pObj, i, scriptContext),
  6672. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(pObj, pObj, start + insertLen + j, element, scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  6673. }
  6674. else
  6675. {
  6676. JS_REENTRANT(jsReentLock,
  6677. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(pObj, start + insertLen + j, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  6678. }
  6679. j++;
  6680. }
  6681. // Clean up the rest
  6682. for (T i = len; i > len - deleteLen + insertLen; i--)
  6683. {
  6684. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(pObj, i - 1, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  6685. }
  6686. }
  6687. if (insertLen > 0)
  6688. {
  6689. T dstIndex = start; // insert index might overflow max array length
  6690. for (uint32 i = 0; i < insertLen; i++)
  6691. {
  6692. JS_REENTRANT(jsReentLock,
  6693. h.ThrowTypeErrorOnFailure(IndexTrace<BigIndex>::SetItem(pObj, dstIndex, insertArgs[i], PropertyOperation_ThrowIfNotExtensible)));
  6694. ++dstIndex;
  6695. }
  6696. }
  6697. // Set up new length
  6698. T newLen = T(len - deleteLen) + insertLen;
  6699. JS_REENTRANT(jsReentLock,
  6700. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(pObj, pObj, PropertyIds::length, IndexTrace<BigIndex>::ToNumber(newLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)),
  6701. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(pNewObj, pNewObj, PropertyIds::length, IndexTrace<BigIndex>::ToNumber(deleteLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  6702. #ifdef VALIDATE_ARRAY
  6703. if (pnewArr)
  6704. {
  6705. pnewArr->ValidateArray();
  6706. }
  6707. #endif
  6708. return pNewObj;
  6709. }
  6710. Var JavascriptArray::EntryToLocaleString(RecyclableObject* function, CallInfo callInfo, ...)
  6711. {
  6712. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  6713. ARGUMENTS(args, callInfo);
  6714. ScriptContext* scriptContext = function->GetScriptContext();
  6715. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6716. Assert(!(callInfo.Flags & CallFlags_New));
  6717. if (args.Info.Count == 0)
  6718. {
  6719. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedObject, _u("Array.prototype.toLocaleString"));
  6720. }
  6721. if (JavascriptArray::IsDirectAccessArray(args[0]))
  6722. {
  6723. JavascriptArray* arr = JavascriptArray::FromVar(args[0]);
  6724. JS_REENTRANT_UNLOCK(jsReentLock, return ToLocaleString(arr, scriptContext));
  6725. }
  6726. else
  6727. {
  6728. if (TypedArrayBase::IsDetachedTypedArray(args[0]))
  6729. {
  6730. JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("Array.prototype.toLocalString"));
  6731. }
  6732. RecyclableObject* obj = nullptr;
  6733. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  6734. {
  6735. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.toLocaleString"));
  6736. }
  6737. JS_REENTRANT_UNLOCK(jsReentLock, return ToLocaleString(obj, scriptContext));
  6738. }
  6739. }
  6740. //
  6741. // Unshift object elements [start, end) to toIndex, asserting toIndex > start.
  6742. //
  6743. template<typename T, typename P>
  6744. void JavascriptArray::Unshift(RecyclableObject* obj, const T& toIndex, P start, P end, ScriptContext* scriptContext)
  6745. {
  6746. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6747. typedef IndexTrace<T> index_trace;
  6748. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.unshift"));
  6749. if (start < end)
  6750. {
  6751. T newEnd = (end - start - 1);// newEnd - 1
  6752. T dst = toIndex + newEnd;
  6753. for (P i = end; i > start; --i)
  6754. {
  6755. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, i - 1));
  6756. if (hasItem)
  6757. {
  6758. Var element = nullptr;
  6759. JS_REENTRANT(jsReentLock, element = JavascriptOperators::GetItem(obj, i - 1, scriptContext),
  6760. h.ThrowTypeErrorOnFailure(index_trace::SetItem(obj, dst, element, PropertyOperation_ThrowIfNotExtensible)));
  6761. }
  6762. else
  6763. {
  6764. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(index_trace::DeleteItem(obj, dst, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  6765. }
  6766. --dst;
  6767. }
  6768. }
  6769. }
  6770. template<typename T>
  6771. void JavascriptArray::GrowArrayHeadHelperForUnshift(JavascriptArray* pArr, uint32 unshiftElements, ScriptContext * scriptContext)
  6772. {
  6773. SparseArraySegmentBase* nextToHeadSeg = pArr->head->next;
  6774. Recycler* recycler = scriptContext->GetRecycler();
  6775. SparseArraySegmentBase *oldHead = pArr->head;
  6776. bool isInlineSegment = JavascriptArray::IsInlineSegment(oldHead, pArr);
  6777. if (nextToHeadSeg == nullptr)
  6778. {
  6779. pArr->EnsureHead<T>();
  6780. pArr->head = SparseArraySegment<T>::From(pArr->head)->GrowByMin(recycler, unshiftElements);
  6781. }
  6782. else
  6783. {
  6784. pArr->head = SparseArraySegment<T>::From(pArr->head)->GrowByMinMax(recycler, unshiftElements, ((nextToHeadSeg->left + unshiftElements) - pArr->head->left - pArr->head->size));
  6785. }
  6786. if (isInlineSegment)
  6787. {
  6788. pArr->ClearElements(oldHead, 0);
  6789. }
  6790. }
  6791. template<typename T>
  6792. void JavascriptArray::UnshiftHelper(JavascriptArray* pArr, uint32 unshiftElements, Js::Var * elements)
  6793. {
  6794. SparseArraySegment<T>* head = SparseArraySegment<T>::From(pArr->head);
  6795. // Make enough room in the head segment to insert new elements at the front
  6796. MoveArray(head->elements + unshiftElements, head->elements, pArr->head->length);
  6797. uint32 oldHeadLength = head->length;
  6798. head->length += unshiftElements;
  6799. head->CheckLengthvsSize();
  6800. /* Set head segment as the last used segment */
  6801. pArr->InvalidateLastUsedSegment();
  6802. bool hasNoMissingValues = pArr->HasNoMissingValues();
  6803. /* Set HasNoMissingValues to false -> Since we shifted elements right, we might have missing values after the memmove */
  6804. if(unshiftElements > oldHeadLength)
  6805. {
  6806. pArr->SetHasNoMissingValues(false);
  6807. }
  6808. #if ENABLE_PROFILE_INFO
  6809. pArr->FillFromArgs(unshiftElements, 0, elements, nullptr, true/*dontCreateNewArray*/);
  6810. #else
  6811. pArr->FillFromArgs(unshiftElements, 0, elements, true/*dontCreateNewArray*/);
  6812. #endif
  6813. // Setting back to the old value
  6814. pArr->SetHasNoMissingValues(hasNoMissingValues);
  6815. }
  6816. Var JavascriptArray::EntryUnshift(RecyclableObject* function, CallInfo callInfo, ...)
  6817. {
  6818. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  6819. ARGUMENTS(args, callInfo);
  6820. ScriptContext* scriptContext = function->GetScriptContext();
  6821. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6822. Assert(!(callInfo.Flags & CallFlags_New));
  6823. Var res = scriptContext->GetLibrary()->GetUndefined();
  6824. if (args.Info.Count == 0)
  6825. {
  6826. return res;
  6827. }
  6828. JavascriptArray * pArr = nullptr;
  6829. if (JavascriptArray::Is(args[0])
  6830. && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
  6831. {
  6832. #if ENABLE_COPYONACCESS_ARRAY
  6833. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
  6834. #endif
  6835. pArr = JavascriptArray::FromVar(args[0]);
  6836. }
  6837. uint32 unshiftElements = args.Info.Count - 1;
  6838. // forceCheckProtoChain - since the array expand to accommodate new items thus we have to check if we have accessor on the proto chain.
  6839. bool useNoSideEffectUnshift = pArr != nullptr && (unshiftElements == 0 || !HasAnyES5ArrayInPrototypeChain(pArr, true /*forceCheckProtoChain*/));
  6840. if (useNoSideEffectUnshift)
  6841. {
  6842. if (unshiftElements > 0)
  6843. {
  6844. uint32 length = pArr->length;
  6845. if (pArr->IsFillFromPrototypes())
  6846. {
  6847. JS_REENTRANT(jsReentLock, pArr->FillFromPrototypes(0, pArr->length)); // We need find all missing value from [[proto]] object
  6848. }
  6849. // As we have already established that the FillFromPrototype should not change the bound of the array.
  6850. if (length != pArr->length)
  6851. {
  6852. Js::Throw::FatalInternalError();
  6853. }
  6854. // Pre-process: truncate overflowing elements to properties
  6855. bool newLenOverflowed = false;
  6856. uint32 maxLen = MaxArrayLength - unshiftElements;
  6857. if (pArr->length > maxLen)
  6858. {
  6859. newLenOverflowed = true;
  6860. // Ensure the array is non-native when overflow happens
  6861. EnsureNonNativeArray(pArr);
  6862. pArr->TruncateToProperties(MaxArrayLength, maxLen);
  6863. Assert(pArr->length + unshiftElements == MaxArrayLength);
  6864. }
  6865. pArr->ClearSegmentMap(); // Dump segmentMap on unshift (before any possible allocation and throw)
  6866. Assert(pArr->length <= MaxArrayLength - unshiftElements);
  6867. bool isIntArray = false;
  6868. bool isFloatArray = false;
  6869. if (JavascriptNativeIntArray::Is(pArr))
  6870. {
  6871. isIntArray = true;
  6872. }
  6873. else if (JavascriptNativeFloatArray::Is(pArr))
  6874. {
  6875. isFloatArray = true;
  6876. }
  6877. // If we need to grow head segment and there is already a next segment, then allocate the new head segment upfront
  6878. // If there is OOM in array allocation, then array consistency is maintained.
  6879. if (pArr->head->size < pArr->head->length + unshiftElements)
  6880. {
  6881. if (isIntArray)
  6882. {
  6883. GrowArrayHeadHelperForUnshift<int32>(pArr, unshiftElements, scriptContext);
  6884. }
  6885. else if (isFloatArray)
  6886. {
  6887. GrowArrayHeadHelperForUnshift<double>(pArr, unshiftElements, scriptContext);
  6888. }
  6889. else
  6890. {
  6891. GrowArrayHeadHelperForUnshift<Var>(pArr, unshiftElements, scriptContext);
  6892. }
  6893. }
  6894. SparseArraySegmentBase* renumberSeg = pArr->head->next;
  6895. while (renumberSeg)
  6896. {
  6897. renumberSeg->left += unshiftElements;
  6898. if (renumberSeg->next == nullptr)
  6899. {
  6900. // last segment can shift its left + size beyond MaxArrayLength, so truncate if so
  6901. renumberSeg->EnsureSizeInBound();
  6902. }
  6903. renumberSeg = renumberSeg->next;
  6904. }
  6905. try
  6906. {
  6907. if (isIntArray)
  6908. {
  6909. UnshiftHelper<int32>(pArr, unshiftElements, args.Values);
  6910. }
  6911. else if (isFloatArray)
  6912. {
  6913. UnshiftHelper<double>(pArr, unshiftElements, args.Values);
  6914. }
  6915. else
  6916. {
  6917. UnshiftHelper<Var>(pArr, unshiftElements, args.Values);
  6918. }
  6919. }
  6920. catch (...)
  6921. {
  6922. Js::Throw::FatalInternalError();
  6923. }
  6924. pArr->InvalidateLastUsedSegment();
  6925. pArr->length += unshiftElements;
  6926. #ifdef VALIDATE_ARRAY
  6927. pArr->ValidateArray();
  6928. #endif
  6929. if (newLenOverflowed) // ES5: throw if new "length" exceeds max array length
  6930. {
  6931. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  6932. }
  6933. }
  6934. res = JavascriptNumber::ToVar(pArr->length, scriptContext);
  6935. }
  6936. else
  6937. {
  6938. RecyclableObject* dynamicObject = nullptr;
  6939. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &dynamicObject))
  6940. {
  6941. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.unshift"));
  6942. }
  6943. JS_REENTRANT(jsReentLock, BigIndex length = OP_GetLength(dynamicObject, scriptContext));
  6944. if (unshiftElements > 0)
  6945. {
  6946. uint32 MaxSpaceUint32 = MaxArrayLength - unshiftElements;
  6947. // Note: end will always be a smallIndex either it is less than length in which case it is MaxSpaceUint32
  6948. // or MaxSpaceUint32 is greater than length meaning length is a uint32 number
  6949. BigIndex end = length > MaxSpaceUint32 ? MaxSpaceUint32 : length;
  6950. if (end < length)
  6951. {
  6952. // Unshift [end, length) to MaxArrayLength
  6953. // MaxArrayLength + (length - MaxSpaceUint32 - 1) = length + unshiftElements -1
  6954. if (length.IsSmallIndex())
  6955. {
  6956. JS_REENTRANT(jsReentLock, Unshift<BigIndex>(dynamicObject, MaxArrayLength, end.GetSmallIndex(), length.GetSmallIndex(), scriptContext));
  6957. }
  6958. else
  6959. {
  6960. JS_REENTRANT(jsReentLock, Unshift<BigIndex, uint64>(dynamicObject, MaxArrayLength, (uint64)end.GetSmallIndex(), length.GetBigIndex(), scriptContext));
  6961. }
  6962. }
  6963. // Unshift [0, end) to unshiftElements
  6964. // unshiftElements + (MaxSpaceUint32 - 0 - 1) = MaxArrayLength -1 therefore this unshift covers up to MaxArrayLength - 1
  6965. JS_REENTRANT(jsReentLock, Unshift<uint32>(dynamicObject, unshiftElements, (uint32)0, end.GetSmallIndex(), scriptContext));
  6966. for (uint32 i = 0; i < unshiftElements; i++)
  6967. {
  6968. JS_REENTRANT(jsReentLock,
  6969. JavascriptOperators::SetItem(dynamicObject, dynamicObject, i, args[i + 1], scriptContext, PropertyOperation_ThrowIfNotExtensible, true));
  6970. }
  6971. }
  6972. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.unshift"));
  6973. //ES6 - update 'length' even if unshiftElements == 0;
  6974. BigIndex newLen = length + unshiftElements;
  6975. res = JavascriptNumber::ToVar(newLen.IsSmallIndex() ? newLen.GetSmallIndex() : newLen.GetBigIndex(), scriptContext);
  6976. JS_REENTRANT(jsReentLock,
  6977. BOOL setLength = JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, res, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  6978. h.ThrowTypeErrorOnFailure(setLength);
  6979. }
  6980. return res;
  6981. }
  6982. Var JavascriptArray::EntryToString(RecyclableObject* function, CallInfo callInfo, ...)
  6983. {
  6984. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  6985. ARGUMENTS(args, callInfo);
  6986. ScriptContext* scriptContext = function->GetScriptContext();
  6987. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6988. Assert(!(callInfo.Flags & CallFlags_New));
  6989. if (args.Info.Count == 0)
  6990. {
  6991. JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedObject);
  6992. }
  6993. // ES5 15.4.4.2: call join, or built-in Object.prototype.toString
  6994. RecyclableObject* obj = nullptr;
  6995. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  6996. {
  6997. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.toString"));
  6998. }
  6999. // In ES5 we could be calling a user defined join, even on array. We must [[Get]] join at runtime.
  7000. JS_REENTRANT(jsReentLock, Var join = JavascriptOperators::GetProperty(obj, PropertyIds::join, scriptContext));
  7001. if (JavascriptConversion::IsCallable(join))
  7002. {
  7003. RecyclableObject* func = RecyclableObject::FromVar(join);
  7004. // We need to record implicit call here, because marked the Array.toString as no side effect,
  7005. // but if we call user code here which may have side effect
  7006. ThreadContext * threadContext = scriptContext->GetThreadContext();
  7007. JS_REENTRANT(jsReentLock,
  7008. Var result = threadContext->ExecuteImplicitCall(func, ImplicitCall_ToPrimitive, [=]() -> Js::Var
  7009. {
  7010. // Stack object should have a pre-op bail on implicit call. We shouldn't see them here.
  7011. Assert(!ThreadContext::IsOnStack(obj));
  7012. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7013. CallFlags flags = CallFlags_Value;
  7014. return CALL_FUNCTION(threadContext, func, CallInfo(flags, 1), obj);
  7015. }));
  7016. if(!result)
  7017. {
  7018. // There was an implicit call and implicit calls are disabled. This would typically cause a bailout.
  7019. Assert(threadContext->IsDisableImplicitCall());
  7020. result = scriptContext->GetLibrary()->GetNull();
  7021. }
  7022. return result;
  7023. }
  7024. else
  7025. {
  7026. // call built-in Object.prototype.toString
  7027. JS_REENTRANT_UNLOCK(jsReentLock,
  7028. return CALL_ENTRYPOINT(scriptContext->GetThreadContext(), JavascriptObject::EntryToString, function, CallInfo(1), obj));
  7029. }
  7030. }
  7031. #if DEBUG
  7032. BOOL JavascriptArray::GetIndex(const char16* propName, uint32 *pIndex)
  7033. {
  7034. uint32 lu, luDig;
  7035. int32 cch = (int32)wcslen(propName);
  7036. char16* pch = const_cast<char16 *>(propName);
  7037. lu = *pch - '0';
  7038. if (lu > 9)
  7039. return FALSE;
  7040. if (0 == lu)
  7041. {
  7042. *pIndex = 0;
  7043. return 1 == cch;
  7044. }
  7045. while ((luDig = *++pch - '0') < 10)
  7046. {
  7047. // If we overflow 32 bits, ignore the item
  7048. if (lu > 0x19999999)
  7049. return FALSE;
  7050. lu *= 10;
  7051. if(lu > (ULONG_MAX - luDig))
  7052. return FALSE;
  7053. lu += luDig;
  7054. }
  7055. if (pch - propName != cch)
  7056. return FALSE;
  7057. if (lu == JavascriptArray::InvalidIndex)
  7058. {
  7059. // 0xFFFFFFFF is not treated as an array index so that the length can be
  7060. // capped at 32 bits.
  7061. return FALSE;
  7062. }
  7063. *pIndex = lu;
  7064. return TRUE;
  7065. }
  7066. #endif
  7067. JavascriptString* JavascriptArray::GetLocaleSeparator(ScriptContext* scriptContext)
  7068. {
  7069. #ifdef ENABLE_GLOBALIZATION
  7070. LCID lcid = GetUserDefaultLCID();
  7071. int count = 0;
  7072. char16 szSeparator[6];
  7073. // According to the document for GetLocaleInfo this is a sufficient buffer size.
  7074. count = GetLocaleInfoW(lcid, LOCALE_SLIST, szSeparator, 5);
  7075. if( !count)
  7076. {
  7077. AssertMsg(FALSE, "GetLocaleInfo failed");
  7078. return scriptContext->GetLibrary()->GetCommaSpaceDisplayString();
  7079. }
  7080. else
  7081. {
  7082. // Append ' ' if necessary
  7083. if( count < 2 || szSeparator[count-2] != ' ')
  7084. {
  7085. szSeparator[count-1] = ' ';
  7086. szSeparator[count] = '\0';
  7087. }
  7088. return JavascriptString::NewCopyBuffer(szSeparator, count, scriptContext);
  7089. }
  7090. #else
  7091. // xplat-todo: Support locale-specific seperator
  7092. return scriptContext->GetLibrary()->GetCommaSpaceDisplayString();
  7093. #endif
  7094. }
  7095. template <typename T>
  7096. JavascriptString* JavascriptArray::ToLocaleString(T* arr, ScriptContext* scriptContext)
  7097. {
  7098. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7099. uint32 length = 0;
  7100. if (TypedArrayBase::Is(arr))
  7101. {
  7102. // For a TypedArray use the actual length of the array.
  7103. length = TypedArrayBase::FromVar(arr)->GetLength();
  7104. }
  7105. else
  7106. {
  7107. //For anything else, use the "length" property if present.
  7108. JS_REENTRANT(jsReentLock, length = ItemTrace<T>::GetLength(arr, scriptContext));
  7109. }
  7110. if (length == 0 || scriptContext->CheckObject(arr))
  7111. {
  7112. return scriptContext->GetLibrary()->GetEmptyString();
  7113. }
  7114. JavascriptString* res = scriptContext->GetLibrary()->GetEmptyString();
  7115. bool pushedObject = false;
  7116. TryFinally([&]()
  7117. {
  7118. scriptContext->PushObject(arr);
  7119. pushedObject = true;
  7120. Var element = nullptr;
  7121. JS_REENTRANT(jsReentLock, BOOL gotItem = ItemTrace<T>::GetItem(arr, 0, &element, scriptContext));
  7122. if (gotItem)
  7123. {
  7124. JS_REENTRANT(jsReentLock, res = JavascriptArray::ToLocaleStringHelper(element, scriptContext));
  7125. }
  7126. if (length > 1)
  7127. {
  7128. JavascriptString* separator = GetLocaleSeparator(scriptContext);
  7129. for (uint32 i = 1; i < length; i++)
  7130. {
  7131. res = JavascriptString::Concat(res, separator);
  7132. JS_REENTRANT(jsReentLock, gotItem = ItemTrace<T>::GetItem(arr, i, &element, scriptContext));
  7133. if (gotItem)
  7134. {
  7135. JS_REENTRANT(jsReentLock, res = JavascriptString::Concat(res, JavascriptArray::ToLocaleStringHelper(element, scriptContext)));
  7136. }
  7137. }
  7138. }
  7139. },
  7140. [&](bool/*hasException*/)
  7141. {
  7142. if (pushedObject)
  7143. {
  7144. Var top = scriptContext->PopObject();
  7145. AssertMsg(top == arr, "Unmatched operation stack");
  7146. }
  7147. });
  7148. if (res == nullptr)
  7149. {
  7150. res = scriptContext->GetLibrary()->GetEmptyString();
  7151. }
  7152. return res;
  7153. }
  7154. Var JavascriptArray::EntryIsArray(RecyclableObject* function, CallInfo callInfo, ...)
  7155. {
  7156. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7157. ARGUMENTS(args, callInfo);
  7158. ScriptContext* scriptContext = function->GetScriptContext();
  7159. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7160. Assert(!(callInfo.Flags & CallFlags_New));
  7161. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Constructor_isArray);
  7162. if (args.Info.Count < 2)
  7163. {
  7164. return scriptContext->GetLibrary()->GetFalse();
  7165. }
  7166. #if ENABLE_COPYONACCESS_ARRAY
  7167. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[1]);
  7168. #endif
  7169. if (JavascriptOperators::IsArray(args[1]))
  7170. {
  7171. return scriptContext->GetLibrary()->GetTrue();
  7172. }
  7173. return scriptContext->GetLibrary()->GetFalse();
  7174. }
  7175. ///----------------------------------------------------------------------------
  7176. /// Find() calls the given predicate callback on each element of the array, in
  7177. /// order, and returns the first element that makes the predicate return true,
  7178. /// as described in (ES6.0: S22.1.3.8).
  7179. ///----------------------------------------------------------------------------
  7180. Var JavascriptArray::EntryFind(RecyclableObject* function, CallInfo callInfo, ...)
  7181. {
  7182. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7183. ARGUMENTS(args, callInfo);
  7184. ScriptContext* scriptContext = function->GetScriptContext();
  7185. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7186. Assert(!(callInfo.Flags & CallFlags_New));
  7187. if (args.Info.Count == 0)
  7188. {
  7189. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.find"));
  7190. }
  7191. int64 length;
  7192. JavascriptArray * pArr = nullptr;
  7193. RecyclableObject* obj = nullptr;
  7194. JS_REENTRANT_UNLOCK(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.find"), &pArr, &obj, &length));
  7195. return JavascriptArray::FindHelper<false>(pArr, nullptr, obj, length, args, scriptContext);
  7196. }
  7197. template <bool findIndex>
  7198. Var JavascriptArray::FindHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
  7199. {
  7200. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7201. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  7202. {
  7203. // typedArrayBase is only non-null if and only if we came here via the TypedArray entrypoint
  7204. if (typedArrayBase != nullptr)
  7205. {
  7206. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, findIndex ? _u("[TypedArray].prototype.findIndex") : _u("[TypedArray].prototype.find"));
  7207. }
  7208. else
  7209. {
  7210. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, findIndex ? _u("Array.prototype.findIndex") : _u("Array.prototype.find"));
  7211. }
  7212. }
  7213. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  7214. Var thisArg;
  7215. if (args.Info.Count > 2)
  7216. {
  7217. thisArg = args[2];
  7218. }
  7219. else
  7220. {
  7221. thisArg = scriptContext->GetLibrary()->GetUndefined();
  7222. }
  7223. // If we came from Array.prototype.find/findIndex and source object is not a JavascriptArray, source could be a TypedArray
  7224. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  7225. {
  7226. typedArrayBase = TypedArrayBase::FromVar(obj);
  7227. }
  7228. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7229. CallFlags flags = CallFlags_Value;
  7230. Var element = nullptr;
  7231. Var testResult = nullptr;
  7232. if (pArr)
  7233. {
  7234. Var undefined = scriptContext->GetLibrary()->GetUndefined();
  7235. Assert(length <= UINT_MAX);
  7236. for (uint32 k = 0; k < (uint32)length; k++)
  7237. {
  7238. element = undefined;
  7239. JS_REENTRANT(jsReentLock, pArr->DirectGetItemAtFull(k, &element));
  7240. Var index = JavascriptNumber::ToVar(k, scriptContext);
  7241. JS_REENTRANT(jsReentLock,
  7242. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7243. element,
  7244. index,
  7245. pArr));
  7246. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7247. {
  7248. return findIndex ? index : element;
  7249. }
  7250. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  7251. // we will process the rest of the array elements like an ES5Array.
  7252. if (!JavascriptArray::Is(obj))
  7253. {
  7254. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  7255. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FindObjectHelper<findIndex>(obj, length, k + 1, callBackFn, thisArg, scriptContext));
  7256. }
  7257. }
  7258. }
  7259. else if (typedArrayBase)
  7260. {
  7261. Assert(length <= UINT_MAX);
  7262. for (uint32 k = 0; k < (uint32)length; k++)
  7263. {
  7264. // Spec does not ask to call HasItem, so we need to go to visit the whole length
  7265. element = typedArrayBase->DirectGetItem(k);
  7266. Var index = JavascriptNumber::ToVar(k, scriptContext);
  7267. JS_REENTRANT(jsReentLock,
  7268. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7269. element,
  7270. index,
  7271. typedArrayBase));
  7272. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7273. {
  7274. return findIndex ? index : element;
  7275. }
  7276. }
  7277. }
  7278. else
  7279. {
  7280. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FindObjectHelper<findIndex>(obj, length, 0u, callBackFn, thisArg, scriptContext));
  7281. }
  7282. return findIndex ? JavascriptNumber::ToVar(-1, scriptContext) : scriptContext->GetLibrary()->GetUndefined();
  7283. }
  7284. template <bool findIndex>
  7285. Var JavascriptArray::FindObjectHelper(RecyclableObject* obj, int64 length, int64 start, RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
  7286. {
  7287. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7288. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7289. CallFlags flags = CallFlags_Value;
  7290. Var element = nullptr;
  7291. Var testResult = nullptr;
  7292. for (int64 k = start; k < length; k++)
  7293. {
  7294. JS_REENTRANT(jsReentLock, element = JavascriptOperators::GetItem(obj, (uint64)k, scriptContext));
  7295. Var index = JavascriptNumber::ToVar(k, scriptContext);
  7296. JS_REENTRANT(jsReentLock,
  7297. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7298. element,
  7299. index,
  7300. obj));
  7301. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7302. {
  7303. return findIndex ? index : element;
  7304. }
  7305. }
  7306. return findIndex ? JavascriptNumber::ToVar(-1, scriptContext) : scriptContext->GetLibrary()->GetUndefined();
  7307. }
  7308. ///----------------------------------------------------------------------------
  7309. /// FindIndex() calls the given predicate callback on each element of the
  7310. /// array, in order, and returns the index of the first element that makes the
  7311. /// predicate return true, as described in (ES6.0: S22.1.3.9).
  7312. ///----------------------------------------------------------------------------
  7313. Var JavascriptArray::EntryFindIndex(RecyclableObject* function, CallInfo callInfo, ...)
  7314. {
  7315. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7316. ARGUMENTS(args, callInfo);
  7317. ScriptContext* scriptContext = function->GetScriptContext();
  7318. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7319. Assert(!(callInfo.Flags & CallFlags_New));
  7320. if (args.Info.Count == 0)
  7321. {
  7322. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.findIndex"));
  7323. }
  7324. int64 length;
  7325. JavascriptArray * pArr = nullptr;
  7326. RecyclableObject* obj = nullptr;
  7327. JS_REENTRANT_UNLOCK(jsReentLock,
  7328. TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.findIndex"), &pArr, &obj, &length));
  7329. return JavascriptArray::FindHelper<true>(pArr, nullptr, obj, length, args, scriptContext);
  7330. }
  7331. ///----------------------------------------------------------------------------
  7332. /// Entries() returns a new ArrayIterator object configured to return key-
  7333. /// value pairs matching the elements of the this array/array-like object,
  7334. /// as described in (ES6.0: S22.1.3.4).
  7335. ///----------------------------------------------------------------------------
  7336. Var JavascriptArray::EntryEntries(RecyclableObject* function, CallInfo callInfo, ...)
  7337. {
  7338. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7339. ARGUMENTS(args, callInfo);
  7340. ScriptContext* scriptContext = function->GetScriptContext();
  7341. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7342. Assert(!(callInfo.Flags & CallFlags_New));
  7343. if (args.Info.Count == 0)
  7344. {
  7345. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.entries"));
  7346. }
  7347. RecyclableObject* thisObj = nullptr;
  7348. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &thisObj))
  7349. {
  7350. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.entries"));
  7351. }
  7352. #if ENABLE_COPYONACCESS_ARRAY
  7353. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(thisObj);
  7354. #endif
  7355. JS_REENTRANT_UNLOCK(jsReentLock,
  7356. return scriptContext->GetLibrary()->CreateArrayIterator(thisObj, JavascriptArrayIteratorKind::KeyAndValue));
  7357. }
  7358. ///----------------------------------------------------------------------------
  7359. /// Keys() returns a new ArrayIterator object configured to return the keys
  7360. /// of the this array/array-like object, as described in (ES6.0: S22.1.3.13).
  7361. ///----------------------------------------------------------------------------
  7362. Var JavascriptArray::EntryKeys(RecyclableObject* function, CallInfo callInfo, ...)
  7363. {
  7364. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7365. ARGUMENTS(args, callInfo);
  7366. ScriptContext* scriptContext = function->GetScriptContext();
  7367. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7368. Assert(!(callInfo.Flags & CallFlags_New));
  7369. if (args.Info.Count == 0)
  7370. {
  7371. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.keys"));
  7372. }
  7373. RecyclableObject* thisObj = nullptr;
  7374. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &thisObj))
  7375. {
  7376. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.keys"));
  7377. }
  7378. #if ENABLE_COPYONACCESS_ARRAY
  7379. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(thisObj);
  7380. #endif
  7381. JS_REENTRANT_UNLOCK(jsReentLock,
  7382. return scriptContext->GetLibrary()->CreateArrayIterator(thisObj, JavascriptArrayIteratorKind::Key));
  7383. }
  7384. ///----------------------------------------------------------------------------
  7385. /// Values() returns a new ArrayIterator object configured to return the values
  7386. /// of the this array/array-like object, as described in (ES6.0: S22.1.3.29).
  7387. ///----------------------------------------------------------------------------
  7388. Var JavascriptArray::EntryValues(RecyclableObject* function, CallInfo callInfo, ...)
  7389. {
  7390. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7391. ARGUMENTS(args, callInfo);
  7392. ScriptContext* scriptContext = function->GetScriptContext();
  7393. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7394. Assert(!(callInfo.Flags & CallFlags_New));
  7395. if (args.Info.Count == 0)
  7396. {
  7397. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.values"));
  7398. }
  7399. RecyclableObject* thisObj = nullptr;
  7400. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &thisObj))
  7401. {
  7402. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.values"));
  7403. }
  7404. #if ENABLE_COPYONACCESS_ARRAY
  7405. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(thisObj);
  7406. #endif
  7407. JS_REENTRANT_UNLOCK(jsReentLock,
  7408. return scriptContext->GetLibrary()->CreateArrayIterator(thisObj, JavascriptArrayIteratorKind::Value));
  7409. }
  7410. Var JavascriptArray::EntryEvery(RecyclableObject* function, CallInfo callInfo, ...)
  7411. {
  7412. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7413. ARGUMENTS(args, callInfo);
  7414. ScriptContext* scriptContext = function->GetScriptContext();
  7415. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7416. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.every"));
  7417. Assert(!(callInfo.Flags & CallFlags_New));
  7418. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_every);
  7419. if (args.Info.Count == 0)
  7420. {
  7421. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.every"));
  7422. }
  7423. BigIndex length;
  7424. JavascriptArray* pArr = nullptr;
  7425. RecyclableObject* obj = nullptr;
  7426. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.every"), &pArr, &obj, &length));
  7427. if (length.IsSmallIndex())
  7428. {
  7429. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::EveryHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  7430. }
  7431. 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
  7432. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::EveryHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  7433. }
  7434. // Array.prototype.every as described by ES6.0 (draft 22) Section 22.1.3.5
  7435. template <typename T>
  7436. Var JavascriptArray::EveryHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  7437. {
  7438. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7439. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  7440. {
  7441. // typedArrayBase is only non-null if and only if we came here via the TypedArray entrypoint
  7442. if (typedArrayBase != nullptr)
  7443. {
  7444. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.every"));
  7445. }
  7446. else
  7447. {
  7448. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.every"));
  7449. }
  7450. }
  7451. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  7452. Var thisArg = nullptr;
  7453. if (args.Info.Count > 2)
  7454. {
  7455. thisArg = args[2];
  7456. }
  7457. else
  7458. {
  7459. thisArg = scriptContext->GetLibrary()->GetUndefined();
  7460. }
  7461. // If we came from Array.prototype.map and source object is not a JavascriptArray, source could be a TypedArray
  7462. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  7463. {
  7464. typedArrayBase = TypedArrayBase::FromVar(obj);
  7465. }
  7466. Var element = nullptr;
  7467. Var testResult = nullptr;
  7468. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7469. CallFlags flags = CallFlags_Value;
  7470. if (pArr)
  7471. {
  7472. Assert(length <= UINT_MAX);
  7473. for (uint32 k = 0; k < (uint32)length; k++)
  7474. {
  7475. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(k, &element));
  7476. if (!gotItem)
  7477. {
  7478. continue;
  7479. }
  7480. JS_REENTRANT(jsReentLock,
  7481. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7482. element,
  7483. JavascriptNumber::ToVar(k, scriptContext),
  7484. pArr));
  7485. if (!JavascriptConversion::ToBoolean(testResult, scriptContext))
  7486. {
  7487. return scriptContext->GetLibrary()->GetFalse();
  7488. }
  7489. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  7490. // we will process the rest of the array elements like an ES5Array.
  7491. if (!JavascriptArray::Is(obj))
  7492. {
  7493. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  7494. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::EveryObjectHelper<T>(obj, length, k + 1, callBackFn, thisArg, scriptContext));
  7495. }
  7496. }
  7497. }
  7498. else if (typedArrayBase)
  7499. {
  7500. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  7501. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  7502. for (uint32 k = 0; k < end; k++)
  7503. {
  7504. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  7505. element = typedArrayBase->DirectGetItem(k);
  7506. JS_REENTRANT(jsReentLock,
  7507. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7508. element,
  7509. JavascriptNumber::ToVar(k, scriptContext),
  7510. typedArrayBase));
  7511. if (!JavascriptConversion::ToBoolean(testResult, scriptContext))
  7512. {
  7513. return scriptContext->GetLibrary()->GetFalse();
  7514. }
  7515. }
  7516. }
  7517. else
  7518. {
  7519. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::EveryObjectHelper<T>(obj, length, 0u, callBackFn, thisArg, scriptContext));
  7520. }
  7521. return scriptContext->GetLibrary()->GetTrue();
  7522. }
  7523. template <typename T>
  7524. Var JavascriptArray::EveryObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
  7525. {
  7526. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7527. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7528. CallFlags flags = CallFlags_Value;
  7529. Var element = nullptr;
  7530. Var testResult = nullptr;
  7531. for (T k = start; k < length; k++)
  7532. {
  7533. // According to es6 spec, we need to call Has first before calling Get
  7534. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  7535. if (hasItem)
  7536. {
  7537. JS_REENTRANT(jsReentLock,
  7538. element = JavascriptOperators::GetItem(obj, k, scriptContext),
  7539. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7540. element,
  7541. JavascriptNumber::ToVar(k, scriptContext),
  7542. obj));
  7543. if (!JavascriptConversion::ToBoolean(testResult, scriptContext))
  7544. {
  7545. return scriptContext->GetLibrary()->GetFalse();
  7546. }
  7547. }
  7548. }
  7549. return scriptContext->GetLibrary()->GetTrue();
  7550. }
  7551. Var JavascriptArray::EntrySome(RecyclableObject* function, CallInfo callInfo, ...)
  7552. {
  7553. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7554. ARGUMENTS(args, callInfo);
  7555. ScriptContext* scriptContext = function->GetScriptContext();
  7556. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7557. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.some"));
  7558. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_some);
  7559. Assert(!(callInfo.Flags & CallFlags_New));
  7560. if (args.Info.Count == 0)
  7561. {
  7562. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.some"));
  7563. }
  7564. BigIndex length;
  7565. JavascriptArray* pArr = nullptr;
  7566. RecyclableObject* obj = nullptr;
  7567. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.some"), &pArr, &obj, &length));
  7568. if (length.IsSmallIndex())
  7569. {
  7570. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SomeHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  7571. }
  7572. 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
  7573. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SomeHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  7574. }
  7575. // Array.prototype.some as described in ES6.0 (draft 22) Section 22.1.3.23
  7576. template <typename T>
  7577. Var JavascriptArray::SomeHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  7578. {
  7579. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7580. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  7581. {
  7582. // We are in the TypedArray version of this API if and only if typedArrayBase != nullptr
  7583. if (typedArrayBase != nullptr)
  7584. {
  7585. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.some"));
  7586. }
  7587. else
  7588. {
  7589. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.some"));
  7590. }
  7591. }
  7592. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  7593. Var thisArg = nullptr;
  7594. if (args.Info.Count > 2)
  7595. {
  7596. thisArg = args[2];
  7597. }
  7598. else
  7599. {
  7600. thisArg = scriptContext->GetLibrary()->GetUndefined();
  7601. }
  7602. // If we came from Array.prototype.some and source object is not a JavascriptArray, source could be a TypedArray
  7603. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  7604. {
  7605. typedArrayBase = TypedArrayBase::FromVar(obj);
  7606. }
  7607. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7608. CallFlags flags = CallFlags_Value;
  7609. Var element = nullptr;
  7610. Var testResult = nullptr;
  7611. if (pArr)
  7612. {
  7613. Assert(length <= UINT_MAX);
  7614. for (uint32 k = 0; k < (uint32)length; k++)
  7615. {
  7616. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(k, &element));
  7617. if (!gotItem)
  7618. {
  7619. continue;
  7620. }
  7621. JS_REENTRANT_UNLOCK(jsReentLock,
  7622. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7623. element,
  7624. JavascriptNumber::ToVar(k, scriptContext),
  7625. pArr));
  7626. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7627. {
  7628. return scriptContext->GetLibrary()->GetTrue();
  7629. }
  7630. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  7631. // we will process the rest of the array elements like an ES5Array.
  7632. if (!JavascriptArray::Is(obj))
  7633. {
  7634. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  7635. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SomeObjectHelper<T>(obj, length, k + 1, callBackFn, thisArg, scriptContext));
  7636. }
  7637. }
  7638. }
  7639. else if (typedArrayBase)
  7640. {
  7641. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  7642. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  7643. for (uint32 k = 0; k < end; k++)
  7644. {
  7645. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  7646. element = typedArrayBase->DirectGetItem(k);
  7647. JS_REENTRANT_UNLOCK(jsReentLock,
  7648. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7649. element,
  7650. JavascriptNumber::ToVar(k, scriptContext),
  7651. typedArrayBase));
  7652. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7653. {
  7654. return scriptContext->GetLibrary()->GetTrue();
  7655. }
  7656. }
  7657. }
  7658. else
  7659. {
  7660. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SomeObjectHelper<T>(obj, length, 0u, callBackFn, thisArg, scriptContext));
  7661. }
  7662. return scriptContext->GetLibrary()->GetFalse();
  7663. }
  7664. template <typename T>
  7665. Var JavascriptArray::SomeObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
  7666. {
  7667. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7668. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7669. CallFlags flags = CallFlags_Value;
  7670. Var element = nullptr;
  7671. Var testResult = nullptr;
  7672. for (T k = start; k < length; k++)
  7673. {
  7674. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  7675. if (hasItem)
  7676. {
  7677. JS_REENTRANT_UNLOCK(jsReentLock,
  7678. element = JavascriptOperators::GetItem(obj, k, scriptContext),
  7679. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7680. element,
  7681. JavascriptNumber::ToVar(k, scriptContext),
  7682. obj));
  7683. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7684. {
  7685. return scriptContext->GetLibrary()->GetTrue();
  7686. }
  7687. }
  7688. }
  7689. return scriptContext->GetLibrary()->GetFalse();
  7690. }
  7691. Var JavascriptArray::EntryForEach(RecyclableObject* function, CallInfo callInfo, ...)
  7692. {
  7693. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7694. ARGUMENTS(args, callInfo);
  7695. ScriptContext* scriptContext = function->GetScriptContext();
  7696. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7697. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.forEach"));
  7698. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_forEach)
  7699. Assert(!(callInfo.Flags & CallFlags_New));
  7700. if (args.Info.Count == 0)
  7701. {
  7702. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.forEach"));
  7703. }
  7704. BigIndex length;
  7705. JavascriptArray* pArr = nullptr;
  7706. RecyclableObject* dynamicObject = nullptr;
  7707. RecyclableObject* callBackFn = nullptr;
  7708. Var thisArg = nullptr;
  7709. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.forEach"), &pArr, &dynamicObject, &length));
  7710. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  7711. {
  7712. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.forEach"));
  7713. }
  7714. callBackFn = RecyclableObject::FromVar(args[1]);
  7715. if (args.Info.Count > 2)
  7716. {
  7717. thisArg = args[2];
  7718. }
  7719. else
  7720. {
  7721. thisArg = scriptContext->GetLibrary()->GetUndefined();
  7722. }
  7723. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7724. CallFlags flags = CallFlags_Value;
  7725. auto fn32 = [dynamicObject, callBackFn, flags, thisArg,
  7726. scriptContext](uint32 k, Var element)
  7727. {
  7728. CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7729. element,
  7730. JavascriptNumber::ToVar(k, scriptContext),
  7731. dynamicObject);
  7732. };
  7733. auto fn64 = [dynamicObject, callBackFn, flags, thisArg,
  7734. scriptContext](uint64 k, Var element)
  7735. {
  7736. CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7737. element,
  7738. JavascriptNumber::ToVar(k, scriptContext),
  7739. dynamicObject);
  7740. };
  7741. if (pArr)
  7742. {
  7743. Assert(pArr == dynamicObject);
  7744. JS_REENTRANT(jsReentLock, pArr->ForEachItemInRange<true>(0, length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex(), scriptContext, fn32));
  7745. }
  7746. else
  7747. {
  7748. if (length.IsSmallIndex())
  7749. {
  7750. JS_REENTRANT(jsReentLock, TemplatedForEachItemInRange<true>(dynamicObject, 0u, length.GetSmallIndex(), scriptContext, fn32));
  7751. }
  7752. else
  7753. {
  7754. JS_REENTRANT(jsReentLock, TemplatedForEachItemInRange<true>(dynamicObject, 0ui64, length.GetBigIndex(), scriptContext, fn64));
  7755. }
  7756. }
  7757. return scriptContext->GetLibrary()->GetUndefined();
  7758. }
  7759. Var JavascriptArray::EntryCopyWithin(RecyclableObject* function, CallInfo callInfo, ...)
  7760. {
  7761. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7762. ARGUMENTS(args, callInfo);
  7763. ScriptContext* scriptContext = function->GetScriptContext();
  7764. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7765. Assert(!(callInfo.Flags & CallFlags_New));
  7766. RecyclableObject* obj = nullptr;
  7767. JavascriptArray* pArr = nullptr;
  7768. int64 length;
  7769. JS_REENTRANT_UNLOCK(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.copyWithin"), &pArr, &obj, &length));
  7770. return JavascriptArray::CopyWithinHelper(pArr, nullptr, obj, length, args, scriptContext);
  7771. }
  7772. // Array.prototype.copyWithin as defined in ES6.0 (draft 22) Section 22.1.3.3
  7773. Var JavascriptArray::CopyWithinHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
  7774. {
  7775. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7776. Assert(args.Info.Count > 0);
  7777. JavascriptLibrary* library = scriptContext->GetLibrary();
  7778. int64 fromVal = 0;
  7779. int64 toVal = 0;
  7780. int64 finalVal = length;
  7781. // If we came from Array.prototype.copyWithin and source object is not a JavascriptArray, source could be a TypedArray
  7782. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  7783. {
  7784. typedArrayBase = TypedArrayBase::FromVar(obj);
  7785. }
  7786. if (args.Info.Count > 1)
  7787. {
  7788. JS_REENTRANT(jsReentLock, toVal = JavascriptArray::GetIndexFromVar(args[1], length, scriptContext));
  7789. if (args.Info.Count > 2)
  7790. {
  7791. JS_REENTRANT(jsReentLock, fromVal = JavascriptArray::GetIndexFromVar(args[2], length, scriptContext));
  7792. if (args.Info.Count > 3 && args[3] != library->GetUndefined())
  7793. {
  7794. JS_REENTRANT(jsReentLock, finalVal = JavascriptArray::GetIndexFromVar(args[3], length, scriptContext));
  7795. }
  7796. }
  7797. }
  7798. // If count would be negative or zero, we won't do anything so go ahead and return early.
  7799. if (finalVal <= fromVal || length <= toVal)
  7800. {
  7801. return obj;
  7802. }
  7803. // Make sure we won't underflow during the count calculation
  7804. Assert(finalVal > fromVal && length > toVal);
  7805. int64 count = min(finalVal - fromVal, length - toVal);
  7806. // We shouldn't have made it here if the count was going to be zero
  7807. Assert(count > 0);
  7808. int direction;
  7809. if (fromVal < toVal && toVal < (fromVal + count))
  7810. {
  7811. direction = -1;
  7812. fromVal += count - 1;
  7813. toVal += count - 1;
  7814. }
  7815. else
  7816. {
  7817. direction = 1;
  7818. }
  7819. // Side effects (such as defining a property in a ToPrimitive call) during evaluation of arguments may convert the array to an ES5 array.
  7820. if (pArr && !JavascriptArray::Is(obj))
  7821. {
  7822. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  7823. pArr = nullptr;
  7824. }
  7825. // If we are going to copy elements from or to indices > 2^32-1 we'll execute this (slightly slower path)
  7826. // It's possible to optimize here so that we use the normal code below except for the > 2^32-1 indices
  7827. if ((direction == -1 && (fromVal >= MaxArrayLength || toVal >= MaxArrayLength))
  7828. || (((fromVal + count) > MaxArrayLength) || ((toVal + count) > MaxArrayLength)))
  7829. {
  7830. while (count > 0)
  7831. {
  7832. Var index = JavascriptNumber::ToVar(fromVal, scriptContext);
  7833. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::OP_HasItem(obj, index, scriptContext));
  7834. if (hasItem)
  7835. {
  7836. Var val = nullptr;
  7837. JS_REENTRANT(jsReentLock,
  7838. val = JavascriptOperators::OP_GetElementI(obj, index, scriptContext),
  7839. JavascriptOperators::OP_SetElementI(obj, JavascriptNumber::ToVar(toVal, scriptContext), val, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  7840. }
  7841. else
  7842. {
  7843. JavascriptOperators::OP_DeleteElementI(obj, JavascriptNumber::ToVar(toVal, scriptContext), scriptContext, PropertyOperation_ThrowOnDeleteIfNotConfig);
  7844. }
  7845. fromVal += direction;
  7846. toVal += direction;
  7847. count--;
  7848. }
  7849. }
  7850. else
  7851. {
  7852. Assert(fromVal < MaxArrayLength);
  7853. Assert(toVal < MaxArrayLength);
  7854. Assert(direction == -1 || (fromVal + count < MaxArrayLength && toVal + count < MaxArrayLength));
  7855. uint32 fromIndex = static_cast<uint32>(fromVal);
  7856. uint32 toIndex = static_cast<uint32>(toVal);
  7857. while (count > 0)
  7858. {
  7859. JS_REENTRANT(jsReentLock, BOOL hasItem = obj->HasItem(fromIndex));
  7860. if (hasItem)
  7861. {
  7862. if (typedArrayBase)
  7863. {
  7864. Var val = typedArrayBase->DirectGetItem(fromIndex);
  7865. JS_REENTRANT(jsReentLock, typedArrayBase->DirectSetItem(toIndex, val));
  7866. }
  7867. else if (pArr)
  7868. {
  7869. JS_REENTRANT(jsReentLock, Var val = pArr->DirectGetItem(fromIndex));
  7870. pArr->SetItem(toIndex, val, Js::PropertyOperation_ThrowIfNotExtensible);
  7871. if (!JavascriptArray::Is(obj))
  7872. {
  7873. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  7874. pArr = nullptr;
  7875. }
  7876. }
  7877. else
  7878. {
  7879. Var val = nullptr;
  7880. JS_REENTRANT(jsReentLock,
  7881. val = JavascriptOperators::OP_GetElementI_UInt32(obj, fromIndex, scriptContext),
  7882. JavascriptOperators::OP_SetElementI_UInt32(obj, toIndex, val, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  7883. }
  7884. }
  7885. else
  7886. {
  7887. obj->DeleteItem(toIndex, PropertyOperation_ThrowOnDeleteIfNotConfig);
  7888. }
  7889. fromIndex += direction;
  7890. toIndex += direction;
  7891. count--;
  7892. }
  7893. }
  7894. return obj;
  7895. }
  7896. Var JavascriptArray::EntryFill(RecyclableObject* function, CallInfo callInfo, ...)
  7897. {
  7898. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7899. ARGUMENTS(args, callInfo);
  7900. ScriptContext* scriptContext = function->GetScriptContext();
  7901. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7902. Assert(!(callInfo.Flags & CallFlags_New));
  7903. RecyclableObject* obj = nullptr;
  7904. JavascriptArray* pArr = nullptr;
  7905. int64 length;
  7906. JS_REENTRANT_UNLOCK(jsReentLock,
  7907. TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.fill"), &pArr, &obj, &length));
  7908. return JavascriptArray::FillHelper(pArr, nullptr, obj, length, args, scriptContext);
  7909. }
  7910. // Array.prototype.fill as defined in ES6.0 (draft 22) Section 22.1.3.6
  7911. Var JavascriptArray::FillHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
  7912. {
  7913. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7914. Assert(args.Info.Count > 0);
  7915. JavascriptLibrary* library = scriptContext->GetLibrary();
  7916. // If we came from Array.prototype.fill and source object is not a JavascriptArray, source could be a TypedArray
  7917. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  7918. {
  7919. typedArrayBase = TypedArrayBase::FromVar(obj);
  7920. }
  7921. Var fillValue;
  7922. if (args.Info.Count > 1)
  7923. {
  7924. fillValue = args[1];
  7925. }
  7926. else
  7927. {
  7928. fillValue = library->GetUndefined();
  7929. }
  7930. int64 k = 0;
  7931. int64 finalVal = length;
  7932. if (args.Info.Count > 2)
  7933. {
  7934. JS_REENTRANT_UNLOCK(jsReentLock, k = JavascriptArray::GetIndexFromVar(args[2], length, scriptContext));
  7935. if (args.Info.Count > 3 && !JavascriptOperators::IsUndefinedObject(args[3]))
  7936. {
  7937. JS_REENTRANT_UNLOCK(jsReentLock, finalVal = JavascriptArray::GetIndexFromVar(args[3], length, scriptContext));
  7938. }
  7939. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  7940. // we will process the array elements like an ES5Array.
  7941. if (pArr && !JavascriptArray::Is(obj))
  7942. {
  7943. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  7944. pArr = nullptr;
  7945. }
  7946. }
  7947. if (k < MaxArrayLength)
  7948. {
  7949. int64 end = min<int64>(finalVal, MaxArrayLength);
  7950. uint32 u32k = static_cast<uint32>(k);
  7951. while (u32k < end)
  7952. {
  7953. if (typedArrayBase)
  7954. {
  7955. JS_REENTRANT(jsReentLock, typedArrayBase->DirectSetItem(u32k, fillValue));
  7956. }
  7957. else if (pArr)
  7958. {
  7959. pArr->SetItem(u32k, fillValue, PropertyOperation_ThrowIfNotExtensible);
  7960. }
  7961. else
  7962. {
  7963. JS_REENTRANT(jsReentLock,
  7964. JavascriptOperators::OP_SetElementI_UInt32(obj, u32k, fillValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible));
  7965. }
  7966. u32k++;
  7967. }
  7968. BigIndex dstIndex = MaxArrayLength;
  7969. for (int64 i = end; i < finalVal; ++i)
  7970. {
  7971. if (pArr)
  7972. {
  7973. pArr->GenericDirectSetItemAt(dstIndex, fillValue);
  7974. ++dstIndex;
  7975. }
  7976. else
  7977. {
  7978. JS_REENTRANT(jsReentLock,
  7979. JavascriptOperators::OP_SetElementI(obj, JavascriptNumber::ToVar(i, scriptContext), fillValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible));
  7980. }
  7981. }
  7982. }
  7983. else
  7984. {
  7985. BigIndex dstIndex = static_cast<uint64>(k);
  7986. for (int64 i = k; i < finalVal; i++)
  7987. {
  7988. if (pArr)
  7989. {
  7990. pArr->GenericDirectSetItemAt(dstIndex, fillValue);
  7991. ++dstIndex;
  7992. }
  7993. else
  7994. {
  7995. JS_REENTRANT(jsReentLock,
  7996. JavascriptOperators::OP_SetElementI(obj, JavascriptNumber::ToVar(i, scriptContext), fillValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible));
  7997. }
  7998. }
  7999. }
  8000. return obj;
  8001. }
  8002. // Array.prototype.map as defined by ES6.0 (Final) 22.1.3.15
  8003. Var JavascriptArray::EntryMap(RecyclableObject* function, CallInfo callInfo, ...)
  8004. {
  8005. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8006. ARGUMENTS(args, callInfo);
  8007. ScriptContext* scriptContext = function->GetScriptContext();
  8008. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8009. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.map"));
  8010. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_map);
  8011. Assert(!(callInfo.Flags & CallFlags_New));
  8012. if (args.Info.Count == 0)
  8013. {
  8014. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.map"));
  8015. }
  8016. BigIndex length;
  8017. JavascriptArray* pArr = nullptr;
  8018. RecyclableObject* obj = nullptr;
  8019. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.map"), &pArr, &obj, &length));
  8020. if (length.IsSmallIndex())
  8021. {
  8022. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::MapHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  8023. }
  8024. 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
  8025. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::MapHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  8026. }
  8027. template<typename T>
  8028. Var JavascriptArray::MapHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  8029. {
  8030. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8031. RecyclableObject* newObj = nullptr;
  8032. JavascriptArray* newArr = nullptr;
  8033. bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
  8034. bool isBuiltinArrayCtor = true;
  8035. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  8036. {
  8037. if (isTypedArrayEntryPoint)
  8038. {
  8039. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.map"));
  8040. }
  8041. else
  8042. {
  8043. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.map"));
  8044. }
  8045. }
  8046. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  8047. Var thisArg;
  8048. if (args.Info.Count > 2)
  8049. {
  8050. thisArg = args[2];
  8051. }
  8052. else
  8053. {
  8054. thisArg = scriptContext->GetLibrary()->GetUndefined();
  8055. }
  8056. // If we came from Array.prototype.map and source object is not a JavascriptArray, source could be a TypedArray
  8057. if (!isTypedArrayEntryPoint && pArr == nullptr && TypedArrayBase::Is(obj))
  8058. {
  8059. typedArrayBase = TypedArrayBase::FromVar(obj);
  8060. }
  8061. // 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
  8062. // and use it to construct the return object.
  8063. if (isTypedArrayEntryPoint)
  8064. {
  8065. JS_REENTRANT(jsReentLock,
  8066. Var constructor = JavascriptOperators::SpeciesConstructor(
  8067. typedArrayBase, TypedArrayBase::GetDefaultConstructor(args[0], scriptContext), scriptContext));
  8068. isBuiltinArrayCtor = false;
  8069. Assert(JavascriptOperators::IsConstructor(constructor));
  8070. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(length, scriptContext) };
  8071. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  8072. JS_REENTRANT(jsReentLock, newObj = RecyclableObject::FromVar(TypedArrayBase::TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), (uint32)length, scriptContext)));
  8073. }
  8074. // skip the typed array and "pure" array case, we still need to handle special arrays like es5array, remote array, and proxy of array.
  8075. else if (pArr == nullptr || scriptContext->GetConfig()->IsES6SpeciesEnabled())
  8076. {
  8077. JS_REENTRANT(jsReentLock, newObj = ArraySpeciesCreate(obj, length, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor));
  8078. }
  8079. if (newObj == nullptr)
  8080. {
  8081. if (length > UINT_MAX)
  8082. {
  8083. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  8084. }
  8085. newArr = scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(length));
  8086. newArr->EnsureHead<Var>();
  8087. newObj = newArr;
  8088. }
  8089. else
  8090. {
  8091. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  8092. if (JavascriptArray::Is(newObj))
  8093. {
  8094. #if ENABLE_COPYONACCESS_ARRAY
  8095. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
  8096. #endif
  8097. newArr = JavascriptArray::FromVar(newObj);
  8098. }
  8099. }
  8100. Var element = nullptr;
  8101. Var mappedValue = nullptr;
  8102. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8103. CallFlags callBackFnflags = CallFlags_Value;
  8104. CallInfo callBackFnInfo = CallInfo(callBackFnflags, 4);
  8105. // We at least have to have newObj as a valid object
  8106. Assert(newObj);
  8107. // The ArraySpeciesCreate call above could have converted the source array into an ES5Array. If this happens
  8108. // we will process the array elements like an ES5Array.
  8109. if (pArr && !JavascriptArray::Is(obj))
  8110. {
  8111. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  8112. pArr = nullptr;
  8113. }
  8114. if (pArr != nullptr)
  8115. {
  8116. // If source is a JavascriptArray, newObj may or may not be an array based on what was in source's constructor property
  8117. Assert(length <= UINT_MAX);
  8118. for (uint32 k = 0; k < (uint32)length; k++)
  8119. {
  8120. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(k, &element));
  8121. if (!gotItem)
  8122. {
  8123. continue;
  8124. }
  8125. JS_REENTRANT(jsReentLock,
  8126. mappedValue = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, callBackFnInfo, thisArg,
  8127. element,
  8128. JavascriptNumber::ToVar(k, scriptContext),
  8129. pArr));
  8130. // If newArr is a valid pointer, then we constructed an array to return. Otherwise we need to do generic object operations
  8131. if (newArr && isBuiltinArrayCtor)
  8132. {
  8133. newArr->DirectSetItemAt(k, mappedValue);
  8134. }
  8135. else
  8136. {
  8137. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, k, mappedValue), scriptContext, k));
  8138. }
  8139. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  8140. // we will process the rest of the array elements like an ES5Array.
  8141. if (!JavascriptArray::Is(obj))
  8142. {
  8143. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  8144. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::MapObjectHelper<T>(obj, length, k + 1, newObj, newArr, isBuiltinArrayCtor, callBackFn, thisArg, scriptContext));
  8145. }
  8146. }
  8147. }
  8148. else if (typedArrayBase != nullptr)
  8149. {
  8150. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  8151. // Source is a TypedArray, we may have tried to call a constructor, but newObj may not be a TypedArray (or an array either)
  8152. TypedArrayBase* newTypedArray = nullptr;
  8153. if (TypedArrayBase::Is(newObj))
  8154. {
  8155. newTypedArray = TypedArrayBase::FromVar(newObj);
  8156. }
  8157. else
  8158. {
  8159. AssertAndFailFast(newArr != nullptr);
  8160. }
  8161. Assert(length <= UINT_MAX);
  8162. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  8163. for (uint32 k = 0; k < end; k++)
  8164. {
  8165. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  8166. element = typedArrayBase->DirectGetItem(k);
  8167. JS_REENTRANT(jsReentLock,
  8168. mappedValue = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, callBackFnInfo, thisArg,
  8169. element,
  8170. JavascriptNumber::ToVar(k, scriptContext),
  8171. obj));
  8172. // If newObj is a TypedArray, set the mappedValue directly, otherwise it should be an array, set that item to that array
  8173. if (newTypedArray)
  8174. {
  8175. JS_REENTRANT(jsReentLock, newTypedArray->DirectSetItem(k, mappedValue));
  8176. }
  8177. else
  8178. {
  8179. newArr->SetItem(k, mappedValue, PropertyOperation_None);
  8180. }
  8181. }
  8182. }
  8183. else
  8184. {
  8185. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::MapObjectHelper<T>(obj, length, 0u, newObj, newArr, isBuiltinArrayCtor, callBackFn, thisArg, scriptContext));
  8186. }
  8187. #ifdef VALIDATE_ARRAY
  8188. if (JavascriptArray::Is(newObj))
  8189. {
  8190. newArr->ValidateArray();
  8191. }
  8192. #endif
  8193. return newObj;
  8194. }
  8195. template<typename T>
  8196. Var JavascriptArray::MapObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* newObj, JavascriptArray* newArr,
  8197. bool isBuiltinArrayCtor, RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
  8198. {
  8199. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8200. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8201. CallFlags callBackFnflags = CallFlags_Value;
  8202. CallInfo callBackFnInfo = CallInfo(callBackFnflags, 4);
  8203. Var element = nullptr;
  8204. Var mappedValue = nullptr;
  8205. for (T k = start; k < length; k++)
  8206. {
  8207. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  8208. if (hasItem)
  8209. {
  8210. JS_REENTRANT(jsReentLock,
  8211. element = JavascriptOperators::GetItem(obj, k, scriptContext),
  8212. mappedValue = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, callBackFnInfo, thisArg,
  8213. element,
  8214. JavascriptNumber::ToVar(k, scriptContext),
  8215. obj));
  8216. if (newArr && isBuiltinArrayCtor)
  8217. {
  8218. newArr->SetItem((uint32)k, mappedValue, PropertyOperation_None);
  8219. }
  8220. else
  8221. {
  8222. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, BigIndex(k), mappedValue), scriptContext, BigIndex(k)));
  8223. }
  8224. }
  8225. }
  8226. #ifdef VALIDATE_ARRAY
  8227. if (JavascriptArray::Is(newObj))
  8228. {
  8229. newArr->ValidateArray();
  8230. }
  8231. #endif
  8232. return newObj;
  8233. }
  8234. Var JavascriptArray::EntryFilter(RecyclableObject* function, CallInfo callInfo, ...)
  8235. {
  8236. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8237. ARGUMENTS(args, callInfo);
  8238. ScriptContext* scriptContext = function->GetScriptContext();
  8239. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8240. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.filter"));
  8241. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_filter);
  8242. Assert(!(callInfo.Flags & CallFlags_New));
  8243. if (args.Info.Count == 0)
  8244. {
  8245. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.filter"));
  8246. }
  8247. BigIndex length;
  8248. JavascriptArray* pArr = nullptr;
  8249. RecyclableObject* obj = nullptr;
  8250. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.filter"), &pArr, &obj, &length));
  8251. if (length.IsSmallIndex())
  8252. {
  8253. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FilterHelper(pArr, obj, length.GetSmallIndex(), args, scriptContext));
  8254. }
  8255. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FilterHelper(pArr, obj, length.GetBigIndex(), args, scriptContext));
  8256. }
  8257. template <typename T>
  8258. Var JavascriptArray::FilterHelper(JavascriptArray* pArr, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  8259. {
  8260. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8261. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  8262. {
  8263. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.filter"));
  8264. }
  8265. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  8266. Var thisArg = nullptr;
  8267. if (args.Info.Count > 2)
  8268. {
  8269. thisArg = args[2];
  8270. }
  8271. else
  8272. {
  8273. thisArg = scriptContext->GetLibrary()->GetUndefined();
  8274. }
  8275. // 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.
  8276. bool isBuiltinArrayCtor = true;
  8277. JS_REENTRANT(jsReentLock, RecyclableObject* newObj = ArraySpeciesCreate(obj, 0, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor));
  8278. JavascriptArray* newArr = nullptr;
  8279. if (newObj == nullptr)
  8280. {
  8281. newArr = scriptContext->GetLibrary()->CreateArray(0);
  8282. newArr->EnsureHead<Var>();
  8283. newObj = newArr;
  8284. }
  8285. else
  8286. {
  8287. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  8288. if (JavascriptArray::Is(newObj))
  8289. {
  8290. #if ENABLE_COPYONACCESS_ARRAY
  8291. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
  8292. #endif
  8293. newArr = JavascriptArray::FromVar(newObj);
  8294. }
  8295. }
  8296. // The ArraySpeciesCreate call above could have converted the source array into an ES5Array. If this happens
  8297. // we will process the array elements like an ES5Array.
  8298. if (pArr && !JavascriptArray::Is(obj))
  8299. {
  8300. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  8301. pArr = nullptr;
  8302. }
  8303. Var element = nullptr;
  8304. Var selected = nullptr;
  8305. if (pArr)
  8306. {
  8307. Assert(length <= MaxArrayLength);
  8308. uint32 i = 0;
  8309. Assert(length <= UINT_MAX);
  8310. for (uint32 k = 0; k < (uint32)length; k++)
  8311. {
  8312. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(k, &element));
  8313. if (!gotItem)
  8314. {
  8315. continue;
  8316. }
  8317. JS_REENTRANT(jsReentLock,
  8318. selected = CALL_ENTRYPOINT(scriptContext->GetThreadContext(),
  8319. callBackFn->GetEntryPoint(), callBackFn, CallInfo(CallFlags_Value, 4),
  8320. thisArg,
  8321. element,
  8322. JavascriptNumber::ToVar(k, scriptContext),
  8323. pArr));
  8324. if (JavascriptConversion::ToBoolean(selected, scriptContext))
  8325. {
  8326. // Try to fast path if the return object is an array
  8327. if (newArr && isBuiltinArrayCtor)
  8328. {
  8329. newArr->DirectSetItemAt(i, element);
  8330. }
  8331. else
  8332. {
  8333. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i));
  8334. }
  8335. ++i;
  8336. }
  8337. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  8338. // we will process the rest of the array elements like an ES5Array.
  8339. if (!JavascriptArray::Is(obj))
  8340. {
  8341. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  8342. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FilterObjectHelper<T>(obj, length, k + 1, newArr, newObj, i, callBackFn, thisArg, scriptContext));
  8343. }
  8344. }
  8345. }
  8346. else
  8347. {
  8348. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FilterObjectHelper<T>(obj, length, 0u, newArr, newObj, 0u, callBackFn, thisArg, scriptContext));
  8349. }
  8350. #ifdef VALIDATE_ARRAY
  8351. if (newArr)
  8352. {
  8353. newArr->ValidateArray();
  8354. }
  8355. #endif
  8356. return newObj;
  8357. }
  8358. template <typename T>
  8359. Var JavascriptArray::FilterObjectHelper(RecyclableObject* obj, T length, T start, JavascriptArray* newArr, RecyclableObject* newObj, T newStart,
  8360. RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
  8361. {
  8362. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8363. Var element = nullptr;
  8364. Var selected = nullptr;
  8365. BigIndex i = BigIndex(newStart);
  8366. for (T k = start; k < length; k++)
  8367. {
  8368. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  8369. if (hasItem)
  8370. {
  8371. JS_REENTRANT(jsReentLock,
  8372. element = JavascriptOperators::GetItem(obj, k, scriptContext),
  8373. selected = CALL_ENTRYPOINT(scriptContext->GetThreadContext(),
  8374. callBackFn->GetEntryPoint(), callBackFn, CallInfo(CallFlags_Value, 4),
  8375. thisArg,
  8376. element,
  8377. JavascriptNumber::ToVar(k, scriptContext),
  8378. obj));
  8379. if (JavascriptConversion::ToBoolean(selected, scriptContext))
  8380. {
  8381. if (newArr)
  8382. {
  8383. newArr->GenericDirectSetItemAt(i, element);
  8384. }
  8385. else
  8386. {
  8387. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i));
  8388. }
  8389. ++i;
  8390. }
  8391. }
  8392. }
  8393. #ifdef VALIDATE_ARRAY
  8394. if (newArr)
  8395. {
  8396. newArr->ValidateArray();
  8397. }
  8398. #endif
  8399. return newObj;
  8400. }
  8401. Var JavascriptArray::EntryReduce(RecyclableObject* function, CallInfo callInfo, ...)
  8402. {
  8403. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8404. ARGUMENTS(args, callInfo);
  8405. ScriptContext* scriptContext = function->GetScriptContext();
  8406. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8407. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.reduce"));
  8408. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_reduce);
  8409. Assert(!(callInfo.Flags & CallFlags_New));
  8410. if (args.Info.Count == 0)
  8411. {
  8412. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reduce"));
  8413. }
  8414. BigIndex length;
  8415. JavascriptArray * pArr = nullptr;
  8416. RecyclableObject* obj = nullptr;
  8417. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.reduce"), &pArr, &obj, &length));
  8418. if (length.IsSmallIndex())
  8419. {
  8420. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  8421. }
  8422. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  8423. }
  8424. // Array.prototype.reduce as described in ES6.0 (draft 22) Section 22.1.3.18
  8425. template <typename T>
  8426. Var JavascriptArray::ReduceHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  8427. {
  8428. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8429. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  8430. {
  8431. if (typedArrayBase != nullptr)
  8432. {
  8433. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.reduce"));
  8434. }
  8435. else
  8436. {
  8437. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.reduce"));
  8438. }
  8439. }
  8440. // If we came from Array.prototype.reduce and source object is not a JavascriptArray, source could be a TypedArray
  8441. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  8442. {
  8443. typedArrayBase = TypedArrayBase::FromVar(obj);
  8444. }
  8445. T k = 0;
  8446. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  8447. Var accumulator = nullptr;
  8448. Var element = nullptr;
  8449. if (args.Info.Count > 2)
  8450. {
  8451. accumulator = args[2];
  8452. }
  8453. else
  8454. {
  8455. if (length == 0)
  8456. {
  8457. JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
  8458. }
  8459. bool bPresent = false;
  8460. if (pArr)
  8461. {
  8462. for (; k < length && bPresent == false; k++)
  8463. {
  8464. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull((uint32)k, &element));
  8465. if (!gotItem)
  8466. {
  8467. continue;
  8468. }
  8469. bPresent = true;
  8470. accumulator = element;
  8471. }
  8472. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  8473. // we will process the array elements like an ES5Array.
  8474. if (!JavascriptArray::Is(obj))
  8475. {
  8476. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  8477. pArr = nullptr;
  8478. }
  8479. }
  8480. else if (typedArrayBase)
  8481. {
  8482. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  8483. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  8484. for (; k < end && bPresent == false; k++)
  8485. {
  8486. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  8487. element = typedArrayBase->DirectGetItem((uint32)k);
  8488. bPresent = true;
  8489. accumulator = element;
  8490. }
  8491. }
  8492. else
  8493. {
  8494. for (; k < length && bPresent == false; k++)
  8495. {
  8496. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  8497. if (hasItem)
  8498. {
  8499. JS_REENTRANT(jsReentLock, accumulator = JavascriptOperators::GetItem(obj, k, scriptContext));
  8500. bPresent = true;
  8501. }
  8502. }
  8503. }
  8504. if (bPresent == false)
  8505. {
  8506. JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
  8507. }
  8508. }
  8509. Assert(accumulator);
  8510. Var undefinedValue = scriptContext->GetLibrary()->GetUndefined();
  8511. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8512. CallFlags flags = CallFlags_Value;
  8513. if (pArr)
  8514. {
  8515. for (; k < length; k++)
  8516. {
  8517. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull((uint32)k, &element));
  8518. if (!gotItem)
  8519. {
  8520. continue;
  8521. }
  8522. JS_REENTRANT(jsReentLock,
  8523. accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 5), undefinedValue,
  8524. accumulator,
  8525. element,
  8526. JavascriptNumber::ToVar(k, scriptContext),
  8527. pArr));
  8528. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  8529. // we will process the rest of the array elements like an ES5Array.
  8530. if (!JavascriptArray::Is(obj))
  8531. {
  8532. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  8533. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceObjectHelper<T>(obj, length, k + 1, callBackFn, accumulator, scriptContext));
  8534. }
  8535. }
  8536. }
  8537. else if (typedArrayBase)
  8538. {
  8539. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  8540. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  8541. for (; k < end; k++)
  8542. {
  8543. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  8544. element = typedArrayBase->DirectGetItem((uint32)k);
  8545. JS_REENTRANT(jsReentLock,
  8546. accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 5), undefinedValue,
  8547. accumulator,
  8548. element,
  8549. JavascriptNumber::ToVar(k, scriptContext),
  8550. typedArrayBase));
  8551. }
  8552. }
  8553. else
  8554. {
  8555. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceObjectHelper<T>(obj, length, k, callBackFn, accumulator, scriptContext));
  8556. }
  8557. return accumulator;
  8558. }
  8559. template <typename T>
  8560. Var JavascriptArray::ReduceObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* callBackFn, Var accumulator, ScriptContext* scriptContext)
  8561. {
  8562. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8563. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8564. CallFlags flags = CallFlags_Value;
  8565. Var element = nullptr;
  8566. for (T k = start; k < length; k++)
  8567. {
  8568. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  8569. if (hasItem)
  8570. {
  8571. JS_REENTRANT(jsReentLock,
  8572. element = JavascriptOperators::GetItem(obj, k, scriptContext),
  8573. accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 5), scriptContext->GetLibrary()->GetUndefined(),
  8574. accumulator,
  8575. element,
  8576. JavascriptNumber::ToVar(k, scriptContext),
  8577. obj));
  8578. }
  8579. }
  8580. return accumulator;
  8581. }
  8582. Var JavascriptArray::EntryReduceRight(RecyclableObject* function, CallInfo callInfo, ...)
  8583. {
  8584. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8585. ARGUMENTS(args, callInfo);
  8586. ScriptContext* scriptContext = function->GetScriptContext();
  8587. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8588. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.reduceRight"));
  8589. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_reduceRight);
  8590. Assert(!(callInfo.Flags & CallFlags_New));
  8591. if (args.Info.Count == 0)
  8592. {
  8593. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reduceRight"));
  8594. }
  8595. BigIndex length;
  8596. JavascriptArray * pArr = nullptr;
  8597. RecyclableObject* obj = nullptr;
  8598. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.reduceRight"), &pArr, &obj, &length));
  8599. if (length.IsSmallIndex())
  8600. {
  8601. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceRightHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  8602. }
  8603. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceRightHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  8604. }
  8605. // Array.prototype.reduceRight as described in ES6.0 (draft 22) Section 22.1.3.19
  8606. template <typename T>
  8607. Var JavascriptArray::ReduceRightHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  8608. {
  8609. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8610. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  8611. {
  8612. if (typedArrayBase != nullptr)
  8613. {
  8614. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.reduceRight"));
  8615. }
  8616. else
  8617. {
  8618. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.reduceRight"));
  8619. }
  8620. }
  8621. // If we came from Array.prototype.reduceRight and source object is not a JavascriptArray, source could be a TypedArray
  8622. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  8623. {
  8624. typedArrayBase = TypedArrayBase::FromVar(obj);
  8625. }
  8626. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  8627. Var accumulator = nullptr;
  8628. Var element = nullptr;
  8629. T k = 0;
  8630. T index = 0;
  8631. if (args.Info.Count > 2)
  8632. {
  8633. accumulator = args[2];
  8634. }
  8635. else
  8636. {
  8637. if (length == 0)
  8638. {
  8639. JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
  8640. }
  8641. bool bPresent = false;
  8642. if (pArr)
  8643. {
  8644. for (; k < length && bPresent == false; k++)
  8645. {
  8646. index = length - k - 1;
  8647. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull((uint32)index, &element));
  8648. if (!gotItem)
  8649. {
  8650. continue;
  8651. }
  8652. bPresent = true;
  8653. accumulator = element;
  8654. }
  8655. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  8656. // we will process the array elements like an ES5Array.
  8657. if (!JavascriptArray::Is(obj))
  8658. {
  8659. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  8660. pArr = nullptr;
  8661. }
  8662. }
  8663. else if (typedArrayBase)
  8664. {
  8665. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  8666. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  8667. for (; k < end && bPresent == false; k++)
  8668. {
  8669. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  8670. index = length - k - 1;
  8671. element = typedArrayBase->DirectGetItem((uint32)index);
  8672. bPresent = true;
  8673. accumulator = element;
  8674. }
  8675. }
  8676. else
  8677. {
  8678. for (; k < length && bPresent == false; k++)
  8679. {
  8680. index = length - k - 1;
  8681. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, index));
  8682. if (hasItem)
  8683. {
  8684. JS_REENTRANT(jsReentLock, accumulator = JavascriptOperators::GetItem(obj, index, scriptContext));
  8685. bPresent = true;
  8686. }
  8687. }
  8688. }
  8689. if (bPresent == false)
  8690. {
  8691. JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
  8692. }
  8693. }
  8694. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8695. CallFlags flags = CallFlags_Value;
  8696. Var undefinedValue = scriptContext->GetLibrary()->GetUndefined();
  8697. if (pArr)
  8698. {
  8699. for (; k < length; k++)
  8700. {
  8701. index = length - k - 1;
  8702. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull((uint32)index, &element));
  8703. if (!gotItem)
  8704. {
  8705. continue;
  8706. }
  8707. JS_REENTRANT(jsReentLock,
  8708. accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 5), undefinedValue,
  8709. accumulator,
  8710. element,
  8711. JavascriptNumber::ToVar(index, scriptContext),
  8712. pArr));
  8713. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  8714. // we will process the rest of the array elements like an ES5Array.
  8715. if (!JavascriptArray::Is(obj))
  8716. {
  8717. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  8718. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceRightObjectHelper<T>(obj, length, k + 1, callBackFn, accumulator, scriptContext));
  8719. }
  8720. }
  8721. }
  8722. else if (typedArrayBase)
  8723. {
  8724. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  8725. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  8726. for (; k < end; k++)
  8727. {
  8728. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  8729. index = length - k - 1;
  8730. element = typedArrayBase->DirectGetItem((uint32)index);
  8731. JS_REENTRANT(jsReentLock,
  8732. accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 5), undefinedValue,
  8733. accumulator,
  8734. element,
  8735. JavascriptNumber::ToVar(index, scriptContext),
  8736. typedArrayBase));
  8737. }
  8738. }
  8739. else
  8740. {
  8741. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceRightObjectHelper<T>(obj, length, k, callBackFn, accumulator, scriptContext));
  8742. }
  8743. return accumulator;
  8744. }
  8745. template <typename T>
  8746. Var JavascriptArray::ReduceRightObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* callBackFn, Var accumulator, ScriptContext* scriptContext)
  8747. {
  8748. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8749. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8750. CallFlags flags = CallFlags_Value;
  8751. Var element = nullptr;
  8752. T index = 0;
  8753. for (T k = start; k < length; k++)
  8754. {
  8755. index = length - k - 1;
  8756. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, index));
  8757. if (hasItem)
  8758. {
  8759. JS_REENTRANT(jsReentLock,
  8760. element = JavascriptOperators::GetItem(obj, index, scriptContext),
  8761. accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(),
  8762. callBackFn, CallInfo(flags, 5), scriptContext->GetLibrary()->GetUndefined(),
  8763. accumulator,
  8764. element,
  8765. JavascriptNumber::ToVar(index, scriptContext),
  8766. obj));
  8767. }
  8768. }
  8769. return accumulator;
  8770. }
  8771. Var JavascriptArray::EntryFrom(RecyclableObject* function, CallInfo callInfo, ...)
  8772. {
  8773. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8774. ARGUMENTS(args, callInfo);
  8775. ScriptContext* scriptContext = function->GetScriptContext();
  8776. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8777. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.from"));
  8778. Assert(!(callInfo.Flags & CallFlags_New));
  8779. JavascriptLibrary* library = scriptContext->GetLibrary();
  8780. RecyclableObject* constructor = nullptr;
  8781. if (JavascriptOperators::IsConstructor(args[0]))
  8782. {
  8783. constructor = RecyclableObject::FromVar(args[0]);
  8784. }
  8785. RecyclableObject* items = nullptr;
  8786. if (args.Info.Count < 2 || !JavascriptConversion::ToObject(args[1], scriptContext, &items))
  8787. {
  8788. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedObject, _u("Array.from"));
  8789. }
  8790. JavascriptArray* itemsArr = nullptr;
  8791. if (JavascriptArray::Is(items))
  8792. {
  8793. #if ENABLE_COPYONACCESS_ARRAY
  8794. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(items);
  8795. #endif
  8796. itemsArr = JavascriptArray::FromVar(items);
  8797. }
  8798. bool mapping = false;
  8799. JavascriptFunction* mapFn = nullptr;
  8800. Var mapFnThisArg = nullptr;
  8801. if (args.Info.Count >= 3 && !JavascriptOperators::IsUndefinedObject(args[2]))
  8802. {
  8803. if (!JavascriptFunction::Is(args[2]))
  8804. {
  8805. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.from"));
  8806. }
  8807. mapFn = JavascriptFunction::FromVar(args[2]);
  8808. if (args.Info.Count >= 4)
  8809. {
  8810. mapFnThisArg = args[3];
  8811. }
  8812. else
  8813. {
  8814. mapFnThisArg = library->GetUndefined();
  8815. }
  8816. mapping = true;
  8817. }
  8818. RecyclableObject* newObj = nullptr;
  8819. JavascriptArray* newArr = nullptr;
  8820. JS_REENTRANT(jsReentLock, RecyclableObject* iterator = JavascriptOperators::GetIterator(items, scriptContext, true /* optional */));
  8821. if (iterator != nullptr)
  8822. {
  8823. if (constructor)
  8824. {
  8825. Js::Var constructorArgs[] = { constructor };
  8826. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  8827. JS_REENTRANT(jsReentLock, newObj = RecyclableObject::FromVar(JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext)));
  8828. if (JavascriptArray::Is(newObj))
  8829. {
  8830. #if ENABLE_COPYONACCESS_ARRAY
  8831. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
  8832. #endif
  8833. newArr = JavascriptArray::FromVar(newObj);
  8834. }
  8835. }
  8836. else
  8837. {
  8838. newArr = scriptContext->GetLibrary()->CreateArray(0);
  8839. newArr->EnsureHead<Var>();
  8840. newObj = newArr;
  8841. }
  8842. uint32 k = 0;
  8843. JS_REENTRANT(jsReentLock, JavascriptOperators::DoIteratorStepAndValue(iterator, scriptContext, [&](Var nextValue) {
  8844. if (mapping)
  8845. {
  8846. Assert(mapFn != nullptr);
  8847. Assert(mapFnThisArg != nullptr);
  8848. Js::Var mapFnArgs[] = { mapFnThisArg, nextValue, JavascriptNumber::ToVar(k, scriptContext) };
  8849. Js::CallInfo mapFnCallInfo(Js::CallFlags_Value, _countof(mapFnArgs));
  8850. nextValue = mapFn->CallFunction(Js::Arguments(mapFnCallInfo, mapFnArgs));
  8851. }
  8852. if (newArr)
  8853. {
  8854. newArr->SetItem(k, nextValue, PropertyOperation_None);
  8855. }
  8856. else
  8857. {
  8858. ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, k, nextValue), scriptContext, k);
  8859. }
  8860. k++;
  8861. }));
  8862. JS_REENTRANT(jsReentLock, JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(k, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  8863. }
  8864. else
  8865. {
  8866. JS_REENTRANT(jsReentLock, int64 len = (int64)OP_GetLength(items, scriptContext));
  8867. if (constructor)
  8868. {
  8869. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(len, scriptContext) };
  8870. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  8871. JS_REENTRANT(jsReentLock, newObj = RecyclableObject::FromVar(JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext)));
  8872. if (JavascriptArray::Is(newObj))
  8873. {
  8874. #if ENABLE_COPYONACCESS_ARRAY
  8875. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
  8876. #endif
  8877. newArr = JavascriptArray::FromVar(newObj);
  8878. }
  8879. }
  8880. else
  8881. {
  8882. // Abstract operation ArrayCreate throws RangeError if length argument is > 2^32 -1
  8883. if (len > MaxArrayLength)
  8884. {
  8885. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect, _u("Array.from"));
  8886. }
  8887. // Static cast len should be valid (len < 2^32) or we would throw above
  8888. newArr = scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(len));
  8889. newArr->EnsureHead<Var>();
  8890. newObj = newArr;
  8891. }
  8892. uint32 k = 0;
  8893. for ( ; k < len; k++)
  8894. {
  8895. Var kValue;
  8896. if (itemsArr)
  8897. {
  8898. JS_REENTRANT(jsReentLock, kValue = itemsArr->DirectGetItem(k));
  8899. }
  8900. else
  8901. {
  8902. JS_REENTRANT(jsReentLock, kValue = JavascriptOperators::OP_GetElementI_UInt32(items, k, scriptContext));
  8903. }
  8904. if (mapping)
  8905. {
  8906. Assert(mapFn != nullptr);
  8907. Assert(mapFnThisArg != nullptr);
  8908. Js::Var mapFnArgs[] = { mapFnThisArg, kValue, JavascriptNumber::ToVar(k, scriptContext) };
  8909. Js::CallInfo mapFnCallInfo(Js::CallFlags_Value, _countof(mapFnArgs));
  8910. JS_REENTRANT(jsReentLock, kValue = mapFn->CallFunction(Js::Arguments(mapFnCallInfo, mapFnArgs)));
  8911. }
  8912. if (newArr)
  8913. {
  8914. newArr->SetItem(k, kValue, PropertyOperation_None);
  8915. }
  8916. else
  8917. {
  8918. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, k, kValue), scriptContext, k));
  8919. }
  8920. }
  8921. JS_REENTRANT(jsReentLock, JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(len, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  8922. }
  8923. return newObj;
  8924. }
  8925. Var JavascriptArray::EntryOf(RecyclableObject* function, CallInfo callInfo, ...)
  8926. {
  8927. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8928. ARGUMENTS(args, callInfo);
  8929. ScriptContext* scriptContext = function->GetScriptContext();
  8930. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8931. Assert(!(callInfo.Flags & CallFlags_New));
  8932. if (args.Info.Count == 0)
  8933. {
  8934. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.of"));
  8935. }
  8936. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::OfHelper(false, args, scriptContext));
  8937. }
  8938. Var JavascriptArray::EntryGetterSymbolSpecies(RecyclableObject* function, CallInfo callInfo, ...)
  8939. {
  8940. ARGUMENTS(args, callInfo);
  8941. Assert(args.Info.Count > 0);
  8942. return args[0];
  8943. }
  8944. // Array.of and %TypedArray%.of as described in ES6.0 (draft 22) Section 22.1.2.2 and 22.2.2.2
  8945. Var JavascriptArray::OfHelper(bool isTypedArrayEntryPoint, Arguments& args, ScriptContext* scriptContext)
  8946. {
  8947. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8948. Assert(args.Info.Count > 0);
  8949. // args.Info.Count cannot equal zero or we would have thrown above so no chance of underflowing
  8950. uint32 len = args.Info.Count - 1;
  8951. Var newObj = nullptr;
  8952. JavascriptArray* newArr = nullptr;
  8953. TypedArrayBase* newTypedArray = nullptr;
  8954. bool isBuiltinArrayCtor = true;
  8955. if (JavascriptOperators::IsConstructor(args[0]))
  8956. {
  8957. RecyclableObject* constructor = RecyclableObject::FromVar(args[0]);
  8958. isBuiltinArrayCtor = (constructor == scriptContext->GetLibrary()->GetArrayConstructor());
  8959. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(len, scriptContext) };
  8960. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  8961. if (isTypedArrayEntryPoint)
  8962. {
  8963. JS_REENTRANT(jsReentLock, newObj = TypedArrayBase::TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), len, scriptContext));
  8964. }
  8965. else
  8966. {
  8967. JS_REENTRANT(jsReentLock, newObj = JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext));
  8968. }
  8969. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  8970. if (JavascriptArray::Is(newObj))
  8971. {
  8972. #if ENABLE_COPYONACCESS_ARRAY
  8973. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
  8974. #endif
  8975. newArr = JavascriptArray::FromVar(newObj);
  8976. }
  8977. else if (TypedArrayBase::Is(newObj))
  8978. {
  8979. newTypedArray = TypedArrayBase::FromVar(newObj);
  8980. }
  8981. }
  8982. else
  8983. {
  8984. // We only throw when the constructor property is not a constructor function in the TypedArray version
  8985. if (isTypedArrayEntryPoint)
  8986. {
  8987. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedFunction, _u("[TypedArray].of"));
  8988. }
  8989. newArr = scriptContext->GetLibrary()->CreateArray(len);
  8990. newArr->EnsureHead<Var>();
  8991. newObj = newArr;
  8992. }
  8993. // At least we have a new object of some kind
  8994. Assert(newObj);
  8995. if (isBuiltinArrayCtor)
  8996. {
  8997. for (uint32 k = 0; k < len; k++)
  8998. {
  8999. Var kValue = args[k + 1];
  9000. newArr->DirectSetItemAt(k, kValue);
  9001. }
  9002. }
  9003. else if (newTypedArray)
  9004. {
  9005. for (uint32 k = 0; k < len; k++)
  9006. {
  9007. Var kValue = args[k + 1];
  9008. JS_REENTRANT(jsReentLock, newTypedArray->DirectSetItem(k, kValue));
  9009. }
  9010. }
  9011. else
  9012. {
  9013. for (uint32 k = 0; k < len; k++)
  9014. {
  9015. Var kValue = args[k + 1];
  9016. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(RecyclableObject::FromVar(newObj), k, kValue), scriptContext, k));
  9017. }
  9018. }
  9019. if (!isTypedArrayEntryPoint)
  9020. {
  9021. // Set length if we are in the Array version of the function
  9022. JS_REENTRANT(jsReentLock, JavascriptOperators::OP_SetProperty(newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(len, scriptContext), scriptContext, nullptr, PropertyOperation_ThrowIfNotExtensible));
  9023. }
  9024. return newObj;
  9025. }
  9026. JavascriptString* JavascriptArray::ToLocaleStringHelper(Var value, ScriptContext* scriptContext)
  9027. {
  9028. TypeId typeId = JavascriptOperators::GetTypeId(value);
  9029. if (typeId == TypeIds_Null || typeId == TypeIds_Undefined)
  9030. {
  9031. return scriptContext->GetLibrary()->GetEmptyString();
  9032. }
  9033. else
  9034. {
  9035. return JavascriptConversion::ToLocaleString(value, scriptContext);
  9036. }
  9037. }
  9038. inline BOOL JavascriptArray::IsFullArray() const
  9039. {
  9040. if (head && head->length == length)
  9041. {
  9042. AssertMsg(head->next == 0 && head->left == 0, "Invalid Array");
  9043. return true;
  9044. }
  9045. return (0 == length);
  9046. }
  9047. /*
  9048. * IsFillFromPrototypes
  9049. * - Check the array has no missing values and only head segment.
  9050. * - Also ensure if the lengths match.
  9051. */
  9052. bool JavascriptArray::IsFillFromPrototypes()
  9053. {
  9054. return !(this->head->next == nullptr && this->HasNoMissingValues() && this->length == this->head->length);
  9055. }
  9056. // Fill all missing value in the array and fill it from prototype between startIndex and limitIndex
  9057. // typically startIndex = 0 and limitIndex = length. From start of the array till end of the array.
  9058. void JavascriptArray::FillFromPrototypes(uint32 startIndex, uint32 limitIndex)
  9059. {
  9060. if (startIndex >= limitIndex)
  9061. {
  9062. return;
  9063. }
  9064. RecyclableObject* prototype = this->GetPrototype();
  9065. // Fill all missing values by walking through prototype
  9066. while (JavascriptOperators::GetTypeId(prototype) != TypeIds_Null)
  9067. {
  9068. ForEachOwnMissingArrayIndexOfObject(this, nullptr, prototype, startIndex, limitIndex,0, [this](uint32 index, Var value) {
  9069. this->SetItem(index, value, PropertyOperation_None);
  9070. });
  9071. prototype = prototype->GetPrototype();
  9072. }
  9073. #ifdef VALIDATE_ARRAY
  9074. ValidateArray();
  9075. #endif
  9076. }
  9077. //
  9078. // JavascriptArray requires head->left == 0 for fast path Get.
  9079. //
  9080. template<typename T>
  9081. void JavascriptArray::EnsureHeadStartsFromZero(Recycler * recycler)
  9082. {
  9083. if (head == nullptr || head->left != 0)
  9084. {
  9085. // This is used to fix up altered arrays.
  9086. // any SegmentMap would be invalid at this point.
  9087. ClearSegmentMap();
  9088. //
  9089. // We could OOM and throw when allocating new empty head, resulting in a corrupted array. Need
  9090. // some protection here. Save the head and switch this array to EmptySegment. Will be restored
  9091. // correctly if allocating new segment succeeds.
  9092. //
  9093. SparseArraySegment<T>* savedHead = SparseArraySegment<T>::From(this->head);
  9094. SparseArraySegment<T>* savedLastUsedSegment = (SparseArraySegment<T>*)this->GetLastUsedSegment();
  9095. SetHeadAndLastUsedSegment(const_cast<SparseArraySegmentBase*>(EmptySegment));
  9096. SparseArraySegment<T> *newSeg = SparseArraySegment<T>::AllocateSegment(recycler, 0, 0, savedHead);
  9097. newSeg->next = savedHead;
  9098. this->head = newSeg;
  9099. SetHasNoMissingValues();
  9100. this->SetLastUsedSegment(savedLastUsedSegment);
  9101. }
  9102. }
  9103. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  9104. void JavascriptArray::CheckForceES5Array()
  9105. {
  9106. if (Configuration::Global.flags.ForceES5Array)
  9107. {
  9108. // There's a bad interaction with the jitted code for native array creation here.
  9109. // ForceES5Array doesn't interact well with native arrays
  9110. if (PHASE_OFF1(NativeArrayPhase))
  9111. {
  9112. GetTypeHandler()->ConvertToTypeWithItemAttributes(this);
  9113. }
  9114. }
  9115. }
  9116. #endif
  9117. template <typename Fn>
  9118. void JavascriptArray::ForEachOwnMissingArrayIndexOfObject(JavascriptArray *baseArray, JavascriptArray *destArray, RecyclableObject* obj, uint32 startIndex, uint32 limitIndex, uint32 destIndex, Fn fn)
  9119. {
  9120. JS_REENTRANCY_LOCK(jsReentLock, baseArray->GetScriptContext()->GetThreadContext());
  9121. Assert(DynamicObject::IsAnyArray(obj) || JavascriptOperators::IsObject(obj));
  9122. Var oldValue;
  9123. JavascriptArray* arr = nullptr;
  9124. if (DynamicObject::IsAnyArray(obj))
  9125. {
  9126. arr = JavascriptArray::FromAnyArray(obj);
  9127. }
  9128. else if (DynamicType::Is(obj->GetTypeId()))
  9129. {
  9130. DynamicObject* dynobj = DynamicObject::FromVar(obj);
  9131. ArrayObject* objectArray = dynobj->GetObjectArray();
  9132. arr = (objectArray && JavascriptArray::IsAnyArray(objectArray)) ? JavascriptArray::FromAnyArray(objectArray) : nullptr;
  9133. }
  9134. if (arr != nullptr)
  9135. {
  9136. if (JavascriptArray::Is(arr))
  9137. {
  9138. arr = EnsureNonNativeArray(arr);
  9139. ArrayElementEnumerator e(arr, startIndex, limitIndex);
  9140. while(e.MoveNext<Var>())
  9141. {
  9142. uint32 index = e.GetIndex();
  9143. if (!baseArray->DirectGetVarItemAt(index, &oldValue, baseArray->GetScriptContext()))
  9144. {
  9145. uint32 n = destIndex + (index - startIndex);
  9146. if (destArray == nullptr || !destArray->DirectGetItemAt(n, &oldValue))
  9147. {
  9148. JS_REENTRANT(jsReentLock, fn(index, e.GetItem<Var>()));
  9149. }
  9150. }
  9151. }
  9152. }
  9153. else
  9154. {
  9155. ScriptContext* scriptContext = obj->GetScriptContext();
  9156. Assert(ES5Array::Is(arr));
  9157. ES5Array* es5Array = ES5Array::FromVar(arr);
  9158. ES5ArrayIndexStaticEnumerator<true> e(es5Array);
  9159. while (e.MoveNext())
  9160. {
  9161. uint32 index = e.GetIndex();
  9162. if (index < startIndex) continue;
  9163. else if (index >= limitIndex) break;
  9164. if (!baseArray->DirectGetVarItemAt(index, &oldValue, baseArray->GetScriptContext()))
  9165. {
  9166. uint32 n = destIndex + (index - startIndex);
  9167. if (destArray == nullptr || !destArray->DirectGetItemAt(n, &oldValue))
  9168. {
  9169. Var value = nullptr;
  9170. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetOwnItem(obj, index, &value, scriptContext));
  9171. if (gotItem)
  9172. {
  9173. JS_REENTRANT(jsReentLock, fn(index, value));
  9174. }
  9175. }
  9176. }
  9177. }
  9178. }
  9179. }
  9180. }
  9181. //
  9182. // ArrayElementEnumerator to enumerate array elements (not including elements from prototypes).
  9183. //
  9184. JavascriptArray::ArrayElementEnumerator::ArrayElementEnumerator(JavascriptArray* arr, uint32 start, uint32 end)
  9185. : start(start), end(min(end, arr->length))
  9186. {
  9187. Init(arr);
  9188. }
  9189. //
  9190. // Initialize this enumerator and prepare for the first MoveNext.
  9191. //
  9192. void JavascriptArray::ArrayElementEnumerator::Init(JavascriptArray* arr)
  9193. {
  9194. // Find start segment
  9195. seg = (arr ? arr->GetBeginLookupSegment(start) : nullptr);
  9196. while (seg && (seg->left + seg->length <= start))
  9197. {
  9198. seg = seg->next;
  9199. }
  9200. // Set start index and endIndex
  9201. if (seg)
  9202. {
  9203. if (seg->left >= end)
  9204. {
  9205. seg = nullptr;
  9206. }
  9207. else
  9208. {
  9209. // set index to be at target index - 1, so MoveNext will move to target
  9210. index = max(seg->left, start) - seg->left - 1;
  9211. endIndex = min(end - seg->left, seg->length);
  9212. }
  9213. }
  9214. }
  9215. //
  9216. // Move to the next element if available.
  9217. //
  9218. template<typename T>
  9219. inline bool JavascriptArray::ArrayElementEnumerator::MoveNext()
  9220. {
  9221. while (seg)
  9222. {
  9223. // Look for next non-null item in current segment
  9224. while (++index < endIndex)
  9225. {
  9226. if (!SparseArraySegment<T>::IsMissingItem(&((SparseArraySegment<T>*)seg)->elements[index]))
  9227. {
  9228. return true;
  9229. }
  9230. }
  9231. // Move to next segment
  9232. seg = seg->next;
  9233. if (seg)
  9234. {
  9235. if (seg->left >= end)
  9236. {
  9237. seg = nullptr;
  9238. break;
  9239. }
  9240. else
  9241. {
  9242. index = static_cast<uint32>(-1);
  9243. endIndex = min(end - seg->left, seg->length);
  9244. }
  9245. }
  9246. }
  9247. return false;
  9248. }
  9249. //
  9250. // Get current array element index.
  9251. //
  9252. uint32 JavascriptArray::ArrayElementEnumerator::GetIndex() const
  9253. {
  9254. Assert(seg && index < seg->length && index < endIndex);
  9255. return seg->left + index;
  9256. }
  9257. //
  9258. // Get current array element value.
  9259. //
  9260. template<typename T>
  9261. T JavascriptArray::ArrayElementEnumerator::GetItem() const
  9262. {
  9263. Assert(seg && index < seg->length && index < endIndex &&
  9264. !SparseArraySegment<T>::IsMissingItem(&((SparseArraySegment<T>*)seg)->elements[index]));
  9265. return ((SparseArraySegment<T>*)seg)->elements[index];
  9266. }
  9267. //
  9268. // Construct a BigIndex initialized to a given uint32 (small index).
  9269. //
  9270. JavascriptArray::BigIndex::BigIndex(uint32 initIndex)
  9271. : index(initIndex), bigIndex(InvalidIndex)
  9272. {
  9273. //ok if initIndex == InvalidIndex
  9274. }
  9275. //
  9276. // Construct a BigIndex initialized to a given uint64 (large or small index).
  9277. //
  9278. JavascriptArray::BigIndex::BigIndex(uint64 initIndex)
  9279. : index(InvalidIndex), bigIndex(initIndex)
  9280. {
  9281. if (bigIndex < InvalidIndex) // if it's actually small index
  9282. {
  9283. index = static_cast<uint32>(bigIndex);
  9284. bigIndex = InvalidIndex;
  9285. }
  9286. }
  9287. bool JavascriptArray::BigIndex::IsUint32Max() const
  9288. {
  9289. return index == InvalidIndex && bigIndex == InvalidIndex;
  9290. }
  9291. bool JavascriptArray::BigIndex::IsSmallIndex() const
  9292. {
  9293. return index < InvalidIndex;
  9294. }
  9295. uint32 JavascriptArray::BigIndex::GetSmallIndex() const
  9296. {
  9297. Assert(IsSmallIndex());
  9298. return index;
  9299. }
  9300. uint64 JavascriptArray::BigIndex::GetBigIndex() const
  9301. {
  9302. Assert(!IsSmallIndex());
  9303. return bigIndex;
  9304. }
  9305. //
  9306. // Convert this index value to a JS number
  9307. //
  9308. Var JavascriptArray::BigIndex::ToNumber(ScriptContext* scriptContext) const
  9309. {
  9310. if (IsSmallIndex())
  9311. {
  9312. return small_index::ToNumber(index, scriptContext);
  9313. }
  9314. else
  9315. {
  9316. return JavascriptNumber::ToVar(bigIndex, scriptContext);
  9317. }
  9318. }
  9319. //
  9320. // Increment this index by 1.
  9321. //
  9322. const JavascriptArray::BigIndex& JavascriptArray::BigIndex::operator++()
  9323. {
  9324. if (IsSmallIndex())
  9325. {
  9326. ++index;
  9327. // If index reaches InvalidIndex, we will start to use bigIndex which is initially InvalidIndex.
  9328. }
  9329. else
  9330. {
  9331. bigIndex = bigIndex + 1;
  9332. }
  9333. return *this;
  9334. }
  9335. //
  9336. // Decrement this index by 1.
  9337. //
  9338. const JavascriptArray::BigIndex& JavascriptArray::BigIndex::operator--()
  9339. {
  9340. if (IsSmallIndex())
  9341. {
  9342. --index;
  9343. }
  9344. else
  9345. {
  9346. Assert(index == InvalidIndex && bigIndex >= InvalidIndex);
  9347. --bigIndex;
  9348. if (bigIndex < InvalidIndex)
  9349. {
  9350. index = InvalidIndex - 1;
  9351. bigIndex = InvalidIndex;
  9352. }
  9353. }
  9354. return *this;
  9355. }
  9356. JavascriptArray::BigIndex JavascriptArray::BigIndex::operator+(const BigIndex& delta) const
  9357. {
  9358. if (delta.IsSmallIndex())
  9359. {
  9360. return operator+(delta.GetSmallIndex());
  9361. }
  9362. if (IsSmallIndex())
  9363. {
  9364. return index + delta.GetBigIndex();
  9365. }
  9366. return bigIndex + delta.GetBigIndex();
  9367. }
  9368. //
  9369. // Get a new BigIndex representing this + delta.
  9370. //
  9371. JavascriptArray::BigIndex JavascriptArray::BigIndex::operator+(uint32 delta) const
  9372. {
  9373. if (IsSmallIndex())
  9374. {
  9375. uint32 newIndex;
  9376. if (UInt32Math::Add(index, delta, &newIndex))
  9377. {
  9378. return static_cast<uint64>(index) + static_cast<uint64>(delta);
  9379. }
  9380. else
  9381. {
  9382. return newIndex; // ok if newIndex == InvalidIndex
  9383. }
  9384. }
  9385. else
  9386. {
  9387. return bigIndex + static_cast<uint64>(delta);
  9388. }
  9389. }
  9390. bool JavascriptArray::BigIndex::operator==(const BigIndex& rhs) const
  9391. {
  9392. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9393. {
  9394. return this->GetSmallIndex() == rhs.GetSmallIndex();
  9395. }
  9396. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9397. {
  9398. // if lhs is big promote rhs
  9399. return this->GetBigIndex() == (uint64) rhs.GetSmallIndex();
  9400. }
  9401. else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
  9402. {
  9403. // if rhs is big promote lhs
  9404. return ((uint64)this->GetSmallIndex()) == rhs.GetBigIndex();
  9405. }
  9406. return this->GetBigIndex() == rhs.GetBigIndex();
  9407. }
  9408. bool JavascriptArray::BigIndex::operator> (const BigIndex& rhs) const
  9409. {
  9410. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9411. {
  9412. return this->GetSmallIndex() > rhs.GetSmallIndex();
  9413. }
  9414. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9415. {
  9416. // if lhs is big promote rhs
  9417. return this->GetBigIndex() > (uint64)rhs.GetSmallIndex();
  9418. }
  9419. else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
  9420. {
  9421. // if rhs is big promote lhs
  9422. return ((uint64)this->GetSmallIndex()) > rhs.GetBigIndex();
  9423. }
  9424. return this->GetBigIndex() > rhs.GetBigIndex();
  9425. }
  9426. bool JavascriptArray::BigIndex::operator< (const BigIndex& rhs) const
  9427. {
  9428. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9429. {
  9430. return this->GetSmallIndex() < rhs.GetSmallIndex();
  9431. }
  9432. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9433. {
  9434. // if lhs is big promote rhs
  9435. return this->GetBigIndex() < (uint64)rhs.GetSmallIndex();
  9436. }
  9437. else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
  9438. {
  9439. // if rhs is big promote lhs
  9440. return ((uint64)this->GetSmallIndex()) < rhs.GetBigIndex();
  9441. }
  9442. return this->GetBigIndex() < rhs.GetBigIndex();
  9443. }
  9444. bool JavascriptArray::BigIndex::operator<=(const BigIndex& rhs) const
  9445. {
  9446. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9447. {
  9448. return this->GetSmallIndex() <= rhs.GetSmallIndex();
  9449. }
  9450. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9451. {
  9452. // if lhs is big promote rhs
  9453. return this->GetBigIndex() <= (uint64)rhs.GetSmallIndex();
  9454. }
  9455. else if (!rhs.IsSmallIndex() && !this->IsSmallIndex())
  9456. {
  9457. // if rhs is big promote lhs
  9458. return ((uint64)this->GetSmallIndex()) <= rhs.GetBigIndex();
  9459. }
  9460. return this->GetBigIndex() <= rhs.GetBigIndex();
  9461. }
  9462. bool JavascriptArray::BigIndex::operator>=(const BigIndex& rhs) const
  9463. {
  9464. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9465. {
  9466. return this->GetSmallIndex() >= rhs.GetSmallIndex();
  9467. }
  9468. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9469. {
  9470. // if lhs is big promote rhs
  9471. return this->GetBigIndex() >= (uint64)rhs.GetSmallIndex();
  9472. }
  9473. else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
  9474. {
  9475. // if rhs is big promote lhs
  9476. return ((uint64)this->GetSmallIndex()) >= rhs.GetBigIndex();
  9477. }
  9478. return this->GetBigIndex() >= rhs.GetBigIndex();
  9479. }
  9480. BOOL JavascriptArray::BigIndex::GetItem(JavascriptArray* arr, Var* outVal) const
  9481. {
  9482. if (IsSmallIndex())
  9483. {
  9484. return small_index::GetItem(arr, index, outVal);
  9485. }
  9486. else
  9487. {
  9488. ScriptContext* scriptContext = arr->GetScriptContext();
  9489. PropertyRecord const * propertyRecord;
  9490. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9491. return arr->GetProperty(arr, propertyRecord->GetPropertyId(), outVal, NULL, scriptContext);
  9492. }
  9493. }
  9494. BOOL JavascriptArray::BigIndex::SetItem(JavascriptArray* arr, Var newValue) const
  9495. {
  9496. if (IsSmallIndex())
  9497. {
  9498. return small_index::SetItem(arr, index, newValue);
  9499. }
  9500. else
  9501. {
  9502. ScriptContext* scriptContext = arr->GetScriptContext();
  9503. PropertyRecord const * propertyRecord;
  9504. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9505. return arr->SetProperty(propertyRecord->GetPropertyId(), newValue, PropertyOperation_None, NULL);
  9506. }
  9507. }
  9508. void JavascriptArray::BigIndex::SetItemIfNotExist(JavascriptArray* arr, Var newValue) const
  9509. {
  9510. if (IsSmallIndex())
  9511. {
  9512. small_index::SetItemIfNotExist(arr, index, newValue);
  9513. }
  9514. else
  9515. {
  9516. ScriptContext* scriptContext = arr->GetScriptContext();
  9517. PropertyRecord const * propertyRecord;
  9518. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9519. Var oldValue;
  9520. PropertyId propertyId = propertyRecord->GetPropertyId();
  9521. if (!arr->GetProperty(arr, propertyId, &oldValue, NULL, scriptContext))
  9522. {
  9523. arr->SetProperty(propertyId, newValue, PropertyOperation_None, NULL);
  9524. }
  9525. }
  9526. }
  9527. BOOL JavascriptArray::BigIndex::DeleteItem(JavascriptArray* arr) const
  9528. {
  9529. if (IsSmallIndex())
  9530. {
  9531. return small_index::DeleteItem(arr, index);
  9532. }
  9533. else
  9534. {
  9535. ScriptContext* scriptContext = arr->GetScriptContext();
  9536. PropertyRecord const * propertyRecord;
  9537. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9538. return arr->DeleteProperty(propertyRecord->GetPropertyId(), PropertyOperation_None);
  9539. }
  9540. }
  9541. BOOL JavascriptArray::BigIndex::SetItem(RecyclableObject* obj, Var newValue, PropertyOperationFlags flags) const
  9542. {
  9543. if (IsSmallIndex())
  9544. {
  9545. return small_index::SetItem(obj, index, newValue, flags);
  9546. }
  9547. else
  9548. {
  9549. ScriptContext* scriptContext = obj->GetScriptContext();
  9550. PropertyRecord const * propertyRecord;
  9551. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9552. return JavascriptOperators::SetProperty(obj, obj, propertyRecord->GetPropertyId(), newValue, scriptContext, flags);
  9553. }
  9554. }
  9555. BOOL JavascriptArray::BigIndex::DeleteItem(RecyclableObject* obj, PropertyOperationFlags flags) const
  9556. {
  9557. if (IsSmallIndex())
  9558. {
  9559. return small_index::DeleteItem(obj, index, flags);
  9560. }
  9561. else
  9562. {
  9563. PropertyRecord const * propertyRecord;
  9564. JavascriptOperators::GetPropertyIdForInt(bigIndex, obj->GetScriptContext(), &propertyRecord);
  9565. return JavascriptOperators::DeleteProperty(obj, propertyRecord->GetPropertyId(), flags);
  9566. }
  9567. }
  9568. //
  9569. // Truncate the array at start and clone the truncated span as properties starting at dstIndex (asserting dstIndex >= MaxArrayLength).
  9570. //
  9571. void JavascriptArray::TruncateToProperties(const BigIndex& dstIndex, uint32 start)
  9572. {
  9573. Assert(!dstIndex.IsSmallIndex());
  9574. typedef IndexTrace<BigIndex> index_trace;
  9575. BigIndex dst = dstIndex;
  9576. uint32 i = start;
  9577. ArrayElementEnumerator e(this, start);
  9578. while(e.MoveNext<Var>())
  9579. {
  9580. // delete all items not enumerated
  9581. while (i < e.GetIndex())
  9582. {
  9583. index_trace::DeleteItem(this, dst);
  9584. ++i;
  9585. ++dst;
  9586. }
  9587. // Copy over the item
  9588. index_trace::SetItem(this, dst, e.GetItem<Var>());
  9589. ++i;
  9590. ++dst;
  9591. }
  9592. // Delete the rest till length
  9593. while (i < this->length)
  9594. {
  9595. index_trace::DeleteItem(this, dst);
  9596. ++i;
  9597. ++dst;
  9598. }
  9599. // Elements moved, truncate the array at start
  9600. SetLength(start);
  9601. }
  9602. //
  9603. // Copy a srcArray elements (including elements from prototypes) to a dstArray starting from an index.
  9604. //
  9605. void JavascriptArray::InternalCopyArrayElements(JavascriptArray* dstArray, const uint32 dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
  9606. {
  9607. Assert(start < end && end <= srcArray->length);
  9608. uint32 count = 0;
  9609. // iterate on the array itself
  9610. ArrayElementEnumerator e(srcArray, start, end);
  9611. while(e.MoveNext<Var>())
  9612. {
  9613. uint32 n = dstIndex + (e.GetIndex() - start);
  9614. dstArray->DirectSetItemAt(n, e.GetItem<Var>());
  9615. count++;
  9616. }
  9617. // iterate on the array's prototypes only if not all elements found
  9618. if (start + count != end)
  9619. {
  9620. InternalFillFromPrototype(dstArray, dstIndex, srcArray, start, end, count);
  9621. }
  9622. }
  9623. //
  9624. // Faster small_index overload of CopyArrayElements, asserting the uint32 dstIndex won't overflow.
  9625. //
  9626. void JavascriptArray::CopyArrayElements(JavascriptArray* dstArray, uint32 dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
  9627. {
  9628. end = min(end, srcArray->length);
  9629. if (start < end)
  9630. {
  9631. Assert(end - start <= MaxArrayLength - dstIndex);
  9632. InternalCopyArrayElements(dstArray, dstIndex, srcArray, start, end);
  9633. }
  9634. }
  9635. template <typename T>
  9636. void JavascriptArray::CopyAnyArrayElementsToVar(JavascriptArray* dstArray, T dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
  9637. {
  9638. #if ENABLE_COPYONACCESS_ARRAY
  9639. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(srcArray);
  9640. #endif
  9641. #if ENABLE_COPYONACCESS_ARRAY
  9642. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(dstArray);
  9643. #endif
  9644. if (JavascriptNativeIntArray::Is(srcArray))
  9645. {
  9646. CopyNativeIntArrayElementsToVar(dstArray, dstIndex, JavascriptNativeIntArray::FromVar(srcArray), start, end);
  9647. }
  9648. else if (JavascriptNativeFloatArray::Is(srcArray))
  9649. {
  9650. CopyNativeFloatArrayElementsToVar(dstArray, dstIndex, JavascriptNativeFloatArray::FromVar(srcArray), start, end);
  9651. }
  9652. else
  9653. {
  9654. CopyArrayElements(dstArray, dstIndex, srcArray, start, end);
  9655. }
  9656. }
  9657. //
  9658. // Faster small_index overload of CopyArrayElements, asserting the uint32 dstIndex won't overflow.
  9659. //
  9660. void JavascriptArray::CopyNativeIntArrayElementsToVar(JavascriptArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
  9661. {
  9662. end = min(end, srcArray->length);
  9663. if (start < end)
  9664. {
  9665. Assert(end - start <= MaxArrayLength - dstIndex);
  9666. InternalCopyNativeIntArrayElements(dstArray, dstIndex, srcArray, start, end);
  9667. }
  9668. }
  9669. bool JavascriptArray::CopyNativeIntArrayElements(JavascriptNativeIntArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
  9670. {
  9671. end = min(end, srcArray->length);
  9672. if (start >= end)
  9673. {
  9674. return false;
  9675. }
  9676. Assert(end - start <= MaxArrayLength - dstIndex);
  9677. Assert(start < end && end <= srcArray->length);
  9678. uint32 count = 0;
  9679. // iterate on the array itself
  9680. ArrayElementEnumerator e(srcArray, start, end);
  9681. while(e.MoveNext<int32>())
  9682. {
  9683. uint n = dstIndex + (e.GetIndex() - start);
  9684. dstArray->DirectSetItemAt(n, e.GetItem<int32>());
  9685. count++;
  9686. }
  9687. // iterate on the array's prototypes only if not all elements found
  9688. if (start + count != end)
  9689. {
  9690. JavascriptArray *varArray = JavascriptNativeIntArray::ToVarArray(dstArray);
  9691. InternalFillFromPrototype(varArray, dstIndex, srcArray, start, end, count);
  9692. return true;
  9693. }
  9694. return false;
  9695. }
  9696. bool JavascriptArray::CopyNativeIntArrayElementsToFloat(JavascriptNativeFloatArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
  9697. {
  9698. end = min(end, srcArray->length);
  9699. if (start >= end)
  9700. {
  9701. return false;
  9702. }
  9703. Assert(end - start <= MaxArrayLength - dstIndex);
  9704. Assert(start < end && end <= srcArray->length);
  9705. uint32 count = 0;
  9706. // iterate on the array itself
  9707. ArrayElementEnumerator e(srcArray, start, end);
  9708. while(e.MoveNext<int32>())
  9709. {
  9710. uint n = dstIndex + (e.GetIndex() - start);
  9711. dstArray->DirectSetItemAt(n, (double)e.GetItem<int32>());
  9712. count++;
  9713. }
  9714. // iterate on the array's prototypes only if not all elements found
  9715. if (start + count != end)
  9716. {
  9717. JavascriptArray *varArray = JavascriptNativeFloatArray::ToVarArray(dstArray);
  9718. InternalFillFromPrototype(varArray, dstIndex, srcArray, start, end, count);
  9719. return true;
  9720. }
  9721. return false;
  9722. }
  9723. //
  9724. // Faster small_index overload of CopyArrayElements, asserting the uint32 dstIndex won't overflow.
  9725. //
  9726. void JavascriptArray::CopyNativeFloatArrayElementsToVar(JavascriptArray* dstArray, uint32 dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
  9727. {
  9728. end = min(end, srcArray->length);
  9729. if (start < end)
  9730. {
  9731. Assert(end - start <= MaxArrayLength - dstIndex);
  9732. InternalCopyNativeFloatArrayElements(dstArray, dstIndex, srcArray, start, end);
  9733. }
  9734. }
  9735. bool JavascriptArray::CopyNativeFloatArrayElements(JavascriptNativeFloatArray* dstArray, uint32 dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
  9736. {
  9737. end = min(end, srcArray->length);
  9738. if (start >= end)
  9739. {
  9740. return false;
  9741. }
  9742. Assert(end - start <= MaxArrayLength - dstIndex);
  9743. Assert(start < end && end <= srcArray->length);
  9744. uint32 count = 0;
  9745. // iterate on the array itself
  9746. ArrayElementEnumerator e(srcArray, start, end);
  9747. while(e.MoveNext<double>())
  9748. {
  9749. uint n = dstIndex + (e.GetIndex() - start);
  9750. dstArray->DirectSetItemAt(n, e.GetItem<double>());
  9751. count++;
  9752. }
  9753. // iterate on the array's prototypes only if not all elements found
  9754. if (start + count != end)
  9755. {
  9756. JavascriptArray *varArray = JavascriptNativeFloatArray::ToVarArray(dstArray);
  9757. InternalFillFromPrototype(varArray, dstIndex, srcArray, start, end, count);
  9758. return true;
  9759. }
  9760. return false;
  9761. }
  9762. JavascriptArray *JavascriptArray::EnsureNonNativeArray(JavascriptArray *arr)
  9763. {
  9764. #if ENABLE_COPYONACCESS_ARRAY
  9765. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(arr);
  9766. #endif
  9767. if (JavascriptNativeIntArray::Is(arr))
  9768. {
  9769. arr = JavascriptNativeIntArray::ToVarArray((JavascriptNativeIntArray*)arr);
  9770. }
  9771. else if (JavascriptNativeFloatArray::Is(arr))
  9772. {
  9773. arr = JavascriptNativeFloatArray::ToVarArray((JavascriptNativeFloatArray*)arr);
  9774. }
  9775. return arr;
  9776. }
  9777. BOOL JavascriptNativeIntArray::DirectGetItemAtFull(uint32 index, Var* outVal)
  9778. {
  9779. ScriptContext* requestContext = type->GetScriptContext();
  9780. if (JavascriptConversion::PropertyQueryFlagsToBoolean(JavascriptNativeIntArray::GetItemQuery(this, index, outVal, requestContext)))
  9781. {
  9782. return TRUE;
  9783. }
  9784. return JavascriptOperators::GetItem(this, this->GetPrototype(), index, outVal, requestContext);
  9785. }
  9786. BOOL JavascriptNativeFloatArray::DirectGetItemAtFull(uint32 index, Var* outVal)
  9787. {
  9788. ScriptContext* requestContext = type->GetScriptContext();
  9789. if (JavascriptConversion::PropertyQueryFlagsToBoolean(JavascriptNativeFloatArray::GetItemQuery(this, index, outVal, requestContext)))
  9790. {
  9791. return TRUE;
  9792. }
  9793. return JavascriptOperators::GetItem(this, this->GetPrototype(), index, outVal, requestContext);
  9794. }
  9795. void JavascriptArray::InternalCopyNativeIntArrayElements(JavascriptArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
  9796. {
  9797. Assert(start < end && end <= srcArray->length);
  9798. uint32 count = 0;
  9799. // iterate on the array itself
  9800. ScriptContext *scriptContext = dstArray->GetScriptContext();
  9801. ArrayElementEnumerator e(srcArray, start, end);
  9802. while(e.MoveNext<int32>())
  9803. {
  9804. uint32 n = dstIndex + (e.GetIndex() - start);
  9805. dstArray->DirectSetItemAt(n, JavascriptNumber::ToVar(e.GetItem<int32>(), scriptContext));
  9806. count++;
  9807. }
  9808. // iterate on the array's prototypes only if not all elements found
  9809. if (start + count != end)
  9810. {
  9811. InternalFillFromPrototype(dstArray, dstIndex, srcArray, start, end, count);
  9812. }
  9813. }
  9814. void JavascriptArray::InternalCopyNativeFloatArrayElements(JavascriptArray* dstArray, uint32 dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
  9815. {
  9816. Assert(start < end && end <= srcArray->length);
  9817. uint32 count = 0;
  9818. // iterate on the array itself
  9819. ScriptContext *scriptContext = dstArray->GetScriptContext();
  9820. ArrayElementEnumerator e(srcArray, start, end);
  9821. while(e.MoveNext<double>())
  9822. {
  9823. uint32 n = dstIndex + (e.GetIndex() - start);
  9824. dstArray->DirectSetItemAt(n, JavascriptNumber::ToVarWithCheck(e.GetItem<double>(), scriptContext));
  9825. count++;
  9826. }
  9827. // iterate on the array's prototypes only if not all elements found
  9828. if (start + count != end)
  9829. {
  9830. InternalFillFromPrototype(dstArray, dstIndex, srcArray, start, end, count);
  9831. }
  9832. }
  9833. Var JavascriptArray::SpreadArrayArgs(Var arrayToSpread, const Js::AuxArray<uint32> *spreadIndices, ScriptContext *scriptContext)
  9834. {
  9835. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  9836. // At this stage we have an array literal with some arguments to be spread.
  9837. // First we need to calculate the real size of the final literal.
  9838. #if ENABLE_COPYONACCESS_ARRAY
  9839. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(arrayToSpread);
  9840. #endif
  9841. JavascriptArray *array = FromVar(arrayToSpread);
  9842. uint32 arrayLength = array->GetLength();
  9843. uint32 actualLength = arrayLength;
  9844. for (unsigned i = 0; i < spreadIndices->count; ++i)
  9845. {
  9846. JS_REENTRANT(jsReentLock,
  9847. actualLength = UInt32Math::Add(actualLength - 1, GetSpreadArgLen(array->DirectGetItem(spreadIndices->elements[i]), scriptContext)));
  9848. }
  9849. JavascriptArray *result = FromVar(OP_NewScArrayWithMissingValues(actualLength, scriptContext));
  9850. // Now we copy each element and expand the spread parameters inline.
  9851. for (unsigned i = 0, spreadArrIndex = 0, resultIndex = 0; i < arrayLength && resultIndex < actualLength; ++i)
  9852. {
  9853. uint32 spreadIndex = spreadIndices->elements[spreadArrIndex]; // The index of the next element to be spread.
  9854. // 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.
  9855. auto needArraySlowCopy = [&](Var instance) {
  9856. if (JavascriptArray::Is(instance))
  9857. {
  9858. JavascriptArray *arr = JavascriptArray::FromVar(instance);
  9859. JS_REENTRANT_UNLOCK(jsReentLock, return arr->IsCrossSiteObject() || arr->IsFillFromPrototypes());
  9860. }
  9861. return false;
  9862. };
  9863. // Designed to have interchangeable arguments with CopyAnyArrayElementsToVar.
  9864. auto slowCopy = [&scriptContext, &needArraySlowCopy
  9865. ](JavascriptArray *dstArray, unsigned dstIndex, Var srcArray, uint32 start, uint32 end) {
  9866. Assert(needArraySlowCopy(srcArray) || ArgumentsObject::Is(srcArray) || TypedArrayBase::Is(srcArray) || JavascriptString::Is(srcArray));
  9867. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  9868. RecyclableObject *propertyObject;
  9869. if (!JavascriptOperators::GetPropertyObject(srcArray, scriptContext, &propertyObject))
  9870. {
  9871. JavascriptError::ThrowTypeError(scriptContext, JSERR_InvalidSpreadArgument);
  9872. }
  9873. for (uint32 j = start; j < end; j++)
  9874. {
  9875. Var element = nullptr;
  9876. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(srcArray, propertyObject, j, &element, scriptContext));
  9877. if (!gotItem)
  9878. {
  9879. // Copy across missing values as undefined as per 12.2.5.2 SpreadElement : ... AssignmentExpression 5f.
  9880. element = scriptContext->GetLibrary()->GetUndefined();
  9881. }
  9882. dstArray->DirectSetItemAt(dstIndex++, element);
  9883. }
  9884. };
  9885. if (i < spreadIndex)
  9886. {
  9887. // Any non-spread elements can be copied in bulk.
  9888. if (needArraySlowCopy(array))
  9889. {
  9890. slowCopy(result, resultIndex, (Var)array, i, spreadIndex);
  9891. }
  9892. else
  9893. {
  9894. JS_REENTRANT(jsReentLock, CopyAnyArrayElementsToVar(result, resultIndex, array, i, spreadIndex));
  9895. }
  9896. resultIndex += spreadIndex - i;
  9897. i = spreadIndex - 1;
  9898. continue;
  9899. }
  9900. else if (i > spreadIndex)
  9901. {
  9902. // Any non-spread elements terminating the array can also be copied in bulk.
  9903. Assert(spreadArrIndex == spreadIndices->count - 1);
  9904. if (needArraySlowCopy(array))
  9905. {
  9906. slowCopy(result, resultIndex, array, i, arrayLength);
  9907. }
  9908. else
  9909. {
  9910. JS_REENTRANT(jsReentLock, CopyAnyArrayElementsToVar(result, resultIndex, array, i, arrayLength));
  9911. }
  9912. break;
  9913. }
  9914. else
  9915. {
  9916. JS_REENTRANT(jsReentLock, Var instance = array->DirectGetItem(i));
  9917. if (SpreadArgument::Is(instance))
  9918. {
  9919. SpreadArgument* spreadArgument = SpreadArgument::FromVar(instance);
  9920. uint32 len = spreadArgument->GetArgumentSpreadCount();
  9921. const Var* spreadItems = spreadArgument->GetArgumentSpread();
  9922. for (uint32 j = 0; j < len; j++)
  9923. {
  9924. result->DirectSetItemAt(resultIndex++, spreadItems[j]);
  9925. }
  9926. }
  9927. else
  9928. {
  9929. Assert(JavascriptOperators::IsUndefinedObject(instance));
  9930. result->DirectSetItemAt(resultIndex++, instance);
  9931. }
  9932. if (spreadArrIndex < spreadIndices->count - 1)
  9933. {
  9934. spreadArrIndex++;
  9935. }
  9936. }
  9937. }
  9938. AssertMsg(arrayLength == array->GetLength(), "Array's length should not have changed");
  9939. return result;
  9940. }
  9941. uint32 JavascriptArray::GetSpreadArgLen(Var spreadArg, ScriptContext *scriptContext)
  9942. {
  9943. // A spread argument can be anything that returns a 'length' property, even if that
  9944. // property is null or undefined.
  9945. spreadArg = CrossSite::MarshalVar(scriptContext, spreadArg);
  9946. if (JavascriptArray::Is(spreadArg))
  9947. {
  9948. JavascriptArray *arr = JavascriptArray::FromVar(spreadArg);
  9949. return arr->GetLength();
  9950. }
  9951. if (TypedArrayBase::Is(spreadArg))
  9952. {
  9953. TypedArrayBase *tarr = TypedArrayBase::FromVar(spreadArg);
  9954. return tarr->GetLength();
  9955. }
  9956. if (SpreadArgument::Is(spreadArg))
  9957. {
  9958. SpreadArgument *spreadFunctionArgs = SpreadArgument::FromVar(spreadArg);
  9959. return spreadFunctionArgs->GetArgumentSpreadCount();
  9960. }
  9961. AssertMsg(false, "LdCustomSpreadIteratorList should have converted the arg to one of the above types");
  9962. Throw::FatalInternalError();
  9963. }
  9964. #ifdef VALIDATE_ARRAY
  9965. class ArraySegmentsVisitor
  9966. {
  9967. private:
  9968. SparseArraySegmentBase* seg;
  9969. public:
  9970. ArraySegmentsVisitor(SparseArraySegmentBase* head)
  9971. : seg(head)
  9972. {
  9973. }
  9974. void operator()(SparseArraySegmentBase* s)
  9975. {
  9976. Assert(seg == s);
  9977. if (seg)
  9978. {
  9979. seg = seg->next;
  9980. }
  9981. }
  9982. };
  9983. void JavascriptArray::ValidateArrayCommon()
  9984. {
  9985. SparseArraySegmentBase * lastUsedSegment = this->GetLastUsedSegment();
  9986. AssertMsg(this != nullptr && head && lastUsedSegment, "Array should not be null");
  9987. AssertMsg(head->left == 0, "Array always should have a segment starting at zero");
  9988. // Simple segments validation
  9989. bool foundLastUsedSegment = false;
  9990. SparseArraySegmentBase *seg = head;
  9991. while(seg != nullptr)
  9992. {
  9993. if (seg == lastUsedSegment)
  9994. {
  9995. foundLastUsedSegment = true;
  9996. }
  9997. AssertMsg(seg->length <= seg->size , "Length greater than size not possible");
  9998. SparseArraySegmentBase* next = seg->next;
  9999. if (next != nullptr)
  10000. {
  10001. AssertMsg(seg->left < next->left, "Segment is adjacent to or overlaps with next segment");
  10002. AssertMsg(seg->size <= (next->left - seg->left), "Segment is adjacent to or overlaps with next segment");
  10003. AssertMsg(!SparseArraySegmentBase::IsLeafSegment(seg, this->GetScriptContext()->GetRecycler()), "Leaf segment with a next pointer");
  10004. }
  10005. else
  10006. {
  10007. AssertMsg(seg->length <= MaxArrayLength - seg->left, "Segment index range overflow");
  10008. AssertMsg(seg->left + seg->length <= this->length, "Segment index range exceeds array length");
  10009. }
  10010. seg = next;
  10011. }
  10012. AssertMsg(foundLastUsedSegment || HasSegmentMap(), "Corrupt lastUsedSegment in array header");
  10013. // Validate segmentMap if present
  10014. if (HasSegmentMap())
  10015. {
  10016. ArraySegmentsVisitor visitor(head);
  10017. GetSegmentMap()->Walk(visitor);
  10018. }
  10019. }
  10020. void JavascriptArray::ValidateArray()
  10021. {
  10022. if (!Js::Configuration::Global.flags.ArrayValidate)
  10023. {
  10024. return;
  10025. }
  10026. ValidateArrayCommon();
  10027. // Detailed segments validation
  10028. JavascriptArray::ValidateVarSegment(SparseArraySegment<Var>::From(head));
  10029. }
  10030. void JavascriptNativeIntArray::ValidateArray()
  10031. {
  10032. if (!Js::Configuration::Global.flags.ArrayValidate)
  10033. {
  10034. #if DBG
  10035. SparseArraySegmentBase *seg = head;
  10036. while (seg)
  10037. {
  10038. if (seg->next != nullptr)
  10039. {
  10040. AssertMsg(!SparseArraySegmentBase::IsLeafSegment(seg, this->GetScriptContext()->GetRecycler()), "Leaf segment with a next pointer");
  10041. }
  10042. seg = seg->next;
  10043. }
  10044. #endif
  10045. return;
  10046. }
  10047. ValidateArrayCommon();
  10048. // Detailed segments validation
  10049. JavascriptArray::ValidateSegment<int32>(SparseArraySegment<int32>::From(head));
  10050. }
  10051. void JavascriptNativeFloatArray::ValidateArray()
  10052. {
  10053. if (!Js::Configuration::Global.flags.ArrayValidate)
  10054. {
  10055. #if DBG
  10056. SparseArraySegmentBase *seg = head;
  10057. while (seg)
  10058. {
  10059. if (seg->next != nullptr)
  10060. {
  10061. AssertMsg(!SparseArraySegmentBase::IsLeafSegment(seg, this->GetScriptContext()->GetRecycler()), "Leaf segment with a next pointer");
  10062. }
  10063. seg = seg->next;
  10064. }
  10065. #endif
  10066. return;
  10067. }
  10068. ValidateArrayCommon();
  10069. // Detailed segments validation
  10070. JavascriptArray::ValidateSegment<double>(SparseArraySegment<double>::From(head));
  10071. }
  10072. void JavascriptArray::ValidateVarSegment(SparseArraySegment<Var>* seg)
  10073. {
  10074. if (!Js::Configuration::Global.flags.ArrayValidate)
  10075. {
  10076. return;
  10077. }
  10078. int32 inspect;
  10079. double inspectDouble;
  10080. while (seg)
  10081. {
  10082. uint32 i = 0;
  10083. for (i = 0; i < seg->length; i++)
  10084. {
  10085. if (SparseArraySegment<Var>::IsMissingItem(&seg->elements[i]))
  10086. {
  10087. continue;
  10088. }
  10089. if (TaggedInt::Is(seg->elements[i]))
  10090. {
  10091. inspect = TaggedInt::ToInt32(seg->elements[i]);
  10092. }
  10093. else if (JavascriptNumber::Is_NoTaggedIntCheck(seg->elements[i]))
  10094. {
  10095. inspectDouble = JavascriptNumber::GetValue(seg->elements[i]);
  10096. }
  10097. else
  10098. {
  10099. AssertMsg(RecyclableObject::Is(seg->elements[i]), "Invalid entry in segment");
  10100. }
  10101. }
  10102. ValidateSegment(seg);
  10103. seg = SparseArraySegment<Var>::From(seg->next);
  10104. }
  10105. }
  10106. template<typename T>
  10107. void JavascriptArray::ValidateSegment(SparseArraySegment<T>* seg)
  10108. {
  10109. if (!Js::Configuration::Global.flags.ArrayValidate)
  10110. {
  10111. return;
  10112. }
  10113. while (seg)
  10114. {
  10115. uint32 i = seg->length;
  10116. while (i < seg->size)
  10117. {
  10118. AssertMsg(SparseArraySegment<T>::IsMissingItem(&seg->elements[i]), "Non missing value the end of the segment");
  10119. i++;
  10120. }
  10121. seg = SparseArraySegment<T>::From(seg->next);
  10122. }
  10123. }
  10124. #endif
  10125. template <typename T>
  10126. void JavascriptArray::InitBoxedInlineHeadSegment(SparseArraySegment<T> * dst, SparseArraySegment<T> * src)
  10127. {
  10128. // Don't copy the segment map, we will build it again
  10129. SetFlags(GetFlags() & ~DynamicObjectFlags::HasSegmentMap);
  10130. SetHeadAndLastUsedSegment(dst);
  10131. dst->left = src->left;
  10132. dst->length = src->length;
  10133. dst->size = src->size;
  10134. dst->CheckLengthvsSize();
  10135. dst->next = src->next;
  10136. CopyArray(dst->elements, dst->size, src->elements, src->size);
  10137. }
  10138. JavascriptArray::JavascriptArray(JavascriptArray * instance, bool boxHead)
  10139. : ArrayObject(instance)
  10140. {
  10141. if (boxHead)
  10142. {
  10143. InitBoxedInlineHeadSegment(DetermineInlineHeadSegmentPointer<JavascriptArray, 0, true>(this), SparseArraySegment<Var>::From(instance->head));
  10144. }
  10145. else
  10146. {
  10147. SetFlags(GetFlags() & ~DynamicObjectFlags::HasSegmentMap);
  10148. head = instance->head;
  10149. SetLastUsedSegment(instance->GetLastUsedSegment());
  10150. }
  10151. }
  10152. template <typename T>
  10153. T * JavascriptArray::BoxStackInstance(T * instance)
  10154. {
  10155. Assert(ThreadContext::IsOnStack(instance));
  10156. // On the stack, the we reserved a pointer before the object as to store the boxed value
  10157. T ** boxedInstanceRef = ((T **)instance) - 1;
  10158. T * boxedInstance = *boxedInstanceRef;
  10159. if (boxedInstance)
  10160. {
  10161. return boxedInstance;
  10162. }
  10163. const size_t inlineSlotsSize = instance->GetTypeHandler()->GetInlineSlotsSize();
  10164. if (ThreadContext::IsOnStack(instance->head))
  10165. {
  10166. boxedInstance = RecyclerNewPlusZ(instance->GetRecycler(),
  10167. inlineSlotsSize + sizeof(Js::SparseArraySegmentBase) + instance->head->size * sizeof(typename T::TElement),
  10168. T, instance, true);
  10169. }
  10170. else if(inlineSlotsSize)
  10171. {
  10172. boxedInstance = RecyclerNewPlusZ(instance->GetRecycler(), inlineSlotsSize, T, instance, false);
  10173. }
  10174. else
  10175. {
  10176. boxedInstance = RecyclerNew(instance->GetRecycler(), T, instance, false);
  10177. }
  10178. *boxedInstanceRef = boxedInstance;
  10179. return boxedInstance;
  10180. }
  10181. JavascriptArray *
  10182. JavascriptArray::BoxStackInstance(JavascriptArray * instance)
  10183. {
  10184. return BoxStackInstance<JavascriptArray>(instance);
  10185. }
  10186. #if ENABLE_TTD
  10187. void JavascriptArray::MarkVisitKindSpecificPtrs(TTD::SnapshotExtractor* extractor)
  10188. {
  10189. TTDAssert(this->GetTypeId() == Js::TypeIds_Array || this->GetTypeId() == Js::TypeIds_ES5Array, "Should only be used on basic arrays (or called as super from ES5Array.");
  10190. ScriptContext* ctx = this->GetScriptContext();
  10191. uint32 index = Js::JavascriptArray::InvalidIndex;
  10192. while(true)
  10193. {
  10194. index = this->GetNextIndex(index);
  10195. if(index == Js::JavascriptArray::InvalidIndex) // End of array
  10196. {
  10197. break;
  10198. }
  10199. Js::Var aval = nullptr;
  10200. if(this->DirectGetVarItemAt(index, &aval, ctx))
  10201. {
  10202. extractor->MarkVisitVar(aval);
  10203. }
  10204. }
  10205. }
  10206. void JavascriptArray::ProcessCorePaths()
  10207. {
  10208. TTDAssert(this->GetTypeId() == Js::TypeIds_Array, "Should only be used on basic arrays.");
  10209. ScriptContext* ctx = this->GetScriptContext();
  10210. uint32 index = Js::JavascriptArray::InvalidIndex;
  10211. while(true)
  10212. {
  10213. index = this->GetNextIndex(index);
  10214. if(index == Js::JavascriptArray::InvalidIndex) // End of array
  10215. {
  10216. break;
  10217. }
  10218. Js::Var aval = nullptr;
  10219. if(this->DirectGetVarItemAt(index, &aval, ctx))
  10220. {
  10221. TTD::UtilSupport::TTAutoString pathExt;
  10222. ctx->TTDWellKnownInfo->BuildArrayIndexBuffer(index, pathExt);
  10223. ctx->TTDWellKnownInfo->EnqueueNewPathVarAsNeeded(this, aval, pathExt.GetStrValue());
  10224. }
  10225. }
  10226. }
  10227. TTD::NSSnapObjects::SnapObjectType JavascriptArray::GetSnapTag_TTD() const
  10228. {
  10229. return TTD::NSSnapObjects::SnapObjectType::SnapArrayObject;
  10230. }
  10231. void JavascriptArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  10232. {
  10233. TTDAssert(this->GetTypeId() == Js::TypeIds_Array, "Should only be used on basic Js arrays.");
  10234. TTD::NSSnapObjects::SnapArrayInfo<TTD::TTDVar>* sai = TTD::NSSnapObjects::ExtractArrayValues<TTD::TTDVar>(this, alloc);
  10235. TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayInfo<TTD::TTDVar>*, TTD::NSSnapObjects::SnapObjectType::SnapArrayObject>(objData, sai);
  10236. }
  10237. #endif
  10238. JavascriptNativeArray::JavascriptNativeArray(JavascriptNativeArray * instance) :
  10239. JavascriptArray(instance, false),
  10240. weakRefToFuncBody(instance->weakRefToFuncBody)
  10241. {
  10242. }
  10243. JavascriptNativeIntArray::JavascriptNativeIntArray(JavascriptNativeIntArray * instance, bool boxHead) :
  10244. JavascriptNativeArray(instance)
  10245. {
  10246. if (boxHead)
  10247. {
  10248. InitBoxedInlineHeadSegment(DetermineInlineHeadSegmentPointer<JavascriptNativeIntArray, 0, true>(this), SparseArraySegment<int>::From(instance->head));
  10249. }
  10250. else
  10251. {
  10252. // Base class ctor should have copied these
  10253. Assert(head == instance->head);
  10254. Assert(segmentUnion.lastUsedSegment == instance->GetLastUsedSegment());
  10255. }
  10256. }
  10257. JavascriptNativeIntArray *
  10258. JavascriptNativeIntArray::BoxStackInstance(JavascriptNativeIntArray * instance)
  10259. {
  10260. return JavascriptArray::BoxStackInstance<JavascriptNativeIntArray>(instance);
  10261. }
  10262. #if ENABLE_TTD
  10263. TTD::NSSnapObjects::SnapObjectType JavascriptNativeIntArray::GetSnapTag_TTD() const
  10264. {
  10265. return TTD::NSSnapObjects::SnapObjectType::SnapNativeIntArrayObject;
  10266. }
  10267. void JavascriptNativeIntArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  10268. {
  10269. TTD::NSSnapObjects::SnapArrayInfo<int32>* sai = TTD::NSSnapObjects::ExtractArrayValues<int32>(this, alloc);
  10270. TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayInfo<int32>*, TTD::NSSnapObjects::SnapObjectType::SnapNativeIntArrayObject>(objData, sai);
  10271. }
  10272. #if ENABLE_COPYONACCESS_ARRAY
  10273. TTD::NSSnapObjects::SnapObjectType JavascriptCopyOnAccessNativeIntArray::GetSnapTag_TTD() const
  10274. {
  10275. return TTD::NSSnapObjects::SnapObjectType::Invalid;
  10276. }
  10277. void JavascriptCopyOnAccessNativeIntArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  10278. {
  10279. TTDAssert(false, "Not implemented yet!!!");
  10280. }
  10281. #endif
  10282. #endif
  10283. JavascriptNativeFloatArray::JavascriptNativeFloatArray(JavascriptNativeFloatArray * instance, bool boxHead) :
  10284. JavascriptNativeArray(instance)
  10285. {
  10286. if (boxHead)
  10287. {
  10288. InitBoxedInlineHeadSegment(DetermineInlineHeadSegmentPointer<JavascriptNativeFloatArray, 0, true>(this), SparseArraySegment<double>::From(instance->head));
  10289. }
  10290. else
  10291. {
  10292. // Base class ctor should have copied these
  10293. Assert(head == instance->head);
  10294. Assert(segmentUnion.lastUsedSegment == instance->GetLastUsedSegment());
  10295. }
  10296. }
  10297. JavascriptNativeFloatArray *
  10298. JavascriptNativeFloatArray::BoxStackInstance(JavascriptNativeFloatArray * instance)
  10299. {
  10300. return JavascriptArray::BoxStackInstance<JavascriptNativeFloatArray>(instance);
  10301. }
  10302. #if ENABLE_TTD
  10303. TTD::NSSnapObjects::SnapObjectType JavascriptNativeFloatArray::GetSnapTag_TTD() const
  10304. {
  10305. return TTD::NSSnapObjects::SnapObjectType::SnapNativeFloatArrayObject;
  10306. }
  10307. void JavascriptNativeFloatArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  10308. {
  10309. TTDAssert(this->GetTypeId() == Js::TypeIds_NativeFloatArray, "Should only be used on native float arrays.");
  10310. TTD::NSSnapObjects::SnapArrayInfo<double>* sai = TTD::NSSnapObjects::ExtractArrayValues<double>(this, alloc);
  10311. TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayInfo<double>*, TTD::NSSnapObjects::SnapObjectType::SnapNativeFloatArrayObject>(objData, sai);
  10312. }
  10313. #endif
  10314. template<typename T>
  10315. RecyclableObject*
  10316. JavascriptArray::ArraySpeciesCreate(Var originalArray, T length, ScriptContext* scriptContext, bool *pIsIntArray, bool *pIsFloatArray, bool *pIsBuiltinArrayCtor)
  10317. {
  10318. if (originalArray == nullptr || !scriptContext->GetConfig()->IsES6SpeciesEnabled())
  10319. {
  10320. return nullptr;
  10321. }
  10322. if (JavascriptArray::Is(originalArray)
  10323. && !DynamicObject::FromVar(originalArray)->GetDynamicType()->GetTypeHandler()->GetIsNotPathTypeHandlerOrHasUserDefinedCtor()
  10324. && DynamicObject::FromVar(originalArray)->GetPrototype() == scriptContext->GetLibrary()->GetArrayPrototype()
  10325. && !scriptContext->GetLibrary()->GetArrayObjectHasUserDefinedSpecies())
  10326. {
  10327. return nullptr;
  10328. }
  10329. Var constructor = scriptContext->GetLibrary()->GetUndefined();
  10330. if (JavascriptOperators::IsArray(originalArray))
  10331. {
  10332. if (!JavascriptOperators::GetProperty(RecyclableObject::FromVar(originalArray), PropertyIds::constructor, &constructor, scriptContext))
  10333. {
  10334. return nullptr;
  10335. }
  10336. if (JavascriptOperators::IsConstructor(constructor))
  10337. {
  10338. ScriptContext* constructorScriptContext = RecyclableObject::FromVar(constructor)->GetScriptContext();
  10339. if (constructorScriptContext != scriptContext)
  10340. {
  10341. if (constructorScriptContext->GetLibrary()->GetArrayConstructor() == constructor)
  10342. {
  10343. constructor = scriptContext->GetLibrary()->GetUndefined();
  10344. }
  10345. }
  10346. }
  10347. if (JavascriptOperators::IsObject(constructor))
  10348. {
  10349. if (!JavascriptOperators::GetProperty((RecyclableObject*)constructor, PropertyIds::_symbolSpecies, &constructor, scriptContext))
  10350. {
  10351. if (pIsBuiltinArrayCtor != nullptr)
  10352. {
  10353. *pIsBuiltinArrayCtor = false;
  10354. }
  10355. return nullptr;
  10356. }
  10357. if (constructor == scriptContext->GetLibrary()->GetNull())
  10358. {
  10359. constructor = scriptContext->GetLibrary()->GetUndefined();
  10360. }
  10361. }
  10362. }
  10363. if (constructor == scriptContext->GetLibrary()->GetUndefined() || constructor == scriptContext->GetLibrary()->GetArrayConstructor())
  10364. {
  10365. if (length > UINT_MAX)
  10366. {
  10367. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  10368. }
  10369. if (nullptr == pIsIntArray)
  10370. {
  10371. return scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(length));
  10372. }
  10373. else
  10374. {
  10375. // If the constructor function is the built-in Array constructor, we can be smart and create the right type of native array.
  10376. JavascriptArray* pArr = JavascriptArray::FromVar(originalArray);
  10377. pArr->GetArrayTypeAndConvert(pIsIntArray, pIsFloatArray);
  10378. return CreateNewArrayHelper(static_cast<uint32>(length), *pIsIntArray, *pIsFloatArray, pArr, scriptContext);
  10379. }
  10380. }
  10381. if (!JavascriptOperators::IsConstructor(constructor))
  10382. {
  10383. JavascriptError::ThrowTypeError(scriptContext, JSERR_NotAConstructor, _u("constructor[Symbol.species]"));
  10384. }
  10385. if (pIsBuiltinArrayCtor != nullptr)
  10386. {
  10387. *pIsBuiltinArrayCtor = false;
  10388. }
  10389. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(length, scriptContext) };
  10390. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  10391. return RecyclableObject::FromVar(JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext));
  10392. }
  10393. /*static*/
  10394. PropertyId const JavascriptArray::specialPropertyIds[] =
  10395. {
  10396. PropertyIds::length
  10397. };
  10398. BOOL JavascriptArray::DeleteProperty(PropertyId propertyId, PropertyOperationFlags flags)
  10399. {
  10400. if (propertyId == PropertyIds::length)
  10401. {
  10402. return false;
  10403. }
  10404. return DynamicObject::DeleteProperty(propertyId, flags);
  10405. }
  10406. BOOL JavascriptArray::DeleteProperty(JavascriptString *propertyNameString, PropertyOperationFlags flags)
  10407. {
  10408. JsUtil::CharacterBuffer<WCHAR> propertyName(propertyNameString->GetString(), propertyNameString->GetLength());
  10409. if (BuiltInPropertyRecords::length.Equals(propertyName))
  10410. {
  10411. return false;
  10412. }
  10413. return DynamicObject::DeleteProperty(propertyNameString, flags);
  10414. }
  10415. PropertyQueryFlags JavascriptArray::HasPropertyQuery(PropertyId propertyId)
  10416. {
  10417. if (propertyId == PropertyIds::length)
  10418. {
  10419. return PropertyQueryFlags::Property_Found;
  10420. }
  10421. ScriptContext* scriptContext = GetScriptContext();
  10422. uint32 index;
  10423. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10424. {
  10425. return JavascriptConversion::BooleanToPropertyQueryFlags(this->HasItem(index));
  10426. }
  10427. return DynamicObject::HasPropertyQuery(propertyId);
  10428. }
  10429. BOOL JavascriptArray::IsEnumerable(PropertyId propertyId)
  10430. {
  10431. if (propertyId == PropertyIds::length)
  10432. {
  10433. return false;
  10434. }
  10435. return DynamicObject::IsEnumerable(propertyId);
  10436. }
  10437. BOOL JavascriptArray::IsConfigurable(PropertyId propertyId)
  10438. {
  10439. if (propertyId == PropertyIds::length)
  10440. {
  10441. return false;
  10442. }
  10443. return DynamicObject::IsConfigurable(propertyId);
  10444. }
  10445. //
  10446. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10447. // handling and only check instance objectArray for numeric propertyIds.
  10448. //
  10449. BOOL JavascriptArray::SetEnumerable(PropertyId propertyId, BOOL value)
  10450. {
  10451. if (propertyId == PropertyIds::length)
  10452. {
  10453. Assert(!value); // Can't change array length enumerable
  10454. return true;
  10455. }
  10456. ScriptContext* scriptContext = this->GetScriptContext();
  10457. uint32 index;
  10458. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10459. {
  10460. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10461. ->SetEnumerable(this, propertyId, value);
  10462. }
  10463. return __super::SetEnumerable(propertyId, value);
  10464. }
  10465. //
  10466. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10467. // handling and only check instance objectArray for numeric propertyIds.
  10468. //
  10469. BOOL JavascriptArray::SetWritable(PropertyId propertyId, BOOL value)
  10470. {
  10471. ScriptContext* scriptContext = this->GetScriptContext();
  10472. uint32 index;
  10473. bool setLengthNonWritable = (propertyId == PropertyIds::length && !value);
  10474. if (setLengthNonWritable || scriptContext->IsNumericPropertyId(propertyId, &index))
  10475. {
  10476. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10477. ->SetWritable(this, propertyId, value);
  10478. }
  10479. return __super::SetWritable(propertyId, value);
  10480. }
  10481. //
  10482. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10483. // handling and only check instance objectArray for numeric propertyIds.
  10484. //
  10485. BOOL JavascriptArray::SetConfigurable(PropertyId propertyId, BOOL value)
  10486. {
  10487. if (propertyId == PropertyIds::length)
  10488. {
  10489. Assert(!value); // Can't change array length configurable
  10490. return true;
  10491. }
  10492. ScriptContext* scriptContext = this->GetScriptContext();
  10493. uint32 index;
  10494. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10495. {
  10496. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10497. ->SetConfigurable(this, propertyId, value);
  10498. }
  10499. return __super::SetConfigurable(propertyId, value);
  10500. }
  10501. //
  10502. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10503. // handling and only check instance objectArray for numeric propertyIds.
  10504. //
  10505. BOOL JavascriptArray::SetAttributes(PropertyId propertyId, PropertyAttributes attributes)
  10506. {
  10507. ScriptContext* scriptContext = this->GetScriptContext();
  10508. // SetAttributes on "length" is not expected. DefineOwnProperty uses SetWritable. If this is
  10509. // changed, we need to handle it here.
  10510. Assert(propertyId != PropertyIds::length);
  10511. uint32 index;
  10512. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10513. {
  10514. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10515. ->SetItemAttributes(this, index, attributes);
  10516. }
  10517. return __super::SetAttributes(propertyId, attributes);
  10518. }
  10519. //
  10520. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10521. // handling and only check instance objectArray for numeric propertyIds.
  10522. //
  10523. BOOL JavascriptArray::SetAccessors(PropertyId propertyId, Var getter, Var setter, PropertyOperationFlags flags)
  10524. {
  10525. ScriptContext* scriptContext = this->GetScriptContext();
  10526. uint32 index;
  10527. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10528. {
  10529. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10530. ->SetItemAccessors(this, index, getter, setter);
  10531. }
  10532. return __super::SetAccessors(propertyId, getter, setter, flags);
  10533. }
  10534. //
  10535. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10536. // handling and only check instance objectArray for numeric propertyIds.
  10537. //
  10538. BOOL JavascriptArray::SetItemWithAttributes(uint32 index, Var value, PropertyAttributes attributes)
  10539. {
  10540. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10541. ->SetItemWithAttributes(this, index, value, attributes);
  10542. }
  10543. //
  10544. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10545. // handling and only check instance objectArray for numeric propertyIds.
  10546. //
  10547. BOOL JavascriptArray::SetItemAttributes(uint32 index, PropertyAttributes attributes)
  10548. {
  10549. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10550. ->SetItemAttributes(this, index, attributes);
  10551. }
  10552. //
  10553. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10554. // handling and only check instance objectArray for numeric propertyIds.
  10555. //
  10556. BOOL JavascriptArray::SetItemAccessors(uint32 index, Var getter, Var setter)
  10557. {
  10558. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10559. ->SetItemAccessors(this, index, getter, setter);
  10560. }
  10561. // Check if this objectArray isFrozen.
  10562. BOOL JavascriptArray::IsObjectArrayFrozen()
  10563. {
  10564. // If this is still a JavascriptArray, it's not frozen.
  10565. return false;
  10566. }
  10567. JavascriptEnumerator * JavascriptArray::GetIndexEnumerator(EnumeratorFlags flags, ScriptContext* requestContext)
  10568. {
  10569. #if ENABLE_COPYONACCESS_ARRAY
  10570. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10571. #endif
  10572. if (!!(flags & EnumeratorFlags::SnapShotSemantics))
  10573. {
  10574. return RecyclerNew(GetRecycler(), JavascriptArrayIndexSnapshotEnumerator, this, flags, requestContext);
  10575. }
  10576. return RecyclerNew(GetRecycler(), JavascriptArrayIndexEnumerator, this, flags, requestContext);
  10577. }
  10578. BOOL JavascriptArray::GetNonIndexEnumerator(JavascriptStaticEnumerator * enumerator, ScriptContext* requestContext)
  10579. {
  10580. #if ENABLE_COPYONACCESS_ARRAY
  10581. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10582. #endif
  10583. return enumerator->Initialize(nullptr, nullptr, this, EnumeratorFlags::SnapShotSemantics, requestContext, nullptr);
  10584. }
  10585. BOOL JavascriptArray::IsItemEnumerable(uint32 index)
  10586. {
  10587. return true;
  10588. }
  10589. //
  10590. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10591. // handling and only check instance objectArray for numeric propertyIds.
  10592. //
  10593. BOOL JavascriptArray::PreventExtensions()
  10594. {
  10595. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)->PreventExtensions(this);
  10596. }
  10597. //
  10598. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10599. // handling and only check instance objectArray for numeric propertyIds.
  10600. //
  10601. BOOL JavascriptArray::Seal()
  10602. {
  10603. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)->Seal(this);
  10604. }
  10605. //
  10606. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10607. // handling and only check instance objectArray for numeric propertyIds.
  10608. //
  10609. BOOL JavascriptArray::Freeze()
  10610. {
  10611. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)->Freeze(this);
  10612. }
  10613. BOOL JavascriptArray::GetSpecialPropertyName(uint32 index, JavascriptString ** propertyName, ScriptContext * requestContext)
  10614. {
  10615. if (index == 0)
  10616. {
  10617. *propertyName = requestContext->GetPropertyString(PropertyIds::length);
  10618. return true;
  10619. }
  10620. return false;
  10621. }
  10622. // Returns the number of special non-enumerable properties this type has.
  10623. uint JavascriptArray::GetSpecialPropertyCount() const
  10624. {
  10625. return _countof(specialPropertyIds);
  10626. }
  10627. // Returns the list of special non-enumerable properties for the type.
  10628. PropertyId const * JavascriptArray::GetSpecialPropertyIds() const
  10629. {
  10630. return specialPropertyIds;
  10631. }
  10632. PropertyQueryFlags JavascriptArray::GetPropertyReferenceQuery(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  10633. {
  10634. return JavascriptArray::GetPropertyQuery(originalInstance, propertyId, value, info, requestContext);
  10635. }
  10636. PropertyQueryFlags JavascriptArray::GetPropertyQuery(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  10637. {
  10638. if (GetPropertyBuiltIns(propertyId, value))
  10639. {
  10640. return PropertyQueryFlags::Property_Found;
  10641. }
  10642. ScriptContext* scriptContext = GetScriptContext();
  10643. uint32 index;
  10644. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10645. {
  10646. return JavascriptConversion::BooleanToPropertyQueryFlags(this->GetItem(this, index, value, scriptContext));
  10647. }
  10648. return DynamicObject::GetPropertyQuery(originalInstance, propertyId, value, info, requestContext);
  10649. }
  10650. PropertyQueryFlags JavascriptArray::GetPropertyQuery(Var originalInstance, JavascriptString* propertyNameString, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  10651. {
  10652. AssertMsg(!PropertyRecord::IsPropertyNameNumeric(propertyNameString->GetString(), propertyNameString->GetLength()),
  10653. "Numeric property names should have been converted to uint or PropertyRecord*");
  10654. PropertyRecord const* propertyRecord;
  10655. this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
  10656. if (propertyRecord != nullptr && GetPropertyBuiltIns(propertyRecord->GetPropertyId(), value))
  10657. {
  10658. return PropertyQueryFlags::Property_Found;
  10659. }
  10660. return DynamicObject::GetPropertyQuery(originalInstance, propertyNameString, value, info, requestContext);
  10661. }
  10662. BOOL JavascriptArray::GetPropertyBuiltIns(PropertyId propertyId, Var* value)
  10663. {
  10664. //
  10665. // length being accessed. Return array length
  10666. //
  10667. if (propertyId == PropertyIds::length)
  10668. {
  10669. *value = JavascriptNumber::ToVar(this->GetLength(), GetScriptContext());
  10670. return true;
  10671. }
  10672. return false;
  10673. }
  10674. PropertyQueryFlags JavascriptArray::HasItemQuery(uint32 index)
  10675. {
  10676. Var value = nullptr;
  10677. return JavascriptConversion::BooleanToPropertyQueryFlags(this->DirectGetItemAt<Var>(index, &value));
  10678. }
  10679. PropertyQueryFlags JavascriptArray::GetItemQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10680. {
  10681. return JavascriptConversion::BooleanToPropertyQueryFlags(this->DirectGetItemAt<Var>(index, value));
  10682. }
  10683. PropertyQueryFlags JavascriptArray::GetItemReferenceQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10684. {
  10685. return JavascriptConversion::BooleanToPropertyQueryFlags(this->DirectGetItemAt<Var>(index, value));
  10686. }
  10687. BOOL JavascriptArray::DirectGetVarItemAt(uint32 index, Var *value, ScriptContext *requestContext)
  10688. {
  10689. return this->DirectGetItemAt<Var>(index, value);
  10690. }
  10691. PropertyQueryFlags JavascriptNativeIntArray::HasItemQuery(uint32 index)
  10692. {
  10693. #if ENABLE_COPYONACCESS_ARRAY
  10694. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10695. #endif
  10696. int32 value;
  10697. return JavascriptConversion::BooleanToPropertyQueryFlags(this->DirectGetItemAt<int32>(index, &value));
  10698. }
  10699. PropertyQueryFlags JavascriptNativeFloatArray::HasItemQuery(uint32 index)
  10700. {
  10701. double dvalue;
  10702. return JavascriptConversion::BooleanToPropertyQueryFlags(this->DirectGetItemAt<double>(index, &dvalue));
  10703. }
  10704. PropertyQueryFlags JavascriptNativeIntArray::GetItemQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10705. {
  10706. #if ENABLE_COPYONACCESS_ARRAY
  10707. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10708. #endif
  10709. return JavascriptConversion::BooleanToPropertyQueryFlags(JavascriptNativeIntArray::DirectGetVarItemAt(index, value, requestContext));
  10710. }
  10711. BOOL JavascriptNativeIntArray::DirectGetVarItemAt(uint32 index, Var *value, ScriptContext *requestContext)
  10712. {
  10713. int32 intvalue;
  10714. if (!this->DirectGetItemAt<int32>(index, &intvalue))
  10715. {
  10716. return FALSE;
  10717. }
  10718. *value = JavascriptNumber::ToVar(intvalue, requestContext);
  10719. return TRUE;
  10720. }
  10721. PropertyQueryFlags JavascriptNativeIntArray::GetItemReferenceQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10722. {
  10723. return JavascriptNativeIntArray::GetItemQuery(originalInstance, index, value, requestContext);
  10724. }
  10725. PropertyQueryFlags JavascriptNativeFloatArray::GetItemQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10726. {
  10727. return JavascriptConversion::BooleanToPropertyQueryFlags(JavascriptNativeFloatArray::DirectGetVarItemAt(index, value, requestContext));
  10728. }
  10729. BOOL JavascriptNativeFloatArray::DirectGetVarItemAt(uint32 index, Var *value, ScriptContext *requestContext)
  10730. {
  10731. double dvalue;
  10732. int32 ivalue;
  10733. if (!this->DirectGetItemAt<double>(index, &dvalue))
  10734. {
  10735. return FALSE;
  10736. }
  10737. if (*(uint64*)&dvalue == 0ull)
  10738. {
  10739. *value = TaggedInt::ToVarUnchecked(0);
  10740. }
  10741. else if (JavascriptNumber::TryGetInt32Value(dvalue, &ivalue) && !TaggedInt::IsOverflow(ivalue))
  10742. {
  10743. *value = TaggedInt::ToVarUnchecked(ivalue);
  10744. }
  10745. else
  10746. {
  10747. *value = JavascriptNumber::ToVarWithCheck(dvalue, requestContext);
  10748. }
  10749. return TRUE;
  10750. }
  10751. PropertyQueryFlags JavascriptNativeFloatArray::GetItemReferenceQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10752. {
  10753. return JavascriptNativeFloatArray::GetItemQuery(originalInstance, index, value, requestContext);
  10754. }
  10755. BOOL JavascriptArray::SetProperty(PropertyId propertyId, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)
  10756. {
  10757. #if ENABLE_COPYONACCESS_ARRAY
  10758. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10759. #endif
  10760. uint32 indexValue;
  10761. if (propertyId == PropertyIds::length)
  10762. {
  10763. return this->SetLength(value);
  10764. }
  10765. else if (GetScriptContext()->IsNumericPropertyId(propertyId, &indexValue))
  10766. {
  10767. // Call this or subclass method
  10768. return SetItem(indexValue, value, flags);
  10769. }
  10770. else
  10771. {
  10772. return DynamicObject::SetProperty(propertyId, value, flags, info);
  10773. }
  10774. }
  10775. BOOL JavascriptArray::SetProperty(JavascriptString* propertyNameString, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)
  10776. {
  10777. AssertMsg(!PropertyRecord::IsPropertyNameNumeric(propertyNameString->GetString(), propertyNameString->GetLength()),
  10778. "Numeric property names should have been converted to uint or PropertyRecord*");
  10779. #if ENABLE_COPYONACCESS_ARRAY
  10780. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10781. #endif
  10782. PropertyRecord const* propertyRecord;
  10783. this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
  10784. if (propertyRecord != nullptr && propertyRecord->GetPropertyId() == PropertyIds::length)
  10785. {
  10786. return this->SetLength(value);
  10787. }
  10788. return DynamicObject::SetProperty(propertyNameString, value, flags, info);
  10789. }
  10790. BOOL JavascriptArray::SetPropertyWithAttributes(PropertyId propertyId, Var value, PropertyAttributes attributes, PropertyValueInfo* info, PropertyOperationFlags flags, SideEffects possibleSideEffects)
  10791. {
  10792. #if ENABLE_COPYONACCESS_ARRAY
  10793. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10794. #endif
  10795. ScriptContext* scriptContext = GetScriptContext();
  10796. if (propertyId == PropertyIds::length)
  10797. {
  10798. Assert(attributes == PropertyWritable);
  10799. Assert(IsWritable(propertyId) && !IsConfigurable(propertyId) && !IsEnumerable(propertyId));
  10800. return this->SetLength(value);
  10801. }
  10802. uint32 index;
  10803. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10804. {
  10805. // Call this or subclass method
  10806. return SetItemWithAttributes(index, value, attributes);
  10807. }
  10808. return __super::SetPropertyWithAttributes(propertyId, value, attributes, info, flags, possibleSideEffects);
  10809. }
  10810. BOOL JavascriptArray::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
  10811. {
  10812. this->DirectSetItemAt(index, value);
  10813. return true;
  10814. }
  10815. BOOL JavascriptNativeIntArray::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
  10816. {
  10817. int32 iValue;
  10818. double dValue;
  10819. #if ENABLE_COPYONACCESS_ARRAY
  10820. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10821. #endif
  10822. TypeId typeId = this->TrySetNativeIntArrayItem(value, &iValue, &dValue);
  10823. if (typeId == TypeIds_NativeIntArray)
  10824. {
  10825. this->SetItem(index, iValue);
  10826. }
  10827. else if (typeId == TypeIds_NativeFloatArray)
  10828. {
  10829. reinterpret_cast<JavascriptNativeFloatArray*>(this)->DirectSetItemAt<double>(index, dValue);
  10830. }
  10831. else
  10832. {
  10833. this->DirectSetItemAt<Var>(index, value);
  10834. }
  10835. return TRUE;
  10836. }
  10837. TypeId JavascriptNativeIntArray::TrySetNativeIntArrayItem(Var value, int32 *iValue, double *dValue)
  10838. {
  10839. if (TaggedInt::Is(value))
  10840. {
  10841. int32 i = TaggedInt::ToInt32(value);
  10842. if (i != JavascriptNativeIntArray::MissingItem)
  10843. {
  10844. *iValue = i;
  10845. return TypeIds_NativeIntArray;
  10846. }
  10847. }
  10848. if (JavascriptNumber::Is_NoTaggedIntCheck(value))
  10849. {
  10850. bool isInt32;
  10851. int32 i;
  10852. double d = JavascriptNumber::GetValue(value);
  10853. if (JavascriptNumber::TryGetInt32OrUInt32Value(d, &i, &isInt32))
  10854. {
  10855. if (isInt32 && i != JavascriptNativeIntArray::MissingItem)
  10856. {
  10857. *iValue = i;
  10858. return TypeIds_NativeIntArray;
  10859. }
  10860. }
  10861. else
  10862. {
  10863. *dValue = d;
  10864. JavascriptNativeIntArray::ToNativeFloatArray(this);
  10865. return TypeIds_NativeFloatArray;
  10866. }
  10867. }
  10868. JavascriptNativeIntArray::ToVarArray(this);
  10869. return TypeIds_Array;
  10870. }
  10871. BOOL JavascriptNativeIntArray::SetItem(uint32 index, int32 iValue)
  10872. {
  10873. if (iValue == JavascriptNativeIntArray::MissingItem)
  10874. {
  10875. JavascriptArray *varArr = JavascriptNativeIntArray::ToVarArray(this);
  10876. varArr->DirectSetItemAt(index, JavascriptNumber::ToVar(iValue, GetScriptContext()));
  10877. return TRUE;
  10878. }
  10879. this->DirectSetItemAt(index, iValue);
  10880. return TRUE;
  10881. }
  10882. BOOL JavascriptNativeFloatArray::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
  10883. {
  10884. double dValue;
  10885. TypeId typeId = this->TrySetNativeFloatArrayItem(value, &dValue);
  10886. if (typeId == TypeIds_NativeFloatArray)
  10887. {
  10888. this->SetItem(index, dValue);
  10889. }
  10890. else
  10891. {
  10892. this->DirectSetItemAt(index, value);
  10893. }
  10894. return TRUE;
  10895. }
  10896. TypeId JavascriptNativeFloatArray::TrySetNativeFloatArrayItem(Var value, double *dValue)
  10897. {
  10898. if (TaggedInt::Is(value))
  10899. {
  10900. *dValue = (double)TaggedInt::ToInt32(value);
  10901. return TypeIds_NativeFloatArray;
  10902. }
  10903. else if (JavascriptNumber::Is_NoTaggedIntCheck(value))
  10904. {
  10905. *dValue = JavascriptNumber::GetValue(value);
  10906. return TypeIds_NativeFloatArray;
  10907. }
  10908. JavascriptNativeFloatArray::ToVarArray(this);
  10909. return TypeIds_Array;
  10910. }
  10911. BOOL JavascriptNativeFloatArray::SetItem(uint32 index, double dValue)
  10912. {
  10913. if (*(uint64*)&dValue == *(uint64*)&JavascriptNativeFloatArray::MissingItem)
  10914. {
  10915. JavascriptArray *varArr = JavascriptNativeFloatArray::ToVarArray(this);
  10916. varArr->DirectSetItemAt(index, JavascriptNumber::ToVarNoCheck(dValue, GetScriptContext()));
  10917. return TRUE;
  10918. }
  10919. this->DirectSetItemAt<double>(index, dValue);
  10920. return TRUE;
  10921. }
  10922. BOOL JavascriptArray::DeleteItem(uint32 index, PropertyOperationFlags flags)
  10923. {
  10924. return this->DirectDeleteItemAt<Var>(index);
  10925. }
  10926. BOOL JavascriptNativeIntArray::DeleteItem(uint32 index, PropertyOperationFlags flags)
  10927. {
  10928. return this->DirectDeleteItemAt<int32>(index);
  10929. }
  10930. BOOL JavascriptNativeFloatArray::DeleteItem(uint32 index, PropertyOperationFlags flags)
  10931. {
  10932. return this->DirectDeleteItemAt<double>(index);
  10933. }
  10934. BOOL JavascriptArray::GetEnumerator(JavascriptStaticEnumerator * enumerator, EnumeratorFlags flags, ScriptContext* requestContext, ForInCache * forInCache)
  10935. {
  10936. #if ENABLE_COPYONACCESS_ARRAY
  10937. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10938. #endif
  10939. return enumerator->Initialize(nullptr, this, this, flags, requestContext, forInCache);
  10940. }
  10941. BOOL JavascriptArray::GetDiagValueString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext)
  10942. {
  10943. stringBuilder->Append(_u('['));
  10944. if (this->length < 10)
  10945. {
  10946. auto funcPtr = [&]()
  10947. {
  10948. ENTER_PINNED_SCOPE(JavascriptString, valueStr);
  10949. valueStr = JavascriptArray::JoinHelper(this, GetLibrary()->GetCommaDisplayString(), requestContext);
  10950. stringBuilder->Append(valueStr->GetString(), valueStr->GetLength());
  10951. LEAVE_PINNED_SCOPE();
  10952. };
  10953. if (!requestContext->GetThreadContext()->IsScriptActive())
  10954. {
  10955. BEGIN_JS_RUNTIME_CALL(requestContext);
  10956. {
  10957. funcPtr();
  10958. }
  10959. END_JS_RUNTIME_CALL(requestContext);
  10960. }
  10961. else
  10962. {
  10963. funcPtr();
  10964. }
  10965. }
  10966. else
  10967. {
  10968. stringBuilder->AppendCppLiteral(_u("..."));
  10969. }
  10970. stringBuilder->Append(_u(']'));
  10971. return TRUE;
  10972. }
  10973. BOOL JavascriptArray::GetDiagTypeString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext)
  10974. {
  10975. stringBuilder->AppendCppLiteral(_u("Object, (Array)"));
  10976. return TRUE;
  10977. }
  10978. bool JavascriptNativeArray::Is(Var aValue)
  10979. {
  10980. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  10981. return JavascriptNativeArray::Is(typeId);
  10982. }
  10983. bool JavascriptNativeArray::Is(TypeId typeId)
  10984. {
  10985. return JavascriptNativeIntArray::Is(typeId) || JavascriptNativeFloatArray::Is(typeId);
  10986. }
  10987. JavascriptNativeArray* JavascriptNativeArray::FromVar(Var aValue)
  10988. {
  10989. AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeArray'");
  10990. return static_cast<JavascriptNativeArray *>(RecyclableObject::FromVar(aValue));
  10991. }
  10992. bool JavascriptNativeIntArray::Is(Var aValue)
  10993. {
  10994. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  10995. return JavascriptNativeIntArray::Is(typeId);
  10996. }
  10997. #if ENABLE_COPYONACCESS_ARRAY
  10998. bool JavascriptCopyOnAccessNativeIntArray::Is(Var aValue)
  10999. {
  11000. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  11001. return JavascriptCopyOnAccessNativeIntArray::Is(typeId);
  11002. }
  11003. #endif
  11004. bool JavascriptNativeIntArray::Is(TypeId typeId)
  11005. {
  11006. return typeId == TypeIds_NativeIntArray;
  11007. }
  11008. #if ENABLE_COPYONACCESS_ARRAY
  11009. bool JavascriptCopyOnAccessNativeIntArray::Is(TypeId typeId)
  11010. {
  11011. return typeId == TypeIds_CopyOnAccessNativeIntArray;
  11012. }
  11013. #endif
  11014. bool JavascriptNativeIntArray::IsNonCrossSite(Var aValue)
  11015. {
  11016. bool ret = !TaggedInt::Is(aValue) && VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(aValue);
  11017. Assert(ret == (JavascriptNativeIntArray::Is(aValue) && !JavascriptNativeIntArray::FromVar(aValue)->IsCrossSiteObject()));
  11018. return ret;
  11019. }
  11020. JavascriptNativeIntArray* JavascriptNativeIntArray::FromVar(Var aValue)
  11021. {
  11022. AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeIntArray'");
  11023. return static_cast<JavascriptNativeIntArray *>(RecyclableObject::FromVar(aValue));
  11024. }
  11025. #if ENABLE_COPYONACCESS_ARRAY
  11026. JavascriptCopyOnAccessNativeIntArray* JavascriptCopyOnAccessNativeIntArray::FromVar(Var aValue)
  11027. {
  11028. AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptCopyOnAccessNativeIntArray'");
  11029. return static_cast<JavascriptCopyOnAccessNativeIntArray *>(RecyclableObject::FromVar(aValue));
  11030. }
  11031. #endif
  11032. bool JavascriptNativeFloatArray::Is(Var aValue)
  11033. {
  11034. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  11035. return JavascriptNativeFloatArray::Is(typeId);
  11036. }
  11037. bool JavascriptNativeFloatArray::Is(TypeId typeId)
  11038. {
  11039. return typeId == TypeIds_NativeFloatArray;
  11040. }
  11041. bool JavascriptNativeFloatArray::IsNonCrossSite(Var aValue)
  11042. {
  11043. bool ret = !TaggedInt::Is(aValue) && VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(aValue);
  11044. Assert(ret == (JavascriptNativeFloatArray::Is(aValue) && !JavascriptNativeFloatArray::FromVar(aValue)->IsCrossSiteObject()));
  11045. return ret;
  11046. }
  11047. JavascriptNativeFloatArray* JavascriptNativeFloatArray::FromVar(Var aValue)
  11048. {
  11049. AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeFloatArray'");
  11050. return static_cast<JavascriptNativeFloatArray *>(RecyclableObject::FromVar(aValue));
  11051. }
  11052. AutoFailFastOnError::~AutoFailFastOnError()
  11053. {
  11054. if (!m_operationCompleted)
  11055. {
  11056. AssertOrFailFast(false);
  11057. }
  11058. }
  11059. template int Js::JavascriptArray::GetParamForIndexOf<unsigned int>(unsigned int, Js::Arguments const&, void*&, unsigned int&, Js::ScriptContext*);
  11060. template bool Js::JavascriptArray::ArrayElementEnumerator::MoveNext<void*>();
  11061. template void Js::JavascriptArray::SetArrayLiteralItem<void*>(unsigned int, void*);
  11062. template void* Js::JavascriptArray::TemplatedIndexOfHelper<false, Js::TypedArrayBase, unsigned int>(Js::TypedArrayBase*, void*, unsigned int, unsigned int, Js::ScriptContext*);
  11063. template void* Js::JavascriptArray::TemplatedIndexOfHelper<true, Js::TypedArrayBase, unsigned int>(Js::TypedArrayBase*, void*, unsigned int, unsigned int, Js::ScriptContext*);
  11064. } //namespace Js