JavascriptArray.cpp 492 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "RuntimeLibraryPch.h"
  6. #include "Types/PathTypeHandler.h"
  7. #include "Types/SpreadArgument.h"
  8. // TODO: Change this generic fatal error to the descriptive one.
  9. #define AssertAndFailFast(x) if (!(x)) { Assert(x); Js::Throw::FatalInternalError(); }
  10. namespace Js
  11. {
  12. // Make sure EmptySegment points to read-only memory.
  13. // Can't do this the easy way because SparseArraySegment has a constructor...
  14. static const char EmptySegmentData[sizeof(SparseArraySegmentBase)] = {0};
  15. const SparseArraySegmentBase *JavascriptArray::EmptySegment = (SparseArraySegmentBase *)&EmptySegmentData;
  16. // col0 : allocation bucket
  17. // col1 : No. of missing items to set during initialization depending on bucket.
  18. // col2 : allocation size for elements in given bucket.
  19. // col1 and col2 is calculated at runtime
  20. uint JavascriptNativeFloatArray::allocationBuckets[][AllocationBucketsInfoSize] =
  21. {
  22. { 3, 0, 0 }, // allocate space for 3 elements for array of length 0,1,2,3
  23. { 5, 0, 0 }, // allocate space for 5 elements for array of length 4,5
  24. { 8, 0, 0 }, // allocate space for 8 elements for array of length 6,7,8
  25. };
  26. #if defined(TARGET_64)
  27. const Var JavascriptArray::MissingItem = (Var)0x8000000280000002;
  28. uint JavascriptNativeIntArray::allocationBuckets[][AllocationBucketsInfoSize] =
  29. {
  30. // See comments above on how to read this
  31. {2, 0, 0},
  32. {6, 0, 0},
  33. {8, 0, 0},
  34. };
  35. uint JavascriptArray::allocationBuckets[][AllocationBucketsInfoSize] =
  36. {
  37. // See comments above on how to read this
  38. {4, 0, 0},
  39. {6, 0, 0},
  40. {8, 0, 0},
  41. };
  42. #else
  43. const Var JavascriptArray::MissingItem = (Var)0x80000002;
  44. uint JavascriptNativeIntArray::allocationBuckets[][AllocationBucketsInfoSize] =
  45. {
  46. // See comments above on how to read this
  47. { 3, 0, 0 },
  48. { 7, 0, 0 },
  49. { 8, 0, 0 },
  50. };
  51. uint JavascriptArray::allocationBuckets[][AllocationBucketsInfoSize] =
  52. {
  53. // See comments above on how to read this
  54. { 4, 0, 0 },
  55. { 8, 0, 0 },
  56. };
  57. #endif
  58. const int32 JavascriptNativeIntArray::MissingItem = 0x80000002;
  59. static const uint64 FloatMissingItemPattern = 0x8000000280000002ull;
  60. const double JavascriptNativeFloatArray::MissingItem = *(double*)&FloatMissingItemPattern;
  61. // Allocate enough space for 4 inline property slots and 16 inline element slots
  62. const size_t JavascriptArray::StackAllocationSize = DetermineAllocationSize<JavascriptArray, 4>(16);
  63. const size_t JavascriptNativeIntArray::StackAllocationSize = DetermineAllocationSize<JavascriptNativeIntArray, 4>(16);
  64. const size_t JavascriptNativeFloatArray::StackAllocationSize = DetermineAllocationSize<JavascriptNativeFloatArray, 4>(16);
  65. SegmentBTree::SegmentBTree()
  66. : segmentCount(0),
  67. segments(nullptr),
  68. keys(nullptr),
  69. children(nullptr)
  70. {
  71. }
  72. uint32 SegmentBTree::GetLazyCrossOverLimit()
  73. {
  74. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  75. if (Js::Configuration::Global.flags.DisableArrayBTree)
  76. {
  77. return Js::JavascriptArray::InvalidIndex;
  78. }
  79. else if (Js::Configuration::Global.flags.ForceArrayBTree)
  80. {
  81. return ARRAY_CROSSOVER_FOR_VALIDATE;
  82. }
  83. #endif
  84. #ifdef VALIDATE_ARRAY
  85. if (Js::Configuration::Global.flags.ArrayValidate)
  86. {
  87. return ARRAY_CROSSOVER_FOR_VALIDATE;
  88. }
  89. #endif
  90. return SegmentBTree::MinDegree * 3;
  91. }
  92. BOOL SegmentBTree::IsLeaf() const
  93. {
  94. return children == NULL;
  95. }
  96. BOOL SegmentBTree::IsFullNode() const
  97. {
  98. return segmentCount == MaxKeys;
  99. }
  100. void SegmentBTree::InternalFind(SegmentBTree* node, uint32 itemIndex, SparseArraySegmentBase*& prev, SparseArraySegmentBase*& matchOrNext)
  101. {
  102. uint32 i = 0;
  103. for(; i < node->segmentCount; i++)
  104. {
  105. Assert(node->keys[i] == node->segments[i]->left);
  106. if (itemIndex < node->keys[i])
  107. {
  108. break;
  109. }
  110. }
  111. // i indicates the 1st segment in the node past any matching segment.
  112. // the i'th child is the children to the 'left' of the i'th segment.
  113. // If itemIndex matches segment i-1 (note that left is always a match even when length == 0)
  114. bool matches = i > 0 && (itemIndex == node->keys[i-1] || itemIndex < node->keys[i-1] + node->segments[i-1]->length);
  115. if (matches)
  116. {
  117. // Find prev segment
  118. if (node->IsLeaf())
  119. {
  120. if (i > 1)
  121. {
  122. // Previous is either sibling or set in a parent
  123. prev = node->segments[i-2];
  124. }
  125. }
  126. else
  127. {
  128. // prev is the right most leaf in children[i-1] tree
  129. SegmentBTree* child = &node->children[i - 1];
  130. while (!child->IsLeaf())
  131. {
  132. child = &child->children[child->segmentCount];
  133. }
  134. prev = child->segments[child->segmentCount - 1];
  135. }
  136. // Return the matching segment
  137. matchOrNext = node->segments[i-1];
  138. }
  139. else // itemIndex in between segment i-1 and i
  140. {
  141. if (i > 0)
  142. {
  143. // Store in previous in case a match or next is the first segment in a child.
  144. prev = node->segments[i-1];
  145. }
  146. if (node->IsLeaf())
  147. {
  148. matchOrNext = (i == 0 ? node->segments[0] : PointerValue(prev->next));
  149. }
  150. else
  151. {
  152. InternalFind(node->children + i, itemIndex, prev, matchOrNext);
  153. }
  154. }
  155. }
  156. void SegmentBTreeRoot::Find(uint32 itemIndex, SparseArraySegmentBase*& prev, SparseArraySegmentBase*& matchOrNext)
  157. {
  158. prev = matchOrNext = NULL;
  159. InternalFind(this, itemIndex, prev, matchOrNext);
  160. Assert(prev == NULL || (prev->next == matchOrNext));// If prev exists it is immediately before matchOrNext in the list of arraysegments
  161. Assert(prev == NULL || (prev->left < itemIndex && prev->left + prev->length <= itemIndex)); // prev should never be a match (left is a match if length == 0)
  162. Assert(matchOrNext == NULL || (matchOrNext->left >= itemIndex || matchOrNext->left + matchOrNext->length > itemIndex));
  163. }
  164. void SegmentBTreeRoot::Add(Recycler* recycler, SparseArraySegmentBase* newSeg)
  165. {
  166. if (IsFullNode())
  167. {
  168. SegmentBTree * children = AllocatorNewArrayZ(Recycler, recycler, SegmentBTree, MaxDegree);
  169. children[0] = *this;
  170. // Even though the segments point to a GC pointer, the main array should keep a references
  171. // as well. So just make it a leaf allocation
  172. this->segmentCount = 0;
  173. this->segments = AllocatorNewArrayLeafZ(Recycler, recycler, SparseArraySegmentBase*, MaxKeys);
  174. this->keys = AllocatorNewArrayLeafZ(Recycler,recycler,uint32,MaxKeys);
  175. this->children = children;
  176. // This split is the only way the tree gets deeper
  177. SplitChild(recycler, this, 0, &children[0]);
  178. }
  179. InsertNonFullNode(recycler, this, newSeg);
  180. }
  181. void SegmentBTree::SwapSegment(uint32 originalKey, SparseArraySegmentBase* oldSeg, SparseArraySegmentBase* newSeg)
  182. {
  183. // Find old segment
  184. uint32 itemIndex = originalKey;
  185. uint32 i = 0;
  186. for(; i < segmentCount; i++)
  187. {
  188. Assert(keys[i] == segments[i]->left || (oldSeg == newSeg && newSeg == segments[i]));
  189. if (itemIndex < keys[i])
  190. {
  191. break;
  192. }
  193. }
  194. // i is 1 past any match
  195. if (i > 0)
  196. {
  197. if (oldSeg == segments[i-1])
  198. {
  199. segments[i-1] = newSeg;
  200. keys[i-1] = newSeg->left;
  201. return;
  202. }
  203. }
  204. Assert(!IsLeaf());
  205. children[i].SwapSegment(originalKey, oldSeg, newSeg);
  206. }
  207. void SegmentBTree::SplitChild(Recycler* recycler, SegmentBTree* parent, uint32 iChild, SegmentBTree* child)
  208. {
  209. // Split child in two, move it's median key up to parent, and put the result of the split
  210. // on either side of the key moved up into parent
  211. Assert(child != NULL);
  212. Assert(parent != NULL);
  213. Assert(!parent->IsFullNode());
  214. Assert(child->IsFullNode());
  215. SegmentBTree newNode;
  216. newNode.segmentCount = MinKeys;
  217. // Even though the segments point to a GC pointer, the main array should keep a references
  218. // as well. So just make it a leaf allocation
  219. newNode.segments = AllocatorNewArrayLeafZ(Recycler, recycler, SparseArraySegmentBase*, MaxKeys);
  220. newNode.keys = AllocatorNewArrayLeafZ(Recycler,recycler,uint32,MaxKeys);
  221. // Move the keys above the median into the new node
  222. for(uint32 i = 0; i < MinKeys; i++)
  223. {
  224. newNode.segments[i] = child->segments[i+MinDegree];
  225. newNode.keys[i] = child->keys[i+MinDegree];
  226. // Do not leave false positive references around in the b-tree
  227. child->segments[i+MinDegree] = nullptr;
  228. }
  229. // If children exist move those as well.
  230. if (!child->IsLeaf())
  231. {
  232. newNode.children = AllocatorNewArrayZ(Recycler, recycler, SegmentBTree, MaxDegree);
  233. for(uint32 j = 0; j < MinDegree; j++)
  234. {
  235. newNode.children[j] = child->children[j+MinDegree];
  236. // Do not leave false positive references around in the b-tree
  237. child->children[j+MinDegree].segments = nullptr;
  238. child->children[j+MinDegree].children = nullptr;
  239. }
  240. }
  241. child->segmentCount = MinKeys;
  242. // Make room for the new child in parent
  243. for(uint32 j = parent->segmentCount; j > iChild; j--)
  244. {
  245. parent->children[j+1] = parent->children[j];
  246. }
  247. // Copy the contents of the new node into the correct place in the parent's child array
  248. parent->children[iChild+1] = newNode;
  249. // Move the keys to make room for the median key
  250. for(uint32 k = parent->segmentCount; k > iChild; k--)
  251. {
  252. parent->segments[k] = parent->segments[k-1];
  253. parent->keys[k] = parent->keys[k-1];
  254. }
  255. // Move the median key into the proper place in the parent node
  256. parent->segments[iChild] = child->segments[MinKeys];
  257. parent->keys[iChild] = child->keys[MinKeys];
  258. // Do not leave false positive references around in the b-tree
  259. child->segments[MinKeys] = nullptr;
  260. parent->segmentCount++;
  261. }
  262. void SegmentBTree::InsertNonFullNode(Recycler* recycler, SegmentBTree* node, SparseArraySegmentBase* newSeg)
  263. {
  264. Assert(!node->IsFullNode());
  265. AnalysisAssert(node->segmentCount < MaxKeys); // Same as !node->IsFullNode()
  266. Assert(newSeg != NULL);
  267. if (node->IsLeaf())
  268. {
  269. // Move the keys
  270. uint32 i = node->segmentCount - 1;
  271. while( (i != -1) && (newSeg->left < node->keys[i]))
  272. {
  273. node->segments[i+1] = node->segments[i];
  274. node->keys[i+1] = node->keys[i];
  275. i--;
  276. }
  277. if (!node->segments)
  278. {
  279. // Even though the segments point to a GC pointer, the main array should keep a references
  280. // as well. So just make it a leaf allocation
  281. node->segments = AllocatorNewArrayLeafZ(Recycler, recycler, SparseArraySegmentBase*, MaxKeys);
  282. node->keys = AllocatorNewArrayLeafZ(Recycler, recycler, uint32, MaxKeys);
  283. }
  284. node->segments[i + 1] = newSeg;
  285. node->keys[i + 1] = newSeg->left;
  286. node->segmentCount++;
  287. }
  288. else
  289. {
  290. // find the correct child node
  291. uint32 i = node->segmentCount-1;
  292. while((i != -1) && (newSeg->left < node->keys[i]))
  293. {
  294. i--;
  295. }
  296. i++;
  297. // Make room if full
  298. if(node->children[i].IsFullNode())
  299. {
  300. // This split doesn't make the tree any deeper as node already has children.
  301. SplitChild(recycler, node, i, node->children+i);
  302. Assert(node->keys[i] == node->segments[i]->left);
  303. if (newSeg->left > node->keys[i])
  304. {
  305. i++;
  306. }
  307. }
  308. InsertNonFullNode(recycler, node->children+i, newSeg);
  309. }
  310. }
  311. inline void ThrowTypeErrorOnFailureHelper::ThrowTypeErrorOnFailure(BOOL operationSucceeded)
  312. {
  313. if (IsThrowTypeError(operationSucceeded))
  314. {
  315. ThrowTypeErrorOnFailure();
  316. }
  317. }
  318. inline void ThrowTypeErrorOnFailureHelper::ThrowTypeErrorOnFailure()
  319. {
  320. JavascriptError::ThrowTypeError(m_scriptContext, VBSERR_ActionNotSupported, m_functionName);
  321. }
  322. inline BOOL ThrowTypeErrorOnFailureHelper::IsThrowTypeError(BOOL operationSucceeded)
  323. {
  324. return !operationSucceeded;
  325. }
  326. // Make sure EmptySegment points to read-only memory.
  327. // Can't do this the easy way because SparseArraySegment has a constructor...
  328. JavascriptArray::JavascriptArray(DynamicType * type)
  329. : ArrayObject(type, false, 0)
  330. {
  331. Assert(type->GetTypeId() == TypeIds_Array || type->GetTypeId() == TypeIds_NativeIntArray || type->GetTypeId() == TypeIds_NativeFloatArray || ((type->GetTypeId() == TypeIds_ES5Array || type->GetTypeId() == TypeIds_Object) && type->GetPrototype() == GetScriptContext()->GetLibrary()->GetArrayPrototype()));
  332. Assert(EmptySegment->length == 0 && EmptySegment->size == 0 && EmptySegment->next == NULL);
  333. InitArrayFlags(DynamicObjectFlags::InitialArrayValue);
  334. SetHeadAndLastUsedSegment(const_cast<SparseArraySegmentBase *>(EmptySegment));
  335. }
  336. JavascriptArray::JavascriptArray(uint32 length, DynamicType * type)
  337. : ArrayObject(type, false, length)
  338. {
  339. Assert(JavascriptArray::Is(type->GetTypeId()));
  340. Assert(EmptySegment->length == 0 && EmptySegment->size == 0 && EmptySegment->next == NULL);
  341. InitArrayFlags(DynamicObjectFlags::InitialArrayValue);
  342. SetHeadAndLastUsedSegment(const_cast<SparseArraySegmentBase *>(EmptySegment));
  343. }
  344. JavascriptArray::JavascriptArray(uint32 length, uint32 size, DynamicType * type)
  345. : ArrayObject(type, false, length)
  346. {
  347. Assert(type->GetTypeId() == TypeIds_Array);
  348. InitArrayFlags(DynamicObjectFlags::InitialArrayValue);
  349. Recycler* recycler = GetRecycler();
  350. SetHeadAndLastUsedSegment(SparseArraySegment<Var>::AllocateSegment(recycler, 0, 0, size, nullptr));
  351. }
  352. JavascriptArray::JavascriptArray(DynamicType * type, uint32 size)
  353. : ArrayObject(type, false)
  354. {
  355. InitArrayFlags(DynamicObjectFlags::InitialArrayValue);
  356. SetHeadAndLastUsedSegment(DetermineInlineHeadSegmentPointer<JavascriptArray, 0, false>(this));
  357. head->size = size;
  358. head->CheckLengthvsSize();
  359. Var fill = Js::JavascriptArray::MissingItem;
  360. for (uint i = 0; i < size; i++)
  361. {
  362. SparseArraySegment<Var>::From(head)->elements[i] = fill;
  363. }
  364. }
  365. JavascriptNativeIntArray::JavascriptNativeIntArray(uint32 length, uint32 size, DynamicType * type)
  366. : JavascriptNativeArray(type)
  367. {
  368. Assert(type->GetTypeId() == TypeIds_NativeIntArray);
  369. this->length = length;
  370. Recycler* recycler = GetRecycler();
  371. SetHeadAndLastUsedSegment(SparseArraySegment<int32>::AllocateSegment(recycler, 0, 0, size, nullptr));
  372. }
  373. JavascriptNativeIntArray::JavascriptNativeIntArray(DynamicType * type, uint32 size)
  374. : JavascriptNativeArray(type)
  375. {
  376. SetHeadAndLastUsedSegment(DetermineInlineHeadSegmentPointer<JavascriptNativeIntArray, 0, false>(this));
  377. head->size = size;
  378. head->CheckLengthvsSize();
  379. SparseArraySegment<int32>::From(head)->FillSegmentBuffer(0, size);
  380. }
  381. JavascriptNativeFloatArray::JavascriptNativeFloatArray(uint32 length, uint32 size, DynamicType * type)
  382. : JavascriptNativeArray(type)
  383. {
  384. Assert(type->GetTypeId() == TypeIds_NativeFloatArray);
  385. this->length = length;
  386. Recycler* recycler = GetRecycler();
  387. SetHeadAndLastUsedSegment(SparseArraySegment<double>::AllocateSegment(recycler, 0, 0, size, nullptr));
  388. }
  389. JavascriptNativeFloatArray::JavascriptNativeFloatArray(DynamicType * type, uint32 size)
  390. : JavascriptNativeArray(type)
  391. {
  392. SetHeadAndLastUsedSegment(DetermineInlineHeadSegmentPointer<JavascriptNativeFloatArray, 0, false>(this));
  393. head->size = size;
  394. head->CheckLengthvsSize();
  395. SparseArraySegment<double>::From(head)->FillSegmentBuffer(0, size);
  396. }
  397. bool JavascriptArray::Is(Var aValue)
  398. {
  399. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  400. return JavascriptArray::Is(typeId);
  401. }
  402. bool JavascriptArray::Is(TypeId typeId)
  403. {
  404. return typeId >= TypeIds_ArrayFirst && typeId <= TypeIds_ArrayLast;
  405. }
  406. bool JavascriptArray::IsVarArray(Var aValue)
  407. {
  408. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  409. return JavascriptArray::IsVarArray(typeId);
  410. }
  411. bool JavascriptArray::IsVarArray(TypeId typeId)
  412. {
  413. return typeId == TypeIds_Array;
  414. }
  415. template<typename T>
  416. bool JavascriptArray::IsMissingItemAt(uint32 index) const
  417. {
  418. SparseArraySegment<T>* headSeg = SparseArraySegment<T>::From(this->head);
  419. return SparseArraySegment<T>::IsMissingItem(&headSeg->elements[index]);
  420. }
  421. bool JavascriptArray::IsMissingItem(uint32 index)
  422. {
  423. if (!(this->head->left <= index && index < (this->head->left+ this->head->length)))
  424. {
  425. return false;
  426. }
  427. bool isIntArray = false, isFloatArray = false;
  428. this->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
  429. if (isIntArray)
  430. {
  431. return IsMissingItemAt<int32>(index);
  432. }
  433. else if (isFloatArray)
  434. {
  435. return IsMissingItemAt<double>(index);
  436. }
  437. else
  438. {
  439. return IsMissingItemAt<Var>(index);
  440. }
  441. }
  442. JavascriptArray* JavascriptArray::FromVar(Var aValue)
  443. {
  444. AssertOrFailFastMsg(Is(aValue), "Ensure var is actually a 'JavascriptArray'");
  445. return static_cast<JavascriptArray *>(aValue);
  446. }
  447. JavascriptArray* JavascriptArray::UnsafeFromVar(Var aValue)
  448. {
  449. AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptArray'");
  450. return static_cast<JavascriptArray *>(aValue);
  451. }
  452. // Get JavascriptArray* from a Var, which is either a JavascriptArray* or ESArray*.
  453. JavascriptArray* JavascriptArray::FromAnyArray(Var aValue)
  454. {
  455. AssertOrFailFastMsg(Is(aValue) || ES5Array::Is(aValue), "Ensure var is actually a 'JavascriptArray' or 'ES5Array'");
  456. return static_cast<JavascriptArray *>(RecyclableObject::FromVar(aValue));
  457. }
  458. JavascriptArray* JavascriptArray::UnsafeFromAnyArray(Var aValue)
  459. {
  460. AssertMsg(Is(aValue) || ES5Array::Is(aValue), "Ensure var is actually a 'JavascriptArray' or 'ES5Array'");
  461. return static_cast<JavascriptArray *>(RecyclableObject::UnsafeFromVar(aValue));
  462. }
  463. // Check if a Var is a direct-accessible (fast path) JavascriptArray.
  464. bool JavascriptArray::IsDirectAccessArray(Var aValue)
  465. {
  466. return RecyclableObject::Is(aValue) &&
  467. (VirtualTableInfo<JavascriptArray>::HasVirtualTable(aValue) ||
  468. VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(aValue) ||
  469. VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(aValue));
  470. }
  471. bool JavascriptArray::IsInlineSegment(SparseArraySegmentBase *seg, JavascriptArray *pArr)
  472. {
  473. if (seg == nullptr)
  474. {
  475. return false;
  476. }
  477. SparseArraySegmentBase* inlineHeadSegment = nullptr;
  478. if (JavascriptNativeArray::Is(pArr))
  479. {
  480. if (JavascriptNativeFloatArray::Is(pArr))
  481. {
  482. inlineHeadSegment = DetermineInlineHeadSegmentPointer<JavascriptNativeFloatArray, 0, true>((JavascriptNativeFloatArray*)pArr);
  483. }
  484. else
  485. {
  486. AssertOrFailFast(JavascriptNativeIntArray::Is(pArr));
  487. inlineHeadSegment = DetermineInlineHeadSegmentPointer<JavascriptNativeIntArray, 0, true>((JavascriptNativeIntArray*)pArr);
  488. }
  489. Assert(inlineHeadSegment);
  490. return (seg == inlineHeadSegment);
  491. }
  492. // This will result in false positives. It is used because DetermineInlineHeadSegmentPointer
  493. // does not handle Arrays that change type e.g. from JavascriptNativeIntArray to JavascriptArray
  494. // This conversion in particular is problematic because JavascriptNativeIntArray is larger than JavascriptArray
  495. // so the returned head segment ptr never equals pArr->head. So we will default to using this and deal with
  496. // false positives. It is better than always doing a hard copy.
  497. return pArr->head != nullptr && HasInlineHeadSegment(pArr->head->length);
  498. }
  499. DynamicObjectFlags JavascriptArray::GetFlags() const
  500. {
  501. return GetArrayFlags();
  502. }
  503. DynamicObjectFlags JavascriptArray::GetFlags_Unchecked() const // do not use except in extreme circumstances
  504. {
  505. return GetArrayFlags_Unchecked();
  506. }
  507. void JavascriptArray::SetFlags(const DynamicObjectFlags flags)
  508. {
  509. SetArrayFlags(flags);
  510. }
  511. DynamicType * JavascriptArray::GetInitialType(ScriptContext * scriptContext)
  512. {
  513. return scriptContext->GetLibrary()->GetArrayType();
  514. }
  515. JavascriptArray *JavascriptArray::GetArrayForArrayOrObjectWithArray(const Var var)
  516. {
  517. bool isObjectWithArray;
  518. TypeId arrayTypeId;
  519. return GetArrayForArrayOrObjectWithArray(var, &isObjectWithArray, &arrayTypeId);
  520. }
  521. JavascriptArray *JavascriptArray::GetArrayForArrayOrObjectWithArray(
  522. const Var var,
  523. bool *const isObjectWithArrayRef,
  524. TypeId *const arrayTypeIdRef)
  525. {
  526. // This is a helper function used by jitted code. The array checks done here match the array checks done by jitted code
  527. // (see Lowerer::GenerateArrayTest) to minimize bailouts.
  528. Assert(var);
  529. Assert(isObjectWithArrayRef);
  530. Assert(arrayTypeIdRef);
  531. *isObjectWithArrayRef = false;
  532. *arrayTypeIdRef = TypeIds_Undefined;
  533. if(!RecyclableObject::Is(var))
  534. {
  535. return nullptr;
  536. }
  537. JavascriptArray *array = nullptr;
  538. INT_PTR vtable = VirtualTableInfoBase::GetVirtualTable(var);
  539. if(vtable == VirtualTableInfo<DynamicObject>::Address)
  540. {
  541. ArrayObject* objectArray = DynamicObject::FromVar(var)->GetObjectArray();
  542. array = (objectArray && Is(objectArray)) ? FromVar(objectArray) : nullptr;
  543. if(!array)
  544. {
  545. return nullptr;
  546. }
  547. *isObjectWithArrayRef = true;
  548. vtable = VirtualTableInfoBase::GetVirtualTable(array);
  549. }
  550. if(vtable == VirtualTableInfo<JavascriptArray>::Address)
  551. {
  552. *arrayTypeIdRef = TypeIds_Array;
  553. }
  554. else if(vtable == VirtualTableInfo<JavascriptNativeIntArray>::Address)
  555. {
  556. *arrayTypeIdRef = TypeIds_NativeIntArray;
  557. }
  558. else if(vtable == VirtualTableInfo<JavascriptNativeFloatArray>::Address)
  559. {
  560. *arrayTypeIdRef = TypeIds_NativeFloatArray;
  561. }
  562. else
  563. {
  564. return nullptr;
  565. }
  566. if(!array)
  567. {
  568. array = FromVar(var);
  569. }
  570. return array;
  571. }
  572. const SparseArraySegmentBase *JavascriptArray::Jit_GetArrayHeadSegmentForArrayOrObjectWithArray(const Var var)
  573. {
  574. // This is a helper function used by jitted code
  575. JavascriptArray *const array = GetArrayForArrayOrObjectWithArray(var);
  576. return array ? array->head : nullptr;
  577. }
  578. uint32 JavascriptArray::Jit_GetArrayHeadSegmentLength(const SparseArraySegmentBase *const headSegment)
  579. {
  580. // This is a helper function used by jitted code
  581. return headSegment ? headSegment->length : 0;
  582. }
  583. bool JavascriptArray::Jit_OperationInvalidatedArrayHeadSegment(
  584. const SparseArraySegmentBase *const headSegmentBeforeOperation,
  585. const uint32 headSegmentLengthBeforeOperation,
  586. const Var varAfterOperation)
  587. {
  588. // This is a helper function used by jitted code
  589. Assert(varAfterOperation);
  590. if(!headSegmentBeforeOperation)
  591. {
  592. return false;
  593. }
  594. const SparseArraySegmentBase *const headSegmentAfterOperation =
  595. Jit_GetArrayHeadSegmentForArrayOrObjectWithArray(varAfterOperation);
  596. return
  597. headSegmentAfterOperation != headSegmentBeforeOperation ||
  598. headSegmentAfterOperation->length != headSegmentLengthBeforeOperation;
  599. }
  600. uint32 JavascriptArray::Jit_GetArrayLength(const Var var)
  601. {
  602. // This is a helper function used by jitted code
  603. bool isObjectWithArray;
  604. TypeId arrayTypeId;
  605. JavascriptArray *const array = GetArrayForArrayOrObjectWithArray(var, &isObjectWithArray, &arrayTypeId);
  606. return array && !isObjectWithArray ? array->GetLength() : 0;
  607. }
  608. bool JavascriptArray::Jit_OperationInvalidatedArrayLength(const uint32 lengthBeforeOperation, const Var varAfterOperation)
  609. {
  610. // This is a helper function used by jitted code
  611. return Jit_GetArrayLength(varAfterOperation) != lengthBeforeOperation;
  612. }
  613. DynamicObjectFlags JavascriptArray::Jit_GetArrayFlagsForArrayOrObjectWithArray(const Var var)
  614. {
  615. // This is a helper function used by jitted code
  616. JavascriptArray *const array = GetArrayForArrayOrObjectWithArray(var);
  617. return array && array->UsesObjectArrayOrFlagsAsFlags() ? array->GetFlags() : DynamicObjectFlags::None;
  618. }
  619. bool JavascriptArray::Jit_OperationCreatedFirstMissingValue(
  620. const DynamicObjectFlags flagsBeforeOperation,
  621. const Var varAfterOperation)
  622. {
  623. // This is a helper function used by jitted code
  624. Assert(varAfterOperation);
  625. return
  626. !!(flagsBeforeOperation & DynamicObjectFlags::HasNoMissingValues) &&
  627. !(Jit_GetArrayFlagsForArrayOrObjectWithArray(varAfterOperation) & DynamicObjectFlags::HasNoMissingValues);
  628. }
  629. bool JavascriptArray::HasNoMissingValues() const
  630. {
  631. return !!(GetFlags() & DynamicObjectFlags::HasNoMissingValues);
  632. }
  633. bool JavascriptArray::HasNoMissingValues_Unchecked() const // do not use except in extreme circumstances
  634. {
  635. return !!(GetFlags_Unchecked() & DynamicObjectFlags::HasNoMissingValues);
  636. }
  637. void JavascriptArray::SetHasNoMissingValues(const bool hasNoMissingValues)
  638. {
  639. SetFlags(
  640. hasNoMissingValues
  641. ? GetFlags() | DynamicObjectFlags::HasNoMissingValues
  642. : GetFlags() & ~DynamicObjectFlags::HasNoMissingValues);
  643. }
  644. template<class T>
  645. bool JavascriptArray::IsMissingHeadSegmentItemImpl(const uint32 index) const
  646. {
  647. Assert(index < head->length);
  648. return SparseArraySegment<T>::IsMissingItem(&SparseArraySegment<T>::From(head)->elements[index]);
  649. }
  650. bool JavascriptArray::IsMissingHeadSegmentItem(const uint32 index) const
  651. {
  652. return IsMissingHeadSegmentItemImpl<Var>(index);
  653. }
  654. #if ENABLE_COPYONACCESS_ARRAY
  655. void JavascriptCopyOnAccessNativeIntArray::ConvertCopyOnAccessSegment()
  656. {
  657. Assert(this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->IsValidIndex(::Math::PointerCastToIntegral<uint32>(this->GetHead())));
  658. SparseArraySegment<int32> *seg = this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->GetSegmentByIndex(::Math::PointerCastToIntegral<byte>(this->GetHead()));
  659. SparseArraySegment<int32> *newSeg = SparseArraySegment<int32>::AllocateLiteralHeadSegment(this->GetRecycler(), seg->length);
  660. #if ENABLE_DEBUG_CONFIG_OPTIONS
  661. if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::CopyOnAccessArrayPhase))
  662. {
  663. Output::Print(_u("Convert copy-on-access array: index(%d) length(%d)\n"), this->GetHead(), seg->length);
  664. Output::Flush();
  665. }
  666. #endif
  667. newSeg->CopySegment(this->GetRecycler(), newSeg, 0, seg, 0, seg->length);
  668. this->SetHeadAndLastUsedSegment(newSeg);
  669. VirtualTableInfo<JavascriptNativeIntArray>::SetVirtualTable(this);
  670. this->type = JavascriptNativeIntArray::GetInitialType(this->GetScriptContext());
  671. ArrayCallSiteInfo *arrayInfo = this->GetArrayCallSiteInfo();
  672. if (arrayInfo && !arrayInfo->isNotCopyOnAccessArray)
  673. {
  674. arrayInfo->isNotCopyOnAccessArray = 1;
  675. }
  676. }
  677. uint32 JavascriptCopyOnAccessNativeIntArray::GetNextIndex(uint32 index) const
  678. {
  679. if (this->length == 0 || (index != Js::JavascriptArray::InvalidIndex && index >= this->length))
  680. {
  681. return Js::JavascriptArray::InvalidIndex;
  682. }
  683. else if (index == Js::JavascriptArray::InvalidIndex)
  684. {
  685. return 0;
  686. }
  687. else
  688. {
  689. return index + 1;
  690. }
  691. }
  692. BOOL JavascriptCopyOnAccessNativeIntArray::DirectGetItemAt(uint32 index, int* outVal)
  693. {
  694. Assert(this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->IsValidIndex(::Math::PointerCastToIntegral<uint32>(this->GetHead())));
  695. SparseArraySegment<int32> *seg = this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->GetSegmentByIndex(::Math::PointerCastToIntegral<byte>(this->GetHead()));
  696. if (this->length == 0 || index == Js::JavascriptArray::InvalidIndex || index >= this->length)
  697. {
  698. return FALSE;
  699. }
  700. else
  701. {
  702. *outVal = seg->elements[index];
  703. return TRUE;
  704. }
  705. }
  706. #endif
  707. bool JavascriptNativeIntArray::IsMissingHeadSegmentItem(const uint32 index) const
  708. {
  709. return IsMissingHeadSegmentItemImpl<int32>(index);
  710. }
  711. bool JavascriptNativeFloatArray::IsMissingHeadSegmentItem(const uint32 index) const
  712. {
  713. return IsMissingHeadSegmentItemImpl<double>(index);
  714. }
  715. void JavascriptArray::InternalFillFromPrototype(JavascriptArray *dstArray, uint32 dstIndex, JavascriptArray *srcArray, uint32 start, uint32 end, uint32 count)
  716. {
  717. RecyclableObject* prototype = srcArray->GetPrototype();
  718. while (start + count != end && !JavascriptOperators::IsNull(prototype))
  719. {
  720. ForEachOwnMissingArrayIndexOfObject(srcArray, dstArray, prototype, start, end, dstIndex, [&](uint32 index, Var value) {
  721. uint32 n = dstIndex + (index - start);
  722. dstArray->SetItem(n, value, PropertyOperation_None);
  723. count++;
  724. });
  725. prototype = prototype->GetPrototype();
  726. }
  727. }
  728. /* static */
  729. bool JavascriptArray::HasInlineHeadSegment(uint32 length)
  730. {
  731. return length <= SparseArraySegmentBase::INLINE_CHUNK_SIZE;
  732. }
  733. Var JavascriptArray::OP_NewScArray(uint32 elementCount, ScriptContext* scriptContext)
  734. {
  735. // Called only to create array literals: size is known.
  736. return scriptContext->GetLibrary()->CreateArrayLiteral(elementCount);
  737. }
  738. Var JavascriptArray::OP_NewScArrayWithElements(uint32 elementCount, Var *elements, ScriptContext* scriptContext)
  739. {
  740. // Called only to create array literals: size is known.
  741. JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(elementCount);
  742. SparseArraySegment<Var> *head = SparseArraySegment<Var>::From(arr->head);
  743. Assert(elementCount <= head->length);
  744. CopyArray(head->elements, head->length, elements, elementCount);
  745. #ifdef VALIDATE_ARRAY
  746. arr->ValidateArray();
  747. #endif
  748. return arr;
  749. }
  750. Var JavascriptArray::OP_NewScArrayWithMissingValues(uint32 elementCount, ScriptContext* scriptContext)
  751. {
  752. // Called only to create array literals: size is known.
  753. JavascriptArray *const array = static_cast<JavascriptArray *>(OP_NewScArray(elementCount, scriptContext));
  754. array->SetHasNoMissingValues(false);
  755. SparseArraySegment<Var> *head = SparseArraySegment<Var>::From(array->head);
  756. head->FillSegmentBuffer(0, elementCount);
  757. return array;
  758. }
  759. #if ENABLE_PROFILE_INFO
  760. Var JavascriptArray::ProfiledNewScArray(uint32 elementCount, ScriptContext *scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
  761. {
  762. if (arrayInfo->IsNativeIntArray())
  763. {
  764. JavascriptNativeIntArray *arr = scriptContext->GetLibrary()->CreateNativeIntArrayLiteral(elementCount);
  765. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  766. return arr;
  767. }
  768. if (arrayInfo->IsNativeFloatArray())
  769. {
  770. JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(elementCount);
  771. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  772. return arr;
  773. }
  774. JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(elementCount);
  775. return arr;
  776. }
  777. #endif
  778. Var JavascriptArray::OP_NewScIntArray(AuxArray<int32> *ints, ScriptContext* scriptContext)
  779. {
  780. uint32 count = ints->count;
  781. JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(count);
  782. SparseArraySegment<Var> *head = SparseArraySegment<Var>::From(arr->head);
  783. Assert(count > 0 && count == head->length);
  784. for (uint i = 0; i < count; i++)
  785. {
  786. head->elements[i] = JavascriptNumber::ToVar(ints->elements[i], scriptContext);
  787. }
  788. return arr;
  789. }
  790. #if ENABLE_PROFILE_INFO
  791. Var JavascriptArray::ProfiledNewScIntArray(AuxArray<int32> *ints, ScriptContext* scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
  792. {
  793. // Called only to create array literals: size is known.
  794. uint32 count = ints->count;
  795. if (arrayInfo->IsNativeIntArray())
  796. {
  797. JavascriptNativeIntArray *arr;
  798. #if ENABLE_COPYONACCESS_ARRAY
  799. JavascriptLibrary *lib = scriptContext->GetLibrary();
  800. FunctionBody *functionBody = weakFuncRef->Get();
  801. if (JavascriptLibrary::IsCopyOnAccessArrayCallSite(lib, arrayInfo, count))
  802. {
  803. Assert(lib->cacheForCopyOnAccessArraySegments);
  804. arr = scriptContext->GetLibrary()->CreateCopyOnAccessNativeIntArrayLiteral(arrayInfo, functionBody, ints);
  805. }
  806. else
  807. #endif
  808. {
  809. arr = scriptContext->GetLibrary()->CreateNativeIntArrayLiteral(count);
  810. SparseArraySegment<int32> *head = SparseArraySegment<int32>::From(arr->head);
  811. Assert(count > 0 && count == head->length);
  812. CopyArray(head->elements, head->length, ints->elements, count);
  813. }
  814. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  815. return arr;
  816. }
  817. if (arrayInfo->IsNativeFloatArray())
  818. {
  819. JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(count);
  820. SparseArraySegment<double> *head = SparseArraySegment<double>::From(arr->head);
  821. Assert(count > 0 && count == head->length);
  822. for (uint i = 0; i < count; i++)
  823. {
  824. head->elements[i] = (double)ints->elements[i];
  825. }
  826. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  827. return arr;
  828. }
  829. return OP_NewScIntArray(ints, scriptContext);
  830. }
  831. #endif
  832. Var JavascriptArray::OP_NewScFltArray(AuxArray<double> *doubles, ScriptContext* scriptContext)
  833. {
  834. uint32 count = doubles->count;
  835. JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(count);
  836. SparseArraySegment<Var> *head = SparseArraySegment<Var>::From(arr->head);
  837. Assert(count > 0 && count == head->length);
  838. for (uint i = 0; i < count; i++)
  839. {
  840. double dval = doubles->elements[i];
  841. int32 ival;
  842. if (JavascriptNumber::TryGetInt32Value(dval, &ival) && !TaggedInt::IsOverflow(ival))
  843. {
  844. head->elements[i] = TaggedInt::ToVarUnchecked(ival);
  845. }
  846. else
  847. {
  848. head->elements[i] = JavascriptNumber::ToVarNoCheck(dval, scriptContext);
  849. }
  850. }
  851. return arr;
  852. }
  853. #if ENABLE_PROFILE_INFO
  854. Var JavascriptArray::ProfiledNewScFltArray(AuxArray<double> *doubles, ScriptContext* scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
  855. {
  856. // Called only to create array literals: size is known.
  857. if (arrayInfo->IsNativeFloatArray())
  858. {
  859. arrayInfo->SetIsNotNativeIntArray();
  860. uint32 count = doubles->count;
  861. JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(count);
  862. SparseArraySegment<double> *head = SparseArraySegment<double>::From(arr->head);
  863. Assert(count > 0 && count == head->length);
  864. CopyArray(head->elements, head->length, doubles->elements, count);
  865. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  866. return arr;
  867. }
  868. return OP_NewScFltArray(doubles, scriptContext);
  869. }
  870. Var JavascriptArray::ProfiledNewInstance(RecyclableObject* function, CallInfo callInfo, ...)
  871. {
  872. ARGUMENTS(args, callInfo);
  873. Assert(JavascriptFunction::Is(function) &&
  874. JavascriptFunction::FromVar(function)->GetFunctionInfo() == &JavascriptArray::EntryInfo::NewInstance);
  875. Assert(callInfo.Count >= 2);
  876. ArrayCallSiteInfo *arrayInfo = (ArrayCallSiteInfo*)args[0];
  877. JavascriptArray* pNew = nullptr;
  878. if (callInfo.Count == 2)
  879. {
  880. // Exactly one argument, which is the array length if it's a uint32.
  881. Var firstArgument = args[1];
  882. int elementCount;
  883. if (TaggedInt::Is(firstArgument))
  884. {
  885. elementCount = TaggedInt::ToInt32(firstArgument);
  886. if (elementCount < 0)
  887. {
  888. JavascriptError::ThrowRangeError(function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  889. }
  890. if (arrayInfo && arrayInfo->IsNativeArray())
  891. {
  892. if (arrayInfo->IsNativeIntArray())
  893. {
  894. pNew = function->GetLibrary()->CreateNativeIntArray(elementCount);
  895. }
  896. else
  897. {
  898. pNew = function->GetLibrary()->CreateNativeFloatArray(elementCount);
  899. }
  900. }
  901. else
  902. {
  903. pNew = function->GetLibrary()->CreateArray(elementCount);
  904. }
  905. }
  906. else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
  907. {
  908. // Non-tagged-int number: make sure the double value is really a uint32.
  909. double value = JavascriptNumber::GetValue(firstArgument);
  910. uint32 uvalue = JavascriptConversion::ToUInt32(value);
  911. if (value != uvalue)
  912. {
  913. JavascriptError::ThrowRangeError(function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  914. }
  915. if (arrayInfo && arrayInfo->IsNativeArray())
  916. {
  917. if (arrayInfo->IsNativeIntArray())
  918. {
  919. pNew = function->GetLibrary()->CreateNativeIntArray(uvalue);
  920. }
  921. else
  922. {
  923. pNew = function->GetLibrary()->CreateNativeFloatArray(uvalue);
  924. }
  925. }
  926. else
  927. {
  928. pNew = function->GetLibrary()->CreateArray(uvalue);
  929. }
  930. }
  931. else
  932. {
  933. //
  934. // First element is not int/double
  935. // create an array of length 1.
  936. // Set first element as the passed Var
  937. //
  938. pNew = function->GetLibrary()->CreateArray(1);
  939. pNew->DirectSetItemAt<Var>(0, firstArgument);
  940. }
  941. }
  942. else
  943. {
  944. // Called with a list of initial element values.
  945. // Create an array of the appropriate length and walk the list.
  946. if (arrayInfo && arrayInfo->IsNativeArray())
  947. {
  948. if (arrayInfo->IsNativeIntArray())
  949. {
  950. pNew = function->GetLibrary()->CreateNativeIntArray(callInfo.Count - 1);
  951. }
  952. else
  953. {
  954. pNew = function->GetLibrary()->CreateNativeFloatArray(callInfo.Count - 1);
  955. }
  956. }
  957. else
  958. {
  959. pNew = function->GetLibrary()->CreateArray(callInfo.Count - 1);
  960. }
  961. pNew->FillFromArgs(callInfo.Count - 1, 0, args.Values, arrayInfo);
  962. }
  963. #ifdef VALIDATE_ARRAY
  964. pNew->ValidateArray();
  965. #endif
  966. return pNew;
  967. }
  968. #endif
  969. Var JavascriptArray::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
  970. {
  971. ARGUMENTS(args, callInfo);
  972. return NewInstance(function, args);
  973. }
  974. Var JavascriptArray::NewInstance(RecyclableObject* function, Arguments args)
  975. {
  976. // Call to new Array(), possibly under another name.
  977. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  978. // SkipDefaultNewObject function flag should have prevented the default object
  979. // being created, except when call true a host dispatch.
  980. const CallInfo &callInfo = args.Info;
  981. Var newTarget = args.GetNewTarget();
  982. bool isCtorSuperCall = JavascriptOperators::GetAndAssertIsConstructorSuperCall(args);
  983. ScriptContext* scriptContext = function->GetScriptContext();
  984. JavascriptArray* pNew = nullptr;
  985. if (callInfo.Count < 2)
  986. {
  987. // No arguments passed to Array(), so create with the default size (0).
  988. pNew = CreateArrayFromConstructorNoArg(function, scriptContext);
  989. return isCtorSuperCall ?
  990. JavascriptOperators::OrdinaryCreateFromConstructor(RecyclableObject::FromVar(newTarget), pNew, nullptr, scriptContext) :
  991. pNew;
  992. }
  993. if (callInfo.Count == 2)
  994. {
  995. // Exactly one argument, which is the array length if it's a uint32.
  996. Var firstArgument = args[1];
  997. int elementCount;
  998. if (TaggedInt::Is(firstArgument))
  999. {
  1000. elementCount = TaggedInt::ToInt32(firstArgument);
  1001. if (elementCount < 0)
  1002. {
  1003. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  1004. }
  1005. pNew = CreateArrayFromConstructor(function, elementCount, scriptContext);
  1006. }
  1007. else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
  1008. {
  1009. // Non-tagged-int number: make sure the double value is really a uint32.
  1010. double value = JavascriptNumber::GetValue(firstArgument);
  1011. uint32 uvalue = JavascriptConversion::ToUInt32(value);
  1012. if (value != uvalue)
  1013. {
  1014. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  1015. }
  1016. pNew = CreateArrayFromConstructor(function, uvalue, scriptContext);
  1017. }
  1018. else
  1019. {
  1020. //
  1021. // First element is not int/double
  1022. // create an array of length 1.
  1023. // Set first element as the passed Var
  1024. //
  1025. pNew = CreateArrayFromConstructor(function, 1, scriptContext);
  1026. JavascriptOperators::SetItem(pNew, pNew, 0u, firstArgument, scriptContext, PropertyOperation_ThrowIfNotExtensible);
  1027. // If we were passed an uninitialized JavascriptArray as the this argument,
  1028. // we need to set the length. We must do this _after_ setting the first
  1029. // element as the array may have side effects such as a setter for property
  1030. // named '0' which would make the previous length of the array observable.
  1031. // If we weren't passed a JavascriptArray as the this argument, this is no-op.
  1032. pNew->SetLength(1);
  1033. }
  1034. }
  1035. else
  1036. {
  1037. // Called with a list of initial element values.
  1038. // Create an array of the appropriate length and walk the list.
  1039. pNew = CreateArrayFromConstructor(function, callInfo.Count - 1, scriptContext);
  1040. pNew->JavascriptArray::FillFromArgs(callInfo.Count - 1, 0, args.Values);
  1041. }
  1042. #ifdef VALIDATE_ARRAY
  1043. pNew->ValidateArray();
  1044. #endif
  1045. return isCtorSuperCall ?
  1046. JavascriptOperators::OrdinaryCreateFromConstructor(RecyclableObject::FromVar(newTarget), pNew, nullptr, scriptContext) :
  1047. pNew;
  1048. }
  1049. JavascriptArray* JavascriptArray::CreateArrayFromConstructor(RecyclableObject* constructor, uint32 length, ScriptContext* scriptContext)
  1050. {
  1051. JavascriptLibrary* library = constructor->GetLibrary();
  1052. // Create the Array object we'll return - this is the only way to create an object which is an exotic Array object.
  1053. // Note: We need to use the library from the ScriptContext of the constructor, not the currently executing function.
  1054. // This is for the case where a built-in @@create method from a different JavascriptLibrary is installed on
  1055. // constructor.
  1056. return library->CreateArray(length);
  1057. }
  1058. JavascriptArray* JavascriptArray::CreateArrayFromConstructorNoArg(RecyclableObject* constructor, ScriptContext* scriptContext)
  1059. {
  1060. JavascriptLibrary* library = constructor->GetLibrary();
  1061. return library->CreateArray();
  1062. }
  1063. #if ENABLE_PROFILE_INFO
  1064. Var JavascriptArray::ProfiledNewInstanceNoArg(RecyclableObject *function, ScriptContext *scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
  1065. {
  1066. Assert(JavascriptFunction::Is(function) &&
  1067. JavascriptFunction::FromVar(function)->GetFunctionInfo() == &JavascriptArray::EntryInfo::NewInstance);
  1068. if (arrayInfo->IsNativeIntArray())
  1069. {
  1070. JavascriptNativeIntArray *arr = scriptContext->GetLibrary()->CreateNativeIntArray();
  1071. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  1072. return arr;
  1073. }
  1074. if (arrayInfo->IsNativeFloatArray())
  1075. {
  1076. JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArray();
  1077. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  1078. return arr;
  1079. }
  1080. return scriptContext->GetLibrary()->CreateArray();
  1081. }
  1082. #endif
  1083. Var JavascriptNativeIntArray::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
  1084. {
  1085. ARGUMENTS(args, callInfo);
  1086. return NewInstance(function, args);
  1087. }
  1088. Var JavascriptNativeIntArray::NewInstance(RecyclableObject* function, Arguments args)
  1089. {
  1090. Assert(!PHASE_OFF1(NativeArrayPhase));
  1091. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1092. const CallInfo &callInfo = args.Info;
  1093. if (callInfo.Count < 2)
  1094. {
  1095. // No arguments passed to Array(), so create with the default size (0).
  1096. return function->GetLibrary()->CreateNativeIntArray();
  1097. }
  1098. JavascriptArray* pNew = nullptr;
  1099. if (callInfo.Count == 2)
  1100. {
  1101. // Exactly one argument, which is the array length if it's a uint32.
  1102. Var firstArgument = args[1];
  1103. int elementCount;
  1104. if (TaggedInt::Is(firstArgument))
  1105. {
  1106. elementCount = TaggedInt::ToInt32(firstArgument);
  1107. if (elementCount < 0)
  1108. {
  1109. JavascriptError::ThrowRangeError(
  1110. function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  1111. }
  1112. pNew = function->GetLibrary()->CreateNativeIntArray(elementCount);
  1113. }
  1114. else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
  1115. {
  1116. // Non-tagged-int number: make sure the double value is really a uint32.
  1117. double value = JavascriptNumber::GetValue(firstArgument);
  1118. uint32 uvalue = JavascriptConversion::ToUInt32(value);
  1119. if (value != uvalue)
  1120. {
  1121. JavascriptError::ThrowRangeError(
  1122. function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  1123. }
  1124. pNew = function->GetLibrary()->CreateNativeIntArray(uvalue);
  1125. }
  1126. else
  1127. {
  1128. //
  1129. // First element is not int/double
  1130. // create an array of length 1.
  1131. // Set first element as the passed Var
  1132. //
  1133. pNew = function->GetLibrary()->CreateArray(1);
  1134. pNew->DirectSetItemAt<Var>(0, firstArgument);
  1135. }
  1136. }
  1137. else
  1138. {
  1139. // Called with a list of initial element values.
  1140. // Create an array of the appropriate length and walk the list.
  1141. JavascriptNativeIntArray *arr = function->GetLibrary()->CreateNativeIntArray(callInfo.Count - 1);
  1142. pNew = arr->FillFromArgs(callInfo.Count - 1, 0, args.Values);
  1143. }
  1144. #ifdef VALIDATE_ARRAY
  1145. pNew->ValidateArray();
  1146. #endif
  1147. return pNew;
  1148. }
  1149. Var JavascriptNativeFloatArray::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
  1150. {
  1151. ARGUMENTS(args, callInfo);
  1152. return NewInstance(function, args);
  1153. }
  1154. Var JavascriptNativeFloatArray::NewInstance(RecyclableObject* function, Arguments args)
  1155. {
  1156. Assert(!PHASE_OFF1(NativeArrayPhase));
  1157. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1158. const CallInfo &callInfo = args.Info;
  1159. if (callInfo.Count < 2)
  1160. {
  1161. // No arguments passed to Array(), so create with the default size (0).
  1162. return function->GetLibrary()->CreateNativeFloatArray();
  1163. }
  1164. JavascriptArray* pNew = nullptr;
  1165. if (callInfo.Count == 2)
  1166. {
  1167. // Exactly one argument, which is the array length if it's a uint32.
  1168. Var firstArgument = args[1];
  1169. int elementCount;
  1170. if (TaggedInt::Is(firstArgument))
  1171. {
  1172. elementCount = TaggedInt::ToInt32(firstArgument);
  1173. if (elementCount < 0)
  1174. {
  1175. JavascriptError::ThrowRangeError(
  1176. function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  1177. }
  1178. pNew = function->GetLibrary()->CreateNativeFloatArray(elementCount);
  1179. }
  1180. else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
  1181. {
  1182. // Non-tagged-int number: make sure the double value is really a uint32.
  1183. double value = JavascriptNumber::GetValue(firstArgument);
  1184. uint32 uvalue = JavascriptConversion::ToUInt32(value);
  1185. if (value != uvalue)
  1186. {
  1187. JavascriptError::ThrowRangeError(
  1188. function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  1189. }
  1190. pNew = function->GetLibrary()->CreateNativeFloatArray(uvalue);
  1191. }
  1192. else
  1193. {
  1194. //
  1195. // First element is not int/double
  1196. // create an array of length 1.
  1197. // Set first element as the passed Var
  1198. //
  1199. pNew = function->GetLibrary()->CreateArray(1);
  1200. pNew->DirectSetItemAt<Var>(0, firstArgument);
  1201. }
  1202. }
  1203. else
  1204. {
  1205. // Called with a list of initial element values.
  1206. // Create an array of the appropriate length and walk the list.
  1207. JavascriptNativeFloatArray *arr = function->GetLibrary()->CreateNativeFloatArray(callInfo.Count - 1);
  1208. pNew = arr->FillFromArgs(callInfo.Count - 1, 0, args.Values);
  1209. }
  1210. #ifdef VALIDATE_ARRAY
  1211. pNew->ValidateArray();
  1212. #endif
  1213. return pNew;
  1214. }
  1215. #if ENABLE_PROFILE_INFO
  1216. JavascriptArray * JavascriptNativeIntArray::FillFromArgs(uint length, uint start, Var *args, ArrayCallSiteInfo *arrayInfo, bool dontCreateNewArray)
  1217. #else
  1218. JavascriptArray * JavascriptNativeIntArray::FillFromArgs(uint length, uint start, Var *args, bool dontCreateNewArray)
  1219. #endif
  1220. {
  1221. uint i;
  1222. for (i = start; i < length; i++)
  1223. {
  1224. Var item = args[i + 1];
  1225. bool isTaggedInt = TaggedInt::Is(item);
  1226. bool isTaggedIntMissingValue = false;
  1227. #ifdef TARGET_64
  1228. if (isTaggedInt)
  1229. {
  1230. int32 iValue = TaggedInt::ToInt32(item);
  1231. isTaggedIntMissingValue = Js::SparseArraySegment<int32>::IsMissingItem(&iValue);
  1232. }
  1233. #endif
  1234. if (isTaggedInt && !isTaggedIntMissingValue)
  1235. {
  1236. // This is taggedInt case and we verified that item is not missing value in AMD64.
  1237. this->DirectSetItemAt(i, TaggedInt::ToInt32(item));
  1238. }
  1239. else if (!isTaggedIntMissingValue && JavascriptNumber::Is_NoTaggedIntCheck(item))
  1240. {
  1241. double dvalue = JavascriptNumber::GetValue(item);
  1242. int32 ivalue;
  1243. if (JavascriptNumber::TryGetInt32Value(dvalue, &ivalue) && !Js::SparseArraySegment<int32>::IsMissingItem(&ivalue))
  1244. {
  1245. this->DirectSetItemAt(i, ivalue);
  1246. }
  1247. else
  1248. {
  1249. #if ENABLE_PROFILE_INFO
  1250. if (arrayInfo)
  1251. {
  1252. arrayInfo->SetIsNotNativeIntArray();
  1253. }
  1254. #endif
  1255. if (HasInlineHeadSegment(length) && i < this->head->length && !dontCreateNewArray)
  1256. {
  1257. // Avoid shrinking the number of elements in the head segment. We can still create a new
  1258. // array here, so go ahead.
  1259. JavascriptNativeFloatArray *fArr =
  1260. this->GetScriptContext()->GetLibrary()->CreateNativeFloatArrayLiteral(length);
  1261. return fArr->JavascriptNativeFloatArray::FillFromArgs(length, 0, args);
  1262. }
  1263. JavascriptNativeFloatArray *fArr = JavascriptNativeIntArray::ToNativeFloatArray(this);
  1264. fArr->DirectSetItemAt(i, dvalue);
  1265. #if ENABLE_PROFILE_INFO
  1266. return fArr->JavascriptNativeFloatArray::FillFromArgs(length, i + 1, args, arrayInfo, dontCreateNewArray);
  1267. #else
  1268. return fArr->JavascriptNativeFloatArray::FillFromArgs(length, i + 1, args, dontCreateNewArray);
  1269. #endif
  1270. }
  1271. }
  1272. else
  1273. {
  1274. #if ENABLE_PROFILE_INFO
  1275. if (arrayInfo)
  1276. {
  1277. arrayInfo->SetIsNotNativeArray();
  1278. }
  1279. #endif
  1280. #pragma prefast(suppress:6237, "The right hand side condition does not have any side effects.")
  1281. if (sizeof(int32) < sizeof(Var) && HasInlineHeadSegment(length) && i < this->head->length && !dontCreateNewArray)
  1282. {
  1283. // Avoid shrinking the number of elements in the head segment. We can still create a new
  1284. // array here, so go ahead.
  1285. JavascriptArray *arr = this->GetScriptContext()->GetLibrary()->CreateArrayLiteral(length);
  1286. return arr->JavascriptArray::FillFromArgs(length, 0, args);
  1287. }
  1288. JavascriptArray *arr = JavascriptNativeIntArray::ToVarArray(this);
  1289. #if ENABLE_PROFILE_INFO
  1290. return arr->JavascriptArray::FillFromArgs(length, i, args, nullptr, dontCreateNewArray);
  1291. #else
  1292. return arr->JavascriptArray::FillFromArgs(length, i, args, dontCreateNewArray);
  1293. #endif
  1294. }
  1295. }
  1296. return this;
  1297. }
  1298. #if ENABLE_PROFILE_INFO
  1299. JavascriptArray * JavascriptNativeFloatArray::FillFromArgs(uint length, uint start, Var *args, ArrayCallSiteInfo *arrayInfo, bool dontCreateNewArray)
  1300. #else
  1301. JavascriptArray * JavascriptNativeFloatArray::FillFromArgs(uint length, uint start, Var *args, bool dontCreateNewArray)
  1302. #endif
  1303. {
  1304. uint i;
  1305. for (i = start; i < length; i++)
  1306. {
  1307. Var item = args[i + 1];
  1308. if (TaggedInt::Is(item))
  1309. {
  1310. this->DirectSetItemAt(i, TaggedInt::ToDouble(item));
  1311. }
  1312. else if (JavascriptNumber::Is_NoTaggedIntCheck(item))
  1313. {
  1314. this->DirectSetItemAt(i, JavascriptNumber::GetValue(item));
  1315. }
  1316. else
  1317. {
  1318. JavascriptArray *arr = JavascriptNativeFloatArray::ToVarArray(this);
  1319. #if ENABLE_PROFILE_INFO
  1320. if (arrayInfo)
  1321. {
  1322. arrayInfo->SetIsNotNativeArray();
  1323. }
  1324. return arr->JavascriptArray::FillFromArgs(length, i, args, nullptr, dontCreateNewArray);
  1325. #else
  1326. return arr->JavascriptArray::FillFromArgs(length, i, args, dontCreateNewArray);
  1327. #endif
  1328. }
  1329. }
  1330. return this;
  1331. }
  1332. #if ENABLE_PROFILE_INFO
  1333. JavascriptArray * JavascriptArray::FillFromArgs(uint length, uint start, Var *args, ArrayCallSiteInfo *arrayInfo, bool dontCreateNewArray)
  1334. #else
  1335. JavascriptArray * JavascriptArray::FillFromArgs(uint length, uint start, Var *args, bool dontCreateNewArray)
  1336. #endif
  1337. {
  1338. uint32 i;
  1339. for (i = start; i < length; i++)
  1340. {
  1341. Var item = args[i + 1];
  1342. this->DirectSetItemAt(i, item);
  1343. }
  1344. return this;
  1345. }
  1346. DynamicType * JavascriptNativeIntArray::GetInitialType(ScriptContext * scriptContext)
  1347. {
  1348. return scriptContext->GetLibrary()->GetNativeIntArrayType();
  1349. }
  1350. #if ENABLE_COPYONACCESS_ARRAY
  1351. DynamicType * JavascriptCopyOnAccessNativeIntArray::GetInitialType(ScriptContext * scriptContext)
  1352. {
  1353. return scriptContext->GetLibrary()->GetCopyOnAccessNativeIntArrayType();
  1354. }
  1355. #endif
  1356. JavascriptNativeFloatArray *JavascriptNativeIntArray::ToNativeFloatArray(JavascriptNativeIntArray *intArray)
  1357. {
  1358. #if ENABLE_PROFILE_INFO
  1359. ArrayCallSiteInfo *arrayInfo = intArray->GetArrayCallSiteInfo();
  1360. if (arrayInfo)
  1361. {
  1362. #if DBG
  1363. Js::JavascriptStackWalker walker(intArray->GetScriptContext());
  1364. Js::JavascriptFunction* caller = nullptr;
  1365. bool foundScriptCaller = false;
  1366. while(walker.GetCaller(&caller))
  1367. {
  1368. if(caller != nullptr && Js::ScriptFunction::Test(caller))
  1369. {
  1370. foundScriptCaller = true;
  1371. break;
  1372. }
  1373. }
  1374. if(foundScriptCaller)
  1375. {
  1376. Assert(caller);
  1377. Assert(caller->GetFunctionBody());
  1378. if(PHASE_TRACE(Js::NativeArrayConversionPhase, caller->GetFunctionBody()))
  1379. {
  1380. Output::Print(_u("Conversion: Int array to Float array ArrayCreationFunctionNumber:%2d CallSiteNumber:%2d \n"), arrayInfo->functionNumber, arrayInfo->callSiteNumber);
  1381. Output::Flush();
  1382. }
  1383. }
  1384. else
  1385. {
  1386. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1387. {
  1388. Output::Print(_u("Conversion: Int array to Float array across ScriptContexts"));
  1389. Output::Flush();
  1390. }
  1391. }
  1392. #else
  1393. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1394. {
  1395. Output::Print(_u("Conversion: Int array to Float array"));
  1396. Output::Flush();
  1397. }
  1398. #endif
  1399. arrayInfo->SetIsNotNativeIntArray();
  1400. }
  1401. #endif
  1402. ScriptContext *scriptContext = intArray->GetScriptContext();
  1403. // Code below has potential to throw due to OOM or SO. Just FailFast on those cases
  1404. AutoDisableInterrupt failFastError(scriptContext->GetThreadContext());
  1405. // Grow the segments
  1406. Recycler *recycler = scriptContext->GetRecycler();
  1407. SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
  1408. for (seg = intArray->head; seg; seg = nextSeg)
  1409. {
  1410. nextSeg = seg->next;
  1411. uint32 size = seg->size;
  1412. if (size == 0)
  1413. {
  1414. continue;
  1415. }
  1416. uint32 left = seg->left;
  1417. uint32 length = seg->length;
  1418. int i;
  1419. int32 ival;
  1420. // The old segment will have size/2 and length capped by the new size.
  1421. uint32 newSegSize = seg->size >> 1;
  1422. if (seg == intArray->head || seg->length > (newSegSize >> 1))
  1423. {
  1424. // Some live elements are being pushed out of this segment, so allocate a new one.
  1425. SparseArraySegment<double> *newSeg =
  1426. SparseArraySegment<double>::AllocateSegment(recycler, left, length, nextSeg);
  1427. Assert(newSeg != nullptr);
  1428. Assert((prevSeg == nullptr) == (seg == intArray->head));
  1429. newSeg->next = nextSeg;
  1430. intArray->LinkSegments((SparseArraySegment<double>*)prevSeg, newSeg);
  1431. if (intArray->GetLastUsedSegment() == seg)
  1432. {
  1433. intArray->SetLastUsedSegment(newSeg);
  1434. }
  1435. prevSeg = newSeg;
  1436. SegmentBTree * segmentMap = intArray->GetSegmentMap();
  1437. if (segmentMap)
  1438. {
  1439. segmentMap->SwapSegment(left, seg, newSeg);
  1440. }
  1441. // Fill the new segment with the overflow.
  1442. for (i = 0; (uint)i < newSeg->length; i++)
  1443. {
  1444. ival = ((SparseArraySegment<int32>*)seg)->elements[i /*+ seg->length*/];
  1445. if (ival == JavascriptNativeIntArray::MissingItem)
  1446. {
  1447. continue;
  1448. }
  1449. newSeg->elements[i] = (double)ival;
  1450. }
  1451. }
  1452. else
  1453. {
  1454. seg->size = newSegSize >> 1;
  1455. seg->CheckLengthvsSize();
  1456. // Now convert the contents that will remain in the old segment.
  1457. for (i = seg->length - 1; i >= 0; i--)
  1458. {
  1459. ival = ((SparseArraySegment<int32>*)seg)->elements[i];
  1460. if (ival == JavascriptNativeIntArray::MissingItem)
  1461. {
  1462. ((SparseArraySegment<double>*)seg)->elements[i] = (double)JavascriptNativeFloatArray::MissingItem;
  1463. }
  1464. else
  1465. {
  1466. ((SparseArraySegment<double>*)seg)->elements[i] = (double)ival;
  1467. }
  1468. }
  1469. prevSeg = seg;
  1470. }
  1471. }
  1472. if (intArray->GetType() == scriptContext->GetLibrary()->GetNativeIntArrayType())
  1473. {
  1474. intArray->type = scriptContext->GetLibrary()->GetNativeFloatArrayType();
  1475. }
  1476. else
  1477. {
  1478. if (intArray->GetDynamicType()->GetIsLocked())
  1479. {
  1480. DynamicTypeHandler *typeHandler = intArray->GetDynamicType()->GetTypeHandler();
  1481. if (typeHandler->IsPathTypeHandler())
  1482. {
  1483. // We can't allow a type with the new type ID to be promoted to the old type.
  1484. // So go to a dictionary type handler, which will orphan the new type.
  1485. // This should be a corner case, so the inability to share the new type is unlikely to matter.
  1486. // If it does matter, try building a path from the new type's built-in root.
  1487. static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(intArray);
  1488. }
  1489. else
  1490. {
  1491. intArray->ChangeType();
  1492. }
  1493. }
  1494. intArray->GetType()->SetTypeId(TypeIds_NativeFloatArray);
  1495. }
  1496. if (CrossSite::IsCrossSiteObjectTyped(intArray))
  1497. {
  1498. Assert(VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::HasVirtualTable(intArray));
  1499. VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::SetVirtualTable(intArray);
  1500. }
  1501. else
  1502. {
  1503. Assert(VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(intArray));
  1504. VirtualTableInfo<JavascriptNativeFloatArray>::SetVirtualTable(intArray);
  1505. }
  1506. failFastError.Completed();
  1507. return (JavascriptNativeFloatArray*)intArray;
  1508. }
  1509. /*
  1510. * JavascriptArray::ChangeArrayTypeToNativeArray<double>
  1511. * - Converts the Var Array's type to NativeFloat.
  1512. * - Sets the VirtualTable to "JavascriptNativeFloatArray"
  1513. */
  1514. template<>
  1515. void JavascriptArray::ChangeArrayTypeToNativeArray<double>(JavascriptArray * varArray, ScriptContext * scriptContext)
  1516. {
  1517. AssertMsg(!JavascriptNativeArray::Is(varArray), "Ensure that the incoming Array is a Var array");
  1518. if (varArray->GetType() == scriptContext->GetLibrary()->GetArrayType())
  1519. {
  1520. varArray->type = scriptContext->GetLibrary()->GetNativeFloatArrayType();
  1521. }
  1522. else
  1523. {
  1524. if (varArray->GetDynamicType()->GetIsLocked())
  1525. {
  1526. DynamicTypeHandler *typeHandler = varArray->GetDynamicType()->GetTypeHandler();
  1527. if (typeHandler->IsPathTypeHandler())
  1528. {
  1529. // We can't allow a type with the new type ID to be promoted to the old type.
  1530. // So go to a dictionary type handler, which will orphan the new type.
  1531. // This should be a corner case, so the inability to share the new type is unlikely to matter.
  1532. // If it does matter, try building a path from the new type's built-in root.
  1533. static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(varArray);
  1534. }
  1535. else
  1536. {
  1537. varArray->ChangeType();
  1538. }
  1539. }
  1540. varArray->GetType()->SetTypeId(TypeIds_NativeFloatArray);
  1541. }
  1542. if (CrossSite::IsCrossSiteObjectTyped(varArray))
  1543. {
  1544. Assert(VirtualTableInfo<CrossSiteObject<JavascriptArray>>::HasVirtualTable(varArray));
  1545. VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::SetVirtualTable(varArray);
  1546. }
  1547. else
  1548. {
  1549. Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(varArray));
  1550. VirtualTableInfo<JavascriptNativeFloatArray>::SetVirtualTable(varArray);
  1551. }
  1552. }
  1553. /*
  1554. * JavascriptArray::ChangeArrayTypeToNativeArray<int32>
  1555. * - Converts the Var Array's type to NativeInt.
  1556. * - Sets the VirtualTable to "JavascriptNativeIntArray"
  1557. */
  1558. template<>
  1559. void JavascriptArray::ChangeArrayTypeToNativeArray<int32>(JavascriptArray * varArray, ScriptContext * scriptContext)
  1560. {
  1561. AssertMsg(!JavascriptNativeArray::Is(varArray), "Ensure that the incoming Array is a Var array");
  1562. if (varArray->GetType() == scriptContext->GetLibrary()->GetArrayType())
  1563. {
  1564. varArray->type = scriptContext->GetLibrary()->GetNativeIntArrayType();
  1565. }
  1566. else
  1567. {
  1568. if (varArray->GetDynamicType()->GetIsLocked())
  1569. {
  1570. DynamicTypeHandler *typeHandler = varArray->GetDynamicType()->GetTypeHandler();
  1571. if (typeHandler->IsPathTypeHandler())
  1572. {
  1573. // We can't allow a type with the new type ID to be promoted to the old type.
  1574. // So go to a dictionary type handler, which will orphan the new type.
  1575. // This should be a corner case, so the inability to share the new type is unlikely to matter.
  1576. // If it does matter, try building a path from the new type's built-in root.
  1577. static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(varArray);
  1578. }
  1579. else
  1580. {
  1581. varArray->ChangeType();
  1582. }
  1583. }
  1584. varArray->GetType()->SetTypeId(TypeIds_NativeIntArray);
  1585. }
  1586. if (CrossSite::IsCrossSiteObjectTyped(varArray))
  1587. {
  1588. Assert(VirtualTableInfo<CrossSiteObject<JavascriptArray>>::HasVirtualTable(varArray));
  1589. VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::SetVirtualTable(varArray);
  1590. }
  1591. else
  1592. {
  1593. Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(varArray));
  1594. VirtualTableInfo<JavascriptNativeIntArray>::SetVirtualTable(varArray);
  1595. }
  1596. }
  1597. template<>
  1598. int32 JavascriptArray::GetNativeValue<int32>(Js::Var ival, ScriptContext * scriptContext)
  1599. {
  1600. return JavascriptConversion::ToInt32(ival, scriptContext);
  1601. }
  1602. template <>
  1603. double JavascriptArray::GetNativeValue<double>(Var ival, ScriptContext * scriptContext)
  1604. {
  1605. return JavascriptConversion::ToNumber(ival, scriptContext);
  1606. }
  1607. /*
  1608. * JavascriptArray::ConvertToNativeArrayInPlace
  1609. * In place conversion of all Var elements to Native Int/Double elements in an array.
  1610. * We do not update the DynamicProfileInfo of the array here.
  1611. */
  1612. template<typename NativeArrayType, typename T>
  1613. NativeArrayType *JavascriptArray::ConvertToNativeArrayInPlace(JavascriptArray *varArray)
  1614. {
  1615. AssertMsg(!JavascriptNativeArray::Is(varArray), "Ensure that the incoming Array is a Var array");
  1616. ScriptContext *scriptContext = varArray->GetScriptContext();
  1617. SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
  1618. for (seg = varArray->head; seg; seg = nextSeg)
  1619. {
  1620. nextSeg = seg->next;
  1621. uint32 size = seg->size;
  1622. if (size == 0)
  1623. {
  1624. continue;
  1625. }
  1626. int i;
  1627. Var ival;
  1628. uint32 growFactor = sizeof(Var) / sizeof(T);
  1629. AssertMsg(growFactor == 1, "We support only in place conversion of Var array to Native Array");
  1630. // Now convert the contents that will remain in the old segment.
  1631. for (i = seg->length - 1; i >= 0; i--)
  1632. {
  1633. ival = ((SparseArraySegment<Var>*)seg)->elements[i];
  1634. if (ival == JavascriptArray::MissingItem)
  1635. {
  1636. ((SparseArraySegment<T>*)seg)->elements[i] = NativeArrayType::MissingItem;
  1637. }
  1638. else
  1639. {
  1640. ((SparseArraySegment<T>*)seg)->elements[i] = GetNativeValue<T>(ival, scriptContext);
  1641. }
  1642. }
  1643. prevSeg = seg;
  1644. }
  1645. // Update the type of the Array
  1646. ChangeArrayTypeToNativeArray<T>(varArray, scriptContext);
  1647. return (NativeArrayType*)varArray;
  1648. }
  1649. JavascriptArray *JavascriptNativeIntArray::ConvertToVarArray(JavascriptNativeIntArray *intArray)
  1650. {
  1651. #if ENABLE_COPYONACCESS_ARRAY
  1652. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(intArray);
  1653. #endif
  1654. ScriptContext *scriptContext = intArray->GetScriptContext();
  1655. Recycler *recycler = scriptContext->GetRecycler();
  1656. SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
  1657. // Code below has potential to throw due to OOM or SO. Just FailFast on those cases
  1658. AutoDisableInterrupt failFastError(scriptContext->GetThreadContext());
  1659. for (seg = intArray->head; seg; seg = nextSeg)
  1660. {
  1661. nextSeg = seg->next;
  1662. uint32 size = seg->size;
  1663. if (size == 0)
  1664. {
  1665. continue;
  1666. }
  1667. uint32 left = seg->left;
  1668. uint32 length = seg->length;
  1669. int i;
  1670. int32 ival;
  1671. // Shrink?
  1672. uint32 growFactor = sizeof(Var) / sizeof(int32);
  1673. if ((growFactor != 1 && (seg == intArray->head || seg->length > (seg->size / growFactor))) ||
  1674. (seg->next == nullptr && SparseArraySegmentBase::IsLeafSegment(seg, recycler)))
  1675. {
  1676. // Some live elements are being pushed out of this segment, so allocate a new one.
  1677. // And/or the old segment is not scanned by the recycler, so we need a new one to hold vars.
  1678. SparseArraySegment<Var> *newSeg =
  1679. SparseArraySegment<Var>::AllocateSegment(recycler, left, length, nextSeg);
  1680. AnalysisAssert(newSeg);
  1681. Assert((prevSeg == nullptr) == (seg == intArray->head));
  1682. newSeg->next = nextSeg;
  1683. intArray->LinkSegments((SparseArraySegment<Var>*)prevSeg, newSeg);
  1684. if (intArray->GetLastUsedSegment() == seg)
  1685. {
  1686. intArray->SetLastUsedSegment(newSeg);
  1687. }
  1688. prevSeg = newSeg;
  1689. SegmentBTree * segmentMap = intArray->GetSegmentMap();
  1690. if (segmentMap)
  1691. {
  1692. segmentMap->SwapSegment(left, seg, newSeg);
  1693. }
  1694. // Fill the new segment with the overflow.
  1695. for (i = 0; (uint)i < newSeg->length; i++)
  1696. {
  1697. ival = ((SparseArraySegment<int32>*)seg)->elements[i];
  1698. if (ival == JavascriptNativeIntArray::MissingItem)
  1699. {
  1700. continue;
  1701. }
  1702. newSeg->elements[i] = JavascriptNumber::ToVar(ival, scriptContext);
  1703. }
  1704. }
  1705. else
  1706. {
  1707. seg->size = seg->size / growFactor;
  1708. seg->CheckLengthvsSize();
  1709. // Now convert the contents that will remain in the old segment.
  1710. // Walk backward in case we're growing the element size.
  1711. for (i = seg->length - 1; i >= 0; i--)
  1712. {
  1713. ival = ((SparseArraySegment<int32>*)seg)->elements[i];
  1714. if (ival == JavascriptNativeIntArray::MissingItem)
  1715. {
  1716. ((SparseArraySegment<Var>*)seg)->elements[i] = (Var)JavascriptArray::MissingItem;
  1717. }
  1718. else
  1719. {
  1720. ((SparseArraySegment<Var>*)seg)->elements[i] = JavascriptNumber::ToVar(ival, scriptContext);
  1721. }
  1722. }
  1723. prevSeg = seg;
  1724. }
  1725. }
  1726. if (intArray->GetType() == scriptContext->GetLibrary()->GetNativeIntArrayType())
  1727. {
  1728. intArray->type = scriptContext->GetLibrary()->GetArrayType();
  1729. }
  1730. else
  1731. {
  1732. if (intArray->GetDynamicType()->GetIsLocked())
  1733. {
  1734. DynamicTypeHandler *typeHandler = intArray->GetDynamicType()->GetTypeHandler();
  1735. if (typeHandler->IsPathTypeHandler())
  1736. {
  1737. // We can't allow a type with the new type ID to be promoted to the old type.
  1738. // So go to a dictionary type handler, which will orphan the new type.
  1739. // This should be a corner case, so the inability to share the new type is unlikely to matter.
  1740. // If it does matter, try building a path from the new type's built-in root.
  1741. static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(intArray);
  1742. }
  1743. else
  1744. {
  1745. intArray->ChangeType();
  1746. }
  1747. }
  1748. intArray->GetType()->SetTypeId(TypeIds_Array);
  1749. }
  1750. if (CrossSite::IsCrossSiteObjectTyped(intArray))
  1751. {
  1752. Assert(VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::HasVirtualTable(intArray));
  1753. VirtualTableInfo<CrossSiteObject<JavascriptArray>>::SetVirtualTable(intArray);
  1754. }
  1755. else
  1756. {
  1757. Assert(VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(intArray));
  1758. VirtualTableInfo<JavascriptArray>::SetVirtualTable(intArray);
  1759. }
  1760. failFastError.Completed();
  1761. return intArray;
  1762. }
  1763. JavascriptArray *JavascriptNativeIntArray::ToVarArray(JavascriptNativeIntArray *intArray)
  1764. {
  1765. #if ENABLE_PROFILE_INFO
  1766. ArrayCallSiteInfo *arrayInfo = intArray->GetArrayCallSiteInfo();
  1767. if (arrayInfo)
  1768. {
  1769. #if DBG
  1770. Js::JavascriptStackWalker walker(intArray->GetScriptContext());
  1771. Js::JavascriptFunction* caller = nullptr;
  1772. bool foundScriptCaller = false;
  1773. while(walker.GetCaller(&caller))
  1774. {
  1775. if(caller != nullptr && Js::ScriptFunction::Test(caller))
  1776. {
  1777. foundScriptCaller = true;
  1778. break;
  1779. }
  1780. }
  1781. if(foundScriptCaller)
  1782. {
  1783. Assert(caller);
  1784. Assert(caller->GetFunctionBody());
  1785. if(PHASE_TRACE(Js::NativeArrayConversionPhase, caller->GetFunctionBody()))
  1786. {
  1787. Output::Print(_u("Conversion: Int array to Var array ArrayCreationFunctionNumber:%2d CallSiteNumber:%2d \n"), arrayInfo->functionNumber, arrayInfo->callSiteNumber);
  1788. Output::Flush();
  1789. }
  1790. }
  1791. else
  1792. {
  1793. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1794. {
  1795. Output::Print(_u("Conversion: Int array to Var array across ScriptContexts"));
  1796. Output::Flush();
  1797. }
  1798. }
  1799. #else
  1800. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1801. {
  1802. Output::Print(_u("Conversion: Int array to Var array"));
  1803. Output::Flush();
  1804. }
  1805. #endif
  1806. arrayInfo->SetIsNotNativeArray();
  1807. }
  1808. #endif
  1809. intArray->ClearArrayCallSiteIndex();
  1810. return ConvertToVarArray(intArray);
  1811. }
  1812. DynamicType * JavascriptNativeFloatArray::GetInitialType(ScriptContext * scriptContext)
  1813. {
  1814. return scriptContext->GetLibrary()->GetNativeFloatArrayType();
  1815. }
  1816. /*
  1817. * JavascriptNativeFloatArray::ConvertToVarArray
  1818. * This function only converts all Float elements to Var elements in an array.
  1819. * DynamicProfileInfo of the array is not updated in this function.
  1820. */
  1821. JavascriptArray *JavascriptNativeFloatArray::ConvertToVarArray(JavascriptNativeFloatArray *fArray)
  1822. {
  1823. // We can't be growing the size of the element.
  1824. Assert(sizeof(double) >= sizeof(Var));
  1825. uint32 shrinkFactor = sizeof(double) / sizeof(Var);
  1826. ScriptContext *scriptContext = fArray->GetScriptContext();
  1827. Recycler *recycler = scriptContext->GetRecycler();
  1828. SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
  1829. // Code below has potential to throw due to OOM or SO. Just FailFast on those cases
  1830. AutoDisableInterrupt failFastError(scriptContext->GetThreadContext());
  1831. for (seg = fArray->head; seg; seg = nextSeg)
  1832. {
  1833. nextSeg = seg->next;
  1834. if (seg->size == 0)
  1835. {
  1836. continue;
  1837. }
  1838. uint32 left = seg->left;
  1839. uint32 length = seg->length;
  1840. SparseArraySegment<Var> *newSeg;
  1841. if (seg->next == nullptr && SparseArraySegmentBase::IsLeafSegment(seg, recycler))
  1842. {
  1843. // The old segment is not scanned by the recycler, so we need a new one to hold vars.
  1844. newSeg =
  1845. SparseArraySegment<Var>::AllocateSegment(recycler, left, length, nextSeg);
  1846. Assert((prevSeg == nullptr) == (seg == fArray->head));
  1847. newSeg->next = nextSeg;
  1848. fArray->LinkSegments((SparseArraySegment<Var>*)prevSeg, newSeg);
  1849. if (fArray->GetLastUsedSegment() == seg)
  1850. {
  1851. fArray->SetLastUsedSegment(newSeg);
  1852. }
  1853. prevSeg = newSeg;
  1854. SegmentBTree * segmentMap = fArray->GetSegmentMap();
  1855. if (segmentMap)
  1856. {
  1857. segmentMap->SwapSegment(left, seg, newSeg);
  1858. }
  1859. }
  1860. else
  1861. {
  1862. newSeg = (SparseArraySegment<Var>*)seg;
  1863. prevSeg = seg;
  1864. if (shrinkFactor != 1)
  1865. {
  1866. uint32 newSize = seg->size * shrinkFactor;
  1867. uint32 limit;
  1868. if (seg->next)
  1869. {
  1870. limit = seg->next->left;
  1871. }
  1872. else
  1873. {
  1874. limit = JavascriptArray::MaxArrayLength;
  1875. }
  1876. seg->size = min(newSize, limit - seg->left);
  1877. seg->CheckLengthvsSize();
  1878. }
  1879. }
  1880. uint32 i;
  1881. for (i = 0; i < seg->length; i++)
  1882. {
  1883. if (SparseArraySegment<double>::IsMissingItem(&((SparseArraySegment<double>*)seg)->elements[i]))
  1884. {
  1885. if (seg == newSeg)
  1886. {
  1887. newSeg->elements[i] = (Var)JavascriptArray::MissingItem;
  1888. }
  1889. Assert(newSeg->elements[i] == (Var)JavascriptArray::MissingItem);
  1890. }
  1891. else if (*(uint64*)&(((SparseArraySegment<double>*)seg)->elements[i]) == 0ull)
  1892. {
  1893. newSeg->elements[i] = TaggedInt::ToVarUnchecked(0);
  1894. }
  1895. else
  1896. {
  1897. int32 ival;
  1898. double dval = ((SparseArraySegment<double>*)seg)->elements[i];
  1899. if (JavascriptNumber::TryGetInt32Value(dval, &ival) && !TaggedInt::IsOverflow(ival))
  1900. {
  1901. newSeg->elements[i] = TaggedInt::ToVarUnchecked(ival);
  1902. }
  1903. else
  1904. {
  1905. newSeg->elements[i] = JavascriptNumber::ToVarWithCheck(dval, scriptContext);
  1906. }
  1907. }
  1908. }
  1909. if (seg == newSeg && shrinkFactor != 1)
  1910. {
  1911. // Fill the remaining slots.
  1912. newSeg->FillSegmentBuffer(i, seg->size);
  1913. }
  1914. }
  1915. if (fArray->GetType() == scriptContext->GetLibrary()->GetNativeFloatArrayType())
  1916. {
  1917. fArray->type = scriptContext->GetLibrary()->GetArrayType();
  1918. }
  1919. else
  1920. {
  1921. if (fArray->GetDynamicType()->GetIsLocked())
  1922. {
  1923. DynamicTypeHandler *typeHandler = fArray->GetDynamicType()->GetTypeHandler();
  1924. if (typeHandler->IsPathTypeHandler())
  1925. {
  1926. // We can't allow a type with the new type ID to be promoted to the old type.
  1927. // So go to a dictionary type handler, which will orphan the new type.
  1928. // This should be a corner case, so the inability to share the new type is unlikely to matter.
  1929. // If it does matter, try building a path from the new type's built-in root.
  1930. static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(fArray);
  1931. }
  1932. else
  1933. {
  1934. fArray->ChangeType();
  1935. }
  1936. }
  1937. fArray->GetType()->SetTypeId(TypeIds_Array);
  1938. }
  1939. if (CrossSite::IsCrossSiteObjectTyped(fArray))
  1940. {
  1941. Assert(VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::HasVirtualTable(fArray));
  1942. VirtualTableInfo<CrossSiteObject<JavascriptArray>>::SetVirtualTable(fArray);
  1943. }
  1944. else
  1945. {
  1946. Assert(VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(fArray));
  1947. VirtualTableInfo<JavascriptArray>::SetVirtualTable(fArray);
  1948. }
  1949. failFastError.Completed();
  1950. return fArray;
  1951. }
  1952. JavascriptArray *JavascriptNativeFloatArray::ToVarArray(JavascriptNativeFloatArray *fArray)
  1953. {
  1954. #if ENABLE_PROFILE_INFO
  1955. ArrayCallSiteInfo *arrayInfo = fArray->GetArrayCallSiteInfo();
  1956. if (arrayInfo)
  1957. {
  1958. #if DBG
  1959. Js::JavascriptStackWalker walker(fArray->GetScriptContext());
  1960. Js::JavascriptFunction* caller = nullptr;
  1961. bool foundScriptCaller = false;
  1962. while(walker.GetCaller(&caller))
  1963. {
  1964. if(caller != nullptr && Js::ScriptFunction::Test(caller))
  1965. {
  1966. foundScriptCaller = true;
  1967. break;
  1968. }
  1969. }
  1970. if(foundScriptCaller)
  1971. {
  1972. Assert(caller);
  1973. Assert(caller->GetFunctionBody());
  1974. if(PHASE_TRACE(Js::NativeArrayConversionPhase, caller->GetFunctionBody()))
  1975. {
  1976. Output::Print(_u("Conversion: Float array to Var array ArrayCreationFunctionNumber:%2d CallSiteNumber:%2d \n"), arrayInfo->functionNumber, arrayInfo->callSiteNumber);
  1977. Output::Flush();
  1978. }
  1979. }
  1980. else
  1981. {
  1982. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1983. {
  1984. Output::Print(_u("Conversion: Float array to Var array across ScriptContexts"));
  1985. Output::Flush();
  1986. }
  1987. }
  1988. #else
  1989. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1990. {
  1991. Output::Print(_u("Conversion: Float array to Var array"));
  1992. Output::Flush();
  1993. }
  1994. #endif
  1995. if(fArray->GetScriptContext()->IsScriptContextInNonDebugMode())
  1996. {
  1997. Assert(!arrayInfo->IsNativeIntArray());
  1998. }
  1999. arrayInfo->SetIsNotNativeArray();
  2000. }
  2001. #endif
  2002. fArray->ClearArrayCallSiteIndex();
  2003. return ConvertToVarArray(fArray);
  2004. }
  2005. // Convert Var to index in the Array.
  2006. // Note: Spec calls out a few rules for these parameters:
  2007. // 1. if (arg > length) { return length; }
  2008. // clamp to length, not length-1
  2009. // 2. if (arg < 0) { return max(0, length + arg); }
  2010. // treat negative arg as index from the end of the array (with -1 mapping to length-1)
  2011. // Effectively, this function will return a value between 0 and length, inclusive.
  2012. int64 JavascriptArray::GetIndexFromVar(Js::Var arg, int64 length, ScriptContext* scriptContext)
  2013. {
  2014. int64 index;
  2015. if (TaggedInt::Is(arg))
  2016. {
  2017. int intValue = TaggedInt::ToInt32(arg);
  2018. if (intValue < 0)
  2019. {
  2020. index = max<int64>(0, length + intValue);
  2021. }
  2022. else
  2023. {
  2024. index = intValue;
  2025. }
  2026. if (index > length)
  2027. {
  2028. index = length;
  2029. }
  2030. }
  2031. else
  2032. {
  2033. double doubleValue = JavascriptConversion::ToInteger(arg, scriptContext);
  2034. // Handle the Number.POSITIVE_INFINITY case
  2035. if (doubleValue > length)
  2036. {
  2037. return length;
  2038. }
  2039. index = NumberUtilities::TryToInt64(doubleValue);
  2040. if (index < 0)
  2041. {
  2042. index = max<int64>(0, index + length);
  2043. }
  2044. }
  2045. return index;
  2046. }
  2047. TypeId JavascriptArray::OP_SetNativeIntElementC(JavascriptNativeIntArray *arr, uint32 index, Var value, ScriptContext *scriptContext)
  2048. {
  2049. int32 iValue;
  2050. double dValue;
  2051. TypeId typeId = arr->TrySetNativeIntArrayItem(value, &iValue, &dValue);
  2052. if (typeId == TypeIds_NativeIntArray)
  2053. {
  2054. arr->SetArrayLiteralItem(index, iValue);
  2055. }
  2056. else if (typeId == TypeIds_NativeFloatArray)
  2057. {
  2058. arr->SetArrayLiteralItem(index, dValue);
  2059. }
  2060. else
  2061. {
  2062. arr->SetArrayLiteralItem(index, value);
  2063. }
  2064. return typeId;
  2065. }
  2066. TypeId JavascriptArray::OP_SetNativeFloatElementC(JavascriptNativeFloatArray *arr, uint32 index, Var value, ScriptContext *scriptContext)
  2067. {
  2068. double dValue;
  2069. TypeId typeId = arr->TrySetNativeFloatArrayItem(value, &dValue);
  2070. if (typeId == TypeIds_NativeFloatArray)
  2071. {
  2072. arr->SetArrayLiteralItem(index, dValue);
  2073. }
  2074. else
  2075. {
  2076. arr->SetArrayLiteralItem(index, value);
  2077. }
  2078. return typeId;
  2079. }
  2080. template<typename T>
  2081. void JavascriptArray::SetArrayLiteralItem(uint32 index, T value)
  2082. {
  2083. SparseArraySegment<T> * segment = SparseArraySegment<T>::From(this->head);
  2084. Assert(segment->left == 0);
  2085. Assert(index < segment->length);
  2086. segment->elements[index] = value;
  2087. }
  2088. void JavascriptNativeIntArray::SetIsPrototype()
  2089. {
  2090. // Force the array to be non-native to simplify inspection, filling from proto, etc.
  2091. ToVarArray(this);
  2092. __super::SetIsPrototype();
  2093. }
  2094. void JavascriptNativeFloatArray::SetIsPrototype()
  2095. {
  2096. // Force the array to be non-native to simplify inspection, filling from proto, etc.
  2097. ToVarArray(this);
  2098. __super::SetIsPrototype();
  2099. }
  2100. #if ENABLE_PROFILE_INFO
  2101. ArrayCallSiteInfo *JavascriptNativeArray::GetArrayCallSiteInfo()
  2102. {
  2103. RecyclerWeakReference<FunctionBody> *weakRef = this->weakRefToFuncBody;
  2104. if (weakRef)
  2105. {
  2106. FunctionBody *functionBody = weakRef->Get();
  2107. if (functionBody)
  2108. {
  2109. if (functionBody->HasDynamicProfileInfo())
  2110. {
  2111. Js::ProfileId profileId = this->GetArrayCallSiteIndex();
  2112. if (profileId < functionBody->GetProfiledArrayCallSiteCount())
  2113. {
  2114. return functionBody->GetAnyDynamicProfileInfo()->GetArrayCallSiteInfo(functionBody, profileId);
  2115. }
  2116. }
  2117. }
  2118. else
  2119. {
  2120. this->ClearArrayCallSiteIndex();
  2121. }
  2122. }
  2123. return nullptr;
  2124. }
  2125. void JavascriptNativeArray::SetArrayProfileInfo(RecyclerWeakReference<FunctionBody> *weakRef, ArrayCallSiteInfo *arrayInfo)
  2126. {
  2127. Assert(weakRef);
  2128. FunctionBody *functionBody = weakRef->Get();
  2129. if (functionBody && functionBody->HasDynamicProfileInfo())
  2130. {
  2131. ArrayCallSiteInfo *baseInfo = functionBody->GetAnyDynamicProfileInfo()->GetArrayCallSiteInfo(functionBody, 0);
  2132. Js::ProfileId index = (Js::ProfileId)(arrayInfo - baseInfo);
  2133. Assert(index < functionBody->GetProfiledArrayCallSiteCount());
  2134. SetArrayCallSite(index, weakRef);
  2135. }
  2136. }
  2137. void JavascriptNativeArray::CopyArrayProfileInfo(Js::JavascriptNativeArray* baseArray)
  2138. {
  2139. if (baseArray->weakRefToFuncBody)
  2140. {
  2141. if (baseArray->weakRefToFuncBody->Get())
  2142. {
  2143. SetArrayCallSite(baseArray->GetArrayCallSiteIndex(), baseArray->weakRefToFuncBody);
  2144. }
  2145. else
  2146. {
  2147. baseArray->ClearArrayCallSiteIndex();
  2148. }
  2149. }
  2150. }
  2151. #endif
  2152. Var JavascriptNativeArray::FindMinOrMax(Js::ScriptContext * scriptContext, bool findMax)
  2153. {
  2154. if (JavascriptNativeIntArray::Is(this))
  2155. {
  2156. return this->FindMinOrMax<int32, false>(scriptContext, findMax);
  2157. }
  2158. else
  2159. {
  2160. return this->FindMinOrMax<double, true>(scriptContext, findMax);
  2161. }
  2162. }
  2163. template <typename T, bool checkNaNAndNegZero>
  2164. Var JavascriptNativeArray::FindMinOrMax(Js::ScriptContext * scriptContext, bool findMax)
  2165. {
  2166. AssertMsg(this->HasNoMissingValues(), "Fastpath is only for arrays with one segment and no missing values");
  2167. uint len = this->GetLength();
  2168. Js::SparseArraySegment<T>* headSegment = ((Js::SparseArraySegment<T>*)this->GetHead());
  2169. uint headSegLen = headSegment->length;
  2170. Assert(headSegLen == len);
  2171. if (headSegment->next == nullptr)
  2172. {
  2173. T currentRes = headSegment->elements[0];
  2174. for (uint i = 0; i < headSegLen; i++)
  2175. {
  2176. T compare = headSegment->elements[i];
  2177. if (checkNaNAndNegZero && JavascriptNumber::IsNan(double(compare)))
  2178. {
  2179. return scriptContext->GetLibrary()->GetNaN();
  2180. }
  2181. if (findMax ? currentRes < compare : currentRes > compare ||
  2182. (checkNaNAndNegZero && compare == 0 && Js::JavascriptNumber::IsNegZero(double(currentRes))))
  2183. {
  2184. currentRes = compare;
  2185. }
  2186. }
  2187. return Js::JavascriptNumber::ToVarNoCheck(currentRes, scriptContext);
  2188. }
  2189. else
  2190. {
  2191. AssertMsg(false, "FindMinOrMax currently supports native arrays with only one segment");
  2192. Throw::FatalInternalError();
  2193. }
  2194. }
  2195. SparseArraySegmentBase * JavascriptArray::GetLastUsedSegment() const
  2196. {
  2197. return HasSegmentMap() ?
  2198. PointerValue(segmentUnion.segmentBTreeRoot->lastUsedSegment) :
  2199. PointerValue(segmentUnion.lastUsedSegment);
  2200. }
  2201. void JavascriptArray::SetHeadAndLastUsedSegment(SparseArraySegmentBase * segment)
  2202. {
  2203. Assert(!HasSegmentMap());
  2204. this->head = this->segmentUnion.lastUsedSegment = segment;
  2205. }
  2206. void JavascriptArray::SetLastUsedSegment(SparseArraySegmentBase * segment)
  2207. {
  2208. if (HasSegmentMap())
  2209. {
  2210. this->segmentUnion.segmentBTreeRoot->lastUsedSegment = segment;
  2211. }
  2212. else
  2213. {
  2214. this->segmentUnion.lastUsedSegment = segment;
  2215. }
  2216. }
  2217. bool JavascriptArray::HasSegmentMap() const
  2218. {
  2219. return !!(GetFlags() & DynamicObjectFlags::HasSegmentMap);
  2220. }
  2221. SegmentBTreeRoot * JavascriptArray::GetSegmentMap() const
  2222. {
  2223. return (HasSegmentMap() ? segmentUnion.segmentBTreeRoot : nullptr);
  2224. }
  2225. void JavascriptArray::SetSegmentMap(SegmentBTreeRoot * segmentMap)
  2226. {
  2227. Assert(!HasSegmentMap());
  2228. SparseArraySegmentBase * lastUsedSeg = this->segmentUnion.lastUsedSegment;
  2229. SetFlags(GetFlags() | DynamicObjectFlags::HasSegmentMap);
  2230. segmentUnion.segmentBTreeRoot = segmentMap;
  2231. segmentMap->lastUsedSegment = lastUsedSeg;
  2232. }
  2233. void JavascriptArray::ClearSegmentMap()
  2234. {
  2235. if (HasSegmentMap())
  2236. {
  2237. SetFlags(GetFlags() & ~DynamicObjectFlags::HasSegmentMap);
  2238. SparseArraySegmentBase * lastUsedSeg = segmentUnion.segmentBTreeRoot->lastUsedSegment;
  2239. segmentUnion.segmentBTreeRoot = nullptr;
  2240. segmentUnion.lastUsedSegment = lastUsedSeg;
  2241. }
  2242. }
  2243. SegmentBTreeRoot * JavascriptArray::BuildSegmentMap()
  2244. {
  2245. Recycler* recycler = GetRecycler();
  2246. SegmentBTreeRoot* tmpSegmentMap = AllocatorNewStruct(Recycler, recycler, SegmentBTreeRoot);
  2247. ForEachSegment([recycler, tmpSegmentMap](SparseArraySegmentBase * current)
  2248. {
  2249. tmpSegmentMap->Add(recycler, current);
  2250. return false;
  2251. });
  2252. // There could be OOM during building segment map. Save to array only after its successful completion.
  2253. SetSegmentMap(tmpSegmentMap);
  2254. return tmpSegmentMap;
  2255. }
  2256. void JavascriptArray::TryAddToSegmentMap(Recycler* recycler, SparseArraySegmentBase* seg)
  2257. {
  2258. SegmentBTreeRoot * savedSegmentMap = GetSegmentMap();
  2259. if (savedSegmentMap)
  2260. {
  2261. //
  2262. // We could OOM and throw when adding to segmentMap, resulting in a corrupted segmentMap on this
  2263. // array. Set segmentMap to null temporarily to protect from this. It will be restored correctly
  2264. // if adding segment succeeds.
  2265. //
  2266. ClearSegmentMap();
  2267. savedSegmentMap->Add(recycler, seg);
  2268. SetSegmentMap(savedSegmentMap);
  2269. }
  2270. }
  2271. void JavascriptArray::InvalidateLastUsedSegment()
  2272. {
  2273. this->SetLastUsedSegment(this->head);
  2274. }
  2275. DescriptorFlags JavascriptArray::GetSetter(PropertyId propertyId, Var *setterValue, PropertyValueInfo* info, ScriptContext* requestContext)
  2276. {
  2277. DescriptorFlags flags;
  2278. if (GetSetterBuiltIns(propertyId, info, &flags))
  2279. {
  2280. return flags;
  2281. }
  2282. return __super::GetSetter(propertyId, setterValue, info, requestContext);
  2283. }
  2284. DescriptorFlags JavascriptArray::GetSetter(JavascriptString* propertyNameString, Var *setterValue, PropertyValueInfo* info, ScriptContext* requestContext)
  2285. {
  2286. DescriptorFlags flags;
  2287. PropertyRecord const* propertyRecord;
  2288. this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
  2289. if (propertyRecord != nullptr && GetSetterBuiltIns(propertyRecord->GetPropertyId(), info, &flags))
  2290. {
  2291. return flags;
  2292. }
  2293. return __super::GetSetter(propertyNameString, setterValue, info, requestContext);
  2294. }
  2295. bool JavascriptArray::GetSetterBuiltIns(PropertyId propertyId, PropertyValueInfo* info, DescriptorFlags* descriptorFlags)
  2296. {
  2297. if (propertyId == PropertyIds::length)
  2298. {
  2299. PropertyValueInfo::SetNoCache(info, this);
  2300. *descriptorFlags = WritableData;
  2301. return true;
  2302. }
  2303. return false;
  2304. }
  2305. SparseArraySegmentBase * JavascriptArray::GetBeginLookupSegment(uint32 index, const bool useSegmentMap) const
  2306. {
  2307. SparseArraySegmentBase *seg = nullptr;
  2308. SparseArraySegmentBase * lastUsedSeg = this->GetLastUsedSegment();
  2309. if (lastUsedSeg != nullptr && lastUsedSeg->left <= index)
  2310. {
  2311. seg = lastUsedSeg;
  2312. if(index - lastUsedSeg->left < lastUsedSeg->size)
  2313. {
  2314. return seg;
  2315. }
  2316. }
  2317. SegmentBTreeRoot * segmentMap = GetSegmentMap();
  2318. if(!useSegmentMap || !segmentMap)
  2319. {
  2320. return seg ? seg : PointerValue(this->head);
  2321. }
  2322. if(seg)
  2323. {
  2324. // If indexes are being accessed sequentially, check the segment after the last-used segment before checking the
  2325. // segment map, as it is likely to hit
  2326. SparseArraySegmentBase *const nextSeg = seg->next;
  2327. if(nextSeg)
  2328. {
  2329. if(index < nextSeg->left)
  2330. {
  2331. return seg;
  2332. }
  2333. else if(index - nextSeg->left < nextSeg->size)
  2334. {
  2335. return nextSeg;
  2336. }
  2337. }
  2338. }
  2339. SparseArraySegmentBase *matchOrNextSeg;
  2340. segmentMap->Find(index, seg, matchOrNextSeg);
  2341. return seg ? seg : matchOrNextSeg;
  2342. }
  2343. uint32 JavascriptArray::GetNextIndex(uint32 index) const
  2344. {
  2345. if (JavascriptNativeIntArray::Is((Var)this))
  2346. {
  2347. return this->GetNextIndexHelper<int32>(index);
  2348. }
  2349. else if (JavascriptNativeFloatArray::Is((Var)this))
  2350. {
  2351. return this->GetNextIndexHelper<double>(index);
  2352. }
  2353. return this->GetNextIndexHelper<Var>(index);
  2354. }
  2355. template<typename T>
  2356. uint32 JavascriptArray::GetNextIndexHelper(uint32 index) const
  2357. {
  2358. AssertMsg(this->head, "array head should never be null");
  2359. uint candidateIndex;
  2360. if (index == JavascriptArray::InvalidIndex)
  2361. {
  2362. candidateIndex = head->left;
  2363. }
  2364. else
  2365. {
  2366. candidateIndex = index + 1;
  2367. }
  2368. SparseArraySegment<T>* current = (SparseArraySegment<T>*)this->GetBeginLookupSegment(candidateIndex);
  2369. while (current != nullptr)
  2370. {
  2371. if ((current->left <= candidateIndex) && ((candidateIndex - current->left) < current->length))
  2372. {
  2373. for (uint i = candidateIndex - current->left; i < current->length; i++)
  2374. {
  2375. if (!SparseArraySegment<T>::IsMissingItem(&current->elements[i]))
  2376. {
  2377. return i + current->left;
  2378. }
  2379. }
  2380. }
  2381. current = SparseArraySegment<T>::From(current->next);
  2382. if (current != NULL)
  2383. {
  2384. if (candidateIndex < current->left)
  2385. {
  2386. candidateIndex = current->left;
  2387. }
  2388. }
  2389. }
  2390. return JavascriptArray::InvalidIndex;
  2391. }
  2392. // If new length > length, we just reset the length
  2393. // If new length < length, we need to remove the rest of the elements and segment
  2394. void JavascriptArray::SetLength(uint32 newLength)
  2395. {
  2396. if (newLength == length)
  2397. return;
  2398. if (head == EmptySegment)
  2399. {
  2400. // Do nothing to the segment.
  2401. }
  2402. else if (newLength == 0)
  2403. {
  2404. this->ClearElements(head, 0);
  2405. head->length = 0;
  2406. head->next = nullptr;
  2407. SetHasNoMissingValues();
  2408. ClearSegmentMap();
  2409. this->InvalidateLastUsedSegment();
  2410. }
  2411. else if (newLength < length)
  2412. {
  2413. // _ _ 2 3 _ _ 6 7 _ _
  2414. // SetLength(0)
  2415. // 0 <= left -> set *prev = null
  2416. // SetLength(2)
  2417. // 2 <= left -> set *prev = null
  2418. // SetLength(3)
  2419. // 3 !<= left; 3 <= right -> truncate to length - 1
  2420. // SetLength(5)
  2421. // 5 <=
  2422. SparseArraySegmentBase* next = GetBeginLookupSegment(newLength - 1); // head, or next.left < newLength
  2423. Field(SparseArraySegmentBase*)* prev = &head;
  2424. while(next != nullptr)
  2425. {
  2426. if (newLength <= next->left)
  2427. {
  2428. ClearSegmentMap(); // truncate segments, null out segmentMap
  2429. *prev = nullptr;
  2430. break;
  2431. }
  2432. else if (newLength <= (next->left + next->length))
  2433. {
  2434. if (next->next)
  2435. {
  2436. ClearSegmentMap(); // Will truncate segments, null out segmentMap
  2437. }
  2438. uint32 newSegmentLength = newLength - next->left;
  2439. this->ClearElements(next, newSegmentLength);
  2440. next->next = nullptr;
  2441. next->length = newSegmentLength;
  2442. next->CheckLengthvsSize();
  2443. break;
  2444. }
  2445. else
  2446. {
  2447. prev = &next->next;
  2448. next = next->next;
  2449. }
  2450. }
  2451. this->InvalidateLastUsedSegment();
  2452. }
  2453. this->length = newLength;
  2454. #ifdef VALIDATE_ARRAY
  2455. ValidateArray();
  2456. #endif
  2457. }
  2458. BOOL JavascriptArray::SetLength(Var newLength)
  2459. {
  2460. ScriptContext *scriptContext;
  2461. if(TaggedInt::Is(newLength))
  2462. {
  2463. int32 lenValue = TaggedInt::ToInt32(newLength);
  2464. if (lenValue < 0)
  2465. {
  2466. scriptContext = GetScriptContext();
  2467. if (scriptContext->GetThreadContext()->RecordImplicitException())
  2468. {
  2469. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  2470. }
  2471. }
  2472. else
  2473. {
  2474. this->SetLength(lenValue);
  2475. }
  2476. return TRUE;
  2477. }
  2478. scriptContext = GetScriptContext();
  2479. uint32 uintValue = JavascriptConversion::ToUInt32(newLength, scriptContext);
  2480. double dblValue = JavascriptConversion::ToNumber(newLength, scriptContext);
  2481. if (dblValue == uintValue)
  2482. {
  2483. this->SetLength(uintValue);
  2484. }
  2485. else
  2486. {
  2487. ThreadContext* threadContext = scriptContext->GetThreadContext();
  2488. ImplicitCallFlags flags = threadContext->GetImplicitCallFlags();
  2489. if (flags != ImplicitCall_None && threadContext->IsDisableImplicitCall())
  2490. {
  2491. // We couldn't execute the implicit call(s) needed to convert the newLength to an integer.
  2492. // Do nothing and let the jitted code bail out.
  2493. return TRUE;
  2494. }
  2495. if (threadContext->RecordImplicitException())
  2496. {
  2497. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  2498. }
  2499. }
  2500. return TRUE;
  2501. }
  2502. void JavascriptArray::ClearElements(SparseArraySegmentBase *seg, uint32 newSegmentLength)
  2503. {
  2504. SparseArraySegment<Var>::ClearElements(((SparseArraySegment<Var>*)seg)->elements + newSegmentLength, seg->length - newSegmentLength);
  2505. }
  2506. void JavascriptNativeIntArray::ClearElements(SparseArraySegmentBase *seg, uint32 newSegmentLength)
  2507. {
  2508. SparseArraySegment<int32>::ClearElements(((SparseArraySegment<int32>*)seg)->elements + newSegmentLength, seg->length - newSegmentLength);
  2509. }
  2510. void JavascriptNativeFloatArray::ClearElements(SparseArraySegmentBase *seg, uint32 newSegmentLength)
  2511. {
  2512. SparseArraySegment<double>::ClearElements(((SparseArraySegment<double>*)seg)->elements + newSegmentLength, seg->length - newSegmentLength);
  2513. }
  2514. Var JavascriptArray::DirectGetItem(uint32 index)
  2515. {
  2516. SparseArraySegment<Var> *seg = (SparseArraySegment<Var>*)this->GetLastUsedSegment();
  2517. uint32 offset = index - seg->left;
  2518. if (index >= seg->left && offset < seg->length)
  2519. {
  2520. if (!SparseArraySegment<Var>::IsMissingItem(&seg->elements[offset]))
  2521. {
  2522. return seg->elements[offset];
  2523. }
  2524. }
  2525. Var element = nullptr;
  2526. if (DirectGetItemAtFull(index, &element))
  2527. {
  2528. return element;
  2529. }
  2530. return GetType()->GetLibrary()->GetUndefined();
  2531. }
  2532. Var JavascriptNativeIntArray::DirectGetItem(uint32 index)
  2533. {
  2534. #if ENABLE_COPYONACCESS_ARRAY
  2535. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  2536. #endif
  2537. SparseArraySegment<int32> *seg = (SparseArraySegment<int32>*)this->GetLastUsedSegment();
  2538. uint32 offset = index - seg->left;
  2539. if (index >= seg->left && offset < seg->length)
  2540. {
  2541. if (!SparseArraySegment<int32>::IsMissingItem(&seg->elements[offset]))
  2542. {
  2543. return JavascriptNumber::ToVar(seg->elements[offset], GetScriptContext());
  2544. }
  2545. }
  2546. Var element = nullptr;
  2547. if (DirectGetItemAtFull(index, &element))
  2548. {
  2549. return element;
  2550. }
  2551. return GetType()->GetLibrary()->GetUndefined();
  2552. }
  2553. DescriptorFlags JavascriptNativeIntArray::GetItemSetter(uint32 index, Var* setterValue, ScriptContext* requestContext)
  2554. {
  2555. #if ENABLE_COPYONACCESS_ARRAY
  2556. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  2557. #endif
  2558. int32 value = 0;
  2559. return this->DirectGetItemAt(index, &value) ? WritableData : None;
  2560. }
  2561. Var JavascriptNativeFloatArray::DirectGetItem(uint32 index)
  2562. {
  2563. SparseArraySegment<double> *seg = (SparseArraySegment<double>*)this->GetLastUsedSegment();
  2564. uint32 offset = index - seg->left;
  2565. if (index >= seg->left && offset < seg->length)
  2566. {
  2567. if (!SparseArraySegment<double>::IsMissingItem(&seg->elements[offset]))
  2568. {
  2569. return JavascriptNumber::ToVarWithCheck(seg->elements[offset], GetScriptContext());
  2570. }
  2571. }
  2572. Var element = nullptr;
  2573. if (DirectGetItemAtFull(index, &element))
  2574. {
  2575. return element;
  2576. }
  2577. return GetType()->GetLibrary()->GetUndefined();
  2578. }
  2579. Var JavascriptArray::DirectGetItem(JavascriptString *propName, ScriptContext* scriptContext)
  2580. {
  2581. PropertyRecord const * propertyRecord;
  2582. scriptContext->GetOrAddPropertyRecord(propName, &propertyRecord);
  2583. return JavascriptOperators::GetProperty(this, propertyRecord->GetPropertyId(), scriptContext, NULL);
  2584. }
  2585. BOOL JavascriptArray::DirectGetItemAtFull(uint32 index, Var* outVal)
  2586. {
  2587. if (this->DirectGetItemAt(index, outVal))
  2588. {
  2589. return TRUE;
  2590. }
  2591. ScriptContext* requestContext = type->GetScriptContext();
  2592. return JavascriptOperators::GetItem(this, this->GetPrototype(), index, outVal, requestContext);
  2593. }
  2594. //
  2595. // Link prev and current. If prev is NULL, make current the head segment.
  2596. //
  2597. void JavascriptArray::LinkSegmentsCommon(SparseArraySegmentBase* prev, SparseArraySegmentBase* current)
  2598. {
  2599. if (prev)
  2600. {
  2601. prev->next = current;
  2602. }
  2603. else
  2604. {
  2605. Assert(current);
  2606. head = current;
  2607. }
  2608. }
  2609. template<typename T>
  2610. BOOL JavascriptArray::DirectDeleteItemAt(uint32 itemIndex)
  2611. {
  2612. if (itemIndex >= length)
  2613. {
  2614. return true;
  2615. }
  2616. SparseArraySegment<T>* next = (SparseArraySegment<T>*)GetBeginLookupSegment(itemIndex);
  2617. while(next != nullptr && next->left <= itemIndex)
  2618. {
  2619. uint32 limit = next->left + next->length;
  2620. if (itemIndex < limit)
  2621. {
  2622. next->SetElement(GetRecycler(), itemIndex, SparseArraySegment<T>::GetMissingItem());
  2623. if(itemIndex - next->left == next->length - 1)
  2624. {
  2625. --next->length;
  2626. next->CheckLengthvsSize();
  2627. }
  2628. else if(next == head)
  2629. {
  2630. SetHasNoMissingValues(false);
  2631. }
  2632. break;
  2633. }
  2634. next = SparseArraySegment<T>::From(next->next);
  2635. }
  2636. #ifdef VALIDATE_ARRAY
  2637. ValidateArray();
  2638. #endif
  2639. return true;
  2640. }
  2641. template <> Var JavascriptArray::ConvertToIndex(BigIndex idxDest, ScriptContext* scriptContext)
  2642. {
  2643. return idxDest.ToNumber(scriptContext);
  2644. }
  2645. template <> uint32 JavascriptArray::ConvertToIndex(BigIndex idxDest, ScriptContext* scriptContext)
  2646. {
  2647. // Note this is only for setting Array length which is a uint32
  2648. return idxDest.IsSmallIndex() ? idxDest.GetSmallIndex() : UINT_MAX;
  2649. }
  2650. template <> Var JavascriptArray::ConvertToIndex(uint32 idxDest, ScriptContext* scriptContext)
  2651. {
  2652. return JavascriptNumber::ToVar(idxDest, scriptContext);
  2653. }
  2654. void JavascriptArray::ThrowErrorOnFailure(BOOL succeeded, ScriptContext* scriptContext, uint32 index)
  2655. {
  2656. if (!succeeded)
  2657. {
  2658. JavascriptError::ThrowTypeError(scriptContext, JSERR_CantRedefineProp, JavascriptConversion::ToString(JavascriptNumber::ToVar(index, scriptContext), scriptContext)->GetSz());
  2659. }
  2660. }
  2661. void JavascriptArray::ThrowErrorOnFailure(BOOL succeeded, ScriptContext* scriptContext, BigIndex index)
  2662. {
  2663. if (!succeeded)
  2664. {
  2665. uint64 i = (uint64)(index.IsSmallIndex() ? index.GetSmallIndex() : index.GetBigIndex());
  2666. JavascriptError::ThrowTypeError(scriptContext, JSERR_CantRedefineProp, JavascriptConversion::ToString(JavascriptNumber::ToVar(i, scriptContext), scriptContext)->GetSz());
  2667. }
  2668. }
  2669. BOOL JavascriptArray::SetArrayLikeObjects(RecyclableObject* pDestObj, uint32 idxDest, Var aItem)
  2670. {
  2671. return pDestObj->SetItem(idxDest, aItem, Js::PropertyOperation_ThrowIfNotExtensible);
  2672. }
  2673. uint64 JavascriptArray::OP_GetLength(Var obj, ScriptContext *scriptContext)
  2674. {
  2675. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  2676. {
  2677. // Casting to uint64 is okay as ToLength will always be >= 0.
  2678. return (uint64)JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
  2679. }
  2680. else
  2681. {
  2682. return (uint64)JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
  2683. }
  2684. }
  2685. template<typename T>
  2686. void JavascriptArray::TryGetArrayAndLength(Var arg,
  2687. ScriptContext *scriptContext,
  2688. PCWSTR methodName,
  2689. __out JavascriptArray** array,
  2690. __out RecyclableObject** obj,
  2691. __out T * length)
  2692. {
  2693. Assert(array != nullptr);
  2694. Assert(obj != nullptr);
  2695. Assert(length != nullptr);
  2696. *array = JavascriptOperators::TryFromVar<JavascriptArray>(arg);
  2697. if (*array && !(*array)->IsCrossSiteObject())
  2698. {
  2699. #if ENABLE_COPYONACCESS_ARRAY
  2700. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(*array);
  2701. #endif
  2702. *obj = *array;
  2703. *length = (*array)->length;
  2704. }
  2705. else
  2706. {
  2707. if (!JavascriptConversion::ToObject(arg, scriptContext, obj))
  2708. {
  2709. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, methodName);
  2710. }
  2711. *length = OP_GetLength(*obj, scriptContext);
  2712. *array = nullptr;
  2713. }
  2714. }
  2715. BOOL JavascriptArray::SetArrayLikeObjects(RecyclableObject* pDestObj, BigIndex idxDest, Var aItem)
  2716. {
  2717. ScriptContext* scriptContext = pDestObj->GetScriptContext();
  2718. if (idxDest.IsSmallIndex())
  2719. {
  2720. return pDestObj->SetItem(idxDest.GetSmallIndex(), aItem, Js::PropertyOperation_ThrowIfNotExtensible);
  2721. }
  2722. PropertyRecord const * propertyRecord;
  2723. JavascriptOperators::GetPropertyIdForInt(idxDest.GetBigIndex(), scriptContext, &propertyRecord);
  2724. return pDestObj->SetProperty(propertyRecord->GetPropertyId(), aItem, PropertyOperation_ThrowIfNotExtensible, nullptr);
  2725. }
  2726. template<typename T>
  2727. void JavascriptArray::ConcatArgs(RecyclableObject* pDestObj, TypeId* remoteTypeIds,
  2728. Js::Arguments& args, ScriptContext* scriptContext, uint start, BigIndex startIdxDest,
  2729. ConcatSpreadableState previousItemSpreadableState /*= ConcatSpreadableState_NotChecked*/, BigIndex *firstPromotedItemLength /* = nullptr */)
  2730. {
  2731. // This never gets called.
  2732. Throw::InternalError();
  2733. }
  2734. //
  2735. // Helper for EntryConcat. Concat args or elements of arg arrays into dest array.
  2736. //
  2737. template<typename T>
  2738. void JavascriptArray::ConcatArgs(RecyclableObject* pDestObj, TypeId* remoteTypeIds,
  2739. Js::Arguments& args, ScriptContext* scriptContext, uint start, uint startIdxDest,
  2740. ConcatSpreadableState previousItemSpreadableState /*= ConcatSpreadableState_NotChecked*/, BigIndex *firstPromotedItemLength /* = nullptr */)
  2741. {
  2742. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  2743. JavascriptArray* pDestArray = JavascriptOperators::TryFromVar<JavascriptArray>(pDestObj);
  2744. if (pDestArray)
  2745. {
  2746. // ConcatArgs function expects to work on the Var array so we are ensuring it.
  2747. pDestArray = EnsureNonNativeArray(pDestArray);
  2748. SET_SECOND_OBJECT_FOR_MUTATION(jsReentLock, pDestArray);
  2749. }
  2750. AssertOrFailFast(scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled()); // ConcatSpreadable is enabled already - not going back.
  2751. T idxDest = startIdxDest;
  2752. for (uint idxArg = start; idxArg < args.Info.Count; idxArg++)
  2753. {
  2754. Var aItem = args[idxArg];
  2755. SETOBJECT_FOR_MUTATION(jsReentLock, aItem);
  2756. bool spreadable = previousItemSpreadableState == ConcatSpreadableState_CheckedAndTrue;
  2757. if (previousItemSpreadableState == ConcatSpreadableState_NotChecked)
  2758. {
  2759. JS_REENTRANT(jsReentLock, spreadable = !!JavascriptOperators::IsConcatSpreadable(aItem));
  2760. }
  2761. // Reset the state for the next item in the array
  2762. previousItemSpreadableState = ConcatSpreadableState_NotChecked;
  2763. if (!spreadable)
  2764. {
  2765. JS_REENTRANT(jsReentLock, JavascriptArray::SetConcatItem<T>(aItem, idxArg, pDestArray, pDestObj, idxDest, scriptContext));
  2766. ++idxDest;
  2767. continue;
  2768. }
  2769. if (pDestArray && JavascriptArray::IsDirectAccessArray(aItem) && JavascriptArray::IsDirectAccessArray(pDestArray)
  2770. && BigIndex(idxDest + JavascriptArray::UnsafeFromVar(aItem)->length).IsSmallIndex() && !JavascriptArray::UnsafeFromVar(aItem)->IsFillFromPrototypes()) // Fast path
  2771. {
  2772. JavascriptNativeIntArray *pIntItemArray = JavascriptOperators::TryFromVar<JavascriptNativeIntArray>(aItem);
  2773. if (pIntItemArray)
  2774. {
  2775. JS_REENTRANT_NO_MUTATE(jsReentLock, CopyNativeIntArrayElementsToVar(pDestArray, BigIndex(idxDest).GetSmallIndex(), pIntItemArray));
  2776. idxDest = idxDest + pIntItemArray->length;
  2777. }
  2778. else
  2779. {
  2780. JavascriptNativeFloatArray *pFloatItemArray = JavascriptOperators::TryFromVar<JavascriptNativeFloatArray>(aItem);
  2781. if (pFloatItemArray)
  2782. {
  2783. JS_REENTRANT_NO_MUTATE(jsReentLock, CopyNativeFloatArrayElementsToVar(pDestArray, BigIndex(idxDest).GetSmallIndex(), pFloatItemArray));
  2784. idxDest = idxDest + pFloatItemArray->length;
  2785. }
  2786. else
  2787. {
  2788. JavascriptArray* pItemArray = JavascriptArray::UnsafeFromVar(aItem);
  2789. JS_REENTRANT(jsReentLock, CopyArrayElements(pDestArray, BigIndex(idxDest).GetSmallIndex(), pItemArray));
  2790. idxDest = idxDest + pItemArray->length;
  2791. }
  2792. }
  2793. }
  2794. else
  2795. {
  2796. AssertOrFailFast(RecyclableObject::Is(aItem));
  2797. //CONSIDER: enumerating remote array instead of walking all indices
  2798. BigIndex length;
  2799. if (firstPromotedItemLength != nullptr)
  2800. {
  2801. length = *firstPromotedItemLength;
  2802. }
  2803. else
  2804. {
  2805. JS_REENTRANT(jsReentLock, length = OP_GetLength(aItem, scriptContext));
  2806. }
  2807. if (PromoteToBigIndex(length, idxDest))
  2808. {
  2809. // This is a special case for spreadable objects. We do not pre-calculate the length
  2810. // in EntryConcat like we do with Arrays because a getProperty on an object Length
  2811. // is observable. The result is we have to check for overflows separately for
  2812. // spreadable objects and promote to a bigger index type when we find them.
  2813. JS_REENTRANT(jsReentLock, ConcatArgs<BigIndex>(pDestObj, remoteTypeIds, args, scriptContext, idxArg, idxDest, ConcatSpreadableState_CheckedAndTrue, &length));
  2814. return;
  2815. }
  2816. if (length + idxDest > FiftyThirdPowerOfTwoMinusOne) // 2^53-1: from ECMA 22.1.3.1 Array.prototype.concat(...arguments)
  2817. {
  2818. JavascriptError::ThrowTypeError(scriptContext, JSERR_IllegalArraySizeAndLength);
  2819. }
  2820. RecyclableObject* itemObject = RecyclableObject::FromVar(aItem);
  2821. Var subItem;
  2822. uint32 lengthToUin32Max = length.IsSmallIndex() ? length.GetSmallIndex() : MaxArrayLength;
  2823. for (uint32 idxSubItem = 0u; idxSubItem < lengthToUin32Max; ++idxSubItem)
  2824. {
  2825. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(itemObject, idxSubItem));
  2826. if (hasItem)
  2827. {
  2828. JS_REENTRANT(jsReentLock, subItem = JavascriptOperators::GetItem(itemObject, idxSubItem, scriptContext));
  2829. if (pDestArray)
  2830. {
  2831. pDestArray->GenericDirectSetItemAt(idxDest, subItem);
  2832. }
  2833. else
  2834. {
  2835. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(SetArrayLikeObjects(pDestObj, idxDest, subItem), scriptContext, idxDest));
  2836. }
  2837. }
  2838. ++idxDest;
  2839. }
  2840. for (BigIndex idxSubItem = MaxArrayLength; idxSubItem < length; ++idxSubItem)
  2841. {
  2842. PropertyRecord const * propertyRecord;
  2843. JavascriptOperators::GetPropertyIdForInt(idxSubItem.GetBigIndex(), scriptContext, &propertyRecord);
  2844. JS_REENTRANT(jsReentLock, BOOL hasProp = JavascriptOperators::HasProperty(itemObject, propertyRecord->GetPropertyId()));
  2845. if (hasProp)
  2846. {
  2847. JS_REENTRANT(jsReentLock, subItem = JavascriptOperators::GetProperty(itemObject, propertyRecord->GetPropertyId(), scriptContext));
  2848. if (pDestArray)
  2849. {
  2850. pDestArray->GenericDirectSetItemAt(idxDest, subItem);
  2851. }
  2852. else
  2853. {
  2854. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(SetArrayLikeObjects(pDestObj, idxDest, subItem), scriptContext, idxSubItem));
  2855. }
  2856. }
  2857. ++idxDest;
  2858. }
  2859. }
  2860. firstPromotedItemLength = nullptr;
  2861. }
  2862. if (!pDestArray)
  2863. {
  2864. JS_REENTRANT(jsReentLock, pDestObj->SetProperty(PropertyIds::length, ConvertToIndex<T, Var>(idxDest, scriptContext), Js::PropertyOperation_None, nullptr));
  2865. }
  2866. else if (pDestArray->GetLength() != ConvertToIndex<T, uint32>(idxDest, scriptContext))
  2867. {
  2868. pDestArray->SetLength(ConvertToIndex<T, uint32>(idxDest, scriptContext));
  2869. }
  2870. }
  2871. bool JavascriptArray::PromoteToBigIndex(BigIndex lhs, BigIndex rhs)
  2872. {
  2873. return false; // already a big index
  2874. }
  2875. bool JavascriptArray::PromoteToBigIndex(BigIndex lhs, uint32 rhs)
  2876. {
  2877. ::Math::RecordOverflowPolicy destLengthOverflow;
  2878. if (lhs.IsSmallIndex())
  2879. {
  2880. UInt32Math::Add(lhs.GetSmallIndex(), rhs, destLengthOverflow);
  2881. return destLengthOverflow.HasOverflowed();
  2882. }
  2883. return true;
  2884. }
  2885. JavascriptArray* JavascriptArray::ConcatIntArgs(JavascriptNativeIntArray* pDestArray, TypeId *remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext)
  2886. {
  2887. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  2888. SET_SECOND_OBJECT_FOR_MUTATION(jsReentLock, pDestArray);
  2889. AssertOrFailFast(scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled());
  2890. Assert(pDestArray->GetTypeId() == TypeIds_NativeIntArray);
  2891. uint idxDest = 0u;
  2892. for (uint idxArg = 0; idxArg < args.Info.Count; idxArg++)
  2893. {
  2894. Var aItem = args[idxArg];
  2895. SETOBJECT_FOR_MUTATION(jsReentLock, aItem);
  2896. bool spreadable = false;
  2897. JS_REENTRANT(jsReentLock, spreadable = !!JavascriptOperators::IsConcatSpreadable(aItem));
  2898. if (!JavascriptNativeIntArray::Is(pDestArray))
  2899. {
  2900. JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest,
  2901. spreadable ? ConcatSpreadableState_CheckedAndTrue : ConcatSpreadableState_CheckedAndFalse));
  2902. return pDestArray;
  2903. }
  2904. if (!spreadable)
  2905. {
  2906. JS_REENTRANT(jsReentLock, pDestArray->SetItem(idxDest, aItem, PropertyOperation_ThrowIfNotExtensible));
  2907. idxDest++;
  2908. if (!JavascriptNativeIntArray::Is(pDestArray)) // SetItem could convert pDestArray to a var array if aItem is not an integer if so fall back
  2909. {
  2910. JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest, ConcatSpreadableState_NotChecked));
  2911. return pDestArray;
  2912. }
  2913. continue;
  2914. }
  2915. JavascriptNativeIntArray * pItemArray = JavascriptOperators::TryFromVar<JavascriptNativeIntArray>(aItem);
  2916. if (pItemArray && !pItemArray->IsFillFromPrototypes()) // Fast path
  2917. {
  2918. JS_REENTRANT_NO_MUTATE(jsReentLock, bool converted = CopyNativeIntArrayElements(pDestArray, idxDest, pItemArray));
  2919. idxDest = idxDest + pItemArray->length;
  2920. if (converted)
  2921. {
  2922. // Copying the last array forced a conversion, so switch over to the var version
  2923. // to finish.
  2924. JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest, ConcatSpreadableState_NotChecked));
  2925. return pDestArray;
  2926. }
  2927. }
  2928. else if (!JavascriptArray::IsAnyArray(aItem) && remoteTypeIds[idxArg] != TypeIds_Array)
  2929. {
  2930. if (TaggedInt::Is(aItem))
  2931. {
  2932. pDestArray->DirectSetItemAt(idxDest, TaggedInt::ToInt32(aItem));
  2933. }
  2934. else
  2935. {
  2936. #if DBG
  2937. int32 int32Value;
  2938. Assert(
  2939. JavascriptNumber::TryGetInt32Value(JavascriptNumber::GetValue(aItem), &int32Value) &&
  2940. !SparseArraySegment<int32>::IsMissingItem(&int32Value));
  2941. #endif
  2942. pDestArray->DirectSetItemAt(idxDest, static_cast<int32>(JavascriptNumber::GetValue(aItem)));
  2943. }
  2944. ++idxDest;
  2945. }
  2946. else
  2947. {
  2948. JavascriptArray *pVarDestArray = JavascriptNativeIntArray::ConvertToVarArray(pDestArray);
  2949. BigIndex length;
  2950. JS_REENTRANT(jsReentLock, length = OP_GetLength(aItem, scriptContext),
  2951. ConcatArgs<uint>(pVarDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest, ConcatSpreadableState_CheckedAndTrue, &length));
  2952. return pVarDestArray;
  2953. }
  2954. }
  2955. if (pDestArray->GetLength() != idxDest)
  2956. {
  2957. pDestArray->SetLength(idxDest);
  2958. }
  2959. return pDestArray;
  2960. }
  2961. JavascriptArray* JavascriptArray::ConcatFloatArgs(JavascriptNativeFloatArray* pDestArray, TypeId *remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext)
  2962. {
  2963. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  2964. SET_SECOND_OBJECT_FOR_MUTATION(jsReentLock, pDestArray);
  2965. AssertOrFailFast(scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled());
  2966. uint idxDest = 0u;
  2967. for (uint idxArg = 0; idxArg < args.Info.Count; idxArg++)
  2968. {
  2969. Var aItem = args[idxArg];
  2970. SETOBJECT_FOR_MUTATION(jsReentLock, aItem);
  2971. bool spreadable = false;
  2972. JS_REENTRANT(jsReentLock, spreadable = !!JavascriptOperators::IsConcatSpreadable(aItem));
  2973. if (!JavascriptNativeFloatArray::Is(pDestArray))
  2974. {
  2975. JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest,
  2976. spreadable ? ConcatSpreadableState_CheckedAndTrue : ConcatSpreadableState_CheckedAndFalse));
  2977. return pDestArray;
  2978. }
  2979. if (!spreadable)
  2980. {
  2981. JS_REENTRANT(jsReentLock, pDestArray->SetItem(idxDest, aItem, PropertyOperation_ThrowIfNotExtensible));
  2982. idxDest = idxDest + 1;
  2983. if (!JavascriptNativeFloatArray::Is(pDestArray)) // SetItem could convert pDestArray to a var array if aItem is not an integer if so fall back
  2984. {
  2985. JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest, ConcatSpreadableState_NotChecked));
  2986. return pDestArray;
  2987. }
  2988. continue;
  2989. }
  2990. bool converted = false;
  2991. if (JavascriptArray::IsAnyArray(aItem) || remoteTypeIds[idxArg] == TypeIds_Array)
  2992. {
  2993. bool isFillFromPrototypes = JavascriptArray::UnsafeFromVar(aItem)->IsFillFromPrototypes();
  2994. JavascriptNativeIntArray * pIntItemArray = JavascriptOperators::TryFromVar<JavascriptNativeIntArray>(aItem);
  2995. if (pIntItemArray && !isFillFromPrototypes) // Fast path
  2996. {
  2997. JS_REENTRANT_NO_MUTATE(jsReentLock, converted = CopyNativeIntArrayElementsToFloat(pDestArray, idxDest, pIntItemArray));
  2998. idxDest = idxDest + pIntItemArray->length;
  2999. }
  3000. else
  3001. {
  3002. JavascriptNativeFloatArray * pFloatItemArray = JavascriptOperators::TryFromVar<JavascriptNativeFloatArray>(aItem);
  3003. if (pFloatItemArray && !isFillFromPrototypes)
  3004. {
  3005. JS_REENTRANT_NO_MUTATE(jsReentLock, converted = CopyNativeFloatArrayElements(pDestArray, idxDest, pFloatItemArray));
  3006. idxDest = idxDest + pFloatItemArray->length;
  3007. }
  3008. else
  3009. {
  3010. JavascriptArray *pVarDestArray = JavascriptNativeFloatArray::ConvertToVarArray(pDestArray);
  3011. BigIndex length;
  3012. JS_REENTRANT(jsReentLock, length = OP_GetLength(aItem, scriptContext),
  3013. ConcatArgs<uint>(pVarDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest, ConcatSpreadableState_CheckedAndTrue, &length));
  3014. return pVarDestArray;
  3015. }
  3016. }
  3017. if (converted)
  3018. {
  3019. // Copying the last array forced a conversion, so switch over to the var version
  3020. // to finish.
  3021. JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest, ConcatSpreadableState_NotChecked));
  3022. return pDestArray;
  3023. }
  3024. }
  3025. else
  3026. {
  3027. if (TaggedInt::Is(aItem))
  3028. {
  3029. pDestArray->DirectSetItemAt(idxDest, (double)TaggedInt::ToInt32(aItem));
  3030. }
  3031. else
  3032. {
  3033. Assert(JavascriptNumber::Is(aItem));
  3034. pDestArray->DirectSetItemAt(idxDest, JavascriptNumber::GetValue(aItem));
  3035. }
  3036. ++idxDest;
  3037. }
  3038. }
  3039. if (pDestArray->GetLength() != idxDest)
  3040. {
  3041. pDestArray->SetLength(idxDest);
  3042. }
  3043. return pDestArray;
  3044. }
  3045. bool JavascriptArray::BoxConcatItem(Var aItem, uint idxArg, ScriptContext *scriptContext)
  3046. {
  3047. return idxArg == 0 && !JavascriptOperators::IsObject(aItem);
  3048. }
  3049. Var JavascriptArray::EntryConcat(RecyclableObject* function, CallInfo callInfo, ...)
  3050. {
  3051. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  3052. ARGUMENTS(args, callInfo);
  3053. ScriptContext* scriptContext = function->GetScriptContext();
  3054. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3055. Assert(!(callInfo.Flags & CallFlags_New));
  3056. if (args.Info.Count == 0)
  3057. {
  3058. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.concat"));
  3059. }
  3060. //
  3061. // Compute the destination ScriptArray size:
  3062. // - Each item, flattening only one level if a ScriptArray.
  3063. //
  3064. uint32 cDestLength = 0;
  3065. JavascriptArray * pDestArray = NULL;
  3066. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault + (args.Info.Count * sizeof(TypeId*)));
  3067. TypeId* remoteTypeIds = (TypeId*)_alloca(args.Info.Count * sizeof(TypeId*));
  3068. bool isInt = true;
  3069. bool isFloat = true;
  3070. ::Math::RecordOverflowPolicy destLengthOverflow;
  3071. for (uint idxArg = 0; idxArg < args.Info.Count; idxArg++)
  3072. {
  3073. Var aItem = args[idxArg];
  3074. #if ENABLE_COPYONACCESS_ARRAY
  3075. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(aItem);
  3076. #endif
  3077. if (DynamicObject::IsAnyArray(aItem)) // Get JavascriptArray or ES5Array length
  3078. {
  3079. JavascriptArray * pItemArray = JavascriptArray::FromAnyArray(aItem);
  3080. if (isFloat)
  3081. {
  3082. if (!JavascriptNativeIntArray::Is(pItemArray))
  3083. {
  3084. isInt = false;
  3085. if (!JavascriptNativeFloatArray::Is(pItemArray))
  3086. {
  3087. isFloat = false;
  3088. }
  3089. }
  3090. }
  3091. cDestLength = UInt32Math::Add(cDestLength, pItemArray->GetLength(), destLengthOverflow);
  3092. }
  3093. else // Get remote array or object length
  3094. {
  3095. // We already checked for types derived from JavascriptArray. These are types that should behave like array
  3096. // i.e. proxy to array and remote array.
  3097. if (JavascriptOperators::IsArray(aItem))
  3098. {
  3099. // Don't try to preserve nativeness of remote arrays. The extra complexity is probably not
  3100. // worth it.
  3101. isInt = false;
  3102. isFloat = false;
  3103. if (!JavascriptProxy::Is(aItem))
  3104. {
  3105. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  3106. {
  3107. JS_REENTRANT(jsReentLock,
  3108. int64 len = JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(aItem, scriptContext), scriptContext));
  3109. // clipping to MaxArrayLength will overflow when added to cDestLength which we catch below
  3110. cDestLength = UInt32Math::Add(cDestLength, len < MaxArrayLength ? (uint32)len : MaxArrayLength, destLengthOverflow);
  3111. }
  3112. else
  3113. {
  3114. JS_REENTRANT(jsReentLock,
  3115. uint len = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(aItem, scriptContext), scriptContext));
  3116. cDestLength = UInt32Math::Add(cDestLength, len, destLengthOverflow);
  3117. }
  3118. }
  3119. remoteTypeIds[idxArg] = TypeIds_Array; // Mark remote array, no matter remote JavascriptArray or ES5Array.
  3120. }
  3121. else
  3122. {
  3123. if (isFloat)
  3124. {
  3125. if (BoxConcatItem(aItem, idxArg, scriptContext))
  3126. {
  3127. // A primitive will be boxed, so we have to create a var array for the result.
  3128. isInt = false;
  3129. isFloat = false;
  3130. }
  3131. else if (!TaggedInt::Is(aItem))
  3132. {
  3133. if (!JavascriptNumber::Is(aItem))
  3134. {
  3135. isInt = false;
  3136. isFloat = false;
  3137. }
  3138. else if (isInt)
  3139. {
  3140. int32 int32Value;
  3141. if(!JavascriptNumber::TryGetInt32Value(JavascriptNumber::GetValue(aItem), &int32Value) ||
  3142. SparseArraySegment<int32>::IsMissingItem(&int32Value))
  3143. {
  3144. isInt = false;
  3145. }
  3146. }
  3147. }
  3148. else if(isInt)
  3149. {
  3150. int32 int32Value = TaggedInt::ToInt32(aItem);
  3151. if(SparseArraySegment<int32>::IsMissingItem(&int32Value))
  3152. {
  3153. isInt = false;
  3154. }
  3155. }
  3156. }
  3157. remoteTypeIds[idxArg] = TypeIds_Limit;
  3158. cDestLength = UInt32Math::Add(cDestLength, 1, destLengthOverflow);
  3159. }
  3160. }
  3161. }
  3162. if (destLengthOverflow.HasOverflowed())
  3163. {
  3164. cDestLength = MaxArrayLength;
  3165. isInt = false;
  3166. isFloat = false;
  3167. }
  3168. //
  3169. // Create the destination array
  3170. //
  3171. RecyclableObject* pDestObj = nullptr;
  3172. bool isArray = false;
  3173. JS_REENTRANT_NO_MUTATE(jsReentLock, pDestObj = ArraySpeciesCreate(args[0], 0, scriptContext));
  3174. if (pDestObj)
  3175. {
  3176. #if ENABLE_COPYONACCESS_ARRAY
  3177. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pDestObj);
  3178. #endif
  3179. // Check the thing that species create made. If it's a native array that can't handle the source
  3180. // data, convert it. If it's a more conservative kind of array than the source data, indicate that
  3181. // so that the data will be converted on copy.
  3182. if (isInt)
  3183. {
  3184. if (JavascriptNativeIntArray::Is(pDestObj))
  3185. {
  3186. isArray = true;
  3187. }
  3188. else
  3189. {
  3190. isInt = false;
  3191. isFloat = JavascriptNativeFloatArray::Is(pDestObj);
  3192. isArray = JavascriptArray::Is(pDestObj);
  3193. }
  3194. }
  3195. else if (isFloat)
  3196. {
  3197. JavascriptNativeIntArray *nativeIntArray = JavascriptOperators::TryFromVar<JavascriptNativeIntArray>(pDestObj);
  3198. if (nativeIntArray)
  3199. {
  3200. JavascriptNativeIntArray::ToNativeFloatArray(nativeIntArray);
  3201. isArray = true;
  3202. }
  3203. else
  3204. {
  3205. isFloat = JavascriptNativeFloatArray::Is(pDestObj);
  3206. isArray = JavascriptArray::Is(pDestObj);
  3207. }
  3208. }
  3209. else
  3210. {
  3211. JavascriptNativeIntArray *nativeIntArray = JavascriptOperators::TryFromVar<Js::JavascriptNativeIntArray>(pDestObj);
  3212. if (nativeIntArray)
  3213. {
  3214. JavascriptNativeIntArray::ToVarArray(nativeIntArray);
  3215. isArray = true;
  3216. }
  3217. else
  3218. {
  3219. JavascriptNativeFloatArray *nativeFloatArray = JavascriptOperators::TryFromVar<Js::JavascriptNativeFloatArray>(pDestObj);
  3220. if (nativeFloatArray)
  3221. {
  3222. JavascriptNativeFloatArray::ToVarArray(nativeFloatArray);
  3223. isArray = true;
  3224. }
  3225. else
  3226. {
  3227. isArray = JavascriptArray::Is(pDestObj);
  3228. }
  3229. }
  3230. }
  3231. }
  3232. if (pDestObj == nullptr || isArray)
  3233. {
  3234. if (isInt)
  3235. {
  3236. JavascriptNativeIntArray *pIntArray = isArray ? JavascriptNativeIntArray::FromVar(pDestObj) : scriptContext->GetLibrary()->CreateNativeIntArray(cDestLength);
  3237. pIntArray->EnsureHead<int32>();
  3238. JS_REENTRANT(jsReentLock, pDestArray = ConcatIntArgs(pIntArray, remoteTypeIds, args, scriptContext));
  3239. }
  3240. else if (isFloat)
  3241. {
  3242. JavascriptNativeFloatArray *pFArray = isArray ? JavascriptNativeFloatArray::FromVar(pDestObj) : scriptContext->GetLibrary()->CreateNativeFloatArray(cDestLength);
  3243. pFArray->EnsureHead<double>();
  3244. JS_REENTRANT(jsReentLock, pDestArray = ConcatFloatArgs(pFArray, remoteTypeIds, args, scriptContext));
  3245. }
  3246. else
  3247. {
  3248. pDestArray = isArray ? JavascriptArray::FromVar(pDestObj) : scriptContext->GetLibrary()->CreateArray(cDestLength);
  3249. // if the constructor has changed then we no longer specialize for ints and floats
  3250. pDestArray->EnsureHead<Var>();
  3251. JS_REENTRANT(jsReentLock, ConcatArgsCallingHelper(pDestArray, remoteTypeIds, args, scriptContext, destLengthOverflow));
  3252. }
  3253. //
  3254. // Return the new array instance.
  3255. //
  3256. #ifdef VALIDATE_ARRAY
  3257. pDestArray->ValidateArray();
  3258. #endif
  3259. return pDestArray;
  3260. }
  3261. Assert(pDestObj);
  3262. JS_REENTRANT(jsReentLock, ConcatArgsCallingHelper(pDestObj, remoteTypeIds, args, scriptContext, destLengthOverflow));
  3263. return pDestObj;
  3264. }
  3265. void JavascriptArray::ConcatArgsCallingHelper(RecyclableObject* pDestObj, TypeId* remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext, ::Math::RecordOverflowPolicy &destLengthOverflow)
  3266. {
  3267. if (destLengthOverflow.HasOverflowed())
  3268. {
  3269. ConcatArgs<BigIndex>(pDestObj, remoteTypeIds, args, scriptContext);
  3270. }
  3271. else
  3272. {
  3273. // Use faster uint32 version if no overflow
  3274. ConcatArgs<uint32>(pDestObj, remoteTypeIds, args, scriptContext);
  3275. }
  3276. }
  3277. template<typename T>
  3278. /* static */ void JavascriptArray::SetConcatItem(Var aItem, uint idxArg, JavascriptArray* pDestArray, RecyclableObject* pDestObj, T idxDest, ScriptContext *scriptContext)
  3279. {
  3280. if (BoxConcatItem(aItem, idxArg, scriptContext))
  3281. {
  3282. // bug# 725784: ES5: not calling ToObject in Step 1 of 15.4.4.4
  3283. RecyclableObject* pObj = nullptr;
  3284. if (FALSE == JavascriptConversion::ToObject(aItem, scriptContext, &pObj))
  3285. {
  3286. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.concat"));
  3287. }
  3288. if (pDestArray)
  3289. {
  3290. pDestArray->GenericDirectSetItemAt(idxDest, pObj);
  3291. }
  3292. else
  3293. {
  3294. SetArrayLikeObjects(pDestObj, idxDest, pObj);
  3295. }
  3296. }
  3297. else
  3298. {
  3299. if (pDestArray)
  3300. {
  3301. pDestArray->GenericDirectSetItemAt(idxDest, aItem);
  3302. }
  3303. else
  3304. {
  3305. SetArrayLikeObjects(pDestObj, idxDest, aItem);
  3306. }
  3307. }
  3308. }
  3309. int64 JavascriptArray::GetFromLastIndex(Var arg, int64 length, ScriptContext *scriptContext)
  3310. {
  3311. int64 fromIndex;
  3312. if (TaggedInt::Is(arg))
  3313. {
  3314. int intValue = TaggedInt::ToInt32(arg);
  3315. if (intValue >= 0)
  3316. {
  3317. fromIndex = min<int64>(intValue, length - 1);
  3318. }
  3319. else if ((uint32)-intValue > length)
  3320. {
  3321. return length;
  3322. }
  3323. else
  3324. {
  3325. fromIndex = intValue + length;
  3326. }
  3327. }
  3328. else
  3329. {
  3330. double value = JavascriptConversion::ToInteger(arg, scriptContext);
  3331. if (value >= 0)
  3332. {
  3333. fromIndex = (int64)min(value, (double)(length - 1));
  3334. }
  3335. else if (value + length < 0)
  3336. {
  3337. return length;
  3338. }
  3339. else
  3340. {
  3341. fromIndex = (int64)(value + length);
  3342. }
  3343. }
  3344. return fromIndex;
  3345. }
  3346. // includesAlgorithm specifies to follow ES7 Array.prototype.includes semantics instead of Array.prototype.indexOf
  3347. // Differences
  3348. // 1. Returns boolean true or false value instead of the search hit index
  3349. // 2. Follows SameValueZero algorithm instead of StrictEquals
  3350. // 3. Missing values are scanned if the search value is undefined
  3351. template <bool includesAlgorithm>
  3352. Var JavascriptArray::IndexOfHelper(Arguments const & args, ScriptContext *scriptContext)
  3353. {
  3354. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3355. SETOBJECT_FOR_MUTATION(jsReentLock, args[0]);
  3356. RecyclableObject* obj = nullptr;
  3357. JavascriptArray* pArr = nullptr;
  3358. BigIndex length;
  3359. Var trueValue = scriptContext->GetLibrary()->GetTrue();
  3360. Var falseValue = scriptContext->GetLibrary()->GetFalse();
  3361. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.indexOf"), &pArr, &obj, &length));
  3362. Var search;
  3363. uint32 fromIndex = 0;
  3364. uint64 fromIndex64 = 0;
  3365. // The evaluation of method arguments may change the type of the array. Hence, we do that prior to the actual helper method calls.
  3366. // The if clause of the conditional statement below applies to an JavascriptArray or TypedArray instances. The rest of the conditional
  3367. // clauses apply to an ES5Array or other valid Javascript objects.
  3368. if ((pArr || TypedArrayBase::Is(obj)) && (length.IsSmallIndex() || length.IsUint32Max()))
  3369. {
  3370. uint32 len = length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex();
  3371. JS_REENTRANT(jsReentLock, BOOL gotParam = GetParamForIndexOf(len, args, search, fromIndex, scriptContext));
  3372. if (!gotParam)
  3373. {
  3374. return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
  3375. }
  3376. }
  3377. else if (length.IsSmallIndex())
  3378. {
  3379. JS_REENTRANT(jsReentLock, BOOL gotParam = GetParamForIndexOf(length.GetSmallIndex(), args, search, fromIndex, scriptContext));
  3380. if (!gotParam)
  3381. {
  3382. return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
  3383. }
  3384. }
  3385. else
  3386. {
  3387. JS_REENTRANT(jsReentLock, BOOL gotParam = GetParamForIndexOf(length.GetBigIndex(), args, search, fromIndex64, scriptContext));
  3388. if (!gotParam)
  3389. {
  3390. return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
  3391. }
  3392. }
  3393. // Side effects (such as defining a property in a ToPrimitive call) during evaluation of fromIndex argument may convert the array to an ES5 array.
  3394. if (pArr && !JavascriptArray::Is(obj))
  3395. {
  3396. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  3397. pArr = nullptr;
  3398. }
  3399. if (pArr)
  3400. {
  3401. if (length.IsSmallIndex() || length.IsUint32Max())
  3402. {
  3403. uint32 len = length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex();
  3404. JS_REENTRANT(jsReentLock, int32 index = pArr->HeadSegmentIndexOfHelper(search, fromIndex, len, includesAlgorithm, scriptContext));
  3405. // If we found the search value in the head segment, or if we determined there is no need to search other segments,
  3406. // we stop right here.
  3407. if (index != -1 || fromIndex == -1)
  3408. {
  3409. if (includesAlgorithm)
  3410. {
  3411. //Array.prototype.includes
  3412. return (index == -1) ? falseValue : trueValue;
  3413. }
  3414. else
  3415. {
  3416. //Array.prototype.indexOf
  3417. return JavascriptNumber::ToVar(index, scriptContext);
  3418. }
  3419. }
  3420. // If we really must search other segments, let's do it now. We'll have to search the slow way (dealing with holes, etc.).
  3421. switch (pArr->GetTypeId())
  3422. {
  3423. case Js::TypeIds_Array:
  3424. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(pArr, search, fromIndex, len, scriptContext));
  3425. case Js::TypeIds_NativeIntArray:
  3426. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(JavascriptNativeIntArray::UnsafeFromVar(pArr), search, fromIndex, len, scriptContext));
  3427. case Js::TypeIds_NativeFloatArray:
  3428. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(JavascriptNativeFloatArray::UnsafeFromVar(pArr), search, fromIndex, len, scriptContext));
  3429. default:
  3430. AssertMsg(FALSE, "invalid array typeid");
  3431. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(pArr, search, fromIndex, len, scriptContext));
  3432. }
  3433. }
  3434. }
  3435. // source object is not a JavascriptArray but source could be a TypedArray
  3436. TypedArrayBase * typedArrayObj = JavascriptOperators::TryFromVar<Js::TypedArrayBase>(obj);
  3437. if (typedArrayObj)
  3438. {
  3439. if (length.IsSmallIndex() || length.IsUint32Max())
  3440. {
  3441. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(typedArrayObj, search, fromIndex, length.GetSmallIndex(), scriptContext));
  3442. }
  3443. }
  3444. if (length.IsSmallIndex())
  3445. {
  3446. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(obj, search, fromIndex, length.GetSmallIndex(), scriptContext));
  3447. }
  3448. else
  3449. {
  3450. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(obj, search, fromIndex64, length.GetBigIndex(), scriptContext));
  3451. }
  3452. }
  3453. // Array.prototype.indexOf as defined in ES6.0 (final) Section 22.1.3.11
  3454. Var JavascriptArray::EntryIndexOf(RecyclableObject* function, CallInfo callInfo, ...)
  3455. {
  3456. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  3457. ARGUMENTS(args, callInfo);
  3458. ScriptContext* scriptContext = function->GetScriptContext();
  3459. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3460. Assert(!(callInfo.Flags & CallFlags_New));
  3461. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_indexOf);
  3462. JS_REENTRANT_UNLOCK(jsReentLock, Var returnValue = IndexOfHelper<false>(args, scriptContext));
  3463. //IndexOfHelper code is reused for array.prototype.includes as well. Let us assert here we didn't get a true or false instead of index
  3464. Assert(returnValue != scriptContext->GetLibrary()->GetTrue() && returnValue != scriptContext->GetLibrary()->GetFalse());
  3465. return returnValue;
  3466. }
  3467. Var JavascriptArray::EntryIncludes(RecyclableObject* function, CallInfo callInfo, ...)
  3468. {
  3469. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  3470. ARGUMENTS(args, callInfo);
  3471. ScriptContext* scriptContext = function->GetScriptContext();
  3472. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3473. Assert(!(callInfo.Flags & CallFlags_New));
  3474. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_includes);
  3475. JS_REENTRANT(jsReentLock, Var returnValue = IndexOfHelper<true>(args, scriptContext));
  3476. Assert(returnValue == scriptContext->GetLibrary()->GetTrue() || returnValue == scriptContext->GetLibrary()->GetFalse());
  3477. return returnValue;
  3478. }
  3479. template<typename T>
  3480. BOOL JavascriptArray::GetParamForIndexOf(T length, Arguments const& args, Var& search, T& fromIndex, ScriptContext * scriptContext)
  3481. {
  3482. if (length == 0)
  3483. {
  3484. return false;
  3485. }
  3486. if (args.Info.Count > 2)
  3487. {
  3488. fromIndex = GetFromIndex(args[2], length, scriptContext);
  3489. if (fromIndex >= length)
  3490. {
  3491. return false;
  3492. }
  3493. search = args[1];
  3494. }
  3495. else
  3496. {
  3497. fromIndex = 0;
  3498. search = args.Info.Count > 1 ? args[1] : scriptContext->GetLibrary()->GetUndefined();
  3499. }
  3500. return true;
  3501. }
  3502. template <>
  3503. BOOL JavascriptArray::TemplatedGetItem(RecyclableObject * obj, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3504. {
  3505. // Note: Sometime cross site array go down this path to get the marshalling
  3506. Assert(!VirtualTableInfo<JavascriptArray>::HasVirtualTable(obj)
  3507. && !VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(obj)
  3508. && !VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(obj));
  3509. if (checkHasItem && !JavascriptOperators::HasItem(obj, index))
  3510. {
  3511. return FALSE;
  3512. }
  3513. return JavascriptOperators::GetItem(obj, index, element, scriptContext);
  3514. }
  3515. template <>
  3516. BOOL JavascriptArray::TemplatedGetItem(RecyclableObject * obj, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3517. {
  3518. // Note: Sometime cross site array go down this path to get the marshalling
  3519. Assert(!VirtualTableInfo<JavascriptArray>::HasVirtualTable(obj)
  3520. && !VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(obj)
  3521. && !VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(obj));
  3522. PropertyRecord const * propertyRecord;
  3523. JavascriptOperators::GetPropertyIdForInt(index, scriptContext, &propertyRecord);
  3524. if (checkHasItem && !JavascriptOperators::HasProperty(obj, propertyRecord->GetPropertyId()))
  3525. {
  3526. return FALSE;
  3527. }
  3528. *element = JavascriptOperators::GetProperty(obj, propertyRecord->GetPropertyId(), scriptContext);
  3529. return *element != scriptContext->GetLibrary()->GetUndefined();
  3530. }
  3531. template <>
  3532. BOOL JavascriptArray::TemplatedGetItem(JavascriptArray *pArr, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3533. {
  3534. Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(pArr)
  3535. || VirtualTableInfo<CrossSiteObject<JavascriptArray>>::HasVirtualTable(pArr));
  3536. return pArr->JavascriptArray::DirectGetItemAtFull(index, element);
  3537. }
  3538. template <>
  3539. BOOL JavascriptArray::TemplatedGetItem(JavascriptArray *pArr, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3540. {
  3541. // This should never get called.
  3542. Assert(false);
  3543. Throw::InternalError();
  3544. }
  3545. template <>
  3546. BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeIntArray *pArr, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3547. {
  3548. Assert(VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(pArr)
  3549. || VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::HasVirtualTable(pArr));
  3550. return pArr->JavascriptNativeIntArray::DirectGetItemAtFull(index, element);
  3551. }
  3552. template <>
  3553. BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeIntArray *pArr, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3554. {
  3555. // This should never get called.
  3556. Assert(false);
  3557. Throw::InternalError();
  3558. }
  3559. template <>
  3560. BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeFloatArray *pArr, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3561. {
  3562. Assert(VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(pArr)
  3563. || VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::HasVirtualTable(pArr));
  3564. return pArr->JavascriptNativeFloatArray::DirectGetItemAtFull(index, element);
  3565. }
  3566. template <>
  3567. BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeFloatArray *pArr, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3568. {
  3569. // This should never get called.
  3570. Assert(false);
  3571. Throw::InternalError();
  3572. }
  3573. template <>
  3574. BOOL JavascriptArray::TemplatedGetItem(TypedArrayBase * typedArrayBase, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3575. {
  3576. // We need to do explicit check for items since length value may not actually match the actual TypedArray length.
  3577. // User could add a length property to a TypedArray instance which lies and returns a different value from the underlying length.
  3578. // Since this method can be called via Array.prototype.indexOf with .apply or .call passing a TypedArray as this parameter
  3579. // we don't know whether or not length == typedArrayBase->GetLength().
  3580. if (checkHasItem && !typedArrayBase->HasItem(index))
  3581. {
  3582. return false;
  3583. }
  3584. *element = typedArrayBase->DirectGetItem(index);
  3585. return true;
  3586. }
  3587. template <>
  3588. BOOL JavascriptArray::TemplatedGetItem(TypedArrayBase * typedArrayBase, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3589. {
  3590. // This should never get called.
  3591. Assert(false);
  3592. Throw::InternalError();
  3593. }
  3594. template <bool includesAlgorithm, typename T, typename P>
  3595. Var JavascriptArray::TemplatedIndexOfHelper(T * pArr, Var search, P fromIndex, P toIndex, ScriptContext * scriptContext)
  3596. {
  3597. Var element = nullptr;
  3598. bool isSearchTaggedInt = TaggedInt::Is(search);
  3599. bool doUndefinedSearch = includesAlgorithm && JavascriptOperators::GetTypeId(search) == TypeIds_Undefined;
  3600. Var trueValue = scriptContext->GetLibrary()->GetTrue();
  3601. Var falseValue = scriptContext->GetLibrary()->GetFalse();
  3602. //Consider: enumerating instead of walking all indices
  3603. for (P i = fromIndex; i < toIndex; i++)
  3604. {
  3605. if (!TryTemplatedGetItem(pArr, i, &element, scriptContext, !includesAlgorithm))
  3606. {
  3607. if (doUndefinedSearch)
  3608. {
  3609. return trueValue;
  3610. }
  3611. continue;
  3612. }
  3613. if (isSearchTaggedInt && TaggedInt::Is(element))
  3614. {
  3615. if (element == search)
  3616. {
  3617. return includesAlgorithm? trueValue : JavascriptNumber::ToVar(i, scriptContext);
  3618. }
  3619. continue;
  3620. }
  3621. if (includesAlgorithm)
  3622. {
  3623. //Array.prototype.includes
  3624. if (JavascriptConversion::SameValueZero(element, search))
  3625. {
  3626. return trueValue;
  3627. }
  3628. }
  3629. else
  3630. {
  3631. //Array.prototype.indexOf
  3632. if (JavascriptOperators::StrictEqual(element, search, scriptContext))
  3633. {
  3634. return JavascriptNumber::ToVar(i, scriptContext);
  3635. }
  3636. }
  3637. }
  3638. return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
  3639. }
  3640. int32 JavascriptArray::HeadSegmentIndexOfHelper(Var search, uint32 &fromIndex, uint32 toIndex, bool includesAlgorithm, ScriptContext * scriptContext)
  3641. {
  3642. Assert(Is(GetTypeId()) && !JavascriptNativeArray::Is(GetTypeId()));
  3643. if (!HasNoMissingValues() || fromIndex >= GetHead()->length)
  3644. {
  3645. return -1;
  3646. }
  3647. bool isSearchTaggedInt = TaggedInt::Is(search);
  3648. // We need to cast head segment to SparseArraySegment<Var> to have access to GetElement (onSparseArraySegment<T>). Because there are separate overloads of this
  3649. // virtual method on JavascriptNativeIntArray and JavascriptNativeFloatArray, we know this version of this method will only be called for true JavascriptArray, and not for
  3650. // either of the derived native arrays, so the elements of each segment used here must be Vars. Hence, the cast is safe.
  3651. SparseArraySegment<Var>* head = static_cast<SparseArraySegment<Var>*>(GetHead());
  3652. uint32 toIndexTrimmed = toIndex <= head->length ? toIndex : head->length;
  3653. for (uint32 i = fromIndex; i < toIndexTrimmed; i++)
  3654. {
  3655. Var element = head->GetElement(i);
  3656. if (isSearchTaggedInt && TaggedInt::Is(element))
  3657. {
  3658. if (search == element)
  3659. {
  3660. return i;
  3661. }
  3662. }
  3663. else if (includesAlgorithm && JavascriptConversion::SameValueZero(element, search))
  3664. {
  3665. //Array.prototype.includes
  3666. return i;
  3667. }
  3668. else if (JavascriptOperators::StrictEqual(element, search, scriptContext))
  3669. {
  3670. //Array.prototype.indexOf
  3671. return i;
  3672. }
  3673. }
  3674. // Element not found in the head segment. Keep looking only if the range of indices extends past
  3675. // the head segment.
  3676. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3677. return -1;
  3678. }
  3679. template<typename T>
  3680. bool AreAllBytesEqual(T value)
  3681. {
  3682. byte* bValue = (byte*)&value;
  3683. byte firstByte = *bValue++;
  3684. for (int i = 1; i < sizeof(T); ++i)
  3685. {
  3686. if (*bValue++ != firstByte)
  3687. {
  3688. return false;
  3689. }
  3690. }
  3691. return true;
  3692. }
  3693. template<>
  3694. void JavascriptArray::CopyValueToSegmentBuferNoCheck(Field(double)* buffer, uint32 length, double value)
  3695. {
  3696. if (JavascriptNumber::IsZero(value) && !JavascriptNumber::IsNegZero(value))
  3697. {
  3698. memset(buffer, 0, sizeof(double) * length);
  3699. }
  3700. else
  3701. {
  3702. for (uint32 i = 0; i < length; i++)
  3703. {
  3704. buffer[i] = value;
  3705. }
  3706. }
  3707. }
  3708. template<>
  3709. void JavascriptArray::CopyValueToSegmentBuferNoCheck(Field(int32)* buffer, uint32 length, int32 value)
  3710. {
  3711. if (value == 0 || AreAllBytesEqual(value))
  3712. {
  3713. memset(buffer, *(byte*)&value, sizeof(int32)* length);
  3714. }
  3715. else
  3716. {
  3717. for (uint32 i = 0; i < length; i++)
  3718. {
  3719. buffer[i] = value;
  3720. }
  3721. }
  3722. }
  3723. template<>
  3724. void JavascriptArray::CopyValueToSegmentBuferNoCheck(Field(Js::Var)* buffer, uint32 length, Js::Var value)
  3725. {
  3726. for (uint32 i = 0; i < length; i++)
  3727. {
  3728. buffer[i] = value;
  3729. }
  3730. }
  3731. int32 JavascriptNativeIntArray::HeadSegmentIndexOfHelper(Var search, uint32 &fromIndex, uint32 toIndex, bool includesAlgorithm, ScriptContext * scriptContext)
  3732. {
  3733. // We proceed largely in the same manner as in JavascriptArray's version of this method (see comments there for more information),
  3734. // except when we can further optimize thanks to the knowledge that all elements in the array are int32's. This allows for two additional optimizations:
  3735. // 1. Only tagged ints or JavascriptNumbers that can be represented as int32 can be strict equal to some element in the array (all int32). Thus, if
  3736. // the search value is some other kind of Var, we can return -1 without ever iterating over the elements.
  3737. // 2. If the search value is a number that can be represented as int32, then we inspect the elements, but we don't need to perform the full strict equality algorithm.
  3738. // Instead we can use simple C++ equality (which in case of such values is equivalent to strict equality in JavaScript).
  3739. if (!HasNoMissingValues() || fromIndex >= GetHead()->length)
  3740. {
  3741. return -1;
  3742. }
  3743. bool isSearchTaggedInt = TaggedInt::Is(search);
  3744. if (!isSearchTaggedInt && !JavascriptNumber::Is_NoTaggedIntCheck(search))
  3745. {
  3746. // The value can't be in the array, but it could be in a prototype, and we can only guarantee that
  3747. // the head segment has no gaps.
  3748. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3749. return -1;
  3750. }
  3751. int32 searchAsInt32;
  3752. if (isSearchTaggedInt)
  3753. {
  3754. searchAsInt32 = TaggedInt::ToInt32(search);
  3755. }
  3756. else if (!JavascriptNumber::TryGetInt32Value<true>(JavascriptNumber::GetValue(search), &searchAsInt32))
  3757. {
  3758. // The value can't be in the array, but it could be in a prototype, and we can only guarantee that
  3759. // the head segment has no gaps.
  3760. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3761. return -1;
  3762. }
  3763. // We need to cast head segment to SparseArraySegment<int32> to have access to GetElement (onSparseArraySegment<T>). Because there are separate overloads of this
  3764. // virtual method on JavascriptNativeIntArray and JavascriptNativeFloatArray, we know this version of this method will only be called for true JavascriptNativeIntArray, and not for
  3765. // the other two, so the elements of each segment used here must be int32's. Hence, the cast is safe.
  3766. SparseArraySegment<int32> * head = static_cast<SparseArraySegment<int32>*>(GetHead());
  3767. uint32 toIndexTrimmed = toIndex <= head->length ? toIndex : head->length;
  3768. for (uint32 i = fromIndex; i < toIndexTrimmed; i++)
  3769. {
  3770. int32 element = head->GetElement(i);
  3771. if (searchAsInt32 == element)
  3772. {
  3773. return i;
  3774. }
  3775. }
  3776. // Element not found in the head segment. Keep looking only if the range of indices extends past
  3777. // the head segment.
  3778. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3779. return -1;
  3780. }
  3781. int32 JavascriptNativeFloatArray::HeadSegmentIndexOfHelper(Var search, uint32 &fromIndex, uint32 toIndex, bool includesAlgorithm, ScriptContext * scriptContext)
  3782. {
  3783. // We proceed largely in the same manner as in JavascriptArray's version of this method (see comments there for more information),
  3784. // except when we can further optimize thanks to the knowledge that all elements in the array are doubles. This allows for two additional optimizations:
  3785. // 1. Only tagged ints or JavascriptNumbers can be strict equal to some element in the array (all doubles). Thus, if
  3786. // the search value is some other kind of Var, we can return -1 without ever iterating over the elements.
  3787. // 2. If the search value is a number, then we inspect the elements, but we don't need to perform the full strict equality algorithm.
  3788. // Instead we can use simple C++ equality (which in case of such values is equivalent to strict equality in JavaScript).
  3789. if (!HasNoMissingValues() || fromIndex >= GetHead()->length)
  3790. {
  3791. return -1;
  3792. }
  3793. bool isSearchTaggedInt = TaggedInt::Is(search);
  3794. if (!isSearchTaggedInt && !JavascriptNumber::Is_NoTaggedIntCheck(search))
  3795. {
  3796. // The value can't be in the array, but it could be in a prototype, and we can only guarantee that
  3797. // the head segment has no gaps.
  3798. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3799. return -1;
  3800. }
  3801. double searchAsDouble = isSearchTaggedInt ? TaggedInt::ToDouble(search) : JavascriptNumber::GetValue(search);
  3802. // We need to cast head segment to SparseArraySegment<double> to have access to GetElement (SparseArraySegment). We know the
  3803. // segment's elements are all Vars so the cast is safe. It would have been more convenient here if JavascriptArray
  3804. // used SparseArraySegment<Var>, instead of SparseArraySegmentBase.
  3805. SparseArraySegment<double> * head = static_cast<SparseArraySegment<double>*>(GetHead());
  3806. uint32 toIndexTrimmed = toIndex <= head->length ? toIndex : head->length;
  3807. bool matchNaN = includesAlgorithm && JavascriptNumber::IsNan(searchAsDouble);
  3808. for (uint32 i = fromIndex; i < toIndexTrimmed; i++)
  3809. {
  3810. double element = head->GetElement(i);
  3811. if (element == searchAsDouble)
  3812. {
  3813. return i;
  3814. }
  3815. //NaN != NaN we expect to match for NaN in Array.prototype.includes algorithm
  3816. if (matchNaN && JavascriptNumber::IsNan(element))
  3817. {
  3818. return i;
  3819. }
  3820. }
  3821. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3822. return -1;
  3823. }
  3824. Var JavascriptArray::EntryJoin(RecyclableObject* function, CallInfo callInfo, ...)
  3825. {
  3826. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  3827. ARGUMENTS(args, callInfo);
  3828. ScriptContext* scriptContext = function->GetScriptContext();
  3829. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3830. Assert(!(callInfo.Flags & CallFlags_New));
  3831. if (args.Info.Count == 0)
  3832. {
  3833. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.join"));
  3834. }
  3835. SETOBJECT_FOR_MUTATION(jsReentLock, args[0]);
  3836. JavascriptString* separator;
  3837. if (args.Info.Count >= 2)
  3838. {
  3839. TypeId typeId = JavascriptOperators::GetTypeId(args[1]);
  3840. //ES5 15.4.4.5 If separator is undefined, let separator be the single-character String ",".
  3841. if (TypeIds_Undefined != typeId)
  3842. {
  3843. JS_REENTRANT(jsReentLock, separator = JavascriptConversion::ToString(args[1], scriptContext));
  3844. }
  3845. else
  3846. {
  3847. separator = scriptContext->GetLibrary()->GetCommaDisplayString();
  3848. }
  3849. }
  3850. else
  3851. {
  3852. separator = scriptContext->GetLibrary()->GetCommaDisplayString();
  3853. }
  3854. JS_REENTRANT_UNLOCK(jsReentLock, return JoinHelper(args[0], separator, scriptContext));
  3855. }
  3856. JavascriptString* JavascriptArray::JoinToString(Var value, ScriptContext* scriptContext)
  3857. {
  3858. TypeId typeId = JavascriptOperators::GetTypeId(value);
  3859. if (typeId <= TypeIds_UndefinedOrNull)
  3860. {
  3861. return scriptContext->GetLibrary()->GetEmptyString();
  3862. }
  3863. else
  3864. {
  3865. return JavascriptConversion::ToString(value, scriptContext);
  3866. }
  3867. }
  3868. JavascriptString* JavascriptArray::JoinHelper(Var thisArg, JavascriptString* separator, ScriptContext* scriptContext)
  3869. {
  3870. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3871. SETOBJECT_FOR_MUTATION(jsReentLock, thisArg);
  3872. JavascriptArray * arr = JavascriptOperators::TryFromVar<JavascriptArray>(thisArg);
  3873. JavascriptProxy * proxy = JavascriptOperators::TryFromVar<JavascriptProxy>(thisArg);
  3874. bool isArray = arr && (scriptContext == arr->GetScriptContext());
  3875. bool isProxy = proxy && (scriptContext == proxy->GetScriptContext());
  3876. Var target = NULL;
  3877. bool isTargetObjectPushed = false;
  3878. // if we are visiting a proxy object, track that we have visited the target object as well so the next time w
  3879. // call the join helper for the target of this proxy, we will return above.
  3880. if (isProxy)
  3881. {
  3882. Assert(proxy);
  3883. target = proxy->GetTarget();
  3884. if (target != nullptr)
  3885. {
  3886. // If we end up joining same array, instead of going in infinite loop, return the empty string
  3887. if (scriptContext->CheckObject(target))
  3888. {
  3889. return scriptContext->GetLibrary()->GetEmptyString();
  3890. }
  3891. else
  3892. {
  3893. scriptContext->PushObject(target);
  3894. isTargetObjectPushed = true;
  3895. }
  3896. }
  3897. }
  3898. // If we end up joining same array, instead of going in infinite loop, return the empty string
  3899. else if (scriptContext->CheckObject(thisArg))
  3900. {
  3901. return scriptContext->GetLibrary()->GetEmptyString();
  3902. }
  3903. if (!isTargetObjectPushed)
  3904. {
  3905. scriptContext->PushObject(thisArg);
  3906. }
  3907. JavascriptString* res = nullptr;
  3908. TryFinally([&]()
  3909. {
  3910. if (isArray)
  3911. {
  3912. #if ENABLE_COPYONACCESS_ARRAY
  3913. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray(thisArg);
  3914. #endif
  3915. switch (arr->GetTypeId())
  3916. {
  3917. case Js::TypeIds_Array:
  3918. JS_REENTRANT(jsReentLock, res = JoinArrayHelper(arr, separator, scriptContext));
  3919. break;
  3920. case Js::TypeIds_NativeIntArray:
  3921. JS_REENTRANT(jsReentLock, res = JoinArrayHelper(JavascriptNativeIntArray::UnsafeFromVar(arr), separator, scriptContext));
  3922. break;
  3923. case Js::TypeIds_NativeFloatArray:
  3924. JS_REENTRANT(jsReentLock, res = JoinArrayHelper(JavascriptNativeFloatArray::UnsafeFromVar(arr), separator, scriptContext));
  3925. break;
  3926. }
  3927. }
  3928. else if (RecyclableObject::Is(thisArg))
  3929. {
  3930. JS_REENTRANT(jsReentLock, res = JoinOtherHelper(RecyclableObject::FromVar(thisArg), separator, scriptContext));
  3931. }
  3932. else
  3933. {
  3934. JS_REENTRANT(jsReentLock, res = JoinOtherHelper(scriptContext->GetLibrary()->CreateNumberObject(thisArg), separator, scriptContext));
  3935. }
  3936. },
  3937. [&](bool/*hasException*/)
  3938. {
  3939. Var top = scriptContext->PopObject();
  3940. if (isProxy)
  3941. {
  3942. AssertMsg(top == target, "Unmatched operation stack");
  3943. }
  3944. else
  3945. {
  3946. AssertMsg(top == thisArg, "Unmatched operation stack");
  3947. }
  3948. });
  3949. if (res == nullptr)
  3950. {
  3951. res = scriptContext->GetLibrary()->GetEmptyString();
  3952. }
  3953. return res;
  3954. }
  3955. static const charcount_t Join_MaxEstimatedAppendCount = static_cast<charcount_t>((64 << 20) / sizeof(void *)); // 64 MB worth of pointers
  3956. template <typename T>
  3957. JavascriptString* JavascriptArray::JoinArrayHelper(T * arr, JavascriptString* separator, ScriptContext* scriptContext)
  3958. {
  3959. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3960. SETOBJECT_FOR_MUTATION(jsReentLock, arr);
  3961. Assert(VirtualTableInfo<T>::HasVirtualTable(arr) || VirtualTableInfo<CrossSiteObject<T>>::HasVirtualTable(arr));
  3962. const uint32 arrLength = arr->length;
  3963. switch(arrLength)
  3964. {
  3965. default:
  3966. {
  3967. CaseDefault:
  3968. bool hasSeparator = (separator->GetLength() != 0);
  3969. const charcount_t estimatedAppendCount =
  3970. min(
  3971. Join_MaxEstimatedAppendCount,
  3972. static_cast<charcount_t>(arrLength + (hasSeparator ? arrLength - 1 : 0)));
  3973. CompoundString *const cs =
  3974. CompoundString::NewWithPointerCapacity(estimatedAppendCount, scriptContext->GetLibrary());
  3975. Var item;
  3976. BOOL gotItem;
  3977. JS_REENTRANT(jsReentLock, gotItem = TemplatedGetItem(arr, 0u, &item, scriptContext));
  3978. if (gotItem)
  3979. {
  3980. JS_REENTRANT(jsReentLock, cs->Append(JavascriptArray::JoinToString(item, scriptContext)));
  3981. }
  3982. for (uint32 i = 1; i < arrLength; i++)
  3983. {
  3984. if (hasSeparator)
  3985. {
  3986. cs->Append(separator);
  3987. }
  3988. JS_REENTRANT(jsReentLock, gotItem = TryTemplatedGetItem(arr, i, &item, scriptContext));
  3989. if (gotItem)
  3990. {
  3991. JS_REENTRANT(jsReentLock, cs->Append(JavascriptArray::JoinToString(item, scriptContext)));
  3992. }
  3993. }
  3994. return cs;
  3995. }
  3996. case 2:
  3997. {
  3998. bool hasSeparator = (separator->GetLength() != 0);
  3999. BOOL gotItem;
  4000. if(hasSeparator)
  4001. {
  4002. goto CaseDefault;
  4003. }
  4004. JavascriptString *res = nullptr;
  4005. Var item;
  4006. JS_REENTRANT(jsReentLock, gotItem = TemplatedGetItem(arr, 0u, &item, scriptContext));
  4007. if (gotItem)
  4008. {
  4009. JS_REENTRANT(jsReentLock, res = JavascriptArray::JoinToString(item, scriptContext));
  4010. }
  4011. JS_REENTRANT(jsReentLock, gotItem = TryTemplatedGetItem(arr, 1u, &item, scriptContext));
  4012. if (gotItem)
  4013. {
  4014. JS_REENTRANT(jsReentLock, JavascriptString *const itemString = JavascriptArray::JoinToString(item, scriptContext));
  4015. return res ? ConcatString::New(res, itemString) : itemString;
  4016. }
  4017. if(res)
  4018. {
  4019. return res;
  4020. }
  4021. goto Case0;
  4022. }
  4023. case 1:
  4024. {
  4025. Var item;
  4026. BOOL gotItem;
  4027. JS_REENTRANT(jsReentLock, gotItem = TemplatedGetItem(arr, 0u, &item, scriptContext));
  4028. if (gotItem)
  4029. {
  4030. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::JoinToString(item, scriptContext));
  4031. }
  4032. // fall through
  4033. }
  4034. case 0:
  4035. Case0:
  4036. return scriptContext->GetLibrary()->GetEmptyString();
  4037. }
  4038. }
  4039. JavascriptString* JavascriptArray::JoinOtherHelper(RecyclableObject* object, JavascriptString* separator, ScriptContext* scriptContext)
  4040. {
  4041. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4042. SETOBJECT_FOR_MUTATION(jsReentLock, object);
  4043. // In ES6-mode, we always load the length property from the object instead of using the internal slot.
  4044. // Even for arrays, this is now observable via proxies.
  4045. // If source object is not an array, we fall back to this behavior anyway.
  4046. JS_REENTRANT(jsReentLock,
  4047. int64 cSrcLength = (int64)OP_GetLength(object, scriptContext));
  4048. switch (cSrcLength)
  4049. {
  4050. default:
  4051. {
  4052. CaseDefault:
  4053. bool hasSeparator = (separator->GetLength() != 0);
  4054. BOOL gotItem;
  4055. const charcount_t estimatedAppendCount =
  4056. min(
  4057. Join_MaxEstimatedAppendCount,
  4058. static_cast<charcount_t>(cSrcLength + (hasSeparator ? cSrcLength - 1 : 0)));
  4059. CompoundString *const cs =
  4060. CompoundString::NewWithPointerCapacity(estimatedAppendCount, scriptContext->GetLibrary());
  4061. Var value;
  4062. JS_REENTRANT(jsReentLock, gotItem = JavascriptOperators::GetItem(object, 0u, &value, scriptContext));
  4063. if (gotItem)
  4064. {
  4065. JS_REENTRANT(jsReentLock, cs->Append(JavascriptArray::JoinToString(value, scriptContext)));
  4066. }
  4067. for (uint32 i = 1; i < cSrcLength; i++)
  4068. {
  4069. if (hasSeparator)
  4070. {
  4071. cs->Append(separator);
  4072. }
  4073. JS_REENTRANT(jsReentLock, gotItem = JavascriptOperators::GetItem(object, i, &value, scriptContext));
  4074. if (gotItem)
  4075. {
  4076. JS_REENTRANT(jsReentLock, cs->Append(JavascriptArray::JoinToString(value, scriptContext)));
  4077. }
  4078. }
  4079. return cs;
  4080. }
  4081. case 2:
  4082. {
  4083. bool hasSeparator = (separator->GetLength() != 0);
  4084. BOOL gotItem;
  4085. if(hasSeparator)
  4086. {
  4087. goto CaseDefault;
  4088. }
  4089. JavascriptString *res = nullptr;
  4090. Var value;
  4091. JS_REENTRANT(jsReentLock, gotItem = JavascriptOperators::GetItem(object, 0u, &value, scriptContext));
  4092. if (gotItem)
  4093. {
  4094. JS_REENTRANT(jsReentLock, res = JavascriptArray::JoinToString(value, scriptContext));
  4095. }
  4096. JS_REENTRANT(jsReentLock, gotItem = JavascriptOperators::GetItem(object, 1u, &value, scriptContext));
  4097. if (gotItem)
  4098. {
  4099. JS_REENTRANT(jsReentLock, JavascriptString *const valueString = JavascriptArray::JoinToString(value, scriptContext));
  4100. return res ? ConcatString::New(res, valueString) : valueString;
  4101. }
  4102. if(res)
  4103. {
  4104. return res;
  4105. }
  4106. goto Case0;
  4107. }
  4108. case 1:
  4109. {
  4110. Var value;
  4111. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(object, 0u, &value, scriptContext));
  4112. if (gotItem)
  4113. {
  4114. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::JoinToString(value, scriptContext));
  4115. }
  4116. // fall through
  4117. }
  4118. case 0:
  4119. Case0:
  4120. return scriptContext->GetLibrary()->GetEmptyString();
  4121. }
  4122. }
  4123. Var JavascriptArray::EntryLastIndexOf(RecyclableObject* function, CallInfo callInfo, ...)
  4124. {
  4125. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  4126. ARGUMENTS(args, callInfo);
  4127. ScriptContext* scriptContext = function->GetScriptContext();
  4128. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4129. SETOBJECT_FOR_MUTATION(jsReentLock, args[0]);
  4130. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_lastIndexOf);
  4131. Assert(!(callInfo.Flags & CallFlags_New));
  4132. int64 length;
  4133. JavascriptArray * pArr = nullptr;
  4134. RecyclableObject* obj = nullptr;
  4135. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.lastIndexOf"), &pArr, &obj, &length));
  4136. Var search;
  4137. int64 fromIndex;
  4138. JS_REENTRANT(jsReentLock,
  4139. BOOL gotParam = GetParamForLastIndexOf(length, args, search, fromIndex, scriptContext));
  4140. if (!gotParam)
  4141. {
  4142. return TaggedInt::ToVarUnchecked(-1);
  4143. }
  4144. // Side effects (such as defining a property in a ToPrimitive call) during evaluation of fromIndex argument may convert the array to an ES5 array.
  4145. if (pArr && !JavascriptArray::Is(obj))
  4146. {
  4147. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  4148. pArr = nullptr;
  4149. }
  4150. if (pArr)
  4151. {
  4152. switch (pArr->GetTypeId())
  4153. {
  4154. case Js::TypeIds_Array:
  4155. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(pArr, search, fromIndex, scriptContext));
  4156. case Js::TypeIds_NativeIntArray:
  4157. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(JavascriptNativeIntArray::UnsafeFromVar(pArr), search, fromIndex, scriptContext));
  4158. case Js::TypeIds_NativeFloatArray:
  4159. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(JavascriptNativeFloatArray::UnsafeFromVar(pArr), search, fromIndex, scriptContext));
  4160. default:
  4161. AssertMsg(FALSE, "invalid array typeid");
  4162. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(pArr, search, fromIndex, scriptContext));
  4163. }
  4164. }
  4165. // source object is not a JavascriptArray but source could be a TypedArray
  4166. TypedArrayBase * typedArrayObj = JavascriptOperators::TryFromVar<Js::TypedArrayBase>(obj);
  4167. if (typedArrayObj)
  4168. {
  4169. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(typedArrayObj, search, fromIndex, scriptContext));
  4170. }
  4171. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(obj, search, fromIndex, scriptContext));
  4172. }
  4173. // Array.prototype.lastIndexOf as described in ES6.0 (draft 22) Section 22.1.3.14
  4174. BOOL JavascriptArray::GetParamForLastIndexOf(int64 length, Arguments const & args, Var& search, int64& fromIndex, ScriptContext * scriptContext)
  4175. {
  4176. if (length == 0)
  4177. {
  4178. return false;
  4179. }
  4180. if (args.Info.Count > 2)
  4181. {
  4182. fromIndex = GetFromLastIndex(args[2], length, scriptContext);
  4183. if (fromIndex >= length)
  4184. {
  4185. return false;
  4186. }
  4187. search = args[1];
  4188. }
  4189. else
  4190. {
  4191. search = args.Info.Count > 1 ? args[1] : scriptContext->GetLibrary()->GetUndefined();
  4192. fromIndex = length - 1;
  4193. }
  4194. return true;
  4195. }
  4196. template <typename T>
  4197. Var JavascriptArray::LastIndexOfHelper(T* pArr, Var search, int64 fromIndex, ScriptContext * scriptContext)
  4198. {
  4199. Var element = nullptr;
  4200. bool isSearchTaggedInt = TaggedInt::Is(search);
  4201. // First handle the indices > 2^32
  4202. while (fromIndex >= MaxArrayLength)
  4203. {
  4204. Var index = JavascriptNumber::ToVar(fromIndex, scriptContext);
  4205. if (JavascriptOperators::OP_HasItem(pArr, index, scriptContext))
  4206. {
  4207. element = JavascriptOperators::OP_GetElementI(pArr, index, scriptContext);
  4208. if (isSearchTaggedInt && TaggedInt::Is(element))
  4209. {
  4210. if (element == search)
  4211. {
  4212. return index;
  4213. }
  4214. fromIndex--;
  4215. continue;
  4216. }
  4217. if (JavascriptOperators::StrictEqual(element, search, scriptContext))
  4218. {
  4219. return index;
  4220. }
  4221. }
  4222. fromIndex--;
  4223. }
  4224. Assert(fromIndex < MaxArrayLength);
  4225. // fromIndex now has to be < MaxArrayLength so casting to uint32 is safe
  4226. uint32 end = static_cast<uint32>(fromIndex);
  4227. for (uint32 i = 0; i <= end; i++)
  4228. {
  4229. uint32 index = end - i;
  4230. if (!TryTemplatedGetItem(pArr, index, &element, scriptContext))
  4231. {
  4232. continue;
  4233. }
  4234. if (isSearchTaggedInt && TaggedInt::Is(element))
  4235. {
  4236. if (element == search)
  4237. {
  4238. return JavascriptNumber::ToVar(index, scriptContext);
  4239. }
  4240. continue;
  4241. }
  4242. if (JavascriptOperators::StrictEqual(element, search, scriptContext))
  4243. {
  4244. return JavascriptNumber::ToVar(index, scriptContext);
  4245. }
  4246. }
  4247. return TaggedInt::ToVarUnchecked(-1);
  4248. }
  4249. /*
  4250. * PopWithNoDst
  4251. * - For pop calls that do not return a value, we only need to decrement the length of the array.
  4252. */
  4253. void JavascriptNativeArray::PopWithNoDst(Var nativeArray)
  4254. {
  4255. Assert(JavascriptNativeArray::Is(nativeArray));
  4256. JavascriptArray * arr = JavascriptArray::FromVar(nativeArray);
  4257. // we will bailout on length 0
  4258. Assert(arr->GetLength() != 0);
  4259. uint32 index = arr->GetLength() - 1;
  4260. arr->SetLength(index);
  4261. }
  4262. /*
  4263. * JavascriptNativeIntArray::Pop
  4264. * - Returns int32 value from the array.
  4265. * - Returns missing item when the element is not available in the array object.
  4266. * - It doesn't walk up the prototype chain.
  4267. * - Length is decremented only if it pops an int32 element, in all other cases - we bail out from the jitted code.
  4268. * - This api cannot cause any implicit call and hence do not need implicit call bailout test around this api
  4269. */
  4270. int32 JavascriptNativeIntArray::Pop(ScriptContext * scriptContext, Var object)
  4271. {
  4272. Assert(JavascriptNativeIntArray::Is(object));
  4273. JavascriptNativeIntArray * arr = JavascriptNativeIntArray::FromVar(object);
  4274. Assert(arr->GetLength() != 0);
  4275. uint32 index = arr->length - 1;
  4276. int32 element = Js::JavascriptOperators::OP_GetNativeIntElementI_UInt32(object, index, scriptContext);
  4277. //If it is a missing item, then don't update the length - Pre-op Bail out will happen.
  4278. if(!SparseArraySegment<int32>::IsMissingItem(&element))
  4279. {
  4280. arr->SetLength(index);
  4281. }
  4282. return element;
  4283. }
  4284. /*
  4285. * JavascriptNativeFloatArray::Pop
  4286. * - Returns double value from the array.
  4287. * - Returns missing item when the element is not available in the array object.
  4288. * - It doesn't walk up the prototype chain.
  4289. * - Length is decremented only if it pops a double element, in all other cases - we bail out from the jitted code.
  4290. * - This api cannot cause any implicit call and hence do not need implicit call bailout test around this api
  4291. */
  4292. double JavascriptNativeFloatArray::Pop(ScriptContext * scriptContext, Var object)
  4293. {
  4294. Assert(JavascriptNativeFloatArray::Is(object));
  4295. JavascriptNativeFloatArray * arr = JavascriptNativeFloatArray::FromVar(object);
  4296. Assert(arr->GetLength() != 0);
  4297. uint32 index = arr->length - 1;
  4298. double element = Js::JavascriptOperators::OP_GetNativeFloatElementI_UInt32(object, index, scriptContext);
  4299. // If it is a missing item then don't update the length - Pre-op Bail out will happen.
  4300. if(!SparseArraySegment<double>::IsMissingItem(&element))
  4301. {
  4302. arr->SetLength(index);
  4303. }
  4304. return element;
  4305. }
  4306. /*
  4307. * JavascriptArray::Pop
  4308. * - Calls the generic Pop API, which can find elements from the prototype chain, when it is not available in the array object.
  4309. * - This API may cause implicit calls. Handles Array and non-array objects
  4310. */
  4311. Var JavascriptArray::Pop(ScriptContext * scriptContext, Var object)
  4312. {
  4313. if (JavascriptArray::Is(object))
  4314. {
  4315. return EntryPopJavascriptArray(scriptContext, JavascriptArray::FromVar(object));
  4316. }
  4317. else
  4318. {
  4319. return EntryPopNonJavascriptArray(scriptContext, object);
  4320. }
  4321. }
  4322. Var JavascriptArray::EntryPopJavascriptArray(ScriptContext * scriptContext, JavascriptArray* arr)
  4323. {
  4324. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4325. SETOBJECT_FOR_MUTATION(jsReentLock, arr);
  4326. uint32 length = arr->length;
  4327. if (length == 0)
  4328. {
  4329. // If length is 0, return 'undefined'
  4330. return scriptContext->GetLibrary()->GetUndefined();
  4331. }
  4332. uint32 index = length - 1;
  4333. Var element;
  4334. JS_REENTRANT(jsReentLock, BOOL gotItem = arr->DirectGetItemAtFull(index, &element));
  4335. if (!gotItem)
  4336. {
  4337. element = scriptContext->GetLibrary()->GetUndefined();
  4338. }
  4339. else
  4340. {
  4341. element = CrossSite::MarshalVar(scriptContext, element, arr->GetScriptContext());
  4342. }
  4343. arr->SetLength(index); // SetLength will clear element at index
  4344. #ifdef VALIDATE_ARRAY
  4345. arr->ValidateArray();
  4346. #endif
  4347. return element;
  4348. }
  4349. Var JavascriptArray::EntryPopNonJavascriptArray(ScriptContext * scriptContext, Var object)
  4350. {
  4351. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4352. RecyclableObject* dynamicObject = nullptr;
  4353. if (FALSE == JavascriptConversion::ToObject(object, scriptContext, &dynamicObject))
  4354. {
  4355. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.pop"));
  4356. }
  4357. SETOBJECT_FOR_MUTATION(jsReentLock, dynamicObject);
  4358. JS_REENTRANT(jsReentLock, BigIndex length = OP_GetLength(dynamicObject, scriptContext));
  4359. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.pop"));
  4360. if (length == 0u)
  4361. {
  4362. // Set length = 0
  4363. JS_REENTRANT(jsReentLock,
  4364. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, TaggedInt::ToVarUnchecked(0), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  4365. return scriptContext->GetLibrary()->GetUndefined();
  4366. }
  4367. BigIndex index = length;
  4368. --index;
  4369. Var element;
  4370. if (index.IsSmallIndex())
  4371. {
  4372. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(dynamicObject, index.GetSmallIndex(), &element, scriptContext));
  4373. if (!gotItem)
  4374. {
  4375. element = scriptContext->GetLibrary()->GetUndefined();
  4376. }
  4377. JS_REENTRANT(jsReentLock,
  4378. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, index.GetSmallIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig)),
  4379. // Set the new length
  4380. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(index.GetSmallIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  4381. }
  4382. else
  4383. {
  4384. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(dynamicObject, index.GetBigIndex(), &element, scriptContext));
  4385. if (!gotItem)
  4386. {
  4387. element = scriptContext->GetLibrary()->GetUndefined();
  4388. }
  4389. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, index.GetBigIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig)),
  4390. // Set the new length
  4391. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(index.GetBigIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  4392. }
  4393. return element;
  4394. }
  4395. Var JavascriptArray::EntryPop(RecyclableObject* function, CallInfo callInfo, ...)
  4396. {
  4397. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  4398. ARGUMENTS(args, callInfo);
  4399. ScriptContext* scriptContext = function->GetScriptContext();
  4400. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4401. SETOBJECT_FOR_MUTATION(jsReentLock, args[0]);
  4402. Assert(!(callInfo.Flags & CallFlags_New));
  4403. if (args.Info.Count == 0)
  4404. {
  4405. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.pop"));
  4406. }
  4407. if (JavascriptArray::Is(args[0]))
  4408. {
  4409. JS_REENTRANT_UNLOCK(jsReentLock, return EntryPopJavascriptArray(scriptContext, JavascriptArray::FromVar(args.Values[0])));
  4410. }
  4411. else
  4412. {
  4413. JS_REENTRANT_UNLOCK(jsReentLock, return EntryPopNonJavascriptArray(scriptContext, args.Values[0]));
  4414. }
  4415. }
  4416. /*
  4417. * JavascriptNativeIntArray::Push
  4418. * Pushes Int element in a native Int Array.
  4419. * We call the generic Push, if the array is not native Int or we have a really big array.
  4420. */
  4421. Var JavascriptNativeIntArray::Push(ScriptContext * scriptContext, Var array, int value)
  4422. {
  4423. // Handle non crossSite native int arrays here length within MaxArrayLength.
  4424. // JavascriptArray::Push will handle other cases.
  4425. if (JavascriptNativeIntArray::IsNonCrossSite(array))
  4426. {
  4427. JavascriptNativeIntArray * nativeIntArray = JavascriptNativeIntArray::UnsafeFromVar(array);
  4428. Assert(!nativeIntArray->IsCrossSiteObject());
  4429. uint32 n = nativeIntArray->length;
  4430. if(n < JavascriptArray::MaxArrayLength)
  4431. {
  4432. nativeIntArray->SetItem(n, value);
  4433. n++;
  4434. AssertMsg(n == nativeIntArray->length, "Wrong update to the length of the native Int array");
  4435. return JavascriptNumber::ToVar(n, scriptContext);
  4436. }
  4437. }
  4438. return JavascriptArray::Push(scriptContext, array, JavascriptNumber::ToVar(value, scriptContext));
  4439. }
  4440. /*
  4441. * JavascriptNativeFloatArray::Push
  4442. * Pushes Float element in a native Int Array.
  4443. * We call the generic Push, if the array is not native Float or we have a really big array.
  4444. */
  4445. Var JavascriptNativeFloatArray::Push(ScriptContext * scriptContext, Var * array, double value)
  4446. {
  4447. // Handle non crossSite native int arrays here length within MaxArrayLength.
  4448. // JavascriptArray::Push will handle other cases.
  4449. if(JavascriptNativeFloatArray::IsNonCrossSite(array))
  4450. {
  4451. JavascriptNativeFloatArray * nativeFloatArray = JavascriptNativeFloatArray::UnsafeFromVar(array);
  4452. Assert(!nativeFloatArray->IsCrossSiteObject());
  4453. uint32 n = nativeFloatArray->length;
  4454. if(n < JavascriptArray::MaxArrayLength)
  4455. {
  4456. nativeFloatArray->SetItem(n, value);
  4457. n++;
  4458. AssertMsg(n == nativeFloatArray->length, "Wrong update to the length of the native Float array");
  4459. return JavascriptNumber::ToVar(n, scriptContext);
  4460. }
  4461. }
  4462. return JavascriptArray::Push(scriptContext, array, JavascriptNumber::ToVarNoCheck(value, scriptContext));
  4463. }
  4464. /*
  4465. * JavascriptArray::Push
  4466. * Pushes Var element in a Var Array.
  4467. */
  4468. Var JavascriptArray::Push(ScriptContext * scriptContext, Var object, Var value)
  4469. {
  4470. Var args[2];
  4471. args[0] = object;
  4472. args[1] = value;
  4473. if (JavascriptArray::Is(object))
  4474. {
  4475. return EntryPushJavascriptArray(scriptContext, args, 2);
  4476. }
  4477. else
  4478. {
  4479. return EntryPushNonJavascriptArray(scriptContext, args, 2);
  4480. }
  4481. }
  4482. /*
  4483. * EntryPushNonJavascriptArray
  4484. * - Handles Entry push calls, when Objects are not javascript arrays
  4485. */
  4486. Var JavascriptArray::EntryPushNonJavascriptArray(ScriptContext * scriptContext, Var * args, uint argCount)
  4487. {
  4488. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4489. RecyclableObject* obj = nullptr;
  4490. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  4491. {
  4492. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.push"));
  4493. }
  4494. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  4495. JS_REENTRANT_UNLOCK(jsReentLock, Var length = JavascriptOperators::OP_GetLength(obj, scriptContext));
  4496. if(JavascriptOperators::GetTypeId(length) == TypeIds_Undefined && scriptContext->GetThreadContext()->IsDisableImplicitCall() &&
  4497. scriptContext->GetThreadContext()->GetImplicitCallFlags() != Js::ImplicitCall_None)
  4498. {
  4499. return length;
  4500. }
  4501. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.push"));
  4502. BigIndex n;
  4503. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  4504. {
  4505. n = (uint64) JavascriptConversion::ToLength(length, scriptContext);
  4506. }
  4507. else
  4508. {
  4509. n = JavascriptConversion::ToUInt32(length, scriptContext);
  4510. }
  4511. // First handle "small" indices.
  4512. uint index;
  4513. for (index=1; index < argCount && n < JavascriptArray::MaxArrayLength; ++index, ++n)
  4514. {
  4515. JS_REENTRANT(jsReentLock,
  4516. BOOL setItem = JavascriptOperators::SetItem(obj, obj, n.GetSmallIndex(), args[index], scriptContext, PropertyOperation_ThrowIfNotExtensible));
  4517. if (h.IsThrowTypeError(setItem))
  4518. {
  4519. if (scriptContext->GetThreadContext()->RecordImplicitException())
  4520. {
  4521. h.ThrowTypeErrorOnFailure();
  4522. }
  4523. else
  4524. {
  4525. return nullptr;
  4526. }
  4527. }
  4528. }
  4529. // Use BigIndex if we need to push indices >= MaxArrayLength
  4530. if (index < argCount)
  4531. {
  4532. BigIndex big = n;
  4533. for (; index < argCount; ++index, ++big)
  4534. {
  4535. JS_REENTRANT(jsReentLock, BOOL setItem = big.SetItem(obj, args[index], PropertyOperation_ThrowIfNotExtensible));
  4536. if (h.IsThrowTypeError(setItem))
  4537. {
  4538. if(scriptContext->GetThreadContext()->RecordImplicitException())
  4539. {
  4540. h.ThrowTypeErrorOnFailure();
  4541. }
  4542. else
  4543. {
  4544. return nullptr;
  4545. }
  4546. }
  4547. }
  4548. // Set the new length; for objects it is all right for this to be >= MaxArrayLength
  4549. JS_REENTRANT(jsReentLock,
  4550. BOOL setLength = JavascriptOperators::SetProperty(obj, obj, PropertyIds::length, big.ToNumber(scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  4551. if (h.IsThrowTypeError(setLength))
  4552. {
  4553. if(scriptContext->GetThreadContext()->RecordImplicitException())
  4554. {
  4555. h.ThrowTypeErrorOnFailure();
  4556. }
  4557. else
  4558. {
  4559. return nullptr;
  4560. }
  4561. }
  4562. return big.ToNumber(scriptContext);
  4563. }
  4564. else
  4565. {
  4566. // Set the new length
  4567. Var lengthAsNUmberVar = JavascriptNumber::ToVar(n.IsSmallIndex() ? n.GetSmallIndex() : n.GetBigIndex(), scriptContext);
  4568. JS_REENTRANT(jsReentLock,
  4569. BOOL setLength = JavascriptOperators::SetProperty(obj, obj, PropertyIds::length, lengthAsNUmberVar, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  4570. if (h.IsThrowTypeError(setLength))
  4571. {
  4572. if(scriptContext->GetThreadContext()->RecordImplicitException())
  4573. {
  4574. h.ThrowTypeErrorOnFailure();
  4575. }
  4576. else
  4577. {
  4578. return nullptr;
  4579. }
  4580. }
  4581. return lengthAsNUmberVar;
  4582. }
  4583. }
  4584. /*
  4585. * JavascriptArray::EntryPushJavascriptArray
  4586. * Pushes Var element in a Var Array.
  4587. * Returns the length of the array.
  4588. */
  4589. Var JavascriptArray::EntryPushJavascriptArray(ScriptContext * scriptContext, Var * args, uint argCount)
  4590. {
  4591. JavascriptArray * arr = JavascriptArray::FromAnyArray(args[0]);
  4592. uint n = arr->length;
  4593. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.push"));
  4594. // Fast Path for one push for small indexes
  4595. if (argCount == 2 && n < JavascriptArray::MaxArrayLength)
  4596. {
  4597. // Set Item is overridden by CrossSiteObject, so no need to check for IsCrossSiteObject()
  4598. h.ThrowTypeErrorOnFailure(arr->SetItem(n, args[1], PropertyOperation_None));
  4599. return JavascriptNumber::ToVar(n + 1, scriptContext);
  4600. }
  4601. // Fast Path for multiple push for small indexes
  4602. if (JavascriptArray::MaxArrayLength - argCount + 1 > n && JavascriptArray::IsVarArray(arr) && scriptContext == arr->GetScriptContext())
  4603. {
  4604. uint index;
  4605. for (index = 1; index < argCount; ++index, ++n)
  4606. {
  4607. Assert(n != JavascriptArray::MaxArrayLength);
  4608. // Set Item is overridden by CrossSiteObject, so no need to check for IsCrossSiteObject()
  4609. arr->JavascriptArray::DirectSetItemAt(n, args[index]);
  4610. }
  4611. return JavascriptNumber::ToVar(n, scriptContext);
  4612. }
  4613. return EntryPushJavascriptArrayNoFastPath(scriptContext, args, argCount);
  4614. }
  4615. Var JavascriptArray::EntryPushJavascriptArrayNoFastPath(ScriptContext * scriptContext, Var * args, uint argCount)
  4616. {
  4617. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4618. JavascriptArray * arr = JavascriptArray::FromAnyArray(args[0]);
  4619. SETOBJECT_FOR_MUTATION(jsReentLock, arr);
  4620. uint n = arr->length;
  4621. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.push"));
  4622. // First handle "small" indices.
  4623. uint index;
  4624. for (index = 1; index < argCount && n < JavascriptArray::MaxArrayLength; ++index, ++n)
  4625. {
  4626. // Set Item is overridden by CrossSiteObject, so no need to check for IsCrossSiteObject()
  4627. h.ThrowTypeErrorOnFailure(arr->SetItem(n, args[index], PropertyOperation_None));
  4628. }
  4629. // Use BigIndex if we need to push indices >= MaxArrayLength
  4630. if (index < argCount)
  4631. {
  4632. // Not supporting native array with BigIndex.
  4633. arr = EnsureNonNativeArray(arr);
  4634. Assert(n == JavascriptArray::MaxArrayLength);
  4635. for (BigIndex big = n; index < argCount; ++index, ++big)
  4636. {
  4637. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(big.SetItem(arr, args[index])));
  4638. }
  4639. #ifdef VALIDATE_ARRAY
  4640. arr->ValidateArray();
  4641. #endif
  4642. // This is where we should set the length, but for arrays it cannot be >= MaxArrayLength
  4643. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  4644. }
  4645. #ifdef VALIDATE_ARRAY
  4646. arr->ValidateArray();
  4647. #endif
  4648. return JavascriptNumber::ToVar(n, scriptContext);
  4649. }
  4650. /*
  4651. * JavascriptArray::EntryPush
  4652. * Handles Push calls(Script Function)
  4653. */
  4654. Var JavascriptArray::EntryPush(RecyclableObject* function, CallInfo callInfo, ...)
  4655. {
  4656. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  4657. ARGUMENTS(args, callInfo);
  4658. ScriptContext* scriptContext = function->GetScriptContext();
  4659. Assert(!(callInfo.Flags & CallFlags_New));
  4660. if (args.Info.Count == 0)
  4661. {
  4662. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.push"));
  4663. }
  4664. if (JavascriptArray::Is(args[0]))
  4665. {
  4666. return EntryPushJavascriptArray(scriptContext, args.Values, args.Info.Count);
  4667. }
  4668. else
  4669. {
  4670. return EntryPushNonJavascriptArray(scriptContext, args.Values, args.Info.Count);
  4671. }
  4672. }
  4673. template <typename T>
  4674. void JavascriptArray::CopyHeadIfInlinedHeadSegment(JavascriptArray *array, Recycler *recycler)
  4675. {
  4676. if (JavascriptArray::IsInlineSegment(array->head, array))
  4677. {
  4678. AnalysisAssert(array->head);
  4679. SparseArraySegment<T>* newHeadSeg = array->ReallocNonLeafSegment((SparseArraySegment<T>*)PointerValue(array->head), array->head->next);
  4680. array->head = newHeadSeg;
  4681. }
  4682. }
  4683. template <typename T>
  4684. void JavascriptArray::ReallocateNonLeafLastSegmentIfLeaf(JavascriptArray * arr, Recycler * recycler)
  4685. {
  4686. Assert(arr->head && arr->head->next); // Doesn't make sense to reallocate a leaf last segment as a non-leaf if its not going to point to any other segments.
  4687. // TODO: Consider utilizing lastUsedSegment once we fix CopyHeadIfInlinedHeadSegment in that respect.
  4688. SparseArraySegmentBase *lastSeg = nullptr;
  4689. SparseArraySegmentBase *seg = arr->head;
  4690. while (seg)
  4691. {
  4692. lastSeg = seg;
  4693. seg = seg->next;
  4694. }
  4695. if (SparseArraySegmentBase::IsLeafSegment(lastSeg, recycler))
  4696. {
  4697. AnalysisAssert(lastSeg);
  4698. arr->ReallocNonLeafSegment((SparseArraySegment<T>*)lastSeg, lastSeg->next, true /*forceNonLeaf*/);
  4699. }
  4700. }
  4701. Var JavascriptArray::EntryReverse(RecyclableObject* function, CallInfo callInfo, ...)
  4702. {
  4703. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  4704. ARGUMENTS(args, callInfo);
  4705. ScriptContext* scriptContext = function->GetScriptContext();
  4706. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4707. Assert(!(callInfo.Flags & CallFlags_New));
  4708. if (args.Info.Count == 0)
  4709. {
  4710. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reverse"));
  4711. }
  4712. BigIndex length = 0u;
  4713. JavascriptArray* pArr = nullptr;
  4714. RecyclableObject* obj = nullptr;
  4715. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.reverse"), &pArr, &obj, &length));
  4716. if (length.IsSmallIndex())
  4717. {
  4718. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReverseHelper(pArr, nullptr, obj, length.GetSmallIndex(), scriptContext));
  4719. }
  4720. Assert(pArr == nullptr || length.IsUint32Max()); // if pArr is not null lets make sure length is safe to cast, which will only happen if length is a uint32max
  4721. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReverseHelper(pArr, nullptr, obj, length.GetBigIndex(), scriptContext));
  4722. }
  4723. bool JavascriptArray::HasAnyES5ArrayInPrototypeChain(JavascriptArray *arr, bool forceCheckProtoChain)
  4724. {
  4725. Assert(arr != nullptr);
  4726. #if ENABLE_COPYONACCESS_ARRAY
  4727. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(arr);
  4728. #endif
  4729. bool hasAnyES5Array = false;
  4730. // If there is no gap (unless forced) we are not filling from the prototype - so no point checking for ES5Array.
  4731. if (forceCheckProtoChain || arr->IsFillFromPrototypes())
  4732. {
  4733. RecyclableObject* prototype = arr->GetPrototype();
  4734. while (!JavascriptOperators::IsNull(prototype))
  4735. {
  4736. RecyclableObject* protoObj = prototype;
  4737. if (!(DynamicObject::IsAnyArray(protoObj) || JavascriptOperators::IsObject(protoObj))
  4738. || JavascriptProxy::Is(protoObj)
  4739. || protoObj->IsExternal())
  4740. {
  4741. hasAnyES5Array = true;
  4742. break;
  4743. }
  4744. if (DynamicObject::IsAnyArray(protoObj))
  4745. {
  4746. if (ES5Array::Is(protoObj))
  4747. {
  4748. hasAnyES5Array = true;
  4749. break;
  4750. }
  4751. }
  4752. else if (DynamicType::Is(protoObj->GetTypeId()))
  4753. {
  4754. DynamicObject* dynobj = DynamicObject::UnsafeFromVar(protoObj);
  4755. ArrayObject* objectArray = dynobj->GetObjectArray();
  4756. if (objectArray != nullptr && ES5Array::Is(objectArray))
  4757. {
  4758. hasAnyES5Array = true;
  4759. break;
  4760. }
  4761. }
  4762. prototype = prototype->GetPrototype();
  4763. }
  4764. }
  4765. return hasAnyES5Array;
  4766. }
  4767. // Array.prototype.reverse as described in ES6.0 (draft 22) Section 22.1.3.20
  4768. template <typename T>
  4769. Var JavascriptArray::ReverseHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, ScriptContext* scriptContext)
  4770. {
  4771. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4772. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  4773. T middle = length / 2;
  4774. Var lowerValue = nullptr, upperValue = nullptr;
  4775. T lowerExists, upperExists;
  4776. const char16* methodName;
  4777. bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
  4778. if (isTypedArrayEntryPoint)
  4779. {
  4780. methodName = _u("[TypedArray].prototype.reverse");
  4781. }
  4782. else
  4783. {
  4784. methodName = _u("Array.prototype.reverse");
  4785. }
  4786. // If we came from Array.prototype.map and source object is not a JavascriptArray, source could be a TypedArray
  4787. if (!isTypedArrayEntryPoint && pArr == nullptr && TypedArrayBase::Is(obj))
  4788. {
  4789. typedArrayBase = TypedArrayBase::UnsafeFromVar(obj);
  4790. }
  4791. ThrowTypeErrorOnFailureHelper h(scriptContext, methodName);
  4792. bool useNoSideEffectReverse = pArr != nullptr && !HasAnyES5ArrayInPrototypeChain(pArr);
  4793. if (useNoSideEffectReverse)
  4794. {
  4795. Recycler * recycler = scriptContext->GetRecycler();
  4796. if (length <= 1)
  4797. {
  4798. return pArr;
  4799. }
  4800. if (pArr->IsFillFromPrototypes())
  4801. {
  4802. // For odd-length arrays, the middle element is unchanged,
  4803. // so we cannot fill it from the prototypes.
  4804. if (length % 2 == 0)
  4805. {
  4806. pArr->FillFromPrototypes(0, (uint32)length);
  4807. }
  4808. else
  4809. {
  4810. middle = length / 2;
  4811. pArr->FillFromPrototypes(0, (uint32)middle);
  4812. pArr->FillFromPrototypes(1 + (uint32)middle, (uint32)length);
  4813. }
  4814. }
  4815. // As we have already established that the FillFromPrototype should not change the bound of the array.
  4816. if (length != (T)pArr->length)
  4817. {
  4818. Js::Throw::FatalInternalError();
  4819. }
  4820. if (pArr->HasNoMissingValues() && pArr->head && pArr->head->next)
  4821. {
  4822. // This function currently does not track missing values in the head segment if there are multiple segments
  4823. pArr->SetHasNoMissingValues(false);
  4824. }
  4825. // Above FillFromPrototypes call can change the length of the array. Our segment calculation below will
  4826. // not work with the stale length. Update the length.
  4827. // Note : since we are reversing the whole segment below - the functionality is not spec compliant already.
  4828. length = pArr->length;
  4829. SparseArraySegmentBase *prevSeg = nullptr;
  4830. SparseArraySegmentBase *nextSeg = nullptr;
  4831. SparseArraySegmentBase *pinPrevSeg = nullptr;
  4832. bool isIntArray = false;
  4833. bool isFloatArray = false;
  4834. pArr->ClearSegmentMap(); // Just dump the segment map on reverse
  4835. if (JavascriptNativeIntArray::Is(pArr))
  4836. {
  4837. isIntArray = true;
  4838. }
  4839. else if (JavascriptNativeFloatArray::Is(pArr))
  4840. {
  4841. isFloatArray = true;
  4842. }
  4843. // Code below has potential to throw due to OOM or SO. Just FailFast on those cases
  4844. AutoDisableInterrupt failFastOnError(scriptContext->GetThreadContext());
  4845. // During the loop below we are going to reverse the segments list. The head segment will become the last segment.
  4846. // We have to verify that the current head segment is not the inilined segement, otherwise due to shuffling below (of EnsureHeadStartsFromZero call below), the inlined segment will no longer
  4847. // be the head and that can create issue down the line. Create new segment if it is an inilined segment.
  4848. if (pArr->head && (pArr->head->next || (pArr->head->left + pArr->head->length) < length))
  4849. {
  4850. if (isIntArray)
  4851. {
  4852. CopyHeadIfInlinedHeadSegment<int32>(pArr, recycler);
  4853. if (pArr->head->next)
  4854. {
  4855. ReallocateNonLeafLastSegmentIfLeaf<int32>(pArr, recycler);
  4856. }
  4857. }
  4858. else if (isFloatArray)
  4859. {
  4860. CopyHeadIfInlinedHeadSegment<double>(pArr, recycler);
  4861. if (pArr->head->next)
  4862. {
  4863. ReallocateNonLeafLastSegmentIfLeaf<double>(pArr, recycler);
  4864. }
  4865. }
  4866. else
  4867. {
  4868. CopyHeadIfInlinedHeadSegment<Var>(pArr, recycler);
  4869. }
  4870. }
  4871. SparseArraySegmentBase* seg = pArr->head;
  4872. while (seg)
  4873. {
  4874. nextSeg = seg->next;
  4875. // If seg.length == 0, it is possible that (seg.left + seg.length == prev.left + prev.length),
  4876. // resulting in 2 segments sharing the same "left".
  4877. if (seg->length > 0)
  4878. {
  4879. if (isIntArray)
  4880. {
  4881. ((SparseArraySegment<int32>*)seg)->ReverseSegment(recycler);
  4882. }
  4883. else if (isFloatArray)
  4884. {
  4885. ((SparseArraySegment<double>*)seg)->ReverseSegment(recycler);
  4886. }
  4887. else
  4888. {
  4889. ((SparseArraySegment<Var>*)seg)->ReverseSegment(recycler);
  4890. }
  4891. if (((uint32)length) < (seg->left + seg->length))
  4892. {
  4893. Js::Throw::FatalInternalError();
  4894. }
  4895. seg->left = ((uint32)length) - (seg->left + seg->length);
  4896. seg->next = prevSeg;
  4897. // Make sure size doesn't overlap with next segment.
  4898. // An easy fix is to just truncate the size...
  4899. seg->EnsureSizeInBound();
  4900. // If the last segment is a leaf, then we may be losing our last scanned pointer to its previous
  4901. // segment. Hold onto it with pinPrevSeg until we reallocate below.
  4902. pinPrevSeg = prevSeg;
  4903. prevSeg = seg;
  4904. }
  4905. seg = nextSeg;
  4906. }
  4907. pArr->head = prevSeg;
  4908. if (isIntArray)
  4909. {
  4910. pArr->EnsureHeadStartsFromZero<int32>(recycler);
  4911. }
  4912. else if (isFloatArray)
  4913. {
  4914. pArr->EnsureHeadStartsFromZero<double>(recycler);
  4915. }
  4916. else
  4917. {
  4918. pArr->EnsureHeadStartsFromZero<Var>(recycler);
  4919. }
  4920. pArr->InvalidateLastUsedSegment(); // lastUsedSegment might be 0-length and discarded above
  4921. #ifdef VALIDATE_ARRAY
  4922. pArr->ValidateArray();
  4923. #endif
  4924. failFastOnError.Completed();
  4925. }
  4926. else if (typedArrayBase)
  4927. {
  4928. Assert(length <= JavascriptArray::MaxArrayLength);
  4929. if (typedArrayBase->GetLength() == length)
  4930. {
  4931. // If typedArrayBase->length == length then we know that the TypedArray will have all items < length
  4932. // and we won't have to check that the elements exist or not.
  4933. for (uint32 lower = 0; lower < (uint32)middle; lower++)
  4934. {
  4935. uint32 upper = (uint32)length - lower - 1;
  4936. lowerValue = typedArrayBase->DirectGetItem(lower);
  4937. upperValue = typedArrayBase->DirectGetItem(upper);
  4938. // We still have to call HasItem even though we know the TypedArray has both lower and upper because
  4939. // there may be a proxy handler trapping HasProperty.
  4940. lowerExists = typedArrayBase->HasItem(lower);
  4941. upperExists = typedArrayBase->HasItem(upper);
  4942. JS_REENTRANT(jsReentLock,
  4943. h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(lower, upperValue)),
  4944. h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(upper, lowerValue)));
  4945. }
  4946. }
  4947. else
  4948. {
  4949. Assert(middle <= UINT_MAX);
  4950. for (uint32 lower = 0; lower < (uint32)middle; lower++)
  4951. {
  4952. uint32 upper = (uint32)length - lower - 1;
  4953. lowerValue = typedArrayBase->DirectGetItem(lower);
  4954. upperValue = typedArrayBase->DirectGetItem(upper);
  4955. lowerExists = typedArrayBase->HasItem(lower);
  4956. upperExists = typedArrayBase->HasItem(upper);
  4957. if (lowerExists)
  4958. {
  4959. if (upperExists)
  4960. {
  4961. JS_REENTRANT(jsReentLock,
  4962. h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(lower, upperValue)),
  4963. h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(upper, lowerValue)));
  4964. }
  4965. else
  4966. {
  4967. // This will always fail for a TypedArray if lower < length
  4968. h.ThrowTypeErrorOnFailure(typedArrayBase->DeleteItem(lower, PropertyOperation_ThrowOnDeleteIfNotConfig));
  4969. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(upper, lowerValue)));
  4970. }
  4971. }
  4972. else
  4973. {
  4974. if (upperExists)
  4975. {
  4976. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(lower, upperValue)));
  4977. // This will always fail for a TypedArray if upper < length
  4978. h.ThrowTypeErrorOnFailure(typedArrayBase->DeleteItem(upper, PropertyOperation_ThrowOnDeleteIfNotConfig));
  4979. }
  4980. }
  4981. }
  4982. }
  4983. }
  4984. else
  4985. {
  4986. for (T lower = 0; lower < middle; lower++)
  4987. {
  4988. T upper = length - lower - 1;
  4989. JS_REENTRANT(jsReentLock,
  4990. lowerExists = JavascriptOperators::HasItem(obj, lower) && JavascriptOperators::GetItem(obj, lower, &lowerValue, scriptContext),
  4991. upperExists = JavascriptOperators::HasItem(obj, upper) && JavascriptOperators::GetItem(obj, upper, &upperValue, scriptContext));
  4992. if (lowerExists)
  4993. {
  4994. if (upperExists)
  4995. {
  4996. JS_REENTRANT(jsReentLock,
  4997. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, lower, upperValue, scriptContext, PropertyOperation_ThrowIfNotExtensible)),
  4998. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, upper, lowerValue, scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  4999. }
  5000. else
  5001. {
  5002. JS_REENTRANT(jsReentLock,
  5003. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(obj, lower, PropertyOperation_ThrowOnDeleteIfNotConfig)),
  5004. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, upper, lowerValue, scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  5005. }
  5006. }
  5007. else
  5008. {
  5009. if (upperExists)
  5010. {
  5011. JS_REENTRANT(jsReentLock,
  5012. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, lower, upperValue, scriptContext, PropertyOperation_ThrowIfNotExtensible)),
  5013. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(obj, upper, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  5014. }
  5015. }
  5016. }
  5017. }
  5018. return obj;
  5019. }
  5020. template<typename T>
  5021. void JavascriptArray::ShiftHelper(JavascriptArray* pArr, ScriptContext * scriptContext)
  5022. {
  5023. Recycler * recycler = scriptContext->GetRecycler();
  5024. SparseArraySegment<T>* next = SparseArraySegment<T>::From(pArr->head->next);
  5025. while (next)
  5026. {
  5027. next->left--;
  5028. next = SparseArraySegment<T>::From(next->next);
  5029. }
  5030. // head and next might overlap as the next segment left is decremented
  5031. next = SparseArraySegment<T>::From(pArr->head->next);
  5032. if (next && (pArr->head->size > next->left))
  5033. {
  5034. AssertMsg(pArr->head->left == 0, "Array always points to a head starting at index 0");
  5035. AssertMsg(pArr->head->size == next->left + 1, "Shift next->left overlaps current segment by more than 1 element");
  5036. SparseArraySegment<T> *head = SparseArraySegment<T>::From(pArr->head);
  5037. SparseArraySegment<T> *oldHead = head;
  5038. bool isInlineSegment = JavascriptArray::IsInlineSegment(head, pArr);
  5039. bool nextIsInlineSegment = JavascriptArray::IsInlineSegment(next, pArr);
  5040. // Merge the two adjacent segments
  5041. if (next->length != 0)
  5042. {
  5043. uint32 offset = head->size - 1;
  5044. // There is room for one unshifted element in head segment.
  5045. // Hence it's enough if we grow the head segment by next->length - 1
  5046. if (next->next)
  5047. {
  5048. // If we have a next->next, we can't grow pass the left of that
  5049. // If the array had a segment map before, the next->next might just be right after next as well.
  5050. // So we just need to grow to the end of the next segment
  5051. // TODO: merge that segment too?
  5052. Assert(next->next->left >= head->size);
  5053. uint32 maxGrowSize = next->next->left - head->size;
  5054. if (maxGrowSize != 0)
  5055. {
  5056. head = head->GrowByMinMax(recycler, next->length - 1, maxGrowSize); //-1 is to account for unshift
  5057. }
  5058. else
  5059. {
  5060. // The next segment is only of length one, so we already have space in the header to copy that
  5061. Assert(next->length == 1);
  5062. }
  5063. }
  5064. else
  5065. {
  5066. head = head->GrowByMin(recycler, next->length - 1); //-1 is to account for unshift
  5067. }
  5068. MoveArray(head->elements + offset, next->elements, next->length);
  5069. head->length = offset + next->length;
  5070. head->CheckLengthvsSize();
  5071. pArr->head = head;
  5072. if (isInlineSegment && oldHead != head)
  5073. {
  5074. pArr->ClearElements(oldHead, 0);
  5075. }
  5076. }
  5077. head->next = next->next;
  5078. if (nextIsInlineSegment)
  5079. {
  5080. pArr->ClearElements(next, 0);
  5081. }
  5082. pArr->InvalidateLastUsedSegment();
  5083. }
  5084. #ifdef VALIDATE_ARRAY
  5085. pArr->ValidateArray();
  5086. #endif
  5087. }
  5088. Var JavascriptArray::EntryShift(RecyclableObject* function, CallInfo callInfo, ...)
  5089. {
  5090. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  5091. ARGUMENTS(args, callInfo);
  5092. ScriptContext* scriptContext = function->GetScriptContext();
  5093. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  5094. SETOBJECT_FOR_MUTATION(jsReentLock, args[0]);
  5095. Assert(!(callInfo.Flags & CallFlags_New));
  5096. Var res = scriptContext->GetLibrary()->GetUndefined();
  5097. if (args.Info.Count == 0)
  5098. {
  5099. return res;
  5100. }
  5101. bool useNoSideEffectShift = JavascriptArray::Is(args[0])
  5102. && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject()
  5103. && !HasAnyES5ArrayInPrototypeChain(JavascriptArray::UnsafeFromVar(args[0]));
  5104. if (useNoSideEffectShift)
  5105. {
  5106. JavascriptArray * pArr = JavascriptArray::UnsafeFromVar(args[0]);
  5107. if (pArr->length == 0)
  5108. {
  5109. return res;
  5110. }
  5111. uint32 length = pArr->length;
  5112. if(pArr->IsFillFromPrototypes())
  5113. {
  5114. pArr->FillFromPrototypes(0, pArr->length); // We need find all missing value from [[proto]] object
  5115. }
  5116. // As we have already established that the FillFromPrototype should not change the bound of the array.
  5117. if (length != pArr->length)
  5118. {
  5119. Js::Throw::FatalInternalError();
  5120. }
  5121. if(pArr->HasNoMissingValues() && pArr->head && pArr->head->next)
  5122. {
  5123. // This function currently does not track missing values in the head segment if there are multiple segments
  5124. pArr->SetHasNoMissingValues(false);
  5125. }
  5126. pArr->length--;
  5127. pArr->ClearSegmentMap(); // Dump segmentMap on shift (before any allocation)
  5128. Recycler * recycler = scriptContext->GetRecycler();
  5129. bool isIntArray = false;
  5130. bool isFloatArray = false;
  5131. if(JavascriptNativeIntArray::Is(pArr))
  5132. {
  5133. isIntArray = true;
  5134. }
  5135. else if(JavascriptNativeFloatArray::Is(pArr))
  5136. {
  5137. isFloatArray = true;
  5138. }
  5139. // Code below has potential to throw due to OOM or SO. Just FailFast on those cases
  5140. AutoDisableInterrupt failFastOnError(scriptContext->GetThreadContext());
  5141. if (pArr->head->length != 0)
  5142. {
  5143. if(isIntArray)
  5144. {
  5145. int32 nativeResult = SparseArraySegment<int32>::From(pArr->head)->GetElement(0);
  5146. if(SparseArraySegment<int32>::IsMissingItem(&nativeResult))
  5147. {
  5148. res = scriptContext->GetLibrary()->GetUndefined();
  5149. }
  5150. else
  5151. {
  5152. res = Js::JavascriptNumber::ToVar(nativeResult, scriptContext);
  5153. }
  5154. SparseArraySegment<int32>::From(pArr->head)->RemoveElement(recycler, 0);
  5155. }
  5156. else if (isFloatArray)
  5157. {
  5158. double nativeResult = SparseArraySegment<double>::From(pArr->head)->GetElement(0);
  5159. if(SparseArraySegment<double>::IsMissingItem(&nativeResult))
  5160. {
  5161. res = scriptContext->GetLibrary()->GetUndefined();
  5162. }
  5163. else
  5164. {
  5165. res = Js::JavascriptNumber::ToVarNoCheck(nativeResult, scriptContext);
  5166. }
  5167. SparseArraySegment<double>::From(pArr->head)->RemoveElement(recycler, 0);
  5168. }
  5169. else
  5170. {
  5171. res = SparseArraySegment<Var>::From(pArr->head)->GetElement(0);
  5172. if(SparseArraySegment<Var>::IsMissingItem(&res))
  5173. {
  5174. res = scriptContext->GetLibrary()->GetUndefined();
  5175. }
  5176. else
  5177. {
  5178. res = CrossSite::MarshalVar(scriptContext, res);
  5179. }
  5180. SparseArraySegment<Var>::From(pArr->head)->RemoveElement(recycler, 0);
  5181. }
  5182. }
  5183. if(isIntArray)
  5184. {
  5185. ShiftHelper<int32>(pArr, scriptContext);
  5186. }
  5187. else if (isFloatArray)
  5188. {
  5189. ShiftHelper<double>(pArr, scriptContext);
  5190. }
  5191. else
  5192. {
  5193. ShiftHelper<Var>(pArr, scriptContext);
  5194. }
  5195. failFastOnError.Completed();
  5196. }
  5197. else
  5198. {
  5199. RecyclableObject* dynamicObject = nullptr;
  5200. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &dynamicObject))
  5201. {
  5202. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.shift"));
  5203. }
  5204. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.shift"));
  5205. JS_REENTRANT(jsReentLock, BigIndex length = OP_GetLength(dynamicObject, scriptContext));
  5206. if (length == 0u)
  5207. {
  5208. // If length is 0, return 'undefined'
  5209. JS_REENTRANT(jsReentLock,
  5210. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, TaggedInt::ToVarUnchecked(0), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  5211. return scriptContext->GetLibrary()->GetUndefined();
  5212. }
  5213. JS_REENTRANT(jsReentLock,
  5214. BOOL gotItem = JavascriptOperators::GetItem(dynamicObject, 0u, &res, scriptContext));
  5215. if (!gotItem)
  5216. {
  5217. res = scriptContext->GetLibrary()->GetUndefined();
  5218. }
  5219. --length;
  5220. uint32 lengthToUin32Max = length.IsSmallIndex() ? length.GetSmallIndex() : MaxArrayLength;
  5221. for (uint32 i = 0u; i < lengthToUin32Max; i++)
  5222. {
  5223. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(dynamicObject, i + 1));
  5224. if (hasItem)
  5225. {
  5226. Var element = nullptr;
  5227. JS_REENTRANT(jsReentLock,
  5228. element = JavascriptOperators::GetItem(dynamicObject, i + 1, scriptContext),
  5229. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(dynamicObject, dynamicObject, i, element, scriptContext, PropertyOperation_ThrowIfNotExtensible, /*skipPrototypeCheck*/ true)));
  5230. }
  5231. else
  5232. {
  5233. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, i, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  5234. }
  5235. }
  5236. for (uint64 i = MaxArrayLength; length > i; i++)
  5237. {
  5238. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(dynamicObject, i + 1));
  5239. if (hasItem)
  5240. {
  5241. Var element = nullptr;
  5242. JS_REENTRANT(jsReentLock,
  5243. element = JavascriptOperators::GetItem(dynamicObject, i + 1, scriptContext),
  5244. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(dynamicObject, dynamicObject, i, element, scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  5245. }
  5246. else
  5247. {
  5248. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, i, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  5249. }
  5250. }
  5251. if (length.IsSmallIndex())
  5252. {
  5253. JS_REENTRANT(jsReentLock,
  5254. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, length.GetSmallIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig)),
  5255. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(length.GetSmallIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  5256. }
  5257. else
  5258. {
  5259. JS_REENTRANT(jsReentLock,
  5260. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, length.GetBigIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig)),
  5261. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(length.GetBigIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  5262. }
  5263. }
  5264. return res;
  5265. }
  5266. Js::JavascriptArray* JavascriptArray::CreateNewArrayHelper(uint32 len, bool isIntArray, bool isFloatArray, Js::JavascriptArray* baseArray, ScriptContext* scriptContext)
  5267. {
  5268. if (isIntArray)
  5269. {
  5270. Js::JavascriptNativeIntArray *pnewArr = scriptContext->GetLibrary()->CreateNativeIntArray(len);
  5271. pnewArr->EnsureHead<int32>();
  5272. #if ENABLE_PROFILE_INFO
  5273. pnewArr->CopyArrayProfileInfo(Js::JavascriptNativeIntArray::UnsafeFromVar(baseArray));
  5274. #endif
  5275. return pnewArr;
  5276. }
  5277. else if (isFloatArray)
  5278. {
  5279. Js::JavascriptNativeFloatArray *pnewArr = scriptContext->GetLibrary()->CreateNativeFloatArray(len);
  5280. pnewArr->EnsureHead<double>();
  5281. #if ENABLE_PROFILE_INFO
  5282. pnewArr->CopyArrayProfileInfo(Js::JavascriptNativeFloatArray::UnsafeFromVar(baseArray));
  5283. #endif
  5284. return pnewArr;
  5285. }
  5286. else
  5287. {
  5288. JavascriptArray *pnewArr = pnewArr = scriptContext->GetLibrary()->CreateArray(len);
  5289. pnewArr->EnsureHead<Var>();
  5290. return pnewArr;
  5291. }
  5292. }
  5293. template<typename T>
  5294. void JavascriptArray::SliceHelper(JavascriptArray* pArr, JavascriptArray* pnewArr, uint32 start, uint32 newLen)
  5295. {
  5296. JS_REENTRANCY_LOCK(jsReentLock, pArr->GetScriptContext()->GetThreadContext());
  5297. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  5298. SparseArraySegment<T>* headSeg = SparseArraySegment<T>::From(pArr->head);
  5299. SparseArraySegment<T>* pnewHeadSeg = SparseArraySegment<T>::From(pnewArr->head);
  5300. // Fill the newly created sliced array
  5301. CopyArray(pnewHeadSeg->elements, newLen, headSeg->elements + start, newLen);
  5302. pnewHeadSeg->length = newLen;
  5303. pnewHeadSeg->CheckLengthvsSize();
  5304. Assert(pnewHeadSeg->length <= pnewHeadSeg->size);
  5305. // Prototype lookup for missing elements
  5306. if (!pArr->HasNoMissingValues())
  5307. {
  5308. for (uint32 i = 0; i < newLen; i++)
  5309. {
  5310. if (!(pArr->head->left <= (i + start) && (i + start) < (pArr->head->left + pArr->head->length)))
  5311. {
  5312. break;
  5313. }
  5314. // array type might be changed in the below call to DirectGetItemAtFull
  5315. // need recheck array type before checking array item [i + start]
  5316. if (pArr->IsMissingItem(i + start))
  5317. {
  5318. Var element;
  5319. pnewArr->SetHasNoMissingValues(false);
  5320. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(i + start, &element));
  5321. if (gotItem)
  5322. {
  5323. JS_REENTRANT(jsReentLock, pnewArr->SetItem(i, element, PropertyOperation_None));
  5324. }
  5325. }
  5326. }
  5327. }
  5328. #ifdef DBG
  5329. else
  5330. {
  5331. for (uint32 i = 0; i < newLen; i++)
  5332. {
  5333. AssertMsg(!SparseArraySegment<T>::IsMissingItem(&headSeg->elements[i+start]), "Array marked incorrectly as having missing value");
  5334. }
  5335. }
  5336. #endif
  5337. }
  5338. // If the creating profile data has changed, convert it to the type of array indicated
  5339. // in the profile
  5340. void JavascriptArray::GetArrayTypeAndConvert(bool* isIntArray, bool* isFloatArray)
  5341. {
  5342. JavascriptNativeIntArray* nativeIntArray = JavascriptOperators::TryFromVar<JavascriptNativeIntArray>(this);
  5343. if (nativeIntArray)
  5344. {
  5345. #if ENABLE_PROFILE_INFO
  5346. ArrayCallSiteInfo* info = nativeIntArray->GetArrayCallSiteInfo();
  5347. if(!info || info->IsNativeIntArray())
  5348. {
  5349. *isIntArray = true;
  5350. }
  5351. else if(info->IsNativeFloatArray())
  5352. {
  5353. JavascriptNativeIntArray::ToNativeFloatArray(nativeIntArray);
  5354. *isFloatArray = true;
  5355. }
  5356. else
  5357. {
  5358. JavascriptNativeIntArray::ToVarArray(nativeIntArray);
  5359. }
  5360. #else
  5361. *isIntArray = true;
  5362. #endif
  5363. }
  5364. else
  5365. {
  5366. JavascriptNativeFloatArray* nativeFloatArray = JavascriptOperators::TryFromVar<JavascriptNativeFloatArray>(this);
  5367. if (nativeFloatArray)
  5368. {
  5369. #if ENABLE_PROFILE_INFO
  5370. ArrayCallSiteInfo* info = nativeFloatArray->GetArrayCallSiteInfo();
  5371. if (info && !info->IsNativeArray())
  5372. {
  5373. JavascriptNativeFloatArray::ToVarArray(nativeFloatArray);
  5374. }
  5375. else
  5376. {
  5377. *isFloatArray = true;
  5378. }
  5379. #else
  5380. *isFloatArray = true;
  5381. #endif
  5382. }
  5383. }
  5384. }
  5385. Var JavascriptArray::EntrySlice(RecyclableObject* function, CallInfo callInfo, ...)
  5386. {
  5387. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  5388. ARGUMENTS(args, callInfo);
  5389. ScriptContext* scriptContext = function->GetScriptContext();
  5390. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  5391. Assert(!(callInfo.Flags & CallFlags_New));
  5392. Var res = scriptContext->GetLibrary()->GetUndefined();
  5393. if (args.Info.Count == 0)
  5394. {
  5395. return res;
  5396. }
  5397. BigIndex length;
  5398. JavascriptArray* pArr = nullptr;
  5399. RecyclableObject* obj = nullptr;
  5400. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.slice"), &pArr, &obj, &length));
  5401. if (length.IsSmallIndex())
  5402. {
  5403. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  5404. }
  5405. Assert(pArr == nullptr || length.IsUint32Max());
  5406. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  5407. }
  5408. // Array.prototype.slice as described in ES6.0 (draft 22) Section 22.1.3.22
  5409. template <typename T>
  5410. Var JavascriptArray::SliceHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  5411. {
  5412. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  5413. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  5414. JavascriptArray* newArr = nullptr;
  5415. RecyclableObject* newObj = nullptr;
  5416. bool isIntArray = false;
  5417. bool isFloatArray = false;
  5418. bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
  5419. bool isBuiltinArrayCtor = true;
  5420. T startT = 0;
  5421. T newLenT = length;
  5422. T endT = length;
  5423. #if ENABLE_COPYONACCESS_ARRAY
  5424. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pArr);
  5425. #endif
  5426. if (args.Info.Count > 1)
  5427. {
  5428. JS_REENTRANT(jsReentLock, startT = GetFromIndex(args[1], length, scriptContext));
  5429. if (args.Info.Count > 2 && JavascriptOperators::GetTypeId(args[2]) != TypeIds_Undefined)
  5430. {
  5431. JS_REENTRANT(jsReentLock, endT = GetFromIndex(args[2], length, scriptContext));
  5432. }
  5433. newLenT = endT > startT ? endT - startT : 0;
  5434. }
  5435. // Side effects (such as defining a property in a ToPrimitive call) during evaluation of arguments start or end may convert the array to an ES5 array.
  5436. if (pArr && !JavascriptArray::Is(obj))
  5437. {
  5438. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  5439. pArr = nullptr;
  5440. }
  5441. if (TypedArrayBase::IsDetachedTypedArray(obj))
  5442. {
  5443. JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("Array.prototype.slice"));
  5444. }
  5445. // If we came from Array.prototype.slice and source object is not a JavascriptArray, source could be a TypedArray
  5446. if (!isTypedArrayEntryPoint && pArr == nullptr && TypedArrayBase::Is(obj))
  5447. {
  5448. typedArrayBase = TypedArrayBase::UnsafeFromVar(obj);
  5449. }
  5450. // If the entry point is %TypedArray%.prototype.slice or the source object is an Array exotic object we should try to load the constructor property
  5451. // and use it to construct the return object.
  5452. if (isTypedArrayEntryPoint)
  5453. {
  5454. JS_REENTRANT(jsReentLock,
  5455. RecyclableObject* constructor = JavascriptOperators::SpeciesConstructor(typedArrayBase, TypedArrayBase::GetDefaultConstructor(args[0], scriptContext), scriptContext));
  5456. isBuiltinArrayCtor = false;
  5457. AssertAndFailFast(pArr == nullptr);
  5458. Assert(JavascriptOperators::IsConstructor(constructor));
  5459. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(newLenT, scriptContext) };
  5460. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  5461. JS_REENTRANT(jsReentLock, newObj = RecyclableObject::FromVar(TypedArrayBase::TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), (uint32)newLenT, scriptContext)));
  5462. }
  5463. else if (pArr != nullptr)
  5464. {
  5465. JS_REENTRANT_NO_MUTATE(jsReentLock, newObj = ArraySpeciesCreate(pArr, newLenT, scriptContext, &isIntArray, &isFloatArray, &isBuiltinArrayCtor));
  5466. }
  5467. // skip the typed array and "pure" array case, we still need to handle special arrays like es5array, remote array, and proxy of array.
  5468. else
  5469. {
  5470. JS_REENTRANT_NO_MUTATE(jsReentLock, newObj = ArraySpeciesCreate(obj, newLenT, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor));
  5471. }
  5472. // If we didn't create a new object above we will create a new array here.
  5473. // This is the pre-ES6 behavior or the case of calling Array.prototype.slice with a constructor argument that is not a constructor function.
  5474. if (newObj == nullptr)
  5475. {
  5476. if (pArr)
  5477. {
  5478. pArr->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
  5479. }
  5480. if (newLenT > JavascriptArray::MaxArrayLength)
  5481. {
  5482. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  5483. }
  5484. newArr = CreateNewArrayHelper(static_cast<uint32>(newLenT), isIntArray, isFloatArray, pArr, scriptContext);
  5485. #if ENABLE_COPYONACCESS_ARRAY
  5486. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  5487. #endif
  5488. newObj = newArr;
  5489. SET_SECOND_OBJECT_FOR_MUTATION(jsReentLock, newArr);
  5490. }
  5491. else
  5492. {
  5493. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  5494. newArr = JavascriptOperators::TryFromVar<JavascriptArray>(newObj);
  5495. if (newArr)
  5496. {
  5497. #if ENABLE_COPYONACCESS_ARRAY
  5498. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  5499. #endif
  5500. }
  5501. }
  5502. uint32 start = (uint32) startT;
  5503. uint32 newLen = (uint32) newLenT;
  5504. // We at least have to have newObj as a valid object
  5505. Assert(newObj);
  5506. // Bail out early if the new object will have zero length.
  5507. if (newLen == 0)
  5508. {
  5509. return newObj;
  5510. }
  5511. // The ArraySpeciesCreate call above could have converted the source array into an ES5Array. If this happens
  5512. // we will process the array elements like an ES5Array.
  5513. if (pArr && !JavascriptArray::Is(obj))
  5514. {
  5515. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  5516. pArr = nullptr;
  5517. }
  5518. if (pArr)
  5519. {
  5520. if (HasAnyES5ArrayInPrototypeChain(pArr))
  5521. {
  5522. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceObjectHelper(obj, start, 0u, newArr, newObj, newLen, scriptContext));
  5523. }
  5524. // If we constructed a new Array object, we have some nice helpers here
  5525. if (newArr && isBuiltinArrayCtor)
  5526. {
  5527. if (JavascriptArray::IsDirectAccessArray(newArr))
  5528. {
  5529. if (((start + newLen) <= pArr->head->length) && newLen <= newArr->head->size) //Fast Path
  5530. {
  5531. if (isIntArray)
  5532. {
  5533. JS_REENTRANT(jsReentLock, SliceHelper<int32>(pArr, newArr, start, newLen));
  5534. }
  5535. else if (isFloatArray)
  5536. {
  5537. JS_REENTRANT(jsReentLock, SliceHelper<double>(pArr, newArr, start, newLen));
  5538. }
  5539. else
  5540. {
  5541. JS_REENTRANT(jsReentLock, SliceHelper<Var>(pArr, newArr, start, newLen));
  5542. }
  5543. }
  5544. else
  5545. {
  5546. if (isIntArray)
  5547. {
  5548. JS_REENTRANT(jsReentLock, CopyNativeIntArrayElements(JavascriptNativeIntArray::FromVar(newArr), 0, JavascriptNativeIntArray::FromVar(pArr), start, start + newLen));
  5549. }
  5550. else if (isFloatArray)
  5551. {
  5552. JS_REENTRANT(jsReentLock, CopyNativeFloatArrayElements(JavascriptNativeFloatArray::FromVar(newArr), 0, JavascriptNativeFloatArray::FromVar(pArr), start, start + newLen));
  5553. }
  5554. else
  5555. {
  5556. JS_REENTRANT(jsReentLock, CopyArrayElements(newArr, 0u, pArr, start, start + newLen));
  5557. }
  5558. }
  5559. }
  5560. else
  5561. {
  5562. AssertMsg(CONFIG_FLAG(ForceES5Array), "newArr can only be ES5Array when it is forced");
  5563. Var element;
  5564. for (uint32 i = 0; i < newLen; i++)
  5565. {
  5566. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(i + start, &element));
  5567. if (!gotItem)
  5568. {
  5569. continue;
  5570. }
  5571. newArr->SetItem(i, element, PropertyOperation_None);
  5572. // Side-effects in the prototype lookup may have changed the source array into an ES5Array. If this happens
  5573. // we will process the rest of the array elements like an ES5Array.
  5574. if (!JavascriptArray::Is(obj))
  5575. {
  5576. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  5577. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceObjectHelper(obj, start, i + 1, newArr, newObj, newLen, scriptContext));
  5578. }
  5579. }
  5580. }
  5581. }
  5582. else
  5583. {
  5584. // The constructed object isn't an array, we'll need to use normal object manipulation
  5585. Var element;
  5586. for (uint32 i = 0; i < newLen; i++)
  5587. {
  5588. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(i + start, &element));
  5589. if (!gotItem)
  5590. {
  5591. continue;
  5592. }
  5593. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i));
  5594. // Side-effects in the prototype lookup may have changed the source array into an ES5Array. If this happens
  5595. // we will process the rest of the array elements like an ES5Array.
  5596. if (!JavascriptArray::Is(obj))
  5597. {
  5598. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  5599. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceObjectHelper(obj, start, i + 1, newArr, newObj, newLen, scriptContext));
  5600. }
  5601. }
  5602. }
  5603. }
  5604. else if (typedArrayBase)
  5605. {
  5606. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  5607. // Source is a TypedArray, we must have created the return object via a call to constructor, but newObj may not be a TypedArray (or an array either)
  5608. TypedArrayBase* newTypedArray = JavascriptOperators::TryFromVar<Js::TypedArrayBase>(newObj);
  5609. if (!newTypedArray)
  5610. {
  5611. AssertAndFailFast(newArr != nullptr);
  5612. }
  5613. Var element;
  5614. for (uint32 i = 0; i < newLen; i++)
  5615. {
  5616. // We only need to call HasItem in the case that we are called from Array.prototype.slice
  5617. if (!isTypedArrayEntryPoint && !typedArrayBase->HasItem(i + start))
  5618. {
  5619. continue;
  5620. }
  5621. element = typedArrayBase->DirectGetItem(i + start);
  5622. // The object we got back from the constructor might not be a TypedArray. In fact, it could be any object.
  5623. if (newTypedArray)
  5624. {
  5625. JS_REENTRANT(jsReentLock, newTypedArray->DirectSetItem(i, element));
  5626. }
  5627. else
  5628. {
  5629. newArr->SetItem(i, element, PropertyOperation_None);
  5630. }
  5631. }
  5632. }
  5633. else
  5634. {
  5635. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceObjectHelper(obj, start, 0u, newArr, newObj, newLen, scriptContext));;
  5636. }
  5637. if (!isTypedArrayEntryPoint)
  5638. {
  5639. JS_REENTRANT(jsReentLock, JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(newLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  5640. }
  5641. #ifdef VALIDATE_ARRAY
  5642. JavascriptArray * jsArr = JavascriptOperators::TryFromVar<JavascriptArray>(newObj);
  5643. if (jsArr)
  5644. {
  5645. jsArr->ValidateArray();
  5646. }
  5647. #endif
  5648. return newObj;
  5649. }
  5650. Var JavascriptArray::SliceObjectHelper(RecyclableObject* obj, uint32 sliceStart, uint32 start, JavascriptArray* newArr, RecyclableObject* newObj, uint32 newLen, ScriptContext* scriptContext)
  5651. {
  5652. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  5653. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  5654. for (uint32 i = start; i < newLen; i++)
  5655. {
  5656. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, i + sliceStart));
  5657. if (hasItem)
  5658. {
  5659. JS_REENTRANT(jsReentLock, Var element = JavascriptOperators::GetItem(obj, i + sliceStart, scriptContext));
  5660. if (newArr != nullptr)
  5661. {
  5662. newArr->SetItem(i, element, PropertyOperation_None);
  5663. }
  5664. else
  5665. {
  5666. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i));
  5667. }
  5668. }
  5669. }
  5670. JS_REENTRANT(jsReentLock,
  5671. JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(newLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  5672. #ifdef VALIDATE_ARRAY
  5673. JavascriptArray * jsArr = JavascriptOperators::TryFromVar<JavascriptArray>(newObj);
  5674. if (jsArr)
  5675. {
  5676. jsArr->ValidateArray();
  5677. }
  5678. #endif
  5679. return newObj;
  5680. }
  5681. struct CompareVarsInfo
  5682. {
  5683. ScriptContext* scriptContext;
  5684. RecyclableObject* compFn;
  5685. };
  5686. int __cdecl compareVars(void* cvInfoV, const void* aRef, const void* bRef)
  5687. {
  5688. CompareVarsInfo* cvInfo=(CompareVarsInfo*)cvInfoV;
  5689. ScriptContext* requestContext=cvInfo->scriptContext;
  5690. RecyclableObject* compFn=cvInfo->compFn;
  5691. AssertMsg(*(Var*)aRef, "No null expected in sort");
  5692. AssertMsg(*(Var*)bRef, "No null expected in sort");
  5693. if (compFn != nullptr)
  5694. {
  5695. ScriptContext* scriptContext = compFn->GetScriptContext();
  5696. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  5697. CallFlags flags = CallFlags_Value;
  5698. Var undefined = scriptContext->GetLibrary()->GetUndefined();
  5699. Var retVal;
  5700. if (requestContext != scriptContext)
  5701. {
  5702. Var leftVar = CrossSite::MarshalVar(scriptContext, *(Var*)aRef);
  5703. Var rightVar = CrossSite::MarshalVar(scriptContext, *(Var*)bRef);
  5704. retVal = CALL_FUNCTION(scriptContext->GetThreadContext(), compFn, CallInfo(flags, 3), undefined, leftVar, rightVar);
  5705. }
  5706. else
  5707. {
  5708. retVal = CALL_FUNCTION(scriptContext->GetThreadContext(), compFn, CallInfo(flags, 3), undefined, *(Var*)aRef, *(Var*)bRef);
  5709. }
  5710. if (TaggedInt::Is(retVal))
  5711. {
  5712. return TaggedInt::ToInt32(retVal);
  5713. }
  5714. double dblResult;
  5715. if (JavascriptNumber::Is_NoTaggedIntCheck(retVal))
  5716. {
  5717. dblResult = JavascriptNumber::GetValue(retVal);
  5718. }
  5719. else
  5720. {
  5721. dblResult = JavascriptConversion::ToNumber_Full(retVal, scriptContext);
  5722. }
  5723. if (dblResult < 0)
  5724. {
  5725. return -1;
  5726. }
  5727. return (dblResult > 0) ? 1 : 0;
  5728. }
  5729. else
  5730. {
  5731. JavascriptString* pStr1 = JavascriptConversion::ToString(*(Var*)aRef, requestContext);
  5732. JavascriptString* pStr2 = JavascriptConversion::ToString(*(Var*)bRef, requestContext);
  5733. return JavascriptString::strcmp(pStr1, pStr2);
  5734. }
  5735. }
  5736. static void hybridSort(__inout_ecount(length) Field(Var) *elements, uint32 length, CompareVarsInfo* compareInfo)
  5737. {
  5738. // The cost of memory moves starts to be more expensive than additional comparer calls (given a simple comparer)
  5739. // for arrays of more than 512 elements.
  5740. if (length > 512)
  5741. {
  5742. qsort_s(elements, length, compareVars, compareInfo);
  5743. return;
  5744. }
  5745. for (int i = 1; i < (int)length; i++)
  5746. {
  5747. if (compareVars(compareInfo, elements + i, elements + i - 1) < 0) {
  5748. // binary search for the left-most element greater than value:
  5749. int first = 0;
  5750. int last = i - 1;
  5751. while (first <= last)
  5752. {
  5753. int middle = (first + last) / 2;
  5754. if (compareVars(compareInfo, elements + i, elements + middle) < 0)
  5755. {
  5756. last = middle - 1;
  5757. }
  5758. else
  5759. {
  5760. first = middle + 1;
  5761. }
  5762. }
  5763. // insert value right before first:
  5764. Var value = elements[i];
  5765. MoveArray(elements + first + 1, elements + first, (i - first));
  5766. elements[first] = value;
  5767. }
  5768. }
  5769. }
  5770. void JavascriptArray::Sort(RecyclableObject* compFn)
  5771. {
  5772. JS_REENTRANCY_LOCK(jsReentLock, this->GetScriptContext()->GetThreadContext());
  5773. if (length <= 1)
  5774. {
  5775. return;
  5776. }
  5777. SETOBJECT_FOR_MUTATION(jsReentLock, this);
  5778. this->EnsureHead<Var>();
  5779. ScriptContext* scriptContext = this->GetScriptContext();
  5780. Recycler* recycler = scriptContext->GetRecycler();
  5781. CompareVarsInfo cvInfo;
  5782. cvInfo.scriptContext = scriptContext;
  5783. cvInfo.compFn = compFn;
  5784. Assert(head != nullptr);
  5785. // Just dump the segment map on sort
  5786. ClearSegmentMap();
  5787. uint32 countUndefined = 0;
  5788. SparseArraySegment<Var>* startSeg = SparseArraySegment<Var>::From(head);
  5789. // Sort may have side effects on the array. Setting a dummy head so that original array is not affected
  5790. uint32 saveLength = length;
  5791. // that if compare function tries to modify the array it won't AV.
  5792. head = const_cast<SparseArraySegmentBase*>(EmptySegment);
  5793. SetFlags(DynamicObjectFlags::None);
  5794. this->InvalidateLastUsedSegment();
  5795. length = 0;
  5796. TryFinally([&]()
  5797. {
  5798. //The array is a continuous array if there is only one segment
  5799. if (startSeg->next == nullptr
  5800. // If this flag is specified, we want to improve the consistency of our array sorts
  5801. // by removing missing values from all kinds of arrays before sorting (done here by
  5802. // using the copy-to-one-segment path for array sorts) and by using a stronger sort
  5803. // comparer than the spec requires (done in CompareElements).
  5804. && !CONFIG_FLAG(StrongArraySort)
  5805. ) // Single segment fast path
  5806. {
  5807. if (compFn != nullptr)
  5808. {
  5809. countUndefined = startSeg->RemoveUndefined(scriptContext);
  5810. #ifdef VALIDATE_ARRAY
  5811. ValidateSegment(startSeg);
  5812. #endif
  5813. JS_REENTRANT(jsReentLock, hybridSort(startSeg->elements, startSeg->length, &cvInfo));
  5814. startSeg->CheckLengthvsSize();
  5815. }
  5816. else
  5817. {
  5818. JS_REENTRANT(jsReentLock, countUndefined = sort(startSeg->elements, &startSeg->length, scriptContext));
  5819. }
  5820. head = startSeg;
  5821. }
  5822. else
  5823. {
  5824. SparseArraySegment<Var>* allElements = SparseArraySegment<Var>::AllocateSegment(recycler, 0, 0, nullptr);
  5825. SparseArraySegment<Var>* next = startSeg;
  5826. uint32 nextIndex = 0;
  5827. // copy all the elements to single segment
  5828. while (next)
  5829. {
  5830. countUndefined += next->RemoveUndefined(scriptContext);
  5831. if (next->length != 0)
  5832. {
  5833. allElements = SparseArraySegment<Var>::CopySegment(recycler, allElements, nextIndex, next, next->left, next->length);
  5834. }
  5835. next = SparseArraySegment<Var>::From(next->next);
  5836. nextIndex = allElements->length;
  5837. #ifdef VALIDATE_ARRAY
  5838. ValidateSegment(allElements);
  5839. #endif
  5840. }
  5841. if (compFn != nullptr)
  5842. {
  5843. JS_REENTRANT(jsReentLock, hybridSort(allElements->elements, allElements->length, &cvInfo));
  5844. }
  5845. else
  5846. {
  5847. JS_REENTRANT(jsReentLock, sort(allElements->elements, &allElements->length, scriptContext));
  5848. allElements->CheckLengthvsSize();
  5849. }
  5850. head = allElements;
  5851. head->next = nullptr;
  5852. }
  5853. },
  5854. [&](bool hasException)
  5855. {
  5856. length = saveLength;
  5857. ClearSegmentMap(); // Dump the segmentMap again in case user compare function rebuilds it
  5858. if (hasException)
  5859. {
  5860. head = startSeg;
  5861. this->InvalidateLastUsedSegment();
  5862. }
  5863. });
  5864. #if DEBUG
  5865. {
  5866. uint32 countNull = 0;
  5867. uint32 index = head->length - 1;
  5868. while (countNull < head->length)
  5869. {
  5870. if (SparseArraySegment<Var>::From(head)->elements[index] != NULL)
  5871. {
  5872. break;
  5873. }
  5874. index--;
  5875. countNull++;
  5876. }
  5877. AssertMsg(countNull == 0, "No null expected at the end");
  5878. }
  5879. #endif
  5880. if (countUndefined != 0)
  5881. {
  5882. // fill undefined at the end
  5883. uint32 newLength = head->length + countUndefined;
  5884. if (newLength > head->size)
  5885. {
  5886. SparseArraySegmentBase *oldHead = head;
  5887. bool isInlineSegment = JavascriptArray::IsInlineSegment(head, this);
  5888. head = SparseArraySegment<Var>::From(head)->GrowByMin(recycler, newLength - head->size);
  5889. if (isInlineSegment)
  5890. {
  5891. this->ClearElements(oldHead, 0);
  5892. }
  5893. }
  5894. Var undefined = scriptContext->GetLibrary()->GetUndefined();
  5895. for (uint32 i = head->length; i < newLength; i++)
  5896. {
  5897. SparseArraySegment<Var>::From(head)->elements[i] = undefined;
  5898. }
  5899. head->length = newLength;
  5900. head->CheckLengthvsSize();
  5901. }
  5902. SetHasNoMissingValues();
  5903. this->InvalidateLastUsedSegment();
  5904. #ifdef VALIDATE_ARRAY
  5905. ValidateArray();
  5906. #endif
  5907. return;
  5908. }
  5909. uint32 JavascriptArray::sort(__inout_ecount(*len) Field(Var) *orig, uint32 *len, ScriptContext *scriptContext)
  5910. {
  5911. uint32 count = 0, countUndefined = 0;
  5912. Element *elements = RecyclerNewArrayZ(scriptContext->GetRecycler(), Element, *len);
  5913. RecyclableObject *undefined = scriptContext->GetLibrary()->GetUndefined();
  5914. //
  5915. // Create the Elements array
  5916. //
  5917. for (uint32 i = 0; i < *len; ++i)
  5918. {
  5919. if (!SparseArraySegment<Var>::IsMissingItem(&orig[i]))
  5920. {
  5921. if (!JavascriptOperators::IsUndefinedObject(orig[i], undefined))
  5922. {
  5923. elements[count].Value = orig[i];
  5924. elements[count].StringValue = JavascriptConversion::ToString(orig[i], scriptContext);
  5925. count++;
  5926. }
  5927. else
  5928. {
  5929. countUndefined++;
  5930. }
  5931. }
  5932. }
  5933. if (count > 0)
  5934. {
  5935. SortElements(elements, 0, count - 1);
  5936. for (uint32 i = 0; i < count; ++i)
  5937. {
  5938. orig[i] = elements[i].Value;
  5939. }
  5940. }
  5941. for (uint32 i = count + countUndefined; i < *len; ++i)
  5942. {
  5943. orig[i] = SparseArraySegment<Var>::GetMissingItem();
  5944. }
  5945. *len = count; // set the correct length
  5946. return countUndefined;
  5947. }
  5948. int __cdecl JavascriptArray::CompareElements(void* context, const void* elem1, const void* elem2)
  5949. {
  5950. const Element* element1 = static_cast<const Element*>(elem1);
  5951. const Element* element2 = static_cast<const Element*>(elem2);
  5952. Assert(element1 != NULL);
  5953. Assert(element2 != NULL);
  5954. if (!CONFIG_FLAG(StrongArraySort))
  5955. {
  5956. return JavascriptString::strcmp(element1->StringValue, element2->StringValue);
  5957. }
  5958. else
  5959. {
  5960. int str_cmp = JavascriptString::strcmp(element1->StringValue, element2->StringValue);
  5961. if (str_cmp != 0)
  5962. {
  5963. return str_cmp;
  5964. }
  5965. // If they are equal, we get to a slightly more complex problem. We want to make a very
  5966. // predictable sort here, regardless of the structure of the array. To achieve this, we
  5967. // need to get an order for every pair of non-identical elements, else there will be an
  5968. // identifiable difference between sparse and dense array sorts in some cases.
  5969. // Handle a common set of equivalent nodes first for speed/convenience
  5970. if (element1->Value == element2->Value)
  5971. {
  5972. return 0;
  5973. }
  5974. // Easy way to do most remaining cases is to just compare the type ids if they differ.
  5975. if (JavascriptOperators::GetTypeId(element1->Value) != JavascriptOperators::GetTypeId(element2->Value))
  5976. {
  5977. return JavascriptOperators::GetTypeId(element1->Value) - JavascriptOperators::GetTypeId(element2->Value);
  5978. }
  5979. // Further comparisons are possible, but get increasingly complex, and aren't necessary
  5980. // for the cases on hand.
  5981. return 0;
  5982. }
  5983. }
  5984. void JavascriptArray::SortElements(Element* elements, uint32 left, uint32 right)
  5985. {
  5986. // Note: use write barrier policy of Field(Var)
  5987. qsort_s<Element, Field(Var)>(elements, right - left + 1, CompareElements, this);
  5988. }
  5989. Var JavascriptArray::EntrySort(RecyclableObject* function, CallInfo callInfo, ...)
  5990. {
  5991. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  5992. ARGUMENTS(args, callInfo);
  5993. ScriptContext* scriptContext = function->GetScriptContext();
  5994. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  5995. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.sort"));
  5996. Assert(!(callInfo.Flags & CallFlags_New));
  5997. AssertMsg(args.Info.Count >= 1, "Should have at least one argument");
  5998. RecyclableObject* compFn = NULL;
  5999. if (args.Info.Count > 1)
  6000. {
  6001. if (JavascriptConversion::IsCallable(args[1]))
  6002. {
  6003. compFn = RecyclableObject::FromVar(args[1]);
  6004. }
  6005. else
  6006. {
  6007. TypeId typeId = JavascriptOperators::GetTypeId(args[1]);
  6008. // Use default comparer:
  6009. // - In ES5 mode if the argument is undefined.
  6010. bool useDefaultComparer = typeId == TypeIds_Undefined;
  6011. if (!useDefaultComparer)
  6012. {
  6013. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.sort"));
  6014. }
  6015. }
  6016. }
  6017. SETOBJECT_FOR_MUTATION(jsReentLock, args[0]);
  6018. bool useNoSideEffectSort = JavascriptArray::Is(args[0])
  6019. && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject()
  6020. && !HasAnyES5ArrayInPrototypeChain(JavascriptArray::UnsafeFromVar(args[0]));
  6021. if (useNoSideEffectSort)
  6022. {
  6023. JavascriptArray *arr = JavascriptArray::UnsafeFromVar(args[0]);
  6024. if (arr->length <= 1)
  6025. {
  6026. return args[0];
  6027. }
  6028. uint32 length = arr->length;
  6029. if(arr->IsFillFromPrototypes())
  6030. {
  6031. arr->FillFromPrototypes(0, arr->length); // We need find all missing value from [[proto]] object
  6032. }
  6033. // As we have already established that the FillFromPrototype should not change the bound of the array.
  6034. if (length != arr->length)
  6035. {
  6036. Js::Throw::FatalInternalError();
  6037. }
  6038. EnsureNonNativeArray(arr);
  6039. JS_REENTRANT(jsReentLock, arr->Sort(compFn));
  6040. }
  6041. else
  6042. {
  6043. RecyclableObject* pObj = nullptr;
  6044. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &pObj))
  6045. {
  6046. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.sort"));
  6047. }
  6048. JS_REENTRANT(jsReentLock,
  6049. uint32 len = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(pObj, scriptContext), scriptContext));
  6050. JavascriptArray* sortArray = scriptContext->GetLibrary()->CreateArray(len);
  6051. sortArray->EnsureHead<Var>();
  6052. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.sort"));
  6053. BEGIN_TEMP_ALLOCATOR(tempAlloc, scriptContext, _u("Runtime"))
  6054. {
  6055. JsUtil::List<uint32, ArenaAllocator>* indexList = JsUtil::List<uint32, ArenaAllocator>::New(tempAlloc);
  6056. for (uint32 i = 0; i < len; i++)
  6057. {
  6058. Var item;
  6059. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(pObj, i, &item, scriptContext));
  6060. if (gotItem)
  6061. {
  6062. indexList->Add(i);
  6063. sortArray->DirectSetItemAt(i, item);
  6064. }
  6065. }
  6066. if (indexList->Count() > 0)
  6067. {
  6068. if (sortArray->length > 1)
  6069. {
  6070. JS_REENTRANT(jsReentLock, sortArray->FillFromPrototypes(0, sortArray->length)); // We need find all missing value from [[proto]] object
  6071. }
  6072. JS_REENTRANT(jsReentLock, sortArray->Sort(compFn));
  6073. uint32 removeIndex = sortArray->head->length;
  6074. for (uint32 i = 0; i < removeIndex; i++)
  6075. {
  6076. AssertMsg(!SparseArraySegment<Var>::IsMissingItem(&SparseArraySegment<Var>::From(sortArray->head)->elements[i]), "No gaps expected in sorted array");
  6077. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(pObj, pObj, i, SparseArraySegment<Var>::From(sortArray->head)->elements[i], scriptContext)));
  6078. }
  6079. for (int i = 0; i < indexList->Count(); i++)
  6080. {
  6081. uint32 value = indexList->Item(i);
  6082. if (value >= removeIndex)
  6083. {
  6084. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure((JavascriptOperators::DeleteItem(pObj, value))));
  6085. }
  6086. }
  6087. }
  6088. }
  6089. END_TEMP_ALLOCATOR(tempAlloc, scriptContext);
  6090. }
  6091. return args[0];
  6092. }
  6093. Var JavascriptArray::EntrySplice(RecyclableObject* function, CallInfo callInfo, ...)
  6094. {
  6095. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  6096. ARGUMENTS(args, callInfo);
  6097. ScriptContext* scriptContext = function->GetScriptContext();
  6098. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6099. Assert(!(callInfo.Flags & CallFlags_New));
  6100. AssertMsg(args.Info.Count >= 1, "Should have at least one argument");
  6101. JavascriptArray* pArr = 0;
  6102. RecyclableObject* pObj = 0;
  6103. uint64 start = 0u;
  6104. uint64 deleteLen = 0u;
  6105. uint64 length = 0u;
  6106. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.splice"), &pArr, &pObj, &length));
  6107. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  6108. switch (args.Info.Count)
  6109. {
  6110. case 1:
  6111. start = length;
  6112. deleteLen = 0u;
  6113. break;
  6114. case 2:
  6115. JS_REENTRANT(jsReentLock, start = GetFromIndex(args[1], length, scriptContext));
  6116. deleteLen = length - start;
  6117. break;
  6118. default:
  6119. JS_REENTRANT(jsReentLock, start = GetFromIndex(args[1], length, scriptContext),
  6120. deleteLen = GetFromIndex(args[2], (length - start), scriptContext, false));
  6121. break;
  6122. }
  6123. // Side effects (such as defining a property in a ToPrimitive call) during evaluation of arguments start or deleteCount may convert the array to an ES5 array.
  6124. if (pArr && !JavascriptArray::Is(pObj))
  6125. {
  6126. AssertOrFailFastMsg(ES5Array::Is(pObj), "The array should have been converted to an ES5Array");
  6127. pArr = nullptr;
  6128. }
  6129. Var* insertArgs = args.Info.Count > 3 ? &args.Values[3] : nullptr;
  6130. uint32 insertLen = args.Info.Count > 3 ? args.Info.Count - 3 : 0;
  6131. // Force check the prototype as we may insert values more than current elements
  6132. if (pArr != nullptr && !HasAnyES5ArrayInPrototypeChain(pArr, true /*forceCheckProtoChain*/))
  6133. {
  6134. // Since we get the length from an array and that cannot be more than uint32.
  6135. _Analysis_assume_(length <= UINT_MAX);
  6136. JS_REENTRANT_UNLOCK(jsReentLock,
  6137. return TryArraySplice(pArr, (uint32)start, (uint32)length, (uint32)deleteLen, insertArgs, insertLen, scriptContext));
  6138. }
  6139. uint64 newLen = (length - deleteLen) + insertLen;
  6140. if (newLen > UINT_MAX || length > UINT_MAX || (length + insertLen) > UINT_MAX)
  6141. {
  6142. JS_REENTRANT_UNLOCK(jsReentLock,
  6143. return ObjectSpliceHelper<uint64>(pObj, length, start, deleteLen, (Var*)insertArgs, insertLen, scriptContext, nullptr));
  6144. }
  6145. else
  6146. {
  6147. JS_REENTRANT_UNLOCK(jsReentLock,
  6148. return ObjectSpliceHelper<uint32>(pObj, (uint32)length, (uint32)start, (uint32)deleteLen, (Var*)insertArgs, insertLen, scriptContext, nullptr));
  6149. }
  6150. }
  6151. inline BOOL JavascriptArray::IsSingleSegmentArray() const
  6152. {
  6153. return nullptr == head->next;
  6154. }
  6155. template<typename T>
  6156. void JavascriptArray::ArraySegmentSpliceHelper(
  6157. JavascriptArray *pnewArr, SparseArraySegment<T> *seg, Field(SparseArraySegment<T>*) *prev,
  6158. uint32 start, uint32 deleteLen, Var* insertArgs, uint32 insertLen, Recycler *recycler)
  6159. {
  6160. // book keeping variables
  6161. uint32 relativeStart = start - seg->left; // This will be different from start when head->left is non zero -
  6162. //(Missing elements at the beginning)
  6163. uint32 headDeleteLen = min(start + deleteLen , seg->left + seg->length) - start; // actual number of elements to delete in
  6164. // head if deleteLen overflows the length of head
  6165. uint32 newHeadLen = seg->length - headDeleteLen + insertLen; // new length of the head after splice
  6166. // Save the deleted elements
  6167. if (headDeleteLen != 0)
  6168. {
  6169. SparseArraySegmentBase *oldHead = pnewArr->head;
  6170. bool isInlineSegment = JavascriptArray::IsInlineSegment(oldHead, pnewArr);
  6171. pnewArr->InvalidateLastUsedSegment();
  6172. pnewArr->head = SparseArraySegment<T>::CopySegment(recycler, SparseArraySegment<T>::From(pnewArr->head), 0, seg, start, headDeleteLen);
  6173. if (isInlineSegment && oldHead != pnewArr->head)
  6174. {
  6175. pnewArr->ClearElements(oldHead, 0);
  6176. }
  6177. }
  6178. if (newHeadLen != 0)
  6179. {
  6180. if (seg->size < newHeadLen)
  6181. {
  6182. if (seg->next)
  6183. {
  6184. // If we have "next", require that we haven't adjusted next segments left yet.
  6185. seg = seg->GrowByMinMax(recycler, newHeadLen - seg->size, seg->next->left - deleteLen + insertLen - seg->left - seg->size);
  6186. }
  6187. else
  6188. {
  6189. seg = seg->GrowByMin(recycler, newHeadLen - seg->size);
  6190. }
  6191. #ifdef VALIDATE_ARRAY
  6192. ValidateSegment(seg);
  6193. #endif
  6194. }
  6195. // Move the elements if necessary
  6196. if (headDeleteLen != insertLen)
  6197. {
  6198. uint32 noElementsToMove = seg->length - (relativeStart + headDeleteLen);
  6199. MoveArray(seg->elements + relativeStart + insertLen,
  6200. seg->elements + relativeStart + headDeleteLen,
  6201. noElementsToMove);
  6202. if (newHeadLen < seg->length) // truncate if necessary
  6203. {
  6204. seg->Truncate(seg->left + newHeadLen); // set end elements to null so that when we introduce null elements we are safe
  6205. }
  6206. seg->length = newHeadLen;
  6207. seg->CheckLengthvsSize();
  6208. }
  6209. // Copy the new elements
  6210. if (insertLen > 0)
  6211. {
  6212. Assert(!VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(pnewArr) &&
  6213. !VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(pnewArr));
  6214. // inserted elements starts at argument 3 of splice(start, deleteNumber, insertelem1, insertelem2, insertelem3, ...);
  6215. CopyArray(seg->elements + relativeStart, insertLen,
  6216. reinterpret_cast<const T*>(insertArgs), insertLen);
  6217. }
  6218. *prev = seg;
  6219. }
  6220. else
  6221. {
  6222. *prev = SparseArraySegment<T>::From(seg->next);
  6223. }
  6224. }
  6225. template<typename T>
  6226. void JavascriptArray::ArraySpliceHelper(JavascriptArray* pnewArr, JavascriptArray* pArr, uint32 start, uint32 deleteLen, Var* insertArgs, uint32 insertLen, ScriptContext *scriptContext)
  6227. {
  6228. // Skip pnewArr->EnsureHead(): we don't use existing segment at all.
  6229. Recycler *recycler = scriptContext->GetRecycler();
  6230. Field(SparseArraySegmentBase*)* prevSeg = &pArr->head; // holds the next pointer of previous
  6231. Field(SparseArraySegmentBase*)* prevPrevSeg = &pArr->head; // this holds the previous pointer to prevSeg dirty trick.
  6232. SparseArraySegmentBase* savePrev = nullptr;
  6233. Assert(pArr->head); // We should never have a null head.
  6234. pArr->EnsureHead<T>();
  6235. SparseArraySegment<T>* startSeg = SparseArraySegment<T>::From(pArr->head);
  6236. const uint32 limit = start + deleteLen;
  6237. uint32 rightLimit;
  6238. if (UInt32Math::Add(startSeg->left, startSeg->size, &rightLimit))
  6239. {
  6240. rightLimit = JavascriptArray::MaxArrayLength;
  6241. }
  6242. // Find out the segment to start delete
  6243. while (startSeg && (rightLimit <= start))
  6244. {
  6245. savePrev = startSeg;
  6246. prevPrevSeg = prevSeg;
  6247. prevSeg = &startSeg->next;
  6248. startSeg = SparseArraySegment<T>::From(startSeg->next);
  6249. if (startSeg)
  6250. {
  6251. if (UInt32Math::Add(startSeg->left, startSeg->size, &rightLimit))
  6252. {
  6253. rightLimit = JavascriptArray::MaxArrayLength;
  6254. }
  6255. }
  6256. }
  6257. bool hasInlineSegment = JavascriptArray::IsInlineSegment(startSeg, pArr);
  6258. if (startSeg)
  6259. {
  6260. // Delete Phase
  6261. if (startSeg->left <= start && (startSeg->left + startSeg->length) >= limit)
  6262. {
  6263. // All splice happens in one segment.
  6264. SparseArraySegmentBase *nextSeg = startSeg->next;
  6265. // Splice the segment first, which might OOM throw but the array would be intact.
  6266. JavascriptArray::ArraySegmentSpliceHelper(
  6267. pnewArr, startSeg, SparseArraySegment<T>::AddressFrom(prevSeg),
  6268. start, deleteLen, insertArgs, insertLen, recycler);
  6269. while (nextSeg)
  6270. {
  6271. // adjust next segments left
  6272. nextSeg->left = nextSeg->left - deleteLen + insertLen;
  6273. if (nextSeg->next == nullptr)
  6274. {
  6275. nextSeg->EnsureSizeInBound();
  6276. }
  6277. nextSeg = nextSeg->next;
  6278. }
  6279. if (*prevSeg)
  6280. {
  6281. (*prevSeg)->EnsureSizeInBound();
  6282. }
  6283. return;
  6284. }
  6285. else
  6286. {
  6287. SparseArraySegment<T>* newHeadSeg = nullptr; // pnewArr->head is null
  6288. Field(SparseArraySegmentBase*)* prevNewHeadSeg = &pnewArr->head;
  6289. // delete till deleteLen and reuse segments for new array if it is possible.
  6290. // 3 steps -
  6291. //1. delete 1st segment (which may be partial delete)
  6292. // 2. delete next n complete segments
  6293. // 3. delete last segment (which again may be partial delete)
  6294. // Step (1) -- WOOB 1116297: When left >= start, step (1) is skipped, resulting in pNewArr->head->left != 0. We need to touch up pNewArr.
  6295. if (startSeg->left < start)
  6296. {
  6297. if (start < startSeg->left + startSeg->length)
  6298. {
  6299. uint32 headDeleteLen = startSeg->left + startSeg->length - start;
  6300. if (startSeg->next)
  6301. {
  6302. // We know the new segment will have a next segment, so allocate it as non-leaf.
  6303. newHeadSeg = SparseArraySegment<T>::template AllocateSegmentImpl<false>(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
  6304. }
  6305. else
  6306. {
  6307. newHeadSeg = SparseArraySegment<T>::AllocateSegment(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
  6308. }
  6309. newHeadSeg = SparseArraySegment<T>::CopySegment(recycler, newHeadSeg, 0, startSeg, start, headDeleteLen);
  6310. newHeadSeg->next = nullptr;
  6311. *prevNewHeadSeg = newHeadSeg;
  6312. prevNewHeadSeg = &newHeadSeg->next;
  6313. startSeg->Truncate(start);
  6314. }
  6315. savePrev = startSeg;
  6316. prevPrevSeg = prevSeg;
  6317. prevSeg = &startSeg->next;
  6318. startSeg = SparseArraySegment<T>::From(startSeg->next);
  6319. }
  6320. // Step (2) first we should do a hard copy if we have an inline head Segment
  6321. else if (hasInlineSegment && nullptr != startSeg)
  6322. {
  6323. // start should be in between left and left + length
  6324. if (startSeg->left <= start && start < startSeg->left + startSeg->length)
  6325. {
  6326. uint32 headDeleteLen = startSeg->left + startSeg->length - start;
  6327. if (startSeg->next)
  6328. {
  6329. // We know the new segment will have a next segment, so allocate it as non-leaf.
  6330. newHeadSeg = SparseArraySegment<T>::template AllocateSegmentImpl<false>(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
  6331. }
  6332. else
  6333. {
  6334. newHeadSeg = SparseArraySegment<T>::AllocateSegment(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
  6335. }
  6336. newHeadSeg = SparseArraySegment<T>::CopySegment(recycler, newHeadSeg, 0, startSeg, start, headDeleteLen);
  6337. *prevNewHeadSeg = newHeadSeg;
  6338. prevNewHeadSeg = &newHeadSeg->next;
  6339. // Remove the entire segment from the original array
  6340. *prevSeg = startSeg->next;
  6341. pArr->ClearElements(startSeg, 0);
  6342. startSeg = SparseArraySegment<T>::From(startSeg->next);
  6343. }
  6344. // if we have an inline head segment with 0 elements, remove it
  6345. else if (startSeg->left == 0 && startSeg->length == 0)
  6346. {
  6347. Assert(startSeg->size != 0);
  6348. *prevSeg = startSeg->next;
  6349. startSeg = SparseArraySegment<T>::From(startSeg->next);
  6350. }
  6351. }
  6352. // Step (2) proper
  6353. SparseArraySegmentBase *temp = nullptr;
  6354. while (startSeg && (startSeg->left + startSeg->length) <= limit)
  6355. {
  6356. temp = startSeg->next;
  6357. // move that entire segment to new array
  6358. startSeg->left = startSeg->left - start;
  6359. startSeg->next = nullptr;
  6360. *prevNewHeadSeg = startSeg;
  6361. prevNewHeadSeg = &startSeg->next;
  6362. // Remove the entire segment from the original array
  6363. *prevSeg = temp;
  6364. startSeg = (SparseArraySegment<T>*)temp;
  6365. }
  6366. // Step(2) above could delete the original head segment entirely, causing current head not
  6367. // starting from 0. Then if any of the following throw, we have a corrupted array. Need
  6368. // protection here.
  6369. bool dummyHeadNodeInserted = false;
  6370. if (!savePrev && (!startSeg || startSeg->left != 0))
  6371. {
  6372. Assert(pArr->head == startSeg);
  6373. pArr->EnsureHeadStartsFromZero<T>(recycler);
  6374. Assert(pArr->head && pArr->head->next == startSeg);
  6375. savePrev = pArr->head;
  6376. prevPrevSeg = prevSeg;
  6377. prevSeg = &pArr->head->next;
  6378. dummyHeadNodeInserted = true;
  6379. }
  6380. // Step (3)
  6381. if (startSeg && (startSeg->left < limit))
  6382. {
  6383. // copy the first part of the last segment to be deleted to new array
  6384. uint32 headDeleteLen = start + deleteLen - startSeg->left ;
  6385. newHeadSeg = SparseArraySegment<T>::AllocateSegment(recycler, startSeg->left - start, headDeleteLen, (SparseArraySegmentBase *)nullptr);
  6386. newHeadSeg = SparseArraySegment<T>::CopySegment(recycler, newHeadSeg, startSeg->left - start, startSeg, startSeg->left, headDeleteLen);
  6387. newHeadSeg->next = nullptr;
  6388. *prevNewHeadSeg = newHeadSeg;
  6389. prevNewHeadSeg = &newHeadSeg->next;
  6390. // move the last segment
  6391. MoveArray(startSeg->elements, startSeg->elements + headDeleteLen, startSeg->length - headDeleteLen);
  6392. startSeg->left = startSeg->left + headDeleteLen; // We are moving the left ahead to point to the right index
  6393. startSeg->length = startSeg->length - headDeleteLen;
  6394. startSeg->CheckLengthvsSize();
  6395. startSeg->Truncate(startSeg->left + startSeg->length);
  6396. startSeg->EnsureSizeInBound(); // Just truncated, size might exceed next.left
  6397. }
  6398. if (startSeg && ((startSeg->left - deleteLen + insertLen) == 0) && dummyHeadNodeInserted)
  6399. {
  6400. Assert(start + insertLen == 0);
  6401. // Remove the dummy head node to preserve array consistency.
  6402. pArr->head = startSeg;
  6403. savePrev = nullptr;
  6404. prevSeg = &pArr->head;
  6405. }
  6406. while (startSeg)
  6407. {
  6408. startSeg->left = startSeg->left - deleteLen + insertLen ;
  6409. if (startSeg->next == nullptr)
  6410. {
  6411. startSeg->EnsureSizeInBound();
  6412. }
  6413. startSeg = SparseArraySegment<T>::From(startSeg->next);
  6414. }
  6415. }
  6416. }
  6417. // The size of pnewArr head allocated in above step 1 might exceed next.left concatenated in step 2/3.
  6418. pnewArr->head->EnsureSizeInBound();
  6419. if (savePrev)
  6420. {
  6421. savePrev->EnsureSizeInBound();
  6422. }
  6423. // insert elements
  6424. if (insertLen > 0)
  6425. {
  6426. Assert(!JavascriptNativeIntArray::Is(pArr) && !JavascriptNativeFloatArray::Is(pArr));
  6427. // InsertPhase
  6428. SparseArraySegment<T> *segInsert = nullptr;
  6429. // see if we are just about the right of the previous segment
  6430. Assert(!savePrev || savePrev->left <= start);
  6431. if (savePrev && (start - savePrev->left < savePrev->size))
  6432. {
  6433. segInsert = (SparseArraySegment<T>*)savePrev;
  6434. uint32 spaceLeft = segInsert->size - (start - segInsert->left);
  6435. if(spaceLeft < insertLen)
  6436. {
  6437. SparseArraySegment<T> *oldSegInsert = segInsert;
  6438. bool isInlineSegment = JavascriptArray::IsInlineSegment(segInsert, pArr);
  6439. if (!segInsert->next)
  6440. {
  6441. segInsert = segInsert->GrowByMin(recycler, insertLen - spaceLeft);
  6442. }
  6443. else
  6444. {
  6445. segInsert = segInsert->GrowByMinMax(recycler, insertLen - spaceLeft, segInsert->next->left - segInsert->left - segInsert->size);
  6446. }
  6447. if (isInlineSegment)
  6448. {
  6449. pArr->ClearElements(oldSegInsert, 0);
  6450. }
  6451. }
  6452. *prevPrevSeg = segInsert;
  6453. segInsert->length = start + insertLen - segInsert->left;
  6454. segInsert->CheckLengthvsSize();
  6455. }
  6456. else
  6457. {
  6458. segInsert = SparseArraySegment<T>::AllocateSegment(recycler, start, insertLen, *prevSeg);
  6459. segInsert->next = *prevSeg;
  6460. *prevSeg = segInsert;
  6461. savePrev = segInsert;
  6462. }
  6463. uint32 relativeStart = start - segInsert->left;
  6464. // inserted elements starts at argument 3 of splice(start, deleteNumber, insertelem1, insertelem2, insertelem3, ...);
  6465. CopyArray(segInsert->elements + relativeStart, insertLen,
  6466. reinterpret_cast<const T*>(insertArgs), insertLen);
  6467. }
  6468. }
  6469. Var JavascriptArray::TryArraySplice(JavascriptArray* pArr, uint32 start, uint32 len, uint32 deleteLen,
  6470. Var* insertArgs, uint32 insertLen, ScriptContext *scriptContext)
  6471. {
  6472. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6473. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  6474. Assert(pArr != nullptr);
  6475. RecyclableObject* newObj = nullptr;
  6476. Recycler *recycler = scriptContext->GetRecycler();
  6477. ::Math::RecordOverflowPolicy newLenOverflow;
  6478. uint32 newLen = UInt32Math::Add(len - deleteLen, insertLen, newLenOverflow); // new length of the array after splice
  6479. // If we have missing values then convert to not native array for now
  6480. // In future, we could support this scenario.
  6481. if (deleteLen == insertLen)
  6482. {
  6483. JS_REENTRANT(jsReentLock, pArr->FillFromPrototypes(start, start + deleteLen));
  6484. }
  6485. else if (len)
  6486. {
  6487. JS_REENTRANT(jsReentLock, pArr->FillFromPrototypes(start, len));
  6488. }
  6489. //
  6490. // If newLen overflowed, pre-process to prevent pushing sparse array segments or elements out of
  6491. // max array length, which would result in tons of index overflow and difficult to fix.
  6492. //
  6493. if (newLenOverflow.HasOverflowed())
  6494. {
  6495. pArr = EnsureNonNativeArray(pArr);
  6496. BigIndex dstIndex = MaxArrayLength;
  6497. uint32 maxInsertLen = MaxArrayLength - start;
  6498. if (insertLen > maxInsertLen)
  6499. {
  6500. // Copy overflowing insertArgs to properties
  6501. for (uint32 i = maxInsertLen; i < insertLen; i++)
  6502. {
  6503. pArr->GenericDirectSetItemAt(dstIndex, insertArgs[i]);
  6504. ++dstIndex;
  6505. }
  6506. insertLen = maxInsertLen; // update
  6507. // Truncate elements on the right to properties
  6508. if (start + deleteLen < len)
  6509. {
  6510. pArr->TruncateToProperties(dstIndex, start + deleteLen);
  6511. }
  6512. }
  6513. else
  6514. {
  6515. // Truncate would-overflow elements to properties
  6516. pArr->TruncateToProperties(dstIndex, MaxArrayLength - insertLen + deleteLen);
  6517. }
  6518. len = pArr->length; // update
  6519. newLen = len - deleteLen + insertLen;
  6520. Assert(newLen == MaxArrayLength);
  6521. }
  6522. if (insertArgs)
  6523. {
  6524. pArr = EnsureNonNativeArray(pArr);
  6525. }
  6526. bool isIntArray = false;
  6527. bool isFloatArray = false;
  6528. bool isBuiltinArrayCtor = true;
  6529. JavascriptArray *newArr = nullptr;
  6530. // Just dump the segment map on splice (before any possible allocation and throw)
  6531. pArr->ClearSegmentMap();
  6532. // If the source object is an Array exotic object (Array.isArray) we should try to load the constructor property
  6533. // and use it to construct the return object.
  6534. JS_REENTRANT_NO_MUTATE(jsReentLock, newObj = ArraySpeciesCreate(pArr, deleteLen, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor));
  6535. if (newObj != nullptr)
  6536. {
  6537. pArr = EnsureNonNativeArray(pArr);
  6538. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  6539. newArr = JavascriptOperators::TryFromVar<JavascriptArray>(newObj);
  6540. if (newArr)
  6541. {
  6542. #if ENABLE_COPYONACCESS_ARRAY
  6543. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  6544. #endif
  6545. SET_SECOND_OBJECT_FOR_MUTATION(jsReentLock, newArr);
  6546. }
  6547. }
  6548. else
  6549. // This is the ES5 case, pArr['constructor'] doesn't exist, or pArr['constructor'] is the builtin Array constructor
  6550. {
  6551. pArr->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
  6552. newArr = CreateNewArrayHelper(deleteLen, isIntArray, isFloatArray, pArr, scriptContext);
  6553. #if ENABLE_COPYONACCESS_ARRAY
  6554. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  6555. #endif
  6556. }
  6557. // If return object is a JavascriptArray, we can use all the array splice helpers
  6558. if (newArr && isBuiltinArrayCtor && len == pArr->length)
  6559. {
  6560. // Code below has potential to throw due to OOM or SO. Just FailFast on those cases
  6561. AutoDisableInterrupt failFastOnError(scriptContext->GetThreadContext());
  6562. // Array has a single segment (need not start at 0) and splice start lies in the range
  6563. // of that segment we optimize splice - Fast path.
  6564. if (pArr->IsSingleSegmentArray() && pArr->head->HasIndex(start))
  6565. {
  6566. SparseArraySegmentBase *oldHead = pArr->head;
  6567. bool isInlineSegment = JavascriptArray::IsInlineSegment(oldHead, pArr);
  6568. if (isIntArray)
  6569. {
  6570. ArraySegmentSpliceHelper<int32>(newArr,
  6571. SparseArraySegment<int32>::From(pArr->head),
  6572. SparseArraySegment<int32>::AddressFrom(&pArr->head),
  6573. start, deleteLen, insertArgs, insertLen, recycler);
  6574. }
  6575. else if (isFloatArray)
  6576. {
  6577. ArraySegmentSpliceHelper<double>(newArr,
  6578. SparseArraySegment<double>::From(pArr->head),
  6579. SparseArraySegment<double>::AddressFrom(&pArr->head),
  6580. start, deleteLen, insertArgs, insertLen, recycler);
  6581. }
  6582. else
  6583. {
  6584. ArraySegmentSpliceHelper<Var>(newArr,
  6585. SparseArraySegment<Var>::From(pArr->head),
  6586. SparseArraySegment<Var>::AddressFrom(&pArr->head),
  6587. start, deleteLen, insertArgs, insertLen, recycler);
  6588. }
  6589. if (isInlineSegment && oldHead != pArr->head)
  6590. {
  6591. pArr->ClearElements(oldHead, 0);
  6592. }
  6593. // Since the start index is within the bounds of the original array's head segment, it will not acquire any new
  6594. // missing values. If the original array had missing values in the head segment, some of them may have been
  6595. // copied into the array that will be returned; otherwise, the array that is returned will also not have any
  6596. // missing values.
  6597. newArr->SetHasNoMissingValues(pArr->HasNoMissingValues());
  6598. }
  6599. else
  6600. {
  6601. if (isIntArray)
  6602. {
  6603. ArraySpliceHelper<int32>(newArr, pArr, start, deleteLen, insertArgs, insertLen, scriptContext);
  6604. }
  6605. else if (isFloatArray)
  6606. {
  6607. ArraySpliceHelper<double>(newArr, pArr, start, deleteLen, insertArgs, insertLen, scriptContext);
  6608. }
  6609. else
  6610. {
  6611. ArraySpliceHelper<Var>(newArr, pArr, start, deleteLen, insertArgs, insertLen, scriptContext);
  6612. }
  6613. // This function currently does not track missing values in the head segment if there are multiple segments
  6614. pArr->SetHasNoMissingValues(false);
  6615. newArr->SetHasNoMissingValues(false);
  6616. }
  6617. if (isIntArray)
  6618. {
  6619. pArr->EnsureHeadStartsFromZero<int32>(recycler);
  6620. newArr->EnsureHeadStartsFromZero<int32>(recycler);
  6621. }
  6622. else if (isFloatArray)
  6623. {
  6624. pArr->EnsureHeadStartsFromZero<double>(recycler);
  6625. newArr->EnsureHeadStartsFromZero<double>(recycler);
  6626. }
  6627. else
  6628. {
  6629. pArr->EnsureHeadStartsFromZero<Var>(recycler);
  6630. newArr->EnsureHeadStartsFromZero<Var>(recycler);
  6631. }
  6632. pArr->InvalidateLastUsedSegment();
  6633. // it is possible for valueOf accessors for the start or deleteLen
  6634. // arguments to modify the size of the array. Since the resulting size of the array
  6635. // is based on the cached value of length, this might lead to us having to trim
  6636. // excess array segments at the end of the splice operation, which SetLength() will do.
  6637. // However, this is also slower than performing the simple length assignment, so we only
  6638. // do it if we can detect the array length changing.
  6639. if (pArr->length != len)
  6640. {
  6641. pArr->SetLength(newLen);
  6642. }
  6643. else
  6644. {
  6645. pArr->length = newLen;
  6646. }
  6647. if (newArr->length != deleteLen)
  6648. {
  6649. newArr->SetLength(deleteLen);
  6650. }
  6651. else
  6652. {
  6653. newArr->length = deleteLen;
  6654. }
  6655. failFastOnError.Completed();
  6656. newArr->InvalidateLastUsedSegment();
  6657. #ifdef VALIDATE_ARRAY
  6658. newArr->ValidateArray();
  6659. pArr->ValidateArray();
  6660. #endif
  6661. if (newLenOverflow.HasOverflowed())
  6662. {
  6663. // ES5 15.4.4.12 16: If new len overflowed, SetLength throws
  6664. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  6665. }
  6666. return newArr;
  6667. }
  6668. if (newLenOverflow.HasOverflowed())
  6669. {
  6670. JS_REENTRANT_UNLOCK(jsReentLock, return ObjectSpliceHelper<uint64>(pArr, len, start, deleteLen, insertArgs, insertLen, scriptContext, newObj));
  6671. }
  6672. else // Use uint32 version if no overflow
  6673. {
  6674. JS_REENTRANT_UNLOCK(jsReentLock, return ObjectSpliceHelper<uint32>(pArr, len, start, deleteLen, insertArgs, insertLen, scriptContext, newObj));
  6675. }
  6676. }
  6677. template<typename T>
  6678. RecyclableObject* JavascriptArray::ObjectSpliceHelper(RecyclableObject* pObj, T len, T start,
  6679. T deleteLen, Var* insertArgs, uint32 insertLen, ScriptContext *scriptContext, RecyclableObject* pNewObj)
  6680. {
  6681. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6682. SETOBJECT_FOR_MUTATION(jsReentLock, pObj);
  6683. JavascriptArray *pnewArr = nullptr;
  6684. if (pNewObj == nullptr)
  6685. {
  6686. JS_REENTRANT_NO_MUTATE(jsReentLock, pNewObj = ArraySpeciesCreate(pObj, deleteLen, scriptContext));
  6687. if (pNewObj == nullptr)
  6688. {
  6689. if (deleteLen > UINT_MAX)
  6690. {
  6691. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  6692. }
  6693. pnewArr = scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(deleteLen));
  6694. pnewArr->EnsureHead<Var>();
  6695. pNewObj = pnewArr;
  6696. }
  6697. }
  6698. pnewArr = JavascriptOperators::TryFromVar<JavascriptArray>(pNewObj);
  6699. if (pnewArr)
  6700. {
  6701. #if ENABLE_COPYONACCESS_ARRAY
  6702. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pnewArr);
  6703. #endif
  6704. SET_SECOND_OBJECT_FOR_MUTATION(jsReentLock, pnewArr);
  6705. }
  6706. // copy elements to delete to new array
  6707. if (pnewArr != nullptr)
  6708. {
  6709. for (uint32 i = 0; i < deleteLen; i++)
  6710. {
  6711. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(pObj, start + i));
  6712. if (hasItem)
  6713. {
  6714. JS_REENTRANT(jsReentLock, Var element = JavascriptOperators::GetItem(pObj, start + i, scriptContext));
  6715. pnewArr->SetItem(i, element, PropertyOperation_None);
  6716. }
  6717. }
  6718. }
  6719. else
  6720. {
  6721. BigIndex k = 0u;
  6722. for (T i = 0u; i < deleteLen; i++)
  6723. {
  6724. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(pObj, start + i));
  6725. if (hasItem)
  6726. {
  6727. Var element = nullptr;
  6728. JS_REENTRANT(jsReentLock, element = JavascriptOperators::GetItem(pObj, start + i, scriptContext),
  6729. ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(pNewObj, k, element), scriptContext, k));
  6730. }
  6731. ++k;
  6732. }
  6733. }
  6734. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.splice"));
  6735. // Now we need reserve room if it is necessary
  6736. if (insertLen > deleteLen) // Might overflow max array length
  6737. {
  6738. // Unshift [start + deleteLen, len) to start + insertLen
  6739. JS_REENTRANT(jsReentLock, Unshift<BigIndex, T>(pObj, start + insertLen, start + deleteLen, len, scriptContext));
  6740. }
  6741. else if (insertLen < deleteLen) // Won't overflow max array length
  6742. {
  6743. T j = 0;
  6744. for (T i = start + deleteLen; i < len; i++)
  6745. {
  6746. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(pObj, i));
  6747. if (hasItem)
  6748. {
  6749. Var element = nullptr;
  6750. JS_REENTRANT(jsReentLock, element = JavascriptOperators::GetItem(pObj, i, scriptContext),
  6751. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(pObj, pObj, start + insertLen + j, element, scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  6752. }
  6753. else
  6754. {
  6755. JS_REENTRANT(jsReentLock,
  6756. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(pObj, start + insertLen + j, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  6757. }
  6758. j++;
  6759. }
  6760. // Clean up the rest
  6761. for (T i = len; i > len - deleteLen + insertLen; i--)
  6762. {
  6763. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(pObj, i - 1, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  6764. }
  6765. }
  6766. if (insertLen > 0)
  6767. {
  6768. T dstIndex = start; // insert index might overflow max array length
  6769. for (uint32 i = 0; i < insertLen; i++)
  6770. {
  6771. JS_REENTRANT(jsReentLock,
  6772. h.ThrowTypeErrorOnFailure(IndexTrace<BigIndex>::SetItem(pObj, dstIndex, insertArgs[i], PropertyOperation_ThrowIfNotExtensible)));
  6773. ++dstIndex;
  6774. }
  6775. }
  6776. // Set up new length
  6777. T newLen = T(len - deleteLen) + insertLen;
  6778. JS_REENTRANT(jsReentLock,
  6779. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(pObj, pObj, PropertyIds::length, IndexTrace<BigIndex>::ToNumber(newLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)),
  6780. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(pNewObj, pNewObj, PropertyIds::length, IndexTrace<BigIndex>::ToNumber(deleteLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  6781. #ifdef VALIDATE_ARRAY
  6782. if (pnewArr)
  6783. {
  6784. pnewArr->ValidateArray();
  6785. }
  6786. #endif
  6787. return pNewObj;
  6788. }
  6789. Var JavascriptArray::EntryToLocaleString(RecyclableObject* function, CallInfo callInfo, ...)
  6790. {
  6791. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  6792. ARGUMENTS(args, callInfo);
  6793. ScriptContext* scriptContext = function->GetScriptContext();
  6794. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6795. SETOBJECT_FOR_MUTATION(jsReentLock, args[0]);
  6796. Assert(!(callInfo.Flags & CallFlags_New));
  6797. if (args.Info.Count == 0)
  6798. {
  6799. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedObject, _u("Array.prototype.toLocaleString"));
  6800. }
  6801. if (JavascriptArray::IsDirectAccessArray(args[0]))
  6802. {
  6803. JavascriptArray* arr = JavascriptArray::UnsafeFromVar(args[0]);
  6804. JS_REENTRANT_UNLOCK(jsReentLock, return ToLocaleString(arr, scriptContext));
  6805. }
  6806. else
  6807. {
  6808. if (TypedArrayBase::IsDetachedTypedArray(args[0]))
  6809. {
  6810. JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("Array.prototype.toLocalString"));
  6811. }
  6812. RecyclableObject* obj = nullptr;
  6813. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  6814. {
  6815. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.toLocaleString"));
  6816. }
  6817. JS_REENTRANT_UNLOCK(jsReentLock, return ToLocaleString(obj, scriptContext));
  6818. }
  6819. }
  6820. //
  6821. // Unshift object elements [start, end) to toIndex, asserting toIndex > start.
  6822. //
  6823. template<typename T, typename P>
  6824. void JavascriptArray::Unshift(RecyclableObject* obj, const T& toIndex, P start, P end, ScriptContext* scriptContext)
  6825. {
  6826. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6827. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  6828. typedef IndexTrace<T> index_trace;
  6829. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.unshift"));
  6830. if (start < end)
  6831. {
  6832. T newEnd = (end - start - 1);// newEnd - 1
  6833. T dst = toIndex + newEnd;
  6834. for (P i = end; i > start; --i)
  6835. {
  6836. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, i - 1));
  6837. if (hasItem)
  6838. {
  6839. Var element = nullptr;
  6840. JS_REENTRANT(jsReentLock, element = JavascriptOperators::GetItem(obj, i - 1, scriptContext),
  6841. h.ThrowTypeErrorOnFailure(index_trace::SetItem(obj, dst, element, PropertyOperation_ThrowIfNotExtensible)));
  6842. }
  6843. else
  6844. {
  6845. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(index_trace::DeleteItem(obj, dst, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  6846. }
  6847. --dst;
  6848. }
  6849. }
  6850. }
  6851. template<typename T>
  6852. void JavascriptArray::GrowArrayHeadHelperForUnshift(JavascriptArray* pArr, uint32 unshiftElements, ScriptContext * scriptContext)
  6853. {
  6854. SparseArraySegmentBase* nextToHeadSeg = pArr->head->next;
  6855. Recycler* recycler = scriptContext->GetRecycler();
  6856. SparseArraySegmentBase *oldHead = pArr->head;
  6857. bool isInlineSegment = JavascriptArray::IsInlineSegment(oldHead, pArr);
  6858. if (nextToHeadSeg == nullptr)
  6859. {
  6860. pArr->EnsureHead<T>();
  6861. pArr->head = SparseArraySegment<T>::From(pArr->head)->GrowByMin(recycler, unshiftElements);
  6862. }
  6863. else
  6864. {
  6865. pArr->head = SparseArraySegment<T>::From(pArr->head)->GrowByMinMax(recycler, unshiftElements, ((nextToHeadSeg->left + unshiftElements) - pArr->head->left - pArr->head->size));
  6866. }
  6867. if (isInlineSegment)
  6868. {
  6869. pArr->ClearElements(oldHead, 0);
  6870. }
  6871. }
  6872. template<typename T>
  6873. void JavascriptArray::UnshiftHelper(JavascriptArray* pArr, uint32 unshiftElements, Js::Var * elements)
  6874. {
  6875. SparseArraySegment<T>* head = SparseArraySegment<T>::From(pArr->head);
  6876. // Make enough room in the head segment to insert new elements at the front
  6877. MoveArray(head->elements + unshiftElements, head->elements, pArr->head->length);
  6878. uint32 oldHeadLength = head->length;
  6879. head->length += unshiftElements;
  6880. head->CheckLengthvsSize();
  6881. /* Set head segment as the last used segment */
  6882. pArr->InvalidateLastUsedSegment();
  6883. bool hasNoMissingValues = pArr->HasNoMissingValues();
  6884. /* Set HasNoMissingValues to false -> Since we shifted elements right, we might have missing values after the memmove */
  6885. if(unshiftElements > oldHeadLength)
  6886. {
  6887. pArr->SetHasNoMissingValues(false);
  6888. }
  6889. #if ENABLE_PROFILE_INFO
  6890. pArr->FillFromArgs(unshiftElements, 0, elements, nullptr, true/*dontCreateNewArray*/);
  6891. #else
  6892. pArr->FillFromArgs(unshiftElements, 0, elements, true/*dontCreateNewArray*/);
  6893. #endif
  6894. // Setting back to the old value
  6895. pArr->SetHasNoMissingValues(hasNoMissingValues);
  6896. }
  6897. Var JavascriptArray::EntryUnshift(RecyclableObject* function, CallInfo callInfo, ...)
  6898. {
  6899. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  6900. ARGUMENTS(args, callInfo);
  6901. ScriptContext* scriptContext = function->GetScriptContext();
  6902. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6903. SETOBJECT_FOR_MUTATION(jsReentLock, args[0]);
  6904. Assert(!(callInfo.Flags & CallFlags_New));
  6905. Var res = scriptContext->GetLibrary()->GetUndefined();
  6906. if (args.Info.Count == 0)
  6907. {
  6908. return res;
  6909. }
  6910. JavascriptArray * pArr = nullptr;
  6911. if (JavascriptArray::Is(args[0])
  6912. && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
  6913. {
  6914. #if ENABLE_COPYONACCESS_ARRAY
  6915. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
  6916. #endif
  6917. pArr = JavascriptArray::FromVar(args[0]);
  6918. }
  6919. uint32 unshiftElements = args.Info.Count - 1;
  6920. // forceCheckProtoChain - since the array expand to accommodate new items thus we have to check if we have accessor on the proto chain.
  6921. bool useNoSideEffectUnshift = pArr != nullptr && (unshiftElements == 0 || !HasAnyES5ArrayInPrototypeChain(pArr, true /*forceCheckProtoChain*/));
  6922. if (useNoSideEffectUnshift)
  6923. {
  6924. if (unshiftElements > 0)
  6925. {
  6926. uint32 length = pArr->length;
  6927. if (pArr->IsFillFromPrototypes())
  6928. {
  6929. pArr->FillFromPrototypes(0, pArr->length); // We need find all missing value from [[proto]] object
  6930. }
  6931. // As we have already established that the FillFromPrototype should not change the bound of the array.
  6932. if (length != pArr->length)
  6933. {
  6934. Js::Throw::FatalInternalError();
  6935. }
  6936. // Pre-process: truncate overflowing elements to properties
  6937. bool newLenOverflowed = false;
  6938. uint32 maxLen = MaxArrayLength - unshiftElements;
  6939. if (pArr->length > maxLen)
  6940. {
  6941. newLenOverflowed = true;
  6942. // Ensure the array is non-native when overflow happens
  6943. EnsureNonNativeArray(pArr);
  6944. pArr->TruncateToProperties(MaxArrayLength, maxLen);
  6945. Assert(pArr->length + unshiftElements == MaxArrayLength);
  6946. }
  6947. pArr->ClearSegmentMap(); // Dump segmentMap on unshift (before any possible allocation and throw)
  6948. Assert(pArr->length <= MaxArrayLength - unshiftElements);
  6949. bool isIntArray = false;
  6950. bool isFloatArray = false;
  6951. if (JavascriptNativeIntArray::Is(pArr))
  6952. {
  6953. isIntArray = true;
  6954. }
  6955. else if (JavascriptNativeFloatArray::Is(pArr))
  6956. {
  6957. isFloatArray = true;
  6958. }
  6959. // If we need to grow head segment and there is already a next segment, then allocate the new head segment upfront
  6960. // If there is OOM in array allocation, then array consistency is maintained.
  6961. if (pArr->head->size < pArr->head->length + unshiftElements)
  6962. {
  6963. if (isIntArray)
  6964. {
  6965. GrowArrayHeadHelperForUnshift<int32>(pArr, unshiftElements, scriptContext);
  6966. }
  6967. else if (isFloatArray)
  6968. {
  6969. GrowArrayHeadHelperForUnshift<double>(pArr, unshiftElements, scriptContext);
  6970. }
  6971. else
  6972. {
  6973. GrowArrayHeadHelperForUnshift<Var>(pArr, unshiftElements, scriptContext);
  6974. }
  6975. }
  6976. SparseArraySegmentBase* renumberSeg = pArr->head->next;
  6977. while (renumberSeg)
  6978. {
  6979. renumberSeg->left += unshiftElements;
  6980. if (renumberSeg->next == nullptr)
  6981. {
  6982. // last segment can shift its left + size beyond MaxArrayLength, so truncate if so
  6983. renumberSeg->EnsureSizeInBound();
  6984. }
  6985. renumberSeg = renumberSeg->next;
  6986. }
  6987. try
  6988. {
  6989. if (isIntArray)
  6990. {
  6991. UnshiftHelper<int32>(pArr, unshiftElements, args.Values);
  6992. }
  6993. else if (isFloatArray)
  6994. {
  6995. UnshiftHelper<double>(pArr, unshiftElements, args.Values);
  6996. }
  6997. else
  6998. {
  6999. UnshiftHelper<Var>(pArr, unshiftElements, args.Values);
  7000. }
  7001. }
  7002. catch (...)
  7003. {
  7004. Js::Throw::FatalInternalError();
  7005. }
  7006. pArr->InvalidateLastUsedSegment();
  7007. pArr->length += unshiftElements;
  7008. #ifdef VALIDATE_ARRAY
  7009. pArr->ValidateArray();
  7010. #endif
  7011. if (newLenOverflowed) // ES5: throw if new "length" exceeds max array length
  7012. {
  7013. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  7014. }
  7015. }
  7016. res = JavascriptNumber::ToVar(pArr->length, scriptContext);
  7017. }
  7018. else
  7019. {
  7020. RecyclableObject* dynamicObject = nullptr;
  7021. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &dynamicObject))
  7022. {
  7023. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.unshift"));
  7024. }
  7025. JS_REENTRANT(jsReentLock, BigIndex length = OP_GetLength(dynamicObject, scriptContext));
  7026. if (unshiftElements > 0)
  7027. {
  7028. uint32 MaxSpaceUint32 = MaxArrayLength - unshiftElements;
  7029. // Note: end will always be a smallIndex either it is less than length in which case it is MaxSpaceUint32
  7030. // or MaxSpaceUint32 is greater than length meaning length is a uint32 number
  7031. BigIndex end = length > MaxSpaceUint32 ? MaxSpaceUint32 : length;
  7032. if (end < length)
  7033. {
  7034. // Unshift [end, length) to MaxArrayLength
  7035. // MaxArrayLength + (length - MaxSpaceUint32 - 1) = length + unshiftElements -1
  7036. if (length.IsSmallIndex())
  7037. {
  7038. JS_REENTRANT(jsReentLock, Unshift<BigIndex>(dynamicObject, MaxArrayLength, end.GetSmallIndex(), length.GetSmallIndex(), scriptContext));
  7039. }
  7040. else
  7041. {
  7042. JS_REENTRANT(jsReentLock, Unshift<BigIndex, uint64>(dynamicObject, MaxArrayLength, (uint64)end.GetSmallIndex(), length.GetBigIndex(), scriptContext));
  7043. }
  7044. }
  7045. // Unshift [0, end) to unshiftElements
  7046. // unshiftElements + (MaxSpaceUint32 - 0 - 1) = MaxArrayLength -1 therefore this unshift covers up to MaxArrayLength - 1
  7047. JS_REENTRANT(jsReentLock, Unshift<uint32>(dynamicObject, unshiftElements, (uint32)0, end.GetSmallIndex(), scriptContext));
  7048. for (uint32 i = 0; i < unshiftElements; i++)
  7049. {
  7050. JS_REENTRANT(jsReentLock,
  7051. JavascriptOperators::SetItem(dynamicObject, dynamicObject, i, args[i + 1], scriptContext, PropertyOperation_ThrowIfNotExtensible, true));
  7052. }
  7053. }
  7054. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.unshift"));
  7055. //ES6 - update 'length' even if unshiftElements == 0;
  7056. BigIndex newLen = length + unshiftElements;
  7057. res = JavascriptNumber::ToVar(newLen.IsSmallIndex() ? newLen.GetSmallIndex() : newLen.GetBigIndex(), scriptContext);
  7058. JS_REENTRANT(jsReentLock,
  7059. BOOL setLength = JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, res, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  7060. h.ThrowTypeErrorOnFailure(setLength);
  7061. }
  7062. return res;
  7063. }
  7064. Var JavascriptArray::EntryToString(RecyclableObject* function, CallInfo callInfo, ...)
  7065. {
  7066. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7067. ARGUMENTS(args, callInfo);
  7068. ScriptContext* scriptContext = function->GetScriptContext();
  7069. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7070. Assert(!(callInfo.Flags & CallFlags_New));
  7071. if (args.Info.Count == 0)
  7072. {
  7073. JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedObject);
  7074. }
  7075. // ES5 15.4.4.2: call join, or built-in Object.prototype.toString
  7076. RecyclableObject* obj = nullptr;
  7077. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  7078. {
  7079. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.toString"));
  7080. }
  7081. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  7082. // In ES5 we could be calling a user defined join, even on array. We must [[Get]] join at runtime.
  7083. JS_REENTRANT(jsReentLock, Var join = JavascriptOperators::GetPropertyNoCache(obj, PropertyIds::join, scriptContext));
  7084. if (JavascriptConversion::IsCallable(join))
  7085. {
  7086. RecyclableObject* func = RecyclableObject::FromVar(join);
  7087. // We need to record implicit call here, because marked the Array.toString as no side effect,
  7088. // but if we call user code here which may have side effect
  7089. ThreadContext * threadContext = scriptContext->GetThreadContext();
  7090. JS_REENTRANT(jsReentLock,
  7091. Var result = threadContext->ExecuteImplicitCall(func, ImplicitCall_ToPrimitive, [=]() -> Js::Var
  7092. {
  7093. // Stack object should have a pre-op bail on implicit call. We shouldn't see them here.
  7094. Assert(!ThreadContext::IsOnStack(obj));
  7095. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7096. CallFlags flags = CallFlags_Value;
  7097. return CALL_FUNCTION(threadContext, func, CallInfo(flags, 1), obj);
  7098. }));
  7099. if(!result)
  7100. {
  7101. // There was an implicit call and implicit calls are disabled. This would typically cause a bailout.
  7102. Assert(threadContext->IsDisableImplicitCall());
  7103. result = scriptContext->GetLibrary()->GetNull();
  7104. }
  7105. return result;
  7106. }
  7107. else
  7108. {
  7109. // call built-in Object.prototype.toString
  7110. JS_REENTRANT_UNLOCK(jsReentLock,
  7111. return CALL_ENTRYPOINT(scriptContext->GetThreadContext(), JavascriptObject::EntryToString, function, CallInfo(1), obj));
  7112. }
  7113. }
  7114. #if DEBUG
  7115. BOOL JavascriptArray::GetIndex(const char16* propName, uint32 *pIndex)
  7116. {
  7117. uint32 lu, luDig;
  7118. int32 cch = (int32)wcslen(propName);
  7119. char16* pch = const_cast<char16 *>(propName);
  7120. lu = *pch - '0';
  7121. if (lu > 9)
  7122. return FALSE;
  7123. if (0 == lu)
  7124. {
  7125. *pIndex = 0;
  7126. return 1 == cch;
  7127. }
  7128. while ((luDig = *++pch - '0') < 10)
  7129. {
  7130. // If we overflow 32 bits, ignore the item
  7131. if (lu > 0x19999999)
  7132. return FALSE;
  7133. lu *= 10;
  7134. if(lu > (ULONG_MAX - luDig))
  7135. return FALSE;
  7136. lu += luDig;
  7137. }
  7138. if (pch - propName != cch)
  7139. return FALSE;
  7140. if (lu == JavascriptArray::InvalidIndex)
  7141. {
  7142. // 0xFFFFFFFF is not treated as an array index so that the length can be
  7143. // capped at 32 bits.
  7144. return FALSE;
  7145. }
  7146. *pIndex = lu;
  7147. return TRUE;
  7148. }
  7149. #endif
  7150. JavascriptString* JavascriptArray::GetLocaleSeparator(ScriptContext* scriptContext)
  7151. {
  7152. #ifdef ENABLE_GLOBALIZATION
  7153. LCID lcid = GetUserDefaultLCID();
  7154. int count = 0;
  7155. char16 szSeparator[6];
  7156. // According to the document for GetLocaleInfo this is a sufficient buffer size.
  7157. count = GetLocaleInfoW(lcid, LOCALE_SLIST, szSeparator, 5);
  7158. if( !count)
  7159. {
  7160. AssertMsg(FALSE, "GetLocaleInfo failed");
  7161. return scriptContext->GetLibrary()->GetCommaSpaceDisplayString();
  7162. }
  7163. else
  7164. {
  7165. // Append ' ' if necessary
  7166. if( count < 2 || szSeparator[count-2] != ' ')
  7167. {
  7168. szSeparator[count-1] = ' ';
  7169. szSeparator[count] = '\0';
  7170. }
  7171. return JavascriptString::NewCopyBuffer(szSeparator, count, scriptContext);
  7172. }
  7173. #else
  7174. // xplat-todo: Support locale-specific separator
  7175. return scriptContext->GetLibrary()->GetCommaSpaceDisplayString();
  7176. #endif
  7177. }
  7178. template <typename T>
  7179. JavascriptString* JavascriptArray::ToLocaleString(T* arr, ScriptContext* scriptContext)
  7180. {
  7181. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7182. SETOBJECT_FOR_MUTATION(jsReentLock, arr);
  7183. uint32 length = 0;
  7184. TypedArrayBase * typedArray = JavascriptOperators::TryFromVar<Js::TypedArrayBase>(arr);
  7185. if (typedArray)
  7186. {
  7187. // For a TypedArray use the actual length of the array.
  7188. length = typedArray->GetLength();
  7189. }
  7190. else
  7191. {
  7192. //For anything else, use the "length" property if present.
  7193. JS_REENTRANT(jsReentLock, length = ItemTrace<T>::GetLength(arr, scriptContext));
  7194. }
  7195. if (length == 0 || scriptContext->CheckObject(arr))
  7196. {
  7197. return scriptContext->GetLibrary()->GetEmptyString();
  7198. }
  7199. JavascriptString* res = scriptContext->GetLibrary()->GetEmptyString();
  7200. bool pushedObject = false;
  7201. TryFinally([&]()
  7202. {
  7203. scriptContext->PushObject(arr);
  7204. pushedObject = true;
  7205. Var element;
  7206. JS_REENTRANT(jsReentLock, BOOL gotItem = ItemTrace<T>::GetItem(arr, 0, &element, scriptContext));
  7207. if (gotItem)
  7208. {
  7209. JS_REENTRANT(jsReentLock, res = JavascriptArray::ToLocaleStringHelper(element, scriptContext));
  7210. }
  7211. if (length > 1)
  7212. {
  7213. JavascriptString* separator = GetLocaleSeparator(scriptContext);
  7214. for (uint32 i = 1; i < length; i++)
  7215. {
  7216. res = JavascriptString::Concat(res, separator);
  7217. JS_REENTRANT(jsReentLock, gotItem = ItemTrace<T>::GetItem(arr, i, &element, scriptContext));
  7218. if (gotItem)
  7219. {
  7220. JS_REENTRANT(jsReentLock, res = JavascriptString::Concat(res, JavascriptArray::ToLocaleStringHelper(element, scriptContext)));
  7221. }
  7222. }
  7223. }
  7224. },
  7225. [&](bool/*hasException*/)
  7226. {
  7227. if (pushedObject)
  7228. {
  7229. Var top = scriptContext->PopObject();
  7230. AssertMsg(top == arr, "Unmatched operation stack");
  7231. }
  7232. });
  7233. if (res == nullptr)
  7234. {
  7235. res = scriptContext->GetLibrary()->GetEmptyString();
  7236. }
  7237. return res;
  7238. }
  7239. Var JavascriptArray::EntryIsArray(RecyclableObject* function, CallInfo callInfo, ...)
  7240. {
  7241. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7242. ARGUMENTS(args, callInfo);
  7243. ScriptContext* scriptContext = function->GetScriptContext();
  7244. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7245. Assert(!(callInfo.Flags & CallFlags_New));
  7246. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Constructor_isArray);
  7247. if (args.Info.Count < 2)
  7248. {
  7249. return scriptContext->GetLibrary()->GetFalse();
  7250. }
  7251. #if ENABLE_COPYONACCESS_ARRAY
  7252. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[1]);
  7253. #endif
  7254. if (JavascriptOperators::IsArray(args[1]))
  7255. {
  7256. return scriptContext->GetLibrary()->GetTrue();
  7257. }
  7258. return scriptContext->GetLibrary()->GetFalse();
  7259. }
  7260. ///----------------------------------------------------------------------------
  7261. /// Find() calls the given predicate callback on each element of the array, in
  7262. /// order, and returns the first element that makes the predicate return true,
  7263. /// as described in (ES6.0: S22.1.3.8).
  7264. ///----------------------------------------------------------------------------
  7265. Var JavascriptArray::EntryFind(RecyclableObject* function, CallInfo callInfo, ...)
  7266. {
  7267. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7268. ARGUMENTS(args, callInfo);
  7269. ScriptContext* scriptContext = function->GetScriptContext();
  7270. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7271. Assert(!(callInfo.Flags & CallFlags_New));
  7272. if (args.Info.Count == 0)
  7273. {
  7274. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.find"));
  7275. }
  7276. int64 length;
  7277. JavascriptArray * pArr = nullptr;
  7278. RecyclableObject* obj = nullptr;
  7279. JS_REENTRANT_UNLOCK(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.find"), &pArr, &obj, &length));
  7280. return JavascriptArray::FindHelper<false>(pArr, nullptr, obj, length, args, scriptContext);
  7281. }
  7282. template <bool findIndex>
  7283. Var JavascriptArray::FindHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
  7284. {
  7285. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7286. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  7287. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  7288. {
  7289. // typedArrayBase is only non-null if and only if we came here via the TypedArray entrypoint
  7290. if (typedArrayBase != nullptr)
  7291. {
  7292. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, findIndex ? _u("[TypedArray].prototype.findIndex") : _u("[TypedArray].prototype.find"));
  7293. }
  7294. else
  7295. {
  7296. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, findIndex ? _u("Array.prototype.findIndex") : _u("Array.prototype.find"));
  7297. }
  7298. }
  7299. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  7300. Var thisArg;
  7301. if (args.Info.Count > 2)
  7302. {
  7303. thisArg = args[2];
  7304. }
  7305. else
  7306. {
  7307. thisArg = scriptContext->GetLibrary()->GetUndefined();
  7308. }
  7309. // If we came from Array.prototype.find/findIndex and source object is not a JavascriptArray, source could be a TypedArray
  7310. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  7311. {
  7312. typedArrayBase = TypedArrayBase::UnsafeFromVar(obj);
  7313. }
  7314. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7315. CallFlags flags = CallFlags_Value;
  7316. Var element = nullptr;
  7317. Var testResult = nullptr;
  7318. if (pArr)
  7319. {
  7320. Var undefined = scriptContext->GetLibrary()->GetUndefined();
  7321. Assert(length <= UINT_MAX);
  7322. for (uint32 k = 0; k < (uint32)length; k++)
  7323. {
  7324. element = undefined;
  7325. JS_REENTRANT(jsReentLock, pArr->DirectGetItemAtFull(k, &element));
  7326. Var index = JavascriptNumber::ToVar(k, scriptContext);
  7327. JS_REENTRANT(jsReentLock,
  7328. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7329. element,
  7330. index,
  7331. pArr));
  7332. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7333. {
  7334. return findIndex ? index : element;
  7335. }
  7336. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  7337. // we will process the rest of the array elements like an ES5Array.
  7338. if (!JavascriptArray::Is(obj))
  7339. {
  7340. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  7341. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FindObjectHelper<findIndex>(obj, length, k + 1, callBackFn, thisArg, scriptContext));
  7342. }
  7343. }
  7344. }
  7345. else if (typedArrayBase)
  7346. {
  7347. Assert(length <= UINT_MAX);
  7348. for (uint32 k = 0; k < (uint32)length; k++)
  7349. {
  7350. // Spec does not ask to call HasItem, so we need to go to visit the whole length
  7351. element = typedArrayBase->DirectGetItem(k);
  7352. Var index = JavascriptNumber::ToVar(k, scriptContext);
  7353. JS_REENTRANT(jsReentLock,
  7354. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7355. element,
  7356. index,
  7357. typedArrayBase));
  7358. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7359. {
  7360. return findIndex ? index : element;
  7361. }
  7362. }
  7363. }
  7364. else
  7365. {
  7366. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FindObjectHelper<findIndex>(obj, length, 0u, callBackFn, thisArg, scriptContext));
  7367. }
  7368. return findIndex ? JavascriptNumber::ToVar(-1, scriptContext) : scriptContext->GetLibrary()->GetUndefined();
  7369. }
  7370. template <bool findIndex>
  7371. Var JavascriptArray::FindObjectHelper(RecyclableObject* obj, int64 length, int64 start, RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
  7372. {
  7373. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7374. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  7375. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7376. CallFlags flags = CallFlags_Value;
  7377. Var element = nullptr;
  7378. Var testResult = nullptr;
  7379. for (int64 k = start; k < length; k++)
  7380. {
  7381. JS_REENTRANT(jsReentLock, element = JavascriptOperators::GetItem(obj, (uint64)k, scriptContext));
  7382. Var index = JavascriptNumber::ToVar(k, scriptContext);
  7383. JS_REENTRANT(jsReentLock,
  7384. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7385. element,
  7386. index,
  7387. obj));
  7388. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7389. {
  7390. return findIndex ? index : element;
  7391. }
  7392. }
  7393. return findIndex ? JavascriptNumber::ToVar(-1, scriptContext) : scriptContext->GetLibrary()->GetUndefined();
  7394. }
  7395. ///----------------------------------------------------------------------------
  7396. /// FindIndex() calls the given predicate callback on each element of the
  7397. /// array, in order, and returns the index of the first element that makes the
  7398. /// predicate return true, as described in (ES6.0: S22.1.3.9).
  7399. ///----------------------------------------------------------------------------
  7400. Var JavascriptArray::EntryFindIndex(RecyclableObject* function, CallInfo callInfo, ...)
  7401. {
  7402. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7403. ARGUMENTS(args, callInfo);
  7404. ScriptContext* scriptContext = function->GetScriptContext();
  7405. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7406. Assert(!(callInfo.Flags & CallFlags_New));
  7407. if (args.Info.Count == 0)
  7408. {
  7409. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.findIndex"));
  7410. }
  7411. int64 length;
  7412. JavascriptArray * pArr = nullptr;
  7413. RecyclableObject* obj = nullptr;
  7414. JS_REENTRANT_UNLOCK(jsReentLock,
  7415. TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.findIndex"), &pArr, &obj, &length));
  7416. return JavascriptArray::FindHelper<true>(pArr, nullptr, obj, length, args, scriptContext);
  7417. }
  7418. ///----------------------------------------------------------------------------
  7419. /// Entries() returns a new ArrayIterator object configured to return key-
  7420. /// value pairs matching the elements of the this array/array-like object,
  7421. /// as described in (ES6.0: S22.1.3.4).
  7422. ///----------------------------------------------------------------------------
  7423. Var JavascriptArray::EntryEntries(RecyclableObject* function, CallInfo callInfo, ...)
  7424. {
  7425. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7426. ARGUMENTS(args, callInfo);
  7427. ScriptContext* scriptContext = function->GetScriptContext();
  7428. #ifdef ENABLE_JS_BUILTINS
  7429. Assert(!scriptContext->IsJsBuiltInEnabled());
  7430. #endif
  7431. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7432. Assert(!(callInfo.Flags & CallFlags_New));
  7433. if (args.Info.Count == 0)
  7434. {
  7435. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.entries"));
  7436. }
  7437. RecyclableObject* thisObj = nullptr;
  7438. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &thisObj))
  7439. {
  7440. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.entries"));
  7441. }
  7442. #if ENABLE_COPYONACCESS_ARRAY
  7443. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(thisObj);
  7444. #endif
  7445. JS_REENTRANT_UNLOCK(jsReentLock,
  7446. return scriptContext->GetLibrary()->CreateArrayIterator(thisObj, JavascriptArrayIteratorKind::KeyAndValue));
  7447. }
  7448. ///----------------------------------------------------------------------------
  7449. /// Keys() returns a new ArrayIterator object configured to return the keys
  7450. /// of the this array/array-like object, as described in (ES6.0: S22.1.3.13).
  7451. ///----------------------------------------------------------------------------
  7452. Var JavascriptArray::EntryKeys(RecyclableObject* function, CallInfo callInfo, ...)
  7453. {
  7454. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7455. ARGUMENTS(args, callInfo);
  7456. ScriptContext* scriptContext = function->GetScriptContext();
  7457. #ifdef ENABLE_JS_BUILTINS
  7458. Assert(!scriptContext->IsJsBuiltInEnabled());
  7459. #endif
  7460. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7461. Assert(!(callInfo.Flags & CallFlags_New));
  7462. if (args.Info.Count == 0)
  7463. {
  7464. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.keys"));
  7465. }
  7466. RecyclableObject* thisObj = nullptr;
  7467. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &thisObj))
  7468. {
  7469. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.keys"));
  7470. }
  7471. #if ENABLE_COPYONACCESS_ARRAY
  7472. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(thisObj);
  7473. #endif
  7474. JS_REENTRANT_UNLOCK(jsReentLock,
  7475. return scriptContext->GetLibrary()->CreateArrayIterator(thisObj, JavascriptArrayIteratorKind::Key));
  7476. }
  7477. ///----------------------------------------------------------------------------
  7478. /// Values() returns a new ArrayIterator object configured to return the values
  7479. /// of the this array/array-like object, as described in (ES6.0: S22.1.3.29).
  7480. ///----------------------------------------------------------------------------
  7481. Var JavascriptArray::EntryValues(RecyclableObject* function, CallInfo callInfo, ...)
  7482. {
  7483. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7484. ARGUMENTS(args, callInfo);
  7485. ScriptContext* scriptContext = function->GetScriptContext();
  7486. #ifdef ENABLE_JS_BUILTINS
  7487. Assert(!scriptContext->IsJsBuiltInEnabled());
  7488. #endif
  7489. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7490. Assert(!(callInfo.Flags & CallFlags_New));
  7491. if (args.Info.Count == 0)
  7492. {
  7493. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.values"));
  7494. }
  7495. RecyclableObject* thisObj = nullptr;
  7496. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &thisObj))
  7497. {
  7498. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.values"));
  7499. }
  7500. #if ENABLE_COPYONACCESS_ARRAY
  7501. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(thisObj);
  7502. #endif
  7503. JS_REENTRANT_UNLOCK(jsReentLock,
  7504. return scriptContext->GetLibrary()->CreateArrayIterator(thisObj, JavascriptArrayIteratorKind::Value));
  7505. }
  7506. Var JavascriptArray::EntryEvery(RecyclableObject* function, CallInfo callInfo, ...)
  7507. {
  7508. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7509. ARGUMENTS(args, callInfo);
  7510. ScriptContext* scriptContext = function->GetScriptContext();
  7511. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7512. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.every"));
  7513. Assert(!(callInfo.Flags & CallFlags_New));
  7514. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_every);
  7515. if (args.Info.Count == 0)
  7516. {
  7517. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.every"));
  7518. }
  7519. BigIndex length;
  7520. JavascriptArray* pArr = nullptr;
  7521. RecyclableObject* obj = nullptr;
  7522. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.every"), &pArr, &obj, &length));
  7523. if (length.IsSmallIndex())
  7524. {
  7525. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::EveryHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  7526. }
  7527. Assert(pArr == nullptr || length.IsUint32Max()); // if pArr is not null lets make sure length is safe to cast, which will only happen if length is a uint32max
  7528. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::EveryHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  7529. }
  7530. // Array.prototype.every as described by ES6.0 (draft 22) Section 22.1.3.5
  7531. template <typename T>
  7532. Var JavascriptArray::EveryHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  7533. {
  7534. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7535. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  7536. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  7537. {
  7538. // typedArrayBase is only non-null if and only if we came here via the TypedArray entrypoint
  7539. if (typedArrayBase != nullptr)
  7540. {
  7541. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.every"));
  7542. }
  7543. else
  7544. {
  7545. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.every"));
  7546. }
  7547. }
  7548. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  7549. Var thisArg = nullptr;
  7550. if (args.Info.Count > 2)
  7551. {
  7552. thisArg = args[2];
  7553. }
  7554. else
  7555. {
  7556. thisArg = scriptContext->GetLibrary()->GetUndefined();
  7557. }
  7558. // If we came from Array.prototype.map and source object is not a JavascriptArray, source could be a TypedArray
  7559. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  7560. {
  7561. typedArrayBase = TypedArrayBase::UnsafeFromVar(obj);
  7562. }
  7563. Var element = nullptr;
  7564. Var testResult = nullptr;
  7565. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7566. CallFlags flags = CallFlags_Value;
  7567. if (typedArrayBase)
  7568. {
  7569. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  7570. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  7571. for (uint32 k = 0; k < end; k++)
  7572. {
  7573. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  7574. element = typedArrayBase->DirectGetItem(k);
  7575. JS_REENTRANT(jsReentLock,
  7576. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7577. element,
  7578. JavascriptNumber::ToVar(k, scriptContext),
  7579. typedArrayBase));
  7580. if (!JavascriptConversion::ToBoolean(testResult, scriptContext))
  7581. {
  7582. return scriptContext->GetLibrary()->GetFalse();
  7583. }
  7584. }
  7585. }
  7586. else
  7587. {
  7588. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::EveryObjectHelper<T>(obj, length, 0u, callBackFn, thisArg, scriptContext));
  7589. }
  7590. return scriptContext->GetLibrary()->GetTrue();
  7591. }
  7592. template <typename T>
  7593. Var JavascriptArray::EveryObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
  7594. {
  7595. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7596. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  7597. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7598. CallFlags flags = CallFlags_Value;
  7599. Var element = nullptr;
  7600. Var testResult = nullptr;
  7601. for (T k = start; k < length; k++)
  7602. {
  7603. // According to es6 spec, we need to call Has first before calling Get
  7604. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  7605. if (hasItem)
  7606. {
  7607. JS_REENTRANT(jsReentLock,
  7608. element = JavascriptOperators::GetItem(obj, k, scriptContext),
  7609. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7610. element,
  7611. JavascriptNumber::ToVar(k, scriptContext),
  7612. obj));
  7613. if (!JavascriptConversion::ToBoolean(testResult, scriptContext))
  7614. {
  7615. return scriptContext->GetLibrary()->GetFalse();
  7616. }
  7617. }
  7618. }
  7619. return scriptContext->GetLibrary()->GetTrue();
  7620. }
  7621. Var JavascriptArray::EntrySome(RecyclableObject* function, CallInfo callInfo, ...)
  7622. {
  7623. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7624. ARGUMENTS(args, callInfo);
  7625. ScriptContext* scriptContext = function->GetScriptContext();
  7626. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7627. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.some"));
  7628. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_some);
  7629. Assert(!(callInfo.Flags & CallFlags_New));
  7630. if (args.Info.Count == 0)
  7631. {
  7632. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.some"));
  7633. }
  7634. BigIndex length;
  7635. JavascriptArray* pArr = nullptr;
  7636. RecyclableObject* obj = nullptr;
  7637. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.some"), &pArr, &obj, &length));
  7638. if (length.IsSmallIndex())
  7639. {
  7640. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SomeHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  7641. }
  7642. Assert(pArr == nullptr || length.IsUint32Max()); // if pArr is not null lets make sure length is safe to cast, which will only happen if length is a uint32max
  7643. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SomeHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  7644. }
  7645. // Array.prototype.some as described in ES6.0 (draft 22) Section 22.1.3.23
  7646. template <typename T>
  7647. Var JavascriptArray::SomeHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  7648. {
  7649. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7650. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  7651. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  7652. {
  7653. // We are in the TypedArray version of this API if and only if typedArrayBase != nullptr
  7654. if (typedArrayBase != nullptr)
  7655. {
  7656. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.some"));
  7657. }
  7658. else
  7659. {
  7660. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.some"));
  7661. }
  7662. }
  7663. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  7664. Var thisArg = nullptr;
  7665. if (args.Info.Count > 2)
  7666. {
  7667. thisArg = args[2];
  7668. }
  7669. else
  7670. {
  7671. thisArg = scriptContext->GetLibrary()->GetUndefined();
  7672. }
  7673. // If we came from Array.prototype.some and source object is not a JavascriptArray, source could be a TypedArray
  7674. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  7675. {
  7676. typedArrayBase = TypedArrayBase::UnsafeFromVar(obj);
  7677. }
  7678. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7679. CallFlags flags = CallFlags_Value;
  7680. Var element = nullptr;
  7681. Var testResult = nullptr;
  7682. if (typedArrayBase)
  7683. {
  7684. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  7685. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  7686. for (uint32 k = 0; k < end; k++)
  7687. {
  7688. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  7689. element = typedArrayBase->DirectGetItem(k);
  7690. JS_REENTRANT_UNLOCK(jsReentLock,
  7691. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7692. element,
  7693. JavascriptNumber::ToVar(k, scriptContext),
  7694. typedArrayBase));
  7695. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7696. {
  7697. return scriptContext->GetLibrary()->GetTrue();
  7698. }
  7699. }
  7700. }
  7701. else
  7702. {
  7703. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SomeObjectHelper<T>(obj, length, 0u, callBackFn, thisArg, scriptContext));
  7704. }
  7705. return scriptContext->GetLibrary()->GetFalse();
  7706. }
  7707. template <typename T>
  7708. Var JavascriptArray::SomeObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
  7709. {
  7710. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7711. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  7712. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7713. CallFlags flags = CallFlags_Value;
  7714. Var element = nullptr;
  7715. Var testResult = nullptr;
  7716. for (T k = start; k < length; k++)
  7717. {
  7718. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  7719. if (hasItem)
  7720. {
  7721. JS_REENTRANT_UNLOCK(jsReentLock,
  7722. element = JavascriptOperators::GetItem(obj, k, scriptContext),
  7723. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7724. element,
  7725. JavascriptNumber::ToVar(k, scriptContext),
  7726. obj));
  7727. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7728. {
  7729. return scriptContext->GetLibrary()->GetTrue();
  7730. }
  7731. }
  7732. }
  7733. return scriptContext->GetLibrary()->GetFalse();
  7734. }
  7735. Var JavascriptArray::EntryForEach(RecyclableObject* function, CallInfo callInfo, ...)
  7736. {
  7737. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7738. ARGUMENTS(args, callInfo);
  7739. ScriptContext* scriptContext = function->GetScriptContext();
  7740. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7741. SETOBJECT_FOR_MUTATION(jsReentLock, args[0]);
  7742. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.forEach"));
  7743. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_forEach)
  7744. Assert(!(callInfo.Flags & CallFlags_New));
  7745. if (args.Info.Count == 0)
  7746. {
  7747. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.forEach"));
  7748. }
  7749. BigIndex length;
  7750. JavascriptArray* pArr = nullptr;
  7751. RecyclableObject* dynamicObject = nullptr;
  7752. RecyclableObject* callBackFn = nullptr;
  7753. Var thisArg = nullptr;
  7754. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.forEach"), &pArr, &dynamicObject, &length));
  7755. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  7756. {
  7757. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.forEach"));
  7758. }
  7759. callBackFn = RecyclableObject::FromVar(args[1]);
  7760. if (args.Info.Count > 2)
  7761. {
  7762. thisArg = args[2];
  7763. }
  7764. else
  7765. {
  7766. thisArg = scriptContext->GetLibrary()->GetUndefined();
  7767. }
  7768. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7769. CallFlags flags = CallFlags_Value;
  7770. auto fn32 = [dynamicObject, callBackFn, flags, thisArg,
  7771. scriptContext](uint32 k, Var element)
  7772. {
  7773. CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7774. element,
  7775. JavascriptNumber::ToVar(k, scriptContext),
  7776. dynamicObject);
  7777. };
  7778. auto fn64 = [dynamicObject, callBackFn, flags, thisArg,
  7779. scriptContext](uint64 k, Var element)
  7780. {
  7781. CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7782. element,
  7783. JavascriptNumber::ToVar(k, scriptContext),
  7784. dynamicObject);
  7785. };
  7786. if (pArr)
  7787. {
  7788. Assert(pArr == dynamicObject);
  7789. JS_REENTRANT(jsReentLock, pArr->ForEachItemInRange<true>(0, length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex(), scriptContext, fn32));
  7790. }
  7791. else
  7792. {
  7793. if (length.IsSmallIndex())
  7794. {
  7795. JS_REENTRANT(jsReentLock, TemplatedForEachItemInRange<true>(dynamicObject, 0u, length.GetSmallIndex(), scriptContext, fn32));
  7796. }
  7797. else
  7798. {
  7799. JS_REENTRANT(jsReentLock, TemplatedForEachItemInRange<true>(dynamicObject, 0ui64, length.GetBigIndex(), scriptContext, fn64));
  7800. }
  7801. }
  7802. return scriptContext->GetLibrary()->GetUndefined();
  7803. }
  7804. Var JavascriptArray::EntryCopyWithin(RecyclableObject* function, CallInfo callInfo, ...)
  7805. {
  7806. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7807. ARGUMENTS(args, callInfo);
  7808. ScriptContext* scriptContext = function->GetScriptContext();
  7809. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7810. Assert(!(callInfo.Flags & CallFlags_New));
  7811. RecyclableObject* obj = nullptr;
  7812. JavascriptArray* pArr = nullptr;
  7813. int64 length;
  7814. JS_REENTRANT_UNLOCK(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.copyWithin"), &pArr, &obj, &length));
  7815. return JavascriptArray::CopyWithinHelper(pArr, nullptr, obj, length, args, scriptContext);
  7816. }
  7817. // Array.prototype.copyWithin as defined in ES6.0 (draft 22) Section 22.1.3.3
  7818. Var JavascriptArray::CopyWithinHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
  7819. {
  7820. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7821. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  7822. Assert(args.Info.Count > 0);
  7823. bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
  7824. JavascriptLibrary* library = scriptContext->GetLibrary();
  7825. int64 fromVal = 0;
  7826. int64 toVal = 0;
  7827. int64 finalVal = length;
  7828. // If we came from Array.prototype.copyWithin and source object is not a JavascriptArray, source could be a TypedArray
  7829. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  7830. {
  7831. typedArrayBase = TypedArrayBase::UnsafeFromVar(obj);
  7832. }
  7833. if (args.Info.Count > 1)
  7834. {
  7835. JS_REENTRANT(jsReentLock, toVal = JavascriptArray::GetIndexFromVar(args[1], length, scriptContext));
  7836. if (args.Info.Count > 2)
  7837. {
  7838. JS_REENTRANT(jsReentLock, fromVal = JavascriptArray::GetIndexFromVar(args[2], length, scriptContext));
  7839. if (args.Info.Count > 3 && args[3] != library->GetUndefined())
  7840. {
  7841. JS_REENTRANT(jsReentLock, finalVal = JavascriptArray::GetIndexFromVar(args[3], length, scriptContext));
  7842. }
  7843. }
  7844. }
  7845. // If count would be negative or zero, we won't do anything so go ahead and return early.
  7846. if (finalVal <= fromVal || length <= toVal)
  7847. {
  7848. return obj;
  7849. }
  7850. // Make sure we won't underflow during the count calculation
  7851. Assert(finalVal > fromVal && length > toVal);
  7852. int64 count = min(finalVal - fromVal, length - toVal);
  7853. // We shouldn't have made it here if the count was going to be zero
  7854. Assert(count > 0);
  7855. // If we entered via TypedArray.prototype.copyWithin, then we can copy by bytes. Otherwise, if the user called
  7856. // Array.prototype.copyWithin on a typed array instance, then the typed array might be responsible for not
  7857. // writing torn values, which memmove does not guarantee.
  7858. if (isTypedArrayEntryPoint)
  7859. {
  7860. Assert(typedArrayBase);
  7861. // Re-validate the typed array, which could have become detached due to reentrant script.
  7862. if (typedArrayBase->IsDetachedBuffer())
  7863. {
  7864. JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("[TypedArray].prototype.copyWithin"));
  7865. }
  7866. AssertOrFailFast(length == typedArrayBase->GetLength());
  7867. uint32 bytesPerElement = typedArrayBase->GetBytesPerElement();
  7868. byte *buffer = typedArrayBase->GetByteBuffer();
  7869. size_t fromByteIndex = static_cast<size_t>(fromVal) * bytesPerElement;
  7870. size_t toByteIndex = static_cast<size_t>(toVal) * bytesPerElement;
  7871. size_t byteCount = static_cast<size_t>(count) * bytesPerElement;
  7872. Assert(typedArrayBase->GetByteLength() >= byteCount);
  7873. Assert(fromByteIndex <= typedArrayBase->GetByteLength() - byteCount);
  7874. Assert(toByteIndex <= typedArrayBase->GetByteLength() - byteCount);
  7875. memmove(&buffer[toByteIndex], &buffer[fromByteIndex], byteCount);
  7876. return obj;
  7877. }
  7878. int direction;
  7879. if (fromVal < toVal && toVal < (fromVal + count))
  7880. {
  7881. direction = -1;
  7882. fromVal += count - 1;
  7883. toVal += count - 1;
  7884. }
  7885. else
  7886. {
  7887. direction = 1;
  7888. }
  7889. // Side effects (such as defining a property in a ToPrimitive call) during evaluation of arguments may convert the array to an ES5 array.
  7890. if (pArr && !JavascriptArray::Is(obj))
  7891. {
  7892. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  7893. pArr = nullptr;
  7894. }
  7895. // If we are going to copy elements from or to indices > 2^32-1 we'll execute this (slightly slower path)
  7896. // It's possible to optimize here so that we use the normal code below except for the > 2^32-1 indices
  7897. if ((direction == -1 && (fromVal >= MaxArrayLength || toVal >= MaxArrayLength))
  7898. || (((fromVal + count) > MaxArrayLength) || ((toVal + count) > MaxArrayLength)))
  7899. {
  7900. while (count > 0)
  7901. {
  7902. Var index = JavascriptNumber::ToVar(fromVal, scriptContext);
  7903. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::OP_HasItem(obj, index, scriptContext));
  7904. if (hasItem)
  7905. {
  7906. Var val = nullptr;
  7907. JS_REENTRANT(jsReentLock,
  7908. val = JavascriptOperators::OP_GetElementI(obj, index, scriptContext),
  7909. JavascriptOperators::OP_SetElementI(obj, JavascriptNumber::ToVar(toVal, scriptContext), val, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  7910. }
  7911. else
  7912. {
  7913. JavascriptOperators::OP_DeleteElementI(obj, JavascriptNumber::ToVar(toVal, scriptContext), scriptContext, PropertyOperation_ThrowOnDeleteIfNotConfig);
  7914. }
  7915. fromVal += direction;
  7916. toVal += direction;
  7917. count--;
  7918. }
  7919. }
  7920. else
  7921. {
  7922. Assert(fromVal < MaxArrayLength);
  7923. Assert(toVal < MaxArrayLength);
  7924. Assert(direction == -1 || (fromVal + count < MaxArrayLength && toVal + count < MaxArrayLength));
  7925. uint32 fromIndex = static_cast<uint32>(fromVal);
  7926. uint32 toIndex = static_cast<uint32>(toVal);
  7927. while (count > 0)
  7928. {
  7929. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, fromIndex));
  7930. if (hasItem)
  7931. {
  7932. if (typedArrayBase)
  7933. {
  7934. Var val = typedArrayBase->DirectGetItem(fromIndex);
  7935. JS_REENTRANT(jsReentLock, typedArrayBase->DirectSetItem(toIndex, val));
  7936. }
  7937. else if (pArr)
  7938. {
  7939. JS_REENTRANT(jsReentLock, Var val = pArr->DirectGetItem(fromIndex));
  7940. pArr->SetItem(toIndex, val, Js::PropertyOperation_ThrowIfNotExtensible);
  7941. if (!JavascriptArray::Is(obj))
  7942. {
  7943. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  7944. pArr = nullptr;
  7945. }
  7946. }
  7947. else
  7948. {
  7949. Var val = nullptr;
  7950. JS_REENTRANT(jsReentLock,
  7951. val = JavascriptOperators::OP_GetElementI_UInt32(obj, fromIndex, scriptContext),
  7952. JavascriptOperators::OP_SetElementI_UInt32(obj, toIndex, val, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  7953. }
  7954. }
  7955. else
  7956. {
  7957. JS_REENTRANT(jsReentLock, obj->DeleteItem(toIndex, PropertyOperation_ThrowOnDeleteIfNotConfig));
  7958. }
  7959. fromIndex += direction;
  7960. toIndex += direction;
  7961. count--;
  7962. }
  7963. }
  7964. return obj;
  7965. }
  7966. Var JavascriptArray::EntryFill(RecyclableObject* function, CallInfo callInfo, ...)
  7967. {
  7968. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7969. ARGUMENTS(args, callInfo);
  7970. ScriptContext* scriptContext = function->GetScriptContext();
  7971. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7972. Assert(!(callInfo.Flags & CallFlags_New));
  7973. RecyclableObject* obj = nullptr;
  7974. JavascriptArray* pArr = nullptr;
  7975. int64 length;
  7976. JS_REENTRANT_UNLOCK(jsReentLock,
  7977. TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.fill"), &pArr, &obj, &length));
  7978. return JavascriptArray::FillHelper(pArr, nullptr, obj, length, args, scriptContext);
  7979. }
  7980. // Array.prototype.fill as defined in ES6.0 (draft 22) Section 22.1.3.6
  7981. Var JavascriptArray::FillHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
  7982. {
  7983. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7984. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  7985. Assert(args.Info.Count > 0);
  7986. JavascriptLibrary* library = scriptContext->GetLibrary();
  7987. // If we came from Array.prototype.fill and source object is not a JavascriptArray, source could be a TypedArray
  7988. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  7989. {
  7990. typedArrayBase = TypedArrayBase::UnsafeFromVar(obj);
  7991. }
  7992. Var fillValue;
  7993. if (args.Info.Count > 1)
  7994. {
  7995. fillValue = args[1];
  7996. }
  7997. else
  7998. {
  7999. fillValue = library->GetUndefined();
  8000. }
  8001. int64 k = 0;
  8002. int64 finalVal = length;
  8003. if (args.Info.Count > 2)
  8004. {
  8005. JS_REENTRANT_UNLOCK(jsReentLock, k = JavascriptArray::GetIndexFromVar(args[2], length, scriptContext));
  8006. if (args.Info.Count > 3 && !JavascriptOperators::IsUndefinedObject(args[3]))
  8007. {
  8008. JS_REENTRANT_UNLOCK(jsReentLock, finalVal = JavascriptArray::GetIndexFromVar(args[3], length, scriptContext));
  8009. }
  8010. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  8011. // we will process the array elements like an ES5Array.
  8012. if (pArr && !JavascriptArray::Is(obj))
  8013. {
  8014. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  8015. pArr = nullptr;
  8016. }
  8017. }
  8018. if (k < MaxArrayLength)
  8019. {
  8020. int64 end = min<int64>(finalVal, MaxArrayLength);
  8021. uint32 u32k = static_cast<uint32>(k);
  8022. while (u32k < end)
  8023. {
  8024. if (typedArrayBase)
  8025. {
  8026. JS_REENTRANT(jsReentLock, typedArrayBase->DirectSetItem(u32k, fillValue));
  8027. }
  8028. else if (pArr)
  8029. {
  8030. pArr->SetItem(u32k, fillValue, PropertyOperation_ThrowIfNotExtensible);
  8031. }
  8032. else
  8033. {
  8034. JS_REENTRANT(jsReentLock,
  8035. JavascriptOperators::OP_SetElementI_UInt32(obj, u32k, fillValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible));
  8036. }
  8037. u32k++;
  8038. }
  8039. BigIndex dstIndex = MaxArrayLength;
  8040. for (int64 i = end; i < finalVal; ++i)
  8041. {
  8042. if (pArr)
  8043. {
  8044. pArr->GenericDirectSetItemAt(dstIndex, fillValue);
  8045. ++dstIndex;
  8046. }
  8047. else
  8048. {
  8049. JS_REENTRANT(jsReentLock,
  8050. JavascriptOperators::OP_SetElementI(obj, JavascriptNumber::ToVar(i, scriptContext), fillValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible));
  8051. }
  8052. }
  8053. }
  8054. else
  8055. {
  8056. BigIndex dstIndex = static_cast<uint64>(k);
  8057. for (int64 i = k; i < finalVal; i++)
  8058. {
  8059. if (pArr)
  8060. {
  8061. pArr->GenericDirectSetItemAt(dstIndex, fillValue);
  8062. ++dstIndex;
  8063. }
  8064. else
  8065. {
  8066. JS_REENTRANT(jsReentLock,
  8067. JavascriptOperators::OP_SetElementI(obj, JavascriptNumber::ToVar(i, scriptContext), fillValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible));
  8068. }
  8069. }
  8070. }
  8071. return obj;
  8072. }
  8073. // Array.prototype.map as defined by ES6.0 (Final) 22.1.3.15
  8074. Var JavascriptArray::EntryMap(RecyclableObject* function, CallInfo callInfo, ...)
  8075. {
  8076. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8077. ARGUMENTS(args, callInfo);
  8078. ScriptContext* scriptContext = function->GetScriptContext();
  8079. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8080. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.map"));
  8081. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_map);
  8082. Assert(!(callInfo.Flags & CallFlags_New));
  8083. if (args.Info.Count == 0)
  8084. {
  8085. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.map"));
  8086. }
  8087. BigIndex length;
  8088. JavascriptArray* pArr = nullptr;
  8089. RecyclableObject* obj = nullptr;
  8090. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.map"), &pArr, &obj, &length));
  8091. if (length.IsSmallIndex())
  8092. {
  8093. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::MapHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  8094. }
  8095. Assert(pArr == nullptr || length.IsUint32Max()); // if pArr is not null lets make sure length is safe to cast, which will only happen if length is a uint32max
  8096. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::MapHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  8097. }
  8098. template<typename T>
  8099. Var JavascriptArray::MapHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  8100. {
  8101. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8102. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  8103. RecyclableObject* newObj = nullptr;
  8104. JavascriptArray* newArr = nullptr;
  8105. bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
  8106. bool isBuiltinArrayCtor = true;
  8107. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  8108. {
  8109. if (isTypedArrayEntryPoint)
  8110. {
  8111. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.map"));
  8112. }
  8113. else
  8114. {
  8115. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.map"));
  8116. }
  8117. }
  8118. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  8119. Var thisArg;
  8120. if (args.Info.Count > 2)
  8121. {
  8122. thisArg = args[2];
  8123. }
  8124. else
  8125. {
  8126. thisArg = scriptContext->GetLibrary()->GetUndefined();
  8127. }
  8128. // If we came from Array.prototype.map and source object is not a JavascriptArray, source could be a TypedArray
  8129. if (!isTypedArrayEntryPoint && pArr == nullptr && TypedArrayBase::Is(obj))
  8130. {
  8131. typedArrayBase = TypedArrayBase::UnsafeFromVar(obj);
  8132. }
  8133. // If the entry point is %TypedArray%.prototype.map or the source object is an Array exotic object we should try to load the constructor property
  8134. // and use it to construct the return object.
  8135. if (isTypedArrayEntryPoint)
  8136. {
  8137. JS_REENTRANT(jsReentLock,
  8138. RecyclableObject* constructor = JavascriptOperators::SpeciesConstructor(
  8139. typedArrayBase, TypedArrayBase::GetDefaultConstructor(args[0], scriptContext), scriptContext));
  8140. isBuiltinArrayCtor = false;
  8141. Assert(JavascriptOperators::IsConstructor(constructor));
  8142. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(length, scriptContext) };
  8143. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  8144. JS_REENTRANT(jsReentLock, newObj = RecyclableObject::FromVar(TypedArrayBase::TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), (uint32)length, scriptContext)));
  8145. }
  8146. // skip the typed array and "pure" array case, we still need to handle special arrays like es5array, remote array, and proxy of array.
  8147. else if (pArr == nullptr || scriptContext->GetConfig()->IsES6SpeciesEnabled())
  8148. {
  8149. JS_REENTRANT_NO_MUTATE(jsReentLock, newObj = ArraySpeciesCreate(obj, length, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor));
  8150. }
  8151. if (newObj == nullptr)
  8152. {
  8153. if (length > UINT_MAX)
  8154. {
  8155. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  8156. }
  8157. newArr = scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(length));
  8158. newArr->EnsureHead<Var>();
  8159. newObj = newArr;
  8160. }
  8161. else
  8162. {
  8163. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  8164. newArr = JavascriptOperators::TryFromVar<JavascriptArray>(newObj);
  8165. if (newArr)
  8166. {
  8167. #if ENABLE_COPYONACCESS_ARRAY
  8168. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  8169. #endif
  8170. SET_SECOND_OBJECT_FOR_MUTATION(jsReentLock, newArr);
  8171. }
  8172. }
  8173. Var element = nullptr;
  8174. Var mappedValue = nullptr;
  8175. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8176. CallFlags callBackFnflags = CallFlags_Value;
  8177. CallInfo callBackFnInfo = CallInfo(callBackFnflags, 4);
  8178. // We at least have to have newObj as a valid object
  8179. Assert(newObj);
  8180. // The ArraySpeciesCreate call above could have converted the source array into an ES5Array. If this happens
  8181. // we will process the array elements like an ES5Array.
  8182. if (pArr && !JavascriptArray::Is(obj))
  8183. {
  8184. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  8185. pArr = nullptr;
  8186. }
  8187. if (pArr != nullptr)
  8188. {
  8189. // If source is a JavascriptArray, newObj may or may not be an array based on what was in source's constructor property
  8190. Assert(length <= UINT_MAX);
  8191. for (uint32 k = 0; k < (uint32)length; k++)
  8192. {
  8193. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(k, &element));
  8194. if (!gotItem)
  8195. {
  8196. continue;
  8197. }
  8198. JS_REENTRANT(jsReentLock,
  8199. mappedValue = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, callBackFnInfo, thisArg,
  8200. element,
  8201. JavascriptNumber::ToVar(k, scriptContext),
  8202. pArr));
  8203. // If newArr is a valid pointer, then we constructed an array to return. Otherwise we need to do generic object operations
  8204. if (newArr && isBuiltinArrayCtor)
  8205. {
  8206. newArr->DirectSetItemAt(k, mappedValue);
  8207. }
  8208. else
  8209. {
  8210. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, k, mappedValue), scriptContext, k));
  8211. }
  8212. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  8213. // we will process the rest of the array elements like an ES5Array.
  8214. if (!JavascriptArray::Is(obj))
  8215. {
  8216. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  8217. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::MapObjectHelper<T>(obj, length, k + 1, newObj, newArr, isBuiltinArrayCtor, callBackFn, thisArg, scriptContext));
  8218. }
  8219. }
  8220. }
  8221. else if (typedArrayBase != nullptr)
  8222. {
  8223. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  8224. // Source is a TypedArray, we may have tried to call a constructor, but newObj may not be a TypedArray (or an array either)
  8225. TypedArrayBase* newTypedArray = JavascriptOperators::TryFromVar<Js::TypedArrayBase>(newObj);
  8226. if (!newTypedArray)
  8227. {
  8228. AssertAndFailFast(newArr != nullptr);
  8229. }
  8230. Assert(length <= UINT_MAX);
  8231. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  8232. for (uint32 k = 0; k < end; k++)
  8233. {
  8234. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  8235. element = typedArrayBase->DirectGetItem(k);
  8236. JS_REENTRANT(jsReentLock,
  8237. mappedValue = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, callBackFnInfo, thisArg,
  8238. element,
  8239. JavascriptNumber::ToVar(k, scriptContext),
  8240. obj));
  8241. // If newObj is a TypedArray, set the mappedValue directly, otherwise it should be an array, set that item to that array
  8242. if (newTypedArray)
  8243. {
  8244. JS_REENTRANT(jsReentLock, newTypedArray->DirectSetItem(k, mappedValue));
  8245. }
  8246. else
  8247. {
  8248. newArr->SetItem(k, mappedValue, PropertyOperation_None);
  8249. }
  8250. }
  8251. }
  8252. else
  8253. {
  8254. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::MapObjectHelper<T>(obj, length, 0u, newObj, newArr, isBuiltinArrayCtor, callBackFn, thisArg, scriptContext));
  8255. }
  8256. #ifdef VALIDATE_ARRAY
  8257. if (JavascriptArray::Is(newObj))
  8258. {
  8259. newArr->ValidateArray();
  8260. }
  8261. #endif
  8262. return newObj;
  8263. }
  8264. template<typename T>
  8265. Var JavascriptArray::MapObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* newObj, JavascriptArray* newArr,
  8266. bool isBuiltinArrayCtor, RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
  8267. {
  8268. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8269. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  8270. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8271. CallFlags callBackFnflags = CallFlags_Value;
  8272. CallInfo callBackFnInfo = CallInfo(callBackFnflags, 4);
  8273. Var element = nullptr;
  8274. Var mappedValue = nullptr;
  8275. for (T k = start; k < length; k++)
  8276. {
  8277. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  8278. if (hasItem)
  8279. {
  8280. JS_REENTRANT(jsReentLock,
  8281. element = JavascriptOperators::GetItem(obj, k, scriptContext),
  8282. mappedValue = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, callBackFnInfo, thisArg,
  8283. element,
  8284. JavascriptNumber::ToVar(k, scriptContext),
  8285. obj));
  8286. if (newArr && isBuiltinArrayCtor)
  8287. {
  8288. newArr->SetItem((uint32)k, mappedValue, PropertyOperation_None);
  8289. }
  8290. else
  8291. {
  8292. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, BigIndex(k), mappedValue), scriptContext, BigIndex(k)));
  8293. }
  8294. }
  8295. }
  8296. #ifdef VALIDATE_ARRAY
  8297. if (JavascriptArray::Is(newObj))
  8298. {
  8299. newArr->ValidateArray();
  8300. }
  8301. #endif
  8302. return newObj;
  8303. }
  8304. Var JavascriptArray::EntryFilter(RecyclableObject* function, CallInfo callInfo, ...)
  8305. {
  8306. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8307. ARGUMENTS(args, callInfo);
  8308. ScriptContext* scriptContext = function->GetScriptContext();
  8309. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8310. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.filter"));
  8311. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_filter);
  8312. Assert(!(callInfo.Flags & CallFlags_New));
  8313. if (args.Info.Count == 0)
  8314. {
  8315. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.filter"));
  8316. }
  8317. BigIndex length;
  8318. JavascriptArray* pArr = nullptr;
  8319. RecyclableObject* obj = nullptr;
  8320. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.filter"), &pArr, &obj, &length));
  8321. if (length.IsSmallIndex())
  8322. {
  8323. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FilterHelper(pArr, obj, length.GetSmallIndex(), args, scriptContext));
  8324. }
  8325. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FilterHelper(pArr, obj, length.GetBigIndex(), args, scriptContext));
  8326. }
  8327. template <typename T>
  8328. Var JavascriptArray::FilterHelper(JavascriptArray* pArr, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  8329. {
  8330. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8331. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  8332. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  8333. {
  8334. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.filter"));
  8335. }
  8336. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  8337. Var thisArg = nullptr;
  8338. if (args.Info.Count > 2)
  8339. {
  8340. thisArg = args[2];
  8341. }
  8342. else
  8343. {
  8344. thisArg = scriptContext->GetLibrary()->GetUndefined();
  8345. }
  8346. // If the source object is an Array exotic object we should try to load the constructor property and use it to construct the return object.
  8347. bool isBuiltinArrayCtor = true;
  8348. JS_REENTRANT_NO_MUTATE(jsReentLock, RecyclableObject* newObj = ArraySpeciesCreate(obj, 0, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor));
  8349. JavascriptArray* newArr = nullptr;
  8350. if (newObj == nullptr)
  8351. {
  8352. newArr = scriptContext->GetLibrary()->CreateArray(0);
  8353. newArr->EnsureHead<Var>();
  8354. newObj = newArr;
  8355. }
  8356. else
  8357. {
  8358. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  8359. newArr = JavascriptOperators::TryFromVar<JavascriptArray>(newObj);
  8360. if (newArr)
  8361. {
  8362. #if ENABLE_COPYONACCESS_ARRAY
  8363. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  8364. #endif
  8365. SET_SECOND_OBJECT_FOR_MUTATION(jsReentLock, newArr);
  8366. }
  8367. }
  8368. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FilterObjectHelper<T>(obj, length, 0u, newArr, newObj, 0u, callBackFn, thisArg, scriptContext));
  8369. }
  8370. template <typename T>
  8371. Var JavascriptArray::FilterObjectHelper(RecyclableObject* obj, T length, T start, JavascriptArray* newArr, RecyclableObject* newObj, T newStart,
  8372. RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
  8373. {
  8374. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8375. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  8376. Var element = nullptr;
  8377. Var selected = nullptr;
  8378. BigIndex i = BigIndex(newStart);
  8379. for (T k = start; k < length; k++)
  8380. {
  8381. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  8382. if (hasItem)
  8383. {
  8384. JS_REENTRANT(jsReentLock,
  8385. element = JavascriptOperators::GetItem(obj, k, scriptContext),
  8386. selected = CALL_ENTRYPOINT(scriptContext->GetThreadContext(),
  8387. callBackFn->GetEntryPoint(), callBackFn, CallInfo(CallFlags_Value, 4),
  8388. thisArg,
  8389. element,
  8390. JavascriptNumber::ToVar(k, scriptContext),
  8391. obj));
  8392. if (JavascriptConversion::ToBoolean(selected, scriptContext))
  8393. {
  8394. if (newArr)
  8395. {
  8396. newArr->GenericDirectSetItemAt(i, element);
  8397. }
  8398. else
  8399. {
  8400. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i));
  8401. }
  8402. ++i;
  8403. }
  8404. }
  8405. }
  8406. #ifdef VALIDATE_ARRAY
  8407. if (newArr)
  8408. {
  8409. newArr->ValidateArray();
  8410. }
  8411. #endif
  8412. return newObj;
  8413. }
  8414. Var JavascriptArray::EntryReduce(RecyclableObject* function, CallInfo callInfo, ...)
  8415. {
  8416. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8417. ARGUMENTS(args, callInfo);
  8418. ScriptContext* scriptContext = function->GetScriptContext();
  8419. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8420. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.reduce"));
  8421. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_reduce);
  8422. Assert(!(callInfo.Flags & CallFlags_New));
  8423. if (args.Info.Count == 0)
  8424. {
  8425. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reduce"));
  8426. }
  8427. BigIndex length;
  8428. JavascriptArray * pArr = nullptr;
  8429. RecyclableObject* obj = nullptr;
  8430. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.reduce"), &pArr, &obj, &length));
  8431. if (length.IsSmallIndex())
  8432. {
  8433. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  8434. }
  8435. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  8436. }
  8437. // Array.prototype.reduce as described in ES6.0 (draft 22) Section 22.1.3.18
  8438. template <typename T>
  8439. Var JavascriptArray::ReduceHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  8440. {
  8441. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8442. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  8443. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  8444. {
  8445. if (typedArrayBase != nullptr)
  8446. {
  8447. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.reduce"));
  8448. }
  8449. else
  8450. {
  8451. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.reduce"));
  8452. }
  8453. }
  8454. // If we came from Array.prototype.reduce and source object is not a JavascriptArray, source could be a TypedArray
  8455. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  8456. {
  8457. typedArrayBase = TypedArrayBase::UnsafeFromVar(obj);
  8458. }
  8459. T k = 0;
  8460. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  8461. Var accumulator = nullptr;
  8462. Var element = nullptr;
  8463. if (args.Info.Count > 2)
  8464. {
  8465. accumulator = args[2];
  8466. }
  8467. else
  8468. {
  8469. if (length == 0)
  8470. {
  8471. JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
  8472. }
  8473. bool bPresent = false;
  8474. if (typedArrayBase)
  8475. {
  8476. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  8477. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  8478. for (; k < end && bPresent == false; k++)
  8479. {
  8480. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  8481. element = typedArrayBase->DirectGetItem((uint32)k);
  8482. bPresent = true;
  8483. accumulator = element;
  8484. }
  8485. }
  8486. else
  8487. {
  8488. for (; k < length && bPresent == false; k++)
  8489. {
  8490. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  8491. if (hasItem)
  8492. {
  8493. JS_REENTRANT(jsReentLock, accumulator = JavascriptOperators::GetItem(obj, k, scriptContext));
  8494. bPresent = true;
  8495. }
  8496. }
  8497. }
  8498. if (bPresent == false)
  8499. {
  8500. JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
  8501. }
  8502. }
  8503. Assert(accumulator);
  8504. Var undefinedValue = scriptContext->GetLibrary()->GetUndefined();
  8505. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8506. CallFlags flags = CallFlags_Value;
  8507. if (typedArrayBase)
  8508. {
  8509. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  8510. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  8511. for (; k < end; k++)
  8512. {
  8513. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  8514. element = typedArrayBase->DirectGetItem((uint32)k);
  8515. JS_REENTRANT(jsReentLock,
  8516. accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 5), undefinedValue,
  8517. accumulator,
  8518. element,
  8519. JavascriptNumber::ToVar(k, scriptContext),
  8520. typedArrayBase));
  8521. }
  8522. }
  8523. else
  8524. {
  8525. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceObjectHelper<T>(obj, length, k, callBackFn, accumulator, scriptContext));
  8526. }
  8527. return accumulator;
  8528. }
  8529. template <typename T>
  8530. Var JavascriptArray::ReduceObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* callBackFn, Var accumulator, ScriptContext* scriptContext)
  8531. {
  8532. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8533. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  8534. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8535. CallFlags flags = CallFlags_Value;
  8536. Var element = nullptr;
  8537. for (T k = start; k < length; k++)
  8538. {
  8539. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  8540. if (hasItem)
  8541. {
  8542. JS_REENTRANT(jsReentLock,
  8543. element = JavascriptOperators::GetItem(obj, k, scriptContext),
  8544. accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 5), scriptContext->GetLibrary()->GetUndefined(),
  8545. accumulator,
  8546. element,
  8547. JavascriptNumber::ToVar(k, scriptContext),
  8548. obj));
  8549. }
  8550. }
  8551. return accumulator;
  8552. }
  8553. Var JavascriptArray::EntryReduceRight(RecyclableObject* function, CallInfo callInfo, ...)
  8554. {
  8555. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8556. ARGUMENTS(args, callInfo);
  8557. ScriptContext* scriptContext = function->GetScriptContext();
  8558. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8559. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.reduceRight"));
  8560. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_reduceRight);
  8561. Assert(!(callInfo.Flags & CallFlags_New));
  8562. if (args.Info.Count == 0)
  8563. {
  8564. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reduceRight"));
  8565. }
  8566. BigIndex length;
  8567. JavascriptArray * pArr = nullptr;
  8568. RecyclableObject* obj = nullptr;
  8569. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.reduceRight"), &pArr, &obj, &length));
  8570. if (length.IsSmallIndex())
  8571. {
  8572. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceRightHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  8573. }
  8574. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceRightHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  8575. }
  8576. // Array.prototype.reduceRight as described in ES6.0 (draft 22) Section 22.1.3.19
  8577. template <typename T>
  8578. Var JavascriptArray::ReduceRightHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  8579. {
  8580. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8581. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  8582. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  8583. {
  8584. if (typedArrayBase != nullptr)
  8585. {
  8586. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.reduceRight"));
  8587. }
  8588. else
  8589. {
  8590. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.reduceRight"));
  8591. }
  8592. }
  8593. // If we came from Array.prototype.reduceRight and source object is not a JavascriptArray, source could be a TypedArray
  8594. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  8595. {
  8596. typedArrayBase = TypedArrayBase::UnsafeFromVar(obj);
  8597. }
  8598. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  8599. Var accumulator = nullptr;
  8600. Var element = nullptr;
  8601. T k = 0;
  8602. T index = 0;
  8603. if (args.Info.Count > 2)
  8604. {
  8605. accumulator = args[2];
  8606. }
  8607. else
  8608. {
  8609. if (length == 0)
  8610. {
  8611. JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
  8612. }
  8613. bool bPresent = false;
  8614. if (typedArrayBase)
  8615. {
  8616. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  8617. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  8618. for (; k < end && bPresent == false; k++)
  8619. {
  8620. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  8621. index = length - k - 1;
  8622. element = typedArrayBase->DirectGetItem((uint32)index);
  8623. bPresent = true;
  8624. accumulator = element;
  8625. }
  8626. }
  8627. else
  8628. {
  8629. for (; k < length && bPresent == false; k++)
  8630. {
  8631. index = length - k - 1;
  8632. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, index));
  8633. if (hasItem)
  8634. {
  8635. JS_REENTRANT(jsReentLock, accumulator = JavascriptOperators::GetItem(obj, index, scriptContext));
  8636. bPresent = true;
  8637. }
  8638. }
  8639. }
  8640. if (bPresent == false)
  8641. {
  8642. JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
  8643. }
  8644. }
  8645. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8646. CallFlags flags = CallFlags_Value;
  8647. Var undefinedValue = scriptContext->GetLibrary()->GetUndefined();
  8648. if (typedArrayBase)
  8649. {
  8650. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  8651. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  8652. for (; k < end; k++)
  8653. {
  8654. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  8655. index = length - k - 1;
  8656. element = typedArrayBase->DirectGetItem((uint32)index);
  8657. JS_REENTRANT(jsReentLock,
  8658. accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 5), undefinedValue,
  8659. accumulator,
  8660. element,
  8661. JavascriptNumber::ToVar(index, scriptContext),
  8662. typedArrayBase));
  8663. }
  8664. }
  8665. else
  8666. {
  8667. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceRightObjectHelper<T>(obj, length, k, callBackFn, accumulator, scriptContext));
  8668. }
  8669. return accumulator;
  8670. }
  8671. template <typename T>
  8672. Var JavascriptArray::ReduceRightObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* callBackFn, Var accumulator, ScriptContext* scriptContext)
  8673. {
  8674. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8675. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  8676. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8677. CallFlags flags = CallFlags_Value;
  8678. Var element = nullptr;
  8679. T index = 0;
  8680. for (T k = start; k < length; k++)
  8681. {
  8682. index = length - k - 1;
  8683. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, index));
  8684. if (hasItem)
  8685. {
  8686. JS_REENTRANT(jsReentLock,
  8687. element = JavascriptOperators::GetItem(obj, index, scriptContext),
  8688. accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(),
  8689. callBackFn, CallInfo(flags, 5), scriptContext->GetLibrary()->GetUndefined(),
  8690. accumulator,
  8691. element,
  8692. JavascriptNumber::ToVar(index, scriptContext),
  8693. obj));
  8694. }
  8695. }
  8696. return accumulator;
  8697. }
  8698. Var JavascriptArray::EntryFrom(RecyclableObject* function, CallInfo callInfo, ...)
  8699. {
  8700. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8701. ARGUMENTS(args, callInfo);
  8702. ScriptContext* scriptContext = function->GetScriptContext();
  8703. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8704. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.from"));
  8705. Assert(!(callInfo.Flags & CallFlags_New));
  8706. JavascriptLibrary* library = scriptContext->GetLibrary();
  8707. RecyclableObject* constructor = nullptr;
  8708. if (JavascriptOperators::IsConstructor(args[0]))
  8709. {
  8710. constructor = RecyclableObject::FromVar(args[0]);
  8711. }
  8712. RecyclableObject* items = nullptr;
  8713. if (args.Info.Count < 2 || !JavascriptConversion::ToObject(args[1], scriptContext, &items))
  8714. {
  8715. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedObject, _u("Array.from"));
  8716. }
  8717. JavascriptArray* itemsArr = JavascriptOperators::TryFromVar<JavascriptArray>(items);
  8718. if (itemsArr)
  8719. {
  8720. #if ENABLE_COPYONACCESS_ARRAY
  8721. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(itemsArr);
  8722. #endif
  8723. }
  8724. SETOBJECT_FOR_MUTATION(jsReentLock, itemsArr);
  8725. bool mapping = false;
  8726. JavascriptFunction* mapFn = nullptr;
  8727. Var mapFnThisArg = nullptr;
  8728. if (args.Info.Count >= 3 && !JavascriptOperators::IsUndefinedObject(args[2]))
  8729. {
  8730. if (!JavascriptFunction::Is(args[2]))
  8731. {
  8732. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.from"));
  8733. }
  8734. mapFn = JavascriptFunction::FromVar(args[2]);
  8735. if (args.Info.Count >= 4)
  8736. {
  8737. mapFnThisArg = args[3];
  8738. }
  8739. else
  8740. {
  8741. mapFnThisArg = library->GetUndefined();
  8742. }
  8743. mapping = true;
  8744. }
  8745. RecyclableObject* newObj = nullptr;
  8746. JavascriptArray* newArr = nullptr;
  8747. JS_REENTRANT(jsReentLock, RecyclableObject* iterator = JavascriptOperators::GetIterator(items, scriptContext, true /* optional */));
  8748. if (iterator != nullptr)
  8749. {
  8750. if (constructor)
  8751. {
  8752. Js::Var constructorArgs[] = { constructor };
  8753. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  8754. JS_REENTRANT(jsReentLock, newObj = RecyclableObject::FromVar(JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext)));
  8755. newArr = JavascriptOperators::TryFromVar<JavascriptArray>(newObj);
  8756. if (newArr)
  8757. {
  8758. #if ENABLE_COPYONACCESS_ARRAY
  8759. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  8760. #endif
  8761. }
  8762. }
  8763. else
  8764. {
  8765. newArr = scriptContext->GetLibrary()->CreateArray(0);
  8766. newArr->EnsureHead<Var>();
  8767. newObj = newArr;
  8768. }
  8769. uint32 k = 0;
  8770. JS_REENTRANT(jsReentLock, JavascriptOperators::DoIteratorStepAndValue(iterator, scriptContext, [&](Var nextValue) {
  8771. if (mapping)
  8772. {
  8773. Assert(mapFn != nullptr);
  8774. Assert(mapFnThisArg != nullptr);
  8775. Var kVar = JavascriptNumber::ToVar(k, scriptContext);
  8776. nextValue = CALL_FUNCTION(scriptContext->GetThreadContext(), mapFn, CallInfo(CallFlags_Value, 3), mapFnThisArg, nextValue, kVar);
  8777. }
  8778. if (newArr)
  8779. {
  8780. newArr->SetItem(k, nextValue, PropertyOperation_None);
  8781. }
  8782. else
  8783. {
  8784. ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, k, nextValue), scriptContext, k);
  8785. }
  8786. k++;
  8787. }));
  8788. JS_REENTRANT(jsReentLock, JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(k, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  8789. }
  8790. else
  8791. {
  8792. JS_REENTRANT(jsReentLock, int64 len = (int64)OP_GetLength(items, scriptContext));
  8793. if (constructor)
  8794. {
  8795. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(len, scriptContext) };
  8796. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  8797. JS_REENTRANT(jsReentLock, newObj = RecyclableObject::FromVar(JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext)));
  8798. newArr = JavascriptOperators::TryFromVar<JavascriptArray>(newObj);
  8799. if (newArr)
  8800. {
  8801. #if ENABLE_COPYONACCESS_ARRAY
  8802. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  8803. #endif
  8804. }
  8805. }
  8806. else
  8807. {
  8808. // Abstract operation ArrayCreate throws RangeError if length argument is > 2^32 -1
  8809. if (len > MaxArrayLength)
  8810. {
  8811. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect, _u("Array.from"));
  8812. }
  8813. // Static cast len should be valid (len < 2^32) or we would throw above
  8814. newArr = scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(len));
  8815. newArr->EnsureHead<Var>();
  8816. newObj = newArr;
  8817. }
  8818. uint32 k = 0;
  8819. for ( ; k < len; k++)
  8820. {
  8821. Var kValue;
  8822. if (itemsArr)
  8823. {
  8824. JS_REENTRANT(jsReentLock, kValue = itemsArr->DirectGetItem(k));
  8825. }
  8826. else
  8827. {
  8828. JS_REENTRANT(jsReentLock, kValue = JavascriptOperators::OP_GetElementI_UInt32(items, k, scriptContext));
  8829. }
  8830. if (mapping)
  8831. {
  8832. Assert(mapFn != nullptr);
  8833. Assert(mapFnThisArg != nullptr);
  8834. Var kVar = JavascriptNumber::ToVar(k, scriptContext);
  8835. JS_REENTRANT(jsReentLock, kValue = CALL_FUNCTION(scriptContext->GetThreadContext(), mapFn, CallInfo(CallFlags_Value, 3), mapFnThisArg, kValue, kVar));
  8836. }
  8837. if (newArr)
  8838. {
  8839. newArr->SetItem(k, kValue, PropertyOperation_None);
  8840. }
  8841. else
  8842. {
  8843. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, k, kValue), scriptContext, k));
  8844. }
  8845. }
  8846. JS_REENTRANT(jsReentLock, JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(len, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  8847. }
  8848. return newObj;
  8849. }
  8850. Var JavascriptArray::EntryOf(RecyclableObject* function, CallInfo callInfo, ...)
  8851. {
  8852. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8853. ARGUMENTS(args, callInfo);
  8854. ScriptContext* scriptContext = function->GetScriptContext();
  8855. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8856. Assert(!(callInfo.Flags & CallFlags_New));
  8857. if (args.Info.Count == 0)
  8858. {
  8859. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.of"));
  8860. }
  8861. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::OfHelper(false, args, scriptContext));
  8862. }
  8863. Var JavascriptArray::EntryGetterSymbolSpecies(RecyclableObject* function, CallInfo callInfo, ...)
  8864. {
  8865. ARGUMENTS(args, callInfo);
  8866. Assert(args.Info.Count > 0);
  8867. return args[0];
  8868. }
  8869. // Array.of and %TypedArray%.of as described in ES6.0 (draft 22) Section 22.1.2.2 and 22.2.2.2
  8870. Var JavascriptArray::OfHelper(bool isTypedArrayEntryPoint, Arguments& args, ScriptContext* scriptContext)
  8871. {
  8872. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8873. Assert(args.Info.Count > 0);
  8874. // args.Info.Count cannot equal zero or we would have thrown above so no chance of underflowing
  8875. uint32 len = args.Info.Count - 1;
  8876. Var newObj = nullptr;
  8877. JavascriptArray* newArr = nullptr;
  8878. TypedArrayBase* newTypedArray = nullptr;
  8879. bool isBuiltinArrayCtor = true;
  8880. if (JavascriptOperators::IsConstructor(args[0]))
  8881. {
  8882. RecyclableObject* constructor = RecyclableObject::FromVar(args[0]);
  8883. isBuiltinArrayCtor = (constructor == scriptContext->GetLibrary()->GetArrayConstructor());
  8884. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(len, scriptContext) };
  8885. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  8886. if (isTypedArrayEntryPoint)
  8887. {
  8888. JS_REENTRANT(jsReentLock, newObj = TypedArrayBase::TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), len, scriptContext));
  8889. }
  8890. else
  8891. {
  8892. JS_REENTRANT(jsReentLock, newObj = JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext));
  8893. }
  8894. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  8895. newArr = JavascriptOperators::TryFromVar<JavascriptArray>(newObj);
  8896. if (newArr)
  8897. {
  8898. #if ENABLE_COPYONACCESS_ARRAY
  8899. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  8900. #endif
  8901. SETOBJECT_FOR_MUTATION(jsReentLock, newArr);
  8902. }
  8903. else if (TypedArrayBase::Is(newObj))
  8904. {
  8905. newTypedArray = TypedArrayBase::UnsafeFromVar(newObj);
  8906. }
  8907. }
  8908. else
  8909. {
  8910. // We only throw when the constructor property is not a constructor function in the TypedArray version
  8911. if (isTypedArrayEntryPoint)
  8912. {
  8913. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedFunction, _u("[TypedArray].of"));
  8914. }
  8915. newArr = scriptContext->GetLibrary()->CreateArray(len);
  8916. newArr->EnsureHead<Var>();
  8917. newObj = newArr;
  8918. }
  8919. // At least we have a new object of some kind
  8920. Assert(newObj);
  8921. if (isBuiltinArrayCtor)
  8922. {
  8923. for (uint32 k = 0; k < len; k++)
  8924. {
  8925. Var kValue = args[k + 1];
  8926. newArr->DirectSetItemAt(k, kValue);
  8927. }
  8928. }
  8929. else if (newTypedArray)
  8930. {
  8931. for (uint32 k = 0; k < len; k++)
  8932. {
  8933. Var kValue = args[k + 1];
  8934. JS_REENTRANT(jsReentLock, newTypedArray->DirectSetItem(k, kValue));
  8935. }
  8936. }
  8937. else
  8938. {
  8939. for (uint32 k = 0; k < len; k++)
  8940. {
  8941. Var kValue = args[k + 1];
  8942. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(RecyclableObject::FromVar(newObj), k, kValue), scriptContext, k));
  8943. }
  8944. }
  8945. if (!isTypedArrayEntryPoint)
  8946. {
  8947. // Set length if we are in the Array version of the function
  8948. JS_REENTRANT(jsReentLock, JavascriptOperators::OP_SetProperty(newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(len, scriptContext), scriptContext, nullptr, PropertyOperation_ThrowIfNotExtensible));
  8949. }
  8950. return newObj;
  8951. }
  8952. JavascriptString* JavascriptArray::ToLocaleStringHelper(Var value, ScriptContext* scriptContext)
  8953. {
  8954. TypeId typeId = JavascriptOperators::GetTypeId(value);
  8955. if (typeId <= TypeIds_UndefinedOrNull)
  8956. {
  8957. return scriptContext->GetLibrary()->GetEmptyString();
  8958. }
  8959. else
  8960. {
  8961. return JavascriptConversion::ToLocaleString(value, scriptContext);
  8962. }
  8963. }
  8964. inline BOOL JavascriptArray::IsFullArray() const
  8965. {
  8966. if (head && head->length == length)
  8967. {
  8968. AssertMsg(head->next == 0 && head->left == 0, "Invalid Array");
  8969. return true;
  8970. }
  8971. return (0 == length);
  8972. }
  8973. /*
  8974. * IsFillFromPrototypes
  8975. * - Check the array has no missing values and only head segment.
  8976. * - Also ensure if the lengths match.
  8977. */
  8978. bool JavascriptArray::IsFillFromPrototypes()
  8979. {
  8980. return !(this->head->next == nullptr && this->HasNoMissingValues() && this->length == this->head->length);
  8981. }
  8982. // Fill all missing value in the array and fill it from prototype between startIndex and limitIndex
  8983. // typically startIndex = 0 and limitIndex = length. From start of the array till end of the array.
  8984. void JavascriptArray::FillFromPrototypes(uint32 startIndex, uint32 limitIndex)
  8985. {
  8986. if (startIndex >= limitIndex)
  8987. {
  8988. return;
  8989. }
  8990. RecyclableObject* prototype = this->GetPrototype();
  8991. // Fill all missing values by walking through prototype
  8992. while (!JavascriptOperators::IsNull(prototype))
  8993. {
  8994. ForEachOwnMissingArrayIndexOfObject(this, nullptr, prototype, startIndex, limitIndex,0, [this](uint32 index, Var value) {
  8995. this->SetItem(index, value, PropertyOperation_None);
  8996. });
  8997. prototype = prototype->GetPrototype();
  8998. }
  8999. #ifdef VALIDATE_ARRAY
  9000. ValidateArray();
  9001. #endif
  9002. }
  9003. //
  9004. // JavascriptArray requires head->left == 0 for fast path Get.
  9005. //
  9006. template<typename T>
  9007. void JavascriptArray::EnsureHeadStartsFromZero(Recycler * recycler)
  9008. {
  9009. if (head == nullptr || head->left != 0)
  9010. {
  9011. // This is used to fix up altered arrays.
  9012. // any SegmentMap would be invalid at this point.
  9013. ClearSegmentMap();
  9014. //
  9015. // We could OOM and throw when allocating new empty head, resulting in a corrupted array. Need
  9016. // some protection here. Save the head and switch this array to EmptySegment. Will be restored
  9017. // correctly if allocating new segment succeeds.
  9018. //
  9019. SparseArraySegment<T>* savedHead = SparseArraySegment<T>::From(this->head);
  9020. SparseArraySegment<T>* savedLastUsedSegment = (SparseArraySegment<T>*)this->GetLastUsedSegment();
  9021. SetHeadAndLastUsedSegment(const_cast<SparseArraySegmentBase*>(EmptySegment));
  9022. SparseArraySegment<T> *newSeg = SparseArraySegment<T>::AllocateSegment(recycler, 0, 0, savedHead);
  9023. newSeg->next = savedHead;
  9024. this->head = newSeg;
  9025. SetHasNoMissingValues();
  9026. this->SetLastUsedSegment(savedLastUsedSegment);
  9027. }
  9028. }
  9029. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  9030. void JavascriptArray::CheckForceES5Array()
  9031. {
  9032. if (Configuration::Global.flags.ForceES5Array)
  9033. {
  9034. // There's a bad interaction with the jitted code for native array creation here.
  9035. // ForceES5Array doesn't interact well with native arrays
  9036. if (PHASE_OFF1(NativeArrayPhase))
  9037. {
  9038. GetTypeHandler()->ConvertToTypeWithItemAttributes(this);
  9039. }
  9040. }
  9041. }
  9042. #endif
  9043. #if DBG
  9044. void JavascriptArray::DoTypeMutation()
  9045. {
  9046. // Type transition
  9047. uint32 random1 = static_cast<uint32>(rand());
  9048. if (random1 % 2 == 0)
  9049. {
  9050. if (JavascriptNativeIntArray::Is(this))
  9051. {
  9052. uint32 random2 = static_cast<uint32>(rand());
  9053. if (random2 % 2 == 0)
  9054. {
  9055. JavascriptNativeIntArray::ToNativeFloatArray(static_cast<JavascriptNativeIntArray*>(this));
  9056. }
  9057. else
  9058. {
  9059. JavascriptNativeIntArray::ToVarArray(static_cast<JavascriptNativeIntArray*>(this));
  9060. }
  9061. }
  9062. else if (JavascriptNativeFloatArray::Is(this))
  9063. {
  9064. JavascriptNativeFloatArray::ToVarArray(static_cast<JavascriptNativeFloatArray*>(this));
  9065. }
  9066. }
  9067. }
  9068. #endif
  9069. template <typename Fn>
  9070. void JavascriptArray::ForEachOwnMissingArrayIndexOfObject(JavascriptArray *baseArray, JavascriptArray *destArray, RecyclableObject* obj, uint32 startIndex, uint32 limitIndex, uint32 destIndex, Fn fn)
  9071. {
  9072. JS_REENTRANCY_LOCK(jsReentLock, baseArray->GetScriptContext()->GetThreadContext());
  9073. SETOBJECT_FOR_MUTATION(jsReentLock, baseArray);
  9074. SET_SECOND_OBJECT_FOR_MUTATION(jsReentLock, destArray);
  9075. Assert(DynamicObject::IsAnyArray(obj) || JavascriptOperators::IsObject(obj));
  9076. Var oldValue;
  9077. JavascriptArray* arr = nullptr;
  9078. if (DynamicObject::IsAnyArray(obj))
  9079. {
  9080. arr = JavascriptArray::UnsafeFromAnyArray(obj);
  9081. }
  9082. else if (DynamicType::Is(obj->GetTypeId()))
  9083. {
  9084. DynamicObject* dynobj = DynamicObject::UnsafeFromVar(obj);
  9085. ArrayObject* objectArray = dynobj->GetObjectArray();
  9086. arr = (objectArray && JavascriptArray::IsAnyArray(objectArray)) ? JavascriptArray::UnsafeFromAnyArray(objectArray) : nullptr;
  9087. }
  9088. if (arr != nullptr)
  9089. {
  9090. if (JavascriptArray::Is(arr))
  9091. {
  9092. arr = EnsureNonNativeArray(arr);
  9093. ArrayElementEnumerator e(arr, startIndex, limitIndex);
  9094. while(e.MoveNext<Var>())
  9095. {
  9096. uint32 index = e.GetIndex();
  9097. if (!baseArray->DirectGetVarItemAt(index, &oldValue, baseArray->GetScriptContext()))
  9098. {
  9099. uint32 n = destIndex + (index - startIndex);
  9100. if (destArray == nullptr || !destArray->DirectGetItemAt(n, &oldValue))
  9101. {
  9102. JS_REENTRANT(jsReentLock, fn(index, e.GetItem<Var>()));
  9103. }
  9104. }
  9105. }
  9106. }
  9107. else
  9108. {
  9109. ScriptContext* scriptContext = obj->GetScriptContext();
  9110. Assert(ES5Array::Is(arr));
  9111. ES5Array* es5Array = ES5Array::FromVar(arr);
  9112. ES5ArrayIndexStaticEnumerator<true> e(es5Array);
  9113. while (e.MoveNext())
  9114. {
  9115. uint32 index = e.GetIndex();
  9116. if (index < startIndex) continue;
  9117. else if (index >= limitIndex) break;
  9118. if (!baseArray->DirectGetVarItemAt(index, &oldValue, baseArray->GetScriptContext()))
  9119. {
  9120. uint32 n = destIndex + (index - startIndex);
  9121. if (destArray == nullptr || !destArray->DirectGetItemAt(n, &oldValue))
  9122. {
  9123. Var value = nullptr;
  9124. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetOwnItem(obj, index, &value, scriptContext));
  9125. if (gotItem)
  9126. {
  9127. JS_REENTRANT(jsReentLock, fn(index, value));
  9128. }
  9129. }
  9130. }
  9131. }
  9132. }
  9133. }
  9134. }
  9135. //
  9136. // ArrayElementEnumerator to enumerate array elements (not including elements from prototypes).
  9137. //
  9138. JavascriptArray::ArrayElementEnumerator::ArrayElementEnumerator(JavascriptArray* arr, uint32 start, uint32 end)
  9139. : start(start), end(min(end, arr->length))
  9140. {
  9141. Init(arr);
  9142. }
  9143. //
  9144. // Initialize this enumerator and prepare for the first MoveNext.
  9145. //
  9146. void JavascriptArray::ArrayElementEnumerator::Init(JavascriptArray* arr)
  9147. {
  9148. // Find start segment
  9149. seg = (arr ? arr->GetBeginLookupSegment(start) : nullptr);
  9150. while (seg && (seg->left + seg->length <= start))
  9151. {
  9152. seg = seg->next;
  9153. }
  9154. // Set start index and endIndex
  9155. if (seg)
  9156. {
  9157. if (seg->left >= end)
  9158. {
  9159. seg = nullptr;
  9160. }
  9161. else
  9162. {
  9163. // set index to be at target index - 1, so MoveNext will move to target
  9164. index = max(seg->left, start) - seg->left - 1;
  9165. endIndex = min(end - seg->left, seg->length);
  9166. }
  9167. }
  9168. }
  9169. //
  9170. // Move to the next element if available.
  9171. //
  9172. template<typename T>
  9173. inline bool JavascriptArray::ArrayElementEnumerator::MoveNext()
  9174. {
  9175. while (seg)
  9176. {
  9177. // Look for next non-null item in current segment
  9178. while (++index < endIndex)
  9179. {
  9180. if (!SparseArraySegment<T>::IsMissingItem(&((SparseArraySegment<T>*)seg)->elements[index]))
  9181. {
  9182. return true;
  9183. }
  9184. }
  9185. // Move to next segment
  9186. seg = seg->next;
  9187. if (seg)
  9188. {
  9189. if (seg->left >= end)
  9190. {
  9191. seg = nullptr;
  9192. break;
  9193. }
  9194. else
  9195. {
  9196. index = static_cast<uint32>(-1);
  9197. endIndex = min(end - seg->left, seg->length);
  9198. }
  9199. }
  9200. }
  9201. return false;
  9202. }
  9203. //
  9204. // Get current array element index.
  9205. //
  9206. uint32 JavascriptArray::ArrayElementEnumerator::GetIndex() const
  9207. {
  9208. Assert(seg && index < seg->length && index < endIndex);
  9209. return seg->left + index;
  9210. }
  9211. //
  9212. // Get current array element value.
  9213. //
  9214. template<typename T>
  9215. T JavascriptArray::ArrayElementEnumerator::GetItem() const
  9216. {
  9217. Assert(seg && index < seg->length && index < endIndex &&
  9218. !SparseArraySegment<T>::IsMissingItem(&((SparseArraySegment<T>*)seg)->elements[index]));
  9219. return ((SparseArraySegment<T>*)seg)->elements[index];
  9220. }
  9221. //
  9222. // Construct a BigIndex initialized to a given uint32 (small index).
  9223. //
  9224. JavascriptArray::BigIndex::BigIndex(uint32 initIndex)
  9225. : index(initIndex), bigIndex(InvalidIndex)
  9226. {
  9227. //ok if initIndex == InvalidIndex
  9228. }
  9229. //
  9230. // Construct a BigIndex initialized to a given uint64 (large or small index).
  9231. //
  9232. JavascriptArray::BigIndex::BigIndex(uint64 initIndex)
  9233. : index(InvalidIndex), bigIndex(initIndex)
  9234. {
  9235. if (bigIndex < InvalidIndex) // if it's actually small index
  9236. {
  9237. index = static_cast<uint32>(bigIndex);
  9238. bigIndex = InvalidIndex;
  9239. }
  9240. }
  9241. bool JavascriptArray::BigIndex::IsUint32Max() const
  9242. {
  9243. return index == InvalidIndex && bigIndex == InvalidIndex;
  9244. }
  9245. bool JavascriptArray::BigIndex::IsSmallIndex() const
  9246. {
  9247. return index < InvalidIndex;
  9248. }
  9249. uint32 JavascriptArray::BigIndex::GetSmallIndex() const
  9250. {
  9251. Assert(IsSmallIndex());
  9252. return index;
  9253. }
  9254. uint64 JavascriptArray::BigIndex::GetBigIndex() const
  9255. {
  9256. Assert(!IsSmallIndex());
  9257. return bigIndex;
  9258. }
  9259. //
  9260. // Convert this index value to a JS number
  9261. //
  9262. Var JavascriptArray::BigIndex::ToNumber(ScriptContext* scriptContext) const
  9263. {
  9264. if (IsSmallIndex())
  9265. {
  9266. return small_index::ToNumber(index, scriptContext);
  9267. }
  9268. else
  9269. {
  9270. return JavascriptNumber::ToVar(bigIndex, scriptContext);
  9271. }
  9272. }
  9273. //
  9274. // Increment this index by 1.
  9275. //
  9276. const JavascriptArray::BigIndex& JavascriptArray::BigIndex::operator++()
  9277. {
  9278. if (IsSmallIndex())
  9279. {
  9280. ++index;
  9281. // If index reaches InvalidIndex, we will start to use bigIndex which is initially InvalidIndex.
  9282. }
  9283. else
  9284. {
  9285. bigIndex = bigIndex + 1;
  9286. }
  9287. return *this;
  9288. }
  9289. //
  9290. // Decrement this index by 1.
  9291. //
  9292. const JavascriptArray::BigIndex& JavascriptArray::BigIndex::operator--()
  9293. {
  9294. if (IsSmallIndex())
  9295. {
  9296. --index;
  9297. }
  9298. else
  9299. {
  9300. Assert(index == InvalidIndex && bigIndex >= InvalidIndex);
  9301. --bigIndex;
  9302. if (bigIndex < InvalidIndex)
  9303. {
  9304. index = InvalidIndex - 1;
  9305. bigIndex = InvalidIndex;
  9306. }
  9307. }
  9308. return *this;
  9309. }
  9310. JavascriptArray::BigIndex JavascriptArray::BigIndex::operator+(const BigIndex& delta) const
  9311. {
  9312. if (delta.IsSmallIndex())
  9313. {
  9314. return operator+(delta.GetSmallIndex());
  9315. }
  9316. if (IsSmallIndex())
  9317. {
  9318. return index + delta.GetBigIndex();
  9319. }
  9320. return bigIndex + delta.GetBigIndex();
  9321. }
  9322. //
  9323. // Get a new BigIndex representing this + delta.
  9324. //
  9325. JavascriptArray::BigIndex JavascriptArray::BigIndex::operator+(uint32 delta) const
  9326. {
  9327. if (IsSmallIndex())
  9328. {
  9329. uint32 newIndex;
  9330. if (UInt32Math::Add(index, delta, &newIndex))
  9331. {
  9332. return static_cast<uint64>(index) + static_cast<uint64>(delta);
  9333. }
  9334. else
  9335. {
  9336. return newIndex; // ok if newIndex == InvalidIndex
  9337. }
  9338. }
  9339. else
  9340. {
  9341. return bigIndex + static_cast<uint64>(delta);
  9342. }
  9343. }
  9344. bool JavascriptArray::BigIndex::operator==(const BigIndex& rhs) const
  9345. {
  9346. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9347. {
  9348. return this->GetSmallIndex() == rhs.GetSmallIndex();
  9349. }
  9350. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9351. {
  9352. // if lhs is big promote rhs
  9353. return this->GetBigIndex() == (uint64) rhs.GetSmallIndex();
  9354. }
  9355. else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
  9356. {
  9357. // if rhs is big promote lhs
  9358. return ((uint64)this->GetSmallIndex()) == rhs.GetBigIndex();
  9359. }
  9360. return this->GetBigIndex() == rhs.GetBigIndex();
  9361. }
  9362. bool JavascriptArray::BigIndex::operator> (const BigIndex& rhs) const
  9363. {
  9364. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9365. {
  9366. return this->GetSmallIndex() > rhs.GetSmallIndex();
  9367. }
  9368. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9369. {
  9370. // if lhs is big promote rhs
  9371. return this->GetBigIndex() > (uint64)rhs.GetSmallIndex();
  9372. }
  9373. else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
  9374. {
  9375. // if rhs is big promote lhs
  9376. return ((uint64)this->GetSmallIndex()) > rhs.GetBigIndex();
  9377. }
  9378. return this->GetBigIndex() > rhs.GetBigIndex();
  9379. }
  9380. bool JavascriptArray::BigIndex::operator< (const BigIndex& rhs) const
  9381. {
  9382. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9383. {
  9384. return this->GetSmallIndex() < rhs.GetSmallIndex();
  9385. }
  9386. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9387. {
  9388. // if lhs is big promote rhs
  9389. return this->GetBigIndex() < (uint64)rhs.GetSmallIndex();
  9390. }
  9391. else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
  9392. {
  9393. // if rhs is big promote lhs
  9394. return ((uint64)this->GetSmallIndex()) < rhs.GetBigIndex();
  9395. }
  9396. return this->GetBigIndex() < rhs.GetBigIndex();
  9397. }
  9398. bool JavascriptArray::BigIndex::operator<=(const BigIndex& rhs) const
  9399. {
  9400. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9401. {
  9402. return this->GetSmallIndex() <= rhs.GetSmallIndex();
  9403. }
  9404. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9405. {
  9406. // if lhs is big promote rhs
  9407. return this->GetBigIndex() <= (uint64)rhs.GetSmallIndex();
  9408. }
  9409. else if (!rhs.IsSmallIndex() && !this->IsSmallIndex())
  9410. {
  9411. // if rhs is big promote lhs
  9412. return ((uint64)this->GetSmallIndex()) <= rhs.GetBigIndex();
  9413. }
  9414. return this->GetBigIndex() <= rhs.GetBigIndex();
  9415. }
  9416. bool JavascriptArray::BigIndex::operator>=(const BigIndex& rhs) const
  9417. {
  9418. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9419. {
  9420. return this->GetSmallIndex() >= rhs.GetSmallIndex();
  9421. }
  9422. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9423. {
  9424. // if lhs is big promote rhs
  9425. return this->GetBigIndex() >= (uint64)rhs.GetSmallIndex();
  9426. }
  9427. else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
  9428. {
  9429. // if rhs is big promote lhs
  9430. return ((uint64)this->GetSmallIndex()) >= rhs.GetBigIndex();
  9431. }
  9432. return this->GetBigIndex() >= rhs.GetBigIndex();
  9433. }
  9434. BOOL JavascriptArray::BigIndex::GetItem(JavascriptArray* arr, Var* outVal) const
  9435. {
  9436. if (IsSmallIndex())
  9437. {
  9438. return small_index::GetItem(arr, index, outVal);
  9439. }
  9440. else
  9441. {
  9442. ScriptContext* scriptContext = arr->GetScriptContext();
  9443. PropertyRecord const * propertyRecord;
  9444. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9445. return arr->GetProperty(arr, propertyRecord->GetPropertyId(), outVal, NULL, scriptContext);
  9446. }
  9447. }
  9448. BOOL JavascriptArray::BigIndex::SetItem(JavascriptArray* arr, Var newValue) const
  9449. {
  9450. if (IsSmallIndex())
  9451. {
  9452. return small_index::SetItem(arr, index, newValue);
  9453. }
  9454. else
  9455. {
  9456. ScriptContext* scriptContext = arr->GetScriptContext();
  9457. PropertyRecord const * propertyRecord;
  9458. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9459. return arr->SetProperty(propertyRecord->GetPropertyId(), newValue, PropertyOperation_None, NULL);
  9460. }
  9461. }
  9462. void JavascriptArray::BigIndex::SetItemIfNotExist(JavascriptArray* arr, Var newValue) const
  9463. {
  9464. if (IsSmallIndex())
  9465. {
  9466. small_index::SetItemIfNotExist(arr, index, newValue);
  9467. }
  9468. else
  9469. {
  9470. ScriptContext* scriptContext = arr->GetScriptContext();
  9471. PropertyRecord const * propertyRecord;
  9472. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9473. Var oldValue;
  9474. PropertyId propertyId = propertyRecord->GetPropertyId();
  9475. if (!arr->GetProperty(arr, propertyId, &oldValue, NULL, scriptContext))
  9476. {
  9477. arr->SetProperty(propertyId, newValue, PropertyOperation_None, NULL);
  9478. }
  9479. }
  9480. }
  9481. BOOL JavascriptArray::BigIndex::DeleteItem(JavascriptArray* arr) const
  9482. {
  9483. if (IsSmallIndex())
  9484. {
  9485. return small_index::DeleteItem(arr, index);
  9486. }
  9487. else
  9488. {
  9489. ScriptContext* scriptContext = arr->GetScriptContext();
  9490. PropertyRecord const * propertyRecord;
  9491. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9492. return arr->DeleteProperty(propertyRecord->GetPropertyId(), PropertyOperation_None);
  9493. }
  9494. }
  9495. BOOL JavascriptArray::BigIndex::SetItem(RecyclableObject* obj, Var newValue, PropertyOperationFlags flags) const
  9496. {
  9497. if (IsSmallIndex())
  9498. {
  9499. return small_index::SetItem(obj, index, newValue, flags);
  9500. }
  9501. else
  9502. {
  9503. ScriptContext* scriptContext = obj->GetScriptContext();
  9504. PropertyRecord const * propertyRecord;
  9505. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9506. return JavascriptOperators::SetProperty(obj, obj, propertyRecord->GetPropertyId(), newValue, scriptContext, flags);
  9507. }
  9508. }
  9509. BOOL JavascriptArray::BigIndex::DeleteItem(RecyclableObject* obj, PropertyOperationFlags flags) const
  9510. {
  9511. if (IsSmallIndex())
  9512. {
  9513. return small_index::DeleteItem(obj, index, flags);
  9514. }
  9515. else
  9516. {
  9517. PropertyRecord const * propertyRecord;
  9518. JavascriptOperators::GetPropertyIdForInt(bigIndex, obj->GetScriptContext(), &propertyRecord);
  9519. return JavascriptOperators::DeleteProperty(obj, propertyRecord->GetPropertyId(), flags);
  9520. }
  9521. }
  9522. //
  9523. // Truncate the array at start and clone the truncated span as properties starting at dstIndex (asserting dstIndex >= MaxArrayLength).
  9524. //
  9525. void JavascriptArray::TruncateToProperties(const BigIndex& dstIndex, uint32 start)
  9526. {
  9527. Assert(!dstIndex.IsSmallIndex());
  9528. typedef IndexTrace<BigIndex> index_trace;
  9529. BigIndex dst = dstIndex;
  9530. uint32 i = start;
  9531. ArrayElementEnumerator e(this, start);
  9532. while(e.MoveNext<Var>())
  9533. {
  9534. // delete all items not enumerated
  9535. while (i < e.GetIndex())
  9536. {
  9537. index_trace::DeleteItem(this, dst);
  9538. ++i;
  9539. ++dst;
  9540. }
  9541. // Copy over the item
  9542. index_trace::SetItem(this, dst, e.GetItem<Var>());
  9543. ++i;
  9544. ++dst;
  9545. }
  9546. // Delete the rest till length
  9547. while (i < this->length)
  9548. {
  9549. index_trace::DeleteItem(this, dst);
  9550. ++i;
  9551. ++dst;
  9552. }
  9553. // Elements moved, truncate the array at start
  9554. SetLength(start);
  9555. }
  9556. //
  9557. // Copy a srcArray elements (including elements from prototypes) to a dstArray starting from an index.
  9558. //
  9559. void JavascriptArray::InternalCopyArrayElements(JavascriptArray* dstArray, const uint32 dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
  9560. {
  9561. Assert(start < end && end <= srcArray->length);
  9562. uint32 count = 0;
  9563. // iterate on the array itself
  9564. ArrayElementEnumerator e(srcArray, start, end);
  9565. while(e.MoveNext<Var>())
  9566. {
  9567. uint32 n = dstIndex + (e.GetIndex() - start);
  9568. dstArray->DirectSetItemAt(n, e.GetItem<Var>());
  9569. count++;
  9570. }
  9571. // iterate on the array's prototypes only if not all elements found
  9572. if (start + count != end)
  9573. {
  9574. InternalFillFromPrototype(dstArray, dstIndex, srcArray, start, end, count);
  9575. }
  9576. }
  9577. //
  9578. // Faster small_index overload of CopyArrayElements, asserting the uint32 dstIndex won't overflow.
  9579. //
  9580. void JavascriptArray::CopyArrayElements(JavascriptArray* dstArray, uint32 dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
  9581. {
  9582. end = min(end, srcArray->length);
  9583. if (start < end)
  9584. {
  9585. Assert(end - start <= MaxArrayLength - dstIndex);
  9586. InternalCopyArrayElements(dstArray, dstIndex, srcArray, start, end);
  9587. }
  9588. }
  9589. template <typename T>
  9590. void JavascriptArray::CopyAnyArrayElementsToVar(JavascriptArray* dstArray, T dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
  9591. {
  9592. #if ENABLE_COPYONACCESS_ARRAY
  9593. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(srcArray);
  9594. #endif
  9595. #if ENABLE_COPYONACCESS_ARRAY
  9596. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(dstArray);
  9597. #endif
  9598. JavascriptNativeIntArray * nativeIntArray = JavascriptOperators::TryFromVar<JavascriptNativeIntArray>(srcArray);
  9599. if (nativeIntArray)
  9600. {
  9601. CopyNativeIntArrayElementsToVar(dstArray, dstIndex, nativeIntArray, start, end);
  9602. }
  9603. else
  9604. {
  9605. JavascriptNativeFloatArray * nativeFloatArray = JavascriptOperators::TryFromVar<JavascriptNativeFloatArray>(srcArray);
  9606. if (nativeFloatArray)
  9607. {
  9608. CopyNativeFloatArrayElementsToVar(dstArray, dstIndex, nativeFloatArray, start, end);
  9609. }
  9610. else
  9611. {
  9612. CopyArrayElements(dstArray, dstIndex, srcArray, start, end);
  9613. }
  9614. }
  9615. }
  9616. //
  9617. // Faster small_index overload of CopyArrayElements, asserting the uint32 dstIndex won't overflow.
  9618. //
  9619. void JavascriptArray::CopyNativeIntArrayElementsToVar(JavascriptArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
  9620. {
  9621. end = min(end, srcArray->length);
  9622. if (start < end)
  9623. {
  9624. Assert(end - start <= MaxArrayLength - dstIndex);
  9625. InternalCopyNativeIntArrayElements(dstArray, dstIndex, srcArray, start, end);
  9626. }
  9627. }
  9628. bool JavascriptArray::CopyNativeIntArrayElements(JavascriptNativeIntArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
  9629. {
  9630. end = min(end, srcArray->length);
  9631. if (start >= end)
  9632. {
  9633. return false;
  9634. }
  9635. Assert(end - start <= MaxArrayLength - dstIndex);
  9636. Assert(start < end && end <= srcArray->length);
  9637. uint32 count = 0;
  9638. // iterate on the array itself
  9639. ArrayElementEnumerator e(srcArray, start, end);
  9640. while(e.MoveNext<int32>())
  9641. {
  9642. uint n = dstIndex + (e.GetIndex() - start);
  9643. dstArray->DirectSetItemAt(n, e.GetItem<int32>());
  9644. count++;
  9645. }
  9646. // iterate on the array's prototypes only if not all elements found
  9647. if (start + count != end)
  9648. {
  9649. JavascriptArray *varArray = JavascriptNativeIntArray::ToVarArray(dstArray);
  9650. InternalFillFromPrototype(varArray, dstIndex, srcArray, start, end, count);
  9651. return true;
  9652. }
  9653. return false;
  9654. }
  9655. bool JavascriptArray::CopyNativeIntArrayElementsToFloat(JavascriptNativeFloatArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
  9656. {
  9657. end = min(end, srcArray->length);
  9658. if (start >= end)
  9659. {
  9660. return false;
  9661. }
  9662. Assert(end - start <= MaxArrayLength - dstIndex);
  9663. Assert(start < end && end <= srcArray->length);
  9664. uint32 count = 0;
  9665. // iterate on the array itself
  9666. ArrayElementEnumerator e(srcArray, start, end);
  9667. while(e.MoveNext<int32>())
  9668. {
  9669. uint n = dstIndex + (e.GetIndex() - start);
  9670. dstArray->DirectSetItemAt(n, (double)e.GetItem<int32>());
  9671. count++;
  9672. }
  9673. // iterate on the array's prototypes only if not all elements found
  9674. if (start + count != end)
  9675. {
  9676. JavascriptArray *varArray = JavascriptNativeFloatArray::ToVarArray(dstArray);
  9677. InternalFillFromPrototype(varArray, dstIndex, srcArray, start, end, count);
  9678. return true;
  9679. }
  9680. return false;
  9681. }
  9682. //
  9683. // Faster small_index overload of CopyArrayElements, asserting the uint32 dstIndex won't overflow.
  9684. //
  9685. void JavascriptArray::CopyNativeFloatArrayElementsToVar(JavascriptArray* dstArray, uint32 dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
  9686. {
  9687. end = min(end, srcArray->length);
  9688. if (start < end)
  9689. {
  9690. Assert(end - start <= MaxArrayLength - dstIndex);
  9691. InternalCopyNativeFloatArrayElements(dstArray, dstIndex, srcArray, start, end);
  9692. }
  9693. }
  9694. bool JavascriptArray::CopyNativeFloatArrayElements(JavascriptNativeFloatArray* dstArray, uint32 dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
  9695. {
  9696. end = min(end, srcArray->length);
  9697. if (start >= end)
  9698. {
  9699. return false;
  9700. }
  9701. Assert(end - start <= MaxArrayLength - dstIndex);
  9702. Assert(start < end && end <= srcArray->length);
  9703. uint32 count = 0;
  9704. // iterate on the array itself
  9705. ArrayElementEnumerator e(srcArray, start, end);
  9706. while(e.MoveNext<double>())
  9707. {
  9708. uint n = dstIndex + (e.GetIndex() - start);
  9709. dstArray->DirectSetItemAt(n, e.GetItem<double>());
  9710. count++;
  9711. }
  9712. // iterate on the array's prototypes only if not all elements found
  9713. if (start + count != end)
  9714. {
  9715. JavascriptArray *varArray = JavascriptNativeFloatArray::ToVarArray(dstArray);
  9716. InternalFillFromPrototype(varArray, dstIndex, srcArray, start, end, count);
  9717. return true;
  9718. }
  9719. return false;
  9720. }
  9721. JavascriptArray *JavascriptArray::EnsureNonNativeArray(JavascriptArray *arr)
  9722. {
  9723. #if ENABLE_COPYONACCESS_ARRAY
  9724. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(arr);
  9725. #endif
  9726. if (JavascriptNativeIntArray::Is(arr))
  9727. {
  9728. arr = JavascriptNativeIntArray::ToVarArray((JavascriptNativeIntArray*)arr);
  9729. }
  9730. else if (JavascriptNativeFloatArray::Is(arr))
  9731. {
  9732. arr = JavascriptNativeFloatArray::ToVarArray((JavascriptNativeFloatArray*)arr);
  9733. }
  9734. return arr;
  9735. }
  9736. BOOL JavascriptNativeIntArray::DirectGetItemAtFull(uint32 index, Var* outVal)
  9737. {
  9738. ScriptContext* requestContext = type->GetScriptContext();
  9739. if (JavascriptConversion::PropertyQueryFlagsToBoolean(JavascriptNativeIntArray::GetItemQuery(this, index, outVal, requestContext)))
  9740. {
  9741. return TRUE;
  9742. }
  9743. return JavascriptOperators::GetItem(this, this->GetPrototype(), index, outVal, requestContext);
  9744. }
  9745. BOOL JavascriptNativeFloatArray::DirectGetItemAtFull(uint32 index, Var* outVal)
  9746. {
  9747. ScriptContext* requestContext = type->GetScriptContext();
  9748. if (JavascriptConversion::PropertyQueryFlagsToBoolean(JavascriptNativeFloatArray::GetItemQuery(this, index, outVal, requestContext)))
  9749. {
  9750. return TRUE;
  9751. }
  9752. return JavascriptOperators::GetItem(this, this->GetPrototype(), index, outVal, requestContext);
  9753. }
  9754. void JavascriptArray::InternalCopyNativeIntArrayElements(JavascriptArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
  9755. {
  9756. Assert(start < end && end <= srcArray->length);
  9757. uint32 count = 0;
  9758. // iterate on the array itself
  9759. ScriptContext *scriptContext = dstArray->GetScriptContext();
  9760. ArrayElementEnumerator e(srcArray, start, end);
  9761. while(e.MoveNext<int32>())
  9762. {
  9763. uint32 n = dstIndex + (e.GetIndex() - start);
  9764. dstArray->DirectSetItemAt(n, JavascriptNumber::ToVar(e.GetItem<int32>(), scriptContext));
  9765. count++;
  9766. }
  9767. // iterate on the array's prototypes only if not all elements found
  9768. if (start + count != end)
  9769. {
  9770. InternalFillFromPrototype(dstArray, dstIndex, srcArray, start, end, count);
  9771. }
  9772. }
  9773. void JavascriptArray::InternalCopyNativeFloatArrayElements(JavascriptArray* dstArray, uint32 dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
  9774. {
  9775. Assert(start < end && end <= srcArray->length);
  9776. uint32 count = 0;
  9777. // iterate on the array itself
  9778. ScriptContext *scriptContext = dstArray->GetScriptContext();
  9779. ArrayElementEnumerator e(srcArray, start, end);
  9780. while(e.MoveNext<double>())
  9781. {
  9782. uint32 n = dstIndex + (e.GetIndex() - start);
  9783. dstArray->DirectSetItemAt(n, JavascriptNumber::ToVarWithCheck(e.GetItem<double>(), scriptContext));
  9784. count++;
  9785. }
  9786. // iterate on the array's prototypes only if not all elements found
  9787. if (start + count != end)
  9788. {
  9789. InternalFillFromPrototype(dstArray, dstIndex, srcArray, start, end, count);
  9790. }
  9791. }
  9792. Var JavascriptArray::SpreadArrayArgs(Var arrayToSpread, const Js::AuxArray<uint32> *spreadIndices, ScriptContext *scriptContext)
  9793. {
  9794. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  9795. SETOBJECT_FOR_MUTATION(jsReentLock, arrayToSpread);
  9796. // At this stage we have an array literal with some arguments to be spread.
  9797. // First we need to calculate the real size of the final literal.
  9798. #if ENABLE_COPYONACCESS_ARRAY
  9799. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(arrayToSpread);
  9800. #endif
  9801. JavascriptArray *array = FromVar(arrayToSpread);
  9802. uint32 arrayLength = array->GetLength();
  9803. uint32 actualLength = arrayLength;
  9804. for (unsigned i = 0; i < spreadIndices->count; ++i)
  9805. {
  9806. JS_REENTRANT(jsReentLock,
  9807. actualLength = UInt32Math::Add(actualLength - 1, GetSpreadArgLen(array->DirectGetItem(spreadIndices->elements[i]), scriptContext)));
  9808. }
  9809. JavascriptArray *result = FromVar(OP_NewScArrayWithMissingValues(actualLength, scriptContext));
  9810. // Now we copy each element and expand the spread parameters inline.
  9811. for (unsigned i = 0, spreadArrIndex = 0, resultIndex = 0; i < arrayLength && resultIndex < actualLength; ++i)
  9812. {
  9813. uint32 spreadIndex = spreadIndices->elements[spreadArrIndex]; // The index of the next element to be spread.
  9814. // An array needs a slow copy if it is a cross-site object or we have missing values that need to be set to undefined.
  9815. auto needArraySlowCopy = [&](Var instance) {
  9816. JavascriptArray *arr = JavascriptOperators::TryFromVar<JavascriptArray>(instance);
  9817. if (arr)
  9818. {
  9819. JS_REENTRANT_UNLOCK(jsReentLock, return arr->IsCrossSiteObject() || arr->IsFillFromPrototypes());
  9820. }
  9821. return false;
  9822. };
  9823. // Designed to have interchangeable arguments with CopyAnyArrayElementsToVar.
  9824. auto slowCopy = [&scriptContext, &needArraySlowCopy
  9825. ](JavascriptArray *dstArray, unsigned dstIndex, Var srcArray, uint32 start, uint32 end) {
  9826. Assert(needArraySlowCopy(srcArray) || ArgumentsObject::Is(srcArray) || TypedArrayBase::Is(srcArray) || JavascriptString::Is(srcArray));
  9827. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  9828. RecyclableObject *propertyObject;
  9829. if (!JavascriptOperators::GetPropertyObject(srcArray, scriptContext, &propertyObject))
  9830. {
  9831. JavascriptError::ThrowTypeError(scriptContext, JSERR_InvalidSpreadArgument);
  9832. }
  9833. for (uint32 j = start; j < end; j++)
  9834. {
  9835. Var element;
  9836. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(srcArray, propertyObject, j, &element, scriptContext));
  9837. if (!gotItem)
  9838. {
  9839. // Copy across missing values as undefined as per 12.2.5.2 SpreadElement : ... AssignmentExpression 5f.
  9840. element = scriptContext->GetLibrary()->GetUndefined();
  9841. }
  9842. dstArray->DirectSetItemAt(dstIndex++, element);
  9843. }
  9844. };
  9845. if (i < spreadIndex)
  9846. {
  9847. // Any non-spread elements can be copied in bulk.
  9848. if (needArraySlowCopy(array))
  9849. {
  9850. slowCopy(result, resultIndex, (Var)array, i, spreadIndex);
  9851. }
  9852. else
  9853. {
  9854. JS_REENTRANT(jsReentLock, CopyAnyArrayElementsToVar(result, resultIndex, array, i, spreadIndex));
  9855. }
  9856. resultIndex += spreadIndex - i;
  9857. i = spreadIndex - 1;
  9858. continue;
  9859. }
  9860. else if (i > spreadIndex)
  9861. {
  9862. // Any non-spread elements terminating the array can also be copied in bulk.
  9863. Assert(spreadArrIndex == spreadIndices->count - 1);
  9864. if (needArraySlowCopy(array))
  9865. {
  9866. slowCopy(result, resultIndex, array, i, arrayLength);
  9867. }
  9868. else
  9869. {
  9870. JS_REENTRANT(jsReentLock, CopyAnyArrayElementsToVar(result, resultIndex, array, i, arrayLength));
  9871. }
  9872. break;
  9873. }
  9874. else
  9875. {
  9876. JS_REENTRANT(jsReentLock, Var instance = array->DirectGetItem(i));
  9877. if (SpreadArgument::Is(instance))
  9878. {
  9879. SpreadArgument* spreadArgument = SpreadArgument::FromVar(instance);
  9880. uint32 len = spreadArgument->GetArgumentSpreadCount();
  9881. const Var* spreadItems = spreadArgument->GetArgumentSpread();
  9882. for (uint32 j = 0; j < len; j++)
  9883. {
  9884. result->DirectSetItemAt(resultIndex++, spreadItems[j]);
  9885. }
  9886. }
  9887. else
  9888. {
  9889. Assert(JavascriptOperators::IsUndefinedObject(instance));
  9890. result->DirectSetItemAt(resultIndex++, instance);
  9891. }
  9892. if (spreadArrIndex < spreadIndices->count - 1)
  9893. {
  9894. spreadArrIndex++;
  9895. }
  9896. }
  9897. }
  9898. AssertMsg(arrayLength == array->GetLength(), "Array's length should not have changed");
  9899. return result;
  9900. }
  9901. uint32 JavascriptArray::GetSpreadArgLen(Var spreadArg, ScriptContext *scriptContext)
  9902. {
  9903. // A spread argument can be anything that returns a 'length' property, even if that
  9904. // property is null or undefined.
  9905. spreadArg = CrossSite::MarshalVar(scriptContext, spreadArg);
  9906. JavascriptArray *arr = JavascriptOperators::TryFromVar<JavascriptArray>(spreadArg);
  9907. if (arr)
  9908. {
  9909. return arr->GetLength();
  9910. }
  9911. TypedArrayBase *tarr = JavascriptOperators::TryFromVar<Js::TypedArrayBase>(spreadArg);
  9912. if (tarr)
  9913. {
  9914. return tarr->GetLength();
  9915. }
  9916. if (SpreadArgument::Is(spreadArg))
  9917. {
  9918. SpreadArgument *spreadFunctionArgs = SpreadArgument::FromVar(spreadArg);
  9919. return spreadFunctionArgs->GetArgumentSpreadCount();
  9920. }
  9921. AssertMsg(false, "LdCustomSpreadIteratorList should have converted the arg to one of the above types");
  9922. Throw::FatalInternalError();
  9923. }
  9924. #ifdef VALIDATE_ARRAY
  9925. class ArraySegmentsVisitor
  9926. {
  9927. private:
  9928. SparseArraySegmentBase* seg;
  9929. public:
  9930. ArraySegmentsVisitor(SparseArraySegmentBase* head)
  9931. : seg(head)
  9932. {
  9933. }
  9934. void operator()(SparseArraySegmentBase* s)
  9935. {
  9936. Assert(seg == s);
  9937. if (seg)
  9938. {
  9939. seg = seg->next;
  9940. }
  9941. }
  9942. };
  9943. void JavascriptArray::ValidateArrayCommon()
  9944. {
  9945. SparseArraySegmentBase * lastUsedSegment = this->GetLastUsedSegment();
  9946. AssertMsg(this != nullptr && head && lastUsedSegment, "Array should not be null");
  9947. AssertMsg(head->left == 0, "Array always should have a segment starting at zero");
  9948. // Simple segments validation
  9949. bool foundLastUsedSegment = false;
  9950. SparseArraySegmentBase *seg = head;
  9951. while(seg != nullptr)
  9952. {
  9953. if (seg == lastUsedSegment)
  9954. {
  9955. foundLastUsedSegment = true;
  9956. }
  9957. AssertMsg(seg->length <= seg->size , "Length greater than size not possible");
  9958. SparseArraySegmentBase* next = seg->next;
  9959. if (next != nullptr)
  9960. {
  9961. AssertMsg(seg->left < next->left, "Segment is adjacent to or overlaps with next segment");
  9962. AssertMsg(seg->size <= (next->left - seg->left), "Segment is adjacent to or overlaps with next segment");
  9963. AssertMsg(!SparseArraySegmentBase::IsLeafSegment(seg, this->GetScriptContext()->GetRecycler()), "Leaf segment with a next pointer");
  9964. }
  9965. else
  9966. {
  9967. AssertMsg(seg->length <= MaxArrayLength - seg->left, "Segment index range overflow");
  9968. AssertMsg(seg->left + seg->length <= this->length, "Segment index range exceeds array length");
  9969. }
  9970. seg = next;
  9971. }
  9972. AssertMsg(foundLastUsedSegment || HasSegmentMap(), "Corrupt lastUsedSegment in array header");
  9973. // Validate segmentMap if present
  9974. if (HasSegmentMap())
  9975. {
  9976. ArraySegmentsVisitor visitor(head);
  9977. GetSegmentMap()->Walk(visitor);
  9978. }
  9979. }
  9980. void JavascriptArray::ValidateArray()
  9981. {
  9982. if (!Js::Configuration::Global.flags.ArrayValidate)
  9983. {
  9984. return;
  9985. }
  9986. ValidateArrayCommon();
  9987. // Detailed segments validation
  9988. JavascriptArray::ValidateVarSegment(SparseArraySegment<Var>::From(head));
  9989. }
  9990. void JavascriptNativeIntArray::ValidateArray()
  9991. {
  9992. if (!Js::Configuration::Global.flags.ArrayValidate)
  9993. {
  9994. #if DBG
  9995. SparseArraySegmentBase *seg = head;
  9996. while (seg)
  9997. {
  9998. if (seg->next != nullptr)
  9999. {
  10000. AssertMsg(!SparseArraySegmentBase::IsLeafSegment(seg, this->GetScriptContext()->GetRecycler()), "Leaf segment with a next pointer");
  10001. }
  10002. seg = seg->next;
  10003. }
  10004. #endif
  10005. return;
  10006. }
  10007. ValidateArrayCommon();
  10008. // Detailed segments validation
  10009. JavascriptArray::ValidateSegment<int32>(SparseArraySegment<int32>::From(head));
  10010. }
  10011. void JavascriptNativeFloatArray::ValidateArray()
  10012. {
  10013. if (!Js::Configuration::Global.flags.ArrayValidate)
  10014. {
  10015. #if DBG
  10016. SparseArraySegmentBase *seg = head;
  10017. while (seg)
  10018. {
  10019. if (seg->next != nullptr)
  10020. {
  10021. AssertMsg(!SparseArraySegmentBase::IsLeafSegment(seg, this->GetScriptContext()->GetRecycler()), "Leaf segment with a next pointer");
  10022. }
  10023. seg = seg->next;
  10024. }
  10025. #endif
  10026. return;
  10027. }
  10028. ValidateArrayCommon();
  10029. // Detailed segments validation
  10030. JavascriptArray::ValidateSegment<double>(SparseArraySegment<double>::From(head));
  10031. }
  10032. void JavascriptArray::ValidateVarSegment(SparseArraySegment<Var>* seg)
  10033. {
  10034. if (!Js::Configuration::Global.flags.ArrayValidate)
  10035. {
  10036. return;
  10037. }
  10038. int32 inspect;
  10039. double inspectDouble;
  10040. while (seg)
  10041. {
  10042. uint32 i = 0;
  10043. for (i = 0; i < seg->length; i++)
  10044. {
  10045. if (SparseArraySegment<Var>::IsMissingItem(&seg->elements[i]))
  10046. {
  10047. continue;
  10048. }
  10049. if (TaggedInt::Is(seg->elements[i]))
  10050. {
  10051. inspect = TaggedInt::ToInt32(seg->elements[i]);
  10052. }
  10053. else if (JavascriptNumber::Is_NoTaggedIntCheck(seg->elements[i]))
  10054. {
  10055. inspectDouble = JavascriptNumber::GetValue(seg->elements[i]);
  10056. }
  10057. else
  10058. {
  10059. AssertMsg(RecyclableObject::Is(seg->elements[i]), "Invalid entry in segment");
  10060. }
  10061. }
  10062. ValidateSegment(seg);
  10063. seg = SparseArraySegment<Var>::From(seg->next);
  10064. }
  10065. }
  10066. template<typename T>
  10067. void JavascriptArray::ValidateSegment(SparseArraySegment<T>* seg)
  10068. {
  10069. if (!Js::Configuration::Global.flags.ArrayValidate)
  10070. {
  10071. return;
  10072. }
  10073. while (seg)
  10074. {
  10075. uint32 i = seg->length;
  10076. while (i < seg->size)
  10077. {
  10078. AssertMsg(SparseArraySegment<T>::IsMissingItem(&seg->elements[i]), "Non missing value the end of the segment");
  10079. i++;
  10080. }
  10081. seg = SparseArraySegment<T>::From(seg->next);
  10082. }
  10083. }
  10084. #endif
  10085. template <typename T>
  10086. void JavascriptArray::InitBoxedInlineSegments(SparseArraySegment<T> * dst, SparseArraySegment<T> * src, bool deepCopy)
  10087. {
  10088. // Don't copy the segment map, we will build it again
  10089. SetFlags(GetFlags() & ~DynamicObjectFlags::HasSegmentMap);
  10090. SetHeadAndLastUsedSegment(dst);
  10091. // Copy head segment data
  10092. dst->left = src->left;
  10093. dst->length = src->length;
  10094. dst->size = src->size;
  10095. dst->CheckLengthvsSize();
  10096. CopyArray(dst->elements, dst->size, src->elements, src->size);
  10097. if (!deepCopy)
  10098. {
  10099. // Without a deep copy, point to the existing next segment
  10100. dst->next = src->next;
  10101. }
  10102. else
  10103. {
  10104. // When deepCopy is true, make a separate copy of each segment. While this involves data
  10105. // duplication, it allows the new object to have a separate lifetime without sharing data.
  10106. AutoDisableInterrupt failFastError(GetScriptContext()->GetThreadContext());
  10107. do
  10108. {
  10109. if (src->next != nullptr)
  10110. {
  10111. // Allocate a new segment in the destination and copy from src
  10112. src = SparseArraySegment<T>::From(src->next);
  10113. dst->next = dst->AllocateSegment(GetRecycler(), src->left, src->length, src->size, src->next);
  10114. dst = SparseArraySegment<T>::From(dst->next);
  10115. CopyArray(dst->elements, dst->size, src->elements, src->size);
  10116. }
  10117. else
  10118. {
  10119. // Terminate the loop
  10120. dst->next = nullptr;
  10121. dst = nullptr;
  10122. }
  10123. } while (dst != nullptr);
  10124. failFastError.Completed();
  10125. }
  10126. }
  10127. JavascriptArray::JavascriptArray(JavascriptArray * instance, bool boxHead, bool deepCopy)
  10128. : ArrayObject(instance)
  10129. {
  10130. if (boxHead)
  10131. {
  10132. InitBoxedInlineSegments(DetermineInlineHeadSegmentPointer<JavascriptArray, 0, true>(this), SparseArraySegment<Var>::From(instance->head), false);
  10133. }
  10134. else
  10135. {
  10136. SetFlags(GetFlags() & ~DynamicObjectFlags::HasSegmentMap);
  10137. head = instance->head;
  10138. SetLastUsedSegment(instance->GetLastUsedSegment());
  10139. }
  10140. }
  10141. template <typename T>
  10142. T * JavascriptArray::BoxStackInstance(T * instance, bool deepCopy)
  10143. {
  10144. Assert(ThreadContext::IsOnStack(instance));
  10145. // On the stack, the we reserved a pointer before the object as to store the boxed value
  10146. T ** boxedInstanceRef = ((T **)instance) - 1;
  10147. T * boxedInstance = *boxedInstanceRef;
  10148. if (boxedInstance)
  10149. {
  10150. return boxedInstance;
  10151. }
  10152. const size_t inlineSlotsSize = instance->GetTypeHandler()->GetInlineSlotsSize();
  10153. if (ThreadContext::IsOnStack(instance->head))
  10154. {
  10155. boxedInstance = RecyclerNewPlusZ(instance->GetRecycler(),
  10156. inlineSlotsSize + sizeof(Js::SparseArraySegmentBase) + instance->head->size * sizeof(typename T::TElement),
  10157. T, instance, true, deepCopy);
  10158. }
  10159. else if(inlineSlotsSize)
  10160. {
  10161. boxedInstance = RecyclerNewPlusZ(instance->GetRecycler(), inlineSlotsSize, T, instance, false, false);
  10162. }
  10163. else
  10164. {
  10165. boxedInstance = RecyclerNew(instance->GetRecycler(), T, instance, false, false);
  10166. }
  10167. *boxedInstanceRef = boxedInstance;
  10168. return boxedInstance;
  10169. }
  10170. JavascriptArray *
  10171. JavascriptArray::BoxStackInstance(JavascriptArray * instance, bool deepCopy)
  10172. {
  10173. return BoxStackInstance<JavascriptArray>(instance, deepCopy);
  10174. }
  10175. #if ENABLE_TTD
  10176. void JavascriptArray::MarkVisitKindSpecificPtrs(TTD::SnapshotExtractor* extractor)
  10177. {
  10178. TTDAssert(this->GetTypeId() == Js::TypeIds_Array || this->GetTypeId() == Js::TypeIds_ES5Array, "Should only be used on basic arrays (or called as super from ES5Array.");
  10179. ScriptContext* ctx = this->GetScriptContext();
  10180. uint32 index = Js::JavascriptArray::InvalidIndex;
  10181. while(true)
  10182. {
  10183. index = this->GetNextIndex(index);
  10184. if(index == Js::JavascriptArray::InvalidIndex) // End of array
  10185. {
  10186. break;
  10187. }
  10188. Js::Var aval = nullptr;
  10189. if(this->DirectGetVarItemAt(index, &aval, ctx))
  10190. {
  10191. extractor->MarkVisitVar(aval);
  10192. }
  10193. }
  10194. }
  10195. void JavascriptArray::ProcessCorePaths()
  10196. {
  10197. TTDAssert(this->GetTypeId() == Js::TypeIds_Array, "Should only be used on basic arrays.");
  10198. ScriptContext* ctx = this->GetScriptContext();
  10199. uint32 index = Js::JavascriptArray::InvalidIndex;
  10200. while(true)
  10201. {
  10202. index = this->GetNextIndex(index);
  10203. if(index == Js::JavascriptArray::InvalidIndex) // End of array
  10204. {
  10205. break;
  10206. }
  10207. Js::Var aval = nullptr;
  10208. if(this->DirectGetVarItemAt(index, &aval, ctx))
  10209. {
  10210. TTD::UtilSupport::TTAutoString pathExt;
  10211. ctx->TTDWellKnownInfo->BuildArrayIndexBuffer(index, pathExt);
  10212. ctx->TTDWellKnownInfo->EnqueueNewPathVarAsNeeded(this, aval, pathExt.GetStrValue());
  10213. }
  10214. }
  10215. }
  10216. TTD::NSSnapObjects::SnapObjectType JavascriptArray::GetSnapTag_TTD() const
  10217. {
  10218. return TTD::NSSnapObjects::SnapObjectType::SnapArrayObject;
  10219. }
  10220. void JavascriptArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  10221. {
  10222. TTDAssert(this->GetTypeId() == Js::TypeIds_Array, "Should only be used on basic Js arrays.");
  10223. TTD::NSSnapObjects::SnapArrayInfo<TTD::TTDVar>* sai = TTD::NSSnapObjects::ExtractArrayValues<TTD::TTDVar>(this, alloc);
  10224. TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayInfo<TTD::TTDVar>*, TTD::NSSnapObjects::SnapObjectType::SnapArrayObject>(objData, sai);
  10225. }
  10226. #endif
  10227. JavascriptNativeArray::JavascriptNativeArray(JavascriptNativeArray * instance) :
  10228. JavascriptArray(instance, false, false),
  10229. weakRefToFuncBody(instance->weakRefToFuncBody)
  10230. {
  10231. }
  10232. JavascriptNativeIntArray::JavascriptNativeIntArray(JavascriptNativeIntArray * instance, bool boxHead, bool deepCopy) :
  10233. JavascriptNativeArray(instance)
  10234. {
  10235. if (boxHead)
  10236. {
  10237. InitBoxedInlineSegments(DetermineInlineHeadSegmentPointer<JavascriptNativeIntArray, 0, true>(this), SparseArraySegment<int>::From(instance->head), deepCopy);
  10238. }
  10239. else
  10240. {
  10241. // Base class ctor should have copied these
  10242. Assert(head == instance->head);
  10243. Assert(segmentUnion.lastUsedSegment == instance->GetLastUsedSegment());
  10244. }
  10245. }
  10246. JavascriptNativeIntArray *
  10247. JavascriptNativeIntArray::BoxStackInstance(JavascriptNativeIntArray * instance, bool deepCopy)
  10248. {
  10249. return JavascriptArray::BoxStackInstance<JavascriptNativeIntArray>(instance, deepCopy);
  10250. }
  10251. #if ENABLE_TTD
  10252. TTD::NSSnapObjects::SnapObjectType JavascriptNativeIntArray::GetSnapTag_TTD() const
  10253. {
  10254. return TTD::NSSnapObjects::SnapObjectType::SnapNativeIntArrayObject;
  10255. }
  10256. void JavascriptNativeIntArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  10257. {
  10258. TTD::NSSnapObjects::SnapArrayInfo<int32>* sai = TTD::NSSnapObjects::ExtractArrayValues<int32>(this, alloc);
  10259. TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayInfo<int32>*, TTD::NSSnapObjects::SnapObjectType::SnapNativeIntArrayObject>(objData, sai);
  10260. }
  10261. #if ENABLE_COPYONACCESS_ARRAY
  10262. TTD::NSSnapObjects::SnapObjectType JavascriptCopyOnAccessNativeIntArray::GetSnapTag_TTD() const
  10263. {
  10264. return TTD::NSSnapObjects::SnapObjectType::Invalid;
  10265. }
  10266. void JavascriptCopyOnAccessNativeIntArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  10267. {
  10268. TTDAssert(false, "Not implemented yet!!!");
  10269. }
  10270. #endif
  10271. #endif
  10272. JavascriptNativeFloatArray::JavascriptNativeFloatArray(JavascriptNativeFloatArray * instance, bool boxHead, bool deepCopy) :
  10273. JavascriptNativeArray(instance)
  10274. {
  10275. if (boxHead)
  10276. {
  10277. InitBoxedInlineSegments(DetermineInlineHeadSegmentPointer<JavascriptNativeFloatArray, 0, true>(this), SparseArraySegment<double>::From(instance->head), deepCopy);
  10278. }
  10279. else
  10280. {
  10281. // Base class ctor should have copied these
  10282. Assert(head == instance->head);
  10283. Assert(segmentUnion.lastUsedSegment == instance->GetLastUsedSegment());
  10284. }
  10285. }
  10286. JavascriptNativeFloatArray *
  10287. JavascriptNativeFloatArray::BoxStackInstance(JavascriptNativeFloatArray * instance, bool deepCopy)
  10288. {
  10289. return JavascriptArray::BoxStackInstance<JavascriptNativeFloatArray>(instance, deepCopy);
  10290. }
  10291. #if ENABLE_TTD
  10292. TTD::NSSnapObjects::SnapObjectType JavascriptNativeFloatArray::GetSnapTag_TTD() const
  10293. {
  10294. return TTD::NSSnapObjects::SnapObjectType::SnapNativeFloatArrayObject;
  10295. }
  10296. void JavascriptNativeFloatArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  10297. {
  10298. TTDAssert(this->GetTypeId() == Js::TypeIds_NativeFloatArray, "Should only be used on native float arrays.");
  10299. TTD::NSSnapObjects::SnapArrayInfo<double>* sai = TTD::NSSnapObjects::ExtractArrayValues<double>(this, alloc);
  10300. TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayInfo<double>*, TTD::NSSnapObjects::SnapObjectType::SnapNativeFloatArrayObject>(objData, sai);
  10301. }
  10302. #endif
  10303. template<typename T>
  10304. RecyclableObject*
  10305. JavascriptArray::ArraySpeciesCreate(Var originalArray, T length, ScriptContext* scriptContext, bool *pIsIntArray, bool *pIsFloatArray, bool *pIsBuiltinArrayCtor)
  10306. {
  10307. if (originalArray == nullptr || !scriptContext->GetConfig()->IsES6SpeciesEnabled())
  10308. {
  10309. return nullptr;
  10310. }
  10311. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  10312. SETOBJECT_FOR_MUTATION(jsReentLock, originalArray);
  10313. if (JavascriptArray::Is(originalArray)
  10314. && !DynamicObject::UnsafeFromVar(originalArray)->GetDynamicType()->GetTypeHandler()->GetIsNotPathTypeHandlerOrHasUserDefinedCtor()
  10315. && DynamicObject::UnsafeFromVar(originalArray)->GetPrototype() == scriptContext->GetLibrary()->GetArrayPrototype()
  10316. && !scriptContext->GetLibrary()->GetArrayObjectHasUserDefinedSpecies())
  10317. {
  10318. return nullptr;
  10319. }
  10320. Var constructor = scriptContext->GetLibrary()->GetUndefined();
  10321. if (JavascriptOperators::IsArray(originalArray))
  10322. {
  10323. JS_REENTRANT(jsReentLock, BOOL getProp = JavascriptOperators::GetProperty(RecyclableObject::UnsafeFromVar(originalArray), PropertyIds::constructor, &constructor, scriptContext));
  10324. if (!getProp)
  10325. {
  10326. return nullptr;
  10327. }
  10328. if (JavascriptOperators::IsConstructor(constructor))
  10329. {
  10330. ScriptContext* constructorScriptContext = RecyclableObject::UnsafeFromVar(constructor)->GetScriptContext();
  10331. if (constructorScriptContext != scriptContext)
  10332. {
  10333. if (constructorScriptContext->GetLibrary()->GetArrayConstructor() == constructor)
  10334. {
  10335. constructor = scriptContext->GetLibrary()->GetUndefined();
  10336. }
  10337. }
  10338. }
  10339. if (JavascriptOperators::IsObject(constructor))
  10340. {
  10341. JS_REENTRANT(jsReentLock, getProp = JavascriptOperators::GetProperty((RecyclableObject*)constructor, PropertyIds::_symbolSpecies, &constructor, scriptContext));
  10342. if (!getProp)
  10343. {
  10344. if (pIsBuiltinArrayCtor != nullptr)
  10345. {
  10346. *pIsBuiltinArrayCtor = false;
  10347. }
  10348. return nullptr;
  10349. }
  10350. if (constructor == scriptContext->GetLibrary()->GetNull())
  10351. {
  10352. constructor = scriptContext->GetLibrary()->GetUndefined();
  10353. }
  10354. }
  10355. }
  10356. if (constructor == scriptContext->GetLibrary()->GetUndefined() || constructor == scriptContext->GetLibrary()->GetArrayConstructor())
  10357. {
  10358. if (length > UINT_MAX)
  10359. {
  10360. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  10361. }
  10362. if (nullptr == pIsIntArray)
  10363. {
  10364. return scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(length));
  10365. }
  10366. else
  10367. {
  10368. // If the constructor function is the built-in Array constructor, we can be smart and create the right type of native array.
  10369. JavascriptArray* pArr = JavascriptArray::FromVar(originalArray);
  10370. pArr->GetArrayTypeAndConvert(pIsIntArray, pIsFloatArray);
  10371. return CreateNewArrayHelper(static_cast<uint32>(length), *pIsIntArray, *pIsFloatArray, pArr, scriptContext);
  10372. }
  10373. }
  10374. if (!JavascriptOperators::IsConstructor(constructor))
  10375. {
  10376. JavascriptError::ThrowTypeError(scriptContext, JSERR_NotAConstructor, _u("constructor[Symbol.species]"));
  10377. }
  10378. if (pIsBuiltinArrayCtor != nullptr)
  10379. {
  10380. *pIsBuiltinArrayCtor = false;
  10381. }
  10382. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(length, scriptContext) };
  10383. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  10384. AssertOrFailFast(Js::RecyclableObject::Is(constructor));
  10385. ThreadContext* threadContext = scriptContext->GetThreadContext();
  10386. Var scObject = threadContext->ExecuteImplicitCall((RecyclableObject*)constructor, ImplicitCall_Accessor, [&]()->Js::Var
  10387. {
  10388. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext));
  10389. });
  10390. return RecyclableObject::FromVar(scObject);
  10391. }
  10392. /*static*/
  10393. PropertyId const JavascriptArray::specialPropertyIds[] =
  10394. {
  10395. PropertyIds::length
  10396. };
  10397. BOOL JavascriptArray::DeleteProperty(PropertyId propertyId, PropertyOperationFlags flags)
  10398. {
  10399. if (propertyId == PropertyIds::length)
  10400. {
  10401. return false;
  10402. }
  10403. return DynamicObject::DeleteProperty(propertyId, flags);
  10404. }
  10405. BOOL JavascriptArray::DeleteProperty(JavascriptString *propertyNameString, PropertyOperationFlags flags)
  10406. {
  10407. JsUtil::CharacterBuffer<WCHAR> propertyName(propertyNameString->GetString(), propertyNameString->GetLength());
  10408. if (BuiltInPropertyRecords::length.Equals(propertyName))
  10409. {
  10410. return false;
  10411. }
  10412. return DynamicObject::DeleteProperty(propertyNameString, flags);
  10413. }
  10414. PropertyQueryFlags JavascriptArray::HasPropertyQuery(PropertyId propertyId)
  10415. {
  10416. if (propertyId == PropertyIds::length)
  10417. {
  10418. return PropertyQueryFlags::Property_Found;
  10419. }
  10420. ScriptContext* scriptContext = GetScriptContext();
  10421. uint32 index;
  10422. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10423. {
  10424. return JavascriptConversion::BooleanToPropertyQueryFlags(this->HasItem(index));
  10425. }
  10426. return DynamicObject::HasPropertyQuery(propertyId);
  10427. }
  10428. BOOL JavascriptArray::IsEnumerable(PropertyId propertyId)
  10429. {
  10430. if (propertyId == PropertyIds::length)
  10431. {
  10432. return false;
  10433. }
  10434. return DynamicObject::IsEnumerable(propertyId);
  10435. }
  10436. BOOL JavascriptArray::IsConfigurable(PropertyId propertyId)
  10437. {
  10438. if (propertyId == PropertyIds::length)
  10439. {
  10440. return false;
  10441. }
  10442. return DynamicObject::IsConfigurable(propertyId);
  10443. }
  10444. //
  10445. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10446. // handling and only check instance objectArray for numeric propertyIds.
  10447. //
  10448. BOOL JavascriptArray::SetEnumerable(PropertyId propertyId, BOOL value)
  10449. {
  10450. if (propertyId == PropertyIds::length)
  10451. {
  10452. Assert(!value); // Can't change array length enumerable
  10453. return true;
  10454. }
  10455. ScriptContext* scriptContext = this->GetScriptContext();
  10456. uint32 index;
  10457. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10458. {
  10459. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10460. ->SetEnumerable(this, propertyId, value);
  10461. }
  10462. return __super::SetEnumerable(propertyId, value);
  10463. }
  10464. //
  10465. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10466. // handling and only check instance objectArray for numeric propertyIds.
  10467. //
  10468. BOOL JavascriptArray::SetWritable(PropertyId propertyId, BOOL value)
  10469. {
  10470. ScriptContext* scriptContext = this->GetScriptContext();
  10471. uint32 index;
  10472. bool setLengthNonWritable = (propertyId == PropertyIds::length && !value);
  10473. if (setLengthNonWritable || scriptContext->IsNumericPropertyId(propertyId, &index))
  10474. {
  10475. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10476. ->SetWritable(this, propertyId, value);
  10477. }
  10478. return __super::SetWritable(propertyId, value);
  10479. }
  10480. //
  10481. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10482. // handling and only check instance objectArray for numeric propertyIds.
  10483. //
  10484. BOOL JavascriptArray::SetConfigurable(PropertyId propertyId, BOOL value)
  10485. {
  10486. if (propertyId == PropertyIds::length)
  10487. {
  10488. Assert(!value); // Can't change array length configurable
  10489. return true;
  10490. }
  10491. ScriptContext* scriptContext = this->GetScriptContext();
  10492. uint32 index;
  10493. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10494. {
  10495. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10496. ->SetConfigurable(this, propertyId, value);
  10497. }
  10498. return __super::SetConfigurable(propertyId, value);
  10499. }
  10500. //
  10501. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10502. // handling and only check instance objectArray for numeric propertyIds.
  10503. //
  10504. BOOL JavascriptArray::SetAttributes(PropertyId propertyId, PropertyAttributes attributes)
  10505. {
  10506. ScriptContext* scriptContext = this->GetScriptContext();
  10507. // SetAttributes on "length" is not expected. DefineOwnProperty uses SetWritable. If this is
  10508. // changed, we need to handle it here.
  10509. Assert(propertyId != PropertyIds::length);
  10510. uint32 index;
  10511. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10512. {
  10513. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10514. ->SetItemAttributes(this, index, attributes);
  10515. }
  10516. return __super::SetAttributes(propertyId, attributes);
  10517. }
  10518. //
  10519. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10520. // handling and only check instance objectArray for numeric propertyIds.
  10521. //
  10522. BOOL JavascriptArray::SetAccessors(PropertyId propertyId, Var getter, Var setter, PropertyOperationFlags flags)
  10523. {
  10524. ScriptContext* scriptContext = this->GetScriptContext();
  10525. uint32 index;
  10526. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10527. {
  10528. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10529. ->SetItemAccessors(this, index, getter, setter);
  10530. }
  10531. return __super::SetAccessors(propertyId, getter, setter, flags);
  10532. }
  10533. //
  10534. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10535. // handling and only check instance objectArray for numeric propertyIds.
  10536. //
  10537. BOOL JavascriptArray::SetItemWithAttributes(uint32 index, Var value, PropertyAttributes attributes)
  10538. {
  10539. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10540. ->SetItemWithAttributes(this, index, value, attributes);
  10541. }
  10542. //
  10543. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10544. // handling and only check instance objectArray for numeric propertyIds.
  10545. //
  10546. BOOL JavascriptArray::SetItemAttributes(uint32 index, PropertyAttributes attributes)
  10547. {
  10548. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10549. ->SetItemAttributes(this, index, attributes);
  10550. }
  10551. //
  10552. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10553. // handling and only check instance objectArray for numeric propertyIds.
  10554. //
  10555. BOOL JavascriptArray::SetItemAccessors(uint32 index, Var getter, Var setter)
  10556. {
  10557. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10558. ->SetItemAccessors(this, index, getter, setter);
  10559. }
  10560. // Check if this objectArray isFrozen.
  10561. BOOL JavascriptArray::IsObjectArrayFrozen()
  10562. {
  10563. // If this is still a JavascriptArray, it's not frozen.
  10564. return false;
  10565. }
  10566. JavascriptEnumerator * JavascriptArray::GetIndexEnumerator(EnumeratorFlags flags, ScriptContext* requestContext)
  10567. {
  10568. #if ENABLE_COPYONACCESS_ARRAY
  10569. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10570. #endif
  10571. if (!!(flags & EnumeratorFlags::SnapShotSemantics))
  10572. {
  10573. return RecyclerNew(GetRecycler(), JavascriptArrayIndexSnapshotEnumerator, this, flags, requestContext);
  10574. }
  10575. return RecyclerNew(GetRecycler(), JavascriptArrayIndexEnumerator, this, flags, requestContext);
  10576. }
  10577. BOOL JavascriptArray::GetNonIndexEnumerator(JavascriptStaticEnumerator * enumerator, ScriptContext* requestContext)
  10578. {
  10579. #if ENABLE_COPYONACCESS_ARRAY
  10580. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10581. #endif
  10582. return enumerator->Initialize(nullptr, nullptr, this, EnumeratorFlags::SnapShotSemantics, requestContext, nullptr);
  10583. }
  10584. BOOL JavascriptArray::IsItemEnumerable(uint32 index)
  10585. {
  10586. return true;
  10587. }
  10588. //
  10589. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10590. // handling and only check instance objectArray for numeric propertyIds.
  10591. //
  10592. BOOL JavascriptArray::PreventExtensions()
  10593. {
  10594. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)->PreventExtensions(this);
  10595. }
  10596. //
  10597. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10598. // handling and only check instance objectArray for numeric propertyIds.
  10599. //
  10600. BOOL JavascriptArray::Seal()
  10601. {
  10602. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)->Seal(this);
  10603. }
  10604. //
  10605. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10606. // handling and only check instance objectArray for numeric propertyIds.
  10607. //
  10608. BOOL JavascriptArray::Freeze()
  10609. {
  10610. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)->Freeze(this);
  10611. }
  10612. BOOL JavascriptArray::GetSpecialPropertyName(uint32 index, JavascriptString ** propertyName, ScriptContext * requestContext)
  10613. {
  10614. if (index == 0)
  10615. {
  10616. *propertyName = requestContext->GetPropertyString(PropertyIds::length);
  10617. return true;
  10618. }
  10619. return false;
  10620. }
  10621. // Returns the number of special non-enumerable properties this type has.
  10622. uint JavascriptArray::GetSpecialPropertyCount() const
  10623. {
  10624. return _countof(specialPropertyIds);
  10625. }
  10626. // Returns the list of special non-enumerable properties for the type.
  10627. PropertyId const * JavascriptArray::GetSpecialPropertyIds() const
  10628. {
  10629. return specialPropertyIds;
  10630. }
  10631. PropertyQueryFlags JavascriptArray::GetPropertyReferenceQuery(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  10632. {
  10633. return JavascriptArray::GetPropertyQuery(originalInstance, propertyId, value, info, requestContext);
  10634. }
  10635. PropertyQueryFlags JavascriptArray::GetPropertyQuery(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  10636. {
  10637. if (GetPropertyBuiltIns(propertyId, value))
  10638. {
  10639. return PropertyQueryFlags::Property_Found;
  10640. }
  10641. ScriptContext* scriptContext = GetScriptContext();
  10642. uint32 index;
  10643. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10644. {
  10645. return JavascriptConversion::BooleanToPropertyQueryFlags(this->GetItem(this, index, value, scriptContext));
  10646. }
  10647. return DynamicObject::GetPropertyQuery(originalInstance, propertyId, value, info, requestContext);
  10648. }
  10649. PropertyQueryFlags JavascriptArray::GetPropertyQuery(Var originalInstance, JavascriptString* propertyNameString, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  10650. {
  10651. AssertMsg(!PropertyRecord::IsPropertyNameNumeric(propertyNameString->GetString(), propertyNameString->GetLength()),
  10652. "Numeric property names should have been converted to uint or PropertyRecord*");
  10653. PropertyRecord const* propertyRecord;
  10654. this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
  10655. if (propertyRecord != nullptr && GetPropertyBuiltIns(propertyRecord->GetPropertyId(), value))
  10656. {
  10657. return PropertyQueryFlags::Property_Found;
  10658. }
  10659. return DynamicObject::GetPropertyQuery(originalInstance, propertyNameString, value, info, requestContext);
  10660. }
  10661. BOOL JavascriptArray::GetPropertyBuiltIns(PropertyId propertyId, Var* value)
  10662. {
  10663. //
  10664. // length being accessed. Return array length
  10665. //
  10666. if (propertyId == PropertyIds::length)
  10667. {
  10668. *value = JavascriptNumber::ToVar(this->GetLength(), GetScriptContext());
  10669. return true;
  10670. }
  10671. return false;
  10672. }
  10673. PropertyQueryFlags JavascriptArray::HasItemQuery(uint32 index)
  10674. {
  10675. Var value;
  10676. return JavascriptConversion::BooleanToPropertyQueryFlags(this->DirectGetItemAt<Var>(index, &value));
  10677. }
  10678. PropertyQueryFlags JavascriptArray::GetItemQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10679. {
  10680. return JavascriptConversion::BooleanToPropertyQueryFlags(this->DirectGetItemAt<Var>(index, value));
  10681. }
  10682. PropertyQueryFlags JavascriptArray::GetItemReferenceQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10683. {
  10684. return JavascriptConversion::BooleanToPropertyQueryFlags(this->DirectGetItemAt<Var>(index, value));
  10685. }
  10686. BOOL JavascriptArray::DirectGetVarItemAt(uint32 index, Var *value, ScriptContext *requestContext)
  10687. {
  10688. return this->DirectGetItemAt<Var>(index, value);
  10689. }
  10690. PropertyQueryFlags JavascriptNativeIntArray::HasItemQuery(uint32 index)
  10691. {
  10692. #if ENABLE_COPYONACCESS_ARRAY
  10693. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10694. #endif
  10695. int32 value;
  10696. return JavascriptConversion::BooleanToPropertyQueryFlags(this->DirectGetItemAt<int32>(index, &value));
  10697. }
  10698. PropertyQueryFlags JavascriptNativeFloatArray::HasItemQuery(uint32 index)
  10699. {
  10700. double dvalue;
  10701. return JavascriptConversion::BooleanToPropertyQueryFlags(this->DirectGetItemAt<double>(index, &dvalue));
  10702. }
  10703. PropertyQueryFlags JavascriptNativeIntArray::GetItemQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10704. {
  10705. #if ENABLE_COPYONACCESS_ARRAY
  10706. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10707. #endif
  10708. return JavascriptConversion::BooleanToPropertyQueryFlags(JavascriptNativeIntArray::DirectGetVarItemAt(index, value, requestContext));
  10709. }
  10710. BOOL JavascriptNativeIntArray::DirectGetVarItemAt(uint32 index, Var *value, ScriptContext *requestContext)
  10711. {
  10712. int32 intvalue;
  10713. if (!this->DirectGetItemAt<int32>(index, &intvalue))
  10714. {
  10715. return FALSE;
  10716. }
  10717. *value = JavascriptNumber::ToVar(intvalue, requestContext);
  10718. return TRUE;
  10719. }
  10720. PropertyQueryFlags JavascriptNativeIntArray::GetItemReferenceQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10721. {
  10722. return JavascriptNativeIntArray::GetItemQuery(originalInstance, index, value, requestContext);
  10723. }
  10724. PropertyQueryFlags JavascriptNativeFloatArray::GetItemQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10725. {
  10726. return JavascriptConversion::BooleanToPropertyQueryFlags(JavascriptNativeFloatArray::DirectGetVarItemAt(index, value, requestContext));
  10727. }
  10728. BOOL JavascriptNativeFloatArray::DirectGetVarItemAt(uint32 index, Var *value, ScriptContext *requestContext)
  10729. {
  10730. double dvalue;
  10731. int32 ivalue;
  10732. if (!this->DirectGetItemAt<double>(index, &dvalue))
  10733. {
  10734. return FALSE;
  10735. }
  10736. if (*(uint64*)&dvalue == 0ull)
  10737. {
  10738. *value = TaggedInt::ToVarUnchecked(0);
  10739. }
  10740. else if (JavascriptNumber::TryGetInt32Value(dvalue, &ivalue) && !TaggedInt::IsOverflow(ivalue))
  10741. {
  10742. *value = TaggedInt::ToVarUnchecked(ivalue);
  10743. }
  10744. else
  10745. {
  10746. *value = JavascriptNumber::ToVarWithCheck(dvalue, requestContext);
  10747. }
  10748. return TRUE;
  10749. }
  10750. PropertyQueryFlags JavascriptNativeFloatArray::GetItemReferenceQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10751. {
  10752. return JavascriptNativeFloatArray::GetItemQuery(originalInstance, index, value, requestContext);
  10753. }
  10754. BOOL JavascriptArray::SetProperty(PropertyId propertyId, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)
  10755. {
  10756. #if ENABLE_COPYONACCESS_ARRAY
  10757. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10758. #endif
  10759. uint32 indexValue;
  10760. if (propertyId == PropertyIds::length)
  10761. {
  10762. return this->SetLength(value);
  10763. }
  10764. else if (GetScriptContext()->IsNumericPropertyId(propertyId, &indexValue))
  10765. {
  10766. // Call this or subclass method
  10767. return SetItem(indexValue, value, flags);
  10768. }
  10769. else
  10770. {
  10771. return DynamicObject::SetProperty(propertyId, value, flags, info);
  10772. }
  10773. }
  10774. BOOL JavascriptArray::SetProperty(JavascriptString* propertyNameString, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)
  10775. {
  10776. AssertMsg(!PropertyRecord::IsPropertyNameNumeric(propertyNameString->GetString(), propertyNameString->GetLength()),
  10777. "Numeric property names should have been converted to uint or PropertyRecord*");
  10778. #if ENABLE_COPYONACCESS_ARRAY
  10779. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10780. #endif
  10781. PropertyRecord const* propertyRecord;
  10782. this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
  10783. if (propertyRecord != nullptr && propertyRecord->GetPropertyId() == PropertyIds::length)
  10784. {
  10785. return this->SetLength(value);
  10786. }
  10787. return DynamicObject::SetProperty(propertyNameString, value, flags, info);
  10788. }
  10789. BOOL JavascriptArray::SetPropertyWithAttributes(PropertyId propertyId, Var value, PropertyAttributes attributes, PropertyValueInfo* info, PropertyOperationFlags flags, SideEffects possibleSideEffects)
  10790. {
  10791. #if ENABLE_COPYONACCESS_ARRAY
  10792. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10793. #endif
  10794. ScriptContext* scriptContext = GetScriptContext();
  10795. if (propertyId == PropertyIds::length)
  10796. {
  10797. Assert(attributes == PropertyWritable);
  10798. Assert(IsWritable(propertyId) && !IsConfigurable(propertyId) && !IsEnumerable(propertyId));
  10799. return this->SetLength(value);
  10800. }
  10801. uint32 index;
  10802. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10803. {
  10804. // Call this or subclass method
  10805. return SetItemWithAttributes(index, value, attributes);
  10806. }
  10807. return __super::SetPropertyWithAttributes(propertyId, value, attributes, info, flags, possibleSideEffects);
  10808. }
  10809. BOOL JavascriptArray::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
  10810. {
  10811. this->DirectSetItemAt(index, value);
  10812. return true;
  10813. }
  10814. BOOL JavascriptNativeIntArray::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
  10815. {
  10816. int32 iValue;
  10817. double dValue;
  10818. #if ENABLE_COPYONACCESS_ARRAY
  10819. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10820. #endif
  10821. TypeId typeId = this->TrySetNativeIntArrayItem(value, &iValue, &dValue);
  10822. if (typeId == TypeIds_NativeIntArray)
  10823. {
  10824. this->SetItem(index, iValue);
  10825. }
  10826. else if (typeId == TypeIds_NativeFloatArray)
  10827. {
  10828. reinterpret_cast<JavascriptNativeFloatArray*>(this)->DirectSetItemAt<double>(index, dValue);
  10829. }
  10830. else
  10831. {
  10832. this->DirectSetItemAt<Var>(index, value);
  10833. }
  10834. return TRUE;
  10835. }
  10836. TypeId JavascriptNativeIntArray::TrySetNativeIntArrayItem(Var value, int32 *iValue, double *dValue)
  10837. {
  10838. if (TaggedInt::Is(value))
  10839. {
  10840. int32 i = TaggedInt::ToInt32(value);
  10841. if (i != JavascriptNativeIntArray::MissingItem)
  10842. {
  10843. *iValue = i;
  10844. return TypeIds_NativeIntArray;
  10845. }
  10846. }
  10847. if (JavascriptNumber::Is_NoTaggedIntCheck(value))
  10848. {
  10849. bool isInt32;
  10850. int32 i;
  10851. double d = JavascriptNumber::GetValue(value);
  10852. if (JavascriptNumber::TryGetInt32OrUInt32Value(d, &i, &isInt32))
  10853. {
  10854. if (isInt32 && i != JavascriptNativeIntArray::MissingItem)
  10855. {
  10856. *iValue = i;
  10857. return TypeIds_NativeIntArray;
  10858. }
  10859. }
  10860. else
  10861. {
  10862. *dValue = d;
  10863. JavascriptNativeIntArray::ToNativeFloatArray(this);
  10864. return TypeIds_NativeFloatArray;
  10865. }
  10866. }
  10867. JavascriptNativeIntArray::ToVarArray(this);
  10868. return TypeIds_Array;
  10869. }
  10870. BOOL JavascriptNativeIntArray::SetItem(uint32 index, int32 iValue)
  10871. {
  10872. if (iValue == JavascriptNativeIntArray::MissingItem)
  10873. {
  10874. JavascriptArray *varArr = JavascriptNativeIntArray::ToVarArray(this);
  10875. varArr->DirectSetItemAt(index, JavascriptNumber::ToVar(iValue, GetScriptContext()));
  10876. return TRUE;
  10877. }
  10878. this->DirectSetItemAt(index, iValue);
  10879. return TRUE;
  10880. }
  10881. BOOL JavascriptNativeFloatArray::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
  10882. {
  10883. double dValue;
  10884. TypeId typeId = this->TrySetNativeFloatArrayItem(value, &dValue);
  10885. if (typeId == TypeIds_NativeFloatArray)
  10886. {
  10887. this->SetItem(index, dValue);
  10888. }
  10889. else
  10890. {
  10891. this->DirectSetItemAt(index, value);
  10892. }
  10893. return TRUE;
  10894. }
  10895. TypeId JavascriptNativeFloatArray::TrySetNativeFloatArrayItem(Var value, double *dValue)
  10896. {
  10897. if (TaggedInt::Is(value))
  10898. {
  10899. *dValue = (double)TaggedInt::ToInt32(value);
  10900. return TypeIds_NativeFloatArray;
  10901. }
  10902. else if (JavascriptNumber::Is_NoTaggedIntCheck(value))
  10903. {
  10904. *dValue = JavascriptNumber::GetValue(value);
  10905. return TypeIds_NativeFloatArray;
  10906. }
  10907. JavascriptNativeFloatArray::ToVarArray(this);
  10908. return TypeIds_Array;
  10909. }
  10910. BOOL JavascriptNativeFloatArray::SetItem(uint32 index, double dValue)
  10911. {
  10912. if (*(uint64*)&dValue == *(uint64*)&JavascriptNativeFloatArray::MissingItem)
  10913. {
  10914. JavascriptArray *varArr = JavascriptNativeFloatArray::ToVarArray(this);
  10915. varArr->DirectSetItemAt(index, JavascriptNumber::ToVarNoCheck(dValue, GetScriptContext()));
  10916. return TRUE;
  10917. }
  10918. this->DirectSetItemAt<double>(index, dValue);
  10919. return TRUE;
  10920. }
  10921. BOOL JavascriptArray::DeleteItem(uint32 index, PropertyOperationFlags flags)
  10922. {
  10923. return this->DirectDeleteItemAt<Var>(index);
  10924. }
  10925. BOOL JavascriptNativeIntArray::DeleteItem(uint32 index, PropertyOperationFlags flags)
  10926. {
  10927. return this->DirectDeleteItemAt<int32>(index);
  10928. }
  10929. BOOL JavascriptNativeFloatArray::DeleteItem(uint32 index, PropertyOperationFlags flags)
  10930. {
  10931. return this->DirectDeleteItemAt<double>(index);
  10932. }
  10933. BOOL JavascriptArray::GetEnumerator(JavascriptStaticEnumerator * enumerator, EnumeratorFlags flags, ScriptContext* requestContext, ForInCache * forInCache)
  10934. {
  10935. #if ENABLE_COPYONACCESS_ARRAY
  10936. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10937. #endif
  10938. return enumerator->Initialize(nullptr, this, this, flags, requestContext, forInCache);
  10939. }
  10940. BOOL JavascriptArray::GetDiagValueString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext)
  10941. {
  10942. stringBuilder->Append(_u('['));
  10943. if (this->length < 10)
  10944. {
  10945. auto funcPtr = [&]()
  10946. {
  10947. ENTER_PINNED_SCOPE(JavascriptString, valueStr);
  10948. valueStr = JavascriptArray::JoinHelper(this, GetLibrary()->GetCommaDisplayString(), requestContext);
  10949. stringBuilder->Append(valueStr->GetString(), valueStr->GetLength());
  10950. LEAVE_PINNED_SCOPE();
  10951. };
  10952. if (!requestContext->GetThreadContext()->IsScriptActive())
  10953. {
  10954. BEGIN_JS_RUNTIME_CALL(requestContext);
  10955. {
  10956. funcPtr();
  10957. }
  10958. END_JS_RUNTIME_CALL(requestContext);
  10959. }
  10960. else
  10961. {
  10962. funcPtr();
  10963. }
  10964. }
  10965. else
  10966. {
  10967. stringBuilder->AppendCppLiteral(_u("..."));
  10968. }
  10969. stringBuilder->Append(_u(']'));
  10970. return TRUE;
  10971. }
  10972. BOOL JavascriptArray::GetDiagTypeString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext)
  10973. {
  10974. stringBuilder->AppendCppLiteral(_u("Object, (Array)"));
  10975. return TRUE;
  10976. }
  10977. bool JavascriptNativeArray::Is(Var aValue)
  10978. {
  10979. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  10980. return JavascriptNativeArray::Is(typeId);
  10981. }
  10982. bool JavascriptNativeArray::Is(TypeId typeId)
  10983. {
  10984. return JavascriptNativeIntArray::Is(typeId) || JavascriptNativeFloatArray::Is(typeId);
  10985. }
  10986. JavascriptNativeArray* JavascriptNativeArray::FromVar(Var aValue)
  10987. {
  10988. AssertOrFailFastMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeArray'");
  10989. return static_cast<JavascriptNativeArray *>(aValue);
  10990. }
  10991. JavascriptNativeArray* JavascriptNativeArray::UnsafeFromVar(Var aValue)
  10992. {
  10993. AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeArray'");
  10994. return static_cast<JavascriptNativeArray *>(aValue);
  10995. }
  10996. bool JavascriptNativeIntArray::Is(Var aValue)
  10997. {
  10998. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  10999. return JavascriptNativeIntArray::Is(typeId);
  11000. }
  11001. #if ENABLE_COPYONACCESS_ARRAY
  11002. bool JavascriptCopyOnAccessNativeIntArray::Is(Var aValue)
  11003. {
  11004. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  11005. return JavascriptCopyOnAccessNativeIntArray::Is(typeId);
  11006. }
  11007. #endif
  11008. bool JavascriptNativeIntArray::Is(TypeId typeId)
  11009. {
  11010. return typeId == TypeIds_NativeIntArray;
  11011. }
  11012. #if ENABLE_COPYONACCESS_ARRAY
  11013. bool JavascriptCopyOnAccessNativeIntArray::Is(TypeId typeId)
  11014. {
  11015. return typeId == TypeIds_CopyOnAccessNativeIntArray;
  11016. }
  11017. #endif
  11018. bool JavascriptNativeIntArray::IsNonCrossSite(Var aValue)
  11019. {
  11020. bool ret = !TaggedInt::Is(aValue) && VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(aValue);
  11021. Assert(ret == (JavascriptNativeIntArray::Is(aValue) && !JavascriptNativeIntArray::FromVar(aValue)->IsCrossSiteObject()));
  11022. return ret;
  11023. }
  11024. JavascriptNativeIntArray* JavascriptNativeIntArray::FromVar(Var aValue)
  11025. {
  11026. AssertOrFailFastMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeIntArray'");
  11027. return static_cast<JavascriptNativeIntArray *>(aValue);
  11028. }
  11029. JavascriptNativeIntArray* JavascriptNativeIntArray::UnsafeFromVar(Var aValue)
  11030. {
  11031. AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeIntArray'");
  11032. return static_cast<JavascriptNativeIntArray *>(aValue);
  11033. }
  11034. #if ENABLE_COPYONACCESS_ARRAY
  11035. JavascriptCopyOnAccessNativeIntArray* JavascriptCopyOnAccessNativeIntArray::FromVar(Var aValue)
  11036. {
  11037. AssertOrFailFastMsg(Is(aValue), "Ensure var is actually a 'JavascriptCopyOnAccessNativeIntArray'");
  11038. return static_cast<JavascriptCopyOnAccessNativeIntArray *>(aValue);
  11039. }
  11040. JavascriptCopyOnAccessNativeIntArray* JavascriptCopyOnAccessNativeIntArray::UnsafeFromVar(Var aValue)
  11041. {
  11042. AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptCopyOnAccessNativeIntArray'");
  11043. return static_cast<JavascriptCopyOnAccessNativeIntArray *>(aValue);
  11044. }
  11045. #endif
  11046. bool JavascriptNativeFloatArray::Is(Var aValue)
  11047. {
  11048. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  11049. return JavascriptNativeFloatArray::Is(typeId);
  11050. }
  11051. bool JavascriptNativeFloatArray::Is(TypeId typeId)
  11052. {
  11053. return typeId == TypeIds_NativeFloatArray;
  11054. }
  11055. bool JavascriptNativeFloatArray::IsNonCrossSite(Var aValue)
  11056. {
  11057. bool ret = !TaggedInt::Is(aValue) && VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(aValue);
  11058. Assert(ret == (JavascriptNativeFloatArray::Is(aValue) && !JavascriptNativeFloatArray::FromVar(aValue)->IsCrossSiteObject()));
  11059. return ret;
  11060. }
  11061. JavascriptNativeFloatArray* JavascriptNativeFloatArray::FromVar(Var aValue)
  11062. {
  11063. AssertOrFailFastMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeFloatArray'");
  11064. return static_cast<JavascriptNativeFloatArray *>(RecyclableObject::FromVar(aValue));
  11065. }
  11066. JavascriptNativeFloatArray* JavascriptNativeFloatArray::UnsafeFromVar(Var aValue)
  11067. {
  11068. AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeFloatArray'");
  11069. return static_cast<JavascriptNativeFloatArray *>(RecyclableObject::UnsafeFromVar(aValue));
  11070. }
  11071. template int Js::JavascriptArray::GetParamForIndexOf<unsigned int>(unsigned int, Js::Arguments const&, void*&, unsigned int&, Js::ScriptContext*);
  11072. template bool Js::JavascriptArray::ArrayElementEnumerator::MoveNext<void*>();
  11073. template void Js::JavascriptArray::SetArrayLiteralItem<void*>(unsigned int, void*);
  11074. template void* Js::JavascriptArray::TemplatedIndexOfHelper<false, Js::TypedArrayBase, unsigned int>(Js::TypedArrayBase*, void*, unsigned int, unsigned int, Js::ScriptContext*);
  11075. template void* Js::JavascriptArray::TemplatedIndexOfHelper<true, Js::TypedArrayBase, unsigned int>(Js::TypedArrayBase*, void*, unsigned int, unsigned int, Js::ScriptContext*);
  11076. } //namespace Js