JavascriptArray.cpp 486 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "RuntimeLibraryPch.h"
  6. #include "Types/PathTypeHandler.h"
  7. #include "Types/SpreadArgument.h"
  8. // TODO: Change this generic fatal error to the descriptive one.
  9. #define AssertAndFailFast(x) if (!(x)) { Assert(x); Js::Throw::FatalInternalError(); }
  10. namespace Js
  11. {
  12. // Make sure EmptySegment points to read-only memory.
  13. // Can't do this the easy way because SparseArraySegment has a constructor...
  14. static const char EmptySegmentData[sizeof(SparseArraySegmentBase)] = {0};
  15. const SparseArraySegmentBase *JavascriptArray::EmptySegment = (SparseArraySegmentBase *)&EmptySegmentData;
  16. // col0 : allocation bucket
  17. // col1 : No. of missing items to set during initialization depending on bucket.
  18. // col2 : allocation size for elements in given bucket.
  19. // col1 and col2 is calculated at runtime
  20. uint JavascriptNativeFloatArray::allocationBuckets[][AllocationBucketsInfoSize] =
  21. {
  22. { 3, 0, 0 }, // allocate space for 3 elements for array of length 0,1,2,3
  23. { 5, 0, 0 }, // allocate space for 5 elements for array of length 4,5
  24. { 8, 0, 0 }, // allocate space for 8 elements for array of length 6,7,8
  25. };
  26. #if defined(_M_X64_OR_ARM64)
  27. const Var JavascriptArray::MissingItem = (Var)0x8000000280000002;
  28. uint JavascriptNativeIntArray::allocationBuckets[][AllocationBucketsInfoSize] =
  29. {
  30. // See comments above on how to read this
  31. {2, 0, 0},
  32. {6, 0, 0},
  33. {8, 0, 0},
  34. };
  35. uint JavascriptArray::allocationBuckets[][AllocationBucketsInfoSize] =
  36. {
  37. // See comments above on how to read this
  38. {4, 0, 0},
  39. {6, 0, 0},
  40. {8, 0, 0},
  41. };
  42. #else
  43. const Var JavascriptArray::MissingItem = (Var)0x80000002;
  44. uint JavascriptNativeIntArray::allocationBuckets[][AllocationBucketsInfoSize] =
  45. {
  46. // See comments above on how to read this
  47. { 3, 0, 0 },
  48. { 7, 0, 0 },
  49. { 8, 0, 0 },
  50. };
  51. uint JavascriptArray::allocationBuckets[][AllocationBucketsInfoSize] =
  52. {
  53. // See comments above on how to read this
  54. { 4, 0, 0 },
  55. { 8, 0, 0 },
  56. };
  57. #endif
  58. const int32 JavascriptNativeIntArray::MissingItem = 0x80000002;
  59. static const uint64 FloatMissingItemPattern = 0x8000000280000002ull;
  60. const double JavascriptNativeFloatArray::MissingItem = *(double*)&FloatMissingItemPattern;
  61. // Allocate enough space for 4 inline property slots and 16 inline element slots
  62. const size_t JavascriptArray::StackAllocationSize = DetermineAllocationSize<JavascriptArray, 4>(16);
  63. const size_t JavascriptNativeIntArray::StackAllocationSize = DetermineAllocationSize<JavascriptNativeIntArray, 4>(16);
  64. const size_t JavascriptNativeFloatArray::StackAllocationSize = DetermineAllocationSize<JavascriptNativeFloatArray, 4>(16);
  65. SegmentBTree::SegmentBTree()
  66. : segmentCount(0),
  67. segments(nullptr),
  68. keys(nullptr),
  69. children(nullptr)
  70. {
  71. }
  72. uint32 SegmentBTree::GetLazyCrossOverLimit()
  73. {
  74. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  75. if (Js::Configuration::Global.flags.DisableArrayBTree)
  76. {
  77. return Js::JavascriptArray::InvalidIndex;
  78. }
  79. else if (Js::Configuration::Global.flags.ForceArrayBTree)
  80. {
  81. return ARRAY_CROSSOVER_FOR_VALIDATE;
  82. }
  83. #endif
  84. #ifdef VALIDATE_ARRAY
  85. if (Js::Configuration::Global.flags.ArrayValidate)
  86. {
  87. return ARRAY_CROSSOVER_FOR_VALIDATE;
  88. }
  89. #endif
  90. return SegmentBTree::MinDegree * 3;
  91. }
  92. BOOL SegmentBTree::IsLeaf() const
  93. {
  94. return children == NULL;
  95. }
  96. BOOL SegmentBTree::IsFullNode() const
  97. {
  98. return segmentCount == MaxKeys;
  99. }
  100. void SegmentBTree::InternalFind(SegmentBTree* node, uint32 itemIndex, SparseArraySegmentBase*& prev, SparseArraySegmentBase*& matchOrNext)
  101. {
  102. uint32 i = 0;
  103. for(; i < node->segmentCount; i++)
  104. {
  105. Assert(node->keys[i] == node->segments[i]->left);
  106. if (itemIndex < node->keys[i])
  107. {
  108. break;
  109. }
  110. }
  111. // i indicates the 1st segment in the node past any matching segment.
  112. // the i'th child is the children to the 'left' of the i'th segment.
  113. // If itemIndex matches segment i-1 (note that left is always a match even when length == 0)
  114. bool matches = i > 0 && (itemIndex == node->keys[i-1] || itemIndex < node->keys[i-1] + node->segments[i-1]->length);
  115. if (matches)
  116. {
  117. // Find prev segment
  118. if (node->IsLeaf())
  119. {
  120. if (i > 1)
  121. {
  122. // Previous is either sibling or set in a parent
  123. prev = node->segments[i-2];
  124. }
  125. }
  126. else
  127. {
  128. // prev is the right most leaf in children[i-1] tree
  129. SegmentBTree* child = &node->children[i - 1];
  130. while (!child->IsLeaf())
  131. {
  132. child = &child->children[child->segmentCount];
  133. }
  134. prev = child->segments[child->segmentCount - 1];
  135. }
  136. // Return the matching segment
  137. matchOrNext = node->segments[i-1];
  138. }
  139. else // itemIndex in between segment i-1 and i
  140. {
  141. if (i > 0)
  142. {
  143. // Store in previous in case a match or next is the first segment in a child.
  144. prev = node->segments[i-1];
  145. }
  146. if (node->IsLeaf())
  147. {
  148. matchOrNext = (i == 0 ? node->segments[0] : PointerValue(prev->next));
  149. }
  150. else
  151. {
  152. InternalFind(node->children + i, itemIndex, prev, matchOrNext);
  153. }
  154. }
  155. }
  156. void SegmentBTreeRoot::Find(uint32 itemIndex, SparseArraySegmentBase*& prev, SparseArraySegmentBase*& matchOrNext)
  157. {
  158. prev = matchOrNext = NULL;
  159. InternalFind(this, itemIndex, prev, matchOrNext);
  160. Assert(prev == NULL || (prev->next == matchOrNext));// If prev exists it is immediately before matchOrNext in the list of arraysegments
  161. Assert(prev == NULL || (prev->left < itemIndex && prev->left + prev->length <= itemIndex)); // prev should never be a match (left is a match if length == 0)
  162. Assert(matchOrNext == NULL || (matchOrNext->left >= itemIndex || matchOrNext->left + matchOrNext->length > itemIndex));
  163. }
  164. void SegmentBTreeRoot::Add(Recycler* recycler, SparseArraySegmentBase* newSeg)
  165. {
  166. if (IsFullNode())
  167. {
  168. SegmentBTree * children = AllocatorNewArrayZ(Recycler, recycler, SegmentBTree, MaxDegree);
  169. children[0] = *this;
  170. // Even though the segments point to a GC pointer, the main array should keep a references
  171. // as well. So just make it a leaf allocation
  172. this->segmentCount = 0;
  173. this->segments = AllocatorNewArrayLeafZ(Recycler, recycler, SparseArraySegmentBase*, MaxKeys);
  174. this->keys = AllocatorNewArrayLeafZ(Recycler,recycler,uint32,MaxKeys);
  175. this->children = children;
  176. // This split is the only way the tree gets deeper
  177. SplitChild(recycler, this, 0, &children[0]);
  178. }
  179. InsertNonFullNode(recycler, this, newSeg);
  180. }
  181. void SegmentBTree::SwapSegment(uint32 originalKey, SparseArraySegmentBase* oldSeg, SparseArraySegmentBase* newSeg)
  182. {
  183. // Find old segment
  184. uint32 itemIndex = originalKey;
  185. uint32 i = 0;
  186. for(; i < segmentCount; i++)
  187. {
  188. Assert(keys[i] == segments[i]->left || (oldSeg == newSeg && newSeg == segments[i]));
  189. if (itemIndex < keys[i])
  190. {
  191. break;
  192. }
  193. }
  194. // i is 1 past any match
  195. if (i > 0)
  196. {
  197. if (oldSeg == segments[i-1])
  198. {
  199. segments[i-1] = newSeg;
  200. keys[i-1] = newSeg->left;
  201. return;
  202. }
  203. }
  204. Assert(!IsLeaf());
  205. children[i].SwapSegment(originalKey, oldSeg, newSeg);
  206. }
  207. void SegmentBTree::SplitChild(Recycler* recycler, SegmentBTree* parent, uint32 iChild, SegmentBTree* child)
  208. {
  209. // Split child in two, move it's median key up to parent, and put the result of the split
  210. // on either side of the key moved up into parent
  211. Assert(child != NULL);
  212. Assert(parent != NULL);
  213. Assert(!parent->IsFullNode());
  214. Assert(child->IsFullNode());
  215. SegmentBTree newNode;
  216. newNode.segmentCount = MinKeys;
  217. // Even though the segments point to a GC pointer, the main array should keep a references
  218. // as well. So just make it a leaf allocation
  219. newNode.segments = AllocatorNewArrayLeafZ(Recycler, recycler, SparseArraySegmentBase*, MaxKeys);
  220. newNode.keys = AllocatorNewArrayLeafZ(Recycler,recycler,uint32,MaxKeys);
  221. // Move the keys above the median into the new node
  222. for(uint32 i = 0; i < MinKeys; i++)
  223. {
  224. newNode.segments[i] = child->segments[i+MinDegree];
  225. newNode.keys[i] = child->keys[i+MinDegree];
  226. // Do not leave false positive references around in the b-tree
  227. child->segments[i+MinDegree] = nullptr;
  228. }
  229. // If children exist move those as well.
  230. if (!child->IsLeaf())
  231. {
  232. newNode.children = AllocatorNewArrayZ(Recycler, recycler, SegmentBTree, MaxDegree);
  233. for(uint32 j = 0; j < MinDegree; j++)
  234. {
  235. newNode.children[j] = child->children[j+MinDegree];
  236. // Do not leave false positive references around in the b-tree
  237. child->children[j+MinDegree].segments = nullptr;
  238. child->children[j+MinDegree].children = nullptr;
  239. }
  240. }
  241. child->segmentCount = MinKeys;
  242. // Make room for the new child in parent
  243. for(uint32 j = parent->segmentCount; j > iChild; j--)
  244. {
  245. parent->children[j+1] = parent->children[j];
  246. }
  247. // Copy the contents of the new node into the correct place in the parent's child array
  248. parent->children[iChild+1] = newNode;
  249. // Move the keys to make room for the median key
  250. for(uint32 k = parent->segmentCount; k > iChild; k--)
  251. {
  252. parent->segments[k] = parent->segments[k-1];
  253. parent->keys[k] = parent->keys[k-1];
  254. }
  255. // Move the median key into the proper place in the parent node
  256. parent->segments[iChild] = child->segments[MinKeys];
  257. parent->keys[iChild] = child->keys[MinKeys];
  258. // Do not leave false positive references around in the b-tree
  259. child->segments[MinKeys] = nullptr;
  260. parent->segmentCount++;
  261. }
  262. void SegmentBTree::InsertNonFullNode(Recycler* recycler, SegmentBTree* node, SparseArraySegmentBase* newSeg)
  263. {
  264. Assert(!node->IsFullNode());
  265. AnalysisAssert(node->segmentCount < MaxKeys); // Same as !node->IsFullNode()
  266. Assert(newSeg != NULL);
  267. if (node->IsLeaf())
  268. {
  269. // Move the keys
  270. uint32 i = node->segmentCount - 1;
  271. while( (i != -1) && (newSeg->left < node->keys[i]))
  272. {
  273. node->segments[i+1] = node->segments[i];
  274. node->keys[i+1] = node->keys[i];
  275. i--;
  276. }
  277. if (!node->segments)
  278. {
  279. // Even though the segments point to a GC pointer, the main array should keep a references
  280. // as well. So just make it a leaf allocation
  281. node->segments = AllocatorNewArrayLeafZ(Recycler, recycler, SparseArraySegmentBase*, MaxKeys);
  282. node->keys = AllocatorNewArrayLeafZ(Recycler, recycler, uint32, MaxKeys);
  283. }
  284. node->segments[i + 1] = newSeg;
  285. node->keys[i + 1] = newSeg->left;
  286. node->segmentCount++;
  287. }
  288. else
  289. {
  290. // find the correct child node
  291. uint32 i = node->segmentCount-1;
  292. while((i != -1) && (newSeg->left < node->keys[i]))
  293. {
  294. i--;
  295. }
  296. i++;
  297. // Make room if full
  298. if(node->children[i].IsFullNode())
  299. {
  300. // This split doesn't make the tree any deeper as node already has children.
  301. SplitChild(recycler, node, i, node->children+i);
  302. Assert(node->keys[i] == node->segments[i]->left);
  303. if (newSeg->left > node->keys[i])
  304. {
  305. i++;
  306. }
  307. }
  308. InsertNonFullNode(recycler, node->children+i, newSeg);
  309. }
  310. }
  311. inline void ThrowTypeErrorOnFailureHelper::ThrowTypeErrorOnFailure(BOOL operationSucceeded)
  312. {
  313. if (IsThrowTypeError(operationSucceeded))
  314. {
  315. ThrowTypeErrorOnFailure();
  316. }
  317. }
  318. inline void ThrowTypeErrorOnFailureHelper::ThrowTypeErrorOnFailure()
  319. {
  320. JavascriptError::ThrowTypeError(m_scriptContext, VBSERR_ActionNotSupported, m_functionName);
  321. }
  322. inline BOOL ThrowTypeErrorOnFailureHelper::IsThrowTypeError(BOOL operationSucceeded)
  323. {
  324. return !operationSucceeded;
  325. }
  326. // Make sure EmptySegment points to read-only memory.
  327. // Can't do this the easy way because SparseArraySegment has a constructor...
  328. JavascriptArray::JavascriptArray(DynamicType * type)
  329. : ArrayObject(type, false, 0)
  330. {
  331. Assert(type->GetTypeId() == TypeIds_Array || type->GetTypeId() == TypeIds_NativeIntArray || type->GetTypeId() == TypeIds_NativeFloatArray || ((type->GetTypeId() == TypeIds_ES5Array || type->GetTypeId() == TypeIds_Object) && type->GetPrototype() == GetScriptContext()->GetLibrary()->GetArrayPrototype()));
  332. Assert(EmptySegment->length == 0 && EmptySegment->size == 0 && EmptySegment->next == NULL);
  333. InitArrayFlags(DynamicObjectFlags::InitialArrayValue);
  334. SetHeadAndLastUsedSegment(const_cast<SparseArraySegmentBase *>(EmptySegment));
  335. }
  336. JavascriptArray::JavascriptArray(uint32 length, DynamicType * type)
  337. : ArrayObject(type, false, length)
  338. {
  339. Assert(JavascriptArray::Is(type->GetTypeId()));
  340. Assert(EmptySegment->length == 0 && EmptySegment->size == 0 && EmptySegment->next == NULL);
  341. InitArrayFlags(DynamicObjectFlags::InitialArrayValue);
  342. SetHeadAndLastUsedSegment(const_cast<SparseArraySegmentBase *>(EmptySegment));
  343. }
  344. JavascriptArray::JavascriptArray(uint32 length, uint32 size, DynamicType * type)
  345. : ArrayObject(type, false, length)
  346. {
  347. Assert(type->GetTypeId() == TypeIds_Array);
  348. InitArrayFlags(DynamicObjectFlags::InitialArrayValue);
  349. Recycler* recycler = GetRecycler();
  350. SetHeadAndLastUsedSegment(SparseArraySegment<Var>::AllocateSegment(recycler, 0, 0, size, nullptr));
  351. }
  352. JavascriptArray::JavascriptArray(DynamicType * type, uint32 size)
  353. : ArrayObject(type, false)
  354. {
  355. InitArrayFlags(DynamicObjectFlags::InitialArrayValue);
  356. SetHeadAndLastUsedSegment(DetermineInlineHeadSegmentPointer<JavascriptArray, 0, false>(this));
  357. head->size = size;
  358. head->CheckLengthvsSize();
  359. Var fill = Js::JavascriptArray::MissingItem;
  360. for (uint i = 0; i < size; i++)
  361. {
  362. SparseArraySegment<Var>::From(head)->elements[i] = fill;
  363. }
  364. }
  365. JavascriptNativeIntArray::JavascriptNativeIntArray(uint32 length, uint32 size, DynamicType * type)
  366. : JavascriptNativeArray(type)
  367. {
  368. Assert(type->GetTypeId() == TypeIds_NativeIntArray);
  369. this->length = length;
  370. Recycler* recycler = GetRecycler();
  371. SetHeadAndLastUsedSegment(SparseArraySegment<int32>::AllocateSegment(recycler, 0, 0, size, nullptr));
  372. }
  373. JavascriptNativeIntArray::JavascriptNativeIntArray(DynamicType * type, uint32 size)
  374. : JavascriptNativeArray(type)
  375. {
  376. SetHeadAndLastUsedSegment(DetermineInlineHeadSegmentPointer<JavascriptNativeIntArray, 0, false>(this));
  377. head->size = size;
  378. head->CheckLengthvsSize();
  379. SparseArraySegment<int32>::From(head)->FillSegmentBuffer(0, size);
  380. }
  381. JavascriptNativeFloatArray::JavascriptNativeFloatArray(uint32 length, uint32 size, DynamicType * type)
  382. : JavascriptNativeArray(type)
  383. {
  384. Assert(type->GetTypeId() == TypeIds_NativeFloatArray);
  385. this->length = length;
  386. Recycler* recycler = GetRecycler();
  387. SetHeadAndLastUsedSegment(SparseArraySegment<double>::AllocateSegment(recycler, 0, 0, size, nullptr));
  388. }
  389. JavascriptNativeFloatArray::JavascriptNativeFloatArray(DynamicType * type, uint32 size)
  390. : JavascriptNativeArray(type)
  391. {
  392. SetHeadAndLastUsedSegment(DetermineInlineHeadSegmentPointer<JavascriptNativeFloatArray, 0, false>(this));
  393. head->size = size;
  394. head->CheckLengthvsSize();
  395. SparseArraySegment<double>::From(head)->FillSegmentBuffer(0, size);
  396. }
  397. bool JavascriptArray::Is(Var aValue)
  398. {
  399. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  400. return JavascriptArray::Is(typeId);
  401. }
  402. bool JavascriptArray::Is(TypeId typeId)
  403. {
  404. return typeId >= TypeIds_ArrayFirst && typeId <= TypeIds_ArrayLast;
  405. }
  406. bool JavascriptArray::IsVarArray(Var aValue)
  407. {
  408. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  409. return JavascriptArray::IsVarArray(typeId);
  410. }
  411. bool JavascriptArray::IsVarArray(TypeId typeId)
  412. {
  413. return typeId == TypeIds_Array;
  414. }
  415. template<typename T>
  416. bool JavascriptArray::IsMissingItemAt(uint32 index) const
  417. {
  418. SparseArraySegment<T>* headSeg = SparseArraySegment<T>::From(this->head);
  419. return SparseArraySegment<T>::IsMissingItem(&headSeg->elements[index]);
  420. }
  421. bool JavascriptArray::IsMissingItem(uint32 index)
  422. {
  423. if (this->length <= index)
  424. {
  425. return false;
  426. }
  427. bool isIntArray = false, isFloatArray = false;
  428. this->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
  429. if (isIntArray)
  430. {
  431. return IsMissingItemAt<int32>(index);
  432. }
  433. else if (isFloatArray)
  434. {
  435. return IsMissingItemAt<double>(index);
  436. }
  437. else
  438. {
  439. return IsMissingItemAt<Var>(index);
  440. }
  441. }
  442. JavascriptArray* JavascriptArray::FromVar(Var aValue)
  443. {
  444. AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptArray'");
  445. return static_cast<JavascriptArray *>(RecyclableObject::FromVar(aValue));
  446. }
  447. // Get JavascriptArray* from a Var, which is either a JavascriptArray* or ESArray*.
  448. JavascriptArray* JavascriptArray::FromAnyArray(Var aValue)
  449. {
  450. AssertMsg(Is(aValue) || ES5Array::Is(aValue), "Ensure var is actually a 'JavascriptArray' or 'ES5Array'");
  451. return static_cast<JavascriptArray *>(RecyclableObject::FromVar(aValue));
  452. }
  453. // Check if a Var is a direct-accessible (fast path) JavascriptArray.
  454. bool JavascriptArray::IsDirectAccessArray(Var aValue)
  455. {
  456. return RecyclableObject::Is(aValue) &&
  457. (VirtualTableInfo<JavascriptArray>::HasVirtualTable(aValue) ||
  458. VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(aValue) ||
  459. VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(aValue));
  460. }
  461. DynamicObjectFlags JavascriptArray::GetFlags() const
  462. {
  463. return GetArrayFlags();
  464. }
  465. DynamicObjectFlags JavascriptArray::GetFlags_Unchecked() const // do not use except in extreme circumstances
  466. {
  467. return GetArrayFlags_Unchecked();
  468. }
  469. void JavascriptArray::SetFlags(const DynamicObjectFlags flags)
  470. {
  471. SetArrayFlags(flags);
  472. }
  473. DynamicType * JavascriptArray::GetInitialType(ScriptContext * scriptContext)
  474. {
  475. return scriptContext->GetLibrary()->GetArrayType();
  476. }
  477. JavascriptArray *JavascriptArray::GetArrayForArrayOrObjectWithArray(const Var var)
  478. {
  479. bool isObjectWithArray;
  480. TypeId arrayTypeId;
  481. return GetArrayForArrayOrObjectWithArray(var, &isObjectWithArray, &arrayTypeId);
  482. }
  483. JavascriptArray *JavascriptArray::GetArrayForArrayOrObjectWithArray(
  484. const Var var,
  485. bool *const isObjectWithArrayRef,
  486. TypeId *const arrayTypeIdRef)
  487. {
  488. // This is a helper function used by jitted code. The array checks done here match the array checks done by jitted code
  489. // (see Lowerer::GenerateArrayTest) to minimize bailouts.
  490. Assert(var);
  491. Assert(isObjectWithArrayRef);
  492. Assert(arrayTypeIdRef);
  493. *isObjectWithArrayRef = false;
  494. *arrayTypeIdRef = TypeIds_Undefined;
  495. if(!RecyclableObject::Is(var))
  496. {
  497. return nullptr;
  498. }
  499. JavascriptArray *array = nullptr;
  500. INT_PTR vtable = VirtualTableInfoBase::GetVirtualTable(var);
  501. if(vtable == VirtualTableInfo<DynamicObject>::Address)
  502. {
  503. ArrayObject* objectArray = DynamicObject::FromVar(var)->GetObjectArray();
  504. array = (objectArray && Is(objectArray)) ? FromVar(objectArray) : nullptr;
  505. if(!array)
  506. {
  507. return nullptr;
  508. }
  509. *isObjectWithArrayRef = true;
  510. vtable = VirtualTableInfoBase::GetVirtualTable(array);
  511. }
  512. if(vtable == VirtualTableInfo<JavascriptArray>::Address)
  513. {
  514. *arrayTypeIdRef = TypeIds_Array;
  515. }
  516. else if(vtable == VirtualTableInfo<JavascriptNativeIntArray>::Address)
  517. {
  518. *arrayTypeIdRef = TypeIds_NativeIntArray;
  519. }
  520. else if(vtable == VirtualTableInfo<JavascriptNativeFloatArray>::Address)
  521. {
  522. *arrayTypeIdRef = TypeIds_NativeFloatArray;
  523. }
  524. else
  525. {
  526. return nullptr;
  527. }
  528. if(!array)
  529. {
  530. array = FromVar(var);
  531. }
  532. return array;
  533. }
  534. const SparseArraySegmentBase *JavascriptArray::Jit_GetArrayHeadSegmentForArrayOrObjectWithArray(const Var var)
  535. {
  536. // This is a helper function used by jitted code
  537. JavascriptArray *const array = GetArrayForArrayOrObjectWithArray(var);
  538. return array ? array->head : nullptr;
  539. }
  540. uint32 JavascriptArray::Jit_GetArrayHeadSegmentLength(const SparseArraySegmentBase *const headSegment)
  541. {
  542. // This is a helper function used by jitted code
  543. return headSegment ? headSegment->length : 0;
  544. }
  545. bool JavascriptArray::Jit_OperationInvalidatedArrayHeadSegment(
  546. const SparseArraySegmentBase *const headSegmentBeforeOperation,
  547. const uint32 headSegmentLengthBeforeOperation,
  548. const Var varAfterOperation)
  549. {
  550. // This is a helper function used by jitted code
  551. Assert(varAfterOperation);
  552. if(!headSegmentBeforeOperation)
  553. {
  554. return false;
  555. }
  556. const SparseArraySegmentBase *const headSegmentAfterOperation =
  557. Jit_GetArrayHeadSegmentForArrayOrObjectWithArray(varAfterOperation);
  558. return
  559. headSegmentAfterOperation != headSegmentBeforeOperation ||
  560. headSegmentAfterOperation->length != headSegmentLengthBeforeOperation;
  561. }
  562. uint32 JavascriptArray::Jit_GetArrayLength(const Var var)
  563. {
  564. // This is a helper function used by jitted code
  565. bool isObjectWithArray;
  566. TypeId arrayTypeId;
  567. JavascriptArray *const array = GetArrayForArrayOrObjectWithArray(var, &isObjectWithArray, &arrayTypeId);
  568. return array && !isObjectWithArray ? array->GetLength() : 0;
  569. }
  570. bool JavascriptArray::Jit_OperationInvalidatedArrayLength(const uint32 lengthBeforeOperation, const Var varAfterOperation)
  571. {
  572. // This is a helper function used by jitted code
  573. return Jit_GetArrayLength(varAfterOperation) != lengthBeforeOperation;
  574. }
  575. DynamicObjectFlags JavascriptArray::Jit_GetArrayFlagsForArrayOrObjectWithArray(const Var var)
  576. {
  577. // This is a helper function used by jitted code
  578. JavascriptArray *const array = GetArrayForArrayOrObjectWithArray(var);
  579. return array && array->UsesObjectArrayOrFlagsAsFlags() ? array->GetFlags() : DynamicObjectFlags::None;
  580. }
  581. bool JavascriptArray::Jit_OperationCreatedFirstMissingValue(
  582. const DynamicObjectFlags flagsBeforeOperation,
  583. const Var varAfterOperation)
  584. {
  585. // This is a helper function used by jitted code
  586. Assert(varAfterOperation);
  587. return
  588. !!(flagsBeforeOperation & DynamicObjectFlags::HasNoMissingValues) &&
  589. !(Jit_GetArrayFlagsForArrayOrObjectWithArray(varAfterOperation) & DynamicObjectFlags::HasNoMissingValues);
  590. }
  591. bool JavascriptArray::HasNoMissingValues() const
  592. {
  593. return !!(GetFlags() & DynamicObjectFlags::HasNoMissingValues);
  594. }
  595. bool JavascriptArray::HasNoMissingValues_Unchecked() const // do not use except in extreme circumstances
  596. {
  597. return !!(GetFlags_Unchecked() & DynamicObjectFlags::HasNoMissingValues);
  598. }
  599. void JavascriptArray::SetHasNoMissingValues(const bool hasNoMissingValues)
  600. {
  601. SetFlags(
  602. hasNoMissingValues
  603. ? GetFlags() | DynamicObjectFlags::HasNoMissingValues
  604. : GetFlags() & ~DynamicObjectFlags::HasNoMissingValues);
  605. }
  606. template<class T>
  607. bool JavascriptArray::IsMissingHeadSegmentItemImpl(const uint32 index) const
  608. {
  609. Assert(index < head->length);
  610. return SparseArraySegment<T>::IsMissingItem(&SparseArraySegment<T>::From(head)->elements[index]);
  611. }
  612. bool JavascriptArray::IsMissingHeadSegmentItem(const uint32 index) const
  613. {
  614. return IsMissingHeadSegmentItemImpl<Var>(index);
  615. }
  616. #if ENABLE_COPYONACCESS_ARRAY
  617. void JavascriptCopyOnAccessNativeIntArray::ConvertCopyOnAccessSegment()
  618. {
  619. Assert(this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->IsValidIndex(::Math::PointerCastToIntegral<uint32>(this->GetHead())));
  620. SparseArraySegment<int32> *seg = this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->GetSegmentByIndex(::Math::PointerCastToIntegral<byte>(this->GetHead()));
  621. SparseArraySegment<int32> *newSeg = SparseArraySegment<int32>::AllocateLiteralHeadSegment(this->GetRecycler(), seg->length);
  622. #if ENABLE_DEBUG_CONFIG_OPTIONS
  623. if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::CopyOnAccessArrayPhase))
  624. {
  625. Output::Print(_u("Convert copy-on-access array: index(%d) length(%d)\n"), this->GetHead(), seg->length);
  626. Output::Flush();
  627. }
  628. #endif
  629. newSeg->CopySegment(this->GetRecycler(), newSeg, 0, seg, 0, seg->length);
  630. this->SetHeadAndLastUsedSegment(newSeg);
  631. VirtualTableInfo<JavascriptNativeIntArray>::SetVirtualTable(this);
  632. this->type = JavascriptNativeIntArray::GetInitialType(this->GetScriptContext());
  633. ArrayCallSiteInfo *arrayInfo = this->GetArrayCallSiteInfo();
  634. if (arrayInfo && !arrayInfo->isNotCopyOnAccessArray)
  635. {
  636. arrayInfo->isNotCopyOnAccessArray = 1;
  637. }
  638. }
  639. uint32 JavascriptCopyOnAccessNativeIntArray::GetNextIndex(uint32 index) const
  640. {
  641. if (this->length == 0 || (index != Js::JavascriptArray::InvalidIndex && index >= this->length))
  642. {
  643. return Js::JavascriptArray::InvalidIndex;
  644. }
  645. else if (index == Js::JavascriptArray::InvalidIndex)
  646. {
  647. return 0;
  648. }
  649. else
  650. {
  651. return index + 1;
  652. }
  653. }
  654. BOOL JavascriptCopyOnAccessNativeIntArray::DirectGetItemAt(uint32 index, int* outVal)
  655. {
  656. Assert(this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->IsValidIndex(::Math::PointerCastToIntegral<uint32>(this->GetHead())));
  657. SparseArraySegment<int32> *seg = this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->GetSegmentByIndex(::Math::PointerCastToIntegral<byte>(this->GetHead()));
  658. if (this->length == 0 || index == Js::JavascriptArray::InvalidIndex || index >= this->length)
  659. {
  660. return FALSE;
  661. }
  662. else
  663. {
  664. *outVal = seg->elements[index];
  665. return TRUE;
  666. }
  667. }
  668. #endif
  669. bool JavascriptNativeIntArray::IsMissingHeadSegmentItem(const uint32 index) const
  670. {
  671. return IsMissingHeadSegmentItemImpl<int32>(index);
  672. }
  673. bool JavascriptNativeFloatArray::IsMissingHeadSegmentItem(const uint32 index) const
  674. {
  675. return IsMissingHeadSegmentItemImpl<double>(index);
  676. }
  677. template<typename T>
  678. void JavascriptArray::InternalFillFromPrototype(JavascriptArray *dstArray, const T& dstIndex, JavascriptArray *srcArray, uint32 start, uint32 end, uint32 count)
  679. {
  680. RecyclableObject* prototype = srcArray->GetPrototype();
  681. while (start + count != end && JavascriptOperators::GetTypeId(prototype) != TypeIds_Null)
  682. {
  683. ForEachOwnMissingArrayIndexOfObject(srcArray, dstArray, prototype, start, end, dstIndex, [&](uint32 index, Var value) {
  684. T n = dstIndex + (index - start);
  685. dstArray->DirectSetItemAt(n, value);
  686. count++;
  687. });
  688. prototype = prototype->GetPrototype();
  689. }
  690. }
  691. template<>
  692. void JavascriptArray::InternalFillFromPrototype(JavascriptArray *dstArray, const uint32& dstIndex, JavascriptArray *srcArray, uint32 start, uint32 end, uint32 count)
  693. {
  694. RecyclableObject* prototype = srcArray->GetPrototype();
  695. while (start + count != end && JavascriptOperators::GetTypeId(prototype) != TypeIds_Null)
  696. {
  697. ForEachOwnMissingArrayIndexOfObject(srcArray, dstArray, prototype, start, end, dstIndex, [&](uint32 index, Var value) {
  698. uint32 n = dstIndex + (index - start);
  699. dstArray->SetItem(n, value, PropertyOperation_None);
  700. count++;
  701. });
  702. prototype = prototype->GetPrototype();
  703. }
  704. }
  705. /* static */
  706. bool JavascriptArray::HasInlineHeadSegment(uint32 length)
  707. {
  708. return length <= SparseArraySegmentBase::INLINE_CHUNK_SIZE;
  709. }
  710. Var JavascriptArray::OP_NewScArray(uint32 elementCount, ScriptContext* scriptContext)
  711. {
  712. // Called only to create array literals: size is known.
  713. return scriptContext->GetLibrary()->CreateArrayLiteral(elementCount);
  714. }
  715. Var JavascriptArray::OP_NewScArrayWithElements(uint32 elementCount, Var *elements, ScriptContext* scriptContext)
  716. {
  717. // Called only to create array literals: size is known.
  718. JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(elementCount);
  719. SparseArraySegment<Var> *head = SparseArraySegment<Var>::From(arr->head);
  720. Assert(elementCount <= head->length);
  721. CopyArray(head->elements, head->length, elements, elementCount);
  722. #ifdef VALIDATE_ARRAY
  723. arr->ValidateArray();
  724. #endif
  725. return arr;
  726. }
  727. Var JavascriptArray::OP_NewScArrayWithMissingValues(uint32 elementCount, ScriptContext* scriptContext)
  728. {
  729. // Called only to create array literals: size is known.
  730. JavascriptArray *const array = static_cast<JavascriptArray *>(OP_NewScArray(elementCount, scriptContext));
  731. array->SetHasNoMissingValues(false);
  732. SparseArraySegment<Var> *head = SparseArraySegment<Var>::From(array->head);
  733. head->FillSegmentBuffer(0, elementCount);
  734. return array;
  735. }
  736. #if ENABLE_PROFILE_INFO
  737. Var JavascriptArray::ProfiledNewScArray(uint32 elementCount, ScriptContext *scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
  738. {
  739. if (arrayInfo->IsNativeIntArray())
  740. {
  741. JavascriptNativeIntArray *arr = scriptContext->GetLibrary()->CreateNativeIntArrayLiteral(elementCount);
  742. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  743. return arr;
  744. }
  745. if (arrayInfo->IsNativeFloatArray())
  746. {
  747. JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(elementCount);
  748. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  749. return arr;
  750. }
  751. JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(elementCount);
  752. return arr;
  753. }
  754. #endif
  755. Var JavascriptArray::OP_NewScIntArray(AuxArray<int32> *ints, ScriptContext* scriptContext)
  756. {
  757. uint32 count = ints->count;
  758. JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(count);
  759. SparseArraySegment<Var> *head = SparseArraySegment<Var>::From(arr->head);
  760. Assert(count > 0 && count == head->length);
  761. for (uint i = 0; i < count; i++)
  762. {
  763. head->elements[i] = JavascriptNumber::ToVar(ints->elements[i], scriptContext);
  764. }
  765. return arr;
  766. }
  767. #if ENABLE_PROFILE_INFO
  768. Var JavascriptArray::ProfiledNewScIntArray(AuxArray<int32> *ints, ScriptContext* scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
  769. {
  770. // Called only to create array literals: size is known.
  771. uint32 count = ints->count;
  772. if (arrayInfo->IsNativeIntArray())
  773. {
  774. JavascriptNativeIntArray *arr;
  775. #if ENABLE_COPYONACCESS_ARRAY
  776. JavascriptLibrary *lib = scriptContext->GetLibrary();
  777. FunctionBody *functionBody = weakFuncRef->Get();
  778. if (JavascriptLibrary::IsCopyOnAccessArrayCallSite(lib, arrayInfo, count))
  779. {
  780. Assert(lib->cacheForCopyOnAccessArraySegments);
  781. arr = scriptContext->GetLibrary()->CreateCopyOnAccessNativeIntArrayLiteral(arrayInfo, functionBody, ints);
  782. }
  783. else
  784. #endif
  785. {
  786. arr = scriptContext->GetLibrary()->CreateNativeIntArrayLiteral(count);
  787. SparseArraySegment<int32> *head = SparseArraySegment<int32>::From(arr->head);
  788. Assert(count > 0 && count == head->length);
  789. CopyArray(head->elements, head->length, ints->elements, count);
  790. }
  791. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  792. return arr;
  793. }
  794. if (arrayInfo->IsNativeFloatArray())
  795. {
  796. JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(count);
  797. SparseArraySegment<double> *head = SparseArraySegment<double>::From(arr->head);
  798. Assert(count > 0 && count == head->length);
  799. for (uint i = 0; i < count; i++)
  800. {
  801. head->elements[i] = (double)ints->elements[i];
  802. }
  803. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  804. return arr;
  805. }
  806. return OP_NewScIntArray(ints, scriptContext);
  807. }
  808. #endif
  809. Var JavascriptArray::OP_NewScFltArray(AuxArray<double> *doubles, ScriptContext* scriptContext)
  810. {
  811. uint32 count = doubles->count;
  812. JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(count);
  813. SparseArraySegment<Var> *head = SparseArraySegment<Var>::From(arr->head);
  814. Assert(count > 0 && count == head->length);
  815. for (uint i = 0; i < count; i++)
  816. {
  817. double dval = doubles->elements[i];
  818. int32 ival;
  819. if (JavascriptNumber::TryGetInt32Value(dval, &ival) && !TaggedInt::IsOverflow(ival))
  820. {
  821. head->elements[i] = TaggedInt::ToVarUnchecked(ival);
  822. }
  823. else
  824. {
  825. head->elements[i] = JavascriptNumber::ToVarNoCheck(dval, scriptContext);
  826. }
  827. }
  828. return arr;
  829. }
  830. #if ENABLE_PROFILE_INFO
  831. Var JavascriptArray::ProfiledNewScFltArray(AuxArray<double> *doubles, ScriptContext* scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
  832. {
  833. // Called only to create array literals: size is known.
  834. if (arrayInfo->IsNativeFloatArray())
  835. {
  836. arrayInfo->SetIsNotNativeIntArray();
  837. uint32 count = doubles->count;
  838. JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(count);
  839. SparseArraySegment<double> *head = SparseArraySegment<double>::From(arr->head);
  840. Assert(count > 0 && count == head->length);
  841. CopyArray(head->elements, head->length, doubles->elements, count);
  842. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  843. return arr;
  844. }
  845. return OP_NewScFltArray(doubles, scriptContext);
  846. }
  847. Var JavascriptArray::ProfiledNewInstance(RecyclableObject* function, CallInfo callInfo, ...)
  848. {
  849. ARGUMENTS(args, callInfo);
  850. Assert(JavascriptFunction::Is(function) &&
  851. JavascriptFunction::FromVar(function)->GetFunctionInfo() == &JavascriptArray::EntryInfo::NewInstance);
  852. Assert(callInfo.Count >= 2);
  853. ArrayCallSiteInfo *arrayInfo = (ArrayCallSiteInfo*)args[0];
  854. JavascriptArray* pNew = nullptr;
  855. if (callInfo.Count == 2)
  856. {
  857. // Exactly one argument, which is the array length if it's a uint32.
  858. Var firstArgument = args[1];
  859. int elementCount;
  860. if (TaggedInt::Is(firstArgument))
  861. {
  862. elementCount = TaggedInt::ToInt32(firstArgument);
  863. if (elementCount < 0)
  864. {
  865. JavascriptError::ThrowRangeError(function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  866. }
  867. if (arrayInfo && arrayInfo->IsNativeArray())
  868. {
  869. if (arrayInfo->IsNativeIntArray())
  870. {
  871. pNew = function->GetLibrary()->CreateNativeIntArray(elementCount);
  872. }
  873. else
  874. {
  875. pNew = function->GetLibrary()->CreateNativeFloatArray(elementCount);
  876. }
  877. }
  878. else
  879. {
  880. pNew = function->GetLibrary()->CreateArray(elementCount);
  881. }
  882. }
  883. else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
  884. {
  885. // Non-tagged-int number: make sure the double value is really a uint32.
  886. double value = JavascriptNumber::GetValue(firstArgument);
  887. uint32 uvalue = JavascriptConversion::ToUInt32(value);
  888. if (value != uvalue)
  889. {
  890. JavascriptError::ThrowRangeError(function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  891. }
  892. if (arrayInfo && arrayInfo->IsNativeArray())
  893. {
  894. if (arrayInfo->IsNativeIntArray())
  895. {
  896. pNew = function->GetLibrary()->CreateNativeIntArray(uvalue);
  897. }
  898. else
  899. {
  900. pNew = function->GetLibrary()->CreateNativeFloatArray(uvalue);
  901. }
  902. }
  903. else
  904. {
  905. pNew = function->GetLibrary()->CreateArray(uvalue);
  906. }
  907. }
  908. else
  909. {
  910. //
  911. // First element is not int/double
  912. // create an array of length 1.
  913. // Set first element as the passed Var
  914. //
  915. pNew = function->GetLibrary()->CreateArray(1);
  916. pNew->DirectSetItemAt<Var>(0, firstArgument);
  917. }
  918. }
  919. else
  920. {
  921. // Called with a list of initial element values.
  922. // Create an array of the appropriate length and walk the list.
  923. if (arrayInfo && arrayInfo->IsNativeArray())
  924. {
  925. if (arrayInfo->IsNativeIntArray())
  926. {
  927. pNew = function->GetLibrary()->CreateNativeIntArray(callInfo.Count - 1);
  928. }
  929. else
  930. {
  931. pNew = function->GetLibrary()->CreateNativeFloatArray(callInfo.Count - 1);
  932. }
  933. }
  934. else
  935. {
  936. pNew = function->GetLibrary()->CreateArray(callInfo.Count - 1);
  937. }
  938. pNew->FillFromArgs(callInfo.Count - 1, 0, args.Values, arrayInfo);
  939. }
  940. #ifdef VALIDATE_ARRAY
  941. pNew->ValidateArray();
  942. #endif
  943. return pNew;
  944. }
  945. #endif
  946. Var JavascriptArray::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
  947. {
  948. ARGUMENTS(args, callInfo);
  949. return NewInstance(function, args);
  950. }
  951. Var JavascriptArray::NewInstance(RecyclableObject* function, Arguments args)
  952. {
  953. // Call to new Array(), possibly under another name.
  954. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  955. // SkipDefaultNewObject function flag should have prevented the default object
  956. // being created, except when call true a host dispatch.
  957. const CallInfo &callInfo = args.Info;
  958. Var newTarget = callInfo.Flags & CallFlags_NewTarget ? args.Values[args.Info.Count] : args[0];
  959. bool isCtorSuperCall = (callInfo.Flags & CallFlags_New) && newTarget != nullptr && !JavascriptOperators::IsUndefined(newTarget);
  960. Assert( isCtorSuperCall || !(callInfo.Flags & CallFlags_New) || args[0] == nullptr
  961. || JavascriptOperators::GetTypeId(args[0]) == TypeIds_HostDispatch);
  962. ScriptContext* scriptContext = function->GetScriptContext();
  963. JavascriptArray* pNew = nullptr;
  964. if (callInfo.Count < 2)
  965. {
  966. // No arguments passed to Array(), so create with the default size (0).
  967. pNew = CreateArrayFromConstructorNoArg(function, scriptContext);
  968. return isCtorSuperCall ?
  969. JavascriptOperators::OrdinaryCreateFromConstructor(RecyclableObject::FromVar(newTarget), pNew, nullptr, scriptContext) :
  970. pNew;
  971. }
  972. if (callInfo.Count == 2)
  973. {
  974. // Exactly one argument, which is the array length if it's a uint32.
  975. Var firstArgument = args[1];
  976. int elementCount;
  977. if (TaggedInt::Is(firstArgument))
  978. {
  979. elementCount = TaggedInt::ToInt32(firstArgument);
  980. if (elementCount < 0)
  981. {
  982. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  983. }
  984. pNew = CreateArrayFromConstructor(function, elementCount, scriptContext);
  985. }
  986. else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
  987. {
  988. // Non-tagged-int number: make sure the double value is really a uint32.
  989. double value = JavascriptNumber::GetValue(firstArgument);
  990. uint32 uvalue = JavascriptConversion::ToUInt32(value);
  991. if (value != uvalue)
  992. {
  993. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  994. }
  995. pNew = CreateArrayFromConstructor(function, uvalue, scriptContext);
  996. }
  997. else
  998. {
  999. //
  1000. // First element is not int/double
  1001. // create an array of length 1.
  1002. // Set first element as the passed Var
  1003. //
  1004. pNew = CreateArrayFromConstructor(function, 1, scriptContext);
  1005. JavascriptOperators::SetItem(pNew, pNew, 0u, firstArgument, scriptContext, PropertyOperation_ThrowIfNotExtensible);
  1006. // If we were passed an uninitialized JavascriptArray as the this argument,
  1007. // we need to set the length. We must do this _after_ setting the first
  1008. // element as the array may have side effects such as a setter for property
  1009. // named '0' which would make the previous length of the array observable.
  1010. // If we weren't passed a JavascriptArray as the this argument, this is no-op.
  1011. pNew->SetLength(1);
  1012. }
  1013. }
  1014. else
  1015. {
  1016. // Called with a list of initial element values.
  1017. // Create an array of the appropriate length and walk the list.
  1018. pNew = CreateArrayFromConstructor(function, callInfo.Count - 1, scriptContext);
  1019. pNew->JavascriptArray::FillFromArgs(callInfo.Count - 1, 0, args.Values);
  1020. }
  1021. #ifdef VALIDATE_ARRAY
  1022. pNew->ValidateArray();
  1023. #endif
  1024. return isCtorSuperCall ?
  1025. JavascriptOperators::OrdinaryCreateFromConstructor(RecyclableObject::FromVar(newTarget), pNew, nullptr, scriptContext) :
  1026. pNew;
  1027. }
  1028. JavascriptArray* JavascriptArray::CreateArrayFromConstructor(RecyclableObject* constructor, uint32 length, ScriptContext* scriptContext)
  1029. {
  1030. JavascriptLibrary* library = constructor->GetLibrary();
  1031. // Create the Array object we'll return - this is the only way to create an object which is an exotic Array object.
  1032. // Note: We need to use the library from the ScriptContext of the constructor, not the currently executing function.
  1033. // This is for the case where a built-in @@create method from a different JavascriptLibrary is installed on
  1034. // constructor.
  1035. return library->CreateArray(length);
  1036. }
  1037. JavascriptArray* JavascriptArray::CreateArrayFromConstructorNoArg(RecyclableObject* constructor, ScriptContext* scriptContext)
  1038. {
  1039. JavascriptLibrary* library = constructor->GetLibrary();
  1040. return library->CreateArray();
  1041. }
  1042. #if ENABLE_PROFILE_INFO
  1043. Var JavascriptArray::ProfiledNewInstanceNoArg(RecyclableObject *function, ScriptContext *scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
  1044. {
  1045. Assert(JavascriptFunction::Is(function) &&
  1046. JavascriptFunction::FromVar(function)->GetFunctionInfo() == &JavascriptArray::EntryInfo::NewInstance);
  1047. if (arrayInfo->IsNativeIntArray())
  1048. {
  1049. JavascriptNativeIntArray *arr = scriptContext->GetLibrary()->CreateNativeIntArray();
  1050. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  1051. return arr;
  1052. }
  1053. if (arrayInfo->IsNativeFloatArray())
  1054. {
  1055. JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArray();
  1056. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  1057. return arr;
  1058. }
  1059. return scriptContext->GetLibrary()->CreateArray();
  1060. }
  1061. #endif
  1062. Var JavascriptNativeIntArray::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
  1063. {
  1064. ARGUMENTS(args, callInfo);
  1065. return NewInstance(function, args);
  1066. }
  1067. Var JavascriptNativeIntArray::NewInstance(RecyclableObject* function, Arguments args)
  1068. {
  1069. Assert(!PHASE_OFF1(NativeArrayPhase));
  1070. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1071. const CallInfo &callInfo = args.Info;
  1072. if (callInfo.Count < 2)
  1073. {
  1074. // No arguments passed to Array(), so create with the default size (0).
  1075. return function->GetLibrary()->CreateNativeIntArray();
  1076. }
  1077. JavascriptArray* pNew = nullptr;
  1078. if (callInfo.Count == 2)
  1079. {
  1080. // Exactly one argument, which is the array length if it's a uint32.
  1081. Var firstArgument = args[1];
  1082. int elementCount;
  1083. if (TaggedInt::Is(firstArgument))
  1084. {
  1085. elementCount = TaggedInt::ToInt32(firstArgument);
  1086. if (elementCount < 0)
  1087. {
  1088. JavascriptError::ThrowRangeError(
  1089. function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  1090. }
  1091. pNew = function->GetLibrary()->CreateNativeIntArray(elementCount);
  1092. }
  1093. else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
  1094. {
  1095. // Non-tagged-int number: make sure the double value is really a uint32.
  1096. double value = JavascriptNumber::GetValue(firstArgument);
  1097. uint32 uvalue = JavascriptConversion::ToUInt32(value);
  1098. if (value != uvalue)
  1099. {
  1100. JavascriptError::ThrowRangeError(
  1101. function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  1102. }
  1103. pNew = function->GetLibrary()->CreateNativeIntArray(uvalue);
  1104. }
  1105. else
  1106. {
  1107. //
  1108. // First element is not int/double
  1109. // create an array of length 1.
  1110. // Set first element as the passed Var
  1111. //
  1112. pNew = function->GetLibrary()->CreateArray(1);
  1113. pNew->DirectSetItemAt<Var>(0, firstArgument);
  1114. }
  1115. }
  1116. else
  1117. {
  1118. // Called with a list of initial element values.
  1119. // Create an array of the appropriate length and walk the list.
  1120. JavascriptNativeIntArray *arr = function->GetLibrary()->CreateNativeIntArray(callInfo.Count - 1);
  1121. pNew = arr->FillFromArgs(callInfo.Count - 1, 0, args.Values);
  1122. }
  1123. #ifdef VALIDATE_ARRAY
  1124. pNew->ValidateArray();
  1125. #endif
  1126. return pNew;
  1127. }
  1128. Var JavascriptNativeFloatArray::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
  1129. {
  1130. ARGUMENTS(args, callInfo);
  1131. return NewInstance(function, args);
  1132. }
  1133. Var JavascriptNativeFloatArray::NewInstance(RecyclableObject* function, Arguments args)
  1134. {
  1135. Assert(!PHASE_OFF1(NativeArrayPhase));
  1136. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1137. const CallInfo &callInfo = args.Info;
  1138. if (callInfo.Count < 2)
  1139. {
  1140. // No arguments passed to Array(), so create with the default size (0).
  1141. return function->GetLibrary()->CreateNativeFloatArray();
  1142. }
  1143. JavascriptArray* pNew = nullptr;
  1144. if (callInfo.Count == 2)
  1145. {
  1146. // Exactly one argument, which is the array length if it's a uint32.
  1147. Var firstArgument = args[1];
  1148. int elementCount;
  1149. if (TaggedInt::Is(firstArgument))
  1150. {
  1151. elementCount = TaggedInt::ToInt32(firstArgument);
  1152. if (elementCount < 0)
  1153. {
  1154. JavascriptError::ThrowRangeError(
  1155. function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  1156. }
  1157. pNew = function->GetLibrary()->CreateNativeFloatArray(elementCount);
  1158. }
  1159. else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
  1160. {
  1161. // Non-tagged-int number: make sure the double value is really a uint32.
  1162. double value = JavascriptNumber::GetValue(firstArgument);
  1163. uint32 uvalue = JavascriptConversion::ToUInt32(value);
  1164. if (value != uvalue)
  1165. {
  1166. JavascriptError::ThrowRangeError(
  1167. function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  1168. }
  1169. pNew = function->GetLibrary()->CreateNativeFloatArray(uvalue);
  1170. }
  1171. else
  1172. {
  1173. //
  1174. // First element is not int/double
  1175. // create an array of length 1.
  1176. // Set first element as the passed Var
  1177. //
  1178. pNew = function->GetLibrary()->CreateArray(1);
  1179. pNew->DirectSetItemAt<Var>(0, firstArgument);
  1180. }
  1181. }
  1182. else
  1183. {
  1184. // Called with a list of initial element values.
  1185. // Create an array of the appropriate length and walk the list.
  1186. JavascriptNativeFloatArray *arr = function->GetLibrary()->CreateNativeFloatArray(callInfo.Count - 1);
  1187. pNew = arr->FillFromArgs(callInfo.Count - 1, 0, args.Values);
  1188. }
  1189. #ifdef VALIDATE_ARRAY
  1190. pNew->ValidateArray();
  1191. #endif
  1192. return pNew;
  1193. }
  1194. #if ENABLE_PROFILE_INFO
  1195. JavascriptArray * JavascriptNativeIntArray::FillFromArgs(uint length, uint start, Var *args, ArrayCallSiteInfo *arrayInfo, bool dontCreateNewArray)
  1196. #else
  1197. JavascriptArray * JavascriptNativeIntArray::FillFromArgs(uint length, uint start, Var *args, bool dontCreateNewArray)
  1198. #endif
  1199. {
  1200. uint i;
  1201. for (i = start; i < length; i++)
  1202. {
  1203. Var item = args[i + 1];
  1204. bool isTaggedInt = TaggedInt::Is(item);
  1205. bool isTaggedIntMissingValue = false;
  1206. #ifdef _M_AMD64
  1207. if (isTaggedInt)
  1208. {
  1209. int32 iValue = TaggedInt::ToInt32(item);
  1210. isTaggedIntMissingValue = Js::SparseArraySegment<int32>::IsMissingItem(&iValue);
  1211. }
  1212. #endif
  1213. if (isTaggedInt && !isTaggedIntMissingValue)
  1214. {
  1215. // This is taggedInt case and we verified that item is not missing value in AMD64.
  1216. this->DirectSetItemAt(i, TaggedInt::ToInt32(item));
  1217. }
  1218. else if (!isTaggedIntMissingValue && JavascriptNumber::Is_NoTaggedIntCheck(item))
  1219. {
  1220. double dvalue = JavascriptNumber::GetValue(item);
  1221. int32 ivalue;
  1222. if (JavascriptNumber::TryGetInt32Value(dvalue, &ivalue) && !Js::SparseArraySegment<int32>::IsMissingItem(&ivalue))
  1223. {
  1224. this->DirectSetItemAt(i, ivalue);
  1225. }
  1226. else
  1227. {
  1228. #if ENABLE_PROFILE_INFO
  1229. if (arrayInfo)
  1230. {
  1231. arrayInfo->SetIsNotNativeIntArray();
  1232. }
  1233. #endif
  1234. if (HasInlineHeadSegment(length) && i < this->head->length && !dontCreateNewArray)
  1235. {
  1236. // Avoid shrinking the number of elements in the head segment. We can still create a new
  1237. // array here, so go ahead.
  1238. JavascriptNativeFloatArray *fArr =
  1239. this->GetScriptContext()->GetLibrary()->CreateNativeFloatArrayLiteral(length);
  1240. return fArr->JavascriptNativeFloatArray::FillFromArgs(length, 0, args);
  1241. }
  1242. JavascriptNativeFloatArray *fArr = JavascriptNativeIntArray::ToNativeFloatArray(this);
  1243. fArr->DirectSetItemAt(i, dvalue);
  1244. #if ENABLE_PROFILE_INFO
  1245. return fArr->JavascriptNativeFloatArray::FillFromArgs(length, i + 1, args, arrayInfo, dontCreateNewArray);
  1246. #else
  1247. return fArr->JavascriptNativeFloatArray::FillFromArgs(length, i + 1, args, dontCreateNewArray);
  1248. #endif
  1249. }
  1250. }
  1251. else
  1252. {
  1253. #if ENABLE_PROFILE_INFO
  1254. if (arrayInfo)
  1255. {
  1256. arrayInfo->SetIsNotNativeArray();
  1257. }
  1258. #endif
  1259. #pragma prefast(suppress:6237, "The right hand side condition does not have any side effects.")
  1260. if (sizeof(int32) < sizeof(Var) && HasInlineHeadSegment(length) && i < this->head->length && !dontCreateNewArray)
  1261. {
  1262. // Avoid shrinking the number of elements in the head segment. We can still create a new
  1263. // array here, so go ahead.
  1264. JavascriptArray *arr = this->GetScriptContext()->GetLibrary()->CreateArrayLiteral(length);
  1265. return arr->JavascriptArray::FillFromArgs(length, 0, args);
  1266. }
  1267. JavascriptArray *arr = JavascriptNativeIntArray::ToVarArray(this);
  1268. #if ENABLE_PROFILE_INFO
  1269. return arr->JavascriptArray::FillFromArgs(length, i, args, nullptr, dontCreateNewArray);
  1270. #else
  1271. return arr->JavascriptArray::FillFromArgs(length, i, args, dontCreateNewArray);
  1272. #endif
  1273. }
  1274. }
  1275. return this;
  1276. }
  1277. #if ENABLE_PROFILE_INFO
  1278. JavascriptArray * JavascriptNativeFloatArray::FillFromArgs(uint length, uint start, Var *args, ArrayCallSiteInfo *arrayInfo, bool dontCreateNewArray)
  1279. #else
  1280. JavascriptArray * JavascriptNativeFloatArray::FillFromArgs(uint length, uint start, Var *args, bool dontCreateNewArray)
  1281. #endif
  1282. {
  1283. uint i;
  1284. for (i = start; i < length; i++)
  1285. {
  1286. Var item = args[i + 1];
  1287. if (TaggedInt::Is(item))
  1288. {
  1289. this->DirectSetItemAt(i, TaggedInt::ToDouble(item));
  1290. }
  1291. else if (JavascriptNumber::Is_NoTaggedIntCheck(item))
  1292. {
  1293. this->DirectSetItemAt(i, JavascriptNumber::GetValue(item));
  1294. }
  1295. else
  1296. {
  1297. JavascriptArray *arr = JavascriptNativeFloatArray::ToVarArray(this);
  1298. #if ENABLE_PROFILE_INFO
  1299. if (arrayInfo)
  1300. {
  1301. arrayInfo->SetIsNotNativeArray();
  1302. }
  1303. return arr->JavascriptArray::FillFromArgs(length, i, args, nullptr, dontCreateNewArray);
  1304. #else
  1305. return arr->JavascriptArray::FillFromArgs(length, i, args, dontCreateNewArray);
  1306. #endif
  1307. }
  1308. }
  1309. return this;
  1310. }
  1311. #if ENABLE_PROFILE_INFO
  1312. JavascriptArray * JavascriptArray::FillFromArgs(uint length, uint start, Var *args, ArrayCallSiteInfo *arrayInfo, bool dontCreateNewArray)
  1313. #else
  1314. JavascriptArray * JavascriptArray::FillFromArgs(uint length, uint start, Var *args, bool dontCreateNewArray)
  1315. #endif
  1316. {
  1317. uint32 i;
  1318. for (i = start; i < length; i++)
  1319. {
  1320. Var item = args[i + 1];
  1321. this->DirectSetItemAt(i, item);
  1322. }
  1323. return this;
  1324. }
  1325. DynamicType * JavascriptNativeIntArray::GetInitialType(ScriptContext * scriptContext)
  1326. {
  1327. return scriptContext->GetLibrary()->GetNativeIntArrayType();
  1328. }
  1329. #if ENABLE_COPYONACCESS_ARRAY
  1330. DynamicType * JavascriptCopyOnAccessNativeIntArray::GetInitialType(ScriptContext * scriptContext)
  1331. {
  1332. return scriptContext->GetLibrary()->GetCopyOnAccessNativeIntArrayType();
  1333. }
  1334. #endif
  1335. JavascriptNativeFloatArray *JavascriptNativeIntArray::ToNativeFloatArray(JavascriptNativeIntArray *intArray)
  1336. {
  1337. #if ENABLE_PROFILE_INFO
  1338. ArrayCallSiteInfo *arrayInfo = intArray->GetArrayCallSiteInfo();
  1339. if (arrayInfo)
  1340. {
  1341. #if DBG
  1342. Js::JavascriptStackWalker walker(intArray->GetScriptContext());
  1343. Js::JavascriptFunction* caller = NULL;
  1344. bool foundScriptCaller = false;
  1345. while(walker.GetCaller(&caller))
  1346. {
  1347. if(caller != NULL && Js::ScriptFunction::Is(caller))
  1348. {
  1349. foundScriptCaller = true;
  1350. break;
  1351. }
  1352. }
  1353. if(foundScriptCaller)
  1354. {
  1355. Assert(caller);
  1356. Assert(caller->GetFunctionBody());
  1357. if(PHASE_TRACE(Js::NativeArrayConversionPhase, caller->GetFunctionBody()))
  1358. {
  1359. Output::Print(_u("Conversion: Int array to Float array ArrayCreationFunctionNumber:%2d CallSiteNumber:%2d \n"), arrayInfo->functionNumber, arrayInfo->callSiteNumber);
  1360. Output::Flush();
  1361. }
  1362. }
  1363. else
  1364. {
  1365. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1366. {
  1367. Output::Print(_u("Conversion: Int array to Float array across ScriptContexts"));
  1368. Output::Flush();
  1369. }
  1370. }
  1371. #else
  1372. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1373. {
  1374. Output::Print(_u("Conversion: Int array to Float array"));
  1375. Output::Flush();
  1376. }
  1377. #endif
  1378. arrayInfo->SetIsNotNativeIntArray();
  1379. }
  1380. #endif
  1381. // Grow the segments
  1382. ScriptContext *scriptContext = intArray->GetScriptContext();
  1383. Recycler *recycler = scriptContext->GetRecycler();
  1384. SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
  1385. for (seg = intArray->head; seg; seg = nextSeg)
  1386. {
  1387. nextSeg = seg->next;
  1388. uint32 size = seg->size;
  1389. if (size == 0)
  1390. {
  1391. continue;
  1392. }
  1393. uint32 left = seg->left;
  1394. uint32 length = seg->length;
  1395. int i;
  1396. int32 ival;
  1397. // The old segment will have size/2 and length capped by the new size.
  1398. uint32 newSegSize = seg->size >> 1;
  1399. if (seg == intArray->head || seg->length > (newSegSize >> 1))
  1400. {
  1401. // Some live elements are being pushed out of this segment, so allocate a new one.
  1402. SparseArraySegment<double> *newSeg =
  1403. SparseArraySegment<double>::AllocateSegment(recycler, left, length, nextSeg);
  1404. Assert(newSeg != nullptr);
  1405. Assert((prevSeg == nullptr) == (seg == intArray->head));
  1406. newSeg->next = nextSeg;
  1407. intArray->LinkSegments((SparseArraySegment<double>*)prevSeg, newSeg);
  1408. if (intArray->GetLastUsedSegment() == seg)
  1409. {
  1410. intArray->SetLastUsedSegment(newSeg);
  1411. }
  1412. prevSeg = newSeg;
  1413. SegmentBTree * segmentMap = intArray->GetSegmentMap();
  1414. if (segmentMap)
  1415. {
  1416. segmentMap->SwapSegment(left, seg, newSeg);
  1417. }
  1418. // Fill the new segment with the overflow.
  1419. for (i = 0; (uint)i < newSeg->length; i++)
  1420. {
  1421. ival = ((SparseArraySegment<int32>*)seg)->elements[i /*+ seg->length*/];
  1422. if (ival == JavascriptNativeIntArray::MissingItem)
  1423. {
  1424. continue;
  1425. }
  1426. newSeg->elements[i] = (double)ival;
  1427. }
  1428. }
  1429. else
  1430. {
  1431. seg->size = newSegSize >> 1;
  1432. seg->CheckLengthvsSize();
  1433. // Now convert the contents that will remain in the old segment.
  1434. for (i = seg->length - 1; i >= 0; i--)
  1435. {
  1436. ival = ((SparseArraySegment<int32>*)seg)->elements[i];
  1437. if (ival == JavascriptNativeIntArray::MissingItem)
  1438. {
  1439. ((SparseArraySegment<double>*)seg)->elements[i] = (double)JavascriptNativeFloatArray::MissingItem;
  1440. }
  1441. else
  1442. {
  1443. ((SparseArraySegment<double>*)seg)->elements[i] = (double)ival;
  1444. }
  1445. }
  1446. prevSeg = seg;
  1447. }
  1448. }
  1449. if (intArray->GetType() == scriptContext->GetLibrary()->GetNativeIntArrayType())
  1450. {
  1451. intArray->type = scriptContext->GetLibrary()->GetNativeFloatArrayType();
  1452. }
  1453. else
  1454. {
  1455. if (intArray->GetDynamicType()->GetIsLocked())
  1456. {
  1457. DynamicTypeHandler *typeHandler = intArray->GetDynamicType()->GetTypeHandler();
  1458. if (typeHandler->IsPathTypeHandler())
  1459. {
  1460. // We can't allow a type with the new type ID to be promoted to the old type.
  1461. // So go to a dictionary type handler, which will orphan the new type.
  1462. // This should be a corner case, so the inability to share the new type is unlikely to matter.
  1463. // If it does matter, try building a path from the new type's built-in root.
  1464. static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(intArray);
  1465. }
  1466. else
  1467. {
  1468. intArray->ChangeType();
  1469. }
  1470. }
  1471. intArray->GetType()->SetTypeId(TypeIds_NativeFloatArray);
  1472. }
  1473. if (CrossSite::IsCrossSiteObjectTyped(intArray))
  1474. {
  1475. Assert(VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::HasVirtualTable(intArray));
  1476. VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::SetVirtualTable(intArray);
  1477. }
  1478. else
  1479. {
  1480. Assert(VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(intArray));
  1481. VirtualTableInfo<JavascriptNativeFloatArray>::SetVirtualTable(intArray);
  1482. }
  1483. return (JavascriptNativeFloatArray*)intArray;
  1484. }
  1485. /*
  1486. * JavascriptArray::ChangeArrayTypeToNativeArray<double>
  1487. * - Converts the Var Array's type to NativeFloat.
  1488. * - Sets the VirtualTable to "JavascriptNativeFloatArray"
  1489. */
  1490. template<>
  1491. void JavascriptArray::ChangeArrayTypeToNativeArray<double>(JavascriptArray * varArray, ScriptContext * scriptContext)
  1492. {
  1493. AssertMsg(!JavascriptNativeArray::Is(varArray), "Ensure that the incoming Array is a Var array");
  1494. if (varArray->GetType() == scriptContext->GetLibrary()->GetArrayType())
  1495. {
  1496. varArray->type = scriptContext->GetLibrary()->GetNativeFloatArrayType();
  1497. }
  1498. else
  1499. {
  1500. if (varArray->GetDynamicType()->GetIsLocked())
  1501. {
  1502. DynamicTypeHandler *typeHandler = varArray->GetDynamicType()->GetTypeHandler();
  1503. if (typeHandler->IsPathTypeHandler())
  1504. {
  1505. // We can't allow a type with the new type ID to be promoted to the old type.
  1506. // So go to a dictionary type handler, which will orphan the new type.
  1507. // This should be a corner case, so the inability to share the new type is unlikely to matter.
  1508. // If it does matter, try building a path from the new type's built-in root.
  1509. static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(varArray);
  1510. }
  1511. else
  1512. {
  1513. varArray->ChangeType();
  1514. }
  1515. }
  1516. varArray->GetType()->SetTypeId(TypeIds_NativeFloatArray);
  1517. }
  1518. if (CrossSite::IsCrossSiteObjectTyped(varArray))
  1519. {
  1520. Assert(VirtualTableInfo<CrossSiteObject<JavascriptArray>>::HasVirtualTable(varArray));
  1521. VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::SetVirtualTable(varArray);
  1522. }
  1523. else
  1524. {
  1525. Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(varArray));
  1526. VirtualTableInfo<JavascriptNativeFloatArray>::SetVirtualTable(varArray);
  1527. }
  1528. }
  1529. /*
  1530. * JavascriptArray::ChangeArrayTypeToNativeArray<int32>
  1531. * - Converts the Var Array's type to NativeInt.
  1532. * - Sets the VirtualTable to "JavascriptNativeIntArray"
  1533. */
  1534. template<>
  1535. void JavascriptArray::ChangeArrayTypeToNativeArray<int32>(JavascriptArray * varArray, ScriptContext * scriptContext)
  1536. {
  1537. AssertMsg(!JavascriptNativeArray::Is(varArray), "Ensure that the incoming Array is a Var array");
  1538. if (varArray->GetType() == scriptContext->GetLibrary()->GetArrayType())
  1539. {
  1540. varArray->type = scriptContext->GetLibrary()->GetNativeIntArrayType();
  1541. }
  1542. else
  1543. {
  1544. if (varArray->GetDynamicType()->GetIsLocked())
  1545. {
  1546. DynamicTypeHandler *typeHandler = varArray->GetDynamicType()->GetTypeHandler();
  1547. if (typeHandler->IsPathTypeHandler())
  1548. {
  1549. // We can't allow a type with the new type ID to be promoted to the old type.
  1550. // So go to a dictionary type handler, which will orphan the new type.
  1551. // This should be a corner case, so the inability to share the new type is unlikely to matter.
  1552. // If it does matter, try building a path from the new type's built-in root.
  1553. static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(varArray);
  1554. }
  1555. else
  1556. {
  1557. varArray->ChangeType();
  1558. }
  1559. }
  1560. varArray->GetType()->SetTypeId(TypeIds_NativeIntArray);
  1561. }
  1562. if (CrossSite::IsCrossSiteObjectTyped(varArray))
  1563. {
  1564. Assert(VirtualTableInfo<CrossSiteObject<JavascriptArray>>::HasVirtualTable(varArray));
  1565. VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::SetVirtualTable(varArray);
  1566. }
  1567. else
  1568. {
  1569. Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(varArray));
  1570. VirtualTableInfo<JavascriptNativeIntArray>::SetVirtualTable(varArray);
  1571. }
  1572. }
  1573. template<>
  1574. int32 JavascriptArray::GetNativeValue<int32>(Js::Var ival, ScriptContext * scriptContext)
  1575. {
  1576. return JavascriptConversion::ToInt32(ival, scriptContext);
  1577. }
  1578. template <>
  1579. double JavascriptArray::GetNativeValue<double>(Var ival, ScriptContext * scriptContext)
  1580. {
  1581. return JavascriptConversion::ToNumber(ival, scriptContext);
  1582. }
  1583. /*
  1584. * JavascriptArray::ConvertToNativeArrayInPlace
  1585. * In place conversion of all Var elements to Native Int/Double elements in an array.
  1586. * We do not update the DynamicProfileInfo of the array here.
  1587. */
  1588. template<typename NativeArrayType, typename T>
  1589. NativeArrayType *JavascriptArray::ConvertToNativeArrayInPlace(JavascriptArray *varArray)
  1590. {
  1591. AssertMsg(!JavascriptNativeArray::Is(varArray), "Ensure that the incoming Array is a Var array");
  1592. ScriptContext *scriptContext = varArray->GetScriptContext();
  1593. SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
  1594. for (seg = varArray->head; seg; seg = nextSeg)
  1595. {
  1596. nextSeg = seg->next;
  1597. uint32 size = seg->size;
  1598. if (size == 0)
  1599. {
  1600. continue;
  1601. }
  1602. int i;
  1603. Var ival;
  1604. uint32 growFactor = sizeof(Var) / sizeof(T);
  1605. AssertMsg(growFactor == 1, "We support only in place conversion of Var array to Native Array");
  1606. // Now convert the contents that will remain in the old segment.
  1607. for (i = seg->length - 1; i >= 0; i--)
  1608. {
  1609. ival = ((SparseArraySegment<Var>*)seg)->elements[i];
  1610. if (ival == JavascriptArray::MissingItem)
  1611. {
  1612. ((SparseArraySegment<T>*)seg)->elements[i] = NativeArrayType::MissingItem;
  1613. }
  1614. else
  1615. {
  1616. ((SparseArraySegment<T>*)seg)->elements[i] = GetNativeValue<T>(ival, scriptContext);
  1617. }
  1618. }
  1619. prevSeg = seg;
  1620. }
  1621. // Update the type of the Array
  1622. ChangeArrayTypeToNativeArray<T>(varArray, scriptContext);
  1623. return (NativeArrayType*)varArray;
  1624. }
  1625. JavascriptArray *JavascriptNativeIntArray::ConvertToVarArray(JavascriptNativeIntArray *intArray)
  1626. {
  1627. #if ENABLE_COPYONACCESS_ARRAY
  1628. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(intArray);
  1629. #endif
  1630. ScriptContext *scriptContext = intArray->GetScriptContext();
  1631. Recycler *recycler = scriptContext->GetRecycler();
  1632. SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
  1633. for (seg = intArray->head; seg; seg = nextSeg)
  1634. {
  1635. nextSeg = seg->next;
  1636. uint32 size = seg->size;
  1637. if (size == 0)
  1638. {
  1639. continue;
  1640. }
  1641. uint32 left = seg->left;
  1642. uint32 length = seg->length;
  1643. int i;
  1644. int32 ival;
  1645. // Shrink?
  1646. uint32 growFactor = sizeof(Var) / sizeof(int32);
  1647. if ((growFactor != 1 && (seg == intArray->head || seg->length > (seg->size / growFactor))) ||
  1648. (seg->next == nullptr && SparseArraySegmentBase::IsLeafSegment(seg, recycler)))
  1649. {
  1650. // Some live elements are being pushed out of this segment, so allocate a new one.
  1651. // And/or the old segment is not scanned by the recycler, so we need a new one to hold vars.
  1652. SparseArraySegment<Var> *newSeg =
  1653. SparseArraySegment<Var>::AllocateSegment(recycler, left, length, nextSeg);
  1654. AnalysisAssert(newSeg);
  1655. Assert((prevSeg == nullptr) == (seg == intArray->head));
  1656. newSeg->next = nextSeg;
  1657. intArray->LinkSegments((SparseArraySegment<Var>*)prevSeg, newSeg);
  1658. if (intArray->GetLastUsedSegment() == seg)
  1659. {
  1660. intArray->SetLastUsedSegment(newSeg);
  1661. }
  1662. prevSeg = newSeg;
  1663. SegmentBTree * segmentMap = intArray->GetSegmentMap();
  1664. if (segmentMap)
  1665. {
  1666. segmentMap->SwapSegment(left, seg, newSeg);
  1667. }
  1668. // Fill the new segment with the overflow.
  1669. for (i = 0; (uint)i < newSeg->length; i++)
  1670. {
  1671. ival = ((SparseArraySegment<int32>*)seg)->elements[i];
  1672. if (ival == JavascriptNativeIntArray::MissingItem)
  1673. {
  1674. continue;
  1675. }
  1676. newSeg->elements[i] = JavascriptNumber::ToVar(ival, scriptContext);
  1677. }
  1678. }
  1679. else
  1680. {
  1681. seg->size = seg->size / growFactor;
  1682. seg->CheckLengthvsSize();
  1683. // Now convert the contents that will remain in the old segment.
  1684. // Walk backward in case we're growing the element size.
  1685. for (i = seg->length - 1; i >= 0; i--)
  1686. {
  1687. ival = ((SparseArraySegment<int32>*)seg)->elements[i];
  1688. if (ival == JavascriptNativeIntArray::MissingItem)
  1689. {
  1690. ((SparseArraySegment<Var>*)seg)->elements[i] = (Var)JavascriptArray::MissingItem;
  1691. }
  1692. else
  1693. {
  1694. ((SparseArraySegment<Var>*)seg)->elements[i] = JavascriptNumber::ToVar(ival, scriptContext);
  1695. }
  1696. }
  1697. prevSeg = seg;
  1698. }
  1699. }
  1700. if (intArray->GetType() == scriptContext->GetLibrary()->GetNativeIntArrayType())
  1701. {
  1702. intArray->type = scriptContext->GetLibrary()->GetArrayType();
  1703. }
  1704. else
  1705. {
  1706. if (intArray->GetDynamicType()->GetIsLocked())
  1707. {
  1708. DynamicTypeHandler *typeHandler = intArray->GetDynamicType()->GetTypeHandler();
  1709. if (typeHandler->IsPathTypeHandler())
  1710. {
  1711. // We can't allow a type with the new type ID to be promoted to the old type.
  1712. // So go to a dictionary type handler, which will orphan the new type.
  1713. // This should be a corner case, so the inability to share the new type is unlikely to matter.
  1714. // If it does matter, try building a path from the new type's built-in root.
  1715. static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(intArray);
  1716. }
  1717. else
  1718. {
  1719. intArray->ChangeType();
  1720. }
  1721. }
  1722. intArray->GetType()->SetTypeId(TypeIds_Array);
  1723. }
  1724. if (CrossSite::IsCrossSiteObjectTyped(intArray))
  1725. {
  1726. Assert(VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::HasVirtualTable(intArray));
  1727. VirtualTableInfo<CrossSiteObject<JavascriptArray>>::SetVirtualTable(intArray);
  1728. }
  1729. else
  1730. {
  1731. Assert(VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(intArray));
  1732. VirtualTableInfo<JavascriptArray>::SetVirtualTable(intArray);
  1733. }
  1734. return intArray;
  1735. }
  1736. JavascriptArray *JavascriptNativeIntArray::ToVarArray(JavascriptNativeIntArray *intArray)
  1737. {
  1738. #if ENABLE_PROFILE_INFO
  1739. ArrayCallSiteInfo *arrayInfo = intArray->GetArrayCallSiteInfo();
  1740. if (arrayInfo)
  1741. {
  1742. #if DBG
  1743. Js::JavascriptStackWalker walker(intArray->GetScriptContext());
  1744. Js::JavascriptFunction* caller = NULL;
  1745. bool foundScriptCaller = false;
  1746. while(walker.GetCaller(&caller))
  1747. {
  1748. if(caller != NULL && Js::ScriptFunction::Is(caller))
  1749. {
  1750. foundScriptCaller = true;
  1751. break;
  1752. }
  1753. }
  1754. if(foundScriptCaller)
  1755. {
  1756. Assert(caller);
  1757. Assert(caller->GetFunctionBody());
  1758. if(PHASE_TRACE(Js::NativeArrayConversionPhase, caller->GetFunctionBody()))
  1759. {
  1760. Output::Print(_u("Conversion: Int array to Var array ArrayCreationFunctionNumber:%2d CallSiteNumber:%2d \n"), arrayInfo->functionNumber, arrayInfo->callSiteNumber);
  1761. Output::Flush();
  1762. }
  1763. }
  1764. else
  1765. {
  1766. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1767. {
  1768. Output::Print(_u("Conversion: Int array to Var array across ScriptContexts"));
  1769. Output::Flush();
  1770. }
  1771. }
  1772. #else
  1773. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1774. {
  1775. Output::Print(_u("Conversion: Int array to Var array"));
  1776. Output::Flush();
  1777. }
  1778. #endif
  1779. arrayInfo->SetIsNotNativeArray();
  1780. }
  1781. #endif
  1782. intArray->ClearArrayCallSiteIndex();
  1783. return ConvertToVarArray(intArray);
  1784. }
  1785. DynamicType * JavascriptNativeFloatArray::GetInitialType(ScriptContext * scriptContext)
  1786. {
  1787. return scriptContext->GetLibrary()->GetNativeFloatArrayType();
  1788. }
  1789. /*
  1790. * JavascriptNativeFloatArray::ConvertToVarArray
  1791. * This function only converts all Float elements to Var elements in an array.
  1792. * DynamicProfileInfo of the array is not updated in this function.
  1793. */
  1794. JavascriptArray *JavascriptNativeFloatArray::ConvertToVarArray(JavascriptNativeFloatArray *fArray)
  1795. {
  1796. // We can't be growing the size of the element.
  1797. Assert(sizeof(double) >= sizeof(Var));
  1798. uint32 shrinkFactor = sizeof(double) / sizeof(Var);
  1799. ScriptContext *scriptContext = fArray->GetScriptContext();
  1800. Recycler *recycler = scriptContext->GetRecycler();
  1801. SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
  1802. for (seg = fArray->head; seg; seg = nextSeg)
  1803. {
  1804. nextSeg = seg->next;
  1805. if (seg->size == 0)
  1806. {
  1807. continue;
  1808. }
  1809. uint32 left = seg->left;
  1810. uint32 length = seg->length;
  1811. SparseArraySegment<Var> *newSeg;
  1812. if (seg->next == nullptr && SparseArraySegmentBase::IsLeafSegment(seg, recycler))
  1813. {
  1814. // The old segment is not scanned by the recycler, so we need a new one to hold vars.
  1815. newSeg =
  1816. SparseArraySegment<Var>::AllocateSegment(recycler, left, length, nextSeg);
  1817. Assert((prevSeg == nullptr) == (seg == fArray->head));
  1818. newSeg->next = nextSeg;
  1819. fArray->LinkSegments((SparseArraySegment<Var>*)prevSeg, newSeg);
  1820. if (fArray->GetLastUsedSegment() == seg)
  1821. {
  1822. fArray->SetLastUsedSegment(newSeg);
  1823. }
  1824. prevSeg = newSeg;
  1825. SegmentBTree * segmentMap = fArray->GetSegmentMap();
  1826. if (segmentMap)
  1827. {
  1828. segmentMap->SwapSegment(left, seg, newSeg);
  1829. }
  1830. }
  1831. else
  1832. {
  1833. newSeg = (SparseArraySegment<Var>*)seg;
  1834. prevSeg = seg;
  1835. if (shrinkFactor != 1)
  1836. {
  1837. uint32 newSize = seg->size * shrinkFactor;
  1838. uint32 limit;
  1839. if (seg->next)
  1840. {
  1841. limit = seg->next->left;
  1842. }
  1843. else
  1844. {
  1845. limit = JavascriptArray::MaxArrayLength;
  1846. }
  1847. seg->size = min(newSize, limit - seg->left);
  1848. }
  1849. }
  1850. uint32 i;
  1851. for (i = 0; i < seg->length; i++)
  1852. {
  1853. if (SparseArraySegment<double>::IsMissingItem(&((SparseArraySegment<double>*)seg)->elements[i]))
  1854. {
  1855. if (seg == newSeg)
  1856. {
  1857. newSeg->elements[i] = (Var)JavascriptArray::MissingItem;
  1858. }
  1859. Assert(newSeg->elements[i] == (Var)JavascriptArray::MissingItem);
  1860. }
  1861. else if (*(uint64*)&(((SparseArraySegment<double>*)seg)->elements[i]) == 0ull)
  1862. {
  1863. newSeg->elements[i] = TaggedInt::ToVarUnchecked(0);
  1864. }
  1865. else
  1866. {
  1867. int32 ival;
  1868. double dval = ((SparseArraySegment<double>*)seg)->elements[i];
  1869. if (JavascriptNumber::TryGetInt32Value(dval, &ival) && !TaggedInt::IsOverflow(ival))
  1870. {
  1871. newSeg->elements[i] = TaggedInt::ToVarUnchecked(ival);
  1872. }
  1873. else
  1874. {
  1875. newSeg->elements[i] = JavascriptNumber::ToVarWithCheck(dval, scriptContext);
  1876. }
  1877. }
  1878. }
  1879. if (seg == newSeg && shrinkFactor != 1)
  1880. {
  1881. // Fill the remaining slots.
  1882. newSeg->FillSegmentBuffer(i, seg->size);
  1883. }
  1884. }
  1885. if (fArray->GetType() == scriptContext->GetLibrary()->GetNativeFloatArrayType())
  1886. {
  1887. fArray->type = scriptContext->GetLibrary()->GetArrayType();
  1888. }
  1889. else
  1890. {
  1891. if (fArray->GetDynamicType()->GetIsLocked())
  1892. {
  1893. DynamicTypeHandler *typeHandler = fArray->GetDynamicType()->GetTypeHandler();
  1894. if (typeHandler->IsPathTypeHandler())
  1895. {
  1896. // We can't allow a type with the new type ID to be promoted to the old type.
  1897. // So go to a dictionary type handler, which will orphan the new type.
  1898. // This should be a corner case, so the inability to share the new type is unlikely to matter.
  1899. // If it does matter, try building a path from the new type's built-in root.
  1900. static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(fArray);
  1901. }
  1902. else
  1903. {
  1904. fArray->ChangeType();
  1905. }
  1906. }
  1907. fArray->GetType()->SetTypeId(TypeIds_Array);
  1908. }
  1909. if (CrossSite::IsCrossSiteObjectTyped(fArray))
  1910. {
  1911. Assert(VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::HasVirtualTable(fArray));
  1912. VirtualTableInfo<CrossSiteObject<JavascriptArray>>::SetVirtualTable(fArray);
  1913. }
  1914. else
  1915. {
  1916. Assert(VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(fArray));
  1917. VirtualTableInfo<JavascriptArray>::SetVirtualTable(fArray);
  1918. }
  1919. return fArray;
  1920. }
  1921. JavascriptArray *JavascriptNativeFloatArray::ToVarArray(JavascriptNativeFloatArray *fArray)
  1922. {
  1923. #if ENABLE_PROFILE_INFO
  1924. ArrayCallSiteInfo *arrayInfo = fArray->GetArrayCallSiteInfo();
  1925. if (arrayInfo)
  1926. {
  1927. #if DBG
  1928. Js::JavascriptStackWalker walker(fArray->GetScriptContext());
  1929. Js::JavascriptFunction* caller = NULL;
  1930. bool foundScriptCaller = false;
  1931. while(walker.GetCaller(&caller))
  1932. {
  1933. if(caller != NULL && Js::ScriptFunction::Is(caller))
  1934. {
  1935. foundScriptCaller = true;
  1936. break;
  1937. }
  1938. }
  1939. if(foundScriptCaller)
  1940. {
  1941. Assert(caller);
  1942. Assert(caller->GetFunctionBody());
  1943. if(PHASE_TRACE(Js::NativeArrayConversionPhase, caller->GetFunctionBody()))
  1944. {
  1945. Output::Print(_u("Conversion: Float array to Var array ArrayCreationFunctionNumber:%2d CallSiteNumber:%2d \n"), arrayInfo->functionNumber, arrayInfo->callSiteNumber);
  1946. Output::Flush();
  1947. }
  1948. }
  1949. else
  1950. {
  1951. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1952. {
  1953. Output::Print(_u("Conversion: Float array to Var array across ScriptContexts"));
  1954. Output::Flush();
  1955. }
  1956. }
  1957. #else
  1958. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1959. {
  1960. Output::Print(_u("Conversion: Float array to Var array"));
  1961. Output::Flush();
  1962. }
  1963. #endif
  1964. if(fArray->GetScriptContext()->IsScriptContextInNonDebugMode())
  1965. {
  1966. Assert(!arrayInfo->IsNativeIntArray());
  1967. }
  1968. arrayInfo->SetIsNotNativeArray();
  1969. }
  1970. #endif
  1971. fArray->ClearArrayCallSiteIndex();
  1972. return ConvertToVarArray(fArray);
  1973. }
  1974. // Convert Var to index in the Array.
  1975. // Note: Spec calls out a few rules for these parameters:
  1976. // 1. if (arg > length) { return length; }
  1977. // clamp to length, not length-1
  1978. // 2. if (arg < 0) { return max(0, length + arg); }
  1979. // treat negative arg as index from the end of the array (with -1 mapping to length-1)
  1980. // Effectively, this function will return a value between 0 and length, inclusive.
  1981. int64 JavascriptArray::GetIndexFromVar(Js::Var arg, int64 length, ScriptContext* scriptContext)
  1982. {
  1983. int64 index;
  1984. if (TaggedInt::Is(arg))
  1985. {
  1986. int intValue = TaggedInt::ToInt32(arg);
  1987. if (intValue < 0)
  1988. {
  1989. index = max<int64>(0, length + intValue);
  1990. }
  1991. else
  1992. {
  1993. index = intValue;
  1994. }
  1995. if (index > length)
  1996. {
  1997. index = length;
  1998. }
  1999. }
  2000. else
  2001. {
  2002. double doubleValue = JavascriptConversion::ToInteger(arg, scriptContext);
  2003. // Handle the Number.POSITIVE_INFINITY case
  2004. if (doubleValue > length)
  2005. {
  2006. return length;
  2007. }
  2008. index = NumberUtilities::TryToInt64(doubleValue);
  2009. if (index < 0)
  2010. {
  2011. index = max<int64>(0, index + length);
  2012. }
  2013. }
  2014. return index;
  2015. }
  2016. TypeId JavascriptArray::OP_SetNativeIntElementC(JavascriptNativeIntArray *arr, uint32 index, Var value, ScriptContext *scriptContext)
  2017. {
  2018. int32 iValue;
  2019. double dValue;
  2020. TypeId typeId = arr->TrySetNativeIntArrayItem(value, &iValue, &dValue);
  2021. if (typeId == TypeIds_NativeIntArray)
  2022. {
  2023. arr->SetArrayLiteralItem(index, iValue);
  2024. }
  2025. else if (typeId == TypeIds_NativeFloatArray)
  2026. {
  2027. arr->SetArrayLiteralItem(index, dValue);
  2028. }
  2029. else
  2030. {
  2031. arr->SetArrayLiteralItem(index, value);
  2032. }
  2033. return typeId;
  2034. }
  2035. TypeId JavascriptArray::OP_SetNativeFloatElementC(JavascriptNativeFloatArray *arr, uint32 index, Var value, ScriptContext *scriptContext)
  2036. {
  2037. double dValue;
  2038. TypeId typeId = arr->TrySetNativeFloatArrayItem(value, &dValue);
  2039. if (typeId == TypeIds_NativeFloatArray)
  2040. {
  2041. arr->SetArrayLiteralItem(index, dValue);
  2042. }
  2043. else
  2044. {
  2045. arr->SetArrayLiteralItem(index, value);
  2046. }
  2047. return typeId;
  2048. }
  2049. template<typename T>
  2050. void JavascriptArray::SetArrayLiteralItem(uint32 index, T value)
  2051. {
  2052. SparseArraySegment<T> * segment = SparseArraySegment<T>::From(this->head);
  2053. Assert(segment->left == 0);
  2054. Assert(index < segment->length);
  2055. segment->elements[index] = value;
  2056. }
  2057. void JavascriptNativeIntArray::SetIsPrototype()
  2058. {
  2059. // Force the array to be non-native to simplify inspection, filling from proto, etc.
  2060. ToVarArray(this);
  2061. __super::SetIsPrototype();
  2062. }
  2063. void JavascriptNativeFloatArray::SetIsPrototype()
  2064. {
  2065. // Force the array to be non-native to simplify inspection, filling from proto, etc.
  2066. ToVarArray(this);
  2067. __super::SetIsPrototype();
  2068. }
  2069. #if ENABLE_PROFILE_INFO
  2070. ArrayCallSiteInfo *JavascriptNativeArray::GetArrayCallSiteInfo()
  2071. {
  2072. RecyclerWeakReference<FunctionBody> *weakRef = this->weakRefToFuncBody;
  2073. if (weakRef)
  2074. {
  2075. FunctionBody *functionBody = weakRef->Get();
  2076. if (functionBody)
  2077. {
  2078. if (functionBody->HasDynamicProfileInfo())
  2079. {
  2080. Js::ProfileId profileId = this->GetArrayCallSiteIndex();
  2081. if (profileId < functionBody->GetProfiledArrayCallSiteCount())
  2082. {
  2083. return functionBody->GetAnyDynamicProfileInfo()->GetArrayCallSiteInfo(functionBody, profileId);
  2084. }
  2085. }
  2086. }
  2087. else
  2088. {
  2089. this->ClearArrayCallSiteIndex();
  2090. }
  2091. }
  2092. return nullptr;
  2093. }
  2094. void JavascriptNativeArray::SetArrayProfileInfo(RecyclerWeakReference<FunctionBody> *weakRef, ArrayCallSiteInfo *arrayInfo)
  2095. {
  2096. Assert(weakRef);
  2097. FunctionBody *functionBody = weakRef->Get();
  2098. if (functionBody && functionBody->HasDynamicProfileInfo())
  2099. {
  2100. ArrayCallSiteInfo *baseInfo = functionBody->GetAnyDynamicProfileInfo()->GetArrayCallSiteInfo(functionBody, 0);
  2101. Js::ProfileId index = (Js::ProfileId)(arrayInfo - baseInfo);
  2102. Assert(index < functionBody->GetProfiledArrayCallSiteCount());
  2103. SetArrayCallSite(index, weakRef);
  2104. }
  2105. }
  2106. void JavascriptNativeArray::CopyArrayProfileInfo(Js::JavascriptNativeArray* baseArray)
  2107. {
  2108. if (baseArray->weakRefToFuncBody)
  2109. {
  2110. if (baseArray->weakRefToFuncBody->Get())
  2111. {
  2112. SetArrayCallSite(baseArray->GetArrayCallSiteIndex(), baseArray->weakRefToFuncBody);
  2113. }
  2114. else
  2115. {
  2116. baseArray->ClearArrayCallSiteIndex();
  2117. }
  2118. }
  2119. }
  2120. #endif
  2121. Var JavascriptNativeArray::FindMinOrMax(Js::ScriptContext * scriptContext, bool findMax)
  2122. {
  2123. if (JavascriptNativeIntArray::Is(this))
  2124. {
  2125. return this->FindMinOrMax<int32, false>(scriptContext, findMax);
  2126. }
  2127. else
  2128. {
  2129. return this->FindMinOrMax<double, true>(scriptContext, findMax);
  2130. }
  2131. }
  2132. template <typename T, bool checkNaNAndNegZero>
  2133. Var JavascriptNativeArray::FindMinOrMax(Js::ScriptContext * scriptContext, bool findMax)
  2134. {
  2135. AssertMsg(this->HasNoMissingValues(), "Fastpath is only for arrays with one segment and no missing values");
  2136. uint len = this->GetLength();
  2137. Js::SparseArraySegment<T>* headSegment = ((Js::SparseArraySegment<T>*)this->GetHead());
  2138. uint headSegLen = headSegment->length;
  2139. Assert(headSegLen == len);
  2140. if (headSegment->next == nullptr)
  2141. {
  2142. T currentRes = headSegment->elements[0];
  2143. for (uint i = 0; i < headSegLen; i++)
  2144. {
  2145. T compare = headSegment->elements[i];
  2146. if (checkNaNAndNegZero && JavascriptNumber::IsNan(double(compare)))
  2147. {
  2148. return scriptContext->GetLibrary()->GetNaN();
  2149. }
  2150. if (findMax ? currentRes < compare : currentRes > compare ||
  2151. (checkNaNAndNegZero && compare == 0 && Js::JavascriptNumber::IsNegZero(double(currentRes))))
  2152. {
  2153. currentRes = compare;
  2154. }
  2155. }
  2156. return Js::JavascriptNumber::ToVarNoCheck(currentRes, scriptContext);
  2157. }
  2158. else
  2159. {
  2160. AssertMsg(false, "FindMinOrMax currently supports native arrays with only one segment");
  2161. Throw::FatalInternalError();
  2162. }
  2163. }
  2164. SparseArraySegmentBase * JavascriptArray::GetLastUsedSegment() const
  2165. {
  2166. return HasSegmentMap() ?
  2167. PointerValue(segmentUnion.segmentBTreeRoot->lastUsedSegment) :
  2168. PointerValue(segmentUnion.lastUsedSegment);
  2169. }
  2170. void JavascriptArray::SetHeadAndLastUsedSegment(SparseArraySegmentBase * segment)
  2171. {
  2172. Assert(!HasSegmentMap());
  2173. this->head = this->segmentUnion.lastUsedSegment = segment;
  2174. }
  2175. void JavascriptArray::SetLastUsedSegment(SparseArraySegmentBase * segment)
  2176. {
  2177. if (HasSegmentMap())
  2178. {
  2179. this->segmentUnion.segmentBTreeRoot->lastUsedSegment = segment;
  2180. }
  2181. else
  2182. {
  2183. this->segmentUnion.lastUsedSegment = segment;
  2184. }
  2185. }
  2186. bool JavascriptArray::HasSegmentMap() const
  2187. {
  2188. return !!(GetFlags() & DynamicObjectFlags::HasSegmentMap);
  2189. }
  2190. SegmentBTreeRoot * JavascriptArray::GetSegmentMap() const
  2191. {
  2192. return (HasSegmentMap() ? segmentUnion.segmentBTreeRoot : nullptr);
  2193. }
  2194. void JavascriptArray::SetSegmentMap(SegmentBTreeRoot * segmentMap)
  2195. {
  2196. Assert(!HasSegmentMap());
  2197. SparseArraySegmentBase * lastUsedSeg = this->segmentUnion.lastUsedSegment;
  2198. SetFlags(GetFlags() | DynamicObjectFlags::HasSegmentMap);
  2199. segmentUnion.segmentBTreeRoot = segmentMap;
  2200. segmentMap->lastUsedSegment = lastUsedSeg;
  2201. }
  2202. void JavascriptArray::ClearSegmentMap()
  2203. {
  2204. if (HasSegmentMap())
  2205. {
  2206. SetFlags(GetFlags() & ~DynamicObjectFlags::HasSegmentMap);
  2207. SparseArraySegmentBase * lastUsedSeg = segmentUnion.segmentBTreeRoot->lastUsedSegment;
  2208. segmentUnion.segmentBTreeRoot = nullptr;
  2209. segmentUnion.lastUsedSegment = lastUsedSeg;
  2210. }
  2211. }
  2212. SegmentBTreeRoot * JavascriptArray::BuildSegmentMap()
  2213. {
  2214. Recycler* recycler = GetRecycler();
  2215. SegmentBTreeRoot* tmpSegmentMap = AllocatorNewStruct(Recycler, recycler, SegmentBTreeRoot);
  2216. ForEachSegment([recycler, tmpSegmentMap](SparseArraySegmentBase * current)
  2217. {
  2218. tmpSegmentMap->Add(recycler, current);
  2219. return false;
  2220. });
  2221. // There could be OOM during building segment map. Save to array only after its successful completion.
  2222. SetSegmentMap(tmpSegmentMap);
  2223. return tmpSegmentMap;
  2224. }
  2225. void JavascriptArray::TryAddToSegmentMap(Recycler* recycler, SparseArraySegmentBase* seg)
  2226. {
  2227. SegmentBTreeRoot * savedSegmentMap = GetSegmentMap();
  2228. if (savedSegmentMap)
  2229. {
  2230. //
  2231. // We could OOM and throw when adding to segmentMap, resulting in a corrupted segmentMap on this
  2232. // array. Set segmentMap to null temporarily to protect from this. It will be restored correctly
  2233. // if adding segment succeeds.
  2234. //
  2235. ClearSegmentMap();
  2236. savedSegmentMap->Add(recycler, seg);
  2237. SetSegmentMap(savedSegmentMap);
  2238. }
  2239. }
  2240. void JavascriptArray::InvalidateLastUsedSegment()
  2241. {
  2242. this->SetLastUsedSegment(this->head);
  2243. }
  2244. DescriptorFlags JavascriptArray::GetSetter(PropertyId propertyId, Var *setterValue, PropertyValueInfo* info, ScriptContext* requestContext)
  2245. {
  2246. DescriptorFlags flags;
  2247. if (GetSetterBuiltIns(propertyId, info, &flags))
  2248. {
  2249. return flags;
  2250. }
  2251. return __super::GetSetter(propertyId, setterValue, info, requestContext);
  2252. }
  2253. DescriptorFlags JavascriptArray::GetSetter(JavascriptString* propertyNameString, Var *setterValue, PropertyValueInfo* info, ScriptContext* requestContext)
  2254. {
  2255. DescriptorFlags flags;
  2256. PropertyRecord const* propertyRecord;
  2257. this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
  2258. if (propertyRecord != nullptr && GetSetterBuiltIns(propertyRecord->GetPropertyId(), info, &flags))
  2259. {
  2260. return flags;
  2261. }
  2262. return __super::GetSetter(propertyNameString, setterValue, info, requestContext);
  2263. }
  2264. bool JavascriptArray::GetSetterBuiltIns(PropertyId propertyId, PropertyValueInfo* info, DescriptorFlags* descriptorFlags)
  2265. {
  2266. if (propertyId == PropertyIds::length)
  2267. {
  2268. PropertyValueInfo::SetNoCache(info, this);
  2269. *descriptorFlags = WritableData;
  2270. return true;
  2271. }
  2272. return false;
  2273. }
  2274. SparseArraySegmentBase * JavascriptArray::GetBeginLookupSegment(uint32 index, const bool useSegmentMap) const
  2275. {
  2276. SparseArraySegmentBase *seg = nullptr;
  2277. SparseArraySegmentBase * lastUsedSeg = this->GetLastUsedSegment();
  2278. if (lastUsedSeg != nullptr && lastUsedSeg->left <= index)
  2279. {
  2280. seg = lastUsedSeg;
  2281. if(index - lastUsedSeg->left < lastUsedSeg->size)
  2282. {
  2283. return seg;
  2284. }
  2285. }
  2286. SegmentBTreeRoot * segmentMap = GetSegmentMap();
  2287. if(!useSegmentMap || !segmentMap)
  2288. {
  2289. return seg ? seg : PointerValue(this->head);
  2290. }
  2291. if(seg)
  2292. {
  2293. // If indexes are being accessed sequentially, check the segment after the last-used segment before checking the
  2294. // segment map, as it is likely to hit
  2295. SparseArraySegmentBase *const nextSeg = seg->next;
  2296. if(nextSeg)
  2297. {
  2298. if(index < nextSeg->left)
  2299. {
  2300. return seg;
  2301. }
  2302. else if(index - nextSeg->left < nextSeg->size)
  2303. {
  2304. return nextSeg;
  2305. }
  2306. }
  2307. }
  2308. SparseArraySegmentBase *matchOrNextSeg;
  2309. segmentMap->Find(index, seg, matchOrNextSeg);
  2310. return seg ? seg : matchOrNextSeg;
  2311. }
  2312. uint32 JavascriptArray::GetNextIndex(uint32 index) const
  2313. {
  2314. if (JavascriptNativeIntArray::Is((Var)this))
  2315. {
  2316. return this->GetNextIndexHelper<int32>(index);
  2317. }
  2318. else if (JavascriptNativeFloatArray::Is((Var)this))
  2319. {
  2320. return this->GetNextIndexHelper<double>(index);
  2321. }
  2322. return this->GetNextIndexHelper<Var>(index);
  2323. }
  2324. template<typename T>
  2325. uint32 JavascriptArray::GetNextIndexHelper(uint32 index) const
  2326. {
  2327. AssertMsg(this->head, "array head should never be null");
  2328. uint candidateIndex;
  2329. if (index == JavascriptArray::InvalidIndex)
  2330. {
  2331. candidateIndex = head->left;
  2332. }
  2333. else
  2334. {
  2335. candidateIndex = index + 1;
  2336. }
  2337. SparseArraySegment<T>* current = (SparseArraySegment<T>*)this->GetBeginLookupSegment(candidateIndex);
  2338. while (current != nullptr)
  2339. {
  2340. if ((current->left <= candidateIndex) && ((candidateIndex - current->left) < current->length))
  2341. {
  2342. for (uint i = candidateIndex - current->left; i < current->length; i++)
  2343. {
  2344. if (!SparseArraySegment<T>::IsMissingItem(&current->elements[i]))
  2345. {
  2346. return i + current->left;
  2347. }
  2348. }
  2349. }
  2350. current = SparseArraySegment<T>::From(current->next);
  2351. if (current != NULL)
  2352. {
  2353. if (candidateIndex < current->left)
  2354. {
  2355. candidateIndex = current->left;
  2356. }
  2357. }
  2358. }
  2359. return JavascriptArray::InvalidIndex;
  2360. }
  2361. // If new length > length, we just reset the length
  2362. // If new length < length, we need to remove the rest of the elements and segment
  2363. void JavascriptArray::SetLength(uint32 newLength)
  2364. {
  2365. if (newLength == length)
  2366. return;
  2367. if (head == EmptySegment)
  2368. {
  2369. // Do nothing to the segment.
  2370. }
  2371. else if (newLength == 0)
  2372. {
  2373. this->ClearElements(head, 0);
  2374. head->length = 0;
  2375. head->next = nullptr;
  2376. SetHasNoMissingValues();
  2377. ClearSegmentMap();
  2378. this->InvalidateLastUsedSegment();
  2379. }
  2380. else if (newLength < length)
  2381. {
  2382. // _ _ 2 3 _ _ 6 7 _ _
  2383. // SetLength(0)
  2384. // 0 <= left -> set *prev = null
  2385. // SetLength(2)
  2386. // 2 <= left -> set *prev = null
  2387. // SetLength(3)
  2388. // 3 !<= left; 3 <= right -> truncate to length - 1
  2389. // SetLength(5)
  2390. // 5 <=
  2391. SparseArraySegmentBase* next = GetBeginLookupSegment(newLength - 1); // head, or next.left < newLength
  2392. Field(SparseArraySegmentBase*)* prev = &head;
  2393. while(next != nullptr)
  2394. {
  2395. if (newLength <= next->left)
  2396. {
  2397. ClearSegmentMap(); // truncate segments, null out segmentMap
  2398. *prev = nullptr;
  2399. break;
  2400. }
  2401. else if (newLength <= (next->left + next->length))
  2402. {
  2403. if (next->next)
  2404. {
  2405. ClearSegmentMap(); // Will truncate segments, null out segmentMap
  2406. }
  2407. uint32 newSegmentLength = newLength - next->left;
  2408. this->ClearElements(next, newSegmentLength);
  2409. next->next = nullptr;
  2410. next->length = newSegmentLength;
  2411. next->CheckLengthvsSize();
  2412. break;
  2413. }
  2414. else
  2415. {
  2416. prev = &next->next;
  2417. next = next->next;
  2418. }
  2419. }
  2420. this->InvalidateLastUsedSegment();
  2421. }
  2422. this->length = newLength;
  2423. #ifdef VALIDATE_ARRAY
  2424. ValidateArray();
  2425. #endif
  2426. }
  2427. BOOL JavascriptArray::SetLength(Var newLength)
  2428. {
  2429. ScriptContext *scriptContext;
  2430. if(TaggedInt::Is(newLength))
  2431. {
  2432. int32 lenValue = TaggedInt::ToInt32(newLength);
  2433. if (lenValue < 0)
  2434. {
  2435. scriptContext = GetScriptContext();
  2436. if (scriptContext->GetThreadContext()->RecordImplicitException())
  2437. {
  2438. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  2439. }
  2440. }
  2441. else
  2442. {
  2443. this->SetLength(lenValue);
  2444. }
  2445. return TRUE;
  2446. }
  2447. scriptContext = GetScriptContext();
  2448. uint32 uintValue = JavascriptConversion::ToUInt32(newLength, scriptContext);
  2449. double dblValue = JavascriptConversion::ToNumber(newLength, scriptContext);
  2450. if (dblValue == uintValue)
  2451. {
  2452. this->SetLength(uintValue);
  2453. }
  2454. else
  2455. {
  2456. ThreadContext* threadContext = scriptContext->GetThreadContext();
  2457. ImplicitCallFlags flags = threadContext->GetImplicitCallFlags();
  2458. if (flags != ImplicitCall_None && threadContext->IsDisableImplicitCall())
  2459. {
  2460. // We couldn't execute the implicit call(s) needed to convert the newLength to an integer.
  2461. // Do nothing and let the jitted code bail out.
  2462. return TRUE;
  2463. }
  2464. if (threadContext->RecordImplicitException())
  2465. {
  2466. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  2467. }
  2468. }
  2469. return TRUE;
  2470. }
  2471. void JavascriptArray::ClearElements(SparseArraySegmentBase *seg, uint32 newSegmentLength)
  2472. {
  2473. SparseArraySegment<Var>::ClearElements(((SparseArraySegment<Var>*)seg)->elements + newSegmentLength, seg->length - newSegmentLength);
  2474. }
  2475. void JavascriptNativeIntArray::ClearElements(SparseArraySegmentBase *seg, uint32 newSegmentLength)
  2476. {
  2477. SparseArraySegment<int32>::ClearElements(((SparseArraySegment<int32>*)seg)->elements + newSegmentLength, seg->length - newSegmentLength);
  2478. }
  2479. void JavascriptNativeFloatArray::ClearElements(SparseArraySegmentBase *seg, uint32 newSegmentLength)
  2480. {
  2481. SparseArraySegment<double>::ClearElements(((SparseArraySegment<double>*)seg)->elements + newSegmentLength, seg->length - newSegmentLength);
  2482. }
  2483. Var JavascriptArray::DirectGetItem(uint32 index)
  2484. {
  2485. SparseArraySegment<Var> *seg = (SparseArraySegment<Var>*)this->GetLastUsedSegment();
  2486. uint32 offset = index - seg->left;
  2487. if (index >= seg->left && offset < seg->length)
  2488. {
  2489. if (!SparseArraySegment<Var>::IsMissingItem(&seg->elements[offset]))
  2490. {
  2491. return seg->elements[offset];
  2492. }
  2493. }
  2494. Var element;
  2495. if (DirectGetItemAtFull(index, &element))
  2496. {
  2497. return element;
  2498. }
  2499. return GetType()->GetLibrary()->GetUndefined();
  2500. }
  2501. Var JavascriptNativeIntArray::DirectGetItem(uint32 index)
  2502. {
  2503. #if ENABLE_COPYONACCESS_ARRAY
  2504. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  2505. #endif
  2506. SparseArraySegment<int32> *seg = (SparseArraySegment<int32>*)this->GetLastUsedSegment();
  2507. uint32 offset = index - seg->left;
  2508. if (index >= seg->left && offset < seg->length)
  2509. {
  2510. if (!SparseArraySegment<int32>::IsMissingItem(&seg->elements[offset]))
  2511. {
  2512. return JavascriptNumber::ToVar(seg->elements[offset], GetScriptContext());
  2513. }
  2514. }
  2515. Var element;
  2516. if (DirectGetItemAtFull(index, &element))
  2517. {
  2518. return element;
  2519. }
  2520. return GetType()->GetLibrary()->GetUndefined();
  2521. }
  2522. DescriptorFlags JavascriptNativeIntArray::GetItemSetter(uint32 index, Var* setterValue, ScriptContext* requestContext)
  2523. {
  2524. #if ENABLE_COPYONACCESS_ARRAY
  2525. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  2526. #endif
  2527. int32 value = 0;
  2528. return this->DirectGetItemAt(index, &value) ? WritableData : None;
  2529. }
  2530. Var JavascriptNativeFloatArray::DirectGetItem(uint32 index)
  2531. {
  2532. SparseArraySegment<double> *seg = (SparseArraySegment<double>*)this->GetLastUsedSegment();
  2533. uint32 offset = index - seg->left;
  2534. if (index >= seg->left && offset < seg->length)
  2535. {
  2536. if (!SparseArraySegment<double>::IsMissingItem(&seg->elements[offset]))
  2537. {
  2538. return JavascriptNumber::ToVarWithCheck(seg->elements[offset], GetScriptContext());
  2539. }
  2540. }
  2541. Var element;
  2542. if (DirectGetItemAtFull(index, &element))
  2543. {
  2544. return element;
  2545. }
  2546. return GetType()->GetLibrary()->GetUndefined();
  2547. }
  2548. Var JavascriptArray::DirectGetItem(JavascriptString *propName, ScriptContext* scriptContext)
  2549. {
  2550. PropertyRecord const * propertyRecord;
  2551. scriptContext->GetOrAddPropertyRecord(propName->GetString(), propName->GetLength(), &propertyRecord);
  2552. return JavascriptOperators::GetProperty(this, propertyRecord->GetPropertyId(), scriptContext, NULL);
  2553. }
  2554. BOOL JavascriptArray::DirectGetItemAtFull(uint32 index, Var* outVal)
  2555. {
  2556. if (this->DirectGetItemAt(index, outVal))
  2557. {
  2558. return TRUE;
  2559. }
  2560. ScriptContext* requestContext = type->GetScriptContext();
  2561. return JavascriptOperators::GetItem(this, this->GetPrototype(), index, outVal, requestContext);
  2562. }
  2563. //
  2564. // Link prev and current. If prev is NULL, make current the head segment.
  2565. //
  2566. void JavascriptArray::LinkSegmentsCommon(SparseArraySegmentBase* prev, SparseArraySegmentBase* current)
  2567. {
  2568. if (prev)
  2569. {
  2570. prev->next = current;
  2571. }
  2572. else
  2573. {
  2574. Assert(current);
  2575. head = current;
  2576. }
  2577. }
  2578. template<typename T>
  2579. BOOL JavascriptArray::DirectDeleteItemAt(uint32 itemIndex)
  2580. {
  2581. if (itemIndex >= length)
  2582. {
  2583. return true;
  2584. }
  2585. SparseArraySegment<T>* next = (SparseArraySegment<T>*)GetBeginLookupSegment(itemIndex);
  2586. while(next != nullptr && next->left <= itemIndex)
  2587. {
  2588. uint32 limit = next->left + next->length;
  2589. if (itemIndex < limit)
  2590. {
  2591. next->SetElement(GetRecycler(), itemIndex, SparseArraySegment<T>::GetMissingItem());
  2592. if(itemIndex - next->left == next->length - 1)
  2593. {
  2594. --next->length;
  2595. next->CheckLengthvsSize();
  2596. }
  2597. else if(next == head)
  2598. {
  2599. SetHasNoMissingValues(false);
  2600. }
  2601. break;
  2602. }
  2603. next = SparseArraySegment<T>::From(next->next);
  2604. }
  2605. #ifdef VALIDATE_ARRAY
  2606. ValidateArray();
  2607. #endif
  2608. return true;
  2609. }
  2610. template <> Var JavascriptArray::ConvertToIndex(BigIndex idxDest, ScriptContext* scriptContext)
  2611. {
  2612. return idxDest.ToNumber(scriptContext);
  2613. }
  2614. template <> uint32 JavascriptArray::ConvertToIndex(BigIndex idxDest, ScriptContext* scriptContext)
  2615. {
  2616. // Note this is only for setting Array length which is a uint32
  2617. return idxDest.IsSmallIndex() ? idxDest.GetSmallIndex() : UINT_MAX;
  2618. }
  2619. template <> Var JavascriptArray::ConvertToIndex(uint32 idxDest, ScriptContext* scriptContext)
  2620. {
  2621. return JavascriptNumber::ToVar(idxDest, scriptContext);
  2622. }
  2623. void JavascriptArray::ThrowErrorOnFailure(BOOL succeeded, ScriptContext* scriptContext, uint32 index)
  2624. {
  2625. if (!succeeded)
  2626. {
  2627. JavascriptError::ThrowTypeError(scriptContext, JSERR_CantRedefineProp, JavascriptConversion::ToString(JavascriptNumber::ToVar(index, scriptContext), scriptContext)->GetSz());
  2628. }
  2629. }
  2630. void JavascriptArray::ThrowErrorOnFailure(BOOL succeeded, ScriptContext* scriptContext, BigIndex index)
  2631. {
  2632. if (!succeeded)
  2633. {
  2634. uint64 i = (uint64)(index.IsSmallIndex() ? index.GetSmallIndex() : index.GetBigIndex());
  2635. JavascriptError::ThrowTypeError(scriptContext, JSERR_CantRedefineProp, JavascriptConversion::ToString(JavascriptNumber::ToVar(i, scriptContext), scriptContext)->GetSz());
  2636. }
  2637. }
  2638. BOOL JavascriptArray::SetArrayLikeObjects(RecyclableObject* pDestObj, uint32 idxDest, Var aItem)
  2639. {
  2640. return pDestObj->SetItem(idxDest, aItem, Js::PropertyOperation_ThrowIfNotExtensible);
  2641. }
  2642. uint64 JavascriptArray::OP_GetLength(Var obj, ScriptContext *scriptContext)
  2643. {
  2644. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  2645. {
  2646. // Casting to uint64 is okay as ToLength will always be >= 0.
  2647. return (uint64)JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
  2648. }
  2649. else
  2650. {
  2651. return (uint64)JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
  2652. }
  2653. }
  2654. template<typename T>
  2655. void JavascriptArray::TryGetArrayAndLength(Var arg,
  2656. ScriptContext *scriptContext,
  2657. PCWSTR methodName,
  2658. __out JavascriptArray** array,
  2659. __out RecyclableObject** obj,
  2660. __out T * length)
  2661. {
  2662. Assert(array != nullptr);
  2663. Assert(obj != nullptr);
  2664. Assert(length != nullptr);
  2665. if (JavascriptArray::Is(arg) && !JavascriptArray::FromVar(arg)->IsCrossSiteObject())
  2666. {
  2667. #if ENABLE_COPYONACCESS_ARRAY
  2668. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(arg);
  2669. #endif
  2670. *array = JavascriptArray::FromVar(arg);
  2671. *obj = *array;
  2672. *length = (*array)->length;
  2673. }
  2674. else
  2675. {
  2676. if (!JavascriptConversion::ToObject(arg, scriptContext, obj))
  2677. {
  2678. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, methodName);
  2679. }
  2680. *length = OP_GetLength(*obj, scriptContext);
  2681. *array = nullptr;
  2682. }
  2683. }
  2684. BOOL JavascriptArray::SetArrayLikeObjects(RecyclableObject* pDestObj, BigIndex idxDest, Var aItem)
  2685. {
  2686. ScriptContext* scriptContext = pDestObj->GetScriptContext();
  2687. if (idxDest.IsSmallIndex())
  2688. {
  2689. return pDestObj->SetItem(idxDest.GetSmallIndex(), aItem, Js::PropertyOperation_ThrowIfNotExtensible);
  2690. }
  2691. PropertyRecord const * propertyRecord;
  2692. JavascriptOperators::GetPropertyIdForInt(idxDest.GetBigIndex(), scriptContext, &propertyRecord);
  2693. return pDestObj->SetProperty(propertyRecord->GetPropertyId(), aItem, PropertyOperation_ThrowIfNotExtensible, nullptr);
  2694. }
  2695. template<typename T>
  2696. void JavascriptArray::ConcatArgs(RecyclableObject* pDestObj, TypeId* remoteTypeIds,
  2697. Js::Arguments& args, ScriptContext* scriptContext, uint start, BigIndex startIdxDest,
  2698. BOOL FirstPromotedItemIsSpreadable, BigIndex FirstPromotedItemLength, bool spreadableCheckedAndTrue)
  2699. {
  2700. // This never gets called.
  2701. Throw::InternalError();
  2702. }
  2703. //
  2704. // Helper for EntryConcat. Concat args or elements of arg arrays into dest array.
  2705. //
  2706. template<typename T>
  2707. void JavascriptArray::ConcatArgs(RecyclableObject* pDestObj, TypeId* remoteTypeIds,
  2708. Js::Arguments& args, ScriptContext* scriptContext, uint start, uint startIdxDest,
  2709. BOOL firstPromotedItemIsSpreadable, BigIndex firstPromotedItemLength, bool spreadableCheckedAndTrue)
  2710. {
  2711. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  2712. JavascriptArray* pDestArray = nullptr;
  2713. if (JavascriptArray::Is(pDestObj))
  2714. {
  2715. pDestArray = JavascriptArray::FromVar(pDestObj);
  2716. }
  2717. T idxDest = startIdxDest;
  2718. for (uint idxArg = start; idxArg < args.Info.Count; idxArg++)
  2719. {
  2720. Var aItem = args[idxArg];
  2721. bool spreadable = spreadableCheckedAndTrue;
  2722. if (!spreadable && scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled())
  2723. {
  2724. // firstPromotedItemIsSpreadable is ONLY used to resume after a type promotion from uint32 to uint64
  2725. // we do this because calls to IsConcatSpreadable are observable (a big deal for proxies) and we don't
  2726. // want to do the work a second time as soon as we record the length we clear the flag.
  2727. JS_REENTRANT(jsReentLock, spreadable = firstPromotedItemIsSpreadable || JavascriptOperators::IsConcatSpreadable(aItem));
  2728. if (!spreadable)
  2729. {
  2730. JS_REENTRANT(jsReentLock, JavascriptArray::SetConcatItem<T>(aItem, idxArg, pDestArray, pDestObj, idxDest, scriptContext));
  2731. ++idxDest;
  2732. continue;
  2733. }
  2734. }
  2735. else
  2736. {
  2737. spreadableCheckedAndTrue = false; // if it was `true`, reset after the first use
  2738. }
  2739. if (pDestArray && JavascriptArray::IsDirectAccessArray(aItem) && JavascriptArray::IsDirectAccessArray(pDestArray)
  2740. && BigIndex(idxDest + JavascriptArray::FromVar(aItem)->length).IsSmallIndex() && !JavascriptArray::FromVar(aItem)->IsFillFromPrototypes()) // Fast path
  2741. {
  2742. if (JavascriptNativeIntArray::Is(aItem))
  2743. {
  2744. JavascriptNativeIntArray *pItemArray = JavascriptNativeIntArray::FromVar(aItem);
  2745. JS_REENTRANT(jsReentLock, CopyNativeIntArrayElementsToVar(pDestArray, idxDest, pItemArray));
  2746. idxDest = idxDest + pItemArray->length;
  2747. }
  2748. else if (JavascriptNativeFloatArray::Is(aItem))
  2749. {
  2750. JavascriptNativeFloatArray *pItemArray = JavascriptNativeFloatArray::FromVar(aItem);
  2751. JS_REENTRANT(jsReentLock, CopyNativeFloatArrayElementsToVar(pDestArray, idxDest, pItemArray));
  2752. idxDest = idxDest + pItemArray->length;
  2753. }
  2754. else
  2755. {
  2756. JavascriptArray* pItemArray = JavascriptArray::FromVar(aItem);
  2757. JS_REENTRANT(jsReentLock, CopyArrayElements(pDestArray, idxDest, pItemArray));
  2758. idxDest = idxDest + pItemArray->length;
  2759. }
  2760. }
  2761. else
  2762. {
  2763. // Flatten if other array or remote array (marked with TypeIds_Array)
  2764. if (DynamicObject::IsAnyArray(aItem) || remoteTypeIds[idxArg] == TypeIds_Array || spreadable)
  2765. {
  2766. //CONSIDER: enumerating remote array instead of walking all indices
  2767. BigIndex length;
  2768. if (firstPromotedItemIsSpreadable)
  2769. {
  2770. firstPromotedItemIsSpreadable = false;
  2771. length = firstPromotedItemLength;
  2772. }
  2773. else
  2774. {
  2775. JS_REENTRANT(jsReentLock, length = OP_GetLength(aItem, scriptContext));
  2776. }
  2777. if (PromoteToBigIndex(length,idxDest))
  2778. {
  2779. // This is a special case for spreadable objects. We do not pre-calculate the length
  2780. // in EntryConcat like we do with Arrays because a getProperty on an object Length
  2781. // is observable. The result is we have to check for overflows separately for
  2782. // spreadable objects and promote to a bigger index type when we find them.
  2783. ConcatArgs<BigIndex>(pDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest, /*firstPromotedItemIsSpreadable*/true, length);
  2784. return;
  2785. }
  2786. if (length + idxDest > FiftyThirdPowerOfTwoMinusOne) // 2^53-1: from ECMA 22.1.3.1 Array.prototype.concat(...arguments)
  2787. {
  2788. JavascriptError::ThrowTypeError(scriptContext, JSERR_IllegalArraySizeAndLength);
  2789. }
  2790. RecyclableObject* itemObject = RecyclableObject::FromVar(aItem);
  2791. Var subItem;
  2792. uint32 lengthToUin32Max = length.IsSmallIndex() ? length.GetSmallIndex() : MaxArrayLength;
  2793. for (uint32 idxSubItem = 0u; idxSubItem < lengthToUin32Max; ++idxSubItem)
  2794. {
  2795. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(itemObject, idxSubItem));
  2796. if (hasItem)
  2797. {
  2798. JS_REENTRANT(jsReentLock, subItem = JavascriptOperators::GetItem(itemObject, idxSubItem, scriptContext));
  2799. if (pDestArray)
  2800. {
  2801. pDestArray->DirectSetItemAt(idxDest, subItem);
  2802. }
  2803. else
  2804. {
  2805. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(SetArrayLikeObjects(pDestObj, idxDest, subItem), scriptContext, idxDest));
  2806. }
  2807. }
  2808. ++idxDest;
  2809. }
  2810. for (BigIndex idxSubItem = MaxArrayLength; idxSubItem < length; ++idxSubItem)
  2811. {
  2812. PropertyRecord const * propertyRecord;
  2813. JavascriptOperators::GetPropertyIdForInt(idxSubItem.GetBigIndex(), scriptContext, &propertyRecord);
  2814. JS_REENTRANT(jsReentLock, BOOL hasProp = JavascriptOperators::HasProperty(itemObject, propertyRecord->GetPropertyId()));
  2815. if (hasProp)
  2816. {
  2817. JS_REENTRANT(jsReentLock, subItem = JavascriptOperators::GetProperty(itemObject, propertyRecord->GetPropertyId(), scriptContext));
  2818. if (pDestArray)
  2819. {
  2820. pDestArray->DirectSetItemAt(idxDest, subItem);
  2821. }
  2822. else
  2823. {
  2824. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(SetArrayLikeObjects(pDestObj, idxDest, subItem), scriptContext, idxSubItem));
  2825. }
  2826. }
  2827. ++idxDest;
  2828. }
  2829. }
  2830. else // concat 1 item
  2831. {
  2832. JS_REENTRANT(jsReentLock, JavascriptArray::SetConcatItem<T>(aItem, idxArg, pDestArray, pDestObj, idxDest, scriptContext));
  2833. ++idxDest;
  2834. }
  2835. }
  2836. }
  2837. if (!pDestArray)
  2838. {
  2839. JS_REENTRANT(jsReentLock, pDestObj->SetProperty(PropertyIds::length, ConvertToIndex<T, Var>(idxDest, scriptContext), Js::PropertyOperation_None, nullptr));
  2840. }
  2841. else if (pDestArray->GetLength() != ConvertToIndex<T, uint32>(idxDest, scriptContext))
  2842. {
  2843. pDestArray->SetLength(ConvertToIndex<T, uint32>(idxDest, scriptContext));
  2844. }
  2845. }
  2846. bool JavascriptArray::PromoteToBigIndex(BigIndex lhs, BigIndex rhs)
  2847. {
  2848. return false; // already a big index
  2849. }
  2850. bool JavascriptArray::PromoteToBigIndex(BigIndex lhs, uint32 rhs)
  2851. {
  2852. ::Math::RecordOverflowPolicy destLengthOverflow;
  2853. if (lhs.IsSmallIndex())
  2854. {
  2855. UInt32Math::Add(lhs.GetSmallIndex(), rhs, destLengthOverflow);
  2856. return destLengthOverflow.HasOverflowed();
  2857. }
  2858. return true;
  2859. }
  2860. JavascriptArray* JavascriptArray::ConcatIntArgs(JavascriptNativeIntArray* pDestArray, TypeId *remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext)
  2861. {
  2862. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  2863. uint idxDest = 0u;
  2864. for (uint idxArg = 0; idxArg < args.Info.Count; idxArg++)
  2865. {
  2866. Var aItem = args[idxArg];
  2867. bool spreadableCheckedAndTrue = false;
  2868. if (scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled())
  2869. {
  2870. JS_REENTRANT(jsReentLock, spreadableCheckedAndTrue = !scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled() || JavascriptOperators::IsConcatSpreadable(aItem));
  2871. if (!JavascriptNativeIntArray::Is(pDestArray))
  2872. {
  2873. ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest, spreadableCheckedAndTrue);
  2874. return pDestArray;
  2875. }
  2876. if(!spreadableCheckedAndTrue)
  2877. {
  2878. JS_REENTRANT(jsReentLock, pDestArray->SetItem(idxDest, aItem, PropertyOperation_ThrowIfNotExtensible));
  2879. idxDest = idxDest + 1;
  2880. if (!JavascriptNativeIntArray::Is(pDestArray)) // SetItem could convert pDestArray to a var array if aItem is not an integer if so fall back
  2881. {
  2882. JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest));
  2883. return pDestArray;
  2884. }
  2885. continue;
  2886. }
  2887. }
  2888. if (JavascriptNativeIntArray::Is(aItem) && !JavascriptNativeIntArray::FromVar(aItem)->IsFillFromPrototypes()) // Fast path
  2889. {
  2890. JavascriptNativeIntArray* pItemArray = JavascriptNativeIntArray::FromVar(aItem);
  2891. JS_REENTRANT(jsReentLock, bool converted = CopyNativeIntArrayElements(pDestArray, idxDest, pItemArray));
  2892. idxDest = idxDest + pItemArray->length;
  2893. if (converted)
  2894. {
  2895. // Copying the last array forced a conversion, so switch over to the var version
  2896. // to finish.
  2897. JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest));
  2898. return pDestArray;
  2899. }
  2900. }
  2901. else if (!JavascriptArray::IsAnyArray(aItem) && remoteTypeIds[idxArg] != TypeIds_Array)
  2902. {
  2903. if (TaggedInt::Is(aItem))
  2904. {
  2905. pDestArray->DirectSetItemAt(idxDest, TaggedInt::ToInt32(aItem));
  2906. }
  2907. else
  2908. {
  2909. #if DBG
  2910. int32 int32Value;
  2911. Assert(
  2912. JavascriptNumber::TryGetInt32Value(JavascriptNumber::GetValue(aItem), &int32Value) &&
  2913. !SparseArraySegment<int32>::IsMissingItem(&int32Value));
  2914. #endif
  2915. pDestArray->DirectSetItemAt(idxDest, static_cast<int32>(JavascriptNumber::GetValue(aItem)));
  2916. }
  2917. ++idxDest;
  2918. }
  2919. else
  2920. {
  2921. JavascriptArray *pVarDestArray = JavascriptNativeIntArray::ConvertToVarArray(pDestArray);
  2922. BigIndex length;
  2923. JS_REENTRANT(jsReentLock, length = OP_GetLength(aItem, scriptContext),
  2924. ConcatArgs<uint>(pVarDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest, spreadableCheckedAndTrue, length));
  2925. return pVarDestArray;
  2926. }
  2927. }
  2928. if (pDestArray->GetLength() != idxDest)
  2929. {
  2930. pDestArray->SetLength(idxDest);
  2931. }
  2932. return pDestArray;
  2933. }
  2934. JavascriptArray* JavascriptArray::ConcatFloatArgs(JavascriptNativeFloatArray* pDestArray, TypeId *remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext)
  2935. {
  2936. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  2937. uint idxDest = 0u;
  2938. for (uint idxArg = 0; idxArg < args.Info.Count; idxArg++)
  2939. {
  2940. Var aItem = args[idxArg];
  2941. bool spreadableCheckedAndTrue = false;
  2942. if (scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled())
  2943. {
  2944. JS_REENTRANT(jsReentLock, spreadableCheckedAndTrue = !scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled() || JavascriptOperators::IsConcatSpreadable(aItem));
  2945. if (!JavascriptNativeFloatArray::Is(pDestArray))
  2946. {
  2947. ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest, spreadableCheckedAndTrue);
  2948. return pDestArray;
  2949. }
  2950. if (!spreadableCheckedAndTrue)
  2951. {
  2952. JS_REENTRANT(jsReentLock, pDestArray->SetItem(idxDest, aItem, PropertyOperation_ThrowIfNotExtensible));
  2953. idxDest = idxDest + 1;
  2954. if (!JavascriptNativeFloatArray::Is(pDestArray)) // SetItem could convert pDestArray to a var array if aItem is not an integer if so fall back
  2955. {
  2956. JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest));
  2957. return pDestArray;
  2958. }
  2959. continue;
  2960. }
  2961. }
  2962. bool converted = false;
  2963. if (JavascriptArray::IsAnyArray(aItem) || remoteTypeIds[idxArg] == TypeIds_Array)
  2964. {
  2965. if (JavascriptNativeIntArray::Is(aItem) && !JavascriptArray::FromVar(aItem)->IsFillFromPrototypes()) // Fast path
  2966. {
  2967. JavascriptNativeIntArray *pIntArray = JavascriptNativeIntArray::FromVar(aItem);
  2968. JS_REENTRANT(jsReentLock, converted = CopyNativeIntArrayElementsToFloat(pDestArray, idxDest, pIntArray));
  2969. idxDest = idxDest + pIntArray->length;
  2970. }
  2971. else if (JavascriptNativeFloatArray::Is(aItem) && !JavascriptArray::FromVar(aItem)->IsFillFromPrototypes())
  2972. {
  2973. JavascriptNativeFloatArray* pItemArray = JavascriptNativeFloatArray::FromVar(aItem);
  2974. JS_REENTRANT(jsReentLock, converted = CopyNativeFloatArrayElements(pDestArray, idxDest, pItemArray));
  2975. idxDest = idxDest + pItemArray->length;
  2976. }
  2977. else
  2978. {
  2979. JavascriptArray *pVarDestArray = JavascriptNativeFloatArray::ConvertToVarArray(pDestArray);
  2980. BigIndex length;
  2981. JS_REENTRANT(jsReentLock, length = OP_GetLength(aItem, scriptContext),
  2982. ConcatArgs<uint>(pVarDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest, spreadableCheckedAndTrue, length));
  2983. return pVarDestArray;
  2984. }
  2985. if (converted)
  2986. {
  2987. // Copying the last array forced a conversion, so switch over to the var version
  2988. // to finish.
  2989. JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest));
  2990. return pDestArray;
  2991. }
  2992. }
  2993. else
  2994. {
  2995. if (TaggedInt::Is(aItem))
  2996. {
  2997. pDestArray->DirectSetItemAt(idxDest, (double)TaggedInt::ToInt32(aItem));
  2998. }
  2999. else
  3000. {
  3001. Assert(JavascriptNumber::Is(aItem));
  3002. pDestArray->DirectSetItemAt(idxDest, JavascriptNumber::GetValue(aItem));
  3003. }
  3004. ++idxDest;
  3005. }
  3006. }
  3007. if (pDestArray->GetLength() != idxDest)
  3008. {
  3009. pDestArray->SetLength(idxDest);
  3010. }
  3011. return pDestArray;
  3012. }
  3013. bool JavascriptArray::BoxConcatItem(Var aItem, uint idxArg, ScriptContext *scriptContext)
  3014. {
  3015. return idxArg == 0 && !JavascriptOperators::IsObject(aItem);
  3016. }
  3017. Var JavascriptArray::EntryConcat(RecyclableObject* function, CallInfo callInfo, ...)
  3018. {
  3019. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  3020. ARGUMENTS(args, callInfo);
  3021. ScriptContext* scriptContext = function->GetScriptContext();
  3022. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3023. Assert(!(callInfo.Flags & CallFlags_New));
  3024. if (args.Info.Count == 0)
  3025. {
  3026. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.concat"));
  3027. }
  3028. //
  3029. // Compute the destination ScriptArray size:
  3030. // - Each item, flattening only one level if a ScriptArray.
  3031. //
  3032. uint32 cDestLength = 0;
  3033. JavascriptArray * pDestArray = NULL;
  3034. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault + (args.Info.Count * sizeof(TypeId*)));
  3035. TypeId* remoteTypeIds = (TypeId*)_alloca(args.Info.Count * sizeof(TypeId*));
  3036. bool isInt = true;
  3037. bool isFloat = true;
  3038. ::Math::RecordOverflowPolicy destLengthOverflow;
  3039. for (uint idxArg = 0; idxArg < args.Info.Count; idxArg++)
  3040. {
  3041. Var aItem = args[idxArg];
  3042. #if ENABLE_COPYONACCESS_ARRAY
  3043. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(aItem);
  3044. #endif
  3045. if (DynamicObject::IsAnyArray(aItem)) // Get JavascriptArray or ES5Array length
  3046. {
  3047. JavascriptArray * pItemArray = JavascriptArray::FromAnyArray(aItem);
  3048. if (isFloat)
  3049. {
  3050. if (!JavascriptNativeIntArray::Is(pItemArray))
  3051. {
  3052. isInt = false;
  3053. if (!JavascriptNativeFloatArray::Is(pItemArray))
  3054. {
  3055. isFloat = false;
  3056. }
  3057. }
  3058. }
  3059. cDestLength = UInt32Math::Add(cDestLength, pItemArray->GetLength(), destLengthOverflow);
  3060. }
  3061. else // Get remote array or object length
  3062. {
  3063. // We already checked for types derived from JavascriptArray. These are types that should behave like array
  3064. // i.e. proxy to array and remote array.
  3065. if (JavascriptOperators::IsArray(aItem))
  3066. {
  3067. // Don't try to preserve nativeness of remote arrays. The extra complexity is probably not
  3068. // worth it.
  3069. isInt = false;
  3070. isFloat = false;
  3071. if (!JavascriptProxy::Is(aItem))
  3072. {
  3073. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  3074. {
  3075. JS_REENTRANT(jsReentLock,
  3076. int64 len = JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(aItem, scriptContext), scriptContext));
  3077. // clipping to MaxArrayLength will overflow when added to cDestLength which we catch below
  3078. cDestLength = UInt32Math::Add(cDestLength, len < MaxArrayLength ? (uint32)len : MaxArrayLength, destLengthOverflow);
  3079. }
  3080. else
  3081. {
  3082. JS_REENTRANT(jsReentLock,
  3083. uint len = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(aItem, scriptContext), scriptContext));
  3084. cDestLength = UInt32Math::Add(cDestLength, len, destLengthOverflow);
  3085. }
  3086. }
  3087. remoteTypeIds[idxArg] = TypeIds_Array; // Mark remote array, no matter remote JavascriptArray or ES5Array.
  3088. }
  3089. else
  3090. {
  3091. if (isFloat)
  3092. {
  3093. if (BoxConcatItem(aItem, idxArg, scriptContext))
  3094. {
  3095. // A primitive will be boxed, so we have to create a var array for the result.
  3096. isInt = false;
  3097. isFloat = false;
  3098. }
  3099. else if (!TaggedInt::Is(aItem))
  3100. {
  3101. if (!JavascriptNumber::Is(aItem))
  3102. {
  3103. isInt = false;
  3104. isFloat = false;
  3105. }
  3106. else if (isInt)
  3107. {
  3108. int32 int32Value;
  3109. if(!JavascriptNumber::TryGetInt32Value(JavascriptNumber::GetValue(aItem), &int32Value) ||
  3110. SparseArraySegment<int32>::IsMissingItem(&int32Value))
  3111. {
  3112. isInt = false;
  3113. }
  3114. }
  3115. }
  3116. else if(isInt)
  3117. {
  3118. int32 int32Value = TaggedInt::ToInt32(aItem);
  3119. if(SparseArraySegment<int32>::IsMissingItem(&int32Value))
  3120. {
  3121. isInt = false;
  3122. }
  3123. }
  3124. }
  3125. remoteTypeIds[idxArg] = TypeIds_Limit;
  3126. cDestLength = UInt32Math::Add(cDestLength, 1, destLengthOverflow);
  3127. }
  3128. }
  3129. }
  3130. if (destLengthOverflow.HasOverflowed())
  3131. {
  3132. cDestLength = MaxArrayLength;
  3133. isInt = false;
  3134. isFloat = false;
  3135. }
  3136. //
  3137. // Create the destination array
  3138. //
  3139. RecyclableObject* pDestObj = nullptr;
  3140. bool isArray = false;
  3141. JS_REENTRANT(jsReentLock, pDestObj = ArraySpeciesCreate(args[0], 0, scriptContext));
  3142. if (pDestObj)
  3143. {
  3144. #if ENABLE_COPYONACCESS_ARRAY
  3145. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pDestObj);
  3146. #endif
  3147. // Check the thing that species create made. If it's a native array that can't handle the source
  3148. // data, convert it. If it's a more conservative kind of array than the source data, indicate that
  3149. // so that the data will be converted on copy.
  3150. if (isInt)
  3151. {
  3152. if (JavascriptNativeIntArray::Is(pDestObj))
  3153. {
  3154. isArray = true;
  3155. }
  3156. else
  3157. {
  3158. isInt = false;
  3159. isFloat = JavascriptNativeFloatArray::Is(pDestObj);
  3160. isArray = JavascriptArray::Is(pDestObj);
  3161. }
  3162. }
  3163. else if (isFloat)
  3164. {
  3165. if (JavascriptNativeIntArray::Is(pDestObj))
  3166. {
  3167. JavascriptNativeIntArray::ToNativeFloatArray(JavascriptNativeIntArray::FromVar(pDestObj));
  3168. isArray = true;
  3169. }
  3170. else
  3171. {
  3172. isFloat = JavascriptNativeFloatArray::Is(pDestObj);
  3173. isArray = JavascriptArray::Is(pDestObj);
  3174. }
  3175. }
  3176. else
  3177. {
  3178. if (JavascriptNativeIntArray::Is(pDestObj))
  3179. {
  3180. JavascriptNativeIntArray::ToVarArray(JavascriptNativeIntArray::FromVar(pDestObj));
  3181. isArray = true;
  3182. }
  3183. else if (JavascriptNativeFloatArray::Is(pDestObj))
  3184. {
  3185. JavascriptNativeFloatArray::ToVarArray(JavascriptNativeFloatArray::FromVar(pDestObj));
  3186. isArray = true;
  3187. }
  3188. else
  3189. {
  3190. isArray = JavascriptArray::Is(pDestObj);
  3191. }
  3192. }
  3193. }
  3194. if (pDestObj == nullptr || isArray)
  3195. {
  3196. if (isInt)
  3197. {
  3198. JavascriptNativeIntArray *pIntArray = isArray ? JavascriptNativeIntArray::FromVar(pDestObj) : scriptContext->GetLibrary()->CreateNativeIntArray(cDestLength);
  3199. pIntArray->EnsureHead<int32>();
  3200. JS_REENTRANT(jsReentLock, pDestArray = ConcatIntArgs(pIntArray, remoteTypeIds, args, scriptContext));
  3201. }
  3202. else if (isFloat)
  3203. {
  3204. JavascriptNativeFloatArray *pFArray = isArray ? JavascriptNativeFloatArray::FromVar(pDestObj) : scriptContext->GetLibrary()->CreateNativeFloatArray(cDestLength);
  3205. pFArray->EnsureHead<double>();
  3206. JS_REENTRANT(jsReentLock, pDestArray = ConcatFloatArgs(pFArray, remoteTypeIds, args, scriptContext));
  3207. }
  3208. else
  3209. {
  3210. pDestArray = isArray ? JavascriptArray::FromVar(pDestObj) : scriptContext->GetLibrary()->CreateArray(cDestLength);
  3211. // if the constructor has changed then we no longer specialize for ints and floats
  3212. pDestArray->EnsureHead<Var>();
  3213. JS_REENTRANT(jsReentLock, ConcatArgsCallingHelper(pDestArray, remoteTypeIds, args, scriptContext, destLengthOverflow));
  3214. }
  3215. //
  3216. // Return the new array instance.
  3217. //
  3218. #ifdef VALIDATE_ARRAY
  3219. pDestArray->ValidateArray();
  3220. #endif
  3221. return pDestArray;
  3222. }
  3223. Assert(pDestObj);
  3224. JS_REENTRANT(jsReentLock, ConcatArgsCallingHelper(pDestObj, remoteTypeIds, args, scriptContext, destLengthOverflow));
  3225. return pDestObj;
  3226. }
  3227. void JavascriptArray::ConcatArgsCallingHelper(RecyclableObject* pDestObj, TypeId* remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext, ::Math::RecordOverflowPolicy &destLengthOverflow)
  3228. {
  3229. if (destLengthOverflow.HasOverflowed())
  3230. {
  3231. ConcatArgs<BigIndex>(pDestObj, remoteTypeIds, args, scriptContext);
  3232. }
  3233. else
  3234. {
  3235. // Use faster uint32 version if no overflow
  3236. ConcatArgs<uint32>(pDestObj, remoteTypeIds, args, scriptContext);
  3237. }
  3238. }
  3239. template<typename T>
  3240. /* static */ void JavascriptArray::SetConcatItem(Var aItem, uint idxArg, JavascriptArray* pDestArray, RecyclableObject* pDestObj, T idxDest, ScriptContext *scriptContext)
  3241. {
  3242. if (BoxConcatItem(aItem, idxArg, scriptContext))
  3243. {
  3244. // bug# 725784: ES5: not calling ToObject in Step 1 of 15.4.4.4
  3245. RecyclableObject* pObj = nullptr;
  3246. if (FALSE == JavascriptConversion::ToObject(aItem, scriptContext, &pObj))
  3247. {
  3248. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.concat"));
  3249. }
  3250. if (pDestArray)
  3251. {
  3252. pDestArray->DirectSetItemAt(idxDest, pObj);
  3253. }
  3254. else
  3255. {
  3256. SetArrayLikeObjects(pDestObj, idxDest, pObj);
  3257. }
  3258. }
  3259. else
  3260. {
  3261. if (pDestArray)
  3262. {
  3263. pDestArray->DirectSetItemAt(idxDest, aItem);
  3264. }
  3265. else
  3266. {
  3267. SetArrayLikeObjects(pDestObj, idxDest, aItem);
  3268. }
  3269. }
  3270. }
  3271. int64 JavascriptArray::GetFromLastIndex(Var arg, int64 length, ScriptContext *scriptContext)
  3272. {
  3273. int64 fromIndex;
  3274. if (TaggedInt::Is(arg))
  3275. {
  3276. int intValue = TaggedInt::ToInt32(arg);
  3277. if (intValue >= 0)
  3278. {
  3279. fromIndex = min<int64>(intValue, length - 1);
  3280. }
  3281. else if ((uint32)-intValue > length)
  3282. {
  3283. return length;
  3284. }
  3285. else
  3286. {
  3287. fromIndex = intValue + length;
  3288. }
  3289. }
  3290. else
  3291. {
  3292. double value = JavascriptConversion::ToInteger(arg, scriptContext);
  3293. if (value >= 0)
  3294. {
  3295. fromIndex = (int64)min(value, (double)(length - 1));
  3296. }
  3297. else if (value + length < 0)
  3298. {
  3299. return length;
  3300. }
  3301. else
  3302. {
  3303. fromIndex = (int64)(value + length);
  3304. }
  3305. }
  3306. return fromIndex;
  3307. }
  3308. // includesAlgorithm specifies to follow ES7 Array.prototype.includes semantics instead of Array.prototype.indexOf
  3309. // Differences
  3310. // 1. Returns boolean true or false value instead of the search hit index
  3311. // 2. Follows SameValueZero algorithm instead of StrictEquals
  3312. // 3. Missing values are scanned if the search value is undefined
  3313. template <bool includesAlgorithm>
  3314. Var JavascriptArray::IndexOfHelper(Arguments const & args, ScriptContext *scriptContext)
  3315. {
  3316. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3317. RecyclableObject* obj = nullptr;
  3318. JavascriptArray* pArr = nullptr;
  3319. BigIndex length;
  3320. Var trueValue = scriptContext->GetLibrary()->GetTrue();
  3321. Var falseValue = scriptContext->GetLibrary()->GetFalse();
  3322. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.indexOf"), &pArr, &obj, &length));
  3323. Var search;
  3324. uint32 fromIndex = 0;
  3325. uint64 fromIndex64 = 0;
  3326. // The evaluation of method arguments may change the type of the array. Hence, we do that prior to the actual helper method calls.
  3327. // The if clause of the conditional statement below applies to an JavascriptArray or TypedArray instances. The rest of the conditional
  3328. // clauses apply to an ES5Array or other valid Javascript objects.
  3329. if ((pArr || TypedArrayBase::Is(obj)) && (length.IsSmallIndex() || length.IsUint32Max()))
  3330. {
  3331. uint32 len = length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex();
  3332. JS_REENTRANT(jsReentLock, BOOL gotParam = GetParamForIndexOf(len, args, search, fromIndex, scriptContext));
  3333. if (!gotParam)
  3334. {
  3335. return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
  3336. }
  3337. }
  3338. else if (length.IsSmallIndex())
  3339. {
  3340. JS_REENTRANT(jsReentLock, BOOL gotParam = GetParamForIndexOf(length.GetSmallIndex(), args, search, fromIndex, scriptContext));
  3341. if (!gotParam)
  3342. {
  3343. return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
  3344. }
  3345. }
  3346. else
  3347. {
  3348. JS_REENTRANT(jsReentLock, BOOL gotParam = GetParamForIndexOf(length.GetBigIndex(), args, search, fromIndex64, scriptContext));
  3349. if (!gotParam)
  3350. {
  3351. return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
  3352. }
  3353. }
  3354. // Side effects (such as defining a property in a ToPrimitive call) during evaluation of fromIndex argument may convert the array to an ES5 array.
  3355. if (pArr && !JavascriptArray::Is(obj))
  3356. {
  3357. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  3358. pArr = nullptr;
  3359. }
  3360. if (pArr)
  3361. {
  3362. if (length.IsSmallIndex() || length.IsUint32Max())
  3363. {
  3364. uint32 len = length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex();
  3365. int32 index = pArr->HeadSegmentIndexOfHelper(search, fromIndex, len, includesAlgorithm, scriptContext);
  3366. // If we found the search value in the head segment, or if we determined there is no need to search other segments,
  3367. // we stop right here.
  3368. if (index != -1 || fromIndex == -1)
  3369. {
  3370. if (includesAlgorithm)
  3371. {
  3372. //Array.prototype.includes
  3373. return (index == -1) ? falseValue : trueValue;
  3374. }
  3375. else
  3376. {
  3377. //Array.prototype.indexOf
  3378. return JavascriptNumber::ToVar(index, scriptContext);
  3379. }
  3380. }
  3381. // If we really must search other segments, let's do it now. We'll have to search the slow way (dealing with holes, etc.).
  3382. switch (pArr->GetTypeId())
  3383. {
  3384. case Js::TypeIds_Array:
  3385. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(pArr, search, fromIndex, len, scriptContext));
  3386. case Js::TypeIds_NativeIntArray:
  3387. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(JavascriptNativeIntArray::FromVar(pArr), search, fromIndex, len, scriptContext));
  3388. case Js::TypeIds_NativeFloatArray:
  3389. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(JavascriptNativeFloatArray::FromVar(pArr), search, fromIndex, len, scriptContext));
  3390. default:
  3391. AssertMsg(FALSE, "invalid array typeid");
  3392. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(pArr, search, fromIndex, len, scriptContext));
  3393. }
  3394. }
  3395. }
  3396. // source object is not a JavascriptArray but source could be a TypedArray
  3397. if (TypedArrayBase::Is(obj))
  3398. {
  3399. if (length.IsSmallIndex() || length.IsUint32Max())
  3400. {
  3401. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(TypedArrayBase::FromVar(obj), search, fromIndex, length.GetSmallIndex(), scriptContext));
  3402. }
  3403. }
  3404. if (length.IsSmallIndex())
  3405. {
  3406. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(obj, search, fromIndex, length.GetSmallIndex(), scriptContext));
  3407. }
  3408. else
  3409. {
  3410. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(obj, search, fromIndex64, length.GetBigIndex(), scriptContext));
  3411. }
  3412. }
  3413. // Array.prototype.indexOf as defined in ES6.0 (final) Section 22.1.3.11
  3414. Var JavascriptArray::EntryIndexOf(RecyclableObject* function, CallInfo callInfo, ...)
  3415. {
  3416. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  3417. ARGUMENTS(args, callInfo);
  3418. ScriptContext* scriptContext = function->GetScriptContext();
  3419. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3420. Assert(!(callInfo.Flags & CallFlags_New));
  3421. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_indexOf);
  3422. JS_REENTRANT_UNLOCK(jsReentLock, Var returnValue = IndexOfHelper<false>(args, scriptContext));
  3423. //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
  3424. Assert(returnValue != scriptContext->GetLibrary()->GetTrue() && returnValue != scriptContext->GetLibrary()->GetFalse());
  3425. return returnValue;
  3426. }
  3427. Var JavascriptArray::EntryIncludes(RecyclableObject* function, CallInfo callInfo, ...)
  3428. {
  3429. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  3430. ARGUMENTS(args, callInfo);
  3431. ScriptContext* scriptContext = function->GetScriptContext();
  3432. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3433. Assert(!(callInfo.Flags & CallFlags_New));
  3434. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_includes);
  3435. JS_REENTRANT(jsReentLock, Var returnValue = IndexOfHelper<true>(args, scriptContext));
  3436. Assert(returnValue == scriptContext->GetLibrary()->GetTrue() || returnValue == scriptContext->GetLibrary()->GetFalse());
  3437. return returnValue;
  3438. }
  3439. template<typename T>
  3440. BOOL JavascriptArray::GetParamForIndexOf(T length, Arguments const& args, Var& search, T& fromIndex, ScriptContext * scriptContext)
  3441. {
  3442. if (length == 0)
  3443. {
  3444. return false;
  3445. }
  3446. if (args.Info.Count > 2)
  3447. {
  3448. fromIndex = GetFromIndex(args[2], length, scriptContext);
  3449. if (fromIndex >= length)
  3450. {
  3451. return false;
  3452. }
  3453. search = args[1];
  3454. }
  3455. else
  3456. {
  3457. fromIndex = 0;
  3458. search = args.Info.Count > 1 ? args[1] : scriptContext->GetLibrary()->GetUndefined();
  3459. }
  3460. return true;
  3461. }
  3462. template <>
  3463. BOOL JavascriptArray::TemplatedGetItem(RecyclableObject * obj, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3464. {
  3465. // Note: Sometime cross site array go down this path to get the marshalling
  3466. Assert(!VirtualTableInfo<JavascriptArray>::HasVirtualTable(obj)
  3467. && !VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(obj)
  3468. && !VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(obj));
  3469. if (checkHasItem && !JavascriptOperators::HasItem(obj, index))
  3470. {
  3471. return FALSE;
  3472. }
  3473. return JavascriptOperators::GetItem(obj, index, element, scriptContext);
  3474. }
  3475. template <>
  3476. BOOL JavascriptArray::TemplatedGetItem(RecyclableObject * obj, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3477. {
  3478. // Note: Sometime cross site array go down this path to get the marshalling
  3479. Assert(!VirtualTableInfo<JavascriptArray>::HasVirtualTable(obj)
  3480. && !VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(obj)
  3481. && !VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(obj));
  3482. PropertyRecord const * propertyRecord;
  3483. JavascriptOperators::GetPropertyIdForInt(index, scriptContext, &propertyRecord);
  3484. if (checkHasItem && !JavascriptOperators::HasProperty(obj, propertyRecord->GetPropertyId()))
  3485. {
  3486. return FALSE;
  3487. }
  3488. *element = JavascriptOperators::GetProperty(obj, propertyRecord->GetPropertyId(), scriptContext);
  3489. return *element != scriptContext->GetLibrary()->GetUndefined();
  3490. }
  3491. template <>
  3492. BOOL JavascriptArray::TemplatedGetItem(JavascriptArray *pArr, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3493. {
  3494. Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(pArr)
  3495. || VirtualTableInfo<CrossSiteObject<JavascriptArray>>::HasVirtualTable(pArr));
  3496. return pArr->JavascriptArray::DirectGetItemAtFull(index, element);
  3497. }
  3498. template <>
  3499. BOOL JavascriptArray::TemplatedGetItem(JavascriptArray *pArr, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3500. {
  3501. // This should never get called.
  3502. Assert(false);
  3503. Throw::InternalError();
  3504. }
  3505. template <>
  3506. BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeIntArray *pArr, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3507. {
  3508. Assert(VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(pArr)
  3509. || VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::HasVirtualTable(pArr));
  3510. return pArr->JavascriptNativeIntArray::DirectGetItemAtFull(index, element);
  3511. }
  3512. template <>
  3513. BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeIntArray *pArr, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3514. {
  3515. // This should never get called.
  3516. Assert(false);
  3517. Throw::InternalError();
  3518. }
  3519. template <>
  3520. BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeFloatArray *pArr, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3521. {
  3522. Assert(VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(pArr)
  3523. || VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::HasVirtualTable(pArr));
  3524. return pArr->JavascriptNativeFloatArray::DirectGetItemAtFull(index, element);
  3525. }
  3526. template <>
  3527. BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeFloatArray *pArr, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3528. {
  3529. // This should never get called.
  3530. Assert(false);
  3531. Throw::InternalError();
  3532. }
  3533. template <>
  3534. BOOL JavascriptArray::TemplatedGetItem(TypedArrayBase * typedArrayBase, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3535. {
  3536. // We need to do explicit check for items since length value may not actually match the actual TypedArray length.
  3537. // User could add a length property to a TypedArray instance which lies and returns a different value from the underlying length.
  3538. // Since this method can be called via Array.prototype.indexOf with .apply or .call passing a TypedArray as this parameter
  3539. // we don't know whether or not length == typedArrayBase->GetLength().
  3540. if (checkHasItem && !typedArrayBase->HasItem(index))
  3541. {
  3542. return false;
  3543. }
  3544. *element = typedArrayBase->DirectGetItem(index);
  3545. return true;
  3546. }
  3547. template <>
  3548. BOOL JavascriptArray::TemplatedGetItem(TypedArrayBase * typedArrayBase, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3549. {
  3550. // This should never get called.
  3551. Assert(false);
  3552. Throw::InternalError();
  3553. }
  3554. template <bool includesAlgorithm, typename T, typename P>
  3555. Var JavascriptArray::TemplatedIndexOfHelper(T * pArr, Var search, P fromIndex, P toIndex, ScriptContext * scriptContext)
  3556. {
  3557. Var element = nullptr;
  3558. bool isSearchTaggedInt = TaggedInt::Is(search);
  3559. bool doUndefinedSearch = includesAlgorithm && JavascriptOperators::GetTypeId(search) == TypeIds_Undefined;
  3560. Var trueValue = scriptContext->GetLibrary()->GetTrue();
  3561. Var falseValue = scriptContext->GetLibrary()->GetFalse();
  3562. //Consider: enumerating instead of walking all indices
  3563. for (P i = fromIndex; i < toIndex; i++)
  3564. {
  3565. if (!TryTemplatedGetItem(pArr, i, &element, scriptContext, !includesAlgorithm))
  3566. {
  3567. if (doUndefinedSearch)
  3568. {
  3569. return trueValue;
  3570. }
  3571. continue;
  3572. }
  3573. if (isSearchTaggedInt && TaggedInt::Is(element))
  3574. {
  3575. if (element == search)
  3576. {
  3577. return includesAlgorithm? trueValue : JavascriptNumber::ToVar(i, scriptContext);
  3578. }
  3579. continue;
  3580. }
  3581. if (includesAlgorithm)
  3582. {
  3583. //Array.prototype.includes
  3584. if (JavascriptConversion::SameValueZero(element, search))
  3585. {
  3586. return trueValue;
  3587. }
  3588. }
  3589. else
  3590. {
  3591. //Array.prototype.indexOf
  3592. if (JavascriptOperators::StrictEqual(element, search, scriptContext))
  3593. {
  3594. return JavascriptNumber::ToVar(i, scriptContext);
  3595. }
  3596. }
  3597. }
  3598. return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
  3599. }
  3600. int32 JavascriptArray::HeadSegmentIndexOfHelper(Var search, uint32 &fromIndex, uint32 toIndex, bool includesAlgorithm, ScriptContext * scriptContext)
  3601. {
  3602. Assert(Is(GetTypeId()) && !JavascriptNativeArray::Is(GetTypeId()));
  3603. if (!HasNoMissingValues() || fromIndex >= GetHead()->length)
  3604. {
  3605. return -1;
  3606. }
  3607. bool isSearchTaggedInt = TaggedInt::Is(search);
  3608. // We need to cast head segment to SparseArraySegment<Var> to have access to GetElement (onSparseArraySegment<T>). Because there are separate overloads of this
  3609. // virtual method on JavascriptNativeIntArray and JavascriptNativeFloatArray, we know this version of this method will only be called for true JavascriptArray, and not for
  3610. // either of the derived native arrays, so the elements of each segment used here must be Vars. Hence, the cast is safe.
  3611. SparseArraySegment<Var>* head = static_cast<SparseArraySegment<Var>*>(GetHead());
  3612. uint32 toIndexTrimmed = toIndex <= head->length ? toIndex : head->length;
  3613. for (uint32 i = fromIndex; i < toIndexTrimmed; i++)
  3614. {
  3615. Var element = head->GetElement(i);
  3616. if (isSearchTaggedInt && TaggedInt::Is(element))
  3617. {
  3618. if (search == element)
  3619. {
  3620. return i;
  3621. }
  3622. }
  3623. else if (includesAlgorithm && JavascriptConversion::SameValueZero(element, search))
  3624. {
  3625. //Array.prototype.includes
  3626. return i;
  3627. }
  3628. else if (JavascriptOperators::StrictEqual(element, search, scriptContext))
  3629. {
  3630. //Array.prototype.indexOf
  3631. return i;
  3632. }
  3633. }
  3634. // Element not found in the head segment. Keep looking only if the range of indices extends past
  3635. // the head segment.
  3636. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3637. return -1;
  3638. }
  3639. template<typename T>
  3640. bool AreAllBytesEqual(T value)
  3641. {
  3642. byte* bValue = (byte*)&value;
  3643. byte firstByte = *bValue++;
  3644. for (int i = 1; i < sizeof(T); ++i)
  3645. {
  3646. if (*bValue++ != firstByte)
  3647. {
  3648. return false;
  3649. }
  3650. }
  3651. return true;
  3652. }
  3653. template<>
  3654. void JavascriptArray::CopyValueToSegmentBuferNoCheck(Field(double)* buffer, uint32 length, double value)
  3655. {
  3656. if (JavascriptNumber::IsZero(value) && !JavascriptNumber::IsNegZero(value))
  3657. {
  3658. memset(buffer, 0, sizeof(double) * length);
  3659. }
  3660. else
  3661. {
  3662. for (uint32 i = 0; i < length; i++)
  3663. {
  3664. buffer[i] = value;
  3665. }
  3666. }
  3667. }
  3668. template<>
  3669. void JavascriptArray::CopyValueToSegmentBuferNoCheck(Field(int32)* buffer, uint32 length, int32 value)
  3670. {
  3671. if (value == 0 || AreAllBytesEqual(value))
  3672. {
  3673. memset(buffer, *(byte*)&value, sizeof(int32)* length);
  3674. }
  3675. else
  3676. {
  3677. for (uint32 i = 0; i < length; i++)
  3678. {
  3679. buffer[i] = value;
  3680. }
  3681. }
  3682. }
  3683. template<>
  3684. void JavascriptArray::CopyValueToSegmentBuferNoCheck(Field(Js::Var)* buffer, uint32 length, Js::Var value)
  3685. {
  3686. for (uint32 i = 0; i < length; i++)
  3687. {
  3688. buffer[i] = value;
  3689. }
  3690. }
  3691. int32 JavascriptNativeIntArray::HeadSegmentIndexOfHelper(Var search, uint32 &fromIndex, uint32 toIndex, bool includesAlgorithm, ScriptContext * scriptContext)
  3692. {
  3693. // We proceed largely in the same manner as in JavascriptArray's version of this method (see comments there for more information),
  3694. // 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:
  3695. // 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
  3696. // the search value is some other kind of Var, we can return -1 without ever iterating over the elements.
  3697. // 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.
  3698. // Instead we can use simple C++ equality (which in case of such values is equivalent to strict equality in JavaScript).
  3699. if (!HasNoMissingValues() || fromIndex >= GetHead()->length)
  3700. {
  3701. return -1;
  3702. }
  3703. bool isSearchTaggedInt = TaggedInt::Is(search);
  3704. if (!isSearchTaggedInt && !JavascriptNumber::Is_NoTaggedIntCheck(search))
  3705. {
  3706. // The value can't be in the array, but it could be in a prototype, and we can only guarantee that
  3707. // the head segment has no gaps.
  3708. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3709. return -1;
  3710. }
  3711. int32 searchAsInt32;
  3712. if (isSearchTaggedInt)
  3713. {
  3714. searchAsInt32 = TaggedInt::ToInt32(search);
  3715. }
  3716. else if (!JavascriptNumber::TryGetInt32Value<true>(JavascriptNumber::GetValue(search), &searchAsInt32))
  3717. {
  3718. // The value can't be in the array, but it could be in a prototype, and we can only guarantee that
  3719. // the head segment has no gaps.
  3720. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3721. return -1;
  3722. }
  3723. // We need to cast head segment to SparseArraySegment<int32> to have access to GetElement (onSparseArraySegment<T>). Because there are separate overloads of this
  3724. // virtual method on JavascriptNativeIntArray and JavascriptNativeFloatArray, we know this version of this method will only be called for true JavascriptNativeIntArray, and not for
  3725. // the other two, so the elements of each segment used here must be int32's. Hence, the cast is safe.
  3726. SparseArraySegment<int32> * head = static_cast<SparseArraySegment<int32>*>(GetHead());
  3727. uint32 toIndexTrimmed = toIndex <= head->length ? toIndex : head->length;
  3728. for (uint32 i = fromIndex; i < toIndexTrimmed; i++)
  3729. {
  3730. int32 element = head->GetElement(i);
  3731. if (searchAsInt32 == element)
  3732. {
  3733. return i;
  3734. }
  3735. }
  3736. // Element not found in the head segment. Keep looking only if the range of indices extends past
  3737. // the head segment.
  3738. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3739. return -1;
  3740. }
  3741. int32 JavascriptNativeFloatArray::HeadSegmentIndexOfHelper(Var search, uint32 &fromIndex, uint32 toIndex, bool includesAlgorithm, ScriptContext * scriptContext)
  3742. {
  3743. // We proceed largely in the same manner as in JavascriptArray's version of this method (see comments there for more information),
  3744. // except when we can further optimize thanks to the knowledge that all elements in the array are doubles. This allows for two additional optimizations:
  3745. // 1. Only tagged ints or JavascriptNumbers can be strict equal to some element in the array (all doubles). Thus, if
  3746. // the search value is some other kind of Var, we can return -1 without ever iterating over the elements.
  3747. // 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.
  3748. // Instead we can use simple C++ equality (which in case of such values is equivalent to strict equality in JavaScript).
  3749. if (!HasNoMissingValues() || fromIndex >= GetHead()->length)
  3750. {
  3751. return -1;
  3752. }
  3753. bool isSearchTaggedInt = TaggedInt::Is(search);
  3754. if (!isSearchTaggedInt && !JavascriptNumber::Is_NoTaggedIntCheck(search))
  3755. {
  3756. // The value can't be in the array, but it could be in a prototype, and we can only guarantee that
  3757. // the head segment has no gaps.
  3758. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3759. return -1;
  3760. }
  3761. double searchAsDouble = isSearchTaggedInt ? TaggedInt::ToDouble(search) : JavascriptNumber::GetValue(search);
  3762. // We need to cast head segment to SparseArraySegment<double> to have access to GetElement (SparseArraySegment). We know the
  3763. // segment's elements are all Vars so the cast is safe. It would have been more convenient here if JavascriptArray
  3764. // used SparseArraySegment<Var>, instead of SparseArraySegmentBase.
  3765. SparseArraySegment<double> * head = static_cast<SparseArraySegment<double>*>(GetHead());
  3766. uint32 toIndexTrimmed = toIndex <= head->length ? toIndex : head->length;
  3767. bool matchNaN = includesAlgorithm && JavascriptNumber::IsNan(searchAsDouble);
  3768. for (uint32 i = fromIndex; i < toIndexTrimmed; i++)
  3769. {
  3770. double element = head->GetElement(i);
  3771. if (element == searchAsDouble)
  3772. {
  3773. return i;
  3774. }
  3775. //NaN != NaN we expect to match for NaN in Array.prototype.includes algorithm
  3776. if (matchNaN && JavascriptNumber::IsNan(element))
  3777. {
  3778. return i;
  3779. }
  3780. }
  3781. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3782. return -1;
  3783. }
  3784. Var JavascriptArray::EntryJoin(RecyclableObject* function, CallInfo callInfo, ...)
  3785. {
  3786. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  3787. ARGUMENTS(args, callInfo);
  3788. ScriptContext* scriptContext = function->GetScriptContext();
  3789. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3790. Assert(!(callInfo.Flags & CallFlags_New));
  3791. if (args.Info.Count == 0)
  3792. {
  3793. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.join"));
  3794. }
  3795. JavascriptString* separator;
  3796. if (args.Info.Count >= 2)
  3797. {
  3798. TypeId typeId = JavascriptOperators::GetTypeId(args[1]);
  3799. //ES5 15.4.4.5 If separator is undefined, let separator be the single-character String ",".
  3800. if (TypeIds_Undefined != typeId)
  3801. {
  3802. JS_REENTRANT(jsReentLock, separator = JavascriptConversion::ToString(args[1], scriptContext));
  3803. }
  3804. else
  3805. {
  3806. separator = scriptContext->GetLibrary()->GetCommaDisplayString();
  3807. }
  3808. }
  3809. else
  3810. {
  3811. separator = scriptContext->GetLibrary()->GetCommaDisplayString();
  3812. }
  3813. JS_REENTRANT_UNLOCK(jsReentLock, return JoinHelper(args[0], separator, scriptContext));
  3814. }
  3815. JavascriptString* JavascriptArray::JoinToString(Var value, ScriptContext* scriptContext)
  3816. {
  3817. TypeId typeId = JavascriptOperators::GetTypeId(value);
  3818. if (typeId == TypeIds_Null || typeId == TypeIds_Undefined)
  3819. {
  3820. return scriptContext->GetLibrary()->GetEmptyString();
  3821. }
  3822. else
  3823. {
  3824. return JavascriptConversion::ToString(value, scriptContext);
  3825. }
  3826. }
  3827. JavascriptString* JavascriptArray::JoinHelper(Var thisArg, JavascriptString* separator, ScriptContext* scriptContext)
  3828. {
  3829. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3830. bool isArray = JavascriptArray::Is(thisArg) && (scriptContext == JavascriptArray::FromVar(thisArg)->GetScriptContext());
  3831. bool isProxy = JavascriptProxy::Is(thisArg) && (scriptContext == JavascriptProxy::FromVar(thisArg)->GetScriptContext());
  3832. Var target = NULL;
  3833. bool isTargetObjectPushed = false;
  3834. // if we are visiting a proxy object, track that we have visited the target object as well so the next time w
  3835. // call the join helper for the target of this proxy, we will return above.
  3836. if (isProxy)
  3837. {
  3838. JavascriptProxy* proxy = JavascriptProxy::FromVar(thisArg);
  3839. Assert(proxy);
  3840. target = proxy->GetTarget();
  3841. if (target != nullptr)
  3842. {
  3843. // If we end up joining same array, instead of going in infinite loop, return the empty string
  3844. if (scriptContext->CheckObject(target))
  3845. {
  3846. return scriptContext->GetLibrary()->GetEmptyString();
  3847. }
  3848. else
  3849. {
  3850. scriptContext->PushObject(target);
  3851. isTargetObjectPushed = true;
  3852. }
  3853. }
  3854. }
  3855. // If we end up joining same array, instead of going in infinite loop, return the empty string
  3856. else if (scriptContext->CheckObject(thisArg))
  3857. {
  3858. return scriptContext->GetLibrary()->GetEmptyString();
  3859. }
  3860. if (!isTargetObjectPushed)
  3861. {
  3862. scriptContext->PushObject(thisArg);
  3863. }
  3864. JavascriptString* res = nullptr;
  3865. TryFinally([&]()
  3866. {
  3867. if (isArray)
  3868. {
  3869. #if ENABLE_COPYONACCESS_ARRAY
  3870. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray(thisArg);
  3871. #endif
  3872. JavascriptArray * arr = JavascriptArray::FromVar(thisArg);
  3873. switch (arr->GetTypeId())
  3874. {
  3875. case Js::TypeIds_Array:
  3876. JS_REENTRANT(jsReentLock, res = JoinArrayHelper(arr, separator, scriptContext));
  3877. break;
  3878. case Js::TypeIds_NativeIntArray:
  3879. JS_REENTRANT(jsReentLock, res = JoinArrayHelper(JavascriptNativeIntArray::FromVar(arr), separator, scriptContext));
  3880. break;
  3881. case Js::TypeIds_NativeFloatArray:
  3882. JS_REENTRANT(jsReentLock, res = JoinArrayHelper(JavascriptNativeFloatArray::FromVar(arr), separator, scriptContext));
  3883. break;
  3884. }
  3885. }
  3886. else if (RecyclableObject::Is(thisArg))
  3887. {
  3888. JS_REENTRANT(jsReentLock, res = JoinOtherHelper(RecyclableObject::FromVar(thisArg), separator, scriptContext));
  3889. }
  3890. else
  3891. {
  3892. JS_REENTRANT(jsReentLock, res = JoinOtherHelper(scriptContext->GetLibrary()->CreateNumberObject(thisArg), separator, scriptContext));
  3893. }
  3894. },
  3895. [&](bool/*hasException*/)
  3896. {
  3897. Var top = scriptContext->PopObject();
  3898. if (isProxy)
  3899. {
  3900. AssertMsg(top == target, "Unmatched operation stack");
  3901. }
  3902. else
  3903. {
  3904. AssertMsg(top == thisArg, "Unmatched operation stack");
  3905. }
  3906. });
  3907. if (res == nullptr)
  3908. {
  3909. res = scriptContext->GetLibrary()->GetEmptyString();
  3910. }
  3911. return res;
  3912. }
  3913. static const charcount_t Join_MaxEstimatedAppendCount = static_cast<charcount_t>((64 << 20) / sizeof(void *)); // 64 MB worth of pointers
  3914. template <typename T>
  3915. JavascriptString* JavascriptArray::JoinArrayHelper(T * arr, JavascriptString* separator, ScriptContext* scriptContext)
  3916. {
  3917. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3918. Assert(VirtualTableInfo<T>::HasVirtualTable(arr) || VirtualTableInfo<CrossSiteObject<T>>::HasVirtualTable(arr));
  3919. const uint32 arrLength = arr->length;
  3920. switch(arrLength)
  3921. {
  3922. default:
  3923. {
  3924. CaseDefault:
  3925. bool hasSeparator = (separator->GetLength() != 0);
  3926. const charcount_t estimatedAppendCount =
  3927. min(
  3928. Join_MaxEstimatedAppendCount,
  3929. static_cast<charcount_t>(arrLength + (hasSeparator ? arrLength - 1 : 0)));
  3930. CompoundString *const cs =
  3931. CompoundString::NewWithPointerCapacity(estimatedAppendCount, scriptContext->GetLibrary());
  3932. Var item;
  3933. BOOL gotItem;
  3934. JS_REENTRANT(jsReentLock, gotItem = TemplatedGetItem(arr, 0u, &item, scriptContext));
  3935. if (gotItem)
  3936. {
  3937. JS_REENTRANT(jsReentLock, cs->Append(JavascriptArray::JoinToString(item, scriptContext)));
  3938. }
  3939. for (uint32 i = 1; i < arrLength; i++)
  3940. {
  3941. if (hasSeparator)
  3942. {
  3943. cs->Append(separator);
  3944. }
  3945. JS_REENTRANT(jsReentLock, gotItem = TryTemplatedGetItem(arr, i, &item, scriptContext));
  3946. if (gotItem)
  3947. {
  3948. JS_REENTRANT(jsReentLock, cs->Append(JavascriptArray::JoinToString(item, scriptContext)));
  3949. }
  3950. }
  3951. return cs;
  3952. }
  3953. case 2:
  3954. {
  3955. bool hasSeparator = (separator->GetLength() != 0);
  3956. BOOL gotItem;
  3957. if(hasSeparator)
  3958. {
  3959. goto CaseDefault;
  3960. }
  3961. JavascriptString *res = nullptr;
  3962. Var item;
  3963. JS_REENTRANT(jsReentLock, gotItem = TemplatedGetItem(arr, 0u, &item, scriptContext));
  3964. if (gotItem)
  3965. {
  3966. JS_REENTRANT(jsReentLock, res = JavascriptArray::JoinToString(item, scriptContext));
  3967. }
  3968. JS_REENTRANT(jsReentLock, gotItem = TryTemplatedGetItem(arr, 1u, &item, scriptContext));
  3969. if (gotItem)
  3970. {
  3971. JS_REENTRANT(jsReentLock, JavascriptString *const itemString = JavascriptArray::JoinToString(item, scriptContext));
  3972. return res ? ConcatString::New(res, itemString) : itemString;
  3973. }
  3974. if(res)
  3975. {
  3976. return res;
  3977. }
  3978. goto Case0;
  3979. }
  3980. case 1:
  3981. {
  3982. Var item;
  3983. BOOL gotItem;
  3984. JS_REENTRANT(jsReentLock, gotItem = TemplatedGetItem(arr, 0u, &item, scriptContext));
  3985. if (gotItem)
  3986. {
  3987. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::JoinToString(item, scriptContext));
  3988. }
  3989. // fall through
  3990. }
  3991. case 0:
  3992. Case0:
  3993. return scriptContext->GetLibrary()->GetEmptyString();
  3994. }
  3995. }
  3996. JavascriptString* JavascriptArray::JoinOtherHelper(RecyclableObject* object, JavascriptString* separator, ScriptContext* scriptContext)
  3997. {
  3998. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3999. // In ES6-mode, we always load the length property from the object instead of using the internal slot.
  4000. // Even for arrays, this is now observable via proxies.
  4001. // If source object is not an array, we fall back to this behavior anyway.
  4002. JS_REENTRANT(jsReentLock,
  4003. int64 cSrcLength = (int64)OP_GetLength(object, scriptContext));
  4004. switch (cSrcLength)
  4005. {
  4006. default:
  4007. {
  4008. CaseDefault:
  4009. bool hasSeparator = (separator->GetLength() != 0);
  4010. BOOL gotItem;
  4011. const charcount_t estimatedAppendCount =
  4012. min(
  4013. Join_MaxEstimatedAppendCount,
  4014. static_cast<charcount_t>(cSrcLength + (hasSeparator ? cSrcLength - 1 : 0)));
  4015. CompoundString *const cs =
  4016. CompoundString::NewWithPointerCapacity(estimatedAppendCount, scriptContext->GetLibrary());
  4017. Var value;
  4018. JS_REENTRANT(jsReentLock, gotItem = JavascriptOperators::GetItem(object, 0u, &value, scriptContext));
  4019. if (gotItem)
  4020. {
  4021. JS_REENTRANT(jsReentLock, cs->Append(JavascriptArray::JoinToString(value, scriptContext)));
  4022. }
  4023. for (uint32 i = 1; i < cSrcLength; i++)
  4024. {
  4025. if (hasSeparator)
  4026. {
  4027. cs->Append(separator);
  4028. }
  4029. JS_REENTRANT(jsReentLock, gotItem = JavascriptOperators::GetItem(object, i, &value, scriptContext));
  4030. if (gotItem)
  4031. {
  4032. JS_REENTRANT(jsReentLock, cs->Append(JavascriptArray::JoinToString(value, scriptContext)));
  4033. }
  4034. }
  4035. return cs;
  4036. }
  4037. case 2:
  4038. {
  4039. bool hasSeparator = (separator->GetLength() != 0);
  4040. BOOL gotItem;
  4041. if(hasSeparator)
  4042. {
  4043. goto CaseDefault;
  4044. }
  4045. JavascriptString *res = nullptr;
  4046. Var value;
  4047. JS_REENTRANT(jsReentLock, gotItem = JavascriptOperators::GetItem(object, 0u, &value, scriptContext));
  4048. if (gotItem)
  4049. {
  4050. JS_REENTRANT(jsReentLock, res = JavascriptArray::JoinToString(value, scriptContext));
  4051. }
  4052. JS_REENTRANT(jsReentLock, gotItem = JavascriptOperators::GetItem(object, 1u, &value, scriptContext));
  4053. if (gotItem)
  4054. {
  4055. JS_REENTRANT(jsReentLock, JavascriptString *const valueString = JavascriptArray::JoinToString(value, scriptContext));
  4056. return res ? ConcatString::New(res, valueString) : valueString;
  4057. }
  4058. if(res)
  4059. {
  4060. return res;
  4061. }
  4062. goto Case0;
  4063. }
  4064. case 1:
  4065. {
  4066. Var value;
  4067. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(object, 0u, &value, scriptContext));
  4068. if (gotItem)
  4069. {
  4070. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::JoinToString(value, scriptContext));
  4071. }
  4072. // fall through
  4073. }
  4074. case 0:
  4075. Case0:
  4076. return scriptContext->GetLibrary()->GetEmptyString();
  4077. }
  4078. }
  4079. Var JavascriptArray::EntryLastIndexOf(RecyclableObject* function, CallInfo callInfo, ...)
  4080. {
  4081. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  4082. ARGUMENTS(args, callInfo);
  4083. ScriptContext* scriptContext = function->GetScriptContext();
  4084. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4085. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_lastIndexOf);
  4086. Assert(!(callInfo.Flags & CallFlags_New));
  4087. int64 length;
  4088. JavascriptArray * pArr = nullptr;
  4089. RecyclableObject* obj = nullptr;
  4090. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.lastIndexOf"), &pArr, &obj, &length));
  4091. Var search;
  4092. int64 fromIndex;
  4093. JS_REENTRANT(jsReentLock,
  4094. BOOL gotParam = GetParamForLastIndexOf(length, args, search, fromIndex, scriptContext));
  4095. if (!gotParam)
  4096. {
  4097. return TaggedInt::ToVarUnchecked(-1);
  4098. }
  4099. // Side effects (such as defining a property in a ToPrimitive call) during evaluation of fromIndex argument may convert the array to an ES5 array.
  4100. if (pArr && !JavascriptArray::Is(obj))
  4101. {
  4102. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  4103. pArr = nullptr;
  4104. }
  4105. if (pArr)
  4106. {
  4107. switch (pArr->GetTypeId())
  4108. {
  4109. case Js::TypeIds_Array:
  4110. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(pArr, search, fromIndex, scriptContext));
  4111. case Js::TypeIds_NativeIntArray:
  4112. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(JavascriptNativeIntArray::FromVar(pArr), search, fromIndex, scriptContext));
  4113. case Js::TypeIds_NativeFloatArray:
  4114. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(JavascriptNativeFloatArray::FromVar(pArr), search, fromIndex, scriptContext));
  4115. default:
  4116. AssertMsg(FALSE, "invalid array typeid");
  4117. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(pArr, search, fromIndex, scriptContext));
  4118. }
  4119. }
  4120. // source object is not a JavascriptArray but source could be a TypedArray
  4121. if (TypedArrayBase::Is(obj))
  4122. {
  4123. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(TypedArrayBase::FromVar(obj), search, fromIndex, scriptContext));
  4124. }
  4125. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(obj, search, fromIndex, scriptContext));
  4126. }
  4127. // Array.prototype.lastIndexOf as described in ES6.0 (draft 22) Section 22.1.3.14
  4128. BOOL JavascriptArray::GetParamForLastIndexOf(int64 length, Arguments const & args, Var& search, int64& fromIndex, ScriptContext * scriptContext)
  4129. {
  4130. if (length == 0)
  4131. {
  4132. return false;
  4133. }
  4134. if (args.Info.Count > 2)
  4135. {
  4136. fromIndex = GetFromLastIndex(args[2], length, scriptContext);
  4137. if (fromIndex >= length)
  4138. {
  4139. return false;
  4140. }
  4141. search = args[1];
  4142. }
  4143. else
  4144. {
  4145. search = args.Info.Count > 1 ? args[1] : scriptContext->GetLibrary()->GetUndefined();
  4146. fromIndex = length - 1;
  4147. }
  4148. return true;
  4149. }
  4150. template <typename T>
  4151. Var JavascriptArray::LastIndexOfHelper(T* pArr, Var search, int64 fromIndex, ScriptContext * scriptContext)
  4152. {
  4153. Var element = nullptr;
  4154. bool isSearchTaggedInt = TaggedInt::Is(search);
  4155. // First handle the indices > 2^32
  4156. while (fromIndex >= MaxArrayLength)
  4157. {
  4158. Var index = JavascriptNumber::ToVar(fromIndex, scriptContext);
  4159. if (JavascriptOperators::OP_HasItem(pArr, index, scriptContext))
  4160. {
  4161. element = JavascriptOperators::OP_GetElementI(pArr, index, scriptContext);
  4162. if (isSearchTaggedInt && TaggedInt::Is(element))
  4163. {
  4164. if (element == search)
  4165. {
  4166. return index;
  4167. }
  4168. fromIndex--;
  4169. continue;
  4170. }
  4171. if (JavascriptOperators::StrictEqual(element, search, scriptContext))
  4172. {
  4173. return index;
  4174. }
  4175. }
  4176. fromIndex--;
  4177. }
  4178. Assert(fromIndex < MaxArrayLength);
  4179. // fromIndex now has to be < MaxArrayLength so casting to uint32 is safe
  4180. uint32 end = static_cast<uint32>(fromIndex);
  4181. for (uint32 i = 0; i <= end; i++)
  4182. {
  4183. uint32 index = end - i;
  4184. if (!TryTemplatedGetItem(pArr, index, &element, scriptContext))
  4185. {
  4186. continue;
  4187. }
  4188. if (isSearchTaggedInt && TaggedInt::Is(element))
  4189. {
  4190. if (element == search)
  4191. {
  4192. return JavascriptNumber::ToVar(index, scriptContext);
  4193. }
  4194. continue;
  4195. }
  4196. if (JavascriptOperators::StrictEqual(element, search, scriptContext))
  4197. {
  4198. return JavascriptNumber::ToVar(index, scriptContext);
  4199. }
  4200. }
  4201. return TaggedInt::ToVarUnchecked(-1);
  4202. }
  4203. /*
  4204. * PopWithNoDst
  4205. * - For pop calls that do not return a value, we only need to decrement the length of the array.
  4206. */
  4207. void JavascriptNativeArray::PopWithNoDst(Var nativeArray)
  4208. {
  4209. Assert(JavascriptNativeArray::Is(nativeArray));
  4210. JavascriptArray * arr = JavascriptArray::FromVar(nativeArray);
  4211. // we will bailout on length 0
  4212. Assert(arr->GetLength() != 0);
  4213. uint32 index = arr->GetLength() - 1;
  4214. arr->SetLength(index);
  4215. }
  4216. /*
  4217. * JavascriptNativeIntArray::Pop
  4218. * - Returns int32 value from the array.
  4219. * - Returns missing item when the element is not available in the array object.
  4220. * - It doesn't walk up the prototype chain.
  4221. * - Length is decremented only if it pops an int32 element, in all other cases - we bail out from the jitted code.
  4222. * - This api cannot cause any implicit call and hence do not need implicit call bailout test around this api
  4223. */
  4224. int32 JavascriptNativeIntArray::Pop(ScriptContext * scriptContext, Var object)
  4225. {
  4226. Assert(JavascriptNativeIntArray::Is(object));
  4227. JavascriptNativeIntArray * arr = JavascriptNativeIntArray::FromVar(object);
  4228. Assert(arr->GetLength() != 0);
  4229. uint32 index = arr->length - 1;
  4230. int32 element = Js::JavascriptOperators::OP_GetNativeIntElementI_UInt32(object, index, scriptContext);
  4231. //If it is a missing item, then don't update the length - Pre-op Bail out will happen.
  4232. if(!SparseArraySegment<int32>::IsMissingItem(&element))
  4233. {
  4234. arr->SetLength(index);
  4235. }
  4236. return element;
  4237. }
  4238. /*
  4239. * JavascriptNativeFloatArray::Pop
  4240. * - Returns double value from the array.
  4241. * - Returns missing item when the element is not available in the array object.
  4242. * - It doesn't walk up the prototype chain.
  4243. * - Length is decremented only if it pops a double element, in all other cases - we bail out from the jitted code.
  4244. * - This api cannot cause any implicit call and hence do not need implicit call bailout test around this api
  4245. */
  4246. double JavascriptNativeFloatArray::Pop(ScriptContext * scriptContext, Var object)
  4247. {
  4248. Assert(JavascriptNativeFloatArray::Is(object));
  4249. JavascriptNativeFloatArray * arr = JavascriptNativeFloatArray::FromVar(object);
  4250. Assert(arr->GetLength() != 0);
  4251. uint32 index = arr->length - 1;
  4252. double element = Js::JavascriptOperators::OP_GetNativeFloatElementI_UInt32(object, index, scriptContext);
  4253. // If it is a missing item then don't update the length - Pre-op Bail out will happen.
  4254. if(!SparseArraySegment<double>::IsMissingItem(&element))
  4255. {
  4256. arr->SetLength(index);
  4257. }
  4258. return element;
  4259. }
  4260. /*
  4261. * JavascriptArray::Pop
  4262. * - Calls the generic Pop API, which can find elements from the prototype chain, when it is not available in the array object.
  4263. * - This API may cause implicit calls. Handles Array and non-array objects
  4264. */
  4265. Var JavascriptArray::Pop(ScriptContext * scriptContext, Var object)
  4266. {
  4267. if (JavascriptArray::Is(object))
  4268. {
  4269. return EntryPopJavascriptArray(scriptContext, object);
  4270. }
  4271. else
  4272. {
  4273. return EntryPopNonJavascriptArray(scriptContext, object);
  4274. }
  4275. }
  4276. Var JavascriptArray::EntryPopJavascriptArray(ScriptContext * scriptContext, Var object)
  4277. {
  4278. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4279. JavascriptArray * arr = JavascriptArray::FromVar(object);
  4280. uint32 length = arr->length;
  4281. if (length == 0)
  4282. {
  4283. // If length is 0, return 'undefined'
  4284. return scriptContext->GetLibrary()->GetUndefined();
  4285. }
  4286. uint32 index = length - 1;
  4287. Var element;
  4288. JS_REENTRANT(jsReentLock, BOOL gotItem = arr->DirectGetItemAtFull(index, &element));
  4289. if (!gotItem)
  4290. {
  4291. element = scriptContext->GetLibrary()->GetUndefined();
  4292. }
  4293. else
  4294. {
  4295. element = CrossSite::MarshalVar(scriptContext, element);
  4296. }
  4297. arr->SetLength(index); // SetLength will clear element at index
  4298. #ifdef VALIDATE_ARRAY
  4299. arr->ValidateArray();
  4300. #endif
  4301. return element;
  4302. }
  4303. Var JavascriptArray::EntryPopNonJavascriptArray(ScriptContext * scriptContext, Var object)
  4304. {
  4305. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4306. RecyclableObject* dynamicObject = nullptr;
  4307. if (FALSE == JavascriptConversion::ToObject(object, scriptContext, &dynamicObject))
  4308. {
  4309. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.pop"));
  4310. }
  4311. JS_REENTRANT(jsReentLock, BigIndex length = OP_GetLength(dynamicObject, scriptContext));
  4312. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.pop"));
  4313. if (length == 0u)
  4314. {
  4315. // Set length = 0
  4316. JS_REENTRANT(jsReentLock,
  4317. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, TaggedInt::ToVarUnchecked(0), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  4318. return scriptContext->GetLibrary()->GetUndefined();
  4319. }
  4320. BigIndex index = length;
  4321. --index;
  4322. Var element;
  4323. if (index.IsSmallIndex())
  4324. {
  4325. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(dynamicObject, index.GetSmallIndex(), &element, scriptContext));
  4326. if (!gotItem)
  4327. {
  4328. element = scriptContext->GetLibrary()->GetUndefined();
  4329. }
  4330. JS_REENTRANT(jsReentLock,
  4331. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, index.GetSmallIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig)),
  4332. // Set the new length
  4333. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(index.GetSmallIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  4334. }
  4335. else
  4336. {
  4337. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(dynamicObject, index.GetBigIndex(), &element, scriptContext));
  4338. if (!gotItem)
  4339. {
  4340. element = scriptContext->GetLibrary()->GetUndefined();
  4341. }
  4342. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, index.GetBigIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig)),
  4343. // Set the new length
  4344. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(index.GetBigIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  4345. }
  4346. return element;
  4347. }
  4348. Var JavascriptArray::EntryPop(RecyclableObject* function, CallInfo callInfo, ...)
  4349. {
  4350. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  4351. ARGUMENTS(args, callInfo);
  4352. ScriptContext* scriptContext = function->GetScriptContext();
  4353. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4354. Assert(!(callInfo.Flags & CallFlags_New));
  4355. if (args.Info.Count == 0)
  4356. {
  4357. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.pop"));
  4358. }
  4359. if (JavascriptArray::Is(args[0]))
  4360. {
  4361. JS_REENTRANT_UNLOCK(jsReentLock, return EntryPopJavascriptArray(scriptContext, args.Values[0]));
  4362. }
  4363. else
  4364. {
  4365. JS_REENTRANT_UNLOCK(jsReentLock, return EntryPopNonJavascriptArray(scriptContext, args.Values[0]));
  4366. }
  4367. }
  4368. /*
  4369. * JavascriptNativeIntArray::Push
  4370. * Pushes Int element in a native Int Array.
  4371. * We call the generic Push, if the array is not native Int or we have a really big array.
  4372. */
  4373. Var JavascriptNativeIntArray::Push(ScriptContext * scriptContext, Var array, int value)
  4374. {
  4375. // Handle non crossSite native int arrays here length within MaxArrayLength.
  4376. // JavascriptArray::Push will handle other cases.
  4377. if (JavascriptNativeIntArray::IsNonCrossSite(array))
  4378. {
  4379. JavascriptNativeIntArray * nativeIntArray = JavascriptNativeIntArray::FromVar(array);
  4380. Assert(!nativeIntArray->IsCrossSiteObject());
  4381. uint32 n = nativeIntArray->length;
  4382. if(n < JavascriptArray::MaxArrayLength)
  4383. {
  4384. nativeIntArray->SetItem(n, value);
  4385. n++;
  4386. AssertMsg(n == nativeIntArray->length, "Wrong update to the length of the native Int array");
  4387. return JavascriptNumber::ToVar(n, scriptContext);
  4388. }
  4389. }
  4390. return JavascriptArray::Push(scriptContext, array, JavascriptNumber::ToVar(value, scriptContext));
  4391. }
  4392. /*
  4393. * JavascriptNativeFloatArray::Push
  4394. * Pushes Float element in a native Int Array.
  4395. * We call the generic Push, if the array is not native Float or we have a really big array.
  4396. */
  4397. Var JavascriptNativeFloatArray::Push(ScriptContext * scriptContext, Var * array, double value)
  4398. {
  4399. // Handle non crossSite native int arrays here length within MaxArrayLength.
  4400. // JavascriptArray::Push will handle other cases.
  4401. if(JavascriptNativeFloatArray::IsNonCrossSite(array))
  4402. {
  4403. JavascriptNativeFloatArray * nativeFloatArray = JavascriptNativeFloatArray::FromVar(array);
  4404. Assert(!nativeFloatArray->IsCrossSiteObject());
  4405. uint32 n = nativeFloatArray->length;
  4406. if(n < JavascriptArray::MaxArrayLength)
  4407. {
  4408. nativeFloatArray->SetItem(n, value);
  4409. n++;
  4410. AssertMsg(n == nativeFloatArray->length, "Wrong update to the length of the native Float array");
  4411. return JavascriptNumber::ToVar(n, scriptContext);
  4412. }
  4413. }
  4414. return JavascriptArray::Push(scriptContext, array, JavascriptNumber::ToVarNoCheck(value, scriptContext));
  4415. }
  4416. /*
  4417. * JavascriptArray::Push
  4418. * Pushes Var element in a Var Array.
  4419. */
  4420. Var JavascriptArray::Push(ScriptContext * scriptContext, Var object, Var value)
  4421. {
  4422. Var args[2];
  4423. args[0] = object;
  4424. args[1] = value;
  4425. if (JavascriptArray::Is(object))
  4426. {
  4427. return EntryPushJavascriptArray(scriptContext, args, 2);
  4428. }
  4429. else
  4430. {
  4431. return EntryPushNonJavascriptArray(scriptContext, args, 2);
  4432. }
  4433. }
  4434. /*
  4435. * EntryPushNonJavascriptArray
  4436. * - Handles Entry push calls, when Objects are not javascript arrays
  4437. */
  4438. Var JavascriptArray::EntryPushNonJavascriptArray(ScriptContext * scriptContext, Var * args, uint argCount)
  4439. {
  4440. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4441. RecyclableObject* obj = nullptr;
  4442. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  4443. {
  4444. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.push"));
  4445. }
  4446. JS_REENTRANT_UNLOCK(jsReentLock, Var length = JavascriptOperators::OP_GetLength(obj, scriptContext));
  4447. if(JavascriptOperators::GetTypeId(length) == TypeIds_Undefined && scriptContext->GetThreadContext()->IsDisableImplicitCall() &&
  4448. scriptContext->GetThreadContext()->GetImplicitCallFlags() != Js::ImplicitCall_None)
  4449. {
  4450. return length;
  4451. }
  4452. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.push"));
  4453. BigIndex n;
  4454. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  4455. {
  4456. n = (uint64) JavascriptConversion::ToLength(length, scriptContext);
  4457. }
  4458. else
  4459. {
  4460. n = JavascriptConversion::ToUInt32(length, scriptContext);
  4461. }
  4462. // First handle "small" indices.
  4463. uint index;
  4464. for (index=1; index < argCount && n < JavascriptArray::MaxArrayLength; ++index, ++n)
  4465. {
  4466. JS_REENTRANT(jsReentLock,
  4467. BOOL setItem = JavascriptOperators::SetItem(obj, obj, n.GetSmallIndex(), args[index], scriptContext, PropertyOperation_ThrowIfNotExtensible));
  4468. if (h.IsThrowTypeError(setItem))
  4469. {
  4470. if (scriptContext->GetThreadContext()->RecordImplicitException())
  4471. {
  4472. h.ThrowTypeErrorOnFailure();
  4473. }
  4474. else
  4475. {
  4476. return nullptr;
  4477. }
  4478. }
  4479. }
  4480. // Use BigIndex if we need to push indices >= MaxArrayLength
  4481. if (index < argCount)
  4482. {
  4483. BigIndex big = n;
  4484. for (; index < argCount; ++index, ++big)
  4485. {
  4486. JS_REENTRANT(jsReentLock, BOOL setItem = big.SetItem(obj, args[index], PropertyOperation_ThrowIfNotExtensible));
  4487. if (h.IsThrowTypeError(setItem))
  4488. {
  4489. if(scriptContext->GetThreadContext()->RecordImplicitException())
  4490. {
  4491. h.ThrowTypeErrorOnFailure();
  4492. }
  4493. else
  4494. {
  4495. return nullptr;
  4496. }
  4497. }
  4498. }
  4499. // Set the new length; for objects it is all right for this to be >= MaxArrayLength
  4500. JS_REENTRANT(jsReentLock,
  4501. BOOL setLength = JavascriptOperators::SetProperty(obj, obj, PropertyIds::length, big.ToNumber(scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  4502. if (h.IsThrowTypeError(setLength))
  4503. {
  4504. if(scriptContext->GetThreadContext()->RecordImplicitException())
  4505. {
  4506. h.ThrowTypeErrorOnFailure();
  4507. }
  4508. else
  4509. {
  4510. return nullptr;
  4511. }
  4512. }
  4513. return big.ToNumber(scriptContext);
  4514. }
  4515. else
  4516. {
  4517. // Set the new length
  4518. Var lengthAsNUmberVar = JavascriptNumber::ToVar(n.IsSmallIndex() ? n.GetSmallIndex() : n.GetBigIndex(), scriptContext);
  4519. JS_REENTRANT(jsReentLock,
  4520. BOOL setLength = JavascriptOperators::SetProperty(obj, obj, PropertyIds::length, lengthAsNUmberVar, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  4521. if (h.IsThrowTypeError(setLength))
  4522. {
  4523. if(scriptContext->GetThreadContext()->RecordImplicitException())
  4524. {
  4525. h.ThrowTypeErrorOnFailure();
  4526. }
  4527. else
  4528. {
  4529. return nullptr;
  4530. }
  4531. }
  4532. return lengthAsNUmberVar;
  4533. }
  4534. }
  4535. /*
  4536. * JavascriptArray::EntryPushJavascriptArray
  4537. * Pushes Var element in a Var Array.
  4538. * Returns the length of the array.
  4539. */
  4540. Var JavascriptArray::EntryPushJavascriptArray(ScriptContext * scriptContext, Var * args, uint argCount)
  4541. {
  4542. JavascriptArray * arr = JavascriptArray::FromAnyArray(args[0]);
  4543. uint n = arr->length;
  4544. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.push"));
  4545. // Fast Path for one push for small indexes
  4546. if (argCount == 2 && n < JavascriptArray::MaxArrayLength)
  4547. {
  4548. // Set Item is overridden by CrossSiteObject, so no need to check for IsCrossSiteObject()
  4549. h.ThrowTypeErrorOnFailure(arr->SetItem(n, args[1], PropertyOperation_None));
  4550. return JavascriptNumber::ToVar(n + 1, scriptContext);
  4551. }
  4552. // Fast Path for multiple push for small indexes
  4553. if (JavascriptArray::MaxArrayLength - argCount + 1 > n && JavascriptArray::IsVarArray(arr) && scriptContext == arr->GetScriptContext())
  4554. {
  4555. uint index;
  4556. for (index = 1; index < argCount; ++index, ++n)
  4557. {
  4558. Assert(n != JavascriptArray::MaxArrayLength);
  4559. // Set Item is overridden by CrossSiteObject, so no need to check for IsCrossSiteObject()
  4560. arr->JavascriptArray::DirectSetItemAt(n, args[index]);
  4561. }
  4562. return JavascriptNumber::ToVar(n, scriptContext);
  4563. }
  4564. return EntryPushJavascriptArrayNoFastPath(scriptContext, args, argCount);
  4565. }
  4566. Var JavascriptArray::EntryPushJavascriptArrayNoFastPath(ScriptContext * scriptContext, Var * args, uint argCount)
  4567. {
  4568. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4569. JavascriptArray * arr = JavascriptArray::FromAnyArray(args[0]);
  4570. uint n = arr->length;
  4571. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.push"));
  4572. // First handle "small" indices.
  4573. uint index;
  4574. for (index = 1; index < argCount && n < JavascriptArray::MaxArrayLength; ++index, ++n)
  4575. {
  4576. // Set Item is overridden by CrossSiteObject, so no need to check for IsCrossSiteObject()
  4577. h.ThrowTypeErrorOnFailure(arr->SetItem(n, args[index], PropertyOperation_None));
  4578. }
  4579. // Use BigIndex if we need to push indices >= MaxArrayLength
  4580. if (index < argCount)
  4581. {
  4582. // Not supporting native array with BigIndex.
  4583. arr = EnsureNonNativeArray(arr);
  4584. Assert(n == JavascriptArray::MaxArrayLength);
  4585. for (BigIndex big = n; index < argCount; ++index, ++big)
  4586. {
  4587. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(big.SetItem(arr, args[index])));
  4588. }
  4589. #ifdef VALIDATE_ARRAY
  4590. arr->ValidateArray();
  4591. #endif
  4592. // This is where we should set the length, but for arrays it cannot be >= MaxArrayLength
  4593. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  4594. }
  4595. #ifdef VALIDATE_ARRAY
  4596. arr->ValidateArray();
  4597. #endif
  4598. return JavascriptNumber::ToVar(n, scriptContext);
  4599. }
  4600. /*
  4601. * JavascriptArray::EntryPush
  4602. * Handles Push calls(Script Function)
  4603. */
  4604. Var JavascriptArray::EntryPush(RecyclableObject* function, CallInfo callInfo, ...)
  4605. {
  4606. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  4607. ARGUMENTS(args, callInfo);
  4608. ScriptContext* scriptContext = function->GetScriptContext();
  4609. Assert(!(callInfo.Flags & CallFlags_New));
  4610. if (args.Info.Count == 0)
  4611. {
  4612. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.push"));
  4613. }
  4614. if (JavascriptArray::Is(args[0]))
  4615. {
  4616. return EntryPushJavascriptArray(scriptContext, args.Values, args.Info.Count);
  4617. }
  4618. else
  4619. {
  4620. return EntryPushNonJavascriptArray(scriptContext, args.Values, args.Info.Count);
  4621. }
  4622. }
  4623. template <typename T>
  4624. void JavascriptArray::CopyHeadIfInlinedHeadSegment(JavascriptArray *array, Recycler *recycler)
  4625. {
  4626. SparseArraySegmentBase* inlineHeadSegment = nullptr;
  4627. bool hasInlineSegment = false;
  4628. if (JavascriptNativeArray::Is(array))
  4629. {
  4630. if (JavascriptNativeFloatArray::Is(array))
  4631. {
  4632. inlineHeadSegment = DetermineInlineHeadSegmentPointer<JavascriptNativeFloatArray, 0, true>((JavascriptNativeFloatArray*)array);
  4633. }
  4634. else if (JavascriptNativeIntArray::Is(array))
  4635. {
  4636. inlineHeadSegment = DetermineInlineHeadSegmentPointer<JavascriptNativeIntArray, 0, true>((JavascriptNativeIntArray*)array);
  4637. }
  4638. Assert(inlineHeadSegment);
  4639. hasInlineSegment = (array->head == (SparseArraySegment<T>*)inlineHeadSegment);
  4640. }
  4641. else
  4642. {
  4643. hasInlineSegment = HasInlineHeadSegment(array->head->length);
  4644. }
  4645. if (hasInlineSegment)
  4646. {
  4647. AnalysisAssert(array->head);
  4648. SparseArraySegment<T>* newHeadSeg = array->ReallocNonLeafSegment((SparseArraySegment<T>*)PointerValue(array->head), array->head->next);
  4649. array->head = newHeadSeg;
  4650. }
  4651. }
  4652. template <typename T>
  4653. void JavascriptArray::ReallocateNonLeafLastSegmentIfLeaf(JavascriptArray * arr, Recycler * recycler)
  4654. {
  4655. 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.
  4656. // TODO: Consider utilizing lastUsedSegment once we fix CopyHeadIfInlinedHeadSegment in that respect.
  4657. SparseArraySegmentBase *lastSeg = nullptr;
  4658. SparseArraySegmentBase *seg = arr->head;
  4659. while (seg)
  4660. {
  4661. lastSeg = seg;
  4662. seg = seg->next;
  4663. }
  4664. if (SparseArraySegmentBase::IsLeafSegment(lastSeg, recycler))
  4665. {
  4666. AnalysisAssert(lastSeg);
  4667. arr->ReallocNonLeafSegment((SparseArraySegment<T>*)lastSeg, lastSeg->next, true /*forceNonLeaf*/);
  4668. }
  4669. }
  4670. Var JavascriptArray::EntryReverse(RecyclableObject* function, CallInfo callInfo, ...)
  4671. {
  4672. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  4673. ARGUMENTS(args, callInfo);
  4674. ScriptContext* scriptContext = function->GetScriptContext();
  4675. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4676. Assert(!(callInfo.Flags & CallFlags_New));
  4677. if (args.Info.Count == 0)
  4678. {
  4679. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reverse"));
  4680. }
  4681. BigIndex length = 0u;
  4682. JavascriptArray* pArr = nullptr;
  4683. RecyclableObject* obj = nullptr;
  4684. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.reverse"), &pArr, &obj, &length));
  4685. if (length.IsSmallIndex())
  4686. {
  4687. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReverseHelper(pArr, nullptr, obj, length.GetSmallIndex(), scriptContext));
  4688. }
  4689. 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
  4690. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReverseHelper(pArr, nullptr, obj, length.GetBigIndex(), scriptContext));
  4691. }
  4692. // Array.prototype.reverse as described in ES6.0 (draft 22) Section 22.1.3.20
  4693. template <typename T>
  4694. Var JavascriptArray::ReverseHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, ScriptContext* scriptContext)
  4695. {
  4696. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4697. T middle = length / 2;
  4698. Var lowerValue = nullptr, upperValue = nullptr;
  4699. T lowerExists, upperExists;
  4700. const char16* methodName;
  4701. bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
  4702. if (isTypedArrayEntryPoint)
  4703. {
  4704. methodName = _u("[TypedArray].prototype.reverse");
  4705. }
  4706. else
  4707. {
  4708. methodName = _u("Array.prototype.reverse");
  4709. }
  4710. // If we came from Array.prototype.map and source object is not a JavascriptArray, source could be a TypedArray
  4711. if (!isTypedArrayEntryPoint && pArr == nullptr && TypedArrayBase::Is(obj))
  4712. {
  4713. typedArrayBase = TypedArrayBase::FromVar(obj);
  4714. }
  4715. ThrowTypeErrorOnFailureHelper h(scriptContext, methodName);
  4716. if (pArr)
  4717. {
  4718. Recycler * recycler = scriptContext->GetRecycler();
  4719. if (length <= 1)
  4720. {
  4721. return pArr;
  4722. }
  4723. if (pArr->IsFillFromPrototypes())
  4724. {
  4725. // For odd-length arrays, the middle element is unchanged,
  4726. // so we cannot fill it from the prototypes.
  4727. if (length % 2 == 0)
  4728. {
  4729. JS_REENTRANT(jsReentLock, pArr->FillFromPrototypes(0, (uint32)length));
  4730. }
  4731. else
  4732. {
  4733. middle = length / 2;
  4734. JS_REENTRANT(jsReentLock,
  4735. pArr->FillFromPrototypes(0, (uint32)middle),
  4736. pArr->FillFromPrototypes(1 + (uint32)middle, (uint32)length));
  4737. }
  4738. }
  4739. if (pArr->HasNoMissingValues() && pArr->head && pArr->head->next)
  4740. {
  4741. // This function currently does not track missing values in the head segment if there are multiple segments
  4742. pArr->SetHasNoMissingValues(false);
  4743. }
  4744. // Above FillFromPrototypes call can change the length of the array. Our segment calculation below will
  4745. // not work with the stale length. Update the length.
  4746. // Note : since we are reversing the whole segment below - the functionality is not spec compliant already.
  4747. length = pArr->length;
  4748. SparseArraySegmentBase *prevSeg = nullptr;
  4749. SparseArraySegmentBase *nextSeg = nullptr;
  4750. SparseArraySegmentBase *pinPrevSeg = nullptr;
  4751. bool isIntArray = false;
  4752. bool isFloatArray = false;
  4753. pArr->ClearSegmentMap(); // Just dump the segment map on reverse
  4754. if (JavascriptNativeIntArray::Is(pArr))
  4755. {
  4756. isIntArray = true;
  4757. }
  4758. else if (JavascriptNativeFloatArray::Is(pArr))
  4759. {
  4760. isFloatArray = true;
  4761. }
  4762. // During the loop below we are going to reverse the segments list. The head segment will become the last segment.
  4763. // We have to verify that the current head segment is not the inilined segement, otherwise due to shuffling below, the inlined segment will no longer
  4764. // be the head and that can create issue down the line. Create new segment if it is an inilined segment.
  4765. if (pArr->head && pArr->head->next)
  4766. {
  4767. if (isIntArray)
  4768. {
  4769. CopyHeadIfInlinedHeadSegment<int32>(pArr, recycler);
  4770. ReallocateNonLeafLastSegmentIfLeaf<int32>(pArr, recycler);
  4771. }
  4772. else if (isFloatArray)
  4773. {
  4774. CopyHeadIfInlinedHeadSegment<double>(pArr, recycler);
  4775. ReallocateNonLeafLastSegmentIfLeaf<double>(pArr, recycler);
  4776. }
  4777. else
  4778. {
  4779. CopyHeadIfInlinedHeadSegment<Var>(pArr, recycler);
  4780. }
  4781. }
  4782. SparseArraySegmentBase* seg = pArr->head;
  4783. while (seg)
  4784. {
  4785. nextSeg = seg->next;
  4786. // If seg.length == 0, it is possible that (seg.left + seg.length == prev.left + prev.length),
  4787. // resulting in 2 segments sharing the same "left".
  4788. if (seg->length > 0)
  4789. {
  4790. if (isIntArray)
  4791. {
  4792. ((SparseArraySegment<int32>*)seg)->ReverseSegment(recycler);
  4793. }
  4794. else if (isFloatArray)
  4795. {
  4796. ((SparseArraySegment<double>*)seg)->ReverseSegment(recycler);
  4797. }
  4798. else
  4799. {
  4800. ((SparseArraySegment<Var>*)seg)->ReverseSegment(recycler);
  4801. }
  4802. seg->left = ((uint32)length) > (seg->left + seg->length) ? ((uint32)length) - (seg->left + seg->length) : 0;
  4803. seg->next = prevSeg;
  4804. // Make sure size doesn't overlap with next segment.
  4805. // An easy fix is to just truncate the size...
  4806. seg->EnsureSizeInBound();
  4807. // If the last segment is a leaf, then we may be losing our last scanned pointer to its previous
  4808. // segment. Hold onto it with pinPrevSeg until we reallocate below.
  4809. pinPrevSeg = prevSeg;
  4810. prevSeg = seg;
  4811. }
  4812. seg = nextSeg;
  4813. }
  4814. pArr->head = prevSeg;
  4815. pArr->InvalidateLastUsedSegment(); // lastUsedSegment might be 0-length and discarded above
  4816. if (isIntArray)
  4817. {
  4818. pArr->EnsureHeadStartsFromZero<int32>(recycler);
  4819. }
  4820. else if (isFloatArray)
  4821. {
  4822. pArr->EnsureHeadStartsFromZero<double>(recycler);
  4823. }
  4824. else
  4825. {
  4826. pArr->EnsureHeadStartsFromZero<Var>(recycler);
  4827. }
  4828. #ifdef VALIDATE_ARRAY
  4829. pArr->ValidateArray();
  4830. #endif
  4831. }
  4832. else if (typedArrayBase)
  4833. {
  4834. Assert(length <= JavascriptArray::MaxArrayLength);
  4835. if (typedArrayBase->GetLength() == length)
  4836. {
  4837. // If typedArrayBase->length == length then we know that the TypedArray will have all items < length
  4838. // and we won't have to check that the elements exist or not.
  4839. for (uint32 lower = 0; lower < (uint32)middle; lower++)
  4840. {
  4841. uint32 upper = (uint32)length - lower - 1;
  4842. lowerValue = typedArrayBase->DirectGetItem(lower);
  4843. upperValue = typedArrayBase->DirectGetItem(upper);
  4844. // We still have to call HasItem even though we know the TypedArray has both lower and upper because
  4845. // there may be a proxy handler trapping HasProperty.
  4846. lowerExists = typedArrayBase->HasItem(lower);
  4847. upperExists = typedArrayBase->HasItem(upper);
  4848. JS_REENTRANT(jsReentLock,
  4849. h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(lower, upperValue)),
  4850. h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(upper, lowerValue)));
  4851. }
  4852. }
  4853. else
  4854. {
  4855. Assert(middle <= UINT_MAX);
  4856. for (uint32 lower = 0; lower < (uint32)middle; lower++)
  4857. {
  4858. uint32 upper = (uint32)length - lower - 1;
  4859. lowerValue = typedArrayBase->DirectGetItem(lower);
  4860. upperValue = typedArrayBase->DirectGetItem(upper);
  4861. lowerExists = typedArrayBase->HasItem(lower);
  4862. upperExists = typedArrayBase->HasItem(upper);
  4863. if (lowerExists)
  4864. {
  4865. if (upperExists)
  4866. {
  4867. JS_REENTRANT(jsReentLock,
  4868. h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(lower, upperValue)),
  4869. h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(upper, lowerValue)));
  4870. }
  4871. else
  4872. {
  4873. // This will always fail for a TypedArray if lower < length
  4874. h.ThrowTypeErrorOnFailure(typedArrayBase->DeleteItem(lower, PropertyOperation_ThrowOnDeleteIfNotConfig));
  4875. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(upper, lowerValue)));
  4876. }
  4877. }
  4878. else
  4879. {
  4880. if (upperExists)
  4881. {
  4882. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(lower, upperValue)));
  4883. // This will always fail for a TypedArray if upper < length
  4884. h.ThrowTypeErrorOnFailure(typedArrayBase->DeleteItem(upper, PropertyOperation_ThrowOnDeleteIfNotConfig));
  4885. }
  4886. }
  4887. }
  4888. }
  4889. }
  4890. else
  4891. {
  4892. for (T lower = 0; lower < middle; lower++)
  4893. {
  4894. T upper = length - lower - 1;
  4895. JS_REENTRANT(jsReentLock,
  4896. lowerExists = JavascriptOperators::HasItem(obj, lower) && JavascriptOperators::GetItem(obj, lower, &lowerValue, scriptContext),
  4897. upperExists = JavascriptOperators::HasItem(obj, upper) && JavascriptOperators::GetItem(obj, upper, &upperValue, scriptContext));
  4898. if (lowerExists)
  4899. {
  4900. if (upperExists)
  4901. {
  4902. JS_REENTRANT(jsReentLock,
  4903. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, lower, upperValue, scriptContext, PropertyOperation_ThrowIfNotExtensible)),
  4904. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, upper, lowerValue, scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  4905. }
  4906. else
  4907. {
  4908. JS_REENTRANT(jsReentLock,
  4909. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(obj, lower, PropertyOperation_ThrowOnDeleteIfNotConfig)),
  4910. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, upper, lowerValue, scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  4911. }
  4912. }
  4913. else
  4914. {
  4915. if (upperExists)
  4916. {
  4917. JS_REENTRANT(jsReentLock,
  4918. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, lower, upperValue, scriptContext, PropertyOperation_ThrowIfNotExtensible)),
  4919. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(obj, upper, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  4920. }
  4921. }
  4922. }
  4923. }
  4924. return obj;
  4925. }
  4926. template<typename T>
  4927. void JavascriptArray::ShiftHelper(JavascriptArray* pArr, ScriptContext * scriptContext)
  4928. {
  4929. Recycler * recycler = scriptContext->GetRecycler();
  4930. SparseArraySegment<T>* next = SparseArraySegment<T>::From(pArr->head->next);
  4931. while (next)
  4932. {
  4933. next->left--;
  4934. next = SparseArraySegment<T>::From(next->next);
  4935. }
  4936. // head and next might overlap as the next segment left is decremented
  4937. next = SparseArraySegment<T>::From(pArr->head->next);
  4938. if (next && (pArr->head->size > next->left))
  4939. {
  4940. AssertMsg(pArr->head->left == 0, "Array always points to a head starting at index 0");
  4941. AssertMsg(pArr->head->size == next->left + 1, "Shift next->left overlaps current segment by more than 1 element");
  4942. SparseArraySegment<T> *head = SparseArraySegment<T>::From(pArr->head);
  4943. // Merge the two adjacent segments
  4944. if (next->length != 0)
  4945. {
  4946. uint32 offset = head->size - 1;
  4947. // There is room for one unshifted element in head segment.
  4948. // Hence it's enough if we grow the head segment by next->length - 1
  4949. if (next->next)
  4950. {
  4951. // If we have a next->next, we can't grow pass the left of that
  4952. // If the array had a segment map before, the next->next might just be right after next as well.
  4953. // So we just need to grow to the end of the next segment
  4954. // TODO: merge that segment too?
  4955. Assert(next->next->left >= head->size);
  4956. uint32 maxGrowSize = next->next->left - head->size;
  4957. if (maxGrowSize != 0)
  4958. {
  4959. head = head->GrowByMinMax(recycler, next->length - 1, maxGrowSize); //-1 is to account for unshift
  4960. }
  4961. else
  4962. {
  4963. // The next segment is only of length one, so we already have space in the header to copy that
  4964. Assert(next->length == 1);
  4965. }
  4966. }
  4967. else
  4968. {
  4969. head = head->GrowByMin(recycler, next->length - 1); //-1 is to account for unshift
  4970. }
  4971. MoveArray(head->elements + offset, next->elements, next->length);
  4972. head->length = offset + next->length;
  4973. head->CheckLengthvsSize();
  4974. pArr->head = head;
  4975. }
  4976. head->next = next->next;
  4977. pArr->InvalidateLastUsedSegment();
  4978. }
  4979. #ifdef VALIDATE_ARRAY
  4980. pArr->ValidateArray();
  4981. #endif
  4982. }
  4983. Var JavascriptArray::EntryShift(RecyclableObject* function, CallInfo callInfo, ...)
  4984. {
  4985. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  4986. ARGUMENTS(args, callInfo);
  4987. ScriptContext* scriptContext = function->GetScriptContext();
  4988. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4989. Assert(!(callInfo.Flags & CallFlags_New));
  4990. Var res = scriptContext->GetLibrary()->GetUndefined();
  4991. if (args.Info.Count == 0)
  4992. {
  4993. return res;
  4994. }
  4995. if (JavascriptArray::Is(args[0]))
  4996. {
  4997. JavascriptArray * pArr = JavascriptArray::FromVar(args[0]);
  4998. #if ENABLE_COPYONACCESS_ARRAY
  4999. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pArr);
  5000. #endif
  5001. if (pArr->length == 0)
  5002. {
  5003. return res;
  5004. }
  5005. if(pArr->IsFillFromPrototypes())
  5006. {
  5007. JS_REENTRANT(jsReentLock, pArr->FillFromPrototypes(0, pArr->length)); // We need find all missing value from [[proto]] object
  5008. }
  5009. if(pArr->HasNoMissingValues() && pArr->head && pArr->head->next)
  5010. {
  5011. // This function currently does not track missing values in the head segment if there are multiple segments
  5012. pArr->SetHasNoMissingValues(false);
  5013. }
  5014. pArr->length--;
  5015. pArr->ClearSegmentMap(); // Dump segmentMap on shift (before any allocation)
  5016. Recycler * recycler = scriptContext->GetRecycler();
  5017. bool isIntArray = false;
  5018. bool isFloatArray = false;
  5019. if(JavascriptNativeIntArray::Is(pArr))
  5020. {
  5021. isIntArray = true;
  5022. }
  5023. else if(JavascriptNativeFloatArray::Is(pArr))
  5024. {
  5025. isFloatArray = true;
  5026. }
  5027. if (pArr->head->length != 0)
  5028. {
  5029. if(isIntArray)
  5030. {
  5031. int32 nativeResult = SparseArraySegment<int32>::From(pArr->head)->GetElement(0);
  5032. if(SparseArraySegment<int32>::IsMissingItem(&nativeResult))
  5033. {
  5034. res = scriptContext->GetLibrary()->GetUndefined();
  5035. }
  5036. else
  5037. {
  5038. res = Js::JavascriptNumber::ToVar(nativeResult, scriptContext);
  5039. }
  5040. SparseArraySegment<int32>::From(pArr->head)->RemoveElement(recycler, 0);
  5041. }
  5042. else if (isFloatArray)
  5043. {
  5044. double nativeResult = SparseArraySegment<double>::From(pArr->head)->GetElement(0);
  5045. if(SparseArraySegment<double>::IsMissingItem(&nativeResult))
  5046. {
  5047. res = scriptContext->GetLibrary()->GetUndefined();
  5048. }
  5049. else
  5050. {
  5051. res = Js::JavascriptNumber::ToVarNoCheck(nativeResult, scriptContext);
  5052. }
  5053. SparseArraySegment<double>::From(pArr->head)->RemoveElement(recycler, 0);
  5054. }
  5055. else
  5056. {
  5057. res = SparseArraySegment<Var>::From(pArr->head)->GetElement(0);
  5058. if(SparseArraySegment<Var>::IsMissingItem(&res))
  5059. {
  5060. res = scriptContext->GetLibrary()->GetUndefined();
  5061. }
  5062. else
  5063. {
  5064. res = CrossSite::MarshalVar(scriptContext, res);
  5065. }
  5066. SparseArraySegment<Var>::From(pArr->head)->RemoveElement(recycler, 0);
  5067. }
  5068. }
  5069. if(isIntArray)
  5070. {
  5071. ShiftHelper<int32>(pArr, scriptContext);
  5072. }
  5073. else if (isFloatArray)
  5074. {
  5075. ShiftHelper<double>(pArr, scriptContext);
  5076. }
  5077. else
  5078. {
  5079. ShiftHelper<Var>(pArr, scriptContext);
  5080. }
  5081. }
  5082. else
  5083. {
  5084. RecyclableObject* dynamicObject = nullptr;
  5085. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &dynamicObject))
  5086. {
  5087. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.shift"));
  5088. }
  5089. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.shift"));
  5090. JS_REENTRANT(jsReentLock, BigIndex length = OP_GetLength(dynamicObject, scriptContext));
  5091. if (length == 0u)
  5092. {
  5093. // If length is 0, return 'undefined'
  5094. JS_REENTRANT(jsReentLock,
  5095. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, TaggedInt::ToVarUnchecked(0), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  5096. return scriptContext->GetLibrary()->GetUndefined();
  5097. }
  5098. JS_REENTRANT(jsReentLock,
  5099. BOOL gotItem = JavascriptOperators::GetItem(dynamicObject, 0u, &res, scriptContext));
  5100. if (!gotItem)
  5101. {
  5102. res = scriptContext->GetLibrary()->GetUndefined();
  5103. }
  5104. --length;
  5105. uint32 lengthToUin32Max = length.IsSmallIndex() ? length.GetSmallIndex() : MaxArrayLength;
  5106. for (uint32 i = 0u; i < lengthToUin32Max; i++)
  5107. {
  5108. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(dynamicObject, i + 1));
  5109. if (hasItem)
  5110. {
  5111. Var element = nullptr;
  5112. JS_REENTRANT(jsReentLock,
  5113. element = JavascriptOperators::GetItem(dynamicObject, i + 1, scriptContext),
  5114. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(dynamicObject, dynamicObject, i, element, scriptContext, PropertyOperation_ThrowIfNotExtensible, /*skipPrototypeCheck*/ true)));
  5115. }
  5116. else
  5117. {
  5118. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, i, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  5119. }
  5120. }
  5121. for (uint64 i = MaxArrayLength; length > i; i++)
  5122. {
  5123. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(dynamicObject, i + 1));
  5124. if (hasItem)
  5125. {
  5126. Var element = nullptr;
  5127. JS_REENTRANT(jsReentLock,
  5128. element = JavascriptOperators::GetItem(dynamicObject, i + 1, scriptContext),
  5129. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(dynamicObject, dynamicObject, i, element, scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  5130. }
  5131. else
  5132. {
  5133. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, i, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  5134. }
  5135. }
  5136. if (length.IsSmallIndex())
  5137. {
  5138. JS_REENTRANT(jsReentLock,
  5139. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, length.GetSmallIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig)),
  5140. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(length.GetSmallIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  5141. }
  5142. else
  5143. {
  5144. JS_REENTRANT(jsReentLock,
  5145. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, length.GetBigIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig)),
  5146. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(length.GetBigIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  5147. }
  5148. }
  5149. return res;
  5150. }
  5151. Js::JavascriptArray* JavascriptArray::CreateNewArrayHelper(uint32 len, bool isIntArray, bool isFloatArray, Js::JavascriptArray* baseArray, ScriptContext* scriptContext)
  5152. {
  5153. if (isIntArray)
  5154. {
  5155. Js::JavascriptNativeIntArray *pnewArr = scriptContext->GetLibrary()->CreateNativeIntArray(len);
  5156. pnewArr->EnsureHead<int32>();
  5157. #if ENABLE_PROFILE_INFO
  5158. pnewArr->CopyArrayProfileInfo(Js::JavascriptNativeIntArray::FromVar(baseArray));
  5159. #endif
  5160. return pnewArr;
  5161. }
  5162. else if (isFloatArray)
  5163. {
  5164. Js::JavascriptNativeFloatArray *pnewArr = scriptContext->GetLibrary()->CreateNativeFloatArray(len);
  5165. pnewArr->EnsureHead<double>();
  5166. #if ENABLE_PROFILE_INFO
  5167. pnewArr->CopyArrayProfileInfo(Js::JavascriptNativeFloatArray::FromVar(baseArray));
  5168. #endif
  5169. return pnewArr;
  5170. }
  5171. else
  5172. {
  5173. JavascriptArray *pnewArr = pnewArr = scriptContext->GetLibrary()->CreateArray(len);
  5174. pnewArr->EnsureHead<Var>();
  5175. return pnewArr;
  5176. }
  5177. }
  5178. template<typename T>
  5179. void JavascriptArray::SliceHelper(JavascriptArray* pArr, JavascriptArray* pnewArr, uint32 start, uint32 newLen)
  5180. {
  5181. JS_REENTRANCY_LOCK(jsReentLock, pArr->GetScriptContext()->GetThreadContext());
  5182. SparseArraySegment<T>* headSeg = SparseArraySegment<T>::From(pArr->head);
  5183. SparseArraySegment<T>* pnewHeadSeg = SparseArraySegment<T>::From(pnewArr->head);
  5184. // Fill the newly created sliced array
  5185. CopyArray(pnewHeadSeg->elements, newLen, headSeg->elements + start, newLen);
  5186. pnewHeadSeg->length = newLen;
  5187. pnewHeadSeg->CheckLengthvsSize();
  5188. Assert(pnewHeadSeg->length <= pnewHeadSeg->size);
  5189. // Prototype lookup for missing elements
  5190. if (!pArr->HasNoMissingValues())
  5191. {
  5192. for (uint32 i = 0; i < newLen && (i + start) < pArr->length; i++)
  5193. {
  5194. // array type might be changed in the below call to DirectGetItemAtFull
  5195. // need recheck array type before checking array item [i + start]
  5196. if (pArr->IsMissingItem(i + start))
  5197. {
  5198. Var element;
  5199. pnewArr->SetHasNoMissingValues(false);
  5200. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(i + start, &element));
  5201. if (gotItem)
  5202. {
  5203. JS_REENTRANT(jsReentLock, pnewArr->SetItem(i, element, PropertyOperation_None));
  5204. }
  5205. }
  5206. }
  5207. }
  5208. #ifdef DBG
  5209. else
  5210. {
  5211. for (uint32 i = 0; i < newLen; i++)
  5212. {
  5213. AssertMsg(!SparseArraySegment<T>::IsMissingItem(&headSeg->elements[i+start]), "Array marked incorrectly as having missing value");
  5214. }
  5215. }
  5216. #endif
  5217. }
  5218. // If the creating profile data has changed, convert it to the type of array indicated
  5219. // in the profile
  5220. void JavascriptArray::GetArrayTypeAndConvert(bool* isIntArray, bool* isFloatArray)
  5221. {
  5222. if (JavascriptNativeIntArray::Is(this))
  5223. {
  5224. #if ENABLE_PROFILE_INFO
  5225. JavascriptNativeIntArray* nativeIntArray = JavascriptNativeIntArray::FromVar(this);
  5226. ArrayCallSiteInfo* info = nativeIntArray->GetArrayCallSiteInfo();
  5227. if(!info || info->IsNativeIntArray())
  5228. {
  5229. *isIntArray = true;
  5230. }
  5231. else if(info->IsNativeFloatArray())
  5232. {
  5233. JavascriptNativeIntArray::ToNativeFloatArray(nativeIntArray);
  5234. *isFloatArray = true;
  5235. }
  5236. else
  5237. {
  5238. JavascriptNativeIntArray::ToVarArray(nativeIntArray);
  5239. }
  5240. #else
  5241. *isIntArray = true;
  5242. #endif
  5243. }
  5244. else if (JavascriptNativeFloatArray::Is(this))
  5245. {
  5246. #if ENABLE_PROFILE_INFO
  5247. JavascriptNativeFloatArray* nativeFloatArray = JavascriptNativeFloatArray::FromVar(this);
  5248. ArrayCallSiteInfo* info = nativeFloatArray->GetArrayCallSiteInfo();
  5249. if(info && !info->IsNativeArray())
  5250. {
  5251. JavascriptNativeFloatArray::ToVarArray(nativeFloatArray);
  5252. }
  5253. else
  5254. {
  5255. *isFloatArray = true;
  5256. }
  5257. #else
  5258. *isFloatArray = true;
  5259. #endif
  5260. }
  5261. }
  5262. Var JavascriptArray::EntrySlice(RecyclableObject* function, CallInfo callInfo, ...)
  5263. {
  5264. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  5265. ARGUMENTS(args, callInfo);
  5266. ScriptContext* scriptContext = function->GetScriptContext();
  5267. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  5268. Assert(!(callInfo.Flags & CallFlags_New));
  5269. Var res = scriptContext->GetLibrary()->GetUndefined();
  5270. if (args.Info.Count == 0)
  5271. {
  5272. return res;
  5273. }
  5274. BigIndex length;
  5275. JavascriptArray* pArr = nullptr;
  5276. RecyclableObject* obj = nullptr;
  5277. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.slice"), &pArr, &obj, &length));
  5278. if (length.IsSmallIndex())
  5279. {
  5280. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  5281. }
  5282. Assert(pArr == nullptr || length.IsUint32Max());
  5283. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  5284. }
  5285. // Array.prototype.slice as described in ES6.0 (draft 22) Section 22.1.3.22
  5286. template <typename T>
  5287. Var JavascriptArray::SliceHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  5288. {
  5289. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  5290. JavascriptArray* newArr = nullptr;
  5291. RecyclableObject* newObj = nullptr;
  5292. bool isIntArray = false;
  5293. bool isFloatArray = false;
  5294. bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
  5295. bool isBuiltinArrayCtor = true;
  5296. T startT = 0;
  5297. T newLenT = length;
  5298. T endT = length;
  5299. #if ENABLE_COPYONACCESS_ARRAY
  5300. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pArr);
  5301. #endif
  5302. if (args.Info.Count > 1)
  5303. {
  5304. JS_REENTRANT(jsReentLock, startT = GetFromIndex(args[1], length, scriptContext));
  5305. if (args.Info.Count > 2 && JavascriptOperators::GetTypeId(args[2]) != TypeIds_Undefined)
  5306. {
  5307. JS_REENTRANT(jsReentLock, endT = GetFromIndex(args[2], length, scriptContext));
  5308. }
  5309. newLenT = endT > startT ? endT - startT : 0;
  5310. }
  5311. // 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.
  5312. if (pArr && !JavascriptArray::Is(obj))
  5313. {
  5314. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  5315. pArr = nullptr;
  5316. }
  5317. if (TypedArrayBase::IsDetachedTypedArray(obj))
  5318. {
  5319. JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("Array.prototype.slice"));
  5320. }
  5321. // If we came from Array.prototype.slice and source object is not a JavascriptArray, source could be a TypedArray
  5322. if (!isTypedArrayEntryPoint && pArr == nullptr && TypedArrayBase::Is(obj))
  5323. {
  5324. typedArrayBase = TypedArrayBase::FromVar(obj);
  5325. }
  5326. // 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
  5327. // and use it to construct the return object.
  5328. if (isTypedArrayEntryPoint)
  5329. {
  5330. JS_REENTRANT(jsReentLock,
  5331. Var constructor = JavascriptOperators::SpeciesConstructor(typedArrayBase, TypedArrayBase::GetDefaultConstructor(args[0], scriptContext), scriptContext));
  5332. isBuiltinArrayCtor = false;
  5333. AssertAndFailFast(pArr == nullptr);
  5334. Assert(JavascriptOperators::IsConstructor(constructor));
  5335. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(newLenT, scriptContext) };
  5336. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  5337. JS_REENTRANT(jsReentLock, newObj = RecyclableObject::FromVar(TypedArrayBase::TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), (uint32)newLenT, scriptContext)));
  5338. }
  5339. else if (pArr != nullptr)
  5340. {
  5341. JS_REENTRANT(jsReentLock, newObj = ArraySpeciesCreate(pArr, newLenT, scriptContext, &isIntArray, &isFloatArray, &isBuiltinArrayCtor));
  5342. }
  5343. // skip the typed array and "pure" array case, we still need to handle special arrays like es5array, remote array, and proxy of array.
  5344. else
  5345. {
  5346. JS_REENTRANT(jsReentLock, newObj = ArraySpeciesCreate(obj, newLenT, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor));
  5347. }
  5348. // If we didn't create a new object above we will create a new array here.
  5349. // This is the pre-ES6 behavior or the case of calling Array.prototype.slice with a constructor argument that is not a constructor function.
  5350. if (newObj == nullptr)
  5351. {
  5352. if (pArr)
  5353. {
  5354. pArr->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
  5355. }
  5356. if (newLenT > JavascriptArray::MaxArrayLength)
  5357. {
  5358. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  5359. }
  5360. newArr = CreateNewArrayHelper(static_cast<uint32>(newLenT), isIntArray, isFloatArray, pArr, scriptContext);
  5361. #if ENABLE_COPYONACCESS_ARRAY
  5362. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  5363. #endif
  5364. newObj = newArr;
  5365. }
  5366. else
  5367. {
  5368. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  5369. if (JavascriptArray::Is(newObj))
  5370. {
  5371. #if ENABLE_COPYONACCESS_ARRAY
  5372. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
  5373. #endif
  5374. newArr = JavascriptArray::FromVar(newObj);
  5375. }
  5376. }
  5377. uint32 start = (uint32) startT;
  5378. uint32 newLen = (uint32) newLenT;
  5379. // We at least have to have newObj as a valid object
  5380. Assert(newObj);
  5381. // Bail out early if the new object will have zero length.
  5382. if (newLen == 0)
  5383. {
  5384. return newObj;
  5385. }
  5386. // The ArraySpeciesCreate call above could have converted the source array into an ES5Array. If this happens
  5387. // we will process the array elements like an ES5Array.
  5388. if (pArr && !JavascriptArray::Is(obj))
  5389. {
  5390. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  5391. pArr = nullptr;
  5392. }
  5393. if (pArr)
  5394. {
  5395. // If we constructed a new Array object, we have some nice helpers here
  5396. if (newArr && isBuiltinArrayCtor)
  5397. {
  5398. if (JavascriptArray::IsDirectAccessArray(newArr))
  5399. {
  5400. if (((start + newLen) <= pArr->head->length) && newLen <= newArr->head->size) //Fast Path
  5401. {
  5402. if (isIntArray)
  5403. {
  5404. JS_REENTRANT(jsReentLock, SliceHelper<int32>(pArr, newArr, start, newLen));
  5405. }
  5406. else if (isFloatArray)
  5407. {
  5408. JS_REENTRANT(jsReentLock, SliceHelper<double>(pArr, newArr, start, newLen));
  5409. }
  5410. else
  5411. {
  5412. JS_REENTRANT(jsReentLock, SliceHelper<Var>(pArr, newArr, start, newLen));
  5413. }
  5414. }
  5415. else
  5416. {
  5417. if (isIntArray)
  5418. {
  5419. JS_REENTRANT(jsReentLock, CopyNativeIntArrayElements(JavascriptNativeIntArray::FromVar(newArr), 0, JavascriptNativeIntArray::FromVar(pArr), start, start + newLen));
  5420. }
  5421. else if (isFloatArray)
  5422. {
  5423. JS_REENTRANT(jsReentLock, CopyNativeFloatArrayElements(JavascriptNativeFloatArray::FromVar(newArr), 0, JavascriptNativeFloatArray::FromVar(pArr), start, start + newLen));
  5424. }
  5425. else
  5426. {
  5427. JS_REENTRANT(jsReentLock, CopyArrayElements(newArr, 0u, pArr, start, start + newLen));
  5428. }
  5429. }
  5430. }
  5431. else
  5432. {
  5433. AssertMsg(CONFIG_FLAG(ForceES5Array), "newArr can only be ES5Array when it is forced");
  5434. Var element;
  5435. for (uint32 i = 0; i < newLen; i++)
  5436. {
  5437. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(i + start, &element));
  5438. if (!gotItem)
  5439. {
  5440. continue;
  5441. }
  5442. newArr->SetItem(i, element, PropertyOperation_None);
  5443. // Side-effects in the prototype lookup may have changed the source array into an ES5Array. If this happens
  5444. // we will process the rest of the array elements like an ES5Array.
  5445. if (!JavascriptArray::Is(obj))
  5446. {
  5447. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  5448. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceObjectHelper(obj, start, i + 1, newArr, newObj, newLen, scriptContext));
  5449. }
  5450. }
  5451. }
  5452. }
  5453. else
  5454. {
  5455. // The constructed object isn't an array, we'll need to use normal object manipulation
  5456. Var element;
  5457. for (uint32 i = 0; i < newLen; i++)
  5458. {
  5459. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(i + start, &element));
  5460. if (!gotItem)
  5461. {
  5462. continue;
  5463. }
  5464. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i));
  5465. // Side-effects in the prototype lookup may have changed the source array into an ES5Array. If this happens
  5466. // we will process the rest of the array elements like an ES5Array.
  5467. if (!JavascriptArray::Is(obj))
  5468. {
  5469. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  5470. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceObjectHelper(obj, start, i + 1, newArr, newObj, newLen, scriptContext));
  5471. }
  5472. }
  5473. }
  5474. }
  5475. else if (typedArrayBase)
  5476. {
  5477. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  5478. // 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)
  5479. TypedArrayBase* newTypedArray = nullptr;
  5480. if (TypedArrayBase::Is(newObj))
  5481. {
  5482. newTypedArray = TypedArrayBase::FromVar(newObj);
  5483. }
  5484. else
  5485. {
  5486. AssertAndFailFast(newArr != nullptr);
  5487. }
  5488. Var element;
  5489. for (uint32 i = 0; i < newLen; i++)
  5490. {
  5491. // We only need to call HasItem in the case that we are called from Array.prototype.slice
  5492. if (!isTypedArrayEntryPoint && !typedArrayBase->HasItem(i + start))
  5493. {
  5494. continue;
  5495. }
  5496. element = typedArrayBase->DirectGetItem(i + start);
  5497. // The object we got back from the constructor might not be a TypedArray. In fact, it could be any object.
  5498. if (newTypedArray)
  5499. {
  5500. JS_REENTRANT(jsReentLock, newTypedArray->DirectSetItem(i, element));
  5501. }
  5502. else
  5503. {
  5504. newArr->SetItem(i, element, PropertyOperation_None);
  5505. }
  5506. }
  5507. }
  5508. else
  5509. {
  5510. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceObjectHelper(obj, start, 0u, newArr, newObj, newLen, scriptContext));;
  5511. }
  5512. if (!isTypedArrayEntryPoint)
  5513. {
  5514. JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(newLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible);
  5515. }
  5516. #ifdef VALIDATE_ARRAY
  5517. if (JavascriptArray::Is(newObj))
  5518. {
  5519. JavascriptArray::FromVar(newObj)->ValidateArray();
  5520. }
  5521. #endif
  5522. return newObj;
  5523. }
  5524. Var JavascriptArray::SliceObjectHelper(RecyclableObject* obj, uint32 sliceStart, uint32 start, JavascriptArray* newArr, RecyclableObject* newObj, uint32 newLen, ScriptContext* scriptContext)
  5525. {
  5526. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  5527. for (uint32 i = start; i < newLen; i++)
  5528. {
  5529. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, i + sliceStart));
  5530. if (hasItem)
  5531. {
  5532. JS_REENTRANT(jsReentLock, Var element = JavascriptOperators::GetItem(obj, i + sliceStart, scriptContext));
  5533. if (newArr != nullptr)
  5534. {
  5535. newArr->SetItem(i, element, PropertyOperation_None);
  5536. }
  5537. else
  5538. {
  5539. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i));
  5540. }
  5541. }
  5542. }
  5543. JS_REENTRANT(jsReentLock,
  5544. JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(newLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  5545. #ifdef VALIDATE_ARRAY
  5546. if (JavascriptArray::Is(newObj))
  5547. {
  5548. JavascriptArray::FromVar(newObj)->ValidateArray();
  5549. }
  5550. #endif
  5551. return newObj;
  5552. }
  5553. struct CompareVarsInfo
  5554. {
  5555. ScriptContext* scriptContext;
  5556. RecyclableObject* compFn;
  5557. };
  5558. int __cdecl compareVars(void* cvInfoV, const void* aRef, const void* bRef)
  5559. {
  5560. CompareVarsInfo* cvInfo=(CompareVarsInfo*)cvInfoV;
  5561. ScriptContext* requestContext=cvInfo->scriptContext;
  5562. RecyclableObject* compFn=cvInfo->compFn;
  5563. AssertMsg(*(Var*)aRef, "No null expected in sort");
  5564. AssertMsg(*(Var*)bRef, "No null expected in sort");
  5565. if (compFn != nullptr)
  5566. {
  5567. ScriptContext* scriptContext = compFn->GetScriptContext();
  5568. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  5569. CallFlags flags = CallFlags_Value;
  5570. Var undefined = scriptContext->GetLibrary()->GetUndefined();
  5571. Var retVal;
  5572. if (requestContext != scriptContext)
  5573. {
  5574. Var leftVar = CrossSite::MarshalVar(scriptContext, *(Var*)aRef);
  5575. Var rightVar = CrossSite::MarshalVar(scriptContext, *(Var*)bRef);
  5576. retVal = CALL_FUNCTION(scriptContext->GetThreadContext(), compFn, CallInfo(flags, 3), undefined, leftVar, rightVar);
  5577. }
  5578. else
  5579. {
  5580. retVal = CALL_FUNCTION(scriptContext->GetThreadContext(), compFn, CallInfo(flags, 3), undefined, *(Var*)aRef, *(Var*)bRef);
  5581. }
  5582. if (TaggedInt::Is(retVal))
  5583. {
  5584. return TaggedInt::ToInt32(retVal);
  5585. }
  5586. double dblResult;
  5587. if (JavascriptNumber::Is_NoTaggedIntCheck(retVal))
  5588. {
  5589. dblResult = JavascriptNumber::GetValue(retVal);
  5590. }
  5591. else
  5592. {
  5593. dblResult = JavascriptConversion::ToNumber_Full(retVal, scriptContext);
  5594. }
  5595. if (dblResult < 0)
  5596. {
  5597. return -1;
  5598. }
  5599. return (dblResult > 0) ? 1 : 0;
  5600. }
  5601. else
  5602. {
  5603. JavascriptString* pStr1 = JavascriptConversion::ToString(*(Var*)aRef, requestContext);
  5604. JavascriptString* pStr2 = JavascriptConversion::ToString(*(Var*)bRef, requestContext);
  5605. return JavascriptString::strcmp(pStr1, pStr2);
  5606. }
  5607. }
  5608. static void hybridSort(__inout_ecount(length) Field(Var) *elements, uint32 length, CompareVarsInfo* compareInfo)
  5609. {
  5610. // The cost of memory moves starts to be more expensive than additional comparer calls (given a simple comparer)
  5611. // for arrays of more than 512 elements.
  5612. if (length > 512)
  5613. {
  5614. qsort_s(elements, length, compareVars, compareInfo);
  5615. return;
  5616. }
  5617. for (int i = 1; i < (int)length; i++)
  5618. {
  5619. if (compareVars(compareInfo, elements + i, elements + i - 1) < 0) {
  5620. // binary search for the left-most element greater than value:
  5621. int first = 0;
  5622. int last = i - 1;
  5623. while (first <= last)
  5624. {
  5625. int middle = (first + last) / 2;
  5626. if (compareVars(compareInfo, elements + i, elements + middle) < 0)
  5627. {
  5628. last = middle - 1;
  5629. }
  5630. else
  5631. {
  5632. first = middle + 1;
  5633. }
  5634. }
  5635. // insert value right before first:
  5636. Var value = elements[i];
  5637. MoveArray(elements + first + 1, elements + first, (i - first));
  5638. elements[first] = value;
  5639. }
  5640. }
  5641. }
  5642. void JavascriptArray::Sort(RecyclableObject* compFn)
  5643. {
  5644. JS_REENTRANCY_LOCK(jsReentLock, this->GetScriptContext()->GetThreadContext());
  5645. if (length <= 1)
  5646. {
  5647. return;
  5648. }
  5649. this->EnsureHead<Var>();
  5650. ScriptContext* scriptContext = this->GetScriptContext();
  5651. Recycler* recycler = scriptContext->GetRecycler();
  5652. CompareVarsInfo cvInfo;
  5653. cvInfo.scriptContext = scriptContext;
  5654. cvInfo.compFn = compFn;
  5655. Assert(head != nullptr);
  5656. // Just dump the segment map on sort
  5657. ClearSegmentMap();
  5658. uint32 countUndefined = 0;
  5659. SparseArraySegment<Var>* startSeg = SparseArraySegment<Var>::From(head);
  5660. // Sort may have side effects on the array. Setting a dummy head so that original array is not affected
  5661. uint32 saveLength = length;
  5662. // that if compare function tries to modify the array it won't AV.
  5663. head = const_cast<SparseArraySegmentBase*>(EmptySegment);
  5664. SetFlags(DynamicObjectFlags::None);
  5665. this->InvalidateLastUsedSegment();
  5666. length = 0;
  5667. TryFinally([&]()
  5668. {
  5669. //The array is a continuous array if there is only one segment
  5670. if (startSeg->next == nullptr) // Single segment fast path
  5671. {
  5672. if (compFn != nullptr)
  5673. {
  5674. countUndefined = startSeg->RemoveUndefined(scriptContext);
  5675. #ifdef VALIDATE_ARRAY
  5676. ValidateSegment(startSeg);
  5677. #endif
  5678. JS_REENTRANT(jsReentLock, hybridSort(startSeg->elements, startSeg->length, &cvInfo));
  5679. startSeg->CheckLengthvsSize();
  5680. }
  5681. else
  5682. {
  5683. JS_REENTRANT(jsReentLock, countUndefined = sort(startSeg->elements, &startSeg->length, scriptContext));
  5684. }
  5685. head = startSeg;
  5686. }
  5687. else
  5688. {
  5689. SparseArraySegment<Var>* allElements = SparseArraySegment<Var>::AllocateSegment(recycler, 0, 0, nullptr);
  5690. SparseArraySegment<Var>* next = startSeg;
  5691. uint32 nextIndex = 0;
  5692. // copy all the elements to single segment
  5693. while (next)
  5694. {
  5695. countUndefined += next->RemoveUndefined(scriptContext);
  5696. if (next->length != 0)
  5697. {
  5698. allElements = SparseArraySegment<Var>::CopySegment(recycler, allElements, nextIndex, next, next->left, next->length);
  5699. }
  5700. next = SparseArraySegment<Var>::From(next->next);
  5701. nextIndex = allElements->length;
  5702. #ifdef VALIDATE_ARRAY
  5703. ValidateSegment(allElements);
  5704. #endif
  5705. }
  5706. if (compFn != nullptr)
  5707. {
  5708. JS_REENTRANT(jsReentLock, hybridSort(allElements->elements, allElements->length, &cvInfo));
  5709. }
  5710. else
  5711. {
  5712. JS_REENTRANT(jsReentLock, sort(allElements->elements, &allElements->length, scriptContext));
  5713. allElements->CheckLengthvsSize();
  5714. }
  5715. head = allElements;
  5716. head->next = nullptr;
  5717. }
  5718. },
  5719. [&](bool hasException)
  5720. {
  5721. length = saveLength;
  5722. ClearSegmentMap(); // Dump the segmentMap again in case user compare function rebuilds it
  5723. if (hasException)
  5724. {
  5725. head = startSeg;
  5726. this->InvalidateLastUsedSegment();
  5727. }
  5728. });
  5729. #if DEBUG
  5730. {
  5731. uint32 countNull = 0;
  5732. uint32 index = head->length - 1;
  5733. while (countNull < head->length)
  5734. {
  5735. if (SparseArraySegment<Var>::From(head)->elements[index] != NULL)
  5736. {
  5737. break;
  5738. }
  5739. index--;
  5740. countNull++;
  5741. }
  5742. AssertMsg(countNull == 0, "No null expected at the end");
  5743. }
  5744. #endif
  5745. if (countUndefined != 0)
  5746. {
  5747. // fill undefined at the end
  5748. uint32 newLength = head->length + countUndefined;
  5749. if (newLength > head->size)
  5750. {
  5751. head = SparseArraySegment<Var>::From(head)->GrowByMin(recycler, newLength - head->size);
  5752. }
  5753. Var undefined = scriptContext->GetLibrary()->GetUndefined();
  5754. for (uint32 i = head->length; i < newLength; i++)
  5755. {
  5756. SparseArraySegment<Var>::From(head)->elements[i] = undefined;
  5757. }
  5758. head->length = newLength;
  5759. head->CheckLengthvsSize();
  5760. }
  5761. SetHasNoMissingValues();
  5762. this->InvalidateLastUsedSegment();
  5763. #ifdef VALIDATE_ARRAY
  5764. ValidateArray();
  5765. #endif
  5766. return;
  5767. }
  5768. uint32 JavascriptArray::sort(__inout_ecount(*len) Field(Var) *orig, uint32 *len, ScriptContext *scriptContext)
  5769. {
  5770. uint32 count = 0, countUndefined = 0;
  5771. Element *elements = RecyclerNewArrayZ(scriptContext->GetRecycler(), Element, *len);
  5772. RecyclableObject *undefined = scriptContext->GetLibrary()->GetUndefined();
  5773. //
  5774. // Create the Elements array
  5775. //
  5776. for (uint32 i = 0; i < *len; ++i)
  5777. {
  5778. if (!SparseArraySegment<Var>::IsMissingItem(&orig[i]))
  5779. {
  5780. if (!JavascriptOperators::IsUndefinedObject(orig[i], undefined))
  5781. {
  5782. elements[count].Value = orig[i];
  5783. elements[count].StringValue = JavascriptConversion::ToString(orig[i], scriptContext);
  5784. count++;
  5785. }
  5786. else
  5787. {
  5788. countUndefined++;
  5789. }
  5790. }
  5791. }
  5792. if (count > 0)
  5793. {
  5794. SortElements(elements, 0, count - 1);
  5795. for (uint32 i = 0; i < count; ++i)
  5796. {
  5797. orig[i] = elements[i].Value;
  5798. }
  5799. }
  5800. for (uint32 i = count + countUndefined; i < *len; ++i)
  5801. {
  5802. orig[i] = SparseArraySegment<Var>::GetMissingItem();
  5803. }
  5804. *len = count; // set the correct length
  5805. return countUndefined;
  5806. }
  5807. int __cdecl JavascriptArray::CompareElements(void* context, const void* elem1, const void* elem2)
  5808. {
  5809. const Element* element1 = static_cast<const Element*>(elem1);
  5810. const Element* element2 = static_cast<const Element*>(elem2);
  5811. Assert(element1 != NULL);
  5812. Assert(element2 != NULL);
  5813. return JavascriptString::strcmp(element1->StringValue, element2->StringValue);
  5814. }
  5815. void JavascriptArray::SortElements(Element* elements, uint32 left, uint32 right)
  5816. {
  5817. // Note: use write barrier policy of Field(Var)
  5818. qsort_s<Element, Field(Var)>(elements, right - left + 1, CompareElements, this);
  5819. }
  5820. Var JavascriptArray::EntrySort(RecyclableObject* function, CallInfo callInfo, ...)
  5821. {
  5822. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  5823. ARGUMENTS(args, callInfo);
  5824. ScriptContext* scriptContext = function->GetScriptContext();
  5825. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  5826. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.sort"));
  5827. Assert(!(callInfo.Flags & CallFlags_New));
  5828. AssertMsg(args.Info.Count >= 1, "Should have at least one argument");
  5829. RecyclableObject* compFn = NULL;
  5830. if (args.Info.Count > 1)
  5831. {
  5832. if (JavascriptConversion::IsCallable(args[1]))
  5833. {
  5834. compFn = RecyclableObject::FromVar(args[1]);
  5835. }
  5836. else
  5837. {
  5838. TypeId typeId = JavascriptOperators::GetTypeId(args[1]);
  5839. // Use default comparer:
  5840. // - In ES5 mode if the argument is undefined.
  5841. bool useDefaultComparer = typeId == TypeIds_Undefined;
  5842. if (!useDefaultComparer)
  5843. {
  5844. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedInternalObject, _u("Array.prototype.sort"));
  5845. }
  5846. }
  5847. }
  5848. if (JavascriptArray::Is(args[0]))
  5849. {
  5850. #if ENABLE_COPYONACCESS_ARRAY
  5851. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
  5852. #endif
  5853. JavascriptArray *arr = JavascriptArray::FromVar(args[0]);
  5854. if (arr->length <= 1)
  5855. {
  5856. return args[0];
  5857. }
  5858. if(arr->IsFillFromPrototypes())
  5859. {
  5860. JS_REENTRANT(jsReentLock, arr->FillFromPrototypes(0, arr->length)); // We need find all missing value from [[proto]] object
  5861. }
  5862. // Maintain nativity of the array only for the following cases (To favor inplace conversions - keeps the conversion cost less):
  5863. // - int cases for X86 and
  5864. // - FloatArray for AMD64
  5865. // We convert the entire array back and forth once here O(n), rather than doing the costly conversion down the call stack which is O(nlogn)
  5866. #if defined(_M_X64_OR_ARM64)
  5867. if(compFn && JavascriptNativeFloatArray::Is(arr))
  5868. {
  5869. arr = JavascriptNativeFloatArray::ConvertToVarArray((JavascriptNativeFloatArray*)arr);
  5870. JS_REENTRANT(jsReentLock, arr->Sort(compFn));
  5871. arr = arr->ConvertToNativeArrayInPlace<JavascriptNativeFloatArray, double>(arr);
  5872. }
  5873. else
  5874. {
  5875. EnsureNonNativeArray(arr);
  5876. JS_REENTRANT(jsReentLock, arr->Sort(compFn));
  5877. }
  5878. #else
  5879. if(compFn && JavascriptNativeIntArray::Is(arr))
  5880. {
  5881. //EnsureNonNativeArray(arr);
  5882. arr = JavascriptNativeIntArray::ConvertToVarArray((JavascriptNativeIntArray*)arr);
  5883. JS_REENTRANT(jsReentLock, arr->Sort(compFn));
  5884. arr = arr->ConvertToNativeArrayInPlace<JavascriptNativeIntArray, int32>(arr);
  5885. }
  5886. else
  5887. {
  5888. EnsureNonNativeArray(arr);
  5889. JS_REENTRANT(jsReentLock, arr->Sort(compFn));
  5890. }
  5891. #endif
  5892. }
  5893. else
  5894. {
  5895. RecyclableObject* pObj = nullptr;
  5896. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &pObj))
  5897. {
  5898. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.sort"));
  5899. }
  5900. JS_REENTRANT(jsReentLock,
  5901. uint32 len = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(pObj, scriptContext), scriptContext));
  5902. JavascriptArray* sortArray = scriptContext->GetLibrary()->CreateArray(len);
  5903. sortArray->EnsureHead<Var>();
  5904. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.sort"));
  5905. BEGIN_TEMP_ALLOCATOR(tempAlloc, scriptContext, _u("Runtime"))
  5906. {
  5907. JsUtil::List<uint32, ArenaAllocator>* indexList = JsUtil::List<uint32, ArenaAllocator>::New(tempAlloc);
  5908. for (uint32 i = 0; i < len; i++)
  5909. {
  5910. Var item;
  5911. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(pObj, i, &item, scriptContext));
  5912. if (gotItem)
  5913. {
  5914. indexList->Add(i);
  5915. sortArray->DirectSetItemAt(i, item);
  5916. }
  5917. }
  5918. if (indexList->Count() > 0)
  5919. {
  5920. if (sortArray->length > 1)
  5921. {
  5922. sortArray->FillFromPrototypes(0, sortArray->length); // We need find all missing value from [[proto]] object
  5923. }
  5924. JS_REENTRANT(jsReentLock, sortArray->Sort(compFn));
  5925. uint32 removeIndex = sortArray->head->length;
  5926. for (uint32 i = 0; i < removeIndex; i++)
  5927. {
  5928. AssertMsg(!SparseArraySegment<Var>::IsMissingItem(&SparseArraySegment<Var>::From(sortArray->head)->elements[i]), "No gaps expected in sorted array");
  5929. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(pObj, pObj, i, SparseArraySegment<Var>::From(sortArray->head)->elements[i], scriptContext)));
  5930. }
  5931. for (int i = 0; i < indexList->Count(); i++)
  5932. {
  5933. uint32 value = indexList->Item(i);
  5934. if (value >= removeIndex)
  5935. {
  5936. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure((JavascriptOperators::DeleteItem(pObj, value))));
  5937. }
  5938. }
  5939. }
  5940. }
  5941. END_TEMP_ALLOCATOR(tempAlloc, scriptContext);
  5942. }
  5943. return args[0];
  5944. }
  5945. Var JavascriptArray::EntrySplice(RecyclableObject* function, CallInfo callInfo, ...)
  5946. {
  5947. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  5948. ARGUMENTS(args, callInfo);
  5949. ScriptContext* scriptContext = function->GetScriptContext();
  5950. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  5951. Assert(!(callInfo.Flags & CallFlags_New));
  5952. AssertMsg(args.Info.Count >= 1, "Should have at least one argument");
  5953. JavascriptArray* pArr = 0;
  5954. RecyclableObject* pObj = 0;
  5955. uint64 start = 0u;
  5956. uint64 deleteLen = 0u;
  5957. uint64 length = 0u;
  5958. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.splice"), &pArr, &pObj, &length));
  5959. switch (args.Info.Count)
  5960. {
  5961. case 1:
  5962. start = length;
  5963. deleteLen = 0u;
  5964. break;
  5965. case 2:
  5966. JS_REENTRANT(jsReentLock, start = GetFromIndex(args[1], length, scriptContext));
  5967. deleteLen = length - start;
  5968. break;
  5969. default:
  5970. JS_REENTRANT(jsReentLock, start = GetFromIndex(args[1], length, scriptContext),
  5971. deleteLen = GetFromIndex(args[2], (length - start), scriptContext, false));
  5972. break;
  5973. }
  5974. // 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.
  5975. if (pArr && !JavascriptArray::Is(pObj))
  5976. {
  5977. AssertOrFailFastMsg(ES5Array::Is(pObj), "The array should have been converted to an ES5Array");
  5978. pArr = nullptr;
  5979. }
  5980. Var* insertArgs = args.Info.Count > 3 ? &args.Values[3] : nullptr;
  5981. uint32 insertLen = args.Info.Count > 3 ? args.Info.Count - 3 : 0;
  5982. if (pArr != nullptr)
  5983. {
  5984. // Since we get the length from an array and that cannot be more than uint32.
  5985. _Analysis_assume_(length <= UINT_MAX);
  5986. JS_REENTRANT_UNLOCK(jsReentLock,
  5987. return TryArraySplice(pArr, (uint32)start, (uint32)length, (uint32)deleteLen, insertArgs, insertLen, scriptContext));
  5988. }
  5989. uint64 newLen = (length - deleteLen) + insertLen;
  5990. if (newLen > UINT_MAX || length > UINT_MAX || (length + insertLen) > UINT_MAX)
  5991. {
  5992. JS_REENTRANT_UNLOCK(jsReentLock,
  5993. return ObjectSpliceHelper<uint64>(pObj, length, start, deleteLen, (Var*)insertArgs, insertLen, scriptContext, nullptr));
  5994. }
  5995. else
  5996. {
  5997. JS_REENTRANT_UNLOCK(jsReentLock,
  5998. return ObjectSpliceHelper<uint32>(pObj, (uint32)length, (uint32)start, (uint32)deleteLen, (Var*)insertArgs, insertLen, scriptContext, nullptr));
  5999. }
  6000. }
  6001. inline BOOL JavascriptArray::IsSingleSegmentArray() const
  6002. {
  6003. return nullptr == head->next;
  6004. }
  6005. template<typename T>
  6006. void JavascriptArray::ArraySegmentSpliceHelper(JavascriptArray *pnewArr, SparseArraySegment<T> *seg, SparseArraySegment<T> **prev,
  6007. uint32 start, uint32 deleteLen, Var* insertArgs, uint32 insertLen, Recycler *recycler)
  6008. {
  6009. // book keeping variables
  6010. uint32 relativeStart = start - seg->left; // This will be different from start when head->left is non zero -
  6011. //(Missing elements at the beginning)
  6012. uint32 headDeleteLen = min(start + deleteLen , seg->left + seg->length) - start; // actual number of elements to delete in
  6013. // head if deleteLen overflows the length of head
  6014. uint32 newHeadLen = seg->length - headDeleteLen + insertLen; // new length of the head after splice
  6015. // Save the deleted elements
  6016. if (headDeleteLen != 0)
  6017. {
  6018. pnewArr->InvalidateLastUsedSegment();
  6019. pnewArr->head = SparseArraySegment<T>::CopySegment(recycler, SparseArraySegment<T>::From(pnewArr->head), 0, seg, start, headDeleteLen);
  6020. }
  6021. if (newHeadLen != 0)
  6022. {
  6023. if (seg->size < newHeadLen)
  6024. {
  6025. if (seg->next)
  6026. {
  6027. // If we have "next", require that we haven't adjusted next segments left yet.
  6028. seg = seg->GrowByMinMax(recycler, newHeadLen - seg->size, seg->next->left - deleteLen + insertLen - seg->left - seg->size);
  6029. }
  6030. else
  6031. {
  6032. seg = seg->GrowByMin(recycler, newHeadLen - seg->size);
  6033. }
  6034. #ifdef VALIDATE_ARRAY
  6035. ValidateSegment(seg);
  6036. #endif
  6037. }
  6038. // Move the elements if necessary
  6039. if (headDeleteLen != insertLen)
  6040. {
  6041. uint32 noElementsToMove = seg->length - (relativeStart + headDeleteLen);
  6042. MoveArray(seg->elements + relativeStart + insertLen,
  6043. seg->elements + relativeStart + headDeleteLen,
  6044. noElementsToMove);
  6045. if (newHeadLen < seg->length) // truncate if necessary
  6046. {
  6047. seg->Truncate(seg->left + newHeadLen); // set end elements to null so that when we introduce null elements we are safe
  6048. }
  6049. seg->length = newHeadLen;
  6050. seg->CheckLengthvsSize();
  6051. }
  6052. // Copy the new elements
  6053. if (insertLen > 0)
  6054. {
  6055. Assert(!VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(pnewArr) &&
  6056. !VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(pnewArr));
  6057. // inserted elements starts at argument 3 of splice(start, deleteNumber, insertelem1, insertelem2, insertelem3, ...);
  6058. CopyArray(seg->elements + relativeStart, insertLen,
  6059. reinterpret_cast<const T*>(insertArgs), insertLen);
  6060. }
  6061. *prev = seg;
  6062. }
  6063. else
  6064. {
  6065. *prev = SparseArraySegment<T>::From(seg->next);
  6066. }
  6067. }
  6068. template<typename T>
  6069. void JavascriptArray::ArraySpliceHelper(JavascriptArray* pnewArr, JavascriptArray* pArr, uint32 start, uint32 deleteLen, Var* insertArgs, uint32 insertLen, ScriptContext *scriptContext)
  6070. {
  6071. // Skip pnewArr->EnsureHead(): we don't use existing segment at all.
  6072. Recycler *recycler = scriptContext->GetRecycler();
  6073. Field(SparseArraySegmentBase*)* prevSeg = &pArr->head; // holds the next pointer of previous
  6074. Field(SparseArraySegmentBase*)* prevPrevSeg = &pArr->head; // this holds the previous pointer to prevSeg dirty trick.
  6075. SparseArraySegmentBase* savePrev = nullptr;
  6076. Assert(pArr->head); // We should never have a null head.
  6077. pArr->EnsureHead<T>();
  6078. SparseArraySegment<T>* startSeg = SparseArraySegment<T>::From(pArr->head);
  6079. const uint32 limit = start + deleteLen;
  6080. uint32 rightLimit;
  6081. if (UInt32Math::Add(startSeg->left, startSeg->size, &rightLimit))
  6082. {
  6083. rightLimit = JavascriptArray::MaxArrayLength;
  6084. }
  6085. // Find out the segment to start delete
  6086. while (startSeg && (rightLimit <= start))
  6087. {
  6088. savePrev = startSeg;
  6089. prevPrevSeg = prevSeg;
  6090. prevSeg = &startSeg->next;
  6091. startSeg = SparseArraySegment<T>::From(startSeg->next);
  6092. if (startSeg)
  6093. {
  6094. if (UInt32Math::Add(startSeg->left, startSeg->size, &rightLimit))
  6095. {
  6096. rightLimit = JavascriptArray::MaxArrayLength;
  6097. }
  6098. }
  6099. }
  6100. // handle inlined segment
  6101. SparseArraySegmentBase* inlineHeadSegment = nullptr;
  6102. bool hasInlineSegment = false;
  6103. // The following if else set is used to determine whether a shallow or hard copy is needed
  6104. if (JavascriptNativeArray::Is(pArr))
  6105. {
  6106. if (JavascriptNativeFloatArray::Is(pArr))
  6107. {
  6108. inlineHeadSegment = DetermineInlineHeadSegmentPointer<JavascriptNativeFloatArray, 0, true>((JavascriptNativeFloatArray*)pArr);
  6109. }
  6110. else if (JavascriptNativeIntArray::Is(pArr))
  6111. {
  6112. inlineHeadSegment = DetermineInlineHeadSegmentPointer<JavascriptNativeIntArray, 0, true>((JavascriptNativeIntArray*)pArr);
  6113. }
  6114. Assert(inlineHeadSegment);
  6115. hasInlineSegment = (startSeg == (SparseArraySegment<T>*)inlineHeadSegment);
  6116. }
  6117. else
  6118. {
  6119. // This will result in false positives. It is used because DetermineInlineHeadSegmentPointer
  6120. // does not handle Arrays that change type e.g. from JavascriptNativeIntArray to JavascriptArray
  6121. // This conversion in particular is problematic because JavascriptNativeIntArray is larger than JavascriptArray
  6122. // so the returned head segment ptr never equals pArr->head. So we will default to using this and deal with
  6123. // false positives. It is better than always doing a hard copy.
  6124. hasInlineSegment = HasInlineHeadSegment(pArr->head->length);
  6125. }
  6126. if (startSeg)
  6127. {
  6128. // Delete Phase
  6129. if (startSeg->left <= start && (startSeg->left + startSeg->length) >= limit)
  6130. {
  6131. // All splice happens in one segment.
  6132. SparseArraySegmentBase *nextSeg = startSeg->next;
  6133. // Splice the segment first, which might OOM throw but the array would be intact.
  6134. JavascriptArray::ArraySegmentSpliceHelper(pnewArr, (SparseArraySegment<T>*)startSeg, (SparseArraySegment<T>**)prevSeg, start, deleteLen, insertArgs, insertLen, recycler);
  6135. while (nextSeg)
  6136. {
  6137. // adjust next segments left
  6138. nextSeg->left = nextSeg->left - deleteLen + insertLen;
  6139. if (nextSeg->next == nullptr)
  6140. {
  6141. nextSeg->EnsureSizeInBound();
  6142. }
  6143. nextSeg = nextSeg->next;
  6144. }
  6145. if (*prevSeg)
  6146. {
  6147. (*prevSeg)->EnsureSizeInBound();
  6148. }
  6149. return;
  6150. }
  6151. else
  6152. {
  6153. SparseArraySegment<T>* newHeadSeg = nullptr; // pnewArr->head is null
  6154. Field(SparseArraySegmentBase*)* prevNewHeadSeg = &pnewArr->head;
  6155. // delete till deleteLen and reuse segments for new array if it is possible.
  6156. // 3 steps -
  6157. //1. delete 1st segment (which may be partial delete)
  6158. // 2. delete next n complete segments
  6159. // 3. delete last segment (which again may be partial delete)
  6160. // Step (1) -- WOOB 1116297: When left >= start, step (1) is skipped, resulting in pNewArr->head->left != 0. We need to touch up pNewArr.
  6161. if (startSeg->left < start)
  6162. {
  6163. if (start < startSeg->left + startSeg->length)
  6164. {
  6165. uint32 headDeleteLen = startSeg->left + startSeg->length - start;
  6166. if (startSeg->next)
  6167. {
  6168. // We know the new segment will have a next segment, so allocate it as non-leaf.
  6169. newHeadSeg = SparseArraySegment<T>::template AllocateSegmentImpl<false>(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
  6170. }
  6171. else
  6172. {
  6173. newHeadSeg = SparseArraySegment<T>::AllocateSegment(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
  6174. }
  6175. newHeadSeg = SparseArraySegment<T>::CopySegment(recycler, newHeadSeg, 0, startSeg, start, headDeleteLen);
  6176. newHeadSeg->next = nullptr;
  6177. *prevNewHeadSeg = newHeadSeg;
  6178. prevNewHeadSeg = &newHeadSeg->next;
  6179. startSeg->Truncate(start);
  6180. }
  6181. savePrev = startSeg;
  6182. prevPrevSeg = prevSeg;
  6183. prevSeg = &startSeg->next;
  6184. startSeg = SparseArraySegment<T>::From(startSeg->next);
  6185. }
  6186. // Step (2) first we should do a hard copy if we have an inline head Segment
  6187. else if (hasInlineSegment && nullptr != startSeg)
  6188. {
  6189. // start should be in between left and left + length
  6190. if (startSeg->left <= start && start < startSeg->left + startSeg->length)
  6191. {
  6192. uint32 headDeleteLen = startSeg->left + startSeg->length - start;
  6193. if (startSeg->next)
  6194. {
  6195. // We know the new segment will have a next segment, so allocate it as non-leaf.
  6196. newHeadSeg = SparseArraySegment<T>::template AllocateSegmentImpl<false>(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
  6197. }
  6198. else
  6199. {
  6200. newHeadSeg = SparseArraySegment<T>::AllocateSegment(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
  6201. }
  6202. newHeadSeg = SparseArraySegment<T>::CopySegment(recycler, newHeadSeg, 0, startSeg, start, headDeleteLen);
  6203. *prevNewHeadSeg = newHeadSeg;
  6204. prevNewHeadSeg = &newHeadSeg->next;
  6205. // Remove the entire segment from the original array
  6206. *prevSeg = startSeg->next;
  6207. startSeg = SparseArraySegment<T>::From(startSeg->next);
  6208. }
  6209. // if we have an inline head segment with 0 elements, remove it
  6210. else if (startSeg->left == 0 && startSeg->length == 0)
  6211. {
  6212. Assert(startSeg->size != 0);
  6213. *prevSeg = startSeg->next;
  6214. startSeg = SparseArraySegment<T>::From(startSeg->next);
  6215. }
  6216. }
  6217. // Step (2) proper
  6218. SparseArraySegmentBase *temp = nullptr;
  6219. while (startSeg && (startSeg->left + startSeg->length) <= limit)
  6220. {
  6221. temp = startSeg->next;
  6222. // move that entire segment to new array
  6223. startSeg->left = startSeg->left - start;
  6224. startSeg->next = nullptr;
  6225. *prevNewHeadSeg = startSeg;
  6226. prevNewHeadSeg = &startSeg->next;
  6227. // Remove the entire segment from the original array
  6228. *prevSeg = temp;
  6229. startSeg = (SparseArraySegment<T>*)temp;
  6230. }
  6231. // Step(2) above could delete the original head segment entirely, causing current head not
  6232. // starting from 0. Then if any of the following throw, we have a corrupted array. Need
  6233. // protection here.
  6234. bool dummyHeadNodeInserted = false;
  6235. if (!savePrev && (!startSeg || startSeg->left != 0))
  6236. {
  6237. Assert(pArr->head == startSeg);
  6238. pArr->EnsureHeadStartsFromZero<T>(recycler);
  6239. Assert(pArr->head && pArr->head->next == startSeg);
  6240. savePrev = pArr->head;
  6241. prevPrevSeg = prevSeg;
  6242. prevSeg = &pArr->head->next;
  6243. dummyHeadNodeInserted = true;
  6244. }
  6245. // Step (3)
  6246. if (startSeg && (startSeg->left < limit))
  6247. {
  6248. // copy the first part of the last segment to be deleted to new array
  6249. uint32 headDeleteLen = start + deleteLen - startSeg->left ;
  6250. newHeadSeg = SparseArraySegment<T>::AllocateSegment(recycler, startSeg->left - start, headDeleteLen, (SparseArraySegmentBase *)nullptr);
  6251. newHeadSeg = SparseArraySegment<T>::CopySegment(recycler, newHeadSeg, startSeg->left - start, startSeg, startSeg->left, headDeleteLen);
  6252. newHeadSeg->next = nullptr;
  6253. *prevNewHeadSeg = newHeadSeg;
  6254. prevNewHeadSeg = &newHeadSeg->next;
  6255. // move the last segment
  6256. MoveArray(startSeg->elements, startSeg->elements + headDeleteLen, startSeg->length - headDeleteLen);
  6257. startSeg->left = startSeg->left + headDeleteLen; // We are moving the left ahead to point to the right index
  6258. startSeg->length = startSeg->length - headDeleteLen;
  6259. startSeg->CheckLengthvsSize();
  6260. startSeg->Truncate(startSeg->left + startSeg->length);
  6261. startSeg->EnsureSizeInBound(); // Just truncated, size might exceed next.left
  6262. }
  6263. if (startSeg && ((startSeg->left - deleteLen + insertLen) == 0) && dummyHeadNodeInserted)
  6264. {
  6265. Assert(start + insertLen == 0);
  6266. // Remove the dummy head node to preserve array consistency.
  6267. pArr->head = startSeg;
  6268. savePrev = nullptr;
  6269. prevSeg = &pArr->head;
  6270. }
  6271. while (startSeg)
  6272. {
  6273. startSeg->left = startSeg->left - deleteLen + insertLen ;
  6274. if (startSeg->next == nullptr)
  6275. {
  6276. startSeg->EnsureSizeInBound();
  6277. }
  6278. startSeg = SparseArraySegment<T>::From(startSeg->next);
  6279. }
  6280. }
  6281. }
  6282. // The size of pnewArr head allocated in above step 1 might exceed next.left concatenated in step 2/3.
  6283. pnewArr->head->EnsureSizeInBound();
  6284. if (savePrev)
  6285. {
  6286. savePrev->EnsureSizeInBound();
  6287. }
  6288. // insert elements
  6289. if (insertLen > 0)
  6290. {
  6291. Assert(!JavascriptNativeIntArray::Is(pArr) && !JavascriptNativeFloatArray::Is(pArr));
  6292. // InsertPhase
  6293. SparseArraySegment<T> *segInsert = nullptr;
  6294. // see if we are just about the right of the previous segment
  6295. Assert(!savePrev || savePrev->left <= start);
  6296. if (savePrev && (start - savePrev->left < savePrev->size))
  6297. {
  6298. segInsert = (SparseArraySegment<T>*)savePrev;
  6299. uint32 spaceLeft = segInsert->size - (start - segInsert->left);
  6300. if(spaceLeft < insertLen)
  6301. {
  6302. if (!segInsert->next)
  6303. {
  6304. segInsert = segInsert->GrowByMin(recycler, insertLen - spaceLeft);
  6305. }
  6306. else
  6307. {
  6308. segInsert = segInsert->GrowByMinMax(recycler, insertLen - spaceLeft, segInsert->next->left - segInsert->left - segInsert->size);
  6309. }
  6310. }
  6311. *prevPrevSeg = segInsert;
  6312. segInsert->length = start + insertLen - segInsert->left;
  6313. segInsert->CheckLengthvsSize();
  6314. }
  6315. else
  6316. {
  6317. segInsert = SparseArraySegment<T>::AllocateSegment(recycler, start, insertLen, *prevSeg);
  6318. segInsert->next = *prevSeg;
  6319. *prevSeg = segInsert;
  6320. savePrev = segInsert;
  6321. }
  6322. uint32 relativeStart = start - segInsert->left;
  6323. // inserted elements starts at argument 3 of splice(start, deleteNumber, insertelem1, insertelem2, insertelem3, ...);
  6324. CopyArray(segInsert->elements + relativeStart, insertLen,
  6325. reinterpret_cast<const T*>(insertArgs), insertLen);
  6326. }
  6327. }
  6328. Var JavascriptArray::TryArraySplice(JavascriptArray* pArr, uint32 start, uint32 len, uint32 deleteLen,
  6329. Var* insertArgs, uint32 insertLen, ScriptContext *scriptContext)
  6330. {
  6331. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6332. Assert(pArr != nullptr);
  6333. RecyclableObject* newObj = nullptr;
  6334. Recycler *recycler = scriptContext->GetRecycler();
  6335. ::Math::RecordOverflowPolicy newLenOverflow;
  6336. uint32 newLen = UInt32Math::Add(len - deleteLen, insertLen, newLenOverflow); // new length of the array after splice
  6337. // If we have missing values then convert to not native array for now
  6338. // In future, we could support this scenario.
  6339. if (deleteLen == insertLen)
  6340. {
  6341. JS_REENTRANT(jsReentLock, pArr->FillFromPrototypes(start, start + deleteLen));
  6342. }
  6343. else if (len)
  6344. {
  6345. JS_REENTRANT(jsReentLock, pArr->FillFromPrototypes(start, len));
  6346. }
  6347. //
  6348. // If newLen overflowed, pre-process to prevent pushing sparse array segments or elements out of
  6349. // max array length, which would result in tons of index overflow and difficult to fix.
  6350. //
  6351. if (newLenOverflow.HasOverflowed())
  6352. {
  6353. pArr = EnsureNonNativeArray(pArr);
  6354. BigIndex dstIndex = MaxArrayLength;
  6355. uint32 maxInsertLen = MaxArrayLength - start;
  6356. if (insertLen > maxInsertLen)
  6357. {
  6358. // Copy overflowing insertArgs to properties
  6359. for (uint32 i = maxInsertLen; i < insertLen; i++)
  6360. {
  6361. pArr->DirectSetItemAt(dstIndex, insertArgs[i]);
  6362. ++dstIndex;
  6363. }
  6364. insertLen = maxInsertLen; // update
  6365. // Truncate elements on the right to properties
  6366. if (start + deleteLen < len)
  6367. {
  6368. pArr->TruncateToProperties(dstIndex, start + deleteLen);
  6369. }
  6370. }
  6371. else
  6372. {
  6373. // Truncate would-overflow elements to properties
  6374. pArr->TruncateToProperties(dstIndex, MaxArrayLength - insertLen + deleteLen);
  6375. }
  6376. len = pArr->length; // update
  6377. newLen = len - deleteLen + insertLen;
  6378. Assert(newLen == MaxArrayLength);
  6379. }
  6380. if (insertArgs)
  6381. {
  6382. pArr = EnsureNonNativeArray(pArr);
  6383. }
  6384. bool isIntArray = false;
  6385. bool isFloatArray = false;
  6386. bool isBuiltinArrayCtor = true;
  6387. JavascriptArray *newArr = nullptr;
  6388. // Just dump the segment map on splice (before any possible allocation and throw)
  6389. pArr->ClearSegmentMap();
  6390. // If the source object is an Array exotic object (Array.isArray) we should try to load the constructor property
  6391. // and use it to construct the return object.
  6392. JS_REENTRANT(jsReentLock, newObj = ArraySpeciesCreate(pArr, deleteLen, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor));
  6393. if (newObj != nullptr)
  6394. {
  6395. pArr = EnsureNonNativeArray(pArr);
  6396. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  6397. if (JavascriptArray::Is(newObj))
  6398. {
  6399. #if ENABLE_COPYONACCESS_ARRAY
  6400. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
  6401. #endif
  6402. newArr = JavascriptArray::FromVar(newObj);
  6403. }
  6404. }
  6405. else
  6406. // This is the ES5 case, pArr['constructor'] doesn't exist, or pArr['constructor'] is the builtin Array constructor
  6407. {
  6408. pArr->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
  6409. newArr = CreateNewArrayHelper(deleteLen, isIntArray, isFloatArray, pArr, scriptContext);
  6410. #if ENABLE_COPYONACCESS_ARRAY
  6411. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  6412. #endif
  6413. }
  6414. // If return object is a JavascriptArray, we can use all the array splice helpers
  6415. if (newArr && isBuiltinArrayCtor && len == pArr->length)
  6416. {
  6417. // Array has a single segment (need not start at 0) and splice start lies in the range
  6418. // of that segment we optimize splice - Fast path.
  6419. if (pArr->IsSingleSegmentArray() && pArr->head->HasIndex(start))
  6420. {
  6421. if (isIntArray)
  6422. {
  6423. ArraySegmentSpliceHelper<int32>(newArr, SparseArraySegment<int32>::From(pArr->head), (SparseArraySegment<int32>**)&pArr->head, start, deleteLen, insertArgs, insertLen, recycler);
  6424. }
  6425. else if (isFloatArray)
  6426. {
  6427. ArraySegmentSpliceHelper<double>(newArr, SparseArraySegment<double>::From(pArr->head), (SparseArraySegment<double>**)&pArr->head, start, deleteLen, insertArgs, insertLen, recycler);
  6428. }
  6429. else
  6430. {
  6431. ArraySegmentSpliceHelper<Var>(newArr, SparseArraySegment<Var>::From(pArr->head), (SparseArraySegment<Var>**)&pArr->head, start, deleteLen, insertArgs, insertLen, recycler);
  6432. }
  6433. // Since the start index is within the bounds of the original array's head segment, it will not acquire any new
  6434. // missing values. If the original array had missing values in the head segment, some of them may have been
  6435. // copied into the array that will be returned; otherwise, the array that is returned will also not have any
  6436. // missing values.
  6437. newArr->SetHasNoMissingValues(pArr->HasNoMissingValues());
  6438. }
  6439. else
  6440. {
  6441. if (isIntArray)
  6442. {
  6443. ArraySpliceHelper<int32>(newArr, pArr, start, deleteLen, insertArgs, insertLen, scriptContext);
  6444. }
  6445. else if (isFloatArray)
  6446. {
  6447. ArraySpliceHelper<double>(newArr, pArr, start, deleteLen, insertArgs, insertLen, scriptContext);
  6448. }
  6449. else
  6450. {
  6451. ArraySpliceHelper<Var>(newArr, pArr, start, deleteLen, insertArgs, insertLen, scriptContext);
  6452. }
  6453. // This function currently does not track missing values in the head segment if there are multiple segments
  6454. pArr->SetHasNoMissingValues(false);
  6455. newArr->SetHasNoMissingValues(false);
  6456. }
  6457. if (isIntArray)
  6458. {
  6459. pArr->EnsureHeadStartsFromZero<int32>(recycler);
  6460. newArr->EnsureHeadStartsFromZero<int32>(recycler);
  6461. }
  6462. else if (isFloatArray)
  6463. {
  6464. pArr->EnsureHeadStartsFromZero<double>(recycler);
  6465. newArr->EnsureHeadStartsFromZero<double>(recycler);
  6466. }
  6467. else
  6468. {
  6469. pArr->EnsureHeadStartsFromZero<Var>(recycler);
  6470. newArr->EnsureHeadStartsFromZero<Var>(recycler);
  6471. }
  6472. pArr->InvalidateLastUsedSegment();
  6473. // it is possible for valueOf accessors for the start or deleteLen
  6474. // arguments to modify the size of the array. Since the resulting size of the array
  6475. // is based on the cached value of length, this might lead to us having to trim
  6476. // excess array segments at the end of the splice operation, which SetLength() will do.
  6477. // However, this is also slower than performing the simple length assignment, so we only
  6478. // do it if we can detect the array length changing.
  6479. if (pArr->length != len)
  6480. {
  6481. pArr->SetLength(newLen);
  6482. }
  6483. else
  6484. {
  6485. pArr->length = newLen;
  6486. }
  6487. if (newArr->length != deleteLen)
  6488. {
  6489. newArr->SetLength(deleteLen);
  6490. }
  6491. else
  6492. {
  6493. newArr->length = deleteLen;
  6494. }
  6495. newArr->InvalidateLastUsedSegment();
  6496. #ifdef VALIDATE_ARRAY
  6497. newArr->ValidateArray();
  6498. pArr->ValidateArray();
  6499. #endif
  6500. if (newLenOverflow.HasOverflowed())
  6501. {
  6502. // ES5 15.4.4.12 16: If new len overflowed, SetLength throws
  6503. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  6504. }
  6505. return newArr;
  6506. }
  6507. if (newLenOverflow.HasOverflowed())
  6508. {
  6509. JS_REENTRANT_UNLOCK(jsReentLock, return ObjectSpliceHelper<uint64>(pArr, len, start, deleteLen, insertArgs, insertLen, scriptContext, newObj));
  6510. }
  6511. else // Use uint32 version if no overflow
  6512. {
  6513. JS_REENTRANT_UNLOCK(jsReentLock, return ObjectSpliceHelper<uint32>(pArr, len, start, deleteLen, insertArgs, insertLen, scriptContext, newObj));
  6514. }
  6515. }
  6516. template<typename T>
  6517. RecyclableObject* JavascriptArray::ObjectSpliceHelper(RecyclableObject* pObj, T len, T start,
  6518. T deleteLen, Var* insertArgs, uint32 insertLen, ScriptContext *scriptContext, RecyclableObject* pNewObj)
  6519. {
  6520. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6521. JavascriptArray *pnewArr = nullptr;
  6522. if (pNewObj == nullptr)
  6523. {
  6524. JS_REENTRANT(jsReentLock, pNewObj = ArraySpeciesCreate(pObj, deleteLen, scriptContext));
  6525. if (pNewObj == nullptr)
  6526. {
  6527. if (deleteLen > UINT_MAX)
  6528. {
  6529. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  6530. }
  6531. pnewArr = scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(deleteLen));
  6532. pnewArr->EnsureHead<Var>();
  6533. pNewObj = pnewArr;
  6534. }
  6535. }
  6536. if (JavascriptArray::Is(pNewObj))
  6537. {
  6538. #if ENABLE_COPYONACCESS_ARRAY
  6539. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pNewObj);
  6540. #endif
  6541. pnewArr = JavascriptArray::FromVar(pNewObj);
  6542. }
  6543. // copy elements to delete to new array
  6544. if (pnewArr != nullptr)
  6545. {
  6546. for (uint32 i = 0; i < deleteLen; i++)
  6547. {
  6548. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(pObj, start + i));
  6549. if (hasItem)
  6550. {
  6551. JS_REENTRANT(jsReentLock, Var element = JavascriptOperators::GetItem(pObj, start + i, scriptContext));
  6552. pnewArr->SetItem(i, element, PropertyOperation_None);
  6553. }
  6554. }
  6555. }
  6556. else
  6557. {
  6558. BigIndex k = 0u;
  6559. for (T i = 0u; i < deleteLen; i++)
  6560. {
  6561. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(pObj, start + i));
  6562. if (hasItem)
  6563. {
  6564. Var element = nullptr;
  6565. JS_REENTRANT(jsReentLock, element = JavascriptOperators::GetItem(pObj, start + i, scriptContext),
  6566. ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(pNewObj, k, element), scriptContext, k));
  6567. }
  6568. ++k;
  6569. }
  6570. }
  6571. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.splice"));
  6572. // Now we need reserve room if it is necessary
  6573. if (insertLen > deleteLen) // Might overflow max array length
  6574. {
  6575. // Unshift [start + deleteLen, len) to start + insertLen
  6576. JS_REENTRANT(jsReentLock, Unshift<BigIndex, T>(pObj, start + insertLen, start + deleteLen, len, scriptContext));
  6577. }
  6578. else if (insertLen < deleteLen) // Won't overflow max array length
  6579. {
  6580. T j = 0;
  6581. for (T i = start + deleteLen; i < len; i++)
  6582. {
  6583. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(pObj, i));
  6584. if (hasItem)
  6585. {
  6586. Var element = nullptr;
  6587. JS_REENTRANT(jsReentLock, element = JavascriptOperators::GetItem(pObj, i, scriptContext),
  6588. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(pObj, pObj, start + insertLen + j, element, scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  6589. }
  6590. else
  6591. {
  6592. JS_REENTRANT(jsReentLock,
  6593. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(pObj, start + insertLen + j, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  6594. }
  6595. j++;
  6596. }
  6597. // Clean up the rest
  6598. for (T i = len; i > len - deleteLen + insertLen; i--)
  6599. {
  6600. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(pObj, i - 1, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  6601. }
  6602. }
  6603. if (insertLen > 0)
  6604. {
  6605. T dstIndex = start; // insert index might overflow max array length
  6606. for (uint32 i = 0; i < insertLen; i++)
  6607. {
  6608. JS_REENTRANT(jsReentLock,
  6609. h.ThrowTypeErrorOnFailure(IndexTrace<BigIndex>::SetItem(pObj, dstIndex, insertArgs[i], PropertyOperation_ThrowIfNotExtensible)));
  6610. ++dstIndex;
  6611. }
  6612. }
  6613. // Set up new length
  6614. T newLen = T(len - deleteLen) + insertLen;
  6615. JS_REENTRANT(jsReentLock,
  6616. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(pObj, pObj, PropertyIds::length, IndexTrace<BigIndex>::ToNumber(newLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)),
  6617. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(pNewObj, pNewObj, PropertyIds::length, IndexTrace<BigIndex>::ToNumber(deleteLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  6618. #ifdef VALIDATE_ARRAY
  6619. if (pnewArr)
  6620. {
  6621. pnewArr->ValidateArray();
  6622. }
  6623. #endif
  6624. return pNewObj;
  6625. }
  6626. Var JavascriptArray::EntryToLocaleString(RecyclableObject* function, CallInfo callInfo, ...)
  6627. {
  6628. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  6629. ARGUMENTS(args, callInfo);
  6630. ScriptContext* scriptContext = function->GetScriptContext();
  6631. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6632. Assert(!(callInfo.Flags & CallFlags_New));
  6633. if (args.Info.Count == 0)
  6634. {
  6635. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedObject, _u("Array.prototype.toLocaleString"));
  6636. }
  6637. if (JavascriptArray::IsDirectAccessArray(args[0]))
  6638. {
  6639. JavascriptArray* arr = JavascriptArray::FromVar(args[0]);
  6640. JS_REENTRANT_UNLOCK(jsReentLock, return ToLocaleString(arr, scriptContext));
  6641. }
  6642. else
  6643. {
  6644. if (TypedArrayBase::IsDetachedTypedArray(args[0]))
  6645. {
  6646. JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("Array.prototype.toLocalString"));
  6647. }
  6648. RecyclableObject* obj = nullptr;
  6649. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  6650. {
  6651. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.toLocaleString"));
  6652. }
  6653. JS_REENTRANT_UNLOCK(jsReentLock, return ToLocaleString(obj, scriptContext));
  6654. }
  6655. }
  6656. //
  6657. // Unshift object elements [start, end) to toIndex, asserting toIndex > start.
  6658. //
  6659. template<typename T, typename P>
  6660. void JavascriptArray::Unshift(RecyclableObject* obj, const T& toIndex, P start, P end, ScriptContext* scriptContext)
  6661. {
  6662. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6663. typedef IndexTrace<T> index_trace;
  6664. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.unshift"));
  6665. if (start < end)
  6666. {
  6667. T newEnd = (end - start - 1);// newEnd - 1
  6668. T dst = toIndex + newEnd;
  6669. for (P i = end; i > start; --i)
  6670. {
  6671. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, i - 1));
  6672. if (hasItem)
  6673. {
  6674. Var element = nullptr;
  6675. JS_REENTRANT(jsReentLock, element = JavascriptOperators::GetItem(obj, i - 1, scriptContext),
  6676. h.ThrowTypeErrorOnFailure(index_trace::SetItem(obj, dst, element, PropertyOperation_ThrowIfNotExtensible)));
  6677. }
  6678. else
  6679. {
  6680. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(index_trace::DeleteItem(obj, dst, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  6681. }
  6682. --dst;
  6683. }
  6684. }
  6685. }
  6686. template<typename T>
  6687. void JavascriptArray::GrowArrayHeadHelperForUnshift(JavascriptArray* pArr, uint32 unshiftElements, ScriptContext * scriptContext)
  6688. {
  6689. SparseArraySegmentBase* nextToHeadSeg = pArr->head->next;
  6690. Recycler* recycler = scriptContext->GetRecycler();
  6691. if (nextToHeadSeg == nullptr)
  6692. {
  6693. pArr->EnsureHead<T>();
  6694. pArr->head = SparseArraySegment<T>::From(pArr->head)->GrowByMin(recycler, unshiftElements);
  6695. }
  6696. else
  6697. {
  6698. pArr->head = SparseArraySegment<T>::From(pArr->head)->GrowByMinMax(recycler, unshiftElements, ((nextToHeadSeg->left + unshiftElements) - pArr->head->left - pArr->head->size));
  6699. }
  6700. }
  6701. template<typename T>
  6702. void JavascriptArray::UnshiftHelper(JavascriptArray* pArr, uint32 unshiftElements, Js::Var * elements)
  6703. {
  6704. SparseArraySegment<T>* head = SparseArraySegment<T>::From(pArr->head);
  6705. // Make enough room in the head segment to insert new elements at the front
  6706. MoveArray(head->elements + unshiftElements, head->elements, pArr->head->length);
  6707. uint32 oldHeadLength = head->length;
  6708. head->length += unshiftElements;
  6709. head->CheckLengthvsSize();
  6710. /* Set head segment as the last used segment */
  6711. pArr->InvalidateLastUsedSegment();
  6712. bool hasNoMissingValues = pArr->HasNoMissingValues();
  6713. /* Set HasNoMissingValues to false -> Since we shifted elements right, we might have missing values after the memmove */
  6714. if(unshiftElements > oldHeadLength)
  6715. {
  6716. pArr->SetHasNoMissingValues(false);
  6717. }
  6718. #if ENABLE_PROFILE_INFO
  6719. pArr->FillFromArgs(unshiftElements, 0, elements, nullptr, true/*dontCreateNewArray*/);
  6720. #else
  6721. pArr->FillFromArgs(unshiftElements, 0, elements, true/*dontCreateNewArray*/);
  6722. #endif
  6723. // Setting back to the old value
  6724. pArr->SetHasNoMissingValues(hasNoMissingValues);
  6725. }
  6726. Var JavascriptArray::EntryUnshift(RecyclableObject* function, CallInfo callInfo, ...)
  6727. {
  6728. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  6729. ARGUMENTS(args, callInfo);
  6730. ScriptContext* scriptContext = function->GetScriptContext();
  6731. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6732. Assert(!(callInfo.Flags & CallFlags_New));
  6733. Var res = scriptContext->GetLibrary()->GetUndefined();
  6734. if (args.Info.Count == 0)
  6735. {
  6736. return res;
  6737. }
  6738. if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
  6739. {
  6740. #if ENABLE_COPYONACCESS_ARRAY
  6741. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
  6742. #endif
  6743. JavascriptArray * pArr = JavascriptArray::FromVar(args[0]);
  6744. uint32 unshiftElements = args.Info.Count - 1;
  6745. if (unshiftElements > 0)
  6746. {
  6747. if (pArr->IsFillFromPrototypes())
  6748. {
  6749. JS_REENTRANT(jsReentLock, pArr->FillFromPrototypes(0, pArr->length)); // We need find all missing value from [[proto]] object
  6750. }
  6751. // Pre-process: truncate overflowing elements to properties
  6752. bool newLenOverflowed = false;
  6753. uint32 maxLen = MaxArrayLength - unshiftElements;
  6754. if (pArr->length > maxLen)
  6755. {
  6756. newLenOverflowed = true;
  6757. // Ensure the array is non-native when overflow happens
  6758. EnsureNonNativeArray(pArr);
  6759. pArr->TruncateToProperties(MaxArrayLength, maxLen);
  6760. Assert(pArr->length + unshiftElements == MaxArrayLength);
  6761. }
  6762. pArr->ClearSegmentMap(); // Dump segmentMap on unshift (before any possible allocation and throw)
  6763. Assert(pArr->length <= MaxArrayLength - unshiftElements);
  6764. bool isIntArray = false;
  6765. bool isFloatArray = false;
  6766. if (JavascriptNativeIntArray::Is(pArr))
  6767. {
  6768. isIntArray = true;
  6769. }
  6770. else if (JavascriptNativeFloatArray::Is(pArr))
  6771. {
  6772. isFloatArray = true;
  6773. }
  6774. // If we need to grow head segment and there is already a next segment, then allocate the new head segment upfront
  6775. // If there is OOM in array allocation, then array consistency is maintained.
  6776. if (pArr->head->size < pArr->head->length + unshiftElements)
  6777. {
  6778. if (isIntArray)
  6779. {
  6780. GrowArrayHeadHelperForUnshift<int32>(pArr, unshiftElements, scriptContext);
  6781. }
  6782. else if (isFloatArray)
  6783. {
  6784. GrowArrayHeadHelperForUnshift<double>(pArr, unshiftElements, scriptContext);
  6785. }
  6786. else
  6787. {
  6788. GrowArrayHeadHelperForUnshift<Var>(pArr, unshiftElements, scriptContext);
  6789. }
  6790. }
  6791. if (isIntArray)
  6792. {
  6793. UnshiftHelper<int32>(pArr, unshiftElements, args.Values);
  6794. }
  6795. else if (isFloatArray)
  6796. {
  6797. UnshiftHelper<double>(pArr, unshiftElements, args.Values);
  6798. }
  6799. else
  6800. {
  6801. UnshiftHelper<Var>(pArr, unshiftElements, args.Values);
  6802. }
  6803. SparseArraySegmentBase* renumberSeg = pArr->head->next;
  6804. while (renumberSeg)
  6805. {
  6806. renumberSeg->left += unshiftElements;
  6807. if (renumberSeg->next == nullptr)
  6808. {
  6809. // last segment can shift its left + size beyond MaxArrayLength, so truncate if so
  6810. renumberSeg->EnsureSizeInBound();
  6811. }
  6812. renumberSeg = renumberSeg->next;
  6813. }
  6814. pArr->InvalidateLastUsedSegment();
  6815. pArr->length += unshiftElements;
  6816. #ifdef VALIDATE_ARRAY
  6817. pArr->ValidateArray();
  6818. #endif
  6819. if (newLenOverflowed) // ES5: throw if new "length" exceeds max array length
  6820. {
  6821. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  6822. }
  6823. }
  6824. res = JavascriptNumber::ToVar(pArr->length, scriptContext);
  6825. }
  6826. else
  6827. {
  6828. RecyclableObject* dynamicObject = nullptr;
  6829. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &dynamicObject))
  6830. {
  6831. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.unshift"));
  6832. }
  6833. JS_REENTRANT(jsReentLock, BigIndex length = OP_GetLength(dynamicObject, scriptContext));
  6834. uint32 unshiftElements = args.Info.Count - 1;
  6835. if (unshiftElements > 0)
  6836. {
  6837. uint32 MaxSpaceUint32 = MaxArrayLength - unshiftElements;
  6838. // Note: end will always be a smallIndex either it is less than length in which case it is MaxSpaceUint32
  6839. // or MaxSpaceUint32 is greater than length meaning length is a uint32 number
  6840. BigIndex end = length > MaxSpaceUint32 ? MaxSpaceUint32 : length;
  6841. if (end < length)
  6842. {
  6843. // Unshift [end, length) to MaxArrayLength
  6844. // MaxArrayLength + (length - MaxSpaceUint32 - 1) = length + unshiftElements -1
  6845. if (length.IsSmallIndex())
  6846. {
  6847. JS_REENTRANT(jsReentLock, Unshift<BigIndex>(dynamicObject, MaxArrayLength, end.GetSmallIndex(), length.GetSmallIndex(), scriptContext));
  6848. }
  6849. else
  6850. {
  6851. JS_REENTRANT(jsReentLock, Unshift<BigIndex, uint64>(dynamicObject, MaxArrayLength, (uint64)end.GetSmallIndex(), length.GetBigIndex(), scriptContext));
  6852. }
  6853. }
  6854. // Unshift [0, end) to unshiftElements
  6855. // unshiftElements + (MaxSpaceUint32 - 0 - 1) = MaxArrayLength -1 therefore this unshift covers up to MaxArrayLength - 1
  6856. JS_REENTRANT(jsReentLock, Unshift<uint32>(dynamicObject, unshiftElements, (uint32)0, end.GetSmallIndex(), scriptContext));
  6857. for (uint32 i = 0; i < unshiftElements; i++)
  6858. {
  6859. JS_REENTRANT(jsReentLock,
  6860. JavascriptOperators::SetItem(dynamicObject, dynamicObject, i, args[i + 1], scriptContext, PropertyOperation_ThrowIfNotExtensible, true));
  6861. }
  6862. }
  6863. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.unshift"));
  6864. //ES6 - update 'length' even if unshiftElements == 0;
  6865. BigIndex newLen = length + unshiftElements;
  6866. res = JavascriptNumber::ToVar(newLen.IsSmallIndex() ? newLen.GetSmallIndex() : newLen.GetBigIndex(), scriptContext);
  6867. JS_REENTRANT(jsReentLock,
  6868. BOOL setLength = JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, res, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  6869. h.ThrowTypeErrorOnFailure(setLength);
  6870. }
  6871. return res;
  6872. }
  6873. Var JavascriptArray::EntryToString(RecyclableObject* function, CallInfo callInfo, ...)
  6874. {
  6875. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  6876. ARGUMENTS(args, callInfo);
  6877. ScriptContext* scriptContext = function->GetScriptContext();
  6878. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6879. Assert(!(callInfo.Flags & CallFlags_New));
  6880. if (args.Info.Count == 0)
  6881. {
  6882. JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedObject);
  6883. }
  6884. // ES5 15.4.4.2: call join, or built-in Object.prototype.toString
  6885. RecyclableObject* obj = nullptr;
  6886. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  6887. {
  6888. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.toString"));
  6889. }
  6890. // In ES5 we could be calling a user defined join, even on array. We must [[Get]] join at runtime.
  6891. JS_REENTRANT(jsReentLock, Var join = JavascriptOperators::GetProperty(obj, PropertyIds::join, scriptContext));
  6892. if (JavascriptConversion::IsCallable(join))
  6893. {
  6894. RecyclableObject* func = RecyclableObject::FromVar(join);
  6895. // We need to record implicit call here, because marked the Array.toString as no side effect,
  6896. // but if we call user code here which may have side effect
  6897. ThreadContext * threadContext = scriptContext->GetThreadContext();
  6898. JS_REENTRANT(jsReentLock,
  6899. Var result = threadContext->ExecuteImplicitCall(func, ImplicitCall_ToPrimitive, [=]() -> Js::Var
  6900. {
  6901. // Stack object should have a pre-op bail on implicit call. We shouldn't see them here.
  6902. Assert(!ThreadContext::IsOnStack(obj));
  6903. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  6904. CallFlags flags = CallFlags_Value;
  6905. return CALL_FUNCTION(threadContext, func, CallInfo(flags, 1), obj);
  6906. }));
  6907. if(!result)
  6908. {
  6909. // There was an implicit call and implicit calls are disabled. This would typically cause a bailout.
  6910. Assert(threadContext->IsDisableImplicitCall());
  6911. result = scriptContext->GetLibrary()->GetNull();
  6912. }
  6913. return result;
  6914. }
  6915. else
  6916. {
  6917. // call built-in Object.prototype.toString
  6918. JS_REENTRANT_UNLOCK(jsReentLock,
  6919. return CALL_ENTRYPOINT(scriptContext->GetThreadContext(), JavascriptObject::EntryToString, function, CallInfo(1), obj));
  6920. }
  6921. }
  6922. #if DEBUG
  6923. BOOL JavascriptArray::GetIndex(const char16* propName, uint32 *pIndex)
  6924. {
  6925. uint32 lu, luDig;
  6926. int32 cch = (int32)wcslen(propName);
  6927. char16* pch = const_cast<char16 *>(propName);
  6928. lu = *pch - '0';
  6929. if (lu > 9)
  6930. return FALSE;
  6931. if (0 == lu)
  6932. {
  6933. *pIndex = 0;
  6934. return 1 == cch;
  6935. }
  6936. while ((luDig = *++pch - '0') < 10)
  6937. {
  6938. // If we overflow 32 bits, ignore the item
  6939. if (lu > 0x19999999)
  6940. return FALSE;
  6941. lu *= 10;
  6942. if(lu > (ULONG_MAX - luDig))
  6943. return FALSE;
  6944. lu += luDig;
  6945. }
  6946. if (pch - propName != cch)
  6947. return FALSE;
  6948. if (lu == JavascriptArray::InvalidIndex)
  6949. {
  6950. // 0xFFFFFFFF is not treated as an array index so that the length can be
  6951. // capped at 32 bits.
  6952. return FALSE;
  6953. }
  6954. *pIndex = lu;
  6955. return TRUE;
  6956. }
  6957. #endif
  6958. JavascriptString* JavascriptArray::GetLocaleSeparator(ScriptContext* scriptContext)
  6959. {
  6960. #ifdef ENABLE_GLOBALIZATION
  6961. LCID lcid = GetUserDefaultLCID();
  6962. int count = 0;
  6963. char16 szSeparator[6];
  6964. // According to the document for GetLocaleInfo this is a sufficient buffer size.
  6965. count = GetLocaleInfoW(lcid, LOCALE_SLIST, szSeparator, 5);
  6966. if( !count)
  6967. {
  6968. AssertMsg(FALSE, "GetLocaleInfo failed");
  6969. return scriptContext->GetLibrary()->GetCommaSpaceDisplayString();
  6970. }
  6971. else
  6972. {
  6973. // Append ' ' if necessary
  6974. if( count < 2 || szSeparator[count-2] != ' ')
  6975. {
  6976. szSeparator[count-1] = ' ';
  6977. szSeparator[count] = '\0';
  6978. }
  6979. return JavascriptString::NewCopyBuffer(szSeparator, count, scriptContext);
  6980. }
  6981. #else
  6982. // xplat-todo: Support locale-specific seperator
  6983. return scriptContext->GetLibrary()->GetCommaSpaceDisplayString();
  6984. #endif
  6985. }
  6986. template <typename T>
  6987. JavascriptString* JavascriptArray::ToLocaleString(T* arr, ScriptContext* scriptContext)
  6988. {
  6989. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6990. uint32 length = 0;
  6991. if (TypedArrayBase::Is(arr))
  6992. {
  6993. // For a TypedArray use the actual length of the array.
  6994. length = TypedArrayBase::FromVar(arr)->GetLength();
  6995. }
  6996. else
  6997. {
  6998. //For anything else, use the "length" property if present.
  6999. JS_REENTRANT(jsReentLock, length = ItemTrace<T>::GetLength(arr, scriptContext));
  7000. }
  7001. if (length == 0 || scriptContext->CheckObject(arr))
  7002. {
  7003. return scriptContext->GetLibrary()->GetEmptyString();
  7004. }
  7005. JavascriptString* res = scriptContext->GetLibrary()->GetEmptyString();
  7006. bool pushedObject = false;
  7007. TryFinally([&]()
  7008. {
  7009. scriptContext->PushObject(arr);
  7010. pushedObject = true;
  7011. Var element;
  7012. JS_REENTRANT(jsReentLock, BOOL gotItem = ItemTrace<T>::GetItem(arr, 0, &element, scriptContext));
  7013. if (gotItem)
  7014. {
  7015. JS_REENTRANT(jsReentLock, res = JavascriptArray::ToLocaleStringHelper(element, scriptContext));
  7016. }
  7017. if (length > 1)
  7018. {
  7019. JavascriptString* separator = GetLocaleSeparator(scriptContext);
  7020. for (uint32 i = 1; i < length; i++)
  7021. {
  7022. res = JavascriptString::Concat(res, separator);
  7023. JS_REENTRANT(jsReentLock, gotItem = ItemTrace<T>::GetItem(arr, i, &element, scriptContext));
  7024. if (gotItem)
  7025. {
  7026. JS_REENTRANT(jsReentLock, res = JavascriptString::Concat(res, JavascriptArray::ToLocaleStringHelper(element, scriptContext)));
  7027. }
  7028. }
  7029. }
  7030. },
  7031. [&](bool/*hasException*/)
  7032. {
  7033. if (pushedObject)
  7034. {
  7035. Var top = scriptContext->PopObject();
  7036. AssertMsg(top == arr, "Unmatched operation stack");
  7037. }
  7038. });
  7039. if (res == nullptr)
  7040. {
  7041. res = scriptContext->GetLibrary()->GetEmptyString();
  7042. }
  7043. return res;
  7044. }
  7045. Var JavascriptArray::EntryIsArray(RecyclableObject* function, CallInfo callInfo, ...)
  7046. {
  7047. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7048. ARGUMENTS(args, callInfo);
  7049. ScriptContext* scriptContext = function->GetScriptContext();
  7050. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7051. Assert(!(callInfo.Flags & CallFlags_New));
  7052. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Constructor_isArray);
  7053. if (args.Info.Count < 2)
  7054. {
  7055. return scriptContext->GetLibrary()->GetFalse();
  7056. }
  7057. #if ENABLE_COPYONACCESS_ARRAY
  7058. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[1]);
  7059. #endif
  7060. if (JavascriptOperators::IsArray(args[1]))
  7061. {
  7062. return scriptContext->GetLibrary()->GetTrue();
  7063. }
  7064. return scriptContext->GetLibrary()->GetFalse();
  7065. }
  7066. ///----------------------------------------------------------------------------
  7067. /// Find() calls the given predicate callback on each element of the array, in
  7068. /// order, and returns the first element that makes the predicate return true,
  7069. /// as described in (ES6.0: S22.1.3.8).
  7070. ///----------------------------------------------------------------------------
  7071. Var JavascriptArray::EntryFind(RecyclableObject* function, CallInfo callInfo, ...)
  7072. {
  7073. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7074. ARGUMENTS(args, callInfo);
  7075. ScriptContext* scriptContext = function->GetScriptContext();
  7076. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7077. Assert(!(callInfo.Flags & CallFlags_New));
  7078. if (args.Info.Count == 0)
  7079. {
  7080. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.find"));
  7081. }
  7082. int64 length;
  7083. JavascriptArray * pArr = nullptr;
  7084. RecyclableObject* obj = nullptr;
  7085. JS_REENTRANT_UNLOCK(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.find"), &pArr, &obj, &length));
  7086. return JavascriptArray::FindHelper<false>(pArr, nullptr, obj, length, args, scriptContext);
  7087. }
  7088. template <bool findIndex>
  7089. Var JavascriptArray::FindHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
  7090. {
  7091. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7092. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  7093. {
  7094. // typedArrayBase is only non-null if and only if we came here via the TypedArray entrypoint
  7095. if (typedArrayBase != nullptr)
  7096. {
  7097. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, findIndex ? _u("[TypedArray].prototype.findIndex") : _u("[TypedArray].prototype.find"));
  7098. }
  7099. else
  7100. {
  7101. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, findIndex ? _u("Array.prototype.findIndex") : _u("Array.prototype.find"));
  7102. }
  7103. }
  7104. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  7105. Var thisArg;
  7106. if (args.Info.Count > 2)
  7107. {
  7108. thisArg = args[2];
  7109. }
  7110. else
  7111. {
  7112. thisArg = scriptContext->GetLibrary()->GetUndefined();
  7113. }
  7114. // If we came from Array.prototype.find/findIndex and source object is not a JavascriptArray, source could be a TypedArray
  7115. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  7116. {
  7117. typedArrayBase = TypedArrayBase::FromVar(obj);
  7118. }
  7119. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7120. CallFlags flags = CallFlags_Value;
  7121. Var element = nullptr;
  7122. Var testResult = nullptr;
  7123. if (pArr)
  7124. {
  7125. Var undefined = scriptContext->GetLibrary()->GetUndefined();
  7126. Assert(length <= UINT_MAX);
  7127. for (uint32 k = 0; k < (uint32)length; k++)
  7128. {
  7129. element = undefined;
  7130. JS_REENTRANT(jsReentLock, pArr->DirectGetItemAtFull(k, &element));
  7131. Var index = JavascriptNumber::ToVar(k, scriptContext);
  7132. JS_REENTRANT(jsReentLock,
  7133. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7134. element,
  7135. index,
  7136. pArr));
  7137. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7138. {
  7139. return findIndex ? index : element;
  7140. }
  7141. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  7142. // we will process the rest of the array elements like an ES5Array.
  7143. if (!JavascriptArray::Is(obj))
  7144. {
  7145. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  7146. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FindObjectHelper<findIndex>(obj, length, k + 1, callBackFn, thisArg, scriptContext));
  7147. }
  7148. }
  7149. }
  7150. else if (typedArrayBase)
  7151. {
  7152. Assert(length <= UINT_MAX);
  7153. for (uint32 k = 0; k < (uint32)length; k++)
  7154. {
  7155. // Spec does not ask to call HasItem, so we need to go to visit the whole length
  7156. element = typedArrayBase->DirectGetItem(k);
  7157. Var index = JavascriptNumber::ToVar(k, scriptContext);
  7158. JS_REENTRANT(jsReentLock,
  7159. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7160. element,
  7161. index,
  7162. typedArrayBase));
  7163. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7164. {
  7165. return findIndex ? index : element;
  7166. }
  7167. }
  7168. }
  7169. else
  7170. {
  7171. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FindObjectHelper<findIndex>(obj, length, 0u, callBackFn, thisArg, scriptContext));
  7172. }
  7173. return findIndex ? JavascriptNumber::ToVar(-1, scriptContext) : scriptContext->GetLibrary()->GetUndefined();
  7174. }
  7175. template <bool findIndex>
  7176. Var JavascriptArray::FindObjectHelper(RecyclableObject* obj, int64 length, int64 start, RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
  7177. {
  7178. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7179. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7180. CallFlags flags = CallFlags_Value;
  7181. Var element = nullptr;
  7182. Var testResult = nullptr;
  7183. for (int64 k = start; k < length; k++)
  7184. {
  7185. JS_REENTRANT(jsReentLock, element = JavascriptOperators::GetItem(obj, (uint64)k, scriptContext));
  7186. Var index = JavascriptNumber::ToVar(k, scriptContext);
  7187. JS_REENTRANT(jsReentLock,
  7188. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7189. element,
  7190. index,
  7191. obj));
  7192. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7193. {
  7194. return findIndex ? index : element;
  7195. }
  7196. }
  7197. return findIndex ? JavascriptNumber::ToVar(-1, scriptContext) : scriptContext->GetLibrary()->GetUndefined();
  7198. }
  7199. ///----------------------------------------------------------------------------
  7200. /// FindIndex() calls the given predicate callback on each element of the
  7201. /// array, in order, and returns the index of the first element that makes the
  7202. /// predicate return true, as described in (ES6.0: S22.1.3.9).
  7203. ///----------------------------------------------------------------------------
  7204. Var JavascriptArray::EntryFindIndex(RecyclableObject* function, CallInfo callInfo, ...)
  7205. {
  7206. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7207. ARGUMENTS(args, callInfo);
  7208. ScriptContext* scriptContext = function->GetScriptContext();
  7209. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7210. Assert(!(callInfo.Flags & CallFlags_New));
  7211. if (args.Info.Count == 0)
  7212. {
  7213. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.findIndex"));
  7214. }
  7215. int64 length;
  7216. JavascriptArray * pArr = nullptr;
  7217. RecyclableObject* obj = nullptr;
  7218. JS_REENTRANT_UNLOCK(jsReentLock,
  7219. TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.findIndex"), &pArr, &obj, &length));
  7220. return JavascriptArray::FindHelper<true>(pArr, nullptr, obj, length, args, scriptContext);
  7221. }
  7222. ///----------------------------------------------------------------------------
  7223. /// Entries() returns a new ArrayIterator object configured to return key-
  7224. /// value pairs matching the elements of the this array/array-like object,
  7225. /// as described in (ES6.0: S22.1.3.4).
  7226. ///----------------------------------------------------------------------------
  7227. Var JavascriptArray::EntryEntries(RecyclableObject* function, CallInfo callInfo, ...)
  7228. {
  7229. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7230. ARGUMENTS(args, callInfo);
  7231. ScriptContext* scriptContext = function->GetScriptContext();
  7232. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7233. Assert(!(callInfo.Flags & CallFlags_New));
  7234. if (args.Info.Count == 0)
  7235. {
  7236. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.entries"));
  7237. }
  7238. RecyclableObject* thisObj = nullptr;
  7239. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &thisObj))
  7240. {
  7241. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.entries"));
  7242. }
  7243. #if ENABLE_COPYONACCESS_ARRAY
  7244. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(thisObj);
  7245. #endif
  7246. JS_REENTRANT_UNLOCK(jsReentLock,
  7247. return scriptContext->GetLibrary()->CreateArrayIterator(thisObj, JavascriptArrayIteratorKind::KeyAndValue));
  7248. }
  7249. ///----------------------------------------------------------------------------
  7250. /// Keys() returns a new ArrayIterator object configured to return the keys
  7251. /// of the this array/array-like object, as described in (ES6.0: S22.1.3.13).
  7252. ///----------------------------------------------------------------------------
  7253. Var JavascriptArray::EntryKeys(RecyclableObject* function, CallInfo callInfo, ...)
  7254. {
  7255. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7256. ARGUMENTS(args, callInfo);
  7257. ScriptContext* scriptContext = function->GetScriptContext();
  7258. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7259. Assert(!(callInfo.Flags & CallFlags_New));
  7260. if (args.Info.Count == 0)
  7261. {
  7262. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.keys"));
  7263. }
  7264. RecyclableObject* thisObj = nullptr;
  7265. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &thisObj))
  7266. {
  7267. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.keys"));
  7268. }
  7269. #if ENABLE_COPYONACCESS_ARRAY
  7270. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(thisObj);
  7271. #endif
  7272. JS_REENTRANT_UNLOCK(jsReentLock,
  7273. return scriptContext->GetLibrary()->CreateArrayIterator(thisObj, JavascriptArrayIteratorKind::Key));
  7274. }
  7275. ///----------------------------------------------------------------------------
  7276. /// Values() returns a new ArrayIterator object configured to return the values
  7277. /// of the this array/array-like object, as described in (ES6.0: S22.1.3.29).
  7278. ///----------------------------------------------------------------------------
  7279. Var JavascriptArray::EntryValues(RecyclableObject* function, CallInfo callInfo, ...)
  7280. {
  7281. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7282. ARGUMENTS(args, callInfo);
  7283. ScriptContext* scriptContext = function->GetScriptContext();
  7284. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7285. Assert(!(callInfo.Flags & CallFlags_New));
  7286. if (args.Info.Count == 0)
  7287. {
  7288. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.values"));
  7289. }
  7290. RecyclableObject* thisObj = nullptr;
  7291. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &thisObj))
  7292. {
  7293. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.values"));
  7294. }
  7295. #if ENABLE_COPYONACCESS_ARRAY
  7296. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(thisObj);
  7297. #endif
  7298. JS_REENTRANT_UNLOCK(jsReentLock,
  7299. return scriptContext->GetLibrary()->CreateArrayIterator(thisObj, JavascriptArrayIteratorKind::Value));
  7300. }
  7301. Var JavascriptArray::EntryEvery(RecyclableObject* function, CallInfo callInfo, ...)
  7302. {
  7303. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7304. ARGUMENTS(args, callInfo);
  7305. ScriptContext* scriptContext = function->GetScriptContext();
  7306. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7307. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.every"));
  7308. Assert(!(callInfo.Flags & CallFlags_New));
  7309. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_every);
  7310. if (args.Info.Count == 0)
  7311. {
  7312. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.every"));
  7313. }
  7314. BigIndex length;
  7315. JavascriptArray* pArr = nullptr;
  7316. RecyclableObject* obj = nullptr;
  7317. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.every"), &pArr, &obj, &length));
  7318. if (length.IsSmallIndex())
  7319. {
  7320. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::EveryHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  7321. }
  7322. 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
  7323. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::EveryHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  7324. }
  7325. // Array.prototype.every as described by ES6.0 (draft 22) Section 22.1.3.5
  7326. template <typename T>
  7327. Var JavascriptArray::EveryHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  7328. {
  7329. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7330. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  7331. {
  7332. // typedArrayBase is only non-null if and only if we came here via the TypedArray entrypoint
  7333. if (typedArrayBase != nullptr)
  7334. {
  7335. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.every"));
  7336. }
  7337. else
  7338. {
  7339. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.every"));
  7340. }
  7341. }
  7342. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  7343. Var thisArg = nullptr;
  7344. if (args.Info.Count > 2)
  7345. {
  7346. thisArg = args[2];
  7347. }
  7348. else
  7349. {
  7350. thisArg = scriptContext->GetLibrary()->GetUndefined();
  7351. }
  7352. // If we came from Array.prototype.map and source object is not a JavascriptArray, source could be a TypedArray
  7353. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  7354. {
  7355. typedArrayBase = TypedArrayBase::FromVar(obj);
  7356. }
  7357. Var element = nullptr;
  7358. Var testResult = nullptr;
  7359. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7360. CallFlags flags = CallFlags_Value;
  7361. if (pArr)
  7362. {
  7363. Assert(length <= UINT_MAX);
  7364. for (uint32 k = 0; k < (uint32)length; k++)
  7365. {
  7366. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(k, &element));
  7367. if (!gotItem)
  7368. {
  7369. continue;
  7370. }
  7371. JS_REENTRANT(jsReentLock,
  7372. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7373. element,
  7374. JavascriptNumber::ToVar(k, scriptContext),
  7375. pArr));
  7376. if (!JavascriptConversion::ToBoolean(testResult, scriptContext))
  7377. {
  7378. return scriptContext->GetLibrary()->GetFalse();
  7379. }
  7380. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  7381. // we will process the rest of the array elements like an ES5Array.
  7382. if (!JavascriptArray::Is(obj))
  7383. {
  7384. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  7385. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::EveryObjectHelper<T>(obj, length, k + 1, callBackFn, thisArg, scriptContext));
  7386. }
  7387. }
  7388. }
  7389. else if (typedArrayBase)
  7390. {
  7391. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  7392. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  7393. for (uint32 k = 0; k < end; k++)
  7394. {
  7395. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  7396. element = typedArrayBase->DirectGetItem(k);
  7397. JS_REENTRANT(jsReentLock,
  7398. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7399. element,
  7400. JavascriptNumber::ToVar(k, scriptContext),
  7401. typedArrayBase));
  7402. if (!JavascriptConversion::ToBoolean(testResult, scriptContext))
  7403. {
  7404. return scriptContext->GetLibrary()->GetFalse();
  7405. }
  7406. }
  7407. }
  7408. else
  7409. {
  7410. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::EveryObjectHelper<T>(obj, length, 0u, callBackFn, thisArg, scriptContext));
  7411. }
  7412. return scriptContext->GetLibrary()->GetTrue();
  7413. }
  7414. template <typename T>
  7415. Var JavascriptArray::EveryObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
  7416. {
  7417. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7418. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7419. CallFlags flags = CallFlags_Value;
  7420. Var element = nullptr;
  7421. Var testResult = nullptr;
  7422. for (T k = start; k < length; k++)
  7423. {
  7424. // According to es6 spec, we need to call Has first before calling Get
  7425. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  7426. if (hasItem)
  7427. {
  7428. JS_REENTRANT(jsReentLock,
  7429. element = JavascriptOperators::GetItem(obj, k, scriptContext),
  7430. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7431. element,
  7432. JavascriptNumber::ToVar(k, scriptContext),
  7433. obj));
  7434. if (!JavascriptConversion::ToBoolean(testResult, scriptContext))
  7435. {
  7436. return scriptContext->GetLibrary()->GetFalse();
  7437. }
  7438. }
  7439. }
  7440. return scriptContext->GetLibrary()->GetTrue();
  7441. }
  7442. Var JavascriptArray::EntrySome(RecyclableObject* function, CallInfo callInfo, ...)
  7443. {
  7444. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7445. ARGUMENTS(args, callInfo);
  7446. ScriptContext* scriptContext = function->GetScriptContext();
  7447. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7448. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.some"));
  7449. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_some);
  7450. Assert(!(callInfo.Flags & CallFlags_New));
  7451. if (args.Info.Count == 0)
  7452. {
  7453. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.some"));
  7454. }
  7455. BigIndex length;
  7456. JavascriptArray* pArr = nullptr;
  7457. RecyclableObject* obj = nullptr;
  7458. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.some"), &pArr, &obj, &length));
  7459. if (length.IsSmallIndex())
  7460. {
  7461. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SomeHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  7462. }
  7463. 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
  7464. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SomeHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  7465. }
  7466. // Array.prototype.some as described in ES6.0 (draft 22) Section 22.1.3.23
  7467. template <typename T>
  7468. Var JavascriptArray::SomeHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  7469. {
  7470. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7471. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  7472. {
  7473. // We are in the TypedArray version of this API if and only if typedArrayBase != nullptr
  7474. if (typedArrayBase != nullptr)
  7475. {
  7476. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.some"));
  7477. }
  7478. else
  7479. {
  7480. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.some"));
  7481. }
  7482. }
  7483. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  7484. Var thisArg = nullptr;
  7485. if (args.Info.Count > 2)
  7486. {
  7487. thisArg = args[2];
  7488. }
  7489. else
  7490. {
  7491. thisArg = scriptContext->GetLibrary()->GetUndefined();
  7492. }
  7493. // If we came from Array.prototype.some and source object is not a JavascriptArray, source could be a TypedArray
  7494. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  7495. {
  7496. typedArrayBase = TypedArrayBase::FromVar(obj);
  7497. }
  7498. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7499. CallFlags flags = CallFlags_Value;
  7500. Var element = nullptr;
  7501. Var testResult = nullptr;
  7502. if (pArr)
  7503. {
  7504. Assert(length <= UINT_MAX);
  7505. for (uint32 k = 0; k < (uint32)length; k++)
  7506. {
  7507. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(k, &element));
  7508. if (!gotItem)
  7509. {
  7510. continue;
  7511. }
  7512. JS_REENTRANT_UNLOCK(jsReentLock,
  7513. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7514. element,
  7515. JavascriptNumber::ToVar(k, scriptContext),
  7516. pArr));
  7517. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7518. {
  7519. return scriptContext->GetLibrary()->GetTrue();
  7520. }
  7521. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  7522. // we will process the rest of the array elements like an ES5Array.
  7523. if (!JavascriptArray::Is(obj))
  7524. {
  7525. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  7526. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SomeObjectHelper<T>(obj, length, k + 1, callBackFn, thisArg, scriptContext));
  7527. }
  7528. }
  7529. }
  7530. else if (typedArrayBase)
  7531. {
  7532. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  7533. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  7534. for (uint32 k = 0; k < end; k++)
  7535. {
  7536. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  7537. element = typedArrayBase->DirectGetItem(k);
  7538. JS_REENTRANT_UNLOCK(jsReentLock,
  7539. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7540. element,
  7541. JavascriptNumber::ToVar(k, scriptContext),
  7542. typedArrayBase));
  7543. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7544. {
  7545. return scriptContext->GetLibrary()->GetTrue();
  7546. }
  7547. }
  7548. }
  7549. else
  7550. {
  7551. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SomeObjectHelper<T>(obj, length, 0u, callBackFn, thisArg, scriptContext));
  7552. }
  7553. return scriptContext->GetLibrary()->GetFalse();
  7554. }
  7555. template <typename T>
  7556. Var JavascriptArray::SomeObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
  7557. {
  7558. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7559. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7560. CallFlags flags = CallFlags_Value;
  7561. Var element = nullptr;
  7562. Var testResult = nullptr;
  7563. for (T k = start; k < length; k++)
  7564. {
  7565. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  7566. if (hasItem)
  7567. {
  7568. JS_REENTRANT_UNLOCK(jsReentLock,
  7569. element = JavascriptOperators::GetItem(obj, k, scriptContext),
  7570. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7571. element,
  7572. JavascriptNumber::ToVar(k, scriptContext),
  7573. obj));
  7574. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7575. {
  7576. return scriptContext->GetLibrary()->GetTrue();
  7577. }
  7578. }
  7579. }
  7580. return scriptContext->GetLibrary()->GetFalse();
  7581. }
  7582. Var JavascriptArray::EntryForEach(RecyclableObject* function, CallInfo callInfo, ...)
  7583. {
  7584. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7585. ARGUMENTS(args, callInfo);
  7586. ScriptContext* scriptContext = function->GetScriptContext();
  7587. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7588. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.forEach"));
  7589. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_forEach)
  7590. Assert(!(callInfo.Flags & CallFlags_New));
  7591. if (args.Info.Count == 0)
  7592. {
  7593. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.forEach"));
  7594. }
  7595. BigIndex length;
  7596. JavascriptArray* pArr = nullptr;
  7597. RecyclableObject* dynamicObject = nullptr;
  7598. RecyclableObject* callBackFn = nullptr;
  7599. Var thisArg = nullptr;
  7600. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.forEach"), &pArr, &dynamicObject, &length));
  7601. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  7602. {
  7603. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.forEach"));
  7604. }
  7605. callBackFn = RecyclableObject::FromVar(args[1]);
  7606. if (args.Info.Count > 2)
  7607. {
  7608. thisArg = args[2];
  7609. }
  7610. else
  7611. {
  7612. thisArg = scriptContext->GetLibrary()->GetUndefined();
  7613. }
  7614. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7615. CallFlags flags = CallFlags_Value;
  7616. auto fn32 = [dynamicObject, callBackFn, flags, thisArg,
  7617. scriptContext](uint32 k, Var element)
  7618. {
  7619. CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7620. element,
  7621. JavascriptNumber::ToVar(k, scriptContext),
  7622. dynamicObject);
  7623. };
  7624. auto fn64 = [dynamicObject, callBackFn, flags, thisArg,
  7625. scriptContext](uint64 k, Var element)
  7626. {
  7627. CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7628. element,
  7629. JavascriptNumber::ToVar(k, scriptContext),
  7630. dynamicObject);
  7631. };
  7632. if (pArr)
  7633. {
  7634. Assert(pArr == dynamicObject);
  7635. JS_REENTRANT(jsReentLock, pArr->ForEachItemInRange<true>(0, length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex(), scriptContext, fn32));
  7636. }
  7637. else
  7638. {
  7639. if (length.IsSmallIndex())
  7640. {
  7641. JS_REENTRANT(jsReentLock, TemplatedForEachItemInRange<true>(dynamicObject, 0u, length.GetSmallIndex(), scriptContext, fn32));
  7642. }
  7643. else
  7644. {
  7645. JS_REENTRANT(jsReentLock, TemplatedForEachItemInRange<true>(dynamicObject, 0ui64, length.GetBigIndex(), scriptContext, fn64));
  7646. }
  7647. }
  7648. return scriptContext->GetLibrary()->GetUndefined();
  7649. }
  7650. Var JavascriptArray::EntryCopyWithin(RecyclableObject* function, CallInfo callInfo, ...)
  7651. {
  7652. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7653. ARGUMENTS(args, callInfo);
  7654. ScriptContext* scriptContext = function->GetScriptContext();
  7655. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7656. Assert(!(callInfo.Flags & CallFlags_New));
  7657. RecyclableObject* obj = nullptr;
  7658. JavascriptArray* pArr = nullptr;
  7659. int64 length;
  7660. JS_REENTRANT_UNLOCK(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.copyWithin"), &pArr, &obj, &length));
  7661. return JavascriptArray::CopyWithinHelper(pArr, nullptr, obj, length, args, scriptContext);
  7662. }
  7663. // Array.prototype.copyWithin as defined in ES6.0 (draft 22) Section 22.1.3.3
  7664. Var JavascriptArray::CopyWithinHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
  7665. {
  7666. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7667. Assert(args.Info.Count > 0);
  7668. JavascriptLibrary* library = scriptContext->GetLibrary();
  7669. int64 fromVal = 0;
  7670. int64 toVal = 0;
  7671. int64 finalVal = length;
  7672. // If we came from Array.prototype.copyWithin and source object is not a JavascriptArray, source could be a TypedArray
  7673. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  7674. {
  7675. typedArrayBase = TypedArrayBase::FromVar(obj);
  7676. }
  7677. if (args.Info.Count > 1)
  7678. {
  7679. JS_REENTRANT(jsReentLock, toVal = JavascriptArray::GetIndexFromVar(args[1], length, scriptContext));
  7680. if (args.Info.Count > 2)
  7681. {
  7682. JS_REENTRANT(jsReentLock, fromVal = JavascriptArray::GetIndexFromVar(args[2], length, scriptContext));
  7683. if (args.Info.Count > 3 && args[3] != library->GetUndefined())
  7684. {
  7685. JS_REENTRANT(jsReentLock, finalVal = JavascriptArray::GetIndexFromVar(args[3], length, scriptContext));
  7686. }
  7687. }
  7688. }
  7689. // If count would be negative or zero, we won't do anything so go ahead and return early.
  7690. if (finalVal <= fromVal || length <= toVal)
  7691. {
  7692. return obj;
  7693. }
  7694. // Make sure we won't underflow during the count calculation
  7695. Assert(finalVal > fromVal && length > toVal);
  7696. int64 count = min(finalVal - fromVal, length - toVal);
  7697. // We shouldn't have made it here if the count was going to be zero
  7698. Assert(count > 0);
  7699. int direction;
  7700. if (fromVal < toVal && toVal < (fromVal + count))
  7701. {
  7702. direction = -1;
  7703. fromVal += count - 1;
  7704. toVal += count - 1;
  7705. }
  7706. else
  7707. {
  7708. direction = 1;
  7709. }
  7710. // Side effects (such as defining a property in a ToPrimitive call) during evaluation of arguments may convert the array to an ES5 array.
  7711. if (pArr && !JavascriptArray::Is(obj))
  7712. {
  7713. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  7714. pArr = nullptr;
  7715. }
  7716. // If we are going to copy elements from or to indices > 2^32-1 we'll execute this (slightly slower path)
  7717. // It's possible to optimize here so that we use the normal code below except for the > 2^32-1 indices
  7718. if ((direction == -1 && (fromVal >= MaxArrayLength || toVal >= MaxArrayLength))
  7719. || (((fromVal + count) > MaxArrayLength) || ((toVal + count) > MaxArrayLength)))
  7720. {
  7721. while (count > 0)
  7722. {
  7723. Var index = JavascriptNumber::ToVar(fromVal, scriptContext);
  7724. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::OP_HasItem(obj, index, scriptContext));
  7725. if (hasItem)
  7726. {
  7727. Var val = nullptr;
  7728. JS_REENTRANT(jsReentLock,
  7729. val = JavascriptOperators::OP_GetElementI(obj, index, scriptContext),
  7730. JavascriptOperators::OP_SetElementI(obj, JavascriptNumber::ToVar(toVal, scriptContext), val, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  7731. }
  7732. else
  7733. {
  7734. JavascriptOperators::OP_DeleteElementI(obj, JavascriptNumber::ToVar(toVal, scriptContext), scriptContext, PropertyOperation_ThrowOnDeleteIfNotConfig);
  7735. }
  7736. fromVal += direction;
  7737. toVal += direction;
  7738. count--;
  7739. }
  7740. }
  7741. else
  7742. {
  7743. Assert(fromVal < MaxArrayLength);
  7744. Assert(toVal < MaxArrayLength);
  7745. Assert(direction == -1 || (fromVal + count < MaxArrayLength && toVal + count < MaxArrayLength));
  7746. uint32 fromIndex = static_cast<uint32>(fromVal);
  7747. uint32 toIndex = static_cast<uint32>(toVal);
  7748. while (count > 0)
  7749. {
  7750. JS_REENTRANT(jsReentLock, BOOL hasItem = obj->HasItem(fromIndex));
  7751. if (hasItem)
  7752. {
  7753. if (typedArrayBase)
  7754. {
  7755. Var val = typedArrayBase->DirectGetItem(fromIndex);
  7756. JS_REENTRANT(jsReentLock, typedArrayBase->DirectSetItem(toIndex, val));
  7757. }
  7758. else if (pArr)
  7759. {
  7760. JS_REENTRANT(jsReentLock, Var val = pArr->DirectGetItem(fromIndex));
  7761. pArr->SetItem(toIndex, val, Js::PropertyOperation_ThrowIfNotExtensible);
  7762. if (!JavascriptArray::Is(obj))
  7763. {
  7764. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  7765. pArr = nullptr;
  7766. }
  7767. }
  7768. else
  7769. {
  7770. Var val = nullptr;
  7771. JS_REENTRANT(jsReentLock,
  7772. val = JavascriptOperators::OP_GetElementI_UInt32(obj, fromIndex, scriptContext),
  7773. JavascriptOperators::OP_SetElementI_UInt32(obj, toIndex, val, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  7774. }
  7775. }
  7776. else
  7777. {
  7778. obj->DeleteItem(toIndex, PropertyOperation_ThrowOnDeleteIfNotConfig);
  7779. }
  7780. fromIndex += direction;
  7781. toIndex += direction;
  7782. count--;
  7783. }
  7784. }
  7785. return obj;
  7786. }
  7787. Var JavascriptArray::EntryFill(RecyclableObject* function, CallInfo callInfo, ...)
  7788. {
  7789. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7790. ARGUMENTS(args, callInfo);
  7791. ScriptContext* scriptContext = function->GetScriptContext();
  7792. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7793. Assert(!(callInfo.Flags & CallFlags_New));
  7794. RecyclableObject* obj = nullptr;
  7795. JavascriptArray* pArr = nullptr;
  7796. int64 length;
  7797. JS_REENTRANT_UNLOCK(jsReentLock,
  7798. TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.fill"), &pArr, &obj, &length));
  7799. return JavascriptArray::FillHelper(pArr, nullptr, obj, length, args, scriptContext);
  7800. }
  7801. // Array.prototype.fill as defined in ES6.0 (draft 22) Section 22.1.3.6
  7802. Var JavascriptArray::FillHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
  7803. {
  7804. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7805. Assert(args.Info.Count > 0);
  7806. JavascriptLibrary* library = scriptContext->GetLibrary();
  7807. // If we came from Array.prototype.fill and source object is not a JavascriptArray, source could be a TypedArray
  7808. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  7809. {
  7810. typedArrayBase = TypedArrayBase::FromVar(obj);
  7811. }
  7812. Var fillValue;
  7813. if (args.Info.Count > 1)
  7814. {
  7815. fillValue = args[1];
  7816. }
  7817. else
  7818. {
  7819. fillValue = library->GetUndefined();
  7820. }
  7821. int64 k = 0;
  7822. int64 finalVal = length;
  7823. if (args.Info.Count > 2)
  7824. {
  7825. JS_REENTRANT_UNLOCK(jsReentLock, k = JavascriptArray::GetIndexFromVar(args[2], length, scriptContext));
  7826. if (args.Info.Count > 3 && !JavascriptOperators::IsUndefinedObject(args[3]))
  7827. {
  7828. JS_REENTRANT_UNLOCK(jsReentLock, finalVal = JavascriptArray::GetIndexFromVar(args[3], length, scriptContext));
  7829. }
  7830. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  7831. // we will process the array elements like an ES5Array.
  7832. if (pArr && !JavascriptArray::Is(obj))
  7833. {
  7834. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  7835. pArr = nullptr;
  7836. }
  7837. }
  7838. if (k < MaxArrayLength)
  7839. {
  7840. int64 end = min<int64>(finalVal, MaxArrayLength);
  7841. uint32 u32k = static_cast<uint32>(k);
  7842. while (u32k < end)
  7843. {
  7844. if (typedArrayBase)
  7845. {
  7846. JS_REENTRANT(jsReentLock, typedArrayBase->DirectSetItem(u32k, fillValue));
  7847. }
  7848. else if (pArr)
  7849. {
  7850. pArr->SetItem(u32k, fillValue, PropertyOperation_ThrowIfNotExtensible);
  7851. }
  7852. else
  7853. {
  7854. JS_REENTRANT(jsReentLock,
  7855. JavascriptOperators::OP_SetElementI_UInt32(obj, u32k, fillValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible));
  7856. }
  7857. u32k++;
  7858. }
  7859. BigIndex dstIndex = MaxArrayLength;
  7860. for (int64 i = end; i < finalVal; ++i)
  7861. {
  7862. if (pArr)
  7863. {
  7864. pArr->DirectSetItemAt(dstIndex, fillValue);
  7865. ++dstIndex;
  7866. }
  7867. else
  7868. {
  7869. JS_REENTRANT(jsReentLock,
  7870. JavascriptOperators::OP_SetElementI(obj, JavascriptNumber::ToVar(i, scriptContext), fillValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible));
  7871. }
  7872. }
  7873. }
  7874. else
  7875. {
  7876. BigIndex dstIndex = static_cast<uint64>(k);
  7877. for (int64 i = k; i < finalVal; i++)
  7878. {
  7879. if (pArr)
  7880. {
  7881. pArr->DirectSetItemAt(dstIndex, fillValue);
  7882. ++dstIndex;
  7883. }
  7884. else
  7885. {
  7886. JS_REENTRANT(jsReentLock,
  7887. JavascriptOperators::OP_SetElementI(obj, JavascriptNumber::ToVar(i, scriptContext), fillValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible));
  7888. }
  7889. }
  7890. }
  7891. return obj;
  7892. }
  7893. // Array.prototype.map as defined by ES6.0 (Final) 22.1.3.15
  7894. Var JavascriptArray::EntryMap(RecyclableObject* function, CallInfo callInfo, ...)
  7895. {
  7896. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7897. ARGUMENTS(args, callInfo);
  7898. ScriptContext* scriptContext = function->GetScriptContext();
  7899. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7900. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.map"));
  7901. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_map);
  7902. Assert(!(callInfo.Flags & CallFlags_New));
  7903. if (args.Info.Count == 0)
  7904. {
  7905. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.map"));
  7906. }
  7907. BigIndex length;
  7908. JavascriptArray* pArr = nullptr;
  7909. RecyclableObject* obj = nullptr;
  7910. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.map"), &pArr, &obj, &length));
  7911. if (length.IsSmallIndex())
  7912. {
  7913. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::MapHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  7914. }
  7915. 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
  7916. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::MapHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  7917. }
  7918. template<typename T>
  7919. Var JavascriptArray::MapHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  7920. {
  7921. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7922. RecyclableObject* newObj = nullptr;
  7923. JavascriptArray* newArr = nullptr;
  7924. bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
  7925. bool isBuiltinArrayCtor = true;
  7926. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  7927. {
  7928. if (isTypedArrayEntryPoint)
  7929. {
  7930. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.map"));
  7931. }
  7932. else
  7933. {
  7934. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.map"));
  7935. }
  7936. }
  7937. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  7938. Var thisArg;
  7939. if (args.Info.Count > 2)
  7940. {
  7941. thisArg = args[2];
  7942. }
  7943. else
  7944. {
  7945. thisArg = scriptContext->GetLibrary()->GetUndefined();
  7946. }
  7947. // If we came from Array.prototype.map and source object is not a JavascriptArray, source could be a TypedArray
  7948. if (!isTypedArrayEntryPoint && pArr == nullptr && TypedArrayBase::Is(obj))
  7949. {
  7950. typedArrayBase = TypedArrayBase::FromVar(obj);
  7951. }
  7952. // 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
  7953. // and use it to construct the return object.
  7954. if (isTypedArrayEntryPoint)
  7955. {
  7956. JS_REENTRANT(jsReentLock,
  7957. Var constructor = JavascriptOperators::SpeciesConstructor(
  7958. typedArrayBase, TypedArrayBase::GetDefaultConstructor(args[0], scriptContext), scriptContext));
  7959. isBuiltinArrayCtor = false;
  7960. Assert(JavascriptOperators::IsConstructor(constructor));
  7961. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(length, scriptContext) };
  7962. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  7963. JS_REENTRANT(jsReentLock, newObj = RecyclableObject::FromVar(TypedArrayBase::TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), (uint32)length, scriptContext)));
  7964. }
  7965. // skip the typed array and "pure" array case, we still need to handle special arrays like es5array, remote array, and proxy of array.
  7966. else if (pArr == nullptr || scriptContext->GetConfig()->IsES6SpeciesEnabled())
  7967. {
  7968. JS_REENTRANT(jsReentLock, newObj = ArraySpeciesCreate(obj, length, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor));
  7969. }
  7970. if (newObj == nullptr)
  7971. {
  7972. if (length > UINT_MAX)
  7973. {
  7974. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  7975. }
  7976. newArr = scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(length));
  7977. newArr->EnsureHead<Var>();
  7978. newObj = newArr;
  7979. }
  7980. else
  7981. {
  7982. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  7983. if (JavascriptArray::Is(newObj))
  7984. {
  7985. #if ENABLE_COPYONACCESS_ARRAY
  7986. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
  7987. #endif
  7988. newArr = JavascriptArray::FromVar(newObj);
  7989. }
  7990. }
  7991. Var element = nullptr;
  7992. Var mappedValue = nullptr;
  7993. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7994. CallFlags callBackFnflags = CallFlags_Value;
  7995. CallInfo callBackFnInfo = CallInfo(callBackFnflags, 4);
  7996. // We at least have to have newObj as a valid object
  7997. Assert(newObj);
  7998. // The ArraySpeciesCreate call above could have converted the source array into an ES5Array. If this happens
  7999. // we will process the array elements like an ES5Array.
  8000. if (pArr && !JavascriptArray::Is(obj))
  8001. {
  8002. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  8003. pArr = nullptr;
  8004. }
  8005. if (pArr != nullptr)
  8006. {
  8007. // If source is a JavascriptArray, newObj may or may not be an array based on what was in source's constructor property
  8008. Assert(length <= UINT_MAX);
  8009. for (uint32 k = 0; k < (uint32)length; k++)
  8010. {
  8011. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(k, &element));
  8012. if (!gotItem)
  8013. {
  8014. continue;
  8015. }
  8016. JS_REENTRANT(jsReentLock,
  8017. mappedValue = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, callBackFnInfo, thisArg,
  8018. element,
  8019. JavascriptNumber::ToVar(k, scriptContext),
  8020. pArr));
  8021. // If newArr is a valid pointer, then we constructed an array to return. Otherwise we need to do generic object operations
  8022. if (newArr && isBuiltinArrayCtor)
  8023. {
  8024. newArr->DirectSetItemAt(k, mappedValue);
  8025. }
  8026. else
  8027. {
  8028. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, k, mappedValue), scriptContext, k));
  8029. }
  8030. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  8031. // we will process the rest of the array elements like an ES5Array.
  8032. if (!JavascriptArray::Is(obj))
  8033. {
  8034. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  8035. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::MapObjectHelper<T>(obj, length, k + 1, newObj, newArr, isBuiltinArrayCtor, callBackFn, thisArg, scriptContext));
  8036. }
  8037. }
  8038. }
  8039. else if (typedArrayBase != nullptr)
  8040. {
  8041. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  8042. // Source is a TypedArray, we may have tried to call a constructor, but newObj may not be a TypedArray (or an array either)
  8043. TypedArrayBase* newTypedArray = nullptr;
  8044. if (TypedArrayBase::Is(newObj))
  8045. {
  8046. newTypedArray = TypedArrayBase::FromVar(newObj);
  8047. }
  8048. else
  8049. {
  8050. AssertAndFailFast(newArr != nullptr);
  8051. }
  8052. Assert(length <= UINT_MAX);
  8053. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  8054. for (uint32 k = 0; k < end; k++)
  8055. {
  8056. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  8057. element = typedArrayBase->DirectGetItem(k);
  8058. JS_REENTRANT(jsReentLock,
  8059. mappedValue = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, callBackFnInfo, thisArg,
  8060. element,
  8061. JavascriptNumber::ToVar(k, scriptContext),
  8062. obj));
  8063. // If newObj is a TypedArray, set the mappedValue directly, otherwise it should be an array, set that item to that array
  8064. if (newTypedArray)
  8065. {
  8066. JS_REENTRANT(jsReentLock, newTypedArray->DirectSetItem(k, mappedValue));
  8067. }
  8068. else
  8069. {
  8070. newArr->SetItem(k, mappedValue, PropertyOperation_None);
  8071. }
  8072. }
  8073. }
  8074. else
  8075. {
  8076. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::MapObjectHelper<T>(obj, length, 0u, newObj, newArr, isBuiltinArrayCtor, callBackFn, thisArg, scriptContext));
  8077. }
  8078. #ifdef VALIDATE_ARRAY
  8079. if (JavascriptArray::Is(newObj))
  8080. {
  8081. newArr->ValidateArray();
  8082. }
  8083. #endif
  8084. return newObj;
  8085. }
  8086. template<typename T>
  8087. Var JavascriptArray::MapObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* newObj, JavascriptArray* newArr,
  8088. bool isBuiltinArrayCtor, RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
  8089. {
  8090. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8091. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8092. CallFlags callBackFnflags = CallFlags_Value;
  8093. CallInfo callBackFnInfo = CallInfo(callBackFnflags, 4);
  8094. Var element = nullptr;
  8095. Var mappedValue = nullptr;
  8096. for (T k = start; k < length; k++)
  8097. {
  8098. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  8099. if (hasItem)
  8100. {
  8101. JS_REENTRANT(jsReentLock,
  8102. element = JavascriptOperators::GetItem(obj, k, scriptContext),
  8103. mappedValue = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, callBackFnInfo, thisArg,
  8104. element,
  8105. JavascriptNumber::ToVar(k, scriptContext),
  8106. obj));
  8107. if (newArr && isBuiltinArrayCtor)
  8108. {
  8109. newArr->SetItem((uint32)k, mappedValue, PropertyOperation_None);
  8110. }
  8111. else
  8112. {
  8113. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, BigIndex(k), mappedValue), scriptContext, BigIndex(k)));
  8114. }
  8115. }
  8116. }
  8117. #ifdef VALIDATE_ARRAY
  8118. if (JavascriptArray::Is(newObj))
  8119. {
  8120. newArr->ValidateArray();
  8121. }
  8122. #endif
  8123. return newObj;
  8124. }
  8125. Var JavascriptArray::EntryFilter(RecyclableObject* function, CallInfo callInfo, ...)
  8126. {
  8127. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8128. ARGUMENTS(args, callInfo);
  8129. ScriptContext* scriptContext = function->GetScriptContext();
  8130. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8131. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.filter"));
  8132. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_filter);
  8133. Assert(!(callInfo.Flags & CallFlags_New));
  8134. if (args.Info.Count == 0)
  8135. {
  8136. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.filter"));
  8137. }
  8138. BigIndex length;
  8139. JavascriptArray* pArr = nullptr;
  8140. RecyclableObject* obj = nullptr;
  8141. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.filter"), &pArr, &obj, &length));
  8142. if (length.IsSmallIndex())
  8143. {
  8144. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FilterHelper(pArr, obj, length.GetSmallIndex(), args, scriptContext));
  8145. }
  8146. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FilterHelper(pArr, obj, length.GetBigIndex(), args, scriptContext));
  8147. }
  8148. template <typename T>
  8149. Var JavascriptArray::FilterHelper(JavascriptArray* pArr, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  8150. {
  8151. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8152. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  8153. {
  8154. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.filter"));
  8155. }
  8156. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  8157. Var thisArg = nullptr;
  8158. if (args.Info.Count > 2)
  8159. {
  8160. thisArg = args[2];
  8161. }
  8162. else
  8163. {
  8164. thisArg = scriptContext->GetLibrary()->GetUndefined();
  8165. }
  8166. // 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.
  8167. bool isBuiltinArrayCtor = true;
  8168. JS_REENTRANT(jsReentLock, RecyclableObject* newObj = ArraySpeciesCreate(obj, 0, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor));
  8169. JavascriptArray* newArr = nullptr;
  8170. if (newObj == nullptr)
  8171. {
  8172. newArr = scriptContext->GetLibrary()->CreateArray(0);
  8173. newArr->EnsureHead<Var>();
  8174. newObj = newArr;
  8175. }
  8176. else
  8177. {
  8178. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  8179. if (JavascriptArray::Is(newObj))
  8180. {
  8181. #if ENABLE_COPYONACCESS_ARRAY
  8182. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
  8183. #endif
  8184. newArr = JavascriptArray::FromVar(newObj);
  8185. }
  8186. }
  8187. // The ArraySpeciesCreate call above could have converted the source array into an ES5Array. If this happens
  8188. // we will process the array elements like an ES5Array.
  8189. if (pArr && !JavascriptArray::Is(obj))
  8190. {
  8191. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  8192. pArr = nullptr;
  8193. }
  8194. Var element = nullptr;
  8195. Var selected = nullptr;
  8196. if (pArr)
  8197. {
  8198. Assert(length <= MaxArrayLength);
  8199. uint32 i = 0;
  8200. Assert(length <= UINT_MAX);
  8201. for (uint32 k = 0; k < (uint32)length; k++)
  8202. {
  8203. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(k, &element));
  8204. if (!gotItem)
  8205. {
  8206. continue;
  8207. }
  8208. JS_REENTRANT(jsReentLock,
  8209. selected = CALL_ENTRYPOINT(scriptContext->GetThreadContext(),
  8210. callBackFn->GetEntryPoint(), callBackFn, CallInfo(CallFlags_Value, 4),
  8211. thisArg,
  8212. element,
  8213. JavascriptNumber::ToVar(k, scriptContext),
  8214. pArr));
  8215. if (JavascriptConversion::ToBoolean(selected, scriptContext))
  8216. {
  8217. // Try to fast path if the return object is an array
  8218. if (newArr && isBuiltinArrayCtor)
  8219. {
  8220. newArr->DirectSetItemAt(i, element);
  8221. }
  8222. else
  8223. {
  8224. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i));
  8225. }
  8226. ++i;
  8227. }
  8228. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  8229. // we will process the rest of the array elements like an ES5Array.
  8230. if (!JavascriptArray::Is(obj))
  8231. {
  8232. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  8233. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FilterObjectHelper<T>(obj, length, k + 1, newArr, newObj, i, callBackFn, thisArg, scriptContext));
  8234. }
  8235. }
  8236. }
  8237. else
  8238. {
  8239. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FilterObjectHelper<T>(obj, length, 0u, newArr, newObj, 0u, callBackFn, thisArg, scriptContext));
  8240. }
  8241. #ifdef VALIDATE_ARRAY
  8242. if (newArr)
  8243. {
  8244. newArr->ValidateArray();
  8245. }
  8246. #endif
  8247. return newObj;
  8248. }
  8249. template <typename T>
  8250. Var JavascriptArray::FilterObjectHelper(RecyclableObject* obj, T length, T start, JavascriptArray* newArr, RecyclableObject* newObj, T newStart,
  8251. RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
  8252. {
  8253. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8254. Var element = nullptr;
  8255. Var selected = nullptr;
  8256. BigIndex i = BigIndex(newStart);
  8257. for (T k = start; k < length; k++)
  8258. {
  8259. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  8260. if (hasItem)
  8261. {
  8262. JS_REENTRANT(jsReentLock,
  8263. element = JavascriptOperators::GetItem(obj, k, scriptContext),
  8264. selected = CALL_ENTRYPOINT(scriptContext->GetThreadContext(),
  8265. callBackFn->GetEntryPoint(), callBackFn, CallInfo(CallFlags_Value, 4),
  8266. thisArg,
  8267. element,
  8268. JavascriptNumber::ToVar(k, scriptContext),
  8269. obj));
  8270. if (JavascriptConversion::ToBoolean(selected, scriptContext))
  8271. {
  8272. if (newArr)
  8273. {
  8274. newArr->DirectSetItemAt(i, element);
  8275. }
  8276. else
  8277. {
  8278. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i));
  8279. }
  8280. ++i;
  8281. }
  8282. }
  8283. }
  8284. #ifdef VALIDATE_ARRAY
  8285. if (newArr)
  8286. {
  8287. newArr->ValidateArray();
  8288. }
  8289. #endif
  8290. return newObj;
  8291. }
  8292. Var JavascriptArray::EntryReduce(RecyclableObject* function, CallInfo callInfo, ...)
  8293. {
  8294. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8295. ARGUMENTS(args, callInfo);
  8296. ScriptContext* scriptContext = function->GetScriptContext();
  8297. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8298. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.reduce"));
  8299. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_reduce);
  8300. Assert(!(callInfo.Flags & CallFlags_New));
  8301. if (args.Info.Count == 0)
  8302. {
  8303. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reduce"));
  8304. }
  8305. BigIndex length;
  8306. JavascriptArray * pArr = nullptr;
  8307. RecyclableObject* obj = nullptr;
  8308. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.reduce"), &pArr, &obj, &length));
  8309. if (length.IsSmallIndex())
  8310. {
  8311. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  8312. }
  8313. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  8314. }
  8315. // Array.prototype.reduce as described in ES6.0 (draft 22) Section 22.1.3.18
  8316. template <typename T>
  8317. Var JavascriptArray::ReduceHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  8318. {
  8319. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8320. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  8321. {
  8322. if (typedArrayBase != nullptr)
  8323. {
  8324. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.reduce"));
  8325. }
  8326. else
  8327. {
  8328. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.reduce"));
  8329. }
  8330. }
  8331. // If we came from Array.prototype.reduce and source object is not a JavascriptArray, source could be a TypedArray
  8332. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  8333. {
  8334. typedArrayBase = TypedArrayBase::FromVar(obj);
  8335. }
  8336. T k = 0;
  8337. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  8338. Var accumulator = nullptr;
  8339. Var element = nullptr;
  8340. if (args.Info.Count > 2)
  8341. {
  8342. accumulator = args[2];
  8343. }
  8344. else
  8345. {
  8346. if (length == 0)
  8347. {
  8348. JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
  8349. }
  8350. bool bPresent = false;
  8351. if (pArr)
  8352. {
  8353. for (; k < length && bPresent == false; k++)
  8354. {
  8355. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull((uint32)k, &element));
  8356. if (!gotItem)
  8357. {
  8358. continue;
  8359. }
  8360. bPresent = true;
  8361. accumulator = element;
  8362. }
  8363. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  8364. // we will process the array elements like an ES5Array.
  8365. if (!JavascriptArray::Is(obj))
  8366. {
  8367. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  8368. pArr = nullptr;
  8369. }
  8370. }
  8371. else if (typedArrayBase)
  8372. {
  8373. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  8374. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  8375. for (; k < end && bPresent == false; k++)
  8376. {
  8377. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  8378. element = typedArrayBase->DirectGetItem((uint32)k);
  8379. bPresent = true;
  8380. accumulator = element;
  8381. }
  8382. }
  8383. else
  8384. {
  8385. for (; k < length && bPresent == false; k++)
  8386. {
  8387. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  8388. if (hasItem)
  8389. {
  8390. JS_REENTRANT(jsReentLock, accumulator = JavascriptOperators::GetItem(obj, k, scriptContext));
  8391. bPresent = true;
  8392. }
  8393. }
  8394. }
  8395. if (bPresent == false)
  8396. {
  8397. JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
  8398. }
  8399. }
  8400. Assert(accumulator);
  8401. Var undefinedValue = scriptContext->GetLibrary()->GetUndefined();
  8402. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8403. CallFlags flags = CallFlags_Value;
  8404. if (pArr)
  8405. {
  8406. for (; k < length; k++)
  8407. {
  8408. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull((uint32)k, &element));
  8409. if (!gotItem)
  8410. {
  8411. continue;
  8412. }
  8413. JS_REENTRANT(jsReentLock,
  8414. accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 5), undefinedValue,
  8415. accumulator,
  8416. element,
  8417. JavascriptNumber::ToVar(k, scriptContext),
  8418. pArr));
  8419. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  8420. // we will process the rest of the array elements like an ES5Array.
  8421. if (!JavascriptArray::Is(obj))
  8422. {
  8423. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  8424. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceObjectHelper<T>(obj, length, k + 1, callBackFn, accumulator, scriptContext));
  8425. }
  8426. }
  8427. }
  8428. else if (typedArrayBase)
  8429. {
  8430. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  8431. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  8432. for (; k < end; k++)
  8433. {
  8434. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  8435. element = typedArrayBase->DirectGetItem((uint32)k);
  8436. JS_REENTRANT(jsReentLock,
  8437. accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 5), undefinedValue,
  8438. accumulator,
  8439. element,
  8440. JavascriptNumber::ToVar(k, scriptContext),
  8441. typedArrayBase));
  8442. }
  8443. }
  8444. else
  8445. {
  8446. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceObjectHelper<T>(obj, length, k, callBackFn, accumulator, scriptContext));
  8447. }
  8448. return accumulator;
  8449. }
  8450. template <typename T>
  8451. Var JavascriptArray::ReduceObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* callBackFn, Var accumulator, ScriptContext* scriptContext)
  8452. {
  8453. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8454. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8455. CallFlags flags = CallFlags_Value;
  8456. Var element = nullptr;
  8457. for (T k = start; k < length; k++)
  8458. {
  8459. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  8460. if (hasItem)
  8461. {
  8462. JS_REENTRANT(jsReentLock,
  8463. element = JavascriptOperators::GetItem(obj, k, scriptContext),
  8464. accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 5), scriptContext->GetLibrary()->GetUndefined(),
  8465. accumulator,
  8466. element,
  8467. JavascriptNumber::ToVar(k, scriptContext),
  8468. obj));
  8469. }
  8470. }
  8471. return accumulator;
  8472. }
  8473. Var JavascriptArray::EntryReduceRight(RecyclableObject* function, CallInfo callInfo, ...)
  8474. {
  8475. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8476. ARGUMENTS(args, callInfo);
  8477. ScriptContext* scriptContext = function->GetScriptContext();
  8478. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8479. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.reduceRight"));
  8480. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_reduceRight);
  8481. Assert(!(callInfo.Flags & CallFlags_New));
  8482. if (args.Info.Count == 0)
  8483. {
  8484. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reduceRight"));
  8485. }
  8486. BigIndex length;
  8487. JavascriptArray * pArr = nullptr;
  8488. RecyclableObject* obj = nullptr;
  8489. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.reduceRight"), &pArr, &obj, &length));
  8490. if (length.IsSmallIndex())
  8491. {
  8492. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceRightHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  8493. }
  8494. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceRightHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  8495. }
  8496. // Array.prototype.reduceRight as described in ES6.0 (draft 22) Section 22.1.3.19
  8497. template <typename T>
  8498. Var JavascriptArray::ReduceRightHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  8499. {
  8500. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8501. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  8502. {
  8503. if (typedArrayBase != nullptr)
  8504. {
  8505. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.reduceRight"));
  8506. }
  8507. else
  8508. {
  8509. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.reduceRight"));
  8510. }
  8511. }
  8512. // If we came from Array.prototype.reduceRight and source object is not a JavascriptArray, source could be a TypedArray
  8513. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  8514. {
  8515. typedArrayBase = TypedArrayBase::FromVar(obj);
  8516. }
  8517. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  8518. Var accumulator = nullptr;
  8519. Var element = nullptr;
  8520. T k = 0;
  8521. T index = 0;
  8522. if (args.Info.Count > 2)
  8523. {
  8524. accumulator = args[2];
  8525. }
  8526. else
  8527. {
  8528. if (length == 0)
  8529. {
  8530. JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
  8531. }
  8532. bool bPresent = false;
  8533. if (pArr)
  8534. {
  8535. for (; k < length && bPresent == false; k++)
  8536. {
  8537. index = length - k - 1;
  8538. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull((uint32)index, &element));
  8539. if (!gotItem)
  8540. {
  8541. continue;
  8542. }
  8543. bPresent = true;
  8544. accumulator = element;
  8545. }
  8546. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  8547. // we will process the array elements like an ES5Array.
  8548. if (!JavascriptArray::Is(obj))
  8549. {
  8550. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  8551. pArr = nullptr;
  8552. }
  8553. }
  8554. else if (typedArrayBase)
  8555. {
  8556. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  8557. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  8558. for (; k < end && bPresent == false; k++)
  8559. {
  8560. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  8561. index = length - k - 1;
  8562. element = typedArrayBase->DirectGetItem((uint32)index);
  8563. bPresent = true;
  8564. accumulator = element;
  8565. }
  8566. }
  8567. else
  8568. {
  8569. for (; k < length && bPresent == false; k++)
  8570. {
  8571. index = length - k - 1;
  8572. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, index));
  8573. if (hasItem)
  8574. {
  8575. JS_REENTRANT(jsReentLock, accumulator = JavascriptOperators::GetItem(obj, index, scriptContext));
  8576. bPresent = true;
  8577. }
  8578. }
  8579. }
  8580. if (bPresent == false)
  8581. {
  8582. JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
  8583. }
  8584. }
  8585. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8586. CallFlags flags = CallFlags_Value;
  8587. Var undefinedValue = scriptContext->GetLibrary()->GetUndefined();
  8588. if (pArr)
  8589. {
  8590. for (; k < length; k++)
  8591. {
  8592. index = length - k - 1;
  8593. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull((uint32)index, &element));
  8594. if (!gotItem)
  8595. {
  8596. continue;
  8597. }
  8598. JS_REENTRANT(jsReentLock,
  8599. accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 5), undefinedValue,
  8600. accumulator,
  8601. element,
  8602. JavascriptNumber::ToVar(index, scriptContext),
  8603. pArr));
  8604. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  8605. // we will process the rest of the array elements like an ES5Array.
  8606. if (!JavascriptArray::Is(obj))
  8607. {
  8608. AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
  8609. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceRightObjectHelper<T>(obj, length, k + 1, callBackFn, accumulator, scriptContext));
  8610. }
  8611. }
  8612. }
  8613. else if (typedArrayBase)
  8614. {
  8615. AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
  8616. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  8617. for (; k < end; k++)
  8618. {
  8619. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  8620. index = length - k - 1;
  8621. element = typedArrayBase->DirectGetItem((uint32)index);
  8622. JS_REENTRANT(jsReentLock,
  8623. accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 5), undefinedValue,
  8624. accumulator,
  8625. element,
  8626. JavascriptNumber::ToVar(index, scriptContext),
  8627. typedArrayBase));
  8628. }
  8629. }
  8630. else
  8631. {
  8632. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceRightObjectHelper<T>(obj, length, k, callBackFn, accumulator, scriptContext));
  8633. }
  8634. return accumulator;
  8635. }
  8636. template <typename T>
  8637. Var JavascriptArray::ReduceRightObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* callBackFn, Var accumulator, ScriptContext* scriptContext)
  8638. {
  8639. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8640. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8641. CallFlags flags = CallFlags_Value;
  8642. Var element = nullptr;
  8643. T index = 0;
  8644. for (T k = start; k < length; k++)
  8645. {
  8646. index = length - k - 1;
  8647. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, index));
  8648. if (hasItem)
  8649. {
  8650. JS_REENTRANT(jsReentLock,
  8651. element = JavascriptOperators::GetItem(obj, index, scriptContext),
  8652. accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(),
  8653. callBackFn, CallInfo(flags, 5), scriptContext->GetLibrary()->GetUndefined(),
  8654. accumulator,
  8655. element,
  8656. JavascriptNumber::ToVar(index, scriptContext),
  8657. obj));
  8658. }
  8659. }
  8660. return accumulator;
  8661. }
  8662. Var JavascriptArray::EntryFrom(RecyclableObject* function, CallInfo callInfo, ...)
  8663. {
  8664. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8665. ARGUMENTS(args, callInfo);
  8666. ScriptContext* scriptContext = function->GetScriptContext();
  8667. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8668. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.from"));
  8669. Assert(!(callInfo.Flags & CallFlags_New));
  8670. JavascriptLibrary* library = scriptContext->GetLibrary();
  8671. RecyclableObject* constructor = nullptr;
  8672. if (JavascriptOperators::IsConstructor(args[0]))
  8673. {
  8674. constructor = RecyclableObject::FromVar(args[0]);
  8675. }
  8676. RecyclableObject* items = nullptr;
  8677. if (args.Info.Count < 2 || !JavascriptConversion::ToObject(args[1], scriptContext, &items))
  8678. {
  8679. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedObject, _u("Array.from"));
  8680. }
  8681. JavascriptArray* itemsArr = nullptr;
  8682. if (JavascriptArray::Is(items))
  8683. {
  8684. #if ENABLE_COPYONACCESS_ARRAY
  8685. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(items);
  8686. #endif
  8687. itemsArr = JavascriptArray::FromVar(items);
  8688. }
  8689. bool mapping = false;
  8690. JavascriptFunction* mapFn = nullptr;
  8691. Var mapFnThisArg = nullptr;
  8692. if (args.Info.Count >= 3 && !JavascriptOperators::IsUndefinedObject(args[2]))
  8693. {
  8694. if (!JavascriptFunction::Is(args[2]))
  8695. {
  8696. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.from"));
  8697. }
  8698. mapFn = JavascriptFunction::FromVar(args[2]);
  8699. if (args.Info.Count >= 4)
  8700. {
  8701. mapFnThisArg = args[3];
  8702. }
  8703. else
  8704. {
  8705. mapFnThisArg = library->GetUndefined();
  8706. }
  8707. mapping = true;
  8708. }
  8709. RecyclableObject* newObj = nullptr;
  8710. JavascriptArray* newArr = nullptr;
  8711. JS_REENTRANT(jsReentLock, RecyclableObject* iterator = JavascriptOperators::GetIterator(items, scriptContext, true /* optional */));
  8712. if (iterator != nullptr)
  8713. {
  8714. if (constructor)
  8715. {
  8716. Js::Var constructorArgs[] = { constructor };
  8717. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  8718. JS_REENTRANT(jsReentLock, newObj = RecyclableObject::FromVar(JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext)));
  8719. if (JavascriptArray::Is(newObj))
  8720. {
  8721. #if ENABLE_COPYONACCESS_ARRAY
  8722. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
  8723. #endif
  8724. newArr = JavascriptArray::FromVar(newObj);
  8725. }
  8726. }
  8727. else
  8728. {
  8729. newArr = scriptContext->GetLibrary()->CreateArray(0);
  8730. newArr->EnsureHead<Var>();
  8731. newObj = newArr;
  8732. }
  8733. uint32 k = 0;
  8734. JS_REENTRANT(jsReentLock, JavascriptOperators::DoIteratorStepAndValue(iterator, scriptContext, [&](Var nextValue) {
  8735. if (mapping)
  8736. {
  8737. Assert(mapFn != nullptr);
  8738. Assert(mapFnThisArg != nullptr);
  8739. Js::Var mapFnArgs[] = { mapFnThisArg, nextValue, JavascriptNumber::ToVar(k, scriptContext) };
  8740. Js::CallInfo mapFnCallInfo(Js::CallFlags_Value, _countof(mapFnArgs));
  8741. nextValue = mapFn->CallFunction(Js::Arguments(mapFnCallInfo, mapFnArgs));
  8742. }
  8743. if (newArr)
  8744. {
  8745. newArr->SetItem(k, nextValue, PropertyOperation_None);
  8746. }
  8747. else
  8748. {
  8749. ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, k, nextValue), scriptContext, k);
  8750. }
  8751. k++;
  8752. }));
  8753. JS_REENTRANT(jsReentLock, JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(k, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  8754. }
  8755. else
  8756. {
  8757. JS_REENTRANT(jsReentLock, int64 len = (int64)OP_GetLength(items, scriptContext));
  8758. if (constructor)
  8759. {
  8760. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(len, scriptContext) };
  8761. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  8762. JS_REENTRANT(jsReentLock, newObj = RecyclableObject::FromVar(JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext)));
  8763. if (JavascriptArray::Is(newObj))
  8764. {
  8765. #if ENABLE_COPYONACCESS_ARRAY
  8766. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
  8767. #endif
  8768. newArr = JavascriptArray::FromVar(newObj);
  8769. }
  8770. }
  8771. else
  8772. {
  8773. // Abstract operation ArrayCreate throws RangeError if length argument is > 2^32 -1
  8774. if (len > MaxArrayLength)
  8775. {
  8776. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect, _u("Array.from"));
  8777. }
  8778. // Static cast len should be valid (len < 2^32) or we would throw above
  8779. newArr = scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(len));
  8780. newArr->EnsureHead<Var>();
  8781. newObj = newArr;
  8782. }
  8783. uint32 k = 0;
  8784. for ( ; k < len; k++)
  8785. {
  8786. Var kValue;
  8787. if (itemsArr)
  8788. {
  8789. JS_REENTRANT(jsReentLock, kValue = itemsArr->DirectGetItem(k));
  8790. }
  8791. else
  8792. {
  8793. JS_REENTRANT(jsReentLock, kValue = JavascriptOperators::OP_GetElementI_UInt32(items, k, scriptContext));
  8794. }
  8795. if (mapping)
  8796. {
  8797. Assert(mapFn != nullptr);
  8798. Assert(mapFnThisArg != nullptr);
  8799. Js::Var mapFnArgs[] = { mapFnThisArg, kValue, JavascriptNumber::ToVar(k, scriptContext) };
  8800. Js::CallInfo mapFnCallInfo(Js::CallFlags_Value, _countof(mapFnArgs));
  8801. JS_REENTRANT(jsReentLock, kValue = mapFn->CallFunction(Js::Arguments(mapFnCallInfo, mapFnArgs)));
  8802. }
  8803. if (newArr)
  8804. {
  8805. newArr->SetItem(k, kValue, PropertyOperation_None);
  8806. }
  8807. else
  8808. {
  8809. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, k, kValue), scriptContext, k));
  8810. }
  8811. }
  8812. JS_REENTRANT(jsReentLock, JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(len, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  8813. }
  8814. return newObj;
  8815. }
  8816. Var JavascriptArray::EntryOf(RecyclableObject* function, CallInfo callInfo, ...)
  8817. {
  8818. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8819. ARGUMENTS(args, callInfo);
  8820. ScriptContext* scriptContext = function->GetScriptContext();
  8821. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8822. Assert(!(callInfo.Flags & CallFlags_New));
  8823. if (args.Info.Count == 0)
  8824. {
  8825. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.of"));
  8826. }
  8827. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::OfHelper(false, args, scriptContext));
  8828. }
  8829. Var JavascriptArray::EntryGetterSymbolSpecies(RecyclableObject* function, CallInfo callInfo, ...)
  8830. {
  8831. ARGUMENTS(args, callInfo);
  8832. Assert(args.Info.Count > 0);
  8833. return args[0];
  8834. }
  8835. // Array.of and %TypedArray%.of as described in ES6.0 (draft 22) Section 22.1.2.2 and 22.2.2.2
  8836. Var JavascriptArray::OfHelper(bool isTypedArrayEntryPoint, Arguments& args, ScriptContext* scriptContext)
  8837. {
  8838. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8839. Assert(args.Info.Count > 0);
  8840. // args.Info.Count cannot equal zero or we would have thrown above so no chance of underflowing
  8841. uint32 len = args.Info.Count - 1;
  8842. Var newObj = nullptr;
  8843. JavascriptArray* newArr = nullptr;
  8844. TypedArrayBase* newTypedArray = nullptr;
  8845. bool isBuiltinArrayCtor = true;
  8846. if (JavascriptOperators::IsConstructor(args[0]))
  8847. {
  8848. RecyclableObject* constructor = RecyclableObject::FromVar(args[0]);
  8849. isBuiltinArrayCtor = (constructor == scriptContext->GetLibrary()->GetArrayConstructor());
  8850. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(len, scriptContext) };
  8851. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  8852. if (isTypedArrayEntryPoint)
  8853. {
  8854. JS_REENTRANT(jsReentLock, newObj = TypedArrayBase::TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), len, scriptContext));
  8855. }
  8856. else
  8857. {
  8858. JS_REENTRANT(jsReentLock, newObj = JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext));
  8859. }
  8860. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  8861. if (JavascriptArray::Is(newObj))
  8862. {
  8863. #if ENABLE_COPYONACCESS_ARRAY
  8864. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
  8865. #endif
  8866. newArr = JavascriptArray::FromVar(newObj);
  8867. }
  8868. else if (TypedArrayBase::Is(newObj))
  8869. {
  8870. newTypedArray = TypedArrayBase::FromVar(newObj);
  8871. }
  8872. }
  8873. else
  8874. {
  8875. // We only throw when the constructor property is not a constructor function in the TypedArray version
  8876. if (isTypedArrayEntryPoint)
  8877. {
  8878. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedFunction, _u("[TypedArray].of"));
  8879. }
  8880. newArr = scriptContext->GetLibrary()->CreateArray(len);
  8881. newArr->EnsureHead<Var>();
  8882. newObj = newArr;
  8883. }
  8884. // At least we have a new object of some kind
  8885. Assert(newObj);
  8886. if (isBuiltinArrayCtor)
  8887. {
  8888. for (uint32 k = 0; k < len; k++)
  8889. {
  8890. Var kValue = args[k + 1];
  8891. newArr->DirectSetItemAt(k, kValue);
  8892. }
  8893. }
  8894. else if (newTypedArray)
  8895. {
  8896. for (uint32 k = 0; k < len; k++)
  8897. {
  8898. Var kValue = args[k + 1];
  8899. JS_REENTRANT(jsReentLock, newTypedArray->DirectSetItem(k, kValue));
  8900. }
  8901. }
  8902. else
  8903. {
  8904. for (uint32 k = 0; k < len; k++)
  8905. {
  8906. Var kValue = args[k + 1];
  8907. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(RecyclableObject::FromVar(newObj), k, kValue), scriptContext, k));
  8908. }
  8909. }
  8910. if (!isTypedArrayEntryPoint)
  8911. {
  8912. // Set length if we are in the Array version of the function
  8913. JS_REENTRANT(jsReentLock, JavascriptOperators::OP_SetProperty(newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(len, scriptContext), scriptContext, nullptr, PropertyOperation_ThrowIfNotExtensible));
  8914. }
  8915. return newObj;
  8916. }
  8917. JavascriptString* JavascriptArray::ToLocaleStringHelper(Var value, ScriptContext* scriptContext)
  8918. {
  8919. TypeId typeId = JavascriptOperators::GetTypeId(value);
  8920. if (typeId == TypeIds_Null || typeId == TypeIds_Undefined)
  8921. {
  8922. return scriptContext->GetLibrary()->GetEmptyString();
  8923. }
  8924. else
  8925. {
  8926. return JavascriptConversion::ToLocaleString(value, scriptContext);
  8927. }
  8928. }
  8929. inline BOOL JavascriptArray::IsFullArray() const
  8930. {
  8931. if (head && head->length == length)
  8932. {
  8933. AssertMsg(head->next == 0 && head->left == 0, "Invalid Array");
  8934. return true;
  8935. }
  8936. return (0 == length);
  8937. }
  8938. /*
  8939. * IsFillFromPrototypes
  8940. * - Check the array has no missing values and only head segment.
  8941. * - Also ensure if the lengths match.
  8942. */
  8943. bool JavascriptArray::IsFillFromPrototypes()
  8944. {
  8945. return !(this->head->next == nullptr && this->HasNoMissingValues() && this->length == this->head->length);
  8946. }
  8947. // Fill all missing value in the array and fill it from prototype between startIndex and limitIndex
  8948. // typically startIndex = 0 and limitIndex = length. From start of the array till end of the array.
  8949. void JavascriptArray::FillFromPrototypes(uint32 startIndex, uint32 limitIndex)
  8950. {
  8951. if (startIndex >= limitIndex)
  8952. {
  8953. return;
  8954. }
  8955. RecyclableObject* prototype = this->GetPrototype();
  8956. // Fill all missing values by walking through prototype
  8957. while (JavascriptOperators::GetTypeId(prototype) != TypeIds_Null)
  8958. {
  8959. ForEachOwnMissingArrayIndexOfObject(this, nullptr, prototype, startIndex, limitIndex,0, [this](uint32 index, Var value) {
  8960. this->SetItem(index, value, PropertyOperation_None);
  8961. });
  8962. prototype = prototype->GetPrototype();
  8963. }
  8964. #ifdef VALIDATE_ARRAY
  8965. ValidateArray();
  8966. #endif
  8967. }
  8968. //
  8969. // JavascriptArray requires head->left == 0 for fast path Get.
  8970. //
  8971. template<typename T>
  8972. void JavascriptArray::EnsureHeadStartsFromZero(Recycler * recycler)
  8973. {
  8974. if (head == nullptr || head->left != 0)
  8975. {
  8976. // This is used to fix up altered arrays.
  8977. // any SegmentMap would be invalid at this point.
  8978. ClearSegmentMap();
  8979. //
  8980. // We could OOM and throw when allocating new empty head, resulting in a corrupted array. Need
  8981. // some protection here. Save the head and switch this array to EmptySegment. Will be restored
  8982. // correctly if allocating new segment succeeds.
  8983. //
  8984. SparseArraySegment<T>* savedHead = SparseArraySegment<T>::From(this->head);
  8985. SparseArraySegment<T>* savedLastUsedSegment = (SparseArraySegment<T>*)this->GetLastUsedSegment();
  8986. SetHeadAndLastUsedSegment(const_cast<SparseArraySegmentBase*>(EmptySegment));
  8987. SparseArraySegment<T> *newSeg = SparseArraySegment<T>::AllocateSegment(recycler, 0, 0, savedHead);
  8988. newSeg->next = savedHead;
  8989. this->head = newSeg;
  8990. SetHasNoMissingValues();
  8991. this->SetLastUsedSegment(savedLastUsedSegment);
  8992. }
  8993. }
  8994. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  8995. void JavascriptArray::CheckForceES5Array()
  8996. {
  8997. if (Configuration::Global.flags.ForceES5Array)
  8998. {
  8999. // There's a bad interaction with the jitted code for native array creation here.
  9000. // ForceES5Array doesn't interact well with native arrays
  9001. if (PHASE_OFF1(NativeArrayPhase))
  9002. {
  9003. GetTypeHandler()->ConvertToTypeWithItemAttributes(this);
  9004. }
  9005. }
  9006. }
  9007. #endif
  9008. template <typename T, typename Fn>
  9009. void JavascriptArray::ForEachOwnMissingArrayIndexOfObject(JavascriptArray *baseArray, JavascriptArray *destArray, RecyclableObject* obj, uint32 startIndex, uint32 limitIndex, T destIndex, Fn fn)
  9010. {
  9011. JS_REENTRANCY_LOCK(jsReentLock, baseArray->GetScriptContext()->GetThreadContext());
  9012. Assert(DynamicObject::IsAnyArray(obj) || JavascriptOperators::IsObject(obj));
  9013. Var oldValue;
  9014. JavascriptArray* arr = nullptr;
  9015. if (DynamicObject::IsAnyArray(obj))
  9016. {
  9017. arr = JavascriptArray::FromAnyArray(obj);
  9018. }
  9019. else if (DynamicType::Is(obj->GetTypeId()))
  9020. {
  9021. DynamicObject* dynobj = DynamicObject::FromVar(obj);
  9022. ArrayObject* objectArray = dynobj->GetObjectArray();
  9023. arr = (objectArray && JavascriptArray::IsAnyArray(objectArray)) ? JavascriptArray::FromAnyArray(objectArray) : nullptr;
  9024. }
  9025. if (arr != nullptr)
  9026. {
  9027. if (JavascriptArray::Is(arr))
  9028. {
  9029. arr = EnsureNonNativeArray(arr);
  9030. ArrayElementEnumerator e(arr, startIndex, limitIndex);
  9031. while(e.MoveNext<Var>())
  9032. {
  9033. uint32 index = e.GetIndex();
  9034. if (!baseArray->DirectGetVarItemAt(index, &oldValue, baseArray->GetScriptContext()))
  9035. {
  9036. T n = destIndex + (index - startIndex);
  9037. if (destArray == nullptr || !destArray->DirectGetItemAt(n, &oldValue))
  9038. {
  9039. JS_REENTRANT(jsReentLock, fn(index, e.GetItem<Var>()));
  9040. }
  9041. }
  9042. }
  9043. }
  9044. else
  9045. {
  9046. ScriptContext* scriptContext = obj->GetScriptContext();
  9047. Assert(ES5Array::Is(arr));
  9048. ES5Array* es5Array = ES5Array::FromVar(arr);
  9049. ES5ArrayIndexStaticEnumerator<true> e(es5Array);
  9050. while (e.MoveNext())
  9051. {
  9052. uint32 index = e.GetIndex();
  9053. if (index < startIndex) continue;
  9054. else if (index >= limitIndex) break;
  9055. if (!baseArray->DirectGetVarItemAt(index, &oldValue, baseArray->GetScriptContext()))
  9056. {
  9057. T n = destIndex + (index - startIndex);
  9058. if (destArray == nullptr || !destArray->DirectGetItemAt(n, &oldValue))
  9059. {
  9060. Var value = nullptr;
  9061. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetOwnItem(obj, index, &value, scriptContext));
  9062. if (gotItem)
  9063. {
  9064. JS_REENTRANT(jsReentLock, fn(index, value));
  9065. }
  9066. }
  9067. }
  9068. }
  9069. }
  9070. }
  9071. }
  9072. //
  9073. // ArrayElementEnumerator to enumerate array elements (not including elements from prototypes).
  9074. //
  9075. JavascriptArray::ArrayElementEnumerator::ArrayElementEnumerator(JavascriptArray* arr, uint32 start, uint32 end)
  9076. : start(start), end(min(end, arr->length))
  9077. {
  9078. Init(arr);
  9079. }
  9080. //
  9081. // Initialize this enumerator and prepare for the first MoveNext.
  9082. //
  9083. void JavascriptArray::ArrayElementEnumerator::Init(JavascriptArray* arr)
  9084. {
  9085. // Find start segment
  9086. seg = (arr ? arr->GetBeginLookupSegment(start) : nullptr);
  9087. while (seg && (seg->left + seg->length <= start))
  9088. {
  9089. seg = seg->next;
  9090. }
  9091. // Set start index and endIndex
  9092. if (seg)
  9093. {
  9094. if (seg->left >= end)
  9095. {
  9096. seg = nullptr;
  9097. }
  9098. else
  9099. {
  9100. // set index to be at target index - 1, so MoveNext will move to target
  9101. index = max(seg->left, start) - seg->left - 1;
  9102. endIndex = min(end - seg->left, seg->length);
  9103. }
  9104. }
  9105. }
  9106. //
  9107. // Move to the next element if available.
  9108. //
  9109. template<typename T>
  9110. inline bool JavascriptArray::ArrayElementEnumerator::MoveNext()
  9111. {
  9112. while (seg)
  9113. {
  9114. // Look for next non-null item in current segment
  9115. while (++index < endIndex)
  9116. {
  9117. if (!SparseArraySegment<T>::IsMissingItem(&((SparseArraySegment<T>*)seg)->elements[index]))
  9118. {
  9119. return true;
  9120. }
  9121. }
  9122. // Move to next segment
  9123. seg = seg->next;
  9124. if (seg)
  9125. {
  9126. if (seg->left >= end)
  9127. {
  9128. seg = nullptr;
  9129. break;
  9130. }
  9131. else
  9132. {
  9133. index = static_cast<uint32>(-1);
  9134. endIndex = min(end - seg->left, seg->length);
  9135. }
  9136. }
  9137. }
  9138. return false;
  9139. }
  9140. //
  9141. // Get current array element index.
  9142. //
  9143. uint32 JavascriptArray::ArrayElementEnumerator::GetIndex() const
  9144. {
  9145. Assert(seg && index < seg->length && index < endIndex);
  9146. return seg->left + index;
  9147. }
  9148. //
  9149. // Get current array element value.
  9150. //
  9151. template<typename T>
  9152. T JavascriptArray::ArrayElementEnumerator::GetItem() const
  9153. {
  9154. Assert(seg && index < seg->length && index < endIndex &&
  9155. !SparseArraySegment<T>::IsMissingItem(&((SparseArraySegment<T>*)seg)->elements[index]));
  9156. return ((SparseArraySegment<T>*)seg)->elements[index];
  9157. }
  9158. //
  9159. // Construct a BigIndex initialized to a given uint32 (small index).
  9160. //
  9161. JavascriptArray::BigIndex::BigIndex(uint32 initIndex)
  9162. : index(initIndex), bigIndex(InvalidIndex)
  9163. {
  9164. //ok if initIndex == InvalidIndex
  9165. }
  9166. //
  9167. // Construct a BigIndex initialized to a given uint64 (large or small index).
  9168. //
  9169. JavascriptArray::BigIndex::BigIndex(uint64 initIndex)
  9170. : index(InvalidIndex), bigIndex(initIndex)
  9171. {
  9172. if (bigIndex < InvalidIndex) // if it's actually small index
  9173. {
  9174. index = static_cast<uint32>(bigIndex);
  9175. bigIndex = InvalidIndex;
  9176. }
  9177. }
  9178. bool JavascriptArray::BigIndex::IsUint32Max() const
  9179. {
  9180. return index == InvalidIndex && bigIndex == InvalidIndex;
  9181. }
  9182. bool JavascriptArray::BigIndex::IsSmallIndex() const
  9183. {
  9184. return index < InvalidIndex;
  9185. }
  9186. uint32 JavascriptArray::BigIndex::GetSmallIndex() const
  9187. {
  9188. Assert(IsSmallIndex());
  9189. return index;
  9190. }
  9191. uint64 JavascriptArray::BigIndex::GetBigIndex() const
  9192. {
  9193. Assert(!IsSmallIndex());
  9194. return bigIndex;
  9195. }
  9196. //
  9197. // Convert this index value to a JS number
  9198. //
  9199. Var JavascriptArray::BigIndex::ToNumber(ScriptContext* scriptContext) const
  9200. {
  9201. if (IsSmallIndex())
  9202. {
  9203. return small_index::ToNumber(index, scriptContext);
  9204. }
  9205. else
  9206. {
  9207. return JavascriptNumber::ToVar(bigIndex, scriptContext);
  9208. }
  9209. }
  9210. //
  9211. // Increment this index by 1.
  9212. //
  9213. const JavascriptArray::BigIndex& JavascriptArray::BigIndex::operator++()
  9214. {
  9215. if (IsSmallIndex())
  9216. {
  9217. ++index;
  9218. // If index reaches InvalidIndex, we will start to use bigIndex which is initially InvalidIndex.
  9219. }
  9220. else
  9221. {
  9222. bigIndex = bigIndex + 1;
  9223. }
  9224. return *this;
  9225. }
  9226. //
  9227. // Decrement this index by 1.
  9228. //
  9229. const JavascriptArray::BigIndex& JavascriptArray::BigIndex::operator--()
  9230. {
  9231. if (IsSmallIndex())
  9232. {
  9233. --index;
  9234. }
  9235. else
  9236. {
  9237. Assert(index == InvalidIndex && bigIndex >= InvalidIndex);
  9238. --bigIndex;
  9239. if (bigIndex < InvalidIndex)
  9240. {
  9241. index = InvalidIndex - 1;
  9242. bigIndex = InvalidIndex;
  9243. }
  9244. }
  9245. return *this;
  9246. }
  9247. JavascriptArray::BigIndex JavascriptArray::BigIndex::operator+(const BigIndex& delta) const
  9248. {
  9249. if (delta.IsSmallIndex())
  9250. {
  9251. return operator+(delta.GetSmallIndex());
  9252. }
  9253. if (IsSmallIndex())
  9254. {
  9255. return index + delta.GetBigIndex();
  9256. }
  9257. return bigIndex + delta.GetBigIndex();
  9258. }
  9259. //
  9260. // Get a new BigIndex representing this + delta.
  9261. //
  9262. JavascriptArray::BigIndex JavascriptArray::BigIndex::operator+(uint32 delta) const
  9263. {
  9264. if (IsSmallIndex())
  9265. {
  9266. uint32 newIndex;
  9267. if (UInt32Math::Add(index, delta, &newIndex))
  9268. {
  9269. return static_cast<uint64>(index) + static_cast<uint64>(delta);
  9270. }
  9271. else
  9272. {
  9273. return newIndex; // ok if newIndex == InvalidIndex
  9274. }
  9275. }
  9276. else
  9277. {
  9278. return bigIndex + static_cast<uint64>(delta);
  9279. }
  9280. }
  9281. bool JavascriptArray::BigIndex::operator==(const BigIndex& rhs) const
  9282. {
  9283. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9284. {
  9285. return this->GetSmallIndex() == rhs.GetSmallIndex();
  9286. }
  9287. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9288. {
  9289. // if lhs is big promote rhs
  9290. return this->GetBigIndex() == (uint64) rhs.GetSmallIndex();
  9291. }
  9292. else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
  9293. {
  9294. // if rhs is big promote lhs
  9295. return ((uint64)this->GetSmallIndex()) == rhs.GetBigIndex();
  9296. }
  9297. return this->GetBigIndex() == rhs.GetBigIndex();
  9298. }
  9299. bool JavascriptArray::BigIndex::operator> (const BigIndex& rhs) const
  9300. {
  9301. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9302. {
  9303. return this->GetSmallIndex() > rhs.GetSmallIndex();
  9304. }
  9305. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9306. {
  9307. // if lhs is big promote rhs
  9308. return this->GetBigIndex() > (uint64)rhs.GetSmallIndex();
  9309. }
  9310. else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
  9311. {
  9312. // if rhs is big promote lhs
  9313. return ((uint64)this->GetSmallIndex()) > rhs.GetBigIndex();
  9314. }
  9315. return this->GetBigIndex() > rhs.GetBigIndex();
  9316. }
  9317. bool JavascriptArray::BigIndex::operator< (const BigIndex& rhs) const
  9318. {
  9319. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9320. {
  9321. return this->GetSmallIndex() < rhs.GetSmallIndex();
  9322. }
  9323. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9324. {
  9325. // if lhs is big promote rhs
  9326. return this->GetBigIndex() < (uint64)rhs.GetSmallIndex();
  9327. }
  9328. else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
  9329. {
  9330. // if rhs is big promote lhs
  9331. return ((uint64)this->GetSmallIndex()) < rhs.GetBigIndex();
  9332. }
  9333. return this->GetBigIndex() < rhs.GetBigIndex();
  9334. }
  9335. bool JavascriptArray::BigIndex::operator<=(const BigIndex& rhs) const
  9336. {
  9337. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9338. {
  9339. return this->GetSmallIndex() <= rhs.GetSmallIndex();
  9340. }
  9341. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9342. {
  9343. // if lhs is big promote rhs
  9344. return this->GetBigIndex() <= (uint64)rhs.GetSmallIndex();
  9345. }
  9346. else if (!rhs.IsSmallIndex() && !this->IsSmallIndex())
  9347. {
  9348. // if rhs is big promote lhs
  9349. return ((uint64)this->GetSmallIndex()) <= rhs.GetBigIndex();
  9350. }
  9351. return this->GetBigIndex() <= rhs.GetBigIndex();
  9352. }
  9353. bool JavascriptArray::BigIndex::operator>=(const BigIndex& rhs) const
  9354. {
  9355. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9356. {
  9357. return this->GetSmallIndex() >= rhs.GetSmallIndex();
  9358. }
  9359. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9360. {
  9361. // if lhs is big promote rhs
  9362. return this->GetBigIndex() >= (uint64)rhs.GetSmallIndex();
  9363. }
  9364. else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
  9365. {
  9366. // if rhs is big promote lhs
  9367. return ((uint64)this->GetSmallIndex()) >= rhs.GetBigIndex();
  9368. }
  9369. return this->GetBigIndex() >= rhs.GetBigIndex();
  9370. }
  9371. BOOL JavascriptArray::BigIndex::GetItem(JavascriptArray* arr, Var* outVal) const
  9372. {
  9373. if (IsSmallIndex())
  9374. {
  9375. return small_index::GetItem(arr, index, outVal);
  9376. }
  9377. else
  9378. {
  9379. ScriptContext* scriptContext = arr->GetScriptContext();
  9380. PropertyRecord const * propertyRecord;
  9381. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9382. return arr->GetProperty(arr, propertyRecord->GetPropertyId(), outVal, NULL, scriptContext);
  9383. }
  9384. }
  9385. BOOL JavascriptArray::BigIndex::SetItem(JavascriptArray* arr, Var newValue) const
  9386. {
  9387. if (IsSmallIndex())
  9388. {
  9389. return small_index::SetItem(arr, index, newValue);
  9390. }
  9391. else
  9392. {
  9393. ScriptContext* scriptContext = arr->GetScriptContext();
  9394. PropertyRecord const * propertyRecord;
  9395. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9396. return arr->SetProperty(propertyRecord->GetPropertyId(), newValue, PropertyOperation_None, NULL);
  9397. }
  9398. }
  9399. void JavascriptArray::BigIndex::SetItemIfNotExist(JavascriptArray* arr, Var newValue) const
  9400. {
  9401. if (IsSmallIndex())
  9402. {
  9403. small_index::SetItemIfNotExist(arr, index, newValue);
  9404. }
  9405. else
  9406. {
  9407. ScriptContext* scriptContext = arr->GetScriptContext();
  9408. PropertyRecord const * propertyRecord;
  9409. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9410. Var oldValue;
  9411. PropertyId propertyId = propertyRecord->GetPropertyId();
  9412. if (!arr->GetProperty(arr, propertyId, &oldValue, NULL, scriptContext))
  9413. {
  9414. arr->SetProperty(propertyId, newValue, PropertyOperation_None, NULL);
  9415. }
  9416. }
  9417. }
  9418. BOOL JavascriptArray::BigIndex::DeleteItem(JavascriptArray* arr) const
  9419. {
  9420. if (IsSmallIndex())
  9421. {
  9422. return small_index::DeleteItem(arr, index);
  9423. }
  9424. else
  9425. {
  9426. ScriptContext* scriptContext = arr->GetScriptContext();
  9427. PropertyRecord const * propertyRecord;
  9428. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9429. return arr->DeleteProperty(propertyRecord->GetPropertyId(), PropertyOperation_None);
  9430. }
  9431. }
  9432. BOOL JavascriptArray::BigIndex::SetItem(RecyclableObject* obj, Var newValue, PropertyOperationFlags flags) const
  9433. {
  9434. if (IsSmallIndex())
  9435. {
  9436. return small_index::SetItem(obj, index, newValue, flags);
  9437. }
  9438. else
  9439. {
  9440. ScriptContext* scriptContext = obj->GetScriptContext();
  9441. PropertyRecord const * propertyRecord;
  9442. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9443. return JavascriptOperators::SetProperty(obj, obj, propertyRecord->GetPropertyId(), newValue, scriptContext, flags);
  9444. }
  9445. }
  9446. BOOL JavascriptArray::BigIndex::DeleteItem(RecyclableObject* obj, PropertyOperationFlags flags) const
  9447. {
  9448. if (IsSmallIndex())
  9449. {
  9450. return small_index::DeleteItem(obj, index, flags);
  9451. }
  9452. else
  9453. {
  9454. PropertyRecord const * propertyRecord;
  9455. JavascriptOperators::GetPropertyIdForInt(bigIndex, obj->GetScriptContext(), &propertyRecord);
  9456. return JavascriptOperators::DeleteProperty(obj, propertyRecord->GetPropertyId(), flags);
  9457. }
  9458. }
  9459. //
  9460. // Truncate the array at start and clone the truncated span as properties starting at dstIndex (asserting dstIndex >= MaxArrayLength).
  9461. //
  9462. void JavascriptArray::TruncateToProperties(const BigIndex& dstIndex, uint32 start)
  9463. {
  9464. Assert(!dstIndex.IsSmallIndex());
  9465. typedef IndexTrace<BigIndex> index_trace;
  9466. BigIndex dst = dstIndex;
  9467. uint32 i = start;
  9468. ArrayElementEnumerator e(this, start);
  9469. while(e.MoveNext<Var>())
  9470. {
  9471. // delete all items not enumerated
  9472. while (i < e.GetIndex())
  9473. {
  9474. index_trace::DeleteItem(this, dst);
  9475. ++i;
  9476. ++dst;
  9477. }
  9478. // Copy over the item
  9479. index_trace::SetItem(this, dst, e.GetItem<Var>());
  9480. ++i;
  9481. ++dst;
  9482. }
  9483. // Delete the rest till length
  9484. while (i < this->length)
  9485. {
  9486. index_trace::DeleteItem(this, dst);
  9487. ++i;
  9488. ++dst;
  9489. }
  9490. // Elements moved, truncate the array at start
  9491. SetLength(start);
  9492. }
  9493. //
  9494. // Copy a srcArray elements (including elements from prototypes) to a dstArray starting from an index.
  9495. //
  9496. template<typename T>
  9497. void JavascriptArray::InternalCopyArrayElements(JavascriptArray* dstArray, const T& dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
  9498. {
  9499. Assert(start < end && end <= srcArray->length);
  9500. uint32 count = 0;
  9501. // iterate on the array itself
  9502. ArrayElementEnumerator e(srcArray, start, end);
  9503. while(e.MoveNext<Var>())
  9504. {
  9505. T n = dstIndex + (e.GetIndex() - start);
  9506. dstArray->DirectSetItemAt(n, e.GetItem<Var>());
  9507. count++;
  9508. }
  9509. // iterate on the array's prototypes only if not all elements found
  9510. if (start + count != end)
  9511. {
  9512. InternalFillFromPrototype(dstArray, dstIndex, srcArray, start, end, count);
  9513. }
  9514. }
  9515. //
  9516. // Copy a srcArray elements (including elements from prototypes) to a dstArray starting from an index. If the index grows larger than
  9517. // "array index", it will automatically turn to SetProperty using the index as property name.
  9518. //
  9519. void JavascriptArray::CopyArrayElements(JavascriptArray* dstArray, const BigIndex& dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
  9520. {
  9521. end = min(end, srcArray->length);
  9522. if (start < end)
  9523. {
  9524. uint32 len = end - start;
  9525. if (dstIndex.IsSmallIndex() && (len < MaxArrayLength - dstIndex.GetSmallIndex()))
  9526. {
  9527. // Won't overflow, use faster small_index version
  9528. InternalCopyArrayElements(dstArray, dstIndex.GetSmallIndex(), srcArray, start, end);
  9529. }
  9530. else
  9531. {
  9532. InternalCopyArrayElements(dstArray, dstIndex, srcArray, start, end);
  9533. }
  9534. }
  9535. }
  9536. //
  9537. // Faster small_index overload of CopyArrayElements, asserting the uint32 dstIndex won't overflow.
  9538. //
  9539. void JavascriptArray::CopyArrayElements(JavascriptArray* dstArray, uint32 dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
  9540. {
  9541. end = min(end, srcArray->length);
  9542. if (start < end)
  9543. {
  9544. Assert(end - start <= MaxArrayLength - dstIndex);
  9545. InternalCopyArrayElements(dstArray, dstIndex, srcArray, start, end);
  9546. }
  9547. }
  9548. template <typename T>
  9549. void JavascriptArray::CopyAnyArrayElementsToVar(JavascriptArray* dstArray, T dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
  9550. {
  9551. #if ENABLE_COPYONACCESS_ARRAY
  9552. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(srcArray);
  9553. #endif
  9554. #if ENABLE_COPYONACCESS_ARRAY
  9555. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(dstArray);
  9556. #endif
  9557. if (JavascriptNativeIntArray::Is(srcArray))
  9558. {
  9559. CopyNativeIntArrayElementsToVar(dstArray, dstIndex, JavascriptNativeIntArray::FromVar(srcArray), start, end);
  9560. }
  9561. else if (JavascriptNativeFloatArray::Is(srcArray))
  9562. {
  9563. CopyNativeFloatArrayElementsToVar(dstArray, dstIndex, JavascriptNativeFloatArray::FromVar(srcArray), start, end);
  9564. }
  9565. else
  9566. {
  9567. CopyArrayElements(dstArray, dstIndex, srcArray, start, end);
  9568. }
  9569. }
  9570. void JavascriptArray::CopyNativeIntArrayElementsToVar(JavascriptArray* dstArray, const BigIndex& dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
  9571. {
  9572. end = min(end, srcArray->length);
  9573. if (start < end)
  9574. {
  9575. uint32 len = end - start;
  9576. if (dstIndex.IsSmallIndex() && (len < MaxArrayLength - dstIndex.GetSmallIndex()))
  9577. {
  9578. // Won't overflow, use faster small_index version
  9579. InternalCopyNativeIntArrayElements(dstArray, dstIndex.GetSmallIndex(), srcArray, start, end);
  9580. }
  9581. else
  9582. {
  9583. InternalCopyNativeIntArrayElements(dstArray, dstIndex, srcArray, start, end);
  9584. }
  9585. }
  9586. }
  9587. //
  9588. // Faster small_index overload of CopyArrayElements, asserting the uint32 dstIndex won't overflow.
  9589. //
  9590. void JavascriptArray::CopyNativeIntArrayElementsToVar(JavascriptArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
  9591. {
  9592. end = min(end, srcArray->length);
  9593. if (start < end)
  9594. {
  9595. Assert(end - start <= MaxArrayLength - dstIndex);
  9596. InternalCopyNativeIntArrayElements(dstArray, dstIndex, srcArray, start, end);
  9597. }
  9598. }
  9599. bool JavascriptArray::CopyNativeIntArrayElements(JavascriptNativeIntArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
  9600. {
  9601. end = min(end, srcArray->length);
  9602. if (start >= end)
  9603. {
  9604. return false;
  9605. }
  9606. Assert(end - start <= MaxArrayLength - dstIndex);
  9607. Assert(start < end && end <= srcArray->length);
  9608. uint32 count = 0;
  9609. // iterate on the array itself
  9610. ArrayElementEnumerator e(srcArray, start, end);
  9611. while(e.MoveNext<int32>())
  9612. {
  9613. uint n = dstIndex + (e.GetIndex() - start);
  9614. dstArray->DirectSetItemAt(n, e.GetItem<int32>());
  9615. count++;
  9616. }
  9617. // iterate on the array's prototypes only if not all elements found
  9618. if (start + count != end)
  9619. {
  9620. JavascriptArray *varArray = JavascriptNativeIntArray::ToVarArray(dstArray);
  9621. InternalFillFromPrototype(varArray, dstIndex, srcArray, start, end, count);
  9622. return true;
  9623. }
  9624. return false;
  9625. }
  9626. bool JavascriptArray::CopyNativeIntArrayElementsToFloat(JavascriptNativeFloatArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
  9627. {
  9628. end = min(end, srcArray->length);
  9629. if (start >= end)
  9630. {
  9631. return false;
  9632. }
  9633. Assert(end - start <= MaxArrayLength - dstIndex);
  9634. Assert(start < end && end <= srcArray->length);
  9635. uint32 count = 0;
  9636. // iterate on the array itself
  9637. ArrayElementEnumerator e(srcArray, start, end);
  9638. while(e.MoveNext<int32>())
  9639. {
  9640. uint n = dstIndex + (e.GetIndex() - start);
  9641. dstArray->DirectSetItemAt(n, (double)e.GetItem<int32>());
  9642. count++;
  9643. }
  9644. // iterate on the array's prototypes only if not all elements found
  9645. if (start + count != end)
  9646. {
  9647. JavascriptArray *varArray = JavascriptNativeFloatArray::ToVarArray(dstArray);
  9648. InternalFillFromPrototype(varArray, dstIndex, srcArray, start, end, count);
  9649. return true;
  9650. }
  9651. return false;
  9652. }
  9653. void JavascriptArray::CopyNativeFloatArrayElementsToVar(JavascriptArray* dstArray, const BigIndex& dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
  9654. {
  9655. end = min(end, srcArray->length);
  9656. if (start < end)
  9657. {
  9658. uint32 len = end - start;
  9659. if (dstIndex.IsSmallIndex() && (len < MaxArrayLength - dstIndex.GetSmallIndex()))
  9660. {
  9661. // Won't overflow, use faster small_index version
  9662. InternalCopyNativeFloatArrayElements(dstArray, dstIndex.GetSmallIndex(), srcArray, start, end);
  9663. }
  9664. else
  9665. {
  9666. InternalCopyNativeFloatArrayElements(dstArray, dstIndex, srcArray, start, end);
  9667. }
  9668. }
  9669. }
  9670. //
  9671. // Faster small_index overload of CopyArrayElements, asserting the uint32 dstIndex won't overflow.
  9672. //
  9673. void JavascriptArray::CopyNativeFloatArrayElementsToVar(JavascriptArray* dstArray, uint32 dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
  9674. {
  9675. end = min(end, srcArray->length);
  9676. if (start < end)
  9677. {
  9678. Assert(end - start <= MaxArrayLength - dstIndex);
  9679. InternalCopyNativeFloatArrayElements(dstArray, dstIndex, srcArray, start, end);
  9680. }
  9681. }
  9682. bool JavascriptArray::CopyNativeFloatArrayElements(JavascriptNativeFloatArray* dstArray, uint32 dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
  9683. {
  9684. end = min(end, srcArray->length);
  9685. if (start >= end)
  9686. {
  9687. return false;
  9688. }
  9689. Assert(end - start <= MaxArrayLength - dstIndex);
  9690. Assert(start < end && end <= srcArray->length);
  9691. uint32 count = 0;
  9692. // iterate on the array itself
  9693. ArrayElementEnumerator e(srcArray, start, end);
  9694. while(e.MoveNext<double>())
  9695. {
  9696. uint n = dstIndex + (e.GetIndex() - start);
  9697. dstArray->DirectSetItemAt(n, e.GetItem<double>());
  9698. count++;
  9699. }
  9700. // iterate on the array's prototypes only if not all elements found
  9701. if (start + count != end)
  9702. {
  9703. JavascriptArray *varArray = JavascriptNativeFloatArray::ToVarArray(dstArray);
  9704. InternalFillFromPrototype(varArray, dstIndex, srcArray, start, end, count);
  9705. return true;
  9706. }
  9707. return false;
  9708. }
  9709. JavascriptArray *JavascriptArray::EnsureNonNativeArray(JavascriptArray *arr)
  9710. {
  9711. #if ENABLE_COPYONACCESS_ARRAY
  9712. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(arr);
  9713. #endif
  9714. if (JavascriptNativeIntArray::Is(arr))
  9715. {
  9716. arr = JavascriptNativeIntArray::ToVarArray((JavascriptNativeIntArray*)arr);
  9717. }
  9718. else if (JavascriptNativeFloatArray::Is(arr))
  9719. {
  9720. arr = JavascriptNativeFloatArray::ToVarArray((JavascriptNativeFloatArray*)arr);
  9721. }
  9722. return arr;
  9723. }
  9724. BOOL JavascriptNativeIntArray::DirectGetItemAtFull(uint32 index, Var* outVal)
  9725. {
  9726. ScriptContext* requestContext = type->GetScriptContext();
  9727. if (JavascriptNativeIntArray::GetItem(this, index, outVal, requestContext))
  9728. {
  9729. return TRUE;
  9730. }
  9731. return JavascriptOperators::GetItem(this, this->GetPrototype(), index, outVal, requestContext);
  9732. }
  9733. BOOL JavascriptNativeFloatArray::DirectGetItemAtFull(uint32 index, Var* outVal)
  9734. {
  9735. ScriptContext* requestContext = type->GetScriptContext();
  9736. if (JavascriptNativeFloatArray::GetItem(this, index, outVal, requestContext))
  9737. {
  9738. return TRUE;
  9739. }
  9740. return JavascriptOperators::GetItem(this, this->GetPrototype(), index, outVal, requestContext);
  9741. }
  9742. template<typename T>
  9743. void JavascriptArray::InternalCopyNativeIntArrayElements(JavascriptArray* dstArray, const T& dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
  9744. {
  9745. Assert(start < end && end <= srcArray->length);
  9746. uint32 count = 0;
  9747. // iterate on the array itself
  9748. ScriptContext *scriptContext = dstArray->GetScriptContext();
  9749. ArrayElementEnumerator e(srcArray, start, end);
  9750. while(e.MoveNext<int32>())
  9751. {
  9752. T n = dstIndex + (e.GetIndex() - start);
  9753. dstArray->DirectSetItemAt(n, JavascriptNumber::ToVar(e.GetItem<int32>(), scriptContext));
  9754. count++;
  9755. }
  9756. // iterate on the array's prototypes only if not all elements found
  9757. if (start + count != end)
  9758. {
  9759. InternalFillFromPrototype(dstArray, dstIndex, srcArray, start, end, count);
  9760. }
  9761. }
  9762. template<typename T>
  9763. void JavascriptArray::InternalCopyNativeFloatArrayElements(JavascriptArray* dstArray, const T& dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
  9764. {
  9765. Assert(start < end && end <= srcArray->length);
  9766. uint32 count = 0;
  9767. // iterate on the array itself
  9768. ScriptContext *scriptContext = dstArray->GetScriptContext();
  9769. ArrayElementEnumerator e(srcArray, start, end);
  9770. while(e.MoveNext<double>())
  9771. {
  9772. T n = dstIndex + (e.GetIndex() - start);
  9773. dstArray->DirectSetItemAt(n, JavascriptNumber::ToVarWithCheck(e.GetItem<double>(), scriptContext));
  9774. count++;
  9775. }
  9776. // iterate on the array's prototypes only if not all elements found
  9777. if (start + count != end)
  9778. {
  9779. InternalFillFromPrototype(dstArray, dstIndex, srcArray, start, end, count);
  9780. }
  9781. }
  9782. Var JavascriptArray::SpreadArrayArgs(Var arrayToSpread, const Js::AuxArray<uint32> *spreadIndices, ScriptContext *scriptContext)
  9783. {
  9784. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  9785. // At this stage we have an array literal with some arguments to be spread.
  9786. // First we need to calculate the real size of the final literal.
  9787. #if ENABLE_COPYONACCESS_ARRAY
  9788. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(arrayToSpread);
  9789. #endif
  9790. JavascriptArray *array = FromVar(arrayToSpread);
  9791. uint32 arrayLength = array->GetLength();
  9792. uint32 actualLength = arrayLength;
  9793. for (unsigned i = 0; i < spreadIndices->count; ++i)
  9794. {
  9795. JS_REENTRANT(jsReentLock,
  9796. actualLength = UInt32Math::Add(actualLength - 1, GetSpreadArgLen(array->DirectGetItem(spreadIndices->elements[i]), scriptContext)));
  9797. }
  9798. JavascriptArray *result = FromVar(OP_NewScArrayWithMissingValues(actualLength, scriptContext));
  9799. // Now we copy each element and expand the spread parameters inline.
  9800. for (unsigned i = 0, spreadArrIndex = 0, resultIndex = 0; i < arrayLength && resultIndex < actualLength; ++i)
  9801. {
  9802. uint32 spreadIndex = spreadIndices->elements[spreadArrIndex]; // The index of the next element to be spread.
  9803. // 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.
  9804. auto needArraySlowCopy = [&](Var instance) {
  9805. if (JavascriptArray::Is(instance))
  9806. {
  9807. JavascriptArray *arr = JavascriptArray::FromVar(instance);
  9808. JS_REENTRANT_UNLOCK(jsReentLock, return arr->IsCrossSiteObject() || arr->IsFillFromPrototypes());
  9809. }
  9810. return false;
  9811. };
  9812. // Designed to have interchangeable arguments with CopyAnyArrayElementsToVar.
  9813. auto slowCopy = [&scriptContext, &needArraySlowCopy
  9814. ](JavascriptArray *dstArray, unsigned dstIndex, Var srcArray, uint32 start, uint32 end) {
  9815. Assert(needArraySlowCopy(srcArray) || ArgumentsObject::Is(srcArray) || TypedArrayBase::Is(srcArray) || JavascriptString::Is(srcArray));
  9816. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  9817. RecyclableObject *propertyObject;
  9818. if (!JavascriptOperators::GetPropertyObject(srcArray, scriptContext, &propertyObject))
  9819. {
  9820. JavascriptError::ThrowTypeError(scriptContext, JSERR_InvalidSpreadArgument);
  9821. }
  9822. for (uint32 j = start; j < end; j++)
  9823. {
  9824. Var element;
  9825. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(srcArray, propertyObject, j, &element, scriptContext));
  9826. if (!gotItem)
  9827. {
  9828. // Copy across missing values as undefined as per 12.2.5.2 SpreadElement : ... AssignmentExpression 5f.
  9829. element = scriptContext->GetLibrary()->GetUndefined();
  9830. }
  9831. dstArray->DirectSetItemAt(dstIndex++, element);
  9832. }
  9833. };
  9834. if (i < spreadIndex)
  9835. {
  9836. // Any non-spread elements can be copied in bulk.
  9837. if (needArraySlowCopy(array))
  9838. {
  9839. slowCopy(result, resultIndex, (Var)array, i, spreadIndex);
  9840. }
  9841. else
  9842. {
  9843. JS_REENTRANT(jsReentLock, CopyAnyArrayElementsToVar(result, resultIndex, array, i, spreadIndex));
  9844. }
  9845. resultIndex += spreadIndex - i;
  9846. i = spreadIndex - 1;
  9847. continue;
  9848. }
  9849. else if (i > spreadIndex)
  9850. {
  9851. // Any non-spread elements terminating the array can also be copied in bulk.
  9852. Assert(spreadArrIndex == spreadIndices->count - 1);
  9853. if (needArraySlowCopy(array))
  9854. {
  9855. slowCopy(result, resultIndex, array, i, arrayLength);
  9856. }
  9857. else
  9858. {
  9859. JS_REENTRANT(jsReentLock, CopyAnyArrayElementsToVar(result, resultIndex, array, i, arrayLength));
  9860. }
  9861. break;
  9862. }
  9863. else
  9864. {
  9865. JS_REENTRANT(jsReentLock, Var instance = array->DirectGetItem(i));
  9866. if (SpreadArgument::Is(instance))
  9867. {
  9868. SpreadArgument* spreadArgument = SpreadArgument::FromVar(instance);
  9869. uint32 len = spreadArgument->GetArgumentSpreadCount();
  9870. const Var* spreadItems = spreadArgument->GetArgumentSpread();
  9871. for (uint32 j = 0; j < len; j++)
  9872. {
  9873. result->DirectSetItemAt(resultIndex++, spreadItems[j]);
  9874. }
  9875. }
  9876. else
  9877. {
  9878. Assert(JavascriptOperators::IsUndefinedObject(instance));
  9879. result->DirectSetItemAt(resultIndex++, instance);
  9880. }
  9881. if (spreadArrIndex < spreadIndices->count - 1)
  9882. {
  9883. spreadArrIndex++;
  9884. }
  9885. }
  9886. }
  9887. AssertMsg(arrayLength == array->GetLength(), "Array's length should not have changed");
  9888. return result;
  9889. }
  9890. uint32 JavascriptArray::GetSpreadArgLen(Var spreadArg, ScriptContext *scriptContext)
  9891. {
  9892. // A spread argument can be anything that returns a 'length' property, even if that
  9893. // property is null or undefined.
  9894. spreadArg = CrossSite::MarshalVar(scriptContext, spreadArg);
  9895. if (JavascriptArray::Is(spreadArg))
  9896. {
  9897. JavascriptArray *arr = JavascriptArray::FromVar(spreadArg);
  9898. return arr->GetLength();
  9899. }
  9900. if (TypedArrayBase::Is(spreadArg))
  9901. {
  9902. TypedArrayBase *tarr = TypedArrayBase::FromVar(spreadArg);
  9903. return tarr->GetLength();
  9904. }
  9905. if (SpreadArgument::Is(spreadArg))
  9906. {
  9907. SpreadArgument *spreadFunctionArgs = SpreadArgument::FromVar(spreadArg);
  9908. return spreadFunctionArgs->GetArgumentSpreadCount();
  9909. }
  9910. AssertMsg(false, "LdCustomSpreadIteratorList should have converted the arg to one of the above types");
  9911. Throw::FatalInternalError();
  9912. }
  9913. #ifdef VALIDATE_ARRAY
  9914. class ArraySegmentsVisitor
  9915. {
  9916. private:
  9917. SparseArraySegmentBase* seg;
  9918. public:
  9919. ArraySegmentsVisitor(SparseArraySegmentBase* head)
  9920. : seg(head)
  9921. {
  9922. }
  9923. void operator()(SparseArraySegmentBase* s)
  9924. {
  9925. Assert(seg == s);
  9926. if (seg)
  9927. {
  9928. seg = seg->next;
  9929. }
  9930. }
  9931. };
  9932. void JavascriptArray::ValidateArrayCommon()
  9933. {
  9934. SparseArraySegmentBase * lastUsedSegment = this->GetLastUsedSegment();
  9935. AssertMsg(this != nullptr && head && lastUsedSegment, "Array should not be null");
  9936. AssertMsg(head->left == 0, "Array always should have a segment starting at zero");
  9937. // Simple segments validation
  9938. bool foundLastUsedSegment = false;
  9939. SparseArraySegmentBase *seg = head;
  9940. while(seg != nullptr)
  9941. {
  9942. if (seg == lastUsedSegment)
  9943. {
  9944. foundLastUsedSegment = true;
  9945. }
  9946. AssertMsg(seg->length <= seg->size , "Length greater than size not possible");
  9947. SparseArraySegmentBase* next = seg->next;
  9948. if (next != nullptr)
  9949. {
  9950. AssertMsg(seg->left < next->left, "Segment is adjacent to or overlaps with next segment");
  9951. AssertMsg(seg->size <= (next->left - seg->left), "Segment is adjacent to or overlaps with next segment");
  9952. AssertMsg(!SparseArraySegmentBase::IsLeafSegment(seg, this->GetScriptContext()->GetRecycler()), "Leaf segment with a next pointer");
  9953. }
  9954. else
  9955. {
  9956. AssertMsg(seg->length <= MaxArrayLength - seg->left, "Segment index range overflow");
  9957. AssertMsg(seg->left + seg->length <= this->length, "Segment index range exceeds array length");
  9958. }
  9959. seg = next;
  9960. }
  9961. AssertMsg(foundLastUsedSegment || HasSegmentMap(), "Corrupt lastUsedSegment in array header");
  9962. // Validate segmentMap if present
  9963. if (HasSegmentMap())
  9964. {
  9965. ArraySegmentsVisitor visitor(head);
  9966. GetSegmentMap()->Walk(visitor);
  9967. }
  9968. }
  9969. void JavascriptArray::ValidateArray()
  9970. {
  9971. if (!Js::Configuration::Global.flags.ArrayValidate)
  9972. {
  9973. return;
  9974. }
  9975. ValidateArrayCommon();
  9976. // Detailed segments validation
  9977. JavascriptArray::ValidateVarSegment(SparseArraySegment<Var>::From(head));
  9978. }
  9979. void JavascriptNativeIntArray::ValidateArray()
  9980. {
  9981. if (!Js::Configuration::Global.flags.ArrayValidate)
  9982. {
  9983. #if DBG
  9984. SparseArraySegmentBase *seg = head;
  9985. while (seg)
  9986. {
  9987. if (seg->next != nullptr)
  9988. {
  9989. AssertMsg(!SparseArraySegmentBase::IsLeafSegment(seg, this->GetScriptContext()->GetRecycler()), "Leaf segment with a next pointer");
  9990. }
  9991. seg = seg->next;
  9992. }
  9993. #endif
  9994. return;
  9995. }
  9996. ValidateArrayCommon();
  9997. // Detailed segments validation
  9998. JavascriptArray::ValidateSegment<int32>(SparseArraySegment<int32>::From(head));
  9999. }
  10000. void JavascriptNativeFloatArray::ValidateArray()
  10001. {
  10002. if (!Js::Configuration::Global.flags.ArrayValidate)
  10003. {
  10004. #if DBG
  10005. SparseArraySegmentBase *seg = head;
  10006. while (seg)
  10007. {
  10008. if (seg->next != nullptr)
  10009. {
  10010. AssertMsg(!SparseArraySegmentBase::IsLeafSegment(seg, this->GetScriptContext()->GetRecycler()), "Leaf segment with a next pointer");
  10011. }
  10012. seg = seg->next;
  10013. }
  10014. #endif
  10015. return;
  10016. }
  10017. ValidateArrayCommon();
  10018. // Detailed segments validation
  10019. JavascriptArray::ValidateSegment<double>(SparseArraySegment<double>::From(head));
  10020. }
  10021. void JavascriptArray::ValidateVarSegment(SparseArraySegment<Var>* seg)
  10022. {
  10023. if (!Js::Configuration::Global.flags.ArrayValidate)
  10024. {
  10025. return;
  10026. }
  10027. int32 inspect;
  10028. double inspectDouble;
  10029. while (seg)
  10030. {
  10031. uint32 i = 0;
  10032. for (i = 0; i < seg->length; i++)
  10033. {
  10034. if (SparseArraySegment<Var>::IsMissingItem(&seg->elements[i]))
  10035. {
  10036. continue;
  10037. }
  10038. if (TaggedInt::Is(seg->elements[i]))
  10039. {
  10040. inspect = TaggedInt::ToInt32(seg->elements[i]);
  10041. }
  10042. else if (JavascriptNumber::Is_NoTaggedIntCheck(seg->elements[i]))
  10043. {
  10044. inspectDouble = JavascriptNumber::GetValue(seg->elements[i]);
  10045. }
  10046. else
  10047. {
  10048. AssertMsg(RecyclableObject::Is(seg->elements[i]), "Invalid entry in segment");
  10049. }
  10050. }
  10051. ValidateSegment(seg);
  10052. seg = SparseArraySegment<Var>::From(seg->next);
  10053. }
  10054. }
  10055. template<typename T>
  10056. void JavascriptArray::ValidateSegment(SparseArraySegment<T>* seg)
  10057. {
  10058. if (!Js::Configuration::Global.flags.ArrayValidate)
  10059. {
  10060. return;
  10061. }
  10062. while (seg)
  10063. {
  10064. uint32 i = seg->length;
  10065. while (i < seg->size)
  10066. {
  10067. AssertMsg(SparseArraySegment<T>::IsMissingItem(&seg->elements[i]), "Non missing value the end of the segment");
  10068. i++;
  10069. }
  10070. seg = SparseArraySegment<T>::From(seg->next);
  10071. }
  10072. }
  10073. #endif
  10074. template <typename T>
  10075. void JavascriptArray::InitBoxedInlineHeadSegment(SparseArraySegment<T> * dst, SparseArraySegment<T> * src)
  10076. {
  10077. // Don't copy the segment map, we will build it again
  10078. SetFlags(GetFlags() & ~DynamicObjectFlags::HasSegmentMap);
  10079. SetHeadAndLastUsedSegment(dst);
  10080. dst->left = src->left;
  10081. dst->length = src->length;
  10082. dst->size = src->size;
  10083. dst->CheckLengthvsSize();
  10084. dst->next = src->next;
  10085. CopyArray(dst->elements, dst->size, src->elements, src->size);
  10086. }
  10087. JavascriptArray::JavascriptArray(JavascriptArray * instance, bool boxHead)
  10088. : ArrayObject(instance)
  10089. {
  10090. if (boxHead)
  10091. {
  10092. InitBoxedInlineHeadSegment(DetermineInlineHeadSegmentPointer<JavascriptArray, 0, true>(this), SparseArraySegment<Var>::From(instance->head));
  10093. }
  10094. else
  10095. {
  10096. SetFlags(GetFlags() & ~DynamicObjectFlags::HasSegmentMap);
  10097. head = instance->head;
  10098. SetLastUsedSegment(instance->GetLastUsedSegment());
  10099. }
  10100. }
  10101. template <typename T>
  10102. T * JavascriptArray::BoxStackInstance(T * instance)
  10103. {
  10104. Assert(ThreadContext::IsOnStack(instance));
  10105. // On the stack, the we reserved a pointer before the object as to store the boxed value
  10106. T ** boxedInstanceRef = ((T **)instance) - 1;
  10107. T * boxedInstance = *boxedInstanceRef;
  10108. if (boxedInstance)
  10109. {
  10110. return boxedInstance;
  10111. }
  10112. const size_t inlineSlotsSize = instance->GetTypeHandler()->GetInlineSlotsSize();
  10113. if (ThreadContext::IsOnStack(instance->head))
  10114. {
  10115. boxedInstance = RecyclerNewPlusZ(instance->GetRecycler(),
  10116. inlineSlotsSize + sizeof(Js::SparseArraySegmentBase) + instance->head->size * sizeof(typename T::TElement),
  10117. T, instance, true);
  10118. }
  10119. else if(inlineSlotsSize)
  10120. {
  10121. boxedInstance = RecyclerNewPlusZ(instance->GetRecycler(), inlineSlotsSize, T, instance, false);
  10122. }
  10123. else
  10124. {
  10125. boxedInstance = RecyclerNew(instance->GetRecycler(), T, instance, false);
  10126. }
  10127. *boxedInstanceRef = boxedInstance;
  10128. return boxedInstance;
  10129. }
  10130. JavascriptArray *
  10131. JavascriptArray::BoxStackInstance(JavascriptArray * instance)
  10132. {
  10133. return BoxStackInstance<JavascriptArray>(instance);
  10134. }
  10135. #if ENABLE_TTD
  10136. void JavascriptArray::MarkVisitKindSpecificPtrs(TTD::SnapshotExtractor* extractor)
  10137. {
  10138. TTDAssert(this->GetTypeId() == Js::TypeIds_Array || this->GetTypeId() == Js::TypeIds_ES5Array, "Should only be used on basic arrays (or called as super from ES5Array.");
  10139. ScriptContext* ctx = this->GetScriptContext();
  10140. uint32 index = Js::JavascriptArray::InvalidIndex;
  10141. while(true)
  10142. {
  10143. index = this->GetNextIndex(index);
  10144. if(index == Js::JavascriptArray::InvalidIndex) // End of array
  10145. {
  10146. break;
  10147. }
  10148. Js::Var aval = nullptr;
  10149. if(this->DirectGetVarItemAt(index, &aval, ctx))
  10150. {
  10151. extractor->MarkVisitVar(aval);
  10152. }
  10153. }
  10154. }
  10155. void JavascriptArray::ProcessCorePaths()
  10156. {
  10157. TTDAssert(this->GetTypeId() == Js::TypeIds_Array, "Should only be used on basic arrays.");
  10158. ScriptContext* ctx = this->GetScriptContext();
  10159. uint32 index = Js::JavascriptArray::InvalidIndex;
  10160. while(true)
  10161. {
  10162. index = this->GetNextIndex(index);
  10163. if(index == Js::JavascriptArray::InvalidIndex) // End of array
  10164. {
  10165. break;
  10166. }
  10167. Js::Var aval = nullptr;
  10168. if(this->DirectGetVarItemAt(index, &aval, ctx))
  10169. {
  10170. TTD::UtilSupport::TTAutoString pathExt;
  10171. ctx->TTDWellKnownInfo->BuildArrayIndexBuffer(index, pathExt);
  10172. ctx->TTDWellKnownInfo->EnqueueNewPathVarAsNeeded(this, aval, pathExt.GetStrValue());
  10173. }
  10174. }
  10175. }
  10176. TTD::NSSnapObjects::SnapObjectType JavascriptArray::GetSnapTag_TTD() const
  10177. {
  10178. return TTD::NSSnapObjects::SnapObjectType::SnapArrayObject;
  10179. }
  10180. void JavascriptArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  10181. {
  10182. TTDAssert(this->GetTypeId() == Js::TypeIds_Array, "Should only be used on basic Js arrays.");
  10183. TTD::NSSnapObjects::SnapArrayInfo<TTD::TTDVar>* sai = TTD::NSSnapObjects::ExtractArrayValues<TTD::TTDVar>(this, alloc);
  10184. TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayInfo<TTD::TTDVar>*, TTD::NSSnapObjects::SnapObjectType::SnapArrayObject>(objData, sai);
  10185. }
  10186. #endif
  10187. JavascriptNativeArray::JavascriptNativeArray(JavascriptNativeArray * instance) :
  10188. JavascriptArray(instance, false),
  10189. weakRefToFuncBody(instance->weakRefToFuncBody)
  10190. {
  10191. }
  10192. JavascriptNativeIntArray::JavascriptNativeIntArray(JavascriptNativeIntArray * instance, bool boxHead) :
  10193. JavascriptNativeArray(instance)
  10194. {
  10195. if (boxHead)
  10196. {
  10197. InitBoxedInlineHeadSegment(DetermineInlineHeadSegmentPointer<JavascriptNativeIntArray, 0, true>(this), SparseArraySegment<int>::From(instance->head));
  10198. }
  10199. else
  10200. {
  10201. // Base class ctor should have copied these
  10202. Assert(head == instance->head);
  10203. Assert(segmentUnion.lastUsedSegment == instance->GetLastUsedSegment());
  10204. }
  10205. }
  10206. JavascriptNativeIntArray *
  10207. JavascriptNativeIntArray::BoxStackInstance(JavascriptNativeIntArray * instance)
  10208. {
  10209. return JavascriptArray::BoxStackInstance<JavascriptNativeIntArray>(instance);
  10210. }
  10211. #if ENABLE_TTD
  10212. TTD::NSSnapObjects::SnapObjectType JavascriptNativeIntArray::GetSnapTag_TTD() const
  10213. {
  10214. return TTD::NSSnapObjects::SnapObjectType::SnapNativeIntArrayObject;
  10215. }
  10216. void JavascriptNativeIntArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  10217. {
  10218. TTD::NSSnapObjects::SnapArrayInfo<int32>* sai = TTD::NSSnapObjects::ExtractArrayValues<int32>(this, alloc);
  10219. TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayInfo<int32>*, TTD::NSSnapObjects::SnapObjectType::SnapNativeIntArrayObject>(objData, sai);
  10220. }
  10221. #if ENABLE_COPYONACCESS_ARRAY
  10222. TTD::NSSnapObjects::SnapObjectType JavascriptCopyOnAccessNativeIntArray::GetSnapTag_TTD() const
  10223. {
  10224. return TTD::NSSnapObjects::SnapObjectType::Invalid;
  10225. }
  10226. void JavascriptCopyOnAccessNativeIntArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  10227. {
  10228. TTDAssert(false, "Not implemented yet!!!");
  10229. }
  10230. #endif
  10231. #endif
  10232. JavascriptNativeFloatArray::JavascriptNativeFloatArray(JavascriptNativeFloatArray * instance, bool boxHead) :
  10233. JavascriptNativeArray(instance)
  10234. {
  10235. if (boxHead)
  10236. {
  10237. InitBoxedInlineHeadSegment(DetermineInlineHeadSegmentPointer<JavascriptNativeFloatArray, 0, true>(this), SparseArraySegment<double>::From(instance->head));
  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. JavascriptNativeFloatArray *
  10247. JavascriptNativeFloatArray::BoxStackInstance(JavascriptNativeFloatArray * instance)
  10248. {
  10249. return JavascriptArray::BoxStackInstance<JavascriptNativeFloatArray>(instance);
  10250. }
  10251. #if ENABLE_TTD
  10252. TTD::NSSnapObjects::SnapObjectType JavascriptNativeFloatArray::GetSnapTag_TTD() const
  10253. {
  10254. return TTD::NSSnapObjects::SnapObjectType::SnapNativeFloatArrayObject;
  10255. }
  10256. void JavascriptNativeFloatArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  10257. {
  10258. TTDAssert(this->GetTypeId() == Js::TypeIds_NativeFloatArray, "Should only be used on native float arrays.");
  10259. TTD::NSSnapObjects::SnapArrayInfo<double>* sai = TTD::NSSnapObjects::ExtractArrayValues<double>(this, alloc);
  10260. TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayInfo<double>*, TTD::NSSnapObjects::SnapObjectType::SnapNativeFloatArrayObject>(objData, sai);
  10261. }
  10262. #endif
  10263. template<typename T>
  10264. RecyclableObject*
  10265. JavascriptArray::ArraySpeciesCreate(Var originalArray, T length, ScriptContext* scriptContext, bool *pIsIntArray, bool *pIsFloatArray, bool *pIsBuiltinArrayCtor)
  10266. {
  10267. if (originalArray == nullptr || !scriptContext->GetConfig()->IsES6SpeciesEnabled())
  10268. {
  10269. return nullptr;
  10270. }
  10271. if (JavascriptArray::Is(originalArray)
  10272. && !DynamicObject::FromVar(originalArray)->GetDynamicType()->GetTypeHandler()->GetIsNotPathTypeHandlerOrHasUserDefinedCtor()
  10273. && DynamicObject::FromVar(originalArray)->GetPrototype() == scriptContext->GetLibrary()->GetArrayPrototype()
  10274. && !scriptContext->GetLibrary()->GetArrayObjectHasUserDefinedSpecies())
  10275. {
  10276. return nullptr;
  10277. }
  10278. Var constructor = scriptContext->GetLibrary()->GetUndefined();
  10279. if (JavascriptOperators::IsArray(originalArray))
  10280. {
  10281. if (!JavascriptOperators::GetProperty(RecyclableObject::FromVar(originalArray), PropertyIds::constructor, &constructor, scriptContext))
  10282. {
  10283. return nullptr;
  10284. }
  10285. if (JavascriptOperators::IsConstructor(constructor))
  10286. {
  10287. ScriptContext* constructorScriptContext = RecyclableObject::FromVar(constructor)->GetScriptContext();
  10288. if (constructorScriptContext != scriptContext)
  10289. {
  10290. if (constructorScriptContext->GetLibrary()->GetArrayConstructor() == constructor)
  10291. {
  10292. constructor = scriptContext->GetLibrary()->GetUndefined();
  10293. }
  10294. }
  10295. }
  10296. if (JavascriptOperators::IsObject(constructor))
  10297. {
  10298. if (!JavascriptOperators::GetProperty((RecyclableObject*)constructor, PropertyIds::_symbolSpecies, &constructor, scriptContext))
  10299. {
  10300. if (pIsBuiltinArrayCtor != nullptr)
  10301. {
  10302. *pIsBuiltinArrayCtor = false;
  10303. }
  10304. return nullptr;
  10305. }
  10306. if (constructor == scriptContext->GetLibrary()->GetNull())
  10307. {
  10308. constructor = scriptContext->GetLibrary()->GetUndefined();
  10309. }
  10310. }
  10311. }
  10312. if (constructor == scriptContext->GetLibrary()->GetUndefined() || constructor == scriptContext->GetLibrary()->GetArrayConstructor())
  10313. {
  10314. if (length > UINT_MAX)
  10315. {
  10316. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  10317. }
  10318. if (nullptr == pIsIntArray)
  10319. {
  10320. return scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(length));
  10321. }
  10322. else
  10323. {
  10324. // If the constructor function is the built-in Array constructor, we can be smart and create the right type of native array.
  10325. JavascriptArray* pArr = JavascriptArray::FromVar(originalArray);
  10326. pArr->GetArrayTypeAndConvert(pIsIntArray, pIsFloatArray);
  10327. return CreateNewArrayHelper(static_cast<uint32>(length), *pIsIntArray, *pIsFloatArray, pArr, scriptContext);
  10328. }
  10329. }
  10330. if (!JavascriptOperators::IsConstructor(constructor))
  10331. {
  10332. JavascriptError::ThrowTypeError(scriptContext, JSERR_NotAConstructor, _u("constructor[Symbol.species]"));
  10333. }
  10334. if (pIsBuiltinArrayCtor != nullptr)
  10335. {
  10336. *pIsBuiltinArrayCtor = false;
  10337. }
  10338. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(length, scriptContext) };
  10339. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  10340. return RecyclableObject::FromVar(JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext));
  10341. }
  10342. /*static*/
  10343. PropertyId const JavascriptArray::specialPropertyIds[] =
  10344. {
  10345. PropertyIds::length
  10346. };
  10347. BOOL JavascriptArray::DeleteProperty(PropertyId propertyId, PropertyOperationFlags flags)
  10348. {
  10349. if (propertyId == PropertyIds::length)
  10350. {
  10351. return false;
  10352. }
  10353. return DynamicObject::DeleteProperty(propertyId, flags);
  10354. }
  10355. BOOL JavascriptArray::DeleteProperty(JavascriptString *propertyNameString, PropertyOperationFlags flags)
  10356. {
  10357. JsUtil::CharacterBuffer<WCHAR> propertyName(propertyNameString->GetString(), propertyNameString->GetLength());
  10358. if (BuiltInPropertyRecords::length.Equals(propertyName))
  10359. {
  10360. return false;
  10361. }
  10362. return DynamicObject::DeleteProperty(propertyNameString, flags);
  10363. }
  10364. BOOL JavascriptArray::HasProperty(PropertyId propertyId)
  10365. {
  10366. if (propertyId == PropertyIds::length)
  10367. {
  10368. return true;
  10369. }
  10370. ScriptContext* scriptContext = GetScriptContext();
  10371. uint32 index;
  10372. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10373. {
  10374. return this->HasItem(index);
  10375. }
  10376. return DynamicObject::HasProperty(propertyId);
  10377. }
  10378. BOOL JavascriptArray::IsEnumerable(PropertyId propertyId)
  10379. {
  10380. if (propertyId == PropertyIds::length)
  10381. {
  10382. return false;
  10383. }
  10384. return DynamicObject::IsEnumerable(propertyId);
  10385. }
  10386. BOOL JavascriptArray::IsConfigurable(PropertyId propertyId)
  10387. {
  10388. if (propertyId == PropertyIds::length)
  10389. {
  10390. return false;
  10391. }
  10392. return DynamicObject::IsConfigurable(propertyId);
  10393. }
  10394. //
  10395. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10396. // handling and only check instance objectArray for numeric propertyIds.
  10397. //
  10398. BOOL JavascriptArray::SetEnumerable(PropertyId propertyId, BOOL value)
  10399. {
  10400. if (propertyId == PropertyIds::length)
  10401. {
  10402. Assert(!value); // Can't change array length enumerable
  10403. return true;
  10404. }
  10405. ScriptContext* scriptContext = this->GetScriptContext();
  10406. uint32 index;
  10407. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10408. {
  10409. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10410. ->SetEnumerable(this, propertyId, value);
  10411. }
  10412. return __super::SetEnumerable(propertyId, value);
  10413. }
  10414. //
  10415. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10416. // handling and only check instance objectArray for numeric propertyIds.
  10417. //
  10418. BOOL JavascriptArray::SetWritable(PropertyId propertyId, BOOL value)
  10419. {
  10420. ScriptContext* scriptContext = this->GetScriptContext();
  10421. uint32 index;
  10422. bool setLengthNonWritable = (propertyId == PropertyIds::length && !value);
  10423. if (setLengthNonWritable || scriptContext->IsNumericPropertyId(propertyId, &index))
  10424. {
  10425. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10426. ->SetWritable(this, propertyId, value);
  10427. }
  10428. return __super::SetWritable(propertyId, value);
  10429. }
  10430. //
  10431. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10432. // handling and only check instance objectArray for numeric propertyIds.
  10433. //
  10434. BOOL JavascriptArray::SetConfigurable(PropertyId propertyId, BOOL value)
  10435. {
  10436. if (propertyId == PropertyIds::length)
  10437. {
  10438. Assert(!value); // Can't change array length configurable
  10439. return true;
  10440. }
  10441. ScriptContext* scriptContext = this->GetScriptContext();
  10442. uint32 index;
  10443. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10444. {
  10445. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10446. ->SetConfigurable(this, propertyId, value);
  10447. }
  10448. return __super::SetConfigurable(propertyId, value);
  10449. }
  10450. //
  10451. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10452. // handling and only check instance objectArray for numeric propertyIds.
  10453. //
  10454. BOOL JavascriptArray::SetAttributes(PropertyId propertyId, PropertyAttributes attributes)
  10455. {
  10456. ScriptContext* scriptContext = this->GetScriptContext();
  10457. // SetAttributes on "length" is not expected. DefineOwnProperty uses SetWritable. If this is
  10458. // changed, we need to handle it here.
  10459. Assert(propertyId != PropertyIds::length);
  10460. uint32 index;
  10461. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10462. {
  10463. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10464. ->SetItemAttributes(this, index, attributes);
  10465. }
  10466. return __super::SetAttributes(propertyId, attributes);
  10467. }
  10468. //
  10469. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10470. // handling and only check instance objectArray for numeric propertyIds.
  10471. //
  10472. BOOL JavascriptArray::SetAccessors(PropertyId propertyId, Var getter, Var setter, PropertyOperationFlags flags)
  10473. {
  10474. ScriptContext* scriptContext = this->GetScriptContext();
  10475. uint32 index;
  10476. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10477. {
  10478. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10479. ->SetItemAccessors(this, index, getter, setter);
  10480. }
  10481. return __super::SetAccessors(propertyId, getter, setter, flags);
  10482. }
  10483. //
  10484. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10485. // handling and only check instance objectArray for numeric propertyIds.
  10486. //
  10487. BOOL JavascriptArray::SetItemWithAttributes(uint32 index, Var value, PropertyAttributes attributes)
  10488. {
  10489. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10490. ->SetItemWithAttributes(this, index, value, attributes);
  10491. }
  10492. //
  10493. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10494. // handling and only check instance objectArray for numeric propertyIds.
  10495. //
  10496. BOOL JavascriptArray::SetItemAttributes(uint32 index, PropertyAttributes attributes)
  10497. {
  10498. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10499. ->SetItemAttributes(this, index, attributes);
  10500. }
  10501. //
  10502. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10503. // handling and only check instance objectArray for numeric propertyIds.
  10504. //
  10505. BOOL JavascriptArray::SetItemAccessors(uint32 index, Var getter, Var setter)
  10506. {
  10507. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10508. ->SetItemAccessors(this, index, getter, setter);
  10509. }
  10510. // Check if this objectArray isFrozen.
  10511. BOOL JavascriptArray::IsObjectArrayFrozen()
  10512. {
  10513. // If this is still a JavascriptArray, it's not frozen.
  10514. return false;
  10515. }
  10516. JavascriptEnumerator * JavascriptArray::GetIndexEnumerator(EnumeratorFlags flags, ScriptContext* requestContext)
  10517. {
  10518. if (!!(flags & EnumeratorFlags::SnapShotSemantics))
  10519. {
  10520. return RecyclerNew(GetRecycler(), JavascriptArrayIndexSnapshotEnumerator, this, flags, requestContext);
  10521. }
  10522. return RecyclerNew(GetRecycler(), JavascriptArrayIndexEnumerator, this, flags, requestContext);
  10523. }
  10524. BOOL JavascriptArray::GetNonIndexEnumerator(JavascriptStaticEnumerator * enumerator, ScriptContext* requestContext)
  10525. {
  10526. return enumerator->Initialize(nullptr, nullptr, this, EnumeratorFlags::SnapShotSemantics, requestContext, nullptr);
  10527. }
  10528. BOOL JavascriptArray::IsItemEnumerable(uint32 index)
  10529. {
  10530. return true;
  10531. }
  10532. //
  10533. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10534. // handling and only check instance objectArray for numeric propertyIds.
  10535. //
  10536. BOOL JavascriptArray::PreventExtensions()
  10537. {
  10538. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)->PreventExtensions(this);
  10539. }
  10540. //
  10541. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10542. // handling and only check instance objectArray for numeric propertyIds.
  10543. //
  10544. BOOL JavascriptArray::Seal()
  10545. {
  10546. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)->Seal(this);
  10547. }
  10548. //
  10549. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10550. // handling and only check instance objectArray for numeric propertyIds.
  10551. //
  10552. BOOL JavascriptArray::Freeze()
  10553. {
  10554. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)->Freeze(this);
  10555. }
  10556. BOOL JavascriptArray::GetSpecialPropertyName(uint32 index, Var *propertyName, ScriptContext * requestContext)
  10557. {
  10558. if (index == 0)
  10559. {
  10560. *propertyName = requestContext->GetPropertyString(PropertyIds::length);
  10561. return true;
  10562. }
  10563. return false;
  10564. }
  10565. // Returns the number of special non-enumerable properties this type has.
  10566. uint JavascriptArray::GetSpecialPropertyCount() const
  10567. {
  10568. return _countof(specialPropertyIds);
  10569. }
  10570. // Returns the list of special non-enumerable properties for the type.
  10571. PropertyId const * JavascriptArray::GetSpecialPropertyIds() const
  10572. {
  10573. return specialPropertyIds;
  10574. }
  10575. BOOL JavascriptArray::GetPropertyReference(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  10576. {
  10577. return JavascriptArray::GetProperty(originalInstance, propertyId, value, info, requestContext);
  10578. }
  10579. BOOL JavascriptArray::GetProperty(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  10580. {
  10581. if (GetPropertyBuiltIns(propertyId, value))
  10582. {
  10583. return true;
  10584. }
  10585. ScriptContext* scriptContext = GetScriptContext();
  10586. uint32 index;
  10587. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10588. {
  10589. return this->GetItem(this, index, value, scriptContext);
  10590. }
  10591. return DynamicObject::GetProperty(originalInstance, propertyId, value, info, requestContext);
  10592. }
  10593. BOOL JavascriptArray::GetProperty(Var originalInstance, JavascriptString* propertyNameString, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  10594. {
  10595. AssertMsg(!PropertyRecord::IsPropertyNameNumeric(propertyNameString->GetString(), propertyNameString->GetLength()),
  10596. "Numeric property names should have been converted to uint or PropertyRecord*");
  10597. PropertyRecord const* propertyRecord;
  10598. this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
  10599. if (propertyRecord != nullptr && GetPropertyBuiltIns(propertyRecord->GetPropertyId(), value))
  10600. {
  10601. return true;
  10602. }
  10603. return DynamicObject::GetProperty(originalInstance, propertyNameString, value, info, requestContext);
  10604. }
  10605. BOOL JavascriptArray::GetPropertyBuiltIns(PropertyId propertyId, Var* value)
  10606. {
  10607. //
  10608. // length being accessed. Return array length
  10609. //
  10610. if (propertyId == PropertyIds::length)
  10611. {
  10612. *value = JavascriptNumber::ToVar(this->GetLength(), GetScriptContext());
  10613. return true;
  10614. }
  10615. return false;
  10616. }
  10617. BOOL JavascriptArray::HasItem(uint32 index)
  10618. {
  10619. Var value;
  10620. return this->DirectGetItemAt<Var>(index, &value);
  10621. }
  10622. BOOL JavascriptArray::GetItem(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10623. {
  10624. return this->DirectGetItemAt<Var>(index, value);
  10625. }
  10626. BOOL JavascriptArray::GetItemReference(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10627. {
  10628. return this->DirectGetItemAt<Var>(index, value);
  10629. }
  10630. BOOL JavascriptArray::DirectGetVarItemAt(uint32 index, Var *value, ScriptContext *requestContext)
  10631. {
  10632. return this->DirectGetItemAt<Var>(index, value);
  10633. }
  10634. BOOL JavascriptNativeIntArray::HasItem(uint32 index)
  10635. {
  10636. #if ENABLE_COPYONACCESS_ARRAY
  10637. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10638. #endif
  10639. int32 value;
  10640. return this->DirectGetItemAt<int32>(index, &value);
  10641. }
  10642. BOOL JavascriptNativeFloatArray::HasItem(uint32 index)
  10643. {
  10644. double dvalue;
  10645. return this->DirectGetItemAt<double>(index, &dvalue);
  10646. }
  10647. BOOL JavascriptNativeIntArray::GetItem(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10648. {
  10649. #if ENABLE_COPYONACCESS_ARRAY
  10650. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10651. #endif
  10652. return JavascriptNativeIntArray::DirectGetVarItemAt(index, value, requestContext);
  10653. }
  10654. BOOL JavascriptNativeIntArray::DirectGetVarItemAt(uint32 index, Var *value, ScriptContext *requestContext)
  10655. {
  10656. int32 intvalue;
  10657. if (!this->DirectGetItemAt<int32>(index, &intvalue))
  10658. {
  10659. return FALSE;
  10660. }
  10661. *value = JavascriptNumber::ToVar(intvalue, requestContext);
  10662. return TRUE;
  10663. }
  10664. BOOL JavascriptNativeIntArray::GetItemReference(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10665. {
  10666. return JavascriptNativeIntArray::GetItem(originalInstance, index, value, requestContext);
  10667. }
  10668. BOOL JavascriptNativeFloatArray::GetItem(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10669. {
  10670. return JavascriptNativeFloatArray::DirectGetVarItemAt(index, value, requestContext);
  10671. }
  10672. BOOL JavascriptNativeFloatArray::DirectGetVarItemAt(uint32 index, Var *value, ScriptContext *requestContext)
  10673. {
  10674. double dvalue;
  10675. int32 ivalue;
  10676. if (!this->DirectGetItemAt<double>(index, &dvalue))
  10677. {
  10678. return FALSE;
  10679. }
  10680. if (*(uint64*)&dvalue == 0ull)
  10681. {
  10682. *value = TaggedInt::ToVarUnchecked(0);
  10683. }
  10684. else if (JavascriptNumber::TryGetInt32Value(dvalue, &ivalue) && !TaggedInt::IsOverflow(ivalue))
  10685. {
  10686. *value = TaggedInt::ToVarUnchecked(ivalue);
  10687. }
  10688. else
  10689. {
  10690. *value = JavascriptNumber::ToVarWithCheck(dvalue, requestContext);
  10691. }
  10692. return TRUE;
  10693. }
  10694. BOOL JavascriptNativeFloatArray::GetItemReference(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10695. {
  10696. return JavascriptNativeFloatArray::GetItem(originalInstance, index, value, requestContext);
  10697. }
  10698. BOOL JavascriptArray::SetProperty(PropertyId propertyId, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)
  10699. {
  10700. #if ENABLE_COPYONACCESS_ARRAY
  10701. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10702. #endif
  10703. uint32 indexValue;
  10704. if (propertyId == PropertyIds::length)
  10705. {
  10706. return this->SetLength(value);
  10707. }
  10708. else if (GetScriptContext()->IsNumericPropertyId(propertyId, &indexValue))
  10709. {
  10710. // Call this or subclass method
  10711. return SetItem(indexValue, value, flags);
  10712. }
  10713. else
  10714. {
  10715. return DynamicObject::SetProperty(propertyId, value, flags, info);
  10716. }
  10717. }
  10718. BOOL JavascriptArray::SetProperty(JavascriptString* propertyNameString, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)
  10719. {
  10720. AssertMsg(!PropertyRecord::IsPropertyNameNumeric(propertyNameString->GetString(), propertyNameString->GetLength()),
  10721. "Numeric property names should have been converted to uint or PropertyRecord*");
  10722. #if ENABLE_COPYONACCESS_ARRAY
  10723. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10724. #endif
  10725. PropertyRecord const* propertyRecord;
  10726. this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
  10727. if (propertyRecord != nullptr && propertyRecord->GetPropertyId() == PropertyIds::length)
  10728. {
  10729. return this->SetLength(value);
  10730. }
  10731. return DynamicObject::SetProperty(propertyNameString, value, flags, info);
  10732. }
  10733. BOOL JavascriptArray::SetPropertyWithAttributes(PropertyId propertyId, Var value, PropertyAttributes attributes, PropertyValueInfo* info, PropertyOperationFlags flags, SideEffects possibleSideEffects)
  10734. {
  10735. #if ENABLE_COPYONACCESS_ARRAY
  10736. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10737. #endif
  10738. ScriptContext* scriptContext = GetScriptContext();
  10739. if (propertyId == PropertyIds::length)
  10740. {
  10741. Assert(attributes == PropertyWritable);
  10742. Assert(IsWritable(propertyId) && !IsConfigurable(propertyId) && !IsEnumerable(propertyId));
  10743. return this->SetLength(value);
  10744. }
  10745. uint32 index;
  10746. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10747. {
  10748. // Call this or subclass method
  10749. return SetItemWithAttributes(index, value, attributes);
  10750. }
  10751. return __super::SetPropertyWithAttributes(propertyId, value, attributes, info, flags, possibleSideEffects);
  10752. }
  10753. BOOL JavascriptArray::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
  10754. {
  10755. this->DirectSetItemAt(index, value);
  10756. return true;
  10757. }
  10758. BOOL JavascriptNativeIntArray::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
  10759. {
  10760. int32 iValue;
  10761. double dValue;
  10762. #if ENABLE_COPYONACCESS_ARRAY
  10763. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10764. #endif
  10765. TypeId typeId = this->TrySetNativeIntArrayItem(value, &iValue, &dValue);
  10766. if (typeId == TypeIds_NativeIntArray)
  10767. {
  10768. this->SetItem(index, iValue);
  10769. }
  10770. else if (typeId == TypeIds_NativeFloatArray)
  10771. {
  10772. reinterpret_cast<JavascriptNativeFloatArray*>(this)->DirectSetItemAt<double>(index, dValue);
  10773. }
  10774. else
  10775. {
  10776. this->DirectSetItemAt<Var>(index, value);
  10777. }
  10778. return TRUE;
  10779. }
  10780. TypeId JavascriptNativeIntArray::TrySetNativeIntArrayItem(Var value, int32 *iValue, double *dValue)
  10781. {
  10782. if (TaggedInt::Is(value))
  10783. {
  10784. int32 i = TaggedInt::ToInt32(value);
  10785. if (i != JavascriptNativeIntArray::MissingItem)
  10786. {
  10787. *iValue = i;
  10788. return TypeIds_NativeIntArray;
  10789. }
  10790. }
  10791. if (JavascriptNumber::Is_NoTaggedIntCheck(value))
  10792. {
  10793. bool isInt32;
  10794. int32 i;
  10795. double d = JavascriptNumber::GetValue(value);
  10796. if (JavascriptNumber::TryGetInt32OrUInt32Value(d, &i, &isInt32))
  10797. {
  10798. if (isInt32 && i != JavascriptNativeIntArray::MissingItem)
  10799. {
  10800. *iValue = i;
  10801. return TypeIds_NativeIntArray;
  10802. }
  10803. }
  10804. else
  10805. {
  10806. *dValue = d;
  10807. JavascriptNativeIntArray::ToNativeFloatArray(this);
  10808. return TypeIds_NativeFloatArray;
  10809. }
  10810. }
  10811. JavascriptNativeIntArray::ToVarArray(this);
  10812. return TypeIds_Array;
  10813. }
  10814. BOOL JavascriptNativeIntArray::SetItem(uint32 index, int32 iValue)
  10815. {
  10816. if (iValue == JavascriptNativeIntArray::MissingItem)
  10817. {
  10818. JavascriptArray *varArr = JavascriptNativeIntArray::ToVarArray(this);
  10819. varArr->DirectSetItemAt(index, JavascriptNumber::ToVar(iValue, GetScriptContext()));
  10820. return TRUE;
  10821. }
  10822. this->DirectSetItemAt(index, iValue);
  10823. return TRUE;
  10824. }
  10825. BOOL JavascriptNativeFloatArray::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
  10826. {
  10827. double dValue;
  10828. TypeId typeId = this->TrySetNativeFloatArrayItem(value, &dValue);
  10829. if (typeId == TypeIds_NativeFloatArray)
  10830. {
  10831. this->SetItem(index, dValue);
  10832. }
  10833. else
  10834. {
  10835. this->DirectSetItemAt(index, value);
  10836. }
  10837. return TRUE;
  10838. }
  10839. TypeId JavascriptNativeFloatArray::TrySetNativeFloatArrayItem(Var value, double *dValue)
  10840. {
  10841. if (TaggedInt::Is(value))
  10842. {
  10843. *dValue = (double)TaggedInt::ToInt32(value);
  10844. return TypeIds_NativeFloatArray;
  10845. }
  10846. else if (JavascriptNumber::Is_NoTaggedIntCheck(value))
  10847. {
  10848. *dValue = JavascriptNumber::GetValue(value);
  10849. return TypeIds_NativeFloatArray;
  10850. }
  10851. JavascriptNativeFloatArray::ToVarArray(this);
  10852. return TypeIds_Array;
  10853. }
  10854. BOOL JavascriptNativeFloatArray::SetItem(uint32 index, double dValue)
  10855. {
  10856. if (*(uint64*)&dValue == *(uint64*)&JavascriptNativeFloatArray::MissingItem)
  10857. {
  10858. JavascriptArray *varArr = JavascriptNativeFloatArray::ToVarArray(this);
  10859. varArr->DirectSetItemAt(index, JavascriptNumber::ToVarNoCheck(dValue, GetScriptContext()));
  10860. return TRUE;
  10861. }
  10862. this->DirectSetItemAt<double>(index, dValue);
  10863. return TRUE;
  10864. }
  10865. BOOL JavascriptArray::DeleteItem(uint32 index, PropertyOperationFlags flags)
  10866. {
  10867. return this->DirectDeleteItemAt<Var>(index);
  10868. }
  10869. BOOL JavascriptNativeIntArray::DeleteItem(uint32 index, PropertyOperationFlags flags)
  10870. {
  10871. return this->DirectDeleteItemAt<int32>(index);
  10872. }
  10873. BOOL JavascriptNativeFloatArray::DeleteItem(uint32 index, PropertyOperationFlags flags)
  10874. {
  10875. return this->DirectDeleteItemAt<double>(index);
  10876. }
  10877. BOOL JavascriptArray::GetEnumerator(JavascriptStaticEnumerator * enumerator, EnumeratorFlags flags, ScriptContext* requestContext, ForInCache * forInCache)
  10878. {
  10879. return enumerator->Initialize(nullptr, this, this, flags, requestContext, forInCache);
  10880. }
  10881. BOOL JavascriptArray::GetDiagValueString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext)
  10882. {
  10883. stringBuilder->Append(_u('['));
  10884. if (this->length < 10)
  10885. {
  10886. auto funcPtr = [&]()
  10887. {
  10888. ENTER_PINNED_SCOPE(JavascriptString, valueStr);
  10889. valueStr = JavascriptArray::JoinHelper(this, GetLibrary()->GetCommaDisplayString(), requestContext);
  10890. stringBuilder->Append(valueStr->GetString(), valueStr->GetLength());
  10891. LEAVE_PINNED_SCOPE();
  10892. };
  10893. if (!requestContext->GetThreadContext()->IsScriptActive())
  10894. {
  10895. BEGIN_JS_RUNTIME_CALL(requestContext);
  10896. {
  10897. funcPtr();
  10898. }
  10899. END_JS_RUNTIME_CALL(requestContext);
  10900. }
  10901. else
  10902. {
  10903. funcPtr();
  10904. }
  10905. }
  10906. else
  10907. {
  10908. stringBuilder->AppendCppLiteral(_u("..."));
  10909. }
  10910. stringBuilder->Append(_u(']'));
  10911. return TRUE;
  10912. }
  10913. BOOL JavascriptArray::GetDiagTypeString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext)
  10914. {
  10915. stringBuilder->AppendCppLiteral(_u("Object, (Array)"));
  10916. return TRUE;
  10917. }
  10918. bool JavascriptNativeArray::Is(Var aValue)
  10919. {
  10920. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  10921. return JavascriptNativeArray::Is(typeId);
  10922. }
  10923. bool JavascriptNativeArray::Is(TypeId typeId)
  10924. {
  10925. return JavascriptNativeIntArray::Is(typeId) || JavascriptNativeFloatArray::Is(typeId);
  10926. }
  10927. JavascriptNativeArray* JavascriptNativeArray::FromVar(Var aValue)
  10928. {
  10929. AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeArray'");
  10930. return static_cast<JavascriptNativeArray *>(RecyclableObject::FromVar(aValue));
  10931. }
  10932. bool JavascriptNativeIntArray::Is(Var aValue)
  10933. {
  10934. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  10935. return JavascriptNativeIntArray::Is(typeId);
  10936. }
  10937. #if ENABLE_COPYONACCESS_ARRAY
  10938. bool JavascriptCopyOnAccessNativeIntArray::Is(Var aValue)
  10939. {
  10940. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  10941. return JavascriptCopyOnAccessNativeIntArray::Is(typeId);
  10942. }
  10943. #endif
  10944. bool JavascriptNativeIntArray::Is(TypeId typeId)
  10945. {
  10946. return typeId == TypeIds_NativeIntArray;
  10947. }
  10948. #if ENABLE_COPYONACCESS_ARRAY
  10949. bool JavascriptCopyOnAccessNativeIntArray::Is(TypeId typeId)
  10950. {
  10951. return typeId == TypeIds_CopyOnAccessNativeIntArray;
  10952. }
  10953. #endif
  10954. bool JavascriptNativeIntArray::IsNonCrossSite(Var aValue)
  10955. {
  10956. bool ret = !TaggedInt::Is(aValue) && VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(aValue);
  10957. Assert(ret == (JavascriptNativeIntArray::Is(aValue) && !JavascriptNativeIntArray::FromVar(aValue)->IsCrossSiteObject()));
  10958. return ret;
  10959. }
  10960. JavascriptNativeIntArray* JavascriptNativeIntArray::FromVar(Var aValue)
  10961. {
  10962. AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeIntArray'");
  10963. return static_cast<JavascriptNativeIntArray *>(RecyclableObject::FromVar(aValue));
  10964. }
  10965. #if ENABLE_COPYONACCESS_ARRAY
  10966. JavascriptCopyOnAccessNativeIntArray* JavascriptCopyOnAccessNativeIntArray::FromVar(Var aValue)
  10967. {
  10968. AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptCopyOnAccessNativeIntArray'");
  10969. return static_cast<JavascriptCopyOnAccessNativeIntArray *>(RecyclableObject::FromVar(aValue));
  10970. }
  10971. #endif
  10972. bool JavascriptNativeFloatArray::Is(Var aValue)
  10973. {
  10974. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  10975. return JavascriptNativeFloatArray::Is(typeId);
  10976. }
  10977. bool JavascriptNativeFloatArray::Is(TypeId typeId)
  10978. {
  10979. return typeId == TypeIds_NativeFloatArray;
  10980. }
  10981. bool JavascriptNativeFloatArray::IsNonCrossSite(Var aValue)
  10982. {
  10983. bool ret = !TaggedInt::Is(aValue) && VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(aValue);
  10984. Assert(ret == (JavascriptNativeFloatArray::Is(aValue) && !JavascriptNativeFloatArray::FromVar(aValue)->IsCrossSiteObject()));
  10985. return ret;
  10986. }
  10987. JavascriptNativeFloatArray* JavascriptNativeFloatArray::FromVar(Var aValue)
  10988. {
  10989. AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeFloatArray'");
  10990. return static_cast<JavascriptNativeFloatArray *>(RecyclableObject::FromVar(aValue));
  10991. }
  10992. template int Js::JavascriptArray::GetParamForIndexOf<unsigned int>(unsigned int, Js::Arguments const&, void*&, unsigned int&, Js::ScriptContext*);
  10993. template bool Js::JavascriptArray::ArrayElementEnumerator::MoveNext<void*>();
  10994. template void Js::JavascriptArray::SetArrayLiteralItem<void*>(unsigned int, void*);
  10995. template void* Js::JavascriptArray::TemplatedIndexOfHelper<false, Js::TypedArrayBase, unsigned int>(Js::TypedArrayBase*, void*, unsigned int, unsigned int, Js::ScriptContext*);
  10996. template void* Js::JavascriptArray::TemplatedIndexOfHelper<true, Js::TypedArrayBase, unsigned int>(Js::TypedArrayBase*, void*, unsigned int, unsigned int, Js::ScriptContext*);
  10997. } //namespace Js