JavascriptArray.cpp 499 KB

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