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 = nullptr;
  1357. bool foundScriptCaller = false;
  1358. while(walker.GetCaller(&caller))
  1359. {
  1360. if(caller != nullptr && Js::ScriptFunction::Test(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. // Code below has potential to throw due to OOM or SO. Just FailFast on those cases
  1395. ScriptContext *scriptContext = intArray->GetScriptContext();
  1396. AutoDisableInterrupt failFastError(scriptContext->GetThreadContext());
  1397. // Grow the segments
  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. AutoDisableInterrupt failFastError(scriptContext->GetThreadContext());
  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 = nullptr;
  1764. bool foundScriptCaller = false;
  1765. while(walker.GetCaller(&caller))
  1766. {
  1767. if(caller != nullptr && Js::ScriptFunction::Test(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. AutoDisableInterrupt failFastError(scriptContext->GetThreadContext());
  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 = nullptr;
  1953. bool foundScriptCaller = false;
  1954. while(walker.GetCaller(&caller))
  1955. {
  1956. if(caller != nullptr && Js::ScriptFunction::Test(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. // ConcatArgs function expects to work on the Var array so we are ensuring it.
  2739. pDestArray = EnsureNonNativeArray(JavascriptArray::FromVar(pDestObj));
  2740. }
  2741. T idxDest = startIdxDest;
  2742. for (uint idxArg = start; idxArg < args.Info.Count; idxArg++)
  2743. {
  2744. Var aItem = args[idxArg];
  2745. bool spreadable = spreadableCheckedAndTrue;
  2746. if (!spreadable && scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled())
  2747. {
  2748. // firstPromotedItemIsSpreadable is ONLY used to resume after a type promotion from uint32 to uint64
  2749. // we do this because calls to IsConcatSpreadable are observable (a big deal for proxies) and we don't
  2750. // want to do the work a second time as soon as we record the length we clear the flag.
  2751. JS_REENTRANT(jsReentLock, spreadable = firstPromotedItemIsSpreadable || JavascriptOperators::IsConcatSpreadable(aItem));
  2752. if (!spreadable)
  2753. {
  2754. JS_REENTRANT(jsReentLock, JavascriptArray::SetConcatItem<T>(aItem, idxArg, pDestArray, pDestObj, idxDest, scriptContext));
  2755. ++idxDest;
  2756. continue;
  2757. }
  2758. }
  2759. else
  2760. {
  2761. spreadableCheckedAndTrue = false; // if it was `true`, reset after the first use
  2762. }
  2763. if (pDestArray && JavascriptArray::IsDirectAccessArray(aItem) && JavascriptArray::IsDirectAccessArray(pDestArray)
  2764. && BigIndex(idxDest + JavascriptArray::FromVar(aItem)->length).IsSmallIndex() && !JavascriptArray::FromVar(aItem)->IsFillFromPrototypes()) // Fast path
  2765. {
  2766. if (JavascriptNativeIntArray::Is(aItem))
  2767. {
  2768. JavascriptNativeIntArray *pItemArray = JavascriptNativeIntArray::FromVar(aItem);
  2769. JS_REENTRANT(jsReentLock, CopyNativeIntArrayElementsToVar(pDestArray, BigIndex(idxDest).GetSmallIndex(), pItemArray));
  2770. idxDest = idxDest + pItemArray->length;
  2771. }
  2772. else if (JavascriptNativeFloatArray::Is(aItem))
  2773. {
  2774. JavascriptNativeFloatArray *pItemArray = JavascriptNativeFloatArray::FromVar(aItem);
  2775. JS_REENTRANT(jsReentLock, CopyNativeFloatArrayElementsToVar(pDestArray, BigIndex(idxDest).GetSmallIndex(), pItemArray));
  2776. idxDest = idxDest + pItemArray->length;
  2777. }
  2778. else
  2779. {
  2780. JavascriptArray* pItemArray = JavascriptArray::FromVar(aItem);
  2781. JS_REENTRANT(jsReentLock, CopyArrayElements(pDestArray, BigIndex(idxDest).GetSmallIndex(), pItemArray));
  2782. idxDest = idxDest + pItemArray->length;
  2783. }
  2784. }
  2785. else
  2786. {
  2787. // Flatten if other array or remote array (marked with TypeIds_Array)
  2788. if (DynamicObject::IsAnyArray(aItem) || remoteTypeIds[idxArg] == TypeIds_Array || spreadable)
  2789. {
  2790. //CONSIDER: enumerating remote array instead of walking all indices
  2791. BigIndex length;
  2792. if (firstPromotedItemIsSpreadable)
  2793. {
  2794. firstPromotedItemIsSpreadable = false;
  2795. length = firstPromotedItemLength;
  2796. }
  2797. else
  2798. {
  2799. JS_REENTRANT(jsReentLock, length = OP_GetLength(aItem, scriptContext));
  2800. }
  2801. if (PromoteToBigIndex(length,idxDest))
  2802. {
  2803. // This is a special case for spreadable objects. We do not pre-calculate the length
  2804. // in EntryConcat like we do with Arrays because a getProperty on an object Length
  2805. // is observable. The result is we have to check for overflows separately for
  2806. // spreadable objects and promote to a bigger index type when we find them.
  2807. ConcatArgs<BigIndex>(pDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest, /*firstPromotedItemIsSpreadable*/true, length);
  2808. return;
  2809. }
  2810. if (length + idxDest > FiftyThirdPowerOfTwoMinusOne) // 2^53-1: from ECMA 22.1.3.1 Array.prototype.concat(...arguments)
  2811. {
  2812. JavascriptError::ThrowTypeError(scriptContext, JSERR_IllegalArraySizeAndLength);
  2813. }
  2814. RecyclableObject* itemObject = RecyclableObject::FromVar(aItem);
  2815. Var subItem;
  2816. uint32 lengthToUin32Max = length.IsSmallIndex() ? length.GetSmallIndex() : MaxArrayLength;
  2817. for (uint32 idxSubItem = 0u; idxSubItem < lengthToUin32Max; ++idxSubItem)
  2818. {
  2819. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(itemObject, idxSubItem));
  2820. if (hasItem)
  2821. {
  2822. JS_REENTRANT(jsReentLock, subItem = JavascriptOperators::GetItem(itemObject, idxSubItem, scriptContext));
  2823. if (pDestArray)
  2824. {
  2825. pDestArray->GenericDirectSetItemAt(idxDest, subItem);
  2826. }
  2827. else
  2828. {
  2829. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(SetArrayLikeObjects(pDestObj, idxDest, subItem), scriptContext, idxDest));
  2830. }
  2831. }
  2832. ++idxDest;
  2833. }
  2834. for (BigIndex idxSubItem = MaxArrayLength; idxSubItem < length; ++idxSubItem)
  2835. {
  2836. PropertyRecord const * propertyRecord;
  2837. JavascriptOperators::GetPropertyIdForInt(idxSubItem.GetBigIndex(), scriptContext, &propertyRecord);
  2838. JS_REENTRANT(jsReentLock, BOOL hasProp = JavascriptOperators::HasProperty(itemObject, propertyRecord->GetPropertyId()));
  2839. if (hasProp)
  2840. {
  2841. JS_REENTRANT(jsReentLock, subItem = JavascriptOperators::GetProperty(itemObject, propertyRecord->GetPropertyId(), scriptContext));
  2842. if (pDestArray)
  2843. {
  2844. pDestArray->GenericDirectSetItemAt(idxDest, subItem);
  2845. }
  2846. else
  2847. {
  2848. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(SetArrayLikeObjects(pDestObj, idxDest, subItem), scriptContext, idxSubItem));
  2849. }
  2850. }
  2851. ++idxDest;
  2852. }
  2853. }
  2854. else // concat 1 item
  2855. {
  2856. JS_REENTRANT(jsReentLock, JavascriptArray::SetConcatItem<T>(aItem, idxArg, pDestArray, pDestObj, idxDest, scriptContext));
  2857. ++idxDest;
  2858. }
  2859. }
  2860. firstPromotedItemIsSpreadable = false;
  2861. }
  2862. if (!pDestArray)
  2863. {
  2864. JS_REENTRANT(jsReentLock, pDestObj->SetProperty(PropertyIds::length, ConvertToIndex<T, Var>(idxDest, scriptContext), Js::PropertyOperation_None, nullptr));
  2865. }
  2866. else if (pDestArray->GetLength() != ConvertToIndex<T, uint32>(idxDest, scriptContext))
  2867. {
  2868. pDestArray->SetLength(ConvertToIndex<T, uint32>(idxDest, scriptContext));
  2869. }
  2870. }
  2871. bool JavascriptArray::PromoteToBigIndex(BigIndex lhs, BigIndex rhs)
  2872. {
  2873. return false; // already a big index
  2874. }
  2875. bool JavascriptArray::PromoteToBigIndex(BigIndex lhs, uint32 rhs)
  2876. {
  2877. ::Math::RecordOverflowPolicy destLengthOverflow;
  2878. if (lhs.IsSmallIndex())
  2879. {
  2880. UInt32Math::Add(lhs.GetSmallIndex(), rhs, destLengthOverflow);
  2881. return destLengthOverflow.HasOverflowed();
  2882. }
  2883. return true;
  2884. }
  2885. JavascriptArray* JavascriptArray::ConcatIntArgs(JavascriptNativeIntArray* pDestArray, TypeId *remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext)
  2886. {
  2887. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  2888. uint idxDest = 0u;
  2889. for (uint idxArg = 0; idxArg < args.Info.Count; idxArg++)
  2890. {
  2891. Var aItem = args[idxArg];
  2892. bool spreadableCheckedAndTrue = false;
  2893. if (scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled())
  2894. {
  2895. JS_REENTRANT(jsReentLock, spreadableCheckedAndTrue = !scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled() || JavascriptOperators::IsConcatSpreadable(aItem));
  2896. if (!JavascriptNativeIntArray::Is(pDestArray))
  2897. {
  2898. ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest, spreadableCheckedAndTrue);
  2899. return pDestArray;
  2900. }
  2901. if(!spreadableCheckedAndTrue)
  2902. {
  2903. JS_REENTRANT(jsReentLock, pDestArray->SetItem(idxDest, aItem, PropertyOperation_ThrowIfNotExtensible));
  2904. idxDest = idxDest + 1;
  2905. if (!JavascriptNativeIntArray::Is(pDestArray)) // SetItem could convert pDestArray to a var array if aItem is not an integer if so fall back
  2906. {
  2907. JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest));
  2908. return pDestArray;
  2909. }
  2910. continue;
  2911. }
  2912. }
  2913. if (JavascriptNativeIntArray::Is(aItem) && !JavascriptNativeIntArray::FromVar(aItem)->IsFillFromPrototypes()) // Fast path
  2914. {
  2915. JavascriptNativeIntArray* pItemArray = JavascriptNativeIntArray::FromVar(aItem);
  2916. JS_REENTRANT(jsReentLock, bool converted = CopyNativeIntArrayElements(pDestArray, idxDest, pItemArray));
  2917. idxDest = idxDest + pItemArray->length;
  2918. if (converted)
  2919. {
  2920. // Copying the last array forced a conversion, so switch over to the var version
  2921. // to finish.
  2922. JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest));
  2923. return pDestArray;
  2924. }
  2925. }
  2926. else if (!JavascriptArray::IsAnyArray(aItem) && remoteTypeIds[idxArg] != TypeIds_Array)
  2927. {
  2928. if (TaggedInt::Is(aItem))
  2929. {
  2930. pDestArray->DirectSetItemAt(idxDest, TaggedInt::ToInt32(aItem));
  2931. }
  2932. else
  2933. {
  2934. #if DBG
  2935. int32 int32Value;
  2936. Assert(
  2937. JavascriptNumber::TryGetInt32Value(JavascriptNumber::GetValue(aItem), &int32Value) &&
  2938. !SparseArraySegment<int32>::IsMissingItem(&int32Value));
  2939. #endif
  2940. pDestArray->DirectSetItemAt(idxDest, static_cast<int32>(JavascriptNumber::GetValue(aItem)));
  2941. }
  2942. ++idxDest;
  2943. }
  2944. else
  2945. {
  2946. JavascriptArray *pVarDestArray = JavascriptNativeIntArray::ConvertToVarArray(pDestArray);
  2947. BigIndex length;
  2948. JS_REENTRANT(jsReentLock, length = OP_GetLength(aItem, scriptContext),
  2949. ConcatArgs<uint>(pVarDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest, spreadableCheckedAndTrue, length));
  2950. return pVarDestArray;
  2951. }
  2952. }
  2953. if (pDestArray->GetLength() != idxDest)
  2954. {
  2955. pDestArray->SetLength(idxDest);
  2956. }
  2957. return pDestArray;
  2958. }
  2959. JavascriptArray* JavascriptArray::ConcatFloatArgs(JavascriptNativeFloatArray* pDestArray, TypeId *remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext)
  2960. {
  2961. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  2962. uint idxDest = 0u;
  2963. for (uint idxArg = 0; idxArg < args.Info.Count; idxArg++)
  2964. {
  2965. Var aItem = args[idxArg];
  2966. bool spreadableCheckedAndTrue = false;
  2967. if (scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled())
  2968. {
  2969. JS_REENTRANT(jsReentLock, spreadableCheckedAndTrue = !scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled() || JavascriptOperators::IsConcatSpreadable(aItem));
  2970. if (!JavascriptNativeFloatArray::Is(pDestArray))
  2971. {
  2972. ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest, spreadableCheckedAndTrue);
  2973. return pDestArray;
  2974. }
  2975. if (!spreadableCheckedAndTrue)
  2976. {
  2977. JS_REENTRANT(jsReentLock, pDestArray->SetItem(idxDest, aItem, PropertyOperation_ThrowIfNotExtensible));
  2978. idxDest = idxDest + 1;
  2979. if (!JavascriptNativeFloatArray::Is(pDestArray)) // SetItem could convert pDestArray to a var array if aItem is not an integer if so fall back
  2980. {
  2981. JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest));
  2982. return pDestArray;
  2983. }
  2984. continue;
  2985. }
  2986. }
  2987. bool converted = false;
  2988. if (JavascriptArray::IsAnyArray(aItem) || remoteTypeIds[idxArg] == TypeIds_Array)
  2989. {
  2990. if (JavascriptNativeIntArray::Is(aItem) && !JavascriptArray::FromVar(aItem)->IsFillFromPrototypes()) // Fast path
  2991. {
  2992. JavascriptNativeIntArray *pIntArray = JavascriptNativeIntArray::FromVar(aItem);
  2993. JS_REENTRANT(jsReentLock, converted = CopyNativeIntArrayElementsToFloat(pDestArray, idxDest, pIntArray));
  2994. idxDest = idxDest + pIntArray->length;
  2995. }
  2996. else if (JavascriptNativeFloatArray::Is(aItem) && !JavascriptArray::FromVar(aItem)->IsFillFromPrototypes())
  2997. {
  2998. JavascriptNativeFloatArray* pItemArray = JavascriptNativeFloatArray::FromVar(aItem);
  2999. JS_REENTRANT(jsReentLock, converted = CopyNativeFloatArrayElements(pDestArray, idxDest, pItemArray));
  3000. idxDest = idxDest + pItemArray->length;
  3001. }
  3002. else
  3003. {
  3004. JavascriptArray *pVarDestArray = JavascriptNativeFloatArray::ConvertToVarArray(pDestArray);
  3005. BigIndex length;
  3006. JS_REENTRANT(jsReentLock, length = OP_GetLength(aItem, scriptContext),
  3007. ConcatArgs<uint>(pVarDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest, spreadableCheckedAndTrue, length));
  3008. return pVarDestArray;
  3009. }
  3010. if (converted)
  3011. {
  3012. // Copying the last array forced a conversion, so switch over to the var version
  3013. // to finish.
  3014. JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest));
  3015. return pDestArray;
  3016. }
  3017. }
  3018. else
  3019. {
  3020. if (TaggedInt::Is(aItem))
  3021. {
  3022. pDestArray->DirectSetItemAt(idxDest, (double)TaggedInt::ToInt32(aItem));
  3023. }
  3024. else
  3025. {
  3026. Assert(JavascriptNumber::Is(aItem));
  3027. pDestArray->DirectSetItemAt(idxDest, JavascriptNumber::GetValue(aItem));
  3028. }
  3029. ++idxDest;
  3030. }
  3031. }
  3032. if (pDestArray->GetLength() != idxDest)
  3033. {
  3034. pDestArray->SetLength(idxDest);
  3035. }
  3036. return pDestArray;
  3037. }
  3038. bool JavascriptArray::BoxConcatItem(Var aItem, uint idxArg, ScriptContext *scriptContext)
  3039. {
  3040. return idxArg == 0 && !JavascriptOperators::IsObject(aItem);
  3041. }
  3042. Var JavascriptArray::EntryConcat(RecyclableObject* function, CallInfo callInfo, ...)
  3043. {
  3044. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  3045. ARGUMENTS(args, callInfo);
  3046. ScriptContext* scriptContext = function->GetScriptContext();
  3047. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3048. Assert(!(callInfo.Flags & CallFlags_New));
  3049. if (args.Info.Count == 0)
  3050. {
  3051. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.concat"));
  3052. }
  3053. //
  3054. // Compute the destination ScriptArray size:
  3055. // - Each item, flattening only one level if a ScriptArray.
  3056. //
  3057. uint32 cDestLength = 0;
  3058. JavascriptArray * pDestArray = NULL;
  3059. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault + (args.Info.Count * sizeof(TypeId*)));
  3060. TypeId* remoteTypeIds = (TypeId*)_alloca(args.Info.Count * sizeof(TypeId*));
  3061. bool isInt = true;
  3062. bool isFloat = true;
  3063. ::Math::RecordOverflowPolicy destLengthOverflow;
  3064. for (uint idxArg = 0; idxArg < args.Info.Count; idxArg++)
  3065. {
  3066. Var aItem = args[idxArg];
  3067. #if ENABLE_COPYONACCESS_ARRAY
  3068. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(aItem);
  3069. #endif
  3070. if (DynamicObject::IsAnyArray(aItem)) // Get JavascriptArray or ES5Array length
  3071. {
  3072. JavascriptArray * pItemArray = JavascriptArray::FromAnyArray(aItem);
  3073. if (isFloat)
  3074. {
  3075. if (!JavascriptNativeIntArray::Is(pItemArray))
  3076. {
  3077. isInt = false;
  3078. if (!JavascriptNativeFloatArray::Is(pItemArray))
  3079. {
  3080. isFloat = false;
  3081. }
  3082. }
  3083. }
  3084. cDestLength = UInt32Math::Add(cDestLength, pItemArray->GetLength(), destLengthOverflow);
  3085. }
  3086. else // Get remote array or object length
  3087. {
  3088. // We already checked for types derived from JavascriptArray. These are types that should behave like array
  3089. // i.e. proxy to array and remote array.
  3090. if (JavascriptOperators::IsArray(aItem))
  3091. {
  3092. // Don't try to preserve nativeness of remote arrays. The extra complexity is probably not
  3093. // worth it.
  3094. isInt = false;
  3095. isFloat = false;
  3096. if (!JavascriptProxy::Is(aItem))
  3097. {
  3098. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  3099. {
  3100. JS_REENTRANT(jsReentLock,
  3101. int64 len = JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(aItem, scriptContext), scriptContext));
  3102. // clipping to MaxArrayLength will overflow when added to cDestLength which we catch below
  3103. cDestLength = UInt32Math::Add(cDestLength, len < MaxArrayLength ? (uint32)len : MaxArrayLength, destLengthOverflow);
  3104. }
  3105. else
  3106. {
  3107. JS_REENTRANT(jsReentLock,
  3108. uint len = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(aItem, scriptContext), scriptContext));
  3109. cDestLength = UInt32Math::Add(cDestLength, len, destLengthOverflow);
  3110. }
  3111. }
  3112. remoteTypeIds[idxArg] = TypeIds_Array; // Mark remote array, no matter remote JavascriptArray or ES5Array.
  3113. }
  3114. else
  3115. {
  3116. if (isFloat)
  3117. {
  3118. if (BoxConcatItem(aItem, idxArg, scriptContext))
  3119. {
  3120. // A primitive will be boxed, so we have to create a var array for the result.
  3121. isInt = false;
  3122. isFloat = false;
  3123. }
  3124. else if (!TaggedInt::Is(aItem))
  3125. {
  3126. if (!JavascriptNumber::Is(aItem))
  3127. {
  3128. isInt = false;
  3129. isFloat = false;
  3130. }
  3131. else if (isInt)
  3132. {
  3133. int32 int32Value;
  3134. if(!JavascriptNumber::TryGetInt32Value(JavascriptNumber::GetValue(aItem), &int32Value) ||
  3135. SparseArraySegment<int32>::IsMissingItem(&int32Value))
  3136. {
  3137. isInt = false;
  3138. }
  3139. }
  3140. }
  3141. else if(isInt)
  3142. {
  3143. int32 int32Value = TaggedInt::ToInt32(aItem);
  3144. if(SparseArraySegment<int32>::IsMissingItem(&int32Value))
  3145. {
  3146. isInt = false;
  3147. }
  3148. }
  3149. }
  3150. remoteTypeIds[idxArg] = TypeIds_Limit;
  3151. cDestLength = UInt32Math::Add(cDestLength, 1, destLengthOverflow);
  3152. }
  3153. }
  3154. }
  3155. if (destLengthOverflow.HasOverflowed())
  3156. {
  3157. cDestLength = MaxArrayLength;
  3158. isInt = false;
  3159. isFloat = false;
  3160. }
  3161. //
  3162. // Create the destination array
  3163. //
  3164. RecyclableObject* pDestObj = nullptr;
  3165. bool isArray = false;
  3166. JS_REENTRANT(jsReentLock, pDestObj = ArraySpeciesCreate(args[0], 0, scriptContext));
  3167. if (pDestObj)
  3168. {
  3169. #if ENABLE_COPYONACCESS_ARRAY
  3170. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pDestObj);
  3171. #endif
  3172. // Check the thing that species create made. If it's a native array that can't handle the source
  3173. // data, convert it. If it's a more conservative kind of array than the source data, indicate that
  3174. // so that the data will be converted on copy.
  3175. if (isInt)
  3176. {
  3177. if (JavascriptNativeIntArray::Is(pDestObj))
  3178. {
  3179. isArray = true;
  3180. }
  3181. else
  3182. {
  3183. isInt = false;
  3184. isFloat = JavascriptNativeFloatArray::Is(pDestObj);
  3185. isArray = JavascriptArray::Is(pDestObj);
  3186. }
  3187. }
  3188. else if (isFloat)
  3189. {
  3190. if (JavascriptNativeIntArray::Is(pDestObj))
  3191. {
  3192. JavascriptNativeIntArray::ToNativeFloatArray(JavascriptNativeIntArray::FromVar(pDestObj));
  3193. isArray = true;
  3194. }
  3195. else
  3196. {
  3197. isFloat = JavascriptNativeFloatArray::Is(pDestObj);
  3198. isArray = JavascriptArray::Is(pDestObj);
  3199. }
  3200. }
  3201. else
  3202. {
  3203. if (JavascriptNativeIntArray::Is(pDestObj))
  3204. {
  3205. JavascriptNativeIntArray::ToVarArray(JavascriptNativeIntArray::FromVar(pDestObj));
  3206. isArray = true;
  3207. }
  3208. else if (JavascriptNativeFloatArray::Is(pDestObj))
  3209. {
  3210. JavascriptNativeFloatArray::ToVarArray(JavascriptNativeFloatArray::FromVar(pDestObj));
  3211. isArray = true;
  3212. }
  3213. else
  3214. {
  3215. isArray = JavascriptArray::Is(pDestObj);
  3216. }
  3217. }
  3218. }
  3219. if (pDestObj == nullptr || isArray)
  3220. {
  3221. if (isInt)
  3222. {
  3223. JavascriptNativeIntArray *pIntArray = isArray ? JavascriptNativeIntArray::FromVar(pDestObj) : scriptContext->GetLibrary()->CreateNativeIntArray(cDestLength);
  3224. pIntArray->EnsureHead<int32>();
  3225. JS_REENTRANT(jsReentLock, pDestArray = ConcatIntArgs(pIntArray, remoteTypeIds, args, scriptContext));
  3226. }
  3227. else if (isFloat)
  3228. {
  3229. JavascriptNativeFloatArray *pFArray = isArray ? JavascriptNativeFloatArray::FromVar(pDestObj) : scriptContext->GetLibrary()->CreateNativeFloatArray(cDestLength);
  3230. pFArray->EnsureHead<double>();
  3231. JS_REENTRANT(jsReentLock, pDestArray = ConcatFloatArgs(pFArray, remoteTypeIds, args, scriptContext));
  3232. }
  3233. else
  3234. {
  3235. pDestArray = isArray ? JavascriptArray::FromVar(pDestObj) : scriptContext->GetLibrary()->CreateArray(cDestLength);
  3236. // if the constructor has changed then we no longer specialize for ints and floats
  3237. pDestArray->EnsureHead<Var>();
  3238. JS_REENTRANT(jsReentLock, ConcatArgsCallingHelper(pDestArray, remoteTypeIds, args, scriptContext, destLengthOverflow));
  3239. }
  3240. //
  3241. // Return the new array instance.
  3242. //
  3243. #ifdef VALIDATE_ARRAY
  3244. pDestArray->ValidateArray();
  3245. #endif
  3246. return pDestArray;
  3247. }
  3248. Assert(pDestObj);
  3249. JS_REENTRANT(jsReentLock, ConcatArgsCallingHelper(pDestObj, remoteTypeIds, args, scriptContext, destLengthOverflow));
  3250. return pDestObj;
  3251. }
  3252. void JavascriptArray::ConcatArgsCallingHelper(RecyclableObject* pDestObj, TypeId* remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext, ::Math::RecordOverflowPolicy &destLengthOverflow)
  3253. {
  3254. if (destLengthOverflow.HasOverflowed())
  3255. {
  3256. ConcatArgs<BigIndex>(pDestObj, remoteTypeIds, args, scriptContext);
  3257. }
  3258. else
  3259. {
  3260. // Use faster uint32 version if no overflow
  3261. ConcatArgs<uint32>(pDestObj, remoteTypeIds, args, scriptContext);
  3262. }
  3263. }
  3264. template<typename T>
  3265. /* static */ void JavascriptArray::SetConcatItem(Var aItem, uint idxArg, JavascriptArray* pDestArray, RecyclableObject* pDestObj, T idxDest, ScriptContext *scriptContext)
  3266. {
  3267. if (BoxConcatItem(aItem, idxArg, scriptContext))
  3268. {
  3269. // bug# 725784: ES5: not calling ToObject in Step 1 of 15.4.4.4
  3270. RecyclableObject* pObj = nullptr;
  3271. if (FALSE == JavascriptConversion::ToObject(aItem, scriptContext, &pObj))
  3272. {
  3273. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.concat"));
  3274. }
  3275. if (pDestArray)
  3276. {
  3277. pDestArray->GenericDirectSetItemAt(idxDest, pObj);
  3278. }
  3279. else
  3280. {
  3281. SetArrayLikeObjects(pDestObj, idxDest, pObj);
  3282. }
  3283. }
  3284. else
  3285. {
  3286. if (pDestArray)
  3287. {
  3288. pDestArray->GenericDirectSetItemAt(idxDest, aItem);
  3289. }
  3290. else
  3291. {
  3292. SetArrayLikeObjects(pDestObj, idxDest, aItem);
  3293. }
  3294. }
  3295. }
  3296. int64 JavascriptArray::GetFromLastIndex(Var arg, int64 length, ScriptContext *scriptContext)
  3297. {
  3298. int64 fromIndex;
  3299. if (TaggedInt::Is(arg))
  3300. {
  3301. int intValue = TaggedInt::ToInt32(arg);
  3302. if (intValue >= 0)
  3303. {
  3304. fromIndex = min<int64>(intValue, length - 1);
  3305. }
  3306. else if ((uint32)-intValue > length)
  3307. {
  3308. return length;
  3309. }
  3310. else
  3311. {
  3312. fromIndex = intValue + length;
  3313. }
  3314. }
  3315. else
  3316. {
  3317. double value = JavascriptConversion::ToInteger(arg, scriptContext);
  3318. if (value >= 0)
  3319. {
  3320. fromIndex = (int64)min(value, (double)(length - 1));
  3321. }
  3322. else if (value + length < 0)
  3323. {
  3324. return length;
  3325. }
  3326. else
  3327. {
  3328. fromIndex = (int64)(value + length);
  3329. }
  3330. }
  3331. return fromIndex;
  3332. }
  3333. // includesAlgorithm specifies to follow ES7 Array.prototype.includes semantics instead of Array.prototype.indexOf
  3334. // Differences
  3335. // 1. Returns boolean true or false value instead of the search hit index
  3336. // 2. Follows SameValueZero algorithm instead of StrictEquals
  3337. // 3. Missing values are scanned if the search value is undefined
  3338. template <bool includesAlgorithm>
  3339. Var JavascriptArray::IndexOfHelper(Arguments const & args, ScriptContext *scriptContext)
  3340. {
  3341. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3342. RecyclableObject* obj = nullptr;
  3343. JavascriptArray* pArr = nullptr;
  3344. BigIndex length;
  3345. Var trueValue = scriptContext->GetLibrary()->GetTrue();
  3346. Var falseValue = scriptContext->GetLibrary()->GetFalse();
  3347. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.indexOf"), &pArr, &obj, &length));
  3348. Var search = nullptr;
  3349. uint32 fromIndex = 0;
  3350. uint64 fromIndex64 = 0;
  3351. // The evaluation of method arguments may change the type of the array. Hence, we do that prior to the actual helper method calls.
  3352. // The if clause of the conditional statement below applies to an JavascriptArray or TypedArray instances. The rest of the conditional
  3353. // clauses apply to an ES5Array or other valid Javascript objects.
  3354. if ((pArr || TypedArrayBase::Is(obj)) && (length.IsSmallIndex() || length.IsUint32Max()))
  3355. {
  3356. uint32 len = length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex();
  3357. JS_REENTRANT(jsReentLock, BOOL gotParam = GetParamForIndexOf(len, args, search, fromIndex, scriptContext));
  3358. if (!gotParam)
  3359. {
  3360. return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
  3361. }
  3362. }
  3363. else if (length.IsSmallIndex())
  3364. {
  3365. JS_REENTRANT(jsReentLock, BOOL gotParam = GetParamForIndexOf(length.GetSmallIndex(), args, search, fromIndex, scriptContext));
  3366. if (!gotParam)
  3367. {
  3368. return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
  3369. }
  3370. }
  3371. else
  3372. {
  3373. JS_REENTRANT(jsReentLock, BOOL gotParam = GetParamForIndexOf(length.GetBigIndex(), args, search, fromIndex64, scriptContext));
  3374. if (!gotParam)
  3375. {
  3376. return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
  3377. }
  3378. }
  3379. // Side effects (such as defining a property in a ToPrimitive call) during evaluation of fromIndex argument may convert the array to an ES5 array.
  3380. if (pArr && !JavascriptArray::Is(obj))
  3381. {
  3382. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  3383. pArr = nullptr;
  3384. }
  3385. if (pArr)
  3386. {
  3387. if (length.IsSmallIndex() || length.IsUint32Max())
  3388. {
  3389. uint32 len = length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex();
  3390. JS_REENTRANT(jsReentLock, int32 index = pArr->HeadSegmentIndexOfHelper(search, fromIndex, len, includesAlgorithm, scriptContext));
  3391. // If we found the search value in the head segment, or if we determined there is no need to search other segments,
  3392. // we stop right here.
  3393. if (index != -1 || fromIndex == -1)
  3394. {
  3395. if (includesAlgorithm)
  3396. {
  3397. //Array.prototype.includes
  3398. return (index == -1) ? falseValue : trueValue;
  3399. }
  3400. else
  3401. {
  3402. //Array.prototype.indexOf
  3403. return JavascriptNumber::ToVar(index, scriptContext);
  3404. }
  3405. }
  3406. // If we really must search other segments, let's do it now. We'll have to search the slow way (dealing with holes, etc.).
  3407. switch (pArr->GetTypeId())
  3408. {
  3409. case Js::TypeIds_Array:
  3410. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(pArr, search, fromIndex, len, scriptContext));
  3411. case Js::TypeIds_NativeIntArray:
  3412. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(JavascriptNativeIntArray::FromVar(pArr), search, fromIndex, len, scriptContext));
  3413. case Js::TypeIds_NativeFloatArray:
  3414. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(JavascriptNativeFloatArray::FromVar(pArr), search, fromIndex, len, scriptContext));
  3415. default:
  3416. AssertMsg(FALSE, "invalid array typeid");
  3417. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(pArr, search, fromIndex, len, scriptContext));
  3418. }
  3419. }
  3420. }
  3421. // source object is not a JavascriptArray but source could be a TypedArray
  3422. if (TypedArrayBase::Is(obj))
  3423. {
  3424. if (length.IsSmallIndex() || length.IsUint32Max())
  3425. {
  3426. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(TypedArrayBase::FromVar(obj), search, fromIndex, length.GetSmallIndex(), scriptContext));
  3427. }
  3428. }
  3429. if (length.IsSmallIndex())
  3430. {
  3431. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(obj, search, fromIndex, length.GetSmallIndex(), scriptContext));
  3432. }
  3433. else
  3434. {
  3435. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(obj, search, fromIndex64, length.GetBigIndex(), scriptContext));
  3436. }
  3437. }
  3438. // Array.prototype.indexOf as defined in ES6.0 (final) Section 22.1.3.11
  3439. Var JavascriptArray::EntryIndexOf(RecyclableObject* function, CallInfo callInfo, ...)
  3440. {
  3441. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  3442. ARGUMENTS(args, callInfo);
  3443. ScriptContext* scriptContext = function->GetScriptContext();
  3444. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3445. Assert(!(callInfo.Flags & CallFlags_New));
  3446. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_indexOf);
  3447. JS_REENTRANT_UNLOCK(jsReentLock, Var returnValue = IndexOfHelper<false>(args, scriptContext));
  3448. //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
  3449. Assert(returnValue != scriptContext->GetLibrary()->GetTrue() && returnValue != scriptContext->GetLibrary()->GetFalse());
  3450. return returnValue;
  3451. }
  3452. Var JavascriptArray::EntryIncludes(RecyclableObject* function, CallInfo callInfo, ...)
  3453. {
  3454. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  3455. ARGUMENTS(args, callInfo);
  3456. ScriptContext* scriptContext = function->GetScriptContext();
  3457. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3458. Assert(!(callInfo.Flags & CallFlags_New));
  3459. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_includes);
  3460. JS_REENTRANT(jsReentLock, Var returnValue = IndexOfHelper<true>(args, scriptContext));
  3461. Assert(returnValue == scriptContext->GetLibrary()->GetTrue() || returnValue == scriptContext->GetLibrary()->GetFalse());
  3462. return returnValue;
  3463. }
  3464. template<typename T>
  3465. BOOL JavascriptArray::GetParamForIndexOf(T length, Arguments const& args, Var& search, T& fromIndex, ScriptContext * scriptContext)
  3466. {
  3467. if (length == 0)
  3468. {
  3469. return false;
  3470. }
  3471. if (args.Info.Count > 2)
  3472. {
  3473. fromIndex = GetFromIndex(args[2], length, scriptContext);
  3474. if (fromIndex >= length)
  3475. {
  3476. return false;
  3477. }
  3478. search = args[1];
  3479. }
  3480. else
  3481. {
  3482. fromIndex = 0;
  3483. search = args.Info.Count > 1 ? args[1] : scriptContext->GetLibrary()->GetUndefined();
  3484. }
  3485. return true;
  3486. }
  3487. template <>
  3488. BOOL JavascriptArray::TemplatedGetItem(RecyclableObject * obj, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3489. {
  3490. // Note: Sometime cross site array go down this path to get the marshalling
  3491. Assert(!VirtualTableInfo<JavascriptArray>::HasVirtualTable(obj)
  3492. && !VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(obj)
  3493. && !VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(obj));
  3494. if (checkHasItem && !JavascriptOperators::HasItem(obj, index))
  3495. {
  3496. return FALSE;
  3497. }
  3498. return JavascriptOperators::GetItem(obj, index, element, scriptContext);
  3499. }
  3500. template <>
  3501. BOOL JavascriptArray::TemplatedGetItem(RecyclableObject * obj, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3502. {
  3503. // Note: Sometime cross site array go down this path to get the marshalling
  3504. Assert(!VirtualTableInfo<JavascriptArray>::HasVirtualTable(obj)
  3505. && !VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(obj)
  3506. && !VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(obj));
  3507. PropertyRecord const * propertyRecord;
  3508. JavascriptOperators::GetPropertyIdForInt(index, scriptContext, &propertyRecord);
  3509. if (checkHasItem && !JavascriptOperators::HasProperty(obj, propertyRecord->GetPropertyId()))
  3510. {
  3511. return FALSE;
  3512. }
  3513. *element = JavascriptOperators::GetProperty(obj, propertyRecord->GetPropertyId(), scriptContext);
  3514. return *element != scriptContext->GetLibrary()->GetUndefined();
  3515. }
  3516. template <>
  3517. BOOL JavascriptArray::TemplatedGetItem(JavascriptArray *pArr, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3518. {
  3519. Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(pArr)
  3520. || VirtualTableInfo<CrossSiteObject<JavascriptArray>>::HasVirtualTable(pArr));
  3521. return pArr->JavascriptArray::DirectGetItemAtFull(index, element);
  3522. }
  3523. template <>
  3524. BOOL JavascriptArray::TemplatedGetItem(JavascriptArray *pArr, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3525. {
  3526. // This should never get called.
  3527. Assert(false);
  3528. Throw::InternalError();
  3529. }
  3530. template <>
  3531. BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeIntArray *pArr, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3532. {
  3533. Assert(VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(pArr)
  3534. || VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::HasVirtualTable(pArr));
  3535. return pArr->JavascriptNativeIntArray::DirectGetItemAtFull(index, element);
  3536. }
  3537. template <>
  3538. BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeIntArray *pArr, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3539. {
  3540. // This should never get called.
  3541. Assert(false);
  3542. Throw::InternalError();
  3543. }
  3544. template <>
  3545. BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeFloatArray *pArr, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3546. {
  3547. Assert(VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(pArr)
  3548. || VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::HasVirtualTable(pArr));
  3549. return pArr->JavascriptNativeFloatArray::DirectGetItemAtFull(index, element);
  3550. }
  3551. template <>
  3552. BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeFloatArray *pArr, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3553. {
  3554. // This should never get called.
  3555. Assert(false);
  3556. Throw::InternalError();
  3557. }
  3558. template <>
  3559. BOOL JavascriptArray::TemplatedGetItem(TypedArrayBase * typedArrayBase, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3560. {
  3561. // We need to do explicit check for items since length value may not actually match the actual TypedArray length.
  3562. // User could add a length property to a TypedArray instance which lies and returns a different value from the underlying length.
  3563. // Since this method can be called via Array.prototype.indexOf with .apply or .call passing a TypedArray as this parameter
  3564. // we don't know whether or not length == typedArrayBase->GetLength().
  3565. if (checkHasItem && !typedArrayBase->HasItem(index))
  3566. {
  3567. return false;
  3568. }
  3569. *element = typedArrayBase->DirectGetItem(index);
  3570. return true;
  3571. }
  3572. template <>
  3573. BOOL JavascriptArray::TemplatedGetItem(TypedArrayBase * typedArrayBase, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3574. {
  3575. // This should never get called.
  3576. Assert(false);
  3577. Throw::InternalError();
  3578. }
  3579. template <bool includesAlgorithm, typename T, typename P>
  3580. Var JavascriptArray::TemplatedIndexOfHelper(T * pArr, Var search, P fromIndex, P toIndex, ScriptContext * scriptContext)
  3581. {
  3582. Var element = nullptr;
  3583. bool isSearchTaggedInt = TaggedInt::Is(search);
  3584. bool doUndefinedSearch = includesAlgorithm && JavascriptOperators::GetTypeId(search) == TypeIds_Undefined;
  3585. Var trueValue = scriptContext->GetLibrary()->GetTrue();
  3586. Var falseValue = scriptContext->GetLibrary()->GetFalse();
  3587. //Consider: enumerating instead of walking all indices
  3588. for (P i = fromIndex; i < toIndex; i++)
  3589. {
  3590. if (!TryTemplatedGetItem(pArr, i, &element, scriptContext, !includesAlgorithm))
  3591. {
  3592. if (doUndefinedSearch)
  3593. {
  3594. return trueValue;
  3595. }
  3596. continue;
  3597. }
  3598. if (isSearchTaggedInt && TaggedInt::Is(element))
  3599. {
  3600. if (element == search)
  3601. {
  3602. return includesAlgorithm? trueValue : JavascriptNumber::ToVar(i, scriptContext);
  3603. }
  3604. continue;
  3605. }
  3606. if (includesAlgorithm)
  3607. {
  3608. //Array.prototype.includes
  3609. if (JavascriptConversion::SameValueZero(element, search))
  3610. {
  3611. return trueValue;
  3612. }
  3613. }
  3614. else
  3615. {
  3616. //Array.prototype.indexOf
  3617. if (JavascriptOperators::StrictEqual(element, search, scriptContext))
  3618. {
  3619. return JavascriptNumber::ToVar(i, scriptContext);
  3620. }
  3621. }
  3622. }
  3623. return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
  3624. }
  3625. int32 JavascriptArray::HeadSegmentIndexOfHelper(Var search, uint32 &fromIndex, uint32 toIndex, bool includesAlgorithm, ScriptContext * scriptContext)
  3626. {
  3627. Assert(Is(GetTypeId()) && !JavascriptNativeArray::Is(GetTypeId()));
  3628. if (!HasNoMissingValues() || fromIndex >= GetHead()->length)
  3629. {
  3630. return -1;
  3631. }
  3632. bool isSearchTaggedInt = TaggedInt::Is(search);
  3633. // We need to cast head segment to SparseArraySegment<Var> to have access to GetElement (onSparseArraySegment<T>). Because there are separate overloads of this
  3634. // virtual method on JavascriptNativeIntArray and JavascriptNativeFloatArray, we know this version of this method will only be called for true JavascriptArray, and not for
  3635. // either of the derived native arrays, so the elements of each segment used here must be Vars. Hence, the cast is safe.
  3636. SparseArraySegment<Var>* head = static_cast<SparseArraySegment<Var>*>(GetHead());
  3637. uint32 toIndexTrimmed = toIndex <= head->length ? toIndex : head->length;
  3638. for (uint32 i = fromIndex; i < toIndexTrimmed; i++)
  3639. {
  3640. Var element = head->GetElement(i);
  3641. if (isSearchTaggedInt && TaggedInt::Is(element))
  3642. {
  3643. if (search == element)
  3644. {
  3645. return i;
  3646. }
  3647. }
  3648. else if (includesAlgorithm && JavascriptConversion::SameValueZero(element, search))
  3649. {
  3650. //Array.prototype.includes
  3651. return i;
  3652. }
  3653. else if (JavascriptOperators::StrictEqual(element, search, scriptContext))
  3654. {
  3655. //Array.prototype.indexOf
  3656. return i;
  3657. }
  3658. }
  3659. // Element not found in the head segment. Keep looking only if the range of indices extends past
  3660. // the head segment.
  3661. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3662. return -1;
  3663. }
  3664. template<typename T>
  3665. bool AreAllBytesEqual(T value)
  3666. {
  3667. byte* bValue = (byte*)&value;
  3668. byte firstByte = *bValue++;
  3669. for (int i = 1; i < sizeof(T); ++i)
  3670. {
  3671. if (*bValue++ != firstByte)
  3672. {
  3673. return false;
  3674. }
  3675. }
  3676. return true;
  3677. }
  3678. template<>
  3679. void JavascriptArray::CopyValueToSegmentBuferNoCheck(Field(double)* buffer, uint32 length, double value)
  3680. {
  3681. if (JavascriptNumber::IsZero(value) && !JavascriptNumber::IsNegZero(value))
  3682. {
  3683. memset(buffer, 0, sizeof(double) * length);
  3684. }
  3685. else
  3686. {
  3687. for (uint32 i = 0; i < length; i++)
  3688. {
  3689. buffer[i] = value;
  3690. }
  3691. }
  3692. }
  3693. template<>
  3694. void JavascriptArray::CopyValueToSegmentBuferNoCheck(Field(int32)* buffer, uint32 length, int32 value)
  3695. {
  3696. if (value == 0 || AreAllBytesEqual(value))
  3697. {
  3698. memset(buffer, *(byte*)&value, sizeof(int32)* length);
  3699. }
  3700. else
  3701. {
  3702. for (uint32 i = 0; i < length; i++)
  3703. {
  3704. buffer[i] = value;
  3705. }
  3706. }
  3707. }
  3708. template<>
  3709. void JavascriptArray::CopyValueToSegmentBuferNoCheck(Field(Js::Var)* buffer, uint32 length, Js::Var value)
  3710. {
  3711. for (uint32 i = 0; i < length; i++)
  3712. {
  3713. buffer[i] = value;
  3714. }
  3715. }
  3716. int32 JavascriptNativeIntArray::HeadSegmentIndexOfHelper(Var search, uint32 &fromIndex, uint32 toIndex, bool includesAlgorithm, ScriptContext * scriptContext)
  3717. {
  3718. // We proceed largely in the same manner as in JavascriptArray's version of this method (see comments there for more information),
  3719. // 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:
  3720. // 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
  3721. // the search value is some other kind of Var, we can return -1 without ever iterating over the elements.
  3722. // 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.
  3723. // Instead we can use simple C++ equality (which in case of such values is equivalent to strict equality in JavaScript).
  3724. if (!HasNoMissingValues() || fromIndex >= GetHead()->length)
  3725. {
  3726. return -1;
  3727. }
  3728. bool isSearchTaggedInt = TaggedInt::Is(search);
  3729. if (!isSearchTaggedInt && !JavascriptNumber::Is_NoTaggedIntCheck(search))
  3730. {
  3731. // The value can't be in the array, but it could be in a prototype, and we can only guarantee that
  3732. // the head segment has no gaps.
  3733. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3734. return -1;
  3735. }
  3736. int32 searchAsInt32;
  3737. if (isSearchTaggedInt)
  3738. {
  3739. searchAsInt32 = TaggedInt::ToInt32(search);
  3740. }
  3741. else if (!JavascriptNumber::TryGetInt32Value<true>(JavascriptNumber::GetValue(search), &searchAsInt32))
  3742. {
  3743. // The value can't be in the array, but it could be in a prototype, and we can only guarantee that
  3744. // the head segment has no gaps.
  3745. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3746. return -1;
  3747. }
  3748. // We need to cast head segment to SparseArraySegment<int32> to have access to GetElement (onSparseArraySegment<T>). Because there are separate overloads of this
  3749. // virtual method on JavascriptNativeIntArray and JavascriptNativeFloatArray, we know this version of this method will only be called for true JavascriptNativeIntArray, and not for
  3750. // the other two, so the elements of each segment used here must be int32's. Hence, the cast is safe.
  3751. SparseArraySegment<int32> * head = static_cast<SparseArraySegment<int32>*>(GetHead());
  3752. uint32 toIndexTrimmed = toIndex <= head->length ? toIndex : head->length;
  3753. for (uint32 i = fromIndex; i < toIndexTrimmed; i++)
  3754. {
  3755. int32 element = head->GetElement(i);
  3756. if (searchAsInt32 == element)
  3757. {
  3758. return i;
  3759. }
  3760. }
  3761. // Element not found in the head segment. Keep looking only if the range of indices extends past
  3762. // the head segment.
  3763. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3764. return -1;
  3765. }
  3766. int32 JavascriptNativeFloatArray::HeadSegmentIndexOfHelper(Var search, uint32 &fromIndex, uint32 toIndex, bool includesAlgorithm, ScriptContext * scriptContext)
  3767. {
  3768. // We proceed largely in the same manner as in JavascriptArray's version of this method (see comments there for more information),
  3769. // except when we can further optimize thanks to the knowledge that all elements in the array are doubles. This allows for two additional optimizations:
  3770. // 1. Only tagged ints or JavascriptNumbers can be strict equal to some element in the array (all doubles). Thus, if
  3771. // the search value is some other kind of Var, we can return -1 without ever iterating over the elements.
  3772. // 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.
  3773. // Instead we can use simple C++ equality (which in case of such values is equivalent to strict equality in JavaScript).
  3774. if (!HasNoMissingValues() || fromIndex >= GetHead()->length)
  3775. {
  3776. return -1;
  3777. }
  3778. bool isSearchTaggedInt = TaggedInt::Is(search);
  3779. if (!isSearchTaggedInt && !JavascriptNumber::Is_NoTaggedIntCheck(search))
  3780. {
  3781. // The value can't be in the array, but it could be in a prototype, and we can only guarantee that
  3782. // the head segment has no gaps.
  3783. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3784. return -1;
  3785. }
  3786. double searchAsDouble = isSearchTaggedInt ? TaggedInt::ToDouble(search) : JavascriptNumber::GetValue(search);
  3787. // We need to cast head segment to SparseArraySegment<double> to have access to GetElement (SparseArraySegment). We know the
  3788. // segment's elements are all Vars so the cast is safe. It would have been more convenient here if JavascriptArray
  3789. // used SparseArraySegment<Var>, instead of SparseArraySegmentBase.
  3790. SparseArraySegment<double> * head = static_cast<SparseArraySegment<double>*>(GetHead());
  3791. uint32 toIndexTrimmed = toIndex <= head->length ? toIndex : head->length;
  3792. bool matchNaN = includesAlgorithm && JavascriptNumber::IsNan(searchAsDouble);
  3793. for (uint32 i = fromIndex; i < toIndexTrimmed; i++)
  3794. {
  3795. double element = head->GetElement(i);
  3796. if (element == searchAsDouble)
  3797. {
  3798. return i;
  3799. }
  3800. //NaN != NaN we expect to match for NaN in Array.prototype.includes algorithm
  3801. if (matchNaN && JavascriptNumber::IsNan(element))
  3802. {
  3803. return i;
  3804. }
  3805. }
  3806. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3807. return -1;
  3808. }
  3809. Var JavascriptArray::EntryJoin(RecyclableObject* function, CallInfo callInfo, ...)
  3810. {
  3811. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  3812. ARGUMENTS(args, callInfo);
  3813. ScriptContext* scriptContext = function->GetScriptContext();
  3814. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3815. Assert(!(callInfo.Flags & CallFlags_New));
  3816. if (args.Info.Count == 0)
  3817. {
  3818. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.join"));
  3819. }
  3820. JavascriptString* separator;
  3821. if (args.Info.Count >= 2)
  3822. {
  3823. TypeId typeId = JavascriptOperators::GetTypeId(args[1]);
  3824. //ES5 15.4.4.5 If separator is undefined, let separator be the single-character String ",".
  3825. if (TypeIds_Undefined != typeId)
  3826. {
  3827. JS_REENTRANT(jsReentLock, separator = JavascriptConversion::ToString(args[1], scriptContext));
  3828. }
  3829. else
  3830. {
  3831. separator = scriptContext->GetLibrary()->GetCommaDisplayString();
  3832. }
  3833. }
  3834. else
  3835. {
  3836. separator = scriptContext->GetLibrary()->GetCommaDisplayString();
  3837. }
  3838. JS_REENTRANT_UNLOCK(jsReentLock, return JoinHelper(args[0], separator, scriptContext));
  3839. }
  3840. JavascriptString* JavascriptArray::JoinToString(Var value, ScriptContext* scriptContext)
  3841. {
  3842. TypeId typeId = JavascriptOperators::GetTypeId(value);
  3843. if (typeId == TypeIds_Null || typeId == TypeIds_Undefined)
  3844. {
  3845. return scriptContext->GetLibrary()->GetEmptyString();
  3846. }
  3847. else
  3848. {
  3849. return JavascriptConversion::ToString(value, scriptContext);
  3850. }
  3851. }
  3852. JavascriptString* JavascriptArray::JoinHelper(Var thisArg, JavascriptString* separator, ScriptContext* scriptContext)
  3853. {
  3854. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3855. bool isArray = JavascriptArray::Is(thisArg) && (scriptContext == JavascriptArray::FromVar(thisArg)->GetScriptContext());
  3856. bool isProxy = JavascriptProxy::Is(thisArg) && (scriptContext == JavascriptProxy::FromVar(thisArg)->GetScriptContext());
  3857. Var target = NULL;
  3858. bool isTargetObjectPushed = false;
  3859. // if we are visiting a proxy object, track that we have visited the target object as well so the next time w
  3860. // call the join helper for the target of this proxy, we will return above.
  3861. if (isProxy)
  3862. {
  3863. JavascriptProxy* proxy = JavascriptProxy::FromVar(thisArg);
  3864. Assert(proxy);
  3865. target = proxy->GetTarget();
  3866. if (target != nullptr)
  3867. {
  3868. // If we end up joining same array, instead of going in infinite loop, return the empty string
  3869. if (scriptContext->CheckObject(target))
  3870. {
  3871. return scriptContext->GetLibrary()->GetEmptyString();
  3872. }
  3873. else
  3874. {
  3875. scriptContext->PushObject(target);
  3876. isTargetObjectPushed = true;
  3877. }
  3878. }
  3879. }
  3880. // If we end up joining same array, instead of going in infinite loop, return the empty string
  3881. else if (scriptContext->CheckObject(thisArg))
  3882. {
  3883. return scriptContext->GetLibrary()->GetEmptyString();
  3884. }
  3885. if (!isTargetObjectPushed)
  3886. {
  3887. scriptContext->PushObject(thisArg);
  3888. }
  3889. JavascriptString* res = nullptr;
  3890. TryFinally([&]()
  3891. {
  3892. if (isArray)
  3893. {
  3894. #if ENABLE_COPYONACCESS_ARRAY
  3895. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray(thisArg);
  3896. #endif
  3897. JavascriptArray * arr = JavascriptArray::FromVar(thisArg);
  3898. switch (arr->GetTypeId())
  3899. {
  3900. case Js::TypeIds_Array:
  3901. JS_REENTRANT(jsReentLock, res = JoinArrayHelper(arr, separator, scriptContext));
  3902. break;
  3903. case Js::TypeIds_NativeIntArray:
  3904. JS_REENTRANT(jsReentLock, res = JoinArrayHelper(JavascriptNativeIntArray::FromVar(arr), separator, scriptContext));
  3905. break;
  3906. case Js::TypeIds_NativeFloatArray:
  3907. JS_REENTRANT(jsReentLock, res = JoinArrayHelper(JavascriptNativeFloatArray::FromVar(arr), separator, scriptContext));
  3908. break;
  3909. }
  3910. }
  3911. else if (RecyclableObject::Is(thisArg))
  3912. {
  3913. JS_REENTRANT(jsReentLock, res = JoinOtherHelper(RecyclableObject::FromVar(thisArg), separator, scriptContext));
  3914. }
  3915. else
  3916. {
  3917. JS_REENTRANT(jsReentLock, res = JoinOtherHelper(scriptContext->GetLibrary()->CreateNumberObject(thisArg), separator, scriptContext));
  3918. }
  3919. },
  3920. [&](bool/*hasException*/)
  3921. {
  3922. Var top = scriptContext->PopObject();
  3923. if (isProxy)
  3924. {
  3925. AssertMsg(top == target, "Unmatched operation stack");
  3926. }
  3927. else
  3928. {
  3929. AssertMsg(top == thisArg, "Unmatched operation stack");
  3930. }
  3931. });
  3932. if (res == nullptr)
  3933. {
  3934. res = scriptContext->GetLibrary()->GetEmptyString();
  3935. }
  3936. return res;
  3937. }
  3938. static const charcount_t Join_MaxEstimatedAppendCount = static_cast<charcount_t>((64 << 20) / sizeof(void *)); // 64 MB worth of pointers
  3939. template <typename T>
  3940. JavascriptString* JavascriptArray::JoinArrayHelper(T * arr, JavascriptString* separator, ScriptContext* scriptContext)
  3941. {
  3942. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3943. Assert(VirtualTableInfo<T>::HasVirtualTable(arr) || VirtualTableInfo<CrossSiteObject<T>>::HasVirtualTable(arr));
  3944. const uint32 arrLength = arr->length;
  3945. switch(arrLength)
  3946. {
  3947. default:
  3948. {
  3949. CaseDefault:
  3950. bool hasSeparator = (separator->GetLength() != 0);
  3951. const charcount_t estimatedAppendCount =
  3952. min(
  3953. Join_MaxEstimatedAppendCount,
  3954. static_cast<charcount_t>(arrLength + (hasSeparator ? arrLength - 1 : 0)));
  3955. CompoundString *const cs =
  3956. CompoundString::NewWithPointerCapacity(estimatedAppendCount, scriptContext->GetLibrary());
  3957. Var item = nullptr;
  3958. BOOL gotItem;
  3959. JS_REENTRANT(jsReentLock, gotItem = TemplatedGetItem(arr, 0u, &item, scriptContext));
  3960. if (gotItem)
  3961. {
  3962. JS_REENTRANT(jsReentLock, cs->Append(JavascriptArray::JoinToString(item, scriptContext)));
  3963. }
  3964. for (uint32 i = 1; i < arrLength; i++)
  3965. {
  3966. if (hasSeparator)
  3967. {
  3968. cs->Append(separator);
  3969. }
  3970. JS_REENTRANT(jsReentLock, gotItem = TryTemplatedGetItem(arr, i, &item, scriptContext));
  3971. if (gotItem)
  3972. {
  3973. JS_REENTRANT(jsReentLock, cs->Append(JavascriptArray::JoinToString(item, scriptContext)));
  3974. }
  3975. }
  3976. return cs;
  3977. }
  3978. case 2:
  3979. {
  3980. bool hasSeparator = (separator->GetLength() != 0);
  3981. BOOL gotItem;
  3982. if(hasSeparator)
  3983. {
  3984. goto CaseDefault;
  3985. }
  3986. JavascriptString *res = nullptr;
  3987. Var item = nullptr;
  3988. JS_REENTRANT(jsReentLock, gotItem = TemplatedGetItem(arr, 0u, &item, scriptContext));
  3989. if (gotItem)
  3990. {
  3991. JS_REENTRANT(jsReentLock, res = JavascriptArray::JoinToString(item, scriptContext));
  3992. }
  3993. JS_REENTRANT(jsReentLock, gotItem = TryTemplatedGetItem(arr, 1u, &item, scriptContext));
  3994. if (gotItem)
  3995. {
  3996. JS_REENTRANT(jsReentLock, JavascriptString *const itemString = JavascriptArray::JoinToString(item, scriptContext));
  3997. return res ? ConcatString::New(res, itemString) : itemString;
  3998. }
  3999. if(res)
  4000. {
  4001. return res;
  4002. }
  4003. goto Case0;
  4004. }
  4005. case 1:
  4006. {
  4007. Var item = nullptr;
  4008. BOOL gotItem;
  4009. JS_REENTRANT(jsReentLock, gotItem = TemplatedGetItem(arr, 0u, &item, scriptContext));
  4010. if (gotItem)
  4011. {
  4012. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::JoinToString(item, scriptContext));
  4013. }
  4014. // fall through
  4015. }
  4016. case 0:
  4017. Case0:
  4018. return scriptContext->GetLibrary()->GetEmptyString();
  4019. }
  4020. }
  4021. JavascriptString* JavascriptArray::JoinOtherHelper(RecyclableObject* object, JavascriptString* separator, ScriptContext* scriptContext)
  4022. {
  4023. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4024. // In ES6-mode, we always load the length property from the object instead of using the internal slot.
  4025. // Even for arrays, this is now observable via proxies.
  4026. // If source object is not an array, we fall back to this behavior anyway.
  4027. JS_REENTRANT(jsReentLock,
  4028. int64 cSrcLength = (int64)OP_GetLength(object, scriptContext));
  4029. switch (cSrcLength)
  4030. {
  4031. default:
  4032. {
  4033. CaseDefault:
  4034. bool hasSeparator = (separator->GetLength() != 0);
  4035. BOOL gotItem;
  4036. const charcount_t estimatedAppendCount =
  4037. min(
  4038. Join_MaxEstimatedAppendCount,
  4039. static_cast<charcount_t>(cSrcLength + (hasSeparator ? cSrcLength - 1 : 0)));
  4040. CompoundString *const cs =
  4041. CompoundString::NewWithPointerCapacity(estimatedAppendCount, scriptContext->GetLibrary());
  4042. Var value = nullptr;
  4043. JS_REENTRANT(jsReentLock, gotItem = JavascriptOperators::GetItem(object, 0u, &value, scriptContext));
  4044. if (gotItem)
  4045. {
  4046. JS_REENTRANT(jsReentLock, cs->Append(JavascriptArray::JoinToString(value, scriptContext)));
  4047. }
  4048. for (uint32 i = 1; i < cSrcLength; i++)
  4049. {
  4050. if (hasSeparator)
  4051. {
  4052. cs->Append(separator);
  4053. }
  4054. JS_REENTRANT(jsReentLock, gotItem = JavascriptOperators::GetItem(object, i, &value, scriptContext));
  4055. if (gotItem)
  4056. {
  4057. JS_REENTRANT(jsReentLock, cs->Append(JavascriptArray::JoinToString(value, scriptContext)));
  4058. }
  4059. }
  4060. return cs;
  4061. }
  4062. case 2:
  4063. {
  4064. bool hasSeparator = (separator->GetLength() != 0);
  4065. BOOL gotItem;
  4066. if(hasSeparator)
  4067. {
  4068. goto CaseDefault;
  4069. }
  4070. JavascriptString *res = nullptr;
  4071. Var value = nullptr;
  4072. JS_REENTRANT(jsReentLock, gotItem = JavascriptOperators::GetItem(object, 0u, &value, scriptContext));
  4073. if (gotItem)
  4074. {
  4075. JS_REENTRANT(jsReentLock, res = JavascriptArray::JoinToString(value, scriptContext));
  4076. }
  4077. JS_REENTRANT(jsReentLock, gotItem = JavascriptOperators::GetItem(object, 1u, &value, scriptContext));
  4078. if (gotItem)
  4079. {
  4080. JS_REENTRANT(jsReentLock, JavascriptString *const valueString = JavascriptArray::JoinToString(value, scriptContext));
  4081. return res ? ConcatString::New(res, valueString) : valueString;
  4082. }
  4083. if(res)
  4084. {
  4085. return res;
  4086. }
  4087. goto Case0;
  4088. }
  4089. case 1:
  4090. {
  4091. Var value = nullptr;
  4092. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(object, 0u, &value, scriptContext));
  4093. if (gotItem)
  4094. {
  4095. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::JoinToString(value, scriptContext));
  4096. }
  4097. // fall through
  4098. }
  4099. case 0:
  4100. Case0:
  4101. return scriptContext->GetLibrary()->GetEmptyString();
  4102. }
  4103. }
  4104. Var JavascriptArray::EntryLastIndexOf(RecyclableObject* function, CallInfo callInfo, ...)
  4105. {
  4106. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  4107. ARGUMENTS(args, callInfo);
  4108. ScriptContext* scriptContext = function->GetScriptContext();
  4109. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4110. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_lastIndexOf);
  4111. Assert(!(callInfo.Flags & CallFlags_New));
  4112. int64 length;
  4113. JavascriptArray * pArr = nullptr;
  4114. RecyclableObject* obj = nullptr;
  4115. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.lastIndexOf"), &pArr, &obj, &length));
  4116. Var search = nullptr;
  4117. int64 fromIndex;
  4118. JS_REENTRANT(jsReentLock,
  4119. BOOL gotParam = GetParamForLastIndexOf(length, args, search, fromIndex, scriptContext));
  4120. if (!gotParam)
  4121. {
  4122. return TaggedInt::ToVarUnchecked(-1);
  4123. }
  4124. // Side effects (such as defining a property in a ToPrimitive call) during evaluation of fromIndex argument may convert the array to an ES5 array.
  4125. if (pArr && !JavascriptArray::Is(obj))
  4126. {
  4127. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  4128. pArr = nullptr;
  4129. }
  4130. if (pArr)
  4131. {
  4132. switch (pArr->GetTypeId())
  4133. {
  4134. case Js::TypeIds_Array:
  4135. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(pArr, search, fromIndex, scriptContext));
  4136. case Js::TypeIds_NativeIntArray:
  4137. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(JavascriptNativeIntArray::FromVar(pArr), search, fromIndex, scriptContext));
  4138. case Js::TypeIds_NativeFloatArray:
  4139. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(JavascriptNativeFloatArray::FromVar(pArr), search, fromIndex, scriptContext));
  4140. default:
  4141. AssertMsg(FALSE, "invalid array typeid");
  4142. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(pArr, search, fromIndex, scriptContext));
  4143. }
  4144. }
  4145. // source object is not a JavascriptArray but source could be a TypedArray
  4146. if (TypedArrayBase::Is(obj))
  4147. {
  4148. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(TypedArrayBase::FromVar(obj), search, fromIndex, scriptContext));
  4149. }
  4150. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(obj, search, fromIndex, scriptContext));
  4151. }
  4152. // Array.prototype.lastIndexOf as described in ES6.0 (draft 22) Section 22.1.3.14
  4153. BOOL JavascriptArray::GetParamForLastIndexOf(int64 length, Arguments const & args, Var& search, int64& fromIndex, ScriptContext * scriptContext)
  4154. {
  4155. if (length == 0)
  4156. {
  4157. return false;
  4158. }
  4159. if (args.Info.Count > 2)
  4160. {
  4161. fromIndex = GetFromLastIndex(args[2], length, scriptContext);
  4162. if (fromIndex >= length)
  4163. {
  4164. return false;
  4165. }
  4166. search = args[1];
  4167. }
  4168. else
  4169. {
  4170. search = args.Info.Count > 1 ? args[1] : scriptContext->GetLibrary()->GetUndefined();
  4171. fromIndex = length - 1;
  4172. }
  4173. return true;
  4174. }
  4175. template <typename T>
  4176. Var JavascriptArray::LastIndexOfHelper(T* pArr, Var search, int64 fromIndex, ScriptContext * scriptContext)
  4177. {
  4178. Var element = nullptr;
  4179. bool isSearchTaggedInt = TaggedInt::Is(search);
  4180. // First handle the indices > 2^32
  4181. while (fromIndex >= MaxArrayLength)
  4182. {
  4183. Var index = JavascriptNumber::ToVar(fromIndex, scriptContext);
  4184. if (JavascriptOperators::OP_HasItem(pArr, index, scriptContext))
  4185. {
  4186. element = JavascriptOperators::OP_GetElementI(pArr, index, scriptContext);
  4187. if (isSearchTaggedInt && TaggedInt::Is(element))
  4188. {
  4189. if (element == search)
  4190. {
  4191. return index;
  4192. }
  4193. fromIndex--;
  4194. continue;
  4195. }
  4196. if (JavascriptOperators::StrictEqual(element, search, scriptContext))
  4197. {
  4198. return index;
  4199. }
  4200. }
  4201. fromIndex--;
  4202. }
  4203. Assert(fromIndex < MaxArrayLength);
  4204. // fromIndex now has to be < MaxArrayLength so casting to uint32 is safe
  4205. uint32 end = static_cast<uint32>(fromIndex);
  4206. for (uint32 i = 0; i <= end; i++)
  4207. {
  4208. uint32 index = end - i;
  4209. if (!TryTemplatedGetItem(pArr, index, &element, scriptContext))
  4210. {
  4211. continue;
  4212. }
  4213. if (isSearchTaggedInt && TaggedInt::Is(element))
  4214. {
  4215. if (element == search)
  4216. {
  4217. return JavascriptNumber::ToVar(index, scriptContext);
  4218. }
  4219. continue;
  4220. }
  4221. if (JavascriptOperators::StrictEqual(element, search, scriptContext))
  4222. {
  4223. return JavascriptNumber::ToVar(index, scriptContext);
  4224. }
  4225. }
  4226. return TaggedInt::ToVarUnchecked(-1);
  4227. }
  4228. /*
  4229. * PopWithNoDst
  4230. * - For pop calls that do not return a value, we only need to decrement the length of the array.
  4231. */
  4232. void JavascriptNativeArray::PopWithNoDst(Var nativeArray)
  4233. {
  4234. Assert(JavascriptNativeArray::Is(nativeArray));
  4235. JavascriptArray * arr = JavascriptArray::FromVar(nativeArray);
  4236. // we will bailout on length 0
  4237. Assert(arr->GetLength() != 0);
  4238. uint32 index = arr->GetLength() - 1;
  4239. arr->SetLength(index);
  4240. }
  4241. /*
  4242. * JavascriptNativeIntArray::Pop
  4243. * - Returns int32 value from the array.
  4244. * - Returns missing item when the element is not available in the array object.
  4245. * - It doesn't walk up the prototype chain.
  4246. * - Length is decremented only if it pops an int32 element, in all other cases - we bail out from the jitted code.
  4247. * - This api cannot cause any implicit call and hence do not need implicit call bailout test around this api
  4248. */
  4249. int32 JavascriptNativeIntArray::Pop(ScriptContext * scriptContext, Var object)
  4250. {
  4251. Assert(JavascriptNativeIntArray::Is(object));
  4252. JavascriptNativeIntArray * arr = JavascriptNativeIntArray::FromVar(object);
  4253. Assert(arr->GetLength() != 0);
  4254. uint32 index = arr->length - 1;
  4255. int32 element = Js::JavascriptOperators::OP_GetNativeIntElementI_UInt32(object, index, scriptContext);
  4256. //If it is a missing item, then don't update the length - Pre-op Bail out will happen.
  4257. if(!SparseArraySegment<int32>::IsMissingItem(&element))
  4258. {
  4259. arr->SetLength(index);
  4260. }
  4261. return element;
  4262. }
  4263. /*
  4264. * JavascriptNativeFloatArray::Pop
  4265. * - Returns double value from the array.
  4266. * - Returns missing item when the element is not available in the array object.
  4267. * - It doesn't walk up the prototype chain.
  4268. * - Length is decremented only if it pops a double element, in all other cases - we bail out from the jitted code.
  4269. * - This api cannot cause any implicit call and hence do not need implicit call bailout test around this api
  4270. */
  4271. double JavascriptNativeFloatArray::Pop(ScriptContext * scriptContext, Var object)
  4272. {
  4273. Assert(JavascriptNativeFloatArray::Is(object));
  4274. JavascriptNativeFloatArray * arr = JavascriptNativeFloatArray::FromVar(object);
  4275. Assert(arr->GetLength() != 0);
  4276. uint32 index = arr->length - 1;
  4277. double element = Js::JavascriptOperators::OP_GetNativeFloatElementI_UInt32(object, index, scriptContext);
  4278. // If it is a missing item then don't update the length - Pre-op Bail out will happen.
  4279. if(!SparseArraySegment<double>::IsMissingItem(&element))
  4280. {
  4281. arr->SetLength(index);
  4282. }
  4283. return element;
  4284. }
  4285. /*
  4286. * JavascriptArray::Pop
  4287. * - Calls the generic Pop API, which can find elements from the prototype chain, when it is not available in the array object.
  4288. * - This API may cause implicit calls. Handles Array and non-array objects
  4289. */
  4290. Var JavascriptArray::Pop(ScriptContext * scriptContext, Var object)
  4291. {
  4292. if (JavascriptArray::Is(object))
  4293. {
  4294. return EntryPopJavascriptArray(scriptContext, JavascriptArray::FromVar(object));
  4295. }
  4296. else
  4297. {
  4298. return EntryPopNonJavascriptArray(scriptContext, object);
  4299. }
  4300. }
  4301. Var JavascriptArray::EntryPopJavascriptArray(ScriptContext * scriptContext, JavascriptArray* arr)
  4302. {
  4303. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4304. uint32 length = arr->length;
  4305. if (length == 0)
  4306. {
  4307. // If length is 0, return 'undefined'
  4308. return scriptContext->GetLibrary()->GetUndefined();
  4309. }
  4310. uint32 index = length - 1;
  4311. Var element = nullptr;
  4312. JS_REENTRANT(jsReentLock, BOOL gotItem = arr->DirectGetItemAtFull(index, &element));
  4313. if (!gotItem)
  4314. {
  4315. element = scriptContext->GetLibrary()->GetUndefined();
  4316. }
  4317. else
  4318. {
  4319. element = CrossSite::MarshalVar(scriptContext, element);
  4320. }
  4321. arr->SetLength(index); // SetLength will clear element at index
  4322. #ifdef VALIDATE_ARRAY
  4323. arr->ValidateArray();
  4324. #endif
  4325. return element;
  4326. }
  4327. Var JavascriptArray::EntryPopNonJavascriptArray(ScriptContext * scriptContext, Var object)
  4328. {
  4329. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4330. RecyclableObject* dynamicObject = nullptr;
  4331. if (FALSE == JavascriptConversion::ToObject(object, scriptContext, &dynamicObject))
  4332. {
  4333. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.pop"));
  4334. }
  4335. JS_REENTRANT(jsReentLock, BigIndex length = OP_GetLength(dynamicObject, scriptContext));
  4336. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.pop"));
  4337. if (length == 0u)
  4338. {
  4339. // Set length = 0
  4340. JS_REENTRANT(jsReentLock,
  4341. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, TaggedInt::ToVarUnchecked(0), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  4342. return scriptContext->GetLibrary()->GetUndefined();
  4343. }
  4344. BigIndex index = length;
  4345. --index;
  4346. Var element = nullptr;
  4347. if (index.IsSmallIndex())
  4348. {
  4349. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(dynamicObject, index.GetSmallIndex(), &element, scriptContext));
  4350. if (!gotItem)
  4351. {
  4352. element = scriptContext->GetLibrary()->GetUndefined();
  4353. }
  4354. JS_REENTRANT(jsReentLock,
  4355. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, index.GetSmallIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig)),
  4356. // Set the new length
  4357. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(index.GetSmallIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  4358. }
  4359. else
  4360. {
  4361. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(dynamicObject, index.GetBigIndex(), &element, scriptContext));
  4362. if (!gotItem)
  4363. {
  4364. element = scriptContext->GetLibrary()->GetUndefined();
  4365. }
  4366. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, index.GetBigIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig)),
  4367. // Set the new length
  4368. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(index.GetBigIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  4369. }
  4370. return element;
  4371. }
  4372. Var JavascriptArray::EntryPop(RecyclableObject* function, CallInfo callInfo, ...)
  4373. {
  4374. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  4375. ARGUMENTS(args, callInfo);
  4376. ScriptContext* scriptContext = function->GetScriptContext();
  4377. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4378. Assert(!(callInfo.Flags & CallFlags_New));
  4379. if (args.Info.Count == 0)
  4380. {
  4381. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.pop"));
  4382. }
  4383. if (JavascriptArray::Is(args[0]))
  4384. {
  4385. JS_REENTRANT_UNLOCK(jsReentLock, return EntryPopJavascriptArray(scriptContext, JavascriptArray::FromVar(args.Values[0])));
  4386. }
  4387. else
  4388. {
  4389. JS_REENTRANT_UNLOCK(jsReentLock, return EntryPopNonJavascriptArray(scriptContext, args.Values[0]));
  4390. }
  4391. }
  4392. /*
  4393. * JavascriptNativeIntArray::Push
  4394. * Pushes Int element in a native Int Array.
  4395. * We call the generic Push, if the array is not native Int or we have a really big array.
  4396. */
  4397. Var JavascriptNativeIntArray::Push(ScriptContext * scriptContext, Var array, int value)
  4398. {
  4399. // Handle non crossSite native int arrays here length within MaxArrayLength.
  4400. // JavascriptArray::Push will handle other cases.
  4401. if (JavascriptNativeIntArray::IsNonCrossSite(array))
  4402. {
  4403. JavascriptNativeIntArray * nativeIntArray = JavascriptNativeIntArray::FromVar(array);
  4404. Assert(!nativeIntArray->IsCrossSiteObject());
  4405. uint32 n = nativeIntArray->length;
  4406. if(n < JavascriptArray::MaxArrayLength)
  4407. {
  4408. nativeIntArray->SetItem(n, value);
  4409. n++;
  4410. AssertMsg(n == nativeIntArray->length, "Wrong update to the length of the native Int array");
  4411. return JavascriptNumber::ToVar(n, scriptContext);
  4412. }
  4413. }
  4414. return JavascriptArray::Push(scriptContext, array, JavascriptNumber::ToVar(value, scriptContext));
  4415. }
  4416. /*
  4417. * JavascriptNativeFloatArray::Push
  4418. * Pushes Float element in a native Int Array.
  4419. * We call the generic Push, if the array is not native Float or we have a really big array.
  4420. */
  4421. Var JavascriptNativeFloatArray::Push(ScriptContext * scriptContext, Var * array, double value)
  4422. {
  4423. // Handle non crossSite native int arrays here length within MaxArrayLength.
  4424. // JavascriptArray::Push will handle other cases.
  4425. if(JavascriptNativeFloatArray::IsNonCrossSite(array))
  4426. {
  4427. JavascriptNativeFloatArray * nativeFloatArray = JavascriptNativeFloatArray::FromVar(array);
  4428. Assert(!nativeFloatArray->IsCrossSiteObject());
  4429. uint32 n = nativeFloatArray->length;
  4430. if(n < JavascriptArray::MaxArrayLength)
  4431. {
  4432. nativeFloatArray->SetItem(n, value);
  4433. n++;
  4434. AssertMsg(n == nativeFloatArray->length, "Wrong update to the length of the native Float array");
  4435. return JavascriptNumber::ToVar(n, scriptContext);
  4436. }
  4437. }
  4438. return JavascriptArray::Push(scriptContext, array, JavascriptNumber::ToVarNoCheck(value, scriptContext));
  4439. }
  4440. /*
  4441. * JavascriptArray::Push
  4442. * Pushes Var element in a Var Array.
  4443. */
  4444. Var JavascriptArray::Push(ScriptContext * scriptContext, Var object, Var value)
  4445. {
  4446. Var args[2];
  4447. args[0] = object;
  4448. args[1] = value;
  4449. if (JavascriptArray::Is(object))
  4450. {
  4451. return EntryPushJavascriptArray(scriptContext, args, 2);
  4452. }
  4453. else
  4454. {
  4455. return EntryPushNonJavascriptArray(scriptContext, args, 2);
  4456. }
  4457. }
  4458. /*
  4459. * EntryPushNonJavascriptArray
  4460. * - Handles Entry push calls, when Objects are not javascript arrays
  4461. */
  4462. Var JavascriptArray::EntryPushNonJavascriptArray(ScriptContext * scriptContext, Var * args, uint argCount)
  4463. {
  4464. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4465. RecyclableObject* obj = nullptr;
  4466. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  4467. {
  4468. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.push"));
  4469. }
  4470. JS_REENTRANT_UNLOCK(jsReentLock, Var length = JavascriptOperators::OP_GetLength(obj, scriptContext));
  4471. if(JavascriptOperators::GetTypeId(length) == TypeIds_Undefined && scriptContext->GetThreadContext()->IsDisableImplicitCall() &&
  4472. scriptContext->GetThreadContext()->GetImplicitCallFlags() != Js::ImplicitCall_None)
  4473. {
  4474. return length;
  4475. }
  4476. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.push"));
  4477. BigIndex n;
  4478. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  4479. {
  4480. n = (uint64) JavascriptConversion::ToLength(length, scriptContext);
  4481. }
  4482. else
  4483. {
  4484. n = JavascriptConversion::ToUInt32(length, scriptContext);
  4485. }
  4486. // First handle "small" indices.
  4487. uint index;
  4488. for (index=1; index < argCount && n < JavascriptArray::MaxArrayLength; ++index, ++n)
  4489. {
  4490. JS_REENTRANT(jsReentLock,
  4491. BOOL setItem = JavascriptOperators::SetItem(obj, obj, n.GetSmallIndex(), args[index], scriptContext, PropertyOperation_ThrowIfNotExtensible));
  4492. if (h.IsThrowTypeError(setItem))
  4493. {
  4494. if (scriptContext->GetThreadContext()->RecordImplicitException())
  4495. {
  4496. h.ThrowTypeErrorOnFailure();
  4497. }
  4498. else
  4499. {
  4500. return nullptr;
  4501. }
  4502. }
  4503. }
  4504. // Use BigIndex if we need to push indices >= MaxArrayLength
  4505. if (index < argCount)
  4506. {
  4507. BigIndex big = n;
  4508. for (; index < argCount; ++index, ++big)
  4509. {
  4510. JS_REENTRANT(jsReentLock, BOOL setItem = big.SetItem(obj, args[index], PropertyOperation_ThrowIfNotExtensible));
  4511. if (h.IsThrowTypeError(setItem))
  4512. {
  4513. if(scriptContext->GetThreadContext()->RecordImplicitException())
  4514. {
  4515. h.ThrowTypeErrorOnFailure();
  4516. }
  4517. else
  4518. {
  4519. return nullptr;
  4520. }
  4521. }
  4522. }
  4523. // Set the new length; for objects it is all right for this to be >= MaxArrayLength
  4524. JS_REENTRANT(jsReentLock,
  4525. BOOL setLength = JavascriptOperators::SetProperty(obj, obj, PropertyIds::length, big.ToNumber(scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  4526. if (h.IsThrowTypeError(setLength))
  4527. {
  4528. if(scriptContext->GetThreadContext()->RecordImplicitException())
  4529. {
  4530. h.ThrowTypeErrorOnFailure();
  4531. }
  4532. else
  4533. {
  4534. return nullptr;
  4535. }
  4536. }
  4537. return big.ToNumber(scriptContext);
  4538. }
  4539. else
  4540. {
  4541. // Set the new length
  4542. Var lengthAsNUmberVar = JavascriptNumber::ToVar(n.IsSmallIndex() ? n.GetSmallIndex() : n.GetBigIndex(), scriptContext);
  4543. JS_REENTRANT(jsReentLock,
  4544. BOOL setLength = JavascriptOperators::SetProperty(obj, obj, PropertyIds::length, lengthAsNUmberVar, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  4545. if (h.IsThrowTypeError(setLength))
  4546. {
  4547. if(scriptContext->GetThreadContext()->RecordImplicitException())
  4548. {
  4549. h.ThrowTypeErrorOnFailure();
  4550. }
  4551. else
  4552. {
  4553. return nullptr;
  4554. }
  4555. }
  4556. return lengthAsNUmberVar;
  4557. }
  4558. }
  4559. /*
  4560. * JavascriptArray::EntryPushJavascriptArray
  4561. * Pushes Var element in a Var Array.
  4562. * Returns the length of the array.
  4563. */
  4564. Var JavascriptArray::EntryPushJavascriptArray(ScriptContext * scriptContext, Var * args, uint argCount)
  4565. {
  4566. JavascriptArray * arr = JavascriptArray::FromAnyArray(args[0]);
  4567. uint n = arr->length;
  4568. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.push"));
  4569. // Fast Path for one push for small indexes
  4570. if (argCount == 2 && n < JavascriptArray::MaxArrayLength)
  4571. {
  4572. // Set Item is overridden by CrossSiteObject, so no need to check for IsCrossSiteObject()
  4573. h.ThrowTypeErrorOnFailure(arr->SetItem(n, args[1], PropertyOperation_None));
  4574. return JavascriptNumber::ToVar(n + 1, scriptContext);
  4575. }
  4576. // Fast Path for multiple push for small indexes
  4577. if (JavascriptArray::MaxArrayLength - argCount + 1 > n && JavascriptArray::IsVarArray(arr) && scriptContext == arr->GetScriptContext())
  4578. {
  4579. uint index;
  4580. for (index = 1; index < argCount; ++index, ++n)
  4581. {
  4582. Assert(n != JavascriptArray::MaxArrayLength);
  4583. // Set Item is overridden by CrossSiteObject, so no need to check for IsCrossSiteObject()
  4584. arr->JavascriptArray::DirectSetItemAt(n, args[index]);
  4585. }
  4586. return JavascriptNumber::ToVar(n, scriptContext);
  4587. }
  4588. return EntryPushJavascriptArrayNoFastPath(scriptContext, args, argCount);
  4589. }
  4590. Var JavascriptArray::EntryPushJavascriptArrayNoFastPath(ScriptContext * scriptContext, Var * args, uint argCount)
  4591. {
  4592. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4593. JavascriptArray * arr = JavascriptArray::FromAnyArray(args[0]);
  4594. uint n = arr->length;
  4595. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.push"));
  4596. // First handle "small" indices.
  4597. uint index;
  4598. for (index = 1; index < argCount && n < JavascriptArray::MaxArrayLength; ++index, ++n)
  4599. {
  4600. // Set Item is overridden by CrossSiteObject, so no need to check for IsCrossSiteObject()
  4601. h.ThrowTypeErrorOnFailure(arr->SetItem(n, args[index], PropertyOperation_None));
  4602. }
  4603. // Use BigIndex if we need to push indices >= MaxArrayLength
  4604. if (index < argCount)
  4605. {
  4606. // Not supporting native array with BigIndex.
  4607. arr = EnsureNonNativeArray(arr);
  4608. Assert(n == JavascriptArray::MaxArrayLength);
  4609. for (BigIndex big = n; index < argCount; ++index, ++big)
  4610. {
  4611. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(big.SetItem(arr, args[index])));
  4612. }
  4613. #ifdef VALIDATE_ARRAY
  4614. arr->ValidateArray();
  4615. #endif
  4616. // This is where we should set the length, but for arrays it cannot be >= MaxArrayLength
  4617. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  4618. }
  4619. #ifdef VALIDATE_ARRAY
  4620. arr->ValidateArray();
  4621. #endif
  4622. return JavascriptNumber::ToVar(n, scriptContext);
  4623. }
  4624. /*
  4625. * JavascriptArray::EntryPush
  4626. * Handles Push calls(Script Function)
  4627. */
  4628. Var JavascriptArray::EntryPush(RecyclableObject* function, CallInfo callInfo, ...)
  4629. {
  4630. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  4631. ARGUMENTS(args, callInfo);
  4632. ScriptContext* scriptContext = function->GetScriptContext();
  4633. Assert(!(callInfo.Flags & CallFlags_New));
  4634. if (args.Info.Count == 0)
  4635. {
  4636. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.push"));
  4637. }
  4638. if (JavascriptArray::Is(args[0]))
  4639. {
  4640. return EntryPushJavascriptArray(scriptContext, args.Values, args.Info.Count);
  4641. }
  4642. else
  4643. {
  4644. return EntryPushNonJavascriptArray(scriptContext, args.Values, args.Info.Count);
  4645. }
  4646. }
  4647. template <typename T>
  4648. void JavascriptArray::CopyHeadIfInlinedHeadSegment(JavascriptArray *array, Recycler *recycler)
  4649. {
  4650. if (JavascriptArray::IsInlineSegment(array->head, array))
  4651. {
  4652. AnalysisAssert(array->head);
  4653. SparseArraySegment<T>* newHeadSeg = array->ReallocNonLeafSegment((SparseArraySegment<T>*)PointerValue(array->head), array->head->next);
  4654. array->head = newHeadSeg;
  4655. }
  4656. }
  4657. template <typename T>
  4658. void JavascriptArray::ReallocateNonLeafLastSegmentIfLeaf(JavascriptArray * arr, Recycler * recycler)
  4659. {
  4660. 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.
  4661. // TODO: Consider utilizing lastUsedSegment once we fix CopyHeadIfInlinedHeadSegment in that respect.
  4662. SparseArraySegmentBase *lastSeg = nullptr;
  4663. SparseArraySegmentBase *seg = arr->head;
  4664. while (seg)
  4665. {
  4666. lastSeg = seg;
  4667. seg = seg->next;
  4668. }
  4669. if (SparseArraySegmentBase::IsLeafSegment(lastSeg, recycler))
  4670. {
  4671. AnalysisAssert(lastSeg);
  4672. arr->ReallocNonLeafSegment((SparseArraySegment<T>*)lastSeg, lastSeg->next, true /*forceNonLeaf*/);
  4673. }
  4674. }
  4675. Var JavascriptArray::EntryReverse(RecyclableObject* function, CallInfo callInfo, ...)
  4676. {
  4677. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  4678. ARGUMENTS(args, callInfo);
  4679. ScriptContext* scriptContext = function->GetScriptContext();
  4680. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4681. Assert(!(callInfo.Flags & CallFlags_New));
  4682. if (args.Info.Count == 0)
  4683. {
  4684. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reverse"));
  4685. }
  4686. BigIndex length = 0u;
  4687. JavascriptArray* pArr = nullptr;
  4688. RecyclableObject* obj = nullptr;
  4689. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.reverse"), &pArr, &obj, &length));
  4690. if (length.IsSmallIndex())
  4691. {
  4692. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReverseHelper(pArr, nullptr, obj, length.GetSmallIndex(), scriptContext));
  4693. }
  4694. 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
  4695. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReverseHelper(pArr, nullptr, obj, length.GetBigIndex(), scriptContext));
  4696. }
  4697. bool JavascriptArray::HasAnyES5ArrayInPrototypeChain(JavascriptArray *arr, bool forceCheckProtoChain)
  4698. {
  4699. Assert(arr != nullptr);
  4700. #if ENABLE_COPYONACCESS_ARRAY
  4701. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(arr);
  4702. #endif
  4703. bool hasAnyES5Array = false;
  4704. // If there is no gap (unless forced) we are not filling from the prototype - so no point checking for ES5Array.
  4705. if (forceCheckProtoChain || arr->IsFillFromPrototypes())
  4706. {
  4707. RecyclableObject* prototype = arr->GetPrototype();
  4708. while (JavascriptOperators::GetTypeId(prototype) != TypeIds_Null)
  4709. {
  4710. RecyclableObject* protoObj = prototype;
  4711. if (!(DynamicObject::IsAnyArray(protoObj) || JavascriptOperators::IsObject(protoObj))
  4712. || JavascriptProxy::Is(protoObj)
  4713. || protoObj->IsExternal())
  4714. {
  4715. hasAnyES5Array = true;
  4716. break;
  4717. }
  4718. if (DynamicObject::IsAnyArray(protoObj))
  4719. {
  4720. if (ES5Array::Is(protoObj))
  4721. {
  4722. hasAnyES5Array = true;
  4723. break;
  4724. }
  4725. }
  4726. else if (DynamicType::Is(protoObj->GetTypeId()))
  4727. {
  4728. DynamicObject* dynobj = DynamicObject::FromVar(protoObj);
  4729. ArrayObject* objectArray = dynobj->GetObjectArray();
  4730. if (objectArray != nullptr && ES5Array::Is(objectArray))
  4731. {
  4732. hasAnyES5Array = true;
  4733. break;
  4734. }
  4735. }
  4736. prototype = prototype->GetPrototype();
  4737. }
  4738. }
  4739. return hasAnyES5Array;
  4740. }
  4741. // Array.prototype.reverse as described in ES6.0 (draft 22) Section 22.1.3.20
  4742. template <typename T>
  4743. Var JavascriptArray::ReverseHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, ScriptContext* scriptContext)
  4744. {
  4745. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4746. T middle = length / 2;
  4747. Var lowerValue = nullptr, upperValue = nullptr;
  4748. T lowerExists, upperExists;
  4749. const char16* methodName;
  4750. bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
  4751. if (isTypedArrayEntryPoint)
  4752. {
  4753. methodName = _u("[TypedArray].prototype.reverse");
  4754. }
  4755. else
  4756. {
  4757. methodName = _u("Array.prototype.reverse");
  4758. }
  4759. // If we came from Array.prototype.map and source object is not a JavascriptArray, source could be a TypedArray
  4760. if (!isTypedArrayEntryPoint && pArr == nullptr && TypedArrayBase::Is(obj))
  4761. {
  4762. typedArrayBase = TypedArrayBase::FromVar(obj);
  4763. }
  4764. ThrowTypeErrorOnFailureHelper h(scriptContext, methodName);
  4765. bool useNoSideEffectReverse = pArr != nullptr && !HasAnyES5ArrayInPrototypeChain(pArr);
  4766. if (useNoSideEffectReverse)
  4767. {
  4768. Recycler * recycler = scriptContext->GetRecycler();
  4769. if (length <= 1)
  4770. {
  4771. return pArr;
  4772. }
  4773. if (pArr->IsFillFromPrototypes())
  4774. {
  4775. // For odd-length arrays, the middle element is unchanged,
  4776. // so we cannot fill it from the prototypes.
  4777. if (length % 2 == 0)
  4778. {
  4779. JS_REENTRANT(jsReentLock, pArr->FillFromPrototypes(0, (uint32)length));
  4780. }
  4781. else
  4782. {
  4783. middle = length / 2;
  4784. JS_REENTRANT(jsReentLock,
  4785. pArr->FillFromPrototypes(0, (uint32)middle),
  4786. pArr->FillFromPrototypes(1 + (uint32)middle, (uint32)length));
  4787. }
  4788. }
  4789. // As we have already established that the FillFromPrototype should not change the bound of the array.
  4790. if (length != (T)pArr->length)
  4791. {
  4792. Js::Throw::FatalInternalError();
  4793. }
  4794. if (pArr->HasNoMissingValues() && pArr->head && pArr->head->next)
  4795. {
  4796. // This function currently does not track missing values in the head segment if there are multiple segments
  4797. pArr->SetHasNoMissingValues(false);
  4798. }
  4799. // Above FillFromPrototypes call can change the length of the array. Our segment calculation below will
  4800. // not work with the stale length. Update the length.
  4801. // Note : since we are reversing the whole segment below - the functionality is not spec compliant already.
  4802. length = pArr->length;
  4803. SparseArraySegmentBase *prevSeg = nullptr;
  4804. SparseArraySegmentBase *nextSeg = nullptr;
  4805. SparseArraySegmentBase *pinPrevSeg = nullptr;
  4806. bool isIntArray = false;
  4807. bool isFloatArray = false;
  4808. pArr->ClearSegmentMap(); // Just dump the segment map on reverse
  4809. if (JavascriptNativeIntArray::Is(pArr))
  4810. {
  4811. isIntArray = true;
  4812. }
  4813. else if (JavascriptNativeFloatArray::Is(pArr))
  4814. {
  4815. isFloatArray = true;
  4816. }
  4817. // During the loop below we are going to reverse the segments list. The head segment will become the last segment.
  4818. // We have to verify that the current head segment is not the inilined segement, otherwise due to shuffling below (of EnsureHeadStartsFromZero call below), the inlined segment will no longer
  4819. // be the head and that can create issue down the line. Create new segment if it is an inilined segment.
  4820. if (pArr->head && (pArr->head->next || (pArr->head->left + pArr->head->length) < length))
  4821. {
  4822. if (isIntArray)
  4823. {
  4824. CopyHeadIfInlinedHeadSegment<int32>(pArr, recycler);
  4825. if (pArr->head->next)
  4826. {
  4827. ReallocateNonLeafLastSegmentIfLeaf<int32>(pArr, recycler);
  4828. }
  4829. }
  4830. else if (isFloatArray)
  4831. {
  4832. CopyHeadIfInlinedHeadSegment<double>(pArr, recycler);
  4833. if (pArr->head->next)
  4834. {
  4835. ReallocateNonLeafLastSegmentIfLeaf<double>(pArr, recycler);
  4836. }
  4837. }
  4838. else
  4839. {
  4840. CopyHeadIfInlinedHeadSegment<Var>(pArr, recycler);
  4841. }
  4842. }
  4843. SparseArraySegmentBase* seg = pArr->head;
  4844. while (seg)
  4845. {
  4846. nextSeg = seg->next;
  4847. // If seg.length == 0, it is possible that (seg.left + seg.length == prev.left + prev.length),
  4848. // resulting in 2 segments sharing the same "left".
  4849. if (seg->length > 0)
  4850. {
  4851. if (isIntArray)
  4852. {
  4853. ((SparseArraySegment<int32>*)seg)->ReverseSegment(recycler);
  4854. }
  4855. else if (isFloatArray)
  4856. {
  4857. ((SparseArraySegment<double>*)seg)->ReverseSegment(recycler);
  4858. }
  4859. else
  4860. {
  4861. ((SparseArraySegment<Var>*)seg)->ReverseSegment(recycler);
  4862. }
  4863. seg->left = ((uint32)length) > (seg->left + seg->length) ? ((uint32)length) - (seg->left + seg->length) : 0;
  4864. seg->next = prevSeg;
  4865. // Make sure size doesn't overlap with next segment.
  4866. // An easy fix is to just truncate the size...
  4867. seg->EnsureSizeInBound();
  4868. // If the last segment is a leaf, then we may be losing our last scanned pointer to its previous
  4869. // segment. Hold onto it with pinPrevSeg until we reallocate below.
  4870. pinPrevSeg = prevSeg;
  4871. prevSeg = seg;
  4872. }
  4873. seg = nextSeg;
  4874. }
  4875. pArr->head = prevSeg;
  4876. if (isIntArray)
  4877. {
  4878. pArr->EnsureHeadStartsFromZero<int32>(recycler);
  4879. }
  4880. else if (isFloatArray)
  4881. {
  4882. pArr->EnsureHeadStartsFromZero<double>(recycler);
  4883. }
  4884. else
  4885. {
  4886. pArr->EnsureHeadStartsFromZero<Var>(recycler);
  4887. }
  4888. pArr->InvalidateLastUsedSegment(); // lastUsedSegment might be 0-length and discarded above
  4889. #ifdef VALIDATE_ARRAY
  4890. pArr->ValidateArray();
  4891. #endif
  4892. }
  4893. else if (typedArrayBase)
  4894. {
  4895. Assert(length <= JavascriptArray::MaxArrayLength);
  4896. if (typedArrayBase->GetLength() == length)
  4897. {
  4898. // If typedArrayBase->length == length then we know that the TypedArray will have all items < length
  4899. // and we won't have to check that the elements exist or not.
  4900. for (uint32 lower = 0; lower < (uint32)middle; lower++)
  4901. {
  4902. uint32 upper = (uint32)length - lower - 1;
  4903. lowerValue = typedArrayBase->DirectGetItem(lower);
  4904. upperValue = typedArrayBase->DirectGetItem(upper);
  4905. // We still have to call HasItem even though we know the TypedArray has both lower and upper because
  4906. // there may be a proxy handler trapping HasProperty.
  4907. lowerExists = typedArrayBase->HasItem(lower);
  4908. upperExists = typedArrayBase->HasItem(upper);
  4909. JS_REENTRANT(jsReentLock,
  4910. h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(lower, upperValue)),
  4911. h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(upper, lowerValue)));
  4912. }
  4913. }
  4914. else
  4915. {
  4916. Assert(middle <= UINT_MAX);
  4917. for (uint32 lower = 0; lower < (uint32)middle; lower++)
  4918. {
  4919. uint32 upper = (uint32)length - lower - 1;
  4920. lowerValue = typedArrayBase->DirectGetItem(lower);
  4921. upperValue = typedArrayBase->DirectGetItem(upper);
  4922. lowerExists = typedArrayBase->HasItem(lower);
  4923. upperExists = typedArrayBase->HasItem(upper);
  4924. if (lowerExists)
  4925. {
  4926. if (upperExists)
  4927. {
  4928. JS_REENTRANT(jsReentLock,
  4929. h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(lower, upperValue)),
  4930. h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(upper, lowerValue)));
  4931. }
  4932. else
  4933. {
  4934. // This will always fail for a TypedArray if lower < length
  4935. h.ThrowTypeErrorOnFailure(typedArrayBase->DeleteItem(lower, PropertyOperation_ThrowOnDeleteIfNotConfig));
  4936. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(upper, lowerValue)));
  4937. }
  4938. }
  4939. else
  4940. {
  4941. if (upperExists)
  4942. {
  4943. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(lower, upperValue)));
  4944. // This will always fail for a TypedArray if upper < length
  4945. h.ThrowTypeErrorOnFailure(typedArrayBase->DeleteItem(upper, PropertyOperation_ThrowOnDeleteIfNotConfig));
  4946. }
  4947. }
  4948. }
  4949. }
  4950. }
  4951. else
  4952. {
  4953. for (T lower = 0; lower < middle; lower++)
  4954. {
  4955. T upper = length - lower - 1;
  4956. JS_REENTRANT(jsReentLock,
  4957. lowerExists = JavascriptOperators::HasItem(obj, lower) && JavascriptOperators::GetItem(obj, lower, &lowerValue, scriptContext),
  4958. upperExists = JavascriptOperators::HasItem(obj, upper) && JavascriptOperators::GetItem(obj, upper, &upperValue, scriptContext));
  4959. if (lowerExists)
  4960. {
  4961. if (upperExists)
  4962. {
  4963. JS_REENTRANT(jsReentLock,
  4964. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, lower, upperValue, scriptContext, PropertyOperation_ThrowIfNotExtensible)),
  4965. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, upper, lowerValue, scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  4966. }
  4967. else
  4968. {
  4969. JS_REENTRANT(jsReentLock,
  4970. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(obj, lower, PropertyOperation_ThrowOnDeleteIfNotConfig)),
  4971. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, upper, lowerValue, scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  4972. }
  4973. }
  4974. else
  4975. {
  4976. if (upperExists)
  4977. {
  4978. JS_REENTRANT(jsReentLock,
  4979. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, lower, upperValue, scriptContext, PropertyOperation_ThrowIfNotExtensible)),
  4980. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(obj, upper, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  4981. }
  4982. }
  4983. }
  4984. }
  4985. return obj;
  4986. }
  4987. template<typename T>
  4988. void JavascriptArray::ShiftHelper(JavascriptArray* pArr, ScriptContext * scriptContext)
  4989. {
  4990. Recycler * recycler = scriptContext->GetRecycler();
  4991. SparseArraySegment<T>* next = SparseArraySegment<T>::From(pArr->head->next);
  4992. while (next)
  4993. {
  4994. next->left--;
  4995. next = SparseArraySegment<T>::From(next->next);
  4996. }
  4997. // head and next might overlap as the next segment left is decremented
  4998. next = SparseArraySegment<T>::From(pArr->head->next);
  4999. if (next && (pArr->head->size > next->left))
  5000. {
  5001. AssertMsg(pArr->head->left == 0, "Array always points to a head starting at index 0");
  5002. AssertMsg(pArr->head->size == next->left + 1, "Shift next->left overlaps current segment by more than 1 element");
  5003. SparseArraySegment<T> *head = SparseArraySegment<T>::From(pArr->head);
  5004. SparseArraySegment<T> *oldHead = head;
  5005. bool isInlineSegment = JavascriptArray::IsInlineSegment(head, pArr);
  5006. bool nextIsInlineSegment = JavascriptArray::IsInlineSegment(next, pArr);
  5007. // Merge the two adjacent segments
  5008. if (next->length != 0)
  5009. {
  5010. uint32 offset = head->size - 1;
  5011. // There is room for one unshifted element in head segment.
  5012. // Hence it's enough if we grow the head segment by next->length - 1
  5013. if (next->next)
  5014. {
  5015. // If we have a next->next, we can't grow pass the left of that
  5016. // If the array had a segment map before, the next->next might just be right after next as well.
  5017. // So we just need to grow to the end of the next segment
  5018. // TODO: merge that segment too?
  5019. Assert(next->next->left >= head->size);
  5020. uint32 maxGrowSize = next->next->left - head->size;
  5021. if (maxGrowSize != 0)
  5022. {
  5023. head = head->GrowByMinMax(recycler, next->length - 1, maxGrowSize); //-1 is to account for unshift
  5024. }
  5025. else
  5026. {
  5027. // The next segment is only of length one, so we already have space in the header to copy that
  5028. Assert(next->length == 1);
  5029. }
  5030. }
  5031. else
  5032. {
  5033. head = head->GrowByMin(recycler, next->length - 1); //-1 is to account for unshift
  5034. }
  5035. MoveArray(head->elements + offset, next->elements, next->length);
  5036. head->length = offset + next->length;
  5037. head->CheckLengthvsSize();
  5038. pArr->head = head;
  5039. if (isInlineSegment && oldHead != head)
  5040. {
  5041. pArr->ClearElements(oldHead, 0);
  5042. }
  5043. }
  5044. head->next = next->next;
  5045. if (nextIsInlineSegment)
  5046. {
  5047. pArr->ClearElements(next, 0);
  5048. }
  5049. pArr->InvalidateLastUsedSegment();
  5050. }
  5051. #ifdef VALIDATE_ARRAY
  5052. pArr->ValidateArray();
  5053. #endif
  5054. }
  5055. Var JavascriptArray::EntryShift(RecyclableObject* function, CallInfo callInfo, ...)
  5056. {
  5057. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  5058. ARGUMENTS(args, callInfo);
  5059. ScriptContext* scriptContext = function->GetScriptContext();
  5060. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  5061. Assert(!(callInfo.Flags & CallFlags_New));
  5062. Var res = scriptContext->GetLibrary()->GetUndefined();
  5063. if (args.Info.Count == 0)
  5064. {
  5065. return res;
  5066. }
  5067. bool useNoSideEffectShift = JavascriptArray::Is(args[0])
  5068. && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject()
  5069. && !HasAnyES5ArrayInPrototypeChain(JavascriptArray::FromVar(args[0]));
  5070. if (useNoSideEffectShift)
  5071. {
  5072. JavascriptArray * pArr = JavascriptArray::FromVar(args[0]);
  5073. if (pArr->length == 0)
  5074. {
  5075. return res;
  5076. }
  5077. uint32 length = pArr->length;
  5078. if(pArr->IsFillFromPrototypes())
  5079. {
  5080. JS_REENTRANT(jsReentLock, pArr->FillFromPrototypes(0, pArr->length)); // We need find all missing value from [[proto]] object
  5081. }
  5082. // As we have already established that the FillFromPrototype should not change the bound of the array.
  5083. if (length != pArr->length)
  5084. {
  5085. Js::Throw::FatalInternalError();
  5086. }
  5087. if(pArr->HasNoMissingValues() && pArr->head && pArr->head->next)
  5088. {
  5089. // This function currently does not track missing values in the head segment if there are multiple segments
  5090. pArr->SetHasNoMissingValues(false);
  5091. }
  5092. pArr->length--;
  5093. pArr->ClearSegmentMap(); // Dump segmentMap on shift (before any allocation)
  5094. Recycler * recycler = scriptContext->GetRecycler();
  5095. bool isIntArray = false;
  5096. bool isFloatArray = false;
  5097. if(JavascriptNativeIntArray::Is(pArr))
  5098. {
  5099. isIntArray = true;
  5100. }
  5101. else if(JavascriptNativeFloatArray::Is(pArr))
  5102. {
  5103. isFloatArray = true;
  5104. }
  5105. if (pArr->head->length != 0)
  5106. {
  5107. if(isIntArray)
  5108. {
  5109. int32 nativeResult = SparseArraySegment<int32>::From(pArr->head)->GetElement(0);
  5110. if(SparseArraySegment<int32>::IsMissingItem(&nativeResult))
  5111. {
  5112. res = scriptContext->GetLibrary()->GetUndefined();
  5113. }
  5114. else
  5115. {
  5116. res = Js::JavascriptNumber::ToVar(nativeResult, scriptContext);
  5117. }
  5118. SparseArraySegment<int32>::From(pArr->head)->RemoveElement(recycler, 0);
  5119. }
  5120. else if (isFloatArray)
  5121. {
  5122. double nativeResult = SparseArraySegment<double>::From(pArr->head)->GetElement(0);
  5123. if(SparseArraySegment<double>::IsMissingItem(&nativeResult))
  5124. {
  5125. res = scriptContext->GetLibrary()->GetUndefined();
  5126. }
  5127. else
  5128. {
  5129. res = Js::JavascriptNumber::ToVarNoCheck(nativeResult, scriptContext);
  5130. }
  5131. SparseArraySegment<double>::From(pArr->head)->RemoveElement(recycler, 0);
  5132. }
  5133. else
  5134. {
  5135. res = SparseArraySegment<Var>::From(pArr->head)->GetElement(0);
  5136. if(SparseArraySegment<Var>::IsMissingItem(&res))
  5137. {
  5138. res = scriptContext->GetLibrary()->GetUndefined();
  5139. }
  5140. else
  5141. {
  5142. res = CrossSite::MarshalVar(scriptContext, res);
  5143. }
  5144. SparseArraySegment<Var>::From(pArr->head)->RemoveElement(recycler, 0);
  5145. }
  5146. }
  5147. if(isIntArray)
  5148. {
  5149. ShiftHelper<int32>(pArr, scriptContext);
  5150. }
  5151. else if (isFloatArray)
  5152. {
  5153. ShiftHelper<double>(pArr, scriptContext);
  5154. }
  5155. else
  5156. {
  5157. ShiftHelper<Var>(pArr, scriptContext);
  5158. }
  5159. }
  5160. else
  5161. {
  5162. RecyclableObject* dynamicObject = nullptr;
  5163. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &dynamicObject))
  5164. {
  5165. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.shift"));
  5166. }
  5167. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.shift"));
  5168. JS_REENTRANT(jsReentLock, BigIndex length = OP_GetLength(dynamicObject, scriptContext));
  5169. if (length == 0u)
  5170. {
  5171. // If length is 0, return 'undefined'
  5172. JS_REENTRANT(jsReentLock,
  5173. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, TaggedInt::ToVarUnchecked(0), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  5174. return scriptContext->GetLibrary()->GetUndefined();
  5175. }
  5176. JS_REENTRANT(jsReentLock,
  5177. BOOL gotItem = JavascriptOperators::GetItem(dynamicObject, 0u, &res, scriptContext));
  5178. if (!gotItem)
  5179. {
  5180. res = scriptContext->GetLibrary()->GetUndefined();
  5181. }
  5182. --length;
  5183. uint32 lengthToUin32Max = length.IsSmallIndex() ? length.GetSmallIndex() : MaxArrayLength;
  5184. for (uint32 i = 0u; i < lengthToUin32Max; i++)
  5185. {
  5186. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(dynamicObject, i + 1));
  5187. if (hasItem)
  5188. {
  5189. Var element = nullptr;
  5190. JS_REENTRANT(jsReentLock,
  5191. element = JavascriptOperators::GetItem(dynamicObject, i + 1, scriptContext),
  5192. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(dynamicObject, dynamicObject, i, element, scriptContext, PropertyOperation_ThrowIfNotExtensible, /*skipPrototypeCheck*/ true)));
  5193. }
  5194. else
  5195. {
  5196. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, i, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  5197. }
  5198. }
  5199. for (uint64 i = MaxArrayLength; length > i; i++)
  5200. {
  5201. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(dynamicObject, i + 1));
  5202. if (hasItem)
  5203. {
  5204. Var element = nullptr;
  5205. JS_REENTRANT(jsReentLock,
  5206. element = JavascriptOperators::GetItem(dynamicObject, i + 1, scriptContext),
  5207. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(dynamicObject, dynamicObject, i, element, scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  5208. }
  5209. else
  5210. {
  5211. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, i, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  5212. }
  5213. }
  5214. if (length.IsSmallIndex())
  5215. {
  5216. JS_REENTRANT(jsReentLock,
  5217. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, length.GetSmallIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig)),
  5218. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(length.GetSmallIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  5219. }
  5220. else
  5221. {
  5222. JS_REENTRANT(jsReentLock,
  5223. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, length.GetBigIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig)),
  5224. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(length.GetBigIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  5225. }
  5226. }
  5227. return res;
  5228. }
  5229. Js::JavascriptArray* JavascriptArray::CreateNewArrayHelper(uint32 len, bool isIntArray, bool isFloatArray, Js::JavascriptArray* baseArray, ScriptContext* scriptContext)
  5230. {
  5231. if (isIntArray)
  5232. {
  5233. Js::JavascriptNativeIntArray *pnewArr = scriptContext->GetLibrary()->CreateNativeIntArray(len);
  5234. pnewArr->EnsureHead<int32>();
  5235. #if ENABLE_PROFILE_INFO
  5236. pnewArr->CopyArrayProfileInfo(Js::JavascriptNativeIntArray::FromVar(baseArray));
  5237. #endif
  5238. return pnewArr;
  5239. }
  5240. else if (isFloatArray)
  5241. {
  5242. Js::JavascriptNativeFloatArray *pnewArr = scriptContext->GetLibrary()->CreateNativeFloatArray(len);
  5243. pnewArr->EnsureHead<double>();
  5244. #if ENABLE_PROFILE_INFO
  5245. pnewArr->CopyArrayProfileInfo(Js::JavascriptNativeFloatArray::FromVar(baseArray));
  5246. #endif
  5247. return pnewArr;
  5248. }
  5249. else
  5250. {
  5251. JavascriptArray *pnewArr = pnewArr = scriptContext->GetLibrary()->CreateArray(len);
  5252. pnewArr->EnsureHead<Var>();
  5253. return pnewArr;
  5254. }
  5255. }
  5256. template<typename T>
  5257. void JavascriptArray::SliceHelper(JavascriptArray* pArr, JavascriptArray* pnewArr, uint32 start, uint32 newLen)
  5258. {
  5259. JS_REENTRANCY_LOCK(jsReentLock, pArr->GetScriptContext()->GetThreadContext());
  5260. SparseArraySegment<T>* headSeg = SparseArraySegment<T>::From(pArr->head);
  5261. SparseArraySegment<T>* pnewHeadSeg = SparseArraySegment<T>::From(pnewArr->head);
  5262. // Fill the newly created sliced array
  5263. CopyArray(pnewHeadSeg->elements, newLen, headSeg->elements + start, newLen);
  5264. pnewHeadSeg->length = newLen;
  5265. pnewHeadSeg->CheckLengthvsSize();
  5266. Assert(pnewHeadSeg->length <= pnewHeadSeg->size);
  5267. // Prototype lookup for missing elements
  5268. if (!pArr->HasNoMissingValues())
  5269. {
  5270. for (uint32 i = 0; i < newLen && (i + start) < pArr->length; i++)
  5271. {
  5272. // array type might be changed in the below call to DirectGetItemAtFull
  5273. // need recheck array type before checking array item [i + start]
  5274. if (pArr->IsMissingItem(i + start))
  5275. {
  5276. Var element = nullptr;
  5277. pnewArr->SetHasNoMissingValues(false);
  5278. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(i + start, &element));
  5279. if (gotItem)
  5280. {
  5281. JS_REENTRANT(jsReentLock, pnewArr->SetItem(i, element, PropertyOperation_None));
  5282. }
  5283. }
  5284. }
  5285. }
  5286. #ifdef DBG
  5287. else
  5288. {
  5289. for (uint32 i = 0; i < newLen; i++)
  5290. {
  5291. AssertMsg(!SparseArraySegment<T>::IsMissingItem(&headSeg->elements[i+start]), "Array marked incorrectly as having missing value");
  5292. }
  5293. }
  5294. #endif
  5295. }
  5296. // If the creating profile data has changed, convert it to the type of array indicated
  5297. // in the profile
  5298. void JavascriptArray::GetArrayTypeAndConvert(bool* isIntArray, bool* isFloatArray)
  5299. {
  5300. if (JavascriptNativeIntArray::Is(this))
  5301. {
  5302. #if ENABLE_PROFILE_INFO
  5303. JavascriptNativeIntArray* nativeIntArray = JavascriptNativeIntArray::FromVar(this);
  5304. ArrayCallSiteInfo* info = nativeIntArray->GetArrayCallSiteInfo();
  5305. if(!info || info->IsNativeIntArray())
  5306. {
  5307. *isIntArray = true;
  5308. }
  5309. else if(info->IsNativeFloatArray())
  5310. {
  5311. JavascriptNativeIntArray::ToNativeFloatArray(nativeIntArray);
  5312. *isFloatArray = true;
  5313. }
  5314. else
  5315. {
  5316. JavascriptNativeIntArray::ToVarArray(nativeIntArray);
  5317. }
  5318. #else
  5319. *isIntArray = true;
  5320. #endif
  5321. }
  5322. else if (JavascriptNativeFloatArray::Is(this))
  5323. {
  5324. #if ENABLE_PROFILE_INFO
  5325. JavascriptNativeFloatArray* nativeFloatArray = JavascriptNativeFloatArray::FromVar(this);
  5326. ArrayCallSiteInfo* info = nativeFloatArray->GetArrayCallSiteInfo();
  5327. if(info && !info->IsNativeArray())
  5328. {
  5329. JavascriptNativeFloatArray::ToVarArray(nativeFloatArray);
  5330. }
  5331. else
  5332. {
  5333. *isFloatArray = true;
  5334. }
  5335. #else
  5336. *isFloatArray = true;
  5337. #endif
  5338. }
  5339. }
  5340. Var JavascriptArray::EntrySlice(RecyclableObject* function, CallInfo callInfo, ...)
  5341. {
  5342. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  5343. ARGUMENTS(args, callInfo);
  5344. ScriptContext* scriptContext = function->GetScriptContext();
  5345. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  5346. Assert(!(callInfo.Flags & CallFlags_New));
  5347. Var res = scriptContext->GetLibrary()->GetUndefined();
  5348. if (args.Info.Count == 0)
  5349. {
  5350. return res;
  5351. }
  5352. BigIndex length;
  5353. JavascriptArray* pArr = nullptr;
  5354. RecyclableObject* obj = nullptr;
  5355. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.slice"), &pArr, &obj, &length));
  5356. if (length.IsSmallIndex())
  5357. {
  5358. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  5359. }
  5360. Assert(pArr == nullptr || length.IsUint32Max());
  5361. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  5362. }
  5363. // Array.prototype.slice as described in ES6.0 (draft 22) Section 22.1.3.22
  5364. template <typename T>
  5365. Var JavascriptArray::SliceHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  5366. {
  5367. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  5368. JavascriptArray* newArr = nullptr;
  5369. RecyclableObject* newObj = nullptr;
  5370. bool isIntArray = false;
  5371. bool isFloatArray = false;
  5372. bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
  5373. bool isBuiltinArrayCtor = true;
  5374. T startT = 0;
  5375. T newLenT = length;
  5376. T endT = length;
  5377. #if ENABLE_COPYONACCESS_ARRAY
  5378. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pArr);
  5379. #endif
  5380. if (args.Info.Count > 1)
  5381. {
  5382. JS_REENTRANT(jsReentLock, startT = GetFromIndex(args[1], length, scriptContext));
  5383. if (args.Info.Count > 2 && JavascriptOperators::GetTypeId(args[2]) != TypeIds_Undefined)
  5384. {
  5385. JS_REENTRANT(jsReentLock, endT = GetFromIndex(args[2], length, scriptContext));
  5386. }
  5387. newLenT = endT > startT ? endT - startT : 0;
  5388. }
  5389. // 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.
  5390. if (pArr && !JavascriptArray::Is(obj))
  5391. {
  5392. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  5393. pArr = nullptr;
  5394. }
  5395. if (TypedArrayBase::IsDetachedTypedArray(obj))
  5396. {
  5397. JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("Array.prototype.slice"));
  5398. }
  5399. // If we came from Array.prototype.slice and source object is not a JavascriptArray, source could be a TypedArray
  5400. if (!isTypedArrayEntryPoint && pArr == nullptr && TypedArrayBase::Is(obj))
  5401. {
  5402. typedArrayBase = TypedArrayBase::FromVar(obj);
  5403. }
  5404. // 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
  5405. // and use it to construct the return object.
  5406. if (isTypedArrayEntryPoint)
  5407. {
  5408. JS_REENTRANT(jsReentLock,
  5409. Var constructor = JavascriptOperators::SpeciesConstructor(typedArrayBase, TypedArrayBase::GetDefaultConstructor(args[0], scriptContext), scriptContext));
  5410. isBuiltinArrayCtor = false;
  5411. AssertAndFailFast(pArr == nullptr);
  5412. Assert(JavascriptOperators::IsConstructor(constructor));
  5413. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(newLenT, scriptContext) };
  5414. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  5415. JS_REENTRANT(jsReentLock, newObj = RecyclableObject::FromVar(TypedArrayBase::TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), (uint32)newLenT, scriptContext)));
  5416. }
  5417. else if (pArr != nullptr)
  5418. {
  5419. JS_REENTRANT(jsReentLock, newObj = ArraySpeciesCreate(pArr, newLenT, scriptContext, &isIntArray, &isFloatArray, &isBuiltinArrayCtor));
  5420. }
  5421. // skip the typed array and "pure" array case, we still need to handle special arrays like es5array, remote array, and proxy of array.
  5422. else
  5423. {
  5424. JS_REENTRANT(jsReentLock, newObj = ArraySpeciesCreate(obj, newLenT, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor));
  5425. }
  5426. // If we didn't create a new object above we will create a new array here.
  5427. // This is the pre-ES6 behavior or the case of calling Array.prototype.slice with a constructor argument that is not a constructor function.
  5428. if (newObj == nullptr)
  5429. {
  5430. if (pArr)
  5431. {
  5432. pArr->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
  5433. }
  5434. if (newLenT > JavascriptArray::MaxArrayLength)
  5435. {
  5436. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  5437. }
  5438. newArr = CreateNewArrayHelper(static_cast<uint32>(newLenT), isIntArray, isFloatArray, pArr, scriptContext);
  5439. #if ENABLE_COPYONACCESS_ARRAY
  5440. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  5441. #endif
  5442. newObj = newArr;
  5443. }
  5444. else
  5445. {
  5446. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  5447. if (JavascriptArray::Is(newObj))
  5448. {
  5449. #if ENABLE_COPYONACCESS_ARRAY
  5450. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
  5451. #endif
  5452. newArr = JavascriptArray::FromVar(newObj);
  5453. }
  5454. }
  5455. uint32 start = (uint32) startT;
  5456. uint32 newLen = (uint32) newLenT;
  5457. // We at least have to have newObj as a valid object
  5458. Assert(newObj);
  5459. // Bail out early if the new object will have zero length.
  5460. if (newLen == 0)
  5461. {
  5462. return newObj;
  5463. }
  5464. // The ArraySpeciesCreate call above could have converted the source array into an ES5Array. If this happens
  5465. // we will process the array elements like an ES5Array.
  5466. if (pArr && !JavascriptArray::Is(obj))
  5467. {
  5468. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  5469. pArr = nullptr;
  5470. }
  5471. if (pArr)
  5472. {
  5473. if (HasAnyES5ArrayInPrototypeChain(pArr))
  5474. {
  5475. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceObjectHelper(obj, start, 0u, newArr, newObj, newLen, scriptContext));
  5476. }
  5477. // If we constructed a new Array object, we have some nice helpers here
  5478. if (newArr && isBuiltinArrayCtor)
  5479. {
  5480. if (JavascriptArray::IsDirectAccessArray(newArr))
  5481. {
  5482. if (((start + newLen) <= pArr->head->length) && newLen <= newArr->head->size) //Fast Path
  5483. {
  5484. if (isIntArray)
  5485. {
  5486. JS_REENTRANT(jsReentLock, SliceHelper<int32>(pArr, newArr, start, newLen));
  5487. }
  5488. else if (isFloatArray)
  5489. {
  5490. JS_REENTRANT(jsReentLock, SliceHelper<double>(pArr, newArr, start, newLen));
  5491. }
  5492. else
  5493. {
  5494. JS_REENTRANT(jsReentLock, SliceHelper<Var>(pArr, newArr, start, newLen));
  5495. }
  5496. }
  5497. else
  5498. {
  5499. if (isIntArray)
  5500. {
  5501. JS_REENTRANT(jsReentLock, CopyNativeIntArrayElements(JavascriptNativeIntArray::FromVar(newArr), 0, JavascriptNativeIntArray::FromVar(pArr), start, start + newLen));
  5502. }
  5503. else if (isFloatArray)
  5504. {
  5505. JS_REENTRANT(jsReentLock, CopyNativeFloatArrayElements(JavascriptNativeFloatArray::FromVar(newArr), 0, JavascriptNativeFloatArray::FromVar(pArr), start, start + newLen));
  5506. }
  5507. else
  5508. {
  5509. JS_REENTRANT(jsReentLock, CopyArrayElements(newArr, 0u, pArr, start, start + newLen));
  5510. }
  5511. }
  5512. }
  5513. else
  5514. {
  5515. AssertMsg(CONFIG_FLAG(ForceES5Array), "newArr can only be ES5Array when it is forced");
  5516. Var element = nullptr;
  5517. for (uint32 i = 0; i < newLen; i++)
  5518. {
  5519. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(i + start, &element));
  5520. if (!gotItem)
  5521. {
  5522. continue;
  5523. }
  5524. newArr->SetItem(i, element, PropertyOperation_None);
  5525. // Side-effects in the prototype lookup may have changed the source array into an ES5Array. If this happens
  5526. // we will process the rest of the array elements like an ES5Array.
  5527. if (!JavascriptArray::Is(obj))
  5528. {
  5529. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  5530. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceObjectHelper(obj, start, i + 1, newArr, newObj, newLen, scriptContext));
  5531. }
  5532. }
  5533. }
  5534. }
  5535. else
  5536. {
  5537. // The constructed object isn't an array, we'll need to use normal object manipulation
  5538. Var element = nullptr;
  5539. for (uint32 i = 0; i < newLen; i++)
  5540. {
  5541. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(i + start, &element));
  5542. if (!gotItem)
  5543. {
  5544. continue;
  5545. }
  5546. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i));
  5547. // Side-effects in the prototype lookup may have changed the source array into an ES5Array. If this happens
  5548. // we will process the rest of the array elements like an ES5Array.
  5549. if (!JavascriptArray::Is(obj))
  5550. {
  5551. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  5552. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceObjectHelper(obj, start, i + 1, newArr, newObj, newLen, scriptContext));
  5553. }
  5554. }
  5555. }
  5556. }
  5557. else if (typedArrayBase)
  5558. {
  5559. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  5560. // 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)
  5561. TypedArrayBase* newTypedArray = nullptr;
  5562. if (TypedArrayBase::Is(newObj))
  5563. {
  5564. newTypedArray = TypedArrayBase::FromVar(newObj);
  5565. }
  5566. else
  5567. {
  5568. AssertAndFailFast(newArr != nullptr);
  5569. }
  5570. Var element;
  5571. for (uint32 i = 0; i < newLen; i++)
  5572. {
  5573. // We only need to call HasItem in the case that we are called from Array.prototype.slice
  5574. if (!isTypedArrayEntryPoint && !typedArrayBase->HasItem(i + start))
  5575. {
  5576. continue;
  5577. }
  5578. element = typedArrayBase->DirectGetItem(i + start);
  5579. // The object we got back from the constructor might not be a TypedArray. In fact, it could be any object.
  5580. if (newTypedArray)
  5581. {
  5582. JS_REENTRANT(jsReentLock, newTypedArray->DirectSetItem(i, element));
  5583. }
  5584. else
  5585. {
  5586. newArr->SetItem(i, element, PropertyOperation_None);
  5587. }
  5588. }
  5589. }
  5590. else
  5591. {
  5592. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceObjectHelper(obj, start, 0u, newArr, newObj, newLen, scriptContext));;
  5593. }
  5594. if (!isTypedArrayEntryPoint)
  5595. {
  5596. JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(newLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible);
  5597. }
  5598. #ifdef VALIDATE_ARRAY
  5599. if (JavascriptArray::Is(newObj))
  5600. {
  5601. JavascriptArray::FromVar(newObj)->ValidateArray();
  5602. }
  5603. #endif
  5604. return newObj;
  5605. }
  5606. Var JavascriptArray::SliceObjectHelper(RecyclableObject* obj, uint32 sliceStart, uint32 start, JavascriptArray* newArr, RecyclableObject* newObj, uint32 newLen, ScriptContext* scriptContext)
  5607. {
  5608. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  5609. for (uint32 i = start; i < newLen; i++)
  5610. {
  5611. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, i + sliceStart));
  5612. if (hasItem)
  5613. {
  5614. JS_REENTRANT(jsReentLock, Var element = JavascriptOperators::GetItem(obj, i + sliceStart, scriptContext));
  5615. if (newArr != nullptr)
  5616. {
  5617. newArr->SetItem(i, element, PropertyOperation_None);
  5618. }
  5619. else
  5620. {
  5621. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i));
  5622. }
  5623. }
  5624. }
  5625. JS_REENTRANT(jsReentLock,
  5626. JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(newLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  5627. #ifdef VALIDATE_ARRAY
  5628. if (JavascriptArray::Is(newObj))
  5629. {
  5630. JavascriptArray::FromVar(newObj)->ValidateArray();
  5631. }
  5632. #endif
  5633. return newObj;
  5634. }
  5635. struct CompareVarsInfo
  5636. {
  5637. ScriptContext* scriptContext;
  5638. RecyclableObject* compFn;
  5639. };
  5640. int __cdecl compareVars(void* cvInfoV, const void* aRef, const void* bRef)
  5641. {
  5642. CompareVarsInfo* cvInfo=(CompareVarsInfo*)cvInfoV;
  5643. ScriptContext* requestContext=cvInfo->scriptContext;
  5644. RecyclableObject* compFn=cvInfo->compFn;
  5645. AssertMsg(*(Var*)aRef, "No null expected in sort");
  5646. AssertMsg(*(Var*)bRef, "No null expected in sort");
  5647. if (compFn != nullptr)
  5648. {
  5649. ScriptContext* scriptContext = compFn->GetScriptContext();
  5650. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  5651. CallFlags flags = CallFlags_Value;
  5652. Var undefined = scriptContext->GetLibrary()->GetUndefined();
  5653. Var retVal;
  5654. if (requestContext != scriptContext)
  5655. {
  5656. Var leftVar = CrossSite::MarshalVar(scriptContext, *(Var*)aRef);
  5657. Var rightVar = CrossSite::MarshalVar(scriptContext, *(Var*)bRef);
  5658. retVal = CALL_FUNCTION(scriptContext->GetThreadContext(), compFn, CallInfo(flags, 3), undefined, leftVar, rightVar);
  5659. }
  5660. else
  5661. {
  5662. retVal = CALL_FUNCTION(scriptContext->GetThreadContext(), compFn, CallInfo(flags, 3), undefined, *(Var*)aRef, *(Var*)bRef);
  5663. }
  5664. if (TaggedInt::Is(retVal))
  5665. {
  5666. return TaggedInt::ToInt32(retVal);
  5667. }
  5668. double dblResult;
  5669. if (JavascriptNumber::Is_NoTaggedIntCheck(retVal))
  5670. {
  5671. dblResult = JavascriptNumber::GetValue(retVal);
  5672. }
  5673. else
  5674. {
  5675. dblResult = JavascriptConversion::ToNumber_Full(retVal, scriptContext);
  5676. }
  5677. if (dblResult < 0)
  5678. {
  5679. return -1;
  5680. }
  5681. return (dblResult > 0) ? 1 : 0;
  5682. }
  5683. else
  5684. {
  5685. JavascriptString* pStr1 = JavascriptConversion::ToString(*(Var*)aRef, requestContext);
  5686. JavascriptString* pStr2 = JavascriptConversion::ToString(*(Var*)bRef, requestContext);
  5687. return JavascriptString::strcmp(pStr1, pStr2);
  5688. }
  5689. }
  5690. static void hybridSort(__inout_ecount(length) Field(Var) *elements, uint32 length, CompareVarsInfo* compareInfo)
  5691. {
  5692. // The cost of memory moves starts to be more expensive than additional comparer calls (given a simple comparer)
  5693. // for arrays of more than 512 elements.
  5694. if (length > 512)
  5695. {
  5696. qsort_s(elements, length, compareVars, compareInfo);
  5697. return;
  5698. }
  5699. for (int i = 1; i < (int)length; i++)
  5700. {
  5701. if (compareVars(compareInfo, elements + i, elements + i - 1) < 0) {
  5702. // binary search for the left-most element greater than value:
  5703. int first = 0;
  5704. int last = i - 1;
  5705. while (first <= last)
  5706. {
  5707. int middle = (first + last) / 2;
  5708. if (compareVars(compareInfo, elements + i, elements + middle) < 0)
  5709. {
  5710. last = middle - 1;
  5711. }
  5712. else
  5713. {
  5714. first = middle + 1;
  5715. }
  5716. }
  5717. // insert value right before first:
  5718. Var value = elements[i];
  5719. MoveArray(elements + first + 1, elements + first, (i - first));
  5720. elements[first] = value;
  5721. }
  5722. }
  5723. }
  5724. void JavascriptArray::Sort(RecyclableObject* compFn)
  5725. {
  5726. JS_REENTRANCY_LOCK(jsReentLock, this->GetScriptContext()->GetThreadContext());
  5727. if (length <= 1)
  5728. {
  5729. return;
  5730. }
  5731. this->EnsureHead<Var>();
  5732. ScriptContext* scriptContext = this->GetScriptContext();
  5733. Recycler* recycler = scriptContext->GetRecycler();
  5734. CompareVarsInfo cvInfo;
  5735. cvInfo.scriptContext = scriptContext;
  5736. cvInfo.compFn = compFn;
  5737. Assert(head != nullptr);
  5738. // Just dump the segment map on sort
  5739. ClearSegmentMap();
  5740. uint32 countUndefined = 0;
  5741. SparseArraySegment<Var>* startSeg = SparseArraySegment<Var>::From(head);
  5742. // Sort may have side effects on the array. Setting a dummy head so that original array is not affected
  5743. uint32 saveLength = length;
  5744. // that if compare function tries to modify the array it won't AV.
  5745. head = const_cast<SparseArraySegmentBase*>(EmptySegment);
  5746. SetFlags(DynamicObjectFlags::None);
  5747. this->InvalidateLastUsedSegment();
  5748. length = 0;
  5749. TryFinally([&]()
  5750. {
  5751. //The array is a continuous array if there is only one segment
  5752. if (startSeg->next == nullptr) // Single segment fast path
  5753. {
  5754. if (compFn != nullptr)
  5755. {
  5756. countUndefined = startSeg->RemoveUndefined(scriptContext);
  5757. #ifdef VALIDATE_ARRAY
  5758. ValidateSegment(startSeg);
  5759. #endif
  5760. JS_REENTRANT(jsReentLock, hybridSort(startSeg->elements, startSeg->length, &cvInfo));
  5761. startSeg->CheckLengthvsSize();
  5762. }
  5763. else
  5764. {
  5765. JS_REENTRANT(jsReentLock, countUndefined = sort(startSeg->elements, &startSeg->length, scriptContext));
  5766. }
  5767. head = startSeg;
  5768. }
  5769. else
  5770. {
  5771. SparseArraySegment<Var>* allElements = SparseArraySegment<Var>::AllocateSegment(recycler, 0, 0, nullptr);
  5772. SparseArraySegment<Var>* next = startSeg;
  5773. uint32 nextIndex = 0;
  5774. // copy all the elements to single segment
  5775. while (next)
  5776. {
  5777. countUndefined += next->RemoveUndefined(scriptContext);
  5778. if (next->length != 0)
  5779. {
  5780. allElements = SparseArraySegment<Var>::CopySegment(recycler, allElements, nextIndex, next, next->left, next->length);
  5781. }
  5782. next = SparseArraySegment<Var>::From(next->next);
  5783. nextIndex = allElements->length;
  5784. #ifdef VALIDATE_ARRAY
  5785. ValidateSegment(allElements);
  5786. #endif
  5787. }
  5788. if (compFn != nullptr)
  5789. {
  5790. JS_REENTRANT(jsReentLock, hybridSort(allElements->elements, allElements->length, &cvInfo));
  5791. }
  5792. else
  5793. {
  5794. JS_REENTRANT(jsReentLock, sort(allElements->elements, &allElements->length, scriptContext));
  5795. allElements->CheckLengthvsSize();
  5796. }
  5797. head = allElements;
  5798. head->next = nullptr;
  5799. }
  5800. },
  5801. [&](bool hasException)
  5802. {
  5803. length = saveLength;
  5804. ClearSegmentMap(); // Dump the segmentMap again in case user compare function rebuilds it
  5805. if (hasException)
  5806. {
  5807. head = startSeg;
  5808. this->InvalidateLastUsedSegment();
  5809. }
  5810. });
  5811. #if DEBUG
  5812. {
  5813. uint32 countNull = 0;
  5814. uint32 index = head->length - 1;
  5815. while (countNull < head->length)
  5816. {
  5817. if (SparseArraySegment<Var>::From(head)->elements[index] != NULL)
  5818. {
  5819. break;
  5820. }
  5821. index--;
  5822. countNull++;
  5823. }
  5824. AssertMsg(countNull == 0, "No null expected at the end");
  5825. }
  5826. #endif
  5827. if (countUndefined != 0)
  5828. {
  5829. // fill undefined at the end
  5830. uint32 newLength = head->length + countUndefined;
  5831. if (newLength > head->size)
  5832. {
  5833. SparseArraySegmentBase *oldHead = head;
  5834. bool isInlineSegment = JavascriptArray::IsInlineSegment(head, this);
  5835. head = SparseArraySegment<Var>::From(head)->GrowByMin(recycler, newLength - head->size);
  5836. if (isInlineSegment)
  5837. {
  5838. this->ClearElements(oldHead, 0);
  5839. }
  5840. }
  5841. Var undefined = scriptContext->GetLibrary()->GetUndefined();
  5842. for (uint32 i = head->length; i < newLength; i++)
  5843. {
  5844. SparseArraySegment<Var>::From(head)->elements[i] = undefined;
  5845. }
  5846. head->length = newLength;
  5847. head->CheckLengthvsSize();
  5848. }
  5849. SetHasNoMissingValues();
  5850. this->InvalidateLastUsedSegment();
  5851. #ifdef VALIDATE_ARRAY
  5852. ValidateArray();
  5853. #endif
  5854. return;
  5855. }
  5856. uint32 JavascriptArray::sort(__inout_ecount(*len) Field(Var) *orig, uint32 *len, ScriptContext *scriptContext)
  5857. {
  5858. uint32 count = 0, countUndefined = 0;
  5859. Element *elements = RecyclerNewArrayZ(scriptContext->GetRecycler(), Element, *len);
  5860. RecyclableObject *undefined = scriptContext->GetLibrary()->GetUndefined();
  5861. //
  5862. // Create the Elements array
  5863. //
  5864. for (uint32 i = 0; i < *len; ++i)
  5865. {
  5866. if (!SparseArraySegment<Var>::IsMissingItem(&orig[i]))
  5867. {
  5868. if (!JavascriptOperators::IsUndefinedObject(orig[i], undefined))
  5869. {
  5870. elements[count].Value = orig[i];
  5871. elements[count].StringValue = JavascriptConversion::ToString(orig[i], scriptContext);
  5872. count++;
  5873. }
  5874. else
  5875. {
  5876. countUndefined++;
  5877. }
  5878. }
  5879. }
  5880. if (count > 0)
  5881. {
  5882. SortElements(elements, 0, count - 1);
  5883. for (uint32 i = 0; i < count; ++i)
  5884. {
  5885. orig[i] = elements[i].Value;
  5886. }
  5887. }
  5888. for (uint32 i = count + countUndefined; i < *len; ++i)
  5889. {
  5890. orig[i] = SparseArraySegment<Var>::GetMissingItem();
  5891. }
  5892. *len = count; // set the correct length
  5893. return countUndefined;
  5894. }
  5895. int __cdecl JavascriptArray::CompareElements(void* context, const void* elem1, const void* elem2)
  5896. {
  5897. const Element* element1 = static_cast<const Element*>(elem1);
  5898. const Element* element2 = static_cast<const Element*>(elem2);
  5899. Assert(element1 != NULL);
  5900. Assert(element2 != NULL);
  5901. return JavascriptString::strcmp(element1->StringValue, element2->StringValue);
  5902. }
  5903. void JavascriptArray::SortElements(Element* elements, uint32 left, uint32 right)
  5904. {
  5905. // Note: use write barrier policy of Field(Var)
  5906. qsort_s<Element, Field(Var)>(elements, right - left + 1, CompareElements, this);
  5907. }
  5908. Var JavascriptArray::EntrySort(RecyclableObject* function, CallInfo callInfo, ...)
  5909. {
  5910. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  5911. ARGUMENTS(args, callInfo);
  5912. ScriptContext* scriptContext = function->GetScriptContext();
  5913. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  5914. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.sort"));
  5915. Assert(!(callInfo.Flags & CallFlags_New));
  5916. AssertMsg(args.Info.Count >= 1, "Should have at least one argument");
  5917. RecyclableObject* compFn = NULL;
  5918. if (args.Info.Count > 1)
  5919. {
  5920. if (JavascriptConversion::IsCallable(args[1]))
  5921. {
  5922. compFn = RecyclableObject::FromVar(args[1]);
  5923. }
  5924. else
  5925. {
  5926. TypeId typeId = JavascriptOperators::GetTypeId(args[1]);
  5927. // Use default comparer:
  5928. // - In ES5 mode if the argument is undefined.
  5929. bool useDefaultComparer = typeId == TypeIds_Undefined;
  5930. if (!useDefaultComparer)
  5931. {
  5932. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.sort"));
  5933. }
  5934. }
  5935. }
  5936. bool useNoSideEffectSort = JavascriptArray::Is(args[0])
  5937. && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject()
  5938. && !HasAnyES5ArrayInPrototypeChain(JavascriptArray::FromVar(args[0]));
  5939. if (useNoSideEffectSort)
  5940. {
  5941. JavascriptArray *arr = JavascriptArray::FromVar(args[0]);
  5942. if (arr->length <= 1)
  5943. {
  5944. return args[0];
  5945. }
  5946. uint32 length = arr->length;
  5947. if(arr->IsFillFromPrototypes())
  5948. {
  5949. JS_REENTRANT(jsReentLock, arr->FillFromPrototypes(0, arr->length)); // We need find all missing value from [[proto]] object
  5950. }
  5951. // As we have already established that the FillFromPrototype should not change the bound of the array.
  5952. if (length != arr->length)
  5953. {
  5954. Js::Throw::FatalInternalError();
  5955. }
  5956. // Maintain nativity of the array only for the following cases (To favor inplace conversions - keeps the conversion cost less):
  5957. // - int cases for X86 and
  5958. // - FloatArray for AMD64
  5959. // 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)
  5960. #if defined(_M_X64_OR_ARM64)
  5961. if(compFn && JavascriptNativeFloatArray::Is(arr))
  5962. {
  5963. arr = JavascriptNativeFloatArray::ConvertToVarArray((JavascriptNativeFloatArray*)arr);
  5964. JS_REENTRANT(jsReentLock, arr->Sort(compFn));
  5965. arr = arr->ConvertToNativeArrayInPlace<JavascriptNativeFloatArray, double>(arr);
  5966. }
  5967. else
  5968. {
  5969. EnsureNonNativeArray(arr);
  5970. JS_REENTRANT(jsReentLock, arr->Sort(compFn));
  5971. }
  5972. #else
  5973. if(compFn && JavascriptNativeIntArray::Is(arr))
  5974. {
  5975. //EnsureNonNativeArray(arr);
  5976. arr = JavascriptNativeIntArray::ConvertToVarArray((JavascriptNativeIntArray*)arr);
  5977. JS_REENTRANT(jsReentLock, arr->Sort(compFn));
  5978. arr = arr->ConvertToNativeArrayInPlace<JavascriptNativeIntArray, int32>(arr);
  5979. }
  5980. else
  5981. {
  5982. EnsureNonNativeArray(arr);
  5983. JS_REENTRANT(jsReentLock, arr->Sort(compFn));
  5984. }
  5985. #endif
  5986. }
  5987. else
  5988. {
  5989. RecyclableObject* pObj = nullptr;
  5990. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &pObj))
  5991. {
  5992. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.sort"));
  5993. }
  5994. JS_REENTRANT(jsReentLock,
  5995. uint32 len = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(pObj, scriptContext), scriptContext));
  5996. JavascriptArray* sortArray = scriptContext->GetLibrary()->CreateArray(len);
  5997. sortArray->EnsureHead<Var>();
  5998. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.sort"));
  5999. BEGIN_TEMP_ALLOCATOR(tempAlloc, scriptContext, _u("Runtime"))
  6000. {
  6001. JsUtil::List<uint32, ArenaAllocator>* indexList = JsUtil::List<uint32, ArenaAllocator>::New(tempAlloc);
  6002. for (uint32 i = 0; i < len; i++)
  6003. {
  6004. Var item = nullptr;
  6005. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(pObj, i, &item, scriptContext));
  6006. if (gotItem)
  6007. {
  6008. indexList->Add(i);
  6009. sortArray->DirectSetItemAt(i, item);
  6010. }
  6011. }
  6012. if (indexList->Count() > 0)
  6013. {
  6014. if (sortArray->length > 1)
  6015. {
  6016. JS_REENTRANT(jsReentLock, sortArray->FillFromPrototypes(0, sortArray->length)); // We need find all missing value from [[proto]] object
  6017. }
  6018. JS_REENTRANT(jsReentLock, sortArray->Sort(compFn));
  6019. uint32 removeIndex = sortArray->head->length;
  6020. for (uint32 i = 0; i < removeIndex; i++)
  6021. {
  6022. AssertMsg(!SparseArraySegment<Var>::IsMissingItem(&SparseArraySegment<Var>::From(sortArray->head)->elements[i]), "No gaps expected in sorted array");
  6023. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(pObj, pObj, i, SparseArraySegment<Var>::From(sortArray->head)->elements[i], scriptContext)));
  6024. }
  6025. for (int i = 0; i < indexList->Count(); i++)
  6026. {
  6027. uint32 value = indexList->Item(i);
  6028. if (value >= removeIndex)
  6029. {
  6030. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure((JavascriptOperators::DeleteItem(pObj, value))));
  6031. }
  6032. }
  6033. }
  6034. }
  6035. END_TEMP_ALLOCATOR(tempAlloc, scriptContext);
  6036. }
  6037. return args[0];
  6038. }
  6039. Var JavascriptArray::EntrySplice(RecyclableObject* function, CallInfo callInfo, ...)
  6040. {
  6041. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  6042. ARGUMENTS(args, callInfo);
  6043. ScriptContext* scriptContext = function->GetScriptContext();
  6044. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6045. Assert(!(callInfo.Flags & CallFlags_New));
  6046. AssertMsg(args.Info.Count >= 1, "Should have at least one argument");
  6047. JavascriptArray* pArr = 0;
  6048. RecyclableObject* pObj = 0;
  6049. uint64 start = 0u;
  6050. uint64 deleteLen = 0u;
  6051. uint64 length = 0u;
  6052. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.splice"), &pArr, &pObj, &length));
  6053. switch (args.Info.Count)
  6054. {
  6055. case 1:
  6056. start = length;
  6057. deleteLen = 0u;
  6058. break;
  6059. case 2:
  6060. JS_REENTRANT(jsReentLock, start = GetFromIndex(args[1], length, scriptContext));
  6061. deleteLen = length - start;
  6062. break;
  6063. default:
  6064. JS_REENTRANT(jsReentLock, start = GetFromIndex(args[1], length, scriptContext),
  6065. deleteLen = GetFromIndex(args[2], (length - start), scriptContext, false));
  6066. break;
  6067. }
  6068. // 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.
  6069. if (pArr && !JavascriptArray::Is(pObj))
  6070. {
  6071. AssertOrFailFastMsg(ES5Array::Is(pObj), "The array should have been converted to an ES5Array");
  6072. pArr = nullptr;
  6073. }
  6074. Var* insertArgs = args.Info.Count > 3 ? &args.Values[3] : nullptr;
  6075. uint32 insertLen = args.Info.Count > 3 ? args.Info.Count - 3 : 0;
  6076. // Force check the prototype as we may insert values more than current elements
  6077. if (pArr != nullptr && !HasAnyES5ArrayInPrototypeChain(pArr, true /*forceCheckProtoChain*/))
  6078. {
  6079. // Since we get the length from an array and that cannot be more than uint32.
  6080. _Analysis_assume_(length <= UINT_MAX);
  6081. JS_REENTRANT_UNLOCK(jsReentLock,
  6082. return TryArraySplice(pArr, (uint32)start, (uint32)length, (uint32)deleteLen, insertArgs, insertLen, scriptContext));
  6083. }
  6084. uint64 newLen = (length - deleteLen) + insertLen;
  6085. if (newLen > UINT_MAX || length > UINT_MAX || (length + insertLen) > UINT_MAX)
  6086. {
  6087. JS_REENTRANT_UNLOCK(jsReentLock,
  6088. return ObjectSpliceHelper<uint64>(pObj, length, start, deleteLen, (Var*)insertArgs, insertLen, scriptContext, nullptr));
  6089. }
  6090. else
  6091. {
  6092. JS_REENTRANT_UNLOCK(jsReentLock,
  6093. return ObjectSpliceHelper<uint32>(pObj, (uint32)length, (uint32)start, (uint32)deleteLen, (Var*)insertArgs, insertLen, scriptContext, nullptr));
  6094. }
  6095. }
  6096. inline BOOL JavascriptArray::IsSingleSegmentArray() const
  6097. {
  6098. return nullptr == head->next;
  6099. }
  6100. template<typename T>
  6101. void JavascriptArray::ArraySegmentSpliceHelper(JavascriptArray *pnewArr, SparseArraySegment<T> *seg, SparseArraySegment<T> **prev,
  6102. uint32 start, uint32 deleteLen, Var* insertArgs, uint32 insertLen, Recycler *recycler)
  6103. {
  6104. // book keeping variables
  6105. uint32 relativeStart = start - seg->left; // This will be different from start when head->left is non zero -
  6106. //(Missing elements at the beginning)
  6107. uint32 headDeleteLen = min(start + deleteLen , seg->left + seg->length) - start; // actual number of elements to delete in
  6108. // head if deleteLen overflows the length of head
  6109. uint32 newHeadLen = seg->length - headDeleteLen + insertLen; // new length of the head after splice
  6110. // Save the deleted elements
  6111. if (headDeleteLen != 0)
  6112. {
  6113. SparseArraySegmentBase *oldHead = pnewArr->head;
  6114. bool isInlineSegment = JavascriptArray::IsInlineSegment(oldHead, pnewArr);
  6115. pnewArr->InvalidateLastUsedSegment();
  6116. pnewArr->head = SparseArraySegment<T>::CopySegment(recycler, SparseArraySegment<T>::From(pnewArr->head), 0, seg, start, headDeleteLen);
  6117. if (isInlineSegment && oldHead != pnewArr->head)
  6118. {
  6119. pnewArr->ClearElements(oldHead, 0);
  6120. }
  6121. }
  6122. if (newHeadLen != 0)
  6123. {
  6124. if (seg->size < newHeadLen)
  6125. {
  6126. if (seg->next)
  6127. {
  6128. // If we have "next", require that we haven't adjusted next segments left yet.
  6129. seg = seg->GrowByMinMax(recycler, newHeadLen - seg->size, seg->next->left - deleteLen + insertLen - seg->left - seg->size);
  6130. }
  6131. else
  6132. {
  6133. seg = seg->GrowByMin(recycler, newHeadLen - seg->size);
  6134. }
  6135. #ifdef VALIDATE_ARRAY
  6136. ValidateSegment(seg);
  6137. #endif
  6138. }
  6139. // Move the elements if necessary
  6140. if (headDeleteLen != insertLen)
  6141. {
  6142. uint32 noElementsToMove = seg->length - (relativeStart + headDeleteLen);
  6143. MoveArray(seg->elements + relativeStart + insertLen,
  6144. seg->elements + relativeStart + headDeleteLen,
  6145. noElementsToMove);
  6146. if (newHeadLen < seg->length) // truncate if necessary
  6147. {
  6148. seg->Truncate(seg->left + newHeadLen); // set end elements to null so that when we introduce null elements we are safe
  6149. }
  6150. seg->length = newHeadLen;
  6151. seg->CheckLengthvsSize();
  6152. }
  6153. // Copy the new elements
  6154. if (insertLen > 0)
  6155. {
  6156. Assert(!VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(pnewArr) &&
  6157. !VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(pnewArr));
  6158. // inserted elements starts at argument 3 of splice(start, deleteNumber, insertelem1, insertelem2, insertelem3, ...);
  6159. CopyArray(seg->elements + relativeStart, insertLen,
  6160. reinterpret_cast<const T*>(insertArgs), insertLen);
  6161. }
  6162. *prev = seg;
  6163. }
  6164. else
  6165. {
  6166. *prev = SparseArraySegment<T>::From(seg->next);
  6167. }
  6168. }
  6169. template<typename T>
  6170. void JavascriptArray::ArraySpliceHelper(JavascriptArray* pnewArr, JavascriptArray* pArr, uint32 start, uint32 deleteLen, Var* insertArgs, uint32 insertLen, ScriptContext *scriptContext)
  6171. {
  6172. // Skip pnewArr->EnsureHead(): we don't use existing segment at all.
  6173. Recycler *recycler = scriptContext->GetRecycler();
  6174. Field(SparseArraySegmentBase*)* prevSeg = &pArr->head; // holds the next pointer of previous
  6175. Field(SparseArraySegmentBase*)* prevPrevSeg = &pArr->head; // this holds the previous pointer to prevSeg dirty trick.
  6176. SparseArraySegmentBase* savePrev = nullptr;
  6177. Assert(pArr->head); // We should never have a null head.
  6178. pArr->EnsureHead<T>();
  6179. SparseArraySegment<T>* startSeg = SparseArraySegment<T>::From(pArr->head);
  6180. const uint32 limit = start + deleteLen;
  6181. uint32 rightLimit;
  6182. if (UInt32Math::Add(startSeg->left, startSeg->size, &rightLimit))
  6183. {
  6184. rightLimit = JavascriptArray::MaxArrayLength;
  6185. }
  6186. // Find out the segment to start delete
  6187. while (startSeg && (rightLimit <= start))
  6188. {
  6189. savePrev = startSeg;
  6190. prevPrevSeg = prevSeg;
  6191. prevSeg = &startSeg->next;
  6192. startSeg = SparseArraySegment<T>::From(startSeg->next);
  6193. if (startSeg)
  6194. {
  6195. if (UInt32Math::Add(startSeg->left, startSeg->size, &rightLimit))
  6196. {
  6197. rightLimit = JavascriptArray::MaxArrayLength;
  6198. }
  6199. }
  6200. }
  6201. bool hasInlineSegment = JavascriptArray::IsInlineSegment(startSeg, pArr);
  6202. if (startSeg)
  6203. {
  6204. // Delete Phase
  6205. if (startSeg->left <= start && (startSeg->left + startSeg->length) >= limit)
  6206. {
  6207. // All splice happens in one segment.
  6208. SparseArraySegmentBase *nextSeg = startSeg->next;
  6209. // Splice the segment first, which might OOM throw but the array would be intact.
  6210. JavascriptArray::ArraySegmentSpliceHelper(pnewArr, (SparseArraySegment<T>*)startSeg, (SparseArraySegment<T>**)prevSeg, start, deleteLen, insertArgs, insertLen, recycler);
  6211. while (nextSeg)
  6212. {
  6213. // adjust next segments left
  6214. nextSeg->left = nextSeg->left - deleteLen + insertLen;
  6215. if (nextSeg->next == nullptr)
  6216. {
  6217. nextSeg->EnsureSizeInBound();
  6218. }
  6219. nextSeg = nextSeg->next;
  6220. }
  6221. if (*prevSeg)
  6222. {
  6223. (*prevSeg)->EnsureSizeInBound();
  6224. }
  6225. return;
  6226. }
  6227. else
  6228. {
  6229. SparseArraySegment<T>* newHeadSeg = nullptr; // pnewArr->head is null
  6230. Field(SparseArraySegmentBase*)* prevNewHeadSeg = &pnewArr->head;
  6231. // delete till deleteLen and reuse segments for new array if it is possible.
  6232. // 3 steps -
  6233. //1. delete 1st segment (which may be partial delete)
  6234. // 2. delete next n complete segments
  6235. // 3. delete last segment (which again may be partial delete)
  6236. // Step (1) -- WOOB 1116297: When left >= start, step (1) is skipped, resulting in pNewArr->head->left != 0. We need to touch up pNewArr.
  6237. if (startSeg->left < start)
  6238. {
  6239. if (start < startSeg->left + startSeg->length)
  6240. {
  6241. uint32 headDeleteLen = startSeg->left + startSeg->length - start;
  6242. if (startSeg->next)
  6243. {
  6244. // We know the new segment will have a next segment, so allocate it as non-leaf.
  6245. newHeadSeg = SparseArraySegment<T>::template AllocateSegmentImpl<false>(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
  6246. }
  6247. else
  6248. {
  6249. newHeadSeg = SparseArraySegment<T>::AllocateSegment(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
  6250. }
  6251. newHeadSeg = SparseArraySegment<T>::CopySegment(recycler, newHeadSeg, 0, startSeg, start, headDeleteLen);
  6252. newHeadSeg->next = nullptr;
  6253. *prevNewHeadSeg = newHeadSeg;
  6254. prevNewHeadSeg = &newHeadSeg->next;
  6255. startSeg->Truncate(start);
  6256. }
  6257. savePrev = startSeg;
  6258. prevPrevSeg = prevSeg;
  6259. prevSeg = &startSeg->next;
  6260. startSeg = SparseArraySegment<T>::From(startSeg->next);
  6261. }
  6262. // Step (2) first we should do a hard copy if we have an inline head Segment
  6263. else if (hasInlineSegment && nullptr != startSeg)
  6264. {
  6265. // start should be in between left and left + length
  6266. if (startSeg->left <= start && start < startSeg->left + startSeg->length)
  6267. {
  6268. uint32 headDeleteLen = startSeg->left + startSeg->length - start;
  6269. if (startSeg->next)
  6270. {
  6271. // We know the new segment will have a next segment, so allocate it as non-leaf.
  6272. newHeadSeg = SparseArraySegment<T>::template AllocateSegmentImpl<false>(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
  6273. }
  6274. else
  6275. {
  6276. newHeadSeg = SparseArraySegment<T>::AllocateSegment(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
  6277. }
  6278. newHeadSeg = SparseArraySegment<T>::CopySegment(recycler, newHeadSeg, 0, startSeg, start, headDeleteLen);
  6279. *prevNewHeadSeg = newHeadSeg;
  6280. prevNewHeadSeg = &newHeadSeg->next;
  6281. // Remove the entire segment from the original array
  6282. *prevSeg = startSeg->next;
  6283. pArr->ClearElements(startSeg, 0);
  6284. startSeg = SparseArraySegment<T>::From(startSeg->next);
  6285. }
  6286. // if we have an inline head segment with 0 elements, remove it
  6287. else if (startSeg->left == 0 && startSeg->length == 0)
  6288. {
  6289. Assert(startSeg->size != 0);
  6290. *prevSeg = startSeg->next;
  6291. startSeg = SparseArraySegment<T>::From(startSeg->next);
  6292. }
  6293. }
  6294. // Step (2) proper
  6295. SparseArraySegmentBase *temp = nullptr;
  6296. while (startSeg && (startSeg->left + startSeg->length) <= limit)
  6297. {
  6298. temp = startSeg->next;
  6299. // move that entire segment to new array
  6300. startSeg->left = startSeg->left - start;
  6301. startSeg->next = nullptr;
  6302. *prevNewHeadSeg = startSeg;
  6303. prevNewHeadSeg = &startSeg->next;
  6304. // Remove the entire segment from the original array
  6305. *prevSeg = temp;
  6306. startSeg = (SparseArraySegment<T>*)temp;
  6307. }
  6308. // Step(2) above could delete the original head segment entirely, causing current head not
  6309. // starting from 0. Then if any of the following throw, we have a corrupted array. Need
  6310. // protection here.
  6311. bool dummyHeadNodeInserted = false;
  6312. if (!savePrev && (!startSeg || startSeg->left != 0))
  6313. {
  6314. Assert(pArr->head == startSeg);
  6315. pArr->EnsureHeadStartsFromZero<T>(recycler);
  6316. Assert(pArr->head && pArr->head->next == startSeg);
  6317. savePrev = pArr->head;
  6318. prevPrevSeg = prevSeg;
  6319. prevSeg = &pArr->head->next;
  6320. dummyHeadNodeInserted = true;
  6321. }
  6322. // Step (3)
  6323. if (startSeg && (startSeg->left < limit))
  6324. {
  6325. // copy the first part of the last segment to be deleted to new array
  6326. uint32 headDeleteLen = start + deleteLen - startSeg->left ;
  6327. newHeadSeg = SparseArraySegment<T>::AllocateSegment(recycler, startSeg->left - start, headDeleteLen, (SparseArraySegmentBase *)nullptr);
  6328. newHeadSeg = SparseArraySegment<T>::CopySegment(recycler, newHeadSeg, startSeg->left - start, startSeg, startSeg->left, headDeleteLen);
  6329. newHeadSeg->next = nullptr;
  6330. *prevNewHeadSeg = newHeadSeg;
  6331. prevNewHeadSeg = &newHeadSeg->next;
  6332. // move the last segment
  6333. MoveArray(startSeg->elements, startSeg->elements + headDeleteLen, startSeg->length - headDeleteLen);
  6334. startSeg->left = startSeg->left + headDeleteLen; // We are moving the left ahead to point to the right index
  6335. startSeg->length = startSeg->length - headDeleteLen;
  6336. startSeg->CheckLengthvsSize();
  6337. startSeg->Truncate(startSeg->left + startSeg->length);
  6338. startSeg->EnsureSizeInBound(); // Just truncated, size might exceed next.left
  6339. }
  6340. if (startSeg && ((startSeg->left - deleteLen + insertLen) == 0) && dummyHeadNodeInserted)
  6341. {
  6342. Assert(start + insertLen == 0);
  6343. // Remove the dummy head node to preserve array consistency.
  6344. pArr->head = startSeg;
  6345. savePrev = nullptr;
  6346. prevSeg = &pArr->head;
  6347. }
  6348. while (startSeg)
  6349. {
  6350. startSeg->left = startSeg->left - deleteLen + insertLen ;
  6351. if (startSeg->next == nullptr)
  6352. {
  6353. startSeg->EnsureSizeInBound();
  6354. }
  6355. startSeg = SparseArraySegment<T>::From(startSeg->next);
  6356. }
  6357. }
  6358. }
  6359. // The size of pnewArr head allocated in above step 1 might exceed next.left concatenated in step 2/3.
  6360. pnewArr->head->EnsureSizeInBound();
  6361. if (savePrev)
  6362. {
  6363. savePrev->EnsureSizeInBound();
  6364. }
  6365. // insert elements
  6366. if (insertLen > 0)
  6367. {
  6368. Assert(!JavascriptNativeIntArray::Is(pArr) && !JavascriptNativeFloatArray::Is(pArr));
  6369. // InsertPhase
  6370. SparseArraySegment<T> *segInsert = nullptr;
  6371. // see if we are just about the right of the previous segment
  6372. Assert(!savePrev || savePrev->left <= start);
  6373. if (savePrev && (start - savePrev->left < savePrev->size))
  6374. {
  6375. segInsert = (SparseArraySegment<T>*)savePrev;
  6376. uint32 spaceLeft = segInsert->size - (start - segInsert->left);
  6377. if(spaceLeft < insertLen)
  6378. {
  6379. SparseArraySegment<T> *oldSegInsert = segInsert;
  6380. bool isInlineSegment = JavascriptArray::IsInlineSegment(segInsert, pArr);
  6381. if (!segInsert->next)
  6382. {
  6383. segInsert = segInsert->GrowByMin(recycler, insertLen - spaceLeft);
  6384. }
  6385. else
  6386. {
  6387. segInsert = segInsert->GrowByMinMax(recycler, insertLen - spaceLeft, segInsert->next->left - segInsert->left - segInsert->size);
  6388. }
  6389. if (isInlineSegment)
  6390. {
  6391. pArr->ClearElements(oldSegInsert, 0);
  6392. }
  6393. }
  6394. *prevPrevSeg = segInsert;
  6395. segInsert->length = start + insertLen - segInsert->left;
  6396. segInsert->CheckLengthvsSize();
  6397. }
  6398. else
  6399. {
  6400. segInsert = SparseArraySegment<T>::AllocateSegment(recycler, start, insertLen, *prevSeg);
  6401. segInsert->next = *prevSeg;
  6402. *prevSeg = segInsert;
  6403. savePrev = segInsert;
  6404. }
  6405. uint32 relativeStart = start - segInsert->left;
  6406. // inserted elements starts at argument 3 of splice(start, deleteNumber, insertelem1, insertelem2, insertelem3, ...);
  6407. CopyArray(segInsert->elements + relativeStart, insertLen,
  6408. reinterpret_cast<const T*>(insertArgs), insertLen);
  6409. }
  6410. }
  6411. Var JavascriptArray::TryArraySplice(JavascriptArray* pArr, uint32 start, uint32 len, uint32 deleteLen,
  6412. Var* insertArgs, uint32 insertLen, ScriptContext *scriptContext)
  6413. {
  6414. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6415. Assert(pArr != nullptr);
  6416. RecyclableObject* newObj = nullptr;
  6417. Recycler *recycler = scriptContext->GetRecycler();
  6418. ::Math::RecordOverflowPolicy newLenOverflow;
  6419. uint32 newLen = UInt32Math::Add(len - deleteLen, insertLen, newLenOverflow); // new length of the array after splice
  6420. // If we have missing values then convert to not native array for now
  6421. // In future, we could support this scenario.
  6422. if (deleteLen == insertLen)
  6423. {
  6424. JS_REENTRANT(jsReentLock, pArr->FillFromPrototypes(start, start + deleteLen));
  6425. }
  6426. else if (len)
  6427. {
  6428. JS_REENTRANT(jsReentLock, pArr->FillFromPrototypes(start, len));
  6429. }
  6430. //
  6431. // If newLen overflowed, pre-process to prevent pushing sparse array segments or elements out of
  6432. // max array length, which would result in tons of index overflow and difficult to fix.
  6433. //
  6434. if (newLenOverflow.HasOverflowed())
  6435. {
  6436. pArr = EnsureNonNativeArray(pArr);
  6437. BigIndex dstIndex = MaxArrayLength;
  6438. uint32 maxInsertLen = MaxArrayLength - start;
  6439. if (insertLen > maxInsertLen)
  6440. {
  6441. // Copy overflowing insertArgs to properties
  6442. for (uint32 i = maxInsertLen; i < insertLen; i++)
  6443. {
  6444. pArr->GenericDirectSetItemAt(dstIndex, insertArgs[i]);
  6445. ++dstIndex;
  6446. }
  6447. insertLen = maxInsertLen; // update
  6448. // Truncate elements on the right to properties
  6449. if (start + deleteLen < len)
  6450. {
  6451. pArr->TruncateToProperties(dstIndex, start + deleteLen);
  6452. }
  6453. }
  6454. else
  6455. {
  6456. // Truncate would-overflow elements to properties
  6457. pArr->TruncateToProperties(dstIndex, MaxArrayLength - insertLen + deleteLen);
  6458. }
  6459. len = pArr->length; // update
  6460. newLen = len - deleteLen + insertLen;
  6461. Assert(newLen == MaxArrayLength);
  6462. }
  6463. if (insertArgs)
  6464. {
  6465. pArr = EnsureNonNativeArray(pArr);
  6466. }
  6467. bool isIntArray = false;
  6468. bool isFloatArray = false;
  6469. bool isBuiltinArrayCtor = true;
  6470. JavascriptArray *newArr = nullptr;
  6471. // Just dump the segment map on splice (before any possible allocation and throw)
  6472. pArr->ClearSegmentMap();
  6473. // If the source object is an Array exotic object (Array.isArray) we should try to load the constructor property
  6474. // and use it to construct the return object.
  6475. JS_REENTRANT(jsReentLock, newObj = ArraySpeciesCreate(pArr, deleteLen, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor));
  6476. if (newObj != nullptr)
  6477. {
  6478. pArr = EnsureNonNativeArray(pArr);
  6479. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  6480. if (JavascriptArray::Is(newObj))
  6481. {
  6482. #if ENABLE_COPYONACCESS_ARRAY
  6483. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
  6484. #endif
  6485. newArr = JavascriptArray::FromVar(newObj);
  6486. }
  6487. }
  6488. else
  6489. // This is the ES5 case, pArr['constructor'] doesn't exist, or pArr['constructor'] is the builtin Array constructor
  6490. {
  6491. pArr->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
  6492. newArr = CreateNewArrayHelper(deleteLen, isIntArray, isFloatArray, pArr, scriptContext);
  6493. #if ENABLE_COPYONACCESS_ARRAY
  6494. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  6495. #endif
  6496. }
  6497. // If return object is a JavascriptArray, we can use all the array splice helpers
  6498. if (newArr && isBuiltinArrayCtor && len == pArr->length)
  6499. {
  6500. // Code below has potential to throw due to OOM or SO. Just FailFast on those cases
  6501. AutoDisableInterrupt failFastOnError(scriptContext->GetThreadContext());
  6502. // Array has a single segment (need not start at 0) and splice start lies in the range
  6503. // of that segment we optimize splice - Fast path.
  6504. if (pArr->IsSingleSegmentArray() && pArr->head->HasIndex(start))
  6505. {
  6506. SparseArraySegmentBase *oldHead = pArr->head;
  6507. bool isInlineSegment = JavascriptArray::IsInlineSegment(oldHead, pArr);
  6508. if (isIntArray)
  6509. {
  6510. ArraySegmentSpliceHelper<int32>(newArr, SparseArraySegment<int32>::From(pArr->head), (SparseArraySegment<int32>**)&pArr->head, start, deleteLen, insertArgs, insertLen, recycler);
  6511. }
  6512. else if (isFloatArray)
  6513. {
  6514. ArraySegmentSpliceHelper<double>(newArr, SparseArraySegment<double>::From(pArr->head), (SparseArraySegment<double>**)&pArr->head, start, deleteLen, insertArgs, insertLen, recycler);
  6515. }
  6516. else
  6517. {
  6518. ArraySegmentSpliceHelper<Var>(newArr, SparseArraySegment<Var>::From(pArr->head), (SparseArraySegment<Var>**)&pArr->head, start, deleteLen, insertArgs, insertLen, recycler);
  6519. }
  6520. if (isInlineSegment && oldHead != pArr->head)
  6521. {
  6522. pArr->ClearElements(oldHead, 0);
  6523. }
  6524. // Since the start index is within the bounds of the original array's head segment, it will not acquire any new
  6525. // missing values. If the original array had missing values in the head segment, some of them may have been
  6526. // copied into the array that will be returned; otherwise, the array that is returned will also not have any
  6527. // missing values.
  6528. newArr->SetHasNoMissingValues(pArr->HasNoMissingValues());
  6529. }
  6530. else
  6531. {
  6532. if (isIntArray)
  6533. {
  6534. ArraySpliceHelper<int32>(newArr, pArr, start, deleteLen, insertArgs, insertLen, scriptContext);
  6535. }
  6536. else if (isFloatArray)
  6537. {
  6538. ArraySpliceHelper<double>(newArr, pArr, start, deleteLen, insertArgs, insertLen, scriptContext);
  6539. }
  6540. else
  6541. {
  6542. ArraySpliceHelper<Var>(newArr, pArr, start, deleteLen, insertArgs, insertLen, scriptContext);
  6543. }
  6544. // This function currently does not track missing values in the head segment if there are multiple segments
  6545. pArr->SetHasNoMissingValues(false);
  6546. newArr->SetHasNoMissingValues(false);
  6547. }
  6548. if (isIntArray)
  6549. {
  6550. pArr->EnsureHeadStartsFromZero<int32>(recycler);
  6551. newArr->EnsureHeadStartsFromZero<int32>(recycler);
  6552. }
  6553. else if (isFloatArray)
  6554. {
  6555. pArr->EnsureHeadStartsFromZero<double>(recycler);
  6556. newArr->EnsureHeadStartsFromZero<double>(recycler);
  6557. }
  6558. else
  6559. {
  6560. pArr->EnsureHeadStartsFromZero<Var>(recycler);
  6561. newArr->EnsureHeadStartsFromZero<Var>(recycler);
  6562. }
  6563. pArr->InvalidateLastUsedSegment();
  6564. // it is possible for valueOf accessors for the start or deleteLen
  6565. // arguments to modify the size of the array. Since the resulting size of the array
  6566. // is based on the cached value of length, this might lead to us having to trim
  6567. // excess array segments at the end of the splice operation, which SetLength() will do.
  6568. // However, this is also slower than performing the simple length assignment, so we only
  6569. // do it if we can detect the array length changing.
  6570. if (pArr->length != len)
  6571. {
  6572. pArr->SetLength(newLen);
  6573. }
  6574. else
  6575. {
  6576. pArr->length = newLen;
  6577. }
  6578. if (newArr->length != deleteLen)
  6579. {
  6580. newArr->SetLength(deleteLen);
  6581. }
  6582. else
  6583. {
  6584. newArr->length = deleteLen;
  6585. }
  6586. failFastOnError.Completed();
  6587. newArr->InvalidateLastUsedSegment();
  6588. #ifdef VALIDATE_ARRAY
  6589. newArr->ValidateArray();
  6590. pArr->ValidateArray();
  6591. #endif
  6592. if (newLenOverflow.HasOverflowed())
  6593. {
  6594. // ES5 15.4.4.12 16: If new len overflowed, SetLength throws
  6595. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  6596. }
  6597. return newArr;
  6598. }
  6599. if (newLenOverflow.HasOverflowed())
  6600. {
  6601. JS_REENTRANT_UNLOCK(jsReentLock, return ObjectSpliceHelper<uint64>(pArr, len, start, deleteLen, insertArgs, insertLen, scriptContext, newObj));
  6602. }
  6603. else // Use uint32 version if no overflow
  6604. {
  6605. JS_REENTRANT_UNLOCK(jsReentLock, return ObjectSpliceHelper<uint32>(pArr, len, start, deleteLen, insertArgs, insertLen, scriptContext, newObj));
  6606. }
  6607. }
  6608. template<typename T>
  6609. RecyclableObject* JavascriptArray::ObjectSpliceHelper(RecyclableObject* pObj, T len, T start,
  6610. T deleteLen, Var* insertArgs, uint32 insertLen, ScriptContext *scriptContext, RecyclableObject* pNewObj)
  6611. {
  6612. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6613. JavascriptArray *pnewArr = nullptr;
  6614. if (pNewObj == nullptr)
  6615. {
  6616. JS_REENTRANT(jsReentLock, pNewObj = ArraySpeciesCreate(pObj, deleteLen, scriptContext));
  6617. if (pNewObj == nullptr)
  6618. {
  6619. if (deleteLen > UINT_MAX)
  6620. {
  6621. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  6622. }
  6623. pnewArr = scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(deleteLen));
  6624. pnewArr->EnsureHead<Var>();
  6625. pNewObj = pnewArr;
  6626. }
  6627. }
  6628. if (JavascriptArray::Is(pNewObj))
  6629. {
  6630. #if ENABLE_COPYONACCESS_ARRAY
  6631. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pNewObj);
  6632. #endif
  6633. pnewArr = JavascriptArray::FromVar(pNewObj);
  6634. }
  6635. // copy elements to delete to new array
  6636. if (pnewArr != nullptr)
  6637. {
  6638. for (uint32 i = 0; i < deleteLen; i++)
  6639. {
  6640. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(pObj, start + i));
  6641. if (hasItem)
  6642. {
  6643. JS_REENTRANT(jsReentLock, Var element = JavascriptOperators::GetItem(pObj, start + i, scriptContext));
  6644. pnewArr->SetItem(i, element, PropertyOperation_None);
  6645. }
  6646. }
  6647. }
  6648. else
  6649. {
  6650. BigIndex k = 0u;
  6651. for (T i = 0u; i < deleteLen; i++)
  6652. {
  6653. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(pObj, start + i));
  6654. if (hasItem)
  6655. {
  6656. Var element = nullptr;
  6657. JS_REENTRANT(jsReentLock, element = JavascriptOperators::GetItem(pObj, start + i, scriptContext),
  6658. ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(pNewObj, k, element), scriptContext, k));
  6659. }
  6660. ++k;
  6661. }
  6662. }
  6663. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.splice"));
  6664. // Now we need reserve room if it is necessary
  6665. if (insertLen > deleteLen) // Might overflow max array length
  6666. {
  6667. // Unshift [start + deleteLen, len) to start + insertLen
  6668. JS_REENTRANT(jsReentLock, Unshift<BigIndex, T>(pObj, start + insertLen, start + deleteLen, len, scriptContext));
  6669. }
  6670. else if (insertLen < deleteLen) // Won't overflow max array length
  6671. {
  6672. T j = 0;
  6673. for (T i = start + deleteLen; i < len; i++)
  6674. {
  6675. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(pObj, i));
  6676. if (hasItem)
  6677. {
  6678. Var element = nullptr;
  6679. JS_REENTRANT(jsReentLock, element = JavascriptOperators::GetItem(pObj, i, scriptContext),
  6680. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(pObj, pObj, start + insertLen + j, element, scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  6681. }
  6682. else
  6683. {
  6684. JS_REENTRANT(jsReentLock,
  6685. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(pObj, start + insertLen + j, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  6686. }
  6687. j++;
  6688. }
  6689. // Clean up the rest
  6690. for (T i = len; i > len - deleteLen + insertLen; i--)
  6691. {
  6692. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(pObj, i - 1, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  6693. }
  6694. }
  6695. if (insertLen > 0)
  6696. {
  6697. T dstIndex = start; // insert index might overflow max array length
  6698. for (uint32 i = 0; i < insertLen; i++)
  6699. {
  6700. JS_REENTRANT(jsReentLock,
  6701. h.ThrowTypeErrorOnFailure(IndexTrace<BigIndex>::SetItem(pObj, dstIndex, insertArgs[i], PropertyOperation_ThrowIfNotExtensible)));
  6702. ++dstIndex;
  6703. }
  6704. }
  6705. // Set up new length
  6706. T newLen = T(len - deleteLen) + insertLen;
  6707. JS_REENTRANT(jsReentLock,
  6708. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(pObj, pObj, PropertyIds::length, IndexTrace<BigIndex>::ToNumber(newLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)),
  6709. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(pNewObj, pNewObj, PropertyIds::length, IndexTrace<BigIndex>::ToNumber(deleteLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  6710. #ifdef VALIDATE_ARRAY
  6711. if (pnewArr)
  6712. {
  6713. pnewArr->ValidateArray();
  6714. }
  6715. #endif
  6716. return pNewObj;
  6717. }
  6718. Var JavascriptArray::EntryToLocaleString(RecyclableObject* function, CallInfo callInfo, ...)
  6719. {
  6720. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  6721. ARGUMENTS(args, callInfo);
  6722. ScriptContext* scriptContext = function->GetScriptContext();
  6723. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6724. Assert(!(callInfo.Flags & CallFlags_New));
  6725. if (args.Info.Count == 0)
  6726. {
  6727. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedObject, _u("Array.prototype.toLocaleString"));
  6728. }
  6729. if (JavascriptArray::IsDirectAccessArray(args[0]))
  6730. {
  6731. JavascriptArray* arr = JavascriptArray::FromVar(args[0]);
  6732. JS_REENTRANT_UNLOCK(jsReentLock, return ToLocaleString(arr, scriptContext));
  6733. }
  6734. else
  6735. {
  6736. if (TypedArrayBase::IsDetachedTypedArray(args[0]))
  6737. {
  6738. JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("Array.prototype.toLocalString"));
  6739. }
  6740. RecyclableObject* obj = nullptr;
  6741. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  6742. {
  6743. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.toLocaleString"));
  6744. }
  6745. JS_REENTRANT_UNLOCK(jsReentLock, return ToLocaleString(obj, scriptContext));
  6746. }
  6747. }
  6748. //
  6749. // Unshift object elements [start, end) to toIndex, asserting toIndex > start.
  6750. //
  6751. template<typename T, typename P>
  6752. void JavascriptArray::Unshift(RecyclableObject* obj, const T& toIndex, P start, P end, ScriptContext* scriptContext)
  6753. {
  6754. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6755. typedef IndexTrace<T> index_trace;
  6756. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.unshift"));
  6757. if (start < end)
  6758. {
  6759. T newEnd = (end - start - 1);// newEnd - 1
  6760. T dst = toIndex + newEnd;
  6761. for (P i = end; i > start; --i)
  6762. {
  6763. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, i - 1));
  6764. if (hasItem)
  6765. {
  6766. Var element = nullptr;
  6767. JS_REENTRANT(jsReentLock, element = JavascriptOperators::GetItem(obj, i - 1, scriptContext),
  6768. h.ThrowTypeErrorOnFailure(index_trace::SetItem(obj, dst, element, PropertyOperation_ThrowIfNotExtensible)));
  6769. }
  6770. else
  6771. {
  6772. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(index_trace::DeleteItem(obj, dst, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  6773. }
  6774. --dst;
  6775. }
  6776. }
  6777. }
  6778. template<typename T>
  6779. void JavascriptArray::GrowArrayHeadHelperForUnshift(JavascriptArray* pArr, uint32 unshiftElements, ScriptContext * scriptContext)
  6780. {
  6781. SparseArraySegmentBase* nextToHeadSeg = pArr->head->next;
  6782. Recycler* recycler = scriptContext->GetRecycler();
  6783. SparseArraySegmentBase *oldHead = pArr->head;
  6784. bool isInlineSegment = JavascriptArray::IsInlineSegment(oldHead, pArr);
  6785. if (nextToHeadSeg == nullptr)
  6786. {
  6787. pArr->EnsureHead<T>();
  6788. pArr->head = SparseArraySegment<T>::From(pArr->head)->GrowByMin(recycler, unshiftElements);
  6789. }
  6790. else
  6791. {
  6792. pArr->head = SparseArraySegment<T>::From(pArr->head)->GrowByMinMax(recycler, unshiftElements, ((nextToHeadSeg->left + unshiftElements) - pArr->head->left - pArr->head->size));
  6793. }
  6794. if (isInlineSegment)
  6795. {
  6796. pArr->ClearElements(oldHead, 0);
  6797. }
  6798. }
  6799. template<typename T>
  6800. void JavascriptArray::UnshiftHelper(JavascriptArray* pArr, uint32 unshiftElements, Js::Var * elements)
  6801. {
  6802. SparseArraySegment<T>* head = SparseArraySegment<T>::From(pArr->head);
  6803. // Make enough room in the head segment to insert new elements at the front
  6804. MoveArray(head->elements + unshiftElements, head->elements, pArr->head->length);
  6805. uint32 oldHeadLength = head->length;
  6806. head->length += unshiftElements;
  6807. head->CheckLengthvsSize();
  6808. /* Set head segment as the last used segment */
  6809. pArr->InvalidateLastUsedSegment();
  6810. bool hasNoMissingValues = pArr->HasNoMissingValues();
  6811. /* Set HasNoMissingValues to false -> Since we shifted elements right, we might have missing values after the memmove */
  6812. if(unshiftElements > oldHeadLength)
  6813. {
  6814. pArr->SetHasNoMissingValues(false);
  6815. }
  6816. #if ENABLE_PROFILE_INFO
  6817. pArr->FillFromArgs(unshiftElements, 0, elements, nullptr, true/*dontCreateNewArray*/);
  6818. #else
  6819. pArr->FillFromArgs(unshiftElements, 0, elements, true/*dontCreateNewArray*/);
  6820. #endif
  6821. // Setting back to the old value
  6822. pArr->SetHasNoMissingValues(hasNoMissingValues);
  6823. }
  6824. Var JavascriptArray::EntryUnshift(RecyclableObject* function, CallInfo callInfo, ...)
  6825. {
  6826. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  6827. ARGUMENTS(args, callInfo);
  6828. ScriptContext* scriptContext = function->GetScriptContext();
  6829. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6830. Assert(!(callInfo.Flags & CallFlags_New));
  6831. Var res = scriptContext->GetLibrary()->GetUndefined();
  6832. if (args.Info.Count == 0)
  6833. {
  6834. return res;
  6835. }
  6836. JavascriptArray * pArr = nullptr;
  6837. if (JavascriptArray::Is(args[0])
  6838. && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
  6839. {
  6840. #if ENABLE_COPYONACCESS_ARRAY
  6841. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
  6842. #endif
  6843. pArr = JavascriptArray::FromVar(args[0]);
  6844. }
  6845. uint32 unshiftElements = args.Info.Count - 1;
  6846. // forceCheckProtoChain - since the array expand to accommodate new items thus we have to check if we have accessor on the proto chain.
  6847. bool useNoSideEffectUnshift = pArr != nullptr && (unshiftElements == 0 || !HasAnyES5ArrayInPrototypeChain(pArr, true /*forceCheckProtoChain*/));
  6848. if (useNoSideEffectUnshift)
  6849. {
  6850. if (unshiftElements > 0)
  6851. {
  6852. uint32 length = pArr->length;
  6853. if (pArr->IsFillFromPrototypes())
  6854. {
  6855. JS_REENTRANT(jsReentLock, pArr->FillFromPrototypes(0, pArr->length)); // We need find all missing value from [[proto]] object
  6856. }
  6857. // As we have already established that the FillFromPrototype should not change the bound of the array.
  6858. if (length != pArr->length)
  6859. {
  6860. Js::Throw::FatalInternalError();
  6861. }
  6862. // Pre-process: truncate overflowing elements to properties
  6863. bool newLenOverflowed = false;
  6864. uint32 maxLen = MaxArrayLength - unshiftElements;
  6865. if (pArr->length > maxLen)
  6866. {
  6867. newLenOverflowed = true;
  6868. // Ensure the array is non-native when overflow happens
  6869. EnsureNonNativeArray(pArr);
  6870. pArr->TruncateToProperties(MaxArrayLength, maxLen);
  6871. Assert(pArr->length + unshiftElements == MaxArrayLength);
  6872. }
  6873. pArr->ClearSegmentMap(); // Dump segmentMap on unshift (before any possible allocation and throw)
  6874. Assert(pArr->length <= MaxArrayLength - unshiftElements);
  6875. bool isIntArray = false;
  6876. bool isFloatArray = false;
  6877. if (JavascriptNativeIntArray::Is(pArr))
  6878. {
  6879. isIntArray = true;
  6880. }
  6881. else if (JavascriptNativeFloatArray::Is(pArr))
  6882. {
  6883. isFloatArray = true;
  6884. }
  6885. // If we need to grow head segment and there is already a next segment, then allocate the new head segment upfront
  6886. // If there is OOM in array allocation, then array consistency is maintained.
  6887. if (pArr->head->size < pArr->head->length + unshiftElements)
  6888. {
  6889. if (isIntArray)
  6890. {
  6891. GrowArrayHeadHelperForUnshift<int32>(pArr, unshiftElements, scriptContext);
  6892. }
  6893. else if (isFloatArray)
  6894. {
  6895. GrowArrayHeadHelperForUnshift<double>(pArr, unshiftElements, scriptContext);
  6896. }
  6897. else
  6898. {
  6899. GrowArrayHeadHelperForUnshift<Var>(pArr, unshiftElements, scriptContext);
  6900. }
  6901. }
  6902. SparseArraySegmentBase* renumberSeg = pArr->head->next;
  6903. while (renumberSeg)
  6904. {
  6905. renumberSeg->left += unshiftElements;
  6906. if (renumberSeg->next == nullptr)
  6907. {
  6908. // last segment can shift its left + size beyond MaxArrayLength, so truncate if so
  6909. renumberSeg->EnsureSizeInBound();
  6910. }
  6911. renumberSeg = renumberSeg->next;
  6912. }
  6913. try
  6914. {
  6915. if (isIntArray)
  6916. {
  6917. UnshiftHelper<int32>(pArr, unshiftElements, args.Values);
  6918. }
  6919. else if (isFloatArray)
  6920. {
  6921. UnshiftHelper<double>(pArr, unshiftElements, args.Values);
  6922. }
  6923. else
  6924. {
  6925. UnshiftHelper<Var>(pArr, unshiftElements, args.Values);
  6926. }
  6927. }
  6928. catch (...)
  6929. {
  6930. Js::Throw::FatalInternalError();
  6931. }
  6932. pArr->InvalidateLastUsedSegment();
  6933. pArr->length += unshiftElements;
  6934. #ifdef VALIDATE_ARRAY
  6935. pArr->ValidateArray();
  6936. #endif
  6937. if (newLenOverflowed) // ES5: throw if new "length" exceeds max array length
  6938. {
  6939. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  6940. }
  6941. }
  6942. res = JavascriptNumber::ToVar(pArr->length, scriptContext);
  6943. }
  6944. else
  6945. {
  6946. RecyclableObject* dynamicObject = nullptr;
  6947. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &dynamicObject))
  6948. {
  6949. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.unshift"));
  6950. }
  6951. JS_REENTRANT(jsReentLock, BigIndex length = OP_GetLength(dynamicObject, scriptContext));
  6952. if (unshiftElements > 0)
  6953. {
  6954. uint32 MaxSpaceUint32 = MaxArrayLength - unshiftElements;
  6955. // Note: end will always be a smallIndex either it is less than length in which case it is MaxSpaceUint32
  6956. // or MaxSpaceUint32 is greater than length meaning length is a uint32 number
  6957. BigIndex end = length > MaxSpaceUint32 ? MaxSpaceUint32 : length;
  6958. if (end < length)
  6959. {
  6960. // Unshift [end, length) to MaxArrayLength
  6961. // MaxArrayLength + (length - MaxSpaceUint32 - 1) = length + unshiftElements -1
  6962. if (length.IsSmallIndex())
  6963. {
  6964. JS_REENTRANT(jsReentLock, Unshift<BigIndex>(dynamicObject, MaxArrayLength, end.GetSmallIndex(), length.GetSmallIndex(), scriptContext));
  6965. }
  6966. else
  6967. {
  6968. JS_REENTRANT(jsReentLock, Unshift<BigIndex, uint64>(dynamicObject, MaxArrayLength, (uint64)end.GetSmallIndex(), length.GetBigIndex(), scriptContext));
  6969. }
  6970. }
  6971. // Unshift [0, end) to unshiftElements
  6972. // unshiftElements + (MaxSpaceUint32 - 0 - 1) = MaxArrayLength -1 therefore this unshift covers up to MaxArrayLength - 1
  6973. JS_REENTRANT(jsReentLock, Unshift<uint32>(dynamicObject, unshiftElements, (uint32)0, end.GetSmallIndex(), scriptContext));
  6974. for (uint32 i = 0; i < unshiftElements; i++)
  6975. {
  6976. JS_REENTRANT(jsReentLock,
  6977. JavascriptOperators::SetItem(dynamicObject, dynamicObject, i, args[i + 1], scriptContext, PropertyOperation_ThrowIfNotExtensible, true));
  6978. }
  6979. }
  6980. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.unshift"));
  6981. //ES6 - update 'length' even if unshiftElements == 0;
  6982. BigIndex newLen = length + unshiftElements;
  6983. res = JavascriptNumber::ToVar(newLen.IsSmallIndex() ? newLen.GetSmallIndex() : newLen.GetBigIndex(), scriptContext);
  6984. JS_REENTRANT(jsReentLock,
  6985. BOOL setLength = JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, res, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  6986. h.ThrowTypeErrorOnFailure(setLength);
  6987. }
  6988. return res;
  6989. }
  6990. Var JavascriptArray::EntryToString(RecyclableObject* function, CallInfo callInfo, ...)
  6991. {
  6992. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  6993. ARGUMENTS(args, callInfo);
  6994. ScriptContext* scriptContext = function->GetScriptContext();
  6995. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6996. Assert(!(callInfo.Flags & CallFlags_New));
  6997. if (args.Info.Count == 0)
  6998. {
  6999. JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedObject);
  7000. }
  7001. // ES5 15.4.4.2: call join, or built-in Object.prototype.toString
  7002. RecyclableObject* obj = nullptr;
  7003. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  7004. {
  7005. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.toString"));
  7006. }
  7007. // In ES5 we could be calling a user defined join, even on array. We must [[Get]] join at runtime.
  7008. JS_REENTRANT(jsReentLock, Var join = JavascriptOperators::GetProperty(obj, PropertyIds::join, scriptContext));
  7009. if (JavascriptConversion::IsCallable(join))
  7010. {
  7011. RecyclableObject* func = RecyclableObject::FromVar(join);
  7012. // We need to record implicit call here, because marked the Array.toString as no side effect,
  7013. // but if we call user code here which may have side effect
  7014. ThreadContext * threadContext = scriptContext->GetThreadContext();
  7015. JS_REENTRANT(jsReentLock,
  7016. Var result = threadContext->ExecuteImplicitCall(func, ImplicitCall_ToPrimitive, [=]() -> Js::Var
  7017. {
  7018. // Stack object should have a pre-op bail on implicit call. We shouldn't see them here.
  7019. Assert(!ThreadContext::IsOnStack(obj));
  7020. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7021. CallFlags flags = CallFlags_Value;
  7022. return CALL_FUNCTION(threadContext, func, CallInfo(flags, 1), obj);
  7023. }));
  7024. if(!result)
  7025. {
  7026. // There was an implicit call and implicit calls are disabled. This would typically cause a bailout.
  7027. Assert(threadContext->IsDisableImplicitCall());
  7028. result = scriptContext->GetLibrary()->GetNull();
  7029. }
  7030. return result;
  7031. }
  7032. else
  7033. {
  7034. // call built-in Object.prototype.toString
  7035. JS_REENTRANT_UNLOCK(jsReentLock,
  7036. return CALL_ENTRYPOINT(scriptContext->GetThreadContext(), JavascriptObject::EntryToString, function, CallInfo(1), obj));
  7037. }
  7038. }
  7039. #if DEBUG
  7040. BOOL JavascriptArray::GetIndex(const char16* propName, uint32 *pIndex)
  7041. {
  7042. uint32 lu, luDig;
  7043. int32 cch = (int32)wcslen(propName);
  7044. char16* pch = const_cast<char16 *>(propName);
  7045. lu = *pch - '0';
  7046. if (lu > 9)
  7047. return FALSE;
  7048. if (0 == lu)
  7049. {
  7050. *pIndex = 0;
  7051. return 1 == cch;
  7052. }
  7053. while ((luDig = *++pch - '0') < 10)
  7054. {
  7055. // If we overflow 32 bits, ignore the item
  7056. if (lu > 0x19999999)
  7057. return FALSE;
  7058. lu *= 10;
  7059. if(lu > (ULONG_MAX - luDig))
  7060. return FALSE;
  7061. lu += luDig;
  7062. }
  7063. if (pch - propName != cch)
  7064. return FALSE;
  7065. if (lu == JavascriptArray::InvalidIndex)
  7066. {
  7067. // 0xFFFFFFFF is not treated as an array index so that the length can be
  7068. // capped at 32 bits.
  7069. return FALSE;
  7070. }
  7071. *pIndex = lu;
  7072. return TRUE;
  7073. }
  7074. #endif
  7075. JavascriptString* JavascriptArray::GetLocaleSeparator(ScriptContext* scriptContext)
  7076. {
  7077. #ifdef ENABLE_GLOBALIZATION
  7078. LCID lcid = GetUserDefaultLCID();
  7079. int count = 0;
  7080. char16 szSeparator[6];
  7081. // According to the document for GetLocaleInfo this is a sufficient buffer size.
  7082. count = GetLocaleInfoW(lcid, LOCALE_SLIST, szSeparator, 5);
  7083. if( !count)
  7084. {
  7085. AssertMsg(FALSE, "GetLocaleInfo failed");
  7086. return scriptContext->GetLibrary()->GetCommaSpaceDisplayString();
  7087. }
  7088. else
  7089. {
  7090. // Append ' ' if necessary
  7091. if( count < 2 || szSeparator[count-2] != ' ')
  7092. {
  7093. szSeparator[count-1] = ' ';
  7094. szSeparator[count] = '\0';
  7095. }
  7096. return JavascriptString::NewCopyBuffer(szSeparator, count, scriptContext);
  7097. }
  7098. #else
  7099. // xplat-todo: Support locale-specific separator
  7100. return scriptContext->GetLibrary()->GetCommaSpaceDisplayString();
  7101. #endif
  7102. }
  7103. template <typename T>
  7104. JavascriptString* JavascriptArray::ToLocaleString(T* arr, ScriptContext* scriptContext)
  7105. {
  7106. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7107. uint32 length = 0;
  7108. if (TypedArrayBase::Is(arr))
  7109. {
  7110. // For a TypedArray use the actual length of the array.
  7111. length = TypedArrayBase::FromVar(arr)->GetLength();
  7112. }
  7113. else
  7114. {
  7115. //For anything else, use the "length" property if present.
  7116. JS_REENTRANT(jsReentLock, length = ItemTrace<T>::GetLength(arr, scriptContext));
  7117. }
  7118. if (length == 0 || scriptContext->CheckObject(arr))
  7119. {
  7120. return scriptContext->GetLibrary()->GetEmptyString();
  7121. }
  7122. JavascriptString* res = scriptContext->GetLibrary()->GetEmptyString();
  7123. bool pushedObject = false;
  7124. TryFinally([&]()
  7125. {
  7126. scriptContext->PushObject(arr);
  7127. pushedObject = true;
  7128. Var element = nullptr;
  7129. JS_REENTRANT(jsReentLock, BOOL gotItem = ItemTrace<T>::GetItem(arr, 0, &element, scriptContext));
  7130. if (gotItem)
  7131. {
  7132. JS_REENTRANT(jsReentLock, res = JavascriptArray::ToLocaleStringHelper(element, scriptContext));
  7133. }
  7134. if (length > 1)
  7135. {
  7136. JavascriptString* separator = GetLocaleSeparator(scriptContext);
  7137. for (uint32 i = 1; i < length; i++)
  7138. {
  7139. res = JavascriptString::Concat(res, separator);
  7140. JS_REENTRANT(jsReentLock, gotItem = ItemTrace<T>::GetItem(arr, i, &element, scriptContext));
  7141. if (gotItem)
  7142. {
  7143. JS_REENTRANT(jsReentLock, res = JavascriptString::Concat(res, JavascriptArray::ToLocaleStringHelper(element, scriptContext)));
  7144. }
  7145. }
  7146. }
  7147. },
  7148. [&](bool/*hasException*/)
  7149. {
  7150. if (pushedObject)
  7151. {
  7152. Var top = scriptContext->PopObject();
  7153. AssertMsg(top == arr, "Unmatched operation stack");
  7154. }
  7155. });
  7156. if (res == nullptr)
  7157. {
  7158. res = scriptContext->GetLibrary()->GetEmptyString();
  7159. }
  7160. return res;
  7161. }
  7162. Var JavascriptArray::EntryIsArray(RecyclableObject* function, CallInfo callInfo, ...)
  7163. {
  7164. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7165. ARGUMENTS(args, callInfo);
  7166. ScriptContext* scriptContext = function->GetScriptContext();
  7167. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7168. Assert(!(callInfo.Flags & CallFlags_New));
  7169. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Constructor_isArray);
  7170. if (args.Info.Count < 2)
  7171. {
  7172. return scriptContext->GetLibrary()->GetFalse();
  7173. }
  7174. #if ENABLE_COPYONACCESS_ARRAY
  7175. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[1]);
  7176. #endif
  7177. if (JavascriptOperators::IsArray(args[1]))
  7178. {
  7179. return scriptContext->GetLibrary()->GetTrue();
  7180. }
  7181. return scriptContext->GetLibrary()->GetFalse();
  7182. }
  7183. ///----------------------------------------------------------------------------
  7184. /// Find() calls the given predicate callback on each element of the array, in
  7185. /// order, and returns the first element that makes the predicate return true,
  7186. /// as described in (ES6.0: S22.1.3.8).
  7187. ///----------------------------------------------------------------------------
  7188. Var JavascriptArray::EntryFind(RecyclableObject* function, CallInfo callInfo, ...)
  7189. {
  7190. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7191. ARGUMENTS(args, callInfo);
  7192. ScriptContext* scriptContext = function->GetScriptContext();
  7193. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7194. Assert(!(callInfo.Flags & CallFlags_New));
  7195. if (args.Info.Count == 0)
  7196. {
  7197. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.find"));
  7198. }
  7199. int64 length;
  7200. JavascriptArray * pArr = nullptr;
  7201. RecyclableObject* obj = nullptr;
  7202. JS_REENTRANT_UNLOCK(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.find"), &pArr, &obj, &length));
  7203. return JavascriptArray::FindHelper<false>(pArr, nullptr, obj, length, args, scriptContext);
  7204. }
  7205. template <bool findIndex>
  7206. Var JavascriptArray::FindHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
  7207. {
  7208. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7209. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  7210. {
  7211. // typedArrayBase is only non-null if and only if we came here via the TypedArray entrypoint
  7212. if (typedArrayBase != nullptr)
  7213. {
  7214. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, findIndex ? _u("[TypedArray].prototype.findIndex") : _u("[TypedArray].prototype.find"));
  7215. }
  7216. else
  7217. {
  7218. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, findIndex ? _u("Array.prototype.findIndex") : _u("Array.prototype.find"));
  7219. }
  7220. }
  7221. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  7222. Var thisArg;
  7223. if (args.Info.Count > 2)
  7224. {
  7225. thisArg = args[2];
  7226. }
  7227. else
  7228. {
  7229. thisArg = scriptContext->GetLibrary()->GetUndefined();
  7230. }
  7231. // If we came from Array.prototype.find/findIndex and source object is not a JavascriptArray, source could be a TypedArray
  7232. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  7233. {
  7234. typedArrayBase = TypedArrayBase::FromVar(obj);
  7235. }
  7236. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7237. CallFlags flags = CallFlags_Value;
  7238. Var element = nullptr;
  7239. Var testResult = nullptr;
  7240. if (pArr)
  7241. {
  7242. Var undefined = scriptContext->GetLibrary()->GetUndefined();
  7243. Assert(length <= UINT_MAX);
  7244. for (uint32 k = 0; k < (uint32)length; k++)
  7245. {
  7246. element = undefined;
  7247. JS_REENTRANT(jsReentLock, pArr->DirectGetItemAtFull(k, &element));
  7248. Var index = JavascriptNumber::ToVar(k, scriptContext);
  7249. JS_REENTRANT(jsReentLock,
  7250. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7251. element,
  7252. index,
  7253. pArr));
  7254. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7255. {
  7256. return findIndex ? index : element;
  7257. }
  7258. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  7259. // we will process the rest of the array elements like an ES5Array.
  7260. if (!JavascriptArray::Is(obj))
  7261. {
  7262. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  7263. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FindObjectHelper<findIndex>(obj, length, k + 1, callBackFn, thisArg, scriptContext));
  7264. }
  7265. }
  7266. }
  7267. else if (typedArrayBase)
  7268. {
  7269. Assert(length <= UINT_MAX);
  7270. for (uint32 k = 0; k < (uint32)length; k++)
  7271. {
  7272. // Spec does not ask to call HasItem, so we need to go to visit the whole length
  7273. element = typedArrayBase->DirectGetItem(k);
  7274. Var index = JavascriptNumber::ToVar(k, scriptContext);
  7275. JS_REENTRANT(jsReentLock,
  7276. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7277. element,
  7278. index,
  7279. typedArrayBase));
  7280. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7281. {
  7282. return findIndex ? index : element;
  7283. }
  7284. }
  7285. }
  7286. else
  7287. {
  7288. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FindObjectHelper<findIndex>(obj, length, 0u, callBackFn, thisArg, scriptContext));
  7289. }
  7290. return findIndex ? JavascriptNumber::ToVar(-1, scriptContext) : scriptContext->GetLibrary()->GetUndefined();
  7291. }
  7292. template <bool findIndex>
  7293. Var JavascriptArray::FindObjectHelper(RecyclableObject* obj, int64 length, int64 start, RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
  7294. {
  7295. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7296. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7297. CallFlags flags = CallFlags_Value;
  7298. Var element = nullptr;
  7299. Var testResult = nullptr;
  7300. for (int64 k = start; k < length; k++)
  7301. {
  7302. JS_REENTRANT(jsReentLock, element = JavascriptOperators::GetItem(obj, (uint64)k, scriptContext));
  7303. Var index = JavascriptNumber::ToVar(k, scriptContext);
  7304. JS_REENTRANT(jsReentLock,
  7305. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7306. element,
  7307. index,
  7308. obj));
  7309. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7310. {
  7311. return findIndex ? index : element;
  7312. }
  7313. }
  7314. return findIndex ? JavascriptNumber::ToVar(-1, scriptContext) : scriptContext->GetLibrary()->GetUndefined();
  7315. }
  7316. ///----------------------------------------------------------------------------
  7317. /// FindIndex() calls the given predicate callback on each element of the
  7318. /// array, in order, and returns the index of the first element that makes the
  7319. /// predicate return true, as described in (ES6.0: S22.1.3.9).
  7320. ///----------------------------------------------------------------------------
  7321. Var JavascriptArray::EntryFindIndex(RecyclableObject* function, CallInfo callInfo, ...)
  7322. {
  7323. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7324. ARGUMENTS(args, callInfo);
  7325. ScriptContext* scriptContext = function->GetScriptContext();
  7326. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7327. Assert(!(callInfo.Flags & CallFlags_New));
  7328. if (args.Info.Count == 0)
  7329. {
  7330. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.findIndex"));
  7331. }
  7332. int64 length;
  7333. JavascriptArray * pArr = nullptr;
  7334. RecyclableObject* obj = nullptr;
  7335. JS_REENTRANT_UNLOCK(jsReentLock,
  7336. TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.findIndex"), &pArr, &obj, &length));
  7337. return JavascriptArray::FindHelper<true>(pArr, nullptr, obj, length, args, scriptContext);
  7338. }
  7339. ///----------------------------------------------------------------------------
  7340. /// Entries() returns a new ArrayIterator object configured to return key-
  7341. /// value pairs matching the elements of the this array/array-like object,
  7342. /// as described in (ES6.0: S22.1.3.4).
  7343. ///----------------------------------------------------------------------------
  7344. Var JavascriptArray::EntryEntries(RecyclableObject* function, CallInfo callInfo, ...)
  7345. {
  7346. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7347. ARGUMENTS(args, callInfo);
  7348. ScriptContext* scriptContext = function->GetScriptContext();
  7349. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7350. Assert(!(callInfo.Flags & CallFlags_New));
  7351. if (args.Info.Count == 0)
  7352. {
  7353. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.entries"));
  7354. }
  7355. RecyclableObject* thisObj = nullptr;
  7356. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &thisObj))
  7357. {
  7358. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.entries"));
  7359. }
  7360. #if ENABLE_COPYONACCESS_ARRAY
  7361. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(thisObj);
  7362. #endif
  7363. JS_REENTRANT_UNLOCK(jsReentLock,
  7364. return scriptContext->GetLibrary()->CreateArrayIterator(thisObj, JavascriptArrayIteratorKind::KeyAndValue));
  7365. }
  7366. ///----------------------------------------------------------------------------
  7367. /// Keys() returns a new ArrayIterator object configured to return the keys
  7368. /// of the this array/array-like object, as described in (ES6.0: S22.1.3.13).
  7369. ///----------------------------------------------------------------------------
  7370. Var JavascriptArray::EntryKeys(RecyclableObject* function, CallInfo callInfo, ...)
  7371. {
  7372. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7373. ARGUMENTS(args, callInfo);
  7374. ScriptContext* scriptContext = function->GetScriptContext();
  7375. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7376. Assert(!(callInfo.Flags & CallFlags_New));
  7377. if (args.Info.Count == 0)
  7378. {
  7379. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.keys"));
  7380. }
  7381. RecyclableObject* thisObj = nullptr;
  7382. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &thisObj))
  7383. {
  7384. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.keys"));
  7385. }
  7386. #if ENABLE_COPYONACCESS_ARRAY
  7387. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(thisObj);
  7388. #endif
  7389. JS_REENTRANT_UNLOCK(jsReentLock,
  7390. return scriptContext->GetLibrary()->CreateArrayIterator(thisObj, JavascriptArrayIteratorKind::Key));
  7391. }
  7392. ///----------------------------------------------------------------------------
  7393. /// Values() returns a new ArrayIterator object configured to return the values
  7394. /// of the this array/array-like object, as described in (ES6.0: S22.1.3.29).
  7395. ///----------------------------------------------------------------------------
  7396. Var JavascriptArray::EntryValues(RecyclableObject* function, CallInfo callInfo, ...)
  7397. {
  7398. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7399. ARGUMENTS(args, callInfo);
  7400. ScriptContext* scriptContext = function->GetScriptContext();
  7401. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7402. Assert(!(callInfo.Flags & CallFlags_New));
  7403. if (args.Info.Count == 0)
  7404. {
  7405. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.values"));
  7406. }
  7407. RecyclableObject* thisObj = nullptr;
  7408. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &thisObj))
  7409. {
  7410. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.values"));
  7411. }
  7412. #if ENABLE_COPYONACCESS_ARRAY
  7413. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(thisObj);
  7414. #endif
  7415. JS_REENTRANT_UNLOCK(jsReentLock,
  7416. return scriptContext->GetLibrary()->CreateArrayIterator(thisObj, JavascriptArrayIteratorKind::Value));
  7417. }
  7418. Var JavascriptArray::EntryEvery(RecyclableObject* function, CallInfo callInfo, ...)
  7419. {
  7420. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7421. ARGUMENTS(args, callInfo);
  7422. ScriptContext* scriptContext = function->GetScriptContext();
  7423. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7424. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.every"));
  7425. Assert(!(callInfo.Flags & CallFlags_New));
  7426. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_every);
  7427. if (args.Info.Count == 0)
  7428. {
  7429. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.every"));
  7430. }
  7431. BigIndex length;
  7432. JavascriptArray* pArr = nullptr;
  7433. RecyclableObject* obj = nullptr;
  7434. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.every"), &pArr, &obj, &length));
  7435. if (length.IsSmallIndex())
  7436. {
  7437. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::EveryHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  7438. }
  7439. 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
  7440. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::EveryHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  7441. }
  7442. // Array.prototype.every as described by ES6.0 (draft 22) Section 22.1.3.5
  7443. template <typename T>
  7444. Var JavascriptArray::EveryHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  7445. {
  7446. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7447. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  7448. {
  7449. // typedArrayBase is only non-null if and only if we came here via the TypedArray entrypoint
  7450. if (typedArrayBase != nullptr)
  7451. {
  7452. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.every"));
  7453. }
  7454. else
  7455. {
  7456. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.every"));
  7457. }
  7458. }
  7459. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  7460. Var thisArg = nullptr;
  7461. if (args.Info.Count > 2)
  7462. {
  7463. thisArg = args[2];
  7464. }
  7465. else
  7466. {
  7467. thisArg = scriptContext->GetLibrary()->GetUndefined();
  7468. }
  7469. // If we came from Array.prototype.map and source object is not a JavascriptArray, source could be a TypedArray
  7470. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  7471. {
  7472. typedArrayBase = TypedArrayBase::FromVar(obj);
  7473. }
  7474. Var element = nullptr;
  7475. Var testResult = nullptr;
  7476. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7477. CallFlags flags = CallFlags_Value;
  7478. if (pArr)
  7479. {
  7480. Assert(length <= UINT_MAX);
  7481. for (uint32 k = 0; k < (uint32)length; k++)
  7482. {
  7483. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(k, &element));
  7484. if (!gotItem)
  7485. {
  7486. continue;
  7487. }
  7488. JS_REENTRANT(jsReentLock,
  7489. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7490. element,
  7491. JavascriptNumber::ToVar(k, scriptContext),
  7492. pArr));
  7493. if (!JavascriptConversion::ToBoolean(testResult, scriptContext))
  7494. {
  7495. return scriptContext->GetLibrary()->GetFalse();
  7496. }
  7497. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  7498. // we will process the rest of the array elements like an ES5Array.
  7499. if (!JavascriptArray::Is(obj))
  7500. {
  7501. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  7502. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::EveryObjectHelper<T>(obj, length, k + 1, callBackFn, thisArg, scriptContext));
  7503. }
  7504. }
  7505. }
  7506. else if (typedArrayBase)
  7507. {
  7508. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  7509. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  7510. for (uint32 k = 0; k < end; k++)
  7511. {
  7512. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  7513. element = typedArrayBase->DirectGetItem(k);
  7514. JS_REENTRANT(jsReentLock,
  7515. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7516. element,
  7517. JavascriptNumber::ToVar(k, scriptContext),
  7518. typedArrayBase));
  7519. if (!JavascriptConversion::ToBoolean(testResult, scriptContext))
  7520. {
  7521. return scriptContext->GetLibrary()->GetFalse();
  7522. }
  7523. }
  7524. }
  7525. else
  7526. {
  7527. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::EveryObjectHelper<T>(obj, length, 0u, callBackFn, thisArg, scriptContext));
  7528. }
  7529. return scriptContext->GetLibrary()->GetTrue();
  7530. }
  7531. template <typename T>
  7532. Var JavascriptArray::EveryObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
  7533. {
  7534. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7535. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7536. CallFlags flags = CallFlags_Value;
  7537. Var element = nullptr;
  7538. Var testResult = nullptr;
  7539. for (T k = start; k < length; k++)
  7540. {
  7541. // According to es6 spec, we need to call Has first before calling Get
  7542. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  7543. if (hasItem)
  7544. {
  7545. JS_REENTRANT(jsReentLock,
  7546. element = JavascriptOperators::GetItem(obj, k, scriptContext),
  7547. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7548. element,
  7549. JavascriptNumber::ToVar(k, scriptContext),
  7550. obj));
  7551. if (!JavascriptConversion::ToBoolean(testResult, scriptContext))
  7552. {
  7553. return scriptContext->GetLibrary()->GetFalse();
  7554. }
  7555. }
  7556. }
  7557. return scriptContext->GetLibrary()->GetTrue();
  7558. }
  7559. Var JavascriptArray::EntrySome(RecyclableObject* function, CallInfo callInfo, ...)
  7560. {
  7561. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7562. ARGUMENTS(args, callInfo);
  7563. ScriptContext* scriptContext = function->GetScriptContext();
  7564. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7565. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.some"));
  7566. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_some);
  7567. Assert(!(callInfo.Flags & CallFlags_New));
  7568. if (args.Info.Count == 0)
  7569. {
  7570. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.some"));
  7571. }
  7572. BigIndex length;
  7573. JavascriptArray* pArr = nullptr;
  7574. RecyclableObject* obj = nullptr;
  7575. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.some"), &pArr, &obj, &length));
  7576. if (length.IsSmallIndex())
  7577. {
  7578. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SomeHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  7579. }
  7580. 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
  7581. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SomeHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  7582. }
  7583. // Array.prototype.some as described in ES6.0 (draft 22) Section 22.1.3.23
  7584. template <typename T>
  7585. Var JavascriptArray::SomeHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  7586. {
  7587. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7588. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  7589. {
  7590. // We are in the TypedArray version of this API if and only if typedArrayBase != nullptr
  7591. if (typedArrayBase != nullptr)
  7592. {
  7593. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.some"));
  7594. }
  7595. else
  7596. {
  7597. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.some"));
  7598. }
  7599. }
  7600. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  7601. Var thisArg = nullptr;
  7602. if (args.Info.Count > 2)
  7603. {
  7604. thisArg = args[2];
  7605. }
  7606. else
  7607. {
  7608. thisArg = scriptContext->GetLibrary()->GetUndefined();
  7609. }
  7610. // If we came from Array.prototype.some and source object is not a JavascriptArray, source could be a TypedArray
  7611. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  7612. {
  7613. typedArrayBase = TypedArrayBase::FromVar(obj);
  7614. }
  7615. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7616. CallFlags flags = CallFlags_Value;
  7617. Var element = nullptr;
  7618. Var testResult = nullptr;
  7619. if (pArr)
  7620. {
  7621. Assert(length <= UINT_MAX);
  7622. for (uint32 k = 0; k < (uint32)length; k++)
  7623. {
  7624. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(k, &element));
  7625. if (!gotItem)
  7626. {
  7627. continue;
  7628. }
  7629. JS_REENTRANT_UNLOCK(jsReentLock,
  7630. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7631. element,
  7632. JavascriptNumber::ToVar(k, scriptContext),
  7633. pArr));
  7634. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7635. {
  7636. return scriptContext->GetLibrary()->GetTrue();
  7637. }
  7638. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  7639. // we will process the rest of the array elements like an ES5Array.
  7640. if (!JavascriptArray::Is(obj))
  7641. {
  7642. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  7643. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SomeObjectHelper<T>(obj, length, k + 1, callBackFn, thisArg, scriptContext));
  7644. }
  7645. }
  7646. }
  7647. else if (typedArrayBase)
  7648. {
  7649. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  7650. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  7651. for (uint32 k = 0; k < end; k++)
  7652. {
  7653. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  7654. element = typedArrayBase->DirectGetItem(k);
  7655. JS_REENTRANT_UNLOCK(jsReentLock,
  7656. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7657. element,
  7658. JavascriptNumber::ToVar(k, scriptContext),
  7659. typedArrayBase));
  7660. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7661. {
  7662. return scriptContext->GetLibrary()->GetTrue();
  7663. }
  7664. }
  7665. }
  7666. else
  7667. {
  7668. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SomeObjectHelper<T>(obj, length, 0u, callBackFn, thisArg, scriptContext));
  7669. }
  7670. return scriptContext->GetLibrary()->GetFalse();
  7671. }
  7672. template <typename T>
  7673. Var JavascriptArray::SomeObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
  7674. {
  7675. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7676. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7677. CallFlags flags = CallFlags_Value;
  7678. Var element = nullptr;
  7679. Var testResult = nullptr;
  7680. for (T k = start; k < length; k++)
  7681. {
  7682. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  7683. if (hasItem)
  7684. {
  7685. JS_REENTRANT_UNLOCK(jsReentLock,
  7686. element = JavascriptOperators::GetItem(obj, k, scriptContext),
  7687. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7688. element,
  7689. JavascriptNumber::ToVar(k, scriptContext),
  7690. obj));
  7691. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7692. {
  7693. return scriptContext->GetLibrary()->GetTrue();
  7694. }
  7695. }
  7696. }
  7697. return scriptContext->GetLibrary()->GetFalse();
  7698. }
  7699. Var JavascriptArray::EntryForEach(RecyclableObject* function, CallInfo callInfo, ...)
  7700. {
  7701. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7702. ARGUMENTS(args, callInfo);
  7703. ScriptContext* scriptContext = function->GetScriptContext();
  7704. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7705. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.forEach"));
  7706. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_forEach)
  7707. Assert(!(callInfo.Flags & CallFlags_New));
  7708. if (args.Info.Count == 0)
  7709. {
  7710. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.forEach"));
  7711. }
  7712. BigIndex length;
  7713. JavascriptArray* pArr = nullptr;
  7714. RecyclableObject* dynamicObject = nullptr;
  7715. RecyclableObject* callBackFn = nullptr;
  7716. Var thisArg = nullptr;
  7717. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.forEach"), &pArr, &dynamicObject, &length));
  7718. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  7719. {
  7720. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.forEach"));
  7721. }
  7722. callBackFn = RecyclableObject::FromVar(args[1]);
  7723. if (args.Info.Count > 2)
  7724. {
  7725. thisArg = args[2];
  7726. }
  7727. else
  7728. {
  7729. thisArg = scriptContext->GetLibrary()->GetUndefined();
  7730. }
  7731. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7732. CallFlags flags = CallFlags_Value;
  7733. auto fn32 = [dynamicObject, callBackFn, flags, thisArg,
  7734. scriptContext](uint32 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. auto fn64 = [dynamicObject, callBackFn, flags, thisArg,
  7742. scriptContext](uint64 k, Var element)
  7743. {
  7744. CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7745. element,
  7746. JavascriptNumber::ToVar(k, scriptContext),
  7747. dynamicObject);
  7748. };
  7749. if (pArr)
  7750. {
  7751. Assert(pArr == dynamicObject);
  7752. JS_REENTRANT(jsReentLock, pArr->ForEachItemInRange<true>(0, length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex(), scriptContext, fn32));
  7753. }
  7754. else
  7755. {
  7756. if (length.IsSmallIndex())
  7757. {
  7758. JS_REENTRANT(jsReentLock, TemplatedForEachItemInRange<true>(dynamicObject, 0u, length.GetSmallIndex(), scriptContext, fn32));
  7759. }
  7760. else
  7761. {
  7762. JS_REENTRANT(jsReentLock, TemplatedForEachItemInRange<true>(dynamicObject, 0ui64, length.GetBigIndex(), scriptContext, fn64));
  7763. }
  7764. }
  7765. return scriptContext->GetLibrary()->GetUndefined();
  7766. }
  7767. Var JavascriptArray::EntryCopyWithin(RecyclableObject* function, CallInfo callInfo, ...)
  7768. {
  7769. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7770. ARGUMENTS(args, callInfo);
  7771. ScriptContext* scriptContext = function->GetScriptContext();
  7772. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7773. Assert(!(callInfo.Flags & CallFlags_New));
  7774. RecyclableObject* obj = nullptr;
  7775. JavascriptArray* pArr = nullptr;
  7776. int64 length;
  7777. JS_REENTRANT_UNLOCK(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.copyWithin"), &pArr, &obj, &length));
  7778. return JavascriptArray::CopyWithinHelper(pArr, nullptr, obj, length, args, scriptContext);
  7779. }
  7780. // Array.prototype.copyWithin as defined in ES6.0 (draft 22) Section 22.1.3.3
  7781. Var JavascriptArray::CopyWithinHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
  7782. {
  7783. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7784. Assert(args.Info.Count > 0);
  7785. JavascriptLibrary* library = scriptContext->GetLibrary();
  7786. int64 fromVal = 0;
  7787. int64 toVal = 0;
  7788. int64 finalVal = length;
  7789. // If we came from Array.prototype.copyWithin and source object is not a JavascriptArray, source could be a TypedArray
  7790. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  7791. {
  7792. typedArrayBase = TypedArrayBase::FromVar(obj);
  7793. }
  7794. if (args.Info.Count > 1)
  7795. {
  7796. JS_REENTRANT(jsReentLock, toVal = JavascriptArray::GetIndexFromVar(args[1], length, scriptContext));
  7797. if (args.Info.Count > 2)
  7798. {
  7799. JS_REENTRANT(jsReentLock, fromVal = JavascriptArray::GetIndexFromVar(args[2], length, scriptContext));
  7800. if (args.Info.Count > 3 && args[3] != library->GetUndefined())
  7801. {
  7802. JS_REENTRANT(jsReentLock, finalVal = JavascriptArray::GetIndexFromVar(args[3], length, scriptContext));
  7803. }
  7804. }
  7805. }
  7806. // If count would be negative or zero, we won't do anything so go ahead and return early.
  7807. if (finalVal <= fromVal || length <= toVal)
  7808. {
  7809. return obj;
  7810. }
  7811. // Make sure we won't underflow during the count calculation
  7812. Assert(finalVal > fromVal && length > toVal);
  7813. int64 count = min(finalVal - fromVal, length - toVal);
  7814. // We shouldn't have made it here if the count was going to be zero
  7815. Assert(count > 0);
  7816. int direction;
  7817. if (fromVal < toVal && toVal < (fromVal + count))
  7818. {
  7819. direction = -1;
  7820. fromVal += count - 1;
  7821. toVal += count - 1;
  7822. }
  7823. else
  7824. {
  7825. direction = 1;
  7826. }
  7827. // Side effects (such as defining a property in a ToPrimitive call) during evaluation of arguments may convert the array to an ES5 array.
  7828. if (pArr && !JavascriptArray::Is(obj))
  7829. {
  7830. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  7831. pArr = nullptr;
  7832. }
  7833. // If we are going to copy elements from or to indices > 2^32-1 we'll execute this (slightly slower path)
  7834. // It's possible to optimize here so that we use the normal code below except for the > 2^32-1 indices
  7835. if ((direction == -1 && (fromVal >= MaxArrayLength || toVal >= MaxArrayLength))
  7836. || (((fromVal + count) > MaxArrayLength) || ((toVal + count) > MaxArrayLength)))
  7837. {
  7838. while (count > 0)
  7839. {
  7840. Var index = JavascriptNumber::ToVar(fromVal, scriptContext);
  7841. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::OP_HasItem(obj, index, scriptContext));
  7842. if (hasItem)
  7843. {
  7844. Var val = nullptr;
  7845. JS_REENTRANT(jsReentLock,
  7846. val = JavascriptOperators::OP_GetElementI(obj, index, scriptContext),
  7847. JavascriptOperators::OP_SetElementI(obj, JavascriptNumber::ToVar(toVal, scriptContext), val, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  7848. }
  7849. else
  7850. {
  7851. JavascriptOperators::OP_DeleteElementI(obj, JavascriptNumber::ToVar(toVal, scriptContext), scriptContext, PropertyOperation_ThrowOnDeleteIfNotConfig);
  7852. }
  7853. fromVal += direction;
  7854. toVal += direction;
  7855. count--;
  7856. }
  7857. }
  7858. else
  7859. {
  7860. Assert(fromVal < MaxArrayLength);
  7861. Assert(toVal < MaxArrayLength);
  7862. Assert(direction == -1 || (fromVal + count < MaxArrayLength && toVal + count < MaxArrayLength));
  7863. uint32 fromIndex = static_cast<uint32>(fromVal);
  7864. uint32 toIndex = static_cast<uint32>(toVal);
  7865. while (count > 0)
  7866. {
  7867. JS_REENTRANT(jsReentLock, BOOL hasItem = obj->HasItem(fromIndex));
  7868. if (hasItem)
  7869. {
  7870. if (typedArrayBase)
  7871. {
  7872. Var val = typedArrayBase->DirectGetItem(fromIndex);
  7873. JS_REENTRANT(jsReentLock, typedArrayBase->DirectSetItem(toIndex, val));
  7874. }
  7875. else if (pArr)
  7876. {
  7877. JS_REENTRANT(jsReentLock, Var val = pArr->DirectGetItem(fromIndex));
  7878. pArr->SetItem(toIndex, val, Js::PropertyOperation_ThrowIfNotExtensible);
  7879. if (!JavascriptArray::Is(obj))
  7880. {
  7881. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  7882. pArr = nullptr;
  7883. }
  7884. }
  7885. else
  7886. {
  7887. Var val = nullptr;
  7888. JS_REENTRANT(jsReentLock,
  7889. val = JavascriptOperators::OP_GetElementI_UInt32(obj, fromIndex, scriptContext),
  7890. JavascriptOperators::OP_SetElementI_UInt32(obj, toIndex, val, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  7891. }
  7892. }
  7893. else
  7894. {
  7895. obj->DeleteItem(toIndex, PropertyOperation_ThrowOnDeleteIfNotConfig);
  7896. }
  7897. fromIndex += direction;
  7898. toIndex += direction;
  7899. count--;
  7900. }
  7901. }
  7902. return obj;
  7903. }
  7904. Var JavascriptArray::EntryFill(RecyclableObject* function, CallInfo callInfo, ...)
  7905. {
  7906. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7907. ARGUMENTS(args, callInfo);
  7908. ScriptContext* scriptContext = function->GetScriptContext();
  7909. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7910. Assert(!(callInfo.Flags & CallFlags_New));
  7911. RecyclableObject* obj = nullptr;
  7912. JavascriptArray* pArr = nullptr;
  7913. int64 length;
  7914. JS_REENTRANT_UNLOCK(jsReentLock,
  7915. TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.fill"), &pArr, &obj, &length));
  7916. return JavascriptArray::FillHelper(pArr, nullptr, obj, length, args, scriptContext);
  7917. }
  7918. // Array.prototype.fill as defined in ES6.0 (draft 22) Section 22.1.3.6
  7919. Var JavascriptArray::FillHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
  7920. {
  7921. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7922. Assert(args.Info.Count > 0);
  7923. JavascriptLibrary* library = scriptContext->GetLibrary();
  7924. // If we came from Array.prototype.fill and source object is not a JavascriptArray, source could be a TypedArray
  7925. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  7926. {
  7927. typedArrayBase = TypedArrayBase::FromVar(obj);
  7928. }
  7929. Var fillValue;
  7930. if (args.Info.Count > 1)
  7931. {
  7932. fillValue = args[1];
  7933. }
  7934. else
  7935. {
  7936. fillValue = library->GetUndefined();
  7937. }
  7938. int64 k = 0;
  7939. int64 finalVal = length;
  7940. if (args.Info.Count > 2)
  7941. {
  7942. JS_REENTRANT_UNLOCK(jsReentLock, k = JavascriptArray::GetIndexFromVar(args[2], length, scriptContext));
  7943. if (args.Info.Count > 3 && !JavascriptOperators::IsUndefinedObject(args[3]))
  7944. {
  7945. JS_REENTRANT_UNLOCK(jsReentLock, finalVal = JavascriptArray::GetIndexFromVar(args[3], length, scriptContext));
  7946. }
  7947. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  7948. // we will process the array elements like an ES5Array.
  7949. if (pArr && !JavascriptArray::Is(obj))
  7950. {
  7951. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  7952. pArr = nullptr;
  7953. }
  7954. }
  7955. if (k < MaxArrayLength)
  7956. {
  7957. int64 end = min<int64>(finalVal, MaxArrayLength);
  7958. uint32 u32k = static_cast<uint32>(k);
  7959. while (u32k < end)
  7960. {
  7961. if (typedArrayBase)
  7962. {
  7963. JS_REENTRANT(jsReentLock, typedArrayBase->DirectSetItem(u32k, fillValue));
  7964. }
  7965. else if (pArr)
  7966. {
  7967. pArr->SetItem(u32k, fillValue, PropertyOperation_ThrowIfNotExtensible);
  7968. }
  7969. else
  7970. {
  7971. JS_REENTRANT(jsReentLock,
  7972. JavascriptOperators::OP_SetElementI_UInt32(obj, u32k, fillValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible));
  7973. }
  7974. u32k++;
  7975. }
  7976. BigIndex dstIndex = MaxArrayLength;
  7977. for (int64 i = end; i < finalVal; ++i)
  7978. {
  7979. if (pArr)
  7980. {
  7981. pArr->GenericDirectSetItemAt(dstIndex, fillValue);
  7982. ++dstIndex;
  7983. }
  7984. else
  7985. {
  7986. JS_REENTRANT(jsReentLock,
  7987. JavascriptOperators::OP_SetElementI(obj, JavascriptNumber::ToVar(i, scriptContext), fillValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible));
  7988. }
  7989. }
  7990. }
  7991. else
  7992. {
  7993. BigIndex dstIndex = static_cast<uint64>(k);
  7994. for (int64 i = k; i < finalVal; i++)
  7995. {
  7996. if (pArr)
  7997. {
  7998. pArr->GenericDirectSetItemAt(dstIndex, fillValue);
  7999. ++dstIndex;
  8000. }
  8001. else
  8002. {
  8003. JS_REENTRANT(jsReentLock,
  8004. JavascriptOperators::OP_SetElementI(obj, JavascriptNumber::ToVar(i, scriptContext), fillValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible));
  8005. }
  8006. }
  8007. }
  8008. return obj;
  8009. }
  8010. // Array.prototype.map as defined by ES6.0 (Final) 22.1.3.15
  8011. Var JavascriptArray::EntryMap(RecyclableObject* function, CallInfo callInfo, ...)
  8012. {
  8013. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8014. ARGUMENTS(args, callInfo);
  8015. ScriptContext* scriptContext = function->GetScriptContext();
  8016. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8017. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.map"));
  8018. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_map);
  8019. Assert(!(callInfo.Flags & CallFlags_New));
  8020. if (args.Info.Count == 0)
  8021. {
  8022. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.map"));
  8023. }
  8024. BigIndex length;
  8025. JavascriptArray* pArr = nullptr;
  8026. RecyclableObject* obj = nullptr;
  8027. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.map"), &pArr, &obj, &length));
  8028. if (length.IsSmallIndex())
  8029. {
  8030. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::MapHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  8031. }
  8032. 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
  8033. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::MapHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  8034. }
  8035. template<typename T>
  8036. Var JavascriptArray::MapHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  8037. {
  8038. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8039. RecyclableObject* newObj = nullptr;
  8040. JavascriptArray* newArr = nullptr;
  8041. bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
  8042. bool isBuiltinArrayCtor = true;
  8043. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  8044. {
  8045. if (isTypedArrayEntryPoint)
  8046. {
  8047. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.map"));
  8048. }
  8049. else
  8050. {
  8051. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.map"));
  8052. }
  8053. }
  8054. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  8055. Var thisArg;
  8056. if (args.Info.Count > 2)
  8057. {
  8058. thisArg = args[2];
  8059. }
  8060. else
  8061. {
  8062. thisArg = scriptContext->GetLibrary()->GetUndefined();
  8063. }
  8064. // If we came from Array.prototype.map and source object is not a JavascriptArray, source could be a TypedArray
  8065. if (!isTypedArrayEntryPoint && pArr == nullptr && TypedArrayBase::Is(obj))
  8066. {
  8067. typedArrayBase = TypedArrayBase::FromVar(obj);
  8068. }
  8069. // 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
  8070. // and use it to construct the return object.
  8071. if (isTypedArrayEntryPoint)
  8072. {
  8073. JS_REENTRANT(jsReentLock,
  8074. Var constructor = JavascriptOperators::SpeciesConstructor(
  8075. typedArrayBase, TypedArrayBase::GetDefaultConstructor(args[0], scriptContext), scriptContext));
  8076. isBuiltinArrayCtor = false;
  8077. Assert(JavascriptOperators::IsConstructor(constructor));
  8078. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(length, scriptContext) };
  8079. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  8080. JS_REENTRANT(jsReentLock, newObj = RecyclableObject::FromVar(TypedArrayBase::TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), (uint32)length, scriptContext)));
  8081. }
  8082. // skip the typed array and "pure" array case, we still need to handle special arrays like es5array, remote array, and proxy of array.
  8083. else if (pArr == nullptr || scriptContext->GetConfig()->IsES6SpeciesEnabled())
  8084. {
  8085. JS_REENTRANT(jsReentLock, newObj = ArraySpeciesCreate(obj, length, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor));
  8086. }
  8087. if (newObj == nullptr)
  8088. {
  8089. if (length > UINT_MAX)
  8090. {
  8091. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  8092. }
  8093. newArr = scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(length));
  8094. newArr->EnsureHead<Var>();
  8095. newObj = newArr;
  8096. }
  8097. else
  8098. {
  8099. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  8100. if (JavascriptArray::Is(newObj))
  8101. {
  8102. #if ENABLE_COPYONACCESS_ARRAY
  8103. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
  8104. #endif
  8105. newArr = JavascriptArray::FromVar(newObj);
  8106. }
  8107. }
  8108. Var element = nullptr;
  8109. Var mappedValue = nullptr;
  8110. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8111. CallFlags callBackFnflags = CallFlags_Value;
  8112. CallInfo callBackFnInfo = CallInfo(callBackFnflags, 4);
  8113. // We at least have to have newObj as a valid object
  8114. Assert(newObj);
  8115. // The ArraySpeciesCreate call above could have converted the source array into an ES5Array. If this happens
  8116. // we will process the array elements like an ES5Array.
  8117. if (pArr && !JavascriptArray::Is(obj))
  8118. {
  8119. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  8120. pArr = nullptr;
  8121. }
  8122. if (pArr != nullptr)
  8123. {
  8124. // If source is a JavascriptArray, newObj may or may not be an array based on what was in source's constructor property
  8125. Assert(length <= UINT_MAX);
  8126. for (uint32 k = 0; k < (uint32)length; k++)
  8127. {
  8128. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(k, &element));
  8129. if (!gotItem)
  8130. {
  8131. continue;
  8132. }
  8133. JS_REENTRANT(jsReentLock,
  8134. mappedValue = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, callBackFnInfo, thisArg,
  8135. element,
  8136. JavascriptNumber::ToVar(k, scriptContext),
  8137. pArr));
  8138. // If newArr is a valid pointer, then we constructed an array to return. Otherwise we need to do generic object operations
  8139. if (newArr && isBuiltinArrayCtor)
  8140. {
  8141. newArr->DirectSetItemAt(k, mappedValue);
  8142. }
  8143. else
  8144. {
  8145. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, k, mappedValue), scriptContext, k));
  8146. }
  8147. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  8148. // we will process the rest of the array elements like an ES5Array.
  8149. if (!JavascriptArray::Is(obj))
  8150. {
  8151. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  8152. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::MapObjectHelper<T>(obj, length, k + 1, newObj, newArr, isBuiltinArrayCtor, callBackFn, thisArg, scriptContext));
  8153. }
  8154. }
  8155. }
  8156. else if (typedArrayBase != nullptr)
  8157. {
  8158. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  8159. // Source is a TypedArray, we may have tried to call a constructor, but newObj may not be a TypedArray (or an array either)
  8160. TypedArrayBase* newTypedArray = nullptr;
  8161. if (TypedArrayBase::Is(newObj))
  8162. {
  8163. newTypedArray = TypedArrayBase::FromVar(newObj);
  8164. }
  8165. else
  8166. {
  8167. AssertAndFailFast(newArr != nullptr);
  8168. }
  8169. Assert(length <= UINT_MAX);
  8170. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  8171. for (uint32 k = 0; k < end; k++)
  8172. {
  8173. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  8174. element = typedArrayBase->DirectGetItem(k);
  8175. JS_REENTRANT(jsReentLock,
  8176. mappedValue = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, callBackFnInfo, thisArg,
  8177. element,
  8178. JavascriptNumber::ToVar(k, scriptContext),
  8179. obj));
  8180. // If newObj is a TypedArray, set the mappedValue directly, otherwise it should be an array, set that item to that array
  8181. if (newTypedArray)
  8182. {
  8183. JS_REENTRANT(jsReentLock, newTypedArray->DirectSetItem(k, mappedValue));
  8184. }
  8185. else
  8186. {
  8187. newArr->SetItem(k, mappedValue, PropertyOperation_None);
  8188. }
  8189. }
  8190. }
  8191. else
  8192. {
  8193. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::MapObjectHelper<T>(obj, length, 0u, newObj, newArr, isBuiltinArrayCtor, callBackFn, thisArg, scriptContext));
  8194. }
  8195. #ifdef VALIDATE_ARRAY
  8196. if (JavascriptArray::Is(newObj))
  8197. {
  8198. newArr->ValidateArray();
  8199. }
  8200. #endif
  8201. return newObj;
  8202. }
  8203. template<typename T>
  8204. Var JavascriptArray::MapObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* newObj, JavascriptArray* newArr,
  8205. bool isBuiltinArrayCtor, RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
  8206. {
  8207. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8208. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8209. CallFlags callBackFnflags = CallFlags_Value;
  8210. CallInfo callBackFnInfo = CallInfo(callBackFnflags, 4);
  8211. Var element = nullptr;
  8212. Var mappedValue = nullptr;
  8213. for (T k = start; k < length; k++)
  8214. {
  8215. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  8216. if (hasItem)
  8217. {
  8218. JS_REENTRANT(jsReentLock,
  8219. element = JavascriptOperators::GetItem(obj, k, scriptContext),
  8220. mappedValue = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, callBackFnInfo, thisArg,
  8221. element,
  8222. JavascriptNumber::ToVar(k, scriptContext),
  8223. obj));
  8224. if (newArr && isBuiltinArrayCtor)
  8225. {
  8226. newArr->SetItem((uint32)k, mappedValue, PropertyOperation_None);
  8227. }
  8228. else
  8229. {
  8230. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, BigIndex(k), mappedValue), scriptContext, BigIndex(k)));
  8231. }
  8232. }
  8233. }
  8234. #ifdef VALIDATE_ARRAY
  8235. if (JavascriptArray::Is(newObj))
  8236. {
  8237. newArr->ValidateArray();
  8238. }
  8239. #endif
  8240. return newObj;
  8241. }
  8242. Var JavascriptArray::EntryFilter(RecyclableObject* function, CallInfo callInfo, ...)
  8243. {
  8244. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8245. ARGUMENTS(args, callInfo);
  8246. ScriptContext* scriptContext = function->GetScriptContext();
  8247. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8248. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.filter"));
  8249. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_filter);
  8250. Assert(!(callInfo.Flags & CallFlags_New));
  8251. if (args.Info.Count == 0)
  8252. {
  8253. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.filter"));
  8254. }
  8255. BigIndex length;
  8256. JavascriptArray* pArr = nullptr;
  8257. RecyclableObject* obj = nullptr;
  8258. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.filter"), &pArr, &obj, &length));
  8259. if (length.IsSmallIndex())
  8260. {
  8261. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FilterHelper(pArr, obj, length.GetSmallIndex(), args, scriptContext));
  8262. }
  8263. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FilterHelper(pArr, obj, length.GetBigIndex(), args, scriptContext));
  8264. }
  8265. template <typename T>
  8266. Var JavascriptArray::FilterHelper(JavascriptArray* pArr, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  8267. {
  8268. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8269. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  8270. {
  8271. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.filter"));
  8272. }
  8273. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  8274. Var thisArg = nullptr;
  8275. if (args.Info.Count > 2)
  8276. {
  8277. thisArg = args[2];
  8278. }
  8279. else
  8280. {
  8281. thisArg = scriptContext->GetLibrary()->GetUndefined();
  8282. }
  8283. // 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.
  8284. bool isBuiltinArrayCtor = true;
  8285. JS_REENTRANT(jsReentLock, RecyclableObject* newObj = ArraySpeciesCreate(obj, 0, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor));
  8286. JavascriptArray* newArr = nullptr;
  8287. if (newObj == nullptr)
  8288. {
  8289. newArr = scriptContext->GetLibrary()->CreateArray(0);
  8290. newArr->EnsureHead<Var>();
  8291. newObj = newArr;
  8292. }
  8293. else
  8294. {
  8295. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  8296. if (JavascriptArray::Is(newObj))
  8297. {
  8298. #if ENABLE_COPYONACCESS_ARRAY
  8299. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
  8300. #endif
  8301. newArr = JavascriptArray::FromVar(newObj);
  8302. }
  8303. }
  8304. // The ArraySpeciesCreate call above could have converted the source array into an ES5Array. If this happens
  8305. // we will process the array elements like an ES5Array.
  8306. if (pArr && !JavascriptArray::Is(obj))
  8307. {
  8308. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  8309. pArr = nullptr;
  8310. }
  8311. Var element = nullptr;
  8312. Var selected = nullptr;
  8313. if (pArr)
  8314. {
  8315. Assert(length <= MaxArrayLength);
  8316. uint32 i = 0;
  8317. Assert(length <= UINT_MAX);
  8318. for (uint32 k = 0; k < (uint32)length; k++)
  8319. {
  8320. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(k, &element));
  8321. if (!gotItem)
  8322. {
  8323. continue;
  8324. }
  8325. JS_REENTRANT(jsReentLock,
  8326. selected = CALL_ENTRYPOINT(scriptContext->GetThreadContext(),
  8327. callBackFn->GetEntryPoint(), callBackFn, CallInfo(CallFlags_Value, 4),
  8328. thisArg,
  8329. element,
  8330. JavascriptNumber::ToVar(k, scriptContext),
  8331. pArr));
  8332. if (JavascriptConversion::ToBoolean(selected, scriptContext))
  8333. {
  8334. // Try to fast path if the return object is an array
  8335. if (newArr && isBuiltinArrayCtor)
  8336. {
  8337. newArr->DirectSetItemAt(i, element);
  8338. }
  8339. else
  8340. {
  8341. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i));
  8342. }
  8343. ++i;
  8344. }
  8345. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  8346. // we will process the rest of the array elements like an ES5Array.
  8347. if (!JavascriptArray::Is(obj))
  8348. {
  8349. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  8350. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FilterObjectHelper<T>(obj, length, k + 1, newArr, newObj, i, callBackFn, thisArg, scriptContext));
  8351. }
  8352. }
  8353. }
  8354. else
  8355. {
  8356. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FilterObjectHelper<T>(obj, length, 0u, newArr, newObj, 0u, callBackFn, thisArg, scriptContext));
  8357. }
  8358. #ifdef VALIDATE_ARRAY
  8359. if (newArr)
  8360. {
  8361. newArr->ValidateArray();
  8362. }
  8363. #endif
  8364. return newObj;
  8365. }
  8366. template <typename T>
  8367. Var JavascriptArray::FilterObjectHelper(RecyclableObject* obj, T length, T start, JavascriptArray* newArr, RecyclableObject* newObj, T newStart,
  8368. RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
  8369. {
  8370. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8371. Var element = nullptr;
  8372. Var selected = nullptr;
  8373. BigIndex i = BigIndex(newStart);
  8374. for (T k = start; k < length; k++)
  8375. {
  8376. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  8377. if (hasItem)
  8378. {
  8379. JS_REENTRANT(jsReentLock,
  8380. element = JavascriptOperators::GetItem(obj, k, scriptContext),
  8381. selected = CALL_ENTRYPOINT(scriptContext->GetThreadContext(),
  8382. callBackFn->GetEntryPoint(), callBackFn, CallInfo(CallFlags_Value, 4),
  8383. thisArg,
  8384. element,
  8385. JavascriptNumber::ToVar(k, scriptContext),
  8386. obj));
  8387. if (JavascriptConversion::ToBoolean(selected, scriptContext))
  8388. {
  8389. if (newArr)
  8390. {
  8391. newArr->GenericDirectSetItemAt(i, element);
  8392. }
  8393. else
  8394. {
  8395. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i));
  8396. }
  8397. ++i;
  8398. }
  8399. }
  8400. }
  8401. #ifdef VALIDATE_ARRAY
  8402. if (newArr)
  8403. {
  8404. newArr->ValidateArray();
  8405. }
  8406. #endif
  8407. return newObj;
  8408. }
  8409. Var JavascriptArray::EntryReduce(RecyclableObject* function, CallInfo callInfo, ...)
  8410. {
  8411. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8412. ARGUMENTS(args, callInfo);
  8413. ScriptContext* scriptContext = function->GetScriptContext();
  8414. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8415. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.reduce"));
  8416. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_reduce);
  8417. Assert(!(callInfo.Flags & CallFlags_New));
  8418. if (args.Info.Count == 0)
  8419. {
  8420. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reduce"));
  8421. }
  8422. BigIndex length;
  8423. JavascriptArray * pArr = nullptr;
  8424. RecyclableObject* obj = nullptr;
  8425. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.reduce"), &pArr, &obj, &length));
  8426. if (length.IsSmallIndex())
  8427. {
  8428. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  8429. }
  8430. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  8431. }
  8432. // Array.prototype.reduce as described in ES6.0 (draft 22) Section 22.1.3.18
  8433. template <typename T>
  8434. Var JavascriptArray::ReduceHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  8435. {
  8436. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8437. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  8438. {
  8439. if (typedArrayBase != nullptr)
  8440. {
  8441. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.reduce"));
  8442. }
  8443. else
  8444. {
  8445. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.reduce"));
  8446. }
  8447. }
  8448. // If we came from Array.prototype.reduce and source object is not a JavascriptArray, source could be a TypedArray
  8449. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  8450. {
  8451. typedArrayBase = TypedArrayBase::FromVar(obj);
  8452. }
  8453. T k = 0;
  8454. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  8455. Var accumulator = nullptr;
  8456. Var element = nullptr;
  8457. if (args.Info.Count > 2)
  8458. {
  8459. accumulator = args[2];
  8460. }
  8461. else
  8462. {
  8463. if (length == 0)
  8464. {
  8465. JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
  8466. }
  8467. bool bPresent = false;
  8468. if (pArr)
  8469. {
  8470. for (; k < length && bPresent == false; k++)
  8471. {
  8472. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull((uint32)k, &element));
  8473. if (!gotItem)
  8474. {
  8475. continue;
  8476. }
  8477. bPresent = true;
  8478. accumulator = element;
  8479. }
  8480. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  8481. // we will process the array elements like an ES5Array.
  8482. if (!JavascriptArray::Is(obj))
  8483. {
  8484. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  8485. pArr = nullptr;
  8486. }
  8487. }
  8488. else if (typedArrayBase)
  8489. {
  8490. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  8491. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  8492. for (; k < end && bPresent == false; k++)
  8493. {
  8494. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  8495. element = typedArrayBase->DirectGetItem((uint32)k);
  8496. bPresent = true;
  8497. accumulator = element;
  8498. }
  8499. }
  8500. else
  8501. {
  8502. for (; k < length && bPresent == false; k++)
  8503. {
  8504. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  8505. if (hasItem)
  8506. {
  8507. JS_REENTRANT(jsReentLock, accumulator = JavascriptOperators::GetItem(obj, k, scriptContext));
  8508. bPresent = true;
  8509. }
  8510. }
  8511. }
  8512. if (bPresent == false)
  8513. {
  8514. JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
  8515. }
  8516. }
  8517. Assert(accumulator);
  8518. Var undefinedValue = scriptContext->GetLibrary()->GetUndefined();
  8519. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8520. CallFlags flags = CallFlags_Value;
  8521. if (pArr)
  8522. {
  8523. for (; k < length; k++)
  8524. {
  8525. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull((uint32)k, &element));
  8526. if (!gotItem)
  8527. {
  8528. continue;
  8529. }
  8530. JS_REENTRANT(jsReentLock,
  8531. accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 5), undefinedValue,
  8532. accumulator,
  8533. element,
  8534. JavascriptNumber::ToVar(k, scriptContext),
  8535. pArr));
  8536. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  8537. // we will process the rest of the array elements like an ES5Array.
  8538. if (!JavascriptArray::Is(obj))
  8539. {
  8540. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  8541. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceObjectHelper<T>(obj, length, k + 1, callBackFn, accumulator, scriptContext));
  8542. }
  8543. }
  8544. }
  8545. else if (typedArrayBase)
  8546. {
  8547. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  8548. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  8549. for (; k < end; k++)
  8550. {
  8551. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  8552. element = typedArrayBase->DirectGetItem((uint32)k);
  8553. JS_REENTRANT(jsReentLock,
  8554. accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 5), undefinedValue,
  8555. accumulator,
  8556. element,
  8557. JavascriptNumber::ToVar(k, scriptContext),
  8558. typedArrayBase));
  8559. }
  8560. }
  8561. else
  8562. {
  8563. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceObjectHelper<T>(obj, length, k, callBackFn, accumulator, scriptContext));
  8564. }
  8565. return accumulator;
  8566. }
  8567. template <typename T>
  8568. Var JavascriptArray::ReduceObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* callBackFn, Var accumulator, ScriptContext* scriptContext)
  8569. {
  8570. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8571. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8572. CallFlags flags = CallFlags_Value;
  8573. Var element = nullptr;
  8574. for (T k = start; k < length; k++)
  8575. {
  8576. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  8577. if (hasItem)
  8578. {
  8579. JS_REENTRANT(jsReentLock,
  8580. element = JavascriptOperators::GetItem(obj, k, scriptContext),
  8581. accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 5), scriptContext->GetLibrary()->GetUndefined(),
  8582. accumulator,
  8583. element,
  8584. JavascriptNumber::ToVar(k, scriptContext),
  8585. obj));
  8586. }
  8587. }
  8588. return accumulator;
  8589. }
  8590. Var JavascriptArray::EntryReduceRight(RecyclableObject* function, CallInfo callInfo, ...)
  8591. {
  8592. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8593. ARGUMENTS(args, callInfo);
  8594. ScriptContext* scriptContext = function->GetScriptContext();
  8595. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8596. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.reduceRight"));
  8597. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_reduceRight);
  8598. Assert(!(callInfo.Flags & CallFlags_New));
  8599. if (args.Info.Count == 0)
  8600. {
  8601. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reduceRight"));
  8602. }
  8603. BigIndex length;
  8604. JavascriptArray * pArr = nullptr;
  8605. RecyclableObject* obj = nullptr;
  8606. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.reduceRight"), &pArr, &obj, &length));
  8607. if (length.IsSmallIndex())
  8608. {
  8609. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceRightHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  8610. }
  8611. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceRightHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  8612. }
  8613. // Array.prototype.reduceRight as described in ES6.0 (draft 22) Section 22.1.3.19
  8614. template <typename T>
  8615. Var JavascriptArray::ReduceRightHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  8616. {
  8617. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8618. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  8619. {
  8620. if (typedArrayBase != nullptr)
  8621. {
  8622. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.reduceRight"));
  8623. }
  8624. else
  8625. {
  8626. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.reduceRight"));
  8627. }
  8628. }
  8629. // If we came from Array.prototype.reduceRight and source object is not a JavascriptArray, source could be a TypedArray
  8630. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  8631. {
  8632. typedArrayBase = TypedArrayBase::FromVar(obj);
  8633. }
  8634. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  8635. Var accumulator = nullptr;
  8636. Var element = nullptr;
  8637. T k = 0;
  8638. T index = 0;
  8639. if (args.Info.Count > 2)
  8640. {
  8641. accumulator = args[2];
  8642. }
  8643. else
  8644. {
  8645. if (length == 0)
  8646. {
  8647. JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
  8648. }
  8649. bool bPresent = false;
  8650. if (pArr)
  8651. {
  8652. for (; k < length && bPresent == false; k++)
  8653. {
  8654. index = length - k - 1;
  8655. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull((uint32)index, &element));
  8656. if (!gotItem)
  8657. {
  8658. continue;
  8659. }
  8660. bPresent = true;
  8661. accumulator = element;
  8662. }
  8663. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  8664. // we will process the array elements like an ES5Array.
  8665. if (!JavascriptArray::Is(obj))
  8666. {
  8667. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  8668. pArr = nullptr;
  8669. }
  8670. }
  8671. else if (typedArrayBase)
  8672. {
  8673. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  8674. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  8675. for (; k < end && bPresent == false; k++)
  8676. {
  8677. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  8678. index = length - k - 1;
  8679. element = typedArrayBase->DirectGetItem((uint32)index);
  8680. bPresent = true;
  8681. accumulator = element;
  8682. }
  8683. }
  8684. else
  8685. {
  8686. for (; k < length && bPresent == false; k++)
  8687. {
  8688. index = length - k - 1;
  8689. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, index));
  8690. if (hasItem)
  8691. {
  8692. JS_REENTRANT(jsReentLock, accumulator = JavascriptOperators::GetItem(obj, index, scriptContext));
  8693. bPresent = true;
  8694. }
  8695. }
  8696. }
  8697. if (bPresent == false)
  8698. {
  8699. JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
  8700. }
  8701. }
  8702. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8703. CallFlags flags = CallFlags_Value;
  8704. Var undefinedValue = scriptContext->GetLibrary()->GetUndefined();
  8705. if (pArr)
  8706. {
  8707. for (; k < length; k++)
  8708. {
  8709. index = length - k - 1;
  8710. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull((uint32)index, &element));
  8711. if (!gotItem)
  8712. {
  8713. continue;
  8714. }
  8715. JS_REENTRANT(jsReentLock,
  8716. accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 5), undefinedValue,
  8717. accumulator,
  8718. element,
  8719. JavascriptNumber::ToVar(index, scriptContext),
  8720. pArr));
  8721. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  8722. // we will process the rest of the array elements like an ES5Array.
  8723. if (!JavascriptArray::Is(obj))
  8724. {
  8725. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  8726. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceRightObjectHelper<T>(obj, length, k + 1, callBackFn, accumulator, scriptContext));
  8727. }
  8728. }
  8729. }
  8730. else if (typedArrayBase)
  8731. {
  8732. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  8733. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  8734. for (; k < end; k++)
  8735. {
  8736. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  8737. index = length - k - 1;
  8738. element = typedArrayBase->DirectGetItem((uint32)index);
  8739. JS_REENTRANT(jsReentLock,
  8740. accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 5), undefinedValue,
  8741. accumulator,
  8742. element,
  8743. JavascriptNumber::ToVar(index, scriptContext),
  8744. typedArrayBase));
  8745. }
  8746. }
  8747. else
  8748. {
  8749. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceRightObjectHelper<T>(obj, length, k, callBackFn, accumulator, scriptContext));
  8750. }
  8751. return accumulator;
  8752. }
  8753. template <typename T>
  8754. Var JavascriptArray::ReduceRightObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* callBackFn, Var accumulator, ScriptContext* scriptContext)
  8755. {
  8756. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8757. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8758. CallFlags flags = CallFlags_Value;
  8759. Var element = nullptr;
  8760. T index = 0;
  8761. for (T k = start; k < length; k++)
  8762. {
  8763. index = length - k - 1;
  8764. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, index));
  8765. if (hasItem)
  8766. {
  8767. JS_REENTRANT(jsReentLock,
  8768. element = JavascriptOperators::GetItem(obj, index, scriptContext),
  8769. accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(),
  8770. callBackFn, CallInfo(flags, 5), scriptContext->GetLibrary()->GetUndefined(),
  8771. accumulator,
  8772. element,
  8773. JavascriptNumber::ToVar(index, scriptContext),
  8774. obj));
  8775. }
  8776. }
  8777. return accumulator;
  8778. }
  8779. Var JavascriptArray::EntryFrom(RecyclableObject* function, CallInfo callInfo, ...)
  8780. {
  8781. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8782. ARGUMENTS(args, callInfo);
  8783. ScriptContext* scriptContext = function->GetScriptContext();
  8784. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8785. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.from"));
  8786. Assert(!(callInfo.Flags & CallFlags_New));
  8787. JavascriptLibrary* library = scriptContext->GetLibrary();
  8788. RecyclableObject* constructor = nullptr;
  8789. if (JavascriptOperators::IsConstructor(args[0]))
  8790. {
  8791. constructor = RecyclableObject::FromVar(args[0]);
  8792. }
  8793. RecyclableObject* items = nullptr;
  8794. if (args.Info.Count < 2 || !JavascriptConversion::ToObject(args[1], scriptContext, &items))
  8795. {
  8796. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedObject, _u("Array.from"));
  8797. }
  8798. JavascriptArray* itemsArr = nullptr;
  8799. if (JavascriptArray::Is(items))
  8800. {
  8801. #if ENABLE_COPYONACCESS_ARRAY
  8802. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(items);
  8803. #endif
  8804. itemsArr = JavascriptArray::FromVar(items);
  8805. }
  8806. bool mapping = false;
  8807. JavascriptFunction* mapFn = nullptr;
  8808. Var mapFnThisArg = nullptr;
  8809. if (args.Info.Count >= 3 && !JavascriptOperators::IsUndefinedObject(args[2]))
  8810. {
  8811. if (!JavascriptFunction::Is(args[2]))
  8812. {
  8813. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.from"));
  8814. }
  8815. mapFn = JavascriptFunction::FromVar(args[2]);
  8816. if (args.Info.Count >= 4)
  8817. {
  8818. mapFnThisArg = args[3];
  8819. }
  8820. else
  8821. {
  8822. mapFnThisArg = library->GetUndefined();
  8823. }
  8824. mapping = true;
  8825. }
  8826. RecyclableObject* newObj = nullptr;
  8827. JavascriptArray* newArr = nullptr;
  8828. JS_REENTRANT(jsReentLock, RecyclableObject* iterator = JavascriptOperators::GetIterator(items, scriptContext, true /* optional */));
  8829. if (iterator != nullptr)
  8830. {
  8831. if (constructor)
  8832. {
  8833. Js::Var constructorArgs[] = { constructor };
  8834. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  8835. JS_REENTRANT(jsReentLock, newObj = RecyclableObject::FromVar(JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext)));
  8836. if (JavascriptArray::Is(newObj))
  8837. {
  8838. #if ENABLE_COPYONACCESS_ARRAY
  8839. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
  8840. #endif
  8841. newArr = JavascriptArray::FromVar(newObj);
  8842. }
  8843. }
  8844. else
  8845. {
  8846. newArr = scriptContext->GetLibrary()->CreateArray(0);
  8847. newArr->EnsureHead<Var>();
  8848. newObj = newArr;
  8849. }
  8850. uint32 k = 0;
  8851. JS_REENTRANT(jsReentLock, JavascriptOperators::DoIteratorStepAndValue(iterator, scriptContext, [&](Var nextValue) {
  8852. if (mapping)
  8853. {
  8854. Assert(mapFn != nullptr);
  8855. Assert(mapFnThisArg != nullptr);
  8856. Js::Var mapFnArgs[] = { mapFnThisArg, nextValue, JavascriptNumber::ToVar(k, scriptContext) };
  8857. Js::CallInfo mapFnCallInfo(Js::CallFlags_Value, _countof(mapFnArgs));
  8858. nextValue = mapFn->CallFunction(Js::Arguments(mapFnCallInfo, mapFnArgs));
  8859. }
  8860. if (newArr)
  8861. {
  8862. newArr->SetItem(k, nextValue, PropertyOperation_None);
  8863. }
  8864. else
  8865. {
  8866. ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, k, nextValue), scriptContext, k);
  8867. }
  8868. k++;
  8869. }));
  8870. JS_REENTRANT(jsReentLock, JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(k, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  8871. }
  8872. else
  8873. {
  8874. JS_REENTRANT(jsReentLock, int64 len = (int64)OP_GetLength(items, scriptContext));
  8875. if (constructor)
  8876. {
  8877. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(len, scriptContext) };
  8878. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  8879. JS_REENTRANT(jsReentLock, newObj = RecyclableObject::FromVar(JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext)));
  8880. if (JavascriptArray::Is(newObj))
  8881. {
  8882. #if ENABLE_COPYONACCESS_ARRAY
  8883. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
  8884. #endif
  8885. newArr = JavascriptArray::FromVar(newObj);
  8886. }
  8887. }
  8888. else
  8889. {
  8890. // Abstract operation ArrayCreate throws RangeError if length argument is > 2^32 -1
  8891. if (len > MaxArrayLength)
  8892. {
  8893. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect, _u("Array.from"));
  8894. }
  8895. // Static cast len should be valid (len < 2^32) or we would throw above
  8896. newArr = scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(len));
  8897. newArr->EnsureHead<Var>();
  8898. newObj = newArr;
  8899. }
  8900. uint32 k = 0;
  8901. for ( ; k < len; k++)
  8902. {
  8903. Var kValue;
  8904. if (itemsArr)
  8905. {
  8906. JS_REENTRANT(jsReentLock, kValue = itemsArr->DirectGetItem(k));
  8907. }
  8908. else
  8909. {
  8910. JS_REENTRANT(jsReentLock, kValue = JavascriptOperators::OP_GetElementI_UInt32(items, k, scriptContext));
  8911. }
  8912. if (mapping)
  8913. {
  8914. Assert(mapFn != nullptr);
  8915. Assert(mapFnThisArg != nullptr);
  8916. Js::Var mapFnArgs[] = { mapFnThisArg, kValue, JavascriptNumber::ToVar(k, scriptContext) };
  8917. Js::CallInfo mapFnCallInfo(Js::CallFlags_Value, _countof(mapFnArgs));
  8918. JS_REENTRANT(jsReentLock, kValue = mapFn->CallFunction(Js::Arguments(mapFnCallInfo, mapFnArgs)));
  8919. }
  8920. if (newArr)
  8921. {
  8922. newArr->SetItem(k, kValue, PropertyOperation_None);
  8923. }
  8924. else
  8925. {
  8926. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, k, kValue), scriptContext, k));
  8927. }
  8928. }
  8929. JS_REENTRANT(jsReentLock, JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(len, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  8930. }
  8931. return newObj;
  8932. }
  8933. Var JavascriptArray::EntryOf(RecyclableObject* function, CallInfo callInfo, ...)
  8934. {
  8935. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8936. ARGUMENTS(args, callInfo);
  8937. ScriptContext* scriptContext = function->GetScriptContext();
  8938. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8939. Assert(!(callInfo.Flags & CallFlags_New));
  8940. if (args.Info.Count == 0)
  8941. {
  8942. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.of"));
  8943. }
  8944. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::OfHelper(false, args, scriptContext));
  8945. }
  8946. Var JavascriptArray::EntryGetterSymbolSpecies(RecyclableObject* function, CallInfo callInfo, ...)
  8947. {
  8948. ARGUMENTS(args, callInfo);
  8949. Assert(args.Info.Count > 0);
  8950. return args[0];
  8951. }
  8952. // Array.of and %TypedArray%.of as described in ES6.0 (draft 22) Section 22.1.2.2 and 22.2.2.2
  8953. Var JavascriptArray::OfHelper(bool isTypedArrayEntryPoint, Arguments& args, ScriptContext* scriptContext)
  8954. {
  8955. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8956. Assert(args.Info.Count > 0);
  8957. // args.Info.Count cannot equal zero or we would have thrown above so no chance of underflowing
  8958. uint32 len = args.Info.Count - 1;
  8959. Var newObj = nullptr;
  8960. JavascriptArray* newArr = nullptr;
  8961. TypedArrayBase* newTypedArray = nullptr;
  8962. bool isBuiltinArrayCtor = true;
  8963. if (JavascriptOperators::IsConstructor(args[0]))
  8964. {
  8965. RecyclableObject* constructor = RecyclableObject::FromVar(args[0]);
  8966. isBuiltinArrayCtor = (constructor == scriptContext->GetLibrary()->GetArrayConstructor());
  8967. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(len, scriptContext) };
  8968. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  8969. if (isTypedArrayEntryPoint)
  8970. {
  8971. JS_REENTRANT(jsReentLock, newObj = TypedArrayBase::TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), len, scriptContext));
  8972. }
  8973. else
  8974. {
  8975. JS_REENTRANT(jsReentLock, newObj = JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext));
  8976. }
  8977. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  8978. if (JavascriptArray::Is(newObj))
  8979. {
  8980. #if ENABLE_COPYONACCESS_ARRAY
  8981. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
  8982. #endif
  8983. newArr = JavascriptArray::FromVar(newObj);
  8984. }
  8985. else if (TypedArrayBase::Is(newObj))
  8986. {
  8987. newTypedArray = TypedArrayBase::FromVar(newObj);
  8988. }
  8989. }
  8990. else
  8991. {
  8992. // We only throw when the constructor property is not a constructor function in the TypedArray version
  8993. if (isTypedArrayEntryPoint)
  8994. {
  8995. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedFunction, _u("[TypedArray].of"));
  8996. }
  8997. newArr = scriptContext->GetLibrary()->CreateArray(len);
  8998. newArr->EnsureHead<Var>();
  8999. newObj = newArr;
  9000. }
  9001. // At least we have a new object of some kind
  9002. Assert(newObj);
  9003. if (isBuiltinArrayCtor)
  9004. {
  9005. for (uint32 k = 0; k < len; k++)
  9006. {
  9007. Var kValue = args[k + 1];
  9008. newArr->DirectSetItemAt(k, kValue);
  9009. }
  9010. }
  9011. else if (newTypedArray)
  9012. {
  9013. for (uint32 k = 0; k < len; k++)
  9014. {
  9015. Var kValue = args[k + 1];
  9016. JS_REENTRANT(jsReentLock, newTypedArray->DirectSetItem(k, kValue));
  9017. }
  9018. }
  9019. else
  9020. {
  9021. for (uint32 k = 0; k < len; k++)
  9022. {
  9023. Var kValue = args[k + 1];
  9024. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(RecyclableObject::FromVar(newObj), k, kValue), scriptContext, k));
  9025. }
  9026. }
  9027. if (!isTypedArrayEntryPoint)
  9028. {
  9029. // Set length if we are in the Array version of the function
  9030. JS_REENTRANT(jsReentLock, JavascriptOperators::OP_SetProperty(newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(len, scriptContext), scriptContext, nullptr, PropertyOperation_ThrowIfNotExtensible));
  9031. }
  9032. return newObj;
  9033. }
  9034. JavascriptString* JavascriptArray::ToLocaleStringHelper(Var value, ScriptContext* scriptContext)
  9035. {
  9036. TypeId typeId = JavascriptOperators::GetTypeId(value);
  9037. if (typeId == TypeIds_Null || typeId == TypeIds_Undefined)
  9038. {
  9039. return scriptContext->GetLibrary()->GetEmptyString();
  9040. }
  9041. else
  9042. {
  9043. return JavascriptConversion::ToLocaleString(value, scriptContext);
  9044. }
  9045. }
  9046. inline BOOL JavascriptArray::IsFullArray() const
  9047. {
  9048. if (head && head->length == length)
  9049. {
  9050. AssertMsg(head->next == 0 && head->left == 0, "Invalid Array");
  9051. return true;
  9052. }
  9053. return (0 == length);
  9054. }
  9055. /*
  9056. * IsFillFromPrototypes
  9057. * - Check the array has no missing values and only head segment.
  9058. * - Also ensure if the lengths match.
  9059. */
  9060. bool JavascriptArray::IsFillFromPrototypes()
  9061. {
  9062. return !(this->head->next == nullptr && this->HasNoMissingValues() && this->length == this->head->length);
  9063. }
  9064. // Fill all missing value in the array and fill it from prototype between startIndex and limitIndex
  9065. // typically startIndex = 0 and limitIndex = length. From start of the array till end of the array.
  9066. void JavascriptArray::FillFromPrototypes(uint32 startIndex, uint32 limitIndex)
  9067. {
  9068. if (startIndex >= limitIndex)
  9069. {
  9070. return;
  9071. }
  9072. RecyclableObject* prototype = this->GetPrototype();
  9073. // Fill all missing values by walking through prototype
  9074. while (JavascriptOperators::GetTypeId(prototype) != TypeIds_Null)
  9075. {
  9076. ForEachOwnMissingArrayIndexOfObject(this, nullptr, prototype, startIndex, limitIndex,0, [this](uint32 index, Var value) {
  9077. this->SetItem(index, value, PropertyOperation_None);
  9078. });
  9079. prototype = prototype->GetPrototype();
  9080. }
  9081. #ifdef VALIDATE_ARRAY
  9082. ValidateArray();
  9083. #endif
  9084. }
  9085. //
  9086. // JavascriptArray requires head->left == 0 for fast path Get.
  9087. //
  9088. template<typename T>
  9089. void JavascriptArray::EnsureHeadStartsFromZero(Recycler * recycler)
  9090. {
  9091. if (head == nullptr || head->left != 0)
  9092. {
  9093. // This is used to fix up altered arrays.
  9094. // any SegmentMap would be invalid at this point.
  9095. ClearSegmentMap();
  9096. //
  9097. // We could OOM and throw when allocating new empty head, resulting in a corrupted array. Need
  9098. // some protection here. Save the head and switch this array to EmptySegment. Will be restored
  9099. // correctly if allocating new segment succeeds.
  9100. //
  9101. SparseArraySegment<T>* savedHead = SparseArraySegment<T>::From(this->head);
  9102. SparseArraySegment<T>* savedLastUsedSegment = (SparseArraySegment<T>*)this->GetLastUsedSegment();
  9103. SetHeadAndLastUsedSegment(const_cast<SparseArraySegmentBase*>(EmptySegment));
  9104. SparseArraySegment<T> *newSeg = SparseArraySegment<T>::AllocateSegment(recycler, 0, 0, savedHead);
  9105. newSeg->next = savedHead;
  9106. this->head = newSeg;
  9107. SetHasNoMissingValues();
  9108. this->SetLastUsedSegment(savedLastUsedSegment);
  9109. }
  9110. }
  9111. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  9112. void JavascriptArray::CheckForceES5Array()
  9113. {
  9114. if (Configuration::Global.flags.ForceES5Array)
  9115. {
  9116. // There's a bad interaction with the jitted code for native array creation here.
  9117. // ForceES5Array doesn't interact well with native arrays
  9118. if (PHASE_OFF1(NativeArrayPhase))
  9119. {
  9120. GetTypeHandler()->ConvertToTypeWithItemAttributes(this);
  9121. }
  9122. }
  9123. }
  9124. #endif
  9125. template <typename Fn>
  9126. void JavascriptArray::ForEachOwnMissingArrayIndexOfObject(JavascriptArray *baseArray, JavascriptArray *destArray, RecyclableObject* obj, uint32 startIndex, uint32 limitIndex, uint32 destIndex, Fn fn)
  9127. {
  9128. JS_REENTRANCY_LOCK(jsReentLock, baseArray->GetScriptContext()->GetThreadContext());
  9129. Assert(DynamicObject::IsAnyArray(obj) || JavascriptOperators::IsObject(obj));
  9130. Var oldValue;
  9131. JavascriptArray* arr = nullptr;
  9132. if (DynamicObject::IsAnyArray(obj))
  9133. {
  9134. arr = JavascriptArray::FromAnyArray(obj);
  9135. }
  9136. else if (DynamicType::Is(obj->GetTypeId()))
  9137. {
  9138. DynamicObject* dynobj = DynamicObject::FromVar(obj);
  9139. ArrayObject* objectArray = dynobj->GetObjectArray();
  9140. arr = (objectArray && JavascriptArray::IsAnyArray(objectArray)) ? JavascriptArray::FromAnyArray(objectArray) : nullptr;
  9141. }
  9142. if (arr != nullptr)
  9143. {
  9144. if (JavascriptArray::Is(arr))
  9145. {
  9146. arr = EnsureNonNativeArray(arr);
  9147. ArrayElementEnumerator e(arr, startIndex, limitIndex);
  9148. while(e.MoveNext<Var>())
  9149. {
  9150. uint32 index = e.GetIndex();
  9151. if (!baseArray->DirectGetVarItemAt(index, &oldValue, baseArray->GetScriptContext()))
  9152. {
  9153. uint32 n = destIndex + (index - startIndex);
  9154. if (destArray == nullptr || !destArray->DirectGetItemAt(n, &oldValue))
  9155. {
  9156. JS_REENTRANT(jsReentLock, fn(index, e.GetItem<Var>()));
  9157. }
  9158. }
  9159. }
  9160. }
  9161. else
  9162. {
  9163. ScriptContext* scriptContext = obj->GetScriptContext();
  9164. Assert(ES5Array::Is(arr));
  9165. ES5Array* es5Array = ES5Array::FromVar(arr);
  9166. ES5ArrayIndexStaticEnumerator<true> e(es5Array);
  9167. while (e.MoveNext())
  9168. {
  9169. uint32 index = e.GetIndex();
  9170. if (index < startIndex) continue;
  9171. else if (index >= limitIndex) break;
  9172. if (!baseArray->DirectGetVarItemAt(index, &oldValue, baseArray->GetScriptContext()))
  9173. {
  9174. uint32 n = destIndex + (index - startIndex);
  9175. if (destArray == nullptr || !destArray->DirectGetItemAt(n, &oldValue))
  9176. {
  9177. Var value = nullptr;
  9178. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetOwnItem(obj, index, &value, scriptContext));
  9179. if (gotItem)
  9180. {
  9181. JS_REENTRANT(jsReentLock, fn(index, value));
  9182. }
  9183. }
  9184. }
  9185. }
  9186. }
  9187. }
  9188. }
  9189. //
  9190. // ArrayElementEnumerator to enumerate array elements (not including elements from prototypes).
  9191. //
  9192. JavascriptArray::ArrayElementEnumerator::ArrayElementEnumerator(JavascriptArray* arr, uint32 start, uint32 end)
  9193. : start(start), end(min(end, arr->length))
  9194. {
  9195. Init(arr);
  9196. }
  9197. //
  9198. // Initialize this enumerator and prepare for the first MoveNext.
  9199. //
  9200. void JavascriptArray::ArrayElementEnumerator::Init(JavascriptArray* arr)
  9201. {
  9202. // Find start segment
  9203. seg = (arr ? arr->GetBeginLookupSegment(start) : nullptr);
  9204. while (seg && (seg->left + seg->length <= start))
  9205. {
  9206. seg = seg->next;
  9207. }
  9208. // Set start index and endIndex
  9209. if (seg)
  9210. {
  9211. if (seg->left >= end)
  9212. {
  9213. seg = nullptr;
  9214. }
  9215. else
  9216. {
  9217. // set index to be at target index - 1, so MoveNext will move to target
  9218. index = max(seg->left, start) - seg->left - 1;
  9219. endIndex = min(end - seg->left, seg->length);
  9220. }
  9221. }
  9222. }
  9223. //
  9224. // Move to the next element if available.
  9225. //
  9226. template<typename T>
  9227. inline bool JavascriptArray::ArrayElementEnumerator::MoveNext()
  9228. {
  9229. while (seg)
  9230. {
  9231. // Look for next non-null item in current segment
  9232. while (++index < endIndex)
  9233. {
  9234. if (!SparseArraySegment<T>::IsMissingItem(&((SparseArraySegment<T>*)seg)->elements[index]))
  9235. {
  9236. return true;
  9237. }
  9238. }
  9239. // Move to next segment
  9240. seg = seg->next;
  9241. if (seg)
  9242. {
  9243. if (seg->left >= end)
  9244. {
  9245. seg = nullptr;
  9246. break;
  9247. }
  9248. else
  9249. {
  9250. index = static_cast<uint32>(-1);
  9251. endIndex = min(end - seg->left, seg->length);
  9252. }
  9253. }
  9254. }
  9255. return false;
  9256. }
  9257. //
  9258. // Get current array element index.
  9259. //
  9260. uint32 JavascriptArray::ArrayElementEnumerator::GetIndex() const
  9261. {
  9262. Assert(seg && index < seg->length && index < endIndex);
  9263. return seg->left + index;
  9264. }
  9265. //
  9266. // Get current array element value.
  9267. //
  9268. template<typename T>
  9269. T JavascriptArray::ArrayElementEnumerator::GetItem() const
  9270. {
  9271. Assert(seg && index < seg->length && index < endIndex &&
  9272. !SparseArraySegment<T>::IsMissingItem(&((SparseArraySegment<T>*)seg)->elements[index]));
  9273. return ((SparseArraySegment<T>*)seg)->elements[index];
  9274. }
  9275. //
  9276. // Construct a BigIndex initialized to a given uint32 (small index).
  9277. //
  9278. JavascriptArray::BigIndex::BigIndex(uint32 initIndex)
  9279. : index(initIndex), bigIndex(InvalidIndex)
  9280. {
  9281. //ok if initIndex == InvalidIndex
  9282. }
  9283. //
  9284. // Construct a BigIndex initialized to a given uint64 (large or small index).
  9285. //
  9286. JavascriptArray::BigIndex::BigIndex(uint64 initIndex)
  9287. : index(InvalidIndex), bigIndex(initIndex)
  9288. {
  9289. if (bigIndex < InvalidIndex) // if it's actually small index
  9290. {
  9291. index = static_cast<uint32>(bigIndex);
  9292. bigIndex = InvalidIndex;
  9293. }
  9294. }
  9295. bool JavascriptArray::BigIndex::IsUint32Max() const
  9296. {
  9297. return index == InvalidIndex && bigIndex == InvalidIndex;
  9298. }
  9299. bool JavascriptArray::BigIndex::IsSmallIndex() const
  9300. {
  9301. return index < InvalidIndex;
  9302. }
  9303. uint32 JavascriptArray::BigIndex::GetSmallIndex() const
  9304. {
  9305. Assert(IsSmallIndex());
  9306. return index;
  9307. }
  9308. uint64 JavascriptArray::BigIndex::GetBigIndex() const
  9309. {
  9310. Assert(!IsSmallIndex());
  9311. return bigIndex;
  9312. }
  9313. //
  9314. // Convert this index value to a JS number
  9315. //
  9316. Var JavascriptArray::BigIndex::ToNumber(ScriptContext* scriptContext) const
  9317. {
  9318. if (IsSmallIndex())
  9319. {
  9320. return small_index::ToNumber(index, scriptContext);
  9321. }
  9322. else
  9323. {
  9324. return JavascriptNumber::ToVar(bigIndex, scriptContext);
  9325. }
  9326. }
  9327. //
  9328. // Increment this index by 1.
  9329. //
  9330. const JavascriptArray::BigIndex& JavascriptArray::BigIndex::operator++()
  9331. {
  9332. if (IsSmallIndex())
  9333. {
  9334. ++index;
  9335. // If index reaches InvalidIndex, we will start to use bigIndex which is initially InvalidIndex.
  9336. }
  9337. else
  9338. {
  9339. bigIndex = bigIndex + 1;
  9340. }
  9341. return *this;
  9342. }
  9343. //
  9344. // Decrement this index by 1.
  9345. //
  9346. const JavascriptArray::BigIndex& JavascriptArray::BigIndex::operator--()
  9347. {
  9348. if (IsSmallIndex())
  9349. {
  9350. --index;
  9351. }
  9352. else
  9353. {
  9354. Assert(index == InvalidIndex && bigIndex >= InvalidIndex);
  9355. --bigIndex;
  9356. if (bigIndex < InvalidIndex)
  9357. {
  9358. index = InvalidIndex - 1;
  9359. bigIndex = InvalidIndex;
  9360. }
  9361. }
  9362. return *this;
  9363. }
  9364. JavascriptArray::BigIndex JavascriptArray::BigIndex::operator+(const BigIndex& delta) const
  9365. {
  9366. if (delta.IsSmallIndex())
  9367. {
  9368. return operator+(delta.GetSmallIndex());
  9369. }
  9370. if (IsSmallIndex())
  9371. {
  9372. return index + delta.GetBigIndex();
  9373. }
  9374. return bigIndex + delta.GetBigIndex();
  9375. }
  9376. //
  9377. // Get a new BigIndex representing this + delta.
  9378. //
  9379. JavascriptArray::BigIndex JavascriptArray::BigIndex::operator+(uint32 delta) const
  9380. {
  9381. if (IsSmallIndex())
  9382. {
  9383. uint32 newIndex;
  9384. if (UInt32Math::Add(index, delta, &newIndex))
  9385. {
  9386. return static_cast<uint64>(index) + static_cast<uint64>(delta);
  9387. }
  9388. else
  9389. {
  9390. return newIndex; // ok if newIndex == InvalidIndex
  9391. }
  9392. }
  9393. else
  9394. {
  9395. return bigIndex + static_cast<uint64>(delta);
  9396. }
  9397. }
  9398. bool JavascriptArray::BigIndex::operator==(const BigIndex& rhs) const
  9399. {
  9400. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9401. {
  9402. return this->GetSmallIndex() == rhs.GetSmallIndex();
  9403. }
  9404. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9405. {
  9406. // if lhs is big promote rhs
  9407. return this->GetBigIndex() == (uint64) rhs.GetSmallIndex();
  9408. }
  9409. else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
  9410. {
  9411. // if rhs is big promote lhs
  9412. return ((uint64)this->GetSmallIndex()) == rhs.GetBigIndex();
  9413. }
  9414. return this->GetBigIndex() == rhs.GetBigIndex();
  9415. }
  9416. bool JavascriptArray::BigIndex::operator> (const BigIndex& rhs) const
  9417. {
  9418. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9419. {
  9420. return this->GetSmallIndex() > rhs.GetSmallIndex();
  9421. }
  9422. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9423. {
  9424. // if lhs is big promote rhs
  9425. return this->GetBigIndex() > (uint64)rhs.GetSmallIndex();
  9426. }
  9427. else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
  9428. {
  9429. // if rhs is big promote lhs
  9430. return ((uint64)this->GetSmallIndex()) > rhs.GetBigIndex();
  9431. }
  9432. return this->GetBigIndex() > rhs.GetBigIndex();
  9433. }
  9434. bool JavascriptArray::BigIndex::operator< (const BigIndex& rhs) const
  9435. {
  9436. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9437. {
  9438. return this->GetSmallIndex() < rhs.GetSmallIndex();
  9439. }
  9440. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9441. {
  9442. // if lhs is big promote rhs
  9443. return this->GetBigIndex() < (uint64)rhs.GetSmallIndex();
  9444. }
  9445. else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
  9446. {
  9447. // if rhs is big promote lhs
  9448. return ((uint64)this->GetSmallIndex()) < rhs.GetBigIndex();
  9449. }
  9450. return this->GetBigIndex() < rhs.GetBigIndex();
  9451. }
  9452. bool JavascriptArray::BigIndex::operator<=(const BigIndex& rhs) const
  9453. {
  9454. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9455. {
  9456. return this->GetSmallIndex() <= rhs.GetSmallIndex();
  9457. }
  9458. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9459. {
  9460. // if lhs is big promote rhs
  9461. return this->GetBigIndex() <= (uint64)rhs.GetSmallIndex();
  9462. }
  9463. else if (!rhs.IsSmallIndex() && !this->IsSmallIndex())
  9464. {
  9465. // if rhs is big promote lhs
  9466. return ((uint64)this->GetSmallIndex()) <= rhs.GetBigIndex();
  9467. }
  9468. return this->GetBigIndex() <= rhs.GetBigIndex();
  9469. }
  9470. bool JavascriptArray::BigIndex::operator>=(const BigIndex& rhs) const
  9471. {
  9472. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9473. {
  9474. return this->GetSmallIndex() >= rhs.GetSmallIndex();
  9475. }
  9476. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9477. {
  9478. // if lhs is big promote rhs
  9479. return this->GetBigIndex() >= (uint64)rhs.GetSmallIndex();
  9480. }
  9481. else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
  9482. {
  9483. // if rhs is big promote lhs
  9484. return ((uint64)this->GetSmallIndex()) >= rhs.GetBigIndex();
  9485. }
  9486. return this->GetBigIndex() >= rhs.GetBigIndex();
  9487. }
  9488. BOOL JavascriptArray::BigIndex::GetItem(JavascriptArray* arr, Var* outVal) const
  9489. {
  9490. if (IsSmallIndex())
  9491. {
  9492. return small_index::GetItem(arr, index, outVal);
  9493. }
  9494. else
  9495. {
  9496. ScriptContext* scriptContext = arr->GetScriptContext();
  9497. PropertyRecord const * propertyRecord;
  9498. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9499. return arr->GetProperty(arr, propertyRecord->GetPropertyId(), outVal, NULL, scriptContext);
  9500. }
  9501. }
  9502. BOOL JavascriptArray::BigIndex::SetItem(JavascriptArray* arr, Var newValue) const
  9503. {
  9504. if (IsSmallIndex())
  9505. {
  9506. return small_index::SetItem(arr, index, newValue);
  9507. }
  9508. else
  9509. {
  9510. ScriptContext* scriptContext = arr->GetScriptContext();
  9511. PropertyRecord const * propertyRecord;
  9512. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9513. return arr->SetProperty(propertyRecord->GetPropertyId(), newValue, PropertyOperation_None, NULL);
  9514. }
  9515. }
  9516. void JavascriptArray::BigIndex::SetItemIfNotExist(JavascriptArray* arr, Var newValue) const
  9517. {
  9518. if (IsSmallIndex())
  9519. {
  9520. small_index::SetItemIfNotExist(arr, index, newValue);
  9521. }
  9522. else
  9523. {
  9524. ScriptContext* scriptContext = arr->GetScriptContext();
  9525. PropertyRecord const * propertyRecord;
  9526. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9527. Var oldValue;
  9528. PropertyId propertyId = propertyRecord->GetPropertyId();
  9529. if (!arr->GetProperty(arr, propertyId, &oldValue, NULL, scriptContext))
  9530. {
  9531. arr->SetProperty(propertyId, newValue, PropertyOperation_None, NULL);
  9532. }
  9533. }
  9534. }
  9535. BOOL JavascriptArray::BigIndex::DeleteItem(JavascriptArray* arr) const
  9536. {
  9537. if (IsSmallIndex())
  9538. {
  9539. return small_index::DeleteItem(arr, index);
  9540. }
  9541. else
  9542. {
  9543. ScriptContext* scriptContext = arr->GetScriptContext();
  9544. PropertyRecord const * propertyRecord;
  9545. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9546. return arr->DeleteProperty(propertyRecord->GetPropertyId(), PropertyOperation_None);
  9547. }
  9548. }
  9549. BOOL JavascriptArray::BigIndex::SetItem(RecyclableObject* obj, Var newValue, PropertyOperationFlags flags) const
  9550. {
  9551. if (IsSmallIndex())
  9552. {
  9553. return small_index::SetItem(obj, index, newValue, flags);
  9554. }
  9555. else
  9556. {
  9557. ScriptContext* scriptContext = obj->GetScriptContext();
  9558. PropertyRecord const * propertyRecord;
  9559. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9560. return JavascriptOperators::SetProperty(obj, obj, propertyRecord->GetPropertyId(), newValue, scriptContext, flags);
  9561. }
  9562. }
  9563. BOOL JavascriptArray::BigIndex::DeleteItem(RecyclableObject* obj, PropertyOperationFlags flags) const
  9564. {
  9565. if (IsSmallIndex())
  9566. {
  9567. return small_index::DeleteItem(obj, index, flags);
  9568. }
  9569. else
  9570. {
  9571. PropertyRecord const * propertyRecord;
  9572. JavascriptOperators::GetPropertyIdForInt(bigIndex, obj->GetScriptContext(), &propertyRecord);
  9573. return JavascriptOperators::DeleteProperty(obj, propertyRecord->GetPropertyId(), flags);
  9574. }
  9575. }
  9576. //
  9577. // Truncate the array at start and clone the truncated span as properties starting at dstIndex (asserting dstIndex >= MaxArrayLength).
  9578. //
  9579. void JavascriptArray::TruncateToProperties(const BigIndex& dstIndex, uint32 start)
  9580. {
  9581. Assert(!dstIndex.IsSmallIndex());
  9582. typedef IndexTrace<BigIndex> index_trace;
  9583. BigIndex dst = dstIndex;
  9584. uint32 i = start;
  9585. ArrayElementEnumerator e(this, start);
  9586. while(e.MoveNext<Var>())
  9587. {
  9588. // delete all items not enumerated
  9589. while (i < e.GetIndex())
  9590. {
  9591. index_trace::DeleteItem(this, dst);
  9592. ++i;
  9593. ++dst;
  9594. }
  9595. // Copy over the item
  9596. index_trace::SetItem(this, dst, e.GetItem<Var>());
  9597. ++i;
  9598. ++dst;
  9599. }
  9600. // Delete the rest till length
  9601. while (i < this->length)
  9602. {
  9603. index_trace::DeleteItem(this, dst);
  9604. ++i;
  9605. ++dst;
  9606. }
  9607. // Elements moved, truncate the array at start
  9608. SetLength(start);
  9609. }
  9610. //
  9611. // Copy a srcArray elements (including elements from prototypes) to a dstArray starting from an index.
  9612. //
  9613. void JavascriptArray::InternalCopyArrayElements(JavascriptArray* dstArray, const uint32 dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
  9614. {
  9615. Assert(start < end && end <= srcArray->length);
  9616. uint32 count = 0;
  9617. // iterate on the array itself
  9618. ArrayElementEnumerator e(srcArray, start, end);
  9619. while(e.MoveNext<Var>())
  9620. {
  9621. uint32 n = dstIndex + (e.GetIndex() - start);
  9622. dstArray->DirectSetItemAt(n, e.GetItem<Var>());
  9623. count++;
  9624. }
  9625. // iterate on the array's prototypes only if not all elements found
  9626. if (start + count != end)
  9627. {
  9628. InternalFillFromPrototype(dstArray, dstIndex, srcArray, start, end, count);
  9629. }
  9630. }
  9631. //
  9632. // Faster small_index overload of CopyArrayElements, asserting the uint32 dstIndex won't overflow.
  9633. //
  9634. void JavascriptArray::CopyArrayElements(JavascriptArray* dstArray, uint32 dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
  9635. {
  9636. end = min(end, srcArray->length);
  9637. if (start < end)
  9638. {
  9639. Assert(end - start <= MaxArrayLength - dstIndex);
  9640. InternalCopyArrayElements(dstArray, dstIndex, srcArray, start, end);
  9641. }
  9642. }
  9643. template <typename T>
  9644. void JavascriptArray::CopyAnyArrayElementsToVar(JavascriptArray* dstArray, T dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
  9645. {
  9646. #if ENABLE_COPYONACCESS_ARRAY
  9647. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(srcArray);
  9648. #endif
  9649. #if ENABLE_COPYONACCESS_ARRAY
  9650. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(dstArray);
  9651. #endif
  9652. if (JavascriptNativeIntArray::Is(srcArray))
  9653. {
  9654. CopyNativeIntArrayElementsToVar(dstArray, dstIndex, JavascriptNativeIntArray::FromVar(srcArray), start, end);
  9655. }
  9656. else if (JavascriptNativeFloatArray::Is(srcArray))
  9657. {
  9658. CopyNativeFloatArrayElementsToVar(dstArray, dstIndex, JavascriptNativeFloatArray::FromVar(srcArray), start, end);
  9659. }
  9660. else
  9661. {
  9662. CopyArrayElements(dstArray, dstIndex, srcArray, start, end);
  9663. }
  9664. }
  9665. //
  9666. // Faster small_index overload of CopyArrayElements, asserting the uint32 dstIndex won't overflow.
  9667. //
  9668. void JavascriptArray::CopyNativeIntArrayElementsToVar(JavascriptArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
  9669. {
  9670. end = min(end, srcArray->length);
  9671. if (start < end)
  9672. {
  9673. Assert(end - start <= MaxArrayLength - dstIndex);
  9674. InternalCopyNativeIntArrayElements(dstArray, dstIndex, srcArray, start, end);
  9675. }
  9676. }
  9677. bool JavascriptArray::CopyNativeIntArrayElements(JavascriptNativeIntArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
  9678. {
  9679. end = min(end, srcArray->length);
  9680. if (start >= end)
  9681. {
  9682. return false;
  9683. }
  9684. Assert(end - start <= MaxArrayLength - dstIndex);
  9685. Assert(start < end && end <= srcArray->length);
  9686. uint32 count = 0;
  9687. // iterate on the array itself
  9688. ArrayElementEnumerator e(srcArray, start, end);
  9689. while(e.MoveNext<int32>())
  9690. {
  9691. uint n = dstIndex + (e.GetIndex() - start);
  9692. dstArray->DirectSetItemAt(n, e.GetItem<int32>());
  9693. count++;
  9694. }
  9695. // iterate on the array's prototypes only if not all elements found
  9696. if (start + count != end)
  9697. {
  9698. JavascriptArray *varArray = JavascriptNativeIntArray::ToVarArray(dstArray);
  9699. InternalFillFromPrototype(varArray, dstIndex, srcArray, start, end, count);
  9700. return true;
  9701. }
  9702. return false;
  9703. }
  9704. bool JavascriptArray::CopyNativeIntArrayElementsToFloat(JavascriptNativeFloatArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
  9705. {
  9706. end = min(end, srcArray->length);
  9707. if (start >= end)
  9708. {
  9709. return false;
  9710. }
  9711. Assert(end - start <= MaxArrayLength - dstIndex);
  9712. Assert(start < end && end <= srcArray->length);
  9713. uint32 count = 0;
  9714. // iterate on the array itself
  9715. ArrayElementEnumerator e(srcArray, start, end);
  9716. while(e.MoveNext<int32>())
  9717. {
  9718. uint n = dstIndex + (e.GetIndex() - start);
  9719. dstArray->DirectSetItemAt(n, (double)e.GetItem<int32>());
  9720. count++;
  9721. }
  9722. // iterate on the array's prototypes only if not all elements found
  9723. if (start + count != end)
  9724. {
  9725. JavascriptArray *varArray = JavascriptNativeFloatArray::ToVarArray(dstArray);
  9726. InternalFillFromPrototype(varArray, dstIndex, srcArray, start, end, count);
  9727. return true;
  9728. }
  9729. return false;
  9730. }
  9731. //
  9732. // Faster small_index overload of CopyArrayElements, asserting the uint32 dstIndex won't overflow.
  9733. //
  9734. void JavascriptArray::CopyNativeFloatArrayElementsToVar(JavascriptArray* dstArray, uint32 dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
  9735. {
  9736. end = min(end, srcArray->length);
  9737. if (start < end)
  9738. {
  9739. Assert(end - start <= MaxArrayLength - dstIndex);
  9740. InternalCopyNativeFloatArrayElements(dstArray, dstIndex, srcArray, start, end);
  9741. }
  9742. }
  9743. bool JavascriptArray::CopyNativeFloatArrayElements(JavascriptNativeFloatArray* dstArray, uint32 dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
  9744. {
  9745. end = min(end, srcArray->length);
  9746. if (start >= end)
  9747. {
  9748. return false;
  9749. }
  9750. Assert(end - start <= MaxArrayLength - dstIndex);
  9751. Assert(start < end && end <= srcArray->length);
  9752. uint32 count = 0;
  9753. // iterate on the array itself
  9754. ArrayElementEnumerator e(srcArray, start, end);
  9755. while(e.MoveNext<double>())
  9756. {
  9757. uint n = dstIndex + (e.GetIndex() - start);
  9758. dstArray->DirectSetItemAt(n, e.GetItem<double>());
  9759. count++;
  9760. }
  9761. // iterate on the array's prototypes only if not all elements found
  9762. if (start + count != end)
  9763. {
  9764. JavascriptArray *varArray = JavascriptNativeFloatArray::ToVarArray(dstArray);
  9765. InternalFillFromPrototype(varArray, dstIndex, srcArray, start, end, count);
  9766. return true;
  9767. }
  9768. return false;
  9769. }
  9770. JavascriptArray *JavascriptArray::EnsureNonNativeArray(JavascriptArray *arr)
  9771. {
  9772. #if ENABLE_COPYONACCESS_ARRAY
  9773. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(arr);
  9774. #endif
  9775. if (JavascriptNativeIntArray::Is(arr))
  9776. {
  9777. arr = JavascriptNativeIntArray::ToVarArray((JavascriptNativeIntArray*)arr);
  9778. }
  9779. else if (JavascriptNativeFloatArray::Is(arr))
  9780. {
  9781. arr = JavascriptNativeFloatArray::ToVarArray((JavascriptNativeFloatArray*)arr);
  9782. }
  9783. return arr;
  9784. }
  9785. BOOL JavascriptNativeIntArray::DirectGetItemAtFull(uint32 index, Var* outVal)
  9786. {
  9787. ScriptContext* requestContext = type->GetScriptContext();
  9788. if (JavascriptConversion::PropertyQueryFlagsToBoolean(JavascriptNativeIntArray::GetItemQuery(this, index, outVal, requestContext)))
  9789. {
  9790. return TRUE;
  9791. }
  9792. return JavascriptOperators::GetItem(this, this->GetPrototype(), index, outVal, requestContext);
  9793. }
  9794. BOOL JavascriptNativeFloatArray::DirectGetItemAtFull(uint32 index, Var* outVal)
  9795. {
  9796. ScriptContext* requestContext = type->GetScriptContext();
  9797. if (JavascriptConversion::PropertyQueryFlagsToBoolean(JavascriptNativeFloatArray::GetItemQuery(this, index, outVal, requestContext)))
  9798. {
  9799. return TRUE;
  9800. }
  9801. return JavascriptOperators::GetItem(this, this->GetPrototype(), index, outVal, requestContext);
  9802. }
  9803. void JavascriptArray::InternalCopyNativeIntArrayElements(JavascriptArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
  9804. {
  9805. Assert(start < end && end <= srcArray->length);
  9806. uint32 count = 0;
  9807. // iterate on the array itself
  9808. ScriptContext *scriptContext = dstArray->GetScriptContext();
  9809. ArrayElementEnumerator e(srcArray, start, end);
  9810. while(e.MoveNext<int32>())
  9811. {
  9812. uint32 n = dstIndex + (e.GetIndex() - start);
  9813. dstArray->DirectSetItemAt(n, JavascriptNumber::ToVar(e.GetItem<int32>(), scriptContext));
  9814. count++;
  9815. }
  9816. // iterate on the array's prototypes only if not all elements found
  9817. if (start + count != end)
  9818. {
  9819. InternalFillFromPrototype(dstArray, dstIndex, srcArray, start, end, count);
  9820. }
  9821. }
  9822. void JavascriptArray::InternalCopyNativeFloatArrayElements(JavascriptArray* dstArray, uint32 dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
  9823. {
  9824. Assert(start < end && end <= srcArray->length);
  9825. uint32 count = 0;
  9826. // iterate on the array itself
  9827. ScriptContext *scriptContext = dstArray->GetScriptContext();
  9828. ArrayElementEnumerator e(srcArray, start, end);
  9829. while(e.MoveNext<double>())
  9830. {
  9831. uint32 n = dstIndex + (e.GetIndex() - start);
  9832. dstArray->DirectSetItemAt(n, JavascriptNumber::ToVarWithCheck(e.GetItem<double>(), scriptContext));
  9833. count++;
  9834. }
  9835. // iterate on the array's prototypes only if not all elements found
  9836. if (start + count != end)
  9837. {
  9838. InternalFillFromPrototype(dstArray, dstIndex, srcArray, start, end, count);
  9839. }
  9840. }
  9841. Var JavascriptArray::SpreadArrayArgs(Var arrayToSpread, const Js::AuxArray<uint32> *spreadIndices, ScriptContext *scriptContext)
  9842. {
  9843. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  9844. // At this stage we have an array literal with some arguments to be spread.
  9845. // First we need to calculate the real size of the final literal.
  9846. #if ENABLE_COPYONACCESS_ARRAY
  9847. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(arrayToSpread);
  9848. #endif
  9849. JavascriptArray *array = FromVar(arrayToSpread);
  9850. uint32 arrayLength = array->GetLength();
  9851. uint32 actualLength = arrayLength;
  9852. for (unsigned i = 0; i < spreadIndices->count; ++i)
  9853. {
  9854. JS_REENTRANT(jsReentLock,
  9855. actualLength = UInt32Math::Add(actualLength - 1, GetSpreadArgLen(array->DirectGetItem(spreadIndices->elements[i]), scriptContext)));
  9856. }
  9857. JavascriptArray *result = FromVar(OP_NewScArrayWithMissingValues(actualLength, scriptContext));
  9858. // Now we copy each element and expand the spread parameters inline.
  9859. for (unsigned i = 0, spreadArrIndex = 0, resultIndex = 0; i < arrayLength && resultIndex < actualLength; ++i)
  9860. {
  9861. uint32 spreadIndex = spreadIndices->elements[spreadArrIndex]; // The index of the next element to be spread.
  9862. // 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.
  9863. auto needArraySlowCopy = [&](Var instance) {
  9864. if (JavascriptArray::Is(instance))
  9865. {
  9866. JavascriptArray *arr = JavascriptArray::FromVar(instance);
  9867. JS_REENTRANT_UNLOCK(jsReentLock, return arr->IsCrossSiteObject() || arr->IsFillFromPrototypes());
  9868. }
  9869. return false;
  9870. };
  9871. // Designed to have interchangeable arguments with CopyAnyArrayElementsToVar.
  9872. auto slowCopy = [&scriptContext, &needArraySlowCopy
  9873. ](JavascriptArray *dstArray, unsigned dstIndex, Var srcArray, uint32 start, uint32 end) {
  9874. Assert(needArraySlowCopy(srcArray) || ArgumentsObject::Is(srcArray) || TypedArrayBase::Is(srcArray) || JavascriptString::Is(srcArray));
  9875. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  9876. RecyclableObject *propertyObject;
  9877. if (!JavascriptOperators::GetPropertyObject(srcArray, scriptContext, &propertyObject))
  9878. {
  9879. JavascriptError::ThrowTypeError(scriptContext, JSERR_InvalidSpreadArgument);
  9880. }
  9881. for (uint32 j = start; j < end; j++)
  9882. {
  9883. Var element = nullptr;
  9884. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(srcArray, propertyObject, j, &element, scriptContext));
  9885. if (!gotItem)
  9886. {
  9887. // Copy across missing values as undefined as per 12.2.5.2 SpreadElement : ... AssignmentExpression 5f.
  9888. element = scriptContext->GetLibrary()->GetUndefined();
  9889. }
  9890. dstArray->DirectSetItemAt(dstIndex++, element);
  9891. }
  9892. };
  9893. if (i < spreadIndex)
  9894. {
  9895. // Any non-spread elements can be copied in bulk.
  9896. if (needArraySlowCopy(array))
  9897. {
  9898. slowCopy(result, resultIndex, (Var)array, i, spreadIndex);
  9899. }
  9900. else
  9901. {
  9902. JS_REENTRANT(jsReentLock, CopyAnyArrayElementsToVar(result, resultIndex, array, i, spreadIndex));
  9903. }
  9904. resultIndex += spreadIndex - i;
  9905. i = spreadIndex - 1;
  9906. continue;
  9907. }
  9908. else if (i > spreadIndex)
  9909. {
  9910. // Any non-spread elements terminating the array can also be copied in bulk.
  9911. Assert(spreadArrIndex == spreadIndices->count - 1);
  9912. if (needArraySlowCopy(array))
  9913. {
  9914. slowCopy(result, resultIndex, array, i, arrayLength);
  9915. }
  9916. else
  9917. {
  9918. JS_REENTRANT(jsReentLock, CopyAnyArrayElementsToVar(result, resultIndex, array, i, arrayLength));
  9919. }
  9920. break;
  9921. }
  9922. else
  9923. {
  9924. JS_REENTRANT(jsReentLock, Var instance = array->DirectGetItem(i));
  9925. if (SpreadArgument::Is(instance))
  9926. {
  9927. SpreadArgument* spreadArgument = SpreadArgument::FromVar(instance);
  9928. uint32 len = spreadArgument->GetArgumentSpreadCount();
  9929. const Var* spreadItems = spreadArgument->GetArgumentSpread();
  9930. for (uint32 j = 0; j < len; j++)
  9931. {
  9932. result->DirectSetItemAt(resultIndex++, spreadItems[j]);
  9933. }
  9934. }
  9935. else
  9936. {
  9937. Assert(JavascriptOperators::IsUndefinedObject(instance));
  9938. result->DirectSetItemAt(resultIndex++, instance);
  9939. }
  9940. if (spreadArrIndex < spreadIndices->count - 1)
  9941. {
  9942. spreadArrIndex++;
  9943. }
  9944. }
  9945. }
  9946. AssertMsg(arrayLength == array->GetLength(), "Array's length should not have changed");
  9947. return result;
  9948. }
  9949. uint32 JavascriptArray::GetSpreadArgLen(Var spreadArg, ScriptContext *scriptContext)
  9950. {
  9951. // A spread argument can be anything that returns a 'length' property, even if that
  9952. // property is null or undefined.
  9953. spreadArg = CrossSite::MarshalVar(scriptContext, spreadArg);
  9954. if (JavascriptArray::Is(spreadArg))
  9955. {
  9956. JavascriptArray *arr = JavascriptArray::FromVar(spreadArg);
  9957. return arr->GetLength();
  9958. }
  9959. if (TypedArrayBase::Is(spreadArg))
  9960. {
  9961. TypedArrayBase *tarr = TypedArrayBase::FromVar(spreadArg);
  9962. return tarr->GetLength();
  9963. }
  9964. if (SpreadArgument::Is(spreadArg))
  9965. {
  9966. SpreadArgument *spreadFunctionArgs = SpreadArgument::FromVar(spreadArg);
  9967. return spreadFunctionArgs->GetArgumentSpreadCount();
  9968. }
  9969. AssertMsg(false, "LdCustomSpreadIteratorList should have converted the arg to one of the above types");
  9970. Throw::FatalInternalError();
  9971. }
  9972. #ifdef VALIDATE_ARRAY
  9973. class ArraySegmentsVisitor
  9974. {
  9975. private:
  9976. SparseArraySegmentBase* seg;
  9977. public:
  9978. ArraySegmentsVisitor(SparseArraySegmentBase* head)
  9979. : seg(head)
  9980. {
  9981. }
  9982. void operator()(SparseArraySegmentBase* s)
  9983. {
  9984. Assert(seg == s);
  9985. if (seg)
  9986. {
  9987. seg = seg->next;
  9988. }
  9989. }
  9990. };
  9991. void JavascriptArray::ValidateArrayCommon()
  9992. {
  9993. SparseArraySegmentBase * lastUsedSegment = this->GetLastUsedSegment();
  9994. AssertMsg(this != nullptr && head && lastUsedSegment, "Array should not be null");
  9995. AssertMsg(head->left == 0, "Array always should have a segment starting at zero");
  9996. // Simple segments validation
  9997. bool foundLastUsedSegment = false;
  9998. SparseArraySegmentBase *seg = head;
  9999. while(seg != nullptr)
  10000. {
  10001. if (seg == lastUsedSegment)
  10002. {
  10003. foundLastUsedSegment = true;
  10004. }
  10005. AssertMsg(seg->length <= seg->size , "Length greater than size not possible");
  10006. SparseArraySegmentBase* next = seg->next;
  10007. if (next != nullptr)
  10008. {
  10009. AssertMsg(seg->left < next->left, "Segment is adjacent to or overlaps with next segment");
  10010. AssertMsg(seg->size <= (next->left - seg->left), "Segment is adjacent to or overlaps with next segment");
  10011. AssertMsg(!SparseArraySegmentBase::IsLeafSegment(seg, this->GetScriptContext()->GetRecycler()), "Leaf segment with a next pointer");
  10012. }
  10013. else
  10014. {
  10015. AssertMsg(seg->length <= MaxArrayLength - seg->left, "Segment index range overflow");
  10016. AssertMsg(seg->left + seg->length <= this->length, "Segment index range exceeds array length");
  10017. }
  10018. seg = next;
  10019. }
  10020. AssertMsg(foundLastUsedSegment || HasSegmentMap(), "Corrupt lastUsedSegment in array header");
  10021. // Validate segmentMap if present
  10022. if (HasSegmentMap())
  10023. {
  10024. ArraySegmentsVisitor visitor(head);
  10025. GetSegmentMap()->Walk(visitor);
  10026. }
  10027. }
  10028. void JavascriptArray::ValidateArray()
  10029. {
  10030. if (!Js::Configuration::Global.flags.ArrayValidate)
  10031. {
  10032. return;
  10033. }
  10034. ValidateArrayCommon();
  10035. // Detailed segments validation
  10036. JavascriptArray::ValidateVarSegment(SparseArraySegment<Var>::From(head));
  10037. }
  10038. void JavascriptNativeIntArray::ValidateArray()
  10039. {
  10040. if (!Js::Configuration::Global.flags.ArrayValidate)
  10041. {
  10042. #if DBG
  10043. SparseArraySegmentBase *seg = head;
  10044. while (seg)
  10045. {
  10046. if (seg->next != nullptr)
  10047. {
  10048. AssertMsg(!SparseArraySegmentBase::IsLeafSegment(seg, this->GetScriptContext()->GetRecycler()), "Leaf segment with a next pointer");
  10049. }
  10050. seg = seg->next;
  10051. }
  10052. #endif
  10053. return;
  10054. }
  10055. ValidateArrayCommon();
  10056. // Detailed segments validation
  10057. JavascriptArray::ValidateSegment<int32>(SparseArraySegment<int32>::From(head));
  10058. }
  10059. void JavascriptNativeFloatArray::ValidateArray()
  10060. {
  10061. if (!Js::Configuration::Global.flags.ArrayValidate)
  10062. {
  10063. #if DBG
  10064. SparseArraySegmentBase *seg = head;
  10065. while (seg)
  10066. {
  10067. if (seg->next != nullptr)
  10068. {
  10069. AssertMsg(!SparseArraySegmentBase::IsLeafSegment(seg, this->GetScriptContext()->GetRecycler()), "Leaf segment with a next pointer");
  10070. }
  10071. seg = seg->next;
  10072. }
  10073. #endif
  10074. return;
  10075. }
  10076. ValidateArrayCommon();
  10077. // Detailed segments validation
  10078. JavascriptArray::ValidateSegment<double>(SparseArraySegment<double>::From(head));
  10079. }
  10080. void JavascriptArray::ValidateVarSegment(SparseArraySegment<Var>* seg)
  10081. {
  10082. if (!Js::Configuration::Global.flags.ArrayValidate)
  10083. {
  10084. return;
  10085. }
  10086. int32 inspect;
  10087. double inspectDouble;
  10088. while (seg)
  10089. {
  10090. uint32 i = 0;
  10091. for (i = 0; i < seg->length; i++)
  10092. {
  10093. if (SparseArraySegment<Var>::IsMissingItem(&seg->elements[i]))
  10094. {
  10095. continue;
  10096. }
  10097. if (TaggedInt::Is(seg->elements[i]))
  10098. {
  10099. inspect = TaggedInt::ToInt32(seg->elements[i]);
  10100. }
  10101. else if (JavascriptNumber::Is_NoTaggedIntCheck(seg->elements[i]))
  10102. {
  10103. inspectDouble = JavascriptNumber::GetValue(seg->elements[i]);
  10104. }
  10105. else
  10106. {
  10107. AssertMsg(RecyclableObject::Is(seg->elements[i]), "Invalid entry in segment");
  10108. }
  10109. }
  10110. ValidateSegment(seg);
  10111. seg = SparseArraySegment<Var>::From(seg->next);
  10112. }
  10113. }
  10114. template<typename T>
  10115. void JavascriptArray::ValidateSegment(SparseArraySegment<T>* seg)
  10116. {
  10117. if (!Js::Configuration::Global.flags.ArrayValidate)
  10118. {
  10119. return;
  10120. }
  10121. while (seg)
  10122. {
  10123. uint32 i = seg->length;
  10124. while (i < seg->size)
  10125. {
  10126. AssertMsg(SparseArraySegment<T>::IsMissingItem(&seg->elements[i]), "Non missing value the end of the segment");
  10127. i++;
  10128. }
  10129. seg = SparseArraySegment<T>::From(seg->next);
  10130. }
  10131. }
  10132. #endif
  10133. template <typename T>
  10134. void JavascriptArray::InitBoxedInlineHeadSegment(SparseArraySegment<T> * dst, SparseArraySegment<T> * src)
  10135. {
  10136. // Don't copy the segment map, we will build it again
  10137. SetFlags(GetFlags() & ~DynamicObjectFlags::HasSegmentMap);
  10138. SetHeadAndLastUsedSegment(dst);
  10139. dst->left = src->left;
  10140. dst->length = src->length;
  10141. dst->size = src->size;
  10142. dst->CheckLengthvsSize();
  10143. dst->next = src->next;
  10144. CopyArray(dst->elements, dst->size, src->elements, src->size);
  10145. }
  10146. JavascriptArray::JavascriptArray(JavascriptArray * instance, bool boxHead)
  10147. : ArrayObject(instance)
  10148. {
  10149. if (boxHead)
  10150. {
  10151. InitBoxedInlineHeadSegment(DetermineInlineHeadSegmentPointer<JavascriptArray, 0, true>(this), SparseArraySegment<Var>::From(instance->head));
  10152. }
  10153. else
  10154. {
  10155. SetFlags(GetFlags() & ~DynamicObjectFlags::HasSegmentMap);
  10156. head = instance->head;
  10157. SetLastUsedSegment(instance->GetLastUsedSegment());
  10158. }
  10159. }
  10160. template <typename T>
  10161. T * JavascriptArray::BoxStackInstance(T * instance)
  10162. {
  10163. Assert(ThreadContext::IsOnStack(instance));
  10164. // On the stack, the we reserved a pointer before the object as to store the boxed value
  10165. T ** boxedInstanceRef = ((T **)instance) - 1;
  10166. T * boxedInstance = *boxedInstanceRef;
  10167. if (boxedInstance)
  10168. {
  10169. return boxedInstance;
  10170. }
  10171. const size_t inlineSlotsSize = instance->GetTypeHandler()->GetInlineSlotsSize();
  10172. if (ThreadContext::IsOnStack(instance->head))
  10173. {
  10174. boxedInstance = RecyclerNewPlusZ(instance->GetRecycler(),
  10175. inlineSlotsSize + sizeof(Js::SparseArraySegmentBase) + instance->head->size * sizeof(typename T::TElement),
  10176. T, instance, true);
  10177. }
  10178. else if(inlineSlotsSize)
  10179. {
  10180. boxedInstance = RecyclerNewPlusZ(instance->GetRecycler(), inlineSlotsSize, T, instance, false);
  10181. }
  10182. else
  10183. {
  10184. boxedInstance = RecyclerNew(instance->GetRecycler(), T, instance, false);
  10185. }
  10186. *boxedInstanceRef = boxedInstance;
  10187. return boxedInstance;
  10188. }
  10189. JavascriptArray *
  10190. JavascriptArray::BoxStackInstance(JavascriptArray * instance)
  10191. {
  10192. return BoxStackInstance<JavascriptArray>(instance);
  10193. }
  10194. #if ENABLE_TTD
  10195. void JavascriptArray::MarkVisitKindSpecificPtrs(TTD::SnapshotExtractor* extractor)
  10196. {
  10197. TTDAssert(this->GetTypeId() == Js::TypeIds_Array || this->GetTypeId() == Js::TypeIds_ES5Array, "Should only be used on basic arrays (or called as super from ES5Array.");
  10198. ScriptContext* ctx = this->GetScriptContext();
  10199. uint32 index = Js::JavascriptArray::InvalidIndex;
  10200. while(true)
  10201. {
  10202. index = this->GetNextIndex(index);
  10203. if(index == Js::JavascriptArray::InvalidIndex) // End of array
  10204. {
  10205. break;
  10206. }
  10207. Js::Var aval = nullptr;
  10208. if(this->DirectGetVarItemAt(index, &aval, ctx))
  10209. {
  10210. extractor->MarkVisitVar(aval);
  10211. }
  10212. }
  10213. }
  10214. void JavascriptArray::ProcessCorePaths()
  10215. {
  10216. TTDAssert(this->GetTypeId() == Js::TypeIds_Array, "Should only be used on basic arrays.");
  10217. ScriptContext* ctx = this->GetScriptContext();
  10218. uint32 index = Js::JavascriptArray::InvalidIndex;
  10219. while(true)
  10220. {
  10221. index = this->GetNextIndex(index);
  10222. if(index == Js::JavascriptArray::InvalidIndex) // End of array
  10223. {
  10224. break;
  10225. }
  10226. Js::Var aval = nullptr;
  10227. if(this->DirectGetVarItemAt(index, &aval, ctx))
  10228. {
  10229. TTD::UtilSupport::TTAutoString pathExt;
  10230. ctx->TTDWellKnownInfo->BuildArrayIndexBuffer(index, pathExt);
  10231. ctx->TTDWellKnownInfo->EnqueueNewPathVarAsNeeded(this, aval, pathExt.GetStrValue());
  10232. }
  10233. }
  10234. }
  10235. TTD::NSSnapObjects::SnapObjectType JavascriptArray::GetSnapTag_TTD() const
  10236. {
  10237. return TTD::NSSnapObjects::SnapObjectType::SnapArrayObject;
  10238. }
  10239. void JavascriptArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  10240. {
  10241. TTDAssert(this->GetTypeId() == Js::TypeIds_Array, "Should only be used on basic Js arrays.");
  10242. TTD::NSSnapObjects::SnapArrayInfo<TTD::TTDVar>* sai = TTD::NSSnapObjects::ExtractArrayValues<TTD::TTDVar>(this, alloc);
  10243. TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayInfo<TTD::TTDVar>*, TTD::NSSnapObjects::SnapObjectType::SnapArrayObject>(objData, sai);
  10244. }
  10245. #endif
  10246. JavascriptNativeArray::JavascriptNativeArray(JavascriptNativeArray * instance) :
  10247. JavascriptArray(instance, false),
  10248. weakRefToFuncBody(instance->weakRefToFuncBody)
  10249. {
  10250. }
  10251. JavascriptNativeIntArray::JavascriptNativeIntArray(JavascriptNativeIntArray * instance, bool boxHead) :
  10252. JavascriptNativeArray(instance)
  10253. {
  10254. if (boxHead)
  10255. {
  10256. InitBoxedInlineHeadSegment(DetermineInlineHeadSegmentPointer<JavascriptNativeIntArray, 0, true>(this), SparseArraySegment<int>::From(instance->head));
  10257. }
  10258. else
  10259. {
  10260. // Base class ctor should have copied these
  10261. Assert(head == instance->head);
  10262. Assert(segmentUnion.lastUsedSegment == instance->GetLastUsedSegment());
  10263. }
  10264. }
  10265. JavascriptNativeIntArray *
  10266. JavascriptNativeIntArray::BoxStackInstance(JavascriptNativeIntArray * instance)
  10267. {
  10268. return JavascriptArray::BoxStackInstance<JavascriptNativeIntArray>(instance);
  10269. }
  10270. #if ENABLE_TTD
  10271. TTD::NSSnapObjects::SnapObjectType JavascriptNativeIntArray::GetSnapTag_TTD() const
  10272. {
  10273. return TTD::NSSnapObjects::SnapObjectType::SnapNativeIntArrayObject;
  10274. }
  10275. void JavascriptNativeIntArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  10276. {
  10277. TTD::NSSnapObjects::SnapArrayInfo<int32>* sai = TTD::NSSnapObjects::ExtractArrayValues<int32>(this, alloc);
  10278. TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayInfo<int32>*, TTD::NSSnapObjects::SnapObjectType::SnapNativeIntArrayObject>(objData, sai);
  10279. }
  10280. #if ENABLE_COPYONACCESS_ARRAY
  10281. TTD::NSSnapObjects::SnapObjectType JavascriptCopyOnAccessNativeIntArray::GetSnapTag_TTD() const
  10282. {
  10283. return TTD::NSSnapObjects::SnapObjectType::Invalid;
  10284. }
  10285. void JavascriptCopyOnAccessNativeIntArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  10286. {
  10287. TTDAssert(false, "Not implemented yet!!!");
  10288. }
  10289. #endif
  10290. #endif
  10291. JavascriptNativeFloatArray::JavascriptNativeFloatArray(JavascriptNativeFloatArray * instance, bool boxHead) :
  10292. JavascriptNativeArray(instance)
  10293. {
  10294. if (boxHead)
  10295. {
  10296. InitBoxedInlineHeadSegment(DetermineInlineHeadSegmentPointer<JavascriptNativeFloatArray, 0, true>(this), SparseArraySegment<double>::From(instance->head));
  10297. }
  10298. else
  10299. {
  10300. // Base class ctor should have copied these
  10301. Assert(head == instance->head);
  10302. Assert(segmentUnion.lastUsedSegment == instance->GetLastUsedSegment());
  10303. }
  10304. }
  10305. JavascriptNativeFloatArray *
  10306. JavascriptNativeFloatArray::BoxStackInstance(JavascriptNativeFloatArray * instance)
  10307. {
  10308. return JavascriptArray::BoxStackInstance<JavascriptNativeFloatArray>(instance);
  10309. }
  10310. #if ENABLE_TTD
  10311. TTD::NSSnapObjects::SnapObjectType JavascriptNativeFloatArray::GetSnapTag_TTD() const
  10312. {
  10313. return TTD::NSSnapObjects::SnapObjectType::SnapNativeFloatArrayObject;
  10314. }
  10315. void JavascriptNativeFloatArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  10316. {
  10317. TTDAssert(this->GetTypeId() == Js::TypeIds_NativeFloatArray, "Should only be used on native float arrays.");
  10318. TTD::NSSnapObjects::SnapArrayInfo<double>* sai = TTD::NSSnapObjects::ExtractArrayValues<double>(this, alloc);
  10319. TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayInfo<double>*, TTD::NSSnapObjects::SnapObjectType::SnapNativeFloatArrayObject>(objData, sai);
  10320. }
  10321. #endif
  10322. template<typename T>
  10323. RecyclableObject*
  10324. JavascriptArray::ArraySpeciesCreate(Var originalArray, T length, ScriptContext* scriptContext, bool *pIsIntArray, bool *pIsFloatArray, bool *pIsBuiltinArrayCtor)
  10325. {
  10326. if (originalArray == nullptr || !scriptContext->GetConfig()->IsES6SpeciesEnabled())
  10327. {
  10328. return nullptr;
  10329. }
  10330. if (JavascriptArray::Is(originalArray)
  10331. && !DynamicObject::FromVar(originalArray)->GetDynamicType()->GetTypeHandler()->GetIsNotPathTypeHandlerOrHasUserDefinedCtor()
  10332. && DynamicObject::FromVar(originalArray)->GetPrototype() == scriptContext->GetLibrary()->GetArrayPrototype()
  10333. && !scriptContext->GetLibrary()->GetArrayObjectHasUserDefinedSpecies())
  10334. {
  10335. return nullptr;
  10336. }
  10337. Var constructor = scriptContext->GetLibrary()->GetUndefined();
  10338. if (JavascriptOperators::IsArray(originalArray))
  10339. {
  10340. if (!JavascriptOperators::GetProperty(RecyclableObject::FromVar(originalArray), PropertyIds::constructor, &constructor, scriptContext))
  10341. {
  10342. return nullptr;
  10343. }
  10344. if (JavascriptOperators::IsConstructor(constructor))
  10345. {
  10346. ScriptContext* constructorScriptContext = RecyclableObject::FromVar(constructor)->GetScriptContext();
  10347. if (constructorScriptContext != scriptContext)
  10348. {
  10349. if (constructorScriptContext->GetLibrary()->GetArrayConstructor() == constructor)
  10350. {
  10351. constructor = scriptContext->GetLibrary()->GetUndefined();
  10352. }
  10353. }
  10354. }
  10355. if (JavascriptOperators::IsObject(constructor))
  10356. {
  10357. if (!JavascriptOperators::GetProperty((RecyclableObject*)constructor, PropertyIds::_symbolSpecies, &constructor, scriptContext))
  10358. {
  10359. if (pIsBuiltinArrayCtor != nullptr)
  10360. {
  10361. *pIsBuiltinArrayCtor = false;
  10362. }
  10363. return nullptr;
  10364. }
  10365. if (constructor == scriptContext->GetLibrary()->GetNull())
  10366. {
  10367. constructor = scriptContext->GetLibrary()->GetUndefined();
  10368. }
  10369. }
  10370. }
  10371. if (constructor == scriptContext->GetLibrary()->GetUndefined() || constructor == scriptContext->GetLibrary()->GetArrayConstructor())
  10372. {
  10373. if (length > UINT_MAX)
  10374. {
  10375. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  10376. }
  10377. if (nullptr == pIsIntArray)
  10378. {
  10379. return scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(length));
  10380. }
  10381. else
  10382. {
  10383. // If the constructor function is the built-in Array constructor, we can be smart and create the right type of native array.
  10384. JavascriptArray* pArr = JavascriptArray::FromVar(originalArray);
  10385. pArr->GetArrayTypeAndConvert(pIsIntArray, pIsFloatArray);
  10386. return CreateNewArrayHelper(static_cast<uint32>(length), *pIsIntArray, *pIsFloatArray, pArr, scriptContext);
  10387. }
  10388. }
  10389. if (!JavascriptOperators::IsConstructor(constructor))
  10390. {
  10391. JavascriptError::ThrowTypeError(scriptContext, JSERR_NotAConstructor, _u("constructor[Symbol.species]"));
  10392. }
  10393. if (pIsBuiltinArrayCtor != nullptr)
  10394. {
  10395. *pIsBuiltinArrayCtor = false;
  10396. }
  10397. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(length, scriptContext) };
  10398. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  10399. return RecyclableObject::FromVar(JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext));
  10400. }
  10401. /*static*/
  10402. PropertyId const JavascriptArray::specialPropertyIds[] =
  10403. {
  10404. PropertyIds::length
  10405. };
  10406. BOOL JavascriptArray::DeleteProperty(PropertyId propertyId, PropertyOperationFlags flags)
  10407. {
  10408. if (propertyId == PropertyIds::length)
  10409. {
  10410. return false;
  10411. }
  10412. return DynamicObject::DeleteProperty(propertyId, flags);
  10413. }
  10414. BOOL JavascriptArray::DeleteProperty(JavascriptString *propertyNameString, PropertyOperationFlags flags)
  10415. {
  10416. JsUtil::CharacterBuffer<WCHAR> propertyName(propertyNameString->GetString(), propertyNameString->GetLength());
  10417. if (BuiltInPropertyRecords::length.Equals(propertyName))
  10418. {
  10419. return false;
  10420. }
  10421. return DynamicObject::DeleteProperty(propertyNameString, flags);
  10422. }
  10423. PropertyQueryFlags JavascriptArray::HasPropertyQuery(PropertyId propertyId)
  10424. {
  10425. if (propertyId == PropertyIds::length)
  10426. {
  10427. return PropertyQueryFlags::Property_Found;
  10428. }
  10429. ScriptContext* scriptContext = GetScriptContext();
  10430. uint32 index;
  10431. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10432. {
  10433. return JavascriptConversion::BooleanToPropertyQueryFlags(this->HasItem(index));
  10434. }
  10435. return DynamicObject::HasPropertyQuery(propertyId);
  10436. }
  10437. BOOL JavascriptArray::IsEnumerable(PropertyId propertyId)
  10438. {
  10439. if (propertyId == PropertyIds::length)
  10440. {
  10441. return false;
  10442. }
  10443. return DynamicObject::IsEnumerable(propertyId);
  10444. }
  10445. BOOL JavascriptArray::IsConfigurable(PropertyId propertyId)
  10446. {
  10447. if (propertyId == PropertyIds::length)
  10448. {
  10449. return false;
  10450. }
  10451. return DynamicObject::IsConfigurable(propertyId);
  10452. }
  10453. //
  10454. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10455. // handling and only check instance objectArray for numeric propertyIds.
  10456. //
  10457. BOOL JavascriptArray::SetEnumerable(PropertyId propertyId, BOOL value)
  10458. {
  10459. if (propertyId == PropertyIds::length)
  10460. {
  10461. Assert(!value); // Can't change array length enumerable
  10462. return true;
  10463. }
  10464. ScriptContext* scriptContext = this->GetScriptContext();
  10465. uint32 index;
  10466. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10467. {
  10468. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10469. ->SetEnumerable(this, propertyId, value);
  10470. }
  10471. return __super::SetEnumerable(propertyId, value);
  10472. }
  10473. //
  10474. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10475. // handling and only check instance objectArray for numeric propertyIds.
  10476. //
  10477. BOOL JavascriptArray::SetWritable(PropertyId propertyId, BOOL value)
  10478. {
  10479. ScriptContext* scriptContext = this->GetScriptContext();
  10480. uint32 index;
  10481. bool setLengthNonWritable = (propertyId == PropertyIds::length && !value);
  10482. if (setLengthNonWritable || scriptContext->IsNumericPropertyId(propertyId, &index))
  10483. {
  10484. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10485. ->SetWritable(this, propertyId, value);
  10486. }
  10487. return __super::SetWritable(propertyId, value);
  10488. }
  10489. //
  10490. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10491. // handling and only check instance objectArray for numeric propertyIds.
  10492. //
  10493. BOOL JavascriptArray::SetConfigurable(PropertyId propertyId, BOOL value)
  10494. {
  10495. if (propertyId == PropertyIds::length)
  10496. {
  10497. Assert(!value); // Can't change array length configurable
  10498. return true;
  10499. }
  10500. ScriptContext* scriptContext = this->GetScriptContext();
  10501. uint32 index;
  10502. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10503. {
  10504. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10505. ->SetConfigurable(this, propertyId, value);
  10506. }
  10507. return __super::SetConfigurable(propertyId, value);
  10508. }
  10509. //
  10510. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10511. // handling and only check instance objectArray for numeric propertyIds.
  10512. //
  10513. BOOL JavascriptArray::SetAttributes(PropertyId propertyId, PropertyAttributes attributes)
  10514. {
  10515. ScriptContext* scriptContext = this->GetScriptContext();
  10516. // SetAttributes on "length" is not expected. DefineOwnProperty uses SetWritable. If this is
  10517. // changed, we need to handle it here.
  10518. Assert(propertyId != PropertyIds::length);
  10519. uint32 index;
  10520. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10521. {
  10522. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10523. ->SetItemAttributes(this, index, attributes);
  10524. }
  10525. return __super::SetAttributes(propertyId, attributes);
  10526. }
  10527. //
  10528. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10529. // handling and only check instance objectArray for numeric propertyIds.
  10530. //
  10531. BOOL JavascriptArray::SetAccessors(PropertyId propertyId, Var getter, Var setter, PropertyOperationFlags flags)
  10532. {
  10533. ScriptContext* scriptContext = this->GetScriptContext();
  10534. uint32 index;
  10535. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10536. {
  10537. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10538. ->SetItemAccessors(this, index, getter, setter);
  10539. }
  10540. return __super::SetAccessors(propertyId, getter, setter, flags);
  10541. }
  10542. //
  10543. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10544. // handling and only check instance objectArray for numeric propertyIds.
  10545. //
  10546. BOOL JavascriptArray::SetItemWithAttributes(uint32 index, Var value, PropertyAttributes attributes)
  10547. {
  10548. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10549. ->SetItemWithAttributes(this, index, value, attributes);
  10550. }
  10551. //
  10552. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10553. // handling and only check instance objectArray for numeric propertyIds.
  10554. //
  10555. BOOL JavascriptArray::SetItemAttributes(uint32 index, PropertyAttributes attributes)
  10556. {
  10557. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10558. ->SetItemAttributes(this, index, attributes);
  10559. }
  10560. //
  10561. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10562. // handling and only check instance objectArray for numeric propertyIds.
  10563. //
  10564. BOOL JavascriptArray::SetItemAccessors(uint32 index, Var getter, Var setter)
  10565. {
  10566. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10567. ->SetItemAccessors(this, index, getter, setter);
  10568. }
  10569. // Check if this objectArray isFrozen.
  10570. BOOL JavascriptArray::IsObjectArrayFrozen()
  10571. {
  10572. // If this is still a JavascriptArray, it's not frozen.
  10573. return false;
  10574. }
  10575. JavascriptEnumerator * JavascriptArray::GetIndexEnumerator(EnumeratorFlags flags, ScriptContext* requestContext)
  10576. {
  10577. #if ENABLE_COPYONACCESS_ARRAY
  10578. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10579. #endif
  10580. if (!!(flags & EnumeratorFlags::SnapShotSemantics))
  10581. {
  10582. return RecyclerNew(GetRecycler(), JavascriptArrayIndexSnapshotEnumerator, this, flags, requestContext);
  10583. }
  10584. return RecyclerNew(GetRecycler(), JavascriptArrayIndexEnumerator, this, flags, requestContext);
  10585. }
  10586. BOOL JavascriptArray::GetNonIndexEnumerator(JavascriptStaticEnumerator * enumerator, ScriptContext* requestContext)
  10587. {
  10588. #if ENABLE_COPYONACCESS_ARRAY
  10589. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10590. #endif
  10591. return enumerator->Initialize(nullptr, nullptr, this, EnumeratorFlags::SnapShotSemantics, requestContext, nullptr);
  10592. }
  10593. BOOL JavascriptArray::IsItemEnumerable(uint32 index)
  10594. {
  10595. return true;
  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::PreventExtensions()
  10602. {
  10603. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)->PreventExtensions(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::Seal()
  10610. {
  10611. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)->Seal(this);
  10612. }
  10613. //
  10614. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10615. // handling and only check instance objectArray for numeric propertyIds.
  10616. //
  10617. BOOL JavascriptArray::Freeze()
  10618. {
  10619. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)->Freeze(this);
  10620. }
  10621. BOOL JavascriptArray::GetSpecialPropertyName(uint32 index, JavascriptString ** propertyName, ScriptContext * requestContext)
  10622. {
  10623. if (index == 0)
  10624. {
  10625. *propertyName = requestContext->GetPropertyString(PropertyIds::length);
  10626. return true;
  10627. }
  10628. return false;
  10629. }
  10630. // Returns the number of special non-enumerable properties this type has.
  10631. uint JavascriptArray::GetSpecialPropertyCount() const
  10632. {
  10633. return _countof(specialPropertyIds);
  10634. }
  10635. // Returns the list of special non-enumerable properties for the type.
  10636. PropertyId const * JavascriptArray::GetSpecialPropertyIds() const
  10637. {
  10638. return specialPropertyIds;
  10639. }
  10640. PropertyQueryFlags JavascriptArray::GetPropertyReferenceQuery(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  10641. {
  10642. return JavascriptArray::GetPropertyQuery(originalInstance, propertyId, value, info, requestContext);
  10643. }
  10644. PropertyQueryFlags JavascriptArray::GetPropertyQuery(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  10645. {
  10646. if (GetPropertyBuiltIns(propertyId, value))
  10647. {
  10648. return PropertyQueryFlags::Property_Found;
  10649. }
  10650. ScriptContext* scriptContext = GetScriptContext();
  10651. uint32 index;
  10652. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10653. {
  10654. return JavascriptConversion::BooleanToPropertyQueryFlags(this->GetItem(this, index, value, scriptContext));
  10655. }
  10656. return DynamicObject::GetPropertyQuery(originalInstance, propertyId, value, info, requestContext);
  10657. }
  10658. PropertyQueryFlags JavascriptArray::GetPropertyQuery(Var originalInstance, JavascriptString* propertyNameString, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  10659. {
  10660. AssertMsg(!PropertyRecord::IsPropertyNameNumeric(propertyNameString->GetString(), propertyNameString->GetLength()),
  10661. "Numeric property names should have been converted to uint or PropertyRecord*");
  10662. PropertyRecord const* propertyRecord;
  10663. this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
  10664. if (propertyRecord != nullptr && GetPropertyBuiltIns(propertyRecord->GetPropertyId(), value))
  10665. {
  10666. return PropertyQueryFlags::Property_Found;
  10667. }
  10668. return DynamicObject::GetPropertyQuery(originalInstance, propertyNameString, value, info, requestContext);
  10669. }
  10670. BOOL JavascriptArray::GetPropertyBuiltIns(PropertyId propertyId, Var* value)
  10671. {
  10672. //
  10673. // length being accessed. Return array length
  10674. //
  10675. if (propertyId == PropertyIds::length)
  10676. {
  10677. *value = JavascriptNumber::ToVar(this->GetLength(), GetScriptContext());
  10678. return true;
  10679. }
  10680. return false;
  10681. }
  10682. PropertyQueryFlags JavascriptArray::HasItemQuery(uint32 index)
  10683. {
  10684. Var value = nullptr;
  10685. return JavascriptConversion::BooleanToPropertyQueryFlags(this->DirectGetItemAt<Var>(index, &value));
  10686. }
  10687. PropertyQueryFlags JavascriptArray::GetItemQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10688. {
  10689. return JavascriptConversion::BooleanToPropertyQueryFlags(this->DirectGetItemAt<Var>(index, value));
  10690. }
  10691. PropertyQueryFlags JavascriptArray::GetItemReferenceQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10692. {
  10693. return JavascriptConversion::BooleanToPropertyQueryFlags(this->DirectGetItemAt<Var>(index, value));
  10694. }
  10695. BOOL JavascriptArray::DirectGetVarItemAt(uint32 index, Var *value, ScriptContext *requestContext)
  10696. {
  10697. return this->DirectGetItemAt<Var>(index, value);
  10698. }
  10699. PropertyQueryFlags JavascriptNativeIntArray::HasItemQuery(uint32 index)
  10700. {
  10701. #if ENABLE_COPYONACCESS_ARRAY
  10702. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10703. #endif
  10704. int32 value;
  10705. return JavascriptConversion::BooleanToPropertyQueryFlags(this->DirectGetItemAt<int32>(index, &value));
  10706. }
  10707. PropertyQueryFlags JavascriptNativeFloatArray::HasItemQuery(uint32 index)
  10708. {
  10709. double dvalue;
  10710. return JavascriptConversion::BooleanToPropertyQueryFlags(this->DirectGetItemAt<double>(index, &dvalue));
  10711. }
  10712. PropertyQueryFlags JavascriptNativeIntArray::GetItemQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10713. {
  10714. #if ENABLE_COPYONACCESS_ARRAY
  10715. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10716. #endif
  10717. return JavascriptConversion::BooleanToPropertyQueryFlags(JavascriptNativeIntArray::DirectGetVarItemAt(index, value, requestContext));
  10718. }
  10719. BOOL JavascriptNativeIntArray::DirectGetVarItemAt(uint32 index, Var *value, ScriptContext *requestContext)
  10720. {
  10721. int32 intvalue;
  10722. if (!this->DirectGetItemAt<int32>(index, &intvalue))
  10723. {
  10724. return FALSE;
  10725. }
  10726. *value = JavascriptNumber::ToVar(intvalue, requestContext);
  10727. return TRUE;
  10728. }
  10729. PropertyQueryFlags JavascriptNativeIntArray::GetItemReferenceQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10730. {
  10731. return JavascriptNativeIntArray::GetItemQuery(originalInstance, index, value, requestContext);
  10732. }
  10733. PropertyQueryFlags JavascriptNativeFloatArray::GetItemQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10734. {
  10735. return JavascriptConversion::BooleanToPropertyQueryFlags(JavascriptNativeFloatArray::DirectGetVarItemAt(index, value, requestContext));
  10736. }
  10737. BOOL JavascriptNativeFloatArray::DirectGetVarItemAt(uint32 index, Var *value, ScriptContext *requestContext)
  10738. {
  10739. double dvalue;
  10740. int32 ivalue;
  10741. if (!this->DirectGetItemAt<double>(index, &dvalue))
  10742. {
  10743. return FALSE;
  10744. }
  10745. if (*(uint64*)&dvalue == 0ull)
  10746. {
  10747. *value = TaggedInt::ToVarUnchecked(0);
  10748. }
  10749. else if (JavascriptNumber::TryGetInt32Value(dvalue, &ivalue) && !TaggedInt::IsOverflow(ivalue))
  10750. {
  10751. *value = TaggedInt::ToVarUnchecked(ivalue);
  10752. }
  10753. else
  10754. {
  10755. *value = JavascriptNumber::ToVarWithCheck(dvalue, requestContext);
  10756. }
  10757. return TRUE;
  10758. }
  10759. PropertyQueryFlags JavascriptNativeFloatArray::GetItemReferenceQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10760. {
  10761. return JavascriptNativeFloatArray::GetItemQuery(originalInstance, index, value, requestContext);
  10762. }
  10763. BOOL JavascriptArray::SetProperty(PropertyId propertyId, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)
  10764. {
  10765. #if ENABLE_COPYONACCESS_ARRAY
  10766. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10767. #endif
  10768. uint32 indexValue;
  10769. if (propertyId == PropertyIds::length)
  10770. {
  10771. return this->SetLength(value);
  10772. }
  10773. else if (GetScriptContext()->IsNumericPropertyId(propertyId, &indexValue))
  10774. {
  10775. // Call this or subclass method
  10776. return SetItem(indexValue, value, flags);
  10777. }
  10778. else
  10779. {
  10780. return DynamicObject::SetProperty(propertyId, value, flags, info);
  10781. }
  10782. }
  10783. BOOL JavascriptArray::SetProperty(JavascriptString* propertyNameString, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)
  10784. {
  10785. AssertMsg(!PropertyRecord::IsPropertyNameNumeric(propertyNameString->GetString(), propertyNameString->GetLength()),
  10786. "Numeric property names should have been converted to uint or PropertyRecord*");
  10787. #if ENABLE_COPYONACCESS_ARRAY
  10788. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10789. #endif
  10790. PropertyRecord const* propertyRecord;
  10791. this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
  10792. if (propertyRecord != nullptr && propertyRecord->GetPropertyId() == PropertyIds::length)
  10793. {
  10794. return this->SetLength(value);
  10795. }
  10796. return DynamicObject::SetProperty(propertyNameString, value, flags, info);
  10797. }
  10798. BOOL JavascriptArray::SetPropertyWithAttributes(PropertyId propertyId, Var value, PropertyAttributes attributes, PropertyValueInfo* info, PropertyOperationFlags flags, SideEffects possibleSideEffects)
  10799. {
  10800. #if ENABLE_COPYONACCESS_ARRAY
  10801. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10802. #endif
  10803. ScriptContext* scriptContext = GetScriptContext();
  10804. if (propertyId == PropertyIds::length)
  10805. {
  10806. Assert(attributes == PropertyWritable);
  10807. Assert(IsWritable(propertyId) && !IsConfigurable(propertyId) && !IsEnumerable(propertyId));
  10808. return this->SetLength(value);
  10809. }
  10810. uint32 index;
  10811. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10812. {
  10813. // Call this or subclass method
  10814. return SetItemWithAttributes(index, value, attributes);
  10815. }
  10816. return __super::SetPropertyWithAttributes(propertyId, value, attributes, info, flags, possibleSideEffects);
  10817. }
  10818. BOOL JavascriptArray::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
  10819. {
  10820. this->DirectSetItemAt(index, value);
  10821. return true;
  10822. }
  10823. BOOL JavascriptNativeIntArray::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
  10824. {
  10825. int32 iValue;
  10826. double dValue;
  10827. #if ENABLE_COPYONACCESS_ARRAY
  10828. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10829. #endif
  10830. TypeId typeId = this->TrySetNativeIntArrayItem(value, &iValue, &dValue);
  10831. if (typeId == TypeIds_NativeIntArray)
  10832. {
  10833. this->SetItem(index, iValue);
  10834. }
  10835. else if (typeId == TypeIds_NativeFloatArray)
  10836. {
  10837. reinterpret_cast<JavascriptNativeFloatArray*>(this)->DirectSetItemAt<double>(index, dValue);
  10838. }
  10839. else
  10840. {
  10841. this->DirectSetItemAt<Var>(index, value);
  10842. }
  10843. return TRUE;
  10844. }
  10845. TypeId JavascriptNativeIntArray::TrySetNativeIntArrayItem(Var value, int32 *iValue, double *dValue)
  10846. {
  10847. if (TaggedInt::Is(value))
  10848. {
  10849. int32 i = TaggedInt::ToInt32(value);
  10850. if (i != JavascriptNativeIntArray::MissingItem)
  10851. {
  10852. *iValue = i;
  10853. return TypeIds_NativeIntArray;
  10854. }
  10855. }
  10856. if (JavascriptNumber::Is_NoTaggedIntCheck(value))
  10857. {
  10858. bool isInt32;
  10859. int32 i;
  10860. double d = JavascriptNumber::GetValue(value);
  10861. if (JavascriptNumber::TryGetInt32OrUInt32Value(d, &i, &isInt32))
  10862. {
  10863. if (isInt32 && i != JavascriptNativeIntArray::MissingItem)
  10864. {
  10865. *iValue = i;
  10866. return TypeIds_NativeIntArray;
  10867. }
  10868. }
  10869. else
  10870. {
  10871. *dValue = d;
  10872. JavascriptNativeIntArray::ToNativeFloatArray(this);
  10873. return TypeIds_NativeFloatArray;
  10874. }
  10875. }
  10876. JavascriptNativeIntArray::ToVarArray(this);
  10877. return TypeIds_Array;
  10878. }
  10879. BOOL JavascriptNativeIntArray::SetItem(uint32 index, int32 iValue)
  10880. {
  10881. if (iValue == JavascriptNativeIntArray::MissingItem)
  10882. {
  10883. JavascriptArray *varArr = JavascriptNativeIntArray::ToVarArray(this);
  10884. varArr->DirectSetItemAt(index, JavascriptNumber::ToVar(iValue, GetScriptContext()));
  10885. return TRUE;
  10886. }
  10887. this->DirectSetItemAt(index, iValue);
  10888. return TRUE;
  10889. }
  10890. BOOL JavascriptNativeFloatArray::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
  10891. {
  10892. double dValue;
  10893. TypeId typeId = this->TrySetNativeFloatArrayItem(value, &dValue);
  10894. if (typeId == TypeIds_NativeFloatArray)
  10895. {
  10896. this->SetItem(index, dValue);
  10897. }
  10898. else
  10899. {
  10900. this->DirectSetItemAt(index, value);
  10901. }
  10902. return TRUE;
  10903. }
  10904. TypeId JavascriptNativeFloatArray::TrySetNativeFloatArrayItem(Var value, double *dValue)
  10905. {
  10906. if (TaggedInt::Is(value))
  10907. {
  10908. *dValue = (double)TaggedInt::ToInt32(value);
  10909. return TypeIds_NativeFloatArray;
  10910. }
  10911. else if (JavascriptNumber::Is_NoTaggedIntCheck(value))
  10912. {
  10913. *dValue = JavascriptNumber::GetValue(value);
  10914. return TypeIds_NativeFloatArray;
  10915. }
  10916. JavascriptNativeFloatArray::ToVarArray(this);
  10917. return TypeIds_Array;
  10918. }
  10919. BOOL JavascriptNativeFloatArray::SetItem(uint32 index, double dValue)
  10920. {
  10921. if (*(uint64*)&dValue == *(uint64*)&JavascriptNativeFloatArray::MissingItem)
  10922. {
  10923. JavascriptArray *varArr = JavascriptNativeFloatArray::ToVarArray(this);
  10924. varArr->DirectSetItemAt(index, JavascriptNumber::ToVarNoCheck(dValue, GetScriptContext()));
  10925. return TRUE;
  10926. }
  10927. this->DirectSetItemAt<double>(index, dValue);
  10928. return TRUE;
  10929. }
  10930. BOOL JavascriptArray::DeleteItem(uint32 index, PropertyOperationFlags flags)
  10931. {
  10932. return this->DirectDeleteItemAt<Var>(index);
  10933. }
  10934. BOOL JavascriptNativeIntArray::DeleteItem(uint32 index, PropertyOperationFlags flags)
  10935. {
  10936. return this->DirectDeleteItemAt<int32>(index);
  10937. }
  10938. BOOL JavascriptNativeFloatArray::DeleteItem(uint32 index, PropertyOperationFlags flags)
  10939. {
  10940. return this->DirectDeleteItemAt<double>(index);
  10941. }
  10942. BOOL JavascriptArray::GetEnumerator(JavascriptStaticEnumerator * enumerator, EnumeratorFlags flags, ScriptContext* requestContext, ForInCache * forInCache)
  10943. {
  10944. #if ENABLE_COPYONACCESS_ARRAY
  10945. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10946. #endif
  10947. return enumerator->Initialize(nullptr, this, this, flags, requestContext, forInCache);
  10948. }
  10949. BOOL JavascriptArray::GetDiagValueString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext)
  10950. {
  10951. stringBuilder->Append(_u('['));
  10952. if (this->length < 10)
  10953. {
  10954. auto funcPtr = [&]()
  10955. {
  10956. ENTER_PINNED_SCOPE(JavascriptString, valueStr);
  10957. valueStr = JavascriptArray::JoinHelper(this, GetLibrary()->GetCommaDisplayString(), requestContext);
  10958. stringBuilder->Append(valueStr->GetString(), valueStr->GetLength());
  10959. LEAVE_PINNED_SCOPE();
  10960. };
  10961. if (!requestContext->GetThreadContext()->IsScriptActive())
  10962. {
  10963. BEGIN_JS_RUNTIME_CALL(requestContext);
  10964. {
  10965. funcPtr();
  10966. }
  10967. END_JS_RUNTIME_CALL(requestContext);
  10968. }
  10969. else
  10970. {
  10971. funcPtr();
  10972. }
  10973. }
  10974. else
  10975. {
  10976. stringBuilder->AppendCppLiteral(_u("..."));
  10977. }
  10978. stringBuilder->Append(_u(']'));
  10979. return TRUE;
  10980. }
  10981. BOOL JavascriptArray::GetDiagTypeString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext)
  10982. {
  10983. stringBuilder->AppendCppLiteral(_u("Object, (Array)"));
  10984. return TRUE;
  10985. }
  10986. bool JavascriptNativeArray::Is(Var aValue)
  10987. {
  10988. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  10989. return JavascriptNativeArray::Is(typeId);
  10990. }
  10991. bool JavascriptNativeArray::Is(TypeId typeId)
  10992. {
  10993. return JavascriptNativeIntArray::Is(typeId) || JavascriptNativeFloatArray::Is(typeId);
  10994. }
  10995. JavascriptNativeArray* JavascriptNativeArray::FromVar(Var aValue)
  10996. {
  10997. AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeArray'");
  10998. return static_cast<JavascriptNativeArray *>(RecyclableObject::FromVar(aValue));
  10999. }
  11000. bool JavascriptNativeIntArray::Is(Var aValue)
  11001. {
  11002. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  11003. return JavascriptNativeIntArray::Is(typeId);
  11004. }
  11005. #if ENABLE_COPYONACCESS_ARRAY
  11006. bool JavascriptCopyOnAccessNativeIntArray::Is(Var aValue)
  11007. {
  11008. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  11009. return JavascriptCopyOnAccessNativeIntArray::Is(typeId);
  11010. }
  11011. #endif
  11012. bool JavascriptNativeIntArray::Is(TypeId typeId)
  11013. {
  11014. return typeId == TypeIds_NativeIntArray;
  11015. }
  11016. #if ENABLE_COPYONACCESS_ARRAY
  11017. bool JavascriptCopyOnAccessNativeIntArray::Is(TypeId typeId)
  11018. {
  11019. return typeId == TypeIds_CopyOnAccessNativeIntArray;
  11020. }
  11021. #endif
  11022. bool JavascriptNativeIntArray::IsNonCrossSite(Var aValue)
  11023. {
  11024. bool ret = !TaggedInt::Is(aValue) && VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(aValue);
  11025. Assert(ret == (JavascriptNativeIntArray::Is(aValue) && !JavascriptNativeIntArray::FromVar(aValue)->IsCrossSiteObject()));
  11026. return ret;
  11027. }
  11028. JavascriptNativeIntArray* JavascriptNativeIntArray::FromVar(Var aValue)
  11029. {
  11030. AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeIntArray'");
  11031. return static_cast<JavascriptNativeIntArray *>(RecyclableObject::FromVar(aValue));
  11032. }
  11033. #if ENABLE_COPYONACCESS_ARRAY
  11034. JavascriptCopyOnAccessNativeIntArray* JavascriptCopyOnAccessNativeIntArray::FromVar(Var aValue)
  11035. {
  11036. AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptCopyOnAccessNativeIntArray'");
  11037. return static_cast<JavascriptCopyOnAccessNativeIntArray *>(RecyclableObject::FromVar(aValue));
  11038. }
  11039. #endif
  11040. bool JavascriptNativeFloatArray::Is(Var aValue)
  11041. {
  11042. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  11043. return JavascriptNativeFloatArray::Is(typeId);
  11044. }
  11045. bool JavascriptNativeFloatArray::Is(TypeId typeId)
  11046. {
  11047. return typeId == TypeIds_NativeFloatArray;
  11048. }
  11049. bool JavascriptNativeFloatArray::IsNonCrossSite(Var aValue)
  11050. {
  11051. bool ret = !TaggedInt::Is(aValue) && VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(aValue);
  11052. Assert(ret == (JavascriptNativeFloatArray::Is(aValue) && !JavascriptNativeFloatArray::FromVar(aValue)->IsCrossSiteObject()));
  11053. return ret;
  11054. }
  11055. JavascriptNativeFloatArray* JavascriptNativeFloatArray::FromVar(Var aValue)
  11056. {
  11057. AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeFloatArray'");
  11058. return static_cast<JavascriptNativeFloatArray *>(RecyclableObject::FromVar(aValue));
  11059. }
  11060. template int Js::JavascriptArray::GetParamForIndexOf<unsigned int>(unsigned int, Js::Arguments const&, void*&, unsigned int&, Js::ScriptContext*);
  11061. template bool Js::JavascriptArray::ArrayElementEnumerator::MoveNext<void*>();
  11062. template void Js::JavascriptArray::SetArrayLiteralItem<void*>(unsigned int, void*);
  11063. template void* Js::JavascriptArray::TemplatedIndexOfHelper<false, Js::TypedArrayBase, unsigned int>(Js::TypedArrayBase*, void*, unsigned int, unsigned int, Js::ScriptContext*);
  11064. template void* Js::JavascriptArray::TemplatedIndexOfHelper<true, Js::TypedArrayBase, unsigned int>(Js::TypedArrayBase*, void*, unsigned int, unsigned int, Js::ScriptContext*);
  11065. } //namespace Js