quickjs-amalgam.c 2.7 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801
  1. #if defined(QJS_BUILD_LIBC) && defined(__linux__) && !defined(_GNU_SOURCE)
  2. #define _GNU_SOURCE
  3. #endif
  4. /*
  5. * QuickJS C atomics definitions
  6. *
  7. * Copyright (c) 2023 Marcin Kolny
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  22. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. */
  27. #if (defined(__GNUC__) || defined(__GNUG__)) && !defined(__clang__)
  28. // Use GCC builtins for version < 4.9
  29. # if((__GNUC__ << 16) + __GNUC_MINOR__ < ((4) << 16) + 9)
  30. # define GCC_BUILTIN_ATOMICS
  31. # endif
  32. #endif
  33. #ifdef GCC_BUILTIN_ATOMICS
  34. #define atomic_fetch_add(obj, arg) \
  35. __atomic_fetch_add(obj, arg, __ATOMIC_SEQ_CST)
  36. #define atomic_compare_exchange_strong(obj, expected, desired) \
  37. __atomic_compare_exchange_n(obj, expected, desired, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)
  38. #define atomic_exchange(obj, desired) \
  39. __atomic_exchange_n (obj, desired, __ATOMIC_SEQ_CST)
  40. #define atomic_load(obj) \
  41. __atomic_load_n(obj, __ATOMIC_SEQ_CST)
  42. #define atomic_store(obj, desired) \
  43. __atomic_store_n(obj, desired, __ATOMIC_SEQ_CST)
  44. #define atomic_fetch_or(obj, arg) \
  45. __atomic_fetch_or(obj, arg, __ATOMIC_SEQ_CST)
  46. #define atomic_fetch_xor(obj, arg) \
  47. __atomic_fetch_xor(obj, arg, __ATOMIC_SEQ_CST)
  48. #define atomic_fetch_and(obj, arg) \
  49. __atomic_fetch_and(obj, arg, __ATOMIC_SEQ_CST)
  50. #define atomic_fetch_sub(obj, arg) \
  51. __atomic_fetch_sub(obj, arg, __ATOMIC_SEQ_CST)
  52. #define _Atomic
  53. #else
  54. #include <stdatomic.h>
  55. #endif
  56. /*
  57. * C utilities
  58. *
  59. * Copyright (c) 2017 Fabrice Bellard
  60. * Copyright (c) 2018 Charlie Gordon
  61. *
  62. * Permission is hereby granted, free of charge, to any person obtaining a copy
  63. * of this software and associated documentation files (the "Software"), to deal
  64. * in the Software without restriction, including without limitation the rights
  65. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  66. * copies of the Software, and to permit persons to whom the Software is
  67. * furnished to do so, subject to the following conditions:
  68. *
  69. * The above copyright notice and this permission notice shall be included in
  70. * all copies or substantial portions of the Software.
  71. *
  72. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  73. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  74. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  75. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  76. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  77. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  78. * THE SOFTWARE.
  79. */
  80. #ifndef CUTILS_H
  81. #define CUTILS_H
  82. #include <stdbool.h>
  83. #include <stdlib.h>
  84. #include <string.h>
  85. #include <inttypes.h>
  86. #include <math.h>
  87. #ifdef __cplusplus
  88. extern "C" {
  89. #endif
  90. #if defined(_MSC_VER)
  91. #include <winsock2.h>
  92. #include <malloc.h>
  93. #define alloca _alloca
  94. #define ssize_t ptrdiff_t
  95. #endif
  96. #if defined(__APPLE__)
  97. #include <malloc/malloc.h>
  98. #elif defined(__linux__) || defined(__ANDROID__) || defined(__CYGWIN__)
  99. #include <malloc.h>
  100. #elif defined(__FreeBSD__)
  101. #include <malloc_np.h>
  102. #elif defined(_WIN32)
  103. #include <windows.h>
  104. #endif
  105. #if !defined(_WIN32) && !defined(EMSCRIPTEN) && !defined(__wasi__)
  106. #include <errno.h>
  107. #include <pthread.h>
  108. #endif
  109. #if defined(_MSC_VER) && !defined(__clang__)
  110. # define likely(x) (x)
  111. # define unlikely(x) (x)
  112. # define force_inline __forceinline
  113. # define no_inline __declspec(noinline)
  114. # define __maybe_unused
  115. # define __attribute__(x)
  116. # define __attribute(x)
  117. #else
  118. # define likely(x) __builtin_expect(!!(x), 1)
  119. # define unlikely(x) __builtin_expect(!!(x), 0)
  120. # define force_inline inline __attribute__((always_inline))
  121. # define no_inline __attribute__((noinline))
  122. # define __maybe_unused __attribute__((unused))
  123. #endif
  124. #if defined(_MSC_VER) && !defined(__clang__)
  125. #include <math.h>
  126. #define INF INFINITY
  127. #define NEG_INF -INFINITY
  128. #else
  129. #define INF (1.0/0.0)
  130. #define NEG_INF (-1.0/0.0)
  131. #endif
  132. #ifndef offsetof
  133. #define offsetof(type, field) ((size_t) &((type *)0)->field)
  134. #endif
  135. #ifndef countof
  136. #define countof(x) (sizeof(x) / sizeof((x)[0]))
  137. #ifndef endof
  138. #define endof(x) ((x) + countof(x))
  139. #endif
  140. #endif
  141. #ifndef container_of
  142. /* return the pointer of type 'type *' containing 'ptr' as field 'member' */
  143. #define container_of(ptr, type, member) ((type *)((uint8_t *)(ptr) - offsetof(type, member)))
  144. #endif
  145. #if defined(_MSC_VER)
  146. #define minimum_length(n) n
  147. #else
  148. #define minimum_length(n) static n
  149. #endif
  150. /* Borrowed from Folly */
  151. #ifndef JS_PRINTF_FORMAT
  152. #ifdef _MSC_VER
  153. #include <sal.h>
  154. #define JS_PRINTF_FORMAT _Printf_format_string_
  155. #define JS_PRINTF_FORMAT_ATTR(format_param, dots_param)
  156. #else
  157. #define JS_PRINTF_FORMAT
  158. #if !defined(__clang__) && defined(__GNUC__)
  159. #define JS_PRINTF_FORMAT_ATTR(format_param, dots_param) \
  160. __attribute__((format(gnu_printf, format_param, dots_param)))
  161. #else
  162. #define JS_PRINTF_FORMAT_ATTR(format_param, dots_param) \
  163. __attribute__((format(printf, format_param, dots_param)))
  164. #endif
  165. #endif
  166. #endif
  167. ////
  168. #ifdef _WIN32
  169. /*
  170. * Dirent interface for Microsoft Visual Studio
  171. *
  172. * Copyright (C) 1998-2019 Toni Ronkko
  173. * This file is part of dirent. Dirent may be freely distributed
  174. * under the MIT license. For all details and documentation, see
  175. * https://github.com/tronkko/dirent
  176. */
  177. #ifndef DIRENT_H
  178. #define DIRENT_H
  179. /* Hide warnings about unreferenced local functions */
  180. #if defined(__clang__)
  181. # pragma clang diagnostic ignored "-Wunused-function"
  182. #elif defined(_MSC_VER)
  183. # pragma warning(disable:4505)
  184. #elif defined(__GNUC__)
  185. # pragma GCC diagnostic ignored "-Wunused-function"
  186. #endif
  187. /*
  188. * Include windows.h without Windows Sockets 1.1 to prevent conflicts with
  189. * Windows Sockets 2.0.
  190. */
  191. #ifndef WIN32_LEAN_AND_MEAN
  192. # define WIN32_LEAN_AND_MEAN
  193. #endif
  194. #include <windows.h>
  195. #include <stdio.h>
  196. #include <stdarg.h>
  197. #include <wchar.h>
  198. #include <string.h>
  199. #include <stdlib.h>
  200. #include <malloc.h>
  201. #include <sys/types.h>
  202. #include <sys/stat.h>
  203. #include <errno.h>
  204. /* Indicates that d_type field is available in dirent structure */
  205. #define _DIRENT_HAVE_D_TYPE
  206. /* Indicates that d_namlen field is available in dirent structure */
  207. #define _DIRENT_HAVE_D_NAMLEN
  208. /* Entries missing from MSVC 6.0 */
  209. #if !defined(FILE_ATTRIBUTE_DEVICE)
  210. # define FILE_ATTRIBUTE_DEVICE 0x40
  211. #endif
  212. /* File type and permission flags for stat(), general mask */
  213. #if !defined(S_IFMT)
  214. # define S_IFMT _S_IFMT
  215. #endif
  216. /* Directory bit */
  217. #if !defined(S_IFDIR)
  218. # define S_IFDIR _S_IFDIR
  219. #endif
  220. /* Character device bit */
  221. #if !defined(S_IFCHR)
  222. # define S_IFCHR _S_IFCHR
  223. #endif
  224. /* Pipe bit */
  225. #if !defined(S_IFFIFO)
  226. # define S_IFFIFO _S_IFFIFO
  227. #endif
  228. /* Regular file bit */
  229. #if !defined(S_IFREG)
  230. # define S_IFREG _S_IFREG
  231. #endif
  232. /* Read permission */
  233. #if !defined(S_IREAD)
  234. # define S_IREAD _S_IREAD
  235. #endif
  236. /* Write permission */
  237. #if !defined(S_IWRITE)
  238. # define S_IWRITE _S_IWRITE
  239. #endif
  240. /* Execute permission */
  241. #if !defined(S_IEXEC)
  242. # define S_IEXEC _S_IEXEC
  243. #endif
  244. /* Pipe */
  245. #if !defined(S_IFIFO)
  246. # define S_IFIFO _S_IFIFO
  247. #endif
  248. /* Block device */
  249. #if !defined(S_IFBLK)
  250. # define S_IFBLK 0
  251. #endif
  252. /* Link */
  253. #if !defined(S_IFLNK)
  254. # define S_IFLNK 0
  255. #endif
  256. /* Socket */
  257. #if !defined(S_IFSOCK)
  258. # define S_IFSOCK 0
  259. #endif
  260. /* Read user permission */
  261. #if !defined(S_IRUSR)
  262. # define S_IRUSR S_IREAD
  263. #endif
  264. /* Write user permission */
  265. #if !defined(S_IWUSR)
  266. # define S_IWUSR S_IWRITE
  267. #endif
  268. /* Execute user permission */
  269. #if !defined(S_IXUSR)
  270. # define S_IXUSR 0
  271. #endif
  272. /* Read group permission */
  273. #if !defined(S_IRGRP)
  274. # define S_IRGRP 0
  275. #endif
  276. /* Write group permission */
  277. #if !defined(S_IWGRP)
  278. # define S_IWGRP 0
  279. #endif
  280. /* Execute group permission */
  281. #if !defined(S_IXGRP)
  282. # define S_IXGRP 0
  283. #endif
  284. /* Read others permission */
  285. #if !defined(S_IROTH)
  286. # define S_IROTH 0
  287. #endif
  288. /* Write others permission */
  289. #if !defined(S_IWOTH)
  290. # define S_IWOTH 0
  291. #endif
  292. /* Execute others permission */
  293. #if !defined(S_IXOTH)
  294. # define S_IXOTH 0
  295. #endif
  296. /* Maximum length of file name */
  297. #if !defined(PATH_MAX)
  298. # define PATH_MAX MAX_PATH
  299. #endif
  300. #if !defined(FILENAME_MAX)
  301. # define FILENAME_MAX MAX_PATH
  302. #endif
  303. #if !defined(NAME_MAX)
  304. # define NAME_MAX FILENAME_MAX
  305. #endif
  306. /* File type flags for d_type */
  307. #define DT_UNKNOWN 0
  308. #define DT_REG S_IFREG
  309. #define DT_DIR S_IFDIR
  310. #define DT_FIFO S_IFIFO
  311. #define DT_SOCK S_IFSOCK
  312. #define DT_CHR S_IFCHR
  313. #define DT_BLK S_IFBLK
  314. #define DT_LNK S_IFLNK
  315. /* Macros for converting between st_mode and d_type */
  316. #define IFTODT(mode) ((mode) & S_IFMT)
  317. #define DTTOIF(type) (type)
  318. /*
  319. * File type macros. Note that block devices, sockets and links cannot be
  320. * distinguished on Windows and the macros S_ISBLK, S_ISSOCK and S_ISLNK are
  321. * only defined for compatibility. These macros should always return false
  322. * on Windows.
  323. */
  324. #if !defined(S_ISFIFO)
  325. # define S_ISFIFO(mode) (((mode) & S_IFMT) == S_IFIFO)
  326. #endif
  327. #if !defined(S_ISDIR)
  328. # define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
  329. #endif
  330. #if !defined(S_ISREG)
  331. # define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
  332. #endif
  333. #if !defined(S_ISLNK)
  334. # define S_ISLNK(mode) (((mode) & S_IFMT) == S_IFLNK)
  335. #endif
  336. #if !defined(S_ISSOCK)
  337. # define S_ISSOCK(mode) (((mode) & S_IFMT) == S_IFSOCK)
  338. #endif
  339. #if !defined(S_ISCHR)
  340. # define S_ISCHR(mode) (((mode) & S_IFMT) == S_IFCHR)
  341. #endif
  342. #if !defined(S_ISBLK)
  343. # define S_ISBLK(mode) (((mode) & S_IFMT) == S_IFBLK)
  344. #endif
  345. /* Return the exact length of the file name without zero terminator */
  346. #define _D_EXACT_NAMLEN(p) ((p)->d_namlen)
  347. /* Return the maximum size of a file name */
  348. #define _D_ALLOC_NAMLEN(p) ((PATH_MAX)+1)
  349. #ifdef __cplusplus
  350. extern "C" {
  351. #endif
  352. /* Wide-character version */
  353. struct _wdirent {
  354. /* Always zero */
  355. long d_ino;
  356. /* File position within stream */
  357. long d_off;
  358. /* Structure size */
  359. unsigned short d_reclen;
  360. /* Length of name without \0 */
  361. size_t d_namlen;
  362. /* File type */
  363. int d_type;
  364. /* File name */
  365. wchar_t d_name[PATH_MAX+1];
  366. };
  367. typedef struct _wdirent _wdirent;
  368. struct _WDIR {
  369. /* Current directory entry */
  370. struct _wdirent ent;
  371. /* Private file data */
  372. WIN32_FIND_DATAW data;
  373. /* True if data is valid */
  374. int cached;
  375. /* Win32 search handle */
  376. HANDLE handle;
  377. /* Initial directory name */
  378. wchar_t *patt;
  379. };
  380. typedef struct _WDIR _WDIR;
  381. /* Multi-byte character version */
  382. struct dirent {
  383. /* Always zero */
  384. long d_ino;
  385. /* File position within stream */
  386. long d_off;
  387. /* Structure size */
  388. unsigned short d_reclen;
  389. /* Length of name without \0 */
  390. size_t d_namlen;
  391. /* File type */
  392. int d_type;
  393. /* File name */
  394. char d_name[PATH_MAX+1];
  395. };
  396. typedef struct dirent dirent;
  397. struct DIR {
  398. struct dirent ent;
  399. struct _WDIR *wdirp;
  400. };
  401. typedef struct DIR DIR;
  402. /* Dirent functions */
  403. static DIR *opendir (const char *dirname);
  404. static _WDIR *_wopendir (const wchar_t *dirname);
  405. static struct dirent *readdir (DIR *dirp);
  406. static struct _wdirent *_wreaddir (_WDIR *dirp);
  407. static int readdir_r(
  408. DIR *dirp, struct dirent *entry, struct dirent **result);
  409. static int _wreaddir_r(
  410. _WDIR *dirp, struct _wdirent *entry, struct _wdirent **result);
  411. static int closedir (DIR *dirp);
  412. static int _wclosedir (_WDIR *dirp);
  413. static void rewinddir (DIR* dirp);
  414. static void _wrewinddir (_WDIR* dirp);
  415. static int scandir (const char *dirname, struct dirent ***namelist,
  416. int (*filter)(const struct dirent*),
  417. int (*compare)(const struct dirent**, const struct dirent**));
  418. static int alphasort (const struct dirent **a, const struct dirent **b);
  419. static int versionsort (const struct dirent **a, const struct dirent **b);
  420. /* For compatibility with Symbian */
  421. #define wdirent _wdirent
  422. #define WDIR _WDIR
  423. #define wopendir _wopendir
  424. #define wreaddir _wreaddir
  425. #define wclosedir _wclosedir
  426. #define wrewinddir _wrewinddir
  427. /* Internal utility functions */
  428. static WIN32_FIND_DATAW *dirent_first (_WDIR *dirp);
  429. static WIN32_FIND_DATAW *dirent_next (_WDIR *dirp);
  430. static int dirent_mbstowcs_s(
  431. size_t *pReturnValue,
  432. wchar_t *wcstr,
  433. size_t sizeInWords,
  434. const char *mbstr,
  435. size_t count);
  436. static int dirent_wcstombs_s(
  437. size_t *pReturnValue,
  438. char *mbstr,
  439. size_t sizeInBytes,
  440. const wchar_t *wcstr,
  441. size_t count);
  442. static void dirent_set_errno (int error);
  443. /*
  444. * Open directory stream DIRNAME for read and return a pointer to the
  445. * internal working area that is used to retrieve individual directory
  446. * entries.
  447. */
  448. static _WDIR*
  449. _wopendir(
  450. const wchar_t *dirname)
  451. {
  452. _WDIR *dirp;
  453. #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
  454. /* Desktop */
  455. DWORD n;
  456. #else
  457. /* WinRT */
  458. size_t n;
  459. #endif
  460. wchar_t *p;
  461. /* Must have directory name */
  462. if (dirname == NULL || dirname[0] == '\0') {
  463. dirent_set_errno (ENOENT);
  464. return NULL;
  465. }
  466. /* Allocate new _WDIR structure */
  467. dirp = (_WDIR*) malloc (sizeof (struct _WDIR));
  468. if (!dirp) {
  469. return NULL;
  470. }
  471. /* Reset _WDIR structure */
  472. dirp->handle = INVALID_HANDLE_VALUE;
  473. dirp->patt = NULL;
  474. dirp->cached = 0;
  475. /*
  476. * Compute the length of full path plus zero terminator
  477. *
  478. * Note that on WinRT there's no way to convert relative paths
  479. * into absolute paths, so just assume it is an absolute path.
  480. */
  481. #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
  482. /* Desktop */
  483. n = GetFullPathNameW (dirname, 0, NULL, NULL);
  484. #else
  485. /* WinRT */
  486. n = wcslen (dirname);
  487. #endif
  488. /* Allocate room for absolute directory name and search pattern */
  489. dirp->patt = (wchar_t*) malloc (sizeof (wchar_t) * n + 16);
  490. if (dirp->patt == NULL) {
  491. goto exit_closedir;
  492. }
  493. /*
  494. * Convert relative directory name to an absolute one. This
  495. * allows rewinddir() to function correctly even when current
  496. * working directory is changed between opendir() and rewinddir().
  497. *
  498. * Note that on WinRT there's no way to convert relative paths
  499. * into absolute paths, so just assume it is an absolute path.
  500. */
  501. #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
  502. /* Desktop */
  503. n = GetFullPathNameW (dirname, n, dirp->patt, NULL);
  504. if (n <= 0) {
  505. goto exit_closedir;
  506. }
  507. #else
  508. /* WinRT */
  509. wcsncpy_s (dirp->patt, n+1, dirname, n);
  510. #endif
  511. /* Append search pattern \* to the directory name */
  512. p = dirp->patt + n;
  513. switch (p[-1]) {
  514. case '\\':
  515. case '/':
  516. case ':':
  517. /* Directory ends in path separator, e.g. c:\temp\ */
  518. /*NOP*/;
  519. break;
  520. default:
  521. /* Directory name doesn't end in path separator */
  522. *p++ = '\\';
  523. }
  524. *p++ = '*';
  525. *p = '\0';
  526. /* Open directory stream and retrieve the first entry */
  527. if (!dirent_first (dirp)) {
  528. goto exit_closedir;
  529. }
  530. /* Success */
  531. return dirp;
  532. /* Failure */
  533. exit_closedir:
  534. _wclosedir (dirp);
  535. return NULL;
  536. }
  537. /*
  538. * Read next directory entry.
  539. *
  540. * Returns pointer to static directory entry which may be overwritten by
  541. * subsequent calls to _wreaddir().
  542. */
  543. static struct _wdirent*
  544. _wreaddir(
  545. _WDIR *dirp)
  546. {
  547. struct _wdirent *entry;
  548. /*
  549. * Read directory entry to buffer. We can safely ignore the return value
  550. * as entry will be set to NULL in case of error.
  551. */
  552. (void) _wreaddir_r (dirp, &dirp->ent, &entry);
  553. /* Return pointer to statically allocated directory entry */
  554. return entry;
  555. }
  556. /*
  557. * Read next directory entry.
  558. *
  559. * Returns zero on success. If end of directory stream is reached, then sets
  560. * result to NULL and returns zero.
  561. */
  562. static int
  563. _wreaddir_r(
  564. _WDIR *dirp,
  565. struct _wdirent *entry,
  566. struct _wdirent **result)
  567. {
  568. WIN32_FIND_DATAW *datap;
  569. /* Read next directory entry */
  570. datap = dirent_next (dirp);
  571. if (datap) {
  572. size_t n;
  573. DWORD attr;
  574. /*
  575. * Copy file name as wide-character string. If the file name is too
  576. * long to fit in to the destination buffer, then truncate file name
  577. * to PATH_MAX characters and zero-terminate the buffer.
  578. */
  579. n = 0;
  580. while (n < PATH_MAX && datap->cFileName[n] != 0) {
  581. entry->d_name[n] = datap->cFileName[n];
  582. n++;
  583. }
  584. entry->d_name[n] = 0;
  585. /* Length of file name excluding zero terminator */
  586. entry->d_namlen = n;
  587. /* File type */
  588. attr = datap->dwFileAttributes;
  589. if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) {
  590. entry->d_type = DT_CHR;
  591. } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
  592. entry->d_type = DT_DIR;
  593. } else {
  594. entry->d_type = DT_REG;
  595. }
  596. /* Reset dummy fields */
  597. entry->d_ino = 0;
  598. entry->d_off = 0;
  599. entry->d_reclen = sizeof (struct _wdirent);
  600. /* Set result address */
  601. *result = entry;
  602. } else {
  603. /* Return NULL to indicate end of directory */
  604. *result = NULL;
  605. }
  606. return /*OK*/0;
  607. }
  608. /*
  609. * Close directory stream opened by opendir() function. This invalidates the
  610. * DIR structure as well as any directory entry read previously by
  611. * _wreaddir().
  612. */
  613. static int
  614. _wclosedir(
  615. _WDIR *dirp)
  616. {
  617. int ok;
  618. if (dirp) {
  619. /* Release search handle */
  620. if (dirp->handle != INVALID_HANDLE_VALUE) {
  621. FindClose (dirp->handle);
  622. }
  623. /* Release search pattern */
  624. free (dirp->patt);
  625. /* Release directory structure */
  626. free (dirp);
  627. ok = /*success*/0;
  628. } else {
  629. /* Invalid directory stream */
  630. dirent_set_errno (EBADF);
  631. ok = /*failure*/-1;
  632. }
  633. return ok;
  634. }
  635. /*
  636. * Rewind directory stream such that _wreaddir() returns the very first
  637. * file name again.
  638. */
  639. static void
  640. _wrewinddir(
  641. _WDIR* dirp)
  642. {
  643. if (dirp) {
  644. /* Release existing search handle */
  645. if (dirp->handle != INVALID_HANDLE_VALUE) {
  646. FindClose (dirp->handle);
  647. }
  648. /* Open new search handle */
  649. dirent_first (dirp);
  650. }
  651. }
  652. /* Get first directory entry (internal) */
  653. static WIN32_FIND_DATAW*
  654. dirent_first(
  655. _WDIR *dirp)
  656. {
  657. WIN32_FIND_DATAW *datap;
  658. DWORD error;
  659. /* Open directory and retrieve the first entry */
  660. dirp->handle = FindFirstFileExW(
  661. dirp->patt, FindExInfoStandard, &dirp->data,
  662. FindExSearchNameMatch, NULL, 0);
  663. if (dirp->handle != INVALID_HANDLE_VALUE) {
  664. /* a directory entry is now waiting in memory */
  665. datap = &dirp->data;
  666. dirp->cached = 1;
  667. } else {
  668. /* Failed to open directory: no directory entry in memory */
  669. dirp->cached = 0;
  670. datap = NULL;
  671. /* Set error code */
  672. error = GetLastError ();
  673. switch (error) {
  674. case ERROR_ACCESS_DENIED:
  675. /* No read access to directory */
  676. dirent_set_errno (EACCES);
  677. break;
  678. case ERROR_DIRECTORY:
  679. /* Directory name is invalid */
  680. dirent_set_errno (ENOTDIR);
  681. break;
  682. case ERROR_PATH_NOT_FOUND:
  683. default:
  684. /* Cannot find the file */
  685. dirent_set_errno (ENOENT);
  686. }
  687. }
  688. return datap;
  689. }
  690. /*
  691. * Get next directory entry (internal).
  692. *
  693. * Returns
  694. */
  695. static WIN32_FIND_DATAW*
  696. dirent_next(
  697. _WDIR *dirp)
  698. {
  699. WIN32_FIND_DATAW *p;
  700. /* Get next directory entry */
  701. if (dirp->cached != 0) {
  702. /* A valid directory entry already in memory */
  703. p = &dirp->data;
  704. dirp->cached = 0;
  705. } else if (dirp->handle != INVALID_HANDLE_VALUE) {
  706. /* Get the next directory entry from stream */
  707. if (FindNextFileW (dirp->handle, &dirp->data) != 0) {
  708. /* Got a file */
  709. p = &dirp->data;
  710. } else {
  711. /* The very last entry has been processed or an error occurred */
  712. FindClose (dirp->handle);
  713. dirp->handle = INVALID_HANDLE_VALUE;
  714. p = NULL;
  715. }
  716. } else {
  717. /* End of directory stream reached */
  718. p = NULL;
  719. }
  720. return p;
  721. }
  722. /*
  723. * Open directory stream using plain old C-string.
  724. */
  725. static DIR*
  726. opendir(
  727. const char *dirname)
  728. {
  729. struct DIR *dirp;
  730. /* Must have directory name */
  731. if (dirname == NULL || dirname[0] == '\0') {
  732. dirent_set_errno (ENOENT);
  733. return NULL;
  734. }
  735. /* Allocate memory for DIR structure */
  736. dirp = (DIR*) malloc (sizeof (struct DIR));
  737. if (!dirp) {
  738. return NULL;
  739. }
  740. {
  741. int error;
  742. wchar_t wname[PATH_MAX + 1];
  743. size_t n;
  744. /* Convert directory name to wide-character string */
  745. error = dirent_mbstowcs_s(
  746. &n, wname, PATH_MAX + 1, dirname, PATH_MAX + 1);
  747. if (error) {
  748. /*
  749. * Cannot convert file name to wide-character string. This
  750. * occurs if the string contains invalid multi-byte sequences or
  751. * the output buffer is too small to contain the resulting
  752. * string.
  753. */
  754. goto exit_free;
  755. }
  756. /* Open directory stream using wide-character name */
  757. dirp->wdirp = _wopendir (wname);
  758. if (!dirp->wdirp) {
  759. goto exit_free;
  760. }
  761. }
  762. /* Success */
  763. return dirp;
  764. /* Failure */
  765. exit_free:
  766. free (dirp);
  767. return NULL;
  768. }
  769. /*
  770. * Read next directory entry.
  771. */
  772. static struct dirent*
  773. readdir(
  774. DIR *dirp)
  775. {
  776. struct dirent *entry;
  777. /*
  778. * Read directory entry to buffer. We can safely ignore the return value
  779. * as entry will be set to NULL in case of error.
  780. */
  781. (void) readdir_r (dirp, &dirp->ent, &entry);
  782. /* Return pointer to statically allocated directory entry */
  783. return entry;
  784. }
  785. /*
  786. * Read next directory entry into called-allocated buffer.
  787. *
  788. * Returns zero on success. If the end of directory stream is reached, then
  789. * sets result to NULL and returns zero.
  790. */
  791. static int
  792. readdir_r(
  793. DIR *dirp,
  794. struct dirent *entry,
  795. struct dirent **result)
  796. {
  797. WIN32_FIND_DATAW *datap;
  798. /* Read next directory entry */
  799. datap = dirent_next (dirp->wdirp);
  800. if (datap) {
  801. size_t n;
  802. int error;
  803. /* Attempt to convert file name to multi-byte string */
  804. error = dirent_wcstombs_s(
  805. &n, entry->d_name, PATH_MAX + 1, datap->cFileName, PATH_MAX + 1);
  806. /*
  807. * If the file name cannot be represented by a multi-byte string,
  808. * then attempt to use old 8+3 file name. This allows traditional
  809. * Unix-code to access some file names despite of unicode
  810. * characters, although file names may seem unfamiliar to the user.
  811. *
  812. * Be ware that the code below cannot come up with a short file
  813. * name unless the file system provides one. At least
  814. * VirtualBox shared folders fail to do this.
  815. */
  816. if (error && datap->cAlternateFileName[0] != '\0') {
  817. error = dirent_wcstombs_s(
  818. &n, entry->d_name, PATH_MAX + 1,
  819. datap->cAlternateFileName, PATH_MAX + 1);
  820. }
  821. if (!error) {
  822. DWORD attr;
  823. /* Length of file name excluding zero terminator */
  824. entry->d_namlen = n - 1;
  825. /* File attributes */
  826. attr = datap->dwFileAttributes;
  827. if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) {
  828. entry->d_type = DT_CHR;
  829. } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
  830. entry->d_type = DT_DIR;
  831. } else {
  832. entry->d_type = DT_REG;
  833. }
  834. /* Reset dummy fields */
  835. entry->d_ino = 0;
  836. entry->d_off = 0;
  837. entry->d_reclen = sizeof (struct dirent);
  838. } else {
  839. /*
  840. * Cannot convert file name to multi-byte string so construct
  841. * an erroneous directory entry and return that. Note that
  842. * we cannot return NULL as that would stop the processing
  843. * of directory entries completely.
  844. */
  845. entry->d_name[0] = '?';
  846. entry->d_name[1] = '\0';
  847. entry->d_namlen = 1;
  848. entry->d_type = DT_UNKNOWN;
  849. entry->d_ino = 0;
  850. entry->d_off = -1;
  851. entry->d_reclen = 0;
  852. }
  853. /* Return pointer to directory entry */
  854. *result = entry;
  855. } else {
  856. /* No more directory entries */
  857. *result = NULL;
  858. }
  859. return /*OK*/0;
  860. }
  861. /*
  862. * Close directory stream.
  863. */
  864. static int
  865. closedir(
  866. DIR *dirp)
  867. {
  868. int ok;
  869. if (dirp) {
  870. /* Close wide-character directory stream */
  871. ok = _wclosedir (dirp->wdirp);
  872. dirp->wdirp = NULL;
  873. /* Release multi-byte character version */
  874. free (dirp);
  875. } else {
  876. /* Invalid directory stream */
  877. dirent_set_errno (EBADF);
  878. ok = /*failure*/-1;
  879. }
  880. return ok;
  881. }
  882. /*
  883. * Rewind directory stream to beginning.
  884. */
  885. static void
  886. rewinddir(
  887. DIR* dirp)
  888. {
  889. /* Rewind wide-character string directory stream */
  890. _wrewinddir (dirp->wdirp);
  891. }
  892. /*
  893. * Scan directory for entries.
  894. */
  895. static int
  896. scandir(
  897. const char *dirname,
  898. struct dirent ***namelist,
  899. int (*filter)(const struct dirent*),
  900. int (*compare)(const struct dirent**, const struct dirent**))
  901. {
  902. struct dirent **files = NULL;
  903. size_t size = 0;
  904. size_t allocated = 0;
  905. const size_t init_size = 1;
  906. DIR *dir = NULL;
  907. struct dirent *entry;
  908. struct dirent *tmp = NULL;
  909. size_t i;
  910. int result = 0;
  911. /* Open directory stream */
  912. dir = opendir (dirname);
  913. if (dir) {
  914. /* Read directory entries to memory */
  915. while (1) {
  916. /* Enlarge pointer table to make room for another pointer */
  917. if (size >= allocated) {
  918. void *p;
  919. size_t num_entries;
  920. /* Compute number of entries in the enlarged pointer table */
  921. if (size < init_size) {
  922. /* Allocate initial pointer table */
  923. num_entries = init_size;
  924. } else {
  925. /* Double the size */
  926. num_entries = size * 2;
  927. }
  928. /* Allocate first pointer table or enlarge existing table */
  929. p = realloc (files, sizeof (void*) * num_entries);
  930. if (p != NULL) {
  931. /* Got the memory */
  932. files = (dirent**) p;
  933. allocated = num_entries;
  934. } else {
  935. /* Out of memory */
  936. result = -1;
  937. break;
  938. }
  939. }
  940. /* Allocate room for temporary directory entry */
  941. if (tmp == NULL) {
  942. tmp = (struct dirent*) malloc (sizeof (struct dirent));
  943. if (tmp == NULL) {
  944. /* Cannot allocate temporary directory entry */
  945. result = -1;
  946. break;
  947. }
  948. }
  949. /* Read directory entry to temporary area */
  950. if (readdir_r (dir, tmp, &entry) == /*OK*/0) {
  951. /* Did we get an entry? */
  952. if (entry != NULL) {
  953. int pass;
  954. /* Determine whether to include the entry in result */
  955. if (filter) {
  956. /* Let the filter function decide */
  957. pass = filter (tmp);
  958. } else {
  959. /* No filter function, include everything */
  960. pass = 1;
  961. }
  962. if (pass) {
  963. /* Store the temporary entry to pointer table */
  964. files[size++] = tmp;
  965. tmp = NULL;
  966. /* Keep up with the number of files */
  967. result++;
  968. }
  969. } else {
  970. /*
  971. * End of directory stream reached => sort entries and
  972. * exit.
  973. */
  974. qsort (files, size, sizeof (void*),
  975. (int (*) (const void*, const void*)) compare);
  976. break;
  977. }
  978. } else {
  979. /* Error reading directory entry */
  980. result = /*Error*/ -1;
  981. break;
  982. }
  983. }
  984. } else {
  985. /* Cannot open directory */
  986. result = /*Error*/ -1;
  987. }
  988. /* Release temporary directory entry */
  989. free (tmp);
  990. /* Release allocated memory on error */
  991. if (result < 0) {
  992. for (i = 0; i < size; i++) {
  993. free (files[i]);
  994. }
  995. free (files);
  996. files = NULL;
  997. }
  998. /* Close directory stream */
  999. if (dir) {
  1000. closedir (dir);
  1001. }
  1002. /* Pass pointer table to caller */
  1003. if (namelist) {
  1004. *namelist = files;
  1005. }
  1006. return result;
  1007. }
  1008. /* Alphabetical sorting */
  1009. static int
  1010. alphasort(
  1011. const struct dirent **a, const struct dirent **b)
  1012. {
  1013. return strcoll ((*a)->d_name, (*b)->d_name);
  1014. }
  1015. /* Sort versions */
  1016. static int
  1017. versionsort(
  1018. const struct dirent **a, const struct dirent **b)
  1019. {
  1020. /* FIXME: implement strverscmp and use that */
  1021. return alphasort (a, b);
  1022. }
  1023. /* Convert multi-byte string to wide character string */
  1024. static int
  1025. dirent_mbstowcs_s(
  1026. size_t *pReturnValue,
  1027. wchar_t *wcstr,
  1028. size_t sizeInWords,
  1029. const char *mbstr,
  1030. size_t count)
  1031. {
  1032. int error;
  1033. #if defined(_MSC_VER) && _MSC_VER >= 1400
  1034. /* Microsoft Visual Studio 2005 or later */
  1035. error = mbstowcs_s (pReturnValue, wcstr, sizeInWords, mbstr, count);
  1036. #else
  1037. /* Older Visual Studio or non-Microsoft compiler */
  1038. size_t n;
  1039. /* Convert to wide-character string (or count characters) */
  1040. n = mbstowcs (wcstr, mbstr, sizeInWords);
  1041. if (!wcstr || n < count) {
  1042. /* Zero-terminate output buffer */
  1043. if (wcstr && sizeInWords) {
  1044. if (n >= sizeInWords) {
  1045. n = sizeInWords - 1;
  1046. }
  1047. wcstr[n] = 0;
  1048. }
  1049. /* Length of resulting multi-byte string WITH zero terminator */
  1050. if (pReturnValue) {
  1051. *pReturnValue = n + 1;
  1052. }
  1053. /* Success */
  1054. error = 0;
  1055. } else {
  1056. /* Could not convert string */
  1057. error = 1;
  1058. }
  1059. #endif
  1060. return error;
  1061. }
  1062. /* Convert wide-character string to multi-byte string */
  1063. static int
  1064. dirent_wcstombs_s(
  1065. size_t *pReturnValue,
  1066. char *mbstr,
  1067. size_t sizeInBytes, /* max size of mbstr */
  1068. const wchar_t *wcstr,
  1069. size_t count)
  1070. {
  1071. int error;
  1072. #if defined(_MSC_VER) && _MSC_VER >= 1400
  1073. /* Microsoft Visual Studio 2005 or later */
  1074. error = wcstombs_s (pReturnValue, mbstr, sizeInBytes, wcstr, count);
  1075. #else
  1076. /* Older Visual Studio or non-Microsoft compiler */
  1077. size_t n;
  1078. /* Convert to multi-byte string (or count the number of bytes needed) */
  1079. n = wcstombs (mbstr, wcstr, sizeInBytes);
  1080. if (!mbstr || n < count) {
  1081. /* Zero-terminate output buffer */
  1082. if (mbstr && sizeInBytes) {
  1083. if (n >= sizeInBytes) {
  1084. n = sizeInBytes - 1;
  1085. }
  1086. mbstr[n] = '\0';
  1087. }
  1088. /* Length of resulting multi-bytes string WITH zero-terminator */
  1089. if (pReturnValue) {
  1090. *pReturnValue = n + 1;
  1091. }
  1092. /* Success */
  1093. error = 0;
  1094. } else {
  1095. /* Cannot convert string */
  1096. error = 1;
  1097. }
  1098. #endif
  1099. return error;
  1100. }
  1101. /* Set errno variable */
  1102. static void
  1103. dirent_set_errno(
  1104. int error)
  1105. {
  1106. #if defined(_MSC_VER) && _MSC_VER >= 1400
  1107. /* Microsoft Visual Studio 2005 and later */
  1108. _set_errno (error);
  1109. #else
  1110. /* Non-Microsoft compiler or older Microsoft compiler */
  1111. errno = error;
  1112. #endif
  1113. }
  1114. #ifdef __cplusplus
  1115. }
  1116. #endif
  1117. #endif /*DIRENT_H*/
  1118. #endif // _WIN32
  1119. ////
  1120. void js__pstrcpy(char *buf, int buf_size, const char *str);
  1121. char *js__pstrcat(char *buf, int buf_size, const char *s);
  1122. int js__strstart(const char *str, const char *val, const char **ptr);
  1123. int js__has_suffix(const char *str, const char *suffix);
  1124. static inline uint8_t is_be(void) {
  1125. union {
  1126. uint16_t a;
  1127. uint8_t b;
  1128. } u = { 0x100 };
  1129. return u.b;
  1130. }
  1131. static inline int max_int(int a, int b)
  1132. {
  1133. if (a > b)
  1134. return a;
  1135. else
  1136. return b;
  1137. }
  1138. static inline int min_int(int a, int b)
  1139. {
  1140. if (a < b)
  1141. return a;
  1142. else
  1143. return b;
  1144. }
  1145. static inline uint32_t max_uint32(uint32_t a, uint32_t b)
  1146. {
  1147. if (a > b)
  1148. return a;
  1149. else
  1150. return b;
  1151. }
  1152. static inline uint32_t min_uint32(uint32_t a, uint32_t b)
  1153. {
  1154. if (a < b)
  1155. return a;
  1156. else
  1157. return b;
  1158. }
  1159. static inline int64_t max_int64(int64_t a, int64_t b)
  1160. {
  1161. if (a > b)
  1162. return a;
  1163. else
  1164. return b;
  1165. }
  1166. static inline int64_t min_int64(int64_t a, int64_t b)
  1167. {
  1168. if (a < b)
  1169. return a;
  1170. else
  1171. return b;
  1172. }
  1173. /* WARNING: undefined if a = 0 */
  1174. static inline int clz32(unsigned int a)
  1175. {
  1176. #if defined(_MSC_VER) && !defined(__clang__)
  1177. unsigned long index;
  1178. _BitScanReverse(&index, a);
  1179. return 31 - index;
  1180. #else
  1181. return __builtin_clz(a);
  1182. #endif
  1183. }
  1184. /* WARNING: undefined if a = 0 */
  1185. static inline int clz64(uint64_t a)
  1186. {
  1187. #if defined(_MSC_VER) && !defined(__clang__)
  1188. #if INTPTR_MAX == INT64_MAX
  1189. unsigned long index;
  1190. _BitScanReverse64(&index, a);
  1191. return 63 - index;
  1192. #else
  1193. if (a >> 32)
  1194. return clz32((unsigned)(a >> 32));
  1195. else
  1196. return clz32((unsigned)a) + 32;
  1197. #endif
  1198. #else
  1199. return __builtin_clzll(a);
  1200. #endif
  1201. }
  1202. /* WARNING: undefined if a = 0 */
  1203. static inline int ctz32(unsigned int a)
  1204. {
  1205. #if defined(_MSC_VER) && !defined(__clang__)
  1206. unsigned long index;
  1207. _BitScanForward(&index, a);
  1208. return index;
  1209. #else
  1210. return __builtin_ctz(a);
  1211. #endif
  1212. }
  1213. /* WARNING: undefined if a = 0 */
  1214. static inline int ctz64(uint64_t a)
  1215. {
  1216. #if defined(_MSC_VER) && !defined(__clang__)
  1217. unsigned long index;
  1218. _BitScanForward64(&index, a);
  1219. return index;
  1220. #else
  1221. return __builtin_ctzll(a);
  1222. #endif
  1223. }
  1224. static inline uint64_t get_u64(const uint8_t *tab)
  1225. {
  1226. uint64_t v;
  1227. memcpy(&v, tab, sizeof(v));
  1228. return v;
  1229. }
  1230. static inline int64_t get_i64(const uint8_t *tab)
  1231. {
  1232. int64_t v;
  1233. memcpy(&v, tab, sizeof(v));
  1234. return v;
  1235. }
  1236. static inline void put_u64(uint8_t *tab, uint64_t val)
  1237. {
  1238. memcpy(tab, &val, sizeof(val));
  1239. }
  1240. static inline uint32_t get_u32(const uint8_t *tab)
  1241. {
  1242. uint32_t v;
  1243. memcpy(&v, tab, sizeof(v));
  1244. return v;
  1245. }
  1246. static inline int32_t get_i32(const uint8_t *tab)
  1247. {
  1248. int32_t v;
  1249. memcpy(&v, tab, sizeof(v));
  1250. return v;
  1251. }
  1252. static inline void put_u32(uint8_t *tab, uint32_t val)
  1253. {
  1254. memcpy(tab, &val, sizeof(val));
  1255. }
  1256. static inline uint32_t get_u16(const uint8_t *tab)
  1257. {
  1258. uint16_t v;
  1259. memcpy(&v, tab, sizeof(v));
  1260. return v;
  1261. }
  1262. static inline int32_t get_i16(const uint8_t *tab)
  1263. {
  1264. int16_t v;
  1265. memcpy(&v, tab, sizeof(v));
  1266. return v;
  1267. }
  1268. static inline void put_u16(uint8_t *tab, uint16_t val)
  1269. {
  1270. memcpy(tab, &val, sizeof(val));
  1271. }
  1272. static inline uint32_t get_u8(const uint8_t *tab)
  1273. {
  1274. return *tab;
  1275. }
  1276. static inline int32_t get_i8(const uint8_t *tab)
  1277. {
  1278. return (int8_t)*tab;
  1279. }
  1280. static inline void put_u8(uint8_t *tab, uint8_t val)
  1281. {
  1282. *tab = val;
  1283. }
  1284. #ifndef bswap16
  1285. static inline uint16_t bswap16(uint16_t x)
  1286. {
  1287. return (x >> 8) | (x << 8);
  1288. }
  1289. #endif
  1290. #ifndef bswap32
  1291. static inline uint32_t bswap32(uint32_t v)
  1292. {
  1293. return ((v & 0xff000000) >> 24) | ((v & 0x00ff0000) >> 8) |
  1294. ((v & 0x0000ff00) << 8) | ((v & 0x000000ff) << 24);
  1295. }
  1296. #endif
  1297. #ifndef bswap64
  1298. static inline uint64_t bswap64(uint64_t v)
  1299. {
  1300. return ((v & ((uint64_t)0xff << (7 * 8))) >> (7 * 8)) |
  1301. ((v & ((uint64_t)0xff << (6 * 8))) >> (5 * 8)) |
  1302. ((v & ((uint64_t)0xff << (5 * 8))) >> (3 * 8)) |
  1303. ((v & ((uint64_t)0xff << (4 * 8))) >> (1 * 8)) |
  1304. ((v & ((uint64_t)0xff << (3 * 8))) << (1 * 8)) |
  1305. ((v & ((uint64_t)0xff << (2 * 8))) << (3 * 8)) |
  1306. ((v & ((uint64_t)0xff << (1 * 8))) << (5 * 8)) |
  1307. ((v & ((uint64_t)0xff << (0 * 8))) << (7 * 8));
  1308. }
  1309. #endif
  1310. static inline void inplace_bswap16(uint8_t *tab) {
  1311. put_u16(tab, bswap16(get_u16(tab)));
  1312. }
  1313. static inline void inplace_bswap32(uint8_t *tab) {
  1314. put_u32(tab, bswap32(get_u32(tab)));
  1315. }
  1316. static inline double fromfp16(uint16_t v) {
  1317. double d, s;
  1318. int e;
  1319. if ((v & 0x7C00) == 0x7C00) {
  1320. d = (v & 0x3FF) ? NAN : INFINITY;
  1321. } else {
  1322. d = (v & 0x3FF) / 1024.;
  1323. e = (v & 0x7C00) >> 10;
  1324. if (e == 0) {
  1325. e = -14;
  1326. } else {
  1327. d += 1;
  1328. e -= 15;
  1329. }
  1330. d = scalbn(d, e);
  1331. }
  1332. s = (v & 0x8000) ? -1.0 : 1.0;
  1333. return d * s;
  1334. }
  1335. static inline uint16_t tofp16(double d) {
  1336. uint16_t f, s;
  1337. double t;
  1338. int e;
  1339. s = 0;
  1340. if (copysign(1, d) < 0) { // preserve sign when |d| is negative zero
  1341. d = -d;
  1342. s = 0x8000;
  1343. }
  1344. if (isinf(d))
  1345. return s | 0x7C00;
  1346. if (isnan(d))
  1347. return s | 0x7C01;
  1348. if (d == 0)
  1349. return s | 0;
  1350. d = 2 * frexp(d, &e);
  1351. e--;
  1352. if (e > 15)
  1353. return s | 0x7C00; // out of range, return +/-infinity
  1354. if (e < -25) {
  1355. d = 0;
  1356. e = 0;
  1357. } else if (e < -14) {
  1358. d = scalbn(d, e + 14);
  1359. e = 0;
  1360. } else {
  1361. d -= 1;
  1362. e += 15;
  1363. }
  1364. d *= 1024.;
  1365. f = (uint16_t)d;
  1366. t = d - f;
  1367. if (t < 0.5)
  1368. goto done;
  1369. if (t == 0.5)
  1370. if ((f & 1) == 0)
  1371. goto done;
  1372. // adjust for rounding
  1373. if (++f == 1024) {
  1374. f = 0;
  1375. if (++e == 31)
  1376. return s | 0x7C00; // out of range, return +/-infinity
  1377. }
  1378. done:
  1379. return s | (e << 10) | f;
  1380. }
  1381. static inline int isfp16nan(uint16_t v) {
  1382. return (v & 0x7FFF) > 0x7C00;
  1383. }
  1384. static inline int isfp16zero(uint16_t v) {
  1385. return (v & 0x7FFF) == 0;
  1386. }
  1387. /* XXX: should take an extra argument to pass slack information to the caller */
  1388. typedef void *DynBufReallocFunc(void *opaque, void *ptr, size_t size);
  1389. typedef struct DynBuf {
  1390. uint8_t *buf;
  1391. size_t size;
  1392. size_t allocated_size;
  1393. bool error; /* true if a memory allocation error occurred */
  1394. DynBufReallocFunc *realloc_func;
  1395. void *opaque; /* for realloc_func */
  1396. } DynBuf;
  1397. void dbuf_init(DynBuf *s);
  1398. void dbuf_init2(DynBuf *s, void *opaque, DynBufReallocFunc *realloc_func);
  1399. int dbuf_realloc(DynBuf *s, size_t new_size);
  1400. int dbuf_write(DynBuf *s, size_t offset, const void *data, size_t len);
  1401. int dbuf_put(DynBuf *s, const void *data, size_t len);
  1402. int dbuf_put_self(DynBuf *s, size_t offset, size_t len);
  1403. int dbuf_putc(DynBuf *s, uint8_t c);
  1404. int dbuf_putstr(DynBuf *s, const char *str);
  1405. static inline int dbuf_put_u16(DynBuf *s, uint16_t val)
  1406. {
  1407. return dbuf_put(s, (uint8_t *)&val, 2);
  1408. }
  1409. static inline int dbuf_put_u32(DynBuf *s, uint32_t val)
  1410. {
  1411. return dbuf_put(s, (uint8_t *)&val, 4);
  1412. }
  1413. static inline int dbuf_put_u64(DynBuf *s, uint64_t val)
  1414. {
  1415. return dbuf_put(s, (uint8_t *)&val, 8);
  1416. }
  1417. int JS_PRINTF_FORMAT_ATTR(2, 3) dbuf_printf(DynBuf *s, JS_PRINTF_FORMAT const char *fmt, ...);
  1418. void dbuf_free(DynBuf *s);
  1419. static inline bool dbuf_error(DynBuf *s) {
  1420. return s->error;
  1421. }
  1422. static inline void dbuf_set_error(DynBuf *s)
  1423. {
  1424. s->error = true;
  1425. }
  1426. /*---- UTF-8 and UTF-16 handling ----*/
  1427. #define UTF8_CHAR_LEN_MAX 4
  1428. enum {
  1429. UTF8_PLAIN_ASCII = 0, // 7-bit ASCII plain text
  1430. UTF8_NON_ASCII = 1, // has non ASCII code points (8-bit or more)
  1431. UTF8_HAS_16BIT = 2, // has 16-bit code points
  1432. UTF8_HAS_NON_BMP1 = 4, // has non-BMP1 code points, needs UTF-16 surrogate pairs
  1433. UTF8_HAS_ERRORS = 8, // has encoding errors
  1434. };
  1435. int utf8_scan(const char *buf, size_t len, size_t *plen);
  1436. size_t utf8_encode_len(uint32_t c);
  1437. size_t utf8_encode(uint8_t buf[minimum_length(UTF8_CHAR_LEN_MAX)], uint32_t c);
  1438. uint32_t utf8_decode_len(const uint8_t *p, size_t max_len, const uint8_t **pp);
  1439. uint32_t utf8_decode(const uint8_t *p, const uint8_t **pp);
  1440. size_t utf8_decode_buf8(uint8_t *dest, size_t dest_len, const char *src, size_t src_len);
  1441. size_t utf8_decode_buf16(uint16_t *dest, size_t dest_len, const char *src, size_t src_len);
  1442. size_t utf8_encode_buf8(char *dest, size_t dest_len, const uint8_t *src, size_t src_len);
  1443. size_t utf8_encode_buf16(char *dest, size_t dest_len, const uint16_t *src, size_t src_len);
  1444. static inline bool is_surrogate(uint32_t c)
  1445. {
  1446. return (c >> 11) == (0xD800 >> 11); // 0xD800-0xDFFF
  1447. }
  1448. static inline bool is_hi_surrogate(uint32_t c)
  1449. {
  1450. return (c >> 10) == (0xD800 >> 10); // 0xD800-0xDBFF
  1451. }
  1452. static inline bool is_lo_surrogate(uint32_t c)
  1453. {
  1454. return (c >> 10) == (0xDC00 >> 10); // 0xDC00-0xDFFF
  1455. }
  1456. static inline uint32_t get_hi_surrogate(uint32_t c)
  1457. {
  1458. return (c >> 10) - (0x10000 >> 10) + 0xD800;
  1459. }
  1460. static inline uint32_t get_lo_surrogate(uint32_t c)
  1461. {
  1462. return (c & 0x3FF) | 0xDC00;
  1463. }
  1464. static inline uint32_t from_surrogate(uint32_t hi, uint32_t lo)
  1465. {
  1466. return 65536 + 1024 * (hi & 1023) + (lo & 1023);
  1467. }
  1468. static inline int from_hex(int c)
  1469. {
  1470. if (c >= '0' && c <= '9')
  1471. return c - '0';
  1472. else if (c >= 'A' && c <= 'F')
  1473. return c - 'A' + 10;
  1474. else if (c >= 'a' && c <= 'f')
  1475. return c - 'a' + 10;
  1476. else
  1477. return -1;
  1478. }
  1479. static inline uint8_t is_upper_ascii(uint8_t c) {
  1480. return c >= 'A' && c <= 'Z';
  1481. }
  1482. static inline uint8_t to_upper_ascii(uint8_t c) {
  1483. return c >= 'a' && c <= 'z' ? c - 'a' + 'A' : c;
  1484. }
  1485. extern char const digits36[36];
  1486. size_t u32toa(char buf[minimum_length(11)], uint32_t n);
  1487. size_t i32toa(char buf[minimum_length(12)], int32_t n);
  1488. size_t u64toa(char buf[minimum_length(21)], uint64_t n);
  1489. size_t i64toa(char buf[minimum_length(22)], int64_t n);
  1490. size_t u32toa_radix(char buf[minimum_length(33)], uint32_t n, unsigned int base);
  1491. size_t i32toa_radix(char buf[minimum_length(34)], int32_t n, unsigned base);
  1492. size_t u64toa_radix(char buf[minimum_length(65)], uint64_t n, unsigned int base);
  1493. size_t i64toa_radix(char buf[minimum_length(66)], int64_t n, unsigned int base);
  1494. void rqsort(void *base, size_t nmemb, size_t size,
  1495. int (*cmp)(const void *, const void *, void *),
  1496. void *arg);
  1497. int64_t js__gettimeofday_us(void);
  1498. uint64_t js__hrtime_ns(void);
  1499. static inline size_t js__malloc_usable_size(const void *ptr)
  1500. {
  1501. #if defined(__APPLE__)
  1502. return malloc_size(ptr);
  1503. #elif defined(_WIN32)
  1504. return _msize((void *)ptr);
  1505. #elif defined(__linux__) || defined(__ANDROID__) || defined(__CYGWIN__) || defined(__FreeBSD__)
  1506. return malloc_usable_size((void *)ptr);
  1507. #else
  1508. return 0;
  1509. #endif
  1510. }
  1511. /* Cross-platform threading APIs. */
  1512. #if !defined(EMSCRIPTEN) && !defined(__wasi__)
  1513. #if defined(_WIN32)
  1514. #define JS_ONCE_INIT INIT_ONCE_STATIC_INIT
  1515. typedef INIT_ONCE js_once_t;
  1516. typedef CRITICAL_SECTION js_mutex_t;
  1517. typedef CONDITION_VARIABLE js_cond_t;
  1518. #else
  1519. #define JS_ONCE_INIT PTHREAD_ONCE_INIT
  1520. typedef pthread_once_t js_once_t;
  1521. typedef pthread_mutex_t js_mutex_t;
  1522. typedef pthread_cond_t js_cond_t;
  1523. #endif
  1524. void js_once(js_once_t *guard, void (*callback)(void));
  1525. void js_mutex_init(js_mutex_t *mutex);
  1526. void js_mutex_destroy(js_mutex_t *mutex);
  1527. void js_mutex_lock(js_mutex_t *mutex);
  1528. void js_mutex_unlock(js_mutex_t *mutex);
  1529. void js_cond_init(js_cond_t *cond);
  1530. void js_cond_destroy(js_cond_t *cond);
  1531. void js_cond_signal(js_cond_t *cond);
  1532. void js_cond_broadcast(js_cond_t *cond);
  1533. void js_cond_wait(js_cond_t *cond, js_mutex_t *mutex);
  1534. int js_cond_timedwait(js_cond_t *cond, js_mutex_t *mutex, uint64_t timeout);
  1535. #endif /* !defined(EMSCRIPTEN) && !defined(__wasi__) */
  1536. #ifdef __cplusplus
  1537. } /* extern "C" { */
  1538. #endif
  1539. #endif /* CUTILS_H */
  1540. /*
  1541. * Linux klist like system
  1542. *
  1543. * Copyright (c) 2016-2017 Fabrice Bellard
  1544. *
  1545. * Permission is hereby granted, free of charge, to any person obtaining a copy
  1546. * of this software and associated documentation files (the "Software"), to deal
  1547. * in the Software without restriction, including without limitation the rights
  1548. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  1549. * copies of the Software, and to permit persons to whom the Software is
  1550. * furnished to do so, subject to the following conditions:
  1551. *
  1552. * The above copyright notice and this permission notice shall be included in
  1553. * all copies or substantial portions of the Software.
  1554. *
  1555. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  1556. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  1557. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  1558. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  1559. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  1560. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  1561. * THE SOFTWARE.
  1562. */
  1563. #ifndef LIST_H
  1564. #define LIST_H
  1565. #ifndef NULL
  1566. #include <stddef.h>
  1567. #endif
  1568. #ifdef __cplusplus
  1569. extern "C" {
  1570. #endif
  1571. struct list_head {
  1572. struct list_head *prev;
  1573. struct list_head *next;
  1574. };
  1575. #define LIST_HEAD_INIT(el) { &(el), &(el) }
  1576. /* return the pointer of type 'type *' containing 'el' as field 'member' */
  1577. #define list_entry(el, type, member) container_of(el, type, member)
  1578. static inline void init_list_head(struct list_head *head)
  1579. {
  1580. head->prev = head;
  1581. head->next = head;
  1582. }
  1583. /* insert 'el' between 'prev' and 'next' */
  1584. static inline void __list_add(struct list_head *el,
  1585. struct list_head *prev, struct list_head *next)
  1586. {
  1587. prev->next = el;
  1588. el->prev = prev;
  1589. el->next = next;
  1590. next->prev = el;
  1591. }
  1592. /* add 'el' at the head of the list 'head' (= after element head) */
  1593. static inline void list_add(struct list_head *el, struct list_head *head)
  1594. {
  1595. __list_add(el, head, head->next);
  1596. }
  1597. /* add 'el' at the end of the list 'head' (= before element head) */
  1598. static inline void list_add_tail(struct list_head *el, struct list_head *head)
  1599. {
  1600. __list_add(el, head->prev, head);
  1601. }
  1602. static inline void list_del(struct list_head *el)
  1603. {
  1604. struct list_head *prev, *next;
  1605. prev = el->prev;
  1606. next = el->next;
  1607. prev->next = next;
  1608. next->prev = prev;
  1609. el->prev = NULL; /* fail safe */
  1610. el->next = NULL; /* fail safe */
  1611. }
  1612. static inline int list_empty(struct list_head *el)
  1613. {
  1614. return el->next == el;
  1615. }
  1616. #define list_for_each(el, head) \
  1617. for(el = (head)->next; el != (head); el = el->next)
  1618. #define list_for_each_safe(el, el1, head) \
  1619. for(el = (head)->next, el1 = el->next; el != (head); \
  1620. el = el1, el1 = el->next)
  1621. #define list_for_each_prev(el, head) \
  1622. for(el = (head)->prev; el != (head); el = el->prev)
  1623. #define list_for_each_prev_safe(el, el1, head) \
  1624. for(el = (head)->prev, el1 = el->prev; el != (head); \
  1625. el = el1, el1 = el->prev)
  1626. #ifdef __cplusplus
  1627. } /* extern "C" { */
  1628. #endif
  1629. #endif /* LIST_H */
  1630. /*
  1631. * Tiny arbitrary precision floating point library
  1632. *
  1633. * Copyright (c) 2017-2021 Fabrice Bellard
  1634. *
  1635. * Permission is hereby granted, free of charge, to any person obtaining a copy
  1636. * of this software and associated documentation files (the "Software"), to deal
  1637. * in the Software without restriction, including without limitation the rights
  1638. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  1639. * copies of the Software, and to permit persons to whom the Software is
  1640. * furnished to do so, subject to the following conditions:
  1641. *
  1642. * The above copyright notice and this permission notice shall be included in
  1643. * all copies or substantial portions of the Software.
  1644. *
  1645. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  1646. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  1647. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  1648. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  1649. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  1650. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  1651. * THE SOFTWARE.
  1652. */
  1653. #ifndef LIBBF_H
  1654. #define LIBBF_H
  1655. #include <stddef.h>
  1656. #include <stdint.h>
  1657. #ifdef __cplusplus
  1658. extern "C" {
  1659. #endif
  1660. #if INTPTR_MAX >= INT64_MAX && !defined(_WIN32) && !defined(__TINYC__)
  1661. #define LIMB_LOG2_BITS 6
  1662. #else
  1663. #define LIMB_LOG2_BITS 5
  1664. #endif
  1665. #define LIMB_BITS (1 << LIMB_LOG2_BITS)
  1666. #if LIMB_BITS == 64
  1667. #ifndef INT128_MAX
  1668. __extension__ typedef __int128 int128_t;
  1669. __extension__ typedef unsigned __int128 uint128_t;
  1670. #endif
  1671. typedef int64_t slimb_t;
  1672. typedef uint64_t limb_t;
  1673. typedef uint128_t dlimb_t;
  1674. #define BF_RAW_EXP_MIN INT64_MIN
  1675. #define BF_RAW_EXP_MAX INT64_MAX
  1676. #define LIMB_DIGITS 19
  1677. #define BF_DEC_BASE UINT64_C(10000000000000000000)
  1678. #else
  1679. typedef int32_t slimb_t;
  1680. typedef uint32_t limb_t;
  1681. typedef uint64_t dlimb_t;
  1682. #define BF_RAW_EXP_MIN INT32_MIN
  1683. #define BF_RAW_EXP_MAX INT32_MAX
  1684. #define LIMB_DIGITS 9
  1685. #define BF_DEC_BASE 1000000000U
  1686. #endif
  1687. /* in bits */
  1688. /* minimum number of bits for the exponent */
  1689. #define BF_EXP_BITS_MIN 3
  1690. /* maximum number of bits for the exponent */
  1691. #define BF_EXP_BITS_MAX (LIMB_BITS - 3)
  1692. /* extended range for exponent, used internally */
  1693. #define BF_EXT_EXP_BITS_MAX (BF_EXP_BITS_MAX + 1)
  1694. /* minimum possible precision */
  1695. #define BF_PREC_MIN 2
  1696. /* minimum possible precision */
  1697. #define BF_PREC_MAX (((limb_t)1 << (LIMB_BITS - 2)) - 2)
  1698. /* some operations support infinite precision */
  1699. #define BF_PREC_INF (BF_PREC_MAX + 1) /* infinite precision */
  1700. #if LIMB_BITS == 64
  1701. #define BF_CHKSUM_MOD (UINT64_C(975620677) * UINT64_C(9795002197))
  1702. #else
  1703. #define BF_CHKSUM_MOD 975620677U
  1704. #endif
  1705. #define BF_EXP_ZERO BF_RAW_EXP_MIN
  1706. #define BF_EXP_INF (BF_RAW_EXP_MAX - 1)
  1707. #define BF_EXP_NAN BF_RAW_EXP_MAX
  1708. /* +/-zero is represented with expn = BF_EXP_ZERO and len = 0,
  1709. +/-infinity is represented with expn = BF_EXP_INF and len = 0,
  1710. NaN is represented with expn = BF_EXP_NAN and len = 0 (sign is ignored)
  1711. */
  1712. typedef struct {
  1713. struct bf_context_t *ctx;
  1714. int sign;
  1715. slimb_t expn;
  1716. limb_t len;
  1717. limb_t *tab;
  1718. } bf_t;
  1719. typedef struct {
  1720. /* must be kept identical to bf_t */
  1721. struct bf_context_t *ctx;
  1722. int sign;
  1723. slimb_t expn;
  1724. limb_t len;
  1725. limb_t *tab;
  1726. } bfdec_t;
  1727. typedef enum {
  1728. BF_RNDN, /* round to nearest, ties to even */
  1729. BF_RNDZ, /* round to zero */
  1730. BF_RNDD, /* round to -inf (the code relies on (BF_RNDD xor BF_RNDU) = 1) */
  1731. BF_RNDU, /* round to +inf */
  1732. BF_RNDNA, /* round to nearest, ties away from zero */
  1733. BF_RNDA, /* round away from zero */
  1734. BF_RNDF, /* faithful rounding (nondeterministic, either RNDD or RNDU,
  1735. inexact flag is always set) */
  1736. } bf_rnd_t;
  1737. /* allow subnormal numbers. Only available if the number of exponent
  1738. bits is <= BF_EXP_BITS_USER_MAX and prec != BF_PREC_INF. */
  1739. #define BF_FLAG_SUBNORMAL (1 << 3)
  1740. /* 'prec' is the precision after the radix point instead of the whole
  1741. mantissa. Can only be used with bf_round() and
  1742. bfdec_[add|sub|mul|div|sqrt|round](). */
  1743. #define BF_FLAG_RADPNT_PREC (1 << 4)
  1744. #define BF_RND_MASK 0x7
  1745. #define BF_EXP_BITS_SHIFT 5
  1746. #define BF_EXP_BITS_MASK 0x3f
  1747. /* shortcut for bf_set_exp_bits(BF_EXT_EXP_BITS_MAX) */
  1748. #define BF_FLAG_EXT_EXP (BF_EXP_BITS_MASK << BF_EXP_BITS_SHIFT)
  1749. /* contains the rounding mode and number of exponents bits */
  1750. typedef uint32_t bf_flags_t;
  1751. typedef void *bf_realloc_func_t(void *opaque, void *ptr, size_t size);
  1752. typedef struct {
  1753. bf_t val;
  1754. limb_t prec;
  1755. } BFConstCache;
  1756. typedef struct bf_context_t {
  1757. void *realloc_opaque;
  1758. bf_realloc_func_t *realloc_func;
  1759. BFConstCache log2_cache;
  1760. BFConstCache pi_cache;
  1761. struct BFNTTState *ntt_state;
  1762. } bf_context_t;
  1763. static inline int bf_get_exp_bits(bf_flags_t flags)
  1764. {
  1765. int e;
  1766. e = (flags >> BF_EXP_BITS_SHIFT) & BF_EXP_BITS_MASK;
  1767. if (e == BF_EXP_BITS_MASK)
  1768. return BF_EXP_BITS_MAX + 1;
  1769. else
  1770. return BF_EXP_BITS_MAX - e;
  1771. }
  1772. static inline bf_flags_t bf_set_exp_bits(int n)
  1773. {
  1774. return ((BF_EXP_BITS_MAX - n) & BF_EXP_BITS_MASK) << BF_EXP_BITS_SHIFT;
  1775. }
  1776. /* returned status */
  1777. #define BF_ST_INVALID_OP (1 << 0)
  1778. #define BF_ST_DIVIDE_ZERO (1 << 1)
  1779. #define BF_ST_OVERFLOW (1 << 2)
  1780. #define BF_ST_UNDERFLOW (1 << 3)
  1781. #define BF_ST_INEXACT (1 << 4)
  1782. /* indicate that a memory allocation error occured. NaN is returned */
  1783. #define BF_ST_MEM_ERROR (1 << 5)
  1784. #define BF_RADIX_MAX 36 /* maximum radix for bf_atof() and bf_ftoa() */
  1785. static inline slimb_t bf_max(slimb_t a, slimb_t b)
  1786. {
  1787. if (a > b)
  1788. return a;
  1789. else
  1790. return b;
  1791. }
  1792. static inline slimb_t bf_min(slimb_t a, slimb_t b)
  1793. {
  1794. if (a < b)
  1795. return a;
  1796. else
  1797. return b;
  1798. }
  1799. void bf_context_init(bf_context_t *s, bf_realloc_func_t *realloc_func,
  1800. void *realloc_opaque);
  1801. void bf_context_end(bf_context_t *s);
  1802. /* free memory allocated for the bf cache data */
  1803. void bf_clear_cache(bf_context_t *s);
  1804. static inline void *bf_realloc(bf_context_t *s, void *ptr, size_t size)
  1805. {
  1806. return s->realloc_func(s->realloc_opaque, ptr, size);
  1807. }
  1808. /* 'size' must be != 0 */
  1809. static inline void *bf_malloc(bf_context_t *s, size_t size)
  1810. {
  1811. return bf_realloc(s, NULL, size);
  1812. }
  1813. static inline void bf_free(bf_context_t *s, void *ptr)
  1814. {
  1815. /* must test ptr otherwise equivalent to malloc(0) */
  1816. if (ptr)
  1817. bf_realloc(s, ptr, 0);
  1818. }
  1819. void bf_init(bf_context_t *s, bf_t *r);
  1820. static inline void bf_delete(bf_t *r)
  1821. {
  1822. bf_context_t *s = r->ctx;
  1823. /* we accept to delete a zeroed bf_t structure */
  1824. if (s && r->tab) {
  1825. bf_realloc(s, r->tab, 0);
  1826. }
  1827. }
  1828. static inline void bf_neg(bf_t *r)
  1829. {
  1830. r->sign ^= 1;
  1831. }
  1832. static inline int bf_is_finite(const bf_t *a)
  1833. {
  1834. return (a->expn < BF_EXP_INF);
  1835. }
  1836. static inline int bf_is_nan(const bf_t *a)
  1837. {
  1838. return (a->expn == BF_EXP_NAN);
  1839. }
  1840. static inline int bf_is_zero(const bf_t *a)
  1841. {
  1842. return (a->expn == BF_EXP_ZERO);
  1843. }
  1844. static inline void bf_memcpy(bf_t *r, const bf_t *a)
  1845. {
  1846. *r = *a;
  1847. }
  1848. int bf_set_ui(bf_t *r, uint64_t a);
  1849. int bf_set_si(bf_t *r, int64_t a);
  1850. void bf_set_nan(bf_t *r);
  1851. void bf_set_zero(bf_t *r, int is_neg);
  1852. void bf_set_inf(bf_t *r, int is_neg);
  1853. int bf_set(bf_t *r, const bf_t *a);
  1854. void bf_move(bf_t *r, bf_t *a);
  1855. int bf_get_float64(const bf_t *a, double *pres, bf_rnd_t rnd_mode);
  1856. int bf_set_float64(bf_t *a, double d);
  1857. int bf_cmpu(const bf_t *a, const bf_t *b);
  1858. int bf_cmp_full(const bf_t *a, const bf_t *b);
  1859. int bf_cmp(const bf_t *a, const bf_t *b);
  1860. static inline int bf_cmp_eq(const bf_t *a, const bf_t *b)
  1861. {
  1862. return bf_cmp(a, b) == 0;
  1863. }
  1864. static inline int bf_cmp_le(const bf_t *a, const bf_t *b)
  1865. {
  1866. return bf_cmp(a, b) <= 0;
  1867. }
  1868. static inline int bf_cmp_lt(const bf_t *a, const bf_t *b)
  1869. {
  1870. return bf_cmp(a, b) < 0;
  1871. }
  1872. int bf_add(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags);
  1873. int bf_sub(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags);
  1874. int bf_add_si(bf_t *r, const bf_t *a, int64_t b1, limb_t prec, bf_flags_t flags);
  1875. int bf_mul(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags);
  1876. int bf_mul_ui(bf_t *r, const bf_t *a, uint64_t b1, limb_t prec, bf_flags_t flags);
  1877. int bf_mul_si(bf_t *r, const bf_t *a, int64_t b1, limb_t prec,
  1878. bf_flags_t flags);
  1879. int bf_mul_2exp(bf_t *r, slimb_t e, limb_t prec, bf_flags_t flags);
  1880. int bf_div(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags);
  1881. #define BF_DIVREM_EUCLIDIAN BF_RNDF
  1882. int bf_divrem(bf_t *q, bf_t *r, const bf_t *a, const bf_t *b,
  1883. limb_t prec, bf_flags_t flags, int rnd_mode);
  1884. int bf_rem(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,
  1885. bf_flags_t flags, int rnd_mode);
  1886. int bf_remquo(slimb_t *pq, bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,
  1887. bf_flags_t flags, int rnd_mode);
  1888. /* round to integer with infinite precision */
  1889. int bf_rint(bf_t *r, int rnd_mode);
  1890. int bf_round(bf_t *r, limb_t prec, bf_flags_t flags);
  1891. int bf_sqrtrem(bf_t *r, bf_t *rem1, const bf_t *a);
  1892. int bf_sqrt(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags);
  1893. slimb_t bf_get_exp_min(const bf_t *a);
  1894. int bf_logic_or(bf_t *r, const bf_t *a, const bf_t *b);
  1895. int bf_logic_xor(bf_t *r, const bf_t *a, const bf_t *b);
  1896. int bf_logic_and(bf_t *r, const bf_t *a, const bf_t *b);
  1897. /* additional flags for bf_atof */
  1898. /* do not accept hex radix prefix (0x or 0X) if radix = 0 or radix = 16 */
  1899. #define BF_ATOF_NO_HEX (1 << 16)
  1900. /* accept binary (0b or 0B) or octal (0o or 0O) radix prefix if radix = 0 */
  1901. #define BF_ATOF_BIN_OCT (1 << 17)
  1902. /* Do not parse NaN or Inf */
  1903. #define BF_ATOF_NO_NAN_INF (1 << 18)
  1904. /* return the exponent separately */
  1905. #define BF_ATOF_EXPONENT (1 << 19)
  1906. int bf_atof(bf_t *a, const char *str, const char **pnext, int radix,
  1907. limb_t prec, bf_flags_t flags);
  1908. /* this version accepts prec = BF_PREC_INF and returns the radix
  1909. exponent */
  1910. int bf_atof2(bf_t *r, slimb_t *pexponent,
  1911. const char *str, const char **pnext, int radix,
  1912. limb_t prec, bf_flags_t flags);
  1913. int bf_mul_pow_radix(bf_t *r, const bf_t *T, limb_t radix,
  1914. slimb_t expn, limb_t prec, bf_flags_t flags);
  1915. /* Conversion of floating point number to string. Return a null
  1916. terminated string or NULL if memory error. *plen contains its
  1917. length if plen != NULL. The exponent letter is "e" for base 10,
  1918. "p" for bases 2, 8, 16 with a binary exponent and "@" for the other
  1919. bases. */
  1920. #define BF_FTOA_FORMAT_MASK (3 << 16)
  1921. /* fixed format: prec significant digits rounded with (flags &
  1922. BF_RND_MASK). Exponential notation is used if too many zeros are
  1923. needed.*/
  1924. #define BF_FTOA_FORMAT_FIXED (0 << 16)
  1925. /* fractional format: prec digits after the decimal point rounded with
  1926. (flags & BF_RND_MASK) */
  1927. #define BF_FTOA_FORMAT_FRAC (1 << 16)
  1928. /* free format:
  1929. For binary radices with bf_ftoa() and for bfdec_ftoa(): use the minimum
  1930. number of digits to represent 'a'. The precision and the rounding
  1931. mode are ignored.
  1932. For the non binary radices with bf_ftoa(): use as many digits as
  1933. necessary so that bf_atof() return the same number when using
  1934. precision 'prec', rounding to nearest and the subnormal
  1935. configuration of 'flags'. The result is meaningful only if 'a' is
  1936. already rounded to 'prec' bits. If the subnormal flag is set, the
  1937. exponent in 'flags' must also be set to the desired exponent range.
  1938. */
  1939. #define BF_FTOA_FORMAT_FREE (2 << 16)
  1940. /* same as BF_FTOA_FORMAT_FREE but uses the minimum number of digits
  1941. (takes more computation time). Identical to BF_FTOA_FORMAT_FREE for
  1942. binary radices with bf_ftoa() and for bfdec_ftoa(). */
  1943. #define BF_FTOA_FORMAT_FREE_MIN (3 << 16)
  1944. /* force exponential notation for fixed or free format */
  1945. #define BF_FTOA_FORCE_EXP (1 << 20)
  1946. /* add 0x prefix for base 16, 0o prefix for base 8 or 0b prefix for
  1947. base 2 if non zero value */
  1948. #define BF_FTOA_ADD_PREFIX (1 << 21)
  1949. /* return "Infinity" instead of "Inf" and add a "+" for positive
  1950. exponents */
  1951. #define BF_FTOA_JS_QUIRKS (1 << 22)
  1952. char *bf_ftoa(size_t *plen, const bf_t *a, int radix, limb_t prec,
  1953. bf_flags_t flags);
  1954. /* modulo 2^n instead of saturation. NaN and infinity return 0 */
  1955. #define BF_GET_INT_MOD (1 << 0)
  1956. int bf_get_int32(int *pres, const bf_t *a, int flags);
  1957. int bf_get_int64(int64_t *pres, const bf_t *a, int flags);
  1958. int bf_get_uint64(uint64_t *pres, const bf_t *a);
  1959. /* the following functions are exported for testing only. */
  1960. void mp_print_str(const char *str, const limb_t *tab, limb_t n);
  1961. void bf_print_str(const char *str, const bf_t *a);
  1962. int bf_resize(bf_t *r, limb_t len);
  1963. int bf_get_fft_size(int *pdpl, int *pnb_mods, limb_t len);
  1964. int bf_normalize_and_round(bf_t *r, limb_t prec1, bf_flags_t flags);
  1965. int bf_can_round(const bf_t *a, slimb_t prec, bf_rnd_t rnd_mode, slimb_t k);
  1966. slimb_t bf_mul_log2_radix(slimb_t a1, unsigned int radix, int is_inv,
  1967. int is_ceil1);
  1968. int mp_mul(bf_context_t *s, limb_t *result,
  1969. const limb_t *op1, limb_t op1_size,
  1970. const limb_t *op2, limb_t op2_size);
  1971. limb_t mp_add(limb_t *res, const limb_t *op1, const limb_t *op2,
  1972. limb_t n, limb_t carry);
  1973. limb_t mp_add_ui(limb_t *tab, limb_t b, size_t n);
  1974. int mp_sqrtrem(bf_context_t *s, limb_t *tabs, limb_t *taba, limb_t n);
  1975. int mp_recip(bf_context_t *s, limb_t *tabr, const limb_t *taba, limb_t n);
  1976. limb_t bf_isqrt(limb_t a);
  1977. /* transcendental functions */
  1978. int bf_const_log2(bf_t *T, limb_t prec, bf_flags_t flags);
  1979. int bf_const_pi(bf_t *T, limb_t prec, bf_flags_t flags);
  1980. int bf_exp(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags);
  1981. int bf_log(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags);
  1982. #define BF_POW_JS_QUIRKS (1 << 16) /* (+/-1)^(+/-Inf) = NaN, 1^NaN = NaN */
  1983. int bf_pow(bf_t *r, const bf_t *x, const bf_t *y, limb_t prec, bf_flags_t flags);
  1984. int bf_cos(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags);
  1985. int bf_sin(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags);
  1986. int bf_tan(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags);
  1987. int bf_atan(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags);
  1988. int bf_atan2(bf_t *r, const bf_t *y, const bf_t *x,
  1989. limb_t prec, bf_flags_t flags);
  1990. int bf_asin(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags);
  1991. int bf_acos(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags);
  1992. /* decimal floating point */
  1993. static inline void bfdec_init(bf_context_t *s, bfdec_t *r)
  1994. {
  1995. bf_init(s, (bf_t *)r);
  1996. }
  1997. static inline void bfdec_delete(bfdec_t *r)
  1998. {
  1999. bf_delete((bf_t *)r);
  2000. }
  2001. static inline void bfdec_neg(bfdec_t *r)
  2002. {
  2003. r->sign ^= 1;
  2004. }
  2005. static inline int bfdec_is_finite(const bfdec_t *a)
  2006. {
  2007. return (a->expn < BF_EXP_INF);
  2008. }
  2009. static inline int bfdec_is_nan(const bfdec_t *a)
  2010. {
  2011. return (a->expn == BF_EXP_NAN);
  2012. }
  2013. static inline int bfdec_is_zero(const bfdec_t *a)
  2014. {
  2015. return (a->expn == BF_EXP_ZERO);
  2016. }
  2017. static inline void bfdec_memcpy(bfdec_t *r, const bfdec_t *a)
  2018. {
  2019. bf_memcpy((bf_t *)r, (const bf_t *)a);
  2020. }
  2021. int bfdec_set_ui(bfdec_t *r, uint64_t a);
  2022. int bfdec_set_si(bfdec_t *r, int64_t a);
  2023. static inline void bfdec_set_nan(bfdec_t *r)
  2024. {
  2025. bf_set_nan((bf_t *)r);
  2026. }
  2027. static inline void bfdec_set_zero(bfdec_t *r, int is_neg)
  2028. {
  2029. bf_set_zero((bf_t *)r, is_neg);
  2030. }
  2031. static inline void bfdec_set_inf(bfdec_t *r, int is_neg)
  2032. {
  2033. bf_set_inf((bf_t *)r, is_neg);
  2034. }
  2035. static inline int bfdec_set(bfdec_t *r, const bfdec_t *a)
  2036. {
  2037. return bf_set((bf_t *)r, (bf_t *)a);
  2038. }
  2039. static inline void bfdec_move(bfdec_t *r, bfdec_t *a)
  2040. {
  2041. bf_move((bf_t *)r, (bf_t *)a);
  2042. }
  2043. static inline int bfdec_cmpu(const bfdec_t *a, const bfdec_t *b)
  2044. {
  2045. return bf_cmpu((const bf_t *)a, (const bf_t *)b);
  2046. }
  2047. static inline int bfdec_cmp_full(const bfdec_t *a, const bfdec_t *b)
  2048. {
  2049. return bf_cmp_full((const bf_t *)a, (const bf_t *)b);
  2050. }
  2051. static inline int bfdec_cmp(const bfdec_t *a, const bfdec_t *b)
  2052. {
  2053. return bf_cmp((const bf_t *)a, (const bf_t *)b);
  2054. }
  2055. static inline int bfdec_cmp_eq(const bfdec_t *a, const bfdec_t *b)
  2056. {
  2057. return bfdec_cmp(a, b) == 0;
  2058. }
  2059. static inline int bfdec_cmp_le(const bfdec_t *a, const bfdec_t *b)
  2060. {
  2061. return bfdec_cmp(a, b) <= 0;
  2062. }
  2063. static inline int bfdec_cmp_lt(const bfdec_t *a, const bfdec_t *b)
  2064. {
  2065. return bfdec_cmp(a, b) < 0;
  2066. }
  2067. int bfdec_add(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,
  2068. bf_flags_t flags);
  2069. int bfdec_sub(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,
  2070. bf_flags_t flags);
  2071. int bfdec_add_si(bfdec_t *r, const bfdec_t *a, int64_t b1, limb_t prec,
  2072. bf_flags_t flags);
  2073. int bfdec_mul(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,
  2074. bf_flags_t flags);
  2075. int bfdec_mul_si(bfdec_t *r, const bfdec_t *a, int64_t b1, limb_t prec,
  2076. bf_flags_t flags);
  2077. int bfdec_div(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,
  2078. bf_flags_t flags);
  2079. int bfdec_divrem(bfdec_t *q, bfdec_t *r, const bfdec_t *a, const bfdec_t *b,
  2080. limb_t prec, bf_flags_t flags, int rnd_mode);
  2081. int bfdec_rem(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,
  2082. bf_flags_t flags, int rnd_mode);
  2083. int bfdec_rint(bfdec_t *r, int rnd_mode);
  2084. int bfdec_sqrt(bfdec_t *r, const bfdec_t *a, limb_t prec, bf_flags_t flags);
  2085. int bfdec_round(bfdec_t *r, limb_t prec, bf_flags_t flags);
  2086. int bfdec_get_int32(int *pres, const bfdec_t *a);
  2087. int bfdec_pow_ui(bfdec_t *r, const bfdec_t *a, limb_t b);
  2088. char *bfdec_ftoa(size_t *plen, const bfdec_t *a, limb_t prec, bf_flags_t flags);
  2089. int bfdec_atof(bfdec_t *r, const char *str, const char **pnext,
  2090. limb_t prec, bf_flags_t flags);
  2091. /* the following functions are exported for testing only. */
  2092. extern const limb_t mp_pow_dec[LIMB_DIGITS + 1];
  2093. void bfdec_print_str(const char *str, const bfdec_t *a);
  2094. static inline int bfdec_resize(bfdec_t *r, limb_t len)
  2095. {
  2096. return bf_resize((bf_t *)r, len);
  2097. }
  2098. int bfdec_normalize_and_round(bfdec_t *r, limb_t prec1, bf_flags_t flags);
  2099. #ifdef __cplusplus
  2100. } /* extern "C" { */
  2101. #endif
  2102. #endif /* LIBBF_H */
  2103. /*
  2104. * Unicode utilities
  2105. *
  2106. * Copyright (c) 2017-2018 Fabrice Bellard
  2107. *
  2108. * Permission is hereby granted, free of charge, to any person obtaining a copy
  2109. * of this software and associated documentation files (the "Software"), to deal
  2110. * in the Software without restriction, including without limitation the rights
  2111. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  2112. * copies of the Software, and to permit persons to whom the Software is
  2113. * furnished to do so, subject to the following conditions:
  2114. *
  2115. * The above copyright notice and this permission notice shall be included in
  2116. * all copies or substantial portions of the Software.
  2117. *
  2118. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  2119. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  2120. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  2121. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  2122. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  2123. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  2124. * THE SOFTWARE.
  2125. */
  2126. #ifndef LIBUNICODE_H
  2127. #define LIBUNICODE_H
  2128. #include <stdbool.h>
  2129. #include <stddef.h>
  2130. #include <inttypes.h>
  2131. #ifdef __cplusplus
  2132. extern "C" {
  2133. #endif
  2134. #define LRE_CC_RES_LEN_MAX 3
  2135. typedef enum {
  2136. UNICODE_NFC,
  2137. UNICODE_NFD,
  2138. UNICODE_NFKC,
  2139. UNICODE_NFKD,
  2140. } UnicodeNormalizationEnum;
  2141. int lre_case_conv(uint32_t *res, uint32_t c, int conv_type);
  2142. int lre_canonicalize(uint32_t c, bool is_unicode);
  2143. bool lre_is_cased(uint32_t c);
  2144. bool lre_is_case_ignorable(uint32_t c);
  2145. /* char ranges */
  2146. typedef struct {
  2147. int len; /* in points, always even */
  2148. int size;
  2149. uint32_t *points; /* points sorted by increasing value */
  2150. void *mem_opaque;
  2151. void *(*realloc_func)(void *opaque, void *ptr, size_t size);
  2152. } CharRange;
  2153. typedef enum {
  2154. CR_OP_UNION,
  2155. CR_OP_INTER,
  2156. CR_OP_XOR,
  2157. } CharRangeOpEnum;
  2158. void cr_init(CharRange *cr, void *mem_opaque, void *(*realloc_func)(void *opaque, void *ptr, size_t size));
  2159. void cr_free(CharRange *cr);
  2160. int cr_realloc(CharRange *cr, int size);
  2161. int cr_copy(CharRange *cr, const CharRange *cr1);
  2162. static inline int cr_add_point(CharRange *cr, uint32_t v)
  2163. {
  2164. if (cr->len >= cr->size) {
  2165. if (cr_realloc(cr, cr->len + 1))
  2166. return -1;
  2167. }
  2168. cr->points[cr->len++] = v;
  2169. return 0;
  2170. }
  2171. static inline int cr_add_interval(CharRange *cr, uint32_t c1, uint32_t c2)
  2172. {
  2173. if ((cr->len + 2) > cr->size) {
  2174. if (cr_realloc(cr, cr->len + 2))
  2175. return -1;
  2176. }
  2177. cr->points[cr->len++] = c1;
  2178. cr->points[cr->len++] = c2;
  2179. return 0;
  2180. }
  2181. int cr_union1(CharRange *cr, const uint32_t *b_pt, int b_len);
  2182. static inline int cr_union_interval(CharRange *cr, uint32_t c1, uint32_t c2)
  2183. {
  2184. uint32_t b_pt[2];
  2185. b_pt[0] = c1;
  2186. b_pt[1] = c2 + 1;
  2187. return cr_union1(cr, b_pt, 2);
  2188. }
  2189. int cr_op(CharRange *cr, const uint32_t *a_pt, int a_len,
  2190. const uint32_t *b_pt, int b_len, int op);
  2191. int cr_invert(CharRange *cr);
  2192. int cr_regexp_canonicalize(CharRange *cr, bool is_unicode);
  2193. bool lre_is_id_start(uint32_t c);
  2194. bool lre_is_id_continue(uint32_t c);
  2195. bool lre_is_white_space(uint32_t c);
  2196. int unicode_normalize(uint32_t **pdst, const uint32_t *src, int src_len,
  2197. UnicodeNormalizationEnum n_type,
  2198. void *opaque, void *(*realloc_func)(void *opaque, void *ptr, size_t size));
  2199. /* Unicode character range functions */
  2200. int unicode_script(CharRange *cr,
  2201. const char *script_name, bool is_ext);
  2202. int unicode_general_category(CharRange *cr, const char *gc_name);
  2203. int unicode_prop(CharRange *cr, const char *prop_name);
  2204. #ifdef __cplusplus
  2205. } /* extern "C" { */
  2206. #endif
  2207. #endif /* LIBUNICODE_H */
  2208. /*
  2209. * Regular Expression Engine
  2210. *
  2211. * Copyright (c) 2017-2018 Fabrice Bellard
  2212. *
  2213. * Permission is hereby granted, free of charge, to any person obtaining a copy
  2214. * of this software and associated documentation files (the "Software"), to deal
  2215. * in the Software without restriction, including without limitation the rights
  2216. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  2217. * copies of the Software, and to permit persons to whom the Software is
  2218. * furnished to do so, subject to the following conditions:
  2219. *
  2220. * The above copyright notice and this permission notice shall be included in
  2221. * all copies or substantial portions of the Software.
  2222. *
  2223. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  2224. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  2225. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  2226. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  2227. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  2228. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  2229. * THE SOFTWARE.
  2230. */
  2231. #ifndef LIBREGEXP_H
  2232. #define LIBREGEXP_H
  2233. #include <stdbool.h>
  2234. #include <stddef.h>
  2235. #ifdef __cplusplus
  2236. extern "C" {
  2237. #endif
  2238. #define LRE_FLAG_GLOBAL (1 << 0)
  2239. #define LRE_FLAG_IGNORECASE (1 << 1)
  2240. #define LRE_FLAG_MULTILINE (1 << 2)
  2241. #define LRE_FLAG_DOTALL (1 << 3)
  2242. #define LRE_FLAG_UNICODE (1 << 4)
  2243. #define LRE_FLAG_STICKY (1 << 5)
  2244. #define LRE_FLAG_INDICES (1 << 6) /* Unused by libregexp, just recorded. */
  2245. #define LRE_FLAG_NAMED_GROUPS (1 << 7) /* named groups are present in the regexp */
  2246. #define LRE_FLAG_UNICODE_SETS (1 << 8)
  2247. uint8_t *lre_compile(int *plen, char *error_msg, int error_msg_size,
  2248. const char *buf, size_t buf_len, int re_flags,
  2249. void *opaque);
  2250. int lre_get_capture_count(const uint8_t *bc_buf);
  2251. int lre_get_flags(const uint8_t *bc_buf);
  2252. const char *lre_get_groupnames(const uint8_t *bc_buf);
  2253. int lre_exec(uint8_t **capture,
  2254. const uint8_t *bc_buf, const uint8_t *cbuf, int cindex, int clen,
  2255. int cbuf_type, void *opaque);
  2256. int lre_parse_escape(const uint8_t **pp, int allow_utf16);
  2257. bool lre_is_space(int c);
  2258. void lre_byte_swap(uint8_t *buf, size_t len, bool is_byte_swapped);
  2259. /* must be provided by the user */
  2260. bool lre_check_stack_overflow(void *opaque, size_t alloca_size);
  2261. void *lre_realloc(void *opaque, void *ptr, size_t size);
  2262. /* JS identifier test */
  2263. extern uint32_t const lre_id_start_table_ascii[4];
  2264. extern uint32_t const lre_id_continue_table_ascii[4];
  2265. static inline int lre_js_is_ident_first(int c)
  2266. {
  2267. if ((uint32_t)c < 128) {
  2268. return (lre_id_start_table_ascii[c >> 5] >> (c & 31)) & 1;
  2269. } else {
  2270. return lre_is_id_start(c);
  2271. }
  2272. }
  2273. static inline int lre_js_is_ident_next(int c)
  2274. {
  2275. if ((uint32_t)c < 128) {
  2276. return (lre_id_continue_table_ascii[c >> 5] >> (c & 31)) & 1;
  2277. } else {
  2278. /* ZWNJ and ZWJ are accepted in identifiers */
  2279. return lre_is_id_continue(c) || c == 0x200C || c == 0x200D;
  2280. }
  2281. }
  2282. #ifdef __cplusplus
  2283. } /* extern "C" { */
  2284. #endif
  2285. #endif /* LIBREGEXP_H */
  2286. /* Compressed unicode tables */
  2287. /* Automatically generated file - do not edit */
  2288. #include <stdint.h>
  2289. static const uint32_t case_conv_table1[378] = {
  2290. 0x00209a30, 0x00309a00, 0x005a8173, 0x00601730,
  2291. 0x006c0730, 0x006f81b3, 0x00701700, 0x007c0700,
  2292. 0x007f8100, 0x00803040, 0x009801c3, 0x00988190,
  2293. 0x00990640, 0x009c9040, 0x00a481b4, 0x00a52e40,
  2294. 0x00bc0130, 0x00bc8640, 0x00bf8170, 0x00c00100,
  2295. 0x00c08130, 0x00c10440, 0x00c30130, 0x00c38240,
  2296. 0x00c48230, 0x00c58240, 0x00c70130, 0x00c78130,
  2297. 0x00c80130, 0x00c88240, 0x00c98130, 0x00ca0130,
  2298. 0x00ca8100, 0x00cb0130, 0x00cb8130, 0x00cc0240,
  2299. 0x00cd0100, 0x00cd8101, 0x00ce0130, 0x00ce8130,
  2300. 0x00cf0100, 0x00cf8130, 0x00d00640, 0x00d30130,
  2301. 0x00d38240, 0x00d48130, 0x00d60240, 0x00d70130,
  2302. 0x00d78240, 0x00d88230, 0x00d98440, 0x00db8130,
  2303. 0x00dc0240, 0x00de0240, 0x00df8100, 0x00e20350,
  2304. 0x00e38350, 0x00e50350, 0x00e69040, 0x00ee8100,
  2305. 0x00ef1240, 0x00f801b4, 0x00f88350, 0x00fa0240,
  2306. 0x00fb0130, 0x00fb8130, 0x00fc2840, 0x01100130,
  2307. 0x01111240, 0x011d0131, 0x011d8240, 0x011e8130,
  2308. 0x011f0131, 0x011f8201, 0x01208240, 0x01218130,
  2309. 0x01220130, 0x01228130, 0x01230a40, 0x01280101,
  2310. 0x01288101, 0x01290101, 0x01298100, 0x012a0100,
  2311. 0x012b0200, 0x012c8100, 0x012d8100, 0x012e0101,
  2312. 0x01300100, 0x01308101, 0x01318100, 0x01320101,
  2313. 0x01328101, 0x01330101, 0x01340100, 0x01348100,
  2314. 0x01350101, 0x01358101, 0x01360101, 0x01378100,
  2315. 0x01388101, 0x01390100, 0x013a8100, 0x013e8101,
  2316. 0x01400100, 0x01410101, 0x01418100, 0x01438101,
  2317. 0x01440100, 0x01448100, 0x01450200, 0x01460100,
  2318. 0x01490100, 0x014e8101, 0x014f0101, 0x01a28173,
  2319. 0x01b80440, 0x01bb0240, 0x01bd8300, 0x01bf8130,
  2320. 0x01c30130, 0x01c40330, 0x01c60130, 0x01c70230,
  2321. 0x01c801d0, 0x01c89130, 0x01d18930, 0x01d60100,
  2322. 0x01d68300, 0x01d801d3, 0x01d89100, 0x01e10173,
  2323. 0x01e18900, 0x01e60100, 0x01e68200, 0x01e78130,
  2324. 0x01e80173, 0x01e88173, 0x01ea8173, 0x01eb0173,
  2325. 0x01eb8100, 0x01ec1840, 0x01f80173, 0x01f88173,
  2326. 0x01f90100, 0x01f98100, 0x01fa01a0, 0x01fa8173,
  2327. 0x01fb8240, 0x01fc8130, 0x01fd0240, 0x01fe8330,
  2328. 0x02001030, 0x02082030, 0x02182000, 0x02281000,
  2329. 0x02302240, 0x02453640, 0x02600130, 0x02608e40,
  2330. 0x02678100, 0x02686040, 0x0298a630, 0x02b0a600,
  2331. 0x02c381b5, 0x08502631, 0x08638131, 0x08668131,
  2332. 0x08682b00, 0x087e8300, 0x09d05011, 0x09f80610,
  2333. 0x09fc0620, 0x0e400174, 0x0e408174, 0x0e410174,
  2334. 0x0e418174, 0x0e420174, 0x0e428174, 0x0e430174,
  2335. 0x0e438180, 0x0e440180, 0x0e448240, 0x0e482b30,
  2336. 0x0e5e8330, 0x0ebc8101, 0x0ebe8101, 0x0ec70101,
  2337. 0x0f007e40, 0x0f3f1840, 0x0f4b01b5, 0x0f4b81b6,
  2338. 0x0f4c01b6, 0x0f4c81b6, 0x0f4d01b7, 0x0f4d8180,
  2339. 0x0f4f0130, 0x0f506040, 0x0f800800, 0x0f840830,
  2340. 0x0f880600, 0x0f8c0630, 0x0f900800, 0x0f940830,
  2341. 0x0f980800, 0x0f9c0830, 0x0fa00600, 0x0fa40630,
  2342. 0x0fa801b0, 0x0fa88100, 0x0fa901d3, 0x0fa98100,
  2343. 0x0faa01d3, 0x0faa8100, 0x0fab01d3, 0x0fab8100,
  2344. 0x0fac8130, 0x0fad8130, 0x0fae8130, 0x0faf8130,
  2345. 0x0fb00800, 0x0fb40830, 0x0fb80200, 0x0fb90400,
  2346. 0x0fbb0201, 0x0fbc0201, 0x0fbd0201, 0x0fbe0201,
  2347. 0x0fc008b7, 0x0fc40867, 0x0fc808b8, 0x0fcc0868,
  2348. 0x0fd008b8, 0x0fd40868, 0x0fd80200, 0x0fd901b9,
  2349. 0x0fd981b1, 0x0fda01b9, 0x0fdb01b1, 0x0fdb81d7,
  2350. 0x0fdc0230, 0x0fdd0230, 0x0fde0161, 0x0fdf0173,
  2351. 0x0fe101b9, 0x0fe181b2, 0x0fe201ba, 0x0fe301b2,
  2352. 0x0fe381d8, 0x0fe40430, 0x0fe60162, 0x0fe80201,
  2353. 0x0fe901d0, 0x0fe981d0, 0x0feb01b0, 0x0feb81d0,
  2354. 0x0fec0230, 0x0fed0230, 0x0ff00201, 0x0ff101d3,
  2355. 0x0ff181d3, 0x0ff201ba, 0x0ff28101, 0x0ff301b0,
  2356. 0x0ff381d3, 0x0ff40231, 0x0ff50230, 0x0ff60131,
  2357. 0x0ff901ba, 0x0ff981b2, 0x0ffa01bb, 0x0ffb01b2,
  2358. 0x0ffb81d9, 0x0ffc0230, 0x0ffd0230, 0x0ffe0162,
  2359. 0x109301a0, 0x109501a0, 0x109581a0, 0x10990131,
  2360. 0x10a70101, 0x10b01031, 0x10b81001, 0x10c18240,
  2361. 0x125b1a31, 0x12681a01, 0x16003031, 0x16183001,
  2362. 0x16300240, 0x16310130, 0x16318130, 0x16320130,
  2363. 0x16328100, 0x16330100, 0x16338640, 0x16368130,
  2364. 0x16370130, 0x16378130, 0x16380130, 0x16390240,
  2365. 0x163a8240, 0x163f0230, 0x16406440, 0x16758440,
  2366. 0x16790240, 0x16802600, 0x16938100, 0x16968100,
  2367. 0x53202e40, 0x53401c40, 0x53910e40, 0x53993e40,
  2368. 0x53bc8440, 0x53be8130, 0x53bf0a40, 0x53c58240,
  2369. 0x53c68130, 0x53c80440, 0x53ca0101, 0x53cb1440,
  2370. 0x53d50130, 0x53d58130, 0x53d60130, 0x53d68130,
  2371. 0x53d70130, 0x53d80130, 0x53d88130, 0x53d90130,
  2372. 0x53d98131, 0x53da1040, 0x53e20131, 0x53e28130,
  2373. 0x53e30130, 0x53e38440, 0x53e58130, 0x53e60240,
  2374. 0x53e80240, 0x53eb0640, 0x53ee0130, 0x53fa8240,
  2375. 0x55a98101, 0x55b85020, 0x7d8001b2, 0x7d8081b2,
  2376. 0x7d8101b2, 0x7d8181da, 0x7d8201da, 0x7d8281b3,
  2377. 0x7d8301b3, 0x7d8981bb, 0x7d8a01bb, 0x7d8a81bb,
  2378. 0x7d8b01bc, 0x7d8b81bb, 0x7f909a31, 0x7fa09a01,
  2379. 0x82002831, 0x82142801, 0x82582431, 0x826c2401,
  2380. 0x82b80b31, 0x82be0f31, 0x82c60731, 0x82ca0231,
  2381. 0x82cb8b01, 0x82d18f01, 0x82d98701, 0x82dd8201,
  2382. 0x86403331, 0x86603301, 0x86a81631, 0x86b81601,
  2383. 0x8c502031, 0x8c602001, 0xb7202031, 0xb7302001,
  2384. 0xf4802231, 0xf4912201,
  2385. };
  2386. static const uint8_t case_conv_table2[378] = {
  2387. 0x01, 0x00, 0x9c, 0x06, 0x07, 0x4d, 0x03, 0x04,
  2388. 0x10, 0x00, 0x8f, 0x0b, 0x00, 0x00, 0x11, 0x00,
  2389. 0x08, 0x00, 0x53, 0x4b, 0x52, 0x00, 0x53, 0x00,
  2390. 0x54, 0x00, 0x3b, 0x55, 0x56, 0x00, 0x58, 0x5a,
  2391. 0x40, 0x5f, 0x5e, 0x00, 0x47, 0x52, 0x63, 0x65,
  2392. 0x43, 0x66, 0x00, 0x68, 0x00, 0x6a, 0x00, 0x6c,
  2393. 0x00, 0x6e, 0x00, 0x70, 0x00, 0x00, 0x41, 0x00,
  2394. 0x00, 0x00, 0x00, 0x1a, 0x00, 0x93, 0x00, 0x00,
  2395. 0x20, 0x36, 0x00, 0x28, 0x00, 0x24, 0x00, 0x24,
  2396. 0x25, 0x2d, 0x00, 0x13, 0x6d, 0x6f, 0x00, 0x29,
  2397. 0x27, 0x2a, 0x14, 0x16, 0x18, 0x1b, 0x1c, 0x41,
  2398. 0x1e, 0x42, 0x1f, 0x4e, 0x3c, 0x40, 0x22, 0x21,
  2399. 0x44, 0x21, 0x43, 0x26, 0x28, 0x27, 0x29, 0x23,
  2400. 0x2b, 0x4b, 0x2d, 0x46, 0x2f, 0x4c, 0x31, 0x4d,
  2401. 0x33, 0x47, 0x45, 0x99, 0x00, 0x00, 0x97, 0x91,
  2402. 0x7f, 0x80, 0x85, 0x86, 0x12, 0x82, 0x84, 0x78,
  2403. 0x79, 0x12, 0x7d, 0xa3, 0x7e, 0x7a, 0x7b, 0x8c,
  2404. 0x92, 0x98, 0xa6, 0xa0, 0x87, 0x00, 0x9a, 0xa1,
  2405. 0x95, 0x77, 0x33, 0x95, 0x00, 0x90, 0x00, 0x76,
  2406. 0x9b, 0x9a, 0x99, 0x98, 0x00, 0x00, 0xa0, 0x00,
  2407. 0x9e, 0x00, 0xa3, 0xa2, 0x15, 0x31, 0x32, 0x33,
  2408. 0xb7, 0xb8, 0x55, 0xac, 0xab, 0x12, 0x14, 0x1e,
  2409. 0x21, 0x22, 0x22, 0x2a, 0x34, 0x35, 0x00, 0xa8,
  2410. 0xa9, 0x39, 0x22, 0x4c, 0x00, 0x00, 0x97, 0x01,
  2411. 0x5a, 0xda, 0x1d, 0x36, 0x05, 0x00, 0xc7, 0xc6,
  2412. 0xc9, 0xc8, 0xcb, 0xca, 0xcd, 0xcc, 0xcf, 0xce,
  2413. 0xc4, 0xd8, 0x45, 0xd9, 0x42, 0xda, 0x46, 0xdb,
  2414. 0xd1, 0xd3, 0xd5, 0xd7, 0xdd, 0xdc, 0xf1, 0xf9,
  2415. 0x01, 0x11, 0x0a, 0x12, 0x80, 0x9f, 0x00, 0x21,
  2416. 0x80, 0xa3, 0xf0, 0x00, 0xc0, 0x40, 0xc6, 0x60,
  2417. 0xea, 0xde, 0xe6, 0x99, 0xc0, 0x00, 0x00, 0x06,
  2418. 0x60, 0xdf, 0x29, 0x00, 0x15, 0x12, 0x06, 0x16,
  2419. 0xfb, 0xe0, 0x09, 0x15, 0x12, 0x84, 0x0b, 0xc6,
  2420. 0x16, 0x02, 0xe2, 0x06, 0xc0, 0x40, 0x00, 0x46,
  2421. 0x60, 0xe1, 0xe3, 0x6d, 0x37, 0x38, 0x39, 0x18,
  2422. 0x17, 0x1a, 0x19, 0x00, 0x1d, 0x1c, 0x1f, 0x1e,
  2423. 0x00, 0x61, 0xba, 0x67, 0x45, 0x48, 0x00, 0x50,
  2424. 0x64, 0x4f, 0x51, 0x00, 0x00, 0x49, 0x00, 0x00,
  2425. 0x00, 0xa5, 0xa6, 0xa7, 0x00, 0x00, 0x00, 0x00,
  2426. 0x00, 0xb9, 0x00, 0x00, 0x5c, 0x00, 0x4a, 0x00,
  2427. 0x5d, 0x57, 0x59, 0x62, 0x60, 0x72, 0x6b, 0x71,
  2428. 0x54, 0x00, 0x3e, 0x69, 0xbb, 0x00, 0x5b, 0x00,
  2429. 0x00, 0x00, 0x25, 0x00, 0x48, 0xaa, 0x8a, 0x8b,
  2430. 0x8c, 0xab, 0xac, 0x58, 0x58, 0xaf, 0x94, 0xb0,
  2431. 0x6f, 0xb2, 0x63, 0x62, 0x65, 0x64, 0x67, 0x66,
  2432. 0x6c, 0x6d, 0x6e, 0x6f, 0x68, 0x69, 0x6a, 0x6b,
  2433. 0x71, 0x70, 0x73, 0x72, 0x75, 0x74, 0x77, 0x76,
  2434. 0x79, 0x78,
  2435. };
  2436. static const uint16_t case_conv_ext[58] = {
  2437. 0x0399, 0x0308, 0x0301, 0x03a5, 0x0313, 0x0300, 0x0342, 0x0391,
  2438. 0x0397, 0x03a9, 0x0046, 0x0049, 0x004c, 0x0053, 0x0069, 0x0307,
  2439. 0x02bc, 0x004e, 0x004a, 0x030c, 0x0535, 0x0552, 0x0048, 0x0331,
  2440. 0x0054, 0x0057, 0x030a, 0x0059, 0x0041, 0x02be, 0x1f08, 0x1f80,
  2441. 0x1f28, 0x1f90, 0x1f68, 0x1fa0, 0x1fba, 0x0386, 0x1fb3, 0x1fca,
  2442. 0x0389, 0x1fc3, 0x03a1, 0x1ffa, 0x038f, 0x1ff3, 0x0544, 0x0546,
  2443. 0x053b, 0x054e, 0x053d, 0x03b8, 0x0462, 0xa64a, 0x1e60, 0x03c9,
  2444. 0x006b, 0x00e5,
  2445. };
  2446. static const uint8_t unicode_prop_Cased1_table[193] = {
  2447. 0x40, 0xa9, 0x80, 0x8e, 0x80, 0xfc, 0x80, 0xd3,
  2448. 0x80, 0x9b, 0x81, 0x8d, 0x02, 0x80, 0xe1, 0x80,
  2449. 0x91, 0x85, 0x9a, 0x01, 0x00, 0x01, 0x11, 0x03,
  2450. 0x04, 0x08, 0x01, 0x08, 0x30, 0x08, 0x01, 0x15,
  2451. 0x20, 0x00, 0x39, 0x99, 0x31, 0x9d, 0x84, 0x40,
  2452. 0x94, 0x80, 0xd6, 0x82, 0xa6, 0x80, 0x41, 0x62,
  2453. 0x80, 0xa6, 0x80, 0x4b, 0x72, 0x80, 0x4c, 0x02,
  2454. 0xf8, 0x02, 0x80, 0x8f, 0x80, 0xb0, 0x40, 0xdb,
  2455. 0x08, 0x80, 0x41, 0xd0, 0x80, 0x8c, 0x80, 0x8f,
  2456. 0x8c, 0xe4, 0x03, 0x01, 0x89, 0x00, 0x14, 0x28,
  2457. 0x10, 0x11, 0x02, 0x01, 0x18, 0x0b, 0x24, 0x4b,
  2458. 0x26, 0x01, 0x01, 0x86, 0xe5, 0x80, 0x60, 0x79,
  2459. 0xb6, 0x81, 0x40, 0x91, 0x81, 0xbd, 0x88, 0x94,
  2460. 0x05, 0x80, 0x98, 0x80, 0xa2, 0x00, 0x80, 0x9b,
  2461. 0x12, 0x82, 0x43, 0x34, 0xa2, 0x06, 0x80, 0x8d,
  2462. 0x60, 0x5c, 0x15, 0x01, 0x10, 0xa9, 0x80, 0x88,
  2463. 0x60, 0xcc, 0x44, 0xd4, 0x80, 0xc6, 0x01, 0x08,
  2464. 0x09, 0x0b, 0x80, 0x8b, 0x00, 0x06, 0x80, 0xc0,
  2465. 0x03, 0x0f, 0x06, 0x80, 0x9b, 0x03, 0x04, 0x00,
  2466. 0x16, 0x80, 0x41, 0x53, 0x81, 0x98, 0x80, 0x98,
  2467. 0x80, 0x9e, 0x80, 0x98, 0x80, 0x9e, 0x80, 0x98,
  2468. 0x80, 0x9e, 0x80, 0x98, 0x80, 0x9e, 0x80, 0x98,
  2469. 0x07, 0x47, 0x33, 0x89, 0x80, 0x93, 0x2d, 0x41,
  2470. 0x04, 0xbd, 0x50, 0xc1, 0x99, 0x85, 0x99, 0x85,
  2471. 0x99,
  2472. };
  2473. static const uint8_t unicode_prop_Cased1_index[18] = {
  2474. 0xb9, 0x02, 0x80, 0xa0, 0x1e, 0x40, 0x9e, 0xa6,
  2475. 0x40, 0xbb, 0x07, 0x01, 0xdb, 0xd6, 0x01, 0x8a,
  2476. 0xf1, 0x01,
  2477. };
  2478. static const uint8_t unicode_prop_Case_Ignorable_table[764] = {
  2479. 0xa6, 0x05, 0x80, 0x8a, 0x80, 0xa2, 0x00, 0x80,
  2480. 0xc6, 0x03, 0x00, 0x03, 0x01, 0x81, 0x41, 0xf6,
  2481. 0x40, 0xbf, 0x19, 0x18, 0x88, 0x08, 0x80, 0x40,
  2482. 0xfa, 0x86, 0x40, 0xce, 0x04, 0x80, 0xb0, 0xac,
  2483. 0x00, 0x01, 0x01, 0x00, 0xab, 0x80, 0x8a, 0x85,
  2484. 0x89, 0x8a, 0x00, 0xa2, 0x80, 0x89, 0x94, 0x8f,
  2485. 0x80, 0xe4, 0x38, 0x89, 0x03, 0xa0, 0x00, 0x80,
  2486. 0x9d, 0x9a, 0xda, 0x8a, 0xb9, 0x8a, 0x18, 0x08,
  2487. 0x97, 0x97, 0xaa, 0x82, 0xab, 0x06, 0x0c, 0x88,
  2488. 0xa8, 0xb9, 0xb6, 0x00, 0x03, 0x3b, 0x02, 0x86,
  2489. 0x89, 0x81, 0x8c, 0x80, 0x8e, 0x80, 0xb9, 0x03,
  2490. 0x1f, 0x80, 0x93, 0x81, 0x99, 0x01, 0x81, 0xb8,
  2491. 0x03, 0x0b, 0x09, 0x12, 0x80, 0x9d, 0x0a, 0x80,
  2492. 0x8a, 0x81, 0xb8, 0x03, 0x20, 0x0b, 0x80, 0x93,
  2493. 0x81, 0x95, 0x28, 0x80, 0xb9, 0x01, 0x00, 0x1f,
  2494. 0x06, 0x81, 0x8a, 0x81, 0x9d, 0x80, 0xbc, 0x80,
  2495. 0x8b, 0x80, 0xb1, 0x02, 0x80, 0xb6, 0x00, 0x14,
  2496. 0x10, 0x1e, 0x81, 0x8a, 0x81, 0x9c, 0x80, 0xb9,
  2497. 0x01, 0x05, 0x04, 0x81, 0x93, 0x81, 0x9b, 0x81,
  2498. 0xb8, 0x0b, 0x1f, 0x80, 0x93, 0x81, 0x9c, 0x80,
  2499. 0xc7, 0x06, 0x10, 0x80, 0xd9, 0x01, 0x86, 0x8a,
  2500. 0x88, 0xe1, 0x01, 0x88, 0x88, 0x00, 0x86, 0xc8,
  2501. 0x81, 0x9a, 0x00, 0x00, 0x80, 0xb6, 0x8d, 0x04,
  2502. 0x01, 0x84, 0x8a, 0x80, 0xa3, 0x88, 0x80, 0xe5,
  2503. 0x18, 0x28, 0x09, 0x81, 0x98, 0x0b, 0x82, 0x8f,
  2504. 0x83, 0x8c, 0x01, 0x0d, 0x80, 0x8e, 0x80, 0xdd,
  2505. 0x80, 0x42, 0x5f, 0x82, 0x43, 0xb1, 0x82, 0x9c,
  2506. 0x81, 0x9d, 0x81, 0x9d, 0x81, 0xbf, 0x08, 0x37,
  2507. 0x01, 0x8a, 0x10, 0x20, 0xac, 0x84, 0xb2, 0x80,
  2508. 0xc0, 0x81, 0xa1, 0x80, 0xf5, 0x13, 0x81, 0x88,
  2509. 0x05, 0x82, 0x40, 0xda, 0x09, 0x80, 0xb9, 0x00,
  2510. 0x30, 0x00, 0x01, 0x3d, 0x89, 0x08, 0xa6, 0x07,
  2511. 0x9e, 0xb0, 0x83, 0xaf, 0x00, 0x20, 0x04, 0x80,
  2512. 0xa7, 0x88, 0x8b, 0x81, 0x9f, 0x19, 0x08, 0x82,
  2513. 0xb7, 0x00, 0x0a, 0x00, 0x82, 0xb9, 0x39, 0x81,
  2514. 0xbf, 0x85, 0xd1, 0x10, 0x8c, 0x06, 0x18, 0x28,
  2515. 0x11, 0xb1, 0xbe, 0x8c, 0x80, 0xa1, 0xe4, 0x41,
  2516. 0xbc, 0x00, 0x82, 0x8a, 0x82, 0x8c, 0x82, 0x8c,
  2517. 0x82, 0x8c, 0x81, 0x8b, 0x27, 0x81, 0x89, 0x01,
  2518. 0x01, 0x84, 0xb0, 0x20, 0x89, 0x00, 0x8c, 0x80,
  2519. 0x8f, 0x8c, 0xb2, 0xa0, 0x4b, 0x8a, 0x81, 0xf0,
  2520. 0x82, 0xfc, 0x80, 0x8e, 0x80, 0xdf, 0x9f, 0xae,
  2521. 0x80, 0x41, 0xd4, 0x80, 0xa3, 0x1a, 0x24, 0x80,
  2522. 0xdc, 0x85, 0xdc, 0x82, 0x60, 0x6f, 0x15, 0x80,
  2523. 0x44, 0xe1, 0x85, 0x41, 0x0d, 0x80, 0xe1, 0x18,
  2524. 0x89, 0x00, 0x9b, 0x83, 0xcf, 0x81, 0x8d, 0xa1,
  2525. 0xcd, 0x80, 0x96, 0x82, 0xe6, 0x12, 0x0f, 0x02,
  2526. 0x03, 0x80, 0x98, 0x0c, 0x80, 0x40, 0x96, 0x81,
  2527. 0x99, 0x91, 0x8c, 0x80, 0xa5, 0x87, 0x98, 0x8a,
  2528. 0xad, 0x82, 0xaf, 0x01, 0x19, 0x81, 0x90, 0x80,
  2529. 0x94, 0x81, 0xc1, 0x29, 0x09, 0x81, 0x8b, 0x07,
  2530. 0x80, 0xa2, 0x80, 0x8a, 0x80, 0xb2, 0x00, 0x11,
  2531. 0x0c, 0x08, 0x80, 0x9a, 0x80, 0x8d, 0x0c, 0x08,
  2532. 0x80, 0xe3, 0x84, 0x88, 0x82, 0xf8, 0x01, 0x03,
  2533. 0x80, 0x60, 0x4f, 0x2f, 0x80, 0x40, 0x92, 0x90,
  2534. 0x42, 0x3c, 0x8f, 0x10, 0x8b, 0x8f, 0xa1, 0x01,
  2535. 0x80, 0x40, 0xa8, 0x06, 0x05, 0x80, 0x8a, 0x80,
  2536. 0xa2, 0x00, 0x80, 0xae, 0x80, 0xac, 0x81, 0xc2,
  2537. 0x80, 0x94, 0x82, 0x42, 0x00, 0x80, 0x40, 0xe1,
  2538. 0x80, 0x40, 0x94, 0x84, 0x44, 0x04, 0x28, 0xa9,
  2539. 0x80, 0x88, 0x42, 0x45, 0x10, 0x0c, 0x83, 0xa7,
  2540. 0x13, 0x80, 0x40, 0xa4, 0x81, 0x42, 0x3c, 0x83,
  2541. 0xa5, 0x80, 0x99, 0x20, 0x80, 0x41, 0x3a, 0x81,
  2542. 0xce, 0x83, 0xc5, 0x8a, 0xb0, 0x83, 0xfa, 0x80,
  2543. 0xb5, 0x8e, 0xa8, 0x01, 0x81, 0x89, 0x82, 0xb0,
  2544. 0x19, 0x09, 0x03, 0x80, 0x89, 0x80, 0xb1, 0x82,
  2545. 0xa3, 0x20, 0x87, 0xbd, 0x80, 0x8b, 0x81, 0xb3,
  2546. 0x88, 0x89, 0x19, 0x80, 0xde, 0x11, 0x00, 0x0d,
  2547. 0x01, 0x80, 0x40, 0x9c, 0x02, 0x87, 0x94, 0x81,
  2548. 0xb8, 0x0a, 0x80, 0xa4, 0x32, 0x84, 0xc5, 0x85,
  2549. 0x8c, 0x00, 0x00, 0x80, 0x8d, 0x81, 0xd4, 0x39,
  2550. 0x10, 0x80, 0x96, 0x80, 0xd3, 0x28, 0x03, 0x08,
  2551. 0x81, 0x40, 0xed, 0x1d, 0x08, 0x81, 0x9a, 0x81,
  2552. 0xd4, 0x39, 0x00, 0x81, 0xe9, 0x00, 0x01, 0x28,
  2553. 0x80, 0xe4, 0x00, 0x01, 0x18, 0x84, 0x41, 0x02,
  2554. 0x88, 0x01, 0x40, 0xff, 0x08, 0x03, 0x80, 0x40,
  2555. 0x8f, 0x19, 0x0b, 0x80, 0x9f, 0x89, 0xa7, 0x29,
  2556. 0x1f, 0x80, 0x88, 0x29, 0x82, 0xad, 0x8c, 0x01,
  2557. 0x41, 0x95, 0x30, 0x28, 0x80, 0xd1, 0x95, 0x0e,
  2558. 0x01, 0x01, 0xf9, 0x2a, 0x00, 0x08, 0x30, 0x80,
  2559. 0xc7, 0x0a, 0x00, 0x80, 0x41, 0x5a, 0x81, 0x8a,
  2560. 0x81, 0xb3, 0x24, 0x00, 0x80, 0x96, 0x80, 0x54,
  2561. 0xd4, 0x90, 0x85, 0x8e, 0x60, 0x2c, 0xc7, 0x8b,
  2562. 0x12, 0x49, 0xbf, 0x84, 0xba, 0x86, 0x88, 0x83,
  2563. 0x41, 0xfb, 0x82, 0xa7, 0x81, 0x41, 0xe1, 0x80,
  2564. 0xbe, 0x90, 0xbf, 0x08, 0x81, 0x60, 0x40, 0x0a,
  2565. 0x18, 0x30, 0x81, 0x4c, 0x9d, 0x08, 0x83, 0x52,
  2566. 0x5b, 0xad, 0x81, 0x96, 0x42, 0x1f, 0x82, 0x88,
  2567. 0x8f, 0x0e, 0x9d, 0x83, 0x40, 0x93, 0x82, 0x47,
  2568. 0xba, 0xb6, 0x83, 0xb1, 0x38, 0x8d, 0x80, 0x95,
  2569. 0x20, 0x8e, 0x45, 0x4f, 0x30, 0x90, 0x0e, 0x01,
  2570. 0x04, 0x84, 0xbd, 0xa0, 0x80, 0x40, 0x9f, 0x8d,
  2571. 0x41, 0x6f, 0x80, 0xbc, 0x83, 0x41, 0xfa, 0x84,
  2572. 0x40, 0xfd, 0x81, 0x42, 0xdf, 0x86, 0xec, 0x87,
  2573. 0x4a, 0xae, 0x84, 0x6c, 0x0c, 0x00, 0x80, 0x9d,
  2574. 0xdf, 0xff, 0x40, 0xef,
  2575. };
  2576. static const uint8_t unicode_prop_Case_Ignorable_index[72] = {
  2577. 0xbe, 0x05, 0x00, 0xfe, 0x07, 0x00, 0x52, 0x0a,
  2578. 0xa0, 0xc1, 0x0b, 0x00, 0x82, 0x0d, 0x00, 0x3f,
  2579. 0x10, 0x80, 0xd4, 0x17, 0x40, 0xcf, 0x1a, 0x20,
  2580. 0xf5, 0x1c, 0x00, 0x80, 0x20, 0x00, 0x16, 0xa0,
  2581. 0x00, 0xc6, 0xa8, 0x00, 0xc2, 0xaa, 0x60, 0x56,
  2582. 0xfe, 0x20, 0xb1, 0x07, 0x01, 0x02, 0x10, 0x01,
  2583. 0x42, 0x12, 0x41, 0xc4, 0x14, 0x21, 0xe1, 0x19,
  2584. 0x81, 0x48, 0x1d, 0x01, 0x44, 0x6b, 0x01, 0x83,
  2585. 0xd1, 0x21, 0x3e, 0xe1, 0x01, 0xf0, 0x01, 0x0e,
  2586. };
  2587. static const uint8_t unicode_prop_ID_Start_table[1133] = {
  2588. 0xc0, 0x99, 0x85, 0x99, 0xae, 0x80, 0x89, 0x03,
  2589. 0x04, 0x96, 0x80, 0x9e, 0x80, 0x41, 0xc9, 0x83,
  2590. 0x8b, 0x8d, 0x26, 0x00, 0x80, 0x40, 0x80, 0x20,
  2591. 0x09, 0x18, 0x05, 0x00, 0x10, 0x00, 0x93, 0x80,
  2592. 0xd2, 0x80, 0x40, 0x8a, 0x87, 0x40, 0xa5, 0x80,
  2593. 0xa5, 0x08, 0x85, 0xa8, 0xc6, 0x9a, 0x1b, 0xac,
  2594. 0xaa, 0xa2, 0x08, 0xe2, 0x00, 0x8e, 0x0e, 0x81,
  2595. 0x89, 0x11, 0x80, 0x8f, 0x00, 0x9d, 0x9c, 0xd8,
  2596. 0x8a, 0x80, 0x97, 0xa0, 0x88, 0x0b, 0x04, 0x95,
  2597. 0x18, 0x88, 0x02, 0x80, 0x96, 0x98, 0x86, 0x8a,
  2598. 0x84, 0x97, 0x05, 0x90, 0xa9, 0xb9, 0xb5, 0x10,
  2599. 0x91, 0x06, 0x89, 0x8e, 0x8f, 0x1f, 0x09, 0x81,
  2600. 0x95, 0x06, 0x00, 0x13, 0x10, 0x8f, 0x80, 0x8c,
  2601. 0x08, 0x82, 0x8d, 0x81, 0x89, 0x07, 0x2b, 0x09,
  2602. 0x95, 0x06, 0x01, 0x01, 0x01, 0x9e, 0x18, 0x80,
  2603. 0x92, 0x82, 0x8f, 0x88, 0x02, 0x80, 0x95, 0x06,
  2604. 0x01, 0x04, 0x10, 0x91, 0x80, 0x8e, 0x81, 0x96,
  2605. 0x80, 0x8a, 0x39, 0x09, 0x95, 0x06, 0x01, 0x04,
  2606. 0x10, 0x9d, 0x08, 0x82, 0x8e, 0x80, 0x90, 0x00,
  2607. 0x2a, 0x10, 0x1a, 0x08, 0x00, 0x0a, 0x0a, 0x12,
  2608. 0x8b, 0x95, 0x80, 0xb3, 0x38, 0x10, 0x96, 0x80,
  2609. 0x8f, 0x10, 0x99, 0x11, 0x01, 0x81, 0x9d, 0x03,
  2610. 0x38, 0x10, 0x96, 0x80, 0x89, 0x04, 0x10, 0x9e,
  2611. 0x08, 0x81, 0x8e, 0x81, 0x90, 0x88, 0x02, 0x80,
  2612. 0xa8, 0x08, 0x8f, 0x04, 0x17, 0x82, 0x97, 0x2c,
  2613. 0x91, 0x82, 0x97, 0x80, 0x88, 0x00, 0x0e, 0xb9,
  2614. 0xaf, 0x01, 0x8b, 0x86, 0xb9, 0x08, 0x00, 0x20,
  2615. 0x97, 0x00, 0x80, 0x89, 0x01, 0x88, 0x01, 0x20,
  2616. 0x80, 0x94, 0x83, 0x9f, 0x80, 0xbe, 0x38, 0xa3,
  2617. 0x9a, 0x84, 0xf2, 0xaa, 0x93, 0x80, 0x8f, 0x2b,
  2618. 0x1a, 0x02, 0x0e, 0x13, 0x8c, 0x8b, 0x80, 0x90,
  2619. 0xa5, 0x00, 0x20, 0x81, 0xaa, 0x80, 0x41, 0x4c,
  2620. 0x03, 0x0e, 0x00, 0x03, 0x81, 0xa8, 0x03, 0x81,
  2621. 0xa0, 0x03, 0x0e, 0x00, 0x03, 0x81, 0x8e, 0x80,
  2622. 0xb8, 0x03, 0x81, 0xc2, 0xa4, 0x8f, 0x8f, 0xd5,
  2623. 0x0d, 0x82, 0x42, 0x6b, 0x81, 0x90, 0x80, 0x99,
  2624. 0x84, 0xca, 0x82, 0x8a, 0x86, 0x91, 0x8c, 0x92,
  2625. 0x8d, 0x91, 0x8d, 0x8c, 0x02, 0x8e, 0xb3, 0xa2,
  2626. 0x03, 0x80, 0xc2, 0xd8, 0x86, 0xa8, 0x00, 0x84,
  2627. 0xc5, 0x89, 0x9e, 0xb0, 0x9d, 0x0c, 0x8a, 0xab,
  2628. 0x83, 0x99, 0xb5, 0x96, 0x88, 0xb4, 0xd1, 0x80,
  2629. 0xdc, 0xae, 0x90, 0x87, 0xb5, 0x9d, 0x8c, 0x81,
  2630. 0x89, 0xab, 0x99, 0xa3, 0xa8, 0x82, 0x89, 0xa3,
  2631. 0x81, 0x8a, 0x84, 0xaa, 0x0a, 0xa8, 0x18, 0x28,
  2632. 0x0a, 0x04, 0x40, 0xbf, 0xbf, 0x41, 0x15, 0x0d,
  2633. 0x81, 0xa5, 0x0d, 0x0f, 0x00, 0x00, 0x00, 0x80,
  2634. 0x9e, 0x81, 0xb4, 0x06, 0x00, 0x12, 0x06, 0x13,
  2635. 0x0d, 0x83, 0x8c, 0x22, 0x06, 0xf3, 0x80, 0x8c,
  2636. 0x80, 0x8f, 0x8c, 0xe4, 0x03, 0x01, 0x89, 0x00,
  2637. 0x0d, 0x28, 0x00, 0x00, 0x80, 0x8f, 0x0b, 0x24,
  2638. 0x18, 0x90, 0xa8, 0x4a, 0x76, 0x40, 0xe4, 0x2b,
  2639. 0x11, 0x8b, 0xa5, 0x00, 0x20, 0x81, 0xb7, 0x30,
  2640. 0x8f, 0x96, 0x88, 0x30, 0x30, 0x30, 0x30, 0x30,
  2641. 0x30, 0x30, 0x86, 0x42, 0x25, 0x82, 0x98, 0x88,
  2642. 0x34, 0x0c, 0x83, 0xd5, 0x1c, 0x80, 0xd9, 0x03,
  2643. 0x84, 0xaa, 0x80, 0xdd, 0x90, 0x9f, 0xaf, 0x8f,
  2644. 0x41, 0xff, 0x59, 0xbf, 0xbf, 0x60, 0x56, 0x8c,
  2645. 0xc2, 0xad, 0x81, 0x41, 0x0c, 0x82, 0x8f, 0x89,
  2646. 0x81, 0x93, 0xae, 0x8f, 0x9e, 0x81, 0xcf, 0xa6,
  2647. 0x88, 0x81, 0xe6, 0x81, 0xc2, 0x09, 0x00, 0x07,
  2648. 0x94, 0x8f, 0x02, 0x03, 0x80, 0x96, 0x9c, 0xb3,
  2649. 0x8d, 0xb1, 0xbd, 0x2a, 0x00, 0x81, 0x8a, 0x9b,
  2650. 0x89, 0x96, 0x98, 0x9c, 0x86, 0xae, 0x9b, 0x80,
  2651. 0x8f, 0x20, 0x89, 0x89, 0x20, 0xa8, 0x96, 0x10,
  2652. 0x87, 0x93, 0x96, 0x10, 0x82, 0xb1, 0x00, 0x11,
  2653. 0x0c, 0x08, 0x00, 0x97, 0x11, 0x8a, 0x32, 0x8b,
  2654. 0x29, 0x29, 0x85, 0x88, 0x30, 0x30, 0xaa, 0x80,
  2655. 0x8d, 0x85, 0xf2, 0x9c, 0x60, 0x2b, 0xa3, 0x8b,
  2656. 0x96, 0x83, 0xb0, 0x60, 0x21, 0x03, 0x41, 0x6d,
  2657. 0x81, 0xe9, 0xa5, 0x86, 0x8b, 0x24, 0x00, 0x89,
  2658. 0x80, 0x8c, 0x04, 0x00, 0x01, 0x01, 0x80, 0xeb,
  2659. 0xa0, 0x41, 0x6a, 0x91, 0xbf, 0x81, 0xb5, 0xa7,
  2660. 0x8b, 0xf3, 0x20, 0x40, 0x86, 0xa3, 0x99, 0x85,
  2661. 0x99, 0x8a, 0xd8, 0x15, 0x0d, 0x0d, 0x0a, 0xa2,
  2662. 0x8b, 0x80, 0x99, 0x80, 0x92, 0x01, 0x80, 0x8e,
  2663. 0x81, 0x8d, 0xa1, 0xfa, 0xc4, 0xb4, 0x41, 0x0a,
  2664. 0x9c, 0x82, 0xb0, 0xae, 0x9f, 0x8c, 0x9d, 0x84,
  2665. 0xa5, 0x89, 0x9d, 0x81, 0xa3, 0x1f, 0x04, 0xa9,
  2666. 0x40, 0x9d, 0x91, 0xa3, 0x83, 0xa3, 0x83, 0xa7,
  2667. 0x87, 0xb3, 0x8b, 0x8a, 0x80, 0x8e, 0x06, 0x01,
  2668. 0x80, 0x8a, 0x80, 0x8e, 0x06, 0x01, 0x82, 0xb3,
  2669. 0x8b, 0x41, 0x36, 0x88, 0x95, 0x89, 0x87, 0x97,
  2670. 0x28, 0xa9, 0x80, 0x88, 0xc4, 0x29, 0x00, 0xab,
  2671. 0x01, 0x10, 0x81, 0x96, 0x89, 0x96, 0x88, 0x9e,
  2672. 0xc0, 0x92, 0x01, 0x89, 0x95, 0x89, 0x99, 0xc5,
  2673. 0xb7, 0x29, 0xbf, 0x80, 0x8e, 0x18, 0x10, 0x9c,
  2674. 0xa9, 0x9c, 0x82, 0x9c, 0xa2, 0x38, 0x9b, 0x9a,
  2675. 0xb5, 0x89, 0x95, 0x89, 0x92, 0x8c, 0x91, 0xed,
  2676. 0xc8, 0xb6, 0xb2, 0x8c, 0xb2, 0x8c, 0xa3, 0xa5,
  2677. 0x9b, 0x88, 0x96, 0x40, 0xf9, 0xa9, 0x29, 0x8f,
  2678. 0x82, 0xba, 0x9c, 0x89, 0x07, 0x95, 0xa9, 0x91,
  2679. 0xad, 0x94, 0x9a, 0x96, 0x8b, 0xb4, 0xb8, 0x09,
  2680. 0x80, 0x8c, 0xac, 0x9f, 0x98, 0x99, 0xa3, 0x9c,
  2681. 0x01, 0x07, 0xa2, 0x10, 0x8b, 0xaf, 0x8d, 0x83,
  2682. 0x94, 0x00, 0x80, 0xa2, 0x91, 0x80, 0x98, 0x92,
  2683. 0x81, 0xbe, 0x30, 0x00, 0x18, 0x8e, 0x80, 0x89,
  2684. 0x86, 0xae, 0xa5, 0x39, 0x09, 0x95, 0x06, 0x01,
  2685. 0x04, 0x10, 0x91, 0x80, 0x8b, 0x84, 0x9d, 0x89,
  2686. 0x00, 0x08, 0x80, 0xa5, 0x00, 0x98, 0x00, 0x80,
  2687. 0xab, 0xb4, 0x91, 0x83, 0x93, 0x82, 0x9d, 0xaf,
  2688. 0x93, 0x08, 0x80, 0x40, 0xb7, 0xae, 0xa8, 0x83,
  2689. 0xa3, 0xaf, 0x93, 0x80, 0xba, 0xaa, 0x8c, 0x80,
  2690. 0xc6, 0x9a, 0xa4, 0x86, 0x40, 0xb8, 0xab, 0xf3,
  2691. 0xbf, 0x9e, 0x39, 0x01, 0x38, 0x08, 0x97, 0x8e,
  2692. 0x00, 0x80, 0xdd, 0x39, 0xa6, 0x8f, 0x00, 0x80,
  2693. 0x9b, 0x80, 0x89, 0xa7, 0x30, 0x94, 0x80, 0x8a,
  2694. 0xad, 0x92, 0x80, 0x91, 0xc8, 0x40, 0xc6, 0xa0,
  2695. 0x9e, 0x88, 0x80, 0xa4, 0x90, 0x80, 0xb0, 0x9d,
  2696. 0xef, 0x30, 0x08, 0xa5, 0x94, 0x80, 0x98, 0x28,
  2697. 0x08, 0x9f, 0x8d, 0x80, 0x41, 0x46, 0x92, 0x8e,
  2698. 0x00, 0x8c, 0x80, 0xa1, 0xfb, 0x80, 0xce, 0x43,
  2699. 0x99, 0xe5, 0xee, 0x90, 0x40, 0xc3, 0x4a, 0x4b,
  2700. 0xe0, 0x8e, 0x44, 0x2f, 0x90, 0x85, 0x98, 0x4f,
  2701. 0x9a, 0x84, 0x42, 0x46, 0x5a, 0xb8, 0x9d, 0x46,
  2702. 0xe1, 0x42, 0x38, 0x86, 0x9e, 0x90, 0xce, 0x90,
  2703. 0x9d, 0x91, 0xaf, 0x8f, 0x83, 0x9e, 0x94, 0x84,
  2704. 0x92, 0x41, 0xaf, 0xac, 0x40, 0xd2, 0xbf, 0xff,
  2705. 0xca, 0x20, 0xc1, 0x8c, 0xbf, 0x08, 0x80, 0x9b,
  2706. 0x57, 0xf7, 0x87, 0x44, 0xd5, 0xa8, 0x89, 0x60,
  2707. 0x22, 0xe6, 0x18, 0x30, 0x08, 0x41, 0x22, 0x8e,
  2708. 0x80, 0x9c, 0x11, 0x80, 0x8d, 0x1f, 0x41, 0x8b,
  2709. 0x49, 0x03, 0xea, 0x84, 0x8c, 0x82, 0x88, 0x86,
  2710. 0x89, 0x57, 0x65, 0xd4, 0x80, 0xc6, 0x01, 0x08,
  2711. 0x09, 0x0b, 0x80, 0x8b, 0x00, 0x06, 0x80, 0xc0,
  2712. 0x03, 0x0f, 0x06, 0x80, 0x9b, 0x03, 0x04, 0x00,
  2713. 0x16, 0x80, 0x41, 0x53, 0x81, 0x98, 0x80, 0x98,
  2714. 0x80, 0x9e, 0x80, 0x98, 0x80, 0x9e, 0x80, 0x98,
  2715. 0x80, 0x9e, 0x80, 0x98, 0x80, 0x9e, 0x80, 0x98,
  2716. 0x07, 0x47, 0x33, 0x9e, 0x2d, 0x41, 0x04, 0xbd,
  2717. 0x40, 0x91, 0xac, 0x89, 0x86, 0x8f, 0x80, 0x41,
  2718. 0x40, 0x9d, 0x91, 0xab, 0x41, 0xe3, 0x9b, 0x40,
  2719. 0xe3, 0x9d, 0x08, 0x41, 0xee, 0x30, 0x18, 0x08,
  2720. 0x8e, 0x80, 0x40, 0xc4, 0xba, 0xc3, 0x30, 0x44,
  2721. 0xb3, 0x18, 0x9a, 0x01, 0x00, 0x08, 0x80, 0x89,
  2722. 0x03, 0x00, 0x00, 0x28, 0x18, 0x00, 0x00, 0x02,
  2723. 0x01, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x01,
  2724. 0x00, 0x0b, 0x06, 0x03, 0x03, 0x00, 0x80, 0x89,
  2725. 0x80, 0x90, 0x22, 0x04, 0x80, 0x90, 0x51, 0x43,
  2726. 0x60, 0xa6, 0xdf, 0x9f, 0x50, 0x39, 0x85, 0x40,
  2727. 0xdd, 0x81, 0x56, 0x81, 0x8d, 0x5d, 0x30, 0x8e,
  2728. 0x42, 0x6d, 0x49, 0xa1, 0x42, 0x1d, 0x45, 0xe1,
  2729. 0x53, 0x4a, 0x84, 0x50, 0x5f,
  2730. };
  2731. static const uint8_t unicode_prop_ID_Start_index[108] = {
  2732. 0xf6, 0x03, 0x20, 0xa6, 0x07, 0x00, 0xa9, 0x09,
  2733. 0x20, 0xb1, 0x0a, 0x00, 0xba, 0x0b, 0x20, 0x3b,
  2734. 0x0d, 0x20, 0xc7, 0x0e, 0x20, 0x49, 0x12, 0x00,
  2735. 0x9b, 0x16, 0x00, 0xac, 0x19, 0x00, 0xc0, 0x1d,
  2736. 0x80, 0x80, 0x20, 0x20, 0x70, 0x2d, 0x00, 0x00,
  2737. 0x32, 0x00, 0xdd, 0xa7, 0x00, 0x4c, 0xaa, 0x20,
  2738. 0xc7, 0xd7, 0x20, 0xfc, 0xfd, 0x20, 0x9d, 0x02,
  2739. 0x21, 0x96, 0x05, 0x01, 0x9f, 0x08, 0x01, 0x49,
  2740. 0x0c, 0x21, 0x76, 0x10, 0x21, 0xa9, 0x12, 0x01,
  2741. 0xb0, 0x14, 0x01, 0x42, 0x19, 0x41, 0x90, 0x1c,
  2742. 0x01, 0xf1, 0x2f, 0x21, 0x90, 0x6b, 0x21, 0x33,
  2743. 0xb1, 0x21, 0x06, 0xd5, 0x01, 0xc3, 0xd7, 0x01,
  2744. 0xff, 0xe7, 0x21, 0x63, 0xee, 0x01, 0x5e, 0xee,
  2745. 0x42, 0xb0, 0x23, 0x03,
  2746. };
  2747. static const uint8_t unicode_prop_ID_Continue1_table[695] = {
  2748. 0xaf, 0x89, 0xa4, 0x80, 0xd6, 0x80, 0x42, 0x47,
  2749. 0xef, 0x96, 0x80, 0x40, 0xfa, 0x84, 0x41, 0x08,
  2750. 0xac, 0x00, 0x01, 0x01, 0x00, 0xc7, 0x8a, 0xaf,
  2751. 0x9e, 0x28, 0xe4, 0x31, 0x29, 0x08, 0x19, 0x89,
  2752. 0x96, 0x80, 0x9d, 0x9a, 0xda, 0x8a, 0x8e, 0x89,
  2753. 0xa0, 0x88, 0x88, 0x80, 0x97, 0x18, 0x88, 0x02,
  2754. 0x04, 0xaa, 0x82, 0xba, 0x88, 0xa9, 0x97, 0x80,
  2755. 0xa0, 0xb5, 0x10, 0x91, 0x06, 0x89, 0x09, 0x89,
  2756. 0x90, 0x82, 0xb7, 0x00, 0x31, 0x09, 0x82, 0x88,
  2757. 0x80, 0x89, 0x09, 0x89, 0x8d, 0x01, 0x82, 0xb7,
  2758. 0x00, 0x23, 0x09, 0x12, 0x80, 0x93, 0x8b, 0x10,
  2759. 0x8a, 0x82, 0xb7, 0x00, 0x38, 0x10, 0x82, 0x93,
  2760. 0x09, 0x89, 0x89, 0x28, 0x82, 0xb7, 0x00, 0x31,
  2761. 0x09, 0x16, 0x82, 0x89, 0x09, 0x89, 0x91, 0x80,
  2762. 0xba, 0x22, 0x10, 0x83, 0x88, 0x80, 0x8d, 0x89,
  2763. 0x8f, 0x84, 0xb6, 0x00, 0x30, 0x10, 0x1e, 0x81,
  2764. 0x8a, 0x09, 0x89, 0x90, 0x82, 0xb7, 0x00, 0x30,
  2765. 0x10, 0x1e, 0x81, 0x8a, 0x09, 0x89, 0x10, 0x8b,
  2766. 0x83, 0xb6, 0x08, 0x30, 0x10, 0x83, 0x88, 0x80,
  2767. 0x89, 0x09, 0x89, 0x90, 0x82, 0xc5, 0x03, 0x28,
  2768. 0x00, 0x3d, 0x89, 0x09, 0xbc, 0x01, 0x86, 0x8b,
  2769. 0x38, 0x89, 0xd6, 0x01, 0x88, 0x8a, 0x30, 0x89,
  2770. 0xbd, 0x0d, 0x89, 0x8a, 0x00, 0x00, 0x03, 0x81,
  2771. 0xb0, 0x93, 0x01, 0x84, 0x8a, 0x80, 0xa3, 0x88,
  2772. 0x80, 0xe3, 0x93, 0x80, 0x89, 0x8b, 0x1b, 0x10,
  2773. 0x11, 0x32, 0x83, 0x8c, 0x8b, 0x80, 0x8e, 0x42,
  2774. 0xbe, 0x82, 0x88, 0x88, 0x43, 0x9f, 0x83, 0x9b,
  2775. 0x82, 0x9c, 0x81, 0x9d, 0x81, 0xbf, 0x9f, 0x88,
  2776. 0x01, 0x89, 0xa0, 0x10, 0x8a, 0x40, 0x8e, 0x80,
  2777. 0xf5, 0x8b, 0x83, 0x8b, 0x89, 0x89, 0xff, 0x8a,
  2778. 0xbb, 0x84, 0xb8, 0x89, 0x80, 0x9c, 0x81, 0x8a,
  2779. 0x85, 0x89, 0x95, 0x8d, 0x80, 0x8f, 0xb0, 0x84,
  2780. 0xae, 0x90, 0x8a, 0x89, 0x90, 0x88, 0x8b, 0x82,
  2781. 0x9d, 0x8c, 0x81, 0x89, 0xab, 0x8d, 0xaf, 0x93,
  2782. 0x87, 0x89, 0x85, 0x89, 0xf5, 0x10, 0x94, 0x18,
  2783. 0x28, 0x0a, 0x40, 0xc5, 0xbf, 0x42, 0x0b, 0x81,
  2784. 0xb0, 0x81, 0x92, 0x80, 0xfa, 0x8c, 0x18, 0x82,
  2785. 0x8b, 0x4b, 0xfd, 0x82, 0x40, 0x8c, 0x80, 0xdf,
  2786. 0x9f, 0x42, 0x29, 0x85, 0xe8, 0x81, 0xdf, 0x80,
  2787. 0x60, 0x75, 0x23, 0x89, 0xc4, 0x03, 0x89, 0x9f,
  2788. 0x81, 0xcf, 0x81, 0x41, 0x0f, 0x02, 0x03, 0x80,
  2789. 0x96, 0x23, 0x80, 0xd2, 0x81, 0xb1, 0x91, 0x89,
  2790. 0x89, 0x85, 0x91, 0x8c, 0x8a, 0x9b, 0x87, 0x98,
  2791. 0x8c, 0xab, 0x83, 0xae, 0x8d, 0x8e, 0x89, 0x8a,
  2792. 0x80, 0x89, 0x89, 0xae, 0x8d, 0x8b, 0x07, 0x09,
  2793. 0x89, 0xa0, 0x82, 0xb1, 0x00, 0x11, 0x0c, 0x08,
  2794. 0x80, 0xa8, 0x24, 0x81, 0x40, 0xeb, 0x38, 0x09,
  2795. 0x89, 0x60, 0x4f, 0x23, 0x80, 0x42, 0xe0, 0x8f,
  2796. 0x8f, 0x8f, 0x11, 0x97, 0x82, 0x40, 0xbf, 0x89,
  2797. 0xa4, 0x80, 0xa4, 0x80, 0x42, 0x96, 0x80, 0x40,
  2798. 0xe1, 0x80, 0x40, 0x94, 0x84, 0x41, 0x24, 0x89,
  2799. 0x45, 0x56, 0x10, 0x0c, 0x83, 0xa7, 0x13, 0x80,
  2800. 0x40, 0xa4, 0x81, 0x42, 0x3c, 0x1f, 0x89, 0x85,
  2801. 0x89, 0x9e, 0x84, 0x41, 0x3c, 0x81, 0xce, 0x83,
  2802. 0xc5, 0x8a, 0xb0, 0x83, 0xf9, 0x82, 0xb4, 0x8e,
  2803. 0x9e, 0x8a, 0x09, 0x89, 0x83, 0xac, 0x8a, 0x30,
  2804. 0xac, 0x89, 0x2a, 0xa3, 0x8d, 0x80, 0x89, 0x21,
  2805. 0xab, 0x80, 0x8b, 0x82, 0xaf, 0x8d, 0x3b, 0x80,
  2806. 0x8b, 0xd1, 0x8b, 0x28, 0x08, 0x40, 0x9c, 0x8b,
  2807. 0x84, 0x89, 0x2b, 0xb6, 0x08, 0x31, 0x09, 0x82,
  2808. 0x88, 0x80, 0x89, 0x09, 0x32, 0x84, 0xc2, 0x88,
  2809. 0x00, 0x08, 0x03, 0x04, 0x00, 0x8d, 0x81, 0xd1,
  2810. 0x91, 0x88, 0x89, 0x18, 0xd0, 0x93, 0x8b, 0x89,
  2811. 0x40, 0xd4, 0x31, 0x88, 0x9a, 0x81, 0xd1, 0x90,
  2812. 0x8e, 0x89, 0xd0, 0x8c, 0x87, 0x89, 0x85, 0x93,
  2813. 0xb8, 0x8e, 0x83, 0x89, 0x40, 0xf1, 0x8e, 0x40,
  2814. 0xa4, 0x89, 0xc5, 0x28, 0x09, 0x18, 0x00, 0x81,
  2815. 0x8b, 0x89, 0xf6, 0x31, 0x32, 0x80, 0x9b, 0x89,
  2816. 0xa7, 0x30, 0x1f, 0x80, 0x88, 0x8a, 0xad, 0x8f,
  2817. 0x41, 0x55, 0x89, 0xb4, 0x38, 0x87, 0x8f, 0x89,
  2818. 0xb7, 0x95, 0x80, 0x8d, 0xf9, 0x2a, 0x00, 0x08,
  2819. 0x30, 0x07, 0x89, 0xaf, 0x20, 0x08, 0x27, 0x89,
  2820. 0x41, 0x48, 0x83, 0x88, 0x08, 0x80, 0xaf, 0x32,
  2821. 0x84, 0x8c, 0x8a, 0x54, 0xe4, 0x05, 0x8e, 0x60,
  2822. 0x2c, 0xc7, 0x9b, 0x49, 0x25, 0x89, 0xd5, 0x89,
  2823. 0xa5, 0x84, 0xba, 0x86, 0x98, 0x89, 0x42, 0x15,
  2824. 0x89, 0x41, 0xd4, 0x00, 0xb6, 0x33, 0xd0, 0x80,
  2825. 0x8a, 0x81, 0x60, 0x4c, 0xaa, 0x81, 0x50, 0x50,
  2826. 0x89, 0x42, 0x05, 0xad, 0x81, 0x96, 0x42, 0x1d,
  2827. 0x22, 0x2f, 0x39, 0x86, 0x9d, 0x83, 0x40, 0x93,
  2828. 0x82, 0x45, 0x88, 0xb1, 0x41, 0xff, 0xb6, 0x83,
  2829. 0xb1, 0x38, 0x8d, 0x80, 0x95, 0x20, 0x8e, 0x45,
  2830. 0x4f, 0x30, 0x90, 0x0e, 0x01, 0x04, 0xe3, 0x80,
  2831. 0x40, 0x9f, 0x86, 0x88, 0x89, 0x41, 0x63, 0x80,
  2832. 0xbc, 0x8d, 0x41, 0xf1, 0x8d, 0x40, 0xf3, 0x08,
  2833. 0x89, 0x42, 0xd4, 0x86, 0xec, 0x34, 0x89, 0x52,
  2834. 0x95, 0x89, 0x6c, 0x05, 0x05, 0x40, 0xef,
  2835. };
  2836. static const uint8_t unicode_prop_ID_Continue1_index[66] = {
  2837. 0xfa, 0x06, 0x00, 0x70, 0x09, 0x00, 0xf0, 0x0a,
  2838. 0x40, 0x57, 0x0c, 0x00, 0xf0, 0x0d, 0x60, 0xc7,
  2839. 0x0f, 0x20, 0xea, 0x17, 0x40, 0x05, 0x1b, 0x00,
  2840. 0x0e, 0x20, 0x00, 0xa0, 0xa6, 0x20, 0xe6, 0xa9,
  2841. 0x20, 0x10, 0xfe, 0x00, 0x40, 0x0a, 0x01, 0xc3,
  2842. 0x10, 0x01, 0x4e, 0x13, 0x01, 0x41, 0x16, 0x01,
  2843. 0x0b, 0x1a, 0x01, 0xaa, 0x1d, 0x01, 0x7a, 0x6d,
  2844. 0x21, 0x45, 0xd2, 0x21, 0xaf, 0xe2, 0x01, 0xf0,
  2845. 0x01, 0x0e,
  2846. };
  2847. static const uint8_t unicode_prop_White_Space_table[22] = {
  2848. 0x88, 0x84, 0x91, 0x80, 0xe3, 0x80, 0x99, 0x80,
  2849. 0x55, 0xde, 0x80, 0x49, 0x7e, 0x8a, 0x9c, 0x0c,
  2850. 0x80, 0xae, 0x80, 0x4f, 0x9f, 0x80,
  2851. };
  2852. static const uint8_t unicode_prop_White_Space_index[3] = {
  2853. 0x01, 0x30, 0x00,
  2854. };
  2855. static const uint8_t unicode_cc_table[916] = {
  2856. 0xb2, 0xcf, 0xd4, 0x00, 0xe8, 0x03, 0xdc, 0x00,
  2857. 0xe8, 0x00, 0xd8, 0x04, 0xdc, 0x01, 0xca, 0x03,
  2858. 0xdc, 0x01, 0xca, 0x0a, 0xdc, 0x04, 0x01, 0x03,
  2859. 0xdc, 0xc7, 0x00, 0xf0, 0xc0, 0x02, 0xdc, 0xc2,
  2860. 0x01, 0xdc, 0x80, 0xc2, 0x03, 0xdc, 0xc0, 0x00,
  2861. 0xe8, 0x01, 0xdc, 0xc0, 0x41, 0xe9, 0x00, 0xea,
  2862. 0x41, 0xe9, 0x00, 0xea, 0x00, 0xe9, 0xcc, 0xb0,
  2863. 0xe2, 0xc4, 0xb0, 0xd8, 0x00, 0xdc, 0xc3, 0x00,
  2864. 0xdc, 0xc2, 0x00, 0xde, 0x00, 0xdc, 0xc5, 0x05,
  2865. 0xdc, 0xc1, 0x00, 0xdc, 0xc1, 0x00, 0xde, 0x00,
  2866. 0xe4, 0xc0, 0x49, 0x0a, 0x43, 0x13, 0x80, 0x00,
  2867. 0x17, 0x80, 0x41, 0x18, 0x80, 0xc0, 0x00, 0xdc,
  2868. 0x80, 0x00, 0x12, 0xb0, 0x17, 0xc7, 0x42, 0x1e,
  2869. 0xaf, 0x47, 0x1b, 0xc1, 0x01, 0xdc, 0xc4, 0x00,
  2870. 0xdc, 0xc1, 0x00, 0xdc, 0x8f, 0x00, 0x23, 0xb0,
  2871. 0x34, 0xc6, 0x81, 0xc3, 0x00, 0xdc, 0xc0, 0x81,
  2872. 0xc1, 0x80, 0x00, 0xdc, 0xc1, 0x00, 0xdc, 0xa2,
  2873. 0x00, 0x24, 0x9d, 0xc0, 0x00, 0xdc, 0xc1, 0x00,
  2874. 0xdc, 0xc1, 0x02, 0xdc, 0xc0, 0x01, 0xdc, 0xc0,
  2875. 0x00, 0xdc, 0xc2, 0x00, 0xdc, 0xc0, 0x00, 0xdc,
  2876. 0xc0, 0x00, 0xdc, 0xc0, 0x00, 0xdc, 0xc1, 0xb0,
  2877. 0x6f, 0xc6, 0x00, 0xdc, 0xc0, 0x88, 0x00, 0xdc,
  2878. 0x97, 0xc3, 0x80, 0xc8, 0x80, 0xc2, 0x80, 0xc4,
  2879. 0xaa, 0x02, 0xdc, 0xb0, 0x0a, 0xc1, 0x02, 0xdc,
  2880. 0xc3, 0xa9, 0xc4, 0x04, 0xdc, 0xcd, 0x80, 0x00,
  2881. 0xdc, 0xc1, 0x00, 0xdc, 0xc1, 0x00, 0xdc, 0xc2,
  2882. 0x02, 0xdc, 0x42, 0x1b, 0xc2, 0x00, 0xdc, 0xc1,
  2883. 0x01, 0xdc, 0xc4, 0xb0, 0x0b, 0x00, 0x07, 0x8f,
  2884. 0x00, 0x09, 0x82, 0xc0, 0x00, 0xdc, 0xc1, 0xb0,
  2885. 0x36, 0x00, 0x07, 0x8f, 0x00, 0x09, 0xaf, 0xc0,
  2886. 0xb0, 0x0c, 0x00, 0x07, 0x8f, 0x00, 0x09, 0xb0,
  2887. 0x3d, 0x00, 0x07, 0x8f, 0x00, 0x09, 0xb0, 0x3d,
  2888. 0x00, 0x07, 0x8f, 0x00, 0x09, 0xb0, 0x4e, 0x00,
  2889. 0x09, 0xb0, 0x3d, 0x00, 0x07, 0x8f, 0x00, 0x09,
  2890. 0x86, 0x00, 0x54, 0x00, 0x5b, 0xb0, 0x34, 0x00,
  2891. 0x07, 0x8f, 0x00, 0x09, 0xb0, 0x3c, 0x01, 0x09,
  2892. 0x8f, 0x00, 0x09, 0xb0, 0x4b, 0x00, 0x09, 0xb0,
  2893. 0x3c, 0x01, 0x67, 0x00, 0x09, 0x8c, 0x03, 0x6b,
  2894. 0xb0, 0x3b, 0x01, 0x76, 0x00, 0x09, 0x8c, 0x03,
  2895. 0x7a, 0xb0, 0x1b, 0x01, 0xdc, 0x9a, 0x00, 0xdc,
  2896. 0x80, 0x00, 0xdc, 0x80, 0x00, 0xd8, 0xb0, 0x06,
  2897. 0x41, 0x81, 0x80, 0x00, 0x84, 0x84, 0x03, 0x82,
  2898. 0x81, 0x00, 0x82, 0x80, 0xc1, 0x00, 0x09, 0x80,
  2899. 0xc1, 0xb0, 0x0d, 0x00, 0xdc, 0xb0, 0x3f, 0x00,
  2900. 0x07, 0x80, 0x01, 0x09, 0xb0, 0x21, 0x00, 0xdc,
  2901. 0xb2, 0x9e, 0xc2, 0xb3, 0x83, 0x01, 0x09, 0x9d,
  2902. 0x00, 0x09, 0xb0, 0x6c, 0x00, 0x09, 0x89, 0xc0,
  2903. 0xb0, 0x9a, 0x00, 0xe4, 0xb0, 0x5e, 0x00, 0xde,
  2904. 0xc0, 0x00, 0xdc, 0xb0, 0xaa, 0xc0, 0x00, 0xdc,
  2905. 0xb0, 0x16, 0x00, 0x09, 0x93, 0xc7, 0x81, 0x00,
  2906. 0xdc, 0xaf, 0xc4, 0x05, 0xdc, 0xc1, 0x00, 0xdc,
  2907. 0x80, 0x01, 0xdc, 0xc1, 0x01, 0xdc, 0xc4, 0x00,
  2908. 0xdc, 0xc3, 0xb0, 0x34, 0x00, 0x07, 0x8e, 0x00,
  2909. 0x09, 0xa5, 0xc0, 0x00, 0xdc, 0xc6, 0xb0, 0x05,
  2910. 0x01, 0x09, 0xb0, 0x09, 0x00, 0x07, 0x8a, 0x01,
  2911. 0x09, 0xb0, 0x12, 0x00, 0x07, 0xb0, 0x67, 0xc2,
  2912. 0x41, 0x00, 0x04, 0xdc, 0xc1, 0x03, 0xdc, 0xc0,
  2913. 0x41, 0x00, 0x05, 0x01, 0x83, 0x00, 0xdc, 0x85,
  2914. 0xc0, 0x82, 0xc1, 0xb0, 0x95, 0xc1, 0x00, 0xdc,
  2915. 0xc6, 0x00, 0xdc, 0xc1, 0x00, 0xea, 0x00, 0xd6,
  2916. 0x00, 0xdc, 0x00, 0xca, 0xe4, 0x00, 0xe8, 0x01,
  2917. 0xe4, 0x00, 0xdc, 0x00, 0xda, 0xc0, 0x00, 0xe9,
  2918. 0x00, 0xdc, 0xc0, 0x00, 0xdc, 0xb2, 0x9f, 0xc1,
  2919. 0x01, 0x01, 0xc3, 0x02, 0x01, 0xc1, 0x83, 0xc0,
  2920. 0x82, 0x01, 0x01, 0xc0, 0x00, 0xdc, 0xc0, 0x01,
  2921. 0x01, 0x03, 0xdc, 0xc0, 0xb8, 0x03, 0xcd, 0xc2,
  2922. 0xb0, 0x5c, 0x00, 0x09, 0xb0, 0x2f, 0xdf, 0xb1,
  2923. 0xf9, 0x00, 0xda, 0x00, 0xe4, 0x00, 0xe8, 0x00,
  2924. 0xde, 0x01, 0xe0, 0xb0, 0x38, 0x01, 0x08, 0xb8,
  2925. 0x6d, 0xa3, 0xc0, 0x83, 0xc9, 0x9f, 0xc1, 0xb0,
  2926. 0x1f, 0xc1, 0xb0, 0xe3, 0x00, 0x09, 0xa4, 0x00,
  2927. 0x09, 0xb0, 0x66, 0x00, 0x09, 0x9a, 0xd1, 0xb0,
  2928. 0x08, 0x02, 0xdc, 0xa4, 0x00, 0x09, 0xb0, 0x2e,
  2929. 0x00, 0x07, 0x8b, 0x00, 0x09, 0xb0, 0xbe, 0xc0,
  2930. 0x80, 0xc1, 0x00, 0xdc, 0x81, 0xc1, 0x84, 0xc1,
  2931. 0x80, 0xc0, 0xb0, 0x03, 0x00, 0x09, 0xb0, 0xc5,
  2932. 0x00, 0x09, 0xb8, 0x46, 0xff, 0x00, 0x1a, 0xb2,
  2933. 0xd0, 0xc6, 0x06, 0xdc, 0xc1, 0xb3, 0x9c, 0x00,
  2934. 0xdc, 0xb0, 0xb1, 0x00, 0xdc, 0xb0, 0x64, 0xc4,
  2935. 0xb6, 0x61, 0x00, 0xdc, 0x80, 0xc0, 0xa7, 0xc0,
  2936. 0x00, 0x01, 0x00, 0xdc, 0x83, 0x00, 0x09, 0xb0,
  2937. 0x74, 0xc0, 0x00, 0xdc, 0xb2, 0x0c, 0xc3, 0xb0,
  2938. 0x10, 0xc4, 0xb1, 0x0c, 0xc1, 0xb0, 0x1f, 0x02,
  2939. 0xdc, 0xb0, 0x15, 0x01, 0xdc, 0xc2, 0x00, 0xdc,
  2940. 0xc0, 0x03, 0xdc, 0xb0, 0x00, 0xc0, 0x00, 0xdc,
  2941. 0xc0, 0x00, 0xdc, 0xb0, 0x8f, 0x00, 0x09, 0xa8,
  2942. 0x00, 0x09, 0x8d, 0x00, 0x09, 0xb0, 0x08, 0x00,
  2943. 0x09, 0x00, 0x07, 0xb0, 0x14, 0xc2, 0xaf, 0x01,
  2944. 0x09, 0xb0, 0x0d, 0x00, 0x07, 0xb0, 0x1b, 0x00,
  2945. 0x09, 0x88, 0x00, 0x07, 0xb0, 0x39, 0x00, 0x09,
  2946. 0x00, 0x07, 0xb0, 0x81, 0x00, 0x07, 0x00, 0x09,
  2947. 0xb0, 0x1f, 0x01, 0x07, 0x8f, 0x00, 0x09, 0x97,
  2948. 0xc6, 0x82, 0xc4, 0xb0, 0x28, 0x02, 0x09, 0xb0,
  2949. 0x40, 0x00, 0x09, 0x82, 0x00, 0x07, 0x96, 0xc0,
  2950. 0xb0, 0x32, 0x00, 0x09, 0x00, 0x07, 0xb0, 0xca,
  2951. 0x00, 0x09, 0x00, 0x07, 0xb0, 0x4d, 0x00, 0x09,
  2952. 0xb0, 0x45, 0x00, 0x09, 0x00, 0x07, 0xb0, 0x42,
  2953. 0x00, 0x09, 0xb0, 0xdc, 0x00, 0x09, 0x00, 0x07,
  2954. 0xb0, 0xd1, 0x01, 0x09, 0x83, 0x00, 0x07, 0xb0,
  2955. 0x6b, 0x00, 0x09, 0xb0, 0x22, 0x00, 0x09, 0x91,
  2956. 0x00, 0x09, 0xb0, 0x20, 0x00, 0x09, 0xb1, 0x74,
  2957. 0x00, 0x09, 0xb0, 0xd1, 0x00, 0x07, 0x80, 0x01,
  2958. 0x09, 0xb0, 0x20, 0x00, 0x09, 0xb1, 0x78, 0x01,
  2959. 0x09, 0xb8, 0x39, 0xbb, 0x00, 0x09, 0xb8, 0x01,
  2960. 0x8f, 0x04, 0x01, 0xb0, 0x0a, 0xc6, 0xb4, 0x88,
  2961. 0x01, 0x06, 0xb8, 0x44, 0x7b, 0x00, 0x01, 0xb8,
  2962. 0x0c, 0x95, 0x01, 0xd8, 0x02, 0x01, 0x82, 0x00,
  2963. 0xe2, 0x04, 0xd8, 0x87, 0x07, 0xdc, 0x81, 0xc4,
  2964. 0x01, 0xdc, 0x9d, 0xc3, 0xb0, 0x63, 0xc2, 0xb8,
  2965. 0x05, 0x8a, 0xc6, 0x80, 0xd0, 0x81, 0xc6, 0x80,
  2966. 0xc1, 0x80, 0xc4, 0xb0, 0x33, 0xc0, 0xb0, 0x6f,
  2967. 0xc6, 0xb1, 0x46, 0xc0, 0xb0, 0x0c, 0xc3, 0xb1,
  2968. 0xcb, 0x01, 0xe8, 0x00, 0xdc, 0xc0, 0xb0, 0xcd,
  2969. 0xc0, 0x00, 0xdc, 0xb2, 0xaf, 0x06, 0xdc, 0xb0,
  2970. 0x3c, 0xc5, 0x00, 0x07,
  2971. };
  2972. static const uint8_t unicode_cc_index[87] = {
  2973. 0x4d, 0x03, 0x00, 0x97, 0x05, 0x20, 0xc6, 0x05,
  2974. 0x00, 0xe7, 0x06, 0x00, 0x45, 0x07, 0x00, 0x9c,
  2975. 0x08, 0x00, 0x4d, 0x09, 0x00, 0x3c, 0x0b, 0x00,
  2976. 0x3d, 0x0d, 0x00, 0x36, 0x0f, 0x00, 0x38, 0x10,
  2977. 0x20, 0x3a, 0x19, 0x00, 0xcb, 0x1a, 0x20, 0xd3,
  2978. 0x1c, 0x00, 0xcf, 0x1d, 0x00, 0xe2, 0x20, 0x00,
  2979. 0x2e, 0x30, 0x20, 0x2b, 0xa9, 0x20, 0xed, 0xab,
  2980. 0x00, 0x39, 0x0a, 0x01, 0x4c, 0x0f, 0x01, 0x35,
  2981. 0x11, 0x21, 0x66, 0x13, 0x01, 0x40, 0x16, 0x01,
  2982. 0x47, 0x1a, 0x01, 0xf0, 0x6a, 0x21, 0x8a, 0xd1,
  2983. 0x01, 0xec, 0xe4, 0x21, 0x4b, 0xe9, 0x01,
  2984. };
  2985. static const uint32_t unicode_decomp_table1[709] = {
  2986. 0x00280081, 0x002a0097, 0x002a8081, 0x002bc097,
  2987. 0x002c8115, 0x002d0097, 0x002d4081, 0x002e0097,
  2988. 0x002e4115, 0x002f0199, 0x00302016, 0x00400842,
  2989. 0x00448a42, 0x004a0442, 0x004c0096, 0x004c8117,
  2990. 0x004d0242, 0x004e4342, 0x004fc12f, 0x0050c342,
  2991. 0x005240bf, 0x00530342, 0x00550942, 0x005a0842,
  2992. 0x005e0096, 0x005e4342, 0x005fc081, 0x00680142,
  2993. 0x006bc142, 0x00710185, 0x0071c317, 0x00734844,
  2994. 0x00778344, 0x00798342, 0x007b02be, 0x007c4197,
  2995. 0x007d0142, 0x007e0444, 0x00800e42, 0x00878142,
  2996. 0x00898744, 0x00ac0483, 0x00b60317, 0x00b80283,
  2997. 0x00d00214, 0x00d10096, 0x00dd0080, 0x00de8097,
  2998. 0x00df8080, 0x00e10097, 0x00e1413e, 0x00e1c080,
  2999. 0x00e204be, 0x00ea83ae, 0x00f282ae, 0x00f401ad,
  3000. 0x00f4c12e, 0x00f54103, 0x00fc0303, 0x00fe4081,
  3001. 0x0100023e, 0x0101c0be, 0x010301be, 0x010640be,
  3002. 0x010e40be, 0x0114023e, 0x0115c0be, 0x011701be,
  3003. 0x011d8144, 0x01304144, 0x01340244, 0x01358144,
  3004. 0x01368344, 0x01388344, 0x013a8644, 0x013e0144,
  3005. 0x0161c085, 0x018882ae, 0x019d422f, 0x01b00184,
  3006. 0x01b4c084, 0x024a4084, 0x024c4084, 0x024d0084,
  3007. 0x0256042e, 0x0272c12e, 0x02770120, 0x0277c084,
  3008. 0x028cc084, 0x028d8084, 0x029641ae, 0x02978084,
  3009. 0x02d20084, 0x02d2c12e, 0x02d70120, 0x02e50084,
  3010. 0x02f281ae, 0x03120084, 0x03300084, 0x0331c122,
  3011. 0x0332812e, 0x035281ae, 0x03768084, 0x037701ae,
  3012. 0x038cc085, 0x03acc085, 0x03b7012f, 0x03c30081,
  3013. 0x03d0c084, 0x03d34084, 0x03d48084, 0x03d5c084,
  3014. 0x03d70084, 0x03da4084, 0x03dcc084, 0x03dd412e,
  3015. 0x03ddc085, 0x03de0084, 0x03de4085, 0x03e04084,
  3016. 0x03e4c084, 0x03e74084, 0x03e88084, 0x03e9c084,
  3017. 0x03eb0084, 0x03ee4084, 0x04098084, 0x043f0081,
  3018. 0x06c18484, 0x06c48084, 0x06cec184, 0x06d00120,
  3019. 0x06d0c084, 0x074b0383, 0x074cc41f, 0x074f1783,
  3020. 0x075e0081, 0x0766d283, 0x07801d44, 0x078e8942,
  3021. 0x07931844, 0x079f0d42, 0x07a58216, 0x07a68085,
  3022. 0x07a6c0be, 0x07a80d44, 0x07aea044, 0x07c00122,
  3023. 0x07c08344, 0x07c20122, 0x07c28344, 0x07c40122,
  3024. 0x07c48244, 0x07c60122, 0x07c68244, 0x07c8113e,
  3025. 0x07d08244, 0x07d20122, 0x07d28244, 0x07d40122,
  3026. 0x07d48344, 0x07d64c3e, 0x07dc4080, 0x07dc80be,
  3027. 0x07dcc080, 0x07dd00be, 0x07dd4080, 0x07dd80be,
  3028. 0x07ddc080, 0x07de00be, 0x07de4080, 0x07de80be,
  3029. 0x07dec080, 0x07df00be, 0x07df4080, 0x07e00820,
  3030. 0x07e40820, 0x07e80820, 0x07ec05be, 0x07eec080,
  3031. 0x07ef00be, 0x07ef4097, 0x07ef8080, 0x07efc117,
  3032. 0x07f0443e, 0x07f24080, 0x07f280be, 0x07f2c080,
  3033. 0x07f303be, 0x07f4c080, 0x07f582ae, 0x07f6c080,
  3034. 0x07f7433e, 0x07f8c080, 0x07f903ae, 0x07fac080,
  3035. 0x07fb013e, 0x07fb8102, 0x07fc83be, 0x07fe4080,
  3036. 0x07fe80be, 0x07fec080, 0x07ff00be, 0x07ff4080,
  3037. 0x07ff8097, 0x0800011e, 0x08008495, 0x08044081,
  3038. 0x0805c097, 0x08090081, 0x08094097, 0x08098099,
  3039. 0x080bc081, 0x080cc085, 0x080d00b1, 0x080d8085,
  3040. 0x080dc0b1, 0x080f0197, 0x0811c197, 0x0815c0b3,
  3041. 0x0817c081, 0x081c0595, 0x081ec081, 0x081f0215,
  3042. 0x0820051f, 0x08228583, 0x08254415, 0x082a0097,
  3043. 0x08400119, 0x08408081, 0x0840c0bf, 0x08414119,
  3044. 0x0841c081, 0x084240bf, 0x0842852d, 0x08454081,
  3045. 0x08458097, 0x08464295, 0x08480097, 0x08484099,
  3046. 0x08488097, 0x08490081, 0x08498080, 0x084a0081,
  3047. 0x084a8102, 0x084b0495, 0x084d421f, 0x084e4081,
  3048. 0x084ec099, 0x084f0283, 0x08514295, 0x08540119,
  3049. 0x0854809b, 0x0854c619, 0x0857c097, 0x08580081,
  3050. 0x08584097, 0x08588099, 0x0858c097, 0x08590081,
  3051. 0x08594097, 0x08598099, 0x0859c09b, 0x085a0097,
  3052. 0x085a4081, 0x085a8097, 0x085ac099, 0x085b0295,
  3053. 0x085c4097, 0x085c8099, 0x085cc097, 0x085d0081,
  3054. 0x085d4097, 0x085d8099, 0x085dc09b, 0x085e0097,
  3055. 0x085e4081, 0x085e8097, 0x085ec099, 0x085f0215,
  3056. 0x08624099, 0x0866813e, 0x086b80be, 0x087341be,
  3057. 0x088100be, 0x088240be, 0x088300be, 0x088901be,
  3058. 0x088b0085, 0x088b40b1, 0x088bc085, 0x088c00b1,
  3059. 0x089040be, 0x089100be, 0x0891c1be, 0x089801be,
  3060. 0x089b42be, 0x089d0144, 0x089e0144, 0x08a00144,
  3061. 0x08a10144, 0x08a20144, 0x08ab023e, 0x08b80244,
  3062. 0x08ba8220, 0x08ca411e, 0x0918049f, 0x091a4523,
  3063. 0x091cc097, 0x091d04a5, 0x091f452b, 0x0921c09b,
  3064. 0x092204a1, 0x09244525, 0x0926c099, 0x09270d25,
  3065. 0x092d8d1f, 0x09340d1f, 0x093a8081, 0x0a8300b3,
  3066. 0x0a9d0099, 0x0a9d4097, 0x0a9d8099, 0x0ab700be,
  3067. 0x0b1f0115, 0x0b5bc081, 0x0ba7c081, 0x0bbcc081,
  3068. 0x0bc004ad, 0x0bc244ad, 0x0bc484ad, 0x0bc6f383,
  3069. 0x0be0852d, 0x0be31d03, 0x0bf1882d, 0x0c000081,
  3070. 0x0c0d8283, 0x0c130b84, 0x0c194284, 0x0c1c0122,
  3071. 0x0c1cc122, 0x0c1d8122, 0x0c1e4122, 0x0c1f0122,
  3072. 0x0c250084, 0x0c26c123, 0x0c278084, 0x0c27c085,
  3073. 0x0c2b0b84, 0x0c314284, 0x0c340122, 0x0c34c122,
  3074. 0x0c358122, 0x0c364122, 0x0c370122, 0x0c3d0084,
  3075. 0x0c3dc220, 0x0c3f8084, 0x0c3fc085, 0x0c4c4a2d,
  3076. 0x0c51451f, 0x0c53ca9f, 0x0c5915ad, 0x0c648703,
  3077. 0x0c800741, 0x0c838089, 0x0c83c129, 0x0c8441a9,
  3078. 0x0c850089, 0x0c854129, 0x0c85c2a9, 0x0c870089,
  3079. 0x0c87408f, 0x0c87808d, 0x0c881241, 0x0c910203,
  3080. 0x0c940099, 0x0c9444a3, 0x0c968323, 0x0c98072d,
  3081. 0x0c9b84af, 0x0c9dc2a1, 0x0c9f00b5, 0x0c9f40b3,
  3082. 0x0c9f8085, 0x0ca01883, 0x0cac4223, 0x0cad4523,
  3083. 0x0cafc097, 0x0cb004a1, 0x0cb241a5, 0x0cb30097,
  3084. 0x0cb34099, 0x0cb38097, 0x0cb3c099, 0x0cb417ad,
  3085. 0x0cbfc085, 0x0cc001b3, 0x0cc0c0b1, 0x0cc100b3,
  3086. 0x0cc14131, 0x0cc1c0b5, 0x0cc200b3, 0x0cc241b1,
  3087. 0x0cc30133, 0x0cc38131, 0x0cc40085, 0x0cc440b1,
  3088. 0x0cc48133, 0x0cc50085, 0x0cc540b5, 0x0cc580b7,
  3089. 0x0cc5c0b5, 0x0cc600b1, 0x0cc64135, 0x0cc6c0b3,
  3090. 0x0cc701b1, 0x0cc7c0b3, 0x0cc800b5, 0x0cc840b3,
  3091. 0x0cc881b1, 0x0cc9422f, 0x0cca4131, 0x0ccac0b5,
  3092. 0x0ccb00b1, 0x0ccb40b3, 0x0ccb80b5, 0x0ccbc0b1,
  3093. 0x0ccc012f, 0x0ccc80b5, 0x0cccc0b3, 0x0ccd00b5,
  3094. 0x0ccd40b1, 0x0ccd80b5, 0x0ccdc085, 0x0cce02b1,
  3095. 0x0ccf40b3, 0x0ccf80b1, 0x0ccfc085, 0x0cd001b1,
  3096. 0x0cd0c0b3, 0x0cd101b1, 0x0cd1c0b5, 0x0cd200b3,
  3097. 0x0cd24085, 0x0cd280b5, 0x0cd2c085, 0x0cd30133,
  3098. 0x0cd381b1, 0x0cd440b3, 0x0cd48085, 0x0cd4c0b1,
  3099. 0x0cd500b3, 0x0cd54085, 0x0cd580b5, 0x0cd5c0b1,
  3100. 0x0cd60521, 0x0cd88525, 0x0cdb02a5, 0x0cdc4099,
  3101. 0x0cdc8117, 0x0cdd0099, 0x0cdd4197, 0x0cde0127,
  3102. 0x0cde8285, 0x0cdfc089, 0x0ce0043f, 0x0ce20099,
  3103. 0x0ce2409b, 0x0ce283bf, 0x0ce44219, 0x0ce54205,
  3104. 0x0ce6433f, 0x0ce7c131, 0x0ce84085, 0x0ce881b1,
  3105. 0x0ce94085, 0x0ce98107, 0x0cea0089, 0x0cea4097,
  3106. 0x0cea8219, 0x0ceb809d, 0x0cebc08d, 0x0cec083f,
  3107. 0x0cf00105, 0x0cf0809b, 0x0cf0c197, 0x0cf1809b,
  3108. 0x0cf1c099, 0x0cf20517, 0x0cf48099, 0x0cf4c117,
  3109. 0x0cf54119, 0x0cf5c097, 0x0cf6009b, 0x0cf64099,
  3110. 0x0cf68217, 0x0cf78119, 0x0cf804a1, 0x0cfa4525,
  3111. 0x0cfcc525, 0x0cff4125, 0x0cffc099, 0x29a70103,
  3112. 0x29dc0081, 0x29fc8195, 0x29fe0103, 0x2ad70203,
  3113. 0x2ada4081, 0x3e401482, 0x3e4a7f82, 0x3e6a3f82,
  3114. 0x3e8aa102, 0x3e9b0110, 0x3e9c2f82, 0x3eb3c590,
  3115. 0x3ec00197, 0x3ec0c119, 0x3ec1413f, 0x3ec4c2af,
  3116. 0x3ec74184, 0x3ec804ad, 0x3eca4081, 0x3eca8304,
  3117. 0x3ecc03a0, 0x3ece02a0, 0x3ecf8084, 0x3ed00120,
  3118. 0x3ed0c120, 0x3ed184ae, 0x3ed3c085, 0x3ed4312d,
  3119. 0x3ef4cbad, 0x3efa892f, 0x3eff022d, 0x3f002f2f,
  3120. 0x3f1782a5, 0x3f18c0b1, 0x3f1907af, 0x3f1cffaf,
  3121. 0x3f3c81a5, 0x3f3d64af, 0x3f542031, 0x3f649b31,
  3122. 0x3f7c0131, 0x3f7c83b3, 0x3f7e40b1, 0x3f7e80bd,
  3123. 0x3f7ec0bb, 0x3f7f00b3, 0x3f840503, 0x3f8c01ad,
  3124. 0x3f8cc315, 0x3f8e462d, 0x3f91cc03, 0x3f97c695,
  3125. 0x3f9c01af, 0x3f9d0085, 0x3f9d852f, 0x3fa03aad,
  3126. 0x3fbd442f, 0x3fc06f1f, 0x3fd7c11f, 0x3fd85fad,
  3127. 0x3fe80081, 0x3fe84f1f, 0x3ff0831f, 0x3ff2831f,
  3128. 0x3ff4831f, 0x3ff6819f, 0x3ff80783, 0x41724092,
  3129. 0x41790092, 0x41e04d83, 0x41e70f91, 0x44268192,
  3130. 0x442ac092, 0x444b8112, 0x44d2c112, 0x44e0c192,
  3131. 0x44e38092, 0x44e44092, 0x44f14212, 0x452ec212,
  3132. 0x456e8112, 0x464e0092, 0x58484412, 0x5b5a0192,
  3133. 0x73358d1f, 0x733c051f, 0x74578392, 0x746ec312,
  3134. 0x75000d1f, 0x75068d1f, 0x750d0d1f, 0x7513839f,
  3135. 0x7515891f, 0x751a0d1f, 0x75208d1f, 0x75271015,
  3136. 0x752f439f, 0x7531459f, 0x75340d1f, 0x753a8d1f,
  3137. 0x75410395, 0x7543441f, 0x7545839f, 0x75478d1f,
  3138. 0x754e0795, 0x7552839f, 0x75548d1f, 0x755b0d1f,
  3139. 0x75618d1f, 0x75680d1f, 0x756e8d1f, 0x75750d1f,
  3140. 0x757b8d1f, 0x75820d1f, 0x75888d1f, 0x758f0d1f,
  3141. 0x75958d1f, 0x759c0d1f, 0x75a28d1f, 0x75a90103,
  3142. 0x75aa089f, 0x75ae4081, 0x75ae839f, 0x75b04081,
  3143. 0x75b08c9f, 0x75b6c081, 0x75b7032d, 0x75b8889f,
  3144. 0x75bcc081, 0x75bd039f, 0x75bec081, 0x75bf0c9f,
  3145. 0x75c54081, 0x75c5832d, 0x75c7089f, 0x75cb4081,
  3146. 0x75cb839f, 0x75cd4081, 0x75cd8c9f, 0x75d3c081,
  3147. 0x75d4032d, 0x75d5889f, 0x75d9c081, 0x75da039f,
  3148. 0x75dbc081, 0x75dc0c9f, 0x75e24081, 0x75e2832d,
  3149. 0x75e4089f, 0x75e84081, 0x75e8839f, 0x75ea4081,
  3150. 0x75ea8c9f, 0x75f0c081, 0x75f1042d, 0x75f3851f,
  3151. 0x75f6051f, 0x75f8851f, 0x75fb051f, 0x75fd851f,
  3152. 0x780c049f, 0x780e419f, 0x780f059f, 0x7811c203,
  3153. 0x7812d0ad, 0x781b0103, 0x7b80022d, 0x7b814dad,
  3154. 0x7b884203, 0x7b89c081, 0x7b8a452d, 0x7b8d0403,
  3155. 0x7b908081, 0x7b91dc03, 0x7ba0052d, 0x7ba2c8ad,
  3156. 0x7ba84483, 0x7baac8ad, 0x7c400097, 0x7c404521,
  3157. 0x7c440d25, 0x7c4a8087, 0x7c4ac115, 0x7c4b4117,
  3158. 0x7c4c0d1f, 0x7c528217, 0x7c538099, 0x7c53c097,
  3159. 0x7c5a8197, 0x7c640097, 0x7c80012f, 0x7c808081,
  3160. 0x7c841603, 0x7c9004c1, 0x7c940103, 0x7efc051f,
  3161. 0xbe0001ac, 0xbe00d110, 0xbe0947ac, 0xbe0d3910,
  3162. 0xbe29872c, 0xbe2d022c, 0xbe2e3790, 0xbe49ff90,
  3163. 0xbe69bc10,
  3164. };
  3165. static const uint16_t unicode_decomp_table2[709] = {
  3166. 0x0020, 0x0000, 0x0061, 0x0002, 0x0004, 0x0006, 0x03bc, 0x0008,
  3167. 0x000a, 0x000c, 0x0015, 0x0095, 0x00a5, 0x00b9, 0x00c1, 0x00c3,
  3168. 0x00c7, 0x00cb, 0x00d1, 0x00d7, 0x00dd, 0x00e0, 0x00e6, 0x00f8,
  3169. 0x0108, 0x010a, 0x0073, 0x0110, 0x0112, 0x0114, 0x0120, 0x012c,
  3170. 0x0144, 0x014d, 0x0153, 0x0162, 0x0168, 0x016a, 0x0176, 0x0192,
  3171. 0x0194, 0x01a9, 0x01bb, 0x01c7, 0x01d1, 0x01d5, 0x02b9, 0x01d7,
  3172. 0x003b, 0x01d9, 0x01db, 0x00b7, 0x01e1, 0x01fc, 0x020c, 0x0218,
  3173. 0x021d, 0x0223, 0x0227, 0x03a3, 0x0233, 0x023f, 0x0242, 0x024b,
  3174. 0x024e, 0x0251, 0x025d, 0x0260, 0x0269, 0x026c, 0x026f, 0x0275,
  3175. 0x0278, 0x0281, 0x028a, 0x029c, 0x029f, 0x02a3, 0x02af, 0x02b9,
  3176. 0x02c5, 0x02c9, 0x02cd, 0x02d1, 0x02d5, 0x02e7, 0x02ed, 0x02f1,
  3177. 0x02f5, 0x02f9, 0x02fd, 0x0305, 0x0309, 0x030d, 0x0313, 0x0317,
  3178. 0x031b, 0x0323, 0x0327, 0x032b, 0x032f, 0x0335, 0x033d, 0x0341,
  3179. 0x0349, 0x034d, 0x0351, 0x0f0b, 0x0357, 0x035b, 0x035f, 0x0363,
  3180. 0x0367, 0x036b, 0x036f, 0x0373, 0x0379, 0x037d, 0x0381, 0x0385,
  3181. 0x0389, 0x038d, 0x0391, 0x0395, 0x0399, 0x039d, 0x03a1, 0x10dc,
  3182. 0x03a5, 0x03c9, 0x03cd, 0x03d9, 0x03dd, 0x03e1, 0x03ef, 0x03f1,
  3183. 0x043d, 0x044f, 0x0499, 0x04f0, 0x0502, 0x054a, 0x0564, 0x056c,
  3184. 0x0570, 0x0573, 0x059a, 0x05fa, 0x05fe, 0x0607, 0x060b, 0x0614,
  3185. 0x0618, 0x061e, 0x0622, 0x0628, 0x068e, 0x0694, 0x0698, 0x069e,
  3186. 0x06a2, 0x06ab, 0x03ac, 0x06f3, 0x03ad, 0x06f6, 0x03ae, 0x06f9,
  3187. 0x03af, 0x06fc, 0x03cc, 0x06ff, 0x03cd, 0x0702, 0x03ce, 0x0705,
  3188. 0x0709, 0x070d, 0x0711, 0x0386, 0x0732, 0x0735, 0x03b9, 0x0737,
  3189. 0x073b, 0x0388, 0x0753, 0x0389, 0x0756, 0x0390, 0x076b, 0x038a,
  3190. 0x0777, 0x03b0, 0x0789, 0x038e, 0x0799, 0x079f, 0x07a3, 0x038c,
  3191. 0x07b8, 0x038f, 0x07bb, 0x00b4, 0x07be, 0x07c0, 0x07c2, 0x2010,
  3192. 0x07cb, 0x002e, 0x07cd, 0x07cf, 0x0020, 0x07d2, 0x07d6, 0x07db,
  3193. 0x07df, 0x07e4, 0x07ea, 0x07f0, 0x0020, 0x07f6, 0x2212, 0x0801,
  3194. 0x0805, 0x0807, 0x081d, 0x0825, 0x0827, 0x0043, 0x082d, 0x0830,
  3195. 0x0190, 0x0836, 0x0839, 0x004e, 0x0845, 0x0847, 0x084c, 0x084e,
  3196. 0x0851, 0x005a, 0x03a9, 0x005a, 0x0853, 0x0857, 0x0860, 0x0069,
  3197. 0x0862, 0x0865, 0x086f, 0x0874, 0x087a, 0x087e, 0x08a2, 0x0049,
  3198. 0x08a4, 0x08a6, 0x08a9, 0x0056, 0x08ab, 0x08ad, 0x08b0, 0x08b4,
  3199. 0x0058, 0x08b6, 0x08b8, 0x08bb, 0x08c0, 0x08c2, 0x08c5, 0x0076,
  3200. 0x08c7, 0x08c9, 0x08cc, 0x08d0, 0x0078, 0x08d2, 0x08d4, 0x08d7,
  3201. 0x08db, 0x08de, 0x08e4, 0x08e7, 0x08f0, 0x08f3, 0x08f6, 0x08f9,
  3202. 0x0902, 0x0906, 0x090b, 0x090f, 0x0914, 0x0917, 0x091a, 0x0923,
  3203. 0x092c, 0x093b, 0x093e, 0x0941, 0x0944, 0x0947, 0x094a, 0x0956,
  3204. 0x095c, 0x0960, 0x0962, 0x0964, 0x0968, 0x096a, 0x0970, 0x0978,
  3205. 0x097c, 0x0980, 0x0986, 0x0989, 0x098f, 0x0991, 0x0030, 0x0993,
  3206. 0x0999, 0x099c, 0x099e, 0x09a1, 0x09a4, 0x2d61, 0x6bcd, 0x9f9f,
  3207. 0x09a6, 0x09b1, 0x09bc, 0x09c7, 0x0a95, 0x0aa1, 0x0b15, 0x0020,
  3208. 0x0b27, 0x0b31, 0x0b8d, 0x0ba1, 0x0ba5, 0x0ba9, 0x0bad, 0x0bb1,
  3209. 0x0bb5, 0x0bb9, 0x0bbd, 0x0bc1, 0x0bc5, 0x0c21, 0x0c35, 0x0c39,
  3210. 0x0c3d, 0x0c41, 0x0c45, 0x0c49, 0x0c4d, 0x0c51, 0x0c55, 0x0c59,
  3211. 0x0c6f, 0x0c71, 0x0c73, 0x0ca0, 0x0cbc, 0x0cdc, 0x0ce4, 0x0cec,
  3212. 0x0cf4, 0x0cfc, 0x0d04, 0x0d0c, 0x0d14, 0x0d22, 0x0d2e, 0x0d7a,
  3213. 0x0d82, 0x0d85, 0x0d89, 0x0d8d, 0x0d9d, 0x0db1, 0x0db5, 0x0dbc,
  3214. 0x0dc2, 0x0dc6, 0x0e28, 0x0e2c, 0x0e30, 0x0e32, 0x0e36, 0x0e3c,
  3215. 0x0e3e, 0x0e41, 0x0e43, 0x0e46, 0x0e77, 0x0e7b, 0x0e89, 0x0e8e,
  3216. 0x0e94, 0x0e9c, 0x0ea3, 0x0ea9, 0x0eb4, 0x0ebe, 0x0ec6, 0x0eca,
  3217. 0x0ecf, 0x0ed9, 0x0edd, 0x0ee4, 0x0eec, 0x0ef3, 0x0ef8, 0x0f04,
  3218. 0x0f0a, 0x0f15, 0x0f1b, 0x0f22, 0x0f28, 0x0f33, 0x0f3d, 0x0f45,
  3219. 0x0f4c, 0x0f51, 0x0f57, 0x0f5e, 0x0f63, 0x0f69, 0x0f70, 0x0f76,
  3220. 0x0f7d, 0x0f82, 0x0f89, 0x0f8d, 0x0f9e, 0x0fa4, 0x0fa9, 0x0fad,
  3221. 0x0fb8, 0x0fbe, 0x0fc9, 0x0fd0, 0x0fd6, 0x0fda, 0x0fe1, 0x0fe5,
  3222. 0x0fef, 0x0ffa, 0x1000, 0x1004, 0x1009, 0x100f, 0x1013, 0x101a,
  3223. 0x101f, 0x1023, 0x1029, 0x102f, 0x1032, 0x1036, 0x1039, 0x103f,
  3224. 0x1045, 0x1059, 0x1061, 0x1079, 0x107c, 0x1080, 0x1095, 0x10a1,
  3225. 0x10b1, 0x10c3, 0x10cb, 0x10cf, 0x10da, 0x10de, 0x10ea, 0x10f2,
  3226. 0x10f4, 0x1100, 0x1105, 0x1111, 0x1141, 0x1149, 0x114d, 0x1153,
  3227. 0x1157, 0x115a, 0x116e, 0x1171, 0x1175, 0x117b, 0x117d, 0x1181,
  3228. 0x1184, 0x118c, 0x1192, 0x1196, 0x119c, 0x11a2, 0x11a8, 0x11ab,
  3229. 0xa76f, 0x11af, 0x11b2, 0x11b6, 0x028d, 0x11be, 0x1210, 0x130e,
  3230. 0x140c, 0x1490, 0x1495, 0x1553, 0x156c, 0x1572, 0x1578, 0x157e,
  3231. 0x158a, 0x1596, 0x002b, 0x15a1, 0x15b9, 0x15bd, 0x15c1, 0x15c5,
  3232. 0x15c9, 0x15cd, 0x15e1, 0x15e5, 0x1649, 0x1662, 0x1688, 0x168e,
  3233. 0x174c, 0x1752, 0x1757, 0x1777, 0x1877, 0x187d, 0x1911, 0x19d3,
  3234. 0x1a77, 0x1a7f, 0x1a9d, 0x1aa2, 0x1ab6, 0x1ac0, 0x1ac6, 0x1ada,
  3235. 0x1adf, 0x1ae5, 0x1af3, 0x1b23, 0x1b30, 0x1b38, 0x1b3c, 0x1b52,
  3236. 0x1bc9, 0x1bdb, 0x1bdd, 0x1bdf, 0x3164, 0x1c20, 0x1c22, 0x1c24,
  3237. 0x1c26, 0x1c28, 0x1c2a, 0x1c48, 0x1c4d, 0x1c52, 0x1c88, 0x1cce,
  3238. 0x1cdc, 0x1ce1, 0x1cea, 0x1cf3, 0x1d01, 0x1d06, 0x1d0b, 0x1d1d,
  3239. 0x1d2f, 0x1d38, 0x1d3d, 0x1d61, 0x1d6f, 0x1d71, 0x1d73, 0x1d93,
  3240. 0x1dae, 0x1db0, 0x1db2, 0x1db4, 0x1db6, 0x1db8, 0x1dba, 0x1dbc,
  3241. 0x1ddc, 0x1dde, 0x1de0, 0x1de2, 0x1de4, 0x1deb, 0x1ded, 0x1def,
  3242. 0x1df1, 0x1e00, 0x1e02, 0x1e04, 0x1e06, 0x1e08, 0x1e0a, 0x1e0c,
  3243. 0x1e0e, 0x1e10, 0x1e12, 0x1e14, 0x1e16, 0x1e18, 0x1e1a, 0x1e1c,
  3244. 0x1e20, 0x03f4, 0x1e22, 0x2207, 0x1e24, 0x2202, 0x1e26, 0x1e2e,
  3245. 0x03f4, 0x1e30, 0x2207, 0x1e32, 0x2202, 0x1e34, 0x1e3c, 0x03f4,
  3246. 0x1e3e, 0x2207, 0x1e40, 0x2202, 0x1e42, 0x1e4a, 0x03f4, 0x1e4c,
  3247. 0x2207, 0x1e4e, 0x2202, 0x1e50, 0x1e58, 0x03f4, 0x1e5a, 0x2207,
  3248. 0x1e5c, 0x2202, 0x1e5e, 0x1e68, 0x1e6a, 0x1e6c, 0x1e6e, 0x1e70,
  3249. 0x1e72, 0x1e74, 0x1e76, 0x1e78, 0x1e80, 0x1ea3, 0x1ea7, 0x1ead,
  3250. 0x1eca, 0x062d, 0x1ed2, 0x1ede, 0x062c, 0x1eee, 0x1f5e, 0x1f6a,
  3251. 0x1f7d, 0x1f8f, 0x1fa2, 0x1fa4, 0x1fa8, 0x1fae, 0x1fb4, 0x1fb6,
  3252. 0x1fba, 0x1fbc, 0x1fc4, 0x1fc7, 0x1fc9, 0x1fcf, 0x1fd1, 0x30b5,
  3253. 0x1fd7, 0x202f, 0x2045, 0x2049, 0x204b, 0x2050, 0x209d, 0x20ae,
  3254. 0x21af, 0x21bf, 0x21c5, 0x22bf, 0x23dd,
  3255. };
  3256. static const uint8_t unicode_decomp_data[9451] = {
  3257. 0x20, 0x88, 0x20, 0x84, 0x32, 0x33, 0x20, 0x81,
  3258. 0x20, 0xa7, 0x31, 0x6f, 0x31, 0xd0, 0x34, 0x31,
  3259. 0xd0, 0x32, 0x33, 0xd0, 0x34, 0x41, 0x80, 0x41,
  3260. 0x81, 0x41, 0x82, 0x41, 0x83, 0x41, 0x88, 0x41,
  3261. 0x8a, 0x00, 0x00, 0x43, 0xa7, 0x45, 0x80, 0x45,
  3262. 0x81, 0x45, 0x82, 0x45, 0x88, 0x49, 0x80, 0x49,
  3263. 0x81, 0x49, 0x82, 0x49, 0x88, 0x00, 0x00, 0x4e,
  3264. 0x83, 0x4f, 0x80, 0x4f, 0x81, 0x4f, 0x82, 0x4f,
  3265. 0x83, 0x4f, 0x88, 0x00, 0x00, 0x00, 0x00, 0x55,
  3266. 0x80, 0x55, 0x81, 0x55, 0x82, 0x55, 0x88, 0x59,
  3267. 0x81, 0x00, 0x00, 0x00, 0x00, 0x61, 0x80, 0x61,
  3268. 0x81, 0x61, 0x82, 0x61, 0x83, 0x61, 0x88, 0x61,
  3269. 0x8a, 0x00, 0x00, 0x63, 0xa7, 0x65, 0x80, 0x65,
  3270. 0x81, 0x65, 0x82, 0x65, 0x88, 0x69, 0x80, 0x69,
  3271. 0x81, 0x69, 0x82, 0x69, 0x88, 0x00, 0x00, 0x6e,
  3272. 0x83, 0x6f, 0x80, 0x6f, 0x81, 0x6f, 0x82, 0x6f,
  3273. 0x83, 0x6f, 0x88, 0x00, 0x00, 0x00, 0x00, 0x75,
  3274. 0x80, 0x75, 0x81, 0x75, 0x82, 0x75, 0x88, 0x79,
  3275. 0x81, 0x00, 0x00, 0x79, 0x88, 0x41, 0x84, 0x41,
  3276. 0x86, 0x41, 0xa8, 0x43, 0x81, 0x43, 0x82, 0x43,
  3277. 0x87, 0x43, 0x8c, 0x44, 0x8c, 0x45, 0x84, 0x45,
  3278. 0x86, 0x45, 0x87, 0x45, 0xa8, 0x45, 0x8c, 0x47,
  3279. 0x82, 0x47, 0x86, 0x47, 0x87, 0x47, 0xa7, 0x48,
  3280. 0x82, 0x49, 0x83, 0x49, 0x84, 0x49, 0x86, 0x49,
  3281. 0xa8, 0x49, 0x87, 0x49, 0x4a, 0x69, 0x6a, 0x4a,
  3282. 0x82, 0x4b, 0xa7, 0x4c, 0x81, 0x4c, 0xa7, 0x4c,
  3283. 0x8c, 0x4c, 0x00, 0x00, 0x6b, 0x20, 0x6b, 0x4e,
  3284. 0x81, 0x4e, 0xa7, 0x4e, 0x8c, 0xbc, 0x02, 0x6e,
  3285. 0x4f, 0x84, 0x4f, 0x86, 0x4f, 0x8b, 0x52, 0x81,
  3286. 0x52, 0xa7, 0x52, 0x8c, 0x53, 0x81, 0x53, 0x82,
  3287. 0x53, 0xa7, 0x53, 0x8c, 0x54, 0xa7, 0x54, 0x8c,
  3288. 0x55, 0x83, 0x55, 0x84, 0x55, 0x86, 0x55, 0x8a,
  3289. 0x55, 0x8b, 0x55, 0xa8, 0x57, 0x82, 0x59, 0x82,
  3290. 0x59, 0x88, 0x5a, 0x81, 0x5a, 0x87, 0x5a, 0x8c,
  3291. 0x4f, 0x9b, 0x55, 0x9b, 0x44, 0x00, 0x7d, 0x01,
  3292. 0x44, 0x00, 0x7e, 0x01, 0x64, 0x00, 0x7e, 0x01,
  3293. 0x4c, 0x4a, 0x4c, 0x6a, 0x6c, 0x6a, 0x4e, 0x4a,
  3294. 0x4e, 0x6a, 0x6e, 0x6a, 0x41, 0x00, 0x8c, 0x49,
  3295. 0x00, 0x8c, 0x4f, 0x00, 0x8c, 0x55, 0x00, 0x8c,
  3296. 0xdc, 0x00, 0x84, 0xdc, 0x00, 0x81, 0xdc, 0x00,
  3297. 0x8c, 0xdc, 0x00, 0x80, 0xc4, 0x00, 0x84, 0x26,
  3298. 0x02, 0x84, 0xc6, 0x00, 0x84, 0x47, 0x8c, 0x4b,
  3299. 0x8c, 0x4f, 0xa8, 0xea, 0x01, 0x84, 0xeb, 0x01,
  3300. 0x84, 0xb7, 0x01, 0x8c, 0x92, 0x02, 0x8c, 0x6a,
  3301. 0x00, 0x8c, 0x44, 0x5a, 0x44, 0x7a, 0x64, 0x7a,
  3302. 0x47, 0x81, 0x4e, 0x00, 0x80, 0xc5, 0x00, 0x81,
  3303. 0xc6, 0x00, 0x81, 0xd8, 0x00, 0x81, 0x41, 0x8f,
  3304. 0x41, 0x91, 0x45, 0x8f, 0x45, 0x91, 0x49, 0x8f,
  3305. 0x49, 0x91, 0x4f, 0x8f, 0x4f, 0x91, 0x52, 0x8f,
  3306. 0x52, 0x91, 0x55, 0x8f, 0x55, 0x91, 0x53, 0xa6,
  3307. 0x54, 0xa6, 0x48, 0x8c, 0x41, 0x00, 0x87, 0x45,
  3308. 0x00, 0xa7, 0xd6, 0x00, 0x84, 0xd5, 0x00, 0x84,
  3309. 0x4f, 0x00, 0x87, 0x2e, 0x02, 0x84, 0x59, 0x00,
  3310. 0x84, 0x68, 0x00, 0x66, 0x02, 0x6a, 0x00, 0x72,
  3311. 0x00, 0x79, 0x02, 0x7b, 0x02, 0x81, 0x02, 0x77,
  3312. 0x00, 0x79, 0x00, 0x20, 0x86, 0x20, 0x87, 0x20,
  3313. 0x8a, 0x20, 0xa8, 0x20, 0x83, 0x20, 0x8b, 0x63,
  3314. 0x02, 0x6c, 0x00, 0x73, 0x00, 0x78, 0x00, 0x95,
  3315. 0x02, 0x80, 0x81, 0x00, 0x93, 0x88, 0x81, 0x20,
  3316. 0xc5, 0x20, 0x81, 0xa8, 0x00, 0x81, 0x91, 0x03,
  3317. 0x81, 0x95, 0x03, 0x81, 0x97, 0x03, 0x81, 0x99,
  3318. 0x03, 0x81, 0x00, 0x00, 0x00, 0x9f, 0x03, 0x81,
  3319. 0x00, 0x00, 0x00, 0xa5, 0x03, 0x81, 0xa9, 0x03,
  3320. 0x81, 0xca, 0x03, 0x81, 0x01, 0x03, 0x98, 0x07,
  3321. 0xa4, 0x07, 0xb0, 0x00, 0xb4, 0x00, 0xb6, 0x00,
  3322. 0xb8, 0x00, 0xca, 0x00, 0x01, 0x03, 0xb8, 0x07,
  3323. 0xc4, 0x07, 0xbe, 0x00, 0xc4, 0x00, 0xc8, 0x00,
  3324. 0xa5, 0x03, 0x0d, 0x13, 0x00, 0x01, 0x03, 0xd1,
  3325. 0x00, 0xd1, 0x07, 0xc6, 0x03, 0xc0, 0x03, 0xba,
  3326. 0x03, 0xc1, 0x03, 0xc2, 0x03, 0x00, 0x00, 0x98,
  3327. 0x03, 0xb5, 0x03, 0x15, 0x04, 0x80, 0x15, 0x04,
  3328. 0x88, 0x00, 0x00, 0x00, 0x13, 0x04, 0x81, 0x06,
  3329. 0x04, 0x88, 0x1a, 0x04, 0x81, 0x18, 0x04, 0x80,
  3330. 0x23, 0x04, 0x86, 0x18, 0x04, 0x86, 0x38, 0x04,
  3331. 0x86, 0x35, 0x04, 0x80, 0x35, 0x04, 0x88, 0x00,
  3332. 0x00, 0x00, 0x33, 0x04, 0x81, 0x56, 0x04, 0x88,
  3333. 0x3a, 0x04, 0x81, 0x38, 0x04, 0x80, 0x43, 0x04,
  3334. 0x86, 0x74, 0x04, 0x8f, 0x16, 0x04, 0x86, 0x10,
  3335. 0x04, 0x86, 0x10, 0x04, 0x88, 0x15, 0x04, 0x86,
  3336. 0xd8, 0x04, 0x88, 0x16, 0x04, 0x88, 0x17, 0x04,
  3337. 0x88, 0x18, 0x04, 0x84, 0x18, 0x04, 0x88, 0x1e,
  3338. 0x04, 0x88, 0xe8, 0x04, 0x88, 0x2d, 0x04, 0x88,
  3339. 0x23, 0x04, 0x84, 0x23, 0x04, 0x88, 0x23, 0x04,
  3340. 0x8b, 0x27, 0x04, 0x88, 0x2b, 0x04, 0x88, 0x65,
  3341. 0x05, 0x82, 0x05, 0x27, 0x06, 0x00, 0x2c, 0x00,
  3342. 0x2d, 0x21, 0x2d, 0x00, 0x2e, 0x23, 0x2d, 0x27,
  3343. 0x06, 0x00, 0x4d, 0x21, 0x4d, 0xa0, 0x4d, 0x23,
  3344. 0x4d, 0xd5, 0x06, 0x54, 0x06, 0x00, 0x00, 0x00,
  3345. 0x00, 0xc1, 0x06, 0x54, 0x06, 0xd2, 0x06, 0x54,
  3346. 0x06, 0x28, 0x09, 0x3c, 0x09, 0x30, 0x09, 0x3c,
  3347. 0x09, 0x33, 0x09, 0x3c, 0x09, 0x15, 0x09, 0x00,
  3348. 0x27, 0x01, 0x27, 0x02, 0x27, 0x07, 0x27, 0x0c,
  3349. 0x27, 0x0d, 0x27, 0x16, 0x27, 0x1a, 0x27, 0xbe,
  3350. 0x09, 0x09, 0x00, 0x09, 0x19, 0xa1, 0x09, 0xbc,
  3351. 0x09, 0xaf, 0x09, 0xbc, 0x09, 0x32, 0x0a, 0x3c,
  3352. 0x0a, 0x38, 0x0a, 0x3c, 0x0a, 0x16, 0x0a, 0x00,
  3353. 0x26, 0x01, 0x26, 0x06, 0x26, 0x2b, 0x0a, 0x3c,
  3354. 0x0a, 0x47, 0x0b, 0x56, 0x0b, 0x3e, 0x0b, 0x09,
  3355. 0x00, 0x09, 0x19, 0x21, 0x0b, 0x3c, 0x0b, 0x92,
  3356. 0x0b, 0xd7, 0x0b, 0xbe, 0x0b, 0x08, 0x00, 0x09,
  3357. 0x00, 0x08, 0x19, 0x46, 0x0c, 0x56, 0x0c, 0xbf,
  3358. 0x0c, 0xd5, 0x0c, 0xc6, 0x0c, 0xd5, 0x0c, 0xc2,
  3359. 0x0c, 0x04, 0x00, 0x08, 0x13, 0x3e, 0x0d, 0x08,
  3360. 0x00, 0x09, 0x00, 0x08, 0x19, 0xd9, 0x0d, 0xca,
  3361. 0x0d, 0xca, 0x0d, 0x0f, 0x05, 0x12, 0x00, 0x0f,
  3362. 0x15, 0x4d, 0x0e, 0x32, 0x0e, 0xcd, 0x0e, 0xb2,
  3363. 0x0e, 0x99, 0x0e, 0x12, 0x00, 0x12, 0x08, 0x42,
  3364. 0x0f, 0xb7, 0x0f, 0x4c, 0x0f, 0xb7, 0x0f, 0x51,
  3365. 0x0f, 0xb7, 0x0f, 0x56, 0x0f, 0xb7, 0x0f, 0x5b,
  3366. 0x0f, 0xb7, 0x0f, 0x40, 0x0f, 0xb5, 0x0f, 0x71,
  3367. 0x0f, 0x72, 0x0f, 0x71, 0x0f, 0x00, 0x03, 0x41,
  3368. 0x0f, 0xb2, 0x0f, 0x81, 0x0f, 0xb3, 0x0f, 0x80,
  3369. 0x0f, 0xb3, 0x0f, 0x81, 0x0f, 0x71, 0x0f, 0x80,
  3370. 0x0f, 0x92, 0x0f, 0xb7, 0x0f, 0x9c, 0x0f, 0xb7,
  3371. 0x0f, 0xa1, 0x0f, 0xb7, 0x0f, 0xa6, 0x0f, 0xb7,
  3372. 0x0f, 0xab, 0x0f, 0xb7, 0x0f, 0x90, 0x0f, 0xb5,
  3373. 0x0f, 0x25, 0x10, 0x2e, 0x10, 0x05, 0x1b, 0x35,
  3374. 0x1b, 0x00, 0x00, 0x00, 0x00, 0x07, 0x1b, 0x35,
  3375. 0x1b, 0x00, 0x00, 0x00, 0x00, 0x09, 0x1b, 0x35,
  3376. 0x1b, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x1b, 0x35,
  3377. 0x1b, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x1b, 0x35,
  3378. 0x1b, 0x11, 0x1b, 0x35, 0x1b, 0x3a, 0x1b, 0x35,
  3379. 0x1b, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x1b, 0x35,
  3380. 0x1b, 0x3e, 0x1b, 0x35, 0x1b, 0x42, 0x1b, 0x35,
  3381. 0x1b, 0x41, 0x00, 0xc6, 0x00, 0x42, 0x00, 0x00,
  3382. 0x00, 0x44, 0x00, 0x45, 0x00, 0x8e, 0x01, 0x47,
  3383. 0x00, 0x4f, 0x00, 0x22, 0x02, 0x50, 0x00, 0x52,
  3384. 0x00, 0x54, 0x00, 0x55, 0x00, 0x57, 0x00, 0x61,
  3385. 0x00, 0x50, 0x02, 0x51, 0x02, 0x02, 0x1d, 0x62,
  3386. 0x00, 0x64, 0x00, 0x65, 0x00, 0x59, 0x02, 0x5b,
  3387. 0x02, 0x5c, 0x02, 0x67, 0x00, 0x00, 0x00, 0x6b,
  3388. 0x00, 0x6d, 0x00, 0x4b, 0x01, 0x6f, 0x00, 0x54,
  3389. 0x02, 0x16, 0x1d, 0x17, 0x1d, 0x70, 0x00, 0x74,
  3390. 0x00, 0x75, 0x00, 0x1d, 0x1d, 0x6f, 0x02, 0x76,
  3391. 0x00, 0x25, 0x1d, 0xb2, 0x03, 0xb3, 0x03, 0xb4,
  3392. 0x03, 0xc6, 0x03, 0xc7, 0x03, 0x69, 0x00, 0x72,
  3393. 0x00, 0x75, 0x00, 0x76, 0x00, 0xb2, 0x03, 0xb3,
  3394. 0x03, 0xc1, 0x03, 0xc6, 0x03, 0xc7, 0x03, 0x52,
  3395. 0x02, 0x63, 0x00, 0x55, 0x02, 0xf0, 0x00, 0x5c,
  3396. 0x02, 0x66, 0x00, 0x5f, 0x02, 0x61, 0x02, 0x65,
  3397. 0x02, 0x68, 0x02, 0x69, 0x02, 0x6a, 0x02, 0x7b,
  3398. 0x1d, 0x9d, 0x02, 0x6d, 0x02, 0x85, 0x1d, 0x9f,
  3399. 0x02, 0x71, 0x02, 0x70, 0x02, 0x72, 0x02, 0x73,
  3400. 0x02, 0x74, 0x02, 0x75, 0x02, 0x78, 0x02, 0x82,
  3401. 0x02, 0x83, 0x02, 0xab, 0x01, 0x89, 0x02, 0x8a,
  3402. 0x02, 0x1c, 0x1d, 0x8b, 0x02, 0x8c, 0x02, 0x7a,
  3403. 0x00, 0x90, 0x02, 0x91, 0x02, 0x92, 0x02, 0xb8,
  3404. 0x03, 0x41, 0x00, 0xa5, 0x42, 0x00, 0x87, 0x42,
  3405. 0x00, 0xa3, 0x42, 0x00, 0xb1, 0xc7, 0x00, 0x81,
  3406. 0x44, 0x00, 0x87, 0x44, 0x00, 0xa3, 0x44, 0x00,
  3407. 0xb1, 0x44, 0x00, 0xa7, 0x44, 0x00, 0xad, 0x12,
  3408. 0x01, 0x80, 0x12, 0x01, 0x81, 0x45, 0x00, 0xad,
  3409. 0x45, 0x00, 0xb0, 0x28, 0x02, 0x86, 0x46, 0x00,
  3410. 0x87, 0x47, 0x00, 0x84, 0x48, 0x00, 0x87, 0x48,
  3411. 0x00, 0xa3, 0x48, 0x00, 0x88, 0x48, 0x00, 0xa7,
  3412. 0x48, 0x00, 0xae, 0x49, 0x00, 0xb0, 0xcf, 0x00,
  3413. 0x81, 0x4b, 0x00, 0x81, 0x4b, 0x00, 0xa3, 0x4b,
  3414. 0x00, 0xb1, 0x4c, 0x00, 0xa3, 0x36, 0x1e, 0x84,
  3415. 0x4c, 0xb1, 0x4c, 0xad, 0x4d, 0x81, 0x4d, 0x87,
  3416. 0x4d, 0xa3, 0x4e, 0x87, 0x4e, 0xa3, 0x4e, 0xb1,
  3417. 0x4e, 0xad, 0xd5, 0x00, 0x81, 0xd5, 0x00, 0x88,
  3418. 0x4c, 0x01, 0x80, 0x4c, 0x01, 0x81, 0x50, 0x00,
  3419. 0x81, 0x50, 0x00, 0x87, 0x52, 0x00, 0x87, 0x52,
  3420. 0x00, 0xa3, 0x5a, 0x1e, 0x84, 0x52, 0x00, 0xb1,
  3421. 0x53, 0x00, 0x87, 0x53, 0x00, 0xa3, 0x5a, 0x01,
  3422. 0x87, 0x60, 0x01, 0x87, 0x62, 0x1e, 0x87, 0x54,
  3423. 0x00, 0x87, 0x54, 0x00, 0xa3, 0x54, 0x00, 0xb1,
  3424. 0x54, 0x00, 0xad, 0x55, 0x00, 0xa4, 0x55, 0x00,
  3425. 0xb0, 0x55, 0x00, 0xad, 0x68, 0x01, 0x81, 0x6a,
  3426. 0x01, 0x88, 0x56, 0x83, 0x56, 0xa3, 0x57, 0x80,
  3427. 0x57, 0x81, 0x57, 0x88, 0x57, 0x87, 0x57, 0xa3,
  3428. 0x58, 0x87, 0x58, 0x88, 0x59, 0x87, 0x5a, 0x82,
  3429. 0x5a, 0xa3, 0x5a, 0xb1, 0x68, 0xb1, 0x74, 0x88,
  3430. 0x77, 0x8a, 0x79, 0x8a, 0x61, 0x00, 0xbe, 0x02,
  3431. 0x7f, 0x01, 0x87, 0x41, 0x00, 0xa3, 0x41, 0x00,
  3432. 0x89, 0xc2, 0x00, 0x81, 0xc2, 0x00, 0x80, 0xc2,
  3433. 0x00, 0x89, 0xc2, 0x00, 0x83, 0xa0, 0x1e, 0x82,
  3434. 0x02, 0x01, 0x81, 0x02, 0x01, 0x80, 0x02, 0x01,
  3435. 0x89, 0x02, 0x01, 0x83, 0xa0, 0x1e, 0x86, 0x45,
  3436. 0x00, 0xa3, 0x45, 0x00, 0x89, 0x45, 0x00, 0x83,
  3437. 0xca, 0x00, 0x81, 0xca, 0x00, 0x80, 0xca, 0x00,
  3438. 0x89, 0xca, 0x00, 0x83, 0xb8, 0x1e, 0x82, 0x49,
  3439. 0x00, 0x89, 0x49, 0x00, 0xa3, 0x4f, 0x00, 0xa3,
  3440. 0x4f, 0x00, 0x89, 0xd4, 0x00, 0x81, 0xd4, 0x00,
  3441. 0x80, 0xd4, 0x00, 0x89, 0xd4, 0x00, 0x83, 0xcc,
  3442. 0x1e, 0x82, 0xa0, 0x01, 0x81, 0xa0, 0x01, 0x80,
  3443. 0xa0, 0x01, 0x89, 0xa0, 0x01, 0x83, 0xa0, 0x01,
  3444. 0xa3, 0x55, 0x00, 0xa3, 0x55, 0x00, 0x89, 0xaf,
  3445. 0x01, 0x81, 0xaf, 0x01, 0x80, 0xaf, 0x01, 0x89,
  3446. 0xaf, 0x01, 0x83, 0xaf, 0x01, 0xa3, 0x59, 0x00,
  3447. 0x80, 0x59, 0x00, 0xa3, 0x59, 0x00, 0x89, 0x59,
  3448. 0x00, 0x83, 0xb1, 0x03, 0x13, 0x03, 0x00, 0x1f,
  3449. 0x80, 0x00, 0x1f, 0x81, 0x00, 0x1f, 0xc2, 0x91,
  3450. 0x03, 0x13, 0x03, 0x08, 0x1f, 0x80, 0x08, 0x1f,
  3451. 0x81, 0x08, 0x1f, 0xc2, 0xb5, 0x03, 0x13, 0x03,
  3452. 0x10, 0x1f, 0x80, 0x10, 0x1f, 0x81, 0x95, 0x03,
  3453. 0x13, 0x03, 0x18, 0x1f, 0x80, 0x18, 0x1f, 0x81,
  3454. 0xb7, 0x03, 0x93, 0xb7, 0x03, 0x94, 0x20, 0x1f,
  3455. 0x80, 0x21, 0x1f, 0x80, 0x20, 0x1f, 0x81, 0x21,
  3456. 0x1f, 0x81, 0x20, 0x1f, 0xc2, 0x21, 0x1f, 0xc2,
  3457. 0x97, 0x03, 0x93, 0x97, 0x03, 0x94, 0x28, 0x1f,
  3458. 0x80, 0x29, 0x1f, 0x80, 0x28, 0x1f, 0x81, 0x29,
  3459. 0x1f, 0x81, 0x28, 0x1f, 0xc2, 0x29, 0x1f, 0xc2,
  3460. 0xb9, 0x03, 0x93, 0xb9, 0x03, 0x94, 0x30, 0x1f,
  3461. 0x80, 0x31, 0x1f, 0x80, 0x30, 0x1f, 0x81, 0x31,
  3462. 0x1f, 0x81, 0x30, 0x1f, 0xc2, 0x31, 0x1f, 0xc2,
  3463. 0x99, 0x03, 0x93, 0x99, 0x03, 0x94, 0x38, 0x1f,
  3464. 0x80, 0x39, 0x1f, 0x80, 0x38, 0x1f, 0x81, 0x39,
  3465. 0x1f, 0x81, 0x38, 0x1f, 0xc2, 0x39, 0x1f, 0xc2,
  3466. 0xbf, 0x03, 0x93, 0xbf, 0x03, 0x94, 0x40, 0x1f,
  3467. 0x80, 0x40, 0x1f, 0x81, 0x9f, 0x03, 0x13, 0x03,
  3468. 0x48, 0x1f, 0x80, 0x48, 0x1f, 0x81, 0xc5, 0x03,
  3469. 0x13, 0x03, 0x50, 0x1f, 0x80, 0x50, 0x1f, 0x81,
  3470. 0x50, 0x1f, 0xc2, 0xa5, 0x03, 0x94, 0x00, 0x00,
  3471. 0x00, 0x59, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x59,
  3472. 0x1f, 0x81, 0x00, 0x00, 0x00, 0x59, 0x1f, 0xc2,
  3473. 0xc9, 0x03, 0x93, 0xc9, 0x03, 0x94, 0x60, 0x1f,
  3474. 0x80, 0x61, 0x1f, 0x80, 0x60, 0x1f, 0x81, 0x61,
  3475. 0x1f, 0x81, 0x60, 0x1f, 0xc2, 0x61, 0x1f, 0xc2,
  3476. 0xa9, 0x03, 0x93, 0xa9, 0x03, 0x94, 0x68, 0x1f,
  3477. 0x80, 0x69, 0x1f, 0x80, 0x68, 0x1f, 0x81, 0x69,
  3478. 0x1f, 0x81, 0x68, 0x1f, 0xc2, 0x69, 0x1f, 0xc2,
  3479. 0xb1, 0x03, 0x80, 0xb5, 0x03, 0x80, 0xb7, 0x03,
  3480. 0x80, 0xb9, 0x03, 0x80, 0xbf, 0x03, 0x80, 0xc5,
  3481. 0x03, 0x80, 0xc9, 0x03, 0x80, 0x00, 0x1f, 0x45,
  3482. 0x03, 0x20, 0x1f, 0x45, 0x03, 0x60, 0x1f, 0x45,
  3483. 0x03, 0xb1, 0x03, 0x86, 0xb1, 0x03, 0x84, 0x70,
  3484. 0x1f, 0xc5, 0xb1, 0x03, 0xc5, 0xac, 0x03, 0xc5,
  3485. 0x00, 0x00, 0x00, 0xb1, 0x03, 0xc2, 0xb6, 0x1f,
  3486. 0xc5, 0x91, 0x03, 0x86, 0x91, 0x03, 0x84, 0x91,
  3487. 0x03, 0x80, 0x91, 0x03, 0xc5, 0x20, 0x93, 0x20,
  3488. 0x93, 0x20, 0xc2, 0xa8, 0x00, 0xc2, 0x74, 0x1f,
  3489. 0xc5, 0xb7, 0x03, 0xc5, 0xae, 0x03, 0xc5, 0x00,
  3490. 0x00, 0x00, 0xb7, 0x03, 0xc2, 0xc6, 0x1f, 0xc5,
  3491. 0x95, 0x03, 0x80, 0x97, 0x03, 0x80, 0x97, 0x03,
  3492. 0xc5, 0xbf, 0x1f, 0x80, 0xbf, 0x1f, 0x81, 0xbf,
  3493. 0x1f, 0xc2, 0xb9, 0x03, 0x86, 0xb9, 0x03, 0x84,
  3494. 0xca, 0x03, 0x80, 0x00, 0x03, 0xb9, 0x42, 0xca,
  3495. 0x42, 0x99, 0x06, 0x99, 0x04, 0x99, 0x00, 0xfe,
  3496. 0x1f, 0x80, 0xfe, 0x1f, 0x81, 0xfe, 0x1f, 0xc2,
  3497. 0xc5, 0x03, 0x86, 0xc5, 0x03, 0x84, 0xcb, 0x03,
  3498. 0x80, 0x00, 0x03, 0xc1, 0x13, 0xc1, 0x14, 0xc5,
  3499. 0x42, 0xcb, 0x42, 0xa5, 0x06, 0xa5, 0x04, 0xa5,
  3500. 0x00, 0xa1, 0x03, 0x94, 0xa8, 0x00, 0x80, 0x85,
  3501. 0x03, 0x60, 0x00, 0x7c, 0x1f, 0xc5, 0xc9, 0x03,
  3502. 0xc5, 0xce, 0x03, 0xc5, 0x00, 0x00, 0x00, 0xc9,
  3503. 0x03, 0xc2, 0xf6, 0x1f, 0xc5, 0x9f, 0x03, 0x80,
  3504. 0xa9, 0x03, 0x80, 0xa9, 0x03, 0xc5, 0x20, 0x94,
  3505. 0x02, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
  3506. 0x20, 0x20, 0x20, 0x20, 0xb3, 0x2e, 0x2e, 0x2e,
  3507. 0x2e, 0x2e, 0x32, 0x20, 0x32, 0x20, 0x32, 0x20,
  3508. 0x00, 0x00, 0x00, 0x35, 0x20, 0x35, 0x20, 0x35,
  3509. 0x20, 0x00, 0x00, 0x00, 0x21, 0x21, 0x00, 0x00,
  3510. 0x20, 0x85, 0x3f, 0x3f, 0x3f, 0x21, 0x21, 0x3f,
  3511. 0x32, 0x20, 0x00, 0x00, 0x00, 0x00, 0x30, 0x69,
  3512. 0x00, 0x00, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  3513. 0x2b, 0x3d, 0x28, 0x29, 0x6e, 0x30, 0x00, 0x2b,
  3514. 0x00, 0x12, 0x22, 0x3d, 0x00, 0x28, 0x00, 0x29,
  3515. 0x00, 0x00, 0x00, 0x61, 0x00, 0x65, 0x00, 0x6f,
  3516. 0x00, 0x78, 0x00, 0x59, 0x02, 0x68, 0x6b, 0x6c,
  3517. 0x6d, 0x6e, 0x70, 0x73, 0x74, 0x52, 0x73, 0x61,
  3518. 0x2f, 0x63, 0x61, 0x2f, 0x73, 0xb0, 0x00, 0x43,
  3519. 0x63, 0x2f, 0x6f, 0x63, 0x2f, 0x75, 0xb0, 0x00,
  3520. 0x46, 0x48, 0x00, 0x1f, 0x00, 0x00, 0x00, 0x20,
  3521. 0xdf, 0x01, 0x01, 0x04, 0x24, 0x4e, 0x6f, 0x50,
  3522. 0x51, 0x52, 0x52, 0x52, 0x53, 0x4d, 0x54, 0x45,
  3523. 0x4c, 0x54, 0x4d, 0x4b, 0x00, 0xc5, 0x00, 0x42,
  3524. 0x43, 0x00, 0x65, 0x45, 0x46, 0x00, 0x4d, 0x6f,
  3525. 0xd0, 0x05, 0x46, 0x41, 0x58, 0xc0, 0x03, 0xb3,
  3526. 0x03, 0x93, 0x03, 0xa0, 0x03, 0x11, 0x22, 0x44,
  3527. 0x64, 0x65, 0x69, 0x6a, 0x31, 0xd0, 0x37, 0x31,
  3528. 0xd0, 0x39, 0x31, 0xd0, 0x31, 0x30, 0x31, 0xd0,
  3529. 0x33, 0x32, 0xd0, 0x33, 0x31, 0xd0, 0x35, 0x32,
  3530. 0xd0, 0x35, 0x33, 0xd0, 0x35, 0x34, 0xd0, 0x35,
  3531. 0x31, 0xd0, 0x36, 0x35, 0xd0, 0x36, 0x31, 0xd0,
  3532. 0x38, 0x33, 0xd0, 0x38, 0x35, 0xd0, 0x38, 0x37,
  3533. 0xd0, 0x38, 0x31, 0xd0, 0x49, 0x49, 0x49, 0x49,
  3534. 0x49, 0x49, 0x56, 0x56, 0x49, 0x56, 0x49, 0x49,
  3535. 0x56, 0x49, 0x49, 0x49, 0x49, 0x58, 0x58, 0x49,
  3536. 0x58, 0x49, 0x49, 0x4c, 0x43, 0x44, 0x4d, 0x69,
  3537. 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x76, 0x76,
  3538. 0x69, 0x76, 0x69, 0x69, 0x76, 0x69, 0x69, 0x69,
  3539. 0x69, 0x78, 0x78, 0x69, 0x78, 0x69, 0x69, 0x6c,
  3540. 0x63, 0x64, 0x6d, 0x30, 0xd0, 0x33, 0x90, 0x21,
  3541. 0xb8, 0x92, 0x21, 0xb8, 0x94, 0x21, 0xb8, 0xd0,
  3542. 0x21, 0xb8, 0xd4, 0x21, 0xb8, 0xd2, 0x21, 0xb8,
  3543. 0x03, 0x22, 0xb8, 0x08, 0x22, 0xb8, 0x0b, 0x22,
  3544. 0xb8, 0x23, 0x22, 0xb8, 0x00, 0x00, 0x00, 0x25,
  3545. 0x22, 0xb8, 0x2b, 0x22, 0x2b, 0x22, 0x2b, 0x22,
  3546. 0x00, 0x00, 0x00, 0x2e, 0x22, 0x2e, 0x22, 0x2e,
  3547. 0x22, 0x00, 0x00, 0x00, 0x3c, 0x22, 0xb8, 0x43,
  3548. 0x22, 0xb8, 0x45, 0x22, 0xb8, 0x00, 0x00, 0x00,
  3549. 0x48, 0x22, 0xb8, 0x3d, 0x00, 0xb8, 0x00, 0x00,
  3550. 0x00, 0x61, 0x22, 0xb8, 0x4d, 0x22, 0xb8, 0x3c,
  3551. 0x00, 0xb8, 0x3e, 0x00, 0xb8, 0x64, 0x22, 0xb8,
  3552. 0x65, 0x22, 0xb8, 0x72, 0x22, 0xb8, 0x76, 0x22,
  3553. 0xb8, 0x7a, 0x22, 0xb8, 0x82, 0x22, 0xb8, 0x86,
  3554. 0x22, 0xb8, 0xa2, 0x22, 0xb8, 0xa8, 0x22, 0xb8,
  3555. 0xa9, 0x22, 0xb8, 0xab, 0x22, 0xb8, 0x7c, 0x22,
  3556. 0xb8, 0x91, 0x22, 0xb8, 0xb2, 0x22, 0x38, 0x03,
  3557. 0x08, 0x30, 0x31, 0x00, 0x31, 0x00, 0x30, 0x00,
  3558. 0x32, 0x30, 0x28, 0x00, 0x31, 0x00, 0x29, 0x00,
  3559. 0x28, 0x00, 0x31, 0x00, 0x30, 0x00, 0x29, 0x00,
  3560. 0x28, 0x32, 0x30, 0x29, 0x31, 0x00, 0x2e, 0x00,
  3561. 0x31, 0x00, 0x30, 0x00, 0x2e, 0x00, 0x32, 0x30,
  3562. 0x2e, 0x28, 0x00, 0x61, 0x00, 0x29, 0x00, 0x41,
  3563. 0x00, 0x61, 0x00, 0x2b, 0x22, 0x00, 0x00, 0x00,
  3564. 0x00, 0x3a, 0x3a, 0x3d, 0x3d, 0x3d, 0x3d, 0x3d,
  3565. 0x3d, 0xdd, 0x2a, 0xb8, 0x6a, 0x56, 0x00, 0x4e,
  3566. 0x00, 0x28, 0x36, 0x3f, 0x59, 0x85, 0x8c, 0xa0,
  3567. 0xba, 0x3f, 0x51, 0x00, 0x26, 0x2c, 0x43, 0x57,
  3568. 0x6c, 0xa1, 0xb6, 0xc1, 0x9b, 0x52, 0x00, 0x5e,
  3569. 0x7a, 0x7f, 0x9d, 0xa6, 0xc1, 0xce, 0xe7, 0xb6,
  3570. 0x53, 0xc8, 0x53, 0xe3, 0x53, 0xd7, 0x56, 0x1f,
  3571. 0x57, 0xeb, 0x58, 0x02, 0x59, 0x0a, 0x59, 0x15,
  3572. 0x59, 0x27, 0x59, 0x73, 0x59, 0x50, 0x5b, 0x80,
  3573. 0x5b, 0xf8, 0x5b, 0x0f, 0x5c, 0x22, 0x5c, 0x38,
  3574. 0x5c, 0x6e, 0x5c, 0x71, 0x5c, 0xdb, 0x5d, 0xe5,
  3575. 0x5d, 0xf1, 0x5d, 0xfe, 0x5d, 0x72, 0x5e, 0x7a,
  3576. 0x5e, 0x7f, 0x5e, 0xf4, 0x5e, 0xfe, 0x5e, 0x0b,
  3577. 0x5f, 0x13, 0x5f, 0x50, 0x5f, 0x61, 0x5f, 0x73,
  3578. 0x5f, 0xc3, 0x5f, 0x08, 0x62, 0x36, 0x62, 0x4b,
  3579. 0x62, 0x2f, 0x65, 0x34, 0x65, 0x87, 0x65, 0x97,
  3580. 0x65, 0xa4, 0x65, 0xb9, 0x65, 0xe0, 0x65, 0xe5,
  3581. 0x65, 0xf0, 0x66, 0x08, 0x67, 0x28, 0x67, 0x20,
  3582. 0x6b, 0x62, 0x6b, 0x79, 0x6b, 0xb3, 0x6b, 0xcb,
  3583. 0x6b, 0xd4, 0x6b, 0xdb, 0x6b, 0x0f, 0x6c, 0x14,
  3584. 0x6c, 0x34, 0x6c, 0x6b, 0x70, 0x2a, 0x72, 0x36,
  3585. 0x72, 0x3b, 0x72, 0x3f, 0x72, 0x47, 0x72, 0x59,
  3586. 0x72, 0x5b, 0x72, 0xac, 0x72, 0x84, 0x73, 0x89,
  3587. 0x73, 0xdc, 0x74, 0xe6, 0x74, 0x18, 0x75, 0x1f,
  3588. 0x75, 0x28, 0x75, 0x30, 0x75, 0x8b, 0x75, 0x92,
  3589. 0x75, 0x76, 0x76, 0x7d, 0x76, 0xae, 0x76, 0xbf,
  3590. 0x76, 0xee, 0x76, 0xdb, 0x77, 0xe2, 0x77, 0xf3,
  3591. 0x77, 0x3a, 0x79, 0xb8, 0x79, 0xbe, 0x79, 0x74,
  3592. 0x7a, 0xcb, 0x7a, 0xf9, 0x7a, 0x73, 0x7c, 0xf8,
  3593. 0x7c, 0x36, 0x7f, 0x51, 0x7f, 0x8a, 0x7f, 0xbd,
  3594. 0x7f, 0x01, 0x80, 0x0c, 0x80, 0x12, 0x80, 0x33,
  3595. 0x80, 0x7f, 0x80, 0x89, 0x80, 0xe3, 0x81, 0x00,
  3596. 0x07, 0x10, 0x19, 0x29, 0x38, 0x3c, 0x8b, 0x8f,
  3597. 0x95, 0x4d, 0x86, 0x6b, 0x86, 0x40, 0x88, 0x4c,
  3598. 0x88, 0x63, 0x88, 0x7e, 0x89, 0x8b, 0x89, 0xd2,
  3599. 0x89, 0x00, 0x8a, 0x37, 0x8c, 0x46, 0x8c, 0x55,
  3600. 0x8c, 0x78, 0x8c, 0x9d, 0x8c, 0x64, 0x8d, 0x70,
  3601. 0x8d, 0xb3, 0x8d, 0xab, 0x8e, 0xca, 0x8e, 0x9b,
  3602. 0x8f, 0xb0, 0x8f, 0xb5, 0x8f, 0x91, 0x90, 0x49,
  3603. 0x91, 0xc6, 0x91, 0xcc, 0x91, 0xd1, 0x91, 0x77,
  3604. 0x95, 0x80, 0x95, 0x1c, 0x96, 0xb6, 0x96, 0xb9,
  3605. 0x96, 0xe8, 0x96, 0x51, 0x97, 0x5e, 0x97, 0x62,
  3606. 0x97, 0x69, 0x97, 0xcb, 0x97, 0xed, 0x97, 0xf3,
  3607. 0x97, 0x01, 0x98, 0xa8, 0x98, 0xdb, 0x98, 0xdf,
  3608. 0x98, 0x96, 0x99, 0x99, 0x99, 0xac, 0x99, 0xa8,
  3609. 0x9a, 0xd8, 0x9a, 0xdf, 0x9a, 0x25, 0x9b, 0x2f,
  3610. 0x9b, 0x32, 0x9b, 0x3c, 0x9b, 0x5a, 0x9b, 0xe5,
  3611. 0x9c, 0x75, 0x9e, 0x7f, 0x9e, 0xa5, 0x9e, 0x00,
  3612. 0x16, 0x1e, 0x28, 0x2c, 0x54, 0x58, 0x69, 0x6e,
  3613. 0x7b, 0x96, 0xa5, 0xad, 0xe8, 0xf7, 0xfb, 0x12,
  3614. 0x30, 0x00, 0x00, 0x41, 0x53, 0x44, 0x53, 0x45,
  3615. 0x53, 0x4b, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,
  3616. 0x00, 0x4d, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,
  3617. 0x00, 0x4f, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,
  3618. 0x00, 0x51, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,
  3619. 0x00, 0x53, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,
  3620. 0x00, 0x55, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,
  3621. 0x00, 0x57, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,
  3622. 0x00, 0x59, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,
  3623. 0x00, 0x5b, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,
  3624. 0x00, 0x5d, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,
  3625. 0x00, 0x5f, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,
  3626. 0x00, 0x61, 0x30, 0x99, 0x30, 0x64, 0x30, 0x99,
  3627. 0x30, 0x00, 0x00, 0x00, 0x00, 0x66, 0x30, 0x99,
  3628. 0x30, 0x00, 0x00, 0x00, 0x00, 0x68, 0x30, 0x99,
  3629. 0x30, 0x6f, 0x30, 0x99, 0x30, 0x72, 0x30, 0x99,
  3630. 0x30, 0x75, 0x30, 0x99, 0x30, 0x78, 0x30, 0x99,
  3631. 0x30, 0x7b, 0x30, 0x99, 0x30, 0x46, 0x30, 0x99,
  3632. 0x30, 0x20, 0x00, 0x99, 0x30, 0x9d, 0x30, 0x99,
  3633. 0x30, 0x88, 0x30, 0x8a, 0x30, 0xab, 0x30, 0x99,
  3634. 0x30, 0x00, 0x00, 0x00, 0x00, 0xad, 0x30, 0x99,
  3635. 0x30, 0x00, 0x00, 0x00, 0x00, 0xaf, 0x30, 0x99,
  3636. 0x30, 0x00, 0x00, 0x00, 0x00, 0xb1, 0x30, 0x99,
  3637. 0x30, 0x00, 0x00, 0x00, 0x00, 0xb3, 0x30, 0x99,
  3638. 0x30, 0x00, 0x00, 0x00, 0x00, 0xb5, 0x30, 0x99,
  3639. 0x30, 0x00, 0x00, 0x00, 0x00, 0xb7, 0x30, 0x99,
  3640. 0x30, 0x00, 0x00, 0x00, 0x00, 0xb9, 0x30, 0x99,
  3641. 0x30, 0x00, 0x00, 0x00, 0x00, 0xbb, 0x30, 0x99,
  3642. 0x30, 0x00, 0x00, 0x00, 0x00, 0xbd, 0x30, 0x99,
  3643. 0x30, 0x00, 0x00, 0x00, 0x00, 0xbf, 0x30, 0x99,
  3644. 0x30, 0x00, 0x00, 0x00, 0x00, 0xc1, 0x30, 0x99,
  3645. 0x30, 0xc4, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,
  3646. 0x00, 0xc6, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,
  3647. 0x00, 0xc8, 0x30, 0x99, 0x30, 0xcf, 0x30, 0x99,
  3648. 0x30, 0xd2, 0x30, 0x99, 0x30, 0xd5, 0x30, 0x99,
  3649. 0x30, 0xd8, 0x30, 0x99, 0x30, 0xdb, 0x30, 0x99,
  3650. 0x30, 0xa6, 0x30, 0x99, 0x30, 0xef, 0x30, 0x99,
  3651. 0x30, 0xfd, 0x30, 0x99, 0x30, 0xb3, 0x30, 0xc8,
  3652. 0x30, 0x00, 0x11, 0x00, 0x01, 0xaa, 0x02, 0xac,
  3653. 0xad, 0x03, 0x04, 0x05, 0xb0, 0xb1, 0xb2, 0xb3,
  3654. 0xb4, 0xb5, 0x1a, 0x06, 0x07, 0x08, 0x21, 0x09,
  3655. 0x11, 0x61, 0x11, 0x14, 0x11, 0x4c, 0x00, 0x01,
  3656. 0xb3, 0xb4, 0xb8, 0xba, 0xbf, 0xc3, 0xc5, 0x08,
  3657. 0xc9, 0xcb, 0x09, 0x0a, 0x0c, 0x0e, 0x0f, 0x13,
  3658. 0x15, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1e, 0x22,
  3659. 0x2c, 0x33, 0x38, 0xdd, 0xde, 0x43, 0x44, 0x45,
  3660. 0x70, 0x71, 0x74, 0x7d, 0x7e, 0x80, 0x8a, 0x8d,
  3661. 0x00, 0x4e, 0x8c, 0x4e, 0x09, 0x4e, 0xdb, 0x56,
  3662. 0x0a, 0x4e, 0x2d, 0x4e, 0x0b, 0x4e, 0x32, 0x75,
  3663. 0x59, 0x4e, 0x19, 0x4e, 0x01, 0x4e, 0x29, 0x59,
  3664. 0x30, 0x57, 0xba, 0x4e, 0x28, 0x00, 0x29, 0x00,
  3665. 0x00, 0x11, 0x02, 0x11, 0x03, 0x11, 0x05, 0x11,
  3666. 0x06, 0x11, 0x07, 0x11, 0x09, 0x11, 0x0b, 0x11,
  3667. 0x0c, 0x11, 0x0e, 0x11, 0x0f, 0x11, 0x10, 0x11,
  3668. 0x11, 0x11, 0x12, 0x11, 0x28, 0x00, 0x00, 0x11,
  3669. 0x61, 0x11, 0x29, 0x00, 0x28, 0x00, 0x02, 0x11,
  3670. 0x61, 0x11, 0x29, 0x00, 0x28, 0x00, 0x05, 0x11,
  3671. 0x61, 0x11, 0x29, 0x00, 0x28, 0x00, 0x09, 0x11,
  3672. 0x61, 0x11, 0x29, 0x00, 0x28, 0x00, 0x0b, 0x11,
  3673. 0x61, 0x11, 0x29, 0x00, 0x28, 0x00, 0x0e, 0x11,
  3674. 0x61, 0x11, 0x29, 0x00, 0x28, 0x00, 0x0c, 0x11,
  3675. 0x6e, 0x11, 0x29, 0x00, 0x28, 0x00, 0x0b, 0x11,
  3676. 0x69, 0x11, 0x0c, 0x11, 0x65, 0x11, 0xab, 0x11,
  3677. 0x29, 0x00, 0x28, 0x00, 0x0b, 0x11, 0x69, 0x11,
  3678. 0x12, 0x11, 0x6e, 0x11, 0x29, 0x00, 0x28, 0x00,
  3679. 0x29, 0x00, 0x00, 0x4e, 0x8c, 0x4e, 0x09, 0x4e,
  3680. 0xdb, 0x56, 0x94, 0x4e, 0x6d, 0x51, 0x03, 0x4e,
  3681. 0x6b, 0x51, 0x5d, 0x4e, 0x41, 0x53, 0x08, 0x67,
  3682. 0x6b, 0x70, 0x34, 0x6c, 0x28, 0x67, 0xd1, 0x91,
  3683. 0x1f, 0x57, 0xe5, 0x65, 0x2a, 0x68, 0x09, 0x67,
  3684. 0x3e, 0x79, 0x0d, 0x54, 0x79, 0x72, 0xa1, 0x8c,
  3685. 0x5d, 0x79, 0xb4, 0x52, 0xe3, 0x4e, 0x7c, 0x54,
  3686. 0x66, 0x5b, 0xe3, 0x76, 0x01, 0x4f, 0xc7, 0x8c,
  3687. 0x54, 0x53, 0x6d, 0x79, 0x11, 0x4f, 0xea, 0x81,
  3688. 0xf3, 0x81, 0x4f, 0x55, 0x7c, 0x5e, 0x87, 0x65,
  3689. 0x8f, 0x7b, 0x50, 0x54, 0x45, 0x32, 0x00, 0x31,
  3690. 0x00, 0x33, 0x00, 0x30, 0x00, 0x00, 0x11, 0x00,
  3691. 0x02, 0x03, 0x05, 0x06, 0x07, 0x09, 0x0b, 0x0c,
  3692. 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x00, 0x11, 0x00,
  3693. 0x61, 0x02, 0x61, 0x03, 0x61, 0x05, 0x61, 0x06,
  3694. 0x61, 0x07, 0x61, 0x09, 0x61, 0x0b, 0x61, 0x0c,
  3695. 0x61, 0x0e, 0x11, 0x61, 0x11, 0x00, 0x11, 0x0e,
  3696. 0x61, 0xb7, 0x00, 0x69, 0x0b, 0x11, 0x01, 0x63,
  3697. 0x00, 0x69, 0x0b, 0x11, 0x6e, 0x11, 0x00, 0x4e,
  3698. 0x8c, 0x4e, 0x09, 0x4e, 0xdb, 0x56, 0x94, 0x4e,
  3699. 0x6d, 0x51, 0x03, 0x4e, 0x6b, 0x51, 0x5d, 0x4e,
  3700. 0x41, 0x53, 0x08, 0x67, 0x6b, 0x70, 0x34, 0x6c,
  3701. 0x28, 0x67, 0xd1, 0x91, 0x1f, 0x57, 0xe5, 0x65,
  3702. 0x2a, 0x68, 0x09, 0x67, 0x3e, 0x79, 0x0d, 0x54,
  3703. 0x79, 0x72, 0xa1, 0x8c, 0x5d, 0x79, 0xb4, 0x52,
  3704. 0xd8, 0x79, 0x37, 0x75, 0x73, 0x59, 0x69, 0x90,
  3705. 0x2a, 0x51, 0x70, 0x53, 0xe8, 0x6c, 0x05, 0x98,
  3706. 0x11, 0x4f, 0x99, 0x51, 0x63, 0x6b, 0x0a, 0x4e,
  3707. 0x2d, 0x4e, 0x0b, 0x4e, 0xe6, 0x5d, 0xf3, 0x53,
  3708. 0x3b, 0x53, 0x97, 0x5b, 0x66, 0x5b, 0xe3, 0x76,
  3709. 0x01, 0x4f, 0xc7, 0x8c, 0x54, 0x53, 0x1c, 0x59,
  3710. 0x33, 0x00, 0x36, 0x00, 0x34, 0x00, 0x30, 0x00,
  3711. 0x35, 0x30, 0x31, 0x00, 0x08, 0x67, 0x31, 0x00,
  3712. 0x30, 0x00, 0x08, 0x67, 0x48, 0x67, 0x65, 0x72,
  3713. 0x67, 0x65, 0x56, 0x4c, 0x54, 0x44, 0xa2, 0x30,
  3714. 0x00, 0x02, 0x04, 0x06, 0x08, 0x09, 0x0b, 0x0d,
  3715. 0x0f, 0x11, 0x13, 0x15, 0x17, 0x19, 0x1b, 0x1d,
  3716. 0x1f, 0x22, 0x24, 0x26, 0x28, 0x29, 0x2a, 0x2b,
  3717. 0x2c, 0x2d, 0x30, 0x33, 0x36, 0x39, 0x3c, 0x3d,
  3718. 0x3e, 0x3f, 0x40, 0x42, 0x44, 0x46, 0x47, 0x48,
  3719. 0x49, 0x4a, 0x4b, 0x4d, 0x4e, 0x4f, 0x50, 0xe4,
  3720. 0x4e, 0x8c, 0x54, 0xa1, 0x30, 0x01, 0x30, 0x5b,
  3721. 0x27, 0x01, 0x4a, 0x34, 0x00, 0x01, 0x52, 0x39,
  3722. 0x01, 0xa2, 0x30, 0x00, 0x5a, 0x49, 0xa4, 0x30,
  3723. 0x00, 0x27, 0x4f, 0x0c, 0xa4, 0x30, 0x00, 0x4f,
  3724. 0x1d, 0x02, 0x05, 0x4f, 0xa8, 0x30, 0x00, 0x11,
  3725. 0x07, 0x54, 0x21, 0xa8, 0x30, 0x00, 0x54, 0x03,
  3726. 0x54, 0xa4, 0x30, 0x06, 0x4f, 0x15, 0x06, 0x58,
  3727. 0x3c, 0x07, 0x00, 0x46, 0xab, 0x30, 0x00, 0x3e,
  3728. 0x18, 0x1d, 0x00, 0x42, 0x3f, 0x51, 0xac, 0x30,
  3729. 0x00, 0x41, 0x47, 0x00, 0x47, 0x32, 0xae, 0x30,
  3730. 0xac, 0x30, 0xae, 0x30, 0x00, 0x1d, 0x4e, 0xad,
  3731. 0x30, 0x00, 0x38, 0x3d, 0x4f, 0x01, 0x3e, 0x13,
  3732. 0x4f, 0xad, 0x30, 0xed, 0x30, 0xad, 0x30, 0x00,
  3733. 0x40, 0x03, 0x3c, 0x33, 0xad, 0x30, 0x00, 0x40,
  3734. 0x34, 0x4f, 0x1b, 0x3e, 0xad, 0x30, 0x00, 0x40,
  3735. 0x42, 0x16, 0x1b, 0xb0, 0x30, 0x00, 0x39, 0x30,
  3736. 0xa4, 0x30, 0x0c, 0x45, 0x3c, 0x24, 0x4f, 0x0b,
  3737. 0x47, 0x18, 0x00, 0x49, 0xaf, 0x30, 0x00, 0x3e,
  3738. 0x4d, 0x1e, 0xb1, 0x30, 0x00, 0x4b, 0x08, 0x02,
  3739. 0x3a, 0x19, 0x02, 0x4b, 0x2c, 0xa4, 0x30, 0x11,
  3740. 0x00, 0x0b, 0x47, 0xb5, 0x30, 0x00, 0x3e, 0x0c,
  3741. 0x47, 0x2b, 0xb0, 0x30, 0x07, 0x3a, 0x43, 0x00,
  3742. 0xb9, 0x30, 0x02, 0x3a, 0x08, 0x02, 0x3a, 0x0f,
  3743. 0x07, 0x43, 0x00, 0xb7, 0x30, 0x10, 0x00, 0x12,
  3744. 0x34, 0x11, 0x3c, 0x13, 0x17, 0xa4, 0x30, 0x2a,
  3745. 0x1f, 0x24, 0x2b, 0x00, 0x20, 0xbb, 0x30, 0x16,
  3746. 0x41, 0x00, 0x38, 0x0d, 0xc4, 0x30, 0x0d, 0x38,
  3747. 0x00, 0xd0, 0x30, 0x00, 0x2c, 0x1c, 0x1b, 0xa2,
  3748. 0x30, 0x32, 0x00, 0x17, 0x26, 0x49, 0xaf, 0x30,
  3749. 0x25, 0x00, 0x3c, 0xb3, 0x30, 0x21, 0x00, 0x20,
  3750. 0x38, 0xa1, 0x30, 0x34, 0x00, 0x48, 0x22, 0x28,
  3751. 0xa3, 0x30, 0x32, 0x00, 0x59, 0x25, 0xa7, 0x30,
  3752. 0x2f, 0x1c, 0x10, 0x00, 0x44, 0xd5, 0x30, 0x00,
  3753. 0x14, 0x1e, 0xaf, 0x30, 0x29, 0x00, 0x10, 0x4d,
  3754. 0x3c, 0xda, 0x30, 0xbd, 0x30, 0xb8, 0x30, 0x22,
  3755. 0x13, 0x1a, 0x20, 0x33, 0x0c, 0x22, 0x3b, 0x01,
  3756. 0x22, 0x44, 0x00, 0x21, 0x44, 0x07, 0xa4, 0x30,
  3757. 0x39, 0x00, 0x4f, 0x24, 0xc8, 0x30, 0x14, 0x23,
  3758. 0x00, 0xdb, 0x30, 0xf3, 0x30, 0xc9, 0x30, 0x14,
  3759. 0x2a, 0x00, 0x12, 0x33, 0x22, 0x12, 0x33, 0x2a,
  3760. 0xa4, 0x30, 0x3a, 0x00, 0x0b, 0x49, 0xa4, 0x30,
  3761. 0x3a, 0x00, 0x47, 0x3a, 0x1f, 0x2b, 0x3a, 0x47,
  3762. 0x0b, 0xb7, 0x30, 0x27, 0x3c, 0x00, 0x30, 0x3c,
  3763. 0xaf, 0x30, 0x30, 0x00, 0x3e, 0x44, 0xdf, 0x30,
  3764. 0xea, 0x30, 0xd0, 0x30, 0x0f, 0x1a, 0x00, 0x2c,
  3765. 0x1b, 0xe1, 0x30, 0xac, 0x30, 0xac, 0x30, 0x35,
  3766. 0x00, 0x1c, 0x47, 0x35, 0x50, 0x1c, 0x3f, 0xa2,
  3767. 0x30, 0x42, 0x5a, 0x27, 0x42, 0x5a, 0x49, 0x44,
  3768. 0x00, 0x51, 0xc3, 0x30, 0x27, 0x00, 0x05, 0x28,
  3769. 0xea, 0x30, 0xe9, 0x30, 0xd4, 0x30, 0x17, 0x00,
  3770. 0x28, 0xd6, 0x30, 0x15, 0x26, 0x00, 0x15, 0xec,
  3771. 0x30, 0xe0, 0x30, 0xb2, 0x30, 0x3a, 0x41, 0x16,
  3772. 0x00, 0x41, 0xc3, 0x30, 0x2c, 0x00, 0x05, 0x30,
  3773. 0x00, 0xb9, 0x70, 0x31, 0x00, 0x30, 0x00, 0xb9,
  3774. 0x70, 0x32, 0x00, 0x30, 0x00, 0xb9, 0x70, 0x68,
  3775. 0x50, 0x61, 0x64, 0x61, 0x41, 0x55, 0x62, 0x61,
  3776. 0x72, 0x6f, 0x56, 0x70, 0x63, 0x64, 0x6d, 0x64,
  3777. 0x00, 0x6d, 0x00, 0xb2, 0x00, 0x49, 0x00, 0x55,
  3778. 0x00, 0x73, 0x5e, 0x10, 0x62, 0x2d, 0x66, 0x8c,
  3779. 0x54, 0x27, 0x59, 0x63, 0x6b, 0x0e, 0x66, 0xbb,
  3780. 0x6c, 0x2a, 0x68, 0x0f, 0x5f, 0x1a, 0x4f, 0x3e,
  3781. 0x79, 0x70, 0x00, 0x41, 0x6e, 0x00, 0x41, 0xbc,
  3782. 0x03, 0x41, 0x6d, 0x00, 0x41, 0x6b, 0x00, 0x41,
  3783. 0x4b, 0x00, 0x42, 0x4d, 0x00, 0x42, 0x47, 0x00,
  3784. 0x42, 0x63, 0x61, 0x6c, 0x6b, 0x63, 0x61, 0x6c,
  3785. 0x70, 0x00, 0x46, 0x6e, 0x00, 0x46, 0xbc, 0x03,
  3786. 0x46, 0xbc, 0x03, 0x67, 0x6d, 0x00, 0x67, 0x6b,
  3787. 0x00, 0x67, 0x48, 0x00, 0x7a, 0x6b, 0x48, 0x7a,
  3788. 0x4d, 0x48, 0x7a, 0x47, 0x48, 0x7a, 0x54, 0x48,
  3789. 0x7a, 0xbc, 0x03, 0x13, 0x21, 0x6d, 0x00, 0x13,
  3790. 0x21, 0x64, 0x00, 0x13, 0x21, 0x6b, 0x00, 0x13,
  3791. 0x21, 0x66, 0x00, 0x6d, 0x6e, 0x00, 0x6d, 0xbc,
  3792. 0x03, 0x6d, 0x6d, 0x00, 0x6d, 0x63, 0x00, 0x6d,
  3793. 0x6b, 0x00, 0x6d, 0x63, 0x00, 0x0a, 0x0a, 0x4f,
  3794. 0x00, 0x0a, 0x4f, 0x6d, 0x00, 0xb2, 0x00, 0x63,
  3795. 0x00, 0x08, 0x0a, 0x4f, 0x0a, 0x0a, 0x50, 0x00,
  3796. 0x0a, 0x50, 0x6d, 0x00, 0xb3, 0x00, 0x6b, 0x00,
  3797. 0x6d, 0x00, 0xb3, 0x00, 0x6d, 0x00, 0x15, 0x22,
  3798. 0x73, 0x00, 0x6d, 0x00, 0x15, 0x22, 0x73, 0x00,
  3799. 0xb2, 0x00, 0x50, 0x61, 0x6b, 0x50, 0x61, 0x4d,
  3800. 0x50, 0x61, 0x47, 0x50, 0x61, 0x72, 0x61, 0x64,
  3801. 0x72, 0x61, 0x64, 0xd1, 0x73, 0x72, 0x00, 0x61,
  3802. 0x00, 0x64, 0x00, 0x15, 0x22, 0x73, 0x00, 0xb2,
  3803. 0x00, 0x70, 0x00, 0x73, 0x6e, 0x00, 0x73, 0xbc,
  3804. 0x03, 0x73, 0x6d, 0x00, 0x73, 0x70, 0x00, 0x56,
  3805. 0x6e, 0x00, 0x56, 0xbc, 0x03, 0x56, 0x6d, 0x00,
  3806. 0x56, 0x6b, 0x00, 0x56, 0x4d, 0x00, 0x56, 0x70,
  3807. 0x00, 0x57, 0x6e, 0x00, 0x57, 0xbc, 0x03, 0x57,
  3808. 0x6d, 0x00, 0x57, 0x6b, 0x00, 0x57, 0x4d, 0x00,
  3809. 0x57, 0x6b, 0x00, 0xa9, 0x03, 0x4d, 0x00, 0xa9,
  3810. 0x03, 0x61, 0x2e, 0x6d, 0x2e, 0x42, 0x71, 0x63,
  3811. 0x63, 0x63, 0x64, 0x43, 0xd1, 0x6b, 0x67, 0x43,
  3812. 0x6f, 0x2e, 0x64, 0x42, 0x47, 0x79, 0x68, 0x61,
  3813. 0x48, 0x50, 0x69, 0x6e, 0x4b, 0x4b, 0x4b, 0x4d,
  3814. 0x6b, 0x74, 0x6c, 0x6d, 0x6c, 0x6e, 0x6c, 0x6f,
  3815. 0x67, 0x6c, 0x78, 0x6d, 0x62, 0x6d, 0x69, 0x6c,
  3816. 0x6d, 0x6f, 0x6c, 0x50, 0x48, 0x70, 0x2e, 0x6d,
  3817. 0x2e, 0x50, 0x50, 0x4d, 0x50, 0x52, 0x73, 0x72,
  3818. 0x53, 0x76, 0x57, 0x62, 0x56, 0xd1, 0x6d, 0x41,
  3819. 0xd1, 0x6d, 0x31, 0x00, 0xe5, 0x65, 0x31, 0x00,
  3820. 0x30, 0x00, 0xe5, 0x65, 0x32, 0x00, 0x30, 0x00,
  3821. 0xe5, 0x65, 0x33, 0x00, 0x30, 0x00, 0xe5, 0x65,
  3822. 0x67, 0x61, 0x6c, 0x4a, 0x04, 0x4c, 0x04, 0x43,
  3823. 0x46, 0x51, 0x26, 0x01, 0x53, 0x01, 0x27, 0xa7,
  3824. 0x37, 0xab, 0x6b, 0x02, 0x52, 0xab, 0x48, 0x8c,
  3825. 0xf4, 0x66, 0xca, 0x8e, 0xc8, 0x8c, 0xd1, 0x6e,
  3826. 0x32, 0x4e, 0xe5, 0x53, 0x9c, 0x9f, 0x9c, 0x9f,
  3827. 0x51, 0x59, 0xd1, 0x91, 0x87, 0x55, 0x48, 0x59,
  3828. 0xf6, 0x61, 0x69, 0x76, 0x85, 0x7f, 0x3f, 0x86,
  3829. 0xba, 0x87, 0xf8, 0x88, 0x8f, 0x90, 0x02, 0x6a,
  3830. 0x1b, 0x6d, 0xd9, 0x70, 0xde, 0x73, 0x3d, 0x84,
  3831. 0x6a, 0x91, 0xf1, 0x99, 0x82, 0x4e, 0x75, 0x53,
  3832. 0x04, 0x6b, 0x1b, 0x72, 0x2d, 0x86, 0x1e, 0x9e,
  3833. 0x50, 0x5d, 0xeb, 0x6f, 0xcd, 0x85, 0x64, 0x89,
  3834. 0xc9, 0x62, 0xd8, 0x81, 0x1f, 0x88, 0xca, 0x5e,
  3835. 0x17, 0x67, 0x6a, 0x6d, 0xfc, 0x72, 0xce, 0x90,
  3836. 0x86, 0x4f, 0xb7, 0x51, 0xde, 0x52, 0xc4, 0x64,
  3837. 0xd3, 0x6a, 0x10, 0x72, 0xe7, 0x76, 0x01, 0x80,
  3838. 0x06, 0x86, 0x5c, 0x86, 0xef, 0x8d, 0x32, 0x97,
  3839. 0x6f, 0x9b, 0xfa, 0x9d, 0x8c, 0x78, 0x7f, 0x79,
  3840. 0xa0, 0x7d, 0xc9, 0x83, 0x04, 0x93, 0x7f, 0x9e,
  3841. 0xd6, 0x8a, 0xdf, 0x58, 0x04, 0x5f, 0x60, 0x7c,
  3842. 0x7e, 0x80, 0x62, 0x72, 0xca, 0x78, 0xc2, 0x8c,
  3843. 0xf7, 0x96, 0xd8, 0x58, 0x62, 0x5c, 0x13, 0x6a,
  3844. 0xda, 0x6d, 0x0f, 0x6f, 0x2f, 0x7d, 0x37, 0x7e,
  3845. 0x4b, 0x96, 0xd2, 0x52, 0x8b, 0x80, 0xdc, 0x51,
  3846. 0xcc, 0x51, 0x1c, 0x7a, 0xbe, 0x7d, 0xf1, 0x83,
  3847. 0x75, 0x96, 0x80, 0x8b, 0xcf, 0x62, 0x02, 0x6a,
  3848. 0xfe, 0x8a, 0x39, 0x4e, 0xe7, 0x5b, 0x12, 0x60,
  3849. 0x87, 0x73, 0x70, 0x75, 0x17, 0x53, 0xfb, 0x78,
  3850. 0xbf, 0x4f, 0xa9, 0x5f, 0x0d, 0x4e, 0xcc, 0x6c,
  3851. 0x78, 0x65, 0x22, 0x7d, 0xc3, 0x53, 0x5e, 0x58,
  3852. 0x01, 0x77, 0x49, 0x84, 0xaa, 0x8a, 0xba, 0x6b,
  3853. 0xb0, 0x8f, 0x88, 0x6c, 0xfe, 0x62, 0xe5, 0x82,
  3854. 0xa0, 0x63, 0x65, 0x75, 0xae, 0x4e, 0x69, 0x51,
  3855. 0xc9, 0x51, 0x81, 0x68, 0xe7, 0x7c, 0x6f, 0x82,
  3856. 0xd2, 0x8a, 0xcf, 0x91, 0xf5, 0x52, 0x42, 0x54,
  3857. 0x73, 0x59, 0xec, 0x5e, 0xc5, 0x65, 0xfe, 0x6f,
  3858. 0x2a, 0x79, 0xad, 0x95, 0x6a, 0x9a, 0x97, 0x9e,
  3859. 0xce, 0x9e, 0x9b, 0x52, 0xc6, 0x66, 0x77, 0x6b,
  3860. 0x62, 0x8f, 0x74, 0x5e, 0x90, 0x61, 0x00, 0x62,
  3861. 0x9a, 0x64, 0x23, 0x6f, 0x49, 0x71, 0x89, 0x74,
  3862. 0xca, 0x79, 0xf4, 0x7d, 0x6f, 0x80, 0x26, 0x8f,
  3863. 0xee, 0x84, 0x23, 0x90, 0x4a, 0x93, 0x17, 0x52,
  3864. 0xa3, 0x52, 0xbd, 0x54, 0xc8, 0x70, 0xc2, 0x88,
  3865. 0xaa, 0x8a, 0xc9, 0x5e, 0xf5, 0x5f, 0x7b, 0x63,
  3866. 0xae, 0x6b, 0x3e, 0x7c, 0x75, 0x73, 0xe4, 0x4e,
  3867. 0xf9, 0x56, 0xe7, 0x5b, 0xba, 0x5d, 0x1c, 0x60,
  3868. 0xb2, 0x73, 0x69, 0x74, 0x9a, 0x7f, 0x46, 0x80,
  3869. 0x34, 0x92, 0xf6, 0x96, 0x48, 0x97, 0x18, 0x98,
  3870. 0x8b, 0x4f, 0xae, 0x79, 0xb4, 0x91, 0xb8, 0x96,
  3871. 0xe1, 0x60, 0x86, 0x4e, 0xda, 0x50, 0xee, 0x5b,
  3872. 0x3f, 0x5c, 0x99, 0x65, 0x02, 0x6a, 0xce, 0x71,
  3873. 0x42, 0x76, 0xfc, 0x84, 0x7c, 0x90, 0x8d, 0x9f,
  3874. 0x88, 0x66, 0x2e, 0x96, 0x89, 0x52, 0x7b, 0x67,
  3875. 0xf3, 0x67, 0x41, 0x6d, 0x9c, 0x6e, 0x09, 0x74,
  3876. 0x59, 0x75, 0x6b, 0x78, 0x10, 0x7d, 0x5e, 0x98,
  3877. 0x6d, 0x51, 0x2e, 0x62, 0x78, 0x96, 0x2b, 0x50,
  3878. 0x19, 0x5d, 0xea, 0x6d, 0x2a, 0x8f, 0x8b, 0x5f,
  3879. 0x44, 0x61, 0x17, 0x68, 0x87, 0x73, 0x86, 0x96,
  3880. 0x29, 0x52, 0x0f, 0x54, 0x65, 0x5c, 0x13, 0x66,
  3881. 0x4e, 0x67, 0xa8, 0x68, 0xe5, 0x6c, 0x06, 0x74,
  3882. 0xe2, 0x75, 0x79, 0x7f, 0xcf, 0x88, 0xe1, 0x88,
  3883. 0xcc, 0x91, 0xe2, 0x96, 0x3f, 0x53, 0xba, 0x6e,
  3884. 0x1d, 0x54, 0xd0, 0x71, 0x98, 0x74, 0xfa, 0x85,
  3885. 0xa3, 0x96, 0x57, 0x9c, 0x9f, 0x9e, 0x97, 0x67,
  3886. 0xcb, 0x6d, 0xe8, 0x81, 0xcb, 0x7a, 0x20, 0x7b,
  3887. 0x92, 0x7c, 0xc0, 0x72, 0x99, 0x70, 0x58, 0x8b,
  3888. 0xc0, 0x4e, 0x36, 0x83, 0x3a, 0x52, 0x07, 0x52,
  3889. 0xa6, 0x5e, 0xd3, 0x62, 0xd6, 0x7c, 0x85, 0x5b,
  3890. 0x1e, 0x6d, 0xb4, 0x66, 0x3b, 0x8f, 0x4c, 0x88,
  3891. 0x4d, 0x96, 0x8b, 0x89, 0xd3, 0x5e, 0x40, 0x51,
  3892. 0xc0, 0x55, 0x00, 0x00, 0x00, 0x00, 0x5a, 0x58,
  3893. 0x00, 0x00, 0x74, 0x66, 0x00, 0x00, 0x00, 0x00,
  3894. 0xde, 0x51, 0x2a, 0x73, 0xca, 0x76, 0x3c, 0x79,
  3895. 0x5e, 0x79, 0x65, 0x79, 0x8f, 0x79, 0x56, 0x97,
  3896. 0xbe, 0x7c, 0xbd, 0x7f, 0x00, 0x00, 0x12, 0x86,
  3897. 0x00, 0x00, 0xf8, 0x8a, 0x00, 0x00, 0x00, 0x00,
  3898. 0x38, 0x90, 0xfd, 0x90, 0xef, 0x98, 0xfc, 0x98,
  3899. 0x28, 0x99, 0xb4, 0x9d, 0xde, 0x90, 0xb7, 0x96,
  3900. 0xae, 0x4f, 0xe7, 0x50, 0x4d, 0x51, 0xc9, 0x52,
  3901. 0xe4, 0x52, 0x51, 0x53, 0x9d, 0x55, 0x06, 0x56,
  3902. 0x68, 0x56, 0x40, 0x58, 0xa8, 0x58, 0x64, 0x5c,
  3903. 0x6e, 0x5c, 0x94, 0x60, 0x68, 0x61, 0x8e, 0x61,
  3904. 0xf2, 0x61, 0x4f, 0x65, 0xe2, 0x65, 0x91, 0x66,
  3905. 0x85, 0x68, 0x77, 0x6d, 0x1a, 0x6e, 0x22, 0x6f,
  3906. 0x6e, 0x71, 0x2b, 0x72, 0x22, 0x74, 0x91, 0x78,
  3907. 0x3e, 0x79, 0x49, 0x79, 0x48, 0x79, 0x50, 0x79,
  3908. 0x56, 0x79, 0x5d, 0x79, 0x8d, 0x79, 0x8e, 0x79,
  3909. 0x40, 0x7a, 0x81, 0x7a, 0xc0, 0x7b, 0xf4, 0x7d,
  3910. 0x09, 0x7e, 0x41, 0x7e, 0x72, 0x7f, 0x05, 0x80,
  3911. 0xed, 0x81, 0x79, 0x82, 0x79, 0x82, 0x57, 0x84,
  3912. 0x10, 0x89, 0x96, 0x89, 0x01, 0x8b, 0x39, 0x8b,
  3913. 0xd3, 0x8c, 0x08, 0x8d, 0xb6, 0x8f, 0x38, 0x90,
  3914. 0xe3, 0x96, 0xff, 0x97, 0x3b, 0x98, 0x75, 0x60,
  3915. 0xee, 0x42, 0x18, 0x82, 0x02, 0x26, 0x4e, 0xb5,
  3916. 0x51, 0x68, 0x51, 0x80, 0x4f, 0x45, 0x51, 0x80,
  3917. 0x51, 0xc7, 0x52, 0xfa, 0x52, 0x9d, 0x55, 0x55,
  3918. 0x55, 0x99, 0x55, 0xe2, 0x55, 0x5a, 0x58, 0xb3,
  3919. 0x58, 0x44, 0x59, 0x54, 0x59, 0x62, 0x5a, 0x28,
  3920. 0x5b, 0xd2, 0x5e, 0xd9, 0x5e, 0x69, 0x5f, 0xad,
  3921. 0x5f, 0xd8, 0x60, 0x4e, 0x61, 0x08, 0x61, 0x8e,
  3922. 0x61, 0x60, 0x61, 0xf2, 0x61, 0x34, 0x62, 0xc4,
  3923. 0x63, 0x1c, 0x64, 0x52, 0x64, 0x56, 0x65, 0x74,
  3924. 0x66, 0x17, 0x67, 0x1b, 0x67, 0x56, 0x67, 0x79,
  3925. 0x6b, 0xba, 0x6b, 0x41, 0x6d, 0xdb, 0x6e, 0xcb,
  3926. 0x6e, 0x22, 0x6f, 0x1e, 0x70, 0x6e, 0x71, 0xa7,
  3927. 0x77, 0x35, 0x72, 0xaf, 0x72, 0x2a, 0x73, 0x71,
  3928. 0x74, 0x06, 0x75, 0x3b, 0x75, 0x1d, 0x76, 0x1f,
  3929. 0x76, 0xca, 0x76, 0xdb, 0x76, 0xf4, 0x76, 0x4a,
  3930. 0x77, 0x40, 0x77, 0xcc, 0x78, 0xb1, 0x7a, 0xc0,
  3931. 0x7b, 0x7b, 0x7c, 0x5b, 0x7d, 0xf4, 0x7d, 0x3e,
  3932. 0x7f, 0x05, 0x80, 0x52, 0x83, 0xef, 0x83, 0x79,
  3933. 0x87, 0x41, 0x89, 0x86, 0x89, 0x96, 0x89, 0xbf,
  3934. 0x8a, 0xf8, 0x8a, 0xcb, 0x8a, 0x01, 0x8b, 0xfe,
  3935. 0x8a, 0xed, 0x8a, 0x39, 0x8b, 0x8a, 0x8b, 0x08,
  3936. 0x8d, 0x38, 0x8f, 0x72, 0x90, 0x99, 0x91, 0x76,
  3937. 0x92, 0x7c, 0x96, 0xe3, 0x96, 0x56, 0x97, 0xdb,
  3938. 0x97, 0xff, 0x97, 0x0b, 0x98, 0x3b, 0x98, 0x12,
  3939. 0x9b, 0x9c, 0x9f, 0x4a, 0x28, 0x44, 0x28, 0xd5,
  3940. 0x33, 0x9d, 0x3b, 0x18, 0x40, 0x39, 0x40, 0x49,
  3941. 0x52, 0xd0, 0x5c, 0xd3, 0x7e, 0x43, 0x9f, 0x8e,
  3942. 0x9f, 0x2a, 0xa0, 0x02, 0x66, 0x66, 0x66, 0x69,
  3943. 0x66, 0x6c, 0x66, 0x66, 0x69, 0x66, 0x66, 0x6c,
  3944. 0x7f, 0x01, 0x74, 0x73, 0x00, 0x74, 0x65, 0x05,
  3945. 0x0f, 0x11, 0x0f, 0x00, 0x0f, 0x06, 0x19, 0x11,
  3946. 0x0f, 0x08, 0xd9, 0x05, 0xb4, 0x05, 0x00, 0x00,
  3947. 0x00, 0x00, 0xf2, 0x05, 0xb7, 0x05, 0xd0, 0x05,
  3948. 0x12, 0x00, 0x03, 0x04, 0x0b, 0x0c, 0x0d, 0x18,
  3949. 0x1a, 0xe9, 0x05, 0xc1, 0x05, 0xe9, 0x05, 0xc2,
  3950. 0x05, 0x49, 0xfb, 0xc1, 0x05, 0x49, 0xfb, 0xc2,
  3951. 0x05, 0xd0, 0x05, 0xb7, 0x05, 0xd0, 0x05, 0xb8,
  3952. 0x05, 0xd0, 0x05, 0xbc, 0x05, 0xd8, 0x05, 0xbc,
  3953. 0x05, 0xde, 0x05, 0xbc, 0x05, 0xe0, 0x05, 0xbc,
  3954. 0x05, 0xe3, 0x05, 0xbc, 0x05, 0xb9, 0x05, 0x2d,
  3955. 0x03, 0x2e, 0x03, 0x2f, 0x03, 0x30, 0x03, 0x31,
  3956. 0x03, 0x1c, 0x00, 0x18, 0x06, 0x22, 0x06, 0x2b,
  3957. 0x06, 0xd0, 0x05, 0xdc, 0x05, 0x71, 0x06, 0x00,
  3958. 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0d, 0x0d, 0x0d,
  3959. 0x0d, 0x0f, 0x0f, 0x0f, 0x0f, 0x09, 0x09, 0x09,
  3960. 0x09, 0x0e, 0x0e, 0x0e, 0x0e, 0x08, 0x08, 0x08,
  3961. 0x08, 0x33, 0x33, 0x33, 0x33, 0x35, 0x35, 0x35,
  3962. 0x35, 0x13, 0x13, 0x13, 0x13, 0x12, 0x12, 0x12,
  3963. 0x12, 0x15, 0x15, 0x15, 0x15, 0x16, 0x16, 0x16,
  3964. 0x16, 0x1c, 0x1c, 0x1b, 0x1b, 0x1d, 0x1d, 0x17,
  3965. 0x17, 0x27, 0x27, 0x20, 0x20, 0x38, 0x38, 0x38,
  3966. 0x38, 0x3e, 0x3e, 0x3e, 0x3e, 0x42, 0x42, 0x42,
  3967. 0x42, 0x40, 0x40, 0x40, 0x40, 0x49, 0x49, 0x4a,
  3968. 0x4a, 0x4a, 0x4a, 0x4f, 0x4f, 0x50, 0x50, 0x50,
  3969. 0x50, 0x4d, 0x4d, 0x4d, 0x4d, 0x61, 0x61, 0x62,
  3970. 0x62, 0x49, 0x06, 0x64, 0x64, 0x64, 0x64, 0x7e,
  3971. 0x7e, 0x7d, 0x7d, 0x7f, 0x7f, 0x2e, 0x82, 0x82,
  3972. 0x7c, 0x7c, 0x80, 0x80, 0x87, 0x87, 0x87, 0x87,
  3973. 0x00, 0x00, 0x26, 0x06, 0x00, 0x01, 0x00, 0x01,
  3974. 0x00, 0xaf, 0x00, 0xaf, 0x00, 0x22, 0x00, 0x22,
  3975. 0x00, 0xa1, 0x00, 0xa1, 0x00, 0xa0, 0x00, 0xa0,
  3976. 0x00, 0xa2, 0x00, 0xa2, 0x00, 0xaa, 0x00, 0xaa,
  3977. 0x00, 0xaa, 0x00, 0x23, 0x00, 0x23, 0x00, 0x23,
  3978. 0xcc, 0x06, 0x00, 0x00, 0x00, 0x00, 0x26, 0x06,
  3979. 0x00, 0x06, 0x00, 0x07, 0x00, 0x1f, 0x00, 0x23,
  3980. 0x00, 0x24, 0x02, 0x06, 0x02, 0x07, 0x02, 0x08,
  3981. 0x02, 0x1f, 0x02, 0x23, 0x02, 0x24, 0x04, 0x06,
  3982. 0x04, 0x07, 0x04, 0x08, 0x04, 0x1f, 0x04, 0x23,
  3983. 0x04, 0x24, 0x05, 0x06, 0x05, 0x1f, 0x05, 0x23,
  3984. 0x05, 0x24, 0x06, 0x07, 0x06, 0x1f, 0x07, 0x06,
  3985. 0x07, 0x1f, 0x08, 0x06, 0x08, 0x07, 0x08, 0x1f,
  3986. 0x0d, 0x06, 0x0d, 0x07, 0x0d, 0x08, 0x0d, 0x1f,
  3987. 0x0f, 0x07, 0x0f, 0x1f, 0x10, 0x06, 0x10, 0x07,
  3988. 0x10, 0x08, 0x10, 0x1f, 0x11, 0x07, 0x11, 0x1f,
  3989. 0x12, 0x1f, 0x13, 0x06, 0x13, 0x1f, 0x14, 0x06,
  3990. 0x14, 0x1f, 0x1b, 0x06, 0x1b, 0x07, 0x1b, 0x08,
  3991. 0x1b, 0x1f, 0x1b, 0x23, 0x1b, 0x24, 0x1c, 0x07,
  3992. 0x1c, 0x1f, 0x1c, 0x23, 0x1c, 0x24, 0x1d, 0x01,
  3993. 0x1d, 0x06, 0x1d, 0x07, 0x1d, 0x08, 0x1d, 0x1e,
  3994. 0x1d, 0x1f, 0x1d, 0x23, 0x1d, 0x24, 0x1e, 0x06,
  3995. 0x1e, 0x07, 0x1e, 0x08, 0x1e, 0x1f, 0x1e, 0x23,
  3996. 0x1e, 0x24, 0x1f, 0x06, 0x1f, 0x07, 0x1f, 0x08,
  3997. 0x1f, 0x1f, 0x1f, 0x23, 0x1f, 0x24, 0x20, 0x06,
  3998. 0x20, 0x07, 0x20, 0x08, 0x20, 0x1f, 0x20, 0x23,
  3999. 0x20, 0x24, 0x21, 0x06, 0x21, 0x1f, 0x21, 0x23,
  4000. 0x21, 0x24, 0x24, 0x06, 0x24, 0x07, 0x24, 0x08,
  4001. 0x24, 0x1f, 0x24, 0x23, 0x24, 0x24, 0x0a, 0x4a,
  4002. 0x0b, 0x4a, 0x23, 0x4a, 0x20, 0x00, 0x4c, 0x06,
  4003. 0x51, 0x06, 0x51, 0x06, 0xff, 0x00, 0x1f, 0x26,
  4004. 0x06, 0x00, 0x0b, 0x00, 0x0c, 0x00, 0x1f, 0x00,
  4005. 0x20, 0x00, 0x23, 0x00, 0x24, 0x02, 0x0b, 0x02,
  4006. 0x0c, 0x02, 0x1f, 0x02, 0x20, 0x02, 0x23, 0x02,
  4007. 0x24, 0x04, 0x0b, 0x04, 0x0c, 0x04, 0x1f, 0x26,
  4008. 0x06, 0x04, 0x20, 0x04, 0x23, 0x04, 0x24, 0x05,
  4009. 0x0b, 0x05, 0x0c, 0x05, 0x1f, 0x05, 0x20, 0x05,
  4010. 0x23, 0x05, 0x24, 0x1b, 0x23, 0x1b, 0x24, 0x1c,
  4011. 0x23, 0x1c, 0x24, 0x1d, 0x01, 0x1d, 0x1e, 0x1d,
  4012. 0x1f, 0x1d, 0x23, 0x1d, 0x24, 0x1e, 0x1f, 0x1e,
  4013. 0x23, 0x1e, 0x24, 0x1f, 0x01, 0x1f, 0x1f, 0x20,
  4014. 0x0b, 0x20, 0x0c, 0x20, 0x1f, 0x20, 0x20, 0x20,
  4015. 0x23, 0x20, 0x24, 0x23, 0x4a, 0x24, 0x0b, 0x24,
  4016. 0x0c, 0x24, 0x1f, 0x24, 0x20, 0x24, 0x23, 0x24,
  4017. 0x24, 0x00, 0x06, 0x00, 0x07, 0x00, 0x08, 0x00,
  4018. 0x1f, 0x00, 0x21, 0x02, 0x06, 0x02, 0x07, 0x02,
  4019. 0x08, 0x02, 0x1f, 0x02, 0x21, 0x04, 0x06, 0x04,
  4020. 0x07, 0x04, 0x08, 0x04, 0x1f, 0x04, 0x21, 0x05,
  4021. 0x1f, 0x06, 0x07, 0x06, 0x1f, 0x07, 0x06, 0x07,
  4022. 0x1f, 0x08, 0x06, 0x08, 0x1f, 0x0d, 0x06, 0x0d,
  4023. 0x07, 0x0d, 0x08, 0x0d, 0x1f, 0x0f, 0x07, 0x0f,
  4024. 0x08, 0x0f, 0x1f, 0x10, 0x06, 0x10, 0x07, 0x10,
  4025. 0x08, 0x10, 0x1f, 0x11, 0x07, 0x12, 0x1f, 0x13,
  4026. 0x06, 0x13, 0x1f, 0x14, 0x06, 0x14, 0x1f, 0x1b,
  4027. 0x06, 0x1b, 0x07, 0x1b, 0x08, 0x1b, 0x1f, 0x1c,
  4028. 0x07, 0x1c, 0x1f, 0x1d, 0x06, 0x1d, 0x07, 0x1d,
  4029. 0x08, 0x1d, 0x1e, 0x1d, 0x1f, 0x1e, 0x06, 0x1e,
  4030. 0x07, 0x1e, 0x08, 0x1e, 0x1f, 0x1e, 0x21, 0x1f,
  4031. 0x06, 0x1f, 0x07, 0x1f, 0x08, 0x1f, 0x1f, 0x20,
  4032. 0x06, 0x20, 0x07, 0x20, 0x08, 0x20, 0x1f, 0x20,
  4033. 0x21, 0x21, 0x06, 0x21, 0x1f, 0x21, 0x4a, 0x24,
  4034. 0x06, 0x24, 0x07, 0x24, 0x08, 0x24, 0x1f, 0x24,
  4035. 0x21, 0x00, 0x1f, 0x00, 0x21, 0x02, 0x1f, 0x02,
  4036. 0x21, 0x04, 0x1f, 0x04, 0x21, 0x05, 0x1f, 0x05,
  4037. 0x21, 0x0d, 0x1f, 0x0d, 0x21, 0x0e, 0x1f, 0x0e,
  4038. 0x21, 0x1d, 0x1e, 0x1d, 0x1f, 0x1e, 0x1f, 0x20,
  4039. 0x1f, 0x20, 0x21, 0x24, 0x1f, 0x24, 0x21, 0x40,
  4040. 0x06, 0x4e, 0x06, 0x51, 0x06, 0x27, 0x06, 0x10,
  4041. 0x22, 0x10, 0x23, 0x12, 0x22, 0x12, 0x23, 0x13,
  4042. 0x22, 0x13, 0x23, 0x0c, 0x22, 0x0c, 0x23, 0x0d,
  4043. 0x22, 0x0d, 0x23, 0x06, 0x22, 0x06, 0x23, 0x05,
  4044. 0x22, 0x05, 0x23, 0x07, 0x22, 0x07, 0x23, 0x0e,
  4045. 0x22, 0x0e, 0x23, 0x0f, 0x22, 0x0f, 0x23, 0x0d,
  4046. 0x05, 0x0d, 0x06, 0x0d, 0x07, 0x0d, 0x1e, 0x0d,
  4047. 0x0a, 0x0c, 0x0a, 0x0e, 0x0a, 0x0f, 0x0a, 0x10,
  4048. 0x22, 0x10, 0x23, 0x12, 0x22, 0x12, 0x23, 0x13,
  4049. 0x22, 0x13, 0x23, 0x0c, 0x22, 0x0c, 0x23, 0x0d,
  4050. 0x22, 0x0d, 0x23, 0x06, 0x22, 0x06, 0x23, 0x05,
  4051. 0x22, 0x05, 0x23, 0x07, 0x22, 0x07, 0x23, 0x0e,
  4052. 0x22, 0x0e, 0x23, 0x0f, 0x22, 0x0f, 0x23, 0x0d,
  4053. 0x05, 0x0d, 0x06, 0x0d, 0x07, 0x0d, 0x1e, 0x0d,
  4054. 0x0a, 0x0c, 0x0a, 0x0e, 0x0a, 0x0f, 0x0a, 0x0d,
  4055. 0x05, 0x0d, 0x06, 0x0d, 0x07, 0x0d, 0x1e, 0x0c,
  4056. 0x20, 0x0d, 0x20, 0x10, 0x1e, 0x0c, 0x05, 0x0c,
  4057. 0x06, 0x0c, 0x07, 0x0d, 0x05, 0x0d, 0x06, 0x0d,
  4058. 0x07, 0x10, 0x1e, 0x11, 0x1e, 0x00, 0x24, 0x00,
  4059. 0x24, 0x2a, 0x06, 0x00, 0x02, 0x1b, 0x00, 0x03,
  4060. 0x02, 0x00, 0x03, 0x02, 0x00, 0x03, 0x1b, 0x00,
  4061. 0x04, 0x1b, 0x00, 0x1b, 0x02, 0x00, 0x1b, 0x03,
  4062. 0x00, 0x1b, 0x04, 0x02, 0x1b, 0x03, 0x02, 0x1b,
  4063. 0x03, 0x03, 0x1b, 0x20, 0x03, 0x1b, 0x1f, 0x09,
  4064. 0x03, 0x02, 0x09, 0x02, 0x03, 0x09, 0x02, 0x1f,
  4065. 0x09, 0x1b, 0x03, 0x09, 0x1b, 0x03, 0x09, 0x1b,
  4066. 0x02, 0x09, 0x1b, 0x1b, 0x09, 0x1b, 0x1b, 0x0b,
  4067. 0x03, 0x03, 0x0b, 0x03, 0x03, 0x0b, 0x1b, 0x1b,
  4068. 0x0a, 0x03, 0x1b, 0x0a, 0x03, 0x1b, 0x0a, 0x02,
  4069. 0x20, 0x0a, 0x1b, 0x04, 0x0a, 0x1b, 0x04, 0x0a,
  4070. 0x1b, 0x1b, 0x0a, 0x1b, 0x1b, 0x0c, 0x03, 0x1f,
  4071. 0x0c, 0x04, 0x1b, 0x0c, 0x04, 0x1b, 0x0d, 0x1b,
  4072. 0x03, 0x0d, 0x1b, 0x03, 0x0d, 0x1b, 0x1b, 0x0d,
  4073. 0x1b, 0x20, 0x0f, 0x02, 0x1b, 0x0f, 0x1b, 0x1b,
  4074. 0x0f, 0x1b, 0x1b, 0x0f, 0x1b, 0x1f, 0x10, 0x1b,
  4075. 0x1b, 0x10, 0x1b, 0x20, 0x10, 0x1b, 0x1f, 0x17,
  4076. 0x04, 0x1b, 0x17, 0x04, 0x1b, 0x18, 0x1b, 0x03,
  4077. 0x18, 0x1b, 0x1b, 0x1a, 0x03, 0x1b, 0x1a, 0x03,
  4078. 0x20, 0x1a, 0x03, 0x1f, 0x1a, 0x02, 0x02, 0x1a,
  4079. 0x02, 0x02, 0x1a, 0x04, 0x1b, 0x1a, 0x04, 0x1b,
  4080. 0x1a, 0x1b, 0x03, 0x1a, 0x1b, 0x03, 0x1b, 0x03,
  4081. 0x02, 0x1b, 0x03, 0x1b, 0x1b, 0x03, 0x20, 0x1b,
  4082. 0x02, 0x03, 0x1b, 0x02, 0x1b, 0x1b, 0x04, 0x02,
  4083. 0x1b, 0x04, 0x1b, 0x28, 0x06, 0x1d, 0x04, 0x06,
  4084. 0x1f, 0x1d, 0x04, 0x1f, 0x1d, 0x1d, 0x1e, 0x05,
  4085. 0x1d, 0x1e, 0x05, 0x21, 0x1e, 0x04, 0x1d, 0x1e,
  4086. 0x04, 0x1d, 0x1e, 0x04, 0x21, 0x1e, 0x1d, 0x22,
  4087. 0x1e, 0x1d, 0x21, 0x22, 0x1d, 0x1d, 0x22, 0x1d,
  4088. 0x1d, 0x00, 0x06, 0x22, 0x02, 0x04, 0x22, 0x02,
  4089. 0x04, 0x21, 0x02, 0x06, 0x22, 0x02, 0x06, 0x21,
  4090. 0x02, 0x1d, 0x22, 0x02, 0x1d, 0x21, 0x04, 0x1d,
  4091. 0x22, 0x04, 0x05, 0x21, 0x04, 0x1d, 0x21, 0x0b,
  4092. 0x06, 0x21, 0x0d, 0x05, 0x22, 0x0c, 0x05, 0x22,
  4093. 0x0e, 0x05, 0x22, 0x1c, 0x04, 0x22, 0x1c, 0x1d,
  4094. 0x22, 0x22, 0x05, 0x22, 0x22, 0x04, 0x22, 0x22,
  4095. 0x1d, 0x22, 0x1d, 0x1d, 0x22, 0x1a, 0x1d, 0x22,
  4096. 0x1e, 0x05, 0x22, 0x1a, 0x1d, 0x05, 0x1c, 0x05,
  4097. 0x1d, 0x11, 0x1d, 0x22, 0x1b, 0x1d, 0x22, 0x1e,
  4098. 0x04, 0x05, 0x1d, 0x06, 0x22, 0x1c, 0x04, 0x1d,
  4099. 0x1b, 0x1d, 0x1d, 0x1c, 0x04, 0x1d, 0x1e, 0x04,
  4100. 0x05, 0x04, 0x05, 0x22, 0x05, 0x04, 0x22, 0x1d,
  4101. 0x04, 0x22, 0x19, 0x1d, 0x22, 0x00, 0x05, 0x22,
  4102. 0x1b, 0x1d, 0x1d, 0x11, 0x04, 0x1d, 0x0d, 0x1d,
  4103. 0x1d, 0x0b, 0x06, 0x22, 0x1e, 0x04, 0x22, 0x35,
  4104. 0x06, 0x00, 0x0f, 0x9d, 0x0d, 0x0f, 0x9d, 0x27,
  4105. 0x06, 0x00, 0x1d, 0x1d, 0x20, 0x00, 0x1c, 0x01,
  4106. 0x0a, 0x1e, 0x06, 0x1e, 0x08, 0x0e, 0x1d, 0x12,
  4107. 0x1e, 0x0a, 0x0c, 0x21, 0x1d, 0x12, 0x1d, 0x23,
  4108. 0x20, 0x21, 0x0c, 0x1d, 0x1e, 0x35, 0x06, 0x00,
  4109. 0x0f, 0x14, 0x27, 0x06, 0x0e, 0x1d, 0x22, 0xff,
  4110. 0x00, 0x1d, 0x1d, 0x20, 0xff, 0x12, 0x1d, 0x23,
  4111. 0x20, 0xff, 0x21, 0x0c, 0x1d, 0x1e, 0x27, 0x06,
  4112. 0x05, 0x1d, 0xff, 0x05, 0x1d, 0x00, 0x1d, 0x20,
  4113. 0x27, 0x06, 0x0a, 0xa5, 0x00, 0x1d, 0x2c, 0x00,
  4114. 0x01, 0x30, 0x02, 0x30, 0x3a, 0x00, 0x3b, 0x00,
  4115. 0x21, 0x00, 0x3f, 0x00, 0x16, 0x30, 0x17, 0x30,
  4116. 0x26, 0x20, 0x13, 0x20, 0x12, 0x01, 0x00, 0x5f,
  4117. 0x5f, 0x28, 0x29, 0x7b, 0x7d, 0x08, 0x30, 0x0c,
  4118. 0x0d, 0x08, 0x09, 0x02, 0x03, 0x00, 0x01, 0x04,
  4119. 0x05, 0x06, 0x07, 0x5b, 0x00, 0x5d, 0x00, 0x3e,
  4120. 0x20, 0x3e, 0x20, 0x3e, 0x20, 0x3e, 0x20, 0x5f,
  4121. 0x00, 0x5f, 0x00, 0x5f, 0x00, 0x2c, 0x00, 0x01,
  4122. 0x30, 0x2e, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x3a,
  4123. 0x00, 0x3f, 0x00, 0x21, 0x00, 0x14, 0x20, 0x28,
  4124. 0x00, 0x29, 0x00, 0x7b, 0x00, 0x7d, 0x00, 0x14,
  4125. 0x30, 0x15, 0x30, 0x23, 0x26, 0x2a, 0x2b, 0x2d,
  4126. 0x3c, 0x3e, 0x3d, 0x00, 0x5c, 0x24, 0x25, 0x40,
  4127. 0x40, 0x06, 0xff, 0x0b, 0x00, 0x0b, 0xff, 0x0c,
  4128. 0x20, 0x00, 0x4d, 0x06, 0x40, 0x06, 0xff, 0x0e,
  4129. 0x00, 0x0e, 0xff, 0x0f, 0x00, 0x0f, 0xff, 0x10,
  4130. 0x00, 0x10, 0xff, 0x11, 0x00, 0x11, 0xff, 0x12,
  4131. 0x00, 0x12, 0x21, 0x06, 0x00, 0x01, 0x01, 0x02,
  4132. 0x02, 0x03, 0x03, 0x04, 0x04, 0x05, 0x05, 0x05,
  4133. 0x05, 0x06, 0x06, 0x07, 0x07, 0x07, 0x07, 0x08,
  4134. 0x08, 0x09, 0x09, 0x09, 0x09, 0x0a, 0x0a, 0x0a,
  4135. 0x0a, 0x0b, 0x0b, 0x0b, 0x0b, 0x0c, 0x0c, 0x0c,
  4136. 0x0c, 0x0d, 0x0d, 0x0d, 0x0d, 0x0e, 0x0e, 0x0f,
  4137. 0x0f, 0x10, 0x10, 0x11, 0x11, 0x12, 0x12, 0x12,
  4138. 0x12, 0x13, 0x13, 0x13, 0x13, 0x14, 0x14, 0x14,
  4139. 0x14, 0x15, 0x15, 0x15, 0x15, 0x16, 0x16, 0x16,
  4140. 0x16, 0x17, 0x17, 0x17, 0x17, 0x18, 0x18, 0x18,
  4141. 0x18, 0x19, 0x19, 0x19, 0x19, 0x20, 0x20, 0x20,
  4142. 0x20, 0x21, 0x21, 0x21, 0x21, 0x22, 0x22, 0x22,
  4143. 0x22, 0x23, 0x23, 0x23, 0x23, 0x24, 0x24, 0x24,
  4144. 0x24, 0x25, 0x25, 0x25, 0x25, 0x26, 0x26, 0x26,
  4145. 0x26, 0x27, 0x27, 0x28, 0x28, 0x29, 0x29, 0x29,
  4146. 0x29, 0x22, 0x06, 0x22, 0x00, 0x22, 0x00, 0x22,
  4147. 0x01, 0x22, 0x01, 0x22, 0x03, 0x22, 0x03, 0x22,
  4148. 0x05, 0x22, 0x05, 0x21, 0x00, 0x85, 0x29, 0x01,
  4149. 0x30, 0x01, 0x0b, 0x0c, 0x00, 0xfa, 0xf1, 0xa0,
  4150. 0xa2, 0xa4, 0xa6, 0xa8, 0xe2, 0xe4, 0xe6, 0xc2,
  4151. 0xfb, 0xa1, 0xa3, 0xa5, 0xa7, 0xa9, 0xaa, 0xac,
  4152. 0xae, 0xb0, 0xb2, 0xb4, 0xb6, 0xb8, 0xba, 0xbc,
  4153. 0xbe, 0xc0, 0xc3, 0xc5, 0xc7, 0xc9, 0xca, 0xcb,
  4154. 0xcc, 0xcd, 0xce, 0xd1, 0xd4, 0xd7, 0xda, 0xdd,
  4155. 0xde, 0xdf, 0xe0, 0xe1, 0xe3, 0xe5, 0xe7, 0xe8,
  4156. 0xe9, 0xea, 0xeb, 0xec, 0xee, 0xf2, 0x98, 0x99,
  4157. 0x31, 0x31, 0x4f, 0x31, 0x55, 0x31, 0x5b, 0x31,
  4158. 0x61, 0x31, 0xa2, 0x00, 0xa3, 0x00, 0xac, 0x00,
  4159. 0xaf, 0x00, 0xa6, 0x00, 0xa5, 0x00, 0xa9, 0x20,
  4160. 0x00, 0x00, 0x02, 0x25, 0x90, 0x21, 0x91, 0x21,
  4161. 0x92, 0x21, 0x93, 0x21, 0xa0, 0x25, 0xcb, 0x25,
  4162. 0xd2, 0x05, 0x07, 0x03, 0x01, 0xda, 0x05, 0x07,
  4163. 0x03, 0x01, 0xd0, 0x02, 0xd1, 0x02, 0xe6, 0x00,
  4164. 0x99, 0x02, 0x53, 0x02, 0x00, 0x00, 0xa3, 0x02,
  4165. 0x66, 0xab, 0xa5, 0x02, 0xa4, 0x02, 0x56, 0x02,
  4166. 0x57, 0x02, 0x91, 0x1d, 0x58, 0x02, 0x5e, 0x02,
  4167. 0xa9, 0x02, 0x64, 0x02, 0x62, 0x02, 0x60, 0x02,
  4168. 0x9b, 0x02, 0x27, 0x01, 0x9c, 0x02, 0x67, 0x02,
  4169. 0x84, 0x02, 0xaa, 0x02, 0xab, 0x02, 0x6c, 0x02,
  4170. 0x04, 0xdf, 0x8e, 0xa7, 0x6e, 0x02, 0x05, 0xdf,
  4171. 0x8e, 0x02, 0x06, 0xdf, 0xf8, 0x00, 0x76, 0x02,
  4172. 0x77, 0x02, 0x71, 0x00, 0x7a, 0x02, 0x08, 0xdf,
  4173. 0x7d, 0x02, 0x7e, 0x02, 0x80, 0x02, 0xa8, 0x02,
  4174. 0xa6, 0x02, 0x67, 0xab, 0xa7, 0x02, 0x88, 0x02,
  4175. 0x71, 0x2c, 0x00, 0x00, 0x8f, 0x02, 0xa1, 0x02,
  4176. 0xa2, 0x02, 0x98, 0x02, 0xc0, 0x01, 0xc1, 0x01,
  4177. 0xc2, 0x01, 0x0a, 0xdf, 0x1e, 0xdf, 0x41, 0x04,
  4178. 0x40, 0x00, 0x00, 0x00, 0x00, 0x14, 0x99, 0x10,
  4179. 0xba, 0x10, 0x00, 0x00, 0x00, 0x00, 0x9b, 0x10,
  4180. 0xba, 0x10, 0x05, 0x05, 0xa5, 0x10, 0xba, 0x10,
  4181. 0x05, 0x31, 0x11, 0x27, 0x11, 0x32, 0x11, 0x27,
  4182. 0x11, 0x55, 0x47, 0x13, 0x3e, 0x13, 0x47, 0x13,
  4183. 0x57, 0x13, 0x55, 0x82, 0x13, 0xc9, 0x13, 0x00,
  4184. 0x00, 0x00, 0x00, 0x84, 0x13, 0xbb, 0x13, 0x05,
  4185. 0x05, 0x8b, 0x13, 0xc2, 0x13, 0x05, 0x90, 0x13,
  4186. 0xc9, 0x13, 0x05, 0xc2, 0x13, 0xc2, 0x13, 0x00,
  4187. 0x00, 0x00, 0x00, 0xc2, 0x13, 0xb8, 0x13, 0xc2,
  4188. 0x13, 0xc9, 0x13, 0x05, 0x55, 0xb9, 0x14, 0xba,
  4189. 0x14, 0xb9, 0x14, 0xb0, 0x14, 0x00, 0x00, 0x00,
  4190. 0x00, 0xb9, 0x14, 0xbd, 0x14, 0x55, 0x50, 0xb8,
  4191. 0x15, 0xaf, 0x15, 0xb9, 0x15, 0xaf, 0x15, 0x55,
  4192. 0x35, 0x19, 0x30, 0x19, 0x05, 0x1e, 0x61, 0x1e,
  4193. 0x61, 0x1e, 0x61, 0x29, 0x61, 0x1e, 0x61, 0x1f,
  4194. 0x61, 0x29, 0x61, 0x1f, 0x61, 0x1e, 0x61, 0x20,
  4195. 0x61, 0x21, 0x61, 0x1f, 0x61, 0x22, 0x61, 0x1f,
  4196. 0x61, 0x21, 0x61, 0x20, 0x61, 0x55, 0x55, 0x55,
  4197. 0x55, 0x67, 0x6d, 0x67, 0x6d, 0x63, 0x6d, 0x67,
  4198. 0x6d, 0x69, 0x6d, 0x67, 0x6d, 0x55, 0x05, 0x41,
  4199. 0x00, 0x30, 0x00, 0x57, 0xd1, 0x65, 0xd1, 0x58,
  4200. 0xd1, 0x65, 0xd1, 0x5f, 0xd1, 0x6e, 0xd1, 0x5f,
  4201. 0xd1, 0x6f, 0xd1, 0x5f, 0xd1, 0x70, 0xd1, 0x5f,
  4202. 0xd1, 0x71, 0xd1, 0x5f, 0xd1, 0x72, 0xd1, 0x55,
  4203. 0x55, 0x55, 0x05, 0xb9, 0xd1, 0x65, 0xd1, 0xba,
  4204. 0xd1, 0x65, 0xd1, 0xbb, 0xd1, 0x6e, 0xd1, 0xbc,
  4205. 0xd1, 0x6e, 0xd1, 0xbb, 0xd1, 0x6f, 0xd1, 0xbc,
  4206. 0xd1, 0x6f, 0xd1, 0x55, 0x55, 0x55, 0x41, 0x00,
  4207. 0x61, 0x00, 0x41, 0x00, 0x61, 0x00, 0x69, 0x00,
  4208. 0x41, 0x00, 0x61, 0x00, 0x41, 0x00, 0x43, 0x44,
  4209. 0x00, 0x00, 0x47, 0x00, 0x00, 0x4a, 0x4b, 0x00,
  4210. 0x00, 0x4e, 0x4f, 0x50, 0x51, 0x00, 0x53, 0x54,
  4211. 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x61, 0x62,
  4212. 0x63, 0x64, 0x00, 0x66, 0x68, 0x00, 0x70, 0x00,
  4213. 0x41, 0x00, 0x61, 0x00, 0x41, 0x42, 0x00, 0x44,
  4214. 0x45, 0x46, 0x47, 0x4a, 0x00, 0x53, 0x00, 0x61,
  4215. 0x00, 0x41, 0x42, 0x00, 0x44, 0x45, 0x46, 0x47,
  4216. 0x00, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x00, 0x4f,
  4217. 0x53, 0x00, 0x61, 0x00, 0x41, 0x00, 0x61, 0x00,
  4218. 0x41, 0x00, 0x61, 0x00, 0x41, 0x00, 0x61, 0x00,
  4219. 0x41, 0x00, 0x61, 0x00, 0x41, 0x00, 0x61, 0x00,
  4220. 0x41, 0x00, 0x61, 0x00, 0x31, 0x01, 0x37, 0x02,
  4221. 0x91, 0x03, 0xa3, 0x03, 0xb1, 0x03, 0xd1, 0x03,
  4222. 0x24, 0x00, 0x1f, 0x04, 0x20, 0x05, 0x91, 0x03,
  4223. 0xa3, 0x03, 0xb1, 0x03, 0xd1, 0x03, 0x24, 0x00,
  4224. 0x1f, 0x04, 0x20, 0x05, 0x91, 0x03, 0xa3, 0x03,
  4225. 0xb1, 0x03, 0xd1, 0x03, 0x24, 0x00, 0x1f, 0x04,
  4226. 0x20, 0x05, 0x91, 0x03, 0xa3, 0x03, 0xb1, 0x03,
  4227. 0xd1, 0x03, 0x24, 0x00, 0x1f, 0x04, 0x20, 0x05,
  4228. 0x91, 0x03, 0xa3, 0x03, 0xb1, 0x03, 0xd1, 0x03,
  4229. 0x24, 0x00, 0x1f, 0x04, 0x20, 0x05, 0x0b, 0x0c,
  4230. 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00,
  4231. 0x30, 0x00, 0x30, 0x04, 0x3a, 0x04, 0x3e, 0x04,
  4232. 0x4b, 0x04, 0x4d, 0x04, 0x4e, 0x04, 0x89, 0xa6,
  4233. 0x30, 0x04, 0xa9, 0x26, 0x28, 0xb9, 0x7f, 0x9f,
  4234. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  4235. 0x08, 0x0a, 0x0b, 0x0e, 0x0f, 0x11, 0x13, 0x14,
  4236. 0x15, 0x16, 0x17, 0x18, 0x1a, 0x1b, 0x61, 0x26,
  4237. 0x25, 0x2f, 0x7b, 0x51, 0xa6, 0xb1, 0x04, 0x27,
  4238. 0x06, 0x00, 0x01, 0x05, 0x08, 0x2a, 0x06, 0x1e,
  4239. 0x08, 0x03, 0x0d, 0x20, 0x19, 0x1a, 0x1b, 0x1c,
  4240. 0x09, 0x0f, 0x17, 0x0b, 0x18, 0x07, 0x0a, 0x00,
  4241. 0x01, 0x04, 0x06, 0x0c, 0x0e, 0x10, 0x44, 0x90,
  4242. 0x77, 0x45, 0x28, 0x06, 0x2c, 0x06, 0x00, 0x00,
  4243. 0x47, 0x06, 0x33, 0x06, 0x17, 0x10, 0x11, 0x12,
  4244. 0x13, 0x00, 0x06, 0x0e, 0x02, 0x0f, 0x34, 0x06,
  4245. 0x2a, 0x06, 0x2b, 0x06, 0x2e, 0x06, 0x00, 0x00,
  4246. 0x36, 0x06, 0x00, 0x00, 0x3a, 0x06, 0x2d, 0x06,
  4247. 0x00, 0x00, 0x4a, 0x06, 0x00, 0x00, 0x44, 0x06,
  4248. 0x00, 0x00, 0x46, 0x06, 0x33, 0x06, 0x39, 0x06,
  4249. 0x00, 0x00, 0x35, 0x06, 0x42, 0x06, 0x00, 0x00,
  4250. 0x34, 0x06, 0x00, 0x00, 0x00, 0x00, 0x2e, 0x06,
  4251. 0x00, 0x00, 0x36, 0x06, 0x00, 0x00, 0x3a, 0x06,
  4252. 0x00, 0x00, 0xba, 0x06, 0x00, 0x00, 0x6f, 0x06,
  4253. 0x00, 0x00, 0x28, 0x06, 0x2c, 0x06, 0x00, 0x00,
  4254. 0x47, 0x06, 0x00, 0x00, 0x00, 0x00, 0x2d, 0x06,
  4255. 0x37, 0x06, 0x4a, 0x06, 0x43, 0x06, 0x00, 0x00,
  4256. 0x45, 0x06, 0x46, 0x06, 0x33, 0x06, 0x39, 0x06,
  4257. 0x41, 0x06, 0x35, 0x06, 0x42, 0x06, 0x00, 0x00,
  4258. 0x34, 0x06, 0x2a, 0x06, 0x2b, 0x06, 0x2e, 0x06,
  4259. 0x00, 0x00, 0x36, 0x06, 0x38, 0x06, 0x3a, 0x06,
  4260. 0x6e, 0x06, 0x00, 0x00, 0xa1, 0x06, 0x27, 0x06,
  4261. 0x00, 0x01, 0x05, 0x08, 0x20, 0x21, 0x0b, 0x06,
  4262. 0x10, 0x23, 0x2a, 0x06, 0x1a, 0x1b, 0x1c, 0x09,
  4263. 0x0f, 0x17, 0x0b, 0x18, 0x07, 0x0a, 0x00, 0x01,
  4264. 0x04, 0x06, 0x0c, 0x0e, 0x10, 0x28, 0x06, 0x2c,
  4265. 0x06, 0x2f, 0x06, 0x00, 0x00, 0x48, 0x06, 0x32,
  4266. 0x06, 0x2d, 0x06, 0x37, 0x06, 0x4a, 0x06, 0x2a,
  4267. 0x06, 0x1a, 0x1b, 0x1c, 0x09, 0x0f, 0x17, 0x0b,
  4268. 0x18, 0x07, 0x0a, 0x00, 0x01, 0x04, 0x06, 0x0c,
  4269. 0x0e, 0x10, 0x30, 0x2e, 0x30, 0x00, 0x2c, 0x00,
  4270. 0x28, 0x00, 0x41, 0x00, 0x29, 0x00, 0x14, 0x30,
  4271. 0x53, 0x00, 0x15, 0x30, 0x43, 0x52, 0x43, 0x44,
  4272. 0x57, 0x5a, 0x41, 0x00, 0x48, 0x56, 0x4d, 0x56,
  4273. 0x53, 0x44, 0x53, 0x53, 0x50, 0x50, 0x56, 0x57,
  4274. 0x43, 0x4d, 0x43, 0x4d, 0x44, 0x4d, 0x52, 0x44,
  4275. 0x4a, 0x4b, 0x30, 0x30, 0x00, 0x68, 0x68, 0x4b,
  4276. 0x62, 0x57, 0x5b, 0xcc, 0x53, 0xc7, 0x30, 0x8c,
  4277. 0x4e, 0x1a, 0x59, 0xe3, 0x89, 0x29, 0x59, 0xa4,
  4278. 0x4e, 0x20, 0x66, 0x21, 0x71, 0x99, 0x65, 0x4d,
  4279. 0x52, 0x8c, 0x5f, 0x8d, 0x51, 0xb0, 0x65, 0x1d,
  4280. 0x52, 0x42, 0x7d, 0x1f, 0x75, 0xa9, 0x8c, 0xf0,
  4281. 0x58, 0x39, 0x54, 0x14, 0x6f, 0x95, 0x62, 0x55,
  4282. 0x63, 0x00, 0x4e, 0x09, 0x4e, 0x4a, 0x90, 0xe6,
  4283. 0x5d, 0x2d, 0x4e, 0xf3, 0x53, 0x07, 0x63, 0x70,
  4284. 0x8d, 0x53, 0x62, 0x81, 0x79, 0x7a, 0x7a, 0x08,
  4285. 0x54, 0x80, 0x6e, 0x09, 0x67, 0x08, 0x67, 0x33,
  4286. 0x75, 0x72, 0x52, 0xb6, 0x55, 0x4d, 0x91, 0x14,
  4287. 0x30, 0x15, 0x30, 0x2c, 0x67, 0x09, 0x4e, 0x8c,
  4288. 0x4e, 0x89, 0x5b, 0xb9, 0x70, 0x53, 0x62, 0xd7,
  4289. 0x76, 0xdd, 0x52, 0x57, 0x65, 0x97, 0x5f, 0xef,
  4290. 0x53, 0x30, 0x00, 0x38, 0x4e, 0x05, 0x00, 0x09,
  4291. 0x22, 0x01, 0x60, 0x4f, 0xae, 0x4f, 0xbb, 0x4f,
  4292. 0x02, 0x50, 0x7a, 0x50, 0x99, 0x50, 0xe7, 0x50,
  4293. 0xcf, 0x50, 0x9e, 0x34, 0x3a, 0x06, 0x4d, 0x51,
  4294. 0x54, 0x51, 0x64, 0x51, 0x77, 0x51, 0x1c, 0x05,
  4295. 0xb9, 0x34, 0x67, 0x51, 0x8d, 0x51, 0x4b, 0x05,
  4296. 0x97, 0x51, 0xa4, 0x51, 0xcc, 0x4e, 0xac, 0x51,
  4297. 0xb5, 0x51, 0xdf, 0x91, 0xf5, 0x51, 0x03, 0x52,
  4298. 0xdf, 0x34, 0x3b, 0x52, 0x46, 0x52, 0x72, 0x52,
  4299. 0x77, 0x52, 0x15, 0x35, 0x02, 0x00, 0x20, 0x80,
  4300. 0x80, 0x00, 0x08, 0x00, 0x00, 0xc7, 0x52, 0x00,
  4301. 0x02, 0x1d, 0x33, 0x3e, 0x3f, 0x50, 0x82, 0x8a,
  4302. 0x93, 0xac, 0xb6, 0xb8, 0xb8, 0xb8, 0x2c, 0x0a,
  4303. 0x70, 0x70, 0xca, 0x53, 0xdf, 0x53, 0x63, 0x0b,
  4304. 0xeb, 0x53, 0xf1, 0x53, 0x06, 0x54, 0x9e, 0x54,
  4305. 0x38, 0x54, 0x48, 0x54, 0x68, 0x54, 0xa2, 0x54,
  4306. 0xf6, 0x54, 0x10, 0x55, 0x53, 0x55, 0x63, 0x55,
  4307. 0x84, 0x55, 0x84, 0x55, 0x99, 0x55, 0xab, 0x55,
  4308. 0xb3, 0x55, 0xc2, 0x55, 0x16, 0x57, 0x06, 0x56,
  4309. 0x17, 0x57, 0x51, 0x56, 0x74, 0x56, 0x07, 0x52,
  4310. 0xee, 0x58, 0xce, 0x57, 0xf4, 0x57, 0x0d, 0x58,
  4311. 0x8b, 0x57, 0x32, 0x58, 0x31, 0x58, 0xac, 0x58,
  4312. 0xe4, 0x14, 0xf2, 0x58, 0xf7, 0x58, 0x06, 0x59,
  4313. 0x1a, 0x59, 0x22, 0x59, 0x62, 0x59, 0xa8, 0x16,
  4314. 0xea, 0x16, 0xec, 0x59, 0x1b, 0x5a, 0x27, 0x5a,
  4315. 0xd8, 0x59, 0x66, 0x5a, 0xee, 0x36, 0xfc, 0x36,
  4316. 0x08, 0x5b, 0x3e, 0x5b, 0x3e, 0x5b, 0xc8, 0x19,
  4317. 0xc3, 0x5b, 0xd8, 0x5b, 0xe7, 0x5b, 0xf3, 0x5b,
  4318. 0x18, 0x1b, 0xff, 0x5b, 0x06, 0x5c, 0x53, 0x5f,
  4319. 0x22, 0x5c, 0x81, 0x37, 0x60, 0x5c, 0x6e, 0x5c,
  4320. 0xc0, 0x5c, 0x8d, 0x5c, 0xe4, 0x1d, 0x43, 0x5d,
  4321. 0xe6, 0x1d, 0x6e, 0x5d, 0x6b, 0x5d, 0x7c, 0x5d,
  4322. 0xe1, 0x5d, 0xe2, 0x5d, 0x2f, 0x38, 0xfd, 0x5d,
  4323. 0x28, 0x5e, 0x3d, 0x5e, 0x69, 0x5e, 0x62, 0x38,
  4324. 0x83, 0x21, 0x7c, 0x38, 0xb0, 0x5e, 0xb3, 0x5e,
  4325. 0xb6, 0x5e, 0xca, 0x5e, 0x92, 0xa3, 0xfe, 0x5e,
  4326. 0x31, 0x23, 0x31, 0x23, 0x01, 0x82, 0x22, 0x5f,
  4327. 0x22, 0x5f, 0xc7, 0x38, 0xb8, 0x32, 0xda, 0x61,
  4328. 0x62, 0x5f, 0x6b, 0x5f, 0xe3, 0x38, 0x9a, 0x5f,
  4329. 0xcd, 0x5f, 0xd7, 0x5f, 0xf9, 0x5f, 0x81, 0x60,
  4330. 0x3a, 0x39, 0x1c, 0x39, 0x94, 0x60, 0xd4, 0x26,
  4331. 0xc7, 0x60, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00,
  4332. 0x00, 0x00, 0x00, 0x08, 0x00, 0x0a, 0x00, 0x00,
  4333. 0x02, 0x08, 0x00, 0x80, 0x08, 0x00, 0x00, 0x08,
  4334. 0x80, 0x28, 0x80, 0x02, 0x00, 0x00, 0x02, 0x48,
  4335. 0x61, 0x00, 0x04, 0x06, 0x04, 0x32, 0x46, 0x6a,
  4336. 0x5c, 0x67, 0x96, 0xaa, 0xae, 0xc8, 0xd3, 0x5d,
  4337. 0x62, 0x00, 0x54, 0x77, 0xf3, 0x0c, 0x2b, 0x3d,
  4338. 0x63, 0xfc, 0x62, 0x68, 0x63, 0x83, 0x63, 0xe4,
  4339. 0x63, 0xf1, 0x2b, 0x22, 0x64, 0xc5, 0x63, 0xa9,
  4340. 0x63, 0x2e, 0x3a, 0x69, 0x64, 0x7e, 0x64, 0x9d,
  4341. 0x64, 0x77, 0x64, 0x6c, 0x3a, 0x4f, 0x65, 0x6c,
  4342. 0x65, 0x0a, 0x30, 0xe3, 0x65, 0xf8, 0x66, 0x49,
  4343. 0x66, 0x19, 0x3b, 0x91, 0x66, 0x08, 0x3b, 0xe4,
  4344. 0x3a, 0x92, 0x51, 0x95, 0x51, 0x00, 0x67, 0x9c,
  4345. 0x66, 0xad, 0x80, 0xd9, 0x43, 0x17, 0x67, 0x1b,
  4346. 0x67, 0x21, 0x67, 0x5e, 0x67, 0x53, 0x67, 0xc3,
  4347. 0x33, 0x49, 0x3b, 0xfa, 0x67, 0x85, 0x67, 0x52,
  4348. 0x68, 0x85, 0x68, 0x6d, 0x34, 0x8e, 0x68, 0x1f,
  4349. 0x68, 0x14, 0x69, 0x9d, 0x3b, 0x42, 0x69, 0xa3,
  4350. 0x69, 0xea, 0x69, 0xa8, 0x6a, 0xa3, 0x36, 0xdb,
  4351. 0x6a, 0x18, 0x3c, 0x21, 0x6b, 0xa7, 0x38, 0x54,
  4352. 0x6b, 0x4e, 0x3c, 0x72, 0x6b, 0x9f, 0x6b, 0xba,
  4353. 0x6b, 0xbb, 0x6b, 0x8d, 0x3a, 0x0b, 0x1d, 0xfa,
  4354. 0x3a, 0x4e, 0x6c, 0xbc, 0x3c, 0xbf, 0x6c, 0xcd,
  4355. 0x6c, 0x67, 0x6c, 0x16, 0x6d, 0x3e, 0x6d, 0x77,
  4356. 0x6d, 0x41, 0x6d, 0x69, 0x6d, 0x78, 0x6d, 0x85,
  4357. 0x6d, 0x1e, 0x3d, 0x34, 0x6d, 0x2f, 0x6e, 0x6e,
  4358. 0x6e, 0x33, 0x3d, 0xcb, 0x6e, 0xc7, 0x6e, 0xd1,
  4359. 0x3e, 0xf9, 0x6d, 0x6e, 0x6f, 0x5e, 0x3f, 0x8e,
  4360. 0x3f, 0xc6, 0x6f, 0x39, 0x70, 0x1e, 0x70, 0x1b,
  4361. 0x70, 0x96, 0x3d, 0x4a, 0x70, 0x7d, 0x70, 0x77,
  4362. 0x70, 0xad, 0x70, 0x25, 0x05, 0x45, 0x71, 0x63,
  4363. 0x42, 0x9c, 0x71, 0xab, 0x43, 0x28, 0x72, 0x35,
  4364. 0x72, 0x50, 0x72, 0x08, 0x46, 0x80, 0x72, 0x95,
  4365. 0x72, 0x35, 0x47, 0x02, 0x20, 0x00, 0x00, 0x20,
  4366. 0x00, 0x00, 0x00, 0x00, 0x08, 0x80, 0x00, 0x00,
  4367. 0x02, 0x02, 0x80, 0x8a, 0x00, 0x00, 0x20, 0x00,
  4368. 0x08, 0x0a, 0x00, 0x80, 0x88, 0x80, 0x20, 0x14,
  4369. 0x48, 0x7a, 0x73, 0x8b, 0x73, 0xac, 0x3e, 0xa5,
  4370. 0x73, 0xb8, 0x3e, 0xb8, 0x3e, 0x47, 0x74, 0x5c,
  4371. 0x74, 0x71, 0x74, 0x85, 0x74, 0xca, 0x74, 0x1b,
  4372. 0x3f, 0x24, 0x75, 0x36, 0x4c, 0x3e, 0x75, 0x92,
  4373. 0x4c, 0x70, 0x75, 0x9f, 0x21, 0x10, 0x76, 0xa1,
  4374. 0x4f, 0xb8, 0x4f, 0x44, 0x50, 0xfc, 0x3f, 0x08,
  4375. 0x40, 0xf4, 0x76, 0xf3, 0x50, 0xf2, 0x50, 0x19,
  4376. 0x51, 0x33, 0x51, 0x1e, 0x77, 0x1f, 0x77, 0x1f,
  4377. 0x77, 0x4a, 0x77, 0x39, 0x40, 0x8b, 0x77, 0x46,
  4378. 0x40, 0x96, 0x40, 0x1d, 0x54, 0x4e, 0x78, 0x8c,
  4379. 0x78, 0xcc, 0x78, 0xe3, 0x40, 0x26, 0x56, 0x56,
  4380. 0x79, 0x9a, 0x56, 0xc5, 0x56, 0x8f, 0x79, 0xeb,
  4381. 0x79, 0x2f, 0x41, 0x40, 0x7a, 0x4a, 0x7a, 0x4f,
  4382. 0x7a, 0x7c, 0x59, 0xa7, 0x5a, 0xa7, 0x5a, 0xee,
  4383. 0x7a, 0x02, 0x42, 0xab, 0x5b, 0xc6, 0x7b, 0xc9,
  4384. 0x7b, 0x27, 0x42, 0x80, 0x5c, 0xd2, 0x7c, 0xa0,
  4385. 0x42, 0xe8, 0x7c, 0xe3, 0x7c, 0x00, 0x7d, 0x86,
  4386. 0x5f, 0x63, 0x7d, 0x01, 0x43, 0xc7, 0x7d, 0x02,
  4387. 0x7e, 0x45, 0x7e, 0x34, 0x43, 0x28, 0x62, 0x47,
  4388. 0x62, 0x59, 0x43, 0xd9, 0x62, 0x7a, 0x7f, 0x3e,
  4389. 0x63, 0x95, 0x7f, 0xfa, 0x7f, 0x05, 0x80, 0xda,
  4390. 0x64, 0x23, 0x65, 0x60, 0x80, 0xa8, 0x65, 0x70,
  4391. 0x80, 0x5f, 0x33, 0xd5, 0x43, 0xb2, 0x80, 0x03,
  4392. 0x81, 0x0b, 0x44, 0x3e, 0x81, 0xb5, 0x5a, 0xa7,
  4393. 0x67, 0xb5, 0x67, 0x93, 0x33, 0x9c, 0x33, 0x01,
  4394. 0x82, 0x04, 0x82, 0x9e, 0x8f, 0x6b, 0x44, 0x91,
  4395. 0x82, 0x8b, 0x82, 0x9d, 0x82, 0xb3, 0x52, 0xb1,
  4396. 0x82, 0xb3, 0x82, 0xbd, 0x82, 0xe6, 0x82, 0x3c,
  4397. 0x6b, 0xe5, 0x82, 0x1d, 0x83, 0x63, 0x83, 0xad,
  4398. 0x83, 0x23, 0x83, 0xbd, 0x83, 0xe7, 0x83, 0x57,
  4399. 0x84, 0x53, 0x83, 0xca, 0x83, 0xcc, 0x83, 0xdc,
  4400. 0x83, 0x36, 0x6c, 0x6b, 0x6d, 0x02, 0x00, 0x00,
  4401. 0x20, 0x22, 0x2a, 0xa0, 0x0a, 0x00, 0x20, 0x80,
  4402. 0x28, 0x00, 0xa8, 0x20, 0x20, 0x00, 0x02, 0x80,
  4403. 0x22, 0x02, 0x8a, 0x08, 0x00, 0xaa, 0x00, 0x00,
  4404. 0x00, 0x02, 0x00, 0x00, 0x28, 0xd5, 0x6c, 0x2b,
  4405. 0x45, 0xf1, 0x84, 0xf3, 0x84, 0x16, 0x85, 0xca,
  4406. 0x73, 0x64, 0x85, 0x2c, 0x6f, 0x5d, 0x45, 0x61,
  4407. 0x45, 0xb1, 0x6f, 0xd2, 0x70, 0x6b, 0x45, 0x50,
  4408. 0x86, 0x5c, 0x86, 0x67, 0x86, 0x69, 0x86, 0xa9,
  4409. 0x86, 0x88, 0x86, 0x0e, 0x87, 0xe2, 0x86, 0x79,
  4410. 0x87, 0x28, 0x87, 0x6b, 0x87, 0x86, 0x87, 0xd7,
  4411. 0x45, 0xe1, 0x87, 0x01, 0x88, 0xf9, 0x45, 0x60,
  4412. 0x88, 0x63, 0x88, 0x67, 0x76, 0xd7, 0x88, 0xde,
  4413. 0x88, 0x35, 0x46, 0xfa, 0x88, 0xbb, 0x34, 0xae,
  4414. 0x78, 0x66, 0x79, 0xbe, 0x46, 0xc7, 0x46, 0xa0,
  4415. 0x8a, 0xed, 0x8a, 0x8a, 0x8b, 0x55, 0x8c, 0xa8,
  4416. 0x7c, 0xab, 0x8c, 0xc1, 0x8c, 0x1b, 0x8d, 0x77,
  4417. 0x8d, 0x2f, 0x7f, 0x04, 0x08, 0xcb, 0x8d, 0xbc,
  4418. 0x8d, 0xf0, 0x8d, 0xde, 0x08, 0xd4, 0x8e, 0x38,
  4419. 0x8f, 0xd2, 0x85, 0xed, 0x85, 0x94, 0x90, 0xf1,
  4420. 0x90, 0x11, 0x91, 0x2e, 0x87, 0x1b, 0x91, 0x38,
  4421. 0x92, 0xd7, 0x92, 0xd8, 0x92, 0x7c, 0x92, 0xf9,
  4422. 0x93, 0x15, 0x94, 0xfa, 0x8b, 0x8b, 0x95, 0x95,
  4423. 0x49, 0xb7, 0x95, 0x77, 0x8d, 0xe6, 0x49, 0xc3,
  4424. 0x96, 0xb2, 0x5d, 0x23, 0x97, 0x45, 0x91, 0x1a,
  4425. 0x92, 0x6e, 0x4a, 0x76, 0x4a, 0xe0, 0x97, 0x0a,
  4426. 0x94, 0xb2, 0x4a, 0x96, 0x94, 0x0b, 0x98, 0x0b,
  4427. 0x98, 0x29, 0x98, 0xb6, 0x95, 0xe2, 0x98, 0x33,
  4428. 0x4b, 0x29, 0x99, 0xa7, 0x99, 0xc2, 0x99, 0xfe,
  4429. 0x99, 0xce, 0x4b, 0x30, 0x9b, 0x12, 0x9b, 0x40,
  4430. 0x9c, 0xfd, 0x9c, 0xce, 0x4c, 0xed, 0x4c, 0x67,
  4431. 0x9d, 0xce, 0xa0, 0xf8, 0x4c, 0x05, 0xa1, 0x0e,
  4432. 0xa2, 0x91, 0xa2, 0xbb, 0x9e, 0x56, 0x4d, 0xf9,
  4433. 0x9e, 0xfe, 0x9e, 0x05, 0x9f, 0x0f, 0x9f, 0x16,
  4434. 0x9f, 0x3b, 0x9f, 0x00, 0xa6, 0x02, 0x88, 0xa0,
  4435. 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x28, 0x00,
  4436. 0x08, 0xa0, 0x80, 0xa0, 0x80, 0x00, 0x80, 0x80,
  4437. 0x00, 0x0a, 0x88, 0x80, 0x00, 0x80, 0x00, 0x20,
  4438. 0x2a, 0x00, 0x80,
  4439. };
  4440. static const uint16_t unicode_comp_table[965] = {
  4441. 0x4a01, 0x49c0, 0x4a02, 0x0280, 0x0281, 0x0282, 0x0283, 0x02c0,
  4442. 0x02c2, 0x0a00, 0x0284, 0x2442, 0x0285, 0x07c0, 0x0980, 0x0982,
  4443. 0x2440, 0x2280, 0x02c4, 0x2282, 0x2284, 0x2286, 0x02c6, 0x02c8,
  4444. 0x02ca, 0x02cc, 0x0287, 0x228a, 0x02ce, 0x228c, 0x2290, 0x2292,
  4445. 0x228e, 0x0288, 0x0289, 0x028a, 0x2482, 0x0300, 0x0302, 0x0304,
  4446. 0x028b, 0x2480, 0x0308, 0x0984, 0x0986, 0x2458, 0x0a02, 0x0306,
  4447. 0x2298, 0x229a, 0x229e, 0x0900, 0x030a, 0x22a0, 0x030c, 0x030e,
  4448. 0x0840, 0x0310, 0x0312, 0x22a2, 0x22a6, 0x09c0, 0x22a4, 0x22a8,
  4449. 0x22aa, 0x028c, 0x028d, 0x028e, 0x0340, 0x0342, 0x0344, 0x0380,
  4450. 0x028f, 0x248e, 0x07c2, 0x0988, 0x098a, 0x2490, 0x0346, 0x22ac,
  4451. 0x0400, 0x22b0, 0x0842, 0x22b2, 0x0402, 0x22b4, 0x0440, 0x0444,
  4452. 0x22b6, 0x0442, 0x22c2, 0x22c0, 0x22c4, 0x22c6, 0x22c8, 0x0940,
  4453. 0x04c0, 0x0291, 0x22ca, 0x04c4, 0x22cc, 0x04c2, 0x22d0, 0x22ce,
  4454. 0x0292, 0x0293, 0x0294, 0x0295, 0x0540, 0x0542, 0x0a08, 0x0296,
  4455. 0x2494, 0x0544, 0x07c4, 0x098c, 0x098e, 0x06c0, 0x2492, 0x0844,
  4456. 0x2308, 0x230a, 0x0580, 0x230c, 0x0584, 0x0990, 0x0992, 0x230e,
  4457. 0x0582, 0x2312, 0x0586, 0x0588, 0x2314, 0x058c, 0x2316, 0x0998,
  4458. 0x058a, 0x231e, 0x0590, 0x2320, 0x099a, 0x058e, 0x2324, 0x2322,
  4459. 0x0299, 0x029a, 0x029b, 0x05c0, 0x05c2, 0x05c4, 0x029c, 0x24ac,
  4460. 0x05c6, 0x05c8, 0x07c6, 0x0994, 0x0996, 0x0700, 0x24aa, 0x2326,
  4461. 0x05ca, 0x232a, 0x2328, 0x2340, 0x2342, 0x2344, 0x2346, 0x05cc,
  4462. 0x234a, 0x2348, 0x234c, 0x234e, 0x2350, 0x24b8, 0x029d, 0x05ce,
  4463. 0x24be, 0x0a0c, 0x2352, 0x0600, 0x24bc, 0x24ba, 0x0640, 0x2354,
  4464. 0x0642, 0x0644, 0x2356, 0x2358, 0x02a0, 0x02a1, 0x02a2, 0x02a3,
  4465. 0x02c1, 0x02c3, 0x0a01, 0x02a4, 0x2443, 0x02a5, 0x07c1, 0x0981,
  4466. 0x0983, 0x2441, 0x2281, 0x02c5, 0x2283, 0x2285, 0x2287, 0x02c7,
  4467. 0x02c9, 0x02cb, 0x02cd, 0x02a7, 0x228b, 0x02cf, 0x228d, 0x2291,
  4468. 0x2293, 0x228f, 0x02a8, 0x02a9, 0x02aa, 0x2483, 0x0301, 0x0303,
  4469. 0x0305, 0x02ab, 0x2481, 0x0309, 0x0985, 0x0987, 0x2459, 0x0a03,
  4470. 0x0307, 0x2299, 0x229b, 0x229f, 0x0901, 0x030b, 0x22a1, 0x030d,
  4471. 0x030f, 0x0841, 0x0311, 0x0313, 0x22a3, 0x22a7, 0x09c1, 0x22a5,
  4472. 0x22a9, 0x22ab, 0x2380, 0x02ac, 0x02ad, 0x02ae, 0x0341, 0x0343,
  4473. 0x0345, 0x02af, 0x248f, 0x07c3, 0x0989, 0x098b, 0x2491, 0x0347,
  4474. 0x22ad, 0x0401, 0x0884, 0x22b1, 0x0843, 0x22b3, 0x0403, 0x22b5,
  4475. 0x0441, 0x0445, 0x22b7, 0x0443, 0x22c3, 0x22c1, 0x22c5, 0x22c7,
  4476. 0x22c9, 0x0941, 0x04c1, 0x02b1, 0x22cb, 0x04c5, 0x22cd, 0x04c3,
  4477. 0x22d1, 0x22cf, 0x02b2, 0x02b3, 0x02b4, 0x02b5, 0x0541, 0x0543,
  4478. 0x0a09, 0x02b6, 0x2495, 0x0545, 0x07c5, 0x098d, 0x098f, 0x06c1,
  4479. 0x2493, 0x0845, 0x2309, 0x230b, 0x0581, 0x230d, 0x0585, 0x0991,
  4480. 0x0993, 0x230f, 0x0583, 0x2313, 0x0587, 0x0589, 0x2315, 0x058d,
  4481. 0x2317, 0x0999, 0x058b, 0x231f, 0x2381, 0x0591, 0x2321, 0x099b,
  4482. 0x058f, 0x2325, 0x2323, 0x02b9, 0x02ba, 0x02bb, 0x05c1, 0x05c3,
  4483. 0x05c5, 0x02bc, 0x24ad, 0x05c7, 0x05c9, 0x07c7, 0x0995, 0x0997,
  4484. 0x0701, 0x24ab, 0x2327, 0x05cb, 0x232b, 0x2329, 0x2341, 0x2343,
  4485. 0x2345, 0x2347, 0x05cd, 0x234b, 0x2349, 0x2382, 0x234d, 0x234f,
  4486. 0x2351, 0x24b9, 0x02bd, 0x05cf, 0x24bf, 0x0a0d, 0x2353, 0x02bf,
  4487. 0x24bd, 0x2383, 0x24bb, 0x0641, 0x2355, 0x0643, 0x0645, 0x2357,
  4488. 0x2359, 0x3101, 0x0c80, 0x2e00, 0x2446, 0x2444, 0x244a, 0x2448,
  4489. 0x0800, 0x0942, 0x0944, 0x0804, 0x2288, 0x2486, 0x2484, 0x248a,
  4490. 0x2488, 0x22ae, 0x2498, 0x2496, 0x249c, 0x249a, 0x2300, 0x0a06,
  4491. 0x2302, 0x0a04, 0x0946, 0x07ce, 0x07ca, 0x07c8, 0x07cc, 0x2447,
  4492. 0x2445, 0x244b, 0x2449, 0x0801, 0x0943, 0x0945, 0x0805, 0x2289,
  4493. 0x2487, 0x2485, 0x248b, 0x2489, 0x22af, 0x2499, 0x2497, 0x249d,
  4494. 0x249b, 0x2301, 0x0a07, 0x2303, 0x0a05, 0x0947, 0x07cf, 0x07cb,
  4495. 0x07c9, 0x07cd, 0x2450, 0x244e, 0x2454, 0x2452, 0x2451, 0x244f,
  4496. 0x2455, 0x2453, 0x2294, 0x2296, 0x2295, 0x2297, 0x2304, 0x2306,
  4497. 0x2305, 0x2307, 0x2318, 0x2319, 0x231a, 0x231b, 0x232c, 0x232d,
  4498. 0x232e, 0x232f, 0x2400, 0x24a2, 0x24a0, 0x24a6, 0x24a4, 0x24a8,
  4499. 0x24a3, 0x24a1, 0x24a7, 0x24a5, 0x24a9, 0x24b0, 0x24ae, 0x24b4,
  4500. 0x24b2, 0x24b6, 0x24b1, 0x24af, 0x24b5, 0x24b3, 0x24b7, 0x0882,
  4501. 0x0880, 0x0881, 0x0802, 0x0803, 0x229c, 0x229d, 0x0a0a, 0x0a0b,
  4502. 0x0883, 0x0b40, 0x2c8a, 0x0c81, 0x2c89, 0x2c88, 0x2540, 0x2541,
  4503. 0x2d00, 0x2e07, 0x0d00, 0x2640, 0x2641, 0x2e80, 0x0d01, 0x26c8,
  4504. 0x26c9, 0x2f00, 0x2f84, 0x0d02, 0x2f83, 0x2f82, 0x0d40, 0x26d8,
  4505. 0x26d9, 0x3186, 0x0d04, 0x2740, 0x2741, 0x3100, 0x3086, 0x0d06,
  4506. 0x3085, 0x3084, 0x0d41, 0x2840, 0x3200, 0x0d07, 0x284f, 0x2850,
  4507. 0x3280, 0x2c84, 0x2e03, 0x2857, 0x0d42, 0x2c81, 0x2c80, 0x24c0,
  4508. 0x24c1, 0x2c86, 0x2c83, 0x28c0, 0x0d43, 0x25c0, 0x25c1, 0x2940,
  4509. 0x0d44, 0x26c0, 0x26c1, 0x2e05, 0x2e02, 0x29c0, 0x0d45, 0x2f05,
  4510. 0x2f04, 0x0d80, 0x26d0, 0x26d1, 0x2f80, 0x2a40, 0x0d82, 0x26e0,
  4511. 0x26e1, 0x3080, 0x3081, 0x2ac0, 0x0d83, 0x3004, 0x3003, 0x0d81,
  4512. 0x27c0, 0x27c1, 0x3082, 0x2b40, 0x0d84, 0x2847, 0x2848, 0x3184,
  4513. 0x3181, 0x2f06, 0x0d08, 0x2f81, 0x3005, 0x0d46, 0x3083, 0x3182,
  4514. 0x0e00, 0x0e01, 0x0f40, 0x1180, 0x1182, 0x0f03, 0x0f00, 0x11c0,
  4515. 0x0f01, 0x1140, 0x1202, 0x1204, 0x0f81, 0x1240, 0x0fc0, 0x1242,
  4516. 0x0f80, 0x1244, 0x1284, 0x0f82, 0x1286, 0x1288, 0x128a, 0x12c0,
  4517. 0x1282, 0x1181, 0x1183, 0x1043, 0x1040, 0x11c1, 0x1041, 0x1141,
  4518. 0x1203, 0x1205, 0x10c1, 0x1241, 0x1000, 0x1243, 0x10c0, 0x1245,
  4519. 0x1285, 0x10c2, 0x1287, 0x1289, 0x128b, 0x12c1, 0x1283, 0x1080,
  4520. 0x1100, 0x1101, 0x1200, 0x1201, 0x1280, 0x1281, 0x1340, 0x1341,
  4521. 0x1343, 0x1342, 0x1344, 0x13c2, 0x1400, 0x13c0, 0x1440, 0x1480,
  4522. 0x14c0, 0x1540, 0x1541, 0x1740, 0x1700, 0x1741, 0x17c0, 0x1800,
  4523. 0x1802, 0x1801, 0x1840, 0x1880, 0x1900, 0x18c0, 0x18c1, 0x1901,
  4524. 0x1940, 0x1942, 0x1941, 0x1980, 0x19c0, 0x19c2, 0x19c1, 0x1c80,
  4525. 0x1cc0, 0x1dc0, 0x1f80, 0x2000, 0x2002, 0x2004, 0x2006, 0x2008,
  4526. 0x2040, 0x2080, 0x2082, 0x20c0, 0x20c1, 0x2100, 0x22b8, 0x22b9,
  4527. 0x2310, 0x2311, 0x231c, 0x231d, 0x244c, 0x2456, 0x244d, 0x2457,
  4528. 0x248c, 0x248d, 0x249e, 0x249f, 0x2500, 0x2502, 0x2504, 0x2bc0,
  4529. 0x2501, 0x2503, 0x2505, 0x2bc1, 0x2bc2, 0x2bc3, 0x2bc4, 0x2bc5,
  4530. 0x2bc6, 0x2bc7, 0x2580, 0x2582, 0x2584, 0x2bc8, 0x2581, 0x2583,
  4531. 0x2585, 0x2bc9, 0x2bca, 0x2bcb, 0x2bcc, 0x2bcd, 0x2bce, 0x2bcf,
  4532. 0x2600, 0x2602, 0x2601, 0x2603, 0x2680, 0x2682, 0x2681, 0x2683,
  4533. 0x26c2, 0x26c4, 0x26c6, 0x2c00, 0x26c3, 0x26c5, 0x26c7, 0x2c01,
  4534. 0x2c02, 0x2c03, 0x2c04, 0x2c05, 0x2c06, 0x2c07, 0x26ca, 0x26cc,
  4535. 0x26ce, 0x2c08, 0x26cb, 0x26cd, 0x26cf, 0x2c09, 0x2c0a, 0x2c0b,
  4536. 0x2c0c, 0x2c0d, 0x2c0e, 0x2c0f, 0x26d2, 0x26d4, 0x26d6, 0x26d3,
  4537. 0x26d5, 0x26d7, 0x26da, 0x26dc, 0x26de, 0x26db, 0x26dd, 0x26df,
  4538. 0x2700, 0x2702, 0x2701, 0x2703, 0x2780, 0x2782, 0x2781, 0x2783,
  4539. 0x2800, 0x2802, 0x2804, 0x2801, 0x2803, 0x2805, 0x2842, 0x2844,
  4540. 0x2846, 0x2849, 0x284b, 0x284d, 0x2c40, 0x284a, 0x284c, 0x284e,
  4541. 0x2c41, 0x2c42, 0x2c43, 0x2c44, 0x2c45, 0x2c46, 0x2c47, 0x2851,
  4542. 0x2853, 0x2855, 0x2c48, 0x2852, 0x2854, 0x2856, 0x2c49, 0x2c4a,
  4543. 0x2c4b, 0x2c4c, 0x2c4d, 0x2c4e, 0x2c4f, 0x2c82, 0x2e01, 0x3180,
  4544. 0x2c87, 0x2f01, 0x2f02, 0x2f03, 0x2e06, 0x3185, 0x3000, 0x3001,
  4545. 0x3002, 0x4640, 0x4641, 0x4680, 0x46c0, 0x46c2, 0x46c1, 0x4700,
  4546. 0x4740, 0x4780, 0x47c0, 0x47c2, 0x4900, 0x4940, 0x4980, 0x4982,
  4547. 0x4a00, 0x49c2, 0x4a03, 0x4a04, 0x4a40, 0x4a41, 0x4a80, 0x4a81,
  4548. 0x4ac0, 0x4ac1, 0x4bc0, 0x4bc1, 0x4b00, 0x4b01, 0x4b40, 0x4b41,
  4549. 0x4bc2, 0x4bc3, 0x4b80, 0x4b81, 0x4b82, 0x4b83, 0x4c00, 0x4c01,
  4550. 0x4c02, 0x4c03, 0x5600, 0x5440, 0x5442, 0x5444, 0x5446, 0x5448,
  4551. 0x544a, 0x544c, 0x544e, 0x5450, 0x5452, 0x5454, 0x5456, 0x5480,
  4552. 0x5482, 0x5484, 0x54c0, 0x54c1, 0x5500, 0x5501, 0x5540, 0x5541,
  4553. 0x5580, 0x5581, 0x55c0, 0x55c1, 0x5680, 0x58c0, 0x5700, 0x5702,
  4554. 0x5704, 0x5706, 0x5708, 0x570a, 0x570c, 0x570e, 0x5710, 0x5712,
  4555. 0x5714, 0x5716, 0x5740, 0x5742, 0x5744, 0x5780, 0x5781, 0x57c0,
  4556. 0x57c1, 0x5800, 0x5801, 0x5840, 0x5841, 0x5880, 0x5881, 0x5900,
  4557. 0x5901, 0x5902, 0x5903, 0x5940, 0x8ec0, 0x8f00, 0x8fc0, 0x8fc2,
  4558. 0x9000, 0x9040, 0x9041, 0x9080, 0x9081, 0x90c0, 0x90c2, 0x9100,
  4559. 0x9140, 0x9182, 0x9180, 0x9183, 0x91c1, 0x91c0, 0x91c3, 0x9200,
  4560. 0x9201, 0x9240, 0x9280, 0x9282, 0x9284, 0x9281, 0x9285, 0x9287,
  4561. 0x9286, 0x9283, 0x92c1, 0x92c0, 0x92c2,
  4562. };
  4563. typedef enum {
  4564. UNICODE_GC_Cn,
  4565. UNICODE_GC_Lu,
  4566. UNICODE_GC_Ll,
  4567. UNICODE_GC_Lt,
  4568. UNICODE_GC_Lm,
  4569. UNICODE_GC_Lo,
  4570. UNICODE_GC_Mn,
  4571. UNICODE_GC_Mc,
  4572. UNICODE_GC_Me,
  4573. UNICODE_GC_Nd,
  4574. UNICODE_GC_Nl,
  4575. UNICODE_GC_No,
  4576. UNICODE_GC_Sm,
  4577. UNICODE_GC_Sc,
  4578. UNICODE_GC_Sk,
  4579. UNICODE_GC_So,
  4580. UNICODE_GC_Pc,
  4581. UNICODE_GC_Pd,
  4582. UNICODE_GC_Ps,
  4583. UNICODE_GC_Pe,
  4584. UNICODE_GC_Pi,
  4585. UNICODE_GC_Pf,
  4586. UNICODE_GC_Po,
  4587. UNICODE_GC_Zs,
  4588. UNICODE_GC_Zl,
  4589. UNICODE_GC_Zp,
  4590. UNICODE_GC_Cc,
  4591. UNICODE_GC_Cf,
  4592. UNICODE_GC_Cs,
  4593. UNICODE_GC_Co,
  4594. UNICODE_GC_LC,
  4595. UNICODE_GC_L,
  4596. UNICODE_GC_M,
  4597. UNICODE_GC_N,
  4598. UNICODE_GC_S,
  4599. UNICODE_GC_P,
  4600. UNICODE_GC_Z,
  4601. UNICODE_GC_C,
  4602. UNICODE_GC_COUNT,
  4603. } UnicodeGCEnum;
  4604. static const char unicode_gc_name_table[] =
  4605. "Cn,Unassigned" "\0"
  4606. "Lu,Uppercase_Letter" "\0"
  4607. "Ll,Lowercase_Letter" "\0"
  4608. "Lt,Titlecase_Letter" "\0"
  4609. "Lm,Modifier_Letter" "\0"
  4610. "Lo,Other_Letter" "\0"
  4611. "Mn,Nonspacing_Mark" "\0"
  4612. "Mc,Spacing_Mark" "\0"
  4613. "Me,Enclosing_Mark" "\0"
  4614. "Nd,Decimal_Number,digit" "\0"
  4615. "Nl,Letter_Number" "\0"
  4616. "No,Other_Number" "\0"
  4617. "Sm,Math_Symbol" "\0"
  4618. "Sc,Currency_Symbol" "\0"
  4619. "Sk,Modifier_Symbol" "\0"
  4620. "So,Other_Symbol" "\0"
  4621. "Pc,Connector_Punctuation" "\0"
  4622. "Pd,Dash_Punctuation" "\0"
  4623. "Ps,Open_Punctuation" "\0"
  4624. "Pe,Close_Punctuation" "\0"
  4625. "Pi,Initial_Punctuation" "\0"
  4626. "Pf,Final_Punctuation" "\0"
  4627. "Po,Other_Punctuation" "\0"
  4628. "Zs,Space_Separator" "\0"
  4629. "Zl,Line_Separator" "\0"
  4630. "Zp,Paragraph_Separator" "\0"
  4631. "Cc,Control,cntrl" "\0"
  4632. "Cf,Format" "\0"
  4633. "Cs,Surrogate" "\0"
  4634. "Co,Private_Use" "\0"
  4635. "LC,Cased_Letter" "\0"
  4636. "L,Letter" "\0"
  4637. "M,Mark,Combining_Mark" "\0"
  4638. "N,Number" "\0"
  4639. "S,Symbol" "\0"
  4640. "P,Punctuation,punct" "\0"
  4641. "Z,Separator" "\0"
  4642. "C,Other" "\0"
  4643. ;
  4644. static const uint8_t unicode_gc_table[4070] = {
  4645. 0xfa, 0x18, 0x17, 0x56, 0x0d, 0x56, 0x12, 0x13,
  4646. 0x16, 0x0c, 0x16, 0x11, 0x36, 0xe9, 0x02, 0x36,
  4647. 0x4c, 0x36, 0xe1, 0x12, 0x12, 0x16, 0x13, 0x0e,
  4648. 0x10, 0x0e, 0xe2, 0x12, 0x12, 0x0c, 0x13, 0x0c,
  4649. 0xfa, 0x19, 0x17, 0x16, 0x6d, 0x0f, 0x16, 0x0e,
  4650. 0x0f, 0x05, 0x14, 0x0c, 0x1b, 0x0f, 0x0e, 0x0f,
  4651. 0x0c, 0x2b, 0x0e, 0x02, 0x36, 0x0e, 0x0b, 0x05,
  4652. 0x15, 0x4b, 0x16, 0xe1, 0x0f, 0x0c, 0xc1, 0xe2,
  4653. 0x10, 0x0c, 0xe2, 0x00, 0xff, 0x30, 0x02, 0xff,
  4654. 0x08, 0x02, 0xff, 0x27, 0xbf, 0x22, 0x21, 0x02,
  4655. 0x5f, 0x5f, 0x21, 0x22, 0x61, 0x02, 0x21, 0x02,
  4656. 0x41, 0x42, 0x21, 0x02, 0x21, 0x02, 0x9f, 0x7f,
  4657. 0x02, 0x5f, 0x5f, 0x21, 0x02, 0x5f, 0x3f, 0x02,
  4658. 0x05, 0x3f, 0x22, 0x65, 0x01, 0x03, 0x02, 0x01,
  4659. 0x03, 0x02, 0x01, 0x03, 0x02, 0xff, 0x08, 0x02,
  4660. 0xff, 0x0a, 0x02, 0x01, 0x03, 0x02, 0x5f, 0x21,
  4661. 0x02, 0xff, 0x32, 0xa2, 0x21, 0x02, 0x21, 0x22,
  4662. 0x5f, 0x41, 0x02, 0xff, 0x00, 0xe2, 0x3c, 0x05,
  4663. 0xe2, 0x13, 0xe4, 0x0a, 0x6e, 0xe4, 0x04, 0xee,
  4664. 0x06, 0x84, 0xce, 0x04, 0x0e, 0x04, 0xee, 0x09,
  4665. 0xe6, 0x68, 0x7f, 0x04, 0x0e, 0x3f, 0x20, 0x04,
  4666. 0x42, 0x16, 0x01, 0x60, 0x2e, 0x01, 0x16, 0x41,
  4667. 0x00, 0x01, 0x00, 0x21, 0x02, 0xe1, 0x09, 0x00,
  4668. 0xe1, 0x01, 0xe2, 0x1b, 0x3f, 0x02, 0x41, 0x42,
  4669. 0xff, 0x10, 0x62, 0x3f, 0x0c, 0x5f, 0x3f, 0x02,
  4670. 0xe1, 0x2b, 0xe2, 0x28, 0xff, 0x1a, 0x0f, 0x86,
  4671. 0x28, 0xff, 0x2f, 0xff, 0x06, 0x02, 0xff, 0x58,
  4672. 0x00, 0xe1, 0x1e, 0x20, 0x04, 0xb6, 0xe2, 0x21,
  4673. 0x16, 0x11, 0x20, 0x2f, 0x0d, 0x00, 0xe6, 0x25,
  4674. 0x11, 0x06, 0x16, 0x26, 0x16, 0x26, 0x16, 0x06,
  4675. 0xe0, 0x00, 0xe5, 0x13, 0x60, 0x65, 0x36, 0xe0,
  4676. 0x03, 0xbb, 0x4c, 0x36, 0x0d, 0x36, 0x2f, 0xe6,
  4677. 0x03, 0x16, 0x1b, 0x56, 0xe5, 0x18, 0x04, 0xe5,
  4678. 0x02, 0xe6, 0x0d, 0xe9, 0x02, 0x76, 0x25, 0x06,
  4679. 0xe5, 0x5b, 0x16, 0x05, 0xc6, 0x1b, 0x0f, 0xa6,
  4680. 0x24, 0x26, 0x0f, 0x66, 0x25, 0xe9, 0x02, 0x45,
  4681. 0x2f, 0x05, 0xf6, 0x06, 0x00, 0x1b, 0x05, 0x06,
  4682. 0xe5, 0x16, 0xe6, 0x13, 0x20, 0xe5, 0x51, 0xe6,
  4683. 0x03, 0x05, 0xe0, 0x06, 0xe9, 0x02, 0xe5, 0x19,
  4684. 0xe6, 0x01, 0x24, 0x0f, 0x56, 0x04, 0x20, 0x06,
  4685. 0x2d, 0xe5, 0x0e, 0x66, 0x04, 0xe6, 0x01, 0x04,
  4686. 0x46, 0x04, 0x86, 0x20, 0xf6, 0x07, 0x00, 0xe5,
  4687. 0x11, 0x46, 0x20, 0x16, 0x00, 0xe5, 0x03, 0x80,
  4688. 0xe5, 0x10, 0x0e, 0xa5, 0x00, 0x3b, 0x80, 0xe6,
  4689. 0x01, 0xe5, 0x21, 0x04, 0xe6, 0x10, 0x1b, 0xe6,
  4690. 0x18, 0x07, 0xe5, 0x2e, 0x06, 0x07, 0x06, 0x05,
  4691. 0x47, 0xe6, 0x00, 0x67, 0x06, 0x27, 0x05, 0xc6,
  4692. 0xe5, 0x02, 0x26, 0x36, 0xe9, 0x02, 0x16, 0x04,
  4693. 0xe5, 0x07, 0x06, 0x27, 0x00, 0xe5, 0x00, 0x20,
  4694. 0x25, 0x20, 0xe5, 0x0e, 0x00, 0xc5, 0x00, 0x05,
  4695. 0x40, 0x65, 0x20, 0x06, 0x05, 0x47, 0x66, 0x20,
  4696. 0x27, 0x20, 0x27, 0x06, 0x05, 0xe0, 0x00, 0x07,
  4697. 0x60, 0x25, 0x00, 0x45, 0x26, 0x20, 0xe9, 0x02,
  4698. 0x25, 0x2d, 0xab, 0x0f, 0x0d, 0x05, 0x16, 0x06,
  4699. 0x20, 0x26, 0x07, 0x00, 0xa5, 0x60, 0x25, 0x20,
  4700. 0xe5, 0x0e, 0x00, 0xc5, 0x00, 0x25, 0x00, 0x25,
  4701. 0x00, 0x25, 0x20, 0x06, 0x00, 0x47, 0x26, 0x60,
  4702. 0x26, 0x20, 0x46, 0x40, 0x06, 0xc0, 0x65, 0x00,
  4703. 0x05, 0xc0, 0xe9, 0x02, 0x26, 0x45, 0x06, 0x16,
  4704. 0xe0, 0x02, 0x26, 0x07, 0x00, 0xe5, 0x01, 0x00,
  4705. 0x45, 0x00, 0xe5, 0x0e, 0x00, 0xc5, 0x00, 0x25,
  4706. 0x00, 0x85, 0x20, 0x06, 0x05, 0x47, 0x86, 0x00,
  4707. 0x26, 0x07, 0x00, 0x27, 0x06, 0x20, 0x05, 0xe0,
  4708. 0x07, 0x25, 0x26, 0x20, 0xe9, 0x02, 0x16, 0x0d,
  4709. 0xc0, 0x05, 0xa6, 0x00, 0x06, 0x27, 0x00, 0xe5,
  4710. 0x00, 0x20, 0x25, 0x20, 0xe5, 0x0e, 0x00, 0xc5,
  4711. 0x00, 0x25, 0x00, 0x85, 0x20, 0x06, 0x05, 0x07,
  4712. 0x06, 0x07, 0x66, 0x20, 0x27, 0x20, 0x27, 0x06,
  4713. 0xc0, 0x26, 0x07, 0x60, 0x25, 0x00, 0x45, 0x26,
  4714. 0x20, 0xe9, 0x02, 0x0f, 0x05, 0xab, 0xe0, 0x02,
  4715. 0x06, 0x05, 0x00, 0xa5, 0x40, 0x45, 0x00, 0x65,
  4716. 0x40, 0x25, 0x00, 0x05, 0x00, 0x25, 0x40, 0x25,
  4717. 0x40, 0x45, 0x40, 0xe5, 0x04, 0x60, 0x27, 0x06,
  4718. 0x27, 0x40, 0x47, 0x00, 0x47, 0x06, 0x20, 0x05,
  4719. 0xa0, 0x07, 0xe0, 0x06, 0xe9, 0x02, 0x4b, 0xaf,
  4720. 0x0d, 0x0f, 0x80, 0x06, 0x47, 0x06, 0xe5, 0x00,
  4721. 0x00, 0x45, 0x00, 0xe5, 0x0f, 0x00, 0xe5, 0x08,
  4722. 0x20, 0x06, 0x05, 0x46, 0x67, 0x00, 0x46, 0x00,
  4723. 0x66, 0xc0, 0x26, 0x00, 0x45, 0x20, 0x05, 0x20,
  4724. 0x25, 0x26, 0x20, 0xe9, 0x02, 0xc0, 0x16, 0xcb,
  4725. 0x0f, 0x05, 0x06, 0x27, 0x16, 0xe5, 0x00, 0x00,
  4726. 0x45, 0x00, 0xe5, 0x0f, 0x00, 0xe5, 0x02, 0x00,
  4727. 0x85, 0x20, 0x06, 0x05, 0x07, 0x06, 0x87, 0x00,
  4728. 0x06, 0x27, 0x00, 0x27, 0x26, 0xc0, 0x27, 0xa0,
  4729. 0x25, 0x00, 0x25, 0x26, 0x20, 0xe9, 0x02, 0x00,
  4730. 0x25, 0x07, 0xe0, 0x04, 0x26, 0x27, 0xe5, 0x01,
  4731. 0x00, 0x45, 0x00, 0xe5, 0x21, 0x26, 0x05, 0x47,
  4732. 0x66, 0x00, 0x47, 0x00, 0x47, 0x06, 0x05, 0x0f,
  4733. 0x60, 0x45, 0x07, 0xcb, 0x45, 0x26, 0x20, 0xe9,
  4734. 0x02, 0xeb, 0x01, 0x0f, 0xa5, 0x00, 0x06, 0x27,
  4735. 0x00, 0xe5, 0x0a, 0x40, 0xe5, 0x10, 0x00, 0xe5,
  4736. 0x01, 0x00, 0x05, 0x20, 0xc5, 0x40, 0x06, 0x60,
  4737. 0x47, 0x46, 0x00, 0x06, 0x00, 0xe7, 0x00, 0xa0,
  4738. 0xe9, 0x02, 0x20, 0x27, 0x16, 0xe0, 0x04, 0xe5,
  4739. 0x28, 0x06, 0x25, 0xc6, 0x60, 0x0d, 0xa5, 0x04,
  4740. 0xe6, 0x00, 0x16, 0xe9, 0x02, 0x36, 0xe0, 0x1d,
  4741. 0x25, 0x00, 0x05, 0x00, 0x85, 0x00, 0xe5, 0x10,
  4742. 0x00, 0x05, 0x00, 0xe5, 0x02, 0x06, 0x25, 0xe6,
  4743. 0x01, 0x05, 0x20, 0x85, 0x00, 0x04, 0x00, 0xc6,
  4744. 0x00, 0xe9, 0x02, 0x20, 0x65, 0xe0, 0x18, 0x05,
  4745. 0x4f, 0xf6, 0x07, 0x0f, 0x16, 0x4f, 0x26, 0xaf,
  4746. 0xe9, 0x02, 0xeb, 0x02, 0x0f, 0x06, 0x0f, 0x06,
  4747. 0x0f, 0x06, 0x12, 0x13, 0x12, 0x13, 0x27, 0xe5,
  4748. 0x00, 0x00, 0xe5, 0x1c, 0x60, 0xe6, 0x06, 0x07,
  4749. 0x86, 0x16, 0x26, 0x85, 0xe6, 0x03, 0x00, 0xe6,
  4750. 0x1c, 0x00, 0xef, 0x00, 0x06, 0xaf, 0x00, 0x2f,
  4751. 0x96, 0x6f, 0x36, 0xe0, 0x1d, 0xe5, 0x23, 0x27,
  4752. 0x66, 0x07, 0xa6, 0x07, 0x26, 0x27, 0x26, 0x05,
  4753. 0xe9, 0x02, 0xb6, 0xa5, 0x27, 0x26, 0x65, 0x46,
  4754. 0x05, 0x47, 0x25, 0xc7, 0x45, 0x66, 0xe5, 0x05,
  4755. 0x06, 0x27, 0x26, 0xa7, 0x06, 0x05, 0x07, 0xe9,
  4756. 0x02, 0x47, 0x06, 0x2f, 0xe1, 0x1e, 0x00, 0x01,
  4757. 0x80, 0x01, 0x20, 0xe2, 0x23, 0x16, 0x04, 0x42,
  4758. 0xe5, 0x80, 0xc1, 0x00, 0x65, 0x20, 0xc5, 0x00,
  4759. 0x05, 0x00, 0x65, 0x20, 0xe5, 0x21, 0x00, 0x65,
  4760. 0x20, 0xe5, 0x19, 0x00, 0x65, 0x20, 0xc5, 0x00,
  4761. 0x05, 0x00, 0x65, 0x20, 0xe5, 0x07, 0x00, 0xe5,
  4762. 0x31, 0x00, 0x65, 0x20, 0xe5, 0x3b, 0x20, 0x46,
  4763. 0xf6, 0x01, 0xeb, 0x0c, 0x40, 0xe5, 0x08, 0xef,
  4764. 0x02, 0xa0, 0xe1, 0x4e, 0x20, 0xa2, 0x20, 0x11,
  4765. 0xe5, 0x81, 0xe4, 0x0f, 0x16, 0xe5, 0x09, 0x17,
  4766. 0xe5, 0x12, 0x12, 0x13, 0x40, 0xe5, 0x43, 0x56,
  4767. 0x4a, 0xe5, 0x00, 0xc0, 0xe5, 0x0a, 0x46, 0x07,
  4768. 0xe0, 0x01, 0xe5, 0x0b, 0x26, 0x07, 0x36, 0xe0,
  4769. 0x01, 0xe5, 0x0a, 0x26, 0xe0, 0x04, 0xe5, 0x05,
  4770. 0x00, 0x45, 0x00, 0x26, 0xe0, 0x04, 0xe5, 0x2c,
  4771. 0x26, 0x07, 0xc6, 0xe7, 0x00, 0x06, 0x27, 0xe6,
  4772. 0x03, 0x56, 0x04, 0x56, 0x0d, 0x05, 0x06, 0x20,
  4773. 0xe9, 0x02, 0xa0, 0xeb, 0x02, 0xa0, 0xb6, 0x11,
  4774. 0x76, 0x46, 0x1b, 0x06, 0xe9, 0x02, 0xa0, 0xe5,
  4775. 0x1b, 0x04, 0xe5, 0x2d, 0xc0, 0x85, 0x26, 0xe5,
  4776. 0x1a, 0x06, 0x05, 0x80, 0xe5, 0x3e, 0xe0, 0x02,
  4777. 0xe5, 0x17, 0x00, 0x46, 0x67, 0x26, 0x47, 0x60,
  4778. 0x27, 0x06, 0xa7, 0x46, 0x60, 0x0f, 0x40, 0x36,
  4779. 0xe9, 0x02, 0xe5, 0x16, 0x20, 0x85, 0xe0, 0x03,
  4780. 0xe5, 0x24, 0x60, 0xe5, 0x12, 0xa0, 0xe9, 0x02,
  4781. 0x0b, 0x40, 0xef, 0x1a, 0xe5, 0x0f, 0x26, 0x27,
  4782. 0x06, 0x20, 0x36, 0xe5, 0x2d, 0x07, 0x06, 0x07,
  4783. 0xc6, 0x00, 0x06, 0x07, 0x06, 0x27, 0xe6, 0x00,
  4784. 0xa7, 0xe6, 0x02, 0x20, 0x06, 0xe9, 0x02, 0xa0,
  4785. 0xe9, 0x02, 0xa0, 0xd6, 0x04, 0xb6, 0x20, 0xe6,
  4786. 0x06, 0x08, 0xe6, 0x08, 0xe0, 0x29, 0x66, 0x07,
  4787. 0xe5, 0x27, 0x06, 0x07, 0x86, 0x07, 0x06, 0x87,
  4788. 0x06, 0x27, 0xe5, 0x00, 0x00, 0x36, 0xe9, 0x02,
  4789. 0xd6, 0xef, 0x02, 0xe6, 0x01, 0xef, 0x01, 0x56,
  4790. 0x26, 0x07, 0xe5, 0x16, 0x07, 0x66, 0x27, 0x26,
  4791. 0x07, 0x46, 0x25, 0xe9, 0x02, 0xe5, 0x24, 0x06,
  4792. 0x07, 0x26, 0x47, 0x06, 0x07, 0x46, 0x27, 0xe0,
  4793. 0x00, 0x76, 0xe5, 0x1c, 0xe7, 0x00, 0xe6, 0x00,
  4794. 0x27, 0x26, 0x40, 0x96, 0xe9, 0x02, 0x40, 0x45,
  4795. 0xe9, 0x02, 0xe5, 0x16, 0xa4, 0x36, 0xe2, 0x01,
  4796. 0x3f, 0x80, 0xe1, 0x23, 0x20, 0x41, 0xf6, 0x00,
  4797. 0xe0, 0x00, 0x46, 0x16, 0xe6, 0x05, 0x07, 0xc6,
  4798. 0x65, 0x06, 0xa5, 0x06, 0x25, 0x07, 0x26, 0x05,
  4799. 0x80, 0xe2, 0x24, 0xe4, 0x37, 0xe2, 0x05, 0x04,
  4800. 0xe2, 0x1a, 0xe4, 0x1d, 0xe6, 0x38, 0xff, 0x80,
  4801. 0x0e, 0xe2, 0x00, 0xff, 0x5a, 0xe2, 0x00, 0xe1,
  4802. 0x00, 0xa2, 0x20, 0xa1, 0x20, 0xe2, 0x00, 0xe1,
  4803. 0x00, 0xe2, 0x00, 0xe1, 0x00, 0xa2, 0x20, 0xa1,
  4804. 0x20, 0xe2, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00,
  4805. 0x01, 0x00, 0x3f, 0xc2, 0xe1, 0x00, 0xe2, 0x06,
  4806. 0x20, 0xe2, 0x00, 0xe3, 0x00, 0xe2, 0x00, 0xe3,
  4807. 0x00, 0xe2, 0x00, 0xe3, 0x00, 0x82, 0x00, 0x22,
  4808. 0x61, 0x03, 0x0e, 0x02, 0x4e, 0x42, 0x00, 0x22,
  4809. 0x61, 0x03, 0x4e, 0x62, 0x20, 0x22, 0x61, 0x00,
  4810. 0x4e, 0xe2, 0x00, 0x81, 0x4e, 0x20, 0x42, 0x00,
  4811. 0x22, 0x61, 0x03, 0x2e, 0x00, 0xf7, 0x03, 0x9b,
  4812. 0xb1, 0x36, 0x14, 0x15, 0x12, 0x34, 0x15, 0x12,
  4813. 0x14, 0xf6, 0x00, 0x18, 0x19, 0x9b, 0x17, 0xf6,
  4814. 0x01, 0x14, 0x15, 0x76, 0x30, 0x56, 0x0c, 0x12,
  4815. 0x13, 0xf6, 0x03, 0x0c, 0x16, 0x10, 0xf6, 0x02,
  4816. 0x17, 0x9b, 0x00, 0xfb, 0x02, 0x0b, 0x04, 0x20,
  4817. 0xab, 0x4c, 0x12, 0x13, 0x04, 0xeb, 0x02, 0x4c,
  4818. 0x12, 0x13, 0x00, 0xe4, 0x05, 0x40, 0xed, 0x19,
  4819. 0xe0, 0x07, 0xe6, 0x05, 0x68, 0x06, 0x48, 0xe6,
  4820. 0x04, 0xe0, 0x07, 0x2f, 0x01, 0x6f, 0x01, 0x2f,
  4821. 0x02, 0x41, 0x22, 0x41, 0x02, 0x0f, 0x01, 0x2f,
  4822. 0x0c, 0x81, 0xaf, 0x01, 0x0f, 0x01, 0x0f, 0x01,
  4823. 0x0f, 0x61, 0x0f, 0x02, 0x61, 0x02, 0x65, 0x02,
  4824. 0x2f, 0x22, 0x21, 0x8c, 0x3f, 0x42, 0x0f, 0x0c,
  4825. 0x2f, 0x02, 0x0f, 0xeb, 0x08, 0xea, 0x1b, 0x3f,
  4826. 0x6a, 0x0b, 0x2f, 0x60, 0x8c, 0x8f, 0x2c, 0x6f,
  4827. 0x0c, 0x2f, 0x0c, 0x2f, 0x0c, 0xcf, 0x0c, 0xef,
  4828. 0x17, 0x2c, 0x2f, 0x0c, 0x0f, 0x0c, 0xef, 0x17,
  4829. 0xec, 0x80, 0x84, 0xef, 0x00, 0x12, 0x13, 0x12,
  4830. 0x13, 0xef, 0x0c, 0x2c, 0xcf, 0x12, 0x13, 0xef,
  4831. 0x49, 0x0c, 0xef, 0x16, 0xec, 0x11, 0xef, 0x20,
  4832. 0xac, 0xef, 0x40, 0xe0, 0x0e, 0xef, 0x03, 0xe0,
  4833. 0x0d, 0xeb, 0x34, 0xef, 0x46, 0xeb, 0x0e, 0xef,
  4834. 0x80, 0x2f, 0x0c, 0xef, 0x01, 0x0c, 0xef, 0x2e,
  4835. 0xec, 0x00, 0xef, 0x67, 0x0c, 0xef, 0x80, 0x70,
  4836. 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13,
  4837. 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0xeb, 0x16,
  4838. 0xef, 0x24, 0x8c, 0x12, 0x13, 0xec, 0x17, 0x12,
  4839. 0x13, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x12,
  4840. 0x13, 0xec, 0x08, 0xef, 0x80, 0x78, 0xec, 0x7b,
  4841. 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13,
  4842. 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13,
  4843. 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0xec, 0x37,
  4844. 0x12, 0x13, 0x12, 0x13, 0xec, 0x18, 0x12, 0x13,
  4845. 0xec, 0x80, 0x7a, 0xef, 0x28, 0xec, 0x0d, 0x2f,
  4846. 0xac, 0xef, 0x1f, 0x20, 0xef, 0x18, 0x00, 0xef,
  4847. 0x61, 0xe1, 0x28, 0xe2, 0x28, 0x5f, 0x21, 0x22,
  4848. 0xdf, 0x41, 0x02, 0x3f, 0x02, 0x3f, 0x82, 0x24,
  4849. 0x41, 0x02, 0xff, 0x5a, 0x02, 0xaf, 0x7f, 0x46,
  4850. 0x3f, 0x80, 0x76, 0x0b, 0x36, 0xe2, 0x1e, 0x00,
  4851. 0x02, 0x80, 0x02, 0x20, 0xe5, 0x30, 0xc0, 0x04,
  4852. 0x16, 0xe0, 0x06, 0x06, 0xe5, 0x0f, 0xe0, 0x01,
  4853. 0xc5, 0x00, 0xc5, 0x00, 0xc5, 0x00, 0xc5, 0x00,
  4854. 0xc5, 0x00, 0xc5, 0x00, 0xc5, 0x00, 0xc5, 0x00,
  4855. 0xe6, 0x18, 0x36, 0x14, 0x15, 0x14, 0x15, 0x56,
  4856. 0x14, 0x15, 0x16, 0x14, 0x15, 0xf6, 0x01, 0x11,
  4857. 0x36, 0x11, 0x16, 0x14, 0x15, 0x36, 0x14, 0x15,
  4858. 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13,
  4859. 0x96, 0x04, 0xf6, 0x02, 0x31, 0x76, 0x11, 0x16,
  4860. 0x12, 0xf6, 0x05, 0x2f, 0x56, 0x12, 0x13, 0x12,
  4861. 0x13, 0x12, 0x13, 0x12, 0x13, 0x11, 0xe0, 0x1a,
  4862. 0xef, 0x12, 0x00, 0xef, 0x51, 0xe0, 0x04, 0xef,
  4863. 0x80, 0x4e, 0xe0, 0x12, 0xef, 0x08, 0x17, 0x56,
  4864. 0x0f, 0x04, 0x05, 0x0a, 0x12, 0x13, 0x12, 0x13,
  4865. 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x2f, 0x12,
  4866. 0x13, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x11,
  4867. 0x12, 0x33, 0x0f, 0xea, 0x01, 0x66, 0x27, 0x11,
  4868. 0x84, 0x2f, 0x4a, 0x04, 0x05, 0x16, 0x2f, 0x00,
  4869. 0xe5, 0x4e, 0x20, 0x26, 0x2e, 0x24, 0x05, 0x11,
  4870. 0xe5, 0x52, 0x16, 0x44, 0x05, 0x80, 0xe5, 0x23,
  4871. 0x00, 0xe5, 0x56, 0x00, 0x2f, 0x6b, 0xef, 0x02,
  4872. 0xe5, 0x18, 0xef, 0x1e, 0xe0, 0x01, 0x0f, 0xe5,
  4873. 0x08, 0xef, 0x17, 0x00, 0xeb, 0x02, 0xef, 0x16,
  4874. 0xeb, 0x00, 0x0f, 0xeb, 0x07, 0xef, 0x18, 0xeb,
  4875. 0x02, 0xef, 0x1f, 0xeb, 0x07, 0xef, 0x80, 0xb8,
  4876. 0xe5, 0x99, 0x38, 0xef, 0x38, 0xe5, 0xc0, 0x11,
  4877. 0x8d, 0x04, 0xe5, 0x83, 0xef, 0x40, 0xef, 0x2f,
  4878. 0xe0, 0x01, 0xe5, 0x20, 0xa4, 0x36, 0xe5, 0x80,
  4879. 0x84, 0x04, 0x56, 0xe5, 0x08, 0xe9, 0x02, 0x25,
  4880. 0xe0, 0x0c, 0xff, 0x26, 0x05, 0x06, 0x48, 0x16,
  4881. 0xe6, 0x02, 0x16, 0x04, 0xff, 0x14, 0x24, 0x26,
  4882. 0xe5, 0x3e, 0xea, 0x02, 0x26, 0xb6, 0xe0, 0x00,
  4883. 0xee, 0x0f, 0xe4, 0x01, 0x2e, 0xff, 0x06, 0x22,
  4884. 0xff, 0x36, 0x04, 0xe2, 0x00, 0x9f, 0xff, 0x02,
  4885. 0x04, 0x2e, 0x7f, 0x05, 0x7f, 0x22, 0xff, 0x0d,
  4886. 0x61, 0x02, 0x81, 0x02, 0xff, 0x07, 0x41, 0x02,
  4887. 0x5f, 0x3f, 0x20, 0x3f, 0x00, 0x02, 0x00, 0x02,
  4888. 0xdf, 0xe0, 0x0d, 0x44, 0x3f, 0x05, 0x24, 0x02,
  4889. 0xc5, 0x06, 0x45, 0x06, 0x65, 0x06, 0xe5, 0x0f,
  4890. 0x27, 0x26, 0x07, 0x6f, 0x06, 0x40, 0xab, 0x2f,
  4891. 0x0d, 0x0f, 0xa0, 0xe5, 0x2c, 0x76, 0xe0, 0x00,
  4892. 0x27, 0xe5, 0x2a, 0xe7, 0x08, 0x26, 0xe0, 0x00,
  4893. 0x36, 0xe9, 0x02, 0xa0, 0xe6, 0x0a, 0xa5, 0x56,
  4894. 0x05, 0x16, 0x25, 0x06, 0xe9, 0x02, 0xe5, 0x14,
  4895. 0xe6, 0x00, 0x36, 0xe5, 0x0f, 0xe6, 0x03, 0x27,
  4896. 0xe0, 0x03, 0x16, 0xe5, 0x15, 0x40, 0x46, 0x07,
  4897. 0xe5, 0x27, 0x06, 0x27, 0x66, 0x27, 0x26, 0x47,
  4898. 0xf6, 0x05, 0x00, 0x04, 0xe9, 0x02, 0x60, 0x36,
  4899. 0x85, 0x06, 0x04, 0xe5, 0x01, 0xe9, 0x02, 0x85,
  4900. 0x00, 0xe5, 0x21, 0xa6, 0x27, 0x26, 0x27, 0x26,
  4901. 0xe0, 0x01, 0x45, 0x06, 0xe5, 0x00, 0x06, 0x07,
  4902. 0x20, 0xe9, 0x02, 0x20, 0x76, 0xe5, 0x08, 0x04,
  4903. 0xa5, 0x4f, 0x05, 0x07, 0x06, 0x07, 0xe5, 0x2a,
  4904. 0x06, 0x05, 0x46, 0x25, 0x26, 0x85, 0x26, 0x05,
  4905. 0x06, 0x05, 0xe0, 0x10, 0x25, 0x04, 0x36, 0xe5,
  4906. 0x03, 0x07, 0x26, 0x27, 0x36, 0x05, 0x24, 0x07,
  4907. 0x06, 0xe0, 0x02, 0xa5, 0x20, 0xa5, 0x20, 0xa5,
  4908. 0xe0, 0x01, 0xc5, 0x00, 0xc5, 0x00, 0xe2, 0x23,
  4909. 0x0e, 0x64, 0xe2, 0x01, 0x04, 0x2e, 0x60, 0xe2,
  4910. 0x48, 0xe5, 0x1b, 0x27, 0x06, 0x27, 0x06, 0x27,
  4911. 0x16, 0x07, 0x06, 0x20, 0xe9, 0x02, 0xa0, 0xe5,
  4912. 0xab, 0x1c, 0xe0, 0x04, 0xe5, 0x0f, 0x60, 0xe5,
  4913. 0x29, 0x60, 0xfc, 0x87, 0x78, 0xfd, 0x98, 0x78,
  4914. 0xe5, 0x80, 0xe6, 0x20, 0xe5, 0x62, 0xe0, 0x1e,
  4915. 0xc2, 0xe0, 0x04, 0x82, 0x80, 0x05, 0x06, 0xe5,
  4916. 0x02, 0x0c, 0xe5, 0x05, 0x00, 0x85, 0x00, 0x05,
  4917. 0x00, 0x25, 0x00, 0x25, 0x00, 0xe5, 0x64, 0xee,
  4918. 0x09, 0xe0, 0x08, 0xe5, 0x80, 0xe3, 0x13, 0x12,
  4919. 0xef, 0x08, 0xe5, 0x38, 0x20, 0xe5, 0x2e, 0xc0,
  4920. 0x0f, 0xe0, 0x18, 0xe5, 0x04, 0x0d, 0x4f, 0xe6,
  4921. 0x08, 0xd6, 0x12, 0x13, 0x16, 0xa0, 0xe6, 0x08,
  4922. 0x16, 0x31, 0x30, 0x12, 0x13, 0x12, 0x13, 0x12,
  4923. 0x13, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x12,
  4924. 0x13, 0x12, 0x13, 0x36, 0x12, 0x13, 0x76, 0x50,
  4925. 0x56, 0x00, 0x76, 0x11, 0x12, 0x13, 0x12, 0x13,
  4926. 0x12, 0x13, 0x56, 0x0c, 0x11, 0x4c, 0x00, 0x16,
  4927. 0x0d, 0x36, 0x60, 0x85, 0x00, 0xe5, 0x7f, 0x20,
  4928. 0x1b, 0x00, 0x56, 0x0d, 0x56, 0x12, 0x13, 0x16,
  4929. 0x0c, 0x16, 0x11, 0x36, 0xe9, 0x02, 0x36, 0x4c,
  4930. 0x36, 0xe1, 0x12, 0x12, 0x16, 0x13, 0x0e, 0x10,
  4931. 0x0e, 0xe2, 0x12, 0x12, 0x0c, 0x13, 0x0c, 0x12,
  4932. 0x13, 0x16, 0x12, 0x13, 0x36, 0xe5, 0x02, 0x04,
  4933. 0xe5, 0x25, 0x24, 0xe5, 0x17, 0x40, 0xa5, 0x20,
  4934. 0xa5, 0x20, 0xa5, 0x20, 0x45, 0x40, 0x2d, 0x0c,
  4935. 0x0e, 0x0f, 0x2d, 0x00, 0x0f, 0x6c, 0x2f, 0xe0,
  4936. 0x02, 0x5b, 0x2f, 0x20, 0xe5, 0x04, 0x00, 0xe5,
  4937. 0x12, 0x00, 0xe5, 0x0b, 0x00, 0x25, 0x00, 0xe5,
  4938. 0x07, 0x20, 0xe5, 0x06, 0xe0, 0x1a, 0xe5, 0x73,
  4939. 0x80, 0x56, 0x60, 0xeb, 0x25, 0x40, 0xef, 0x01,
  4940. 0xea, 0x2d, 0x6b, 0xef, 0x09, 0x2b, 0x4f, 0x00,
  4941. 0xef, 0x05, 0x40, 0x0f, 0xe0, 0x27, 0xef, 0x25,
  4942. 0x06, 0xe0, 0x7a, 0xe5, 0x15, 0x40, 0xe5, 0x29,
  4943. 0xe0, 0x07, 0x06, 0xeb, 0x13, 0x60, 0xe5, 0x18,
  4944. 0x6b, 0xe0, 0x01, 0xe5, 0x0c, 0x0a, 0xe5, 0x00,
  4945. 0x0a, 0x80, 0xe5, 0x1e, 0x86, 0x80, 0xe5, 0x16,
  4946. 0x00, 0x16, 0xe5, 0x1c, 0x60, 0xe5, 0x00, 0x16,
  4947. 0x8a, 0xe0, 0x22, 0xe1, 0x20, 0xe2, 0x20, 0xe5,
  4948. 0x46, 0x20, 0xe9, 0x02, 0xa0, 0xe1, 0x1c, 0x60,
  4949. 0xe2, 0x1c, 0x60, 0xe5, 0x20, 0xe0, 0x00, 0xe5,
  4950. 0x2c, 0xe0, 0x03, 0x16, 0xe1, 0x03, 0x00, 0xe1,
  4951. 0x07, 0x00, 0xc1, 0x00, 0x21, 0x00, 0xe2, 0x03,
  4952. 0x00, 0xe2, 0x07, 0x00, 0xc2, 0x00, 0x22, 0x40,
  4953. 0xe5, 0x2c, 0xe0, 0x04, 0xe5, 0x80, 0xaf, 0xe0,
  4954. 0x01, 0xe5, 0x0e, 0xe0, 0x02, 0xe5, 0x00, 0xe0,
  4955. 0x10, 0xa4, 0x00, 0xe4, 0x22, 0x00, 0xe4, 0x01,
  4956. 0xe0, 0x3d, 0xa5, 0x20, 0x05, 0x00, 0xe5, 0x24,
  4957. 0x00, 0x25, 0x40, 0x05, 0x20, 0xe5, 0x0f, 0x00,
  4958. 0x16, 0xeb, 0x00, 0xe5, 0x0f, 0x2f, 0xcb, 0xe5,
  4959. 0x17, 0xe0, 0x00, 0xeb, 0x01, 0xe0, 0x28, 0xe5,
  4960. 0x0b, 0x00, 0x25, 0x80, 0x8b, 0xe5, 0x0e, 0xab,
  4961. 0x40, 0x16, 0xe5, 0x12, 0x80, 0x16, 0xe0, 0x38,
  4962. 0xe5, 0x30, 0x60, 0x2b, 0x25, 0xeb, 0x08, 0x20,
  4963. 0xeb, 0x26, 0x05, 0x46, 0x00, 0x26, 0x80, 0x66,
  4964. 0x65, 0x00, 0x45, 0x00, 0xe5, 0x15, 0x20, 0x46,
  4965. 0x60, 0x06, 0xeb, 0x01, 0xc0, 0xf6, 0x01, 0xc0,
  4966. 0xe5, 0x15, 0x2b, 0x16, 0xe5, 0x15, 0x4b, 0xe0,
  4967. 0x18, 0xe5, 0x00, 0x0f, 0xe5, 0x14, 0x26, 0x60,
  4968. 0x8b, 0xd6, 0xe0, 0x01, 0xe5, 0x2e, 0x40, 0xd6,
  4969. 0xe5, 0x0e, 0x20, 0xeb, 0x00, 0xe5, 0x0b, 0x80,
  4970. 0xeb, 0x00, 0xe5, 0x0a, 0xc0, 0x76, 0xe0, 0x04,
  4971. 0xcb, 0xe0, 0x48, 0xe5, 0x41, 0xe0, 0x2f, 0xe1,
  4972. 0x2b, 0xe0, 0x05, 0xe2, 0x2b, 0xc0, 0xab, 0xe5,
  4973. 0x1c, 0x66, 0xe0, 0x00, 0xe9, 0x02, 0xa0, 0xe9,
  4974. 0x02, 0x65, 0x04, 0x05, 0xe1, 0x0e, 0x40, 0x86,
  4975. 0x11, 0x04, 0xe2, 0x0e, 0xe0, 0x00, 0x2c, 0xe0,
  4976. 0x80, 0x48, 0xeb, 0x17, 0x00, 0xe5, 0x22, 0x00,
  4977. 0x26, 0x11, 0x20, 0x25, 0xe0, 0x08, 0x45, 0xe0,
  4978. 0x2f, 0x66, 0xe5, 0x15, 0xeb, 0x02, 0x05, 0xe0,
  4979. 0x00, 0xe5, 0x0e, 0xe6, 0x03, 0x6b, 0x96, 0xe0,
  4980. 0x0e, 0xe5, 0x0a, 0x66, 0x76, 0xe0, 0x1e, 0xe5,
  4981. 0x0d, 0xcb, 0xe0, 0x0c, 0xe5, 0x0f, 0xe0, 0x01,
  4982. 0x07, 0x06, 0x07, 0xe5, 0x2d, 0xe6, 0x07, 0xd6,
  4983. 0x60, 0xeb, 0x0c, 0xe9, 0x02, 0x06, 0x25, 0x26,
  4984. 0x05, 0xe0, 0x01, 0x46, 0x07, 0xe5, 0x25, 0x47,
  4985. 0x66, 0x27, 0x26, 0x36, 0x1b, 0x76, 0x06, 0xe0,
  4986. 0x02, 0x1b, 0x20, 0xe5, 0x11, 0xc0, 0xe9, 0x02,
  4987. 0xa0, 0x46, 0xe5, 0x1c, 0x86, 0x07, 0xe6, 0x00,
  4988. 0x00, 0xe9, 0x02, 0x76, 0x05, 0x27, 0x05, 0xe0,
  4989. 0x00, 0xe5, 0x1b, 0x06, 0x36, 0x05, 0xe0, 0x01,
  4990. 0x26, 0x07, 0xe5, 0x28, 0x47, 0xe6, 0x01, 0x27,
  4991. 0x65, 0x76, 0x66, 0x16, 0x07, 0x06, 0xe9, 0x02,
  4992. 0x05, 0x16, 0x05, 0x56, 0x00, 0xeb, 0x0c, 0xe0,
  4993. 0x03, 0xe5, 0x0a, 0x00, 0xe5, 0x11, 0x47, 0x46,
  4994. 0x27, 0x06, 0x07, 0x26, 0xb6, 0x06, 0x25, 0x06,
  4995. 0xe0, 0x36, 0xc5, 0x00, 0x05, 0x00, 0x65, 0x00,
  4996. 0xe5, 0x07, 0x00, 0xe5, 0x02, 0x16, 0xa0, 0xe5,
  4997. 0x27, 0x06, 0x47, 0xe6, 0x00, 0x80, 0xe9, 0x02,
  4998. 0xa0, 0x26, 0x27, 0x00, 0xe5, 0x00, 0x20, 0x25,
  4999. 0x20, 0xe5, 0x0e, 0x00, 0xc5, 0x00, 0x25, 0x00,
  5000. 0x85, 0x00, 0x26, 0x05, 0x27, 0x06, 0x67, 0x20,
  5001. 0x27, 0x20, 0x47, 0x20, 0x05, 0xa0, 0x07, 0x80,
  5002. 0x85, 0x27, 0x20, 0xc6, 0x40, 0x86, 0xe0, 0x03,
  5003. 0xe5, 0x02, 0x00, 0x05, 0x20, 0x05, 0x00, 0xe5,
  5004. 0x1e, 0x00, 0x05, 0x47, 0xa6, 0x00, 0x07, 0x20,
  5005. 0x07, 0x00, 0x67, 0x00, 0x27, 0x06, 0x07, 0x06,
  5006. 0x05, 0x06, 0x05, 0x36, 0x00, 0x36, 0xe0, 0x00,
  5007. 0x26, 0xe0, 0x15, 0xe5, 0x2d, 0x47, 0xe6, 0x00,
  5008. 0x27, 0x46, 0x07, 0x06, 0x65, 0x96, 0xe9, 0x02,
  5009. 0x36, 0x00, 0x16, 0x06, 0x45, 0xe0, 0x16, 0xe5,
  5010. 0x28, 0x47, 0xa6, 0x07, 0x06, 0x67, 0x26, 0x07,
  5011. 0x26, 0x25, 0x16, 0x05, 0xe0, 0x00, 0xe9, 0x02,
  5012. 0xe0, 0x80, 0x1e, 0xe5, 0x27, 0x47, 0x66, 0x20,
  5013. 0x67, 0x26, 0x07, 0x26, 0xf6, 0x0f, 0x65, 0x26,
  5014. 0xe0, 0x1a, 0xe5, 0x28, 0x47, 0xe6, 0x00, 0x27,
  5015. 0x06, 0x07, 0x26, 0x56, 0x05, 0xe0, 0x03, 0xe9,
  5016. 0x02, 0xa0, 0xf6, 0x05, 0xe0, 0x0b, 0xe5, 0x23,
  5017. 0x06, 0x07, 0x06, 0x27, 0xa6, 0x07, 0x06, 0x05,
  5018. 0x16, 0xa0, 0xe9, 0x02, 0xa0, 0xe9, 0x0c, 0xe0,
  5019. 0x14, 0xe5, 0x13, 0x20, 0x06, 0x07, 0x06, 0x27,
  5020. 0x66, 0x07, 0x86, 0x60, 0xe9, 0x02, 0x2b, 0x56,
  5021. 0x0f, 0xc5, 0xe0, 0x80, 0x31, 0xe5, 0x24, 0x47,
  5022. 0xe6, 0x01, 0x07, 0x26, 0x16, 0xe0, 0x5c, 0xe1,
  5023. 0x18, 0xe2, 0x18, 0xe9, 0x02, 0xeb, 0x01, 0xe0,
  5024. 0x04, 0xe5, 0x00, 0x20, 0x05, 0x20, 0xe5, 0x00,
  5025. 0x00, 0x25, 0x00, 0xe5, 0x10, 0xa7, 0x00, 0x27,
  5026. 0x20, 0x26, 0x07, 0x06, 0x05, 0x07, 0x05, 0x07,
  5027. 0x06, 0x56, 0xe0, 0x01, 0xe9, 0x02, 0xe0, 0x3e,
  5028. 0xe5, 0x00, 0x20, 0xe5, 0x1f, 0x47, 0x66, 0x20,
  5029. 0x26, 0x67, 0x06, 0x05, 0x16, 0x05, 0x07, 0xe0,
  5030. 0x13, 0x05, 0xe6, 0x02, 0xe5, 0x20, 0xa6, 0x07,
  5031. 0x05, 0x66, 0xf6, 0x00, 0x06, 0xe0, 0x00, 0x05,
  5032. 0xa6, 0x27, 0x46, 0xe5, 0x26, 0xe6, 0x05, 0x07,
  5033. 0x26, 0x56, 0x05, 0x96, 0xe0, 0x05, 0xe5, 0x41,
  5034. 0xc0, 0xf6, 0x02, 0xe0, 0x80, 0x2e, 0xe5, 0x19,
  5035. 0x16, 0xe0, 0x06, 0xe9, 0x02, 0xa0, 0xe5, 0x01,
  5036. 0x00, 0xe5, 0x1d, 0x07, 0xc6, 0x00, 0xa6, 0x07,
  5037. 0x06, 0x05, 0x96, 0xe0, 0x02, 0xe9, 0x02, 0xeb,
  5038. 0x0b, 0x40, 0x36, 0xe5, 0x16, 0x20, 0xe6, 0x0e,
  5039. 0x00, 0x07, 0xc6, 0x07, 0x26, 0x07, 0x26, 0xe0,
  5040. 0x41, 0xc5, 0x00, 0x25, 0x00, 0xe5, 0x1e, 0xa6,
  5041. 0x40, 0x06, 0x00, 0x26, 0x00, 0xc6, 0x05, 0x06,
  5042. 0xe0, 0x00, 0xe9, 0x02, 0xa0, 0xa5, 0x00, 0x25,
  5043. 0x00, 0xe5, 0x18, 0x87, 0x00, 0x26, 0x00, 0x27,
  5044. 0x06, 0x07, 0x06, 0x05, 0xc0, 0xe9, 0x02, 0xe0,
  5045. 0x80, 0xae, 0xe5, 0x0b, 0x26, 0x27, 0x36, 0xc0,
  5046. 0x26, 0x05, 0x07, 0xe5, 0x05, 0x00, 0xe5, 0x1a,
  5047. 0x27, 0x86, 0x40, 0x27, 0x06, 0x07, 0x06, 0xf6,
  5048. 0x05, 0xe9, 0x02, 0x06, 0xe0, 0x4d, 0x05, 0xe0,
  5049. 0x07, 0xeb, 0x0d, 0xef, 0x00, 0x6d, 0xef, 0x09,
  5050. 0xe0, 0x05, 0x16, 0xe5, 0x83, 0x12, 0xe0, 0x5e,
  5051. 0xea, 0x67, 0x00, 0x96, 0xe0, 0x03, 0xe5, 0x80,
  5052. 0x3c, 0xe0, 0x89, 0xc4, 0xe5, 0x59, 0x36, 0xe0,
  5053. 0x05, 0xe5, 0x83, 0xa8, 0xfb, 0x08, 0x06, 0xa5,
  5054. 0xe6, 0x07, 0xe0, 0x02, 0xe5, 0x8f, 0x13, 0x80,
  5055. 0xe5, 0x81, 0xbf, 0xe0, 0x9a, 0x31, 0xe5, 0x16,
  5056. 0xe6, 0x04, 0x47, 0x46, 0xe9, 0x02, 0xe0, 0x86,
  5057. 0x3e, 0xe5, 0x81, 0xb1, 0xc0, 0xe5, 0x17, 0x00,
  5058. 0xe9, 0x02, 0x60, 0x36, 0xe5, 0x47, 0x00, 0xe9,
  5059. 0x02, 0xa0, 0xe5, 0x16, 0x20, 0x86, 0x16, 0xe0,
  5060. 0x02, 0xe5, 0x28, 0xc6, 0x96, 0x6f, 0x64, 0x16,
  5061. 0x0f, 0xe0, 0x02, 0xe9, 0x02, 0x00, 0xcb, 0x00,
  5062. 0xe5, 0x0d, 0x80, 0xe5, 0x0b, 0xe0, 0x81, 0x28,
  5063. 0x44, 0xe5, 0x20, 0x24, 0x56, 0xe9, 0x02, 0xe0,
  5064. 0x80, 0x3e, 0xe1, 0x18, 0xe2, 0x18, 0xeb, 0x0f,
  5065. 0x76, 0xe0, 0x5d, 0xe5, 0x43, 0x60, 0x06, 0x05,
  5066. 0xe7, 0x2f, 0xc0, 0x66, 0xe4, 0x05, 0xe0, 0x38,
  5067. 0x24, 0x16, 0x04, 0x06, 0xe0, 0x03, 0x27, 0xe0,
  5068. 0x06, 0xe5, 0x97, 0x70, 0xe0, 0x00, 0xe5, 0x84,
  5069. 0x4e, 0xe0, 0x21, 0xe5, 0x02, 0xe0, 0xa2, 0x5f,
  5070. 0x64, 0x00, 0xc4, 0x00, 0x24, 0x00, 0xe5, 0x80,
  5071. 0x9b, 0xe0, 0x07, 0x05, 0xe0, 0x15, 0x45, 0x20,
  5072. 0x05, 0xe0, 0x06, 0x65, 0xe0, 0x00, 0xe5, 0x81,
  5073. 0x04, 0xe0, 0x88, 0x7c, 0xe5, 0x63, 0x80, 0xe5,
  5074. 0x05, 0x40, 0xe5, 0x01, 0xc0, 0xe5, 0x02, 0x20,
  5075. 0x0f, 0x26, 0x16, 0x7b, 0xe0, 0x8e, 0xd4, 0xef,
  5076. 0x80, 0x68, 0xe9, 0x02, 0xa0, 0xef, 0x81, 0x2c,
  5077. 0xe0, 0x44, 0xe6, 0x26, 0x20, 0xe6, 0x0f, 0xe0,
  5078. 0x01, 0xef, 0x6c, 0xe0, 0x34, 0xef, 0x80, 0x6e,
  5079. 0xe0, 0x02, 0xef, 0x1f, 0x20, 0xef, 0x34, 0x27,
  5080. 0x46, 0x4f, 0xa7, 0xfb, 0x00, 0xe6, 0x00, 0x2f,
  5081. 0xc6, 0xef, 0x16, 0x66, 0xef, 0x35, 0xe0, 0x0d,
  5082. 0xef, 0x3a, 0x46, 0x0f, 0xe0, 0x72, 0xeb, 0x0c,
  5083. 0xe0, 0x04, 0xeb, 0x0c, 0xe0, 0x04, 0xef, 0x4f,
  5084. 0xe0, 0x01, 0xeb, 0x11, 0xe0, 0x7f, 0xe1, 0x12,
  5085. 0xe2, 0x12, 0xe1, 0x12, 0xc2, 0x00, 0xe2, 0x0a,
  5086. 0xe1, 0x12, 0xe2, 0x12, 0x01, 0x00, 0x21, 0x20,
  5087. 0x01, 0x20, 0x21, 0x20, 0x61, 0x00, 0xe1, 0x00,
  5088. 0x62, 0x00, 0x02, 0x00, 0xc2, 0x00, 0xe2, 0x03,
  5089. 0xe1, 0x12, 0xe2, 0x12, 0x21, 0x00, 0x61, 0x20,
  5090. 0xe1, 0x00, 0x00, 0xc1, 0x00, 0xe2, 0x12, 0x21,
  5091. 0x00, 0x61, 0x00, 0x81, 0x00, 0x01, 0x40, 0xc1,
  5092. 0x00, 0xe2, 0x12, 0xe1, 0x12, 0xe2, 0x12, 0xe1,
  5093. 0x12, 0xe2, 0x12, 0xe1, 0x12, 0xe2, 0x12, 0xe1,
  5094. 0x12, 0xe2, 0x12, 0xe1, 0x12, 0xe2, 0x12, 0xe1,
  5095. 0x12, 0xe2, 0x14, 0x20, 0xe1, 0x11, 0x0c, 0xe2,
  5096. 0x11, 0x0c, 0xa2, 0xe1, 0x11, 0x0c, 0xe2, 0x11,
  5097. 0x0c, 0xa2, 0xe1, 0x11, 0x0c, 0xe2, 0x11, 0x0c,
  5098. 0xa2, 0xe1, 0x11, 0x0c, 0xe2, 0x11, 0x0c, 0xa2,
  5099. 0xe1, 0x11, 0x0c, 0xe2, 0x11, 0x0c, 0xa2, 0x3f,
  5100. 0x20, 0xe9, 0x2a, 0xef, 0x81, 0x78, 0xe6, 0x2f,
  5101. 0x6f, 0xe6, 0x2a, 0xef, 0x00, 0x06, 0xef, 0x06,
  5102. 0x06, 0x2f, 0x96, 0xe0, 0x07, 0x86, 0x00, 0xe6,
  5103. 0x07, 0xe0, 0x83, 0xc8, 0xe2, 0x02, 0x05, 0xe2,
  5104. 0x0c, 0xa0, 0xa2, 0xe0, 0x80, 0x4d, 0xc6, 0x00,
  5105. 0xe6, 0x09, 0x20, 0xc6, 0x00, 0x26, 0x00, 0x86,
  5106. 0x80, 0xe4, 0x36, 0xe0, 0x19, 0x06, 0xe0, 0x68,
  5107. 0xe5, 0x25, 0x40, 0xc6, 0xc4, 0x20, 0xe9, 0x02,
  5108. 0x60, 0x05, 0x0f, 0xe0, 0x80, 0xb8, 0xe5, 0x16,
  5109. 0x06, 0xe0, 0x09, 0xe5, 0x24, 0x66, 0xe9, 0x02,
  5110. 0x80, 0x0d, 0xe0, 0x81, 0x48, 0xe5, 0x13, 0x04,
  5111. 0x66, 0xe9, 0x02, 0xe0, 0x80, 0x4e, 0xe5, 0x16,
  5112. 0x26, 0x05, 0xe9, 0x02, 0x60, 0x16, 0xe0, 0x81,
  5113. 0x58, 0xc5, 0x00, 0x65, 0x00, 0x25, 0x00, 0xe5,
  5114. 0x07, 0x00, 0xe5, 0x80, 0x3d, 0x20, 0xeb, 0x01,
  5115. 0xc6, 0xe0, 0x21, 0xe1, 0x1a, 0xe2, 0x1a, 0xc6,
  5116. 0x04, 0x60, 0xe9, 0x02, 0x60, 0x36, 0xe0, 0x82,
  5117. 0x89, 0xeb, 0x33, 0x0f, 0x4b, 0x0d, 0x6b, 0xe0,
  5118. 0x44, 0xeb, 0x25, 0x0f, 0xeb, 0x07, 0xe0, 0x80,
  5119. 0x3a, 0x65, 0x00, 0xe5, 0x13, 0x00, 0x25, 0x00,
  5120. 0x05, 0x20, 0x05, 0x00, 0xe5, 0x02, 0x00, 0x65,
  5121. 0x00, 0x05, 0x00, 0x05, 0xa0, 0x05, 0x60, 0x05,
  5122. 0x00, 0x05, 0x00, 0x05, 0x00, 0x45, 0x00, 0x25,
  5123. 0x00, 0x05, 0x20, 0x05, 0x00, 0x05, 0x00, 0x05,
  5124. 0x00, 0x05, 0x00, 0x05, 0x00, 0x25, 0x00, 0x05,
  5125. 0x20, 0x65, 0x00, 0xc5, 0x00, 0x65, 0x00, 0x65,
  5126. 0x00, 0x05, 0x00, 0xe5, 0x02, 0x00, 0xe5, 0x09,
  5127. 0x80, 0x45, 0x00, 0x85, 0x00, 0xe5, 0x09, 0xe0,
  5128. 0x2c, 0x2c, 0xe0, 0x80, 0x86, 0xef, 0x24, 0x60,
  5129. 0xef, 0x5c, 0xe0, 0x04, 0xef, 0x07, 0x20, 0xef,
  5130. 0x07, 0x00, 0xef, 0x07, 0x00, 0xef, 0x1d, 0xe0,
  5131. 0x02, 0xeb, 0x05, 0xef, 0x80, 0x19, 0xe0, 0x30,
  5132. 0xef, 0x15, 0xe0, 0x05, 0xef, 0x24, 0x60, 0xef,
  5133. 0x01, 0xc0, 0x2f, 0xe0, 0x06, 0xaf, 0xe0, 0x80,
  5134. 0x12, 0xef, 0x80, 0x73, 0x8e, 0xef, 0x82, 0x50,
  5135. 0x60, 0xef, 0x09, 0x40, 0xef, 0x05, 0x40, 0xef,
  5136. 0x6f, 0x60, 0xef, 0x57, 0xa0, 0xef, 0x04, 0x60,
  5137. 0x0f, 0xe0, 0x07, 0xef, 0x04, 0x60, 0xef, 0x30,
  5138. 0xe0, 0x00, 0xef, 0x02, 0xa0, 0xef, 0x20, 0xe0,
  5139. 0x00, 0xef, 0x16, 0x20, 0xef, 0x04, 0x60, 0x2f,
  5140. 0xe0, 0x36, 0xef, 0x80, 0xcc, 0xe0, 0x04, 0xef,
  5141. 0x06, 0x20, 0xef, 0x05, 0x40, 0xef, 0x02, 0x80,
  5142. 0xef, 0x30, 0xc0, 0xef, 0x07, 0x20, 0xef, 0x03,
  5143. 0xa0, 0xef, 0x01, 0xc0, 0xef, 0x80, 0x0b, 0x00,
  5144. 0xef, 0x54, 0xe9, 0x02, 0xe0, 0x83, 0x7e, 0xe5,
  5145. 0xc0, 0x66, 0x58, 0xe0, 0x18, 0xe5, 0x8f, 0xb2,
  5146. 0xa0, 0xe5, 0x80, 0x56, 0x20, 0xe5, 0x95, 0xfa,
  5147. 0xe0, 0x06, 0xe5, 0x9c, 0xa9, 0xe0, 0x07, 0xe5,
  5148. 0x81, 0xe6, 0xe0, 0x89, 0x1a, 0xe5, 0x81, 0x96,
  5149. 0xe0, 0x85, 0x5a, 0xe5, 0x92, 0xc3, 0x80, 0xe5,
  5150. 0x8f, 0xd8, 0xe0, 0xca, 0x9b, 0xc9, 0x1b, 0xe0,
  5151. 0x16, 0xfb, 0x58, 0xe0, 0x78, 0xe6, 0x80, 0x68,
  5152. 0xe0, 0xc0, 0xbd, 0x88, 0xfd, 0xc0, 0xbf, 0x76,
  5153. 0x20, 0xfd, 0xc0, 0xbf, 0x76, 0x20,
  5154. };
  5155. typedef enum {
  5156. UNICODE_SCRIPT_Unknown,
  5157. UNICODE_SCRIPT_Adlam,
  5158. UNICODE_SCRIPT_Ahom,
  5159. UNICODE_SCRIPT_Anatolian_Hieroglyphs,
  5160. UNICODE_SCRIPT_Arabic,
  5161. UNICODE_SCRIPT_Armenian,
  5162. UNICODE_SCRIPT_Avestan,
  5163. UNICODE_SCRIPT_Balinese,
  5164. UNICODE_SCRIPT_Bamum,
  5165. UNICODE_SCRIPT_Bassa_Vah,
  5166. UNICODE_SCRIPT_Batak,
  5167. UNICODE_SCRIPT_Bengali,
  5168. UNICODE_SCRIPT_Bhaiksuki,
  5169. UNICODE_SCRIPT_Bopomofo,
  5170. UNICODE_SCRIPT_Brahmi,
  5171. UNICODE_SCRIPT_Braille,
  5172. UNICODE_SCRIPT_Buginese,
  5173. UNICODE_SCRIPT_Buhid,
  5174. UNICODE_SCRIPT_Canadian_Aboriginal,
  5175. UNICODE_SCRIPT_Carian,
  5176. UNICODE_SCRIPT_Caucasian_Albanian,
  5177. UNICODE_SCRIPT_Chakma,
  5178. UNICODE_SCRIPT_Cham,
  5179. UNICODE_SCRIPT_Cherokee,
  5180. UNICODE_SCRIPT_Chorasmian,
  5181. UNICODE_SCRIPT_Common,
  5182. UNICODE_SCRIPT_Coptic,
  5183. UNICODE_SCRIPT_Cuneiform,
  5184. UNICODE_SCRIPT_Cypriot,
  5185. UNICODE_SCRIPT_Cyrillic,
  5186. UNICODE_SCRIPT_Cypro_Minoan,
  5187. UNICODE_SCRIPT_Deseret,
  5188. UNICODE_SCRIPT_Devanagari,
  5189. UNICODE_SCRIPT_Dives_Akuru,
  5190. UNICODE_SCRIPT_Dogra,
  5191. UNICODE_SCRIPT_Duployan,
  5192. UNICODE_SCRIPT_Egyptian_Hieroglyphs,
  5193. UNICODE_SCRIPT_Elbasan,
  5194. UNICODE_SCRIPT_Elymaic,
  5195. UNICODE_SCRIPT_Ethiopic,
  5196. UNICODE_SCRIPT_Georgian,
  5197. UNICODE_SCRIPT_Glagolitic,
  5198. UNICODE_SCRIPT_Gothic,
  5199. UNICODE_SCRIPT_Garay,
  5200. UNICODE_SCRIPT_Grantha,
  5201. UNICODE_SCRIPT_Greek,
  5202. UNICODE_SCRIPT_Gujarati,
  5203. UNICODE_SCRIPT_Gunjala_Gondi,
  5204. UNICODE_SCRIPT_Gurmukhi,
  5205. UNICODE_SCRIPT_Gurung_Khema,
  5206. UNICODE_SCRIPT_Han,
  5207. UNICODE_SCRIPT_Hangul,
  5208. UNICODE_SCRIPT_Hanifi_Rohingya,
  5209. UNICODE_SCRIPT_Hanunoo,
  5210. UNICODE_SCRIPT_Hatran,
  5211. UNICODE_SCRIPT_Hebrew,
  5212. UNICODE_SCRIPT_Hiragana,
  5213. UNICODE_SCRIPT_Imperial_Aramaic,
  5214. UNICODE_SCRIPT_Inherited,
  5215. UNICODE_SCRIPT_Inscriptional_Pahlavi,
  5216. UNICODE_SCRIPT_Inscriptional_Parthian,
  5217. UNICODE_SCRIPT_Javanese,
  5218. UNICODE_SCRIPT_Kaithi,
  5219. UNICODE_SCRIPT_Kannada,
  5220. UNICODE_SCRIPT_Katakana,
  5221. UNICODE_SCRIPT_Kawi,
  5222. UNICODE_SCRIPT_Kayah_Li,
  5223. UNICODE_SCRIPT_Kharoshthi,
  5224. UNICODE_SCRIPT_Khmer,
  5225. UNICODE_SCRIPT_Khojki,
  5226. UNICODE_SCRIPT_Khitan_Small_Script,
  5227. UNICODE_SCRIPT_Khudawadi,
  5228. UNICODE_SCRIPT_Kirat_Rai,
  5229. UNICODE_SCRIPT_Lao,
  5230. UNICODE_SCRIPT_Latin,
  5231. UNICODE_SCRIPT_Lepcha,
  5232. UNICODE_SCRIPT_Limbu,
  5233. UNICODE_SCRIPT_Linear_A,
  5234. UNICODE_SCRIPT_Linear_B,
  5235. UNICODE_SCRIPT_Lisu,
  5236. UNICODE_SCRIPT_Lycian,
  5237. UNICODE_SCRIPT_Lydian,
  5238. UNICODE_SCRIPT_Makasar,
  5239. UNICODE_SCRIPT_Mahajani,
  5240. UNICODE_SCRIPT_Malayalam,
  5241. UNICODE_SCRIPT_Mandaic,
  5242. UNICODE_SCRIPT_Manichaean,
  5243. UNICODE_SCRIPT_Marchen,
  5244. UNICODE_SCRIPT_Masaram_Gondi,
  5245. UNICODE_SCRIPT_Medefaidrin,
  5246. UNICODE_SCRIPT_Meetei_Mayek,
  5247. UNICODE_SCRIPT_Mende_Kikakui,
  5248. UNICODE_SCRIPT_Meroitic_Cursive,
  5249. UNICODE_SCRIPT_Meroitic_Hieroglyphs,
  5250. UNICODE_SCRIPT_Miao,
  5251. UNICODE_SCRIPT_Modi,
  5252. UNICODE_SCRIPT_Mongolian,
  5253. UNICODE_SCRIPT_Mro,
  5254. UNICODE_SCRIPT_Multani,
  5255. UNICODE_SCRIPT_Myanmar,
  5256. UNICODE_SCRIPT_Nabataean,
  5257. UNICODE_SCRIPT_Nag_Mundari,
  5258. UNICODE_SCRIPT_Nandinagari,
  5259. UNICODE_SCRIPT_New_Tai_Lue,
  5260. UNICODE_SCRIPT_Newa,
  5261. UNICODE_SCRIPT_Nko,
  5262. UNICODE_SCRIPT_Nushu,
  5263. UNICODE_SCRIPT_Nyiakeng_Puachue_Hmong,
  5264. UNICODE_SCRIPT_Ogham,
  5265. UNICODE_SCRIPT_Ol_Chiki,
  5266. UNICODE_SCRIPT_Ol_Onal,
  5267. UNICODE_SCRIPT_Old_Hungarian,
  5268. UNICODE_SCRIPT_Old_Italic,
  5269. UNICODE_SCRIPT_Old_North_Arabian,
  5270. UNICODE_SCRIPT_Old_Permic,
  5271. UNICODE_SCRIPT_Old_Persian,
  5272. UNICODE_SCRIPT_Old_Sogdian,
  5273. UNICODE_SCRIPT_Old_South_Arabian,
  5274. UNICODE_SCRIPT_Old_Turkic,
  5275. UNICODE_SCRIPT_Old_Uyghur,
  5276. UNICODE_SCRIPT_Oriya,
  5277. UNICODE_SCRIPT_Osage,
  5278. UNICODE_SCRIPT_Osmanya,
  5279. UNICODE_SCRIPT_Pahawh_Hmong,
  5280. UNICODE_SCRIPT_Palmyrene,
  5281. UNICODE_SCRIPT_Pau_Cin_Hau,
  5282. UNICODE_SCRIPT_Phags_Pa,
  5283. UNICODE_SCRIPT_Phoenician,
  5284. UNICODE_SCRIPT_Psalter_Pahlavi,
  5285. UNICODE_SCRIPT_Rejang,
  5286. UNICODE_SCRIPT_Runic,
  5287. UNICODE_SCRIPT_Samaritan,
  5288. UNICODE_SCRIPT_Saurashtra,
  5289. UNICODE_SCRIPT_Sharada,
  5290. UNICODE_SCRIPT_Shavian,
  5291. UNICODE_SCRIPT_Siddham,
  5292. UNICODE_SCRIPT_SignWriting,
  5293. UNICODE_SCRIPT_Sinhala,
  5294. UNICODE_SCRIPT_Sogdian,
  5295. UNICODE_SCRIPT_Sora_Sompeng,
  5296. UNICODE_SCRIPT_Soyombo,
  5297. UNICODE_SCRIPT_Sundanese,
  5298. UNICODE_SCRIPT_Sunuwar,
  5299. UNICODE_SCRIPT_Syloti_Nagri,
  5300. UNICODE_SCRIPT_Syriac,
  5301. UNICODE_SCRIPT_Tagalog,
  5302. UNICODE_SCRIPT_Tagbanwa,
  5303. UNICODE_SCRIPT_Tai_Le,
  5304. UNICODE_SCRIPT_Tai_Tham,
  5305. UNICODE_SCRIPT_Tai_Viet,
  5306. UNICODE_SCRIPT_Takri,
  5307. UNICODE_SCRIPT_Tamil,
  5308. UNICODE_SCRIPT_Tangut,
  5309. UNICODE_SCRIPT_Telugu,
  5310. UNICODE_SCRIPT_Thaana,
  5311. UNICODE_SCRIPT_Thai,
  5312. UNICODE_SCRIPT_Tibetan,
  5313. UNICODE_SCRIPT_Tifinagh,
  5314. UNICODE_SCRIPT_Tirhuta,
  5315. UNICODE_SCRIPT_Tangsa,
  5316. UNICODE_SCRIPT_Todhri,
  5317. UNICODE_SCRIPT_Toto,
  5318. UNICODE_SCRIPT_Tulu_Tigalari,
  5319. UNICODE_SCRIPT_Ugaritic,
  5320. UNICODE_SCRIPT_Vai,
  5321. UNICODE_SCRIPT_Vithkuqi,
  5322. UNICODE_SCRIPT_Wancho,
  5323. UNICODE_SCRIPT_Warang_Citi,
  5324. UNICODE_SCRIPT_Yezidi,
  5325. UNICODE_SCRIPT_Yi,
  5326. UNICODE_SCRIPT_Zanabazar_Square,
  5327. UNICODE_SCRIPT_COUNT,
  5328. } UnicodeScriptEnum;
  5329. static const char unicode_script_name_table[] =
  5330. "Adlam,Adlm" "\0"
  5331. "Ahom,Ahom" "\0"
  5332. "Anatolian_Hieroglyphs,Hluw" "\0"
  5333. "Arabic,Arab" "\0"
  5334. "Armenian,Armn" "\0"
  5335. "Avestan,Avst" "\0"
  5336. "Balinese,Bali" "\0"
  5337. "Bamum,Bamu" "\0"
  5338. "Bassa_Vah,Bass" "\0"
  5339. "Batak,Batk" "\0"
  5340. "Bengali,Beng" "\0"
  5341. "Bhaiksuki,Bhks" "\0"
  5342. "Bopomofo,Bopo" "\0"
  5343. "Brahmi,Brah" "\0"
  5344. "Braille,Brai" "\0"
  5345. "Buginese,Bugi" "\0"
  5346. "Buhid,Buhd" "\0"
  5347. "Canadian_Aboriginal,Cans" "\0"
  5348. "Carian,Cari" "\0"
  5349. "Caucasian_Albanian,Aghb" "\0"
  5350. "Chakma,Cakm" "\0"
  5351. "Cham,Cham" "\0"
  5352. "Cherokee,Cher" "\0"
  5353. "Chorasmian,Chrs" "\0"
  5354. "Common,Zyyy" "\0"
  5355. "Coptic,Copt,Qaac" "\0"
  5356. "Cuneiform,Xsux" "\0"
  5357. "Cypriot,Cprt" "\0"
  5358. "Cyrillic,Cyrl" "\0"
  5359. "Cypro_Minoan,Cpmn" "\0"
  5360. "Deseret,Dsrt" "\0"
  5361. "Devanagari,Deva" "\0"
  5362. "Dives_Akuru,Diak" "\0"
  5363. "Dogra,Dogr" "\0"
  5364. "Duployan,Dupl" "\0"
  5365. "Egyptian_Hieroglyphs,Egyp" "\0"
  5366. "Elbasan,Elba" "\0"
  5367. "Elymaic,Elym" "\0"
  5368. "Ethiopic,Ethi" "\0"
  5369. "Georgian,Geor" "\0"
  5370. "Glagolitic,Glag" "\0"
  5371. "Gothic,Goth" "\0"
  5372. "Garay,Gara" "\0"
  5373. "Grantha,Gran" "\0"
  5374. "Greek,Grek" "\0"
  5375. "Gujarati,Gujr" "\0"
  5376. "Gunjala_Gondi,Gong" "\0"
  5377. "Gurmukhi,Guru" "\0"
  5378. "Gurung_Khema,Gukh" "\0"
  5379. "Han,Hani" "\0"
  5380. "Hangul,Hang" "\0"
  5381. "Hanifi_Rohingya,Rohg" "\0"
  5382. "Hanunoo,Hano" "\0"
  5383. "Hatran,Hatr" "\0"
  5384. "Hebrew,Hebr" "\0"
  5385. "Hiragana,Hira" "\0"
  5386. "Imperial_Aramaic,Armi" "\0"
  5387. "Inherited,Zinh,Qaai" "\0"
  5388. "Inscriptional_Pahlavi,Phli" "\0"
  5389. "Inscriptional_Parthian,Prti" "\0"
  5390. "Javanese,Java" "\0"
  5391. "Kaithi,Kthi" "\0"
  5392. "Kannada,Knda" "\0"
  5393. "Katakana,Kana" "\0"
  5394. "Kawi,Kawi" "\0"
  5395. "Kayah_Li,Kali" "\0"
  5396. "Kharoshthi,Khar" "\0"
  5397. "Khmer,Khmr" "\0"
  5398. "Khojki,Khoj" "\0"
  5399. "Khitan_Small_Script,Kits" "\0"
  5400. "Khudawadi,Sind" "\0"
  5401. "Kirat_Rai,Krai" "\0"
  5402. "Lao,Laoo" "\0"
  5403. "Latin,Latn" "\0"
  5404. "Lepcha,Lepc" "\0"
  5405. "Limbu,Limb" "\0"
  5406. "Linear_A,Lina" "\0"
  5407. "Linear_B,Linb" "\0"
  5408. "Lisu,Lisu" "\0"
  5409. "Lycian,Lyci" "\0"
  5410. "Lydian,Lydi" "\0"
  5411. "Makasar,Maka" "\0"
  5412. "Mahajani,Mahj" "\0"
  5413. "Malayalam,Mlym" "\0"
  5414. "Mandaic,Mand" "\0"
  5415. "Manichaean,Mani" "\0"
  5416. "Marchen,Marc" "\0"
  5417. "Masaram_Gondi,Gonm" "\0"
  5418. "Medefaidrin,Medf" "\0"
  5419. "Meetei_Mayek,Mtei" "\0"
  5420. "Mende_Kikakui,Mend" "\0"
  5421. "Meroitic_Cursive,Merc" "\0"
  5422. "Meroitic_Hieroglyphs,Mero" "\0"
  5423. "Miao,Plrd" "\0"
  5424. "Modi,Modi" "\0"
  5425. "Mongolian,Mong" "\0"
  5426. "Mro,Mroo" "\0"
  5427. "Multani,Mult" "\0"
  5428. "Myanmar,Mymr" "\0"
  5429. "Nabataean,Nbat" "\0"
  5430. "Nag_Mundari,Nagm" "\0"
  5431. "Nandinagari,Nand" "\0"
  5432. "New_Tai_Lue,Talu" "\0"
  5433. "Newa,Newa" "\0"
  5434. "Nko,Nkoo" "\0"
  5435. "Nushu,Nshu" "\0"
  5436. "Nyiakeng_Puachue_Hmong,Hmnp" "\0"
  5437. "Ogham,Ogam" "\0"
  5438. "Ol_Chiki,Olck" "\0"
  5439. "Ol_Onal,Onao" "\0"
  5440. "Old_Hungarian,Hung" "\0"
  5441. "Old_Italic,Ital" "\0"
  5442. "Old_North_Arabian,Narb" "\0"
  5443. "Old_Permic,Perm" "\0"
  5444. "Old_Persian,Xpeo" "\0"
  5445. "Old_Sogdian,Sogo" "\0"
  5446. "Old_South_Arabian,Sarb" "\0"
  5447. "Old_Turkic,Orkh" "\0"
  5448. "Old_Uyghur,Ougr" "\0"
  5449. "Oriya,Orya" "\0"
  5450. "Osage,Osge" "\0"
  5451. "Osmanya,Osma" "\0"
  5452. "Pahawh_Hmong,Hmng" "\0"
  5453. "Palmyrene,Palm" "\0"
  5454. "Pau_Cin_Hau,Pauc" "\0"
  5455. "Phags_Pa,Phag" "\0"
  5456. "Phoenician,Phnx" "\0"
  5457. "Psalter_Pahlavi,Phlp" "\0"
  5458. "Rejang,Rjng" "\0"
  5459. "Runic,Runr" "\0"
  5460. "Samaritan,Samr" "\0"
  5461. "Saurashtra,Saur" "\0"
  5462. "Sharada,Shrd" "\0"
  5463. "Shavian,Shaw" "\0"
  5464. "Siddham,Sidd" "\0"
  5465. "SignWriting,Sgnw" "\0"
  5466. "Sinhala,Sinh" "\0"
  5467. "Sogdian,Sogd" "\0"
  5468. "Sora_Sompeng,Sora" "\0"
  5469. "Soyombo,Soyo" "\0"
  5470. "Sundanese,Sund" "\0"
  5471. "Sunuwar,Sunu" "\0"
  5472. "Syloti_Nagri,Sylo" "\0"
  5473. "Syriac,Syrc" "\0"
  5474. "Tagalog,Tglg" "\0"
  5475. "Tagbanwa,Tagb" "\0"
  5476. "Tai_Le,Tale" "\0"
  5477. "Tai_Tham,Lana" "\0"
  5478. "Tai_Viet,Tavt" "\0"
  5479. "Takri,Takr" "\0"
  5480. "Tamil,Taml" "\0"
  5481. "Tangut,Tang" "\0"
  5482. "Telugu,Telu" "\0"
  5483. "Thaana,Thaa" "\0"
  5484. "Thai,Thai" "\0"
  5485. "Tibetan,Tibt" "\0"
  5486. "Tifinagh,Tfng" "\0"
  5487. "Tirhuta,Tirh" "\0"
  5488. "Tangsa,Tnsa" "\0"
  5489. "Todhri,Todr" "\0"
  5490. "Toto,Toto" "\0"
  5491. "Tulu_Tigalari,Tutg" "\0"
  5492. "Ugaritic,Ugar" "\0"
  5493. "Vai,Vaii" "\0"
  5494. "Vithkuqi,Vith" "\0"
  5495. "Wancho,Wcho" "\0"
  5496. "Warang_Citi,Wara" "\0"
  5497. "Yezidi,Yezi" "\0"
  5498. "Yi,Yiii" "\0"
  5499. "Zanabazar_Square,Zanb" "\0"
  5500. ;
  5501. static const uint8_t unicode_script_table[2803] = {
  5502. 0xc0, 0x19, 0x99, 0x4a, 0x85, 0x19, 0x99, 0x4a,
  5503. 0xae, 0x19, 0x80, 0x4a, 0x8e, 0x19, 0x80, 0x4a,
  5504. 0x84, 0x19, 0x96, 0x4a, 0x80, 0x19, 0x9e, 0x4a,
  5505. 0x80, 0x19, 0xe1, 0x60, 0x4a, 0xa6, 0x19, 0x84,
  5506. 0x4a, 0x84, 0x19, 0x81, 0x0d, 0x93, 0x19, 0xe0,
  5507. 0x0f, 0x3a, 0x83, 0x2d, 0x80, 0x19, 0x82, 0x2d,
  5508. 0x01, 0x83, 0x2d, 0x80, 0x19, 0x80, 0x2d, 0x03,
  5509. 0x80, 0x2d, 0x80, 0x19, 0x80, 0x2d, 0x80, 0x19,
  5510. 0x82, 0x2d, 0x00, 0x80, 0x2d, 0x00, 0x93, 0x2d,
  5511. 0x00, 0xbe, 0x2d, 0x8d, 0x1a, 0x8f, 0x2d, 0xe0,
  5512. 0x24, 0x1d, 0x81, 0x3a, 0xe0, 0x48, 0x1d, 0x00,
  5513. 0xa5, 0x05, 0x01, 0xb1, 0x05, 0x01, 0x82, 0x05,
  5514. 0x00, 0xb6, 0x37, 0x07, 0x9a, 0x37, 0x03, 0x85,
  5515. 0x37, 0x0a, 0x84, 0x04, 0x80, 0x19, 0x85, 0x04,
  5516. 0x80, 0x19, 0x8d, 0x04, 0x80, 0x19, 0x82, 0x04,
  5517. 0x80, 0x19, 0x9f, 0x04, 0x80, 0x19, 0x89, 0x04,
  5518. 0x8a, 0x3a, 0x99, 0x04, 0x80, 0x3a, 0xe0, 0x0b,
  5519. 0x04, 0x80, 0x19, 0xa1, 0x04, 0x8d, 0x90, 0x00,
  5520. 0xbb, 0x90, 0x01, 0x82, 0x90, 0xaf, 0x04, 0xb1,
  5521. 0x9a, 0x0d, 0xba, 0x69, 0x01, 0x82, 0x69, 0xad,
  5522. 0x83, 0x01, 0x8e, 0x83, 0x00, 0x9b, 0x55, 0x01,
  5523. 0x80, 0x55, 0x00, 0x8a, 0x90, 0x04, 0x9e, 0x04,
  5524. 0x00, 0x81, 0x04, 0x04, 0xca, 0x04, 0x80, 0x19,
  5525. 0x9c, 0x04, 0xd0, 0x20, 0x83, 0x3a, 0x8e, 0x20,
  5526. 0x81, 0x19, 0x99, 0x20, 0x83, 0x0b, 0x00, 0x87,
  5527. 0x0b, 0x01, 0x81, 0x0b, 0x01, 0x95, 0x0b, 0x00,
  5528. 0x86, 0x0b, 0x00, 0x80, 0x0b, 0x02, 0x83, 0x0b,
  5529. 0x01, 0x88, 0x0b, 0x01, 0x81, 0x0b, 0x01, 0x83,
  5530. 0x0b, 0x07, 0x80, 0x0b, 0x03, 0x81, 0x0b, 0x00,
  5531. 0x84, 0x0b, 0x01, 0x98, 0x0b, 0x01, 0x82, 0x30,
  5532. 0x00, 0x85, 0x30, 0x03, 0x81, 0x30, 0x01, 0x95,
  5533. 0x30, 0x00, 0x86, 0x30, 0x00, 0x81, 0x30, 0x00,
  5534. 0x81, 0x30, 0x00, 0x81, 0x30, 0x01, 0x80, 0x30,
  5535. 0x00, 0x84, 0x30, 0x03, 0x81, 0x30, 0x01, 0x82,
  5536. 0x30, 0x02, 0x80, 0x30, 0x06, 0x83, 0x30, 0x00,
  5537. 0x80, 0x30, 0x06, 0x90, 0x30, 0x09, 0x82, 0x2e,
  5538. 0x00, 0x88, 0x2e, 0x00, 0x82, 0x2e, 0x00, 0x95,
  5539. 0x2e, 0x00, 0x86, 0x2e, 0x00, 0x81, 0x2e, 0x00,
  5540. 0x84, 0x2e, 0x01, 0x89, 0x2e, 0x00, 0x82, 0x2e,
  5541. 0x00, 0x82, 0x2e, 0x01, 0x80, 0x2e, 0x0e, 0x83,
  5542. 0x2e, 0x01, 0x8b, 0x2e, 0x06, 0x86, 0x2e, 0x00,
  5543. 0x82, 0x78, 0x00, 0x87, 0x78, 0x01, 0x81, 0x78,
  5544. 0x01, 0x95, 0x78, 0x00, 0x86, 0x78, 0x00, 0x81,
  5545. 0x78, 0x00, 0x84, 0x78, 0x01, 0x88, 0x78, 0x01,
  5546. 0x81, 0x78, 0x01, 0x82, 0x78, 0x06, 0x82, 0x78,
  5547. 0x03, 0x81, 0x78, 0x00, 0x84, 0x78, 0x01, 0x91,
  5548. 0x78, 0x09, 0x81, 0x97, 0x00, 0x85, 0x97, 0x02,
  5549. 0x82, 0x97, 0x00, 0x83, 0x97, 0x02, 0x81, 0x97,
  5550. 0x00, 0x80, 0x97, 0x00, 0x81, 0x97, 0x02, 0x81,
  5551. 0x97, 0x02, 0x82, 0x97, 0x02, 0x8b, 0x97, 0x03,
  5552. 0x84, 0x97, 0x02, 0x82, 0x97, 0x00, 0x83, 0x97,
  5553. 0x01, 0x80, 0x97, 0x05, 0x80, 0x97, 0x0d, 0x94,
  5554. 0x97, 0x04, 0x8c, 0x99, 0x00, 0x82, 0x99, 0x00,
  5555. 0x96, 0x99, 0x00, 0x8f, 0x99, 0x01, 0x88, 0x99,
  5556. 0x00, 0x82, 0x99, 0x00, 0x83, 0x99, 0x06, 0x81,
  5557. 0x99, 0x00, 0x82, 0x99, 0x01, 0x80, 0x99, 0x01,
  5558. 0x83, 0x99, 0x01, 0x89, 0x99, 0x06, 0x88, 0x99,
  5559. 0x8c, 0x3f, 0x00, 0x82, 0x3f, 0x00, 0x96, 0x3f,
  5560. 0x00, 0x89, 0x3f, 0x00, 0x84, 0x3f, 0x01, 0x88,
  5561. 0x3f, 0x00, 0x82, 0x3f, 0x00, 0x83, 0x3f, 0x06,
  5562. 0x81, 0x3f, 0x05, 0x81, 0x3f, 0x00, 0x83, 0x3f,
  5563. 0x01, 0x89, 0x3f, 0x00, 0x82, 0x3f, 0x0b, 0x8c,
  5564. 0x54, 0x00, 0x82, 0x54, 0x00, 0xb2, 0x54, 0x00,
  5565. 0x82, 0x54, 0x00, 0x85, 0x54, 0x03, 0x8f, 0x54,
  5566. 0x01, 0x99, 0x54, 0x00, 0x82, 0x89, 0x00, 0x91,
  5567. 0x89, 0x02, 0x97, 0x89, 0x00, 0x88, 0x89, 0x00,
  5568. 0x80, 0x89, 0x01, 0x86, 0x89, 0x02, 0x80, 0x89,
  5569. 0x03, 0x85, 0x89, 0x00, 0x80, 0x89, 0x00, 0x87,
  5570. 0x89, 0x05, 0x89, 0x89, 0x01, 0x82, 0x89, 0x0b,
  5571. 0xb9, 0x9b, 0x03, 0x80, 0x19, 0x9b, 0x9b, 0x24,
  5572. 0x81, 0x49, 0x00, 0x80, 0x49, 0x00, 0x84, 0x49,
  5573. 0x00, 0x97, 0x49, 0x00, 0x80, 0x49, 0x00, 0x96,
  5574. 0x49, 0x01, 0x84, 0x49, 0x00, 0x80, 0x49, 0x00,
  5575. 0x86, 0x49, 0x00, 0x89, 0x49, 0x01, 0x83, 0x49,
  5576. 0x1f, 0xc7, 0x9c, 0x00, 0xa3, 0x9c, 0x03, 0xa6,
  5577. 0x9c, 0x00, 0xa3, 0x9c, 0x00, 0x8e, 0x9c, 0x00,
  5578. 0x86, 0x9c, 0x83, 0x19, 0x81, 0x9c, 0x24, 0xe0,
  5579. 0x3f, 0x63, 0xa5, 0x28, 0x00, 0x80, 0x28, 0x04,
  5580. 0x80, 0x28, 0x01, 0xaa, 0x28, 0x80, 0x19, 0x83,
  5581. 0x28, 0xe0, 0x9f, 0x33, 0xc8, 0x27, 0x00, 0x83,
  5582. 0x27, 0x01, 0x86, 0x27, 0x00, 0x80, 0x27, 0x00,
  5583. 0x83, 0x27, 0x01, 0xa8, 0x27, 0x00, 0x83, 0x27,
  5584. 0x01, 0xa0, 0x27, 0x00, 0x83, 0x27, 0x01, 0x86,
  5585. 0x27, 0x00, 0x80, 0x27, 0x00, 0x83, 0x27, 0x01,
  5586. 0x8e, 0x27, 0x00, 0xb8, 0x27, 0x00, 0x83, 0x27,
  5587. 0x01, 0xc2, 0x27, 0x01, 0x9f, 0x27, 0x02, 0x99,
  5588. 0x27, 0x05, 0xd5, 0x17, 0x01, 0x85, 0x17, 0x01,
  5589. 0xe2, 0x1f, 0x12, 0x9c, 0x6c, 0x02, 0xca, 0x82,
  5590. 0x82, 0x19, 0x8a, 0x82, 0x06, 0x95, 0x91, 0x08,
  5591. 0x80, 0x91, 0x94, 0x35, 0x81, 0x19, 0x08, 0x93,
  5592. 0x11, 0x0b, 0x8c, 0x92, 0x00, 0x82, 0x92, 0x00,
  5593. 0x81, 0x92, 0x0b, 0xdd, 0x44, 0x01, 0x89, 0x44,
  5594. 0x05, 0x89, 0x44, 0x05, 0x81, 0x60, 0x81, 0x19,
  5595. 0x80, 0x60, 0x80, 0x19, 0x93, 0x60, 0x05, 0xd8,
  5596. 0x60, 0x06, 0xaa, 0x60, 0x04, 0xc5, 0x12, 0x09,
  5597. 0x9e, 0x4c, 0x00, 0x8b, 0x4c, 0x03, 0x8b, 0x4c,
  5598. 0x03, 0x80, 0x4c, 0x02, 0x8b, 0x4c, 0x9d, 0x93,
  5599. 0x01, 0x84, 0x93, 0x0a, 0xab, 0x67, 0x03, 0x99,
  5600. 0x67, 0x05, 0x8a, 0x67, 0x02, 0x81, 0x67, 0x9f,
  5601. 0x44, 0x9b, 0x10, 0x01, 0x81, 0x10, 0xbe, 0x94,
  5602. 0x00, 0x9c, 0x94, 0x01, 0x8a, 0x94, 0x05, 0x89,
  5603. 0x94, 0x05, 0x8d, 0x94, 0x01, 0x9e, 0x3a, 0x30,
  5604. 0xcc, 0x07, 0x00, 0xb1, 0x07, 0xbf, 0x8d, 0xb3,
  5605. 0x0a, 0x07, 0x83, 0x0a, 0xb7, 0x4b, 0x02, 0x8e,
  5606. 0x4b, 0x02, 0x82, 0x4b, 0xaf, 0x6d, 0x8a, 0x1d,
  5607. 0x04, 0xaa, 0x28, 0x01, 0x82, 0x28, 0x87, 0x8d,
  5608. 0x07, 0x82, 0x3a, 0x80, 0x19, 0x8c, 0x3a, 0x80,
  5609. 0x19, 0x86, 0x3a, 0x83, 0x19, 0x80, 0x3a, 0x85,
  5610. 0x19, 0x80, 0x3a, 0x82, 0x19, 0x81, 0x3a, 0x80,
  5611. 0x19, 0x04, 0xa5, 0x4a, 0x84, 0x2d, 0x80, 0x1d,
  5612. 0xb0, 0x4a, 0x84, 0x2d, 0x83, 0x4a, 0x84, 0x2d,
  5613. 0x8c, 0x4a, 0x80, 0x1d, 0xc5, 0x4a, 0x80, 0x2d,
  5614. 0xbf, 0x3a, 0xe0, 0x9f, 0x4a, 0x95, 0x2d, 0x01,
  5615. 0x85, 0x2d, 0x01, 0xa5, 0x2d, 0x01, 0x85, 0x2d,
  5616. 0x01, 0x87, 0x2d, 0x00, 0x80, 0x2d, 0x00, 0x80,
  5617. 0x2d, 0x00, 0x80, 0x2d, 0x00, 0x9e, 0x2d, 0x01,
  5618. 0xb4, 0x2d, 0x00, 0x8e, 0x2d, 0x00, 0x8d, 0x2d,
  5619. 0x01, 0x85, 0x2d, 0x00, 0x92, 0x2d, 0x01, 0x82,
  5620. 0x2d, 0x00, 0x88, 0x2d, 0x00, 0x8b, 0x19, 0x81,
  5621. 0x3a, 0xd6, 0x19, 0x00, 0x8a, 0x19, 0x80, 0x4a,
  5622. 0x01, 0x8a, 0x19, 0x80, 0x4a, 0x8e, 0x19, 0x00,
  5623. 0x8c, 0x4a, 0x02, 0xa0, 0x19, 0x0e, 0xa0, 0x3a,
  5624. 0x0e, 0xa5, 0x19, 0x80, 0x2d, 0x82, 0x19, 0x81,
  5625. 0x4a, 0x85, 0x19, 0x80, 0x4a, 0x9a, 0x19, 0x80,
  5626. 0x4a, 0x90, 0x19, 0xa8, 0x4a, 0x82, 0x19, 0x03,
  5627. 0xe2, 0x39, 0x19, 0x15, 0x8a, 0x19, 0x14, 0xe3,
  5628. 0x3f, 0x19, 0xe0, 0x9f, 0x0f, 0xe2, 0x13, 0x19,
  5629. 0x01, 0x9f, 0x19, 0x00, 0xe0, 0x08, 0x19, 0xdf,
  5630. 0x29, 0x9f, 0x4a, 0xe0, 0x13, 0x1a, 0x04, 0x86,
  5631. 0x1a, 0xa5, 0x28, 0x00, 0x80, 0x28, 0x04, 0x80,
  5632. 0x28, 0x01, 0xb7, 0x9d, 0x06, 0x81, 0x9d, 0x0d,
  5633. 0x80, 0x9d, 0x96, 0x27, 0x08, 0x86, 0x27, 0x00,
  5634. 0x86, 0x27, 0x00, 0x86, 0x27, 0x00, 0x86, 0x27,
  5635. 0x00, 0x86, 0x27, 0x00, 0x86, 0x27, 0x00, 0x86,
  5636. 0x27, 0x00, 0x86, 0x27, 0x00, 0x9f, 0x1d, 0xdd,
  5637. 0x19, 0x21, 0x99, 0x32, 0x00, 0xd8, 0x32, 0x0b,
  5638. 0xe0, 0x75, 0x32, 0x19, 0x94, 0x19, 0x80, 0x32,
  5639. 0x80, 0x19, 0x80, 0x32, 0x98, 0x19, 0x88, 0x32,
  5640. 0x83, 0x3a, 0x81, 0x33, 0x87, 0x19, 0x83, 0x32,
  5641. 0x83, 0x19, 0x00, 0xd5, 0x38, 0x01, 0x81, 0x3a,
  5642. 0x81, 0x19, 0x82, 0x38, 0x80, 0x19, 0xd9, 0x40,
  5643. 0x81, 0x19, 0x82, 0x40, 0x04, 0xaa, 0x0d, 0x00,
  5644. 0xdd, 0x33, 0x00, 0x8f, 0x19, 0x9f, 0x0d, 0xa5,
  5645. 0x19, 0x08, 0x80, 0x19, 0x8f, 0x40, 0x9e, 0x33,
  5646. 0x00, 0xbf, 0x19, 0x9e, 0x33, 0xd0, 0x19, 0xae,
  5647. 0x40, 0x80, 0x19, 0xd7, 0x40, 0xe0, 0x47, 0x19,
  5648. 0xf0, 0x09, 0x5f, 0x32, 0xbf, 0x19, 0xf0, 0x41,
  5649. 0x9f, 0x32, 0xe4, 0x2c, 0xa9, 0x02, 0xb6, 0xa9,
  5650. 0x08, 0xaf, 0x4f, 0xe0, 0xcb, 0xa4, 0x13, 0xdf,
  5651. 0x1d, 0xd7, 0x08, 0x07, 0xa1, 0x19, 0xe0, 0x05,
  5652. 0x4a, 0x82, 0x19, 0xc2, 0x4a, 0x01, 0x81, 0x4a,
  5653. 0x00, 0x80, 0x4a, 0x00, 0x87, 0x4a, 0x14, 0x8d,
  5654. 0x4a, 0xac, 0x8f, 0x02, 0x89, 0x19, 0x05, 0xb7,
  5655. 0x7e, 0x07, 0xc5, 0x84, 0x07, 0x8b, 0x84, 0x05,
  5656. 0x9f, 0x20, 0xad, 0x42, 0x80, 0x19, 0x80, 0x42,
  5657. 0xa3, 0x81, 0x0a, 0x80, 0x81, 0x9c, 0x33, 0x02,
  5658. 0xcd, 0x3d, 0x00, 0x80, 0x19, 0x89, 0x3d, 0x03,
  5659. 0x81, 0x3d, 0x9e, 0x63, 0x00, 0xb6, 0x16, 0x08,
  5660. 0x8d, 0x16, 0x01, 0x89, 0x16, 0x01, 0x83, 0x16,
  5661. 0x9f, 0x63, 0xc2, 0x95, 0x17, 0x84, 0x95, 0x96,
  5662. 0x5a, 0x09, 0x85, 0x27, 0x01, 0x85, 0x27, 0x01,
  5663. 0x85, 0x27, 0x08, 0x86, 0x27, 0x00, 0x86, 0x27,
  5664. 0x00, 0xaa, 0x4a, 0x80, 0x19, 0x88, 0x4a, 0x80,
  5665. 0x2d, 0x83, 0x4a, 0x81, 0x19, 0x03, 0xcf, 0x17,
  5666. 0xad, 0x5a, 0x01, 0x89, 0x5a, 0x05, 0xf0, 0x1b,
  5667. 0x43, 0x33, 0x0b, 0x96, 0x33, 0x03, 0xb0, 0x33,
  5668. 0x70, 0x10, 0xa3, 0xe1, 0x0d, 0x32, 0x01, 0xe0,
  5669. 0x09, 0x32, 0x25, 0x86, 0x4a, 0x0b, 0x84, 0x05,
  5670. 0x04, 0x99, 0x37, 0x00, 0x84, 0x37, 0x00, 0x80,
  5671. 0x37, 0x00, 0x81, 0x37, 0x00, 0x81, 0x37, 0x00,
  5672. 0x89, 0x37, 0xe0, 0x12, 0x04, 0x0f, 0xe1, 0x0a,
  5673. 0x04, 0x81, 0x19, 0xcf, 0x04, 0x01, 0xb5, 0x04,
  5674. 0x06, 0x80, 0x04, 0x1f, 0x8f, 0x04, 0x8f, 0x3a,
  5675. 0x89, 0x19, 0x05, 0x8d, 0x3a, 0x81, 0x1d, 0xa2,
  5676. 0x19, 0x00, 0x92, 0x19, 0x00, 0x83, 0x19, 0x03,
  5677. 0x84, 0x04, 0x00, 0xe0, 0x26, 0x04, 0x01, 0x80,
  5678. 0x19, 0x00, 0x9f, 0x19, 0x99, 0x4a, 0x85, 0x19,
  5679. 0x99, 0x4a, 0x8a, 0x19, 0x89, 0x40, 0x80, 0x19,
  5680. 0xac, 0x40, 0x81, 0x19, 0x9e, 0x33, 0x02, 0x85,
  5681. 0x33, 0x01, 0x85, 0x33, 0x01, 0x85, 0x33, 0x01,
  5682. 0x82, 0x33, 0x02, 0x86, 0x19, 0x00, 0x86, 0x19,
  5683. 0x09, 0x84, 0x19, 0x01, 0x8b, 0x4e, 0x00, 0x99,
  5684. 0x4e, 0x00, 0x92, 0x4e, 0x00, 0x81, 0x4e, 0x00,
  5685. 0x8e, 0x4e, 0x01, 0x8d, 0x4e, 0x21, 0xe0, 0x1a,
  5686. 0x4e, 0x04, 0x82, 0x19, 0x03, 0xac, 0x19, 0x02,
  5687. 0x88, 0x19, 0xce, 0x2d, 0x00, 0x8c, 0x19, 0x02,
  5688. 0x80, 0x2d, 0x2e, 0xac, 0x19, 0x80, 0x3a, 0x60,
  5689. 0x21, 0x9c, 0x50, 0x02, 0xb0, 0x13, 0x0e, 0x80,
  5690. 0x3a, 0x9a, 0x19, 0x03, 0xa3, 0x70, 0x08, 0x82,
  5691. 0x70, 0x9a, 0x2a, 0x04, 0xaa, 0x72, 0x04, 0x9d,
  5692. 0xa3, 0x00, 0x80, 0xa3, 0xa3, 0x73, 0x03, 0x8d,
  5693. 0x73, 0x29, 0xcf, 0x1f, 0xaf, 0x86, 0x9d, 0x7a,
  5694. 0x01, 0x89, 0x7a, 0x05, 0xa3, 0x79, 0x03, 0xa3,
  5695. 0x79, 0x03, 0xa7, 0x25, 0x07, 0xb3, 0x14, 0x0a,
  5696. 0x80, 0x14, 0x8a, 0xa5, 0x00, 0x8e, 0xa5, 0x00,
  5697. 0x86, 0xa5, 0x00, 0x81, 0xa5, 0x00, 0x8a, 0xa5,
  5698. 0x00, 0x8e, 0xa5, 0x00, 0x86, 0xa5, 0x00, 0x81,
  5699. 0xa5, 0x02, 0xb3, 0xa0, 0x0b, 0xe0, 0xd6, 0x4d,
  5700. 0x08, 0x95, 0x4d, 0x09, 0x87, 0x4d, 0x17, 0x85,
  5701. 0x4a, 0x00, 0xa9, 0x4a, 0x00, 0x88, 0x4a, 0x44,
  5702. 0x85, 0x1c, 0x01, 0x80, 0x1c, 0x00, 0xab, 0x1c,
  5703. 0x00, 0x81, 0x1c, 0x02, 0x80, 0x1c, 0x01, 0x80,
  5704. 0x1c, 0x95, 0x39, 0x00, 0x88, 0x39, 0x9f, 0x7c,
  5705. 0x9e, 0x64, 0x07, 0x88, 0x64, 0x2f, 0x92, 0x36,
  5706. 0x00, 0x81, 0x36, 0x04, 0x84, 0x36, 0x9b, 0x7f,
  5707. 0x02, 0x80, 0x7f, 0x99, 0x51, 0x04, 0x80, 0x51,
  5708. 0x3f, 0x9f, 0x5d, 0x97, 0x5c, 0x03, 0x93, 0x5c,
  5709. 0x01, 0xad, 0x5c, 0x83, 0x43, 0x00, 0x81, 0x43,
  5710. 0x04, 0x87, 0x43, 0x00, 0x82, 0x43, 0x00, 0x9c,
  5711. 0x43, 0x01, 0x82, 0x43, 0x03, 0x89, 0x43, 0x06,
  5712. 0x88, 0x43, 0x06, 0x9f, 0x75, 0x9f, 0x71, 0x1f,
  5713. 0xa6, 0x56, 0x03, 0x8b, 0x56, 0x08, 0xb5, 0x06,
  5714. 0x02, 0x86, 0x06, 0x95, 0x3c, 0x01, 0x87, 0x3c,
  5715. 0x92, 0x3b, 0x04, 0x87, 0x3b, 0x91, 0x80, 0x06,
  5716. 0x83, 0x80, 0x0b, 0x86, 0x80, 0x4f, 0xc8, 0x76,
  5717. 0x36, 0xb2, 0x6f, 0x0c, 0xb2, 0x6f, 0x06, 0x85,
  5718. 0x6f, 0xa7, 0x34, 0x07, 0x89, 0x34, 0x05, 0xa5,
  5719. 0x2b, 0x02, 0x9c, 0x2b, 0x07, 0x81, 0x2b, 0x60,
  5720. 0x6f, 0x9e, 0x04, 0x00, 0xa9, 0xa8, 0x00, 0x82,
  5721. 0xa8, 0x01, 0x81, 0xa8, 0x0f, 0x82, 0x04, 0x36,
  5722. 0x83, 0x04, 0xa7, 0x74, 0x07, 0xa9, 0x8a, 0x15,
  5723. 0x99, 0x77, 0x25, 0x9b, 0x18, 0x13, 0x96, 0x26,
  5724. 0x08, 0xcd, 0x0e, 0x03, 0xa3, 0x0e, 0x08, 0x80,
  5725. 0x0e, 0xc2, 0x3e, 0x09, 0x80, 0x3e, 0x01, 0x98,
  5726. 0x8b, 0x06, 0x89, 0x8b, 0x05, 0xb4, 0x15, 0x00,
  5727. 0x91, 0x15, 0x07, 0xa6, 0x53, 0x08, 0xdf, 0x85,
  5728. 0x00, 0x93, 0x89, 0x0a, 0x91, 0x45, 0x00, 0xae,
  5729. 0x45, 0x3d, 0x86, 0x62, 0x00, 0x80, 0x62, 0x00,
  5730. 0x83, 0x62, 0x00, 0x8e, 0x62, 0x00, 0x8a, 0x62,
  5731. 0x05, 0xba, 0x47, 0x04, 0x89, 0x47, 0x05, 0x83,
  5732. 0x2c, 0x00, 0x87, 0x2c, 0x01, 0x81, 0x2c, 0x01,
  5733. 0x95, 0x2c, 0x00, 0x86, 0x2c, 0x00, 0x81, 0x2c,
  5734. 0x00, 0x84, 0x2c, 0x00, 0x80, 0x3a, 0x88, 0x2c,
  5735. 0x01, 0x81, 0x2c, 0x01, 0x82, 0x2c, 0x01, 0x80,
  5736. 0x2c, 0x05, 0x80, 0x2c, 0x04, 0x86, 0x2c, 0x01,
  5737. 0x86, 0x2c, 0x02, 0x84, 0x2c, 0x0a, 0x89, 0xa2,
  5738. 0x00, 0x80, 0xa2, 0x01, 0x80, 0xa2, 0x00, 0xa5,
  5739. 0xa2, 0x00, 0x89, 0xa2, 0x00, 0x80, 0xa2, 0x01,
  5740. 0x80, 0xa2, 0x00, 0x83, 0xa2, 0x00, 0x89, 0xa2,
  5741. 0x00, 0x81, 0xa2, 0x07, 0x81, 0xa2, 0x1c, 0xdb,
  5742. 0x68, 0x00, 0x84, 0x68, 0x1d, 0xc7, 0x9e, 0x07,
  5743. 0x89, 0x9e, 0x60, 0x45, 0xb5, 0x87, 0x01, 0xa5,
  5744. 0x87, 0x21, 0xc4, 0x5f, 0x0a, 0x89, 0x5f, 0x05,
  5745. 0x8c, 0x60, 0x12, 0xb9, 0x96, 0x05, 0x89, 0x96,
  5746. 0x05, 0x93, 0x63, 0x1b, 0x9a, 0x02, 0x01, 0x8e,
  5747. 0x02, 0x03, 0x96, 0x02, 0x60, 0x58, 0xbb, 0x22,
  5748. 0x60, 0x03, 0xd2, 0xa7, 0x0b, 0x80, 0xa7, 0x86,
  5749. 0x21, 0x01, 0x80, 0x21, 0x01, 0x87, 0x21, 0x00,
  5750. 0x81, 0x21, 0x00, 0x9d, 0x21, 0x00, 0x81, 0x21,
  5751. 0x01, 0x8b, 0x21, 0x08, 0x89, 0x21, 0x45, 0x87,
  5752. 0x66, 0x01, 0xad, 0x66, 0x01, 0x8a, 0x66, 0x1a,
  5753. 0xc7, 0xaa, 0x07, 0xd2, 0x8c, 0x0c, 0x8f, 0x12,
  5754. 0xb8, 0x7d, 0x06, 0x89, 0x20, 0x60, 0x55, 0xa1,
  5755. 0x8e, 0x0d, 0x89, 0x8e, 0x05, 0x88, 0x0c, 0x00,
  5756. 0xac, 0x0c, 0x00, 0x8d, 0x0c, 0x09, 0x9c, 0x0c,
  5757. 0x02, 0x9f, 0x57, 0x01, 0x95, 0x57, 0x00, 0x8d,
  5758. 0x57, 0x48, 0x86, 0x58, 0x00, 0x81, 0x58, 0x00,
  5759. 0xab, 0x58, 0x02, 0x80, 0x58, 0x00, 0x81, 0x58,
  5760. 0x00, 0x88, 0x58, 0x07, 0x89, 0x58, 0x05, 0x85,
  5761. 0x2f, 0x00, 0x81, 0x2f, 0x00, 0xa4, 0x2f, 0x00,
  5762. 0x81, 0x2f, 0x00, 0x85, 0x2f, 0x06, 0x89, 0x2f,
  5763. 0x60, 0xd5, 0x98, 0x52, 0x06, 0x90, 0x41, 0x00,
  5764. 0xa8, 0x41, 0x02, 0x9c, 0x41, 0x54, 0x80, 0x4f,
  5765. 0x0e, 0xb1, 0x97, 0x0c, 0x80, 0x97, 0xe3, 0x39,
  5766. 0x1b, 0x60, 0x05, 0xe0, 0x0e, 0x1b, 0x00, 0x84,
  5767. 0x1b, 0x0a, 0xe0, 0x63, 0x1b, 0x69, 0xeb, 0xe0,
  5768. 0x02, 0x1e, 0x0c, 0xe3, 0xf5, 0x24, 0x09, 0xef,
  5769. 0x3a, 0x24, 0x04, 0xe1, 0xe6, 0x03, 0x70, 0x0a,
  5770. 0x58, 0xb9, 0x31, 0x66, 0x65, 0xe1, 0xd8, 0x08,
  5771. 0x06, 0x9e, 0x61, 0x00, 0x89, 0x61, 0x03, 0x81,
  5772. 0x61, 0xce, 0x9f, 0x00, 0x89, 0x9f, 0x05, 0x9d,
  5773. 0x09, 0x01, 0x85, 0x09, 0x09, 0xc5, 0x7b, 0x09,
  5774. 0x89, 0x7b, 0x00, 0x86, 0x7b, 0x00, 0x94, 0x7b,
  5775. 0x04, 0x92, 0x7b, 0x61, 0x4f, 0xb9, 0x48, 0x60,
  5776. 0x65, 0xda, 0x59, 0x60, 0x04, 0xca, 0x5e, 0x03,
  5777. 0xb8, 0x5e, 0x06, 0x90, 0x5e, 0x3f, 0x80, 0x98,
  5778. 0x80, 0x6a, 0x81, 0x32, 0x80, 0x46, 0x0a, 0x81,
  5779. 0x32, 0x0d, 0xf0, 0x07, 0x97, 0x98, 0x07, 0xe2,
  5780. 0x9f, 0x98, 0xe1, 0x75, 0x46, 0x28, 0x80, 0x46,
  5781. 0x88, 0x98, 0x70, 0x12, 0x86, 0x83, 0x40, 0x00,
  5782. 0x86, 0x40, 0x00, 0x81, 0x40, 0x00, 0x80, 0x40,
  5783. 0xe0, 0xbe, 0x38, 0x82, 0x40, 0x0e, 0x80, 0x38,
  5784. 0x1c, 0x82, 0x38, 0x01, 0x80, 0x40, 0x0d, 0x83,
  5785. 0x40, 0x07, 0xe1, 0x2b, 0x6a, 0x68, 0xa3, 0xe0,
  5786. 0x0a, 0x23, 0x04, 0x8c, 0x23, 0x02, 0x88, 0x23,
  5787. 0x06, 0x89, 0x23, 0x01, 0x83, 0x23, 0x83, 0x19,
  5788. 0x6e, 0xfb, 0xe0, 0x99, 0x19, 0x05, 0xe1, 0x53,
  5789. 0x19, 0x4b, 0xad, 0x3a, 0x01, 0x96, 0x3a, 0x08,
  5790. 0xe0, 0x13, 0x19, 0x3b, 0xe0, 0x95, 0x19, 0x09,
  5791. 0xa6, 0x19, 0x01, 0xbd, 0x19, 0x82, 0x3a, 0x90,
  5792. 0x19, 0x87, 0x3a, 0x81, 0x19, 0x86, 0x3a, 0x9d,
  5793. 0x19, 0x83, 0x3a, 0xbc, 0x19, 0x14, 0xc5, 0x2d,
  5794. 0x60, 0x19, 0x93, 0x19, 0x0b, 0x93, 0x19, 0x0b,
  5795. 0xd6, 0x19, 0x08, 0x98, 0x19, 0x60, 0x26, 0xd4,
  5796. 0x19, 0x00, 0xc6, 0x19, 0x00, 0x81, 0x19, 0x01,
  5797. 0x80, 0x19, 0x01, 0x81, 0x19, 0x01, 0x83, 0x19,
  5798. 0x00, 0x8b, 0x19, 0x00, 0x80, 0x19, 0x00, 0x86,
  5799. 0x19, 0x00, 0xc0, 0x19, 0x00, 0x83, 0x19, 0x01,
  5800. 0x87, 0x19, 0x00, 0x86, 0x19, 0x00, 0x9b, 0x19,
  5801. 0x00, 0x83, 0x19, 0x00, 0x84, 0x19, 0x00, 0x80,
  5802. 0x19, 0x02, 0x86, 0x19, 0x00, 0xe0, 0xf3, 0x19,
  5803. 0x01, 0xe0, 0xc3, 0x19, 0x01, 0xb1, 0x19, 0xe2,
  5804. 0x2b, 0x88, 0x0e, 0x84, 0x88, 0x00, 0x8e, 0x88,
  5805. 0x63, 0xef, 0x9e, 0x4a, 0x05, 0x85, 0x4a, 0x60,
  5806. 0x74, 0x86, 0x29, 0x00, 0x90, 0x29, 0x01, 0x86,
  5807. 0x29, 0x00, 0x81, 0x29, 0x00, 0x84, 0x29, 0x04,
  5808. 0xbd, 0x1d, 0x20, 0x80, 0x1d, 0x60, 0x0f, 0xac,
  5809. 0x6b, 0x02, 0x8d, 0x6b, 0x01, 0x89, 0x6b, 0x03,
  5810. 0x81, 0x6b, 0x60, 0xdf, 0x9e, 0xa1, 0x10, 0xb9,
  5811. 0xa6, 0x04, 0x80, 0xa6, 0x61, 0x6f, 0xa9, 0x65,
  5812. 0x60, 0x75, 0xaa, 0x6e, 0x03, 0x80, 0x6e, 0x61,
  5813. 0x7f, 0x86, 0x27, 0x00, 0x83, 0x27, 0x00, 0x81,
  5814. 0x27, 0x00, 0x8e, 0x27, 0x00, 0xe0, 0x64, 0x5b,
  5815. 0x01, 0x8f, 0x5b, 0x28, 0xcb, 0x01, 0x03, 0x89,
  5816. 0x01, 0x03, 0x81, 0x01, 0x62, 0xb0, 0xc3, 0x19,
  5817. 0x4b, 0xbc, 0x19, 0x60, 0x61, 0x83, 0x04, 0x00,
  5818. 0x9a, 0x04, 0x00, 0x81, 0x04, 0x00, 0x80, 0x04,
  5819. 0x01, 0x80, 0x04, 0x00, 0x89, 0x04, 0x00, 0x83,
  5820. 0x04, 0x00, 0x80, 0x04, 0x00, 0x80, 0x04, 0x05,
  5821. 0x80, 0x04, 0x03, 0x80, 0x04, 0x00, 0x80, 0x04,
  5822. 0x00, 0x80, 0x04, 0x00, 0x82, 0x04, 0x00, 0x81,
  5823. 0x04, 0x00, 0x80, 0x04, 0x01, 0x80, 0x04, 0x00,
  5824. 0x80, 0x04, 0x00, 0x80, 0x04, 0x00, 0x80, 0x04,
  5825. 0x00, 0x80, 0x04, 0x00, 0x81, 0x04, 0x00, 0x80,
  5826. 0x04, 0x01, 0x83, 0x04, 0x00, 0x86, 0x04, 0x00,
  5827. 0x83, 0x04, 0x00, 0x83, 0x04, 0x00, 0x80, 0x04,
  5828. 0x00, 0x89, 0x04, 0x00, 0x90, 0x04, 0x04, 0x82,
  5829. 0x04, 0x00, 0x84, 0x04, 0x00, 0x90, 0x04, 0x33,
  5830. 0x81, 0x04, 0x60, 0xad, 0xab, 0x19, 0x03, 0xe0,
  5831. 0x03, 0x19, 0x0b, 0x8e, 0x19, 0x01, 0x8e, 0x19,
  5832. 0x00, 0x8e, 0x19, 0x00, 0xa4, 0x19, 0x09, 0xe0,
  5833. 0x4d, 0x19, 0x37, 0x99, 0x19, 0x80, 0x38, 0x81,
  5834. 0x19, 0x0c, 0xab, 0x19, 0x03, 0x88, 0x19, 0x06,
  5835. 0x81, 0x19, 0x0d, 0x85, 0x19, 0x60, 0x39, 0xe3,
  5836. 0x77, 0x19, 0x03, 0x90, 0x19, 0x02, 0x8c, 0x19,
  5837. 0x02, 0xe0, 0x16, 0x19, 0x03, 0xde, 0x19, 0x05,
  5838. 0x8b, 0x19, 0x03, 0x80, 0x19, 0x0e, 0x8b, 0x19,
  5839. 0x03, 0xb7, 0x19, 0x07, 0x89, 0x19, 0x05, 0xa7,
  5840. 0x19, 0x07, 0x9d, 0x19, 0x01, 0x8b, 0x19, 0x03,
  5841. 0x81, 0x19, 0x3d, 0xe0, 0xf3, 0x19, 0x0b, 0x8d,
  5842. 0x19, 0x01, 0x8c, 0x19, 0x02, 0x89, 0x19, 0x04,
  5843. 0xb7, 0x19, 0x06, 0x8e, 0x19, 0x01, 0x8a, 0x19,
  5844. 0x05, 0x88, 0x19, 0x06, 0xe0, 0x32, 0x19, 0x00,
  5845. 0xe0, 0x05, 0x19, 0x63, 0xa5, 0xf0, 0x96, 0x7f,
  5846. 0x32, 0x1f, 0xef, 0xd9, 0x32, 0x05, 0xe0, 0x7d,
  5847. 0x32, 0x01, 0xf0, 0x06, 0x21, 0x32, 0x0d, 0xf0,
  5848. 0x0c, 0xd0, 0x32, 0x0e, 0xe2, 0x0d, 0x32, 0x69,
  5849. 0x41, 0xe1, 0xbd, 0x32, 0x65, 0x81, 0xf0, 0x02,
  5850. 0xea, 0x32, 0x04, 0xef, 0xff, 0x32, 0x7a, 0xcb,
  5851. 0xf0, 0x80, 0x19, 0x1d, 0xdf, 0x19, 0x60, 0x1f,
  5852. 0xe0, 0x8f, 0x3a,
  5853. };
  5854. static const uint8_t unicode_script_ext_table[1253] = {
  5855. 0x80, 0x36, 0x00, 0x00, 0x10, 0x06, 0x13, 0x1a,
  5856. 0x23, 0x25, 0x28, 0x29, 0x2f, 0x2a, 0x2d, 0x32,
  5857. 0x4a, 0x51, 0x53, 0x72, 0x86, 0x81, 0x83, 0x00,
  5858. 0x00, 0x07, 0x0b, 0x1d, 0x20, 0x4a, 0x4f, 0x9b,
  5859. 0xa1, 0x09, 0x00, 0x00, 0x02, 0x0d, 0x4a, 0x00,
  5860. 0x00, 0x02, 0x02, 0x0d, 0x4a, 0x00, 0x00, 0x00,
  5861. 0x02, 0x4a, 0x4f, 0x08, 0x00, 0x00, 0x02, 0x4a,
  5862. 0x9b, 0x00, 0x00, 0x00, 0x02, 0x0d, 0x4a, 0x25,
  5863. 0x00, 0x00, 0x08, 0x17, 0x1a, 0x1d, 0x2d, 0x4a,
  5864. 0x72, 0x8e, 0x93, 0x00, 0x08, 0x17, 0x1d, 0x2d,
  5865. 0x4a, 0x79, 0x8e, 0x93, 0xa0, 0x00, 0x04, 0x17,
  5866. 0x1d, 0x4a, 0x9d, 0x00, 0x05, 0x29, 0x4a, 0x8e,
  5867. 0x90, 0x9b, 0x00, 0x0b, 0x14, 0x17, 0x1a, 0x1d,
  5868. 0x2a, 0x2d, 0x4a, 0x79, 0x90, 0x9d, 0xa0, 0x00,
  5869. 0x06, 0x1a, 0x25, 0x29, 0x2a, 0x40, 0x4a, 0x00,
  5870. 0x04, 0x1d, 0x2d, 0x4a, 0x72, 0x00, 0x09, 0x1a,
  5871. 0x23, 0x37, 0x4a, 0x72, 0x90, 0x93, 0x9d, 0xa0,
  5872. 0x00, 0x0a, 0x05, 0x1d, 0x23, 0x2a, 0x2d, 0x37,
  5873. 0x4a, 0x72, 0x90, 0x93, 0x00, 0x02, 0x4a, 0x9d,
  5874. 0x00, 0x03, 0x23, 0x4a, 0x90, 0x00, 0x04, 0x17,
  5875. 0x1d, 0x4a, 0x79, 0x00, 0x03, 0x17, 0x4a, 0x93,
  5876. 0x00, 0x02, 0x4a, 0x8e, 0x00, 0x02, 0x27, 0x4a,
  5877. 0x00, 0x00, 0x00, 0x02, 0x4a, 0x8e, 0x00, 0x03,
  5878. 0x1d, 0x4a, 0xa0, 0x00, 0x00, 0x00, 0x04, 0x2d,
  5879. 0x4a, 0x72, 0xa0, 0x0b, 0x00, 0x00, 0x02, 0x4a,
  5880. 0x90, 0x01, 0x00, 0x00, 0x05, 0x17, 0x23, 0x40,
  5881. 0x4a, 0x90, 0x00, 0x04, 0x17, 0x23, 0x4a, 0x90,
  5882. 0x00, 0x02, 0x4a, 0x90, 0x06, 0x00, 0x00, 0x03,
  5883. 0x4a, 0x8e, 0x90, 0x00, 0x02, 0x4a, 0x90, 0x00,
  5884. 0x00, 0x00, 0x03, 0x17, 0x4a, 0x90, 0x00, 0x06,
  5885. 0x14, 0x17, 0x2a, 0x4a, 0x8e, 0x9b, 0x0f, 0x00,
  5886. 0x00, 0x01, 0x2d, 0x01, 0x00, 0x00, 0x01, 0x2d,
  5887. 0x11, 0x00, 0x00, 0x02, 0x4a, 0x79, 0x04, 0x00,
  5888. 0x00, 0x03, 0x14, 0x4a, 0xa0, 0x03, 0x00, 0x0c,
  5889. 0x01, 0x4a, 0x03, 0x00, 0x01, 0x02, 0x1a, 0x2d,
  5890. 0x80, 0x8c, 0x00, 0x00, 0x02, 0x1d, 0x72, 0x00,
  5891. 0x02, 0x1d, 0x29, 0x01, 0x02, 0x1d, 0x4a, 0x00,
  5892. 0x02, 0x1d, 0x29, 0x80, 0x80, 0x00, 0x00, 0x03,
  5893. 0x05, 0x28, 0x29, 0x80, 0x01, 0x00, 0x00, 0x07,
  5894. 0x04, 0x2b, 0x69, 0x34, 0x90, 0x9a, 0xa8, 0x0d,
  5895. 0x00, 0x00, 0x07, 0x04, 0x2b, 0x69, 0x34, 0x90,
  5896. 0x9a, 0xa8, 0x00, 0x03, 0x04, 0x90, 0x9a, 0x01,
  5897. 0x00, 0x00, 0x08, 0x01, 0x04, 0x2b, 0x69, 0x34,
  5898. 0x90, 0x9a, 0xa8, 0x1f, 0x00, 0x00, 0x09, 0x01,
  5899. 0x04, 0x55, 0x56, 0x77, 0x80, 0x34, 0x8a, 0x90,
  5900. 0x09, 0x00, 0x0a, 0x02, 0x04, 0x90, 0x09, 0x00,
  5901. 0x09, 0x03, 0x04, 0x9a, 0xa8, 0x05, 0x00, 0x00,
  5902. 0x02, 0x04, 0x90, 0x62, 0x00, 0x00, 0x02, 0x04,
  5903. 0x34, 0x81, 0xfb, 0x00, 0x00, 0x0d, 0x0b, 0x20,
  5904. 0x2c, 0x2e, 0x30, 0x3f, 0x4a, 0x54, 0x78, 0x85,
  5905. 0x97, 0x99, 0x9e, 0x00, 0x0c, 0x0b, 0x20, 0x2c,
  5906. 0x2e, 0x30, 0x3f, 0x4a, 0x54, 0x78, 0x97, 0x99,
  5907. 0x9e, 0x10, 0x00, 0x00, 0x15, 0x0b, 0x20, 0x22,
  5908. 0x2f, 0x58, 0x2c, 0x2e, 0x30, 0x3f, 0x53, 0x54,
  5909. 0x66, 0x6e, 0x78, 0x47, 0x89, 0x8f, 0x96, 0x97,
  5910. 0x99, 0x9e, 0x00, 0x17, 0x0b, 0x20, 0x22, 0x2f,
  5911. 0x58, 0x2c, 0x2e, 0x31, 0x30, 0x3f, 0x4c, 0x53,
  5912. 0x54, 0x66, 0x6e, 0x78, 0x47, 0x89, 0x8f, 0x96,
  5913. 0x97, 0x99, 0x9e, 0x09, 0x04, 0x20, 0x22, 0x3e,
  5914. 0x53, 0x75, 0x00, 0x09, 0x03, 0x0b, 0x15, 0x8f,
  5915. 0x75, 0x00, 0x09, 0x02, 0x30, 0x62, 0x75, 0x00,
  5916. 0x09, 0x02, 0x2e, 0x45, 0x80, 0x75, 0x00, 0x0d,
  5917. 0x02, 0x2c, 0x97, 0x80, 0x71, 0x00, 0x09, 0x03,
  5918. 0x3f, 0x66, 0xa2, 0x82, 0xcf, 0x00, 0x09, 0x03,
  5919. 0x15, 0x63, 0x93, 0x80, 0x30, 0x00, 0x00, 0x03,
  5920. 0x28, 0x29, 0x4a, 0x85, 0x6e, 0x00, 0x02, 0x01,
  5921. 0x82, 0x46, 0x00, 0x01, 0x04, 0x11, 0x35, 0x92,
  5922. 0x91, 0x80, 0x4a, 0x00, 0x01, 0x02, 0x60, 0x7e,
  5923. 0x00, 0x00, 0x00, 0x02, 0x60, 0x7e, 0x84, 0x49,
  5924. 0x00, 0x00, 0x04, 0x0b, 0x20, 0x2c, 0x3f, 0x00,
  5925. 0x01, 0x20, 0x00, 0x04, 0x0b, 0x20, 0x2c, 0x3f,
  5926. 0x00, 0x03, 0x20, 0x2c, 0x3f, 0x00, 0x01, 0x20,
  5927. 0x01, 0x02, 0x0b, 0x20, 0x00, 0x02, 0x20, 0x85,
  5928. 0x00, 0x02, 0x0b, 0x20, 0x00, 0x02, 0x20, 0x85,
  5929. 0x00, 0x06, 0x20, 0x3f, 0x54, 0x78, 0x97, 0x99,
  5930. 0x00, 0x01, 0x20, 0x01, 0x02, 0x20, 0x85, 0x01,
  5931. 0x01, 0x20, 0x00, 0x02, 0x20, 0x85, 0x00, 0x02,
  5932. 0x0b, 0x20, 0x06, 0x01, 0x20, 0x00, 0x02, 0x20,
  5933. 0x66, 0x00, 0x02, 0x0b, 0x20, 0x01, 0x01, 0x20,
  5934. 0x00, 0x02, 0x0b, 0x20, 0x03, 0x01, 0x20, 0x00,
  5935. 0x0b, 0x0b, 0x20, 0x2c, 0x3f, 0x54, 0x66, 0x78,
  5936. 0x89, 0x99, 0x9e, 0xa2, 0x00, 0x02, 0x20, 0x2c,
  5937. 0x00, 0x04, 0x20, 0x2c, 0x3f, 0xa2, 0x01, 0x02,
  5938. 0x0b, 0x20, 0x00, 0x01, 0x0b, 0x01, 0x02, 0x20,
  5939. 0x2c, 0x00, 0x01, 0x66, 0x80, 0x44, 0x00, 0x01,
  5940. 0x01, 0x2d, 0x35, 0x00, 0x00, 0x03, 0x1d, 0x4a,
  5941. 0x90, 0x00, 0x00, 0x00, 0x01, 0x90, 0x81, 0xb3,
  5942. 0x00, 0x00, 0x03, 0x4a, 0x60, 0x7e, 0x1e, 0x00,
  5943. 0x00, 0x02, 0x01, 0x04, 0x09, 0x00, 0x00, 0x06,
  5944. 0x13, 0x28, 0x29, 0x6f, 0x50, 0x76, 0x01, 0x00,
  5945. 0x00, 0x04, 0x13, 0x2d, 0x6f, 0x5d, 0x80, 0x11,
  5946. 0x00, 0x00, 0x03, 0x20, 0x2c, 0x4a, 0x8c, 0xa5,
  5947. 0x00, 0x00, 0x02, 0x1a, 0x4a, 0x17, 0x00, 0x00,
  5948. 0x02, 0x06, 0x76, 0x00, 0x07, 0x06, 0x13, 0x28,
  5949. 0x6f, 0x3e, 0x51, 0x83, 0x09, 0x00, 0x00, 0x01,
  5950. 0x23, 0x03, 0x00, 0x00, 0x03, 0x01, 0x04, 0x6f,
  5951. 0x00, 0x00, 0x00, 0x02, 0x1d, 0x29, 0x81, 0x2b,
  5952. 0x00, 0x0f, 0x02, 0x32, 0x98, 0x00, 0x00, 0x00,
  5953. 0x07, 0x0d, 0x33, 0x32, 0x38, 0x40, 0x60, 0xa9,
  5954. 0x00, 0x08, 0x0d, 0x33, 0x32, 0x38, 0x40, 0x60,
  5955. 0x7e, 0xa9, 0x00, 0x05, 0x0d, 0x33, 0x32, 0x38,
  5956. 0x40, 0x01, 0x00, 0x00, 0x01, 0x32, 0x00, 0x00,
  5957. 0x01, 0x08, 0x0d, 0x33, 0x32, 0x38, 0x40, 0x60,
  5958. 0x9c, 0xa9, 0x01, 0x09, 0x0d, 0x33, 0x32, 0x38,
  5959. 0x40, 0x4f, 0x60, 0x9c, 0xa9, 0x05, 0x06, 0x0d,
  5960. 0x33, 0x32, 0x38, 0x40, 0xa9, 0x00, 0x00, 0x00,
  5961. 0x05, 0x0d, 0x33, 0x32, 0x38, 0x40, 0x07, 0x06,
  5962. 0x0d, 0x33, 0x32, 0x38, 0x40, 0xa9, 0x03, 0x05,
  5963. 0x0d, 0x33, 0x32, 0x38, 0x40, 0x09, 0x00, 0x03,
  5964. 0x02, 0x0d, 0x32, 0x01, 0x00, 0x00, 0x05, 0x0d,
  5965. 0x33, 0x32, 0x38, 0x40, 0x04, 0x02, 0x38, 0x40,
  5966. 0x00, 0x00, 0x00, 0x05, 0x0d, 0x33, 0x32, 0x38,
  5967. 0x40, 0x03, 0x00, 0x01, 0x03, 0x32, 0x38, 0x40,
  5968. 0x01, 0x01, 0x32, 0x58, 0x00, 0x03, 0x02, 0x38,
  5969. 0x40, 0x02, 0x00, 0x00, 0x02, 0x38, 0x40, 0x59,
  5970. 0x00, 0x00, 0x06, 0x0d, 0x33, 0x32, 0x38, 0x40,
  5971. 0xa9, 0x00, 0x02, 0x38, 0x40, 0x80, 0x12, 0x00,
  5972. 0x0f, 0x01, 0x32, 0x1f, 0x00, 0x25, 0x01, 0x32,
  5973. 0x08, 0x00, 0x00, 0x02, 0x32, 0x98, 0x2f, 0x00,
  5974. 0x27, 0x01, 0x32, 0x37, 0x00, 0x30, 0x01, 0x32,
  5975. 0x0e, 0x00, 0x0b, 0x01, 0x32, 0x32, 0x00, 0x00,
  5976. 0x01, 0x32, 0x57, 0x00, 0x18, 0x01, 0x32, 0x09,
  5977. 0x00, 0x04, 0x01, 0x32, 0x5f, 0x00, 0x1e, 0x01,
  5978. 0x32, 0xc0, 0x31, 0xef, 0x00, 0x00, 0x02, 0x1d,
  5979. 0x29, 0x80, 0x0f, 0x00, 0x07, 0x02, 0x32, 0x4a,
  5980. 0x80, 0xa7, 0x00, 0x02, 0x10, 0x20, 0x22, 0x2e,
  5981. 0x30, 0x45, 0x3f, 0x3e, 0x53, 0x54, 0x5f, 0x66,
  5982. 0x85, 0x47, 0x96, 0x9e, 0xa2, 0x02, 0x0f, 0x20,
  5983. 0x22, 0x2e, 0x30, 0x45, 0x3f, 0x3e, 0x53, 0x5f,
  5984. 0x66, 0x85, 0x47, 0x96, 0x9e, 0xa2, 0x01, 0x0b,
  5985. 0x20, 0x22, 0x2e, 0x30, 0x45, 0x3e, 0x53, 0x5f,
  5986. 0x47, 0x96, 0x9e, 0x00, 0x0c, 0x20, 0x22, 0x2e,
  5987. 0x30, 0x45, 0x3e, 0x53, 0x5f, 0x85, 0x47, 0x96,
  5988. 0x9e, 0x00, 0x0b, 0x20, 0x22, 0x2e, 0x30, 0x45,
  5989. 0x3e, 0x53, 0x5f, 0x47, 0x96, 0x9e, 0x80, 0x36,
  5990. 0x00, 0x00, 0x03, 0x0b, 0x20, 0xa2, 0x00, 0x00,
  5991. 0x00, 0x02, 0x20, 0x97, 0x39, 0x00, 0x00, 0x03,
  5992. 0x42, 0x4a, 0x63, 0x80, 0x1f, 0x00, 0x00, 0x02,
  5993. 0x10, 0x3d, 0xc0, 0x12, 0xed, 0x00, 0x01, 0x02,
  5994. 0x04, 0x69, 0x80, 0x31, 0x00, 0x00, 0x02, 0x04,
  5995. 0x9a, 0x09, 0x00, 0x00, 0x02, 0x04, 0x9a, 0x46,
  5996. 0x00, 0x01, 0x05, 0x0d, 0x33, 0x32, 0x38, 0x40,
  5997. 0x80, 0x99, 0x00, 0x04, 0x06, 0x0d, 0x33, 0x32,
  5998. 0x38, 0x40, 0xa9, 0x09, 0x00, 0x00, 0x02, 0x38,
  5999. 0x40, 0x2c, 0x00, 0x01, 0x02, 0x38, 0x40, 0x80,
  6000. 0xdf, 0x00, 0x01, 0x03, 0x1e, 0x1c, 0x4e, 0x00,
  6001. 0x02, 0x1c, 0x4e, 0x03, 0x00, 0x2c, 0x03, 0x1c,
  6002. 0x4d, 0x4e, 0x02, 0x00, 0x08, 0x02, 0x1c, 0x4e,
  6003. 0x81, 0x1f, 0x00, 0x1b, 0x02, 0x04, 0x1a, 0x87,
  6004. 0x75, 0x00, 0x00, 0x02, 0x56, 0x77, 0x87, 0x8d,
  6005. 0x00, 0x00, 0x02, 0x2c, 0x97, 0x00, 0x00, 0x00,
  6006. 0x02, 0x2c, 0x97, 0x36, 0x00, 0x01, 0x02, 0x2c,
  6007. 0x97, 0x8c, 0x12, 0x00, 0x01, 0x02, 0x2c, 0x97,
  6008. 0x00, 0x00, 0x00, 0x02, 0x2c, 0x97, 0xc0, 0x5c,
  6009. 0x4b, 0x00, 0x03, 0x01, 0x23, 0x96, 0x3b, 0x00,
  6010. 0x11, 0x01, 0x32, 0x9e, 0x5d, 0x00, 0x01, 0x01,
  6011. 0x32, 0xce, 0xcd, 0x2d, 0x00,
  6012. };
  6013. static const uint8_t unicode_prop_Hyphen_table[28] = {
  6014. 0xac, 0x80, 0xfe, 0x80, 0x44, 0xdb, 0x80, 0x52,
  6015. 0x7a, 0x80, 0x48, 0x08, 0x81, 0x4e, 0x04, 0x80,
  6016. 0x42, 0xe2, 0x80, 0x60, 0xcd, 0x66, 0x80, 0x40,
  6017. 0xa8, 0x80, 0xd6, 0x80,
  6018. };
  6019. static const uint8_t unicode_prop_Other_Math_table[200] = {
  6020. 0xdd, 0x80, 0x43, 0x70, 0x11, 0x80, 0x99, 0x09,
  6021. 0x81, 0x5c, 0x1f, 0x80, 0x9a, 0x82, 0x8a, 0x80,
  6022. 0x9f, 0x83, 0x97, 0x81, 0x8d, 0x81, 0xc0, 0x8c,
  6023. 0x18, 0x11, 0x1c, 0x91, 0x03, 0x01, 0x89, 0x00,
  6024. 0x14, 0x28, 0x11, 0x09, 0x02, 0x05, 0x13, 0x24,
  6025. 0xca, 0x21, 0x18, 0x08, 0x08, 0x00, 0x21, 0x0b,
  6026. 0x0b, 0x91, 0x09, 0x00, 0x06, 0x00, 0x29, 0x41,
  6027. 0x21, 0x83, 0x40, 0xa7, 0x08, 0x80, 0x97, 0x80,
  6028. 0x90, 0x80, 0x41, 0xbc, 0x81, 0x8b, 0x88, 0x24,
  6029. 0x21, 0x09, 0x14, 0x8d, 0x00, 0x01, 0x85, 0x97,
  6030. 0x81, 0xb8, 0x00, 0x80, 0x9c, 0x83, 0x88, 0x81,
  6031. 0x41, 0x55, 0x81, 0x9e, 0x89, 0x41, 0x92, 0x95,
  6032. 0xbe, 0x83, 0x9f, 0x81, 0x60, 0xd4, 0x62, 0x00,
  6033. 0x03, 0x80, 0x40, 0xd2, 0x00, 0x80, 0x60, 0xd4,
  6034. 0xc0, 0xd4, 0x80, 0xc6, 0x01, 0x08, 0x09, 0x0b,
  6035. 0x80, 0x8b, 0x00, 0x06, 0x80, 0xc0, 0x03, 0x0f,
  6036. 0x06, 0x80, 0x9b, 0x03, 0x04, 0x00, 0x16, 0x80,
  6037. 0x41, 0x53, 0x81, 0x98, 0x80, 0x98, 0x80, 0x9e,
  6038. 0x80, 0x98, 0x80, 0x9e, 0x80, 0x98, 0x80, 0x9e,
  6039. 0x80, 0x98, 0x80, 0x9e, 0x80, 0x98, 0x07, 0x81,
  6040. 0xb1, 0x55, 0xff, 0x18, 0x9a, 0x01, 0x00, 0x08,
  6041. 0x80, 0x89, 0x03, 0x00, 0x00, 0x28, 0x18, 0x00,
  6042. 0x00, 0x02, 0x01, 0x00, 0x08, 0x00, 0x00, 0x00,
  6043. 0x00, 0x01, 0x00, 0x0b, 0x06, 0x03, 0x03, 0x00,
  6044. 0x80, 0x89, 0x80, 0x90, 0x22, 0x04, 0x80, 0x90,
  6045. };
  6046. static const uint8_t unicode_prop_Other_Alphabetic_table[443] = {
  6047. 0x43, 0x44, 0x80, 0x9c, 0x8c, 0x42, 0x3f, 0x8d,
  6048. 0x00, 0x01, 0x01, 0x00, 0xc7, 0x8a, 0xaf, 0x8c,
  6049. 0x06, 0x8f, 0x80, 0xe4, 0x33, 0x19, 0x0b, 0x80,
  6050. 0xa2, 0x80, 0x9d, 0x8f, 0xe5, 0x8a, 0xe4, 0x0a,
  6051. 0x88, 0x02, 0x03, 0xe9, 0x80, 0xbb, 0x8b, 0x16,
  6052. 0x85, 0x93, 0xb5, 0x09, 0x8e, 0x01, 0x22, 0x89,
  6053. 0x81, 0x9c, 0x82, 0xb9, 0x31, 0x09, 0x81, 0x89,
  6054. 0x80, 0x89, 0x81, 0x9c, 0x82, 0xb9, 0x23, 0x09,
  6055. 0x0b, 0x80, 0x9d, 0x0a, 0x80, 0x8a, 0x82, 0xb9,
  6056. 0x38, 0x10, 0x81, 0x94, 0x81, 0x95, 0x13, 0x82,
  6057. 0xb9, 0x31, 0x09, 0x81, 0x88, 0x81, 0x89, 0x81,
  6058. 0x9d, 0x80, 0xba, 0x22, 0x10, 0x82, 0x89, 0x80,
  6059. 0xa7, 0x84, 0xb8, 0x30, 0x10, 0x17, 0x81, 0x8a,
  6060. 0x81, 0x9c, 0x82, 0xb9, 0x30, 0x10, 0x17, 0x81,
  6061. 0x8a, 0x81, 0x8e, 0x80, 0x8b, 0x83, 0xb9, 0x30,
  6062. 0x10, 0x82, 0x89, 0x80, 0x89, 0x81, 0x9c, 0x82,
  6063. 0xca, 0x28, 0x00, 0x87, 0x91, 0x81, 0xbc, 0x01,
  6064. 0x86, 0x91, 0x80, 0xe2, 0x01, 0x28, 0x81, 0x8f,
  6065. 0x80, 0x40, 0xa2, 0x92, 0x88, 0x8a, 0x80, 0xa3,
  6066. 0xed, 0x8b, 0x00, 0x0b, 0x96, 0x1b, 0x10, 0x11,
  6067. 0x32, 0x83, 0x8c, 0x8b, 0x00, 0x89, 0x83, 0x46,
  6068. 0x73, 0x81, 0x9d, 0x81, 0x9d, 0x81, 0x9d, 0x81,
  6069. 0xc1, 0x92, 0x40, 0xbb, 0x81, 0xa1, 0x80, 0xf5,
  6070. 0x8b, 0x83, 0x88, 0x40, 0xdd, 0x84, 0xb8, 0x89,
  6071. 0x81, 0x93, 0xc9, 0x81, 0x8a, 0x82, 0xb0, 0x84,
  6072. 0xaf, 0x8e, 0xbb, 0x82, 0x9d, 0x88, 0x09, 0xb8,
  6073. 0x8a, 0xb1, 0x92, 0x41, 0x9b, 0xa1, 0x46, 0xc0,
  6074. 0xb3, 0x48, 0xf5, 0x9f, 0x60, 0x78, 0x73, 0x87,
  6075. 0xa1, 0x81, 0x41, 0x61, 0x07, 0x80, 0x96, 0x84,
  6076. 0xd7, 0x81, 0xb1, 0x8f, 0x00, 0xb8, 0x80, 0xa5,
  6077. 0x84, 0x9b, 0x8b, 0xac, 0x83, 0xaf, 0x8b, 0xa4,
  6078. 0x80, 0xc2, 0x8d, 0x8b, 0x07, 0x81, 0xac, 0x82,
  6079. 0xb1, 0x00, 0x11, 0x0c, 0x80, 0xab, 0x24, 0x80,
  6080. 0x40, 0xec, 0x87, 0x60, 0x4f, 0x32, 0x80, 0x48,
  6081. 0x56, 0x84, 0x46, 0x85, 0x10, 0x0c, 0x83, 0x43,
  6082. 0x13, 0x83, 0xc0, 0x80, 0x41, 0x40, 0x81, 0xce,
  6083. 0x80, 0x41, 0x02, 0x82, 0xb4, 0x8d, 0xac, 0x81,
  6084. 0x8a, 0x82, 0xac, 0x88, 0x88, 0x80, 0xbc, 0x82,
  6085. 0xa3, 0x8b, 0x91, 0x81, 0xb8, 0x82, 0xaf, 0x8c,
  6086. 0x8d, 0x81, 0xdb, 0x88, 0x08, 0x28, 0x08, 0x40,
  6087. 0x9c, 0x89, 0x96, 0x83, 0xb9, 0x31, 0x09, 0x81,
  6088. 0x89, 0x80, 0x89, 0x81, 0xd3, 0x88, 0x00, 0x08,
  6089. 0x03, 0x01, 0xe6, 0x8c, 0x02, 0xe9, 0x91, 0x40,
  6090. 0xec, 0x31, 0x86, 0x9c, 0x81, 0xd1, 0x8e, 0x00,
  6091. 0xe9, 0x8a, 0xe6, 0x8d, 0x41, 0x00, 0x8c, 0x40,
  6092. 0xf6, 0x28, 0x09, 0x0a, 0x00, 0x80, 0x40, 0x8d,
  6093. 0x31, 0x2b, 0x80, 0x9b, 0x89, 0xa9, 0x20, 0x83,
  6094. 0x91, 0x8a, 0xad, 0x8d, 0x41, 0x96, 0x38, 0x86,
  6095. 0xd2, 0x95, 0x80, 0x8d, 0xf9, 0x2a, 0x00, 0x08,
  6096. 0x10, 0x02, 0x80, 0xc1, 0x20, 0x08, 0x83, 0x41,
  6097. 0x5b, 0x83, 0x88, 0x08, 0x80, 0xaf, 0x32, 0x82,
  6098. 0x60, 0x41, 0xdc, 0x90, 0x4e, 0x1f, 0x00, 0xb6,
  6099. 0x33, 0xdc, 0x81, 0x60, 0x4c, 0xab, 0x80, 0x60,
  6100. 0x23, 0x60, 0x30, 0x90, 0x0e, 0x01, 0x04, 0xe3,
  6101. 0x80, 0x48, 0xb6, 0x80, 0x47, 0xe7, 0x99, 0x85,
  6102. 0x99, 0x85, 0x99,
  6103. };
  6104. static const uint8_t unicode_prop_Other_Lowercase_table[69] = {
  6105. 0x40, 0xa9, 0x80, 0x8e, 0x80, 0x41, 0xf4, 0x88,
  6106. 0x31, 0x9d, 0x84, 0xdf, 0x80, 0xb3, 0x80, 0x4d,
  6107. 0x80, 0x80, 0x4c, 0x2e, 0xbe, 0x8c, 0x80, 0xa1,
  6108. 0xa4, 0x42, 0xb0, 0x80, 0x8c, 0x80, 0x8f, 0x8c,
  6109. 0x40, 0xd2, 0x8f, 0x43, 0x4f, 0x99, 0x47, 0x91,
  6110. 0x81, 0x60, 0x7a, 0x1d, 0x81, 0x40, 0xd1, 0x80,
  6111. 0x40, 0x80, 0x12, 0x81, 0x43, 0x61, 0x83, 0x88,
  6112. 0x80, 0x60, 0x5c, 0x15, 0x01, 0x10, 0xa9, 0x80,
  6113. 0x88, 0x60, 0xd8, 0x74, 0xbd,
  6114. };
  6115. static const uint8_t unicode_prop_Other_Uppercase_table[15] = {
  6116. 0x60, 0x21, 0x5f, 0x8f, 0x43, 0x45, 0x99, 0x61,
  6117. 0xcc, 0x5f, 0x99, 0x85, 0x99, 0x85, 0x99,
  6118. };
  6119. static const uint8_t unicode_prop_Other_Grapheme_Extend_table[112] = {
  6120. 0x49, 0xbd, 0x80, 0x97, 0x80, 0x41, 0x65, 0x80,
  6121. 0x97, 0x80, 0xe5, 0x80, 0x97, 0x80, 0x40, 0xe7,
  6122. 0x00, 0x03, 0x08, 0x81, 0x88, 0x81, 0xe6, 0x80,
  6123. 0x97, 0x80, 0xf6, 0x80, 0x8e, 0x80, 0x49, 0x34,
  6124. 0x80, 0x9d, 0x80, 0x43, 0xff, 0x04, 0x00, 0x04,
  6125. 0x81, 0xe4, 0x80, 0xc6, 0x81, 0x44, 0x17, 0x80,
  6126. 0x50, 0x20, 0x81, 0x60, 0x79, 0x22, 0x80, 0xeb,
  6127. 0x80, 0x60, 0x55, 0xdc, 0x81, 0x52, 0x1f, 0x80,
  6128. 0xf3, 0x80, 0x41, 0x07, 0x80, 0x8d, 0x80, 0x88,
  6129. 0x80, 0xdf, 0x80, 0x88, 0x01, 0x00, 0x14, 0x80,
  6130. 0x40, 0xdf, 0x80, 0x8b, 0x80, 0x40, 0xf0, 0x80,
  6131. 0x41, 0x05, 0x80, 0x42, 0x78, 0x80, 0x8b, 0x80,
  6132. 0x46, 0x02, 0x80, 0x60, 0x50, 0xad, 0x81, 0x60,
  6133. 0x61, 0x72, 0x0d, 0x85, 0x6c, 0x2e, 0xac, 0xdf,
  6134. };
  6135. static const uint8_t unicode_prop_Other_Default_Ignorable_Code_Point_table[32] = {
  6136. 0x43, 0x4e, 0x80, 0x4e, 0x0e, 0x81, 0x46, 0x52,
  6137. 0x81, 0x48, 0xae, 0x80, 0x50, 0xfd, 0x80, 0x60,
  6138. 0xce, 0x3a, 0x80, 0xce, 0x88, 0x6d, 0x00, 0x06,
  6139. 0x00, 0x9d, 0xdf, 0xff, 0x40, 0xef, 0x4e, 0x0f,
  6140. };
  6141. static const uint8_t unicode_prop_Other_ID_Start_table[11] = {
  6142. 0x58, 0x84, 0x81, 0x48, 0x90, 0x80, 0x94, 0x80,
  6143. 0x4f, 0x6b, 0x81,
  6144. };
  6145. static const uint8_t unicode_prop_Other_ID_Continue_table[22] = {
  6146. 0x40, 0xb6, 0x80, 0x42, 0xce, 0x80, 0x4f, 0xe0,
  6147. 0x88, 0x46, 0x67, 0x80, 0x46, 0x30, 0x81, 0x50,
  6148. 0xec, 0x80, 0x60, 0xce, 0x68, 0x80,
  6149. };
  6150. static const uint8_t unicode_prop_Prepended_Concatenation_Mark_table[19] = {
  6151. 0x45, 0xff, 0x85, 0x40, 0xd6, 0x80, 0xb0, 0x80,
  6152. 0x41, 0x7f, 0x81, 0xcf, 0x80, 0x61, 0x07, 0xd9,
  6153. 0x80, 0x8e, 0x80,
  6154. };
  6155. static const uint8_t unicode_prop_XID_Start1_table[31] = {
  6156. 0x43, 0x79, 0x80, 0x4a, 0xb7, 0x80, 0xfe, 0x80,
  6157. 0x60, 0x21, 0xe6, 0x81, 0x60, 0xcb, 0xc0, 0x85,
  6158. 0x41, 0x95, 0x81, 0xf3, 0x00, 0x00, 0x00, 0x00,
  6159. 0x00, 0x00, 0x00, 0x80, 0x41, 0x1e, 0x81,
  6160. };
  6161. static const uint8_t unicode_prop_XID_Continue1_table[23] = {
  6162. 0x43, 0x79, 0x80, 0x60, 0x2d, 0x1f, 0x81, 0x60,
  6163. 0xcb, 0xc0, 0x85, 0x41, 0x95, 0x81, 0xf3, 0x00,
  6164. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80,
  6165. };
  6166. static const uint8_t unicode_prop_Changes_When_Titlecased1_table[22] = {
  6167. 0x41, 0xc3, 0x08, 0x08, 0x81, 0xa4, 0x81, 0x4e,
  6168. 0xdc, 0xaa, 0x0a, 0x4e, 0x87, 0x3f, 0x3f, 0x87,
  6169. 0x8b, 0x80, 0x8e, 0x80, 0xae, 0x80,
  6170. };
  6171. static const uint8_t unicode_prop_Changes_When_Casefolded1_table[29] = {
  6172. 0x41, 0xef, 0x80, 0x41, 0x9e, 0x80, 0x9e, 0x80,
  6173. 0x5a, 0xe4, 0x83, 0x40, 0xb5, 0x00, 0x00, 0x00,
  6174. 0x80, 0xde, 0x06, 0x06, 0x80, 0x8a, 0x09, 0x81,
  6175. 0x89, 0x10, 0x81, 0x8d, 0x80,
  6176. };
  6177. static const uint8_t unicode_prop_Changes_When_NFKC_Casefolded1_table[450] = {
  6178. 0x40, 0x9f, 0x06, 0x00, 0x01, 0x00, 0x01, 0x12,
  6179. 0x10, 0x82, 0xf3, 0x80, 0x8b, 0x80, 0x40, 0x84,
  6180. 0x01, 0x01, 0x80, 0xa2, 0x01, 0x80, 0x40, 0xbb,
  6181. 0x88, 0x9e, 0x29, 0x84, 0xda, 0x08, 0x81, 0x89,
  6182. 0x80, 0xa3, 0x04, 0x02, 0x04, 0x08, 0x07, 0x80,
  6183. 0x9e, 0x80, 0xa0, 0x82, 0x9c, 0x80, 0x42, 0x28,
  6184. 0x80, 0xd7, 0x83, 0x42, 0xde, 0x87, 0xfb, 0x08,
  6185. 0x80, 0xd2, 0x01, 0x80, 0xa1, 0x11, 0x80, 0x40,
  6186. 0xfc, 0x81, 0x42, 0xd4, 0x80, 0xfe, 0x80, 0xa7,
  6187. 0x81, 0xad, 0x80, 0xb5, 0x80, 0x88, 0x03, 0x03,
  6188. 0x03, 0x80, 0x8b, 0x80, 0x88, 0x00, 0x26, 0x80,
  6189. 0x90, 0x80, 0x88, 0x03, 0x03, 0x03, 0x80, 0x8b,
  6190. 0x80, 0x41, 0x41, 0x80, 0xe1, 0x81, 0x46, 0x52,
  6191. 0x81, 0xd4, 0x84, 0x45, 0x1b, 0x10, 0x8a, 0x80,
  6192. 0x91, 0x80, 0x9b, 0x8c, 0x80, 0xa1, 0xa4, 0x40,
  6193. 0xd5, 0x83, 0x40, 0xb5, 0x00, 0x00, 0x00, 0x80,
  6194. 0x99, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80,
  6195. 0xb7, 0x05, 0x00, 0x13, 0x05, 0x11, 0x02, 0x0c,
  6196. 0x11, 0x00, 0x00, 0x0c, 0x15, 0x05, 0x08, 0x8f,
  6197. 0x00, 0x20, 0x8b, 0x12, 0x2a, 0x08, 0x0b, 0x00,
  6198. 0x07, 0x82, 0x8c, 0x06, 0x92, 0x81, 0x9a, 0x80,
  6199. 0x8c, 0x8a, 0x80, 0xd6, 0x18, 0x10, 0x8a, 0x01,
  6200. 0x0c, 0x0a, 0x00, 0x10, 0x11, 0x02, 0x06, 0x05,
  6201. 0x1c, 0x85, 0x8f, 0x8f, 0x8f, 0x88, 0x80, 0x40,
  6202. 0xa1, 0x08, 0x81, 0x40, 0xf7, 0x81, 0x41, 0x34,
  6203. 0xd5, 0x99, 0x9a, 0x45, 0x20, 0x80, 0xe6, 0x82,
  6204. 0xe4, 0x80, 0x41, 0x9e, 0x81, 0x40, 0xf0, 0x80,
  6205. 0x41, 0x2e, 0x80, 0xd2, 0x80, 0x8b, 0x40, 0xd5,
  6206. 0xa9, 0x80, 0xb4, 0x00, 0x82, 0xdf, 0x09, 0x80,
  6207. 0xde, 0x80, 0xb0, 0xdd, 0x82, 0x8d, 0xdf, 0x9e,
  6208. 0x80, 0xa7, 0x87, 0xae, 0x80, 0x41, 0x7f, 0x60,
  6209. 0x72, 0x9b, 0x81, 0x40, 0xd1, 0x80, 0x40, 0x80,
  6210. 0x12, 0x81, 0x43, 0x61, 0x83, 0x88, 0x80, 0x60,
  6211. 0x4d, 0x95, 0x41, 0x0d, 0x08, 0x00, 0x81, 0x89,
  6212. 0x00, 0x00, 0x09, 0x82, 0xc3, 0x81, 0xe9, 0xc2,
  6213. 0x00, 0x97, 0x04, 0x00, 0x01, 0x01, 0x80, 0xeb,
  6214. 0xa0, 0x41, 0x6a, 0x91, 0xbf, 0x81, 0xb5, 0xa7,
  6215. 0x8c, 0x82, 0x99, 0x95, 0x94, 0x81, 0x8b, 0x80,
  6216. 0x92, 0x03, 0x1a, 0x00, 0x80, 0x40, 0x86, 0x08,
  6217. 0x80, 0x9f, 0x99, 0x40, 0x83, 0x15, 0x0d, 0x0d,
  6218. 0x0a, 0x16, 0x06, 0x80, 0x88, 0x47, 0x87, 0x20,
  6219. 0xa9, 0x80, 0x88, 0x60, 0xb4, 0xe4, 0x83, 0x50,
  6220. 0x31, 0xa3, 0x44, 0x63, 0x86, 0x8d, 0x87, 0xbf,
  6221. 0x85, 0x42, 0x3e, 0xd4, 0x80, 0xc6, 0x01, 0x08,
  6222. 0x09, 0x0b, 0x80, 0x8b, 0x00, 0x06, 0x80, 0xc0,
  6223. 0x03, 0x0f, 0x06, 0x80, 0x9b, 0x03, 0x04, 0x00,
  6224. 0x16, 0x80, 0x41, 0x53, 0x81, 0x41, 0x23, 0x81,
  6225. 0xb1, 0x48, 0x2f, 0xbd, 0x4d, 0x91, 0x18, 0x9a,
  6226. 0x01, 0x00, 0x08, 0x80, 0x89, 0x03, 0x00, 0x00,
  6227. 0x28, 0x18, 0x00, 0x00, 0x02, 0x01, 0x00, 0x08,
  6228. 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x0b, 0x06,
  6229. 0x03, 0x03, 0x00, 0x80, 0x89, 0x80, 0x90, 0x22,
  6230. 0x04, 0x80, 0x90, 0x42, 0x43, 0x8a, 0x84, 0x9e,
  6231. 0x80, 0x9f, 0x99, 0x82, 0xa2, 0x80, 0xee, 0x82,
  6232. 0x8c, 0xab, 0x83, 0x88, 0x31, 0x49, 0x9d, 0x89,
  6233. 0x60, 0xfc, 0x05, 0x42, 0x1d, 0x6b, 0x05, 0xe1,
  6234. 0x4f, 0xff,
  6235. };
  6236. static const uint8_t unicode_prop_ASCII_Hex_Digit_table[5] = {
  6237. 0xaf, 0x89, 0x35, 0x99, 0x85,
  6238. };
  6239. static const uint8_t unicode_prop_Bidi_Control_table[10] = {
  6240. 0x46, 0x1b, 0x80, 0x59, 0xf0, 0x81, 0x99, 0x84,
  6241. 0xb6, 0x83,
  6242. };
  6243. static const uint8_t unicode_prop_Dash_table[58] = {
  6244. 0xac, 0x80, 0x45, 0x5b, 0x80, 0xb2, 0x80, 0x4e,
  6245. 0x40, 0x80, 0x44, 0x04, 0x80, 0x48, 0x08, 0x85,
  6246. 0xbc, 0x80, 0xa6, 0x80, 0x8e, 0x80, 0x41, 0x85,
  6247. 0x80, 0x4c, 0x03, 0x01, 0x80, 0x9e, 0x0b, 0x80,
  6248. 0x9b, 0x80, 0x41, 0xbd, 0x80, 0x92, 0x80, 0xee,
  6249. 0x80, 0x60, 0xcd, 0x8f, 0x81, 0xa4, 0x80, 0x89,
  6250. 0x80, 0x40, 0xa8, 0x80, 0x4e, 0x5f, 0x80, 0x41,
  6251. 0x3d, 0x80,
  6252. };
  6253. static const uint8_t unicode_prop_Deprecated_table[23] = {
  6254. 0x41, 0x48, 0x80, 0x45, 0x28, 0x80, 0x49, 0x02,
  6255. 0x00, 0x80, 0x48, 0x28, 0x81, 0x48, 0xc4, 0x85,
  6256. 0x42, 0xb8, 0x81, 0x6d, 0xdc, 0xd5, 0x80,
  6257. };
  6258. static const uint8_t unicode_prop_Diacritic_table[438] = {
  6259. 0xdd, 0x00, 0x80, 0xc6, 0x05, 0x03, 0x01, 0x81,
  6260. 0x41, 0xf6, 0x40, 0x9e, 0x07, 0x25, 0x90, 0x0b,
  6261. 0x80, 0x88, 0x81, 0x40, 0xfc, 0x84, 0x40, 0xd0,
  6262. 0x80, 0xb6, 0x90, 0x80, 0x9a, 0x00, 0x01, 0x00,
  6263. 0x40, 0x85, 0x3b, 0x81, 0x40, 0x85, 0x0b, 0x0a,
  6264. 0x82, 0xc2, 0x9a, 0xda, 0x8a, 0xb9, 0x8a, 0xa1,
  6265. 0x81, 0xfd, 0x87, 0xa8, 0x89, 0x8f, 0x9b, 0xbc,
  6266. 0x80, 0x8f, 0x02, 0x83, 0x9b, 0x80, 0xc9, 0x80,
  6267. 0x8f, 0x80, 0xed, 0x80, 0x8f, 0x80, 0xed, 0x80,
  6268. 0x8f, 0x80, 0xae, 0x82, 0xbb, 0x80, 0x8f, 0x06,
  6269. 0x80, 0xf6, 0x80, 0xed, 0x80, 0x8f, 0x80, 0xed,
  6270. 0x80, 0x8f, 0x80, 0xec, 0x81, 0x8f, 0x80, 0xfb,
  6271. 0x80, 0xee, 0x80, 0x8b, 0x28, 0x80, 0xea, 0x80,
  6272. 0x8c, 0x84, 0xca, 0x81, 0x9a, 0x00, 0x00, 0x03,
  6273. 0x81, 0xc1, 0x10, 0x81, 0xbd, 0x80, 0xef, 0x00,
  6274. 0x81, 0xa7, 0x0b, 0x84, 0x98, 0x30, 0x80, 0x89,
  6275. 0x81, 0x42, 0xc0, 0x82, 0x43, 0xb3, 0x81, 0x9d,
  6276. 0x80, 0x40, 0x93, 0x8a, 0x88, 0x80, 0x41, 0x5a,
  6277. 0x82, 0x41, 0x23, 0x80, 0x93, 0x39, 0x80, 0xaf,
  6278. 0x8e, 0x81, 0x8a, 0xe7, 0x80, 0x8e, 0x80, 0xa5,
  6279. 0x88, 0xb5, 0x81, 0xb9, 0x80, 0x8a, 0x81, 0xc1,
  6280. 0x81, 0xbf, 0x85, 0xd1, 0x98, 0x18, 0x28, 0x0a,
  6281. 0xb1, 0xbe, 0xd8, 0x8b, 0xa4, 0x8a, 0x41, 0xbc,
  6282. 0x00, 0x82, 0x8a, 0x82, 0x8c, 0x82, 0x8c, 0x82,
  6283. 0x8c, 0x81, 0x4c, 0xef, 0x82, 0x41, 0x3c, 0x80,
  6284. 0x41, 0xf9, 0x85, 0xe8, 0x83, 0xde, 0x80, 0x60,
  6285. 0x75, 0x71, 0x80, 0x8b, 0x08, 0x80, 0x9b, 0x81,
  6286. 0xd1, 0x81, 0x8d, 0xa1, 0xe5, 0x82, 0xec, 0x81,
  6287. 0x8b, 0x80, 0xa4, 0x80, 0x40, 0x96, 0x80, 0x9a,
  6288. 0x91, 0xb8, 0x83, 0xa3, 0x80, 0xde, 0x80, 0x8b,
  6289. 0x80, 0xa3, 0x80, 0x40, 0x94, 0x82, 0xc0, 0x83,
  6290. 0xb2, 0x80, 0xe3, 0x84, 0x88, 0x82, 0xff, 0x81,
  6291. 0x60, 0x4f, 0x2f, 0x80, 0x43, 0x00, 0x8f, 0x41,
  6292. 0x0d, 0x00, 0x80, 0xae, 0x80, 0xac, 0x81, 0xc2,
  6293. 0x80, 0x42, 0xfb, 0x80, 0x44, 0x9e, 0x28, 0xa9,
  6294. 0x80, 0x88, 0x42, 0x7c, 0x13, 0x80, 0x40, 0xa4,
  6295. 0x81, 0x42, 0x3a, 0x85, 0xa5, 0x80, 0x99, 0x84,
  6296. 0x41, 0x8e, 0x82, 0xc5, 0x8a, 0xb0, 0x83, 0x40,
  6297. 0xbf, 0x80, 0xa8, 0x80, 0xc7, 0x81, 0xf7, 0x81,
  6298. 0xbd, 0x80, 0xcb, 0x80, 0x88, 0x82, 0xe7, 0x81,
  6299. 0x40, 0xb1, 0x81, 0xcf, 0x81, 0x8f, 0x80, 0x97,
  6300. 0x32, 0x84, 0xd8, 0x10, 0x81, 0x8c, 0x81, 0xde,
  6301. 0x02, 0x80, 0xfa, 0x81, 0x40, 0xfa, 0x81, 0xfd,
  6302. 0x80, 0xf5, 0x81, 0xf2, 0x80, 0x41, 0x0c, 0x81,
  6303. 0x41, 0x01, 0x0b, 0x80, 0x40, 0x9b, 0x80, 0xd2,
  6304. 0x80, 0x91, 0x80, 0xd0, 0x80, 0x41, 0xa4, 0x80,
  6305. 0x41, 0x01, 0x00, 0x81, 0xd0, 0x80, 0x41, 0xa8,
  6306. 0x81, 0x96, 0x80, 0x54, 0xeb, 0x8e, 0x60, 0x2c,
  6307. 0xd8, 0x80, 0x49, 0xbf, 0x84, 0xba, 0x86, 0x42,
  6308. 0x33, 0x81, 0x42, 0x21, 0x90, 0xcf, 0x81, 0x60,
  6309. 0x3f, 0xfd, 0x18, 0x30, 0x81, 0x5f, 0x00, 0xad,
  6310. 0x81, 0x96, 0x42, 0x1f, 0x12, 0x2f, 0x39, 0x86,
  6311. 0x9d, 0x83, 0x4e, 0x81, 0xbd, 0x40, 0xc1, 0x86,
  6312. 0x41, 0x76, 0x80, 0xbc, 0x83, 0x42, 0xfd, 0x81,
  6313. 0x42, 0xdf, 0x86, 0xec, 0x10, 0x82,
  6314. };
  6315. static const uint8_t unicode_prop_Extender_table[111] = {
  6316. 0x40, 0xb6, 0x80, 0x42, 0x17, 0x81, 0x43, 0x6d,
  6317. 0x80, 0x41, 0xb8, 0x80, 0x42, 0x75, 0x80, 0x40,
  6318. 0x88, 0x80, 0xd8, 0x80, 0x42, 0xef, 0x80, 0xfe,
  6319. 0x80, 0x49, 0x42, 0x80, 0xb7, 0x80, 0x42, 0x62,
  6320. 0x80, 0x41, 0x8d, 0x80, 0xc3, 0x80, 0x53, 0x88,
  6321. 0x80, 0xaa, 0x84, 0xe6, 0x81, 0xdc, 0x82, 0x60,
  6322. 0x6f, 0x15, 0x80, 0x45, 0xf5, 0x80, 0x43, 0xc1,
  6323. 0x80, 0x95, 0x80, 0x40, 0x88, 0x80, 0xeb, 0x80,
  6324. 0x94, 0x81, 0x60, 0x54, 0x7a, 0x80, 0x48, 0x0f,
  6325. 0x81, 0x45, 0xca, 0x80, 0x9a, 0x03, 0x80, 0x44,
  6326. 0xc6, 0x80, 0x41, 0x24, 0x80, 0xf3, 0x81, 0x41,
  6327. 0xf1, 0x82, 0x44, 0xce, 0x80, 0x60, 0x50, 0xa8,
  6328. 0x81, 0x44, 0x9b, 0x08, 0x80, 0x60, 0x71, 0x57,
  6329. 0x81, 0x44, 0xb0, 0x80, 0x43, 0x53, 0x82,
  6330. };
  6331. static const uint8_t unicode_prop_Hex_Digit_table[12] = {
  6332. 0xaf, 0x89, 0x35, 0x99, 0x85, 0x60, 0xfe, 0xa8,
  6333. 0x89, 0x35, 0x99, 0x85,
  6334. };
  6335. static const uint8_t unicode_prop_IDS_Unary_Operator_table[4] = {
  6336. 0x60, 0x2f, 0xfd, 0x81,
  6337. };
  6338. static const uint8_t unicode_prop_IDS_Binary_Operator_table[8] = {
  6339. 0x60, 0x2f, 0xef, 0x09, 0x89, 0x41, 0xf0, 0x80,
  6340. };
  6341. static const uint8_t unicode_prop_IDS_Trinary_Operator_table[4] = {
  6342. 0x60, 0x2f, 0xf1, 0x81,
  6343. };
  6344. static const uint8_t unicode_prop_Ideographic_table[72] = {
  6345. 0x60, 0x30, 0x05, 0x81, 0x98, 0x88, 0x8d, 0x82,
  6346. 0x43, 0xc4, 0x59, 0xbf, 0xbf, 0x60, 0x51, 0xff,
  6347. 0x60, 0x58, 0xff, 0x41, 0x6d, 0x81, 0xe9, 0x60,
  6348. 0x75, 0x09, 0x80, 0x9a, 0x57, 0xf7, 0x87, 0x44,
  6349. 0xd5, 0xa8, 0x89, 0x60, 0x24, 0x66, 0x41, 0x8b,
  6350. 0x60, 0x4d, 0x03, 0x60, 0xa6, 0xdf, 0x9f, 0x50,
  6351. 0x39, 0x85, 0x40, 0xdd, 0x81, 0x56, 0x81, 0x8d,
  6352. 0x5d, 0x30, 0x8e, 0x42, 0x6d, 0x49, 0xa1, 0x42,
  6353. 0x1d, 0x45, 0xe1, 0x53, 0x4a, 0x84, 0x50, 0x5f,
  6354. };
  6355. static const uint8_t unicode_prop_Join_Control_table[4] = {
  6356. 0x60, 0x20, 0x0b, 0x81,
  6357. };
  6358. static const uint8_t unicode_prop_Logical_Order_Exception_table[15] = {
  6359. 0x4e, 0x3f, 0x84, 0xfa, 0x84, 0x4a, 0xef, 0x11,
  6360. 0x80, 0x60, 0x90, 0xf9, 0x09, 0x00, 0x81,
  6361. };
  6362. static const uint8_t unicode_prop_Modifier_Combining_Mark_table[16] = {
  6363. 0x46, 0x53, 0x09, 0x80, 0x40, 0x82, 0x05, 0x02,
  6364. 0x81, 0x41, 0xe0, 0x08, 0x12, 0x80, 0x9e, 0x80,
  6365. };
  6366. static const uint8_t unicode_prop_Noncharacter_Code_Point_table[71] = {
  6367. 0x60, 0xfd, 0xcf, 0x9f, 0x42, 0x0d, 0x81, 0x60,
  6368. 0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81, 0x60,
  6369. 0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81, 0x60,
  6370. 0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81, 0x60,
  6371. 0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81, 0x60,
  6372. 0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81, 0x60,
  6373. 0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81, 0x60,
  6374. 0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81, 0x60,
  6375. 0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81,
  6376. };
  6377. static const uint8_t unicode_prop_Pattern_Syntax_table[58] = {
  6378. 0xa0, 0x8e, 0x89, 0x86, 0x99, 0x18, 0x80, 0x99,
  6379. 0x83, 0xa1, 0x30, 0x00, 0x08, 0x00, 0x0b, 0x03,
  6380. 0x02, 0x80, 0x96, 0x80, 0x9e, 0x80, 0x5f, 0x17,
  6381. 0x97, 0x87, 0x8e, 0x81, 0x92, 0x80, 0x89, 0x41,
  6382. 0x30, 0x42, 0xcf, 0x40, 0x9f, 0x42, 0x75, 0x9d,
  6383. 0x44, 0x6b, 0x41, 0xff, 0xff, 0x41, 0x80, 0x13,
  6384. 0x98, 0x8e, 0x80, 0x60, 0xcd, 0x0c, 0x81, 0x41,
  6385. 0x04, 0x81,
  6386. };
  6387. static const uint8_t unicode_prop_Pattern_White_Space_table[11] = {
  6388. 0x88, 0x84, 0x91, 0x80, 0xe3, 0x80, 0x5f, 0x87,
  6389. 0x81, 0x97, 0x81,
  6390. };
  6391. static const uint8_t unicode_prop_Quotation_Mark_table[31] = {
  6392. 0xa1, 0x03, 0x80, 0x40, 0x82, 0x80, 0x8e, 0x80,
  6393. 0x5f, 0x5b, 0x87, 0x98, 0x81, 0x4e, 0x06, 0x80,
  6394. 0x41, 0xc8, 0x83, 0x8c, 0x82, 0x60, 0xce, 0x20,
  6395. 0x83, 0x40, 0xbc, 0x03, 0x80, 0xd9, 0x81,
  6396. };
  6397. static const uint8_t unicode_prop_Radical_table[9] = {
  6398. 0x60, 0x2e, 0x7f, 0x99, 0x80, 0xd8, 0x8b, 0x40,
  6399. 0xd5,
  6400. };
  6401. static const uint8_t unicode_prop_Regional_Indicator_table[4] = {
  6402. 0x61, 0xf1, 0xe5, 0x99,
  6403. };
  6404. static const uint8_t unicode_prop_Sentence_Terminal_table[213] = {
  6405. 0xa0, 0x80, 0x8b, 0x80, 0x8f, 0x80, 0x45, 0x48,
  6406. 0x80, 0x40, 0x92, 0x82, 0x40, 0xb3, 0x80, 0xaa,
  6407. 0x82, 0x40, 0xf5, 0x80, 0xbc, 0x00, 0x02, 0x81,
  6408. 0x41, 0x24, 0x81, 0x46, 0xe3, 0x81, 0x43, 0x15,
  6409. 0x03, 0x81, 0x43, 0x04, 0x80, 0x40, 0xc5, 0x81,
  6410. 0x40, 0x9c, 0x81, 0xac, 0x04, 0x80, 0x41, 0x39,
  6411. 0x81, 0x41, 0x61, 0x83, 0x40, 0xa1, 0x81, 0x89,
  6412. 0x09, 0x81, 0x9c, 0x82, 0x40, 0xba, 0x81, 0xc0,
  6413. 0x81, 0x43, 0xa3, 0x80, 0x96, 0x81, 0x88, 0x82,
  6414. 0x4c, 0xae, 0x82, 0x41, 0x31, 0x80, 0x8c, 0x80,
  6415. 0x95, 0x81, 0x41, 0xac, 0x80, 0x60, 0x74, 0xfb,
  6416. 0x80, 0x41, 0x0d, 0x81, 0x40, 0xe2, 0x02, 0x80,
  6417. 0x41, 0x7d, 0x81, 0xd5, 0x81, 0xde, 0x80, 0x40,
  6418. 0x97, 0x81, 0x40, 0x92, 0x82, 0x40, 0x8f, 0x81,
  6419. 0x40, 0xf8, 0x80, 0x60, 0x52, 0x25, 0x01, 0x81,
  6420. 0xba, 0x02, 0x81, 0x40, 0xa8, 0x80, 0x8b, 0x80,
  6421. 0x8f, 0x80, 0xc0, 0x80, 0x4a, 0xf3, 0x81, 0x44,
  6422. 0xfc, 0x84, 0xab, 0x83, 0x40, 0xbc, 0x81, 0xf4,
  6423. 0x83, 0xfe, 0x82, 0x40, 0x80, 0x0d, 0x80, 0x8f,
  6424. 0x81, 0xd7, 0x08, 0x81, 0xeb, 0x80, 0x41, 0x29,
  6425. 0x81, 0xf4, 0x81, 0x41, 0x74, 0x0c, 0x8e, 0xe8,
  6426. 0x81, 0x40, 0xf8, 0x82, 0x42, 0x04, 0x00, 0x80,
  6427. 0x40, 0xfa, 0x81, 0xd6, 0x81, 0x41, 0xa3, 0x81,
  6428. 0x42, 0xb3, 0x81, 0xc9, 0x81, 0x60, 0x4b, 0x28,
  6429. 0x81, 0x40, 0x84, 0x80, 0xc0, 0x81, 0x8a, 0x80,
  6430. 0x42, 0x28, 0x81, 0x41, 0x27, 0x80, 0x60, 0x4e,
  6431. 0x05, 0x80, 0x5d, 0xe7, 0x80,
  6432. };
  6433. static const uint8_t unicode_prop_Soft_Dotted_table[79] = {
  6434. 0xe8, 0x81, 0x40, 0xc3, 0x80, 0x41, 0x18, 0x80,
  6435. 0x9d, 0x80, 0xb3, 0x80, 0x93, 0x80, 0x41, 0x3f,
  6436. 0x80, 0xe1, 0x00, 0x80, 0x59, 0x08, 0x80, 0xb2,
  6437. 0x80, 0x8c, 0x02, 0x80, 0x40, 0x83, 0x80, 0x40,
  6438. 0x9c, 0x80, 0x41, 0xa4, 0x80, 0x40, 0xd5, 0x81,
  6439. 0x4b, 0x31, 0x80, 0x61, 0xa7, 0xa4, 0x81, 0xb1,
  6440. 0x81, 0xb1, 0x81, 0xb1, 0x81, 0xb1, 0x81, 0xb1,
  6441. 0x81, 0xb1, 0x81, 0xb1, 0x81, 0xb1, 0x81, 0xb1,
  6442. 0x81, 0xb1, 0x81, 0xb1, 0x81, 0xb1, 0x81, 0x48,
  6443. 0x85, 0x80, 0x41, 0x30, 0x81, 0x99, 0x80,
  6444. };
  6445. static const uint8_t unicode_prop_Terminal_Punctuation_table[264] = {
  6446. 0xa0, 0x80, 0x89, 0x00, 0x80, 0x8a, 0x0a, 0x80,
  6447. 0x43, 0x3d, 0x07, 0x80, 0x42, 0x00, 0x80, 0xb8,
  6448. 0x80, 0xc7, 0x80, 0x8d, 0x00, 0x82, 0x40, 0xb3,
  6449. 0x80, 0xaa, 0x8a, 0x00, 0x40, 0xea, 0x81, 0xb5,
  6450. 0x28, 0x87, 0x9e, 0x80, 0x41, 0x04, 0x81, 0x44,
  6451. 0xf3, 0x81, 0x40, 0xab, 0x03, 0x85, 0x41, 0x36,
  6452. 0x81, 0x43, 0x14, 0x87, 0x43, 0x04, 0x80, 0xfb,
  6453. 0x82, 0xc6, 0x81, 0x40, 0x9c, 0x12, 0x80, 0xa6,
  6454. 0x19, 0x81, 0x41, 0x39, 0x81, 0x41, 0x61, 0x83,
  6455. 0x40, 0xa1, 0x81, 0x89, 0x08, 0x82, 0x9c, 0x82,
  6456. 0x40, 0xba, 0x84, 0xbd, 0x81, 0x43, 0xa3, 0x80,
  6457. 0x96, 0x81, 0x88, 0x82, 0x4c, 0xae, 0x82, 0x41,
  6458. 0x31, 0x80, 0x8c, 0x03, 0x80, 0x89, 0x00, 0x0a,
  6459. 0x81, 0x41, 0xab, 0x81, 0x60, 0x74, 0xfa, 0x81,
  6460. 0x41, 0x0c, 0x82, 0x40, 0xe2, 0x84, 0x41, 0x7d,
  6461. 0x81, 0xd5, 0x81, 0xde, 0x80, 0x40, 0x96, 0x82,
  6462. 0x40, 0x92, 0x82, 0xfe, 0x80, 0x8f, 0x81, 0x40,
  6463. 0xf8, 0x80, 0x60, 0x52, 0x25, 0x01, 0x81, 0xb8,
  6464. 0x10, 0x83, 0x40, 0xa8, 0x80, 0x89, 0x00, 0x80,
  6465. 0x8a, 0x0a, 0x80, 0xc0, 0x01, 0x80, 0x44, 0x39,
  6466. 0x80, 0xaf, 0x80, 0x44, 0x85, 0x80, 0x40, 0xc6,
  6467. 0x80, 0x41, 0x35, 0x81, 0x40, 0x97, 0x85, 0xc3,
  6468. 0x85, 0xd8, 0x83, 0x43, 0xb7, 0x84, 0xab, 0x83,
  6469. 0x40, 0xbc, 0x86, 0xef, 0x83, 0xfe, 0x82, 0x40,
  6470. 0x80, 0x0d, 0x80, 0x8f, 0x81, 0xd7, 0x84, 0xeb,
  6471. 0x80, 0x41, 0x29, 0x81, 0xf4, 0x82, 0x8b, 0x81,
  6472. 0x41, 0x65, 0x1a, 0x8e, 0xe8, 0x81, 0x40, 0xf8,
  6473. 0x82, 0x42, 0x04, 0x00, 0x80, 0x40, 0xfa, 0x81,
  6474. 0xd6, 0x0b, 0x81, 0x41, 0x9d, 0x82, 0xac, 0x80,
  6475. 0x42, 0x84, 0x81, 0xc9, 0x81, 0x45, 0x2a, 0x84,
  6476. 0x60, 0x45, 0xf8, 0x81, 0x40, 0x84, 0x80, 0xc0,
  6477. 0x82, 0x89, 0x80, 0x42, 0x28, 0x81, 0x41, 0x26,
  6478. 0x81, 0x60, 0x4e, 0x05, 0x80, 0x5d, 0xe6, 0x83,
  6479. };
  6480. static const uint8_t unicode_prop_Unified_Ideograph_table[48] = {
  6481. 0x60, 0x33, 0xff, 0x59, 0xbf, 0xbf, 0x60, 0x51,
  6482. 0xff, 0x60, 0x5a, 0x0d, 0x08, 0x00, 0x81, 0x89,
  6483. 0x00, 0x00, 0x09, 0x82, 0x61, 0x05, 0xd5, 0x60,
  6484. 0xa6, 0xdf, 0x9f, 0x50, 0x39, 0x85, 0x40, 0xdd,
  6485. 0x81, 0x56, 0x81, 0x8d, 0x5d, 0x30, 0x8e, 0x42,
  6486. 0x6d, 0x51, 0xa1, 0x53, 0x4a, 0x84, 0x50, 0x5f,
  6487. };
  6488. static const uint8_t unicode_prop_Variation_Selector_table[13] = {
  6489. 0x58, 0x0a, 0x10, 0x80, 0x60, 0xe5, 0xef, 0x8f,
  6490. 0x6d, 0x02, 0xef, 0x40, 0xef,
  6491. };
  6492. static const uint8_t unicode_prop_Bidi_Mirrored_table[173] = {
  6493. 0xa7, 0x81, 0x91, 0x00, 0x80, 0x9b, 0x00, 0x80,
  6494. 0x9c, 0x00, 0x80, 0xac, 0x80, 0x8e, 0x80, 0x4e,
  6495. 0x7d, 0x83, 0x47, 0x5c, 0x81, 0x49, 0x9b, 0x81,
  6496. 0x89, 0x81, 0xb5, 0x81, 0x8d, 0x81, 0x40, 0xb0,
  6497. 0x80, 0x40, 0xbf, 0x1a, 0x2a, 0x02, 0x0a, 0x18,
  6498. 0x18, 0x00, 0x03, 0x88, 0x20, 0x80, 0x91, 0x23,
  6499. 0x88, 0x08, 0x00, 0x38, 0x9f, 0x0b, 0x20, 0x88,
  6500. 0x09, 0x92, 0x21, 0x88, 0x21, 0x0b, 0x97, 0x81,
  6501. 0x8f, 0x3b, 0x93, 0x0e, 0x81, 0x44, 0x3c, 0x8d,
  6502. 0xc9, 0x01, 0x18, 0x08, 0x14, 0x1c, 0x12, 0x8d,
  6503. 0x41, 0x92, 0x95, 0x0d, 0x80, 0x8d, 0x38, 0x35,
  6504. 0x10, 0x1c, 0x01, 0x0c, 0x18, 0x02, 0x09, 0x89,
  6505. 0x29, 0x81, 0x8b, 0x92, 0x03, 0x08, 0x00, 0x08,
  6506. 0x03, 0x21, 0x2a, 0x97, 0x81, 0x8a, 0x0b, 0x18,
  6507. 0x09, 0x0b, 0xaa, 0x0f, 0x80, 0xa7, 0x20, 0x00,
  6508. 0x14, 0x22, 0x18, 0x14, 0x00, 0x40, 0xff, 0x80,
  6509. 0x42, 0x02, 0x1a, 0x08, 0x81, 0x8d, 0x09, 0x89,
  6510. 0xaa, 0x87, 0x41, 0xaa, 0x89, 0x0f, 0x60, 0xce,
  6511. 0x3c, 0x2c, 0x81, 0x40, 0xa1, 0x81, 0x91, 0x00,
  6512. 0x80, 0x9b, 0x00, 0x80, 0x9c, 0x00, 0x00, 0x08,
  6513. 0x81, 0x60, 0xd7, 0x76, 0x80, 0xb8, 0x80, 0xb8,
  6514. 0x80, 0xb8, 0x80, 0xb8, 0x80,
  6515. };
  6516. static const uint8_t unicode_prop_Emoji_table[238] = {
  6517. 0xa2, 0x05, 0x04, 0x89, 0xee, 0x03, 0x80, 0x5f,
  6518. 0x8c, 0x80, 0x8b, 0x80, 0x40, 0xd7, 0x80, 0x95,
  6519. 0x80, 0xd9, 0x85, 0x8e, 0x81, 0x41, 0x6e, 0x81,
  6520. 0x8b, 0x80, 0x40, 0xa5, 0x80, 0x98, 0x8a, 0x1a,
  6521. 0x40, 0xc6, 0x80, 0x40, 0xe6, 0x81, 0x89, 0x80,
  6522. 0x88, 0x80, 0xb9, 0x18, 0x84, 0x88, 0x01, 0x01,
  6523. 0x09, 0x03, 0x01, 0x00, 0x09, 0x02, 0x02, 0x0f,
  6524. 0x14, 0x00, 0x04, 0x8b, 0x8a, 0x09, 0x00, 0x08,
  6525. 0x80, 0x91, 0x01, 0x81, 0x91, 0x28, 0x00, 0x0a,
  6526. 0x0c, 0x01, 0x0b, 0x81, 0x8a, 0x0c, 0x09, 0x04,
  6527. 0x08, 0x00, 0x81, 0x93, 0x0c, 0x28, 0x19, 0x03,
  6528. 0x01, 0x01, 0x28, 0x01, 0x00, 0x00, 0x05, 0x02,
  6529. 0x05, 0x80, 0x89, 0x81, 0x8e, 0x01, 0x03, 0x00,
  6530. 0x03, 0x10, 0x80, 0x8a, 0x81, 0xaf, 0x82, 0x88,
  6531. 0x80, 0x8d, 0x80, 0x8d, 0x80, 0x41, 0x73, 0x81,
  6532. 0x41, 0xce, 0x82, 0x92, 0x81, 0xb2, 0x03, 0x80,
  6533. 0x44, 0xd9, 0x80, 0x8b, 0x80, 0x42, 0x58, 0x00,
  6534. 0x80, 0x61, 0xbd, 0x69, 0x80, 0x40, 0xc9, 0x80,
  6535. 0x40, 0x9f, 0x81, 0x8b, 0x81, 0x8d, 0x01, 0x89,
  6536. 0xca, 0x99, 0x01, 0x96, 0x80, 0x93, 0x01, 0x88,
  6537. 0x94, 0x81, 0x40, 0xad, 0xa1, 0x81, 0xef, 0x09,
  6538. 0x02, 0x81, 0xd2, 0x0a, 0x80, 0x41, 0x06, 0x80,
  6539. 0xbe, 0x8a, 0x28, 0x97, 0x31, 0x0f, 0x8b, 0x01,
  6540. 0x19, 0x03, 0x81, 0x8c, 0x09, 0x07, 0x81, 0x88,
  6541. 0x04, 0x82, 0x8b, 0x17, 0x11, 0x00, 0x03, 0x05,
  6542. 0x02, 0x05, 0xd5, 0xaf, 0xc5, 0x27, 0x0a, 0x83,
  6543. 0x89, 0x10, 0x01, 0x10, 0x81, 0x89, 0x40, 0xe2,
  6544. 0x8b, 0x18, 0x41, 0x1a, 0xae, 0x80, 0x89, 0x80,
  6545. 0x40, 0xb8, 0xef, 0x8c, 0x82, 0x89, 0x84, 0xb7,
  6546. 0x86, 0x8e, 0x81, 0x8a, 0x85, 0x88,
  6547. };
  6548. static const uint8_t unicode_prop_Emoji_Component_table[28] = {
  6549. 0xa2, 0x05, 0x04, 0x89, 0x5f, 0xd2, 0x80, 0x40,
  6550. 0xd4, 0x80, 0x60, 0xdd, 0x2a, 0x80, 0x60, 0xf3,
  6551. 0xd5, 0x99, 0x41, 0xfa, 0x84, 0x45, 0xaf, 0x83,
  6552. 0x6c, 0x06, 0x6b, 0xdf,
  6553. };
  6554. static const uint8_t unicode_prop_Emoji_Modifier_table[4] = {
  6555. 0x61, 0xf3, 0xfa, 0x84,
  6556. };
  6557. static const uint8_t unicode_prop_Emoji_Modifier_Base_table[71] = {
  6558. 0x60, 0x26, 0x1c, 0x80, 0x40, 0xda, 0x80, 0x8f,
  6559. 0x83, 0x61, 0xcc, 0x76, 0x80, 0xbb, 0x11, 0x01,
  6560. 0x82, 0xf4, 0x09, 0x8a, 0x94, 0x92, 0x10, 0x1a,
  6561. 0x02, 0x30, 0x00, 0x97, 0x80, 0x40, 0xc8, 0x0b,
  6562. 0x80, 0x94, 0x03, 0x81, 0x40, 0xad, 0x12, 0x84,
  6563. 0xd2, 0x80, 0x8f, 0x82, 0x88, 0x80, 0x8a, 0x80,
  6564. 0x42, 0x3e, 0x01, 0x07, 0x3d, 0x80, 0x88, 0x89,
  6565. 0x0a, 0xb7, 0x80, 0xbc, 0x08, 0x08, 0x80, 0x90,
  6566. 0x10, 0x8c, 0x40, 0xe4, 0x82, 0xa9, 0x88,
  6567. };
  6568. static const uint8_t unicode_prop_Emoji_Presentation_table[144] = {
  6569. 0x60, 0x23, 0x19, 0x81, 0x40, 0xcc, 0x1a, 0x01,
  6570. 0x80, 0x42, 0x08, 0x81, 0x94, 0x81, 0xb1, 0x8b,
  6571. 0xaa, 0x80, 0x92, 0x80, 0x8c, 0x07, 0x81, 0x90,
  6572. 0x0c, 0x0f, 0x04, 0x80, 0x94, 0x06, 0x08, 0x03,
  6573. 0x01, 0x06, 0x03, 0x81, 0x9b, 0x80, 0xa2, 0x00,
  6574. 0x03, 0x10, 0x80, 0xbc, 0x82, 0x97, 0x80, 0x8d,
  6575. 0x80, 0x43, 0x5a, 0x81, 0xb2, 0x03, 0x80, 0x61,
  6576. 0xc4, 0xad, 0x80, 0x40, 0xc9, 0x80, 0x40, 0xbd,
  6577. 0x01, 0x89, 0xca, 0x99, 0x00, 0x97, 0x80, 0x93,
  6578. 0x01, 0x20, 0x82, 0x94, 0x81, 0x40, 0xad, 0xa0,
  6579. 0x8b, 0x88, 0x80, 0xc5, 0x80, 0x95, 0x8b, 0xaa,
  6580. 0x1c, 0x8b, 0x90, 0x10, 0x82, 0xc6, 0x00, 0x80,
  6581. 0x40, 0xba, 0x81, 0xbe, 0x8c, 0x18, 0x97, 0x91,
  6582. 0x80, 0x99, 0x81, 0x8c, 0x80, 0xd5, 0xd4, 0xaf,
  6583. 0xc5, 0x28, 0x12, 0x0a, 0x1b, 0x8a, 0x0e, 0x88,
  6584. 0x40, 0xe2, 0x8b, 0x18, 0x41, 0x1a, 0xae, 0x80,
  6585. 0x89, 0x80, 0x40, 0xb8, 0xef, 0x8c, 0x82, 0x89,
  6586. 0x84, 0xb7, 0x86, 0x8e, 0x81, 0x8a, 0x85, 0x88,
  6587. };
  6588. static const uint8_t unicode_prop_Extended_Pictographic_table[156] = {
  6589. 0x40, 0xa8, 0x03, 0x80, 0x5f, 0x8c, 0x80, 0x8b,
  6590. 0x80, 0x40, 0xd7, 0x80, 0x95, 0x80, 0xd9, 0x85,
  6591. 0x8e, 0x81, 0x41, 0x6e, 0x81, 0x8b, 0x80, 0xde,
  6592. 0x80, 0xc5, 0x80, 0x98, 0x8a, 0x1a, 0x40, 0xc6,
  6593. 0x80, 0x40, 0xe6, 0x81, 0x89, 0x80, 0x88, 0x80,
  6594. 0xb9, 0x18, 0x28, 0x8b, 0x80, 0xf1, 0x89, 0xf5,
  6595. 0x81, 0x8a, 0x00, 0x00, 0x28, 0x10, 0x28, 0x89,
  6596. 0x81, 0x8e, 0x01, 0x03, 0x00, 0x03, 0x10, 0x80,
  6597. 0x8a, 0x84, 0xac, 0x82, 0x88, 0x80, 0x8d, 0x80,
  6598. 0x8d, 0x80, 0x41, 0x73, 0x81, 0x41, 0xce, 0x82,
  6599. 0x92, 0x81, 0xb2, 0x03, 0x80, 0x44, 0xd9, 0x80,
  6600. 0x8b, 0x80, 0x42, 0x58, 0x00, 0x80, 0x61, 0xbd,
  6601. 0x65, 0x40, 0xff, 0x8c, 0x82, 0x9e, 0x80, 0xbb,
  6602. 0x85, 0x8b, 0x81, 0x8d, 0x01, 0x89, 0x91, 0xb8,
  6603. 0x9a, 0x8e, 0x89, 0x80, 0x93, 0x01, 0x88, 0x03,
  6604. 0x88, 0x41, 0xb1, 0x84, 0x41, 0x3d, 0x87, 0x41,
  6605. 0x09, 0xaf, 0xff, 0xf3, 0x8b, 0xd4, 0xaa, 0x8b,
  6606. 0x83, 0xb7, 0x87, 0x89, 0x85, 0xa7, 0x87, 0x9d,
  6607. 0xd1, 0x8b, 0xae, 0x80, 0x89, 0x80, 0x41, 0xb8,
  6608. 0x40, 0xff, 0x43, 0xfd,
  6609. };
  6610. static const uint8_t unicode_prop_Default_Ignorable_Code_Point_table[51] = {
  6611. 0x40, 0xac, 0x80, 0x42, 0xa0, 0x80, 0x42, 0xcb,
  6612. 0x80, 0x4b, 0x41, 0x81, 0x46, 0x52, 0x81, 0xd4,
  6613. 0x84, 0x47, 0xfa, 0x84, 0x99, 0x84, 0xb0, 0x8f,
  6614. 0x50, 0xf3, 0x80, 0x60, 0xcc, 0x9a, 0x8f, 0x40,
  6615. 0xee, 0x80, 0x40, 0x9f, 0x80, 0xce, 0x88, 0x60,
  6616. 0xbc, 0xa6, 0x83, 0x54, 0xce, 0x87, 0x6c, 0x2e,
  6617. 0x84, 0x4f, 0xff,
  6618. };
  6619. typedef enum {
  6620. UNICODE_PROP_Hyphen,
  6621. UNICODE_PROP_Other_Math,
  6622. UNICODE_PROP_Other_Alphabetic,
  6623. UNICODE_PROP_Other_Lowercase,
  6624. UNICODE_PROP_Other_Uppercase,
  6625. UNICODE_PROP_Other_Grapheme_Extend,
  6626. UNICODE_PROP_Other_Default_Ignorable_Code_Point,
  6627. UNICODE_PROP_Other_ID_Start,
  6628. UNICODE_PROP_Other_ID_Continue,
  6629. UNICODE_PROP_Prepended_Concatenation_Mark,
  6630. UNICODE_PROP_ID_Continue1,
  6631. UNICODE_PROP_XID_Start1,
  6632. UNICODE_PROP_XID_Continue1,
  6633. UNICODE_PROP_Changes_When_Titlecased1,
  6634. UNICODE_PROP_Changes_When_Casefolded1,
  6635. UNICODE_PROP_Changes_When_NFKC_Casefolded1,
  6636. UNICODE_PROP_ASCII_Hex_Digit,
  6637. UNICODE_PROP_Bidi_Control,
  6638. UNICODE_PROP_Dash,
  6639. UNICODE_PROP_Deprecated,
  6640. UNICODE_PROP_Diacritic,
  6641. UNICODE_PROP_Extender,
  6642. UNICODE_PROP_Hex_Digit,
  6643. UNICODE_PROP_IDS_Unary_Operator,
  6644. UNICODE_PROP_IDS_Binary_Operator,
  6645. UNICODE_PROP_IDS_Trinary_Operator,
  6646. UNICODE_PROP_Ideographic,
  6647. UNICODE_PROP_Join_Control,
  6648. UNICODE_PROP_Logical_Order_Exception,
  6649. UNICODE_PROP_Modifier_Combining_Mark,
  6650. UNICODE_PROP_Noncharacter_Code_Point,
  6651. UNICODE_PROP_Pattern_Syntax,
  6652. UNICODE_PROP_Pattern_White_Space,
  6653. UNICODE_PROP_Quotation_Mark,
  6654. UNICODE_PROP_Radical,
  6655. UNICODE_PROP_Regional_Indicator,
  6656. UNICODE_PROP_Sentence_Terminal,
  6657. UNICODE_PROP_Soft_Dotted,
  6658. UNICODE_PROP_Terminal_Punctuation,
  6659. UNICODE_PROP_Unified_Ideograph,
  6660. UNICODE_PROP_Variation_Selector,
  6661. UNICODE_PROP_White_Space,
  6662. UNICODE_PROP_Bidi_Mirrored,
  6663. UNICODE_PROP_Emoji,
  6664. UNICODE_PROP_Emoji_Component,
  6665. UNICODE_PROP_Emoji_Modifier,
  6666. UNICODE_PROP_Emoji_Modifier_Base,
  6667. UNICODE_PROP_Emoji_Presentation,
  6668. UNICODE_PROP_Extended_Pictographic,
  6669. UNICODE_PROP_Default_Ignorable_Code_Point,
  6670. UNICODE_PROP_ID_Start,
  6671. UNICODE_PROP_Case_Ignorable,
  6672. UNICODE_PROP_ASCII,
  6673. UNICODE_PROP_Alphabetic,
  6674. UNICODE_PROP_Any,
  6675. UNICODE_PROP_Assigned,
  6676. UNICODE_PROP_Cased,
  6677. UNICODE_PROP_Changes_When_Casefolded,
  6678. UNICODE_PROP_Changes_When_Casemapped,
  6679. UNICODE_PROP_Changes_When_Lowercased,
  6680. UNICODE_PROP_Changes_When_NFKC_Casefolded,
  6681. UNICODE_PROP_Changes_When_Titlecased,
  6682. UNICODE_PROP_Changes_When_Uppercased,
  6683. UNICODE_PROP_Grapheme_Base,
  6684. UNICODE_PROP_Grapheme_Extend,
  6685. UNICODE_PROP_ID_Continue,
  6686. UNICODE_PROP_ID_Compat_Math_Start,
  6687. UNICODE_PROP_ID_Compat_Math_Continue,
  6688. UNICODE_PROP_Lowercase,
  6689. UNICODE_PROP_Math,
  6690. UNICODE_PROP_Uppercase,
  6691. UNICODE_PROP_XID_Continue,
  6692. UNICODE_PROP_XID_Start,
  6693. UNICODE_PROP_Cased1,
  6694. UNICODE_PROP_InCB,
  6695. UNICODE_PROP_COUNT,
  6696. } UnicodePropertyEnum;
  6697. static const char unicode_prop_name_table[] =
  6698. "ASCII_Hex_Digit,AHex" "\0"
  6699. "Bidi_Control,Bidi_C" "\0"
  6700. "Dash" "\0"
  6701. "Deprecated,Dep" "\0"
  6702. "Diacritic,Dia" "\0"
  6703. "Extender,Ext" "\0"
  6704. "Hex_Digit,Hex" "\0"
  6705. "IDS_Unary_Operator,IDSU" "\0"
  6706. "IDS_Binary_Operator,IDSB" "\0"
  6707. "IDS_Trinary_Operator,IDST" "\0"
  6708. "Ideographic,Ideo" "\0"
  6709. "Join_Control,Join_C" "\0"
  6710. "Logical_Order_Exception,LOE" "\0"
  6711. "Modifier_Combining_Mark,MCM" "\0"
  6712. "Noncharacter_Code_Point,NChar" "\0"
  6713. "Pattern_Syntax,Pat_Syn" "\0"
  6714. "Pattern_White_Space,Pat_WS" "\0"
  6715. "Quotation_Mark,QMark" "\0"
  6716. "Radical" "\0"
  6717. "Regional_Indicator,RI" "\0"
  6718. "Sentence_Terminal,STerm" "\0"
  6719. "Soft_Dotted,SD" "\0"
  6720. "Terminal_Punctuation,Term" "\0"
  6721. "Unified_Ideograph,UIdeo" "\0"
  6722. "Variation_Selector,VS" "\0"
  6723. "White_Space,space" "\0"
  6724. "Bidi_Mirrored,Bidi_M" "\0"
  6725. "Emoji" "\0"
  6726. "Emoji_Component,EComp" "\0"
  6727. "Emoji_Modifier,EMod" "\0"
  6728. "Emoji_Modifier_Base,EBase" "\0"
  6729. "Emoji_Presentation,EPres" "\0"
  6730. "Extended_Pictographic,ExtPict" "\0"
  6731. "Default_Ignorable_Code_Point,DI" "\0"
  6732. "ID_Start,IDS" "\0"
  6733. "Case_Ignorable,CI" "\0"
  6734. "ASCII" "\0"
  6735. "Alphabetic,Alpha" "\0"
  6736. "Any" "\0"
  6737. "Assigned" "\0"
  6738. "Cased" "\0"
  6739. "Changes_When_Casefolded,CWCF" "\0"
  6740. "Changes_When_Casemapped,CWCM" "\0"
  6741. "Changes_When_Lowercased,CWL" "\0"
  6742. "Changes_When_NFKC_Casefolded,CWKCF" "\0"
  6743. "Changes_When_Titlecased,CWT" "\0"
  6744. "Changes_When_Uppercased,CWU" "\0"
  6745. "Grapheme_Base,Gr_Base" "\0"
  6746. "Grapheme_Extend,Gr_Ext" "\0"
  6747. "ID_Continue,IDC" "\0"
  6748. "ID_Compat_Math_Start" "\0"
  6749. "ID_Compat_Math_Continue" "\0"
  6750. "Lowercase,Lower" "\0"
  6751. "Math" "\0"
  6752. "Uppercase,Upper" "\0"
  6753. "XID_Continue,XIDC" "\0"
  6754. "XID_Start,XIDS" "\0"
  6755. ;
  6756. static const uint8_t * const unicode_prop_table[] = {
  6757. unicode_prop_Hyphen_table,
  6758. unicode_prop_Other_Math_table,
  6759. unicode_prop_Other_Alphabetic_table,
  6760. unicode_prop_Other_Lowercase_table,
  6761. unicode_prop_Other_Uppercase_table,
  6762. unicode_prop_Other_Grapheme_Extend_table,
  6763. unicode_prop_Other_Default_Ignorable_Code_Point_table,
  6764. unicode_prop_Other_ID_Start_table,
  6765. unicode_prop_Other_ID_Continue_table,
  6766. unicode_prop_Prepended_Concatenation_Mark_table,
  6767. unicode_prop_ID_Continue1_table,
  6768. unicode_prop_XID_Start1_table,
  6769. unicode_prop_XID_Continue1_table,
  6770. unicode_prop_Changes_When_Titlecased1_table,
  6771. unicode_prop_Changes_When_Casefolded1_table,
  6772. unicode_prop_Changes_When_NFKC_Casefolded1_table,
  6773. unicode_prop_ASCII_Hex_Digit_table,
  6774. unicode_prop_Bidi_Control_table,
  6775. unicode_prop_Dash_table,
  6776. unicode_prop_Deprecated_table,
  6777. unicode_prop_Diacritic_table,
  6778. unicode_prop_Extender_table,
  6779. unicode_prop_Hex_Digit_table,
  6780. unicode_prop_IDS_Unary_Operator_table,
  6781. unicode_prop_IDS_Binary_Operator_table,
  6782. unicode_prop_IDS_Trinary_Operator_table,
  6783. unicode_prop_Ideographic_table,
  6784. unicode_prop_Join_Control_table,
  6785. unicode_prop_Logical_Order_Exception_table,
  6786. unicode_prop_Modifier_Combining_Mark_table,
  6787. unicode_prop_Noncharacter_Code_Point_table,
  6788. unicode_prop_Pattern_Syntax_table,
  6789. unicode_prop_Pattern_White_Space_table,
  6790. unicode_prop_Quotation_Mark_table,
  6791. unicode_prop_Radical_table,
  6792. unicode_prop_Regional_Indicator_table,
  6793. unicode_prop_Sentence_Terminal_table,
  6794. unicode_prop_Soft_Dotted_table,
  6795. unicode_prop_Terminal_Punctuation_table,
  6796. unicode_prop_Unified_Ideograph_table,
  6797. unicode_prop_Variation_Selector_table,
  6798. unicode_prop_White_Space_table,
  6799. unicode_prop_Bidi_Mirrored_table,
  6800. unicode_prop_Emoji_table,
  6801. unicode_prop_Emoji_Component_table,
  6802. unicode_prop_Emoji_Modifier_table,
  6803. unicode_prop_Emoji_Modifier_Base_table,
  6804. unicode_prop_Emoji_Presentation_table,
  6805. unicode_prop_Extended_Pictographic_table,
  6806. unicode_prop_Default_Ignorable_Code_Point_table,
  6807. unicode_prop_ID_Start_table,
  6808. unicode_prop_Case_Ignorable_table,
  6809. };
  6810. static const uint16_t unicode_prop_len_table[] = {
  6811. countof(unicode_prop_Hyphen_table),
  6812. countof(unicode_prop_Other_Math_table),
  6813. countof(unicode_prop_Other_Alphabetic_table),
  6814. countof(unicode_prop_Other_Lowercase_table),
  6815. countof(unicode_prop_Other_Uppercase_table),
  6816. countof(unicode_prop_Other_Grapheme_Extend_table),
  6817. countof(unicode_prop_Other_Default_Ignorable_Code_Point_table),
  6818. countof(unicode_prop_Other_ID_Start_table),
  6819. countof(unicode_prop_Other_ID_Continue_table),
  6820. countof(unicode_prop_Prepended_Concatenation_Mark_table),
  6821. countof(unicode_prop_ID_Continue1_table),
  6822. countof(unicode_prop_XID_Start1_table),
  6823. countof(unicode_prop_XID_Continue1_table),
  6824. countof(unicode_prop_Changes_When_Titlecased1_table),
  6825. countof(unicode_prop_Changes_When_Casefolded1_table),
  6826. countof(unicode_prop_Changes_When_NFKC_Casefolded1_table),
  6827. countof(unicode_prop_ASCII_Hex_Digit_table),
  6828. countof(unicode_prop_Bidi_Control_table),
  6829. countof(unicode_prop_Dash_table),
  6830. countof(unicode_prop_Deprecated_table),
  6831. countof(unicode_prop_Diacritic_table),
  6832. countof(unicode_prop_Extender_table),
  6833. countof(unicode_prop_Hex_Digit_table),
  6834. countof(unicode_prop_IDS_Unary_Operator_table),
  6835. countof(unicode_prop_IDS_Binary_Operator_table),
  6836. countof(unicode_prop_IDS_Trinary_Operator_table),
  6837. countof(unicode_prop_Ideographic_table),
  6838. countof(unicode_prop_Join_Control_table),
  6839. countof(unicode_prop_Logical_Order_Exception_table),
  6840. countof(unicode_prop_Modifier_Combining_Mark_table),
  6841. countof(unicode_prop_Noncharacter_Code_Point_table),
  6842. countof(unicode_prop_Pattern_Syntax_table),
  6843. countof(unicode_prop_Pattern_White_Space_table),
  6844. countof(unicode_prop_Quotation_Mark_table),
  6845. countof(unicode_prop_Radical_table),
  6846. countof(unicode_prop_Regional_Indicator_table),
  6847. countof(unicode_prop_Sentence_Terminal_table),
  6848. countof(unicode_prop_Soft_Dotted_table),
  6849. countof(unicode_prop_Terminal_Punctuation_table),
  6850. countof(unicode_prop_Unified_Ideograph_table),
  6851. countof(unicode_prop_Variation_Selector_table),
  6852. countof(unicode_prop_White_Space_table),
  6853. countof(unicode_prop_Bidi_Mirrored_table),
  6854. countof(unicode_prop_Emoji_table),
  6855. countof(unicode_prop_Emoji_Component_table),
  6856. countof(unicode_prop_Emoji_Modifier_table),
  6857. countof(unicode_prop_Emoji_Modifier_Base_table),
  6858. countof(unicode_prop_Emoji_Presentation_table),
  6859. countof(unicode_prop_Extended_Pictographic_table),
  6860. countof(unicode_prop_Default_Ignorable_Code_Point_table),
  6861. countof(unicode_prop_ID_Start_table),
  6862. countof(unicode_prop_Case_Ignorable_table),
  6863. };
  6864. /*
  6865. * QuickJS Javascript Engine
  6866. *
  6867. * Copyright (c) 2017-2024 Fabrice Bellard
  6868. * Copyright (c) 2017-2024 Charlie Gordon
  6869. * Copyright (c) 2023-2025 Ben Noordhuis
  6870. * Copyright (c) 2023-2025 Saúl Ibarra Corretgé
  6871. *
  6872. * Permission is hereby granted, free of charge, to any person obtaining a copy
  6873. * of this software and associated documentation files (the "Software"), to deal
  6874. * in the Software without restriction, including without limitation the rights
  6875. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  6876. * copies of the Software, and to permit persons to whom the Software is
  6877. * furnished to do so, subject to the following conditions:
  6878. *
  6879. * The above copyright notice and this permission notice shall be included in
  6880. * all copies or substantial portions of the Software.
  6881. *
  6882. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  6883. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  6884. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  6885. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  6886. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  6887. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  6888. * THE SOFTWARE.
  6889. */
  6890. #ifndef QUICKJS_H
  6891. #define QUICKJS_H
  6892. #include <stdbool.h>
  6893. #include <stdio.h>
  6894. #include <stdint.h>
  6895. #include <string.h>
  6896. #include <math.h>
  6897. #ifdef __cplusplus
  6898. extern "C" {
  6899. #endif
  6900. #define QUICKJS_NG 1
  6901. #if defined(__GNUC__) || defined(__clang__)
  6902. #define js_force_inline inline __attribute__((always_inline))
  6903. #define JS_EXTERN __attribute__((visibility("default")))
  6904. #else
  6905. #define js_force_inline inline
  6906. #define JS_EXTERN /* nothing */
  6907. #endif
  6908. /* Borrowed from Folly */
  6909. #ifndef JS_PRINTF_FORMAT
  6910. #ifdef _MSC_VER
  6911. #include <sal.h>
  6912. #define JS_PRINTF_FORMAT _Printf_format_string_
  6913. #define JS_PRINTF_FORMAT_ATTR(format_param, dots_param)
  6914. #else
  6915. #define JS_PRINTF_FORMAT
  6916. #if !defined(__clang__) && defined(__GNUC__)
  6917. #define JS_PRINTF_FORMAT_ATTR(format_param, dots_param) \
  6918. __attribute__((format(gnu_printf, format_param, dots_param)))
  6919. #else
  6920. #define JS_PRINTF_FORMAT_ATTR(format_param, dots_param) \
  6921. __attribute__((format(printf, format_param, dots_param)))
  6922. #endif
  6923. #endif
  6924. #endif
  6925. typedef struct JSRuntime JSRuntime;
  6926. typedef struct JSContext JSContext;
  6927. typedef struct JSObject JSObject;
  6928. typedef struct JSClass JSClass;
  6929. typedef uint32_t JSClassID;
  6930. typedef uint32_t JSAtom;
  6931. /* Unless documented otherwise, C string pointers (`char *` or `const char *`)
  6932. are assumed to verify these constraints:
  6933. - unless a length is passed separately, the string has a null terminator
  6934. - string contents is either pure ASCII or is UTF-8 encoded.
  6935. */
  6936. /* Overridable purely for testing purposes; don't touch. */
  6937. #ifndef JS_NAN_BOXING
  6938. #if INTPTR_MAX < INT64_MAX
  6939. #define JS_NAN_BOXING 1 /* Use NAN boxing for 32bit builds. */
  6940. #endif
  6941. #endif
  6942. enum {
  6943. /* all tags with a reference count are negative */
  6944. JS_TAG_FIRST = -9, /* first negative tag */
  6945. JS_TAG_BIG_INT = -9,
  6946. JS_TAG_SYMBOL = -8,
  6947. JS_TAG_STRING = -7,
  6948. JS_TAG_MODULE = -3, /* used internally */
  6949. JS_TAG_FUNCTION_BYTECODE = -2, /* used internally */
  6950. JS_TAG_OBJECT = -1,
  6951. JS_TAG_INT = 0,
  6952. JS_TAG_BOOL = 1,
  6953. JS_TAG_NULL = 2,
  6954. JS_TAG_UNDEFINED = 3,
  6955. JS_TAG_UNINITIALIZED = 4,
  6956. JS_TAG_CATCH_OFFSET = 5,
  6957. JS_TAG_EXCEPTION = 6,
  6958. JS_TAG_FLOAT64 = 7,
  6959. /* any larger tag is FLOAT64 if JS_NAN_BOXING */
  6960. };
  6961. #if !defined(JS_CHECK_JSVALUE)
  6962. #define JSValueConst JSValue
  6963. #endif
  6964. // JS_CHECK_JSVALUE build mode does not produce working code but is here to
  6965. // help catch reference counting bugs at compile time, by making it harder
  6966. // to mix up JSValue and JSValueConst
  6967. //
  6968. // rules:
  6969. //
  6970. // - a function with a JSValue parameter takes ownership;
  6971. // caller must *not* call JS_FreeValue
  6972. //
  6973. // - a function with a JSValueConst parameter does not take ownership;
  6974. // caller *must* call JS_FreeValue
  6975. //
  6976. // - a function returning a JSValue transfers ownership to caller;
  6977. // caller *must* call JS_FreeValue
  6978. //
  6979. // - a function returning a JSValueConst does *not* transfer ownership;
  6980. // caller must *not* call JS_FreeValue
  6981. #if defined(JS_CHECK_JSVALUE)
  6982. typedef struct JSValue *JSValue;
  6983. typedef const struct JSValue *JSValueConst;
  6984. #define JS_MKVAL(tag, val) ((JSValue)((tag) | (intptr_t)(val) << 4))
  6985. #define JS_MKPTR(tag, ptr) ((JSValue)((tag) | (intptr_t)(ptr)))
  6986. #define JS_VALUE_GET_NORM_TAG(v) ((int)((intptr_t)(v) & 15))
  6987. #define JS_VALUE_GET_TAG(v) ((int)((intptr_t)(v) & 15))
  6988. #define JS_VALUE_GET_PTR(v) ((void *)((intptr_t)(v) & ~15))
  6989. #define JS_VALUE_GET_INT(v) ((int)((intptr_t)(v) >> 4))
  6990. #define JS_VALUE_GET_BOOL(v) ((int)((intptr_t)(v) >> 4))
  6991. #define JS_VALUE_GET_FLOAT64(v) ((double)((intptr_t)(v) >> 4))
  6992. #define JS_TAG_IS_FLOAT64(tag) ((int)(tag) == JS_TAG_FLOAT64)
  6993. #define JS_NAN JS_MKVAL(JS_TAG_FLOAT64, 0)
  6994. static inline JSValue __JS_NewFloat64(double d)
  6995. {
  6996. return JS_MKVAL(JS_TAG_FLOAT64, (int)d);
  6997. }
  6998. static inline bool JS_VALUE_IS_NAN(JSValue v)
  6999. {
  7000. (void)&v;
  7001. return false;
  7002. }
  7003. #elif defined(JS_NAN_BOXING) && JS_NAN_BOXING
  7004. typedef uint64_t JSValue;
  7005. #define JS_VALUE_GET_TAG(v) (int)((v) >> 32)
  7006. #define JS_VALUE_GET_INT(v) (int)(v)
  7007. #define JS_VALUE_GET_BOOL(v) (int)(v)
  7008. #define JS_VALUE_GET_PTR(v) (void *)(intptr_t)(v)
  7009. #define JS_MKVAL(tag, val) (((uint64_t)(tag) << 32) | (uint32_t)(val))
  7010. #define JS_MKPTR(tag, ptr) (((uint64_t)(tag) << 32) | (uintptr_t)(ptr))
  7011. #define JS_FLOAT64_TAG_ADDEND (0x7ff80000 - JS_TAG_FIRST + 1) /* quiet NaN encoding */
  7012. static inline double JS_VALUE_GET_FLOAT64(JSValue v)
  7013. {
  7014. union {
  7015. JSValue v;
  7016. double d;
  7017. } u;
  7018. u.v = v;
  7019. u.v += (uint64_t)JS_FLOAT64_TAG_ADDEND << 32;
  7020. return u.d;
  7021. }
  7022. #define JS_NAN (0x7ff8000000000000 - ((uint64_t)JS_FLOAT64_TAG_ADDEND << 32))
  7023. static inline JSValue __JS_NewFloat64(double d)
  7024. {
  7025. union {
  7026. double d;
  7027. uint64_t u64;
  7028. } u;
  7029. JSValue v;
  7030. u.d = d;
  7031. /* normalize NaN */
  7032. if ((u.u64 & 0x7fffffffffffffff) > 0x7ff0000000000000)
  7033. v = JS_NAN;
  7034. else
  7035. v = u.u64 - ((uint64_t)JS_FLOAT64_TAG_ADDEND << 32);
  7036. return v;
  7037. }
  7038. #define JS_TAG_IS_FLOAT64(tag) ((unsigned)((tag) - JS_TAG_FIRST) >= (JS_TAG_FLOAT64 - JS_TAG_FIRST))
  7039. /* same as JS_VALUE_GET_TAG, but return JS_TAG_FLOAT64 with NaN boxing */
  7040. static inline int JS_VALUE_GET_NORM_TAG(JSValue v)
  7041. {
  7042. uint32_t tag;
  7043. tag = JS_VALUE_GET_TAG(v);
  7044. if (JS_TAG_IS_FLOAT64(tag))
  7045. return JS_TAG_FLOAT64;
  7046. else
  7047. return tag;
  7048. }
  7049. static inline bool JS_VALUE_IS_NAN(JSValue v)
  7050. {
  7051. uint32_t tag;
  7052. tag = JS_VALUE_GET_TAG(v);
  7053. return tag == (JS_NAN >> 32);
  7054. }
  7055. #else /* !JS_NAN_BOXING */
  7056. typedef union JSValueUnion {
  7057. int32_t int32;
  7058. double float64;
  7059. void *ptr;
  7060. } JSValueUnion;
  7061. typedef struct JSValue {
  7062. JSValueUnion u;
  7063. int64_t tag;
  7064. } JSValue;
  7065. #define JS_VALUE_GET_TAG(v) ((int32_t)(v).tag)
  7066. /* same as JS_VALUE_GET_TAG, but return JS_TAG_FLOAT64 with NaN boxing */
  7067. #define JS_VALUE_GET_NORM_TAG(v) JS_VALUE_GET_TAG(v)
  7068. #define JS_VALUE_GET_INT(v) ((v).u.int32)
  7069. #define JS_VALUE_GET_BOOL(v) ((v).u.int32)
  7070. #define JS_VALUE_GET_FLOAT64(v) ((v).u.float64)
  7071. #define JS_VALUE_GET_PTR(v) ((v).u.ptr)
  7072. /* msvc doesn't understand designated initializers without /std:c++20 */
  7073. #ifdef __cplusplus
  7074. static inline JSValue JS_MKPTR(int64_t tag, void *ptr)
  7075. {
  7076. JSValue v;
  7077. v.u.ptr = ptr;
  7078. v.tag = tag;
  7079. return v;
  7080. }
  7081. static inline JSValue JS_MKVAL(int64_t tag, int32_t int32)
  7082. {
  7083. JSValue v;
  7084. v.u.int32 = int32;
  7085. v.tag = tag;
  7086. return v;
  7087. }
  7088. static inline JSValue JS_MKNAN(void)
  7089. {
  7090. JSValue v;
  7091. v.u.float64 = NAN;
  7092. v.tag = JS_TAG_FLOAT64;
  7093. return v;
  7094. }
  7095. /* provide as macros for consistency and backward compat reasons */
  7096. #define JS_MKPTR(tag, ptr) JS_MKPTR(tag, ptr)
  7097. #define JS_MKVAL(tag, val) JS_MKVAL(tag, val)
  7098. #define JS_NAN JS_MKNAN() /* alas, not a constant expression */
  7099. #else
  7100. #define JS_MKPTR(tag, p) (JSValue){ (JSValueUnion){ .ptr = p }, tag }
  7101. #define JS_MKVAL(tag, val) (JSValue){ (JSValueUnion){ .int32 = val }, tag }
  7102. #define JS_NAN (JSValue){ (JSValueUnion){ .float64 = NAN }, JS_TAG_FLOAT64 }
  7103. #endif
  7104. #define JS_TAG_IS_FLOAT64(tag) ((unsigned)(tag) == JS_TAG_FLOAT64)
  7105. static inline JSValue __JS_NewFloat64(double d)
  7106. {
  7107. JSValue v;
  7108. v.tag = JS_TAG_FLOAT64;
  7109. v.u.float64 = d;
  7110. return v;
  7111. }
  7112. static inline bool JS_VALUE_IS_NAN(JSValue v)
  7113. {
  7114. union {
  7115. double d;
  7116. uint64_t u64;
  7117. } u;
  7118. if (v.tag != JS_TAG_FLOAT64)
  7119. return 0;
  7120. u.d = v.u.float64;
  7121. return (u.u64 & 0x7fffffffffffffff) > 0x7ff0000000000000;
  7122. }
  7123. #endif /* !JS_NAN_BOXING */
  7124. #define JS_VALUE_IS_BOTH_INT(v1, v2) ((JS_VALUE_GET_TAG(v1) | JS_VALUE_GET_TAG(v2)) == 0)
  7125. #define JS_VALUE_IS_BOTH_FLOAT(v1, v2) (JS_TAG_IS_FLOAT64(JS_VALUE_GET_TAG(v1)) && JS_TAG_IS_FLOAT64(JS_VALUE_GET_TAG(v2)))
  7126. #define JS_VALUE_GET_OBJ(v) ((JSObject *)JS_VALUE_GET_PTR(v))
  7127. #define JS_VALUE_HAS_REF_COUNT(v) ((unsigned)JS_VALUE_GET_TAG(v) >= (unsigned)JS_TAG_FIRST)
  7128. /* special values */
  7129. #define JS_NULL JS_MKVAL(JS_TAG_NULL, 0)
  7130. #define JS_UNDEFINED JS_MKVAL(JS_TAG_UNDEFINED, 0)
  7131. #define JS_FALSE JS_MKVAL(JS_TAG_BOOL, 0)
  7132. #define JS_TRUE JS_MKVAL(JS_TAG_BOOL, 1)
  7133. #define JS_EXCEPTION JS_MKVAL(JS_TAG_EXCEPTION, 0)
  7134. #define JS_UNINITIALIZED JS_MKVAL(JS_TAG_UNINITIALIZED, 0)
  7135. /* flags for object properties */
  7136. #define JS_PROP_CONFIGURABLE (1 << 0)
  7137. #define JS_PROP_WRITABLE (1 << 1)
  7138. #define JS_PROP_ENUMERABLE (1 << 2)
  7139. #define JS_PROP_C_W_E (JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE | JS_PROP_ENUMERABLE)
  7140. #define JS_PROP_LENGTH (1 << 3) /* used internally in Arrays */
  7141. #define JS_PROP_TMASK (3 << 4) /* mask for NORMAL, GETSET, VARREF, AUTOINIT */
  7142. #define JS_PROP_NORMAL (0 << 4)
  7143. #define JS_PROP_GETSET (1 << 4)
  7144. #define JS_PROP_VARREF (2 << 4) /* used internally */
  7145. #define JS_PROP_AUTOINIT (3 << 4) /* used internally */
  7146. /* flags for JS_DefineProperty */
  7147. #define JS_PROP_HAS_SHIFT 8
  7148. #define JS_PROP_HAS_CONFIGURABLE (1 << 8)
  7149. #define JS_PROP_HAS_WRITABLE (1 << 9)
  7150. #define JS_PROP_HAS_ENUMERABLE (1 << 10)
  7151. #define JS_PROP_HAS_GET (1 << 11)
  7152. #define JS_PROP_HAS_SET (1 << 12)
  7153. #define JS_PROP_HAS_VALUE (1 << 13)
  7154. /* throw an exception if false would be returned
  7155. (JS_DefineProperty/JS_SetProperty) */
  7156. #define JS_PROP_THROW (1 << 14)
  7157. /* throw an exception if false would be returned in strict mode
  7158. (JS_SetProperty) */
  7159. #define JS_PROP_THROW_STRICT (1 << 15)
  7160. #define JS_PROP_NO_ADD (1 << 16) /* internal use */
  7161. #define JS_PROP_NO_EXOTIC (1 << 17) /* internal use */
  7162. #define JS_PROP_DEFINE_PROPERTY (1 << 18) /* internal use */
  7163. #define JS_PROP_REFLECT_DEFINE_PROPERTY (1 << 19) /* internal use */
  7164. #ifndef JS_DEFAULT_STACK_SIZE
  7165. #define JS_DEFAULT_STACK_SIZE (1024 * 1024)
  7166. #endif
  7167. /* JS_Eval() flags */
  7168. #define JS_EVAL_TYPE_GLOBAL (0 << 0) /* global code (default) */
  7169. #define JS_EVAL_TYPE_MODULE (1 << 0) /* module code */
  7170. #define JS_EVAL_TYPE_DIRECT (2 << 0) /* direct call (internal use) */
  7171. #define JS_EVAL_TYPE_INDIRECT (3 << 0) /* indirect call (internal use) */
  7172. #define JS_EVAL_TYPE_MASK (3 << 0)
  7173. #define JS_EVAL_FLAG_STRICT (1 << 3) /* force 'strict' mode */
  7174. #define JS_EVAL_FLAG_UNUSED (1 << 4) /* unused */
  7175. /* compile but do not run. The result is an object with a
  7176. JS_TAG_FUNCTION_BYTECODE or JS_TAG_MODULE tag. It can be executed
  7177. with JS_EvalFunction(). */
  7178. #define JS_EVAL_FLAG_COMPILE_ONLY (1 << 5)
  7179. /* don't include the stack frames before this eval in the Error() backtraces */
  7180. #define JS_EVAL_FLAG_BACKTRACE_BARRIER (1 << 6)
  7181. /* allow top-level await in normal script. JS_Eval() returns a
  7182. promise. Only allowed with JS_EVAL_TYPE_GLOBAL */
  7183. #define JS_EVAL_FLAG_ASYNC (1 << 7)
  7184. typedef JSValue JSCFunction(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv);
  7185. typedef JSValue JSCFunctionMagic(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic);
  7186. typedef JSValue JSCFunctionData(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic, JSValueConst *func_data);
  7187. typedef struct JSMallocFunctions {
  7188. void *(*js_calloc)(void *opaque, size_t count, size_t size);
  7189. void *(*js_malloc)(void *opaque, size_t size);
  7190. void (*js_free)(void *opaque, void *ptr);
  7191. void *(*js_realloc)(void *opaque, void *ptr, size_t size);
  7192. size_t (*js_malloc_usable_size)(const void *ptr);
  7193. } JSMallocFunctions;
  7194. // Debug trace system: the debug output will be produced to the dump stream (currently
  7195. // stdout) if dumps are enabled and JS_SetDumpFlags is invoked with the corresponding
  7196. // bit set.
  7197. #define JS_DUMP_BYTECODE_FINAL 0x01 /* dump pass 3 final byte code */
  7198. #define JS_DUMP_BYTECODE_PASS2 0x02 /* dump pass 2 code */
  7199. #define JS_DUMP_BYTECODE_PASS1 0x04 /* dump pass 1 code */
  7200. #define JS_DUMP_BYTECODE_HEX 0x10 /* dump bytecode in hex */
  7201. #define JS_DUMP_BYTECODE_PC2LINE 0x20 /* dump line number table */
  7202. #define JS_DUMP_BYTECODE_STACK 0x40 /* dump compute_stack_size */
  7203. #define JS_DUMP_BYTECODE_STEP 0x80 /* dump executed bytecode */
  7204. #define JS_DUMP_READ_OBJECT 0x100 /* dump the marshalled objects at load time */
  7205. #define JS_DUMP_FREE 0x200 /* dump every object free */
  7206. #define JS_DUMP_GC 0x400 /* dump the occurrence of the automatic GC */
  7207. #define JS_DUMP_GC_FREE 0x800 /* dump objects freed by the GC */
  7208. #define JS_DUMP_MODULE_RESOLVE 0x1000 /* dump module resolution steps */
  7209. #define JS_DUMP_PROMISE 0x2000 /* dump promise steps */
  7210. #define JS_DUMP_LEAKS 0x4000 /* dump leaked objects and strings in JS_FreeRuntime */
  7211. #define JS_DUMP_ATOM_LEAKS 0x8000 /* dump leaked atoms in JS_FreeRuntime */
  7212. #define JS_DUMP_MEM 0x10000 /* dump memory usage in JS_FreeRuntime */
  7213. #define JS_DUMP_OBJECTS 0x20000 /* dump objects in JS_FreeRuntime */
  7214. #define JS_DUMP_ATOMS 0x40000 /* dump atoms in JS_FreeRuntime */
  7215. #define JS_DUMP_SHAPES 0x80000 /* dump shapes in JS_FreeRuntime */
  7216. // Finalizers run in LIFO order at the very end of JS_FreeRuntime.
  7217. // Intended for cleanup of associated resources; the runtime itself
  7218. // is no longer usable.
  7219. typedef void JSRuntimeFinalizer(JSRuntime *rt, void *arg);
  7220. typedef struct JSGCObjectHeader JSGCObjectHeader;
  7221. JS_EXTERN JSRuntime *JS_NewRuntime(void);
  7222. /* info lifetime must exceed that of rt */
  7223. JS_EXTERN void JS_SetRuntimeInfo(JSRuntime *rt, const char *info);
  7224. /* use 0 to disable memory limit */
  7225. JS_EXTERN void JS_SetMemoryLimit(JSRuntime *rt, size_t limit);
  7226. JS_EXTERN void JS_SetDumpFlags(JSRuntime *rt, uint64_t flags);
  7227. JS_EXTERN uint64_t JS_GetDumpFlags(JSRuntime *rt);
  7228. JS_EXTERN size_t JS_GetGCThreshold(JSRuntime *rt);
  7229. JS_EXTERN void JS_SetGCThreshold(JSRuntime *rt, size_t gc_threshold);
  7230. /* use 0 to disable maximum stack size check */
  7231. JS_EXTERN void JS_SetMaxStackSize(JSRuntime *rt, size_t stack_size);
  7232. /* should be called when changing thread to update the stack top value
  7233. used to check stack overflow. */
  7234. JS_EXTERN void JS_UpdateStackTop(JSRuntime *rt);
  7235. JS_EXTERN JSRuntime *JS_NewRuntime2(const JSMallocFunctions *mf, void *opaque);
  7236. JS_EXTERN void JS_FreeRuntime(JSRuntime *rt);
  7237. JS_EXTERN void *JS_GetRuntimeOpaque(JSRuntime *rt);
  7238. JS_EXTERN void JS_SetRuntimeOpaque(JSRuntime *rt, void *opaque);
  7239. JS_EXTERN int JS_AddRuntimeFinalizer(JSRuntime *rt,
  7240. JSRuntimeFinalizer *finalizer, void *arg);
  7241. typedef void JS_MarkFunc(JSRuntime *rt, JSGCObjectHeader *gp);
  7242. JS_EXTERN void JS_MarkValue(JSRuntime *rt, JSValueConst val,
  7243. JS_MarkFunc *mark_func);
  7244. JS_EXTERN void JS_RunGC(JSRuntime *rt);
  7245. JS_EXTERN bool JS_IsLiveObject(JSRuntime *rt, JSValueConst obj);
  7246. JS_EXTERN JSContext *JS_NewContext(JSRuntime *rt);
  7247. JS_EXTERN void JS_FreeContext(JSContext *s);
  7248. JS_EXTERN JSContext *JS_DupContext(JSContext *ctx);
  7249. JS_EXTERN void *JS_GetContextOpaque(JSContext *ctx);
  7250. JS_EXTERN void JS_SetContextOpaque(JSContext *ctx, void *opaque);
  7251. JS_EXTERN JSRuntime *JS_GetRuntime(JSContext *ctx);
  7252. JS_EXTERN void JS_SetClassProto(JSContext *ctx, JSClassID class_id, JSValue obj);
  7253. JS_EXTERN JSValue JS_GetClassProto(JSContext *ctx, JSClassID class_id);
  7254. JS_EXTERN JSValue JS_GetFunctionProto(JSContext *ctx);
  7255. /* the following functions are used to select the intrinsic object to
  7256. save memory */
  7257. JS_EXTERN JSContext *JS_NewContextRaw(JSRuntime *rt);
  7258. JS_EXTERN void JS_AddIntrinsicBaseObjects(JSContext *ctx);
  7259. JS_EXTERN void JS_AddIntrinsicDate(JSContext *ctx);
  7260. JS_EXTERN void JS_AddIntrinsicEval(JSContext *ctx);
  7261. JS_EXTERN void JS_AddIntrinsicRegExpCompiler(JSContext *ctx);
  7262. JS_EXTERN void JS_AddIntrinsicRegExp(JSContext *ctx);
  7263. JS_EXTERN void JS_AddIntrinsicJSON(JSContext *ctx);
  7264. JS_EXTERN void JS_AddIntrinsicProxy(JSContext *ctx);
  7265. JS_EXTERN void JS_AddIntrinsicMapSet(JSContext *ctx);
  7266. JS_EXTERN void JS_AddIntrinsicTypedArrays(JSContext *ctx);
  7267. JS_EXTERN void JS_AddIntrinsicPromise(JSContext *ctx);
  7268. JS_EXTERN void JS_AddIntrinsicBigInt(JSContext *ctx);
  7269. JS_EXTERN void JS_AddIntrinsicWeakRef(JSContext *ctx);
  7270. JS_EXTERN void JS_AddPerformance(JSContext *ctx);
  7271. /* for equality comparisons and sameness */
  7272. JS_EXTERN int JS_IsEqual(JSContext *ctx, JSValueConst op1, JSValueConst op2);
  7273. JS_EXTERN bool JS_IsStrictEqual(JSContext *ctx, JSValueConst op1, JSValueConst op2);
  7274. JS_EXTERN bool JS_IsSameValue(JSContext *ctx, JSValueConst op1, JSValueConst op2);
  7275. /* Similar to same-value equality, but +0 and -0 are considered equal. */
  7276. JS_EXTERN bool JS_IsSameValueZero(JSContext *ctx, JSValueConst op1, JSValueConst op2);
  7277. /* Only used for running 262 tests. TODO(saghul) add build time flag. */
  7278. JS_EXTERN JSValue js_string_codePointRange(JSContext *ctx, JSValueConst this_val,
  7279. int argc, JSValueConst *argv);
  7280. JS_EXTERN void *js_calloc_rt(JSRuntime *rt, size_t count, size_t size);
  7281. JS_EXTERN void *js_malloc_rt(JSRuntime *rt, size_t size);
  7282. JS_EXTERN void js_free_rt(JSRuntime *rt, void *ptr);
  7283. JS_EXTERN void *js_realloc_rt(JSRuntime *rt, void *ptr, size_t size);
  7284. JS_EXTERN size_t js_malloc_usable_size_rt(JSRuntime *rt, const void *ptr);
  7285. JS_EXTERN void *js_mallocz_rt(JSRuntime *rt, size_t size);
  7286. JS_EXTERN void *js_calloc(JSContext *ctx, size_t count, size_t size);
  7287. JS_EXTERN void *js_malloc(JSContext *ctx, size_t size);
  7288. JS_EXTERN void js_free(JSContext *ctx, void *ptr);
  7289. JS_EXTERN void *js_realloc(JSContext *ctx, void *ptr, size_t size);
  7290. JS_EXTERN size_t js_malloc_usable_size(JSContext *ctx, const void *ptr);
  7291. JS_EXTERN void *js_realloc2(JSContext *ctx, void *ptr, size_t size, size_t *pslack);
  7292. JS_EXTERN void *js_mallocz(JSContext *ctx, size_t size);
  7293. JS_EXTERN char *js_strdup(JSContext *ctx, const char *str);
  7294. JS_EXTERN char *js_strndup(JSContext *ctx, const char *s, size_t n);
  7295. typedef struct JSMemoryUsage {
  7296. int64_t malloc_size, malloc_limit, memory_used_size;
  7297. int64_t malloc_count;
  7298. int64_t memory_used_count;
  7299. int64_t atom_count, atom_size;
  7300. int64_t str_count, str_size;
  7301. int64_t obj_count, obj_size;
  7302. int64_t prop_count, prop_size;
  7303. int64_t shape_count, shape_size;
  7304. int64_t js_func_count, js_func_size, js_func_code_size;
  7305. int64_t js_func_pc2line_count, js_func_pc2line_size;
  7306. int64_t c_func_count, array_count;
  7307. int64_t fast_array_count, fast_array_elements;
  7308. int64_t binary_object_count, binary_object_size;
  7309. } JSMemoryUsage;
  7310. JS_EXTERN void JS_ComputeMemoryUsage(JSRuntime *rt, JSMemoryUsage *s);
  7311. JS_EXTERN void JS_DumpMemoryUsage(FILE *fp, const JSMemoryUsage *s, JSRuntime *rt);
  7312. /* atom support */
  7313. #define JS_ATOM_NULL 0
  7314. JS_EXTERN JSAtom JS_NewAtomLen(JSContext *ctx, const char *str, size_t len);
  7315. JS_EXTERN JSAtom JS_NewAtom(JSContext *ctx, const char *str);
  7316. JS_EXTERN JSAtom JS_NewAtomUInt32(JSContext *ctx, uint32_t n);
  7317. JS_EXTERN JSAtom JS_DupAtom(JSContext *ctx, JSAtom v);
  7318. JS_EXTERN void JS_FreeAtom(JSContext *ctx, JSAtom v);
  7319. JS_EXTERN void JS_FreeAtomRT(JSRuntime *rt, JSAtom v);
  7320. JS_EXTERN JSValue JS_AtomToValue(JSContext *ctx, JSAtom atom);
  7321. JS_EXTERN JSValue JS_AtomToString(JSContext *ctx, JSAtom atom);
  7322. JS_EXTERN const char *JS_AtomToCString(JSContext *ctx, JSAtom atom);
  7323. JS_EXTERN JSAtom JS_ValueToAtom(JSContext *ctx, JSValueConst val);
  7324. /* object class support */
  7325. typedef struct JSPropertyEnum {
  7326. bool is_enumerable;
  7327. JSAtom atom;
  7328. } JSPropertyEnum;
  7329. typedef struct JSPropertyDescriptor {
  7330. int flags;
  7331. JSValue value;
  7332. JSValue getter;
  7333. JSValue setter;
  7334. } JSPropertyDescriptor;
  7335. typedef struct JSClassExoticMethods {
  7336. /* Return -1 if exception (can only happen in case of Proxy object),
  7337. false if the property does not exists, true if it exists. If 1 is
  7338. returned, the property descriptor 'desc' is filled if != NULL. */
  7339. int (*get_own_property)(JSContext *ctx, JSPropertyDescriptor *desc,
  7340. JSValueConst obj, JSAtom prop);
  7341. /* '*ptab' should hold the '*plen' property keys. Return 0 if OK,
  7342. -1 if exception. The 'is_enumerable' field is ignored.
  7343. */
  7344. int (*get_own_property_names)(JSContext *ctx, JSPropertyEnum **ptab,
  7345. uint32_t *plen, JSValueConst obj);
  7346. /* return < 0 if exception, or true/false */
  7347. int (*delete_property)(JSContext *ctx, JSValueConst obj, JSAtom prop);
  7348. /* return < 0 if exception or true/false */
  7349. int (*define_own_property)(JSContext *ctx, JSValueConst this_obj,
  7350. JSAtom prop, JSValueConst val,
  7351. JSValueConst getter, JSValueConst setter,
  7352. int flags);
  7353. /* The following methods can be emulated with the previous ones,
  7354. so they are usually not needed */
  7355. /* return < 0 if exception or true/false */
  7356. int (*has_property)(JSContext *ctx, JSValueConst obj, JSAtom atom);
  7357. JSValue (*get_property)(JSContext *ctx, JSValueConst obj, JSAtom atom,
  7358. JSValueConst receiver);
  7359. /* return < 0 if exception or true/false */
  7360. int (*set_property)(JSContext *ctx, JSValueConst obj, JSAtom atom,
  7361. JSValueConst value, JSValueConst receiver, int flags);
  7362. } JSClassExoticMethods;
  7363. typedef void JSClassFinalizer(JSRuntime *rt, JSValueConst val);
  7364. typedef void JSClassGCMark(JSRuntime *rt, JSValueConst val,
  7365. JS_MarkFunc *mark_func);
  7366. #define JS_CALL_FLAG_CONSTRUCTOR (1 << 0)
  7367. typedef JSValue JSClassCall(JSContext *ctx, JSValueConst func_obj,
  7368. JSValueConst this_val, int argc,
  7369. JSValueConst *argv, int flags);
  7370. typedef struct JSClassDef {
  7371. const char *class_name; /* pure ASCII only! */
  7372. JSClassFinalizer *finalizer;
  7373. JSClassGCMark *gc_mark;
  7374. /* if call != NULL, the object is a function. If (flags &
  7375. JS_CALL_FLAG_CONSTRUCTOR) != 0, the function is called as a
  7376. constructor. In this case, 'this_val' is new.target. A
  7377. constructor call only happens if the object constructor bit is
  7378. set (see JS_SetConstructorBit()). */
  7379. JSClassCall *call;
  7380. /* XXX: suppress this indirection ? It is here only to save memory
  7381. because only a few classes need these methods */
  7382. JSClassExoticMethods *exotic;
  7383. } JSClassDef;
  7384. #define JS_EVAL_OPTIONS_VERSION 1
  7385. typedef struct JSEvalOptions {
  7386. int version;
  7387. int eval_flags;
  7388. const char *filename;
  7389. int line_num;
  7390. // can add new fields in ABI-compatible manner by incrementing JS_EVAL_OPTIONS_VERSION
  7391. } JSEvalOptions;
  7392. #define JS_INVALID_CLASS_ID 0
  7393. JS_EXTERN JSClassID JS_NewClassID(JSRuntime *rt, JSClassID *pclass_id);
  7394. /* Returns the class ID if `v` is an object, otherwise returns JS_INVALID_CLASS_ID. */
  7395. JS_EXTERN JSClassID JS_GetClassID(JSValueConst v);
  7396. JS_EXTERN int JS_NewClass(JSRuntime *rt, JSClassID class_id, const JSClassDef *class_def);
  7397. JS_EXTERN bool JS_IsRegisteredClass(JSRuntime *rt, JSClassID class_id);
  7398. /* value handling */
  7399. static js_force_inline JSValue JS_NewBool(JSContext *ctx, bool val)
  7400. {
  7401. (void)&ctx;
  7402. return JS_MKVAL(JS_TAG_BOOL, (val != 0));
  7403. }
  7404. static js_force_inline JSValue JS_NewInt32(JSContext *ctx, int32_t val)
  7405. {
  7406. (void)&ctx;
  7407. return JS_MKVAL(JS_TAG_INT, val);
  7408. }
  7409. static js_force_inline JSValue JS_NewFloat64(JSContext *ctx, double val)
  7410. {
  7411. (void)&ctx;
  7412. return __JS_NewFloat64(val);
  7413. }
  7414. static js_force_inline JSValue JS_NewCatchOffset(JSContext *ctx, int32_t val)
  7415. {
  7416. (void)&ctx;
  7417. return JS_MKVAL(JS_TAG_CATCH_OFFSET, val);
  7418. }
  7419. static js_force_inline JSValue JS_NewInt64(JSContext *ctx, int64_t val)
  7420. {
  7421. JSValue v;
  7422. if (val >= INT32_MIN && val <= INT32_MAX) {
  7423. v = JS_NewInt32(ctx, (int32_t)val);
  7424. } else {
  7425. v = JS_NewFloat64(ctx, (double)val);
  7426. }
  7427. return v;
  7428. }
  7429. static js_force_inline JSValue JS_NewUint32(JSContext *ctx, uint32_t val)
  7430. {
  7431. JSValue v;
  7432. if (val <= INT32_MAX) {
  7433. v = JS_NewInt32(ctx, (int32_t)val);
  7434. } else {
  7435. v = JS_NewFloat64(ctx, (double)val);
  7436. }
  7437. return v;
  7438. }
  7439. JS_EXTERN JSValue JS_NewNumber(JSContext *ctx, double d);
  7440. JS_EXTERN JSValue JS_NewBigInt64(JSContext *ctx, int64_t v);
  7441. JS_EXTERN JSValue JS_NewBigUint64(JSContext *ctx, uint64_t v);
  7442. static inline bool JS_IsNumber(JSValueConst v)
  7443. {
  7444. int tag = JS_VALUE_GET_TAG(v);
  7445. return tag == JS_TAG_INT || JS_TAG_IS_FLOAT64(tag);
  7446. }
  7447. static inline bool JS_IsBigInt(JSContext *ctx, JSValueConst v)
  7448. {
  7449. (void)&ctx;
  7450. return JS_VALUE_GET_TAG(v) == JS_TAG_BIG_INT;
  7451. }
  7452. static inline bool JS_IsBool(JSValueConst v)
  7453. {
  7454. return JS_VALUE_GET_TAG(v) == JS_TAG_BOOL;
  7455. }
  7456. static inline bool JS_IsNull(JSValueConst v)
  7457. {
  7458. return JS_VALUE_GET_TAG(v) == JS_TAG_NULL;
  7459. }
  7460. static inline bool JS_IsUndefined(JSValueConst v)
  7461. {
  7462. return JS_VALUE_GET_TAG(v) == JS_TAG_UNDEFINED;
  7463. }
  7464. static inline bool JS_IsException(JSValueConst v)
  7465. {
  7466. return JS_VALUE_GET_TAG(v) == JS_TAG_EXCEPTION;
  7467. }
  7468. static inline bool JS_IsUninitialized(JSValueConst v)
  7469. {
  7470. return JS_VALUE_GET_TAG(v) == JS_TAG_UNINITIALIZED;
  7471. }
  7472. static inline bool JS_IsString(JSValueConst v)
  7473. {
  7474. return JS_VALUE_GET_TAG(v) == JS_TAG_STRING;
  7475. }
  7476. static inline bool JS_IsSymbol(JSValueConst v)
  7477. {
  7478. return JS_VALUE_GET_TAG(v) == JS_TAG_SYMBOL;
  7479. }
  7480. static inline bool JS_IsObject(JSValueConst v)
  7481. {
  7482. return JS_VALUE_GET_TAG(v) == JS_TAG_OBJECT;
  7483. }
  7484. static inline bool JS_IsModule(JSValueConst v)
  7485. {
  7486. return JS_VALUE_GET_TAG(v) == JS_TAG_MODULE;
  7487. }
  7488. JS_EXTERN JSValue JS_Throw(JSContext *ctx, JSValue obj);
  7489. JS_EXTERN JSValue JS_GetException(JSContext *ctx);
  7490. JS_EXTERN bool JS_HasException(JSContext *ctx);
  7491. JS_EXTERN bool JS_IsError(JSContext *ctx, JSValueConst val);
  7492. JS_EXTERN bool JS_IsUncatchableError(JSContext* ctx, JSValueConst val);
  7493. JS_EXTERN void JS_SetUncatchableError(JSContext *ctx, JSValueConst val);
  7494. JS_EXTERN void JS_ClearUncatchableError(JSContext *ctx, JSValueConst val);
  7495. // Shorthand for:
  7496. // JSValue exc = JS_GetException(ctx);
  7497. // JS_ClearUncatchableError(ctx, exc);
  7498. // JS_Throw(ctx, exc);
  7499. JS_EXTERN void JS_ResetUncatchableError(JSContext *ctx);
  7500. JS_EXTERN JSValue JS_NewError(JSContext *ctx);
  7501. JS_EXTERN JSValue JS_PRINTF_FORMAT_ATTR(2, 3) JS_ThrowPlainError(JSContext *ctx, JS_PRINTF_FORMAT const char *fmt, ...);
  7502. JS_EXTERN JSValue JS_PRINTF_FORMAT_ATTR(2, 3) JS_ThrowSyntaxError(JSContext *ctx, JS_PRINTF_FORMAT const char *fmt, ...);
  7503. JS_EXTERN JSValue JS_PRINTF_FORMAT_ATTR(2, 3) JS_ThrowTypeError(JSContext *ctx, JS_PRINTF_FORMAT const char *fmt, ...);
  7504. JS_EXTERN JSValue JS_PRINTF_FORMAT_ATTR(2, 3) JS_ThrowReferenceError(JSContext *ctx, JS_PRINTF_FORMAT const char *fmt, ...);
  7505. JS_EXTERN JSValue JS_PRINTF_FORMAT_ATTR(2, 3) JS_ThrowRangeError(JSContext *ctx, JS_PRINTF_FORMAT const char *fmt, ...);
  7506. JS_EXTERN JSValue JS_PRINTF_FORMAT_ATTR(2, 3) JS_ThrowInternalError(JSContext *ctx, JS_PRINTF_FORMAT const char *fmt, ...);
  7507. JS_EXTERN JSValue JS_ThrowOutOfMemory(JSContext *ctx);
  7508. JS_EXTERN void JS_FreeValue(JSContext *ctx, JSValue v);
  7509. JS_EXTERN void JS_FreeValueRT(JSRuntime *rt, JSValue v);
  7510. JS_EXTERN JSValue JS_DupValue(JSContext *ctx, JSValueConst v);
  7511. JS_EXTERN JSValue JS_DupValueRT(JSRuntime *rt, JSValueConst v);
  7512. JS_EXTERN int JS_ToBool(JSContext *ctx, JSValueConst val); /* return -1 for JS_EXCEPTION */
  7513. static inline JSValue JS_ToBoolean(JSContext *ctx, JSValueConst val)
  7514. {
  7515. return JS_NewBool(ctx, JS_ToBool(ctx, val));
  7516. }
  7517. JS_EXTERN JSValue JS_ToNumber(JSContext *ctx, JSValueConst val);
  7518. JS_EXTERN int JS_ToInt32(JSContext *ctx, int32_t *pres, JSValueConst val);
  7519. static inline int JS_ToUint32(JSContext *ctx, uint32_t *pres, JSValueConst val)
  7520. {
  7521. return JS_ToInt32(ctx, (int32_t*)pres, val);
  7522. }
  7523. JS_EXTERN int JS_ToInt64(JSContext *ctx, int64_t *pres, JSValueConst val);
  7524. JS_EXTERN int JS_ToIndex(JSContext *ctx, uint64_t *plen, JSValueConst val);
  7525. JS_EXTERN int JS_ToFloat64(JSContext *ctx, double *pres, JSValueConst val);
  7526. /* return an exception if 'val' is a Number */
  7527. JS_EXTERN int JS_ToBigInt64(JSContext *ctx, int64_t *pres, JSValueConst val);
  7528. JS_EXTERN int JS_ToBigUint64(JSContext *ctx, uint64_t *pres, JSValueConst val);
  7529. /* same as JS_ToInt64() but allow BigInt */
  7530. JS_EXTERN int JS_ToInt64Ext(JSContext *ctx, int64_t *pres, JSValueConst val);
  7531. JS_EXTERN JSValue JS_NewStringLen(JSContext *ctx, const char *str1, size_t len1);
  7532. static inline JSValue JS_NewString(JSContext *ctx, const char *str) {
  7533. return JS_NewStringLen(ctx, str, strlen(str));
  7534. }
  7535. JS_EXTERN JSValue JS_NewAtomString(JSContext *ctx, const char *str);
  7536. JS_EXTERN JSValue JS_ToString(JSContext *ctx, JSValueConst val);
  7537. JS_EXTERN JSValue JS_ToPropertyKey(JSContext *ctx, JSValueConst val);
  7538. JS_EXTERN const char *JS_ToCStringLen2(JSContext *ctx, size_t *plen, JSValueConst val1, bool cesu8);
  7539. static inline const char *JS_ToCStringLen(JSContext *ctx, size_t *plen, JSValueConst val1)
  7540. {
  7541. return JS_ToCStringLen2(ctx, plen, val1, 0);
  7542. }
  7543. static inline const char *JS_ToCString(JSContext *ctx, JSValueConst val1)
  7544. {
  7545. return JS_ToCStringLen2(ctx, NULL, val1, 0);
  7546. }
  7547. JS_EXTERN void JS_FreeCString(JSContext *ctx, const char *ptr);
  7548. JS_EXTERN JSValue JS_NewObjectProtoClass(JSContext *ctx, JSValueConst proto,
  7549. JSClassID class_id);
  7550. JS_EXTERN JSValue JS_NewObjectClass(JSContext *ctx, int class_id);
  7551. JS_EXTERN JSValue JS_NewObjectProto(JSContext *ctx, JSValueConst proto);
  7552. JS_EXTERN JSValue JS_NewObject(JSContext *ctx);
  7553. // takes ownership of the values
  7554. JS_EXTERN JSValue JS_NewObjectFrom(JSContext *ctx, int count,
  7555. const JSAtom *props,
  7556. const JSValue *values);
  7557. // takes ownership of the values
  7558. JS_EXTERN JSValue JS_NewObjectFromStr(JSContext *ctx, int count,
  7559. const char **props,
  7560. const JSValue *values);
  7561. JS_EXTERN JSValue JS_ToObject(JSContext *ctx, JSValueConst val);
  7562. JS_EXTERN JSValue JS_ToObjectString(JSContext *ctx, JSValueConst val);
  7563. JS_EXTERN bool JS_IsFunction(JSContext* ctx, JSValueConst val);
  7564. JS_EXTERN bool JS_IsConstructor(JSContext* ctx, JSValueConst val);
  7565. JS_EXTERN bool JS_SetConstructorBit(JSContext *ctx, JSValueConst func_obj, bool val);
  7566. JS_EXTERN bool JS_IsRegExp(JSValueConst val);
  7567. JS_EXTERN bool JS_IsMap(JSValueConst val);
  7568. JS_EXTERN JSValue JS_NewArray(JSContext *ctx);
  7569. // takes ownership of the values
  7570. JS_EXTERN JSValue JS_NewArrayFrom(JSContext *ctx, int count,
  7571. const JSValue *values);
  7572. // reader beware: JS_IsArray used to "punch" through proxies and check
  7573. // if the target object is an array but it no longer does; use JS_IsProxy
  7574. // and JS_GetProxyTarget instead, and remember that the target itself can
  7575. // also be a proxy, ad infinitum
  7576. JS_EXTERN bool JS_IsArray(JSValueConst val);
  7577. JS_EXTERN bool JS_IsProxy(JSValueConst val);
  7578. JS_EXTERN JSValue JS_GetProxyTarget(JSContext *ctx, JSValueConst proxy);
  7579. JS_EXTERN JSValue JS_GetProxyHandler(JSContext *ctx, JSValueConst proxy);
  7580. JS_EXTERN JSValue JS_NewDate(JSContext *ctx, double epoch_ms);
  7581. JS_EXTERN bool JS_IsDate(JSValueConst v);
  7582. JS_EXTERN JSValue JS_GetProperty(JSContext *ctx, JSValueConst this_obj, JSAtom prop);
  7583. JS_EXTERN JSValue JS_GetPropertyUint32(JSContext *ctx, JSValueConst this_obj,
  7584. uint32_t idx);
  7585. JS_EXTERN JSValue JS_GetPropertyInt64(JSContext *ctx, JSValueConst this_obj,
  7586. int64_t idx);
  7587. JS_EXTERN JSValue JS_GetPropertyStr(JSContext *ctx, JSValueConst this_obj,
  7588. const char *prop);
  7589. JS_EXTERN int JS_SetProperty(JSContext *ctx, JSValueConst this_obj,
  7590. JSAtom prop, JSValue val);
  7591. JS_EXTERN int JS_SetPropertyUint32(JSContext *ctx, JSValueConst this_obj,
  7592. uint32_t idx, JSValue val);
  7593. JS_EXTERN int JS_SetPropertyInt64(JSContext *ctx, JSValueConst this_obj,
  7594. int64_t idx, JSValue val);
  7595. JS_EXTERN int JS_SetPropertyStr(JSContext *ctx, JSValueConst this_obj,
  7596. const char *prop, JSValue val);
  7597. JS_EXTERN int JS_HasProperty(JSContext *ctx, JSValueConst this_obj, JSAtom prop);
  7598. JS_EXTERN int JS_IsExtensible(JSContext *ctx, JSValueConst obj);
  7599. JS_EXTERN int JS_PreventExtensions(JSContext *ctx, JSValueConst obj);
  7600. JS_EXTERN int JS_DeleteProperty(JSContext *ctx, JSValueConst obj, JSAtom prop, int flags);
  7601. JS_EXTERN int JS_SetPrototype(JSContext *ctx, JSValueConst obj, JSValue proto_val);
  7602. JS_EXTERN JSValue JS_GetPrototype(JSContext *ctx, JSValueConst val);
  7603. JS_EXTERN int JS_GetLength(JSContext *ctx, JSValueConst obj, int64_t *pres);
  7604. JS_EXTERN int JS_SetLength(JSContext *ctx, JSValueConst obj, int64_t len);
  7605. JS_EXTERN int JS_SealObject(JSContext *ctx, JSValueConst obj);
  7606. JS_EXTERN int JS_FreezeObject(JSContext *ctx, JSValueConst obj);
  7607. #define JS_GPN_STRING_MASK (1 << 0)
  7608. #define JS_GPN_SYMBOL_MASK (1 << 1)
  7609. #define JS_GPN_PRIVATE_MASK (1 << 2)
  7610. /* only include the enumerable properties */
  7611. #define JS_GPN_ENUM_ONLY (1 << 4)
  7612. /* set theJSPropertyEnum.is_enumerable field */
  7613. #define JS_GPN_SET_ENUM (1 << 5)
  7614. JS_EXTERN int JS_GetOwnPropertyNames(JSContext *ctx, JSPropertyEnum **ptab,
  7615. uint32_t *plen, JSValueConst obj,
  7616. int flags);
  7617. JS_EXTERN int JS_GetOwnProperty(JSContext *ctx, JSPropertyDescriptor *desc,
  7618. JSValueConst obj, JSAtom prop);
  7619. JS_EXTERN void JS_FreePropertyEnum(JSContext *ctx, JSPropertyEnum *tab,
  7620. uint32_t len);
  7621. JS_EXTERN JSValue JS_Call(JSContext *ctx, JSValueConst func_obj,
  7622. JSValueConst this_obj, int argc, JSValueConst *argv);
  7623. JS_EXTERN JSValue JS_Invoke(JSContext *ctx, JSValueConst this_val, JSAtom atom,
  7624. int argc, JSValueConst *argv);
  7625. JS_EXTERN JSValue JS_CallConstructor(JSContext *ctx, JSValueConst func_obj,
  7626. int argc, JSValueConst *argv);
  7627. JS_EXTERN JSValue JS_CallConstructor2(JSContext *ctx, JSValueConst func_obj,
  7628. JSValueConst new_target,
  7629. int argc, JSValueConst *argv);
  7630. /* Try to detect if the input is a module. Returns true if parsing the input
  7631. * as a module produces no syntax errors. It's a naive approach that is not
  7632. * wholly infallible: non-strict classic scripts may _parse_ okay as a module
  7633. * but not _execute_ as one (different runtime semantics.) Use with caution.
  7634. * |input| can be either ASCII or UTF-8 encoded source code.
  7635. */
  7636. JS_EXTERN bool JS_DetectModule(const char *input, size_t input_len);
  7637. /* 'input' must be zero terminated i.e. input[input_len] = '\0'. */
  7638. JS_EXTERN JSValue JS_Eval(JSContext *ctx, const char *input, size_t input_len,
  7639. const char *filename, int eval_flags);
  7640. JS_EXTERN JSValue JS_Eval2(JSContext *ctx, const char *input, size_t input_len,
  7641. JSEvalOptions *options);
  7642. JS_EXTERN JSValue JS_EvalThis(JSContext *ctx, JSValueConst this_obj,
  7643. const char *input, size_t input_len,
  7644. const char *filename, int eval_flags);
  7645. JS_EXTERN JSValue JS_EvalThis2(JSContext *ctx, JSValueConst this_obj,
  7646. const char *input, size_t input_len,
  7647. JSEvalOptions *options);
  7648. JS_EXTERN JSValue JS_GetGlobalObject(JSContext *ctx);
  7649. JS_EXTERN int JS_IsInstanceOf(JSContext *ctx, JSValueConst val, JSValueConst obj);
  7650. JS_EXTERN int JS_DefineProperty(JSContext *ctx, JSValueConst this_obj,
  7651. JSAtom prop, JSValueConst val,
  7652. JSValueConst getter, JSValueConst setter,
  7653. int flags);
  7654. JS_EXTERN int JS_DefinePropertyValue(JSContext *ctx, JSValueConst this_obj,
  7655. JSAtom prop, JSValue val, int flags);
  7656. JS_EXTERN int JS_DefinePropertyValueUint32(JSContext *ctx, JSValueConst this_obj,
  7657. uint32_t idx, JSValue val, int flags);
  7658. JS_EXTERN int JS_DefinePropertyValueStr(JSContext *ctx, JSValueConst this_obj,
  7659. const char *prop, JSValue val, int flags);
  7660. JS_EXTERN int JS_DefinePropertyGetSet(JSContext *ctx, JSValueConst this_obj,
  7661. JSAtom prop, JSValue getter, JSValue setter,
  7662. int flags);
  7663. /* Only supported for custom classes, returns 0 on success < 0 otherwise. */
  7664. JS_EXTERN int JS_SetOpaque(JSValueConst obj, void *opaque);
  7665. JS_EXTERN void *JS_GetOpaque(JSValueConst obj, JSClassID class_id);
  7666. JS_EXTERN void *JS_GetOpaque2(JSContext *ctx, JSValueConst obj, JSClassID class_id);
  7667. JS_EXTERN void *JS_GetAnyOpaque(JSValueConst obj, JSClassID *class_id);
  7668. /* 'buf' must be zero terminated i.e. buf[buf_len] = '\0'. */
  7669. JS_EXTERN JSValue JS_ParseJSON(JSContext *ctx, const char *buf, size_t buf_len,
  7670. const char *filename);
  7671. JS_EXTERN JSValue JS_JSONStringify(JSContext *ctx, JSValueConst obj,
  7672. JSValueConst replacer, JSValueConst space0);
  7673. typedef void JSFreeArrayBufferDataFunc(JSRuntime *rt, void *opaque, void *ptr);
  7674. JS_EXTERN JSValue JS_NewArrayBuffer(JSContext *ctx, uint8_t *buf, size_t len,
  7675. JSFreeArrayBufferDataFunc *free_func, void *opaque,
  7676. bool is_shared);
  7677. JS_EXTERN JSValue JS_NewArrayBufferCopy(JSContext *ctx, const uint8_t *buf, size_t len);
  7678. JS_EXTERN void JS_DetachArrayBuffer(JSContext *ctx, JSValueConst obj);
  7679. JS_EXTERN uint8_t *JS_GetArrayBuffer(JSContext *ctx, size_t *psize, JSValueConst obj);
  7680. JS_EXTERN bool JS_IsArrayBuffer(JSValueConst obj);
  7681. JS_EXTERN uint8_t *JS_GetUint8Array(JSContext *ctx, size_t *psize, JSValueConst obj);
  7682. typedef enum JSTypedArrayEnum {
  7683. JS_TYPED_ARRAY_UINT8C = 0,
  7684. JS_TYPED_ARRAY_INT8,
  7685. JS_TYPED_ARRAY_UINT8,
  7686. JS_TYPED_ARRAY_INT16,
  7687. JS_TYPED_ARRAY_UINT16,
  7688. JS_TYPED_ARRAY_INT32,
  7689. JS_TYPED_ARRAY_UINT32,
  7690. JS_TYPED_ARRAY_BIG_INT64,
  7691. JS_TYPED_ARRAY_BIG_UINT64,
  7692. JS_TYPED_ARRAY_FLOAT16,
  7693. JS_TYPED_ARRAY_FLOAT32,
  7694. JS_TYPED_ARRAY_FLOAT64,
  7695. } JSTypedArrayEnum;
  7696. JS_EXTERN JSValue JS_NewTypedArray(JSContext *ctx, int argc, JSValueConst *argv,
  7697. JSTypedArrayEnum array_type);
  7698. JS_EXTERN JSValue JS_GetTypedArrayBuffer(JSContext *ctx, JSValueConst obj,
  7699. size_t *pbyte_offset,
  7700. size_t *pbyte_length,
  7701. size_t *pbytes_per_element);
  7702. JS_EXTERN JSValue JS_NewUint8Array(JSContext *ctx, uint8_t *buf, size_t len,
  7703. JSFreeArrayBufferDataFunc *free_func, void *opaque,
  7704. bool is_shared);
  7705. /* returns -1 if not a typed array otherwise return a JSTypedArrayEnum value */
  7706. JS_EXTERN int JS_GetTypedArrayType(JSValueConst obj);
  7707. JS_EXTERN JSValue JS_NewUint8ArrayCopy(JSContext *ctx, const uint8_t *buf, size_t len);
  7708. typedef struct {
  7709. void *(*sab_alloc)(void *opaque, size_t size);
  7710. void (*sab_free)(void *opaque, void *ptr);
  7711. void (*sab_dup)(void *opaque, void *ptr);
  7712. void *sab_opaque;
  7713. } JSSharedArrayBufferFunctions;
  7714. JS_EXTERN void JS_SetSharedArrayBufferFunctions(JSRuntime *rt, const JSSharedArrayBufferFunctions *sf);
  7715. typedef enum JSPromiseStateEnum {
  7716. JS_PROMISE_PENDING,
  7717. JS_PROMISE_FULFILLED,
  7718. JS_PROMISE_REJECTED,
  7719. } JSPromiseStateEnum;
  7720. JS_EXTERN JSValue JS_NewPromiseCapability(JSContext *ctx, JSValue *resolving_funcs);
  7721. JS_EXTERN JSPromiseStateEnum JS_PromiseState(JSContext *ctx,
  7722. JSValueConst promise);
  7723. JS_EXTERN JSValue JS_PromiseResult(JSContext *ctx, JSValueConst promise);
  7724. JS_EXTERN bool JS_IsPromise(JSValueConst val);
  7725. JS_EXTERN JSValue JS_NewSymbol(JSContext *ctx, const char *description, bool is_global);
  7726. /* is_handled = true means that the rejection is handled */
  7727. typedef void JSHostPromiseRejectionTracker(JSContext *ctx, JSValueConst promise,
  7728. JSValueConst reason,
  7729. bool is_handled, void *opaque);
  7730. JS_EXTERN void JS_SetHostPromiseRejectionTracker(JSRuntime *rt, JSHostPromiseRejectionTracker *cb, void *opaque);
  7731. /* return != 0 if the JS code needs to be interrupted */
  7732. typedef int JSInterruptHandler(JSRuntime *rt, void *opaque);
  7733. JS_EXTERN void JS_SetInterruptHandler(JSRuntime *rt, JSInterruptHandler *cb, void *opaque);
  7734. /* if can_block is true, Atomics.wait() can be used */
  7735. JS_EXTERN void JS_SetCanBlock(JSRuntime *rt, bool can_block);
  7736. /* set the [IsHTMLDDA] internal slot */
  7737. JS_EXTERN void JS_SetIsHTMLDDA(JSContext *ctx, JSValueConst obj);
  7738. typedef struct JSModuleDef JSModuleDef;
  7739. /* return the module specifier (allocated with js_malloc()) or NULL if
  7740. exception */
  7741. typedef char *JSModuleNormalizeFunc(JSContext *ctx,
  7742. const char *module_base_name,
  7743. const char *module_name, void *opaque);
  7744. typedef JSModuleDef *JSModuleLoaderFunc(JSContext *ctx,
  7745. const char *module_name, void *opaque);
  7746. /* module_normalize = NULL is allowed and invokes the default module
  7747. filename normalizer */
  7748. JS_EXTERN void JS_SetModuleLoaderFunc(JSRuntime *rt,
  7749. JSModuleNormalizeFunc *module_normalize,
  7750. JSModuleLoaderFunc *module_loader, void *opaque);
  7751. /* return the import.meta object of a module */
  7752. JS_EXTERN JSValue JS_GetImportMeta(JSContext *ctx, JSModuleDef *m);
  7753. JS_EXTERN JSAtom JS_GetModuleName(JSContext *ctx, JSModuleDef *m);
  7754. JS_EXTERN JSValue JS_GetModuleNamespace(JSContext *ctx, JSModuleDef *m);
  7755. /* JS Job support */
  7756. typedef JSValue JSJobFunc(JSContext *ctx, int argc, JSValueConst *argv);
  7757. JS_EXTERN int JS_EnqueueJob(JSContext *ctx, JSJobFunc *job_func,
  7758. int argc, JSValueConst *argv);
  7759. JS_EXTERN bool JS_IsJobPending(JSRuntime *rt);
  7760. JS_EXTERN int JS_ExecutePendingJob(JSRuntime *rt, JSContext **pctx);
  7761. /* Structure to retrieve (de)serialized SharedArrayBuffer objects. */
  7762. typedef struct JSSABTab {
  7763. uint8_t **tab;
  7764. size_t len;
  7765. } JSSABTab;
  7766. /* Object Writer/Reader (currently only used to handle precompiled code) */
  7767. #define JS_WRITE_OBJ_BYTECODE (1 << 0) /* allow function/module */
  7768. #define JS_WRITE_OBJ_BSWAP (0) /* byte swapped output (obsolete, handled transparently) */
  7769. #define JS_WRITE_OBJ_SAB (1 << 2) /* allow SharedArrayBuffer */
  7770. #define JS_WRITE_OBJ_REFERENCE (1 << 3) /* allow object references to encode arbitrary object graph */
  7771. #define JS_WRITE_OBJ_STRIP_SOURCE (1 << 4) /* do not write source code information */
  7772. #define JS_WRITE_OBJ_STRIP_DEBUG (1 << 5) /* do not write debug information */
  7773. JS_EXTERN uint8_t *JS_WriteObject(JSContext *ctx, size_t *psize, JSValueConst obj, int flags);
  7774. JS_EXTERN uint8_t *JS_WriteObject2(JSContext *ctx, size_t *psize, JSValueConst obj,
  7775. int flags, JSSABTab *psab_tab);
  7776. #define JS_READ_OBJ_BYTECODE (1 << 0) /* allow function/module */
  7777. #define JS_READ_OBJ_ROM_DATA (0) /* avoid duplicating 'buf' data (obsolete, broken by ICs) */
  7778. #define JS_READ_OBJ_SAB (1 << 2) /* allow SharedArrayBuffer */
  7779. #define JS_READ_OBJ_REFERENCE (1 << 3) /* allow object references */
  7780. JS_EXTERN JSValue JS_ReadObject(JSContext *ctx, const uint8_t *buf, size_t buf_len, int flags);
  7781. JS_EXTERN JSValue JS_ReadObject2(JSContext *ctx, const uint8_t *buf, size_t buf_len,
  7782. int flags, JSSABTab *psab_tab);
  7783. /* instantiate and evaluate a bytecode function. Only used when
  7784. reading a script or module with JS_ReadObject() */
  7785. JS_EXTERN JSValue JS_EvalFunction(JSContext *ctx, JSValue fun_obj);
  7786. /* load the dependencies of the module 'obj'. Useful when JS_ReadObject()
  7787. returns a module. */
  7788. JS_EXTERN int JS_ResolveModule(JSContext *ctx, JSValueConst obj);
  7789. /* only exported for os.Worker() */
  7790. JS_EXTERN JSAtom JS_GetScriptOrModuleName(JSContext *ctx, int n_stack_levels);
  7791. /* only exported for os.Worker() */
  7792. JS_EXTERN JSValue JS_LoadModule(JSContext *ctx, const char *basename,
  7793. const char *filename);
  7794. /* C function definition */
  7795. typedef enum JSCFunctionEnum { /* XXX: should rename for namespace isolation */
  7796. JS_CFUNC_generic,
  7797. JS_CFUNC_generic_magic,
  7798. JS_CFUNC_constructor,
  7799. JS_CFUNC_constructor_magic,
  7800. JS_CFUNC_constructor_or_func,
  7801. JS_CFUNC_constructor_or_func_magic,
  7802. JS_CFUNC_f_f,
  7803. JS_CFUNC_f_f_f,
  7804. JS_CFUNC_getter,
  7805. JS_CFUNC_setter,
  7806. JS_CFUNC_getter_magic,
  7807. JS_CFUNC_setter_magic,
  7808. JS_CFUNC_iterator_next,
  7809. } JSCFunctionEnum;
  7810. typedef union JSCFunctionType {
  7811. JSCFunction *generic;
  7812. JSValue (*generic_magic)(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic);
  7813. JSCFunction *constructor;
  7814. JSValue (*constructor_magic)(JSContext *ctx, JSValueConst new_target, int argc, JSValueConst *argv, int magic);
  7815. JSCFunction *constructor_or_func;
  7816. double (*f_f)(double);
  7817. double (*f_f_f)(double, double);
  7818. JSValue (*getter)(JSContext *ctx, JSValueConst this_val);
  7819. JSValue (*setter)(JSContext *ctx, JSValueConst this_val, JSValueConst val);
  7820. JSValue (*getter_magic)(JSContext *ctx, JSValueConst this_val, int magic);
  7821. JSValue (*setter_magic)(JSContext *ctx, JSValueConst this_val, JSValueConst val, int magic);
  7822. JSValue (*iterator_next)(JSContext *ctx, JSValueConst this_val,
  7823. int argc, JSValueConst *argv, int *pdone, int magic);
  7824. } JSCFunctionType;
  7825. JS_EXTERN JSValue JS_NewCFunction2(JSContext *ctx, JSCFunction *func,
  7826. const char *name,
  7827. int length, JSCFunctionEnum cproto, int magic);
  7828. JS_EXTERN JSValue JS_NewCFunction3(JSContext *ctx, JSCFunction *func,
  7829. const char *name,
  7830. int length, JSCFunctionEnum cproto, int magic,
  7831. JSValue proto_val);
  7832. JS_EXTERN JSValue JS_NewCFunctionData(JSContext *ctx, JSCFunctionData *func,
  7833. int length, int magic, int data_len,
  7834. JSValueConst *data);
  7835. static inline JSValue JS_NewCFunction(JSContext *ctx, JSCFunction *func,
  7836. const char *name, int length)
  7837. {
  7838. return JS_NewCFunction2(ctx, func, name, length, JS_CFUNC_generic, 0);
  7839. }
  7840. static inline JSValue JS_NewCFunctionMagic(JSContext *ctx, JSCFunctionMagic *func,
  7841. const char *name, int length,
  7842. JSCFunctionEnum cproto, int magic)
  7843. {
  7844. /* Used to squelch a -Wcast-function-type warning. */
  7845. JSCFunctionType ft;
  7846. ft.generic_magic = func;
  7847. return JS_NewCFunction2(ctx, ft.generic, name, length, cproto, magic);
  7848. }
  7849. JS_EXTERN void JS_SetConstructor(JSContext *ctx, JSValueConst func_obj,
  7850. JSValueConst proto);
  7851. /* C property definition */
  7852. typedef struct JSCFunctionListEntry {
  7853. const char *name; /* pure ASCII or UTF-8 encoded */
  7854. uint8_t prop_flags;
  7855. uint8_t def_type;
  7856. int16_t magic;
  7857. union {
  7858. struct {
  7859. uint8_t length; /* XXX: should move outside union */
  7860. uint8_t cproto; /* XXX: should move outside union */
  7861. JSCFunctionType cfunc;
  7862. } func;
  7863. struct {
  7864. JSCFunctionType get;
  7865. JSCFunctionType set;
  7866. } getset;
  7867. struct {
  7868. const char *name;
  7869. int base;
  7870. } alias;
  7871. struct {
  7872. const struct JSCFunctionListEntry *tab;
  7873. int len;
  7874. } prop_list;
  7875. const char *str; /* pure ASCII or UTF-8 encoded */
  7876. int32_t i32;
  7877. int64_t i64;
  7878. uint64_t u64;
  7879. double f64;
  7880. } u;
  7881. } JSCFunctionListEntry;
  7882. #define JS_DEF_CFUNC 0
  7883. #define JS_DEF_CGETSET 1
  7884. #define JS_DEF_CGETSET_MAGIC 2
  7885. #define JS_DEF_PROP_STRING 3
  7886. #define JS_DEF_PROP_INT32 4
  7887. #define JS_DEF_PROP_INT64 5
  7888. #define JS_DEF_PROP_DOUBLE 6
  7889. #define JS_DEF_PROP_UNDEFINED 7
  7890. #define JS_DEF_OBJECT 8
  7891. #define JS_DEF_ALIAS 9
  7892. /* Note: c++ does not like nested designators */
  7893. #define JS_CFUNC_DEF(name, length, func1) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_CFUNC, 0, { .func = { length, JS_CFUNC_generic, { .generic = func1 } } } }
  7894. #define JS_CFUNC_DEF2(name, length, func1, prop_flags) { name, prop_flags, JS_DEF_CFUNC, 0, { .func = { length, JS_CFUNC_generic, { .generic = func1 } } } }
  7895. #define JS_CFUNC_MAGIC_DEF(name, length, func1, magic) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_CFUNC, magic, { .func = { length, JS_CFUNC_generic_magic, { .generic_magic = func1 } } } }
  7896. #define JS_CFUNC_SPECIAL_DEF(name, length, cproto, func1) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_CFUNC, 0, { .func = { length, JS_CFUNC_ ## cproto, { .cproto = func1 } } } }
  7897. #define JS_ITERATOR_NEXT_DEF(name, length, func1, magic) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_CFUNC, magic, { .func = { length, JS_CFUNC_iterator_next, { .iterator_next = func1 } } } }
  7898. #define JS_CGETSET_DEF(name, fgetter, fsetter) { name, JS_PROP_CONFIGURABLE, JS_DEF_CGETSET, 0, { .getset = { .get = { .getter = fgetter }, .set = { .setter = fsetter } } } }
  7899. #define JS_CGETSET_DEF2(name, fgetter, fsetter, prop_flags) { name, prop_flags, JS_DEF_CGETSET, 0, { .getset = { .get = { .getter = fgetter }, .set = { .setter = fsetter } } } }
  7900. #define JS_CGETSET_MAGIC_DEF(name, fgetter, fsetter, magic) { name, JS_PROP_CONFIGURABLE, JS_DEF_CGETSET_MAGIC, magic, { .getset = { .get = { .getter_magic = fgetter }, .set = { .setter_magic = fsetter } } } }
  7901. #define JS_PROP_STRING_DEF(name, cstr, prop_flags) { name, prop_flags, JS_DEF_PROP_STRING, 0, { .str = cstr } }
  7902. #define JS_PROP_INT32_DEF(name, val, prop_flags) { name, prop_flags, JS_DEF_PROP_INT32, 0, { .i32 = val } }
  7903. #define JS_PROP_INT64_DEF(name, val, prop_flags) { name, prop_flags, JS_DEF_PROP_INT64, 0, { .i64 = val } }
  7904. #define JS_PROP_DOUBLE_DEF(name, val, prop_flags) { name, prop_flags, JS_DEF_PROP_DOUBLE, 0, { .f64 = val } }
  7905. #define JS_PROP_U2D_DEF(name, val, prop_flags) { name, prop_flags, JS_DEF_PROP_DOUBLE, 0, { .u64 = val } }
  7906. #define JS_PROP_UNDEFINED_DEF(name, prop_flags) { name, prop_flags, JS_DEF_PROP_UNDEFINED, 0, { .i32 = 0 } }
  7907. #define JS_OBJECT_DEF(name, tab, len, prop_flags) { name, prop_flags, JS_DEF_OBJECT, 0, { .prop_list = { tab, len } } }
  7908. #define JS_ALIAS_DEF(name, from) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_ALIAS, 0, { .alias = { from, -1 } } }
  7909. #define JS_ALIAS_BASE_DEF(name, from, base) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_ALIAS, 0, { .alias = { from, base } } }
  7910. JS_EXTERN void JS_SetPropertyFunctionList(JSContext *ctx, JSValue obj,
  7911. const JSCFunctionListEntry *tab,
  7912. int len);
  7913. /* C module definition */
  7914. typedef int JSModuleInitFunc(JSContext *ctx, JSModuleDef *m);
  7915. JS_EXTERN JSModuleDef *JS_NewCModule(JSContext *ctx, const char *name_str,
  7916. JSModuleInitFunc *func);
  7917. /* can only be called before the module is instantiated */
  7918. JS_EXTERN int JS_AddModuleExport(JSContext *ctx, JSModuleDef *m, const char *name_str);
  7919. JS_EXTERN int JS_AddModuleExportList(JSContext *ctx, JSModuleDef *m,
  7920. const JSCFunctionListEntry *tab, int len);
  7921. /* can only be called after the module is instantiated */
  7922. JS_EXTERN int JS_SetModuleExport(JSContext *ctx, JSModuleDef *m, const char *export_name,
  7923. JSValue val);
  7924. JS_EXTERN int JS_SetModuleExportList(JSContext *ctx, JSModuleDef *m,
  7925. const JSCFunctionListEntry *tab, int len);
  7926. /* Version */
  7927. #define QJS_VERSION_MAJOR 0
  7928. #define QJS_VERSION_MINOR 9
  7929. #define QJS_VERSION_PATCH 0
  7930. #define QJS_VERSION_SUFFIX ""
  7931. JS_EXTERN const char* JS_GetVersion(void);
  7932. /* Integration point for quickjs-libc.c, not for public use. */
  7933. JS_EXTERN uintptr_t js_std_cmd(int cmd, ...);
  7934. #undef JS_EXTERN
  7935. #undef js_force_inline
  7936. #ifdef __cplusplus
  7937. } /* extern "C" { */
  7938. #endif
  7939. #endif /* QUICKJS_H */
  7940. /*
  7941. * QuickJS Javascript Engine
  7942. *
  7943. * Copyright (c) 2017-2024 Fabrice Bellard
  7944. * Copyright (c) 2017-2024 Charlie Gordon
  7945. * Copyright (c) 2023-2025 Ben Noordhuis
  7946. * Copyright (c) 2023-2025 Saúl Ibarra Corretgé
  7947. *
  7948. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7949. * of this software and associated documentation files (the "Software"), to deal
  7950. * in the Software without restriction, including without limitation the rights
  7951. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7952. * copies of the Software, and to permit persons to whom the Software is
  7953. * furnished to do so, subject to the following conditions:
  7954. *
  7955. * The above copyright notice and this permission notice shall be included in
  7956. * all copies or substantial portions of the Software.
  7957. *
  7958. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  7959. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  7960. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  7961. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  7962. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  7963. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  7964. * THE SOFTWARE.
  7965. */
  7966. #include <stdlib.h>
  7967. #include <stdio.h>
  7968. #include <stdarg.h>
  7969. #include <inttypes.h>
  7970. #include <string.h>
  7971. #include <assert.h>
  7972. #if !defined(_MSC_VER)
  7973. #include <sys/time.h>
  7974. #if defined(_WIN32)
  7975. #include <timezoneapi.h>
  7976. #endif
  7977. #endif
  7978. #if defined(_WIN32)
  7979. #include <intrin.h>
  7980. #endif
  7981. #include <time.h>
  7982. #include <fenv.h>
  7983. #include <math.h>
  7984. #if defined(EMSCRIPTEN) || defined(_MSC_VER)
  7985. #define DIRECT_DISPATCH 0
  7986. #else
  7987. #define DIRECT_DISPATCH 1
  7988. #endif
  7989. #if defined(__APPLE__)
  7990. #define MALLOC_OVERHEAD 0
  7991. #else
  7992. #define MALLOC_OVERHEAD 8
  7993. #endif
  7994. #if defined(__NEWLIB__)
  7995. #define NO_TM_GMTOFF
  7996. #endif
  7997. // atomic_store etc. are completely busted in recent versions of tcc;
  7998. // somehow the compiler forgets to load |ptr| into %rdi when calling
  7999. // the __atomic_*() helpers in its lib/stdatomic.c and lib/atomic.S
  8000. #if !defined(__TINYC__) && !defined(EMSCRIPTEN) && !defined(__wasi__) && !__STDC_NO_ATOMICS__
  8001. #define CONFIG_ATOMICS
  8002. #endif
  8003. #ifndef __GNUC__
  8004. #define __extension__
  8005. #endif
  8006. #ifndef NDEBUG
  8007. #define ENABLE_DUMPS
  8008. #endif
  8009. //#define FORCE_GC_AT_MALLOC /* test the GC by forcing it before each object allocation */
  8010. #define check_dump_flag(rt, flag) ((rt->dump_flags & (flag +0)) == (flag +0))
  8011. #define STRINGIFY_(x) #x
  8012. #define STRINGIFY(x) STRINGIFY_(x)
  8013. #define QJS_VERSION_STRING \
  8014. STRINGIFY(QJS_VERSION_MAJOR) "." STRINGIFY(QJS_VERSION_MINOR) "." STRINGIFY(QJS_VERSION_PATCH) QJS_VERSION_SUFFIX
  8015. const char* JS_GetVersion(void) {
  8016. return QJS_VERSION_STRING;
  8017. }
  8018. #undef STRINFIGY_
  8019. #undef STRINGIFY
  8020. static inline JSValueConst *vc(JSValue *vals)
  8021. {
  8022. return (JSValueConst *)vals;
  8023. }
  8024. static inline JSValue unsafe_unconst(JSValueConst v)
  8025. {
  8026. #ifdef JS_CHECK_JSVALUE
  8027. return (JSValue)v;
  8028. #else
  8029. return v;
  8030. #endif
  8031. }
  8032. static inline JSValueConst safe_const(JSValue v)
  8033. {
  8034. #ifdef JS_CHECK_JSVALUE
  8035. return (JSValueConst)v;
  8036. #else
  8037. return v;
  8038. #endif
  8039. }
  8040. enum {
  8041. /* classid tag */ /* union usage | properties */
  8042. JS_CLASS_OBJECT = 1, /* must be first */
  8043. JS_CLASS_ARRAY, /* u.array | length */
  8044. JS_CLASS_ERROR,
  8045. JS_CLASS_NUMBER, /* u.object_data */
  8046. JS_CLASS_STRING, /* u.object_data */
  8047. JS_CLASS_BOOLEAN, /* u.object_data */
  8048. JS_CLASS_SYMBOL, /* u.object_data */
  8049. JS_CLASS_ARGUMENTS, /* u.array | length */
  8050. JS_CLASS_MAPPED_ARGUMENTS, /* | length */
  8051. JS_CLASS_DATE, /* u.object_data */
  8052. JS_CLASS_MODULE_NS,
  8053. JS_CLASS_C_FUNCTION, /* u.cfunc */
  8054. JS_CLASS_BYTECODE_FUNCTION, /* u.func */
  8055. JS_CLASS_BOUND_FUNCTION, /* u.bound_function */
  8056. JS_CLASS_C_FUNCTION_DATA, /* u.c_function_data_record */
  8057. JS_CLASS_GENERATOR_FUNCTION, /* u.func */
  8058. JS_CLASS_FOR_IN_ITERATOR, /* u.for_in_iterator */
  8059. JS_CLASS_REGEXP, /* u.regexp */
  8060. JS_CLASS_ARRAY_BUFFER, /* u.array_buffer */
  8061. JS_CLASS_SHARED_ARRAY_BUFFER, /* u.array_buffer */
  8062. JS_CLASS_UINT8C_ARRAY, /* u.array (typed_array) */
  8063. JS_CLASS_INT8_ARRAY, /* u.array (typed_array) */
  8064. JS_CLASS_UINT8_ARRAY, /* u.array (typed_array) */
  8065. JS_CLASS_INT16_ARRAY, /* u.array (typed_array) */
  8066. JS_CLASS_UINT16_ARRAY, /* u.array (typed_array) */
  8067. JS_CLASS_INT32_ARRAY, /* u.array (typed_array) */
  8068. JS_CLASS_UINT32_ARRAY, /* u.array (typed_array) */
  8069. JS_CLASS_BIG_INT64_ARRAY, /* u.array (typed_array) */
  8070. JS_CLASS_BIG_UINT64_ARRAY, /* u.array (typed_array) */
  8071. JS_CLASS_FLOAT16_ARRAY, /* u.array (typed_array) */
  8072. JS_CLASS_FLOAT32_ARRAY, /* u.array (typed_array) */
  8073. JS_CLASS_FLOAT64_ARRAY, /* u.array (typed_array) */
  8074. JS_CLASS_DATAVIEW, /* u.typed_array */
  8075. JS_CLASS_BIG_INT, /* u.object_data */
  8076. JS_CLASS_MAP, /* u.map_state */
  8077. JS_CLASS_SET, /* u.map_state */
  8078. JS_CLASS_WEAKMAP, /* u.map_state */
  8079. JS_CLASS_WEAKSET, /* u.map_state */
  8080. JS_CLASS_ITERATOR,
  8081. JS_CLASS_ITERATOR_HELPER, /* u.iterator_helper_data */
  8082. JS_CLASS_ITERATOR_WRAP, /* u.iterator_wrap_data */
  8083. JS_CLASS_MAP_ITERATOR, /* u.map_iterator_data */
  8084. JS_CLASS_SET_ITERATOR, /* u.map_iterator_data */
  8085. JS_CLASS_ARRAY_ITERATOR, /* u.array_iterator_data */
  8086. JS_CLASS_STRING_ITERATOR, /* u.array_iterator_data */
  8087. JS_CLASS_REGEXP_STRING_ITERATOR, /* u.regexp_string_iterator_data */
  8088. JS_CLASS_GENERATOR, /* u.generator_data */
  8089. JS_CLASS_PROXY, /* u.proxy_data */
  8090. JS_CLASS_PROMISE, /* u.promise_data */
  8091. JS_CLASS_PROMISE_RESOLVE_FUNCTION, /* u.promise_function_data */
  8092. JS_CLASS_PROMISE_REJECT_FUNCTION, /* u.promise_function_data */
  8093. JS_CLASS_ASYNC_FUNCTION, /* u.func */
  8094. JS_CLASS_ASYNC_FUNCTION_RESOLVE, /* u.async_function_data */
  8095. JS_CLASS_ASYNC_FUNCTION_REJECT, /* u.async_function_data */
  8096. JS_CLASS_ASYNC_FROM_SYNC_ITERATOR, /* u.async_from_sync_iterator_data */
  8097. JS_CLASS_ASYNC_GENERATOR_FUNCTION, /* u.func */
  8098. JS_CLASS_ASYNC_GENERATOR, /* u.async_generator_data */
  8099. JS_CLASS_WEAK_REF,
  8100. JS_CLASS_FINALIZATION_REGISTRY,
  8101. JS_CLASS_CALL_SITE,
  8102. JS_CLASS_INIT_COUNT, /* last entry for predefined classes */
  8103. };
  8104. /* number of typed array types */
  8105. #define JS_TYPED_ARRAY_COUNT (JS_CLASS_FLOAT64_ARRAY - JS_CLASS_UINT8C_ARRAY + 1)
  8106. static uint8_t const typed_array_size_log2[JS_TYPED_ARRAY_COUNT];
  8107. #define typed_array_size_log2(classid) (typed_array_size_log2[(classid)- JS_CLASS_UINT8C_ARRAY])
  8108. typedef enum JSErrorEnum {
  8109. JS_EVAL_ERROR,
  8110. JS_RANGE_ERROR,
  8111. JS_REFERENCE_ERROR,
  8112. JS_SYNTAX_ERROR,
  8113. JS_TYPE_ERROR,
  8114. JS_URI_ERROR,
  8115. JS_INTERNAL_ERROR,
  8116. JS_AGGREGATE_ERROR,
  8117. JS_NATIVE_ERROR_COUNT, /* number of different NativeError objects */
  8118. JS_PLAIN_ERROR = JS_NATIVE_ERROR_COUNT
  8119. } JSErrorEnum;
  8120. #define JS_MAX_LOCAL_VARS 65535
  8121. #define JS_STACK_SIZE_MAX 65534
  8122. #define JS_STRING_LEN_MAX ((1 << 30) - 1)
  8123. #define __exception __attribute__((warn_unused_result))
  8124. typedef struct JSShape JSShape;
  8125. typedef struct JSString JSString;
  8126. typedef struct JSString JSAtomStruct;
  8127. #define JS_VALUE_GET_STRING(v) ((JSString *)JS_VALUE_GET_PTR(v))
  8128. typedef enum {
  8129. JS_GC_PHASE_NONE,
  8130. JS_GC_PHASE_DECREF,
  8131. JS_GC_PHASE_REMOVE_CYCLES,
  8132. } JSGCPhaseEnum;
  8133. typedef struct JSMallocState {
  8134. size_t malloc_count;
  8135. size_t malloc_size;
  8136. size_t malloc_limit;
  8137. void *opaque; /* user opaque */
  8138. } JSMallocState;
  8139. typedef struct JSRuntimeFinalizerState {
  8140. struct JSRuntimeFinalizerState *next;
  8141. JSRuntimeFinalizer *finalizer;
  8142. void *arg;
  8143. } JSRuntimeFinalizerState;
  8144. struct JSRuntime {
  8145. JSMallocFunctions mf;
  8146. JSMallocState malloc_state;
  8147. const char *rt_info;
  8148. int atom_hash_size; /* power of two */
  8149. int atom_count;
  8150. int atom_size;
  8151. int atom_count_resize; /* resize hash table at this count */
  8152. uint32_t *atom_hash;
  8153. JSAtomStruct **atom_array;
  8154. int atom_free_index; /* 0 = none */
  8155. JSClassID js_class_id_alloc; /* counter for user defined classes */
  8156. int class_count; /* size of class_array */
  8157. JSClass *class_array;
  8158. struct list_head context_list; /* list of JSContext.link */
  8159. /* list of JSGCObjectHeader.link. List of allocated GC objects (used
  8160. by the garbage collector) */
  8161. struct list_head gc_obj_list;
  8162. /* list of JSGCObjectHeader.link. Used during JS_FreeValueRT() */
  8163. struct list_head gc_zero_ref_count_list;
  8164. struct list_head tmp_obj_list; /* used during GC */
  8165. JSGCPhaseEnum gc_phase : 8;
  8166. size_t malloc_gc_threshold;
  8167. #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS
  8168. struct list_head string_list; /* list of JSString.link */
  8169. #endif
  8170. /* stack limitation */
  8171. uintptr_t stack_size; /* in bytes, 0 if no limit */
  8172. uintptr_t stack_top;
  8173. uintptr_t stack_limit; /* lower stack limit */
  8174. JSValue current_exception;
  8175. /* true if inside an out of memory error, to avoid recursing */
  8176. bool in_out_of_memory;
  8177. /* true if inside build_backtrace, to avoid recursing */
  8178. bool in_build_stack_trace;
  8179. /* true if inside JS_FreeRuntime */
  8180. bool in_free;
  8181. struct JSStackFrame *current_stack_frame;
  8182. JSInterruptHandler *interrupt_handler;
  8183. void *interrupt_opaque;
  8184. JSHostPromiseRejectionTracker *host_promise_rejection_tracker;
  8185. void *host_promise_rejection_tracker_opaque;
  8186. struct list_head job_list; /* list of JSJobEntry.link */
  8187. JSModuleNormalizeFunc *module_normalize_func;
  8188. JSModuleLoaderFunc *module_loader_func;
  8189. void *module_loader_opaque;
  8190. /* timestamp for internal use in module evaluation */
  8191. int64_t module_async_evaluation_next_timestamp;
  8192. /* used to allocate, free and clone SharedArrayBuffers */
  8193. JSSharedArrayBufferFunctions sab_funcs;
  8194. bool can_block; /* true if Atomics.wait can block */
  8195. uint32_t dump_flags : 24;
  8196. /* Shape hash table */
  8197. int shape_hash_bits;
  8198. int shape_hash_size;
  8199. int shape_hash_count; /* number of hashed shapes */
  8200. JSShape **shape_hash;
  8201. bf_context_t bf_ctx;
  8202. void *user_opaque;
  8203. void *libc_opaque;
  8204. JSRuntimeFinalizerState *finalizers;
  8205. };
  8206. struct JSClass {
  8207. uint32_t class_id; /* 0 means free entry */
  8208. JSAtom class_name;
  8209. JSClassFinalizer *finalizer;
  8210. JSClassGCMark *gc_mark;
  8211. JSClassCall *call;
  8212. /* pointers for exotic behavior, can be NULL if none are present */
  8213. const JSClassExoticMethods *exotic;
  8214. };
  8215. typedef struct JSStackFrame {
  8216. struct JSStackFrame *prev_frame; /* NULL if first stack frame */
  8217. JSValue cur_func; /* current function, JS_UNDEFINED if the frame is detached */
  8218. JSValue *arg_buf; /* arguments */
  8219. JSValue *var_buf; /* variables */
  8220. struct list_head var_ref_list; /* list of JSVarRef.link */
  8221. uint8_t *cur_pc; /* only used in bytecode functions : PC of the
  8222. instruction after the call */
  8223. uint32_t arg_count : 31;
  8224. uint32_t is_strict_mode : 1;
  8225. /* only used in generators. Current stack pointer value. NULL if
  8226. the function is running. */
  8227. JSValue *cur_sp;
  8228. } JSStackFrame;
  8229. typedef enum {
  8230. JS_GC_OBJ_TYPE_JS_OBJECT,
  8231. JS_GC_OBJ_TYPE_FUNCTION_BYTECODE,
  8232. JS_GC_OBJ_TYPE_SHAPE,
  8233. JS_GC_OBJ_TYPE_VAR_REF,
  8234. JS_GC_OBJ_TYPE_ASYNC_FUNCTION,
  8235. JS_GC_OBJ_TYPE_JS_CONTEXT,
  8236. } JSGCObjectTypeEnum;
  8237. /* header for GC objects. GC objects are C data structures with a
  8238. reference count that can reference other GC objects. JS Objects are
  8239. a particular type of GC object. */
  8240. struct JSGCObjectHeader {
  8241. int ref_count; /* must come first, 32-bit */
  8242. JSGCObjectTypeEnum gc_obj_type : 4;
  8243. uint8_t mark : 4; /* used by the GC */
  8244. uint8_t dummy1; /* not used by the GC */
  8245. uint16_t dummy2; /* not used by the GC */
  8246. struct list_head link;
  8247. };
  8248. typedef struct JSVarRef {
  8249. union {
  8250. JSGCObjectHeader header; /* must come first */
  8251. struct {
  8252. int __gc_ref_count; /* corresponds to header.ref_count */
  8253. uint8_t __gc_mark; /* corresponds to header.mark/gc_obj_type */
  8254. /* 0 : the JSVarRef is on the stack. header.link is an element
  8255. of JSStackFrame.var_ref_list.
  8256. 1 : the JSVarRef is detached. header.link has the normal meanning
  8257. */
  8258. uint8_t is_detached : 1;
  8259. uint8_t is_arg : 1;
  8260. uint16_t var_idx; /* index of the corresponding function variable on
  8261. the stack */
  8262. };
  8263. };
  8264. JSValue *pvalue; /* pointer to the value, either on the stack or
  8265. to 'value' */
  8266. JSValue value; /* used when the variable is no longer on the stack */
  8267. } JSVarRef;
  8268. typedef struct JSRefCountHeader {
  8269. int ref_count;
  8270. } JSRefCountHeader;
  8271. /* the same structure is used for big integers.
  8272. Big integers are never infinite or NaNs */
  8273. typedef struct JSBigInt {
  8274. JSRefCountHeader header; /* must come first, 32-bit */
  8275. bf_t num;
  8276. } JSBigInt;
  8277. typedef enum {
  8278. JS_AUTOINIT_ID_PROTOTYPE,
  8279. JS_AUTOINIT_ID_MODULE_NS,
  8280. JS_AUTOINIT_ID_PROP,
  8281. } JSAutoInitIDEnum;
  8282. /* must be large enough to have a negligible runtime cost and small
  8283. enough to call the interrupt callback often. */
  8284. #define JS_INTERRUPT_COUNTER_INIT 10000
  8285. struct JSContext {
  8286. JSGCObjectHeader header; /* must come first */
  8287. JSRuntime *rt;
  8288. struct list_head link;
  8289. uint16_t binary_object_count;
  8290. int binary_object_size;
  8291. JSShape *array_shape; /* initial shape for Array objects */
  8292. JSValue *class_proto;
  8293. JSValue function_proto;
  8294. JSValue function_ctor;
  8295. JSValue array_ctor;
  8296. JSValue regexp_ctor;
  8297. JSValue promise_ctor;
  8298. JSValue native_error_proto[JS_NATIVE_ERROR_COUNT];
  8299. JSValue error_ctor;
  8300. JSValue error_back_trace;
  8301. JSValue error_prepare_stack;
  8302. JSValue error_stack_trace_limit;
  8303. JSValue iterator_ctor;
  8304. JSValue iterator_proto;
  8305. JSValue async_iterator_proto;
  8306. JSValue array_proto_values;
  8307. JSValue throw_type_error;
  8308. JSValue eval_obj;
  8309. JSValue global_obj; /* global object */
  8310. JSValue global_var_obj; /* contains the global let/const definitions */
  8311. double time_origin;
  8312. uint64_t random_state;
  8313. bf_context_t *bf_ctx; /* points to rt->bf_ctx, shared by all contexts */
  8314. /* when the counter reaches zero, JSRutime.interrupt_handler is called */
  8315. int interrupt_counter;
  8316. struct list_head loaded_modules; /* list of JSModuleDef.link */
  8317. /* if NULL, RegExp compilation is not supported */
  8318. JSValue (*compile_regexp)(JSContext *ctx, JSValueConst pattern,
  8319. JSValueConst flags);
  8320. /* if NULL, eval is not supported */
  8321. JSValue (*eval_internal)(JSContext *ctx, JSValueConst this_obj,
  8322. const char *input, size_t input_len,
  8323. const char *filename, int line, int flags, int scope_idx);
  8324. void *user_opaque;
  8325. };
  8326. typedef union JSFloat64Union {
  8327. double d;
  8328. uint64_t u64;
  8329. uint32_t u32[2];
  8330. } JSFloat64Union;
  8331. typedef enum {
  8332. JS_WEAK_REF_KIND_MAP,
  8333. JS_WEAK_REF_KIND_WEAK_REF,
  8334. JS_WEAK_REF_KIND_FINALIZATION_REGISTRY_ENTRY,
  8335. } JSWeakRefKindEnum;
  8336. typedef struct JSWeakRefRecord {
  8337. JSWeakRefKindEnum kind;
  8338. struct JSWeakRefRecord *next_weak_ref;
  8339. union {
  8340. struct JSMapRecord *map_record;
  8341. struct JSWeakRefData *weak_ref_data;
  8342. struct JSFinRecEntry *fin_rec_entry;
  8343. } u;
  8344. } JSWeakRefRecord;
  8345. enum {
  8346. JS_ATOM_TYPE_STRING = 1,
  8347. JS_ATOM_TYPE_GLOBAL_SYMBOL,
  8348. JS_ATOM_TYPE_SYMBOL,
  8349. JS_ATOM_TYPE_PRIVATE,
  8350. };
  8351. enum {
  8352. JS_ATOM_HASH_SYMBOL,
  8353. JS_ATOM_HASH_PRIVATE,
  8354. };
  8355. typedef enum {
  8356. JS_ATOM_KIND_STRING,
  8357. JS_ATOM_KIND_SYMBOL,
  8358. JS_ATOM_KIND_PRIVATE,
  8359. } JSAtomKindEnum;
  8360. #define JS_ATOM_HASH_MASK ((1 << 30) - 1)
  8361. struct JSString {
  8362. JSRefCountHeader header; /* must come first, 32-bit */
  8363. uint32_t len : 31;
  8364. uint8_t is_wide_char : 1; /* 0 = 8 bits, 1 = 16 bits characters */
  8365. /* for JS_ATOM_TYPE_SYMBOL: hash = 0, atom_type = 3,
  8366. for JS_ATOM_TYPE_PRIVATE: hash = 1, atom_type = 3
  8367. XXX: could change encoding to have one more bit in hash */
  8368. uint32_t hash : 30;
  8369. uint8_t atom_type : 2; /* != 0 if atom, JS_ATOM_TYPE_x */
  8370. uint32_t hash_next; /* atom_index for JS_ATOM_TYPE_SYMBOL */
  8371. JSWeakRefRecord *first_weak_ref;
  8372. #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS
  8373. struct list_head link; /* string list */
  8374. #endif
  8375. };
  8376. static inline uint8_t *str8(JSString *p)
  8377. {
  8378. return (void *)(p + 1);
  8379. }
  8380. static inline uint16_t *str16(JSString *p)
  8381. {
  8382. return (void *)(p + 1);
  8383. }
  8384. typedef struct JSClosureVar {
  8385. uint8_t is_local : 1;
  8386. uint8_t is_arg : 1;
  8387. uint8_t is_const : 1;
  8388. uint8_t is_lexical : 1;
  8389. uint8_t var_kind : 4; /* see JSVarKindEnum */
  8390. /* 8 bits available */
  8391. uint16_t var_idx; /* is_local = true: index to a normal variable of the
  8392. parent function. otherwise: index to a closure
  8393. variable of the parent function */
  8394. JSAtom var_name;
  8395. } JSClosureVar;
  8396. #define ARG_SCOPE_INDEX 1
  8397. #define ARG_SCOPE_END (-2)
  8398. typedef struct JSVarScope {
  8399. int parent; /* index into fd->scopes of the enclosing scope */
  8400. int first; /* index into fd->vars of the last variable in this scope */
  8401. } JSVarScope;
  8402. typedef enum {
  8403. /* XXX: add more variable kinds here instead of using bit fields */
  8404. JS_VAR_NORMAL,
  8405. JS_VAR_FUNCTION_DECL, /* lexical var with function declaration */
  8406. JS_VAR_NEW_FUNCTION_DECL, /* lexical var with async/generator
  8407. function declaration */
  8408. JS_VAR_CATCH,
  8409. JS_VAR_FUNCTION_NAME, /* function expression name */
  8410. JS_VAR_PRIVATE_FIELD,
  8411. JS_VAR_PRIVATE_METHOD,
  8412. JS_VAR_PRIVATE_GETTER,
  8413. JS_VAR_PRIVATE_SETTER, /* must come after JS_VAR_PRIVATE_GETTER */
  8414. JS_VAR_PRIVATE_GETTER_SETTER, /* must come after JS_VAR_PRIVATE_SETTER */
  8415. } JSVarKindEnum;
  8416. /* XXX: could use a different structure in bytecode functions to save
  8417. memory */
  8418. typedef struct JSVarDef {
  8419. JSAtom var_name;
  8420. /* index into fd->scopes of this variable lexical scope */
  8421. int scope_level;
  8422. /* during compilation:
  8423. - if scope_level = 0: scope in which the variable is defined
  8424. - if scope_level != 0: index into fd->vars of the next
  8425. variable in the same or enclosing lexical scope
  8426. in a bytecode function:
  8427. index into fd->vars of the next
  8428. variable in the same or enclosing lexical scope
  8429. */
  8430. int scope_next;
  8431. uint8_t is_const : 1;
  8432. uint8_t is_lexical : 1;
  8433. uint8_t is_captured : 1;
  8434. uint8_t is_static_private : 1; /* only used during private class field parsing */
  8435. uint8_t var_kind : 4; /* see JSVarKindEnum */
  8436. /* only used during compilation: function pool index for lexical
  8437. variables with var_kind =
  8438. JS_VAR_FUNCTION_DECL/JS_VAR_NEW_FUNCTION_DECL or scope level of
  8439. the definition of the 'var' variables (they have scope_level =
  8440. 0) */
  8441. int func_pool_idx : 24; /* only used during compilation : index in
  8442. the constant pool for hoisted function
  8443. definition */
  8444. } JSVarDef;
  8445. /* for the encoding of the pc2line table */
  8446. #define PC2LINE_BASE (-1)
  8447. #define PC2LINE_RANGE 5
  8448. #define PC2LINE_OP_FIRST 1
  8449. #define PC2LINE_DIFF_PC_MAX ((255 - PC2LINE_OP_FIRST) / PC2LINE_RANGE)
  8450. typedef enum JSFunctionKindEnum {
  8451. JS_FUNC_NORMAL = 0,
  8452. JS_FUNC_GENERATOR = (1 << 0),
  8453. JS_FUNC_ASYNC = (1 << 1),
  8454. JS_FUNC_ASYNC_GENERATOR = (JS_FUNC_GENERATOR | JS_FUNC_ASYNC),
  8455. } JSFunctionKindEnum;
  8456. typedef struct JSFunctionBytecode {
  8457. JSGCObjectHeader header; /* must come first */
  8458. uint8_t is_strict_mode : 1;
  8459. uint8_t has_prototype : 1; /* true if a prototype field is necessary */
  8460. uint8_t has_simple_parameter_list : 1;
  8461. uint8_t is_derived_class_constructor : 1;
  8462. /* true if home_object needs to be initialized */
  8463. uint8_t need_home_object : 1;
  8464. uint8_t func_kind : 2;
  8465. uint8_t new_target_allowed : 1;
  8466. uint8_t super_call_allowed : 1;
  8467. uint8_t super_allowed : 1;
  8468. uint8_t arguments_allowed : 1;
  8469. uint8_t backtrace_barrier : 1; /* stop backtrace on this function */
  8470. /* XXX: 5 bits available */
  8471. uint8_t *byte_code_buf; /* (self pointer) */
  8472. int byte_code_len;
  8473. JSAtom func_name;
  8474. JSVarDef *vardefs; /* arguments + local variables (arg_count + var_count) (self pointer) */
  8475. JSClosureVar *closure_var; /* list of variables in the closure (self pointer) */
  8476. uint16_t arg_count;
  8477. uint16_t var_count;
  8478. uint16_t defined_arg_count; /* for length function property */
  8479. uint16_t stack_size; /* maximum stack size */
  8480. JSContext *realm; /* function realm */
  8481. JSValue *cpool; /* constant pool (self pointer) */
  8482. int cpool_count;
  8483. int closure_var_count;
  8484. JSAtom filename;
  8485. int line_num;
  8486. int col_num;
  8487. int source_len;
  8488. int pc2line_len;
  8489. uint8_t *pc2line_buf;
  8490. char *source;
  8491. } JSFunctionBytecode;
  8492. typedef struct JSBoundFunction {
  8493. JSValue func_obj;
  8494. JSValue this_val;
  8495. int argc;
  8496. JSValue argv[];
  8497. } JSBoundFunction;
  8498. typedef enum JSIteratorKindEnum {
  8499. JS_ITERATOR_KIND_KEY,
  8500. JS_ITERATOR_KIND_VALUE,
  8501. JS_ITERATOR_KIND_KEY_AND_VALUE,
  8502. } JSIteratorKindEnum;
  8503. typedef enum JSIteratorHelperKindEnum {
  8504. JS_ITERATOR_HELPER_KIND_DROP,
  8505. JS_ITERATOR_HELPER_KIND_EVERY,
  8506. JS_ITERATOR_HELPER_KIND_FILTER,
  8507. JS_ITERATOR_HELPER_KIND_FIND,
  8508. JS_ITERATOR_HELPER_KIND_FLAT_MAP,
  8509. JS_ITERATOR_HELPER_KIND_FOR_EACH,
  8510. JS_ITERATOR_HELPER_KIND_MAP,
  8511. JS_ITERATOR_HELPER_KIND_SOME,
  8512. JS_ITERATOR_HELPER_KIND_TAKE,
  8513. } JSIteratorHelperKindEnum;
  8514. typedef struct JSForInIterator {
  8515. JSValue obj;
  8516. bool is_array;
  8517. uint32_t array_length;
  8518. uint32_t idx;
  8519. } JSForInIterator;
  8520. typedef struct JSRegExp {
  8521. JSString *pattern;
  8522. JSString *bytecode; /* also contains the flags */
  8523. } JSRegExp;
  8524. typedef struct JSProxyData {
  8525. JSValue target;
  8526. JSValue handler;
  8527. uint8_t is_func;
  8528. uint8_t is_revoked;
  8529. } JSProxyData;
  8530. typedef struct JSArrayBuffer {
  8531. int byte_length; /* 0 if detached */
  8532. int max_byte_length; /* -1 if not resizable; >= byte_length otherwise */
  8533. uint8_t detached;
  8534. uint8_t shared; /* if shared, the array buffer cannot be detached */
  8535. uint8_t *data; /* NULL if detached */
  8536. struct list_head array_list;
  8537. void *opaque;
  8538. JSFreeArrayBufferDataFunc *free_func;
  8539. } JSArrayBuffer;
  8540. typedef struct JSTypedArray {
  8541. struct list_head link; /* link to arraybuffer */
  8542. JSObject *obj; /* back pointer to the TypedArray/DataView object */
  8543. JSObject *buffer; /* based array buffer */
  8544. uint32_t offset; /* byte offset in the array buffer */
  8545. uint32_t length; /* byte length in the array buffer */
  8546. bool track_rab; /* auto-track length of backing array buffer */
  8547. } JSTypedArray;
  8548. typedef struct JSAsyncFunctionState {
  8549. JSValue this_val; /* 'this' generator argument */
  8550. int argc; /* number of function arguments */
  8551. bool throw_flag; /* used to throw an exception in JS_CallInternal() */
  8552. JSStackFrame frame;
  8553. } JSAsyncFunctionState;
  8554. /* XXX: could use an object instead to avoid the
  8555. JS_TAG_ASYNC_FUNCTION tag for the GC */
  8556. typedef struct JSAsyncFunctionData {
  8557. JSGCObjectHeader header; /* must come first */
  8558. JSValue resolving_funcs[2];
  8559. bool is_active; /* true if the async function state is valid */
  8560. JSAsyncFunctionState func_state;
  8561. } JSAsyncFunctionData;
  8562. typedef struct JSReqModuleEntry {
  8563. JSAtom module_name;
  8564. JSModuleDef *module; /* used using resolution */
  8565. } JSReqModuleEntry;
  8566. typedef enum JSExportTypeEnum {
  8567. JS_EXPORT_TYPE_LOCAL,
  8568. JS_EXPORT_TYPE_INDIRECT,
  8569. } JSExportTypeEnum;
  8570. typedef struct JSExportEntry {
  8571. union {
  8572. struct {
  8573. int var_idx; /* closure variable index */
  8574. JSVarRef *var_ref; /* if != NULL, reference to the variable */
  8575. } local; /* for local export */
  8576. int req_module_idx; /* module for indirect export */
  8577. } u;
  8578. JSExportTypeEnum export_type;
  8579. JSAtom local_name; /* '*' if export ns from. not used for local
  8580. export after compilation */
  8581. JSAtom export_name; /* exported variable name */
  8582. } JSExportEntry;
  8583. typedef struct JSStarExportEntry {
  8584. int req_module_idx; /* in req_module_entries */
  8585. } JSStarExportEntry;
  8586. typedef struct JSImportEntry {
  8587. int var_idx; /* closure variable index */
  8588. JSAtom import_name;
  8589. int req_module_idx; /* in req_module_entries */
  8590. } JSImportEntry;
  8591. typedef enum {
  8592. JS_MODULE_STATUS_UNLINKED,
  8593. JS_MODULE_STATUS_LINKING,
  8594. JS_MODULE_STATUS_LINKED,
  8595. JS_MODULE_STATUS_EVALUATING,
  8596. JS_MODULE_STATUS_EVALUATING_ASYNC,
  8597. JS_MODULE_STATUS_EVALUATED,
  8598. } JSModuleStatus;
  8599. struct JSModuleDef {
  8600. JSRefCountHeader header; /* must come first, 32-bit */
  8601. JSAtom module_name;
  8602. struct list_head link;
  8603. JSReqModuleEntry *req_module_entries;
  8604. int req_module_entries_count;
  8605. int req_module_entries_size;
  8606. JSExportEntry *export_entries;
  8607. int export_entries_count;
  8608. int export_entries_size;
  8609. JSStarExportEntry *star_export_entries;
  8610. int star_export_entries_count;
  8611. int star_export_entries_size;
  8612. JSImportEntry *import_entries;
  8613. int import_entries_count;
  8614. int import_entries_size;
  8615. JSValue module_ns;
  8616. JSValue func_obj; /* only used for JS modules */
  8617. JSModuleInitFunc *init_func; /* only used for C modules */
  8618. bool has_tla; /* true if func_obj contains await */
  8619. bool resolved;
  8620. bool func_created;
  8621. JSModuleStatus status : 8;
  8622. /* temp use during js_module_link() & js_module_evaluate() */
  8623. int dfs_index, dfs_ancestor_index;
  8624. JSModuleDef *stack_prev;
  8625. /* temp use during js_module_evaluate() */
  8626. JSModuleDef **async_parent_modules;
  8627. int async_parent_modules_count;
  8628. int async_parent_modules_size;
  8629. int pending_async_dependencies;
  8630. bool async_evaluation;
  8631. int64_t async_evaluation_timestamp;
  8632. JSModuleDef *cycle_root;
  8633. JSValue promise; /* corresponds to spec field: capability */
  8634. JSValue resolving_funcs[2]; /* corresponds to spec field: capability */
  8635. /* true if evaluation yielded an exception. It is saved in
  8636. eval_exception */
  8637. bool eval_has_exception;
  8638. JSValue eval_exception;
  8639. JSValue meta_obj; /* for import.meta */
  8640. };
  8641. typedef struct JSJobEntry {
  8642. struct list_head link;
  8643. JSContext *ctx;
  8644. JSJobFunc *job_func;
  8645. int argc;
  8646. JSValue argv[];
  8647. } JSJobEntry;
  8648. typedef struct JSProperty {
  8649. union {
  8650. JSValue value; /* JS_PROP_NORMAL */
  8651. struct { /* JS_PROP_GETSET */
  8652. JSObject *getter; /* NULL if undefined */
  8653. JSObject *setter; /* NULL if undefined */
  8654. } getset;
  8655. JSVarRef *var_ref; /* JS_PROP_VARREF */
  8656. struct { /* JS_PROP_AUTOINIT */
  8657. /* in order to use only 2 pointers, we compress the realm
  8658. and the init function pointer */
  8659. uintptr_t realm_and_id; /* realm and init_id (JS_AUTOINIT_ID_x)
  8660. in the 2 low bits */
  8661. void *opaque;
  8662. } init;
  8663. } u;
  8664. } JSProperty;
  8665. #define JS_PROP_INITIAL_SIZE 2
  8666. #define JS_PROP_INITIAL_HASH_SIZE 4 /* must be a power of two */
  8667. #define JS_ARRAY_INITIAL_SIZE 2
  8668. typedef struct JSShapeProperty {
  8669. uint32_t hash_next : 26; /* 0 if last in list */
  8670. uint32_t flags : 6; /* JS_PROP_XXX */
  8671. JSAtom atom; /* JS_ATOM_NULL = free property entry */
  8672. } JSShapeProperty;
  8673. struct JSShape {
  8674. /* hash table of size hash_mask + 1 before the start of the
  8675. structure (see prop_hash_end()). */
  8676. JSGCObjectHeader header;
  8677. /* true if the shape is inserted in the shape hash table. If not,
  8678. JSShape.hash is not valid */
  8679. uint8_t is_hashed;
  8680. /* If true, the shape may have small array index properties 'n' with 0
  8681. <= n <= 2^31-1. If false, the shape is guaranteed not to have
  8682. small array index properties */
  8683. uint8_t has_small_array_index;
  8684. uint32_t hash; /* current hash value */
  8685. uint32_t prop_hash_mask;
  8686. int prop_size; /* allocated properties */
  8687. int prop_count; /* include deleted properties */
  8688. int deleted_prop_count;
  8689. JSShape *shape_hash_next; /* in JSRuntime.shape_hash[h] list */
  8690. JSObject *proto;
  8691. JSShapeProperty prop[]; /* prop_size elements */
  8692. };
  8693. struct JSObject {
  8694. union {
  8695. JSGCObjectHeader header;
  8696. struct {
  8697. int __gc_ref_count; /* corresponds to header.ref_count */
  8698. uint8_t __gc_mark; /* corresponds to header.mark/gc_obj_type */
  8699. uint8_t extensible : 1;
  8700. uint8_t free_mark : 1; /* only used when freeing objects with cycles */
  8701. uint8_t is_exotic : 1; /* true if object has exotic property handlers */
  8702. uint8_t fast_array : 1; /* true if u.array is used for get/put (for JS_CLASS_ARRAY, JS_CLASS_ARGUMENTS and typed arrays) */
  8703. uint8_t is_constructor : 1; /* true if object is a constructor function */
  8704. uint8_t is_uncatchable_error : 1; /* if true, error is not catchable */
  8705. uint8_t tmp_mark : 1; /* used in JS_WriteObjectRec() */
  8706. uint8_t is_HTMLDDA : 1; /* specific annex B IsHtmlDDA behavior */
  8707. uint16_t class_id; /* see JS_CLASS_x */
  8708. };
  8709. };
  8710. /* byte offsets: 16/24 */
  8711. JSShape *shape; /* prototype and property names + flag */
  8712. JSProperty *prop; /* array of properties */
  8713. /* byte offsets: 24/40 */
  8714. JSWeakRefRecord *first_weak_ref;
  8715. /* byte offsets: 28/48 */
  8716. union {
  8717. void *opaque;
  8718. struct JSBoundFunction *bound_function; /* JS_CLASS_BOUND_FUNCTION */
  8719. struct JSCFunctionDataRecord *c_function_data_record; /* JS_CLASS_C_FUNCTION_DATA */
  8720. struct JSForInIterator *for_in_iterator; /* JS_CLASS_FOR_IN_ITERATOR */
  8721. struct JSArrayBuffer *array_buffer; /* JS_CLASS_ARRAY_BUFFER, JS_CLASS_SHARED_ARRAY_BUFFER */
  8722. struct JSTypedArray *typed_array; /* JS_CLASS_UINT8C_ARRAY..JS_CLASS_DATAVIEW */
  8723. struct JSMapState *map_state; /* JS_CLASS_MAP..JS_CLASS_WEAKSET */
  8724. struct JSMapIteratorData *map_iterator_data; /* JS_CLASS_MAP_ITERATOR, JS_CLASS_SET_ITERATOR */
  8725. struct JSArrayIteratorData *array_iterator_data; /* JS_CLASS_ARRAY_ITERATOR, JS_CLASS_STRING_ITERATOR */
  8726. struct JSRegExpStringIteratorData *regexp_string_iterator_data; /* JS_CLASS_REGEXP_STRING_ITERATOR */
  8727. struct JSGeneratorData *generator_data; /* JS_CLASS_GENERATOR */
  8728. struct JSIteratorHelperData *iterator_helper_data; /* JS_CLASS_ITERATOR_HELPER */
  8729. struct JSIteratorWrapData *iterator_wrap_data; /* JS_CLASS_ITERATOR_WRAP */
  8730. struct JSProxyData *proxy_data; /* JS_CLASS_PROXY */
  8731. struct JSPromiseData *promise_data; /* JS_CLASS_PROMISE */
  8732. struct JSPromiseFunctionData *promise_function_data; /* JS_CLASS_PROMISE_RESOLVE_FUNCTION, JS_CLASS_PROMISE_REJECT_FUNCTION */
  8733. struct JSAsyncFunctionData *async_function_data; /* JS_CLASS_ASYNC_FUNCTION_RESOLVE, JS_CLASS_ASYNC_FUNCTION_REJECT */
  8734. struct JSAsyncFromSyncIteratorData *async_from_sync_iterator_data; /* JS_CLASS_ASYNC_FROM_SYNC_ITERATOR */
  8735. struct JSAsyncGeneratorData *async_generator_data; /* JS_CLASS_ASYNC_GENERATOR */
  8736. struct { /* JS_CLASS_BYTECODE_FUNCTION: 12/24 bytes */
  8737. /* also used by JS_CLASS_GENERATOR_FUNCTION, JS_CLASS_ASYNC_FUNCTION and JS_CLASS_ASYNC_GENERATOR_FUNCTION */
  8738. struct JSFunctionBytecode *function_bytecode;
  8739. JSVarRef **var_refs;
  8740. JSObject *home_object; /* for 'super' access */
  8741. } func;
  8742. struct { /* JS_CLASS_C_FUNCTION: 12/20 bytes */
  8743. JSContext *realm;
  8744. JSCFunctionType c_function;
  8745. uint8_t length;
  8746. uint8_t cproto;
  8747. int16_t magic;
  8748. } cfunc;
  8749. /* array part for fast arrays and typed arrays */
  8750. struct { /* JS_CLASS_ARRAY, JS_CLASS_ARGUMENTS, JS_CLASS_UINT8C_ARRAY..JS_CLASS_FLOAT64_ARRAY */
  8751. union {
  8752. uint32_t size; /* JS_CLASS_ARRAY, JS_CLASS_ARGUMENTS */
  8753. struct JSTypedArray *typed_array; /* JS_CLASS_UINT8C_ARRAY..JS_CLASS_FLOAT64_ARRAY */
  8754. } u1;
  8755. union {
  8756. JSValue *values; /* JS_CLASS_ARRAY, JS_CLASS_ARGUMENTS */
  8757. void *ptr; /* JS_CLASS_UINT8C_ARRAY..JS_CLASS_FLOAT64_ARRAY */
  8758. int8_t *int8_ptr; /* JS_CLASS_INT8_ARRAY */
  8759. uint8_t *uint8_ptr; /* JS_CLASS_UINT8_ARRAY, JS_CLASS_UINT8C_ARRAY */
  8760. int16_t *int16_ptr; /* JS_CLASS_INT16_ARRAY */
  8761. uint16_t *uint16_ptr; /* JS_CLASS_UINT16_ARRAY */
  8762. int32_t *int32_ptr; /* JS_CLASS_INT32_ARRAY */
  8763. uint32_t *uint32_ptr; /* JS_CLASS_UINT32_ARRAY */
  8764. int64_t *int64_ptr; /* JS_CLASS_INT64_ARRAY */
  8765. uint64_t *uint64_ptr; /* JS_CLASS_UINT64_ARRAY */
  8766. uint16_t *fp16_ptr; /* JS_CLASS_FLOAT16_ARRAY */
  8767. float *float_ptr; /* JS_CLASS_FLOAT32_ARRAY */
  8768. double *double_ptr; /* JS_CLASS_FLOAT64_ARRAY */
  8769. } u;
  8770. uint32_t count; /* <= 2^31-1. 0 for a detached typed array */
  8771. } array; /* 12/20 bytes */
  8772. JSRegExp regexp; /* JS_CLASS_REGEXP: 8/16 bytes */
  8773. JSValue object_data; /* for JS_SetObjectData(): 8/16/16 bytes */
  8774. } u;
  8775. /* byte sizes: 40/48/72 */
  8776. };
  8777. typedef struct JSCallSiteData {
  8778. JSValue filename;
  8779. JSValue func;
  8780. JSValue func_name;
  8781. bool native;
  8782. int line_num;
  8783. int col_num;
  8784. } JSCallSiteData;
  8785. enum {
  8786. __JS_ATOM_NULL = JS_ATOM_NULL,
  8787. #define DEF(name, str) JS_ATOM_ ## name,
  8788. /*
  8789. * QuickJS atom definitions
  8790. *
  8791. * Copyright (c) 2017-2018 Fabrice Bellard
  8792. * Copyright (c) 2017-2018 Charlie Gordon
  8793. *
  8794. * Permission is hereby granted, free of charge, to any person obtaining a copy
  8795. * of this software and associated documentation files (the "Software"), to deal
  8796. * in the Software without restriction, including without limitation the rights
  8797. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8798. * copies of the Software, and to permit persons to whom the Software is
  8799. * furnished to do so, subject to the following conditions:
  8800. *
  8801. * The above copyright notice and this permission notice shall be included in
  8802. * all copies or substantial portions of the Software.
  8803. *
  8804. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  8805. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  8806. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  8807. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  8808. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  8809. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  8810. * THE SOFTWARE.
  8811. */
  8812. #ifdef DEF
  8813. /* Note: first atoms are considered as keywords in the parser */
  8814. DEF(null, "null") /* must be first */
  8815. DEF(false, "false")
  8816. DEF(true, "true")
  8817. DEF(if, "if")
  8818. DEF(else, "else")
  8819. DEF(return, "return")
  8820. DEF(var, "var")
  8821. DEF(this, "this")
  8822. DEF(delete, "delete")
  8823. DEF(void, "void")
  8824. DEF(typeof, "typeof")
  8825. DEF(new, "new")
  8826. DEF(in, "in")
  8827. DEF(instanceof, "instanceof")
  8828. DEF(do, "do")
  8829. DEF(while, "while")
  8830. DEF(for, "for")
  8831. DEF(break, "break")
  8832. DEF(continue, "continue")
  8833. DEF(switch, "switch")
  8834. DEF(case, "case")
  8835. DEF(default, "default")
  8836. DEF(throw, "throw")
  8837. DEF(try, "try")
  8838. DEF(catch, "catch")
  8839. DEF(finally, "finally")
  8840. DEF(function, "function")
  8841. DEF(debugger, "debugger")
  8842. DEF(with, "with")
  8843. /* FutureReservedWord */
  8844. DEF(class, "class")
  8845. DEF(const, "const")
  8846. DEF(enum, "enum")
  8847. DEF(export, "export")
  8848. DEF(extends, "extends")
  8849. DEF(import, "import")
  8850. DEF(super, "super")
  8851. /* FutureReservedWords when parsing strict mode code */
  8852. DEF(implements, "implements")
  8853. DEF(interface, "interface")
  8854. DEF(let, "let")
  8855. DEF(package, "package")
  8856. DEF(private, "private")
  8857. DEF(protected, "protected")
  8858. DEF(public, "public")
  8859. DEF(static, "static")
  8860. DEF(yield, "yield")
  8861. DEF(await, "await")
  8862. /* empty string */
  8863. DEF(empty_string, "")
  8864. /* identifiers */
  8865. DEF(keys, "keys")
  8866. DEF(size, "size")
  8867. DEF(length, "length")
  8868. DEF(message, "message")
  8869. DEF(cause, "cause")
  8870. DEF(errors, "errors")
  8871. DEF(stack, "stack")
  8872. DEF(name, "name")
  8873. DEF(toString, "toString")
  8874. DEF(toLocaleString, "toLocaleString")
  8875. DEF(valueOf, "valueOf")
  8876. DEF(eval, "eval")
  8877. DEF(prototype, "prototype")
  8878. DEF(constructor, "constructor")
  8879. DEF(configurable, "configurable")
  8880. DEF(writable, "writable")
  8881. DEF(enumerable, "enumerable")
  8882. DEF(value, "value")
  8883. DEF(get, "get")
  8884. DEF(set, "set")
  8885. DEF(of, "of")
  8886. DEF(__proto__, "__proto__")
  8887. DEF(undefined, "undefined")
  8888. DEF(number, "number")
  8889. DEF(boolean, "boolean")
  8890. DEF(string, "string")
  8891. DEF(object, "object")
  8892. DEF(symbol, "symbol")
  8893. DEF(integer, "integer")
  8894. DEF(unknown, "unknown")
  8895. DEF(arguments, "arguments")
  8896. DEF(callee, "callee")
  8897. DEF(caller, "caller")
  8898. DEF(_eval_, "<eval>")
  8899. DEF(_ret_, "<ret>")
  8900. DEF(_var_, "<var>")
  8901. DEF(_arg_var_, "<arg_var>")
  8902. DEF(_with_, "<with>")
  8903. DEF(lastIndex, "lastIndex")
  8904. DEF(target, "target")
  8905. DEF(index, "index")
  8906. DEF(input, "input")
  8907. DEF(defineProperties, "defineProperties")
  8908. DEF(apply, "apply")
  8909. DEF(join, "join")
  8910. DEF(concat, "concat")
  8911. DEF(split, "split")
  8912. DEF(construct, "construct")
  8913. DEF(getPrototypeOf, "getPrototypeOf")
  8914. DEF(setPrototypeOf, "setPrototypeOf")
  8915. DEF(isExtensible, "isExtensible")
  8916. DEF(preventExtensions, "preventExtensions")
  8917. DEF(has, "has")
  8918. DEF(deleteProperty, "deleteProperty")
  8919. DEF(defineProperty, "defineProperty")
  8920. DEF(getOwnPropertyDescriptor, "getOwnPropertyDescriptor")
  8921. DEF(ownKeys, "ownKeys")
  8922. DEF(add, "add")
  8923. DEF(done, "done")
  8924. DEF(next, "next")
  8925. DEF(values, "values")
  8926. DEF(source, "source")
  8927. DEF(flags, "flags")
  8928. DEF(global, "global")
  8929. DEF(unicode, "unicode")
  8930. DEF(raw, "raw")
  8931. DEF(new_target, "new.target")
  8932. DEF(this_active_func, "this.active_func")
  8933. DEF(home_object, "<home_object>")
  8934. DEF(computed_field, "<computed_field>")
  8935. DEF(static_computed_field, "<static_computed_field>") /* must come after computed_fields */
  8936. DEF(class_fields_init, "<class_fields_init>")
  8937. DEF(brand, "<brand>")
  8938. DEF(hash_constructor, "#constructor")
  8939. DEF(as, "as")
  8940. DEF(from, "from")
  8941. DEF(meta, "meta")
  8942. DEF(_default_, "*default*")
  8943. DEF(_star_, "*")
  8944. DEF(Module, "Module")
  8945. DEF(then, "then")
  8946. DEF(resolve, "resolve")
  8947. DEF(reject, "reject")
  8948. DEF(promise, "promise")
  8949. DEF(proxy, "proxy")
  8950. DEF(revoke, "revoke")
  8951. DEF(async, "async")
  8952. DEF(exec, "exec")
  8953. DEF(groups, "groups")
  8954. DEF(indices, "indices")
  8955. DEF(status, "status")
  8956. DEF(reason, "reason")
  8957. DEF(globalThis, "globalThis")
  8958. DEF(bigint, "bigint")
  8959. DEF(not_equal, "not-equal")
  8960. DEF(timed_out, "timed-out")
  8961. DEF(ok, "ok")
  8962. DEF(toJSON, "toJSON")
  8963. DEF(maxByteLength, "maxByteLength")
  8964. /* class names */
  8965. DEF(Object, "Object")
  8966. DEF(Array, "Array")
  8967. DEF(Error, "Error")
  8968. DEF(Number, "Number")
  8969. DEF(String, "String")
  8970. DEF(Boolean, "Boolean")
  8971. DEF(Symbol, "Symbol")
  8972. DEF(Arguments, "Arguments")
  8973. DEF(Math, "Math")
  8974. DEF(JSON, "JSON")
  8975. DEF(Date, "Date")
  8976. DEF(Function, "Function")
  8977. DEF(GeneratorFunction, "GeneratorFunction")
  8978. DEF(ForInIterator, "ForInIterator")
  8979. DEF(RegExp, "RegExp")
  8980. DEF(ArrayBuffer, "ArrayBuffer")
  8981. DEF(SharedArrayBuffer, "SharedArrayBuffer")
  8982. /* must keep same order as class IDs for typed arrays */
  8983. DEF(Uint8ClampedArray, "Uint8ClampedArray")
  8984. DEF(Int8Array, "Int8Array")
  8985. DEF(Uint8Array, "Uint8Array")
  8986. DEF(Int16Array, "Int16Array")
  8987. DEF(Uint16Array, "Uint16Array")
  8988. DEF(Int32Array, "Int32Array")
  8989. DEF(Uint32Array, "Uint32Array")
  8990. DEF(BigInt64Array, "BigInt64Array")
  8991. DEF(BigUint64Array, "BigUint64Array")
  8992. DEF(Float16Array, "Float16Array")
  8993. DEF(Float32Array, "Float32Array")
  8994. DEF(Float64Array, "Float64Array")
  8995. DEF(DataView, "DataView")
  8996. DEF(BigInt, "BigInt")
  8997. DEF(WeakRef, "WeakRef")
  8998. DEF(FinalizationRegistry, "FinalizationRegistry")
  8999. DEF(Map, "Map")
  9000. DEF(Set, "Set") /* Map + 1 */
  9001. DEF(WeakMap, "WeakMap") /* Map + 2 */
  9002. DEF(WeakSet, "WeakSet") /* Map + 3 */
  9003. DEF(Iterator, "Iterator")
  9004. DEF(IteratorHelper, "Iterator Helper")
  9005. DEF(IteratorWrap, "Iterator Wrap")
  9006. DEF(Map_Iterator, "Map Iterator")
  9007. DEF(Set_Iterator, "Set Iterator")
  9008. DEF(Array_Iterator, "Array Iterator")
  9009. DEF(String_Iterator, "String Iterator")
  9010. DEF(RegExp_String_Iterator, "RegExp String Iterator")
  9011. DEF(Generator, "Generator")
  9012. DEF(Proxy, "Proxy")
  9013. DEF(Promise, "Promise")
  9014. DEF(PromiseResolveFunction, "PromiseResolveFunction")
  9015. DEF(PromiseRejectFunction, "PromiseRejectFunction")
  9016. DEF(AsyncFunction, "AsyncFunction")
  9017. DEF(AsyncFunctionResolve, "AsyncFunctionResolve")
  9018. DEF(AsyncFunctionReject, "AsyncFunctionReject")
  9019. DEF(AsyncGeneratorFunction, "AsyncGeneratorFunction")
  9020. DEF(AsyncGenerator, "AsyncGenerator")
  9021. DEF(EvalError, "EvalError")
  9022. DEF(RangeError, "RangeError")
  9023. DEF(ReferenceError, "ReferenceError")
  9024. DEF(SyntaxError, "SyntaxError")
  9025. DEF(TypeError, "TypeError")
  9026. DEF(URIError, "URIError")
  9027. DEF(InternalError, "InternalError")
  9028. DEF(CallSite, "CallSite")
  9029. /* private symbols */
  9030. DEF(Private_brand, "<brand>")
  9031. /* symbols */
  9032. DEF(Symbol_toPrimitive, "Symbol.toPrimitive")
  9033. DEF(Symbol_iterator, "Symbol.iterator")
  9034. DEF(Symbol_match, "Symbol.match")
  9035. DEF(Symbol_matchAll, "Symbol.matchAll")
  9036. DEF(Symbol_replace, "Symbol.replace")
  9037. DEF(Symbol_search, "Symbol.search")
  9038. DEF(Symbol_split, "Symbol.split")
  9039. DEF(Symbol_toStringTag, "Symbol.toStringTag")
  9040. DEF(Symbol_isConcatSpreadable, "Symbol.isConcatSpreadable")
  9041. DEF(Symbol_hasInstance, "Symbol.hasInstance")
  9042. DEF(Symbol_species, "Symbol.species")
  9043. DEF(Symbol_unscopables, "Symbol.unscopables")
  9044. DEF(Symbol_asyncIterator, "Symbol.asyncIterator")
  9045. #endif /* DEF */
  9046. #undef DEF
  9047. JS_ATOM_END,
  9048. };
  9049. #define JS_ATOM_LAST_KEYWORD JS_ATOM_super
  9050. #define JS_ATOM_LAST_STRICT_KEYWORD JS_ATOM_yield
  9051. static const char js_atom_init[] =
  9052. #define DEF(name, str) str "\0"
  9053. /*
  9054. * QuickJS atom definitions
  9055. *
  9056. * Copyright (c) 2017-2018 Fabrice Bellard
  9057. * Copyright (c) 2017-2018 Charlie Gordon
  9058. *
  9059. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9060. * of this software and associated documentation files (the "Software"), to deal
  9061. * in the Software without restriction, including without limitation the rights
  9062. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9063. * copies of the Software, and to permit persons to whom the Software is
  9064. * furnished to do so, subject to the following conditions:
  9065. *
  9066. * The above copyright notice and this permission notice shall be included in
  9067. * all copies or substantial portions of the Software.
  9068. *
  9069. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  9070. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  9071. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  9072. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  9073. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  9074. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  9075. * THE SOFTWARE.
  9076. */
  9077. #ifdef DEF
  9078. /* Note: first atoms are considered as keywords in the parser */
  9079. DEF(null, "null") /* must be first */
  9080. DEF(false, "false")
  9081. DEF(true, "true")
  9082. DEF(if, "if")
  9083. DEF(else, "else")
  9084. DEF(return, "return")
  9085. DEF(var, "var")
  9086. DEF(this, "this")
  9087. DEF(delete, "delete")
  9088. DEF(void, "void")
  9089. DEF(typeof, "typeof")
  9090. DEF(new, "new")
  9091. DEF(in, "in")
  9092. DEF(instanceof, "instanceof")
  9093. DEF(do, "do")
  9094. DEF(while, "while")
  9095. DEF(for, "for")
  9096. DEF(break, "break")
  9097. DEF(continue, "continue")
  9098. DEF(switch, "switch")
  9099. DEF(case, "case")
  9100. DEF(default, "default")
  9101. DEF(throw, "throw")
  9102. DEF(try, "try")
  9103. DEF(catch, "catch")
  9104. DEF(finally, "finally")
  9105. DEF(function, "function")
  9106. DEF(debugger, "debugger")
  9107. DEF(with, "with")
  9108. /* FutureReservedWord */
  9109. DEF(class, "class")
  9110. DEF(const, "const")
  9111. DEF(enum, "enum")
  9112. DEF(export, "export")
  9113. DEF(extends, "extends")
  9114. DEF(import, "import")
  9115. DEF(super, "super")
  9116. /* FutureReservedWords when parsing strict mode code */
  9117. DEF(implements, "implements")
  9118. DEF(interface, "interface")
  9119. DEF(let, "let")
  9120. DEF(package, "package")
  9121. DEF(private, "private")
  9122. DEF(protected, "protected")
  9123. DEF(public, "public")
  9124. DEF(static, "static")
  9125. DEF(yield, "yield")
  9126. DEF(await, "await")
  9127. /* empty string */
  9128. DEF(empty_string, "")
  9129. /* identifiers */
  9130. DEF(keys, "keys")
  9131. DEF(size, "size")
  9132. DEF(length, "length")
  9133. DEF(message, "message")
  9134. DEF(cause, "cause")
  9135. DEF(errors, "errors")
  9136. DEF(stack, "stack")
  9137. DEF(name, "name")
  9138. DEF(toString, "toString")
  9139. DEF(toLocaleString, "toLocaleString")
  9140. DEF(valueOf, "valueOf")
  9141. DEF(eval, "eval")
  9142. DEF(prototype, "prototype")
  9143. DEF(constructor, "constructor")
  9144. DEF(configurable, "configurable")
  9145. DEF(writable, "writable")
  9146. DEF(enumerable, "enumerable")
  9147. DEF(value, "value")
  9148. DEF(get, "get")
  9149. DEF(set, "set")
  9150. DEF(of, "of")
  9151. DEF(__proto__, "__proto__")
  9152. DEF(undefined, "undefined")
  9153. DEF(number, "number")
  9154. DEF(boolean, "boolean")
  9155. DEF(string, "string")
  9156. DEF(object, "object")
  9157. DEF(symbol, "symbol")
  9158. DEF(integer, "integer")
  9159. DEF(unknown, "unknown")
  9160. DEF(arguments, "arguments")
  9161. DEF(callee, "callee")
  9162. DEF(caller, "caller")
  9163. DEF(_eval_, "<eval>")
  9164. DEF(_ret_, "<ret>")
  9165. DEF(_var_, "<var>")
  9166. DEF(_arg_var_, "<arg_var>")
  9167. DEF(_with_, "<with>")
  9168. DEF(lastIndex, "lastIndex")
  9169. DEF(target, "target")
  9170. DEF(index, "index")
  9171. DEF(input, "input")
  9172. DEF(defineProperties, "defineProperties")
  9173. DEF(apply, "apply")
  9174. DEF(join, "join")
  9175. DEF(concat, "concat")
  9176. DEF(split, "split")
  9177. DEF(construct, "construct")
  9178. DEF(getPrototypeOf, "getPrototypeOf")
  9179. DEF(setPrototypeOf, "setPrototypeOf")
  9180. DEF(isExtensible, "isExtensible")
  9181. DEF(preventExtensions, "preventExtensions")
  9182. DEF(has, "has")
  9183. DEF(deleteProperty, "deleteProperty")
  9184. DEF(defineProperty, "defineProperty")
  9185. DEF(getOwnPropertyDescriptor, "getOwnPropertyDescriptor")
  9186. DEF(ownKeys, "ownKeys")
  9187. DEF(add, "add")
  9188. DEF(done, "done")
  9189. DEF(next, "next")
  9190. DEF(values, "values")
  9191. DEF(source, "source")
  9192. DEF(flags, "flags")
  9193. DEF(global, "global")
  9194. DEF(unicode, "unicode")
  9195. DEF(raw, "raw")
  9196. DEF(new_target, "new.target")
  9197. DEF(this_active_func, "this.active_func")
  9198. DEF(home_object, "<home_object>")
  9199. DEF(computed_field, "<computed_field>")
  9200. DEF(static_computed_field, "<static_computed_field>") /* must come after computed_fields */
  9201. DEF(class_fields_init, "<class_fields_init>")
  9202. DEF(brand, "<brand>")
  9203. DEF(hash_constructor, "#constructor")
  9204. DEF(as, "as")
  9205. DEF(from, "from")
  9206. DEF(meta, "meta")
  9207. DEF(_default_, "*default*")
  9208. DEF(_star_, "*")
  9209. DEF(Module, "Module")
  9210. DEF(then, "then")
  9211. DEF(resolve, "resolve")
  9212. DEF(reject, "reject")
  9213. DEF(promise, "promise")
  9214. DEF(proxy, "proxy")
  9215. DEF(revoke, "revoke")
  9216. DEF(async, "async")
  9217. DEF(exec, "exec")
  9218. DEF(groups, "groups")
  9219. DEF(indices, "indices")
  9220. DEF(status, "status")
  9221. DEF(reason, "reason")
  9222. DEF(globalThis, "globalThis")
  9223. DEF(bigint, "bigint")
  9224. DEF(not_equal, "not-equal")
  9225. DEF(timed_out, "timed-out")
  9226. DEF(ok, "ok")
  9227. DEF(toJSON, "toJSON")
  9228. DEF(maxByteLength, "maxByteLength")
  9229. /* class names */
  9230. DEF(Object, "Object")
  9231. DEF(Array, "Array")
  9232. DEF(Error, "Error")
  9233. DEF(Number, "Number")
  9234. DEF(String, "String")
  9235. DEF(Boolean, "Boolean")
  9236. DEF(Symbol, "Symbol")
  9237. DEF(Arguments, "Arguments")
  9238. DEF(Math, "Math")
  9239. DEF(JSON, "JSON")
  9240. DEF(Date, "Date")
  9241. DEF(Function, "Function")
  9242. DEF(GeneratorFunction, "GeneratorFunction")
  9243. DEF(ForInIterator, "ForInIterator")
  9244. DEF(RegExp, "RegExp")
  9245. DEF(ArrayBuffer, "ArrayBuffer")
  9246. DEF(SharedArrayBuffer, "SharedArrayBuffer")
  9247. /* must keep same order as class IDs for typed arrays */
  9248. DEF(Uint8ClampedArray, "Uint8ClampedArray")
  9249. DEF(Int8Array, "Int8Array")
  9250. DEF(Uint8Array, "Uint8Array")
  9251. DEF(Int16Array, "Int16Array")
  9252. DEF(Uint16Array, "Uint16Array")
  9253. DEF(Int32Array, "Int32Array")
  9254. DEF(Uint32Array, "Uint32Array")
  9255. DEF(BigInt64Array, "BigInt64Array")
  9256. DEF(BigUint64Array, "BigUint64Array")
  9257. DEF(Float16Array, "Float16Array")
  9258. DEF(Float32Array, "Float32Array")
  9259. DEF(Float64Array, "Float64Array")
  9260. DEF(DataView, "DataView")
  9261. DEF(BigInt, "BigInt")
  9262. DEF(WeakRef, "WeakRef")
  9263. DEF(FinalizationRegistry, "FinalizationRegistry")
  9264. DEF(Map, "Map")
  9265. DEF(Set, "Set") /* Map + 1 */
  9266. DEF(WeakMap, "WeakMap") /* Map + 2 */
  9267. DEF(WeakSet, "WeakSet") /* Map + 3 */
  9268. DEF(Iterator, "Iterator")
  9269. DEF(IteratorHelper, "Iterator Helper")
  9270. DEF(IteratorWrap, "Iterator Wrap")
  9271. DEF(Map_Iterator, "Map Iterator")
  9272. DEF(Set_Iterator, "Set Iterator")
  9273. DEF(Array_Iterator, "Array Iterator")
  9274. DEF(String_Iterator, "String Iterator")
  9275. DEF(RegExp_String_Iterator, "RegExp String Iterator")
  9276. DEF(Generator, "Generator")
  9277. DEF(Proxy, "Proxy")
  9278. DEF(Promise, "Promise")
  9279. DEF(PromiseResolveFunction, "PromiseResolveFunction")
  9280. DEF(PromiseRejectFunction, "PromiseRejectFunction")
  9281. DEF(AsyncFunction, "AsyncFunction")
  9282. DEF(AsyncFunctionResolve, "AsyncFunctionResolve")
  9283. DEF(AsyncFunctionReject, "AsyncFunctionReject")
  9284. DEF(AsyncGeneratorFunction, "AsyncGeneratorFunction")
  9285. DEF(AsyncGenerator, "AsyncGenerator")
  9286. DEF(EvalError, "EvalError")
  9287. DEF(RangeError, "RangeError")
  9288. DEF(ReferenceError, "ReferenceError")
  9289. DEF(SyntaxError, "SyntaxError")
  9290. DEF(TypeError, "TypeError")
  9291. DEF(URIError, "URIError")
  9292. DEF(InternalError, "InternalError")
  9293. DEF(CallSite, "CallSite")
  9294. /* private symbols */
  9295. DEF(Private_brand, "<brand>")
  9296. /* symbols */
  9297. DEF(Symbol_toPrimitive, "Symbol.toPrimitive")
  9298. DEF(Symbol_iterator, "Symbol.iterator")
  9299. DEF(Symbol_match, "Symbol.match")
  9300. DEF(Symbol_matchAll, "Symbol.matchAll")
  9301. DEF(Symbol_replace, "Symbol.replace")
  9302. DEF(Symbol_search, "Symbol.search")
  9303. DEF(Symbol_split, "Symbol.split")
  9304. DEF(Symbol_toStringTag, "Symbol.toStringTag")
  9305. DEF(Symbol_isConcatSpreadable, "Symbol.isConcatSpreadable")
  9306. DEF(Symbol_hasInstance, "Symbol.hasInstance")
  9307. DEF(Symbol_species, "Symbol.species")
  9308. DEF(Symbol_unscopables, "Symbol.unscopables")
  9309. DEF(Symbol_asyncIterator, "Symbol.asyncIterator")
  9310. #endif /* DEF */
  9311. #undef DEF
  9312. ;
  9313. typedef enum OPCodeFormat {
  9314. #define FMT(f) OP_FMT_ ## f,
  9315. #define DEF(id, size, n_pop, n_push, f)
  9316. /*
  9317. * QuickJS opcode definitions
  9318. *
  9319. * Copyright (c) 2017-2018 Fabrice Bellard
  9320. * Copyright (c) 2017-2018 Charlie Gordon
  9321. *
  9322. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9323. * of this software and associated documentation files (the "Software"), to deal
  9324. * in the Software without restriction, including without limitation the rights
  9325. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9326. * copies of the Software, and to permit persons to whom the Software is
  9327. * furnished to do so, subject to the following conditions:
  9328. *
  9329. * The above copyright notice and this permission notice shall be included in
  9330. * all copies or substantial portions of the Software.
  9331. *
  9332. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  9333. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  9334. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  9335. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  9336. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  9337. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  9338. * THE SOFTWARE.
  9339. */
  9340. #ifdef FMT
  9341. FMT(none)
  9342. FMT(none_int)
  9343. FMT(none_loc)
  9344. FMT(none_arg)
  9345. FMT(none_var_ref)
  9346. FMT(u8)
  9347. FMT(i8)
  9348. FMT(loc8)
  9349. FMT(const8)
  9350. FMT(label8)
  9351. FMT(u16)
  9352. FMT(i16)
  9353. FMT(label16)
  9354. FMT(npop)
  9355. FMT(npopx)
  9356. FMT(npop_u16)
  9357. FMT(loc)
  9358. FMT(arg)
  9359. FMT(var_ref)
  9360. FMT(u32)
  9361. FMT(u32x2)
  9362. FMT(i32)
  9363. FMT(const)
  9364. FMT(label)
  9365. FMT(atom)
  9366. FMT(atom_u8)
  9367. FMT(atom_u16)
  9368. FMT(atom_label_u8)
  9369. FMT(atom_label_u16)
  9370. FMT(label_u16)
  9371. #undef FMT
  9372. #endif /* FMT */
  9373. #ifdef DEF
  9374. #ifndef def
  9375. #define def(id, size, n_pop, n_push, f) DEF(id, size, n_pop, n_push, f)
  9376. #endif
  9377. DEF(invalid, 1, 0, 0, none) /* never emitted */
  9378. /* push values */
  9379. DEF( push_i32, 5, 0, 1, i32)
  9380. DEF( push_const, 5, 0, 1, const)
  9381. DEF( fclosure, 5, 0, 1, const) /* must follow push_const */
  9382. DEF(push_atom_value, 5, 0, 1, atom)
  9383. DEF( private_symbol, 5, 0, 1, atom)
  9384. DEF( undefined, 1, 0, 1, none)
  9385. DEF( null, 1, 0, 1, none)
  9386. DEF( push_this, 1, 0, 1, none) /* only used at the start of a function */
  9387. DEF( push_false, 1, 0, 1, none)
  9388. DEF( push_true, 1, 0, 1, none)
  9389. DEF( object, 1, 0, 1, none)
  9390. DEF( special_object, 2, 0, 1, u8) /* only used at the start of a function */
  9391. DEF( rest, 3, 0, 1, u16) /* only used at the start of a function */
  9392. DEF( drop, 1, 1, 0, none) /* a -> */
  9393. DEF( nip, 1, 2, 1, none) /* a b -> b */
  9394. DEF( nip1, 1, 3, 2, none) /* a b c -> b c */
  9395. DEF( dup, 1, 1, 2, none) /* a -> a a */
  9396. DEF( dup1, 1, 2, 3, none) /* a b -> a a b */
  9397. DEF( dup2, 1, 2, 4, none) /* a b -> a b a b */
  9398. DEF( dup3, 1, 3, 6, none) /* a b c -> a b c a b c */
  9399. DEF( insert2, 1, 2, 3, none) /* obj a -> a obj a (dup_x1) */
  9400. DEF( insert3, 1, 3, 4, none) /* obj prop a -> a obj prop a (dup_x2) */
  9401. DEF( insert4, 1, 4, 5, none) /* this obj prop a -> a this obj prop a */
  9402. DEF( perm3, 1, 3, 3, none) /* obj a b -> a obj b */
  9403. DEF( perm4, 1, 4, 4, none) /* obj prop a b -> a obj prop b */
  9404. DEF( perm5, 1, 5, 5, none) /* this obj prop a b -> a this obj prop b */
  9405. DEF( swap, 1, 2, 2, none) /* a b -> b a */
  9406. DEF( swap2, 1, 4, 4, none) /* a b c d -> c d a b */
  9407. DEF( rot3l, 1, 3, 3, none) /* x a b -> a b x */
  9408. DEF( rot3r, 1, 3, 3, none) /* a b x -> x a b */
  9409. DEF( rot4l, 1, 4, 4, none) /* x a b c -> a b c x */
  9410. DEF( rot5l, 1, 5, 5, none) /* x a b c d -> a b c d x */
  9411. DEF(call_constructor, 3, 2, 1, npop) /* func new.target args -> ret. arguments are not counted in n_pop */
  9412. DEF( call, 3, 1, 1, npop) /* arguments are not counted in n_pop */
  9413. DEF( tail_call, 3, 1, 0, npop) /* arguments are not counted in n_pop */
  9414. DEF( call_method, 3, 2, 1, npop) /* arguments are not counted in n_pop */
  9415. DEF(tail_call_method, 3, 2, 0, npop) /* arguments are not counted in n_pop */
  9416. DEF( array_from, 3, 0, 1, npop) /* arguments are not counted in n_pop */
  9417. DEF( apply, 3, 3, 1, u16)
  9418. DEF( return, 1, 1, 0, none)
  9419. DEF( return_undef, 1, 0, 0, none)
  9420. DEF(check_ctor_return, 1, 1, 2, none)
  9421. DEF( check_ctor, 1, 0, 0, none)
  9422. DEF( init_ctor, 1, 0, 1, none)
  9423. DEF( check_brand, 1, 2, 2, none) /* this_obj func -> this_obj func */
  9424. DEF( add_brand, 1, 2, 0, none) /* this_obj home_obj -> */
  9425. DEF( return_async, 1, 1, 0, none)
  9426. DEF( throw, 1, 1, 0, none)
  9427. DEF( throw_error, 6, 0, 0, atom_u8)
  9428. DEF( eval, 5, 1, 1, npop_u16) /* func args... -> ret_val */
  9429. DEF( apply_eval, 3, 2, 1, u16) /* func array -> ret_eval */
  9430. DEF( regexp, 1, 2, 1, none) /* create a RegExp object from the pattern and a
  9431. bytecode string */
  9432. DEF( get_super, 1, 1, 1, none)
  9433. DEF( import, 1, 1, 1, none) /* dynamic module import */
  9434. DEF( check_var, 5, 0, 1, atom) /* check if a variable exists */
  9435. DEF( get_var_undef, 5, 0, 1, atom) /* push undefined if the variable does not exist */
  9436. DEF( get_var, 5, 0, 1, atom) /* throw an exception if the variable does not exist */
  9437. DEF( put_var, 5, 1, 0, atom) /* must come after get_var */
  9438. DEF( put_var_init, 5, 1, 0, atom) /* must come after put_var. Used to initialize a global lexical variable */
  9439. DEF( put_var_strict, 5, 2, 0, atom) /* for strict mode variable write */
  9440. DEF( get_ref_value, 1, 2, 3, none)
  9441. DEF( put_ref_value, 1, 3, 0, none)
  9442. DEF( define_var, 6, 0, 0, atom_u8)
  9443. DEF(check_define_var, 6, 0, 0, atom_u8)
  9444. DEF( define_func, 6, 1, 0, atom_u8)
  9445. // order matters, see IC counterparts
  9446. DEF( get_field, 5, 1, 1, atom)
  9447. DEF( get_field2, 5, 1, 2, atom)
  9448. DEF( put_field, 5, 2, 0, atom)
  9449. DEF( get_private_field, 1, 2, 1, none) /* obj prop -> value */
  9450. DEF( put_private_field, 1, 3, 0, none) /* obj value prop -> */
  9451. DEF(define_private_field, 1, 3, 1, none) /* obj prop value -> obj */
  9452. DEF( get_array_el, 1, 2, 1, none)
  9453. DEF( get_array_el2, 1, 2, 2, none) /* obj prop -> obj value */
  9454. DEF( put_array_el, 1, 3, 0, none)
  9455. DEF(get_super_value, 1, 3, 1, none) /* this obj prop -> value */
  9456. DEF(put_super_value, 1, 4, 0, none) /* this obj prop value -> */
  9457. DEF( define_field, 5, 2, 1, atom)
  9458. DEF( set_name, 5, 1, 1, atom)
  9459. DEF(set_name_computed, 1, 2, 2, none)
  9460. DEF( set_proto, 1, 2, 1, none)
  9461. DEF(set_home_object, 1, 2, 2, none)
  9462. DEF(define_array_el, 1, 3, 2, none)
  9463. DEF( append, 1, 3, 2, none) /* append enumerated object, update length */
  9464. DEF(copy_data_properties, 2, 3, 3, u8)
  9465. DEF( define_method, 6, 2, 1, atom_u8)
  9466. DEF(define_method_computed, 2, 3, 1, u8) /* must come after define_method */
  9467. DEF( define_class, 6, 2, 2, atom_u8) /* parent ctor -> ctor proto */
  9468. DEF( define_class_computed, 6, 3, 3, atom_u8) /* field_name parent ctor -> field_name ctor proto (class with computed name) */
  9469. DEF( get_loc, 3, 0, 1, loc)
  9470. DEF( put_loc, 3, 1, 0, loc) /* must come after get_loc */
  9471. DEF( set_loc, 3, 1, 1, loc) /* must come after put_loc */
  9472. DEF( get_arg, 3, 0, 1, arg)
  9473. DEF( put_arg, 3, 1, 0, arg) /* must come after get_arg */
  9474. DEF( set_arg, 3, 1, 1, arg) /* must come after put_arg */
  9475. DEF( get_var_ref, 3, 0, 1, var_ref)
  9476. DEF( put_var_ref, 3, 1, 0, var_ref) /* must come after get_var_ref */
  9477. DEF( set_var_ref, 3, 1, 1, var_ref) /* must come after put_var_ref */
  9478. DEF(set_loc_uninitialized, 3, 0, 0, loc)
  9479. DEF( get_loc_check, 3, 0, 1, loc)
  9480. DEF( put_loc_check, 3, 1, 0, loc) /* must come after get_loc_check */
  9481. DEF( put_loc_check_init, 3, 1, 0, loc)
  9482. DEF(get_var_ref_check, 3, 0, 1, var_ref)
  9483. DEF(put_var_ref_check, 3, 1, 0, var_ref) /* must come after get_var_ref_check */
  9484. DEF(put_var_ref_check_init, 3, 1, 0, var_ref)
  9485. DEF( close_loc, 3, 0, 0, loc)
  9486. DEF( if_false, 5, 1, 0, label)
  9487. DEF( if_true, 5, 1, 0, label) /* must come after if_false */
  9488. DEF( goto, 5, 0, 0, label) /* must come after if_true */
  9489. DEF( catch, 5, 0, 1, label)
  9490. DEF( gosub, 5, 0, 0, label) /* used to execute the finally block */
  9491. DEF( ret, 1, 1, 0, none) /* used to return from the finally block */
  9492. DEF( nip_catch, 1, 2, 1, none) /* catch ... a -> a */
  9493. DEF( to_object, 1, 1, 1, none)
  9494. //DEF( to_string, 1, 1, 1, none)
  9495. DEF( to_propkey, 1, 1, 1, none)
  9496. DEF( to_propkey2, 1, 2, 2, none)
  9497. DEF( with_get_var, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */
  9498. DEF( with_put_var, 10, 2, 1, atom_label_u8) /* must be in the same order as scope_xxx */
  9499. DEF(with_delete_var, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */
  9500. DEF( with_make_ref, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */
  9501. DEF( with_get_ref, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */
  9502. DEF(with_get_ref_undef, 10, 1, 0, atom_label_u8)
  9503. DEF( make_loc_ref, 7, 0, 2, atom_u16)
  9504. DEF( make_arg_ref, 7, 0, 2, atom_u16)
  9505. DEF(make_var_ref_ref, 7, 0, 2, atom_u16)
  9506. DEF( make_var_ref, 5, 0, 2, atom)
  9507. DEF( for_in_start, 1, 1, 1, none)
  9508. DEF( for_of_start, 1, 1, 3, none)
  9509. DEF(for_await_of_start, 1, 1, 3, none)
  9510. DEF( for_in_next, 1, 1, 3, none)
  9511. DEF( for_of_next, 2, 3, 5, u8)
  9512. DEF(iterator_check_object, 1, 1, 1, none)
  9513. DEF(iterator_get_value_done, 1, 1, 2, none)
  9514. DEF( iterator_close, 1, 3, 0, none)
  9515. DEF( iterator_next, 1, 4, 4, none)
  9516. DEF( iterator_call, 2, 4, 5, u8)
  9517. DEF( initial_yield, 1, 0, 0, none)
  9518. DEF( yield, 1, 1, 2, none)
  9519. DEF( yield_star, 1, 1, 2, none)
  9520. DEF(async_yield_star, 1, 1, 2, none)
  9521. DEF( await, 1, 1, 1, none)
  9522. /* arithmetic/logic operations */
  9523. DEF( neg, 1, 1, 1, none)
  9524. DEF( plus, 1, 1, 1, none)
  9525. DEF( dec, 1, 1, 1, none)
  9526. DEF( inc, 1, 1, 1, none)
  9527. DEF( post_dec, 1, 1, 2, none)
  9528. DEF( post_inc, 1, 1, 2, none)
  9529. DEF( dec_loc, 2, 0, 0, loc8)
  9530. DEF( inc_loc, 2, 0, 0, loc8)
  9531. DEF( add_loc, 2, 1, 0, loc8)
  9532. DEF( not, 1, 1, 1, none)
  9533. DEF( lnot, 1, 1, 1, none)
  9534. DEF( typeof, 1, 1, 1, none)
  9535. DEF( delete, 1, 2, 1, none)
  9536. DEF( delete_var, 5, 0, 1, atom)
  9537. /* warning: order matters (see js_parse_assign_expr) */
  9538. DEF( mul, 1, 2, 1, none)
  9539. DEF( div, 1, 2, 1, none)
  9540. DEF( mod, 1, 2, 1, none)
  9541. DEF( add, 1, 2, 1, none)
  9542. DEF( sub, 1, 2, 1, none)
  9543. DEF( shl, 1, 2, 1, none)
  9544. DEF( sar, 1, 2, 1, none)
  9545. DEF( shr, 1, 2, 1, none)
  9546. DEF( and, 1, 2, 1, none)
  9547. DEF( xor, 1, 2, 1, none)
  9548. DEF( or, 1, 2, 1, none)
  9549. DEF( pow, 1, 2, 1, none)
  9550. DEF( lt, 1, 2, 1, none)
  9551. DEF( lte, 1, 2, 1, none)
  9552. DEF( gt, 1, 2, 1, none)
  9553. DEF( gte, 1, 2, 1, none)
  9554. DEF( instanceof, 1, 2, 1, none)
  9555. DEF( in, 1, 2, 1, none)
  9556. DEF( eq, 1, 2, 1, none)
  9557. DEF( neq, 1, 2, 1, none)
  9558. DEF( strict_eq, 1, 2, 1, none)
  9559. DEF( strict_neq, 1, 2, 1, none)
  9560. DEF(is_undefined_or_null, 1, 1, 1, none)
  9561. DEF( private_in, 1, 2, 1, none)
  9562. /* must be the last non short and non temporary opcode */
  9563. DEF( nop, 1, 0, 0, none)
  9564. /* temporary opcodes: never emitted in the final bytecode */
  9565. def( enter_scope, 3, 0, 0, u16) /* emitted in phase 1, removed in phase 2 */
  9566. def( leave_scope, 3, 0, 0, u16) /* emitted in phase 1, removed in phase 2 */
  9567. def( label, 5, 0, 0, label) /* emitted in phase 1, removed in phase 3 */
  9568. def(scope_get_var_undef, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */
  9569. def( scope_get_var, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */
  9570. def( scope_put_var, 7, 1, 0, atom_u16) /* emitted in phase 1, removed in phase 2 */
  9571. def(scope_delete_var, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */
  9572. def( scope_make_ref, 11, 0, 2, atom_label_u16) /* emitted in phase 1, removed in phase 2 */
  9573. def( scope_get_ref, 7, 0, 2, atom_u16) /* emitted in phase 1, removed in phase 2 */
  9574. def(scope_put_var_init, 7, 0, 2, atom_u16) /* emitted in phase 1, removed in phase 2 */
  9575. def(scope_get_private_field, 7, 1, 1, atom_u16) /* obj -> value, emitted in phase 1, removed in phase 2 */
  9576. def(scope_get_private_field2, 7, 1, 2, atom_u16) /* obj -> obj value, emitted in phase 1, removed in phase 2 */
  9577. def(scope_put_private_field, 7, 2, 0, atom_u16) /* obj value ->, emitted in phase 1, removed in phase 2 */
  9578. def(scope_in_private_field, 7, 1, 1, atom_u16) /* obj -> res emitted in phase 1, removed in phase 2 */
  9579. def(get_field_opt_chain, 5, 1, 1, atom) /* emitted in phase 1, removed in phase 2 */
  9580. def(get_array_el_opt_chain, 1, 2, 1, none) /* emitted in phase 1, removed in phase 2 */
  9581. def( set_class_name, 5, 1, 1, u32) /* emitted in phase 1, removed in phase 2 */
  9582. def( source_loc, 9, 0, 0, u32x2) /* emitted in phase 1, removed in phase 3 */
  9583. DEF( push_minus1, 1, 0, 1, none_int)
  9584. DEF( push_0, 1, 0, 1, none_int)
  9585. DEF( push_1, 1, 0, 1, none_int)
  9586. DEF( push_2, 1, 0, 1, none_int)
  9587. DEF( push_3, 1, 0, 1, none_int)
  9588. DEF( push_4, 1, 0, 1, none_int)
  9589. DEF( push_5, 1, 0, 1, none_int)
  9590. DEF( push_6, 1, 0, 1, none_int)
  9591. DEF( push_7, 1, 0, 1, none_int)
  9592. DEF( push_i8, 2, 0, 1, i8)
  9593. DEF( push_i16, 3, 0, 1, i16)
  9594. DEF( push_const8, 2, 0, 1, const8)
  9595. DEF( fclosure8, 2, 0, 1, const8) /* must follow push_const8 */
  9596. DEF(push_empty_string, 1, 0, 1, none)
  9597. DEF( get_loc8, 2, 0, 1, loc8)
  9598. DEF( put_loc8, 2, 1, 0, loc8)
  9599. DEF( set_loc8, 2, 1, 1, loc8)
  9600. DEF( get_loc0_loc1, 1, 0, 2, none_loc)
  9601. DEF( get_loc0, 1, 0, 1, none_loc)
  9602. DEF( get_loc1, 1, 0, 1, none_loc)
  9603. DEF( get_loc2, 1, 0, 1, none_loc)
  9604. DEF( get_loc3, 1, 0, 1, none_loc)
  9605. DEF( put_loc0, 1, 1, 0, none_loc)
  9606. DEF( put_loc1, 1, 1, 0, none_loc)
  9607. DEF( put_loc2, 1, 1, 0, none_loc)
  9608. DEF( put_loc3, 1, 1, 0, none_loc)
  9609. DEF( set_loc0, 1, 1, 1, none_loc)
  9610. DEF( set_loc1, 1, 1, 1, none_loc)
  9611. DEF( set_loc2, 1, 1, 1, none_loc)
  9612. DEF( set_loc3, 1, 1, 1, none_loc)
  9613. DEF( get_arg0, 1, 0, 1, none_arg)
  9614. DEF( get_arg1, 1, 0, 1, none_arg)
  9615. DEF( get_arg2, 1, 0, 1, none_arg)
  9616. DEF( get_arg3, 1, 0, 1, none_arg)
  9617. DEF( put_arg0, 1, 1, 0, none_arg)
  9618. DEF( put_arg1, 1, 1, 0, none_arg)
  9619. DEF( put_arg2, 1, 1, 0, none_arg)
  9620. DEF( put_arg3, 1, 1, 0, none_arg)
  9621. DEF( set_arg0, 1, 1, 1, none_arg)
  9622. DEF( set_arg1, 1, 1, 1, none_arg)
  9623. DEF( set_arg2, 1, 1, 1, none_arg)
  9624. DEF( set_arg3, 1, 1, 1, none_arg)
  9625. DEF( get_var_ref0, 1, 0, 1, none_var_ref)
  9626. DEF( get_var_ref1, 1, 0, 1, none_var_ref)
  9627. DEF( get_var_ref2, 1, 0, 1, none_var_ref)
  9628. DEF( get_var_ref3, 1, 0, 1, none_var_ref)
  9629. DEF( put_var_ref0, 1, 1, 0, none_var_ref)
  9630. DEF( put_var_ref1, 1, 1, 0, none_var_ref)
  9631. DEF( put_var_ref2, 1, 1, 0, none_var_ref)
  9632. DEF( put_var_ref3, 1, 1, 0, none_var_ref)
  9633. DEF( set_var_ref0, 1, 1, 1, none_var_ref)
  9634. DEF( set_var_ref1, 1, 1, 1, none_var_ref)
  9635. DEF( set_var_ref2, 1, 1, 1, none_var_ref)
  9636. DEF( set_var_ref3, 1, 1, 1, none_var_ref)
  9637. DEF( get_length, 1, 1, 1, none)
  9638. DEF( if_false8, 2, 1, 0, label8)
  9639. DEF( if_true8, 2, 1, 0, label8) /* must come after if_false8 */
  9640. DEF( goto8, 2, 0, 0, label8) /* must come after if_true8 */
  9641. DEF( goto16, 3, 0, 0, label16)
  9642. DEF( call0, 1, 1, 1, npopx)
  9643. DEF( call1, 1, 1, 1, npopx)
  9644. DEF( call2, 1, 1, 1, npopx)
  9645. DEF( call3, 1, 1, 1, npopx)
  9646. DEF( is_undefined, 1, 1, 1, none)
  9647. DEF( is_null, 1, 1, 1, none)
  9648. DEF(typeof_is_undefined, 1, 1, 1, none)
  9649. DEF( typeof_is_function, 1, 1, 1, none)
  9650. #undef DEF
  9651. #undef def
  9652. #endif /* DEF */
  9653. #undef DEF
  9654. #undef FMT
  9655. } OPCodeFormat;
  9656. typedef enum OPCodeEnum {
  9657. #define FMT(f)
  9658. #define DEF(id, size, n_pop, n_push, f) OP_ ## id,
  9659. #define def(id, size, n_pop, n_push, f)
  9660. /*
  9661. * QuickJS opcode definitions
  9662. *
  9663. * Copyright (c) 2017-2018 Fabrice Bellard
  9664. * Copyright (c) 2017-2018 Charlie Gordon
  9665. *
  9666. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9667. * of this software and associated documentation files (the "Software"), to deal
  9668. * in the Software without restriction, including without limitation the rights
  9669. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9670. * copies of the Software, and to permit persons to whom the Software is
  9671. * furnished to do so, subject to the following conditions:
  9672. *
  9673. * The above copyright notice and this permission notice shall be included in
  9674. * all copies or substantial portions of the Software.
  9675. *
  9676. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  9677. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  9678. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  9679. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  9680. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  9681. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  9682. * THE SOFTWARE.
  9683. */
  9684. #ifdef FMT
  9685. FMT(none)
  9686. FMT(none_int)
  9687. FMT(none_loc)
  9688. FMT(none_arg)
  9689. FMT(none_var_ref)
  9690. FMT(u8)
  9691. FMT(i8)
  9692. FMT(loc8)
  9693. FMT(const8)
  9694. FMT(label8)
  9695. FMT(u16)
  9696. FMT(i16)
  9697. FMT(label16)
  9698. FMT(npop)
  9699. FMT(npopx)
  9700. FMT(npop_u16)
  9701. FMT(loc)
  9702. FMT(arg)
  9703. FMT(var_ref)
  9704. FMT(u32)
  9705. FMT(u32x2)
  9706. FMT(i32)
  9707. FMT(const)
  9708. FMT(label)
  9709. FMT(atom)
  9710. FMT(atom_u8)
  9711. FMT(atom_u16)
  9712. FMT(atom_label_u8)
  9713. FMT(atom_label_u16)
  9714. FMT(label_u16)
  9715. #undef FMT
  9716. #endif /* FMT */
  9717. #ifdef DEF
  9718. #ifndef def
  9719. #define def(id, size, n_pop, n_push, f) DEF(id, size, n_pop, n_push, f)
  9720. #endif
  9721. DEF(invalid, 1, 0, 0, none) /* never emitted */
  9722. /* push values */
  9723. DEF( push_i32, 5, 0, 1, i32)
  9724. DEF( push_const, 5, 0, 1, const)
  9725. DEF( fclosure, 5, 0, 1, const) /* must follow push_const */
  9726. DEF(push_atom_value, 5, 0, 1, atom)
  9727. DEF( private_symbol, 5, 0, 1, atom)
  9728. DEF( undefined, 1, 0, 1, none)
  9729. DEF( null, 1, 0, 1, none)
  9730. DEF( push_this, 1, 0, 1, none) /* only used at the start of a function */
  9731. DEF( push_false, 1, 0, 1, none)
  9732. DEF( push_true, 1, 0, 1, none)
  9733. DEF( object, 1, 0, 1, none)
  9734. DEF( special_object, 2, 0, 1, u8) /* only used at the start of a function */
  9735. DEF( rest, 3, 0, 1, u16) /* only used at the start of a function */
  9736. DEF( drop, 1, 1, 0, none) /* a -> */
  9737. DEF( nip, 1, 2, 1, none) /* a b -> b */
  9738. DEF( nip1, 1, 3, 2, none) /* a b c -> b c */
  9739. DEF( dup, 1, 1, 2, none) /* a -> a a */
  9740. DEF( dup1, 1, 2, 3, none) /* a b -> a a b */
  9741. DEF( dup2, 1, 2, 4, none) /* a b -> a b a b */
  9742. DEF( dup3, 1, 3, 6, none) /* a b c -> a b c a b c */
  9743. DEF( insert2, 1, 2, 3, none) /* obj a -> a obj a (dup_x1) */
  9744. DEF( insert3, 1, 3, 4, none) /* obj prop a -> a obj prop a (dup_x2) */
  9745. DEF( insert4, 1, 4, 5, none) /* this obj prop a -> a this obj prop a */
  9746. DEF( perm3, 1, 3, 3, none) /* obj a b -> a obj b */
  9747. DEF( perm4, 1, 4, 4, none) /* obj prop a b -> a obj prop b */
  9748. DEF( perm5, 1, 5, 5, none) /* this obj prop a b -> a this obj prop b */
  9749. DEF( swap, 1, 2, 2, none) /* a b -> b a */
  9750. DEF( swap2, 1, 4, 4, none) /* a b c d -> c d a b */
  9751. DEF( rot3l, 1, 3, 3, none) /* x a b -> a b x */
  9752. DEF( rot3r, 1, 3, 3, none) /* a b x -> x a b */
  9753. DEF( rot4l, 1, 4, 4, none) /* x a b c -> a b c x */
  9754. DEF( rot5l, 1, 5, 5, none) /* x a b c d -> a b c d x */
  9755. DEF(call_constructor, 3, 2, 1, npop) /* func new.target args -> ret. arguments are not counted in n_pop */
  9756. DEF( call, 3, 1, 1, npop) /* arguments are not counted in n_pop */
  9757. DEF( tail_call, 3, 1, 0, npop) /* arguments are not counted in n_pop */
  9758. DEF( call_method, 3, 2, 1, npop) /* arguments are not counted in n_pop */
  9759. DEF(tail_call_method, 3, 2, 0, npop) /* arguments are not counted in n_pop */
  9760. DEF( array_from, 3, 0, 1, npop) /* arguments are not counted in n_pop */
  9761. DEF( apply, 3, 3, 1, u16)
  9762. DEF( return, 1, 1, 0, none)
  9763. DEF( return_undef, 1, 0, 0, none)
  9764. DEF(check_ctor_return, 1, 1, 2, none)
  9765. DEF( check_ctor, 1, 0, 0, none)
  9766. DEF( init_ctor, 1, 0, 1, none)
  9767. DEF( check_brand, 1, 2, 2, none) /* this_obj func -> this_obj func */
  9768. DEF( add_brand, 1, 2, 0, none) /* this_obj home_obj -> */
  9769. DEF( return_async, 1, 1, 0, none)
  9770. DEF( throw, 1, 1, 0, none)
  9771. DEF( throw_error, 6, 0, 0, atom_u8)
  9772. DEF( eval, 5, 1, 1, npop_u16) /* func args... -> ret_val */
  9773. DEF( apply_eval, 3, 2, 1, u16) /* func array -> ret_eval */
  9774. DEF( regexp, 1, 2, 1, none) /* create a RegExp object from the pattern and a
  9775. bytecode string */
  9776. DEF( get_super, 1, 1, 1, none)
  9777. DEF( import, 1, 1, 1, none) /* dynamic module import */
  9778. DEF( check_var, 5, 0, 1, atom) /* check if a variable exists */
  9779. DEF( get_var_undef, 5, 0, 1, atom) /* push undefined if the variable does not exist */
  9780. DEF( get_var, 5, 0, 1, atom) /* throw an exception if the variable does not exist */
  9781. DEF( put_var, 5, 1, 0, atom) /* must come after get_var */
  9782. DEF( put_var_init, 5, 1, 0, atom) /* must come after put_var. Used to initialize a global lexical variable */
  9783. DEF( put_var_strict, 5, 2, 0, atom) /* for strict mode variable write */
  9784. DEF( get_ref_value, 1, 2, 3, none)
  9785. DEF( put_ref_value, 1, 3, 0, none)
  9786. DEF( define_var, 6, 0, 0, atom_u8)
  9787. DEF(check_define_var, 6, 0, 0, atom_u8)
  9788. DEF( define_func, 6, 1, 0, atom_u8)
  9789. // order matters, see IC counterparts
  9790. DEF( get_field, 5, 1, 1, atom)
  9791. DEF( get_field2, 5, 1, 2, atom)
  9792. DEF( put_field, 5, 2, 0, atom)
  9793. DEF( get_private_field, 1, 2, 1, none) /* obj prop -> value */
  9794. DEF( put_private_field, 1, 3, 0, none) /* obj value prop -> */
  9795. DEF(define_private_field, 1, 3, 1, none) /* obj prop value -> obj */
  9796. DEF( get_array_el, 1, 2, 1, none)
  9797. DEF( get_array_el2, 1, 2, 2, none) /* obj prop -> obj value */
  9798. DEF( put_array_el, 1, 3, 0, none)
  9799. DEF(get_super_value, 1, 3, 1, none) /* this obj prop -> value */
  9800. DEF(put_super_value, 1, 4, 0, none) /* this obj prop value -> */
  9801. DEF( define_field, 5, 2, 1, atom)
  9802. DEF( set_name, 5, 1, 1, atom)
  9803. DEF(set_name_computed, 1, 2, 2, none)
  9804. DEF( set_proto, 1, 2, 1, none)
  9805. DEF(set_home_object, 1, 2, 2, none)
  9806. DEF(define_array_el, 1, 3, 2, none)
  9807. DEF( append, 1, 3, 2, none) /* append enumerated object, update length */
  9808. DEF(copy_data_properties, 2, 3, 3, u8)
  9809. DEF( define_method, 6, 2, 1, atom_u8)
  9810. DEF(define_method_computed, 2, 3, 1, u8) /* must come after define_method */
  9811. DEF( define_class, 6, 2, 2, atom_u8) /* parent ctor -> ctor proto */
  9812. DEF( define_class_computed, 6, 3, 3, atom_u8) /* field_name parent ctor -> field_name ctor proto (class with computed name) */
  9813. DEF( get_loc, 3, 0, 1, loc)
  9814. DEF( put_loc, 3, 1, 0, loc) /* must come after get_loc */
  9815. DEF( set_loc, 3, 1, 1, loc) /* must come after put_loc */
  9816. DEF( get_arg, 3, 0, 1, arg)
  9817. DEF( put_arg, 3, 1, 0, arg) /* must come after get_arg */
  9818. DEF( set_arg, 3, 1, 1, arg) /* must come after put_arg */
  9819. DEF( get_var_ref, 3, 0, 1, var_ref)
  9820. DEF( put_var_ref, 3, 1, 0, var_ref) /* must come after get_var_ref */
  9821. DEF( set_var_ref, 3, 1, 1, var_ref) /* must come after put_var_ref */
  9822. DEF(set_loc_uninitialized, 3, 0, 0, loc)
  9823. DEF( get_loc_check, 3, 0, 1, loc)
  9824. DEF( put_loc_check, 3, 1, 0, loc) /* must come after get_loc_check */
  9825. DEF( put_loc_check_init, 3, 1, 0, loc)
  9826. DEF(get_var_ref_check, 3, 0, 1, var_ref)
  9827. DEF(put_var_ref_check, 3, 1, 0, var_ref) /* must come after get_var_ref_check */
  9828. DEF(put_var_ref_check_init, 3, 1, 0, var_ref)
  9829. DEF( close_loc, 3, 0, 0, loc)
  9830. DEF( if_false, 5, 1, 0, label)
  9831. DEF( if_true, 5, 1, 0, label) /* must come after if_false */
  9832. DEF( goto, 5, 0, 0, label) /* must come after if_true */
  9833. DEF( catch, 5, 0, 1, label)
  9834. DEF( gosub, 5, 0, 0, label) /* used to execute the finally block */
  9835. DEF( ret, 1, 1, 0, none) /* used to return from the finally block */
  9836. DEF( nip_catch, 1, 2, 1, none) /* catch ... a -> a */
  9837. DEF( to_object, 1, 1, 1, none)
  9838. //DEF( to_string, 1, 1, 1, none)
  9839. DEF( to_propkey, 1, 1, 1, none)
  9840. DEF( to_propkey2, 1, 2, 2, none)
  9841. DEF( with_get_var, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */
  9842. DEF( with_put_var, 10, 2, 1, atom_label_u8) /* must be in the same order as scope_xxx */
  9843. DEF(with_delete_var, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */
  9844. DEF( with_make_ref, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */
  9845. DEF( with_get_ref, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */
  9846. DEF(with_get_ref_undef, 10, 1, 0, atom_label_u8)
  9847. DEF( make_loc_ref, 7, 0, 2, atom_u16)
  9848. DEF( make_arg_ref, 7, 0, 2, atom_u16)
  9849. DEF(make_var_ref_ref, 7, 0, 2, atom_u16)
  9850. DEF( make_var_ref, 5, 0, 2, atom)
  9851. DEF( for_in_start, 1, 1, 1, none)
  9852. DEF( for_of_start, 1, 1, 3, none)
  9853. DEF(for_await_of_start, 1, 1, 3, none)
  9854. DEF( for_in_next, 1, 1, 3, none)
  9855. DEF( for_of_next, 2, 3, 5, u8)
  9856. DEF(iterator_check_object, 1, 1, 1, none)
  9857. DEF(iterator_get_value_done, 1, 1, 2, none)
  9858. DEF( iterator_close, 1, 3, 0, none)
  9859. DEF( iterator_next, 1, 4, 4, none)
  9860. DEF( iterator_call, 2, 4, 5, u8)
  9861. DEF( initial_yield, 1, 0, 0, none)
  9862. DEF( yield, 1, 1, 2, none)
  9863. DEF( yield_star, 1, 1, 2, none)
  9864. DEF(async_yield_star, 1, 1, 2, none)
  9865. DEF( await, 1, 1, 1, none)
  9866. /* arithmetic/logic operations */
  9867. DEF( neg, 1, 1, 1, none)
  9868. DEF( plus, 1, 1, 1, none)
  9869. DEF( dec, 1, 1, 1, none)
  9870. DEF( inc, 1, 1, 1, none)
  9871. DEF( post_dec, 1, 1, 2, none)
  9872. DEF( post_inc, 1, 1, 2, none)
  9873. DEF( dec_loc, 2, 0, 0, loc8)
  9874. DEF( inc_loc, 2, 0, 0, loc8)
  9875. DEF( add_loc, 2, 1, 0, loc8)
  9876. DEF( not, 1, 1, 1, none)
  9877. DEF( lnot, 1, 1, 1, none)
  9878. DEF( typeof, 1, 1, 1, none)
  9879. DEF( delete, 1, 2, 1, none)
  9880. DEF( delete_var, 5, 0, 1, atom)
  9881. /* warning: order matters (see js_parse_assign_expr) */
  9882. DEF( mul, 1, 2, 1, none)
  9883. DEF( div, 1, 2, 1, none)
  9884. DEF( mod, 1, 2, 1, none)
  9885. DEF( add, 1, 2, 1, none)
  9886. DEF( sub, 1, 2, 1, none)
  9887. DEF( shl, 1, 2, 1, none)
  9888. DEF( sar, 1, 2, 1, none)
  9889. DEF( shr, 1, 2, 1, none)
  9890. DEF( and, 1, 2, 1, none)
  9891. DEF( xor, 1, 2, 1, none)
  9892. DEF( or, 1, 2, 1, none)
  9893. DEF( pow, 1, 2, 1, none)
  9894. DEF( lt, 1, 2, 1, none)
  9895. DEF( lte, 1, 2, 1, none)
  9896. DEF( gt, 1, 2, 1, none)
  9897. DEF( gte, 1, 2, 1, none)
  9898. DEF( instanceof, 1, 2, 1, none)
  9899. DEF( in, 1, 2, 1, none)
  9900. DEF( eq, 1, 2, 1, none)
  9901. DEF( neq, 1, 2, 1, none)
  9902. DEF( strict_eq, 1, 2, 1, none)
  9903. DEF( strict_neq, 1, 2, 1, none)
  9904. DEF(is_undefined_or_null, 1, 1, 1, none)
  9905. DEF( private_in, 1, 2, 1, none)
  9906. /* must be the last non short and non temporary opcode */
  9907. DEF( nop, 1, 0, 0, none)
  9908. /* temporary opcodes: never emitted in the final bytecode */
  9909. def( enter_scope, 3, 0, 0, u16) /* emitted in phase 1, removed in phase 2 */
  9910. def( leave_scope, 3, 0, 0, u16) /* emitted in phase 1, removed in phase 2 */
  9911. def( label, 5, 0, 0, label) /* emitted in phase 1, removed in phase 3 */
  9912. def(scope_get_var_undef, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */
  9913. def( scope_get_var, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */
  9914. def( scope_put_var, 7, 1, 0, atom_u16) /* emitted in phase 1, removed in phase 2 */
  9915. def(scope_delete_var, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */
  9916. def( scope_make_ref, 11, 0, 2, atom_label_u16) /* emitted in phase 1, removed in phase 2 */
  9917. def( scope_get_ref, 7, 0, 2, atom_u16) /* emitted in phase 1, removed in phase 2 */
  9918. def(scope_put_var_init, 7, 0, 2, atom_u16) /* emitted in phase 1, removed in phase 2 */
  9919. def(scope_get_private_field, 7, 1, 1, atom_u16) /* obj -> value, emitted in phase 1, removed in phase 2 */
  9920. def(scope_get_private_field2, 7, 1, 2, atom_u16) /* obj -> obj value, emitted in phase 1, removed in phase 2 */
  9921. def(scope_put_private_field, 7, 2, 0, atom_u16) /* obj value ->, emitted in phase 1, removed in phase 2 */
  9922. def(scope_in_private_field, 7, 1, 1, atom_u16) /* obj -> res emitted in phase 1, removed in phase 2 */
  9923. def(get_field_opt_chain, 5, 1, 1, atom) /* emitted in phase 1, removed in phase 2 */
  9924. def(get_array_el_opt_chain, 1, 2, 1, none) /* emitted in phase 1, removed in phase 2 */
  9925. def( set_class_name, 5, 1, 1, u32) /* emitted in phase 1, removed in phase 2 */
  9926. def( source_loc, 9, 0, 0, u32x2) /* emitted in phase 1, removed in phase 3 */
  9927. DEF( push_minus1, 1, 0, 1, none_int)
  9928. DEF( push_0, 1, 0, 1, none_int)
  9929. DEF( push_1, 1, 0, 1, none_int)
  9930. DEF( push_2, 1, 0, 1, none_int)
  9931. DEF( push_3, 1, 0, 1, none_int)
  9932. DEF( push_4, 1, 0, 1, none_int)
  9933. DEF( push_5, 1, 0, 1, none_int)
  9934. DEF( push_6, 1, 0, 1, none_int)
  9935. DEF( push_7, 1, 0, 1, none_int)
  9936. DEF( push_i8, 2, 0, 1, i8)
  9937. DEF( push_i16, 3, 0, 1, i16)
  9938. DEF( push_const8, 2, 0, 1, const8)
  9939. DEF( fclosure8, 2, 0, 1, const8) /* must follow push_const8 */
  9940. DEF(push_empty_string, 1, 0, 1, none)
  9941. DEF( get_loc8, 2, 0, 1, loc8)
  9942. DEF( put_loc8, 2, 1, 0, loc8)
  9943. DEF( set_loc8, 2, 1, 1, loc8)
  9944. DEF( get_loc0_loc1, 1, 0, 2, none_loc)
  9945. DEF( get_loc0, 1, 0, 1, none_loc)
  9946. DEF( get_loc1, 1, 0, 1, none_loc)
  9947. DEF( get_loc2, 1, 0, 1, none_loc)
  9948. DEF( get_loc3, 1, 0, 1, none_loc)
  9949. DEF( put_loc0, 1, 1, 0, none_loc)
  9950. DEF( put_loc1, 1, 1, 0, none_loc)
  9951. DEF( put_loc2, 1, 1, 0, none_loc)
  9952. DEF( put_loc3, 1, 1, 0, none_loc)
  9953. DEF( set_loc0, 1, 1, 1, none_loc)
  9954. DEF( set_loc1, 1, 1, 1, none_loc)
  9955. DEF( set_loc2, 1, 1, 1, none_loc)
  9956. DEF( set_loc3, 1, 1, 1, none_loc)
  9957. DEF( get_arg0, 1, 0, 1, none_arg)
  9958. DEF( get_arg1, 1, 0, 1, none_arg)
  9959. DEF( get_arg2, 1, 0, 1, none_arg)
  9960. DEF( get_arg3, 1, 0, 1, none_arg)
  9961. DEF( put_arg0, 1, 1, 0, none_arg)
  9962. DEF( put_arg1, 1, 1, 0, none_arg)
  9963. DEF( put_arg2, 1, 1, 0, none_arg)
  9964. DEF( put_arg3, 1, 1, 0, none_arg)
  9965. DEF( set_arg0, 1, 1, 1, none_arg)
  9966. DEF( set_arg1, 1, 1, 1, none_arg)
  9967. DEF( set_arg2, 1, 1, 1, none_arg)
  9968. DEF( set_arg3, 1, 1, 1, none_arg)
  9969. DEF( get_var_ref0, 1, 0, 1, none_var_ref)
  9970. DEF( get_var_ref1, 1, 0, 1, none_var_ref)
  9971. DEF( get_var_ref2, 1, 0, 1, none_var_ref)
  9972. DEF( get_var_ref3, 1, 0, 1, none_var_ref)
  9973. DEF( put_var_ref0, 1, 1, 0, none_var_ref)
  9974. DEF( put_var_ref1, 1, 1, 0, none_var_ref)
  9975. DEF( put_var_ref2, 1, 1, 0, none_var_ref)
  9976. DEF( put_var_ref3, 1, 1, 0, none_var_ref)
  9977. DEF( set_var_ref0, 1, 1, 1, none_var_ref)
  9978. DEF( set_var_ref1, 1, 1, 1, none_var_ref)
  9979. DEF( set_var_ref2, 1, 1, 1, none_var_ref)
  9980. DEF( set_var_ref3, 1, 1, 1, none_var_ref)
  9981. DEF( get_length, 1, 1, 1, none)
  9982. DEF( if_false8, 2, 1, 0, label8)
  9983. DEF( if_true8, 2, 1, 0, label8) /* must come after if_false8 */
  9984. DEF( goto8, 2, 0, 0, label8) /* must come after if_true8 */
  9985. DEF( goto16, 3, 0, 0, label16)
  9986. DEF( call0, 1, 1, 1, npopx)
  9987. DEF( call1, 1, 1, 1, npopx)
  9988. DEF( call2, 1, 1, 1, npopx)
  9989. DEF( call3, 1, 1, 1, npopx)
  9990. DEF( is_undefined, 1, 1, 1, none)
  9991. DEF( is_null, 1, 1, 1, none)
  9992. DEF(typeof_is_undefined, 1, 1, 1, none)
  9993. DEF( typeof_is_function, 1, 1, 1, none)
  9994. #undef DEF
  9995. #undef def
  9996. #endif /* DEF */
  9997. #undef def
  9998. #undef DEF
  9999. #undef FMT
  10000. OP_COUNT, /* excluding temporary opcodes */
  10001. /* temporary opcodes : overlap with the short opcodes */
  10002. OP_TEMP_START = OP_nop + 1,
  10003. OP___dummy = OP_TEMP_START - 1,
  10004. #define FMT(f)
  10005. #define DEF(id, size, n_pop, n_push, f)
  10006. #define def(id, size, n_pop, n_push, f) OP_ ## id,
  10007. /*
  10008. * QuickJS opcode definitions
  10009. *
  10010. * Copyright (c) 2017-2018 Fabrice Bellard
  10011. * Copyright (c) 2017-2018 Charlie Gordon
  10012. *
  10013. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10014. * of this software and associated documentation files (the "Software"), to deal
  10015. * in the Software without restriction, including without limitation the rights
  10016. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10017. * copies of the Software, and to permit persons to whom the Software is
  10018. * furnished to do so, subject to the following conditions:
  10019. *
  10020. * The above copyright notice and this permission notice shall be included in
  10021. * all copies or substantial portions of the Software.
  10022. *
  10023. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  10024. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  10025. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  10026. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  10027. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  10028. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  10029. * THE SOFTWARE.
  10030. */
  10031. #ifdef FMT
  10032. FMT(none)
  10033. FMT(none_int)
  10034. FMT(none_loc)
  10035. FMT(none_arg)
  10036. FMT(none_var_ref)
  10037. FMT(u8)
  10038. FMT(i8)
  10039. FMT(loc8)
  10040. FMT(const8)
  10041. FMT(label8)
  10042. FMT(u16)
  10043. FMT(i16)
  10044. FMT(label16)
  10045. FMT(npop)
  10046. FMT(npopx)
  10047. FMT(npop_u16)
  10048. FMT(loc)
  10049. FMT(arg)
  10050. FMT(var_ref)
  10051. FMT(u32)
  10052. FMT(u32x2)
  10053. FMT(i32)
  10054. FMT(const)
  10055. FMT(label)
  10056. FMT(atom)
  10057. FMT(atom_u8)
  10058. FMT(atom_u16)
  10059. FMT(atom_label_u8)
  10060. FMT(atom_label_u16)
  10061. FMT(label_u16)
  10062. #undef FMT
  10063. #endif /* FMT */
  10064. #ifdef DEF
  10065. #ifndef def
  10066. #define def(id, size, n_pop, n_push, f) DEF(id, size, n_pop, n_push, f)
  10067. #endif
  10068. DEF(invalid, 1, 0, 0, none) /* never emitted */
  10069. /* push values */
  10070. DEF( push_i32, 5, 0, 1, i32)
  10071. DEF( push_const, 5, 0, 1, const)
  10072. DEF( fclosure, 5, 0, 1, const) /* must follow push_const */
  10073. DEF(push_atom_value, 5, 0, 1, atom)
  10074. DEF( private_symbol, 5, 0, 1, atom)
  10075. DEF( undefined, 1, 0, 1, none)
  10076. DEF( null, 1, 0, 1, none)
  10077. DEF( push_this, 1, 0, 1, none) /* only used at the start of a function */
  10078. DEF( push_false, 1, 0, 1, none)
  10079. DEF( push_true, 1, 0, 1, none)
  10080. DEF( object, 1, 0, 1, none)
  10081. DEF( special_object, 2, 0, 1, u8) /* only used at the start of a function */
  10082. DEF( rest, 3, 0, 1, u16) /* only used at the start of a function */
  10083. DEF( drop, 1, 1, 0, none) /* a -> */
  10084. DEF( nip, 1, 2, 1, none) /* a b -> b */
  10085. DEF( nip1, 1, 3, 2, none) /* a b c -> b c */
  10086. DEF( dup, 1, 1, 2, none) /* a -> a a */
  10087. DEF( dup1, 1, 2, 3, none) /* a b -> a a b */
  10088. DEF( dup2, 1, 2, 4, none) /* a b -> a b a b */
  10089. DEF( dup3, 1, 3, 6, none) /* a b c -> a b c a b c */
  10090. DEF( insert2, 1, 2, 3, none) /* obj a -> a obj a (dup_x1) */
  10091. DEF( insert3, 1, 3, 4, none) /* obj prop a -> a obj prop a (dup_x2) */
  10092. DEF( insert4, 1, 4, 5, none) /* this obj prop a -> a this obj prop a */
  10093. DEF( perm3, 1, 3, 3, none) /* obj a b -> a obj b */
  10094. DEF( perm4, 1, 4, 4, none) /* obj prop a b -> a obj prop b */
  10095. DEF( perm5, 1, 5, 5, none) /* this obj prop a b -> a this obj prop b */
  10096. DEF( swap, 1, 2, 2, none) /* a b -> b a */
  10097. DEF( swap2, 1, 4, 4, none) /* a b c d -> c d a b */
  10098. DEF( rot3l, 1, 3, 3, none) /* x a b -> a b x */
  10099. DEF( rot3r, 1, 3, 3, none) /* a b x -> x a b */
  10100. DEF( rot4l, 1, 4, 4, none) /* x a b c -> a b c x */
  10101. DEF( rot5l, 1, 5, 5, none) /* x a b c d -> a b c d x */
  10102. DEF(call_constructor, 3, 2, 1, npop) /* func new.target args -> ret. arguments are not counted in n_pop */
  10103. DEF( call, 3, 1, 1, npop) /* arguments are not counted in n_pop */
  10104. DEF( tail_call, 3, 1, 0, npop) /* arguments are not counted in n_pop */
  10105. DEF( call_method, 3, 2, 1, npop) /* arguments are not counted in n_pop */
  10106. DEF(tail_call_method, 3, 2, 0, npop) /* arguments are not counted in n_pop */
  10107. DEF( array_from, 3, 0, 1, npop) /* arguments are not counted in n_pop */
  10108. DEF( apply, 3, 3, 1, u16)
  10109. DEF( return, 1, 1, 0, none)
  10110. DEF( return_undef, 1, 0, 0, none)
  10111. DEF(check_ctor_return, 1, 1, 2, none)
  10112. DEF( check_ctor, 1, 0, 0, none)
  10113. DEF( init_ctor, 1, 0, 1, none)
  10114. DEF( check_brand, 1, 2, 2, none) /* this_obj func -> this_obj func */
  10115. DEF( add_brand, 1, 2, 0, none) /* this_obj home_obj -> */
  10116. DEF( return_async, 1, 1, 0, none)
  10117. DEF( throw, 1, 1, 0, none)
  10118. DEF( throw_error, 6, 0, 0, atom_u8)
  10119. DEF( eval, 5, 1, 1, npop_u16) /* func args... -> ret_val */
  10120. DEF( apply_eval, 3, 2, 1, u16) /* func array -> ret_eval */
  10121. DEF( regexp, 1, 2, 1, none) /* create a RegExp object from the pattern and a
  10122. bytecode string */
  10123. DEF( get_super, 1, 1, 1, none)
  10124. DEF( import, 1, 1, 1, none) /* dynamic module import */
  10125. DEF( check_var, 5, 0, 1, atom) /* check if a variable exists */
  10126. DEF( get_var_undef, 5, 0, 1, atom) /* push undefined if the variable does not exist */
  10127. DEF( get_var, 5, 0, 1, atom) /* throw an exception if the variable does not exist */
  10128. DEF( put_var, 5, 1, 0, atom) /* must come after get_var */
  10129. DEF( put_var_init, 5, 1, 0, atom) /* must come after put_var. Used to initialize a global lexical variable */
  10130. DEF( put_var_strict, 5, 2, 0, atom) /* for strict mode variable write */
  10131. DEF( get_ref_value, 1, 2, 3, none)
  10132. DEF( put_ref_value, 1, 3, 0, none)
  10133. DEF( define_var, 6, 0, 0, atom_u8)
  10134. DEF(check_define_var, 6, 0, 0, atom_u8)
  10135. DEF( define_func, 6, 1, 0, atom_u8)
  10136. // order matters, see IC counterparts
  10137. DEF( get_field, 5, 1, 1, atom)
  10138. DEF( get_field2, 5, 1, 2, atom)
  10139. DEF( put_field, 5, 2, 0, atom)
  10140. DEF( get_private_field, 1, 2, 1, none) /* obj prop -> value */
  10141. DEF( put_private_field, 1, 3, 0, none) /* obj value prop -> */
  10142. DEF(define_private_field, 1, 3, 1, none) /* obj prop value -> obj */
  10143. DEF( get_array_el, 1, 2, 1, none)
  10144. DEF( get_array_el2, 1, 2, 2, none) /* obj prop -> obj value */
  10145. DEF( put_array_el, 1, 3, 0, none)
  10146. DEF(get_super_value, 1, 3, 1, none) /* this obj prop -> value */
  10147. DEF(put_super_value, 1, 4, 0, none) /* this obj prop value -> */
  10148. DEF( define_field, 5, 2, 1, atom)
  10149. DEF( set_name, 5, 1, 1, atom)
  10150. DEF(set_name_computed, 1, 2, 2, none)
  10151. DEF( set_proto, 1, 2, 1, none)
  10152. DEF(set_home_object, 1, 2, 2, none)
  10153. DEF(define_array_el, 1, 3, 2, none)
  10154. DEF( append, 1, 3, 2, none) /* append enumerated object, update length */
  10155. DEF(copy_data_properties, 2, 3, 3, u8)
  10156. DEF( define_method, 6, 2, 1, atom_u8)
  10157. DEF(define_method_computed, 2, 3, 1, u8) /* must come after define_method */
  10158. DEF( define_class, 6, 2, 2, atom_u8) /* parent ctor -> ctor proto */
  10159. DEF( define_class_computed, 6, 3, 3, atom_u8) /* field_name parent ctor -> field_name ctor proto (class with computed name) */
  10160. DEF( get_loc, 3, 0, 1, loc)
  10161. DEF( put_loc, 3, 1, 0, loc) /* must come after get_loc */
  10162. DEF( set_loc, 3, 1, 1, loc) /* must come after put_loc */
  10163. DEF( get_arg, 3, 0, 1, arg)
  10164. DEF( put_arg, 3, 1, 0, arg) /* must come after get_arg */
  10165. DEF( set_arg, 3, 1, 1, arg) /* must come after put_arg */
  10166. DEF( get_var_ref, 3, 0, 1, var_ref)
  10167. DEF( put_var_ref, 3, 1, 0, var_ref) /* must come after get_var_ref */
  10168. DEF( set_var_ref, 3, 1, 1, var_ref) /* must come after put_var_ref */
  10169. DEF(set_loc_uninitialized, 3, 0, 0, loc)
  10170. DEF( get_loc_check, 3, 0, 1, loc)
  10171. DEF( put_loc_check, 3, 1, 0, loc) /* must come after get_loc_check */
  10172. DEF( put_loc_check_init, 3, 1, 0, loc)
  10173. DEF(get_var_ref_check, 3, 0, 1, var_ref)
  10174. DEF(put_var_ref_check, 3, 1, 0, var_ref) /* must come after get_var_ref_check */
  10175. DEF(put_var_ref_check_init, 3, 1, 0, var_ref)
  10176. DEF( close_loc, 3, 0, 0, loc)
  10177. DEF( if_false, 5, 1, 0, label)
  10178. DEF( if_true, 5, 1, 0, label) /* must come after if_false */
  10179. DEF( goto, 5, 0, 0, label) /* must come after if_true */
  10180. DEF( catch, 5, 0, 1, label)
  10181. DEF( gosub, 5, 0, 0, label) /* used to execute the finally block */
  10182. DEF( ret, 1, 1, 0, none) /* used to return from the finally block */
  10183. DEF( nip_catch, 1, 2, 1, none) /* catch ... a -> a */
  10184. DEF( to_object, 1, 1, 1, none)
  10185. //DEF( to_string, 1, 1, 1, none)
  10186. DEF( to_propkey, 1, 1, 1, none)
  10187. DEF( to_propkey2, 1, 2, 2, none)
  10188. DEF( with_get_var, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */
  10189. DEF( with_put_var, 10, 2, 1, atom_label_u8) /* must be in the same order as scope_xxx */
  10190. DEF(with_delete_var, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */
  10191. DEF( with_make_ref, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */
  10192. DEF( with_get_ref, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */
  10193. DEF(with_get_ref_undef, 10, 1, 0, atom_label_u8)
  10194. DEF( make_loc_ref, 7, 0, 2, atom_u16)
  10195. DEF( make_arg_ref, 7, 0, 2, atom_u16)
  10196. DEF(make_var_ref_ref, 7, 0, 2, atom_u16)
  10197. DEF( make_var_ref, 5, 0, 2, atom)
  10198. DEF( for_in_start, 1, 1, 1, none)
  10199. DEF( for_of_start, 1, 1, 3, none)
  10200. DEF(for_await_of_start, 1, 1, 3, none)
  10201. DEF( for_in_next, 1, 1, 3, none)
  10202. DEF( for_of_next, 2, 3, 5, u8)
  10203. DEF(iterator_check_object, 1, 1, 1, none)
  10204. DEF(iterator_get_value_done, 1, 1, 2, none)
  10205. DEF( iterator_close, 1, 3, 0, none)
  10206. DEF( iterator_next, 1, 4, 4, none)
  10207. DEF( iterator_call, 2, 4, 5, u8)
  10208. DEF( initial_yield, 1, 0, 0, none)
  10209. DEF( yield, 1, 1, 2, none)
  10210. DEF( yield_star, 1, 1, 2, none)
  10211. DEF(async_yield_star, 1, 1, 2, none)
  10212. DEF( await, 1, 1, 1, none)
  10213. /* arithmetic/logic operations */
  10214. DEF( neg, 1, 1, 1, none)
  10215. DEF( plus, 1, 1, 1, none)
  10216. DEF( dec, 1, 1, 1, none)
  10217. DEF( inc, 1, 1, 1, none)
  10218. DEF( post_dec, 1, 1, 2, none)
  10219. DEF( post_inc, 1, 1, 2, none)
  10220. DEF( dec_loc, 2, 0, 0, loc8)
  10221. DEF( inc_loc, 2, 0, 0, loc8)
  10222. DEF( add_loc, 2, 1, 0, loc8)
  10223. DEF( not, 1, 1, 1, none)
  10224. DEF( lnot, 1, 1, 1, none)
  10225. DEF( typeof, 1, 1, 1, none)
  10226. DEF( delete, 1, 2, 1, none)
  10227. DEF( delete_var, 5, 0, 1, atom)
  10228. /* warning: order matters (see js_parse_assign_expr) */
  10229. DEF( mul, 1, 2, 1, none)
  10230. DEF( div, 1, 2, 1, none)
  10231. DEF( mod, 1, 2, 1, none)
  10232. DEF( add, 1, 2, 1, none)
  10233. DEF( sub, 1, 2, 1, none)
  10234. DEF( shl, 1, 2, 1, none)
  10235. DEF( sar, 1, 2, 1, none)
  10236. DEF( shr, 1, 2, 1, none)
  10237. DEF( and, 1, 2, 1, none)
  10238. DEF( xor, 1, 2, 1, none)
  10239. DEF( or, 1, 2, 1, none)
  10240. DEF( pow, 1, 2, 1, none)
  10241. DEF( lt, 1, 2, 1, none)
  10242. DEF( lte, 1, 2, 1, none)
  10243. DEF( gt, 1, 2, 1, none)
  10244. DEF( gte, 1, 2, 1, none)
  10245. DEF( instanceof, 1, 2, 1, none)
  10246. DEF( in, 1, 2, 1, none)
  10247. DEF( eq, 1, 2, 1, none)
  10248. DEF( neq, 1, 2, 1, none)
  10249. DEF( strict_eq, 1, 2, 1, none)
  10250. DEF( strict_neq, 1, 2, 1, none)
  10251. DEF(is_undefined_or_null, 1, 1, 1, none)
  10252. DEF( private_in, 1, 2, 1, none)
  10253. /* must be the last non short and non temporary opcode */
  10254. DEF( nop, 1, 0, 0, none)
  10255. /* temporary opcodes: never emitted in the final bytecode */
  10256. def( enter_scope, 3, 0, 0, u16) /* emitted in phase 1, removed in phase 2 */
  10257. def( leave_scope, 3, 0, 0, u16) /* emitted in phase 1, removed in phase 2 */
  10258. def( label, 5, 0, 0, label) /* emitted in phase 1, removed in phase 3 */
  10259. def(scope_get_var_undef, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */
  10260. def( scope_get_var, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */
  10261. def( scope_put_var, 7, 1, 0, atom_u16) /* emitted in phase 1, removed in phase 2 */
  10262. def(scope_delete_var, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */
  10263. def( scope_make_ref, 11, 0, 2, atom_label_u16) /* emitted in phase 1, removed in phase 2 */
  10264. def( scope_get_ref, 7, 0, 2, atom_u16) /* emitted in phase 1, removed in phase 2 */
  10265. def(scope_put_var_init, 7, 0, 2, atom_u16) /* emitted in phase 1, removed in phase 2 */
  10266. def(scope_get_private_field, 7, 1, 1, atom_u16) /* obj -> value, emitted in phase 1, removed in phase 2 */
  10267. def(scope_get_private_field2, 7, 1, 2, atom_u16) /* obj -> obj value, emitted in phase 1, removed in phase 2 */
  10268. def(scope_put_private_field, 7, 2, 0, atom_u16) /* obj value ->, emitted in phase 1, removed in phase 2 */
  10269. def(scope_in_private_field, 7, 1, 1, atom_u16) /* obj -> res emitted in phase 1, removed in phase 2 */
  10270. def(get_field_opt_chain, 5, 1, 1, atom) /* emitted in phase 1, removed in phase 2 */
  10271. def(get_array_el_opt_chain, 1, 2, 1, none) /* emitted in phase 1, removed in phase 2 */
  10272. def( set_class_name, 5, 1, 1, u32) /* emitted in phase 1, removed in phase 2 */
  10273. def( source_loc, 9, 0, 0, u32x2) /* emitted in phase 1, removed in phase 3 */
  10274. DEF( push_minus1, 1, 0, 1, none_int)
  10275. DEF( push_0, 1, 0, 1, none_int)
  10276. DEF( push_1, 1, 0, 1, none_int)
  10277. DEF( push_2, 1, 0, 1, none_int)
  10278. DEF( push_3, 1, 0, 1, none_int)
  10279. DEF( push_4, 1, 0, 1, none_int)
  10280. DEF( push_5, 1, 0, 1, none_int)
  10281. DEF( push_6, 1, 0, 1, none_int)
  10282. DEF( push_7, 1, 0, 1, none_int)
  10283. DEF( push_i8, 2, 0, 1, i8)
  10284. DEF( push_i16, 3, 0, 1, i16)
  10285. DEF( push_const8, 2, 0, 1, const8)
  10286. DEF( fclosure8, 2, 0, 1, const8) /* must follow push_const8 */
  10287. DEF(push_empty_string, 1, 0, 1, none)
  10288. DEF( get_loc8, 2, 0, 1, loc8)
  10289. DEF( put_loc8, 2, 1, 0, loc8)
  10290. DEF( set_loc8, 2, 1, 1, loc8)
  10291. DEF( get_loc0_loc1, 1, 0, 2, none_loc)
  10292. DEF( get_loc0, 1, 0, 1, none_loc)
  10293. DEF( get_loc1, 1, 0, 1, none_loc)
  10294. DEF( get_loc2, 1, 0, 1, none_loc)
  10295. DEF( get_loc3, 1, 0, 1, none_loc)
  10296. DEF( put_loc0, 1, 1, 0, none_loc)
  10297. DEF( put_loc1, 1, 1, 0, none_loc)
  10298. DEF( put_loc2, 1, 1, 0, none_loc)
  10299. DEF( put_loc3, 1, 1, 0, none_loc)
  10300. DEF( set_loc0, 1, 1, 1, none_loc)
  10301. DEF( set_loc1, 1, 1, 1, none_loc)
  10302. DEF( set_loc2, 1, 1, 1, none_loc)
  10303. DEF( set_loc3, 1, 1, 1, none_loc)
  10304. DEF( get_arg0, 1, 0, 1, none_arg)
  10305. DEF( get_arg1, 1, 0, 1, none_arg)
  10306. DEF( get_arg2, 1, 0, 1, none_arg)
  10307. DEF( get_arg3, 1, 0, 1, none_arg)
  10308. DEF( put_arg0, 1, 1, 0, none_arg)
  10309. DEF( put_arg1, 1, 1, 0, none_arg)
  10310. DEF( put_arg2, 1, 1, 0, none_arg)
  10311. DEF( put_arg3, 1, 1, 0, none_arg)
  10312. DEF( set_arg0, 1, 1, 1, none_arg)
  10313. DEF( set_arg1, 1, 1, 1, none_arg)
  10314. DEF( set_arg2, 1, 1, 1, none_arg)
  10315. DEF( set_arg3, 1, 1, 1, none_arg)
  10316. DEF( get_var_ref0, 1, 0, 1, none_var_ref)
  10317. DEF( get_var_ref1, 1, 0, 1, none_var_ref)
  10318. DEF( get_var_ref2, 1, 0, 1, none_var_ref)
  10319. DEF( get_var_ref3, 1, 0, 1, none_var_ref)
  10320. DEF( put_var_ref0, 1, 1, 0, none_var_ref)
  10321. DEF( put_var_ref1, 1, 1, 0, none_var_ref)
  10322. DEF( put_var_ref2, 1, 1, 0, none_var_ref)
  10323. DEF( put_var_ref3, 1, 1, 0, none_var_ref)
  10324. DEF( set_var_ref0, 1, 1, 1, none_var_ref)
  10325. DEF( set_var_ref1, 1, 1, 1, none_var_ref)
  10326. DEF( set_var_ref2, 1, 1, 1, none_var_ref)
  10327. DEF( set_var_ref3, 1, 1, 1, none_var_ref)
  10328. DEF( get_length, 1, 1, 1, none)
  10329. DEF( if_false8, 2, 1, 0, label8)
  10330. DEF( if_true8, 2, 1, 0, label8) /* must come after if_false8 */
  10331. DEF( goto8, 2, 0, 0, label8) /* must come after if_true8 */
  10332. DEF( goto16, 3, 0, 0, label16)
  10333. DEF( call0, 1, 1, 1, npopx)
  10334. DEF( call1, 1, 1, 1, npopx)
  10335. DEF( call2, 1, 1, 1, npopx)
  10336. DEF( call3, 1, 1, 1, npopx)
  10337. DEF( is_undefined, 1, 1, 1, none)
  10338. DEF( is_null, 1, 1, 1, none)
  10339. DEF(typeof_is_undefined, 1, 1, 1, none)
  10340. DEF( typeof_is_function, 1, 1, 1, none)
  10341. #undef DEF
  10342. #undef def
  10343. #endif /* DEF */
  10344. #undef def
  10345. #undef DEF
  10346. #undef FMT
  10347. OP_TEMP_END,
  10348. } OPCodeEnum;
  10349. static int JS_InitAtoms(JSRuntime *rt);
  10350. static JSAtom __JS_NewAtomInit(JSRuntime *rt, const char *str, int len,
  10351. int atom_type);
  10352. static void JS_FreeAtomStruct(JSRuntime *rt, JSAtomStruct *p);
  10353. static void free_function_bytecode(JSRuntime *rt, JSFunctionBytecode *b);
  10354. static JSValue js_call_c_function(JSContext *ctx, JSValueConst func_obj,
  10355. JSValueConst this_obj,
  10356. int argc, JSValueConst *argv, int flags);
  10357. static JSValue js_call_bound_function(JSContext *ctx, JSValueConst func_obj,
  10358. JSValueConst this_obj,
  10359. int argc, JSValueConst *argv, int flags);
  10360. static JSValue JS_CallInternal(JSContext *ctx, JSValueConst func_obj,
  10361. JSValueConst this_obj, JSValueConst new_target,
  10362. int argc, JSValueConst *argv, int flags);
  10363. static JSValue JS_CallConstructorInternal(JSContext *ctx,
  10364. JSValueConst func_obj,
  10365. JSValueConst new_target,
  10366. int argc, JSValueConst *argv, int flags);
  10367. static JSValue JS_CallFree(JSContext *ctx, JSValue func_obj, JSValueConst this_obj,
  10368. int argc, JSValueConst *argv);
  10369. static JSValue JS_InvokeFree(JSContext *ctx, JSValue this_val, JSAtom atom,
  10370. int argc, JSValueConst *argv);
  10371. static __exception int JS_ToArrayLengthFree(JSContext *ctx, uint32_t *plen,
  10372. JSValue val, bool is_array_ctor);
  10373. static JSValue JS_EvalObject(JSContext *ctx, JSValueConst this_obj,
  10374. JSValueConst val, int flags, int scope_idx);
  10375. JSValue JS_PRINTF_FORMAT_ATTR(2, 3) JS_ThrowInternalError(JSContext *ctx, JS_PRINTF_FORMAT const char *fmt, ...);
  10376. static __maybe_unused void JS_DumpString(JSRuntime *rt, JSString *p);
  10377. static __maybe_unused void JS_DumpObjectHeader(JSRuntime *rt);
  10378. static __maybe_unused void JS_DumpObject(JSRuntime *rt, JSObject *p);
  10379. static __maybe_unused void JS_DumpGCObject(JSRuntime *rt, JSGCObjectHeader *p);
  10380. static __maybe_unused void JS_DumpValue(JSRuntime *rt, JSValueConst val);
  10381. static __maybe_unused void JS_DumpAtoms(JSRuntime *rt);
  10382. static __maybe_unused void JS_DumpShapes(JSRuntime *rt);
  10383. static JSValue js_function_apply(JSContext *ctx, JSValueConst this_val,
  10384. int argc, JSValueConst *argv, int magic);
  10385. static void js_array_finalizer(JSRuntime *rt, JSValueConst val);
  10386. static void js_array_mark(JSRuntime *rt, JSValueConst val,
  10387. JS_MarkFunc *mark_func);
  10388. static void js_object_data_finalizer(JSRuntime *rt, JSValueConst val);
  10389. static void js_object_data_mark(JSRuntime *rt, JSValueConst val,
  10390. JS_MarkFunc *mark_func);
  10391. static void js_c_function_finalizer(JSRuntime *rt, JSValueConst val);
  10392. static void js_c_function_mark(JSRuntime *rt, JSValueConst val,
  10393. JS_MarkFunc *mark_func);
  10394. static void js_bytecode_function_finalizer(JSRuntime *rt, JSValueConst val);
  10395. static void js_bytecode_function_mark(JSRuntime *rt, JSValueConst val,
  10396. JS_MarkFunc *mark_func);
  10397. static void js_bound_function_finalizer(JSRuntime *rt, JSValueConst val);
  10398. static void js_bound_function_mark(JSRuntime *rt, JSValueConst val,
  10399. JS_MarkFunc *mark_func);
  10400. static void js_for_in_iterator_finalizer(JSRuntime *rt, JSValueConst val);
  10401. static void js_for_in_iterator_mark(JSRuntime *rt, JSValueConst val,
  10402. JS_MarkFunc *mark_func);
  10403. static void js_regexp_finalizer(JSRuntime *rt, JSValueConst val);
  10404. static void js_array_buffer_finalizer(JSRuntime *rt, JSValueConst val);
  10405. static void js_typed_array_finalizer(JSRuntime *rt, JSValueConst val);
  10406. static void js_typed_array_mark(JSRuntime *rt, JSValueConst val,
  10407. JS_MarkFunc *mark_func);
  10408. static void js_proxy_finalizer(JSRuntime *rt, JSValueConst val);
  10409. static void js_proxy_mark(JSRuntime *rt, JSValueConst val,
  10410. JS_MarkFunc *mark_func);
  10411. static void js_map_finalizer(JSRuntime *rt, JSValueConst val);
  10412. static void js_map_mark(JSRuntime *rt, JSValueConst val,
  10413. JS_MarkFunc *mark_func);
  10414. static void js_map_iterator_finalizer(JSRuntime *rt, JSValueConst val);
  10415. static void js_map_iterator_mark(JSRuntime *rt, JSValueConst val,
  10416. JS_MarkFunc *mark_func);
  10417. static void js_array_iterator_finalizer(JSRuntime *rt, JSValueConst val);
  10418. static void js_array_iterator_mark(JSRuntime *rt, JSValueConst val,
  10419. JS_MarkFunc *mark_func);
  10420. static void js_iterator_helper_finalizer(JSRuntime *rt, JSValueConst val);
  10421. static void js_iterator_helper_mark(JSRuntime *rt, JSValueConst val,
  10422. JS_MarkFunc *mark_func);
  10423. static void js_iterator_wrap_finalizer(JSRuntime *rt, JSValueConst val);
  10424. static void js_iterator_wrap_mark(JSRuntime *rt, JSValueConst val,
  10425. JS_MarkFunc *mark_func);
  10426. static void js_regexp_string_iterator_finalizer(JSRuntime *rt,
  10427. JSValueConst val);
  10428. static void js_regexp_string_iterator_mark(JSRuntime *rt, JSValueConst val,
  10429. JS_MarkFunc *mark_func);
  10430. static void js_generator_finalizer(JSRuntime *rt, JSValueConst val);
  10431. static void js_generator_mark(JSRuntime *rt, JSValueConst val,
  10432. JS_MarkFunc *mark_func);
  10433. static void js_promise_finalizer(JSRuntime *rt, JSValueConst val);
  10434. static void js_promise_mark(JSRuntime *rt, JSValueConst val,
  10435. JS_MarkFunc *mark_func);
  10436. static void js_promise_resolve_function_finalizer(JSRuntime *rt, JSValueConst val);
  10437. static void js_promise_resolve_function_mark(JSRuntime *rt, JSValueConst val,
  10438. JS_MarkFunc *mark_func);
  10439. #define HINT_STRING 0
  10440. #define HINT_NUMBER 1
  10441. #define HINT_NONE 2
  10442. #define HINT_FORCE_ORDINARY (1 << 4) // don't try Symbol.toPrimitive
  10443. static JSValue JS_ToPrimitiveFree(JSContext *ctx, JSValue val, int hint);
  10444. static JSValue JS_ToStringFree(JSContext *ctx, JSValue val);
  10445. static int JS_ToBoolFree(JSContext *ctx, JSValue val);
  10446. static int JS_ToInt32Free(JSContext *ctx, int32_t *pres, JSValue val);
  10447. static int JS_ToFloat64Free(JSContext *ctx, double *pres, JSValue val);
  10448. static int JS_ToUint8ClampFree(JSContext *ctx, int32_t *pres, JSValue val);
  10449. static JSValue js_new_string8_len(JSContext *ctx, const char *buf, int len);
  10450. static JSValue js_compile_regexp(JSContext *ctx, JSValueConst pattern,
  10451. JSValueConst flags);
  10452. static JSValue js_regexp_constructor_internal(JSContext *ctx, JSValueConst ctor,
  10453. JSValue pattern, JSValue bc);
  10454. static void gc_decref(JSRuntime *rt);
  10455. static int JS_NewClass1(JSRuntime *rt, JSClassID class_id,
  10456. const JSClassDef *class_def, JSAtom name);
  10457. static JSValue js_array_push(JSContext *ctx, JSValueConst this_val,
  10458. int argc, JSValueConst *argv, int unshift);
  10459. typedef enum JSStrictEqModeEnum {
  10460. JS_EQ_STRICT,
  10461. JS_EQ_SAME_VALUE,
  10462. JS_EQ_SAME_VALUE_ZERO,
  10463. } JSStrictEqModeEnum;
  10464. static bool js_strict_eq2(JSContext *ctx, JSValue op1, JSValue op2,
  10465. JSStrictEqModeEnum eq_mode);
  10466. static bool js_strict_eq(JSContext *ctx, JSValue op1, JSValue op2);
  10467. static bool js_same_value(JSContext *ctx, JSValueConst op1, JSValueConst op2);
  10468. static bool js_same_value_zero(JSContext *ctx, JSValueConst op1, JSValueConst op2);
  10469. static JSValue JS_ToObjectFree(JSContext *ctx, JSValue val);
  10470. static JSProperty *add_property(JSContext *ctx,
  10471. JSObject *p, JSAtom prop, int prop_flags);
  10472. static JSValue JS_NewBigInt(JSContext *ctx);
  10473. static inline bf_t *JS_GetBigInt(JSValueConst val)
  10474. {
  10475. JSBigInt *p = JS_VALUE_GET_PTR(val);
  10476. return &p->num;
  10477. }
  10478. static JSValue JS_CompactBigInt1(JSContext *ctx, JSValue val);
  10479. static JSValue JS_CompactBigInt(JSContext *ctx, JSValue val);
  10480. static int JS_ToBigInt64Free(JSContext *ctx, int64_t *pres, JSValue val);
  10481. static bf_t *JS_ToBigInt(JSContext *ctx, bf_t *buf, JSValueConst val);
  10482. static bf_t *JS_ToBigInt1(JSContext *ctx, bf_t *buf, JSValueConst val);
  10483. static void JS_FreeBigInt(JSContext *ctx, bf_t *a, bf_t *buf);
  10484. JSValue JS_ThrowOutOfMemory(JSContext *ctx);
  10485. static JSValue JS_ThrowTypeErrorRevokedProxy(JSContext *ctx);
  10486. static JSValue js_proxy_getPrototypeOf(JSContext *ctx, JSValueConst obj);
  10487. static int js_proxy_setPrototypeOf(JSContext *ctx, JSValueConst obj,
  10488. JSValueConst proto_val, bool throw_flag);
  10489. static int js_proxy_isExtensible(JSContext *ctx, JSValueConst obj);
  10490. static int js_proxy_preventExtensions(JSContext *ctx, JSValueConst obj);
  10491. static int js_proxy_isArray(JSContext *ctx, JSValueConst obj);
  10492. static int JS_CreateProperty(JSContext *ctx, JSObject *p,
  10493. JSAtom prop, JSValueConst val,
  10494. JSValueConst getter, JSValueConst setter,
  10495. int flags);
  10496. static int js_string_memcmp(JSString *p1, JSString *p2, int len);
  10497. static void reset_weak_ref(JSRuntime *rt, JSWeakRefRecord **first_weak_ref);
  10498. static bool is_valid_weakref_target(JSValueConst val);
  10499. static void insert_weakref_record(JSValueConst target,
  10500. struct JSWeakRefRecord *wr);
  10501. static JSValue js_array_buffer_constructor3(JSContext *ctx,
  10502. JSValueConst new_target,
  10503. uint64_t len, uint64_t *max_len,
  10504. JSClassID class_id,
  10505. uint8_t *buf,
  10506. JSFreeArrayBufferDataFunc *free_func,
  10507. void *opaque, bool alloc_flag);
  10508. static void js_array_buffer_free(JSRuntime *rt, void *opaque, void *ptr);
  10509. static JSArrayBuffer *js_get_array_buffer(JSContext *ctx, JSValueConst obj);
  10510. static bool array_buffer_is_resizable(const JSArrayBuffer *abuf);
  10511. static JSValue js_typed_array_constructor(JSContext *ctx,
  10512. JSValueConst this_val,
  10513. int argc, JSValueConst *argv,
  10514. int classid);
  10515. static JSValue js_typed_array_constructor_ta(JSContext *ctx,
  10516. JSValueConst new_target,
  10517. JSValueConst src_obj,
  10518. int classid, uint32_t len);
  10519. static bool is_typed_array(JSClassID class_id);
  10520. static bool typed_array_is_oob(JSObject *p);
  10521. static uint32_t typed_array_get_length(JSContext *ctx, JSObject *p);
  10522. static JSValue JS_ThrowTypeErrorDetachedArrayBuffer(JSContext *ctx);
  10523. static JSValue JS_ThrowTypeErrorArrayBufferOOB(JSContext *ctx);
  10524. static JSVarRef *get_var_ref(JSContext *ctx, JSStackFrame *sf, int var_idx,
  10525. bool is_arg);
  10526. static JSValue js_generator_function_call(JSContext *ctx, JSValueConst func_obj,
  10527. JSValueConst this_obj,
  10528. int argc, JSValueConst *argv,
  10529. int flags);
  10530. static void js_async_function_resolve_finalizer(JSRuntime *rt,
  10531. JSValueConst val);
  10532. static void js_async_function_resolve_mark(JSRuntime *rt, JSValueConst val,
  10533. JS_MarkFunc *mark_func);
  10534. static JSValue JS_EvalInternal(JSContext *ctx, JSValueConst this_obj,
  10535. const char *input, size_t input_len,
  10536. const char *filename, int line, int flags, int scope_idx);
  10537. static void js_free_module_def(JSContext *ctx, JSModuleDef *m);
  10538. static void js_mark_module_def(JSRuntime *rt, JSModuleDef *m,
  10539. JS_MarkFunc *mark_func);
  10540. static JSValue js_import_meta(JSContext *ctx);
  10541. static JSValue js_dynamic_import(JSContext *ctx, JSValueConst specifier);
  10542. static void free_var_ref(JSRuntime *rt, JSVarRef *var_ref);
  10543. static JSValue js_new_promise_capability(JSContext *ctx,
  10544. JSValue *resolving_funcs,
  10545. JSValueConst ctor);
  10546. static __exception int perform_promise_then(JSContext *ctx,
  10547. JSValueConst promise,
  10548. JSValueConst *resolve_reject,
  10549. JSValueConst *cap_resolving_funcs);
  10550. static JSValue js_promise_resolve(JSContext *ctx, JSValueConst this_val,
  10551. int argc, JSValueConst *argv, int magic);
  10552. static JSValue js_promise_then(JSContext *ctx, JSValueConst this_val,
  10553. int argc, JSValueConst *argv);
  10554. static bool js_string_eq(JSString *p1, JSString *p2);
  10555. static int js_string_compare(JSString *p1, JSString *p2);
  10556. static int JS_SetPropertyValue(JSContext *ctx, JSValueConst this_obj,
  10557. JSValue prop, JSValue val, int flags);
  10558. static int JS_NumberIsInteger(JSContext *ctx, JSValueConst val);
  10559. static bool JS_NumberIsNegativeOrMinusZero(JSContext *ctx, JSValueConst val);
  10560. static JSValue JS_ToNumberFree(JSContext *ctx, JSValue val);
  10561. static int JS_GetOwnPropertyInternal(JSContext *ctx, JSPropertyDescriptor *desc,
  10562. JSObject *p, JSAtom prop);
  10563. static void js_free_desc(JSContext *ctx, JSPropertyDescriptor *desc);
  10564. static void async_func_mark(JSRuntime *rt, JSAsyncFunctionState *s,
  10565. JS_MarkFunc *mark_func);
  10566. static void JS_AddIntrinsicBasicObjects(JSContext *ctx);
  10567. static void js_free_shape(JSRuntime *rt, JSShape *sh);
  10568. static void js_free_shape_null(JSRuntime *rt, JSShape *sh);
  10569. static int js_shape_prepare_update(JSContext *ctx, JSObject *p,
  10570. JSShapeProperty **pprs);
  10571. static int init_shape_hash(JSRuntime *rt);
  10572. static __exception int js_get_length32(JSContext *ctx, uint32_t *pres,
  10573. JSValueConst obj);
  10574. static __exception int js_get_length64(JSContext *ctx, int64_t *pres,
  10575. JSValueConst obj);
  10576. static __exception int js_set_length64(JSContext *ctx, JSValueConst obj,
  10577. int64_t len);
  10578. static void free_arg_list(JSContext *ctx, JSValue *tab, uint32_t len);
  10579. static JSValue *build_arg_list(JSContext *ctx, uint32_t *plen,
  10580. JSValueConst array_arg);
  10581. static JSValue js_create_array(JSContext *ctx, int len, JSValueConst *tab);
  10582. static bool js_get_fast_array(JSContext *ctx, JSValue obj,
  10583. JSValue **arrpp, uint32_t *countp);
  10584. static int expand_fast_array(JSContext *ctx, JSObject *p, uint32_t new_len);
  10585. static JSValue JS_CreateAsyncFromSyncIterator(JSContext *ctx,
  10586. JSValue sync_iter);
  10587. static void js_c_function_data_finalizer(JSRuntime *rt, JSValueConst val);
  10588. static void js_c_function_data_mark(JSRuntime *rt, JSValueConst val,
  10589. JS_MarkFunc *mark_func);
  10590. static JSValue js_c_function_data_call(JSContext *ctx, JSValueConst func_obj,
  10591. JSValueConst this_val,
  10592. int argc, JSValueConst *argv, int flags);
  10593. static JSAtom js_symbol_to_atom(JSContext *ctx, JSValueConst val);
  10594. static void add_gc_object(JSRuntime *rt, JSGCObjectHeader *h,
  10595. JSGCObjectTypeEnum type);
  10596. static void remove_gc_object(JSGCObjectHeader *h);
  10597. static void js_async_function_free0(JSRuntime *rt, JSAsyncFunctionData *s);
  10598. static JSValue js_instantiate_prototype(JSContext *ctx, JSObject *p, JSAtom atom, void *opaque);
  10599. static JSValue js_module_ns_autoinit(JSContext *ctx, JSObject *p, JSAtom atom,
  10600. void *opaque);
  10601. static JSValue JS_InstantiateFunctionListItem2(JSContext *ctx, JSObject *p,
  10602. JSAtom atom, void *opaque);
  10603. static void js_set_uncatchable_error(JSContext *ctx, JSValueConst val,
  10604. bool flag);
  10605. static JSValue js_new_callsite(JSContext *ctx, JSCallSiteData *csd);
  10606. static void js_new_callsite_data(JSContext *ctx, JSCallSiteData *csd, JSStackFrame *sf);
  10607. static void js_new_callsite_data2(JSContext *ctx, JSCallSiteData *csd, const char *filename, int line_num, int col_num);
  10608. static void _JS_AddIntrinsicCallSite(JSContext *ctx);
  10609. static void JS_SetOpaqueInternal(JSValueConst obj, void *opaque);
  10610. static const JSClassExoticMethods js_arguments_exotic_methods;
  10611. static const JSClassExoticMethods js_string_exotic_methods;
  10612. static const JSClassExoticMethods js_proxy_exotic_methods;
  10613. static const JSClassExoticMethods js_module_ns_exotic_methods;
  10614. static inline bool double_is_int32(double d)
  10615. {
  10616. uint64_t u, e;
  10617. JSFloat64Union t;
  10618. t.d = d;
  10619. u = t.u64;
  10620. e = ((u >> 52) & 0x7FF) - 1023;
  10621. if (e > 30) {
  10622. // accept 0, INT32_MIN, reject too large, too small, nan, inf, -0
  10623. return !u || (u == 0xc1e0000000000000);
  10624. } else {
  10625. // shift out sign, exponent and whole part bits
  10626. // value is fractional if remaining low bits are non-zero
  10627. return !(u << 12 << e);
  10628. }
  10629. }
  10630. static JSValue js_float64(double d)
  10631. {
  10632. return __JS_NewFloat64(d);
  10633. }
  10634. static int compare_u32(uint32_t a, uint32_t b)
  10635. {
  10636. return -(a < b) + (b < a); // -1, 0 or 1
  10637. }
  10638. static JSValue js_int32(int32_t v)
  10639. {
  10640. return JS_MKVAL(JS_TAG_INT, v);
  10641. }
  10642. static JSValue js_uint32(uint32_t v)
  10643. {
  10644. if (v <= INT32_MAX)
  10645. return js_int32(v);
  10646. else
  10647. return js_float64(v);
  10648. }
  10649. static JSValue js_int64(int64_t v)
  10650. {
  10651. if (v >= INT32_MIN && v <= INT32_MAX)
  10652. return js_int32(v);
  10653. else
  10654. return js_float64(v);
  10655. }
  10656. #define JS_NewInt64(ctx, val) js_int64(val)
  10657. static JSValue js_number(double d)
  10658. {
  10659. if (double_is_int32(d))
  10660. return js_int32((int32_t)d);
  10661. else
  10662. return js_float64(d);
  10663. }
  10664. JSValue JS_NewNumber(JSContext *ctx, double d)
  10665. {
  10666. return js_number(d);
  10667. }
  10668. static JSValue js_bool(bool v)
  10669. {
  10670. return JS_MKVAL(JS_TAG_BOOL, (v != 0));
  10671. }
  10672. static JSValue js_dup(JSValueConst v)
  10673. {
  10674. if (JS_VALUE_HAS_REF_COUNT(v)) {
  10675. JSRefCountHeader *p = (JSRefCountHeader *)JS_VALUE_GET_PTR(v);
  10676. p->ref_count++;
  10677. }
  10678. return unsafe_unconst(v);
  10679. }
  10680. JSValue JS_DupValue(JSContext *ctx, JSValueConst v)
  10681. {
  10682. return js_dup(v);
  10683. }
  10684. JSValue JS_DupValueRT(JSRuntime *rt, JSValueConst v)
  10685. {
  10686. return js_dup(v);
  10687. }
  10688. static void js_trigger_gc(JSRuntime *rt, size_t size)
  10689. {
  10690. bool force_gc;
  10691. #ifdef FORCE_GC_AT_MALLOC
  10692. force_gc = true;
  10693. #else
  10694. force_gc = ((rt->malloc_state.malloc_size + size) >
  10695. rt->malloc_gc_threshold);
  10696. #endif
  10697. if (force_gc) {
  10698. #ifdef ENABLE_DUMPS // JS_DUMP_GC
  10699. if (check_dump_flag(rt, JS_DUMP_GC)) {
  10700. printf("GC: size=%zd\n", rt->malloc_state.malloc_size);
  10701. }
  10702. #endif
  10703. JS_RunGC(rt);
  10704. rt->malloc_gc_threshold = rt->malloc_state.malloc_size +
  10705. (rt->malloc_state.malloc_size >> 1);
  10706. }
  10707. }
  10708. static size_t js_malloc_usable_size_unknown(const void *ptr)
  10709. {
  10710. return 0;
  10711. }
  10712. void *js_calloc_rt(JSRuntime *rt, size_t count, size_t size)
  10713. {
  10714. void *ptr;
  10715. JSMallocState *s;
  10716. /* Do not allocate zero bytes: behavior is platform dependent */
  10717. assert(count != 0 && size != 0);
  10718. if (size > 0)
  10719. if (unlikely(count != (count * size) / size))
  10720. return NULL;
  10721. s = &rt->malloc_state;
  10722. /* When malloc_limit is 0 (unlimited), malloc_limit - 1 will be SIZE_MAX. */
  10723. if (unlikely(s->malloc_size + (count * size) > s->malloc_limit - 1))
  10724. return NULL;
  10725. ptr = rt->mf.js_calloc(s->opaque, count, size);
  10726. if (!ptr)
  10727. return NULL;
  10728. s->malloc_count++;
  10729. s->malloc_size += rt->mf.js_malloc_usable_size(ptr) + MALLOC_OVERHEAD;
  10730. return ptr;
  10731. }
  10732. void *js_malloc_rt(JSRuntime *rt, size_t size)
  10733. {
  10734. void *ptr;
  10735. JSMallocState *s;
  10736. /* Do not allocate zero bytes: behavior is platform dependent */
  10737. assert(size != 0);
  10738. s = &rt->malloc_state;
  10739. /* When malloc_limit is 0 (unlimited), malloc_limit - 1 will be SIZE_MAX. */
  10740. if (unlikely(s->malloc_size + size > s->malloc_limit - 1))
  10741. return NULL;
  10742. ptr = rt->mf.js_malloc(s->opaque, size);
  10743. if (!ptr)
  10744. return NULL;
  10745. s->malloc_count++;
  10746. s->malloc_size += rt->mf.js_malloc_usable_size(ptr) + MALLOC_OVERHEAD;
  10747. return ptr;
  10748. }
  10749. void js_free_rt(JSRuntime *rt, void *ptr)
  10750. {
  10751. JSMallocState *s;
  10752. if (!ptr)
  10753. return;
  10754. s = &rt->malloc_state;
  10755. s->malloc_count--;
  10756. s->malloc_size -= rt->mf.js_malloc_usable_size(ptr) + MALLOC_OVERHEAD;
  10757. rt->mf.js_free(s->opaque, ptr);
  10758. }
  10759. void *js_realloc_rt(JSRuntime *rt, void *ptr, size_t size)
  10760. {
  10761. size_t old_size;
  10762. JSMallocState *s;
  10763. if (!ptr) {
  10764. if (size == 0)
  10765. return NULL;
  10766. return js_malloc_rt(rt, size);
  10767. }
  10768. if (unlikely(size == 0)) {
  10769. js_free_rt(rt, ptr);
  10770. return NULL;
  10771. }
  10772. old_size = rt->mf.js_malloc_usable_size(ptr);
  10773. s = &rt->malloc_state;
  10774. /* When malloc_limit is 0 (unlimited), malloc_limit - 1 will be SIZE_MAX. */
  10775. if (s->malloc_size + size - old_size > s->malloc_limit - 1)
  10776. return NULL;
  10777. ptr = rt->mf.js_realloc(s->opaque, ptr, size);
  10778. if (!ptr)
  10779. return NULL;
  10780. s->malloc_size += rt->mf.js_malloc_usable_size(ptr) - old_size;
  10781. return ptr;
  10782. }
  10783. size_t js_malloc_usable_size_rt(JSRuntime *rt, const void *ptr)
  10784. {
  10785. return rt->mf.js_malloc_usable_size(ptr);
  10786. }
  10787. /**
  10788. * This used to be implemented as malloc + memset, but using calloc
  10789. * yields better performance in initial, bursty allocations, something useful
  10790. * for QuickJS.
  10791. *
  10792. * More information: https://github.com/quickjs-ng/quickjs/pull/519
  10793. */
  10794. void *js_mallocz_rt(JSRuntime *rt, size_t size)
  10795. {
  10796. return js_calloc_rt(rt, 1, size);
  10797. }
  10798. /* called by libbf */
  10799. static void *js_bf_realloc(void *opaque, void *ptr, size_t size)
  10800. {
  10801. JSRuntime *rt = opaque;
  10802. return js_realloc_rt(rt, ptr, size);
  10803. }
  10804. /* Throw out of memory in case of error */
  10805. void *js_calloc(JSContext *ctx, size_t count, size_t size)
  10806. {
  10807. void *ptr;
  10808. ptr = js_calloc_rt(ctx->rt, count, size);
  10809. if (unlikely(!ptr)) {
  10810. JS_ThrowOutOfMemory(ctx);
  10811. return NULL;
  10812. }
  10813. return ptr;
  10814. }
  10815. /* Throw out of memory in case of error */
  10816. void *js_malloc(JSContext *ctx, size_t size)
  10817. {
  10818. void *ptr;
  10819. ptr = js_malloc_rt(ctx->rt, size);
  10820. if (unlikely(!ptr)) {
  10821. JS_ThrowOutOfMemory(ctx);
  10822. return NULL;
  10823. }
  10824. return ptr;
  10825. }
  10826. /* Throw out of memory in case of error */
  10827. void *js_mallocz(JSContext *ctx, size_t size)
  10828. {
  10829. void *ptr;
  10830. ptr = js_mallocz_rt(ctx->rt, size);
  10831. if (unlikely(!ptr)) {
  10832. JS_ThrowOutOfMemory(ctx);
  10833. return NULL;
  10834. }
  10835. return ptr;
  10836. }
  10837. void js_free(JSContext *ctx, void *ptr)
  10838. {
  10839. js_free_rt(ctx->rt, ptr);
  10840. }
  10841. /* Throw out of memory in case of error */
  10842. void *js_realloc(JSContext *ctx, void *ptr, size_t size)
  10843. {
  10844. void *ret;
  10845. ret = js_realloc_rt(ctx->rt, ptr, size);
  10846. if (unlikely(!ret && size != 0)) {
  10847. JS_ThrowOutOfMemory(ctx);
  10848. return NULL;
  10849. }
  10850. return ret;
  10851. }
  10852. /* store extra allocated size in *pslack if successful */
  10853. void *js_realloc2(JSContext *ctx, void *ptr, size_t size, size_t *pslack)
  10854. {
  10855. void *ret;
  10856. ret = js_realloc_rt(ctx->rt, ptr, size);
  10857. if (unlikely(!ret && size != 0)) {
  10858. JS_ThrowOutOfMemory(ctx);
  10859. return NULL;
  10860. }
  10861. if (pslack) {
  10862. size_t new_size = js_malloc_usable_size_rt(ctx->rt, ret);
  10863. *pslack = (new_size > size) ? new_size - size : 0;
  10864. }
  10865. return ret;
  10866. }
  10867. size_t js_malloc_usable_size(JSContext *ctx, const void *ptr)
  10868. {
  10869. return js_malloc_usable_size_rt(ctx->rt, ptr);
  10870. }
  10871. /* Throw out of memory exception in case of error */
  10872. char *js_strndup(JSContext *ctx, const char *s, size_t n)
  10873. {
  10874. char *ptr;
  10875. ptr = js_malloc(ctx, n + 1);
  10876. if (ptr) {
  10877. memcpy(ptr, s, n);
  10878. ptr[n] = '\0';
  10879. }
  10880. return ptr;
  10881. }
  10882. char *js_strdup(JSContext *ctx, const char *str)
  10883. {
  10884. return js_strndup(ctx, str, strlen(str));
  10885. }
  10886. static no_inline int js_realloc_array(JSContext *ctx, void **parray,
  10887. int elem_size, int *psize, int req_size)
  10888. {
  10889. int new_size;
  10890. size_t slack;
  10891. void *new_array;
  10892. /* XXX: potential arithmetic overflow */
  10893. new_size = max_int(req_size, *psize * 3 / 2);
  10894. new_array = js_realloc2(ctx, *parray, new_size * elem_size, &slack);
  10895. if (!new_array)
  10896. return -1;
  10897. new_size += slack / elem_size;
  10898. *psize = new_size;
  10899. *parray = new_array;
  10900. return 0;
  10901. }
  10902. /* resize the array and update its size if req_size > *psize */
  10903. static inline int js_resize_array(JSContext *ctx, void **parray, int elem_size,
  10904. int *psize, int req_size)
  10905. {
  10906. if (unlikely(req_size > *psize))
  10907. return js_realloc_array(ctx, parray, elem_size, psize, req_size);
  10908. else
  10909. return 0;
  10910. }
  10911. static void *js_dbuf_realloc(void *ctx, void *ptr, size_t size)
  10912. {
  10913. return js_realloc(ctx, ptr, size);
  10914. }
  10915. static inline void js_dbuf_init(JSContext *ctx, DynBuf *s)
  10916. {
  10917. dbuf_init2(s, ctx, js_dbuf_realloc);
  10918. }
  10919. static inline int is_digit(int c) {
  10920. return c >= '0' && c <= '9';
  10921. }
  10922. static inline int string_get(JSString *p, int idx) {
  10923. return p->is_wide_char ? str16(p)[idx] : str8(p)[idx];
  10924. }
  10925. typedef struct JSClassShortDef {
  10926. JSAtom class_name;
  10927. JSClassFinalizer *finalizer;
  10928. JSClassGCMark *gc_mark;
  10929. } JSClassShortDef;
  10930. static JSClassShortDef const js_std_class_def[] = {
  10931. { JS_ATOM_Object, NULL, NULL }, /* JS_CLASS_OBJECT */
  10932. { JS_ATOM_Array, js_array_finalizer, js_array_mark }, /* JS_CLASS_ARRAY */
  10933. { JS_ATOM_Error, NULL, NULL }, /* JS_CLASS_ERROR */
  10934. { JS_ATOM_Number, js_object_data_finalizer, js_object_data_mark }, /* JS_CLASS_NUMBER */
  10935. { JS_ATOM_String, js_object_data_finalizer, js_object_data_mark }, /* JS_CLASS_STRING */
  10936. { JS_ATOM_Boolean, js_object_data_finalizer, js_object_data_mark }, /* JS_CLASS_BOOLEAN */
  10937. { JS_ATOM_Symbol, js_object_data_finalizer, js_object_data_mark }, /* JS_CLASS_SYMBOL */
  10938. { JS_ATOM_Arguments, js_array_finalizer, js_array_mark }, /* JS_CLASS_ARGUMENTS */
  10939. { JS_ATOM_Arguments, NULL, NULL }, /* JS_CLASS_MAPPED_ARGUMENTS */
  10940. { JS_ATOM_Date, js_object_data_finalizer, js_object_data_mark }, /* JS_CLASS_DATE */
  10941. { JS_ATOM_Object, NULL, NULL }, /* JS_CLASS_MODULE_NS */
  10942. { JS_ATOM_Function, js_c_function_finalizer, js_c_function_mark }, /* JS_CLASS_C_FUNCTION */
  10943. { JS_ATOM_Function, js_bytecode_function_finalizer, js_bytecode_function_mark }, /* JS_CLASS_BYTECODE_FUNCTION */
  10944. { JS_ATOM_Function, js_bound_function_finalizer, js_bound_function_mark }, /* JS_CLASS_BOUND_FUNCTION */
  10945. { JS_ATOM_Function, js_c_function_data_finalizer, js_c_function_data_mark }, /* JS_CLASS_C_FUNCTION_DATA */
  10946. { JS_ATOM_GeneratorFunction, js_bytecode_function_finalizer, js_bytecode_function_mark }, /* JS_CLASS_GENERATOR_FUNCTION */
  10947. { JS_ATOM_ForInIterator, js_for_in_iterator_finalizer, js_for_in_iterator_mark }, /* JS_CLASS_FOR_IN_ITERATOR */
  10948. { JS_ATOM_RegExp, js_regexp_finalizer, NULL }, /* JS_CLASS_REGEXP */
  10949. { JS_ATOM_ArrayBuffer, js_array_buffer_finalizer, NULL }, /* JS_CLASS_ARRAY_BUFFER */
  10950. { JS_ATOM_SharedArrayBuffer, js_array_buffer_finalizer, NULL }, /* JS_CLASS_SHARED_ARRAY_BUFFER */
  10951. { JS_ATOM_Uint8ClampedArray, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_UINT8C_ARRAY */
  10952. { JS_ATOM_Int8Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_INT8_ARRAY */
  10953. { JS_ATOM_Uint8Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_UINT8_ARRAY */
  10954. { JS_ATOM_Int16Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_INT16_ARRAY */
  10955. { JS_ATOM_Uint16Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_UINT16_ARRAY */
  10956. { JS_ATOM_Int32Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_INT32_ARRAY */
  10957. { JS_ATOM_Uint32Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_UINT32_ARRAY */
  10958. { JS_ATOM_BigInt64Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_BIG_INT64_ARRAY */
  10959. { JS_ATOM_BigUint64Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_BIG_UINT64_ARRAY */
  10960. { JS_ATOM_Float16Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_FLOAT16_ARRAY */
  10961. { JS_ATOM_Float32Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_FLOAT32_ARRAY */
  10962. { JS_ATOM_Float64Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_FLOAT64_ARRAY */
  10963. { JS_ATOM_DataView, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_DATAVIEW */
  10964. { JS_ATOM_BigInt, js_object_data_finalizer, js_object_data_mark }, /* JS_CLASS_BIG_INT */
  10965. { JS_ATOM_Map, js_map_finalizer, js_map_mark }, /* JS_CLASS_MAP */
  10966. { JS_ATOM_Set, js_map_finalizer, js_map_mark }, /* JS_CLASS_SET */
  10967. { JS_ATOM_WeakMap, js_map_finalizer, js_map_mark }, /* JS_CLASS_WEAKMAP */
  10968. { JS_ATOM_WeakSet, js_map_finalizer, js_map_mark }, /* JS_CLASS_WEAKSET */
  10969. { JS_ATOM_Iterator, NULL, NULL }, /* JS_CLASS_ITERATOR */
  10970. { JS_ATOM_IteratorHelper, js_iterator_helper_finalizer, js_iterator_helper_mark }, /* JS_CLASS_ITERATOR_HELPER */
  10971. { JS_ATOM_IteratorWrap, js_iterator_wrap_finalizer, js_iterator_wrap_mark }, /* JS_CLASS_ITERATOR_WRAP */
  10972. { JS_ATOM_Map_Iterator, js_map_iterator_finalizer, js_map_iterator_mark }, /* JS_CLASS_MAP_ITERATOR */
  10973. { JS_ATOM_Set_Iterator, js_map_iterator_finalizer, js_map_iterator_mark }, /* JS_CLASS_SET_ITERATOR */
  10974. { JS_ATOM_Array_Iterator, js_array_iterator_finalizer, js_array_iterator_mark }, /* JS_CLASS_ARRAY_ITERATOR */
  10975. { JS_ATOM_String_Iterator, js_array_iterator_finalizer, js_array_iterator_mark }, /* JS_CLASS_STRING_ITERATOR */
  10976. { JS_ATOM_RegExp_String_Iterator, js_regexp_string_iterator_finalizer, js_regexp_string_iterator_mark }, /* JS_CLASS_REGEXP_STRING_ITERATOR */
  10977. { JS_ATOM_Generator, js_generator_finalizer, js_generator_mark }, /* JS_CLASS_GENERATOR */
  10978. };
  10979. static int init_class_range(JSRuntime *rt, JSClassShortDef const *tab,
  10980. int start, int count)
  10981. {
  10982. JSClassDef cm_s, *cm = &cm_s;
  10983. int i, class_id;
  10984. for(i = 0; i < count; i++) {
  10985. class_id = i + start;
  10986. memset(cm, 0, sizeof(*cm));
  10987. cm->finalizer = tab[i].finalizer;
  10988. cm->gc_mark = tab[i].gc_mark;
  10989. if (JS_NewClass1(rt, class_id, cm, tab[i].class_name) < 0)
  10990. return -1;
  10991. }
  10992. return 0;
  10993. }
  10994. /* Uses code from LLVM project. */
  10995. static inline uintptr_t js_get_stack_pointer(void)
  10996. {
  10997. #if defined(__clang__) || defined(__GNUC__)
  10998. return (uintptr_t)__builtin_frame_address(0);
  10999. #elif defined(_MSC_VER)
  11000. return (uintptr_t)_AddressOfReturnAddress();
  11001. #else
  11002. char CharOnStack = 0;
  11003. // The volatile store here is intended to escape the local variable, to
  11004. // prevent the compiler from optimizing CharOnStack into anything other
  11005. // than a char on the stack.
  11006. //
  11007. // Tested on: MSVC 2015 - 2019, GCC 4.9 - 9, Clang 3.2 - 9, ICC 13 - 19.
  11008. char *volatile Ptr = &CharOnStack;
  11009. return (uintptr_t) Ptr;
  11010. #endif
  11011. }
  11012. static inline bool js_check_stack_overflow(JSRuntime *rt, size_t alloca_size)
  11013. {
  11014. uintptr_t sp;
  11015. sp = js_get_stack_pointer() - alloca_size;
  11016. return unlikely(sp < rt->stack_limit);
  11017. }
  11018. JSRuntime *JS_NewRuntime2(const JSMallocFunctions *mf, void *opaque)
  11019. {
  11020. JSRuntime *rt;
  11021. JSMallocState ms;
  11022. memset(&ms, 0, sizeof(ms));
  11023. ms.opaque = opaque;
  11024. ms.malloc_limit = 0;
  11025. rt = mf->js_calloc(opaque, 1, sizeof(JSRuntime));
  11026. if (!rt)
  11027. return NULL;
  11028. rt->mf = *mf;
  11029. if (!rt->mf.js_malloc_usable_size) {
  11030. /* use dummy function if none provided */
  11031. rt->mf.js_malloc_usable_size = js_malloc_usable_size_unknown;
  11032. }
  11033. /* Inline what js_malloc_rt does since we cannot use it here. */
  11034. ms.malloc_count++;
  11035. ms.malloc_size += rt->mf.js_malloc_usable_size(rt) + MALLOC_OVERHEAD;
  11036. rt->malloc_state = ms;
  11037. rt->malloc_gc_threshold = 256 * 1024;
  11038. bf_context_init(&rt->bf_ctx, js_bf_realloc, rt);
  11039. init_list_head(&rt->context_list);
  11040. init_list_head(&rt->gc_obj_list);
  11041. init_list_head(&rt->gc_zero_ref_count_list);
  11042. rt->gc_phase = JS_GC_PHASE_NONE;
  11043. #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS
  11044. init_list_head(&rt->string_list);
  11045. #endif
  11046. init_list_head(&rt->job_list);
  11047. if (JS_InitAtoms(rt))
  11048. goto fail;
  11049. /* create the object, array and function classes */
  11050. if (init_class_range(rt, js_std_class_def, JS_CLASS_OBJECT,
  11051. countof(js_std_class_def)) < 0)
  11052. goto fail;
  11053. rt->class_array[JS_CLASS_ARGUMENTS].exotic = &js_arguments_exotic_methods;
  11054. rt->class_array[JS_CLASS_STRING].exotic = &js_string_exotic_methods;
  11055. rt->class_array[JS_CLASS_MODULE_NS].exotic = &js_module_ns_exotic_methods;
  11056. rt->class_array[JS_CLASS_C_FUNCTION].call = js_call_c_function;
  11057. rt->class_array[JS_CLASS_C_FUNCTION_DATA].call = js_c_function_data_call;
  11058. rt->class_array[JS_CLASS_BOUND_FUNCTION].call = js_call_bound_function;
  11059. rt->class_array[JS_CLASS_GENERATOR_FUNCTION].call = js_generator_function_call;
  11060. if (init_shape_hash(rt))
  11061. goto fail;
  11062. rt->js_class_id_alloc = JS_CLASS_INIT_COUNT;
  11063. rt->stack_size = JS_DEFAULT_STACK_SIZE;
  11064. #ifdef __wasi__
  11065. rt->stack_size = 0;
  11066. #endif
  11067. JS_UpdateStackTop(rt);
  11068. rt->current_exception = JS_UNINITIALIZED;
  11069. return rt;
  11070. fail:
  11071. JS_FreeRuntime(rt);
  11072. return NULL;
  11073. }
  11074. void *JS_GetRuntimeOpaque(JSRuntime *rt)
  11075. {
  11076. return rt->user_opaque;
  11077. }
  11078. void JS_SetRuntimeOpaque(JSRuntime *rt, void *opaque)
  11079. {
  11080. rt->user_opaque = opaque;
  11081. }
  11082. int JS_AddRuntimeFinalizer(JSRuntime *rt, JSRuntimeFinalizer *finalizer,
  11083. void *arg)
  11084. {
  11085. JSRuntimeFinalizerState *fs = js_malloc_rt(rt, sizeof(*fs));
  11086. if (!fs)
  11087. return -1;
  11088. fs->next = rt->finalizers;
  11089. fs->finalizer = finalizer;
  11090. fs->arg = arg;
  11091. rt->finalizers = fs;
  11092. return 0;
  11093. }
  11094. static void *js_def_calloc(void *opaque, size_t count, size_t size)
  11095. {
  11096. return calloc(count, size);
  11097. }
  11098. static void *js_def_malloc(void *opaque, size_t size)
  11099. {
  11100. return malloc(size);
  11101. }
  11102. static void js_def_free(void *opaque, void *ptr)
  11103. {
  11104. free(ptr);
  11105. }
  11106. static void *js_def_realloc(void *opaque, void *ptr, size_t size)
  11107. {
  11108. return realloc(ptr, size);
  11109. }
  11110. static const JSMallocFunctions def_malloc_funcs = {
  11111. js_def_calloc,
  11112. js_def_malloc,
  11113. js_def_free,
  11114. js_def_realloc,
  11115. js__malloc_usable_size
  11116. };
  11117. JSRuntime *JS_NewRuntime(void)
  11118. {
  11119. return JS_NewRuntime2(&def_malloc_funcs, NULL);
  11120. }
  11121. void JS_SetMemoryLimit(JSRuntime *rt, size_t limit)
  11122. {
  11123. rt->malloc_state.malloc_limit = limit;
  11124. }
  11125. void JS_SetDumpFlags(JSRuntime *rt, uint64_t flags)
  11126. {
  11127. #ifdef ENABLE_DUMPS
  11128. rt->dump_flags = flags;
  11129. #endif
  11130. }
  11131. uint64_t JS_GetDumpFlags(JSRuntime *rt)
  11132. {
  11133. #ifdef ENABLE_DUMPS
  11134. return rt->dump_flags;
  11135. #else
  11136. return 0;
  11137. #endif
  11138. }
  11139. size_t JS_GetGCThreshold(JSRuntime *rt) {
  11140. return rt->malloc_gc_threshold;
  11141. }
  11142. /* use -1 to disable automatic GC */
  11143. void JS_SetGCThreshold(JSRuntime *rt, size_t gc_threshold)
  11144. {
  11145. rt->malloc_gc_threshold = gc_threshold;
  11146. }
  11147. #define malloc(s) malloc_is_forbidden(s)
  11148. #define free(p) free_is_forbidden(p)
  11149. #define realloc(p,s) realloc_is_forbidden(p,s)
  11150. void JS_SetInterruptHandler(JSRuntime *rt, JSInterruptHandler *cb, void *opaque)
  11151. {
  11152. rt->interrupt_handler = cb;
  11153. rt->interrupt_opaque = opaque;
  11154. }
  11155. void JS_SetCanBlock(JSRuntime *rt, bool can_block)
  11156. {
  11157. rt->can_block = can_block;
  11158. }
  11159. void JS_SetSharedArrayBufferFunctions(JSRuntime *rt,
  11160. const JSSharedArrayBufferFunctions *sf)
  11161. {
  11162. rt->sab_funcs = *sf;
  11163. }
  11164. /* return 0 if OK, < 0 if exception */
  11165. int JS_EnqueueJob(JSContext *ctx, JSJobFunc *job_func,
  11166. int argc, JSValueConst *argv)
  11167. {
  11168. JSRuntime *rt = ctx->rt;
  11169. JSJobEntry *e;
  11170. int i;
  11171. assert(!rt->in_free);
  11172. e = js_malloc(ctx, sizeof(*e) + argc * sizeof(JSValue));
  11173. if (!e)
  11174. return -1;
  11175. e->ctx = ctx;
  11176. e->job_func = job_func;
  11177. e->argc = argc;
  11178. for(i = 0; i < argc; i++) {
  11179. e->argv[i] = js_dup(argv[i]);
  11180. }
  11181. list_add_tail(&e->link, &rt->job_list);
  11182. return 0;
  11183. }
  11184. bool JS_IsJobPending(JSRuntime *rt)
  11185. {
  11186. return !list_empty(&rt->job_list);
  11187. }
  11188. /* return < 0 if exception, 0 if no job pending, 1 if a job was
  11189. executed successfully. the context of the job is stored in '*pctx' */
  11190. int JS_ExecutePendingJob(JSRuntime *rt, JSContext **pctx)
  11191. {
  11192. JSContext *ctx;
  11193. JSJobEntry *e;
  11194. JSValue res;
  11195. int i, ret;
  11196. if (list_empty(&rt->job_list)) {
  11197. *pctx = NULL;
  11198. return 0;
  11199. }
  11200. /* get the first pending job and execute it */
  11201. e = list_entry(rt->job_list.next, JSJobEntry, link);
  11202. list_del(&e->link);
  11203. ctx = e->ctx;
  11204. res = e->job_func(e->ctx, e->argc, vc(e->argv));
  11205. for(i = 0; i < e->argc; i++)
  11206. JS_FreeValue(ctx, e->argv[i]);
  11207. if (JS_IsException(res))
  11208. ret = -1;
  11209. else
  11210. ret = 1;
  11211. JS_FreeValue(ctx, res);
  11212. js_free(ctx, e);
  11213. *pctx = ctx;
  11214. return ret;
  11215. }
  11216. static inline uint32_t atom_get_free(const JSAtomStruct *p)
  11217. {
  11218. return (uintptr_t)p >> 1;
  11219. }
  11220. static inline bool atom_is_free(const JSAtomStruct *p)
  11221. {
  11222. return (uintptr_t)p & 1;
  11223. }
  11224. static inline JSAtomStruct *atom_set_free(uint32_t v)
  11225. {
  11226. return (JSAtomStruct *)(((uintptr_t)v << 1) | 1);
  11227. }
  11228. /* Note: the string contents are uninitialized */
  11229. static JSString *js_alloc_string_rt(JSRuntime *rt, int max_len, int is_wide_char)
  11230. {
  11231. JSString *str;
  11232. str = js_malloc_rt(rt, sizeof(JSString) + (max_len << is_wide_char) + 1 - is_wide_char);
  11233. if (unlikely(!str))
  11234. return NULL;
  11235. str->header.ref_count = 1;
  11236. str->is_wide_char = is_wide_char;
  11237. str->len = max_len;
  11238. str->atom_type = 0;
  11239. str->hash = 0; /* optional but costless */
  11240. str->hash_next = 0; /* optional */
  11241. #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS
  11242. list_add_tail(&str->link, &rt->string_list);
  11243. #endif
  11244. return str;
  11245. }
  11246. static JSString *js_alloc_string(JSContext *ctx, int max_len, int is_wide_char)
  11247. {
  11248. JSString *p;
  11249. p = js_alloc_string_rt(ctx->rt, max_len, is_wide_char);
  11250. if (unlikely(!p)) {
  11251. JS_ThrowOutOfMemory(ctx);
  11252. return NULL;
  11253. }
  11254. return p;
  11255. }
  11256. /* same as JS_FreeValueRT() but faster */
  11257. static inline void js_free_string(JSRuntime *rt, JSString *str)
  11258. {
  11259. if (--str->header.ref_count <= 0) {
  11260. if (str->atom_type) {
  11261. JS_FreeAtomStruct(rt, str);
  11262. } else {
  11263. #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS
  11264. list_del(&str->link);
  11265. #endif
  11266. js_free_rt(rt, str);
  11267. }
  11268. }
  11269. }
  11270. void JS_SetRuntimeInfo(JSRuntime *rt, const char *s)
  11271. {
  11272. if (rt)
  11273. rt->rt_info = s;
  11274. }
  11275. void JS_FreeRuntime(JSRuntime *rt)
  11276. {
  11277. struct list_head *el, *el1;
  11278. int i;
  11279. rt->in_free = true;
  11280. JS_FreeValueRT(rt, rt->current_exception);
  11281. list_for_each_safe(el, el1, &rt->job_list) {
  11282. JSJobEntry *e = list_entry(el, JSJobEntry, link);
  11283. for(i = 0; i < e->argc; i++)
  11284. JS_FreeValueRT(rt, e->argv[i]);
  11285. js_free_rt(rt, e);
  11286. }
  11287. init_list_head(&rt->job_list);
  11288. JS_RunGC(rt);
  11289. #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS
  11290. /* leaking objects */
  11291. if (check_dump_flag(rt, JS_DUMP_LEAKS)) {
  11292. bool header_done;
  11293. JSGCObjectHeader *p;
  11294. int count;
  11295. /* remove the internal refcounts to display only the object
  11296. referenced externally */
  11297. list_for_each(el, &rt->gc_obj_list) {
  11298. p = list_entry(el, JSGCObjectHeader, link);
  11299. p->mark = 0;
  11300. }
  11301. gc_decref(rt);
  11302. header_done = false;
  11303. list_for_each(el, &rt->gc_obj_list) {
  11304. p = list_entry(el, JSGCObjectHeader, link);
  11305. if (p->ref_count != 0) {
  11306. if (!header_done) {
  11307. printf("Object leaks:\n");
  11308. JS_DumpObjectHeader(rt);
  11309. header_done = true;
  11310. }
  11311. JS_DumpGCObject(rt, p);
  11312. }
  11313. }
  11314. count = 0;
  11315. list_for_each(el, &rt->gc_obj_list) {
  11316. p = list_entry(el, JSGCObjectHeader, link);
  11317. if (p->ref_count == 0) {
  11318. count++;
  11319. }
  11320. }
  11321. if (count != 0)
  11322. printf("Secondary object leaks: %d\n", count);
  11323. }
  11324. #endif
  11325. assert(list_empty(&rt->gc_obj_list));
  11326. /* free the classes */
  11327. for(i = 0; i < rt->class_count; i++) {
  11328. JSClass *cl = &rt->class_array[i];
  11329. if (cl->class_id != 0) {
  11330. JS_FreeAtomRT(rt, cl->class_name);
  11331. }
  11332. }
  11333. js_free_rt(rt, rt->class_array);
  11334. bf_context_end(&rt->bf_ctx);
  11335. #ifdef ENABLE_DUMPS // JS_DUMP_ATOM_LEAKS
  11336. /* only the atoms defined in JS_InitAtoms() should be left */
  11337. if (check_dump_flag(rt, JS_DUMP_ATOM_LEAKS)) {
  11338. bool header_done = false;
  11339. for(i = 0; i < rt->atom_size; i++) {
  11340. JSAtomStruct *p = rt->atom_array[i];
  11341. if (!atom_is_free(p) /* && p->str*/) {
  11342. if (i >= JS_ATOM_END || p->header.ref_count != 1) {
  11343. if (!header_done) {
  11344. header_done = true;
  11345. if (rt->rt_info) {
  11346. printf("%s:1: atom leakage:", rt->rt_info);
  11347. } else {
  11348. printf("Atom leaks:\n"
  11349. " %6s %6s %s\n",
  11350. "ID", "REFCNT", "NAME");
  11351. }
  11352. }
  11353. if (rt->rt_info) {
  11354. printf(" ");
  11355. } else {
  11356. printf(" %6u %6u ", i, p->header.ref_count);
  11357. }
  11358. switch (p->atom_type) {
  11359. case JS_ATOM_TYPE_STRING:
  11360. JS_DumpString(rt, p);
  11361. break;
  11362. case JS_ATOM_TYPE_GLOBAL_SYMBOL:
  11363. printf("Symbol.for(");
  11364. JS_DumpString(rt, p);
  11365. printf(")");
  11366. break;
  11367. case JS_ATOM_TYPE_SYMBOL:
  11368. if (p->hash == JS_ATOM_HASH_SYMBOL) {
  11369. printf("Symbol(");
  11370. JS_DumpString(rt, p);
  11371. printf(")");
  11372. } else {
  11373. printf("Private(");
  11374. JS_DumpString(rt, p);
  11375. printf(")");
  11376. }
  11377. break;
  11378. }
  11379. if (rt->rt_info) {
  11380. printf(":%u", p->header.ref_count);
  11381. } else {
  11382. printf("\n");
  11383. }
  11384. }
  11385. }
  11386. }
  11387. if (rt->rt_info && header_done)
  11388. printf("\n");
  11389. }
  11390. #endif
  11391. /* free the atoms */
  11392. for(i = 0; i < rt->atom_size; i++) {
  11393. JSAtomStruct *p = rt->atom_array[i];
  11394. if (!atom_is_free(p)) {
  11395. #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS
  11396. list_del(&p->link);
  11397. #endif
  11398. js_free_rt(rt, p);
  11399. }
  11400. }
  11401. js_free_rt(rt, rt->atom_array);
  11402. js_free_rt(rt, rt->atom_hash);
  11403. js_free_rt(rt, rt->shape_hash);
  11404. #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS
  11405. if (check_dump_flag(rt, JS_DUMP_LEAKS) && !list_empty(&rt->string_list)) {
  11406. if (rt->rt_info) {
  11407. printf("%s:1: string leakage:", rt->rt_info);
  11408. } else {
  11409. printf("String leaks:\n"
  11410. " %6s %s\n",
  11411. "REFCNT", "VALUE");
  11412. }
  11413. list_for_each_safe(el, el1, &rt->string_list) {
  11414. JSString *str = list_entry(el, JSString, link);
  11415. if (rt->rt_info) {
  11416. printf(" ");
  11417. } else {
  11418. printf(" %6u ", str->header.ref_count);
  11419. }
  11420. JS_DumpString(rt, str);
  11421. if (rt->rt_info) {
  11422. printf(":%u", str->header.ref_count);
  11423. } else {
  11424. printf("\n");
  11425. }
  11426. list_del(&str->link);
  11427. js_free_rt(rt, str);
  11428. }
  11429. if (rt->rt_info)
  11430. printf("\n");
  11431. }
  11432. #endif
  11433. while (rt->finalizers) {
  11434. JSRuntimeFinalizerState *fs = rt->finalizers;
  11435. rt->finalizers = fs->next;
  11436. fs->finalizer(rt, fs->arg);
  11437. js_free_rt(rt, fs);
  11438. }
  11439. #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS
  11440. if (check_dump_flag(rt, JS_DUMP_LEAKS)) {
  11441. JSMallocState *s = &rt->malloc_state;
  11442. if (s->malloc_count > 1) {
  11443. if (rt->rt_info)
  11444. printf("%s:1: ", rt->rt_info);
  11445. printf("Memory leak: %zd bytes lost in %zd block%s\n",
  11446. s->malloc_size - sizeof(JSRuntime),
  11447. s->malloc_count - 1, &"s"[s->malloc_count == 2]);
  11448. }
  11449. }
  11450. #endif
  11451. {
  11452. JSMallocState *ms = &rt->malloc_state;
  11453. rt->mf.js_free(ms->opaque, rt);
  11454. }
  11455. }
  11456. JSContext *JS_NewContextRaw(JSRuntime *rt)
  11457. {
  11458. JSContext *ctx;
  11459. int i;
  11460. ctx = js_mallocz_rt(rt, sizeof(JSContext));
  11461. if (!ctx)
  11462. return NULL;
  11463. ctx->header.ref_count = 1;
  11464. add_gc_object(rt, &ctx->header, JS_GC_OBJ_TYPE_JS_CONTEXT);
  11465. ctx->class_proto = js_malloc_rt(rt, sizeof(ctx->class_proto[0]) *
  11466. rt->class_count);
  11467. if (!ctx->class_proto) {
  11468. js_free_rt(rt, ctx);
  11469. return NULL;
  11470. }
  11471. ctx->rt = rt;
  11472. list_add_tail(&ctx->link, &rt->context_list);
  11473. ctx->bf_ctx = &rt->bf_ctx;
  11474. for(i = 0; i < rt->class_count; i++)
  11475. ctx->class_proto[i] = JS_NULL;
  11476. ctx->array_ctor = JS_NULL;
  11477. ctx->iterator_ctor = JS_NULL;
  11478. ctx->regexp_ctor = JS_NULL;
  11479. ctx->promise_ctor = JS_NULL;
  11480. ctx->error_ctor = JS_NULL;
  11481. ctx->error_back_trace = JS_UNDEFINED;
  11482. ctx->error_prepare_stack = JS_UNDEFINED;
  11483. ctx->error_stack_trace_limit = js_int32(10);
  11484. init_list_head(&ctx->loaded_modules);
  11485. JS_AddIntrinsicBasicObjects(ctx);
  11486. return ctx;
  11487. }
  11488. JSContext *JS_NewContext(JSRuntime *rt)
  11489. {
  11490. JSContext *ctx;
  11491. ctx = JS_NewContextRaw(rt);
  11492. if (!ctx)
  11493. return NULL;
  11494. JS_AddIntrinsicBaseObjects(ctx);
  11495. JS_AddIntrinsicDate(ctx);
  11496. JS_AddIntrinsicEval(ctx);
  11497. JS_AddIntrinsicRegExp(ctx);
  11498. JS_AddIntrinsicJSON(ctx);
  11499. JS_AddIntrinsicProxy(ctx);
  11500. JS_AddIntrinsicMapSet(ctx);
  11501. JS_AddIntrinsicTypedArrays(ctx);
  11502. JS_AddIntrinsicPromise(ctx);
  11503. JS_AddIntrinsicBigInt(ctx);
  11504. JS_AddIntrinsicWeakRef(ctx);
  11505. JS_AddPerformance(ctx);
  11506. return ctx;
  11507. }
  11508. void *JS_GetContextOpaque(JSContext *ctx)
  11509. {
  11510. return ctx->user_opaque;
  11511. }
  11512. void JS_SetContextOpaque(JSContext *ctx, void *opaque)
  11513. {
  11514. ctx->user_opaque = opaque;
  11515. }
  11516. /* set the new value and free the old value after (freeing the value
  11517. can reallocate the object data) */
  11518. static inline void set_value(JSContext *ctx, JSValue *pval, JSValue new_val)
  11519. {
  11520. JSValue old_val;
  11521. old_val = *pval;
  11522. *pval = new_val;
  11523. JS_FreeValue(ctx, old_val);
  11524. }
  11525. void JS_SetClassProto(JSContext *ctx, JSClassID class_id, JSValue obj)
  11526. {
  11527. assert(class_id < ctx->rt->class_count);
  11528. set_value(ctx, &ctx->class_proto[class_id], obj);
  11529. }
  11530. JSValue JS_GetClassProto(JSContext *ctx, JSClassID class_id)
  11531. {
  11532. assert(class_id < ctx->rt->class_count);
  11533. return js_dup(ctx->class_proto[class_id]);
  11534. }
  11535. JSValue JS_GetFunctionProto(JSContext *ctx)
  11536. {
  11537. return js_dup(ctx->function_proto);
  11538. }
  11539. typedef enum JSFreeModuleEnum {
  11540. JS_FREE_MODULE_ALL,
  11541. JS_FREE_MODULE_NOT_RESOLVED,
  11542. } JSFreeModuleEnum;
  11543. /* XXX: would be more efficient with separate module lists */
  11544. static void js_free_modules(JSContext *ctx, JSFreeModuleEnum flag)
  11545. {
  11546. struct list_head *el, *el1;
  11547. list_for_each_safe(el, el1, &ctx->loaded_modules) {
  11548. JSModuleDef *m = list_entry(el, JSModuleDef, link);
  11549. if (flag == JS_FREE_MODULE_ALL ||
  11550. (flag == JS_FREE_MODULE_NOT_RESOLVED && !m->resolved)) {
  11551. js_free_module_def(ctx, m);
  11552. }
  11553. }
  11554. }
  11555. JSContext *JS_DupContext(JSContext *ctx)
  11556. {
  11557. ctx->header.ref_count++;
  11558. return ctx;
  11559. }
  11560. /* used by the GC */
  11561. static void JS_MarkContext(JSRuntime *rt, JSContext *ctx,
  11562. JS_MarkFunc *mark_func)
  11563. {
  11564. int i;
  11565. struct list_head *el;
  11566. /* modules are not seen by the GC, so we directly mark the objects
  11567. referenced by each module */
  11568. list_for_each(el, &ctx->loaded_modules) {
  11569. JSModuleDef *m = list_entry(el, JSModuleDef, link);
  11570. js_mark_module_def(rt, m, mark_func);
  11571. }
  11572. JS_MarkValue(rt, ctx->global_obj, mark_func);
  11573. JS_MarkValue(rt, ctx->global_var_obj, mark_func);
  11574. JS_MarkValue(rt, ctx->throw_type_error, mark_func);
  11575. JS_MarkValue(rt, ctx->eval_obj, mark_func);
  11576. JS_MarkValue(rt, ctx->array_proto_values, mark_func);
  11577. for(i = 0; i < JS_NATIVE_ERROR_COUNT; i++) {
  11578. JS_MarkValue(rt, ctx->native_error_proto[i], mark_func);
  11579. }
  11580. JS_MarkValue(rt, ctx->error_ctor, mark_func);
  11581. JS_MarkValue(rt, ctx->error_back_trace, mark_func);
  11582. JS_MarkValue(rt, ctx->error_prepare_stack, mark_func);
  11583. JS_MarkValue(rt, ctx->error_stack_trace_limit, mark_func);
  11584. for(i = 0; i < rt->class_count; i++) {
  11585. JS_MarkValue(rt, ctx->class_proto[i], mark_func);
  11586. }
  11587. JS_MarkValue(rt, ctx->iterator_ctor, mark_func);
  11588. JS_MarkValue(rt, ctx->async_iterator_proto, mark_func);
  11589. JS_MarkValue(rt, ctx->promise_ctor, mark_func);
  11590. JS_MarkValue(rt, ctx->array_ctor, mark_func);
  11591. JS_MarkValue(rt, ctx->regexp_ctor, mark_func);
  11592. JS_MarkValue(rt, ctx->function_ctor, mark_func);
  11593. JS_MarkValue(rt, ctx->function_proto, mark_func);
  11594. if (ctx->array_shape)
  11595. mark_func(rt, &ctx->array_shape->header);
  11596. }
  11597. void JS_FreeContext(JSContext *ctx)
  11598. {
  11599. JSRuntime *rt = ctx->rt;
  11600. int i;
  11601. if (--ctx->header.ref_count > 0)
  11602. return;
  11603. assert(ctx->header.ref_count == 0);
  11604. #ifdef ENABLE_DUMPS // JS_DUMP_ATOMS
  11605. if (check_dump_flag(rt, JS_DUMP_ATOMS))
  11606. JS_DumpAtoms(ctx->rt);
  11607. #endif
  11608. #ifdef ENABLE_DUMPS // JS_DUMP_SHAPES
  11609. if (check_dump_flag(rt, JS_DUMP_SHAPES))
  11610. JS_DumpShapes(ctx->rt);
  11611. #endif
  11612. #ifdef ENABLE_DUMPS // JS_DUMP_OBJECTS
  11613. if (check_dump_flag(rt, JS_DUMP_OBJECTS)) {
  11614. struct list_head *el;
  11615. JSGCObjectHeader *p;
  11616. printf("JSObjects: {\n");
  11617. JS_DumpObjectHeader(ctx->rt);
  11618. list_for_each(el, &rt->gc_obj_list) {
  11619. p = list_entry(el, JSGCObjectHeader, link);
  11620. JS_DumpGCObject(rt, p);
  11621. }
  11622. printf("}\n");
  11623. }
  11624. #endif
  11625. #ifdef ENABLE_DUMPS // JS_DUMP_MEM
  11626. if (check_dump_flag(rt, JS_DUMP_MEM)) {
  11627. JSMemoryUsage stats;
  11628. JS_ComputeMemoryUsage(rt, &stats);
  11629. JS_DumpMemoryUsage(stdout, &stats, rt);
  11630. }
  11631. #endif
  11632. js_free_modules(ctx, JS_FREE_MODULE_ALL);
  11633. JS_FreeValue(ctx, ctx->global_obj);
  11634. JS_FreeValue(ctx, ctx->global_var_obj);
  11635. JS_FreeValue(ctx, ctx->throw_type_error);
  11636. JS_FreeValue(ctx, ctx->eval_obj);
  11637. JS_FreeValue(ctx, ctx->array_proto_values);
  11638. for(i = 0; i < JS_NATIVE_ERROR_COUNT; i++) {
  11639. JS_FreeValue(ctx, ctx->native_error_proto[i]);
  11640. }
  11641. JS_FreeValue(ctx, ctx->error_ctor);
  11642. JS_FreeValue(ctx, ctx->error_back_trace);
  11643. JS_FreeValue(ctx, ctx->error_prepare_stack);
  11644. JS_FreeValue(ctx, ctx->error_stack_trace_limit);
  11645. for(i = 0; i < rt->class_count; i++) {
  11646. JS_FreeValue(ctx, ctx->class_proto[i]);
  11647. }
  11648. js_free_rt(rt, ctx->class_proto);
  11649. JS_FreeValue(ctx, ctx->iterator_ctor);
  11650. JS_FreeValue(ctx, ctx->async_iterator_proto);
  11651. JS_FreeValue(ctx, ctx->promise_ctor);
  11652. JS_FreeValue(ctx, ctx->array_ctor);
  11653. JS_FreeValue(ctx, ctx->regexp_ctor);
  11654. JS_FreeValue(ctx, ctx->function_ctor);
  11655. JS_FreeValue(ctx, ctx->function_proto);
  11656. js_free_shape_null(ctx->rt, ctx->array_shape);
  11657. list_del(&ctx->link);
  11658. remove_gc_object(&ctx->header);
  11659. js_free_rt(ctx->rt, ctx);
  11660. }
  11661. JSRuntime *JS_GetRuntime(JSContext *ctx)
  11662. {
  11663. return ctx->rt;
  11664. }
  11665. static void update_stack_limit(JSRuntime *rt)
  11666. {
  11667. #if defined(__wasi__)
  11668. rt->stack_limit = 0; /* no limit */
  11669. #else
  11670. if (rt->stack_size == 0) {
  11671. rt->stack_limit = 0; /* no limit */
  11672. } else {
  11673. rt->stack_limit = rt->stack_top - rt->stack_size;
  11674. }
  11675. #endif
  11676. }
  11677. void JS_SetMaxStackSize(JSRuntime *rt, size_t stack_size)
  11678. {
  11679. rt->stack_size = stack_size;
  11680. update_stack_limit(rt);
  11681. }
  11682. void JS_UpdateStackTop(JSRuntime *rt)
  11683. {
  11684. rt->stack_top = js_get_stack_pointer();
  11685. update_stack_limit(rt);
  11686. }
  11687. static inline bool is_strict_mode(JSContext *ctx)
  11688. {
  11689. JSStackFrame *sf = ctx->rt->current_stack_frame;
  11690. return sf && sf->is_strict_mode;
  11691. }
  11692. /* JSAtom support */
  11693. #define JS_ATOM_TAG_INT (1U << 31)
  11694. #define JS_ATOM_MAX_INT (JS_ATOM_TAG_INT - 1)
  11695. #define JS_ATOM_MAX ((1U << 30) - 1)
  11696. /* return the max count from the hash size */
  11697. #define JS_ATOM_COUNT_RESIZE(n) ((n) * 2)
  11698. static inline bool __JS_AtomIsConst(JSAtom v)
  11699. {
  11700. return (int32_t)v < JS_ATOM_END;
  11701. }
  11702. static inline bool __JS_AtomIsTaggedInt(JSAtom v)
  11703. {
  11704. return (v & JS_ATOM_TAG_INT) != 0;
  11705. }
  11706. static inline JSAtom __JS_AtomFromUInt32(uint32_t v)
  11707. {
  11708. return v | JS_ATOM_TAG_INT;
  11709. }
  11710. static inline uint32_t __JS_AtomToUInt32(JSAtom atom)
  11711. {
  11712. return atom & ~JS_ATOM_TAG_INT;
  11713. }
  11714. static inline int is_num(int c)
  11715. {
  11716. return c >= '0' && c <= '9';
  11717. }
  11718. /* return true if the string is a number n with 0 <= n <= 2^32-1 */
  11719. static inline bool is_num_string(uint32_t *pval, JSString *p)
  11720. {
  11721. uint32_t n;
  11722. uint64_t n64;
  11723. int c, i, len;
  11724. len = p->len;
  11725. if (len == 0 || len > 10)
  11726. return false;
  11727. c = string_get(p, 0);
  11728. if (is_num(c)) {
  11729. if (c == '0') {
  11730. if (len != 1)
  11731. return false;
  11732. n = 0;
  11733. } else {
  11734. n = c - '0';
  11735. for(i = 1; i < len; i++) {
  11736. c = string_get(p, i);
  11737. if (!is_num(c))
  11738. return false;
  11739. n64 = (uint64_t)n * 10 + (c - '0');
  11740. if ((n64 >> 32) != 0)
  11741. return false;
  11742. n = n64;
  11743. }
  11744. }
  11745. *pval = n;
  11746. return true;
  11747. } else {
  11748. return false;
  11749. }
  11750. }
  11751. /* XXX: could use faster version ? */
  11752. static inline uint32_t hash_string8(const uint8_t *str, size_t len, uint32_t h)
  11753. {
  11754. size_t i;
  11755. for(i = 0; i < len; i++)
  11756. h = h * 263 + str[i];
  11757. return h;
  11758. }
  11759. static inline uint32_t hash_string16(const uint16_t *str,
  11760. size_t len, uint32_t h)
  11761. {
  11762. size_t i;
  11763. for(i = 0; i < len; i++)
  11764. h = h * 263 + str[i];
  11765. return h;
  11766. }
  11767. static uint32_t hash_string(JSString *str, uint32_t h)
  11768. {
  11769. if (str->is_wide_char)
  11770. h = hash_string16(str16(str), str->len, h);
  11771. else
  11772. h = hash_string8(str8(str), str->len, h);
  11773. return h;
  11774. }
  11775. static __maybe_unused void JS_DumpString(JSRuntime *rt, JSString *p)
  11776. {
  11777. int i, c, sep;
  11778. if (p == NULL) {
  11779. printf("<null>");
  11780. return;
  11781. }
  11782. if (p->header.ref_count != 1)
  11783. printf("%d", p->header.ref_count);
  11784. if (p->is_wide_char)
  11785. putchar('L');
  11786. sep = '\"';
  11787. putchar(sep);
  11788. for(i = 0; i < p->len; i++) {
  11789. c = string_get(p, i);
  11790. if (c == sep || c == '\\') {
  11791. putchar('\\');
  11792. putchar(c);
  11793. } else if (c >= ' ' && c <= 126) {
  11794. putchar(c);
  11795. } else if (c == '\n') {
  11796. putchar('\\');
  11797. putchar('n');
  11798. } else {
  11799. printf("\\u%04x", c);
  11800. }
  11801. }
  11802. putchar(sep);
  11803. }
  11804. static __maybe_unused void JS_DumpAtoms(JSRuntime *rt)
  11805. {
  11806. JSAtomStruct *p;
  11807. int h, i;
  11808. /* This only dumps hashed atoms, not JS_ATOM_TYPE_SYMBOL atoms */
  11809. printf("JSAtom count=%d size=%d hash_size=%d:\n",
  11810. rt->atom_count, rt->atom_size, rt->atom_hash_size);
  11811. printf("JSAtom hash table: {\n");
  11812. for(i = 0; i < rt->atom_hash_size; i++) {
  11813. h = rt->atom_hash[i];
  11814. if (h) {
  11815. printf(" %d:", i);
  11816. while (h) {
  11817. p = rt->atom_array[h];
  11818. printf(" ");
  11819. JS_DumpString(rt, p);
  11820. h = p->hash_next;
  11821. }
  11822. printf("\n");
  11823. }
  11824. }
  11825. printf("}\n");
  11826. printf("JSAtom table: {\n");
  11827. for(i = 0; i < rt->atom_size; i++) {
  11828. p = rt->atom_array[i];
  11829. if (!atom_is_free(p)) {
  11830. printf(" %d: { %d %08x ", i, p->atom_type, p->hash);
  11831. if (!(p->len == 0 && p->is_wide_char != 0))
  11832. JS_DumpString(rt, p);
  11833. printf(" %d }\n", p->hash_next);
  11834. }
  11835. }
  11836. printf("}\n");
  11837. }
  11838. static int JS_ResizeAtomHash(JSRuntime *rt, int new_hash_size)
  11839. {
  11840. JSAtomStruct *p;
  11841. uint32_t new_hash_mask, h, i, hash_next1, j, *new_hash;
  11842. assert((new_hash_size & (new_hash_size - 1)) == 0); /* power of two */
  11843. new_hash_mask = new_hash_size - 1;
  11844. new_hash = js_mallocz_rt(rt, sizeof(rt->atom_hash[0]) * new_hash_size);
  11845. if (!new_hash)
  11846. return -1;
  11847. for(i = 0; i < rt->atom_hash_size; i++) {
  11848. h = rt->atom_hash[i];
  11849. while (h != 0) {
  11850. p = rt->atom_array[h];
  11851. hash_next1 = p->hash_next;
  11852. /* add in new hash table */
  11853. j = p->hash & new_hash_mask;
  11854. p->hash_next = new_hash[j];
  11855. new_hash[j] = h;
  11856. h = hash_next1;
  11857. }
  11858. }
  11859. js_free_rt(rt, rt->atom_hash);
  11860. rt->atom_hash = new_hash;
  11861. rt->atom_hash_size = new_hash_size;
  11862. rt->atom_count_resize = JS_ATOM_COUNT_RESIZE(new_hash_size);
  11863. // JS_DumpAtoms(rt);
  11864. return 0;
  11865. }
  11866. static int JS_InitAtoms(JSRuntime *rt)
  11867. {
  11868. int i, len, atom_type;
  11869. const char *p;
  11870. rt->atom_hash_size = 0;
  11871. rt->atom_hash = NULL;
  11872. rt->atom_count = 0;
  11873. rt->atom_size = 0;
  11874. rt->atom_free_index = 0;
  11875. if (JS_ResizeAtomHash(rt, 256)) /* there are at least 195 predefined atoms */
  11876. return -1;
  11877. p = js_atom_init;
  11878. for(i = 1; i < JS_ATOM_END; i++) {
  11879. if (i == JS_ATOM_Private_brand)
  11880. atom_type = JS_ATOM_TYPE_PRIVATE;
  11881. else if (i >= JS_ATOM_Symbol_toPrimitive)
  11882. atom_type = JS_ATOM_TYPE_SYMBOL;
  11883. else
  11884. atom_type = JS_ATOM_TYPE_STRING;
  11885. len = strlen(p);
  11886. if (__JS_NewAtomInit(rt, p, len, atom_type) == JS_ATOM_NULL)
  11887. return -1;
  11888. p = p + len + 1;
  11889. }
  11890. return 0;
  11891. }
  11892. static JSAtom JS_DupAtomRT(JSRuntime *rt, JSAtom v)
  11893. {
  11894. JSAtomStruct *p;
  11895. if (!__JS_AtomIsConst(v)) {
  11896. p = rt->atom_array[v];
  11897. p->header.ref_count++;
  11898. }
  11899. return v;
  11900. }
  11901. JSAtom JS_DupAtom(JSContext *ctx, JSAtom v)
  11902. {
  11903. JSRuntime *rt;
  11904. JSAtomStruct *p;
  11905. if (!__JS_AtomIsConst(v)) {
  11906. rt = ctx->rt;
  11907. p = rt->atom_array[v];
  11908. p->header.ref_count++;
  11909. }
  11910. return v;
  11911. }
  11912. static JSAtomKindEnum JS_AtomGetKind(JSContext *ctx, JSAtom v)
  11913. {
  11914. JSRuntime *rt;
  11915. JSAtomStruct *p;
  11916. rt = ctx->rt;
  11917. if (__JS_AtomIsTaggedInt(v))
  11918. return JS_ATOM_KIND_STRING;
  11919. p = rt->atom_array[v];
  11920. switch(p->atom_type) {
  11921. case JS_ATOM_TYPE_STRING:
  11922. return JS_ATOM_KIND_STRING;
  11923. case JS_ATOM_TYPE_GLOBAL_SYMBOL:
  11924. return JS_ATOM_KIND_SYMBOL;
  11925. case JS_ATOM_TYPE_SYMBOL:
  11926. switch(p->hash) {
  11927. case JS_ATOM_HASH_SYMBOL:
  11928. return JS_ATOM_KIND_SYMBOL;
  11929. case JS_ATOM_HASH_PRIVATE:
  11930. return JS_ATOM_KIND_PRIVATE;
  11931. default:
  11932. abort();
  11933. }
  11934. default:
  11935. abort();
  11936. }
  11937. return (JSAtomKindEnum){-1}; // pacify compiler
  11938. }
  11939. static JSAtom js_get_atom_index(JSRuntime *rt, JSAtomStruct *p)
  11940. {
  11941. uint32_t i = p->hash_next; /* atom_index */
  11942. if (p->atom_type != JS_ATOM_TYPE_SYMBOL) {
  11943. JSAtomStruct *p1;
  11944. i = rt->atom_hash[p->hash & (rt->atom_hash_size - 1)];
  11945. p1 = rt->atom_array[i];
  11946. while (p1 != p) {
  11947. assert(i != 0);
  11948. i = p1->hash_next;
  11949. p1 = rt->atom_array[i];
  11950. }
  11951. }
  11952. return i;
  11953. }
  11954. /* string case (internal). Return JS_ATOM_NULL if error. 'str' is
  11955. freed. */
  11956. static JSAtom __JS_NewAtom(JSRuntime *rt, JSString *str, int atom_type)
  11957. {
  11958. uint32_t h, h1, i;
  11959. JSAtomStruct *p;
  11960. int len;
  11961. if (atom_type < JS_ATOM_TYPE_SYMBOL) {
  11962. /* str is not NULL */
  11963. if (str->atom_type == atom_type) {
  11964. /* str is the atom, return its index */
  11965. i = js_get_atom_index(rt, str);
  11966. /* reduce string refcount and increase atom's unless constant */
  11967. if (__JS_AtomIsConst(i))
  11968. str->header.ref_count--;
  11969. return i;
  11970. }
  11971. /* try and locate an already registered atom */
  11972. len = str->len;
  11973. h = hash_string(str, atom_type);
  11974. h &= JS_ATOM_HASH_MASK;
  11975. h1 = h & (rt->atom_hash_size - 1);
  11976. i = rt->atom_hash[h1];
  11977. while (i != 0) {
  11978. p = rt->atom_array[i];
  11979. if (p->hash == h &&
  11980. p->atom_type == atom_type &&
  11981. p->len == len &&
  11982. js_string_memcmp(p, str, len) == 0) {
  11983. if (!__JS_AtomIsConst(i))
  11984. p->header.ref_count++;
  11985. goto done;
  11986. }
  11987. i = p->hash_next;
  11988. }
  11989. } else {
  11990. h1 = 0; /* avoid warning */
  11991. if (atom_type == JS_ATOM_TYPE_SYMBOL) {
  11992. h = JS_ATOM_HASH_SYMBOL;
  11993. } else {
  11994. h = JS_ATOM_HASH_PRIVATE;
  11995. atom_type = JS_ATOM_TYPE_SYMBOL;
  11996. }
  11997. }
  11998. if (rt->atom_free_index == 0) {
  11999. /* allow new atom entries */
  12000. uint32_t new_size, start;
  12001. JSAtomStruct **new_array;
  12002. /* alloc new with size progression 3/2:
  12003. 4 6 9 13 19 28 42 63 94 141 211 316 474 711 1066 1599 2398 3597 5395 8092
  12004. preallocating space for predefined atoms (at least 195).
  12005. */
  12006. new_size = max_int(211, rt->atom_size * 3 / 2);
  12007. if (new_size > JS_ATOM_MAX)
  12008. goto fail;
  12009. /* XXX: should use realloc2 to use slack space */
  12010. new_array = js_realloc_rt(rt, rt->atom_array, sizeof(*new_array) * new_size);
  12011. if (!new_array)
  12012. goto fail;
  12013. /* Note: the atom 0 is not used */
  12014. start = rt->atom_size;
  12015. if (start == 0) {
  12016. /* JS_ATOM_NULL entry */
  12017. p = js_mallocz_rt(rt, sizeof(JSAtomStruct));
  12018. if (!p) {
  12019. js_free_rt(rt, new_array);
  12020. goto fail;
  12021. }
  12022. p->header.ref_count = 1; /* not refcounted */
  12023. p->atom_type = JS_ATOM_TYPE_SYMBOL;
  12024. #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS
  12025. list_add_tail(&p->link, &rt->string_list);
  12026. #endif
  12027. new_array[0] = p;
  12028. rt->atom_count++;
  12029. start = 1;
  12030. }
  12031. rt->atom_size = new_size;
  12032. rt->atom_array = new_array;
  12033. rt->atom_free_index = start;
  12034. for(i = start; i < new_size; i++) {
  12035. uint32_t next;
  12036. if (i == (new_size - 1))
  12037. next = 0;
  12038. else
  12039. next = i + 1;
  12040. rt->atom_array[i] = atom_set_free(next);
  12041. }
  12042. }
  12043. if (str) {
  12044. if (str->atom_type == 0) {
  12045. p = str;
  12046. p->atom_type = atom_type;
  12047. } else {
  12048. p = js_malloc_rt(rt, sizeof(JSString) +
  12049. (str->len << str->is_wide_char) +
  12050. 1 - str->is_wide_char);
  12051. if (unlikely(!p))
  12052. goto fail;
  12053. p->header.ref_count = 1;
  12054. p->is_wide_char = str->is_wide_char;
  12055. p->len = str->len;
  12056. #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS
  12057. list_add_tail(&p->link, &rt->string_list);
  12058. #endif
  12059. memcpy(str8(p), str8(str), (str->len << str->is_wide_char) +
  12060. 1 - str->is_wide_char);
  12061. js_free_string(rt, str);
  12062. }
  12063. } else {
  12064. p = js_malloc_rt(rt, sizeof(JSAtomStruct)); /* empty wide string */
  12065. if (!p)
  12066. return JS_ATOM_NULL;
  12067. p->header.ref_count = 1;
  12068. p->is_wide_char = 1; /* Hack to represent NULL as a JSString */
  12069. p->len = 0;
  12070. #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS
  12071. list_add_tail(&p->link, &rt->string_list);
  12072. #endif
  12073. }
  12074. /* use an already free entry */
  12075. i = rt->atom_free_index;
  12076. rt->atom_free_index = atom_get_free(rt->atom_array[i]);
  12077. rt->atom_array[i] = p;
  12078. p->hash = h;
  12079. p->hash_next = i; /* atom_index */
  12080. p->atom_type = atom_type;
  12081. p->first_weak_ref = NULL;
  12082. rt->atom_count++;
  12083. if (atom_type != JS_ATOM_TYPE_SYMBOL) {
  12084. p->hash_next = rt->atom_hash[h1];
  12085. rt->atom_hash[h1] = i;
  12086. if (unlikely(rt->atom_count >= rt->atom_count_resize))
  12087. JS_ResizeAtomHash(rt, rt->atom_hash_size * 2);
  12088. }
  12089. // JS_DumpAtoms(rt);
  12090. return i;
  12091. fail:
  12092. i = JS_ATOM_NULL;
  12093. done:
  12094. if (str)
  12095. js_free_string(rt, str);
  12096. return i;
  12097. }
  12098. // XXX: `str` must be pure ASCII. No UTF-8 encoded strings
  12099. // XXX: `str` must not be the string representation of a small integer
  12100. static JSAtom __JS_NewAtomInit(JSRuntime *rt, const char *str, int len,
  12101. int atom_type)
  12102. {
  12103. JSString *p;
  12104. p = js_alloc_string_rt(rt, len, 0);
  12105. if (!p)
  12106. return JS_ATOM_NULL;
  12107. memcpy(str8(p), str, len);
  12108. str8(p)[len] = '\0';
  12109. return __JS_NewAtom(rt, p, atom_type);
  12110. }
  12111. // XXX: `str` must be raw 8-bit contents. No UTF-8 encoded strings
  12112. static JSAtom __JS_FindAtom(JSRuntime *rt, const char *str, size_t len,
  12113. int atom_type)
  12114. {
  12115. uint32_t h, h1, i;
  12116. JSAtomStruct *p;
  12117. h = hash_string8((const uint8_t *)str, len, JS_ATOM_TYPE_STRING);
  12118. h &= JS_ATOM_HASH_MASK;
  12119. h1 = h & (rt->atom_hash_size - 1);
  12120. i = rt->atom_hash[h1];
  12121. while (i != 0) {
  12122. p = rt->atom_array[i];
  12123. if (p->hash == h &&
  12124. p->atom_type == JS_ATOM_TYPE_STRING &&
  12125. p->len == len &&
  12126. p->is_wide_char == 0 &&
  12127. memcmp(str8(p), str, len) == 0) {
  12128. if (!__JS_AtomIsConst(i))
  12129. p->header.ref_count++;
  12130. return i;
  12131. }
  12132. i = p->hash_next;
  12133. }
  12134. return JS_ATOM_NULL;
  12135. }
  12136. static void JS_FreeAtomStruct(JSRuntime *rt, JSAtomStruct *p)
  12137. {
  12138. uint32_t i = p->hash_next; /* atom_index */
  12139. if (p->atom_type != JS_ATOM_TYPE_SYMBOL) {
  12140. JSAtomStruct *p0, *p1;
  12141. uint32_t h0;
  12142. h0 = p->hash & (rt->atom_hash_size - 1);
  12143. i = rt->atom_hash[h0];
  12144. p1 = rt->atom_array[i];
  12145. if (p1 == p) {
  12146. rt->atom_hash[h0] = p1->hash_next;
  12147. } else {
  12148. for(;;) {
  12149. assert(i != 0);
  12150. p0 = p1;
  12151. i = p1->hash_next;
  12152. p1 = rt->atom_array[i];
  12153. if (p1 == p) {
  12154. p0->hash_next = p1->hash_next;
  12155. break;
  12156. }
  12157. }
  12158. }
  12159. }
  12160. /* insert in free atom list */
  12161. rt->atom_array[i] = atom_set_free(rt->atom_free_index);
  12162. rt->atom_free_index = i;
  12163. if (unlikely(p->first_weak_ref)) {
  12164. reset_weak_ref(rt, &p->first_weak_ref);
  12165. }
  12166. /* free the string structure */
  12167. #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS
  12168. list_del(&p->link);
  12169. #endif
  12170. js_free_rt(rt, p);
  12171. rt->atom_count--;
  12172. assert(rt->atom_count >= 0);
  12173. }
  12174. static void __JS_FreeAtom(JSRuntime *rt, uint32_t i)
  12175. {
  12176. JSAtomStruct *p;
  12177. p = rt->atom_array[i];
  12178. if (--p->header.ref_count > 0)
  12179. return;
  12180. JS_FreeAtomStruct(rt, p);
  12181. }
  12182. /* Warning: 'p' is freed */
  12183. static JSAtom JS_NewAtomStr(JSContext *ctx, JSString *p)
  12184. {
  12185. JSRuntime *rt = ctx->rt;
  12186. uint32_t n;
  12187. if (is_num_string(&n, p)) {
  12188. if (n <= JS_ATOM_MAX_INT) {
  12189. js_free_string(rt, p);
  12190. return __JS_AtomFromUInt32(n);
  12191. }
  12192. }
  12193. /* XXX: should generate an exception */
  12194. return __JS_NewAtom(rt, p, JS_ATOM_TYPE_STRING);
  12195. }
  12196. /* `str` may be pure ASCII or UTF-8 encoded */
  12197. JSAtom JS_NewAtomLen(JSContext *ctx, const char *str, size_t len)
  12198. {
  12199. JSValue val;
  12200. if (len == 0 || !is_digit(*str)) {
  12201. // TODO(chqrlie): this does not work if `str` has UTF-8 encoded contents
  12202. // bug example: `({ "\u00c3\u00a9": 1 }).\u00e9` evaluates to `1`.
  12203. JSAtom atom = __JS_FindAtom(ctx->rt, str, len, JS_ATOM_TYPE_STRING);
  12204. if (atom)
  12205. return atom;
  12206. }
  12207. val = JS_NewStringLen(ctx, str, len);
  12208. if (JS_IsException(val))
  12209. return JS_ATOM_NULL;
  12210. return JS_NewAtomStr(ctx, JS_VALUE_GET_STRING(val));
  12211. }
  12212. /* `str` may be pure ASCII or UTF-8 encoded */
  12213. JSAtom JS_NewAtom(JSContext *ctx, const char *str)
  12214. {
  12215. return JS_NewAtomLen(ctx, str, strlen(str));
  12216. }
  12217. JSAtom JS_NewAtomUInt32(JSContext *ctx, uint32_t n)
  12218. {
  12219. if (n <= JS_ATOM_MAX_INT) {
  12220. return __JS_AtomFromUInt32(n);
  12221. } else {
  12222. char buf[16];
  12223. size_t len = u32toa(buf, n);
  12224. JSValue val = js_new_string8_len(ctx, buf, len);
  12225. if (JS_IsException(val))
  12226. return JS_ATOM_NULL;
  12227. return __JS_NewAtom(ctx->rt, JS_VALUE_GET_STRING(val),
  12228. JS_ATOM_TYPE_STRING);
  12229. }
  12230. }
  12231. static JSAtom JS_NewAtomInt64(JSContext *ctx, int64_t n)
  12232. {
  12233. if ((uint64_t)n <= JS_ATOM_MAX_INT) {
  12234. return __JS_AtomFromUInt32((uint32_t)n);
  12235. } else {
  12236. char buf[24];
  12237. size_t len = i64toa(buf, n);
  12238. JSValue val = js_new_string8_len(ctx, buf, len);
  12239. if (JS_IsException(val))
  12240. return JS_ATOM_NULL;
  12241. return __JS_NewAtom(ctx->rt, JS_VALUE_GET_STRING(val),
  12242. JS_ATOM_TYPE_STRING);
  12243. }
  12244. }
  12245. /* 'p' is freed */
  12246. static JSValue JS_NewSymbolInternal(JSContext *ctx, JSString *p, int atom_type)
  12247. {
  12248. JSRuntime *rt = ctx->rt;
  12249. JSAtom atom;
  12250. atom = __JS_NewAtom(rt, p, atom_type);
  12251. if (atom == JS_ATOM_NULL)
  12252. return JS_ThrowOutOfMemory(ctx);
  12253. return JS_MKPTR(JS_TAG_SYMBOL, rt->atom_array[atom]);
  12254. }
  12255. /* descr must be a non-numeric string atom */
  12256. static JSValue JS_NewSymbolFromAtom(JSContext *ctx, JSAtom descr,
  12257. int atom_type)
  12258. {
  12259. JSRuntime *rt = ctx->rt;
  12260. JSString *p;
  12261. assert(!__JS_AtomIsTaggedInt(descr));
  12262. assert(descr < rt->atom_size);
  12263. p = rt->atom_array[descr];
  12264. js_dup(JS_MKPTR(JS_TAG_STRING, p));
  12265. return JS_NewSymbolInternal(ctx, p, atom_type);
  12266. }
  12267. /* `description` may be pure ASCII or UTF-8 encoded */
  12268. JSValue JS_NewSymbol(JSContext *ctx, const char *description, bool is_global)
  12269. {
  12270. JSAtom atom = JS_NewAtom(ctx, description);
  12271. if (atom == JS_ATOM_NULL)
  12272. return JS_EXCEPTION;
  12273. return JS_NewSymbolFromAtom(ctx, atom, is_global ? JS_ATOM_TYPE_GLOBAL_SYMBOL : JS_ATOM_TYPE_SYMBOL);
  12274. }
  12275. #define ATOM_GET_STR_BUF_SIZE 64
  12276. static const char *JS_AtomGetStrRT(JSRuntime *rt, char *buf, int buf_size,
  12277. JSAtom atom)
  12278. {
  12279. if (__JS_AtomIsTaggedInt(atom)) {
  12280. snprintf(buf, buf_size, "%u", __JS_AtomToUInt32(atom));
  12281. } else if (atom == JS_ATOM_NULL) {
  12282. snprintf(buf, buf_size, "<null>");
  12283. } else if (atom >= rt->atom_size) {
  12284. assert(atom < rt->atom_size);
  12285. snprintf(buf, buf_size, "<invalid %x>", atom);
  12286. } else {
  12287. JSAtomStruct *p = rt->atom_array[atom];
  12288. *buf = '\0';
  12289. if (atom_is_free(p)) {
  12290. assert(!atom_is_free(p));
  12291. snprintf(buf, buf_size, "<free %x>", atom);
  12292. } else if (p != NULL) {
  12293. JSString *str = p;
  12294. if (str->is_wide_char) {
  12295. /* encode surrogates correctly */
  12296. utf8_encode_buf16(buf, buf_size, str16(str), str->len);
  12297. } else {
  12298. utf8_encode_buf8(buf, buf_size, str8(str), str->len);
  12299. }
  12300. }
  12301. }
  12302. return buf;
  12303. }
  12304. static const char *JS_AtomGetStr(JSContext *ctx, char *buf, int buf_size, JSAtom atom)
  12305. {
  12306. return JS_AtomGetStrRT(ctx->rt, buf, buf_size, atom);
  12307. }
  12308. static JSValue __JS_AtomToValue(JSContext *ctx, JSAtom atom, bool force_string)
  12309. {
  12310. char buf[ATOM_GET_STR_BUF_SIZE];
  12311. if (__JS_AtomIsTaggedInt(atom)) {
  12312. size_t len = u32toa(buf, __JS_AtomToUInt32(atom));
  12313. return js_new_string8_len(ctx, buf, len);
  12314. } else {
  12315. JSRuntime *rt = ctx->rt;
  12316. JSAtomStruct *p;
  12317. assert(atom < rt->atom_size);
  12318. p = rt->atom_array[atom];
  12319. if (p->atom_type == JS_ATOM_TYPE_STRING) {
  12320. goto ret_string;
  12321. } else if (force_string) {
  12322. if (p->len == 0 && p->is_wide_char != 0) {
  12323. /* no description string */
  12324. p = rt->atom_array[JS_ATOM_empty_string];
  12325. }
  12326. ret_string:
  12327. return js_dup(JS_MKPTR(JS_TAG_STRING, p));
  12328. } else {
  12329. return js_dup(JS_MKPTR(JS_TAG_SYMBOL, p));
  12330. }
  12331. }
  12332. }
  12333. JSValue JS_AtomToValue(JSContext *ctx, JSAtom atom)
  12334. {
  12335. return __JS_AtomToValue(ctx, atom, false);
  12336. }
  12337. JSValue JS_AtomToString(JSContext *ctx, JSAtom atom)
  12338. {
  12339. return __JS_AtomToValue(ctx, atom, true);
  12340. }
  12341. /* return true if the atom is an array index (i.e. 0 <= index <=
  12342. 2^32-2 and return its value */
  12343. static bool JS_AtomIsArrayIndex(JSContext *ctx, uint32_t *pval, JSAtom atom)
  12344. {
  12345. if (__JS_AtomIsTaggedInt(atom)) {
  12346. *pval = __JS_AtomToUInt32(atom);
  12347. return true;
  12348. } else {
  12349. JSRuntime *rt = ctx->rt;
  12350. JSAtomStruct *p;
  12351. uint32_t val;
  12352. assert(atom < rt->atom_size);
  12353. p = rt->atom_array[atom];
  12354. if (p->atom_type == JS_ATOM_TYPE_STRING &&
  12355. is_num_string(&val, p) && val != -1) {
  12356. *pval = val;
  12357. return true;
  12358. } else {
  12359. *pval = 0;
  12360. return false;
  12361. }
  12362. }
  12363. }
  12364. /* This test must be fast if atom is not a numeric index (e.g. a
  12365. method name). Return JS_UNDEFINED if not a numeric
  12366. index. JS_EXCEPTION can also be returned. */
  12367. static JSValue JS_AtomIsNumericIndex1(JSContext *ctx, JSAtom atom)
  12368. {
  12369. JSRuntime *rt = ctx->rt;
  12370. JSAtomStruct *p1;
  12371. JSString *p;
  12372. int c, len, ret;
  12373. JSValue num, str;
  12374. if (__JS_AtomIsTaggedInt(atom))
  12375. return js_int32(__JS_AtomToUInt32(atom));
  12376. assert(atom < rt->atom_size);
  12377. p1 = rt->atom_array[atom];
  12378. if (p1->atom_type != JS_ATOM_TYPE_STRING)
  12379. return JS_UNDEFINED;
  12380. p = p1;
  12381. len = p->len;
  12382. if (p->is_wide_char) {
  12383. const uint16_t *r = str16(p), *r_end = str16(p) + len;
  12384. if (r >= r_end)
  12385. return JS_UNDEFINED;
  12386. c = *r;
  12387. if (c == '-') {
  12388. if (r >= r_end)
  12389. return JS_UNDEFINED;
  12390. r++;
  12391. c = *r;
  12392. /* -0 case is specific */
  12393. if (c == '0' && len == 2)
  12394. goto minus_zero;
  12395. }
  12396. /* XXX: should test NaN, but the tests do not check it */
  12397. if (!is_num(c)) {
  12398. /* XXX: String should be normalized, therefore 8-bit only */
  12399. const uint16_t nfinity16[7] = { 'n', 'f', 'i', 'n', 'i', 't', 'y' };
  12400. if (!(c =='I' && (r_end - r) == 8 &&
  12401. !memcmp(r + 1, nfinity16, sizeof(nfinity16))))
  12402. return JS_UNDEFINED;
  12403. }
  12404. } else {
  12405. const uint8_t *r = str8(p), *r_end = str8(p) + len;
  12406. if (r >= r_end)
  12407. return JS_UNDEFINED;
  12408. c = *r;
  12409. if (c == '-') {
  12410. if (r >= r_end)
  12411. return JS_UNDEFINED;
  12412. r++;
  12413. c = *r;
  12414. /* -0 case is specific */
  12415. if (c == '0' && len == 2) {
  12416. minus_zero:
  12417. return js_float64(-0.0);
  12418. }
  12419. }
  12420. if (!is_num(c)) {
  12421. if (!(c =='I' && (r_end - r) == 8 &&
  12422. !memcmp(r + 1, "nfinity", 7)))
  12423. return JS_UNDEFINED;
  12424. }
  12425. }
  12426. /* this is ECMA CanonicalNumericIndexString primitive */
  12427. num = JS_ToNumber(ctx, JS_MKPTR(JS_TAG_STRING, p));
  12428. if (JS_IsException(num))
  12429. return num;
  12430. str = JS_ToString(ctx, num);
  12431. if (JS_IsException(str)) {
  12432. JS_FreeValue(ctx, num);
  12433. return str;
  12434. }
  12435. ret = js_string_eq(p, JS_VALUE_GET_STRING(str));
  12436. JS_FreeValue(ctx, str);
  12437. if (ret) {
  12438. return num;
  12439. } else {
  12440. JS_FreeValue(ctx, num);
  12441. return JS_UNDEFINED;
  12442. }
  12443. }
  12444. /* return -1 if exception or true/false */
  12445. static int JS_AtomIsNumericIndex(JSContext *ctx, JSAtom atom)
  12446. {
  12447. JSValue num;
  12448. num = JS_AtomIsNumericIndex1(ctx, atom);
  12449. if (likely(JS_IsUndefined(num)))
  12450. return false;
  12451. if (JS_IsException(num))
  12452. return -1;
  12453. JS_FreeValue(ctx, num);
  12454. return true;
  12455. }
  12456. void JS_FreeAtom(JSContext *ctx, JSAtom v)
  12457. {
  12458. if (!__JS_AtomIsConst(v))
  12459. __JS_FreeAtom(ctx->rt, v);
  12460. }
  12461. void JS_FreeAtomRT(JSRuntime *rt, JSAtom v)
  12462. {
  12463. if (!__JS_AtomIsConst(v))
  12464. __JS_FreeAtom(rt, v);
  12465. }
  12466. /* return true if 'v' is a symbol with a string description */
  12467. static bool JS_AtomSymbolHasDescription(JSContext *ctx, JSAtom v)
  12468. {
  12469. JSRuntime *rt;
  12470. JSAtomStruct *p;
  12471. rt = ctx->rt;
  12472. if (__JS_AtomIsTaggedInt(v))
  12473. return false;
  12474. p = rt->atom_array[v];
  12475. return (((p->atom_type == JS_ATOM_TYPE_SYMBOL &&
  12476. p->hash == JS_ATOM_HASH_SYMBOL) ||
  12477. p->atom_type == JS_ATOM_TYPE_GLOBAL_SYMBOL) &&
  12478. !(p->len == 0 && p->is_wide_char != 0));
  12479. }
  12480. static __maybe_unused void print_atom(JSContext *ctx, JSAtom atom)
  12481. {
  12482. char buf[ATOM_GET_STR_BUF_SIZE];
  12483. const char *p;
  12484. int i;
  12485. /* XXX: should handle embedded null characters */
  12486. /* XXX: should move encoding code to JS_AtomGetStr */
  12487. p = JS_AtomGetStr(ctx, buf, sizeof(buf), atom);
  12488. for (i = 0; p[i]; i++) {
  12489. int c = (unsigned char)p[i];
  12490. if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  12491. (c == '_' || c == '$') || (c >= '0' && c <= '9' && i > 0)))
  12492. break;
  12493. }
  12494. if (i > 0 && p[i] == '\0') {
  12495. printf("%s", p);
  12496. } else {
  12497. putchar('"');
  12498. printf("%.*s", i, p);
  12499. for (; p[i]; i++) {
  12500. int c = (unsigned char)p[i];
  12501. if (c == '\"' || c == '\\') {
  12502. putchar('\\');
  12503. putchar(c);
  12504. } else if (c >= ' ' && c <= 126) {
  12505. putchar(c);
  12506. } else if (c == '\n') {
  12507. putchar('\\');
  12508. putchar('n');
  12509. } else {
  12510. printf("\\u%04x", c);
  12511. }
  12512. }
  12513. putchar('\"');
  12514. }
  12515. }
  12516. /* free with JS_FreeCString() */
  12517. const char *JS_AtomToCString(JSContext *ctx, JSAtom atom)
  12518. {
  12519. JSValue str;
  12520. const char *cstr;
  12521. str = JS_AtomToString(ctx, atom);
  12522. if (JS_IsException(str))
  12523. return NULL;
  12524. cstr = JS_ToCString(ctx, str);
  12525. JS_FreeValue(ctx, str);
  12526. return cstr;
  12527. }
  12528. /* return a string atom containing name concatenated with str1 */
  12529. /* `str1` may be pure ASCII or UTF-8 encoded */
  12530. // TODO(chqrlie): use string concatenation instead of UTF-8 conversion
  12531. static JSAtom js_atom_concat_str(JSContext *ctx, JSAtom name, const char *str1)
  12532. {
  12533. JSValue str;
  12534. JSAtom atom;
  12535. const char *cstr;
  12536. char *cstr2;
  12537. size_t len, len1;
  12538. str = JS_AtomToString(ctx, name);
  12539. if (JS_IsException(str))
  12540. return JS_ATOM_NULL;
  12541. cstr = JS_ToCStringLen(ctx, &len, str);
  12542. if (!cstr)
  12543. goto fail;
  12544. len1 = strlen(str1);
  12545. cstr2 = js_malloc(ctx, len + len1 + 1);
  12546. if (!cstr2)
  12547. goto fail;
  12548. memcpy(cstr2, cstr, len);
  12549. memcpy(cstr2 + len, str1, len1);
  12550. cstr2[len + len1] = '\0';
  12551. atom = JS_NewAtomLen(ctx, cstr2, len + len1);
  12552. js_free(ctx, cstr2);
  12553. JS_FreeCString(ctx, cstr);
  12554. JS_FreeValue(ctx, str);
  12555. return atom;
  12556. fail:
  12557. JS_FreeCString(ctx, cstr);
  12558. JS_FreeValue(ctx, str);
  12559. return JS_ATOM_NULL;
  12560. }
  12561. static JSAtom js_atom_concat_num(JSContext *ctx, JSAtom name, uint32_t n)
  12562. {
  12563. char buf[16];
  12564. u32toa(buf, n);
  12565. return js_atom_concat_str(ctx, name, buf);
  12566. }
  12567. static inline bool JS_IsEmptyString(JSValueConst v)
  12568. {
  12569. return JS_VALUE_GET_TAG(v) == JS_TAG_STRING && JS_VALUE_GET_STRING(v)->len == 0;
  12570. }
  12571. /* JSClass support */
  12572. /* a new class ID is allocated if *pclass_id == 0, otherwise *pclass_id is left unchanged */
  12573. JSClassID JS_NewClassID(JSRuntime *rt, JSClassID *pclass_id)
  12574. {
  12575. JSClassID class_id = *pclass_id;
  12576. if (class_id == 0) {
  12577. class_id = rt->js_class_id_alloc++;
  12578. *pclass_id = class_id;
  12579. }
  12580. return class_id;
  12581. }
  12582. JSClassID JS_GetClassID(JSValueConst v)
  12583. {
  12584. JSObject *p;
  12585. if (JS_VALUE_GET_TAG(v) != JS_TAG_OBJECT)
  12586. return JS_INVALID_CLASS_ID;
  12587. p = JS_VALUE_GET_OBJ(v);
  12588. return p->class_id;
  12589. }
  12590. bool JS_IsRegisteredClass(JSRuntime *rt, JSClassID class_id)
  12591. {
  12592. return (class_id < rt->class_count &&
  12593. rt->class_array[class_id].class_id != 0);
  12594. }
  12595. /* create a new object internal class. Return -1 if error, 0 if
  12596. OK. The finalizer can be NULL if none is needed. */
  12597. static int JS_NewClass1(JSRuntime *rt, JSClassID class_id,
  12598. const JSClassDef *class_def, JSAtom name)
  12599. {
  12600. int new_size, i;
  12601. JSClass *cl, *new_class_array;
  12602. struct list_head *el;
  12603. if (class_id >= (1 << 16))
  12604. return -1;
  12605. if (class_id < rt->class_count &&
  12606. rt->class_array[class_id].class_id != 0)
  12607. return -1;
  12608. if (class_id >= rt->class_count) {
  12609. new_size = max_int(JS_CLASS_INIT_COUNT,
  12610. max_int(class_id + 1, rt->class_count * 3 / 2));
  12611. /* reallocate the context class prototype array, if any */
  12612. list_for_each(el, &rt->context_list) {
  12613. JSContext *ctx = list_entry(el, JSContext, link);
  12614. JSValue *new_tab;
  12615. new_tab = js_realloc_rt(rt, ctx->class_proto,
  12616. sizeof(ctx->class_proto[0]) * new_size);
  12617. if (!new_tab)
  12618. return -1;
  12619. for(i = rt->class_count; i < new_size; i++)
  12620. new_tab[i] = JS_NULL;
  12621. ctx->class_proto = new_tab;
  12622. }
  12623. /* reallocate the class array */
  12624. new_class_array = js_realloc_rt(rt, rt->class_array,
  12625. sizeof(JSClass) * new_size);
  12626. if (!new_class_array)
  12627. return -1;
  12628. memset(new_class_array + rt->class_count, 0,
  12629. (new_size - rt->class_count) * sizeof(JSClass));
  12630. rt->class_array = new_class_array;
  12631. rt->class_count = new_size;
  12632. }
  12633. cl = &rt->class_array[class_id];
  12634. cl->class_id = class_id;
  12635. cl->class_name = JS_DupAtomRT(rt, name);
  12636. cl->finalizer = class_def->finalizer;
  12637. cl->gc_mark = class_def->gc_mark;
  12638. cl->call = class_def->call;
  12639. cl->exotic = class_def->exotic;
  12640. return 0;
  12641. }
  12642. int JS_NewClass(JSRuntime *rt, JSClassID class_id, const JSClassDef *class_def)
  12643. {
  12644. int ret, len;
  12645. JSAtom name;
  12646. // XXX: class_def->class_name must be raw 8-bit contents. No UTF-8 encoded strings
  12647. len = strlen(class_def->class_name);
  12648. name = __JS_FindAtom(rt, class_def->class_name, len, JS_ATOM_TYPE_STRING);
  12649. if (name == JS_ATOM_NULL) {
  12650. name = __JS_NewAtomInit(rt, class_def->class_name, len, JS_ATOM_TYPE_STRING);
  12651. if (name == JS_ATOM_NULL)
  12652. return -1;
  12653. }
  12654. ret = JS_NewClass1(rt, class_id, class_def, name);
  12655. JS_FreeAtomRT(rt, name);
  12656. return ret;
  12657. }
  12658. // XXX: `buf` contains raw 8-bit data, no UTF-8 decoding is performed
  12659. // XXX: no special case for len == 0
  12660. static JSValue js_new_string8_len(JSContext *ctx, const char *buf, int len)
  12661. {
  12662. JSString *str;
  12663. str = js_alloc_string(ctx, len, 0);
  12664. if (!str)
  12665. return JS_EXCEPTION;
  12666. memcpy(str8(str), buf, len);
  12667. str8(str)[len] = '\0';
  12668. return JS_MKPTR(JS_TAG_STRING, str);
  12669. }
  12670. // XXX: `buf` contains raw 8-bit data, no UTF-8 decoding is performed
  12671. // XXX: no special case for the empty string
  12672. static inline JSValue js_new_string8(JSContext *ctx, const char *str)
  12673. {
  12674. return js_new_string8_len(ctx, str, strlen(str));
  12675. }
  12676. static JSValue js_new_string16_len(JSContext *ctx, const uint16_t *buf, int len)
  12677. {
  12678. JSString *str;
  12679. str = js_alloc_string(ctx, len, 1);
  12680. if (!str)
  12681. return JS_EXCEPTION;
  12682. memcpy(str16(str), buf, len * 2);
  12683. return JS_MKPTR(JS_TAG_STRING, str);
  12684. }
  12685. static JSValue js_new_string_char(JSContext *ctx, uint16_t c)
  12686. {
  12687. if (c < 0x100) {
  12688. char ch8 = c;
  12689. return js_new_string8_len(ctx, &ch8, 1);
  12690. } else {
  12691. uint16_t ch16 = c;
  12692. return js_new_string16_len(ctx, &ch16, 1);
  12693. }
  12694. }
  12695. static JSValue js_sub_string(JSContext *ctx, JSString *p, int start, int end)
  12696. {
  12697. int len = end - start;
  12698. if (start == 0 && end == p->len) {
  12699. return js_dup(JS_MKPTR(JS_TAG_STRING, p));
  12700. }
  12701. if (len <= 0) {
  12702. return JS_AtomToString(ctx, JS_ATOM_empty_string);
  12703. }
  12704. if (p->is_wide_char) {
  12705. JSString *str;
  12706. int i;
  12707. uint16_t c = 0;
  12708. for (i = start; i < end; i++) {
  12709. c |= str16(p)[i];
  12710. }
  12711. if (c > 0xFF)
  12712. return js_new_string16_len(ctx, str16(p) + start, len);
  12713. str = js_alloc_string(ctx, len, 0);
  12714. if (!str)
  12715. return JS_EXCEPTION;
  12716. for (i = 0; i < len; i++) {
  12717. str8(str)[i] = str16(p)[start + i];
  12718. }
  12719. str8(str)[len] = '\0';
  12720. return JS_MKPTR(JS_TAG_STRING, str);
  12721. } else {
  12722. return js_new_string8_len(ctx, (const char *)(str8(p) + start), len);
  12723. }
  12724. }
  12725. typedef struct StringBuffer {
  12726. JSContext *ctx;
  12727. JSString *str;
  12728. int len;
  12729. int size;
  12730. int is_wide_char;
  12731. int error_status;
  12732. } StringBuffer;
  12733. /* It is valid to call string_buffer_end() and all string_buffer functions even
  12734. if string_buffer_init() or another string_buffer function returns an error.
  12735. If the error_status is set, string_buffer_end() returns JS_EXCEPTION.
  12736. */
  12737. static int string_buffer_init2(JSContext *ctx, StringBuffer *s, int size,
  12738. int is_wide)
  12739. {
  12740. s->ctx = ctx;
  12741. s->size = size;
  12742. s->len = 0;
  12743. s->is_wide_char = is_wide;
  12744. s->error_status = 0;
  12745. s->str = js_alloc_string(ctx, size, is_wide);
  12746. if (unlikely(!s->str)) {
  12747. s->size = 0;
  12748. return s->error_status = -1;
  12749. }
  12750. #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS
  12751. /* the StringBuffer may reallocate the JSString, only link it at the end */
  12752. list_del(&s->str->link);
  12753. #endif
  12754. return 0;
  12755. }
  12756. static inline int string_buffer_init(JSContext *ctx, StringBuffer *s, int size)
  12757. {
  12758. return string_buffer_init2(ctx, s, size, 0);
  12759. }
  12760. static void string_buffer_free(StringBuffer *s)
  12761. {
  12762. js_free(s->ctx, s->str);
  12763. s->str = NULL;
  12764. }
  12765. static int string_buffer_set_error(StringBuffer *s)
  12766. {
  12767. js_free(s->ctx, s->str);
  12768. s->str = NULL;
  12769. s->size = 0;
  12770. s->len = 0;
  12771. return s->error_status = -1;
  12772. }
  12773. static no_inline int string_buffer_widen(StringBuffer *s, int size)
  12774. {
  12775. JSString *str;
  12776. size_t slack;
  12777. int i;
  12778. if (s->error_status)
  12779. return -1;
  12780. str = js_realloc2(s->ctx, s->str, sizeof(JSString) + (size << 1), &slack);
  12781. if (!str)
  12782. return string_buffer_set_error(s);
  12783. size += slack >> 1;
  12784. for(i = s->len; i-- > 0;) {
  12785. str16(str)[i] = str8(str)[i];
  12786. }
  12787. s->is_wide_char = 1;
  12788. s->size = size;
  12789. s->str = str;
  12790. return 0;
  12791. }
  12792. static no_inline int string_buffer_realloc(StringBuffer *s, int new_len, int c)
  12793. {
  12794. JSString *new_str;
  12795. int new_size;
  12796. size_t new_size_bytes, slack;
  12797. if (s->error_status)
  12798. return -1;
  12799. if (new_len > JS_STRING_LEN_MAX) {
  12800. JS_ThrowRangeError(s->ctx, "invalid string length");
  12801. return string_buffer_set_error(s);
  12802. }
  12803. new_size = min_int(max_int(new_len, s->size * 3 / 2), JS_STRING_LEN_MAX);
  12804. if (!s->is_wide_char && c >= 0x100) {
  12805. return string_buffer_widen(s, new_size);
  12806. }
  12807. new_size_bytes = sizeof(JSString) + (new_size << s->is_wide_char) + 1 - s->is_wide_char;
  12808. new_str = js_realloc2(s->ctx, s->str, new_size_bytes, &slack);
  12809. if (!new_str)
  12810. return string_buffer_set_error(s);
  12811. new_size = min_int(new_size + (slack >> s->is_wide_char), JS_STRING_LEN_MAX);
  12812. s->size = new_size;
  12813. s->str = new_str;
  12814. return 0;
  12815. }
  12816. static no_inline int string_buffer_putc_slow(StringBuffer *s, uint32_t c)
  12817. {
  12818. if (unlikely(s->len >= s->size)) {
  12819. if (string_buffer_realloc(s, s->len + 1, c))
  12820. return -1;
  12821. }
  12822. if (s->is_wide_char) {
  12823. str16(s->str)[s->len++] = c;
  12824. } else if (c < 0x100) {
  12825. str8(s->str)[s->len++] = c;
  12826. } else {
  12827. if (string_buffer_widen(s, s->size))
  12828. return -1;
  12829. str16(s->str)[s->len++] = c;
  12830. }
  12831. return 0;
  12832. }
  12833. /* 0 <= c <= 0xff */
  12834. static int string_buffer_putc8(StringBuffer *s, uint32_t c)
  12835. {
  12836. if (unlikely(s->len >= s->size)) {
  12837. if (string_buffer_realloc(s, s->len + 1, c))
  12838. return -1;
  12839. }
  12840. if (s->is_wide_char) {
  12841. str16(s->str)[s->len++] = c;
  12842. } else {
  12843. str8(s->str)[s->len++] = c;
  12844. }
  12845. return 0;
  12846. }
  12847. /* 0 <= c <= 0xffff */
  12848. static int string_buffer_putc16(StringBuffer *s, uint32_t c)
  12849. {
  12850. if (likely(s->len < s->size)) {
  12851. if (s->is_wide_char) {
  12852. str16(s->str)[s->len++] = c;
  12853. return 0;
  12854. } else if (c < 0x100) {
  12855. str8(s->str)[s->len++] = c;
  12856. return 0;
  12857. }
  12858. }
  12859. return string_buffer_putc_slow(s, c);
  12860. }
  12861. /* 0 <= c <= 0x10ffff */
  12862. static int string_buffer_putc(StringBuffer *s, uint32_t c)
  12863. {
  12864. if (unlikely(c >= 0x10000)) {
  12865. /* surrogate pair */
  12866. if (string_buffer_putc16(s, get_hi_surrogate(c)))
  12867. return -1;
  12868. c = get_lo_surrogate(c);
  12869. }
  12870. return string_buffer_putc16(s, c);
  12871. }
  12872. static int string_getc(JSString *p, int *pidx)
  12873. {
  12874. int idx, c, c1;
  12875. idx = *pidx;
  12876. if (p->is_wide_char) {
  12877. c = str16(p)[idx++];
  12878. if (is_hi_surrogate(c) && idx < p->len) {
  12879. c1 = str16(p)[idx];
  12880. if (is_lo_surrogate(c1)) {
  12881. c = from_surrogate(c, c1);
  12882. idx++;
  12883. }
  12884. }
  12885. } else {
  12886. c = str8(p)[idx++];
  12887. }
  12888. *pidx = idx;
  12889. return c;
  12890. }
  12891. static int string_buffer_write8(StringBuffer *s, const uint8_t *p, int len)
  12892. {
  12893. int i;
  12894. if (s->len + len > s->size) {
  12895. if (string_buffer_realloc(s, s->len + len, 0))
  12896. return -1;
  12897. }
  12898. if (s->is_wide_char) {
  12899. for (i = 0; i < len; i++) {
  12900. str16(s->str)[s->len + i] = p[i];
  12901. }
  12902. s->len += len;
  12903. } else {
  12904. memcpy(&str8(s->str)[s->len], p, len);
  12905. s->len += len;
  12906. }
  12907. return 0;
  12908. }
  12909. static int string_buffer_write16(StringBuffer *s, const uint16_t *p, int len)
  12910. {
  12911. int c = 0, i;
  12912. for (i = 0; i < len; i++) {
  12913. c |= p[i];
  12914. }
  12915. if (s->len + len > s->size) {
  12916. if (string_buffer_realloc(s, s->len + len, c))
  12917. return -1;
  12918. } else if (!s->is_wide_char && c >= 0x100) {
  12919. if (string_buffer_widen(s, s->size))
  12920. return -1;
  12921. }
  12922. if (s->is_wide_char) {
  12923. memcpy(&str16(s->str)[s->len], p, len << 1);
  12924. s->len += len;
  12925. } else {
  12926. for (i = 0; i < len; i++) {
  12927. str8(s->str)[s->len + i] = p[i];
  12928. }
  12929. s->len += len;
  12930. }
  12931. return 0;
  12932. }
  12933. /* appending an ASCII string */
  12934. static int string_buffer_puts8(StringBuffer *s, const char *str)
  12935. {
  12936. return string_buffer_write8(s, (const uint8_t *)str, strlen(str));
  12937. }
  12938. static int string_buffer_concat(StringBuffer *s, JSString *p,
  12939. uint32_t from, uint32_t to)
  12940. {
  12941. if (to <= from)
  12942. return 0;
  12943. if (p->is_wide_char)
  12944. return string_buffer_write16(s, str16(p) + from, to - from);
  12945. else
  12946. return string_buffer_write8(s, str8(p) + from, to - from);
  12947. }
  12948. static int string_buffer_concat_value(StringBuffer *s, JSValueConst v)
  12949. {
  12950. JSString *p;
  12951. JSValue v1;
  12952. int res;
  12953. if (s->error_status) {
  12954. /* prevent exception overload */
  12955. return -1;
  12956. }
  12957. if (unlikely(JS_VALUE_GET_TAG(v) != JS_TAG_STRING)) {
  12958. v1 = JS_ToString(s->ctx, v);
  12959. if (JS_IsException(v1))
  12960. return string_buffer_set_error(s);
  12961. p = JS_VALUE_GET_STRING(v1);
  12962. res = string_buffer_concat(s, p, 0, p->len);
  12963. JS_FreeValue(s->ctx, v1);
  12964. return res;
  12965. }
  12966. p = JS_VALUE_GET_STRING(v);
  12967. return string_buffer_concat(s, p, 0, p->len);
  12968. }
  12969. static int string_buffer_concat_value_free(StringBuffer *s, JSValue v)
  12970. {
  12971. JSString *p;
  12972. int res;
  12973. if (s->error_status) {
  12974. /* prevent exception overload */
  12975. JS_FreeValue(s->ctx, v);
  12976. return -1;
  12977. }
  12978. if (unlikely(JS_VALUE_GET_TAG(v) != JS_TAG_STRING)) {
  12979. v = JS_ToStringFree(s->ctx, v);
  12980. if (JS_IsException(v))
  12981. return string_buffer_set_error(s);
  12982. }
  12983. p = JS_VALUE_GET_STRING(v);
  12984. res = string_buffer_concat(s, p, 0, p->len);
  12985. JS_FreeValue(s->ctx, v);
  12986. return res;
  12987. }
  12988. static int string_buffer_fill(StringBuffer *s, int c, int count)
  12989. {
  12990. /* XXX: optimize */
  12991. if (s->len + count > s->size) {
  12992. if (string_buffer_realloc(s, s->len + count, c))
  12993. return -1;
  12994. }
  12995. while (count-- > 0) {
  12996. if (string_buffer_putc16(s, c))
  12997. return -1;
  12998. }
  12999. return 0;
  13000. }
  13001. static JSValue string_buffer_end(StringBuffer *s)
  13002. {
  13003. JSString *str;
  13004. str = s->str;
  13005. if (s->error_status)
  13006. return JS_EXCEPTION;
  13007. if (s->len == 0) {
  13008. js_free(s->ctx, str);
  13009. s->str = NULL;
  13010. return JS_AtomToString(s->ctx, JS_ATOM_empty_string);
  13011. }
  13012. if (s->len < s->size) {
  13013. /* smaller size so js_realloc should not fail, but OK if it does */
  13014. /* XXX: should add some slack to avoid unnecessary calls */
  13015. /* XXX: might need to use malloc+free to ensure smaller size */
  13016. str = js_realloc_rt(s->ctx->rt, str, sizeof(JSString) +
  13017. (s->len << s->is_wide_char) + 1 - s->is_wide_char);
  13018. if (str == NULL)
  13019. str = s->str;
  13020. s->str = str;
  13021. }
  13022. if (!s->is_wide_char)
  13023. str8(str)[s->len] = 0;
  13024. #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS
  13025. list_add_tail(&str->link, &s->ctx->rt->string_list);
  13026. #endif
  13027. str->is_wide_char = s->is_wide_char;
  13028. str->len = s->len;
  13029. s->str = NULL;
  13030. return JS_MKPTR(JS_TAG_STRING, str);
  13031. }
  13032. /* create a string from a UTF-8 buffer */
  13033. JSValue JS_NewStringLen(JSContext *ctx, const char *buf, size_t buf_len)
  13034. {
  13035. JSString *str;
  13036. size_t len;
  13037. int kind;
  13038. if (buf_len <= 0) {
  13039. return JS_AtomToString(ctx, JS_ATOM_empty_string);
  13040. }
  13041. /* Compute string kind and length: 7-bit, 8-bit, 16-bit, 16-bit UTF-16 */
  13042. kind = utf8_scan(buf, buf_len, &len);
  13043. if (len > JS_STRING_LEN_MAX)
  13044. return JS_ThrowRangeError(ctx, "invalid string length");
  13045. switch (kind) {
  13046. case UTF8_PLAIN_ASCII:
  13047. str = js_alloc_string(ctx, len, 0);
  13048. if (!str)
  13049. return JS_EXCEPTION;
  13050. memcpy(str8(str), buf, len);
  13051. str8(str)[len] = '\0';
  13052. break;
  13053. case UTF8_NON_ASCII:
  13054. /* buf contains non-ASCII code-points, but limited to 8-bit values */
  13055. str = js_alloc_string(ctx, len, 0);
  13056. if (!str)
  13057. return JS_EXCEPTION;
  13058. utf8_decode_buf8(str8(str), len + 1, buf, buf_len);
  13059. break;
  13060. default:
  13061. // This causes a potential problem in JS_ThrowError if message is invalid
  13062. //if (kind & UTF8_HAS_ERRORS)
  13063. // return JS_ThrowRangeError(ctx, "invalid UTF-8 sequence");
  13064. str = js_alloc_string(ctx, len, 1);
  13065. if (!str)
  13066. return JS_EXCEPTION;
  13067. utf8_decode_buf16(str16(str), len, buf, buf_len);
  13068. break;
  13069. }
  13070. return JS_MKPTR(JS_TAG_STRING, str);
  13071. }
  13072. static JSValue JS_ConcatString3(JSContext *ctx, const char *str1,
  13073. JSValue str2, const char *str3)
  13074. {
  13075. StringBuffer b_s, *b = &b_s;
  13076. int len1, len3;
  13077. JSString *p;
  13078. if (unlikely(JS_VALUE_GET_TAG(str2) != JS_TAG_STRING)) {
  13079. str2 = JS_ToStringFree(ctx, str2);
  13080. if (JS_IsException(str2))
  13081. goto fail;
  13082. }
  13083. p = JS_VALUE_GET_STRING(str2);
  13084. len1 = strlen(str1);
  13085. len3 = strlen(str3);
  13086. if (string_buffer_init2(ctx, b, len1 + p->len + len3, p->is_wide_char))
  13087. goto fail;
  13088. string_buffer_write8(b, (const uint8_t *)str1, len1);
  13089. string_buffer_concat(b, p, 0, p->len);
  13090. string_buffer_write8(b, (const uint8_t *)str3, len3);
  13091. JS_FreeValue(ctx, str2);
  13092. return string_buffer_end(b);
  13093. fail:
  13094. JS_FreeValue(ctx, str2);
  13095. return JS_EXCEPTION;
  13096. }
  13097. /* `str` may be pure ASCII or UTF-8 encoded */
  13098. JSValue JS_NewAtomString(JSContext *ctx, const char *str)
  13099. {
  13100. JSAtom atom = JS_NewAtom(ctx, str);
  13101. if (atom == JS_ATOM_NULL)
  13102. return JS_EXCEPTION;
  13103. JSValue val = JS_AtomToString(ctx, atom);
  13104. JS_FreeAtom(ctx, atom);
  13105. return val;
  13106. }
  13107. /* return (NULL, 0) if exception. */
  13108. /* return pointer into a JSString with a live ref_count */
  13109. /* cesu8 determines if non-BMP1 codepoints are encoded as 1 or 2 utf-8 sequences */
  13110. const char *JS_ToCStringLen2(JSContext *ctx, size_t *plen, JSValueConst val1,
  13111. bool cesu8)
  13112. {
  13113. JSValue val;
  13114. JSString *str, *str_new;
  13115. int pos, len, c, c1;
  13116. JSObject *p;
  13117. uint8_t *q;
  13118. if (JS_VALUE_GET_TAG(val1) == JS_TAG_STRING) {
  13119. val = js_dup(val1);
  13120. goto go;
  13121. }
  13122. val = JS_ToString(ctx, val1);
  13123. if (!JS_IsException(val))
  13124. goto go;
  13125. // Stringification can fail when there is an exception pending,
  13126. // e.g. a stack overflow InternalError. Special-case exception
  13127. // objects to make debugging easier, look up the .message property
  13128. // and stringify that.
  13129. if (JS_VALUE_GET_TAG(val1) != JS_TAG_OBJECT)
  13130. goto fail;
  13131. p = JS_VALUE_GET_OBJ(val1);
  13132. if (p->class_id != JS_CLASS_ERROR)
  13133. goto fail;
  13134. val = JS_GetProperty(ctx, val1, JS_ATOM_message);
  13135. if (JS_VALUE_GET_TAG(val) != JS_TAG_STRING) {
  13136. JS_FreeValue(ctx, val);
  13137. goto fail;
  13138. }
  13139. go:
  13140. str = JS_VALUE_GET_STRING(val);
  13141. len = str->len;
  13142. if (!str->is_wide_char) {
  13143. const uint8_t *src = str8(str);
  13144. int count;
  13145. /* count the number of non-ASCII characters */
  13146. /* Scanning the whole string is required for ASCII strings,
  13147. and computing the number of non-ASCII bytes is less expensive
  13148. than testing each byte, hence this method is faster for ASCII
  13149. strings, which is the most common case.
  13150. */
  13151. count = 0;
  13152. for (pos = 0; pos < len; pos++) {
  13153. count += src[pos] >> 7;
  13154. }
  13155. if (count == 0) {
  13156. if (plen)
  13157. *plen = len;
  13158. return (const char *)src;
  13159. }
  13160. str_new = js_alloc_string(ctx, len + count, 0);
  13161. if (!str_new)
  13162. goto fail;
  13163. q = str8(str_new);
  13164. for (pos = 0; pos < len; pos++) {
  13165. c = src[pos];
  13166. if (c < 0x80) {
  13167. *q++ = c;
  13168. } else {
  13169. *q++ = (c >> 6) | 0xc0;
  13170. *q++ = (c & 0x3f) | 0x80;
  13171. }
  13172. }
  13173. } else {
  13174. const uint16_t *src = str16(str);
  13175. /* Allocate 3 bytes per 16 bit code point. Surrogate pairs may
  13176. produce 4 bytes but use 2 code points.
  13177. */
  13178. str_new = js_alloc_string(ctx, len * 3, 0);
  13179. if (!str_new)
  13180. goto fail;
  13181. q = str8(str_new);
  13182. pos = 0;
  13183. while (pos < len) {
  13184. c = src[pos++];
  13185. if (c < 0x80) {
  13186. *q++ = c;
  13187. } else {
  13188. if (is_hi_surrogate(c)) {
  13189. if (pos < len && !cesu8) {
  13190. c1 = src[pos];
  13191. if (is_lo_surrogate(c1)) {
  13192. pos++;
  13193. c = from_surrogate(c, c1);
  13194. } else {
  13195. /* Keep unmatched surrogate code points */
  13196. /* c = 0xfffd; */ /* error */
  13197. }
  13198. } else {
  13199. /* Keep unmatched surrogate code points */
  13200. /* c = 0xfffd; */ /* error */
  13201. }
  13202. }
  13203. q += utf8_encode(q, c);
  13204. }
  13205. }
  13206. }
  13207. *q = '\0';
  13208. str_new->len = q - str8(str_new);
  13209. JS_FreeValue(ctx, val);
  13210. if (plen)
  13211. *plen = str_new->len;
  13212. return (const char *)str8(str_new);
  13213. fail:
  13214. if (plen)
  13215. *plen = 0;
  13216. return NULL;
  13217. }
  13218. void JS_FreeCString(JSContext *ctx, const char *ptr)
  13219. {
  13220. if (!ptr)
  13221. return;
  13222. /* purposely removing constness */
  13223. JS_FreeValue(ctx, JS_MKPTR(JS_TAG_STRING, (JSString *)ptr - 1));
  13224. }
  13225. static int memcmp16_8(const uint16_t *src1, const uint8_t *src2, int len)
  13226. {
  13227. int c, i;
  13228. for(i = 0; i < len; i++) {
  13229. c = src1[i] - src2[i];
  13230. if (c != 0)
  13231. return c;
  13232. }
  13233. return 0;
  13234. }
  13235. static int memcmp16(const uint16_t *src1, const uint16_t *src2, int len)
  13236. {
  13237. int c, i;
  13238. for(i = 0; i < len; i++) {
  13239. c = src1[i] - src2[i];
  13240. if (c != 0)
  13241. return c;
  13242. }
  13243. return 0;
  13244. }
  13245. static int js_string_memcmp(JSString *p1, JSString *p2, int len)
  13246. {
  13247. int res;
  13248. if (likely(!p1->is_wide_char)) {
  13249. if (likely(!p2->is_wide_char))
  13250. res = memcmp(str8(p1), str8(p2), len);
  13251. else
  13252. res = -memcmp16_8(str16(p2), str8(p1), len);
  13253. } else {
  13254. if (!p2->is_wide_char)
  13255. res = memcmp16_8(str16(p1), str8(p2), len);
  13256. else
  13257. res = memcmp16(str16(p1), str16(p2), len);
  13258. }
  13259. return res;
  13260. }
  13261. static bool js_string_eq(JSString *p1, JSString *p2) {
  13262. if (p1->len != p2->len)
  13263. return false;
  13264. return js_string_memcmp(p1, p2, p1->len) == 0;
  13265. }
  13266. /* return < 0, 0 or > 0 */
  13267. static int js_string_compare(JSString *p1, JSString *p2)
  13268. {
  13269. int res, len;
  13270. len = min_int(p1->len, p2->len);
  13271. res = js_string_memcmp(p1, p2, len);
  13272. if (res == 0)
  13273. res = compare_u32(p1->len, p2->len);
  13274. return res;
  13275. }
  13276. static void copy_str16(uint16_t *dst, JSString *p, int offset, int len)
  13277. {
  13278. if (p->is_wide_char) {
  13279. memcpy(dst, str16(p) + offset, len * 2);
  13280. } else {
  13281. const uint8_t *src1 = str8(p) + offset;
  13282. int i;
  13283. for(i = 0; i < len; i++)
  13284. dst[i] = src1[i];
  13285. }
  13286. }
  13287. static JSValue JS_ConcatString1(JSContext *ctx, JSString *p1, JSString *p2)
  13288. {
  13289. JSString *p;
  13290. uint32_t len;
  13291. int is_wide_char;
  13292. len = p1->len + p2->len;
  13293. if (len > JS_STRING_LEN_MAX)
  13294. return JS_ThrowRangeError(ctx, "invalid string length");
  13295. is_wide_char = p1->is_wide_char | p2->is_wide_char;
  13296. p = js_alloc_string(ctx, len, is_wide_char);
  13297. if (!p)
  13298. return JS_EXCEPTION;
  13299. if (!is_wide_char) {
  13300. memcpy(str8(p), str8(p1), p1->len);
  13301. memcpy(str8(p) + p1->len, str8(p2), p2->len);
  13302. str8(p)[len] = '\0';
  13303. } else {
  13304. copy_str16(str16(p), p1, 0, p1->len);
  13305. copy_str16(str16(p) + p1->len, p2, 0, p2->len);
  13306. }
  13307. return JS_MKPTR(JS_TAG_STRING, p);
  13308. }
  13309. /* op1 and op2 are converted to strings. For convience, op1 or op2 =
  13310. JS_EXCEPTION are accepted and return JS_EXCEPTION. */
  13311. static JSValue JS_ConcatString(JSContext *ctx, JSValue op1, JSValue op2)
  13312. {
  13313. JSValue ret;
  13314. JSString *p1, *p2;
  13315. if (unlikely(JS_VALUE_GET_TAG(op1) != JS_TAG_STRING)) {
  13316. op1 = JS_ToStringFree(ctx, op1);
  13317. if (JS_IsException(op1)) {
  13318. JS_FreeValue(ctx, op2);
  13319. return JS_EXCEPTION;
  13320. }
  13321. }
  13322. if (unlikely(JS_VALUE_GET_TAG(op2) != JS_TAG_STRING)) {
  13323. op2 = JS_ToStringFree(ctx, op2);
  13324. if (JS_IsException(op2)) {
  13325. JS_FreeValue(ctx, op1);
  13326. return JS_EXCEPTION;
  13327. }
  13328. }
  13329. p1 = JS_VALUE_GET_STRING(op1);
  13330. p2 = JS_VALUE_GET_STRING(op2);
  13331. /* XXX: could also check if p1 is empty */
  13332. if (p2->len == 0) {
  13333. goto ret_op1;
  13334. }
  13335. if (p1->header.ref_count == 1 && p1->is_wide_char == p2->is_wide_char
  13336. && js_malloc_usable_size(ctx, p1) >= sizeof(*p1) + ((p1->len + p2->len) << p2->is_wide_char) + 1 - p1->is_wide_char) {
  13337. /* Concatenate in place in available space at the end of p1 */
  13338. if (p1->is_wide_char) {
  13339. memcpy(str16(p1) + p1->len, str16(p2), p2->len << 1);
  13340. p1->len += p2->len;
  13341. } else {
  13342. memcpy(str8(p1) + p1->len, str8(p2), p2->len);
  13343. p1->len += p2->len;
  13344. str8(p1)[p1->len] = '\0';
  13345. }
  13346. ret_op1:
  13347. JS_FreeValue(ctx, op2);
  13348. return op1;
  13349. }
  13350. ret = JS_ConcatString1(ctx, p1, p2);
  13351. JS_FreeValue(ctx, op1);
  13352. JS_FreeValue(ctx, op2);
  13353. return ret;
  13354. }
  13355. /* Shape support */
  13356. static inline size_t get_shape_size(size_t hash_size, size_t prop_size)
  13357. {
  13358. return hash_size * sizeof(uint32_t) + sizeof(JSShape) +
  13359. prop_size * sizeof(JSShapeProperty);
  13360. }
  13361. static inline JSShape *get_shape_from_alloc(void *sh_alloc, size_t hash_size)
  13362. {
  13363. return (JSShape *)(void *)((uint32_t *)sh_alloc + hash_size);
  13364. }
  13365. static inline uint32_t *prop_hash_end(JSShape *sh)
  13366. {
  13367. return (uint32_t *)sh;
  13368. }
  13369. static inline void *get_alloc_from_shape(JSShape *sh)
  13370. {
  13371. return prop_hash_end(sh) - ((intptr_t)sh->prop_hash_mask + 1);
  13372. }
  13373. static inline JSShapeProperty *get_shape_prop(JSShape *sh)
  13374. {
  13375. return sh->prop;
  13376. }
  13377. static int init_shape_hash(JSRuntime *rt)
  13378. {
  13379. rt->shape_hash_bits = 4; /* 16 shapes */
  13380. rt->shape_hash_size = 1 << rt->shape_hash_bits;
  13381. rt->shape_hash_count = 0;
  13382. rt->shape_hash = js_mallocz_rt(rt, sizeof(rt->shape_hash[0]) *
  13383. rt->shape_hash_size);
  13384. if (!rt->shape_hash)
  13385. return -1;
  13386. return 0;
  13387. }
  13388. /* same magic hash multiplier as the Linux kernel */
  13389. static uint32_t shape_hash(uint32_t h, uint32_t val)
  13390. {
  13391. return (h + val) * 0x9e370001;
  13392. }
  13393. /* truncate the shape hash to 'hash_bits' bits */
  13394. static uint32_t get_shape_hash(uint32_t h, int hash_bits)
  13395. {
  13396. return h >> (32 - hash_bits);
  13397. }
  13398. static uint32_t shape_initial_hash(JSObject *proto)
  13399. {
  13400. uint32_t h;
  13401. h = shape_hash(1, (uintptr_t)proto);
  13402. if (sizeof(proto) > 4)
  13403. h = shape_hash(h, (uint64_t)(uintptr_t)proto >> 32);
  13404. return h;
  13405. }
  13406. static int resize_shape_hash(JSRuntime *rt, int new_shape_hash_bits)
  13407. {
  13408. int new_shape_hash_size, i;
  13409. uint32_t h;
  13410. JSShape **new_shape_hash, *sh, *sh_next;
  13411. new_shape_hash_size = 1 << new_shape_hash_bits;
  13412. new_shape_hash = js_mallocz_rt(rt, sizeof(rt->shape_hash[0]) *
  13413. new_shape_hash_size);
  13414. if (!new_shape_hash)
  13415. return -1;
  13416. for(i = 0; i < rt->shape_hash_size; i++) {
  13417. for(sh = rt->shape_hash[i]; sh != NULL; sh = sh_next) {
  13418. sh_next = sh->shape_hash_next;
  13419. h = get_shape_hash(sh->hash, new_shape_hash_bits);
  13420. sh->shape_hash_next = new_shape_hash[h];
  13421. new_shape_hash[h] = sh;
  13422. }
  13423. }
  13424. js_free_rt(rt, rt->shape_hash);
  13425. rt->shape_hash_bits = new_shape_hash_bits;
  13426. rt->shape_hash_size = new_shape_hash_size;
  13427. rt->shape_hash = new_shape_hash;
  13428. return 0;
  13429. }
  13430. static void js_shape_hash_link(JSRuntime *rt, JSShape *sh)
  13431. {
  13432. uint32_t h;
  13433. h = get_shape_hash(sh->hash, rt->shape_hash_bits);
  13434. sh->shape_hash_next = rt->shape_hash[h];
  13435. rt->shape_hash[h] = sh;
  13436. rt->shape_hash_count++;
  13437. }
  13438. static void js_shape_hash_unlink(JSRuntime *rt, JSShape *sh)
  13439. {
  13440. uint32_t h;
  13441. JSShape **psh;
  13442. h = get_shape_hash(sh->hash, rt->shape_hash_bits);
  13443. psh = &rt->shape_hash[h];
  13444. while (*psh != sh)
  13445. psh = &(*psh)->shape_hash_next;
  13446. *psh = sh->shape_hash_next;
  13447. rt->shape_hash_count--;
  13448. }
  13449. /* create a new empty shape with prototype 'proto' */
  13450. static no_inline JSShape *js_new_shape2(JSContext *ctx, JSObject *proto,
  13451. int hash_size, int prop_size)
  13452. {
  13453. JSRuntime *rt = ctx->rt;
  13454. void *sh_alloc;
  13455. JSShape *sh;
  13456. /* resize the shape hash table if necessary */
  13457. if (2 * (rt->shape_hash_count + 1) > rt->shape_hash_size) {
  13458. resize_shape_hash(rt, rt->shape_hash_bits + 1);
  13459. }
  13460. sh_alloc = js_malloc(ctx, get_shape_size(hash_size, prop_size));
  13461. if (!sh_alloc)
  13462. return NULL;
  13463. sh = get_shape_from_alloc(sh_alloc, hash_size);
  13464. sh->header.ref_count = 1;
  13465. add_gc_object(rt, &sh->header, JS_GC_OBJ_TYPE_SHAPE);
  13466. if (proto)
  13467. js_dup(JS_MKPTR(JS_TAG_OBJECT, proto));
  13468. sh->proto = proto;
  13469. memset(prop_hash_end(sh) - hash_size, 0, sizeof(prop_hash_end(sh)[0]) *
  13470. hash_size);
  13471. sh->prop_hash_mask = hash_size - 1;
  13472. sh->prop_size = prop_size;
  13473. sh->prop_count = 0;
  13474. sh->deleted_prop_count = 0;
  13475. /* insert in the hash table */
  13476. sh->hash = shape_initial_hash(proto);
  13477. sh->is_hashed = true;
  13478. sh->has_small_array_index = false;
  13479. js_shape_hash_link(ctx->rt, sh);
  13480. return sh;
  13481. }
  13482. static JSShape *js_new_shape(JSContext *ctx, JSObject *proto)
  13483. {
  13484. return js_new_shape2(ctx, proto, JS_PROP_INITIAL_HASH_SIZE,
  13485. JS_PROP_INITIAL_SIZE);
  13486. }
  13487. /* The shape is cloned. The new shape is not inserted in the shape
  13488. hash table */
  13489. static JSShape *js_clone_shape(JSContext *ctx, JSShape *sh1)
  13490. {
  13491. JSShape *sh;
  13492. void *sh_alloc, *sh_alloc1;
  13493. size_t size;
  13494. JSShapeProperty *pr;
  13495. uint32_t i, hash_size;
  13496. hash_size = sh1->prop_hash_mask + 1;
  13497. size = get_shape_size(hash_size, sh1->prop_size);
  13498. sh_alloc = js_malloc(ctx, size);
  13499. if (!sh_alloc)
  13500. return NULL;
  13501. sh_alloc1 = get_alloc_from_shape(sh1);
  13502. memcpy(sh_alloc, sh_alloc1, size);
  13503. sh = get_shape_from_alloc(sh_alloc, hash_size);
  13504. sh->header.ref_count = 1;
  13505. add_gc_object(ctx->rt, &sh->header, JS_GC_OBJ_TYPE_SHAPE);
  13506. sh->is_hashed = false;
  13507. if (sh->proto) {
  13508. js_dup(JS_MKPTR(JS_TAG_OBJECT, sh->proto));
  13509. }
  13510. for(i = 0, pr = get_shape_prop(sh); i < sh->prop_count; i++, pr++) {
  13511. JS_DupAtom(ctx, pr->atom);
  13512. }
  13513. return sh;
  13514. }
  13515. static JSShape *js_dup_shape(JSShape *sh)
  13516. {
  13517. sh->header.ref_count++;
  13518. return sh;
  13519. }
  13520. static void js_free_shape0(JSRuntime *rt, JSShape *sh)
  13521. {
  13522. uint32_t i;
  13523. JSShapeProperty *pr;
  13524. assert(sh->header.ref_count == 0);
  13525. if (sh->is_hashed)
  13526. js_shape_hash_unlink(rt, sh);
  13527. if (sh->proto != NULL) {
  13528. JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_OBJECT, sh->proto));
  13529. }
  13530. pr = get_shape_prop(sh);
  13531. for(i = 0; i < sh->prop_count; i++) {
  13532. JS_FreeAtomRT(rt, pr->atom);
  13533. pr++;
  13534. }
  13535. remove_gc_object(&sh->header);
  13536. js_free_rt(rt, get_alloc_from_shape(sh));
  13537. }
  13538. static void js_free_shape(JSRuntime *rt, JSShape *sh)
  13539. {
  13540. if (unlikely(--sh->header.ref_count <= 0)) {
  13541. js_free_shape0(rt, sh);
  13542. }
  13543. }
  13544. static void js_free_shape_null(JSRuntime *rt, JSShape *sh)
  13545. {
  13546. if (sh)
  13547. js_free_shape(rt, sh);
  13548. }
  13549. /* make space to hold at least 'count' properties */
  13550. static no_inline int resize_properties(JSContext *ctx, JSShape **psh,
  13551. JSObject *p, uint32_t count)
  13552. {
  13553. JSShape *sh;
  13554. uint32_t new_size, new_hash_size, new_hash_mask, i;
  13555. JSShapeProperty *pr;
  13556. void *sh_alloc;
  13557. intptr_t h;
  13558. sh = *psh;
  13559. new_size = max_int(count, sh->prop_size * 3 / 2);
  13560. /* Reallocate prop array first to avoid crash or size inconsistency
  13561. in case of memory allocation failure */
  13562. if (p) {
  13563. JSProperty *new_prop;
  13564. new_prop = js_realloc(ctx, p->prop, sizeof(new_prop[0]) * new_size);
  13565. if (unlikely(!new_prop))
  13566. return -1;
  13567. p->prop = new_prop;
  13568. }
  13569. new_hash_size = sh->prop_hash_mask + 1;
  13570. while (new_hash_size < new_size)
  13571. new_hash_size = 2 * new_hash_size;
  13572. if (new_hash_size != (sh->prop_hash_mask + 1)) {
  13573. JSShape *old_sh;
  13574. /* resize the hash table and the properties */
  13575. old_sh = sh;
  13576. sh_alloc = js_malloc(ctx, get_shape_size(new_hash_size, new_size));
  13577. if (!sh_alloc)
  13578. return -1;
  13579. sh = get_shape_from_alloc(sh_alloc, new_hash_size);
  13580. list_del(&old_sh->header.link);
  13581. /* copy all the fields and the properties */
  13582. memcpy(sh, old_sh,
  13583. sizeof(JSShape) + sizeof(sh->prop[0]) * old_sh->prop_count);
  13584. list_add_tail(&sh->header.link, &ctx->rt->gc_obj_list);
  13585. new_hash_mask = new_hash_size - 1;
  13586. sh->prop_hash_mask = new_hash_mask;
  13587. memset(prop_hash_end(sh) - new_hash_size, 0,
  13588. sizeof(prop_hash_end(sh)[0]) * new_hash_size);
  13589. for(i = 0, pr = sh->prop; i < sh->prop_count; i++, pr++) {
  13590. if (pr->atom != JS_ATOM_NULL) {
  13591. h = ((uintptr_t)pr->atom & new_hash_mask);
  13592. pr->hash_next = prop_hash_end(sh)[-h - 1];
  13593. prop_hash_end(sh)[-h - 1] = i + 1;
  13594. }
  13595. }
  13596. js_free(ctx, get_alloc_from_shape(old_sh));
  13597. } else {
  13598. /* only resize the properties */
  13599. list_del(&sh->header.link);
  13600. sh_alloc = js_realloc(ctx, get_alloc_from_shape(sh),
  13601. get_shape_size(new_hash_size, new_size));
  13602. if (unlikely(!sh_alloc)) {
  13603. /* insert again in the GC list */
  13604. list_add_tail(&sh->header.link, &ctx->rt->gc_obj_list);
  13605. return -1;
  13606. }
  13607. sh = get_shape_from_alloc(sh_alloc, new_hash_size);
  13608. list_add_tail(&sh->header.link, &ctx->rt->gc_obj_list);
  13609. }
  13610. *psh = sh;
  13611. sh->prop_size = new_size;
  13612. return 0;
  13613. }
  13614. /* remove the deleted properties. */
  13615. static int compact_properties(JSContext *ctx, JSObject *p)
  13616. {
  13617. JSShape *sh, *old_sh;
  13618. void *sh_alloc;
  13619. intptr_t h;
  13620. uint32_t new_hash_size, i, j, new_hash_mask, new_size;
  13621. JSShapeProperty *old_pr, *pr;
  13622. JSProperty *prop, *new_prop;
  13623. sh = p->shape;
  13624. assert(!sh->is_hashed);
  13625. new_size = max_int(JS_PROP_INITIAL_SIZE,
  13626. sh->prop_count - sh->deleted_prop_count);
  13627. assert(new_size <= sh->prop_size);
  13628. new_hash_size = sh->prop_hash_mask + 1;
  13629. while ((new_hash_size / 2) >= new_size)
  13630. new_hash_size = new_hash_size / 2;
  13631. new_hash_mask = new_hash_size - 1;
  13632. /* resize the hash table and the properties */
  13633. old_sh = sh;
  13634. sh_alloc = js_malloc(ctx, get_shape_size(new_hash_size, new_size));
  13635. if (!sh_alloc)
  13636. return -1;
  13637. sh = get_shape_from_alloc(sh_alloc, new_hash_size);
  13638. list_del(&old_sh->header.link);
  13639. memcpy(sh, old_sh, sizeof(JSShape));
  13640. list_add_tail(&sh->header.link, &ctx->rt->gc_obj_list);
  13641. memset(prop_hash_end(sh) - new_hash_size, 0,
  13642. sizeof(prop_hash_end(sh)[0]) * new_hash_size);
  13643. j = 0;
  13644. old_pr = old_sh->prop;
  13645. pr = sh->prop;
  13646. prop = p->prop;
  13647. for(i = 0; i < sh->prop_count; i++) {
  13648. if (old_pr->atom != JS_ATOM_NULL) {
  13649. pr->atom = old_pr->atom;
  13650. pr->flags = old_pr->flags;
  13651. h = ((uintptr_t)old_pr->atom & new_hash_mask);
  13652. pr->hash_next = prop_hash_end(sh)[-h - 1];
  13653. prop_hash_end(sh)[-h - 1] = j + 1;
  13654. prop[j] = prop[i];
  13655. j++;
  13656. pr++;
  13657. }
  13658. old_pr++;
  13659. }
  13660. assert(j == (sh->prop_count - sh->deleted_prop_count));
  13661. sh->prop_hash_mask = new_hash_mask;
  13662. sh->prop_size = new_size;
  13663. sh->deleted_prop_count = 0;
  13664. sh->prop_count = j;
  13665. p->shape = sh;
  13666. js_free(ctx, get_alloc_from_shape(old_sh));
  13667. /* reduce the size of the object properties */
  13668. new_prop = js_realloc(ctx, p->prop, sizeof(new_prop[0]) * new_size);
  13669. if (new_prop)
  13670. p->prop = new_prop;
  13671. return 0;
  13672. }
  13673. static int add_shape_property(JSContext *ctx, JSShape **psh,
  13674. JSObject *p, JSAtom atom, int prop_flags)
  13675. {
  13676. JSRuntime *rt = ctx->rt;
  13677. JSShape *sh = *psh;
  13678. JSShapeProperty *pr, *prop;
  13679. uint32_t hash_mask, new_shape_hash = 0;
  13680. intptr_t h;
  13681. /* update the shape hash */
  13682. if (sh->is_hashed) {
  13683. js_shape_hash_unlink(rt, sh);
  13684. new_shape_hash = shape_hash(shape_hash(sh->hash, atom), prop_flags);
  13685. }
  13686. if (unlikely(sh->prop_count >= sh->prop_size)) {
  13687. if (resize_properties(ctx, psh, p, sh->prop_count + 1)) {
  13688. /* in case of error, reinsert in the hash table.
  13689. sh is still valid if resize_properties() failed */
  13690. if (sh->is_hashed)
  13691. js_shape_hash_link(rt, sh);
  13692. return -1;
  13693. }
  13694. sh = *psh;
  13695. }
  13696. if (sh->is_hashed) {
  13697. sh->hash = new_shape_hash;
  13698. js_shape_hash_link(rt, sh);
  13699. }
  13700. /* Initialize the new shape property.
  13701. The object property at p->prop[sh->prop_count] is uninitialized */
  13702. prop = get_shape_prop(sh);
  13703. pr = &prop[sh->prop_count++];
  13704. pr->atom = JS_DupAtom(ctx, atom);
  13705. pr->flags = prop_flags;
  13706. sh->has_small_array_index |= __JS_AtomIsTaggedInt(atom);
  13707. /* add in hash table */
  13708. hash_mask = sh->prop_hash_mask;
  13709. h = atom & hash_mask;
  13710. pr->hash_next = prop_hash_end(sh)[-h - 1];
  13711. prop_hash_end(sh)[-h - 1] = sh->prop_count;
  13712. return 0;
  13713. }
  13714. /* find a hashed empty shape matching the prototype. Return NULL if
  13715. not found */
  13716. static JSShape *find_hashed_shape_proto(JSRuntime *rt, JSObject *proto)
  13717. {
  13718. JSShape *sh1;
  13719. uint32_t h, h1;
  13720. h = shape_initial_hash(proto);
  13721. h1 = get_shape_hash(h, rt->shape_hash_bits);
  13722. for(sh1 = rt->shape_hash[h1]; sh1 != NULL; sh1 = sh1->shape_hash_next) {
  13723. if (sh1->hash == h &&
  13724. sh1->proto == proto &&
  13725. sh1->prop_count == 0) {
  13726. return sh1;
  13727. }
  13728. }
  13729. return NULL;
  13730. }
  13731. /* find a hashed shape matching sh + (prop, prop_flags). Return NULL if
  13732. not found */
  13733. static JSShape *find_hashed_shape_prop(JSRuntime *rt, JSShape *sh,
  13734. JSAtom atom, int prop_flags)
  13735. {
  13736. JSShape *sh1;
  13737. uint32_t h, h1, i, n;
  13738. h = sh->hash;
  13739. h = shape_hash(h, atom);
  13740. h = shape_hash(h, prop_flags);
  13741. h1 = get_shape_hash(h, rt->shape_hash_bits);
  13742. for(sh1 = rt->shape_hash[h1]; sh1 != NULL; sh1 = sh1->shape_hash_next) {
  13743. /* we test the hash first so that the rest is done only if the
  13744. shapes really match */
  13745. if (sh1->hash == h &&
  13746. sh1->proto == sh->proto &&
  13747. sh1->prop_count == ((n = sh->prop_count) + 1)) {
  13748. for(i = 0; i < n; i++) {
  13749. if (unlikely(sh1->prop[i].atom != sh->prop[i].atom) ||
  13750. unlikely(sh1->prop[i].flags != sh->prop[i].flags))
  13751. goto next;
  13752. }
  13753. if (unlikely(sh1->prop[n].atom != atom) ||
  13754. unlikely(sh1->prop[n].flags != prop_flags))
  13755. goto next;
  13756. return sh1;
  13757. }
  13758. next: ;
  13759. }
  13760. return NULL;
  13761. }
  13762. static __maybe_unused void JS_DumpShape(JSRuntime *rt, int i, JSShape *sh)
  13763. {
  13764. char atom_buf[ATOM_GET_STR_BUF_SIZE];
  13765. int j;
  13766. /* XXX: should output readable class prototype */
  13767. printf("%5d %3d%c %14p %5d %5d", i,
  13768. sh->header.ref_count, " *"[sh->is_hashed],
  13769. (void *)sh->proto, sh->prop_size, sh->prop_count);
  13770. for(j = 0; j < sh->prop_count; j++) {
  13771. printf(" %s", JS_AtomGetStrRT(rt, atom_buf, sizeof(atom_buf),
  13772. sh->prop[j].atom));
  13773. }
  13774. printf("\n");
  13775. }
  13776. static __maybe_unused void JS_DumpShapes(JSRuntime *rt)
  13777. {
  13778. int i;
  13779. JSShape *sh;
  13780. struct list_head *el;
  13781. JSObject *p;
  13782. JSGCObjectHeader *gp;
  13783. printf("JSShapes: {\n");
  13784. printf("%5s %4s %14s %5s %5s %s\n", "SLOT", "REFS", "PROTO", "SIZE", "COUNT", "PROPS");
  13785. for(i = 0; i < rt->shape_hash_size; i++) {
  13786. for(sh = rt->shape_hash[i]; sh != NULL; sh = sh->shape_hash_next) {
  13787. JS_DumpShape(rt, i, sh);
  13788. assert(sh->is_hashed);
  13789. }
  13790. }
  13791. /* dump non-hashed shapes */
  13792. list_for_each(el, &rt->gc_obj_list) {
  13793. gp = list_entry(el, JSGCObjectHeader, link);
  13794. if (gp->gc_obj_type == JS_GC_OBJ_TYPE_JS_OBJECT) {
  13795. p = (JSObject *)gp;
  13796. if (!p->shape->is_hashed) {
  13797. JS_DumpShape(rt, -1, p->shape);
  13798. }
  13799. }
  13800. }
  13801. printf("}\n");
  13802. }
  13803. static JSValue JS_NewObjectFromShape(JSContext *ctx, JSShape *sh, JSClassID class_id)
  13804. {
  13805. JSObject *p;
  13806. js_trigger_gc(ctx->rt, sizeof(JSObject));
  13807. p = js_malloc(ctx, sizeof(JSObject));
  13808. if (unlikely(!p))
  13809. goto fail;
  13810. p->class_id = class_id;
  13811. p->extensible = true;
  13812. p->free_mark = 0;
  13813. p->is_exotic = 0;
  13814. p->fast_array = 0;
  13815. p->is_constructor = 0;
  13816. p->is_uncatchable_error = 0;
  13817. p->tmp_mark = 0;
  13818. p->is_HTMLDDA = 0;
  13819. p->first_weak_ref = NULL;
  13820. p->u.opaque = NULL;
  13821. p->shape = sh;
  13822. p->prop = js_malloc(ctx, sizeof(JSProperty) * sh->prop_size);
  13823. if (unlikely(!p->prop)) {
  13824. js_free(ctx, p);
  13825. fail:
  13826. js_free_shape(ctx->rt, sh);
  13827. return JS_EXCEPTION;
  13828. }
  13829. switch(class_id) {
  13830. case JS_CLASS_OBJECT:
  13831. break;
  13832. case JS_CLASS_ARRAY:
  13833. {
  13834. JSProperty *pr;
  13835. p->is_exotic = 1;
  13836. p->fast_array = 1;
  13837. p->u.array.u.values = NULL;
  13838. p->u.array.count = 0;
  13839. p->u.array.u1.size = 0;
  13840. /* the length property is always the first one */
  13841. if (likely(sh == ctx->array_shape)) {
  13842. pr = &p->prop[0];
  13843. } else {
  13844. /* only used for the first array */
  13845. /* cannot fail */
  13846. pr = add_property(ctx, p, JS_ATOM_length,
  13847. JS_PROP_WRITABLE | JS_PROP_LENGTH);
  13848. }
  13849. pr->u.value = js_int32(0);
  13850. }
  13851. break;
  13852. case JS_CLASS_C_FUNCTION:
  13853. p->prop[0].u.value = JS_UNDEFINED;
  13854. break;
  13855. case JS_CLASS_ARGUMENTS:
  13856. case JS_CLASS_UINT8C_ARRAY:
  13857. case JS_CLASS_INT8_ARRAY:
  13858. case JS_CLASS_UINT8_ARRAY:
  13859. case JS_CLASS_INT16_ARRAY:
  13860. case JS_CLASS_UINT16_ARRAY:
  13861. case JS_CLASS_INT32_ARRAY:
  13862. case JS_CLASS_UINT32_ARRAY:
  13863. case JS_CLASS_BIG_INT64_ARRAY:
  13864. case JS_CLASS_BIG_UINT64_ARRAY:
  13865. case JS_CLASS_FLOAT16_ARRAY:
  13866. case JS_CLASS_FLOAT32_ARRAY:
  13867. case JS_CLASS_FLOAT64_ARRAY:
  13868. p->is_exotic = 1;
  13869. p->fast_array = 1;
  13870. p->u.array.u.ptr = NULL;
  13871. p->u.array.count = 0;
  13872. break;
  13873. case JS_CLASS_DATAVIEW:
  13874. p->u.array.u.ptr = NULL;
  13875. p->u.array.count = 0;
  13876. break;
  13877. case JS_CLASS_NUMBER:
  13878. case JS_CLASS_STRING:
  13879. case JS_CLASS_BOOLEAN:
  13880. case JS_CLASS_SYMBOL:
  13881. case JS_CLASS_DATE:
  13882. case JS_CLASS_BIG_INT:
  13883. p->u.object_data = JS_UNDEFINED;
  13884. goto set_exotic;
  13885. case JS_CLASS_REGEXP:
  13886. p->u.regexp.pattern = NULL;
  13887. p->u.regexp.bytecode = NULL;
  13888. goto set_exotic;
  13889. default:
  13890. set_exotic:
  13891. if (ctx->rt->class_array[class_id].exotic) {
  13892. p->is_exotic = 1;
  13893. }
  13894. break;
  13895. }
  13896. p->header.ref_count = 1;
  13897. add_gc_object(ctx->rt, &p->header, JS_GC_OBJ_TYPE_JS_OBJECT);
  13898. return JS_MKPTR(JS_TAG_OBJECT, p);
  13899. }
  13900. static JSObject *get_proto_obj(JSValueConst proto_val)
  13901. {
  13902. if (JS_VALUE_GET_TAG(proto_val) != JS_TAG_OBJECT)
  13903. return NULL;
  13904. else
  13905. return JS_VALUE_GET_OBJ(proto_val);
  13906. }
  13907. /* WARNING: proto must be an object or JS_NULL */
  13908. JSValue JS_NewObjectProtoClass(JSContext *ctx, JSValueConst proto_val,
  13909. JSClassID class_id)
  13910. {
  13911. JSShape *sh;
  13912. JSObject *proto;
  13913. proto = get_proto_obj(proto_val);
  13914. sh = find_hashed_shape_proto(ctx->rt, proto);
  13915. if (likely(sh)) {
  13916. sh = js_dup_shape(sh);
  13917. } else {
  13918. sh = js_new_shape(ctx, proto);
  13919. if (!sh)
  13920. return JS_EXCEPTION;
  13921. }
  13922. return JS_NewObjectFromShape(ctx, sh, class_id);
  13923. }
  13924. static int JS_SetObjectData(JSContext *ctx, JSValueConst obj, JSValue val)
  13925. {
  13926. JSObject *p;
  13927. if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) {
  13928. p = JS_VALUE_GET_OBJ(obj);
  13929. switch(p->class_id) {
  13930. case JS_CLASS_NUMBER:
  13931. case JS_CLASS_STRING:
  13932. case JS_CLASS_BOOLEAN:
  13933. case JS_CLASS_SYMBOL:
  13934. case JS_CLASS_DATE:
  13935. case JS_CLASS_BIG_INT:
  13936. JS_FreeValue(ctx, p->u.object_data);
  13937. p->u.object_data = val;
  13938. return 0;
  13939. }
  13940. }
  13941. JS_FreeValue(ctx, val);
  13942. if (!JS_IsException(obj))
  13943. JS_ThrowTypeError(ctx, "invalid object type");
  13944. return -1;
  13945. }
  13946. JSValue JS_NewObjectClass(JSContext *ctx, int class_id)
  13947. {
  13948. return JS_NewObjectProtoClass(ctx, ctx->class_proto[class_id], class_id);
  13949. }
  13950. JSValue JS_NewObjectProto(JSContext *ctx, JSValueConst proto)
  13951. {
  13952. return JS_NewObjectProtoClass(ctx, proto, JS_CLASS_OBJECT);
  13953. }
  13954. JSValue JS_NewObjectFrom(JSContext *ctx, int count, const JSAtom *props,
  13955. const JSValue *values)
  13956. {
  13957. JSShapeProperty *pr;
  13958. uint32_t *hash;
  13959. JSRuntime *rt;
  13960. JSObject *p;
  13961. JSShape *sh;
  13962. JSValue obj;
  13963. JSAtom atom;
  13964. intptr_t h;
  13965. int i;
  13966. rt = ctx->rt;
  13967. obj = JS_NewObject(ctx);
  13968. if (JS_IsException(obj))
  13969. return JS_EXCEPTION;
  13970. if (count > 0) {
  13971. p = JS_VALUE_GET_OBJ(obj);
  13972. sh = p->shape;
  13973. assert(sh->is_hashed);
  13974. assert(sh->header.ref_count == 1);
  13975. js_shape_hash_unlink(rt, sh);
  13976. if (resize_properties(ctx, &sh, p, count)) {
  13977. js_shape_hash_link(rt, sh);
  13978. JS_FreeValue(ctx, obj);
  13979. return JS_EXCEPTION;
  13980. }
  13981. p->shape = sh;
  13982. for (i = 0; i < count; i++) {
  13983. atom = props[i];
  13984. pr = &sh->prop[i];
  13985. sh->hash = shape_hash(shape_hash(sh->hash, atom), JS_PROP_C_W_E);
  13986. sh->has_small_array_index |= __JS_AtomIsTaggedInt(atom);
  13987. h = atom & sh->prop_hash_mask;
  13988. hash = &prop_hash_end(sh)[-h - 1];
  13989. pr->hash_next = *hash;
  13990. *hash = i + 1;
  13991. pr->atom = JS_DupAtom(ctx, atom);
  13992. pr->flags = JS_PROP_C_W_E;
  13993. p->prop[i].u.value = values[i];
  13994. }
  13995. js_shape_hash_link(rt, sh);
  13996. sh->prop_count = count;
  13997. }
  13998. return obj;
  13999. }
  14000. JSValue JS_NewObjectFromStr(JSContext *ctx, int count, const char **props,
  14001. const JSValue *values)
  14002. {
  14003. JSAtom atoms_s[16], *atoms = atoms_s;
  14004. JSValue ret;
  14005. int i;
  14006. i = 0;
  14007. ret = JS_EXCEPTION;
  14008. if (count < 1)
  14009. goto out;
  14010. if (count > (int)countof(atoms_s)) {
  14011. atoms = js_malloc(ctx, count * sizeof(*atoms));
  14012. if (!atoms)
  14013. return JS_EXCEPTION;
  14014. }
  14015. for (i = 0; i < count; i++) {
  14016. atoms[i] = JS_NewAtom(ctx, props[i]);
  14017. if (atoms[i] == JS_ATOM_NULL)
  14018. goto out;
  14019. }
  14020. ret = JS_NewObjectFrom(ctx, count, atoms, values);
  14021. out:
  14022. while (i-- > 0)
  14023. JS_FreeAtom(ctx, atoms[i]);
  14024. if (atoms != atoms_s)
  14025. js_free(ctx, atoms);
  14026. return ret;
  14027. }
  14028. JSValue JS_NewArray(JSContext *ctx)
  14029. {
  14030. return JS_NewObjectFromShape(ctx, js_dup_shape(ctx->array_shape),
  14031. JS_CLASS_ARRAY);
  14032. }
  14033. // note: takes ownership of |values|, unlike js_create_array
  14034. JSValue JS_NewArrayFrom(JSContext *ctx, int count, const JSValue *values)
  14035. {
  14036. JSObject *p;
  14037. JSValue obj;
  14038. obj = JS_NewArray(ctx);
  14039. if (JS_IsException(obj))
  14040. return JS_EXCEPTION;
  14041. if (count > 0) {
  14042. p = JS_VALUE_GET_OBJ(obj);
  14043. if (expand_fast_array(ctx, p, count)) {
  14044. JS_FreeValue(ctx, obj);
  14045. return JS_EXCEPTION;
  14046. }
  14047. p->u.array.count = count;
  14048. p->prop[0].u.value = js_int32(count);
  14049. memcpy(p->u.array.u.values, values, count * sizeof(*values));
  14050. }
  14051. return obj;
  14052. }
  14053. JSValue JS_NewObject(JSContext *ctx)
  14054. {
  14055. /* inline JS_NewObjectClass(ctx, JS_CLASS_OBJECT); */
  14056. return JS_NewObjectProtoClass(ctx, ctx->class_proto[JS_CLASS_OBJECT], JS_CLASS_OBJECT);
  14057. }
  14058. static void js_function_set_properties(JSContext *ctx, JSValue func_obj,
  14059. JSAtom name, int len)
  14060. {
  14061. /* ES6 feature non compatible with ES5.1: length is configurable */
  14062. JS_DefinePropertyValue(ctx, func_obj, JS_ATOM_length, js_int32(len),
  14063. JS_PROP_CONFIGURABLE);
  14064. JS_DefinePropertyValue(ctx, func_obj, JS_ATOM_name,
  14065. JS_AtomToString(ctx, name), JS_PROP_CONFIGURABLE);
  14066. }
  14067. static bool js_class_has_bytecode(JSClassID class_id)
  14068. {
  14069. return (class_id == JS_CLASS_BYTECODE_FUNCTION ||
  14070. class_id == JS_CLASS_GENERATOR_FUNCTION ||
  14071. class_id == JS_CLASS_ASYNC_FUNCTION ||
  14072. class_id == JS_CLASS_ASYNC_GENERATOR_FUNCTION);
  14073. }
  14074. /* return NULL without exception if not a function or no bytecode */
  14075. static JSFunctionBytecode *JS_GetFunctionBytecode(JSValueConst val)
  14076. {
  14077. JSObject *p;
  14078. if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT)
  14079. return NULL;
  14080. p = JS_VALUE_GET_OBJ(val);
  14081. if (!js_class_has_bytecode(p->class_id))
  14082. return NULL;
  14083. return p->u.func.function_bytecode;
  14084. }
  14085. static void js_method_set_home_object(JSContext *ctx, JSValue func_obj,
  14086. JSValue home_obj)
  14087. {
  14088. JSObject *p, *p1;
  14089. JSFunctionBytecode *b;
  14090. if (JS_VALUE_GET_TAG(func_obj) != JS_TAG_OBJECT)
  14091. return;
  14092. p = JS_VALUE_GET_OBJ(func_obj);
  14093. if (!js_class_has_bytecode(p->class_id))
  14094. return;
  14095. b = p->u.func.function_bytecode;
  14096. if (b->need_home_object) {
  14097. p1 = p->u.func.home_object;
  14098. if (p1) {
  14099. JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p1));
  14100. }
  14101. if (JS_VALUE_GET_TAG(home_obj) == JS_TAG_OBJECT)
  14102. p1 = JS_VALUE_GET_OBJ(js_dup(home_obj));
  14103. else
  14104. p1 = NULL;
  14105. p->u.func.home_object = p1;
  14106. }
  14107. }
  14108. static JSValue js_get_function_name(JSContext *ctx, JSAtom name)
  14109. {
  14110. JSValue name_str;
  14111. name_str = JS_AtomToString(ctx, name);
  14112. if (JS_AtomSymbolHasDescription(ctx, name)) {
  14113. name_str = JS_ConcatString3(ctx, "[", name_str, "]");
  14114. }
  14115. return name_str;
  14116. }
  14117. /* Modify the name of a method according to the atom and
  14118. 'flags'. 'flags' is a bitmask of JS_PROP_HAS_GET and
  14119. JS_PROP_HAS_SET. Also set the home object of the method.
  14120. Return < 0 if exception. */
  14121. static int js_method_set_properties(JSContext *ctx, JSValue func_obj,
  14122. JSAtom name, int flags, JSValue home_obj)
  14123. {
  14124. JSValue name_str;
  14125. name_str = js_get_function_name(ctx, name);
  14126. if (flags & JS_PROP_HAS_GET) {
  14127. name_str = JS_ConcatString3(ctx, "get ", name_str, "");
  14128. } else if (flags & JS_PROP_HAS_SET) {
  14129. name_str = JS_ConcatString3(ctx, "set ", name_str, "");
  14130. }
  14131. if (JS_IsException(name_str))
  14132. return -1;
  14133. if (JS_DefinePropertyValue(ctx, func_obj, JS_ATOM_name, name_str,
  14134. JS_PROP_CONFIGURABLE) < 0)
  14135. return -1;
  14136. js_method_set_home_object(ctx, func_obj, home_obj);
  14137. return 0;
  14138. }
  14139. /* Note: at least 'length' arguments will be readable in 'argv' */
  14140. /* `name` may be NULL, pure ASCII or UTF-8 encoded */
  14141. JSValue JS_NewCFunction3(JSContext *ctx, JSCFunction *func,
  14142. const char *name,
  14143. int length, JSCFunctionEnum cproto, int magic,
  14144. JSValue proto_val)
  14145. {
  14146. JSValue func_obj;
  14147. JSObject *p;
  14148. JSAtom name_atom;
  14149. func_obj = JS_NewObjectProtoClass(ctx, proto_val, JS_CLASS_C_FUNCTION);
  14150. if (JS_IsException(func_obj))
  14151. return func_obj;
  14152. p = JS_VALUE_GET_OBJ(func_obj);
  14153. p->u.cfunc.realm = JS_DupContext(ctx);
  14154. p->u.cfunc.c_function.generic = func;
  14155. p->u.cfunc.length = length;
  14156. p->u.cfunc.cproto = cproto;
  14157. p->u.cfunc.magic = magic;
  14158. p->is_constructor = (cproto == JS_CFUNC_constructor ||
  14159. cproto == JS_CFUNC_constructor_magic ||
  14160. cproto == JS_CFUNC_constructor_or_func ||
  14161. cproto == JS_CFUNC_constructor_or_func_magic);
  14162. if (!name)
  14163. name = "";
  14164. name_atom = JS_NewAtom(ctx, name);
  14165. js_function_set_properties(ctx, func_obj, name_atom, length);
  14166. JS_FreeAtom(ctx, name_atom);
  14167. return func_obj;
  14168. }
  14169. /* Note: at least 'length' arguments will be readable in 'argv' */
  14170. JSValue JS_NewCFunction2(JSContext *ctx, JSCFunction *func,
  14171. const char *name,
  14172. int length, JSCFunctionEnum cproto, int magic)
  14173. {
  14174. return JS_NewCFunction3(ctx, func, name, length, cproto, magic,
  14175. ctx->function_proto);
  14176. }
  14177. typedef struct JSCFunctionDataRecord {
  14178. JSCFunctionData *func;
  14179. uint8_t length;
  14180. uint8_t data_len;
  14181. uint16_t magic;
  14182. JSValue data[];
  14183. } JSCFunctionDataRecord;
  14184. static void js_c_function_data_finalizer(JSRuntime *rt, JSValueConst val)
  14185. {
  14186. JSCFunctionDataRecord *s = JS_GetOpaque(val, JS_CLASS_C_FUNCTION_DATA);
  14187. int i;
  14188. if (s) {
  14189. for(i = 0; i < s->data_len; i++) {
  14190. JS_FreeValueRT(rt, s->data[i]);
  14191. }
  14192. js_free_rt(rt, s);
  14193. }
  14194. }
  14195. static void js_c_function_data_mark(JSRuntime *rt, JSValueConst val,
  14196. JS_MarkFunc *mark_func)
  14197. {
  14198. JSCFunctionDataRecord *s = JS_GetOpaque(val, JS_CLASS_C_FUNCTION_DATA);
  14199. int i;
  14200. if (s) {
  14201. for(i = 0; i < s->data_len; i++) {
  14202. JS_MarkValue(rt, s->data[i], mark_func);
  14203. }
  14204. }
  14205. }
  14206. static JSValue js_c_function_data_call(JSContext *ctx, JSValueConst func_obj,
  14207. JSValueConst this_val,
  14208. int argc, JSValueConst *argv, int flags)
  14209. {
  14210. JSCFunctionDataRecord *s = JS_GetOpaque(func_obj, JS_CLASS_C_FUNCTION_DATA);
  14211. JSValueConst *arg_buf;
  14212. int i;
  14213. /* XXX: could add the function on the stack for debug */
  14214. if (unlikely(argc < s->length)) {
  14215. arg_buf = alloca(sizeof(arg_buf[0]) * s->length);
  14216. for(i = 0; i < argc; i++)
  14217. arg_buf[i] = argv[i];
  14218. for(i = argc; i < s->length; i++)
  14219. arg_buf[i] = JS_UNDEFINED;
  14220. } else {
  14221. arg_buf = argv;
  14222. }
  14223. return s->func(ctx, this_val, argc, arg_buf, s->magic, vc(s->data));
  14224. }
  14225. JSValue JS_NewCFunctionData(JSContext *ctx, JSCFunctionData *func,
  14226. int length, int magic, int data_len,
  14227. JSValueConst *data)
  14228. {
  14229. JSCFunctionDataRecord *s;
  14230. JSValue func_obj;
  14231. int i;
  14232. func_obj = JS_NewObjectProtoClass(ctx, ctx->function_proto,
  14233. JS_CLASS_C_FUNCTION_DATA);
  14234. if (JS_IsException(func_obj))
  14235. return func_obj;
  14236. s = js_malloc(ctx, sizeof(*s) + data_len * sizeof(JSValue));
  14237. if (!s) {
  14238. JS_FreeValue(ctx, func_obj);
  14239. return JS_EXCEPTION;
  14240. }
  14241. s->func = func;
  14242. s->length = length;
  14243. s->data_len = data_len;
  14244. s->magic = magic;
  14245. for(i = 0; i < data_len; i++)
  14246. s->data[i] = js_dup(data[i]);
  14247. JS_SetOpaqueInternal(func_obj, s);
  14248. js_function_set_properties(ctx, func_obj,
  14249. JS_ATOM_empty_string, length);
  14250. return func_obj;
  14251. }
  14252. static JSContext *js_autoinit_get_realm(JSProperty *pr)
  14253. {
  14254. return (JSContext *)(pr->u.init.realm_and_id & ~3);
  14255. }
  14256. static JSAutoInitIDEnum js_autoinit_get_id(JSProperty *pr)
  14257. {
  14258. return pr->u.init.realm_and_id & 3;
  14259. }
  14260. static void js_autoinit_free(JSRuntime *rt, JSProperty *pr)
  14261. {
  14262. JS_FreeContext(js_autoinit_get_realm(pr));
  14263. }
  14264. static void js_autoinit_mark(JSRuntime *rt, JSProperty *pr,
  14265. JS_MarkFunc *mark_func)
  14266. {
  14267. mark_func(rt, &js_autoinit_get_realm(pr)->header);
  14268. }
  14269. static void free_property(JSRuntime *rt, JSProperty *pr, int prop_flags)
  14270. {
  14271. if (unlikely(prop_flags & JS_PROP_TMASK)) {
  14272. if ((prop_flags & JS_PROP_TMASK) == JS_PROP_GETSET) {
  14273. if (pr->u.getset.getter)
  14274. JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.getter));
  14275. if (pr->u.getset.setter)
  14276. JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.setter));
  14277. } else if ((prop_flags & JS_PROP_TMASK) == JS_PROP_VARREF) {
  14278. free_var_ref(rt, pr->u.var_ref);
  14279. } else if ((prop_flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) {
  14280. js_autoinit_free(rt, pr);
  14281. }
  14282. } else {
  14283. JS_FreeValueRT(rt, pr->u.value);
  14284. }
  14285. }
  14286. static force_inline JSShapeProperty *find_own_property1(JSObject *p,
  14287. JSAtom atom)
  14288. {
  14289. JSShape *sh;
  14290. JSShapeProperty *pr, *prop;
  14291. intptr_t h;
  14292. sh = p->shape;
  14293. h = (uintptr_t)atom & sh->prop_hash_mask;
  14294. h = prop_hash_end(sh)[-h - 1];
  14295. prop = get_shape_prop(sh);
  14296. while (h) {
  14297. pr = &prop[h - 1];
  14298. if (likely(pr->atom == atom)) {
  14299. return pr;
  14300. }
  14301. h = pr->hash_next;
  14302. }
  14303. return NULL;
  14304. }
  14305. static force_inline JSShapeProperty *find_own_property(JSProperty **ppr,
  14306. JSObject *p,
  14307. JSAtom atom)
  14308. {
  14309. JSShape *sh;
  14310. JSShapeProperty *pr, *prop;
  14311. intptr_t h;
  14312. sh = p->shape;
  14313. h = (uintptr_t)atom & sh->prop_hash_mask;
  14314. h = prop_hash_end(sh)[-h - 1];
  14315. prop = get_shape_prop(sh);
  14316. while (h) {
  14317. pr = &prop[h - 1];
  14318. if (likely(pr->atom == atom)) {
  14319. *ppr = &p->prop[h - 1];
  14320. /* the compiler should be able to assume that pr != NULL here */
  14321. return pr;
  14322. }
  14323. h = pr->hash_next;
  14324. }
  14325. *ppr = NULL;
  14326. return NULL;
  14327. }
  14328. /* indicate that the object may be part of a function prototype cycle */
  14329. static void set_cycle_flag(JSContext *ctx, JSValueConst obj)
  14330. {
  14331. }
  14332. static void free_var_ref(JSRuntime *rt, JSVarRef *var_ref)
  14333. {
  14334. if (var_ref) {
  14335. assert(var_ref->header.ref_count > 0);
  14336. if (--var_ref->header.ref_count == 0) {
  14337. if (var_ref->is_detached) {
  14338. JS_FreeValueRT(rt, var_ref->value);
  14339. remove_gc_object(&var_ref->header);
  14340. } else {
  14341. list_del(&var_ref->header.link); /* still on the stack */
  14342. }
  14343. js_free_rt(rt, var_ref);
  14344. }
  14345. }
  14346. }
  14347. static void js_array_finalizer(JSRuntime *rt, JSValueConst val)
  14348. {
  14349. JSObject *p = JS_VALUE_GET_OBJ(val);
  14350. int i;
  14351. for(i = 0; i < p->u.array.count; i++) {
  14352. JS_FreeValueRT(rt, p->u.array.u.values[i]);
  14353. }
  14354. js_free_rt(rt, p->u.array.u.values);
  14355. }
  14356. static void js_array_mark(JSRuntime *rt, JSValueConst val,
  14357. JS_MarkFunc *mark_func)
  14358. {
  14359. JSObject *p = JS_VALUE_GET_OBJ(val);
  14360. int i;
  14361. for(i = 0; i < p->u.array.count; i++) {
  14362. JS_MarkValue(rt, p->u.array.u.values[i], mark_func);
  14363. }
  14364. }
  14365. static void js_object_data_finalizer(JSRuntime *rt, JSValueConst val)
  14366. {
  14367. JSObject *p = JS_VALUE_GET_OBJ(val);
  14368. JS_FreeValueRT(rt, p->u.object_data);
  14369. p->u.object_data = JS_UNDEFINED;
  14370. }
  14371. static void js_object_data_mark(JSRuntime *rt, JSValueConst val,
  14372. JS_MarkFunc *mark_func)
  14373. {
  14374. JSObject *p = JS_VALUE_GET_OBJ(val);
  14375. JS_MarkValue(rt, p->u.object_data, mark_func);
  14376. }
  14377. static void js_c_function_finalizer(JSRuntime *rt, JSValueConst val)
  14378. {
  14379. JSObject *p = JS_VALUE_GET_OBJ(val);
  14380. if (p->u.cfunc.realm)
  14381. JS_FreeContext(p->u.cfunc.realm);
  14382. }
  14383. static void js_c_function_mark(JSRuntime *rt, JSValueConst val,
  14384. JS_MarkFunc *mark_func)
  14385. {
  14386. JSObject *p = JS_VALUE_GET_OBJ(val);
  14387. if (p->u.cfunc.realm)
  14388. mark_func(rt, &p->u.cfunc.realm->header);
  14389. }
  14390. static void js_bytecode_function_finalizer(JSRuntime *rt, JSValueConst val)
  14391. {
  14392. JSObject *p1, *p = JS_VALUE_GET_OBJ(val);
  14393. JSFunctionBytecode *b;
  14394. JSVarRef **var_refs;
  14395. int i;
  14396. p1 = p->u.func.home_object;
  14397. if (p1) {
  14398. JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_OBJECT, p1));
  14399. }
  14400. b = p->u.func.function_bytecode;
  14401. if (b) {
  14402. var_refs = p->u.func.var_refs;
  14403. if (var_refs) {
  14404. for(i = 0; i < b->closure_var_count; i++)
  14405. free_var_ref(rt, var_refs[i]);
  14406. js_free_rt(rt, var_refs);
  14407. }
  14408. JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_FUNCTION_BYTECODE, b));
  14409. }
  14410. }
  14411. static void js_bytecode_function_mark(JSRuntime *rt, JSValueConst val,
  14412. JS_MarkFunc *mark_func)
  14413. {
  14414. JSObject *p = JS_VALUE_GET_OBJ(val);
  14415. JSVarRef **var_refs = p->u.func.var_refs;
  14416. JSFunctionBytecode *b = p->u.func.function_bytecode;
  14417. int i;
  14418. if (p->u.func.home_object) {
  14419. JS_MarkValue(rt, JS_MKPTR(JS_TAG_OBJECT, p->u.func.home_object),
  14420. mark_func);
  14421. }
  14422. if (b) {
  14423. if (var_refs) {
  14424. for(i = 0; i < b->closure_var_count; i++) {
  14425. JSVarRef *var_ref = var_refs[i];
  14426. if (var_ref && var_ref->is_detached) {
  14427. mark_func(rt, &var_ref->header);
  14428. }
  14429. }
  14430. }
  14431. /* must mark the function bytecode because template objects may be
  14432. part of a cycle */
  14433. JS_MarkValue(rt, JS_MKPTR(JS_TAG_FUNCTION_BYTECODE, b), mark_func);
  14434. }
  14435. }
  14436. static void js_bound_function_finalizer(JSRuntime *rt, JSValueConst val)
  14437. {
  14438. JSObject *p = JS_VALUE_GET_OBJ(val);
  14439. JSBoundFunction *bf = p->u.bound_function;
  14440. int i;
  14441. JS_FreeValueRT(rt, bf->func_obj);
  14442. JS_FreeValueRT(rt, bf->this_val);
  14443. for(i = 0; i < bf->argc; i++) {
  14444. JS_FreeValueRT(rt, bf->argv[i]);
  14445. }
  14446. js_free_rt(rt, bf);
  14447. }
  14448. static void js_bound_function_mark(JSRuntime *rt, JSValueConst val,
  14449. JS_MarkFunc *mark_func)
  14450. {
  14451. JSObject *p = JS_VALUE_GET_OBJ(val);
  14452. JSBoundFunction *bf = p->u.bound_function;
  14453. int i;
  14454. JS_MarkValue(rt, bf->func_obj, mark_func);
  14455. JS_MarkValue(rt, bf->this_val, mark_func);
  14456. for(i = 0; i < bf->argc; i++)
  14457. JS_MarkValue(rt, bf->argv[i], mark_func);
  14458. }
  14459. static void js_for_in_iterator_finalizer(JSRuntime *rt, JSValueConst val)
  14460. {
  14461. JSObject *p = JS_VALUE_GET_OBJ(val);
  14462. JSForInIterator *it = p->u.for_in_iterator;
  14463. JS_FreeValueRT(rt, it->obj);
  14464. js_free_rt(rt, it);
  14465. }
  14466. static void js_for_in_iterator_mark(JSRuntime *rt, JSValueConst val,
  14467. JS_MarkFunc *mark_func)
  14468. {
  14469. JSObject *p = JS_VALUE_GET_OBJ(val);
  14470. JSForInIterator *it = p->u.for_in_iterator;
  14471. JS_MarkValue(rt, it->obj, mark_func);
  14472. }
  14473. static void free_object(JSRuntime *rt, JSObject *p)
  14474. {
  14475. int i;
  14476. JSClassFinalizer *finalizer;
  14477. JSShape *sh;
  14478. JSShapeProperty *pr;
  14479. p->free_mark = 1; /* used to tell the object is invalid when
  14480. freeing cycles */
  14481. /* free all the fields */
  14482. sh = p->shape;
  14483. pr = get_shape_prop(sh);
  14484. for(i = 0; i < sh->prop_count; i++) {
  14485. free_property(rt, &p->prop[i], pr->flags);
  14486. pr++;
  14487. }
  14488. js_free_rt(rt, p->prop);
  14489. /* as an optimization we destroy the shape immediately without
  14490. putting it in gc_zero_ref_count_list */
  14491. js_free_shape(rt, sh);
  14492. /* fail safe */
  14493. p->shape = NULL;
  14494. p->prop = NULL;
  14495. if (unlikely(p->first_weak_ref)) {
  14496. reset_weak_ref(rt, &p->first_weak_ref);
  14497. }
  14498. finalizer = rt->class_array[p->class_id].finalizer;
  14499. if (finalizer)
  14500. (*finalizer)(rt, JS_MKPTR(JS_TAG_OBJECT, p));
  14501. /* fail safe */
  14502. p->class_id = 0;
  14503. p->u.opaque = NULL;
  14504. p->u.func.var_refs = NULL;
  14505. p->u.func.home_object = NULL;
  14506. remove_gc_object(&p->header);
  14507. if (rt->gc_phase == JS_GC_PHASE_REMOVE_CYCLES && p->header.ref_count != 0) {
  14508. list_add_tail(&p->header.link, &rt->gc_zero_ref_count_list);
  14509. } else {
  14510. js_free_rt(rt, p);
  14511. }
  14512. }
  14513. static void free_gc_object(JSRuntime *rt, JSGCObjectHeader *gp)
  14514. {
  14515. switch(gp->gc_obj_type) {
  14516. case JS_GC_OBJ_TYPE_JS_OBJECT:
  14517. free_object(rt, (JSObject *)gp);
  14518. break;
  14519. case JS_GC_OBJ_TYPE_FUNCTION_BYTECODE:
  14520. free_function_bytecode(rt, (JSFunctionBytecode *)gp);
  14521. break;
  14522. default:
  14523. abort();
  14524. }
  14525. }
  14526. static void free_zero_refcount(JSRuntime *rt)
  14527. {
  14528. struct list_head *el;
  14529. JSGCObjectHeader *p;
  14530. rt->gc_phase = JS_GC_PHASE_DECREF;
  14531. for(;;) {
  14532. el = rt->gc_zero_ref_count_list.next;
  14533. if (el == &rt->gc_zero_ref_count_list)
  14534. break;
  14535. p = list_entry(el, JSGCObjectHeader, link);
  14536. assert(p->ref_count == 0);
  14537. free_gc_object(rt, p);
  14538. }
  14539. rt->gc_phase = JS_GC_PHASE_NONE;
  14540. }
  14541. /* called with the ref_count of 'v' reaches zero. */
  14542. static void js_free_value_rt(JSRuntime *rt, JSValue v)
  14543. {
  14544. uint32_t tag = JS_VALUE_GET_TAG(v);
  14545. #ifdef ENABLE_DUMPS // JS_DUMP_FREE
  14546. if (check_dump_flag(rt, JS_DUMP_FREE)) {
  14547. /* Prevent invalid object access during GC */
  14548. if ((rt->gc_phase != JS_GC_PHASE_REMOVE_CYCLES)
  14549. || (tag != JS_TAG_OBJECT && tag != JS_TAG_FUNCTION_BYTECODE)) {
  14550. printf("Freeing ");
  14551. if (tag == JS_TAG_OBJECT) {
  14552. JS_DumpObject(rt, JS_VALUE_GET_OBJ(v));
  14553. } else {
  14554. JS_DumpValue(rt, v);
  14555. printf("\n");
  14556. }
  14557. }
  14558. }
  14559. #endif
  14560. switch(tag) {
  14561. case JS_TAG_STRING:
  14562. {
  14563. JSString *p = JS_VALUE_GET_STRING(v);
  14564. if (p->atom_type) {
  14565. JS_FreeAtomStruct(rt, p);
  14566. } else {
  14567. #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS
  14568. list_del(&p->link);
  14569. #endif
  14570. js_free_rt(rt, p);
  14571. }
  14572. }
  14573. break;
  14574. case JS_TAG_OBJECT:
  14575. case JS_TAG_FUNCTION_BYTECODE:
  14576. {
  14577. JSGCObjectHeader *p = JS_VALUE_GET_PTR(v);
  14578. if (rt->gc_phase != JS_GC_PHASE_REMOVE_CYCLES) {
  14579. list_del(&p->link);
  14580. list_add(&p->link, &rt->gc_zero_ref_count_list);
  14581. if (rt->gc_phase == JS_GC_PHASE_NONE) {
  14582. free_zero_refcount(rt);
  14583. }
  14584. }
  14585. }
  14586. break;
  14587. case JS_TAG_MODULE:
  14588. abort(); /* never freed here */
  14589. break;
  14590. case JS_TAG_BIG_INT:
  14591. {
  14592. JSBigInt *bf = JS_VALUE_GET_PTR(v);
  14593. bf_delete(&bf->num);
  14594. js_free_rt(rt, bf);
  14595. }
  14596. break;
  14597. case JS_TAG_SYMBOL:
  14598. {
  14599. JSAtomStruct *p = JS_VALUE_GET_PTR(v);
  14600. JS_FreeAtomStruct(rt, p);
  14601. }
  14602. break;
  14603. default:
  14604. printf("js_free_value_rt: unknown tag=%d\n", tag);
  14605. abort();
  14606. }
  14607. }
  14608. void JS_FreeValueRT(JSRuntime *rt, JSValue v)
  14609. {
  14610. if (JS_VALUE_HAS_REF_COUNT(v)) {
  14611. JSRefCountHeader *p = (JSRefCountHeader *)JS_VALUE_GET_PTR(v);
  14612. if (--p->ref_count <= 0) {
  14613. js_free_value_rt(rt, v);
  14614. }
  14615. }
  14616. }
  14617. void JS_FreeValue(JSContext *ctx, JSValue v)
  14618. {
  14619. JS_FreeValueRT(ctx->rt, v);
  14620. }
  14621. /* garbage collection */
  14622. static void add_gc_object(JSRuntime *rt, JSGCObjectHeader *h,
  14623. JSGCObjectTypeEnum type)
  14624. {
  14625. h->mark = 0;
  14626. h->gc_obj_type = type;
  14627. list_add_tail(&h->link, &rt->gc_obj_list);
  14628. }
  14629. static void remove_gc_object(JSGCObjectHeader *h)
  14630. {
  14631. list_del(&h->link);
  14632. }
  14633. void JS_MarkValue(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func)
  14634. {
  14635. if (JS_VALUE_HAS_REF_COUNT(val)) {
  14636. switch(JS_VALUE_GET_TAG(val)) {
  14637. case JS_TAG_OBJECT:
  14638. case JS_TAG_FUNCTION_BYTECODE:
  14639. mark_func(rt, JS_VALUE_GET_PTR(val));
  14640. break;
  14641. default:
  14642. break;
  14643. }
  14644. }
  14645. }
  14646. static void mark_children(JSRuntime *rt, JSGCObjectHeader *gp,
  14647. JS_MarkFunc *mark_func)
  14648. {
  14649. switch(gp->gc_obj_type) {
  14650. case JS_GC_OBJ_TYPE_JS_OBJECT:
  14651. {
  14652. JSObject *p = (JSObject *)gp;
  14653. JSShapeProperty *prs;
  14654. JSShape *sh;
  14655. int i;
  14656. sh = p->shape;
  14657. mark_func(rt, &sh->header);
  14658. /* mark all the fields */
  14659. prs = get_shape_prop(sh);
  14660. for(i = 0; i < sh->prop_count; i++) {
  14661. JSProperty *pr = &p->prop[i];
  14662. if (prs->atom != JS_ATOM_NULL) {
  14663. if (prs->flags & JS_PROP_TMASK) {
  14664. if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) {
  14665. if (pr->u.getset.getter)
  14666. mark_func(rt, &pr->u.getset.getter->header);
  14667. if (pr->u.getset.setter)
  14668. mark_func(rt, &pr->u.getset.setter->header);
  14669. } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) {
  14670. if (pr->u.var_ref->is_detached) {
  14671. /* Note: the tag does not matter
  14672. provided it is a GC object */
  14673. mark_func(rt, &pr->u.var_ref->header);
  14674. }
  14675. } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) {
  14676. js_autoinit_mark(rt, pr, mark_func);
  14677. }
  14678. } else {
  14679. JS_MarkValue(rt, pr->u.value, mark_func);
  14680. }
  14681. }
  14682. prs++;
  14683. }
  14684. if (p->class_id != JS_CLASS_OBJECT) {
  14685. JSClassGCMark *gc_mark;
  14686. gc_mark = rt->class_array[p->class_id].gc_mark;
  14687. if (gc_mark)
  14688. gc_mark(rt, JS_MKPTR(JS_TAG_OBJECT, p), mark_func);
  14689. }
  14690. }
  14691. break;
  14692. case JS_GC_OBJ_TYPE_FUNCTION_BYTECODE:
  14693. /* the template objects can be part of a cycle */
  14694. {
  14695. JSFunctionBytecode *b = (JSFunctionBytecode *)gp;
  14696. int i;
  14697. for(i = 0; i < b->cpool_count; i++) {
  14698. JS_MarkValue(rt, b->cpool[i], mark_func);
  14699. }
  14700. if (b->realm)
  14701. mark_func(rt, &b->realm->header);
  14702. }
  14703. break;
  14704. case JS_GC_OBJ_TYPE_VAR_REF:
  14705. {
  14706. JSVarRef *var_ref = (JSVarRef *)gp;
  14707. /* only detached variable referenced are taken into account */
  14708. assert(var_ref->is_detached);
  14709. JS_MarkValue(rt, *var_ref->pvalue, mark_func);
  14710. }
  14711. break;
  14712. case JS_GC_OBJ_TYPE_ASYNC_FUNCTION:
  14713. {
  14714. JSAsyncFunctionData *s = (JSAsyncFunctionData *)gp;
  14715. if (s->is_active)
  14716. async_func_mark(rt, &s->func_state, mark_func);
  14717. JS_MarkValue(rt, s->resolving_funcs[0], mark_func);
  14718. JS_MarkValue(rt, s->resolving_funcs[1], mark_func);
  14719. }
  14720. break;
  14721. case JS_GC_OBJ_TYPE_SHAPE:
  14722. {
  14723. JSShape *sh = (JSShape *)gp;
  14724. if (sh->proto != NULL) {
  14725. mark_func(rt, &sh->proto->header);
  14726. }
  14727. }
  14728. break;
  14729. case JS_GC_OBJ_TYPE_JS_CONTEXT:
  14730. {
  14731. JSContext *ctx = (JSContext *)gp;
  14732. JS_MarkContext(rt, ctx, mark_func);
  14733. }
  14734. break;
  14735. default:
  14736. abort();
  14737. }
  14738. }
  14739. static void gc_decref_child(JSRuntime *rt, JSGCObjectHeader *p)
  14740. {
  14741. assert(p->ref_count > 0);
  14742. p->ref_count--;
  14743. if (p->ref_count == 0 && p->mark == 1) {
  14744. list_del(&p->link);
  14745. list_add_tail(&p->link, &rt->tmp_obj_list);
  14746. }
  14747. }
  14748. static void gc_decref(JSRuntime *rt)
  14749. {
  14750. struct list_head *el, *el1;
  14751. JSGCObjectHeader *p;
  14752. init_list_head(&rt->tmp_obj_list);
  14753. /* decrement the refcount of all the children of all the GC
  14754. objects and move the GC objects with zero refcount to
  14755. tmp_obj_list */
  14756. list_for_each_safe(el, el1, &rt->gc_obj_list) {
  14757. p = list_entry(el, JSGCObjectHeader, link);
  14758. assert(p->mark == 0);
  14759. mark_children(rt, p, gc_decref_child);
  14760. p->mark = 1;
  14761. if (p->ref_count == 0) {
  14762. list_del(&p->link);
  14763. list_add_tail(&p->link, &rt->tmp_obj_list);
  14764. }
  14765. }
  14766. }
  14767. static void gc_scan_incref_child(JSRuntime *rt, JSGCObjectHeader *p)
  14768. {
  14769. p->ref_count++;
  14770. if (p->ref_count == 1) {
  14771. /* ref_count was 0: remove from tmp_obj_list and add at the
  14772. end of gc_obj_list */
  14773. list_del(&p->link);
  14774. list_add_tail(&p->link, &rt->gc_obj_list);
  14775. p->mark = 0; /* reset the mark for the next GC call */
  14776. }
  14777. }
  14778. static void gc_scan_incref_child2(JSRuntime *rt, JSGCObjectHeader *p)
  14779. {
  14780. p->ref_count++;
  14781. }
  14782. static void gc_scan(JSRuntime *rt)
  14783. {
  14784. struct list_head *el;
  14785. JSGCObjectHeader *p;
  14786. /* keep the objects with a refcount > 0 and their children. */
  14787. list_for_each(el, &rt->gc_obj_list) {
  14788. p = list_entry(el, JSGCObjectHeader, link);
  14789. assert(p->ref_count > 0);
  14790. p->mark = 0; /* reset the mark for the next GC call */
  14791. mark_children(rt, p, gc_scan_incref_child);
  14792. }
  14793. /* restore the refcount of the objects to be deleted. */
  14794. list_for_each(el, &rt->tmp_obj_list) {
  14795. p = list_entry(el, JSGCObjectHeader, link);
  14796. mark_children(rt, p, gc_scan_incref_child2);
  14797. }
  14798. }
  14799. static void gc_free_cycles(JSRuntime *rt)
  14800. {
  14801. struct list_head *el, *el1;
  14802. JSGCObjectHeader *p;
  14803. #ifdef ENABLE_DUMPS // JS_DUMP_GC_FREE
  14804. bool header_done = false;
  14805. #endif
  14806. rt->gc_phase = JS_GC_PHASE_REMOVE_CYCLES;
  14807. for(;;) {
  14808. el = rt->tmp_obj_list.next;
  14809. if (el == &rt->tmp_obj_list)
  14810. break;
  14811. p = list_entry(el, JSGCObjectHeader, link);
  14812. /* Only need to free the GC object associated with JS
  14813. values. The rest will be automatically removed because they
  14814. must be referenced by them. */
  14815. switch(p->gc_obj_type) {
  14816. case JS_GC_OBJ_TYPE_JS_OBJECT:
  14817. case JS_GC_OBJ_TYPE_FUNCTION_BYTECODE:
  14818. #ifdef ENABLE_DUMPS // JS_DUMP_GC_FREE
  14819. if (check_dump_flag(rt, JS_DUMP_GC_FREE)) {
  14820. if (!header_done) {
  14821. printf("Freeing cycles:\n");
  14822. JS_DumpObjectHeader(rt);
  14823. header_done = true;
  14824. }
  14825. JS_DumpGCObject(rt, p);
  14826. }
  14827. #endif
  14828. free_gc_object(rt, p);
  14829. break;
  14830. default:
  14831. list_del(&p->link);
  14832. list_add_tail(&p->link, &rt->gc_zero_ref_count_list);
  14833. break;
  14834. }
  14835. }
  14836. rt->gc_phase = JS_GC_PHASE_NONE;
  14837. list_for_each_safe(el, el1, &rt->gc_zero_ref_count_list) {
  14838. p = list_entry(el, JSGCObjectHeader, link);
  14839. assert(p->gc_obj_type == JS_GC_OBJ_TYPE_JS_OBJECT ||
  14840. p->gc_obj_type == JS_GC_OBJ_TYPE_FUNCTION_BYTECODE);
  14841. js_free_rt(rt, p);
  14842. }
  14843. init_list_head(&rt->gc_zero_ref_count_list);
  14844. }
  14845. void JS_RunGC(JSRuntime *rt)
  14846. {
  14847. /* decrement the reference of the children of each object. mark =
  14848. 1 after this pass. */
  14849. gc_decref(rt);
  14850. /* keep the GC objects with a non zero refcount and their childs */
  14851. gc_scan(rt);
  14852. /* free the GC objects in a cycle */
  14853. gc_free_cycles(rt);
  14854. }
  14855. /* Return false if not an object or if the object has already been
  14856. freed (zombie objects are visible in finalizers when freeing
  14857. cycles). */
  14858. bool JS_IsLiveObject(JSRuntime *rt, JSValueConst obj)
  14859. {
  14860. JSObject *p;
  14861. if (!JS_IsObject(obj))
  14862. return false;
  14863. p = JS_VALUE_GET_OBJ(obj);
  14864. return !p->free_mark;
  14865. }
  14866. /* Compute memory used by various object types */
  14867. /* XXX: poor man's approach to handling multiply referenced objects */
  14868. typedef struct JSMemoryUsage_helper {
  14869. double memory_used_count;
  14870. double str_count;
  14871. double str_size;
  14872. int64_t js_func_count;
  14873. double js_func_size;
  14874. int64_t js_func_code_size;
  14875. int64_t js_func_pc2line_count;
  14876. int64_t js_func_pc2line_size;
  14877. } JSMemoryUsage_helper;
  14878. static void compute_value_size(JSValue val, JSMemoryUsage_helper *hp);
  14879. static void compute_jsstring_size(JSString *str, JSMemoryUsage_helper *hp)
  14880. {
  14881. if (!str->atom_type) { /* atoms are handled separately */
  14882. double s_ref_count = str->header.ref_count;
  14883. hp->str_count += 1 / s_ref_count;
  14884. hp->str_size += ((sizeof(*str) + (str->len << str->is_wide_char) +
  14885. 1 - str->is_wide_char) / s_ref_count);
  14886. }
  14887. }
  14888. static void compute_bytecode_size(JSFunctionBytecode *b, JSMemoryUsage_helper *hp)
  14889. {
  14890. int memory_used_count, js_func_size, i;
  14891. memory_used_count = 0;
  14892. js_func_size = sizeof(*b);
  14893. if (b->vardefs) {
  14894. js_func_size += (b->arg_count + b->var_count) * sizeof(*b->vardefs);
  14895. }
  14896. if (b->cpool) {
  14897. js_func_size += b->cpool_count * sizeof(*b->cpool);
  14898. for (i = 0; i < b->cpool_count; i++) {
  14899. JSValue val = b->cpool[i];
  14900. compute_value_size(val, hp);
  14901. }
  14902. }
  14903. if (b->closure_var) {
  14904. js_func_size += b->closure_var_count * sizeof(*b->closure_var);
  14905. }
  14906. if (b->byte_code_buf) {
  14907. hp->js_func_code_size += b->byte_code_len;
  14908. }
  14909. memory_used_count++;
  14910. js_func_size += b->source_len + 1;
  14911. if (b->pc2line_len) {
  14912. memory_used_count++;
  14913. hp->js_func_pc2line_count += 1;
  14914. hp->js_func_pc2line_size += b->pc2line_len;
  14915. }
  14916. hp->js_func_size += js_func_size;
  14917. hp->js_func_count += 1;
  14918. hp->memory_used_count += memory_used_count;
  14919. }
  14920. static void compute_value_size(JSValue val, JSMemoryUsage_helper *hp)
  14921. {
  14922. switch(JS_VALUE_GET_TAG(val)) {
  14923. case JS_TAG_STRING:
  14924. compute_jsstring_size(JS_VALUE_GET_STRING(val), hp);
  14925. break;
  14926. case JS_TAG_BIG_INT:
  14927. /* should track JSBigInt usage */
  14928. break;
  14929. }
  14930. }
  14931. void JS_ComputeMemoryUsage(JSRuntime *rt, JSMemoryUsage *s)
  14932. {
  14933. struct list_head *el, *el1;
  14934. int i;
  14935. JSMemoryUsage_helper mem = { 0 }, *hp = &mem;
  14936. memset(s, 0, sizeof(*s));
  14937. s->malloc_count = rt->malloc_state.malloc_count;
  14938. s->malloc_size = rt->malloc_state.malloc_size;
  14939. s->malloc_limit = rt->malloc_state.malloc_limit;
  14940. s->memory_used_count = 2; /* rt + rt->class_array */
  14941. s->memory_used_size = sizeof(JSRuntime) + sizeof(JSClass) * rt->class_count;
  14942. list_for_each(el, &rt->context_list) {
  14943. JSContext *ctx = list_entry(el, JSContext, link);
  14944. JSShape *sh = ctx->array_shape;
  14945. s->memory_used_count += 2; /* ctx + ctx->class_proto */
  14946. s->memory_used_size += sizeof(JSContext) +
  14947. sizeof(JSValue) * rt->class_count;
  14948. s->binary_object_count += ctx->binary_object_count;
  14949. s->binary_object_size += ctx->binary_object_size;
  14950. /* the hashed shapes are counted separately */
  14951. if (sh && !sh->is_hashed) {
  14952. int hash_size = sh->prop_hash_mask + 1;
  14953. s->shape_count++;
  14954. s->shape_size += get_shape_size(hash_size, sh->prop_size);
  14955. }
  14956. list_for_each(el1, &ctx->loaded_modules) {
  14957. JSModuleDef *m = list_entry(el1, JSModuleDef, link);
  14958. s->memory_used_count += 1;
  14959. s->memory_used_size += sizeof(*m);
  14960. if (m->req_module_entries) {
  14961. s->memory_used_count += 1;
  14962. s->memory_used_size += m->req_module_entries_count * sizeof(*m->req_module_entries);
  14963. }
  14964. if (m->export_entries) {
  14965. s->memory_used_count += 1;
  14966. s->memory_used_size += m->export_entries_count * sizeof(*m->export_entries);
  14967. for (i = 0; i < m->export_entries_count; i++) {
  14968. JSExportEntry *me = &m->export_entries[i];
  14969. if (me->export_type == JS_EXPORT_TYPE_LOCAL && me->u.local.var_ref) {
  14970. /* potential multiple count */
  14971. s->memory_used_count += 1;
  14972. compute_value_size(me->u.local.var_ref->value, hp);
  14973. }
  14974. }
  14975. }
  14976. if (m->star_export_entries) {
  14977. s->memory_used_count += 1;
  14978. s->memory_used_size += m->star_export_entries_count * sizeof(*m->star_export_entries);
  14979. }
  14980. if (m->import_entries) {
  14981. s->memory_used_count += 1;
  14982. s->memory_used_size += m->import_entries_count * sizeof(*m->import_entries);
  14983. }
  14984. compute_value_size(m->module_ns, hp);
  14985. compute_value_size(m->func_obj, hp);
  14986. }
  14987. }
  14988. list_for_each(el, &rt->gc_obj_list) {
  14989. JSGCObjectHeader *gp = list_entry(el, JSGCObjectHeader, link);
  14990. JSObject *p;
  14991. JSShape *sh;
  14992. JSShapeProperty *prs;
  14993. /* XXX: could count the other GC object types too */
  14994. if (gp->gc_obj_type == JS_GC_OBJ_TYPE_FUNCTION_BYTECODE) {
  14995. compute_bytecode_size((JSFunctionBytecode *)gp, hp);
  14996. continue;
  14997. } else if (gp->gc_obj_type != JS_GC_OBJ_TYPE_JS_OBJECT) {
  14998. continue;
  14999. }
  15000. p = (JSObject *)gp;
  15001. sh = p->shape;
  15002. s->obj_count++;
  15003. if (p->prop) {
  15004. s->memory_used_count++;
  15005. s->prop_size += sh->prop_size * sizeof(*p->prop);
  15006. s->prop_count += sh->prop_count;
  15007. prs = get_shape_prop(sh);
  15008. for(i = 0; i < sh->prop_count; i++) {
  15009. JSProperty *pr = &p->prop[i];
  15010. if (prs->atom != JS_ATOM_NULL && !(prs->flags & JS_PROP_TMASK)) {
  15011. compute_value_size(pr->u.value, hp);
  15012. }
  15013. prs++;
  15014. }
  15015. }
  15016. /* the hashed shapes are counted separately */
  15017. if (!sh->is_hashed) {
  15018. int hash_size = sh->prop_hash_mask + 1;
  15019. s->shape_count++;
  15020. s->shape_size += get_shape_size(hash_size, sh->prop_size);
  15021. }
  15022. switch(p->class_id) {
  15023. case JS_CLASS_ARRAY: /* u.array | length */
  15024. case JS_CLASS_ARGUMENTS: /* u.array | length */
  15025. s->array_count++;
  15026. if (p->fast_array) {
  15027. s->fast_array_count++;
  15028. if (p->u.array.u.values) {
  15029. s->memory_used_count++;
  15030. s->memory_used_size += p->u.array.count *
  15031. sizeof(*p->u.array.u.values);
  15032. s->fast_array_elements += p->u.array.count;
  15033. for (i = 0; i < p->u.array.count; i++) {
  15034. compute_value_size(p->u.array.u.values[i], hp);
  15035. }
  15036. }
  15037. }
  15038. break;
  15039. case JS_CLASS_NUMBER: /* u.object_data */
  15040. case JS_CLASS_STRING: /* u.object_data */
  15041. case JS_CLASS_BOOLEAN: /* u.object_data */
  15042. case JS_CLASS_SYMBOL: /* u.object_data */
  15043. case JS_CLASS_DATE: /* u.object_data */
  15044. case JS_CLASS_BIG_INT: /* u.object_data */
  15045. compute_value_size(p->u.object_data, hp);
  15046. break;
  15047. case JS_CLASS_C_FUNCTION: /* u.cfunc */
  15048. s->c_func_count++;
  15049. break;
  15050. case JS_CLASS_BYTECODE_FUNCTION: /* u.func */
  15051. {
  15052. JSFunctionBytecode *b = p->u.func.function_bytecode;
  15053. JSVarRef **var_refs = p->u.func.var_refs;
  15054. /* home_object: object will be accounted for in list scan */
  15055. if (var_refs) {
  15056. s->memory_used_count++;
  15057. s->js_func_size += b->closure_var_count * sizeof(*var_refs);
  15058. for (i = 0; i < b->closure_var_count; i++) {
  15059. if (var_refs[i]) {
  15060. double ref_count = var_refs[i]->header.ref_count;
  15061. s->memory_used_count += 1 / ref_count;
  15062. s->js_func_size += sizeof(*var_refs[i]) / ref_count;
  15063. /* handle non object closed values */
  15064. if (var_refs[i]->pvalue == &var_refs[i]->value) {
  15065. /* potential multiple count */
  15066. compute_value_size(var_refs[i]->value, hp);
  15067. }
  15068. }
  15069. }
  15070. }
  15071. }
  15072. break;
  15073. case JS_CLASS_BOUND_FUNCTION: /* u.bound_function */
  15074. {
  15075. JSBoundFunction *bf = p->u.bound_function;
  15076. /* func_obj and this_val are objects */
  15077. for (i = 0; i < bf->argc; i++) {
  15078. compute_value_size(bf->argv[i], hp);
  15079. }
  15080. s->memory_used_count += 1;
  15081. s->memory_used_size += sizeof(*bf) + bf->argc * sizeof(*bf->argv);
  15082. }
  15083. break;
  15084. case JS_CLASS_C_FUNCTION_DATA: /* u.c_function_data_record */
  15085. {
  15086. JSCFunctionDataRecord *fd = p->u.c_function_data_record;
  15087. if (fd) {
  15088. for (i = 0; i < fd->data_len; i++) {
  15089. compute_value_size(fd->data[i], hp);
  15090. }
  15091. s->memory_used_count += 1;
  15092. s->memory_used_size += sizeof(*fd) + fd->data_len * sizeof(*fd->data);
  15093. }
  15094. }
  15095. break;
  15096. case JS_CLASS_REGEXP: /* u.regexp */
  15097. compute_jsstring_size(p->u.regexp.pattern, hp);
  15098. compute_jsstring_size(p->u.regexp.bytecode, hp);
  15099. break;
  15100. case JS_CLASS_FOR_IN_ITERATOR: /* u.for_in_iterator */
  15101. {
  15102. JSForInIterator *it = p->u.for_in_iterator;
  15103. if (it) {
  15104. compute_value_size(it->obj, hp);
  15105. s->memory_used_count += 1;
  15106. s->memory_used_size += sizeof(*it);
  15107. }
  15108. }
  15109. break;
  15110. case JS_CLASS_ARRAY_BUFFER: /* u.array_buffer */
  15111. case JS_CLASS_SHARED_ARRAY_BUFFER: /* u.array_buffer */
  15112. {
  15113. JSArrayBuffer *abuf = p->u.array_buffer;
  15114. if (abuf) {
  15115. s->memory_used_count += 1;
  15116. s->memory_used_size += sizeof(*abuf);
  15117. if (abuf->data) {
  15118. s->memory_used_count += 1;
  15119. s->memory_used_size += abuf->byte_length;
  15120. }
  15121. }
  15122. }
  15123. break;
  15124. case JS_CLASS_GENERATOR: /* u.generator_data */
  15125. case JS_CLASS_UINT8C_ARRAY: /* u.typed_array / u.array */
  15126. case JS_CLASS_INT8_ARRAY: /* u.typed_array / u.array */
  15127. case JS_CLASS_UINT8_ARRAY: /* u.typed_array / u.array */
  15128. case JS_CLASS_INT16_ARRAY: /* u.typed_array / u.array */
  15129. case JS_CLASS_UINT16_ARRAY: /* u.typed_array / u.array */
  15130. case JS_CLASS_INT32_ARRAY: /* u.typed_array / u.array */
  15131. case JS_CLASS_UINT32_ARRAY: /* u.typed_array / u.array */
  15132. case JS_CLASS_BIG_INT64_ARRAY: /* u.typed_array / u.array */
  15133. case JS_CLASS_BIG_UINT64_ARRAY: /* u.typed_array / u.array */
  15134. case JS_CLASS_FLOAT16_ARRAY: /* u.typed_array / u.array */
  15135. case JS_CLASS_FLOAT32_ARRAY: /* u.typed_array / u.array */
  15136. case JS_CLASS_FLOAT64_ARRAY: /* u.typed_array / u.array */
  15137. case JS_CLASS_DATAVIEW: /* u.typed_array */
  15138. case JS_CLASS_MAP: /* u.map_state */
  15139. case JS_CLASS_SET: /* u.map_state */
  15140. case JS_CLASS_WEAKMAP: /* u.map_state */
  15141. case JS_CLASS_WEAKSET: /* u.map_state */
  15142. case JS_CLASS_MAP_ITERATOR: /* u.map_iterator_data */
  15143. case JS_CLASS_SET_ITERATOR: /* u.map_iterator_data */
  15144. case JS_CLASS_ARRAY_ITERATOR: /* u.array_iterator_data */
  15145. case JS_CLASS_STRING_ITERATOR: /* u.array_iterator_data */
  15146. case JS_CLASS_PROXY: /* u.proxy_data */
  15147. case JS_CLASS_PROMISE: /* u.promise_data */
  15148. case JS_CLASS_PROMISE_RESOLVE_FUNCTION: /* u.promise_function_data */
  15149. case JS_CLASS_PROMISE_REJECT_FUNCTION: /* u.promise_function_data */
  15150. case JS_CLASS_ASYNC_FUNCTION_RESOLVE: /* u.async_function_data */
  15151. case JS_CLASS_ASYNC_FUNCTION_REJECT: /* u.async_function_data */
  15152. case JS_CLASS_ASYNC_FROM_SYNC_ITERATOR: /* u.async_from_sync_iterator_data */
  15153. case JS_CLASS_ASYNC_GENERATOR: /* u.async_generator_data */
  15154. /* TODO */
  15155. default:
  15156. /* XXX: class definition should have an opaque block size */
  15157. if (p->u.opaque) {
  15158. s->memory_used_count += 1;
  15159. }
  15160. break;
  15161. }
  15162. }
  15163. s->obj_size += s->obj_count * sizeof(JSObject);
  15164. /* hashed shapes */
  15165. s->memory_used_count++; /* rt->shape_hash */
  15166. s->memory_used_size += sizeof(rt->shape_hash[0]) * rt->shape_hash_size;
  15167. for(i = 0; i < rt->shape_hash_size; i++) {
  15168. JSShape *sh;
  15169. for(sh = rt->shape_hash[i]; sh != NULL; sh = sh->shape_hash_next) {
  15170. int hash_size = sh->prop_hash_mask + 1;
  15171. s->shape_count++;
  15172. s->shape_size += get_shape_size(hash_size, sh->prop_size);
  15173. }
  15174. }
  15175. /* atoms */
  15176. s->memory_used_count += 2; /* rt->atom_array, rt->atom_hash */
  15177. s->atom_count = rt->atom_count;
  15178. s->atom_size = sizeof(rt->atom_array[0]) * rt->atom_size +
  15179. sizeof(rt->atom_hash[0]) * rt->atom_hash_size;
  15180. for(i = 0; i < rt->atom_size; i++) {
  15181. JSAtomStruct *p = rt->atom_array[i];
  15182. if (!atom_is_free(p)) {
  15183. s->atom_size += (sizeof(*p) + (p->len << p->is_wide_char) +
  15184. 1 - p->is_wide_char);
  15185. }
  15186. }
  15187. s->str_count = round(mem.str_count);
  15188. s->str_size = round(mem.str_size);
  15189. s->js_func_count = mem.js_func_count;
  15190. s->js_func_size = round(mem.js_func_size);
  15191. s->js_func_code_size = mem.js_func_code_size;
  15192. s->js_func_pc2line_count = mem.js_func_pc2line_count;
  15193. s->js_func_pc2line_size = mem.js_func_pc2line_size;
  15194. s->memory_used_count += round(mem.memory_used_count) +
  15195. s->atom_count + s->str_count +
  15196. s->obj_count + s->shape_count +
  15197. s->js_func_count + s->js_func_pc2line_count;
  15198. s->memory_used_size += s->atom_size + s->str_size +
  15199. s->obj_size + s->prop_size + s->shape_size +
  15200. s->js_func_size + s->js_func_code_size + s->js_func_pc2line_size;
  15201. }
  15202. void JS_DumpMemoryUsage(FILE *fp, const JSMemoryUsage *s, JSRuntime *rt)
  15203. {
  15204. fprintf(fp, "QuickJS-ng memory usage -- %s version, %d-bit, %s Endian, malloc limit: %"PRId64"\n\n",
  15205. JS_GetVersion(), (int)sizeof(void *) * 8, is_be() ? "Big" : "Little", s->malloc_limit);
  15206. if (rt) {
  15207. static const struct {
  15208. const char *name;
  15209. size_t size;
  15210. } object_types[] = {
  15211. { "JSRuntime", sizeof(JSRuntime) },
  15212. { "JSContext", sizeof(JSContext) },
  15213. { "JSObject", sizeof(JSObject) },
  15214. { "JSString", sizeof(JSString) },
  15215. { "JSFunctionBytecode", sizeof(JSFunctionBytecode) },
  15216. };
  15217. int i, usage_size_ok = 0;
  15218. for(i = 0; i < countof(object_types); i++) {
  15219. unsigned int size = object_types[i].size;
  15220. void *p = js_malloc_rt(rt, size);
  15221. if (p) {
  15222. unsigned int size1 = js_malloc_usable_size_rt(rt, p);
  15223. if (size1 >= size) {
  15224. usage_size_ok = 1;
  15225. fprintf(fp, " %3u + %-2u %s\n",
  15226. size, size1 - size, object_types[i].name);
  15227. }
  15228. js_free_rt(rt, p);
  15229. }
  15230. }
  15231. if (!usage_size_ok) {
  15232. fprintf(fp, " malloc_usable_size unavailable\n");
  15233. }
  15234. {
  15235. int obj_classes[JS_CLASS_INIT_COUNT + 1] = { 0 };
  15236. int class_id;
  15237. struct list_head *el;
  15238. list_for_each(el, &rt->gc_obj_list) {
  15239. JSGCObjectHeader *gp = list_entry(el, JSGCObjectHeader, link);
  15240. JSObject *p;
  15241. if (gp->gc_obj_type == JS_GC_OBJ_TYPE_JS_OBJECT) {
  15242. p = (JSObject *)gp;
  15243. obj_classes[min_uint32(p->class_id, JS_CLASS_INIT_COUNT)]++;
  15244. }
  15245. }
  15246. fprintf(fp, "\n" "JSObject classes\n");
  15247. if (obj_classes[0])
  15248. fprintf(fp, " %5d %2.0d %s\n", obj_classes[0], 0, "none");
  15249. for (class_id = 1; class_id < JS_CLASS_INIT_COUNT; class_id++) {
  15250. if (obj_classes[class_id]) {
  15251. char buf[ATOM_GET_STR_BUF_SIZE];
  15252. fprintf(fp, " %5d %2.0d %s\n", obj_classes[class_id], class_id,
  15253. JS_AtomGetStrRT(rt, buf, sizeof(buf), js_std_class_def[class_id - 1].class_name));
  15254. }
  15255. }
  15256. if (obj_classes[JS_CLASS_INIT_COUNT])
  15257. fprintf(fp, " %5d %2.0d %s\n", obj_classes[JS_CLASS_INIT_COUNT], 0, "other");
  15258. }
  15259. fprintf(fp, "\n");
  15260. }
  15261. fprintf(fp, "%-20s %8s %8s\n", "NAME", "COUNT", "SIZE");
  15262. if (s->malloc_count) {
  15263. fprintf(fp, "%-20s %8"PRId64" %8"PRId64" (%0.1f per block)\n",
  15264. "memory allocated", s->malloc_count, s->malloc_size,
  15265. (double)s->malloc_size / s->malloc_count);
  15266. fprintf(fp, "%-20s %8"PRId64" %8"PRId64" (%d overhead, %0.1f average slack)\n",
  15267. "memory used", s->memory_used_count, s->memory_used_size,
  15268. MALLOC_OVERHEAD, ((double)(s->malloc_size - s->memory_used_size) /
  15269. s->memory_used_count));
  15270. }
  15271. if (s->atom_count) {
  15272. fprintf(fp, "%-20s %8"PRId64" %8"PRId64" (%0.1f per atom)\n",
  15273. "atoms", s->atom_count, s->atom_size,
  15274. (double)s->atom_size / s->atom_count);
  15275. }
  15276. if (s->str_count) {
  15277. fprintf(fp, "%-20s %8"PRId64" %8"PRId64" (%0.1f per string)\n",
  15278. "strings", s->str_count, s->str_size,
  15279. (double)s->str_size / s->str_count);
  15280. }
  15281. if (s->obj_count) {
  15282. fprintf(fp, "%-20s %8"PRId64" %8"PRId64" (%0.1f per object)\n",
  15283. "objects", s->obj_count, s->obj_size,
  15284. (double)s->obj_size / s->obj_count);
  15285. fprintf(fp, "%-20s %8"PRId64" %8"PRId64" (%0.1f per object)\n",
  15286. " properties", s->prop_count, s->prop_size,
  15287. (double)s->prop_count / s->obj_count);
  15288. fprintf(fp, "%-20s %8"PRId64" %8"PRId64" (%0.1f per shape)\n",
  15289. " shapes", s->shape_count, s->shape_size,
  15290. (double)s->shape_size / s->shape_count);
  15291. }
  15292. if (s->js_func_count) {
  15293. fprintf(fp, "%-20s %8"PRId64" %8"PRId64"\n",
  15294. "bytecode functions", s->js_func_count, s->js_func_size);
  15295. fprintf(fp, "%-20s %8"PRId64" %8"PRId64" (%0.1f per function)\n",
  15296. " bytecode", s->js_func_count, s->js_func_code_size,
  15297. (double)s->js_func_code_size / s->js_func_count);
  15298. if (s->js_func_pc2line_count) {
  15299. fprintf(fp, "%-20s %8"PRId64" %8"PRId64" (%0.1f per function)\n",
  15300. " pc2line", s->js_func_pc2line_count,
  15301. s->js_func_pc2line_size,
  15302. (double)s->js_func_pc2line_size / s->js_func_pc2line_count);
  15303. }
  15304. }
  15305. if (s->c_func_count) {
  15306. fprintf(fp, "%-20s %8"PRId64"\n", "C functions", s->c_func_count);
  15307. }
  15308. if (s->array_count) {
  15309. fprintf(fp, "%-20s %8"PRId64"\n", "arrays", s->array_count);
  15310. if (s->fast_array_count) {
  15311. fprintf(fp, "%-20s %8"PRId64"\n", " fast arrays", s->fast_array_count);
  15312. fprintf(fp, "%-20s %8"PRId64" %8"PRId64" (%0.1f per fast array)\n",
  15313. " elements", s->fast_array_elements,
  15314. s->fast_array_elements * (int)sizeof(JSValue),
  15315. (double)s->fast_array_elements / s->fast_array_count);
  15316. }
  15317. }
  15318. if (s->binary_object_count) {
  15319. fprintf(fp, "%-20s %8"PRId64" %8"PRId64"\n",
  15320. "binary objects", s->binary_object_count, s->binary_object_size);
  15321. }
  15322. }
  15323. JSValue JS_GetGlobalObject(JSContext *ctx)
  15324. {
  15325. return js_dup(ctx->global_obj);
  15326. }
  15327. /* WARNING: obj is freed */
  15328. JSValue JS_Throw(JSContext *ctx, JSValue obj)
  15329. {
  15330. JSRuntime *rt = ctx->rt;
  15331. JS_FreeValue(ctx, rt->current_exception);
  15332. rt->current_exception = obj;
  15333. return JS_EXCEPTION;
  15334. }
  15335. /* return the pending exception (cannot be called twice). */
  15336. JSValue JS_GetException(JSContext *ctx)
  15337. {
  15338. JSValue val;
  15339. JSRuntime *rt = ctx->rt;
  15340. val = rt->current_exception;
  15341. rt->current_exception = JS_UNINITIALIZED;
  15342. return val;
  15343. }
  15344. bool JS_HasException(JSContext *ctx)
  15345. {
  15346. return !JS_IsUninitialized(ctx->rt->current_exception);
  15347. }
  15348. static void dbuf_put_leb128(DynBuf *s, uint32_t v)
  15349. {
  15350. uint32_t a;
  15351. for(;;) {
  15352. a = v & 0x7f;
  15353. v >>= 7;
  15354. if (v != 0) {
  15355. dbuf_putc(s, a | 0x80);
  15356. } else {
  15357. dbuf_putc(s, a);
  15358. break;
  15359. }
  15360. }
  15361. }
  15362. static void dbuf_put_sleb128(DynBuf *s, int32_t v1)
  15363. {
  15364. uint32_t v = v1;
  15365. dbuf_put_leb128(s, (2 * v) ^ -(v >> 31));
  15366. }
  15367. static int get_leb128(uint32_t *pval, const uint8_t *buf,
  15368. const uint8_t *buf_end)
  15369. {
  15370. const uint8_t *ptr = buf;
  15371. uint32_t v, a, i;
  15372. v = 0;
  15373. for(i = 0; i < 5; i++) {
  15374. if (unlikely(ptr >= buf_end))
  15375. break;
  15376. a = *ptr++;
  15377. v |= (a & 0x7f) << (i * 7);
  15378. if (!(a & 0x80)) {
  15379. *pval = v;
  15380. return ptr - buf;
  15381. }
  15382. }
  15383. *pval = 0;
  15384. return -1;
  15385. }
  15386. static int get_sleb128(int32_t *pval, const uint8_t *buf,
  15387. const uint8_t *buf_end)
  15388. {
  15389. int ret;
  15390. uint32_t val;
  15391. ret = get_leb128(&val, buf, buf_end);
  15392. if (ret < 0) {
  15393. *pval = 0;
  15394. return -1;
  15395. }
  15396. *pval = (val >> 1) ^ -(val & 1);
  15397. return ret;
  15398. }
  15399. static int find_line_num(JSContext *ctx, JSFunctionBytecode *b,
  15400. uint32_t pc_value, int *col)
  15401. {
  15402. const uint8_t *p_end, *p;
  15403. int new_line_num, new_col_num, line_num, col_num, pc, v, ret;
  15404. unsigned int op;
  15405. *col = 1;
  15406. p = b->pc2line_buf;
  15407. if (!p)
  15408. goto fail;
  15409. p_end = p + b->pc2line_len;
  15410. pc = 0;
  15411. line_num = b->line_num;
  15412. col_num = b->col_num;
  15413. while (p < p_end) {
  15414. op = *p++;
  15415. if (op == 0) {
  15416. uint32_t val;
  15417. ret = get_leb128(&val, p, p_end);
  15418. if (ret < 0)
  15419. goto fail;
  15420. pc += val;
  15421. p += ret;
  15422. ret = get_sleb128(&v, p, p_end);
  15423. if (ret < 0)
  15424. goto fail;
  15425. p += ret;
  15426. new_line_num = line_num + v;
  15427. } else {
  15428. op -= PC2LINE_OP_FIRST;
  15429. pc += (op / PC2LINE_RANGE);
  15430. new_line_num = line_num + (op % PC2LINE_RANGE) + PC2LINE_BASE;
  15431. }
  15432. ret = get_sleb128(&v, p, p_end);
  15433. if (ret < 0)
  15434. goto fail;
  15435. p += ret;
  15436. new_col_num = col_num + v;
  15437. if (pc_value < pc)
  15438. break;
  15439. line_num = new_line_num;
  15440. col_num = new_col_num;
  15441. }
  15442. *col = col_num;
  15443. return line_num;
  15444. fail:
  15445. /* should never happen */
  15446. return b->line_num;
  15447. }
  15448. /* in order to avoid executing arbitrary code during the stack trace
  15449. generation, we only look at simple 'name' properties containing a
  15450. string. */
  15451. static const char *get_func_name(JSContext *ctx, JSValueConst func)
  15452. {
  15453. JSProperty *pr;
  15454. JSShapeProperty *prs;
  15455. JSValue val;
  15456. if (JS_VALUE_GET_TAG(func) != JS_TAG_OBJECT)
  15457. return NULL;
  15458. prs = find_own_property(&pr, JS_VALUE_GET_OBJ(func), JS_ATOM_name);
  15459. if (!prs)
  15460. return NULL;
  15461. if ((prs->flags & JS_PROP_TMASK) != JS_PROP_NORMAL)
  15462. return NULL;
  15463. val = pr->u.value;
  15464. if (JS_VALUE_GET_TAG(val) != JS_TAG_STRING)
  15465. return NULL;
  15466. return JS_ToCString(ctx, val);
  15467. }
  15468. /* Note: it is important that no exception is returned by this function */
  15469. static bool can_add_backtrace(JSValueConst obj)
  15470. {
  15471. JSObject *p;
  15472. if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)
  15473. return false;
  15474. p = JS_VALUE_GET_OBJ(obj);
  15475. if (p->class_id != JS_CLASS_ERROR)
  15476. return false;
  15477. if (find_own_property1(p, JS_ATOM_stack))
  15478. return false;
  15479. return true;
  15480. }
  15481. #define JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL (1 << 0)
  15482. /* only taken into account if filename is provided */
  15483. #define JS_BACKTRACE_FLAG_SINGLE_LEVEL (1 << 1)
  15484. #define JS_BACKTRACE_FLAG_FILTER_FUNC (1 << 2)
  15485. /* if filename != NULL, an additional level is added with the filename
  15486. and line number information (used for parse error). */
  15487. static void build_backtrace(JSContext *ctx, JSValueConst error_val,
  15488. JSValueConst filter_func, const char *filename,
  15489. int line_num, int col_num, int backtrace_flags)
  15490. {
  15491. JSStackFrame *sf, *sf_start;
  15492. JSValue stack, prepare, saved_exception;
  15493. DynBuf dbuf;
  15494. const char *func_name_str;
  15495. const char *str1;
  15496. JSObject *p;
  15497. JSFunctionBytecode *b;
  15498. bool backtrace_barrier, has_prepare, has_filter_func;
  15499. JSRuntime *rt;
  15500. JSCallSiteData csd[64];
  15501. uint32_t i;
  15502. double d;
  15503. int stack_trace_limit;
  15504. rt = ctx->rt;
  15505. if (rt->in_build_stack_trace)
  15506. return;
  15507. rt->in_build_stack_trace = true;
  15508. // Save exception because conversion to double may fail.
  15509. saved_exception = JS_GetException(ctx);
  15510. // Extract stack trace limit.
  15511. // Ignore error since it sets d to NAN anyway.
  15512. // coverity[check_return]
  15513. JS_ToFloat64(ctx, &d, ctx->error_stack_trace_limit);
  15514. if (isnan(d) || d < 0.0)
  15515. stack_trace_limit = 0;
  15516. else if (d > INT32_MAX)
  15517. stack_trace_limit = INT32_MAX;
  15518. else
  15519. stack_trace_limit = fabs(d);
  15520. // Restore current exception.
  15521. JS_Throw(ctx, saved_exception);
  15522. saved_exception = JS_UNINITIALIZED;
  15523. stack_trace_limit = min_int(stack_trace_limit, countof(csd));
  15524. stack_trace_limit = max_int(stack_trace_limit, 0);
  15525. has_prepare = false;
  15526. has_filter_func = backtrace_flags & JS_BACKTRACE_FLAG_FILTER_FUNC;
  15527. i = 0;
  15528. if (!JS_IsNull(ctx->error_ctor)) {
  15529. prepare = js_dup(ctx->error_prepare_stack);
  15530. has_prepare = JS_IsFunction(ctx, prepare);
  15531. }
  15532. if (has_prepare) {
  15533. saved_exception = JS_GetException(ctx);
  15534. if (stack_trace_limit == 0)
  15535. goto done;
  15536. if (filename)
  15537. js_new_callsite_data2(ctx, &csd[i++], filename, line_num, col_num);
  15538. } else {
  15539. js_dbuf_init(ctx, &dbuf);
  15540. if (stack_trace_limit == 0)
  15541. goto done;
  15542. if (filename) {
  15543. i++;
  15544. dbuf_printf(&dbuf, " at %s", filename);
  15545. if (line_num != -1)
  15546. dbuf_printf(&dbuf, ":%d:%d", line_num, col_num);
  15547. dbuf_putc(&dbuf, '\n');
  15548. }
  15549. }
  15550. if (filename && (backtrace_flags & JS_BACKTRACE_FLAG_SINGLE_LEVEL))
  15551. goto done;
  15552. sf_start = rt->current_stack_frame;
  15553. /* Find the frame we want to start from. Note that when a filter is used the filter
  15554. function will be the first, but we also specify we want to skip the first one. */
  15555. if (has_filter_func) {
  15556. for (sf = sf_start; sf != NULL && i < stack_trace_limit; sf = sf->prev_frame) {
  15557. if (js_same_value(ctx, sf->cur_func, filter_func)) {
  15558. sf_start = sf;
  15559. break;
  15560. }
  15561. }
  15562. }
  15563. for (sf = sf_start; sf != NULL && i < stack_trace_limit; sf = sf->prev_frame) {
  15564. if (backtrace_flags & JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL) {
  15565. backtrace_flags &= ~JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL;
  15566. continue;
  15567. }
  15568. p = JS_VALUE_GET_OBJ(sf->cur_func);
  15569. b = NULL;
  15570. backtrace_barrier = false;
  15571. if (js_class_has_bytecode(p->class_id)) {
  15572. b = p->u.func.function_bytecode;
  15573. backtrace_barrier = b->backtrace_barrier;
  15574. }
  15575. if (has_prepare) {
  15576. js_new_callsite_data(ctx, &csd[i], sf);
  15577. } else {
  15578. /* func_name_str is UTF-8 encoded if needed */
  15579. func_name_str = get_func_name(ctx, sf->cur_func);
  15580. if (!func_name_str || func_name_str[0] == '\0')
  15581. str1 = "<anonymous>";
  15582. else
  15583. str1 = func_name_str;
  15584. dbuf_printf(&dbuf, " at %s", str1);
  15585. JS_FreeCString(ctx, func_name_str);
  15586. if (b && sf->cur_pc) {
  15587. const char *atom_str;
  15588. int line_num1, col_num1;
  15589. uint32_t pc;
  15590. pc = sf->cur_pc - b->byte_code_buf - 1;
  15591. line_num1 = find_line_num(ctx, b, pc, &col_num1);
  15592. atom_str = b->filename ? JS_AtomToCString(ctx, b->filename) : NULL;
  15593. dbuf_printf(&dbuf, " (%s", atom_str ? atom_str : "<null>");
  15594. JS_FreeCString(ctx, atom_str);
  15595. if (line_num1 != -1)
  15596. dbuf_printf(&dbuf, ":%d:%d", line_num1, col_num1);
  15597. dbuf_putc(&dbuf, ')');
  15598. } else if (b) {
  15599. // FIXME(bnoordhuis) Missing `sf->cur_pc = pc` in bytecode
  15600. // handler in JS_CallInternal. Almost never user observable
  15601. // except with intercepting JS proxies that throw exceptions.
  15602. dbuf_printf(&dbuf, " (missing)");
  15603. } else {
  15604. dbuf_printf(&dbuf, " (native)");
  15605. }
  15606. dbuf_putc(&dbuf, '\n');
  15607. }
  15608. i++;
  15609. /* stop backtrace if JS_EVAL_FLAG_BACKTRACE_BARRIER was used */
  15610. if (backtrace_barrier)
  15611. break;
  15612. }
  15613. done:
  15614. if (has_prepare) {
  15615. int j = 0, k;
  15616. stack = JS_NewArray(ctx);
  15617. if (JS_IsException(stack)) {
  15618. stack = JS_NULL;
  15619. } else {
  15620. for (; j < i; j++) {
  15621. JSValue v = js_new_callsite(ctx, &csd[j]);
  15622. if (JS_IsException(v))
  15623. break;
  15624. if (JS_DefinePropertyValueUint32(ctx, stack, j, v, JS_PROP_C_W_E) < 0) {
  15625. JS_FreeValue(ctx, v);
  15626. break;
  15627. }
  15628. }
  15629. }
  15630. // Clear the csd's we didn't use in case of error.
  15631. for (k = j; k < i; k++) {
  15632. JS_FreeValue(ctx, csd[k].filename);
  15633. JS_FreeValue(ctx, csd[k].func);
  15634. JS_FreeValue(ctx, csd[k].func_name);
  15635. }
  15636. JSValueConst args[] = {
  15637. error_val,
  15638. stack,
  15639. };
  15640. JSValue stack2 = JS_Call(ctx, prepare, ctx->error_ctor, countof(args), args);
  15641. JS_FreeValue(ctx, stack);
  15642. if (JS_IsException(stack2))
  15643. stack = JS_NULL;
  15644. else
  15645. stack = stack2;
  15646. JS_FreeValue(ctx, prepare);
  15647. JS_Throw(ctx, saved_exception);
  15648. } else {
  15649. if (dbuf_error(&dbuf))
  15650. stack = JS_NULL;
  15651. else
  15652. stack = JS_NewStringLen(ctx, (char *)dbuf.buf, dbuf.size);
  15653. dbuf_free(&dbuf);
  15654. }
  15655. if (JS_IsUndefined(ctx->error_back_trace))
  15656. ctx->error_back_trace = js_dup(stack);
  15657. if (has_filter_func || can_add_backtrace(error_val)) {
  15658. JS_DefinePropertyValue(ctx, error_val, JS_ATOM_stack, stack,
  15659. JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);
  15660. } else {
  15661. JS_FreeValue(ctx, stack);
  15662. }
  15663. rt->in_build_stack_trace = false;
  15664. }
  15665. JSValue JS_NewError(JSContext *ctx)
  15666. {
  15667. JSValue obj = JS_NewObjectClass(ctx, JS_CLASS_ERROR);
  15668. if (JS_IsException(obj))
  15669. return JS_EXCEPTION;
  15670. build_backtrace(ctx, obj, JS_UNDEFINED, NULL, 0, 0, 0);
  15671. return obj;
  15672. }
  15673. static JSValue JS_MakeError(JSContext *ctx, JSErrorEnum error_num,
  15674. const char *message, bool add_backtrace)
  15675. {
  15676. JSValue obj, msg;
  15677. if (error_num == JS_PLAIN_ERROR) {
  15678. obj = JS_NewObjectClass(ctx, JS_CLASS_ERROR);
  15679. } else {
  15680. obj = JS_NewObjectProtoClass(ctx, ctx->native_error_proto[error_num],
  15681. JS_CLASS_ERROR);
  15682. }
  15683. if (JS_IsException(obj))
  15684. return JS_EXCEPTION;
  15685. msg = JS_NewString(ctx, message);
  15686. if (JS_IsException(msg))
  15687. msg = JS_NewString(ctx, "Invalid error message");
  15688. if (!JS_IsException(msg)) {
  15689. JS_DefinePropertyValue(ctx, obj, JS_ATOM_message, msg,
  15690. JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);
  15691. }
  15692. if (add_backtrace)
  15693. build_backtrace(ctx, obj, JS_UNDEFINED, NULL, 0, 0, 0);
  15694. return obj;
  15695. }
  15696. /* fmt and arguments may be pure ASCII or UTF-8 encoded contents */
  15697. static JSValue JS_PRINTF_FORMAT_ATTR(4, 0)
  15698. JS_ThrowError2(JSContext *ctx, JSErrorEnum error_num,
  15699. bool add_backtrace, JS_PRINTF_FORMAT const char *fmt, va_list ap)
  15700. {
  15701. char buf[256];
  15702. JSValue obj;
  15703. vsnprintf(buf, sizeof(buf), fmt, ap);
  15704. obj = JS_MakeError(ctx, error_num, buf, add_backtrace);
  15705. if (unlikely(JS_IsException(obj))) {
  15706. /* out of memory: throw JS_NULL to avoid recursing */
  15707. obj = JS_NULL;
  15708. }
  15709. return JS_Throw(ctx, obj);
  15710. }
  15711. static JSValue JS_PRINTF_FORMAT_ATTR(3, 0)
  15712. JS_ThrowError(JSContext *ctx, JSErrorEnum error_num,
  15713. JS_PRINTF_FORMAT const char *fmt, va_list ap)
  15714. {
  15715. JSRuntime *rt = ctx->rt;
  15716. JSStackFrame *sf;
  15717. bool add_backtrace;
  15718. /* the backtrace is added later if called from a bytecode function */
  15719. sf = rt->current_stack_frame;
  15720. add_backtrace = !rt->in_out_of_memory &&
  15721. (!sf || (JS_GetFunctionBytecode(sf->cur_func) == NULL));
  15722. return JS_ThrowError2(ctx, error_num, add_backtrace, fmt, ap);
  15723. }
  15724. JSValue JS_PRINTF_FORMAT_ATTR(2, 3) JS_ThrowPlainError(JSContext *ctx, JS_PRINTF_FORMAT const char *fmt, ...)
  15725. {
  15726. JSValue val;
  15727. va_list ap;
  15728. va_start(ap, fmt);
  15729. val = JS_ThrowError(ctx, JS_PLAIN_ERROR, fmt, ap);
  15730. va_end(ap);
  15731. return val;
  15732. }
  15733. JSValue JS_PRINTF_FORMAT_ATTR(2, 3) JS_ThrowSyntaxError(JSContext *ctx, JS_PRINTF_FORMAT const char *fmt, ...)
  15734. {
  15735. JSValue val;
  15736. va_list ap;
  15737. va_start(ap, fmt);
  15738. val = JS_ThrowError(ctx, JS_SYNTAX_ERROR, fmt, ap);
  15739. va_end(ap);
  15740. return val;
  15741. }
  15742. JSValue JS_PRINTF_FORMAT_ATTR(2, 3) JS_ThrowTypeError(JSContext *ctx, JS_PRINTF_FORMAT const char *fmt, ...)
  15743. {
  15744. JSValue val;
  15745. va_list ap;
  15746. va_start(ap, fmt);
  15747. val = JS_ThrowError(ctx, JS_TYPE_ERROR, fmt, ap);
  15748. va_end(ap);
  15749. return val;
  15750. }
  15751. static int JS_PRINTF_FORMAT_ATTR(3, 4) JS_ThrowTypeErrorOrFalse(JSContext *ctx, int flags, JS_PRINTF_FORMAT const char *fmt, ...)
  15752. {
  15753. va_list ap;
  15754. if ((flags & JS_PROP_THROW) ||
  15755. ((flags & JS_PROP_THROW_STRICT) && is_strict_mode(ctx))) {
  15756. va_start(ap, fmt);
  15757. JS_ThrowError(ctx, JS_TYPE_ERROR, fmt, ap);
  15758. va_end(ap);
  15759. return -1;
  15760. } else {
  15761. return false;
  15762. }
  15763. }
  15764. #ifdef __GNUC__
  15765. #pragma GCC diagnostic push
  15766. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  15767. #endif // __GNUC__
  15768. static JSValue JS_ThrowTypeErrorAtom(JSContext *ctx, const char *fmt, JSAtom atom)
  15769. {
  15770. char buf[ATOM_GET_STR_BUF_SIZE];
  15771. JS_AtomGetStr(ctx, buf, sizeof(buf), atom);
  15772. return JS_ThrowTypeError(ctx, fmt, buf);
  15773. }
  15774. static JSValue JS_ThrowSyntaxErrorAtom(JSContext *ctx, const char *fmt, JSAtom atom)
  15775. {
  15776. char buf[ATOM_GET_STR_BUF_SIZE];
  15777. JS_AtomGetStr(ctx, buf, sizeof(buf), atom);
  15778. return JS_ThrowSyntaxError(ctx, fmt, buf);
  15779. }
  15780. #ifdef __GNUC__
  15781. #pragma GCC diagnostic pop // ignored "-Wformat-nonliteral"
  15782. #endif // __GNUC__
  15783. static int JS_ThrowTypeErrorReadOnly(JSContext *ctx, int flags, JSAtom atom)
  15784. {
  15785. if ((flags & JS_PROP_THROW) ||
  15786. ((flags & JS_PROP_THROW_STRICT) && is_strict_mode(ctx))) {
  15787. JS_ThrowTypeErrorAtom(ctx, "'%s' is read-only", atom);
  15788. return -1;
  15789. } else {
  15790. return false;
  15791. }
  15792. }
  15793. JSValue JS_PRINTF_FORMAT_ATTR(2, 3) JS_ThrowReferenceError(JSContext *ctx, JS_PRINTF_FORMAT const char *fmt, ...)
  15794. {
  15795. JSValue val;
  15796. va_list ap;
  15797. va_start(ap, fmt);
  15798. val = JS_ThrowError(ctx, JS_REFERENCE_ERROR, fmt, ap);
  15799. va_end(ap);
  15800. return val;
  15801. }
  15802. JSValue JS_PRINTF_FORMAT_ATTR(2, 3) JS_ThrowRangeError(JSContext *ctx, JS_PRINTF_FORMAT const char *fmt, ...)
  15803. {
  15804. JSValue val;
  15805. va_list ap;
  15806. va_start(ap, fmt);
  15807. val = JS_ThrowError(ctx, JS_RANGE_ERROR, fmt, ap);
  15808. va_end(ap);
  15809. return val;
  15810. }
  15811. JSValue JS_PRINTF_FORMAT_ATTR(2, 3) JS_ThrowInternalError(JSContext *ctx, JS_PRINTF_FORMAT const char *fmt, ...)
  15812. {
  15813. JSValue val;
  15814. va_list ap;
  15815. va_start(ap, fmt);
  15816. val = JS_ThrowError(ctx, JS_INTERNAL_ERROR, fmt, ap);
  15817. va_end(ap);
  15818. return val;
  15819. }
  15820. JSValue JS_ThrowOutOfMemory(JSContext *ctx)
  15821. {
  15822. JSRuntime *rt = ctx->rt;
  15823. if (!rt->in_out_of_memory) {
  15824. rt->in_out_of_memory = true;
  15825. JS_ThrowInternalError(ctx, "out of memory");
  15826. rt->in_out_of_memory = false;
  15827. }
  15828. return JS_EXCEPTION;
  15829. }
  15830. static JSValue JS_ThrowStackOverflow(JSContext *ctx)
  15831. {
  15832. return JS_ThrowRangeError(ctx, "Maximum call stack size exceeded");
  15833. }
  15834. static JSValue JS_ThrowTypeErrorNotAFunction(JSContext *ctx)
  15835. {
  15836. return JS_ThrowTypeError(ctx, "not a function");
  15837. }
  15838. static JSValue JS_ThrowTypeErrorNotAnObject(JSContext *ctx)
  15839. {
  15840. return JS_ThrowTypeError(ctx, "not an object");
  15841. }
  15842. static JSValue JS_ThrowTypeErrorNotASymbol(JSContext *ctx)
  15843. {
  15844. return JS_ThrowTypeError(ctx, "not a symbol");
  15845. }
  15846. static JSValue JS_ThrowReferenceErrorNotDefined(JSContext *ctx, JSAtom name)
  15847. {
  15848. char buf[ATOM_GET_STR_BUF_SIZE];
  15849. return JS_ThrowReferenceError(ctx, "%s is not defined",
  15850. JS_AtomGetStr(ctx, buf, sizeof(buf), name));
  15851. }
  15852. static JSValue JS_ThrowReferenceErrorUninitialized(JSContext *ctx, JSAtom name)
  15853. {
  15854. char buf[ATOM_GET_STR_BUF_SIZE];
  15855. return JS_ThrowReferenceError(ctx, "%s is not initialized",
  15856. name == JS_ATOM_NULL ? "lexical variable" :
  15857. JS_AtomGetStr(ctx, buf, sizeof(buf), name));
  15858. }
  15859. static JSValue JS_ThrowReferenceErrorUninitialized2(JSContext *ctx,
  15860. JSFunctionBytecode *b,
  15861. int idx, bool is_ref)
  15862. {
  15863. JSAtom atom = JS_ATOM_NULL;
  15864. if (is_ref) {
  15865. atom = b->closure_var[idx].var_name;
  15866. } else {
  15867. /* not present if the function is stripped and contains no eval() */
  15868. if (b->vardefs)
  15869. atom = b->vardefs[b->arg_count + idx].var_name;
  15870. }
  15871. return JS_ThrowReferenceErrorUninitialized(ctx, atom);
  15872. }
  15873. static JSValue JS_ThrowTypeErrorInvalidClass(JSContext *ctx, int class_id)
  15874. {
  15875. JSRuntime *rt = ctx->rt;
  15876. JSAtom name;
  15877. name = rt->class_array[class_id].class_name;
  15878. return JS_ThrowTypeErrorAtom(ctx, "%s object expected", name);
  15879. }
  15880. static no_inline __exception int __js_poll_interrupts(JSContext *ctx)
  15881. {
  15882. JSRuntime *rt = ctx->rt;
  15883. ctx->interrupt_counter = JS_INTERRUPT_COUNTER_INIT;
  15884. if (rt->interrupt_handler) {
  15885. if (rt->interrupt_handler(rt, rt->interrupt_opaque)) {
  15886. /* XXX: should set a specific flag to avoid catching */
  15887. JS_ThrowInternalError(ctx, "interrupted");
  15888. js_set_uncatchable_error(ctx, ctx->rt->current_exception, true);
  15889. return -1;
  15890. }
  15891. }
  15892. return 0;
  15893. }
  15894. static inline __exception int js_poll_interrupts(JSContext *ctx)
  15895. {
  15896. if (unlikely(--ctx->interrupt_counter <= 0)) {
  15897. return __js_poll_interrupts(ctx);
  15898. } else {
  15899. return 0;
  15900. }
  15901. }
  15902. /* return -1 (exception) or true/false */
  15903. static int JS_SetPrototypeInternal(JSContext *ctx, JSValueConst obj,
  15904. JSValueConst proto_val, bool throw_flag)
  15905. {
  15906. JSObject *proto, *p, *p1;
  15907. JSShape *sh;
  15908. if (throw_flag) {
  15909. if (JS_VALUE_GET_TAG(obj) == JS_TAG_NULL ||
  15910. JS_VALUE_GET_TAG(obj) == JS_TAG_UNDEFINED)
  15911. goto not_obj;
  15912. } else {
  15913. if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)
  15914. goto not_obj;
  15915. }
  15916. p = JS_VALUE_GET_OBJ(obj);
  15917. if (JS_VALUE_GET_TAG(proto_val) != JS_TAG_OBJECT) {
  15918. if (JS_VALUE_GET_TAG(proto_val) != JS_TAG_NULL) {
  15919. not_obj:
  15920. JS_ThrowTypeErrorNotAnObject(ctx);
  15921. return -1;
  15922. }
  15923. proto = NULL;
  15924. } else {
  15925. proto = JS_VALUE_GET_OBJ(proto_val);
  15926. }
  15927. if (throw_flag && JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)
  15928. return true;
  15929. if (unlikely(p->class_id == JS_CLASS_PROXY))
  15930. return js_proxy_setPrototypeOf(ctx, obj, proto_val, throw_flag);
  15931. sh = p->shape;
  15932. if (sh->proto == proto)
  15933. return true;
  15934. if (p == JS_VALUE_GET_OBJ(ctx->class_proto[JS_CLASS_OBJECT])) {
  15935. if (throw_flag) {
  15936. JS_ThrowTypeError(ctx, "'Immutable prototype object \'Object.prototype\' cannot have their prototype set'");
  15937. return -1;
  15938. }
  15939. return false;
  15940. }
  15941. if (!p->extensible) {
  15942. if (throw_flag) {
  15943. JS_ThrowTypeError(ctx, "object is not extensible");
  15944. return -1;
  15945. } else {
  15946. return false;
  15947. }
  15948. }
  15949. if (proto) {
  15950. /* check if there is a cycle */
  15951. p1 = proto;
  15952. do {
  15953. if (p1 == p) {
  15954. if (throw_flag) {
  15955. JS_ThrowTypeError(ctx, "circular prototype chain");
  15956. return -1;
  15957. } else {
  15958. return false;
  15959. }
  15960. }
  15961. /* Note: for Proxy objects, proto is NULL */
  15962. p1 = p1->shape->proto;
  15963. } while (p1 != NULL);
  15964. js_dup(proto_val);
  15965. }
  15966. if (js_shape_prepare_update(ctx, p, NULL))
  15967. return -1;
  15968. sh = p->shape;
  15969. if (sh->proto)
  15970. JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, sh->proto));
  15971. sh->proto = proto;
  15972. return true;
  15973. }
  15974. /* return -1 (exception) or true/false */
  15975. int JS_SetPrototype(JSContext *ctx, JSValueConst obj, JSValue proto_val)
  15976. {
  15977. return JS_SetPrototypeInternal(ctx, obj, proto_val, true);
  15978. }
  15979. /* Only works for primitive types, otherwise return JS_NULL. */
  15980. static JSValueConst JS_GetPrototypePrimitive(JSContext *ctx, JSValueConst val)
  15981. {
  15982. JSValue ret;
  15983. switch(JS_VALUE_GET_NORM_TAG(val)) {
  15984. case JS_TAG_BIG_INT:
  15985. ret = ctx->class_proto[JS_CLASS_BIG_INT];
  15986. break;
  15987. case JS_TAG_INT:
  15988. case JS_TAG_FLOAT64:
  15989. ret = ctx->class_proto[JS_CLASS_NUMBER];
  15990. break;
  15991. case JS_TAG_BOOL:
  15992. ret = ctx->class_proto[JS_CLASS_BOOLEAN];
  15993. break;
  15994. case JS_TAG_STRING:
  15995. ret = ctx->class_proto[JS_CLASS_STRING];
  15996. break;
  15997. case JS_TAG_SYMBOL:
  15998. ret = ctx->class_proto[JS_CLASS_SYMBOL];
  15999. break;
  16000. case JS_TAG_OBJECT:
  16001. case JS_TAG_NULL:
  16002. case JS_TAG_UNDEFINED:
  16003. default:
  16004. ret = JS_NULL;
  16005. break;
  16006. }
  16007. return ret;
  16008. }
  16009. /* Return an Object, JS_NULL or JS_EXCEPTION in case of Proxy object. */
  16010. JSValue JS_GetPrototype(JSContext *ctx, JSValueConst obj)
  16011. {
  16012. JSValue val;
  16013. if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) {
  16014. JSObject *p;
  16015. p = JS_VALUE_GET_OBJ(obj);
  16016. if (unlikely(p->class_id == JS_CLASS_PROXY)) {
  16017. val = js_proxy_getPrototypeOf(ctx, obj);
  16018. } else {
  16019. p = p->shape->proto;
  16020. if (!p)
  16021. val = JS_NULL;
  16022. else
  16023. val = js_dup(JS_MKPTR(JS_TAG_OBJECT, p));
  16024. }
  16025. } else {
  16026. val = js_dup(JS_GetPrototypePrimitive(ctx, obj));
  16027. }
  16028. return val;
  16029. }
  16030. static JSValue JS_GetPrototypeFree(JSContext *ctx, JSValue obj)
  16031. {
  16032. JSValue obj1;
  16033. obj1 = JS_GetPrototype(ctx, obj);
  16034. JS_FreeValue(ctx, obj);
  16035. return obj1;
  16036. }
  16037. int JS_GetLength(JSContext *ctx, JSValueConst obj, int64_t *pres) {
  16038. return js_get_length64(ctx, pres, obj);
  16039. }
  16040. int JS_SetLength(JSContext *ctx, JSValueConst obj, int64_t len) {
  16041. return js_set_length64(ctx, obj, len);
  16042. }
  16043. /* return true, false or (-1) in case of exception */
  16044. static int JS_OrdinaryIsInstanceOf(JSContext *ctx, JSValueConst val,
  16045. JSValueConst obj)
  16046. {
  16047. JSValue obj_proto;
  16048. JSObject *proto;
  16049. const JSObject *p, *proto1;
  16050. int ret;
  16051. if (!JS_IsFunction(ctx, obj))
  16052. return false;
  16053. p = JS_VALUE_GET_OBJ(obj);
  16054. if (p->class_id == JS_CLASS_BOUND_FUNCTION) {
  16055. JSBoundFunction *s = p->u.bound_function;
  16056. return JS_IsInstanceOf(ctx, val, s->func_obj);
  16057. }
  16058. /* Only explicitly boxed values are instances of constructors */
  16059. if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT)
  16060. return false;
  16061. obj_proto = JS_GetProperty(ctx, obj, JS_ATOM_prototype);
  16062. if (JS_VALUE_GET_TAG(obj_proto) != JS_TAG_OBJECT) {
  16063. if (!JS_IsException(obj_proto))
  16064. JS_ThrowTypeError(ctx, "operand 'prototype' property is not an object");
  16065. ret = -1;
  16066. goto done;
  16067. }
  16068. proto = JS_VALUE_GET_OBJ(obj_proto);
  16069. p = JS_VALUE_GET_OBJ(val);
  16070. for(;;) {
  16071. proto1 = p->shape->proto;
  16072. if (!proto1) {
  16073. /* slow case if proxy in the prototype chain */
  16074. if (unlikely(p->class_id == JS_CLASS_PROXY)) {
  16075. JSValue obj1;
  16076. obj1 = js_dup(JS_MKPTR(JS_TAG_OBJECT, (JSObject *)p));
  16077. for(;;) {
  16078. obj1 = JS_GetPrototypeFree(ctx, obj1);
  16079. if (JS_IsException(obj1)) {
  16080. ret = -1;
  16081. break;
  16082. }
  16083. if (JS_IsNull(obj1)) {
  16084. ret = false;
  16085. break;
  16086. }
  16087. if (proto == JS_VALUE_GET_OBJ(obj1)) {
  16088. JS_FreeValue(ctx, obj1);
  16089. ret = true;
  16090. break;
  16091. }
  16092. /* must check for timeout to avoid infinite loop */
  16093. if (js_poll_interrupts(ctx)) {
  16094. JS_FreeValue(ctx, obj1);
  16095. ret = -1;
  16096. break;
  16097. }
  16098. }
  16099. } else {
  16100. ret = false;
  16101. }
  16102. break;
  16103. }
  16104. p = proto1;
  16105. if (proto == p) {
  16106. ret = true;
  16107. break;
  16108. }
  16109. }
  16110. done:
  16111. JS_FreeValue(ctx, obj_proto);
  16112. return ret;
  16113. }
  16114. /* return true, false or (-1) in case of exception */
  16115. int JS_IsInstanceOf(JSContext *ctx, JSValueConst val, JSValueConst obj)
  16116. {
  16117. JSValue method;
  16118. if (!JS_IsObject(obj))
  16119. goto fail;
  16120. method = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_hasInstance);
  16121. if (JS_IsException(method))
  16122. return -1;
  16123. if (!JS_IsNull(method) && !JS_IsUndefined(method)) {
  16124. JSValue ret;
  16125. ret = JS_CallFree(ctx, method, obj, 1, &val);
  16126. return JS_ToBoolFree(ctx, ret);
  16127. }
  16128. /* legacy case */
  16129. if (!JS_IsFunction(ctx, obj)) {
  16130. fail:
  16131. JS_ThrowTypeError(ctx, "invalid 'instanceof' right operand");
  16132. return -1;
  16133. }
  16134. return JS_OrdinaryIsInstanceOf(ctx, val, obj);
  16135. }
  16136. /* return the value associated to the autoinit property or an exception */
  16137. typedef JSValue JSAutoInitFunc(JSContext *ctx, JSObject *p, JSAtom atom, void *opaque);
  16138. static JSAutoInitFunc *js_autoinit_func_table[] = {
  16139. js_instantiate_prototype, /* JS_AUTOINIT_ID_PROTOTYPE */
  16140. js_module_ns_autoinit, /* JS_AUTOINIT_ID_MODULE_NS */
  16141. JS_InstantiateFunctionListItem2, /* JS_AUTOINIT_ID_PROP */
  16142. };
  16143. /* warning: 'prs' is reallocated after it */
  16144. static int JS_AutoInitProperty(JSContext *ctx, JSObject *p, JSAtom prop,
  16145. JSProperty *pr, JSShapeProperty *prs)
  16146. {
  16147. JSValue val;
  16148. JSContext *realm;
  16149. JSAutoInitFunc *func;
  16150. if (js_shape_prepare_update(ctx, p, &prs))
  16151. return -1;
  16152. realm = js_autoinit_get_realm(pr);
  16153. func = js_autoinit_func_table[js_autoinit_get_id(pr)];
  16154. /* 'func' shall not modify the object properties 'pr' */
  16155. val = func(realm, p, prop, pr->u.init.opaque);
  16156. js_autoinit_free(ctx->rt, pr);
  16157. prs->flags &= ~JS_PROP_TMASK;
  16158. pr->u.value = JS_UNDEFINED;
  16159. if (JS_IsException(val))
  16160. return -1;
  16161. pr->u.value = val;
  16162. return 0;
  16163. }
  16164. static JSValue JS_GetPropertyInternal(JSContext *ctx, JSValueConst obj,
  16165. JSAtom prop, JSValueConst this_obj,
  16166. bool throw_ref_error)
  16167. {
  16168. JSObject *p;
  16169. JSProperty *pr;
  16170. JSShapeProperty *prs;
  16171. uint32_t tag, proto_depth;
  16172. proto_depth = 0;
  16173. tag = JS_VALUE_GET_TAG(obj);
  16174. if (unlikely(tag != JS_TAG_OBJECT)) {
  16175. switch(tag) {
  16176. case JS_TAG_NULL:
  16177. return JS_ThrowTypeErrorAtom(ctx, "cannot read property '%s' of null", prop);
  16178. case JS_TAG_UNDEFINED:
  16179. return JS_ThrowTypeErrorAtom(ctx, "cannot read property '%s' of undefined", prop);
  16180. case JS_TAG_EXCEPTION:
  16181. return JS_EXCEPTION;
  16182. case JS_TAG_STRING:
  16183. {
  16184. JSString *p1 = JS_VALUE_GET_STRING(obj);
  16185. if (__JS_AtomIsTaggedInt(prop)) {
  16186. uint32_t idx, ch;
  16187. idx = __JS_AtomToUInt32(prop);
  16188. if (idx < p1->len) {
  16189. ch = string_get(p1, idx);
  16190. return js_new_string_char(ctx, ch);
  16191. }
  16192. } else if (prop == JS_ATOM_length) {
  16193. return js_int32(p1->len);
  16194. }
  16195. }
  16196. break;
  16197. default:
  16198. break;
  16199. }
  16200. /* cannot raise an exception */
  16201. p = JS_VALUE_GET_OBJ(JS_GetPrototypePrimitive(ctx, obj));
  16202. if (!p)
  16203. return JS_UNDEFINED;
  16204. } else {
  16205. p = JS_VALUE_GET_OBJ(obj);
  16206. }
  16207. for(;;) {
  16208. prs = find_own_property(&pr, p, prop);
  16209. if (prs) {
  16210. /* found */
  16211. if (unlikely(prs->flags & JS_PROP_TMASK)) {
  16212. if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) {
  16213. if (unlikely(!pr->u.getset.getter)) {
  16214. return JS_UNDEFINED;
  16215. } else {
  16216. JSValue func = JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.getter);
  16217. /* Note: the field could be removed in the getter */
  16218. func = js_dup(func);
  16219. return JS_CallFree(ctx, func, this_obj, 0, NULL);
  16220. }
  16221. } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) {
  16222. JSValue val = *pr->u.var_ref->pvalue;
  16223. if (unlikely(JS_IsUninitialized(val)))
  16224. return JS_ThrowReferenceErrorUninitialized(ctx, prs->atom);
  16225. return js_dup(val);
  16226. } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) {
  16227. /* Instantiate property and retry */
  16228. if (JS_AutoInitProperty(ctx, p, prop, pr, prs))
  16229. return JS_EXCEPTION;
  16230. continue;
  16231. }
  16232. } else {
  16233. return js_dup(pr->u.value);
  16234. }
  16235. }
  16236. if (unlikely(p->is_exotic)) {
  16237. /* exotic behaviors */
  16238. if (p->fast_array) {
  16239. if (__JS_AtomIsTaggedInt(prop)) {
  16240. uint32_t idx = __JS_AtomToUInt32(prop);
  16241. if (idx < p->u.array.count) {
  16242. /* we avoid duplicating the code */
  16243. return JS_GetPropertyUint32(ctx, JS_MKPTR(JS_TAG_OBJECT, p), idx);
  16244. } else if (is_typed_array(p->class_id)) {
  16245. return JS_UNDEFINED;
  16246. }
  16247. } else if (is_typed_array(p->class_id)) {
  16248. int ret;
  16249. ret = JS_AtomIsNumericIndex(ctx, prop);
  16250. if (ret != 0) {
  16251. if (ret < 0)
  16252. return JS_EXCEPTION;
  16253. return JS_UNDEFINED;
  16254. }
  16255. }
  16256. } else {
  16257. const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic;
  16258. if (em) {
  16259. if (em->get_property) {
  16260. JSValue obj1, retval;
  16261. /* XXX: should pass throw_ref_error */
  16262. /* Note: if 'p' is a prototype, it can be
  16263. freed in the called function */
  16264. obj1 = js_dup(JS_MKPTR(JS_TAG_OBJECT, p));
  16265. retval = em->get_property(ctx, obj1, prop, this_obj);
  16266. JS_FreeValue(ctx, obj1);
  16267. return retval;
  16268. }
  16269. if (em->get_own_property) {
  16270. JSPropertyDescriptor desc;
  16271. int ret;
  16272. JSValue obj1;
  16273. /* Note: if 'p' is a prototype, it can be
  16274. freed in the called function */
  16275. obj1 = js_dup(JS_MKPTR(JS_TAG_OBJECT, p));
  16276. ret = em->get_own_property(ctx, &desc, obj1, prop);
  16277. JS_FreeValue(ctx, obj1);
  16278. if (ret < 0)
  16279. return JS_EXCEPTION;
  16280. if (ret) {
  16281. if (desc.flags & JS_PROP_GETSET) {
  16282. JS_FreeValue(ctx, desc.setter);
  16283. return JS_CallFree(ctx, desc.getter, this_obj, 0, NULL);
  16284. } else {
  16285. return desc.value;
  16286. }
  16287. }
  16288. }
  16289. }
  16290. }
  16291. }
  16292. proto_depth++;
  16293. p = p->shape->proto;
  16294. if (!p)
  16295. break;
  16296. }
  16297. if (unlikely(throw_ref_error)) {
  16298. return JS_ThrowReferenceErrorNotDefined(ctx, prop);
  16299. } else {
  16300. return JS_UNDEFINED;
  16301. }
  16302. }
  16303. JSValue JS_GetProperty(JSContext *ctx, JSValueConst this_obj, JSAtom prop)
  16304. {
  16305. return JS_GetPropertyInternal(ctx, this_obj, prop, this_obj, false);
  16306. }
  16307. static JSValue JS_ThrowTypeErrorPrivateNotFound(JSContext *ctx, JSAtom atom)
  16308. {
  16309. return JS_ThrowTypeErrorAtom(ctx, "private class field '%s' does not exist",
  16310. atom);
  16311. }
  16312. /* Private fields can be added even on non extensible objects or
  16313. Proxies */
  16314. static int JS_DefinePrivateField(JSContext *ctx, JSValueConst obj,
  16315. JSValue name, JSValue val)
  16316. {
  16317. JSObject *p;
  16318. JSShapeProperty *prs;
  16319. JSProperty *pr;
  16320. JSAtom prop;
  16321. if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)) {
  16322. JS_ThrowTypeErrorNotAnObject(ctx);
  16323. goto fail;
  16324. }
  16325. /* safety check */
  16326. if (unlikely(JS_VALUE_GET_TAG(name) != JS_TAG_SYMBOL)) {
  16327. JS_ThrowTypeErrorNotASymbol(ctx);
  16328. goto fail;
  16329. }
  16330. prop = js_symbol_to_atom(ctx, name);
  16331. p = JS_VALUE_GET_OBJ(obj);
  16332. prs = find_own_property(&pr, p, prop);
  16333. if (prs) {
  16334. JS_ThrowTypeErrorAtom(ctx, "private class field '%s' already exists",
  16335. prop);
  16336. goto fail;
  16337. }
  16338. pr = add_property(ctx, p, prop, JS_PROP_C_W_E);
  16339. if (unlikely(!pr)) {
  16340. fail:
  16341. JS_FreeValue(ctx, val);
  16342. return -1;
  16343. }
  16344. pr->u.value = val;
  16345. return 0;
  16346. }
  16347. static JSValue JS_GetPrivateField(JSContext *ctx, JSValueConst obj,
  16348. JSValueConst name)
  16349. {
  16350. JSObject *p;
  16351. JSShapeProperty *prs;
  16352. JSProperty *pr;
  16353. JSAtom prop;
  16354. if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT))
  16355. return JS_ThrowTypeErrorNotAnObject(ctx);
  16356. /* safety check */
  16357. if (unlikely(JS_VALUE_GET_TAG(name) != JS_TAG_SYMBOL))
  16358. return JS_ThrowTypeErrorNotASymbol(ctx);
  16359. prop = js_symbol_to_atom(ctx, name);
  16360. p = JS_VALUE_GET_OBJ(obj);
  16361. prs = find_own_property(&pr, p, prop);
  16362. if (!prs) {
  16363. JS_ThrowTypeErrorPrivateNotFound(ctx, prop);
  16364. return JS_EXCEPTION;
  16365. }
  16366. return js_dup(pr->u.value);
  16367. }
  16368. static int JS_SetPrivateField(JSContext *ctx, JSValueConst obj,
  16369. JSValueConst name, JSValue val)
  16370. {
  16371. JSObject *p;
  16372. JSShapeProperty *prs;
  16373. JSProperty *pr;
  16374. JSAtom prop;
  16375. if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)) {
  16376. JS_ThrowTypeErrorNotAnObject(ctx);
  16377. goto fail;
  16378. }
  16379. /* safety check */
  16380. if (unlikely(JS_VALUE_GET_TAG(name) != JS_TAG_SYMBOL)) {
  16381. JS_ThrowTypeErrorNotASymbol(ctx);
  16382. goto fail;
  16383. }
  16384. prop = js_symbol_to_atom(ctx, name);
  16385. p = JS_VALUE_GET_OBJ(obj);
  16386. prs = find_own_property(&pr, p, prop);
  16387. if (!prs) {
  16388. JS_ThrowTypeErrorPrivateNotFound(ctx, prop);
  16389. fail:
  16390. JS_FreeValue(ctx, val);
  16391. return -1;
  16392. }
  16393. set_value(ctx, &pr->u.value, val);
  16394. return 0;
  16395. }
  16396. /* add a private brand field to 'home_obj' if not already present and
  16397. if obj is != null add a private brand to it */
  16398. static int JS_AddBrand(JSContext *ctx, JSValueConst obj, JSValueConst home_obj)
  16399. {
  16400. JSObject *p, *p1;
  16401. JSShapeProperty *prs;
  16402. JSProperty *pr;
  16403. JSValue brand;
  16404. JSAtom brand_atom;
  16405. if (unlikely(JS_VALUE_GET_TAG(home_obj) != JS_TAG_OBJECT)) {
  16406. JS_ThrowTypeErrorNotAnObject(ctx);
  16407. return -1;
  16408. }
  16409. p = JS_VALUE_GET_OBJ(home_obj);
  16410. prs = find_own_property(&pr, p, JS_ATOM_Private_brand);
  16411. if (!prs) {
  16412. /* if the brand is not present, add it */
  16413. brand = JS_NewSymbolFromAtom(ctx, JS_ATOM_brand, JS_ATOM_TYPE_PRIVATE);
  16414. if (JS_IsException(brand))
  16415. return -1;
  16416. pr = add_property(ctx, p, JS_ATOM_Private_brand, JS_PROP_C_W_E);
  16417. if (!pr) {
  16418. JS_FreeValue(ctx, brand);
  16419. return -1;
  16420. }
  16421. pr->u.value = js_dup(brand);
  16422. } else {
  16423. brand = js_dup(pr->u.value);
  16424. }
  16425. brand_atom = js_symbol_to_atom(ctx, brand);
  16426. if (JS_IsObject(obj)) {
  16427. p1 = JS_VALUE_GET_OBJ(obj);
  16428. prs = find_own_property(&pr, p1, brand_atom);
  16429. if (unlikely(prs)) {
  16430. JS_FreeAtom(ctx, brand_atom);
  16431. JS_ThrowTypeError(ctx, "private method is already present");
  16432. return -1;
  16433. }
  16434. pr = add_property(ctx, p1, brand_atom, JS_PROP_C_W_E);
  16435. JS_FreeAtom(ctx, brand_atom);
  16436. if (!pr)
  16437. return -1;
  16438. pr->u.value = JS_UNDEFINED;
  16439. } else {
  16440. JS_FreeAtom(ctx, brand_atom);
  16441. }
  16442. return 0;
  16443. }
  16444. /* return a boolean telling if the brand of the home object of 'func'
  16445. is present on 'obj' or -1 in case of exception */
  16446. static int JS_CheckBrand(JSContext *ctx, JSValue obj, JSValue func)
  16447. {
  16448. JSObject *p, *p1, *home_obj;
  16449. JSShapeProperty *prs;
  16450. JSProperty *pr;
  16451. JSValue brand;
  16452. /* get the home object of 'func' */
  16453. if (unlikely(JS_VALUE_GET_TAG(func) != JS_TAG_OBJECT))
  16454. goto not_obj;
  16455. p1 = JS_VALUE_GET_OBJ(func);
  16456. if (!js_class_has_bytecode(p1->class_id))
  16457. goto not_obj;
  16458. home_obj = p1->u.func.home_object;
  16459. if (!home_obj)
  16460. goto not_obj;
  16461. prs = find_own_property(&pr, home_obj, JS_ATOM_Private_brand);
  16462. if (!prs) {
  16463. JS_ThrowTypeError(ctx, "expecting <brand> private field");
  16464. return -1;
  16465. }
  16466. brand = pr->u.value;
  16467. /* safety check */
  16468. if (unlikely(JS_VALUE_GET_TAG(brand) != JS_TAG_SYMBOL))
  16469. goto not_obj;
  16470. /* get the brand array of 'obj' */
  16471. if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)) {
  16472. not_obj:
  16473. JS_ThrowTypeErrorNotAnObject(ctx);
  16474. return -1;
  16475. }
  16476. p = JS_VALUE_GET_OBJ(obj);
  16477. prs = find_own_property(&pr, p, js_symbol_to_atom(ctx, brand));
  16478. return (prs != NULL);
  16479. }
  16480. static uint32_t js_string_obj_get_length(JSContext *ctx, JSValueConst obj)
  16481. {
  16482. JSObject *p;
  16483. JSString *p1;
  16484. uint32_t len = 0;
  16485. /* This is a class exotic method: obj class_id is JS_CLASS_STRING */
  16486. p = JS_VALUE_GET_OBJ(obj);
  16487. if (JS_VALUE_GET_TAG(p->u.object_data) == JS_TAG_STRING) {
  16488. p1 = JS_VALUE_GET_STRING(p->u.object_data);
  16489. len = p1->len;
  16490. }
  16491. return len;
  16492. }
  16493. static int num_keys_cmp(const void *p1, const void *p2, void *opaque)
  16494. {
  16495. JSContext *ctx = opaque;
  16496. JSAtom atom1 = ((const JSPropertyEnum *)p1)->atom;
  16497. JSAtom atom2 = ((const JSPropertyEnum *)p2)->atom;
  16498. uint32_t v1, v2;
  16499. bool atom1_is_integer, atom2_is_integer;
  16500. atom1_is_integer = JS_AtomIsArrayIndex(ctx, &v1, atom1);
  16501. atom2_is_integer = JS_AtomIsArrayIndex(ctx, &v2, atom2);
  16502. assert(atom1_is_integer && atom2_is_integer);
  16503. if (v1 < v2)
  16504. return -1;
  16505. else if (v1 == v2)
  16506. return 0;
  16507. else
  16508. return 1;
  16509. }
  16510. static void js_free_prop_enum(JSContext *ctx, JSPropertyEnum *tab, uint32_t len)
  16511. {
  16512. uint32_t i;
  16513. if (tab) {
  16514. for(i = 0; i < len; i++)
  16515. JS_FreeAtom(ctx, tab[i].atom);
  16516. js_free(ctx, tab);
  16517. }
  16518. }
  16519. /* return < 0 in case if exception, 0 if OK. ptab and its atoms must
  16520. be freed by the user. */
  16521. static int __exception JS_GetOwnPropertyNamesInternal(JSContext *ctx,
  16522. JSPropertyEnum **ptab,
  16523. uint32_t *plen,
  16524. JSObject *p, int flags)
  16525. {
  16526. int i, j;
  16527. JSShape *sh;
  16528. JSShapeProperty *prs;
  16529. JSPropertyEnum *tab_atom, *tab_exotic;
  16530. JSAtom atom;
  16531. uint32_t num_keys_count, str_keys_count, sym_keys_count, atom_count;
  16532. uint32_t num_index, str_index, sym_index, exotic_count, exotic_keys_count;
  16533. bool is_enumerable, num_sorted;
  16534. uint32_t num_key;
  16535. JSAtomKindEnum kind;
  16536. /* clear pointer for consistency in case of failure */
  16537. *ptab = NULL;
  16538. *plen = 0;
  16539. /* compute the number of returned properties */
  16540. num_keys_count = 0;
  16541. str_keys_count = 0;
  16542. sym_keys_count = 0;
  16543. exotic_keys_count = 0;
  16544. exotic_count = 0;
  16545. tab_exotic = NULL;
  16546. sh = p->shape;
  16547. for(i = 0, prs = get_shape_prop(sh); i < sh->prop_count; i++, prs++) {
  16548. atom = prs->atom;
  16549. if (atom != JS_ATOM_NULL) {
  16550. is_enumerable = ((prs->flags & JS_PROP_ENUMERABLE) != 0);
  16551. kind = JS_AtomGetKind(ctx, atom);
  16552. if ((!(flags & JS_GPN_ENUM_ONLY) || is_enumerable) &&
  16553. ((flags >> kind) & 1) != 0) {
  16554. /* need to raise an exception in case of the module
  16555. name space (implicit GetOwnProperty) */
  16556. if (unlikely((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) &&
  16557. (flags & (JS_GPN_SET_ENUM | JS_GPN_ENUM_ONLY))) {
  16558. JSVarRef *var_ref = p->prop[i].u.var_ref;
  16559. if (unlikely(JS_IsUninitialized(*var_ref->pvalue))) {
  16560. JS_ThrowReferenceErrorUninitialized(ctx, prs->atom);
  16561. return -1;
  16562. }
  16563. }
  16564. if (JS_AtomIsArrayIndex(ctx, &num_key, atom)) {
  16565. num_keys_count++;
  16566. } else if (kind == JS_ATOM_KIND_STRING) {
  16567. str_keys_count++;
  16568. } else {
  16569. sym_keys_count++;
  16570. }
  16571. }
  16572. }
  16573. }
  16574. if (p->is_exotic) {
  16575. if (p->fast_array) {
  16576. if (flags & JS_GPN_STRING_MASK) {
  16577. num_keys_count += p->u.array.count;
  16578. }
  16579. } else if (p->class_id == JS_CLASS_STRING) {
  16580. if (flags & JS_GPN_STRING_MASK) {
  16581. num_keys_count += js_string_obj_get_length(ctx, JS_MKPTR(JS_TAG_OBJECT, p));
  16582. }
  16583. } else {
  16584. const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic;
  16585. if (em && em->get_own_property_names) {
  16586. if (em->get_own_property_names(ctx, &tab_exotic, &exotic_count,
  16587. JS_MKPTR(JS_TAG_OBJECT, p)))
  16588. return -1;
  16589. for(i = 0; i < exotic_count; i++) {
  16590. atom = tab_exotic[i].atom;
  16591. kind = JS_AtomGetKind(ctx, atom);
  16592. if (((flags >> kind) & 1) != 0) {
  16593. is_enumerable = false;
  16594. if (flags & (JS_GPN_SET_ENUM | JS_GPN_ENUM_ONLY)) {
  16595. JSPropertyDescriptor desc;
  16596. int res;
  16597. /* set the "is_enumerable" field if necessary */
  16598. res = JS_GetOwnPropertyInternal(ctx, &desc, p, atom);
  16599. if (res < 0) {
  16600. js_free_prop_enum(ctx, tab_exotic, exotic_count);
  16601. return -1;
  16602. }
  16603. if (res) {
  16604. is_enumerable =
  16605. ((desc.flags & JS_PROP_ENUMERABLE) != 0);
  16606. js_free_desc(ctx, &desc);
  16607. }
  16608. tab_exotic[i].is_enumerable = is_enumerable;
  16609. }
  16610. if (!(flags & JS_GPN_ENUM_ONLY) || is_enumerable) {
  16611. exotic_keys_count++;
  16612. }
  16613. }
  16614. }
  16615. }
  16616. }
  16617. }
  16618. /* fill them */
  16619. atom_count = num_keys_count + str_keys_count + sym_keys_count + exotic_keys_count;
  16620. /* avoid allocating 0 bytes */
  16621. tab_atom = js_malloc(ctx, sizeof(tab_atom[0]) * max_int(atom_count, 1));
  16622. if (!tab_atom) {
  16623. js_free_prop_enum(ctx, tab_exotic, exotic_count);
  16624. return -1;
  16625. }
  16626. num_index = 0;
  16627. str_index = num_keys_count;
  16628. sym_index = str_index + str_keys_count;
  16629. num_sorted = true;
  16630. sh = p->shape;
  16631. for(i = 0, prs = get_shape_prop(sh); i < sh->prop_count; i++, prs++) {
  16632. atom = prs->atom;
  16633. if (atom != JS_ATOM_NULL) {
  16634. is_enumerable = ((prs->flags & JS_PROP_ENUMERABLE) != 0);
  16635. kind = JS_AtomGetKind(ctx, atom);
  16636. if ((!(flags & JS_GPN_ENUM_ONLY) || is_enumerable) &&
  16637. ((flags >> kind) & 1) != 0) {
  16638. if (JS_AtomIsArrayIndex(ctx, &num_key, atom)) {
  16639. j = num_index++;
  16640. num_sorted = false;
  16641. } else if (kind == JS_ATOM_KIND_STRING) {
  16642. j = str_index++;
  16643. } else {
  16644. j = sym_index++;
  16645. }
  16646. tab_atom[j].atom = JS_DupAtom(ctx, atom);
  16647. tab_atom[j].is_enumerable = is_enumerable;
  16648. }
  16649. }
  16650. }
  16651. if (p->is_exotic) {
  16652. int len;
  16653. if (p->fast_array) {
  16654. if (flags & JS_GPN_STRING_MASK) {
  16655. len = p->u.array.count;
  16656. goto add_array_keys;
  16657. }
  16658. } else if (p->class_id == JS_CLASS_STRING) {
  16659. if (flags & JS_GPN_STRING_MASK) {
  16660. len = js_string_obj_get_length(ctx, JS_MKPTR(JS_TAG_OBJECT, p));
  16661. add_array_keys:
  16662. for(i = 0; i < len; i++) {
  16663. tab_atom[num_index].atom = __JS_AtomFromUInt32(i);
  16664. if (tab_atom[num_index].atom == JS_ATOM_NULL) {
  16665. js_free_prop_enum(ctx, tab_atom, num_index);
  16666. return -1;
  16667. }
  16668. tab_atom[num_index].is_enumerable = true;
  16669. num_index++;
  16670. }
  16671. }
  16672. } else {
  16673. /* Note: exotic keys are not reordered and comes after the object own properties. */
  16674. for(i = 0; i < exotic_count; i++) {
  16675. atom = tab_exotic[i].atom;
  16676. is_enumerable = tab_exotic[i].is_enumerable;
  16677. kind = JS_AtomGetKind(ctx, atom);
  16678. if ((!(flags & JS_GPN_ENUM_ONLY) || is_enumerable) &&
  16679. ((flags >> kind) & 1) != 0) {
  16680. tab_atom[sym_index].atom = atom;
  16681. tab_atom[sym_index].is_enumerable = is_enumerable;
  16682. sym_index++;
  16683. } else {
  16684. JS_FreeAtom(ctx, atom);
  16685. }
  16686. }
  16687. js_free(ctx, tab_exotic);
  16688. }
  16689. }
  16690. assert(num_index == num_keys_count);
  16691. assert(str_index == num_keys_count + str_keys_count);
  16692. assert(sym_index == atom_count);
  16693. if (num_keys_count != 0 && !num_sorted) {
  16694. rqsort(tab_atom, num_keys_count, sizeof(tab_atom[0]), num_keys_cmp,
  16695. ctx);
  16696. }
  16697. *ptab = tab_atom;
  16698. *plen = atom_count;
  16699. return 0;
  16700. }
  16701. int JS_GetOwnPropertyNames(JSContext *ctx, JSPropertyEnum **ptab,
  16702. uint32_t *plen, JSValueConst obj, int flags)
  16703. {
  16704. if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) {
  16705. JS_ThrowTypeErrorNotAnObject(ctx);
  16706. return -1;
  16707. }
  16708. return JS_GetOwnPropertyNamesInternal(ctx, ptab, plen,
  16709. JS_VALUE_GET_OBJ(obj), flags);
  16710. }
  16711. /* Return -1 if exception,
  16712. false if the property does not exist, true if it exists. If true is
  16713. returned, the property descriptor 'desc' is filled present. */
  16714. static int JS_GetOwnPropertyInternal(JSContext *ctx, JSPropertyDescriptor *desc,
  16715. JSObject *p, JSAtom prop)
  16716. {
  16717. JSShapeProperty *prs;
  16718. JSProperty *pr;
  16719. retry:
  16720. prs = find_own_property(&pr, p, prop);
  16721. if (prs) {
  16722. if (desc) {
  16723. desc->flags = prs->flags & JS_PROP_C_W_E;
  16724. desc->getter = JS_UNDEFINED;
  16725. desc->setter = JS_UNDEFINED;
  16726. desc->value = JS_UNDEFINED;
  16727. if (unlikely(prs->flags & JS_PROP_TMASK)) {
  16728. if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) {
  16729. desc->flags |= JS_PROP_GETSET;
  16730. if (pr->u.getset.getter)
  16731. desc->getter = js_dup(JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.getter));
  16732. if (pr->u.getset.setter)
  16733. desc->setter = js_dup(JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.setter));
  16734. } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) {
  16735. JSValue val = *pr->u.var_ref->pvalue;
  16736. if (unlikely(JS_IsUninitialized(val))) {
  16737. JS_ThrowReferenceErrorUninitialized(ctx, prs->atom);
  16738. return -1;
  16739. }
  16740. desc->value = js_dup(val);
  16741. } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) {
  16742. /* Instantiate property and retry */
  16743. if (JS_AutoInitProperty(ctx, p, prop, pr, prs))
  16744. return -1;
  16745. goto retry;
  16746. }
  16747. } else {
  16748. desc->value = js_dup(pr->u.value);
  16749. }
  16750. } else {
  16751. /* for consistency, send the exception even if desc is NULL */
  16752. if (unlikely((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF)) {
  16753. if (unlikely(JS_IsUninitialized(*pr->u.var_ref->pvalue))) {
  16754. JS_ThrowReferenceErrorUninitialized(ctx, prs->atom);
  16755. return -1;
  16756. }
  16757. } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) {
  16758. /* nothing to do: delay instantiation until actual value and/or attributes are read */
  16759. }
  16760. }
  16761. return true;
  16762. }
  16763. if (p->is_exotic) {
  16764. if (p->fast_array) {
  16765. /* specific case for fast arrays */
  16766. if (__JS_AtomIsTaggedInt(prop)) {
  16767. uint32_t idx;
  16768. idx = __JS_AtomToUInt32(prop);
  16769. if (idx < p->u.array.count) {
  16770. if (desc) {
  16771. desc->flags = JS_PROP_WRITABLE | JS_PROP_ENUMERABLE |
  16772. JS_PROP_CONFIGURABLE;
  16773. desc->getter = JS_UNDEFINED;
  16774. desc->setter = JS_UNDEFINED;
  16775. desc->value = JS_GetPropertyUint32(ctx, JS_MKPTR(JS_TAG_OBJECT, p), idx);
  16776. }
  16777. return true;
  16778. }
  16779. }
  16780. } else {
  16781. const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic;
  16782. if (em && em->get_own_property) {
  16783. return em->get_own_property(ctx, desc,
  16784. JS_MKPTR(JS_TAG_OBJECT, p), prop);
  16785. }
  16786. }
  16787. }
  16788. return false;
  16789. }
  16790. int JS_GetOwnProperty(JSContext *ctx, JSPropertyDescriptor *desc,
  16791. JSValueConst obj, JSAtom prop)
  16792. {
  16793. if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) {
  16794. JS_ThrowTypeErrorNotAnObject(ctx);
  16795. return -1;
  16796. }
  16797. return JS_GetOwnPropertyInternal(ctx, desc, JS_VALUE_GET_OBJ(obj), prop);
  16798. }
  16799. void JS_FreePropertyEnum(JSContext *ctx, JSPropertyEnum *tab,
  16800. uint32_t len)
  16801. {
  16802. js_free_prop_enum(ctx, tab, len);
  16803. }
  16804. /* return -1 if exception (Proxy object only) or true/false */
  16805. int JS_IsExtensible(JSContext *ctx, JSValueConst obj)
  16806. {
  16807. JSObject *p;
  16808. if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT))
  16809. return false;
  16810. p = JS_VALUE_GET_OBJ(obj);
  16811. if (unlikely(p->class_id == JS_CLASS_PROXY))
  16812. return js_proxy_isExtensible(ctx, obj);
  16813. else
  16814. return p->extensible;
  16815. }
  16816. /* return -1 if exception (Proxy object only) or true/false */
  16817. int JS_PreventExtensions(JSContext *ctx, JSValueConst obj)
  16818. {
  16819. JSObject *p;
  16820. if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT))
  16821. return false;
  16822. p = JS_VALUE_GET_OBJ(obj);
  16823. if (unlikely(p->class_id == JS_CLASS_PROXY))
  16824. return js_proxy_preventExtensions(ctx, obj);
  16825. p->extensible = false;
  16826. return true;
  16827. }
  16828. /* return -1 if exception otherwise true or false */
  16829. int JS_HasProperty(JSContext *ctx, JSValueConst obj, JSAtom prop)
  16830. {
  16831. JSObject *p;
  16832. int ret;
  16833. JSValue obj1;
  16834. if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT))
  16835. return false;
  16836. p = JS_VALUE_GET_OBJ(obj);
  16837. for(;;) {
  16838. if (p->is_exotic) {
  16839. const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic;
  16840. if (em && em->has_property) {
  16841. /* has_property can free the prototype */
  16842. obj1 = js_dup(JS_MKPTR(JS_TAG_OBJECT, p));
  16843. ret = em->has_property(ctx, obj1, prop);
  16844. JS_FreeValue(ctx, obj1);
  16845. return ret;
  16846. }
  16847. }
  16848. /* JS_GetOwnPropertyInternal can free the prototype */
  16849. js_dup(JS_MKPTR(JS_TAG_OBJECT, p));
  16850. ret = JS_GetOwnPropertyInternal(ctx, NULL, p, prop);
  16851. JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p));
  16852. if (ret != 0)
  16853. return ret;
  16854. if (is_typed_array(p->class_id)) {
  16855. ret = JS_AtomIsNumericIndex(ctx, prop);
  16856. if (ret != 0) {
  16857. if (ret < 0)
  16858. return -1;
  16859. return false;
  16860. }
  16861. }
  16862. p = p->shape->proto;
  16863. if (!p)
  16864. break;
  16865. }
  16866. return false;
  16867. }
  16868. /* val must be a symbol */
  16869. static JSAtom js_symbol_to_atom(JSContext *ctx, JSValueConst val)
  16870. {
  16871. JSAtomStruct *p = JS_VALUE_GET_PTR(val);
  16872. return js_get_atom_index(ctx->rt, p);
  16873. }
  16874. /* return JS_ATOM_NULL in case of exception */
  16875. JSAtom JS_ValueToAtom(JSContext *ctx, JSValueConst val)
  16876. {
  16877. JSAtom atom;
  16878. uint32_t tag;
  16879. tag = JS_VALUE_GET_TAG(val);
  16880. if (tag == JS_TAG_INT &&
  16881. (uint32_t)JS_VALUE_GET_INT(val) <= JS_ATOM_MAX_INT) {
  16882. /* fast path for integer values */
  16883. atom = __JS_AtomFromUInt32(JS_VALUE_GET_INT(val));
  16884. } else if (tag == JS_TAG_SYMBOL) {
  16885. JSAtomStruct *p = JS_VALUE_GET_PTR(val);
  16886. atom = JS_DupAtom(ctx, js_get_atom_index(ctx->rt, p));
  16887. } else {
  16888. JSValue str;
  16889. str = JS_ToPropertyKey(ctx, val);
  16890. if (JS_IsException(str))
  16891. return JS_ATOM_NULL;
  16892. if (JS_VALUE_GET_TAG(str) == JS_TAG_SYMBOL) {
  16893. atom = js_symbol_to_atom(ctx, str);
  16894. } else {
  16895. atom = JS_NewAtomStr(ctx, JS_VALUE_GET_STRING(str));
  16896. }
  16897. }
  16898. return atom;
  16899. }
  16900. static bool js_get_fast_array_element(JSContext *ctx, JSObject *p,
  16901. uint32_t idx, JSValue *pval)
  16902. {
  16903. switch(p->class_id) {
  16904. case JS_CLASS_ARRAY:
  16905. case JS_CLASS_ARGUMENTS:
  16906. if (unlikely(idx >= p->u.array.count)) return false;
  16907. *pval = js_dup(p->u.array.u.values[idx]);
  16908. return true;
  16909. case JS_CLASS_INT8_ARRAY:
  16910. if (unlikely(idx >= p->u.array.count)) return false;
  16911. *pval = js_int32(p->u.array.u.int8_ptr[idx]);
  16912. return true;
  16913. case JS_CLASS_UINT8C_ARRAY:
  16914. case JS_CLASS_UINT8_ARRAY:
  16915. if (unlikely(idx >= p->u.array.count)) return false;
  16916. *pval = js_int32(p->u.array.u.uint8_ptr[idx]);
  16917. return true;
  16918. case JS_CLASS_INT16_ARRAY:
  16919. if (unlikely(idx >= p->u.array.count)) return false;
  16920. *pval = js_int32(p->u.array.u.int16_ptr[idx]);
  16921. return true;
  16922. case JS_CLASS_UINT16_ARRAY:
  16923. if (unlikely(idx >= p->u.array.count)) return false;
  16924. *pval = js_int32(p->u.array.u.uint16_ptr[idx]);
  16925. return true;
  16926. case JS_CLASS_INT32_ARRAY:
  16927. if (unlikely(idx >= p->u.array.count)) return false;
  16928. *pval = js_int32(p->u.array.u.int32_ptr[idx]);
  16929. return true;
  16930. case JS_CLASS_UINT32_ARRAY:
  16931. if (unlikely(idx >= p->u.array.count)) return false;
  16932. *pval = js_uint32(p->u.array.u.uint32_ptr[idx]);
  16933. return true;
  16934. case JS_CLASS_BIG_INT64_ARRAY:
  16935. if (unlikely(idx >= p->u.array.count)) return false;
  16936. *pval = JS_NewBigInt64(ctx, p->u.array.u.int64_ptr[idx]);
  16937. return true;
  16938. case JS_CLASS_BIG_UINT64_ARRAY:
  16939. if (unlikely(idx >= p->u.array.count)) return false;
  16940. *pval = JS_NewBigUint64(ctx, p->u.array.u.uint64_ptr[idx]);
  16941. return true;
  16942. case JS_CLASS_FLOAT16_ARRAY:
  16943. if (unlikely(idx >= p->u.array.count)) return false;
  16944. *pval = js_float64(fromfp16(p->u.array.u.fp16_ptr[idx]));
  16945. return true;
  16946. case JS_CLASS_FLOAT32_ARRAY:
  16947. if (unlikely(idx >= p->u.array.count)) return false;
  16948. *pval = js_float64(p->u.array.u.float_ptr[idx]);
  16949. return true;
  16950. case JS_CLASS_FLOAT64_ARRAY:
  16951. if (unlikely(idx >= p->u.array.count)) return false;
  16952. *pval = js_float64(p->u.array.u.double_ptr[idx]);
  16953. return true;
  16954. default:
  16955. return false;
  16956. }
  16957. }
  16958. static JSValue JS_GetPropertyValue(JSContext *ctx, JSValueConst this_obj,
  16959. JSValue prop)
  16960. {
  16961. JSAtom atom;
  16962. JSValue ret;
  16963. uint32_t tag;
  16964. tag = JS_VALUE_GET_TAG(this_obj);
  16965. if (likely(tag == JS_TAG_OBJECT)) {
  16966. if (JS_VALUE_GET_TAG(prop) == JS_TAG_INT) {
  16967. JSObject *p = JS_VALUE_GET_OBJ(this_obj);
  16968. uint32_t idx = JS_VALUE_GET_INT(prop);
  16969. JSValue val;
  16970. /* fast path for array and typed array access */
  16971. if (js_get_fast_array_element(ctx, p, idx, &val))
  16972. return val;
  16973. }
  16974. } else {
  16975. switch(tag) {
  16976. case JS_TAG_NULL:
  16977. JS_FreeValue(ctx, prop);
  16978. return JS_ThrowTypeError(ctx, "cannot read property of null");
  16979. case JS_TAG_UNDEFINED:
  16980. JS_FreeValue(ctx, prop);
  16981. return JS_ThrowTypeError(ctx, "cannot read property of undefined");
  16982. }
  16983. }
  16984. atom = JS_ValueToAtom(ctx, prop);
  16985. JS_FreeValue(ctx, prop);
  16986. if (unlikely(atom == JS_ATOM_NULL))
  16987. return JS_EXCEPTION;
  16988. ret = JS_GetProperty(ctx, this_obj, atom);
  16989. JS_FreeAtom(ctx, atom);
  16990. return ret;
  16991. }
  16992. JSValue JS_GetPropertyUint32(JSContext *ctx, JSValueConst this_obj,
  16993. uint32_t idx)
  16994. {
  16995. return JS_GetPropertyInt64(ctx, this_obj, idx);
  16996. }
  16997. /* Check if an object has a generalized numeric property. Return value:
  16998. -1 for exception, *pval set to JS_EXCEPTION
  16999. true if property exists, stored into *pval,
  17000. false if property does not exist. *pval set to JS_UNDEFINED.
  17001. */
  17002. static int JS_TryGetPropertyInt64(JSContext *ctx, JSValueConst obj, int64_t idx, JSValue *pval)
  17003. {
  17004. JSValue val;
  17005. JSAtom prop;
  17006. int present;
  17007. if (likely(JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT &&
  17008. (uint64_t)idx <= INT32_MAX)) {
  17009. /* fast path for array and typed array access */
  17010. JSObject *p = JS_VALUE_GET_OBJ(obj);
  17011. if (js_get_fast_array_element(ctx, p, idx, pval))
  17012. return true;
  17013. }
  17014. val = JS_EXCEPTION;
  17015. present = -1;
  17016. prop = JS_NewAtomInt64(ctx, idx);
  17017. if (likely(prop != JS_ATOM_NULL)) {
  17018. present = JS_HasProperty(ctx, obj, prop);
  17019. if (present > 0) {
  17020. val = JS_GetProperty(ctx, obj, prop);
  17021. if (unlikely(JS_IsException(val)))
  17022. present = -1;
  17023. } else if (present == false) {
  17024. val = JS_UNDEFINED;
  17025. }
  17026. JS_FreeAtom(ctx, prop);
  17027. }
  17028. *pval = val;
  17029. return present;
  17030. }
  17031. JSValue JS_GetPropertyInt64(JSContext *ctx, JSValueConst obj, int64_t idx)
  17032. {
  17033. JSAtom prop;
  17034. JSValue val;
  17035. if (likely(JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT &&
  17036. (uint64_t)idx <= INT32_MAX)) {
  17037. /* fast path for array and typed array access */
  17038. JSObject *p = JS_VALUE_GET_OBJ(obj);
  17039. if (js_get_fast_array_element(ctx, p, idx, &val))
  17040. return val;
  17041. }
  17042. prop = JS_NewAtomInt64(ctx, idx);
  17043. if (prop == JS_ATOM_NULL)
  17044. return JS_EXCEPTION;
  17045. val = JS_GetProperty(ctx, obj, prop);
  17046. JS_FreeAtom(ctx, prop);
  17047. return val;
  17048. }
  17049. /* `prop` may be pure ASCII or UTF-8 encoded */
  17050. JSValue JS_GetPropertyStr(JSContext *ctx, JSValueConst this_obj,
  17051. const char *prop)
  17052. {
  17053. JSAtom atom;
  17054. JSValue ret;
  17055. atom = JS_NewAtom(ctx, prop);
  17056. ret = JS_GetProperty(ctx, this_obj, atom);
  17057. JS_FreeAtom(ctx, atom);
  17058. return ret;
  17059. }
  17060. /* Note: the property value is not initialized. Return NULL if memory
  17061. error. */
  17062. static JSProperty *add_property(JSContext *ctx,
  17063. JSObject *p, JSAtom prop, int prop_flags)
  17064. {
  17065. JSShape *sh, *new_sh;
  17066. sh = p->shape;
  17067. if (sh->is_hashed) {
  17068. /* try to find an existing shape */
  17069. new_sh = find_hashed_shape_prop(ctx->rt, sh, prop, prop_flags);
  17070. if (new_sh) {
  17071. /* matching shape found: use it */
  17072. /* the property array may need to be resized */
  17073. if (new_sh->prop_size != sh->prop_size) {
  17074. JSProperty *new_prop;
  17075. new_prop = js_realloc(ctx, p->prop, sizeof(p->prop[0]) *
  17076. new_sh->prop_size);
  17077. if (!new_prop)
  17078. return NULL;
  17079. p->prop = new_prop;
  17080. }
  17081. p->shape = js_dup_shape(new_sh);
  17082. js_free_shape(ctx->rt, sh);
  17083. return &p->prop[new_sh->prop_count - 1];
  17084. } else if (sh->header.ref_count != 1) {
  17085. /* if the shape is shared, clone it */
  17086. new_sh = js_clone_shape(ctx, sh);
  17087. if (!new_sh)
  17088. return NULL;
  17089. /* hash the cloned shape */
  17090. new_sh->is_hashed = true;
  17091. js_shape_hash_link(ctx->rt, new_sh);
  17092. js_free_shape(ctx->rt, p->shape);
  17093. p->shape = new_sh;
  17094. }
  17095. }
  17096. assert(p->shape->header.ref_count == 1);
  17097. if (add_shape_property(ctx, &p->shape, p, prop, prop_flags))
  17098. return NULL;
  17099. return &p->prop[p->shape->prop_count - 1];
  17100. }
  17101. /* can be called on Array or Arguments objects. return < 0 if
  17102. memory alloc error. */
  17103. static no_inline __exception int convert_fast_array_to_array(JSContext *ctx,
  17104. JSObject *p)
  17105. {
  17106. JSProperty *pr;
  17107. JSShape *sh;
  17108. JSValue *tab;
  17109. uint32_t i, len, new_count;
  17110. if (js_shape_prepare_update(ctx, p, NULL))
  17111. return -1;
  17112. len = p->u.array.count;
  17113. /* resize the properties once to simplify the error handling */
  17114. sh = p->shape;
  17115. new_count = sh->prop_count + len;
  17116. if (new_count > sh->prop_size) {
  17117. if (resize_properties(ctx, &p->shape, p, new_count))
  17118. return -1;
  17119. }
  17120. tab = p->u.array.u.values;
  17121. for(i = 0; i < len; i++) {
  17122. /* add_property cannot fail here but
  17123. __JS_AtomFromUInt32(i) fails for i > INT32_MAX */
  17124. pr = add_property(ctx, p, __JS_AtomFromUInt32(i), JS_PROP_C_W_E);
  17125. pr->u.value = *tab++;
  17126. }
  17127. js_free(ctx, p->u.array.u.values);
  17128. p->u.array.count = 0;
  17129. p->u.array.u.values = NULL; /* fail safe */
  17130. p->u.array.u1.size = 0;
  17131. p->fast_array = 0;
  17132. return 0;
  17133. }
  17134. static int delete_property(JSContext *ctx, JSObject *p, JSAtom atom)
  17135. {
  17136. JSShape *sh;
  17137. JSShapeProperty *pr, *lpr, *prop;
  17138. JSProperty *pr1;
  17139. uint32_t lpr_idx;
  17140. intptr_t h, h1;
  17141. redo:
  17142. sh = p->shape;
  17143. h1 = atom & sh->prop_hash_mask;
  17144. h = prop_hash_end(sh)[-h1 - 1];
  17145. prop = get_shape_prop(sh);
  17146. lpr = NULL;
  17147. lpr_idx = 0; /* prevent warning */
  17148. while (h != 0) {
  17149. pr = &prop[h - 1];
  17150. if (likely(pr->atom == atom)) {
  17151. /* found ! */
  17152. if (!(pr->flags & JS_PROP_CONFIGURABLE))
  17153. return false;
  17154. /* realloc the shape if needed */
  17155. if (lpr)
  17156. lpr_idx = lpr - get_shape_prop(sh);
  17157. if (js_shape_prepare_update(ctx, p, &pr))
  17158. return -1;
  17159. sh = p->shape;
  17160. /* remove property */
  17161. if (lpr) {
  17162. lpr = get_shape_prop(sh) + lpr_idx;
  17163. lpr->hash_next = pr->hash_next;
  17164. } else {
  17165. prop_hash_end(sh)[-h1 - 1] = pr->hash_next;
  17166. }
  17167. sh->deleted_prop_count++;
  17168. /* free the entry */
  17169. pr1 = &p->prop[h - 1];
  17170. free_property(ctx->rt, pr1, pr->flags);
  17171. JS_FreeAtom(ctx, pr->atom);
  17172. /* put default values */
  17173. pr->flags = 0;
  17174. pr->atom = JS_ATOM_NULL;
  17175. pr1->u.value = JS_UNDEFINED;
  17176. /* compact the properties if too many deleted properties */
  17177. if (sh->deleted_prop_count >= 8 &&
  17178. sh->deleted_prop_count >= ((unsigned)sh->prop_count / 2)) {
  17179. compact_properties(ctx, p);
  17180. }
  17181. return true;
  17182. }
  17183. lpr = pr;
  17184. h = pr->hash_next;
  17185. }
  17186. if (p->is_exotic) {
  17187. if (p->fast_array) {
  17188. uint32_t idx;
  17189. if (JS_AtomIsArrayIndex(ctx, &idx, atom) &&
  17190. idx < p->u.array.count) {
  17191. if (p->class_id == JS_CLASS_ARRAY ||
  17192. p->class_id == JS_CLASS_ARGUMENTS) {
  17193. /* Special case deleting the last element of a fast Array */
  17194. if (idx == p->u.array.count - 1) {
  17195. JS_FreeValue(ctx, p->u.array.u.values[idx]);
  17196. p->u.array.count = idx;
  17197. return true;
  17198. }
  17199. if (convert_fast_array_to_array(ctx, p))
  17200. return -1;
  17201. goto redo;
  17202. } else {
  17203. return false;
  17204. }
  17205. }
  17206. } else {
  17207. const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic;
  17208. if (em && em->delete_property) {
  17209. return em->delete_property(ctx, JS_MKPTR(JS_TAG_OBJECT, p), atom);
  17210. }
  17211. }
  17212. }
  17213. /* not found */
  17214. return true;
  17215. }
  17216. static int call_setter(JSContext *ctx, JSObject *setter,
  17217. JSValueConst this_obj, JSValue val, int flags)
  17218. {
  17219. JSValue ret, func;
  17220. if (likely(setter)) {
  17221. func = JS_MKPTR(JS_TAG_OBJECT, setter);
  17222. /* Note: the field could be removed in the setter */
  17223. func = js_dup(func);
  17224. ret = JS_CallFree(ctx, func, this_obj, 1, vc(&val));
  17225. JS_FreeValue(ctx, val);
  17226. if (JS_IsException(ret))
  17227. return -1;
  17228. JS_FreeValue(ctx, ret);
  17229. return true;
  17230. } else {
  17231. JS_FreeValue(ctx, val);
  17232. if ((flags & JS_PROP_THROW) ||
  17233. ((flags & JS_PROP_THROW_STRICT) && is_strict_mode(ctx))) {
  17234. JS_ThrowTypeError(ctx, "no setter for property");
  17235. return -1;
  17236. }
  17237. return false;
  17238. }
  17239. }
  17240. /* set the array length and remove the array elements if necessary. */
  17241. static int set_array_length(JSContext *ctx, JSObject *p, JSValue val,
  17242. int flags)
  17243. {
  17244. uint32_t len, idx, cur_len;
  17245. int i, ret;
  17246. /* Note: this call can reallocate the properties of 'p' */
  17247. ret = JS_ToArrayLengthFree(ctx, &len, val, false);
  17248. if (ret)
  17249. return -1;
  17250. /* JS_ToArrayLengthFree() must be done before the read-only test */
  17251. if (unlikely(!(p->shape->prop[0].flags & JS_PROP_WRITABLE)))
  17252. return JS_ThrowTypeErrorReadOnly(ctx, flags, JS_ATOM_length);
  17253. if (likely(p->fast_array)) {
  17254. uint32_t old_len = p->u.array.count;
  17255. if (len < old_len) {
  17256. for(i = len; i < old_len; i++) {
  17257. JS_FreeValue(ctx, p->u.array.u.values[i]);
  17258. }
  17259. p->u.array.count = len;
  17260. }
  17261. p->prop[0].u.value = js_uint32(len);
  17262. } else {
  17263. /* Note: length is always a uint32 because the object is an
  17264. array */
  17265. JS_ToUint32(ctx, &cur_len, p->prop[0].u.value);
  17266. if (len < cur_len) {
  17267. uint32_t d;
  17268. JSShape *sh;
  17269. JSShapeProperty *pr;
  17270. d = cur_len - len;
  17271. sh = p->shape;
  17272. if (d <= sh->prop_count) {
  17273. JSAtom atom;
  17274. /* faster to iterate */
  17275. while (cur_len > len) {
  17276. atom = JS_NewAtomUInt32(ctx, cur_len - 1);
  17277. ret = delete_property(ctx, p, atom);
  17278. JS_FreeAtom(ctx, atom);
  17279. if (unlikely(!ret)) {
  17280. /* unlikely case: property is not
  17281. configurable */
  17282. break;
  17283. }
  17284. cur_len--;
  17285. }
  17286. } else {
  17287. /* faster to iterate thru all the properties. Need two
  17288. passes in case one of the property is not
  17289. configurable */
  17290. cur_len = len;
  17291. for(i = 0, pr = get_shape_prop(sh); i < sh->prop_count;
  17292. i++, pr++) {
  17293. if (pr->atom != JS_ATOM_NULL &&
  17294. JS_AtomIsArrayIndex(ctx, &idx, pr->atom)) {
  17295. if (idx >= cur_len &&
  17296. !(pr->flags & JS_PROP_CONFIGURABLE)) {
  17297. cur_len = idx + 1;
  17298. }
  17299. }
  17300. }
  17301. for(i = 0, pr = get_shape_prop(sh); i < sh->prop_count;
  17302. i++, pr++) {
  17303. if (pr->atom != JS_ATOM_NULL &&
  17304. JS_AtomIsArrayIndex(ctx, &idx, pr->atom)) {
  17305. if (idx >= cur_len) {
  17306. /* remove the property */
  17307. delete_property(ctx, p, pr->atom);
  17308. /* WARNING: the shape may have been modified */
  17309. sh = p->shape;
  17310. pr = get_shape_prop(sh) + i;
  17311. }
  17312. }
  17313. }
  17314. }
  17315. } else {
  17316. cur_len = len;
  17317. }
  17318. set_value(ctx, &p->prop[0].u.value, js_uint32(cur_len));
  17319. if (unlikely(cur_len > len)) {
  17320. return JS_ThrowTypeErrorOrFalse(ctx, flags, "not configurable");
  17321. }
  17322. }
  17323. return true;
  17324. }
  17325. /* return -1 if exception */
  17326. static int expand_fast_array(JSContext *ctx, JSObject *p, uint32_t new_len)
  17327. {
  17328. uint32_t new_size;
  17329. size_t slack;
  17330. JSValue *new_array_prop;
  17331. /* XXX: potential arithmetic overflow */
  17332. new_size = max_int(new_len, p->u.array.u1.size * 3 / 2);
  17333. new_array_prop = js_realloc2(ctx, p->u.array.u.values, sizeof(JSValue) * new_size, &slack);
  17334. if (!new_array_prop)
  17335. return -1;
  17336. new_size += slack / sizeof(*new_array_prop);
  17337. p->u.array.u.values = new_array_prop;
  17338. p->u.array.u1.size = new_size;
  17339. return 0;
  17340. }
  17341. /* Preconditions: 'p' must be of class JS_CLASS_ARRAY, p->fast_array =
  17342. true and p->extensible = true */
  17343. static int add_fast_array_element(JSContext *ctx, JSObject *p,
  17344. JSValue val, int flags)
  17345. {
  17346. uint32_t new_len, array_len;
  17347. /* extend the array by one */
  17348. /* XXX: convert to slow array if new_len > 2^31-1 elements */
  17349. new_len = p->u.array.count + 1;
  17350. /* update the length if necessary. We assume that if the length is
  17351. not an integer, then if it >= 2^31. */
  17352. if (likely(JS_VALUE_GET_TAG(p->prop[0].u.value) == JS_TAG_INT)) {
  17353. array_len = JS_VALUE_GET_INT(p->prop[0].u.value);
  17354. if (new_len > array_len) {
  17355. if (unlikely(!(get_shape_prop(p->shape)->flags & JS_PROP_WRITABLE))) {
  17356. JS_FreeValue(ctx, val);
  17357. return JS_ThrowTypeErrorReadOnly(ctx, flags, JS_ATOM_length);
  17358. }
  17359. p->prop[0].u.value = js_int32(new_len);
  17360. }
  17361. }
  17362. if (unlikely(new_len > p->u.array.u1.size)) {
  17363. if (expand_fast_array(ctx, p, new_len)) {
  17364. JS_FreeValue(ctx, val);
  17365. return -1;
  17366. }
  17367. }
  17368. p->u.array.u.values[new_len - 1] = val;
  17369. p->u.array.count = new_len;
  17370. return true;
  17371. }
  17372. static void js_free_desc(JSContext *ctx, JSPropertyDescriptor *desc)
  17373. {
  17374. JS_FreeValue(ctx, desc->getter);
  17375. JS_FreeValue(ctx, desc->setter);
  17376. JS_FreeValue(ctx, desc->value);
  17377. }
  17378. /* return -1 in case of exception or true or false. Warning: 'val' is
  17379. freed by the function. 'flags' is a bitmask of JS_PROP_NO_ADD,
  17380. JS_PROP_THROW or JS_PROP_THROW_STRICT. If JS_PROP_NO_ADD is set,
  17381. the new property is not added and an error is raised.
  17382. 'obj' must be an object when obj != this_obj.
  17383. */
  17384. static int JS_SetPropertyInternal2(JSContext *ctx, JSValueConst obj, JSAtom prop,
  17385. JSValue val, JSValueConst this_obj, int flags)
  17386. {
  17387. JSObject *p, *p1;
  17388. JSShapeProperty *prs;
  17389. JSProperty *pr;
  17390. JSPropertyDescriptor desc;
  17391. int ret;
  17392. switch(JS_VALUE_GET_TAG(this_obj)) {
  17393. case JS_TAG_NULL:
  17394. JS_ThrowTypeErrorAtom(ctx, "cannot set property '%s' of null", prop);
  17395. goto fail;
  17396. case JS_TAG_UNDEFINED:
  17397. JS_ThrowTypeErrorAtom(ctx, "cannot set property '%s' of undefined", prop);
  17398. goto fail;
  17399. case JS_TAG_OBJECT:
  17400. p = JS_VALUE_GET_OBJ(this_obj);
  17401. p1 = JS_VALUE_GET_OBJ(obj);
  17402. if (p == p1)
  17403. break;
  17404. goto retry2;
  17405. default:
  17406. if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)
  17407. obj = JS_GetPrototypePrimitive(ctx, obj);
  17408. p = NULL;
  17409. p1 = JS_VALUE_GET_OBJ(obj);
  17410. goto prototype_lookup;
  17411. }
  17412. retry:
  17413. prs = find_own_property(&pr, p1, prop);
  17414. if (prs) {
  17415. if (likely((prs->flags & (JS_PROP_TMASK | JS_PROP_WRITABLE |
  17416. JS_PROP_LENGTH)) == JS_PROP_WRITABLE)) {
  17417. /* fast case */
  17418. set_value(ctx, &pr->u.value, val);
  17419. return true;
  17420. } else if (prs->flags & JS_PROP_LENGTH) {
  17421. assert(p->class_id == JS_CLASS_ARRAY);
  17422. assert(prop == JS_ATOM_length);
  17423. return set_array_length(ctx, p, val, flags);
  17424. } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) {
  17425. return call_setter(ctx, pr->u.getset.setter, this_obj, val, flags);
  17426. } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) {
  17427. /* JS_PROP_WRITABLE is always true for variable
  17428. references, but they are write protected in module name
  17429. spaces. */
  17430. if (p->class_id == JS_CLASS_MODULE_NS)
  17431. goto read_only_prop;
  17432. set_value(ctx, pr->u.var_ref->pvalue, val);
  17433. return true;
  17434. } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) {
  17435. /* Instantiate property and retry (potentially useless) */
  17436. if (JS_AutoInitProperty(ctx, p, prop, pr, prs))
  17437. goto fail;
  17438. goto retry;
  17439. } else {
  17440. goto read_only_prop;
  17441. }
  17442. }
  17443. for(;;) {
  17444. if (p1->is_exotic) {
  17445. if (p1->fast_array) {
  17446. if (__JS_AtomIsTaggedInt(prop)) {
  17447. uint32_t idx = __JS_AtomToUInt32(prop);
  17448. if (idx < p1->u.array.count) {
  17449. if (unlikely(p == p1))
  17450. return JS_SetPropertyValue(ctx, this_obj, js_int32(idx), val, flags);
  17451. else
  17452. break;
  17453. } else if (is_typed_array(p1->class_id)) {
  17454. goto typed_array_oob;
  17455. }
  17456. } else if (is_typed_array(p1->class_id)) {
  17457. ret = JS_AtomIsNumericIndex(ctx, prop);
  17458. if (ret != 0) {
  17459. if (ret < 0)
  17460. goto fail;
  17461. typed_array_oob:
  17462. // per spec: evaluate value for side effects
  17463. if (p1->class_id == JS_CLASS_BIG_INT64_ARRAY ||
  17464. p1->class_id == JS_CLASS_BIG_UINT64_ARRAY) {
  17465. int64_t v;
  17466. if (JS_ToBigInt64Free(ctx, &v, val))
  17467. return -1;
  17468. } else {
  17469. val = JS_ToNumberFree(ctx, val);
  17470. JS_FreeValue(ctx, val);
  17471. if (JS_IsException(val))
  17472. return -1;
  17473. }
  17474. return true;
  17475. }
  17476. }
  17477. } else {
  17478. const JSClassExoticMethods *em = ctx->rt->class_array[p1->class_id].exotic;
  17479. if (em) {
  17480. JSValue obj1;
  17481. if (em->set_property) {
  17482. /* set_property can free the prototype */
  17483. obj1 = js_dup(JS_MKPTR(JS_TAG_OBJECT, p1));
  17484. ret = em->set_property(ctx, obj1, prop,
  17485. val, this_obj, flags);
  17486. JS_FreeValue(ctx, obj1);
  17487. JS_FreeValue(ctx, val);
  17488. return ret;
  17489. }
  17490. if (em->get_own_property) {
  17491. /* get_own_property can free the prototype */
  17492. obj1 = js_dup(JS_MKPTR(JS_TAG_OBJECT, p1));
  17493. ret = em->get_own_property(ctx, &desc,
  17494. obj1, prop);
  17495. JS_FreeValue(ctx, obj1);
  17496. if (ret < 0)
  17497. goto fail;
  17498. if (ret) {
  17499. if (desc.flags & JS_PROP_GETSET) {
  17500. JSObject *setter;
  17501. if (JS_IsUndefined(desc.setter))
  17502. setter = NULL;
  17503. else
  17504. setter = JS_VALUE_GET_OBJ(desc.setter);
  17505. ret = call_setter(ctx, setter, this_obj, val, flags);
  17506. JS_FreeValue(ctx, desc.getter);
  17507. JS_FreeValue(ctx, desc.setter);
  17508. return ret;
  17509. } else {
  17510. JS_FreeValue(ctx, desc.value);
  17511. if (!(desc.flags & JS_PROP_WRITABLE))
  17512. goto read_only_prop;
  17513. if (likely(p == p1)) {
  17514. ret = JS_DefineProperty(ctx, this_obj, prop, val,
  17515. JS_UNDEFINED, JS_UNDEFINED,
  17516. JS_PROP_HAS_VALUE);
  17517. JS_FreeValue(ctx, val);
  17518. return ret;
  17519. } else {
  17520. break;
  17521. }
  17522. }
  17523. }
  17524. }
  17525. }
  17526. }
  17527. }
  17528. p1 = p1->shape->proto;
  17529. prototype_lookup:
  17530. if (!p1)
  17531. break;
  17532. retry2:
  17533. prs = find_own_property(&pr, p1, prop);
  17534. if (prs) {
  17535. if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) {
  17536. return call_setter(ctx, pr->u.getset.setter, this_obj, val, flags);
  17537. } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) {
  17538. /* Instantiate property and retry (potentially useless) */
  17539. if (JS_AutoInitProperty(ctx, p1, prop, pr, prs))
  17540. return -1;
  17541. goto retry2;
  17542. } else if (!(prs->flags & JS_PROP_WRITABLE)) {
  17543. goto read_only_prop;
  17544. }
  17545. }
  17546. }
  17547. if (unlikely(flags & JS_PROP_NO_ADD)) {
  17548. JS_ThrowReferenceErrorNotDefined(ctx, prop);
  17549. goto fail;
  17550. }
  17551. if (unlikely(!p)) {
  17552. ret = JS_ThrowTypeErrorOrFalse(ctx, flags, "not an object");
  17553. goto done;
  17554. }
  17555. if (unlikely(!p->extensible)) {
  17556. ret = JS_ThrowTypeErrorOrFalse(ctx, flags, "object is not extensible");
  17557. goto done;
  17558. }
  17559. if (p == JS_VALUE_GET_OBJ(obj)) {
  17560. if (p->is_exotic) {
  17561. if (p->class_id == JS_CLASS_ARRAY && p->fast_array &&
  17562. __JS_AtomIsTaggedInt(prop)) {
  17563. uint32_t idx = __JS_AtomToUInt32(prop);
  17564. if (idx == p->u.array.count) {
  17565. /* fast case */
  17566. return add_fast_array_element(ctx, p, val, flags);
  17567. }
  17568. }
  17569. goto generic_create_prop;
  17570. } else {
  17571. pr = add_property(ctx, p, prop, JS_PROP_C_W_E);
  17572. if (!pr)
  17573. goto fail;
  17574. pr->u.value = val;
  17575. return true;
  17576. }
  17577. }
  17578. // TODO(bnoordhuis) return JSProperty slot and update in place
  17579. // when plain property (not is_exotic/setter/etc.) to avoid
  17580. // calling find_own_property() thrice?
  17581. ret = JS_GetOwnPropertyInternal(ctx, &desc, p, prop);
  17582. if (ret < 0)
  17583. goto fail;
  17584. if (ret) {
  17585. JS_FreeValue(ctx, desc.value);
  17586. if (desc.flags & JS_PROP_GETSET) {
  17587. JS_FreeValue(ctx, desc.getter);
  17588. JS_FreeValue(ctx, desc.setter);
  17589. ret = JS_ThrowTypeErrorOrFalse(ctx, flags, "setter is forbidden");
  17590. goto done;
  17591. } else if (!(desc.flags & JS_PROP_WRITABLE) ||
  17592. p->class_id == JS_CLASS_MODULE_NS) {
  17593. read_only_prop:
  17594. ret = JS_ThrowTypeErrorReadOnly(ctx, flags, prop);
  17595. goto done;
  17596. }
  17597. ret = JS_DefineProperty(ctx, this_obj, prop, val,
  17598. JS_UNDEFINED, JS_UNDEFINED,
  17599. JS_PROP_HAS_VALUE);
  17600. } else {
  17601. generic_create_prop:
  17602. ret = JS_CreateProperty(ctx, p, prop, val, JS_UNDEFINED, JS_UNDEFINED,
  17603. flags |
  17604. JS_PROP_HAS_VALUE |
  17605. JS_PROP_HAS_ENUMERABLE |
  17606. JS_PROP_HAS_WRITABLE |
  17607. JS_PROP_HAS_CONFIGURABLE |
  17608. JS_PROP_C_W_E);
  17609. }
  17610. done:
  17611. JS_FreeValue(ctx, val);
  17612. return ret;
  17613. fail:
  17614. JS_FreeValue(ctx, val);
  17615. return -1;
  17616. }
  17617. static int JS_SetPropertyInternal(JSContext *ctx, JSValueConst obj, JSAtom prop,
  17618. JSValue val, int flags)
  17619. {
  17620. return JS_SetPropertyInternal2(ctx, obj, prop, val, obj, flags);
  17621. }
  17622. int JS_SetProperty(JSContext *ctx, JSValueConst this_obj, JSAtom prop, JSValue val)
  17623. {
  17624. return JS_SetPropertyInternal(ctx, this_obj, prop, val, JS_PROP_THROW);
  17625. }
  17626. /* flags can be JS_PROP_THROW or JS_PROP_THROW_STRICT */
  17627. static int JS_SetPropertyValue(JSContext *ctx, JSValueConst this_obj,
  17628. JSValue prop, JSValue val, int flags)
  17629. {
  17630. if (likely(JS_VALUE_GET_TAG(this_obj) == JS_TAG_OBJECT &&
  17631. JS_VALUE_GET_TAG(prop) == JS_TAG_INT)) {
  17632. JSObject *p;
  17633. uint32_t idx;
  17634. double d;
  17635. int32_t v;
  17636. /* fast path for array access */
  17637. p = JS_VALUE_GET_OBJ(this_obj);
  17638. idx = JS_VALUE_GET_INT(prop);
  17639. switch(p->class_id) {
  17640. case JS_CLASS_ARRAY:
  17641. if (unlikely(idx >= (uint32_t)p->u.array.count)) {
  17642. JSObject *p1;
  17643. JSShape *sh1;
  17644. /* fast path to add an element to the array */
  17645. if (idx != (uint32_t)p->u.array.count ||
  17646. !p->fast_array || !p->extensible)
  17647. goto slow_path;
  17648. /* check if prototype chain has a numeric property */
  17649. p1 = p->shape->proto;
  17650. while (p1 != NULL) {
  17651. sh1 = p1->shape;
  17652. if (p1->class_id == JS_CLASS_ARRAY) {
  17653. if (unlikely(!p1->fast_array))
  17654. goto slow_path;
  17655. } else if (p1->class_id == JS_CLASS_OBJECT) {
  17656. if (unlikely(sh1->has_small_array_index))
  17657. goto slow_path;
  17658. } else {
  17659. goto slow_path;
  17660. }
  17661. p1 = sh1->proto;
  17662. }
  17663. /* add element */
  17664. return add_fast_array_element(ctx, p, val, flags);
  17665. }
  17666. set_value(ctx, &p->u.array.u.values[idx], val);
  17667. break;
  17668. case JS_CLASS_ARGUMENTS:
  17669. if (unlikely(idx >= (uint32_t)p->u.array.count))
  17670. goto slow_path;
  17671. set_value(ctx, &p->u.array.u.values[idx], val);
  17672. break;
  17673. case JS_CLASS_UINT8C_ARRAY:
  17674. if (JS_ToUint8ClampFree(ctx, &v, val))
  17675. goto ta_cvt_fail;
  17676. /* Note: the conversion can detach the typed array, so the
  17677. array bound check must be done after */
  17678. if (unlikely(idx >= (uint32_t)p->u.array.count))
  17679. goto ta_out_of_bound;
  17680. p->u.array.u.uint8_ptr[idx] = v;
  17681. break;
  17682. case JS_CLASS_INT8_ARRAY:
  17683. case JS_CLASS_UINT8_ARRAY:
  17684. if (JS_ToInt32Free(ctx, &v, val))
  17685. goto ta_cvt_fail;
  17686. if (unlikely(idx >= (uint32_t)p->u.array.count))
  17687. goto ta_out_of_bound;
  17688. p->u.array.u.uint8_ptr[idx] = v;
  17689. break;
  17690. case JS_CLASS_INT16_ARRAY:
  17691. case JS_CLASS_UINT16_ARRAY:
  17692. if (JS_ToInt32Free(ctx, &v, val))
  17693. goto ta_cvt_fail;
  17694. if (unlikely(idx >= (uint32_t)p->u.array.count))
  17695. goto ta_out_of_bound;
  17696. p->u.array.u.uint16_ptr[idx] = v;
  17697. break;
  17698. case JS_CLASS_INT32_ARRAY:
  17699. case JS_CLASS_UINT32_ARRAY:
  17700. if (JS_ToInt32Free(ctx, &v, val))
  17701. goto ta_cvt_fail;
  17702. if (unlikely(idx >= (uint32_t)p->u.array.count))
  17703. goto ta_out_of_bound;
  17704. p->u.array.u.uint32_ptr[idx] = v;
  17705. break;
  17706. case JS_CLASS_BIG_INT64_ARRAY:
  17707. case JS_CLASS_BIG_UINT64_ARRAY:
  17708. /* XXX: need specific conversion function */
  17709. {
  17710. int64_t v;
  17711. if (JS_ToBigInt64Free(ctx, &v, val))
  17712. goto ta_cvt_fail;
  17713. if (unlikely(idx >= (uint32_t)p->u.array.count))
  17714. goto ta_out_of_bound;
  17715. p->u.array.u.uint64_ptr[idx] = v;
  17716. }
  17717. break;
  17718. case JS_CLASS_FLOAT16_ARRAY:
  17719. if (JS_ToFloat64Free(ctx, &d, val))
  17720. goto ta_cvt_fail;
  17721. if (unlikely(idx >= (uint32_t)p->u.array.count))
  17722. goto ta_out_of_bound;
  17723. p->u.array.u.fp16_ptr[idx] = tofp16(d);
  17724. break;
  17725. case JS_CLASS_FLOAT32_ARRAY:
  17726. if (JS_ToFloat64Free(ctx, &d, val))
  17727. goto ta_cvt_fail;
  17728. if (unlikely(idx >= (uint32_t)p->u.array.count))
  17729. goto ta_out_of_bound;
  17730. p->u.array.u.float_ptr[idx] = d;
  17731. break;
  17732. case JS_CLASS_FLOAT64_ARRAY:
  17733. if (JS_ToFloat64Free(ctx, &d, val)) {
  17734. ta_cvt_fail:
  17735. if (flags & JS_PROP_REFLECT_DEFINE_PROPERTY) {
  17736. JS_FreeValue(ctx, JS_GetException(ctx));
  17737. return false;
  17738. }
  17739. return -1;
  17740. }
  17741. if (unlikely(idx >= (uint32_t)p->u.array.count)) {
  17742. ta_out_of_bound:
  17743. if (typed_array_is_oob(p))
  17744. if (flags & JS_PROP_DEFINE_PROPERTY)
  17745. return JS_ThrowTypeErrorOrFalse(ctx, flags, "out-of-bound numeric index");
  17746. return true; // per spec: no OOB exception
  17747. }
  17748. p->u.array.u.double_ptr[idx] = d;
  17749. break;
  17750. default:
  17751. goto slow_path;
  17752. }
  17753. return true;
  17754. } else {
  17755. JSAtom atom;
  17756. int ret;
  17757. slow_path:
  17758. atom = JS_ValueToAtom(ctx, prop);
  17759. JS_FreeValue(ctx, prop);
  17760. if (unlikely(atom == JS_ATOM_NULL)) {
  17761. JS_FreeValue(ctx, val);
  17762. return -1;
  17763. }
  17764. ret = JS_SetPropertyInternal(ctx, this_obj, atom, val, flags);
  17765. JS_FreeAtom(ctx, atom);
  17766. return ret;
  17767. }
  17768. }
  17769. int JS_SetPropertyUint32(JSContext *ctx, JSValueConst this_obj,
  17770. uint32_t idx, JSValue val)
  17771. {
  17772. return JS_SetPropertyValue(ctx, this_obj, js_uint32(idx), val,
  17773. JS_PROP_THROW);
  17774. }
  17775. int JS_SetPropertyInt64(JSContext *ctx, JSValueConst this_obj,
  17776. int64_t idx, JSValue val)
  17777. {
  17778. JSAtom prop;
  17779. int res;
  17780. if ((uint64_t)idx <= INT32_MAX) {
  17781. /* fast path for fast arrays */
  17782. return JS_SetPropertyValue(ctx, this_obj, js_int32(idx), val,
  17783. JS_PROP_THROW);
  17784. }
  17785. prop = JS_NewAtomInt64(ctx, idx);
  17786. if (prop == JS_ATOM_NULL) {
  17787. JS_FreeValue(ctx, val);
  17788. return -1;
  17789. }
  17790. res = JS_SetProperty(ctx, this_obj, prop, val);
  17791. JS_FreeAtom(ctx, prop);
  17792. return res;
  17793. }
  17794. /* `prop` may be pure ASCII or UTF-8 encoded */
  17795. int JS_SetPropertyStr(JSContext *ctx, JSValueConst this_obj,
  17796. const char *prop, JSValue val)
  17797. {
  17798. JSAtom atom;
  17799. int ret;
  17800. atom = JS_NewAtom(ctx, prop);
  17801. ret = JS_SetPropertyInternal(ctx, this_obj, atom, val, JS_PROP_THROW);
  17802. JS_FreeAtom(ctx, atom);
  17803. return ret;
  17804. }
  17805. /* compute the property flags. For each flag: (JS_PROP_HAS_x forces
  17806. it, otherwise def_flags is used)
  17807. Note: makes assumption about the bit pattern of the flags
  17808. */
  17809. static int get_prop_flags(int flags, int def_flags)
  17810. {
  17811. int mask;
  17812. mask = (flags >> JS_PROP_HAS_SHIFT) & JS_PROP_C_W_E;
  17813. return (flags & mask) | (def_flags & ~mask);
  17814. }
  17815. static int JS_CreateProperty(JSContext *ctx, JSObject *p,
  17816. JSAtom prop, JSValueConst val,
  17817. JSValueConst getter, JSValueConst setter,
  17818. int flags)
  17819. {
  17820. JSProperty *pr;
  17821. int ret, prop_flags;
  17822. /* add a new property or modify an existing exotic one */
  17823. if (p->is_exotic) {
  17824. if (p->class_id == JS_CLASS_ARRAY) {
  17825. uint32_t idx, len;
  17826. if (p->fast_array) {
  17827. if (__JS_AtomIsTaggedInt(prop)) {
  17828. idx = __JS_AtomToUInt32(prop);
  17829. if (idx == p->u.array.count) {
  17830. if (!p->extensible)
  17831. goto not_extensible;
  17832. if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET))
  17833. goto convert_to_array;
  17834. prop_flags = get_prop_flags(flags, 0);
  17835. if (prop_flags != JS_PROP_C_W_E)
  17836. goto convert_to_array;
  17837. return add_fast_array_element(ctx, p,
  17838. js_dup(val), flags);
  17839. } else {
  17840. goto convert_to_array;
  17841. }
  17842. } else if (JS_AtomIsArrayIndex(ctx, &idx, prop)) {
  17843. /* convert the fast array to normal array */
  17844. convert_to_array:
  17845. if (convert_fast_array_to_array(ctx, p))
  17846. return -1;
  17847. goto generic_array;
  17848. }
  17849. } else if (JS_AtomIsArrayIndex(ctx, &idx, prop)) {
  17850. JSProperty *plen;
  17851. JSShapeProperty *pslen;
  17852. generic_array:
  17853. /* update the length field */
  17854. plen = &p->prop[0];
  17855. JS_ToUint32(ctx, &len, plen->u.value);
  17856. if ((idx + 1) > len) {
  17857. pslen = get_shape_prop(p->shape);
  17858. if (unlikely(!(pslen->flags & JS_PROP_WRITABLE)))
  17859. return JS_ThrowTypeErrorReadOnly(ctx, flags, JS_ATOM_length);
  17860. /* XXX: should update the length after defining
  17861. the property */
  17862. len = idx + 1;
  17863. set_value(ctx, &plen->u.value, js_uint32(len));
  17864. }
  17865. }
  17866. } else if (is_typed_array(p->class_id)) {
  17867. ret = JS_AtomIsNumericIndex(ctx, prop);
  17868. if (ret != 0) {
  17869. if (ret < 0)
  17870. return -1;
  17871. return JS_ThrowTypeErrorOrFalse(ctx, flags, "cannot create numeric index in typed array");
  17872. }
  17873. } else if (!(flags & JS_PROP_NO_EXOTIC)) {
  17874. const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic;
  17875. if (em) {
  17876. if (em->define_own_property) {
  17877. return em->define_own_property(ctx, JS_MKPTR(JS_TAG_OBJECT, p),
  17878. prop, val, getter, setter, flags);
  17879. }
  17880. ret = JS_IsExtensible(ctx, JS_MKPTR(JS_TAG_OBJECT, p));
  17881. if (ret < 0)
  17882. return -1;
  17883. if (!ret)
  17884. goto not_extensible;
  17885. }
  17886. }
  17887. }
  17888. if (!p->extensible) {
  17889. not_extensible:
  17890. return JS_ThrowTypeErrorOrFalse(ctx, flags, "object is not extensible");
  17891. }
  17892. if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET)) {
  17893. prop_flags = (flags & (JS_PROP_CONFIGURABLE | JS_PROP_ENUMERABLE)) |
  17894. JS_PROP_GETSET;
  17895. } else {
  17896. prop_flags = flags & JS_PROP_C_W_E;
  17897. }
  17898. pr = add_property(ctx, p, prop, prop_flags);
  17899. if (unlikely(!pr))
  17900. return -1;
  17901. if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET)) {
  17902. pr->u.getset.getter = NULL;
  17903. if ((flags & JS_PROP_HAS_GET) && JS_IsFunction(ctx, getter)) {
  17904. pr->u.getset.getter =
  17905. JS_VALUE_GET_OBJ(js_dup(getter));
  17906. }
  17907. pr->u.getset.setter = NULL;
  17908. if ((flags & JS_PROP_HAS_SET) && JS_IsFunction(ctx, setter)) {
  17909. pr->u.getset.setter =
  17910. JS_VALUE_GET_OBJ(js_dup(setter));
  17911. }
  17912. } else {
  17913. if (flags & JS_PROP_HAS_VALUE) {
  17914. pr->u.value = js_dup(val);
  17915. } else {
  17916. pr->u.value = JS_UNDEFINED;
  17917. }
  17918. }
  17919. return true;
  17920. }
  17921. /* return false if not OK */
  17922. static bool check_define_prop_flags(int prop_flags, int flags)
  17923. {
  17924. bool has_accessor, is_getset;
  17925. if (!(prop_flags & JS_PROP_CONFIGURABLE)) {
  17926. if ((flags & (JS_PROP_HAS_CONFIGURABLE | JS_PROP_CONFIGURABLE)) ==
  17927. (JS_PROP_HAS_CONFIGURABLE | JS_PROP_CONFIGURABLE)) {
  17928. return false;
  17929. }
  17930. if ((flags & JS_PROP_HAS_ENUMERABLE) &&
  17931. (flags & JS_PROP_ENUMERABLE) != (prop_flags & JS_PROP_ENUMERABLE))
  17932. return false;
  17933. }
  17934. if (flags & (JS_PROP_HAS_VALUE | JS_PROP_HAS_WRITABLE |
  17935. JS_PROP_HAS_GET | JS_PROP_HAS_SET)) {
  17936. if (!(prop_flags & JS_PROP_CONFIGURABLE)) {
  17937. has_accessor = ((flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET)) != 0);
  17938. is_getset = ((prop_flags & JS_PROP_TMASK) == JS_PROP_GETSET);
  17939. if (has_accessor != is_getset)
  17940. return false;
  17941. if (!has_accessor && !is_getset && !(prop_flags & JS_PROP_WRITABLE)) {
  17942. /* not writable: cannot set the writable bit */
  17943. if ((flags & (JS_PROP_HAS_WRITABLE | JS_PROP_WRITABLE)) ==
  17944. (JS_PROP_HAS_WRITABLE | JS_PROP_WRITABLE))
  17945. return false;
  17946. }
  17947. }
  17948. }
  17949. return true;
  17950. }
  17951. /* ensure that the shape can be safely modified */
  17952. static int js_shape_prepare_update(JSContext *ctx, JSObject *p,
  17953. JSShapeProperty **pprs)
  17954. {
  17955. JSShape *sh;
  17956. uint32_t idx = 0; /* prevent warning */
  17957. sh = p->shape;
  17958. if (sh->is_hashed) {
  17959. if (sh->header.ref_count != 1) {
  17960. if (pprs)
  17961. idx = *pprs - get_shape_prop(sh);
  17962. /* clone the shape (the resulting one is no longer hashed) */
  17963. sh = js_clone_shape(ctx, sh);
  17964. if (!sh)
  17965. return -1;
  17966. js_free_shape(ctx->rt, p->shape);
  17967. p->shape = sh;
  17968. if (pprs)
  17969. *pprs = get_shape_prop(sh) + idx;
  17970. } else {
  17971. js_shape_hash_unlink(ctx->rt, sh);
  17972. sh->is_hashed = false;
  17973. }
  17974. }
  17975. return 0;
  17976. }
  17977. static int js_update_property_flags(JSContext *ctx, JSObject *p,
  17978. JSShapeProperty **pprs, int flags)
  17979. {
  17980. if (flags != (*pprs)->flags) {
  17981. if (js_shape_prepare_update(ctx, p, pprs))
  17982. return -1;
  17983. (*pprs)->flags = flags;
  17984. }
  17985. return 0;
  17986. }
  17987. /* allowed flags:
  17988. JS_PROP_CONFIGURABLE, JS_PROP_WRITABLE, JS_PROP_ENUMERABLE
  17989. JS_PROP_HAS_GET, JS_PROP_HAS_SET, JS_PROP_HAS_VALUE,
  17990. JS_PROP_HAS_CONFIGURABLE, JS_PROP_HAS_WRITABLE, JS_PROP_HAS_ENUMERABLE,
  17991. JS_PROP_THROW, JS_PROP_NO_EXOTIC.
  17992. If JS_PROP_THROW is set, return an exception instead of false.
  17993. if JS_PROP_NO_EXOTIC is set, do not call the exotic
  17994. define_own_property callback.
  17995. return -1 (exception), false or true.
  17996. */
  17997. int JS_DefineProperty(JSContext *ctx, JSValueConst this_obj,
  17998. JSAtom prop, JSValueConst val,
  17999. JSValueConst getter, JSValueConst setter, int flags)
  18000. {
  18001. JSObject *p;
  18002. JSShapeProperty *prs;
  18003. JSProperty *pr;
  18004. int mask, res;
  18005. if (JS_VALUE_GET_TAG(this_obj) != JS_TAG_OBJECT) {
  18006. JS_ThrowTypeErrorNotAnObject(ctx);
  18007. return -1;
  18008. }
  18009. p = JS_VALUE_GET_OBJ(this_obj);
  18010. redo_prop_update:
  18011. prs = find_own_property(&pr, p, prop);
  18012. if (prs) {
  18013. /* the range of the Array length property is always tested before */
  18014. if ((prs->flags & JS_PROP_LENGTH) && (flags & JS_PROP_HAS_VALUE)) {
  18015. uint32_t array_length;
  18016. if (JS_ToArrayLengthFree(ctx, &array_length,
  18017. js_dup(val), false)) {
  18018. return -1;
  18019. }
  18020. /* this code relies on the fact that Uint32 are never allocated */
  18021. val = js_uint32(array_length);
  18022. /* prs may have been modified */
  18023. prs = find_own_property(&pr, p, prop);
  18024. assert(prs != NULL);
  18025. }
  18026. /* property already exists */
  18027. if (!check_define_prop_flags(prs->flags, flags)) {
  18028. not_configurable:
  18029. return JS_ThrowTypeErrorOrFalse(ctx, flags, "property is not configurable");
  18030. }
  18031. if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) {
  18032. /* Instantiate property and retry */
  18033. if (JS_AutoInitProperty(ctx, p, prop, pr, prs))
  18034. return -1;
  18035. goto redo_prop_update;
  18036. }
  18037. if (flags & (JS_PROP_HAS_VALUE | JS_PROP_HAS_WRITABLE |
  18038. JS_PROP_HAS_GET | JS_PROP_HAS_SET)) {
  18039. if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET)) {
  18040. JSObject *new_getter, *new_setter;
  18041. if (JS_IsFunction(ctx, getter)) {
  18042. new_getter = JS_VALUE_GET_OBJ(getter);
  18043. } else {
  18044. new_getter = NULL;
  18045. }
  18046. if (JS_IsFunction(ctx, setter)) {
  18047. new_setter = JS_VALUE_GET_OBJ(setter);
  18048. } else {
  18049. new_setter = NULL;
  18050. }
  18051. if ((prs->flags & JS_PROP_TMASK) != JS_PROP_GETSET) {
  18052. if (js_shape_prepare_update(ctx, p, &prs))
  18053. return -1;
  18054. /* convert to getset */
  18055. if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) {
  18056. free_var_ref(ctx->rt, pr->u.var_ref);
  18057. } else {
  18058. JS_FreeValue(ctx, pr->u.value);
  18059. }
  18060. prs->flags = (prs->flags &
  18061. (JS_PROP_CONFIGURABLE | JS_PROP_ENUMERABLE)) |
  18062. JS_PROP_GETSET;
  18063. pr->u.getset.getter = NULL;
  18064. pr->u.getset.setter = NULL;
  18065. } else {
  18066. if (!(prs->flags & JS_PROP_CONFIGURABLE)) {
  18067. if ((flags & JS_PROP_HAS_GET) &&
  18068. new_getter != pr->u.getset.getter) {
  18069. goto not_configurable;
  18070. }
  18071. if ((flags & JS_PROP_HAS_SET) &&
  18072. new_setter != pr->u.getset.setter) {
  18073. goto not_configurable;
  18074. }
  18075. }
  18076. }
  18077. if (flags & JS_PROP_HAS_GET) {
  18078. if (pr->u.getset.getter)
  18079. JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.getter));
  18080. if (new_getter)
  18081. js_dup(getter);
  18082. pr->u.getset.getter = new_getter;
  18083. }
  18084. if (flags & JS_PROP_HAS_SET) {
  18085. if (pr->u.getset.setter)
  18086. JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.setter));
  18087. if (new_setter)
  18088. js_dup(setter);
  18089. pr->u.getset.setter = new_setter;
  18090. }
  18091. } else {
  18092. if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) {
  18093. /* convert to data descriptor */
  18094. if (js_shape_prepare_update(ctx, p, &prs))
  18095. return -1;
  18096. if (pr->u.getset.getter)
  18097. JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.getter));
  18098. if (pr->u.getset.setter)
  18099. JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.setter));
  18100. prs->flags &= ~(JS_PROP_TMASK | JS_PROP_WRITABLE);
  18101. pr->u.value = JS_UNDEFINED;
  18102. } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) {
  18103. /* Note: JS_PROP_VARREF is always writable */
  18104. } else {
  18105. if ((prs->flags & (JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE)) == 0 &&
  18106. (flags & JS_PROP_HAS_VALUE)) {
  18107. if (!js_same_value(ctx, val, pr->u.value)) {
  18108. goto not_configurable;
  18109. } else {
  18110. return true;
  18111. }
  18112. }
  18113. }
  18114. if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) {
  18115. if (flags & JS_PROP_HAS_VALUE) {
  18116. if (p->class_id == JS_CLASS_MODULE_NS) {
  18117. /* JS_PROP_WRITABLE is always true for variable
  18118. references, but they are write protected in module name
  18119. spaces. */
  18120. if (!js_same_value(ctx, val, *pr->u.var_ref->pvalue))
  18121. goto not_configurable;
  18122. }
  18123. /* update the reference */
  18124. set_value(ctx, pr->u.var_ref->pvalue, js_dup(val));
  18125. }
  18126. /* if writable is set to false, no longer a
  18127. reference (for mapped arguments) */
  18128. if ((flags & (JS_PROP_HAS_WRITABLE | JS_PROP_WRITABLE)) == JS_PROP_HAS_WRITABLE) {
  18129. JSValue val1;
  18130. if (js_shape_prepare_update(ctx, p, &prs))
  18131. return -1;
  18132. val1 = js_dup(*pr->u.var_ref->pvalue);
  18133. free_var_ref(ctx->rt, pr->u.var_ref);
  18134. pr->u.value = val1;
  18135. prs->flags &= ~(JS_PROP_TMASK | JS_PROP_WRITABLE);
  18136. }
  18137. } else if (prs->flags & JS_PROP_LENGTH) {
  18138. if (flags & JS_PROP_HAS_VALUE) {
  18139. /* Note: no JS code is executable because
  18140. 'val' is guaranted to be a Uint32 */
  18141. res = set_array_length(ctx, p, js_dup(val), flags);
  18142. } else {
  18143. res = true;
  18144. }
  18145. /* still need to reset the writable flag if
  18146. needed. The JS_PROP_LENGTH is kept because the
  18147. Uint32 test is still done if the length
  18148. property is read-only. */
  18149. if ((flags & (JS_PROP_HAS_WRITABLE | JS_PROP_WRITABLE)) ==
  18150. JS_PROP_HAS_WRITABLE) {
  18151. prs = get_shape_prop(p->shape);
  18152. if (js_update_property_flags(ctx, p, &prs,
  18153. prs->flags & ~JS_PROP_WRITABLE))
  18154. return -1;
  18155. }
  18156. return res;
  18157. } else {
  18158. if (flags & JS_PROP_HAS_VALUE) {
  18159. JS_FreeValue(ctx, pr->u.value);
  18160. pr->u.value = js_dup(val);
  18161. }
  18162. if (flags & JS_PROP_HAS_WRITABLE) {
  18163. if (js_update_property_flags(ctx, p, &prs,
  18164. (prs->flags & ~JS_PROP_WRITABLE) |
  18165. (flags & JS_PROP_WRITABLE)))
  18166. return -1;
  18167. }
  18168. }
  18169. }
  18170. }
  18171. mask = 0;
  18172. if (flags & JS_PROP_HAS_CONFIGURABLE)
  18173. mask |= JS_PROP_CONFIGURABLE;
  18174. if (flags & JS_PROP_HAS_ENUMERABLE)
  18175. mask |= JS_PROP_ENUMERABLE;
  18176. if (js_update_property_flags(ctx, p, &prs,
  18177. (prs->flags & ~mask) | (flags & mask)))
  18178. return -1;
  18179. return true;
  18180. }
  18181. /* handle modification of fast array elements */
  18182. if (p->fast_array) {
  18183. uint32_t idx;
  18184. uint32_t prop_flags;
  18185. if (p->class_id == JS_CLASS_ARRAY) {
  18186. if (__JS_AtomIsTaggedInt(prop)) {
  18187. idx = __JS_AtomToUInt32(prop);
  18188. if (idx < p->u.array.count) {
  18189. prop_flags = get_prop_flags(flags, JS_PROP_C_W_E);
  18190. if (prop_flags != JS_PROP_C_W_E)
  18191. goto convert_to_slow_array;
  18192. if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET)) {
  18193. convert_to_slow_array:
  18194. if (convert_fast_array_to_array(ctx, p))
  18195. return -1;
  18196. else
  18197. goto redo_prop_update;
  18198. }
  18199. if (flags & JS_PROP_HAS_VALUE) {
  18200. set_value(ctx, &p->u.array.u.values[idx], js_dup(val));
  18201. }
  18202. return true;
  18203. }
  18204. }
  18205. } else if (is_typed_array(p->class_id)) {
  18206. JSValue num;
  18207. int ret;
  18208. if (!__JS_AtomIsTaggedInt(prop)) {
  18209. /* slow path with to handle all numeric indexes */
  18210. num = JS_AtomIsNumericIndex1(ctx, prop);
  18211. if (JS_IsUndefined(num))
  18212. goto typed_array_done;
  18213. if (JS_IsException(num))
  18214. return -1;
  18215. ret = JS_NumberIsInteger(ctx, num);
  18216. if (ret < 0) {
  18217. JS_FreeValue(ctx, num);
  18218. return -1;
  18219. }
  18220. if (!ret) {
  18221. JS_FreeValue(ctx, num);
  18222. return JS_ThrowTypeErrorOrFalse(ctx, flags, "non integer index in typed array");
  18223. }
  18224. ret = JS_NumberIsNegativeOrMinusZero(ctx, num);
  18225. JS_FreeValue(ctx, num);
  18226. if (ret) {
  18227. return JS_ThrowTypeErrorOrFalse(ctx, flags, "negative index in typed array");
  18228. }
  18229. if (!__JS_AtomIsTaggedInt(prop))
  18230. goto typed_array_oob;
  18231. }
  18232. idx = __JS_AtomToUInt32(prop);
  18233. /* if the typed array is detached, p->u.array.count = 0 */
  18234. if (idx >= typed_array_get_length(ctx, p)) {
  18235. typed_array_oob:
  18236. return JS_ThrowTypeErrorOrFalse(ctx, flags, "out-of-bound index in typed array");
  18237. }
  18238. prop_flags = get_prop_flags(flags, JS_PROP_ENUMERABLE | JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);
  18239. if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET) ||
  18240. prop_flags != (JS_PROP_ENUMERABLE | JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE)) {
  18241. return JS_ThrowTypeErrorOrFalse(ctx, flags, "invalid descriptor flags");
  18242. }
  18243. if (flags & JS_PROP_HAS_VALUE) {
  18244. return JS_SetPropertyValue(ctx, this_obj, js_int32(idx), js_dup(val), flags);
  18245. }
  18246. return true;
  18247. typed_array_done: ;
  18248. }
  18249. }
  18250. return JS_CreateProperty(ctx, p, prop, val, getter, setter, flags);
  18251. }
  18252. static int JS_DefineAutoInitProperty(JSContext *ctx, JSValueConst this_obj,
  18253. JSAtom prop, JSAutoInitIDEnum id,
  18254. void *opaque, int flags)
  18255. {
  18256. JSObject *p;
  18257. JSProperty *pr;
  18258. if (JS_VALUE_GET_TAG(this_obj) != JS_TAG_OBJECT)
  18259. return false;
  18260. p = JS_VALUE_GET_OBJ(this_obj);
  18261. if (find_own_property(&pr, p, prop)) {
  18262. /* property already exists */
  18263. abort();
  18264. return false;
  18265. }
  18266. /* Specialized CreateProperty */
  18267. pr = add_property(ctx, p, prop, (flags & JS_PROP_C_W_E) | JS_PROP_AUTOINIT);
  18268. if (unlikely(!pr))
  18269. return -1;
  18270. pr->u.init.realm_and_id = (uintptr_t)JS_DupContext(ctx);
  18271. assert((pr->u.init.realm_and_id & 3) == 0);
  18272. assert(id <= 3);
  18273. pr->u.init.realm_and_id |= id;
  18274. pr->u.init.opaque = opaque;
  18275. return true;
  18276. }
  18277. /* shortcut to add or redefine a new property value */
  18278. int JS_DefinePropertyValue(JSContext *ctx, JSValueConst this_obj,
  18279. JSAtom prop, JSValue val, int flags)
  18280. {
  18281. int ret;
  18282. ret = JS_DefineProperty(ctx, this_obj, prop, val, JS_UNDEFINED, JS_UNDEFINED,
  18283. flags | JS_PROP_HAS_VALUE | JS_PROP_HAS_CONFIGURABLE | JS_PROP_HAS_WRITABLE | JS_PROP_HAS_ENUMERABLE);
  18284. JS_FreeValue(ctx, val);
  18285. return ret;
  18286. }
  18287. int JS_DefinePropertyValueValue(JSContext *ctx, JSValueConst this_obj,
  18288. JSValue prop, JSValue val, int flags)
  18289. {
  18290. JSAtom atom;
  18291. int ret;
  18292. atom = JS_ValueToAtom(ctx, prop);
  18293. JS_FreeValue(ctx, prop);
  18294. if (unlikely(atom == JS_ATOM_NULL)) {
  18295. JS_FreeValue(ctx, val);
  18296. return -1;
  18297. }
  18298. ret = JS_DefinePropertyValue(ctx, this_obj, atom, val, flags);
  18299. JS_FreeAtom(ctx, atom);
  18300. return ret;
  18301. }
  18302. int JS_DefinePropertyValueUint32(JSContext *ctx, JSValueConst this_obj,
  18303. uint32_t idx, JSValue val, int flags)
  18304. {
  18305. return JS_DefinePropertyValueValue(ctx, this_obj, js_uint32(idx),
  18306. val, flags);
  18307. }
  18308. int JS_DefinePropertyValueInt64(JSContext *ctx, JSValueConst this_obj,
  18309. int64_t idx, JSValue val, int flags)
  18310. {
  18311. return JS_DefinePropertyValueValue(ctx, this_obj, js_int64(idx),
  18312. val, flags);
  18313. }
  18314. /* `prop` may be pure ASCII or UTF-8 encoded */
  18315. int JS_DefinePropertyValueStr(JSContext *ctx, JSValueConst this_obj,
  18316. const char *prop, JSValue val, int flags)
  18317. {
  18318. JSAtom atom;
  18319. int ret;
  18320. atom = JS_NewAtom(ctx, prop);
  18321. ret = JS_DefinePropertyValue(ctx, this_obj, atom, val, flags);
  18322. JS_FreeAtom(ctx, atom);
  18323. return ret;
  18324. }
  18325. /* shortcut to add getter & setter */
  18326. int JS_DefinePropertyGetSet(JSContext *ctx, JSValueConst this_obj,
  18327. JSAtom prop, JSValue getter, JSValue setter,
  18328. int flags)
  18329. {
  18330. int ret;
  18331. ret = JS_DefineProperty(ctx, this_obj, prop, JS_UNDEFINED, getter, setter,
  18332. flags | JS_PROP_HAS_GET | JS_PROP_HAS_SET |
  18333. JS_PROP_HAS_CONFIGURABLE | JS_PROP_HAS_ENUMERABLE);
  18334. JS_FreeValue(ctx, getter);
  18335. JS_FreeValue(ctx, setter);
  18336. return ret;
  18337. }
  18338. static int JS_CreateDataPropertyUint32(JSContext *ctx, JSValueConst this_obj,
  18339. int64_t idx, JSValue val, int flags)
  18340. {
  18341. return JS_DefinePropertyValueValue(ctx, this_obj, js_int64(idx),
  18342. val, flags | JS_PROP_CONFIGURABLE |
  18343. JS_PROP_ENUMERABLE | JS_PROP_WRITABLE);
  18344. }
  18345. /* return true if 'obj' has a non empty 'name' string */
  18346. static bool js_object_has_name(JSContext *ctx, JSValue obj)
  18347. {
  18348. JSProperty *pr;
  18349. JSShapeProperty *prs;
  18350. JSValue val;
  18351. JSString *p;
  18352. prs = find_own_property(&pr, JS_VALUE_GET_OBJ(obj), JS_ATOM_name);
  18353. if (!prs)
  18354. return false;
  18355. if ((prs->flags & JS_PROP_TMASK) != JS_PROP_NORMAL)
  18356. return true;
  18357. val = pr->u.value;
  18358. if (JS_VALUE_GET_TAG(val) != JS_TAG_STRING)
  18359. return true;
  18360. p = JS_VALUE_GET_STRING(val);
  18361. return (p->len != 0);
  18362. }
  18363. static int JS_DefineObjectName(JSContext *ctx, JSValue obj,
  18364. JSAtom name, int flags)
  18365. {
  18366. if (name != JS_ATOM_NULL
  18367. && JS_IsObject(obj)
  18368. && !js_object_has_name(ctx, obj)
  18369. && JS_DefinePropertyValue(ctx, obj, JS_ATOM_name, JS_AtomToString(ctx, name), flags) < 0) {
  18370. return -1;
  18371. }
  18372. return 0;
  18373. }
  18374. static int JS_DefineObjectNameComputed(JSContext *ctx, JSValue obj,
  18375. JSValue str, int flags)
  18376. {
  18377. if (JS_IsObject(obj) &&
  18378. !js_object_has_name(ctx, obj)) {
  18379. JSAtom prop;
  18380. JSValue name_str;
  18381. prop = JS_ValueToAtom(ctx, str);
  18382. if (prop == JS_ATOM_NULL)
  18383. return -1;
  18384. name_str = js_get_function_name(ctx, prop);
  18385. JS_FreeAtom(ctx, prop);
  18386. if (JS_IsException(name_str))
  18387. return -1;
  18388. if (JS_DefinePropertyValue(ctx, obj, JS_ATOM_name, name_str, flags) < 0)
  18389. return -1;
  18390. }
  18391. return 0;
  18392. }
  18393. #define DEFINE_GLOBAL_LEX_VAR (1 << 7)
  18394. #define DEFINE_GLOBAL_FUNC_VAR (1 << 6)
  18395. static JSValue JS_ThrowSyntaxErrorVarRedeclaration(JSContext *ctx, JSAtom prop)
  18396. {
  18397. return JS_ThrowSyntaxErrorAtom(ctx, "redeclaration of '%s'", prop);
  18398. }
  18399. /* flags is 0, DEFINE_GLOBAL_LEX_VAR or DEFINE_GLOBAL_FUNC_VAR */
  18400. /* XXX: could support exotic global object. */
  18401. static int JS_CheckDefineGlobalVar(JSContext *ctx, JSAtom prop, int flags)
  18402. {
  18403. JSObject *p;
  18404. JSShapeProperty *prs;
  18405. p = JS_VALUE_GET_OBJ(ctx->global_obj);
  18406. prs = find_own_property1(p, prop);
  18407. /* XXX: should handle JS_PROP_AUTOINIT */
  18408. if (flags & DEFINE_GLOBAL_LEX_VAR) {
  18409. if (prs && !(prs->flags & JS_PROP_CONFIGURABLE))
  18410. goto fail_redeclaration;
  18411. } else {
  18412. if (!prs && !p->extensible)
  18413. goto define_error;
  18414. if (flags & DEFINE_GLOBAL_FUNC_VAR) {
  18415. if (prs) {
  18416. if (!(prs->flags & JS_PROP_CONFIGURABLE) &&
  18417. ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET ||
  18418. ((prs->flags & (JS_PROP_WRITABLE | JS_PROP_ENUMERABLE)) !=
  18419. (JS_PROP_WRITABLE | JS_PROP_ENUMERABLE)))) {
  18420. define_error:
  18421. JS_ThrowTypeErrorAtom(ctx, "cannot define variable '%s'",
  18422. prop);
  18423. return -1;
  18424. }
  18425. }
  18426. }
  18427. }
  18428. /* check if there already is a lexical declaration */
  18429. p = JS_VALUE_GET_OBJ(ctx->global_var_obj);
  18430. prs = find_own_property1(p, prop);
  18431. if (prs) {
  18432. fail_redeclaration:
  18433. JS_ThrowSyntaxErrorVarRedeclaration(ctx, prop);
  18434. return -1;
  18435. }
  18436. return 0;
  18437. }
  18438. /* def_flags is (0, DEFINE_GLOBAL_LEX_VAR) |
  18439. JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE */
  18440. /* XXX: could support exotic global object. */
  18441. static int JS_DefineGlobalVar(JSContext *ctx, JSAtom prop, int def_flags)
  18442. {
  18443. JSObject *p;
  18444. JSShapeProperty *prs;
  18445. JSProperty *pr;
  18446. JSValue val;
  18447. int flags;
  18448. if (def_flags & DEFINE_GLOBAL_LEX_VAR) {
  18449. p = JS_VALUE_GET_OBJ(ctx->global_var_obj);
  18450. flags = JS_PROP_ENUMERABLE | (def_flags & JS_PROP_WRITABLE) |
  18451. JS_PROP_CONFIGURABLE;
  18452. val = JS_UNINITIALIZED;
  18453. } else {
  18454. p = JS_VALUE_GET_OBJ(ctx->global_obj);
  18455. flags = JS_PROP_ENUMERABLE | JS_PROP_WRITABLE |
  18456. (def_flags & JS_PROP_CONFIGURABLE);
  18457. val = JS_UNDEFINED;
  18458. }
  18459. prs = find_own_property1(p, prop);
  18460. if (prs)
  18461. return 0;
  18462. if (!p->extensible)
  18463. return 0;
  18464. pr = add_property(ctx, p, prop, flags);
  18465. if (unlikely(!pr))
  18466. return -1;
  18467. pr->u.value = val;
  18468. return 0;
  18469. }
  18470. /* 'def_flags' is 0 or JS_PROP_CONFIGURABLE. */
  18471. /* XXX: could support exotic global object. */
  18472. static int JS_DefineGlobalFunction(JSContext *ctx, JSAtom prop,
  18473. JSValue func, int def_flags)
  18474. {
  18475. JSObject *p;
  18476. JSShapeProperty *prs;
  18477. int flags;
  18478. p = JS_VALUE_GET_OBJ(ctx->global_obj);
  18479. prs = find_own_property1(p, prop);
  18480. flags = JS_PROP_HAS_VALUE | JS_PROP_THROW;
  18481. if (!prs || (prs->flags & JS_PROP_CONFIGURABLE)) {
  18482. flags |= JS_PROP_ENUMERABLE | JS_PROP_WRITABLE | def_flags |
  18483. JS_PROP_HAS_CONFIGURABLE | JS_PROP_HAS_WRITABLE | JS_PROP_HAS_ENUMERABLE;
  18484. }
  18485. if (JS_DefineProperty(ctx, ctx->global_obj, prop, func,
  18486. JS_UNDEFINED, JS_UNDEFINED, flags) < 0)
  18487. return -1;
  18488. return 0;
  18489. }
  18490. static JSValue JS_GetGlobalVar(JSContext *ctx, JSAtom prop,
  18491. bool throw_ref_error)
  18492. {
  18493. JSObject *p;
  18494. JSShapeProperty *prs;
  18495. JSProperty *pr;
  18496. /* no exotic behavior is possible in global_var_obj */
  18497. p = JS_VALUE_GET_OBJ(ctx->global_var_obj);
  18498. prs = find_own_property(&pr, p, prop);
  18499. if (prs) {
  18500. /* XXX: should handle JS_PROP_TMASK properties */
  18501. if (unlikely(JS_IsUninitialized(pr->u.value)))
  18502. return JS_ThrowReferenceErrorUninitialized(ctx, prs->atom);
  18503. return js_dup(pr->u.value);
  18504. }
  18505. return JS_GetPropertyInternal(ctx, ctx->global_obj, prop,
  18506. ctx->global_obj, throw_ref_error);
  18507. }
  18508. /* construct a reference to a global variable */
  18509. static int JS_GetGlobalVarRef(JSContext *ctx, JSAtom prop, JSValue *sp)
  18510. {
  18511. JSObject *p;
  18512. JSShapeProperty *prs;
  18513. JSProperty *pr;
  18514. /* no exotic behavior is possible in global_var_obj */
  18515. p = JS_VALUE_GET_OBJ(ctx->global_var_obj);
  18516. prs = find_own_property(&pr, p, prop);
  18517. if (prs) {
  18518. /* XXX: should handle JS_PROP_AUTOINIT properties? */
  18519. /* XXX: conformance: do these tests in
  18520. OP_put_var_ref/OP_get_var_ref ? */
  18521. if (unlikely(JS_IsUninitialized(pr->u.value))) {
  18522. JS_ThrowReferenceErrorUninitialized(ctx, prs->atom);
  18523. return -1;
  18524. }
  18525. if (unlikely(!(prs->flags & JS_PROP_WRITABLE))) {
  18526. return JS_ThrowTypeErrorReadOnly(ctx, JS_PROP_THROW, prop);
  18527. }
  18528. sp[0] = js_dup(ctx->global_var_obj);
  18529. } else {
  18530. int ret;
  18531. ret = JS_HasProperty(ctx, ctx->global_obj, prop);
  18532. if (ret < 0)
  18533. return -1;
  18534. if (ret) {
  18535. sp[0] = js_dup(ctx->global_obj);
  18536. } else {
  18537. sp[0] = JS_UNDEFINED;
  18538. }
  18539. }
  18540. sp[1] = JS_AtomToValue(ctx, prop);
  18541. return 0;
  18542. }
  18543. /* use for strict variable access: test if the variable exists */
  18544. static int JS_CheckGlobalVar(JSContext *ctx, JSAtom prop)
  18545. {
  18546. JSObject *p;
  18547. JSShapeProperty *prs;
  18548. int ret;
  18549. /* no exotic behavior is possible in global_var_obj */
  18550. p = JS_VALUE_GET_OBJ(ctx->global_var_obj);
  18551. prs = find_own_property1(p, prop);
  18552. if (prs) {
  18553. ret = true;
  18554. } else {
  18555. ret = JS_HasProperty(ctx, ctx->global_obj, prop);
  18556. if (ret < 0)
  18557. return -1;
  18558. }
  18559. return ret;
  18560. }
  18561. /* flag = 0: normal variable write
  18562. flag = 1: initialize lexical variable
  18563. flag = 2: normal variable write, strict check was done before
  18564. */
  18565. static int JS_SetGlobalVar(JSContext *ctx, JSAtom prop, JSValue val,
  18566. int flag)
  18567. {
  18568. JSObject *p;
  18569. JSShapeProperty *prs;
  18570. JSProperty *pr;
  18571. int flags;
  18572. /* no exotic behavior is possible in global_var_obj */
  18573. p = JS_VALUE_GET_OBJ(ctx->global_var_obj);
  18574. prs = find_own_property(&pr, p, prop);
  18575. if (prs) {
  18576. /* XXX: should handle JS_PROP_AUTOINIT properties? */
  18577. if (flag != 1) {
  18578. if (unlikely(JS_IsUninitialized(pr->u.value))) {
  18579. JS_FreeValue(ctx, val);
  18580. JS_ThrowReferenceErrorUninitialized(ctx, prs->atom);
  18581. return -1;
  18582. }
  18583. if (unlikely(!(prs->flags & JS_PROP_WRITABLE))) {
  18584. JS_FreeValue(ctx, val);
  18585. return JS_ThrowTypeErrorReadOnly(ctx, JS_PROP_THROW, prop);
  18586. }
  18587. }
  18588. set_value(ctx, &pr->u.value, val);
  18589. return 0;
  18590. }
  18591. flags = JS_PROP_THROW_STRICT;
  18592. if (is_strict_mode(ctx))
  18593. flags |= JS_PROP_NO_ADD;
  18594. return JS_SetPropertyInternal(ctx, ctx->global_obj, prop, val, flags);
  18595. }
  18596. /* return -1, false or true. return false if not configurable or
  18597. invalid object. return -1 in case of exception.
  18598. flags can be 0, JS_PROP_THROW or JS_PROP_THROW_STRICT */
  18599. int JS_DeleteProperty(JSContext *ctx, JSValueConst obj, JSAtom prop, int flags)
  18600. {
  18601. JSValue obj1;
  18602. JSObject *p;
  18603. int res;
  18604. obj1 = JS_ToObject(ctx, obj);
  18605. if (JS_IsException(obj1))
  18606. return -1;
  18607. p = JS_VALUE_GET_OBJ(obj1);
  18608. res = delete_property(ctx, p, prop);
  18609. JS_FreeValue(ctx, obj1);
  18610. if (res != false)
  18611. return res;
  18612. if ((flags & JS_PROP_THROW) ||
  18613. ((flags & JS_PROP_THROW_STRICT) && is_strict_mode(ctx))) {
  18614. JS_ThrowTypeError(ctx, "could not delete property");
  18615. return -1;
  18616. }
  18617. return false;
  18618. }
  18619. int JS_DeletePropertyInt64(JSContext *ctx, JSValueConst obj, int64_t idx, int flags)
  18620. {
  18621. JSAtom prop;
  18622. int res;
  18623. if ((uint64_t)idx <= JS_ATOM_MAX_INT) {
  18624. /* fast path for fast arrays */
  18625. return JS_DeleteProperty(ctx, obj, __JS_AtomFromUInt32(idx), flags);
  18626. }
  18627. prop = JS_NewAtomInt64(ctx, idx);
  18628. if (prop == JS_ATOM_NULL)
  18629. return -1;
  18630. res = JS_DeleteProperty(ctx, obj, prop, flags);
  18631. JS_FreeAtom(ctx, prop);
  18632. return res;
  18633. }
  18634. bool JS_IsFunction(JSContext *ctx, JSValueConst val)
  18635. {
  18636. JSObject *p;
  18637. if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT)
  18638. return false;
  18639. p = JS_VALUE_GET_OBJ(val);
  18640. switch(p->class_id) {
  18641. case JS_CLASS_BYTECODE_FUNCTION:
  18642. return true;
  18643. case JS_CLASS_PROXY:
  18644. return p->u.proxy_data->is_func;
  18645. default:
  18646. return (ctx->rt->class_array[p->class_id].call != NULL);
  18647. }
  18648. }
  18649. static bool JS_IsCFunction(JSContext *ctx, JSValueConst val, JSCFunction *func,
  18650. int magic)
  18651. {
  18652. JSObject *p;
  18653. if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT)
  18654. return false;
  18655. p = JS_VALUE_GET_OBJ(val);
  18656. if (p->class_id == JS_CLASS_C_FUNCTION)
  18657. return (p->u.cfunc.c_function.generic == func && p->u.cfunc.magic == magic);
  18658. else
  18659. return false;
  18660. }
  18661. bool JS_IsConstructor(JSContext *ctx, JSValueConst val)
  18662. {
  18663. JSObject *p;
  18664. if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT)
  18665. return false;
  18666. p = JS_VALUE_GET_OBJ(val);
  18667. return p->is_constructor;
  18668. }
  18669. bool JS_SetConstructorBit(JSContext *ctx, JSValueConst func_obj, bool val)
  18670. {
  18671. JSObject *p;
  18672. if (JS_VALUE_GET_TAG(func_obj) != JS_TAG_OBJECT)
  18673. return false;
  18674. p = JS_VALUE_GET_OBJ(func_obj);
  18675. p->is_constructor = val;
  18676. return true;
  18677. }
  18678. bool JS_IsRegExp(JSValueConst val)
  18679. {
  18680. if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT)
  18681. return false;
  18682. return JS_VALUE_GET_OBJ(val)->class_id == JS_CLASS_REGEXP;
  18683. }
  18684. bool JS_IsMap(JSValueConst val)
  18685. {
  18686. if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT)
  18687. return false;
  18688. return JS_VALUE_GET_OBJ(val)->class_id == JS_CLASS_MAP;
  18689. }
  18690. bool JS_IsError(JSContext *ctx, JSValueConst val)
  18691. {
  18692. JSObject *p;
  18693. if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT)
  18694. return false;
  18695. p = JS_VALUE_GET_OBJ(val);
  18696. return (p->class_id == JS_CLASS_ERROR);
  18697. }
  18698. /* used to avoid catching interrupt exceptions */
  18699. bool JS_IsUncatchableError(JSContext *ctx, JSValueConst val)
  18700. {
  18701. JSObject *p;
  18702. if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT)
  18703. return false;
  18704. p = JS_VALUE_GET_OBJ(val);
  18705. return p->class_id == JS_CLASS_ERROR && p->is_uncatchable_error;
  18706. }
  18707. static void js_set_uncatchable_error(JSContext *ctx, JSValueConst val, bool flag)
  18708. {
  18709. JSObject *p;
  18710. if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT)
  18711. return;
  18712. p = JS_VALUE_GET_OBJ(val);
  18713. if (p->class_id == JS_CLASS_ERROR)
  18714. p->is_uncatchable_error = flag;
  18715. }
  18716. void JS_SetUncatchableError(JSContext *ctx, JSValueConst val)
  18717. {
  18718. js_set_uncatchable_error(ctx, val, true);
  18719. }
  18720. void JS_ClearUncatchableError(JSContext *ctx, JSValueConst val)
  18721. {
  18722. js_set_uncatchable_error(ctx, val, false);
  18723. }
  18724. void JS_ResetUncatchableError(JSContext *ctx)
  18725. {
  18726. js_set_uncatchable_error(ctx, ctx->rt->current_exception, false);
  18727. }
  18728. int JS_SetOpaque(JSValueConst obj, void *opaque)
  18729. {
  18730. JSObject *p;
  18731. if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) {
  18732. p = JS_VALUE_GET_OBJ(obj);
  18733. // User code can't set the opaque of internal objects.
  18734. if (p->class_id >= JS_CLASS_INIT_COUNT) {
  18735. p->u.opaque = opaque;
  18736. return 0;
  18737. }
  18738. }
  18739. return -1;
  18740. }
  18741. /* |obj| must be a JSObject of an internal class. */
  18742. static void JS_SetOpaqueInternal(JSValueConst obj, void *opaque)
  18743. {
  18744. JSObject *p;
  18745. assert(JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT);
  18746. p = JS_VALUE_GET_OBJ(obj);
  18747. assert(p->class_id < JS_CLASS_INIT_COUNT);
  18748. p->u.opaque = opaque;
  18749. }
  18750. /* return NULL if not an object of class class_id */
  18751. void *JS_GetOpaque(JSValueConst obj, JSClassID class_id)
  18752. {
  18753. JSObject *p;
  18754. if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)
  18755. return NULL;
  18756. p = JS_VALUE_GET_OBJ(obj);
  18757. if (p->class_id != class_id)
  18758. return NULL;
  18759. return p->u.opaque;
  18760. }
  18761. void *JS_GetOpaque2(JSContext *ctx, JSValueConst obj, JSClassID class_id)
  18762. {
  18763. void *p = JS_GetOpaque(obj, class_id);
  18764. if (unlikely(!p)) {
  18765. JS_ThrowTypeErrorInvalidClass(ctx, class_id);
  18766. }
  18767. return p;
  18768. }
  18769. void *JS_GetAnyOpaque(JSValueConst obj, JSClassID *class_id)
  18770. {
  18771. JSObject *p;
  18772. if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) {
  18773. *class_id = 0;
  18774. return NULL;
  18775. }
  18776. p = JS_VALUE_GET_OBJ(obj);
  18777. *class_id = p->class_id;
  18778. return p->u.opaque;
  18779. }
  18780. static JSValue JS_ToPrimitiveFree(JSContext *ctx, JSValue val, int hint)
  18781. {
  18782. int i;
  18783. bool force_ordinary;
  18784. JSAtom method_name;
  18785. JSValue method, ret;
  18786. if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT)
  18787. return val;
  18788. force_ordinary = hint & HINT_FORCE_ORDINARY;
  18789. hint &= ~HINT_FORCE_ORDINARY;
  18790. if (!force_ordinary) {
  18791. method = JS_GetProperty(ctx, val, JS_ATOM_Symbol_toPrimitive);
  18792. if (JS_IsException(method))
  18793. goto exception;
  18794. /* ECMA says *If exoticToPrim is not undefined* but tests in
  18795. test262 use null as a non callable converter */
  18796. if (!JS_IsUndefined(method) && !JS_IsNull(method)) {
  18797. JSAtom atom;
  18798. JSValue arg;
  18799. switch(hint) {
  18800. case HINT_STRING:
  18801. atom = JS_ATOM_string;
  18802. break;
  18803. case HINT_NUMBER:
  18804. atom = JS_ATOM_number;
  18805. break;
  18806. default:
  18807. case HINT_NONE:
  18808. atom = JS_ATOM_default;
  18809. break;
  18810. }
  18811. arg = JS_AtomToString(ctx, atom);
  18812. ret = JS_CallFree(ctx, method, val, 1, vc(&arg));
  18813. JS_FreeValue(ctx, arg);
  18814. if (JS_IsException(ret))
  18815. goto exception;
  18816. JS_FreeValue(ctx, val);
  18817. if (JS_VALUE_GET_TAG(ret) != JS_TAG_OBJECT)
  18818. return ret;
  18819. JS_FreeValue(ctx, ret);
  18820. return JS_ThrowTypeError(ctx, "toPrimitive");
  18821. }
  18822. }
  18823. if (hint != HINT_STRING)
  18824. hint = HINT_NUMBER;
  18825. for(i = 0; i < 2; i++) {
  18826. if ((i ^ hint) == 0) {
  18827. method_name = JS_ATOM_toString;
  18828. } else {
  18829. method_name = JS_ATOM_valueOf;
  18830. }
  18831. method = JS_GetProperty(ctx, val, method_name);
  18832. if (JS_IsException(method))
  18833. goto exception;
  18834. if (JS_IsFunction(ctx, method)) {
  18835. ret = JS_CallFree(ctx, method, val, 0, NULL);
  18836. if (JS_IsException(ret))
  18837. goto exception;
  18838. if (JS_VALUE_GET_TAG(ret) != JS_TAG_OBJECT) {
  18839. JS_FreeValue(ctx, val);
  18840. return ret;
  18841. }
  18842. JS_FreeValue(ctx, ret);
  18843. } else {
  18844. JS_FreeValue(ctx, method);
  18845. }
  18846. }
  18847. JS_ThrowTypeError(ctx, "toPrimitive");
  18848. exception:
  18849. JS_FreeValue(ctx, val);
  18850. return JS_EXCEPTION;
  18851. }
  18852. static JSValue JS_ToPrimitive(JSContext *ctx, JSValueConst val, int hint)
  18853. {
  18854. return JS_ToPrimitiveFree(ctx, js_dup(val), hint);
  18855. }
  18856. void JS_SetIsHTMLDDA(JSContext *ctx, JSValueConst obj)
  18857. {
  18858. JSObject *p;
  18859. if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)
  18860. return;
  18861. p = JS_VALUE_GET_OBJ(obj);
  18862. p->is_HTMLDDA = true;
  18863. }
  18864. static inline bool JS_IsHTMLDDA(JSContext *ctx, JSValueConst obj)
  18865. {
  18866. JSObject *p;
  18867. if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)
  18868. return false;
  18869. p = JS_VALUE_GET_OBJ(obj);
  18870. return p->is_HTMLDDA;
  18871. }
  18872. static int JS_ToBoolFree(JSContext *ctx, JSValue val)
  18873. {
  18874. uint32_t tag = JS_VALUE_GET_TAG(val);
  18875. switch(tag) {
  18876. case JS_TAG_INT:
  18877. return JS_VALUE_GET_INT(val) != 0;
  18878. case JS_TAG_BOOL:
  18879. case JS_TAG_NULL:
  18880. case JS_TAG_UNDEFINED:
  18881. return JS_VALUE_GET_INT(val);
  18882. case JS_TAG_EXCEPTION:
  18883. return -1;
  18884. case JS_TAG_STRING:
  18885. {
  18886. bool ret = JS_VALUE_GET_STRING(val)->len != 0;
  18887. JS_FreeValue(ctx, val);
  18888. return ret;
  18889. }
  18890. case JS_TAG_BIG_INT:
  18891. {
  18892. JSBigInt *p = JS_VALUE_GET_PTR(val);
  18893. bool ret;
  18894. ret = p->num.expn != BF_EXP_ZERO && p->num.expn != BF_EXP_NAN;
  18895. JS_FreeValue(ctx, val);
  18896. return ret;
  18897. }
  18898. case JS_TAG_OBJECT:
  18899. {
  18900. JSObject *p = JS_VALUE_GET_OBJ(val);
  18901. bool ret = !p->is_HTMLDDA;
  18902. JS_FreeValue(ctx, val);
  18903. return ret;
  18904. }
  18905. break;
  18906. default:
  18907. if (JS_TAG_IS_FLOAT64(tag)) {
  18908. double d = JS_VALUE_GET_FLOAT64(val);
  18909. return !isnan(d) && d != 0;
  18910. } else {
  18911. JS_FreeValue(ctx, val);
  18912. return true;
  18913. }
  18914. }
  18915. }
  18916. int JS_ToBool(JSContext *ctx, JSValueConst val)
  18917. {
  18918. return JS_ToBoolFree(ctx, js_dup(val));
  18919. }
  18920. /* pc points to pure ASCII or UTF-8, null terminated contents */
  18921. static int skip_spaces(const char *pc)
  18922. {
  18923. const uint8_t *p, *p_next, *p_start;
  18924. uint32_t c;
  18925. p = p_start = (const uint8_t *)pc;
  18926. for (;;) {
  18927. c = *p++;
  18928. if (c < 0x80) {
  18929. if (!((c >= 0x09 && c <= 0x0d) || (c == 0x20)))
  18930. break;
  18931. } else {
  18932. c = utf8_decode(p - 1, &p_next);
  18933. /* no need to test for invalid UTF-8, 0xFFFD is not a space */
  18934. if (!lre_is_space(c))
  18935. break;
  18936. p = p_next;
  18937. }
  18938. }
  18939. return p - 1 - p_start;
  18940. }
  18941. static inline int to_digit(int c)
  18942. {
  18943. if (c >= '0' && c <= '9')
  18944. return c - '0';
  18945. else if (c >= 'A' && c <= 'Z')
  18946. return c - 'A' + 10;
  18947. else if (c >= 'a' && c <= 'z')
  18948. return c - 'a' + 10;
  18949. else
  18950. return 36;
  18951. }
  18952. /* XXX: remove */
  18953. static double js_strtod(const char *str, int radix, bool is_float)
  18954. {
  18955. double d;
  18956. int c;
  18957. if (!is_float || radix != 10) {
  18958. const char *p = str;
  18959. uint64_t n_max, n;
  18960. int int_exp, is_neg;
  18961. is_neg = 0;
  18962. if (*p == '-') {
  18963. is_neg = 1;
  18964. p++;
  18965. }
  18966. /* skip leading zeros */
  18967. while (*p == '0')
  18968. p++;
  18969. n = 0;
  18970. if (radix == 10)
  18971. n_max = ((uint64_t)-1 - 9) / 10; /* most common case */
  18972. else
  18973. n_max = ((uint64_t)-1 - (radix - 1)) / radix;
  18974. /* XXX: could be more precise */
  18975. int_exp = 0;
  18976. while ((c = to_digit(*p)) < radix) {
  18977. if (n <= n_max) {
  18978. n = n * radix + c;
  18979. } else {
  18980. if (radix == 10)
  18981. goto strtod_case;
  18982. int_exp++;
  18983. }
  18984. p++;
  18985. }
  18986. d = n;
  18987. if (int_exp != 0) {
  18988. d *= pow(radix, int_exp);
  18989. }
  18990. if (is_neg)
  18991. d = -d;
  18992. } else {
  18993. strtod_case:
  18994. d = strtod(str, NULL);
  18995. }
  18996. return d;
  18997. }
  18998. static JSValue js_string_to_bigint(JSContext *ctx, const char *buf, int radix)
  18999. {
  19000. bf_t *a;
  19001. int ret;
  19002. JSValue val;
  19003. val = JS_NewBigInt(ctx);
  19004. if (JS_IsException(val))
  19005. return val;
  19006. a = JS_GetBigInt(val);
  19007. ret = bf_atof(a, buf, NULL, radix, BF_PREC_INF, BF_RNDZ);
  19008. if (ret & BF_ST_MEM_ERROR) {
  19009. JS_FreeValue(ctx, val);
  19010. return JS_ThrowOutOfMemory(ctx);
  19011. }
  19012. return JS_CompactBigInt1(ctx, val);
  19013. }
  19014. /* `js_atof(ctx, p, len, pp, radix, flags)`
  19015. Convert the string pointed to by `p` to a number value.
  19016. Return an exception in case of memory error.
  19017. Return `JS_NAN` if invalid syntax.
  19018. - `p` points to a null terminated UTF-8 encoded char array,
  19019. - `len` the length of the array,
  19020. - `pp` if not null receives a pointer to the next character,
  19021. - `radix` must be in range 2 to 36, else return `JS_NAN`.
  19022. - `flags` is a combination of the flags below.
  19023. There is a null byte at `p[len]`, but there might be embedded null
  19024. bytes between `p[0]` and `p[len]` which must produce `JS_NAN` if
  19025. the `ATOD_NO_TRAILING_CHARS` flag is present.
  19026. */
  19027. #define ATOD_TRIM_SPACES (1 << 0) /* trim white space */
  19028. #define ATOD_ACCEPT_EMPTY (1 << 1) /* accept an empty string, value is 0 */
  19029. #define ATOD_ACCEPT_FLOAT (1 << 2) /* parse decimal floating point syntax */
  19030. #define ATOD_ACCEPT_INFINITY (1 << 3) /* parse Infinity as a float point number */
  19031. #define ATOD_ACCEPT_BIN_OCT (1 << 4) /* accept 0o and 0b prefixes */
  19032. #define ATOD_ACCEPT_HEX_PREFIX (1 << 5) /* accept 0x prefix for radix 16 */
  19033. #define ATOD_ACCEPT_UNDERSCORES (1 << 6) /* accept _ between digits as a digit separator */
  19034. #define ATOD_ACCEPT_SUFFIX (1 << 7) /* allow 'n' suffix to produce BigInt */
  19035. #define ATOD_WANT_BIG_INT (1 << 8) /* return type must be BigInt */
  19036. #define ATOD_DECIMAL_AFTER_SIGN (1 << 9) /* only accept decimal number after sign */
  19037. #define ATOD_NO_TRAILING_CHARS (1 << 10) /* do not accept trailing characters */
  19038. static JSValue js_atof(JSContext *ctx, const char *p, size_t len,
  19039. const char **pp, int radix, int flags)
  19040. {
  19041. const char *p_start;
  19042. const char *end = p + len;
  19043. int sep;
  19044. bool is_float;
  19045. char buf1[64], *buf = buf1;
  19046. size_t i, j;
  19047. JSValue val = JS_NAN;
  19048. double d;
  19049. char sign;
  19050. if (radix < 2 || radix > 36)
  19051. goto done;
  19052. /* optional separator between digits */
  19053. sep = (flags & ATOD_ACCEPT_UNDERSCORES) ? '_' : 256;
  19054. sign = 0;
  19055. if (flags & ATOD_TRIM_SPACES)
  19056. p += skip_spaces(p);
  19057. if (p == end && (flags & ATOD_ACCEPT_EMPTY)) {
  19058. if (pp) *pp = p;
  19059. if (flags & ATOD_WANT_BIG_INT)
  19060. return JS_NewBigInt64(ctx, 0);
  19061. else
  19062. return js_int32(0);
  19063. }
  19064. if (*p == '+' || *p == '-') {
  19065. sign = *p;
  19066. p++;
  19067. if (flags & ATOD_DECIMAL_AFTER_SIGN)
  19068. flags &= ~(ATOD_ACCEPT_HEX_PREFIX | ATOD_ACCEPT_BIN_OCT);
  19069. }
  19070. if (p[0] == '0') {
  19071. if ((p[1] == 'x' || p[1] == 'X') &&
  19072. ((flags & ATOD_ACCEPT_HEX_PREFIX) || radix == 16)) {
  19073. p += 2;
  19074. radix = 16;
  19075. } else if (flags & ATOD_ACCEPT_BIN_OCT) {
  19076. if (p[1] == 'o' || p[1] == 'O') {
  19077. p += 2;
  19078. radix = 8;
  19079. } else if (p[1] == 'b' || p[1] == 'B') {
  19080. p += 2;
  19081. radix = 2;
  19082. }
  19083. }
  19084. } else {
  19085. if (*p == 'I' && (flags & ATOD_ACCEPT_INFINITY) && js__strstart(p, "Infinity", &p)) {
  19086. d = INF;
  19087. if (sign == '-')
  19088. d = -d;
  19089. val = js_float64(d);
  19090. goto done;
  19091. }
  19092. }
  19093. is_float = false;
  19094. p_start = p;
  19095. while (to_digit(*p) < radix) {
  19096. p++;
  19097. if (*p == sep && to_digit(p[1]) < radix)
  19098. p++;
  19099. }
  19100. if ((flags & ATOD_ACCEPT_FLOAT) && radix == 10) {
  19101. if (*p == '.' && (p > p_start || to_digit(p[1]) < radix)) {
  19102. is_float = true;
  19103. p++;
  19104. while (to_digit(*p) < radix) {
  19105. p++;
  19106. if (*p == sep && to_digit(p[1]) < radix)
  19107. p++;
  19108. }
  19109. }
  19110. if (p > p_start && (*p == 'e' || *p == 'E')) {
  19111. i = 1;
  19112. if (p[1] == '+' || p[1] == '-') {
  19113. i++;
  19114. }
  19115. if (is_digit(p[i])) {
  19116. is_float = true;
  19117. p += i + 1;
  19118. while (is_digit(*p) || (*p == sep && is_digit(p[1])))
  19119. p++;
  19120. }
  19121. }
  19122. }
  19123. if (p == p_start)
  19124. goto done;
  19125. len = p - p_start;
  19126. if (unlikely((len + 2) > sizeof(buf1))) {
  19127. buf = js_malloc_rt(ctx->rt, len + 2); /* no exception raised */
  19128. if (!buf) {
  19129. if (pp) *pp = p;
  19130. return JS_ThrowOutOfMemory(ctx);
  19131. }
  19132. }
  19133. /* remove the separators and the radix prefix */
  19134. j = 0;
  19135. if (sign == '-')
  19136. buf[j++] = '-';
  19137. for (i = 0; i < len; i++) {
  19138. if (p_start[i] != '_')
  19139. buf[j++] = p_start[i];
  19140. }
  19141. buf[j] = '\0';
  19142. if (flags & ATOD_ACCEPT_SUFFIX) {
  19143. if (*p == 'n') {
  19144. p++;
  19145. flags |= ATOD_WANT_BIG_INT;
  19146. }
  19147. }
  19148. if (flags & ATOD_WANT_BIG_INT) {
  19149. if (!is_float)
  19150. val = js_string_to_bigint(ctx, buf, radix);
  19151. } else {
  19152. d = js_strtod(buf, radix, is_float);
  19153. val = js_number(d); /* return int or float64 */
  19154. }
  19155. done:
  19156. if (flags & ATOD_NO_TRAILING_CHARS) {
  19157. if (flags & ATOD_TRIM_SPACES)
  19158. p += skip_spaces(p);
  19159. if (p != end) {
  19160. JS_FreeValue(ctx, val);
  19161. val = JS_NAN;
  19162. }
  19163. }
  19164. if (buf != buf1)
  19165. js_free_rt(ctx->rt, buf);
  19166. if (pp) *pp = p;
  19167. return val;
  19168. }
  19169. typedef enum JSToNumberHintEnum {
  19170. TON_FLAG_NUMBER,
  19171. TON_FLAG_NUMERIC,
  19172. } JSToNumberHintEnum;
  19173. static JSValue JS_ToNumberHintFree(JSContext *ctx, JSValue val,
  19174. JSToNumberHintEnum flag)
  19175. {
  19176. uint32_t tag;
  19177. JSValue ret;
  19178. redo:
  19179. tag = JS_VALUE_GET_NORM_TAG(val);
  19180. switch(tag) {
  19181. case JS_TAG_BIG_INT:
  19182. if (flag != TON_FLAG_NUMERIC) {
  19183. JS_FreeValue(ctx, val);
  19184. return JS_ThrowTypeError(ctx, "cannot convert BigInt to number");
  19185. }
  19186. ret = val;
  19187. break;
  19188. case JS_TAG_FLOAT64:
  19189. case JS_TAG_INT:
  19190. case JS_TAG_EXCEPTION:
  19191. ret = val;
  19192. break;
  19193. case JS_TAG_BOOL:
  19194. case JS_TAG_NULL:
  19195. ret = js_int32(JS_VALUE_GET_INT(val));
  19196. break;
  19197. case JS_TAG_UNDEFINED:
  19198. ret = JS_NAN;
  19199. break;
  19200. case JS_TAG_OBJECT:
  19201. val = JS_ToPrimitiveFree(ctx, val, HINT_NUMBER);
  19202. if (JS_IsException(val))
  19203. return JS_EXCEPTION;
  19204. goto redo;
  19205. case JS_TAG_STRING:
  19206. {
  19207. const char *str;
  19208. size_t len;
  19209. int flags;
  19210. str = JS_ToCStringLen(ctx, &len, val);
  19211. JS_FreeValue(ctx, val);
  19212. if (!str)
  19213. return JS_EXCEPTION;
  19214. flags = ATOD_TRIM_SPACES | ATOD_ACCEPT_EMPTY |
  19215. ATOD_ACCEPT_FLOAT | ATOD_ACCEPT_INFINITY |
  19216. ATOD_ACCEPT_HEX_PREFIX | ATOD_ACCEPT_BIN_OCT |
  19217. ATOD_DECIMAL_AFTER_SIGN | ATOD_NO_TRAILING_CHARS;
  19218. ret = js_atof(ctx, str, len, NULL, 10, flags);
  19219. JS_FreeCString(ctx, str);
  19220. }
  19221. break;
  19222. case JS_TAG_SYMBOL:
  19223. JS_FreeValue(ctx, val);
  19224. return JS_ThrowTypeError(ctx, "cannot convert symbol to number");
  19225. default:
  19226. JS_FreeValue(ctx, val);
  19227. ret = JS_NAN;
  19228. break;
  19229. }
  19230. return ret;
  19231. }
  19232. static JSValue JS_ToNumberFree(JSContext *ctx, JSValue val)
  19233. {
  19234. return JS_ToNumberHintFree(ctx, val, TON_FLAG_NUMBER);
  19235. }
  19236. static JSValue JS_ToNumericFree(JSContext *ctx, JSValue val)
  19237. {
  19238. return JS_ToNumberHintFree(ctx, val, TON_FLAG_NUMERIC);
  19239. }
  19240. static JSValue JS_ToNumeric(JSContext *ctx, JSValueConst val)
  19241. {
  19242. return JS_ToNumericFree(ctx, js_dup(val));
  19243. }
  19244. static __exception int __JS_ToFloat64Free(JSContext *ctx, double *pres,
  19245. JSValue val)
  19246. {
  19247. double d;
  19248. uint32_t tag;
  19249. val = JS_ToNumberFree(ctx, val);
  19250. if (JS_IsException(val)) {
  19251. *pres = NAN;
  19252. return -1;
  19253. }
  19254. tag = JS_VALUE_GET_NORM_TAG(val);
  19255. switch(tag) {
  19256. case JS_TAG_INT:
  19257. d = JS_VALUE_GET_INT(val);
  19258. break;
  19259. case JS_TAG_FLOAT64:
  19260. d = JS_VALUE_GET_FLOAT64(val);
  19261. break;
  19262. case JS_TAG_BIG_INT:
  19263. {
  19264. JSBigInt *p = JS_VALUE_GET_PTR(val);
  19265. /* XXX: there can be a double rounding issue with some
  19266. primitives (such as JS_ToUint8ClampFree()), but it is
  19267. not critical to fix it. */
  19268. bf_get_float64(&p->num, &d, BF_RNDN);
  19269. JS_FreeValue(ctx, val);
  19270. }
  19271. break;
  19272. default:
  19273. abort();
  19274. }
  19275. *pres = d;
  19276. return 0;
  19277. }
  19278. static inline int JS_ToFloat64Free(JSContext *ctx, double *pres, JSValue val)
  19279. {
  19280. uint32_t tag;
  19281. tag = JS_VALUE_GET_TAG(val);
  19282. if (tag <= JS_TAG_NULL) {
  19283. *pres = JS_VALUE_GET_INT(val);
  19284. return 0;
  19285. } else if (JS_TAG_IS_FLOAT64(tag)) {
  19286. *pres = JS_VALUE_GET_FLOAT64(val);
  19287. return 0;
  19288. } else {
  19289. return __JS_ToFloat64Free(ctx, pres, val);
  19290. }
  19291. }
  19292. int JS_ToFloat64(JSContext *ctx, double *pres, JSValueConst val)
  19293. {
  19294. return JS_ToFloat64Free(ctx, pres, js_dup(val));
  19295. }
  19296. JSValue JS_ToNumber(JSContext *ctx, JSValueConst val)
  19297. {
  19298. return JS_ToNumberFree(ctx, js_dup(val));
  19299. }
  19300. /* same as JS_ToNumber() but return 0 in case of NaN/Undefined */
  19301. static __maybe_unused JSValue JS_ToIntegerFree(JSContext *ctx, JSValue val)
  19302. {
  19303. uint32_t tag;
  19304. JSValue ret;
  19305. redo:
  19306. tag = JS_VALUE_GET_NORM_TAG(val);
  19307. switch(tag) {
  19308. case JS_TAG_INT:
  19309. case JS_TAG_BOOL:
  19310. case JS_TAG_NULL:
  19311. case JS_TAG_UNDEFINED:
  19312. ret = js_int32(JS_VALUE_GET_INT(val));
  19313. break;
  19314. case JS_TAG_FLOAT64:
  19315. {
  19316. double d = JS_VALUE_GET_FLOAT64(val);
  19317. if (isnan(d)) {
  19318. ret = js_int32(0);
  19319. } else {
  19320. /* convert -0 to +0 */
  19321. d = trunc(d) + 0.0;
  19322. ret = js_number(d);
  19323. }
  19324. }
  19325. break;
  19326. default:
  19327. val = JS_ToNumberFree(ctx, val);
  19328. if (JS_IsException(val))
  19329. return val;
  19330. goto redo;
  19331. }
  19332. return ret;
  19333. }
  19334. /* Note: the integer value is satured to 32 bits */
  19335. static int JS_ToInt32SatFree(JSContext *ctx, int *pres, JSValue val)
  19336. {
  19337. uint32_t tag;
  19338. int ret;
  19339. redo:
  19340. tag = JS_VALUE_GET_NORM_TAG(val);
  19341. switch(tag) {
  19342. case JS_TAG_INT:
  19343. case JS_TAG_BOOL:
  19344. case JS_TAG_NULL:
  19345. case JS_TAG_UNDEFINED:
  19346. ret = JS_VALUE_GET_INT(val);
  19347. break;
  19348. case JS_TAG_EXCEPTION:
  19349. *pres = 0;
  19350. return -1;
  19351. case JS_TAG_FLOAT64:
  19352. {
  19353. double d = JS_VALUE_GET_FLOAT64(val);
  19354. if (isnan(d)) {
  19355. ret = 0;
  19356. } else {
  19357. if (d < INT32_MIN)
  19358. ret = INT32_MIN;
  19359. else if (d > INT32_MAX)
  19360. ret = INT32_MAX;
  19361. else
  19362. ret = (int)d;
  19363. }
  19364. }
  19365. break;
  19366. default:
  19367. val = JS_ToNumberFree(ctx, val);
  19368. if (JS_IsException(val)) {
  19369. *pres = 0;
  19370. return -1;
  19371. }
  19372. goto redo;
  19373. }
  19374. *pres = ret;
  19375. return 0;
  19376. }
  19377. static int JS_ToInt32Sat(JSContext *ctx, int *pres, JSValueConst val)
  19378. {
  19379. return JS_ToInt32SatFree(ctx, pres, js_dup(val));
  19380. }
  19381. static int JS_ToInt32Clamp(JSContext *ctx, int *pres, JSValueConst val,
  19382. int min, int max, int min_offset)
  19383. {
  19384. int res = JS_ToInt32SatFree(ctx, pres, js_dup(val));
  19385. if (res == 0) {
  19386. if (*pres < min) {
  19387. *pres += min_offset;
  19388. if (*pres < min)
  19389. *pres = min;
  19390. } else {
  19391. if (*pres > max)
  19392. *pres = max;
  19393. }
  19394. }
  19395. return res;
  19396. }
  19397. static int JS_ToInt64SatFree(JSContext *ctx, int64_t *pres, JSValue val)
  19398. {
  19399. uint32_t tag;
  19400. redo:
  19401. tag = JS_VALUE_GET_NORM_TAG(val);
  19402. switch(tag) {
  19403. case JS_TAG_INT:
  19404. case JS_TAG_BOOL:
  19405. case JS_TAG_NULL:
  19406. case JS_TAG_UNDEFINED:
  19407. *pres = JS_VALUE_GET_INT(val);
  19408. return 0;
  19409. case JS_TAG_EXCEPTION:
  19410. *pres = 0;
  19411. return -1;
  19412. case JS_TAG_FLOAT64:
  19413. {
  19414. double d = JS_VALUE_GET_FLOAT64(val);
  19415. if (isnan(d)) {
  19416. *pres = 0;
  19417. } else {
  19418. if (d < INT64_MIN)
  19419. *pres = INT64_MIN;
  19420. else if (d >= 0x1p63)
  19421. *pres = INT64_MAX;
  19422. else
  19423. *pres = (int64_t)d;
  19424. }
  19425. }
  19426. return 0;
  19427. default:
  19428. val = JS_ToNumberFree(ctx, val);
  19429. if (JS_IsException(val)) {
  19430. *pres = 0;
  19431. return -1;
  19432. }
  19433. goto redo;
  19434. }
  19435. }
  19436. int JS_ToInt64Sat(JSContext *ctx, int64_t *pres, JSValueConst val)
  19437. {
  19438. return JS_ToInt64SatFree(ctx, pres, js_dup(val));
  19439. }
  19440. int JS_ToInt64Clamp(JSContext *ctx, int64_t *pres, JSValueConst val,
  19441. int64_t min, int64_t max, int64_t neg_offset)
  19442. {
  19443. int res = JS_ToInt64SatFree(ctx, pres, js_dup(val));
  19444. if (res == 0) {
  19445. if (*pres < 0)
  19446. *pres += neg_offset;
  19447. if (*pres < min)
  19448. *pres = min;
  19449. else if (*pres > max)
  19450. *pres = max;
  19451. }
  19452. return res;
  19453. }
  19454. /* Same as JS_ToInt32Free() but with a 64 bit result. Return (<0, 0)
  19455. in case of exception */
  19456. static int JS_ToInt64Free(JSContext *ctx, int64_t *pres, JSValue val)
  19457. {
  19458. uint32_t tag;
  19459. int64_t ret;
  19460. redo:
  19461. tag = JS_VALUE_GET_NORM_TAG(val);
  19462. switch(tag) {
  19463. case JS_TAG_INT:
  19464. case JS_TAG_BOOL:
  19465. case JS_TAG_NULL:
  19466. case JS_TAG_UNDEFINED:
  19467. ret = JS_VALUE_GET_INT(val);
  19468. break;
  19469. case JS_TAG_FLOAT64:
  19470. {
  19471. JSFloat64Union u;
  19472. double d;
  19473. int e;
  19474. d = JS_VALUE_GET_FLOAT64(val);
  19475. u.d = d;
  19476. /* we avoid doing fmod(x, 2^64) */
  19477. e = (u.u64 >> 52) & 0x7ff;
  19478. if (likely(e <= (1023 + 62))) {
  19479. /* fast case */
  19480. ret = (int64_t)d;
  19481. } else if (e <= (1023 + 62 + 53)) {
  19482. uint64_t v;
  19483. /* remainder modulo 2^64 */
  19484. v = (u.u64 & (((uint64_t)1 << 52) - 1)) | ((uint64_t)1 << 52);
  19485. ret = v << ((e - 1023) - 52);
  19486. /* take the sign into account */
  19487. if (u.u64 >> 63)
  19488. if (ret != INT64_MIN)
  19489. ret = -ret;
  19490. } else {
  19491. ret = 0; /* also handles NaN and +inf */
  19492. }
  19493. }
  19494. break;
  19495. default:
  19496. val = JS_ToNumberFree(ctx, val);
  19497. if (JS_IsException(val)) {
  19498. *pres = 0;
  19499. return -1;
  19500. }
  19501. goto redo;
  19502. }
  19503. *pres = ret;
  19504. return 0;
  19505. }
  19506. int JS_ToInt64(JSContext *ctx, int64_t *pres, JSValueConst val)
  19507. {
  19508. return JS_ToInt64Free(ctx, pres, js_dup(val));
  19509. }
  19510. int JS_ToInt64Ext(JSContext *ctx, int64_t *pres, JSValueConst val)
  19511. {
  19512. if (JS_IsBigInt(ctx, val))
  19513. return JS_ToBigInt64(ctx, pres, val);
  19514. else
  19515. return JS_ToInt64(ctx, pres, val);
  19516. }
  19517. /* return (<0, 0) in case of exception */
  19518. static int JS_ToInt32Free(JSContext *ctx, int32_t *pres, JSValue val)
  19519. {
  19520. uint32_t tag;
  19521. int32_t ret;
  19522. redo:
  19523. tag = JS_VALUE_GET_NORM_TAG(val);
  19524. switch(tag) {
  19525. case JS_TAG_INT:
  19526. case JS_TAG_BOOL:
  19527. case JS_TAG_NULL:
  19528. case JS_TAG_UNDEFINED:
  19529. ret = JS_VALUE_GET_INT(val);
  19530. break;
  19531. case JS_TAG_FLOAT64:
  19532. {
  19533. JSFloat64Union u;
  19534. double d;
  19535. int e;
  19536. d = JS_VALUE_GET_FLOAT64(val);
  19537. u.d = d;
  19538. /* we avoid doing fmod(x, 2^32) */
  19539. e = (u.u64 >> 52) & 0x7ff;
  19540. if (likely(e <= (1023 + 30))) {
  19541. /* fast case */
  19542. ret = (int32_t)d;
  19543. } else if (e <= (1023 + 30 + 53)) {
  19544. uint64_t v;
  19545. /* remainder modulo 2^32 */
  19546. v = (u.u64 & (((uint64_t)1 << 52) - 1)) | ((uint64_t)1 << 52);
  19547. v = v << ((e - 1023) - 52 + 32);
  19548. ret = v >> 32;
  19549. /* take the sign into account */
  19550. if (u.u64 >> 63)
  19551. if (ret != INT32_MIN)
  19552. ret = -ret;
  19553. } else {
  19554. ret = 0; /* also handles NaN and +inf */
  19555. }
  19556. }
  19557. break;
  19558. default:
  19559. val = JS_ToNumberFree(ctx, val);
  19560. if (JS_IsException(val)) {
  19561. *pres = 0;
  19562. return -1;
  19563. }
  19564. goto redo;
  19565. }
  19566. *pres = ret;
  19567. return 0;
  19568. }
  19569. int JS_ToInt32(JSContext *ctx, int32_t *pres, JSValueConst val)
  19570. {
  19571. return JS_ToInt32Free(ctx, pres, js_dup(val));
  19572. }
  19573. static inline int JS_ToUint32Free(JSContext *ctx, uint32_t *pres, JSValue val)
  19574. {
  19575. return JS_ToInt32Free(ctx, (int32_t *)pres, val);
  19576. }
  19577. static int JS_ToUint8ClampFree(JSContext *ctx, int32_t *pres, JSValue val)
  19578. {
  19579. uint32_t tag;
  19580. int res;
  19581. redo:
  19582. tag = JS_VALUE_GET_NORM_TAG(val);
  19583. switch(tag) {
  19584. case JS_TAG_INT:
  19585. case JS_TAG_BOOL:
  19586. case JS_TAG_NULL:
  19587. case JS_TAG_UNDEFINED:
  19588. res = JS_VALUE_GET_INT(val);
  19589. res = max_int(0, min_int(255, res));
  19590. break;
  19591. case JS_TAG_FLOAT64:
  19592. {
  19593. double d = JS_VALUE_GET_FLOAT64(val);
  19594. if (isnan(d)) {
  19595. res = 0;
  19596. } else {
  19597. if (d < 0)
  19598. res = 0;
  19599. else if (d > 255)
  19600. res = 255;
  19601. else
  19602. res = lrint(d);
  19603. }
  19604. }
  19605. break;
  19606. default:
  19607. val = JS_ToNumberFree(ctx, val);
  19608. if (JS_IsException(val)) {
  19609. *pres = 0;
  19610. return -1;
  19611. }
  19612. goto redo;
  19613. }
  19614. *pres = res;
  19615. return 0;
  19616. }
  19617. static __exception int JS_ToArrayLengthFree(JSContext *ctx, uint32_t *plen,
  19618. JSValue val, bool is_array_ctor)
  19619. {
  19620. uint32_t tag, len;
  19621. tag = JS_VALUE_GET_TAG(val);
  19622. switch(tag) {
  19623. case JS_TAG_INT:
  19624. case JS_TAG_BOOL:
  19625. case JS_TAG_NULL:
  19626. {
  19627. int v;
  19628. v = JS_VALUE_GET_INT(val);
  19629. if (v < 0)
  19630. goto fail;
  19631. len = v;
  19632. }
  19633. break;
  19634. case JS_TAG_BIG_INT:
  19635. {
  19636. JSBigInt *p = JS_VALUE_GET_PTR(val);
  19637. bf_t a;
  19638. bool res;
  19639. bf_get_int32((int32_t *)&len, &p->num, BF_GET_INT_MOD);
  19640. bf_init(ctx->bf_ctx, &a);
  19641. bf_set_ui(&a, len);
  19642. res = bf_cmp_eq(&a, &p->num);
  19643. bf_delete(&a);
  19644. JS_FreeValue(ctx, val);
  19645. if (!res)
  19646. goto fail;
  19647. }
  19648. break;
  19649. default:
  19650. if (JS_TAG_IS_FLOAT64(tag)) {
  19651. double d;
  19652. d = JS_VALUE_GET_FLOAT64(val);
  19653. if (!(d >= 0 && d <= UINT32_MAX))
  19654. goto fail;
  19655. len = (uint32_t)d;
  19656. if (len != d)
  19657. goto fail;
  19658. } else {
  19659. uint32_t len1;
  19660. if (is_array_ctor) {
  19661. val = JS_ToNumberFree(ctx, val);
  19662. if (JS_IsException(val))
  19663. return -1;
  19664. /* cannot recurse because val is a number */
  19665. if (JS_ToArrayLengthFree(ctx, &len, val, true))
  19666. return -1;
  19667. } else {
  19668. /* legacy behavior: must do the conversion twice and compare */
  19669. if (JS_ToUint32(ctx, &len, val)) {
  19670. JS_FreeValue(ctx, val);
  19671. return -1;
  19672. }
  19673. val = JS_ToNumberFree(ctx, val);
  19674. if (JS_IsException(val))
  19675. return -1;
  19676. /* cannot recurse because val is a number */
  19677. if (JS_ToArrayLengthFree(ctx, &len1, val, false))
  19678. return -1;
  19679. if (len1 != len) {
  19680. fail:
  19681. JS_ThrowRangeError(ctx, "invalid array length");
  19682. return -1;
  19683. }
  19684. }
  19685. }
  19686. break;
  19687. }
  19688. *plen = len;
  19689. return 0;
  19690. }
  19691. #define MAX_SAFE_INTEGER (((int64_t)1 << 53) - 1)
  19692. static bool is_safe_integer(double d)
  19693. {
  19694. return isfinite(d) && floor(d) == d &&
  19695. fabs(d) <= (double)MAX_SAFE_INTEGER;
  19696. }
  19697. int JS_ToIndex(JSContext *ctx, uint64_t *plen, JSValueConst val)
  19698. {
  19699. int64_t v;
  19700. if (JS_ToInt64Sat(ctx, &v, val))
  19701. return -1;
  19702. if (v < 0 || v > MAX_SAFE_INTEGER) {
  19703. JS_ThrowRangeError(ctx, "invalid array index");
  19704. *plen = 0;
  19705. return -1;
  19706. }
  19707. *plen = v;
  19708. return 0;
  19709. }
  19710. /* convert a value to a length between 0 and MAX_SAFE_INTEGER.
  19711. return -1 for exception */
  19712. static __exception int JS_ToLengthFree(JSContext *ctx, int64_t *plen,
  19713. JSValue val)
  19714. {
  19715. int res = JS_ToInt64Clamp(ctx, plen, val, 0, MAX_SAFE_INTEGER, 0);
  19716. JS_FreeValue(ctx, val);
  19717. return res;
  19718. }
  19719. /* Note: can return an exception */
  19720. static int JS_NumberIsInteger(JSContext *ctx, JSValueConst val)
  19721. {
  19722. double d;
  19723. if (!JS_IsNumber(val))
  19724. return false;
  19725. if (unlikely(JS_ToFloat64(ctx, &d, val)))
  19726. return -1;
  19727. return isfinite(d) && floor(d) == d;
  19728. }
  19729. static bool JS_NumberIsNegativeOrMinusZero(JSContext *ctx, JSValueConst val)
  19730. {
  19731. uint32_t tag;
  19732. tag = JS_VALUE_GET_NORM_TAG(val);
  19733. switch(tag) {
  19734. case JS_TAG_INT:
  19735. {
  19736. int v;
  19737. v = JS_VALUE_GET_INT(val);
  19738. return (v < 0);
  19739. }
  19740. case JS_TAG_FLOAT64:
  19741. {
  19742. JSFloat64Union u;
  19743. u.d = JS_VALUE_GET_FLOAT64(val);
  19744. return (u.u64 >> 63);
  19745. }
  19746. case JS_TAG_BIG_INT:
  19747. {
  19748. JSBigInt *p = JS_VALUE_GET_PTR(val);
  19749. /* Note: integer zeros are not necessarily positive */
  19750. return p->num.sign && !bf_is_zero(&p->num);
  19751. }
  19752. default:
  19753. return false;
  19754. }
  19755. }
  19756. static JSValue js_bigint_to_string1(JSContext *ctx, JSValueConst val, int radix)
  19757. {
  19758. JSValue ret;
  19759. bf_t a_s, *a;
  19760. char *str;
  19761. int saved_sign;
  19762. size_t len;
  19763. a = JS_ToBigInt(ctx, &a_s, val);
  19764. if (!a)
  19765. return JS_EXCEPTION;
  19766. saved_sign = a->sign;
  19767. if (a->expn == BF_EXP_ZERO)
  19768. a->sign = 0;
  19769. str = bf_ftoa(&len, a, radix, 0, BF_RNDZ | BF_FTOA_FORMAT_FRAC |
  19770. BF_FTOA_JS_QUIRKS);
  19771. a->sign = saved_sign;
  19772. JS_FreeBigInt(ctx, a, &a_s);
  19773. if (!str)
  19774. return JS_ThrowOutOfMemory(ctx);
  19775. ret = js_new_string8_len(ctx, str, len);
  19776. bf_free(ctx->bf_ctx, str);
  19777. return ret;
  19778. }
  19779. static JSValue js_bigint_to_string(JSContext *ctx, JSValueConst val)
  19780. {
  19781. return js_bigint_to_string1(ctx, val, 10);
  19782. }
  19783. /*---- floating point number to string conversions ----*/
  19784. /* JavaScript rounding is specified as round to nearest tie away
  19785. from zero (RNDNA), but in `printf` the "ties" case is not
  19786. specified (in most cases it is RNDN, round to nearest, tie to even),
  19787. so we must round manually. We generate 2 extra places and make
  19788. an extra call to snprintf if these are exactly '50'.
  19789. We set the current rounding mode to FE_DOWNWARD to check if the
  19790. last 2 places become '49'. If not, we must round up, which is
  19791. performed in place using the string digits.
  19792. Note that we cannot rely on snprintf for rounding up:
  19793. the code below fails on macOS for `0.5.toFixed(0)`: gives `0` expected `1`
  19794. fesetround(FE_UPWARD);
  19795. snprintf(dest, size, "%.*f", n_digits, d);
  19796. fesetround(FE_TONEAREST);
  19797. */
  19798. /* `js_fcvt` minimum buffer length:
  19799. - up to 21 digits in integral part
  19800. - 1 potential decimal point
  19801. - up to 102 decimals
  19802. - 1 null terminator
  19803. */
  19804. #define JS_FCVT_BUF_SIZE (21+1+102+1)
  19805. /* `js_ecvt` minimum buffer length:
  19806. - 1 leading digit
  19807. - 1 potential decimal point
  19808. - up to 102 decimals
  19809. - 5 exponent characters (from 'e-324' to 'e+308')
  19810. - 1 null terminator
  19811. */
  19812. #define JS_ECVT_BUF_SIZE (1+1+102+5+1)
  19813. /* `js_dtoa` minimum buffer length:
  19814. - 8 byte prefix
  19815. - either JS_FCVT_BUF_SIZE or JS_ECVT_BUF_SIZE
  19816. - JS_FCVT_BUF_SIZE is larger than JS_ECVT_BUF_SIZE
  19817. */
  19818. #define JS_DTOA_BUF_SIZE (8+JS_FCVT_BUF_SIZE)
  19819. /* `js_ecvt1`: compute the digits and decimal point spot for a double
  19820. - `d` is finite, positive or zero
  19821. - `n_digits` number of significant digits in range 1..103
  19822. - `buf` receives the printf result
  19823. - `buf` has a fixed format: n_digits with a decimal point at offset 1
  19824. and exponent 'e{+/-}xx[x]' at offset n_digits+1
  19825. Return n_digits
  19826. Store the position of the decimal point into `*decpt`
  19827. */
  19828. static int js_ecvt1(double d, int n_digits,
  19829. char dest[minimum_length(JS_ECVT_BUF_SIZE)],
  19830. size_t size, int *decpt)
  19831. {
  19832. /* d is positive, ensure decimal point is always present */
  19833. snprintf(dest, size, "%#.*e", n_digits - 1, d);
  19834. /* dest contents:
  19835. 0: first digit
  19836. 1: '.' decimal point (locale specific)
  19837. 2..n_digits: (n_digits-1) additional digits
  19838. n_digits+1: 'e' exponent mark
  19839. n_digits+2..: exponent sign, value and null terminator
  19840. */
  19841. /* extract the exponent (actually the position of the decimal point) */
  19842. *decpt = 1 + atoi(dest + n_digits + 2);
  19843. return n_digits;
  19844. }
  19845. /* `js_ecvt`: compute the digits and decimal point spot for a double
  19846. with proper javascript rounding. We cannot use `ecvt` for multiple
  19847. resasons: portability, because of the number of digits is typically
  19848. limited to 17, finally because the default rounding is inadequate.
  19849. `d` is finite and positive or zero.
  19850. `n_digits` number of significant digits in range 1..101
  19851. or 0 for automatic (only as many digits as necessary)
  19852. Return the number of digits produced in `dest`.
  19853. Store the position of the decimal point into `*decpt`
  19854. */
  19855. static int js_ecvt(double d, int n_digits,
  19856. char dest[minimum_length(JS_ECVT_BUF_SIZE)],
  19857. size_t size, int *decpt)
  19858. {
  19859. if (n_digits == 0) {
  19860. /* find the minimum number of digits (XXX: inefficient but simple) */
  19861. // TODO(chqrlie) use direct method from quickjs-printf
  19862. unsigned int n_digits_min = 1;
  19863. unsigned int n_digits_max = 17;
  19864. for (;;) {
  19865. n_digits = (n_digits_min + n_digits_max) / 2;
  19866. js_ecvt1(d, n_digits, dest, size, decpt);
  19867. if (n_digits_min == n_digits_max)
  19868. return n_digits;
  19869. /* dest contents:
  19870. 0: first digit
  19871. 1: '.' decimal point (locale specific)
  19872. 2..n_digits: (n_digits-1) additional digits
  19873. n_digits+1: 'e' exponent mark
  19874. n_digits+2..: exponent sign, value and null terminator
  19875. */
  19876. if (strtod(dest, NULL) == d) {
  19877. unsigned int n0 = n_digits;
  19878. /* enough digits */
  19879. /* strip the trailing zeros */
  19880. while (dest[n_digits] == '0')
  19881. n_digits--;
  19882. if (n_digits == n_digits_min)
  19883. return n_digits;
  19884. /* done if trailing zeros and not denormal or huge */
  19885. if (n_digits < n0 && d > 3e-308 && d < 8e307)
  19886. return n_digits;
  19887. n_digits_max = n_digits;
  19888. } else {
  19889. /* need at least one more digit */
  19890. n_digits_min = n_digits + 1;
  19891. }
  19892. }
  19893. } else {
  19894. #if defined(FE_DOWNWARD) && defined(FE_TONEAREST)
  19895. int i;
  19896. /* generate 2 extra digits: 99% chances to avoid 2 calls */
  19897. js_ecvt1(d, n_digits + 2, dest, size, decpt);
  19898. if (dest[n_digits + 1] < '5')
  19899. return n_digits; /* truncate the 2 extra digits */
  19900. if (dest[n_digits + 1] == '5' && dest[n_digits + 2] == '0') {
  19901. /* close to half-way: try rounding toward 0 */
  19902. fesetround(FE_DOWNWARD);
  19903. js_ecvt1(d, n_digits + 2, dest, size, decpt);
  19904. fesetround(FE_TONEAREST);
  19905. if (dest[n_digits + 1] < '5')
  19906. return n_digits; /* truncate the 2 extra digits */
  19907. }
  19908. /* round up in the string */
  19909. for(i = n_digits;; i--) {
  19910. /* ignore the locale specific decimal point */
  19911. if (is_digit(dest[i])) {
  19912. if (dest[i]++ < '9')
  19913. break;
  19914. dest[i] = '0';
  19915. if (i == 0) {
  19916. dest[0] = '1';
  19917. (*decpt)++;
  19918. break;
  19919. }
  19920. }
  19921. }
  19922. return n_digits; /* truncate the 2 extra digits */
  19923. #else
  19924. /* No disambiguation available, eg: __wasi__ targets */
  19925. return js_ecvt1(d, n_digits, dest, size, decpt);
  19926. #endif
  19927. }
  19928. }
  19929. /* `js_fcvt`: convert a floating point value to %f format using RNDNA
  19930. `d` is finite and positive or zero.
  19931. `n_digits` number of decimal places in range 0..100
  19932. Return the number of characters produced in `dest`.
  19933. */
  19934. static size_t js_fcvt(double d, int n_digits,
  19935. char dest[minimum_length(JS_FCVT_BUF_SIZE)], size_t size)
  19936. {
  19937. #if defined(FE_DOWNWARD) && defined(FE_TONEAREST)
  19938. int i, n1;
  19939. /* generate 2 extra digits: 99% chances to avoid 2 calls */
  19940. n1 = snprintf(dest, size, "%.*f", n_digits + 2, d) - 2;
  19941. if (dest[n1] >= '5') {
  19942. if (dest[n1] == '5' && dest[n1 + 1] == '0') {
  19943. /* close to half-way: try rounding toward 0 */
  19944. fesetround(FE_DOWNWARD);
  19945. n1 = snprintf(dest, size, "%.*f", n_digits + 2, d) - 2;
  19946. fesetround(FE_TONEAREST);
  19947. }
  19948. if (dest[n1] >= '5') { /* number should be rounded up */
  19949. /* d is either exactly half way or greater: round the string manually */
  19950. for (i = n1 - 1;; i--) {
  19951. /* ignore the locale specific decimal point */
  19952. if (is_digit(dest[i])) {
  19953. if (dest[i]++ < '9')
  19954. break;
  19955. dest[i] = '0';
  19956. if (i == 0) {
  19957. dest[0] = '1';
  19958. dest[n1] = '0';
  19959. dest[n1 - n_digits - 1] = '0';
  19960. dest[n1 - n_digits] = '.';
  19961. n1++;
  19962. break;
  19963. }
  19964. }
  19965. }
  19966. }
  19967. }
  19968. /* truncate the extra 2 digits and the decimal point if !n_digits */
  19969. n1 -= !n_digits;
  19970. //dest[n1] = '\0'; // optional
  19971. return n1;
  19972. #else
  19973. /* No disambiguation available, eg: __wasi__ targets */
  19974. return snprintf(dest, size, "%.*f", n_digits, d);
  19975. #endif
  19976. }
  19977. static JSValue js_dtoa_infinite(JSContext *ctx, double d)
  19978. {
  19979. // TODO(chqrlie) use atoms for NaN and Infinite?
  19980. if (isnan(d))
  19981. return js_new_string8(ctx, "NaN");
  19982. if (d < 0)
  19983. return js_new_string8(ctx, "-Infinity");
  19984. else
  19985. return js_new_string8(ctx, "Infinity");
  19986. }
  19987. #define JS_DTOA_TOSTRING 0 /* use as many digits as necessary */
  19988. #define JS_DTOA_EXPONENTIAL 1 /* use exponential notation either fixed or variable digits */
  19989. #define JS_DTOA_FIXED 2 /* force fixed number of fractional digits */
  19990. #define JS_DTOA_PRECISION 3 /* use n_digits significant digits (1 <= n_digits <= 101) */
  19991. /* `js_dtoa`: convert a floating point number to a string
  19992. - `mode`: one of the 4 supported formats
  19993. - `n_digits`: digit number according to mode
  19994. - TOSTRING: 0 only. As many digits as necessary
  19995. - EXPONENTIAL: 0 as many decimals as necessary
  19996. - 1..101 number of significant digits
  19997. - FIXED: 0..100 number of decimal places
  19998. - PRECISION: 1..101 number of significant digits
  19999. */
  20000. // XXX: should use libbf or quickjs-printf.
  20001. static JSValue js_dtoa(JSContext *ctx, double d, int n_digits, int mode)
  20002. {
  20003. char buf[JS_DTOA_BUF_SIZE];
  20004. size_t len;
  20005. char *start;
  20006. int sign, decpt, exp, i, k, n, n_max;
  20007. if (!isfinite(d))
  20008. return js_dtoa_infinite(ctx, d);
  20009. sign = (d < 0);
  20010. start = buf + 8;
  20011. d = fabs(d); /* also converts -0 to 0 */
  20012. if (mode != JS_DTOA_EXPONENTIAL && n_digits == 0) {
  20013. /* fast path for exact integers in variable format:
  20014. clip to MAX_SAFE_INTEGER because to ensure insignificant
  20015. digits are generated as 0.
  20016. used for JS_DTOA_TOSTRING and JS_DTOA_FIXED without decimals.
  20017. */
  20018. if (d <= (double)MAX_SAFE_INTEGER) {
  20019. uint64_t u64 = (uint64_t)d;
  20020. if (d == u64) {
  20021. len = u64toa(start, u64);
  20022. goto done;
  20023. }
  20024. }
  20025. }
  20026. if (mode == JS_DTOA_FIXED) {
  20027. len = js_fcvt(d, n_digits, start, sizeof(buf) - 8);
  20028. // TODO(chqrlie) patch the locale specific decimal point
  20029. goto done;
  20030. }
  20031. n_max = (n_digits > 0) ? n_digits : 21;
  20032. /* the number has k digits (1 <= k <= n_max) */
  20033. k = js_ecvt(d, n_digits, start, sizeof(buf) - 8, &decpt);
  20034. /* buffer contents:
  20035. 0: first digit
  20036. 1: '.' decimal point
  20037. 2..k: (k-1) additional digits
  20038. */
  20039. n = decpt; /* d=10^(n-k)*(buf1) i.e. d= < x.yyyy 10^(n-1) */
  20040. if (mode != JS_DTOA_EXPONENTIAL) {
  20041. /* mode is JS_DTOA_PRECISION or JS_DTOA_TOSTRING */
  20042. if (n >= 1 && n <= n_max) {
  20043. /* between 1 and n_max digits before the decimal point */
  20044. if (k <= n) {
  20045. /* all digits before the point, append zeros */
  20046. start[1] = start[0];
  20047. start++;
  20048. for(i = k; i < n; i++)
  20049. start[i] = '0';
  20050. len = n;
  20051. } else {
  20052. /* k > n: move digits before the point */
  20053. for(i = 1; i < n; i++)
  20054. start[i] = start[i + 1];
  20055. start[i] = '.';
  20056. len = 1 + k;
  20057. }
  20058. goto done;
  20059. }
  20060. if (n >= -5 && n <= 0) {
  20061. /* insert -n leading 0 decimals and a '0.' prefix */
  20062. n = -n;
  20063. start[1] = start[0];
  20064. start -= n + 1;
  20065. start[0] = '0';
  20066. start[1] = '.';
  20067. for(i = 0; i < n; i++)
  20068. start[2 + i] = '0';
  20069. len = 2 + k + n;
  20070. goto done;
  20071. }
  20072. }
  20073. /* exponential notation */
  20074. exp = n - 1;
  20075. /* count the digits and the decimal point if at least one decimal */
  20076. len = k + (k > 1);
  20077. start[1] = '.'; /* patch the locale specific decimal point */
  20078. start[len] = 'e';
  20079. start[len + 1] = '+';
  20080. if (exp < 0) {
  20081. start[len + 1] = '-';
  20082. exp = -exp;
  20083. }
  20084. len += 2 + 1 + (exp > 9) + (exp > 99);
  20085. for (i = len - 1; exp > 9;) {
  20086. int quo = exp / 10;
  20087. start[i--] = (char)('0' + exp % 10);
  20088. exp = quo;
  20089. }
  20090. start[i] = (char)('0' + exp);
  20091. done:
  20092. start[-1] = '-'; /* prepend the sign if negative */
  20093. return js_new_string8_len(ctx, start - sign, len + sign);
  20094. }
  20095. /* `js_dtoa_radix`: convert a floating point number using a specific base
  20096. - `d` must be finite
  20097. - `radix` must be in range 2..36
  20098. */
  20099. static JSValue js_dtoa_radix(JSContext *ctx, double d, int radix)
  20100. {
  20101. char buf[2200], *ptr, *ptr2, *ptr3;
  20102. int sign, digit;
  20103. double frac, d0;
  20104. int64_t n0;
  20105. if (!isfinite(d))
  20106. return js_dtoa_infinite(ctx, d);
  20107. sign = (d < 0);
  20108. d = fabs(d);
  20109. d0 = trunc(d);
  20110. n0 = 0;
  20111. frac = d - d0;
  20112. ptr2 = buf + 1100; /* ptr2 points to the end of the string */
  20113. ptr = ptr2; /* ptr points to the beginning of the string */
  20114. if (d0 <= MAX_SAFE_INTEGER) {
  20115. int64_t n = n0 = (int64_t)d0;
  20116. while (n >= radix) {
  20117. digit = n % radix;
  20118. n = n / radix;
  20119. *--ptr = digits36[digit];
  20120. }
  20121. *--ptr = digits36[(size_t)n];
  20122. } else {
  20123. /* no decimals */
  20124. while (d0 >= radix) {
  20125. digit = fmod(d0, radix);
  20126. d0 = trunc(d0 / radix);
  20127. if (d0 >= MAX_SAFE_INTEGER)
  20128. digit = 0;
  20129. *--ptr = digits36[digit];
  20130. }
  20131. *--ptr = digits36[(size_t)d0];
  20132. goto done;
  20133. }
  20134. if (frac != 0) {
  20135. double log2_radix = log2(radix);
  20136. double prec = 1023 + 51; // handle subnormals
  20137. *ptr2++ = '.';
  20138. while (frac != 0 && n0 <= MAX_SAFE_INTEGER/2 && prec > 0) {
  20139. frac *= radix;
  20140. digit = trunc(frac);
  20141. frac -= digit;
  20142. *ptr2++ = digits36[digit];
  20143. n0 = n0 * radix + digit;
  20144. prec -= log2_radix;
  20145. }
  20146. if (frac * radix >= radix / 2) {
  20147. /* round up the string representation manually */
  20148. char nine = digits36[radix - 1];
  20149. while (ptr2[-1] == nine) {
  20150. /* strip trailing '9' or equivalent digits */
  20151. ptr2--;
  20152. }
  20153. if (ptr2[-1] == '.') {
  20154. /* strip the 'decimal' point */
  20155. ptr2--;
  20156. /* increment the integral part */
  20157. for (ptr3 = ptr2;;) {
  20158. if (ptr3[-1] != nine) {
  20159. ptr3[-1] = (ptr3[-1] == '9') ? 'a' : ptr3[-1] + 1;
  20160. break;
  20161. }
  20162. *--ptr3 = '0';
  20163. if (ptr3 <= ptr) {
  20164. /* prepend a '1' if number was all nines */
  20165. *--ptr = '1';
  20166. break;
  20167. }
  20168. }
  20169. } else {
  20170. /* increment the last fractional digit */
  20171. ptr2[-1] = (ptr2[-1] == '9') ? 'a' : ptr2[-1] + 1;
  20172. }
  20173. } else {
  20174. /* strip trailing fractional zeros */
  20175. while (ptr2[-1] == '0')
  20176. ptr2--;
  20177. /* strip the 'decimal' point if last */
  20178. ptr2 -= (ptr2[-1] == '.');
  20179. }
  20180. }
  20181. done:
  20182. ptr[-1] = '-';
  20183. ptr -= sign;
  20184. return js_new_string8_len(ctx, ptr, ptr2 - ptr);
  20185. }
  20186. JSValue JS_ToStringInternal(JSContext *ctx, JSValueConst val,
  20187. bool is_ToPropertyKey)
  20188. {
  20189. uint32_t tag;
  20190. char buf[32];
  20191. size_t len;
  20192. tag = JS_VALUE_GET_NORM_TAG(val);
  20193. switch(tag) {
  20194. case JS_TAG_STRING:
  20195. return js_dup(val);
  20196. case JS_TAG_INT:
  20197. len = i32toa(buf, JS_VALUE_GET_INT(val));
  20198. return js_new_string8_len(ctx, buf, len);
  20199. case JS_TAG_BOOL:
  20200. return JS_AtomToString(ctx, JS_VALUE_GET_BOOL(val) ?
  20201. JS_ATOM_true : JS_ATOM_false);
  20202. case JS_TAG_NULL:
  20203. return JS_AtomToString(ctx, JS_ATOM_null);
  20204. case JS_TAG_UNDEFINED:
  20205. return JS_AtomToString(ctx, JS_ATOM_undefined);
  20206. case JS_TAG_EXCEPTION:
  20207. return JS_EXCEPTION;
  20208. case JS_TAG_OBJECT:
  20209. {
  20210. JSValue val1, ret;
  20211. val1 = JS_ToPrimitive(ctx, val, HINT_STRING);
  20212. if (JS_IsException(val1))
  20213. return val1;
  20214. ret = JS_ToStringInternal(ctx, val1, is_ToPropertyKey);
  20215. JS_FreeValue(ctx, val1);
  20216. return ret;
  20217. }
  20218. break;
  20219. case JS_TAG_FUNCTION_BYTECODE:
  20220. return js_new_string8(ctx, "[function bytecode]");
  20221. case JS_TAG_SYMBOL:
  20222. if (is_ToPropertyKey) {
  20223. return js_dup(val);
  20224. } else {
  20225. return JS_ThrowTypeError(ctx, "cannot convert symbol to string");
  20226. }
  20227. case JS_TAG_FLOAT64:
  20228. return js_dtoa(ctx, JS_VALUE_GET_FLOAT64(val), 0, JS_DTOA_TOSTRING);
  20229. case JS_TAG_BIG_INT:
  20230. return js_bigint_to_string(ctx, val);
  20231. case JS_TAG_UNINITIALIZED:
  20232. return js_new_string8(ctx, "[uninitialized]");
  20233. default:
  20234. return js_new_string8(ctx, "[unsupported type]");
  20235. }
  20236. }
  20237. JSValue JS_ToString(JSContext *ctx, JSValueConst val)
  20238. {
  20239. return JS_ToStringInternal(ctx, val, false);
  20240. }
  20241. static JSValue JS_ToStringFree(JSContext *ctx, JSValue val)
  20242. {
  20243. JSValue ret;
  20244. ret = JS_ToString(ctx, val);
  20245. JS_FreeValue(ctx, val);
  20246. return ret;
  20247. }
  20248. static JSValue JS_ToLocaleStringFree(JSContext *ctx, JSValue val)
  20249. {
  20250. if (JS_IsUndefined(val) || JS_IsNull(val))
  20251. return JS_ToStringFree(ctx, val);
  20252. return JS_InvokeFree(ctx, val, JS_ATOM_toLocaleString, 0, NULL);
  20253. }
  20254. JSValue JS_ToPropertyKey(JSContext *ctx, JSValueConst val)
  20255. {
  20256. return JS_ToStringInternal(ctx, val, true);
  20257. }
  20258. static JSValue JS_ToStringCheckObject(JSContext *ctx, JSValueConst val)
  20259. {
  20260. uint32_t tag = JS_VALUE_GET_TAG(val);
  20261. if (tag == JS_TAG_NULL || tag == JS_TAG_UNDEFINED)
  20262. return JS_ThrowTypeError(ctx, "null or undefined are forbidden");
  20263. return JS_ToString(ctx, val);
  20264. }
  20265. static JSValue JS_ToQuotedString(JSContext *ctx, JSValueConst val1)
  20266. {
  20267. JSValue val;
  20268. JSString *p;
  20269. int i;
  20270. uint32_t c;
  20271. StringBuffer b_s, *b = &b_s;
  20272. char buf[16];
  20273. val = JS_ToStringCheckObject(ctx, val1);
  20274. if (JS_IsException(val))
  20275. return val;
  20276. p = JS_VALUE_GET_STRING(val);
  20277. if (string_buffer_init(ctx, b, p->len + 2))
  20278. goto fail;
  20279. if (string_buffer_putc8(b, '\"'))
  20280. goto fail;
  20281. for(i = 0; i < p->len; ) {
  20282. c = string_getc(p, &i);
  20283. switch(c) {
  20284. case '\t':
  20285. c = 't';
  20286. goto quote;
  20287. case '\r':
  20288. c = 'r';
  20289. goto quote;
  20290. case '\n':
  20291. c = 'n';
  20292. goto quote;
  20293. case '\b':
  20294. c = 'b';
  20295. goto quote;
  20296. case '\f':
  20297. c = 'f';
  20298. goto quote;
  20299. case '\"':
  20300. case '\\':
  20301. quote:
  20302. if (string_buffer_putc8(b, '\\'))
  20303. goto fail;
  20304. if (string_buffer_putc8(b, c))
  20305. goto fail;
  20306. break;
  20307. default:
  20308. if (c < 32 || is_surrogate(c)) {
  20309. snprintf(buf, sizeof(buf), "\\u%04x", c);
  20310. if (string_buffer_write8(b, (uint8_t*)buf, 6))
  20311. goto fail;
  20312. } else {
  20313. if (string_buffer_putc(b, c))
  20314. goto fail;
  20315. }
  20316. break;
  20317. }
  20318. }
  20319. if (string_buffer_putc8(b, '\"'))
  20320. goto fail;
  20321. JS_FreeValue(ctx, val);
  20322. return string_buffer_end(b);
  20323. fail:
  20324. JS_FreeValue(ctx, val);
  20325. string_buffer_free(b);
  20326. return JS_EXCEPTION;
  20327. }
  20328. static __maybe_unused void JS_DumpObjectHeader(JSRuntime *rt)
  20329. {
  20330. printf("%14s %4s %4s %14s %10s %s\n",
  20331. "ADDRESS", "REFS", "SHRF", "PROTO", "CLASS", "PROPS");
  20332. }
  20333. /* for debug only: dump an object without side effect */
  20334. static __maybe_unused void JS_DumpObject(JSRuntime *rt, JSObject *p)
  20335. {
  20336. uint32_t i;
  20337. char atom_buf[ATOM_GET_STR_BUF_SIZE];
  20338. JSShape *sh;
  20339. JSShapeProperty *prs;
  20340. JSProperty *pr;
  20341. bool is_first = true;
  20342. /* XXX: should encode atoms with special characters */
  20343. sh = p->shape; /* the shape can be NULL while freeing an object */
  20344. printf("%14p %4d ",
  20345. (void *)p,
  20346. p->header.ref_count);
  20347. if (sh) {
  20348. printf("%3d%c %14p ",
  20349. sh->header.ref_count,
  20350. " *"[sh->is_hashed],
  20351. (void *)sh->proto);
  20352. } else {
  20353. printf("%3s %14s ", "-", "-");
  20354. }
  20355. printf("%10s ",
  20356. JS_AtomGetStrRT(rt, atom_buf, sizeof(atom_buf), rt->class_array[p->class_id].class_name));
  20357. if (p->is_exotic && p->fast_array) {
  20358. printf("[ ");
  20359. for(i = 0; i < p->u.array.count; i++) {
  20360. if (i != 0)
  20361. printf(", ");
  20362. switch (p->class_id) {
  20363. case JS_CLASS_ARRAY:
  20364. case JS_CLASS_ARGUMENTS:
  20365. JS_DumpValue(rt, p->u.array.u.values[i]);
  20366. break;
  20367. case JS_CLASS_UINT8C_ARRAY:
  20368. case JS_CLASS_INT8_ARRAY:
  20369. case JS_CLASS_UINT8_ARRAY:
  20370. case JS_CLASS_INT16_ARRAY:
  20371. case JS_CLASS_UINT16_ARRAY:
  20372. case JS_CLASS_INT32_ARRAY:
  20373. case JS_CLASS_UINT32_ARRAY:
  20374. case JS_CLASS_BIG_INT64_ARRAY:
  20375. case JS_CLASS_BIG_UINT64_ARRAY:
  20376. case JS_CLASS_FLOAT16_ARRAY:
  20377. case JS_CLASS_FLOAT32_ARRAY:
  20378. case JS_CLASS_FLOAT64_ARRAY:
  20379. {
  20380. int size = 1 << typed_array_size_log2(p->class_id);
  20381. const uint8_t *b = p->u.array.u.uint8_ptr + i * size;
  20382. while (size-- > 0)
  20383. printf("%02X", *b++);
  20384. }
  20385. break;
  20386. }
  20387. }
  20388. printf(" ] ");
  20389. }
  20390. if (sh) {
  20391. printf("{ ");
  20392. for(i = 0, prs = get_shape_prop(sh); i < sh->prop_count; i++, prs++) {
  20393. if (prs->atom != JS_ATOM_NULL) {
  20394. pr = &p->prop[i];
  20395. if (!is_first)
  20396. printf(", ");
  20397. printf("%s: ",
  20398. JS_AtomGetStrRT(rt, atom_buf, sizeof(atom_buf), prs->atom));
  20399. if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) {
  20400. printf("[getset %p %p]", (void *)pr->u.getset.getter,
  20401. (void *)pr->u.getset.setter);
  20402. } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) {
  20403. printf("[varref %p]", (void *)pr->u.var_ref);
  20404. } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) {
  20405. printf("[autoinit %p %d %p]",
  20406. (void *)js_autoinit_get_realm(pr),
  20407. js_autoinit_get_id(pr),
  20408. (void *)pr->u.init.opaque);
  20409. } else {
  20410. JS_DumpValue(rt, pr->u.value);
  20411. }
  20412. is_first = false;
  20413. }
  20414. }
  20415. printf(" }");
  20416. }
  20417. if (js_class_has_bytecode(p->class_id)) {
  20418. JSFunctionBytecode *b = p->u.func.function_bytecode;
  20419. JSVarRef **var_refs;
  20420. if (b->closure_var_count) {
  20421. var_refs = p->u.func.var_refs;
  20422. printf(" Closure:");
  20423. for(i = 0; i < b->closure_var_count; i++) {
  20424. printf(" ");
  20425. JS_DumpValue(rt, var_refs[i]->value);
  20426. }
  20427. if (p->u.func.home_object) {
  20428. printf(" HomeObject: ");
  20429. JS_DumpValue(rt, JS_MKPTR(JS_TAG_OBJECT, p->u.func.home_object));
  20430. }
  20431. }
  20432. }
  20433. printf("\n");
  20434. }
  20435. static __maybe_unused void JS_DumpGCObject(JSRuntime *rt, JSGCObjectHeader *p)
  20436. {
  20437. if (p->gc_obj_type == JS_GC_OBJ_TYPE_JS_OBJECT) {
  20438. JS_DumpObject(rt, (JSObject *)p);
  20439. } else {
  20440. printf("%14p %4d ",
  20441. (void *)p,
  20442. p->ref_count);
  20443. switch(p->gc_obj_type) {
  20444. case JS_GC_OBJ_TYPE_FUNCTION_BYTECODE:
  20445. printf("[function bytecode]");
  20446. break;
  20447. case JS_GC_OBJ_TYPE_SHAPE:
  20448. printf("[shape]");
  20449. break;
  20450. case JS_GC_OBJ_TYPE_VAR_REF:
  20451. printf("[var_ref]");
  20452. break;
  20453. case JS_GC_OBJ_TYPE_ASYNC_FUNCTION:
  20454. printf("[async_function]");
  20455. break;
  20456. case JS_GC_OBJ_TYPE_JS_CONTEXT:
  20457. printf("[js_context]");
  20458. break;
  20459. default:
  20460. printf("[unknown %d]", p->gc_obj_type);
  20461. break;
  20462. }
  20463. printf("\n");
  20464. }
  20465. }
  20466. static __maybe_unused void JS_DumpValue(JSRuntime *rt, JSValueConst val)
  20467. {
  20468. uint32_t tag = JS_VALUE_GET_NORM_TAG(val);
  20469. const char *str;
  20470. switch(tag) {
  20471. case JS_TAG_INT:
  20472. printf("%d", JS_VALUE_GET_INT(val));
  20473. break;
  20474. case JS_TAG_BOOL:
  20475. if (JS_VALUE_GET_BOOL(val))
  20476. str = "true";
  20477. else
  20478. str = "false";
  20479. goto print_str;
  20480. case JS_TAG_NULL:
  20481. str = "null";
  20482. goto print_str;
  20483. case JS_TAG_EXCEPTION:
  20484. str = "exception";
  20485. goto print_str;
  20486. case JS_TAG_UNINITIALIZED:
  20487. str = "uninitialized";
  20488. goto print_str;
  20489. case JS_TAG_UNDEFINED:
  20490. str = "undefined";
  20491. print_str:
  20492. printf("%s", str);
  20493. break;
  20494. case JS_TAG_FLOAT64:
  20495. printf("%.14g", JS_VALUE_GET_FLOAT64(val));
  20496. break;
  20497. case JS_TAG_BIG_INT:
  20498. {
  20499. JSBigInt *p = JS_VALUE_GET_PTR(val);
  20500. char *str;
  20501. str = bf_ftoa(NULL, &p->num, 10, 0,
  20502. BF_RNDZ | BF_FTOA_FORMAT_FRAC);
  20503. printf("%sn", str);
  20504. bf_realloc(&rt->bf_ctx, str, 0);
  20505. }
  20506. break;
  20507. case JS_TAG_STRING:
  20508. {
  20509. JSString *p;
  20510. p = JS_VALUE_GET_STRING(val);
  20511. JS_DumpString(rt, p);
  20512. }
  20513. break;
  20514. case JS_TAG_FUNCTION_BYTECODE:
  20515. {
  20516. JSFunctionBytecode *b = JS_VALUE_GET_PTR(val);
  20517. char buf[ATOM_GET_STR_BUF_SIZE];
  20518. if (b->func_name) {
  20519. printf("[bytecode %s]", JS_AtomGetStrRT(rt, buf, sizeof(buf), b->func_name));
  20520. } else {
  20521. printf("[bytecode (anonymous)]");
  20522. }
  20523. }
  20524. break;
  20525. case JS_TAG_OBJECT:
  20526. {
  20527. JSObject *p = JS_VALUE_GET_OBJ(val);
  20528. JSAtom atom = rt->class_array[p->class_id].class_name;
  20529. char atom_buf[ATOM_GET_STR_BUF_SIZE];
  20530. printf("[%s %p]",
  20531. JS_AtomGetStrRT(rt, atom_buf, sizeof(atom_buf), atom), (void *)p);
  20532. }
  20533. break;
  20534. case JS_TAG_SYMBOL:
  20535. {
  20536. JSAtomStruct *p = JS_VALUE_GET_PTR(val);
  20537. char atom_buf[ATOM_GET_STR_BUF_SIZE];
  20538. printf("Symbol(%s)",
  20539. JS_AtomGetStrRT(rt, atom_buf, sizeof(atom_buf), js_get_atom_index(rt, p)));
  20540. }
  20541. break;
  20542. case JS_TAG_MODULE:
  20543. printf("[module]");
  20544. break;
  20545. default:
  20546. printf("[unknown tag %d]", tag);
  20547. break;
  20548. }
  20549. }
  20550. bool JS_IsArray(JSValueConst val)
  20551. {
  20552. if (JS_VALUE_GET_TAG(val) == JS_TAG_OBJECT) {
  20553. JSObject *p = JS_VALUE_GET_OBJ(val);
  20554. return p->class_id == JS_CLASS_ARRAY;
  20555. }
  20556. return false;
  20557. }
  20558. /* return -1 if exception (proxy case) or true/false */
  20559. static int js_is_array(JSContext *ctx, JSValueConst val)
  20560. {
  20561. JSObject *p;
  20562. if (JS_VALUE_GET_TAG(val) == JS_TAG_OBJECT) {
  20563. p = JS_VALUE_GET_OBJ(val);
  20564. if (unlikely(p->class_id == JS_CLASS_PROXY))
  20565. return js_proxy_isArray(ctx, val);
  20566. else
  20567. return p->class_id == JS_CLASS_ARRAY;
  20568. } else {
  20569. return false;
  20570. }
  20571. }
  20572. static double js_math_pow(double a, double b)
  20573. {
  20574. if (unlikely(!isfinite(b)) && fabs(a) == 1) {
  20575. /* not compatible with IEEE 754 */
  20576. return NAN;
  20577. } else {
  20578. return pow(a, b);
  20579. }
  20580. }
  20581. JSValue JS_NewBigInt64(JSContext *ctx, int64_t v)
  20582. {
  20583. JSValue val;
  20584. bf_t *a;
  20585. val = JS_NewBigInt(ctx);
  20586. if (JS_IsException(val))
  20587. return val;
  20588. a = JS_GetBigInt(val);
  20589. if (bf_set_si(a, v)) {
  20590. JS_FreeValue(ctx, val);
  20591. return JS_ThrowOutOfMemory(ctx);
  20592. }
  20593. return val;
  20594. }
  20595. JSValue JS_NewBigUint64(JSContext *ctx, uint64_t v)
  20596. {
  20597. JSValue val;
  20598. bf_t *a;
  20599. val = JS_NewBigInt(ctx);
  20600. if (JS_IsException(val))
  20601. return val;
  20602. a = JS_GetBigInt(val);
  20603. if (bf_set_ui(a, v)) {
  20604. JS_FreeValue(ctx, val);
  20605. return JS_ThrowOutOfMemory(ctx);
  20606. }
  20607. return val;
  20608. }
  20609. /* if the returned bigint is allocated it is equal to
  20610. 'buf'. Otherwise it is a pointer to the bigint in 'val'. Return
  20611. NULL in case of error. */
  20612. // TODO(bnoordhuis) Merge with JS_ToBigInt()
  20613. static bf_t *JS_ToBigInt1(JSContext *ctx, bf_t *buf, JSValueConst val)
  20614. {
  20615. uint32_t tag;
  20616. bf_t *r;
  20617. JSBigInt *p;
  20618. tag = JS_VALUE_GET_NORM_TAG(val);
  20619. switch(tag) {
  20620. case JS_TAG_INT:
  20621. case JS_TAG_BOOL:
  20622. case JS_TAG_NULL:
  20623. r = buf;
  20624. bf_init(ctx->bf_ctx, r);
  20625. if (bf_set_si(r, JS_VALUE_GET_INT(val)))
  20626. goto fail;
  20627. break;
  20628. case JS_TAG_FLOAT64:
  20629. r = buf;
  20630. bf_init(ctx->bf_ctx, r);
  20631. if (bf_set_float64(r, JS_VALUE_GET_FLOAT64(val))) {
  20632. fail:
  20633. bf_delete(r);
  20634. return NULL;
  20635. }
  20636. break;
  20637. case JS_TAG_BIG_INT:
  20638. p = JS_VALUE_GET_PTR(val);
  20639. r = &p->num;
  20640. break;
  20641. case JS_TAG_UNDEFINED:
  20642. default:
  20643. r = buf;
  20644. bf_init(ctx->bf_ctx, r);
  20645. bf_set_nan(r);
  20646. break;
  20647. }
  20648. return r;
  20649. }
  20650. /* return NaN if bad bigint literal */
  20651. static JSValue JS_StringToBigInt(JSContext *ctx, JSValue val)
  20652. {
  20653. const char *str;
  20654. size_t len;
  20655. int flags;
  20656. str = JS_ToCStringLen(ctx, &len, val);
  20657. JS_FreeValue(ctx, val);
  20658. if (!str)
  20659. return JS_EXCEPTION;
  20660. flags = ATOD_WANT_BIG_INT |
  20661. ATOD_TRIM_SPACES | ATOD_ACCEPT_EMPTY |
  20662. ATOD_ACCEPT_HEX_PREFIX | ATOD_ACCEPT_BIN_OCT |
  20663. ATOD_DECIMAL_AFTER_SIGN | ATOD_NO_TRAILING_CHARS;
  20664. val = js_atof(ctx, str, len, NULL, 10, flags);
  20665. JS_FreeCString(ctx, str);
  20666. return val;
  20667. }
  20668. static JSValue JS_StringToBigIntErr(JSContext *ctx, JSValue val)
  20669. {
  20670. val = JS_StringToBigInt(ctx, val);
  20671. if (JS_VALUE_IS_NAN(val))
  20672. return JS_ThrowSyntaxError(ctx, "invalid BigInt literal");
  20673. return val;
  20674. }
  20675. /* if the returned bigint is allocated it is equal to
  20676. 'buf'. Otherwise it is a pointer to the bigint in 'val'. */
  20677. static bf_t *JS_ToBigIntFree(JSContext *ctx, bf_t *buf, JSValue val)
  20678. {
  20679. uint32_t tag;
  20680. bf_t *r;
  20681. JSBigInt *p;
  20682. redo:
  20683. tag = JS_VALUE_GET_NORM_TAG(val);
  20684. switch(tag) {
  20685. case JS_TAG_INT:
  20686. case JS_TAG_NULL:
  20687. case JS_TAG_UNDEFINED:
  20688. case JS_TAG_FLOAT64:
  20689. goto fail;
  20690. case JS_TAG_BOOL:
  20691. r = buf;
  20692. bf_init(ctx->bf_ctx, r);
  20693. bf_set_si(r, JS_VALUE_GET_INT(val));
  20694. break;
  20695. case JS_TAG_BIG_INT:
  20696. p = JS_VALUE_GET_PTR(val);
  20697. r = &p->num;
  20698. break;
  20699. case JS_TAG_STRING:
  20700. val = JS_StringToBigIntErr(ctx, val);
  20701. if (JS_IsException(val))
  20702. return NULL;
  20703. goto redo;
  20704. case JS_TAG_OBJECT:
  20705. val = JS_ToPrimitiveFree(ctx, val, HINT_NUMBER);
  20706. if (JS_IsException(val))
  20707. return NULL;
  20708. goto redo;
  20709. default:
  20710. fail:
  20711. JS_FreeValue(ctx, val);
  20712. JS_ThrowTypeError(ctx, "cannot convert to BigInt");
  20713. return NULL;
  20714. }
  20715. return r;
  20716. }
  20717. static bf_t *JS_ToBigInt(JSContext *ctx, bf_t *buf, JSValueConst val)
  20718. {
  20719. return JS_ToBigIntFree(ctx, buf, js_dup(val));
  20720. }
  20721. static __maybe_unused JSValue JS_ToBigIntValueFree(JSContext *ctx, JSValue val)
  20722. {
  20723. if (JS_VALUE_GET_TAG(val) == JS_TAG_BIG_INT) {
  20724. return val;
  20725. } else {
  20726. bf_t a_s, *a, *r;
  20727. int ret;
  20728. JSValue res;
  20729. res = JS_NewBigInt(ctx);
  20730. if (JS_IsException(res))
  20731. return JS_EXCEPTION;
  20732. a = JS_ToBigIntFree(ctx, &a_s, val);
  20733. if (!a) {
  20734. JS_FreeValue(ctx, res);
  20735. return JS_EXCEPTION;
  20736. }
  20737. r = JS_GetBigInt(res);
  20738. ret = bf_set(r, a);
  20739. JS_FreeBigInt(ctx, a, &a_s);
  20740. if (ret) {
  20741. JS_FreeValue(ctx, res);
  20742. return JS_ThrowOutOfMemory(ctx);
  20743. }
  20744. return JS_CompactBigInt(ctx, res);
  20745. }
  20746. }
  20747. /* free the bf_t allocated by JS_ToBigInt */
  20748. static void JS_FreeBigInt(JSContext *ctx, bf_t *a, bf_t *buf)
  20749. {
  20750. if (a == buf) {
  20751. bf_delete(a);
  20752. } else {
  20753. JSBigInt *p = (JSBigInt *)((uint8_t *)a - offsetof(JSBigInt, num));
  20754. JS_FreeValue(ctx, JS_MKPTR(JS_TAG_BIG_INT, p));
  20755. }
  20756. }
  20757. /* XXX: merge with JS_ToInt64Free with a specific flag */
  20758. static int JS_ToBigInt64Free(JSContext *ctx, int64_t *pres, JSValue val)
  20759. {
  20760. bf_t a_s, *a;
  20761. a = JS_ToBigIntFree(ctx, &a_s, val);
  20762. if (!a) {
  20763. *pres = 0;
  20764. return -1;
  20765. }
  20766. bf_get_int64(pres, a, BF_GET_INT_MOD);
  20767. JS_FreeBigInt(ctx, a, &a_s);
  20768. return 0;
  20769. }
  20770. int JS_ToBigInt64(JSContext *ctx, int64_t *pres, JSValueConst val)
  20771. {
  20772. return JS_ToBigInt64Free(ctx, pres, js_dup(val));
  20773. }
  20774. int JS_ToBigUint64(JSContext *ctx, uint64_t *pres, JSValueConst val)
  20775. {
  20776. return JS_ToBigInt64Free(ctx, (int64_t *)pres, js_dup(val));
  20777. }
  20778. static JSValue JS_NewBigInt(JSContext *ctx)
  20779. {
  20780. JSBigInt *p;
  20781. p = js_malloc(ctx, sizeof(*p));
  20782. if (!p)
  20783. return JS_EXCEPTION;
  20784. p->header.ref_count = 1;
  20785. bf_init(ctx->bf_ctx, &p->num);
  20786. return JS_MKPTR(JS_TAG_BIG_INT, p);
  20787. }
  20788. static JSValue JS_CompactBigInt1(JSContext *ctx, JSValue val)
  20789. {
  20790. if (JS_VALUE_GET_TAG(val) != JS_TAG_BIG_INT)
  20791. return val; /* fail safe */
  20792. bf_t *a = JS_GetBigInt(val);
  20793. if (a->expn == BF_EXP_ZERO && a->sign) {
  20794. assert(((JSBigInt*)JS_VALUE_GET_PTR(val))->header.ref_count == 1);
  20795. a->sign = 0;
  20796. }
  20797. return val;
  20798. }
  20799. /* Nnormalize the zero representation. Could also be used to convert the bigint
  20800. to a short bigint value. The reference count of the value must be
  20801. 1. Cannot fail */
  20802. static JSValue JS_CompactBigInt(JSContext *ctx, JSValue val)
  20803. {
  20804. return JS_CompactBigInt1(ctx, val);
  20805. }
  20806. static JSValue throw_bf_exception(JSContext *ctx, int status)
  20807. {
  20808. const char *str;
  20809. if (status & BF_ST_MEM_ERROR)
  20810. return JS_ThrowOutOfMemory(ctx);
  20811. if (status & BF_ST_DIVIDE_ZERO) {
  20812. str = "division by zero";
  20813. } else if (status & BF_ST_INVALID_OP) {
  20814. str = "invalid operation";
  20815. } else {
  20816. str = "integer overflow";
  20817. }
  20818. return JS_ThrowRangeError(ctx, "%s", str);
  20819. }
  20820. static int js_unary_arith_bigint(JSContext *ctx,
  20821. JSValue *pres, OPCodeEnum op, JSValue op1)
  20822. {
  20823. bf_t a_s, *r, *a;
  20824. int ret, v;
  20825. JSValue res;
  20826. if (op == OP_plus) {
  20827. JS_ThrowTypeError(ctx, "BigInt argument with unary +");
  20828. JS_FreeValue(ctx, op1);
  20829. return -1;
  20830. }
  20831. res = JS_NewBigInt(ctx);
  20832. if (JS_IsException(res)) {
  20833. JS_FreeValue(ctx, op1);
  20834. return -1;
  20835. }
  20836. r = JS_GetBigInt(res);
  20837. a = JS_ToBigIntFree(ctx, &a_s, op1); // infallible, always a bigint
  20838. ret = 0;
  20839. switch(op) {
  20840. case OP_inc:
  20841. case OP_dec:
  20842. v = 2 * (op - OP_dec) - 1;
  20843. ret = bf_add_si(r, a, v, BF_PREC_INF, BF_RNDZ);
  20844. break;
  20845. case OP_plus:
  20846. ret = bf_set(r, a);
  20847. break;
  20848. case OP_neg:
  20849. ret = bf_set(r, a);
  20850. bf_neg(r);
  20851. break;
  20852. case OP_not:
  20853. ret = bf_add_si(r, a, 1, BF_PREC_INF, BF_RNDZ);
  20854. bf_neg(r);
  20855. break;
  20856. default:
  20857. abort();
  20858. }
  20859. JS_FreeBigInt(ctx, a, &a_s);
  20860. if (unlikely(ret)) {
  20861. JS_FreeValue(ctx, res);
  20862. throw_bf_exception(ctx, ret);
  20863. return -1;
  20864. }
  20865. res = JS_CompactBigInt(ctx, res);
  20866. *pres = res;
  20867. return 0;
  20868. }
  20869. static no_inline __exception int js_unary_arith_slow(JSContext *ctx,
  20870. JSValue *sp,
  20871. OPCodeEnum op)
  20872. {
  20873. JSValue op1;
  20874. int v;
  20875. uint32_t tag;
  20876. op1 = sp[-1];
  20877. /* fast path for float64 */
  20878. if (JS_TAG_IS_FLOAT64(JS_VALUE_GET_TAG(op1)))
  20879. goto handle_float64;
  20880. op1 = JS_ToNumericFree(ctx, op1);
  20881. if (JS_IsException(op1))
  20882. goto exception;
  20883. tag = JS_VALUE_GET_TAG(op1);
  20884. switch(tag) {
  20885. case JS_TAG_INT:
  20886. {
  20887. int64_t v64;
  20888. v64 = JS_VALUE_GET_INT(op1);
  20889. switch(op) {
  20890. case OP_inc:
  20891. case OP_dec:
  20892. v = 2 * (op - OP_dec) - 1;
  20893. v64 += v;
  20894. break;
  20895. case OP_plus:
  20896. break;
  20897. case OP_neg:
  20898. if (v64 == 0) {
  20899. sp[-1] = js_float64(-0.0);
  20900. return 0;
  20901. } else {
  20902. v64 = -v64;
  20903. }
  20904. break;
  20905. default:
  20906. abort();
  20907. }
  20908. sp[-1] = js_int64(v64);
  20909. }
  20910. break;
  20911. case JS_TAG_BIG_INT:
  20912. if (js_unary_arith_bigint(ctx, sp - 1, op, op1))
  20913. goto exception;
  20914. break;
  20915. default:
  20916. handle_float64:
  20917. {
  20918. double d = JS_VALUE_GET_FLOAT64(op1);
  20919. switch(op) {
  20920. case OP_inc:
  20921. case OP_dec:
  20922. v = 2 * (op - OP_dec) - 1;
  20923. d += v;
  20924. break;
  20925. case OP_plus:
  20926. break;
  20927. case OP_neg:
  20928. d = -d;
  20929. break;
  20930. default:
  20931. abort();
  20932. }
  20933. sp[-1] = js_float64(d);
  20934. }
  20935. break;
  20936. }
  20937. return 0;
  20938. exception:
  20939. sp[-1] = JS_UNDEFINED;
  20940. return -1;
  20941. }
  20942. static __exception int js_post_inc_slow(JSContext *ctx,
  20943. JSValue *sp, OPCodeEnum op)
  20944. {
  20945. JSValue op1;
  20946. /* XXX: allow custom operators */
  20947. op1 = sp[-1];
  20948. op1 = JS_ToNumericFree(ctx, op1);
  20949. if (JS_IsException(op1)) {
  20950. sp[-1] = JS_UNDEFINED;
  20951. return -1;
  20952. }
  20953. sp[-1] = op1;
  20954. sp[0] = js_dup(op1);
  20955. return js_unary_arith_slow(ctx, sp + 1, op - OP_post_dec + OP_dec);
  20956. }
  20957. static no_inline int js_not_slow(JSContext *ctx, JSValue *sp)
  20958. {
  20959. JSValue op1;
  20960. op1 = JS_ToNumericFree(ctx, sp[-1]);
  20961. if (JS_IsException(op1))
  20962. goto exception;
  20963. if (JS_VALUE_GET_TAG(op1) == JS_TAG_BIG_INT) {
  20964. if (js_unary_arith_bigint(ctx, sp - 1, OP_not, op1))
  20965. goto exception;
  20966. } else {
  20967. int32_t v1;
  20968. if (unlikely(JS_ToInt32Free(ctx, &v1, op1)))
  20969. goto exception;
  20970. sp[-1] = js_int32(~v1);
  20971. }
  20972. return 0;
  20973. exception:
  20974. sp[-1] = JS_UNDEFINED;
  20975. return -1;
  20976. }
  20977. static int js_binary_arith_bigint(JSContext *ctx, OPCodeEnum op,
  20978. JSValue *pres, JSValue op1, JSValue op2)
  20979. {
  20980. bf_t a_s, b_s, *r, *a, *b;
  20981. int ret;
  20982. JSValue res;
  20983. a = JS_ToBigIntFree(ctx, &a_s, op1);
  20984. if (!a) {
  20985. JS_FreeValue(ctx, op2);
  20986. return -1;
  20987. }
  20988. b = JS_ToBigIntFree(ctx, &b_s, op2);
  20989. if (!b) {
  20990. JS_FreeBigInt(ctx, a, &a_s);
  20991. return -1;
  20992. }
  20993. res = JS_NewBigInt(ctx);
  20994. if (JS_IsException(res)) {
  20995. JS_FreeBigInt(ctx, a, &a_s);
  20996. JS_FreeBigInt(ctx, b, &b_s);
  20997. return -1;
  20998. }
  20999. r = JS_GetBigInt(res);
  21000. ret = 0;
  21001. switch(op) {
  21002. case OP_add:
  21003. ret = bf_add(r, a, b, BF_PREC_INF, BF_RNDZ);
  21004. break;
  21005. case OP_sub:
  21006. ret = bf_sub(r, a, b, BF_PREC_INF, BF_RNDZ);
  21007. break;
  21008. case OP_mul:
  21009. ret = bf_mul(r, a, b, BF_PREC_INF, BF_RNDZ);
  21010. break;
  21011. case OP_div:
  21012. {
  21013. bf_t rem_s, *rem = &rem_s;
  21014. bf_init(ctx->bf_ctx, rem);
  21015. ret = bf_divrem(r, rem, a, b, BF_PREC_INF, BF_RNDZ, BF_RNDZ);
  21016. bf_delete(rem);
  21017. }
  21018. break;
  21019. case OP_mod:
  21020. ret = bf_rem(r, a, b, BF_PREC_INF, BF_RNDZ,
  21021. BF_RNDZ) & BF_ST_INVALID_OP;
  21022. break;
  21023. case OP_pow:
  21024. if (b->sign) {
  21025. ret = BF_ST_INVALID_OP;
  21026. } else {
  21027. ret = bf_pow(r, a, b, BF_PREC_INF, BF_RNDZ | BF_POW_JS_QUIRKS);
  21028. }
  21029. break;
  21030. /* logical operations */
  21031. case OP_shl:
  21032. case OP_sar:
  21033. {
  21034. slimb_t v2;
  21035. #if LIMB_BITS == 32
  21036. bf_get_int32(&v2, b, 0);
  21037. if (v2 == INT32_MIN)
  21038. v2 = INT32_MIN + 1;
  21039. #else
  21040. bf_get_int64(&v2, b, 0);
  21041. if (v2 == INT64_MIN)
  21042. v2 = INT64_MIN + 1;
  21043. #endif
  21044. if (op == OP_sar)
  21045. v2 = -v2;
  21046. ret = bf_set(r, a);
  21047. ret |= bf_mul_2exp(r, v2, BF_PREC_INF, BF_RNDZ);
  21048. if (v2 < 0) {
  21049. ret |= bf_rint(r, BF_RNDD) & (BF_ST_OVERFLOW | BF_ST_MEM_ERROR);
  21050. }
  21051. }
  21052. break;
  21053. case OP_and:
  21054. ret = bf_logic_and(r, a, b);
  21055. break;
  21056. case OP_or:
  21057. ret = bf_logic_or(r, a, b);
  21058. break;
  21059. case OP_xor:
  21060. ret = bf_logic_xor(r, a, b);
  21061. break;
  21062. default:
  21063. abort();
  21064. }
  21065. JS_FreeBigInt(ctx, a, &a_s);
  21066. JS_FreeBigInt(ctx, b, &b_s);
  21067. if (unlikely(ret)) {
  21068. JS_FreeValue(ctx, res);
  21069. throw_bf_exception(ctx, ret);
  21070. return -1;
  21071. }
  21072. *pres = JS_CompactBigInt(ctx, res);
  21073. return 0;
  21074. }
  21075. static no_inline __exception int js_binary_arith_slow(JSContext *ctx, JSValue *sp,
  21076. OPCodeEnum op)
  21077. {
  21078. JSValue op1, op2;
  21079. uint32_t tag1, tag2;
  21080. double d1, d2;
  21081. op1 = sp[-2];
  21082. op2 = sp[-1];
  21083. tag1 = JS_VALUE_GET_NORM_TAG(op1);
  21084. tag2 = JS_VALUE_GET_NORM_TAG(op2);
  21085. /* fast path for float operations */
  21086. if (tag1 == JS_TAG_FLOAT64 && tag2 == JS_TAG_FLOAT64) {
  21087. d1 = JS_VALUE_GET_FLOAT64(op1);
  21088. d2 = JS_VALUE_GET_FLOAT64(op2);
  21089. goto handle_float64;
  21090. }
  21091. op1 = JS_ToNumericFree(ctx, op1);
  21092. if (JS_IsException(op1)) {
  21093. JS_FreeValue(ctx, op2);
  21094. goto exception;
  21095. }
  21096. op2 = JS_ToNumericFree(ctx, op2);
  21097. if (JS_IsException(op2)) {
  21098. JS_FreeValue(ctx, op1);
  21099. goto exception;
  21100. }
  21101. tag1 = JS_VALUE_GET_NORM_TAG(op1);
  21102. tag2 = JS_VALUE_GET_NORM_TAG(op2);
  21103. if (tag1 == JS_TAG_INT && tag2 == JS_TAG_INT) {
  21104. int32_t v1, v2;
  21105. int64_t v;
  21106. v1 = JS_VALUE_GET_INT(op1);
  21107. v2 = JS_VALUE_GET_INT(op2);
  21108. switch(op) {
  21109. case OP_sub:
  21110. v = (int64_t)v1 - (int64_t)v2;
  21111. break;
  21112. case OP_mul:
  21113. v = (int64_t)v1 * (int64_t)v2;
  21114. if (v == 0 && (v1 | v2) < 0) {
  21115. sp[-2] = js_float64(-0.0);
  21116. return 0;
  21117. }
  21118. break;
  21119. case OP_div:
  21120. sp[-2] = js_float64((double)v1 / (double)v2);
  21121. return 0;
  21122. case OP_mod:
  21123. if (v1 < 0 || v2 <= 0) {
  21124. sp[-2] = js_number(fmod(v1, v2));
  21125. return 0;
  21126. } else {
  21127. v = (int64_t)v1 % (int64_t)v2;
  21128. }
  21129. break;
  21130. case OP_pow:
  21131. sp[-2] = js_number(js_math_pow(v1, v2));
  21132. return 0;
  21133. default:
  21134. abort();
  21135. }
  21136. sp[-2] = js_int64(v);
  21137. } else if (tag1 == JS_TAG_BIG_INT || tag2 == JS_TAG_BIG_INT) {
  21138. if (js_binary_arith_bigint(ctx, op, sp - 2, op1, op2))
  21139. goto exception;
  21140. } else {
  21141. double dr;
  21142. /* float64 result */
  21143. if (JS_ToFloat64Free(ctx, &d1, op1)) {
  21144. JS_FreeValue(ctx, op2);
  21145. goto exception;
  21146. }
  21147. if (JS_ToFloat64Free(ctx, &d2, op2))
  21148. goto exception;
  21149. handle_float64:
  21150. switch(op) {
  21151. case OP_sub:
  21152. dr = d1 - d2;
  21153. break;
  21154. case OP_mul:
  21155. dr = d1 * d2;
  21156. break;
  21157. case OP_div:
  21158. dr = d1 / d2;
  21159. break;
  21160. case OP_mod:
  21161. dr = fmod(d1, d2);
  21162. break;
  21163. case OP_pow:
  21164. dr = js_math_pow(d1, d2);
  21165. break;
  21166. default:
  21167. abort();
  21168. }
  21169. sp[-2] = js_float64(dr);
  21170. }
  21171. return 0;
  21172. exception:
  21173. sp[-2] = JS_UNDEFINED;
  21174. sp[-1] = JS_UNDEFINED;
  21175. return -1;
  21176. }
  21177. static no_inline __exception int js_add_slow(JSContext *ctx, JSValue *sp)
  21178. {
  21179. JSValue op1, op2;
  21180. uint32_t tag1, tag2;
  21181. op1 = sp[-2];
  21182. op2 = sp[-1];
  21183. tag1 = JS_VALUE_GET_NORM_TAG(op1);
  21184. tag2 = JS_VALUE_GET_NORM_TAG(op2);
  21185. /* fast path for float64 */
  21186. if (tag1 == JS_TAG_FLOAT64 && tag2 == JS_TAG_FLOAT64) {
  21187. double d1, d2;
  21188. d1 = JS_VALUE_GET_FLOAT64(op1);
  21189. d2 = JS_VALUE_GET_FLOAT64(op2);
  21190. sp[-2] = js_float64(d1 + d2);
  21191. return 0;
  21192. }
  21193. if (tag1 == JS_TAG_OBJECT || tag2 == JS_TAG_OBJECT) {
  21194. op1 = JS_ToPrimitiveFree(ctx, op1, HINT_NONE);
  21195. if (JS_IsException(op1)) {
  21196. JS_FreeValue(ctx, op2);
  21197. goto exception;
  21198. }
  21199. op2 = JS_ToPrimitiveFree(ctx, op2, HINT_NONE);
  21200. if (JS_IsException(op2)) {
  21201. JS_FreeValue(ctx, op1);
  21202. goto exception;
  21203. }
  21204. tag1 = JS_VALUE_GET_NORM_TAG(op1);
  21205. tag2 = JS_VALUE_GET_NORM_TAG(op2);
  21206. }
  21207. if (tag1 == JS_TAG_STRING || tag2 == JS_TAG_STRING) {
  21208. sp[-2] = JS_ConcatString(ctx, op1, op2);
  21209. if (JS_IsException(sp[-2]))
  21210. goto exception;
  21211. return 0;
  21212. }
  21213. op1 = JS_ToNumericFree(ctx, op1);
  21214. if (JS_IsException(op1)) {
  21215. JS_FreeValue(ctx, op2);
  21216. goto exception;
  21217. }
  21218. op2 = JS_ToNumericFree(ctx, op2);
  21219. if (JS_IsException(op2)) {
  21220. JS_FreeValue(ctx, op1);
  21221. goto exception;
  21222. }
  21223. tag1 = JS_VALUE_GET_NORM_TAG(op1);
  21224. tag2 = JS_VALUE_GET_NORM_TAG(op2);
  21225. if (tag1 == JS_TAG_INT && tag2 == JS_TAG_INT) {
  21226. int32_t v1, v2;
  21227. int64_t v;
  21228. v1 = JS_VALUE_GET_INT(op1);
  21229. v2 = JS_VALUE_GET_INT(op2);
  21230. v = (int64_t)v1 + (int64_t)v2;
  21231. sp[-2] = js_int64(v);
  21232. } else if (tag1 == JS_TAG_BIG_INT || tag2 == JS_TAG_BIG_INT) {
  21233. if (js_binary_arith_bigint(ctx, OP_add, sp - 2, op1, op2))
  21234. goto exception;
  21235. } else {
  21236. double d1, d2;
  21237. /* float64 result */
  21238. if (JS_ToFloat64Free(ctx, &d1, op1)) {
  21239. JS_FreeValue(ctx, op2);
  21240. goto exception;
  21241. }
  21242. if (JS_ToFloat64Free(ctx, &d2, op2))
  21243. goto exception;
  21244. sp[-2] = js_float64(d1 + d2);
  21245. }
  21246. return 0;
  21247. exception:
  21248. sp[-2] = JS_UNDEFINED;
  21249. sp[-1] = JS_UNDEFINED;
  21250. return -1;
  21251. }
  21252. static no_inline __exception int js_binary_logic_slow(JSContext *ctx,
  21253. JSValue *sp,
  21254. OPCodeEnum op)
  21255. {
  21256. JSValue op1, op2;
  21257. uint32_t tag1, tag2;
  21258. uint32_t v1, v2, r;
  21259. op1 = sp[-2];
  21260. op2 = sp[-1];
  21261. tag1 = JS_VALUE_GET_NORM_TAG(op1);
  21262. tag2 = JS_VALUE_GET_NORM_TAG(op2);
  21263. op1 = JS_ToNumericFree(ctx, op1);
  21264. if (JS_IsException(op1)) {
  21265. JS_FreeValue(ctx, op2);
  21266. goto exception;
  21267. }
  21268. op2 = JS_ToNumericFree(ctx, op2);
  21269. if (JS_IsException(op2)) {
  21270. JS_FreeValue(ctx, op1);
  21271. goto exception;
  21272. }
  21273. tag1 = JS_VALUE_GET_TAG(op1);
  21274. tag2 = JS_VALUE_GET_TAG(op2);
  21275. if (tag1 == JS_TAG_BIG_INT || tag2 == JS_TAG_BIG_INT) {
  21276. if (tag1 != tag2) {
  21277. JS_FreeValue(ctx, op1);
  21278. JS_FreeValue(ctx, op2);
  21279. JS_ThrowTypeError(ctx, "both operands must be BigInt");
  21280. goto exception;
  21281. } else if (js_binary_arith_bigint(ctx, op, sp - 2, op1, op2)) {
  21282. goto exception;
  21283. }
  21284. } else {
  21285. if (unlikely(JS_ToInt32Free(ctx, (int32_t *)&v1, op1))) {
  21286. JS_FreeValue(ctx, op2);
  21287. goto exception;
  21288. }
  21289. if (unlikely(JS_ToInt32Free(ctx, (int32_t *)&v2, op2)))
  21290. goto exception;
  21291. switch(op) {
  21292. case OP_shl:
  21293. r = v1 << (v2 & 0x1f);
  21294. break;
  21295. case OP_sar:
  21296. r = (int)v1 >> (v2 & 0x1f);
  21297. break;
  21298. case OP_and:
  21299. r = v1 & v2;
  21300. break;
  21301. case OP_or:
  21302. r = v1 | v2;
  21303. break;
  21304. case OP_xor:
  21305. r = v1 ^ v2;
  21306. break;
  21307. default:
  21308. abort();
  21309. }
  21310. sp[-2] = js_int32(r);
  21311. }
  21312. return 0;
  21313. exception:
  21314. sp[-2] = JS_UNDEFINED;
  21315. sp[-1] = JS_UNDEFINED;
  21316. return -1;
  21317. }
  21318. static int js_compare_bigint(JSContext *ctx, OPCodeEnum op,
  21319. JSValue op1, JSValue op2)
  21320. {
  21321. bf_t a_s, b_s, *a, *b;
  21322. int res;
  21323. a = JS_ToBigInt1(ctx, &a_s, op1);
  21324. if (!a) {
  21325. JS_FreeValue(ctx, op2);
  21326. return -1;
  21327. }
  21328. b = JS_ToBigInt1(ctx, &b_s, op2);
  21329. if (!b) {
  21330. if (a == &a_s)
  21331. bf_delete(a);
  21332. JS_FreeValue(ctx, op1);
  21333. return -1;
  21334. }
  21335. switch(op) {
  21336. case OP_lt:
  21337. res = bf_cmp_lt(a, b); /* if NaN return false */
  21338. break;
  21339. case OP_lte:
  21340. res = bf_cmp_le(a, b); /* if NaN return false */
  21341. break;
  21342. case OP_gt:
  21343. res = bf_cmp_lt(b, a); /* if NaN return false */
  21344. break;
  21345. case OP_gte:
  21346. res = bf_cmp_le(b, a); /* if NaN return false */
  21347. break;
  21348. case OP_eq:
  21349. res = bf_cmp_eq(a, b); /* if NaN return false */
  21350. break;
  21351. default:
  21352. abort();
  21353. }
  21354. if (a == &a_s)
  21355. bf_delete(a);
  21356. if (b == &b_s)
  21357. bf_delete(b);
  21358. JS_FreeValue(ctx, op1);
  21359. JS_FreeValue(ctx, op2);
  21360. return res;
  21361. }
  21362. static no_inline int js_relational_slow(JSContext *ctx, JSValue *sp,
  21363. OPCodeEnum op)
  21364. {
  21365. JSValue op1, op2;
  21366. int res;
  21367. uint32_t tag1, tag2;
  21368. op1 = sp[-2];
  21369. op2 = sp[-1];
  21370. tag1 = JS_VALUE_GET_NORM_TAG(op1);
  21371. tag2 = JS_VALUE_GET_NORM_TAG(op2);
  21372. op1 = JS_ToPrimitiveFree(ctx, op1, HINT_NUMBER);
  21373. if (JS_IsException(op1)) {
  21374. JS_FreeValue(ctx, op2);
  21375. goto exception;
  21376. }
  21377. op2 = JS_ToPrimitiveFree(ctx, op2, HINT_NUMBER);
  21378. if (JS_IsException(op2)) {
  21379. JS_FreeValue(ctx, op1);
  21380. goto exception;
  21381. }
  21382. tag1 = JS_VALUE_GET_NORM_TAG(op1);
  21383. tag2 = JS_VALUE_GET_NORM_TAG(op2);
  21384. if (tag1 == JS_TAG_STRING && tag2 == JS_TAG_STRING) {
  21385. JSString *p1, *p2;
  21386. p1 = JS_VALUE_GET_STRING(op1);
  21387. p2 = JS_VALUE_GET_STRING(op2);
  21388. res = js_string_compare(p1, p2);
  21389. switch(op) {
  21390. case OP_lt:
  21391. res = (res < 0);
  21392. break;
  21393. case OP_lte:
  21394. res = (res <= 0);
  21395. break;
  21396. case OP_gt:
  21397. res = (res > 0);
  21398. break;
  21399. default:
  21400. case OP_gte:
  21401. res = (res >= 0);
  21402. break;
  21403. }
  21404. JS_FreeValue(ctx, op1);
  21405. JS_FreeValue(ctx, op2);
  21406. } else if ((tag1 <= JS_TAG_NULL || tag1 == JS_TAG_FLOAT64) &&
  21407. (tag2 <= JS_TAG_NULL || tag2 == JS_TAG_FLOAT64)) {
  21408. /* fast path for float64/int */
  21409. goto float64_compare;
  21410. } else {
  21411. if (((tag1 == JS_TAG_BIG_INT && tag2 == JS_TAG_STRING) ||
  21412. (tag2 == JS_TAG_BIG_INT && tag1 == JS_TAG_STRING))) {
  21413. if (tag1 == JS_TAG_STRING) {
  21414. op1 = JS_StringToBigInt(ctx, op1);
  21415. if (JS_VALUE_GET_TAG(op1) != JS_TAG_BIG_INT)
  21416. goto invalid_bigint_string;
  21417. }
  21418. if (tag2 == JS_TAG_STRING) {
  21419. op2 = JS_StringToBigInt(ctx, op2);
  21420. if (JS_VALUE_GET_TAG(op2) != JS_TAG_BIG_INT) {
  21421. invalid_bigint_string:
  21422. JS_FreeValue(ctx, op1);
  21423. JS_FreeValue(ctx, op2);
  21424. res = false;
  21425. goto done;
  21426. }
  21427. }
  21428. } else {
  21429. op1 = JS_ToNumericFree(ctx, op1);
  21430. if (JS_IsException(op1)) {
  21431. JS_FreeValue(ctx, op2);
  21432. goto exception;
  21433. }
  21434. op2 = JS_ToNumericFree(ctx, op2);
  21435. if (JS_IsException(op2)) {
  21436. JS_FreeValue(ctx, op1);
  21437. goto exception;
  21438. }
  21439. }
  21440. tag1 = JS_VALUE_GET_NORM_TAG(op1);
  21441. tag2 = JS_VALUE_GET_NORM_TAG(op2);
  21442. if (tag1 == JS_TAG_BIG_INT || tag2 == JS_TAG_BIG_INT) {
  21443. res = js_compare_bigint(ctx, op, op1, op2);
  21444. if (res < 0)
  21445. goto exception;
  21446. } else {
  21447. double d1, d2;
  21448. float64_compare:
  21449. /* can use floating point comparison */
  21450. if (tag1 == JS_TAG_FLOAT64) {
  21451. d1 = JS_VALUE_GET_FLOAT64(op1);
  21452. } else {
  21453. d1 = JS_VALUE_GET_INT(op1);
  21454. }
  21455. if (tag2 == JS_TAG_FLOAT64) {
  21456. d2 = JS_VALUE_GET_FLOAT64(op2);
  21457. } else {
  21458. d2 = JS_VALUE_GET_INT(op2);
  21459. }
  21460. switch(op) {
  21461. case OP_lt:
  21462. res = (d1 < d2); /* if NaN return false */
  21463. break;
  21464. case OP_lte:
  21465. res = (d1 <= d2); /* if NaN return false */
  21466. break;
  21467. case OP_gt:
  21468. res = (d1 > d2); /* if NaN return false */
  21469. break;
  21470. default:
  21471. case OP_gte:
  21472. res = (d1 >= d2); /* if NaN return false */
  21473. break;
  21474. }
  21475. }
  21476. }
  21477. done:
  21478. sp[-2] = js_bool(res);
  21479. return 0;
  21480. exception:
  21481. sp[-2] = JS_UNDEFINED;
  21482. sp[-1] = JS_UNDEFINED;
  21483. return -1;
  21484. }
  21485. static bool tag_is_number(uint32_t tag)
  21486. {
  21487. return (tag == JS_TAG_INT || tag == JS_TAG_BIG_INT ||
  21488. tag == JS_TAG_FLOAT64);
  21489. }
  21490. static no_inline __exception int js_eq_slow(JSContext *ctx, JSValue *sp,
  21491. bool is_neq)
  21492. {
  21493. JSValue op1, op2;
  21494. int res;
  21495. uint32_t tag1, tag2;
  21496. op1 = sp[-2];
  21497. op2 = sp[-1];
  21498. redo:
  21499. tag1 = JS_VALUE_GET_NORM_TAG(op1);
  21500. tag2 = JS_VALUE_GET_NORM_TAG(op2);
  21501. if (tag_is_number(tag1) && tag_is_number(tag2)) {
  21502. if (tag1 == JS_TAG_INT && tag2 == JS_TAG_INT) {
  21503. res = JS_VALUE_GET_INT(op1) == JS_VALUE_GET_INT(op2);
  21504. } else if ((tag1 == JS_TAG_FLOAT64 &&
  21505. (tag2 == JS_TAG_INT || tag2 == JS_TAG_FLOAT64)) ||
  21506. (tag2 == JS_TAG_FLOAT64 &&
  21507. (tag1 == JS_TAG_INT || tag1 == JS_TAG_FLOAT64))) {
  21508. double d1, d2;
  21509. if (tag1 == JS_TAG_FLOAT64) {
  21510. d1 = JS_VALUE_GET_FLOAT64(op1);
  21511. } else {
  21512. d1 = JS_VALUE_GET_INT(op1);
  21513. }
  21514. if (tag2 == JS_TAG_FLOAT64) {
  21515. d2 = JS_VALUE_GET_FLOAT64(op2);
  21516. } else {
  21517. d2 = JS_VALUE_GET_INT(op2);
  21518. }
  21519. res = (d1 == d2);
  21520. } else {
  21521. res = js_compare_bigint(ctx, OP_eq, op1, op2);
  21522. if (res < 0)
  21523. goto exception;
  21524. }
  21525. } else if (tag1 == tag2) {
  21526. res = js_strict_eq2(ctx, op1, op2, JS_EQ_STRICT);
  21527. } else if ((tag1 == JS_TAG_NULL && tag2 == JS_TAG_UNDEFINED) ||
  21528. (tag2 == JS_TAG_NULL && tag1 == JS_TAG_UNDEFINED)) {
  21529. res = true;
  21530. } else if ((tag1 == JS_TAG_STRING && tag_is_number(tag2)) ||
  21531. (tag2 == JS_TAG_STRING && tag_is_number(tag1))) {
  21532. if ((tag1 == JS_TAG_BIG_INT || tag2 == JS_TAG_BIG_INT)) {
  21533. if (tag1 == JS_TAG_STRING) {
  21534. op1 = JS_StringToBigInt(ctx, op1);
  21535. if (JS_VALUE_GET_TAG(op1) != JS_TAG_BIG_INT)
  21536. goto invalid_bigint_string;
  21537. }
  21538. if (tag2 == JS_TAG_STRING) {
  21539. op2 = JS_StringToBigInt(ctx, op2);
  21540. if (JS_VALUE_GET_TAG(op2) != JS_TAG_BIG_INT) {
  21541. invalid_bigint_string:
  21542. JS_FreeValue(ctx, op1);
  21543. JS_FreeValue(ctx, op2);
  21544. res = false;
  21545. goto done;
  21546. }
  21547. }
  21548. } else {
  21549. op1 = JS_ToNumericFree(ctx, op1);
  21550. if (JS_IsException(op1)) {
  21551. JS_FreeValue(ctx, op2);
  21552. goto exception;
  21553. }
  21554. op2 = JS_ToNumericFree(ctx, op2);
  21555. if (JS_IsException(op2)) {
  21556. JS_FreeValue(ctx, op1);
  21557. goto exception;
  21558. }
  21559. }
  21560. res = js_strict_eq(ctx, op1, op2);
  21561. } else if (tag1 == JS_TAG_BOOL) {
  21562. op1 = js_int32(JS_VALUE_GET_INT(op1));
  21563. goto redo;
  21564. } else if (tag2 == JS_TAG_BOOL) {
  21565. op2 = js_int32(JS_VALUE_GET_INT(op2));
  21566. goto redo;
  21567. } else if ((tag1 == JS_TAG_OBJECT &&
  21568. (tag_is_number(tag2) || tag2 == JS_TAG_STRING || tag2 == JS_TAG_SYMBOL)) ||
  21569. (tag2 == JS_TAG_OBJECT &&
  21570. (tag_is_number(tag1) || tag1 == JS_TAG_STRING || tag1 == JS_TAG_SYMBOL))) {
  21571. op1 = JS_ToPrimitiveFree(ctx, op1, HINT_NONE);
  21572. if (JS_IsException(op1)) {
  21573. JS_FreeValue(ctx, op2);
  21574. goto exception;
  21575. }
  21576. op2 = JS_ToPrimitiveFree(ctx, op2, HINT_NONE);
  21577. if (JS_IsException(op2)) {
  21578. JS_FreeValue(ctx, op1);
  21579. goto exception;
  21580. }
  21581. goto redo;
  21582. } else {
  21583. /* IsHTMLDDA object is equivalent to undefined for '==' and '!=' */
  21584. if ((JS_IsHTMLDDA(ctx, op1) &&
  21585. (tag2 == JS_TAG_NULL || tag2 == JS_TAG_UNDEFINED)) ||
  21586. (JS_IsHTMLDDA(ctx, op2) &&
  21587. (tag1 == JS_TAG_NULL || tag1 == JS_TAG_UNDEFINED))) {
  21588. res = true;
  21589. } else {
  21590. res = false;
  21591. }
  21592. JS_FreeValue(ctx, op1);
  21593. JS_FreeValue(ctx, op2);
  21594. }
  21595. done:
  21596. sp[-2] = js_bool(res ^ is_neq);
  21597. return 0;
  21598. exception:
  21599. sp[-2] = JS_UNDEFINED;
  21600. sp[-1] = JS_UNDEFINED;
  21601. return -1;
  21602. }
  21603. static no_inline int js_shr_slow(JSContext *ctx, JSValue *sp)
  21604. {
  21605. JSValue op1, op2;
  21606. uint32_t v1, v2, r;
  21607. op1 = sp[-2];
  21608. op2 = sp[-1];
  21609. op1 = JS_ToNumericFree(ctx, op1);
  21610. if (JS_IsException(op1)) {
  21611. JS_FreeValue(ctx, op2);
  21612. goto exception;
  21613. }
  21614. op2 = JS_ToNumericFree(ctx, op2);
  21615. if (JS_IsException(op2)) {
  21616. JS_FreeValue(ctx, op1);
  21617. goto exception;
  21618. }
  21619. if ((JS_VALUE_GET_TAG(op1) == JS_TAG_BIG_INT ||
  21620. JS_VALUE_GET_TAG(op2) == JS_TAG_BIG_INT)) {
  21621. JS_ThrowTypeError(ctx, "BigInt operands are forbidden for >>>");
  21622. JS_FreeValue(ctx, op1);
  21623. JS_FreeValue(ctx, op2);
  21624. goto exception;
  21625. }
  21626. /* cannot give an exception */
  21627. JS_ToUint32Free(ctx, &v1, op1);
  21628. JS_ToUint32Free(ctx, &v2, op2);
  21629. r = v1 >> (v2 & 0x1f);
  21630. sp[-2] = js_uint32(r);
  21631. return 0;
  21632. exception:
  21633. sp[-2] = JS_UNDEFINED;
  21634. sp[-1] = JS_UNDEFINED;
  21635. return -1;
  21636. }
  21637. static bool js_strict_eq2(JSContext *ctx, JSValue op1, JSValue op2,
  21638. JSStrictEqModeEnum eq_mode)
  21639. {
  21640. bool res;
  21641. int tag1, tag2;
  21642. double d1, d2;
  21643. tag1 = JS_VALUE_GET_NORM_TAG(op1);
  21644. tag2 = JS_VALUE_GET_NORM_TAG(op2);
  21645. switch(tag1) {
  21646. case JS_TAG_BOOL:
  21647. if (tag1 != tag2) {
  21648. res = false;
  21649. } else {
  21650. res = JS_VALUE_GET_INT(op1) == JS_VALUE_GET_INT(op2);
  21651. goto done_no_free;
  21652. }
  21653. break;
  21654. case JS_TAG_NULL:
  21655. case JS_TAG_UNDEFINED:
  21656. res = (tag1 == tag2);
  21657. break;
  21658. case JS_TAG_STRING:
  21659. {
  21660. JSString *p1, *p2;
  21661. if (tag1 != tag2) {
  21662. res = false;
  21663. } else {
  21664. p1 = JS_VALUE_GET_STRING(op1);
  21665. p2 = JS_VALUE_GET_STRING(op2);
  21666. res = js_string_eq(p1, p2);
  21667. }
  21668. }
  21669. break;
  21670. case JS_TAG_SYMBOL:
  21671. {
  21672. JSAtomStruct *p1, *p2;
  21673. if (tag1 != tag2) {
  21674. res = false;
  21675. } else {
  21676. p1 = JS_VALUE_GET_PTR(op1);
  21677. p2 = JS_VALUE_GET_PTR(op2);
  21678. res = (p1 == p2);
  21679. }
  21680. }
  21681. break;
  21682. case JS_TAG_OBJECT:
  21683. if (tag1 != tag2)
  21684. res = false;
  21685. else
  21686. res = JS_VALUE_GET_OBJ(op1) == JS_VALUE_GET_OBJ(op2);
  21687. break;
  21688. case JS_TAG_INT:
  21689. d1 = JS_VALUE_GET_INT(op1);
  21690. if (tag2 == JS_TAG_INT) {
  21691. d2 = JS_VALUE_GET_INT(op2);
  21692. goto number_test;
  21693. } else if (tag2 == JS_TAG_FLOAT64) {
  21694. d2 = JS_VALUE_GET_FLOAT64(op2);
  21695. goto number_test;
  21696. } else {
  21697. res = false;
  21698. }
  21699. break;
  21700. case JS_TAG_FLOAT64:
  21701. d1 = JS_VALUE_GET_FLOAT64(op1);
  21702. if (tag2 == JS_TAG_FLOAT64) {
  21703. d2 = JS_VALUE_GET_FLOAT64(op2);
  21704. } else if (tag2 == JS_TAG_INT) {
  21705. d2 = JS_VALUE_GET_INT(op2);
  21706. } else {
  21707. res = false;
  21708. break;
  21709. }
  21710. number_test:
  21711. if (unlikely(eq_mode >= JS_EQ_SAME_VALUE)) {
  21712. JSFloat64Union u1, u2;
  21713. /* NaN is not always normalized, so this test is necessary */
  21714. if (isnan(d1) || isnan(d2)) {
  21715. res = isnan(d1) == isnan(d2);
  21716. } else if (eq_mode == JS_EQ_SAME_VALUE_ZERO) {
  21717. res = (d1 == d2); /* +0 == -0 */
  21718. } else {
  21719. u1.d = d1;
  21720. u2.d = d2;
  21721. res = (u1.u64 == u2.u64); /* +0 != -0 */
  21722. }
  21723. } else {
  21724. res = (d1 == d2); /* if NaN return false and +0 == -0 */
  21725. }
  21726. goto done_no_free;
  21727. case JS_TAG_BIG_INT:
  21728. {
  21729. bf_t a_s, *a, b_s, *b;
  21730. if (tag1 != tag2) {
  21731. res = false;
  21732. break;
  21733. }
  21734. a = JS_ToBigInt1(ctx, &a_s, op1);
  21735. b = JS_ToBigInt1(ctx, &b_s, op2);
  21736. res = bf_cmp_eq(a, b);
  21737. if (a == &a_s)
  21738. bf_delete(a);
  21739. if (b == &b_s)
  21740. bf_delete(b);
  21741. }
  21742. break;
  21743. default:
  21744. res = false;
  21745. break;
  21746. }
  21747. JS_FreeValue(ctx, op1);
  21748. JS_FreeValue(ctx, op2);
  21749. done_no_free:
  21750. return res;
  21751. }
  21752. static bool js_strict_eq(JSContext *ctx, JSValue op1, JSValue op2)
  21753. {
  21754. return js_strict_eq2(ctx, op1, op2, JS_EQ_STRICT);
  21755. }
  21756. static bool js_same_value(JSContext *ctx, JSValueConst op1, JSValueConst op2)
  21757. {
  21758. return js_strict_eq2(ctx, js_dup(op1), js_dup(op2), JS_EQ_SAME_VALUE);
  21759. }
  21760. static bool js_same_value_zero(JSContext *ctx, JSValueConst op1, JSValueConst op2)
  21761. {
  21762. return js_strict_eq2(ctx, js_dup(op1), js_dup(op2), JS_EQ_SAME_VALUE_ZERO);
  21763. }
  21764. static no_inline int js_strict_eq_slow(JSContext *ctx, JSValue *sp,
  21765. bool is_neq)
  21766. {
  21767. bool res;
  21768. res = js_strict_eq(ctx, sp[-2], sp[-1]);
  21769. sp[-2] = js_bool(res ^ is_neq);
  21770. return 0;
  21771. }
  21772. static __exception int js_operator_in(JSContext *ctx, JSValue *sp)
  21773. {
  21774. JSValue op1, op2;
  21775. JSAtom atom;
  21776. int ret;
  21777. op1 = sp[-2];
  21778. op2 = sp[-1];
  21779. if (JS_VALUE_GET_TAG(op2) != JS_TAG_OBJECT) {
  21780. JS_ThrowTypeError(ctx, "invalid 'in' operand");
  21781. return -1;
  21782. }
  21783. atom = JS_ValueToAtom(ctx, op1);
  21784. if (unlikely(atom == JS_ATOM_NULL))
  21785. return -1;
  21786. ret = JS_HasProperty(ctx, op2, atom);
  21787. JS_FreeAtom(ctx, atom);
  21788. if (ret < 0)
  21789. return -1;
  21790. JS_FreeValue(ctx, op1);
  21791. JS_FreeValue(ctx, op2);
  21792. sp[-2] = js_bool(ret);
  21793. return 0;
  21794. }
  21795. static __exception int js_operator_private_in(JSContext *ctx, JSValue *sp)
  21796. {
  21797. JSValue op1, op2;
  21798. int ret;
  21799. op1 = sp[-2]; /* object */
  21800. op2 = sp[-1]; /* field name or method function */
  21801. if (JS_VALUE_GET_TAG(op1) != JS_TAG_OBJECT) {
  21802. JS_ThrowTypeError(ctx, "invalid 'in' operand");
  21803. return -1;
  21804. }
  21805. if (JS_IsObject(op2)) {
  21806. /* method: use the brand */
  21807. ret = JS_CheckBrand(ctx, op1, op2);
  21808. if (ret < 0)
  21809. return -1;
  21810. } else {
  21811. JSAtom atom;
  21812. JSObject *p;
  21813. JSShapeProperty *prs;
  21814. JSProperty *pr;
  21815. /* field */
  21816. atom = JS_ValueToAtom(ctx, op2);
  21817. if (unlikely(atom == JS_ATOM_NULL))
  21818. return -1;
  21819. p = JS_VALUE_GET_OBJ(op1);
  21820. prs = find_own_property(&pr, p, atom);
  21821. JS_FreeAtom(ctx, atom);
  21822. ret = (prs != NULL);
  21823. }
  21824. JS_FreeValue(ctx, op1);
  21825. JS_FreeValue(ctx, op2);
  21826. sp[-2] = JS_NewBool(ctx, ret);
  21827. return 0;
  21828. }
  21829. static __exception int js_has_unscopable(JSContext *ctx, JSValue obj,
  21830. JSAtom atom)
  21831. {
  21832. JSValue arr, val;
  21833. int ret;
  21834. arr = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_unscopables);
  21835. if (JS_IsException(arr))
  21836. return -1;
  21837. ret = 0;
  21838. if (JS_IsObject(arr)) {
  21839. val = JS_GetProperty(ctx, arr, atom);
  21840. ret = JS_ToBoolFree(ctx, val);
  21841. }
  21842. JS_FreeValue(ctx, arr);
  21843. return ret;
  21844. }
  21845. static __exception int js_operator_instanceof(JSContext *ctx, JSValue *sp)
  21846. {
  21847. JSValue op1, op2;
  21848. int ret;
  21849. op1 = sp[-2];
  21850. op2 = sp[-1];
  21851. ret = JS_IsInstanceOf(ctx, op1, op2);
  21852. if (ret < 0)
  21853. return ret;
  21854. JS_FreeValue(ctx, op1);
  21855. JS_FreeValue(ctx, op2);
  21856. sp[-2] = js_bool(ret);
  21857. return 0;
  21858. }
  21859. static __exception int js_operator_typeof(JSContext *ctx, JSValue op1)
  21860. {
  21861. JSAtom atom;
  21862. uint32_t tag;
  21863. tag = JS_VALUE_GET_NORM_TAG(op1);
  21864. switch(tag) {
  21865. case JS_TAG_BIG_INT:
  21866. atom = JS_ATOM_bigint;
  21867. break;
  21868. case JS_TAG_INT:
  21869. case JS_TAG_FLOAT64:
  21870. atom = JS_ATOM_number;
  21871. break;
  21872. case JS_TAG_UNDEFINED:
  21873. atom = JS_ATOM_undefined;
  21874. break;
  21875. case JS_TAG_BOOL:
  21876. atom = JS_ATOM_boolean;
  21877. break;
  21878. case JS_TAG_STRING:
  21879. atom = JS_ATOM_string;
  21880. break;
  21881. case JS_TAG_OBJECT:
  21882. {
  21883. JSObject *p;
  21884. p = JS_VALUE_GET_OBJ(op1);
  21885. if (unlikely(p->is_HTMLDDA))
  21886. atom = JS_ATOM_undefined;
  21887. else if (JS_IsFunction(ctx, op1))
  21888. atom = JS_ATOM_function;
  21889. else
  21890. goto obj_type;
  21891. }
  21892. break;
  21893. case JS_TAG_NULL:
  21894. obj_type:
  21895. atom = JS_ATOM_object;
  21896. break;
  21897. case JS_TAG_SYMBOL:
  21898. atom = JS_ATOM_symbol;
  21899. break;
  21900. default:
  21901. atom = JS_ATOM_unknown;
  21902. break;
  21903. }
  21904. return atom;
  21905. }
  21906. static __exception int js_operator_delete(JSContext *ctx, JSValue *sp)
  21907. {
  21908. JSValue op1, op2;
  21909. JSAtom atom;
  21910. int ret;
  21911. op1 = sp[-2];
  21912. op2 = sp[-1];
  21913. atom = JS_ValueToAtom(ctx, op2);
  21914. if (unlikely(atom == JS_ATOM_NULL))
  21915. return -1;
  21916. ret = JS_DeleteProperty(ctx, op1, atom, JS_PROP_THROW_STRICT);
  21917. JS_FreeAtom(ctx, atom);
  21918. if (unlikely(ret < 0))
  21919. return -1;
  21920. JS_FreeValue(ctx, op1);
  21921. JS_FreeValue(ctx, op2);
  21922. sp[-2] = js_bool(ret);
  21923. return 0;
  21924. }
  21925. static JSValue js_throw_type_error(JSContext *ctx, JSValueConst this_val,
  21926. int argc, JSValueConst *argv)
  21927. {
  21928. return JS_ThrowTypeError(ctx, "invalid property access");
  21929. }
  21930. /* XXX: not 100% compatible, but mozilla seems to use a similar
  21931. implementation to ensure that caller in non strict mode does not
  21932. throw (ES5 compatibility) */
  21933. static JSValue js_function_proto_caller(JSContext *ctx, JSValueConst this_val,
  21934. int argc, JSValueConst *argv)
  21935. {
  21936. JSFunctionBytecode *b = JS_GetFunctionBytecode(this_val);
  21937. if (!b || b->is_strict_mode || !b->has_prototype) {
  21938. return js_throw_type_error(ctx, this_val, 0, NULL);
  21939. }
  21940. return JS_UNDEFINED;
  21941. }
  21942. static JSValue js_function_proto_fileName(JSContext *ctx,
  21943. JSValueConst this_val)
  21944. {
  21945. JSFunctionBytecode *b = JS_GetFunctionBytecode(this_val);
  21946. if (b) {
  21947. return JS_AtomToString(ctx, b->filename);
  21948. }
  21949. return JS_UNDEFINED;
  21950. }
  21951. static JSValue js_function_proto_int32(JSContext *ctx,
  21952. JSValueConst this_val,
  21953. int magic)
  21954. {
  21955. JSFunctionBytecode *b = JS_GetFunctionBytecode(this_val);
  21956. if (b) {
  21957. int *field = (int *) ((char *)b + magic);
  21958. return js_int32(*field);
  21959. }
  21960. return JS_UNDEFINED;
  21961. }
  21962. static int js_arguments_define_own_property(JSContext *ctx,
  21963. JSValueConst this_obj,
  21964. JSAtom prop, JSValueConst val,
  21965. JSValueConst getter,
  21966. JSValueConst setter, int flags)
  21967. {
  21968. JSObject *p;
  21969. uint32_t idx;
  21970. p = JS_VALUE_GET_OBJ(this_obj);
  21971. /* convert to normal array when redefining an existing numeric field */
  21972. if (p->fast_array && JS_AtomIsArrayIndex(ctx, &idx, prop) &&
  21973. idx < p->u.array.count) {
  21974. if (convert_fast_array_to_array(ctx, p))
  21975. return -1;
  21976. }
  21977. /* run the default define own property */
  21978. return JS_DefineProperty(ctx, this_obj, prop, val, getter, setter,
  21979. flags | JS_PROP_NO_EXOTIC);
  21980. }
  21981. static const JSClassExoticMethods js_arguments_exotic_methods = {
  21982. .define_own_property = js_arguments_define_own_property,
  21983. };
  21984. static JSValue js_build_arguments(JSContext *ctx, int argc, JSValueConst *argv)
  21985. {
  21986. JSValue val, *tab;
  21987. JSProperty *pr;
  21988. JSObject *p;
  21989. int i;
  21990. val = JS_NewObjectProtoClass(ctx, ctx->class_proto[JS_CLASS_OBJECT],
  21991. JS_CLASS_ARGUMENTS);
  21992. if (JS_IsException(val))
  21993. return val;
  21994. p = JS_VALUE_GET_OBJ(val);
  21995. /* add the length field (cannot fail) */
  21996. pr = add_property(ctx, p, JS_ATOM_length,
  21997. JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);
  21998. if (!pr) {
  21999. JS_FreeValue(ctx, val);
  22000. return JS_EXCEPTION;
  22001. }
  22002. pr->u.value = js_int32(argc);
  22003. /* initialize the fast array part */
  22004. tab = NULL;
  22005. if (argc > 0) {
  22006. tab = js_malloc(ctx, sizeof(tab[0]) * argc);
  22007. if (!tab) {
  22008. JS_FreeValue(ctx, val);
  22009. return JS_EXCEPTION;
  22010. }
  22011. for(i = 0; i < argc; i++) {
  22012. tab[i] = js_dup(argv[i]);
  22013. }
  22014. }
  22015. p->u.array.u.values = tab;
  22016. p->u.array.count = argc;
  22017. JS_DefinePropertyValue(ctx, val, JS_ATOM_Symbol_iterator,
  22018. js_dup(ctx->array_proto_values),
  22019. JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE);
  22020. /* add callee property to throw a TypeError in strict mode */
  22021. JS_DefineProperty(ctx, val, JS_ATOM_callee, JS_UNDEFINED,
  22022. ctx->throw_type_error, ctx->throw_type_error,
  22023. JS_PROP_HAS_GET | JS_PROP_HAS_SET);
  22024. return val;
  22025. }
  22026. #define GLOBAL_VAR_OFFSET 0x40000000
  22027. #define ARGUMENT_VAR_OFFSET 0x20000000
  22028. /* legacy arguments object: add references to the function arguments */
  22029. static JSValue js_build_mapped_arguments(JSContext *ctx, int argc,
  22030. JSValueConst *argv,
  22031. JSStackFrame *sf, int arg_count)
  22032. {
  22033. JSValue val;
  22034. JSProperty *pr;
  22035. JSObject *p;
  22036. int i;
  22037. val = JS_NewObjectProtoClass(ctx, ctx->class_proto[JS_CLASS_OBJECT],
  22038. JS_CLASS_MAPPED_ARGUMENTS);
  22039. if (JS_IsException(val))
  22040. return val;
  22041. p = JS_VALUE_GET_OBJ(val);
  22042. /* add the length field (cannot fail) */
  22043. pr = add_property(ctx, p, JS_ATOM_length,
  22044. JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);
  22045. if (!pr)
  22046. goto fail;
  22047. pr->u.value = js_int32(argc);
  22048. for(i = 0; i < arg_count; i++) {
  22049. JSVarRef *var_ref;
  22050. var_ref = get_var_ref(ctx, sf, i, true);
  22051. if (!var_ref)
  22052. goto fail;
  22053. pr = add_property(ctx, p, __JS_AtomFromUInt32(i), JS_PROP_C_W_E | JS_PROP_VARREF);
  22054. if (!pr) {
  22055. free_var_ref(ctx->rt, var_ref);
  22056. goto fail;
  22057. }
  22058. pr->u.var_ref = var_ref;
  22059. }
  22060. /* the arguments not mapped to the arguments of the function can
  22061. be normal properties */
  22062. for(i = arg_count; i < argc; i++) {
  22063. if (JS_DefinePropertyValueUint32(ctx, val, i,
  22064. js_dup(argv[i]),
  22065. JS_PROP_C_W_E) < 0)
  22066. goto fail;
  22067. }
  22068. JS_DefinePropertyValue(ctx, val, JS_ATOM_Symbol_iterator,
  22069. js_dup(ctx->array_proto_values),
  22070. JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE);
  22071. /* callee returns this function in non strict mode */
  22072. JS_DefinePropertyValue(ctx, val, JS_ATOM_callee,
  22073. js_dup(ctx->rt->current_stack_frame->cur_func),
  22074. JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE);
  22075. return val;
  22076. fail:
  22077. JS_FreeValue(ctx, val);
  22078. return JS_EXCEPTION;
  22079. }
  22080. static JSValue build_for_in_iterator(JSContext *ctx, JSValue obj)
  22081. {
  22082. JSObject *p;
  22083. JSPropertyEnum *tab_atom;
  22084. int i;
  22085. JSValue enum_obj, obj1;
  22086. JSForInIterator *it;
  22087. uint32_t tag, tab_atom_count;
  22088. tag = JS_VALUE_GET_TAG(obj);
  22089. if (tag != JS_TAG_OBJECT && tag != JS_TAG_NULL && tag != JS_TAG_UNDEFINED) {
  22090. obj = JS_ToObjectFree(ctx, obj);
  22091. }
  22092. it = js_malloc(ctx, sizeof(*it));
  22093. if (!it) {
  22094. JS_FreeValue(ctx, obj);
  22095. return JS_EXCEPTION;
  22096. }
  22097. enum_obj = JS_NewObjectProtoClass(ctx, JS_NULL, JS_CLASS_FOR_IN_ITERATOR);
  22098. if (JS_IsException(enum_obj)) {
  22099. js_free(ctx, it);
  22100. JS_FreeValue(ctx, obj);
  22101. return JS_EXCEPTION;
  22102. }
  22103. it->is_array = false;
  22104. it->obj = obj;
  22105. it->idx = 0;
  22106. p = JS_VALUE_GET_OBJ(enum_obj);
  22107. p->u.for_in_iterator = it;
  22108. if (tag == JS_TAG_NULL || tag == JS_TAG_UNDEFINED)
  22109. return enum_obj;
  22110. /* fast path: assume no enumerable properties in the prototype chain */
  22111. obj1 = js_dup(obj);
  22112. for(;;) {
  22113. obj1 = JS_GetPrototypeFree(ctx, obj1);
  22114. if (JS_IsNull(obj1))
  22115. break;
  22116. if (JS_IsException(obj1))
  22117. goto fail;
  22118. if (JS_GetOwnPropertyNamesInternal(ctx, &tab_atom, &tab_atom_count,
  22119. JS_VALUE_GET_OBJ(obj1),
  22120. JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY)) {
  22121. JS_FreeValue(ctx, obj1);
  22122. goto fail;
  22123. }
  22124. js_free_prop_enum(ctx, tab_atom, tab_atom_count);
  22125. if (tab_atom_count != 0) {
  22126. JS_FreeValue(ctx, obj1);
  22127. goto slow_path;
  22128. }
  22129. /* must check for timeout to avoid infinite loop */
  22130. if (js_poll_interrupts(ctx)) {
  22131. JS_FreeValue(ctx, obj1);
  22132. goto fail;
  22133. }
  22134. }
  22135. p = JS_VALUE_GET_OBJ(obj);
  22136. if (p->fast_array) {
  22137. JSShape *sh;
  22138. JSShapeProperty *prs;
  22139. /* check that there are no enumerable normal fields */
  22140. sh = p->shape;
  22141. for(i = 0, prs = get_shape_prop(sh); i < sh->prop_count; i++, prs++) {
  22142. if (prs->flags & JS_PROP_ENUMERABLE)
  22143. goto normal_case;
  22144. }
  22145. /* for fast arrays, we only store the number of elements */
  22146. it->is_array = true;
  22147. it->array_length = p->u.array.count;
  22148. } else {
  22149. normal_case:
  22150. if (JS_GetOwnPropertyNamesInternal(ctx, &tab_atom, &tab_atom_count, p,
  22151. JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY))
  22152. goto fail;
  22153. for(i = 0; i < tab_atom_count; i++) {
  22154. JS_SetPropertyInternal(ctx, enum_obj, tab_atom[i].atom, JS_NULL, 0);
  22155. }
  22156. js_free_prop_enum(ctx, tab_atom, tab_atom_count);
  22157. }
  22158. return enum_obj;
  22159. slow_path:
  22160. /* non enumerable properties hide the enumerables ones in the
  22161. prototype chain */
  22162. obj1 = js_dup(obj);
  22163. for(;;) {
  22164. if (JS_GetOwnPropertyNamesInternal(ctx, &tab_atom, &tab_atom_count,
  22165. JS_VALUE_GET_OBJ(obj1),
  22166. JS_GPN_STRING_MASK | JS_GPN_SET_ENUM)) {
  22167. JS_FreeValue(ctx, obj1);
  22168. goto fail;
  22169. }
  22170. for(i = 0; i < tab_atom_count; i++) {
  22171. JS_DefinePropertyValue(ctx, enum_obj, tab_atom[i].atom, JS_NULL,
  22172. (tab_atom[i].is_enumerable ?
  22173. JS_PROP_ENUMERABLE : 0));
  22174. }
  22175. js_free_prop_enum(ctx, tab_atom, tab_atom_count);
  22176. obj1 = JS_GetPrototypeFree(ctx, obj1);
  22177. if (JS_IsNull(obj1))
  22178. break;
  22179. if (JS_IsException(obj1))
  22180. goto fail;
  22181. /* must check for timeout to avoid infinite loop */
  22182. if (js_poll_interrupts(ctx)) {
  22183. JS_FreeValue(ctx, obj1);
  22184. goto fail;
  22185. }
  22186. }
  22187. return enum_obj;
  22188. fail:
  22189. JS_FreeValue(ctx, enum_obj);
  22190. return JS_EXCEPTION;
  22191. }
  22192. /* obj -> enum_obj */
  22193. static __exception int js_for_in_start(JSContext *ctx, JSValue *sp)
  22194. {
  22195. sp[-1] = build_for_in_iterator(ctx, sp[-1]);
  22196. if (JS_IsException(sp[-1]))
  22197. return -1;
  22198. return 0;
  22199. }
  22200. /* enum_obj -> enum_obj value done */
  22201. static __exception int js_for_in_next(JSContext *ctx, JSValue *sp)
  22202. {
  22203. JSValue enum_obj;
  22204. JSObject *p;
  22205. JSAtom prop;
  22206. JSForInIterator *it;
  22207. int ret;
  22208. enum_obj = sp[-1];
  22209. /* fail safe */
  22210. if (JS_VALUE_GET_TAG(enum_obj) != JS_TAG_OBJECT)
  22211. goto done;
  22212. p = JS_VALUE_GET_OBJ(enum_obj);
  22213. if (p->class_id != JS_CLASS_FOR_IN_ITERATOR)
  22214. goto done;
  22215. it = p->u.for_in_iterator;
  22216. for(;;) {
  22217. if (it->is_array) {
  22218. if (it->idx >= it->array_length)
  22219. goto done;
  22220. prop = __JS_AtomFromUInt32(it->idx);
  22221. it->idx++;
  22222. } else {
  22223. JSShape *sh = p->shape;
  22224. JSShapeProperty *prs;
  22225. if (it->idx >= sh->prop_count)
  22226. goto done;
  22227. prs = get_shape_prop(sh) + it->idx;
  22228. prop = prs->atom;
  22229. it->idx++;
  22230. if (prop == JS_ATOM_NULL || !(prs->flags & JS_PROP_ENUMERABLE))
  22231. continue;
  22232. }
  22233. // check if the property was deleted unless we're dealing with a proxy
  22234. JSValue obj = it->obj;
  22235. if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) {
  22236. JSObject *p = JS_VALUE_GET_OBJ(obj);
  22237. if (p->class_id == JS_CLASS_PROXY)
  22238. break;
  22239. }
  22240. ret = JS_HasProperty(ctx, obj, prop);
  22241. if (ret < 0)
  22242. return ret;
  22243. if (ret)
  22244. break;
  22245. }
  22246. /* return the property */
  22247. sp[0] = JS_AtomToValue(ctx, prop);
  22248. sp[1] = JS_FALSE;
  22249. return 0;
  22250. done:
  22251. /* return the end */
  22252. sp[0] = JS_UNDEFINED;
  22253. sp[1] = JS_TRUE;
  22254. return 0;
  22255. }
  22256. static JSValue JS_GetIterator2(JSContext *ctx, JSValueConst obj,
  22257. JSValueConst method)
  22258. {
  22259. JSValue enum_obj;
  22260. enum_obj = JS_Call(ctx, method, obj, 0, NULL);
  22261. if (JS_IsException(enum_obj))
  22262. return enum_obj;
  22263. if (!JS_IsObject(enum_obj)) {
  22264. JS_FreeValue(ctx, enum_obj);
  22265. return JS_ThrowTypeErrorNotAnObject(ctx);
  22266. }
  22267. return enum_obj;
  22268. }
  22269. static JSValue JS_GetIterator(JSContext *ctx, JSValueConst obj, bool is_async)
  22270. {
  22271. JSValue method, ret, sync_iter;
  22272. if (is_async) {
  22273. method = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_asyncIterator);
  22274. if (JS_IsException(method))
  22275. return method;
  22276. if (JS_IsUndefined(method) || JS_IsNull(method)) {
  22277. method = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_iterator);
  22278. if (JS_IsException(method))
  22279. return method;
  22280. sync_iter = JS_GetIterator2(ctx, obj, method);
  22281. JS_FreeValue(ctx, method);
  22282. if (JS_IsException(sync_iter))
  22283. return sync_iter;
  22284. ret = JS_CreateAsyncFromSyncIterator(ctx, sync_iter);
  22285. JS_FreeValue(ctx, sync_iter);
  22286. return ret;
  22287. }
  22288. } else {
  22289. method = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_iterator);
  22290. if (JS_IsException(method))
  22291. return method;
  22292. }
  22293. if (!JS_IsFunction(ctx, method)) {
  22294. JS_FreeValue(ctx, method);
  22295. return JS_ThrowTypeError(ctx, "value is not iterable");
  22296. }
  22297. ret = JS_GetIterator2(ctx, obj, method);
  22298. JS_FreeValue(ctx, method);
  22299. return ret;
  22300. }
  22301. /* return *pdone = 2 if the iterator object is not parsed */
  22302. static JSValue JS_IteratorNext2(JSContext *ctx, JSValueConst enum_obj,
  22303. JSValueConst method,
  22304. int argc, JSValueConst *argv, int *pdone)
  22305. {
  22306. JSValue obj;
  22307. /* fast path for the built-in iterators (avoid creating the
  22308. intermediate result object) */
  22309. if (JS_IsObject(method)) {
  22310. JSObject *p = JS_VALUE_GET_OBJ(method);
  22311. if (p->class_id == JS_CLASS_C_FUNCTION &&
  22312. p->u.cfunc.cproto == JS_CFUNC_iterator_next) {
  22313. JSCFunctionType func;
  22314. JSValueConst args[1];
  22315. /* in case the function expects one argument */
  22316. if (argc == 0) {
  22317. args[0] = JS_UNDEFINED;
  22318. argv = args;
  22319. }
  22320. func = p->u.cfunc.c_function;
  22321. return func.iterator_next(ctx, enum_obj, argc, argv,
  22322. pdone, p->u.cfunc.magic);
  22323. }
  22324. }
  22325. obj = JS_Call(ctx, method, enum_obj, argc, argv);
  22326. if (JS_IsException(obj))
  22327. goto fail;
  22328. if (!JS_IsObject(obj)) {
  22329. JS_FreeValue(ctx, obj);
  22330. JS_ThrowTypeError(ctx, "iterator must return an object");
  22331. goto fail;
  22332. }
  22333. *pdone = 2;
  22334. return obj;
  22335. fail:
  22336. *pdone = false;
  22337. return JS_EXCEPTION;
  22338. }
  22339. static JSValue JS_IteratorNext(JSContext *ctx, JSValueConst enum_obj,
  22340. JSValueConst method,
  22341. int argc, JSValueConst *argv, int *pdone)
  22342. {
  22343. JSValue obj, value, done_val;
  22344. int done;
  22345. obj = JS_IteratorNext2(ctx, enum_obj, method, argc, argv, &done);
  22346. if (JS_IsException(obj))
  22347. goto fail;
  22348. if (done != 2) {
  22349. *pdone = done;
  22350. return obj;
  22351. } else {
  22352. done_val = JS_GetProperty(ctx, obj, JS_ATOM_done);
  22353. if (JS_IsException(done_val))
  22354. goto fail;
  22355. *pdone = JS_ToBoolFree(ctx, done_val);
  22356. value = JS_UNDEFINED;
  22357. if (!*pdone) {
  22358. value = JS_GetProperty(ctx, obj, JS_ATOM_value);
  22359. }
  22360. JS_FreeValue(ctx, obj);
  22361. return value;
  22362. }
  22363. fail:
  22364. JS_FreeValue(ctx, obj);
  22365. *pdone = false;
  22366. return JS_EXCEPTION;
  22367. }
  22368. /* return < 0 in case of exception */
  22369. static int JS_IteratorClose(JSContext *ctx, JSValueConst enum_obj,
  22370. bool is_exception_pending)
  22371. {
  22372. JSValue method, ret, ex_obj;
  22373. int res;
  22374. if (is_exception_pending) {
  22375. ex_obj = ctx->rt->current_exception;
  22376. ctx->rt->current_exception = JS_UNINITIALIZED;
  22377. res = -1;
  22378. } else {
  22379. ex_obj = JS_UNDEFINED;
  22380. res = 0;
  22381. }
  22382. method = JS_GetProperty(ctx, enum_obj, JS_ATOM_return);
  22383. if (JS_IsException(method)) {
  22384. res = -1;
  22385. goto done;
  22386. }
  22387. if (JS_IsUndefined(method) || JS_IsNull(method)) {
  22388. goto done;
  22389. }
  22390. ret = JS_CallFree(ctx, method, enum_obj, 0, NULL);
  22391. if (!is_exception_pending) {
  22392. if (JS_IsException(ret)) {
  22393. res = -1;
  22394. } else if (!JS_IsObject(ret)) {
  22395. JS_ThrowTypeErrorNotAnObject(ctx);
  22396. res = -1;
  22397. }
  22398. }
  22399. JS_FreeValue(ctx, ret);
  22400. done:
  22401. if (is_exception_pending) {
  22402. JS_Throw(ctx, ex_obj);
  22403. }
  22404. return res;
  22405. }
  22406. /* obj -> enum_rec (3 slots) */
  22407. static __exception int js_for_of_start(JSContext *ctx, JSValue *sp,
  22408. bool is_async)
  22409. {
  22410. JSValue op1, obj, method;
  22411. op1 = sp[-1];
  22412. obj = JS_GetIterator(ctx, op1, is_async);
  22413. if (JS_IsException(obj))
  22414. return -1;
  22415. JS_FreeValue(ctx, op1);
  22416. sp[-1] = obj;
  22417. method = JS_GetProperty(ctx, obj, JS_ATOM_next);
  22418. if (JS_IsException(method))
  22419. return -1;
  22420. sp[0] = method;
  22421. return 0;
  22422. }
  22423. /* enum_rec [objs] -> enum_rec [objs] value done. There are 'offset'
  22424. objs. If 'done' is true or in case of exception, 'enum_rec' is set
  22425. to undefined. If 'done' is true, 'value' is always set to
  22426. undefined. */
  22427. static __exception int js_for_of_next(JSContext *ctx, JSValue *sp, int offset)
  22428. {
  22429. JSValue value = JS_UNDEFINED;
  22430. int done = 1;
  22431. if (likely(!JS_IsUndefined(sp[offset]))) {
  22432. value = JS_IteratorNext(ctx, sp[offset], sp[offset + 1], 0, NULL, &done);
  22433. if (JS_IsException(value))
  22434. done = -1;
  22435. if (done) {
  22436. /* value is JS_UNDEFINED or JS_EXCEPTION */
  22437. /* replace the iteration object with undefined */
  22438. JS_FreeValue(ctx, sp[offset]);
  22439. sp[offset] = JS_UNDEFINED;
  22440. if (done < 0) {
  22441. return -1;
  22442. } else {
  22443. JS_FreeValue(ctx, value);
  22444. value = JS_UNDEFINED;
  22445. }
  22446. }
  22447. }
  22448. sp[0] = value;
  22449. sp[1] = js_bool(done);
  22450. return 0;
  22451. }
  22452. static JSValue JS_IteratorGetCompleteValue(JSContext *ctx, JSValue obj,
  22453. int *pdone)
  22454. {
  22455. JSValue done_val, value;
  22456. int done;
  22457. done_val = JS_GetProperty(ctx, obj, JS_ATOM_done);
  22458. if (JS_IsException(done_val))
  22459. goto fail;
  22460. done = JS_ToBoolFree(ctx, done_val);
  22461. value = JS_GetProperty(ctx, obj, JS_ATOM_value);
  22462. if (JS_IsException(value))
  22463. goto fail;
  22464. *pdone = done;
  22465. return value;
  22466. fail:
  22467. *pdone = false;
  22468. return JS_EXCEPTION;
  22469. }
  22470. static __exception int js_iterator_get_value_done(JSContext *ctx, JSValue *sp)
  22471. {
  22472. JSValue obj, value;
  22473. int done;
  22474. obj = sp[-1];
  22475. if (!JS_IsObject(obj)) {
  22476. JS_ThrowTypeError(ctx, "iterator must return an object");
  22477. return -1;
  22478. }
  22479. value = JS_IteratorGetCompleteValue(ctx, obj, &done);
  22480. if (JS_IsException(value))
  22481. return -1;
  22482. JS_FreeValue(ctx, obj);
  22483. sp[-1] = value;
  22484. sp[0] = js_bool(done);
  22485. return 0;
  22486. }
  22487. static JSValue js_create_iterator_result(JSContext *ctx,
  22488. JSValue val,
  22489. bool done)
  22490. {
  22491. JSValue obj;
  22492. obj = JS_NewObject(ctx);
  22493. if (JS_IsException(obj)) {
  22494. JS_FreeValue(ctx, val);
  22495. return obj;
  22496. }
  22497. if (JS_DefinePropertyValue(ctx, obj, JS_ATOM_value,
  22498. val, JS_PROP_C_W_E) < 0) {
  22499. goto fail;
  22500. }
  22501. if (JS_DefinePropertyValue(ctx, obj, JS_ATOM_done,
  22502. js_bool(done), JS_PROP_C_W_E) < 0) {
  22503. fail:
  22504. JS_FreeValue(ctx, obj);
  22505. return JS_EXCEPTION;
  22506. }
  22507. return obj;
  22508. }
  22509. static JSValue js_array_iterator_next(JSContext *ctx, JSValueConst this_val,
  22510. int argc, JSValueConst *argv,
  22511. int *pdone, int magic);
  22512. static JSValue js_create_array_iterator(JSContext *ctx, JSValueConst this_val,
  22513. int argc, JSValueConst *argv, int magic);
  22514. static bool js_is_fast_array(JSContext *ctx, JSValue obj)
  22515. {
  22516. /* Try and handle fast arrays explicitly */
  22517. if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) {
  22518. JSObject *p = JS_VALUE_GET_OBJ(obj);
  22519. if (p->class_id == JS_CLASS_ARRAY && p->fast_array) {
  22520. return true;
  22521. }
  22522. }
  22523. return false;
  22524. }
  22525. /* Access an Array's internal JSValue array if available */
  22526. static bool js_get_fast_array(JSContext *ctx, JSValue obj,
  22527. JSValue **arrpp, uint32_t *countp)
  22528. {
  22529. /* Try and handle fast arrays explicitly */
  22530. if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) {
  22531. JSObject *p = JS_VALUE_GET_OBJ(obj);
  22532. if (p->class_id == JS_CLASS_ARRAY && p->fast_array) {
  22533. *countp = p->u.array.count;
  22534. *arrpp = p->u.array.u.values;
  22535. return true;
  22536. }
  22537. }
  22538. return false;
  22539. }
  22540. static __exception int js_append_enumerate(JSContext *ctx, JSValue *sp)
  22541. {
  22542. JSValue iterator, enumobj, method, value;
  22543. int is_array_iterator;
  22544. JSValue *arrp;
  22545. uint32_t i, count32, pos;
  22546. if (JS_VALUE_GET_TAG(sp[-2]) != JS_TAG_INT) {
  22547. JS_ThrowInternalError(ctx, "invalid index for append");
  22548. return -1;
  22549. }
  22550. pos = JS_VALUE_GET_INT(sp[-2]);
  22551. /* XXX: further optimisations:
  22552. - use ctx->array_proto_values?
  22553. - check if array_iterator_prototype next method is built-in and
  22554. avoid constructing actual iterator object?
  22555. - build this into js_for_of_start and use in all `for (x of o)` loops
  22556. */
  22557. iterator = JS_GetProperty(ctx, sp[-1], JS_ATOM_Symbol_iterator);
  22558. if (JS_IsException(iterator))
  22559. return -1;
  22560. /* Used to squelch a -Wcast-function-type warning. */
  22561. JSCFunctionType ft = { .generic_magic = js_create_array_iterator };
  22562. is_array_iterator = JS_IsCFunction(ctx, iterator,
  22563. ft.generic,
  22564. JS_ITERATOR_KIND_VALUE);
  22565. JS_FreeValue(ctx, iterator);
  22566. enumobj = JS_GetIterator(ctx, sp[-1], false);
  22567. if (JS_IsException(enumobj))
  22568. return -1;
  22569. method = JS_GetProperty(ctx, enumobj, JS_ATOM_next);
  22570. if (JS_IsException(method)) {
  22571. JS_FreeValue(ctx, enumobj);
  22572. return -1;
  22573. }
  22574. /* Used to squelch a -Wcast-function-type warning. */
  22575. JSCFunctionType ft2 = { .iterator_next = js_array_iterator_next };
  22576. if (is_array_iterator
  22577. && JS_IsCFunction(ctx, method, ft2.generic, 0)
  22578. && js_get_fast_array(ctx, sp[-1], &arrp, &count32)) {
  22579. uint32_t len;
  22580. if (js_get_length32(ctx, &len, sp[-1]))
  22581. goto exception;
  22582. /* if len > count32, the elements >= count32 might be read in
  22583. the prototypes and might have side effects */
  22584. if (len != count32)
  22585. goto general_case;
  22586. /* Handle fast arrays explicitly */
  22587. for (i = 0; i < count32; i++) {
  22588. if (JS_DefinePropertyValueUint32(ctx, sp[-3], pos++,
  22589. js_dup(arrp[i]), JS_PROP_C_W_E) < 0)
  22590. goto exception;
  22591. }
  22592. } else {
  22593. general_case:
  22594. for (;;) {
  22595. int done;
  22596. value = JS_IteratorNext(ctx, enumobj, method, 0, NULL, &done);
  22597. if (JS_IsException(value))
  22598. goto exception;
  22599. if (done) {
  22600. /* value is JS_UNDEFINED */
  22601. break;
  22602. }
  22603. if (JS_DefinePropertyValueUint32(ctx, sp[-3], pos++, value, JS_PROP_C_W_E) < 0)
  22604. goto exception;
  22605. }
  22606. }
  22607. /* Note: could raise an error if too many elements */
  22608. sp[-2] = js_int32(pos);
  22609. JS_FreeValue(ctx, enumobj);
  22610. JS_FreeValue(ctx, method);
  22611. return 0;
  22612. exception:
  22613. JS_IteratorClose(ctx, enumobj, true);
  22614. JS_FreeValue(ctx, enumobj);
  22615. JS_FreeValue(ctx, method);
  22616. return -1;
  22617. }
  22618. static __exception int JS_CopyDataProperties(JSContext *ctx,
  22619. JSValue target,
  22620. JSValue source,
  22621. JSValue excluded,
  22622. bool setprop)
  22623. {
  22624. JSPropertyEnum *tab_atom;
  22625. JSValue val;
  22626. uint32_t i, tab_atom_count;
  22627. JSObject *p;
  22628. JSObject *pexcl = NULL;
  22629. int ret, gpn_flags;
  22630. JSPropertyDescriptor desc;
  22631. bool is_enumerable;
  22632. if (JS_VALUE_GET_TAG(source) != JS_TAG_OBJECT)
  22633. return 0;
  22634. if (JS_VALUE_GET_TAG(excluded) == JS_TAG_OBJECT)
  22635. pexcl = JS_VALUE_GET_OBJ(excluded);
  22636. p = JS_VALUE_GET_OBJ(source);
  22637. gpn_flags = JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK | JS_GPN_ENUM_ONLY;
  22638. if (p->is_exotic) {
  22639. const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic;
  22640. /* cannot use JS_GPN_ENUM_ONLY with e.g. proxies because it
  22641. introduces a visible change */
  22642. if (em && em->get_own_property_names) {
  22643. gpn_flags &= ~JS_GPN_ENUM_ONLY;
  22644. }
  22645. }
  22646. if (JS_GetOwnPropertyNamesInternal(ctx, &tab_atom, &tab_atom_count, p,
  22647. gpn_flags))
  22648. return -1;
  22649. for (i = 0; i < tab_atom_count; i++) {
  22650. if (pexcl) {
  22651. ret = JS_GetOwnPropertyInternal(ctx, NULL, pexcl, tab_atom[i].atom);
  22652. if (ret) {
  22653. if (ret < 0)
  22654. goto exception;
  22655. continue;
  22656. }
  22657. }
  22658. if (!(gpn_flags & JS_GPN_ENUM_ONLY)) {
  22659. /* test if the property is enumerable */
  22660. ret = JS_GetOwnPropertyInternal(ctx, &desc, p, tab_atom[i].atom);
  22661. if (ret < 0)
  22662. goto exception;
  22663. if (!ret)
  22664. continue;
  22665. is_enumerable = (desc.flags & JS_PROP_ENUMERABLE) != 0;
  22666. js_free_desc(ctx, &desc);
  22667. if (!is_enumerable)
  22668. continue;
  22669. }
  22670. val = JS_GetProperty(ctx, source, tab_atom[i].atom);
  22671. if (JS_IsException(val))
  22672. goto exception;
  22673. if (setprop)
  22674. ret = JS_SetProperty(ctx, target, tab_atom[i].atom, val);
  22675. else
  22676. ret = JS_DefinePropertyValue(ctx, target, tab_atom[i].atom, val,
  22677. JS_PROP_C_W_E);
  22678. if (ret < 0)
  22679. goto exception;
  22680. }
  22681. js_free_prop_enum(ctx, tab_atom, tab_atom_count);
  22682. return 0;
  22683. exception:
  22684. js_free_prop_enum(ctx, tab_atom, tab_atom_count);
  22685. return -1;
  22686. }
  22687. /* only valid inside C functions */
  22688. static JSValueConst JS_GetActiveFunction(JSContext *ctx)
  22689. {
  22690. return ctx->rt->current_stack_frame->cur_func;
  22691. }
  22692. static JSVarRef *get_var_ref(JSContext *ctx, JSStackFrame *sf,
  22693. int var_idx, bool is_arg)
  22694. {
  22695. JSVarRef *var_ref;
  22696. struct list_head *el;
  22697. list_for_each(el, &sf->var_ref_list) {
  22698. var_ref = list_entry(el, JSVarRef, header.link);
  22699. if (var_ref->var_idx == var_idx && var_ref->is_arg == is_arg) {
  22700. var_ref->header.ref_count++;
  22701. return var_ref;
  22702. }
  22703. }
  22704. /* create a new one */
  22705. var_ref = js_malloc(ctx, sizeof(JSVarRef));
  22706. if (!var_ref)
  22707. return NULL;
  22708. var_ref->header.ref_count = 1;
  22709. var_ref->is_detached = false;
  22710. var_ref->is_arg = is_arg;
  22711. var_ref->var_idx = var_idx;
  22712. list_add_tail(&var_ref->header.link, &sf->var_ref_list);
  22713. if (is_arg)
  22714. var_ref->pvalue = &sf->arg_buf[var_idx];
  22715. else
  22716. var_ref->pvalue = &sf->var_buf[var_idx];
  22717. var_ref->value = JS_UNDEFINED;
  22718. return var_ref;
  22719. }
  22720. static JSValue js_closure2(JSContext *ctx, JSValue func_obj,
  22721. JSFunctionBytecode *b,
  22722. JSVarRef **cur_var_refs,
  22723. JSStackFrame *sf)
  22724. {
  22725. JSObject *p;
  22726. JSVarRef **var_refs;
  22727. int i;
  22728. p = JS_VALUE_GET_OBJ(func_obj);
  22729. p->u.func.function_bytecode = b;
  22730. p->u.func.home_object = NULL;
  22731. p->u.func.var_refs = NULL;
  22732. if (b->closure_var_count) {
  22733. var_refs = js_mallocz(ctx, sizeof(var_refs[0]) * b->closure_var_count);
  22734. if (!var_refs)
  22735. goto fail;
  22736. p->u.func.var_refs = var_refs;
  22737. for(i = 0; i < b->closure_var_count; i++) {
  22738. JSClosureVar *cv = &b->closure_var[i];
  22739. JSVarRef *var_ref;
  22740. if (cv->is_local) {
  22741. /* reuse the existing variable reference if it already exists */
  22742. var_ref = get_var_ref(ctx, sf, cv->var_idx, cv->is_arg);
  22743. if (!var_ref)
  22744. goto fail;
  22745. } else {
  22746. var_ref = cur_var_refs[cv->var_idx];
  22747. var_ref->header.ref_count++;
  22748. }
  22749. var_refs[i] = var_ref;
  22750. }
  22751. }
  22752. return func_obj;
  22753. fail:
  22754. /* bfunc is freed when func_obj is freed */
  22755. JS_FreeValue(ctx, func_obj);
  22756. return JS_EXCEPTION;
  22757. }
  22758. static JSValue js_instantiate_prototype(JSContext *ctx, JSObject *p, JSAtom atom, void *opaque)
  22759. {
  22760. JSValue obj, this_val;
  22761. int ret;
  22762. this_val = JS_MKPTR(JS_TAG_OBJECT, p);
  22763. obj = JS_NewObject(ctx);
  22764. if (JS_IsException(obj))
  22765. return JS_EXCEPTION;
  22766. set_cycle_flag(ctx, obj);
  22767. set_cycle_flag(ctx, this_val);
  22768. ret = JS_DefinePropertyValue(ctx, obj, JS_ATOM_constructor,
  22769. js_dup(this_val),
  22770. JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);
  22771. if (ret < 0) {
  22772. JS_FreeValue(ctx, obj);
  22773. return JS_EXCEPTION;
  22774. }
  22775. return obj;
  22776. }
  22777. static const uint16_t func_kind_to_class_id[] = {
  22778. [JS_FUNC_NORMAL] = JS_CLASS_BYTECODE_FUNCTION,
  22779. [JS_FUNC_GENERATOR] = JS_CLASS_GENERATOR_FUNCTION,
  22780. [JS_FUNC_ASYNC] = JS_CLASS_ASYNC_FUNCTION,
  22781. [JS_FUNC_ASYNC_GENERATOR] = JS_CLASS_ASYNC_GENERATOR_FUNCTION,
  22782. };
  22783. static JSValue js_closure(JSContext *ctx, JSValue bfunc,
  22784. JSVarRef **cur_var_refs,
  22785. JSStackFrame *sf)
  22786. {
  22787. JSFunctionBytecode *b;
  22788. JSValue func_obj;
  22789. JSAtom name_atom;
  22790. b = JS_VALUE_GET_PTR(bfunc);
  22791. func_obj = JS_NewObjectClass(ctx, func_kind_to_class_id[b->func_kind]);
  22792. if (JS_IsException(func_obj)) {
  22793. JS_FreeValue(ctx, bfunc);
  22794. return JS_EXCEPTION;
  22795. }
  22796. func_obj = js_closure2(ctx, func_obj, b, cur_var_refs, sf);
  22797. if (JS_IsException(func_obj)) {
  22798. /* bfunc has been freed */
  22799. goto fail;
  22800. }
  22801. name_atom = b->func_name;
  22802. if (name_atom == JS_ATOM_NULL)
  22803. name_atom = JS_ATOM_empty_string;
  22804. js_function_set_properties(ctx, func_obj, name_atom,
  22805. b->defined_arg_count);
  22806. if (b->func_kind & JS_FUNC_GENERATOR) {
  22807. JSValue proto;
  22808. int proto_class_id;
  22809. /* generators have a prototype field which is used as
  22810. prototype for the generator object */
  22811. if (b->func_kind == JS_FUNC_ASYNC_GENERATOR)
  22812. proto_class_id = JS_CLASS_ASYNC_GENERATOR;
  22813. else
  22814. proto_class_id = JS_CLASS_GENERATOR;
  22815. proto = JS_NewObjectProto(ctx, ctx->class_proto[proto_class_id]);
  22816. if (JS_IsException(proto))
  22817. goto fail;
  22818. JS_DefinePropertyValue(ctx, func_obj, JS_ATOM_prototype, proto,
  22819. JS_PROP_WRITABLE);
  22820. } else if (b->has_prototype) {
  22821. /* add the 'prototype' property: delay instantiation to avoid
  22822. creating cycles for every javascript function. The prototype
  22823. object is created on the fly when first accessed */
  22824. JS_SetConstructorBit(ctx, func_obj, true);
  22825. JS_DefineAutoInitProperty(ctx, func_obj, JS_ATOM_prototype,
  22826. JS_AUTOINIT_ID_PROTOTYPE, NULL,
  22827. JS_PROP_WRITABLE);
  22828. }
  22829. return func_obj;
  22830. fail:
  22831. /* bfunc is freed when func_obj is freed */
  22832. JS_FreeValue(ctx, func_obj);
  22833. return JS_EXCEPTION;
  22834. }
  22835. #define JS_DEFINE_CLASS_HAS_HERITAGE (1 << 0)
  22836. static int js_op_define_class(JSContext *ctx, JSValue *sp,
  22837. JSAtom class_name, int class_flags,
  22838. JSVarRef **cur_var_refs,
  22839. JSStackFrame *sf, bool is_computed_name)
  22840. {
  22841. JSValue bfunc, parent_class, proto = JS_UNDEFINED;
  22842. JSValue ctor = JS_UNDEFINED, parent_proto = JS_UNDEFINED;
  22843. JSFunctionBytecode *b;
  22844. parent_class = sp[-2];
  22845. bfunc = sp[-1];
  22846. if (class_flags & JS_DEFINE_CLASS_HAS_HERITAGE) {
  22847. if (JS_IsNull(parent_class)) {
  22848. parent_proto = JS_NULL;
  22849. parent_class = js_dup(ctx->function_proto);
  22850. } else {
  22851. if (!JS_IsConstructor(ctx, parent_class)) {
  22852. JS_ThrowTypeError(ctx, "parent class must be constructor");
  22853. goto fail;
  22854. }
  22855. parent_proto = JS_GetProperty(ctx, parent_class, JS_ATOM_prototype);
  22856. if (JS_IsException(parent_proto))
  22857. goto fail;
  22858. if (!JS_IsNull(parent_proto) && !JS_IsObject(parent_proto)) {
  22859. JS_ThrowTypeError(ctx, "parent prototype must be an object or null");
  22860. goto fail;
  22861. }
  22862. }
  22863. } else {
  22864. /* parent_class is JS_UNDEFINED in this case */
  22865. parent_proto = js_dup(ctx->class_proto[JS_CLASS_OBJECT]);
  22866. parent_class = js_dup(ctx->function_proto);
  22867. }
  22868. proto = JS_NewObjectProto(ctx, parent_proto);
  22869. if (JS_IsException(proto))
  22870. goto fail;
  22871. b = JS_VALUE_GET_PTR(bfunc);
  22872. assert(b->func_kind == JS_FUNC_NORMAL);
  22873. ctor = JS_NewObjectProtoClass(ctx, parent_class,
  22874. JS_CLASS_BYTECODE_FUNCTION);
  22875. if (JS_IsException(ctor))
  22876. goto fail;
  22877. ctor = js_closure2(ctx, ctor, b, cur_var_refs, sf);
  22878. bfunc = JS_UNDEFINED;
  22879. if (JS_IsException(ctor))
  22880. goto fail;
  22881. js_method_set_home_object(ctx, ctor, proto);
  22882. JS_SetConstructorBit(ctx, ctor, true);
  22883. JS_DefinePropertyValue(ctx, ctor, JS_ATOM_length,
  22884. js_int32(b->defined_arg_count),
  22885. JS_PROP_CONFIGURABLE);
  22886. if (is_computed_name) {
  22887. if (JS_DefineObjectNameComputed(ctx, ctor, sp[-3],
  22888. JS_PROP_CONFIGURABLE) < 0)
  22889. goto fail;
  22890. } else {
  22891. if (JS_DefineObjectName(ctx, ctor, class_name, JS_PROP_CONFIGURABLE) < 0)
  22892. goto fail;
  22893. }
  22894. /* the constructor property must be first. It can be overriden by
  22895. computed property names */
  22896. if (JS_DefinePropertyValue(ctx, proto, JS_ATOM_constructor,
  22897. js_dup(ctor),
  22898. JS_PROP_CONFIGURABLE |
  22899. JS_PROP_WRITABLE | JS_PROP_THROW) < 0)
  22900. goto fail;
  22901. /* set the prototype property */
  22902. if (JS_DefinePropertyValue(ctx, ctor, JS_ATOM_prototype,
  22903. js_dup(proto), JS_PROP_THROW) < 0)
  22904. goto fail;
  22905. set_cycle_flag(ctx, ctor);
  22906. set_cycle_flag(ctx, proto);
  22907. JS_FreeValue(ctx, parent_proto);
  22908. JS_FreeValue(ctx, parent_class);
  22909. sp[-2] = ctor;
  22910. sp[-1] = proto;
  22911. return 0;
  22912. fail:
  22913. JS_FreeValue(ctx, parent_class);
  22914. JS_FreeValue(ctx, parent_proto);
  22915. JS_FreeValue(ctx, bfunc);
  22916. JS_FreeValue(ctx, proto);
  22917. JS_FreeValue(ctx, ctor);
  22918. sp[-2] = JS_UNDEFINED;
  22919. sp[-1] = JS_UNDEFINED;
  22920. return -1;
  22921. }
  22922. static void close_var_refs(JSRuntime *rt, JSStackFrame *sf)
  22923. {
  22924. struct list_head *el, *el1;
  22925. JSVarRef *var_ref;
  22926. int var_idx;
  22927. list_for_each_safe(el, el1, &sf->var_ref_list) {
  22928. var_ref = list_entry(el, JSVarRef, header.link);
  22929. var_idx = var_ref->var_idx;
  22930. if (var_ref->is_arg)
  22931. var_ref->value = js_dup(sf->arg_buf[var_idx]);
  22932. else
  22933. var_ref->value = js_dup(sf->var_buf[var_idx]);
  22934. var_ref->pvalue = &var_ref->value;
  22935. /* the reference is no longer to a local variable */
  22936. var_ref->is_detached = true;
  22937. add_gc_object(rt, &var_ref->header, JS_GC_OBJ_TYPE_VAR_REF);
  22938. }
  22939. }
  22940. static void close_lexical_var(JSContext *ctx, JSStackFrame *sf, int var_idx)
  22941. {
  22942. struct list_head *el, *el1;
  22943. JSVarRef *var_ref;
  22944. list_for_each_safe(el, el1, &sf->var_ref_list) {
  22945. var_ref = list_entry(el, JSVarRef, header.link);
  22946. if (var_idx == var_ref->var_idx && !var_ref->is_arg) {
  22947. var_ref->value = js_dup(sf->var_buf[var_idx]);
  22948. var_ref->pvalue = &var_ref->value;
  22949. list_del(&var_ref->header.link);
  22950. /* the reference is no longer to a local variable */
  22951. var_ref->is_detached = true;
  22952. add_gc_object(ctx->rt, &var_ref->header, JS_GC_OBJ_TYPE_VAR_REF);
  22953. }
  22954. }
  22955. }
  22956. #define JS_CALL_FLAG_COPY_ARGV (1 << 1)
  22957. #define JS_CALL_FLAG_GENERATOR (1 << 2)
  22958. static JSValue js_call_c_function(JSContext *ctx, JSValueConst func_obj,
  22959. JSValueConst this_obj,
  22960. int argc, JSValueConst *argv, int flags)
  22961. {
  22962. JSRuntime *rt = ctx->rt;
  22963. JSCFunctionType func;
  22964. JSObject *p;
  22965. JSStackFrame sf_s, *sf = &sf_s, *prev_sf;
  22966. JSValue ret_val;
  22967. JSValueConst *arg_buf;
  22968. int arg_count, i;
  22969. JSCFunctionEnum cproto;
  22970. p = JS_VALUE_GET_OBJ(func_obj);
  22971. cproto = p->u.cfunc.cproto;
  22972. arg_count = p->u.cfunc.length;
  22973. /* better to always check stack overflow */
  22974. if (js_check_stack_overflow(rt, sizeof(arg_buf[0]) * arg_count))
  22975. return JS_ThrowStackOverflow(ctx);
  22976. prev_sf = rt->current_stack_frame;
  22977. sf->prev_frame = prev_sf;
  22978. rt->current_stack_frame = sf;
  22979. ctx = p->u.cfunc.realm; /* change the current realm */
  22980. sf->is_strict_mode = false;
  22981. sf->cur_func = unsafe_unconst(func_obj);
  22982. sf->arg_count = argc;
  22983. arg_buf = argv;
  22984. if (unlikely(argc < arg_count)) {
  22985. /* ensure that at least argc_count arguments are readable */
  22986. arg_buf = alloca(sizeof(arg_buf[0]) * arg_count);
  22987. for(i = 0; i < argc; i++)
  22988. arg_buf[i] = argv[i];
  22989. for(i = argc; i < arg_count; i++)
  22990. arg_buf[i] = JS_UNDEFINED;
  22991. sf->arg_count = arg_count;
  22992. }
  22993. sf->arg_buf = (JSValue *)arg_buf;
  22994. func = p->u.cfunc.c_function;
  22995. switch(cproto) {
  22996. case JS_CFUNC_constructor:
  22997. case JS_CFUNC_constructor_or_func:
  22998. if (!(flags & JS_CALL_FLAG_CONSTRUCTOR)) {
  22999. if (cproto == JS_CFUNC_constructor) {
  23000. not_a_constructor:
  23001. ret_val = JS_ThrowTypeError(ctx, "must be called with new");
  23002. break;
  23003. } else {
  23004. this_obj = JS_UNDEFINED;
  23005. }
  23006. }
  23007. /* here this_obj is new_target */
  23008. /* fall thru */
  23009. case JS_CFUNC_generic:
  23010. ret_val = func.generic(ctx, this_obj, argc, arg_buf);
  23011. break;
  23012. case JS_CFUNC_constructor_magic:
  23013. case JS_CFUNC_constructor_or_func_magic:
  23014. if (!(flags & JS_CALL_FLAG_CONSTRUCTOR)) {
  23015. if (cproto == JS_CFUNC_constructor_magic) {
  23016. goto not_a_constructor;
  23017. } else {
  23018. this_obj = JS_UNDEFINED;
  23019. }
  23020. }
  23021. /* fall thru */
  23022. case JS_CFUNC_generic_magic:
  23023. ret_val = func.generic_magic(ctx, this_obj, argc, arg_buf,
  23024. p->u.cfunc.magic);
  23025. break;
  23026. case JS_CFUNC_getter:
  23027. ret_val = func.getter(ctx, this_obj);
  23028. break;
  23029. case JS_CFUNC_setter:
  23030. ret_val = func.setter(ctx, this_obj, arg_buf[0]);
  23031. break;
  23032. case JS_CFUNC_getter_magic:
  23033. ret_val = func.getter_magic(ctx, this_obj, p->u.cfunc.magic);
  23034. break;
  23035. case JS_CFUNC_setter_magic:
  23036. ret_val = func.setter_magic(ctx, this_obj, arg_buf[0], p->u.cfunc.magic);
  23037. break;
  23038. case JS_CFUNC_f_f:
  23039. {
  23040. double d1;
  23041. if (unlikely(JS_ToFloat64(ctx, &d1, arg_buf[0]))) {
  23042. ret_val = JS_EXCEPTION;
  23043. break;
  23044. }
  23045. ret_val = js_number(func.f_f(d1));
  23046. }
  23047. break;
  23048. case JS_CFUNC_f_f_f:
  23049. {
  23050. double d1, d2;
  23051. if (unlikely(JS_ToFloat64(ctx, &d1, arg_buf[0]))) {
  23052. ret_val = JS_EXCEPTION;
  23053. break;
  23054. }
  23055. if (unlikely(JS_ToFloat64(ctx, &d2, arg_buf[1]))) {
  23056. ret_val = JS_EXCEPTION;
  23057. break;
  23058. }
  23059. ret_val = js_number(func.f_f_f(d1, d2));
  23060. }
  23061. break;
  23062. case JS_CFUNC_iterator_next:
  23063. {
  23064. int done;
  23065. ret_val = func.iterator_next(ctx, this_obj, argc, arg_buf,
  23066. &done, p->u.cfunc.magic);
  23067. if (!JS_IsException(ret_val) && done != 2) {
  23068. ret_val = js_create_iterator_result(ctx, ret_val, done);
  23069. }
  23070. }
  23071. break;
  23072. default:
  23073. abort();
  23074. }
  23075. rt->current_stack_frame = sf->prev_frame;
  23076. return ret_val;
  23077. }
  23078. static JSValue js_call_bound_function(JSContext *ctx, JSValueConst func_obj,
  23079. JSValueConst this_obj,
  23080. int argc, JSValueConst *argv, int flags)
  23081. {
  23082. JSObject *p;
  23083. JSBoundFunction *bf;
  23084. JSValueConst *arg_buf, new_target;
  23085. int arg_count, i;
  23086. p = JS_VALUE_GET_OBJ(func_obj);
  23087. bf = p->u.bound_function;
  23088. arg_count = bf->argc + argc;
  23089. if (js_check_stack_overflow(ctx->rt, sizeof(JSValue) * arg_count))
  23090. return JS_ThrowStackOverflow(ctx);
  23091. arg_buf = alloca(sizeof(JSValue) * arg_count);
  23092. for(i = 0; i < bf->argc; i++) {
  23093. arg_buf[i] = bf->argv[i];
  23094. }
  23095. for(i = 0; i < argc; i++) {
  23096. arg_buf[bf->argc + i] = argv[i];
  23097. }
  23098. if (flags & JS_CALL_FLAG_CONSTRUCTOR) {
  23099. new_target = this_obj;
  23100. if (js_same_value(ctx, func_obj, new_target))
  23101. new_target = bf->func_obj;
  23102. return JS_CallConstructor2(ctx, bf->func_obj, new_target,
  23103. arg_count, arg_buf);
  23104. } else {
  23105. return JS_Call(ctx, bf->func_obj, bf->this_val,
  23106. arg_count, arg_buf);
  23107. }
  23108. }
  23109. /* argument of OP_special_object */
  23110. typedef enum {
  23111. OP_SPECIAL_OBJECT_ARGUMENTS,
  23112. OP_SPECIAL_OBJECT_MAPPED_ARGUMENTS,
  23113. OP_SPECIAL_OBJECT_THIS_FUNC,
  23114. OP_SPECIAL_OBJECT_NEW_TARGET,
  23115. OP_SPECIAL_OBJECT_HOME_OBJECT,
  23116. OP_SPECIAL_OBJECT_VAR_OBJECT,
  23117. OP_SPECIAL_OBJECT_IMPORT_META,
  23118. } OPSpecialObjectEnum;
  23119. #define FUNC_RET_AWAIT 0
  23120. #define FUNC_RET_YIELD 1
  23121. #define FUNC_RET_YIELD_STAR 2
  23122. #ifdef ENABLE_DUMPS // JS_DUMP_BYTECODE_*
  23123. static void dump_single_byte_code(JSContext *ctx, const uint8_t *pc,
  23124. JSFunctionBytecode *b, int start_pos);
  23125. static void print_func_name(JSFunctionBytecode *b);
  23126. #endif
  23127. static bool needs_backtrace(JSValue exc)
  23128. {
  23129. JSObject *p;
  23130. if (JS_VALUE_GET_TAG(exc) != JS_TAG_OBJECT)
  23131. return false;
  23132. p = JS_VALUE_GET_OBJ(exc);
  23133. if (p->class_id != JS_CLASS_ERROR)
  23134. return false;
  23135. return !find_own_property1(p, JS_ATOM_stack);
  23136. }
  23137. /* argv[] is modified if (flags & JS_CALL_FLAG_COPY_ARGV) = 0. */
  23138. static JSValue JS_CallInternal(JSContext *caller_ctx, JSValueConst func_obj,
  23139. JSValueConst this_obj, JSValueConst new_target,
  23140. int argc, JSValueConst *argv, int flags)
  23141. {
  23142. JSRuntime *rt = caller_ctx->rt;
  23143. JSContext *ctx;
  23144. JSObject *p;
  23145. JSFunctionBytecode *b;
  23146. JSStackFrame sf_s, *sf = &sf_s;
  23147. uint8_t *pc;
  23148. int opcode, arg_allocated_size, i;
  23149. JSValue *local_buf, *stack_buf, *var_buf, *arg_buf, *sp, ret_val, *pval;
  23150. JSVarRef **var_refs;
  23151. size_t alloca_size;
  23152. #ifdef ENABLE_DUMPS // JS_DUMP_BYTECODE_STEP
  23153. #define DUMP_BYTECODE_OR_DONT(pc) \
  23154. if (check_dump_flag(ctx->rt, JS_DUMP_BYTECODE_STEP)) dump_single_byte_code(ctx, pc, b, 0);
  23155. #else
  23156. #define DUMP_BYTECODE_OR_DONT(pc)
  23157. #endif
  23158. #if !DIRECT_DISPATCH
  23159. #define SWITCH(pc) DUMP_BYTECODE_OR_DONT(pc) switch (opcode = *pc++)
  23160. #define CASE(op) case op
  23161. #define DEFAULT default
  23162. #define BREAK break
  23163. #else
  23164. __extension__ static const void * const dispatch_table[256] = {
  23165. #define DEF(id, size, n_pop, n_push, f) && case_OP_ ## id,
  23166. #define def(id, size, n_pop, n_push, f)
  23167. /*
  23168. * QuickJS opcode definitions
  23169. *
  23170. * Copyright (c) 2017-2018 Fabrice Bellard
  23171. * Copyright (c) 2017-2018 Charlie Gordon
  23172. *
  23173. * Permission is hereby granted, free of charge, to any person obtaining a copy
  23174. * of this software and associated documentation files (the "Software"), to deal
  23175. * in the Software without restriction, including without limitation the rights
  23176. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  23177. * copies of the Software, and to permit persons to whom the Software is
  23178. * furnished to do so, subject to the following conditions:
  23179. *
  23180. * The above copyright notice and this permission notice shall be included in
  23181. * all copies or substantial portions of the Software.
  23182. *
  23183. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  23184. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23185. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  23186. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23187. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23188. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23189. * THE SOFTWARE.
  23190. */
  23191. #ifdef FMT
  23192. FMT(none)
  23193. FMT(none_int)
  23194. FMT(none_loc)
  23195. FMT(none_arg)
  23196. FMT(none_var_ref)
  23197. FMT(u8)
  23198. FMT(i8)
  23199. FMT(loc8)
  23200. FMT(const8)
  23201. FMT(label8)
  23202. FMT(u16)
  23203. FMT(i16)
  23204. FMT(label16)
  23205. FMT(npop)
  23206. FMT(npopx)
  23207. FMT(npop_u16)
  23208. FMT(loc)
  23209. FMT(arg)
  23210. FMT(var_ref)
  23211. FMT(u32)
  23212. FMT(u32x2)
  23213. FMT(i32)
  23214. FMT(const)
  23215. FMT(label)
  23216. FMT(atom)
  23217. FMT(atom_u8)
  23218. FMT(atom_u16)
  23219. FMT(atom_label_u8)
  23220. FMT(atom_label_u16)
  23221. FMT(label_u16)
  23222. #undef FMT
  23223. #endif /* FMT */
  23224. #ifdef DEF
  23225. #ifndef def
  23226. #define def(id, size, n_pop, n_push, f) DEF(id, size, n_pop, n_push, f)
  23227. #endif
  23228. DEF(invalid, 1, 0, 0, none) /* never emitted */
  23229. /* push values */
  23230. DEF( push_i32, 5, 0, 1, i32)
  23231. DEF( push_const, 5, 0, 1, const)
  23232. DEF( fclosure, 5, 0, 1, const) /* must follow push_const */
  23233. DEF(push_atom_value, 5, 0, 1, atom)
  23234. DEF( private_symbol, 5, 0, 1, atom)
  23235. DEF( undefined, 1, 0, 1, none)
  23236. DEF( null, 1, 0, 1, none)
  23237. DEF( push_this, 1, 0, 1, none) /* only used at the start of a function */
  23238. DEF( push_false, 1, 0, 1, none)
  23239. DEF( push_true, 1, 0, 1, none)
  23240. DEF( object, 1, 0, 1, none)
  23241. DEF( special_object, 2, 0, 1, u8) /* only used at the start of a function */
  23242. DEF( rest, 3, 0, 1, u16) /* only used at the start of a function */
  23243. DEF( drop, 1, 1, 0, none) /* a -> */
  23244. DEF( nip, 1, 2, 1, none) /* a b -> b */
  23245. DEF( nip1, 1, 3, 2, none) /* a b c -> b c */
  23246. DEF( dup, 1, 1, 2, none) /* a -> a a */
  23247. DEF( dup1, 1, 2, 3, none) /* a b -> a a b */
  23248. DEF( dup2, 1, 2, 4, none) /* a b -> a b a b */
  23249. DEF( dup3, 1, 3, 6, none) /* a b c -> a b c a b c */
  23250. DEF( insert2, 1, 2, 3, none) /* obj a -> a obj a (dup_x1) */
  23251. DEF( insert3, 1, 3, 4, none) /* obj prop a -> a obj prop a (dup_x2) */
  23252. DEF( insert4, 1, 4, 5, none) /* this obj prop a -> a this obj prop a */
  23253. DEF( perm3, 1, 3, 3, none) /* obj a b -> a obj b */
  23254. DEF( perm4, 1, 4, 4, none) /* obj prop a b -> a obj prop b */
  23255. DEF( perm5, 1, 5, 5, none) /* this obj prop a b -> a this obj prop b */
  23256. DEF( swap, 1, 2, 2, none) /* a b -> b a */
  23257. DEF( swap2, 1, 4, 4, none) /* a b c d -> c d a b */
  23258. DEF( rot3l, 1, 3, 3, none) /* x a b -> a b x */
  23259. DEF( rot3r, 1, 3, 3, none) /* a b x -> x a b */
  23260. DEF( rot4l, 1, 4, 4, none) /* x a b c -> a b c x */
  23261. DEF( rot5l, 1, 5, 5, none) /* x a b c d -> a b c d x */
  23262. DEF(call_constructor, 3, 2, 1, npop) /* func new.target args -> ret. arguments are not counted in n_pop */
  23263. DEF( call, 3, 1, 1, npop) /* arguments are not counted in n_pop */
  23264. DEF( tail_call, 3, 1, 0, npop) /* arguments are not counted in n_pop */
  23265. DEF( call_method, 3, 2, 1, npop) /* arguments are not counted in n_pop */
  23266. DEF(tail_call_method, 3, 2, 0, npop) /* arguments are not counted in n_pop */
  23267. DEF( array_from, 3, 0, 1, npop) /* arguments are not counted in n_pop */
  23268. DEF( apply, 3, 3, 1, u16)
  23269. DEF( return, 1, 1, 0, none)
  23270. DEF( return_undef, 1, 0, 0, none)
  23271. DEF(check_ctor_return, 1, 1, 2, none)
  23272. DEF( check_ctor, 1, 0, 0, none)
  23273. DEF( init_ctor, 1, 0, 1, none)
  23274. DEF( check_brand, 1, 2, 2, none) /* this_obj func -> this_obj func */
  23275. DEF( add_brand, 1, 2, 0, none) /* this_obj home_obj -> */
  23276. DEF( return_async, 1, 1, 0, none)
  23277. DEF( throw, 1, 1, 0, none)
  23278. DEF( throw_error, 6, 0, 0, atom_u8)
  23279. DEF( eval, 5, 1, 1, npop_u16) /* func args... -> ret_val */
  23280. DEF( apply_eval, 3, 2, 1, u16) /* func array -> ret_eval */
  23281. DEF( regexp, 1, 2, 1, none) /* create a RegExp object from the pattern and a
  23282. bytecode string */
  23283. DEF( get_super, 1, 1, 1, none)
  23284. DEF( import, 1, 1, 1, none) /* dynamic module import */
  23285. DEF( check_var, 5, 0, 1, atom) /* check if a variable exists */
  23286. DEF( get_var_undef, 5, 0, 1, atom) /* push undefined if the variable does not exist */
  23287. DEF( get_var, 5, 0, 1, atom) /* throw an exception if the variable does not exist */
  23288. DEF( put_var, 5, 1, 0, atom) /* must come after get_var */
  23289. DEF( put_var_init, 5, 1, 0, atom) /* must come after put_var. Used to initialize a global lexical variable */
  23290. DEF( put_var_strict, 5, 2, 0, atom) /* for strict mode variable write */
  23291. DEF( get_ref_value, 1, 2, 3, none)
  23292. DEF( put_ref_value, 1, 3, 0, none)
  23293. DEF( define_var, 6, 0, 0, atom_u8)
  23294. DEF(check_define_var, 6, 0, 0, atom_u8)
  23295. DEF( define_func, 6, 1, 0, atom_u8)
  23296. // order matters, see IC counterparts
  23297. DEF( get_field, 5, 1, 1, atom)
  23298. DEF( get_field2, 5, 1, 2, atom)
  23299. DEF( put_field, 5, 2, 0, atom)
  23300. DEF( get_private_field, 1, 2, 1, none) /* obj prop -> value */
  23301. DEF( put_private_field, 1, 3, 0, none) /* obj value prop -> */
  23302. DEF(define_private_field, 1, 3, 1, none) /* obj prop value -> obj */
  23303. DEF( get_array_el, 1, 2, 1, none)
  23304. DEF( get_array_el2, 1, 2, 2, none) /* obj prop -> obj value */
  23305. DEF( put_array_el, 1, 3, 0, none)
  23306. DEF(get_super_value, 1, 3, 1, none) /* this obj prop -> value */
  23307. DEF(put_super_value, 1, 4, 0, none) /* this obj prop value -> */
  23308. DEF( define_field, 5, 2, 1, atom)
  23309. DEF( set_name, 5, 1, 1, atom)
  23310. DEF(set_name_computed, 1, 2, 2, none)
  23311. DEF( set_proto, 1, 2, 1, none)
  23312. DEF(set_home_object, 1, 2, 2, none)
  23313. DEF(define_array_el, 1, 3, 2, none)
  23314. DEF( append, 1, 3, 2, none) /* append enumerated object, update length */
  23315. DEF(copy_data_properties, 2, 3, 3, u8)
  23316. DEF( define_method, 6, 2, 1, atom_u8)
  23317. DEF(define_method_computed, 2, 3, 1, u8) /* must come after define_method */
  23318. DEF( define_class, 6, 2, 2, atom_u8) /* parent ctor -> ctor proto */
  23319. DEF( define_class_computed, 6, 3, 3, atom_u8) /* field_name parent ctor -> field_name ctor proto (class with computed name) */
  23320. DEF( get_loc, 3, 0, 1, loc)
  23321. DEF( put_loc, 3, 1, 0, loc) /* must come after get_loc */
  23322. DEF( set_loc, 3, 1, 1, loc) /* must come after put_loc */
  23323. DEF( get_arg, 3, 0, 1, arg)
  23324. DEF( put_arg, 3, 1, 0, arg) /* must come after get_arg */
  23325. DEF( set_arg, 3, 1, 1, arg) /* must come after put_arg */
  23326. DEF( get_var_ref, 3, 0, 1, var_ref)
  23327. DEF( put_var_ref, 3, 1, 0, var_ref) /* must come after get_var_ref */
  23328. DEF( set_var_ref, 3, 1, 1, var_ref) /* must come after put_var_ref */
  23329. DEF(set_loc_uninitialized, 3, 0, 0, loc)
  23330. DEF( get_loc_check, 3, 0, 1, loc)
  23331. DEF( put_loc_check, 3, 1, 0, loc) /* must come after get_loc_check */
  23332. DEF( put_loc_check_init, 3, 1, 0, loc)
  23333. DEF(get_var_ref_check, 3, 0, 1, var_ref)
  23334. DEF(put_var_ref_check, 3, 1, 0, var_ref) /* must come after get_var_ref_check */
  23335. DEF(put_var_ref_check_init, 3, 1, 0, var_ref)
  23336. DEF( close_loc, 3, 0, 0, loc)
  23337. DEF( if_false, 5, 1, 0, label)
  23338. DEF( if_true, 5, 1, 0, label) /* must come after if_false */
  23339. DEF( goto, 5, 0, 0, label) /* must come after if_true */
  23340. DEF( catch, 5, 0, 1, label)
  23341. DEF( gosub, 5, 0, 0, label) /* used to execute the finally block */
  23342. DEF( ret, 1, 1, 0, none) /* used to return from the finally block */
  23343. DEF( nip_catch, 1, 2, 1, none) /* catch ... a -> a */
  23344. DEF( to_object, 1, 1, 1, none)
  23345. //DEF( to_string, 1, 1, 1, none)
  23346. DEF( to_propkey, 1, 1, 1, none)
  23347. DEF( to_propkey2, 1, 2, 2, none)
  23348. DEF( with_get_var, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */
  23349. DEF( with_put_var, 10, 2, 1, atom_label_u8) /* must be in the same order as scope_xxx */
  23350. DEF(with_delete_var, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */
  23351. DEF( with_make_ref, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */
  23352. DEF( with_get_ref, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */
  23353. DEF(with_get_ref_undef, 10, 1, 0, atom_label_u8)
  23354. DEF( make_loc_ref, 7, 0, 2, atom_u16)
  23355. DEF( make_arg_ref, 7, 0, 2, atom_u16)
  23356. DEF(make_var_ref_ref, 7, 0, 2, atom_u16)
  23357. DEF( make_var_ref, 5, 0, 2, atom)
  23358. DEF( for_in_start, 1, 1, 1, none)
  23359. DEF( for_of_start, 1, 1, 3, none)
  23360. DEF(for_await_of_start, 1, 1, 3, none)
  23361. DEF( for_in_next, 1, 1, 3, none)
  23362. DEF( for_of_next, 2, 3, 5, u8)
  23363. DEF(iterator_check_object, 1, 1, 1, none)
  23364. DEF(iterator_get_value_done, 1, 1, 2, none)
  23365. DEF( iterator_close, 1, 3, 0, none)
  23366. DEF( iterator_next, 1, 4, 4, none)
  23367. DEF( iterator_call, 2, 4, 5, u8)
  23368. DEF( initial_yield, 1, 0, 0, none)
  23369. DEF( yield, 1, 1, 2, none)
  23370. DEF( yield_star, 1, 1, 2, none)
  23371. DEF(async_yield_star, 1, 1, 2, none)
  23372. DEF( await, 1, 1, 1, none)
  23373. /* arithmetic/logic operations */
  23374. DEF( neg, 1, 1, 1, none)
  23375. DEF( plus, 1, 1, 1, none)
  23376. DEF( dec, 1, 1, 1, none)
  23377. DEF( inc, 1, 1, 1, none)
  23378. DEF( post_dec, 1, 1, 2, none)
  23379. DEF( post_inc, 1, 1, 2, none)
  23380. DEF( dec_loc, 2, 0, 0, loc8)
  23381. DEF( inc_loc, 2, 0, 0, loc8)
  23382. DEF( add_loc, 2, 1, 0, loc8)
  23383. DEF( not, 1, 1, 1, none)
  23384. DEF( lnot, 1, 1, 1, none)
  23385. DEF( typeof, 1, 1, 1, none)
  23386. DEF( delete, 1, 2, 1, none)
  23387. DEF( delete_var, 5, 0, 1, atom)
  23388. /* warning: order matters (see js_parse_assign_expr) */
  23389. DEF( mul, 1, 2, 1, none)
  23390. DEF( div, 1, 2, 1, none)
  23391. DEF( mod, 1, 2, 1, none)
  23392. DEF( add, 1, 2, 1, none)
  23393. DEF( sub, 1, 2, 1, none)
  23394. DEF( shl, 1, 2, 1, none)
  23395. DEF( sar, 1, 2, 1, none)
  23396. DEF( shr, 1, 2, 1, none)
  23397. DEF( and, 1, 2, 1, none)
  23398. DEF( xor, 1, 2, 1, none)
  23399. DEF( or, 1, 2, 1, none)
  23400. DEF( pow, 1, 2, 1, none)
  23401. DEF( lt, 1, 2, 1, none)
  23402. DEF( lte, 1, 2, 1, none)
  23403. DEF( gt, 1, 2, 1, none)
  23404. DEF( gte, 1, 2, 1, none)
  23405. DEF( instanceof, 1, 2, 1, none)
  23406. DEF( in, 1, 2, 1, none)
  23407. DEF( eq, 1, 2, 1, none)
  23408. DEF( neq, 1, 2, 1, none)
  23409. DEF( strict_eq, 1, 2, 1, none)
  23410. DEF( strict_neq, 1, 2, 1, none)
  23411. DEF(is_undefined_or_null, 1, 1, 1, none)
  23412. DEF( private_in, 1, 2, 1, none)
  23413. /* must be the last non short and non temporary opcode */
  23414. DEF( nop, 1, 0, 0, none)
  23415. /* temporary opcodes: never emitted in the final bytecode */
  23416. def( enter_scope, 3, 0, 0, u16) /* emitted in phase 1, removed in phase 2 */
  23417. def( leave_scope, 3, 0, 0, u16) /* emitted in phase 1, removed in phase 2 */
  23418. def( label, 5, 0, 0, label) /* emitted in phase 1, removed in phase 3 */
  23419. def(scope_get_var_undef, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */
  23420. def( scope_get_var, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */
  23421. def( scope_put_var, 7, 1, 0, atom_u16) /* emitted in phase 1, removed in phase 2 */
  23422. def(scope_delete_var, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */
  23423. def( scope_make_ref, 11, 0, 2, atom_label_u16) /* emitted in phase 1, removed in phase 2 */
  23424. def( scope_get_ref, 7, 0, 2, atom_u16) /* emitted in phase 1, removed in phase 2 */
  23425. def(scope_put_var_init, 7, 0, 2, atom_u16) /* emitted in phase 1, removed in phase 2 */
  23426. def(scope_get_private_field, 7, 1, 1, atom_u16) /* obj -> value, emitted in phase 1, removed in phase 2 */
  23427. def(scope_get_private_field2, 7, 1, 2, atom_u16) /* obj -> obj value, emitted in phase 1, removed in phase 2 */
  23428. def(scope_put_private_field, 7, 2, 0, atom_u16) /* obj value ->, emitted in phase 1, removed in phase 2 */
  23429. def(scope_in_private_field, 7, 1, 1, atom_u16) /* obj -> res emitted in phase 1, removed in phase 2 */
  23430. def(get_field_opt_chain, 5, 1, 1, atom) /* emitted in phase 1, removed in phase 2 */
  23431. def(get_array_el_opt_chain, 1, 2, 1, none) /* emitted in phase 1, removed in phase 2 */
  23432. def( set_class_name, 5, 1, 1, u32) /* emitted in phase 1, removed in phase 2 */
  23433. def( source_loc, 9, 0, 0, u32x2) /* emitted in phase 1, removed in phase 3 */
  23434. DEF( push_minus1, 1, 0, 1, none_int)
  23435. DEF( push_0, 1, 0, 1, none_int)
  23436. DEF( push_1, 1, 0, 1, none_int)
  23437. DEF( push_2, 1, 0, 1, none_int)
  23438. DEF( push_3, 1, 0, 1, none_int)
  23439. DEF( push_4, 1, 0, 1, none_int)
  23440. DEF( push_5, 1, 0, 1, none_int)
  23441. DEF( push_6, 1, 0, 1, none_int)
  23442. DEF( push_7, 1, 0, 1, none_int)
  23443. DEF( push_i8, 2, 0, 1, i8)
  23444. DEF( push_i16, 3, 0, 1, i16)
  23445. DEF( push_const8, 2, 0, 1, const8)
  23446. DEF( fclosure8, 2, 0, 1, const8) /* must follow push_const8 */
  23447. DEF(push_empty_string, 1, 0, 1, none)
  23448. DEF( get_loc8, 2, 0, 1, loc8)
  23449. DEF( put_loc8, 2, 1, 0, loc8)
  23450. DEF( set_loc8, 2, 1, 1, loc8)
  23451. DEF( get_loc0_loc1, 1, 0, 2, none_loc)
  23452. DEF( get_loc0, 1, 0, 1, none_loc)
  23453. DEF( get_loc1, 1, 0, 1, none_loc)
  23454. DEF( get_loc2, 1, 0, 1, none_loc)
  23455. DEF( get_loc3, 1, 0, 1, none_loc)
  23456. DEF( put_loc0, 1, 1, 0, none_loc)
  23457. DEF( put_loc1, 1, 1, 0, none_loc)
  23458. DEF( put_loc2, 1, 1, 0, none_loc)
  23459. DEF( put_loc3, 1, 1, 0, none_loc)
  23460. DEF( set_loc0, 1, 1, 1, none_loc)
  23461. DEF( set_loc1, 1, 1, 1, none_loc)
  23462. DEF( set_loc2, 1, 1, 1, none_loc)
  23463. DEF( set_loc3, 1, 1, 1, none_loc)
  23464. DEF( get_arg0, 1, 0, 1, none_arg)
  23465. DEF( get_arg1, 1, 0, 1, none_arg)
  23466. DEF( get_arg2, 1, 0, 1, none_arg)
  23467. DEF( get_arg3, 1, 0, 1, none_arg)
  23468. DEF( put_arg0, 1, 1, 0, none_arg)
  23469. DEF( put_arg1, 1, 1, 0, none_arg)
  23470. DEF( put_arg2, 1, 1, 0, none_arg)
  23471. DEF( put_arg3, 1, 1, 0, none_arg)
  23472. DEF( set_arg0, 1, 1, 1, none_arg)
  23473. DEF( set_arg1, 1, 1, 1, none_arg)
  23474. DEF( set_arg2, 1, 1, 1, none_arg)
  23475. DEF( set_arg3, 1, 1, 1, none_arg)
  23476. DEF( get_var_ref0, 1, 0, 1, none_var_ref)
  23477. DEF( get_var_ref1, 1, 0, 1, none_var_ref)
  23478. DEF( get_var_ref2, 1, 0, 1, none_var_ref)
  23479. DEF( get_var_ref3, 1, 0, 1, none_var_ref)
  23480. DEF( put_var_ref0, 1, 1, 0, none_var_ref)
  23481. DEF( put_var_ref1, 1, 1, 0, none_var_ref)
  23482. DEF( put_var_ref2, 1, 1, 0, none_var_ref)
  23483. DEF( put_var_ref3, 1, 1, 0, none_var_ref)
  23484. DEF( set_var_ref0, 1, 1, 1, none_var_ref)
  23485. DEF( set_var_ref1, 1, 1, 1, none_var_ref)
  23486. DEF( set_var_ref2, 1, 1, 1, none_var_ref)
  23487. DEF( set_var_ref3, 1, 1, 1, none_var_ref)
  23488. DEF( get_length, 1, 1, 1, none)
  23489. DEF( if_false8, 2, 1, 0, label8)
  23490. DEF( if_true8, 2, 1, 0, label8) /* must come after if_false8 */
  23491. DEF( goto8, 2, 0, 0, label8) /* must come after if_true8 */
  23492. DEF( goto16, 3, 0, 0, label16)
  23493. DEF( call0, 1, 1, 1, npopx)
  23494. DEF( call1, 1, 1, 1, npopx)
  23495. DEF( call2, 1, 1, 1, npopx)
  23496. DEF( call3, 1, 1, 1, npopx)
  23497. DEF( is_undefined, 1, 1, 1, none)
  23498. DEF( is_null, 1, 1, 1, none)
  23499. DEF(typeof_is_undefined, 1, 1, 1, none)
  23500. DEF( typeof_is_function, 1, 1, 1, none)
  23501. #undef DEF
  23502. #undef def
  23503. #endif /* DEF */
  23504. [ OP_COUNT ... 255 ] = &&case_default
  23505. };
  23506. #define SWITCH(pc) DUMP_BYTECODE_OR_DONT(pc) __extension__ ({ goto *dispatch_table[opcode = *pc++]; });
  23507. #define CASE(op) case_ ## op
  23508. #define DEFAULT case_default
  23509. #define BREAK SWITCH(pc)
  23510. #endif
  23511. if (js_poll_interrupts(caller_ctx))
  23512. return JS_EXCEPTION;
  23513. if (unlikely(JS_VALUE_GET_TAG(func_obj) != JS_TAG_OBJECT)) {
  23514. if (flags & JS_CALL_FLAG_GENERATOR) {
  23515. JSAsyncFunctionState *s = JS_VALUE_GET_PTR(func_obj);
  23516. /* func_obj get contains a pointer to JSFuncAsyncState */
  23517. /* the stack frame is already allocated */
  23518. sf = &s->frame;
  23519. p = JS_VALUE_GET_OBJ(sf->cur_func);
  23520. b = p->u.func.function_bytecode;
  23521. ctx = b->realm;
  23522. var_refs = p->u.func.var_refs;
  23523. local_buf = arg_buf = sf->arg_buf;
  23524. var_buf = sf->var_buf;
  23525. stack_buf = sf->var_buf + b->var_count;
  23526. sp = sf->cur_sp;
  23527. sf->cur_sp = NULL; /* cur_sp is NULL if the function is running */
  23528. pc = sf->cur_pc;
  23529. sf->prev_frame = rt->current_stack_frame;
  23530. rt->current_stack_frame = sf;
  23531. if (s->throw_flag)
  23532. goto exception;
  23533. else
  23534. goto restart;
  23535. } else {
  23536. goto not_a_function;
  23537. }
  23538. }
  23539. p = JS_VALUE_GET_OBJ(func_obj);
  23540. if (unlikely(p->class_id != JS_CLASS_BYTECODE_FUNCTION)) {
  23541. JSClassCall *call_func;
  23542. call_func = rt->class_array[p->class_id].call;
  23543. if (!call_func) {
  23544. not_a_function:
  23545. return JS_ThrowTypeErrorNotAFunction(caller_ctx);
  23546. }
  23547. return call_func(caller_ctx, func_obj, this_obj, argc,
  23548. argv, flags);
  23549. }
  23550. b = p->u.func.function_bytecode;
  23551. if (unlikely(argc < b->arg_count || (flags & JS_CALL_FLAG_COPY_ARGV))) {
  23552. arg_allocated_size = b->arg_count;
  23553. } else {
  23554. arg_allocated_size = 0;
  23555. }
  23556. alloca_size = sizeof(JSValue) * (arg_allocated_size + b->var_count +
  23557. b->stack_size);
  23558. if (js_check_stack_overflow(rt, alloca_size))
  23559. return JS_ThrowStackOverflow(caller_ctx);
  23560. sf->is_strict_mode = b->is_strict_mode;
  23561. arg_buf = (JSValue *)argv;
  23562. sf->arg_count = argc;
  23563. sf->cur_func = unsafe_unconst(func_obj);
  23564. init_list_head(&sf->var_ref_list);
  23565. var_refs = p->u.func.var_refs;
  23566. local_buf = alloca(alloca_size);
  23567. if (unlikely(arg_allocated_size)) {
  23568. int n = min_int(argc, b->arg_count);
  23569. arg_buf = local_buf;
  23570. for(i = 0; i < n; i++)
  23571. arg_buf[i] = js_dup(argv[i]);
  23572. for(; i < b->arg_count; i++)
  23573. arg_buf[i] = JS_UNDEFINED;
  23574. sf->arg_count = b->arg_count;
  23575. }
  23576. var_buf = local_buf + arg_allocated_size;
  23577. sf->var_buf = var_buf;
  23578. sf->arg_buf = arg_buf;
  23579. for(i = 0; i < b->var_count; i++)
  23580. var_buf[i] = JS_UNDEFINED;
  23581. stack_buf = var_buf + b->var_count;
  23582. sp = stack_buf;
  23583. pc = b->byte_code_buf;
  23584. /* sf->cur_pc must we set to pc before any recursive calls to JS_CallInternal. */
  23585. sf->cur_pc = NULL;
  23586. sf->prev_frame = rt->current_stack_frame;
  23587. rt->current_stack_frame = sf;
  23588. ctx = b->realm; /* set the current realm */
  23589. #ifdef ENABLE_DUMPS // JS_DUMP_BYTECODE_STEP
  23590. if (check_dump_flag(ctx->rt, JS_DUMP_BYTECODE_STEP))
  23591. print_func_name(b);
  23592. #endif
  23593. restart:
  23594. for(;;) {
  23595. int call_argc;
  23596. JSValue *call_argv;
  23597. SWITCH(pc) {
  23598. CASE(OP_push_i32):
  23599. *sp++ = js_int32(get_u32(pc));
  23600. pc += 4;
  23601. BREAK;
  23602. CASE(OP_push_const):
  23603. *sp++ = js_dup(b->cpool[get_u32(pc)]);
  23604. pc += 4;
  23605. BREAK;
  23606. CASE(OP_push_minus1):
  23607. CASE(OP_push_0):
  23608. CASE(OP_push_1):
  23609. CASE(OP_push_2):
  23610. CASE(OP_push_3):
  23611. CASE(OP_push_4):
  23612. CASE(OP_push_5):
  23613. CASE(OP_push_6):
  23614. CASE(OP_push_7):
  23615. *sp++ = js_int32(opcode - OP_push_0);
  23616. BREAK;
  23617. CASE(OP_push_i8):
  23618. *sp++ = js_int32(get_i8(pc));
  23619. pc += 1;
  23620. BREAK;
  23621. CASE(OP_push_i16):
  23622. *sp++ = js_int32(get_i16(pc));
  23623. pc += 2;
  23624. BREAK;
  23625. CASE(OP_push_const8):
  23626. *sp++ = js_dup(b->cpool[*pc++]);
  23627. BREAK;
  23628. CASE(OP_fclosure8):
  23629. *sp++ = js_closure(ctx, js_dup(b->cpool[*pc++]), var_refs, sf);
  23630. if (unlikely(JS_IsException(sp[-1])))
  23631. goto exception;
  23632. BREAK;
  23633. CASE(OP_push_empty_string):
  23634. *sp++ = JS_AtomToString(ctx, JS_ATOM_empty_string);
  23635. BREAK;
  23636. CASE(OP_get_length):
  23637. {
  23638. JSValue val;
  23639. sf->cur_pc = pc;
  23640. val = JS_GetProperty(ctx, sp[-1], JS_ATOM_length);
  23641. if (unlikely(JS_IsException(val)))
  23642. goto exception;
  23643. JS_FreeValue(ctx, sp[-1]);
  23644. sp[-1] = val;
  23645. }
  23646. BREAK;
  23647. CASE(OP_push_atom_value):
  23648. *sp++ = JS_AtomToValue(ctx, get_u32(pc));
  23649. pc += 4;
  23650. BREAK;
  23651. CASE(OP_undefined):
  23652. *sp++ = JS_UNDEFINED;
  23653. BREAK;
  23654. CASE(OP_null):
  23655. *sp++ = JS_NULL;
  23656. BREAK;
  23657. CASE(OP_push_this):
  23658. /* OP_push_this is only called at the start of a function */
  23659. {
  23660. JSValue val;
  23661. if (!b->is_strict_mode) {
  23662. uint32_t tag = JS_VALUE_GET_TAG(this_obj);
  23663. if (likely(tag == JS_TAG_OBJECT))
  23664. goto normal_this;
  23665. if (tag == JS_TAG_NULL || tag == JS_TAG_UNDEFINED) {
  23666. val = js_dup(ctx->global_obj);
  23667. } else {
  23668. val = JS_ToObject(ctx, this_obj);
  23669. if (JS_IsException(val))
  23670. goto exception;
  23671. }
  23672. } else {
  23673. normal_this:
  23674. val = js_dup(this_obj);
  23675. }
  23676. *sp++ = val;
  23677. }
  23678. BREAK;
  23679. CASE(OP_push_false):
  23680. *sp++ = JS_FALSE;
  23681. BREAK;
  23682. CASE(OP_push_true):
  23683. *sp++ = JS_TRUE;
  23684. BREAK;
  23685. CASE(OP_object):
  23686. *sp++ = JS_NewObject(ctx);
  23687. if (unlikely(JS_IsException(sp[-1])))
  23688. goto exception;
  23689. BREAK;
  23690. CASE(OP_special_object):
  23691. {
  23692. int arg = *pc++;
  23693. switch(arg) {
  23694. case OP_SPECIAL_OBJECT_ARGUMENTS:
  23695. *sp++ = js_build_arguments(ctx, argc, argv);
  23696. if (unlikely(JS_IsException(sp[-1])))
  23697. goto exception;
  23698. break;
  23699. case OP_SPECIAL_OBJECT_MAPPED_ARGUMENTS:
  23700. *sp++ = js_build_mapped_arguments(ctx, argc, argv,
  23701. sf, min_int(argc, b->arg_count));
  23702. if (unlikely(JS_IsException(sp[-1])))
  23703. goto exception;
  23704. break;
  23705. case OP_SPECIAL_OBJECT_THIS_FUNC:
  23706. *sp++ = js_dup(sf->cur_func);
  23707. break;
  23708. case OP_SPECIAL_OBJECT_NEW_TARGET:
  23709. *sp++ = js_dup(new_target);
  23710. break;
  23711. case OP_SPECIAL_OBJECT_HOME_OBJECT:
  23712. {
  23713. JSObject *p1;
  23714. p1 = p->u.func.home_object;
  23715. if (unlikely(!p1))
  23716. *sp++ = JS_UNDEFINED;
  23717. else
  23718. *sp++ = js_dup(JS_MKPTR(JS_TAG_OBJECT, p1));
  23719. }
  23720. break;
  23721. case OP_SPECIAL_OBJECT_VAR_OBJECT:
  23722. *sp++ = JS_NewObjectProto(ctx, JS_NULL);
  23723. if (unlikely(JS_IsException(sp[-1])))
  23724. goto exception;
  23725. break;
  23726. case OP_SPECIAL_OBJECT_IMPORT_META:
  23727. *sp++ = js_import_meta(ctx);
  23728. if (unlikely(JS_IsException(sp[-1])))
  23729. goto exception;
  23730. break;
  23731. default:
  23732. abort();
  23733. }
  23734. }
  23735. BREAK;
  23736. CASE(OP_rest):
  23737. {
  23738. int i, n, first = get_u16(pc);
  23739. pc += 2;
  23740. i = min_int(first, argc);
  23741. n = argc - i;
  23742. *sp++ = js_create_array(ctx, n, &argv[i]);
  23743. if (unlikely(JS_IsException(sp[-1])))
  23744. goto exception;
  23745. }
  23746. BREAK;
  23747. CASE(OP_drop):
  23748. JS_FreeValue(ctx, sp[-1]);
  23749. sp--;
  23750. BREAK;
  23751. CASE(OP_nip):
  23752. JS_FreeValue(ctx, sp[-2]);
  23753. sp[-2] = sp[-1];
  23754. sp--;
  23755. BREAK;
  23756. CASE(OP_nip1): /* a b c -> b c */
  23757. JS_FreeValue(ctx, sp[-3]);
  23758. sp[-3] = sp[-2];
  23759. sp[-2] = sp[-1];
  23760. sp--;
  23761. BREAK;
  23762. CASE(OP_dup):
  23763. sp[0] = js_dup(sp[-1]);
  23764. sp++;
  23765. BREAK;
  23766. CASE(OP_dup2): /* a b -> a b a b */
  23767. sp[0] = js_dup(sp[-2]);
  23768. sp[1] = js_dup(sp[-1]);
  23769. sp += 2;
  23770. BREAK;
  23771. CASE(OP_dup3): /* a b c -> a b c a b c */
  23772. sp[0] = js_dup(sp[-3]);
  23773. sp[1] = js_dup(sp[-2]);
  23774. sp[2] = js_dup(sp[-1]);
  23775. sp += 3;
  23776. BREAK;
  23777. CASE(OP_dup1): /* a b -> a a b */
  23778. sp[0] = sp[-1];
  23779. sp[-1] = js_dup(sp[-2]);
  23780. sp++;
  23781. BREAK;
  23782. CASE(OP_insert2): /* obj a -> a obj a (dup_x1) */
  23783. sp[0] = sp[-1];
  23784. sp[-1] = sp[-2];
  23785. sp[-2] = js_dup(sp[0]);
  23786. sp++;
  23787. BREAK;
  23788. CASE(OP_insert3): /* obj prop a -> a obj prop a (dup_x2) */
  23789. sp[0] = sp[-1];
  23790. sp[-1] = sp[-2];
  23791. sp[-2] = sp[-3];
  23792. sp[-3] = js_dup(sp[0]);
  23793. sp++;
  23794. BREAK;
  23795. CASE(OP_insert4): /* this obj prop a -> a this obj prop a */
  23796. sp[0] = sp[-1];
  23797. sp[-1] = sp[-2];
  23798. sp[-2] = sp[-3];
  23799. sp[-3] = sp[-4];
  23800. sp[-4] = js_dup(sp[0]);
  23801. sp++;
  23802. BREAK;
  23803. CASE(OP_perm3): /* obj a b -> a obj b (213) */
  23804. {
  23805. JSValue tmp;
  23806. tmp = sp[-2];
  23807. sp[-2] = sp[-3];
  23808. sp[-3] = tmp;
  23809. }
  23810. BREAK;
  23811. CASE(OP_rot3l): /* x a b -> a b x (231) */
  23812. {
  23813. JSValue tmp;
  23814. tmp = sp[-3];
  23815. sp[-3] = sp[-2];
  23816. sp[-2] = sp[-1];
  23817. sp[-1] = tmp;
  23818. }
  23819. BREAK;
  23820. CASE(OP_rot4l): /* x a b c -> a b c x */
  23821. {
  23822. JSValue tmp;
  23823. tmp = sp[-4];
  23824. sp[-4] = sp[-3];
  23825. sp[-3] = sp[-2];
  23826. sp[-2] = sp[-1];
  23827. sp[-1] = tmp;
  23828. }
  23829. BREAK;
  23830. CASE(OP_rot5l): /* x a b c d -> a b c d x */
  23831. {
  23832. JSValue tmp;
  23833. tmp = sp[-5];
  23834. sp[-5] = sp[-4];
  23835. sp[-4] = sp[-3];
  23836. sp[-3] = sp[-2];
  23837. sp[-2] = sp[-1];
  23838. sp[-1] = tmp;
  23839. }
  23840. BREAK;
  23841. CASE(OP_rot3r): /* a b x -> x a b (312) */
  23842. {
  23843. JSValue tmp;
  23844. tmp = sp[-1];
  23845. sp[-1] = sp[-2];
  23846. sp[-2] = sp[-3];
  23847. sp[-3] = tmp;
  23848. }
  23849. BREAK;
  23850. CASE(OP_perm4): /* obj prop a b -> a obj prop b */
  23851. {
  23852. JSValue tmp;
  23853. tmp = sp[-2];
  23854. sp[-2] = sp[-3];
  23855. sp[-3] = sp[-4];
  23856. sp[-4] = tmp;
  23857. }
  23858. BREAK;
  23859. CASE(OP_perm5): /* this obj prop a b -> a this obj prop b */
  23860. {
  23861. JSValue tmp;
  23862. tmp = sp[-2];
  23863. sp[-2] = sp[-3];
  23864. sp[-3] = sp[-4];
  23865. sp[-4] = sp[-5];
  23866. sp[-5] = tmp;
  23867. }
  23868. BREAK;
  23869. CASE(OP_swap): /* a b -> b a */
  23870. {
  23871. JSValue tmp;
  23872. tmp = sp[-2];
  23873. sp[-2] = sp[-1];
  23874. sp[-1] = tmp;
  23875. }
  23876. BREAK;
  23877. CASE(OP_swap2): /* a b c d -> c d a b */
  23878. {
  23879. JSValue tmp1, tmp2;
  23880. tmp1 = sp[-4];
  23881. tmp2 = sp[-3];
  23882. sp[-4] = sp[-2];
  23883. sp[-3] = sp[-1];
  23884. sp[-2] = tmp1;
  23885. sp[-1] = tmp2;
  23886. }
  23887. BREAK;
  23888. CASE(OP_fclosure):
  23889. {
  23890. JSValue bfunc = js_dup(b->cpool[get_u32(pc)]);
  23891. pc += 4;
  23892. *sp++ = js_closure(ctx, bfunc, var_refs, sf);
  23893. if (unlikely(JS_IsException(sp[-1])))
  23894. goto exception;
  23895. }
  23896. BREAK;
  23897. CASE(OP_call0):
  23898. CASE(OP_call1):
  23899. CASE(OP_call2):
  23900. CASE(OP_call3):
  23901. call_argc = opcode - OP_call0;
  23902. goto has_call_argc;
  23903. CASE(OP_call):
  23904. CASE(OP_tail_call):
  23905. {
  23906. call_argc = get_u16(pc);
  23907. pc += 2;
  23908. goto has_call_argc;
  23909. has_call_argc:
  23910. call_argv = sp - call_argc;
  23911. sf->cur_pc = pc;
  23912. ret_val = JS_CallInternal(ctx, call_argv[-1], JS_UNDEFINED,
  23913. JS_UNDEFINED, call_argc,
  23914. vc(call_argv), 0);
  23915. if (unlikely(JS_IsException(ret_val)))
  23916. goto exception;
  23917. if (opcode == OP_tail_call)
  23918. goto done;
  23919. for(i = -1; i < call_argc; i++)
  23920. JS_FreeValue(ctx, call_argv[i]);
  23921. sp -= call_argc + 1;
  23922. *sp++ = ret_val;
  23923. }
  23924. BREAK;
  23925. CASE(OP_call_constructor):
  23926. {
  23927. call_argc = get_u16(pc);
  23928. pc += 2;
  23929. call_argv = sp - call_argc;
  23930. sf->cur_pc = pc;
  23931. ret_val = JS_CallConstructorInternal(ctx, call_argv[-2],
  23932. call_argv[-1], call_argc,
  23933. vc(call_argv), 0);
  23934. if (unlikely(JS_IsException(ret_val)))
  23935. goto exception;
  23936. for(i = -2; i < call_argc; i++)
  23937. JS_FreeValue(ctx, call_argv[i]);
  23938. sp -= call_argc + 2;
  23939. *sp++ = ret_val;
  23940. }
  23941. BREAK;
  23942. CASE(OP_call_method):
  23943. CASE(OP_tail_call_method):
  23944. {
  23945. call_argc = get_u16(pc);
  23946. pc += 2;
  23947. call_argv = sp - call_argc;
  23948. sf->cur_pc = pc;
  23949. ret_val = JS_CallInternal(ctx, call_argv[-1], call_argv[-2],
  23950. JS_UNDEFINED, call_argc,
  23951. vc(call_argv), 0);
  23952. if (unlikely(JS_IsException(ret_val)))
  23953. goto exception;
  23954. if (opcode == OP_tail_call_method)
  23955. goto done;
  23956. for(i = -2; i < call_argc; i++)
  23957. JS_FreeValue(ctx, call_argv[i]);
  23958. sp -= call_argc + 2;
  23959. *sp++ = ret_val;
  23960. }
  23961. BREAK;
  23962. CASE(OP_array_from):
  23963. {
  23964. call_argc = get_u16(pc);
  23965. pc += 2;
  23966. call_argv = sp - call_argc;
  23967. ret_val = JS_NewArrayFrom(ctx, call_argc, call_argv);
  23968. if (unlikely(JS_IsException(ret_val)))
  23969. goto exception;
  23970. sp -= call_argc;
  23971. *sp++ = ret_val;
  23972. }
  23973. BREAK;
  23974. CASE(OP_apply):
  23975. {
  23976. int magic;
  23977. magic = get_u16(pc);
  23978. pc += 2;
  23979. sf->cur_pc = pc;
  23980. ret_val = js_function_apply(ctx, sp[-3], 2, vc(&sp[-2]), magic);
  23981. if (unlikely(JS_IsException(ret_val)))
  23982. goto exception;
  23983. JS_FreeValue(ctx, sp[-3]);
  23984. JS_FreeValue(ctx, sp[-2]);
  23985. JS_FreeValue(ctx, sp[-1]);
  23986. sp -= 3;
  23987. *sp++ = ret_val;
  23988. }
  23989. BREAK;
  23990. CASE(OP_return):
  23991. ret_val = *--sp;
  23992. goto done;
  23993. CASE(OP_return_undef):
  23994. ret_val = JS_UNDEFINED;
  23995. goto done;
  23996. CASE(OP_check_ctor_return):
  23997. /* return true if 'this' should be returned */
  23998. if (!JS_IsObject(sp[-1])) {
  23999. if (!JS_IsUndefined(sp[-1])) {
  24000. JS_ThrowTypeError(caller_ctx, "derived class constructor must return an object or undefined");
  24001. goto exception;
  24002. }
  24003. sp[0] = JS_TRUE;
  24004. } else {
  24005. sp[0] = JS_FALSE;
  24006. }
  24007. sp++;
  24008. BREAK;
  24009. CASE(OP_check_ctor):
  24010. if (JS_IsUndefined(new_target)) {
  24011. non_ctor_call:
  24012. JS_ThrowTypeError(ctx, "class constructors must be invoked with 'new'");
  24013. goto exception;
  24014. }
  24015. BREAK;
  24016. CASE(OP_init_ctor):
  24017. {
  24018. JSValue super, ret;
  24019. sf->cur_pc = pc;
  24020. if (JS_IsUndefined(new_target))
  24021. goto non_ctor_call;
  24022. super = JS_GetPrototype(ctx, func_obj);
  24023. if (JS_IsException(super))
  24024. goto exception;
  24025. ret = JS_CallConstructor2(ctx, super, new_target, argc, argv);
  24026. JS_FreeValue(ctx, super);
  24027. if (JS_IsException(ret))
  24028. goto exception;
  24029. *sp++ = ret;
  24030. }
  24031. BREAK;
  24032. CASE(OP_check_brand):
  24033. {
  24034. int ret = JS_CheckBrand(ctx, sp[-2], sp[-1]);
  24035. if (ret < 0)
  24036. goto exception;
  24037. if (!ret) {
  24038. JS_ThrowTypeError(ctx, "invalid brand on object");
  24039. goto exception;
  24040. }
  24041. }
  24042. BREAK;
  24043. CASE(OP_add_brand):
  24044. if (JS_AddBrand(ctx, sp[-2], sp[-1]) < 0)
  24045. goto exception;
  24046. JS_FreeValue(ctx, sp[-2]);
  24047. JS_FreeValue(ctx, sp[-1]);
  24048. sp -= 2;
  24049. BREAK;
  24050. CASE(OP_throw):
  24051. JS_Throw(ctx, *--sp);
  24052. goto exception;
  24053. CASE(OP_throw_error):
  24054. #define JS_THROW_VAR_RO 0
  24055. #define JS_THROW_VAR_REDECL 1
  24056. #define JS_THROW_VAR_UNINITIALIZED 2
  24057. #define JS_THROW_ERROR_DELETE_SUPER 3
  24058. #define JS_THROW_ERROR_ITERATOR_THROW 4
  24059. {
  24060. JSAtom atom;
  24061. int type;
  24062. atom = get_u32(pc);
  24063. type = pc[4];
  24064. pc += 5;
  24065. if (type == JS_THROW_VAR_RO)
  24066. JS_ThrowTypeErrorReadOnly(ctx, JS_PROP_THROW, atom);
  24067. else
  24068. if (type == JS_THROW_VAR_REDECL)
  24069. JS_ThrowSyntaxErrorVarRedeclaration(ctx, atom);
  24070. else
  24071. if (type == JS_THROW_VAR_UNINITIALIZED)
  24072. JS_ThrowReferenceErrorUninitialized(ctx, atom);
  24073. else
  24074. if (type == JS_THROW_ERROR_DELETE_SUPER)
  24075. JS_ThrowReferenceError(ctx, "unsupported reference to 'super'");
  24076. else
  24077. if (type == JS_THROW_ERROR_ITERATOR_THROW)
  24078. JS_ThrowTypeError(ctx, "iterator does not have a throw method");
  24079. else
  24080. JS_ThrowInternalError(ctx, "invalid throw var type %d", type);
  24081. }
  24082. goto exception;
  24083. CASE(OP_eval):
  24084. {
  24085. JSValue obj;
  24086. int scope_idx;
  24087. call_argc = get_u16(pc);
  24088. scope_idx = get_u16(pc + 2) - 1;
  24089. pc += 4;
  24090. call_argv = sp - call_argc;
  24091. sf->cur_pc = pc;
  24092. if (js_same_value(ctx, call_argv[-1], ctx->eval_obj)) {
  24093. if (call_argc >= 1)
  24094. obj = call_argv[0];
  24095. else
  24096. obj = JS_UNDEFINED;
  24097. ret_val = JS_EvalObject(ctx, JS_UNDEFINED, obj,
  24098. JS_EVAL_TYPE_DIRECT, scope_idx);
  24099. } else {
  24100. ret_val = JS_CallInternal(ctx, call_argv[-1], JS_UNDEFINED,
  24101. JS_UNDEFINED, call_argc,
  24102. vc(call_argv), 0);
  24103. }
  24104. if (unlikely(JS_IsException(ret_val)))
  24105. goto exception;
  24106. for(i = -1; i < call_argc; i++)
  24107. JS_FreeValue(ctx, call_argv[i]);
  24108. sp -= call_argc + 1;
  24109. *sp++ = ret_val;
  24110. }
  24111. BREAK;
  24112. /* could merge with OP_apply */
  24113. CASE(OP_apply_eval):
  24114. {
  24115. int scope_idx;
  24116. uint32_t len;
  24117. JSValue *tab;
  24118. JSValue obj;
  24119. scope_idx = get_u16(pc) - 1;
  24120. pc += 2;
  24121. sf->cur_pc = pc;
  24122. tab = build_arg_list(ctx, &len, sp[-1]);
  24123. if (!tab)
  24124. goto exception;
  24125. if (js_same_value(ctx, sp[-2], ctx->eval_obj)) {
  24126. if (len >= 1)
  24127. obj = tab[0];
  24128. else
  24129. obj = JS_UNDEFINED;
  24130. ret_val = JS_EvalObject(ctx, JS_UNDEFINED, obj,
  24131. JS_EVAL_TYPE_DIRECT, scope_idx);
  24132. } else {
  24133. ret_val = JS_Call(ctx, sp[-2], JS_UNDEFINED, len, vc(tab));
  24134. }
  24135. free_arg_list(ctx, tab, len);
  24136. if (unlikely(JS_IsException(ret_val)))
  24137. goto exception;
  24138. JS_FreeValue(ctx, sp[-2]);
  24139. JS_FreeValue(ctx, sp[-1]);
  24140. sp -= 2;
  24141. *sp++ = ret_val;
  24142. }
  24143. BREAK;
  24144. CASE(OP_regexp):
  24145. {
  24146. sp[-2] = js_regexp_constructor_internal(ctx, JS_UNDEFINED,
  24147. sp[-2], sp[-1]);
  24148. sp--;
  24149. }
  24150. BREAK;
  24151. CASE(OP_get_super):
  24152. {
  24153. JSValue proto;
  24154. proto = JS_GetPrototype(ctx, sp[-1]);
  24155. if (JS_IsException(proto))
  24156. goto exception;
  24157. JS_FreeValue(ctx, sp[-1]);
  24158. sp[-1] = proto;
  24159. }
  24160. BREAK;
  24161. CASE(OP_import):
  24162. {
  24163. JSValue val;
  24164. sf->cur_pc = pc;
  24165. val = js_dynamic_import(ctx, sp[-1]);
  24166. if (JS_IsException(val))
  24167. goto exception;
  24168. JS_FreeValue(ctx, sp[-1]);
  24169. sp[-1] = val;
  24170. }
  24171. BREAK;
  24172. CASE(OP_check_var):
  24173. {
  24174. int ret;
  24175. JSAtom atom;
  24176. atom = get_u32(pc);
  24177. pc += 4;
  24178. ret = JS_CheckGlobalVar(ctx, atom);
  24179. if (ret < 0)
  24180. goto exception;
  24181. *sp++ = js_bool(ret);
  24182. }
  24183. BREAK;
  24184. CASE(OP_get_var_undef):
  24185. CASE(OP_get_var):
  24186. {
  24187. JSValue val;
  24188. JSAtom atom;
  24189. atom = get_u32(pc);
  24190. pc += 4;
  24191. sf->cur_pc = pc;
  24192. val = JS_GetGlobalVar(ctx, atom, opcode - OP_get_var_undef);
  24193. if (unlikely(JS_IsException(val)))
  24194. goto exception;
  24195. *sp++ = val;
  24196. }
  24197. BREAK;
  24198. CASE(OP_put_var):
  24199. CASE(OP_put_var_init):
  24200. {
  24201. int ret;
  24202. JSAtom atom;
  24203. atom = get_u32(pc);
  24204. pc += 4;
  24205. sf->cur_pc = pc;
  24206. ret = JS_SetGlobalVar(ctx, atom, sp[-1], opcode - OP_put_var);
  24207. sp--;
  24208. if (unlikely(ret < 0))
  24209. goto exception;
  24210. }
  24211. BREAK;
  24212. CASE(OP_put_var_strict):
  24213. {
  24214. int ret;
  24215. JSAtom atom;
  24216. atom = get_u32(pc);
  24217. pc += 4;
  24218. sf->cur_pc = pc;
  24219. /* sp[-2] is JS_TRUE or JS_FALSE */
  24220. if (unlikely(!JS_VALUE_GET_INT(sp[-2]))) {
  24221. JS_ThrowReferenceErrorNotDefined(ctx, atom);
  24222. goto exception;
  24223. }
  24224. ret = JS_SetGlobalVar(ctx, atom, sp[-1], 2);
  24225. sp -= 2;
  24226. if (unlikely(ret < 0))
  24227. goto exception;
  24228. }
  24229. BREAK;
  24230. CASE(OP_check_define_var):
  24231. {
  24232. JSAtom atom;
  24233. int flags;
  24234. atom = get_u32(pc);
  24235. flags = pc[4];
  24236. pc += 5;
  24237. if (JS_CheckDefineGlobalVar(ctx, atom, flags))
  24238. goto exception;
  24239. }
  24240. BREAK;
  24241. CASE(OP_define_var):
  24242. {
  24243. JSAtom atom;
  24244. int flags;
  24245. atom = get_u32(pc);
  24246. flags = pc[4];
  24247. pc += 5;
  24248. if (JS_DefineGlobalVar(ctx, atom, flags))
  24249. goto exception;
  24250. }
  24251. BREAK;
  24252. CASE(OP_define_func):
  24253. {
  24254. JSAtom atom;
  24255. int flags;
  24256. atom = get_u32(pc);
  24257. flags = pc[4];
  24258. pc += 5;
  24259. if (JS_DefineGlobalFunction(ctx, atom, sp[-1], flags))
  24260. goto exception;
  24261. JS_FreeValue(ctx, sp[-1]);
  24262. sp--;
  24263. }
  24264. BREAK;
  24265. CASE(OP_get_loc):
  24266. {
  24267. int idx;
  24268. idx = get_u16(pc);
  24269. pc += 2;
  24270. sp[0] = js_dup(var_buf[idx]);
  24271. sp++;
  24272. }
  24273. BREAK;
  24274. CASE(OP_put_loc):
  24275. {
  24276. int idx;
  24277. idx = get_u16(pc);
  24278. pc += 2;
  24279. set_value(ctx, &var_buf[idx], sp[-1]);
  24280. sp--;
  24281. }
  24282. BREAK;
  24283. CASE(OP_set_loc):
  24284. {
  24285. int idx;
  24286. idx = get_u16(pc);
  24287. pc += 2;
  24288. set_value(ctx, &var_buf[idx], js_dup(sp[-1]));
  24289. }
  24290. BREAK;
  24291. CASE(OP_get_arg):
  24292. {
  24293. int idx;
  24294. idx = get_u16(pc);
  24295. pc += 2;
  24296. sp[0] = js_dup(arg_buf[idx]);
  24297. sp++;
  24298. }
  24299. BREAK;
  24300. CASE(OP_put_arg):
  24301. {
  24302. int idx;
  24303. idx = get_u16(pc);
  24304. pc += 2;
  24305. set_value(ctx, &arg_buf[idx], sp[-1]);
  24306. sp--;
  24307. }
  24308. BREAK;
  24309. CASE(OP_set_arg):
  24310. {
  24311. int idx;
  24312. idx = get_u16(pc);
  24313. pc += 2;
  24314. set_value(ctx, &arg_buf[idx], js_dup(sp[-1]));
  24315. }
  24316. BREAK;
  24317. CASE(OP_get_loc8): *sp++ = js_dup(var_buf[*pc++]); BREAK;
  24318. CASE(OP_put_loc8): set_value(ctx, &var_buf[*pc++], *--sp); BREAK;
  24319. CASE(OP_set_loc8): set_value(ctx, &var_buf[*pc++], js_dup(sp[-1])); BREAK;
  24320. // Observation: get_loc0 and get_loc1 are individually very
  24321. // frequent opcodes _and_ they are very often paired together,
  24322. // making them ideal candidates for opcode fusion.
  24323. CASE(OP_get_loc0_loc1):
  24324. *sp++ = js_dup(var_buf[0]);
  24325. *sp++ = js_dup(var_buf[1]);
  24326. BREAK;
  24327. CASE(OP_get_loc0): *sp++ = js_dup(var_buf[0]); BREAK;
  24328. CASE(OP_get_loc1): *sp++ = js_dup(var_buf[1]); BREAK;
  24329. CASE(OP_get_loc2): *sp++ = js_dup(var_buf[2]); BREAK;
  24330. CASE(OP_get_loc3): *sp++ = js_dup(var_buf[3]); BREAK;
  24331. CASE(OP_put_loc0): set_value(ctx, &var_buf[0], *--sp); BREAK;
  24332. CASE(OP_put_loc1): set_value(ctx, &var_buf[1], *--sp); BREAK;
  24333. CASE(OP_put_loc2): set_value(ctx, &var_buf[2], *--sp); BREAK;
  24334. CASE(OP_put_loc3): set_value(ctx, &var_buf[3], *--sp); BREAK;
  24335. CASE(OP_set_loc0): set_value(ctx, &var_buf[0], js_dup(sp[-1])); BREAK;
  24336. CASE(OP_set_loc1): set_value(ctx, &var_buf[1], js_dup(sp[-1])); BREAK;
  24337. CASE(OP_set_loc2): set_value(ctx, &var_buf[2], js_dup(sp[-1])); BREAK;
  24338. CASE(OP_set_loc3): set_value(ctx, &var_buf[3], js_dup(sp[-1])); BREAK;
  24339. CASE(OP_get_arg0): *sp++ = js_dup(arg_buf[0]); BREAK;
  24340. CASE(OP_get_arg1): *sp++ = js_dup(arg_buf[1]); BREAK;
  24341. CASE(OP_get_arg2): *sp++ = js_dup(arg_buf[2]); BREAK;
  24342. CASE(OP_get_arg3): *sp++ = js_dup(arg_buf[3]); BREAK;
  24343. CASE(OP_put_arg0): set_value(ctx, &arg_buf[0], *--sp); BREAK;
  24344. CASE(OP_put_arg1): set_value(ctx, &arg_buf[1], *--sp); BREAK;
  24345. CASE(OP_put_arg2): set_value(ctx, &arg_buf[2], *--sp); BREAK;
  24346. CASE(OP_put_arg3): set_value(ctx, &arg_buf[3], *--sp); BREAK;
  24347. CASE(OP_set_arg0): set_value(ctx, &arg_buf[0], js_dup(sp[-1])); BREAK;
  24348. CASE(OP_set_arg1): set_value(ctx, &arg_buf[1], js_dup(sp[-1])); BREAK;
  24349. CASE(OP_set_arg2): set_value(ctx, &arg_buf[2], js_dup(sp[-1])); BREAK;
  24350. CASE(OP_set_arg3): set_value(ctx, &arg_buf[3], js_dup(sp[-1])); BREAK;
  24351. CASE(OP_get_var_ref0): *sp++ = js_dup(*var_refs[0]->pvalue); BREAK;
  24352. CASE(OP_get_var_ref1): *sp++ = js_dup(*var_refs[1]->pvalue); BREAK;
  24353. CASE(OP_get_var_ref2): *sp++ = js_dup(*var_refs[2]->pvalue); BREAK;
  24354. CASE(OP_get_var_ref3): *sp++ = js_dup(*var_refs[3]->pvalue); BREAK;
  24355. CASE(OP_put_var_ref0): set_value(ctx, var_refs[0]->pvalue, *--sp); BREAK;
  24356. CASE(OP_put_var_ref1): set_value(ctx, var_refs[1]->pvalue, *--sp); BREAK;
  24357. CASE(OP_put_var_ref2): set_value(ctx, var_refs[2]->pvalue, *--sp); BREAK;
  24358. CASE(OP_put_var_ref3): set_value(ctx, var_refs[3]->pvalue, *--sp); BREAK;
  24359. CASE(OP_set_var_ref0): set_value(ctx, var_refs[0]->pvalue, js_dup(sp[-1])); BREAK;
  24360. CASE(OP_set_var_ref1): set_value(ctx, var_refs[1]->pvalue, js_dup(sp[-1])); BREAK;
  24361. CASE(OP_set_var_ref2): set_value(ctx, var_refs[2]->pvalue, js_dup(sp[-1])); BREAK;
  24362. CASE(OP_set_var_ref3): set_value(ctx, var_refs[3]->pvalue, js_dup(sp[-1])); BREAK;
  24363. CASE(OP_get_var_ref):
  24364. {
  24365. int idx;
  24366. JSValue val;
  24367. idx = get_u16(pc);
  24368. pc += 2;
  24369. val = *var_refs[idx]->pvalue;
  24370. sp[0] = js_dup(val);
  24371. sp++;
  24372. }
  24373. BREAK;
  24374. CASE(OP_put_var_ref):
  24375. {
  24376. int idx;
  24377. idx = get_u16(pc);
  24378. pc += 2;
  24379. set_value(ctx, var_refs[idx]->pvalue, sp[-1]);
  24380. sp--;
  24381. }
  24382. BREAK;
  24383. CASE(OP_set_var_ref):
  24384. {
  24385. int idx;
  24386. idx = get_u16(pc);
  24387. pc += 2;
  24388. set_value(ctx, var_refs[idx]->pvalue, js_dup(sp[-1]));
  24389. }
  24390. BREAK;
  24391. CASE(OP_get_var_ref_check):
  24392. {
  24393. int idx;
  24394. JSValue val;
  24395. idx = get_u16(pc);
  24396. pc += 2;
  24397. val = *var_refs[idx]->pvalue;
  24398. if (unlikely(JS_IsUninitialized(val))) {
  24399. JS_ThrowReferenceErrorUninitialized2(ctx, b, idx, true);
  24400. goto exception;
  24401. }
  24402. sp[0] = js_dup(val);
  24403. sp++;
  24404. }
  24405. BREAK;
  24406. CASE(OP_put_var_ref_check):
  24407. {
  24408. int idx;
  24409. idx = get_u16(pc);
  24410. pc += 2;
  24411. if (unlikely(JS_IsUninitialized(*var_refs[idx]->pvalue))) {
  24412. JS_ThrowReferenceErrorUninitialized2(ctx, b, idx, true);
  24413. goto exception;
  24414. }
  24415. set_value(ctx, var_refs[idx]->pvalue, sp[-1]);
  24416. sp--;
  24417. }
  24418. BREAK;
  24419. CASE(OP_put_var_ref_check_init):
  24420. {
  24421. int idx;
  24422. idx = get_u16(pc);
  24423. pc += 2;
  24424. if (unlikely(!JS_IsUninitialized(*var_refs[idx]->pvalue))) {
  24425. JS_ThrowReferenceErrorUninitialized2(ctx, b, idx, true);
  24426. goto exception;
  24427. }
  24428. set_value(ctx, var_refs[idx]->pvalue, sp[-1]);
  24429. sp--;
  24430. }
  24431. BREAK;
  24432. CASE(OP_set_loc_uninitialized):
  24433. {
  24434. int idx;
  24435. idx = get_u16(pc);
  24436. pc += 2;
  24437. set_value(ctx, &var_buf[idx], JS_UNINITIALIZED);
  24438. }
  24439. BREAK;
  24440. CASE(OP_get_loc_check):
  24441. {
  24442. int idx;
  24443. idx = get_u16(pc);
  24444. pc += 2;
  24445. if (unlikely(JS_IsUninitialized(var_buf[idx]))) {
  24446. JS_ThrowReferenceErrorUninitialized2(caller_ctx, b, idx,
  24447. false);
  24448. goto exception;
  24449. }
  24450. sp[0] = js_dup(var_buf[idx]);
  24451. sp++;
  24452. }
  24453. BREAK;
  24454. CASE(OP_put_loc_check):
  24455. {
  24456. int idx;
  24457. idx = get_u16(pc);
  24458. pc += 2;
  24459. if (unlikely(JS_IsUninitialized(var_buf[idx]))) {
  24460. JS_ThrowReferenceErrorUninitialized2(caller_ctx, b, idx,
  24461. false);
  24462. goto exception;
  24463. }
  24464. set_value(ctx, &var_buf[idx], sp[-1]);
  24465. sp--;
  24466. }
  24467. BREAK;
  24468. CASE(OP_put_loc_check_init):
  24469. {
  24470. int idx;
  24471. idx = get_u16(pc);
  24472. pc += 2;
  24473. if (unlikely(!JS_IsUninitialized(var_buf[idx]))) {
  24474. JS_ThrowReferenceError(caller_ctx,
  24475. "'this' can be initialized only once");
  24476. goto exception;
  24477. }
  24478. set_value(ctx, &var_buf[idx], sp[-1]);
  24479. sp--;
  24480. }
  24481. BREAK;
  24482. CASE(OP_close_loc):
  24483. {
  24484. int idx;
  24485. idx = get_u16(pc);
  24486. pc += 2;
  24487. close_lexical_var(ctx, sf, idx);
  24488. }
  24489. BREAK;
  24490. CASE(OP_make_loc_ref):
  24491. CASE(OP_make_arg_ref):
  24492. CASE(OP_make_var_ref_ref):
  24493. {
  24494. JSVarRef *var_ref;
  24495. JSProperty *pr;
  24496. JSAtom atom;
  24497. int idx;
  24498. atom = get_u32(pc);
  24499. idx = get_u16(pc + 4);
  24500. pc += 6;
  24501. *sp++ = JS_NewObjectProto(ctx, JS_NULL);
  24502. if (unlikely(JS_IsException(sp[-1])))
  24503. goto exception;
  24504. if (opcode == OP_make_var_ref_ref) {
  24505. var_ref = var_refs[idx];
  24506. var_ref->header.ref_count++;
  24507. } else {
  24508. var_ref = get_var_ref(ctx, sf, idx, opcode == OP_make_arg_ref);
  24509. if (!var_ref)
  24510. goto exception;
  24511. }
  24512. pr = add_property(ctx, JS_VALUE_GET_OBJ(sp[-1]), atom,
  24513. JS_PROP_WRITABLE | JS_PROP_VARREF);
  24514. if (!pr) {
  24515. free_var_ref(rt, var_ref);
  24516. goto exception;
  24517. }
  24518. pr->u.var_ref = var_ref;
  24519. *sp++ = JS_AtomToValue(ctx, atom);
  24520. }
  24521. BREAK;
  24522. CASE(OP_make_var_ref):
  24523. {
  24524. JSAtom atom;
  24525. atom = get_u32(pc);
  24526. pc += 4;
  24527. if (JS_GetGlobalVarRef(ctx, atom, sp))
  24528. goto exception;
  24529. sp += 2;
  24530. }
  24531. BREAK;
  24532. CASE(OP_goto):
  24533. pc += (int32_t)get_u32(pc);
  24534. if (unlikely(js_poll_interrupts(ctx)))
  24535. goto exception;
  24536. BREAK;
  24537. CASE(OP_goto16):
  24538. pc += (int16_t)get_u16(pc);
  24539. if (unlikely(js_poll_interrupts(ctx)))
  24540. goto exception;
  24541. BREAK;
  24542. CASE(OP_goto8):
  24543. pc += (int8_t)pc[0];
  24544. if (unlikely(js_poll_interrupts(ctx)))
  24545. goto exception;
  24546. BREAK;
  24547. CASE(OP_if_true):
  24548. {
  24549. int res;
  24550. JSValue op1;
  24551. op1 = sp[-1];
  24552. pc += 4;
  24553. if ((uint32_t)JS_VALUE_GET_TAG(op1) <= JS_TAG_UNDEFINED) {
  24554. res = JS_VALUE_GET_INT(op1);
  24555. } else {
  24556. res = JS_ToBoolFree(ctx, op1);
  24557. }
  24558. sp--;
  24559. if (res) {
  24560. pc += (int32_t)get_u32(pc - 4) - 4;
  24561. }
  24562. if (unlikely(js_poll_interrupts(ctx)))
  24563. goto exception;
  24564. }
  24565. BREAK;
  24566. CASE(OP_if_false):
  24567. {
  24568. int res;
  24569. JSValue op1;
  24570. op1 = sp[-1];
  24571. pc += 4;
  24572. if ((uint32_t)JS_VALUE_GET_TAG(op1) <= JS_TAG_UNDEFINED) {
  24573. res = JS_VALUE_GET_INT(op1);
  24574. } else {
  24575. res = JS_ToBoolFree(ctx, op1);
  24576. }
  24577. sp--;
  24578. if (!res) {
  24579. pc += (int32_t)get_u32(pc - 4) - 4;
  24580. }
  24581. if (unlikely(js_poll_interrupts(ctx)))
  24582. goto exception;
  24583. }
  24584. BREAK;
  24585. CASE(OP_if_true8):
  24586. {
  24587. int res;
  24588. JSValue op1;
  24589. op1 = sp[-1];
  24590. pc += 1;
  24591. if ((uint32_t)JS_VALUE_GET_TAG(op1) <= JS_TAG_UNDEFINED) {
  24592. res = JS_VALUE_GET_INT(op1);
  24593. } else {
  24594. res = JS_ToBoolFree(ctx, op1);
  24595. }
  24596. sp--;
  24597. if (res) {
  24598. pc += (int8_t)pc[-1] - 1;
  24599. }
  24600. if (unlikely(js_poll_interrupts(ctx)))
  24601. goto exception;
  24602. }
  24603. BREAK;
  24604. CASE(OP_if_false8):
  24605. {
  24606. int res;
  24607. JSValue op1;
  24608. op1 = sp[-1];
  24609. pc += 1;
  24610. if ((uint32_t)JS_VALUE_GET_TAG(op1) <= JS_TAG_UNDEFINED) {
  24611. res = JS_VALUE_GET_INT(op1);
  24612. } else {
  24613. res = JS_ToBoolFree(ctx, op1);
  24614. }
  24615. sp--;
  24616. if (!res) {
  24617. pc += (int8_t)pc[-1] - 1;
  24618. }
  24619. if (unlikely(js_poll_interrupts(ctx)))
  24620. goto exception;
  24621. }
  24622. BREAK;
  24623. CASE(OP_catch):
  24624. {
  24625. int32_t diff;
  24626. diff = get_u32(pc);
  24627. sp[0] = JS_NewCatchOffset(ctx, pc + diff - b->byte_code_buf);
  24628. sp++;
  24629. pc += 4;
  24630. }
  24631. BREAK;
  24632. CASE(OP_gosub):
  24633. {
  24634. int32_t diff;
  24635. diff = get_u32(pc);
  24636. /* XXX: should have a different tag to avoid security flaw */
  24637. sp[0] = js_int32(pc + 4 - b->byte_code_buf);
  24638. sp++;
  24639. pc += diff;
  24640. }
  24641. BREAK;
  24642. CASE(OP_ret):
  24643. {
  24644. JSValue op1;
  24645. uint32_t pos;
  24646. op1 = sp[-1];
  24647. if (unlikely(JS_VALUE_GET_TAG(op1) != JS_TAG_INT))
  24648. goto ret_fail;
  24649. pos = JS_VALUE_GET_INT(op1);
  24650. if (unlikely(pos >= b->byte_code_len)) {
  24651. ret_fail:
  24652. JS_ThrowInternalError(ctx, "invalid ret value");
  24653. goto exception;
  24654. }
  24655. sp--;
  24656. pc = b->byte_code_buf + pos;
  24657. }
  24658. BREAK;
  24659. CASE(OP_for_in_start):
  24660. sf->cur_pc = pc;
  24661. if (js_for_in_start(ctx, sp))
  24662. goto exception;
  24663. BREAK;
  24664. CASE(OP_for_in_next):
  24665. sf->cur_pc = pc;
  24666. if (js_for_in_next(ctx, sp))
  24667. goto exception;
  24668. sp += 2;
  24669. BREAK;
  24670. CASE(OP_for_of_start):
  24671. sf->cur_pc = pc;
  24672. if (js_for_of_start(ctx, sp, false))
  24673. goto exception;
  24674. sp += 1;
  24675. *sp++ = JS_NewCatchOffset(ctx, 0);
  24676. BREAK;
  24677. CASE(OP_for_of_next):
  24678. {
  24679. int offset = -3 - pc[0];
  24680. pc += 1;
  24681. sf->cur_pc = pc;
  24682. if (js_for_of_next(ctx, sp, offset))
  24683. goto exception;
  24684. sp += 2;
  24685. }
  24686. BREAK;
  24687. CASE(OP_for_await_of_start):
  24688. sf->cur_pc = pc;
  24689. if (js_for_of_start(ctx, sp, true))
  24690. goto exception;
  24691. sp += 1;
  24692. *sp++ = JS_NewCatchOffset(ctx, 0);
  24693. BREAK;
  24694. CASE(OP_iterator_get_value_done):
  24695. sf->cur_pc = pc;
  24696. if (js_iterator_get_value_done(ctx, sp))
  24697. goto exception;
  24698. sp += 1;
  24699. BREAK;
  24700. CASE(OP_iterator_check_object):
  24701. if (unlikely(!JS_IsObject(sp[-1]))) {
  24702. JS_ThrowTypeError(ctx, "iterator must return an object");
  24703. goto exception;
  24704. }
  24705. BREAK;
  24706. CASE(OP_iterator_close):
  24707. /* iter_obj next catch_offset -> */
  24708. sp--; /* drop the catch offset to avoid getting caught by exception */
  24709. JS_FreeValue(ctx, sp[-1]); /* drop the next method */
  24710. sp--;
  24711. if (!JS_IsUndefined(sp[-1])) {
  24712. sf->cur_pc = pc;
  24713. if (JS_IteratorClose(ctx, sp[-1], false))
  24714. goto exception;
  24715. JS_FreeValue(ctx, sp[-1]);
  24716. }
  24717. sp--;
  24718. BREAK;
  24719. CASE(OP_nip_catch):
  24720. {
  24721. JSValue ret_val;
  24722. /* catch_offset ... ret_val -> ret_eval */
  24723. ret_val = *--sp;
  24724. while (sp > stack_buf &&
  24725. JS_VALUE_GET_TAG(sp[-1]) != JS_TAG_CATCH_OFFSET) {
  24726. JS_FreeValue(ctx, *--sp);
  24727. }
  24728. if (unlikely(sp == stack_buf)) {
  24729. JS_ThrowInternalError(ctx, "nip_catch");
  24730. JS_FreeValue(ctx, ret_val);
  24731. goto exception;
  24732. }
  24733. sp[-1] = ret_val;
  24734. }
  24735. BREAK;
  24736. CASE(OP_iterator_next):
  24737. /* stack: iter_obj next catch_offset val */
  24738. {
  24739. JSValue ret;
  24740. sf->cur_pc = pc;
  24741. ret = JS_Call(ctx, sp[-3], sp[-4], 1, vc(sp - 1));
  24742. if (JS_IsException(ret))
  24743. goto exception;
  24744. JS_FreeValue(ctx, sp[-1]);
  24745. sp[-1] = ret;
  24746. }
  24747. BREAK;
  24748. CASE(OP_iterator_call):
  24749. /* stack: iter_obj next catch_offset val */
  24750. {
  24751. JSValue method, ret;
  24752. bool ret_flag;
  24753. int flags;
  24754. flags = *pc++;
  24755. sf->cur_pc = pc;
  24756. method = JS_GetProperty(ctx, sp[-4], (flags & 1) ?
  24757. JS_ATOM_throw : JS_ATOM_return);
  24758. if (JS_IsException(method))
  24759. goto exception;
  24760. if (JS_IsUndefined(method) || JS_IsNull(method)) {
  24761. ret_flag = true;
  24762. } else {
  24763. if (flags & 2) {
  24764. /* no argument */
  24765. ret = JS_CallFree(ctx, method, sp[-4],
  24766. 0, NULL);
  24767. } else {
  24768. ret = JS_CallFree(ctx, method, sp[-4],
  24769. 1, vc(sp - 1));
  24770. }
  24771. if (JS_IsException(ret))
  24772. goto exception;
  24773. JS_FreeValue(ctx, sp[-1]);
  24774. sp[-1] = ret;
  24775. ret_flag = false;
  24776. }
  24777. sp[0] = js_bool(ret_flag);
  24778. sp += 1;
  24779. }
  24780. BREAK;
  24781. CASE(OP_lnot):
  24782. {
  24783. int res;
  24784. JSValue op1;
  24785. op1 = sp[-1];
  24786. if ((uint32_t)JS_VALUE_GET_TAG(op1) <= JS_TAG_UNDEFINED) {
  24787. res = JS_VALUE_GET_INT(op1) != 0;
  24788. } else {
  24789. res = JS_ToBoolFree(ctx, op1);
  24790. }
  24791. sp[-1] = js_bool(!res);
  24792. }
  24793. BREAK;
  24794. CASE(OP_get_field):
  24795. {
  24796. JSValue val;
  24797. JSAtom atom;
  24798. atom = get_u32(pc);
  24799. pc += 4;
  24800. sf->cur_pc = pc;
  24801. val = JS_GetPropertyInternal(ctx, sp[-1], atom, sp[-1], false);
  24802. if (unlikely(JS_IsException(val)))
  24803. goto exception;
  24804. JS_FreeValue(ctx, sp[-1]);
  24805. sp[-1] = val;
  24806. }
  24807. BREAK;
  24808. CASE(OP_get_field2):
  24809. {
  24810. JSValue val;
  24811. JSAtom atom;
  24812. atom = get_u32(pc);
  24813. pc += 4;
  24814. sf->cur_pc = pc;
  24815. val = JS_GetPropertyInternal(ctx, sp[-1], atom, sp[-1], false);
  24816. if (unlikely(JS_IsException(val)))
  24817. goto exception;
  24818. *sp++ = val;
  24819. }
  24820. BREAK;
  24821. CASE(OP_put_field):
  24822. {
  24823. int ret;
  24824. JSAtom atom;
  24825. atom = get_u32(pc);
  24826. pc += 4;
  24827. sf->cur_pc = pc;
  24828. ret = JS_SetPropertyInternal2(ctx,
  24829. sp[-2], atom,
  24830. sp[-1], sp[-2],
  24831. JS_PROP_THROW_STRICT);
  24832. JS_FreeValue(ctx, sp[-2]);
  24833. sp -= 2;
  24834. if (unlikely(ret < 0))
  24835. goto exception;
  24836. }
  24837. BREAK;
  24838. CASE(OP_private_symbol):
  24839. {
  24840. JSAtom atom;
  24841. JSValue val;
  24842. atom = get_u32(pc);
  24843. pc += 4;
  24844. val = JS_NewSymbolFromAtom(ctx, atom, JS_ATOM_TYPE_PRIVATE);
  24845. if (JS_IsException(val))
  24846. goto exception;
  24847. *sp++ = val;
  24848. }
  24849. BREAK;
  24850. CASE(OP_get_private_field):
  24851. {
  24852. JSValue val;
  24853. sf->cur_pc = pc;
  24854. val = JS_GetPrivateField(ctx, sp[-2], sp[-1]);
  24855. JS_FreeValue(ctx, sp[-1]);
  24856. JS_FreeValue(ctx, sp[-2]);
  24857. sp[-2] = val;
  24858. sp--;
  24859. if (unlikely(JS_IsException(val)))
  24860. goto exception;
  24861. }
  24862. BREAK;
  24863. CASE(OP_put_private_field):
  24864. {
  24865. int ret;
  24866. sf->cur_pc = pc;
  24867. ret = JS_SetPrivateField(ctx, sp[-3], sp[-1], sp[-2]);
  24868. JS_FreeValue(ctx, sp[-3]);
  24869. JS_FreeValue(ctx, sp[-1]);
  24870. sp -= 3;
  24871. if (unlikely(ret < 0))
  24872. goto exception;
  24873. }
  24874. BREAK;
  24875. CASE(OP_define_private_field):
  24876. {
  24877. int ret;
  24878. ret = JS_DefinePrivateField(ctx, sp[-3], sp[-2], sp[-1]);
  24879. JS_FreeValue(ctx, sp[-2]);
  24880. sp -= 2;
  24881. if (unlikely(ret < 0))
  24882. goto exception;
  24883. }
  24884. BREAK;
  24885. CASE(OP_define_field):
  24886. {
  24887. int ret;
  24888. JSAtom atom;
  24889. atom = get_u32(pc);
  24890. pc += 4;
  24891. ret = JS_DefinePropertyValue(ctx, sp[-2], atom, sp[-1],
  24892. JS_PROP_C_W_E | JS_PROP_THROW);
  24893. sp--;
  24894. if (unlikely(ret < 0))
  24895. goto exception;
  24896. }
  24897. BREAK;
  24898. CASE(OP_set_name):
  24899. {
  24900. int ret;
  24901. JSAtom atom;
  24902. atom = get_u32(pc);
  24903. pc += 4;
  24904. ret = JS_DefineObjectName(ctx, sp[-1], atom, JS_PROP_CONFIGURABLE);
  24905. if (unlikely(ret < 0))
  24906. goto exception;
  24907. }
  24908. BREAK;
  24909. CASE(OP_set_name_computed):
  24910. {
  24911. int ret;
  24912. ret = JS_DefineObjectNameComputed(ctx, sp[-1], sp[-2], JS_PROP_CONFIGURABLE);
  24913. if (unlikely(ret < 0))
  24914. goto exception;
  24915. }
  24916. BREAK;
  24917. CASE(OP_set_proto):
  24918. {
  24919. JSValue proto;
  24920. proto = sp[-1];
  24921. if (JS_IsObject(proto) || JS_IsNull(proto)) {
  24922. if (JS_SetPrototypeInternal(ctx, sp[-2], proto, true) < 0)
  24923. goto exception;
  24924. }
  24925. JS_FreeValue(ctx, proto);
  24926. sp--;
  24927. }
  24928. BREAK;
  24929. CASE(OP_set_home_object):
  24930. js_method_set_home_object(ctx, sp[-1], sp[-2]);
  24931. BREAK;
  24932. CASE(OP_define_method):
  24933. CASE(OP_define_method_computed):
  24934. {
  24935. JSValue getter, setter, value;
  24936. JSValue obj;
  24937. JSAtom atom;
  24938. int flags, ret, op_flags;
  24939. bool is_computed;
  24940. #define OP_DEFINE_METHOD_METHOD 0
  24941. #define OP_DEFINE_METHOD_GETTER 1
  24942. #define OP_DEFINE_METHOD_SETTER 2
  24943. #define OP_DEFINE_METHOD_ENUMERABLE 4
  24944. is_computed = (opcode == OP_define_method_computed);
  24945. if (is_computed) {
  24946. atom = JS_ValueToAtom(ctx, sp[-2]);
  24947. if (unlikely(atom == JS_ATOM_NULL))
  24948. goto exception;
  24949. opcode += OP_define_method - OP_define_method_computed;
  24950. } else {
  24951. atom = get_u32(pc);
  24952. pc += 4;
  24953. }
  24954. op_flags = *pc++;
  24955. obj = sp[-2 - is_computed];
  24956. flags = JS_PROP_HAS_CONFIGURABLE | JS_PROP_CONFIGURABLE |
  24957. JS_PROP_HAS_ENUMERABLE | JS_PROP_THROW;
  24958. if (op_flags & OP_DEFINE_METHOD_ENUMERABLE)
  24959. flags |= JS_PROP_ENUMERABLE;
  24960. op_flags &= 3;
  24961. value = JS_UNDEFINED;
  24962. getter = JS_UNDEFINED;
  24963. setter = JS_UNDEFINED;
  24964. if (op_flags == OP_DEFINE_METHOD_METHOD) {
  24965. value = sp[-1];
  24966. flags |= JS_PROP_HAS_VALUE | JS_PROP_HAS_WRITABLE | JS_PROP_WRITABLE;
  24967. } else if (op_flags == OP_DEFINE_METHOD_GETTER) {
  24968. getter = sp[-1];
  24969. flags |= JS_PROP_HAS_GET;
  24970. } else {
  24971. setter = sp[-1];
  24972. flags |= JS_PROP_HAS_SET;
  24973. }
  24974. ret = js_method_set_properties(ctx, sp[-1], atom, flags, obj);
  24975. if (ret >= 0) {
  24976. ret = JS_DefineProperty(ctx, obj, atom, value,
  24977. getter, setter, flags);
  24978. }
  24979. JS_FreeValue(ctx, sp[-1]);
  24980. if (is_computed) {
  24981. JS_FreeAtom(ctx, atom);
  24982. JS_FreeValue(ctx, sp[-2]);
  24983. }
  24984. sp -= 1 + is_computed;
  24985. if (unlikely(ret < 0))
  24986. goto exception;
  24987. }
  24988. BREAK;
  24989. CASE(OP_define_class):
  24990. CASE(OP_define_class_computed):
  24991. {
  24992. int class_flags;
  24993. JSAtom atom;
  24994. atom = get_u32(pc);
  24995. class_flags = pc[4];
  24996. pc += 5;
  24997. if (js_op_define_class(ctx, sp, atom, class_flags,
  24998. var_refs, sf,
  24999. (opcode == OP_define_class_computed)) < 0)
  25000. goto exception;
  25001. }
  25002. BREAK;
  25003. CASE(OP_get_array_el):
  25004. {
  25005. JSValue val;
  25006. sf->cur_pc = pc;
  25007. val = JS_GetPropertyValue(ctx, sp[-2], sp[-1]);
  25008. JS_FreeValue(ctx, sp[-2]);
  25009. sp[-2] = val;
  25010. sp--;
  25011. if (unlikely(JS_IsException(val)))
  25012. goto exception;
  25013. }
  25014. BREAK;
  25015. CASE(OP_get_array_el2):
  25016. {
  25017. JSValue val;
  25018. sf->cur_pc = pc;
  25019. val = JS_GetPropertyValue(ctx, sp[-2], sp[-1]);
  25020. sp[-1] = val;
  25021. if (unlikely(JS_IsException(val)))
  25022. goto exception;
  25023. }
  25024. BREAK;
  25025. CASE(OP_get_ref_value):
  25026. {
  25027. JSValue val;
  25028. sf->cur_pc = pc;
  25029. if (unlikely(JS_IsUndefined(sp[-2]))) {
  25030. JSAtom atom = JS_ValueToAtom(ctx, sp[-1]);
  25031. if (atom != JS_ATOM_NULL) {
  25032. JS_ThrowReferenceErrorNotDefined(ctx, atom);
  25033. JS_FreeAtom(ctx, atom);
  25034. }
  25035. goto exception;
  25036. }
  25037. val = JS_GetPropertyValue(ctx, sp[-2],
  25038. js_dup(sp[-1]));
  25039. if (unlikely(JS_IsException(val)))
  25040. goto exception;
  25041. sp[0] = val;
  25042. sp++;
  25043. }
  25044. BREAK;
  25045. CASE(OP_get_super_value):
  25046. {
  25047. JSValue val;
  25048. JSAtom atom;
  25049. sf->cur_pc = pc;
  25050. atom = JS_ValueToAtom(ctx, sp[-1]);
  25051. if (unlikely(atom == JS_ATOM_NULL))
  25052. goto exception;
  25053. val = JS_GetPropertyInternal(ctx, sp[-2], atom, sp[-3], false);
  25054. JS_FreeAtom(ctx, atom);
  25055. if (unlikely(JS_IsException(val)))
  25056. goto exception;
  25057. JS_FreeValue(ctx, sp[-1]);
  25058. JS_FreeValue(ctx, sp[-2]);
  25059. JS_FreeValue(ctx, sp[-3]);
  25060. sp[-3] = val;
  25061. sp -= 2;
  25062. }
  25063. BREAK;
  25064. CASE(OP_put_array_el):
  25065. {
  25066. int ret;
  25067. sf->cur_pc = pc;
  25068. ret = JS_SetPropertyValue(ctx, sp[-3], sp[-2], sp[-1], JS_PROP_THROW_STRICT);
  25069. JS_FreeValue(ctx, sp[-3]);
  25070. sp -= 3;
  25071. if (unlikely(ret < 0))
  25072. goto exception;
  25073. }
  25074. BREAK;
  25075. CASE(OP_put_ref_value):
  25076. {
  25077. int ret, flags;
  25078. sf->cur_pc = pc;
  25079. flags = JS_PROP_THROW_STRICT;
  25080. if (unlikely(JS_IsUndefined(sp[-3]))) {
  25081. if (is_strict_mode(ctx)) {
  25082. JSAtom atom = JS_ValueToAtom(ctx, sp[-2]);
  25083. if (atom != JS_ATOM_NULL) {
  25084. JS_ThrowReferenceErrorNotDefined(ctx, atom);
  25085. JS_FreeAtom(ctx, atom);
  25086. }
  25087. goto exception;
  25088. } else {
  25089. sp[-3] = js_dup(ctx->global_obj);
  25090. }
  25091. } else {
  25092. if (is_strict_mode(ctx))
  25093. flags |= JS_PROP_NO_ADD;
  25094. }
  25095. ret = JS_SetPropertyValue(ctx, sp[-3], sp[-2], sp[-1], flags);
  25096. JS_FreeValue(ctx, sp[-3]);
  25097. sp -= 3;
  25098. if (unlikely(ret < 0))
  25099. goto exception;
  25100. }
  25101. BREAK;
  25102. CASE(OP_put_super_value):
  25103. {
  25104. int ret;
  25105. JSAtom atom;
  25106. sf->cur_pc = pc;
  25107. if (JS_VALUE_GET_TAG(sp[-3]) != JS_TAG_OBJECT) {
  25108. JS_ThrowTypeErrorNotAnObject(ctx);
  25109. goto exception;
  25110. }
  25111. atom = JS_ValueToAtom(ctx, sp[-2]);
  25112. if (unlikely(atom == JS_ATOM_NULL))
  25113. goto exception;
  25114. ret = JS_SetPropertyInternal2(ctx,
  25115. sp[-3], atom,
  25116. sp[-1], sp[-4],
  25117. JS_PROP_THROW_STRICT);
  25118. JS_FreeAtom(ctx, atom);
  25119. JS_FreeValue(ctx, sp[-4]);
  25120. JS_FreeValue(ctx, sp[-3]);
  25121. JS_FreeValue(ctx, sp[-2]);
  25122. sp -= 4;
  25123. if (ret < 0)
  25124. goto exception;
  25125. }
  25126. BREAK;
  25127. CASE(OP_define_array_el):
  25128. {
  25129. int ret;
  25130. ret = JS_DefinePropertyValueValue(ctx, sp[-3], js_dup(sp[-2]), sp[-1],
  25131. JS_PROP_C_W_E | JS_PROP_THROW);
  25132. sp -= 1;
  25133. if (unlikely(ret < 0))
  25134. goto exception;
  25135. }
  25136. BREAK;
  25137. CASE(OP_append): /* array pos enumobj -- array pos */
  25138. {
  25139. sf->cur_pc = pc;
  25140. if (js_append_enumerate(ctx, sp))
  25141. goto exception;
  25142. JS_FreeValue(ctx, *--sp);
  25143. }
  25144. BREAK;
  25145. CASE(OP_copy_data_properties): /* target source excludeList */
  25146. {
  25147. /* stack offsets (-1 based):
  25148. 2 bits for target,
  25149. 3 bits for source,
  25150. 2 bits for exclusionList */
  25151. int mask;
  25152. mask = *pc++;
  25153. sf->cur_pc = pc;
  25154. if (JS_CopyDataProperties(ctx, sp[-1 - (mask & 3)],
  25155. sp[-1 - ((mask >> 2) & 7)],
  25156. sp[-1 - ((mask >> 5) & 7)], 0))
  25157. goto exception;
  25158. }
  25159. BREAK;
  25160. CASE(OP_add):
  25161. {
  25162. JSValue op1, op2;
  25163. op1 = sp[-2];
  25164. op2 = sp[-1];
  25165. if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {
  25166. int64_t r;
  25167. r = (int64_t)JS_VALUE_GET_INT(op1) + JS_VALUE_GET_INT(op2);
  25168. if (unlikely((int)r != r))
  25169. goto add_slow;
  25170. sp[-2] = js_int32(r);
  25171. sp--;
  25172. } else if (JS_VALUE_IS_BOTH_FLOAT(op1, op2)) {
  25173. sp[-2] = js_float64(JS_VALUE_GET_FLOAT64(op1) +
  25174. JS_VALUE_GET_FLOAT64(op2));
  25175. sp--;
  25176. } else {
  25177. add_slow:
  25178. sf->cur_pc = pc;
  25179. if (js_add_slow(ctx, sp))
  25180. goto exception;
  25181. sp--;
  25182. }
  25183. }
  25184. BREAK;
  25185. CASE(OP_add_loc):
  25186. {
  25187. JSValue *pv;
  25188. int idx;
  25189. idx = *pc;
  25190. pc += 1;
  25191. pv = &var_buf[idx];
  25192. if (likely(JS_VALUE_IS_BOTH_INT(*pv, sp[-1]))) {
  25193. int64_t r;
  25194. r = (int64_t)JS_VALUE_GET_INT(*pv) +
  25195. JS_VALUE_GET_INT(sp[-1]);
  25196. if (unlikely((int)r != r))
  25197. goto add_loc_slow;
  25198. *pv = js_int32(r);
  25199. sp--;
  25200. } else if (JS_VALUE_GET_TAG(*pv) == JS_TAG_STRING) {
  25201. JSValue op1;
  25202. op1 = sp[-1];
  25203. sp--;
  25204. sf->cur_pc = pc;
  25205. op1 = JS_ToPrimitiveFree(ctx, op1, HINT_NONE);
  25206. if (JS_IsException(op1))
  25207. goto exception;
  25208. op1 = JS_ConcatString(ctx, js_dup(*pv), op1);
  25209. if (JS_IsException(op1))
  25210. goto exception;
  25211. set_value(ctx, pv, op1);
  25212. } else {
  25213. JSValue ops[2];
  25214. add_loc_slow:
  25215. /* In case of exception, js_add_slow frees ops[0]
  25216. and ops[1], so we must duplicate *pv */
  25217. sf->cur_pc = pc;
  25218. ops[0] = js_dup(*pv);
  25219. ops[1] = sp[-1];
  25220. sp--;
  25221. if (js_add_slow(ctx, ops + 2))
  25222. goto exception;
  25223. set_value(ctx, pv, ops[0]);
  25224. }
  25225. }
  25226. BREAK;
  25227. CASE(OP_sub):
  25228. {
  25229. JSValue op1, op2;
  25230. op1 = sp[-2];
  25231. op2 = sp[-1];
  25232. if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {
  25233. int64_t r;
  25234. r = (int64_t)JS_VALUE_GET_INT(op1) - JS_VALUE_GET_INT(op2);
  25235. if (unlikely((int)r != r))
  25236. goto binary_arith_slow;
  25237. sp[-2] = js_int32(r);
  25238. sp--;
  25239. } else if (JS_VALUE_IS_BOTH_FLOAT(op1, op2)) {
  25240. sp[-2] = js_float64(JS_VALUE_GET_FLOAT64(op1) -
  25241. JS_VALUE_GET_FLOAT64(op2));
  25242. sp--;
  25243. } else {
  25244. goto binary_arith_slow;
  25245. }
  25246. }
  25247. BREAK;
  25248. CASE(OP_mul):
  25249. {
  25250. JSValue op1, op2;
  25251. double d;
  25252. op1 = sp[-2];
  25253. op2 = sp[-1];
  25254. if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {
  25255. int32_t v1, v2;
  25256. int64_t r;
  25257. v1 = JS_VALUE_GET_INT(op1);
  25258. v2 = JS_VALUE_GET_INT(op2);
  25259. r = (int64_t)v1 * v2;
  25260. if (unlikely((int)r != r)) {
  25261. d = (double)r;
  25262. goto mul_fp_res;
  25263. }
  25264. /* need to test zero case for -0 result */
  25265. if (unlikely(r == 0 && (v1 | v2) < 0)) {
  25266. d = -0.0;
  25267. goto mul_fp_res;
  25268. }
  25269. sp[-2] = js_int32(r);
  25270. sp--;
  25271. } else if (JS_VALUE_IS_BOTH_FLOAT(op1, op2)) {
  25272. d = JS_VALUE_GET_FLOAT64(op1) * JS_VALUE_GET_FLOAT64(op2);
  25273. mul_fp_res:
  25274. sp[-2] = js_float64(d);
  25275. sp--;
  25276. } else {
  25277. goto binary_arith_slow;
  25278. }
  25279. }
  25280. BREAK;
  25281. CASE(OP_div):
  25282. {
  25283. JSValue op1, op2;
  25284. op1 = sp[-2];
  25285. op2 = sp[-1];
  25286. if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {
  25287. int v1, v2;
  25288. v1 = JS_VALUE_GET_INT(op1);
  25289. v2 = JS_VALUE_GET_INT(op2);
  25290. sp[-2] = js_number((double)v1 / (double)v2);
  25291. sp--;
  25292. } else {
  25293. goto binary_arith_slow;
  25294. }
  25295. }
  25296. BREAK;
  25297. CASE(OP_mod):
  25298. {
  25299. JSValue op1, op2;
  25300. op1 = sp[-2];
  25301. op2 = sp[-1];
  25302. if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {
  25303. int v1, v2, r;
  25304. v1 = JS_VALUE_GET_INT(op1);
  25305. v2 = JS_VALUE_GET_INT(op2);
  25306. /* We must avoid v2 = 0, v1 = INT32_MIN and v2 =
  25307. -1 and the cases where the result is -0. */
  25308. if (unlikely(v1 < 0 || v2 <= 0))
  25309. goto binary_arith_slow;
  25310. r = v1 % v2;
  25311. sp[-2] = js_int32(r);
  25312. sp--;
  25313. } else {
  25314. goto binary_arith_slow;
  25315. }
  25316. }
  25317. BREAK;
  25318. CASE(OP_pow):
  25319. binary_arith_slow:
  25320. sf->cur_pc = pc;
  25321. if (js_binary_arith_slow(ctx, sp, opcode))
  25322. goto exception;
  25323. sp--;
  25324. BREAK;
  25325. CASE(OP_plus):
  25326. {
  25327. JSValue op1;
  25328. uint32_t tag;
  25329. op1 = sp[-1];
  25330. tag = JS_VALUE_GET_TAG(op1);
  25331. if (tag == JS_TAG_INT || JS_TAG_IS_FLOAT64(tag)) {
  25332. } else {
  25333. sf->cur_pc = pc;
  25334. if (js_unary_arith_slow(ctx, sp, opcode))
  25335. goto exception;
  25336. }
  25337. }
  25338. BREAK;
  25339. CASE(OP_neg):
  25340. {
  25341. JSValue op1;
  25342. uint32_t tag;
  25343. int val;
  25344. double d;
  25345. op1 = sp[-1];
  25346. tag = JS_VALUE_GET_TAG(op1);
  25347. if (tag == JS_TAG_INT) {
  25348. val = JS_VALUE_GET_INT(op1);
  25349. /* Note: -0 cannot be expressed as integer */
  25350. if (unlikely(val == 0)) {
  25351. d = -0.0;
  25352. goto neg_fp_res;
  25353. }
  25354. if (unlikely(val == INT32_MIN)) {
  25355. d = -(double)val;
  25356. goto neg_fp_res;
  25357. }
  25358. sp[-1] = js_int32(-val);
  25359. } else if (JS_TAG_IS_FLOAT64(tag)) {
  25360. d = -JS_VALUE_GET_FLOAT64(op1);
  25361. neg_fp_res:
  25362. sp[-1] = js_float64(d);
  25363. } else {
  25364. sf->cur_pc = pc;
  25365. if (js_unary_arith_slow(ctx, sp, opcode))
  25366. goto exception;
  25367. }
  25368. }
  25369. BREAK;
  25370. CASE(OP_inc):
  25371. {
  25372. JSValue op1;
  25373. int val;
  25374. op1 = sp[-1];
  25375. if (JS_VALUE_GET_TAG(op1) == JS_TAG_INT) {
  25376. val = JS_VALUE_GET_INT(op1);
  25377. if (unlikely(val == INT32_MAX))
  25378. goto inc_slow;
  25379. sp[-1] = js_int32(val + 1);
  25380. } else {
  25381. inc_slow:
  25382. sf->cur_pc = pc;
  25383. if (js_unary_arith_slow(ctx, sp, opcode))
  25384. goto exception;
  25385. }
  25386. }
  25387. BREAK;
  25388. CASE(OP_dec):
  25389. {
  25390. JSValue op1;
  25391. int val;
  25392. op1 = sp[-1];
  25393. if (JS_VALUE_GET_TAG(op1) == JS_TAG_INT) {
  25394. val = JS_VALUE_GET_INT(op1);
  25395. if (unlikely(val == INT32_MIN))
  25396. goto dec_slow;
  25397. sp[-1] = js_int32(val - 1);
  25398. } else {
  25399. dec_slow:
  25400. sf->cur_pc = pc;
  25401. if (js_unary_arith_slow(ctx, sp, opcode))
  25402. goto exception;
  25403. }
  25404. }
  25405. BREAK;
  25406. CASE(OP_post_inc):
  25407. CASE(OP_post_dec):
  25408. sf->cur_pc = pc;
  25409. if (js_post_inc_slow(ctx, sp, opcode))
  25410. goto exception;
  25411. sp++;
  25412. BREAK;
  25413. CASE(OP_inc_loc):
  25414. {
  25415. JSValue op1;
  25416. int val;
  25417. int idx;
  25418. idx = *pc;
  25419. pc += 1;
  25420. op1 = var_buf[idx];
  25421. if (JS_VALUE_GET_TAG(op1) == JS_TAG_INT) {
  25422. val = JS_VALUE_GET_INT(op1);
  25423. if (unlikely(val == INT32_MAX))
  25424. goto inc_loc_slow;
  25425. var_buf[idx] = js_int32(val + 1);
  25426. } else {
  25427. inc_loc_slow:
  25428. sf->cur_pc = pc;
  25429. /* must duplicate otherwise the variable value may
  25430. be destroyed before JS code accesses it */
  25431. op1 = js_dup(op1);
  25432. if (js_unary_arith_slow(ctx, &op1 + 1, OP_inc))
  25433. goto exception;
  25434. set_value(ctx, &var_buf[idx], op1);
  25435. }
  25436. }
  25437. BREAK;
  25438. CASE(OP_dec_loc):
  25439. {
  25440. JSValue op1;
  25441. int val;
  25442. int idx;
  25443. idx = *pc;
  25444. pc += 1;
  25445. op1 = var_buf[idx];
  25446. if (JS_VALUE_GET_TAG(op1) == JS_TAG_INT) {
  25447. val = JS_VALUE_GET_INT(op1);
  25448. if (unlikely(val == INT32_MIN))
  25449. goto dec_loc_slow;
  25450. var_buf[idx] = js_int32(val - 1);
  25451. } else {
  25452. dec_loc_slow:
  25453. sf->cur_pc = pc;
  25454. /* must duplicate otherwise the variable value may
  25455. be destroyed before JS code accesses it */
  25456. op1 = js_dup(op1);
  25457. if (js_unary_arith_slow(ctx, &op1 + 1, OP_dec))
  25458. goto exception;
  25459. set_value(ctx, &var_buf[idx], op1);
  25460. }
  25461. }
  25462. BREAK;
  25463. CASE(OP_not):
  25464. {
  25465. JSValue op1;
  25466. op1 = sp[-1];
  25467. if (JS_VALUE_GET_TAG(op1) == JS_TAG_INT) {
  25468. sp[-1] = js_int32(~JS_VALUE_GET_INT(op1));
  25469. } else {
  25470. sf->cur_pc = pc;
  25471. if (js_not_slow(ctx, sp))
  25472. goto exception;
  25473. }
  25474. }
  25475. BREAK;
  25476. CASE(OP_shl):
  25477. {
  25478. JSValue op1, op2;
  25479. op1 = sp[-2];
  25480. op2 = sp[-1];
  25481. if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {
  25482. uint32_t v1, v2;
  25483. v1 = JS_VALUE_GET_INT(op1);
  25484. v2 = JS_VALUE_GET_INT(op2) & 0x1f;
  25485. sp[-2] = js_int32(v1 << v2);
  25486. sp--;
  25487. } else {
  25488. sf->cur_pc = pc;
  25489. if (js_binary_logic_slow(ctx, sp, opcode))
  25490. goto exception;
  25491. sp--;
  25492. }
  25493. }
  25494. BREAK;
  25495. CASE(OP_shr):
  25496. {
  25497. JSValue op1, op2;
  25498. op1 = sp[-2];
  25499. op2 = sp[-1];
  25500. if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {
  25501. uint32_t v2;
  25502. v2 = JS_VALUE_GET_INT(op2);
  25503. v2 &= 0x1f;
  25504. sp[-2] = js_uint32((uint32_t)JS_VALUE_GET_INT(op1) >> v2);
  25505. sp--;
  25506. } else {
  25507. sf->cur_pc = pc;
  25508. if (js_shr_slow(ctx, sp))
  25509. goto exception;
  25510. sp--;
  25511. }
  25512. }
  25513. BREAK;
  25514. CASE(OP_sar):
  25515. {
  25516. JSValue op1, op2;
  25517. op1 = sp[-2];
  25518. op2 = sp[-1];
  25519. if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {
  25520. uint32_t v2;
  25521. v2 = JS_VALUE_GET_INT(op2);
  25522. if (unlikely(v2 > 0x1f)) {
  25523. v2 &= 0x1f;
  25524. }
  25525. sp[-2] = js_int32((int)JS_VALUE_GET_INT(op1) >> v2);
  25526. sp--;
  25527. } else {
  25528. sf->cur_pc = pc;
  25529. if (js_binary_logic_slow(ctx, sp, opcode))
  25530. goto exception;
  25531. sp--;
  25532. }
  25533. }
  25534. BREAK;
  25535. CASE(OP_and):
  25536. {
  25537. JSValue op1, op2;
  25538. op1 = sp[-2];
  25539. op2 = sp[-1];
  25540. if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {
  25541. sp[-2] = js_int32(JS_VALUE_GET_INT(op1) & JS_VALUE_GET_INT(op2));
  25542. sp--;
  25543. } else {
  25544. sf->cur_pc = pc;
  25545. if (js_binary_logic_slow(ctx, sp, opcode))
  25546. goto exception;
  25547. sp--;
  25548. }
  25549. }
  25550. BREAK;
  25551. CASE(OP_or):
  25552. {
  25553. JSValue op1, op2;
  25554. op1 = sp[-2];
  25555. op2 = sp[-1];
  25556. if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {
  25557. sp[-2] = js_int32(JS_VALUE_GET_INT(op1) | JS_VALUE_GET_INT(op2));
  25558. sp--;
  25559. } else {
  25560. sf->cur_pc = pc;
  25561. if (js_binary_logic_slow(ctx, sp, opcode))
  25562. goto exception;
  25563. sp--;
  25564. }
  25565. }
  25566. BREAK;
  25567. CASE(OP_xor):
  25568. {
  25569. JSValue op1, op2;
  25570. op1 = sp[-2];
  25571. op2 = sp[-1];
  25572. if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {
  25573. sp[-2] = js_int32(JS_VALUE_GET_INT(op1) ^ JS_VALUE_GET_INT(op2));
  25574. sp--;
  25575. } else {
  25576. sf->cur_pc = pc;
  25577. if (js_binary_logic_slow(ctx, sp, opcode))
  25578. goto exception;
  25579. sp--;
  25580. }
  25581. }
  25582. BREAK;
  25583. #define OP_CMP(opcode, binary_op, slow_call) \
  25584. CASE(opcode): \
  25585. { \
  25586. JSValue op1, op2; \
  25587. op1 = sp[-2]; \
  25588. op2 = sp[-1]; \
  25589. if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) { \
  25590. sp[-2] = js_bool(JS_VALUE_GET_INT(op1) binary_op JS_VALUE_GET_INT(op2)); \
  25591. sp--; \
  25592. } else { \
  25593. sf->cur_pc = pc; \
  25594. if (slow_call) \
  25595. goto exception; \
  25596. sp--; \
  25597. } \
  25598. } \
  25599. BREAK
  25600. OP_CMP(OP_lt, <, js_relational_slow(ctx, sp, opcode));
  25601. OP_CMP(OP_lte, <=, js_relational_slow(ctx, sp, opcode));
  25602. OP_CMP(OP_gt, >, js_relational_slow(ctx, sp, opcode));
  25603. OP_CMP(OP_gte, >=, js_relational_slow(ctx, sp, opcode));
  25604. OP_CMP(OP_eq, ==, js_eq_slow(ctx, sp, 0));
  25605. OP_CMP(OP_neq, !=, js_eq_slow(ctx, sp, 1));
  25606. OP_CMP(OP_strict_eq, ==, js_strict_eq_slow(ctx, sp, 0));
  25607. OP_CMP(OP_strict_neq, !=, js_strict_eq_slow(ctx, sp, 1));
  25608. CASE(OP_in):
  25609. sf->cur_pc = pc;
  25610. if (js_operator_in(ctx, sp))
  25611. goto exception;
  25612. sp--;
  25613. BREAK;
  25614. CASE(OP_private_in):
  25615. if (js_operator_private_in(ctx, sp))
  25616. goto exception;
  25617. sp--;
  25618. BREAK;
  25619. CASE(OP_instanceof):
  25620. sf->cur_pc = pc;
  25621. if (js_operator_instanceof(ctx, sp))
  25622. goto exception;
  25623. sp--;
  25624. BREAK;
  25625. CASE(OP_typeof):
  25626. {
  25627. JSValue op1;
  25628. JSAtom atom;
  25629. op1 = sp[-1];
  25630. atom = js_operator_typeof(ctx, op1);
  25631. JS_FreeValue(ctx, op1);
  25632. sp[-1] = JS_AtomToString(ctx, atom);
  25633. }
  25634. BREAK;
  25635. CASE(OP_delete):
  25636. sf->cur_pc = pc;
  25637. if (js_operator_delete(ctx, sp))
  25638. goto exception;
  25639. sp--;
  25640. BREAK;
  25641. CASE(OP_delete_var):
  25642. {
  25643. JSAtom atom;
  25644. int ret;
  25645. atom = get_u32(pc);
  25646. pc += 4;
  25647. sf->cur_pc = pc;
  25648. ret = JS_DeleteProperty(ctx, ctx->global_obj, atom, 0);
  25649. if (unlikely(ret < 0))
  25650. goto exception;
  25651. *sp++ = js_bool(ret);
  25652. }
  25653. BREAK;
  25654. CASE(OP_to_object):
  25655. if (JS_VALUE_GET_TAG(sp[-1]) != JS_TAG_OBJECT) {
  25656. sf->cur_pc = pc;
  25657. ret_val = JS_ToObject(ctx, sp[-1]);
  25658. if (JS_IsException(ret_val))
  25659. goto exception;
  25660. JS_FreeValue(ctx, sp[-1]);
  25661. sp[-1] = ret_val;
  25662. }
  25663. BREAK;
  25664. CASE(OP_to_propkey):
  25665. switch (JS_VALUE_GET_TAG(sp[-1])) {
  25666. case JS_TAG_INT:
  25667. case JS_TAG_STRING:
  25668. case JS_TAG_SYMBOL:
  25669. break;
  25670. default:
  25671. sf->cur_pc = pc;
  25672. ret_val = JS_ToPropertyKey(ctx, sp[-1]);
  25673. if (JS_IsException(ret_val))
  25674. goto exception;
  25675. JS_FreeValue(ctx, sp[-1]);
  25676. sp[-1] = ret_val;
  25677. break;
  25678. }
  25679. BREAK;
  25680. CASE(OP_to_propkey2):
  25681. /* must be tested first */
  25682. if (unlikely(JS_IsUndefined(sp[-2]) || JS_IsNull(sp[-2]))) {
  25683. JS_ThrowTypeError(ctx, "value has no property");
  25684. goto exception;
  25685. }
  25686. switch (JS_VALUE_GET_TAG(sp[-1])) {
  25687. case JS_TAG_INT:
  25688. case JS_TAG_STRING:
  25689. case JS_TAG_SYMBOL:
  25690. break;
  25691. default:
  25692. sf->cur_pc = pc;
  25693. ret_val = JS_ToPropertyKey(ctx, sp[-1]);
  25694. if (JS_IsException(ret_val))
  25695. goto exception;
  25696. JS_FreeValue(ctx, sp[-1]);
  25697. sp[-1] = ret_val;
  25698. break;
  25699. }
  25700. BREAK;
  25701. CASE(OP_with_get_var):
  25702. CASE(OP_with_put_var):
  25703. CASE(OP_with_delete_var):
  25704. CASE(OP_with_make_ref):
  25705. CASE(OP_with_get_ref):
  25706. CASE(OP_with_get_ref_undef):
  25707. {
  25708. JSAtom atom;
  25709. int32_t diff;
  25710. JSValue obj, val;
  25711. int ret, is_with;
  25712. atom = get_u32(pc);
  25713. diff = get_u32(pc + 4);
  25714. is_with = pc[8];
  25715. pc += 9;
  25716. sf->cur_pc = pc;
  25717. obj = sp[-1];
  25718. ret = JS_HasProperty(ctx, obj, atom);
  25719. if (unlikely(ret < 0))
  25720. goto exception;
  25721. if (ret) {
  25722. if (is_with) {
  25723. ret = js_has_unscopable(ctx, obj, atom);
  25724. if (unlikely(ret < 0))
  25725. goto exception;
  25726. if (ret)
  25727. goto no_with;
  25728. }
  25729. switch (opcode) {
  25730. case OP_with_get_var:
  25731. val = JS_GetProperty(ctx, obj, atom);
  25732. if (unlikely(JS_IsException(val)))
  25733. goto exception;
  25734. set_value(ctx, &sp[-1], val);
  25735. break;
  25736. case OP_with_put_var:
  25737. /* XXX: check if strict mode */
  25738. ret = JS_SetPropertyInternal(ctx, obj, atom, sp[-2],
  25739. JS_PROP_THROW_STRICT);
  25740. JS_FreeValue(ctx, sp[-1]);
  25741. sp -= 2;
  25742. if (unlikely(ret < 0))
  25743. goto exception;
  25744. break;
  25745. case OP_with_delete_var:
  25746. ret = JS_DeleteProperty(ctx, obj, atom, 0);
  25747. if (unlikely(ret < 0))
  25748. goto exception;
  25749. JS_FreeValue(ctx, sp[-1]);
  25750. sp[-1] = js_bool(ret);
  25751. break;
  25752. case OP_with_make_ref:
  25753. /* produce a pair object/propname on the stack */
  25754. *sp++ = JS_AtomToValue(ctx, atom);
  25755. break;
  25756. case OP_with_get_ref:
  25757. /* produce a pair object/method on the stack */
  25758. val = JS_GetProperty(ctx, obj, atom);
  25759. if (unlikely(JS_IsException(val)))
  25760. goto exception;
  25761. *sp++ = val;
  25762. break;
  25763. case OP_with_get_ref_undef:
  25764. /* produce a pair undefined/function on the stack */
  25765. val = JS_GetProperty(ctx, obj, atom);
  25766. if (unlikely(JS_IsException(val)))
  25767. goto exception;
  25768. JS_FreeValue(ctx, sp[-1]);
  25769. sp[-1] = JS_UNDEFINED;
  25770. *sp++ = val;
  25771. break;
  25772. }
  25773. pc += diff - 5;
  25774. } else {
  25775. no_with:
  25776. /* if not jumping, drop the object argument */
  25777. JS_FreeValue(ctx, sp[-1]);
  25778. sp--;
  25779. }
  25780. }
  25781. BREAK;
  25782. CASE(OP_await):
  25783. ret_val = js_int32(FUNC_RET_AWAIT);
  25784. goto done_generator;
  25785. CASE(OP_yield):
  25786. ret_val = js_int32(FUNC_RET_YIELD);
  25787. goto done_generator;
  25788. CASE(OP_yield_star):
  25789. CASE(OP_async_yield_star):
  25790. ret_val = js_int32(FUNC_RET_YIELD_STAR);
  25791. goto done_generator;
  25792. CASE(OP_return_async):
  25793. CASE(OP_initial_yield):
  25794. ret_val = JS_UNDEFINED;
  25795. goto done_generator;
  25796. CASE(OP_nop):
  25797. BREAK;
  25798. CASE(OP_is_undefined_or_null):
  25799. if (JS_VALUE_GET_TAG(sp[-1]) == JS_TAG_UNDEFINED ||
  25800. JS_VALUE_GET_TAG(sp[-1]) == JS_TAG_NULL) {
  25801. goto set_true;
  25802. } else {
  25803. goto free_and_set_false;
  25804. }
  25805. CASE(OP_is_undefined):
  25806. if (JS_VALUE_GET_TAG(sp[-1]) == JS_TAG_UNDEFINED) {
  25807. goto set_true;
  25808. } else {
  25809. goto free_and_set_false;
  25810. }
  25811. CASE(OP_is_null):
  25812. if (JS_VALUE_GET_TAG(sp[-1]) == JS_TAG_NULL) {
  25813. goto set_true;
  25814. } else {
  25815. goto free_and_set_false;
  25816. }
  25817. /* XXX: could merge to a single opcode */
  25818. CASE(OP_typeof_is_undefined):
  25819. /* different from OP_is_undefined because of isHTMLDDA */
  25820. if (js_operator_typeof(ctx, sp[-1]) == JS_ATOM_undefined) {
  25821. goto free_and_set_true;
  25822. } else {
  25823. goto free_and_set_false;
  25824. }
  25825. CASE(OP_typeof_is_function):
  25826. if (js_operator_typeof(ctx, sp[-1]) == JS_ATOM_function) {
  25827. goto free_and_set_true;
  25828. } else {
  25829. goto free_and_set_false;
  25830. }
  25831. free_and_set_true:
  25832. JS_FreeValue(ctx, sp[-1]);
  25833. set_true:
  25834. sp[-1] = JS_TRUE;
  25835. BREAK;
  25836. free_and_set_false:
  25837. JS_FreeValue(ctx, sp[-1]);
  25838. sp[-1] = JS_FALSE;
  25839. BREAK;
  25840. CASE(OP_invalid):
  25841. DEFAULT:
  25842. JS_ThrowInternalError(ctx, "invalid opcode: pc=%u opcode=0x%02x",
  25843. (int)(pc - b->byte_code_buf - 1), opcode);
  25844. goto exception;
  25845. }
  25846. }
  25847. exception:
  25848. if (needs_backtrace(rt->current_exception)
  25849. || JS_IsUndefined(ctx->error_back_trace)) {
  25850. sf->cur_pc = pc;
  25851. build_backtrace(ctx, rt->current_exception, JS_UNDEFINED,
  25852. NULL, 0, 0, 0);
  25853. }
  25854. if (!JS_IsUncatchableError(ctx, rt->current_exception)) {
  25855. while (sp > stack_buf) {
  25856. JSValue val = *--sp;
  25857. JS_FreeValue(ctx, val);
  25858. if (JS_VALUE_GET_TAG(val) == JS_TAG_CATCH_OFFSET) {
  25859. int pos = JS_VALUE_GET_INT(val);
  25860. if (pos == 0) {
  25861. /* enumerator: close it with a throw */
  25862. JS_FreeValue(ctx, sp[-1]); /* drop the next method */
  25863. sp--;
  25864. JS_IteratorClose(ctx, sp[-1], true);
  25865. } else {
  25866. *sp++ = rt->current_exception;
  25867. rt->current_exception = JS_UNINITIALIZED;
  25868. JS_FreeValueRT(rt, ctx->error_back_trace);
  25869. ctx->error_back_trace = JS_UNDEFINED;
  25870. pc = b->byte_code_buf + pos;
  25871. goto restart;
  25872. }
  25873. }
  25874. }
  25875. }
  25876. ret_val = JS_EXCEPTION;
  25877. /* the local variables are freed by the caller in the generator
  25878. case. Hence the label 'done' should never be reached in a
  25879. generator function. */
  25880. if (b->func_kind != JS_FUNC_NORMAL) {
  25881. done_generator:
  25882. sf->cur_pc = pc;
  25883. sf->cur_sp = sp;
  25884. } else {
  25885. done:
  25886. if (unlikely(!list_empty(&sf->var_ref_list))) {
  25887. /* variable references reference the stack: must close them */
  25888. close_var_refs(rt, sf);
  25889. }
  25890. /* free the local variables and stack */
  25891. for(pval = local_buf; pval < sp; pval++) {
  25892. JS_FreeValue(ctx, *pval);
  25893. }
  25894. }
  25895. rt->current_stack_frame = sf->prev_frame;
  25896. return ret_val;
  25897. }
  25898. JSValue JS_Call(JSContext *ctx, JSValueConst func_obj, JSValueConst this_obj,
  25899. int argc, JSValueConst *argv)
  25900. {
  25901. return JS_CallInternal(ctx, func_obj, this_obj, JS_UNDEFINED,
  25902. argc, argv, JS_CALL_FLAG_COPY_ARGV);
  25903. }
  25904. static JSValue JS_CallFree(JSContext *ctx, JSValue func_obj, JSValueConst this_obj,
  25905. int argc, JSValueConst *argv)
  25906. {
  25907. JSValue res = JS_CallInternal(ctx, func_obj, this_obj, JS_UNDEFINED,
  25908. argc, argv, JS_CALL_FLAG_COPY_ARGV);
  25909. JS_FreeValue(ctx, func_obj);
  25910. return res;
  25911. }
  25912. /* warning: the refcount of the context is not incremented. Return
  25913. NULL in case of exception (case of revoked proxy only) */
  25914. static JSContext *JS_GetFunctionRealm(JSContext *ctx, JSValueConst func_obj)
  25915. {
  25916. JSObject *p;
  25917. JSContext *realm;
  25918. if (JS_VALUE_GET_TAG(func_obj) != JS_TAG_OBJECT)
  25919. return ctx;
  25920. p = JS_VALUE_GET_OBJ(func_obj);
  25921. switch(p->class_id) {
  25922. case JS_CLASS_C_FUNCTION:
  25923. realm = p->u.cfunc.realm;
  25924. break;
  25925. case JS_CLASS_BYTECODE_FUNCTION:
  25926. case JS_CLASS_GENERATOR_FUNCTION:
  25927. case JS_CLASS_ASYNC_FUNCTION:
  25928. case JS_CLASS_ASYNC_GENERATOR_FUNCTION:
  25929. {
  25930. JSFunctionBytecode *b;
  25931. b = p->u.func.function_bytecode;
  25932. realm = b->realm;
  25933. }
  25934. break;
  25935. case JS_CLASS_PROXY:
  25936. {
  25937. JSProxyData *s = p->u.opaque;
  25938. if (!s)
  25939. return ctx;
  25940. if (s->is_revoked) {
  25941. JS_ThrowTypeErrorRevokedProxy(ctx);
  25942. return NULL;
  25943. } else {
  25944. realm = JS_GetFunctionRealm(ctx, s->target);
  25945. }
  25946. }
  25947. break;
  25948. case JS_CLASS_BOUND_FUNCTION:
  25949. {
  25950. JSBoundFunction *bf = p->u.bound_function;
  25951. realm = JS_GetFunctionRealm(ctx, bf->func_obj);
  25952. }
  25953. break;
  25954. default:
  25955. realm = ctx;
  25956. break;
  25957. }
  25958. return realm;
  25959. }
  25960. static JSValue js_create_from_ctor(JSContext *ctx, JSValueConst ctor,
  25961. int class_id)
  25962. {
  25963. JSValue proto, obj;
  25964. JSContext *realm;
  25965. if (JS_IsUndefined(ctor)) {
  25966. proto = js_dup(ctx->class_proto[class_id]);
  25967. } else {
  25968. proto = JS_GetProperty(ctx, ctor, JS_ATOM_prototype);
  25969. if (JS_IsException(proto))
  25970. return proto;
  25971. if (!JS_IsObject(proto)) {
  25972. JS_FreeValue(ctx, proto);
  25973. realm = JS_GetFunctionRealm(ctx, ctor);
  25974. if (!realm)
  25975. return JS_EXCEPTION;
  25976. proto = js_dup(realm->class_proto[class_id]);
  25977. }
  25978. }
  25979. obj = JS_NewObjectProtoClass(ctx, proto, class_id);
  25980. JS_FreeValue(ctx, proto);
  25981. return obj;
  25982. }
  25983. /* argv[] is modified if (flags & JS_CALL_FLAG_COPY_ARGV) = 0. */
  25984. static JSValue JS_CallConstructorInternal(JSContext *ctx,
  25985. JSValueConst func_obj,
  25986. JSValueConst new_target,
  25987. int argc, JSValueConst *argv,
  25988. int flags)
  25989. {
  25990. JSObject *p;
  25991. JSFunctionBytecode *b;
  25992. if (js_poll_interrupts(ctx))
  25993. return JS_EXCEPTION;
  25994. flags |= JS_CALL_FLAG_CONSTRUCTOR;
  25995. if (unlikely(JS_VALUE_GET_TAG(func_obj) != JS_TAG_OBJECT))
  25996. goto not_a_function;
  25997. p = JS_VALUE_GET_OBJ(func_obj);
  25998. if (unlikely(!p->is_constructor))
  25999. return JS_ThrowTypeError(ctx, "not a constructor");
  26000. if (unlikely(p->class_id != JS_CLASS_BYTECODE_FUNCTION)) {
  26001. JSClassCall *call_func;
  26002. call_func = ctx->rt->class_array[p->class_id].call;
  26003. if (!call_func) {
  26004. not_a_function:
  26005. return JS_ThrowTypeErrorNotAFunction(ctx);
  26006. }
  26007. return call_func(ctx, func_obj, new_target, argc,
  26008. argv, flags);
  26009. }
  26010. b = p->u.func.function_bytecode;
  26011. if (b->is_derived_class_constructor) {
  26012. return JS_CallInternal(ctx, func_obj, JS_UNDEFINED, new_target, argc, argv, flags);
  26013. } else {
  26014. JSValue obj, ret;
  26015. /* legacy constructor behavior */
  26016. obj = js_create_from_ctor(ctx, new_target, JS_CLASS_OBJECT);
  26017. if (JS_IsException(obj))
  26018. return JS_EXCEPTION;
  26019. ret = JS_CallInternal(ctx, func_obj, obj, new_target, argc, argv, flags);
  26020. if (JS_VALUE_GET_TAG(ret) == JS_TAG_OBJECT ||
  26021. JS_IsException(ret)) {
  26022. JS_FreeValue(ctx, obj);
  26023. return ret;
  26024. } else {
  26025. JS_FreeValue(ctx, ret);
  26026. return obj;
  26027. }
  26028. }
  26029. }
  26030. JSValue JS_CallConstructor2(JSContext *ctx, JSValueConst func_obj,
  26031. JSValueConst new_target,
  26032. int argc, JSValueConst *argv)
  26033. {
  26034. return JS_CallConstructorInternal(ctx, func_obj, new_target,
  26035. argc, argv,
  26036. JS_CALL_FLAG_COPY_ARGV);
  26037. }
  26038. JSValue JS_CallConstructor(JSContext *ctx, JSValueConst func_obj,
  26039. int argc, JSValueConst *argv)
  26040. {
  26041. return JS_CallConstructorInternal(ctx, func_obj, func_obj,
  26042. argc, argv,
  26043. JS_CALL_FLAG_COPY_ARGV);
  26044. }
  26045. JSValue JS_Invoke(JSContext *ctx, JSValueConst this_val, JSAtom atom,
  26046. int argc, JSValueConst *argv)
  26047. {
  26048. JSValue func_obj;
  26049. func_obj = JS_GetProperty(ctx, this_val, atom);
  26050. if (JS_IsException(func_obj))
  26051. return func_obj;
  26052. return JS_CallFree(ctx, func_obj, this_val, argc, argv);
  26053. }
  26054. static JSValue JS_InvokeFree(JSContext *ctx, JSValue this_val, JSAtom atom,
  26055. int argc, JSValueConst *argv)
  26056. {
  26057. JSValue res = JS_Invoke(ctx, this_val, atom, argc, argv);
  26058. JS_FreeValue(ctx, this_val);
  26059. return res;
  26060. }
  26061. /* JSAsyncFunctionState (used by generator and async functions) */
  26062. static __exception int async_func_init(JSContext *ctx, JSAsyncFunctionState *s,
  26063. JSValueConst func_obj,
  26064. JSValueConst this_obj,
  26065. int argc, JSValueConst *argv)
  26066. {
  26067. JSObject *p;
  26068. JSFunctionBytecode *b;
  26069. JSStackFrame *sf;
  26070. int local_count, i, arg_buf_len, n;
  26071. sf = &s->frame;
  26072. init_list_head(&sf->var_ref_list);
  26073. p = JS_VALUE_GET_OBJ(func_obj);
  26074. b = p->u.func.function_bytecode;
  26075. sf->is_strict_mode = b->is_strict_mode;
  26076. sf->cur_pc = b->byte_code_buf;
  26077. arg_buf_len = max_int(b->arg_count, argc);
  26078. local_count = arg_buf_len + b->var_count + b->stack_size;
  26079. sf->arg_buf = js_malloc(ctx, sizeof(JSValue) * max_int(local_count, 1));
  26080. if (!sf->arg_buf)
  26081. return -1;
  26082. sf->cur_func = js_dup(func_obj);
  26083. s->this_val = js_dup(this_obj);
  26084. s->argc = argc;
  26085. sf->arg_count = arg_buf_len;
  26086. sf->var_buf = sf->arg_buf + arg_buf_len;
  26087. sf->cur_sp = sf->var_buf + b->var_count;
  26088. for(i = 0; i < argc; i++)
  26089. sf->arg_buf[i] = js_dup(argv[i]);
  26090. n = arg_buf_len + b->var_count;
  26091. for(i = argc; i < n; i++)
  26092. sf->arg_buf[i] = JS_UNDEFINED;
  26093. return 0;
  26094. }
  26095. static void async_func_mark(JSRuntime *rt, JSAsyncFunctionState *s,
  26096. JS_MarkFunc *mark_func)
  26097. {
  26098. JSStackFrame *sf;
  26099. JSValue *sp;
  26100. sf = &s->frame;
  26101. JS_MarkValue(rt, sf->cur_func, mark_func);
  26102. JS_MarkValue(rt, s->this_val, mark_func);
  26103. if (sf->cur_sp) {
  26104. /* if the function is running, cur_sp is not known so we
  26105. cannot mark the stack. Marking the variables is not needed
  26106. because a running function cannot be part of a removable
  26107. cycle */
  26108. for(sp = sf->arg_buf; sp < sf->cur_sp; sp++)
  26109. JS_MarkValue(rt, *sp, mark_func);
  26110. }
  26111. }
  26112. static void async_func_free(JSRuntime *rt, JSAsyncFunctionState *s)
  26113. {
  26114. JSStackFrame *sf;
  26115. JSValue *sp;
  26116. sf = &s->frame;
  26117. /* close the closure variables. */
  26118. close_var_refs(rt, sf);
  26119. if (sf->arg_buf) {
  26120. /* cannot free the function if it is running */
  26121. assert(sf->cur_sp != NULL);
  26122. for(sp = sf->arg_buf; sp < sf->cur_sp; sp++) {
  26123. JS_FreeValueRT(rt, *sp);
  26124. }
  26125. js_free_rt(rt, sf->arg_buf);
  26126. }
  26127. JS_FreeValueRT(rt, sf->cur_func);
  26128. JS_FreeValueRT(rt, s->this_val);
  26129. }
  26130. static JSValue async_func_resume(JSContext *ctx, JSAsyncFunctionState *s)
  26131. {
  26132. JSValue func_obj;
  26133. if (js_check_stack_overflow(ctx->rt, 0))
  26134. return JS_ThrowStackOverflow(ctx);
  26135. /* the tag does not matter provided it is not an object */
  26136. func_obj = JS_MKPTR(JS_TAG_INT, s);
  26137. return JS_CallInternal(ctx, func_obj, s->this_val, JS_UNDEFINED,
  26138. s->argc, vc(s->frame.arg_buf),
  26139. JS_CALL_FLAG_GENERATOR);
  26140. }
  26141. /* Generators */
  26142. typedef enum JSGeneratorStateEnum {
  26143. JS_GENERATOR_STATE_SUSPENDED_START,
  26144. JS_GENERATOR_STATE_SUSPENDED_YIELD,
  26145. JS_GENERATOR_STATE_SUSPENDED_YIELD_STAR,
  26146. JS_GENERATOR_STATE_EXECUTING,
  26147. JS_GENERATOR_STATE_COMPLETED,
  26148. } JSGeneratorStateEnum;
  26149. typedef struct JSGeneratorData {
  26150. JSGeneratorStateEnum state;
  26151. JSAsyncFunctionState func_state;
  26152. } JSGeneratorData;
  26153. static void free_generator_stack_rt(JSRuntime *rt, JSGeneratorData *s)
  26154. {
  26155. if (s->state == JS_GENERATOR_STATE_COMPLETED)
  26156. return;
  26157. async_func_free(rt, &s->func_state);
  26158. s->state = JS_GENERATOR_STATE_COMPLETED;
  26159. }
  26160. static void js_generator_finalizer(JSRuntime *rt, JSValueConst obj)
  26161. {
  26162. JSGeneratorData *s = JS_GetOpaque(obj, JS_CLASS_GENERATOR);
  26163. if (s) {
  26164. free_generator_stack_rt(rt, s);
  26165. js_free_rt(rt, s);
  26166. }
  26167. }
  26168. static void free_generator_stack(JSContext *ctx, JSGeneratorData *s)
  26169. {
  26170. free_generator_stack_rt(ctx->rt, s);
  26171. }
  26172. static void js_generator_mark(JSRuntime *rt, JSValueConst val,
  26173. JS_MarkFunc *mark_func)
  26174. {
  26175. JSObject *p = JS_VALUE_GET_OBJ(val);
  26176. JSGeneratorData *s = p->u.generator_data;
  26177. if (!s || s->state == JS_GENERATOR_STATE_COMPLETED)
  26178. return;
  26179. async_func_mark(rt, &s->func_state, mark_func);
  26180. }
  26181. /* XXX: use enum */
  26182. #define GEN_MAGIC_NEXT 0
  26183. #define GEN_MAGIC_RETURN 1
  26184. #define GEN_MAGIC_THROW 2
  26185. static JSValue js_generator_next(JSContext *ctx, JSValueConst this_val,
  26186. int argc, JSValueConst *argv,
  26187. int *pdone, int magic)
  26188. {
  26189. JSGeneratorData *s = JS_GetOpaque(this_val, JS_CLASS_GENERATOR);
  26190. JSStackFrame *sf;
  26191. JSValue ret, func_ret;
  26192. *pdone = true;
  26193. if (!s)
  26194. return JS_ThrowTypeError(ctx, "not a generator");
  26195. sf = &s->func_state.frame;
  26196. switch(s->state) {
  26197. default:
  26198. case JS_GENERATOR_STATE_SUSPENDED_START:
  26199. if (magic == GEN_MAGIC_NEXT) {
  26200. goto exec_no_arg;
  26201. } else {
  26202. free_generator_stack(ctx, s);
  26203. goto done;
  26204. }
  26205. break;
  26206. case JS_GENERATOR_STATE_SUSPENDED_YIELD_STAR:
  26207. case JS_GENERATOR_STATE_SUSPENDED_YIELD:
  26208. /* cur_sp[-1] was set to JS_UNDEFINED in the previous call */
  26209. ret = js_dup(argv[0]);
  26210. if (magic == GEN_MAGIC_THROW &&
  26211. s->state == JS_GENERATOR_STATE_SUSPENDED_YIELD) {
  26212. JS_Throw(ctx, ret);
  26213. s->func_state.throw_flag = true;
  26214. } else {
  26215. sf->cur_sp[-1] = ret;
  26216. sf->cur_sp[0] = js_int32(magic);
  26217. sf->cur_sp++;
  26218. exec_no_arg:
  26219. s->func_state.throw_flag = false;
  26220. }
  26221. s->state = JS_GENERATOR_STATE_EXECUTING;
  26222. func_ret = async_func_resume(ctx, &s->func_state);
  26223. s->state = JS_GENERATOR_STATE_SUSPENDED_YIELD;
  26224. if (JS_IsException(func_ret)) {
  26225. /* finalize the execution in case of exception */
  26226. free_generator_stack(ctx, s);
  26227. return func_ret;
  26228. }
  26229. if (JS_VALUE_GET_TAG(func_ret) == JS_TAG_INT) {
  26230. /* get the returned yield value at the top of the stack */
  26231. ret = sf->cur_sp[-1];
  26232. sf->cur_sp[-1] = JS_UNDEFINED;
  26233. if (JS_VALUE_GET_INT(func_ret) == FUNC_RET_YIELD_STAR) {
  26234. s->state = JS_GENERATOR_STATE_SUSPENDED_YIELD_STAR;
  26235. /* return (value, done) object */
  26236. *pdone = 2;
  26237. } else {
  26238. *pdone = false;
  26239. }
  26240. } else {
  26241. /* end of iterator */
  26242. ret = sf->cur_sp[-1];
  26243. sf->cur_sp[-1] = JS_UNDEFINED;
  26244. JS_FreeValue(ctx, func_ret);
  26245. free_generator_stack(ctx, s);
  26246. }
  26247. break;
  26248. case JS_GENERATOR_STATE_COMPLETED:
  26249. done:
  26250. /* execution is finished */
  26251. switch(magic) {
  26252. default:
  26253. case GEN_MAGIC_NEXT:
  26254. ret = JS_UNDEFINED;
  26255. break;
  26256. case GEN_MAGIC_RETURN:
  26257. ret = js_dup(argv[0]);
  26258. break;
  26259. case GEN_MAGIC_THROW:
  26260. ret = JS_Throw(ctx, js_dup(argv[0]));
  26261. break;
  26262. }
  26263. break;
  26264. case JS_GENERATOR_STATE_EXECUTING:
  26265. ret = JS_ThrowTypeError(ctx, "cannot invoke a running generator");
  26266. break;
  26267. }
  26268. return ret;
  26269. }
  26270. static JSValue js_generator_function_call(JSContext *ctx, JSValueConst func_obj,
  26271. JSValueConst this_obj,
  26272. int argc, JSValueConst *argv,
  26273. int flags)
  26274. {
  26275. JSValue obj, func_ret;
  26276. JSGeneratorData *s;
  26277. s = js_mallocz(ctx, sizeof(*s));
  26278. if (!s)
  26279. return JS_EXCEPTION;
  26280. s->state = JS_GENERATOR_STATE_SUSPENDED_START;
  26281. if (async_func_init(ctx, &s->func_state, func_obj, this_obj, argc, argv)) {
  26282. s->state = JS_GENERATOR_STATE_COMPLETED;
  26283. goto fail;
  26284. }
  26285. /* execute the function up to 'OP_initial_yield' */
  26286. func_ret = async_func_resume(ctx, &s->func_state);
  26287. if (JS_IsException(func_ret))
  26288. goto fail;
  26289. JS_FreeValue(ctx, func_ret);
  26290. obj = js_create_from_ctor(ctx, func_obj, JS_CLASS_GENERATOR);
  26291. if (JS_IsException(obj))
  26292. goto fail;
  26293. JS_SetOpaqueInternal(obj, s);
  26294. return obj;
  26295. fail:
  26296. free_generator_stack_rt(ctx->rt, s);
  26297. js_free(ctx, s);
  26298. return JS_EXCEPTION;
  26299. }
  26300. /* AsyncFunction */
  26301. static void js_async_function_terminate(JSRuntime *rt, JSAsyncFunctionData *s)
  26302. {
  26303. if (s->is_active) {
  26304. async_func_free(rt, &s->func_state);
  26305. s->is_active = false;
  26306. }
  26307. }
  26308. static void js_async_function_free0(JSRuntime *rt, JSAsyncFunctionData *s)
  26309. {
  26310. js_async_function_terminate(rt, s);
  26311. JS_FreeValueRT(rt, s->resolving_funcs[0]);
  26312. JS_FreeValueRT(rt, s->resolving_funcs[1]);
  26313. remove_gc_object(&s->header);
  26314. js_free_rt(rt, s);
  26315. }
  26316. static void js_async_function_free(JSRuntime *rt, JSAsyncFunctionData *s)
  26317. {
  26318. if (--s->header.ref_count == 0) {
  26319. js_async_function_free0(rt, s);
  26320. }
  26321. }
  26322. static void js_async_function_resolve_finalizer(JSRuntime *rt,
  26323. JSValueConst val)
  26324. {
  26325. JSObject *p = JS_VALUE_GET_OBJ(val);
  26326. JSAsyncFunctionData *s = p->u.async_function_data;
  26327. if (s) {
  26328. js_async_function_free(rt, s);
  26329. }
  26330. }
  26331. static void js_async_function_resolve_mark(JSRuntime *rt, JSValueConst val,
  26332. JS_MarkFunc *mark_func)
  26333. {
  26334. JSObject *p = JS_VALUE_GET_OBJ(val);
  26335. JSAsyncFunctionData *s = p->u.async_function_data;
  26336. if (s) {
  26337. mark_func(rt, &s->header);
  26338. }
  26339. }
  26340. static int js_async_function_resolve_create(JSContext *ctx,
  26341. JSAsyncFunctionData *s,
  26342. JSValue *resolving_funcs)
  26343. {
  26344. int i;
  26345. JSObject *p;
  26346. for(i = 0; i < 2; i++) {
  26347. resolving_funcs[i] =
  26348. JS_NewObjectProtoClass(ctx, ctx->function_proto,
  26349. JS_CLASS_ASYNC_FUNCTION_RESOLVE + i);
  26350. if (JS_IsException(resolving_funcs[i])) {
  26351. if (i == 1)
  26352. JS_FreeValue(ctx, resolving_funcs[0]);
  26353. return -1;
  26354. }
  26355. p = JS_VALUE_GET_OBJ(resolving_funcs[i]);
  26356. s->header.ref_count++;
  26357. p->u.async_function_data = s;
  26358. }
  26359. return 0;
  26360. }
  26361. static bool js_async_function_resume(JSContext *ctx, JSAsyncFunctionData *s)
  26362. {
  26363. bool is_success = true;
  26364. JSValue func_ret, ret2;
  26365. func_ret = async_func_resume(ctx, &s->func_state);
  26366. if (JS_IsException(func_ret)) {
  26367. fail:
  26368. if (unlikely(JS_IsUncatchableError(ctx, ctx->rt->current_exception))) {
  26369. is_success = false;
  26370. } else {
  26371. JSValue error = JS_GetException(ctx);
  26372. ret2 = JS_Call(ctx, s->resolving_funcs[1], JS_UNDEFINED,
  26373. 1, vc(&error));
  26374. JS_FreeValue(ctx, error);
  26375. resolved:
  26376. if (unlikely(JS_IsException(ret2))) {
  26377. if (JS_IsUncatchableError(ctx, ctx->rt->current_exception)) {
  26378. is_success = false;
  26379. } else {
  26380. abort(); /* BUG */
  26381. }
  26382. }
  26383. JS_FreeValue(ctx, ret2);
  26384. }
  26385. js_async_function_terminate(ctx->rt, s);
  26386. } else {
  26387. JSValue value;
  26388. value = s->func_state.frame.cur_sp[-1];
  26389. s->func_state.frame.cur_sp[-1] = JS_UNDEFINED;
  26390. if (JS_IsUndefined(func_ret)) {
  26391. /* function returned */
  26392. ret2 = JS_Call(ctx, s->resolving_funcs[0], JS_UNDEFINED,
  26393. 1, vc(&value));
  26394. JS_FreeValue(ctx, value);
  26395. goto resolved;
  26396. } else {
  26397. JSValue promise, resolving_funcs[2], resolving_funcs1[2];
  26398. int i, res;
  26399. /* await */
  26400. JS_FreeValue(ctx, func_ret); /* not used */
  26401. promise = js_promise_resolve(ctx, ctx->promise_ctor,
  26402. 1, vc(&value), 0);
  26403. JS_FreeValue(ctx, value);
  26404. if (JS_IsException(promise))
  26405. goto fail;
  26406. if (js_async_function_resolve_create(ctx, s, resolving_funcs)) {
  26407. JS_FreeValue(ctx, promise);
  26408. goto fail;
  26409. }
  26410. /* Note: no need to create 'thrownawayCapability' as in
  26411. the spec */
  26412. for(i = 0; i < 2; i++)
  26413. resolving_funcs1[i] = JS_UNDEFINED;
  26414. res = perform_promise_then(ctx, promise,
  26415. vc(resolving_funcs),
  26416. vc(resolving_funcs1));
  26417. JS_FreeValue(ctx, promise);
  26418. for(i = 0; i < 2; i++)
  26419. JS_FreeValue(ctx, resolving_funcs[i]);
  26420. if (res)
  26421. goto fail;
  26422. }
  26423. }
  26424. return is_success;
  26425. }
  26426. static JSValue js_async_function_resolve_call(JSContext *ctx,
  26427. JSValueConst func_obj,
  26428. JSValueConst this_obj,
  26429. int argc, JSValueConst *argv,
  26430. int flags)
  26431. {
  26432. JSObject *p = JS_VALUE_GET_OBJ(func_obj);
  26433. JSAsyncFunctionData *s = p->u.async_function_data;
  26434. bool is_reject = p->class_id - JS_CLASS_ASYNC_FUNCTION_RESOLVE;
  26435. JSValueConst arg;
  26436. if (argc > 0)
  26437. arg = argv[0];
  26438. else
  26439. arg = JS_UNDEFINED;
  26440. s->func_state.throw_flag = is_reject;
  26441. if (is_reject) {
  26442. JS_Throw(ctx, js_dup(arg));
  26443. } else {
  26444. /* return value of await */
  26445. s->func_state.frame.cur_sp[-1] = js_dup(arg);
  26446. }
  26447. if (!js_async_function_resume(ctx, s))
  26448. return JS_EXCEPTION;
  26449. return JS_UNDEFINED;
  26450. }
  26451. static JSValue js_async_function_call(JSContext *ctx, JSValueConst func_obj,
  26452. JSValueConst this_obj,
  26453. int argc, JSValueConst *argv, int flags)
  26454. {
  26455. JSValue promise;
  26456. JSAsyncFunctionData *s;
  26457. s = js_mallocz(ctx, sizeof(*s));
  26458. if (!s)
  26459. return JS_EXCEPTION;
  26460. s->header.ref_count = 1;
  26461. add_gc_object(ctx->rt, &s->header, JS_GC_OBJ_TYPE_ASYNC_FUNCTION);
  26462. s->is_active = false;
  26463. s->resolving_funcs[0] = JS_UNDEFINED;
  26464. s->resolving_funcs[1] = JS_UNDEFINED;
  26465. promise = JS_NewPromiseCapability(ctx, s->resolving_funcs);
  26466. if (JS_IsException(promise))
  26467. goto fail;
  26468. if (async_func_init(ctx, &s->func_state, func_obj, this_obj, argc, argv)) {
  26469. fail:
  26470. JS_FreeValue(ctx, promise);
  26471. js_async_function_free(ctx->rt, s);
  26472. return JS_EXCEPTION;
  26473. }
  26474. s->is_active = true;
  26475. if (!js_async_function_resume(ctx, s))
  26476. goto fail;
  26477. js_async_function_free(ctx->rt, s);
  26478. return promise;
  26479. }
  26480. /* AsyncGenerator */
  26481. typedef enum JSAsyncGeneratorStateEnum {
  26482. JS_ASYNC_GENERATOR_STATE_SUSPENDED_START,
  26483. JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD,
  26484. JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD_STAR,
  26485. JS_ASYNC_GENERATOR_STATE_EXECUTING,
  26486. JS_ASYNC_GENERATOR_STATE_AWAITING_RETURN,
  26487. JS_ASYNC_GENERATOR_STATE_COMPLETED,
  26488. } JSAsyncGeneratorStateEnum;
  26489. typedef struct JSAsyncGeneratorRequest {
  26490. struct list_head link;
  26491. /* completion */
  26492. int completion_type; /* GEN_MAGIC_x */
  26493. JSValue result;
  26494. /* promise capability */
  26495. JSValue promise;
  26496. JSValue resolving_funcs[2];
  26497. } JSAsyncGeneratorRequest;
  26498. typedef struct JSAsyncGeneratorData {
  26499. JSObject *generator; /* back pointer to the object (const) */
  26500. JSAsyncGeneratorStateEnum state;
  26501. JSAsyncFunctionState func_state;
  26502. struct list_head queue; /* list of JSAsyncGeneratorRequest.link */
  26503. } JSAsyncGeneratorData;
  26504. static void js_async_generator_free(JSRuntime *rt,
  26505. JSAsyncGeneratorData *s)
  26506. {
  26507. struct list_head *el, *el1;
  26508. JSAsyncGeneratorRequest *req;
  26509. list_for_each_safe(el, el1, &s->queue) {
  26510. req = list_entry(el, JSAsyncGeneratorRequest, link);
  26511. JS_FreeValueRT(rt, req->result);
  26512. JS_FreeValueRT(rt, req->promise);
  26513. JS_FreeValueRT(rt, req->resolving_funcs[0]);
  26514. JS_FreeValueRT(rt, req->resolving_funcs[1]);
  26515. js_free_rt(rt, req);
  26516. }
  26517. if (s->state != JS_ASYNC_GENERATOR_STATE_COMPLETED &&
  26518. s->state != JS_ASYNC_GENERATOR_STATE_AWAITING_RETURN) {
  26519. async_func_free(rt, &s->func_state);
  26520. }
  26521. js_free_rt(rt, s);
  26522. }
  26523. static void js_async_generator_finalizer(JSRuntime *rt, JSValueConst obj)
  26524. {
  26525. JSAsyncGeneratorData *s = JS_GetOpaque(obj, JS_CLASS_ASYNC_GENERATOR);
  26526. if (s) {
  26527. js_async_generator_free(rt, s);
  26528. }
  26529. }
  26530. static void js_async_generator_mark(JSRuntime *rt, JSValueConst val,
  26531. JS_MarkFunc *mark_func)
  26532. {
  26533. JSAsyncGeneratorData *s = JS_GetOpaque(val, JS_CLASS_ASYNC_GENERATOR);
  26534. struct list_head *el;
  26535. JSAsyncGeneratorRequest *req;
  26536. if (s) {
  26537. list_for_each(el, &s->queue) {
  26538. req = list_entry(el, JSAsyncGeneratorRequest, link);
  26539. JS_MarkValue(rt, req->result, mark_func);
  26540. JS_MarkValue(rt, req->promise, mark_func);
  26541. JS_MarkValue(rt, req->resolving_funcs[0], mark_func);
  26542. JS_MarkValue(rt, req->resolving_funcs[1], mark_func);
  26543. }
  26544. if (s->state != JS_ASYNC_GENERATOR_STATE_COMPLETED &&
  26545. s->state != JS_ASYNC_GENERATOR_STATE_AWAITING_RETURN) {
  26546. async_func_mark(rt, &s->func_state, mark_func);
  26547. }
  26548. }
  26549. }
  26550. static JSValue js_async_generator_resolve_function(JSContext *ctx,
  26551. JSValueConst this_obj,
  26552. int argc, JSValueConst *argv,
  26553. int magic, JSValueConst *func_data);
  26554. static int js_async_generator_resolve_function_create(JSContext *ctx,
  26555. JSValue generator,
  26556. JSValue *resolving_funcs,
  26557. bool is_resume_next)
  26558. {
  26559. int i;
  26560. JSValue func;
  26561. for(i = 0; i < 2; i++) {
  26562. func = JS_NewCFunctionData(ctx, js_async_generator_resolve_function, 1,
  26563. i + is_resume_next * 2, 1, vc(&generator));
  26564. if (JS_IsException(func)) {
  26565. if (i == 1)
  26566. JS_FreeValue(ctx, resolving_funcs[0]);
  26567. return -1;
  26568. }
  26569. resolving_funcs[i] = func;
  26570. }
  26571. return 0;
  26572. }
  26573. static int js_async_generator_await(JSContext *ctx,
  26574. JSAsyncGeneratorData *s,
  26575. JSValue value)
  26576. {
  26577. JSValue promise, resolving_funcs[2], resolving_funcs1[2];
  26578. int i, res;
  26579. promise = js_promise_resolve(ctx, ctx->promise_ctor,
  26580. 1, vc(&value), 0);
  26581. if (JS_IsException(promise))
  26582. goto fail;
  26583. if (js_async_generator_resolve_function_create(ctx, JS_MKPTR(JS_TAG_OBJECT, s->generator),
  26584. resolving_funcs, false)) {
  26585. JS_FreeValue(ctx, promise);
  26586. goto fail;
  26587. }
  26588. /* Note: no need to create 'thrownawayCapability' as in
  26589. the spec */
  26590. for(i = 0; i < 2; i++)
  26591. resolving_funcs1[i] = JS_UNDEFINED;
  26592. res = perform_promise_then(ctx, promise,
  26593. vc(resolving_funcs),
  26594. vc(resolving_funcs1));
  26595. JS_FreeValue(ctx, promise);
  26596. for(i = 0; i < 2; i++)
  26597. JS_FreeValue(ctx, resolving_funcs[i]);
  26598. if (res)
  26599. goto fail;
  26600. return 0;
  26601. fail:
  26602. return -1;
  26603. }
  26604. static void js_async_generator_resolve_or_reject(JSContext *ctx,
  26605. JSAsyncGeneratorData *s,
  26606. JSValueConst result,
  26607. int is_reject)
  26608. {
  26609. JSAsyncGeneratorRequest *next;
  26610. JSValue ret;
  26611. next = list_entry(s->queue.next, JSAsyncGeneratorRequest, link);
  26612. list_del(&next->link);
  26613. ret = JS_Call(ctx, next->resolving_funcs[is_reject], JS_UNDEFINED, 1,
  26614. &result);
  26615. JS_FreeValue(ctx, ret);
  26616. JS_FreeValue(ctx, next->result);
  26617. JS_FreeValue(ctx, next->promise);
  26618. JS_FreeValue(ctx, next->resolving_funcs[0]);
  26619. JS_FreeValue(ctx, next->resolving_funcs[1]);
  26620. js_free(ctx, next);
  26621. }
  26622. static void js_async_generator_resolve(JSContext *ctx,
  26623. JSAsyncGeneratorData *s,
  26624. JSValueConst value,
  26625. bool done)
  26626. {
  26627. JSValue result;
  26628. result = js_create_iterator_result(ctx, js_dup(value), done);
  26629. /* XXX: better exception handling ? */
  26630. js_async_generator_resolve_or_reject(ctx, s, result, 0);
  26631. JS_FreeValue(ctx, result);
  26632. }
  26633. static void js_async_generator_reject(JSContext *ctx,
  26634. JSAsyncGeneratorData *s,
  26635. JSValueConst exception)
  26636. {
  26637. js_async_generator_resolve_or_reject(ctx, s, exception, 1);
  26638. }
  26639. static void js_async_generator_complete(JSContext *ctx,
  26640. JSAsyncGeneratorData *s)
  26641. {
  26642. if (s->state != JS_ASYNC_GENERATOR_STATE_COMPLETED) {
  26643. s->state = JS_ASYNC_GENERATOR_STATE_COMPLETED;
  26644. async_func_free(ctx->rt, &s->func_state);
  26645. }
  26646. }
  26647. static int js_async_generator_completed_return(JSContext *ctx,
  26648. JSAsyncGeneratorData *s,
  26649. JSValue value)
  26650. {
  26651. JSValue promise, resolving_funcs[2], resolving_funcs1[2];
  26652. int res;
  26653. // Can fail looking up JS_ATOM_constructor when is_reject==0.
  26654. promise = js_promise_resolve(ctx, ctx->promise_ctor, 1, vc(&value),
  26655. /*is_reject*/0);
  26656. // A poisoned .constructor property is observable and the resulting
  26657. // exception should be delivered to the catch handler.
  26658. if (JS_IsException(promise)) {
  26659. JSValue err = JS_GetException(ctx);
  26660. promise = js_promise_resolve(ctx, ctx->promise_ctor, 1, vc(&err),
  26661. /*is_reject*/1);
  26662. JS_FreeValue(ctx, err);
  26663. if (JS_IsException(promise))
  26664. return -1;
  26665. }
  26666. if (js_async_generator_resolve_function_create(ctx,
  26667. JS_MKPTR(JS_TAG_OBJECT, s->generator),
  26668. resolving_funcs1,
  26669. true)) {
  26670. JS_FreeValue(ctx, promise);
  26671. return -1;
  26672. }
  26673. resolving_funcs[0] = JS_UNDEFINED;
  26674. resolving_funcs[1] = JS_UNDEFINED;
  26675. res = perform_promise_then(ctx, promise,
  26676. vc(resolving_funcs1),
  26677. vc(resolving_funcs));
  26678. JS_FreeValue(ctx, resolving_funcs1[0]);
  26679. JS_FreeValue(ctx, resolving_funcs1[1]);
  26680. JS_FreeValue(ctx, promise);
  26681. return res;
  26682. }
  26683. static void js_async_generator_resume_next(JSContext *ctx,
  26684. JSAsyncGeneratorData *s)
  26685. {
  26686. JSAsyncGeneratorRequest *next;
  26687. JSValue func_ret, value;
  26688. for(;;) {
  26689. if (list_empty(&s->queue))
  26690. break;
  26691. next = list_entry(s->queue.next, JSAsyncGeneratorRequest, link);
  26692. switch(s->state) {
  26693. case JS_ASYNC_GENERATOR_STATE_EXECUTING:
  26694. /* only happens when restarting execution after await() */
  26695. goto resume_exec;
  26696. case JS_ASYNC_GENERATOR_STATE_AWAITING_RETURN:
  26697. goto done;
  26698. case JS_ASYNC_GENERATOR_STATE_SUSPENDED_START:
  26699. if (next->completion_type == GEN_MAGIC_NEXT) {
  26700. goto exec_no_arg;
  26701. } else {
  26702. js_async_generator_complete(ctx, s);
  26703. }
  26704. break;
  26705. case JS_ASYNC_GENERATOR_STATE_COMPLETED:
  26706. if (next->completion_type == GEN_MAGIC_NEXT) {
  26707. js_async_generator_resolve(ctx, s, JS_UNDEFINED, true);
  26708. } else if (next->completion_type == GEN_MAGIC_RETURN) {
  26709. s->state = JS_ASYNC_GENERATOR_STATE_AWAITING_RETURN;
  26710. js_async_generator_completed_return(ctx, s, next->result);
  26711. } else {
  26712. js_async_generator_reject(ctx, s, next->result);
  26713. }
  26714. goto done;
  26715. case JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD:
  26716. case JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD_STAR:
  26717. value = js_dup(next->result);
  26718. if (next->completion_type == GEN_MAGIC_THROW &&
  26719. s->state == JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD) {
  26720. JS_Throw(ctx, value);
  26721. s->func_state.throw_flag = true;
  26722. } else {
  26723. /* 'yield' returns a value. 'yield *' also returns a value
  26724. in case the 'throw' method is called */
  26725. s->func_state.frame.cur_sp[-1] = value;
  26726. s->func_state.frame.cur_sp[0] =
  26727. js_int32(next->completion_type);
  26728. s->func_state.frame.cur_sp++;
  26729. exec_no_arg:
  26730. s->func_state.throw_flag = false;
  26731. }
  26732. s->state = JS_ASYNC_GENERATOR_STATE_EXECUTING;
  26733. resume_exec:
  26734. func_ret = async_func_resume(ctx, &s->func_state);
  26735. if (JS_IsException(func_ret)) {
  26736. value = JS_GetException(ctx);
  26737. js_async_generator_complete(ctx, s);
  26738. js_async_generator_reject(ctx, s, value);
  26739. JS_FreeValue(ctx, value);
  26740. } else if (JS_VALUE_GET_TAG(func_ret) == JS_TAG_INT) {
  26741. int func_ret_code, ret;
  26742. value = s->func_state.frame.cur_sp[-1];
  26743. s->func_state.frame.cur_sp[-1] = JS_UNDEFINED;
  26744. func_ret_code = JS_VALUE_GET_INT(func_ret);
  26745. switch(func_ret_code) {
  26746. case FUNC_RET_YIELD:
  26747. case FUNC_RET_YIELD_STAR:
  26748. if (func_ret_code == FUNC_RET_YIELD_STAR)
  26749. s->state = JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD_STAR;
  26750. else
  26751. s->state = JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD;
  26752. js_async_generator_resolve(ctx, s, value, false);
  26753. JS_FreeValue(ctx, value);
  26754. break;
  26755. case FUNC_RET_AWAIT:
  26756. ret = js_async_generator_await(ctx, s, value);
  26757. JS_FreeValue(ctx, value);
  26758. if (ret < 0) {
  26759. /* exception: throw it */
  26760. s->func_state.throw_flag = true;
  26761. goto resume_exec;
  26762. }
  26763. goto done;
  26764. default:
  26765. abort();
  26766. }
  26767. } else {
  26768. assert(JS_IsUndefined(func_ret));
  26769. /* end of function */
  26770. value = s->func_state.frame.cur_sp[-1];
  26771. s->func_state.frame.cur_sp[-1] = JS_UNDEFINED;
  26772. js_async_generator_complete(ctx, s);
  26773. js_async_generator_resolve(ctx, s, value, true);
  26774. JS_FreeValue(ctx, value);
  26775. }
  26776. break;
  26777. default:
  26778. abort();
  26779. }
  26780. }
  26781. done: ;
  26782. }
  26783. static JSValue js_async_generator_resolve_function(JSContext *ctx,
  26784. JSValueConst this_obj,
  26785. int argc, JSValueConst *argv,
  26786. int magic, JSValueConst *func_data)
  26787. {
  26788. bool is_reject = magic & 1;
  26789. JSAsyncGeneratorData *s = JS_GetOpaque(func_data[0], JS_CLASS_ASYNC_GENERATOR);
  26790. JSValueConst arg = argv[0];
  26791. /* XXX: what if s == NULL */
  26792. if (magic >= 2) {
  26793. /* resume next case in AWAITING_RETURN state */
  26794. assert(s->state == JS_ASYNC_GENERATOR_STATE_AWAITING_RETURN ||
  26795. s->state == JS_ASYNC_GENERATOR_STATE_COMPLETED);
  26796. s->state = JS_ASYNC_GENERATOR_STATE_COMPLETED;
  26797. if (is_reject) {
  26798. js_async_generator_reject(ctx, s, arg);
  26799. } else {
  26800. js_async_generator_resolve(ctx, s, arg, true);
  26801. }
  26802. } else {
  26803. /* restart function execution after await() */
  26804. assert(s->state == JS_ASYNC_GENERATOR_STATE_EXECUTING);
  26805. s->func_state.throw_flag = is_reject;
  26806. if (is_reject) {
  26807. JS_Throw(ctx, js_dup(arg));
  26808. } else {
  26809. /* return value of await */
  26810. s->func_state.frame.cur_sp[-1] = js_dup(arg);
  26811. }
  26812. js_async_generator_resume_next(ctx, s);
  26813. }
  26814. return JS_UNDEFINED;
  26815. }
  26816. /* magic = GEN_MAGIC_x */
  26817. static JSValue js_async_generator_next(JSContext *ctx, JSValueConst this_val,
  26818. int argc, JSValueConst *argv,
  26819. int magic)
  26820. {
  26821. JSAsyncGeneratorData *s = JS_GetOpaque(this_val, JS_CLASS_ASYNC_GENERATOR);
  26822. JSValue promise, resolving_funcs[2];
  26823. JSAsyncGeneratorRequest *req;
  26824. promise = JS_NewPromiseCapability(ctx, resolving_funcs);
  26825. if (JS_IsException(promise))
  26826. return JS_EXCEPTION;
  26827. if (!s) {
  26828. JSValue err, res2;
  26829. JS_ThrowTypeError(ctx, "not an AsyncGenerator object");
  26830. err = JS_GetException(ctx);
  26831. res2 = JS_Call(ctx, resolving_funcs[1], JS_UNDEFINED,
  26832. 1, vc(&err));
  26833. JS_FreeValue(ctx, err);
  26834. JS_FreeValue(ctx, res2);
  26835. JS_FreeValue(ctx, resolving_funcs[0]);
  26836. JS_FreeValue(ctx, resolving_funcs[1]);
  26837. return promise;
  26838. }
  26839. req = js_mallocz(ctx, sizeof(*req));
  26840. if (!req)
  26841. goto fail;
  26842. req->completion_type = magic;
  26843. req->result = js_dup(argv[0]);
  26844. req->promise = js_dup(promise);
  26845. req->resolving_funcs[0] = resolving_funcs[0];
  26846. req->resolving_funcs[1] = resolving_funcs[1];
  26847. list_add_tail(&req->link, &s->queue);
  26848. if (s->state != JS_ASYNC_GENERATOR_STATE_EXECUTING) {
  26849. js_async_generator_resume_next(ctx, s);
  26850. }
  26851. return promise;
  26852. fail:
  26853. JS_FreeValue(ctx, resolving_funcs[0]);
  26854. JS_FreeValue(ctx, resolving_funcs[1]);
  26855. JS_FreeValue(ctx, promise);
  26856. return JS_EXCEPTION;
  26857. }
  26858. static JSValue js_async_generator_function_call(JSContext *ctx,
  26859. JSValueConst func_obj,
  26860. JSValueConst this_obj,
  26861. int argc, JSValueConst *argv,
  26862. int flags)
  26863. {
  26864. JSValue obj, func_ret;
  26865. JSAsyncGeneratorData *s;
  26866. s = js_mallocz(ctx, sizeof(*s));
  26867. if (!s)
  26868. return JS_EXCEPTION;
  26869. s->state = JS_ASYNC_GENERATOR_STATE_SUSPENDED_START;
  26870. init_list_head(&s->queue);
  26871. if (async_func_init(ctx, &s->func_state, func_obj, this_obj, argc, argv)) {
  26872. s->state = JS_ASYNC_GENERATOR_STATE_COMPLETED;
  26873. goto fail;
  26874. }
  26875. /* execute the function up to 'OP_initial_yield' (no yield nor
  26876. await are possible) */
  26877. func_ret = async_func_resume(ctx, &s->func_state);
  26878. if (JS_IsException(func_ret))
  26879. goto fail;
  26880. JS_FreeValue(ctx, func_ret);
  26881. obj = js_create_from_ctor(ctx, func_obj, JS_CLASS_ASYNC_GENERATOR);
  26882. if (JS_IsException(obj))
  26883. goto fail;
  26884. s->generator = JS_VALUE_GET_OBJ(obj);
  26885. JS_SetOpaqueInternal(obj, s);
  26886. return obj;
  26887. fail:
  26888. js_async_generator_free(ctx->rt, s);
  26889. return JS_EXCEPTION;
  26890. }
  26891. /* JS parser */
  26892. enum {
  26893. TOK_NUMBER = -128,
  26894. TOK_STRING,
  26895. TOK_TEMPLATE,
  26896. TOK_IDENT,
  26897. TOK_REGEXP,
  26898. /* warning: order matters (see js_parse_assign_expr) */
  26899. TOK_MUL_ASSIGN,
  26900. TOK_DIV_ASSIGN,
  26901. TOK_MOD_ASSIGN,
  26902. TOK_PLUS_ASSIGN,
  26903. TOK_MINUS_ASSIGN,
  26904. TOK_SHL_ASSIGN,
  26905. TOK_SAR_ASSIGN,
  26906. TOK_SHR_ASSIGN,
  26907. TOK_AND_ASSIGN,
  26908. TOK_XOR_ASSIGN,
  26909. TOK_OR_ASSIGN,
  26910. TOK_POW_ASSIGN,
  26911. TOK_LAND_ASSIGN,
  26912. TOK_LOR_ASSIGN,
  26913. TOK_DOUBLE_QUESTION_MARK_ASSIGN,
  26914. TOK_DEC,
  26915. TOK_INC,
  26916. TOK_SHL,
  26917. TOK_SAR,
  26918. TOK_SHR,
  26919. TOK_LT,
  26920. TOK_LTE,
  26921. TOK_GT,
  26922. TOK_GTE,
  26923. TOK_EQ,
  26924. TOK_STRICT_EQ,
  26925. TOK_NEQ,
  26926. TOK_STRICT_NEQ,
  26927. TOK_LAND,
  26928. TOK_LOR,
  26929. TOK_POW,
  26930. TOK_ARROW,
  26931. TOK_ELLIPSIS,
  26932. TOK_DOUBLE_QUESTION_MARK,
  26933. TOK_QUESTION_MARK_DOT,
  26934. TOK_ERROR,
  26935. TOK_PRIVATE_NAME,
  26936. TOK_EOF,
  26937. /* keywords: WARNING: same order as atoms */
  26938. TOK_NULL, /* must be first */
  26939. TOK_FALSE,
  26940. TOK_TRUE,
  26941. TOK_IF,
  26942. TOK_ELSE,
  26943. TOK_RETURN,
  26944. TOK_VAR,
  26945. TOK_THIS,
  26946. TOK_DELETE,
  26947. TOK_VOID,
  26948. TOK_TYPEOF,
  26949. TOK_NEW,
  26950. TOK_IN,
  26951. TOK_INSTANCEOF,
  26952. TOK_DO,
  26953. TOK_WHILE,
  26954. TOK_FOR,
  26955. TOK_BREAK,
  26956. TOK_CONTINUE,
  26957. TOK_SWITCH,
  26958. TOK_CASE,
  26959. TOK_DEFAULT,
  26960. TOK_THROW,
  26961. TOK_TRY,
  26962. TOK_CATCH,
  26963. TOK_FINALLY,
  26964. TOK_FUNCTION,
  26965. TOK_DEBUGGER,
  26966. TOK_WITH,
  26967. /* FutureReservedWord */
  26968. TOK_CLASS,
  26969. TOK_CONST,
  26970. TOK_ENUM,
  26971. TOK_EXPORT,
  26972. TOK_EXTENDS,
  26973. TOK_IMPORT,
  26974. TOK_SUPER,
  26975. /* FutureReservedWords when parsing strict mode code */
  26976. TOK_IMPLEMENTS,
  26977. TOK_INTERFACE,
  26978. TOK_LET,
  26979. TOK_PACKAGE,
  26980. TOK_PRIVATE,
  26981. TOK_PROTECTED,
  26982. TOK_PUBLIC,
  26983. TOK_STATIC,
  26984. TOK_YIELD,
  26985. TOK_AWAIT, /* must be last */
  26986. TOK_OF, /* only used for js_parse_skip_parens_token() */
  26987. };
  26988. #define TOK_FIRST_KEYWORD TOK_NULL
  26989. #define TOK_LAST_KEYWORD TOK_AWAIT
  26990. /* unicode code points */
  26991. #define CP_NBSP 0x00a0
  26992. #define CP_BOM 0xfeff
  26993. #define CP_LS 0x2028
  26994. #define CP_PS 0x2029
  26995. typedef struct BlockEnv {
  26996. struct BlockEnv *prev;
  26997. JSAtom label_name; /* JS_ATOM_NULL if none */
  26998. int label_break; /* -1 if none */
  26999. int label_cont; /* -1 if none */
  27000. int drop_count; /* number of stack elements to drop */
  27001. int label_finally; /* -1 if none */
  27002. int scope_level;
  27003. uint8_t has_iterator : 1;
  27004. uint8_t is_regular_stmt : 1; // i.e. not a loop statement
  27005. } BlockEnv;
  27006. typedef struct JSGlobalVar {
  27007. int cpool_idx; /* if >= 0, index in the constant pool for hoisted
  27008. function defintion*/
  27009. uint8_t force_init : 1; /* force initialization to undefined */
  27010. uint8_t is_lexical : 1; /* global let/const definition */
  27011. uint8_t is_const : 1; /* const definition */
  27012. int scope_level; /* scope of definition */
  27013. JSAtom var_name; /* variable name */
  27014. } JSGlobalVar;
  27015. typedef struct RelocEntry {
  27016. struct RelocEntry *next;
  27017. uint32_t addr; /* address to patch */
  27018. int size; /* address size: 1, 2 or 4 bytes */
  27019. } RelocEntry;
  27020. typedef struct JumpSlot {
  27021. int op;
  27022. int size;
  27023. int pos;
  27024. int label;
  27025. } JumpSlot;
  27026. typedef struct LabelSlot {
  27027. int ref_count;
  27028. int pos; /* phase 1 address, -1 means not resolved yet */
  27029. int pos2; /* phase 2 address, -1 means not resolved yet */
  27030. int addr; /* phase 3 address, -1 means not resolved yet */
  27031. RelocEntry *first_reloc;
  27032. } LabelSlot;
  27033. typedef struct SourceLocSlot {
  27034. uint32_t pc;
  27035. int line_num;
  27036. int col_num;
  27037. } SourceLocSlot;
  27038. typedef enum JSParseFunctionEnum {
  27039. JS_PARSE_FUNC_STATEMENT,
  27040. JS_PARSE_FUNC_VAR,
  27041. JS_PARSE_FUNC_EXPR,
  27042. JS_PARSE_FUNC_ARROW,
  27043. JS_PARSE_FUNC_GETTER,
  27044. JS_PARSE_FUNC_SETTER,
  27045. JS_PARSE_FUNC_METHOD,
  27046. JS_PARSE_FUNC_CLASS_STATIC_INIT,
  27047. JS_PARSE_FUNC_CLASS_CONSTRUCTOR,
  27048. JS_PARSE_FUNC_DERIVED_CLASS_CONSTRUCTOR,
  27049. } JSParseFunctionEnum;
  27050. typedef enum JSParseExportEnum {
  27051. JS_PARSE_EXPORT_NONE,
  27052. JS_PARSE_EXPORT_NAMED,
  27053. JS_PARSE_EXPORT_DEFAULT,
  27054. } JSParseExportEnum;
  27055. typedef struct JSFunctionDef {
  27056. JSContext *ctx;
  27057. struct JSFunctionDef *parent;
  27058. int parent_cpool_idx; /* index in the constant pool of the parent
  27059. or -1 if none */
  27060. int parent_scope_level; /* scope level in parent at point of definition */
  27061. struct list_head child_list; /* list of JSFunctionDef.link */
  27062. struct list_head link;
  27063. bool is_eval; /* true if eval code */
  27064. int eval_type; /* only valid if is_eval = true */
  27065. bool is_global_var; /* true if variables are not defined locally:
  27066. eval global, eval module or non strict eval */
  27067. bool is_func_expr; /* true if function expression */
  27068. bool has_home_object; /* true if the home object is available */
  27069. bool has_prototype; /* true if a prototype field is necessary */
  27070. bool has_simple_parameter_list;
  27071. bool has_parameter_expressions; /* if true, an argument scope is created */
  27072. bool has_use_strict; /* to reject directive in special cases */
  27073. bool has_eval_call; /* true if the function contains a call to eval() */
  27074. bool has_arguments_binding; /* true if the 'arguments' binding is
  27075. available in the function */
  27076. bool has_this_binding; /* true if the 'this' and new.target binding are
  27077. available in the function */
  27078. bool new_target_allowed; /* true if the 'new.target' does not
  27079. throw a syntax error */
  27080. bool super_call_allowed; /* true if super() is allowed */
  27081. bool super_allowed; /* true if super. or super[] is allowed */
  27082. bool arguments_allowed; /* true if the 'arguments' identifier is allowed */
  27083. bool is_derived_class_constructor;
  27084. bool in_function_body;
  27085. bool backtrace_barrier;
  27086. JSFunctionKindEnum func_kind : 8;
  27087. JSParseFunctionEnum func_type : 7;
  27088. uint8_t is_strict_mode : 1;
  27089. JSAtom func_name; /* JS_ATOM_NULL if no name */
  27090. JSVarDef *vars;
  27091. uint32_t *vars_htab; // indexes into vars[]
  27092. int var_size; /* allocated size for vars[] */
  27093. int var_count;
  27094. JSVarDef *args;
  27095. int arg_size; /* allocated size for args[] */
  27096. int arg_count; /* number of arguments */
  27097. int defined_arg_count;
  27098. int var_object_idx; /* -1 if none */
  27099. int arg_var_object_idx; /* -1 if none (var object for the argument scope) */
  27100. int arguments_var_idx; /* -1 if none */
  27101. int arguments_arg_idx; /* argument variable definition in argument scope,
  27102. -1 if none */
  27103. int func_var_idx; /* variable containing the current function (-1
  27104. if none, only used if is_func_expr is true) */
  27105. int eval_ret_idx; /* variable containing the return value of the eval, -1 if none */
  27106. int this_var_idx; /* variable containg the 'this' value, -1 if none */
  27107. int new_target_var_idx; /* variable containg the 'new.target' value, -1 if none */
  27108. int this_active_func_var_idx; /* variable containg the 'this.active_func' value, -1 if none */
  27109. int home_object_var_idx;
  27110. bool need_home_object;
  27111. int scope_level; /* index into fd->scopes if the current lexical scope */
  27112. int scope_first; /* index into vd->vars of first lexically scoped variable */
  27113. int scope_size; /* allocated size of fd->scopes array */
  27114. int scope_count; /* number of entries used in the fd->scopes array */
  27115. JSVarScope *scopes;
  27116. JSVarScope def_scope_array[4];
  27117. int body_scope; /* scope of the body of the function or eval */
  27118. int global_var_count;
  27119. int global_var_size;
  27120. JSGlobalVar *global_vars;
  27121. DynBuf byte_code;
  27122. int last_opcode_pos; /* -1 if no last opcode */
  27123. bool use_short_opcodes; /* true if short opcodes are used in byte_code */
  27124. LabelSlot *label_slots;
  27125. int label_size; /* allocated size for label_slots[] */
  27126. int label_count;
  27127. BlockEnv *top_break; /* break/continue label stack */
  27128. /* constant pool (strings, functions, numbers) */
  27129. JSValue *cpool;
  27130. int cpool_count;
  27131. int cpool_size;
  27132. /* list of variables in the closure */
  27133. int closure_var_count;
  27134. int closure_var_size;
  27135. JSClosureVar *closure_var;
  27136. JumpSlot *jump_slots;
  27137. int jump_size;
  27138. int jump_count;
  27139. SourceLocSlot *source_loc_slots;
  27140. int source_loc_size;
  27141. int source_loc_count;
  27142. int line_number_last;
  27143. int line_number_last_pc;
  27144. int col_number_last;
  27145. /* pc2line table */
  27146. JSAtom filename;
  27147. int line_num;
  27148. int col_num;
  27149. DynBuf pc2line;
  27150. char *source; /* raw source, utf-8 encoded */
  27151. int source_len;
  27152. JSModuleDef *module; /* != NULL when parsing a module */
  27153. bool has_await; /* true if await is used (used in module eval) */
  27154. } JSFunctionDef;
  27155. typedef struct JSToken {
  27156. int val;
  27157. int line_num; /* line number of token start */
  27158. int col_num; /* column number of token start */
  27159. const uint8_t *ptr;
  27160. union {
  27161. struct {
  27162. JSValue str;
  27163. int sep;
  27164. } str;
  27165. struct {
  27166. JSValue val;
  27167. } num;
  27168. struct {
  27169. JSAtom atom;
  27170. bool has_escape;
  27171. bool is_reserved;
  27172. } ident;
  27173. struct {
  27174. JSValue body;
  27175. JSValue flags;
  27176. } regexp;
  27177. } u;
  27178. } JSToken;
  27179. typedef struct JSParseState {
  27180. JSContext *ctx;
  27181. int last_line_num; /* line number of last token */
  27182. int last_col_num; /* column number of last token */
  27183. int line_num; /* line number of current offset */
  27184. int col_num; /* column number of current offset */
  27185. const char *filename;
  27186. JSToken token;
  27187. bool got_lf; /* true if got line feed before the current token */
  27188. const uint8_t *last_ptr;
  27189. const uint8_t *buf_start;
  27190. const uint8_t *buf_ptr;
  27191. const uint8_t *buf_end;
  27192. const uint8_t *eol; // most recently seen end-of-line character
  27193. const uint8_t *mark; // first token character, invariant: eol < mark
  27194. /* current function code */
  27195. JSFunctionDef *cur_func;
  27196. bool is_module; /* parsing a module */
  27197. bool allow_html_comments;
  27198. } JSParseState;
  27199. typedef struct JSOpCode {
  27200. #ifdef ENABLE_DUMPS // JS_DUMP_BYTECODE_*
  27201. const char *name;
  27202. #endif
  27203. uint8_t size; /* in bytes */
  27204. /* the opcodes remove n_pop items from the top of the stack, then
  27205. pushes n_push items */
  27206. uint8_t n_pop;
  27207. uint8_t n_push;
  27208. uint8_t fmt;
  27209. } JSOpCode;
  27210. static const JSOpCode opcode_info[OP_COUNT + (OP_TEMP_END - OP_TEMP_START)] = {
  27211. #define FMT(f)
  27212. #ifdef ENABLE_DUMPS // JS_DUMP_BYTECODE_*
  27213. #define DEF(id, size, n_pop, n_push, f) { #id, size, n_pop, n_push, OP_FMT_ ## f },
  27214. #else
  27215. #define DEF(id, size, n_pop, n_push, f) { size, n_pop, n_push, OP_FMT_ ## f },
  27216. #endif
  27217. /*
  27218. * QuickJS opcode definitions
  27219. *
  27220. * Copyright (c) 2017-2018 Fabrice Bellard
  27221. * Copyright (c) 2017-2018 Charlie Gordon
  27222. *
  27223. * Permission is hereby granted, free of charge, to any person obtaining a copy
  27224. * of this software and associated documentation files (the "Software"), to deal
  27225. * in the Software without restriction, including without limitation the rights
  27226. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  27227. * copies of the Software, and to permit persons to whom the Software is
  27228. * furnished to do so, subject to the following conditions:
  27229. *
  27230. * The above copyright notice and this permission notice shall be included in
  27231. * all copies or substantial portions of the Software.
  27232. *
  27233. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  27234. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  27235. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  27236. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  27237. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  27238. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  27239. * THE SOFTWARE.
  27240. */
  27241. #ifdef FMT
  27242. FMT(none)
  27243. FMT(none_int)
  27244. FMT(none_loc)
  27245. FMT(none_arg)
  27246. FMT(none_var_ref)
  27247. FMT(u8)
  27248. FMT(i8)
  27249. FMT(loc8)
  27250. FMT(const8)
  27251. FMT(label8)
  27252. FMT(u16)
  27253. FMT(i16)
  27254. FMT(label16)
  27255. FMT(npop)
  27256. FMT(npopx)
  27257. FMT(npop_u16)
  27258. FMT(loc)
  27259. FMT(arg)
  27260. FMT(var_ref)
  27261. FMT(u32)
  27262. FMT(u32x2)
  27263. FMT(i32)
  27264. FMT(const)
  27265. FMT(label)
  27266. FMT(atom)
  27267. FMT(atom_u8)
  27268. FMT(atom_u16)
  27269. FMT(atom_label_u8)
  27270. FMT(atom_label_u16)
  27271. FMT(label_u16)
  27272. #undef FMT
  27273. #endif /* FMT */
  27274. #ifdef DEF
  27275. #ifndef def
  27276. #define def(id, size, n_pop, n_push, f) DEF(id, size, n_pop, n_push, f)
  27277. #endif
  27278. DEF(invalid, 1, 0, 0, none) /* never emitted */
  27279. /* push values */
  27280. DEF( push_i32, 5, 0, 1, i32)
  27281. DEF( push_const, 5, 0, 1, const)
  27282. DEF( fclosure, 5, 0, 1, const) /* must follow push_const */
  27283. DEF(push_atom_value, 5, 0, 1, atom)
  27284. DEF( private_symbol, 5, 0, 1, atom)
  27285. DEF( undefined, 1, 0, 1, none)
  27286. DEF( null, 1, 0, 1, none)
  27287. DEF( push_this, 1, 0, 1, none) /* only used at the start of a function */
  27288. DEF( push_false, 1, 0, 1, none)
  27289. DEF( push_true, 1, 0, 1, none)
  27290. DEF( object, 1, 0, 1, none)
  27291. DEF( special_object, 2, 0, 1, u8) /* only used at the start of a function */
  27292. DEF( rest, 3, 0, 1, u16) /* only used at the start of a function */
  27293. DEF( drop, 1, 1, 0, none) /* a -> */
  27294. DEF( nip, 1, 2, 1, none) /* a b -> b */
  27295. DEF( nip1, 1, 3, 2, none) /* a b c -> b c */
  27296. DEF( dup, 1, 1, 2, none) /* a -> a a */
  27297. DEF( dup1, 1, 2, 3, none) /* a b -> a a b */
  27298. DEF( dup2, 1, 2, 4, none) /* a b -> a b a b */
  27299. DEF( dup3, 1, 3, 6, none) /* a b c -> a b c a b c */
  27300. DEF( insert2, 1, 2, 3, none) /* obj a -> a obj a (dup_x1) */
  27301. DEF( insert3, 1, 3, 4, none) /* obj prop a -> a obj prop a (dup_x2) */
  27302. DEF( insert4, 1, 4, 5, none) /* this obj prop a -> a this obj prop a */
  27303. DEF( perm3, 1, 3, 3, none) /* obj a b -> a obj b */
  27304. DEF( perm4, 1, 4, 4, none) /* obj prop a b -> a obj prop b */
  27305. DEF( perm5, 1, 5, 5, none) /* this obj prop a b -> a this obj prop b */
  27306. DEF( swap, 1, 2, 2, none) /* a b -> b a */
  27307. DEF( swap2, 1, 4, 4, none) /* a b c d -> c d a b */
  27308. DEF( rot3l, 1, 3, 3, none) /* x a b -> a b x */
  27309. DEF( rot3r, 1, 3, 3, none) /* a b x -> x a b */
  27310. DEF( rot4l, 1, 4, 4, none) /* x a b c -> a b c x */
  27311. DEF( rot5l, 1, 5, 5, none) /* x a b c d -> a b c d x */
  27312. DEF(call_constructor, 3, 2, 1, npop) /* func new.target args -> ret. arguments are not counted in n_pop */
  27313. DEF( call, 3, 1, 1, npop) /* arguments are not counted in n_pop */
  27314. DEF( tail_call, 3, 1, 0, npop) /* arguments are not counted in n_pop */
  27315. DEF( call_method, 3, 2, 1, npop) /* arguments are not counted in n_pop */
  27316. DEF(tail_call_method, 3, 2, 0, npop) /* arguments are not counted in n_pop */
  27317. DEF( array_from, 3, 0, 1, npop) /* arguments are not counted in n_pop */
  27318. DEF( apply, 3, 3, 1, u16)
  27319. DEF( return, 1, 1, 0, none)
  27320. DEF( return_undef, 1, 0, 0, none)
  27321. DEF(check_ctor_return, 1, 1, 2, none)
  27322. DEF( check_ctor, 1, 0, 0, none)
  27323. DEF( init_ctor, 1, 0, 1, none)
  27324. DEF( check_brand, 1, 2, 2, none) /* this_obj func -> this_obj func */
  27325. DEF( add_brand, 1, 2, 0, none) /* this_obj home_obj -> */
  27326. DEF( return_async, 1, 1, 0, none)
  27327. DEF( throw, 1, 1, 0, none)
  27328. DEF( throw_error, 6, 0, 0, atom_u8)
  27329. DEF( eval, 5, 1, 1, npop_u16) /* func args... -> ret_val */
  27330. DEF( apply_eval, 3, 2, 1, u16) /* func array -> ret_eval */
  27331. DEF( regexp, 1, 2, 1, none) /* create a RegExp object from the pattern and a
  27332. bytecode string */
  27333. DEF( get_super, 1, 1, 1, none)
  27334. DEF( import, 1, 1, 1, none) /* dynamic module import */
  27335. DEF( check_var, 5, 0, 1, atom) /* check if a variable exists */
  27336. DEF( get_var_undef, 5, 0, 1, atom) /* push undefined if the variable does not exist */
  27337. DEF( get_var, 5, 0, 1, atom) /* throw an exception if the variable does not exist */
  27338. DEF( put_var, 5, 1, 0, atom) /* must come after get_var */
  27339. DEF( put_var_init, 5, 1, 0, atom) /* must come after put_var. Used to initialize a global lexical variable */
  27340. DEF( put_var_strict, 5, 2, 0, atom) /* for strict mode variable write */
  27341. DEF( get_ref_value, 1, 2, 3, none)
  27342. DEF( put_ref_value, 1, 3, 0, none)
  27343. DEF( define_var, 6, 0, 0, atom_u8)
  27344. DEF(check_define_var, 6, 0, 0, atom_u8)
  27345. DEF( define_func, 6, 1, 0, atom_u8)
  27346. // order matters, see IC counterparts
  27347. DEF( get_field, 5, 1, 1, atom)
  27348. DEF( get_field2, 5, 1, 2, atom)
  27349. DEF( put_field, 5, 2, 0, atom)
  27350. DEF( get_private_field, 1, 2, 1, none) /* obj prop -> value */
  27351. DEF( put_private_field, 1, 3, 0, none) /* obj value prop -> */
  27352. DEF(define_private_field, 1, 3, 1, none) /* obj prop value -> obj */
  27353. DEF( get_array_el, 1, 2, 1, none)
  27354. DEF( get_array_el2, 1, 2, 2, none) /* obj prop -> obj value */
  27355. DEF( put_array_el, 1, 3, 0, none)
  27356. DEF(get_super_value, 1, 3, 1, none) /* this obj prop -> value */
  27357. DEF(put_super_value, 1, 4, 0, none) /* this obj prop value -> */
  27358. DEF( define_field, 5, 2, 1, atom)
  27359. DEF( set_name, 5, 1, 1, atom)
  27360. DEF(set_name_computed, 1, 2, 2, none)
  27361. DEF( set_proto, 1, 2, 1, none)
  27362. DEF(set_home_object, 1, 2, 2, none)
  27363. DEF(define_array_el, 1, 3, 2, none)
  27364. DEF( append, 1, 3, 2, none) /* append enumerated object, update length */
  27365. DEF(copy_data_properties, 2, 3, 3, u8)
  27366. DEF( define_method, 6, 2, 1, atom_u8)
  27367. DEF(define_method_computed, 2, 3, 1, u8) /* must come after define_method */
  27368. DEF( define_class, 6, 2, 2, atom_u8) /* parent ctor -> ctor proto */
  27369. DEF( define_class_computed, 6, 3, 3, atom_u8) /* field_name parent ctor -> field_name ctor proto (class with computed name) */
  27370. DEF( get_loc, 3, 0, 1, loc)
  27371. DEF( put_loc, 3, 1, 0, loc) /* must come after get_loc */
  27372. DEF( set_loc, 3, 1, 1, loc) /* must come after put_loc */
  27373. DEF( get_arg, 3, 0, 1, arg)
  27374. DEF( put_arg, 3, 1, 0, arg) /* must come after get_arg */
  27375. DEF( set_arg, 3, 1, 1, arg) /* must come after put_arg */
  27376. DEF( get_var_ref, 3, 0, 1, var_ref)
  27377. DEF( put_var_ref, 3, 1, 0, var_ref) /* must come after get_var_ref */
  27378. DEF( set_var_ref, 3, 1, 1, var_ref) /* must come after put_var_ref */
  27379. DEF(set_loc_uninitialized, 3, 0, 0, loc)
  27380. DEF( get_loc_check, 3, 0, 1, loc)
  27381. DEF( put_loc_check, 3, 1, 0, loc) /* must come after get_loc_check */
  27382. DEF( put_loc_check_init, 3, 1, 0, loc)
  27383. DEF(get_var_ref_check, 3, 0, 1, var_ref)
  27384. DEF(put_var_ref_check, 3, 1, 0, var_ref) /* must come after get_var_ref_check */
  27385. DEF(put_var_ref_check_init, 3, 1, 0, var_ref)
  27386. DEF( close_loc, 3, 0, 0, loc)
  27387. DEF( if_false, 5, 1, 0, label)
  27388. DEF( if_true, 5, 1, 0, label) /* must come after if_false */
  27389. DEF( goto, 5, 0, 0, label) /* must come after if_true */
  27390. DEF( catch, 5, 0, 1, label)
  27391. DEF( gosub, 5, 0, 0, label) /* used to execute the finally block */
  27392. DEF( ret, 1, 1, 0, none) /* used to return from the finally block */
  27393. DEF( nip_catch, 1, 2, 1, none) /* catch ... a -> a */
  27394. DEF( to_object, 1, 1, 1, none)
  27395. //DEF( to_string, 1, 1, 1, none)
  27396. DEF( to_propkey, 1, 1, 1, none)
  27397. DEF( to_propkey2, 1, 2, 2, none)
  27398. DEF( with_get_var, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */
  27399. DEF( with_put_var, 10, 2, 1, atom_label_u8) /* must be in the same order as scope_xxx */
  27400. DEF(with_delete_var, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */
  27401. DEF( with_make_ref, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */
  27402. DEF( with_get_ref, 10, 1, 0, atom_label_u8) /* must be in the same order as scope_xxx */
  27403. DEF(with_get_ref_undef, 10, 1, 0, atom_label_u8)
  27404. DEF( make_loc_ref, 7, 0, 2, atom_u16)
  27405. DEF( make_arg_ref, 7, 0, 2, atom_u16)
  27406. DEF(make_var_ref_ref, 7, 0, 2, atom_u16)
  27407. DEF( make_var_ref, 5, 0, 2, atom)
  27408. DEF( for_in_start, 1, 1, 1, none)
  27409. DEF( for_of_start, 1, 1, 3, none)
  27410. DEF(for_await_of_start, 1, 1, 3, none)
  27411. DEF( for_in_next, 1, 1, 3, none)
  27412. DEF( for_of_next, 2, 3, 5, u8)
  27413. DEF(iterator_check_object, 1, 1, 1, none)
  27414. DEF(iterator_get_value_done, 1, 1, 2, none)
  27415. DEF( iterator_close, 1, 3, 0, none)
  27416. DEF( iterator_next, 1, 4, 4, none)
  27417. DEF( iterator_call, 2, 4, 5, u8)
  27418. DEF( initial_yield, 1, 0, 0, none)
  27419. DEF( yield, 1, 1, 2, none)
  27420. DEF( yield_star, 1, 1, 2, none)
  27421. DEF(async_yield_star, 1, 1, 2, none)
  27422. DEF( await, 1, 1, 1, none)
  27423. /* arithmetic/logic operations */
  27424. DEF( neg, 1, 1, 1, none)
  27425. DEF( plus, 1, 1, 1, none)
  27426. DEF( dec, 1, 1, 1, none)
  27427. DEF( inc, 1, 1, 1, none)
  27428. DEF( post_dec, 1, 1, 2, none)
  27429. DEF( post_inc, 1, 1, 2, none)
  27430. DEF( dec_loc, 2, 0, 0, loc8)
  27431. DEF( inc_loc, 2, 0, 0, loc8)
  27432. DEF( add_loc, 2, 1, 0, loc8)
  27433. DEF( not, 1, 1, 1, none)
  27434. DEF( lnot, 1, 1, 1, none)
  27435. DEF( typeof, 1, 1, 1, none)
  27436. DEF( delete, 1, 2, 1, none)
  27437. DEF( delete_var, 5, 0, 1, atom)
  27438. /* warning: order matters (see js_parse_assign_expr) */
  27439. DEF( mul, 1, 2, 1, none)
  27440. DEF( div, 1, 2, 1, none)
  27441. DEF( mod, 1, 2, 1, none)
  27442. DEF( add, 1, 2, 1, none)
  27443. DEF( sub, 1, 2, 1, none)
  27444. DEF( shl, 1, 2, 1, none)
  27445. DEF( sar, 1, 2, 1, none)
  27446. DEF( shr, 1, 2, 1, none)
  27447. DEF( and, 1, 2, 1, none)
  27448. DEF( xor, 1, 2, 1, none)
  27449. DEF( or, 1, 2, 1, none)
  27450. DEF( pow, 1, 2, 1, none)
  27451. DEF( lt, 1, 2, 1, none)
  27452. DEF( lte, 1, 2, 1, none)
  27453. DEF( gt, 1, 2, 1, none)
  27454. DEF( gte, 1, 2, 1, none)
  27455. DEF( instanceof, 1, 2, 1, none)
  27456. DEF( in, 1, 2, 1, none)
  27457. DEF( eq, 1, 2, 1, none)
  27458. DEF( neq, 1, 2, 1, none)
  27459. DEF( strict_eq, 1, 2, 1, none)
  27460. DEF( strict_neq, 1, 2, 1, none)
  27461. DEF(is_undefined_or_null, 1, 1, 1, none)
  27462. DEF( private_in, 1, 2, 1, none)
  27463. /* must be the last non short and non temporary opcode */
  27464. DEF( nop, 1, 0, 0, none)
  27465. /* temporary opcodes: never emitted in the final bytecode */
  27466. def( enter_scope, 3, 0, 0, u16) /* emitted in phase 1, removed in phase 2 */
  27467. def( leave_scope, 3, 0, 0, u16) /* emitted in phase 1, removed in phase 2 */
  27468. def( label, 5, 0, 0, label) /* emitted in phase 1, removed in phase 3 */
  27469. def(scope_get_var_undef, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */
  27470. def( scope_get_var, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */
  27471. def( scope_put_var, 7, 1, 0, atom_u16) /* emitted in phase 1, removed in phase 2 */
  27472. def(scope_delete_var, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */
  27473. def( scope_make_ref, 11, 0, 2, atom_label_u16) /* emitted in phase 1, removed in phase 2 */
  27474. def( scope_get_ref, 7, 0, 2, atom_u16) /* emitted in phase 1, removed in phase 2 */
  27475. def(scope_put_var_init, 7, 0, 2, atom_u16) /* emitted in phase 1, removed in phase 2 */
  27476. def(scope_get_private_field, 7, 1, 1, atom_u16) /* obj -> value, emitted in phase 1, removed in phase 2 */
  27477. def(scope_get_private_field2, 7, 1, 2, atom_u16) /* obj -> obj value, emitted in phase 1, removed in phase 2 */
  27478. def(scope_put_private_field, 7, 2, 0, atom_u16) /* obj value ->, emitted in phase 1, removed in phase 2 */
  27479. def(scope_in_private_field, 7, 1, 1, atom_u16) /* obj -> res emitted in phase 1, removed in phase 2 */
  27480. def(get_field_opt_chain, 5, 1, 1, atom) /* emitted in phase 1, removed in phase 2 */
  27481. def(get_array_el_opt_chain, 1, 2, 1, none) /* emitted in phase 1, removed in phase 2 */
  27482. def( set_class_name, 5, 1, 1, u32) /* emitted in phase 1, removed in phase 2 */
  27483. def( source_loc, 9, 0, 0, u32x2) /* emitted in phase 1, removed in phase 3 */
  27484. DEF( push_minus1, 1, 0, 1, none_int)
  27485. DEF( push_0, 1, 0, 1, none_int)
  27486. DEF( push_1, 1, 0, 1, none_int)
  27487. DEF( push_2, 1, 0, 1, none_int)
  27488. DEF( push_3, 1, 0, 1, none_int)
  27489. DEF( push_4, 1, 0, 1, none_int)
  27490. DEF( push_5, 1, 0, 1, none_int)
  27491. DEF( push_6, 1, 0, 1, none_int)
  27492. DEF( push_7, 1, 0, 1, none_int)
  27493. DEF( push_i8, 2, 0, 1, i8)
  27494. DEF( push_i16, 3, 0, 1, i16)
  27495. DEF( push_const8, 2, 0, 1, const8)
  27496. DEF( fclosure8, 2, 0, 1, const8) /* must follow push_const8 */
  27497. DEF(push_empty_string, 1, 0, 1, none)
  27498. DEF( get_loc8, 2, 0, 1, loc8)
  27499. DEF( put_loc8, 2, 1, 0, loc8)
  27500. DEF( set_loc8, 2, 1, 1, loc8)
  27501. DEF( get_loc0_loc1, 1, 0, 2, none_loc)
  27502. DEF( get_loc0, 1, 0, 1, none_loc)
  27503. DEF( get_loc1, 1, 0, 1, none_loc)
  27504. DEF( get_loc2, 1, 0, 1, none_loc)
  27505. DEF( get_loc3, 1, 0, 1, none_loc)
  27506. DEF( put_loc0, 1, 1, 0, none_loc)
  27507. DEF( put_loc1, 1, 1, 0, none_loc)
  27508. DEF( put_loc2, 1, 1, 0, none_loc)
  27509. DEF( put_loc3, 1, 1, 0, none_loc)
  27510. DEF( set_loc0, 1, 1, 1, none_loc)
  27511. DEF( set_loc1, 1, 1, 1, none_loc)
  27512. DEF( set_loc2, 1, 1, 1, none_loc)
  27513. DEF( set_loc3, 1, 1, 1, none_loc)
  27514. DEF( get_arg0, 1, 0, 1, none_arg)
  27515. DEF( get_arg1, 1, 0, 1, none_arg)
  27516. DEF( get_arg2, 1, 0, 1, none_arg)
  27517. DEF( get_arg3, 1, 0, 1, none_arg)
  27518. DEF( put_arg0, 1, 1, 0, none_arg)
  27519. DEF( put_arg1, 1, 1, 0, none_arg)
  27520. DEF( put_arg2, 1, 1, 0, none_arg)
  27521. DEF( put_arg3, 1, 1, 0, none_arg)
  27522. DEF( set_arg0, 1, 1, 1, none_arg)
  27523. DEF( set_arg1, 1, 1, 1, none_arg)
  27524. DEF( set_arg2, 1, 1, 1, none_arg)
  27525. DEF( set_arg3, 1, 1, 1, none_arg)
  27526. DEF( get_var_ref0, 1, 0, 1, none_var_ref)
  27527. DEF( get_var_ref1, 1, 0, 1, none_var_ref)
  27528. DEF( get_var_ref2, 1, 0, 1, none_var_ref)
  27529. DEF( get_var_ref3, 1, 0, 1, none_var_ref)
  27530. DEF( put_var_ref0, 1, 1, 0, none_var_ref)
  27531. DEF( put_var_ref1, 1, 1, 0, none_var_ref)
  27532. DEF( put_var_ref2, 1, 1, 0, none_var_ref)
  27533. DEF( put_var_ref3, 1, 1, 0, none_var_ref)
  27534. DEF( set_var_ref0, 1, 1, 1, none_var_ref)
  27535. DEF( set_var_ref1, 1, 1, 1, none_var_ref)
  27536. DEF( set_var_ref2, 1, 1, 1, none_var_ref)
  27537. DEF( set_var_ref3, 1, 1, 1, none_var_ref)
  27538. DEF( get_length, 1, 1, 1, none)
  27539. DEF( if_false8, 2, 1, 0, label8)
  27540. DEF( if_true8, 2, 1, 0, label8) /* must come after if_false8 */
  27541. DEF( goto8, 2, 0, 0, label8) /* must come after if_true8 */
  27542. DEF( goto16, 3, 0, 0, label16)
  27543. DEF( call0, 1, 1, 1, npopx)
  27544. DEF( call1, 1, 1, 1, npopx)
  27545. DEF( call2, 1, 1, 1, npopx)
  27546. DEF( call3, 1, 1, 1, npopx)
  27547. DEF( is_undefined, 1, 1, 1, none)
  27548. DEF( is_null, 1, 1, 1, none)
  27549. DEF(typeof_is_undefined, 1, 1, 1, none)
  27550. DEF( typeof_is_function, 1, 1, 1, none)
  27551. #undef DEF
  27552. #undef def
  27553. #endif /* DEF */
  27554. #undef DEF
  27555. #undef FMT
  27556. };
  27557. /* After the final compilation pass, short opcodes are used. Their
  27558. opcodes overlap with the temporary opcodes which cannot appear in
  27559. the final bytecode. Their description is after the temporary
  27560. opcodes in opcode_info[]. */
  27561. #define short_opcode_info(op) \
  27562. opcode_info[(op) >= OP_TEMP_START ? \
  27563. (op) + (OP_TEMP_END - OP_TEMP_START) : (op)]
  27564. static __exception int next_token(JSParseState *s);
  27565. static void free_token(JSParseState *s, JSToken *token)
  27566. {
  27567. switch(token->val) {
  27568. case TOK_NUMBER:
  27569. JS_FreeValue(s->ctx, token->u.num.val);
  27570. break;
  27571. case TOK_STRING:
  27572. case TOK_TEMPLATE:
  27573. JS_FreeValue(s->ctx, token->u.str.str);
  27574. break;
  27575. case TOK_REGEXP:
  27576. JS_FreeValue(s->ctx, token->u.regexp.body);
  27577. JS_FreeValue(s->ctx, token->u.regexp.flags);
  27578. break;
  27579. case TOK_IDENT:
  27580. case TOK_PRIVATE_NAME:
  27581. JS_FreeAtom(s->ctx, token->u.ident.atom);
  27582. break;
  27583. default:
  27584. if (token->val >= TOK_FIRST_KEYWORD &&
  27585. token->val <= TOK_LAST_KEYWORD) {
  27586. JS_FreeAtom(s->ctx, token->u.ident.atom);
  27587. }
  27588. break;
  27589. }
  27590. }
  27591. static void __attribute((unused)) dump_token(JSParseState *s,
  27592. const JSToken *token)
  27593. {
  27594. printf("%d:%d ", token->line_num, token->col_num);
  27595. switch(token->val) {
  27596. case TOK_NUMBER:
  27597. {
  27598. double d;
  27599. JS_ToFloat64(s->ctx, &d, token->u.num.val); /* no exception possible */
  27600. printf("number: %.14g\n", d);
  27601. }
  27602. break;
  27603. case TOK_IDENT:
  27604. dump_atom:
  27605. {
  27606. char buf[ATOM_GET_STR_BUF_SIZE];
  27607. printf("ident: '%s'\n",
  27608. JS_AtomGetStr(s->ctx, buf, sizeof(buf), token->u.ident.atom));
  27609. }
  27610. break;
  27611. case TOK_STRING:
  27612. {
  27613. const char *str;
  27614. /* XXX: quote the string */
  27615. str = JS_ToCString(s->ctx, token->u.str.str);
  27616. printf("string: '%s'\n", str);
  27617. JS_FreeCString(s->ctx, str);
  27618. }
  27619. break;
  27620. case TOK_TEMPLATE:
  27621. {
  27622. const char *str;
  27623. str = JS_ToCString(s->ctx, token->u.str.str);
  27624. printf("template: `%s`\n", str);
  27625. JS_FreeCString(s->ctx, str);
  27626. }
  27627. break;
  27628. case TOK_REGEXP:
  27629. {
  27630. const char *str, *str2;
  27631. str = JS_ToCString(s->ctx, token->u.regexp.body);
  27632. str2 = JS_ToCString(s->ctx, token->u.regexp.flags);
  27633. printf("regexp: '%s' '%s'\n", str, str2);
  27634. JS_FreeCString(s->ctx, str);
  27635. JS_FreeCString(s->ctx, str2);
  27636. }
  27637. break;
  27638. case TOK_EOF:
  27639. printf("eof\n");
  27640. break;
  27641. default:
  27642. if (s->token.val >= TOK_NULL && s->token.val <= TOK_LAST_KEYWORD) {
  27643. goto dump_atom;
  27644. } else if (s->token.val >= 256) {
  27645. printf("token: %d\n", token->val);
  27646. } else {
  27647. printf("token: '%c'\n", token->val);
  27648. }
  27649. break;
  27650. }
  27651. }
  27652. int JS_PRINTF_FORMAT_ATTR(2, 3) js_parse_error(JSParseState *s, JS_PRINTF_FORMAT const char *fmt, ...)
  27653. {
  27654. JSContext *ctx = s->ctx;
  27655. va_list ap;
  27656. int backtrace_flags;
  27657. va_start(ap, fmt);
  27658. JS_ThrowError2(ctx, JS_SYNTAX_ERROR, false, fmt, ap);
  27659. va_end(ap);
  27660. backtrace_flags = 0;
  27661. if (s->cur_func && s->cur_func->backtrace_barrier)
  27662. backtrace_flags = JS_BACKTRACE_FLAG_SINGLE_LEVEL;
  27663. build_backtrace(ctx, ctx->rt->current_exception, JS_UNDEFINED, s->filename,
  27664. s->line_num, s->col_num, backtrace_flags);
  27665. return -1;
  27666. }
  27667. static int js_parse_expect(JSParseState *s, int tok)
  27668. {
  27669. char buf[ATOM_GET_STR_BUF_SIZE];
  27670. if (s->token.val == tok)
  27671. return next_token(s);
  27672. switch(s->token.val) {
  27673. case TOK_EOF:
  27674. return js_parse_error(s, "Unexpected end of input");
  27675. case TOK_NUMBER:
  27676. return js_parse_error(s, "Unexpected number");
  27677. case TOK_STRING:
  27678. return js_parse_error(s, "Unexpected string");
  27679. case TOK_TEMPLATE:
  27680. return js_parse_error(s, "Unexpected string template");
  27681. case TOK_REGEXP:
  27682. return js_parse_error(s, "Unexpected regexp");
  27683. case TOK_IDENT:
  27684. return js_parse_error(s, "Unexpected identifier '%s'",
  27685. JS_AtomGetStr(s->ctx, buf, sizeof(buf),
  27686. s->token.u.ident.atom));
  27687. case TOK_ERROR:
  27688. return js_parse_error(s, "Invalid or unexpected token");
  27689. default:
  27690. return js_parse_error(s, "Unexpected token '%.*s'",
  27691. (int)(s->buf_ptr - s->token.ptr),
  27692. (const char *)s->token.ptr);
  27693. }
  27694. }
  27695. static int js_parse_expect_semi(JSParseState *s)
  27696. {
  27697. if (s->token.val != ';') {
  27698. /* automatic insertion of ';' */
  27699. if (s->token.val == TOK_EOF || s->token.val == '}' || s->got_lf) {
  27700. return 0;
  27701. }
  27702. return js_parse_error(s, "expecting '%c'", ';');
  27703. }
  27704. return next_token(s);
  27705. }
  27706. static int js_parse_error_reserved_identifier(JSParseState *s)
  27707. {
  27708. char buf1[ATOM_GET_STR_BUF_SIZE];
  27709. return js_parse_error(s, "'%s' is a reserved identifier",
  27710. JS_AtomGetStr(s->ctx, buf1, sizeof(buf1),
  27711. s->token.u.ident.atom));
  27712. }
  27713. static __exception int js_parse_template_part(JSParseState *s,
  27714. const uint8_t *p)
  27715. {
  27716. const uint8_t *p_next;
  27717. uint32_t c;
  27718. StringBuffer b_s, *b = &b_s;
  27719. /* p points to the first byte of the template part */
  27720. if (string_buffer_init(s->ctx, b, 32))
  27721. goto fail;
  27722. for(;;) {
  27723. if (p >= s->buf_end)
  27724. goto unexpected_eof;
  27725. c = *p++;
  27726. if (c == '`') {
  27727. /* template end part */
  27728. break;
  27729. }
  27730. if (c == '$' && *p == '{') {
  27731. /* template start or middle part */
  27732. p++;
  27733. break;
  27734. }
  27735. if (c == '\\') {
  27736. if (string_buffer_putc8(b, c))
  27737. goto fail;
  27738. if (p >= s->buf_end)
  27739. goto unexpected_eof;
  27740. c = *p++;
  27741. }
  27742. /* newline sequences are normalized as single '\n' bytes */
  27743. if (c == '\r') {
  27744. if (*p == '\n')
  27745. p++;
  27746. c = '\n';
  27747. }
  27748. if (c == '\n') {
  27749. s->line_num++;
  27750. s->eol = &p[-1];
  27751. s->mark = p;
  27752. } else if (c >= 0x80) {
  27753. c = utf8_decode(p - 1, &p_next);
  27754. if (p_next == p) {
  27755. js_parse_error(s, "invalid UTF-8 sequence");
  27756. goto fail;
  27757. }
  27758. p = p_next;
  27759. }
  27760. if (string_buffer_putc(b, c))
  27761. goto fail;
  27762. }
  27763. s->token.val = TOK_TEMPLATE;
  27764. s->token.u.str.sep = c;
  27765. s->token.u.str.str = string_buffer_end(b);
  27766. s->buf_ptr = p;
  27767. return 0;
  27768. unexpected_eof:
  27769. js_parse_error(s, "unexpected end of string");
  27770. fail:
  27771. string_buffer_free(b);
  27772. return -1;
  27773. }
  27774. static __exception int js_parse_string(JSParseState *s, int sep,
  27775. bool do_throw, const uint8_t *p,
  27776. JSToken *token, const uint8_t **pp)
  27777. {
  27778. const uint8_t *p_next;
  27779. int ret;
  27780. uint32_t c;
  27781. StringBuffer b_s, *b = &b_s;
  27782. /* string */
  27783. if (string_buffer_init(s->ctx, b, 32))
  27784. goto fail;
  27785. for(;;) {
  27786. if (p >= s->buf_end)
  27787. goto invalid_char;
  27788. c = *p;
  27789. if (c < 0x20) {
  27790. if (sep == '`') {
  27791. if (c == '\r') {
  27792. if (p[1] == '\n')
  27793. p++;
  27794. c = '\n';
  27795. }
  27796. /* do not update s->line_num */
  27797. } else if (c == '\n' || c == '\r')
  27798. goto invalid_char;
  27799. }
  27800. p++;
  27801. if (c == sep)
  27802. break;
  27803. if (c == '$' && *p == '{' && sep == '`') {
  27804. /* template start or middle part */
  27805. p++;
  27806. break;
  27807. }
  27808. if (c == '\\') {
  27809. c = *p;
  27810. switch(c) {
  27811. case '\0':
  27812. if (p >= s->buf_end) {
  27813. if (sep != '`')
  27814. goto invalid_char;
  27815. if (do_throw)
  27816. js_parse_error(s, "Unexpected end of input");
  27817. goto fail;
  27818. }
  27819. p++;
  27820. break;
  27821. case '\'':
  27822. case '\"':
  27823. case '\\':
  27824. p++;
  27825. break;
  27826. case '\r': /* accept DOS and MAC newline sequences */
  27827. if (p[1] == '\n') {
  27828. p++;
  27829. }
  27830. /* fall thru */
  27831. case '\n':
  27832. /* ignore escaped newline sequence */
  27833. p++;
  27834. if (sep != '`') {
  27835. s->line_num++;
  27836. s->eol = &p[-1];
  27837. s->mark = p;
  27838. }
  27839. continue;
  27840. default:
  27841. if (c == '0' && !(p[1] >= '0' && p[1] <= '9')) {
  27842. /* accept isolated \0 */
  27843. p++;
  27844. c = '\0';
  27845. } else
  27846. if ((c >= '0' && c <= '9')
  27847. && (s->cur_func->is_strict_mode || sep == '`')) {
  27848. if (do_throw) {
  27849. js_parse_error(s, "%s are not allowed in %s",
  27850. (c >= '8') ? "\\8 and \\9" : "Octal escape sequences",
  27851. (sep == '`') ? "template strings" : "strict mode");
  27852. }
  27853. goto fail;
  27854. } else if (c >= 0x80) {
  27855. c = utf8_decode(p, &p_next);
  27856. if (p_next == p + 1) {
  27857. goto invalid_utf8;
  27858. }
  27859. p = p_next;
  27860. /* LS or PS are skipped */
  27861. if (c == CP_LS || c == CP_PS)
  27862. continue;
  27863. } else {
  27864. ret = lre_parse_escape(&p, true);
  27865. if (ret == -1) {
  27866. if (do_throw) {
  27867. js_parse_error(s, "Invalid %s escape sequence",
  27868. c == 'u' ? "Unicode" : "hexadecimal");
  27869. }
  27870. goto fail;
  27871. } else if (ret < 0) {
  27872. /* ignore the '\' (could output a warning) */
  27873. p++;
  27874. } else {
  27875. c = ret;
  27876. }
  27877. }
  27878. break;
  27879. }
  27880. } else if (c >= 0x80) {
  27881. c = utf8_decode(p - 1, &p_next);
  27882. if (p_next == p)
  27883. goto invalid_utf8;
  27884. p = p_next;
  27885. }
  27886. if (string_buffer_putc(b, c))
  27887. goto fail;
  27888. }
  27889. token->val = TOK_STRING;
  27890. token->u.str.sep = c;
  27891. token->u.str.str = string_buffer_end(b);
  27892. *pp = p;
  27893. return 0;
  27894. invalid_utf8:
  27895. if (do_throw)
  27896. js_parse_error(s, "invalid UTF-8 sequence");
  27897. goto fail;
  27898. invalid_char:
  27899. if (do_throw)
  27900. js_parse_error(s, "unexpected end of string");
  27901. fail:
  27902. string_buffer_free(b);
  27903. return -1;
  27904. }
  27905. static inline bool token_is_pseudo_keyword(JSParseState *s, JSAtom atom) {
  27906. return s->token.val == TOK_IDENT && s->token.u.ident.atom == atom &&
  27907. !s->token.u.ident.has_escape;
  27908. }
  27909. static __exception int js_parse_regexp(JSParseState *s)
  27910. {
  27911. const uint8_t *p, *p_next;
  27912. bool in_class;
  27913. StringBuffer b_s, *b = &b_s;
  27914. StringBuffer b2_s, *b2 = &b2_s;
  27915. uint32_t c;
  27916. p = s->buf_ptr;
  27917. p++;
  27918. in_class = false;
  27919. if (string_buffer_init(s->ctx, b, 32))
  27920. return -1;
  27921. if (string_buffer_init(s->ctx, b2, 1))
  27922. goto fail;
  27923. for(;;) {
  27924. if (p >= s->buf_end) {
  27925. eof_error:
  27926. js_parse_error(s, "unexpected end of regexp");
  27927. goto fail;
  27928. }
  27929. c = *p++;
  27930. if (c == '\n' || c == '\r') {
  27931. goto eol_error;
  27932. } else if (c == '/') {
  27933. if (!in_class)
  27934. break;
  27935. } else if (c == '[') {
  27936. in_class = true;
  27937. } else if (c == ']') {
  27938. /* XXX: incorrect as the first character in a class */
  27939. in_class = false;
  27940. } else if (c == '\\') {
  27941. if (string_buffer_putc8(b, c))
  27942. goto fail;
  27943. c = *p++;
  27944. if (c == '\n' || c == '\r')
  27945. goto eol_error;
  27946. else if (c == '\0' && p >= s->buf_end)
  27947. goto eof_error;
  27948. else if (c >= 0x80) {
  27949. c = utf8_decode(p - 1, &p_next);
  27950. if (p_next == p) {
  27951. goto invalid_utf8;
  27952. }
  27953. p = p_next;
  27954. if (c == CP_LS || c == CP_PS)
  27955. goto eol_error;
  27956. }
  27957. } else if (c >= 0x80) {
  27958. c = utf8_decode(p - 1, &p_next);
  27959. if (p_next == p) {
  27960. invalid_utf8:
  27961. js_parse_error(s, "invalid UTF-8 sequence");
  27962. goto fail;
  27963. }
  27964. p = p_next;
  27965. /* LS or PS are considered as line terminator */
  27966. if (c == CP_LS || c == CP_PS) {
  27967. eol_error:
  27968. js_parse_error(s, "unexpected line terminator in regexp");
  27969. goto fail;
  27970. }
  27971. }
  27972. if (string_buffer_putc(b, c))
  27973. goto fail;
  27974. }
  27975. /* flags */
  27976. for(;;) {
  27977. c = utf8_decode(p, &p_next);
  27978. /* no need to test for invalid UTF-8, 0xFFFD is not ident_next */
  27979. if (!lre_js_is_ident_next(c))
  27980. break;
  27981. if (string_buffer_putc(b2, c))
  27982. goto fail;
  27983. p = p_next;
  27984. }
  27985. s->token.val = TOK_REGEXP;
  27986. s->token.u.regexp.body = string_buffer_end(b);
  27987. s->token.u.regexp.flags = string_buffer_end(b2);
  27988. s->buf_ptr = p;
  27989. return 0;
  27990. fail:
  27991. string_buffer_free(b);
  27992. string_buffer_free(b2);
  27993. return -1;
  27994. }
  27995. static __exception int ident_realloc(JSContext *ctx, char **pbuf, size_t *psize,
  27996. char *static_buf)
  27997. {
  27998. char *buf, *new_buf;
  27999. size_t size, new_size;
  28000. buf = *pbuf;
  28001. size = *psize;
  28002. if (size >= (SIZE_MAX / 3) * 2)
  28003. new_size = SIZE_MAX;
  28004. else
  28005. new_size = size + (size >> 1);
  28006. if (buf == static_buf) {
  28007. new_buf = js_malloc(ctx, new_size);
  28008. if (!new_buf)
  28009. return -1;
  28010. memcpy(new_buf, buf, size);
  28011. } else {
  28012. new_buf = js_realloc(ctx, buf, new_size);
  28013. if (!new_buf)
  28014. return -1;
  28015. }
  28016. *pbuf = new_buf;
  28017. *psize = new_size;
  28018. return 0;
  28019. }
  28020. /* convert a TOK_IDENT to a keyword when needed */
  28021. static void update_token_ident(JSParseState *s)
  28022. {
  28023. if (s->token.u.ident.atom <= JS_ATOM_LAST_KEYWORD ||
  28024. (s->token.u.ident.atom <= JS_ATOM_LAST_STRICT_KEYWORD &&
  28025. s->cur_func->is_strict_mode) ||
  28026. (s->token.u.ident.atom == JS_ATOM_yield &&
  28027. ((s->cur_func->func_kind & JS_FUNC_GENERATOR) ||
  28028. (s->cur_func->func_type == JS_PARSE_FUNC_ARROW &&
  28029. !s->cur_func->in_function_body && s->cur_func->parent &&
  28030. (s->cur_func->parent->func_kind & JS_FUNC_GENERATOR)))) ||
  28031. (s->token.u.ident.atom == JS_ATOM_await &&
  28032. (s->is_module ||
  28033. (s->cur_func->func_kind & JS_FUNC_ASYNC) ||
  28034. s->cur_func->func_type == JS_PARSE_FUNC_CLASS_STATIC_INIT ||
  28035. (s->cur_func->func_type == JS_PARSE_FUNC_ARROW &&
  28036. !s->cur_func->in_function_body && s->cur_func->parent &&
  28037. ((s->cur_func->parent->func_kind & JS_FUNC_ASYNC) ||
  28038. s->cur_func->parent->func_type == JS_PARSE_FUNC_CLASS_STATIC_INIT))))) {
  28039. if (s->token.u.ident.has_escape) {
  28040. s->token.u.ident.is_reserved = true;
  28041. s->token.val = TOK_IDENT;
  28042. } else {
  28043. /* The keywords atoms are pre allocated */
  28044. s->token.val = s->token.u.ident.atom - 1 + TOK_FIRST_KEYWORD;
  28045. }
  28046. }
  28047. }
  28048. /* if the current token is an identifier or keyword, reparse it
  28049. according to the current function type */
  28050. static void reparse_ident_token(JSParseState *s)
  28051. {
  28052. if (s->token.val == TOK_IDENT ||
  28053. (s->token.val >= TOK_FIRST_KEYWORD &&
  28054. s->token.val <= TOK_LAST_KEYWORD)) {
  28055. s->token.val = TOK_IDENT;
  28056. s->token.u.ident.is_reserved = false;
  28057. update_token_ident(s);
  28058. }
  28059. }
  28060. /* 'c' is the first character. Return JS_ATOM_NULL in case of error */
  28061. static JSAtom parse_ident(JSParseState *s, const uint8_t **pp,
  28062. bool *pident_has_escape, int c, bool is_private)
  28063. {
  28064. const uint8_t *p, *p_next;
  28065. char ident_buf[128], *buf;
  28066. size_t ident_size, ident_pos;
  28067. JSAtom atom = JS_ATOM_NULL;
  28068. p = *pp;
  28069. buf = ident_buf;
  28070. ident_size = sizeof(ident_buf);
  28071. ident_pos = 0;
  28072. if (is_private)
  28073. buf[ident_pos++] = '#';
  28074. for(;;) {
  28075. if (c < 0x80) {
  28076. buf[ident_pos++] = c;
  28077. } else {
  28078. ident_pos += utf8_encode((uint8_t*)buf + ident_pos, c);
  28079. }
  28080. c = *p;
  28081. p_next = p + 1;
  28082. if (c == '\\' && *p_next == 'u') {
  28083. c = lre_parse_escape(&p_next, true);
  28084. *pident_has_escape = true;
  28085. } else if (c >= 0x80) {
  28086. c = utf8_decode(p, &p_next);
  28087. /* no need to test for invalid UTF-8, 0xFFFD is not ident_next */
  28088. }
  28089. if (!lre_js_is_ident_next(c))
  28090. break;
  28091. p = p_next;
  28092. if (unlikely(ident_pos >= ident_size - UTF8_CHAR_LEN_MAX)) {
  28093. if (ident_realloc(s->ctx, &buf, &ident_size, ident_buf))
  28094. goto done;
  28095. }
  28096. }
  28097. /* buf is pure ASCII or UTF-8 encoded */
  28098. atom = JS_NewAtomLen(s->ctx, buf, ident_pos);
  28099. done:
  28100. if (unlikely(buf != ident_buf))
  28101. js_free(s->ctx, buf);
  28102. *pp = p;
  28103. return atom;
  28104. }
  28105. static __exception int next_token(JSParseState *s)
  28106. {
  28107. const uint8_t *p, *p_next;
  28108. int c;
  28109. bool ident_has_escape;
  28110. JSAtom atom;
  28111. int flags, radix;
  28112. if (js_check_stack_overflow(s->ctx->rt, 1000)) {
  28113. JS_ThrowStackOverflow(s->ctx);
  28114. return -1;
  28115. }
  28116. free_token(s, &s->token);
  28117. p = s->last_ptr = s->buf_ptr;
  28118. s->got_lf = false;
  28119. s->last_line_num = s->token.line_num;
  28120. s->last_col_num = s->token.col_num;
  28121. redo:
  28122. s->token.line_num = s->line_num;
  28123. s->token.col_num = s->col_num;
  28124. s->token.ptr = p;
  28125. c = *p;
  28126. switch(c) {
  28127. case 0:
  28128. if (p >= s->buf_end) {
  28129. s->token.val = TOK_EOF;
  28130. } else {
  28131. goto def_token;
  28132. }
  28133. break;
  28134. case '`':
  28135. if (js_parse_template_part(s, p + 1))
  28136. goto fail;
  28137. p = s->buf_ptr;
  28138. break;
  28139. case '\'':
  28140. case '\"':
  28141. if (js_parse_string(s, c, true, p + 1, &s->token, &p))
  28142. goto fail;
  28143. break;
  28144. case '\r': /* accept DOS and MAC newline sequences */
  28145. if (p[1] == '\n') {
  28146. p++;
  28147. }
  28148. /* fall thru */
  28149. case '\n':
  28150. p++;
  28151. line_terminator:
  28152. s->eol = &p[-1];
  28153. s->mark = p;
  28154. s->got_lf = true;
  28155. s->line_num++;
  28156. goto redo;
  28157. case '\f':
  28158. case '\v':
  28159. case ' ':
  28160. case '\t':
  28161. s->mark = ++p;
  28162. goto redo;
  28163. case '/':
  28164. if (p[1] == '*') {
  28165. /* comment */
  28166. p += 2;
  28167. for(;;) {
  28168. if (*p == '\0' && p >= s->buf_end) {
  28169. js_parse_error(s, "unexpected end of comment");
  28170. goto fail;
  28171. }
  28172. if (p[0] == '*' && p[1] == '/') {
  28173. p += 2;
  28174. break;
  28175. }
  28176. if (*p == '\n') {
  28177. s->line_num++;
  28178. s->got_lf = true; /* considered as LF for ASI */
  28179. s->eol = p++;
  28180. s->mark = p;
  28181. } else if (*p == '\r') {
  28182. s->got_lf = true; /* considered as LF for ASI */
  28183. p++;
  28184. } else if (*p >= 0x80) {
  28185. c = utf8_decode(p, &p);
  28186. /* ignore invalid UTF-8 in comments */
  28187. if (c == CP_LS || c == CP_PS) {
  28188. s->got_lf = true; /* considered as LF for ASI */
  28189. }
  28190. } else {
  28191. p++;
  28192. }
  28193. }
  28194. s->mark = p;
  28195. goto redo;
  28196. } else if (p[1] == '/') {
  28197. /* line comment */
  28198. p += 2;
  28199. skip_line_comment:
  28200. for(;;) {
  28201. if (*p == '\0' && p >= s->buf_end)
  28202. break;
  28203. if (*p == '\r' || *p == '\n')
  28204. break;
  28205. if (*p >= 0x80) {
  28206. c = utf8_decode(p, &p);
  28207. /* ignore invalid UTF-8 in comments */
  28208. /* LS or PS are considered as line terminator */
  28209. if (c == CP_LS || c == CP_PS) {
  28210. break;
  28211. }
  28212. } else {
  28213. p++;
  28214. }
  28215. }
  28216. s->mark = p;
  28217. goto redo;
  28218. } else if (p[1] == '=') {
  28219. p += 2;
  28220. s->token.val = TOK_DIV_ASSIGN;
  28221. } else {
  28222. p++;
  28223. s->token.val = c;
  28224. }
  28225. break;
  28226. case '\\':
  28227. if (p[1] == 'u') {
  28228. const uint8_t *p1 = p + 1;
  28229. int c1 = lre_parse_escape(&p1, true);
  28230. if (c1 >= 0 && lre_js_is_ident_first(c1)) {
  28231. c = c1;
  28232. p = p1;
  28233. ident_has_escape = true;
  28234. goto has_ident;
  28235. } else {
  28236. /* XXX: syntax error? */
  28237. }
  28238. }
  28239. goto def_token;
  28240. case 'a': case 'b': case 'c': case 'd':
  28241. case 'e': case 'f': case 'g': case 'h':
  28242. case 'i': case 'j': case 'k': case 'l':
  28243. case 'm': case 'n': case 'o': case 'p':
  28244. case 'q': case 'r': case 's': case 't':
  28245. case 'u': case 'v': case 'w': case 'x':
  28246. case 'y': case 'z':
  28247. case 'A': case 'B': case 'C': case 'D':
  28248. case 'E': case 'F': case 'G': case 'H':
  28249. case 'I': case 'J': case 'K': case 'L':
  28250. case 'M': case 'N': case 'O': case 'P':
  28251. case 'Q': case 'R': case 'S': case 'T':
  28252. case 'U': case 'V': case 'W': case 'X':
  28253. case 'Y': case 'Z':
  28254. case '_':
  28255. case '$':
  28256. /* identifier */
  28257. s->mark = p;
  28258. p++;
  28259. ident_has_escape = false;
  28260. has_ident:
  28261. atom = parse_ident(s, &p, &ident_has_escape, c, false);
  28262. if (atom == JS_ATOM_NULL)
  28263. goto fail;
  28264. s->token.u.ident.atom = atom;
  28265. s->token.u.ident.has_escape = ident_has_escape;
  28266. s->token.u.ident.is_reserved = false;
  28267. s->token.val = TOK_IDENT;
  28268. update_token_ident(s);
  28269. break;
  28270. case '#':
  28271. /* private name */
  28272. {
  28273. p++;
  28274. c = *p;
  28275. p_next = p + 1;
  28276. if (c == '\\' && *p_next == 'u') {
  28277. c = lre_parse_escape(&p_next, true);
  28278. } else if (c >= 0x80) {
  28279. c = utf8_decode(p, &p_next);
  28280. if (p_next == p + 1)
  28281. goto invalid_utf8;
  28282. }
  28283. if (!lre_js_is_ident_first(c)) {
  28284. js_parse_error(s, "invalid first character of private name");
  28285. goto fail;
  28286. }
  28287. p = p_next;
  28288. ident_has_escape = false; /* not used */
  28289. atom = parse_ident(s, &p, &ident_has_escape, c, true);
  28290. if (atom == JS_ATOM_NULL)
  28291. goto fail;
  28292. s->token.u.ident.atom = atom;
  28293. s->token.val = TOK_PRIVATE_NAME;
  28294. }
  28295. break;
  28296. case '.':
  28297. if (p[1] == '.' && p[2] == '.') {
  28298. p += 3;
  28299. s->token.val = TOK_ELLIPSIS;
  28300. break;
  28301. }
  28302. if (p[1] >= '0' && p[1] <= '9') {
  28303. flags = ATOD_ACCEPT_UNDERSCORES | ATOD_ACCEPT_FLOAT;
  28304. radix = 10;
  28305. goto parse_number;
  28306. }
  28307. goto def_token;
  28308. case '0':
  28309. if (is_digit(p[1])) { /* handle legacy octal */
  28310. if (s->cur_func->is_strict_mode) {
  28311. js_parse_error(s, "Octal literals are not allowed in strict mode");
  28312. goto fail;
  28313. }
  28314. /* Legacy octal: no separators, no suffix, no floats,
  28315. base 8 unless non octal digits are detected */
  28316. flags = 0;
  28317. radix = 8;
  28318. while (is_digit(*p)) {
  28319. if (*p >= '8' && *p <= '9')
  28320. radix = 10;
  28321. p++;
  28322. }
  28323. p = s->token.ptr;
  28324. goto parse_number;
  28325. }
  28326. if (p[1] == '_') {
  28327. js_parse_error(s, "Numeric separator can not be used after leading 0");
  28328. goto fail;
  28329. }
  28330. flags = ATOD_ACCEPT_HEX_PREFIX | ATOD_ACCEPT_BIN_OCT |
  28331. ATOD_ACCEPT_FLOAT | ATOD_ACCEPT_UNDERSCORES | ATOD_ACCEPT_SUFFIX;
  28332. radix = 10;
  28333. goto parse_number;
  28334. case '1': case '2': case '3': case '4':
  28335. case '5': case '6': case '7': case '8':
  28336. case '9':
  28337. /* number */
  28338. {
  28339. JSValue ret;
  28340. const char *p1;
  28341. flags = ATOD_ACCEPT_FLOAT | ATOD_ACCEPT_UNDERSCORES | ATOD_ACCEPT_SUFFIX;
  28342. radix = 10;
  28343. parse_number:
  28344. p1 = (const char *)p;
  28345. ret = js_atof(s->ctx, p1, s->buf_end - p, &p1, radix, flags);
  28346. p = (const uint8_t *)p1;
  28347. if (JS_IsException(ret))
  28348. goto fail;
  28349. /* reject `10instanceof Number` */
  28350. if (JS_VALUE_IS_NAN(ret) ||
  28351. lre_js_is_ident_next(utf8_decode(p, &p_next))) {
  28352. JS_FreeValue(s->ctx, ret);
  28353. js_parse_error(s, "invalid number literal");
  28354. goto fail;
  28355. }
  28356. s->token.val = TOK_NUMBER;
  28357. s->token.u.num.val = ret;
  28358. }
  28359. break;
  28360. case '*':
  28361. if (p[1] == '=') {
  28362. p += 2;
  28363. s->token.val = TOK_MUL_ASSIGN;
  28364. } else if (p[1] == '*') {
  28365. if (p[2] == '=') {
  28366. p += 3;
  28367. s->token.val = TOK_POW_ASSIGN;
  28368. } else {
  28369. p += 2;
  28370. s->token.val = TOK_POW;
  28371. }
  28372. } else {
  28373. goto def_token;
  28374. }
  28375. break;
  28376. case '%':
  28377. if (p[1] == '=') {
  28378. p += 2;
  28379. s->token.val = TOK_MOD_ASSIGN;
  28380. } else {
  28381. goto def_token;
  28382. }
  28383. break;
  28384. case '+':
  28385. if (p[1] == '=') {
  28386. p += 2;
  28387. s->token.val = TOK_PLUS_ASSIGN;
  28388. } else if (p[1] == '+') {
  28389. p += 2;
  28390. s->token.val = TOK_INC;
  28391. } else {
  28392. goto def_token;
  28393. }
  28394. break;
  28395. case '-':
  28396. if (p[1] == '=') {
  28397. p += 2;
  28398. s->token.val = TOK_MINUS_ASSIGN;
  28399. } else if (p[1] == '-') {
  28400. if (s->allow_html_comments && p[2] == '>' &&
  28401. (s->got_lf || s->last_ptr == s->buf_start)) {
  28402. /* Annex B: `-->` at beginning of line is an html comment end.
  28403. It extends to the end of the line.
  28404. */
  28405. goto skip_line_comment;
  28406. }
  28407. p += 2;
  28408. s->token.val = TOK_DEC;
  28409. } else {
  28410. goto def_token;
  28411. }
  28412. break;
  28413. case '<':
  28414. if (p[1] == '=') {
  28415. p += 2;
  28416. s->token.val = TOK_LTE;
  28417. } else if (p[1] == '<') {
  28418. if (p[2] == '=') {
  28419. p += 3;
  28420. s->token.val = TOK_SHL_ASSIGN;
  28421. } else {
  28422. p += 2;
  28423. s->token.val = TOK_SHL;
  28424. }
  28425. } else if (s->allow_html_comments &&
  28426. p[1] == '!' && p[2] == '-' && p[3] == '-') {
  28427. /* Annex B: handle `<!--` single line html comments */
  28428. goto skip_line_comment;
  28429. } else {
  28430. goto def_token;
  28431. }
  28432. break;
  28433. case '>':
  28434. if (p[1] == '=') {
  28435. p += 2;
  28436. s->token.val = TOK_GTE;
  28437. } else if (p[1] == '>') {
  28438. if (p[2] == '>') {
  28439. if (p[3] == '=') {
  28440. p += 4;
  28441. s->token.val = TOK_SHR_ASSIGN;
  28442. } else {
  28443. p += 3;
  28444. s->token.val = TOK_SHR;
  28445. }
  28446. } else if (p[2] == '=') {
  28447. p += 3;
  28448. s->token.val = TOK_SAR_ASSIGN;
  28449. } else {
  28450. p += 2;
  28451. s->token.val = TOK_SAR;
  28452. }
  28453. } else {
  28454. goto def_token;
  28455. }
  28456. break;
  28457. case '=':
  28458. if (p[1] == '=') {
  28459. if (p[2] == '=') {
  28460. p += 3;
  28461. s->token.val = TOK_STRICT_EQ;
  28462. } else {
  28463. p += 2;
  28464. s->token.val = TOK_EQ;
  28465. }
  28466. } else if (p[1] == '>') {
  28467. p += 2;
  28468. s->token.val = TOK_ARROW;
  28469. } else {
  28470. goto def_token;
  28471. }
  28472. break;
  28473. case '!':
  28474. if (p[1] == '=') {
  28475. if (p[2] == '=') {
  28476. p += 3;
  28477. s->token.val = TOK_STRICT_NEQ;
  28478. } else {
  28479. p += 2;
  28480. s->token.val = TOK_NEQ;
  28481. }
  28482. } else {
  28483. goto def_token;
  28484. }
  28485. break;
  28486. case '&':
  28487. if (p[1] == '=') {
  28488. p += 2;
  28489. s->token.val = TOK_AND_ASSIGN;
  28490. } else if (p[1] == '&') {
  28491. if (p[2] == '=') {
  28492. p += 3;
  28493. s->token.val = TOK_LAND_ASSIGN;
  28494. } else {
  28495. p += 2;
  28496. s->token.val = TOK_LAND;
  28497. }
  28498. } else {
  28499. goto def_token;
  28500. }
  28501. break;
  28502. case '^':
  28503. if (p[1] == '=') {
  28504. p += 2;
  28505. s->token.val = TOK_XOR_ASSIGN;
  28506. } else {
  28507. goto def_token;
  28508. }
  28509. break;
  28510. case '|':
  28511. if (p[1] == '=') {
  28512. p += 2;
  28513. s->token.val = TOK_OR_ASSIGN;
  28514. } else if (p[1] == '|') {
  28515. if (p[2] == '=') {
  28516. p += 3;
  28517. s->token.val = TOK_LOR_ASSIGN;
  28518. } else {
  28519. p += 2;
  28520. s->token.val = TOK_LOR;
  28521. }
  28522. } else {
  28523. goto def_token;
  28524. }
  28525. break;
  28526. case '?':
  28527. if (p[1] == '?') {
  28528. if (p[2] == '=') {
  28529. p += 3;
  28530. s->token.val = TOK_DOUBLE_QUESTION_MARK_ASSIGN;
  28531. } else {
  28532. p += 2;
  28533. s->token.val = TOK_DOUBLE_QUESTION_MARK;
  28534. }
  28535. } else if (p[1] == '.' && !(p[2] >= '0' && p[2] <= '9')) {
  28536. p += 2;
  28537. s->token.val = TOK_QUESTION_MARK_DOT;
  28538. } else {
  28539. goto def_token;
  28540. }
  28541. break;
  28542. default:
  28543. if (c >= 0x80) { /* non-ASCII code-point */
  28544. c = utf8_decode(p, &p_next);
  28545. if (p_next == p + 1)
  28546. goto invalid_utf8;
  28547. p = p_next;
  28548. switch(c) {
  28549. case CP_PS:
  28550. case CP_LS:
  28551. /* XXX: should avoid incrementing line_number, but
  28552. needed to handle HTML comments */
  28553. goto line_terminator;
  28554. default:
  28555. if (lre_is_space(c)) {
  28556. s->mark = p;
  28557. goto redo;
  28558. } else if (lre_js_is_ident_first(c)) {
  28559. ident_has_escape = false;
  28560. goto has_ident;
  28561. } else {
  28562. js_parse_error(s, "unexpected character");
  28563. goto fail;
  28564. }
  28565. }
  28566. }
  28567. def_token:
  28568. s->token.val = c;
  28569. p++;
  28570. break;
  28571. }
  28572. s->token.col_num = max_int(1, s->mark - s->eol);
  28573. s->buf_ptr = p;
  28574. // dump_token(s, &s->token);
  28575. return 0;
  28576. invalid_utf8:
  28577. js_parse_error(s, "invalid UTF-8 sequence");
  28578. fail:
  28579. s->token.val = TOK_ERROR;
  28580. return -1;
  28581. }
  28582. static int json_parse_error(JSParseState *s, const uint8_t *curp, const char *msg)
  28583. {
  28584. const uint8_t *p, *line_start;
  28585. int position = curp - s->buf_start;
  28586. int line = 1;
  28587. for (line_start = p = s->buf_start; p < curp; p++) {
  28588. /* column count does not account for TABs nor wide characters */
  28589. if (*p == '\r' || *p == '\n') {
  28590. p += 1 + (p[0] == '\r' && p[1] == '\n');
  28591. line++;
  28592. line_start = p;
  28593. }
  28594. }
  28595. return js_parse_error(s, "%s in JSON at position %d (line %d column %d)",
  28596. msg, position, line, (int)(p - line_start) + 1);
  28597. }
  28598. static int json_parse_string(JSParseState *s, const uint8_t **pp)
  28599. {
  28600. const uint8_t *p, *p_next;
  28601. int i;
  28602. uint32_t c;
  28603. StringBuffer b_s, *b = &b_s;
  28604. if (string_buffer_init(s->ctx, b, 32))
  28605. goto fail;
  28606. p = *pp;
  28607. for(;;) {
  28608. if (p >= s->buf_end) {
  28609. goto end_of_input;
  28610. }
  28611. c = *p++;
  28612. if (c == '"')
  28613. break;
  28614. if (c < 0x20) {
  28615. json_parse_error(s, p - 1, "Bad control character in string literal");
  28616. goto fail;
  28617. }
  28618. if (c == '\\') {
  28619. c = *p++;
  28620. switch(c) {
  28621. case 'b': c = '\b'; break;
  28622. case 'f': c = '\f'; break;
  28623. case 'n': c = '\n'; break;
  28624. case 'r': c = '\r'; break;
  28625. case 't': c = '\t'; break;
  28626. case '\"': break;
  28627. case '\\': break;
  28628. case '/': break; /* for v8 compatibility */
  28629. case 'u':
  28630. c = 0;
  28631. for(i = 0; i < 4; i++) {
  28632. int h = from_hex(*p++);
  28633. if (h < 0) {
  28634. json_parse_error(s, p - 1, "Bad Unicode escape");
  28635. goto fail;
  28636. }
  28637. c = (c << 4) | h;
  28638. }
  28639. break;
  28640. default:
  28641. if (p > s->buf_end)
  28642. goto end_of_input;
  28643. json_parse_error(s, p - 1, "Bad escaped character");
  28644. goto fail;
  28645. }
  28646. } else
  28647. if (c >= 0x80) {
  28648. c = utf8_decode(p - 1, &p_next);
  28649. if (p_next == p) {
  28650. json_parse_error(s, p - 1, "Bad UTF-8 sequence");
  28651. goto fail;
  28652. }
  28653. p = p_next;
  28654. }
  28655. if (string_buffer_putc(b, c))
  28656. goto fail;
  28657. }
  28658. s->token.val = TOK_STRING;
  28659. s->token.u.str.sep = '"';
  28660. s->token.u.str.str = string_buffer_end(b);
  28661. *pp = p;
  28662. return 0;
  28663. end_of_input:
  28664. js_parse_error(s, "Unexpected end of JSON input");
  28665. fail:
  28666. string_buffer_free(b);
  28667. return -1;
  28668. }
  28669. static int json_parse_number(JSParseState *s, const uint8_t **pp)
  28670. {
  28671. const uint8_t *p = *pp;
  28672. const uint8_t *p_start = p;
  28673. if (*p == '+' || *p == '-')
  28674. p++;
  28675. if (!is_digit(*p))
  28676. return js_parse_error(s, "Unexpected token '%c'", *p_start);
  28677. if (p[0] == '0' && is_digit(p[1]))
  28678. return json_parse_error(s, p, "Unexpected number");
  28679. while (is_digit(*p))
  28680. p++;
  28681. if (*p == '.') {
  28682. p++;
  28683. if (!is_digit(*p))
  28684. return json_parse_error(s, p, "Unterminated fractional number");
  28685. while (is_digit(*p))
  28686. p++;
  28687. }
  28688. if (*p == 'e' || *p == 'E') {
  28689. p++;
  28690. if (*p == '+' || *p == '-')
  28691. p++;
  28692. if (!is_digit(*p))
  28693. return json_parse_error(s, p, "Exponent part is missing a number");
  28694. while (is_digit(*p))
  28695. p++;
  28696. }
  28697. s->token.val = TOK_NUMBER;
  28698. s->token.u.num.val = js_float64(strtod((const char *)p_start, NULL));
  28699. *pp = p;
  28700. return 0;
  28701. }
  28702. /* 'c' is the first character. Return JS_ATOM_NULL in case of error */
  28703. static JSAtom json_parse_ident(JSParseState *s, const uint8_t **pp, int c)
  28704. {
  28705. const uint8_t *p;
  28706. char ident_buf[128], *buf;
  28707. size_t ident_size, ident_pos;
  28708. JSAtom atom;
  28709. p = *pp;
  28710. buf = ident_buf;
  28711. ident_size = sizeof(ident_buf);
  28712. ident_pos = 0;
  28713. for(;;) {
  28714. buf[ident_pos++] = c;
  28715. c = *p;
  28716. if (c >= 128 ||
  28717. !((lre_id_continue_table_ascii[c >> 5] >> (c & 31)) & 1))
  28718. break;
  28719. p++;
  28720. if (unlikely(ident_pos >= ident_size - UTF8_CHAR_LEN_MAX)) {
  28721. if (ident_realloc(s->ctx, &buf, &ident_size, ident_buf)) {
  28722. atom = JS_ATOM_NULL;
  28723. goto done;
  28724. }
  28725. }
  28726. }
  28727. /* buf contains pure ASCII */
  28728. atom = JS_NewAtomLen(s->ctx, buf, ident_pos);
  28729. done:
  28730. if (unlikely(buf != ident_buf))
  28731. js_free(s->ctx, buf);
  28732. *pp = p;
  28733. return atom;
  28734. }
  28735. static __exception int json_next_token(JSParseState *s)
  28736. {
  28737. const uint8_t *p, *p_next;
  28738. int c;
  28739. JSAtom atom;
  28740. if (js_check_stack_overflow(s->ctx->rt, 1000)) {
  28741. JS_ThrowStackOverflow(s->ctx);
  28742. return -1;
  28743. }
  28744. free_token(s, &s->token);
  28745. p = s->last_ptr = s->buf_ptr;
  28746. s->last_line_num = s->token.line_num;
  28747. s->last_col_num = s->token.col_num;
  28748. redo:
  28749. s->token.line_num = s->line_num;
  28750. s->token.col_num = s->col_num;
  28751. s->token.ptr = p;
  28752. c = *p;
  28753. switch(c) {
  28754. case 0:
  28755. if (p >= s->buf_end) {
  28756. s->token.val = TOK_EOF;
  28757. } else {
  28758. goto def_token;
  28759. }
  28760. break;
  28761. case '\'':
  28762. /* JSON does not accept single quoted strings */
  28763. goto def_token;
  28764. case '\"':
  28765. p++;
  28766. if (json_parse_string(s, &p))
  28767. goto fail;
  28768. break;
  28769. case '\r': /* accept DOS and MAC newline sequences */
  28770. if (p[1] == '\n') {
  28771. p++;
  28772. }
  28773. /* fall thru */
  28774. case '\n':
  28775. s->line_num++;
  28776. s->eol = p++;
  28777. s->mark = p;
  28778. goto redo;
  28779. case '\f':
  28780. case '\v':
  28781. /* JSONWhitespace does not match <VT>, nor <FF> */
  28782. goto def_token;
  28783. case ' ':
  28784. case '\t':
  28785. p++;
  28786. s->mark = p;
  28787. goto redo;
  28788. case '/':
  28789. /* JSON does not accept comments */
  28790. goto def_token;
  28791. case 'a': case 'b': case 'c': case 'd':
  28792. case 'e': case 'f': case 'g': case 'h':
  28793. case 'i': case 'j': case 'k': case 'l':
  28794. case 'm': case 'n': case 'o': case 'p':
  28795. case 'q': case 'r': case 's': case 't':
  28796. case 'u': case 'v': case 'w': case 'x':
  28797. case 'y': case 'z':
  28798. case 'A': case 'B': case 'C': case 'D':
  28799. case 'E': case 'F': case 'G': case 'H':
  28800. case 'I': case 'J': case 'K': case 'L':
  28801. case 'M': case 'N': case 'O': case 'P':
  28802. case 'Q': case 'R': case 'S': case 'T':
  28803. case 'U': case 'V': case 'W': case 'X':
  28804. case 'Y': case 'Z':
  28805. case '_':
  28806. case '$':
  28807. /* identifier : only pure ascii characters are accepted */
  28808. p++;
  28809. atom = json_parse_ident(s, &p, c);
  28810. if (atom == JS_ATOM_NULL)
  28811. goto fail;
  28812. s->token.u.ident.atom = atom;
  28813. s->token.u.ident.has_escape = false;
  28814. s->token.u.ident.is_reserved = false;
  28815. s->token.val = TOK_IDENT;
  28816. break;
  28817. case '-':
  28818. if (!is_digit(p[1])) {
  28819. json_parse_error(s, p, "No number after minus sign");
  28820. goto fail;
  28821. }
  28822. goto parse_number;
  28823. case '0':
  28824. if (is_digit(p[1])) {
  28825. json_parse_error(s, p, "Unexpected number");
  28826. goto fail;
  28827. }
  28828. goto parse_number;
  28829. case '1': case '2': case '3': case '4':
  28830. case '5': case '6': case '7': case '8':
  28831. case '9':
  28832. /* number */
  28833. parse_number:
  28834. if (json_parse_number(s, &p))
  28835. goto fail;
  28836. break;
  28837. default:
  28838. if (c >= 0x80) {
  28839. c = utf8_decode(p, &p_next);
  28840. if (p_next == p + 1) {
  28841. js_parse_error(s, "Unexpected token '\\x%02x' in JSON", *p);
  28842. } else {
  28843. if (c > 0xFFFF) {
  28844. c = get_hi_surrogate(c);
  28845. }
  28846. js_parse_error(s, "Unexpected token '\\u%04x' in JSON", c);
  28847. }
  28848. goto fail;
  28849. }
  28850. def_token:
  28851. s->token.val = c;
  28852. p++;
  28853. break;
  28854. }
  28855. s->token.col_num = s->mark - s->eol;
  28856. s->buf_ptr = p;
  28857. // dump_token(s, &s->token);
  28858. return 0;
  28859. fail:
  28860. s->token.val = TOK_ERROR;
  28861. return -1;
  28862. }
  28863. /* only used for ':' and '=>', 'let' or 'function' look-ahead. *pp is
  28864. only set if TOK_IMPORT is returned */
  28865. /* XXX: handle all unicode cases */
  28866. static int simple_next_token(const uint8_t **pp, bool no_line_terminator)
  28867. {
  28868. const uint8_t *p;
  28869. uint32_t c;
  28870. /* skip spaces and comments */
  28871. p = *pp;
  28872. for (;;) {
  28873. switch(c = *p++) {
  28874. case '\r':
  28875. case '\n':
  28876. if (no_line_terminator)
  28877. return '\n';
  28878. continue;
  28879. case ' ':
  28880. case '\t':
  28881. case '\v':
  28882. case '\f':
  28883. continue;
  28884. case '/':
  28885. if (*p == '/') {
  28886. if (no_line_terminator)
  28887. return '\n';
  28888. while (*p && *p != '\r' && *p != '\n')
  28889. p++;
  28890. continue;
  28891. }
  28892. if (*p == '*') {
  28893. while (*++p) {
  28894. if ((*p == '\r' || *p == '\n') && no_line_terminator)
  28895. return '\n';
  28896. if (*p == '*' && p[1] == '/') {
  28897. p += 2;
  28898. break;
  28899. }
  28900. }
  28901. continue;
  28902. }
  28903. break;
  28904. case '=':
  28905. if (*p == '>')
  28906. return TOK_ARROW;
  28907. break;
  28908. default:
  28909. if (lre_js_is_ident_first(c)) {
  28910. if (c == 'i') {
  28911. if (p[0] == 'n' && !lre_js_is_ident_next(p[1])) {
  28912. return TOK_IN;
  28913. }
  28914. if (p[0] == 'm' && p[1] == 'p' && p[2] == 'o' &&
  28915. p[3] == 'r' && p[4] == 't' &&
  28916. !lre_js_is_ident_next(p[5])) {
  28917. *pp = p + 5;
  28918. return TOK_IMPORT;
  28919. }
  28920. } else if (c == 'o' && *p == 'f' && !lre_js_is_ident_next(p[1])) {
  28921. return TOK_OF;
  28922. } else if (c == 'e' &&
  28923. p[0] == 'x' && p[1] == 'p' && p[2] == 'o' &&
  28924. p[3] == 'r' && p[4] == 't' &&
  28925. !lre_js_is_ident_next(p[5])) {
  28926. *pp = p + 5;
  28927. return TOK_EXPORT;
  28928. } else if (c == 'f' && p[0] == 'u' && p[1] == 'n' &&
  28929. p[2] == 'c' && p[3] == 't' && p[4] == 'i' &&
  28930. p[5] == 'o' && p[6] == 'n' && !lre_js_is_ident_next(p[7])) {
  28931. return TOK_FUNCTION;
  28932. } else if (c == 'a' && p[0] == 'w' && p[1] == 'a' &&
  28933. p[2] == 'i' && p[3] == 't' && !lre_js_is_ident_next(p[4])) {
  28934. return TOK_AWAIT;
  28935. }
  28936. return TOK_IDENT;
  28937. }
  28938. break;
  28939. }
  28940. return c;
  28941. }
  28942. }
  28943. static int peek_token(JSParseState *s, bool no_line_terminator)
  28944. {
  28945. const uint8_t *p = s->buf_ptr;
  28946. return simple_next_token(&p, no_line_terminator);
  28947. }
  28948. static void skip_shebang(const uint8_t **pp, const uint8_t *buf_end)
  28949. {
  28950. const uint8_t *p = *pp;
  28951. int c;
  28952. if (p[0] == '#' && p[1] == '!') {
  28953. p += 2;
  28954. while (p < buf_end) {
  28955. if (*p == '\n' || *p == '\r') {
  28956. break;
  28957. } else if (*p >= 0x80) {
  28958. c = utf8_decode(p, &p);
  28959. /* purposely ignore UTF-8 encoding errors in this comment line */
  28960. if (c == CP_LS || c == CP_PS)
  28961. break;
  28962. } else {
  28963. p++;
  28964. }
  28965. }
  28966. *pp = p;
  28967. }
  28968. }
  28969. static inline int get_prev_opcode(JSFunctionDef *fd) {
  28970. if (fd->last_opcode_pos < 0)
  28971. return OP_invalid;
  28972. else
  28973. return fd->byte_code.buf[fd->last_opcode_pos];
  28974. }
  28975. static bool js_is_live_code(JSParseState *s) {
  28976. switch (get_prev_opcode(s->cur_func)) {
  28977. case OP_tail_call:
  28978. case OP_tail_call_method:
  28979. case OP_return:
  28980. case OP_return_undef:
  28981. case OP_return_async:
  28982. case OP_throw:
  28983. case OP_throw_error:
  28984. case OP_goto:
  28985. case OP_goto8:
  28986. case OP_goto16:
  28987. case OP_ret:
  28988. return false;
  28989. default:
  28990. return true;
  28991. }
  28992. }
  28993. static void emit_u8(JSParseState *s, uint8_t val)
  28994. {
  28995. dbuf_putc(&s->cur_func->byte_code, val);
  28996. }
  28997. static void emit_u16(JSParseState *s, uint16_t val)
  28998. {
  28999. dbuf_put_u16(&s->cur_func->byte_code, val);
  29000. }
  29001. static void emit_u32(JSParseState *s, uint32_t val)
  29002. {
  29003. dbuf_put_u32(&s->cur_func->byte_code, val);
  29004. }
  29005. static void emit_source_loc(JSParseState *s)
  29006. {
  29007. JSFunctionDef *fd = s->cur_func;
  29008. DynBuf *bc = &fd->byte_code;
  29009. dbuf_putc(bc, OP_source_loc);
  29010. dbuf_put_u32(bc, s->token.line_num);
  29011. dbuf_put_u32(bc, s->token.col_num);
  29012. }
  29013. static void emit_op(JSParseState *s, uint8_t val)
  29014. {
  29015. JSFunctionDef *fd = s->cur_func;
  29016. DynBuf *bc = &fd->byte_code;
  29017. fd->last_opcode_pos = bc->size;
  29018. dbuf_putc(bc, val);
  29019. }
  29020. static void emit_atom(JSParseState *s, JSAtom name)
  29021. {
  29022. emit_u32(s, JS_DupAtom(s->ctx, name));
  29023. }
  29024. static int update_label(JSFunctionDef *s, int label, int delta)
  29025. {
  29026. LabelSlot *ls;
  29027. assert(label >= 0 && label < s->label_count);
  29028. ls = &s->label_slots[label];
  29029. ls->ref_count += delta;
  29030. assert(ls->ref_count >= 0);
  29031. return ls->ref_count;
  29032. }
  29033. static int new_label_fd(JSFunctionDef *fd, int label)
  29034. {
  29035. LabelSlot *ls;
  29036. if (label < 0) {
  29037. if (js_resize_array(fd->ctx, (void *)&fd->label_slots,
  29038. sizeof(fd->label_slots[0]),
  29039. &fd->label_size, fd->label_count + 1))
  29040. return -1;
  29041. label = fd->label_count++;
  29042. ls = &fd->label_slots[label];
  29043. ls->ref_count = 0;
  29044. ls->pos = -1;
  29045. ls->pos2 = -1;
  29046. ls->addr = -1;
  29047. ls->first_reloc = NULL;
  29048. }
  29049. return label;
  29050. }
  29051. static int new_label(JSParseState *s)
  29052. {
  29053. return new_label_fd(s->cur_func, -1);
  29054. }
  29055. /* don't update the last opcode and don't emit line number info */
  29056. static void emit_label_raw(JSParseState *s, int label)
  29057. {
  29058. emit_u8(s, OP_label);
  29059. emit_u32(s, label);
  29060. s->cur_func->label_slots[label].pos = s->cur_func->byte_code.size;
  29061. }
  29062. /* return the label ID offset */
  29063. static int emit_label(JSParseState *s, int label)
  29064. {
  29065. if (label >= 0) {
  29066. emit_op(s, OP_label);
  29067. emit_u32(s, label);
  29068. s->cur_func->label_slots[label].pos = s->cur_func->byte_code.size;
  29069. return s->cur_func->byte_code.size - 4;
  29070. } else {
  29071. return -1;
  29072. }
  29073. }
  29074. /* return label or -1 if dead code */
  29075. static int emit_goto(JSParseState *s, int opcode, int label)
  29076. {
  29077. if (js_is_live_code(s)) {
  29078. if (label < 0)
  29079. label = new_label(s);
  29080. emit_op(s, opcode);
  29081. emit_u32(s, label);
  29082. s->cur_func->label_slots[label].ref_count++;
  29083. return label;
  29084. }
  29085. return -1;
  29086. }
  29087. /* return the constant pool index. 'val' is not duplicated. */
  29088. static int cpool_add(JSParseState *s, JSValue val)
  29089. {
  29090. JSFunctionDef *fd = s->cur_func;
  29091. if (js_resize_array(s->ctx, (void *)&fd->cpool, sizeof(fd->cpool[0]),
  29092. &fd->cpool_size, fd->cpool_count + 1))
  29093. return -1;
  29094. fd->cpool[fd->cpool_count++] = val;
  29095. return fd->cpool_count - 1;
  29096. }
  29097. static __exception int emit_push_const(JSParseState *s, JSValue val,
  29098. bool as_atom)
  29099. {
  29100. int idx;
  29101. if (JS_VALUE_GET_TAG(val) == JS_TAG_STRING && as_atom) {
  29102. JSAtom atom;
  29103. /* warning: JS_NewAtomStr frees the string value */
  29104. js_dup(val);
  29105. atom = JS_NewAtomStr(s->ctx, JS_VALUE_GET_STRING(val));
  29106. if (atom != JS_ATOM_NULL && !__JS_AtomIsTaggedInt(atom)) {
  29107. emit_op(s, OP_push_atom_value);
  29108. emit_u32(s, atom);
  29109. return 0;
  29110. }
  29111. }
  29112. idx = cpool_add(s, js_dup(val));
  29113. if (idx < 0)
  29114. return -1;
  29115. emit_op(s, OP_push_const);
  29116. emit_u32(s, idx);
  29117. return 0;
  29118. }
  29119. // perl hash; variation of k&r hash with a different magic multiplier
  29120. // and a final shuffle to improve distribution of the low-order bits
  29121. static uint32_t hash_bytes(uint32_t h, const void *b, size_t n)
  29122. {
  29123. const char *p;
  29124. for (p = b; p < (char *)b + n; p++)
  29125. h = 33*h + *p;
  29126. h += h >> 5;
  29127. return h;
  29128. }
  29129. static uint32_t hash_atom(JSAtom atom)
  29130. {
  29131. return hash_bytes(0, &atom, sizeof(atom));
  29132. }
  29133. // caveat emptor: the table size must be a power of two in order for
  29134. // masking to work, and the load factor constant must be an odd number (5)
  29135. //
  29136. // f(n)=n+n/t is used to estimate the load factor but changing t to an
  29137. // even number introduces gaps in the output of f, sometimes "jumping"
  29138. // over the next power of two; it's at powers of two when the hash table
  29139. // must be resized
  29140. static int update_var_htab(JSContext *ctx, JSFunctionDef *fd)
  29141. {
  29142. uint32_t i, j, k, m, *p;
  29143. if (fd->var_count < 27) // 27 + 27/5 == 32
  29144. return 0;
  29145. k = fd->var_count - 1;
  29146. m = fd->var_count + fd->var_count/5;
  29147. if (m & (m - 1)) // unless power of two
  29148. goto insert;
  29149. m *= 2;
  29150. p = js_realloc(ctx, fd->vars_htab, m * sizeof(*fd->vars_htab));
  29151. if (!p)
  29152. return -1;
  29153. for (i = 0; i < m; i++)
  29154. p[i] = UINT32_MAX;
  29155. fd->vars_htab = p;
  29156. k = 0;
  29157. m--;
  29158. insert:
  29159. m = UINT32_MAX >> clz32(m);
  29160. do {
  29161. i = hash_atom(fd->vars[k].var_name);
  29162. j = 1;
  29163. for (;;) {
  29164. p = &fd->vars_htab[i & m];
  29165. if (*p == UINT32_MAX)
  29166. break;
  29167. i += j;
  29168. j += 1; // quadratic probing
  29169. }
  29170. *p = k++;
  29171. } while (k < (uint32_t)fd->var_count);
  29172. return 0;
  29173. }
  29174. static int find_var_htab(JSFunctionDef *fd, JSAtom var_name)
  29175. {
  29176. uint32_t i, j, m, *p;
  29177. i = hash_atom(var_name);
  29178. j = 1;
  29179. m = fd->var_count + fd->var_count/5;
  29180. m = UINT32_MAX >> clz32(m);
  29181. for (;;) {
  29182. p = &fd->vars_htab[i & m];
  29183. if (*p == UINT32_MAX)
  29184. return -1;
  29185. if (fd->vars[*p].var_name == var_name)
  29186. return *p;
  29187. i += j;
  29188. j += 1; // quadratic probing
  29189. }
  29190. return -1; // pacify compiler
  29191. }
  29192. /* return the variable index or -1 if not found,
  29193. add ARGUMENT_VAR_OFFSET for argument variables */
  29194. static int find_arg(JSContext *ctx, JSFunctionDef *fd, JSAtom name)
  29195. {
  29196. int i;
  29197. for(i = fd->arg_count; i-- > 0;) {
  29198. if (fd->args[i].var_name == name)
  29199. return i | ARGUMENT_VAR_OFFSET;
  29200. }
  29201. return -1;
  29202. }
  29203. static int find_var(JSContext *ctx, JSFunctionDef *fd, JSAtom name)
  29204. {
  29205. JSVarDef *vd;
  29206. int i;
  29207. if (fd->vars_htab) {
  29208. i = find_var_htab(fd, name);
  29209. if (i == -1)
  29210. goto not_found;
  29211. vd = &fd->vars[i];
  29212. if (fd->vars[i].scope_level == 0)
  29213. return i;
  29214. }
  29215. for(i = fd->var_count; i-- > 0;) {
  29216. vd = &fd->vars[i];
  29217. if (vd->var_name == name)
  29218. if (vd->scope_level == 0)
  29219. return i;
  29220. }
  29221. not_found:
  29222. return find_arg(ctx, fd, name);
  29223. }
  29224. /* find a variable declaration in a given scope */
  29225. static int find_var_in_scope(JSContext *ctx, JSFunctionDef *fd,
  29226. JSAtom name, int scope_level)
  29227. {
  29228. int scope_idx;
  29229. for(scope_idx = fd->scopes[scope_level].first; scope_idx >= 0;
  29230. scope_idx = fd->vars[scope_idx].scope_next) {
  29231. if (fd->vars[scope_idx].scope_level != scope_level)
  29232. break;
  29233. if (fd->vars[scope_idx].var_name == name)
  29234. return scope_idx;
  29235. }
  29236. return -1;
  29237. }
  29238. /* return true if scope == parent_scope or if scope is a child of
  29239. parent_scope */
  29240. static bool is_child_scope(JSContext *ctx, JSFunctionDef *fd,
  29241. int scope, int parent_scope)
  29242. {
  29243. while (scope >= 0) {
  29244. if (scope == parent_scope)
  29245. return true;
  29246. scope = fd->scopes[scope].parent;
  29247. }
  29248. return false;
  29249. }
  29250. /* find a 'var' declaration in the same scope or a child scope */
  29251. static int find_var_in_child_scope(JSContext *ctx, JSFunctionDef *fd,
  29252. JSAtom name, int scope_level)
  29253. {
  29254. int i;
  29255. for(i = 0; i < fd->var_count; i++) {
  29256. JSVarDef *vd = &fd->vars[i];
  29257. if (vd->var_name == name && vd->scope_level == 0) {
  29258. if (is_child_scope(ctx, fd, vd->scope_next,
  29259. scope_level))
  29260. return i;
  29261. }
  29262. }
  29263. return -1;
  29264. }
  29265. static JSGlobalVar *find_global_var(JSFunctionDef *fd, JSAtom name)
  29266. {
  29267. int i;
  29268. for(i = 0; i < fd->global_var_count; i++) {
  29269. JSGlobalVar *hf = &fd->global_vars[i];
  29270. if (hf->var_name == name)
  29271. return hf;
  29272. }
  29273. return NULL;
  29274. }
  29275. static JSGlobalVar *find_lexical_global_var(JSFunctionDef *fd, JSAtom name)
  29276. {
  29277. JSGlobalVar *hf = find_global_var(fd, name);
  29278. if (hf && hf->is_lexical)
  29279. return hf;
  29280. else
  29281. return NULL;
  29282. }
  29283. static int find_lexical_decl(JSContext *ctx, JSFunctionDef *fd, JSAtom name,
  29284. int scope_idx, bool check_catch_var)
  29285. {
  29286. while (scope_idx >= 0) {
  29287. JSVarDef *vd = &fd->vars[scope_idx];
  29288. if (vd->var_name == name &&
  29289. (vd->is_lexical || (vd->var_kind == JS_VAR_CATCH &&
  29290. check_catch_var)))
  29291. return scope_idx;
  29292. scope_idx = vd->scope_next;
  29293. }
  29294. if (fd->is_eval && fd->eval_type == JS_EVAL_TYPE_GLOBAL) {
  29295. if (find_lexical_global_var(fd, name))
  29296. return GLOBAL_VAR_OFFSET;
  29297. }
  29298. return -1;
  29299. }
  29300. static int push_scope(JSParseState *s) {
  29301. if (s->cur_func) {
  29302. JSFunctionDef *fd = s->cur_func;
  29303. int scope = fd->scope_count;
  29304. /* XXX: should check for scope overflow */
  29305. if ((fd->scope_count + 1) > fd->scope_size) {
  29306. int new_size;
  29307. size_t slack;
  29308. JSVarScope *new_buf;
  29309. /* XXX: potential arithmetic overflow */
  29310. new_size = max_int(fd->scope_count + 1, fd->scope_size * 3 / 2);
  29311. if (fd->scopes == fd->def_scope_array) {
  29312. new_buf = js_realloc2(s->ctx, NULL, new_size * sizeof(*fd->scopes), &slack);
  29313. if (!new_buf)
  29314. return -1;
  29315. memcpy(new_buf, fd->scopes, fd->scope_count * sizeof(*fd->scopes));
  29316. } else {
  29317. new_buf = js_realloc2(s->ctx, fd->scopes, new_size * sizeof(*fd->scopes), &slack);
  29318. if (!new_buf)
  29319. return -1;
  29320. }
  29321. new_size += slack / sizeof(*new_buf);
  29322. fd->scopes = new_buf;
  29323. fd->scope_size = new_size;
  29324. }
  29325. fd->scope_count++;
  29326. fd->scopes[scope].parent = fd->scope_level;
  29327. fd->scopes[scope].first = fd->scope_first;
  29328. emit_op(s, OP_enter_scope);
  29329. emit_u16(s, scope);
  29330. return fd->scope_level = scope;
  29331. }
  29332. return 0;
  29333. }
  29334. static int get_first_lexical_var(JSFunctionDef *fd, int scope)
  29335. {
  29336. while (scope >= 0) {
  29337. int scope_idx = fd->scopes[scope].first;
  29338. if (scope_idx >= 0)
  29339. return scope_idx;
  29340. scope = fd->scopes[scope].parent;
  29341. }
  29342. return -1;
  29343. }
  29344. static void pop_scope(JSParseState *s) {
  29345. if (s->cur_func) {
  29346. /* disable scoped variables */
  29347. JSFunctionDef *fd = s->cur_func;
  29348. int scope = fd->scope_level;
  29349. emit_op(s, OP_leave_scope);
  29350. emit_u16(s, scope);
  29351. fd->scope_level = fd->scopes[scope].parent;
  29352. fd->scope_first = get_first_lexical_var(fd, fd->scope_level);
  29353. }
  29354. }
  29355. static void close_scopes(JSParseState *s, int scope, int scope_stop)
  29356. {
  29357. while (scope > scope_stop) {
  29358. emit_op(s, OP_leave_scope);
  29359. emit_u16(s, scope);
  29360. scope = s->cur_func->scopes[scope].parent;
  29361. }
  29362. }
  29363. /* return the variable index or -1 if error */
  29364. static int add_var(JSContext *ctx, JSFunctionDef *fd, JSAtom name)
  29365. {
  29366. JSVarDef *vd;
  29367. /* the local variable indexes are currently stored on 16 bits */
  29368. if (fd->var_count >= JS_MAX_LOCAL_VARS) {
  29369. // XXX: add_var() should take JSParseState *s and use js_parse_error
  29370. JS_ThrowSyntaxError(ctx, "too many variables declared (only %d allowed)",
  29371. JS_MAX_LOCAL_VARS - 1);
  29372. return -1;
  29373. }
  29374. if (js_resize_array(ctx, (void **)&fd->vars, sizeof(fd->vars[0]),
  29375. &fd->var_size, fd->var_count + 1))
  29376. return -1;
  29377. vd = &fd->vars[fd->var_count++];
  29378. memset(vd, 0, sizeof(*vd));
  29379. vd->var_name = JS_DupAtom(ctx, name);
  29380. vd->func_pool_idx = -1;
  29381. if (update_var_htab(ctx, fd))
  29382. return -1;
  29383. return fd->var_count - 1;
  29384. }
  29385. static int add_scope_var(JSContext *ctx, JSFunctionDef *fd, JSAtom name,
  29386. JSVarKindEnum var_kind)
  29387. {
  29388. int idx = add_var(ctx, fd, name);
  29389. if (idx >= 0) {
  29390. JSVarDef *vd = &fd->vars[idx];
  29391. vd->var_kind = var_kind;
  29392. vd->scope_level = fd->scope_level;
  29393. vd->scope_next = fd->scope_first;
  29394. fd->scopes[fd->scope_level].first = idx;
  29395. fd->scope_first = idx;
  29396. }
  29397. return idx;
  29398. }
  29399. static int add_func_var(JSContext *ctx, JSFunctionDef *fd, JSAtom name)
  29400. {
  29401. int idx = fd->func_var_idx;
  29402. if (idx < 0 && (idx = add_var(ctx, fd, name)) >= 0) {
  29403. fd->func_var_idx = idx;
  29404. fd->vars[idx].var_kind = JS_VAR_FUNCTION_NAME;
  29405. if (fd->is_strict_mode)
  29406. fd->vars[idx].is_const = true;
  29407. }
  29408. return idx;
  29409. }
  29410. static int add_arguments_var(JSContext *ctx, JSFunctionDef *fd)
  29411. {
  29412. int idx = fd->arguments_var_idx;
  29413. if (idx < 0 && (idx = add_var(ctx, fd, JS_ATOM_arguments)) >= 0) {
  29414. fd->arguments_var_idx = idx;
  29415. }
  29416. return idx;
  29417. }
  29418. /* add an argument definition in the argument scope. Only needed when
  29419. "eval()" may be called in the argument scope. Return 0 if OK. */
  29420. static int add_arguments_arg(JSContext *ctx, JSFunctionDef *fd)
  29421. {
  29422. int idx;
  29423. if (fd->arguments_arg_idx < 0) {
  29424. idx = find_var_in_scope(ctx, fd, JS_ATOM_arguments, ARG_SCOPE_INDEX);
  29425. if (idx < 0) {
  29426. /* XXX: the scope links are not fully updated. May be an
  29427. issue if there are child scopes of the argument
  29428. scope */
  29429. idx = add_var(ctx, fd, JS_ATOM_arguments);
  29430. if (idx < 0)
  29431. return -1;
  29432. fd->vars[idx].scope_next = fd->scopes[ARG_SCOPE_INDEX].first;
  29433. fd->scopes[ARG_SCOPE_INDEX].first = idx;
  29434. fd->vars[idx].scope_level = ARG_SCOPE_INDEX;
  29435. fd->vars[idx].is_lexical = true;
  29436. fd->arguments_arg_idx = idx;
  29437. }
  29438. }
  29439. return 0;
  29440. }
  29441. static int add_arg(JSContext *ctx, JSFunctionDef *fd, JSAtom name)
  29442. {
  29443. JSVarDef *vd;
  29444. /* the local variable indexes are currently stored on 16 bits */
  29445. if (fd->arg_count >= JS_MAX_LOCAL_VARS) {
  29446. // XXX: add_arg() should take JSParseState *s and use js_parse_error
  29447. JS_ThrowSyntaxError(ctx, "too many parameters in function definition (only %d allowed)",
  29448. JS_MAX_LOCAL_VARS - 1);
  29449. return -1;
  29450. }
  29451. if (js_resize_array(ctx, (void **)&fd->args, sizeof(fd->args[0]),
  29452. &fd->arg_size, fd->arg_count + 1))
  29453. return -1;
  29454. vd = &fd->args[fd->arg_count++];
  29455. memset(vd, 0, sizeof(*vd));
  29456. vd->var_name = JS_DupAtom(ctx, name);
  29457. vd->func_pool_idx = -1;
  29458. return fd->arg_count - 1;
  29459. }
  29460. /* add a global variable definition */
  29461. static JSGlobalVar *add_global_var(JSContext *ctx, JSFunctionDef *s,
  29462. JSAtom name)
  29463. {
  29464. JSGlobalVar *hf;
  29465. if (js_resize_array(ctx, (void **)&s->global_vars,
  29466. sizeof(s->global_vars[0]),
  29467. &s->global_var_size, s->global_var_count + 1))
  29468. return NULL;
  29469. hf = &s->global_vars[s->global_var_count++];
  29470. hf->cpool_idx = -1;
  29471. hf->force_init = false;
  29472. hf->is_lexical = false;
  29473. hf->is_const = false;
  29474. hf->scope_level = s->scope_level;
  29475. hf->var_name = JS_DupAtom(ctx, name);
  29476. return hf;
  29477. }
  29478. typedef enum {
  29479. JS_VAR_DEF_WITH,
  29480. JS_VAR_DEF_LET,
  29481. JS_VAR_DEF_CONST,
  29482. JS_VAR_DEF_FUNCTION_DECL, /* function declaration */
  29483. JS_VAR_DEF_NEW_FUNCTION_DECL, /* async/generator function declaration */
  29484. JS_VAR_DEF_CATCH,
  29485. JS_VAR_DEF_VAR,
  29486. } JSVarDefEnum;
  29487. static int define_var(JSParseState *s, JSFunctionDef *fd, JSAtom name,
  29488. JSVarDefEnum var_def_type)
  29489. {
  29490. JSContext *ctx = s->ctx;
  29491. JSVarDef *vd;
  29492. int idx;
  29493. switch (var_def_type) {
  29494. case JS_VAR_DEF_WITH:
  29495. idx = add_scope_var(ctx, fd, name, JS_VAR_NORMAL);
  29496. break;
  29497. case JS_VAR_DEF_LET:
  29498. case JS_VAR_DEF_CONST:
  29499. case JS_VAR_DEF_FUNCTION_DECL:
  29500. case JS_VAR_DEF_NEW_FUNCTION_DECL:
  29501. idx = find_lexical_decl(ctx, fd, name, fd->scope_first, true);
  29502. if (idx >= 0) {
  29503. if (idx < GLOBAL_VAR_OFFSET) {
  29504. if (fd->vars[idx].scope_level == fd->scope_level) {
  29505. /* same scope: in non strict mode, functions
  29506. can be redefined (annex B.3.3.4). */
  29507. if (!(!fd->is_strict_mode &&
  29508. var_def_type == JS_VAR_DEF_FUNCTION_DECL &&
  29509. fd->vars[idx].var_kind == JS_VAR_FUNCTION_DECL)) {
  29510. goto redef_lex_error;
  29511. }
  29512. } else if (fd->vars[idx].var_kind == JS_VAR_CATCH && (fd->vars[idx].scope_level + 2) == fd->scope_level) {
  29513. goto redef_lex_error;
  29514. }
  29515. } else {
  29516. if (fd->scope_level == fd->body_scope) {
  29517. redef_lex_error:
  29518. /* redefining a scoped var in the same scope: error */
  29519. return js_parse_error(s, "invalid redefinition of lexical identifier");
  29520. }
  29521. }
  29522. }
  29523. if (var_def_type != JS_VAR_DEF_FUNCTION_DECL &&
  29524. var_def_type != JS_VAR_DEF_NEW_FUNCTION_DECL &&
  29525. fd->scope_level == fd->body_scope &&
  29526. find_arg(ctx, fd, name) >= 0) {
  29527. /* lexical variable redefines a parameter name */
  29528. return js_parse_error(s, "invalid redefinition of parameter name");
  29529. }
  29530. if (find_var_in_child_scope(ctx, fd, name, fd->scope_level) >= 0) {
  29531. return js_parse_error(s, "invalid redefinition of a variable");
  29532. }
  29533. if (fd->is_global_var) {
  29534. JSGlobalVar *hf;
  29535. hf = find_global_var(fd, name);
  29536. if (hf && is_child_scope(ctx, fd, hf->scope_level,
  29537. fd->scope_level)) {
  29538. return js_parse_error(s, "invalid redefinition of global identifier");
  29539. }
  29540. }
  29541. if (fd->is_eval &&
  29542. (fd->eval_type == JS_EVAL_TYPE_GLOBAL ||
  29543. fd->eval_type == JS_EVAL_TYPE_MODULE) &&
  29544. fd->scope_level == fd->body_scope) {
  29545. JSGlobalVar *hf;
  29546. hf = add_global_var(s->ctx, fd, name);
  29547. if (!hf)
  29548. return -1;
  29549. hf->is_lexical = true;
  29550. hf->is_const = (var_def_type == JS_VAR_DEF_CONST);
  29551. idx = GLOBAL_VAR_OFFSET;
  29552. } else {
  29553. JSVarKindEnum var_kind;
  29554. if (var_def_type == JS_VAR_DEF_FUNCTION_DECL)
  29555. var_kind = JS_VAR_FUNCTION_DECL;
  29556. else if (var_def_type == JS_VAR_DEF_NEW_FUNCTION_DECL)
  29557. var_kind = JS_VAR_NEW_FUNCTION_DECL;
  29558. else
  29559. var_kind = JS_VAR_NORMAL;
  29560. idx = add_scope_var(ctx, fd, name, var_kind);
  29561. if (idx >= 0) {
  29562. vd = &fd->vars[idx];
  29563. vd->is_lexical = 1;
  29564. vd->is_const = (var_def_type == JS_VAR_DEF_CONST);
  29565. }
  29566. }
  29567. break;
  29568. case JS_VAR_DEF_CATCH:
  29569. idx = add_scope_var(ctx, fd, name, JS_VAR_CATCH);
  29570. break;
  29571. case JS_VAR_DEF_VAR:
  29572. if (find_lexical_decl(ctx, fd, name, fd->scope_first,
  29573. false) >= 0) {
  29574. invalid_lexical_redefinition:
  29575. /* error to redefine a var that inside a lexical scope */
  29576. return js_parse_error(s, "invalid redefinition of lexical identifier");
  29577. }
  29578. if (fd->is_global_var) {
  29579. JSGlobalVar *hf;
  29580. hf = find_global_var(fd, name);
  29581. if (hf && hf->is_lexical && hf->scope_level == fd->scope_level &&
  29582. fd->eval_type == JS_EVAL_TYPE_MODULE) {
  29583. goto invalid_lexical_redefinition;
  29584. }
  29585. hf = add_global_var(s->ctx, fd, name);
  29586. if (!hf)
  29587. return -1;
  29588. idx = GLOBAL_VAR_OFFSET;
  29589. } else {
  29590. /* if the variable already exists, don't add it again */
  29591. idx = find_var(ctx, fd, name);
  29592. if (idx >= 0)
  29593. break;
  29594. idx = add_var(ctx, fd, name);
  29595. if (idx >= 0) {
  29596. if (name == JS_ATOM_arguments && fd->has_arguments_binding)
  29597. fd->arguments_var_idx = idx;
  29598. fd->vars[idx].scope_next = fd->scope_level;
  29599. }
  29600. }
  29601. break;
  29602. default:
  29603. abort();
  29604. }
  29605. return idx;
  29606. }
  29607. /* add a private field variable in the current scope */
  29608. static int add_private_class_field(JSParseState *s, JSFunctionDef *fd,
  29609. JSAtom name, JSVarKindEnum var_kind, bool is_static)
  29610. {
  29611. JSContext *ctx = s->ctx;
  29612. JSVarDef *vd;
  29613. int idx;
  29614. idx = add_scope_var(ctx, fd, name, var_kind);
  29615. if (idx < 0)
  29616. return idx;
  29617. vd = &fd->vars[idx];
  29618. vd->is_lexical = 1;
  29619. vd->is_const = 1;
  29620. vd->is_static_private = is_static;
  29621. return idx;
  29622. }
  29623. static __exception int js_parse_expr(JSParseState *s);
  29624. static __exception int js_parse_function_decl(JSParseState *s,
  29625. JSParseFunctionEnum func_type,
  29626. JSFunctionKindEnum func_kind,
  29627. JSAtom func_name, const uint8_t *ptr,
  29628. int start_line, int start_col);
  29629. static JSFunctionDef *js_parse_function_class_fields_init(JSParseState *s);
  29630. static __exception int js_parse_function_decl2(JSParseState *s,
  29631. JSParseFunctionEnum func_type,
  29632. JSFunctionKindEnum func_kind,
  29633. JSAtom func_name,
  29634. const uint8_t *ptr,
  29635. int function_line_num,
  29636. int function_col_num,
  29637. JSParseExportEnum export_flag,
  29638. JSFunctionDef **pfd);
  29639. static __exception int js_parse_assign_expr2(JSParseState *s, int parse_flags);
  29640. static __exception int js_parse_assign_expr(JSParseState *s);
  29641. static __exception int js_parse_unary(JSParseState *s, int parse_flags);
  29642. static void push_break_entry(JSFunctionDef *fd, BlockEnv *be,
  29643. JSAtom label_name,
  29644. int label_break, int label_cont,
  29645. int drop_count);
  29646. static void pop_break_entry(JSFunctionDef *fd);
  29647. static JSExportEntry *add_export_entry(JSParseState *s, JSModuleDef *m,
  29648. JSAtom local_name, JSAtom export_name,
  29649. JSExportTypeEnum export_type);
  29650. /* Note: all the fields are already sealed except length */
  29651. static int seal_template_obj(JSContext *ctx, JSValue obj)
  29652. {
  29653. JSObject *p;
  29654. JSShapeProperty *prs;
  29655. p = JS_VALUE_GET_OBJ(obj);
  29656. prs = find_own_property1(p, JS_ATOM_length);
  29657. if (prs) {
  29658. if (js_update_property_flags(ctx, p, &prs,
  29659. prs->flags & ~(JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE)))
  29660. return -1;
  29661. }
  29662. p->extensible = false;
  29663. return 0;
  29664. }
  29665. static __exception int js_parse_template(JSParseState *s, int call, int *argc)
  29666. {
  29667. JSContext *ctx = s->ctx;
  29668. JSValue raw_array, template_object;
  29669. JSToken cooked;
  29670. int depth, ret;
  29671. raw_array = JS_UNDEFINED; /* avoid warning */
  29672. template_object = JS_UNDEFINED; /* avoid warning */
  29673. if (call) {
  29674. /* Create a template object: an array of cooked strings */
  29675. /* Create an array of raw strings and store it to the raw property */
  29676. template_object = JS_NewArray(ctx);
  29677. if (JS_IsException(template_object))
  29678. return -1;
  29679. // pool_idx = s->cur_func->cpool_count;
  29680. ret = emit_push_const(s, template_object, 0);
  29681. JS_FreeValue(ctx, template_object);
  29682. if (ret)
  29683. return -1;
  29684. raw_array = JS_NewArray(ctx);
  29685. if (JS_IsException(raw_array))
  29686. return -1;
  29687. if (JS_DefinePropertyValue(ctx, template_object, JS_ATOM_raw,
  29688. raw_array, JS_PROP_THROW) < 0) {
  29689. return -1;
  29690. }
  29691. }
  29692. depth = 0;
  29693. while (s->token.val == TOK_TEMPLATE) {
  29694. const uint8_t *p = s->token.ptr + 1;
  29695. cooked = s->token;
  29696. if (call) {
  29697. if (JS_DefinePropertyValueUint32(ctx, raw_array, depth,
  29698. js_dup(s->token.u.str.str),
  29699. JS_PROP_ENUMERABLE | JS_PROP_THROW) < 0) {
  29700. return -1;
  29701. }
  29702. /* re-parse the string with escape sequences but do not throw a
  29703. syntax error if it contains invalid sequences
  29704. */
  29705. if (js_parse_string(s, '`', false, p, &cooked, &p)) {
  29706. cooked.u.str.str = JS_UNDEFINED;
  29707. }
  29708. if (JS_DefinePropertyValueUint32(ctx, template_object, depth,
  29709. cooked.u.str.str,
  29710. JS_PROP_ENUMERABLE | JS_PROP_THROW) < 0) {
  29711. return -1;
  29712. }
  29713. } else {
  29714. JSString *str;
  29715. /* re-parse the string with escape sequences and throw a
  29716. syntax error if it contains invalid sequences
  29717. */
  29718. JS_FreeValue(ctx, s->token.u.str.str);
  29719. s->token.u.str.str = JS_UNDEFINED;
  29720. if (js_parse_string(s, '`', true, p, &cooked, &p))
  29721. return -1;
  29722. str = JS_VALUE_GET_STRING(cooked.u.str.str);
  29723. if (str->len != 0 || depth == 0) {
  29724. ret = emit_push_const(s, cooked.u.str.str, 1);
  29725. JS_FreeValue(s->ctx, cooked.u.str.str);
  29726. if (ret)
  29727. return -1;
  29728. if (depth == 0) {
  29729. if (s->token.u.str.sep == '`')
  29730. goto done1;
  29731. emit_op(s, OP_get_field2);
  29732. emit_atom(s, JS_ATOM_concat);
  29733. }
  29734. depth++;
  29735. } else {
  29736. JS_FreeValue(s->ctx, cooked.u.str.str);
  29737. }
  29738. }
  29739. if (s->token.u.str.sep == '`')
  29740. goto done;
  29741. if (next_token(s))
  29742. return -1;
  29743. if (js_parse_expr(s))
  29744. return -1;
  29745. depth++;
  29746. if (s->token.val != '}') {
  29747. return js_parse_error(s, "expected '}' after template expression");
  29748. }
  29749. /* XXX: should convert to string at this stage? */
  29750. free_token(s, &s->token);
  29751. /* Resume TOK_TEMPLATE parsing (s->token.line_num and
  29752. * s->token.ptr are OK) */
  29753. s->got_lf = false;
  29754. s->last_line_num = s->token.line_num;
  29755. s->last_col_num = s->token.col_num;
  29756. if (js_parse_template_part(s, s->buf_ptr))
  29757. return -1;
  29758. }
  29759. return js_parse_expect(s, TOK_TEMPLATE);
  29760. done:
  29761. if (call) {
  29762. /* Seal the objects */
  29763. seal_template_obj(ctx, raw_array);
  29764. seal_template_obj(ctx, template_object);
  29765. *argc = depth + 1;
  29766. } else {
  29767. emit_op(s, OP_call_method);
  29768. emit_u16(s, depth - 1);
  29769. }
  29770. done1:
  29771. return next_token(s);
  29772. }
  29773. #define PROP_TYPE_IDENT 0
  29774. #define PROP_TYPE_VAR 1
  29775. #define PROP_TYPE_GET 2
  29776. #define PROP_TYPE_SET 3
  29777. #define PROP_TYPE_STAR 4
  29778. #define PROP_TYPE_ASYNC 5
  29779. #define PROP_TYPE_ASYNC_STAR 6
  29780. #define PROP_TYPE_PRIVATE (1 << 4)
  29781. static bool token_is_ident(int tok)
  29782. {
  29783. /* Accept keywords and reserved words as property names */
  29784. return (tok == TOK_IDENT ||
  29785. (tok >= TOK_FIRST_KEYWORD &&
  29786. tok <= TOK_LAST_KEYWORD));
  29787. }
  29788. /* if the property is an expression, name = JS_ATOM_NULL */
  29789. static int __exception js_parse_property_name(JSParseState *s,
  29790. JSAtom *pname,
  29791. bool allow_method, bool allow_var,
  29792. bool allow_private)
  29793. {
  29794. int is_private = 0;
  29795. bool is_non_reserved_ident;
  29796. JSAtom name;
  29797. int prop_type;
  29798. prop_type = PROP_TYPE_IDENT;
  29799. if (allow_method) {
  29800. if (token_is_pseudo_keyword(s, JS_ATOM_get)
  29801. || token_is_pseudo_keyword(s, JS_ATOM_set)) {
  29802. /* get x(), set x() */
  29803. name = JS_DupAtom(s->ctx, s->token.u.ident.atom);
  29804. if (next_token(s))
  29805. goto fail1;
  29806. if (s->token.val == ':' || s->token.val == ',' ||
  29807. s->token.val == '}' || s->token.val == '(' ||
  29808. s->token.val == '=' || s->token.val == ';') {
  29809. is_non_reserved_ident = true;
  29810. goto ident_found;
  29811. }
  29812. prop_type = PROP_TYPE_GET + (name == JS_ATOM_set);
  29813. JS_FreeAtom(s->ctx, name);
  29814. } else if (s->token.val == '*') {
  29815. if (next_token(s))
  29816. goto fail;
  29817. prop_type = PROP_TYPE_STAR;
  29818. } else if (token_is_pseudo_keyword(s, JS_ATOM_async) &&
  29819. peek_token(s, true) != '\n') {
  29820. name = JS_DupAtom(s->ctx, s->token.u.ident.atom);
  29821. if (next_token(s))
  29822. goto fail1;
  29823. if (s->token.val == ':' || s->token.val == ',' ||
  29824. s->token.val == '}' || s->token.val == '(' ||
  29825. s->token.val == '=' || s->token.val == ';') {
  29826. is_non_reserved_ident = true;
  29827. goto ident_found;
  29828. }
  29829. JS_FreeAtom(s->ctx, name);
  29830. if (s->token.val == '*') {
  29831. if (next_token(s))
  29832. goto fail;
  29833. prop_type = PROP_TYPE_ASYNC_STAR;
  29834. } else {
  29835. prop_type = PROP_TYPE_ASYNC;
  29836. }
  29837. }
  29838. }
  29839. if (token_is_ident(s->token.val)) {
  29840. /* variable can only be a non-reserved identifier */
  29841. is_non_reserved_ident =
  29842. (s->token.val == TOK_IDENT && !s->token.u.ident.is_reserved);
  29843. /* keywords and reserved words have a valid atom */
  29844. name = JS_DupAtom(s->ctx, s->token.u.ident.atom);
  29845. if (next_token(s))
  29846. goto fail1;
  29847. ident_found:
  29848. if (is_non_reserved_ident &&
  29849. prop_type == PROP_TYPE_IDENT && allow_var) {
  29850. if (!(s->token.val == ':' ||
  29851. (s->token.val == '(' && allow_method))) {
  29852. prop_type = PROP_TYPE_VAR;
  29853. }
  29854. }
  29855. } else if (s->token.val == TOK_STRING) {
  29856. name = JS_ValueToAtom(s->ctx, s->token.u.str.str);
  29857. if (name == JS_ATOM_NULL)
  29858. goto fail;
  29859. if (next_token(s))
  29860. goto fail1;
  29861. } else if (s->token.val == TOK_NUMBER) {
  29862. JSValue val;
  29863. val = s->token.u.num.val;
  29864. name = JS_ValueToAtom(s->ctx, val);
  29865. if (name == JS_ATOM_NULL)
  29866. goto fail;
  29867. if (next_token(s))
  29868. goto fail1;
  29869. } else if (s->token.val == '[') {
  29870. if (next_token(s))
  29871. goto fail;
  29872. if (js_parse_expr(s))
  29873. goto fail;
  29874. if (js_parse_expect(s, ']'))
  29875. goto fail;
  29876. name = JS_ATOM_NULL;
  29877. } else if (s->token.val == TOK_PRIVATE_NAME && allow_private) {
  29878. name = JS_DupAtom(s->ctx, s->token.u.ident.atom);
  29879. if (next_token(s))
  29880. goto fail1;
  29881. is_private = PROP_TYPE_PRIVATE;
  29882. } else {
  29883. goto invalid_prop;
  29884. }
  29885. if (prop_type != PROP_TYPE_IDENT && prop_type != PROP_TYPE_VAR &&
  29886. s->token.val != '(') {
  29887. JS_FreeAtom(s->ctx, name);
  29888. invalid_prop:
  29889. js_parse_error(s, "invalid property name");
  29890. goto fail;
  29891. }
  29892. *pname = name;
  29893. return prop_type | is_private;
  29894. fail1:
  29895. JS_FreeAtom(s->ctx, name);
  29896. fail:
  29897. *pname = JS_ATOM_NULL;
  29898. return -1;
  29899. }
  29900. typedef struct JSParsePos {
  29901. int last_line_num;
  29902. int last_col_num;
  29903. int line_num;
  29904. int col_num;
  29905. bool got_lf;
  29906. const uint8_t *ptr;
  29907. const uint8_t *eol;
  29908. const uint8_t *mark;
  29909. } JSParsePos;
  29910. static int js_parse_get_pos(JSParseState *s, JSParsePos *sp)
  29911. {
  29912. sp->last_line_num = s->last_line_num;
  29913. sp->last_col_num = s->last_col_num;
  29914. sp->line_num = s->token.line_num;
  29915. sp->col_num = s->token.col_num;
  29916. sp->ptr = s->token.ptr;
  29917. sp->eol = s->eol;
  29918. sp->mark = s->mark;
  29919. sp->got_lf = s->got_lf;
  29920. return 0;
  29921. }
  29922. static __exception int js_parse_seek_token(JSParseState *s, const JSParsePos *sp)
  29923. {
  29924. s->token.line_num = sp->last_line_num;
  29925. s->token.col_num = sp->last_col_num;
  29926. s->line_num = sp->line_num;
  29927. s->col_num = sp->col_num;
  29928. s->buf_ptr = sp->ptr;
  29929. s->eol = sp->eol;
  29930. s->mark = sp->mark;
  29931. s->got_lf = sp->got_lf;
  29932. return next_token(s);
  29933. }
  29934. /* return true if a regexp literal is allowed after this token */
  29935. static bool is_regexp_allowed(int tok)
  29936. {
  29937. switch (tok) {
  29938. case TOK_NUMBER:
  29939. case TOK_STRING:
  29940. case TOK_REGEXP:
  29941. case TOK_DEC:
  29942. case TOK_INC:
  29943. case TOK_NULL:
  29944. case TOK_FALSE:
  29945. case TOK_TRUE:
  29946. case TOK_THIS:
  29947. case ')':
  29948. case ']':
  29949. case '}': /* XXX: regexp may occur after */
  29950. case TOK_IDENT:
  29951. return false;
  29952. default:
  29953. return true;
  29954. }
  29955. }
  29956. #define SKIP_HAS_SEMI (1 << 0)
  29957. #define SKIP_HAS_ELLIPSIS (1 << 1)
  29958. #define SKIP_HAS_ASSIGNMENT (1 << 2)
  29959. /* XXX: improve speed with early bailout */
  29960. /* XXX: no longer works if regexps are present. Could use previous
  29961. regexp parsing heuristics to handle most cases */
  29962. static int js_parse_skip_parens_token(JSParseState *s, int *pbits, bool no_line_terminator)
  29963. {
  29964. char state[256];
  29965. size_t level = 0;
  29966. JSParsePos pos;
  29967. int last_tok, tok = TOK_EOF;
  29968. int c, tok_len, bits = 0;
  29969. /* protect from underflow */
  29970. state[level++] = 0;
  29971. js_parse_get_pos(s, &pos);
  29972. last_tok = 0;
  29973. for (;;) {
  29974. switch(s->token.val) {
  29975. case '(':
  29976. case '[':
  29977. case '{':
  29978. if (level >= sizeof(state))
  29979. goto done;
  29980. state[level++] = s->token.val;
  29981. break;
  29982. case ')':
  29983. if (state[--level] != '(')
  29984. goto done;
  29985. break;
  29986. case ']':
  29987. if (state[--level] != '[')
  29988. goto done;
  29989. break;
  29990. case '}':
  29991. c = state[--level];
  29992. if (c == '`') {
  29993. /* continue the parsing of the template */
  29994. free_token(s, &s->token);
  29995. /* Resume TOK_TEMPLATE parsing (s->token.line_num and
  29996. * s->token.ptr are OK) */
  29997. s->got_lf = false;
  29998. s->last_line_num = s->token.line_num;
  29999. s->last_col_num = s->token.col_num;
  30000. if (js_parse_template_part(s, s->buf_ptr))
  30001. goto done;
  30002. goto handle_template;
  30003. } else if (c != '{') {
  30004. goto done;
  30005. }
  30006. break;
  30007. case TOK_TEMPLATE:
  30008. handle_template:
  30009. if (s->token.u.str.sep != '`') {
  30010. /* '${' inside the template : closing '}' and continue
  30011. parsing the template */
  30012. if (level >= sizeof(state))
  30013. goto done;
  30014. state[level++] = '`';
  30015. }
  30016. break;
  30017. case TOK_EOF:
  30018. goto done;
  30019. case ';':
  30020. if (level == 2) {
  30021. bits |= SKIP_HAS_SEMI;
  30022. }
  30023. break;
  30024. case TOK_ELLIPSIS:
  30025. if (level == 2) {
  30026. bits |= SKIP_HAS_ELLIPSIS;
  30027. }
  30028. break;
  30029. case '=':
  30030. bits |= SKIP_HAS_ASSIGNMENT;
  30031. break;
  30032. case TOK_DIV_ASSIGN:
  30033. tok_len = 2;
  30034. goto parse_regexp;
  30035. case '/':
  30036. tok_len = 1;
  30037. parse_regexp:
  30038. if (is_regexp_allowed(last_tok)) {
  30039. s->buf_ptr -= tok_len;
  30040. if (js_parse_regexp(s)) {
  30041. /* XXX: should clear the exception */
  30042. goto done;
  30043. }
  30044. }
  30045. break;
  30046. }
  30047. /* last_tok is only used to recognize regexps */
  30048. if (s->token.val == TOK_IDENT &&
  30049. (token_is_pseudo_keyword(s, JS_ATOM_of) ||
  30050. token_is_pseudo_keyword(s, JS_ATOM_yield))) {
  30051. last_tok = TOK_OF;
  30052. } else {
  30053. last_tok = s->token.val;
  30054. }
  30055. if (next_token(s)) {
  30056. /* XXX: should clear the exception generated by next_token() */
  30057. break;
  30058. }
  30059. if (level <= 1) {
  30060. tok = s->token.val;
  30061. if (token_is_pseudo_keyword(s, JS_ATOM_of))
  30062. tok = TOK_OF;
  30063. if (no_line_terminator && s->last_line_num != s->token.line_num)
  30064. tok = '\n';
  30065. break;
  30066. }
  30067. }
  30068. done:
  30069. if (pbits) {
  30070. *pbits = bits;
  30071. }
  30072. if (js_parse_seek_token(s, &pos))
  30073. return -1;
  30074. return tok;
  30075. }
  30076. static void set_object_name(JSParseState *s, JSAtom name)
  30077. {
  30078. JSFunctionDef *fd = s->cur_func;
  30079. int opcode;
  30080. opcode = get_prev_opcode(fd);
  30081. if (opcode == OP_set_name) {
  30082. /* XXX: should free atom after OP_set_name? */
  30083. fd->byte_code.size = fd->last_opcode_pos;
  30084. fd->last_opcode_pos = -1;
  30085. emit_op(s, OP_set_name);
  30086. emit_atom(s, name);
  30087. } else if (opcode == OP_set_class_name) {
  30088. int define_class_pos;
  30089. JSAtom atom;
  30090. define_class_pos = fd->last_opcode_pos + 1 -
  30091. get_u32(fd->byte_code.buf + fd->last_opcode_pos + 1);
  30092. assert(fd->byte_code.buf[define_class_pos] == OP_define_class);
  30093. /* for consistency we free the previous atom which is
  30094. JS_ATOM_empty_string */
  30095. atom = get_u32(fd->byte_code.buf + define_class_pos + 1);
  30096. JS_FreeAtom(s->ctx, atom);
  30097. put_u32(fd->byte_code.buf + define_class_pos + 1,
  30098. JS_DupAtom(s->ctx, name));
  30099. fd->last_opcode_pos = -1;
  30100. }
  30101. }
  30102. static void set_object_name_computed(JSParseState *s)
  30103. {
  30104. JSFunctionDef *fd = s->cur_func;
  30105. int opcode;
  30106. opcode = get_prev_opcode(fd);
  30107. if (opcode == OP_set_name) {
  30108. /* XXX: should free atom after OP_set_name? */
  30109. fd->byte_code.size = fd->last_opcode_pos;
  30110. fd->last_opcode_pos = -1;
  30111. emit_op(s, OP_set_name_computed);
  30112. } else if (opcode == OP_set_class_name) {
  30113. int define_class_pos;
  30114. define_class_pos = fd->last_opcode_pos + 1 -
  30115. get_u32(fd->byte_code.buf + fd->last_opcode_pos + 1);
  30116. assert(fd->byte_code.buf[define_class_pos] == OP_define_class);
  30117. fd->byte_code.buf[define_class_pos] = OP_define_class_computed;
  30118. fd->last_opcode_pos = -1;
  30119. }
  30120. }
  30121. static __exception int js_parse_object_literal(JSParseState *s)
  30122. {
  30123. JSAtom name = JS_ATOM_NULL;
  30124. const uint8_t *start_ptr;
  30125. int start_line, start_col, prop_type;
  30126. bool has_proto;
  30127. if (next_token(s))
  30128. goto fail;
  30129. /* XXX: add an initial length that will be patched back */
  30130. emit_op(s, OP_object);
  30131. has_proto = false;
  30132. while (s->token.val != '}') {
  30133. /* specific case for getter/setter */
  30134. start_ptr = s->token.ptr;
  30135. start_line = s->token.line_num;
  30136. start_col = s->token.col_num;
  30137. if (s->token.val == TOK_ELLIPSIS) {
  30138. if (next_token(s))
  30139. return -1;
  30140. if (js_parse_assign_expr(s))
  30141. return -1;
  30142. emit_op(s, OP_null); /* dummy excludeList */
  30143. emit_op(s, OP_copy_data_properties);
  30144. emit_u8(s, 2 | (1 << 2) | (0 << 5));
  30145. emit_op(s, OP_drop); /* pop excludeList */
  30146. emit_op(s, OP_drop); /* pop src object */
  30147. goto next;
  30148. }
  30149. prop_type = js_parse_property_name(s, &name, true, true, false);
  30150. if (prop_type < 0)
  30151. goto fail;
  30152. if (prop_type == PROP_TYPE_VAR) {
  30153. /* shortcut for x: x */
  30154. emit_op(s, OP_scope_get_var);
  30155. emit_atom(s, name);
  30156. emit_u16(s, s->cur_func->scope_level);
  30157. emit_op(s, OP_define_field);
  30158. emit_atom(s, name);
  30159. } else if (s->token.val == '(') {
  30160. bool is_getset = (prop_type == PROP_TYPE_GET ||
  30161. prop_type == PROP_TYPE_SET);
  30162. JSParseFunctionEnum func_type;
  30163. JSFunctionKindEnum func_kind;
  30164. int op_flags;
  30165. func_kind = JS_FUNC_NORMAL;
  30166. if (is_getset) {
  30167. func_type = JS_PARSE_FUNC_GETTER + prop_type - PROP_TYPE_GET;
  30168. } else {
  30169. func_type = JS_PARSE_FUNC_METHOD;
  30170. if (prop_type == PROP_TYPE_STAR)
  30171. func_kind = JS_FUNC_GENERATOR;
  30172. else if (prop_type == PROP_TYPE_ASYNC)
  30173. func_kind = JS_FUNC_ASYNC;
  30174. else if (prop_type == PROP_TYPE_ASYNC_STAR)
  30175. func_kind = JS_FUNC_ASYNC_GENERATOR;
  30176. }
  30177. if (js_parse_function_decl(s, func_type, func_kind, JS_ATOM_NULL,
  30178. start_ptr, start_line, start_col))
  30179. goto fail;
  30180. if (name == JS_ATOM_NULL) {
  30181. emit_op(s, OP_define_method_computed);
  30182. } else {
  30183. emit_op(s, OP_define_method);
  30184. emit_atom(s, name);
  30185. }
  30186. if (is_getset) {
  30187. op_flags = OP_DEFINE_METHOD_GETTER +
  30188. prop_type - PROP_TYPE_GET;
  30189. } else {
  30190. op_flags = OP_DEFINE_METHOD_METHOD;
  30191. }
  30192. emit_u8(s, op_flags | OP_DEFINE_METHOD_ENUMERABLE);
  30193. } else {
  30194. if (js_parse_expect(s, ':'))
  30195. goto fail;
  30196. if (js_parse_assign_expr(s))
  30197. goto fail;
  30198. if (name == JS_ATOM_NULL) {
  30199. set_object_name_computed(s);
  30200. emit_op(s, OP_define_array_el);
  30201. emit_op(s, OP_drop);
  30202. } else if (name == JS_ATOM___proto__) {
  30203. if (has_proto) {
  30204. js_parse_error(s, "duplicate __proto__ property name");
  30205. goto fail;
  30206. }
  30207. emit_op(s, OP_set_proto);
  30208. has_proto = true;
  30209. } else {
  30210. set_object_name(s, name);
  30211. emit_op(s, OP_define_field);
  30212. emit_atom(s, name);
  30213. }
  30214. }
  30215. JS_FreeAtom(s->ctx, name);
  30216. next:
  30217. name = JS_ATOM_NULL;
  30218. if (s->token.val != ',')
  30219. break;
  30220. if (next_token(s))
  30221. goto fail;
  30222. }
  30223. if (js_parse_expect(s, '}'))
  30224. goto fail;
  30225. return 0;
  30226. fail:
  30227. JS_FreeAtom(s->ctx, name);
  30228. return -1;
  30229. }
  30230. /* allow the 'in' binary operator */
  30231. #define PF_IN_ACCEPTED (1 << 0)
  30232. /* allow function calls parsing in js_parse_postfix_expr() */
  30233. #define PF_POSTFIX_CALL (1 << 1)
  30234. /* allow the exponentiation operator in js_parse_unary() */
  30235. #define PF_POW_ALLOWED (1 << 2)
  30236. /* forbid the exponentiation operator in js_parse_unary() */
  30237. #define PF_POW_FORBIDDEN (1 << 3)
  30238. static __exception int js_parse_postfix_expr(JSParseState *s, int parse_flags);
  30239. static __exception int js_parse_left_hand_side_expr(JSParseState *s)
  30240. {
  30241. return js_parse_postfix_expr(s, PF_POSTFIX_CALL);
  30242. }
  30243. /* find field in the current scope */
  30244. static int find_private_class_field(JSContext *ctx, JSFunctionDef *fd,
  30245. JSAtom name, int scope_level)
  30246. {
  30247. int idx;
  30248. idx = fd->scopes[scope_level].first;
  30249. while (idx != -1) {
  30250. if (fd->vars[idx].scope_level != scope_level)
  30251. break;
  30252. if (fd->vars[idx].var_name == name)
  30253. return idx;
  30254. idx = fd->vars[idx].scope_next;
  30255. }
  30256. return -1;
  30257. }
  30258. /* initialize the class fields, called by the constructor. Note:
  30259. super() can be called in an arrow function, so <this> and
  30260. <class_fields_init> can be variable references */
  30261. static void emit_class_field_init(JSParseState *s)
  30262. {
  30263. int label_next;
  30264. emit_op(s, OP_scope_get_var);
  30265. emit_atom(s, JS_ATOM_class_fields_init);
  30266. emit_u16(s, s->cur_func->scope_level);
  30267. /* no need to call the class field initializer if not defined */
  30268. emit_op(s, OP_dup);
  30269. label_next = emit_goto(s, OP_if_false, -1);
  30270. emit_op(s, OP_scope_get_var);
  30271. emit_atom(s, JS_ATOM_this);
  30272. emit_u16(s, 0);
  30273. emit_op(s, OP_swap);
  30274. emit_op(s, OP_call_method);
  30275. emit_u16(s, 0);
  30276. emit_label(s, label_next);
  30277. emit_op(s, OP_drop);
  30278. }
  30279. /* build a private setter function name from the private getter name */
  30280. static JSAtom get_private_setter_name(JSContext *ctx, JSAtom name)
  30281. {
  30282. return js_atom_concat_str(ctx, name, "<set>");
  30283. }
  30284. typedef struct {
  30285. JSFunctionDef *fields_init_fd;
  30286. int computed_fields_count;
  30287. bool need_brand;
  30288. int brand_push_pos;
  30289. bool is_static;
  30290. } ClassFieldsDef;
  30291. static __exception int emit_class_init_start(JSParseState *s,
  30292. ClassFieldsDef *cf)
  30293. {
  30294. int label_add_brand;
  30295. cf->fields_init_fd = js_parse_function_class_fields_init(s);
  30296. if (!cf->fields_init_fd)
  30297. return -1;
  30298. s->cur_func = cf->fields_init_fd;
  30299. if (!cf->is_static) {
  30300. /* add the brand to the newly created instance */
  30301. /* XXX: would be better to add the code only if needed, maybe in a
  30302. later pass */
  30303. emit_op(s, OP_push_false); /* will be patched later */
  30304. cf->brand_push_pos = cf->fields_init_fd->last_opcode_pos;
  30305. label_add_brand = emit_goto(s, OP_if_false, -1);
  30306. emit_op(s, OP_scope_get_var);
  30307. emit_atom(s, JS_ATOM_this);
  30308. emit_u16(s, 0);
  30309. emit_op(s, OP_scope_get_var);
  30310. emit_atom(s, JS_ATOM_home_object);
  30311. emit_u16(s, 0);
  30312. emit_op(s, OP_add_brand);
  30313. emit_label(s, label_add_brand);
  30314. }
  30315. s->cur_func = s->cur_func->parent;
  30316. return 0;
  30317. }
  30318. static void emit_class_init_end(JSParseState *s, ClassFieldsDef *cf)
  30319. {
  30320. int cpool_idx;
  30321. s->cur_func = cf->fields_init_fd;
  30322. emit_op(s, OP_return_undef);
  30323. s->cur_func = s->cur_func->parent;
  30324. cpool_idx = cpool_add(s, JS_NULL);
  30325. cf->fields_init_fd->parent_cpool_idx = cpool_idx;
  30326. emit_op(s, OP_fclosure);
  30327. emit_u32(s, cpool_idx);
  30328. emit_op(s, OP_set_home_object);
  30329. }
  30330. static void emit_return(JSParseState *s, bool hasval);
  30331. static JSFunctionDef *js_new_function_def(JSContext *ctx,
  30332. JSFunctionDef *parent,
  30333. bool is_eval,
  30334. bool is_func_expr,
  30335. const char *filename,
  30336. int line_num,
  30337. int col_num);
  30338. static __exception int js_parse_class_default_ctor(JSParseState *s,
  30339. bool has_super,
  30340. JSFunctionDef **pfd)
  30341. {
  30342. JSParseFunctionEnum func_type;
  30343. JSFunctionDef *fd = s->cur_func;
  30344. fd = js_new_function_def(s->ctx, fd, false, false, s->filename,
  30345. s->token.line_num, s->token.col_num);
  30346. if (!fd)
  30347. return -1;
  30348. s->cur_func = fd;
  30349. fd->has_home_object = true;
  30350. fd->super_allowed = true;
  30351. fd->has_prototype = false;
  30352. fd->has_this_binding = true;
  30353. fd->new_target_allowed = true;
  30354. push_scope(s); /* enter body scope */
  30355. fd->body_scope = fd->scope_level;
  30356. if (has_super) {
  30357. fd->is_derived_class_constructor = true;
  30358. fd->super_call_allowed = true;
  30359. fd->arguments_allowed = true;
  30360. fd->has_arguments_binding = true;
  30361. func_type = JS_PARSE_FUNC_DERIVED_CLASS_CONSTRUCTOR;
  30362. emit_op(s, OP_init_ctor);
  30363. // TODO(bnoordhuis) roll into OP_init_ctor
  30364. emit_op(s, OP_scope_put_var_init);
  30365. emit_atom(s, JS_ATOM_this);
  30366. emit_u16(s, 0);
  30367. emit_class_field_init(s);
  30368. } else {
  30369. func_type = JS_PARSE_FUNC_CLASS_CONSTRUCTOR;
  30370. /* error if not invoked as a constructor */
  30371. emit_op(s, OP_check_ctor);
  30372. emit_class_field_init(s);
  30373. }
  30374. fd->func_kind = JS_FUNC_NORMAL;
  30375. fd->func_type = func_type;
  30376. emit_return(s, false);
  30377. s->cur_func = fd->parent;
  30378. if (pfd)
  30379. *pfd = fd;
  30380. int idx;
  30381. /* the real object will be set at the end of the compilation */
  30382. idx = cpool_add(s, JS_NULL);
  30383. fd->parent_cpool_idx = idx;
  30384. return 0;
  30385. }
  30386. static __exception int js_parse_class(JSParseState *s, bool is_class_expr,
  30387. JSParseExportEnum export_flag)
  30388. {
  30389. JSContext *ctx = s->ctx;
  30390. JSFunctionDef *fd = s->cur_func;
  30391. JSAtom name = JS_ATOM_NULL, class_name = JS_ATOM_NULL, class_name1;
  30392. JSAtom class_var_name = JS_ATOM_NULL;
  30393. JSFunctionDef *method_fd, *ctor_fd;
  30394. int class_name_var_idx, prop_type, ctor_cpool_offset;
  30395. int class_flags = 0, i, define_class_offset;
  30396. bool is_static, is_private, is_strict_mode;
  30397. const uint8_t *class_start_ptr = s->token.ptr;
  30398. const uint8_t *start_ptr;
  30399. ClassFieldsDef class_fields[2];
  30400. /* classes are parsed and executed in strict mode */
  30401. is_strict_mode = fd->is_strict_mode;
  30402. fd->is_strict_mode = true;
  30403. if (next_token(s))
  30404. goto fail;
  30405. if (s->token.val == TOK_IDENT) {
  30406. if (s->token.u.ident.is_reserved) {
  30407. js_parse_error_reserved_identifier(s);
  30408. goto fail;
  30409. }
  30410. class_name = JS_DupAtom(ctx, s->token.u.ident.atom);
  30411. if (next_token(s))
  30412. goto fail;
  30413. } else if (!is_class_expr && export_flag != JS_PARSE_EXPORT_DEFAULT) {
  30414. js_parse_error(s, "class statement requires a name");
  30415. goto fail;
  30416. }
  30417. if (!is_class_expr) {
  30418. if (class_name == JS_ATOM_NULL)
  30419. class_var_name = JS_ATOM__default_; /* export default */
  30420. else
  30421. class_var_name = class_name;
  30422. class_var_name = JS_DupAtom(ctx, class_var_name);
  30423. }
  30424. push_scope(s);
  30425. if (s->token.val == TOK_EXTENDS) {
  30426. class_flags = JS_DEFINE_CLASS_HAS_HERITAGE;
  30427. if (next_token(s))
  30428. goto fail;
  30429. if (js_parse_left_hand_side_expr(s))
  30430. goto fail;
  30431. } else {
  30432. emit_op(s, OP_undefined);
  30433. }
  30434. /* add a 'const' definition for the class name */
  30435. if (class_name != JS_ATOM_NULL) {
  30436. class_name_var_idx = define_var(s, fd, class_name, JS_VAR_DEF_CONST);
  30437. if (class_name_var_idx < 0)
  30438. goto fail;
  30439. }
  30440. if (js_parse_expect(s, '{'))
  30441. goto fail;
  30442. /* this scope contains the private fields */
  30443. push_scope(s);
  30444. emit_op(s, OP_push_const);
  30445. ctor_cpool_offset = fd->byte_code.size;
  30446. emit_u32(s, 0); /* will be patched at the end of the class parsing */
  30447. if (class_name == JS_ATOM_NULL) {
  30448. if (class_var_name != JS_ATOM_NULL)
  30449. class_name1 = JS_ATOM_default;
  30450. else
  30451. class_name1 = JS_ATOM_empty_string;
  30452. } else {
  30453. class_name1 = class_name;
  30454. }
  30455. emit_op(s, OP_define_class);
  30456. emit_atom(s, class_name1);
  30457. emit_u8(s, class_flags);
  30458. define_class_offset = fd->last_opcode_pos;
  30459. for(i = 0; i < 2; i++) {
  30460. ClassFieldsDef *cf = &class_fields[i];
  30461. cf->fields_init_fd = NULL;
  30462. cf->computed_fields_count = 0;
  30463. cf->need_brand = false;
  30464. cf->is_static = i;
  30465. }
  30466. ctor_fd = NULL;
  30467. while (s->token.val != '}') {
  30468. if (s->token.val == ';') {
  30469. if (next_token(s))
  30470. goto fail;
  30471. continue;
  30472. }
  30473. is_static = false;
  30474. if (s->token.val == TOK_STATIC) {
  30475. int next = peek_token(s, true);
  30476. if (!(next == ';' || next == '}' || next == '(' || next == '='))
  30477. is_static = true;
  30478. }
  30479. prop_type = -1;
  30480. if (is_static) {
  30481. if (next_token(s))
  30482. goto fail;
  30483. if (s->token.val == '{') {
  30484. ClassFieldsDef *cf = &class_fields[is_static];
  30485. if (!cf->fields_init_fd)
  30486. if (emit_class_init_start(s, cf))
  30487. goto fail;
  30488. s->cur_func = cf->fields_init_fd;
  30489. // stack is now: <empty>
  30490. JSFunctionDef *init;
  30491. if (js_parse_function_decl2(s, JS_PARSE_FUNC_CLASS_STATIC_INIT,
  30492. JS_FUNC_NORMAL, JS_ATOM_NULL,
  30493. s->token.ptr,
  30494. s->token.line_num,
  30495. s->token.col_num,
  30496. JS_PARSE_EXPORT_NONE, &init) < 0) {
  30497. goto fail;
  30498. }
  30499. // stack is now: fclosure
  30500. push_scope(s);
  30501. emit_op(s, OP_scope_get_var);
  30502. emit_atom(s, JS_ATOM_this);
  30503. emit_u16(s, 0);
  30504. // stack is now: fclosure this
  30505. if (class_name != JS_ATOM_NULL) {
  30506. // TODO(bnoordhuis) pass as argument to init method?
  30507. emit_op(s, OP_dup);
  30508. emit_op(s, OP_scope_put_var_init);
  30509. emit_atom(s, class_name);
  30510. emit_u16(s, s->cur_func->scope_level);
  30511. }
  30512. emit_op(s, OP_swap);
  30513. // stack is now: this fclosure
  30514. emit_op(s, OP_call_method);
  30515. emit_u16(s, 0);
  30516. // stack is now: returnvalue
  30517. emit_op(s, OP_drop);
  30518. // stack is now: <empty>
  30519. pop_scope(s);
  30520. s->cur_func = s->cur_func->parent;
  30521. continue;
  30522. }
  30523. /* allow "static" field name */
  30524. if (s->token.val == ';' || s->token.val == '=') {
  30525. is_static = false;
  30526. name = JS_DupAtom(ctx, JS_ATOM_static);
  30527. prop_type = PROP_TYPE_IDENT;
  30528. }
  30529. }
  30530. if (is_static)
  30531. emit_op(s, OP_swap);
  30532. start_ptr = s->token.ptr;
  30533. if (prop_type < 0) {
  30534. prop_type = js_parse_property_name(s, &name, true, false, true);
  30535. if (prop_type < 0)
  30536. goto fail;
  30537. }
  30538. is_private = prop_type & PROP_TYPE_PRIVATE;
  30539. prop_type &= ~PROP_TYPE_PRIVATE;
  30540. if ((name == JS_ATOM_constructor && !is_static &&
  30541. prop_type != PROP_TYPE_IDENT) ||
  30542. (name == JS_ATOM_prototype && is_static) ||
  30543. name == JS_ATOM_hash_constructor) {
  30544. js_parse_error(s, "invalid method name");
  30545. goto fail;
  30546. }
  30547. if (prop_type == PROP_TYPE_GET || prop_type == PROP_TYPE_SET) {
  30548. bool is_set = prop_type - PROP_TYPE_GET;
  30549. JSFunctionDef *method_fd;
  30550. if (is_private) {
  30551. int idx, var_kind, is_static1;
  30552. idx = find_private_class_field(ctx, fd, name, fd->scope_level);
  30553. if (idx >= 0) {
  30554. var_kind = fd->vars[idx].var_kind;
  30555. is_static1 = fd->vars[idx].is_static_private;
  30556. if (var_kind == JS_VAR_PRIVATE_FIELD ||
  30557. var_kind == JS_VAR_PRIVATE_METHOD ||
  30558. var_kind == JS_VAR_PRIVATE_GETTER_SETTER ||
  30559. var_kind == (JS_VAR_PRIVATE_GETTER + is_set) ||
  30560. (var_kind == (JS_VAR_PRIVATE_GETTER + 1 - is_set) &&
  30561. is_static != is_static1)) {
  30562. goto private_field_already_defined;
  30563. }
  30564. fd->vars[idx].var_kind = JS_VAR_PRIVATE_GETTER_SETTER;
  30565. } else {
  30566. if (add_private_class_field(s, fd, name,
  30567. JS_VAR_PRIVATE_GETTER + is_set, is_static) < 0)
  30568. goto fail;
  30569. }
  30570. class_fields[is_static].need_brand = true;
  30571. }
  30572. if (js_parse_function_decl2(s, JS_PARSE_FUNC_GETTER + is_set,
  30573. JS_FUNC_NORMAL, JS_ATOM_NULL,
  30574. start_ptr,
  30575. s->token.line_num,
  30576. s->token.col_num,
  30577. JS_PARSE_EXPORT_NONE, &method_fd))
  30578. goto fail;
  30579. if (is_private) {
  30580. method_fd->need_home_object = true; /* needed for brand check */
  30581. emit_op(s, OP_set_home_object);
  30582. /* XXX: missing function name */
  30583. emit_op(s, OP_scope_put_var_init);
  30584. if (is_set) {
  30585. JSAtom setter_name;
  30586. int ret;
  30587. setter_name = get_private_setter_name(ctx, name);
  30588. if (setter_name == JS_ATOM_NULL)
  30589. goto fail;
  30590. emit_atom(s, setter_name);
  30591. ret = add_private_class_field(s, fd, setter_name,
  30592. JS_VAR_PRIVATE_SETTER, is_static);
  30593. JS_FreeAtom(ctx, setter_name);
  30594. if (ret < 0)
  30595. goto fail;
  30596. } else {
  30597. emit_atom(s, name);
  30598. }
  30599. emit_u16(s, s->cur_func->scope_level);
  30600. } else {
  30601. if (name == JS_ATOM_NULL) {
  30602. emit_op(s, OP_define_method_computed);
  30603. } else {
  30604. emit_op(s, OP_define_method);
  30605. emit_atom(s, name);
  30606. }
  30607. emit_u8(s, OP_DEFINE_METHOD_GETTER + is_set);
  30608. }
  30609. } else if (prop_type == PROP_TYPE_IDENT && s->token.val != '(') {
  30610. ClassFieldsDef *cf = &class_fields[is_static];
  30611. JSAtom field_var_name = JS_ATOM_NULL;
  30612. /* class field */
  30613. /* XXX: spec: not consistent with method name checks */
  30614. if (name == JS_ATOM_constructor || name == JS_ATOM_prototype) {
  30615. js_parse_error(s, "invalid field name");
  30616. goto fail;
  30617. }
  30618. if (is_private) {
  30619. if (find_private_class_field(ctx, fd, name,
  30620. fd->scope_level) >= 0) {
  30621. goto private_field_already_defined;
  30622. }
  30623. if (add_private_class_field(s, fd, name,
  30624. JS_VAR_PRIVATE_FIELD, is_static) < 0)
  30625. goto fail;
  30626. emit_op(s, OP_private_symbol);
  30627. emit_atom(s, name);
  30628. emit_op(s, OP_scope_put_var_init);
  30629. emit_atom(s, name);
  30630. emit_u16(s, s->cur_func->scope_level);
  30631. }
  30632. if (!cf->fields_init_fd) {
  30633. if (emit_class_init_start(s, cf))
  30634. goto fail;
  30635. }
  30636. if (name == JS_ATOM_NULL ) {
  30637. /* save the computed field name into a variable */
  30638. field_var_name = js_atom_concat_num(ctx, JS_ATOM_computed_field + is_static, cf->computed_fields_count);
  30639. if (field_var_name == JS_ATOM_NULL)
  30640. goto fail;
  30641. if (define_var(s, fd, field_var_name, JS_VAR_DEF_CONST) < 0) {
  30642. JS_FreeAtom(ctx, field_var_name);
  30643. goto fail;
  30644. }
  30645. emit_op(s, OP_to_propkey);
  30646. emit_op(s, OP_scope_put_var_init);
  30647. emit_atom(s, field_var_name);
  30648. emit_u16(s, s->cur_func->scope_level);
  30649. }
  30650. s->cur_func = cf->fields_init_fd;
  30651. emit_op(s, OP_scope_get_var);
  30652. emit_atom(s, JS_ATOM_this);
  30653. emit_u16(s, 0);
  30654. // expose class name to static initializers
  30655. if (is_static && class_name != JS_ATOM_NULL) {
  30656. emit_op(s, OP_dup);
  30657. emit_op(s, OP_scope_put_var_init);
  30658. emit_atom(s, class_name);
  30659. emit_u16(s, s->cur_func->scope_level);
  30660. }
  30661. if (name == JS_ATOM_NULL) {
  30662. emit_op(s, OP_scope_get_var);
  30663. emit_atom(s, field_var_name);
  30664. emit_u16(s, s->cur_func->scope_level);
  30665. cf->computed_fields_count++;
  30666. JS_FreeAtom(ctx, field_var_name);
  30667. } else if (is_private) {
  30668. emit_op(s, OP_scope_get_var);
  30669. emit_atom(s, name);
  30670. emit_u16(s, s->cur_func->scope_level);
  30671. }
  30672. if (s->token.val == '=') {
  30673. if (next_token(s))
  30674. goto fail;
  30675. if (js_parse_assign_expr(s))
  30676. goto fail;
  30677. } else {
  30678. emit_op(s, OP_undefined);
  30679. }
  30680. if (is_private) {
  30681. set_object_name_computed(s);
  30682. emit_op(s, OP_define_private_field);
  30683. } else if (name == JS_ATOM_NULL) {
  30684. set_object_name_computed(s);
  30685. emit_op(s, OP_define_array_el);
  30686. emit_op(s, OP_drop);
  30687. } else {
  30688. set_object_name(s, name);
  30689. emit_op(s, OP_define_field);
  30690. emit_atom(s, name);
  30691. }
  30692. s->cur_func = s->cur_func->parent;
  30693. if (js_parse_expect_semi(s))
  30694. goto fail;
  30695. } else {
  30696. JSParseFunctionEnum func_type;
  30697. JSFunctionKindEnum func_kind;
  30698. func_type = JS_PARSE_FUNC_METHOD;
  30699. func_kind = JS_FUNC_NORMAL;
  30700. if (prop_type == PROP_TYPE_STAR) {
  30701. func_kind = JS_FUNC_GENERATOR;
  30702. } else if (prop_type == PROP_TYPE_ASYNC) {
  30703. func_kind = JS_FUNC_ASYNC;
  30704. } else if (prop_type == PROP_TYPE_ASYNC_STAR) {
  30705. func_kind = JS_FUNC_ASYNC_GENERATOR;
  30706. } else if (name == JS_ATOM_constructor && !is_static) {
  30707. if (ctor_fd) {
  30708. js_parse_error(s, "property constructor appears more than once");
  30709. goto fail;
  30710. }
  30711. if (class_flags & JS_DEFINE_CLASS_HAS_HERITAGE)
  30712. func_type = JS_PARSE_FUNC_DERIVED_CLASS_CONSTRUCTOR;
  30713. else
  30714. func_type = JS_PARSE_FUNC_CLASS_CONSTRUCTOR;
  30715. }
  30716. if (is_private) {
  30717. class_fields[is_static].need_brand = true;
  30718. }
  30719. if (js_parse_function_decl2(s, func_type, func_kind, JS_ATOM_NULL,
  30720. start_ptr,
  30721. s->token.line_num,
  30722. s->token.col_num,
  30723. JS_PARSE_EXPORT_NONE, &method_fd))
  30724. goto fail;
  30725. if (func_type == JS_PARSE_FUNC_DERIVED_CLASS_CONSTRUCTOR ||
  30726. func_type == JS_PARSE_FUNC_CLASS_CONSTRUCTOR) {
  30727. ctor_fd = method_fd;
  30728. } else if (is_private) {
  30729. method_fd->need_home_object = true; /* needed for brand check */
  30730. if (find_private_class_field(ctx, fd, name,
  30731. fd->scope_level) >= 0) {
  30732. private_field_already_defined:
  30733. js_parse_error(s, "private class field is already defined");
  30734. goto fail;
  30735. }
  30736. if (add_private_class_field(s, fd, name,
  30737. JS_VAR_PRIVATE_METHOD, is_static) < 0)
  30738. goto fail;
  30739. emit_op(s, OP_set_home_object);
  30740. emit_op(s, OP_set_name);
  30741. emit_atom(s, name);
  30742. emit_op(s, OP_scope_put_var_init);
  30743. emit_atom(s, name);
  30744. emit_u16(s, s->cur_func->scope_level);
  30745. } else {
  30746. if (name == JS_ATOM_NULL) {
  30747. emit_op(s, OP_define_method_computed);
  30748. } else {
  30749. emit_op(s, OP_define_method);
  30750. emit_atom(s, name);
  30751. }
  30752. emit_u8(s, OP_DEFINE_METHOD_METHOD);
  30753. }
  30754. }
  30755. if (is_static)
  30756. emit_op(s, OP_swap);
  30757. JS_FreeAtom(ctx, name);
  30758. name = JS_ATOM_NULL;
  30759. }
  30760. if (s->token.val != '}') {
  30761. js_parse_error(s, "expecting '%c'", '}');
  30762. goto fail;
  30763. }
  30764. if (!ctor_fd) {
  30765. if (js_parse_class_default_ctor(s, class_flags & JS_DEFINE_CLASS_HAS_HERITAGE, &ctor_fd))
  30766. goto fail;
  30767. }
  30768. /* patch the constant pool index for the constructor */
  30769. put_u32(fd->byte_code.buf + ctor_cpool_offset, ctor_fd->parent_cpool_idx);
  30770. /* store the class source code in the constructor. */
  30771. js_free(ctx, ctor_fd->source);
  30772. ctor_fd->source_len = s->buf_ptr - class_start_ptr;
  30773. ctor_fd->source = js_strndup(ctx, (const char *)class_start_ptr, ctor_fd->source_len);
  30774. if (!ctor_fd->source)
  30775. goto fail;
  30776. /* consume the '}' */
  30777. if (next_token(s))
  30778. goto fail;
  30779. {
  30780. ClassFieldsDef *cf = &class_fields[0];
  30781. int var_idx;
  30782. if (cf->need_brand) {
  30783. /* add a private brand to the prototype */
  30784. emit_op(s, OP_dup);
  30785. emit_op(s, OP_null);
  30786. emit_op(s, OP_swap);
  30787. emit_op(s, OP_add_brand);
  30788. /* define the brand field in 'this' of the initializer */
  30789. if (!cf->fields_init_fd) {
  30790. if (emit_class_init_start(s, cf))
  30791. goto fail;
  30792. }
  30793. /* patch the start of the function to enable the
  30794. OP_add_brand_instance code */
  30795. cf->fields_init_fd->byte_code.buf[cf->brand_push_pos] = OP_push_true;
  30796. }
  30797. /* store the function to initialize the fields to that it can be
  30798. referenced by the constructor */
  30799. var_idx = define_var(s, fd, JS_ATOM_class_fields_init,
  30800. JS_VAR_DEF_CONST);
  30801. if (var_idx < 0)
  30802. goto fail;
  30803. if (cf->fields_init_fd) {
  30804. emit_class_init_end(s, cf);
  30805. } else {
  30806. emit_op(s, OP_undefined);
  30807. }
  30808. emit_op(s, OP_scope_put_var_init);
  30809. emit_atom(s, JS_ATOM_class_fields_init);
  30810. emit_u16(s, s->cur_func->scope_level);
  30811. }
  30812. /* drop the prototype */
  30813. emit_op(s, OP_drop);
  30814. if (class_fields[1].need_brand) {
  30815. /* add a private brand to the class */
  30816. emit_op(s, OP_dup);
  30817. emit_op(s, OP_dup);
  30818. emit_op(s, OP_add_brand);
  30819. }
  30820. /* initialize the static fields */
  30821. if (class_fields[1].fields_init_fd != NULL) {
  30822. ClassFieldsDef *cf = &class_fields[1];
  30823. emit_op(s, OP_dup);
  30824. emit_class_init_end(s, cf);
  30825. emit_op(s, OP_call_method);
  30826. emit_u16(s, 0);
  30827. emit_op(s, OP_drop);
  30828. }
  30829. if (class_name != JS_ATOM_NULL) {
  30830. /* store the class name in the scoped class name variable (it
  30831. is independent from the class statement variable
  30832. definition) */
  30833. emit_op(s, OP_dup);
  30834. emit_op(s, OP_scope_put_var_init);
  30835. emit_atom(s, class_name);
  30836. emit_u16(s, fd->scope_level);
  30837. }
  30838. pop_scope(s);
  30839. pop_scope(s);
  30840. /* the class statements have a block level scope */
  30841. if (class_var_name != JS_ATOM_NULL) {
  30842. if (define_var(s, fd, class_var_name, JS_VAR_DEF_LET) < 0)
  30843. goto fail;
  30844. emit_op(s, OP_scope_put_var_init);
  30845. emit_atom(s, class_var_name);
  30846. emit_u16(s, fd->scope_level);
  30847. } else {
  30848. if (class_name == JS_ATOM_NULL) {
  30849. /* cannot use OP_set_name because the name of the class
  30850. must be defined before the static initializers are
  30851. executed */
  30852. emit_op(s, OP_set_class_name);
  30853. emit_u32(s, fd->last_opcode_pos + 1 - define_class_offset);
  30854. }
  30855. }
  30856. if (export_flag != JS_PARSE_EXPORT_NONE) {
  30857. if (!add_export_entry(s, fd->module,
  30858. class_var_name,
  30859. export_flag == JS_PARSE_EXPORT_NAMED ? class_var_name : JS_ATOM_default,
  30860. JS_EXPORT_TYPE_LOCAL))
  30861. goto fail;
  30862. }
  30863. JS_FreeAtom(ctx, class_name);
  30864. JS_FreeAtom(ctx, class_var_name);
  30865. fd->is_strict_mode = is_strict_mode;
  30866. return 0;
  30867. fail:
  30868. JS_FreeAtom(ctx, name);
  30869. JS_FreeAtom(ctx, class_name);
  30870. JS_FreeAtom(ctx, class_var_name);
  30871. fd->is_strict_mode = is_strict_mode;
  30872. return -1;
  30873. }
  30874. static __exception int js_parse_array_literal(JSParseState *s)
  30875. {
  30876. uint32_t idx;
  30877. bool need_length;
  30878. if (next_token(s))
  30879. return -1;
  30880. /* small regular arrays are created on the stack */
  30881. idx = 0;
  30882. while (s->token.val != ']' && idx < 32) {
  30883. if (s->token.val == ',' || s->token.val == TOK_ELLIPSIS)
  30884. break;
  30885. if (js_parse_assign_expr(s))
  30886. return -1;
  30887. idx++;
  30888. /* accept trailing comma */
  30889. if (s->token.val == ',') {
  30890. if (next_token(s))
  30891. return -1;
  30892. } else
  30893. if (s->token.val != ']')
  30894. goto done;
  30895. }
  30896. emit_op(s, OP_array_from);
  30897. emit_u16(s, idx);
  30898. /* larger arrays and holes are handled with explicit indices */
  30899. need_length = false;
  30900. while (s->token.val != ']' && idx < 0x7fffffff) {
  30901. if (s->token.val == TOK_ELLIPSIS)
  30902. break;
  30903. need_length = true;
  30904. if (s->token.val != ',') {
  30905. if (js_parse_assign_expr(s))
  30906. return -1;
  30907. emit_op(s, OP_define_field);
  30908. emit_u32(s, __JS_AtomFromUInt32(idx));
  30909. need_length = false;
  30910. }
  30911. idx++;
  30912. /* accept trailing comma */
  30913. if (s->token.val == ',') {
  30914. if (next_token(s))
  30915. return -1;
  30916. }
  30917. }
  30918. if (s->token.val == ']') {
  30919. if (need_length) {
  30920. /* Set the length: Cannot use OP_define_field because
  30921. length is not configurable */
  30922. emit_op(s, OP_dup);
  30923. emit_op(s, OP_push_i32);
  30924. emit_u32(s, idx);
  30925. emit_op(s, OP_put_field);
  30926. emit_atom(s, JS_ATOM_length);
  30927. }
  30928. goto done;
  30929. }
  30930. /* huge arrays and spread elements require a dynamic index on the stack */
  30931. emit_op(s, OP_push_i32);
  30932. emit_u32(s, idx);
  30933. /* stack has array, index */
  30934. while (s->token.val != ']') {
  30935. if (s->token.val == TOK_ELLIPSIS) {
  30936. if (next_token(s))
  30937. return -1;
  30938. if (js_parse_assign_expr(s))
  30939. return -1;
  30940. emit_op(s, OP_append);
  30941. } else {
  30942. need_length = true;
  30943. if (s->token.val != ',') {
  30944. if (js_parse_assign_expr(s))
  30945. return -1;
  30946. /* a idx val */
  30947. emit_op(s, OP_define_array_el);
  30948. need_length = false;
  30949. }
  30950. emit_op(s, OP_inc);
  30951. }
  30952. if (s->token.val != ',')
  30953. break;
  30954. if (next_token(s))
  30955. return -1;
  30956. }
  30957. if (need_length) {
  30958. /* Set the length: cannot use OP_define_field because
  30959. length is not configurable */
  30960. emit_op(s, OP_dup1); /* array length - array array length */
  30961. emit_op(s, OP_put_field);
  30962. emit_atom(s, JS_ATOM_length);
  30963. } else {
  30964. emit_op(s, OP_drop); /* array length - array */
  30965. }
  30966. done:
  30967. return js_parse_expect(s, ']');
  30968. }
  30969. /* XXX: remove */
  30970. static bool has_with_scope(JSFunctionDef *s, int scope_level)
  30971. {
  30972. /* check if scope chain contains a with statement */
  30973. while (s) {
  30974. int scope_idx = s->scopes[scope_level].first;
  30975. while (scope_idx >= 0) {
  30976. JSVarDef *vd = &s->vars[scope_idx];
  30977. if (vd->var_name == JS_ATOM__with_)
  30978. return true;
  30979. scope_idx = vd->scope_next;
  30980. }
  30981. /* check parent scopes */
  30982. scope_level = s->parent_scope_level;
  30983. s = s->parent;
  30984. }
  30985. return false;
  30986. }
  30987. static __exception int get_lvalue(JSParseState *s, int *popcode, int *pscope,
  30988. JSAtom *pname, int *plabel, int *pdepth, bool keep,
  30989. int tok)
  30990. {
  30991. JSFunctionDef *fd;
  30992. int opcode, scope, label, depth;
  30993. JSAtom name;
  30994. /* we check the last opcode to get the lvalue type */
  30995. fd = s->cur_func;
  30996. scope = 0;
  30997. name = JS_ATOM_NULL;
  30998. label = -1;
  30999. depth = 0;
  31000. switch(opcode = get_prev_opcode(fd)) {
  31001. case OP_scope_get_var:
  31002. name = get_u32(fd->byte_code.buf + fd->last_opcode_pos + 1);
  31003. scope = get_u16(fd->byte_code.buf + fd->last_opcode_pos + 5);
  31004. if ((name == JS_ATOM_arguments || name == JS_ATOM_eval) &&
  31005. fd->is_strict_mode) {
  31006. return js_parse_error(s, "invalid lvalue in strict mode");
  31007. }
  31008. if (name == JS_ATOM_this || name == JS_ATOM_new_target)
  31009. goto invalid_lvalue;
  31010. depth = 2; /* will generate OP_get_ref_value */
  31011. break;
  31012. case OP_get_field:
  31013. name = get_u32(fd->byte_code.buf + fd->last_opcode_pos + 1);
  31014. depth = 1;
  31015. break;
  31016. case OP_scope_get_private_field:
  31017. name = get_u32(fd->byte_code.buf + fd->last_opcode_pos + 1);
  31018. scope = get_u16(fd->byte_code.buf + fd->last_opcode_pos + 5);
  31019. depth = 1;
  31020. break;
  31021. case OP_get_array_el:
  31022. depth = 2;
  31023. break;
  31024. case OP_get_super_value:
  31025. depth = 3;
  31026. break;
  31027. default:
  31028. invalid_lvalue:
  31029. if (tok == TOK_FOR) {
  31030. return js_parse_error(s, "invalid for in/of left hand-side");
  31031. } else if (tok == TOK_INC || tok == TOK_DEC) {
  31032. return js_parse_error(s, "invalid increment/decrement operand");
  31033. } else if (tok == '[' || tok == '{') {
  31034. return js_parse_error(s, "invalid destructuring target");
  31035. } else {
  31036. return js_parse_error(s, "invalid assignment left-hand side");
  31037. }
  31038. }
  31039. /* remove the last opcode */
  31040. fd->byte_code.size = fd->last_opcode_pos;
  31041. fd->last_opcode_pos = -1;
  31042. if (keep) {
  31043. /* get the value but keep the object/fields on the stack */
  31044. switch(opcode) {
  31045. case OP_scope_get_var:
  31046. label = new_label(s);
  31047. emit_op(s, OP_scope_make_ref);
  31048. emit_atom(s, name);
  31049. emit_u32(s, label);
  31050. emit_u16(s, scope);
  31051. update_label(fd, label, 1);
  31052. emit_op(s, OP_get_ref_value);
  31053. opcode = OP_get_ref_value;
  31054. break;
  31055. case OP_get_field:
  31056. emit_op(s, OP_get_field2);
  31057. emit_atom(s, name);
  31058. break;
  31059. case OP_scope_get_private_field:
  31060. emit_op(s, OP_scope_get_private_field2);
  31061. emit_atom(s, name);
  31062. emit_u16(s, scope);
  31063. break;
  31064. case OP_get_array_el:
  31065. /* XXX: replace by a single opcode ? */
  31066. emit_op(s, OP_to_propkey2);
  31067. emit_op(s, OP_dup2);
  31068. emit_op(s, OP_get_array_el);
  31069. break;
  31070. case OP_get_super_value:
  31071. emit_op(s, OP_to_propkey);
  31072. emit_op(s, OP_dup3);
  31073. emit_op(s, OP_get_super_value);
  31074. break;
  31075. default:
  31076. abort();
  31077. }
  31078. } else {
  31079. switch(opcode) {
  31080. case OP_scope_get_var:
  31081. label = new_label(s);
  31082. emit_op(s, OP_scope_make_ref);
  31083. emit_atom(s, name);
  31084. emit_u32(s, label);
  31085. emit_u16(s, scope);
  31086. update_label(fd, label, 1);
  31087. opcode = OP_get_ref_value;
  31088. break;
  31089. case OP_get_array_el:
  31090. emit_op(s, OP_to_propkey2);
  31091. break;
  31092. case OP_get_super_value:
  31093. emit_op(s, OP_to_propkey);
  31094. break;
  31095. }
  31096. }
  31097. *popcode = opcode;
  31098. *pscope = scope;
  31099. /* name has refcount for OP_get_field and OP_get_ref_value,
  31100. and JS_ATOM_NULL for other opcodes */
  31101. *pname = name;
  31102. *plabel = label;
  31103. if (pdepth)
  31104. *pdepth = depth;
  31105. return 0;
  31106. }
  31107. typedef enum {
  31108. PUT_LVALUE_NOKEEP, /* [depth] v -> */
  31109. PUT_LVALUE_NOKEEP_DEPTH, /* [depth] v -> , keep depth (currently
  31110. just disable optimizations) */
  31111. PUT_LVALUE_KEEP_TOP, /* [depth] v -> v */
  31112. PUT_LVALUE_KEEP_SECOND, /* [depth] v0 v -> v0 */
  31113. PUT_LVALUE_NOKEEP_BOTTOM, /* v [depth] -> */
  31114. } PutLValueEnum;
  31115. /* name has a live reference. 'is_let' is only used with opcode =
  31116. OP_scope_get_var which is never generated by get_lvalue(). */
  31117. static void put_lvalue(JSParseState *s, int opcode, int scope,
  31118. JSAtom name, int label, PutLValueEnum special,
  31119. bool is_let)
  31120. {
  31121. switch(opcode) {
  31122. case OP_get_field:
  31123. case OP_scope_get_private_field:
  31124. /* depth = 1 */
  31125. switch(special) {
  31126. case PUT_LVALUE_NOKEEP:
  31127. case PUT_LVALUE_NOKEEP_DEPTH:
  31128. break;
  31129. case PUT_LVALUE_KEEP_TOP:
  31130. emit_op(s, OP_insert2); /* obj v -> v obj v */
  31131. break;
  31132. case PUT_LVALUE_KEEP_SECOND:
  31133. emit_op(s, OP_perm3); /* obj v0 v -> v0 obj v */
  31134. break;
  31135. case PUT_LVALUE_NOKEEP_BOTTOM:
  31136. emit_op(s, OP_swap);
  31137. break;
  31138. default:
  31139. abort();
  31140. }
  31141. break;
  31142. case OP_get_array_el:
  31143. case OP_get_ref_value:
  31144. /* depth = 2 */
  31145. if (opcode == OP_get_ref_value) {
  31146. JS_FreeAtom(s->ctx, name);
  31147. emit_label(s, label);
  31148. }
  31149. switch(special) {
  31150. case PUT_LVALUE_NOKEEP:
  31151. emit_op(s, OP_nop); /* will trigger optimization */
  31152. break;
  31153. case PUT_LVALUE_NOKEEP_DEPTH:
  31154. break;
  31155. case PUT_LVALUE_KEEP_TOP:
  31156. emit_op(s, OP_insert3); /* obj prop v -> v obj prop v */
  31157. break;
  31158. case PUT_LVALUE_KEEP_SECOND:
  31159. emit_op(s, OP_perm4); /* obj prop v0 v -> v0 obj prop v */
  31160. break;
  31161. case PUT_LVALUE_NOKEEP_BOTTOM:
  31162. emit_op(s, OP_rot3l);
  31163. break;
  31164. default:
  31165. abort();
  31166. }
  31167. break;
  31168. case OP_get_super_value:
  31169. /* depth = 3 */
  31170. switch(special) {
  31171. case PUT_LVALUE_NOKEEP:
  31172. case PUT_LVALUE_NOKEEP_DEPTH:
  31173. break;
  31174. case PUT_LVALUE_KEEP_TOP:
  31175. emit_op(s, OP_insert4); /* this obj prop v -> v this obj prop v */
  31176. break;
  31177. case PUT_LVALUE_KEEP_SECOND:
  31178. emit_op(s, OP_perm5); /* this obj prop v0 v -> v0 this obj prop v */
  31179. break;
  31180. case PUT_LVALUE_NOKEEP_BOTTOM:
  31181. emit_op(s, OP_rot4l);
  31182. break;
  31183. default:
  31184. abort();
  31185. }
  31186. break;
  31187. default:
  31188. break;
  31189. }
  31190. switch(opcode) {
  31191. case OP_scope_get_var: /* val -- */
  31192. assert(special == PUT_LVALUE_NOKEEP ||
  31193. special == PUT_LVALUE_NOKEEP_DEPTH);
  31194. emit_op(s, is_let ? OP_scope_put_var_init : OP_scope_put_var);
  31195. emit_u32(s, name); /* has refcount */
  31196. emit_u16(s, scope);
  31197. break;
  31198. case OP_get_field:
  31199. emit_op(s, OP_put_field);
  31200. emit_u32(s, name); /* name has refcount */
  31201. break;
  31202. case OP_scope_get_private_field:
  31203. emit_op(s, OP_scope_put_private_field);
  31204. emit_u32(s, name); /* name has refcount */
  31205. emit_u16(s, scope);
  31206. break;
  31207. case OP_get_array_el:
  31208. emit_op(s, OP_put_array_el);
  31209. break;
  31210. case OP_get_ref_value:
  31211. emit_op(s, OP_put_ref_value);
  31212. break;
  31213. case OP_get_super_value:
  31214. emit_op(s, OP_put_super_value);
  31215. break;
  31216. default:
  31217. abort();
  31218. }
  31219. }
  31220. static __exception int js_parse_expr_paren(JSParseState *s)
  31221. {
  31222. if (js_parse_expect(s, '('))
  31223. return -1;
  31224. if (js_parse_expr(s))
  31225. return -1;
  31226. if (js_parse_expect(s, ')'))
  31227. return -1;
  31228. return 0;
  31229. }
  31230. static int js_unsupported_keyword(JSParseState *s, JSAtom atom)
  31231. {
  31232. char buf[ATOM_GET_STR_BUF_SIZE];
  31233. return js_parse_error(s, "unsupported keyword: %s",
  31234. JS_AtomGetStr(s->ctx, buf, sizeof(buf), atom));
  31235. }
  31236. static __exception int js_define_var(JSParseState *s, JSAtom name, int tok)
  31237. {
  31238. JSFunctionDef *fd = s->cur_func;
  31239. JSVarDefEnum var_def_type;
  31240. if (name == JS_ATOM_yield && fd->func_kind == JS_FUNC_GENERATOR) {
  31241. return js_parse_error(s, "yield is a reserved identifier");
  31242. }
  31243. if ((name == JS_ATOM_arguments || name == JS_ATOM_eval)
  31244. && fd->is_strict_mode) {
  31245. return js_parse_error(s, "invalid variable name in strict mode");
  31246. }
  31247. if (tok == TOK_LET || tok == TOK_CONST) {
  31248. if (name == JS_ATOM_let)
  31249. return js_parse_error(s, "invalid lexical variable name 'let'");
  31250. // |undefined| is allowed as an identifier except at the global
  31251. // scope of a classic script; sloppy or strict doesn't matter
  31252. if (name == JS_ATOM_undefined
  31253. && fd->scope_level == 1
  31254. && fd->is_global_var
  31255. && !fd->module) {
  31256. return js_parse_error(s, "'undefined' already declared");
  31257. }
  31258. }
  31259. switch(tok) {
  31260. case TOK_LET:
  31261. var_def_type = JS_VAR_DEF_LET;
  31262. break;
  31263. case TOK_CONST:
  31264. var_def_type = JS_VAR_DEF_CONST;
  31265. break;
  31266. case TOK_VAR:
  31267. var_def_type = JS_VAR_DEF_VAR;
  31268. break;
  31269. case TOK_CATCH:
  31270. var_def_type = JS_VAR_DEF_CATCH;
  31271. break;
  31272. default:
  31273. abort();
  31274. }
  31275. if (define_var(s, fd, name, var_def_type) < 0)
  31276. return -1;
  31277. return 0;
  31278. }
  31279. static void js_emit_spread_code(JSParseState *s, int depth)
  31280. {
  31281. int label_rest_next, label_rest_done;
  31282. /* XXX: could check if enum object is an actual array and optimize
  31283. slice extraction. enumeration record and target array are in a
  31284. different order from OP_append case. */
  31285. /* enum_rec xxx -- enum_rec xxx array 0 */
  31286. emit_op(s, OP_array_from);
  31287. emit_u16(s, 0);
  31288. emit_op(s, OP_push_i32);
  31289. emit_u32(s, 0);
  31290. emit_label(s, label_rest_next = new_label(s));
  31291. emit_op(s, OP_for_of_next);
  31292. emit_u8(s, 2 + depth);
  31293. label_rest_done = emit_goto(s, OP_if_true, -1);
  31294. /* array idx val -- array idx */
  31295. emit_op(s, OP_define_array_el);
  31296. emit_op(s, OP_inc);
  31297. emit_goto(s, OP_goto, label_rest_next);
  31298. emit_label(s, label_rest_done);
  31299. /* enum_rec xxx array idx undef -- enum_rec xxx array */
  31300. emit_op(s, OP_drop);
  31301. emit_op(s, OP_drop);
  31302. }
  31303. static int js_parse_check_duplicate_parameter(JSParseState *s, JSAtom name)
  31304. {
  31305. /* Check for duplicate parameter names */
  31306. JSFunctionDef *fd = s->cur_func;
  31307. int i;
  31308. for (i = 0; i < fd->arg_count; i++) {
  31309. if (fd->args[i].var_name == name)
  31310. goto duplicate;
  31311. }
  31312. for (i = 0; i < fd->var_count; i++) {
  31313. if (fd->vars[i].var_name == name)
  31314. goto duplicate;
  31315. }
  31316. return 0;
  31317. duplicate:
  31318. return js_parse_error(s, "Duplicate parameter name not allowed in this context");
  31319. }
  31320. static JSAtom js_parse_destructuring_var(JSParseState *s, int tok, bool is_arg)
  31321. {
  31322. JSAtom name;
  31323. if (!(s->token.val == TOK_IDENT && !s->token.u.ident.is_reserved)
  31324. || (s->cur_func->is_strict_mode &&
  31325. (s->token.u.ident.atom == JS_ATOM_eval || s->token.u.ident.atom == JS_ATOM_arguments))) {
  31326. js_parse_error(s, "invalid destructuring target");
  31327. return JS_ATOM_NULL;
  31328. }
  31329. name = JS_DupAtom(s->ctx, s->token.u.ident.atom);
  31330. if (is_arg && js_parse_check_duplicate_parameter(s, name))
  31331. goto fail;
  31332. if (next_token(s))
  31333. goto fail;
  31334. return name;
  31335. fail:
  31336. JS_FreeAtom(s->ctx, name);
  31337. return JS_ATOM_NULL;
  31338. }
  31339. /* Return -1 if error, 0 if no initializer, 1 if an initializer is
  31340. present at the top level. */
  31341. static int js_parse_destructuring_element(JSParseState *s, int tok,
  31342. bool is_arg, bool hasval,
  31343. int has_ellipsis, // tri-state
  31344. bool allow_initializer,
  31345. bool export_flag)
  31346. {
  31347. int label_parse, label_assign, label_done, label_lvalue, depth_lvalue;
  31348. int start_addr, assign_addr;
  31349. JSAtom prop_name, var_name;
  31350. int opcode, scope, tok1, skip_bits;
  31351. bool has_initializer;
  31352. label_lvalue = -1;
  31353. if (has_ellipsis < 0) {
  31354. /* pre-parse destructuration target for spread detection */
  31355. js_parse_skip_parens_token(s, &skip_bits, false);
  31356. has_ellipsis = skip_bits & SKIP_HAS_ELLIPSIS;
  31357. }
  31358. label_parse = new_label(s);
  31359. label_assign = new_label(s);
  31360. start_addr = s->cur_func->byte_code.size;
  31361. if (hasval) {
  31362. /* consume value from the stack */
  31363. emit_op(s, OP_dup);
  31364. emit_op(s, OP_undefined);
  31365. emit_op(s, OP_strict_eq);
  31366. emit_goto(s, OP_if_true, label_parse);
  31367. emit_label(s, label_assign);
  31368. } else {
  31369. emit_goto(s, OP_goto, label_parse);
  31370. emit_label(s, label_assign);
  31371. /* leave value on the stack */
  31372. emit_op(s, OP_dup);
  31373. }
  31374. assign_addr = s->cur_func->byte_code.size;
  31375. if (s->token.val == '{') {
  31376. if (next_token(s))
  31377. return -1;
  31378. /* throw an exception if the value cannot be converted to an object */
  31379. emit_op(s, OP_to_object);
  31380. if (has_ellipsis) {
  31381. /* add excludeList on stack just below src object */
  31382. emit_op(s, OP_object);
  31383. emit_op(s, OP_swap);
  31384. }
  31385. while (s->token.val != '}') {
  31386. int prop_type;
  31387. if (s->token.val == TOK_ELLIPSIS) {
  31388. if (!has_ellipsis) {
  31389. JS_ThrowInternalError(s->ctx, "unexpected ellipsis token");
  31390. return -1;
  31391. }
  31392. if (next_token(s))
  31393. return -1;
  31394. if (tok) {
  31395. var_name = js_parse_destructuring_var(s, tok, is_arg);
  31396. if (var_name == JS_ATOM_NULL)
  31397. return -1;
  31398. opcode = OP_scope_get_var;
  31399. scope = s->cur_func->scope_level;
  31400. label_lvalue = -1;
  31401. depth_lvalue = 0;
  31402. } else {
  31403. if (js_parse_left_hand_side_expr(s))
  31404. return -1;
  31405. if (get_lvalue(s, &opcode, &scope, &var_name,
  31406. &label_lvalue, &depth_lvalue, false, '{'))
  31407. return -1;
  31408. }
  31409. if (s->token.val != '}') {
  31410. js_parse_error(s, "assignment rest property must be last");
  31411. goto var_error;
  31412. }
  31413. emit_op(s, OP_object); /* target */
  31414. emit_op(s, OP_copy_data_properties);
  31415. emit_u8(s, 0 | ((depth_lvalue + 1) << 2) | ((depth_lvalue + 2) << 5));
  31416. goto set_val;
  31417. }
  31418. prop_type = js_parse_property_name(s, &prop_name, false, true, false);
  31419. if (prop_type < 0)
  31420. return -1;
  31421. var_name = JS_ATOM_NULL;
  31422. opcode = OP_scope_get_var;
  31423. scope = s->cur_func->scope_level;
  31424. label_lvalue = -1;
  31425. depth_lvalue = 0;
  31426. if (prop_type == PROP_TYPE_IDENT) {
  31427. if (next_token(s))
  31428. goto prop_error;
  31429. if ((s->token.val == '[' || s->token.val == '{')
  31430. && ((tok1 = js_parse_skip_parens_token(s, &skip_bits, false)) == ',' ||
  31431. tok1 == '=' || tok1 == '}')) {
  31432. if (prop_name == JS_ATOM_NULL) {
  31433. /* computed property name on stack */
  31434. if (has_ellipsis) {
  31435. /* define the property in excludeList */
  31436. emit_op(s, OP_to_propkey); /* avoid calling ToString twice */
  31437. emit_op(s, OP_perm3); /* TOS: src excludeList prop */
  31438. emit_op(s, OP_null); /* TOS: src excludeList prop null */
  31439. emit_op(s, OP_define_array_el); /* TOS: src excludeList prop */
  31440. emit_op(s, OP_perm3); /* TOS: excludeList src prop */
  31441. }
  31442. /* get the computed property from the source object */
  31443. emit_op(s, OP_get_array_el2);
  31444. } else {
  31445. /* named property */
  31446. if (has_ellipsis) {
  31447. /* define the property in excludeList */
  31448. emit_op(s, OP_swap); /* TOS: src excludeList */
  31449. emit_op(s, OP_null); /* TOS: src excludeList null */
  31450. emit_op(s, OP_define_field); /* TOS: src excludeList */
  31451. emit_atom(s, prop_name);
  31452. emit_op(s, OP_swap); /* TOS: excludeList src */
  31453. }
  31454. /* get the named property from the source object */
  31455. emit_op(s, OP_get_field2);
  31456. emit_u32(s, prop_name);
  31457. }
  31458. if (js_parse_destructuring_element(s, tok, is_arg, true, -1, true, export_flag) < 0)
  31459. return -1;
  31460. if (s->token.val == '}')
  31461. break;
  31462. /* accept a trailing comma before the '}' */
  31463. if (js_parse_expect(s, ','))
  31464. return -1;
  31465. continue;
  31466. }
  31467. if (prop_name == JS_ATOM_NULL) {
  31468. emit_op(s, OP_to_propkey2);
  31469. if (has_ellipsis) {
  31470. /* define the property in excludeList */
  31471. emit_op(s, OP_perm3);
  31472. emit_op(s, OP_null);
  31473. emit_op(s, OP_define_array_el);
  31474. emit_op(s, OP_perm3);
  31475. }
  31476. /* source prop -- source source prop */
  31477. emit_op(s, OP_dup1);
  31478. } else {
  31479. if (has_ellipsis) {
  31480. /* define the property in excludeList */
  31481. emit_op(s, OP_swap);
  31482. emit_op(s, OP_null);
  31483. emit_op(s, OP_define_field);
  31484. emit_atom(s, prop_name);
  31485. emit_op(s, OP_swap);
  31486. }
  31487. /* source -- source source */
  31488. emit_op(s, OP_dup);
  31489. }
  31490. if (tok) {
  31491. var_name = js_parse_destructuring_var(s, tok, is_arg);
  31492. if (var_name == JS_ATOM_NULL)
  31493. goto prop_error;
  31494. } else {
  31495. if (js_parse_left_hand_side_expr(s))
  31496. goto prop_error;
  31497. lvalue:
  31498. if (get_lvalue(s, &opcode, &scope, &var_name,
  31499. &label_lvalue, &depth_lvalue, false, '{'))
  31500. goto prop_error;
  31501. /* swap ref and lvalue object if any */
  31502. if (prop_name == JS_ATOM_NULL) {
  31503. switch(depth_lvalue) {
  31504. case 1:
  31505. /* source prop x -> x source prop */
  31506. emit_op(s, OP_rot3r);
  31507. break;
  31508. case 2:
  31509. /* source prop x y -> x y source prop */
  31510. emit_op(s, OP_swap2); /* t p2 s p1 */
  31511. break;
  31512. case 3:
  31513. /* source prop x y z -> x y z source prop */
  31514. emit_op(s, OP_rot5l);
  31515. emit_op(s, OP_rot5l);
  31516. break;
  31517. }
  31518. } else {
  31519. switch(depth_lvalue) {
  31520. case 1:
  31521. /* source x -> x source */
  31522. emit_op(s, OP_swap);
  31523. break;
  31524. case 2:
  31525. /* source x y -> x y source */
  31526. emit_op(s, OP_rot3l);
  31527. break;
  31528. case 3:
  31529. /* source x y z -> x y z source */
  31530. emit_op(s, OP_rot4l);
  31531. break;
  31532. }
  31533. }
  31534. }
  31535. if (prop_name == JS_ATOM_NULL) {
  31536. /* computed property name on stack */
  31537. /* XXX: should have OP_get_array_el2x with depth */
  31538. /* source prop -- val */
  31539. emit_op(s, OP_get_array_el);
  31540. } else {
  31541. /* named property */
  31542. /* XXX: should have OP_get_field2x with depth */
  31543. /* source -- val */
  31544. emit_op(s, OP_get_field);
  31545. emit_u32(s, prop_name);
  31546. }
  31547. } else {
  31548. /* prop_type = PROP_TYPE_VAR, cannot be a computed property */
  31549. if (is_arg && js_parse_check_duplicate_parameter(s, prop_name))
  31550. goto prop_error;
  31551. if (s->cur_func->is_strict_mode &&
  31552. (prop_name == JS_ATOM_eval || prop_name == JS_ATOM_arguments)) {
  31553. js_parse_error(s, "invalid destructuring target");
  31554. goto prop_error;
  31555. }
  31556. if (has_ellipsis) {
  31557. /* define the property in excludeList */
  31558. emit_op(s, OP_swap);
  31559. emit_op(s, OP_null);
  31560. emit_op(s, OP_define_field);
  31561. emit_atom(s, prop_name);
  31562. emit_op(s, OP_swap);
  31563. }
  31564. if (!tok || tok == TOK_VAR) {
  31565. /* generate reference */
  31566. /* source -- source source */
  31567. emit_op(s, OP_dup);
  31568. emit_op(s, OP_scope_get_var);
  31569. emit_atom(s, prop_name);
  31570. emit_u16(s, s->cur_func->scope_level);
  31571. goto lvalue;
  31572. }
  31573. var_name = JS_DupAtom(s->ctx, prop_name);
  31574. /* source -- source val */
  31575. emit_op(s, OP_get_field2);
  31576. emit_u32(s, prop_name);
  31577. }
  31578. set_val:
  31579. if (tok) {
  31580. if (js_define_var(s, var_name, tok))
  31581. goto var_error;
  31582. if (export_flag) {
  31583. if (!add_export_entry(s, s->cur_func->module, var_name, var_name,
  31584. JS_EXPORT_TYPE_LOCAL))
  31585. goto var_error;
  31586. }
  31587. scope = s->cur_func->scope_level;
  31588. }
  31589. if (s->token.val == '=') { /* handle optional default value */
  31590. int label_hasval;
  31591. emit_op(s, OP_dup);
  31592. emit_op(s, OP_undefined);
  31593. emit_op(s, OP_strict_eq);
  31594. label_hasval = emit_goto(s, OP_if_false, -1);
  31595. if (next_token(s))
  31596. goto var_error;
  31597. emit_op(s, OP_drop);
  31598. if (js_parse_assign_expr(s))
  31599. goto var_error;
  31600. if (opcode == OP_scope_get_var || opcode == OP_get_ref_value)
  31601. set_object_name(s, var_name);
  31602. emit_label(s, label_hasval);
  31603. }
  31604. /* store value into lvalue object */
  31605. put_lvalue(s, opcode, scope, var_name, label_lvalue,
  31606. PUT_LVALUE_NOKEEP_DEPTH,
  31607. (tok == TOK_CONST || tok == TOK_LET));
  31608. if (s->token.val == '}')
  31609. break;
  31610. /* accept a trailing comma before the '}' */
  31611. if (js_parse_expect(s, ','))
  31612. return -1;
  31613. }
  31614. /* drop the source object */
  31615. emit_op(s, OP_drop);
  31616. if (has_ellipsis) {
  31617. emit_op(s, OP_drop); /* pop excludeList */
  31618. }
  31619. if (next_token(s))
  31620. return -1;
  31621. } else if (s->token.val == '[') {
  31622. bool has_spread;
  31623. int enum_depth;
  31624. BlockEnv block_env;
  31625. if (next_token(s))
  31626. return -1;
  31627. /* the block environment is only needed in generators in case
  31628. 'yield' triggers a 'return' */
  31629. push_break_entry(s->cur_func, &block_env,
  31630. JS_ATOM_NULL, -1, -1, 2);
  31631. block_env.has_iterator = true;
  31632. emit_op(s, OP_for_of_start);
  31633. has_spread = false;
  31634. while (s->token.val != ']') {
  31635. /* get the next value */
  31636. if (s->token.val == TOK_ELLIPSIS) {
  31637. if (next_token(s))
  31638. return -1;
  31639. if (s->token.val == ',' || s->token.val == ']')
  31640. return js_parse_error(s, "missing binding pattern...");
  31641. has_spread = true;
  31642. }
  31643. if (s->token.val == ',') {
  31644. /* do nothing, skip the value, has_spread is false */
  31645. emit_op(s, OP_for_of_next);
  31646. emit_u8(s, 0);
  31647. emit_op(s, OP_drop);
  31648. emit_op(s, OP_drop);
  31649. } else if ((s->token.val == '[' || s->token.val == '{')
  31650. && ((tok1 = js_parse_skip_parens_token(s, &skip_bits, false)) == ',' ||
  31651. tok1 == '=' || tok1 == ']')) {
  31652. if (has_spread) {
  31653. if (tok1 == '=')
  31654. return js_parse_error(s, "rest element cannot have a default value");
  31655. js_emit_spread_code(s, 0);
  31656. } else {
  31657. emit_op(s, OP_for_of_next);
  31658. emit_u8(s, 0);
  31659. emit_op(s, OP_drop);
  31660. }
  31661. if (js_parse_destructuring_element(s, tok, is_arg, true, skip_bits & SKIP_HAS_ELLIPSIS, true, export_flag) < 0)
  31662. return -1;
  31663. } else {
  31664. var_name = JS_ATOM_NULL;
  31665. enum_depth = 0;
  31666. if (tok) {
  31667. var_name = js_parse_destructuring_var(s, tok, is_arg);
  31668. if (var_name == JS_ATOM_NULL)
  31669. goto var_error;
  31670. if (js_define_var(s, var_name, tok))
  31671. goto var_error;
  31672. opcode = OP_scope_get_var;
  31673. scope = s->cur_func->scope_level;
  31674. } else {
  31675. if (js_parse_left_hand_side_expr(s))
  31676. return -1;
  31677. if (get_lvalue(s, &opcode, &scope, &var_name,
  31678. &label_lvalue, &enum_depth, false, '[')) {
  31679. return -1;
  31680. }
  31681. }
  31682. if (has_spread) {
  31683. js_emit_spread_code(s, enum_depth);
  31684. } else {
  31685. emit_op(s, OP_for_of_next);
  31686. emit_u8(s, enum_depth);
  31687. emit_op(s, OP_drop);
  31688. }
  31689. if (s->token.val == '=' && !has_spread) {
  31690. /* handle optional default value */
  31691. int label_hasval;
  31692. emit_op(s, OP_dup);
  31693. emit_op(s, OP_undefined);
  31694. emit_op(s, OP_strict_eq);
  31695. label_hasval = emit_goto(s, OP_if_false, -1);
  31696. if (next_token(s))
  31697. goto var_error;
  31698. emit_op(s, OP_drop);
  31699. if (js_parse_assign_expr(s))
  31700. goto var_error;
  31701. if (opcode == OP_scope_get_var || opcode == OP_get_ref_value)
  31702. set_object_name(s, var_name);
  31703. emit_label(s, label_hasval);
  31704. }
  31705. /* store value into lvalue object */
  31706. put_lvalue(s, opcode, scope, var_name,
  31707. label_lvalue, PUT_LVALUE_NOKEEP_DEPTH,
  31708. (tok == TOK_CONST || tok == TOK_LET));
  31709. }
  31710. if (s->token.val == ']')
  31711. break;
  31712. if (has_spread)
  31713. return js_parse_error(s, "rest element must be the last one");
  31714. /* accept a trailing comma before the ']' */
  31715. if (js_parse_expect(s, ','))
  31716. return -1;
  31717. }
  31718. /* close iterator object:
  31719. if completed, enum_obj has been replaced by undefined */
  31720. emit_op(s, OP_iterator_close);
  31721. pop_break_entry(s->cur_func);
  31722. if (next_token(s))
  31723. return -1;
  31724. } else {
  31725. return js_parse_error(s, "invalid assignment syntax");
  31726. }
  31727. if (s->token.val == '=' && allow_initializer) {
  31728. label_done = emit_goto(s, OP_goto, -1);
  31729. if (next_token(s))
  31730. return -1;
  31731. emit_label(s, label_parse);
  31732. if (hasval)
  31733. emit_op(s, OP_drop);
  31734. if (js_parse_assign_expr(s))
  31735. return -1;
  31736. emit_goto(s, OP_goto, label_assign);
  31737. emit_label(s, label_done);
  31738. has_initializer = true;
  31739. } else {
  31740. /* normally hasval is true except if
  31741. js_parse_skip_parens_token() was wrong in the parsing */
  31742. // assert(hasval);
  31743. if (!hasval) {
  31744. js_parse_error(s, "too complicated destructuring expression");
  31745. return -1;
  31746. }
  31747. /* remove test and decrement label ref count */
  31748. memset(s->cur_func->byte_code.buf + start_addr, OP_nop,
  31749. assign_addr - start_addr);
  31750. s->cur_func->label_slots[label_parse].ref_count--;
  31751. has_initializer = false;
  31752. }
  31753. return has_initializer;
  31754. prop_error:
  31755. JS_FreeAtom(s->ctx, prop_name);
  31756. var_error:
  31757. JS_FreeAtom(s->ctx, var_name);
  31758. return -1;
  31759. }
  31760. typedef enum FuncCallType {
  31761. FUNC_CALL_NORMAL,
  31762. FUNC_CALL_NEW,
  31763. FUNC_CALL_SUPER_CTOR,
  31764. FUNC_CALL_TEMPLATE,
  31765. } FuncCallType;
  31766. static void optional_chain_test(JSParseState *s, int *poptional_chaining_label,
  31767. int drop_count)
  31768. {
  31769. int label_next, i;
  31770. if (*poptional_chaining_label < 0)
  31771. *poptional_chaining_label = new_label(s);
  31772. /* XXX: could be more efficient with a specific opcode */
  31773. emit_op(s, OP_dup);
  31774. emit_op(s, OP_is_undefined_or_null);
  31775. label_next = emit_goto(s, OP_if_false, -1);
  31776. for(i = 0; i < drop_count; i++)
  31777. emit_op(s, OP_drop);
  31778. emit_op(s, OP_undefined);
  31779. emit_goto(s, OP_goto, *poptional_chaining_label);
  31780. emit_label(s, label_next);
  31781. }
  31782. /* allowed parse_flags: PF_POSTFIX_CALL */
  31783. static __exception int js_parse_postfix_expr(JSParseState *s, int parse_flags)
  31784. {
  31785. FuncCallType call_type;
  31786. int optional_chaining_label;
  31787. bool accept_lparen = (parse_flags & PF_POSTFIX_CALL) != 0;
  31788. call_type = FUNC_CALL_NORMAL;
  31789. switch(s->token.val) {
  31790. case TOK_NUMBER:
  31791. {
  31792. JSValue val;
  31793. val = s->token.u.num.val;
  31794. if (JS_VALUE_GET_TAG(val) == JS_TAG_INT) {
  31795. emit_op(s, OP_push_i32);
  31796. emit_u32(s, JS_VALUE_GET_INT(val));
  31797. } else {
  31798. if (emit_push_const(s, val, 0) < 0)
  31799. return -1;
  31800. }
  31801. }
  31802. if (next_token(s))
  31803. return -1;
  31804. break;
  31805. case TOK_TEMPLATE:
  31806. if (js_parse_template(s, 0, NULL))
  31807. return -1;
  31808. break;
  31809. case TOK_STRING:
  31810. if (emit_push_const(s, s->token.u.str.str, 1))
  31811. return -1;
  31812. if (next_token(s))
  31813. return -1;
  31814. break;
  31815. case TOK_DIV_ASSIGN:
  31816. s->buf_ptr -= 2;
  31817. goto parse_regexp;
  31818. case '/':
  31819. s->buf_ptr--;
  31820. parse_regexp:
  31821. {
  31822. JSValue str;
  31823. int ret, backtrace_flags;
  31824. if (!s->ctx->compile_regexp)
  31825. return js_parse_error(s, "RegExp are not supported");
  31826. /* the previous token is '/' or '/=', so no need to free */
  31827. if (js_parse_regexp(s))
  31828. return -1;
  31829. ret = emit_push_const(s, s->token.u.regexp.body, 0);
  31830. str = s->ctx->compile_regexp(s->ctx, s->token.u.regexp.body,
  31831. s->token.u.regexp.flags);
  31832. if (JS_IsException(str)) {
  31833. /* add the line number info */
  31834. backtrace_flags = 0;
  31835. if (s->cur_func && s->cur_func->backtrace_barrier)
  31836. backtrace_flags = JS_BACKTRACE_FLAG_SINGLE_LEVEL;
  31837. build_backtrace(s->ctx, s->ctx->rt->current_exception, JS_UNDEFINED,
  31838. s->filename,
  31839. s->token.line_num,
  31840. s->token.col_num,
  31841. backtrace_flags);
  31842. return -1;
  31843. }
  31844. ret = emit_push_const(s, str, 0);
  31845. JS_FreeValue(s->ctx, str);
  31846. if (ret)
  31847. return -1;
  31848. /* we use a specific opcode to be sure the correct
  31849. function is called (otherwise the bytecode would have
  31850. to be verified by the RegExp constructor) */
  31851. emit_op(s, OP_regexp);
  31852. if (next_token(s))
  31853. return -1;
  31854. }
  31855. break;
  31856. case '(':
  31857. if (js_parse_expr_paren(s))
  31858. return -1;
  31859. break;
  31860. case TOK_FUNCTION:
  31861. if (js_parse_function_decl(s, JS_PARSE_FUNC_EXPR,
  31862. JS_FUNC_NORMAL, JS_ATOM_NULL,
  31863. s->token.ptr,
  31864. s->token.line_num,
  31865. s->token.col_num))
  31866. return -1;
  31867. break;
  31868. case TOK_CLASS:
  31869. if (js_parse_class(s, true, JS_PARSE_EXPORT_NONE))
  31870. return -1;
  31871. break;
  31872. case TOK_NULL:
  31873. if (next_token(s))
  31874. return -1;
  31875. emit_op(s, OP_null);
  31876. break;
  31877. case TOK_THIS:
  31878. if (next_token(s))
  31879. return -1;
  31880. emit_op(s, OP_scope_get_var);
  31881. emit_atom(s, JS_ATOM_this);
  31882. emit_u16(s, 0);
  31883. break;
  31884. case TOK_FALSE:
  31885. if (next_token(s))
  31886. return -1;
  31887. emit_op(s, OP_push_false);
  31888. break;
  31889. case TOK_TRUE:
  31890. if (next_token(s))
  31891. return -1;
  31892. emit_op(s, OP_push_true);
  31893. break;
  31894. case TOK_IDENT:
  31895. {
  31896. JSAtom name;
  31897. if (s->token.u.ident.is_reserved) {
  31898. return js_parse_error_reserved_identifier(s);
  31899. }
  31900. if (token_is_pseudo_keyword(s, JS_ATOM_async) &&
  31901. peek_token(s, true) != '\n') {
  31902. const uint8_t *source_ptr;
  31903. int source_line_num;
  31904. int source_col_num;
  31905. source_ptr = s->token.ptr;
  31906. source_line_num = s->token.line_num;
  31907. source_col_num = s->token.col_num;
  31908. if (next_token(s))
  31909. return -1;
  31910. if (s->token.val == TOK_FUNCTION) {
  31911. if (js_parse_function_decl(s, JS_PARSE_FUNC_EXPR,
  31912. JS_FUNC_ASYNC, JS_ATOM_NULL,
  31913. source_ptr,
  31914. source_line_num,
  31915. source_col_num))
  31916. return -1;
  31917. } else {
  31918. name = JS_DupAtom(s->ctx, JS_ATOM_async);
  31919. goto do_get_var;
  31920. }
  31921. } else {
  31922. if (s->token.u.ident.atom == JS_ATOM_arguments &&
  31923. !s->cur_func->arguments_allowed) {
  31924. js_parse_error(s, "'arguments' identifier is not allowed in class field initializer");
  31925. return -1;
  31926. }
  31927. name = JS_DupAtom(s->ctx, s->token.u.ident.atom);
  31928. if (next_token(s)) { /* update line number before emitting code */
  31929. JS_FreeAtom(s->ctx, name);
  31930. return -1;
  31931. }
  31932. do_get_var:
  31933. emit_op(s, OP_scope_get_var);
  31934. emit_u32(s, name);
  31935. emit_u16(s, s->cur_func->scope_level);
  31936. }
  31937. }
  31938. break;
  31939. case '{':
  31940. case '[':
  31941. {
  31942. int skip_bits;
  31943. if (js_parse_skip_parens_token(s, &skip_bits, false) == '=') {
  31944. if (js_parse_destructuring_element(s, 0, false, false, skip_bits & SKIP_HAS_ELLIPSIS, true, false) < 0)
  31945. return -1;
  31946. } else {
  31947. if (s->token.val == '{') {
  31948. if (js_parse_object_literal(s))
  31949. return -1;
  31950. } else {
  31951. if (js_parse_array_literal(s))
  31952. return -1;
  31953. }
  31954. }
  31955. }
  31956. break;
  31957. case TOK_NEW:
  31958. if (next_token(s))
  31959. return -1;
  31960. if (s->token.val == '.') {
  31961. if (next_token(s))
  31962. return -1;
  31963. if (!token_is_pseudo_keyword(s, JS_ATOM_target))
  31964. return js_parse_error(s, "expecting target");
  31965. if (!s->cur_func->new_target_allowed)
  31966. return js_parse_error(s, "new.target only allowed within functions");
  31967. if (next_token(s))
  31968. return -1;
  31969. emit_op(s, OP_scope_get_var);
  31970. emit_atom(s, JS_ATOM_new_target);
  31971. emit_u16(s, 0);
  31972. } else {
  31973. emit_source_loc(s);
  31974. if (js_parse_postfix_expr(s, 0))
  31975. return -1;
  31976. accept_lparen = true;
  31977. if (s->token.val != '(') {
  31978. /* new operator on an object */
  31979. emit_op(s, OP_dup);
  31980. emit_op(s, OP_call_constructor);
  31981. emit_u16(s, 0);
  31982. } else {
  31983. call_type = FUNC_CALL_NEW;
  31984. }
  31985. }
  31986. break;
  31987. case TOK_SUPER:
  31988. if (next_token(s))
  31989. return -1;
  31990. if (s->token.val == '(') {
  31991. if (!s->cur_func->super_call_allowed)
  31992. return js_parse_error(s, "super() is only valid in a derived class constructor");
  31993. call_type = FUNC_CALL_SUPER_CTOR;
  31994. } else if (s->token.val == '.' || s->token.val == '[') {
  31995. if (!s->cur_func->super_allowed)
  31996. return js_parse_error(s, "'super' is only valid in a method");
  31997. emit_op(s, OP_scope_get_var);
  31998. emit_atom(s, JS_ATOM_this);
  31999. emit_u16(s, 0);
  32000. emit_op(s, OP_scope_get_var);
  32001. emit_atom(s, JS_ATOM_home_object);
  32002. emit_u16(s, 0);
  32003. emit_op(s, OP_get_super);
  32004. } else {
  32005. return js_parse_error(s, "invalid use of 'super'");
  32006. }
  32007. break;
  32008. case TOK_IMPORT:
  32009. if (next_token(s))
  32010. return -1;
  32011. if (s->token.val == '.') {
  32012. if (next_token(s))
  32013. return -1;
  32014. if (!token_is_pseudo_keyword(s, JS_ATOM_meta))
  32015. return js_parse_error(s, "meta expected");
  32016. if (!s->is_module)
  32017. return js_parse_error(s, "import.meta only valid in module code");
  32018. if (next_token(s))
  32019. return -1;
  32020. emit_op(s, OP_special_object);
  32021. emit_u8(s, OP_SPECIAL_OBJECT_IMPORT_META);
  32022. } else {
  32023. if (js_parse_expect(s, '('))
  32024. return -1;
  32025. if (!accept_lparen)
  32026. return js_parse_error(s, "invalid use of 'import()'");
  32027. if (js_parse_assign_expr(s))
  32028. return -1;
  32029. if (js_parse_expect(s, ')'))
  32030. return -1;
  32031. emit_op(s, OP_import);
  32032. }
  32033. break;
  32034. default:
  32035. return js_parse_error(s, "unexpected token in expression: '%.*s'",
  32036. (int)(s->buf_ptr - s->token.ptr), s->token.ptr);
  32037. }
  32038. optional_chaining_label = -1;
  32039. for(;;) {
  32040. JSFunctionDef *fd = s->cur_func;
  32041. bool has_optional_chain = false;
  32042. if (s->token.val == TOK_QUESTION_MARK_DOT) {
  32043. /* optional chaining */
  32044. if (next_token(s))
  32045. return -1;
  32046. has_optional_chain = true;
  32047. if (s->token.val == '(' && accept_lparen) {
  32048. goto parse_func_call;
  32049. } else if (s->token.val == '[') {
  32050. goto parse_array_access;
  32051. } else {
  32052. goto parse_property;
  32053. }
  32054. } else if (s->token.val == TOK_TEMPLATE &&
  32055. call_type == FUNC_CALL_NORMAL) {
  32056. if (optional_chaining_label >= 0) {
  32057. return js_parse_error(s, "template literal cannot appear in an optional chain");
  32058. }
  32059. call_type = FUNC_CALL_TEMPLATE;
  32060. goto parse_func_call2;
  32061. } else if (s->token.val == '(' && accept_lparen) {
  32062. int opcode, arg_count, drop_count;
  32063. /* function call */
  32064. parse_func_call:
  32065. if (next_token(s))
  32066. return -1;
  32067. if (call_type == FUNC_CALL_NORMAL) {
  32068. parse_func_call2:
  32069. emit_source_loc(s);
  32070. switch(opcode = get_prev_opcode(fd)) {
  32071. case OP_get_field:
  32072. /* keep the object on the stack */
  32073. fd->byte_code.buf[fd->last_opcode_pos] = OP_get_field2;
  32074. drop_count = 2;
  32075. break;
  32076. case OP_get_field_opt_chain:
  32077. {
  32078. int opt_chain_label, next_label;
  32079. opt_chain_label = get_u32(fd->byte_code.buf +
  32080. fd->last_opcode_pos + 1 + 4 + 1);
  32081. /* keep the object on the stack */
  32082. fd->byte_code.buf[fd->last_opcode_pos] = OP_get_field2;
  32083. fd->byte_code.size = fd->last_opcode_pos + 1 + 4;
  32084. next_label = emit_goto(s, OP_goto, -1);
  32085. emit_label(s, opt_chain_label);
  32086. /* need an additional undefined value for the
  32087. case where the optional field does not
  32088. exists */
  32089. emit_op(s, OP_undefined);
  32090. emit_label(s, next_label);
  32091. drop_count = 2;
  32092. opcode = OP_get_field;
  32093. }
  32094. break;
  32095. case OP_scope_get_private_field:
  32096. /* keep the object on the stack */
  32097. fd->byte_code.buf[fd->last_opcode_pos] = OP_scope_get_private_field2;
  32098. drop_count = 2;
  32099. break;
  32100. case OP_get_array_el:
  32101. /* keep the object on the stack */
  32102. fd->byte_code.buf[fd->last_opcode_pos] = OP_get_array_el2;
  32103. drop_count = 2;
  32104. break;
  32105. case OP_get_array_el_opt_chain:
  32106. {
  32107. int opt_chain_label, next_label;
  32108. opt_chain_label = get_u32(fd->byte_code.buf +
  32109. fd->last_opcode_pos + 1 + 1);
  32110. /* keep the object on the stack */
  32111. fd->byte_code.buf[fd->last_opcode_pos] = OP_get_array_el2;
  32112. fd->byte_code.size = fd->last_opcode_pos + 1;
  32113. next_label = emit_goto(s, OP_goto, -1);
  32114. emit_label(s, opt_chain_label);
  32115. /* need an additional undefined value for the
  32116. case where the optional field does not
  32117. exists */
  32118. emit_op(s, OP_undefined);
  32119. emit_label(s, next_label);
  32120. drop_count = 2;
  32121. opcode = OP_get_array_el;
  32122. }
  32123. break;
  32124. case OP_scope_get_var:
  32125. {
  32126. JSAtom name;
  32127. int scope;
  32128. name = get_u32(fd->byte_code.buf + fd->last_opcode_pos + 1);
  32129. scope = get_u16(fd->byte_code.buf + fd->last_opcode_pos + 5);
  32130. if (name == JS_ATOM_eval && call_type == FUNC_CALL_NORMAL && !has_optional_chain) {
  32131. /* direct 'eval' */
  32132. opcode = OP_eval;
  32133. } else {
  32134. /* verify if function name resolves to a simple
  32135. get_loc/get_arg: a function call inside a `with`
  32136. statement can resolve to a method call of the
  32137. `with` context object
  32138. */
  32139. /* XXX: always generate the OP_scope_get_ref
  32140. and remove it in variable resolution
  32141. pass ? */
  32142. if (has_with_scope(fd, scope)) {
  32143. opcode = OP_scope_get_ref;
  32144. fd->byte_code.buf[fd->last_opcode_pos] = opcode;
  32145. }
  32146. }
  32147. drop_count = 1;
  32148. }
  32149. break;
  32150. case OP_get_super_value:
  32151. fd->byte_code.buf[fd->last_opcode_pos] = OP_get_array_el;
  32152. /* on stack: this func_obj */
  32153. opcode = OP_get_array_el;
  32154. drop_count = 2;
  32155. break;
  32156. default:
  32157. opcode = OP_invalid;
  32158. drop_count = 1;
  32159. break;
  32160. }
  32161. if (has_optional_chain) {
  32162. optional_chain_test(s, &optional_chaining_label,
  32163. drop_count);
  32164. }
  32165. } else {
  32166. opcode = OP_invalid;
  32167. }
  32168. if (call_type == FUNC_CALL_TEMPLATE) {
  32169. if (js_parse_template(s, 1, &arg_count))
  32170. return -1;
  32171. goto emit_func_call;
  32172. } else if (call_type == FUNC_CALL_SUPER_CTOR) {
  32173. emit_op(s, OP_scope_get_var);
  32174. emit_atom(s, JS_ATOM_this_active_func);
  32175. emit_u16(s, 0);
  32176. emit_op(s, OP_get_super);
  32177. emit_op(s, OP_scope_get_var);
  32178. emit_atom(s, JS_ATOM_new_target);
  32179. emit_u16(s, 0);
  32180. } else if (call_type == FUNC_CALL_NEW) {
  32181. emit_op(s, OP_dup); /* new.target = function */
  32182. }
  32183. /* parse arguments */
  32184. arg_count = 0;
  32185. while (s->token.val != ')') {
  32186. if (arg_count >= 65535) {
  32187. return js_parse_error(s, "Too many arguments in function call (only %d allowed)",
  32188. 65535 - 1);
  32189. }
  32190. if (s->token.val == TOK_ELLIPSIS)
  32191. break;
  32192. if (js_parse_assign_expr(s))
  32193. return -1;
  32194. arg_count++;
  32195. if (s->token.val == ')')
  32196. break;
  32197. /* accept a trailing comma before the ')' */
  32198. if (js_parse_expect(s, ','))
  32199. return -1;
  32200. }
  32201. if (s->token.val == TOK_ELLIPSIS) {
  32202. emit_op(s, OP_array_from);
  32203. emit_u16(s, arg_count);
  32204. emit_op(s, OP_push_i32);
  32205. emit_u32(s, arg_count);
  32206. /* on stack: array idx */
  32207. while (s->token.val != ')') {
  32208. if (s->token.val == TOK_ELLIPSIS) {
  32209. if (next_token(s))
  32210. return -1;
  32211. if (js_parse_assign_expr(s))
  32212. return -1;
  32213. /* XXX: could pass is_last indicator? */
  32214. emit_op(s, OP_append);
  32215. } else {
  32216. if (js_parse_assign_expr(s))
  32217. return -1;
  32218. /* array idx val */
  32219. emit_op(s, OP_define_array_el);
  32220. emit_op(s, OP_inc);
  32221. }
  32222. if (s->token.val == ')')
  32223. break;
  32224. /* accept a trailing comma before the ')' */
  32225. if (js_parse_expect(s, ','))
  32226. return -1;
  32227. }
  32228. if (next_token(s))
  32229. return -1;
  32230. /* drop the index */
  32231. emit_op(s, OP_drop);
  32232. /* apply function call */
  32233. switch(opcode) {
  32234. case OP_get_field:
  32235. case OP_scope_get_private_field:
  32236. case OP_get_array_el:
  32237. case OP_scope_get_ref:
  32238. /* obj func array -> func obj array */
  32239. emit_op(s, OP_perm3);
  32240. emit_op(s, OP_apply);
  32241. emit_u16(s, call_type == FUNC_CALL_NEW);
  32242. break;
  32243. case OP_eval:
  32244. emit_op(s, OP_apply_eval);
  32245. emit_u16(s, fd->scope_level);
  32246. fd->has_eval_call = true;
  32247. break;
  32248. default:
  32249. if (call_type == FUNC_CALL_SUPER_CTOR) {
  32250. emit_op(s, OP_apply);
  32251. emit_u16(s, 1);
  32252. /* set the 'this' value */
  32253. emit_op(s, OP_dup);
  32254. emit_op(s, OP_scope_put_var_init);
  32255. emit_atom(s, JS_ATOM_this);
  32256. emit_u16(s, 0);
  32257. emit_class_field_init(s);
  32258. } else if (call_type == FUNC_CALL_NEW) {
  32259. /* obj func array -> func obj array */
  32260. emit_op(s, OP_perm3);
  32261. emit_op(s, OP_apply);
  32262. emit_u16(s, 1);
  32263. } else {
  32264. /* func array -> func undef array */
  32265. emit_op(s, OP_undefined);
  32266. emit_op(s, OP_swap);
  32267. emit_op(s, OP_apply);
  32268. emit_u16(s, 0);
  32269. }
  32270. break;
  32271. }
  32272. } else {
  32273. if (next_token(s))
  32274. return -1;
  32275. emit_func_call:
  32276. switch(opcode) {
  32277. case OP_get_field:
  32278. case OP_scope_get_private_field:
  32279. case OP_get_array_el:
  32280. case OP_scope_get_ref:
  32281. emit_op(s, OP_call_method);
  32282. emit_u16(s, arg_count);
  32283. break;
  32284. case OP_eval:
  32285. emit_op(s, OP_eval);
  32286. emit_u16(s, arg_count);
  32287. emit_u16(s, fd->scope_level);
  32288. fd->has_eval_call = true;
  32289. break;
  32290. default:
  32291. if (call_type == FUNC_CALL_SUPER_CTOR) {
  32292. emit_op(s, OP_call_constructor);
  32293. emit_u16(s, arg_count);
  32294. /* set the 'this' value */
  32295. emit_op(s, OP_dup);
  32296. emit_op(s, OP_scope_put_var_init);
  32297. emit_atom(s, JS_ATOM_this);
  32298. emit_u16(s, 0);
  32299. emit_class_field_init(s);
  32300. } else if (call_type == FUNC_CALL_NEW) {
  32301. emit_op(s, OP_call_constructor);
  32302. emit_u16(s, arg_count);
  32303. } else {
  32304. emit_op(s, OP_call);
  32305. emit_u16(s, arg_count);
  32306. }
  32307. break;
  32308. }
  32309. }
  32310. call_type = FUNC_CALL_NORMAL;
  32311. } else if (s->token.val == '.') {
  32312. if (next_token(s))
  32313. return -1;
  32314. parse_property:
  32315. if (s->token.val == TOK_PRIVATE_NAME) {
  32316. /* private class field */
  32317. if (get_prev_opcode(fd) == OP_get_super) {
  32318. return js_parse_error(s, "private class field forbidden after super");
  32319. }
  32320. if (has_optional_chain) {
  32321. optional_chain_test(s, &optional_chaining_label, 1);
  32322. }
  32323. emit_op(s, OP_scope_get_private_field);
  32324. emit_atom(s, s->token.u.ident.atom);
  32325. emit_u16(s, s->cur_func->scope_level);
  32326. } else {
  32327. if (!token_is_ident(s->token.val)) {
  32328. return js_parse_error(s, "expecting field name");
  32329. }
  32330. if (get_prev_opcode(fd) == OP_get_super) {
  32331. JSValue val;
  32332. int ret;
  32333. val = JS_AtomToValue(s->ctx, s->token.u.ident.atom);
  32334. ret = emit_push_const(s, val, 1);
  32335. JS_FreeValue(s->ctx, val);
  32336. if (ret)
  32337. return -1;
  32338. emit_op(s, OP_get_super_value);
  32339. } else {
  32340. if (has_optional_chain) {
  32341. optional_chain_test(s, &optional_chaining_label, 1);
  32342. }
  32343. emit_op(s, OP_get_field);
  32344. emit_atom(s, s->token.u.ident.atom);
  32345. }
  32346. }
  32347. if (next_token(s))
  32348. return -1;
  32349. } else if (s->token.val == '[') {
  32350. int prev_op;
  32351. parse_array_access:
  32352. prev_op = get_prev_opcode(fd);
  32353. if (has_optional_chain) {
  32354. optional_chain_test(s, &optional_chaining_label, 1);
  32355. }
  32356. if (next_token(s))
  32357. return -1;
  32358. if (js_parse_expr(s))
  32359. return -1;
  32360. if (js_parse_expect(s, ']'))
  32361. return -1;
  32362. if (prev_op == OP_get_super) {
  32363. emit_op(s, OP_get_super_value);
  32364. } else {
  32365. emit_op(s, OP_get_array_el);
  32366. }
  32367. } else {
  32368. break;
  32369. }
  32370. }
  32371. if (optional_chaining_label >= 0) {
  32372. JSFunctionDef *fd = s->cur_func;
  32373. int opcode;
  32374. emit_label_raw(s, optional_chaining_label);
  32375. /* modify the last opcode so that it is an indicator of an
  32376. optional chain */
  32377. opcode = get_prev_opcode(fd);
  32378. if (opcode == OP_get_field || opcode == OP_get_array_el) {
  32379. if (opcode == OP_get_field)
  32380. opcode = OP_get_field_opt_chain;
  32381. else
  32382. opcode = OP_get_array_el_opt_chain;
  32383. fd->byte_code.buf[fd->last_opcode_pos] = opcode;
  32384. } else {
  32385. fd->last_opcode_pos = -1;
  32386. }
  32387. }
  32388. return 0;
  32389. }
  32390. static __exception int js_parse_delete(JSParseState *s)
  32391. {
  32392. JSFunctionDef *fd = s->cur_func;
  32393. JSAtom name;
  32394. int opcode;
  32395. if (next_token(s))
  32396. return -1;
  32397. if (js_parse_unary(s, PF_POW_FORBIDDEN))
  32398. return -1;
  32399. switch(opcode = get_prev_opcode(fd)) {
  32400. case OP_get_field:
  32401. case OP_get_field_opt_chain:
  32402. {
  32403. JSValue val;
  32404. int ret, opt_chain_label, next_label;
  32405. if (opcode == OP_get_field_opt_chain) {
  32406. opt_chain_label = get_u32(fd->byte_code.buf +
  32407. fd->last_opcode_pos + 1 + 4 + 1);
  32408. } else {
  32409. opt_chain_label = -1;
  32410. }
  32411. name = get_u32(fd->byte_code.buf + fd->last_opcode_pos + 1);
  32412. fd->byte_code.size = fd->last_opcode_pos;
  32413. val = JS_AtomToValue(s->ctx, name);
  32414. ret = emit_push_const(s, val, 1);
  32415. JS_FreeValue(s->ctx, val);
  32416. JS_FreeAtom(s->ctx, name);
  32417. if (ret)
  32418. return ret;
  32419. emit_op(s, OP_delete);
  32420. if (opt_chain_label >= 0) {
  32421. next_label = emit_goto(s, OP_goto, -1);
  32422. emit_label(s, opt_chain_label);
  32423. /* if the optional chain is not taken, return 'true' */
  32424. emit_op(s, OP_drop);
  32425. emit_op(s, OP_push_true);
  32426. emit_label(s, next_label);
  32427. }
  32428. fd->last_opcode_pos = -1;
  32429. }
  32430. break;
  32431. case OP_get_array_el:
  32432. fd->byte_code.size = fd->last_opcode_pos;
  32433. fd->last_opcode_pos = -1;
  32434. emit_op(s, OP_delete);
  32435. break;
  32436. case OP_get_array_el_opt_chain:
  32437. {
  32438. int opt_chain_label, next_label;
  32439. opt_chain_label = get_u32(fd->byte_code.buf +
  32440. fd->last_opcode_pos + 1 + 1);
  32441. fd->byte_code.size = fd->last_opcode_pos;
  32442. emit_op(s, OP_delete);
  32443. next_label = emit_goto(s, OP_goto, -1);
  32444. emit_label(s, opt_chain_label);
  32445. /* if the optional chain is not taken, return 'true' */
  32446. emit_op(s, OP_drop);
  32447. emit_op(s, OP_push_true);
  32448. emit_label(s, next_label);
  32449. fd->last_opcode_pos = -1;
  32450. }
  32451. break;
  32452. case OP_scope_get_var:
  32453. /* 'delete this': this is not a reference */
  32454. name = get_u32(fd->byte_code.buf + fd->last_opcode_pos + 1);
  32455. if (name == JS_ATOM_this || name == JS_ATOM_new_target)
  32456. goto ret_true;
  32457. if (fd->is_strict_mode) {
  32458. return js_parse_error(s, "cannot delete a direct reference in strict mode");
  32459. } else {
  32460. fd->byte_code.buf[fd->last_opcode_pos] = OP_scope_delete_var;
  32461. }
  32462. break;
  32463. case OP_scope_get_private_field:
  32464. return js_parse_error(s, "cannot delete a private class field");
  32465. case OP_get_super_value:
  32466. fd->byte_code.size = fd->last_opcode_pos;
  32467. fd->last_opcode_pos = -1;
  32468. emit_op(s, OP_throw_error);
  32469. emit_atom(s, JS_ATOM_NULL);
  32470. emit_u8(s, JS_THROW_ERROR_DELETE_SUPER);
  32471. break;
  32472. default:
  32473. ret_true:
  32474. emit_op(s, OP_drop);
  32475. emit_op(s, OP_push_true);
  32476. break;
  32477. }
  32478. return 0;
  32479. }
  32480. /* allowed parse_flags: PF_POW_ALLOWED, PF_POW_FORBIDDEN */
  32481. static __exception int js_parse_unary(JSParseState *s, int parse_flags)
  32482. {
  32483. int op;
  32484. switch(s->token.val) {
  32485. case '+':
  32486. case '-':
  32487. case '!':
  32488. case '~':
  32489. case TOK_VOID:
  32490. op = s->token.val;
  32491. if (next_token(s))
  32492. return -1;
  32493. if (js_parse_unary(s, PF_POW_FORBIDDEN))
  32494. return -1;
  32495. switch(op) {
  32496. case '-':
  32497. emit_op(s, OP_neg);
  32498. break;
  32499. case '+':
  32500. emit_op(s, OP_plus);
  32501. break;
  32502. case '!':
  32503. emit_op(s, OP_lnot);
  32504. break;
  32505. case '~':
  32506. emit_op(s, OP_not);
  32507. break;
  32508. case TOK_VOID:
  32509. emit_op(s, OP_drop);
  32510. emit_op(s, OP_undefined);
  32511. break;
  32512. default:
  32513. abort();
  32514. }
  32515. parse_flags = 0;
  32516. break;
  32517. case TOK_DEC:
  32518. case TOK_INC:
  32519. {
  32520. int opcode, op, scope, label;
  32521. JSAtom name;
  32522. op = s->token.val;
  32523. if (next_token(s))
  32524. return -1;
  32525. if (js_parse_unary(s, 0))
  32526. return -1;
  32527. if (get_lvalue(s, &opcode, &scope, &name, &label, NULL, true, op))
  32528. return -1;
  32529. emit_op(s, OP_dec + op - TOK_DEC);
  32530. put_lvalue(s, opcode, scope, name, label, PUT_LVALUE_KEEP_TOP,
  32531. false);
  32532. }
  32533. break;
  32534. case TOK_TYPEOF:
  32535. {
  32536. JSFunctionDef *fd;
  32537. if (next_token(s))
  32538. return -1;
  32539. if (js_parse_unary(s, PF_POW_FORBIDDEN))
  32540. return -1;
  32541. /* reference access should not return an exception, so we
  32542. patch the get_var */
  32543. fd = s->cur_func;
  32544. if (get_prev_opcode(fd) == OP_scope_get_var) {
  32545. fd->byte_code.buf[fd->last_opcode_pos] = OP_scope_get_var_undef;
  32546. }
  32547. emit_op(s, OP_typeof);
  32548. parse_flags = 0;
  32549. }
  32550. break;
  32551. case TOK_DELETE:
  32552. if (js_parse_delete(s))
  32553. return -1;
  32554. parse_flags = 0;
  32555. break;
  32556. case TOK_AWAIT:
  32557. if (!(s->cur_func->func_kind & JS_FUNC_ASYNC))
  32558. return js_parse_error(s, "unexpected 'await' keyword");
  32559. if (!s->cur_func->in_function_body)
  32560. return js_parse_error(s, "await in default expression");
  32561. if (next_token(s))
  32562. return -1;
  32563. if (js_parse_unary(s, PF_POW_FORBIDDEN))
  32564. return -1;
  32565. s->cur_func->has_await = true;
  32566. emit_op(s, OP_await);
  32567. parse_flags = 0;
  32568. break;
  32569. default:
  32570. if (js_parse_postfix_expr(s, PF_POSTFIX_CALL))
  32571. return -1;
  32572. if (!s->got_lf &&
  32573. (s->token.val == TOK_DEC || s->token.val == TOK_INC)) {
  32574. int opcode, op, scope, label;
  32575. JSAtom name;
  32576. op = s->token.val;
  32577. if (get_lvalue(s, &opcode, &scope, &name, &label, NULL, true, op))
  32578. return -1;
  32579. emit_op(s, OP_post_dec + op - TOK_DEC);
  32580. put_lvalue(s, opcode, scope, name, label, PUT_LVALUE_KEEP_SECOND,
  32581. false);
  32582. if (next_token(s))
  32583. return -1;
  32584. }
  32585. break;
  32586. }
  32587. if (parse_flags & (PF_POW_ALLOWED | PF_POW_FORBIDDEN)) {
  32588. if (s->token.val == TOK_POW) {
  32589. /* Strict ES7 exponentiation syntax rules: To solve
  32590. conficting semantics between different implementations
  32591. regarding the precedence of prefix operators and the
  32592. postifx exponential, ES7 specifies that -2**2 is a
  32593. syntax error. */
  32594. if (parse_flags & PF_POW_FORBIDDEN)
  32595. return js_parse_error(s, "unparenthesized unary expression can't appear on the left-hand side of '**'");
  32596. if (next_token(s))
  32597. return -1;
  32598. if (js_parse_unary(s, PF_POW_ALLOWED))
  32599. return -1;
  32600. emit_op(s, OP_pow);
  32601. }
  32602. }
  32603. return 0;
  32604. }
  32605. /* allowed parse_flags: PF_IN_ACCEPTED */
  32606. static __exception int js_parse_expr_binary(JSParseState *s, int level,
  32607. int parse_flags)
  32608. {
  32609. int op, opcode;
  32610. if (level == 0) {
  32611. return js_parse_unary(s, PF_POW_ALLOWED);
  32612. } else if (s->token.val == TOK_PRIVATE_NAME &&
  32613. (parse_flags & PF_IN_ACCEPTED) && level == 4 &&
  32614. peek_token(s, false) == TOK_IN) {
  32615. JSAtom atom;
  32616. atom = JS_DupAtom(s->ctx, s->token.u.ident.atom);
  32617. if (next_token(s))
  32618. goto fail_private_in;
  32619. if (s->token.val != TOK_IN)
  32620. goto fail_private_in;
  32621. if (next_token(s))
  32622. goto fail_private_in;
  32623. if (js_parse_expr_binary(s, level - 1, parse_flags)) {
  32624. fail_private_in:
  32625. JS_FreeAtom(s->ctx, atom);
  32626. return -1;
  32627. }
  32628. emit_op(s, OP_scope_in_private_field);
  32629. emit_atom(s, atom);
  32630. emit_u16(s, s->cur_func->scope_level);
  32631. JS_FreeAtom(s->ctx, atom);
  32632. return 0;
  32633. } else {
  32634. if (js_parse_expr_binary(s, level - 1, parse_flags))
  32635. return -1;
  32636. }
  32637. for(;;) {
  32638. op = s->token.val;
  32639. switch(level) {
  32640. case 1:
  32641. switch(op) {
  32642. case '*':
  32643. opcode = OP_mul;
  32644. break;
  32645. case '/':
  32646. opcode = OP_div;
  32647. break;
  32648. case '%':
  32649. opcode = OP_mod;
  32650. break;
  32651. default:
  32652. return 0;
  32653. }
  32654. break;
  32655. case 2:
  32656. switch(op) {
  32657. case '+':
  32658. opcode = OP_add;
  32659. break;
  32660. case '-':
  32661. opcode = OP_sub;
  32662. break;
  32663. default:
  32664. return 0;
  32665. }
  32666. break;
  32667. case 3:
  32668. switch(op) {
  32669. case TOK_SHL:
  32670. opcode = OP_shl;
  32671. break;
  32672. case TOK_SAR:
  32673. opcode = OP_sar;
  32674. break;
  32675. case TOK_SHR:
  32676. opcode = OP_shr;
  32677. break;
  32678. default:
  32679. return 0;
  32680. }
  32681. break;
  32682. case 4:
  32683. switch(op) {
  32684. case '<':
  32685. opcode = OP_lt;
  32686. break;
  32687. case '>':
  32688. opcode = OP_gt;
  32689. break;
  32690. case TOK_LTE:
  32691. opcode = OP_lte;
  32692. break;
  32693. case TOK_GTE:
  32694. opcode = OP_gte;
  32695. break;
  32696. case TOK_INSTANCEOF:
  32697. opcode = OP_instanceof;
  32698. break;
  32699. case TOK_IN:
  32700. if (parse_flags & PF_IN_ACCEPTED) {
  32701. opcode = OP_in;
  32702. } else {
  32703. return 0;
  32704. }
  32705. break;
  32706. default:
  32707. return 0;
  32708. }
  32709. break;
  32710. case 5:
  32711. switch(op) {
  32712. case TOK_EQ:
  32713. opcode = OP_eq;
  32714. break;
  32715. case TOK_NEQ:
  32716. opcode = OP_neq;
  32717. break;
  32718. case TOK_STRICT_EQ:
  32719. opcode = OP_strict_eq;
  32720. break;
  32721. case TOK_STRICT_NEQ:
  32722. opcode = OP_strict_neq;
  32723. break;
  32724. default:
  32725. return 0;
  32726. }
  32727. break;
  32728. case 6:
  32729. switch(op) {
  32730. case '&':
  32731. opcode = OP_and;
  32732. break;
  32733. default:
  32734. return 0;
  32735. }
  32736. break;
  32737. case 7:
  32738. switch(op) {
  32739. case '^':
  32740. opcode = OP_xor;
  32741. break;
  32742. default:
  32743. return 0;
  32744. }
  32745. break;
  32746. case 8:
  32747. switch(op) {
  32748. case '|':
  32749. opcode = OP_or;
  32750. break;
  32751. default:
  32752. return 0;
  32753. }
  32754. break;
  32755. default:
  32756. abort();
  32757. }
  32758. if (next_token(s))
  32759. return -1;
  32760. emit_source_loc(s);
  32761. if (js_parse_expr_binary(s, level - 1, parse_flags))
  32762. return -1;
  32763. emit_op(s, opcode);
  32764. }
  32765. return 0;
  32766. }
  32767. /* allowed parse_flags: PF_IN_ACCEPTED */
  32768. static __exception int js_parse_logical_and_or(JSParseState *s, int op,
  32769. int parse_flags)
  32770. {
  32771. int label1;
  32772. if (op == TOK_LAND) {
  32773. if (js_parse_expr_binary(s, 8, parse_flags))
  32774. return -1;
  32775. } else {
  32776. if (js_parse_logical_and_or(s, TOK_LAND, parse_flags))
  32777. return -1;
  32778. }
  32779. if (s->token.val == op) {
  32780. label1 = new_label(s);
  32781. for(;;) {
  32782. if (next_token(s))
  32783. return -1;
  32784. emit_op(s, OP_dup);
  32785. emit_goto(s, op == TOK_LAND ? OP_if_false : OP_if_true, label1);
  32786. emit_op(s, OP_drop);
  32787. if (op == TOK_LAND) {
  32788. if (js_parse_expr_binary(s, 8, parse_flags))
  32789. return -1;
  32790. } else {
  32791. if (js_parse_logical_and_or(s, TOK_LAND, parse_flags))
  32792. return -1;
  32793. }
  32794. if (s->token.val != op) {
  32795. if (s->token.val == TOK_DOUBLE_QUESTION_MARK)
  32796. return js_parse_error(s, "cannot mix ?? with && or ||");
  32797. break;
  32798. }
  32799. }
  32800. emit_label(s, label1);
  32801. }
  32802. return 0;
  32803. }
  32804. static __exception int js_parse_coalesce_expr(JSParseState *s, int parse_flags)
  32805. {
  32806. int label1;
  32807. if (js_parse_logical_and_or(s, TOK_LOR, parse_flags))
  32808. return -1;
  32809. if (s->token.val == TOK_DOUBLE_QUESTION_MARK) {
  32810. label1 = new_label(s);
  32811. for(;;) {
  32812. if (next_token(s))
  32813. return -1;
  32814. emit_op(s, OP_dup);
  32815. emit_op(s, OP_is_undefined_or_null);
  32816. emit_goto(s, OP_if_false, label1);
  32817. emit_op(s, OP_drop);
  32818. if (js_parse_expr_binary(s, 8, parse_flags))
  32819. return -1;
  32820. if (s->token.val != TOK_DOUBLE_QUESTION_MARK)
  32821. break;
  32822. }
  32823. emit_label(s, label1);
  32824. }
  32825. return 0;
  32826. }
  32827. /* allowed parse_flags: PF_IN_ACCEPTED */
  32828. static __exception int js_parse_cond_expr(JSParseState *s, int parse_flags)
  32829. {
  32830. int label1, label2;
  32831. if (js_parse_coalesce_expr(s, parse_flags))
  32832. return -1;
  32833. if (s->token.val == '?') {
  32834. if (next_token(s))
  32835. return -1;
  32836. label1 = emit_goto(s, OP_if_false, -1);
  32837. if (js_parse_assign_expr(s))
  32838. return -1;
  32839. if (js_parse_expect(s, ':'))
  32840. return -1;
  32841. label2 = emit_goto(s, OP_goto, -1);
  32842. emit_label(s, label1);
  32843. if (js_parse_assign_expr2(s, parse_flags & PF_IN_ACCEPTED))
  32844. return -1;
  32845. emit_label(s, label2);
  32846. }
  32847. return 0;
  32848. }
  32849. /* allowed parse_flags: PF_IN_ACCEPTED */
  32850. static __exception int js_parse_assign_expr2(JSParseState *s, int parse_flags)
  32851. {
  32852. int opcode, op, scope;
  32853. JSAtom name0 = JS_ATOM_NULL;
  32854. JSAtom name;
  32855. if (s->token.val == TOK_YIELD) {
  32856. bool is_star = false, is_async;
  32857. if (!(s->cur_func->func_kind & JS_FUNC_GENERATOR))
  32858. return js_parse_error(s, "unexpected 'yield' keyword");
  32859. if (!s->cur_func->in_function_body)
  32860. return js_parse_error(s, "yield in default expression");
  32861. if (next_token(s))
  32862. return -1;
  32863. /* XXX: is there a better method to detect 'yield' without
  32864. parameters ? */
  32865. if (s->token.val != ';' && s->token.val != ')' &&
  32866. s->token.val != ']' && s->token.val != '}' &&
  32867. s->token.val != ',' && s->token.val != ':' && !s->got_lf) {
  32868. if (s->token.val == '*') {
  32869. is_star = true;
  32870. if (next_token(s))
  32871. return -1;
  32872. }
  32873. if (js_parse_assign_expr2(s, parse_flags))
  32874. return -1;
  32875. } else {
  32876. emit_op(s, OP_undefined);
  32877. }
  32878. is_async = (s->cur_func->func_kind == JS_FUNC_ASYNC_GENERATOR);
  32879. if (is_star) {
  32880. int label_loop, label_return, label_next;
  32881. int label_return1, label_yield, label_throw, label_throw1;
  32882. int label_throw2;
  32883. label_loop = new_label(s);
  32884. label_yield = new_label(s);
  32885. emit_op(s, is_async ? OP_for_await_of_start : OP_for_of_start);
  32886. /* remove the catch offset (XXX: could avoid pushing back
  32887. undefined) */
  32888. emit_op(s, OP_drop);
  32889. emit_op(s, OP_undefined);
  32890. emit_op(s, OP_undefined); /* initial value */
  32891. emit_label(s, label_loop);
  32892. emit_op(s, OP_iterator_next);
  32893. if (is_async)
  32894. emit_op(s, OP_await);
  32895. emit_op(s, OP_iterator_check_object);
  32896. emit_op(s, OP_get_field2);
  32897. emit_atom(s, JS_ATOM_done);
  32898. label_next = emit_goto(s, OP_if_true, -1); /* end of loop */
  32899. emit_label(s, label_yield);
  32900. if (is_async) {
  32901. /* OP_async_yield_star takes the value as parameter */
  32902. emit_op(s, OP_get_field);
  32903. emit_atom(s, JS_ATOM_value);
  32904. emit_op(s, OP_async_yield_star);
  32905. } else {
  32906. /* OP_yield_star takes (value, done) as parameter */
  32907. emit_op(s, OP_yield_star);
  32908. }
  32909. emit_op(s, OP_dup);
  32910. label_return = emit_goto(s, OP_if_true, -1);
  32911. emit_op(s, OP_drop);
  32912. emit_goto(s, OP_goto, label_loop);
  32913. emit_label(s, label_return);
  32914. emit_op(s, OP_push_i32);
  32915. emit_u32(s, 2);
  32916. emit_op(s, OP_strict_eq);
  32917. label_throw = emit_goto(s, OP_if_true, -1);
  32918. /* return handling */
  32919. if (is_async)
  32920. emit_op(s, OP_await);
  32921. emit_op(s, OP_iterator_call);
  32922. emit_u8(s, 0);
  32923. label_return1 = emit_goto(s, OP_if_true, -1);
  32924. if (is_async)
  32925. emit_op(s, OP_await);
  32926. emit_op(s, OP_iterator_check_object);
  32927. emit_op(s, OP_get_field2);
  32928. emit_atom(s, JS_ATOM_done);
  32929. emit_goto(s, OP_if_false, label_yield);
  32930. emit_op(s, OP_get_field);
  32931. emit_atom(s, JS_ATOM_value);
  32932. emit_label(s, label_return1);
  32933. emit_op(s, OP_nip);
  32934. emit_op(s, OP_nip);
  32935. emit_op(s, OP_nip);
  32936. emit_return(s, true);
  32937. /* throw handling */
  32938. emit_label(s, label_throw);
  32939. emit_op(s, OP_iterator_call);
  32940. emit_u8(s, 1);
  32941. label_throw1 = emit_goto(s, OP_if_true, -1);
  32942. if (is_async)
  32943. emit_op(s, OP_await);
  32944. emit_op(s, OP_iterator_check_object);
  32945. emit_op(s, OP_get_field2);
  32946. emit_atom(s, JS_ATOM_done);
  32947. emit_goto(s, OP_if_false, label_yield);
  32948. emit_goto(s, OP_goto, label_next);
  32949. /* close the iterator and throw a type error exception */
  32950. emit_label(s, label_throw1);
  32951. emit_op(s, OP_iterator_call);
  32952. emit_u8(s, 2);
  32953. label_throw2 = emit_goto(s, OP_if_true, -1);
  32954. if (is_async)
  32955. emit_op(s, OP_await);
  32956. emit_label(s, label_throw2);
  32957. emit_op(s, OP_throw_error);
  32958. emit_atom(s, JS_ATOM_NULL);
  32959. emit_u8(s, JS_THROW_ERROR_ITERATOR_THROW);
  32960. emit_label(s, label_next);
  32961. emit_op(s, OP_get_field);
  32962. emit_atom(s, JS_ATOM_value);
  32963. emit_op(s, OP_nip); /* keep the value associated with
  32964. done = true */
  32965. emit_op(s, OP_nip);
  32966. emit_op(s, OP_nip);
  32967. } else {
  32968. int label_next;
  32969. if (is_async)
  32970. emit_op(s, OP_await);
  32971. emit_op(s, OP_yield);
  32972. label_next = emit_goto(s, OP_if_false, -1);
  32973. emit_return(s, true);
  32974. emit_label(s, label_next);
  32975. }
  32976. return 0;
  32977. } else if (s->token.val == '(' &&
  32978. js_parse_skip_parens_token(s, NULL, true) == TOK_ARROW) {
  32979. return js_parse_function_decl(s, JS_PARSE_FUNC_ARROW,
  32980. JS_FUNC_NORMAL, JS_ATOM_NULL,
  32981. s->token.ptr, s->token.line_num,
  32982. s->token.col_num);
  32983. } else if (token_is_pseudo_keyword(s, JS_ATOM_async)) {
  32984. const uint8_t *source_ptr;
  32985. int tok, source_line_num, source_col_num;
  32986. JSParsePos pos;
  32987. /* fast test */
  32988. tok = peek_token(s, true);
  32989. if (tok == TOK_FUNCTION || tok == '\n')
  32990. goto next;
  32991. source_ptr = s->token.ptr;
  32992. source_line_num = s->token.line_num;
  32993. source_col_num = s->token.col_num;
  32994. js_parse_get_pos(s, &pos);
  32995. if (next_token(s))
  32996. return -1;
  32997. if ((s->token.val == '(' &&
  32998. js_parse_skip_parens_token(s, NULL, true) == TOK_ARROW) ||
  32999. (s->token.val == TOK_IDENT && !s->token.u.ident.is_reserved &&
  33000. peek_token(s, true) == TOK_ARROW)) {
  33001. return js_parse_function_decl(s, JS_PARSE_FUNC_ARROW,
  33002. JS_FUNC_ASYNC, JS_ATOM_NULL,
  33003. source_ptr, source_line_num,
  33004. source_col_num);
  33005. } else {
  33006. /* undo the token parsing */
  33007. if (js_parse_seek_token(s, &pos))
  33008. return -1;
  33009. }
  33010. } else if (s->token.val == TOK_IDENT &&
  33011. peek_token(s, true) == TOK_ARROW) {
  33012. return js_parse_function_decl(s, JS_PARSE_FUNC_ARROW,
  33013. JS_FUNC_NORMAL, JS_ATOM_NULL,
  33014. s->token.ptr, s->token.line_num,
  33015. s->token.col_num);
  33016. }
  33017. next:
  33018. if (s->token.val == TOK_IDENT) {
  33019. /* name0 is used to check for OP_set_name pattern, not duplicated */
  33020. name0 = s->token.u.ident.atom;
  33021. }
  33022. if (js_parse_cond_expr(s, parse_flags))
  33023. return -1;
  33024. op = s->token.val;
  33025. if (op == '=' || (op >= TOK_MUL_ASSIGN && op <= TOK_POW_ASSIGN)) {
  33026. int label;
  33027. if (next_token(s))
  33028. return -1;
  33029. if (get_lvalue(s, &opcode, &scope, &name, &label, NULL, (op != '='), op) < 0)
  33030. return -1;
  33031. // comply with rather obtuse evaluation order of computed properties:
  33032. // obj[key]=val evaluates val->obj->key when obj is null/undefined
  33033. // but key->obj->val when an object
  33034. // FIXME(bnoordhuis) less stack shuffling; don't to_propkey twice in
  33035. // happy path; replace `dup is_undefined_or_null if_true` with new
  33036. // opcode if_undefined_or_null? replace `swap dup` with over?
  33037. if (op == '=' && opcode == OP_get_array_el) {
  33038. int label_next = -1;
  33039. JSFunctionDef *fd = s->cur_func;
  33040. assert(OP_to_propkey2 == fd->byte_code.buf[fd->last_opcode_pos]);
  33041. fd->byte_code.size = fd->last_opcode_pos;
  33042. fd->last_opcode_pos = -1;
  33043. emit_op(s, OP_swap); // obj key -> key obj
  33044. emit_op(s, OP_dup);
  33045. emit_op(s, OP_is_undefined_or_null);
  33046. label_next = emit_goto(s, OP_if_true, -1);
  33047. emit_op(s, OP_swap);
  33048. emit_op(s, OP_to_propkey);
  33049. emit_op(s, OP_swap);
  33050. emit_label(s, label_next);
  33051. emit_op(s, OP_swap);
  33052. }
  33053. if (js_parse_assign_expr2(s, parse_flags)) {
  33054. JS_FreeAtom(s->ctx, name);
  33055. return -1;
  33056. }
  33057. if (op == '=' && opcode == OP_get_array_el) {
  33058. emit_op(s, OP_swap); // obj key val -> obj val key
  33059. emit_op(s, OP_to_propkey);
  33060. emit_op(s, OP_swap);
  33061. }
  33062. if (op == '=') {
  33063. if (opcode == OP_get_ref_value && name == name0) {
  33064. set_object_name(s, name);
  33065. }
  33066. } else {
  33067. emit_op(s, op - TOK_MUL_ASSIGN + OP_mul);
  33068. }
  33069. put_lvalue(s, opcode, scope, name, label, PUT_LVALUE_KEEP_TOP, false);
  33070. } else if (op >= TOK_LAND_ASSIGN && op <= TOK_DOUBLE_QUESTION_MARK_ASSIGN) {
  33071. int label, label1, depth_lvalue, label2;
  33072. if (next_token(s))
  33073. return -1;
  33074. if (get_lvalue(s, &opcode, &scope, &name, &label,
  33075. &depth_lvalue, true, op) < 0)
  33076. return -1;
  33077. emit_op(s, OP_dup);
  33078. if (op == TOK_DOUBLE_QUESTION_MARK_ASSIGN)
  33079. emit_op(s, OP_is_undefined_or_null);
  33080. label1 = emit_goto(s, op == TOK_LOR_ASSIGN ? OP_if_true : OP_if_false,
  33081. -1);
  33082. emit_op(s, OP_drop);
  33083. if (js_parse_assign_expr2(s, parse_flags)) {
  33084. JS_FreeAtom(s->ctx, name);
  33085. return -1;
  33086. }
  33087. if (opcode == OP_get_ref_value && name == name0) {
  33088. set_object_name(s, name);
  33089. }
  33090. switch(depth_lvalue) {
  33091. case 1:
  33092. emit_op(s, OP_insert2);
  33093. break;
  33094. case 2:
  33095. emit_op(s, OP_insert3);
  33096. break;
  33097. case 3:
  33098. emit_op(s, OP_insert4);
  33099. break;
  33100. default:
  33101. abort();
  33102. }
  33103. /* XXX: we disable the OP_put_ref_value optimization by not
  33104. using put_lvalue() otherwise depth_lvalue is not correct */
  33105. put_lvalue(s, opcode, scope, name, label, PUT_LVALUE_NOKEEP_DEPTH,
  33106. false);
  33107. label2 = emit_goto(s, OP_goto, -1);
  33108. emit_label(s, label1);
  33109. /* remove the lvalue stack entries */
  33110. while (depth_lvalue != 0) {
  33111. emit_op(s, OP_nip);
  33112. depth_lvalue--;
  33113. }
  33114. emit_label(s, label2);
  33115. }
  33116. return 0;
  33117. }
  33118. static __exception int js_parse_assign_expr(JSParseState *s)
  33119. {
  33120. return js_parse_assign_expr2(s, PF_IN_ACCEPTED);
  33121. }
  33122. /* allowed parse_flags: PF_IN_ACCEPTED */
  33123. static __exception int js_parse_expr2(JSParseState *s, int parse_flags)
  33124. {
  33125. bool comma = false;
  33126. for(;;) {
  33127. if (js_parse_assign_expr2(s, parse_flags))
  33128. return -1;
  33129. if (comma) {
  33130. /* prevent get_lvalue from using the last expression
  33131. as an lvalue. This also prevents the conversion of
  33132. of get_var to get_ref for method lookup in function
  33133. call inside `with` statement.
  33134. */
  33135. s->cur_func->last_opcode_pos = -1;
  33136. }
  33137. if (s->token.val != ',')
  33138. break;
  33139. comma = true;
  33140. if (next_token(s))
  33141. return -1;
  33142. emit_op(s, OP_drop);
  33143. }
  33144. return 0;
  33145. }
  33146. static __exception int js_parse_expr(JSParseState *s)
  33147. {
  33148. return js_parse_expr2(s, PF_IN_ACCEPTED);
  33149. }
  33150. static void push_break_entry(JSFunctionDef *fd, BlockEnv *be,
  33151. JSAtom label_name,
  33152. int label_break, int label_cont,
  33153. int drop_count)
  33154. {
  33155. be->prev = fd->top_break;
  33156. fd->top_break = be;
  33157. be->label_name = label_name;
  33158. be->label_break = label_break;
  33159. be->label_cont = label_cont;
  33160. be->drop_count = drop_count;
  33161. be->label_finally = -1;
  33162. be->scope_level = fd->scope_level;
  33163. be->has_iterator = false;
  33164. be->is_regular_stmt = false;
  33165. }
  33166. static void pop_break_entry(JSFunctionDef *fd)
  33167. {
  33168. BlockEnv *be;
  33169. be = fd->top_break;
  33170. fd->top_break = be->prev;
  33171. }
  33172. static __exception int emit_break(JSParseState *s, JSAtom name, int is_cont)
  33173. {
  33174. BlockEnv *top;
  33175. int i, scope_level;
  33176. scope_level = s->cur_func->scope_level;
  33177. top = s->cur_func->top_break;
  33178. while (top != NULL) {
  33179. close_scopes(s, scope_level, top->scope_level);
  33180. scope_level = top->scope_level;
  33181. if (is_cont &&
  33182. top->label_cont != -1 &&
  33183. (name == JS_ATOM_NULL || top->label_name == name)) {
  33184. /* continue stays inside the same block */
  33185. emit_goto(s, OP_goto, top->label_cont);
  33186. return 0;
  33187. }
  33188. if (!is_cont && top->label_break != -1) {
  33189. if (top->label_name == name ||
  33190. (name == JS_ATOM_NULL && !top->is_regular_stmt)) {
  33191. emit_goto(s, OP_goto, top->label_break);
  33192. return 0;
  33193. }
  33194. }
  33195. i = 0;
  33196. if (top->has_iterator) {
  33197. emit_op(s, OP_iterator_close);
  33198. i += 3;
  33199. }
  33200. for(; i < top->drop_count; i++)
  33201. emit_op(s, OP_drop);
  33202. if (top->label_finally != -1) {
  33203. /* must push dummy value to keep same stack depth */
  33204. emit_op(s, OP_undefined);
  33205. emit_goto(s, OP_gosub, top->label_finally);
  33206. emit_op(s, OP_drop);
  33207. }
  33208. top = top->prev;
  33209. }
  33210. if (name == JS_ATOM_NULL) {
  33211. if (is_cont)
  33212. return js_parse_error(s, "continue must be inside loop");
  33213. else
  33214. return js_parse_error(s, "break must be inside loop or switch");
  33215. } else {
  33216. return js_parse_error(s, "break/continue label not found");
  33217. }
  33218. }
  33219. /* execute the finally blocks before return */
  33220. static void emit_return(JSParseState *s, bool hasval)
  33221. {
  33222. BlockEnv *top;
  33223. if (s->cur_func->func_kind != JS_FUNC_NORMAL) {
  33224. if (!hasval) {
  33225. /* no value: direct return in case of async generator */
  33226. emit_op(s, OP_undefined);
  33227. hasval = true;
  33228. } else if (s->cur_func->func_kind == JS_FUNC_ASYNC_GENERATOR) {
  33229. /* the await must be done before handling the "finally" in
  33230. case it raises an exception */
  33231. emit_op(s, OP_await);
  33232. }
  33233. }
  33234. top = s->cur_func->top_break;
  33235. while (top != NULL) {
  33236. if (top->has_iterator || top->label_finally != -1) {
  33237. if (!hasval) {
  33238. emit_op(s, OP_undefined);
  33239. hasval = true;
  33240. }
  33241. /* Remove the stack elements up to and including the catch
  33242. offset. When 'yield' is used in an expression we have
  33243. no easy way to count them, so we use this specific
  33244. instruction instead. */
  33245. emit_op(s, OP_nip_catch);
  33246. /* stack: iter_obj next ret_val */
  33247. if (top->has_iterator) {
  33248. if (s->cur_func->func_kind == JS_FUNC_ASYNC_GENERATOR) {
  33249. int label_next, label_next2;
  33250. emit_op(s, OP_nip); /* next */
  33251. emit_op(s, OP_swap);
  33252. emit_op(s, OP_get_field2);
  33253. emit_atom(s, JS_ATOM_return);
  33254. /* stack: iter_obj return_func */
  33255. emit_op(s, OP_dup);
  33256. emit_op(s, OP_is_undefined_or_null);
  33257. label_next = emit_goto(s, OP_if_true, -1);
  33258. emit_op(s, OP_call_method);
  33259. emit_u16(s, 0);
  33260. emit_op(s, OP_iterator_check_object);
  33261. emit_op(s, OP_await);
  33262. label_next2 = emit_goto(s, OP_goto, -1);
  33263. emit_label(s, label_next);
  33264. emit_op(s, OP_drop);
  33265. emit_label(s, label_next2);
  33266. emit_op(s, OP_drop);
  33267. } else {
  33268. emit_op(s, OP_rot3r);
  33269. emit_op(s, OP_undefined); /* dummy catch offset */
  33270. emit_op(s, OP_iterator_close);
  33271. }
  33272. } else {
  33273. /* execute the "finally" block */
  33274. emit_goto(s, OP_gosub, top->label_finally);
  33275. }
  33276. }
  33277. top = top->prev;
  33278. }
  33279. if (s->cur_func->is_derived_class_constructor) {
  33280. int label_return;
  33281. /* 'this' can be uninitialized, so it may be accessed only if
  33282. the derived class constructor does not return an object */
  33283. if (hasval) {
  33284. emit_op(s, OP_check_ctor_return);
  33285. label_return = emit_goto(s, OP_if_false, -1);
  33286. emit_op(s, OP_drop);
  33287. } else {
  33288. label_return = -1;
  33289. }
  33290. /* XXX: if this is not initialized, should throw the
  33291. ReferenceError in the caller realm */
  33292. emit_op(s, OP_scope_get_var);
  33293. emit_atom(s, JS_ATOM_this);
  33294. emit_u16(s, 0);
  33295. emit_label(s, label_return);
  33296. emit_op(s, OP_return);
  33297. } else if (s->cur_func->func_kind != JS_FUNC_NORMAL) {
  33298. emit_op(s, OP_return_async);
  33299. } else {
  33300. emit_op(s, hasval ? OP_return : OP_return_undef);
  33301. }
  33302. }
  33303. #define DECL_MASK_FUNC (1 << 0) /* allow normal function declaration */
  33304. /* ored with DECL_MASK_FUNC if function declarations are allowed with a label */
  33305. #define DECL_MASK_FUNC_WITH_LABEL (1 << 1)
  33306. #define DECL_MASK_OTHER (1 << 2) /* all other declarations */
  33307. #define DECL_MASK_ALL (DECL_MASK_FUNC | DECL_MASK_FUNC_WITH_LABEL | DECL_MASK_OTHER)
  33308. static __exception int js_parse_statement_or_decl(JSParseState *s,
  33309. int decl_mask);
  33310. static __exception int js_parse_statement(JSParseState *s)
  33311. {
  33312. return js_parse_statement_or_decl(s, 0);
  33313. }
  33314. static __exception int js_parse_block(JSParseState *s)
  33315. {
  33316. if (js_parse_expect(s, '{'))
  33317. return -1;
  33318. if (s->token.val != '}') {
  33319. push_scope(s);
  33320. for(;;) {
  33321. if (js_parse_statement_or_decl(s, DECL_MASK_ALL))
  33322. return -1;
  33323. if (s->token.val == '}')
  33324. break;
  33325. }
  33326. pop_scope(s);
  33327. }
  33328. if (next_token(s))
  33329. return -1;
  33330. return 0;
  33331. }
  33332. /* allowed parse_flags: PF_IN_ACCEPTED */
  33333. static __exception int js_parse_var(JSParseState *s, int parse_flags, int tok,
  33334. bool export_flag)
  33335. {
  33336. JSContext *ctx = s->ctx;
  33337. JSFunctionDef *fd = s->cur_func;
  33338. JSAtom name = JS_ATOM_NULL;
  33339. for (;;) {
  33340. if (s->token.val == TOK_IDENT) {
  33341. if (s->token.u.ident.is_reserved) {
  33342. return js_parse_error_reserved_identifier(s);
  33343. }
  33344. name = JS_DupAtom(ctx, s->token.u.ident.atom);
  33345. if (name == JS_ATOM_let && (tok == TOK_LET || tok == TOK_CONST)) {
  33346. js_parse_error(s, "'let' is not a valid lexical identifier");
  33347. goto var_error;
  33348. }
  33349. if (next_token(s))
  33350. goto var_error;
  33351. if (js_define_var(s, name, tok))
  33352. goto var_error;
  33353. if (export_flag) {
  33354. if (!add_export_entry(s, s->cur_func->module, name, name,
  33355. JS_EXPORT_TYPE_LOCAL))
  33356. goto var_error;
  33357. }
  33358. if (s->token.val == '=') {
  33359. if (next_token(s))
  33360. goto var_error;
  33361. if (tok == TOK_VAR) {
  33362. /* Must make a reference for proper `with` semantics */
  33363. int opcode, scope, label;
  33364. JSAtom name1;
  33365. emit_op(s, OP_scope_get_var);
  33366. emit_atom(s, name);
  33367. emit_u16(s, fd->scope_level);
  33368. if (get_lvalue(s, &opcode, &scope, &name1, &label, NULL, false, '=') < 0)
  33369. goto var_error;
  33370. if (js_parse_assign_expr2(s, parse_flags)) {
  33371. JS_FreeAtom(ctx, name1);
  33372. goto var_error;
  33373. }
  33374. set_object_name(s, name);
  33375. put_lvalue(s, opcode, scope, name1, label,
  33376. PUT_LVALUE_NOKEEP, false);
  33377. } else {
  33378. if (js_parse_assign_expr2(s, parse_flags))
  33379. goto var_error;
  33380. set_object_name(s, name);
  33381. emit_op(s, (tok == TOK_CONST || tok == TOK_LET) ?
  33382. OP_scope_put_var_init : OP_scope_put_var);
  33383. emit_atom(s, name);
  33384. emit_u16(s, fd->scope_level);
  33385. }
  33386. } else {
  33387. if (tok == TOK_CONST) {
  33388. js_parse_error(s, "missing initializer for const variable");
  33389. goto var_error;
  33390. }
  33391. if (tok == TOK_LET) {
  33392. /* initialize lexical variable upon entering its scope */
  33393. emit_op(s, OP_undefined);
  33394. emit_op(s, OP_scope_put_var_init);
  33395. emit_atom(s, name);
  33396. emit_u16(s, fd->scope_level);
  33397. }
  33398. }
  33399. JS_FreeAtom(ctx, name);
  33400. } else {
  33401. int skip_bits;
  33402. if ((s->token.val == '[' || s->token.val == '{')
  33403. && js_parse_skip_parens_token(s, &skip_bits, false) == '=') {
  33404. emit_op(s, OP_undefined);
  33405. if (js_parse_destructuring_element(s, tok, false, true, skip_bits & SKIP_HAS_ELLIPSIS, true, export_flag) < 0)
  33406. return -1;
  33407. } else {
  33408. return js_parse_error(s, "variable name expected");
  33409. }
  33410. }
  33411. if (s->token.val != ',')
  33412. break;
  33413. if (next_token(s))
  33414. return -1;
  33415. }
  33416. return 0;
  33417. var_error:
  33418. JS_FreeAtom(ctx, name);
  33419. return -1;
  33420. }
  33421. /* test if the current token is a label. Use simplistic look-ahead scanner */
  33422. static bool is_label(JSParseState *s)
  33423. {
  33424. return (s->token.val == TOK_IDENT && !s->token.u.ident.is_reserved &&
  33425. peek_token(s, false) == ':');
  33426. }
  33427. /* test if the current token is a let keyword. Use simplistic look-ahead scanner */
  33428. static int is_let(JSParseState *s, int decl_mask)
  33429. {
  33430. int res = false;
  33431. if (token_is_pseudo_keyword(s, JS_ATOM_let)) {
  33432. JSParsePos pos;
  33433. js_parse_get_pos(s, &pos);
  33434. for (;;) {
  33435. if (next_token(s)) {
  33436. res = -1;
  33437. break;
  33438. }
  33439. if (s->token.val == '[') {
  33440. /* let [ is a syntax restriction:
  33441. it never introduces an ExpressionStatement */
  33442. res = true;
  33443. break;
  33444. }
  33445. if (s->token.val == '{' ||
  33446. (s->token.val == TOK_IDENT && !s->token.u.ident.is_reserved) ||
  33447. s->token.val == TOK_LET ||
  33448. s->token.val == TOK_YIELD ||
  33449. s->token.val == TOK_AWAIT) {
  33450. /* Check for possible ASI if not scanning for Declaration */
  33451. /* XXX: should also check that `{` introduces a BindingPattern,
  33452. but Firefox does not and rejects eval("let=1;let\n{if(1)2;}") */
  33453. if (s->last_line_num == s->token.line_num || (decl_mask & DECL_MASK_OTHER)) {
  33454. res = true;
  33455. break;
  33456. }
  33457. break;
  33458. }
  33459. break;
  33460. }
  33461. if (js_parse_seek_token(s, &pos)) {
  33462. res = -1;
  33463. }
  33464. }
  33465. return res;
  33466. }
  33467. /* XXX: handle IteratorClose when exiting the loop before the
  33468. enumeration is done */
  33469. static __exception int js_parse_for_in_of(JSParseState *s, int label_name,
  33470. bool is_async)
  33471. {
  33472. JSContext *ctx = s->ctx;
  33473. JSFunctionDef *fd = s->cur_func;
  33474. JSAtom var_name;
  33475. bool has_initializer, is_for_of, has_destructuring;
  33476. int tok, tok1, opcode, scope, block_scope_level;
  33477. int label_next, label_expr, label_cont, label_body, label_break;
  33478. int pos_next, pos_expr;
  33479. BlockEnv break_entry;
  33480. has_initializer = false;
  33481. has_destructuring = false;
  33482. is_for_of = false;
  33483. block_scope_level = fd->scope_level;
  33484. label_cont = new_label(s);
  33485. label_body = new_label(s);
  33486. label_break = new_label(s);
  33487. label_next = new_label(s);
  33488. /* create scope for the lexical variables declared in the enumeration
  33489. expressions. XXX: Not completely correct because of weird capturing
  33490. semantics in `for (i of o) a.push(function(){return i})` */
  33491. push_scope(s);
  33492. /* local for_in scope starts here so individual elements
  33493. can be closed in statement. */
  33494. push_break_entry(s->cur_func, &break_entry,
  33495. label_name, label_break, label_cont, 1);
  33496. break_entry.scope_level = block_scope_level;
  33497. label_expr = emit_goto(s, OP_goto, -1);
  33498. pos_next = s->cur_func->byte_code.size;
  33499. emit_label(s, label_next);
  33500. tok = s->token.val;
  33501. switch (is_let(s, DECL_MASK_OTHER)) {
  33502. case true:
  33503. tok = TOK_LET;
  33504. break;
  33505. case false:
  33506. break;
  33507. default:
  33508. return -1;
  33509. }
  33510. if (tok == TOK_VAR || tok == TOK_LET || tok == TOK_CONST) {
  33511. if (next_token(s))
  33512. return -1;
  33513. if (!(s->token.val == TOK_IDENT && !s->token.u.ident.is_reserved)) {
  33514. if (s->token.val == '[' || s->token.val == '{') {
  33515. if (js_parse_destructuring_element(s, tok, false, true, -1, false, false) < 0)
  33516. return -1;
  33517. has_destructuring = true;
  33518. } else {
  33519. return js_parse_error(s, "variable name expected");
  33520. }
  33521. var_name = JS_ATOM_NULL;
  33522. } else {
  33523. var_name = JS_DupAtom(ctx, s->token.u.ident.atom);
  33524. if (next_token(s)) {
  33525. JS_FreeAtom(s->ctx, var_name);
  33526. return -1;
  33527. }
  33528. if (js_define_var(s, var_name, tok)) {
  33529. JS_FreeAtom(s->ctx, var_name);
  33530. return -1;
  33531. }
  33532. emit_op(s, (tok == TOK_CONST || tok == TOK_LET) ?
  33533. OP_scope_put_var_init : OP_scope_put_var);
  33534. emit_atom(s, var_name);
  33535. emit_u16(s, fd->scope_level);
  33536. }
  33537. } else if (!is_async && token_is_pseudo_keyword(s, JS_ATOM_async) && peek_token(s, false) == TOK_OF) {
  33538. return js_parse_error(s, "'for of' expression cannot start with 'async'");
  33539. } else {
  33540. int skip_bits;
  33541. if ((s->token.val == '[' || s->token.val == '{')
  33542. && ((tok1 = js_parse_skip_parens_token(s, &skip_bits, false)) == TOK_IN || tok1 == TOK_OF)) {
  33543. if (js_parse_destructuring_element(s, 0, false, true, skip_bits & SKIP_HAS_ELLIPSIS, true, false) < 0)
  33544. return -1;
  33545. } else {
  33546. int lvalue_label;
  33547. if (js_parse_left_hand_side_expr(s))
  33548. return -1;
  33549. if (get_lvalue(s, &opcode, &scope, &var_name, &lvalue_label,
  33550. NULL, false, TOK_FOR))
  33551. return -1;
  33552. put_lvalue(s, opcode, scope, var_name, lvalue_label,
  33553. PUT_LVALUE_NOKEEP_BOTTOM, false);
  33554. }
  33555. var_name = JS_ATOM_NULL;
  33556. }
  33557. emit_goto(s, OP_goto, label_body);
  33558. pos_expr = s->cur_func->byte_code.size;
  33559. emit_label(s, label_expr);
  33560. if (s->token.val == '=') {
  33561. /* XXX: potential scoping issue if inside `with` statement */
  33562. has_initializer = true;
  33563. /* parse and evaluate initializer prior to evaluating the
  33564. object (only used with "for in" with a non lexical variable
  33565. in non strict mode */
  33566. if (next_token(s) || js_parse_assign_expr2(s, 0)) {
  33567. JS_FreeAtom(ctx, var_name);
  33568. return -1;
  33569. }
  33570. if (var_name != JS_ATOM_NULL) {
  33571. emit_op(s, OP_scope_put_var);
  33572. emit_atom(s, var_name);
  33573. emit_u16(s, fd->scope_level);
  33574. }
  33575. }
  33576. JS_FreeAtom(ctx, var_name);
  33577. if (token_is_pseudo_keyword(s, JS_ATOM_of)) {
  33578. is_for_of = true;
  33579. break_entry.has_iterator = true;
  33580. break_entry.drop_count += 2;
  33581. if (has_initializer)
  33582. goto initializer_error;
  33583. } else if (s->token.val == TOK_IN) {
  33584. if (is_async)
  33585. return js_parse_error(s, "'for await' loop should be used with 'of'");
  33586. if (has_initializer &&
  33587. (tok != TOK_VAR || fd->is_strict_mode || has_destructuring)) {
  33588. initializer_error:
  33589. return js_parse_error(s, "a declaration in the head of a for-%s loop can't have an initializer",
  33590. is_for_of ? "of" : "in");
  33591. }
  33592. } else {
  33593. return js_parse_error(s, "expected 'of' or 'in' in for control expression");
  33594. }
  33595. if (next_token(s))
  33596. return -1;
  33597. if (is_for_of) {
  33598. if (js_parse_assign_expr(s))
  33599. return -1;
  33600. } else {
  33601. if (js_parse_expr(s))
  33602. return -1;
  33603. }
  33604. /* close the scope after having evaluated the expression so that
  33605. the TDZ values are in the closures */
  33606. close_scopes(s, s->cur_func->scope_level, block_scope_level);
  33607. if (is_for_of) {
  33608. if (is_async)
  33609. emit_op(s, OP_for_await_of_start);
  33610. else
  33611. emit_op(s, OP_for_of_start);
  33612. /* on stack: enum_rec */
  33613. } else {
  33614. emit_op(s, OP_for_in_start);
  33615. /* on stack: enum_obj */
  33616. }
  33617. emit_goto(s, OP_goto, label_cont);
  33618. if (js_parse_expect(s, ')'))
  33619. return -1;
  33620. {
  33621. /* move the `next` code here */
  33622. DynBuf *bc = &s->cur_func->byte_code;
  33623. int chunk_size = pos_expr - pos_next;
  33624. int offset = bc->size - pos_next;
  33625. int i;
  33626. dbuf_realloc(bc, bc->size + chunk_size);
  33627. dbuf_put(bc, bc->buf + pos_next, chunk_size);
  33628. memset(bc->buf + pos_next, OP_nop, chunk_size);
  33629. /* `next` part ends with a goto */
  33630. s->cur_func->last_opcode_pos = bc->size - 5;
  33631. /* relocate labels */
  33632. for (i = label_cont; i < s->cur_func->label_count; i++) {
  33633. LabelSlot *ls = &s->cur_func->label_slots[i];
  33634. if (ls->pos >= pos_next && ls->pos < pos_expr)
  33635. ls->pos += offset;
  33636. }
  33637. }
  33638. emit_label(s, label_body);
  33639. if (js_parse_statement(s))
  33640. return -1;
  33641. close_scopes(s, s->cur_func->scope_level, block_scope_level);
  33642. emit_label(s, label_cont);
  33643. if (is_for_of) {
  33644. if (is_async) {
  33645. /* call the next method */
  33646. /* stack: iter_obj next catch_offset */
  33647. emit_op(s, OP_dup3);
  33648. emit_op(s, OP_drop);
  33649. emit_op(s, OP_call_method);
  33650. emit_u16(s, 0);
  33651. /* get the result of the promise */
  33652. emit_op(s, OP_await);
  33653. /* unwrap the value and done values */
  33654. emit_op(s, OP_iterator_get_value_done);
  33655. } else {
  33656. emit_op(s, OP_for_of_next);
  33657. emit_u8(s, 0);
  33658. }
  33659. } else {
  33660. emit_op(s, OP_for_in_next);
  33661. }
  33662. /* on stack: enum_rec / enum_obj value bool */
  33663. emit_goto(s, OP_if_false, label_next);
  33664. /* drop the undefined value from for_xx_next */
  33665. emit_op(s, OP_drop);
  33666. emit_label(s, label_break);
  33667. if (is_for_of) {
  33668. /* close and drop enum_rec */
  33669. emit_op(s, OP_iterator_close);
  33670. } else {
  33671. emit_op(s, OP_drop);
  33672. }
  33673. pop_break_entry(s->cur_func);
  33674. pop_scope(s);
  33675. return 0;
  33676. }
  33677. static void set_eval_ret_undefined(JSParseState *s)
  33678. {
  33679. if (s->cur_func->eval_ret_idx >= 0) {
  33680. emit_op(s, OP_undefined);
  33681. emit_op(s, OP_put_loc);
  33682. emit_u16(s, s->cur_func->eval_ret_idx);
  33683. }
  33684. }
  33685. static __exception int js_parse_statement_or_decl(JSParseState *s,
  33686. int decl_mask)
  33687. {
  33688. JSContext *ctx = s->ctx;
  33689. JSAtom label_name;
  33690. int tok;
  33691. /* specific label handling */
  33692. /* XXX: support multiple labels on loop statements */
  33693. label_name = JS_ATOM_NULL;
  33694. if (is_label(s)) {
  33695. BlockEnv *be;
  33696. label_name = JS_DupAtom(ctx, s->token.u.ident.atom);
  33697. for (be = s->cur_func->top_break; be; be = be->prev) {
  33698. if (be->label_name == label_name) {
  33699. js_parse_error(s, "duplicate label name");
  33700. goto fail;
  33701. }
  33702. }
  33703. if (next_token(s))
  33704. goto fail;
  33705. if (js_parse_expect(s, ':'))
  33706. goto fail;
  33707. if (s->token.val != TOK_FOR
  33708. && s->token.val != TOK_DO
  33709. && s->token.val != TOK_WHILE) {
  33710. /* labelled regular statement */
  33711. JSFunctionDef *fd = s->cur_func;
  33712. int label_break, mask;
  33713. BlockEnv break_entry;
  33714. label_break = new_label(s);
  33715. push_break_entry(fd, &break_entry, label_name, label_break, -1, 0);
  33716. fd->top_break->is_regular_stmt = 1;
  33717. if (!fd->is_strict_mode &&
  33718. (decl_mask & DECL_MASK_FUNC_WITH_LABEL)) {
  33719. mask = DECL_MASK_FUNC | DECL_MASK_FUNC_WITH_LABEL;
  33720. } else {
  33721. mask = 0;
  33722. }
  33723. if (js_parse_statement_or_decl(s, mask))
  33724. goto fail;
  33725. emit_label(s, label_break);
  33726. pop_break_entry(fd);
  33727. goto done;
  33728. }
  33729. }
  33730. switch(tok = s->token.val) {
  33731. case '{':
  33732. if (js_parse_block(s))
  33733. goto fail;
  33734. break;
  33735. case TOK_RETURN:
  33736. if (s->cur_func->is_eval) {
  33737. js_parse_error(s, "return not in a function");
  33738. goto fail;
  33739. }
  33740. if (s->cur_func->func_type == JS_PARSE_FUNC_CLASS_STATIC_INIT) {
  33741. js_parse_error(s, "return in a static initializer block");
  33742. goto fail;
  33743. }
  33744. if (next_token(s))
  33745. goto fail;
  33746. if (s->token.val != ';' && s->token.val != '}' && !s->got_lf) {
  33747. if (js_parse_expr(s))
  33748. goto fail;
  33749. emit_return(s, true);
  33750. } else {
  33751. emit_return(s, false);
  33752. }
  33753. if (js_parse_expect_semi(s))
  33754. goto fail;
  33755. break;
  33756. case TOK_THROW:
  33757. if (next_token(s))
  33758. goto fail;
  33759. if (s->got_lf) {
  33760. js_parse_error(s, "line terminator not allowed after throw");
  33761. goto fail;
  33762. }
  33763. emit_source_loc(s);
  33764. if (js_parse_expr(s))
  33765. goto fail;
  33766. emit_op(s, OP_throw);
  33767. if (js_parse_expect_semi(s))
  33768. goto fail;
  33769. break;
  33770. case TOK_LET:
  33771. case TOK_CONST:
  33772. haslet:
  33773. if (!(decl_mask & DECL_MASK_OTHER)) {
  33774. js_parse_error(s, "lexical declarations can't appear in single-statement context");
  33775. goto fail;
  33776. }
  33777. /* fall thru */
  33778. case TOK_VAR:
  33779. if (next_token(s))
  33780. goto fail;
  33781. if (js_parse_var(s, PF_IN_ACCEPTED, tok, /*export_flag*/false))
  33782. goto fail;
  33783. if (js_parse_expect_semi(s))
  33784. goto fail;
  33785. break;
  33786. case TOK_IF:
  33787. {
  33788. int label1, label2, mask;
  33789. if (next_token(s))
  33790. goto fail;
  33791. /* create a new scope for `let f;if(1) function f(){}` */
  33792. push_scope(s);
  33793. set_eval_ret_undefined(s);
  33794. if (js_parse_expr_paren(s))
  33795. goto fail;
  33796. label1 = emit_goto(s, OP_if_false, -1);
  33797. if (s->cur_func->is_strict_mode)
  33798. mask = 0;
  33799. else
  33800. mask = DECL_MASK_FUNC; /* Annex B.3.4 */
  33801. if (js_parse_statement_or_decl(s, mask))
  33802. goto fail;
  33803. if (s->token.val == TOK_ELSE) {
  33804. label2 = emit_goto(s, OP_goto, -1);
  33805. if (next_token(s))
  33806. goto fail;
  33807. emit_label(s, label1);
  33808. if (js_parse_statement_or_decl(s, mask))
  33809. goto fail;
  33810. label1 = label2;
  33811. }
  33812. emit_label(s, label1);
  33813. pop_scope(s);
  33814. }
  33815. break;
  33816. case TOK_WHILE:
  33817. {
  33818. int label_cont, label_break;
  33819. BlockEnv break_entry;
  33820. label_cont = new_label(s);
  33821. label_break = new_label(s);
  33822. push_break_entry(s->cur_func, &break_entry,
  33823. label_name, label_break, label_cont, 0);
  33824. if (next_token(s))
  33825. goto fail;
  33826. set_eval_ret_undefined(s);
  33827. emit_label(s, label_cont);
  33828. if (js_parse_expr_paren(s))
  33829. goto fail;
  33830. emit_goto(s, OP_if_false, label_break);
  33831. if (js_parse_statement(s))
  33832. goto fail;
  33833. emit_goto(s, OP_goto, label_cont);
  33834. emit_label(s, label_break);
  33835. pop_break_entry(s->cur_func);
  33836. }
  33837. break;
  33838. case TOK_DO:
  33839. {
  33840. int label_cont, label_break, label1;
  33841. BlockEnv break_entry;
  33842. label_cont = new_label(s);
  33843. label_break = new_label(s);
  33844. label1 = new_label(s);
  33845. push_break_entry(s->cur_func, &break_entry,
  33846. label_name, label_break, label_cont, 0);
  33847. if (next_token(s))
  33848. goto fail;
  33849. emit_label(s, label1);
  33850. set_eval_ret_undefined(s);
  33851. if (js_parse_statement(s))
  33852. goto fail;
  33853. emit_label(s, label_cont);
  33854. if (js_parse_expect(s, TOK_WHILE))
  33855. goto fail;
  33856. if (js_parse_expr_paren(s))
  33857. goto fail;
  33858. /* Insert semicolon if missing */
  33859. if (s->token.val == ';') {
  33860. if (next_token(s))
  33861. goto fail;
  33862. }
  33863. emit_goto(s, OP_if_true, label1);
  33864. emit_label(s, label_break);
  33865. pop_break_entry(s->cur_func);
  33866. }
  33867. break;
  33868. case TOK_FOR:
  33869. {
  33870. int label_cont, label_break, label_body, label_test;
  33871. int pos_cont, pos_body, block_scope_level;
  33872. BlockEnv break_entry;
  33873. int tok, bits;
  33874. bool is_async;
  33875. if (next_token(s))
  33876. goto fail;
  33877. set_eval_ret_undefined(s);
  33878. bits = 0;
  33879. is_async = false;
  33880. if (s->token.val == '(') {
  33881. js_parse_skip_parens_token(s, &bits, false);
  33882. } else if (s->token.val == TOK_AWAIT) {
  33883. if (!(s->cur_func->func_kind & JS_FUNC_ASYNC)) {
  33884. js_parse_error(s, "for await is only valid in asynchronous functions");
  33885. goto fail;
  33886. }
  33887. is_async = true;
  33888. if (next_token(s))
  33889. goto fail;
  33890. s->cur_func->has_await = true;
  33891. }
  33892. if (js_parse_expect(s, '('))
  33893. goto fail;
  33894. if (!(bits & SKIP_HAS_SEMI)) {
  33895. /* parse for/in or for/of */
  33896. if (js_parse_for_in_of(s, label_name, is_async))
  33897. goto fail;
  33898. break;
  33899. }
  33900. block_scope_level = s->cur_func->scope_level;
  33901. /* create scope for the lexical variables declared in the initial,
  33902. test and increment expressions */
  33903. push_scope(s);
  33904. /* initial expression */
  33905. tok = s->token.val;
  33906. if (tok != ';') {
  33907. switch (is_let(s, DECL_MASK_OTHER)) {
  33908. case true:
  33909. tok = TOK_LET;
  33910. break;
  33911. case false:
  33912. break;
  33913. default:
  33914. goto fail;
  33915. }
  33916. if (tok == TOK_VAR || tok == TOK_LET || tok == TOK_CONST) {
  33917. if (next_token(s))
  33918. goto fail;
  33919. if (js_parse_var(s, 0, tok, /*export_flag*/false))
  33920. goto fail;
  33921. } else {
  33922. if (js_parse_expr2(s, false))
  33923. goto fail;
  33924. emit_op(s, OP_drop);
  33925. }
  33926. /* close the closures before the first iteration */
  33927. close_scopes(s, s->cur_func->scope_level, block_scope_level);
  33928. }
  33929. if (js_parse_expect(s, ';'))
  33930. goto fail;
  33931. label_test = new_label(s);
  33932. label_cont = new_label(s);
  33933. label_body = new_label(s);
  33934. label_break = new_label(s);
  33935. push_break_entry(s->cur_func, &break_entry,
  33936. label_name, label_break, label_cont, 0);
  33937. /* test expression */
  33938. if (s->token.val == ';') {
  33939. /* no test expression */
  33940. label_test = label_body;
  33941. } else {
  33942. emit_label(s, label_test);
  33943. if (js_parse_expr(s))
  33944. goto fail;
  33945. emit_goto(s, OP_if_false, label_break);
  33946. }
  33947. if (js_parse_expect(s, ';'))
  33948. goto fail;
  33949. if (s->token.val == ')') {
  33950. /* no end expression */
  33951. break_entry.label_cont = label_cont = label_test;
  33952. pos_cont = 0; /* avoid warning */
  33953. } else {
  33954. /* skip the end expression */
  33955. emit_goto(s, OP_goto, label_body);
  33956. pos_cont = s->cur_func->byte_code.size;
  33957. emit_label(s, label_cont);
  33958. if (js_parse_expr(s))
  33959. goto fail;
  33960. emit_op(s, OP_drop);
  33961. if (label_test != label_body)
  33962. emit_goto(s, OP_goto, label_test);
  33963. }
  33964. if (js_parse_expect(s, ')'))
  33965. goto fail;
  33966. pos_body = s->cur_func->byte_code.size;
  33967. emit_label(s, label_body);
  33968. if (js_parse_statement(s))
  33969. goto fail;
  33970. /* close the closures before the next iteration */
  33971. /* XXX: check continue case */
  33972. close_scopes(s, s->cur_func->scope_level, block_scope_level);
  33973. if (label_test != label_body && label_cont != label_test) {
  33974. /* move the increment code here */
  33975. DynBuf *bc = &s->cur_func->byte_code;
  33976. int chunk_size = pos_body - pos_cont;
  33977. int offset = bc->size - pos_cont;
  33978. int i;
  33979. dbuf_realloc(bc, bc->size + chunk_size);
  33980. dbuf_put(bc, bc->buf + pos_cont, chunk_size);
  33981. memset(bc->buf + pos_cont, OP_nop, chunk_size);
  33982. /* increment part ends with a goto */
  33983. s->cur_func->last_opcode_pos = bc->size - 5;
  33984. /* relocate labels */
  33985. for (i = label_cont; i < s->cur_func->label_count; i++) {
  33986. LabelSlot *ls = &s->cur_func->label_slots[i];
  33987. if (ls->pos >= pos_cont && ls->pos < pos_body)
  33988. ls->pos += offset;
  33989. }
  33990. } else {
  33991. emit_goto(s, OP_goto, label_cont);
  33992. }
  33993. emit_label(s, label_break);
  33994. pop_break_entry(s->cur_func);
  33995. pop_scope(s);
  33996. }
  33997. break;
  33998. case TOK_BREAK:
  33999. case TOK_CONTINUE:
  34000. {
  34001. int is_cont = s->token.val - TOK_BREAK;
  34002. int label;
  34003. if (next_token(s))
  34004. goto fail;
  34005. if (!s->got_lf && s->token.val == TOK_IDENT && !s->token.u.ident.is_reserved)
  34006. label = s->token.u.ident.atom;
  34007. else
  34008. label = JS_ATOM_NULL;
  34009. if (emit_break(s, label, is_cont))
  34010. goto fail;
  34011. if (label != JS_ATOM_NULL) {
  34012. if (next_token(s))
  34013. goto fail;
  34014. }
  34015. if (js_parse_expect_semi(s))
  34016. goto fail;
  34017. }
  34018. break;
  34019. case TOK_SWITCH:
  34020. {
  34021. int label_case, label_break, label1;
  34022. int default_label_pos;
  34023. BlockEnv break_entry;
  34024. if (next_token(s))
  34025. goto fail;
  34026. set_eval_ret_undefined(s);
  34027. if (js_parse_expr_paren(s))
  34028. goto fail;
  34029. push_scope(s);
  34030. label_break = new_label(s);
  34031. push_break_entry(s->cur_func, &break_entry,
  34032. label_name, label_break, -1, 1);
  34033. if (js_parse_expect(s, '{'))
  34034. goto fail;
  34035. default_label_pos = -1;
  34036. label_case = -1;
  34037. while (s->token.val != '}') {
  34038. if (s->token.val == TOK_CASE) {
  34039. label1 = -1;
  34040. if (label_case >= 0) {
  34041. /* skip the case if needed */
  34042. label1 = emit_goto(s, OP_goto, -1);
  34043. }
  34044. emit_label(s, label_case);
  34045. label_case = -1;
  34046. for (;;) {
  34047. /* parse a sequence of case clauses */
  34048. if (next_token(s))
  34049. goto fail;
  34050. emit_op(s, OP_dup);
  34051. if (js_parse_expr(s))
  34052. goto fail;
  34053. if (js_parse_expect(s, ':'))
  34054. goto fail;
  34055. emit_op(s, OP_strict_eq);
  34056. if (s->token.val == TOK_CASE) {
  34057. label1 = emit_goto(s, OP_if_true, label1);
  34058. } else {
  34059. label_case = emit_goto(s, OP_if_false, -1);
  34060. emit_label(s, label1);
  34061. break;
  34062. }
  34063. }
  34064. } else if (s->token.val == TOK_DEFAULT) {
  34065. if (next_token(s))
  34066. goto fail;
  34067. if (js_parse_expect(s, ':'))
  34068. goto fail;
  34069. if (default_label_pos >= 0) {
  34070. js_parse_error(s, "duplicate default");
  34071. goto fail;
  34072. }
  34073. if (label_case < 0) {
  34074. /* falling thru direct from switch expression */
  34075. label_case = emit_goto(s, OP_goto, -1);
  34076. }
  34077. /* Emit a dummy label opcode. Label will be patched after
  34078. the end of the switch body. Do not use emit_label(s, 0)
  34079. because it would clobber label 0 address, preventing
  34080. proper optimizer operation.
  34081. */
  34082. emit_op(s, OP_label);
  34083. emit_u32(s, 0);
  34084. default_label_pos = s->cur_func->byte_code.size - 4;
  34085. } else {
  34086. if (label_case < 0) {
  34087. /* falling thru direct from switch expression */
  34088. js_parse_error(s, "invalid switch statement");
  34089. goto fail;
  34090. }
  34091. if (js_parse_statement_or_decl(s, DECL_MASK_ALL))
  34092. goto fail;
  34093. }
  34094. }
  34095. if (js_parse_expect(s, '}'))
  34096. goto fail;
  34097. if (default_label_pos >= 0) {
  34098. /* Ugly patch for the the `default` label, shameful and risky */
  34099. put_u32(s->cur_func->byte_code.buf + default_label_pos,
  34100. label_case);
  34101. s->cur_func->label_slots[label_case].pos = default_label_pos + 4;
  34102. } else {
  34103. emit_label(s, label_case);
  34104. }
  34105. emit_label(s, label_break);
  34106. emit_op(s, OP_drop); /* drop the switch expression */
  34107. pop_break_entry(s->cur_func);
  34108. pop_scope(s);
  34109. }
  34110. break;
  34111. case TOK_TRY:
  34112. {
  34113. int label_catch, label_catch2, label_finally, label_end;
  34114. JSAtom name;
  34115. BlockEnv block_env;
  34116. set_eval_ret_undefined(s);
  34117. if (next_token(s))
  34118. goto fail;
  34119. label_catch = new_label(s);
  34120. label_catch2 = new_label(s);
  34121. label_finally = new_label(s);
  34122. label_end = new_label(s);
  34123. emit_goto(s, OP_catch, label_catch);
  34124. push_break_entry(s->cur_func, &block_env,
  34125. JS_ATOM_NULL, -1, -1, 1);
  34126. block_env.label_finally = label_finally;
  34127. if (js_parse_block(s))
  34128. goto fail;
  34129. pop_break_entry(s->cur_func);
  34130. if (js_is_live_code(s)) {
  34131. /* drop the catch offset */
  34132. emit_op(s, OP_drop);
  34133. /* must push dummy value to keep same stack size */
  34134. emit_op(s, OP_undefined);
  34135. emit_goto(s, OP_gosub, label_finally);
  34136. emit_op(s, OP_drop);
  34137. emit_goto(s, OP_goto, label_end);
  34138. }
  34139. if (s->token.val == TOK_CATCH) {
  34140. if (next_token(s))
  34141. goto fail;
  34142. push_scope(s); /* catch variable */
  34143. emit_label(s, label_catch);
  34144. if (s->token.val == '{') {
  34145. /* support optional-catch-binding feature */
  34146. emit_op(s, OP_drop); /* pop the exception object */
  34147. } else {
  34148. if (js_parse_expect(s, '('))
  34149. goto fail;
  34150. if (!(s->token.val == TOK_IDENT && !s->token.u.ident.is_reserved)) {
  34151. if (s->token.val == '[' || s->token.val == '{') {
  34152. /* XXX: TOK_LET is not completely correct */
  34153. if (js_parse_destructuring_element(s, TOK_LET, false, true, -1, true, false) < 0)
  34154. goto fail;
  34155. } else {
  34156. js_parse_error(s, "identifier expected");
  34157. goto fail;
  34158. }
  34159. } else {
  34160. name = JS_DupAtom(ctx, s->token.u.ident.atom);
  34161. if (next_token(s)
  34162. || js_define_var(s, name, TOK_CATCH) < 0) {
  34163. JS_FreeAtom(ctx, name);
  34164. goto fail;
  34165. }
  34166. /* store the exception value in the catch variable */
  34167. emit_op(s, OP_scope_put_var);
  34168. emit_u32(s, name);
  34169. emit_u16(s, s->cur_func->scope_level);
  34170. }
  34171. if (js_parse_expect(s, ')'))
  34172. goto fail;
  34173. }
  34174. /* XXX: should keep the address to nop it out if there is no finally block */
  34175. emit_goto(s, OP_catch, label_catch2);
  34176. push_scope(s); /* catch block */
  34177. push_break_entry(s->cur_func, &block_env, JS_ATOM_NULL,
  34178. -1, -1, 1);
  34179. block_env.label_finally = label_finally;
  34180. if (js_parse_block(s))
  34181. goto fail;
  34182. pop_break_entry(s->cur_func);
  34183. pop_scope(s); /* catch block */
  34184. pop_scope(s); /* catch variable */
  34185. if (js_is_live_code(s)) {
  34186. /* drop the catch2 offset */
  34187. emit_op(s, OP_drop);
  34188. /* XXX: should keep the address to nop it out if there is no finally block */
  34189. /* must push dummy value to keep same stack size */
  34190. emit_op(s, OP_undefined);
  34191. emit_goto(s, OP_gosub, label_finally);
  34192. emit_op(s, OP_drop);
  34193. emit_goto(s, OP_goto, label_end);
  34194. }
  34195. /* catch exceptions thrown in the catch block to execute the
  34196. * finally clause and rethrow the exception */
  34197. emit_label(s, label_catch2);
  34198. /* catch value is at TOS, no need to push undefined */
  34199. emit_goto(s, OP_gosub, label_finally);
  34200. emit_op(s, OP_throw);
  34201. } else if (s->token.val == TOK_FINALLY) {
  34202. /* finally without catch : execute the finally clause
  34203. * and rethrow the exception */
  34204. emit_label(s, label_catch);
  34205. /* catch value is at TOS, no need to push undefined */
  34206. emit_goto(s, OP_gosub, label_finally);
  34207. emit_op(s, OP_throw);
  34208. } else {
  34209. js_parse_error(s, "expecting catch or finally");
  34210. goto fail;
  34211. }
  34212. emit_label(s, label_finally);
  34213. if (s->token.val == TOK_FINALLY) {
  34214. int saved_eval_ret_idx = 0; /* avoid warning */
  34215. if (next_token(s))
  34216. goto fail;
  34217. /* on the stack: ret_value gosub_ret_value */
  34218. push_break_entry(s->cur_func, &block_env, JS_ATOM_NULL,
  34219. -1, -1, 2);
  34220. if (s->cur_func->eval_ret_idx >= 0) {
  34221. /* 'finally' updates eval_ret only if not a normal
  34222. termination */
  34223. saved_eval_ret_idx =
  34224. add_var(s->ctx, s->cur_func, JS_ATOM__ret_);
  34225. if (saved_eval_ret_idx < 0)
  34226. goto fail;
  34227. emit_op(s, OP_get_loc);
  34228. emit_u16(s, s->cur_func->eval_ret_idx);
  34229. emit_op(s, OP_put_loc);
  34230. emit_u16(s, saved_eval_ret_idx);
  34231. set_eval_ret_undefined(s);
  34232. }
  34233. if (js_parse_block(s))
  34234. goto fail;
  34235. if (s->cur_func->eval_ret_idx >= 0) {
  34236. emit_op(s, OP_get_loc);
  34237. emit_u16(s, saved_eval_ret_idx);
  34238. emit_op(s, OP_put_loc);
  34239. emit_u16(s, s->cur_func->eval_ret_idx);
  34240. }
  34241. pop_break_entry(s->cur_func);
  34242. }
  34243. emit_op(s, OP_ret);
  34244. emit_label(s, label_end);
  34245. }
  34246. break;
  34247. case ';':
  34248. /* empty statement */
  34249. if (next_token(s))
  34250. goto fail;
  34251. break;
  34252. case TOK_WITH:
  34253. if (s->cur_func->is_strict_mode) {
  34254. js_parse_error(s, "invalid keyword: with");
  34255. goto fail;
  34256. } else {
  34257. int with_idx;
  34258. if (next_token(s))
  34259. goto fail;
  34260. if (js_parse_expr_paren(s))
  34261. goto fail;
  34262. push_scope(s);
  34263. with_idx = define_var(s, s->cur_func, JS_ATOM__with_,
  34264. JS_VAR_DEF_WITH);
  34265. if (with_idx < 0)
  34266. goto fail;
  34267. emit_op(s, OP_to_object);
  34268. emit_op(s, OP_put_loc);
  34269. emit_u16(s, with_idx);
  34270. set_eval_ret_undefined(s);
  34271. if (js_parse_statement(s))
  34272. goto fail;
  34273. /* Popping scope drops lexical context for the with object variable */
  34274. pop_scope(s);
  34275. }
  34276. break;
  34277. case TOK_FUNCTION:
  34278. /* ES6 Annex B.3.2 and B.3.3 semantics */
  34279. if (!(decl_mask & DECL_MASK_FUNC))
  34280. goto func_decl_error;
  34281. if (!(decl_mask & DECL_MASK_OTHER) && peek_token(s, false) == '*')
  34282. goto func_decl_error;
  34283. goto parse_func_var;
  34284. case TOK_IDENT:
  34285. if (s->token.u.ident.is_reserved) {
  34286. js_parse_error_reserved_identifier(s);
  34287. goto fail;
  34288. }
  34289. /* Determine if `let` introduces a Declaration or an ExpressionStatement */
  34290. switch (is_let(s, decl_mask)) {
  34291. case true:
  34292. tok = TOK_LET;
  34293. goto haslet;
  34294. case false:
  34295. break;
  34296. default:
  34297. goto fail;
  34298. }
  34299. if (token_is_pseudo_keyword(s, JS_ATOM_async) &&
  34300. peek_token(s, true) == TOK_FUNCTION) {
  34301. if (!(decl_mask & DECL_MASK_OTHER)) {
  34302. func_decl_error:
  34303. js_parse_error(s, "function declarations can't appear in single-statement context");
  34304. goto fail;
  34305. }
  34306. parse_func_var:
  34307. if (js_parse_function_decl(s, JS_PARSE_FUNC_VAR,
  34308. JS_FUNC_NORMAL, JS_ATOM_NULL,
  34309. s->token.ptr,
  34310. s->token.line_num,
  34311. s->token.col_num))
  34312. goto fail;
  34313. break;
  34314. }
  34315. goto hasexpr;
  34316. case TOK_CLASS:
  34317. if (!(decl_mask & DECL_MASK_OTHER)) {
  34318. js_parse_error(s, "class declarations can't appear in single-statement context");
  34319. goto fail;
  34320. }
  34321. if (js_parse_class(s, false, JS_PARSE_EXPORT_NONE))
  34322. return -1;
  34323. break;
  34324. case TOK_DEBUGGER:
  34325. /* currently no debugger, so just skip the keyword */
  34326. if (next_token(s))
  34327. goto fail;
  34328. if (js_parse_expect_semi(s))
  34329. goto fail;
  34330. break;
  34331. case TOK_ENUM:
  34332. case TOK_EXPORT:
  34333. case TOK_EXTENDS:
  34334. js_unsupported_keyword(s, s->token.u.ident.atom);
  34335. goto fail;
  34336. default:
  34337. hasexpr:
  34338. emit_source_loc(s);
  34339. if (js_parse_expr(s))
  34340. goto fail;
  34341. if (s->cur_func->eval_ret_idx >= 0) {
  34342. /* store the expression value so that it can be returned
  34343. by eval() */
  34344. emit_op(s, OP_put_loc);
  34345. emit_u16(s, s->cur_func->eval_ret_idx);
  34346. } else {
  34347. emit_op(s, OP_drop); /* drop the result */
  34348. }
  34349. if (js_parse_expect_semi(s))
  34350. goto fail;
  34351. break;
  34352. }
  34353. done:
  34354. JS_FreeAtom(ctx, label_name);
  34355. return 0;
  34356. fail:
  34357. JS_FreeAtom(ctx, label_name);
  34358. return -1;
  34359. }
  34360. /* 'name' is freed */
  34361. static JSModuleDef *js_new_module_def(JSContext *ctx, JSAtom name)
  34362. {
  34363. JSModuleDef *m;
  34364. m = js_mallocz(ctx, sizeof(*m));
  34365. if (!m) {
  34366. JS_FreeAtom(ctx, name);
  34367. return NULL;
  34368. }
  34369. m->header.ref_count = 1;
  34370. m->module_name = name;
  34371. m->module_ns = JS_UNDEFINED;
  34372. m->func_obj = JS_UNDEFINED;
  34373. m->eval_exception = JS_UNDEFINED;
  34374. m->meta_obj = JS_UNDEFINED;
  34375. m->promise = JS_UNDEFINED;
  34376. m->resolving_funcs[0] = JS_UNDEFINED;
  34377. m->resolving_funcs[1] = JS_UNDEFINED;
  34378. list_add_tail(&m->link, &ctx->loaded_modules);
  34379. return m;
  34380. }
  34381. static void js_mark_module_def(JSRuntime *rt, JSModuleDef *m,
  34382. JS_MarkFunc *mark_func)
  34383. {
  34384. int i;
  34385. for(i = 0; i < m->export_entries_count; i++) {
  34386. JSExportEntry *me = &m->export_entries[i];
  34387. if (me->export_type == JS_EXPORT_TYPE_LOCAL &&
  34388. me->u.local.var_ref) {
  34389. mark_func(rt, &me->u.local.var_ref->header);
  34390. }
  34391. }
  34392. JS_MarkValue(rt, m->module_ns, mark_func);
  34393. JS_MarkValue(rt, m->func_obj, mark_func);
  34394. JS_MarkValue(rt, m->eval_exception, mark_func);
  34395. JS_MarkValue(rt, m->meta_obj, mark_func);
  34396. JS_MarkValue(rt, m->promise, mark_func);
  34397. JS_MarkValue(rt, m->resolving_funcs[0], mark_func);
  34398. JS_MarkValue(rt, m->resolving_funcs[1], mark_func);
  34399. }
  34400. static void js_free_module_def(JSContext *ctx, JSModuleDef *m)
  34401. {
  34402. int i;
  34403. JS_FreeAtom(ctx, m->module_name);
  34404. for(i = 0; i < m->req_module_entries_count; i++) {
  34405. JSReqModuleEntry *rme = &m->req_module_entries[i];
  34406. JS_FreeAtom(ctx, rme->module_name);
  34407. }
  34408. js_free(ctx, m->req_module_entries);
  34409. for(i = 0; i < m->export_entries_count; i++) {
  34410. JSExportEntry *me = &m->export_entries[i];
  34411. if (me->export_type == JS_EXPORT_TYPE_LOCAL)
  34412. free_var_ref(ctx->rt, me->u.local.var_ref);
  34413. JS_FreeAtom(ctx, me->export_name);
  34414. JS_FreeAtom(ctx, me->local_name);
  34415. }
  34416. js_free(ctx, m->export_entries);
  34417. js_free(ctx, m->star_export_entries);
  34418. for(i = 0; i < m->import_entries_count; i++) {
  34419. JSImportEntry *mi = &m->import_entries[i];
  34420. JS_FreeAtom(ctx, mi->import_name);
  34421. }
  34422. js_free(ctx, m->import_entries);
  34423. js_free(ctx, m->async_parent_modules);
  34424. JS_FreeValue(ctx, m->module_ns);
  34425. JS_FreeValue(ctx, m->func_obj);
  34426. JS_FreeValue(ctx, m->eval_exception);
  34427. JS_FreeValue(ctx, m->meta_obj);
  34428. JS_FreeValue(ctx, m->promise);
  34429. JS_FreeValue(ctx, m->resolving_funcs[0]);
  34430. JS_FreeValue(ctx, m->resolving_funcs[1]);
  34431. list_del(&m->link);
  34432. js_free(ctx, m);
  34433. }
  34434. static int add_req_module_entry(JSContext *ctx, JSModuleDef *m,
  34435. JSAtom module_name)
  34436. {
  34437. JSReqModuleEntry *rme;
  34438. int i;
  34439. /* no need to add the module request if it is already present */
  34440. for(i = 0; i < m->req_module_entries_count; i++) {
  34441. rme = &m->req_module_entries[i];
  34442. if (rme->module_name == module_name)
  34443. return i;
  34444. }
  34445. if (js_resize_array(ctx, (void **)&m->req_module_entries,
  34446. sizeof(JSReqModuleEntry),
  34447. &m->req_module_entries_size,
  34448. m->req_module_entries_count + 1))
  34449. return -1;
  34450. rme = &m->req_module_entries[m->req_module_entries_count++];
  34451. rme->module_name = JS_DupAtom(ctx, module_name);
  34452. rme->module = NULL;
  34453. return i;
  34454. }
  34455. static JSExportEntry *find_export_entry(JSContext *ctx, const JSModuleDef *m,
  34456. JSAtom export_name)
  34457. {
  34458. JSExportEntry *me;
  34459. int i;
  34460. for(i = 0; i < m->export_entries_count; i++) {
  34461. me = &m->export_entries[i];
  34462. if (me->export_name == export_name)
  34463. return me;
  34464. }
  34465. return NULL;
  34466. }
  34467. static JSExportEntry *add_export_entry2(JSContext *ctx,
  34468. JSParseState *s, JSModuleDef *m,
  34469. JSAtom local_name, JSAtom export_name,
  34470. JSExportTypeEnum export_type)
  34471. {
  34472. JSExportEntry *me;
  34473. if (find_export_entry(ctx, m, export_name)) {
  34474. char buf1[ATOM_GET_STR_BUF_SIZE];
  34475. if (s) {
  34476. js_parse_error(s, "duplicate exported name '%s'",
  34477. JS_AtomGetStr(ctx, buf1, sizeof(buf1), export_name));
  34478. } else {
  34479. JS_ThrowSyntaxErrorAtom(ctx, "duplicate exported name '%s'", export_name);
  34480. }
  34481. return NULL;
  34482. }
  34483. if (js_resize_array(ctx, (void **)&m->export_entries,
  34484. sizeof(JSExportEntry),
  34485. &m->export_entries_size,
  34486. m->export_entries_count + 1))
  34487. return NULL;
  34488. me = &m->export_entries[m->export_entries_count++];
  34489. memset(me, 0, sizeof(*me));
  34490. me->local_name = JS_DupAtom(ctx, local_name);
  34491. me->export_name = JS_DupAtom(ctx, export_name);
  34492. me->export_type = export_type;
  34493. return me;
  34494. }
  34495. static JSExportEntry *add_export_entry(JSParseState *s, JSModuleDef *m,
  34496. JSAtom local_name, JSAtom export_name,
  34497. JSExportTypeEnum export_type)
  34498. {
  34499. return add_export_entry2(s->ctx, s, m, local_name, export_name,
  34500. export_type);
  34501. }
  34502. static int add_star_export_entry(JSContext *ctx, JSModuleDef *m,
  34503. int req_module_idx)
  34504. {
  34505. JSStarExportEntry *se;
  34506. if (js_resize_array(ctx, (void **)&m->star_export_entries,
  34507. sizeof(JSStarExportEntry),
  34508. &m->star_export_entries_size,
  34509. m->star_export_entries_count + 1))
  34510. return -1;
  34511. se = &m->star_export_entries[m->star_export_entries_count++];
  34512. se->req_module_idx = req_module_idx;
  34513. return 0;
  34514. }
  34515. /* create a C module */
  34516. /* `name_str` may be pure ASCII or UTF-8 encoded */
  34517. JSModuleDef *JS_NewCModule(JSContext *ctx, const char *name_str,
  34518. JSModuleInitFunc *func)
  34519. {
  34520. JSModuleDef *m;
  34521. JSAtom name;
  34522. name = JS_NewAtom(ctx, name_str);
  34523. if (name == JS_ATOM_NULL)
  34524. return NULL;
  34525. m = js_new_module_def(ctx, name);
  34526. m->init_func = func;
  34527. return m;
  34528. }
  34529. /* `export_name` may be pure ASCII or UTF-8 encoded */
  34530. int JS_AddModuleExport(JSContext *ctx, JSModuleDef *m, const char *export_name)
  34531. {
  34532. JSExportEntry *me;
  34533. JSAtom name;
  34534. name = JS_NewAtom(ctx, export_name);
  34535. if (name == JS_ATOM_NULL)
  34536. return -1;
  34537. me = add_export_entry2(ctx, NULL, m, JS_ATOM_NULL, name,
  34538. JS_EXPORT_TYPE_LOCAL);
  34539. JS_FreeAtom(ctx, name);
  34540. if (!me)
  34541. return -1;
  34542. else
  34543. return 0;
  34544. }
  34545. /* `export_name` may be pure ASCII or UTF-8 encoded */
  34546. int JS_SetModuleExport(JSContext *ctx, JSModuleDef *m, const char *export_name,
  34547. JSValue val)
  34548. {
  34549. JSExportEntry *me;
  34550. JSAtom name;
  34551. name = JS_NewAtom(ctx, export_name);
  34552. if (name == JS_ATOM_NULL)
  34553. goto fail;
  34554. me = find_export_entry(ctx, m, name);
  34555. JS_FreeAtom(ctx, name);
  34556. if (!me)
  34557. goto fail;
  34558. set_value(ctx, me->u.local.var_ref->pvalue, val);
  34559. return 0;
  34560. fail:
  34561. JS_FreeValue(ctx, val);
  34562. return -1;
  34563. }
  34564. void JS_SetModuleLoaderFunc(JSRuntime *rt,
  34565. JSModuleNormalizeFunc *module_normalize,
  34566. JSModuleLoaderFunc *module_loader, void *opaque)
  34567. {
  34568. rt->module_normalize_func = module_normalize;
  34569. rt->module_loader_func = module_loader;
  34570. rt->module_loader_opaque = opaque;
  34571. }
  34572. /* default module filename normalizer */
  34573. static char *js_default_module_normalize_name(JSContext *ctx,
  34574. const char *base_name,
  34575. const char *name)
  34576. {
  34577. char *filename, *p;
  34578. const char *r;
  34579. int cap;
  34580. int len;
  34581. if (name[0] != '.') {
  34582. /* if no initial dot, the module name is not modified */
  34583. return js_strdup(ctx, name);
  34584. }
  34585. p = strrchr(base_name, '/');
  34586. if (p)
  34587. len = p - base_name;
  34588. else
  34589. len = 0;
  34590. cap = len + strlen(name) + 1 + 1;
  34591. filename = js_malloc(ctx, cap);
  34592. if (!filename)
  34593. return NULL;
  34594. memcpy(filename, base_name, len);
  34595. filename[len] = '\0';
  34596. /* we only normalize the leading '..' or '.' */
  34597. r = name;
  34598. for(;;) {
  34599. if (r[0] == '.' && r[1] == '/') {
  34600. r += 2;
  34601. } else if (r[0] == '.' && r[1] == '.' && r[2] == '/') {
  34602. /* remove the last path element of filename, except if "."
  34603. or ".." */
  34604. if (filename[0] == '\0')
  34605. break;
  34606. p = strrchr(filename, '/');
  34607. if (!p)
  34608. p = filename;
  34609. else
  34610. p++;
  34611. if (!strcmp(p, ".") || !strcmp(p, ".."))
  34612. break;
  34613. if (p > filename)
  34614. p--;
  34615. *p = '\0';
  34616. r += 3;
  34617. } else {
  34618. break;
  34619. }
  34620. }
  34621. if (filename[0] != '\0')
  34622. js__pstrcat(filename, cap, "/");
  34623. js__pstrcat(filename, cap, r);
  34624. // printf("normalize: %s %s -> %s\n", base_name, name, filename);
  34625. return filename;
  34626. }
  34627. static JSModuleDef *js_find_loaded_module(JSContext *ctx, JSAtom name)
  34628. {
  34629. struct list_head *el;
  34630. JSModuleDef *m;
  34631. /* first look at the loaded modules */
  34632. list_for_each(el, &ctx->loaded_modules) {
  34633. m = list_entry(el, JSModuleDef, link);
  34634. if (m->module_name == name)
  34635. return m;
  34636. }
  34637. return NULL;
  34638. }
  34639. /* return NULL in case of exception (e.g. module could not be loaded) */
  34640. /* `base_cname` and `cname1` may be pure ASCII or UTF-8 encoded */
  34641. static JSModuleDef *js_host_resolve_imported_module(JSContext *ctx,
  34642. const char *base_cname,
  34643. const char *cname1)
  34644. {
  34645. JSRuntime *rt = ctx->rt;
  34646. JSModuleDef *m;
  34647. char *cname;
  34648. JSAtom module_name;
  34649. if (!rt->module_normalize_func) {
  34650. cname = js_default_module_normalize_name(ctx, base_cname, cname1);
  34651. } else {
  34652. cname = rt->module_normalize_func(ctx, base_cname, cname1,
  34653. rt->module_loader_opaque);
  34654. }
  34655. if (!cname)
  34656. return NULL;
  34657. module_name = JS_NewAtom(ctx, cname);
  34658. if (module_name == JS_ATOM_NULL) {
  34659. js_free(ctx, cname);
  34660. return NULL;
  34661. }
  34662. /* first look at the loaded modules */
  34663. m = js_find_loaded_module(ctx, module_name);
  34664. if (m) {
  34665. js_free(ctx, cname);
  34666. JS_FreeAtom(ctx, module_name);
  34667. return m;
  34668. }
  34669. JS_FreeAtom(ctx, module_name);
  34670. /* load the module */
  34671. if (!rt->module_loader_func) {
  34672. /* XXX: use a syntax error ? */
  34673. // XXX: update JS_DetectModule when you change this
  34674. JS_ThrowReferenceError(ctx, "could not load module '%s'",
  34675. cname);
  34676. js_free(ctx, cname);
  34677. return NULL;
  34678. }
  34679. m = rt->module_loader_func(ctx, cname, rt->module_loader_opaque);
  34680. js_free(ctx, cname);
  34681. return m;
  34682. }
  34683. static JSModuleDef *js_host_resolve_imported_module_atom(JSContext *ctx,
  34684. JSAtom base_module_name,
  34685. JSAtom module_name1)
  34686. {
  34687. const char *base_cname, *cname;
  34688. JSModuleDef *m;
  34689. base_cname = JS_AtomToCString(ctx, base_module_name);
  34690. if (!base_cname)
  34691. return NULL;
  34692. cname = JS_AtomToCString(ctx, module_name1);
  34693. if (!cname) {
  34694. JS_FreeCString(ctx, base_cname);
  34695. return NULL;
  34696. }
  34697. m = js_host_resolve_imported_module(ctx, base_cname, cname);
  34698. JS_FreeCString(ctx, base_cname);
  34699. JS_FreeCString(ctx, cname);
  34700. return m;
  34701. }
  34702. typedef struct JSResolveEntry {
  34703. JSModuleDef *module;
  34704. JSAtom name;
  34705. } JSResolveEntry;
  34706. typedef struct JSResolveState {
  34707. JSResolveEntry *array;
  34708. int size;
  34709. int count;
  34710. } JSResolveState;
  34711. static int find_resolve_entry(JSResolveState *s,
  34712. JSModuleDef *m, JSAtom name)
  34713. {
  34714. int i;
  34715. for(i = 0; i < s->count; i++) {
  34716. JSResolveEntry *re = &s->array[i];
  34717. if (re->module == m && re->name == name)
  34718. return i;
  34719. }
  34720. return -1;
  34721. }
  34722. static int add_resolve_entry(JSContext *ctx, JSResolveState *s,
  34723. JSModuleDef *m, JSAtom name)
  34724. {
  34725. JSResolveEntry *re;
  34726. if (js_resize_array(ctx, (void **)&s->array,
  34727. sizeof(JSResolveEntry),
  34728. &s->size, s->count + 1))
  34729. return -1;
  34730. re = &s->array[s->count++];
  34731. re->module = m;
  34732. re->name = JS_DupAtom(ctx, name);
  34733. return 0;
  34734. }
  34735. typedef enum JSResolveResultEnum {
  34736. JS_RESOLVE_RES_EXCEPTION = -1, /* memory alloc error */
  34737. JS_RESOLVE_RES_FOUND = 0,
  34738. JS_RESOLVE_RES_NOT_FOUND,
  34739. JS_RESOLVE_RES_CIRCULAR,
  34740. JS_RESOLVE_RES_AMBIGUOUS,
  34741. } JSResolveResultEnum;
  34742. static JSResolveResultEnum js_resolve_export1(JSContext *ctx,
  34743. JSModuleDef **pmodule,
  34744. JSExportEntry **pme,
  34745. JSModuleDef *m,
  34746. JSAtom export_name,
  34747. JSResolveState *s)
  34748. {
  34749. JSExportEntry *me;
  34750. *pmodule = NULL;
  34751. *pme = NULL;
  34752. if (find_resolve_entry(s, m, export_name) >= 0)
  34753. return JS_RESOLVE_RES_CIRCULAR;
  34754. if (add_resolve_entry(ctx, s, m, export_name) < 0)
  34755. return JS_RESOLVE_RES_EXCEPTION;
  34756. me = find_export_entry(ctx, m, export_name);
  34757. if (me) {
  34758. if (me->export_type == JS_EXPORT_TYPE_LOCAL) {
  34759. /* local export */
  34760. *pmodule = m;
  34761. *pme = me;
  34762. return JS_RESOLVE_RES_FOUND;
  34763. } else {
  34764. /* indirect export */
  34765. JSModuleDef *m1;
  34766. m1 = m->req_module_entries[me->u.req_module_idx].module;
  34767. if (me->local_name == JS_ATOM__star_) {
  34768. /* export ns from */
  34769. *pmodule = m;
  34770. *pme = me;
  34771. return JS_RESOLVE_RES_FOUND;
  34772. } else {
  34773. return js_resolve_export1(ctx, pmodule, pme, m1,
  34774. me->local_name, s);
  34775. }
  34776. }
  34777. } else {
  34778. if (export_name != JS_ATOM_default) {
  34779. /* not found in direct or indirect exports: try star exports */
  34780. int i;
  34781. for(i = 0; i < m->star_export_entries_count; i++) {
  34782. JSStarExportEntry *se = &m->star_export_entries[i];
  34783. JSModuleDef *m1, *res_m;
  34784. JSExportEntry *res_me;
  34785. JSResolveResultEnum ret;
  34786. m1 = m->req_module_entries[se->req_module_idx].module;
  34787. ret = js_resolve_export1(ctx, &res_m, &res_me, m1,
  34788. export_name, s);
  34789. if (ret == JS_RESOLVE_RES_AMBIGUOUS ||
  34790. ret == JS_RESOLVE_RES_EXCEPTION) {
  34791. return ret;
  34792. } else if (ret == JS_RESOLVE_RES_FOUND) {
  34793. if (*pme != NULL) {
  34794. if (*pmodule != res_m ||
  34795. res_me->local_name != (*pme)->local_name) {
  34796. *pmodule = NULL;
  34797. *pme = NULL;
  34798. return JS_RESOLVE_RES_AMBIGUOUS;
  34799. }
  34800. } else {
  34801. *pmodule = res_m;
  34802. *pme = res_me;
  34803. }
  34804. }
  34805. }
  34806. if (*pme != NULL)
  34807. return JS_RESOLVE_RES_FOUND;
  34808. }
  34809. return JS_RESOLVE_RES_NOT_FOUND;
  34810. }
  34811. }
  34812. /* If the return value is JS_RESOLVE_RES_FOUND, return the module
  34813. (*pmodule) and the corresponding local export entry
  34814. (*pme). Otherwise return (NULL, NULL) */
  34815. static JSResolveResultEnum js_resolve_export(JSContext *ctx,
  34816. JSModuleDef **pmodule,
  34817. JSExportEntry **pme,
  34818. JSModuleDef *m,
  34819. JSAtom export_name)
  34820. {
  34821. JSResolveState ss, *s = &ss;
  34822. int i;
  34823. JSResolveResultEnum ret;
  34824. s->array = NULL;
  34825. s->size = 0;
  34826. s->count = 0;
  34827. ret = js_resolve_export1(ctx, pmodule, pme, m, export_name, s);
  34828. for(i = 0; i < s->count; i++)
  34829. JS_FreeAtom(ctx, s->array[i].name);
  34830. js_free(ctx, s->array);
  34831. return ret;
  34832. }
  34833. static void js_resolve_export_throw_error(JSContext *ctx,
  34834. JSResolveResultEnum res,
  34835. JSModuleDef *m, JSAtom export_name)
  34836. {
  34837. char buf1[ATOM_GET_STR_BUF_SIZE];
  34838. char buf2[ATOM_GET_STR_BUF_SIZE];
  34839. switch(res) {
  34840. case JS_RESOLVE_RES_EXCEPTION:
  34841. break;
  34842. default:
  34843. case JS_RESOLVE_RES_NOT_FOUND:
  34844. JS_ThrowSyntaxError(ctx, "Could not find export '%s' in module '%s'",
  34845. JS_AtomGetStr(ctx, buf1, sizeof(buf1), export_name),
  34846. JS_AtomGetStr(ctx, buf2, sizeof(buf2), m->module_name));
  34847. break;
  34848. case JS_RESOLVE_RES_CIRCULAR:
  34849. JS_ThrowSyntaxError(ctx, "circular reference when looking for export '%s' in module '%s'",
  34850. JS_AtomGetStr(ctx, buf1, sizeof(buf1), export_name),
  34851. JS_AtomGetStr(ctx, buf2, sizeof(buf2), m->module_name));
  34852. break;
  34853. case JS_RESOLVE_RES_AMBIGUOUS:
  34854. JS_ThrowSyntaxError(ctx, "export '%s' in module '%s' is ambiguous",
  34855. JS_AtomGetStr(ctx, buf1, sizeof(buf1), export_name),
  34856. JS_AtomGetStr(ctx, buf2, sizeof(buf2), m->module_name));
  34857. break;
  34858. }
  34859. }
  34860. typedef enum {
  34861. EXPORTED_NAME_AMBIGUOUS,
  34862. EXPORTED_NAME_NORMAL,
  34863. EXPORTED_NAME_NS,
  34864. } ExportedNameEntryEnum;
  34865. typedef struct ExportedNameEntry {
  34866. JSAtom export_name;
  34867. ExportedNameEntryEnum export_type;
  34868. union {
  34869. JSExportEntry *me; /* using when the list is built */
  34870. JSVarRef *var_ref; /* EXPORTED_NAME_NORMAL */
  34871. JSModuleDef *module; /* for EXPORTED_NAME_NS */
  34872. } u;
  34873. } ExportedNameEntry;
  34874. typedef struct GetExportNamesState {
  34875. JSModuleDef **modules;
  34876. int modules_size;
  34877. int modules_count;
  34878. ExportedNameEntry *exported_names;
  34879. int exported_names_size;
  34880. int exported_names_count;
  34881. } GetExportNamesState;
  34882. static int find_exported_name(GetExportNamesState *s, JSAtom name)
  34883. {
  34884. int i;
  34885. for(i = 0; i < s->exported_names_count; i++) {
  34886. if (s->exported_names[i].export_name == name)
  34887. return i;
  34888. }
  34889. return -1;
  34890. }
  34891. static __exception int get_exported_names(JSContext *ctx,
  34892. GetExportNamesState *s,
  34893. JSModuleDef *m, bool from_star)
  34894. {
  34895. ExportedNameEntry *en;
  34896. int i, j;
  34897. /* check circular reference */
  34898. for(i = 0; i < s->modules_count; i++) {
  34899. if (s->modules[i] == m)
  34900. return 0;
  34901. }
  34902. if (js_resize_array(ctx, (void **)&s->modules, sizeof(s->modules[0]),
  34903. &s->modules_size, s->modules_count + 1))
  34904. return -1;
  34905. s->modules[s->modules_count++] = m;
  34906. for(i = 0; i < m->export_entries_count; i++) {
  34907. JSExportEntry *me = &m->export_entries[i];
  34908. if (from_star && me->export_name == JS_ATOM_default)
  34909. continue;
  34910. j = find_exported_name(s, me->export_name);
  34911. if (j < 0) {
  34912. if (js_resize_array(ctx, (void **)&s->exported_names, sizeof(s->exported_names[0]),
  34913. &s->exported_names_size,
  34914. s->exported_names_count + 1))
  34915. return -1;
  34916. en = &s->exported_names[s->exported_names_count++];
  34917. en->export_name = me->export_name;
  34918. /* avoid a second lookup for simple module exports */
  34919. if (from_star || me->export_type != JS_EXPORT_TYPE_LOCAL)
  34920. en->u.me = NULL;
  34921. else
  34922. en->u.me = me;
  34923. } else {
  34924. en = &s->exported_names[j];
  34925. en->u.me = NULL;
  34926. }
  34927. }
  34928. for(i = 0; i < m->star_export_entries_count; i++) {
  34929. JSStarExportEntry *se = &m->star_export_entries[i];
  34930. JSModuleDef *m1;
  34931. m1 = m->req_module_entries[se->req_module_idx].module;
  34932. if (get_exported_names(ctx, s, m1, true))
  34933. return -1;
  34934. }
  34935. return 0;
  34936. }
  34937. /* Unfortunately, the spec gives a different behavior from GetOwnProperty ! */
  34938. static int js_module_ns_has(JSContext *ctx, JSValueConst obj, JSAtom atom)
  34939. {
  34940. return (find_own_property1(JS_VALUE_GET_OBJ(obj), atom) != NULL);
  34941. }
  34942. static const JSClassExoticMethods js_module_ns_exotic_methods = {
  34943. .has_property = js_module_ns_has,
  34944. };
  34945. static int exported_names_cmp(const void *p1, const void *p2, void *opaque)
  34946. {
  34947. JSContext *ctx = opaque;
  34948. const ExportedNameEntry *me1 = p1;
  34949. const ExportedNameEntry *me2 = p2;
  34950. JSValue str1, str2;
  34951. int ret;
  34952. /* XXX: should avoid allocation memory in atom comparison */
  34953. str1 = JS_AtomToString(ctx, me1->export_name);
  34954. str2 = JS_AtomToString(ctx, me2->export_name);
  34955. if (JS_IsException(str1) || JS_IsException(str2)) {
  34956. /* XXX: raise an error ? */
  34957. ret = 0;
  34958. } else {
  34959. ret = js_string_compare(JS_VALUE_GET_STRING(str1),
  34960. JS_VALUE_GET_STRING(str2));
  34961. }
  34962. JS_FreeValue(ctx, str1);
  34963. JS_FreeValue(ctx, str2);
  34964. return ret;
  34965. }
  34966. static JSValue js_module_ns_autoinit(JSContext *ctx, JSObject *p, JSAtom atom,
  34967. void *opaque)
  34968. {
  34969. JSModuleDef *m = opaque;
  34970. return JS_GetModuleNamespace(ctx, m);
  34971. }
  34972. static JSValue js_build_module_ns(JSContext *ctx, JSModuleDef *m)
  34973. {
  34974. JSValue obj;
  34975. JSObject *p;
  34976. GetExportNamesState s_s, *s = &s_s;
  34977. int i, ret;
  34978. JSProperty *pr;
  34979. obj = JS_NewObjectClass(ctx, JS_CLASS_MODULE_NS);
  34980. if (JS_IsException(obj))
  34981. return obj;
  34982. p = JS_VALUE_GET_OBJ(obj);
  34983. memset(s, 0, sizeof(*s));
  34984. ret = get_exported_names(ctx, s, m, false);
  34985. js_free(ctx, s->modules);
  34986. if (ret)
  34987. goto fail;
  34988. /* Resolve the exported names. The ambiguous exports are removed */
  34989. for(i = 0; i < s->exported_names_count; i++) {
  34990. ExportedNameEntry *en = &s->exported_names[i];
  34991. JSResolveResultEnum res;
  34992. JSExportEntry *res_me;
  34993. JSModuleDef *res_m;
  34994. if (en->u.me) {
  34995. res_me = en->u.me; /* fast case: no resolution needed */
  34996. res_m = m;
  34997. res = JS_RESOLVE_RES_FOUND;
  34998. } else {
  34999. res = js_resolve_export(ctx, &res_m, &res_me, m,
  35000. en->export_name);
  35001. }
  35002. if (res != JS_RESOLVE_RES_FOUND) {
  35003. if (res != JS_RESOLVE_RES_AMBIGUOUS) {
  35004. js_resolve_export_throw_error(ctx, res, m, en->export_name);
  35005. goto fail;
  35006. }
  35007. en->export_type = EXPORTED_NAME_AMBIGUOUS;
  35008. } else {
  35009. if (res_me->local_name == JS_ATOM__star_) {
  35010. en->export_type = EXPORTED_NAME_NS;
  35011. en->u.module = res_m->req_module_entries[res_me->u.req_module_idx].module;
  35012. } else {
  35013. en->export_type = EXPORTED_NAME_NORMAL;
  35014. if (res_me->u.local.var_ref) {
  35015. en->u.var_ref = res_me->u.local.var_ref;
  35016. } else {
  35017. JSObject *p1 = JS_VALUE_GET_OBJ(res_m->func_obj);
  35018. p1 = JS_VALUE_GET_OBJ(res_m->func_obj);
  35019. en->u.var_ref = p1->u.func.var_refs[res_me->u.local.var_idx];
  35020. }
  35021. }
  35022. }
  35023. }
  35024. /* sort the exported names */
  35025. rqsort(s->exported_names, s->exported_names_count,
  35026. sizeof(s->exported_names[0]), exported_names_cmp, ctx);
  35027. for(i = 0; i < s->exported_names_count; i++) {
  35028. ExportedNameEntry *en = &s->exported_names[i];
  35029. switch(en->export_type) {
  35030. case EXPORTED_NAME_NORMAL:
  35031. {
  35032. JSVarRef *var_ref = en->u.var_ref;
  35033. if (!var_ref) {
  35034. js_resolve_export_throw_error(ctx, JS_RESOLVE_RES_CIRCULAR,
  35035. m, en->export_name);
  35036. goto fail;
  35037. }
  35038. pr = add_property(ctx, p, en->export_name,
  35039. JS_PROP_ENUMERABLE | JS_PROP_WRITABLE |
  35040. JS_PROP_VARREF);
  35041. if (!pr)
  35042. goto fail;
  35043. var_ref->header.ref_count++;
  35044. pr->u.var_ref = var_ref;
  35045. }
  35046. break;
  35047. case EXPORTED_NAME_NS:
  35048. /* the exported namespace must be created on demand */
  35049. if (JS_DefineAutoInitProperty(ctx, obj,
  35050. en->export_name,
  35051. JS_AUTOINIT_ID_MODULE_NS,
  35052. en->u.module, JS_PROP_ENUMERABLE | JS_PROP_WRITABLE) < 0)
  35053. goto fail;
  35054. break;
  35055. default:
  35056. break;
  35057. }
  35058. }
  35059. js_free(ctx, s->exported_names);
  35060. JS_DefinePropertyValue(ctx, obj, JS_ATOM_Symbol_toStringTag,
  35061. JS_AtomToString(ctx, JS_ATOM_Module),
  35062. 0);
  35063. p->extensible = false;
  35064. return obj;
  35065. fail:
  35066. js_free(ctx, s->exported_names);
  35067. JS_FreeValue(ctx, obj);
  35068. return JS_EXCEPTION;
  35069. }
  35070. JSValue JS_GetModuleNamespace(JSContext *ctx, JSModuleDef *m)
  35071. {
  35072. if (JS_IsUndefined(m->module_ns)) {
  35073. JSValue val;
  35074. val = js_build_module_ns(ctx, m);
  35075. if (JS_IsException(val))
  35076. return JS_EXCEPTION;
  35077. m->module_ns = val;
  35078. }
  35079. return js_dup(m->module_ns);
  35080. }
  35081. #ifdef ENABLE_DUMPS // JS_DUMP_MODULE_RESOLVE
  35082. #define module_trace(ctx, ...) \
  35083. do { \
  35084. if (check_dump_flag(ctx->rt, JS_DUMP_MODULE_RESOLVE)) \
  35085. printf(__VA_ARGS__); \
  35086. } while (0)
  35087. #else
  35088. #define module_trace(...)
  35089. #endif
  35090. /* Load all the required modules for module 'm' */
  35091. static int js_resolve_module(JSContext *ctx, JSModuleDef *m)
  35092. {
  35093. int i;
  35094. JSModuleDef *m1;
  35095. if (m->resolved)
  35096. return 0;
  35097. #ifdef ENABLE_DUMPS // JS_DUMP_MODULE_RESOLVE
  35098. if (check_dump_flag(ctx->rt, JS_DUMP_MODULE_RESOLVE)) {
  35099. char buf1[ATOM_GET_STR_BUF_SIZE];
  35100. printf("resolving module '%s':\n", JS_AtomGetStr(ctx, buf1, sizeof(buf1), m->module_name));
  35101. }
  35102. #endif
  35103. m->resolved = true;
  35104. /* resolve each requested module */
  35105. for(i = 0; i < m->req_module_entries_count; i++) {
  35106. JSReqModuleEntry *rme = &m->req_module_entries[i];
  35107. m1 = js_host_resolve_imported_module_atom(ctx, m->module_name,
  35108. rme->module_name);
  35109. if (!m1)
  35110. return -1;
  35111. rme->module = m1;
  35112. /* already done in js_host_resolve_imported_module() except if
  35113. the module was loaded with JS_EvalBinary() */
  35114. if (js_resolve_module(ctx, m1) < 0)
  35115. return -1;
  35116. }
  35117. return 0;
  35118. }
  35119. static JSVarRef *js_create_module_var(JSContext *ctx, bool is_lexical)
  35120. {
  35121. JSVarRef *var_ref;
  35122. var_ref = js_malloc(ctx, sizeof(JSVarRef));
  35123. if (!var_ref)
  35124. return NULL;
  35125. var_ref->header.ref_count = 1;
  35126. if (is_lexical)
  35127. var_ref->value = JS_UNINITIALIZED;
  35128. else
  35129. var_ref->value = JS_UNDEFINED;
  35130. var_ref->pvalue = &var_ref->value;
  35131. var_ref->is_detached = true;
  35132. add_gc_object(ctx->rt, &var_ref->header, JS_GC_OBJ_TYPE_VAR_REF);
  35133. return var_ref;
  35134. }
  35135. /* Create the <eval> function associated with the module */
  35136. static int js_create_module_bytecode_function(JSContext *ctx, JSModuleDef *m)
  35137. {
  35138. JSFunctionBytecode *b;
  35139. int i;
  35140. JSVarRef **var_refs;
  35141. JSValue func_obj, bfunc;
  35142. JSObject *p;
  35143. bfunc = m->func_obj;
  35144. func_obj = JS_NewObjectProtoClass(ctx, ctx->function_proto,
  35145. JS_CLASS_BYTECODE_FUNCTION);
  35146. if (JS_IsException(func_obj))
  35147. return -1;
  35148. b = JS_VALUE_GET_PTR(bfunc);
  35149. p = JS_VALUE_GET_OBJ(func_obj);
  35150. p->u.func.function_bytecode = b;
  35151. b->header.ref_count++;
  35152. p->u.func.home_object = NULL;
  35153. p->u.func.var_refs = NULL;
  35154. if (b->closure_var_count) {
  35155. var_refs = js_mallocz(ctx, sizeof(var_refs[0]) * b->closure_var_count);
  35156. if (!var_refs)
  35157. goto fail;
  35158. p->u.func.var_refs = var_refs;
  35159. /* create the global variables. The other variables are
  35160. imported from other modules */
  35161. for(i = 0; i < b->closure_var_count; i++) {
  35162. JSClosureVar *cv = &b->closure_var[i];
  35163. JSVarRef *var_ref;
  35164. if (cv->is_local) {
  35165. var_ref = js_create_module_var(ctx, cv->is_lexical);
  35166. if (!var_ref)
  35167. goto fail;
  35168. module_trace(ctx, "local %d: %p\n", i, (void *)var_ref);
  35169. var_refs[i] = var_ref;
  35170. }
  35171. }
  35172. }
  35173. m->func_obj = func_obj;
  35174. JS_FreeValue(ctx, bfunc);
  35175. return 0;
  35176. fail:
  35177. JS_FreeValue(ctx, func_obj);
  35178. return -1;
  35179. }
  35180. /* must be done before js_link_module() because of cyclic references */
  35181. static int js_create_module_function(JSContext *ctx, JSModuleDef *m)
  35182. {
  35183. bool is_c_module;
  35184. int i;
  35185. JSVarRef *var_ref;
  35186. if (m->func_created)
  35187. return 0;
  35188. is_c_module = (m->init_func != NULL);
  35189. if (is_c_module) {
  35190. /* initialize the exported variables */
  35191. for(i = 0; i < m->export_entries_count; i++) {
  35192. JSExportEntry *me = &m->export_entries[i];
  35193. if (me->export_type == JS_EXPORT_TYPE_LOCAL) {
  35194. var_ref = js_create_module_var(ctx, false);
  35195. if (!var_ref)
  35196. return -1;
  35197. me->u.local.var_ref = var_ref;
  35198. }
  35199. }
  35200. } else {
  35201. if (js_create_module_bytecode_function(ctx, m))
  35202. return -1;
  35203. }
  35204. m->func_created = true;
  35205. /* do it on the dependencies */
  35206. for(i = 0; i < m->req_module_entries_count; i++) {
  35207. JSReqModuleEntry *rme = &m->req_module_entries[i];
  35208. if (js_create_module_function(ctx, rme->module) < 0)
  35209. return -1;
  35210. }
  35211. return 0;
  35212. }
  35213. /* Prepare a module to be executed by resolving all the imported
  35214. variables. */
  35215. static int js_inner_module_linking(JSContext *ctx, JSModuleDef *m,
  35216. JSModuleDef **pstack_top, int index)
  35217. {
  35218. int i;
  35219. JSImportEntry *mi;
  35220. JSModuleDef *m1;
  35221. JSVarRef **var_refs, *var_ref;
  35222. JSObject *p;
  35223. bool is_c_module;
  35224. JSValue ret_val;
  35225. if (js_check_stack_overflow(ctx->rt, 0)) {
  35226. JS_ThrowStackOverflow(ctx);
  35227. return -1;
  35228. }
  35229. #ifdef ENABLE_DUMPS // JS_DUMP_MODULE_RESOLVE
  35230. if (check_dump_flag(ctx->rt, JS_DUMP_MODULE_RESOLVE)) {
  35231. char buf1[ATOM_GET_STR_BUF_SIZE];
  35232. printf("js_inner_module_linking '%s':\n", JS_AtomGetStr(ctx, buf1, sizeof(buf1), m->module_name));
  35233. }
  35234. #endif
  35235. if (m->status == JS_MODULE_STATUS_LINKING ||
  35236. m->status == JS_MODULE_STATUS_LINKED ||
  35237. m->status == JS_MODULE_STATUS_EVALUATING_ASYNC ||
  35238. m->status == JS_MODULE_STATUS_EVALUATED)
  35239. return index;
  35240. assert(m->status == JS_MODULE_STATUS_UNLINKED);
  35241. m->status = JS_MODULE_STATUS_LINKING;
  35242. m->dfs_index = index;
  35243. m->dfs_ancestor_index = index;
  35244. index++;
  35245. /* push 'm' on stack */
  35246. m->stack_prev = *pstack_top;
  35247. *pstack_top = m;
  35248. for(i = 0; i < m->req_module_entries_count; i++) {
  35249. JSReqModuleEntry *rme = &m->req_module_entries[i];
  35250. m1 = rme->module;
  35251. index = js_inner_module_linking(ctx, m1, pstack_top, index);
  35252. if (index < 0)
  35253. goto fail;
  35254. assert(m1->status == JS_MODULE_STATUS_LINKING ||
  35255. m1->status == JS_MODULE_STATUS_LINKED ||
  35256. m1->status == JS_MODULE_STATUS_EVALUATING_ASYNC ||
  35257. m1->status == JS_MODULE_STATUS_EVALUATED);
  35258. if (m1->status == JS_MODULE_STATUS_LINKING) {
  35259. m->dfs_ancestor_index = min_int(m->dfs_ancestor_index,
  35260. m1->dfs_ancestor_index);
  35261. }
  35262. }
  35263. #ifdef ENABLE_DUMPS // JS_DUMP_MODULE_RESOLVE
  35264. if (check_dump_flag(ctx->rt, JS_DUMP_MODULE_RESOLVE)) {
  35265. char buf1[ATOM_GET_STR_BUF_SIZE];
  35266. printf("instantiating module '%s':\n", JS_AtomGetStr(ctx, buf1, sizeof(buf1), m->module_name));
  35267. }
  35268. #endif
  35269. /* check the indirect exports */
  35270. for(i = 0; i < m->export_entries_count; i++) {
  35271. JSExportEntry *me = &m->export_entries[i];
  35272. if (me->export_type == JS_EXPORT_TYPE_INDIRECT &&
  35273. me->local_name != JS_ATOM__star_) {
  35274. JSResolveResultEnum ret;
  35275. JSExportEntry *res_me;
  35276. JSModuleDef *res_m, *m1;
  35277. m1 = m->req_module_entries[me->u.req_module_idx].module;
  35278. ret = js_resolve_export(ctx, &res_m, &res_me, m1, me->local_name);
  35279. if (ret != JS_RESOLVE_RES_FOUND) {
  35280. js_resolve_export_throw_error(ctx, ret, m, me->export_name);
  35281. goto fail;
  35282. }
  35283. }
  35284. }
  35285. #ifdef ENABLE_DUMPS // JS_DUMP_MODULE_RESOLVE
  35286. if (check_dump_flag(ctx->rt, JS_DUMP_MODULE_RESOLVE)) {
  35287. printf("exported bindings:\n");
  35288. for(i = 0; i < m->export_entries_count; i++) {
  35289. JSExportEntry *me = &m->export_entries[i];
  35290. printf(" name="); print_atom(ctx, me->export_name);
  35291. printf(" local="); print_atom(ctx, me->local_name);
  35292. printf(" type=%d idx=%d\n", me->export_type, me->u.local.var_idx);
  35293. }
  35294. }
  35295. #endif
  35296. is_c_module = (m->init_func != NULL);
  35297. if (!is_c_module) {
  35298. p = JS_VALUE_GET_OBJ(m->func_obj);
  35299. var_refs = p->u.func.var_refs;
  35300. for(i = 0; i < m->import_entries_count; i++) {
  35301. mi = &m->import_entries[i];
  35302. #ifdef ENABLE_DUMPS // JS_DUMP_MODULE_RESOLVE
  35303. if (check_dump_flag(ctx->rt, JS_DUMP_MODULE_RESOLVE)) {
  35304. printf("import var_idx=%d name=", mi->var_idx);
  35305. print_atom(ctx, mi->import_name);
  35306. printf(": ");
  35307. }
  35308. #endif
  35309. m1 = m->req_module_entries[mi->req_module_idx].module;
  35310. if (mi->import_name == JS_ATOM__star_) {
  35311. JSValue val;
  35312. /* name space import */
  35313. val = JS_GetModuleNamespace(ctx, m1);
  35314. if (JS_IsException(val))
  35315. goto fail;
  35316. set_value(ctx, &var_refs[mi->var_idx]->value, val);
  35317. module_trace(ctx, "namespace\n");
  35318. } else {
  35319. JSResolveResultEnum ret;
  35320. JSExportEntry *res_me;
  35321. JSModuleDef *res_m;
  35322. JSObject *p1;
  35323. ret = js_resolve_export(ctx, &res_m,
  35324. &res_me, m1, mi->import_name);
  35325. if (ret != JS_RESOLVE_RES_FOUND) {
  35326. js_resolve_export_throw_error(ctx, ret, m1, mi->import_name);
  35327. goto fail;
  35328. }
  35329. if (res_me->local_name == JS_ATOM__star_) {
  35330. JSValue val;
  35331. JSModuleDef *m2;
  35332. /* name space import from */
  35333. m2 = res_m->req_module_entries[res_me->u.req_module_idx].module;
  35334. val = JS_GetModuleNamespace(ctx, m2);
  35335. if (JS_IsException(val))
  35336. goto fail;
  35337. var_ref = js_create_module_var(ctx, true);
  35338. if (!var_ref) {
  35339. JS_FreeValue(ctx, val);
  35340. goto fail;
  35341. }
  35342. set_value(ctx, &var_ref->value, val);
  35343. var_refs[mi->var_idx] = var_ref;
  35344. module_trace(ctx, "namespace from\n");
  35345. } else {
  35346. var_ref = res_me->u.local.var_ref;
  35347. if (!var_ref) {
  35348. p1 = JS_VALUE_GET_OBJ(res_m->func_obj);
  35349. var_ref = p1->u.func.var_refs[res_me->u.local.var_idx];
  35350. }
  35351. var_ref->header.ref_count++;
  35352. var_refs[mi->var_idx] = var_ref;
  35353. module_trace(ctx, "local export (var_ref=%p)\n", (void *)var_ref);
  35354. }
  35355. }
  35356. }
  35357. /* keep the exported variables in the module export entries (they
  35358. are used when the eval function is deleted and cannot be
  35359. initialized before in case imports are exported) */
  35360. for(i = 0; i < m->export_entries_count; i++) {
  35361. JSExportEntry *me = &m->export_entries[i];
  35362. if (me->export_type == JS_EXPORT_TYPE_LOCAL) {
  35363. var_ref = var_refs[me->u.local.var_idx];
  35364. var_ref->header.ref_count++;
  35365. me->u.local.var_ref = var_ref;
  35366. }
  35367. }
  35368. /* initialize the global variables */
  35369. ret_val = JS_Call(ctx, m->func_obj, JS_TRUE, 0, NULL);
  35370. if (JS_IsException(ret_val))
  35371. goto fail;
  35372. JS_FreeValue(ctx, ret_val);
  35373. }
  35374. assert(m->dfs_ancestor_index <= m->dfs_index);
  35375. if (m->dfs_index == m->dfs_ancestor_index) {
  35376. for(;;) {
  35377. /* pop m1 from stack */
  35378. m1 = *pstack_top;
  35379. *pstack_top = m1->stack_prev;
  35380. m1->status = JS_MODULE_STATUS_LINKED;
  35381. if (m1 == m)
  35382. break;
  35383. }
  35384. }
  35385. #ifdef ENABLE_DUMPS // JS_DUMP_MODULE_RESOLVE
  35386. if (check_dump_flag(ctx->rt, JS_DUMP_MODULE_RESOLVE)) {
  35387. printf("js_inner_module_linking done\n");
  35388. }
  35389. #endif
  35390. return index;
  35391. fail:
  35392. return -1;
  35393. }
  35394. /* Prepare a module to be executed by resolving all the imported
  35395. variables. */
  35396. static int js_link_module(JSContext *ctx, JSModuleDef *m)
  35397. {
  35398. JSModuleDef *stack_top, *m1;
  35399. #ifdef ENABLE_DUMPS // JS_DUMP_MODULE_RESOLVE
  35400. if (check_dump_flag(ctx->rt, JS_DUMP_MODULE_RESOLVE)) {
  35401. char buf1[ATOM_GET_STR_BUF_SIZE];
  35402. printf("js_link_module '%s':\n", JS_AtomGetStr(ctx, buf1, sizeof(buf1), m->module_name));
  35403. }
  35404. #endif
  35405. assert(m->status == JS_MODULE_STATUS_UNLINKED ||
  35406. m->status == JS_MODULE_STATUS_LINKED ||
  35407. m->status == JS_MODULE_STATUS_EVALUATING_ASYNC ||
  35408. m->status == JS_MODULE_STATUS_EVALUATED);
  35409. stack_top = NULL;
  35410. if (js_inner_module_linking(ctx, m, &stack_top, 0) < 0) {
  35411. while (stack_top != NULL) {
  35412. m1 = stack_top;
  35413. assert(m1->status == JS_MODULE_STATUS_LINKING);
  35414. m1->status = JS_MODULE_STATUS_UNLINKED;
  35415. stack_top = m1->stack_prev;
  35416. }
  35417. return -1;
  35418. }
  35419. assert(stack_top == NULL);
  35420. assert(m->status == JS_MODULE_STATUS_LINKED ||
  35421. m->status == JS_MODULE_STATUS_EVALUATING_ASYNC ||
  35422. m->status == JS_MODULE_STATUS_EVALUATED);
  35423. return 0;
  35424. }
  35425. /* return JS_ATOM_NULL if the name cannot be found. Only works with
  35426. not striped bytecode functions. */
  35427. JSAtom JS_GetScriptOrModuleName(JSContext *ctx, int n_stack_levels)
  35428. {
  35429. JSStackFrame *sf;
  35430. JSFunctionBytecode *b;
  35431. JSObject *p;
  35432. /* XXX: currently we just use the filename of the englobing
  35433. function. It does not work for eval(). Need to add a
  35434. ScriptOrModule info in JSFunctionBytecode */
  35435. sf = ctx->rt->current_stack_frame;
  35436. if (!sf)
  35437. return JS_ATOM_NULL;
  35438. while (n_stack_levels-- > 0) {
  35439. sf = sf->prev_frame;
  35440. if (!sf)
  35441. return JS_ATOM_NULL;
  35442. }
  35443. if (JS_VALUE_GET_TAG(sf->cur_func) != JS_TAG_OBJECT)
  35444. return JS_ATOM_NULL;
  35445. p = JS_VALUE_GET_OBJ(sf->cur_func);
  35446. if (!js_class_has_bytecode(p->class_id))
  35447. return JS_ATOM_NULL;
  35448. b = p->u.func.function_bytecode;
  35449. return JS_DupAtom(ctx, b->filename);
  35450. }
  35451. JSAtom JS_GetModuleName(JSContext *ctx, JSModuleDef *m)
  35452. {
  35453. return JS_DupAtom(ctx, m->module_name);
  35454. }
  35455. JSValue JS_GetImportMeta(JSContext *ctx, JSModuleDef *m)
  35456. {
  35457. JSValue obj;
  35458. /* allocate meta_obj only if requested to save memory */
  35459. obj = m->meta_obj;
  35460. if (JS_IsUndefined(obj)) {
  35461. obj = JS_NewObjectProto(ctx, JS_NULL);
  35462. if (JS_IsException(obj))
  35463. return JS_EXCEPTION;
  35464. m->meta_obj = obj;
  35465. }
  35466. return js_dup(obj);
  35467. }
  35468. static JSValue js_import_meta(JSContext *ctx)
  35469. {
  35470. JSAtom filename;
  35471. JSModuleDef *m;
  35472. filename = JS_GetScriptOrModuleName(ctx, 0);
  35473. if (filename == JS_ATOM_NULL)
  35474. goto fail;
  35475. /* XXX: inefficient, need to add a module or script pointer in
  35476. JSFunctionBytecode */
  35477. m = js_find_loaded_module(ctx, filename);
  35478. JS_FreeAtom(ctx, filename);
  35479. if (!m) {
  35480. fail:
  35481. JS_ThrowTypeError(ctx, "import.meta not supported in this context");
  35482. return JS_EXCEPTION;
  35483. }
  35484. return JS_GetImportMeta(ctx, m);
  35485. }
  35486. static JSValue JS_NewModuleValue(JSContext *ctx, JSModuleDef *m)
  35487. {
  35488. return js_dup(JS_MKPTR(JS_TAG_MODULE, m));
  35489. }
  35490. static JSValue js_load_module_rejected(JSContext *ctx, JSValueConst this_val,
  35491. int argc, JSValueConst *argv, int magic,
  35492. JSValueConst *func_data)
  35493. {
  35494. JSValueConst *resolving_funcs = func_data;
  35495. JSValueConst error;
  35496. JSValue ret;
  35497. /* XXX: check if the test is necessary */
  35498. if (argc >= 1)
  35499. error = argv[0];
  35500. else
  35501. error = JS_UNDEFINED;
  35502. ret = JS_Call(ctx, resolving_funcs[1], JS_UNDEFINED, 1, &error);
  35503. JS_FreeValue(ctx, ret);
  35504. return JS_UNDEFINED;
  35505. }
  35506. static JSValue js_load_module_fulfilled(JSContext *ctx, JSValueConst this_val,
  35507. int argc, JSValueConst *argv, int magic,
  35508. JSValueConst *func_data)
  35509. {
  35510. JSValueConst *resolving_funcs = func_data;
  35511. JSModuleDef *m = JS_VALUE_GET_PTR(func_data[2]);
  35512. JSValue ret, ns;
  35513. /* return the module namespace */
  35514. ns = JS_GetModuleNamespace(ctx, m);
  35515. if (JS_IsException(ns)) {
  35516. JSValue err = JS_GetException(ctx);
  35517. js_load_module_rejected(ctx, JS_UNDEFINED, 1, vc(&err), 0, func_data);
  35518. return JS_UNDEFINED;
  35519. }
  35520. ret = JS_Call(ctx, resolving_funcs[0], JS_UNDEFINED, 1, vc(&ns));
  35521. JS_FreeValue(ctx, ret);
  35522. JS_FreeValue(ctx, ns);
  35523. return JS_UNDEFINED;
  35524. }
  35525. static void JS_LoadModuleInternal(JSContext *ctx, const char *basename,
  35526. const char *filename,
  35527. JSValueConst *resolving_funcs)
  35528. {
  35529. JSValue evaluate_promise;
  35530. JSModuleDef *m;
  35531. JSValue ret, err, func_obj, evaluate_resolving_funcs[2];
  35532. JSValueConst func_data[3];
  35533. m = js_host_resolve_imported_module(ctx, basename, filename);
  35534. if (!m)
  35535. goto fail;
  35536. if (js_resolve_module(ctx, m) < 0) {
  35537. js_free_modules(ctx, JS_FREE_MODULE_NOT_RESOLVED);
  35538. goto fail;
  35539. }
  35540. /* Evaluate the module code */
  35541. func_obj = JS_NewModuleValue(ctx, m);
  35542. evaluate_promise = JS_EvalFunction(ctx, func_obj);
  35543. if (JS_IsException(evaluate_promise)) {
  35544. fail:
  35545. err = JS_GetException(ctx);
  35546. ret = JS_Call(ctx, resolving_funcs[1], JS_UNDEFINED, 1, vc(&err));
  35547. JS_FreeValue(ctx, ret); /* XXX: what to do if exception ? */
  35548. JS_FreeValue(ctx, err);
  35549. return;
  35550. }
  35551. func_obj = JS_NewModuleValue(ctx, m);
  35552. func_data[0] = resolving_funcs[0];
  35553. func_data[1] = resolving_funcs[1];
  35554. func_data[2] = func_obj;
  35555. evaluate_resolving_funcs[0] = JS_NewCFunctionData(ctx, js_load_module_fulfilled, 0, 0, 3, func_data);
  35556. evaluate_resolving_funcs[1] = JS_NewCFunctionData(ctx, js_load_module_rejected, 0, 0, 3, func_data);
  35557. JS_FreeValue(ctx, func_obj);
  35558. ret = js_promise_then(ctx, evaluate_promise, 2, vc(evaluate_resolving_funcs));
  35559. JS_FreeValue(ctx, ret);
  35560. JS_FreeValue(ctx, evaluate_resolving_funcs[0]);
  35561. JS_FreeValue(ctx, evaluate_resolving_funcs[1]);
  35562. JS_FreeValue(ctx, evaluate_promise);
  35563. }
  35564. /* Return a promise or an exception in case of memory error. Used by
  35565. os.Worker() */
  35566. JSValue JS_LoadModule(JSContext *ctx, const char *basename,
  35567. const char *filename)
  35568. {
  35569. JSValue promise, resolving_funcs[2];
  35570. promise = JS_NewPromiseCapability(ctx, resolving_funcs);
  35571. if (JS_IsException(promise))
  35572. return JS_EXCEPTION;
  35573. JS_LoadModuleInternal(ctx, basename, filename, vc(resolving_funcs));
  35574. JS_FreeValue(ctx, resolving_funcs[0]);
  35575. JS_FreeValue(ctx, resolving_funcs[1]);
  35576. return promise;
  35577. }
  35578. static JSValue js_dynamic_import_job(JSContext *ctx,
  35579. int argc, JSValueConst *argv)
  35580. {
  35581. JSValueConst *resolving_funcs = argv;
  35582. JSValueConst basename_val = argv[2];
  35583. JSValueConst specifier = argv[3];
  35584. const char *basename = NULL, *filename;
  35585. JSValue ret, err;
  35586. if (!JS_IsString(basename_val)) {
  35587. JS_ThrowTypeError(ctx, "no function filename for import()");
  35588. goto exception;
  35589. }
  35590. basename = JS_ToCString(ctx, basename_val);
  35591. if (!basename)
  35592. goto exception;
  35593. filename = JS_ToCString(ctx, specifier);
  35594. if (!filename)
  35595. goto exception;
  35596. JS_LoadModuleInternal(ctx, basename, filename,
  35597. resolving_funcs);
  35598. JS_FreeCString(ctx, filename);
  35599. JS_FreeCString(ctx, basename);
  35600. return JS_UNDEFINED;
  35601. exception:
  35602. err = JS_GetException(ctx);
  35603. ret = JS_Call(ctx, resolving_funcs[1], JS_UNDEFINED, 1, vc(&err));
  35604. JS_FreeValue(ctx, ret); /* XXX: what to do if exception ? */
  35605. JS_FreeValue(ctx, err);
  35606. JS_FreeCString(ctx, basename);
  35607. return JS_UNDEFINED;
  35608. }
  35609. static JSValue js_dynamic_import(JSContext *ctx, JSValueConst specifier)
  35610. {
  35611. JSAtom basename;
  35612. JSValue promise, resolving_funcs[2], basename_val;
  35613. JSValue args[4];
  35614. basename = JS_GetScriptOrModuleName(ctx, 0);
  35615. if (basename == JS_ATOM_NULL)
  35616. basename_val = JS_NULL;
  35617. else
  35618. basename_val = JS_AtomToValue(ctx, basename);
  35619. JS_FreeAtom(ctx, basename);
  35620. if (JS_IsException(basename_val))
  35621. return basename_val;
  35622. promise = JS_NewPromiseCapability(ctx, resolving_funcs);
  35623. if (JS_IsException(promise)) {
  35624. JS_FreeValue(ctx, basename_val);
  35625. return promise;
  35626. }
  35627. args[0] = resolving_funcs[0];
  35628. args[1] = resolving_funcs[1];
  35629. args[2] = basename_val;
  35630. args[3] = unsafe_unconst(specifier);
  35631. /* cannot run JS_LoadModuleInternal synchronously because it would
  35632. cause an unexpected recursion in js_evaluate_module() */
  35633. JS_EnqueueJob(ctx, js_dynamic_import_job, 4, vc(args));
  35634. JS_FreeValue(ctx, basename_val);
  35635. JS_FreeValue(ctx, resolving_funcs[0]);
  35636. JS_FreeValue(ctx, resolving_funcs[1]);
  35637. return promise;
  35638. }
  35639. static void js_set_module_evaluated(JSContext *ctx, JSModuleDef *m)
  35640. {
  35641. m->status = JS_MODULE_STATUS_EVALUATED;
  35642. if (!JS_IsUndefined(m->promise)) {
  35643. JSValue ret_val;
  35644. assert(m->cycle_root == m);
  35645. JSValueConst value = JS_UNDEFINED;
  35646. ret_val = JS_Call(ctx, m->resolving_funcs[0], JS_UNDEFINED, 1, &value);
  35647. JS_FreeValue(ctx, ret_val);
  35648. }
  35649. }
  35650. typedef struct {
  35651. JSModuleDef **tab;
  35652. int count;
  35653. int size;
  35654. } ExecModuleList;
  35655. /* XXX: slow. Could use a linked list instead of ExecModuleList */
  35656. static bool find_in_exec_module_list(ExecModuleList *exec_list, JSModuleDef *m)
  35657. {
  35658. int i;
  35659. for(i = 0; i < exec_list->count; i++) {
  35660. if (exec_list->tab[i] == m)
  35661. return true;
  35662. }
  35663. return false;
  35664. }
  35665. static int gather_available_ancestors(JSContext *ctx, JSModuleDef *module,
  35666. ExecModuleList *exec_list)
  35667. {
  35668. int i;
  35669. if (js_check_stack_overflow(ctx->rt, 0)) {
  35670. JS_ThrowStackOverflow(ctx);
  35671. return -1;
  35672. }
  35673. for(i = 0; i < module->async_parent_modules_count; i++) {
  35674. JSModuleDef *m = module->async_parent_modules[i];
  35675. if (!find_in_exec_module_list(exec_list, m) &&
  35676. !m->cycle_root->eval_has_exception) {
  35677. assert(m->status == JS_MODULE_STATUS_EVALUATING_ASYNC);
  35678. assert(!m->eval_has_exception);
  35679. assert(m->async_evaluation);
  35680. assert(m->pending_async_dependencies > 0);
  35681. m->pending_async_dependencies--;
  35682. if (m->pending_async_dependencies == 0) {
  35683. if (js_resize_array(ctx, (void **)&exec_list->tab, sizeof(exec_list->tab[0]), &exec_list->size, exec_list->count + 1)) {
  35684. return -1;
  35685. }
  35686. exec_list->tab[exec_list->count++] = m;
  35687. if (!m->has_tla) {
  35688. if (gather_available_ancestors(ctx, m, exec_list))
  35689. return -1;
  35690. }
  35691. }
  35692. }
  35693. }
  35694. return 0;
  35695. }
  35696. static int exec_module_list_cmp(const void *p1, const void *p2, void *opaque)
  35697. {
  35698. JSModuleDef *m1 = *(JSModuleDef **)p1;
  35699. JSModuleDef *m2 = *(JSModuleDef **)p2;
  35700. return (m1->async_evaluation_timestamp > m2->async_evaluation_timestamp) -
  35701. (m1->async_evaluation_timestamp < m2->async_evaluation_timestamp);
  35702. }
  35703. static int js_execute_async_module(JSContext *ctx, JSModuleDef *m);
  35704. static int js_execute_sync_module(JSContext *ctx, JSModuleDef *m,
  35705. JSValue *pvalue);
  35706. static JSValue js_async_module_execution_rejected(JSContext *ctx, JSValueConst this_val,
  35707. int argc, JSValueConst *argv, int magic,
  35708. JSValueConst *func_data)
  35709. {
  35710. JSModuleDef *module = JS_VALUE_GET_PTR(func_data[0]);
  35711. JSValueConst error = argv[0];
  35712. int i;
  35713. if (js_check_stack_overflow(ctx->rt, 0))
  35714. return JS_ThrowStackOverflow(ctx);
  35715. if (module->status == JS_MODULE_STATUS_EVALUATED) {
  35716. assert(module->eval_has_exception);
  35717. return JS_UNDEFINED;
  35718. }
  35719. assert(module->status == JS_MODULE_STATUS_EVALUATING_ASYNC);
  35720. assert(!module->eval_has_exception);
  35721. assert(module->async_evaluation);
  35722. module->eval_has_exception = true;
  35723. module->eval_exception = js_dup(error);
  35724. module->status = JS_MODULE_STATUS_EVALUATED;
  35725. for(i = 0; i < module->async_parent_modules_count; i++) {
  35726. JSModuleDef *m = module->async_parent_modules[i];
  35727. JSValue m_obj = JS_NewModuleValue(ctx, m);
  35728. js_async_module_execution_rejected(ctx, JS_UNDEFINED, 1, &error, 0,
  35729. vc(&m_obj));
  35730. JS_FreeValue(ctx, m_obj);
  35731. }
  35732. if (!JS_IsUndefined(module->promise)) {
  35733. JSValue ret_val;
  35734. assert(module->cycle_root == module);
  35735. ret_val = JS_Call(ctx, module->resolving_funcs[1], JS_UNDEFINED,
  35736. 1, &error);
  35737. JS_FreeValue(ctx, ret_val);
  35738. }
  35739. return JS_UNDEFINED;
  35740. }
  35741. static JSValue js_async_module_execution_fulfilled(JSContext *ctx, JSValueConst this_val,
  35742. int argc, JSValueConst *argv, int magic,
  35743. JSValueConst *func_data)
  35744. {
  35745. JSModuleDef *module = JS_VALUE_GET_PTR(func_data[0]);
  35746. ExecModuleList exec_list_s, *exec_list = &exec_list_s;
  35747. int i;
  35748. if (module->status == JS_MODULE_STATUS_EVALUATED) {
  35749. assert(module->eval_has_exception);
  35750. return JS_UNDEFINED;
  35751. }
  35752. assert(module->status == JS_MODULE_STATUS_EVALUATING_ASYNC);
  35753. assert(!module->eval_has_exception);
  35754. assert(module->async_evaluation);
  35755. module->async_evaluation = false;
  35756. js_set_module_evaluated(ctx, module);
  35757. exec_list->tab = NULL;
  35758. exec_list->count = 0;
  35759. exec_list->size = 0;
  35760. if (gather_available_ancestors(ctx, module, exec_list) < 0) {
  35761. js_free(ctx, exec_list->tab);
  35762. return JS_EXCEPTION;
  35763. }
  35764. /* sort by increasing async_evaluation timestamp */
  35765. rqsort(exec_list->tab, exec_list->count, sizeof(exec_list->tab[0]),
  35766. exec_module_list_cmp, NULL);
  35767. for(i = 0; i < exec_list->count; i++) {
  35768. JSModuleDef *m = exec_list->tab[i];
  35769. if (m->status == JS_MODULE_STATUS_EVALUATED) {
  35770. assert(m->eval_has_exception);
  35771. } else if (m->has_tla) {
  35772. js_execute_async_module(ctx, m);
  35773. } else {
  35774. JSValue error;
  35775. if (js_execute_sync_module(ctx, m, &error) < 0) {
  35776. JSValue m_obj = JS_NewModuleValue(ctx, m);
  35777. js_async_module_execution_rejected(ctx, JS_UNDEFINED,
  35778. 1, vc(&error),
  35779. 0, vc(&m_obj));
  35780. JS_FreeValue(ctx, m_obj);
  35781. JS_FreeValue(ctx, error);
  35782. } else {
  35783. js_set_module_evaluated(ctx, m);
  35784. }
  35785. }
  35786. }
  35787. js_free(ctx, exec_list->tab);
  35788. return JS_UNDEFINED;
  35789. }
  35790. static int js_execute_async_module(JSContext *ctx, JSModuleDef *m)
  35791. {
  35792. JSValue promise, m_obj;
  35793. JSValue resolve_funcs[2], ret_val;
  35794. promise = js_async_function_call(ctx, m->func_obj, JS_UNDEFINED, 0, NULL, 0);
  35795. if (JS_IsException(promise))
  35796. return -1;
  35797. m_obj = JS_NewModuleValue(ctx, m);
  35798. resolve_funcs[0] = JS_NewCFunctionData(ctx, js_async_module_execution_fulfilled, 0, 0, 1, vc(&m_obj));
  35799. resolve_funcs[1] = JS_NewCFunctionData(ctx, js_async_module_execution_rejected, 0, 0, 1, vc(&m_obj));
  35800. ret_val = js_promise_then(ctx, promise, 2, vc(resolve_funcs));
  35801. JS_FreeValue(ctx, ret_val);
  35802. JS_FreeValue(ctx, m_obj);
  35803. JS_FreeValue(ctx, resolve_funcs[0]);
  35804. JS_FreeValue(ctx, resolve_funcs[1]);
  35805. JS_FreeValue(ctx, promise);
  35806. return 0;
  35807. }
  35808. /* return < 0 in case of exception. *pvalue contains the exception. */
  35809. static int js_execute_sync_module(JSContext *ctx, JSModuleDef *m,
  35810. JSValue *pvalue)
  35811. {
  35812. if (m->init_func) {
  35813. /* C module init : no asynchronous execution */
  35814. if (m->init_func(ctx, m) < 0)
  35815. goto fail;
  35816. } else {
  35817. JSValue promise;
  35818. JSPromiseStateEnum state;
  35819. promise = js_async_function_call(ctx, m->func_obj, JS_UNDEFINED, 0, NULL, 0);
  35820. if (JS_IsException(promise))
  35821. goto fail;
  35822. state = JS_PromiseState(ctx, promise);
  35823. if (state == JS_PROMISE_FULFILLED) {
  35824. JS_FreeValue(ctx, promise);
  35825. } else if (state == JS_PROMISE_REJECTED) {
  35826. *pvalue = JS_PromiseResult(ctx, promise);
  35827. JS_FreeValue(ctx, promise);
  35828. return -1;
  35829. } else {
  35830. JS_FreeValue(ctx, promise);
  35831. JS_ThrowTypeError(ctx, "promise is pending");
  35832. fail:
  35833. *pvalue = JS_GetException(ctx);
  35834. return -1;
  35835. }
  35836. }
  35837. *pvalue = JS_UNDEFINED;
  35838. return 0;
  35839. }
  35840. /* spec: InnerModuleEvaluation. Return (index, JS_UNDEFINED) or (-1,
  35841. exception) */
  35842. static int js_inner_module_evaluation(JSContext *ctx, JSModuleDef *m,
  35843. int index, JSModuleDef **pstack_top,
  35844. JSValue *pvalue)
  35845. {
  35846. JSModuleDef *m1;
  35847. int i;
  35848. if (js_check_stack_overflow(ctx->rt, 0)) {
  35849. JS_ThrowStackOverflow(ctx);
  35850. *pvalue = JS_GetException(ctx);
  35851. return -1;
  35852. }
  35853. #ifdef ENABLE_DUMPS // JS_DUMP_MODULE_RESOLVE
  35854. if (check_dump_flag(ctx->rt, JS_DUMP_MODULE_RESOLVE)) {
  35855. char buf1[ATOM_GET_STR_BUF_SIZE];
  35856. printf("js_inner_module_evaluation '%s':\n", JS_AtomGetStr(ctx, buf1, sizeof(buf1), m->module_name));
  35857. }
  35858. #endif
  35859. if (m->status == JS_MODULE_STATUS_EVALUATING_ASYNC ||
  35860. m->status == JS_MODULE_STATUS_EVALUATED) {
  35861. if (m->eval_has_exception) {
  35862. *pvalue = js_dup(m->eval_exception);
  35863. return -1;
  35864. } else {
  35865. *pvalue = JS_UNDEFINED;
  35866. return index;
  35867. }
  35868. }
  35869. if (m->status == JS_MODULE_STATUS_EVALUATING) {
  35870. *pvalue = JS_UNDEFINED;
  35871. return index;
  35872. }
  35873. assert(m->status == JS_MODULE_STATUS_LINKED);
  35874. m->status = JS_MODULE_STATUS_EVALUATING;
  35875. m->dfs_index = index;
  35876. m->dfs_ancestor_index = index;
  35877. m->pending_async_dependencies = 0;
  35878. index++;
  35879. /* push 'm' on stack */
  35880. m->stack_prev = *pstack_top;
  35881. *pstack_top = m;
  35882. for(i = 0; i < m->req_module_entries_count; i++) {
  35883. JSReqModuleEntry *rme = &m->req_module_entries[i];
  35884. m1 = rme->module;
  35885. index = js_inner_module_evaluation(ctx, m1, index, pstack_top, pvalue);
  35886. if (index < 0)
  35887. return -1;
  35888. assert(m1->status == JS_MODULE_STATUS_EVALUATING ||
  35889. m1->status == JS_MODULE_STATUS_EVALUATING_ASYNC ||
  35890. m1->status == JS_MODULE_STATUS_EVALUATED);
  35891. if (m1->status == JS_MODULE_STATUS_EVALUATING) {
  35892. m->dfs_ancestor_index = min_int(m->dfs_ancestor_index,
  35893. m1->dfs_ancestor_index);
  35894. } else {
  35895. m1 = m1->cycle_root;
  35896. assert(m1->status == JS_MODULE_STATUS_EVALUATING_ASYNC ||
  35897. m1->status == JS_MODULE_STATUS_EVALUATED);
  35898. if (m1->eval_has_exception) {
  35899. *pvalue = js_dup(m1->eval_exception);
  35900. return -1;
  35901. }
  35902. }
  35903. if (m1->async_evaluation) {
  35904. m->pending_async_dependencies++;
  35905. if (js_resize_array(ctx, (void **)&m1->async_parent_modules, sizeof(m1->async_parent_modules[0]), &m1->async_parent_modules_size, m1->async_parent_modules_count + 1)) {
  35906. *pvalue = JS_GetException(ctx);
  35907. return -1;
  35908. }
  35909. m1->async_parent_modules[m1->async_parent_modules_count++] = m;
  35910. }
  35911. }
  35912. if (m->pending_async_dependencies > 0) {
  35913. assert(!m->async_evaluation);
  35914. m->async_evaluation = true;
  35915. m->async_evaluation_timestamp =
  35916. ctx->rt->module_async_evaluation_next_timestamp++;
  35917. } else if (m->has_tla) {
  35918. assert(!m->async_evaluation);
  35919. m->async_evaluation = true;
  35920. m->async_evaluation_timestamp =
  35921. ctx->rt->module_async_evaluation_next_timestamp++;
  35922. js_execute_async_module(ctx, m);
  35923. } else {
  35924. if (js_execute_sync_module(ctx, m, pvalue) < 0)
  35925. return -1;
  35926. }
  35927. assert(m->dfs_ancestor_index <= m->dfs_index);
  35928. if (m->dfs_index == m->dfs_ancestor_index) {
  35929. for(;;) {
  35930. /* pop m1 from stack */
  35931. m1 = *pstack_top;
  35932. *pstack_top = m1->stack_prev;
  35933. if (!m1->async_evaluation) {
  35934. m1->status = JS_MODULE_STATUS_EVALUATED;
  35935. } else {
  35936. m1->status = JS_MODULE_STATUS_EVALUATING_ASYNC;
  35937. }
  35938. /* spec bug: cycle_root must be assigned before the test */
  35939. m1->cycle_root = m;
  35940. if (m1 == m)
  35941. break;
  35942. }
  35943. }
  35944. *pvalue = JS_UNDEFINED;
  35945. return index;
  35946. }
  35947. /* Run the <eval> function of the module and of all its requested
  35948. modules. Return a promise or an exception. */
  35949. static JSValue js_evaluate_module(JSContext *ctx, JSModuleDef *m)
  35950. {
  35951. JSModuleDef *m1, *stack_top;
  35952. JSValue ret_val, result;
  35953. assert(m->status == JS_MODULE_STATUS_LINKED ||
  35954. m->status == JS_MODULE_STATUS_EVALUATING_ASYNC ||
  35955. m->status == JS_MODULE_STATUS_EVALUATED);
  35956. if (m->status == JS_MODULE_STATUS_EVALUATING_ASYNC ||
  35957. m->status == JS_MODULE_STATUS_EVALUATED) {
  35958. m = m->cycle_root;
  35959. }
  35960. /* a promise may be created only on the cycle_root of a cycle */
  35961. if (!JS_IsUndefined(m->promise))
  35962. return js_dup(m->promise);
  35963. m->promise = JS_NewPromiseCapability(ctx, m->resolving_funcs);
  35964. if (JS_IsException(m->promise))
  35965. return JS_EXCEPTION;
  35966. stack_top = NULL;
  35967. if (js_inner_module_evaluation(ctx, m, 0, &stack_top, &result) < 0) {
  35968. while (stack_top != NULL) {
  35969. m1 = stack_top;
  35970. assert(m1->status == JS_MODULE_STATUS_EVALUATING);
  35971. m1->status = JS_MODULE_STATUS_EVALUATED;
  35972. m1->eval_has_exception = true;
  35973. m1->eval_exception = js_dup(result);
  35974. m1->cycle_root = m; /* spec bug: should be present */
  35975. stack_top = m1->stack_prev;
  35976. }
  35977. JS_FreeValue(ctx, result);
  35978. assert(m->status == JS_MODULE_STATUS_EVALUATED);
  35979. assert(m->eval_has_exception);
  35980. ret_val = JS_Call(ctx, m->resolving_funcs[1], JS_UNDEFINED,
  35981. 1, vc(&m->eval_exception));
  35982. JS_FreeValue(ctx, ret_val);
  35983. } else {
  35984. assert(m->status == JS_MODULE_STATUS_EVALUATING_ASYNC ||
  35985. m->status == JS_MODULE_STATUS_EVALUATED);
  35986. assert(!m->eval_has_exception);
  35987. if (!m->async_evaluation) {
  35988. assert(m->status == JS_MODULE_STATUS_EVALUATED);
  35989. JSValueConst value = JS_UNDEFINED;
  35990. ret_val = JS_Call(ctx, m->resolving_funcs[0], JS_UNDEFINED,
  35991. 1, &value);
  35992. JS_FreeValue(ctx, ret_val);
  35993. }
  35994. assert(stack_top == NULL);
  35995. }
  35996. return js_dup(m->promise);
  35997. }
  35998. static __exception JSAtom js_parse_from_clause(JSParseState *s)
  35999. {
  36000. JSAtom module_name;
  36001. if (!token_is_pseudo_keyword(s, JS_ATOM_from)) {
  36002. js_parse_error(s, "from clause expected");
  36003. return JS_ATOM_NULL;
  36004. }
  36005. if (next_token(s))
  36006. return JS_ATOM_NULL;
  36007. if (s->token.val != TOK_STRING) {
  36008. js_parse_error(s, "string expected");
  36009. return JS_ATOM_NULL;
  36010. }
  36011. module_name = JS_ValueToAtom(s->ctx, s->token.u.str.str);
  36012. if (module_name == JS_ATOM_NULL)
  36013. return JS_ATOM_NULL;
  36014. if (next_token(s)) {
  36015. JS_FreeAtom(s->ctx, module_name);
  36016. return JS_ATOM_NULL;
  36017. }
  36018. return module_name;
  36019. }
  36020. static __exception int js_parse_export(JSParseState *s)
  36021. {
  36022. JSContext *ctx = s->ctx;
  36023. JSModuleDef *m = s->cur_func->module;
  36024. JSAtom local_name, export_name;
  36025. int first_export, idx, i, tok;
  36026. JSAtom module_name;
  36027. JSExportEntry *me;
  36028. if (next_token(s))
  36029. return -1;
  36030. tok = s->token.val;
  36031. if (tok == TOK_CLASS) {
  36032. return js_parse_class(s, false, JS_PARSE_EXPORT_NAMED);
  36033. } else if (tok == TOK_FUNCTION ||
  36034. (token_is_pseudo_keyword(s, JS_ATOM_async) &&
  36035. peek_token(s, true) == TOK_FUNCTION)) {
  36036. return js_parse_function_decl2(s, JS_PARSE_FUNC_STATEMENT,
  36037. JS_FUNC_NORMAL, JS_ATOM_NULL,
  36038. s->token.ptr,
  36039. s->token.line_num,
  36040. s->token.col_num,
  36041. JS_PARSE_EXPORT_NAMED, NULL);
  36042. }
  36043. if (next_token(s))
  36044. return -1;
  36045. switch(tok) {
  36046. case '{':
  36047. first_export = m->export_entries_count;
  36048. while (s->token.val != '}') {
  36049. if (!token_is_ident(s->token.val)) {
  36050. js_parse_error(s, "identifier expected");
  36051. return -1;
  36052. }
  36053. local_name = JS_DupAtom(ctx, s->token.u.ident.atom);
  36054. export_name = JS_ATOM_NULL;
  36055. if (next_token(s))
  36056. goto fail;
  36057. if (token_is_pseudo_keyword(s, JS_ATOM_as)) {
  36058. if (next_token(s))
  36059. goto fail;
  36060. if (!token_is_ident(s->token.val)) {
  36061. js_parse_error(s, "identifier expected");
  36062. goto fail;
  36063. }
  36064. export_name = JS_DupAtom(ctx, s->token.u.ident.atom);
  36065. if (next_token(s)) {
  36066. fail:
  36067. JS_FreeAtom(ctx, local_name);
  36068. fail1:
  36069. JS_FreeAtom(ctx, export_name);
  36070. return -1;
  36071. }
  36072. } else {
  36073. export_name = JS_DupAtom(ctx, local_name);
  36074. }
  36075. me = add_export_entry(s, m, local_name, export_name,
  36076. JS_EXPORT_TYPE_LOCAL);
  36077. JS_FreeAtom(ctx, local_name);
  36078. JS_FreeAtom(ctx, export_name);
  36079. if (!me)
  36080. return -1;
  36081. if (s->token.val != ',')
  36082. break;
  36083. if (next_token(s))
  36084. return -1;
  36085. }
  36086. if (js_parse_expect(s, '}'))
  36087. return -1;
  36088. if (token_is_pseudo_keyword(s, JS_ATOM_from)) {
  36089. module_name = js_parse_from_clause(s);
  36090. if (module_name == JS_ATOM_NULL)
  36091. return -1;
  36092. idx = add_req_module_entry(ctx, m, module_name);
  36093. JS_FreeAtom(ctx, module_name);
  36094. if (idx < 0)
  36095. return -1;
  36096. for(i = first_export; i < m->export_entries_count; i++) {
  36097. me = &m->export_entries[i];
  36098. me->export_type = JS_EXPORT_TYPE_INDIRECT;
  36099. me->u.req_module_idx = idx;
  36100. }
  36101. }
  36102. break;
  36103. case '*':
  36104. if (token_is_pseudo_keyword(s, JS_ATOM_as)) {
  36105. /* export ns from */
  36106. if (next_token(s))
  36107. return -1;
  36108. if (!token_is_ident(s->token.val)) {
  36109. js_parse_error(s, "identifier expected");
  36110. return -1;
  36111. }
  36112. export_name = JS_DupAtom(ctx, s->token.u.ident.atom);
  36113. if (next_token(s))
  36114. goto fail1;
  36115. module_name = js_parse_from_clause(s);
  36116. if (module_name == JS_ATOM_NULL)
  36117. goto fail1;
  36118. idx = add_req_module_entry(ctx, m, module_name);
  36119. JS_FreeAtom(ctx, module_name);
  36120. if (idx < 0)
  36121. goto fail1;
  36122. me = add_export_entry(s, m, JS_ATOM__star_, export_name,
  36123. JS_EXPORT_TYPE_INDIRECT);
  36124. JS_FreeAtom(ctx, export_name);
  36125. if (!me)
  36126. return -1;
  36127. me->u.req_module_idx = idx;
  36128. } else {
  36129. module_name = js_parse_from_clause(s);
  36130. if (module_name == JS_ATOM_NULL)
  36131. return -1;
  36132. idx = add_req_module_entry(ctx, m, module_name);
  36133. JS_FreeAtom(ctx, module_name);
  36134. if (idx < 0)
  36135. return -1;
  36136. if (add_star_export_entry(ctx, m, idx) < 0)
  36137. return -1;
  36138. }
  36139. break;
  36140. case TOK_DEFAULT:
  36141. if (s->token.val == TOK_CLASS) {
  36142. return js_parse_class(s, false, JS_PARSE_EXPORT_DEFAULT);
  36143. } else if (s->token.val == TOK_FUNCTION ||
  36144. (token_is_pseudo_keyword(s, JS_ATOM_async) &&
  36145. peek_token(s, true) == TOK_FUNCTION)) {
  36146. return js_parse_function_decl2(s, JS_PARSE_FUNC_STATEMENT,
  36147. JS_FUNC_NORMAL, JS_ATOM_NULL,
  36148. s->token.ptr,
  36149. s->token.line_num,
  36150. s->token.col_num,
  36151. JS_PARSE_EXPORT_DEFAULT, NULL);
  36152. } else {
  36153. if (js_parse_assign_expr(s))
  36154. return -1;
  36155. }
  36156. /* set the name of anonymous functions */
  36157. set_object_name(s, JS_ATOM_default);
  36158. /* store the value in the _default_ global variable and export
  36159. it */
  36160. local_name = JS_ATOM__default_;
  36161. if (define_var(s, s->cur_func, local_name, JS_VAR_DEF_LET) < 0)
  36162. return -1;
  36163. emit_op(s, OP_scope_put_var_init);
  36164. emit_atom(s, local_name);
  36165. emit_u16(s, 0);
  36166. if (!add_export_entry(s, m, local_name, JS_ATOM_default,
  36167. JS_EXPORT_TYPE_LOCAL))
  36168. return -1;
  36169. break;
  36170. case TOK_VAR:
  36171. case TOK_LET:
  36172. case TOK_CONST:
  36173. return js_parse_var(s, PF_IN_ACCEPTED, tok, /*export_flag*/true);
  36174. default:
  36175. return js_parse_error(s, "invalid export syntax");
  36176. }
  36177. return js_parse_expect_semi(s);
  36178. }
  36179. static int add_closure_var(JSContext *ctx, JSFunctionDef *s,
  36180. bool is_local, bool is_arg,
  36181. int var_idx, JSAtom var_name,
  36182. bool is_const, bool is_lexical,
  36183. JSVarKindEnum var_kind);
  36184. static int add_import(JSParseState *s, JSModuleDef *m,
  36185. JSAtom local_name, JSAtom import_name)
  36186. {
  36187. JSContext *ctx = s->ctx;
  36188. int i, var_idx;
  36189. JSImportEntry *mi;
  36190. bool is_local;
  36191. if (local_name == JS_ATOM_arguments || local_name == JS_ATOM_eval)
  36192. return js_parse_error(s, "invalid import binding");
  36193. if (local_name != JS_ATOM_default) {
  36194. for (i = 0; i < s->cur_func->closure_var_count; i++) {
  36195. if (s->cur_func->closure_var[i].var_name == local_name)
  36196. return js_parse_error(s, "duplicate import binding");
  36197. }
  36198. }
  36199. is_local = (import_name == JS_ATOM__star_);
  36200. var_idx = add_closure_var(ctx, s->cur_func, is_local, false,
  36201. m->import_entries_count,
  36202. local_name, true, true, JS_VAR_NORMAL);
  36203. if (var_idx < 0)
  36204. return -1;
  36205. if (js_resize_array(ctx, (void **)&m->import_entries,
  36206. sizeof(JSImportEntry),
  36207. &m->import_entries_size,
  36208. m->import_entries_count + 1))
  36209. return -1;
  36210. mi = &m->import_entries[m->import_entries_count++];
  36211. mi->import_name = JS_DupAtom(ctx, import_name);
  36212. mi->var_idx = var_idx;
  36213. return 0;
  36214. }
  36215. static __exception int js_parse_import(JSParseState *s)
  36216. {
  36217. JSContext *ctx = s->ctx;
  36218. JSModuleDef *m = s->cur_func->module;
  36219. JSAtom local_name, import_name, module_name;
  36220. int first_import, i, idx;
  36221. if (next_token(s))
  36222. return -1;
  36223. first_import = m->import_entries_count;
  36224. if (s->token.val == TOK_STRING) {
  36225. module_name = JS_ValueToAtom(ctx, s->token.u.str.str);
  36226. if (module_name == JS_ATOM_NULL)
  36227. return -1;
  36228. if (next_token(s)) {
  36229. JS_FreeAtom(ctx, module_name);
  36230. return -1;
  36231. }
  36232. } else {
  36233. if (s->token.val == TOK_IDENT) {
  36234. if (s->token.u.ident.is_reserved) {
  36235. return js_parse_error_reserved_identifier(s);
  36236. }
  36237. /* "default" import */
  36238. local_name = JS_DupAtom(ctx, s->token.u.ident.atom);
  36239. import_name = JS_ATOM_default;
  36240. if (next_token(s))
  36241. goto fail;
  36242. if (add_import(s, m, local_name, import_name))
  36243. goto fail;
  36244. JS_FreeAtom(ctx, local_name);
  36245. if (s->token.val != ',')
  36246. goto end_import_clause;
  36247. if (next_token(s))
  36248. return -1;
  36249. }
  36250. if (s->token.val == '*') {
  36251. /* name space import */
  36252. if (next_token(s))
  36253. return -1;
  36254. if (!token_is_pseudo_keyword(s, JS_ATOM_as))
  36255. return js_parse_error(s, "expecting 'as'");
  36256. if (next_token(s))
  36257. return -1;
  36258. if (!token_is_ident(s->token.val)) {
  36259. js_parse_error(s, "identifier expected");
  36260. return -1;
  36261. }
  36262. local_name = JS_DupAtom(ctx, s->token.u.ident.atom);
  36263. import_name = JS_ATOM__star_;
  36264. if (next_token(s))
  36265. goto fail;
  36266. if (add_import(s, m, local_name, import_name))
  36267. goto fail;
  36268. JS_FreeAtom(ctx, local_name);
  36269. } else if (s->token.val == '{') {
  36270. if (next_token(s))
  36271. return -1;
  36272. while (s->token.val != '}') {
  36273. if (!token_is_ident(s->token.val)) {
  36274. js_parse_error(s, "identifier expected");
  36275. return -1;
  36276. }
  36277. import_name = JS_DupAtom(ctx, s->token.u.ident.atom);
  36278. local_name = JS_ATOM_NULL;
  36279. if (next_token(s))
  36280. goto fail;
  36281. if (token_is_pseudo_keyword(s, JS_ATOM_as)) {
  36282. if (next_token(s))
  36283. goto fail;
  36284. if (!token_is_ident(s->token.val)) {
  36285. js_parse_error(s, "identifier expected");
  36286. goto fail;
  36287. }
  36288. local_name = JS_DupAtom(ctx, s->token.u.ident.atom);
  36289. if (next_token(s)) {
  36290. fail:
  36291. JS_FreeAtom(ctx, local_name);
  36292. JS_FreeAtom(ctx, import_name);
  36293. return -1;
  36294. }
  36295. } else {
  36296. local_name = JS_DupAtom(ctx, import_name);
  36297. }
  36298. if (add_import(s, m, local_name, import_name))
  36299. goto fail;
  36300. JS_FreeAtom(ctx, local_name);
  36301. JS_FreeAtom(ctx, import_name);
  36302. if (s->token.val != ',')
  36303. break;
  36304. if (next_token(s))
  36305. return -1;
  36306. }
  36307. if (js_parse_expect(s, '}'))
  36308. return -1;
  36309. }
  36310. end_import_clause:
  36311. module_name = js_parse_from_clause(s);
  36312. if (module_name == JS_ATOM_NULL)
  36313. return -1;
  36314. }
  36315. idx = add_req_module_entry(ctx, m, module_name);
  36316. JS_FreeAtom(ctx, module_name);
  36317. if (idx < 0)
  36318. return -1;
  36319. for(i = first_import; i < m->import_entries_count; i++)
  36320. m->import_entries[i].req_module_idx = idx;
  36321. return js_parse_expect_semi(s);
  36322. }
  36323. static __exception int js_parse_source_element(JSParseState *s)
  36324. {
  36325. JSFunctionDef *fd = s->cur_func;
  36326. int tok;
  36327. if (s->token.val == TOK_FUNCTION ||
  36328. (token_is_pseudo_keyword(s, JS_ATOM_async) &&
  36329. peek_token(s, true) == TOK_FUNCTION)) {
  36330. if (js_parse_function_decl(s, JS_PARSE_FUNC_STATEMENT,
  36331. JS_FUNC_NORMAL, JS_ATOM_NULL,
  36332. s->token.ptr,
  36333. s->token.line_num,
  36334. s->token.col_num))
  36335. return -1;
  36336. } else if (s->token.val == TOK_EXPORT && fd->module) {
  36337. if (js_parse_export(s))
  36338. return -1;
  36339. } else if (s->token.val == TOK_IMPORT && fd->module &&
  36340. ((tok = peek_token(s, false)) != '(' && tok != '.')) {
  36341. /* the peek_token is needed to avoid confusion with ImportCall
  36342. (dynamic import) or import.meta */
  36343. if (js_parse_import(s))
  36344. return -1;
  36345. } else {
  36346. if (js_parse_statement_or_decl(s, DECL_MASK_ALL))
  36347. return -1;
  36348. }
  36349. return 0;
  36350. }
  36351. /* `filename` may be pure ASCII or UTF-8 encoded */
  36352. static JSFunctionDef *js_new_function_def(JSContext *ctx,
  36353. JSFunctionDef *parent,
  36354. bool is_eval,
  36355. bool is_func_expr,
  36356. const char *filename,
  36357. int line_num,
  36358. int col_num)
  36359. {
  36360. JSFunctionDef *fd;
  36361. fd = js_mallocz(ctx, sizeof(*fd));
  36362. if (!fd)
  36363. return NULL;
  36364. fd->ctx = ctx;
  36365. init_list_head(&fd->child_list);
  36366. /* insert in parent list */
  36367. fd->parent = parent;
  36368. fd->parent_cpool_idx = -1;
  36369. if (parent) {
  36370. list_add_tail(&fd->link, &parent->child_list);
  36371. fd->is_strict_mode = parent->is_strict_mode;
  36372. fd->parent_scope_level = parent->scope_level;
  36373. }
  36374. fd->is_eval = is_eval;
  36375. fd->is_func_expr = is_func_expr;
  36376. js_dbuf_init(ctx, &fd->byte_code);
  36377. fd->last_opcode_pos = -1;
  36378. fd->func_name = JS_ATOM_NULL;
  36379. fd->var_object_idx = -1;
  36380. fd->arg_var_object_idx = -1;
  36381. fd->arguments_var_idx = -1;
  36382. fd->arguments_arg_idx = -1;
  36383. fd->func_var_idx = -1;
  36384. fd->eval_ret_idx = -1;
  36385. fd->this_var_idx = -1;
  36386. fd->new_target_var_idx = -1;
  36387. fd->this_active_func_var_idx = -1;
  36388. fd->home_object_var_idx = -1;
  36389. /* XXX: should distinguish arg, var and var object and body scopes */
  36390. fd->scopes = fd->def_scope_array;
  36391. fd->scope_size = countof(fd->def_scope_array);
  36392. fd->scope_count = 1;
  36393. fd->scopes[0].first = -1;
  36394. fd->scopes[0].parent = -1;
  36395. fd->scope_level = 0; /* 0: var/arg scope */
  36396. fd->scope_first = -1;
  36397. fd->body_scope = -1;
  36398. fd->filename = JS_NewAtom(ctx, filename);
  36399. fd->line_num = line_num;
  36400. fd->col_num = col_num;
  36401. js_dbuf_init(ctx, &fd->pc2line);
  36402. //fd->pc2line_last_line_num = line_num;
  36403. //fd->pc2line_last_pc = 0;
  36404. return fd;
  36405. }
  36406. static void free_bytecode_atoms(JSRuntime *rt,
  36407. const uint8_t *bc_buf, int bc_len,
  36408. bool use_short_opcodes)
  36409. {
  36410. int pos, len, op;
  36411. JSAtom atom;
  36412. const JSOpCode *oi;
  36413. pos = 0;
  36414. while (pos < bc_len) {
  36415. op = bc_buf[pos];
  36416. if (use_short_opcodes)
  36417. oi = &short_opcode_info(op);
  36418. else
  36419. oi = &opcode_info[op];
  36420. len = oi->size;
  36421. switch(oi->fmt) {
  36422. case OP_FMT_atom:
  36423. case OP_FMT_atom_u8:
  36424. case OP_FMT_atom_u16:
  36425. case OP_FMT_atom_label_u8:
  36426. case OP_FMT_atom_label_u16:
  36427. atom = get_u32(bc_buf + pos + 1);
  36428. JS_FreeAtomRT(rt, atom);
  36429. break;
  36430. default:
  36431. break;
  36432. }
  36433. pos += len;
  36434. }
  36435. }
  36436. static void js_free_function_def(JSContext *ctx, JSFunctionDef *fd)
  36437. {
  36438. int i;
  36439. struct list_head *el, *el1;
  36440. /* free the child functions */
  36441. list_for_each_safe(el, el1, &fd->child_list) {
  36442. JSFunctionDef *fd1;
  36443. fd1 = list_entry(el, JSFunctionDef, link);
  36444. js_free_function_def(ctx, fd1);
  36445. }
  36446. free_bytecode_atoms(ctx->rt, fd->byte_code.buf, fd->byte_code.size,
  36447. fd->use_short_opcodes);
  36448. dbuf_free(&fd->byte_code);
  36449. js_free(ctx, fd->jump_slots);
  36450. js_free(ctx, fd->label_slots);
  36451. js_free(ctx, fd->source_loc_slots);
  36452. for(i = 0; i < fd->cpool_count; i++) {
  36453. JS_FreeValue(ctx, fd->cpool[i]);
  36454. }
  36455. js_free(ctx, fd->cpool);
  36456. JS_FreeAtom(ctx, fd->func_name);
  36457. for(i = 0; i < fd->var_count; i++) {
  36458. JS_FreeAtom(ctx, fd->vars[i].var_name);
  36459. }
  36460. js_free(ctx, fd->vars);
  36461. js_free(ctx, fd->vars_htab); // XXX can probably be freed earlier?
  36462. for(i = 0; i < fd->arg_count; i++) {
  36463. JS_FreeAtom(ctx, fd->args[i].var_name);
  36464. }
  36465. js_free(ctx, fd->args);
  36466. for(i = 0; i < fd->global_var_count; i++) {
  36467. JS_FreeAtom(ctx, fd->global_vars[i].var_name);
  36468. }
  36469. js_free(ctx, fd->global_vars);
  36470. for(i = 0; i < fd->closure_var_count; i++) {
  36471. JSClosureVar *cv = &fd->closure_var[i];
  36472. JS_FreeAtom(ctx, cv->var_name);
  36473. }
  36474. js_free(ctx, fd->closure_var);
  36475. if (fd->scopes != fd->def_scope_array)
  36476. js_free(ctx, fd->scopes);
  36477. JS_FreeAtom(ctx, fd->filename);
  36478. dbuf_free(&fd->pc2line);
  36479. js_free(ctx, fd->source);
  36480. if (fd->parent) {
  36481. /* remove in parent list */
  36482. list_del(&fd->link);
  36483. }
  36484. js_free(ctx, fd);
  36485. }
  36486. #ifdef ENABLE_DUMPS // JS_DUMP_BYTECODE_*
  36487. static const char *skip_lines(const char *p, int n) {
  36488. while (p && n-- > 0 && *p) {
  36489. while (*p && *p++ != '\n')
  36490. continue;
  36491. }
  36492. return p;
  36493. }
  36494. static void print_lines(const char *source, int line, int line1) {
  36495. const char *s = source;
  36496. const char *p = skip_lines(s, line);
  36497. if (p && *p) {
  36498. while (line++ < line1) {
  36499. p = skip_lines(s = p, 1);
  36500. printf(";; %.*s", (int)(p - s), s);
  36501. if (!*p) {
  36502. if (p[-1] != '\n')
  36503. printf("\n");
  36504. break;
  36505. }
  36506. }
  36507. }
  36508. }
  36509. static void dump_byte_code(JSContext *ctx, int pass,
  36510. const uint8_t *tab, int len,
  36511. const JSVarDef *args, int arg_count,
  36512. const JSVarDef *vars, int var_count,
  36513. const JSClosureVar *closure_var, int closure_var_count,
  36514. const JSValue *cpool, uint32_t cpool_count,
  36515. const char *source, int line_num,
  36516. const LabelSlot *label_slots, JSFunctionBytecode *b,
  36517. int start_pos)
  36518. {
  36519. const JSOpCode *oi;
  36520. int pos, pos_next, op, size, idx, addr, line, line1, in_source;
  36521. uint8_t *bits = js_mallocz(ctx, len * sizeof(*bits));
  36522. bool use_short_opcodes = (b != NULL);
  36523. if (start_pos != 0 || bits == NULL)
  36524. goto no_labels;
  36525. /* scan for jump targets */
  36526. for (pos = 0; pos < len; pos = pos_next) {
  36527. op = tab[pos];
  36528. if (use_short_opcodes)
  36529. oi = &short_opcode_info(op);
  36530. else
  36531. oi = &opcode_info[op];
  36532. pos_next = pos + oi->size;
  36533. if (op < OP_COUNT) {
  36534. switch (oi->fmt) {
  36535. case OP_FMT_label8:
  36536. pos++;
  36537. addr = (int8_t)tab[pos];
  36538. goto has_addr;
  36539. case OP_FMT_label16:
  36540. pos++;
  36541. addr = (int16_t)get_u16(tab + pos);
  36542. goto has_addr;
  36543. case OP_FMT_atom_label_u8:
  36544. case OP_FMT_atom_label_u16:
  36545. pos += 4;
  36546. /* fall thru */
  36547. case OP_FMT_label:
  36548. case OP_FMT_label_u16:
  36549. pos++;
  36550. addr = get_u32(tab + pos);
  36551. goto has_addr;
  36552. has_addr:
  36553. if (pass == 1)
  36554. addr = label_slots[addr].pos;
  36555. if (pass == 2)
  36556. addr = label_slots[addr].pos2;
  36557. if (pass == 3)
  36558. addr += pos;
  36559. if (addr >= 0 && addr < len)
  36560. bits[addr] |= 1;
  36561. break;
  36562. }
  36563. }
  36564. }
  36565. no_labels:
  36566. in_source = 0;
  36567. if (source) {
  36568. /* Always print first line: needed if single line */
  36569. print_lines(source, 0, 1);
  36570. in_source = 1;
  36571. }
  36572. line1 = line = 1;
  36573. pos = 0;
  36574. while (pos < len) {
  36575. op = tab[pos];
  36576. if (source) {
  36577. if (b) {
  36578. int col1;
  36579. line1 = find_line_num(ctx, b, pos, &col1) - line_num + 1;
  36580. } else if (op == OP_source_loc) {
  36581. line1 = get_u32(tab + pos + 1) - line_num + 1;
  36582. }
  36583. if (line1 > line) {
  36584. if (!in_source)
  36585. printf("\n");
  36586. in_source = 1;
  36587. print_lines(source, line, line1);
  36588. line = line1;
  36589. //bits[pos] |= 2;
  36590. }
  36591. }
  36592. if (in_source)
  36593. printf("\n");
  36594. in_source = 0;
  36595. if (op >= OP_COUNT) {
  36596. printf("invalid opcode (0x%02x)\n", op);
  36597. pos++;
  36598. continue;
  36599. }
  36600. if (use_short_opcodes)
  36601. oi = &short_opcode_info(op);
  36602. else
  36603. oi = &opcode_info[op];
  36604. size = oi->size;
  36605. if (pos + size > len) {
  36606. printf("truncated opcode (0x%02x)\n", op);
  36607. break;
  36608. }
  36609. #ifdef ENABLE_DUMPS // JS_DUMP_BYTECODE_HEX
  36610. if (check_dump_flag(ctx->rt, JS_DUMP_BYTECODE_HEX)) {
  36611. int i, x, x0;
  36612. x = x0 = printf("%5d ", pos);
  36613. for (i = 0; i < size; i++) {
  36614. if (i == 6) {
  36615. printf("\n%*s", x = x0, "");
  36616. }
  36617. x += printf(" %02X", tab[pos + i]);
  36618. }
  36619. printf("%*s", x0 + 20 - x, "");
  36620. }
  36621. #endif
  36622. if (bits && bits[pos]) {
  36623. printf("%5d: ", pos);
  36624. } else {
  36625. printf(" ");
  36626. }
  36627. printf("%-15s", oi->name); /* align opcode arguments */
  36628. pos++;
  36629. switch(oi->fmt) {
  36630. case OP_FMT_none_int:
  36631. printf(" %d", op - OP_push_0);
  36632. break;
  36633. case OP_FMT_npopx:
  36634. printf(" %d", op - OP_call0);
  36635. break;
  36636. case OP_FMT_u8:
  36637. printf(" %u", get_u8(tab + pos));
  36638. break;
  36639. case OP_FMT_i8:
  36640. printf(" %d", get_i8(tab + pos));
  36641. break;
  36642. case OP_FMT_u16:
  36643. case OP_FMT_npop:
  36644. printf(" %u", get_u16(tab + pos));
  36645. break;
  36646. case OP_FMT_npop_u16:
  36647. printf(" %u,%u", get_u16(tab + pos), get_u16(tab + pos + 2));
  36648. break;
  36649. case OP_FMT_i16:
  36650. printf(" %d", get_i16(tab + pos));
  36651. break;
  36652. case OP_FMT_i32:
  36653. printf(" %d", get_i32(tab + pos));
  36654. break;
  36655. case OP_FMT_u32:
  36656. printf(" %u", get_u32(tab + pos));
  36657. break;
  36658. case OP_FMT_u32x2:
  36659. printf(" %u:%u", get_u32(tab + pos), get_u32(tab + pos + 4));
  36660. break;
  36661. case OP_FMT_label8:
  36662. addr = get_i8(tab + pos);
  36663. goto has_addr1;
  36664. case OP_FMT_label16:
  36665. addr = get_i16(tab + pos);
  36666. goto has_addr1;
  36667. case OP_FMT_label:
  36668. case OP_FMT_label_u16:
  36669. addr = get_u32(tab + pos);
  36670. has_addr1:
  36671. if (pass == 1)
  36672. printf(" %d:%u", addr, label_slots[addr].pos);
  36673. if (pass == 2)
  36674. printf(" %d:%u", addr, label_slots[addr].pos2);
  36675. if (pass == 3) {
  36676. if (start_pos)
  36677. printf(" %04x", addr + pos + start_pos);
  36678. else
  36679. printf(" %d", addr + pos);
  36680. }
  36681. if (oi->fmt == OP_FMT_label_u16)
  36682. printf(",%u", get_u16(tab + pos + 4));
  36683. break;
  36684. case OP_FMT_const8:
  36685. idx = get_u8(tab + pos);
  36686. goto has_pool_idx;
  36687. case OP_FMT_const:
  36688. idx = get_u32(tab + pos);
  36689. goto has_pool_idx;
  36690. has_pool_idx:
  36691. printf(" %-4u ; ", idx);
  36692. if (idx < cpool_count) {
  36693. JS_DumpValue(ctx->rt, cpool[idx]);
  36694. }
  36695. break;
  36696. case OP_FMT_atom:
  36697. printf(" ");
  36698. print_atom(ctx, get_u32(tab + pos));
  36699. break;
  36700. case OP_FMT_atom_u8:
  36701. printf(" ");
  36702. print_atom(ctx, get_u32(tab + pos));
  36703. printf(",%d", get_u8(tab + pos + 4));
  36704. break;
  36705. case OP_FMT_atom_u16:
  36706. printf(" ");
  36707. print_atom(ctx, get_u32(tab + pos));
  36708. printf(",%d", get_u16(tab + pos + 4));
  36709. break;
  36710. case OP_FMT_atom_label_u8:
  36711. case OP_FMT_atom_label_u16:
  36712. printf(" ");
  36713. print_atom(ctx, get_u32(tab + pos));
  36714. addr = get_u32(tab + pos + 4);
  36715. if (pass == 1)
  36716. printf(",%u:%u", addr, label_slots[addr].pos);
  36717. if (pass == 2)
  36718. printf(",%u:%u", addr, label_slots[addr].pos2);
  36719. if (pass == 3)
  36720. printf(",%u", addr + pos + 4);
  36721. if (oi->fmt == OP_FMT_atom_label_u8)
  36722. printf(",%u", get_u8(tab + pos + 8));
  36723. else
  36724. printf(",%u", get_u16(tab + pos + 8));
  36725. break;
  36726. case OP_FMT_none_loc:
  36727. if (op == OP_get_loc0_loc1) {
  36728. printf(" 0, 1 ; ");
  36729. if (var_count > 0)
  36730. print_atom(ctx, vars[0].var_name);
  36731. if (var_count > 1)
  36732. print_atom(ctx, vars[1].var_name);
  36733. } else {
  36734. idx = (op - OP_get_loc0) % 4;
  36735. goto has_loc;
  36736. }
  36737. break;
  36738. case OP_FMT_loc8:
  36739. idx = get_u8(tab + pos);
  36740. goto has_loc;
  36741. case OP_FMT_loc:
  36742. idx = get_u16(tab + pos);
  36743. has_loc:
  36744. printf(" %-4d ; ", idx);
  36745. if (idx < var_count) {
  36746. print_atom(ctx, vars[idx].var_name);
  36747. }
  36748. break;
  36749. case OP_FMT_none_arg:
  36750. idx = (op - OP_get_arg0) % 4;
  36751. goto has_arg;
  36752. case OP_FMT_arg:
  36753. idx = get_u16(tab + pos);
  36754. has_arg:
  36755. printf(" %-4d ; ", idx);
  36756. if (idx < arg_count) {
  36757. print_atom(ctx, args[idx].var_name);
  36758. }
  36759. break;
  36760. case OP_FMT_none_var_ref:
  36761. idx = (op - OP_get_var_ref0) % 4;
  36762. goto has_var_ref;
  36763. case OP_FMT_var_ref:
  36764. idx = get_u16(tab + pos);
  36765. has_var_ref:
  36766. printf(" %-4d ; ", idx);
  36767. if (idx < closure_var_count) {
  36768. print_atom(ctx, closure_var[idx].var_name);
  36769. }
  36770. break;
  36771. default:
  36772. break;
  36773. }
  36774. printf("\n");
  36775. pos += oi->size - 1;
  36776. }
  36777. if (source) {
  36778. if (!in_source)
  36779. printf("\n");
  36780. print_lines(source, line, INT32_MAX);
  36781. }
  36782. js_free(ctx, bits);
  36783. }
  36784. // caveat emptor: intended to be called during execution of bytecode
  36785. // and only works for pass3 bytecode
  36786. static __maybe_unused void dump_single_byte_code(JSContext *ctx,
  36787. const uint8_t *pc,
  36788. JSFunctionBytecode *b,
  36789. int start_pos)
  36790. {
  36791. JSVarDef *args, *vars;
  36792. args = vars = b->vardefs;
  36793. if (vars)
  36794. vars = &vars[b->arg_count];
  36795. dump_byte_code(ctx, /*pass*/3, pc, short_opcode_info(*pc).size,
  36796. args, b->arg_count, vars, b->var_count,
  36797. b->closure_var, b->closure_var_count,
  36798. b->cpool, b->cpool_count,
  36799. NULL, b->line_num,
  36800. NULL, b, start_pos);
  36801. }
  36802. static __maybe_unused void print_func_name(JSFunctionBytecode *b)
  36803. {
  36804. print_lines(b->source, 0, 1);
  36805. }
  36806. static __maybe_unused void dump_pc2line(JSContext *ctx,
  36807. const uint8_t *buf, int len,
  36808. int line_num, int col_num)
  36809. {
  36810. const uint8_t *p_end, *p_next, *p;
  36811. int pc, v;
  36812. unsigned int op;
  36813. if (len <= 0)
  36814. return;
  36815. printf("%5s %5s %5s\n", "PC", "LINE", "COLUMN");
  36816. p = buf;
  36817. p_end = buf + len;
  36818. pc = 0;
  36819. while (p < p_end) {
  36820. op = *p++;
  36821. if (op == 0) {
  36822. v = utf8_decode_len(p, p_end - p, &p_next);
  36823. if (v < 0)
  36824. goto fail;
  36825. pc += v;
  36826. p = p_next;
  36827. v = utf8_decode_len(p, p_end - p, &p_next);
  36828. if (v < 0)
  36829. goto fail;
  36830. if (v & 1) {
  36831. v = -(v >> 1) - 1;
  36832. } else {
  36833. v = v >> 1;
  36834. }
  36835. line_num += v;
  36836. p = p_next;
  36837. } else {
  36838. op -= PC2LINE_OP_FIRST;
  36839. pc += (op / PC2LINE_RANGE);
  36840. line_num += (op % PC2LINE_RANGE) + PC2LINE_BASE;
  36841. }
  36842. v = utf8_decode_len(p, p_end - p, &p_next);
  36843. if (v < 0)
  36844. goto fail;
  36845. if (v & 1) {
  36846. v = -(v >> 1) - 1;
  36847. } else {
  36848. v = v >> 1;
  36849. }
  36850. col_num += v;
  36851. p = p_next;
  36852. printf("%5d %5d %5d\n", pc, line_num, col_num);
  36853. }
  36854. return;
  36855. fail:
  36856. printf("invalid pc2line encode pos=%d\n", (int)(p - buf));
  36857. }
  36858. static __maybe_unused void js_dump_function_bytecode(JSContext *ctx, JSFunctionBytecode *b)
  36859. {
  36860. int i;
  36861. char atom_buf[ATOM_GET_STR_BUF_SIZE];
  36862. const char *str;
  36863. const uint8_t *op;
  36864. if (b->filename != JS_ATOM_NULL) {
  36865. str = JS_AtomGetStr(ctx, atom_buf, sizeof(atom_buf), b->filename);
  36866. printf("%s:%d:%d: ", str, b->line_num, b->col_num);
  36867. }
  36868. str = JS_AtomGetStr(ctx, atom_buf, sizeof(atom_buf), b->func_name);
  36869. printf("function: %s%s\n", &"*"[b->func_kind != JS_FUNC_GENERATOR], str);
  36870. printf(" mode: %s\n", b->is_strict_mode ? "strict" : "sloppy");
  36871. if (b->arg_count && b->vardefs) {
  36872. printf(" args:");
  36873. for(i = 0; i < b->arg_count; i++) {
  36874. printf(" %s", JS_AtomGetStr(ctx, atom_buf, sizeof(atom_buf),
  36875. b->vardefs[i].var_name));
  36876. }
  36877. printf("\n");
  36878. }
  36879. if (b->var_count && b->vardefs) {
  36880. printf(" locals:\n");
  36881. for(i = 0; i < b->var_count; i++) {
  36882. JSVarDef *vd = &b->vardefs[b->arg_count + i];
  36883. printf("%5d: %s %s", i,
  36884. vd->var_kind == JS_VAR_CATCH ? "catch" :
  36885. (vd->var_kind == JS_VAR_FUNCTION_DECL ||
  36886. vd->var_kind == JS_VAR_NEW_FUNCTION_DECL) ? "function" :
  36887. vd->is_const ? "const" :
  36888. vd->is_lexical ? "let" : "var",
  36889. JS_AtomGetStr(ctx, atom_buf, sizeof(atom_buf), vd->var_name));
  36890. if (vd->scope_level)
  36891. printf(" [level:%d next:%d]", vd->scope_level, vd->scope_next);
  36892. printf("\n");
  36893. }
  36894. }
  36895. if (b->closure_var_count) {
  36896. printf(" closure vars:\n");
  36897. for(i = 0; i < b->closure_var_count; i++) {
  36898. JSClosureVar *cv = &b->closure_var[i];
  36899. printf("%5d: %s %s:%s%d %s\n", i,
  36900. JS_AtomGetStr(ctx, atom_buf, sizeof(atom_buf), cv->var_name),
  36901. cv->is_local ? "local" : "parent",
  36902. cv->is_arg ? "arg" : "loc", cv->var_idx,
  36903. cv->is_const ? "const" :
  36904. cv->is_lexical ? "let" : "var");
  36905. }
  36906. }
  36907. printf(" stack_size: %d\n", b->stack_size);
  36908. printf(" byte_code_len: %d\n", b->byte_code_len);
  36909. op = b->byte_code_buf;
  36910. for (i = 0; op < &b->byte_code_buf[b->byte_code_len]; i++)
  36911. op += short_opcode_info(*op).size;
  36912. printf(" opcodes: %d\n", i);
  36913. dump_byte_code(ctx, 3, b->byte_code_buf, b->byte_code_len,
  36914. b->vardefs, b->arg_count,
  36915. b->vardefs ? b->vardefs + b->arg_count : NULL, b->var_count,
  36916. b->closure_var, b->closure_var_count,
  36917. b->cpool, b->cpool_count,
  36918. b->source, b->line_num, NULL, b, 0);
  36919. #ifdef ENABLE_DUMPS // JS_DUMP_BYTECODE_PC2LINE
  36920. if (check_dump_flag(ctx->rt, JS_DUMP_BYTECODE_PC2LINE))
  36921. dump_pc2line(ctx, b->pc2line_buf, b->pc2line_len, b->line_num, b->col_num);
  36922. #endif
  36923. printf("\n");
  36924. }
  36925. #endif
  36926. static int add_closure_var(JSContext *ctx, JSFunctionDef *s,
  36927. bool is_local, bool is_arg,
  36928. int var_idx, JSAtom var_name,
  36929. bool is_const, bool is_lexical,
  36930. JSVarKindEnum var_kind)
  36931. {
  36932. JSClosureVar *cv;
  36933. /* the closure variable indexes are currently stored on 16 bits */
  36934. if (s->closure_var_count >= JS_MAX_LOCAL_VARS) {
  36935. // XXX: add_closure_var() should take JSParseState *s and use js_parse_error
  36936. JS_ThrowSyntaxError(ctx, "too many closure variables used (only %d allowed)",
  36937. JS_MAX_LOCAL_VARS - 1);
  36938. return -1;
  36939. }
  36940. if (js_resize_array(ctx, (void **)&s->closure_var,
  36941. sizeof(s->closure_var[0]),
  36942. &s->closure_var_size, s->closure_var_count + 1))
  36943. return -1;
  36944. cv = &s->closure_var[s->closure_var_count++];
  36945. cv->is_local = is_local;
  36946. cv->is_arg = is_arg;
  36947. cv->is_const = is_const;
  36948. cv->is_lexical = is_lexical;
  36949. cv->var_kind = var_kind;
  36950. cv->var_idx = var_idx;
  36951. cv->var_name = JS_DupAtom(ctx, var_name);
  36952. return s->closure_var_count - 1;
  36953. }
  36954. static int find_closure_var(JSContext *ctx, JSFunctionDef *s,
  36955. JSAtom var_name)
  36956. {
  36957. int i;
  36958. for(i = 0; i < s->closure_var_count; i++) {
  36959. JSClosureVar *cv = &s->closure_var[i];
  36960. if (cv->var_name == var_name)
  36961. return i;
  36962. }
  36963. return -1;
  36964. }
  36965. /* 'fd' must be a parent of 's'. Create in 's' a closure referencing a
  36966. local variable (is_local = true) or a closure (is_local = false) in
  36967. 'fd' */
  36968. static int get_closure_var2(JSContext *ctx, JSFunctionDef *s,
  36969. JSFunctionDef *fd, bool is_local,
  36970. bool is_arg, int var_idx, JSAtom var_name,
  36971. bool is_const, bool is_lexical,
  36972. JSVarKindEnum var_kind)
  36973. {
  36974. int i;
  36975. if (fd != s->parent) {
  36976. var_idx = get_closure_var2(ctx, s->parent, fd, is_local,
  36977. is_arg, var_idx, var_name,
  36978. is_const, is_lexical, var_kind);
  36979. if (var_idx < 0)
  36980. return -1;
  36981. is_local = false;
  36982. }
  36983. for(i = 0; i < s->closure_var_count; i++) {
  36984. JSClosureVar *cv = &s->closure_var[i];
  36985. if (cv->var_idx == var_idx && cv->is_arg == is_arg &&
  36986. cv->is_local == is_local)
  36987. return i;
  36988. }
  36989. return add_closure_var(ctx, s, is_local, is_arg, var_idx, var_name,
  36990. is_const, is_lexical, var_kind);
  36991. }
  36992. static int get_closure_var(JSContext *ctx, JSFunctionDef *s,
  36993. JSFunctionDef *fd, bool is_arg,
  36994. int var_idx, JSAtom var_name,
  36995. bool is_const, bool is_lexical,
  36996. JSVarKindEnum var_kind)
  36997. {
  36998. return get_closure_var2(ctx, s, fd, true, is_arg,
  36999. var_idx, var_name, is_const, is_lexical,
  37000. var_kind);
  37001. }
  37002. static int get_with_scope_opcode(int op)
  37003. {
  37004. if (op == OP_scope_get_var_undef)
  37005. return OP_with_get_var;
  37006. else
  37007. return OP_with_get_var + (op - OP_scope_get_var);
  37008. }
  37009. static bool can_opt_put_ref_value(const uint8_t *bc_buf, int pos)
  37010. {
  37011. int opcode = bc_buf[pos];
  37012. return (bc_buf[pos + 1] == OP_put_ref_value &&
  37013. (opcode == OP_insert3 ||
  37014. opcode == OP_perm4 ||
  37015. opcode == OP_nop ||
  37016. opcode == OP_rot3l));
  37017. }
  37018. static bool can_opt_put_global_ref_value(const uint8_t *bc_buf, int pos)
  37019. {
  37020. int opcode = bc_buf[pos];
  37021. return (bc_buf[pos + 1] == OP_put_ref_value &&
  37022. (opcode == OP_insert3 ||
  37023. opcode == OP_perm4 ||
  37024. opcode == OP_nop ||
  37025. opcode == OP_rot3l));
  37026. }
  37027. static int optimize_scope_make_ref(JSContext *ctx, JSFunctionDef *s,
  37028. DynBuf *bc, uint8_t *bc_buf,
  37029. LabelSlot *ls, int pos_next,
  37030. int get_op, int var_idx)
  37031. {
  37032. int label_pos, end_pos, pos;
  37033. /* XXX: should optimize `loc(a) += expr` as `expr add_loc(a)`
  37034. but only if expr does not modify `a`.
  37035. should scan the code between pos_next and label_pos
  37036. for operations that can potentially change `a`:
  37037. OP_scope_make_ref(a), function calls, jumps and gosub.
  37038. */
  37039. /* replace the reference get/put with normal variable
  37040. accesses */
  37041. if (bc_buf[pos_next] == OP_get_ref_value) {
  37042. dbuf_putc(bc, get_op);
  37043. dbuf_put_u16(bc, var_idx);
  37044. pos_next++;
  37045. }
  37046. /* remove the OP_label to make room for replacement */
  37047. /* label should have a refcount of 0 anyway */
  37048. /* XXX: should avoid this patch by inserting nops in phase 1 */
  37049. label_pos = ls->pos;
  37050. pos = label_pos - 5;
  37051. assert(bc_buf[pos] == OP_label);
  37052. /* label points to an instruction pair:
  37053. - insert3 / put_ref_value
  37054. - perm4 / put_ref_value
  37055. - rot3l / put_ref_value
  37056. - nop / put_ref_value
  37057. */
  37058. end_pos = label_pos + 2;
  37059. if (bc_buf[label_pos] == OP_insert3)
  37060. bc_buf[pos++] = OP_dup;
  37061. bc_buf[pos] = get_op + 1;
  37062. put_u16(bc_buf + pos + 1, var_idx);
  37063. pos += 3;
  37064. /* pad with OP_nop */
  37065. while (pos < end_pos)
  37066. bc_buf[pos++] = OP_nop;
  37067. return pos_next;
  37068. }
  37069. static int optimize_scope_make_global_ref(JSContext *ctx, JSFunctionDef *s,
  37070. DynBuf *bc, uint8_t *bc_buf,
  37071. LabelSlot *ls, int pos_next,
  37072. JSAtom var_name)
  37073. {
  37074. int label_pos, end_pos, pos, op;
  37075. bool is_strict_mode = s->is_strict_mode;
  37076. /* replace the reference get/put with normal variable
  37077. accesses */
  37078. if (is_strict_mode) {
  37079. /* need to check if the variable exists before evaluating the right
  37080. expression */
  37081. /* XXX: need an extra OP_true if destructuring an array */
  37082. dbuf_putc(bc, OP_check_var);
  37083. dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));
  37084. } else {
  37085. /* XXX: need 2 extra OP_true if destructuring an array */
  37086. }
  37087. if (bc_buf[pos_next] == OP_get_ref_value) {
  37088. dbuf_putc(bc, OP_get_var);
  37089. dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));
  37090. pos_next++;
  37091. }
  37092. /* remove the OP_label to make room for replacement */
  37093. /* label should have a refcount of 0 anyway */
  37094. /* XXX: should have emitted several OP_nop to avoid this kludge */
  37095. label_pos = ls->pos;
  37096. pos = label_pos - 5;
  37097. assert(bc_buf[pos] == OP_label);
  37098. end_pos = label_pos + 2;
  37099. op = bc_buf[label_pos];
  37100. if (is_strict_mode) {
  37101. if (op != OP_nop) {
  37102. switch(op) {
  37103. case OP_insert3:
  37104. op = OP_insert2;
  37105. break;
  37106. case OP_perm4:
  37107. op = OP_perm3;
  37108. break;
  37109. case OP_rot3l:
  37110. op = OP_swap;
  37111. break;
  37112. default:
  37113. abort();
  37114. }
  37115. bc_buf[pos++] = op;
  37116. }
  37117. } else {
  37118. if (op == OP_insert3)
  37119. bc_buf[pos++] = OP_dup;
  37120. }
  37121. if (is_strict_mode) {
  37122. bc_buf[pos] = OP_put_var_strict;
  37123. /* XXX: need 1 extra OP_drop if destructuring an array */
  37124. } else {
  37125. bc_buf[pos] = OP_put_var;
  37126. /* XXX: need 2 extra OP_drop if destructuring an array */
  37127. }
  37128. put_u32(bc_buf + pos + 1, JS_DupAtom(ctx, var_name));
  37129. pos += 5;
  37130. /* pad with OP_nop */
  37131. while (pos < end_pos)
  37132. bc_buf[pos++] = OP_nop;
  37133. return pos_next;
  37134. }
  37135. static int add_var_this(JSContext *ctx, JSFunctionDef *fd)
  37136. {
  37137. int idx;
  37138. idx = add_var(ctx, fd, JS_ATOM_this);
  37139. if (idx >= 0 && fd->is_derived_class_constructor) {
  37140. JSVarDef *vd = &fd->vars[idx];
  37141. /* XXX: should have is_this flag or var type */
  37142. vd->is_lexical = 1; /* used to trigger 'uninitialized' checks
  37143. in a derived class constructor */
  37144. }
  37145. return idx;
  37146. }
  37147. static int resolve_pseudo_var(JSContext *ctx, JSFunctionDef *s,
  37148. JSAtom var_name)
  37149. {
  37150. int var_idx;
  37151. if (!s->has_this_binding)
  37152. return -1;
  37153. switch(var_name) {
  37154. case JS_ATOM_home_object:
  37155. /* 'home_object' pseudo variable */
  37156. if (s->home_object_var_idx < 0)
  37157. s->home_object_var_idx = add_var(ctx, s, var_name);
  37158. var_idx = s->home_object_var_idx;
  37159. break;
  37160. case JS_ATOM_this_active_func:
  37161. /* 'this.active_func' pseudo variable */
  37162. if (s->this_active_func_var_idx < 0)
  37163. s->this_active_func_var_idx = add_var(ctx, s, var_name);
  37164. var_idx = s->this_active_func_var_idx;
  37165. break;
  37166. case JS_ATOM_new_target:
  37167. /* 'new.target' pseudo variable */
  37168. if (s->new_target_var_idx < 0)
  37169. s->new_target_var_idx = add_var(ctx, s, var_name);
  37170. var_idx = s->new_target_var_idx;
  37171. break;
  37172. case JS_ATOM_this:
  37173. /* 'this' pseudo variable */
  37174. if (s->this_var_idx < 0)
  37175. s->this_var_idx = add_var_this(ctx, s);
  37176. var_idx = s->this_var_idx;
  37177. break;
  37178. default:
  37179. var_idx = -1;
  37180. break;
  37181. }
  37182. return var_idx;
  37183. }
  37184. /* test if 'var_name' is in the variable object on the stack. If is it
  37185. the case, handle it and jump to 'label_done' */
  37186. static void var_object_test(JSContext *ctx, JSFunctionDef *s,
  37187. JSAtom var_name, int op, DynBuf *bc,
  37188. int *plabel_done, bool is_with)
  37189. {
  37190. dbuf_putc(bc, get_with_scope_opcode(op));
  37191. dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));
  37192. *plabel_done = new_label_fd(s, *plabel_done);
  37193. dbuf_put_u32(bc, *plabel_done);
  37194. dbuf_putc(bc, is_with);
  37195. update_label(s, *plabel_done, 1);
  37196. s->jump_size++;
  37197. }
  37198. /* return the position of the next opcode */
  37199. static int resolve_scope_var(JSContext *ctx, JSFunctionDef *s,
  37200. JSAtom var_name, int scope_level, int op,
  37201. DynBuf *bc, uint8_t *bc_buf,
  37202. LabelSlot *ls, int pos_next)
  37203. {
  37204. int idx, var_idx, is_put;
  37205. int label_done;
  37206. JSFunctionDef *fd;
  37207. JSVarDef *vd;
  37208. bool is_pseudo_var, is_arg_scope;
  37209. label_done = -1;
  37210. /* XXX: could be simpler to use a specific function to
  37211. resolve the pseudo variables */
  37212. is_pseudo_var = (var_name == JS_ATOM_home_object ||
  37213. var_name == JS_ATOM_this_active_func ||
  37214. var_name == JS_ATOM_new_target ||
  37215. var_name == JS_ATOM_this);
  37216. /* resolve local scoped variables */
  37217. var_idx = -1;
  37218. for (idx = s->scopes[scope_level].first; idx >= 0;) {
  37219. vd = &s->vars[idx];
  37220. if (vd->var_name == var_name) {
  37221. if (op == OP_scope_put_var || op == OP_scope_make_ref) {
  37222. if (vd->is_const) {
  37223. dbuf_putc(bc, OP_throw_error);
  37224. dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));
  37225. dbuf_putc(bc, JS_THROW_VAR_RO);
  37226. goto done;
  37227. }
  37228. }
  37229. var_idx = idx;
  37230. break;
  37231. } else
  37232. if (vd->var_name == JS_ATOM__with_ && !is_pseudo_var) {
  37233. dbuf_putc(bc, OP_get_loc);
  37234. dbuf_put_u16(bc, idx);
  37235. var_object_test(ctx, s, var_name, op, bc, &label_done, 1);
  37236. }
  37237. idx = vd->scope_next;
  37238. }
  37239. is_arg_scope = (idx == ARG_SCOPE_END);
  37240. if (var_idx < 0) {
  37241. /* argument scope: variables are not visible but pseudo
  37242. variables are visible */
  37243. if (!is_arg_scope) {
  37244. var_idx = find_var(ctx, s, var_name);
  37245. }
  37246. if (var_idx < 0 && is_pseudo_var)
  37247. var_idx = resolve_pseudo_var(ctx, s, var_name);
  37248. if (var_idx < 0 && var_name == JS_ATOM_arguments &&
  37249. s->has_arguments_binding) {
  37250. /* 'arguments' pseudo variable */
  37251. var_idx = add_arguments_var(ctx, s);
  37252. }
  37253. if (var_idx < 0 && s->is_func_expr && var_name == s->func_name) {
  37254. /* add a new variable with the function name */
  37255. var_idx = add_func_var(ctx, s, var_name);
  37256. }
  37257. }
  37258. if (var_idx >= 0) {
  37259. if ((op == OP_scope_put_var || op == OP_scope_make_ref) &&
  37260. !(var_idx & ARGUMENT_VAR_OFFSET) &&
  37261. s->vars[var_idx].is_const) {
  37262. /* only happens when assigning a function expression name
  37263. in strict mode */
  37264. dbuf_putc(bc, OP_throw_error);
  37265. dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));
  37266. dbuf_putc(bc, JS_THROW_VAR_RO);
  37267. goto done;
  37268. }
  37269. /* OP_scope_put_var_init is only used to initialize a
  37270. lexical variable, so it is never used in a with or var object. It
  37271. can be used with a closure (module global variable case). */
  37272. switch (op) {
  37273. case OP_scope_make_ref:
  37274. if (!(var_idx & ARGUMENT_VAR_OFFSET) &&
  37275. s->vars[var_idx].var_kind == JS_VAR_FUNCTION_NAME) {
  37276. /* Create a dummy object reference for the func_var */
  37277. dbuf_putc(bc, OP_object);
  37278. dbuf_putc(bc, OP_get_loc);
  37279. dbuf_put_u16(bc, var_idx);
  37280. dbuf_putc(bc, OP_define_field);
  37281. dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));
  37282. dbuf_putc(bc, OP_push_atom_value);
  37283. dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));
  37284. } else
  37285. if (label_done == -1 && can_opt_put_ref_value(bc_buf, ls->pos)) {
  37286. int get_op;
  37287. if (var_idx & ARGUMENT_VAR_OFFSET) {
  37288. get_op = OP_get_arg;
  37289. var_idx -= ARGUMENT_VAR_OFFSET;
  37290. } else {
  37291. if (s->vars[var_idx].is_lexical)
  37292. get_op = OP_get_loc_check;
  37293. else
  37294. get_op = OP_get_loc;
  37295. }
  37296. pos_next = optimize_scope_make_ref(ctx, s, bc, bc_buf, ls,
  37297. pos_next, get_op, var_idx);
  37298. } else {
  37299. /* Create a dummy object with a named slot that is
  37300. a reference to the local variable */
  37301. if (var_idx & ARGUMENT_VAR_OFFSET) {
  37302. dbuf_putc(bc, OP_make_arg_ref);
  37303. dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));
  37304. dbuf_put_u16(bc, var_idx - ARGUMENT_VAR_OFFSET);
  37305. } else {
  37306. dbuf_putc(bc, OP_make_loc_ref);
  37307. dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));
  37308. dbuf_put_u16(bc, var_idx);
  37309. }
  37310. }
  37311. break;
  37312. case OP_scope_get_ref:
  37313. dbuf_putc(bc, OP_undefined);
  37314. /* fall thru */
  37315. case OP_scope_get_var_undef:
  37316. case OP_scope_get_var:
  37317. case OP_scope_put_var:
  37318. case OP_scope_put_var_init:
  37319. is_put = (op == OP_scope_put_var || op == OP_scope_put_var_init);
  37320. if (var_idx & ARGUMENT_VAR_OFFSET) {
  37321. dbuf_putc(bc, OP_get_arg + is_put);
  37322. dbuf_put_u16(bc, var_idx - ARGUMENT_VAR_OFFSET);
  37323. } else {
  37324. if (is_put) {
  37325. if (s->vars[var_idx].is_lexical) {
  37326. if (op == OP_scope_put_var_init) {
  37327. /* 'this' can only be initialized once */
  37328. if (var_name == JS_ATOM_this)
  37329. dbuf_putc(bc, OP_put_loc_check_init);
  37330. else
  37331. dbuf_putc(bc, OP_put_loc);
  37332. } else {
  37333. dbuf_putc(bc, OP_put_loc_check);
  37334. }
  37335. } else {
  37336. dbuf_putc(bc, OP_put_loc);
  37337. }
  37338. } else {
  37339. if (s->vars[var_idx].is_lexical) {
  37340. dbuf_putc(bc, OP_get_loc_check);
  37341. } else {
  37342. dbuf_putc(bc, OP_get_loc);
  37343. }
  37344. }
  37345. dbuf_put_u16(bc, var_idx);
  37346. }
  37347. break;
  37348. case OP_scope_delete_var:
  37349. dbuf_putc(bc, OP_push_false);
  37350. break;
  37351. }
  37352. goto done;
  37353. }
  37354. /* check eval object */
  37355. if (!is_arg_scope && s->var_object_idx >= 0 && !is_pseudo_var) {
  37356. dbuf_putc(bc, OP_get_loc);
  37357. dbuf_put_u16(bc, s->var_object_idx);
  37358. var_object_test(ctx, s, var_name, op, bc, &label_done, 0);
  37359. }
  37360. /* check eval object in argument scope */
  37361. if (s->arg_var_object_idx >= 0 && !is_pseudo_var) {
  37362. dbuf_putc(bc, OP_get_loc);
  37363. dbuf_put_u16(bc, s->arg_var_object_idx);
  37364. var_object_test(ctx, s, var_name, op, bc, &label_done, 0);
  37365. }
  37366. /* check parent scopes */
  37367. for (fd = s; fd->parent;) {
  37368. scope_level = fd->parent_scope_level;
  37369. fd = fd->parent;
  37370. for (idx = fd->scopes[scope_level].first; idx >= 0;) {
  37371. vd = &fd->vars[idx];
  37372. if (vd->var_name == var_name) {
  37373. if (op == OP_scope_put_var || op == OP_scope_make_ref) {
  37374. if (vd->is_const) {
  37375. dbuf_putc(bc, OP_throw_error);
  37376. dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));
  37377. dbuf_putc(bc, JS_THROW_VAR_RO);
  37378. goto done;
  37379. }
  37380. }
  37381. var_idx = idx;
  37382. break;
  37383. } else if (vd->var_name == JS_ATOM__with_ && !is_pseudo_var) {
  37384. vd->is_captured = 1;
  37385. idx = get_closure_var(ctx, s, fd, false, idx, vd->var_name, false, false, JS_VAR_NORMAL);
  37386. if (idx >= 0) {
  37387. dbuf_putc(bc, OP_get_var_ref);
  37388. dbuf_put_u16(bc, idx);
  37389. var_object_test(ctx, s, var_name, op, bc, &label_done, 1);
  37390. }
  37391. }
  37392. idx = vd->scope_next;
  37393. }
  37394. is_arg_scope = (idx == ARG_SCOPE_END);
  37395. if (var_idx >= 0)
  37396. break;
  37397. if (!is_arg_scope) {
  37398. var_idx = find_var(ctx, fd, var_name);
  37399. if (var_idx >= 0)
  37400. break;
  37401. }
  37402. if (is_pseudo_var) {
  37403. var_idx = resolve_pseudo_var(ctx, fd, var_name);
  37404. if (var_idx >= 0)
  37405. break;
  37406. }
  37407. if (var_name == JS_ATOM_arguments && fd->has_arguments_binding) {
  37408. var_idx = add_arguments_var(ctx, fd);
  37409. break;
  37410. }
  37411. if (fd->is_func_expr && fd->func_name == var_name) {
  37412. /* add a new variable with the function name */
  37413. var_idx = add_func_var(ctx, fd, var_name);
  37414. break;
  37415. }
  37416. /* check eval object */
  37417. if (!is_arg_scope && fd->var_object_idx >= 0 && !is_pseudo_var) {
  37418. vd = &fd->vars[fd->var_object_idx];
  37419. vd->is_captured = 1;
  37420. idx = get_closure_var(ctx, s, fd, false,
  37421. fd->var_object_idx, vd->var_name,
  37422. false, false, JS_VAR_NORMAL);
  37423. dbuf_putc(bc, OP_get_var_ref);
  37424. dbuf_put_u16(bc, idx);
  37425. var_object_test(ctx, s, var_name, op, bc, &label_done, 0);
  37426. }
  37427. /* check eval object in argument scope */
  37428. if (fd->arg_var_object_idx >= 0 && !is_pseudo_var) {
  37429. vd = &fd->vars[fd->arg_var_object_idx];
  37430. vd->is_captured = 1;
  37431. idx = get_closure_var(ctx, s, fd, false,
  37432. fd->arg_var_object_idx, vd->var_name,
  37433. false, false, JS_VAR_NORMAL);
  37434. dbuf_putc(bc, OP_get_var_ref);
  37435. dbuf_put_u16(bc, idx);
  37436. var_object_test(ctx, s, var_name, op, bc, &label_done, 0);
  37437. }
  37438. if (fd->is_eval)
  37439. break; /* it it necessarily the top level function */
  37440. }
  37441. /* check direct eval scope (in the closure of the eval function
  37442. which is necessarily at the top level) */
  37443. if (!fd)
  37444. fd = s;
  37445. if (var_idx < 0 && fd->is_eval) {
  37446. int idx1;
  37447. for (idx1 = 0; idx1 < fd->closure_var_count; idx1++) {
  37448. JSClosureVar *cv = &fd->closure_var[idx1];
  37449. if (var_name == cv->var_name) {
  37450. if (fd != s) {
  37451. idx = get_closure_var2(ctx, s, fd,
  37452. false,
  37453. cv->is_arg, idx1,
  37454. cv->var_name, cv->is_const,
  37455. cv->is_lexical, cv->var_kind);
  37456. } else {
  37457. idx = idx1;
  37458. }
  37459. goto has_idx;
  37460. } else if ((cv->var_name == JS_ATOM__var_ ||
  37461. cv->var_name == JS_ATOM__arg_var_ ||
  37462. cv->var_name == JS_ATOM__with_) && !is_pseudo_var) {
  37463. int is_with = (cv->var_name == JS_ATOM__with_);
  37464. if (fd != s) {
  37465. idx = get_closure_var2(ctx, s, fd,
  37466. false,
  37467. cv->is_arg, idx1,
  37468. cv->var_name, false, false,
  37469. JS_VAR_NORMAL);
  37470. } else {
  37471. idx = idx1;
  37472. }
  37473. dbuf_putc(bc, OP_get_var_ref);
  37474. dbuf_put_u16(bc, idx);
  37475. var_object_test(ctx, s, var_name, op, bc, &label_done, is_with);
  37476. }
  37477. }
  37478. }
  37479. if (var_idx >= 0) {
  37480. /* find the corresponding closure variable */
  37481. if (var_idx & ARGUMENT_VAR_OFFSET) {
  37482. fd->args[var_idx - ARGUMENT_VAR_OFFSET].is_captured = 1;
  37483. idx = get_closure_var(ctx, s, fd,
  37484. true, var_idx - ARGUMENT_VAR_OFFSET,
  37485. var_name, false, false, JS_VAR_NORMAL);
  37486. } else {
  37487. fd->vars[var_idx].is_captured = 1;
  37488. idx = get_closure_var(ctx, s, fd,
  37489. false, var_idx,
  37490. var_name,
  37491. fd->vars[var_idx].is_const,
  37492. fd->vars[var_idx].is_lexical,
  37493. fd->vars[var_idx].var_kind);
  37494. }
  37495. if (idx >= 0) {
  37496. has_idx:
  37497. if ((op == OP_scope_put_var || op == OP_scope_make_ref) &&
  37498. s->closure_var[idx].is_const) {
  37499. dbuf_putc(bc, OP_throw_error);
  37500. dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));
  37501. dbuf_putc(bc, JS_THROW_VAR_RO);
  37502. goto done;
  37503. }
  37504. switch (op) {
  37505. case OP_scope_make_ref:
  37506. if (s->closure_var[idx].var_kind == JS_VAR_FUNCTION_NAME) {
  37507. /* Create a dummy object reference for the func_var */
  37508. dbuf_putc(bc, OP_object);
  37509. dbuf_putc(bc, OP_get_var_ref);
  37510. dbuf_put_u16(bc, idx);
  37511. dbuf_putc(bc, OP_define_field);
  37512. dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));
  37513. dbuf_putc(bc, OP_push_atom_value);
  37514. dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));
  37515. } else
  37516. if (label_done == -1 &&
  37517. can_opt_put_ref_value(bc_buf, ls->pos)) {
  37518. int get_op;
  37519. if (s->closure_var[idx].is_lexical)
  37520. get_op = OP_get_var_ref_check;
  37521. else
  37522. get_op = OP_get_var_ref;
  37523. pos_next = optimize_scope_make_ref(ctx, s, bc, bc_buf, ls,
  37524. pos_next,
  37525. get_op, idx);
  37526. } else {
  37527. /* Create a dummy object with a named slot that is
  37528. a reference to the closure variable */
  37529. dbuf_putc(bc, OP_make_var_ref_ref);
  37530. dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));
  37531. dbuf_put_u16(bc, idx);
  37532. }
  37533. break;
  37534. case OP_scope_get_ref:
  37535. /* XXX: should create a dummy object with a named slot that is
  37536. a reference to the closure variable */
  37537. dbuf_putc(bc, OP_undefined);
  37538. /* fall thru */
  37539. case OP_scope_get_var_undef:
  37540. case OP_scope_get_var:
  37541. case OP_scope_put_var:
  37542. case OP_scope_put_var_init:
  37543. is_put = (op == OP_scope_put_var ||
  37544. op == OP_scope_put_var_init);
  37545. if (is_put) {
  37546. if (s->closure_var[idx].is_lexical) {
  37547. if (op == OP_scope_put_var_init) {
  37548. /* 'this' can only be initialized once */
  37549. if (var_name == JS_ATOM_this)
  37550. dbuf_putc(bc, OP_put_var_ref_check_init);
  37551. else
  37552. dbuf_putc(bc, OP_put_var_ref);
  37553. } else {
  37554. dbuf_putc(bc, OP_put_var_ref_check);
  37555. }
  37556. } else {
  37557. dbuf_putc(bc, OP_put_var_ref);
  37558. }
  37559. } else {
  37560. if (s->closure_var[idx].is_lexical) {
  37561. dbuf_putc(bc, OP_get_var_ref_check);
  37562. } else {
  37563. dbuf_putc(bc, OP_get_var_ref);
  37564. }
  37565. }
  37566. dbuf_put_u16(bc, idx);
  37567. break;
  37568. case OP_scope_delete_var:
  37569. dbuf_putc(bc, OP_push_false);
  37570. break;
  37571. }
  37572. goto done;
  37573. }
  37574. }
  37575. /* global variable access */
  37576. switch (op) {
  37577. case OP_scope_make_ref:
  37578. if (label_done == -1 && can_opt_put_global_ref_value(bc_buf, ls->pos)) {
  37579. pos_next = optimize_scope_make_global_ref(ctx, s, bc, bc_buf, ls,
  37580. pos_next, var_name);
  37581. } else {
  37582. dbuf_putc(bc, OP_make_var_ref);
  37583. dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));
  37584. }
  37585. break;
  37586. case OP_scope_get_ref:
  37587. /* XXX: should create a dummy object with a named slot that is
  37588. a reference to the global variable */
  37589. dbuf_putc(bc, OP_undefined);
  37590. dbuf_putc(bc, OP_get_var);
  37591. dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));
  37592. break;
  37593. case OP_scope_get_var_undef:
  37594. case OP_scope_get_var:
  37595. case OP_scope_put_var:
  37596. dbuf_putc(bc, OP_get_var_undef + (op - OP_scope_get_var_undef));
  37597. dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));
  37598. break;
  37599. case OP_scope_put_var_init:
  37600. dbuf_putc(bc, OP_put_var_init);
  37601. dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));
  37602. break;
  37603. case OP_scope_delete_var:
  37604. dbuf_putc(bc, OP_delete_var);
  37605. dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));
  37606. break;
  37607. }
  37608. done:
  37609. if (label_done >= 0) {
  37610. dbuf_putc(bc, OP_label);
  37611. dbuf_put_u32(bc, label_done);
  37612. s->label_slots[label_done].pos2 = bc->size;
  37613. }
  37614. return pos_next;
  37615. }
  37616. /* search in all scopes */
  37617. static int find_private_class_field_all(JSContext *ctx, JSFunctionDef *fd,
  37618. JSAtom name, int scope_level)
  37619. {
  37620. int idx;
  37621. idx = fd->scopes[scope_level].first;
  37622. while (idx >= 0) {
  37623. if (fd->vars[idx].var_name == name)
  37624. return idx;
  37625. idx = fd->vars[idx].scope_next;
  37626. }
  37627. return -1;
  37628. }
  37629. static void get_loc_or_ref(DynBuf *bc, bool is_ref, int idx)
  37630. {
  37631. /* if the field is not initialized, the error is catched when
  37632. accessing it */
  37633. if (is_ref)
  37634. dbuf_putc(bc, OP_get_var_ref);
  37635. else
  37636. dbuf_putc(bc, OP_get_loc);
  37637. dbuf_put_u16(bc, idx);
  37638. }
  37639. static int resolve_scope_private_field1(JSContext *ctx,
  37640. bool *pis_ref, int *pvar_kind,
  37641. JSFunctionDef *s,
  37642. JSAtom var_name, int scope_level)
  37643. {
  37644. int idx, var_kind;
  37645. JSFunctionDef *fd;
  37646. bool is_ref;
  37647. fd = s;
  37648. is_ref = false;
  37649. for(;;) {
  37650. idx = find_private_class_field_all(ctx, fd, var_name, scope_level);
  37651. if (idx >= 0) {
  37652. var_kind = fd->vars[idx].var_kind;
  37653. if (is_ref) {
  37654. idx = get_closure_var(ctx, s, fd, false, idx, var_name,
  37655. true, true, JS_VAR_NORMAL);
  37656. if (idx < 0)
  37657. return -1;
  37658. }
  37659. break;
  37660. }
  37661. scope_level = fd->parent_scope_level;
  37662. if (!fd->parent) {
  37663. if (fd->is_eval) {
  37664. /* closure of the eval function (top level) */
  37665. for (idx = 0; idx < fd->closure_var_count; idx++) {
  37666. JSClosureVar *cv = &fd->closure_var[idx];
  37667. if (cv->var_name == var_name) {
  37668. var_kind = cv->var_kind;
  37669. is_ref = true;
  37670. if (fd != s) {
  37671. idx = get_closure_var2(ctx, s, fd,
  37672. false,
  37673. cv->is_arg, idx,
  37674. cv->var_name, cv->is_const,
  37675. cv->is_lexical,
  37676. cv->var_kind);
  37677. if (idx < 0)
  37678. return -1;
  37679. }
  37680. goto done;
  37681. }
  37682. }
  37683. }
  37684. /* XXX: no line number info */
  37685. // XXX: resolve_scope_private_field1() should take JSParseState *s and use js_parse_error_atom
  37686. JS_ThrowSyntaxErrorAtom(ctx, "undefined private field '%s'",
  37687. var_name);
  37688. return -1;
  37689. } else {
  37690. fd = fd->parent;
  37691. }
  37692. is_ref = true;
  37693. }
  37694. done:
  37695. *pis_ref = is_ref;
  37696. *pvar_kind = var_kind;
  37697. return idx;
  37698. }
  37699. /* return 0 if OK or -1 if the private field could not be resolved */
  37700. static int resolve_scope_private_field(JSContext *ctx, JSFunctionDef *s,
  37701. JSAtom var_name, int scope_level, int op,
  37702. DynBuf *bc)
  37703. {
  37704. int idx, var_kind;
  37705. bool is_ref;
  37706. idx = resolve_scope_private_field1(ctx, &is_ref, &var_kind, s,
  37707. var_name, scope_level);
  37708. if (idx < 0)
  37709. return -1;
  37710. assert(var_kind != JS_VAR_NORMAL);
  37711. switch (op) {
  37712. case OP_scope_get_private_field:
  37713. case OP_scope_get_private_field2:
  37714. switch(var_kind) {
  37715. case JS_VAR_PRIVATE_FIELD:
  37716. if (op == OP_scope_get_private_field2)
  37717. dbuf_putc(bc, OP_dup);
  37718. get_loc_or_ref(bc, is_ref, idx);
  37719. dbuf_putc(bc, OP_get_private_field);
  37720. break;
  37721. case JS_VAR_PRIVATE_METHOD:
  37722. get_loc_or_ref(bc, is_ref, idx);
  37723. dbuf_putc(bc, OP_check_brand);
  37724. if (op != OP_scope_get_private_field2)
  37725. dbuf_putc(bc, OP_nip);
  37726. break;
  37727. case JS_VAR_PRIVATE_GETTER:
  37728. case JS_VAR_PRIVATE_GETTER_SETTER:
  37729. if (op == OP_scope_get_private_field2)
  37730. dbuf_putc(bc, OP_dup);
  37731. get_loc_or_ref(bc, is_ref, idx);
  37732. dbuf_putc(bc, OP_check_brand);
  37733. dbuf_putc(bc, OP_call_method);
  37734. dbuf_put_u16(bc, 0);
  37735. break;
  37736. case JS_VAR_PRIVATE_SETTER:
  37737. /* XXX: add clearer error message */
  37738. dbuf_putc(bc, OP_throw_error);
  37739. dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));
  37740. dbuf_putc(bc, JS_THROW_VAR_RO);
  37741. break;
  37742. default:
  37743. abort();
  37744. }
  37745. break;
  37746. case OP_scope_put_private_field:
  37747. switch(var_kind) {
  37748. case JS_VAR_PRIVATE_FIELD:
  37749. get_loc_or_ref(bc, is_ref, idx);
  37750. dbuf_putc(bc, OP_put_private_field);
  37751. break;
  37752. case JS_VAR_PRIVATE_METHOD:
  37753. case JS_VAR_PRIVATE_GETTER:
  37754. /* XXX: add clearer error message */
  37755. dbuf_putc(bc, OP_throw_error);
  37756. dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));
  37757. dbuf_putc(bc, JS_THROW_VAR_RO);
  37758. break;
  37759. case JS_VAR_PRIVATE_SETTER:
  37760. case JS_VAR_PRIVATE_GETTER_SETTER:
  37761. {
  37762. JSAtom setter_name = get_private_setter_name(ctx, var_name);
  37763. if (setter_name == JS_ATOM_NULL)
  37764. return -1;
  37765. idx = resolve_scope_private_field1(ctx, &is_ref,
  37766. &var_kind, s,
  37767. setter_name, scope_level);
  37768. JS_FreeAtom(ctx, setter_name);
  37769. if (idx < 0)
  37770. return -1;
  37771. assert(var_kind == JS_VAR_PRIVATE_SETTER);
  37772. get_loc_or_ref(bc, is_ref, idx);
  37773. dbuf_putc(bc, OP_swap);
  37774. /* obj func value */
  37775. dbuf_putc(bc, OP_rot3r);
  37776. /* value obj func */
  37777. dbuf_putc(bc, OP_check_brand);
  37778. dbuf_putc(bc, OP_rot3l);
  37779. /* obj func value */
  37780. dbuf_putc(bc, OP_call_method);
  37781. dbuf_put_u16(bc, 1);
  37782. dbuf_putc(bc, OP_drop);
  37783. }
  37784. break;
  37785. default:
  37786. abort();
  37787. }
  37788. break;
  37789. case OP_scope_in_private_field:
  37790. get_loc_or_ref(bc, is_ref, idx);
  37791. dbuf_putc(bc, OP_private_in);
  37792. break;
  37793. default:
  37794. abort();
  37795. }
  37796. return 0;
  37797. }
  37798. static void mark_eval_captured_variables(JSContext *ctx, JSFunctionDef *s,
  37799. int scope_level)
  37800. {
  37801. int idx;
  37802. JSVarDef *vd;
  37803. for (idx = s->scopes[scope_level].first; idx >= 0;) {
  37804. vd = &s->vars[idx];
  37805. vd->is_captured = 1;
  37806. idx = vd->scope_next;
  37807. }
  37808. }
  37809. /* XXX: should handle the argument scope generically */
  37810. static bool is_var_in_arg_scope(const JSVarDef *vd)
  37811. {
  37812. return (vd->var_name == JS_ATOM_home_object ||
  37813. vd->var_name == JS_ATOM_this_active_func ||
  37814. vd->var_name == JS_ATOM_new_target ||
  37815. vd->var_name == JS_ATOM_this ||
  37816. vd->var_name == JS_ATOM__arg_var_ ||
  37817. vd->var_kind == JS_VAR_FUNCTION_NAME);
  37818. }
  37819. static void add_eval_variables(JSContext *ctx, JSFunctionDef *s)
  37820. {
  37821. JSFunctionDef *fd;
  37822. JSVarDef *vd;
  37823. int i, scope_level, scope_idx;
  37824. bool has_arguments_binding, has_this_binding, is_arg_scope;
  37825. /* in non strict mode, variables are created in the caller's
  37826. environment object */
  37827. if (!s->is_eval && !s->is_strict_mode) {
  37828. s->var_object_idx = add_var(ctx, s, JS_ATOM__var_);
  37829. if (s->has_parameter_expressions) {
  37830. /* an additional variable object is needed for the
  37831. argument scope */
  37832. s->arg_var_object_idx = add_var(ctx, s, JS_ATOM__arg_var_);
  37833. }
  37834. }
  37835. /* eval can potentially use 'arguments' so we must define it */
  37836. has_this_binding = s->has_this_binding;
  37837. if (has_this_binding) {
  37838. if (s->this_var_idx < 0)
  37839. s->this_var_idx = add_var_this(ctx, s);
  37840. if (s->new_target_var_idx < 0)
  37841. s->new_target_var_idx = add_var(ctx, s, JS_ATOM_new_target);
  37842. if (s->is_derived_class_constructor && s->this_active_func_var_idx < 0)
  37843. s->this_active_func_var_idx = add_var(ctx, s, JS_ATOM_this_active_func);
  37844. if (s->has_home_object && s->home_object_var_idx < 0)
  37845. s->home_object_var_idx = add_var(ctx, s, JS_ATOM_home_object);
  37846. }
  37847. has_arguments_binding = s->has_arguments_binding;
  37848. if (has_arguments_binding) {
  37849. add_arguments_var(ctx, s);
  37850. /* also add an arguments binding in the argument scope to
  37851. raise an error if a direct eval in the argument scope tries
  37852. to redefine it */
  37853. if (s->has_parameter_expressions && !s->is_strict_mode)
  37854. add_arguments_arg(ctx, s);
  37855. }
  37856. if (s->is_func_expr && s->func_name != JS_ATOM_NULL)
  37857. add_func_var(ctx, s, s->func_name);
  37858. /* eval can use all the variables of the enclosing functions, so
  37859. they must be all put in the closure. The closure variables are
  37860. ordered by scope. It works only because no closure are created
  37861. before. */
  37862. assert(s->is_eval || s->closure_var_count == 0);
  37863. /* XXX: inefficient, but eval performance is less critical */
  37864. fd = s;
  37865. for(;;) {
  37866. scope_level = fd->parent_scope_level;
  37867. fd = fd->parent;
  37868. if (!fd)
  37869. break;
  37870. /* add 'this' if it was not previously added */
  37871. if (!has_this_binding && fd->has_this_binding) {
  37872. if (fd->this_var_idx < 0)
  37873. fd->this_var_idx = add_var_this(ctx, fd);
  37874. if (fd->new_target_var_idx < 0)
  37875. fd->new_target_var_idx = add_var(ctx, fd, JS_ATOM_new_target);
  37876. if (fd->is_derived_class_constructor && fd->this_active_func_var_idx < 0)
  37877. fd->this_active_func_var_idx = add_var(ctx, fd, JS_ATOM_this_active_func);
  37878. if (fd->has_home_object && fd->home_object_var_idx < 0)
  37879. fd->home_object_var_idx = add_var(ctx, fd, JS_ATOM_home_object);
  37880. has_this_binding = true;
  37881. }
  37882. /* add 'arguments' if it was not previously added */
  37883. if (!has_arguments_binding && fd->has_arguments_binding) {
  37884. add_arguments_var(ctx, fd);
  37885. has_arguments_binding = true;
  37886. }
  37887. /* add function name */
  37888. if (fd->is_func_expr && fd->func_name != JS_ATOM_NULL)
  37889. add_func_var(ctx, fd, fd->func_name);
  37890. /* add lexical variables */
  37891. scope_idx = fd->scopes[scope_level].first;
  37892. while (scope_idx >= 0) {
  37893. vd = &fd->vars[scope_idx];
  37894. vd->is_captured = 1;
  37895. get_closure_var(ctx, s, fd, false, scope_idx,
  37896. vd->var_name, vd->is_const, vd->is_lexical, vd->var_kind);
  37897. scope_idx = vd->scope_next;
  37898. }
  37899. is_arg_scope = (scope_idx == ARG_SCOPE_END);
  37900. if (!is_arg_scope) {
  37901. /* add unscoped variables */
  37902. /* XXX: propagate is_const and var_kind too ? */
  37903. for(i = 0; i < fd->arg_count; i++) {
  37904. vd = &fd->args[i];
  37905. if (vd->var_name != JS_ATOM_NULL) {
  37906. get_closure_var(ctx, s, fd,
  37907. true, i, vd->var_name, false,
  37908. vd->is_lexical, JS_VAR_NORMAL);
  37909. }
  37910. }
  37911. for(i = 0; i < fd->var_count; i++) {
  37912. vd = &fd->vars[i];
  37913. /* do not close top level last result */
  37914. if (vd->scope_level == 0 &&
  37915. vd->var_name != JS_ATOM__ret_ &&
  37916. vd->var_name != JS_ATOM_NULL) {
  37917. get_closure_var(ctx, s, fd,
  37918. false, i, vd->var_name, false,
  37919. vd->is_lexical, JS_VAR_NORMAL);
  37920. }
  37921. }
  37922. } else {
  37923. for(i = 0; i < fd->var_count; i++) {
  37924. vd = &fd->vars[i];
  37925. /* do not close top level last result */
  37926. if (vd->scope_level == 0 && is_var_in_arg_scope(vd)) {
  37927. get_closure_var(ctx, s, fd,
  37928. false, i, vd->var_name, false,
  37929. vd->is_lexical, JS_VAR_NORMAL);
  37930. }
  37931. }
  37932. }
  37933. if (fd->is_eval) {
  37934. int idx;
  37935. /* add direct eval variables (we are necessarily at the
  37936. top level) */
  37937. for (idx = 0; idx < fd->closure_var_count; idx++) {
  37938. JSClosureVar *cv = &fd->closure_var[idx];
  37939. get_closure_var2(ctx, s, fd,
  37940. false, cv->is_arg,
  37941. idx, cv->var_name, cv->is_const,
  37942. cv->is_lexical, cv->var_kind);
  37943. }
  37944. }
  37945. }
  37946. }
  37947. static void set_closure_from_var(JSContext *ctx, JSClosureVar *cv,
  37948. JSVarDef *vd, int var_idx)
  37949. {
  37950. cv->is_local = true;
  37951. cv->is_arg = false;
  37952. cv->is_const = vd->is_const;
  37953. cv->is_lexical = vd->is_lexical;
  37954. cv->var_kind = vd->var_kind;
  37955. cv->var_idx = var_idx;
  37956. cv->var_name = JS_DupAtom(ctx, vd->var_name);
  37957. }
  37958. /* for direct eval compilation: add references to the variables of the
  37959. calling function */
  37960. static __exception int add_closure_variables(JSContext *ctx, JSFunctionDef *s,
  37961. JSFunctionBytecode *b, int scope_idx)
  37962. {
  37963. int i, count;
  37964. JSVarDef *vd;
  37965. bool is_arg_scope;
  37966. count = b->arg_count + b->var_count + b->closure_var_count;
  37967. s->closure_var = NULL;
  37968. s->closure_var_count = 0;
  37969. s->closure_var_size = count;
  37970. if (count == 0)
  37971. return 0;
  37972. s->closure_var = js_malloc(ctx, sizeof(s->closure_var[0]) * count);
  37973. if (!s->closure_var)
  37974. return -1;
  37975. /* Add lexical variables in scope at the point of evaluation */
  37976. for (i = scope_idx; i >= 0;) {
  37977. vd = &b->vardefs[b->arg_count + i];
  37978. if (vd->scope_level > 0) {
  37979. JSClosureVar *cv = &s->closure_var[s->closure_var_count++];
  37980. set_closure_from_var(ctx, cv, vd, i);
  37981. }
  37982. i = vd->scope_next;
  37983. }
  37984. is_arg_scope = (i == ARG_SCOPE_END);
  37985. if (!is_arg_scope) {
  37986. /* Add argument variables */
  37987. for(i = 0; i < b->arg_count; i++) {
  37988. JSClosureVar *cv = &s->closure_var[s->closure_var_count++];
  37989. vd = &b->vardefs[i];
  37990. cv->is_local = true;
  37991. cv->is_arg = true;
  37992. cv->is_const = false;
  37993. cv->is_lexical = false;
  37994. cv->var_kind = JS_VAR_NORMAL;
  37995. cv->var_idx = i;
  37996. cv->var_name = JS_DupAtom(ctx, vd->var_name);
  37997. }
  37998. /* Add local non lexical variables */
  37999. for(i = 0; i < b->var_count; i++) {
  38000. vd = &b->vardefs[b->arg_count + i];
  38001. if (vd->scope_level == 0 && vd->var_name != JS_ATOM__ret_) {
  38002. JSClosureVar *cv = &s->closure_var[s->closure_var_count++];
  38003. set_closure_from_var(ctx, cv, vd, i);
  38004. }
  38005. }
  38006. } else {
  38007. /* only add pseudo variables */
  38008. for(i = 0; i < b->var_count; i++) {
  38009. vd = &b->vardefs[b->arg_count + i];
  38010. if (vd->scope_level == 0 && is_var_in_arg_scope(vd)) {
  38011. JSClosureVar *cv = &s->closure_var[s->closure_var_count++];
  38012. set_closure_from_var(ctx, cv, vd, i);
  38013. }
  38014. }
  38015. }
  38016. for(i = 0; i < b->closure_var_count; i++) {
  38017. JSClosureVar *cv0 = &b->closure_var[i];
  38018. JSClosureVar *cv = &s->closure_var[s->closure_var_count++];
  38019. cv->is_local = false;
  38020. cv->is_arg = cv0->is_arg;
  38021. cv->is_const = cv0->is_const;
  38022. cv->is_lexical = cv0->is_lexical;
  38023. cv->var_kind = cv0->var_kind;
  38024. cv->var_idx = i;
  38025. cv->var_name = JS_DupAtom(ctx, cv0->var_name);
  38026. }
  38027. return 0;
  38028. }
  38029. typedef struct CodeContext {
  38030. const uint8_t *bc_buf; /* code buffer */
  38031. int bc_len; /* length of the code buffer */
  38032. int pos; /* position past the matched code pattern */
  38033. int line_num; /* last visited OP_source_loc parameter or -1 */
  38034. int col_num; /* last visited OP_source_loc parameter or -1 */
  38035. int op;
  38036. int idx;
  38037. int label;
  38038. int val;
  38039. JSAtom atom;
  38040. } CodeContext;
  38041. #define M2(op1, op2) ((uint32_t)(op1) | ((uint32_t)(op2) << 8))
  38042. #define M3(op1, op2, op3) ((uint32_t)(op1) | ((uint32_t)(op2) << 8) | ((uint32_t)(op3) << 16))
  38043. #define M4(op1, op2, op3, op4) ((uint32_t)(op1) | ((uint32_t)(op2) << 8) | ((uint32_t)(op3) << 16) | ((uint32_t)(op4) << 24))
  38044. static bool code_match(CodeContext *s, int pos, ...)
  38045. {
  38046. const uint8_t *tab = s->bc_buf;
  38047. int op, len, op1, line_num, col_num, pos_next;
  38048. va_list ap;
  38049. bool ret = false;
  38050. line_num = -1;
  38051. col_num = -1;
  38052. va_start(ap, pos);
  38053. for(;;) {
  38054. op1 = va_arg(ap, int);
  38055. if (op1 == -1) {
  38056. s->pos = pos;
  38057. s->line_num = line_num;
  38058. s->col_num = col_num;
  38059. ret = true;
  38060. break;
  38061. }
  38062. for (;;) {
  38063. if (pos >= s->bc_len)
  38064. goto done;
  38065. op = tab[pos];
  38066. len = opcode_info[op].size;
  38067. pos_next = pos + len;
  38068. if (pos_next > s->bc_len)
  38069. goto done;
  38070. if (op == OP_source_loc) {
  38071. line_num = get_u32(tab + pos + 1);
  38072. col_num = get_u32(tab + pos + 5);
  38073. pos = pos_next;
  38074. } else {
  38075. break;
  38076. }
  38077. }
  38078. if (op != op1) {
  38079. if (op1 == (uint8_t)op1 || !op)
  38080. break;
  38081. if (op != (uint8_t)op1
  38082. && op != (uint8_t)(op1 >> 8)
  38083. && op != (uint8_t)(op1 >> 16)
  38084. && op != (uint8_t)(op1 >> 24)) {
  38085. break;
  38086. }
  38087. s->op = op;
  38088. }
  38089. pos++;
  38090. switch(opcode_info[op].fmt) {
  38091. case OP_FMT_loc8:
  38092. case OP_FMT_u8:
  38093. {
  38094. int idx = tab[pos];
  38095. int arg = va_arg(ap, int);
  38096. if (arg == -1) {
  38097. s->idx = idx;
  38098. } else {
  38099. if (arg != idx)
  38100. goto done;
  38101. }
  38102. break;
  38103. }
  38104. case OP_FMT_u16:
  38105. case OP_FMT_npop:
  38106. case OP_FMT_loc:
  38107. case OP_FMT_arg:
  38108. case OP_FMT_var_ref:
  38109. {
  38110. int idx = get_u16(tab + pos);
  38111. int arg = va_arg(ap, int);
  38112. if (arg == -1) {
  38113. s->idx = idx;
  38114. } else {
  38115. if (arg != idx)
  38116. goto done;
  38117. }
  38118. break;
  38119. }
  38120. case OP_FMT_i32:
  38121. case OP_FMT_u32:
  38122. case OP_FMT_label:
  38123. case OP_FMT_const:
  38124. {
  38125. s->label = get_u32(tab + pos);
  38126. break;
  38127. }
  38128. case OP_FMT_label_u16:
  38129. {
  38130. s->label = get_u32(tab + pos);
  38131. s->val = get_u16(tab + pos + 4);
  38132. break;
  38133. }
  38134. case OP_FMT_atom:
  38135. {
  38136. s->atom = get_u32(tab + pos);
  38137. break;
  38138. }
  38139. case OP_FMT_atom_u8:
  38140. {
  38141. s->atom = get_u32(tab + pos);
  38142. s->val = get_u8(tab + pos + 4);
  38143. break;
  38144. }
  38145. case OP_FMT_atom_u16:
  38146. {
  38147. s->atom = get_u32(tab + pos);
  38148. s->val = get_u16(tab + pos + 4);
  38149. break;
  38150. }
  38151. case OP_FMT_atom_label_u8:
  38152. {
  38153. s->atom = get_u32(tab + pos);
  38154. s->label = get_u32(tab + pos + 4);
  38155. s->val = get_u8(tab + pos + 8);
  38156. break;
  38157. }
  38158. default:
  38159. break;
  38160. }
  38161. pos = pos_next;
  38162. }
  38163. done:
  38164. va_end(ap);
  38165. return ret;
  38166. }
  38167. static void instantiate_hoisted_definitions(JSContext *ctx, JSFunctionDef *s, DynBuf *bc)
  38168. {
  38169. int i, idx, label_next = -1;
  38170. /* add the hoisted functions in arguments and local variables */
  38171. for(i = 0; i < s->arg_count; i++) {
  38172. JSVarDef *vd = &s->args[i];
  38173. if (vd->func_pool_idx >= 0) {
  38174. dbuf_putc(bc, OP_fclosure);
  38175. dbuf_put_u32(bc, vd->func_pool_idx);
  38176. dbuf_putc(bc, OP_put_arg);
  38177. dbuf_put_u16(bc, i);
  38178. }
  38179. }
  38180. for(i = 0; i < s->var_count; i++) {
  38181. JSVarDef *vd = &s->vars[i];
  38182. if (vd->scope_level == 0 && vd->func_pool_idx >= 0) {
  38183. dbuf_putc(bc, OP_fclosure);
  38184. dbuf_put_u32(bc, vd->func_pool_idx);
  38185. dbuf_putc(bc, OP_put_loc);
  38186. dbuf_put_u16(bc, i);
  38187. }
  38188. }
  38189. /* the module global variables must be initialized before
  38190. evaluating the module so that the exported functions are
  38191. visible if there are cyclic module references */
  38192. if (s->module) {
  38193. label_next = new_label_fd(s, -1);
  38194. /* if 'this' is true, initialize the global variables and return */
  38195. dbuf_putc(bc, OP_push_this);
  38196. dbuf_putc(bc, OP_if_false);
  38197. dbuf_put_u32(bc, label_next);
  38198. update_label(s, label_next, 1);
  38199. s->jump_size++;
  38200. }
  38201. /* add the global variables (only happens if s->is_global_var is
  38202. true) */
  38203. for(i = 0; i < s->global_var_count; i++) {
  38204. JSGlobalVar *hf = &s->global_vars[i];
  38205. int has_closure = 0;
  38206. bool force_init = hf->force_init;
  38207. /* we are in an eval, so the closure contains all the
  38208. enclosing variables */
  38209. /* If the outer function has a variable environment,
  38210. create a property for the variable there */
  38211. for(idx = 0; idx < s->closure_var_count; idx++) {
  38212. JSClosureVar *cv = &s->closure_var[idx];
  38213. if (cv->var_name == hf->var_name) {
  38214. has_closure = 2;
  38215. force_init = false;
  38216. break;
  38217. }
  38218. if (cv->var_name == JS_ATOM__var_ ||
  38219. cv->var_name == JS_ATOM__arg_var_) {
  38220. dbuf_putc(bc, OP_get_var_ref);
  38221. dbuf_put_u16(bc, idx);
  38222. has_closure = 1;
  38223. force_init = true;
  38224. break;
  38225. }
  38226. }
  38227. if (!has_closure) {
  38228. int flags;
  38229. flags = 0;
  38230. if (s->eval_type != JS_EVAL_TYPE_GLOBAL)
  38231. flags |= JS_PROP_CONFIGURABLE;
  38232. if (hf->cpool_idx >= 0 && !hf->is_lexical) {
  38233. /* global function definitions need a specific handling */
  38234. dbuf_putc(bc, OP_fclosure);
  38235. dbuf_put_u32(bc, hf->cpool_idx);
  38236. dbuf_putc(bc, OP_define_func);
  38237. dbuf_put_u32(bc, JS_DupAtom(ctx, hf->var_name));
  38238. dbuf_putc(bc, flags);
  38239. goto done_global_var;
  38240. } else {
  38241. if (hf->is_lexical) {
  38242. flags |= DEFINE_GLOBAL_LEX_VAR;
  38243. if (!hf->is_const)
  38244. flags |= JS_PROP_WRITABLE;
  38245. }
  38246. dbuf_putc(bc, OP_define_var);
  38247. dbuf_put_u32(bc, JS_DupAtom(ctx, hf->var_name));
  38248. dbuf_putc(bc, flags);
  38249. }
  38250. }
  38251. if (hf->cpool_idx >= 0 || force_init) {
  38252. if (hf->cpool_idx >= 0) {
  38253. dbuf_putc(bc, OP_fclosure);
  38254. dbuf_put_u32(bc, hf->cpool_idx);
  38255. if (hf->var_name == JS_ATOM__default_) {
  38256. /* set default export function name */
  38257. dbuf_putc(bc, OP_set_name);
  38258. dbuf_put_u32(bc, JS_DupAtom(ctx, JS_ATOM_default));
  38259. }
  38260. } else {
  38261. dbuf_putc(bc, OP_undefined);
  38262. }
  38263. if (has_closure == 2) {
  38264. dbuf_putc(bc, OP_put_var_ref);
  38265. dbuf_put_u16(bc, idx);
  38266. } else if (has_closure == 1) {
  38267. dbuf_putc(bc, OP_define_field);
  38268. dbuf_put_u32(bc, JS_DupAtom(ctx, hf->var_name));
  38269. dbuf_putc(bc, OP_drop);
  38270. } else {
  38271. /* XXX: Check if variable is writable and enumerable */
  38272. dbuf_putc(bc, OP_put_var);
  38273. dbuf_put_u32(bc, JS_DupAtom(ctx, hf->var_name));
  38274. }
  38275. }
  38276. done_global_var:
  38277. JS_FreeAtom(ctx, hf->var_name);
  38278. }
  38279. if (s->module) {
  38280. dbuf_putc(bc, OP_return_undef);
  38281. dbuf_putc(bc, OP_label);
  38282. dbuf_put_u32(bc, label_next);
  38283. s->label_slots[label_next].pos2 = bc->size;
  38284. }
  38285. js_free(ctx, s->global_vars);
  38286. s->global_vars = NULL;
  38287. s->global_var_count = 0;
  38288. s->global_var_size = 0;
  38289. }
  38290. static int skip_dead_code(JSFunctionDef *s, const uint8_t *bc_buf, int bc_len,
  38291. int pos, int *linep, int *colp)
  38292. {
  38293. int op, len, label;
  38294. for (; pos < bc_len; pos += len) {
  38295. op = bc_buf[pos];
  38296. len = opcode_info[op].size;
  38297. if (op == OP_source_loc) {
  38298. *linep = get_u32(bc_buf + pos + 1);
  38299. *colp = get_u32(bc_buf + pos + 5);
  38300. } else if (op == OP_label) {
  38301. label = get_u32(bc_buf + pos + 1);
  38302. if (update_label(s, label, 0) > 0)
  38303. break;
  38304. assert(s->label_slots[label].first_reloc == NULL);
  38305. } else {
  38306. /* XXX: output a warning for unreachable code? */
  38307. JSAtom atom;
  38308. switch(opcode_info[op].fmt) {
  38309. case OP_FMT_label:
  38310. case OP_FMT_label_u16:
  38311. label = get_u32(bc_buf + pos + 1);
  38312. update_label(s, label, -1);
  38313. break;
  38314. case OP_FMT_atom_label_u8:
  38315. case OP_FMT_atom_label_u16:
  38316. label = get_u32(bc_buf + pos + 5);
  38317. update_label(s, label, -1);
  38318. /* fall thru */
  38319. case OP_FMT_atom:
  38320. case OP_FMT_atom_u8:
  38321. case OP_FMT_atom_u16:
  38322. atom = get_u32(bc_buf + pos + 1);
  38323. JS_FreeAtom(s->ctx, atom);
  38324. break;
  38325. default:
  38326. break;
  38327. }
  38328. }
  38329. }
  38330. return pos;
  38331. }
  38332. static int get_label_pos(JSFunctionDef *s, int label)
  38333. {
  38334. int i, pos;
  38335. for (i = 0; i < 20; i++) {
  38336. pos = s->label_slots[label].pos;
  38337. for (;;) {
  38338. switch (s->byte_code.buf[pos]) {
  38339. case OP_source_loc:
  38340. pos += 9;
  38341. continue;
  38342. case OP_label:
  38343. pos += 5;
  38344. continue;
  38345. case OP_goto:
  38346. label = get_u32(s->byte_code.buf + pos + 1);
  38347. break;
  38348. default:
  38349. return pos;
  38350. }
  38351. break;
  38352. }
  38353. }
  38354. return pos;
  38355. }
  38356. /* convert global variable accesses to local variables or closure
  38357. variables when necessary */
  38358. static __exception int resolve_variables(JSContext *ctx, JSFunctionDef *s)
  38359. {
  38360. int pos, pos_next, bc_len, op, len, i, idx, line_num, col_num;
  38361. uint8_t *bc_buf;
  38362. JSAtom var_name;
  38363. DynBuf bc_out;
  38364. CodeContext cc;
  38365. int scope;
  38366. cc.bc_buf = bc_buf = s->byte_code.buf;
  38367. cc.bc_len = bc_len = s->byte_code.size;
  38368. js_dbuf_init(ctx, &bc_out);
  38369. /* first pass for runtime checks (must be done before the
  38370. variables are created) */
  38371. for(i = 0; i < s->global_var_count; i++) {
  38372. JSGlobalVar *hf = &s->global_vars[i];
  38373. int flags;
  38374. /* check if global variable (XXX: simplify) */
  38375. for(idx = 0; idx < s->closure_var_count; idx++) {
  38376. JSClosureVar *cv = &s->closure_var[idx];
  38377. if (cv->var_name == hf->var_name) {
  38378. if (s->eval_type == JS_EVAL_TYPE_DIRECT &&
  38379. cv->is_lexical) {
  38380. /* Check if a lexical variable is
  38381. redefined as 'var'. XXX: Could abort
  38382. compilation here, but for consistency
  38383. with the other checks, we delay the
  38384. error generation. */
  38385. dbuf_putc(&bc_out, OP_throw_error);
  38386. dbuf_put_u32(&bc_out, JS_DupAtom(ctx, hf->var_name));
  38387. dbuf_putc(&bc_out, JS_THROW_VAR_REDECL);
  38388. }
  38389. goto next;
  38390. }
  38391. if (cv->var_name == JS_ATOM__var_ ||
  38392. cv->var_name == JS_ATOM__arg_var_)
  38393. goto next;
  38394. }
  38395. dbuf_putc(&bc_out, OP_check_define_var);
  38396. dbuf_put_u32(&bc_out, JS_DupAtom(ctx, hf->var_name));
  38397. flags = 0;
  38398. if (hf->is_lexical)
  38399. flags |= DEFINE_GLOBAL_LEX_VAR;
  38400. if (hf->cpool_idx >= 0)
  38401. flags |= DEFINE_GLOBAL_FUNC_VAR;
  38402. dbuf_putc(&bc_out, flags);
  38403. next: ;
  38404. }
  38405. line_num = 0; /* avoid warning */
  38406. col_num = 0;
  38407. for (pos = 0; pos < bc_len; pos = pos_next) {
  38408. op = bc_buf[pos];
  38409. len = opcode_info[op].size;
  38410. pos_next = pos + len;
  38411. switch(op) {
  38412. case OP_source_loc:
  38413. line_num = get_u32(bc_buf + pos + 1);
  38414. col_num = get_u32(bc_buf + pos + 5);
  38415. s->source_loc_size++;
  38416. goto no_change;
  38417. case OP_eval: /* convert scope index to adjusted variable index */
  38418. {
  38419. int call_argc = get_u16(bc_buf + pos + 1);
  38420. scope = get_u16(bc_buf + pos + 1 + 2);
  38421. mark_eval_captured_variables(ctx, s, scope);
  38422. dbuf_putc(&bc_out, op);
  38423. dbuf_put_u16(&bc_out, call_argc);
  38424. dbuf_put_u16(&bc_out, s->scopes[scope].first + 1);
  38425. }
  38426. break;
  38427. case OP_apply_eval: /* convert scope index to adjusted variable index */
  38428. scope = get_u16(bc_buf + pos + 1);
  38429. mark_eval_captured_variables(ctx, s, scope);
  38430. dbuf_putc(&bc_out, op);
  38431. dbuf_put_u16(&bc_out, s->scopes[scope].first + 1);
  38432. break;
  38433. case OP_scope_get_var_undef:
  38434. case OP_scope_get_var:
  38435. case OP_scope_put_var:
  38436. case OP_scope_delete_var:
  38437. case OP_scope_get_ref:
  38438. case OP_scope_put_var_init:
  38439. var_name = get_u32(bc_buf + pos + 1);
  38440. scope = get_u16(bc_buf + pos + 5);
  38441. pos_next = resolve_scope_var(ctx, s, var_name, scope, op, &bc_out,
  38442. NULL, NULL, pos_next);
  38443. JS_FreeAtom(ctx, var_name);
  38444. break;
  38445. case OP_scope_make_ref:
  38446. {
  38447. int label;
  38448. LabelSlot *ls;
  38449. var_name = get_u32(bc_buf + pos + 1);
  38450. label = get_u32(bc_buf + pos + 5);
  38451. scope = get_u16(bc_buf + pos + 9);
  38452. ls = &s->label_slots[label];
  38453. ls->ref_count--; /* always remove label reference */
  38454. pos_next = resolve_scope_var(ctx, s, var_name, scope, op, &bc_out,
  38455. bc_buf, ls, pos_next);
  38456. JS_FreeAtom(ctx, var_name);
  38457. }
  38458. break;
  38459. case OP_scope_get_private_field:
  38460. case OP_scope_get_private_field2:
  38461. case OP_scope_put_private_field:
  38462. case OP_scope_in_private_field:
  38463. {
  38464. int ret;
  38465. var_name = get_u32(bc_buf + pos + 1);
  38466. scope = get_u16(bc_buf + pos + 5);
  38467. ret = resolve_scope_private_field(ctx, s, var_name, scope, op, &bc_out);
  38468. if (ret < 0)
  38469. goto fail;
  38470. JS_FreeAtom(ctx, var_name);
  38471. }
  38472. break;
  38473. case OP_gosub:
  38474. s->jump_size++;
  38475. {
  38476. /* remove calls to empty finalizers */
  38477. int label;
  38478. LabelSlot *ls;
  38479. label = get_u32(bc_buf + pos + 1);
  38480. assert(label >= 0 && label < s->label_count);
  38481. ls = &s->label_slots[label];
  38482. if (code_match(&cc, ls->pos, OP_ret, -1)) {
  38483. ls->ref_count--;
  38484. break;
  38485. }
  38486. }
  38487. goto no_change;
  38488. case OP_insert3:
  38489. /* Transformation: insert3 put_array_el|put_ref_value drop -> put_array_el|put_ref_value */
  38490. if (code_match(&cc, pos_next, M2(OP_put_array_el, OP_put_ref_value), OP_drop, -1)) {
  38491. dbuf_putc(&bc_out, cc.op);
  38492. pos_next = cc.pos;
  38493. if (cc.line_num == -1)
  38494. break;
  38495. if (cc.line_num != line_num || cc.col_num != col_num) {
  38496. line_num = cc.line_num;
  38497. col_num = cc.col_num;
  38498. s->source_loc_size++;
  38499. dbuf_putc(&bc_out, OP_source_loc);
  38500. dbuf_put_u32(&bc_out, line_num);
  38501. dbuf_put_u32(&bc_out, col_num);
  38502. }
  38503. break;
  38504. }
  38505. goto no_change;
  38506. case OP_goto:
  38507. s->jump_size++;
  38508. /* fall thru */
  38509. case OP_tail_call:
  38510. case OP_tail_call_method:
  38511. case OP_return:
  38512. case OP_return_undef:
  38513. case OP_throw:
  38514. case OP_throw_error:
  38515. case OP_ret:
  38516. {
  38517. /* remove dead code */
  38518. int line = -1;
  38519. int col = -1;
  38520. dbuf_put(&bc_out, bc_buf + pos, len);
  38521. pos = skip_dead_code(s, bc_buf, bc_len, pos + len,
  38522. &line, &col);
  38523. pos_next = pos;
  38524. if (line < 0 || pos >= bc_len)
  38525. break;
  38526. if (line_num != line || col_num != col) {
  38527. line_num = line;
  38528. col_num = col;
  38529. s->source_loc_size++;
  38530. dbuf_putc(&bc_out, OP_source_loc);
  38531. dbuf_put_u32(&bc_out, line_num);
  38532. dbuf_put_u32(&bc_out, col_num);
  38533. }
  38534. break;
  38535. }
  38536. goto no_change;
  38537. case OP_label:
  38538. {
  38539. int label;
  38540. LabelSlot *ls;
  38541. label = get_u32(bc_buf + pos + 1);
  38542. assert(label >= 0 && label < s->label_count);
  38543. ls = &s->label_slots[label];
  38544. ls->pos2 = bc_out.size + opcode_info[op].size;
  38545. }
  38546. goto no_change;
  38547. case OP_enter_scope:
  38548. {
  38549. int scope_idx, scope = get_u16(bc_buf + pos + 1);
  38550. if (scope == s->body_scope) {
  38551. instantiate_hoisted_definitions(ctx, s, &bc_out);
  38552. }
  38553. for(scope_idx = s->scopes[scope].first; scope_idx >= 0;) {
  38554. JSVarDef *vd = &s->vars[scope_idx];
  38555. if (vd->scope_level == scope) {
  38556. if (scope_idx != s->arguments_arg_idx) {
  38557. if (vd->var_kind == JS_VAR_FUNCTION_DECL ||
  38558. vd->var_kind == JS_VAR_NEW_FUNCTION_DECL) {
  38559. /* Initialize lexical variable upon entering scope */
  38560. dbuf_putc(&bc_out, OP_fclosure);
  38561. dbuf_put_u32(&bc_out, vd->func_pool_idx);
  38562. dbuf_putc(&bc_out, OP_put_loc);
  38563. dbuf_put_u16(&bc_out, scope_idx);
  38564. } else {
  38565. /* XXX: should check if variable can be used
  38566. before initialization */
  38567. dbuf_putc(&bc_out, OP_set_loc_uninitialized);
  38568. dbuf_put_u16(&bc_out, scope_idx);
  38569. }
  38570. }
  38571. scope_idx = vd->scope_next;
  38572. } else {
  38573. break;
  38574. }
  38575. }
  38576. }
  38577. break;
  38578. case OP_leave_scope:
  38579. {
  38580. int scope_idx, scope = get_u16(bc_buf + pos + 1);
  38581. for(scope_idx = s->scopes[scope].first; scope_idx >= 0;) {
  38582. JSVarDef *vd = &s->vars[scope_idx];
  38583. if (vd->scope_level == scope) {
  38584. if (vd->is_captured) {
  38585. dbuf_putc(&bc_out, OP_close_loc);
  38586. dbuf_put_u16(&bc_out, scope_idx);
  38587. }
  38588. scope_idx = vd->scope_next;
  38589. } else {
  38590. break;
  38591. }
  38592. }
  38593. }
  38594. break;
  38595. case OP_set_name:
  38596. {
  38597. /* remove dummy set_name opcodes */
  38598. JSAtom name = get_u32(bc_buf + pos + 1);
  38599. if (name == JS_ATOM_NULL)
  38600. break;
  38601. }
  38602. goto no_change;
  38603. case OP_if_false:
  38604. case OP_if_true:
  38605. case OP_catch:
  38606. s->jump_size++;
  38607. goto no_change;
  38608. case OP_dup:
  38609. /* Transformation: dup if_false(l1) drop, l1: if_false(l2) -> if_false(l2) */
  38610. /* Transformation: dup if_true(l1) drop, l1: if_true(l2) -> if_true(l2) */
  38611. if (code_match(&cc, pos_next, M2(OP_if_false, OP_if_true), OP_drop, -1)) {
  38612. int lab0, lab1, op1, pos1, line1, col1, pos2;
  38613. lab0 = lab1 = cc.label;
  38614. assert(lab1 >= 0 && lab1 < s->label_count);
  38615. op1 = cc.op;
  38616. pos1 = cc.pos;
  38617. line1 = cc.line_num;
  38618. col1 = cc.col_num;
  38619. while (code_match(&cc, (pos2 = get_label_pos(s, lab1)), OP_dup, op1, OP_drop, -1)) {
  38620. lab1 = cc.label;
  38621. }
  38622. if (code_match(&cc, pos2, op1, -1)) {
  38623. s->jump_size++;
  38624. update_label(s, lab0, -1);
  38625. update_label(s, cc.label, +1);
  38626. dbuf_putc(&bc_out, op1);
  38627. dbuf_put_u32(&bc_out, cc.label);
  38628. pos_next = pos1;
  38629. if (line1 == -1)
  38630. break;
  38631. if (line1 != line_num || col1 != col_num) {
  38632. line_num = line1;
  38633. col_num = col1;
  38634. s->source_loc_size++;
  38635. dbuf_putc(&bc_out, OP_source_loc);
  38636. dbuf_put_u32(&bc_out, line_num);
  38637. dbuf_put_u32(&bc_out, col_num);
  38638. }
  38639. break;
  38640. }
  38641. }
  38642. goto no_change;
  38643. case OP_nop:
  38644. /* remove erased code */
  38645. break;
  38646. case OP_set_class_name:
  38647. /* only used during parsing */
  38648. break;
  38649. case OP_get_field_opt_chain: /* equivalent to OP_get_field */
  38650. {
  38651. JSAtom name = get_u32(bc_buf + pos + 1);
  38652. dbuf_putc(&bc_out, OP_get_field);
  38653. dbuf_put_u32(&bc_out, name);
  38654. }
  38655. break;
  38656. case OP_get_array_el_opt_chain: /* equivalent to OP_get_array_el */
  38657. dbuf_putc(&bc_out, OP_get_array_el);
  38658. break;
  38659. default:
  38660. no_change:
  38661. dbuf_put(&bc_out, bc_buf + pos, len);
  38662. break;
  38663. }
  38664. }
  38665. /* set the new byte code */
  38666. dbuf_free(&s->byte_code);
  38667. s->byte_code = bc_out;
  38668. if (dbuf_error(&s->byte_code)) {
  38669. JS_ThrowOutOfMemory(ctx);
  38670. return -1;
  38671. }
  38672. return 0;
  38673. fail:
  38674. /* continue the copy to keep the atom refcounts consistent */
  38675. /* XXX: find a better solution ? */
  38676. for (; pos < bc_len; pos = pos_next) {
  38677. op = bc_buf[pos];
  38678. len = opcode_info[op].size;
  38679. pos_next = pos + len;
  38680. dbuf_put(&bc_out, bc_buf + pos, len);
  38681. }
  38682. dbuf_free(&s->byte_code);
  38683. s->byte_code = bc_out;
  38684. return -1;
  38685. }
  38686. /* the pc2line table gives a line number for each PC value */
  38687. static void add_pc2line_info(JSFunctionDef *s, uint32_t pc,
  38688. int line_num, int col_num)
  38689. {
  38690. if (s->source_loc_slots == NULL)
  38691. return;
  38692. if (s->source_loc_count >= s->source_loc_size)
  38693. return;
  38694. if (pc < s->line_number_last_pc)
  38695. return;
  38696. if (line_num == s->line_number_last)
  38697. if (col_num == s->col_number_last)
  38698. return;
  38699. s->source_loc_slots[s->source_loc_count].pc = pc;
  38700. s->source_loc_slots[s->source_loc_count].line_num = line_num;
  38701. s->source_loc_slots[s->source_loc_count].col_num = col_num;
  38702. s->source_loc_count++;
  38703. s->line_number_last_pc = pc;
  38704. s->line_number_last = line_num;
  38705. s->col_number_last = col_num;
  38706. }
  38707. static void compute_pc2line_info(JSFunctionDef *s)
  38708. {
  38709. if (s->source_loc_slots) {
  38710. int last_line_num = s->line_num;
  38711. int last_col_num = s->col_num;
  38712. uint32_t last_pc = 0;
  38713. int i;
  38714. js_dbuf_init(s->ctx, &s->pc2line);
  38715. for (i = 0; i < s->source_loc_count; i++) {
  38716. uint32_t pc = s->source_loc_slots[i].pc;
  38717. int line_num = s->source_loc_slots[i].line_num;
  38718. int col_num = s->source_loc_slots[i].col_num;
  38719. int diff_pc, diff_line, diff_col;
  38720. if (line_num < 0)
  38721. continue;
  38722. diff_pc = pc - last_pc;
  38723. if (diff_pc < 0)
  38724. continue;
  38725. diff_line = line_num - last_line_num;
  38726. diff_col = col_num - last_col_num;
  38727. if (diff_line == 0 && diff_col == 0)
  38728. continue;
  38729. if (diff_line >= PC2LINE_BASE &&
  38730. diff_line < PC2LINE_BASE + PC2LINE_RANGE &&
  38731. diff_pc <= PC2LINE_DIFF_PC_MAX) {
  38732. dbuf_putc(&s->pc2line, (diff_line - PC2LINE_BASE) +
  38733. diff_pc * PC2LINE_RANGE + PC2LINE_OP_FIRST);
  38734. } else {
  38735. /* longer encoding */
  38736. dbuf_putc(&s->pc2line, 0);
  38737. dbuf_put_leb128(&s->pc2line, diff_pc);
  38738. dbuf_put_sleb128(&s->pc2line, diff_line);
  38739. }
  38740. dbuf_put_sleb128(&s->pc2line, diff_col);
  38741. last_pc = pc;
  38742. last_line_num = line_num;
  38743. last_col_num = col_num;
  38744. }
  38745. }
  38746. }
  38747. static RelocEntry *add_reloc(JSContext *ctx, LabelSlot *ls, uint32_t addr, int size)
  38748. {
  38749. RelocEntry *re;
  38750. re = js_malloc(ctx, sizeof(*re));
  38751. if (!re)
  38752. return NULL;
  38753. re->addr = addr;
  38754. re->size = size;
  38755. re->next = ls->first_reloc;
  38756. ls->first_reloc = re;
  38757. return re;
  38758. }
  38759. static bool code_has_label(CodeContext *s, int pos, int label)
  38760. {
  38761. while (pos < s->bc_len) {
  38762. int op = s->bc_buf[pos];
  38763. if (op == OP_source_loc) {
  38764. pos += 9;
  38765. continue;
  38766. }
  38767. if (op == OP_label) {
  38768. int lab = get_u32(s->bc_buf + pos + 1);
  38769. if (lab == label)
  38770. return true;
  38771. pos += 5;
  38772. continue;
  38773. }
  38774. if (op == OP_goto) {
  38775. int lab = get_u32(s->bc_buf + pos + 1);
  38776. if (lab == label)
  38777. return true;
  38778. }
  38779. break;
  38780. }
  38781. return false;
  38782. }
  38783. /* return the target label, following the OP_goto jumps
  38784. the first opcode at destination is stored in *pop
  38785. */
  38786. static int find_jump_target(JSFunctionDef *s, int label, int *pop)
  38787. {
  38788. int i, pos, op;
  38789. update_label(s, label, -1);
  38790. for (i = 0; i < 10; i++) {
  38791. assert(label >= 0 && label < s->label_count);
  38792. pos = s->label_slots[label].pos2;
  38793. for (;;) {
  38794. switch(op = s->byte_code.buf[pos]) {
  38795. case OP_source_loc:
  38796. case OP_label:
  38797. pos += opcode_info[op].size;
  38798. continue;
  38799. case OP_goto:
  38800. label = get_u32(s->byte_code.buf + pos + 1);
  38801. break;
  38802. case OP_drop:
  38803. /* ignore drop opcodes if followed by OP_return_undef */
  38804. while (s->byte_code.buf[++pos] == OP_drop)
  38805. continue;
  38806. if (s->byte_code.buf[pos] == OP_return_undef)
  38807. op = OP_return_undef;
  38808. /* fall thru */
  38809. default:
  38810. goto done;
  38811. }
  38812. break;
  38813. }
  38814. }
  38815. /* cycle detected, could issue a warning */
  38816. done:
  38817. *pop = op;
  38818. update_label(s, label, +1);
  38819. return label;
  38820. }
  38821. static void push_short_int(DynBuf *bc_out, int val)
  38822. {
  38823. if (val >= -1 && val <= 7) {
  38824. dbuf_putc(bc_out, OP_push_0 + val);
  38825. return;
  38826. }
  38827. if (val == (int8_t)val) {
  38828. dbuf_putc(bc_out, OP_push_i8);
  38829. dbuf_putc(bc_out, val);
  38830. return;
  38831. }
  38832. if (val == (int16_t)val) {
  38833. dbuf_putc(bc_out, OP_push_i16);
  38834. dbuf_put_u16(bc_out, val);
  38835. return;
  38836. }
  38837. dbuf_putc(bc_out, OP_push_i32);
  38838. dbuf_put_u32(bc_out, val);
  38839. }
  38840. static void put_short_code(DynBuf *bc_out, int op, int idx)
  38841. {
  38842. if (idx < 4) {
  38843. switch (op) {
  38844. case OP_get_loc:
  38845. dbuf_putc(bc_out, OP_get_loc0 + idx);
  38846. return;
  38847. case OP_put_loc:
  38848. dbuf_putc(bc_out, OP_put_loc0 + idx);
  38849. return;
  38850. case OP_set_loc:
  38851. dbuf_putc(bc_out, OP_set_loc0 + idx);
  38852. return;
  38853. case OP_get_arg:
  38854. dbuf_putc(bc_out, OP_get_arg0 + idx);
  38855. return;
  38856. case OP_put_arg:
  38857. dbuf_putc(bc_out, OP_put_arg0 + idx);
  38858. return;
  38859. case OP_set_arg:
  38860. dbuf_putc(bc_out, OP_set_arg0 + idx);
  38861. return;
  38862. case OP_get_var_ref:
  38863. dbuf_putc(bc_out, OP_get_var_ref0 + idx);
  38864. return;
  38865. case OP_put_var_ref:
  38866. dbuf_putc(bc_out, OP_put_var_ref0 + idx);
  38867. return;
  38868. case OP_set_var_ref:
  38869. dbuf_putc(bc_out, OP_set_var_ref0 + idx);
  38870. return;
  38871. case OP_call:
  38872. dbuf_putc(bc_out, OP_call0 + idx);
  38873. return;
  38874. }
  38875. }
  38876. if (idx < 256) {
  38877. switch (op) {
  38878. case OP_get_loc:
  38879. dbuf_putc(bc_out, OP_get_loc8);
  38880. dbuf_putc(bc_out, idx);
  38881. return;
  38882. case OP_put_loc:
  38883. dbuf_putc(bc_out, OP_put_loc8);
  38884. dbuf_putc(bc_out, idx);
  38885. return;
  38886. case OP_set_loc:
  38887. dbuf_putc(bc_out, OP_set_loc8);
  38888. dbuf_putc(bc_out, idx);
  38889. return;
  38890. }
  38891. }
  38892. dbuf_putc(bc_out, op);
  38893. dbuf_put_u16(bc_out, idx);
  38894. }
  38895. /* peephole optimizations and resolve goto/labels */
  38896. static __exception int resolve_labels(JSContext *ctx, JSFunctionDef *s)
  38897. {
  38898. int pos, pos_next, bc_len, op, op1, len, i, line_num, col_num, patch_offsets;
  38899. const uint8_t *bc_buf;
  38900. DynBuf bc_out;
  38901. LabelSlot *label_slots, *ls;
  38902. RelocEntry *re, *re_next;
  38903. CodeContext cc;
  38904. int label;
  38905. JumpSlot *jp;
  38906. label_slots = s->label_slots;
  38907. line_num = s->line_num;
  38908. col_num = s->col_num;
  38909. cc.bc_buf = bc_buf = s->byte_code.buf;
  38910. cc.bc_len = bc_len = s->byte_code.size;
  38911. js_dbuf_init(ctx, &bc_out);
  38912. if (s->jump_size) {
  38913. s->jump_slots = js_mallocz(s->ctx, sizeof(*s->jump_slots) * s->jump_size);
  38914. if (s->jump_slots == NULL)
  38915. return -1;
  38916. }
  38917. if (s->source_loc_size) {
  38918. s->source_loc_slots = js_mallocz(s->ctx, sizeof(*s->source_loc_slots) * s->source_loc_size);
  38919. if (s->source_loc_slots == NULL)
  38920. return -1;
  38921. s->line_number_last = s->line_num;
  38922. s->col_number_last = s->col_num;
  38923. s->line_number_last_pc = 0;
  38924. }
  38925. /* initialize the 'home_object' variable if needed */
  38926. if (s->home_object_var_idx >= 0) {
  38927. dbuf_putc(&bc_out, OP_special_object);
  38928. dbuf_putc(&bc_out, OP_SPECIAL_OBJECT_HOME_OBJECT);
  38929. put_short_code(&bc_out, OP_put_loc, s->home_object_var_idx);
  38930. }
  38931. /* initialize the 'this.active_func' variable if needed */
  38932. if (s->this_active_func_var_idx >= 0) {
  38933. dbuf_putc(&bc_out, OP_special_object);
  38934. dbuf_putc(&bc_out, OP_SPECIAL_OBJECT_THIS_FUNC);
  38935. put_short_code(&bc_out, OP_put_loc, s->this_active_func_var_idx);
  38936. }
  38937. /* initialize the 'new.target' variable if needed */
  38938. if (s->new_target_var_idx >= 0) {
  38939. dbuf_putc(&bc_out, OP_special_object);
  38940. dbuf_putc(&bc_out, OP_SPECIAL_OBJECT_NEW_TARGET);
  38941. put_short_code(&bc_out, OP_put_loc, s->new_target_var_idx);
  38942. }
  38943. /* initialize the 'this' variable if needed. In a derived class
  38944. constructor, this is initially uninitialized. */
  38945. if (s->this_var_idx >= 0) {
  38946. if (s->is_derived_class_constructor) {
  38947. dbuf_putc(&bc_out, OP_set_loc_uninitialized);
  38948. dbuf_put_u16(&bc_out, s->this_var_idx);
  38949. } else {
  38950. dbuf_putc(&bc_out, OP_push_this);
  38951. put_short_code(&bc_out, OP_put_loc, s->this_var_idx);
  38952. }
  38953. }
  38954. /* initialize the 'arguments' variable if needed */
  38955. if (s->arguments_var_idx >= 0) {
  38956. if (s->is_strict_mode || !s->has_simple_parameter_list) {
  38957. dbuf_putc(&bc_out, OP_special_object);
  38958. dbuf_putc(&bc_out, OP_SPECIAL_OBJECT_ARGUMENTS);
  38959. } else {
  38960. dbuf_putc(&bc_out, OP_special_object);
  38961. dbuf_putc(&bc_out, OP_SPECIAL_OBJECT_MAPPED_ARGUMENTS);
  38962. }
  38963. if (s->arguments_arg_idx >= 0)
  38964. put_short_code(&bc_out, OP_set_loc, s->arguments_arg_idx);
  38965. put_short_code(&bc_out, OP_put_loc, s->arguments_var_idx);
  38966. }
  38967. /* initialize a reference to the current function if needed */
  38968. if (s->func_var_idx >= 0) {
  38969. dbuf_putc(&bc_out, OP_special_object);
  38970. dbuf_putc(&bc_out, OP_SPECIAL_OBJECT_THIS_FUNC);
  38971. put_short_code(&bc_out, OP_put_loc, s->func_var_idx);
  38972. }
  38973. /* initialize the variable environment object if needed */
  38974. if (s->var_object_idx >= 0) {
  38975. dbuf_putc(&bc_out, OP_special_object);
  38976. dbuf_putc(&bc_out, OP_SPECIAL_OBJECT_VAR_OBJECT);
  38977. put_short_code(&bc_out, OP_put_loc, s->var_object_idx);
  38978. }
  38979. if (s->arg_var_object_idx >= 0) {
  38980. dbuf_putc(&bc_out, OP_special_object);
  38981. dbuf_putc(&bc_out, OP_SPECIAL_OBJECT_VAR_OBJECT);
  38982. put_short_code(&bc_out, OP_put_loc, s->arg_var_object_idx);
  38983. }
  38984. for (pos = 0; pos < bc_len; pos = pos_next) {
  38985. int val;
  38986. op = bc_buf[pos];
  38987. len = opcode_info[op].size;
  38988. pos_next = pos + len;
  38989. switch(op) {
  38990. case OP_source_loc:
  38991. /* line number info (for debug). We put it in a separate
  38992. compressed table to reduce memory usage and get better
  38993. performance */
  38994. line_num = get_u32(bc_buf + pos + 1);
  38995. col_num = get_u32(bc_buf + pos + 5);
  38996. break;
  38997. case OP_label:
  38998. {
  38999. label = get_u32(bc_buf + pos + 1);
  39000. assert(label >= 0 && label < s->label_count);
  39001. ls = &label_slots[label];
  39002. assert(ls->addr == -1);
  39003. ls->addr = bc_out.size;
  39004. /* resolve the relocation entries */
  39005. for(re = ls->first_reloc; re != NULL; re = re_next) {
  39006. int diff = ls->addr - re->addr;
  39007. re_next = re->next;
  39008. switch (re->size) {
  39009. case 4:
  39010. put_u32(bc_out.buf + re->addr, diff);
  39011. break;
  39012. case 2:
  39013. assert(diff == (int16_t)diff);
  39014. put_u16(bc_out.buf + re->addr, diff);
  39015. break;
  39016. case 1:
  39017. assert(diff == (int8_t)diff);
  39018. put_u8(bc_out.buf + re->addr, diff);
  39019. break;
  39020. }
  39021. js_free(ctx, re);
  39022. }
  39023. ls->first_reloc = NULL;
  39024. }
  39025. break;
  39026. case OP_call:
  39027. case OP_call_method:
  39028. {
  39029. /* detect and transform tail calls */
  39030. int argc;
  39031. argc = get_u16(bc_buf + pos + 1);
  39032. if (code_match(&cc, pos_next, OP_return, -1)) {
  39033. if (cc.line_num >= 0) line_num = cc.line_num;
  39034. if (cc.col_num >= 0) col_num = cc.col_num;
  39035. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39036. put_short_code(&bc_out, op + 1, argc);
  39037. pos_next = skip_dead_code(s, bc_buf, bc_len, cc.pos,
  39038. &line_num, &col_num);
  39039. break;
  39040. }
  39041. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39042. put_short_code(&bc_out, op, argc);
  39043. break;
  39044. }
  39045. goto no_change;
  39046. case OP_return:
  39047. case OP_return_undef:
  39048. case OP_return_async:
  39049. case OP_throw:
  39050. case OP_throw_error:
  39051. pos_next = skip_dead_code(s, bc_buf, bc_len, pos_next,
  39052. &line_num, &col_num);
  39053. goto no_change;
  39054. case OP_goto:
  39055. label = get_u32(bc_buf + pos + 1);
  39056. has_goto:
  39057. {
  39058. /* Use custom matcher because multiple labels can follow */
  39059. label = find_jump_target(s, label, &op1);
  39060. if (code_has_label(&cc, pos_next, label)) {
  39061. /* jump to next instruction: remove jump */
  39062. update_label(s, label, -1);
  39063. break;
  39064. }
  39065. if (op1 == OP_return || op1 == OP_return_undef || op1 == OP_throw) {
  39066. /* jump to return/throw: remove jump, append return/throw */
  39067. /* updating the line number obfuscates assembly listing */
  39068. update_label(s, label, -1);
  39069. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39070. dbuf_putc(&bc_out, op1);
  39071. pos_next = skip_dead_code(s, bc_buf, bc_len, pos_next,
  39072. &line_num, &col_num);
  39073. break;
  39074. }
  39075. /* XXX: should duplicate single instructions followed by goto or return */
  39076. /* For example, can match one of these followed by return:
  39077. push_i32 / push_const / push_atom_value / get_var /
  39078. undefined / null / push_false / push_true / get_ref_value /
  39079. get_loc / get_arg / get_var_ref
  39080. */
  39081. }
  39082. goto has_label;
  39083. case OP_gosub:
  39084. label = get_u32(bc_buf + pos + 1);
  39085. goto has_label;
  39086. case OP_catch:
  39087. label = get_u32(bc_buf + pos + 1);
  39088. goto has_label;
  39089. case OP_if_true:
  39090. case OP_if_false:
  39091. label = get_u32(bc_buf + pos + 1);
  39092. label = find_jump_target(s, label, &op1);
  39093. /* transform if_false/if_true(l1) label(l1) -> drop label(l1) */
  39094. if (code_has_label(&cc, pos_next, label)) {
  39095. update_label(s, label, -1);
  39096. dbuf_putc(&bc_out, OP_drop);
  39097. break;
  39098. }
  39099. /* transform if_false(l1) goto(l2) label(l1) -> if_false(l2) label(l1) */
  39100. if (code_match(&cc, pos_next, OP_goto, -1)) {
  39101. int pos1 = cc.pos;
  39102. int line1 = cc.line_num;
  39103. int col1 = cc.col_num;
  39104. if (code_has_label(&cc, pos1, label)) {
  39105. if (line1 >= 0) line_num = line1;
  39106. if (col1 >= 0) col_num = col1;
  39107. pos_next = pos1;
  39108. update_label(s, label, -1);
  39109. label = cc.label;
  39110. op ^= OP_if_true ^ OP_if_false;
  39111. }
  39112. }
  39113. has_label:
  39114. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39115. if (op == OP_goto) {
  39116. pos_next = skip_dead_code(s, bc_buf, bc_len, pos_next,
  39117. &line_num, &col_num);
  39118. }
  39119. assert(label >= 0 && label < s->label_count);
  39120. ls = &label_slots[label];
  39121. jp = &s->jump_slots[s->jump_count++];
  39122. jp->op = op;
  39123. jp->size = 4;
  39124. jp->pos = bc_out.size + 1;
  39125. jp->label = label;
  39126. if (ls->addr == -1) {
  39127. int diff = ls->pos2 - pos - 1;
  39128. if (diff < 128 && (op == OP_if_false || op == OP_if_true || op == OP_goto)) {
  39129. jp->size = 1;
  39130. jp->op = OP_if_false8 + (op - OP_if_false);
  39131. dbuf_putc(&bc_out, OP_if_false8 + (op - OP_if_false));
  39132. dbuf_putc(&bc_out, 0);
  39133. if (!add_reloc(ctx, ls, bc_out.size - 1, 1))
  39134. goto fail;
  39135. break;
  39136. }
  39137. if (diff < 32768 && op == OP_goto) {
  39138. jp->size = 2;
  39139. jp->op = OP_goto16;
  39140. dbuf_putc(&bc_out, OP_goto16);
  39141. dbuf_put_u16(&bc_out, 0);
  39142. if (!add_reloc(ctx, ls, bc_out.size - 2, 2))
  39143. goto fail;
  39144. break;
  39145. }
  39146. } else {
  39147. int diff = ls->addr - bc_out.size - 1;
  39148. if (diff == (int8_t)diff && (op == OP_if_false || op == OP_if_true || op == OP_goto)) {
  39149. jp->size = 1;
  39150. jp->op = OP_if_false8 + (op - OP_if_false);
  39151. dbuf_putc(&bc_out, OP_if_false8 + (op - OP_if_false));
  39152. dbuf_putc(&bc_out, diff);
  39153. break;
  39154. }
  39155. if (diff == (int16_t)diff && op == OP_goto) {
  39156. jp->size = 2;
  39157. jp->op = OP_goto16;
  39158. dbuf_putc(&bc_out, OP_goto16);
  39159. dbuf_put_u16(&bc_out, diff);
  39160. break;
  39161. }
  39162. }
  39163. dbuf_putc(&bc_out, op);
  39164. dbuf_put_u32(&bc_out, ls->addr - bc_out.size);
  39165. if (ls->addr == -1) {
  39166. /* unresolved yet: create a new relocation entry */
  39167. if (!add_reloc(ctx, ls, bc_out.size - 4, 4))
  39168. goto fail;
  39169. }
  39170. break;
  39171. case OP_with_get_var:
  39172. case OP_with_put_var:
  39173. case OP_with_delete_var:
  39174. case OP_with_make_ref:
  39175. case OP_with_get_ref:
  39176. case OP_with_get_ref_undef:
  39177. {
  39178. JSAtom atom;
  39179. int is_with;
  39180. atom = get_u32(bc_buf + pos + 1);
  39181. label = get_u32(bc_buf + pos + 5);
  39182. is_with = bc_buf[pos + 9];
  39183. label = find_jump_target(s, label, &op1);
  39184. assert(label >= 0 && label < s->label_count);
  39185. ls = &label_slots[label];
  39186. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39187. jp = &s->jump_slots[s->jump_count++];
  39188. jp->op = op;
  39189. jp->size = 4;
  39190. jp->pos = bc_out.size + 5;
  39191. jp->label = label;
  39192. dbuf_putc(&bc_out, op);
  39193. dbuf_put_u32(&bc_out, atom);
  39194. dbuf_put_u32(&bc_out, ls->addr - bc_out.size);
  39195. if (ls->addr == -1) {
  39196. /* unresolved yet: create a new relocation entry */
  39197. if (!add_reloc(ctx, ls, bc_out.size - 4, 4))
  39198. goto fail;
  39199. }
  39200. dbuf_putc(&bc_out, is_with);
  39201. }
  39202. break;
  39203. case OP_drop:
  39204. /* remove useless drops before return */
  39205. if (code_match(&cc, pos_next, OP_return_undef, -1)) {
  39206. if (cc.line_num >= 0) line_num = cc.line_num;
  39207. if (cc.col_num >= 0) col_num = cc.col_num;
  39208. break;
  39209. }
  39210. goto no_change;
  39211. case OP_null:
  39212. /* transform null strict_eq into is_null */
  39213. if (code_match(&cc, pos_next, OP_strict_eq, -1)) {
  39214. if (cc.line_num >= 0) line_num = cc.line_num;
  39215. if (cc.col_num >= 0) col_num = cc.col_num;
  39216. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39217. dbuf_putc(&bc_out, OP_is_null);
  39218. pos_next = cc.pos;
  39219. break;
  39220. }
  39221. /* transform null strict_neq if_false/if_true -> is_null if_true/if_false */
  39222. if (code_match(&cc, pos_next, OP_strict_neq, M2(OP_if_false, OP_if_true), -1)) {
  39223. if (cc.line_num >= 0) line_num = cc.line_num;
  39224. if (cc.col_num >= 0) col_num = cc.col_num;
  39225. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39226. dbuf_putc(&bc_out, OP_is_null);
  39227. pos_next = cc.pos;
  39228. label = cc.label;
  39229. op = cc.op ^ OP_if_false ^ OP_if_true;
  39230. goto has_label;
  39231. }
  39232. /* fall thru */
  39233. case OP_push_false:
  39234. case OP_push_true:
  39235. val = (op == OP_push_true);
  39236. if (code_match(&cc, pos_next, M2(OP_if_false, OP_if_true), -1)) {
  39237. has_constant_test:
  39238. if (cc.line_num >= 0) line_num = cc.line_num;
  39239. if (cc.col_num >= 0) col_num = cc.col_num;
  39240. if (val == cc.op - OP_if_false) {
  39241. /* transform null if_false(l1) -> goto l1 */
  39242. /* transform false if_false(l1) -> goto l1 */
  39243. /* transform true if_true(l1) -> goto l1 */
  39244. pos_next = cc.pos;
  39245. op = OP_goto;
  39246. label = cc.label;
  39247. goto has_goto;
  39248. } else {
  39249. /* transform null if_true(l1) -> nop */
  39250. /* transform false if_true(l1) -> nop */
  39251. /* transform true if_false(l1) -> nop */
  39252. pos_next = cc.pos;
  39253. update_label(s, cc.label, -1);
  39254. break;
  39255. }
  39256. }
  39257. goto no_change;
  39258. case OP_push_i32:
  39259. /* transform i32(val) neg -> i32(-val) */
  39260. val = get_i32(bc_buf + pos + 1);
  39261. if ((val != INT32_MIN && val != 0)
  39262. && code_match(&cc, pos_next, OP_neg, -1)) {
  39263. if (cc.line_num >= 0) line_num = cc.line_num;
  39264. if (cc.col_num >= 0) col_num = cc.col_num;
  39265. if (code_match(&cc, cc.pos, OP_drop, -1)) {
  39266. if (cc.line_num >= 0) line_num = cc.line_num;
  39267. if (cc.col_num >= 0) col_num = cc.col_num;
  39268. } else {
  39269. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39270. push_short_int(&bc_out, -val);
  39271. }
  39272. pos_next = cc.pos;
  39273. break;
  39274. }
  39275. /* remove push/drop pairs generated by the parser */
  39276. if (code_match(&cc, pos_next, OP_drop, -1)) {
  39277. if (cc.line_num >= 0) line_num = cc.line_num;
  39278. if (cc.col_num >= 0) col_num = cc.col_num;
  39279. pos_next = cc.pos;
  39280. break;
  39281. }
  39282. /* Optimize constant tests: `if (0)`, `if (1)`, `if (!0)`... */
  39283. if (code_match(&cc, pos_next, M2(OP_if_false, OP_if_true), -1)) {
  39284. val = (val != 0);
  39285. goto has_constant_test;
  39286. }
  39287. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39288. push_short_int(&bc_out, val);
  39289. break;
  39290. case OP_push_const:
  39291. case OP_fclosure:
  39292. {
  39293. int idx = get_u32(bc_buf + pos + 1);
  39294. if (idx < 256) {
  39295. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39296. dbuf_putc(&bc_out, OP_push_const8 + op - OP_push_const);
  39297. dbuf_putc(&bc_out, idx);
  39298. break;
  39299. }
  39300. }
  39301. goto no_change;
  39302. case OP_get_field:
  39303. {
  39304. JSAtom atom = get_u32(bc_buf + pos + 1);
  39305. if (atom == JS_ATOM_length) {
  39306. JS_FreeAtom(ctx, atom);
  39307. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39308. dbuf_putc(&bc_out, OP_get_length);
  39309. break;
  39310. }
  39311. }
  39312. goto no_change;
  39313. case OP_push_atom_value:
  39314. {
  39315. JSAtom atom = get_u32(bc_buf + pos + 1);
  39316. /* remove push/drop pairs generated by the parser */
  39317. if (code_match(&cc, pos_next, OP_drop, -1)) {
  39318. JS_FreeAtom(ctx, atom);
  39319. if (cc.line_num >= 0) line_num = cc.line_num;
  39320. if (cc.col_num >= 0) col_num = cc.col_num;
  39321. pos_next = cc.pos;
  39322. break;
  39323. }
  39324. if (atom == JS_ATOM_empty_string) {
  39325. JS_FreeAtom(ctx, atom);
  39326. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39327. dbuf_putc(&bc_out, OP_push_empty_string);
  39328. break;
  39329. }
  39330. }
  39331. goto no_change;
  39332. case OP_to_propkey:
  39333. case OP_to_propkey2:
  39334. /* remove redundant to_propkey/to_propkey2 opcodes when storing simple data */
  39335. if (code_match(&cc, pos_next, M3(OP_get_loc, OP_get_arg, OP_get_var_ref), -1, OP_put_array_el, -1)
  39336. || code_match(&cc, pos_next, M3(OP_push_i32, OP_push_const, OP_push_atom_value), OP_put_array_el, -1)
  39337. || code_match(&cc, pos_next, M4(OP_undefined, OP_null, OP_push_true, OP_push_false), OP_put_array_el, -1)) {
  39338. break;
  39339. }
  39340. goto no_change;
  39341. case OP_undefined:
  39342. /* remove push/drop pairs generated by the parser */
  39343. if (code_match(&cc, pos_next, OP_drop, -1)) {
  39344. if (cc.line_num >= 0) line_num = cc.line_num;
  39345. if (cc.col_num >= 0) col_num = cc.col_num;
  39346. pos_next = cc.pos;
  39347. break;
  39348. }
  39349. /* transform undefined return -> return_undefined */
  39350. if (code_match(&cc, pos_next, OP_return, -1)) {
  39351. if (cc.line_num >= 0) line_num = cc.line_num;
  39352. if (cc.col_num >= 0) col_num = cc.col_num;
  39353. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39354. dbuf_putc(&bc_out, OP_return_undef);
  39355. pos_next = cc.pos;
  39356. break;
  39357. }
  39358. /* transform undefined if_true(l1)/if_false(l1) -> nop/goto(l1) */
  39359. if (code_match(&cc, pos_next, M2(OP_if_false, OP_if_true), -1)) {
  39360. val = 0;
  39361. goto has_constant_test;
  39362. }
  39363. /* transform undefined strict_eq -> is_undefined */
  39364. if (code_match(&cc, pos_next, OP_strict_eq, -1)) {
  39365. if (cc.line_num >= 0) line_num = cc.line_num;
  39366. if (cc.col_num >= 0) col_num = cc.col_num;
  39367. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39368. dbuf_putc(&bc_out, OP_is_undefined);
  39369. pos_next = cc.pos;
  39370. break;
  39371. }
  39372. /* transform undefined strict_neq if_false/if_true -> is_undefined if_true/if_false */
  39373. if (code_match(&cc, pos_next, OP_strict_neq, M2(OP_if_false, OP_if_true), -1)) {
  39374. if (cc.line_num >= 0) line_num = cc.line_num;
  39375. if (cc.col_num >= 0) col_num = cc.col_num;
  39376. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39377. dbuf_putc(&bc_out, OP_is_undefined);
  39378. pos_next = cc.pos;
  39379. label = cc.label;
  39380. op = cc.op ^ OP_if_false ^ OP_if_true;
  39381. goto has_label;
  39382. }
  39383. goto no_change;
  39384. case OP_insert2:
  39385. /* Transformation:
  39386. insert2 put_field(a) drop -> put_field(a)
  39387. insert2 put_var_strict(a) drop -> put_var_strict(a)
  39388. */
  39389. if (code_match(&cc, pos_next, M2(OP_put_field, OP_put_var_strict), OP_drop, -1)) {
  39390. if (cc.line_num >= 0) line_num = cc.line_num;
  39391. if (cc.col_num >= 0) col_num = cc.col_num;
  39392. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39393. dbuf_putc(&bc_out, cc.op);
  39394. dbuf_put_u32(&bc_out, cc.atom);
  39395. pos_next = cc.pos;
  39396. break;
  39397. }
  39398. goto no_change;
  39399. case OP_dup:
  39400. {
  39401. /* Transformation: dup put_x(n) drop -> put_x(n) */
  39402. int op1, line2 = -1;
  39403. /* Transformation: dup put_x(n) -> set_x(n) */
  39404. if (code_match(&cc, pos_next, M3(OP_put_loc, OP_put_arg, OP_put_var_ref), -1, -1)) {
  39405. if (cc.line_num >= 0) line_num = cc.line_num;
  39406. if (cc.col_num >= 0) col_num = cc.col_num;
  39407. op1 = cc.op + 1; /* put_x -> set_x */
  39408. pos_next = cc.pos;
  39409. if (code_match(&cc, cc.pos, OP_drop, -1)) {
  39410. if (cc.line_num >= 0) line_num = cc.line_num;
  39411. if (cc.col_num >= 0) col_num = cc.col_num;
  39412. op1 -= 1; /* set_x drop -> put_x */
  39413. pos_next = cc.pos;
  39414. if (code_match(&cc, cc.pos, op1 - 1, cc.idx, -1)) {
  39415. line2 = cc.line_num; /* delay line number update */
  39416. op1 += 1; /* put_x(n) get_x(n) -> set_x(n) */
  39417. pos_next = cc.pos;
  39418. }
  39419. }
  39420. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39421. put_short_code(&bc_out, op1, cc.idx);
  39422. if (line2 >= 0) line_num = line2;
  39423. break;
  39424. }
  39425. }
  39426. goto no_change;
  39427. case OP_swap:
  39428. // transformation: swap swap -> nothing!
  39429. if (code_match(&cc, pos_next, OP_swap, -1, -1)) {
  39430. if (cc.line_num >= 0) line_num = cc.line_num;
  39431. if (cc.col_num >= 0) col_num = cc.col_num;
  39432. pos_next = cc.pos;
  39433. break;
  39434. }
  39435. goto no_change;
  39436. case OP_get_loc:
  39437. {
  39438. /* transformation:
  39439. get_loc(n) post_dec put_loc(n) drop -> dec_loc(n)
  39440. get_loc(n) post_inc put_loc(n) drop -> inc_loc(n)
  39441. get_loc(n) dec dup put_loc(n) drop -> dec_loc(n)
  39442. get_loc(n) inc dup put_loc(n) drop -> inc_loc(n)
  39443. */
  39444. int idx;
  39445. idx = get_u16(bc_buf + pos + 1);
  39446. if (idx >= 256)
  39447. goto no_change;
  39448. if (code_match(&cc, pos_next, M2(OP_post_dec, OP_post_inc), OP_put_loc, idx, OP_drop, -1) ||
  39449. code_match(&cc, pos_next, M2(OP_dec, OP_inc), OP_dup, OP_put_loc, idx, OP_drop, -1)) {
  39450. if (cc.line_num >= 0) line_num = cc.line_num;
  39451. if (cc.col_num >= 0) col_num = cc.col_num;
  39452. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39453. dbuf_putc(&bc_out, (cc.op == OP_inc || cc.op == OP_post_inc) ? OP_inc_loc : OP_dec_loc);
  39454. dbuf_putc(&bc_out, idx);
  39455. pos_next = cc.pos;
  39456. break;
  39457. }
  39458. /* transformation:
  39459. get_loc(n) push_atom_value(x) add dup put_loc(n) drop -> push_atom_value(x) add_loc(n)
  39460. */
  39461. if (code_match(&cc, pos_next, OP_push_atom_value, OP_add, OP_dup, OP_put_loc, idx, OP_drop, -1)) {
  39462. if (cc.line_num >= 0) line_num = cc.line_num;
  39463. if (cc.col_num >= 0) col_num = cc.col_num;
  39464. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39465. if (cc.atom == JS_ATOM_empty_string) {
  39466. JS_FreeAtom(ctx, cc.atom);
  39467. dbuf_putc(&bc_out, OP_push_empty_string);
  39468. } else {
  39469. dbuf_putc(&bc_out, OP_push_atom_value);
  39470. dbuf_put_u32(&bc_out, cc.atom);
  39471. }
  39472. dbuf_putc(&bc_out, OP_add_loc);
  39473. dbuf_putc(&bc_out, idx);
  39474. pos_next = cc.pos;
  39475. break;
  39476. }
  39477. /* transformation:
  39478. get_loc(n) push_i32(x) add dup put_loc(n) drop -> push_i32(x) add_loc(n)
  39479. */
  39480. if (code_match(&cc, pos_next, OP_push_i32, OP_add, OP_dup, OP_put_loc, idx, OP_drop, -1)) {
  39481. if (cc.line_num >= 0) line_num = cc.line_num;
  39482. if (cc.col_num >= 0) col_num = cc.col_num;
  39483. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39484. push_short_int(&bc_out, cc.label);
  39485. dbuf_putc(&bc_out, OP_add_loc);
  39486. dbuf_putc(&bc_out, idx);
  39487. pos_next = cc.pos;
  39488. break;
  39489. }
  39490. /* transformation: XXX: also do these:
  39491. get_loc(n) get_loc(x) add dup put_loc(n) drop -> get_loc(x) add_loc(n)
  39492. get_loc(n) get_arg(x) add dup put_loc(n) drop -> get_arg(x) add_loc(n)
  39493. get_loc(n) get_var_ref(x) add dup put_loc(n) drop -> get_var_ref(x) add_loc(n)
  39494. */
  39495. if (code_match(&cc, pos_next, M3(OP_get_loc, OP_get_arg, OP_get_var_ref), -1, OP_add, OP_dup, OP_put_loc, idx, OP_drop, -1)) {
  39496. if (cc.line_num >= 0) line_num = cc.line_num;
  39497. if (cc.col_num >= 0) col_num = cc.col_num;
  39498. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39499. put_short_code(&bc_out, cc.op, cc.idx);
  39500. dbuf_putc(&bc_out, OP_add_loc);
  39501. dbuf_putc(&bc_out, idx);
  39502. pos_next = cc.pos;
  39503. break;
  39504. }
  39505. /* transformation: get_loc(0) get_loc(1) -> get_loc0_loc1 */
  39506. if (idx == 0 && code_match(&cc, pos_next, OP_get_loc, 1, -1)) {
  39507. if (cc.line_num >= 0) line_num = cc.line_num;
  39508. if (cc.col_num >= 0) col_num = cc.col_num;
  39509. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39510. dbuf_putc(&bc_out, OP_get_loc0_loc1);
  39511. pos_next = cc.pos;
  39512. break;
  39513. }
  39514. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39515. put_short_code(&bc_out, op, idx);
  39516. }
  39517. break;
  39518. case OP_get_arg:
  39519. case OP_get_var_ref:
  39520. {
  39521. int idx;
  39522. idx = get_u16(bc_buf + pos + 1);
  39523. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39524. put_short_code(&bc_out, op, idx);
  39525. }
  39526. break;
  39527. case OP_put_loc:
  39528. case OP_put_arg:
  39529. case OP_put_var_ref:
  39530. {
  39531. /* transformation: put_x(n) get_x(n) -> set_x(n) */
  39532. int idx;
  39533. idx = get_u16(bc_buf + pos + 1);
  39534. if (code_match(&cc, pos_next, op - 1, idx, -1)) {
  39535. if (cc.line_num >= 0) line_num = cc.line_num;
  39536. if (cc.col_num >= 0) col_num = cc.col_num;
  39537. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39538. put_short_code(&bc_out, op + 1, idx);
  39539. pos_next = cc.pos;
  39540. break;
  39541. }
  39542. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39543. put_short_code(&bc_out, op, idx);
  39544. }
  39545. break;
  39546. case OP_post_inc:
  39547. case OP_post_dec:
  39548. {
  39549. /* transformation:
  39550. post_inc put_x drop -> inc put_x
  39551. post_inc perm3 put_field drop -> inc put_field
  39552. post_inc perm3 put_var_strict drop -> inc put_var_strict
  39553. post_inc perm4 put_array_el drop -> inc put_array_el
  39554. */
  39555. int op1, idx;
  39556. if (code_match(&cc, pos_next, M3(OP_put_loc, OP_put_arg, OP_put_var_ref), -1, OP_drop, -1)) {
  39557. if (cc.line_num >= 0) line_num = cc.line_num;
  39558. if (cc.col_num >= 0) col_num = cc.col_num;
  39559. op1 = cc.op;
  39560. idx = cc.idx;
  39561. pos_next = cc.pos;
  39562. if (code_match(&cc, cc.pos, op1 - 1, idx, -1)) {
  39563. if (cc.line_num >= 0) line_num = cc.line_num;
  39564. if (cc.col_num >= 0) col_num = cc.col_num;
  39565. op1 += 1; /* put_x(n) get_x(n) -> set_x(n) */
  39566. pos_next = cc.pos;
  39567. }
  39568. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39569. dbuf_putc(&bc_out, OP_dec + (op - OP_post_dec));
  39570. put_short_code(&bc_out, op1, idx);
  39571. break;
  39572. }
  39573. if (code_match(&cc, pos_next, OP_perm3, M2(OP_put_field, OP_put_var_strict), OP_drop, -1)) {
  39574. if (cc.line_num >= 0) line_num = cc.line_num;
  39575. if (cc.col_num >= 0) col_num = cc.col_num;
  39576. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39577. dbuf_putc(&bc_out, OP_dec + (op - OP_post_dec));
  39578. dbuf_putc(&bc_out, cc.op);
  39579. dbuf_put_u32(&bc_out, cc.atom);
  39580. pos_next = cc.pos;
  39581. break;
  39582. }
  39583. if (code_match(&cc, pos_next, OP_perm4, OP_put_array_el, OP_drop, -1)) {
  39584. if (cc.line_num >= 0) line_num = cc.line_num;
  39585. if (cc.col_num >= 0) col_num = cc.col_num;
  39586. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39587. dbuf_putc(&bc_out, OP_dec + (op - OP_post_dec));
  39588. dbuf_putc(&bc_out, OP_put_array_el);
  39589. pos_next = cc.pos;
  39590. break;
  39591. }
  39592. }
  39593. goto no_change;
  39594. case OP_typeof:
  39595. /* simplify typeof tests */
  39596. if (code_match(&cc, pos_next, OP_push_atom_value, M4(OP_strict_eq, OP_strict_neq, OP_eq, OP_neq), -1)) {
  39597. if (cc.line_num >= 0) line_num = cc.line_num;
  39598. if (cc.col_num >= 0) col_num = cc.col_num;
  39599. int op1 = (cc.op == OP_strict_eq || cc.op == OP_eq) ? OP_strict_eq : OP_strict_neq;
  39600. int op2 = -1;
  39601. switch (cc.atom) {
  39602. case JS_ATOM_undefined:
  39603. op2 = OP_typeof_is_undefined;
  39604. break;
  39605. case JS_ATOM_function:
  39606. op2 = OP_typeof_is_function;
  39607. break;
  39608. }
  39609. if (op2 >= 0) {
  39610. /* transform typeof(s) == "<type>" into is_<type> */
  39611. if (op1 == OP_strict_eq) {
  39612. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39613. dbuf_putc(&bc_out, op2);
  39614. JS_FreeAtom(ctx, cc.atom);
  39615. pos_next = cc.pos;
  39616. break;
  39617. }
  39618. if (op1 == OP_strict_neq && code_match(&cc, cc.pos, OP_if_false, -1)) {
  39619. /* transform typeof(s) != "<type>" if_false into is_<type> if_true */
  39620. if (cc.line_num >= 0) line_num = cc.line_num;
  39621. if (cc.col_num >= 0) col_num = cc.col_num;
  39622. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39623. dbuf_putc(&bc_out, op2);
  39624. JS_FreeAtom(ctx, cc.atom);
  39625. pos_next = cc.pos;
  39626. label = cc.label;
  39627. op = OP_if_true;
  39628. goto has_label;
  39629. }
  39630. }
  39631. }
  39632. goto no_change;
  39633. default:
  39634. no_change:
  39635. add_pc2line_info(s, bc_out.size, line_num, col_num);
  39636. dbuf_put(&bc_out, bc_buf + pos, len);
  39637. break;
  39638. }
  39639. }
  39640. /* check that there were no missing labels */
  39641. for(i = 0; i < s->label_count; i++) {
  39642. assert(label_slots[i].first_reloc == NULL);
  39643. }
  39644. /* more jump optimizations */
  39645. patch_offsets = 0;
  39646. for (i = 0, jp = s->jump_slots; i < s->jump_count; i++, jp++) {
  39647. LabelSlot *ls;
  39648. JumpSlot *jp1;
  39649. int j, pos, diff, delta;
  39650. delta = 3;
  39651. switch (op = jp->op) {
  39652. case OP_goto16:
  39653. delta = 1;
  39654. /* fall thru */
  39655. case OP_if_false:
  39656. case OP_if_true:
  39657. case OP_goto:
  39658. pos = jp->pos;
  39659. diff = s->label_slots[jp->label].addr - pos;
  39660. if (diff >= -128 && diff <= 127 + delta) {
  39661. //put_u8(bc_out.buf + pos, diff);
  39662. jp->size = 1;
  39663. if (op == OP_goto16) {
  39664. bc_out.buf[pos - 1] = jp->op = OP_goto8;
  39665. } else {
  39666. bc_out.buf[pos - 1] = jp->op = OP_if_false8 + (op - OP_if_false);
  39667. }
  39668. goto shrink;
  39669. } else
  39670. if (diff == (int16_t)diff && op == OP_goto) {
  39671. //put_u16(bc_out.buf + pos, diff);
  39672. jp->size = 2;
  39673. delta = 2;
  39674. bc_out.buf[pos - 1] = jp->op = OP_goto16;
  39675. shrink:
  39676. /* XXX: should reduce complexity, using 2 finger copy scheme */
  39677. memmove(bc_out.buf + pos + jp->size, bc_out.buf + pos + jp->size + delta,
  39678. bc_out.size - pos - jp->size - delta);
  39679. bc_out.size -= delta;
  39680. patch_offsets++;
  39681. for (j = 0, ls = s->label_slots; j < s->label_count; j++, ls++) {
  39682. if (ls->addr > pos)
  39683. ls->addr -= delta;
  39684. }
  39685. for (j = i + 1, jp1 = jp + 1; j < s->jump_count; j++, jp1++) {
  39686. if (jp1->pos > pos)
  39687. jp1->pos -= delta;
  39688. }
  39689. for (j = 0; j < s->source_loc_count; j++) {
  39690. if (s->source_loc_slots[j].pc > pos)
  39691. s->source_loc_slots[j].pc -= delta;
  39692. }
  39693. continue;
  39694. }
  39695. break;
  39696. }
  39697. }
  39698. if (patch_offsets) {
  39699. JumpSlot *jp1;
  39700. int j;
  39701. for (j = 0, jp1 = s->jump_slots; j < s->jump_count; j++, jp1++) {
  39702. int diff1 = s->label_slots[jp1->label].addr - jp1->pos;
  39703. switch (jp1->size) {
  39704. case 1:
  39705. put_u8(bc_out.buf + jp1->pos, diff1);
  39706. break;
  39707. case 2:
  39708. put_u16(bc_out.buf + jp1->pos, diff1);
  39709. break;
  39710. case 4:
  39711. put_u32(bc_out.buf + jp1->pos, diff1);
  39712. break;
  39713. }
  39714. }
  39715. }
  39716. js_free(ctx, s->jump_slots);
  39717. s->jump_slots = NULL;
  39718. js_free(ctx, s->label_slots);
  39719. s->label_slots = NULL;
  39720. /* XXX: should delay until copying to runtime bytecode function */
  39721. compute_pc2line_info(s);
  39722. js_free(ctx, s->source_loc_slots);
  39723. s->source_loc_slots = NULL;
  39724. /* set the new byte code */
  39725. dbuf_free(&s->byte_code);
  39726. s->byte_code = bc_out;
  39727. s->use_short_opcodes = true;
  39728. if (dbuf_error(&s->byte_code)) {
  39729. JS_ThrowOutOfMemory(ctx);
  39730. return -1;
  39731. }
  39732. return 0;
  39733. fail:
  39734. /* XXX: not safe */
  39735. dbuf_free(&bc_out);
  39736. return -1;
  39737. }
  39738. /* compute the maximum stack size needed by the function */
  39739. typedef struct StackSizeState {
  39740. int bc_len;
  39741. int stack_len_max;
  39742. uint16_t *stack_level_tab;
  39743. int32_t *catch_pos_tab;
  39744. int *pc_stack;
  39745. int pc_stack_len;
  39746. int pc_stack_size;
  39747. } StackSizeState;
  39748. /* 'op' is only used for error indication */
  39749. static __exception int ss_check(JSContext *ctx, StackSizeState *s,
  39750. int pos, int op, int stack_len, int catch_pos)
  39751. {
  39752. if ((unsigned)pos >= s->bc_len) {
  39753. JS_ThrowInternalError(ctx, "bytecode buffer overflow (op=%d, pc=%d)", op, pos);
  39754. return -1;
  39755. }
  39756. if (stack_len > s->stack_len_max) {
  39757. s->stack_len_max = stack_len;
  39758. if (s->stack_len_max > JS_STACK_SIZE_MAX) {
  39759. JS_ThrowInternalError(ctx, "stack overflow (op=%d, pc=%d)", op, pos);
  39760. return -1;
  39761. }
  39762. }
  39763. if (s->stack_level_tab[pos] != 0xffff) {
  39764. /* already explored: check that the stack size is consistent */
  39765. if (s->stack_level_tab[pos] != stack_len) {
  39766. JS_ThrowInternalError(ctx, "inconsistent stack size: %d %d (pc=%d)",
  39767. s->stack_level_tab[pos], stack_len, pos);
  39768. return -1;
  39769. } else if (s->catch_pos_tab[pos] != catch_pos) {
  39770. JS_ThrowInternalError(ctx, "inconsistent catch position: %d %d (pc=%d)",
  39771. s->catch_pos_tab[pos], catch_pos, pos);
  39772. return -1;
  39773. } else {
  39774. return 0;
  39775. }
  39776. }
  39777. /* mark as explored and store the stack size */
  39778. s->stack_level_tab[pos] = stack_len;
  39779. s->catch_pos_tab[pos] = catch_pos;
  39780. /* queue the new PC to explore */
  39781. if (js_resize_array(ctx, (void **)&s->pc_stack, sizeof(s->pc_stack[0]),
  39782. &s->pc_stack_size, s->pc_stack_len + 1))
  39783. return -1;
  39784. s->pc_stack[s->pc_stack_len++] = pos;
  39785. return 0;
  39786. }
  39787. static __exception int compute_stack_size(JSContext *ctx,
  39788. JSFunctionDef *fd,
  39789. int *pstack_size)
  39790. {
  39791. StackSizeState s_s, *s = &s_s;
  39792. int i, diff, n_pop, pos_next, stack_len, pos, op, catch_pos, catch_level;
  39793. const JSOpCode *oi;
  39794. const uint8_t *bc_buf;
  39795. bc_buf = fd->byte_code.buf;
  39796. s->bc_len = fd->byte_code.size;
  39797. /* bc_len > 0 */
  39798. s->stack_level_tab = js_malloc(ctx, sizeof(s->stack_level_tab[0]) *
  39799. s->bc_len);
  39800. if (!s->stack_level_tab)
  39801. return -1;
  39802. for(i = 0; i < s->bc_len; i++)
  39803. s->stack_level_tab[i] = 0xffff;
  39804. s->pc_stack = NULL;
  39805. s->catch_pos_tab = js_malloc(ctx, sizeof(s->catch_pos_tab[0]) * s->bc_len);
  39806. if (!s->catch_pos_tab)
  39807. goto fail;
  39808. s->stack_len_max = 0;
  39809. s->pc_stack_len = 0;
  39810. s->pc_stack_size = 0;
  39811. /* breadth-first graph exploration */
  39812. if (ss_check(ctx, s, 0, OP_invalid, 0, -1))
  39813. goto fail;
  39814. while (s->pc_stack_len > 0) {
  39815. pos = s->pc_stack[--s->pc_stack_len];
  39816. stack_len = s->stack_level_tab[pos];
  39817. catch_pos = s->catch_pos_tab[pos];
  39818. op = bc_buf[pos];
  39819. if (op == 0 || op >= OP_COUNT) {
  39820. JS_ThrowInternalError(ctx, "invalid opcode (op=%d, pc=%d)", op, pos);
  39821. goto fail;
  39822. }
  39823. oi = &short_opcode_info(op);
  39824. #ifdef ENABLE_DUMPS // JS_DUMP_BYTECODE_STACK
  39825. if (check_dump_flag(ctx->rt, JS_DUMP_BYTECODE_STACK))
  39826. printf("%5d: %10s %5d %5d\n", pos, oi->name, stack_len, catch_pos);
  39827. #endif
  39828. pos_next = pos + oi->size;
  39829. if (pos_next > s->bc_len) {
  39830. JS_ThrowInternalError(ctx, "bytecode buffer overflow (op=%d, pc=%d)", op, pos);
  39831. goto fail;
  39832. }
  39833. n_pop = oi->n_pop;
  39834. /* call pops a variable number of arguments */
  39835. if (oi->fmt == OP_FMT_npop || oi->fmt == OP_FMT_npop_u16) {
  39836. n_pop += get_u16(bc_buf + pos + 1);
  39837. } else if (oi->fmt == OP_FMT_npopx) {
  39838. n_pop += op - OP_call0;
  39839. }
  39840. if (stack_len < n_pop) {
  39841. JS_ThrowInternalError(ctx, "stack underflow (op=%d, pc=%d)", op, pos);
  39842. goto fail;
  39843. }
  39844. stack_len += oi->n_push - n_pop;
  39845. if (stack_len > s->stack_len_max) {
  39846. s->stack_len_max = stack_len;
  39847. if (s->stack_len_max > JS_STACK_SIZE_MAX) {
  39848. JS_ThrowInternalError(ctx, "stack overflow (op=%d, pc=%d)", op, pos);
  39849. goto fail;
  39850. }
  39851. }
  39852. switch(op) {
  39853. case OP_tail_call:
  39854. case OP_tail_call_method:
  39855. case OP_return:
  39856. case OP_return_undef:
  39857. case OP_return_async:
  39858. case OP_throw:
  39859. case OP_throw_error:
  39860. case OP_ret:
  39861. goto done_insn;
  39862. case OP_goto:
  39863. diff = get_u32(bc_buf + pos + 1);
  39864. pos_next = pos + 1 + diff;
  39865. break;
  39866. case OP_goto16:
  39867. diff = (int16_t)get_u16(bc_buf + pos + 1);
  39868. pos_next = pos + 1 + diff;
  39869. break;
  39870. case OP_goto8:
  39871. diff = (int8_t)bc_buf[pos + 1];
  39872. pos_next = pos + 1 + diff;
  39873. break;
  39874. case OP_if_true8:
  39875. case OP_if_false8:
  39876. diff = (int8_t)bc_buf[pos + 1];
  39877. if (ss_check(ctx, s, pos + 1 + diff, op, stack_len, catch_pos))
  39878. goto fail;
  39879. break;
  39880. case OP_if_true:
  39881. case OP_if_false:
  39882. diff = get_u32(bc_buf + pos + 1);
  39883. if (ss_check(ctx, s, pos + 1 + diff, op, stack_len, catch_pos))
  39884. goto fail;
  39885. break;
  39886. case OP_gosub:
  39887. diff = get_u32(bc_buf + pos + 1);
  39888. if (ss_check(ctx, s, pos + 1 + diff, op, stack_len + 1, catch_pos))
  39889. goto fail;
  39890. break;
  39891. case OP_with_get_var:
  39892. case OP_with_delete_var:
  39893. diff = get_u32(bc_buf + pos + 5);
  39894. if (ss_check(ctx, s, pos + 5 + diff, op, stack_len + 1, catch_pos))
  39895. goto fail;
  39896. break;
  39897. case OP_with_make_ref:
  39898. case OP_with_get_ref:
  39899. case OP_with_get_ref_undef:
  39900. diff = get_u32(bc_buf + pos + 5);
  39901. if (ss_check(ctx, s, pos + 5 + diff, op, stack_len + 2, catch_pos))
  39902. goto fail;
  39903. break;
  39904. case OP_with_put_var:
  39905. diff = get_u32(bc_buf + pos + 5);
  39906. if (ss_check(ctx, s, pos + 5 + diff, op, stack_len - 1, catch_pos))
  39907. goto fail;
  39908. break;
  39909. case OP_catch:
  39910. diff = get_u32(bc_buf + pos + 1);
  39911. if (ss_check(ctx, s, pos + 1 + diff, op, stack_len, catch_pos))
  39912. goto fail;
  39913. catch_pos = pos;
  39914. break;
  39915. case OP_for_of_start:
  39916. case OP_for_await_of_start:
  39917. catch_pos = pos;
  39918. break;
  39919. /* we assume the catch offset entry is only removed with
  39920. some op codes */
  39921. case OP_drop:
  39922. catch_level = stack_len;
  39923. goto check_catch;
  39924. case OP_nip:
  39925. catch_level = stack_len - 1;
  39926. goto check_catch;
  39927. case OP_nip1:
  39928. catch_level = stack_len - 1;
  39929. goto check_catch;
  39930. case OP_iterator_close:
  39931. catch_level = stack_len + 2;
  39932. check_catch:
  39933. /* Note: for for_of_start/for_await_of_start we consider
  39934. the catch offset is on the first stack entry instead of
  39935. the thirst */
  39936. if (catch_pos >= 0) {
  39937. int level;
  39938. level = s->stack_level_tab[catch_pos];
  39939. if (bc_buf[catch_pos] != OP_catch)
  39940. level++; /* for_of_start, for_wait_of_start */
  39941. /* catch_level = stack_level before op_catch is executed ? */
  39942. if (catch_level == level) {
  39943. catch_pos = s->catch_pos_tab[catch_pos];
  39944. }
  39945. }
  39946. break;
  39947. case OP_nip_catch:
  39948. if (catch_pos < 0) {
  39949. JS_ThrowInternalError(ctx, "nip_catch: no catch op (pc=%d)", pos);
  39950. goto fail;
  39951. }
  39952. stack_len = s->stack_level_tab[catch_pos];
  39953. if (bc_buf[catch_pos] != OP_catch)
  39954. stack_len++; /* for_of_start, for_wait_of_start */
  39955. stack_len++; /* no stack overflow is possible by construction */
  39956. catch_pos = s->catch_pos_tab[catch_pos];
  39957. break;
  39958. default:
  39959. break;
  39960. }
  39961. if (ss_check(ctx, s, pos_next, op, stack_len, catch_pos))
  39962. goto fail;
  39963. done_insn: ;
  39964. }
  39965. js_free(ctx, s->pc_stack);
  39966. js_free(ctx, s->catch_pos_tab);
  39967. js_free(ctx, s->stack_level_tab);
  39968. *pstack_size = s->stack_len_max;
  39969. return 0;
  39970. fail:
  39971. js_free(ctx, s->pc_stack);
  39972. js_free(ctx, s->catch_pos_tab);
  39973. js_free(ctx, s->stack_level_tab);
  39974. *pstack_size = 0;
  39975. return -1;
  39976. }
  39977. static int add_module_variables(JSContext *ctx, JSFunctionDef *fd)
  39978. {
  39979. int i, idx;
  39980. JSModuleDef *m = fd->module;
  39981. JSExportEntry *me;
  39982. JSGlobalVar *hf;
  39983. /* The imported global variables were added as closure variables
  39984. in js_parse_import(). We add here the module global
  39985. variables. */
  39986. for(i = 0; i < fd->global_var_count; i++) {
  39987. hf = &fd->global_vars[i];
  39988. if (add_closure_var(ctx, fd, true, false, i, hf->var_name, hf->is_const,
  39989. hf->is_lexical, JS_VAR_NORMAL) < 0)
  39990. return -1;
  39991. }
  39992. /* resolve the variable names of the local exports */
  39993. for(i = 0; i < m->export_entries_count; i++) {
  39994. me = &m->export_entries[i];
  39995. if (me->export_type == JS_EXPORT_TYPE_LOCAL) {
  39996. idx = find_closure_var(ctx, fd, me->local_name);
  39997. if (idx < 0) {
  39998. // XXX: add_module_variables() should take JSParseState *s and use js_parse_error_atom
  39999. JS_ThrowSyntaxErrorAtom(ctx, "exported variable '%s' does not exist",
  40000. me->local_name);
  40001. return -1;
  40002. }
  40003. me->u.local.var_idx = idx;
  40004. }
  40005. }
  40006. return 0;
  40007. }
  40008. /* create a function object from a function definition. The function
  40009. definition is freed. All the child functions are also created. It
  40010. must be done this way to resolve all the variables. */
  40011. static JSValue js_create_function(JSContext *ctx, JSFunctionDef *fd)
  40012. {
  40013. JSValue func_obj;
  40014. JSFunctionBytecode *b;
  40015. struct list_head *el, *el1;
  40016. int stack_size, scope, idx;
  40017. int function_size, byte_code_offset, cpool_offset;
  40018. int closure_var_offset, vardefs_offset;
  40019. /* recompute scope linkage */
  40020. for (scope = 0; scope < fd->scope_count; scope++) {
  40021. fd->scopes[scope].first = -1;
  40022. }
  40023. if (fd->has_parameter_expressions) {
  40024. /* special end of variable list marker for the argument scope */
  40025. fd->scopes[ARG_SCOPE_INDEX].first = ARG_SCOPE_END;
  40026. }
  40027. for (idx = 0; idx < fd->var_count; idx++) {
  40028. JSVarDef *vd = &fd->vars[idx];
  40029. vd->scope_next = fd->scopes[vd->scope_level].first;
  40030. fd->scopes[vd->scope_level].first = idx;
  40031. }
  40032. for (scope = 2; scope < fd->scope_count; scope++) {
  40033. JSVarScope *sd = &fd->scopes[scope];
  40034. if (sd->first < 0)
  40035. sd->first = fd->scopes[sd->parent].first;
  40036. }
  40037. for (idx = 0; idx < fd->var_count; idx++) {
  40038. JSVarDef *vd = &fd->vars[idx];
  40039. if (vd->scope_next < 0 && vd->scope_level > 1) {
  40040. scope = fd->scopes[vd->scope_level].parent;
  40041. vd->scope_next = fd->scopes[scope].first;
  40042. }
  40043. }
  40044. /* if the function contains an eval call, the closure variables
  40045. are used to compile the eval and they must be ordered by scope,
  40046. so it is necessary to create the closure variables before any
  40047. other variable lookup is done. */
  40048. if (fd->has_eval_call)
  40049. add_eval_variables(ctx, fd);
  40050. /* add the module global variables in the closure */
  40051. if (fd->module) {
  40052. if (add_module_variables(ctx, fd))
  40053. goto fail;
  40054. }
  40055. /* first create all the child functions */
  40056. list_for_each_safe(el, el1, &fd->child_list) {
  40057. JSFunctionDef *fd1;
  40058. int cpool_idx;
  40059. fd1 = list_entry(el, JSFunctionDef, link);
  40060. cpool_idx = fd1->parent_cpool_idx;
  40061. func_obj = js_create_function(ctx, fd1);
  40062. if (JS_IsException(func_obj))
  40063. goto fail;
  40064. /* save it in the constant pool */
  40065. assert(cpool_idx >= 0);
  40066. fd->cpool[cpool_idx] = func_obj;
  40067. }
  40068. #ifdef ENABLE_DUMPS // JS_DUMP_BYTECODE_PASS1
  40069. if (check_dump_flag(ctx->rt, JS_DUMP_BYTECODE_PASS1)) {
  40070. printf("pass 1\n");
  40071. dump_byte_code(ctx, 1, fd->byte_code.buf, fd->byte_code.size,
  40072. fd->args, fd->arg_count, fd->vars, fd->var_count,
  40073. fd->closure_var, fd->closure_var_count,
  40074. fd->cpool, fd->cpool_count, fd->source, fd->line_num,
  40075. fd->label_slots, NULL, 0);
  40076. printf("\n");
  40077. }
  40078. #endif
  40079. if (resolve_variables(ctx, fd))
  40080. goto fail;
  40081. #ifdef ENABLE_DUMPS // JS_DUMP_BYTECODE_PASS2
  40082. if (check_dump_flag(ctx->rt, JS_DUMP_BYTECODE_PASS2)) {
  40083. printf("pass 2\n");
  40084. dump_byte_code(ctx, 2, fd->byte_code.buf, fd->byte_code.size,
  40085. fd->args, fd->arg_count, fd->vars, fd->var_count,
  40086. fd->closure_var, fd->closure_var_count,
  40087. fd->cpool, fd->cpool_count, fd->source, fd->line_num,
  40088. fd->label_slots, NULL, 0);
  40089. printf("\n");
  40090. }
  40091. #endif
  40092. if (resolve_labels(ctx, fd))
  40093. goto fail;
  40094. if (compute_stack_size(ctx, fd, &stack_size) < 0)
  40095. goto fail;
  40096. function_size = sizeof(*b);
  40097. cpool_offset = function_size;
  40098. function_size += fd->cpool_count * sizeof(*fd->cpool);
  40099. vardefs_offset = function_size;
  40100. function_size += (fd->arg_count + fd->var_count) * sizeof(*b->vardefs);
  40101. closure_var_offset = function_size;
  40102. function_size += fd->closure_var_count * sizeof(*fd->closure_var);
  40103. byte_code_offset = function_size;
  40104. function_size += fd->byte_code.size;
  40105. b = js_mallocz(ctx, function_size);
  40106. if (!b)
  40107. goto fail;
  40108. b->header.ref_count = 1;
  40109. b->byte_code_buf = (void *)((uint8_t*)b + byte_code_offset);
  40110. b->byte_code_len = fd->byte_code.size;
  40111. memcpy(b->byte_code_buf, fd->byte_code.buf, fd->byte_code.size);
  40112. js_free(ctx, fd->byte_code.buf);
  40113. fd->byte_code.buf = NULL;
  40114. b->func_name = fd->func_name;
  40115. if (fd->arg_count + fd->var_count > 0) {
  40116. b->vardefs = (void *)((uint8_t*)b + vardefs_offset);
  40117. if (fd->arg_count > 0)
  40118. memcpy(b->vardefs, fd->args, fd->arg_count * sizeof(fd->args[0]));
  40119. if (fd->var_count > 0)
  40120. memcpy(b->vardefs + fd->arg_count, fd->vars, fd->var_count * sizeof(fd->vars[0]));
  40121. b->var_count = fd->var_count;
  40122. b->arg_count = fd->arg_count;
  40123. b->defined_arg_count = fd->defined_arg_count;
  40124. js_free(ctx, fd->args);
  40125. js_free(ctx, fd->vars);
  40126. js_free(ctx, fd->vars_htab);
  40127. }
  40128. b->cpool_count = fd->cpool_count;
  40129. if (b->cpool_count) {
  40130. b->cpool = (void *)((uint8_t*)b + cpool_offset);
  40131. memcpy(b->cpool, fd->cpool, b->cpool_count * sizeof(*b->cpool));
  40132. }
  40133. js_free(ctx, fd->cpool);
  40134. fd->cpool = NULL;
  40135. b->stack_size = stack_size;
  40136. /* XXX: source and pc2line info should be packed at the end of the
  40137. JSFunctionBytecode structure, avoiding allocation overhead
  40138. */
  40139. b->filename = fd->filename;
  40140. b->line_num = fd->line_num;
  40141. b->col_num = fd->col_num;
  40142. b->pc2line_buf = js_realloc(ctx, fd->pc2line.buf, fd->pc2line.size);
  40143. if (!b->pc2line_buf)
  40144. b->pc2line_buf = fd->pc2line.buf;
  40145. b->pc2line_len = fd->pc2line.size;
  40146. b->source = fd->source;
  40147. b->source_len = fd->source_len;
  40148. if (fd->scopes != fd->def_scope_array)
  40149. js_free(ctx, fd->scopes);
  40150. b->closure_var_count = fd->closure_var_count;
  40151. if (b->closure_var_count) {
  40152. b->closure_var = (void *)((uint8_t*)b + closure_var_offset);
  40153. memcpy(b->closure_var, fd->closure_var, b->closure_var_count * sizeof(*b->closure_var));
  40154. }
  40155. js_free(ctx, fd->closure_var);
  40156. fd->closure_var = NULL;
  40157. b->has_prototype = fd->has_prototype;
  40158. b->has_simple_parameter_list = fd->has_simple_parameter_list;
  40159. b->is_strict_mode = fd->is_strict_mode;
  40160. b->is_derived_class_constructor = fd->is_derived_class_constructor;
  40161. b->func_kind = fd->func_kind;
  40162. b->need_home_object = (fd->home_object_var_idx >= 0 ||
  40163. fd->need_home_object);
  40164. b->new_target_allowed = fd->new_target_allowed;
  40165. b->super_call_allowed = fd->super_call_allowed;
  40166. b->super_allowed = fd->super_allowed;
  40167. b->arguments_allowed = fd->arguments_allowed;
  40168. b->backtrace_barrier = fd->backtrace_barrier;
  40169. b->realm = JS_DupContext(ctx);
  40170. add_gc_object(ctx->rt, &b->header, JS_GC_OBJ_TYPE_FUNCTION_BYTECODE);
  40171. #ifdef ENABLE_DUMPS // JS_DUMP_BYTECODE_FINAL
  40172. if (check_dump_flag(ctx->rt, JS_DUMP_BYTECODE_FINAL))
  40173. js_dump_function_bytecode(ctx, b);
  40174. #endif
  40175. if (fd->parent) {
  40176. /* remove from parent list */
  40177. list_del(&fd->link);
  40178. }
  40179. js_free(ctx, fd);
  40180. return JS_MKPTR(JS_TAG_FUNCTION_BYTECODE, b);
  40181. fail:
  40182. js_free_function_def(ctx, fd);
  40183. return JS_EXCEPTION;
  40184. }
  40185. static void free_function_bytecode(JSRuntime *rt, JSFunctionBytecode *b)
  40186. {
  40187. int i;
  40188. free_bytecode_atoms(rt, b->byte_code_buf, b->byte_code_len, true);
  40189. if (b->vardefs) {
  40190. for(i = 0; i < b->arg_count + b->var_count; i++) {
  40191. JS_FreeAtomRT(rt, b->vardefs[i].var_name);
  40192. }
  40193. }
  40194. for(i = 0; i < b->cpool_count; i++)
  40195. JS_FreeValueRT(rt, b->cpool[i]);
  40196. for(i = 0; i < b->closure_var_count; i++) {
  40197. JSClosureVar *cv = &b->closure_var[i];
  40198. JS_FreeAtomRT(rt, cv->var_name);
  40199. }
  40200. if (b->realm)
  40201. JS_FreeContext(b->realm);
  40202. JS_FreeAtomRT(rt, b->func_name);
  40203. JS_FreeAtomRT(rt, b->filename);
  40204. js_free_rt(rt, b->pc2line_buf);
  40205. js_free_rt(rt, b->source);
  40206. remove_gc_object(&b->header);
  40207. if (rt->gc_phase == JS_GC_PHASE_REMOVE_CYCLES && b->header.ref_count != 0) {
  40208. list_add_tail(&b->header.link, &rt->gc_zero_ref_count_list);
  40209. } else {
  40210. js_free_rt(rt, b);
  40211. }
  40212. }
  40213. static __exception int js_parse_directives(JSParseState *s)
  40214. {
  40215. char str[20];
  40216. JSParsePos pos;
  40217. bool has_semi;
  40218. if (s->token.val != TOK_STRING)
  40219. return 0;
  40220. js_parse_get_pos(s, &pos);
  40221. while(s->token.val == TOK_STRING) {
  40222. /* Copy actual source string representation */
  40223. snprintf(str, sizeof str, "%.*s",
  40224. (int)(s->buf_ptr - s->token.ptr - 2), s->token.ptr + 1);
  40225. if (next_token(s))
  40226. return -1;
  40227. has_semi = false;
  40228. switch (s->token.val) {
  40229. case ';':
  40230. if (next_token(s))
  40231. return -1;
  40232. has_semi = true;
  40233. break;
  40234. case '}':
  40235. case TOK_EOF:
  40236. has_semi = true;
  40237. break;
  40238. case TOK_NUMBER:
  40239. case TOK_STRING:
  40240. case TOK_TEMPLATE:
  40241. case TOK_IDENT:
  40242. case TOK_REGEXP:
  40243. case TOK_DEC:
  40244. case TOK_INC:
  40245. case TOK_NULL:
  40246. case TOK_FALSE:
  40247. case TOK_TRUE:
  40248. case TOK_IF:
  40249. case TOK_RETURN:
  40250. case TOK_VAR:
  40251. case TOK_THIS:
  40252. case TOK_DELETE:
  40253. case TOK_TYPEOF:
  40254. case TOK_NEW:
  40255. case TOK_DO:
  40256. case TOK_WHILE:
  40257. case TOK_FOR:
  40258. case TOK_SWITCH:
  40259. case TOK_THROW:
  40260. case TOK_TRY:
  40261. case TOK_FUNCTION:
  40262. case TOK_DEBUGGER:
  40263. case TOK_WITH:
  40264. case TOK_CLASS:
  40265. case TOK_CONST:
  40266. case TOK_ENUM:
  40267. case TOK_EXPORT:
  40268. case TOK_IMPORT:
  40269. case TOK_SUPER:
  40270. case TOK_INTERFACE:
  40271. case TOK_LET:
  40272. case TOK_PACKAGE:
  40273. case TOK_PRIVATE:
  40274. case TOK_PROTECTED:
  40275. case TOK_PUBLIC:
  40276. case TOK_STATIC:
  40277. /* automatic insertion of ';' */
  40278. if (s->got_lf)
  40279. has_semi = true;
  40280. break;
  40281. default:
  40282. break;
  40283. }
  40284. if (!has_semi)
  40285. break;
  40286. if (!strcmp(str, "use strict")) {
  40287. s->cur_func->has_use_strict = true;
  40288. s->cur_func->is_strict_mode = true;
  40289. }
  40290. }
  40291. return js_parse_seek_token(s, &pos);
  40292. }
  40293. static bool js_invalid_strict_name(JSAtom name) {
  40294. switch (name) {
  40295. case JS_ATOM_eval:
  40296. case JS_ATOM_arguments:
  40297. case JS_ATOM_implements: // future strict reserved words
  40298. case JS_ATOM_interface:
  40299. case JS_ATOM_let:
  40300. case JS_ATOM_package:
  40301. case JS_ATOM_private:
  40302. case JS_ATOM_protected:
  40303. case JS_ATOM_public:
  40304. case JS_ATOM_static:
  40305. case JS_ATOM_yield:
  40306. return true;
  40307. default:
  40308. return false;
  40309. }
  40310. }
  40311. static int js_parse_function_check_names(JSParseState *s, JSFunctionDef *fd,
  40312. JSAtom func_name)
  40313. {
  40314. JSAtom name;
  40315. int i, idx;
  40316. if (fd->is_strict_mode) {
  40317. if (!fd->has_simple_parameter_list && fd->has_use_strict) {
  40318. return js_parse_error(s, "\"use strict\" not allowed in function with default or destructuring parameter");
  40319. }
  40320. if (js_invalid_strict_name(func_name)) {
  40321. return js_parse_error(s, "invalid function name in strict code");
  40322. }
  40323. for (idx = 0; idx < fd->arg_count; idx++) {
  40324. name = fd->args[idx].var_name;
  40325. if (js_invalid_strict_name(name)) {
  40326. return js_parse_error(s, "invalid argument name in strict code");
  40327. }
  40328. }
  40329. }
  40330. /* check async_generator case */
  40331. if (fd->is_strict_mode
  40332. || !fd->has_simple_parameter_list
  40333. || (fd->func_type == JS_PARSE_FUNC_METHOD && fd->func_kind == JS_FUNC_ASYNC)
  40334. || fd->func_type == JS_PARSE_FUNC_ARROW
  40335. || fd->func_type == JS_PARSE_FUNC_METHOD) {
  40336. for (idx = 0; idx < fd->arg_count; idx++) {
  40337. name = fd->args[idx].var_name;
  40338. if (name != JS_ATOM_NULL) {
  40339. for (i = 0; i < idx; i++) {
  40340. if (fd->args[i].var_name == name)
  40341. goto duplicate;
  40342. }
  40343. /* Check if argument name duplicates a destructuring parameter */
  40344. /* XXX: should have a flag for such variables */
  40345. for (i = 0; i < fd->var_count; i++) {
  40346. if (fd->vars[i].var_name == name &&
  40347. fd->vars[i].scope_level == 0)
  40348. goto duplicate;
  40349. }
  40350. }
  40351. }
  40352. }
  40353. return 0;
  40354. duplicate:
  40355. return js_parse_error(s, "Duplicate parameter name not allowed in this context");
  40356. }
  40357. /* create a function to initialize class fields */
  40358. static JSFunctionDef *js_parse_function_class_fields_init(JSParseState *s)
  40359. {
  40360. JSFunctionDef *fd;
  40361. fd = js_new_function_def(s->ctx, s->cur_func, false, false,
  40362. s->filename, 0, 0);
  40363. if (!fd)
  40364. return NULL;
  40365. fd->func_name = JS_ATOM_NULL;
  40366. fd->has_prototype = false;
  40367. fd->has_home_object = true;
  40368. fd->has_arguments_binding = false;
  40369. fd->has_this_binding = true;
  40370. fd->is_derived_class_constructor = false;
  40371. fd->new_target_allowed = true;
  40372. fd->super_call_allowed = false;
  40373. fd->super_allowed = fd->has_home_object;
  40374. fd->arguments_allowed = false;
  40375. fd->func_kind = JS_FUNC_NORMAL;
  40376. fd->func_type = JS_PARSE_FUNC_METHOD;
  40377. return fd;
  40378. }
  40379. /* func_name must be JS_ATOM_NULL for JS_PARSE_FUNC_STATEMENT and
  40380. JS_PARSE_FUNC_EXPR, JS_PARSE_FUNC_ARROW and JS_PARSE_FUNC_VAR */
  40381. static __exception int js_parse_function_decl2(JSParseState *s,
  40382. JSParseFunctionEnum func_type,
  40383. JSFunctionKindEnum func_kind,
  40384. JSAtom func_name,
  40385. const uint8_t *ptr,
  40386. int function_line_num,
  40387. int function_col_num,
  40388. JSParseExportEnum export_flag,
  40389. JSFunctionDef **pfd)
  40390. {
  40391. JSContext *ctx = s->ctx;
  40392. JSFunctionDef *fd = s->cur_func;
  40393. bool is_expr;
  40394. int func_idx, lexical_func_idx = -1;
  40395. bool has_opt_arg;
  40396. bool create_func_var = false;
  40397. is_expr = (func_type != JS_PARSE_FUNC_STATEMENT &&
  40398. func_type != JS_PARSE_FUNC_VAR);
  40399. if (func_type == JS_PARSE_FUNC_STATEMENT ||
  40400. func_type == JS_PARSE_FUNC_VAR ||
  40401. func_type == JS_PARSE_FUNC_EXPR) {
  40402. if (func_kind == JS_FUNC_NORMAL &&
  40403. token_is_pseudo_keyword(s, JS_ATOM_async) &&
  40404. peek_token(s, true) != '\n') {
  40405. if (next_token(s))
  40406. return -1;
  40407. func_kind = JS_FUNC_ASYNC;
  40408. }
  40409. if (next_token(s))
  40410. return -1;
  40411. if (s->token.val == '*') {
  40412. if (next_token(s))
  40413. return -1;
  40414. func_kind |= JS_FUNC_GENERATOR;
  40415. }
  40416. if (s->token.val == TOK_IDENT) {
  40417. if (s->token.u.ident.is_reserved ||
  40418. (s->token.u.ident.atom == JS_ATOM_yield &&
  40419. func_type == JS_PARSE_FUNC_EXPR &&
  40420. (func_kind & JS_FUNC_GENERATOR)) ||
  40421. (s->token.u.ident.atom == JS_ATOM_await &&
  40422. ((func_type == JS_PARSE_FUNC_EXPR &&
  40423. (func_kind & JS_FUNC_ASYNC)) ||
  40424. func_type == JS_PARSE_FUNC_CLASS_STATIC_INIT))) {
  40425. return js_parse_error_reserved_identifier(s);
  40426. }
  40427. }
  40428. if (s->token.val == TOK_IDENT ||
  40429. (((s->token.val == TOK_YIELD && !fd->is_strict_mode) ||
  40430. (s->token.val == TOK_AWAIT && !s->is_module)) &&
  40431. func_type == JS_PARSE_FUNC_EXPR)) {
  40432. func_name = JS_DupAtom(ctx, s->token.u.ident.atom);
  40433. if (next_token(s)) {
  40434. JS_FreeAtom(ctx, func_name);
  40435. return -1;
  40436. }
  40437. } else {
  40438. if (func_type != JS_PARSE_FUNC_EXPR &&
  40439. export_flag != JS_PARSE_EXPORT_DEFAULT) {
  40440. return js_parse_error(s, "function name expected");
  40441. }
  40442. }
  40443. } else if (func_type != JS_PARSE_FUNC_ARROW) {
  40444. func_name = JS_DupAtom(ctx, func_name);
  40445. }
  40446. if (fd->is_eval && fd->eval_type == JS_EVAL_TYPE_MODULE &&
  40447. (func_type == JS_PARSE_FUNC_STATEMENT || func_type == JS_PARSE_FUNC_VAR)) {
  40448. JSGlobalVar *hf;
  40449. hf = find_global_var(fd, func_name);
  40450. /* XXX: should check scope chain */
  40451. if (hf && hf->scope_level == fd->scope_level) {
  40452. js_parse_error(s, "invalid redefinition of global identifier in module code");
  40453. JS_FreeAtom(ctx, func_name);
  40454. return -1;
  40455. }
  40456. }
  40457. if (func_type == JS_PARSE_FUNC_VAR) {
  40458. if (!fd->is_strict_mode
  40459. && func_kind == JS_FUNC_NORMAL
  40460. && find_lexical_decl(ctx, fd, func_name, fd->scope_first, false) < 0
  40461. && !((func_idx = find_var(ctx, fd, func_name)) >= 0 && (func_idx & ARGUMENT_VAR_OFFSET))
  40462. && !(func_name == JS_ATOM_arguments && fd->has_arguments_binding)) {
  40463. create_func_var = true;
  40464. }
  40465. /* Create the lexical name here so that the function closure
  40466. contains it */
  40467. if (fd->is_eval &&
  40468. (fd->eval_type == JS_EVAL_TYPE_GLOBAL ||
  40469. fd->eval_type == JS_EVAL_TYPE_MODULE) &&
  40470. fd->scope_level == fd->body_scope) {
  40471. /* avoid creating a lexical variable in the global
  40472. scope. XXX: check annex B */
  40473. JSGlobalVar *hf;
  40474. hf = find_global_var(fd, func_name);
  40475. /* XXX: should check scope chain */
  40476. if (hf && hf->scope_level == fd->scope_level) {
  40477. js_parse_error(s, "invalid redefinition of global identifier");
  40478. JS_FreeAtom(ctx, func_name);
  40479. return -1;
  40480. }
  40481. } else {
  40482. /* Always create a lexical name, fail if at the same scope as
  40483. existing name */
  40484. /* Lexical variable will be initialized upon entering scope */
  40485. lexical_func_idx = define_var(s, fd, func_name,
  40486. func_kind != JS_FUNC_NORMAL ?
  40487. JS_VAR_DEF_NEW_FUNCTION_DECL :
  40488. JS_VAR_DEF_FUNCTION_DECL);
  40489. if (lexical_func_idx < 0) {
  40490. JS_FreeAtom(ctx, func_name);
  40491. return -1;
  40492. }
  40493. }
  40494. }
  40495. fd = js_new_function_def(ctx, fd, false, is_expr, s->filename,
  40496. function_line_num, function_col_num);
  40497. if (!fd) {
  40498. JS_FreeAtom(ctx, func_name);
  40499. return -1;
  40500. }
  40501. if (pfd)
  40502. *pfd = fd;
  40503. s->cur_func = fd;
  40504. fd->func_name = func_name;
  40505. /* XXX: test !fd->is_generator is always false */
  40506. fd->has_prototype = (func_type == JS_PARSE_FUNC_STATEMENT ||
  40507. func_type == JS_PARSE_FUNC_VAR ||
  40508. func_type == JS_PARSE_FUNC_EXPR) &&
  40509. func_kind == JS_FUNC_NORMAL;
  40510. fd->has_home_object = (func_type == JS_PARSE_FUNC_METHOD ||
  40511. func_type == JS_PARSE_FUNC_GETTER ||
  40512. func_type == JS_PARSE_FUNC_SETTER ||
  40513. func_type == JS_PARSE_FUNC_CLASS_CONSTRUCTOR ||
  40514. func_type == JS_PARSE_FUNC_DERIVED_CLASS_CONSTRUCTOR);
  40515. fd->has_arguments_binding = (func_type != JS_PARSE_FUNC_ARROW &&
  40516. func_type != JS_PARSE_FUNC_CLASS_STATIC_INIT);
  40517. fd->has_this_binding = fd->has_arguments_binding;
  40518. fd->is_derived_class_constructor = (func_type == JS_PARSE_FUNC_DERIVED_CLASS_CONSTRUCTOR);
  40519. if (func_type == JS_PARSE_FUNC_ARROW) {
  40520. fd->new_target_allowed = fd->parent->new_target_allowed;
  40521. fd->super_call_allowed = fd->parent->super_call_allowed;
  40522. fd->super_allowed = fd->parent->super_allowed;
  40523. fd->arguments_allowed = fd->parent->arguments_allowed;
  40524. } else if (func_type == JS_PARSE_FUNC_CLASS_STATIC_INIT) {
  40525. fd->new_target_allowed = true; // although new.target === undefined
  40526. fd->super_call_allowed = false;
  40527. fd->super_allowed = true;
  40528. fd->arguments_allowed = false;
  40529. } else {
  40530. fd->new_target_allowed = true;
  40531. fd->super_call_allowed = fd->is_derived_class_constructor;
  40532. fd->super_allowed = fd->has_home_object;
  40533. fd->arguments_allowed = true;
  40534. }
  40535. /* fd->in_function_body == false prevents yield/await during the parsing
  40536. of the arguments in generator/async functions. They are parsed as
  40537. regular identifiers for other function kinds. */
  40538. fd->func_kind = func_kind;
  40539. fd->func_type = func_type;
  40540. if (func_type == JS_PARSE_FUNC_CLASS_CONSTRUCTOR ||
  40541. func_type == JS_PARSE_FUNC_DERIVED_CLASS_CONSTRUCTOR) {
  40542. /* error if not invoked as a constructor */
  40543. emit_op(s, OP_check_ctor);
  40544. }
  40545. if (func_type == JS_PARSE_FUNC_CLASS_CONSTRUCTOR) {
  40546. emit_class_field_init(s);
  40547. }
  40548. /* parse arguments */
  40549. fd->has_simple_parameter_list = true;
  40550. fd->has_parameter_expressions = false;
  40551. has_opt_arg = false;
  40552. if (func_type == JS_PARSE_FUNC_ARROW && s->token.val == TOK_IDENT) {
  40553. JSAtom name;
  40554. if (s->token.u.ident.is_reserved) {
  40555. js_parse_error_reserved_identifier(s);
  40556. goto fail;
  40557. }
  40558. name = s->token.u.ident.atom;
  40559. if (add_arg(ctx, fd, name) < 0)
  40560. goto fail;
  40561. fd->defined_arg_count = 1;
  40562. } else if (func_type != JS_PARSE_FUNC_CLASS_STATIC_INIT) {
  40563. if (s->token.val == '(') {
  40564. int skip_bits;
  40565. /* if there is an '=' inside the parameter list, we
  40566. consider there is a parameter expression inside */
  40567. js_parse_skip_parens_token(s, &skip_bits, false);
  40568. if (skip_bits & SKIP_HAS_ASSIGNMENT)
  40569. fd->has_parameter_expressions = true;
  40570. if (next_token(s))
  40571. goto fail;
  40572. } else {
  40573. if (js_parse_expect(s, '('))
  40574. goto fail;
  40575. }
  40576. if (fd->has_parameter_expressions) {
  40577. fd->scope_level = -1; /* force no parent scope */
  40578. if (push_scope(s) < 0)
  40579. return -1;
  40580. }
  40581. while (s->token.val != ')') {
  40582. JSAtom name;
  40583. bool rest = false;
  40584. int idx, has_initializer;
  40585. if (s->token.val == TOK_ELLIPSIS) {
  40586. fd->has_simple_parameter_list = false;
  40587. rest = true;
  40588. if (next_token(s))
  40589. goto fail;
  40590. }
  40591. if (s->token.val == '[' || s->token.val == '{') {
  40592. fd->has_simple_parameter_list = false;
  40593. if (rest) {
  40594. emit_op(s, OP_rest);
  40595. emit_u16(s, fd->arg_count);
  40596. } else {
  40597. /* unnamed arg for destructuring */
  40598. idx = add_arg(ctx, fd, JS_ATOM_NULL);
  40599. emit_op(s, OP_get_arg);
  40600. emit_u16(s, idx);
  40601. }
  40602. has_initializer = js_parse_destructuring_element(s, fd->has_parameter_expressions ? TOK_LET : TOK_VAR, true, true, -1, true, false);
  40603. if (has_initializer < 0)
  40604. goto fail;
  40605. if (has_initializer)
  40606. has_opt_arg = true;
  40607. if (!has_opt_arg)
  40608. fd->defined_arg_count++;
  40609. } else if (s->token.val == TOK_IDENT) {
  40610. if (s->token.u.ident.is_reserved) {
  40611. js_parse_error_reserved_identifier(s);
  40612. goto fail;
  40613. }
  40614. name = s->token.u.ident.atom;
  40615. if (name == JS_ATOM_yield && fd->func_kind == JS_FUNC_GENERATOR) {
  40616. js_parse_error_reserved_identifier(s);
  40617. goto fail;
  40618. }
  40619. if (fd->has_parameter_expressions) {
  40620. if (js_parse_check_duplicate_parameter(s, name))
  40621. goto fail;
  40622. if (define_var(s, fd, name, JS_VAR_DEF_LET) < 0)
  40623. goto fail;
  40624. }
  40625. /* XXX: could avoid allocating an argument if rest is true */
  40626. idx = add_arg(ctx, fd, name);
  40627. if (idx < 0)
  40628. goto fail;
  40629. if (next_token(s))
  40630. goto fail;
  40631. if (rest) {
  40632. emit_op(s, OP_rest);
  40633. emit_u16(s, idx);
  40634. if (fd->has_parameter_expressions) {
  40635. emit_op(s, OP_dup);
  40636. emit_op(s, OP_scope_put_var_init);
  40637. emit_atom(s, name);
  40638. emit_u16(s, fd->scope_level);
  40639. }
  40640. emit_op(s, OP_put_arg);
  40641. emit_u16(s, idx);
  40642. fd->has_simple_parameter_list = false;
  40643. has_opt_arg = true;
  40644. } else if (s->token.val == '=') {
  40645. int label;
  40646. fd->has_simple_parameter_list = false;
  40647. has_opt_arg = true;
  40648. if (next_token(s))
  40649. goto fail;
  40650. label = new_label(s);
  40651. emit_op(s, OP_get_arg);
  40652. emit_u16(s, idx);
  40653. emit_op(s, OP_dup);
  40654. emit_op(s, OP_undefined);
  40655. emit_op(s, OP_strict_eq);
  40656. emit_goto(s, OP_if_false, label);
  40657. emit_op(s, OP_drop);
  40658. if (js_parse_assign_expr(s))
  40659. goto fail;
  40660. set_object_name(s, name);
  40661. emit_op(s, OP_dup);
  40662. emit_op(s, OP_put_arg);
  40663. emit_u16(s, idx);
  40664. emit_label(s, label);
  40665. emit_op(s, OP_scope_put_var_init);
  40666. emit_atom(s, name);
  40667. emit_u16(s, fd->scope_level);
  40668. } else {
  40669. if (!has_opt_arg) {
  40670. fd->defined_arg_count++;
  40671. }
  40672. if (fd->has_parameter_expressions) {
  40673. /* copy the argument to the argument scope */
  40674. emit_op(s, OP_get_arg);
  40675. emit_u16(s, idx);
  40676. emit_op(s, OP_scope_put_var_init);
  40677. emit_atom(s, name);
  40678. emit_u16(s, fd->scope_level);
  40679. }
  40680. }
  40681. } else {
  40682. js_parse_error(s, "missing formal parameter");
  40683. goto fail;
  40684. }
  40685. if (rest && s->token.val != ')') {
  40686. js_parse_expect(s, ')');
  40687. goto fail;
  40688. }
  40689. if (s->token.val == ')')
  40690. break;
  40691. if (js_parse_expect(s, ','))
  40692. goto fail;
  40693. }
  40694. if ((func_type == JS_PARSE_FUNC_GETTER && fd->arg_count != 0) ||
  40695. (func_type == JS_PARSE_FUNC_SETTER && fd->arg_count != 1)) {
  40696. js_parse_error(s, "invalid number of arguments for getter or setter");
  40697. goto fail;
  40698. }
  40699. }
  40700. if (fd->has_parameter_expressions) {
  40701. int idx;
  40702. /* Copy the variables in the argument scope to the variable
  40703. scope (see FunctionDeclarationInstantiation() in spec). The
  40704. normal arguments are already present, so no need to copy
  40705. them. */
  40706. idx = fd->scopes[fd->scope_level].first;
  40707. while (idx >= 0) {
  40708. JSVarDef *vd = &fd->vars[idx];
  40709. if (vd->scope_level != fd->scope_level)
  40710. break;
  40711. if (find_var(ctx, fd, vd->var_name) < 0) {
  40712. if (add_var(ctx, fd, vd->var_name) < 0)
  40713. goto fail;
  40714. vd = &fd->vars[idx]; /* fd->vars may have been reallocated */
  40715. emit_op(s, OP_scope_get_var);
  40716. emit_atom(s, vd->var_name);
  40717. emit_u16(s, fd->scope_level);
  40718. emit_op(s, OP_scope_put_var);
  40719. emit_atom(s, vd->var_name);
  40720. emit_u16(s, 0);
  40721. }
  40722. idx = vd->scope_next;
  40723. }
  40724. /* the argument scope has no parent, hence we don't use pop_scope(s) */
  40725. emit_op(s, OP_leave_scope);
  40726. emit_u16(s, fd->scope_level);
  40727. /* set the variable scope as the current scope */
  40728. fd->scope_level = 0;
  40729. fd->scope_first = fd->scopes[fd->scope_level].first;
  40730. }
  40731. if (next_token(s))
  40732. goto fail;
  40733. /* generator function: yield after the parameters are evaluated */
  40734. if (func_kind == JS_FUNC_GENERATOR ||
  40735. func_kind == JS_FUNC_ASYNC_GENERATOR)
  40736. emit_op(s, OP_initial_yield);
  40737. /* in generators, yield expression is forbidden during the parsing
  40738. of the arguments */
  40739. fd->in_function_body = true;
  40740. push_scope(s); /* enter body scope */
  40741. fd->body_scope = fd->scope_level;
  40742. if (s->token.val == TOK_ARROW) {
  40743. if (next_token(s))
  40744. goto fail;
  40745. if (s->token.val != '{') {
  40746. if (js_parse_function_check_names(s, fd, func_name))
  40747. goto fail;
  40748. if (js_parse_assign_expr(s))
  40749. goto fail;
  40750. if (func_kind != JS_FUNC_NORMAL)
  40751. emit_op(s, OP_return_async);
  40752. else
  40753. emit_op(s, OP_return);
  40754. /* save the function source code */
  40755. /* the end of the function source code is after the last
  40756. token of the function source stored into s->last_ptr */
  40757. fd->source_len = s->last_ptr - ptr;
  40758. fd->source = js_strndup(ctx, (const char *)ptr, fd->source_len);
  40759. if (!fd->source)
  40760. goto fail;
  40761. goto done;
  40762. }
  40763. }
  40764. // js_parse_class() already consumed the '{'
  40765. if (func_type != JS_PARSE_FUNC_CLASS_STATIC_INIT)
  40766. if (js_parse_expect(s, '{'))
  40767. goto fail;
  40768. if (js_parse_directives(s))
  40769. goto fail;
  40770. /* in strict_mode, check function and argument names */
  40771. if (js_parse_function_check_names(s, fd, func_name))
  40772. goto fail;
  40773. while (s->token.val != '}') {
  40774. if (js_parse_source_element(s))
  40775. goto fail;
  40776. }
  40777. /* save the function source code */
  40778. fd->source_len = s->buf_ptr - ptr;
  40779. fd->source = js_strndup(ctx, (const char *)ptr, fd->source_len);
  40780. if (!fd->source)
  40781. goto fail;
  40782. if (next_token(s)) {
  40783. /* consume the '}' */
  40784. goto fail;
  40785. }
  40786. /* in case there is no return, add one */
  40787. if (js_is_live_code(s)) {
  40788. emit_return(s, false);
  40789. }
  40790. done:
  40791. s->cur_func = fd->parent;
  40792. /* Reparse identifiers after the function is terminated so that
  40793. the token is parsed in the englobing function. It could be done
  40794. by just using next_token() here for normal functions, but it is
  40795. necessary for arrow functions with an expression body. */
  40796. reparse_ident_token(s);
  40797. /* create the function object */
  40798. {
  40799. int idx;
  40800. JSAtom func_name = fd->func_name;
  40801. /* the real object will be set at the end of the compilation */
  40802. idx = cpool_add(s, JS_NULL);
  40803. fd->parent_cpool_idx = idx;
  40804. if (is_expr) {
  40805. /* for constructors, no code needs to be generated here */
  40806. if (func_type != JS_PARSE_FUNC_CLASS_CONSTRUCTOR &&
  40807. func_type != JS_PARSE_FUNC_DERIVED_CLASS_CONSTRUCTOR) {
  40808. /* OP_fclosure creates the function object from the bytecode
  40809. and adds the scope information */
  40810. emit_op(s, OP_fclosure);
  40811. emit_u32(s, idx);
  40812. if (func_name == JS_ATOM_NULL) {
  40813. emit_op(s, OP_set_name);
  40814. emit_u32(s, JS_ATOM_NULL);
  40815. }
  40816. }
  40817. } else if (func_type == JS_PARSE_FUNC_VAR) {
  40818. emit_op(s, OP_fclosure);
  40819. emit_u32(s, idx);
  40820. if (create_func_var) {
  40821. if (s->cur_func->is_global_var) {
  40822. JSGlobalVar *hf;
  40823. /* the global variable must be defined at the start of the
  40824. function */
  40825. hf = add_global_var(ctx, s->cur_func, func_name);
  40826. if (!hf)
  40827. goto fail;
  40828. /* it is considered as defined at the top level
  40829. (needed for annex B.3.3.4 and B.3.3.5
  40830. checks) */
  40831. hf->scope_level = 0;
  40832. hf->force_init = s->cur_func->is_strict_mode;
  40833. /* store directly into global var, bypass lexical scope */
  40834. emit_op(s, OP_dup);
  40835. emit_op(s, OP_scope_put_var);
  40836. emit_atom(s, func_name);
  40837. emit_u16(s, 0);
  40838. } else {
  40839. /* do not call define_var to bypass lexical scope check */
  40840. func_idx = find_var(ctx, s->cur_func, func_name);
  40841. if (func_idx < 0) {
  40842. func_idx = add_var(ctx, s->cur_func, func_name);
  40843. if (func_idx < 0)
  40844. goto fail;
  40845. }
  40846. /* store directly into local var, bypass lexical catch scope */
  40847. emit_op(s, OP_dup);
  40848. emit_op(s, OP_scope_put_var);
  40849. emit_atom(s, func_name);
  40850. emit_u16(s, 0);
  40851. }
  40852. }
  40853. if (lexical_func_idx >= 0) {
  40854. /* lexical variable will be initialized upon entering scope */
  40855. s->cur_func->vars[lexical_func_idx].func_pool_idx = idx;
  40856. emit_op(s, OP_drop);
  40857. } else {
  40858. /* store function object into its lexical name */
  40859. /* XXX: could use OP_put_loc directly */
  40860. emit_op(s, OP_scope_put_var_init);
  40861. emit_atom(s, func_name);
  40862. emit_u16(s, s->cur_func->scope_level);
  40863. }
  40864. } else {
  40865. if (!s->cur_func->is_global_var) {
  40866. int var_idx = define_var(s, s->cur_func, func_name, JS_VAR_DEF_VAR);
  40867. if (var_idx < 0)
  40868. goto fail;
  40869. /* the variable will be assigned at the top of the function */
  40870. if (var_idx & ARGUMENT_VAR_OFFSET) {
  40871. s->cur_func->args[var_idx - ARGUMENT_VAR_OFFSET].func_pool_idx = idx;
  40872. } else {
  40873. s->cur_func->vars[var_idx].func_pool_idx = idx;
  40874. }
  40875. } else {
  40876. JSAtom func_var_name;
  40877. JSGlobalVar *hf;
  40878. if (func_name == JS_ATOM_NULL)
  40879. func_var_name = JS_ATOM__default_; /* export default */
  40880. else
  40881. func_var_name = func_name;
  40882. /* the variable will be assigned at the top of the function */
  40883. hf = add_global_var(ctx, s->cur_func, func_var_name);
  40884. if (!hf)
  40885. goto fail;
  40886. hf->cpool_idx = idx;
  40887. if (export_flag != JS_PARSE_EXPORT_NONE) {
  40888. if (!add_export_entry(s, s->cur_func->module, func_var_name,
  40889. export_flag == JS_PARSE_EXPORT_NAMED ? func_var_name : JS_ATOM_default, JS_EXPORT_TYPE_LOCAL))
  40890. goto fail;
  40891. }
  40892. }
  40893. }
  40894. }
  40895. return 0;
  40896. fail:
  40897. s->cur_func = fd->parent;
  40898. js_free_function_def(ctx, fd);
  40899. if (pfd)
  40900. *pfd = NULL;
  40901. return -1;
  40902. }
  40903. static __exception int js_parse_function_decl(JSParseState *s,
  40904. JSParseFunctionEnum func_type,
  40905. JSFunctionKindEnum func_kind,
  40906. JSAtom func_name,
  40907. const uint8_t *ptr,
  40908. int start_line,
  40909. int start_col)
  40910. {
  40911. return js_parse_function_decl2(s, func_type, func_kind, func_name, ptr,
  40912. start_line, start_col,
  40913. JS_PARSE_EXPORT_NONE, NULL);
  40914. }
  40915. static __exception int js_parse_program(JSParseState *s)
  40916. {
  40917. JSFunctionDef *fd = s->cur_func;
  40918. int idx;
  40919. if (next_token(s))
  40920. return -1;
  40921. if (js_parse_directives(s))
  40922. return -1;
  40923. fd->is_global_var = (fd->eval_type == JS_EVAL_TYPE_GLOBAL) ||
  40924. (fd->eval_type == JS_EVAL_TYPE_MODULE) ||
  40925. !fd->is_strict_mode;
  40926. if (!s->is_module) {
  40927. /* hidden variable for the return value */
  40928. fd->eval_ret_idx = idx = add_var(s->ctx, fd, JS_ATOM__ret_);
  40929. if (idx < 0)
  40930. return -1;
  40931. }
  40932. while (s->token.val != TOK_EOF) {
  40933. if (js_parse_source_element(s))
  40934. return -1;
  40935. }
  40936. if (!s->is_module) {
  40937. /* return the value of the hidden variable eval_ret_idx */
  40938. if (fd->func_kind == JS_FUNC_ASYNC) {
  40939. /* wrap the return value in an object so that promises can
  40940. be safely returned */
  40941. emit_op(s, OP_object);
  40942. emit_op(s, OP_dup);
  40943. emit_op(s, OP_get_loc);
  40944. emit_u16(s, fd->eval_ret_idx);
  40945. emit_op(s, OP_put_field);
  40946. emit_atom(s, JS_ATOM_value);
  40947. } else {
  40948. emit_op(s, OP_get_loc);
  40949. emit_u16(s, fd->eval_ret_idx);
  40950. }
  40951. emit_return(s, true);
  40952. } else {
  40953. emit_return(s, false);
  40954. }
  40955. return 0;
  40956. }
  40957. static void js_parse_init(JSContext *ctx, JSParseState *s,
  40958. const char *input, size_t input_len,
  40959. const char *filename, int line)
  40960. {
  40961. memset(s, 0, sizeof(*s));
  40962. s->ctx = ctx;
  40963. s->filename = filename;
  40964. s->line_num = line;
  40965. s->col_num = 1;
  40966. s->buf_start = s->buf_ptr = (const uint8_t *)input;
  40967. s->buf_end = s->buf_ptr + input_len;
  40968. s->mark = s->buf_ptr + min_int(1, input_len);
  40969. s->eol = s->buf_ptr;
  40970. s->token.val = ' ';
  40971. s->token.line_num = 1;
  40972. s->token.col_num = 1;
  40973. }
  40974. static JSValue JS_EvalFunctionInternal(JSContext *ctx, JSValue fun_obj,
  40975. JSValueConst this_obj,
  40976. JSVarRef **var_refs, JSStackFrame *sf)
  40977. {
  40978. JSValue ret_val;
  40979. uint32_t tag;
  40980. tag = JS_VALUE_GET_TAG(fun_obj);
  40981. if (tag == JS_TAG_FUNCTION_BYTECODE) {
  40982. fun_obj = js_closure(ctx, fun_obj, var_refs, sf);
  40983. ret_val = JS_CallFree(ctx, fun_obj, this_obj, 0, NULL);
  40984. } else if (tag == JS_TAG_MODULE) {
  40985. JSModuleDef *m;
  40986. m = JS_VALUE_GET_PTR(fun_obj);
  40987. /* the module refcount should be >= 2 */
  40988. JS_FreeValue(ctx, fun_obj);
  40989. if (js_create_module_function(ctx, m) < 0)
  40990. goto fail;
  40991. if (js_link_module(ctx, m) < 0)
  40992. goto fail;
  40993. ret_val = js_evaluate_module(ctx, m);
  40994. if (JS_IsException(ret_val)) {
  40995. fail:
  40996. return JS_EXCEPTION;
  40997. }
  40998. } else {
  40999. JS_FreeValue(ctx, fun_obj);
  41000. ret_val = JS_ThrowTypeError(ctx, "bytecode function expected");
  41001. }
  41002. return ret_val;
  41003. }
  41004. JSValue JS_EvalFunction(JSContext *ctx, JSValue fun_obj)
  41005. {
  41006. return JS_EvalFunctionInternal(ctx, fun_obj, ctx->global_obj, NULL, NULL);
  41007. }
  41008. /* 'input' must be zero terminated i.e. input[input_len] = '\0'. */
  41009. /* `export_name` and `input` may be pure ASCII or UTF-8 encoded */
  41010. static JSValue __JS_EvalInternal(JSContext *ctx, JSValueConst this_obj,
  41011. const char *input, size_t input_len,
  41012. const char *filename, int line, int flags, int scope_idx)
  41013. {
  41014. JSParseState s1, *s = &s1;
  41015. int err, eval_type;
  41016. JSValue fun_obj, ret_val;
  41017. JSStackFrame *sf;
  41018. JSVarRef **var_refs;
  41019. JSFunctionBytecode *b;
  41020. JSFunctionDef *fd;
  41021. JSModuleDef *m;
  41022. bool is_strict_mode;
  41023. js_parse_init(ctx, s, input, input_len, filename, line);
  41024. skip_shebang(&s->buf_ptr, s->buf_end);
  41025. eval_type = flags & JS_EVAL_TYPE_MASK;
  41026. m = NULL;
  41027. if (eval_type == JS_EVAL_TYPE_DIRECT) {
  41028. JSObject *p;
  41029. sf = ctx->rt->current_stack_frame;
  41030. assert(sf != NULL);
  41031. assert(JS_VALUE_GET_TAG(sf->cur_func) == JS_TAG_OBJECT);
  41032. p = JS_VALUE_GET_OBJ(sf->cur_func);
  41033. assert(js_class_has_bytecode(p->class_id));
  41034. b = p->u.func.function_bytecode;
  41035. var_refs = p->u.func.var_refs;
  41036. is_strict_mode = b->is_strict_mode;
  41037. } else {
  41038. sf = NULL;
  41039. b = NULL;
  41040. var_refs = NULL;
  41041. is_strict_mode = (flags & JS_EVAL_FLAG_STRICT) != 0;
  41042. if (eval_type == JS_EVAL_TYPE_MODULE) {
  41043. JSAtom module_name = JS_NewAtom(ctx, filename);
  41044. if (module_name == JS_ATOM_NULL)
  41045. return JS_EXCEPTION;
  41046. m = js_new_module_def(ctx, module_name);
  41047. if (!m)
  41048. return JS_EXCEPTION;
  41049. is_strict_mode = true;
  41050. }
  41051. }
  41052. fd = js_new_function_def(ctx, NULL, true, false, filename, line, 1);
  41053. if (!fd)
  41054. goto fail1;
  41055. s->cur_func = fd;
  41056. fd->eval_type = eval_type;
  41057. fd->has_this_binding = (eval_type != JS_EVAL_TYPE_DIRECT);
  41058. fd->backtrace_barrier = ((flags & JS_EVAL_FLAG_BACKTRACE_BARRIER) != 0);
  41059. if (eval_type == JS_EVAL_TYPE_DIRECT) {
  41060. fd->new_target_allowed = b->new_target_allowed;
  41061. fd->super_call_allowed = b->super_call_allowed;
  41062. fd->super_allowed = b->super_allowed;
  41063. fd->arguments_allowed = b->arguments_allowed;
  41064. } else {
  41065. fd->new_target_allowed = false;
  41066. fd->super_call_allowed = false;
  41067. fd->super_allowed = false;
  41068. fd->arguments_allowed = true;
  41069. }
  41070. fd->is_strict_mode = is_strict_mode;
  41071. fd->func_name = JS_DupAtom(ctx, JS_ATOM__eval_);
  41072. if (b) {
  41073. if (add_closure_variables(ctx, fd, b, scope_idx))
  41074. goto fail;
  41075. }
  41076. fd->module = m;
  41077. if (m != NULL || (flags & JS_EVAL_FLAG_ASYNC)) {
  41078. fd->in_function_body = true;
  41079. fd->func_kind = JS_FUNC_ASYNC;
  41080. }
  41081. s->is_module = (m != NULL);
  41082. s->allow_html_comments = !s->is_module;
  41083. push_scope(s); /* body scope */
  41084. fd->body_scope = fd->scope_level;
  41085. err = js_parse_program(s);
  41086. if (err) {
  41087. fail:
  41088. free_token(s, &s->token);
  41089. js_free_function_def(ctx, fd);
  41090. goto fail1;
  41091. }
  41092. if (m != NULL)
  41093. m->has_tla = fd->has_await;
  41094. /* create the function object and all the enclosed functions */
  41095. fun_obj = js_create_function(ctx, fd);
  41096. if (JS_IsException(fun_obj))
  41097. goto fail1;
  41098. /* Could add a flag to avoid resolution if necessary */
  41099. if (m) {
  41100. m->func_obj = fun_obj;
  41101. if (js_resolve_module(ctx, m) < 0)
  41102. goto fail1;
  41103. fun_obj = JS_NewModuleValue(ctx, m);
  41104. }
  41105. if (flags & JS_EVAL_FLAG_COMPILE_ONLY) {
  41106. ret_val = fun_obj;
  41107. } else {
  41108. ret_val = JS_EvalFunctionInternal(ctx, fun_obj, this_obj, var_refs, sf);
  41109. }
  41110. return ret_val;
  41111. fail1:
  41112. /* XXX: should free all the unresolved dependencies */
  41113. if (m)
  41114. js_free_module_def(ctx, m);
  41115. return JS_EXCEPTION;
  41116. }
  41117. /* the indirection is needed to make 'eval' optional */
  41118. static JSValue JS_EvalInternal(JSContext *ctx, JSValueConst this_obj,
  41119. const char *input, size_t input_len,
  41120. const char *filename, int line, int flags, int scope_idx)
  41121. {
  41122. JSRuntime *rt = ctx->rt;
  41123. if (unlikely(!ctx->eval_internal)) {
  41124. return JS_ThrowTypeError(ctx, "eval is not supported");
  41125. }
  41126. if (!rt->current_stack_frame) {
  41127. JS_FreeValueRT(rt, ctx->error_back_trace);
  41128. ctx->error_back_trace = JS_UNDEFINED;
  41129. }
  41130. return ctx->eval_internal(ctx, this_obj, input, input_len, filename, line,
  41131. flags, scope_idx);
  41132. }
  41133. static JSValue JS_EvalObject(JSContext *ctx, JSValueConst this_obj,
  41134. JSValueConst val, int flags, int scope_idx)
  41135. {
  41136. JSValue ret;
  41137. const char *str;
  41138. size_t len;
  41139. if (!JS_IsString(val))
  41140. return js_dup(val);
  41141. str = JS_ToCStringLen(ctx, &len, val);
  41142. if (!str)
  41143. return JS_EXCEPTION;
  41144. ret = JS_EvalInternal(ctx, this_obj, str, len, "<input>", 1, flags, scope_idx);
  41145. JS_FreeCString(ctx, str);
  41146. return ret;
  41147. }
  41148. JSValue JS_EvalThis(JSContext *ctx, JSValueConst this_obj,
  41149. const char *input, size_t input_len,
  41150. const char *filename, int eval_flags)
  41151. {
  41152. JSEvalOptions options = {
  41153. .version = JS_EVAL_OPTIONS_VERSION,
  41154. .filename = filename,
  41155. .line_num = 1,
  41156. .eval_flags = eval_flags
  41157. };
  41158. return JS_EvalThis2(ctx, this_obj, input, input_len, &options);
  41159. }
  41160. JSValue JS_EvalThis2(JSContext *ctx, JSValueConst this_obj,
  41161. const char *input, size_t input_len,
  41162. JSEvalOptions *options)
  41163. {
  41164. const char *filename = "<unnamed>";
  41165. int line = 1;
  41166. int eval_flags = 0;
  41167. if (options) {
  41168. if (options->version != JS_EVAL_OPTIONS_VERSION)
  41169. return JS_ThrowInternalError(ctx, "bad JSEvalOptions version");
  41170. if (options->filename)
  41171. filename = options->filename;
  41172. if (options->line_num != 0)
  41173. line = options->line_num;
  41174. eval_flags = options->eval_flags;
  41175. }
  41176. JSValue ret;
  41177. assert((eval_flags & JS_EVAL_TYPE_MASK) == JS_EVAL_TYPE_GLOBAL ||
  41178. (eval_flags & JS_EVAL_TYPE_MASK) == JS_EVAL_TYPE_MODULE);
  41179. ret = JS_EvalInternal(ctx, this_obj, input, input_len, filename, line,
  41180. eval_flags, -1);
  41181. return ret;
  41182. }
  41183. JSValue JS_Eval(JSContext *ctx, const char *input, size_t input_len,
  41184. const char *filename, int eval_flags)
  41185. {
  41186. JSEvalOptions options = {
  41187. .version = JS_EVAL_OPTIONS_VERSION,
  41188. .filename = filename,
  41189. .line_num = 1,
  41190. .eval_flags = eval_flags
  41191. };
  41192. return JS_EvalThis2(ctx, ctx->global_obj, input, input_len, &options);
  41193. }
  41194. JSValue JS_Eval2(JSContext *ctx, const char *input, size_t input_len, JSEvalOptions *options)
  41195. {
  41196. return JS_EvalThis2(ctx, ctx->global_obj, input, input_len, options);
  41197. }
  41198. int JS_ResolveModule(JSContext *ctx, JSValueConst obj)
  41199. {
  41200. if (JS_VALUE_GET_TAG(obj) == JS_TAG_MODULE) {
  41201. JSModuleDef *m = JS_VALUE_GET_PTR(obj);
  41202. if (js_resolve_module(ctx, m) < 0) {
  41203. js_free_modules(ctx, JS_FREE_MODULE_NOT_RESOLVED);
  41204. return -1;
  41205. }
  41206. }
  41207. return 0;
  41208. }
  41209. /*******************************************************************/
  41210. /* object list */
  41211. typedef struct {
  41212. JSObject *obj;
  41213. uint32_t hash_next; /* -1 if no next entry */
  41214. } JSObjectListEntry;
  41215. /* XXX: reuse it to optimize weak references */
  41216. typedef struct {
  41217. JSObjectListEntry *object_tab;
  41218. int object_count;
  41219. int object_size;
  41220. uint32_t *hash_table;
  41221. uint32_t hash_size;
  41222. } JSObjectList;
  41223. static void js_object_list_init(JSObjectList *s)
  41224. {
  41225. memset(s, 0, sizeof(*s));
  41226. }
  41227. static uint32_t js_object_list_get_hash(JSObject *p, uint32_t hash_size)
  41228. {
  41229. return ((uintptr_t)p * 3163) & (hash_size - 1);
  41230. }
  41231. static int js_object_list_resize_hash(JSContext *ctx, JSObjectList *s,
  41232. uint32_t new_hash_size)
  41233. {
  41234. JSObjectListEntry *e;
  41235. uint32_t i, h, *new_hash_table;
  41236. new_hash_table = js_malloc(ctx, sizeof(new_hash_table[0]) * new_hash_size);
  41237. if (!new_hash_table)
  41238. return -1;
  41239. js_free(ctx, s->hash_table);
  41240. s->hash_table = new_hash_table;
  41241. s->hash_size = new_hash_size;
  41242. for(i = 0; i < s->hash_size; i++) {
  41243. s->hash_table[i] = -1;
  41244. }
  41245. for(i = 0; i < s->object_count; i++) {
  41246. e = &s->object_tab[i];
  41247. h = js_object_list_get_hash(e->obj, s->hash_size);
  41248. e->hash_next = s->hash_table[h];
  41249. s->hash_table[h] = i;
  41250. }
  41251. return 0;
  41252. }
  41253. /* the reference count of 'obj' is not modified. Return 0 if OK, -1 if
  41254. memory error */
  41255. static int js_object_list_add(JSContext *ctx, JSObjectList *s, JSObject *obj)
  41256. {
  41257. JSObjectListEntry *e;
  41258. uint32_t h, new_hash_size;
  41259. if (js_resize_array(ctx, (void *)&s->object_tab,
  41260. sizeof(s->object_tab[0]),
  41261. &s->object_size, s->object_count + 1))
  41262. return -1;
  41263. if (unlikely((s->object_count + 1) >= s->hash_size)) {
  41264. new_hash_size = max_uint32(s->hash_size, 4);
  41265. while (new_hash_size <= s->object_count)
  41266. new_hash_size *= 2;
  41267. if (js_object_list_resize_hash(ctx, s, new_hash_size))
  41268. return -1;
  41269. }
  41270. e = &s->object_tab[s->object_count++];
  41271. h = js_object_list_get_hash(obj, s->hash_size);
  41272. e->obj = obj;
  41273. e->hash_next = s->hash_table[h];
  41274. s->hash_table[h] = s->object_count - 1;
  41275. return 0;
  41276. }
  41277. /* return -1 if not present or the object index */
  41278. static int js_object_list_find(JSContext *ctx, JSObjectList *s, JSObject *obj)
  41279. {
  41280. JSObjectListEntry *e;
  41281. uint32_t h, p;
  41282. /* must test empty size because there is no hash table */
  41283. if (s->object_count == 0)
  41284. return -1;
  41285. h = js_object_list_get_hash(obj, s->hash_size);
  41286. p = s->hash_table[h];
  41287. while (p != -1) {
  41288. e = &s->object_tab[p];
  41289. if (e->obj == obj)
  41290. return p;
  41291. p = e->hash_next;
  41292. }
  41293. return -1;
  41294. }
  41295. static void js_object_list_end(JSContext *ctx, JSObjectList *s)
  41296. {
  41297. js_free(ctx, s->object_tab);
  41298. js_free(ctx, s->hash_table);
  41299. }
  41300. /*******************************************************************/
  41301. /* binary object writer & reader */
  41302. typedef enum BCTagEnum {
  41303. BC_TAG_NULL = 1,
  41304. BC_TAG_UNDEFINED,
  41305. BC_TAG_BOOL_FALSE,
  41306. BC_TAG_BOOL_TRUE,
  41307. BC_TAG_INT32,
  41308. BC_TAG_FLOAT64,
  41309. BC_TAG_STRING,
  41310. BC_TAG_OBJECT,
  41311. BC_TAG_ARRAY,
  41312. BC_TAG_BIG_INT,
  41313. BC_TAG_TEMPLATE_OBJECT,
  41314. BC_TAG_FUNCTION_BYTECODE,
  41315. BC_TAG_MODULE,
  41316. BC_TAG_TYPED_ARRAY,
  41317. BC_TAG_ARRAY_BUFFER,
  41318. BC_TAG_SHARED_ARRAY_BUFFER,
  41319. BC_TAG_REGEXP,
  41320. BC_TAG_DATE,
  41321. BC_TAG_OBJECT_VALUE,
  41322. BC_TAG_OBJECT_REFERENCE,
  41323. BC_TAG_MAP,
  41324. BC_TAG_SET,
  41325. BC_TAG_SYMBOL,
  41326. } BCTagEnum;
  41327. #define BC_VERSION 19
  41328. typedef struct BCWriterState {
  41329. JSContext *ctx;
  41330. DynBuf dbuf;
  41331. bool allow_bytecode;
  41332. bool allow_sab;
  41333. bool allow_reference;
  41334. bool allow_source;
  41335. bool allow_debug;
  41336. uint32_t first_atom;
  41337. uint32_t *atom_to_idx;
  41338. int atom_to_idx_size;
  41339. JSAtom *idx_to_atom;
  41340. int idx_to_atom_count;
  41341. int idx_to_atom_size;
  41342. uint8_t **sab_tab;
  41343. int sab_tab_len;
  41344. int sab_tab_size;
  41345. /* list of referenced objects (used if allow_reference = true) */
  41346. JSObjectList object_list;
  41347. } BCWriterState;
  41348. #ifdef ENABLE_DUMPS // JS_DUMP_READ_OBJECT
  41349. static const char * const bc_tag_str[] = {
  41350. "invalid",
  41351. "null",
  41352. "undefined",
  41353. "false",
  41354. "true",
  41355. "int32",
  41356. "float64",
  41357. "string",
  41358. "object",
  41359. "array",
  41360. "BigInt",
  41361. "template",
  41362. "function",
  41363. "module",
  41364. "TypedArray",
  41365. "ArrayBuffer",
  41366. "SharedArrayBuffer",
  41367. "RegExp",
  41368. "Date",
  41369. "ObjectValue",
  41370. "ObjectReference",
  41371. "Map",
  41372. "Set",
  41373. "Symbol",
  41374. };
  41375. #endif
  41376. static void bc_put_u8(BCWriterState *s, uint8_t v)
  41377. {
  41378. dbuf_putc(&s->dbuf, v);
  41379. }
  41380. static void bc_put_u16(BCWriterState *s, uint16_t v)
  41381. {
  41382. if (is_be())
  41383. v = bswap16(v);
  41384. dbuf_put_u16(&s->dbuf, v);
  41385. }
  41386. static __maybe_unused void bc_put_u32(BCWriterState *s, uint32_t v)
  41387. {
  41388. if (is_be())
  41389. v = bswap32(v);
  41390. dbuf_put_u32(&s->dbuf, v);
  41391. }
  41392. static void bc_put_u64(BCWriterState *s, uint64_t v)
  41393. {
  41394. if (is_be())
  41395. v = bswap64(v);
  41396. dbuf_put(&s->dbuf, (uint8_t *)&v, sizeof(v));
  41397. }
  41398. static void bc_put_leb128(BCWriterState *s, uint32_t v)
  41399. {
  41400. dbuf_put_leb128(&s->dbuf, v);
  41401. }
  41402. static void bc_put_sleb128(BCWriterState *s, int32_t v)
  41403. {
  41404. dbuf_put_sleb128(&s->dbuf, v);
  41405. }
  41406. static void bc_set_flags(uint32_t *pflags, int *pidx, uint32_t val, int n)
  41407. {
  41408. *pflags = *pflags | (val << *pidx);
  41409. *pidx += n;
  41410. }
  41411. static int bc_atom_to_idx(BCWriterState *s, uint32_t *pres, JSAtom atom)
  41412. {
  41413. uint32_t v;
  41414. if (atom < s->first_atom || __JS_AtomIsTaggedInt(atom)) {
  41415. *pres = atom;
  41416. return 0;
  41417. }
  41418. atom -= s->first_atom;
  41419. if (atom < s->atom_to_idx_size && s->atom_to_idx[atom] != 0) {
  41420. *pres = s->atom_to_idx[atom];
  41421. return 0;
  41422. }
  41423. if (atom >= s->atom_to_idx_size) {
  41424. int old_size, i;
  41425. old_size = s->atom_to_idx_size;
  41426. if (js_resize_array(s->ctx, (void **)&s->atom_to_idx,
  41427. sizeof(s->atom_to_idx[0]), &s->atom_to_idx_size,
  41428. atom + 1))
  41429. return -1;
  41430. /* XXX: could add a specific js_resize_array() function to do it */
  41431. for(i = old_size; i < s->atom_to_idx_size; i++)
  41432. s->atom_to_idx[i] = 0;
  41433. }
  41434. if (js_resize_array(s->ctx, (void **)&s->idx_to_atom,
  41435. sizeof(s->idx_to_atom[0]),
  41436. &s->idx_to_atom_size, s->idx_to_atom_count + 1))
  41437. goto fail;
  41438. v = s->idx_to_atom_count++;
  41439. s->idx_to_atom[v] = atom + s->first_atom;
  41440. v += s->first_atom;
  41441. s->atom_to_idx[atom] = v;
  41442. *pres = v;
  41443. return 0;
  41444. fail:
  41445. *pres = 0;
  41446. return -1;
  41447. }
  41448. static int bc_put_atom(BCWriterState *s, JSAtom atom)
  41449. {
  41450. uint32_t v;
  41451. if (__JS_AtomIsTaggedInt(atom)) {
  41452. v = (__JS_AtomToUInt32(atom) << 1) | 1;
  41453. } else {
  41454. if (bc_atom_to_idx(s, &v, atom))
  41455. return -1;
  41456. v <<= 1;
  41457. }
  41458. bc_put_leb128(s, v);
  41459. return 0;
  41460. }
  41461. static void bc_byte_swap(uint8_t *bc_buf, int bc_len)
  41462. {
  41463. int pos, len, op, fmt;
  41464. pos = 0;
  41465. while (pos < bc_len) {
  41466. op = bc_buf[pos];
  41467. len = short_opcode_info(op).size;
  41468. fmt = short_opcode_info(op).fmt;
  41469. switch(fmt) {
  41470. case OP_FMT_u16:
  41471. case OP_FMT_i16:
  41472. case OP_FMT_label16:
  41473. case OP_FMT_npop:
  41474. case OP_FMT_loc:
  41475. case OP_FMT_arg:
  41476. case OP_FMT_var_ref:
  41477. put_u16(bc_buf + pos + 1,
  41478. bswap16(get_u16(bc_buf + pos + 1)));
  41479. break;
  41480. case OP_FMT_i32:
  41481. case OP_FMT_u32:
  41482. case OP_FMT_const:
  41483. case OP_FMT_label:
  41484. case OP_FMT_atom:
  41485. case OP_FMT_atom_u8:
  41486. put_u32(bc_buf + pos + 1,
  41487. bswap32(get_u32(bc_buf + pos + 1)));
  41488. break;
  41489. case OP_FMT_atom_u16:
  41490. case OP_FMT_label_u16:
  41491. put_u32(bc_buf + pos + 1,
  41492. bswap32(get_u32(bc_buf + pos + 1)));
  41493. put_u16(bc_buf + pos + 1 + 4,
  41494. bswap16(get_u16(bc_buf + pos + 1 + 4)));
  41495. break;
  41496. case OP_FMT_atom_label_u8:
  41497. case OP_FMT_atom_label_u16:
  41498. put_u32(bc_buf + pos + 1,
  41499. bswap32(get_u32(bc_buf + pos + 1)));
  41500. put_u32(bc_buf + pos + 1 + 4,
  41501. bswap32(get_u32(bc_buf + pos + 1 + 4)));
  41502. if (fmt == OP_FMT_atom_label_u16) {
  41503. put_u16(bc_buf + pos + 1 + 4 + 4,
  41504. bswap16(get_u16(bc_buf + pos + 1 + 4 + 4)));
  41505. }
  41506. break;
  41507. case OP_FMT_npop_u16:
  41508. put_u16(bc_buf + pos + 1,
  41509. bswap16(get_u16(bc_buf + pos + 1)));
  41510. put_u16(bc_buf + pos + 1 + 2,
  41511. bswap16(get_u16(bc_buf + pos + 1 + 2)));
  41512. break;
  41513. default:
  41514. break;
  41515. }
  41516. pos += len;
  41517. }
  41518. }
  41519. static int JS_WriteFunctionBytecode(BCWriterState *s,
  41520. const JSFunctionBytecode *b)
  41521. {
  41522. int pos, len, bc_len, op;
  41523. JSAtom atom;
  41524. uint8_t *bc_buf;
  41525. uint32_t val;
  41526. bc_len = b->byte_code_len;
  41527. bc_buf = js_malloc(s->ctx, bc_len);
  41528. if (!bc_buf)
  41529. return -1;
  41530. memcpy(bc_buf, b->byte_code_buf, bc_len);
  41531. pos = 0;
  41532. while (pos < bc_len) {
  41533. op = bc_buf[pos];
  41534. len = short_opcode_info(op).size;
  41535. switch(short_opcode_info(op).fmt) {
  41536. case OP_FMT_atom:
  41537. case OP_FMT_atom_u8:
  41538. case OP_FMT_atom_u16:
  41539. case OP_FMT_atom_label_u8:
  41540. case OP_FMT_atom_label_u16:
  41541. atom = get_u32(bc_buf + pos + 1);
  41542. if (bc_atom_to_idx(s, &val, atom))
  41543. goto fail;
  41544. put_u32(bc_buf + pos + 1, val);
  41545. break;
  41546. default:
  41547. break;
  41548. }
  41549. pos += len;
  41550. }
  41551. if (is_be())
  41552. bc_byte_swap(bc_buf, bc_len);
  41553. dbuf_put(&s->dbuf, bc_buf, bc_len);
  41554. js_free(s->ctx, bc_buf);
  41555. return 0;
  41556. fail:
  41557. js_free(s->ctx, bc_buf);
  41558. return -1;
  41559. }
  41560. static void JS_WriteString(BCWriterState *s, JSString *p)
  41561. {
  41562. int i;
  41563. bc_put_leb128(s, ((uint32_t)p->len << 1) | p->is_wide_char);
  41564. if (p->is_wide_char) {
  41565. for(i = 0; i < p->len; i++)
  41566. bc_put_u16(s, str16(p)[i]);
  41567. } else {
  41568. dbuf_put(&s->dbuf, str8(p), p->len);
  41569. }
  41570. }
  41571. static int JS_WriteBigInt(BCWriterState *s, JSValueConst obj)
  41572. {
  41573. uint32_t tag, tag1;
  41574. int64_t e;
  41575. JSBigInt *bf = JS_VALUE_GET_PTR(obj);
  41576. bf_t *a = &bf->num;
  41577. size_t len, i, n1, j;
  41578. limb_t v;
  41579. tag = JS_VALUE_GET_TAG(obj);
  41580. switch(tag) {
  41581. case JS_TAG_BIG_INT:
  41582. tag1 = BC_TAG_BIG_INT;
  41583. break;
  41584. default:
  41585. abort();
  41586. }
  41587. bc_put_u8(s, tag1);
  41588. /* sign + exponent */
  41589. if (a->expn == BF_EXP_ZERO)
  41590. e = 0;
  41591. else if (a->expn == BF_EXP_INF)
  41592. e = 1;
  41593. else if (a->expn == BF_EXP_NAN)
  41594. e = 2;
  41595. else if (a->expn >= 0)
  41596. e = a->expn + 3;
  41597. else
  41598. e = a->expn;
  41599. e = (e * 2) | a->sign;
  41600. if (e < INT32_MIN || e > INT32_MAX) {
  41601. JS_ThrowRangeError(s->ctx, "maximum BigInt size exceeded");
  41602. return -1;
  41603. }
  41604. bc_put_sleb128(s, e);
  41605. /* mantissa */
  41606. if (a->len != 0) {
  41607. i = 0;
  41608. while (i < a->len && a->tab[i] == 0)
  41609. i++;
  41610. assert(i < a->len);
  41611. v = a->tab[i];
  41612. n1 = sizeof(limb_t);
  41613. while ((v & 0xff) == 0) {
  41614. n1--;
  41615. v >>= 8;
  41616. }
  41617. i++;
  41618. len = (a->len - i) * sizeof(limb_t) + n1;
  41619. if (len > INT32_MAX) {
  41620. JS_ThrowRangeError(s->ctx, "maximum BigInt size exceeded");
  41621. return -1;
  41622. }
  41623. bc_put_leb128(s, len);
  41624. /* always saved in byte based little endian representation */
  41625. for(j = 0; j < n1; j++) {
  41626. bc_put_u8(s, v >> (j * 8));
  41627. }
  41628. for(; i < a->len; i++) {
  41629. limb_t v = a->tab[i];
  41630. #if LIMB_BITS == 32
  41631. bc_put_u32(s, v);
  41632. #else
  41633. bc_put_u64(s, v);
  41634. #endif
  41635. }
  41636. }
  41637. return 0;
  41638. }
  41639. static int JS_WriteObjectRec(BCWriterState *s, JSValueConst obj);
  41640. static int JS_WriteFunctionTag(BCWriterState *s, JSValueConst obj)
  41641. {
  41642. JSFunctionBytecode *b = JS_VALUE_GET_PTR(obj);
  41643. uint32_t flags;
  41644. int idx, i;
  41645. bc_put_u8(s, BC_TAG_FUNCTION_BYTECODE);
  41646. flags = idx = 0;
  41647. bc_set_flags(&flags, &idx, b->has_prototype, 1);
  41648. bc_set_flags(&flags, &idx, b->has_simple_parameter_list, 1);
  41649. bc_set_flags(&flags, &idx, b->is_derived_class_constructor, 1);
  41650. bc_set_flags(&flags, &idx, b->need_home_object, 1);
  41651. bc_set_flags(&flags, &idx, b->func_kind, 2);
  41652. bc_set_flags(&flags, &idx, b->new_target_allowed, 1);
  41653. bc_set_flags(&flags, &idx, b->super_call_allowed, 1);
  41654. bc_set_flags(&flags, &idx, b->super_allowed, 1);
  41655. bc_set_flags(&flags, &idx, b->arguments_allowed, 1);
  41656. bc_set_flags(&flags, &idx, b->backtrace_barrier, 1);
  41657. bc_set_flags(&flags, &idx, s->allow_debug, 1);
  41658. assert(idx <= 16);
  41659. bc_put_u16(s, flags);
  41660. bc_put_u8(s, b->is_strict_mode);
  41661. bc_put_atom(s, b->func_name);
  41662. bc_put_leb128(s, b->arg_count);
  41663. bc_put_leb128(s, b->var_count);
  41664. bc_put_leb128(s, b->defined_arg_count);
  41665. bc_put_leb128(s, b->stack_size);
  41666. bc_put_leb128(s, b->closure_var_count);
  41667. bc_put_leb128(s, b->cpool_count);
  41668. bc_put_leb128(s, b->byte_code_len);
  41669. if (b->vardefs) {
  41670. /* XXX: this field is redundant */
  41671. bc_put_leb128(s, b->arg_count + b->var_count);
  41672. for(i = 0; i < b->arg_count + b->var_count; i++) {
  41673. JSVarDef *vd = &b->vardefs[i];
  41674. bc_put_atom(s, vd->var_name);
  41675. bc_put_leb128(s, vd->scope_level);
  41676. bc_put_leb128(s, vd->scope_next + 1);
  41677. flags = idx = 0;
  41678. bc_set_flags(&flags, &idx, vd->var_kind, 4);
  41679. bc_set_flags(&flags, &idx, vd->is_const, 1);
  41680. bc_set_flags(&flags, &idx, vd->is_lexical, 1);
  41681. bc_set_flags(&flags, &idx, vd->is_captured, 1);
  41682. assert(idx <= 8);
  41683. bc_put_u8(s, flags);
  41684. }
  41685. } else {
  41686. bc_put_leb128(s, 0);
  41687. }
  41688. for(i = 0; i < b->closure_var_count; i++) {
  41689. JSClosureVar *cv = &b->closure_var[i];
  41690. bc_put_atom(s, cv->var_name);
  41691. bc_put_leb128(s, cv->var_idx);
  41692. flags = idx = 0;
  41693. bc_set_flags(&flags, &idx, cv->is_local, 1);
  41694. bc_set_flags(&flags, &idx, cv->is_arg, 1);
  41695. bc_set_flags(&flags, &idx, cv->is_const, 1);
  41696. bc_set_flags(&flags, &idx, cv->is_lexical, 1);
  41697. bc_set_flags(&flags, &idx, cv->var_kind, 4);
  41698. assert(idx <= 8);
  41699. bc_put_u8(s, flags);
  41700. }
  41701. // write constant pool before code so code can be disassembled
  41702. // on the fly at read time
  41703. for(i = 0; i < b->cpool_count; i++) {
  41704. if (JS_WriteObjectRec(s, b->cpool[i]))
  41705. goto fail;
  41706. }
  41707. if (JS_WriteFunctionBytecode(s, b))
  41708. goto fail;
  41709. if (s->allow_debug) {
  41710. bc_put_atom(s, b->filename);
  41711. bc_put_leb128(s, b->line_num);
  41712. bc_put_leb128(s, b->col_num);
  41713. bc_put_leb128(s, b->pc2line_len);
  41714. dbuf_put(&s->dbuf, b->pc2line_buf, b->pc2line_len);
  41715. if (s->allow_source && b->source) {
  41716. bc_put_leb128(s, b->source_len);
  41717. dbuf_put(&s->dbuf, b->source, b->source_len);
  41718. } else {
  41719. bc_put_leb128(s, 0);
  41720. }
  41721. }
  41722. return 0;
  41723. fail:
  41724. return -1;
  41725. }
  41726. static int JS_WriteModule(BCWriterState *s, JSValueConst obj)
  41727. {
  41728. JSModuleDef *m = JS_VALUE_GET_PTR(obj);
  41729. int i;
  41730. bc_put_u8(s, BC_TAG_MODULE);
  41731. bc_put_atom(s, m->module_name);
  41732. bc_put_leb128(s, m->req_module_entries_count);
  41733. for(i = 0; i < m->req_module_entries_count; i++) {
  41734. JSReqModuleEntry *rme = &m->req_module_entries[i];
  41735. bc_put_atom(s, rme->module_name);
  41736. }
  41737. bc_put_leb128(s, m->export_entries_count);
  41738. for(i = 0; i < m->export_entries_count; i++) {
  41739. JSExportEntry *me = &m->export_entries[i];
  41740. bc_put_u8(s, me->export_type);
  41741. if (me->export_type == JS_EXPORT_TYPE_LOCAL) {
  41742. bc_put_leb128(s, me->u.local.var_idx);
  41743. } else {
  41744. bc_put_leb128(s, me->u.req_module_idx);
  41745. bc_put_atom(s, me->local_name);
  41746. }
  41747. bc_put_atom(s, me->export_name);
  41748. }
  41749. bc_put_leb128(s, m->star_export_entries_count);
  41750. for(i = 0; i < m->star_export_entries_count; i++) {
  41751. JSStarExportEntry *se = &m->star_export_entries[i];
  41752. bc_put_leb128(s, se->req_module_idx);
  41753. }
  41754. bc_put_leb128(s, m->import_entries_count);
  41755. for(i = 0; i < m->import_entries_count; i++) {
  41756. JSImportEntry *mi = &m->import_entries[i];
  41757. bc_put_leb128(s, mi->var_idx);
  41758. bc_put_atom(s, mi->import_name);
  41759. bc_put_leb128(s, mi->req_module_idx);
  41760. }
  41761. bc_put_u8(s, m->has_tla);
  41762. if (JS_WriteObjectRec(s, m->func_obj))
  41763. goto fail;
  41764. return 0;
  41765. fail:
  41766. return -1;
  41767. }
  41768. static int JS_WriteArray(BCWriterState *s, JSValueConst obj)
  41769. {
  41770. JSObject *p = JS_VALUE_GET_OBJ(obj);
  41771. uint32_t i, len;
  41772. JSValue val;
  41773. int ret;
  41774. bool is_template;
  41775. if (s->allow_bytecode && !p->extensible) {
  41776. /* not extensible array: we consider it is a
  41777. template when we are saving bytecode */
  41778. bc_put_u8(s, BC_TAG_TEMPLATE_OBJECT);
  41779. is_template = true;
  41780. } else {
  41781. bc_put_u8(s, BC_TAG_ARRAY);
  41782. is_template = false;
  41783. }
  41784. if (js_get_length32(s->ctx, &len, obj))
  41785. goto fail1;
  41786. bc_put_leb128(s, len);
  41787. for(i = 0; i < len; i++) {
  41788. val = JS_GetPropertyUint32(s->ctx, obj, i);
  41789. if (JS_IsException(val))
  41790. goto fail1;
  41791. ret = JS_WriteObjectRec(s, val);
  41792. JS_FreeValue(s->ctx, val);
  41793. if (ret)
  41794. goto fail1;
  41795. }
  41796. if (is_template) {
  41797. val = JS_GetProperty(s->ctx, obj, JS_ATOM_raw);
  41798. if (JS_IsException(val))
  41799. goto fail1;
  41800. ret = JS_WriteObjectRec(s, val);
  41801. JS_FreeValue(s->ctx, val);
  41802. if (ret)
  41803. goto fail1;
  41804. }
  41805. return 0;
  41806. fail1:
  41807. return -1;
  41808. }
  41809. static int JS_WriteObjectTag(BCWriterState *s, JSValueConst obj)
  41810. {
  41811. JSObject *p = JS_VALUE_GET_OBJ(obj);
  41812. uint32_t i, prop_count;
  41813. JSShape *sh;
  41814. JSShapeProperty *pr;
  41815. int pass;
  41816. JSAtom atom;
  41817. bc_put_u8(s, BC_TAG_OBJECT);
  41818. prop_count = 0;
  41819. sh = p->shape;
  41820. for(pass = 0; pass < 2; pass++) {
  41821. if (pass == 1)
  41822. bc_put_leb128(s, prop_count);
  41823. for(i = 0, pr = get_shape_prop(sh); i < sh->prop_count; i++, pr++) {
  41824. atom = pr->atom;
  41825. if (atom != JS_ATOM_NULL && (pr->flags & JS_PROP_ENUMERABLE)) {
  41826. if (pr->flags & JS_PROP_TMASK) {
  41827. JS_ThrowTypeError(s->ctx, "only value properties are supported");
  41828. goto fail;
  41829. }
  41830. if (pass == 0) {
  41831. prop_count++;
  41832. } else {
  41833. bc_put_atom(s, atom);
  41834. if (JS_WriteObjectRec(s, p->prop[i].u.value))
  41835. goto fail;
  41836. }
  41837. }
  41838. }
  41839. }
  41840. return 0;
  41841. fail:
  41842. return -1;
  41843. }
  41844. static int JS_WriteTypedArray(BCWriterState *s, JSValueConst obj)
  41845. {
  41846. JSObject *p = JS_VALUE_GET_OBJ(obj);
  41847. JSTypedArray *ta = p->u.typed_array;
  41848. bc_put_u8(s, BC_TAG_TYPED_ARRAY);
  41849. bc_put_u8(s, p->class_id - JS_CLASS_UINT8C_ARRAY);
  41850. bc_put_leb128(s, p->u.array.count);
  41851. bc_put_leb128(s, ta->offset);
  41852. if (JS_WriteObjectRec(s, JS_MKPTR(JS_TAG_OBJECT, ta->buffer)))
  41853. return -1;
  41854. return 0;
  41855. }
  41856. static int JS_WriteArrayBuffer(BCWriterState *s, JSValueConst obj)
  41857. {
  41858. JSObject *p = JS_VALUE_GET_OBJ(obj);
  41859. JSArrayBuffer *abuf = p->u.array_buffer;
  41860. if (abuf->detached) {
  41861. JS_ThrowTypeErrorDetachedArrayBuffer(s->ctx);
  41862. return -1;
  41863. }
  41864. bc_put_u8(s, BC_TAG_ARRAY_BUFFER);
  41865. bc_put_leb128(s, abuf->byte_length);
  41866. bc_put_leb128(s, abuf->max_byte_length);
  41867. dbuf_put(&s->dbuf, abuf->data, abuf->byte_length);
  41868. return 0;
  41869. }
  41870. static int JS_WriteSharedArrayBuffer(BCWriterState *s, JSValueConst obj)
  41871. {
  41872. JSObject *p = JS_VALUE_GET_OBJ(obj);
  41873. JSArrayBuffer *abuf = p->u.array_buffer;
  41874. assert(!abuf->detached); /* SharedArrayBuffer are never detached */
  41875. bc_put_u8(s, BC_TAG_SHARED_ARRAY_BUFFER);
  41876. bc_put_leb128(s, abuf->byte_length);
  41877. bc_put_leb128(s, abuf->max_byte_length);
  41878. bc_put_u64(s, (uintptr_t)abuf->data);
  41879. if (js_resize_array(s->ctx, (void **)&s->sab_tab, sizeof(s->sab_tab[0]),
  41880. &s->sab_tab_size, s->sab_tab_len + 1))
  41881. return -1;
  41882. /* keep the SAB pointer so that the user can clone it or free it */
  41883. s->sab_tab[s->sab_tab_len++] = abuf->data;
  41884. return 0;
  41885. }
  41886. static int JS_WriteRegExp(BCWriterState *s, JSRegExp regexp)
  41887. {
  41888. JSString *bc = regexp.bytecode;
  41889. assert(!bc->is_wide_char);
  41890. JS_WriteString(s, regexp.pattern);
  41891. if (is_be())
  41892. lre_byte_swap(str8(bc), bc->len, /*is_byte_swapped*/false);
  41893. JS_WriteString(s, bc);
  41894. if (is_be())
  41895. lre_byte_swap(str8(bc), bc->len, /*is_byte_swapped*/true);
  41896. return 0;
  41897. }
  41898. static int JS_WriteMap(BCWriterState *s, struct JSMapState *map_state);
  41899. static int JS_WriteSet(BCWriterState *s, struct JSMapState *map_state);
  41900. static int JS_WriteObjectRec(BCWriterState *s, JSValueConst obj)
  41901. {
  41902. uint32_t tag;
  41903. if (js_check_stack_overflow(s->ctx->rt, 0)) {
  41904. JS_ThrowStackOverflow(s->ctx);
  41905. return -1;
  41906. }
  41907. tag = JS_VALUE_GET_NORM_TAG(obj);
  41908. switch(tag) {
  41909. case JS_TAG_NULL:
  41910. bc_put_u8(s, BC_TAG_NULL);
  41911. break;
  41912. case JS_TAG_UNDEFINED:
  41913. bc_put_u8(s, BC_TAG_UNDEFINED);
  41914. break;
  41915. case JS_TAG_BOOL:
  41916. bc_put_u8(s, BC_TAG_BOOL_FALSE + JS_VALUE_GET_INT(obj));
  41917. break;
  41918. case JS_TAG_INT:
  41919. bc_put_u8(s, BC_TAG_INT32);
  41920. bc_put_sleb128(s, JS_VALUE_GET_INT(obj));
  41921. break;
  41922. case JS_TAG_FLOAT64:
  41923. {
  41924. JSFloat64Union u;
  41925. bc_put_u8(s, BC_TAG_FLOAT64);
  41926. u.d = JS_VALUE_GET_FLOAT64(obj);
  41927. bc_put_u64(s, u.u64);
  41928. }
  41929. break;
  41930. case JS_TAG_STRING:
  41931. {
  41932. JSString *p = JS_VALUE_GET_STRING(obj);
  41933. bc_put_u8(s, BC_TAG_STRING);
  41934. JS_WriteString(s, p);
  41935. }
  41936. break;
  41937. case JS_TAG_FUNCTION_BYTECODE:
  41938. if (!s->allow_bytecode)
  41939. goto invalid_tag;
  41940. if (JS_WriteFunctionTag(s, obj))
  41941. goto fail;
  41942. break;
  41943. case JS_TAG_MODULE:
  41944. if (!s->allow_bytecode)
  41945. goto invalid_tag;
  41946. if (JS_WriteModule(s, obj))
  41947. goto fail;
  41948. break;
  41949. case JS_TAG_OBJECT:
  41950. {
  41951. JSObject *p = JS_VALUE_GET_OBJ(obj);
  41952. int ret, idx;
  41953. if (s->allow_reference) {
  41954. idx = js_object_list_find(s->ctx, &s->object_list, p);
  41955. if (idx >= 0) {
  41956. bc_put_u8(s, BC_TAG_OBJECT_REFERENCE);
  41957. bc_put_leb128(s, idx);
  41958. break;
  41959. } else {
  41960. if (js_object_list_add(s->ctx, &s->object_list, p))
  41961. goto fail;
  41962. }
  41963. } else {
  41964. if (p->tmp_mark) {
  41965. JS_ThrowTypeError(s->ctx, "circular reference");
  41966. goto fail;
  41967. }
  41968. p->tmp_mark = 1;
  41969. }
  41970. switch(p->class_id) {
  41971. case JS_CLASS_ARRAY:
  41972. ret = JS_WriteArray(s, obj);
  41973. break;
  41974. case JS_CLASS_OBJECT:
  41975. ret = JS_WriteObjectTag(s, obj);
  41976. break;
  41977. case JS_CLASS_ARRAY_BUFFER:
  41978. ret = JS_WriteArrayBuffer(s, obj);
  41979. break;
  41980. case JS_CLASS_SHARED_ARRAY_BUFFER:
  41981. if (!s->allow_sab)
  41982. goto invalid_tag;
  41983. ret = JS_WriteSharedArrayBuffer(s, obj);
  41984. break;
  41985. case JS_CLASS_REGEXP:
  41986. bc_put_u8(s, BC_TAG_REGEXP);
  41987. ret = JS_WriteRegExp(s, p->u.regexp);
  41988. break;
  41989. case JS_CLASS_DATE:
  41990. bc_put_u8(s, BC_TAG_DATE);
  41991. ret = JS_WriteObjectRec(s, p->u.object_data);
  41992. break;
  41993. case JS_CLASS_NUMBER:
  41994. case JS_CLASS_STRING:
  41995. case JS_CLASS_BOOLEAN:
  41996. case JS_CLASS_BIG_INT:
  41997. bc_put_u8(s, BC_TAG_OBJECT_VALUE);
  41998. ret = JS_WriteObjectRec(s, p->u.object_data);
  41999. break;
  42000. case JS_CLASS_MAP:
  42001. bc_put_u8(s, BC_TAG_MAP);
  42002. ret = JS_WriteMap(s, p->u.map_state);
  42003. break;
  42004. case JS_CLASS_SET:
  42005. bc_put_u8(s, BC_TAG_SET);
  42006. ret = JS_WriteSet(s, p->u.map_state);
  42007. break;
  42008. default:
  42009. if (is_typed_array(p->class_id)) {
  42010. ret = JS_WriteTypedArray(s, obj);
  42011. } else {
  42012. JS_ThrowTypeError(s->ctx, "unsupported object class");
  42013. ret = -1;
  42014. }
  42015. break;
  42016. }
  42017. p->tmp_mark = 0;
  42018. if (ret)
  42019. goto fail;
  42020. }
  42021. break;
  42022. case JS_TAG_BIG_INT:
  42023. if (JS_WriteBigInt(s, obj))
  42024. goto fail;
  42025. break;
  42026. case JS_TAG_SYMBOL:
  42027. {
  42028. JSAtomStruct *p = JS_VALUE_GET_PTR(obj);
  42029. if (p->atom_type != JS_ATOM_TYPE_GLOBAL_SYMBOL && p->atom_type != JS_ATOM_TYPE_SYMBOL) {
  42030. JS_ThrowTypeError(s->ctx, "unsupported symbol type");
  42031. goto fail;
  42032. }
  42033. JSAtom atom = js_get_atom_index(s->ctx->rt, p);
  42034. bc_put_u8(s, BC_TAG_SYMBOL);
  42035. bc_put_atom(s, atom);
  42036. }
  42037. break;
  42038. default:
  42039. invalid_tag:
  42040. JS_ThrowInternalError(s->ctx, "unsupported tag (%d)", tag);
  42041. goto fail;
  42042. }
  42043. return 0;
  42044. fail:
  42045. return -1;
  42046. }
  42047. /* create the atom table */
  42048. static int JS_WriteObjectAtoms(BCWriterState *s)
  42049. {
  42050. JSRuntime *rt = s->ctx->rt;
  42051. DynBuf dbuf1;
  42052. int i, atoms_size;
  42053. dbuf1 = s->dbuf;
  42054. js_dbuf_init(s->ctx, &s->dbuf);
  42055. bc_put_u8(s, BC_VERSION);
  42056. bc_put_leb128(s, s->idx_to_atom_count);
  42057. for(i = 0; i < s->idx_to_atom_count; i++) {
  42058. JSAtom atom = s->idx_to_atom[i];
  42059. if (__JS_AtomIsConst(atom)) {
  42060. bc_put_u8(s, 0 /* the type */);
  42061. /* TODO(saghul): encoding for tagged integers and keyword-ish atoms could be
  42062. more efficient. */
  42063. bc_put_u32(s, atom);
  42064. } else {
  42065. JSAtomStruct *p = rt->atom_array[atom];
  42066. uint8_t type = p->atom_type;
  42067. assert(type != JS_ATOM_TYPE_PRIVATE);
  42068. bc_put_u8(s, type);
  42069. JS_WriteString(s, p);
  42070. }
  42071. }
  42072. /* XXX: should check for OOM in above phase */
  42073. /* move the atoms at the start */
  42074. /* XXX: could just append dbuf1 data, but it uses more memory if
  42075. dbuf1 is larger than dbuf */
  42076. atoms_size = s->dbuf.size;
  42077. if (dbuf_realloc(&dbuf1, dbuf1.size + atoms_size))
  42078. goto fail;
  42079. memmove(dbuf1.buf + atoms_size, dbuf1.buf, dbuf1.size);
  42080. memcpy(dbuf1.buf, s->dbuf.buf, atoms_size);
  42081. dbuf1.size += atoms_size;
  42082. dbuf_free(&s->dbuf);
  42083. s->dbuf = dbuf1;
  42084. return 0;
  42085. fail:
  42086. dbuf_free(&dbuf1);
  42087. return -1;
  42088. }
  42089. uint8_t *JS_WriteObject2(JSContext *ctx, size_t *psize, JSValueConst obj,
  42090. int flags, JSSABTab *psab_tab)
  42091. {
  42092. BCWriterState ss, *s = &ss;
  42093. memset(s, 0, sizeof(*s));
  42094. s->ctx = ctx;
  42095. s->allow_bytecode = ((flags & JS_WRITE_OBJ_BYTECODE) != 0);
  42096. s->allow_sab = ((flags & JS_WRITE_OBJ_SAB) != 0);
  42097. s->allow_reference = ((flags & JS_WRITE_OBJ_REFERENCE) != 0);
  42098. s->allow_source = ((flags & JS_WRITE_OBJ_STRIP_SOURCE) == 0);
  42099. s->allow_debug = ((flags & JS_WRITE_OBJ_STRIP_DEBUG) == 0);
  42100. /* XXX: could use a different version when bytecode is included */
  42101. if (s->allow_bytecode)
  42102. s->first_atom = JS_ATOM_END;
  42103. else
  42104. s->first_atom = 1;
  42105. js_dbuf_init(ctx, &s->dbuf);
  42106. js_object_list_init(&s->object_list);
  42107. if (JS_WriteObjectRec(s, obj))
  42108. goto fail;
  42109. if (JS_WriteObjectAtoms(s))
  42110. goto fail;
  42111. js_object_list_end(ctx, &s->object_list);
  42112. js_free(ctx, s->atom_to_idx);
  42113. js_free(ctx, s->idx_to_atom);
  42114. *psize = s->dbuf.size;
  42115. if (psab_tab) {
  42116. psab_tab->tab = s->sab_tab;
  42117. psab_tab->len = s->sab_tab_len;
  42118. } else {
  42119. js_free(ctx, s->sab_tab);
  42120. }
  42121. return s->dbuf.buf;
  42122. fail:
  42123. js_object_list_end(ctx, &s->object_list);
  42124. js_free(ctx, s->atom_to_idx);
  42125. js_free(ctx, s->idx_to_atom);
  42126. dbuf_free(&s->dbuf);
  42127. *psize = 0;
  42128. if (psab_tab) {
  42129. psab_tab->tab = NULL;
  42130. psab_tab->len = 0;
  42131. }
  42132. return NULL;
  42133. }
  42134. uint8_t *JS_WriteObject(JSContext *ctx, size_t *psize, JSValueConst obj,
  42135. int flags)
  42136. {
  42137. return JS_WriteObject2(ctx, psize, obj, flags, NULL);
  42138. }
  42139. typedef struct BCReaderState {
  42140. JSContext *ctx;
  42141. const uint8_t *buf_start, *ptr, *buf_end;
  42142. uint32_t first_atom;
  42143. uint32_t idx_to_atom_count;
  42144. JSAtom *idx_to_atom;
  42145. int error_state;
  42146. bool allow_sab;
  42147. bool allow_bytecode;
  42148. bool allow_reference;
  42149. /* object references */
  42150. JSObject **objects;
  42151. int objects_count;
  42152. int objects_size;
  42153. /* SAB references */
  42154. uint8_t **sab_tab;
  42155. int sab_tab_len;
  42156. int sab_tab_size;
  42157. /* used for JS_DUMP_READ_OBJECT */
  42158. const uint8_t *ptr_last;
  42159. int level;
  42160. } BCReaderState;
  42161. #ifdef ENABLE_DUMPS // JS_DUMP_READ_OBJECT
  42162. static void JS_PRINTF_FORMAT_ATTR(2, 3) bc_read_trace(BCReaderState *s, JS_PRINTF_FORMAT const char *fmt, ...) {
  42163. va_list ap;
  42164. int i, n, n0;
  42165. if (!check_dump_flag(s->ctx->rt, JS_DUMP_READ_OBJECT))
  42166. return;
  42167. if (!s->ptr_last)
  42168. s->ptr_last = s->buf_start;
  42169. n = n0 = 0;
  42170. if (s->ptr > s->ptr_last || s->ptr == s->buf_start) {
  42171. n0 = printf("%04x: ", (int)(s->ptr_last - s->buf_start));
  42172. n += n0;
  42173. }
  42174. for (i = 0; s->ptr_last < s->ptr; i++) {
  42175. if ((i & 7) == 0 && i > 0) {
  42176. printf("\n%*s", n0, "");
  42177. n = n0;
  42178. }
  42179. n += printf(" %02x", *s->ptr_last++);
  42180. }
  42181. if (*fmt == '}')
  42182. s->level--;
  42183. if (n < 32 + s->level * 2) {
  42184. printf("%*s", 32 + s->level * 2 - n, "");
  42185. }
  42186. va_start(ap, fmt);
  42187. vfprintf(stdout, fmt, ap);
  42188. va_end(ap);
  42189. if (strchr(fmt, '{'))
  42190. s->level++;
  42191. }
  42192. #else
  42193. #define bc_read_trace(...)
  42194. #endif
  42195. static int bc_read_error_end(BCReaderState *s)
  42196. {
  42197. if (!s->error_state) {
  42198. JS_ThrowSyntaxError(s->ctx, "read after the end of the buffer");
  42199. }
  42200. return s->error_state = -1;
  42201. }
  42202. static int bc_get_u8(BCReaderState *s, uint8_t *pval)
  42203. {
  42204. if (unlikely(s->buf_end - s->ptr < 1)) {
  42205. *pval = 0; /* avoid warning */
  42206. return bc_read_error_end(s);
  42207. }
  42208. *pval = *s->ptr++;
  42209. return 0;
  42210. }
  42211. static int bc_get_u16(BCReaderState *s, uint16_t *pval)
  42212. {
  42213. uint16_t v;
  42214. if (unlikely(s->buf_end - s->ptr < 2)) {
  42215. *pval = 0; /* avoid warning */
  42216. return bc_read_error_end(s);
  42217. }
  42218. v = get_u16(s->ptr);
  42219. if (is_be())
  42220. v = bswap16(v);
  42221. *pval = v;
  42222. s->ptr += 2;
  42223. return 0;
  42224. }
  42225. static __maybe_unused int bc_get_u32(BCReaderState *s, uint32_t *pval)
  42226. {
  42227. uint32_t v;
  42228. if (unlikely(s->buf_end - s->ptr < 4)) {
  42229. *pval = 0; /* avoid warning */
  42230. return bc_read_error_end(s);
  42231. }
  42232. v = get_u32(s->ptr);
  42233. if (is_be())
  42234. v = bswap32(v);
  42235. *pval = v;
  42236. s->ptr += 4;
  42237. return 0;
  42238. }
  42239. static int bc_get_u64(BCReaderState *s, uint64_t *pval)
  42240. {
  42241. uint64_t v;
  42242. if (unlikely(s->buf_end - s->ptr < 8)) {
  42243. *pval = 0; /* avoid warning */
  42244. return bc_read_error_end(s);
  42245. }
  42246. v = get_u64(s->ptr);
  42247. if (is_be())
  42248. v = bswap64(v);
  42249. *pval = v;
  42250. s->ptr += 8;
  42251. return 0;
  42252. }
  42253. static int bc_get_leb128(BCReaderState *s, uint32_t *pval)
  42254. {
  42255. int ret;
  42256. ret = get_leb128(pval, s->ptr, s->buf_end);
  42257. if (unlikely(ret < 0))
  42258. return bc_read_error_end(s);
  42259. s->ptr += ret;
  42260. return 0;
  42261. }
  42262. static int bc_get_sleb128(BCReaderState *s, int32_t *pval)
  42263. {
  42264. int ret;
  42265. ret = get_sleb128(pval, s->ptr, s->buf_end);
  42266. if (unlikely(ret < 0))
  42267. return bc_read_error_end(s);
  42268. s->ptr += ret;
  42269. return 0;
  42270. }
  42271. /* XXX: used to read an `int` with a positive value */
  42272. static int bc_get_leb128_int(BCReaderState *s, int *pval)
  42273. {
  42274. return bc_get_leb128(s, (uint32_t *)pval);
  42275. }
  42276. static int bc_get_leb128_u16(BCReaderState *s, uint16_t *pval)
  42277. {
  42278. uint32_t val;
  42279. if (bc_get_leb128(s, &val)) {
  42280. *pval = 0;
  42281. return -1;
  42282. }
  42283. *pval = val;
  42284. return 0;
  42285. }
  42286. static int bc_get_buf(BCReaderState *s, void *buf, uint32_t buf_len)
  42287. {
  42288. if (buf_len != 0) {
  42289. if (unlikely(!buf || s->buf_end - s->ptr < buf_len))
  42290. return bc_read_error_end(s);
  42291. memcpy(buf, s->ptr, buf_len);
  42292. s->ptr += buf_len;
  42293. }
  42294. return 0;
  42295. }
  42296. static int bc_idx_to_atom(BCReaderState *s, JSAtom *patom, uint32_t idx)
  42297. {
  42298. JSAtom atom;
  42299. if (__JS_AtomIsTaggedInt(idx)) {
  42300. atom = idx;
  42301. } else if (idx < s->first_atom) {
  42302. atom = JS_DupAtom(s->ctx, idx);
  42303. } else {
  42304. idx -= s->first_atom;
  42305. if (idx >= s->idx_to_atom_count) {
  42306. JS_ThrowSyntaxError(s->ctx, "invalid atom index (pos=%u)",
  42307. (unsigned int)(s->ptr - s->buf_start));
  42308. *patom = JS_ATOM_NULL;
  42309. return s->error_state = -1;
  42310. }
  42311. atom = JS_DupAtom(s->ctx, s->idx_to_atom[idx]);
  42312. }
  42313. *patom = atom;
  42314. return 0;
  42315. }
  42316. static int bc_get_atom(BCReaderState *s, JSAtom *patom)
  42317. {
  42318. uint32_t v;
  42319. if (bc_get_leb128(s, &v))
  42320. return -1;
  42321. if (v & 1) {
  42322. *patom = __JS_AtomFromUInt32(v >> 1);
  42323. return 0;
  42324. } else {
  42325. return bc_idx_to_atom(s, patom, v >> 1);
  42326. }
  42327. }
  42328. static JSString *JS_ReadString(BCReaderState *s)
  42329. {
  42330. uint32_t len;
  42331. size_t size;
  42332. bool is_wide_char;
  42333. JSString *p;
  42334. if (bc_get_leb128(s, &len))
  42335. return NULL;
  42336. is_wide_char = len & 1;
  42337. len >>= 1;
  42338. p = js_alloc_string(s->ctx, len, is_wide_char);
  42339. if (!p) {
  42340. s->error_state = -1;
  42341. return NULL;
  42342. }
  42343. size = (size_t)len << is_wide_char;
  42344. if ((s->buf_end - s->ptr) < size) {
  42345. bc_read_error_end(s);
  42346. js_free_string(s->ctx->rt, p);
  42347. return NULL;
  42348. }
  42349. memcpy(str8(p), s->ptr, size);
  42350. s->ptr += size;
  42351. if (is_wide_char) {
  42352. if (is_be()) {
  42353. uint32_t i;
  42354. for (i = 0; i < len; i++)
  42355. str16(p)[i] = bswap16(str16(p)[i]);
  42356. }
  42357. } else {
  42358. str8(p)[size] = '\0'; /* add the trailing zero for 8 bit strings */
  42359. }
  42360. #ifdef ENABLE_DUMPS // JS_DUMP_READ_OBJECT
  42361. if (check_dump_flag(s->ctx->rt, JS_DUMP_READ_OBJECT)) {
  42362. bc_read_trace(s, "%s", ""); // hex dump and indentation
  42363. JS_DumpString(s->ctx->rt, p);
  42364. printf("\n");
  42365. }
  42366. #endif
  42367. return p;
  42368. }
  42369. static uint32_t bc_get_flags(uint32_t flags, int *pidx, int n)
  42370. {
  42371. uint32_t val;
  42372. /* XXX: this does not work for n == 32 */
  42373. val = (flags >> *pidx) & ((1U << n) - 1);
  42374. *pidx += n;
  42375. return val;
  42376. }
  42377. static int JS_ReadFunctionBytecode(BCReaderState *s, JSFunctionBytecode *b,
  42378. int byte_code_offset, uint32_t bc_len)
  42379. {
  42380. uint8_t *bc_buf;
  42381. int pos, len, op;
  42382. JSAtom atom;
  42383. uint32_t idx;
  42384. bc_buf = (uint8_t*)b + byte_code_offset;
  42385. if (bc_get_buf(s, bc_buf, bc_len))
  42386. return -1;
  42387. b->byte_code_buf = bc_buf;
  42388. if (is_be())
  42389. bc_byte_swap(bc_buf, bc_len);
  42390. pos = 0;
  42391. while (pos < bc_len) {
  42392. op = bc_buf[pos];
  42393. len = short_opcode_info(op).size;
  42394. switch(short_opcode_info(op).fmt) {
  42395. case OP_FMT_atom:
  42396. case OP_FMT_atom_u8:
  42397. case OP_FMT_atom_u16:
  42398. case OP_FMT_atom_label_u8:
  42399. case OP_FMT_atom_label_u16:
  42400. idx = get_u32(bc_buf + pos + 1);
  42401. if (bc_idx_to_atom(s, &atom, idx)) {
  42402. /* Note: the atoms will be freed up to this position */
  42403. b->byte_code_len = pos;
  42404. return -1;
  42405. }
  42406. put_u32(bc_buf + pos + 1, atom);
  42407. break;
  42408. default:
  42409. break;
  42410. }
  42411. #ifdef ENABLE_DUMPS // JS_DUMP_READ_OBJECT
  42412. if (check_dump_flag(s->ctx->rt, JS_DUMP_READ_OBJECT)) {
  42413. const uint8_t *save_ptr = s->ptr;
  42414. s->ptr = s->ptr_last + len;
  42415. s->level -= 4;
  42416. bc_read_trace(s, "%s", ""); // hex dump + indent
  42417. dump_single_byte_code(s->ctx, bc_buf + pos, b,
  42418. s->ptr - s->buf_start - len);
  42419. s->level += 4;
  42420. s->ptr = save_ptr;
  42421. }
  42422. #endif
  42423. pos += len;
  42424. }
  42425. return 0;
  42426. }
  42427. static JSValue JS_ReadBigInt(BCReaderState *s)
  42428. {
  42429. JSValue obj;
  42430. uint8_t v8;
  42431. int32_t e;
  42432. uint32_t len;
  42433. limb_t l, i, n;
  42434. limb_t v;
  42435. bf_t *a;
  42436. obj = JS_NewBigInt(s->ctx);
  42437. if (JS_IsException(obj))
  42438. goto fail;
  42439. /* sign + exponent */
  42440. if (bc_get_sleb128(s, &e))
  42441. goto fail;
  42442. a = JS_GetBigInt(obj);
  42443. a->sign = e & 1;
  42444. e >>= 1;
  42445. if (e == 0)
  42446. a->expn = BF_EXP_ZERO;
  42447. else if (e == 1)
  42448. a->expn = BF_EXP_INF;
  42449. else if (e == 2)
  42450. a->expn = BF_EXP_NAN;
  42451. else if (e >= 3)
  42452. a->expn = e - 3;
  42453. else
  42454. a->expn = e;
  42455. /* mantissa */
  42456. if (a->expn != BF_EXP_ZERO &&
  42457. a->expn != BF_EXP_INF &&
  42458. a->expn != BF_EXP_NAN) {
  42459. if (bc_get_leb128(s, &len))
  42460. goto fail;
  42461. bc_read_trace(s, "len=%" PRId64 "\n", (int64_t)len);
  42462. if (len == 0) {
  42463. JS_ThrowRangeError(s->ctx, "maximum BigInt size exceeded");
  42464. goto fail;
  42465. }
  42466. l = (len + sizeof(limb_t) - 1) / sizeof(limb_t);
  42467. if (bf_resize(a, l)) {
  42468. JS_ThrowOutOfMemory(s->ctx);
  42469. goto fail;
  42470. }
  42471. n = len & (sizeof(limb_t) - 1);
  42472. if (n != 0) {
  42473. v = 0;
  42474. for(i = 0; i < n; i++) {
  42475. if (bc_get_u8(s, &v8))
  42476. goto fail;
  42477. v |= (limb_t)v8 << ((sizeof(limb_t) - n + i) * 8);
  42478. }
  42479. a->tab[0] = v;
  42480. i = 1;
  42481. } else {
  42482. i = 0;
  42483. }
  42484. for(; i < l; i++) {
  42485. #if LIMB_BITS == 32
  42486. if (bc_get_u32(s, &v))
  42487. goto fail;
  42488. #else
  42489. if (bc_get_u64(s, &v))
  42490. goto fail;
  42491. #endif
  42492. a->tab[i] = v;
  42493. }
  42494. }
  42495. return obj;
  42496. fail:
  42497. JS_FreeValue(s->ctx, obj);
  42498. return JS_EXCEPTION;
  42499. }
  42500. static JSValue JS_ReadObjectRec(BCReaderState *s);
  42501. static int BC_add_object_ref1(BCReaderState *s, JSObject *p)
  42502. {
  42503. if (s->allow_reference) {
  42504. if (js_resize_array(s->ctx, (void *)&s->objects,
  42505. sizeof(s->objects[0]),
  42506. &s->objects_size, s->objects_count + 1))
  42507. return -1;
  42508. s->objects[s->objects_count++] = p;
  42509. }
  42510. return 0;
  42511. }
  42512. static int BC_add_object_ref(BCReaderState *s, JSValue obj)
  42513. {
  42514. return BC_add_object_ref1(s, JS_VALUE_GET_OBJ(obj));
  42515. }
  42516. static JSValue JS_ReadFunctionTag(BCReaderState *s)
  42517. {
  42518. JSContext *ctx = s->ctx;
  42519. JSFunctionBytecode bc, *b;
  42520. JSValue obj = JS_UNDEFINED;
  42521. uint16_t v16;
  42522. uint8_t v8;
  42523. int idx, i, local_count, has_debug_info;
  42524. int function_size, cpool_offset, byte_code_offset;
  42525. int closure_var_offset, vardefs_offset;
  42526. memset(&bc, 0, sizeof(bc));
  42527. bc.header.ref_count = 1;
  42528. //bc.gc_header.mark = 0;
  42529. if (bc_get_u16(s, &v16))
  42530. goto fail;
  42531. idx = 0;
  42532. bc.has_prototype = bc_get_flags(v16, &idx, 1);
  42533. bc.has_simple_parameter_list = bc_get_flags(v16, &idx, 1);
  42534. bc.is_derived_class_constructor = bc_get_flags(v16, &idx, 1);
  42535. bc.need_home_object = bc_get_flags(v16, &idx, 1);
  42536. bc.func_kind = bc_get_flags(v16, &idx, 2);
  42537. bc.new_target_allowed = bc_get_flags(v16, &idx, 1);
  42538. bc.super_call_allowed = bc_get_flags(v16, &idx, 1);
  42539. bc.super_allowed = bc_get_flags(v16, &idx, 1);
  42540. bc.arguments_allowed = bc_get_flags(v16, &idx, 1);
  42541. bc.backtrace_barrier = bc_get_flags(v16, &idx, 1);
  42542. has_debug_info = bc_get_flags(v16, &idx, 1);
  42543. if (bc_get_u8(s, &v8))
  42544. goto fail;
  42545. bc.is_strict_mode = (v8 > 0);
  42546. if (bc_get_atom(s, &bc.func_name))
  42547. goto fail;
  42548. if (bc_get_leb128_u16(s, &bc.arg_count))
  42549. goto fail;
  42550. if (bc_get_leb128_u16(s, &bc.var_count))
  42551. goto fail;
  42552. if (bc_get_leb128_u16(s, &bc.defined_arg_count))
  42553. goto fail;
  42554. if (bc_get_leb128_u16(s, &bc.stack_size))
  42555. goto fail;
  42556. if (bc_get_leb128_int(s, &bc.closure_var_count))
  42557. goto fail;
  42558. if (bc_get_leb128_int(s, &bc.cpool_count))
  42559. goto fail;
  42560. if (bc_get_leb128_int(s, &bc.byte_code_len))
  42561. goto fail;
  42562. if (bc_get_leb128_int(s, &local_count))
  42563. goto fail;
  42564. function_size = sizeof(*b);
  42565. cpool_offset = function_size;
  42566. function_size += bc.cpool_count * sizeof(*bc.cpool);
  42567. vardefs_offset = function_size;
  42568. function_size += local_count * sizeof(*bc.vardefs);
  42569. closure_var_offset = function_size;
  42570. function_size += bc.closure_var_count * sizeof(*bc.closure_var);
  42571. byte_code_offset = function_size;
  42572. function_size += bc.byte_code_len;
  42573. b = js_mallocz(ctx, function_size);
  42574. if (!b)
  42575. goto fail;
  42576. memcpy(b, &bc, sizeof(*b));
  42577. bc.func_name = JS_ATOM_NULL;
  42578. b->header.ref_count = 1;
  42579. if (local_count != 0) {
  42580. b->vardefs = (void *)((uint8_t*)b + vardefs_offset);
  42581. }
  42582. if (b->closure_var_count != 0) {
  42583. b->closure_var = (void *)((uint8_t*)b + closure_var_offset);
  42584. }
  42585. if (b->cpool_count != 0) {
  42586. b->cpool = (void *)((uint8_t*)b + cpool_offset);
  42587. }
  42588. add_gc_object(ctx->rt, &b->header, JS_GC_OBJ_TYPE_FUNCTION_BYTECODE);
  42589. obj = JS_MKPTR(JS_TAG_FUNCTION_BYTECODE, b);
  42590. #ifdef ENABLE_DUMPS // JS_DUMP_READ_OBJECT
  42591. if (check_dump_flag(s->ctx->rt, JS_DUMP_READ_OBJECT)) {
  42592. if (b->func_name) {
  42593. bc_read_trace(s, "name: ");
  42594. print_atom(s->ctx, b->func_name);
  42595. printf("\n");
  42596. }
  42597. }
  42598. #endif
  42599. bc_read_trace(s, "args=%d vars=%d defargs=%d closures=%d cpool=%d\n",
  42600. b->arg_count, b->var_count, b->defined_arg_count,
  42601. b->closure_var_count, b->cpool_count);
  42602. bc_read_trace(s, "stack=%d bclen=%d locals=%d\n",
  42603. b->stack_size, b->byte_code_len, local_count);
  42604. if (local_count != 0) {
  42605. bc_read_trace(s, "vars {\n");
  42606. bc_read_trace(s, "off flags scope name\n");
  42607. for(i = 0; i < local_count; i++) {
  42608. JSVarDef *vd = &b->vardefs[i];
  42609. if (bc_get_atom(s, &vd->var_name))
  42610. goto fail;
  42611. if (bc_get_leb128_int(s, &vd->scope_level))
  42612. goto fail;
  42613. if (bc_get_leb128_int(s, &vd->scope_next))
  42614. goto fail;
  42615. vd->scope_next--;
  42616. if (bc_get_u8(s, &v8))
  42617. goto fail;
  42618. idx = 0;
  42619. vd->var_kind = bc_get_flags(v8, &idx, 4);
  42620. vd->is_const = bc_get_flags(v8, &idx, 1);
  42621. vd->is_lexical = bc_get_flags(v8, &idx, 1);
  42622. vd->is_captured = bc_get_flags(v8, &idx, 1);
  42623. #ifdef ENABLE_DUMPS // JS_DUMP_READ_OBJECT
  42624. if (check_dump_flag(s->ctx->rt, JS_DUMP_READ_OBJECT)) {
  42625. bc_read_trace(s, "%3d %d%c%c%c %4d ",
  42626. i, vd->var_kind,
  42627. vd->is_const ? 'C' : '.',
  42628. vd->is_lexical ? 'L' : '.',
  42629. vd->is_captured ? 'X' : '.',
  42630. vd->scope_level);
  42631. print_atom(s->ctx, vd->var_name);
  42632. printf("\n");
  42633. }
  42634. #endif
  42635. }
  42636. bc_read_trace(s, "}\n");
  42637. }
  42638. if (b->closure_var_count != 0) {
  42639. bc_read_trace(s, "closure vars {\n");
  42640. bc_read_trace(s, "off flags idx name\n");
  42641. for(i = 0; i < b->closure_var_count; i++) {
  42642. JSClosureVar *cv = &b->closure_var[i];
  42643. int var_idx;
  42644. if (bc_get_atom(s, &cv->var_name))
  42645. goto fail;
  42646. if (bc_get_leb128_int(s, &var_idx))
  42647. goto fail;
  42648. cv->var_idx = var_idx;
  42649. if (bc_get_u8(s, &v8))
  42650. goto fail;
  42651. idx = 0;
  42652. cv->is_local = bc_get_flags(v8, &idx, 1);
  42653. cv->is_arg = bc_get_flags(v8, &idx, 1);
  42654. cv->is_const = bc_get_flags(v8, &idx, 1);
  42655. cv->is_lexical = bc_get_flags(v8, &idx, 1);
  42656. cv->var_kind = bc_get_flags(v8, &idx, 4);
  42657. #ifdef ENABLE_DUMPS // JS_DUMP_READ_OBJECT
  42658. if (check_dump_flag(s->ctx->rt, JS_DUMP_READ_OBJECT)) {
  42659. bc_read_trace(s, "%3d %d%c%c%c%c %3d ",
  42660. i, cv->var_kind,
  42661. cv->is_local ? 'L' : '.',
  42662. cv->is_arg ? 'A' : '.',
  42663. cv->is_const ? 'C' : '.',
  42664. cv->is_lexical ? 'X' : '.',
  42665. cv->var_idx);
  42666. print_atom(s->ctx, cv->var_name);
  42667. printf("\n");
  42668. }
  42669. #endif
  42670. }
  42671. bc_read_trace(s, "}\n");
  42672. }
  42673. if (b->cpool_count != 0) {
  42674. bc_read_trace(s, "cpool {\n");
  42675. for(i = 0; i < b->cpool_count; i++) {
  42676. JSValue val;
  42677. val = JS_ReadObjectRec(s);
  42678. if (JS_IsException(val))
  42679. goto fail;
  42680. b->cpool[i] = val;
  42681. }
  42682. bc_read_trace(s, "}\n");
  42683. }
  42684. {
  42685. bc_read_trace(s, "bytecode {\n");
  42686. if (JS_ReadFunctionBytecode(s, b, byte_code_offset, b->byte_code_len))
  42687. goto fail;
  42688. bc_read_trace(s, "}\n");
  42689. }
  42690. if (!has_debug_info)
  42691. goto nodebug;
  42692. /* read optional debug information */
  42693. bc_read_trace(s, "debug {\n");
  42694. if (bc_get_atom(s, &b->filename))
  42695. goto fail;
  42696. if (bc_get_leb128_int(s, &b->line_num))
  42697. goto fail;
  42698. if (bc_get_leb128_int(s, &b->col_num))
  42699. goto fail;
  42700. #ifdef ENABLE_DUMPS // JS_DUMP_READ_OBJECT
  42701. if (check_dump_flag(s->ctx->rt, JS_DUMP_READ_OBJECT)) {
  42702. bc_read_trace(s, "filename: ");
  42703. print_atom(s->ctx, b->filename);
  42704. printf(", line: %d, column: %d\n", b->line_num, b->col_num);
  42705. }
  42706. #endif
  42707. if (bc_get_leb128_int(s, &b->pc2line_len))
  42708. goto fail;
  42709. if (b->pc2line_len) {
  42710. bc_read_trace(s, "positions: %d bytes\n", b->pc2line_len);
  42711. b->pc2line_buf = js_mallocz(ctx, b->pc2line_len);
  42712. if (!b->pc2line_buf)
  42713. goto fail;
  42714. if (bc_get_buf(s, b->pc2line_buf, b->pc2line_len))
  42715. goto fail;
  42716. }
  42717. if (bc_get_leb128_int(s, &b->source_len))
  42718. goto fail;
  42719. if (b->source_len) {
  42720. bc_read_trace(s, "source: %d bytes\n", b->source_len);
  42721. if (s->ptr_last)
  42722. s->ptr_last += b->source_len; // omit source code hex dump
  42723. /* b->source is a UTF-8 encoded null terminated C string */
  42724. b->source = js_mallocz(ctx, b->source_len + 1);
  42725. if (!b->source)
  42726. goto fail;
  42727. if (bc_get_buf(s, b->source, b->source_len))
  42728. goto fail;
  42729. }
  42730. bc_read_trace(s, "}\n");
  42731. nodebug:
  42732. b->realm = JS_DupContext(ctx);
  42733. return obj;
  42734. fail:
  42735. JS_FreeAtom(ctx, bc.func_name);
  42736. JS_FreeValue(ctx, obj);
  42737. return JS_EXCEPTION;
  42738. }
  42739. static JSValue JS_ReadModule(BCReaderState *s)
  42740. {
  42741. JSContext *ctx = s->ctx;
  42742. JSValue obj;
  42743. JSModuleDef *m = NULL;
  42744. JSAtom module_name;
  42745. int i;
  42746. uint8_t v8;
  42747. if (bc_get_atom(s, &module_name))
  42748. goto fail;
  42749. #ifdef ENABLE_DUMPS // JS_DUMP_READ_OBJECT
  42750. if (check_dump_flag(s->ctx->rt, JS_DUMP_READ_OBJECT)) {
  42751. bc_read_trace(s, "name: ");
  42752. print_atom(s->ctx, module_name);
  42753. printf("\n");
  42754. }
  42755. #endif
  42756. m = js_new_module_def(ctx, module_name);
  42757. if (!m)
  42758. goto fail;
  42759. obj = js_dup(JS_MKPTR(JS_TAG_MODULE, m));
  42760. if (bc_get_leb128_int(s, &m->req_module_entries_count))
  42761. goto fail;
  42762. obj = JS_NewModuleValue(ctx, m);
  42763. if (m->req_module_entries_count != 0) {
  42764. m->req_module_entries_size = m->req_module_entries_count;
  42765. m->req_module_entries = js_mallocz(ctx, sizeof(m->req_module_entries[0]) * m->req_module_entries_size);
  42766. if (!m->req_module_entries)
  42767. goto fail;
  42768. for(i = 0; i < m->req_module_entries_count; i++) {
  42769. JSReqModuleEntry *rme = &m->req_module_entries[i];
  42770. JSModuleDef **pm = &rme->module;
  42771. if (bc_get_atom(s, &rme->module_name))
  42772. goto fail;
  42773. // Resolves a module either from the cache or by requesting
  42774. // it from the module loader. From cache is not ideal because
  42775. // the module may not be the one it was a time of serialization
  42776. // but directly petitioning the module loader is not correct
  42777. // either because then the same module can get loaded twice.
  42778. // JS_WriteModule() does not serialize modules transitively
  42779. // because that doesn't work for C modules and is also prone
  42780. // to loading the same JS module twice.
  42781. *pm = js_host_resolve_imported_module_atom(s->ctx, m->module_name,
  42782. rme->module_name);
  42783. if (!*pm)
  42784. goto fail;
  42785. }
  42786. }
  42787. if (bc_get_leb128_int(s, &m->export_entries_count))
  42788. goto fail;
  42789. if (m->export_entries_count != 0) {
  42790. m->export_entries_size = m->export_entries_count;
  42791. m->export_entries = js_mallocz(ctx, sizeof(m->export_entries[0]) * m->export_entries_size);
  42792. if (!m->export_entries)
  42793. goto fail;
  42794. for(i = 0; i < m->export_entries_count; i++) {
  42795. JSExportEntry *me = &m->export_entries[i];
  42796. if (bc_get_u8(s, &v8))
  42797. goto fail;
  42798. me->export_type = v8;
  42799. if (me->export_type == JS_EXPORT_TYPE_LOCAL) {
  42800. if (bc_get_leb128_int(s, &me->u.local.var_idx))
  42801. goto fail;
  42802. } else {
  42803. if (bc_get_leb128_int(s, &me->u.req_module_idx))
  42804. goto fail;
  42805. if (bc_get_atom(s, &me->local_name))
  42806. goto fail;
  42807. }
  42808. if (bc_get_atom(s, &me->export_name))
  42809. goto fail;
  42810. }
  42811. }
  42812. if (bc_get_leb128_int(s, &m->star_export_entries_count))
  42813. goto fail;
  42814. if (m->star_export_entries_count != 0) {
  42815. m->star_export_entries_size = m->star_export_entries_count;
  42816. m->star_export_entries = js_mallocz(ctx, sizeof(m->star_export_entries[0]) * m->star_export_entries_size);
  42817. if (!m->star_export_entries)
  42818. goto fail;
  42819. for(i = 0; i < m->star_export_entries_count; i++) {
  42820. JSStarExportEntry *se = &m->star_export_entries[i];
  42821. if (bc_get_leb128_int(s, &se->req_module_idx))
  42822. goto fail;
  42823. }
  42824. }
  42825. if (bc_get_leb128_int(s, &m->import_entries_count))
  42826. goto fail;
  42827. if (m->import_entries_count != 0) {
  42828. m->import_entries_size = m->import_entries_count;
  42829. m->import_entries = js_mallocz(ctx, sizeof(m->import_entries[0]) * m->import_entries_size);
  42830. if (!m->import_entries)
  42831. goto fail;
  42832. for(i = 0; i < m->import_entries_count; i++) {
  42833. JSImportEntry *mi = &m->import_entries[i];
  42834. if (bc_get_leb128_int(s, &mi->var_idx))
  42835. goto fail;
  42836. if (bc_get_atom(s, &mi->import_name))
  42837. goto fail;
  42838. if (bc_get_leb128_int(s, &mi->req_module_idx))
  42839. goto fail;
  42840. }
  42841. }
  42842. if (bc_get_u8(s, &v8))
  42843. goto fail;
  42844. m->has_tla = (v8 != 0);
  42845. m->func_obj = JS_ReadObjectRec(s);
  42846. if (JS_IsException(m->func_obj))
  42847. goto fail;
  42848. return obj;
  42849. fail:
  42850. if (m) {
  42851. js_free_module_def(ctx, m);
  42852. }
  42853. return JS_EXCEPTION;
  42854. }
  42855. static JSValue JS_ReadObjectTag(BCReaderState *s)
  42856. {
  42857. JSContext *ctx = s->ctx;
  42858. JSValue obj;
  42859. uint32_t prop_count, i;
  42860. JSAtom atom;
  42861. JSValue val;
  42862. int ret;
  42863. obj = JS_NewObject(ctx);
  42864. if (BC_add_object_ref(s, obj))
  42865. goto fail;
  42866. if (bc_get_leb128(s, &prop_count))
  42867. goto fail;
  42868. for(i = 0; i < prop_count; i++) {
  42869. if (bc_get_atom(s, &atom))
  42870. goto fail;
  42871. #ifdef ENABLE_DUMPS // JS_DUMP_READ_OBJECT
  42872. if (check_dump_flag(s->ctx->rt, JS_DUMP_READ_OBJECT)) {
  42873. bc_read_trace(s, "propname: ");
  42874. print_atom(s->ctx, atom);
  42875. printf("\n");
  42876. }
  42877. #endif
  42878. val = JS_ReadObjectRec(s);
  42879. if (JS_IsException(val)) {
  42880. JS_FreeAtom(ctx, atom);
  42881. goto fail;
  42882. }
  42883. ret = JS_DefinePropertyValue(ctx, obj, atom, val, JS_PROP_C_W_E);
  42884. JS_FreeAtom(ctx, atom);
  42885. if (ret < 0)
  42886. goto fail;
  42887. }
  42888. return obj;
  42889. fail:
  42890. JS_FreeValue(ctx, obj);
  42891. return JS_EXCEPTION;
  42892. }
  42893. static JSValue JS_ReadArray(BCReaderState *s, int tag)
  42894. {
  42895. JSContext *ctx = s->ctx;
  42896. JSValue obj;
  42897. uint32_t len, i;
  42898. JSValue val;
  42899. int ret, prop_flags;
  42900. bool is_template;
  42901. obj = JS_NewArray(ctx);
  42902. if (BC_add_object_ref(s, obj))
  42903. goto fail;
  42904. is_template = (tag == BC_TAG_TEMPLATE_OBJECT);
  42905. if (bc_get_leb128(s, &len))
  42906. goto fail;
  42907. for(i = 0; i < len; i++) {
  42908. val = JS_ReadObjectRec(s);
  42909. if (JS_IsException(val))
  42910. goto fail;
  42911. if (is_template)
  42912. prop_flags = JS_PROP_ENUMERABLE;
  42913. else
  42914. prop_flags = JS_PROP_C_W_E;
  42915. ret = JS_DefinePropertyValueUint32(ctx, obj, i, val,
  42916. prop_flags);
  42917. if (ret < 0)
  42918. goto fail;
  42919. }
  42920. if (is_template) {
  42921. val = JS_ReadObjectRec(s);
  42922. if (JS_IsException(val))
  42923. goto fail;
  42924. if (!JS_IsUndefined(val)) {
  42925. ret = JS_DefinePropertyValue(ctx, obj, JS_ATOM_raw, val, 0);
  42926. if (ret < 0)
  42927. goto fail;
  42928. }
  42929. JS_PreventExtensions(ctx, obj);
  42930. }
  42931. return obj;
  42932. fail:
  42933. JS_FreeValue(ctx, obj);
  42934. return JS_EXCEPTION;
  42935. }
  42936. static JSValue JS_ReadTypedArray(BCReaderState *s)
  42937. {
  42938. JSContext *ctx = s->ctx;
  42939. JSValue obj = JS_UNDEFINED, array_buffer = JS_UNDEFINED;
  42940. uint8_t array_tag;
  42941. JSValueConst args[3];
  42942. uint32_t offset, len, idx;
  42943. if (bc_get_u8(s, &array_tag))
  42944. return JS_EXCEPTION;
  42945. if (array_tag >= JS_TYPED_ARRAY_COUNT)
  42946. return JS_ThrowTypeError(ctx, "invalid typed array");
  42947. if (bc_get_leb128(s, &len))
  42948. return JS_EXCEPTION;
  42949. if (bc_get_leb128(s, &offset))
  42950. return JS_EXCEPTION;
  42951. /* XXX: this hack could be avoided if the typed array could be
  42952. created before the array buffer */
  42953. idx = s->objects_count;
  42954. if (BC_add_object_ref1(s, NULL))
  42955. goto fail;
  42956. array_buffer = JS_ReadObjectRec(s);
  42957. if (JS_IsException(array_buffer))
  42958. return JS_EXCEPTION;
  42959. if (!js_get_array_buffer(ctx, array_buffer)) {
  42960. JS_FreeValue(ctx, array_buffer);
  42961. return JS_EXCEPTION;
  42962. }
  42963. args[0] = array_buffer;
  42964. args[1] = js_int64(offset);
  42965. args[2] = js_int64(len);
  42966. obj = js_typed_array_constructor(ctx, JS_UNDEFINED,
  42967. 3, args,
  42968. JS_CLASS_UINT8C_ARRAY + array_tag);
  42969. if (JS_IsException(obj))
  42970. goto fail;
  42971. if (s->allow_reference) {
  42972. s->objects[idx] = JS_VALUE_GET_OBJ(obj);
  42973. }
  42974. JS_FreeValue(ctx, array_buffer);
  42975. return obj;
  42976. fail:
  42977. JS_FreeValue(ctx, array_buffer);
  42978. JS_FreeValue(ctx, obj);
  42979. return JS_EXCEPTION;
  42980. }
  42981. static JSValue JS_ReadArrayBuffer(BCReaderState *s)
  42982. {
  42983. JSContext *ctx = s->ctx;
  42984. uint32_t byte_length, max_byte_length;
  42985. uint64_t max_byte_length_u64, *pmax_byte_length = NULL;
  42986. JSValue obj;
  42987. if (bc_get_leb128(s, &byte_length))
  42988. return JS_EXCEPTION;
  42989. if (bc_get_leb128(s, &max_byte_length))
  42990. return JS_EXCEPTION;
  42991. if (max_byte_length < byte_length)
  42992. return JS_ThrowTypeError(ctx, "invalid array buffer");
  42993. if (max_byte_length != UINT32_MAX) {
  42994. max_byte_length_u64 = max_byte_length;
  42995. pmax_byte_length = &max_byte_length_u64;
  42996. }
  42997. if (unlikely(s->buf_end - s->ptr < byte_length)) {
  42998. bc_read_error_end(s);
  42999. return JS_EXCEPTION;
  43000. }
  43001. // makes a copy of the input
  43002. obj = js_array_buffer_constructor3(ctx, JS_UNDEFINED,
  43003. byte_length, pmax_byte_length,
  43004. JS_CLASS_ARRAY_BUFFER,
  43005. (uint8_t*)s->ptr,
  43006. js_array_buffer_free, NULL,
  43007. /*alloc_flag*/true);
  43008. if (JS_IsException(obj))
  43009. goto fail;
  43010. if (BC_add_object_ref(s, obj))
  43011. goto fail;
  43012. s->ptr += byte_length;
  43013. return obj;
  43014. fail:
  43015. JS_FreeValue(ctx, obj);
  43016. return JS_EXCEPTION;
  43017. }
  43018. static JSValue JS_ReadSharedArrayBuffer(BCReaderState *s)
  43019. {
  43020. JSContext *ctx = s->ctx;
  43021. uint32_t byte_length, max_byte_length;
  43022. uint64_t max_byte_length_u64, *pmax_byte_length = NULL;
  43023. uint8_t *data_ptr;
  43024. JSValue obj;
  43025. uint64_t u64;
  43026. if (bc_get_leb128(s, &byte_length))
  43027. return JS_EXCEPTION;
  43028. if (bc_get_leb128(s, &max_byte_length))
  43029. return JS_EXCEPTION;
  43030. if (max_byte_length < byte_length)
  43031. return JS_ThrowTypeError(ctx, "invalid array buffer");
  43032. if (max_byte_length != UINT32_MAX) {
  43033. max_byte_length_u64 = max_byte_length;
  43034. pmax_byte_length = &max_byte_length_u64;
  43035. }
  43036. if (bc_get_u64(s, &u64))
  43037. return JS_EXCEPTION;
  43038. data_ptr = (uint8_t *)(uintptr_t)u64;
  43039. if (js_resize_array(s->ctx, (void **)&s->sab_tab, sizeof(s->sab_tab[0]),
  43040. &s->sab_tab_size, s->sab_tab_len + 1))
  43041. return JS_EXCEPTION;
  43042. /* keep the SAB pointer so that the user can clone it or free it */
  43043. s->sab_tab[s->sab_tab_len++] = data_ptr;
  43044. /* the SharedArrayBuffer is cloned */
  43045. obj = js_array_buffer_constructor3(ctx, JS_UNDEFINED,
  43046. byte_length, pmax_byte_length,
  43047. JS_CLASS_SHARED_ARRAY_BUFFER,
  43048. data_ptr,
  43049. NULL, NULL, false);
  43050. if (JS_IsException(obj))
  43051. goto fail;
  43052. if (BC_add_object_ref(s, obj))
  43053. goto fail;
  43054. return obj;
  43055. fail:
  43056. JS_FreeValue(ctx, obj);
  43057. return JS_EXCEPTION;
  43058. }
  43059. static JSValue JS_ReadRegExp(BCReaderState *s)
  43060. {
  43061. JSContext *ctx = s->ctx;
  43062. JSString *pattern;
  43063. JSString *bc;
  43064. pattern = JS_ReadString(s);
  43065. if (!pattern)
  43066. return JS_EXCEPTION;
  43067. bc = JS_ReadString(s);
  43068. if (!bc) {
  43069. js_free_string(ctx->rt, pattern);
  43070. return JS_EXCEPTION;
  43071. }
  43072. if (bc->is_wide_char) {
  43073. js_free_string(ctx->rt, pattern);
  43074. js_free_string(ctx->rt, bc);
  43075. return JS_ThrowInternalError(ctx, "bad regexp bytecode");
  43076. }
  43077. if (is_be())
  43078. lre_byte_swap(str8(bc), bc->len, /*is_byte_swapped*/true);
  43079. return js_regexp_constructor_internal(ctx, JS_UNDEFINED,
  43080. JS_MKPTR(JS_TAG_STRING, pattern),
  43081. JS_MKPTR(JS_TAG_STRING, bc));
  43082. }
  43083. static JSValue JS_ReadDate(BCReaderState *s)
  43084. {
  43085. JSContext *ctx = s->ctx;
  43086. JSValue val, obj = JS_UNDEFINED;
  43087. val = JS_ReadObjectRec(s);
  43088. if (JS_IsException(val))
  43089. goto fail;
  43090. if (!JS_IsNumber(val)) {
  43091. JS_ThrowTypeError(ctx, "Number tag expected for date");
  43092. goto fail;
  43093. }
  43094. obj = JS_NewObjectProtoClass(ctx, ctx->class_proto[JS_CLASS_DATE],
  43095. JS_CLASS_DATE);
  43096. if (JS_IsException(obj))
  43097. goto fail;
  43098. if (BC_add_object_ref(s, obj))
  43099. goto fail;
  43100. JS_SetObjectData(ctx, obj, val);
  43101. return obj;
  43102. fail:
  43103. JS_FreeValue(ctx, val);
  43104. JS_FreeValue(ctx, obj);
  43105. return JS_EXCEPTION;
  43106. }
  43107. static JSValue JS_ReadObjectValue(BCReaderState *s)
  43108. {
  43109. JSContext *ctx = s->ctx;
  43110. JSValue val, obj = JS_UNDEFINED;
  43111. val = JS_ReadObjectRec(s);
  43112. if (JS_IsException(val))
  43113. goto fail;
  43114. obj = JS_ToObject(ctx, val);
  43115. if (JS_IsException(obj))
  43116. goto fail;
  43117. if (BC_add_object_ref(s, obj))
  43118. goto fail;
  43119. JS_FreeValue(ctx, val);
  43120. return obj;
  43121. fail:
  43122. JS_FreeValue(ctx, val);
  43123. JS_FreeValue(ctx, obj);
  43124. return JS_EXCEPTION;
  43125. }
  43126. static JSValue JS_ReadMap(BCReaderState *s);
  43127. static JSValue JS_ReadSet(BCReaderState *s);
  43128. static JSValue JS_ReadObjectRec(BCReaderState *s)
  43129. {
  43130. JSContext *ctx = s->ctx;
  43131. uint8_t tag;
  43132. JSValue obj = JS_UNDEFINED;
  43133. if (js_check_stack_overflow(ctx->rt, 0))
  43134. return JS_ThrowStackOverflow(ctx);
  43135. if (bc_get_u8(s, &tag))
  43136. return JS_EXCEPTION;
  43137. bc_read_trace(s, "%s {\n", bc_tag_str[tag]);
  43138. switch(tag) {
  43139. case BC_TAG_NULL:
  43140. obj = JS_NULL;
  43141. break;
  43142. case BC_TAG_UNDEFINED:
  43143. obj = JS_UNDEFINED;
  43144. break;
  43145. case BC_TAG_BOOL_FALSE:
  43146. case BC_TAG_BOOL_TRUE:
  43147. obj = js_bool(tag - BC_TAG_BOOL_FALSE);
  43148. break;
  43149. case BC_TAG_INT32:
  43150. {
  43151. int32_t val;
  43152. if (bc_get_sleb128(s, &val))
  43153. return JS_EXCEPTION;
  43154. bc_read_trace(s, "%d\n", val);
  43155. obj = js_int32(val);
  43156. }
  43157. break;
  43158. case BC_TAG_FLOAT64:
  43159. {
  43160. JSFloat64Union u;
  43161. if (bc_get_u64(s, &u.u64))
  43162. return JS_EXCEPTION;
  43163. bc_read_trace(s, "%g\n", u.d);
  43164. obj = js_float64(u.d);
  43165. }
  43166. break;
  43167. case BC_TAG_STRING:
  43168. {
  43169. JSString *p;
  43170. p = JS_ReadString(s);
  43171. if (!p)
  43172. return JS_EXCEPTION;
  43173. obj = JS_MKPTR(JS_TAG_STRING, p);
  43174. }
  43175. break;
  43176. case BC_TAG_FUNCTION_BYTECODE:
  43177. if (!s->allow_bytecode)
  43178. goto no_allow_bytecode;
  43179. obj = JS_ReadFunctionTag(s);
  43180. break;
  43181. case BC_TAG_MODULE:
  43182. if (!s->allow_bytecode) {
  43183. no_allow_bytecode:
  43184. return JS_ThrowSyntaxError(ctx, "no bytecode allowed");
  43185. }
  43186. obj = JS_ReadModule(s);
  43187. break;
  43188. case BC_TAG_OBJECT:
  43189. obj = JS_ReadObjectTag(s);
  43190. break;
  43191. case BC_TAG_ARRAY:
  43192. case BC_TAG_TEMPLATE_OBJECT:
  43193. obj = JS_ReadArray(s, tag);
  43194. break;
  43195. case BC_TAG_TYPED_ARRAY:
  43196. obj = JS_ReadTypedArray(s);
  43197. break;
  43198. case BC_TAG_ARRAY_BUFFER:
  43199. obj = JS_ReadArrayBuffer(s);
  43200. break;
  43201. case BC_TAG_SHARED_ARRAY_BUFFER:
  43202. if (!s->allow_sab || !ctx->rt->sab_funcs.sab_dup)
  43203. goto invalid_tag;
  43204. obj = JS_ReadSharedArrayBuffer(s);
  43205. break;
  43206. case BC_TAG_REGEXP:
  43207. obj = JS_ReadRegExp(s);
  43208. break;
  43209. case BC_TAG_DATE:
  43210. obj = JS_ReadDate(s);
  43211. break;
  43212. case BC_TAG_OBJECT_VALUE:
  43213. obj = JS_ReadObjectValue(s);
  43214. break;
  43215. case BC_TAG_BIG_INT:
  43216. obj = JS_ReadBigInt(s);
  43217. break;
  43218. case BC_TAG_OBJECT_REFERENCE:
  43219. {
  43220. uint32_t val;
  43221. if (!s->allow_reference)
  43222. return JS_ThrowSyntaxError(ctx, "object references are not allowed");
  43223. if (bc_get_leb128(s, &val))
  43224. return JS_EXCEPTION;
  43225. bc_read_trace(s, "%u\n", val);
  43226. if (val >= s->objects_count) {
  43227. return JS_ThrowSyntaxError(ctx, "invalid object reference (%u >= %u)",
  43228. val, s->objects_count);
  43229. }
  43230. obj = js_dup(JS_MKPTR(JS_TAG_OBJECT, s->objects[val]));
  43231. }
  43232. break;
  43233. case BC_TAG_MAP:
  43234. obj = JS_ReadMap(s);
  43235. break;
  43236. case BC_TAG_SET:
  43237. obj = JS_ReadSet(s);
  43238. break;
  43239. case BC_TAG_SYMBOL:
  43240. {
  43241. JSAtom atom;
  43242. if (bc_get_atom(s, &atom))
  43243. return JS_EXCEPTION;
  43244. if (__JS_AtomIsConst(atom)) {
  43245. obj = JS_AtomToValue(s->ctx, atom);
  43246. } else {
  43247. JSAtomStruct *p = s->ctx->rt->atom_array[atom];
  43248. obj = JS_NewSymbolFromAtom(s->ctx, atom, p->atom_type);
  43249. }
  43250. }
  43251. break;
  43252. default:
  43253. invalid_tag:
  43254. return JS_ThrowSyntaxError(ctx, "invalid tag (tag=%d pos=%u)",
  43255. tag, (unsigned int)(s->ptr - s->buf_start));
  43256. }
  43257. bc_read_trace(s, "}\n");
  43258. return obj;
  43259. }
  43260. static int JS_ReadObjectAtoms(BCReaderState *s)
  43261. {
  43262. uint8_t v8, type;
  43263. JSString *p;
  43264. int i;
  43265. JSAtom atom;
  43266. if (bc_get_u8(s, &v8))
  43267. return -1;
  43268. if (v8 != BC_VERSION) {
  43269. JS_ThrowSyntaxError(s->ctx, "invalid version (%d expected=%d)",
  43270. v8, BC_VERSION);
  43271. return -1;
  43272. }
  43273. if (bc_get_leb128(s, &s->idx_to_atom_count))
  43274. return -1;
  43275. if (s->idx_to_atom_count > 1000*1000) {
  43276. JS_ThrowInternalError(s->ctx, "unreasonable atom count: %u",
  43277. s->idx_to_atom_count);
  43278. return -1;
  43279. }
  43280. bc_read_trace(s, "%u atom indexes {\n", s->idx_to_atom_count);
  43281. if (s->idx_to_atom_count != 0) {
  43282. s->idx_to_atom = js_mallocz(s->ctx, s->idx_to_atom_count *
  43283. sizeof(s->idx_to_atom[0]));
  43284. if (!s->idx_to_atom)
  43285. return s->error_state = -1;
  43286. }
  43287. for(i = 0; i < s->idx_to_atom_count; i++) {
  43288. if (bc_get_u8(s, &type)) {
  43289. return -1;
  43290. }
  43291. if (type == 0) {
  43292. if (bc_get_u32(s, &atom))
  43293. return -1;
  43294. if (!__JS_AtomIsConst(atom)) {
  43295. JS_ThrowInternalError(s->ctx, "out of range atom");
  43296. return -1;
  43297. }
  43298. } else {
  43299. if (type < JS_ATOM_TYPE_STRING || type >= JS_ATOM_TYPE_PRIVATE) {
  43300. JS_ThrowInternalError(s->ctx, "invalid symbol type %d", type);
  43301. return -1;
  43302. }
  43303. p = JS_ReadString(s);
  43304. if (!p)
  43305. return -1;
  43306. atom = __JS_NewAtom(s->ctx->rt, p, type);
  43307. }
  43308. if (atom == JS_ATOM_NULL)
  43309. return s->error_state = -1;
  43310. s->idx_to_atom[i] = atom;
  43311. }
  43312. bc_read_trace(s, "}\n");
  43313. return 0;
  43314. }
  43315. static void bc_reader_free(BCReaderState *s)
  43316. {
  43317. int i;
  43318. if (s->idx_to_atom) {
  43319. for(i = 0; i < s->idx_to_atom_count; i++) {
  43320. JS_FreeAtom(s->ctx, s->idx_to_atom[i]);
  43321. }
  43322. js_free(s->ctx, s->idx_to_atom);
  43323. }
  43324. js_free(s->ctx, s->objects);
  43325. }
  43326. JSValue JS_ReadObject2(JSContext *ctx, const uint8_t *buf, size_t buf_len,
  43327. int flags, JSSABTab *psab_tab)
  43328. {
  43329. BCReaderState ss, *s = &ss;
  43330. JSValue obj;
  43331. ctx->binary_object_count += 1;
  43332. ctx->binary_object_size += buf_len;
  43333. memset(s, 0, sizeof(*s));
  43334. s->ctx = ctx;
  43335. s->buf_start = buf;
  43336. s->buf_end = buf + buf_len;
  43337. s->ptr = buf;
  43338. s->allow_bytecode = ((flags & JS_READ_OBJ_BYTECODE) != 0);
  43339. s->allow_sab = ((flags & JS_READ_OBJ_SAB) != 0);
  43340. s->allow_reference = ((flags & JS_READ_OBJ_REFERENCE) != 0);
  43341. if (s->allow_bytecode)
  43342. s->first_atom = JS_ATOM_END;
  43343. else
  43344. s->first_atom = 1;
  43345. if (JS_ReadObjectAtoms(s)) {
  43346. obj = JS_EXCEPTION;
  43347. } else {
  43348. obj = JS_ReadObjectRec(s);
  43349. }
  43350. if (psab_tab) {
  43351. psab_tab->tab = s->sab_tab;
  43352. psab_tab->len = s->sab_tab_len;
  43353. } else {
  43354. js_free(ctx, s->sab_tab);
  43355. }
  43356. bc_reader_free(s);
  43357. return obj;
  43358. }
  43359. JSValue JS_ReadObject(JSContext *ctx, const uint8_t *buf, size_t buf_len,
  43360. int flags)
  43361. {
  43362. return JS_ReadObject2(ctx, buf, buf_len, flags, NULL);
  43363. }
  43364. /*******************************************************************/
  43365. /* runtime functions & objects */
  43366. static JSValue js_string_constructor(JSContext *ctx, JSValueConst this_val,
  43367. int argc, JSValueConst *argv);
  43368. static JSValue js_boolean_constructor(JSContext *ctx, JSValueConst this_val,
  43369. int argc, JSValueConst *argv);
  43370. static JSValue js_number_constructor(JSContext *ctx, JSValueConst this_val,
  43371. int argc, JSValueConst *argv);
  43372. static int check_function(JSContext *ctx, JSValueConst obj)
  43373. {
  43374. if (likely(JS_IsFunction(ctx, obj)))
  43375. return 0;
  43376. JS_ThrowTypeErrorNotAFunction(ctx);
  43377. return -1;
  43378. }
  43379. static int check_exception_free(JSContext *ctx, JSValue obj)
  43380. {
  43381. JS_FreeValue(ctx, obj);
  43382. return JS_IsException(obj);
  43383. }
  43384. /* `export_name` may be pure ASCII or UTF-8 encoded */
  43385. static JSAtom find_atom(JSContext *ctx, const char *name)
  43386. {
  43387. JSAtom atom;
  43388. int len;
  43389. if (*name == '[') {
  43390. name++;
  43391. len = strlen(name) - 1;
  43392. /* We assume 8 bit non null strings, which is the case for these
  43393. symbols */
  43394. for(atom = JS_ATOM_Symbol_toPrimitive; atom < JS_ATOM_END; atom++) {
  43395. JSAtomStruct *p = ctx->rt->atom_array[atom];
  43396. JSString *str = p;
  43397. if (str->len == len && !memcmp(str8(str), name, len))
  43398. return JS_DupAtom(ctx, atom);
  43399. }
  43400. abort();
  43401. } else {
  43402. atom = JS_NewAtom(ctx, name);
  43403. }
  43404. return atom;
  43405. }
  43406. static JSValue JS_InstantiateFunctionListItem2(JSContext *ctx, JSObject *p,
  43407. JSAtom atom, void *opaque)
  43408. {
  43409. const JSCFunctionListEntry *e = opaque;
  43410. JSValue val;
  43411. switch(e->def_type) {
  43412. case JS_DEF_CFUNC:
  43413. val = JS_NewCFunction2(ctx, e->u.func.cfunc.generic,
  43414. e->name, e->u.func.length, e->u.func.cproto, e->magic);
  43415. break;
  43416. case JS_DEF_PROP_STRING:
  43417. val = JS_NewAtomString(ctx, e->u.str);
  43418. break;
  43419. case JS_DEF_OBJECT:
  43420. val = JS_NewObject(ctx);
  43421. JS_SetPropertyFunctionList(ctx, val, e->u.prop_list.tab, e->u.prop_list.len);
  43422. break;
  43423. default:
  43424. abort();
  43425. }
  43426. return val;
  43427. }
  43428. static int JS_InstantiateFunctionListItem(JSContext *ctx, JSValue obj,
  43429. JSAtom atom,
  43430. const JSCFunctionListEntry *e)
  43431. {
  43432. JSValue val;
  43433. int prop_flags = e->prop_flags;
  43434. switch(e->def_type) {
  43435. case JS_DEF_ALIAS: /* using autoinit for aliases is not safe */
  43436. {
  43437. JSAtom atom1 = find_atom(ctx, e->u.alias.name);
  43438. switch (e->u.alias.base) {
  43439. case -1:
  43440. val = JS_GetProperty(ctx, obj, atom1);
  43441. break;
  43442. case 0:
  43443. val = JS_GetProperty(ctx, ctx->global_obj, atom1);
  43444. break;
  43445. case 1:
  43446. val = JS_GetProperty(ctx, ctx->class_proto[JS_CLASS_ARRAY], atom1);
  43447. break;
  43448. default:
  43449. abort();
  43450. }
  43451. JS_FreeAtom(ctx, atom1);
  43452. if (atom == JS_ATOM_Symbol_toPrimitive) {
  43453. /* Symbol.toPrimitive functions are not writable */
  43454. prop_flags = JS_PROP_CONFIGURABLE;
  43455. } else if (atom == JS_ATOM_Symbol_hasInstance) {
  43456. /* Function.prototype[Symbol.hasInstance] is not writable nor configurable */
  43457. prop_flags = 0;
  43458. }
  43459. }
  43460. break;
  43461. case JS_DEF_CFUNC:
  43462. if (atom == JS_ATOM_Symbol_toPrimitive) {
  43463. /* Symbol.toPrimitive functions are not writable */
  43464. prop_flags = JS_PROP_CONFIGURABLE;
  43465. } else if (atom == JS_ATOM_Symbol_hasInstance) {
  43466. /* Function.prototype[Symbol.hasInstance] is not writable nor configurable */
  43467. prop_flags = 0;
  43468. }
  43469. JS_DefineAutoInitProperty(ctx, obj, atom, JS_AUTOINIT_ID_PROP,
  43470. (void *)e, prop_flags);
  43471. return 0;
  43472. case JS_DEF_CGETSET: /* XXX: use autoinit again ? */
  43473. case JS_DEF_CGETSET_MAGIC:
  43474. {
  43475. JSValue getter, setter;
  43476. char buf[64];
  43477. getter = JS_UNDEFINED;
  43478. if (e->u.getset.get.generic) {
  43479. snprintf(buf, sizeof(buf), "get %s", e->name);
  43480. getter = JS_NewCFunction2(ctx, e->u.getset.get.generic,
  43481. buf, 0, e->def_type == JS_DEF_CGETSET_MAGIC ? JS_CFUNC_getter_magic : JS_CFUNC_getter,
  43482. e->magic);
  43483. }
  43484. setter = JS_UNDEFINED;
  43485. if (e->u.getset.set.generic) {
  43486. snprintf(buf, sizeof(buf), "set %s", e->name);
  43487. setter = JS_NewCFunction2(ctx, e->u.getset.set.generic,
  43488. buf, 1, e->def_type == JS_DEF_CGETSET_MAGIC ? JS_CFUNC_setter_magic : JS_CFUNC_setter,
  43489. e->magic);
  43490. }
  43491. JS_DefinePropertyGetSet(ctx, obj, atom, getter, setter, prop_flags);
  43492. return 0;
  43493. }
  43494. break;
  43495. case JS_DEF_PROP_INT32:
  43496. val = js_int32(e->u.i32);
  43497. break;
  43498. case JS_DEF_PROP_INT64:
  43499. val = js_int64(e->u.i64);
  43500. break;
  43501. case JS_DEF_PROP_DOUBLE:
  43502. val = js_float64(e->u.f64);
  43503. break;
  43504. case JS_DEF_PROP_UNDEFINED:
  43505. val = JS_UNDEFINED;
  43506. break;
  43507. case JS_DEF_PROP_STRING:
  43508. case JS_DEF_OBJECT:
  43509. JS_DefineAutoInitProperty(ctx, obj, atom, JS_AUTOINIT_ID_PROP,
  43510. (void *)e, prop_flags);
  43511. return 0;
  43512. default:
  43513. abort();
  43514. }
  43515. JS_DefinePropertyValue(ctx, obj, atom, val, prop_flags);
  43516. return 0;
  43517. }
  43518. void JS_SetPropertyFunctionList(JSContext *ctx, JSValue obj,
  43519. const JSCFunctionListEntry *tab, int len)
  43520. {
  43521. int i;
  43522. for (i = 0; i < len; i++) {
  43523. const JSCFunctionListEntry *e = &tab[i];
  43524. JSAtom atom = find_atom(ctx, e->name);
  43525. JS_InstantiateFunctionListItem(ctx, obj, atom, e);
  43526. JS_FreeAtom(ctx, atom);
  43527. }
  43528. }
  43529. int JS_AddModuleExportList(JSContext *ctx, JSModuleDef *m,
  43530. const JSCFunctionListEntry *tab, int len)
  43531. {
  43532. int i;
  43533. for(i = 0; i < len; i++) {
  43534. if (JS_AddModuleExport(ctx, m, tab[i].name))
  43535. return -1;
  43536. }
  43537. return 0;
  43538. }
  43539. int JS_SetModuleExportList(JSContext *ctx, JSModuleDef *m,
  43540. const JSCFunctionListEntry *tab, int len)
  43541. {
  43542. int i;
  43543. JSValue val;
  43544. for(i = 0; i < len; i++) {
  43545. const JSCFunctionListEntry *e = &tab[i];
  43546. switch(e->def_type) {
  43547. case JS_DEF_CFUNC:
  43548. val = JS_NewCFunction2(ctx, e->u.func.cfunc.generic,
  43549. e->name, e->u.func.length, e->u.func.cproto, e->magic);
  43550. break;
  43551. case JS_DEF_PROP_STRING:
  43552. /* `e->u.str` may be pure ASCII or UTF-8 encoded */
  43553. val = JS_NewString(ctx, e->u.str);
  43554. break;
  43555. case JS_DEF_PROP_INT32:
  43556. val = js_int32(e->u.i32);
  43557. break;
  43558. case JS_DEF_PROP_INT64:
  43559. val = js_int64(e->u.i64);
  43560. break;
  43561. case JS_DEF_PROP_DOUBLE:
  43562. val = js_float64(e->u.f64);
  43563. break;
  43564. case JS_DEF_OBJECT:
  43565. val = JS_NewObject(ctx);
  43566. JS_SetPropertyFunctionList(ctx, val, e->u.prop_list.tab, e->u.prop_list.len);
  43567. break;
  43568. default:
  43569. abort();
  43570. }
  43571. if (JS_SetModuleExport(ctx, m, e->name, val))
  43572. return -1;
  43573. }
  43574. return 0;
  43575. }
  43576. /* Note: 'func_obj' is not necessarily a constructor */
  43577. static void JS_SetConstructor2(JSContext *ctx,
  43578. JSValueConst func_obj,
  43579. JSValueConst proto,
  43580. int proto_flags, int ctor_flags)
  43581. {
  43582. JS_DefinePropertyValue(ctx, func_obj, JS_ATOM_prototype,
  43583. js_dup(proto), proto_flags);
  43584. JS_DefinePropertyValue(ctx, proto, JS_ATOM_constructor,
  43585. js_dup(func_obj), ctor_flags);
  43586. set_cycle_flag(ctx, func_obj);
  43587. set_cycle_flag(ctx, proto);
  43588. }
  43589. void JS_SetConstructor(JSContext *ctx, JSValueConst func_obj,
  43590. JSValueConst proto)
  43591. {
  43592. JS_SetConstructor2(ctx, func_obj, proto,
  43593. 0, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);
  43594. }
  43595. static void JS_NewGlobalCConstructor2(JSContext *ctx,
  43596. JSValue func_obj,
  43597. const char *name,
  43598. JSValueConst proto)
  43599. {
  43600. JS_DefinePropertyValueStr(ctx, ctx->global_obj, name,
  43601. js_dup(func_obj),
  43602. JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);
  43603. JS_SetConstructor(ctx, func_obj, proto);
  43604. JS_FreeValue(ctx, func_obj);
  43605. }
  43606. static JSValue JS_NewGlobalCConstructor(JSContext *ctx, const char *name,
  43607. JSCFunction *func, int length,
  43608. JSValueConst proto)
  43609. {
  43610. JSValue func_obj;
  43611. func_obj = JS_NewCFunction2(ctx, func, name, length, JS_CFUNC_constructor_or_func, 0);
  43612. JS_NewGlobalCConstructor2(ctx, func_obj, name, proto);
  43613. return func_obj;
  43614. }
  43615. static JSValue JS_NewGlobalCConstructorOnly(JSContext *ctx, const char *name,
  43616. JSCFunction *func, int length,
  43617. JSValue proto)
  43618. {
  43619. JSValue func_obj;
  43620. func_obj = JS_NewCFunction2(ctx, func, name, length, JS_CFUNC_constructor, 0);
  43621. JS_NewGlobalCConstructor2(ctx, func_obj, name, proto);
  43622. return func_obj;
  43623. }
  43624. static JSValue js_global_eval(JSContext *ctx, JSValueConst this_val,
  43625. int argc, JSValueConst *argv)
  43626. {
  43627. return JS_EvalObject(ctx, ctx->global_obj, argv[0], JS_EVAL_TYPE_INDIRECT, -1);
  43628. }
  43629. static JSValue js_global_isNaN(JSContext *ctx, JSValueConst this_val,
  43630. int argc, JSValueConst *argv)
  43631. {
  43632. double d;
  43633. if (unlikely(JS_ToFloat64(ctx, &d, argv[0])))
  43634. return JS_EXCEPTION;
  43635. return js_bool(isnan(d));
  43636. }
  43637. static JSValue js_global_isFinite(JSContext *ctx, JSValueConst this_val,
  43638. int argc, JSValueConst *argv)
  43639. {
  43640. bool res;
  43641. double d;
  43642. if (unlikely(JS_ToFloat64(ctx, &d, argv[0])))
  43643. return JS_EXCEPTION;
  43644. res = isfinite(d);
  43645. return js_bool(res);
  43646. }
  43647. static JSValue js_microtask_job(JSContext *ctx,
  43648. int argc, JSValueConst *argv)
  43649. {
  43650. return JS_Call(ctx, argv[0], ctx->global_obj, 0, NULL);
  43651. }
  43652. static JSValue js_global_queueMicrotask(JSContext *ctx, JSValueConst this_val,
  43653. int argc, JSValueConst *argv)
  43654. {
  43655. if (check_function(ctx, argv[0]))
  43656. return JS_EXCEPTION;
  43657. if (JS_EnqueueJob(ctx, js_microtask_job, 1, &argv[0]))
  43658. return JS_EXCEPTION;
  43659. return JS_UNDEFINED;
  43660. }
  43661. /* Object class */
  43662. JSValue JS_ToObject(JSContext *ctx, JSValueConst val)
  43663. {
  43664. int tag = JS_VALUE_GET_NORM_TAG(val);
  43665. JSValue obj;
  43666. switch(tag) {
  43667. default:
  43668. case JS_TAG_NULL:
  43669. case JS_TAG_UNDEFINED:
  43670. return JS_ThrowTypeError(ctx, "Cannot convert undefined or null to object");
  43671. case JS_TAG_OBJECT:
  43672. case JS_TAG_EXCEPTION:
  43673. return js_dup(val);
  43674. case JS_TAG_BIG_INT:
  43675. obj = JS_NewObjectClass(ctx, JS_CLASS_BIG_INT);
  43676. goto set_value;
  43677. case JS_TAG_INT:
  43678. case JS_TAG_FLOAT64:
  43679. obj = JS_NewObjectClass(ctx, JS_CLASS_NUMBER);
  43680. goto set_value;
  43681. case JS_TAG_STRING:
  43682. /* XXX: should call the string constructor */
  43683. {
  43684. JSString *p1 = JS_VALUE_GET_STRING(val);
  43685. obj = JS_NewObjectClass(ctx, JS_CLASS_STRING);
  43686. JS_DefinePropertyValue(ctx, obj, JS_ATOM_length, js_int32(p1->len), 0);
  43687. }
  43688. goto set_value;
  43689. case JS_TAG_BOOL:
  43690. obj = JS_NewObjectClass(ctx, JS_CLASS_BOOLEAN);
  43691. goto set_value;
  43692. case JS_TAG_SYMBOL:
  43693. obj = JS_NewObjectClass(ctx, JS_CLASS_SYMBOL);
  43694. set_value:
  43695. if (!JS_IsException(obj))
  43696. JS_SetObjectData(ctx, obj, js_dup(val));
  43697. return obj;
  43698. }
  43699. }
  43700. static JSValue JS_ToObjectFree(JSContext *ctx, JSValue val)
  43701. {
  43702. JSValue obj = JS_ToObject(ctx, val);
  43703. JS_FreeValue(ctx, val);
  43704. return obj;
  43705. }
  43706. static int js_obj_to_desc(JSContext *ctx, JSPropertyDescriptor *d,
  43707. JSValueConst desc)
  43708. {
  43709. JSValue val, getter, setter;
  43710. int present;
  43711. int flags;
  43712. if (!JS_IsObject(desc)) {
  43713. JS_ThrowTypeError(ctx, "Property description must be an object");
  43714. return -1;
  43715. }
  43716. flags = 0;
  43717. val = JS_UNDEFINED;
  43718. getter = JS_UNDEFINED;
  43719. setter = JS_UNDEFINED;
  43720. present = JS_HasProperty(ctx, desc, JS_ATOM_enumerable);
  43721. if (present < 0)
  43722. goto fail;
  43723. if (present) {
  43724. JSValue prop = JS_GetProperty(ctx, desc, JS_ATOM_enumerable);
  43725. if (JS_IsException(prop))
  43726. goto fail;
  43727. flags |= JS_PROP_HAS_ENUMERABLE;
  43728. if (JS_ToBoolFree(ctx, prop))
  43729. flags |= JS_PROP_ENUMERABLE;
  43730. }
  43731. present = JS_HasProperty(ctx, desc, JS_ATOM_configurable);
  43732. if (present < 0)
  43733. goto fail;
  43734. if (present) {
  43735. JSValue prop = JS_GetProperty(ctx, desc, JS_ATOM_configurable);
  43736. if (JS_IsException(prop))
  43737. goto fail;
  43738. flags |= JS_PROP_HAS_CONFIGURABLE;
  43739. if (JS_ToBoolFree(ctx, prop))
  43740. flags |= JS_PROP_CONFIGURABLE;
  43741. }
  43742. present = JS_HasProperty(ctx, desc, JS_ATOM_value);
  43743. if (present < 0)
  43744. goto fail;
  43745. if (present) {
  43746. flags |= JS_PROP_HAS_VALUE;
  43747. val = JS_GetProperty(ctx, desc, JS_ATOM_value);
  43748. if (JS_IsException(val))
  43749. goto fail;
  43750. }
  43751. present = JS_HasProperty(ctx, desc, JS_ATOM_writable);
  43752. if (present < 0)
  43753. goto fail;
  43754. if (present) {
  43755. JSValue prop = JS_GetProperty(ctx, desc, JS_ATOM_writable);
  43756. if (JS_IsException(prop))
  43757. goto fail;
  43758. flags |= JS_PROP_HAS_WRITABLE;
  43759. if (JS_ToBoolFree(ctx, prop))
  43760. flags |= JS_PROP_WRITABLE;
  43761. }
  43762. present = JS_HasProperty(ctx, desc, JS_ATOM_get);
  43763. if (present < 0)
  43764. goto fail;
  43765. if (present) {
  43766. flags |= JS_PROP_HAS_GET;
  43767. getter = JS_GetProperty(ctx, desc, JS_ATOM_get);
  43768. if (JS_IsException(getter) ||
  43769. !(JS_IsUndefined(getter) || JS_IsFunction(ctx, getter))) {
  43770. JS_ThrowTypeError(ctx, "Getter must be a function");
  43771. goto fail;
  43772. }
  43773. }
  43774. present = JS_HasProperty(ctx, desc, JS_ATOM_set);
  43775. if (present < 0)
  43776. goto fail;
  43777. if (present) {
  43778. flags |= JS_PROP_HAS_SET;
  43779. setter = JS_GetProperty(ctx, desc, JS_ATOM_set);
  43780. if (JS_IsException(setter) ||
  43781. !(JS_IsUndefined(setter) || JS_IsFunction(ctx, setter))) {
  43782. JS_ThrowTypeError(ctx, "Setter must be a function");
  43783. goto fail;
  43784. }
  43785. }
  43786. if ((flags & (JS_PROP_HAS_SET | JS_PROP_HAS_GET)) &&
  43787. (flags & (JS_PROP_HAS_VALUE | JS_PROP_HAS_WRITABLE))) {
  43788. JS_ThrowTypeError(ctx, "Invalid property descriptor. Cannot both specify accessors and a value or writable attribute");
  43789. goto fail;
  43790. }
  43791. d->flags = flags;
  43792. d->value = val;
  43793. d->getter = getter;
  43794. d->setter = setter;
  43795. return 0;
  43796. fail:
  43797. JS_FreeValue(ctx, val);
  43798. JS_FreeValue(ctx, getter);
  43799. JS_FreeValue(ctx, setter);
  43800. return -1;
  43801. }
  43802. static __exception int JS_DefinePropertyDesc(JSContext *ctx, JSValueConst obj,
  43803. JSAtom prop, JSValueConst desc,
  43804. int flags)
  43805. {
  43806. JSPropertyDescriptor d;
  43807. int ret;
  43808. if (js_obj_to_desc(ctx, &d, desc) < 0)
  43809. return -1;
  43810. ret = JS_DefineProperty(ctx, obj, prop,
  43811. d.value, d.getter, d.setter, d.flags | flags);
  43812. js_free_desc(ctx, &d);
  43813. return ret;
  43814. }
  43815. static __exception int JS_ObjectDefineProperties(JSContext *ctx,
  43816. JSValueConst obj,
  43817. JSValueConst properties)
  43818. {
  43819. JSValue props, desc;
  43820. JSObject *p;
  43821. JSPropertyEnum *atoms;
  43822. uint32_t len, i;
  43823. int ret = -1;
  43824. if (!JS_IsObject(obj)) {
  43825. JS_ThrowTypeError(ctx, "Object.defineProperties called on non-object");
  43826. return -1;
  43827. }
  43828. desc = JS_UNDEFINED;
  43829. props = JS_ToObject(ctx, properties);
  43830. if (JS_IsException(props))
  43831. return -1;
  43832. p = JS_VALUE_GET_OBJ(props);
  43833. if (JS_GetOwnPropertyNamesInternal(ctx, &atoms, &len, p, JS_GPN_ENUM_ONLY | JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK) < 0)
  43834. goto exception;
  43835. // XXX: ECMA specifies that all descriptions should be validated before
  43836. // modifying the object. This would require allocating an array
  43837. // JSPropertyDescriptor and use 2 separate loops.
  43838. for(i = 0; i < len; i++) {
  43839. JS_FreeValue(ctx, desc);
  43840. desc = JS_GetProperty(ctx, props, atoms[i].atom);
  43841. if (JS_IsException(desc))
  43842. goto exception;
  43843. if (JS_DefinePropertyDesc(ctx, obj, atoms[i].atom, desc,
  43844. JS_PROP_THROW | JS_PROP_DEFINE_PROPERTY) < 0)
  43845. goto exception;
  43846. }
  43847. ret = 0;
  43848. exception:
  43849. js_free_prop_enum(ctx, atoms, len);
  43850. JS_FreeValue(ctx, props);
  43851. JS_FreeValue(ctx, desc);
  43852. return ret;
  43853. }
  43854. static JSValue js_object_constructor(JSContext *ctx, JSValueConst new_target,
  43855. int argc, JSValueConst *argv)
  43856. {
  43857. JSValue ret;
  43858. if (!JS_IsUndefined(new_target) &&
  43859. JS_VALUE_GET_OBJ(new_target) !=
  43860. JS_VALUE_GET_OBJ(JS_GetActiveFunction(ctx))) {
  43861. ret = js_create_from_ctor(ctx, new_target, JS_CLASS_OBJECT);
  43862. } else {
  43863. int tag = JS_VALUE_GET_NORM_TAG(argv[0]);
  43864. switch(tag) {
  43865. case JS_TAG_NULL:
  43866. case JS_TAG_UNDEFINED:
  43867. ret = JS_NewObject(ctx);
  43868. break;
  43869. default:
  43870. ret = JS_ToObject(ctx, argv[0]);
  43871. break;
  43872. }
  43873. }
  43874. return ret;
  43875. }
  43876. static JSValue js_object_create(JSContext *ctx, JSValueConst this_val,
  43877. int argc, JSValueConst *argv)
  43878. {
  43879. JSValueConst proto, props;
  43880. JSValue obj;
  43881. proto = argv[0];
  43882. if (!JS_IsObject(proto) && !JS_IsNull(proto))
  43883. return JS_ThrowTypeError(ctx, "object prototype may only be an Object or null");
  43884. obj = JS_NewObjectProto(ctx, proto);
  43885. if (JS_IsException(obj))
  43886. return JS_EXCEPTION;
  43887. props = argv[1];
  43888. if (!JS_IsUndefined(props)) {
  43889. if (JS_ObjectDefineProperties(ctx, obj, props)) {
  43890. JS_FreeValue(ctx, obj);
  43891. return JS_EXCEPTION;
  43892. }
  43893. }
  43894. return obj;
  43895. }
  43896. static JSValue js_object_getPrototypeOf(JSContext *ctx, JSValueConst this_val,
  43897. int argc, JSValueConst *argv, int magic)
  43898. {
  43899. JSValueConst val = argv[0];
  43900. if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT) {
  43901. /* ES6 feature non compatible with ES5.1: primitive types are
  43902. accepted */
  43903. if (magic || JS_VALUE_GET_TAG(val) == JS_TAG_NULL ||
  43904. JS_VALUE_GET_TAG(val) == JS_TAG_UNDEFINED)
  43905. return JS_ThrowTypeErrorNotAnObject(ctx);
  43906. }
  43907. return JS_GetPrototype(ctx, val);
  43908. }
  43909. static JSValue js_object_setPrototypeOf(JSContext *ctx, JSValueConst this_val,
  43910. int argc, JSValueConst *argv)
  43911. {
  43912. JSValueConst obj = argv[0];
  43913. if (JS_SetPrototypeInternal(ctx, obj, argv[1], true) < 0)
  43914. return JS_EXCEPTION;
  43915. return js_dup(obj);
  43916. }
  43917. /* magic = 1 if called as Reflect.defineProperty */
  43918. static JSValue js_object_defineProperty(JSContext *ctx, JSValueConst this_val,
  43919. int argc, JSValueConst *argv, int magic)
  43920. {
  43921. JSValueConst obj, prop, desc;
  43922. int ret, flags;
  43923. JSAtom atom;
  43924. obj = argv[0];
  43925. prop = argv[1];
  43926. desc = argv[2];
  43927. if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)
  43928. return JS_ThrowTypeErrorNotAnObject(ctx);
  43929. atom = JS_ValueToAtom(ctx, prop);
  43930. if (unlikely(atom == JS_ATOM_NULL))
  43931. return JS_EXCEPTION;
  43932. flags = JS_PROP_THROW | JS_PROP_DEFINE_PROPERTY;
  43933. if (magic)
  43934. flags = JS_PROP_REFLECT_DEFINE_PROPERTY;
  43935. ret = JS_DefinePropertyDesc(ctx, obj, atom, desc, flags);
  43936. JS_FreeAtom(ctx, atom);
  43937. if (ret < 0) {
  43938. return JS_EXCEPTION;
  43939. } else if (magic) {
  43940. return js_bool(ret);
  43941. } else {
  43942. return js_dup(obj);
  43943. }
  43944. }
  43945. static JSValue js_object_defineProperties(JSContext *ctx, JSValueConst this_val,
  43946. int argc, JSValueConst *argv)
  43947. {
  43948. // defineProperties(obj, properties)
  43949. JSValueConst obj = argv[0];
  43950. if (JS_ObjectDefineProperties(ctx, obj, argv[1]))
  43951. return JS_EXCEPTION;
  43952. return js_dup(obj);
  43953. }
  43954. /* magic = 1 if called as __defineSetter__ */
  43955. static JSValue js_object___defineGetter__(JSContext *ctx, JSValueConst this_val,
  43956. int argc, JSValueConst *argv, int magic)
  43957. {
  43958. JSValue obj;
  43959. JSValueConst prop, value, get, set;
  43960. int ret, flags;
  43961. JSAtom atom;
  43962. prop = argv[0];
  43963. value = argv[1];
  43964. obj = JS_ToObject(ctx, this_val);
  43965. if (JS_IsException(obj))
  43966. return JS_EXCEPTION;
  43967. if (check_function(ctx, value)) {
  43968. JS_FreeValue(ctx, obj);
  43969. return JS_EXCEPTION;
  43970. }
  43971. atom = JS_ValueToAtom(ctx, prop);
  43972. if (unlikely(atom == JS_ATOM_NULL)) {
  43973. JS_FreeValue(ctx, obj);
  43974. return JS_EXCEPTION;
  43975. }
  43976. flags = JS_PROP_THROW |
  43977. JS_PROP_HAS_ENUMERABLE | JS_PROP_ENUMERABLE |
  43978. JS_PROP_HAS_CONFIGURABLE | JS_PROP_CONFIGURABLE;
  43979. if (magic) {
  43980. get = JS_UNDEFINED;
  43981. set = value;
  43982. flags |= JS_PROP_HAS_SET;
  43983. } else {
  43984. get = value;
  43985. set = JS_UNDEFINED;
  43986. flags |= JS_PROP_HAS_GET;
  43987. }
  43988. ret = JS_DefineProperty(ctx, obj, atom, JS_UNDEFINED, get, set, flags);
  43989. JS_FreeValue(ctx, obj);
  43990. JS_FreeAtom(ctx, atom);
  43991. if (ret < 0) {
  43992. return JS_EXCEPTION;
  43993. } else {
  43994. return JS_UNDEFINED;
  43995. }
  43996. }
  43997. static JSValue js_object_getOwnPropertyDescriptor(JSContext *ctx, JSValueConst this_val,
  43998. int argc, JSValueConst *argv, int magic)
  43999. {
  44000. JSValueConst prop;
  44001. JSAtom atom;
  44002. JSValue ret, obj;
  44003. JSPropertyDescriptor desc;
  44004. int res, flags;
  44005. if (magic) {
  44006. /* Reflect.getOwnPropertyDescriptor case */
  44007. if (JS_VALUE_GET_TAG(argv[0]) != JS_TAG_OBJECT)
  44008. return JS_ThrowTypeErrorNotAnObject(ctx);
  44009. obj = js_dup(argv[0]);
  44010. } else {
  44011. obj = JS_ToObject(ctx, argv[0]);
  44012. if (JS_IsException(obj))
  44013. return obj;
  44014. }
  44015. prop = argv[1];
  44016. atom = JS_ValueToAtom(ctx, prop);
  44017. if (unlikely(atom == JS_ATOM_NULL))
  44018. goto exception;
  44019. ret = JS_UNDEFINED;
  44020. if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) {
  44021. res = JS_GetOwnPropertyInternal(ctx, &desc, JS_VALUE_GET_OBJ(obj), atom);
  44022. if (res < 0)
  44023. goto exception;
  44024. if (res) {
  44025. ret = JS_NewObject(ctx);
  44026. if (JS_IsException(ret))
  44027. goto exception1;
  44028. flags = JS_PROP_C_W_E | JS_PROP_THROW;
  44029. if (desc.flags & JS_PROP_GETSET) {
  44030. if (JS_DefinePropertyValue(ctx, ret, JS_ATOM_get, js_dup(desc.getter), flags) < 0
  44031. || JS_DefinePropertyValue(ctx, ret, JS_ATOM_set, js_dup(desc.setter), flags) < 0)
  44032. goto exception1;
  44033. } else {
  44034. if (JS_DefinePropertyValue(ctx, ret, JS_ATOM_value, js_dup(desc.value), flags) < 0
  44035. || JS_DefinePropertyValue(ctx, ret, JS_ATOM_writable,
  44036. js_bool(desc.flags & JS_PROP_WRITABLE),
  44037. flags) < 0)
  44038. goto exception1;
  44039. }
  44040. if (JS_DefinePropertyValue(ctx, ret, JS_ATOM_enumerable,
  44041. js_bool(desc.flags & JS_PROP_ENUMERABLE),
  44042. flags) < 0
  44043. || JS_DefinePropertyValue(ctx, ret, JS_ATOM_configurable,
  44044. js_bool(desc.flags & JS_PROP_CONFIGURABLE),
  44045. flags) < 0)
  44046. goto exception1;
  44047. js_free_desc(ctx, &desc);
  44048. }
  44049. }
  44050. JS_FreeAtom(ctx, atom);
  44051. JS_FreeValue(ctx, obj);
  44052. return ret;
  44053. exception1:
  44054. js_free_desc(ctx, &desc);
  44055. JS_FreeValue(ctx, ret);
  44056. exception:
  44057. JS_FreeAtom(ctx, atom);
  44058. JS_FreeValue(ctx, obj);
  44059. return JS_EXCEPTION;
  44060. }
  44061. static JSValue js_object_getOwnPropertyDescriptors(JSContext *ctx, JSValueConst this_val,
  44062. int argc, JSValueConst *argv)
  44063. {
  44064. //getOwnPropertyDescriptors(obj)
  44065. JSValue obj, r;
  44066. JSObject *p;
  44067. JSPropertyEnum *props;
  44068. uint32_t len, i;
  44069. r = JS_UNDEFINED;
  44070. obj = JS_ToObject(ctx, argv[0]);
  44071. if (JS_IsException(obj))
  44072. return JS_EXCEPTION;
  44073. p = JS_VALUE_GET_OBJ(obj);
  44074. if (JS_GetOwnPropertyNamesInternal(ctx, &props, &len, p,
  44075. JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK))
  44076. goto exception;
  44077. r = JS_NewObject(ctx);
  44078. if (JS_IsException(r))
  44079. goto exception;
  44080. for(i = 0; i < len; i++) {
  44081. JSValue atomValue, desc;
  44082. JSValueConst args[2];
  44083. atomValue = JS_AtomToValue(ctx, props[i].atom);
  44084. if (JS_IsException(atomValue))
  44085. goto exception;
  44086. args[0] = obj;
  44087. args[1] = atomValue;
  44088. desc = js_object_getOwnPropertyDescriptor(ctx, JS_UNDEFINED, 2, args, 0);
  44089. JS_FreeValue(ctx, atomValue);
  44090. if (JS_IsException(desc))
  44091. goto exception;
  44092. if (!JS_IsUndefined(desc)) {
  44093. if (JS_DefinePropertyValue(ctx, r, props[i].atom, desc,
  44094. JS_PROP_C_W_E | JS_PROP_THROW) < 0)
  44095. goto exception;
  44096. }
  44097. }
  44098. js_free_prop_enum(ctx, props, len);
  44099. JS_FreeValue(ctx, obj);
  44100. return r;
  44101. exception:
  44102. js_free_prop_enum(ctx, props, len);
  44103. JS_FreeValue(ctx, obj);
  44104. JS_FreeValue(ctx, r);
  44105. return JS_EXCEPTION;
  44106. }
  44107. static JSValue JS_GetOwnPropertyNames2(JSContext *ctx, JSValueConst obj1,
  44108. int flags, int kind)
  44109. {
  44110. JSValue obj, r, val, key, value;
  44111. JSObject *p;
  44112. JSPropertyEnum *atoms;
  44113. uint32_t len, i, j;
  44114. r = JS_UNDEFINED;
  44115. val = JS_UNDEFINED;
  44116. obj = JS_ToObject(ctx, obj1);
  44117. if (JS_IsException(obj))
  44118. return JS_EXCEPTION;
  44119. p = JS_VALUE_GET_OBJ(obj);
  44120. if (JS_GetOwnPropertyNamesInternal(ctx, &atoms, &len, p, flags & ~JS_GPN_ENUM_ONLY))
  44121. goto exception;
  44122. r = JS_NewArray(ctx);
  44123. if (JS_IsException(r))
  44124. goto exception;
  44125. for(j = i = 0; i < len; i++) {
  44126. JSAtom atom = atoms[i].atom;
  44127. if (flags & JS_GPN_ENUM_ONLY) {
  44128. JSPropertyDescriptor desc;
  44129. int res;
  44130. /* Check if property is still enumerable */
  44131. res = JS_GetOwnPropertyInternal(ctx, &desc, p, atom);
  44132. if (res < 0)
  44133. goto exception;
  44134. if (!res)
  44135. continue;
  44136. js_free_desc(ctx, &desc);
  44137. if (!(desc.flags & JS_PROP_ENUMERABLE))
  44138. continue;
  44139. }
  44140. switch(kind) {
  44141. default:
  44142. case JS_ITERATOR_KIND_KEY:
  44143. val = JS_AtomToValue(ctx, atom);
  44144. if (JS_IsException(val))
  44145. goto exception;
  44146. break;
  44147. case JS_ITERATOR_KIND_VALUE:
  44148. val = JS_GetProperty(ctx, obj, atom);
  44149. if (JS_IsException(val))
  44150. goto exception;
  44151. break;
  44152. case JS_ITERATOR_KIND_KEY_AND_VALUE:
  44153. val = JS_NewArray(ctx);
  44154. if (JS_IsException(val))
  44155. goto exception;
  44156. key = JS_AtomToValue(ctx, atom);
  44157. if (JS_IsException(key))
  44158. goto exception1;
  44159. if (JS_CreateDataPropertyUint32(ctx, val, 0, key, JS_PROP_THROW) < 0)
  44160. goto exception1;
  44161. value = JS_GetProperty(ctx, obj, atom);
  44162. if (JS_IsException(value))
  44163. goto exception1;
  44164. if (JS_CreateDataPropertyUint32(ctx, val, 1, value, JS_PROP_THROW) < 0)
  44165. goto exception1;
  44166. break;
  44167. }
  44168. if (JS_CreateDataPropertyUint32(ctx, r, j++, val, 0) < 0)
  44169. goto exception;
  44170. }
  44171. goto done;
  44172. exception1:
  44173. JS_FreeValue(ctx, val);
  44174. exception:
  44175. JS_FreeValue(ctx, r);
  44176. r = JS_EXCEPTION;
  44177. done:
  44178. js_free_prop_enum(ctx, atoms, len);
  44179. JS_FreeValue(ctx, obj);
  44180. return r;
  44181. }
  44182. static JSValue js_object_getOwnPropertyNames(JSContext *ctx, JSValueConst this_val,
  44183. int argc, JSValueConst *argv)
  44184. {
  44185. return JS_GetOwnPropertyNames2(ctx, argv[0],
  44186. JS_GPN_STRING_MASK, JS_ITERATOR_KIND_KEY);
  44187. }
  44188. static JSValue js_object_getOwnPropertySymbols(JSContext *ctx, JSValueConst this_val,
  44189. int argc, JSValueConst *argv)
  44190. {
  44191. return JS_GetOwnPropertyNames2(ctx, argv[0],
  44192. JS_GPN_SYMBOL_MASK, JS_ITERATOR_KIND_KEY);
  44193. }
  44194. static JSValue js_object_groupBy(JSContext *ctx, JSValueConst this_val,
  44195. int argc, JSValueConst *argv)
  44196. {
  44197. JSValue res, iter, next, groups, k, v, prop;
  44198. JSValueConst cb, args[2];
  44199. int64_t idx;
  44200. int done;
  44201. // "is function?" check must be observed before argv[0] is accessed
  44202. cb = argv[1];
  44203. if (check_function(ctx, cb))
  44204. return JS_EXCEPTION;
  44205. // TODO(bnoordhuis) add fast path for arrays but as groupBy() is
  44206. // defined in terms of iterators, the fast path must check that
  44207. // this[Symbol.iterator] is the built-in array iterator
  44208. iter = JS_GetIterator(ctx, argv[0], /*is_async*/false);
  44209. if (JS_IsException(iter))
  44210. return JS_EXCEPTION;
  44211. k = JS_UNDEFINED;
  44212. v = JS_UNDEFINED;
  44213. prop = JS_UNDEFINED;
  44214. groups = JS_UNDEFINED;
  44215. next = JS_GetProperty(ctx, iter, JS_ATOM_next);
  44216. if (JS_IsException(next))
  44217. goto exception;
  44218. groups = JS_NewObjectProto(ctx, JS_NULL);
  44219. if (JS_IsException(groups))
  44220. goto exception;
  44221. for (idx = 0; ; idx++) {
  44222. v = JS_IteratorNext(ctx, iter, next, 0, NULL, &done);
  44223. if (JS_IsException(v))
  44224. goto exception;
  44225. if (done)
  44226. break; // v is JS_UNDEFINED
  44227. args[0] = v;
  44228. args[1] = js_int64(idx);
  44229. k = JS_Call(ctx, cb, ctx->global_obj, 2, args);
  44230. if (JS_IsException(k))
  44231. goto exception;
  44232. k = js_dup(k);
  44233. prop = JS_GetPropertyValue(ctx, groups, k);
  44234. if (JS_IsException(prop))
  44235. goto exception;
  44236. if (JS_IsUndefined(prop)) {
  44237. prop = JS_NewArray(ctx);
  44238. if (JS_IsException(prop))
  44239. goto exception;
  44240. k = js_dup(k);
  44241. prop = js_dup(prop);
  44242. if (JS_SetPropertyValue(ctx, groups, k, prop,
  44243. JS_PROP_C_W_E|JS_PROP_THROW) < 0) {
  44244. goto exception;
  44245. }
  44246. }
  44247. res = js_array_push(ctx, prop, 1, vc(&v), /*unshift*/0);
  44248. if (JS_IsException(res))
  44249. goto exception;
  44250. // res is an int64
  44251. JS_FreeValue(ctx, prop);
  44252. JS_FreeValue(ctx, k);
  44253. JS_FreeValue(ctx, v);
  44254. prop = JS_UNDEFINED;
  44255. k = JS_UNDEFINED;
  44256. v = JS_UNDEFINED;
  44257. }
  44258. JS_FreeValue(ctx, iter);
  44259. JS_FreeValue(ctx, next);
  44260. return groups;
  44261. exception:
  44262. JS_FreeValue(ctx, prop);
  44263. JS_FreeValue(ctx, k);
  44264. JS_FreeValue(ctx, v);
  44265. JS_FreeValue(ctx, groups);
  44266. JS_FreeValue(ctx, iter);
  44267. JS_FreeValue(ctx, next);
  44268. return JS_EXCEPTION;
  44269. }
  44270. static JSValue js_object_keys(JSContext *ctx, JSValueConst this_val,
  44271. int argc, JSValueConst *argv, int kind)
  44272. {
  44273. return JS_GetOwnPropertyNames2(ctx, argv[0],
  44274. JS_GPN_ENUM_ONLY | JS_GPN_STRING_MASK, kind);
  44275. }
  44276. static JSValue js_object_isExtensible(JSContext *ctx, JSValueConst this_val,
  44277. int argc, JSValueConst *argv, int reflect)
  44278. {
  44279. JSValueConst obj;
  44280. int ret;
  44281. obj = argv[0];
  44282. if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) {
  44283. if (reflect)
  44284. return JS_ThrowTypeErrorNotAnObject(ctx);
  44285. else
  44286. return JS_FALSE;
  44287. }
  44288. ret = JS_IsExtensible(ctx, obj);
  44289. if (ret < 0)
  44290. return JS_EXCEPTION;
  44291. else
  44292. return js_bool(ret);
  44293. }
  44294. static JSValue js_object_preventExtensions(JSContext *ctx, JSValueConst this_val,
  44295. int argc, JSValueConst *argv, int reflect)
  44296. {
  44297. JSValueConst obj;
  44298. int ret;
  44299. obj = argv[0];
  44300. if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) {
  44301. if (reflect)
  44302. return JS_ThrowTypeErrorNotAnObject(ctx);
  44303. else
  44304. return js_dup(obj);
  44305. }
  44306. ret = JS_PreventExtensions(ctx, obj);
  44307. if (ret < 0)
  44308. return JS_EXCEPTION;
  44309. if (reflect) {
  44310. return js_bool(ret);
  44311. } else {
  44312. if (!ret)
  44313. return JS_ThrowTypeError(ctx, "proxy preventExtensions handler returned false");
  44314. return js_dup(obj);
  44315. }
  44316. }
  44317. static JSValue js_object_hasOwnProperty(JSContext *ctx, JSValueConst this_val,
  44318. int argc, JSValueConst *argv)
  44319. {
  44320. JSValue obj;
  44321. JSAtom atom;
  44322. JSObject *p;
  44323. int ret;
  44324. atom = JS_ValueToAtom(ctx, argv[0]); /* must be done first */
  44325. if (unlikely(atom == JS_ATOM_NULL))
  44326. return JS_EXCEPTION;
  44327. obj = JS_ToObject(ctx, this_val);
  44328. if (JS_IsException(obj)) {
  44329. JS_FreeAtom(ctx, atom);
  44330. return obj;
  44331. }
  44332. p = JS_VALUE_GET_OBJ(obj);
  44333. ret = JS_GetOwnPropertyInternal(ctx, NULL, p, atom);
  44334. JS_FreeAtom(ctx, atom);
  44335. JS_FreeValue(ctx, obj);
  44336. if (ret < 0)
  44337. return JS_EXCEPTION;
  44338. else
  44339. return js_bool(ret);
  44340. }
  44341. static JSValue js_object_hasOwn(JSContext *ctx, JSValueConst this_val,
  44342. int argc, JSValueConst *argv)
  44343. {
  44344. JSValue obj;
  44345. JSAtom atom;
  44346. JSObject *p;
  44347. int ret;
  44348. obj = JS_ToObject(ctx, argv[0]);
  44349. if (JS_IsException(obj))
  44350. return obj;
  44351. atom = JS_ValueToAtom(ctx, argv[1]);
  44352. if (unlikely(atom == JS_ATOM_NULL)) {
  44353. JS_FreeValue(ctx, obj);
  44354. return JS_EXCEPTION;
  44355. }
  44356. p = JS_VALUE_GET_OBJ(obj);
  44357. ret = JS_GetOwnPropertyInternal(ctx, NULL, p, atom);
  44358. JS_FreeAtom(ctx, atom);
  44359. JS_FreeValue(ctx, obj);
  44360. if (ret < 0)
  44361. return JS_EXCEPTION;
  44362. else
  44363. return js_bool(ret);
  44364. }
  44365. static JSValue js_object_valueOf(JSContext *ctx, JSValueConst this_val,
  44366. int argc, JSValueConst *argv)
  44367. {
  44368. return JS_ToObject(ctx, this_val);
  44369. }
  44370. static JSValue js_object_toString(JSContext *ctx, JSValueConst this_val,
  44371. int argc, JSValueConst *argv)
  44372. {
  44373. JSValue obj, tag;
  44374. int is_array;
  44375. JSAtom atom;
  44376. JSObject *p;
  44377. if (JS_IsNull(this_val)) {
  44378. tag = js_new_string8(ctx, "Null");
  44379. } else if (JS_IsUndefined(this_val)) {
  44380. tag = js_new_string8(ctx, "Undefined");
  44381. } else {
  44382. obj = JS_ToObject(ctx, this_val);
  44383. if (JS_IsException(obj))
  44384. return obj;
  44385. is_array = js_is_array(ctx, obj);
  44386. if (is_array < 0) {
  44387. JS_FreeValue(ctx, obj);
  44388. return JS_EXCEPTION;
  44389. }
  44390. if (is_array) {
  44391. atom = JS_ATOM_Array;
  44392. } else if (JS_IsFunction(ctx, obj)) {
  44393. atom = JS_ATOM_Function;
  44394. } else {
  44395. p = JS_VALUE_GET_OBJ(obj);
  44396. switch(p->class_id) {
  44397. case JS_CLASS_STRING:
  44398. case JS_CLASS_ARGUMENTS:
  44399. case JS_CLASS_MAPPED_ARGUMENTS:
  44400. case JS_CLASS_ERROR:
  44401. case JS_CLASS_BOOLEAN:
  44402. case JS_CLASS_NUMBER:
  44403. case JS_CLASS_DATE:
  44404. case JS_CLASS_REGEXP:
  44405. atom = ctx->rt->class_array[p->class_id].class_name;
  44406. break;
  44407. default:
  44408. atom = JS_ATOM_Object;
  44409. break;
  44410. }
  44411. }
  44412. tag = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_toStringTag);
  44413. JS_FreeValue(ctx, obj);
  44414. if (JS_IsException(tag))
  44415. return JS_EXCEPTION;
  44416. if (!JS_IsString(tag)) {
  44417. JS_FreeValue(ctx, tag);
  44418. tag = JS_AtomToString(ctx, atom);
  44419. }
  44420. }
  44421. return JS_ConcatString3(ctx, "[object ", tag, "]");
  44422. }
  44423. JSValue JS_ToObjectString(JSContext *ctx, JSValueConst val)
  44424. {
  44425. return js_object_toString(ctx, val, 0, NULL);
  44426. }
  44427. static JSValue js_object_toLocaleString(JSContext *ctx, JSValueConst this_val,
  44428. int argc, JSValueConst *argv)
  44429. {
  44430. return JS_Invoke(ctx, this_val, JS_ATOM_toString, 0, NULL);
  44431. }
  44432. static JSValue js_object_assign(JSContext *ctx, JSValueConst this_val,
  44433. int argc, JSValueConst *argv)
  44434. {
  44435. // Object.assign(obj, source1)
  44436. JSValue obj, s;
  44437. int i;
  44438. s = JS_UNDEFINED;
  44439. obj = JS_ToObject(ctx, argv[0]);
  44440. if (JS_IsException(obj))
  44441. goto exception;
  44442. for (i = 1; i < argc; i++) {
  44443. if (!JS_IsNull(argv[i]) && !JS_IsUndefined(argv[i])) {
  44444. s = JS_ToObject(ctx, argv[i]);
  44445. if (JS_IsException(s))
  44446. goto exception;
  44447. if (JS_CopyDataProperties(ctx, obj, s, JS_UNDEFINED, true))
  44448. goto exception;
  44449. JS_FreeValue(ctx, s);
  44450. }
  44451. }
  44452. return obj;
  44453. exception:
  44454. JS_FreeValue(ctx, obj);
  44455. JS_FreeValue(ctx, s);
  44456. return JS_EXCEPTION;
  44457. }
  44458. static JSValue js_object_seal(JSContext *ctx, JSValueConst this_val,
  44459. int argc, JSValueConst *argv, int freeze_flag)
  44460. {
  44461. JSValueConst obj = argv[0];
  44462. JSObject *p;
  44463. JSTypedArray *ta;
  44464. JSArrayBuffer *abuf;
  44465. JSPropertyEnum *props;
  44466. uint32_t len, i;
  44467. int flags, desc_flags, res;
  44468. if (!JS_IsObject(obj))
  44469. return js_dup(obj);
  44470. p = JS_VALUE_GET_OBJ(obj);
  44471. if (p->class_id == JS_CLASS_MODULE_NS) {
  44472. return JS_ThrowTypeError(ctx, "cannot %s module namespace",
  44473. freeze_flag ? "freeze" : "seal");
  44474. }
  44475. res = JS_PreventExtensions(ctx, obj);
  44476. if (res < 0)
  44477. return JS_EXCEPTION;
  44478. if (!res) {
  44479. return JS_ThrowTypeError(ctx, "proxy preventExtensions handler returned false");
  44480. }
  44481. if (freeze_flag && is_typed_array(p->class_id)) {
  44482. ta = p->u.typed_array;
  44483. abuf = ta->buffer->u.array_buffer;
  44484. if (array_buffer_is_resizable(abuf) || typed_array_is_oob(p))
  44485. return JS_ThrowTypeError(ctx, "cannot freeze resizable typed array");
  44486. }
  44487. flags = JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK;
  44488. if (JS_GetOwnPropertyNamesInternal(ctx, &props, &len, p, flags))
  44489. return JS_EXCEPTION;
  44490. for(i = 0; i < len; i++) {
  44491. JSPropertyDescriptor desc;
  44492. JSAtom prop = props[i].atom;
  44493. desc_flags = JS_PROP_THROW | JS_PROP_HAS_CONFIGURABLE;
  44494. if (freeze_flag) {
  44495. res = JS_GetOwnPropertyInternal(ctx, &desc, p, prop);
  44496. if (res < 0)
  44497. goto exception;
  44498. if (res) {
  44499. if (desc.flags & JS_PROP_WRITABLE)
  44500. desc_flags |= JS_PROP_HAS_WRITABLE;
  44501. js_free_desc(ctx, &desc);
  44502. }
  44503. }
  44504. if (JS_DefineProperty(ctx, obj, prop, JS_UNDEFINED,
  44505. JS_UNDEFINED, JS_UNDEFINED, desc_flags) < 0)
  44506. goto exception;
  44507. }
  44508. js_free_prop_enum(ctx, props, len);
  44509. return js_dup(obj);
  44510. exception:
  44511. js_free_prop_enum(ctx, props, len);
  44512. return JS_EXCEPTION;
  44513. }
  44514. static JSValue js_object_isSealed(JSContext *ctx, JSValueConst this_val,
  44515. int argc, JSValueConst *argv, int is_frozen)
  44516. {
  44517. JSValueConst obj = argv[0];
  44518. JSObject *p;
  44519. JSPropertyEnum *props;
  44520. uint32_t len, i;
  44521. int flags, res;
  44522. if (!JS_IsObject(obj))
  44523. return JS_TRUE;
  44524. p = JS_VALUE_GET_OBJ(obj);
  44525. flags = JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK;
  44526. if (JS_GetOwnPropertyNamesInternal(ctx, &props, &len, p, flags))
  44527. return JS_EXCEPTION;
  44528. for(i = 0; i < len; i++) {
  44529. JSPropertyDescriptor desc;
  44530. JSAtom prop = props[i].atom;
  44531. res = JS_GetOwnPropertyInternal(ctx, &desc, p, prop);
  44532. if (res < 0)
  44533. goto exception;
  44534. if (res) {
  44535. js_free_desc(ctx, &desc);
  44536. if ((desc.flags & JS_PROP_CONFIGURABLE)
  44537. || (is_frozen && (desc.flags & JS_PROP_WRITABLE))) {
  44538. res = false;
  44539. goto done;
  44540. }
  44541. }
  44542. }
  44543. res = JS_IsExtensible(ctx, obj);
  44544. if (res < 0)
  44545. return JS_EXCEPTION;
  44546. res ^= 1;
  44547. done:
  44548. js_free_prop_enum(ctx, props, len);
  44549. return js_bool(res);
  44550. exception:
  44551. js_free_prop_enum(ctx, props, len);
  44552. return JS_EXCEPTION;
  44553. }
  44554. int JS_SealObject(JSContext *ctx, JSValueConst obj)
  44555. {
  44556. JSValue value = js_object_seal(ctx, JS_UNDEFINED, 1, &obj, 0);
  44557. int result = JS_IsException(value) ? -1 : true;
  44558. JS_FreeValue(ctx, value);
  44559. return result;
  44560. }
  44561. int JS_FreezeObject(JSContext *ctx, JSValueConst obj)
  44562. {
  44563. JSValue value = js_object_seal(ctx, JS_UNDEFINED, 1, &obj, 1);
  44564. int result = JS_IsException(value) ? -1 : true;
  44565. JS_FreeValue(ctx, value);
  44566. return result;
  44567. }
  44568. static JSValue js_object_fromEntries(JSContext *ctx, JSValueConst this_val,
  44569. int argc, JSValueConst *argv)
  44570. {
  44571. JSValue obj, iter, next_method = JS_UNDEFINED;
  44572. JSValueConst iterable;
  44573. int done;
  44574. /* RequireObjectCoercible() not necessary because it is tested in
  44575. JS_GetIterator() by JS_GetProperty() */
  44576. iterable = argv[0];
  44577. obj = JS_NewObject(ctx);
  44578. if (JS_IsException(obj))
  44579. return obj;
  44580. iter = JS_GetIterator(ctx, iterable, false);
  44581. if (JS_IsException(iter))
  44582. goto fail;
  44583. next_method = JS_GetProperty(ctx, iter, JS_ATOM_next);
  44584. if (JS_IsException(next_method))
  44585. goto fail;
  44586. for(;;) {
  44587. JSValue key, value, item;
  44588. item = JS_IteratorNext(ctx, iter, next_method, 0, NULL, &done);
  44589. if (JS_IsException(item))
  44590. goto fail;
  44591. if (done) {
  44592. JS_FreeValue(ctx, item);
  44593. break;
  44594. }
  44595. key = JS_UNDEFINED;
  44596. value = JS_UNDEFINED;
  44597. if (!JS_IsObject(item)) {
  44598. JS_ThrowTypeErrorNotAnObject(ctx);
  44599. goto fail1;
  44600. }
  44601. key = JS_GetPropertyUint32(ctx, item, 0);
  44602. if (JS_IsException(key))
  44603. goto fail1;
  44604. value = JS_GetPropertyUint32(ctx, item, 1);
  44605. if (JS_IsException(value)) {
  44606. JS_FreeValue(ctx, key);
  44607. goto fail1;
  44608. }
  44609. if (JS_DefinePropertyValueValue(ctx, obj, key, value,
  44610. JS_PROP_C_W_E | JS_PROP_THROW) < 0) {
  44611. fail1:
  44612. JS_FreeValue(ctx, item);
  44613. goto fail;
  44614. }
  44615. JS_FreeValue(ctx, item);
  44616. }
  44617. JS_FreeValue(ctx, next_method);
  44618. JS_FreeValue(ctx, iter);
  44619. return obj;
  44620. fail:
  44621. if (JS_IsObject(iter)) {
  44622. /* close the iterator object, preserving pending exception */
  44623. JS_IteratorClose(ctx, iter, true);
  44624. }
  44625. JS_FreeValue(ctx, next_method);
  44626. JS_FreeValue(ctx, iter);
  44627. JS_FreeValue(ctx, obj);
  44628. return JS_EXCEPTION;
  44629. }
  44630. static JSValue js_object_is(JSContext *ctx, JSValueConst this_val,
  44631. int argc, JSValueConst *argv)
  44632. {
  44633. return js_bool(js_same_value(ctx, argv[0], argv[1]));
  44634. }
  44635. static JSValue JS_SpeciesConstructor(JSContext *ctx, JSValueConst obj,
  44636. JSValueConst defaultConstructor)
  44637. {
  44638. JSValue ctor, species;
  44639. if (!JS_IsObject(obj))
  44640. return JS_ThrowTypeErrorNotAnObject(ctx);
  44641. ctor = JS_GetProperty(ctx, obj, JS_ATOM_constructor);
  44642. if (JS_IsException(ctor))
  44643. return ctor;
  44644. if (JS_IsUndefined(ctor))
  44645. return js_dup(defaultConstructor);
  44646. if (!JS_IsObject(ctor)) {
  44647. JS_FreeValue(ctx, ctor);
  44648. return JS_ThrowTypeErrorNotAnObject(ctx);
  44649. }
  44650. species = JS_GetProperty(ctx, ctor, JS_ATOM_Symbol_species);
  44651. JS_FreeValue(ctx, ctor);
  44652. if (JS_IsException(species))
  44653. return species;
  44654. if (JS_IsUndefined(species) || JS_IsNull(species))
  44655. return js_dup(defaultConstructor);
  44656. if (!JS_IsConstructor(ctx, species)) {
  44657. JS_FreeValue(ctx, species);
  44658. return JS_ThrowTypeError(ctx, "not a constructor");
  44659. }
  44660. return species;
  44661. }
  44662. static JSValue js_object_get___proto__(JSContext *ctx, JSValueConst this_val)
  44663. {
  44664. JSValue val, ret;
  44665. val = JS_ToObject(ctx, this_val);
  44666. if (JS_IsException(val))
  44667. return val;
  44668. ret = JS_GetPrototype(ctx, val);
  44669. JS_FreeValue(ctx, val);
  44670. return ret;
  44671. }
  44672. static JSValue js_object_set___proto__(JSContext *ctx, JSValueConst this_val,
  44673. JSValueConst proto)
  44674. {
  44675. if (JS_IsUndefined(this_val) || JS_IsNull(this_val))
  44676. return JS_ThrowTypeErrorNotAnObject(ctx);
  44677. if (!JS_IsObject(proto) && !JS_IsNull(proto))
  44678. return JS_UNDEFINED;
  44679. if (JS_SetPrototypeInternal(ctx, this_val, proto, true) < 0)
  44680. return JS_EXCEPTION;
  44681. else
  44682. return JS_UNDEFINED;
  44683. }
  44684. static JSValue js_object_isPrototypeOf(JSContext *ctx, JSValueConst this_val,
  44685. int argc, JSValueConst *argv)
  44686. {
  44687. JSValue obj, v1;
  44688. JSValueConst v;
  44689. int res;
  44690. v = argv[0];
  44691. if (!JS_IsObject(v))
  44692. return JS_FALSE;
  44693. obj = JS_ToObject(ctx, this_val);
  44694. if (JS_IsException(obj))
  44695. return JS_EXCEPTION;
  44696. v1 = js_dup(v);
  44697. for(;;) {
  44698. v1 = JS_GetPrototypeFree(ctx, v1);
  44699. if (JS_IsException(v1))
  44700. goto exception;
  44701. if (JS_IsNull(v1)) {
  44702. res = false;
  44703. break;
  44704. }
  44705. if (JS_VALUE_GET_OBJ(obj) == JS_VALUE_GET_OBJ(v1)) {
  44706. res = true;
  44707. break;
  44708. }
  44709. /* avoid infinite loop (possible with proxies) */
  44710. if (js_poll_interrupts(ctx))
  44711. goto exception;
  44712. }
  44713. JS_FreeValue(ctx, v1);
  44714. JS_FreeValue(ctx, obj);
  44715. return js_bool(res);
  44716. exception:
  44717. JS_FreeValue(ctx, v1);
  44718. JS_FreeValue(ctx, obj);
  44719. return JS_EXCEPTION;
  44720. }
  44721. static JSValue js_object_propertyIsEnumerable(JSContext *ctx, JSValueConst this_val,
  44722. int argc, JSValueConst *argv)
  44723. {
  44724. JSValue obj, res = JS_EXCEPTION;
  44725. JSAtom prop = JS_ATOM_NULL;
  44726. JSPropertyDescriptor desc;
  44727. int has_prop;
  44728. obj = JS_ToObject(ctx, this_val);
  44729. if (JS_IsException(obj))
  44730. goto exception;
  44731. prop = JS_ValueToAtom(ctx, argv[0]);
  44732. if (unlikely(prop == JS_ATOM_NULL))
  44733. goto exception;
  44734. has_prop = JS_GetOwnPropertyInternal(ctx, &desc, JS_VALUE_GET_OBJ(obj), prop);
  44735. if (has_prop < 0)
  44736. goto exception;
  44737. if (has_prop) {
  44738. res = js_bool(desc.flags & JS_PROP_ENUMERABLE);
  44739. js_free_desc(ctx, &desc);
  44740. } else {
  44741. res = JS_FALSE;
  44742. }
  44743. exception:
  44744. JS_FreeAtom(ctx, prop);
  44745. JS_FreeValue(ctx, obj);
  44746. return res;
  44747. }
  44748. static JSValue js_object___lookupGetter__(JSContext *ctx, JSValueConst this_val,
  44749. int argc, JSValueConst *argv, int setter)
  44750. {
  44751. JSValue obj, res = JS_EXCEPTION;
  44752. JSAtom prop = JS_ATOM_NULL;
  44753. JSPropertyDescriptor desc;
  44754. int has_prop;
  44755. obj = JS_ToObject(ctx, this_val);
  44756. if (JS_IsException(obj))
  44757. goto exception;
  44758. prop = JS_ValueToAtom(ctx, argv[0]);
  44759. if (unlikely(prop == JS_ATOM_NULL))
  44760. goto exception;
  44761. for (;;) {
  44762. has_prop = JS_GetOwnPropertyInternal(ctx, &desc, JS_VALUE_GET_OBJ(obj), prop);
  44763. if (has_prop < 0)
  44764. goto exception;
  44765. if (has_prop) {
  44766. if (desc.flags & JS_PROP_GETSET)
  44767. res = js_dup(setter ? desc.setter : desc.getter);
  44768. else
  44769. res = JS_UNDEFINED;
  44770. js_free_desc(ctx, &desc);
  44771. break;
  44772. }
  44773. obj = JS_GetPrototypeFree(ctx, obj);
  44774. if (JS_IsException(obj))
  44775. goto exception;
  44776. if (JS_IsNull(obj)) {
  44777. res = JS_UNDEFINED;
  44778. break;
  44779. }
  44780. /* avoid infinite loop (possible with proxies) */
  44781. if (js_poll_interrupts(ctx))
  44782. goto exception;
  44783. }
  44784. exception:
  44785. JS_FreeAtom(ctx, prop);
  44786. JS_FreeValue(ctx, obj);
  44787. return res;
  44788. }
  44789. static const JSCFunctionListEntry js_object_funcs[] = {
  44790. JS_CFUNC_DEF("create", 2, js_object_create ),
  44791. JS_CFUNC_MAGIC_DEF("getPrototypeOf", 1, js_object_getPrototypeOf, 0 ),
  44792. JS_CFUNC_DEF("setPrototypeOf", 2, js_object_setPrototypeOf ),
  44793. JS_CFUNC_MAGIC_DEF("defineProperty", 3, js_object_defineProperty, 0 ),
  44794. JS_CFUNC_DEF("defineProperties", 2, js_object_defineProperties ),
  44795. JS_CFUNC_DEF("getOwnPropertyNames", 1, js_object_getOwnPropertyNames ),
  44796. JS_CFUNC_DEF("getOwnPropertySymbols", 1, js_object_getOwnPropertySymbols ),
  44797. JS_CFUNC_DEF("groupBy", 2, js_object_groupBy ),
  44798. JS_CFUNC_MAGIC_DEF("keys", 1, js_object_keys, JS_ITERATOR_KIND_KEY ),
  44799. JS_CFUNC_MAGIC_DEF("values", 1, js_object_keys, JS_ITERATOR_KIND_VALUE ),
  44800. JS_CFUNC_MAGIC_DEF("entries", 1, js_object_keys, JS_ITERATOR_KIND_KEY_AND_VALUE ),
  44801. JS_CFUNC_MAGIC_DEF("isExtensible", 1, js_object_isExtensible, 0 ),
  44802. JS_CFUNC_MAGIC_DEF("preventExtensions", 1, js_object_preventExtensions, 0 ),
  44803. JS_CFUNC_MAGIC_DEF("getOwnPropertyDescriptor", 2, js_object_getOwnPropertyDescriptor, 0 ),
  44804. JS_CFUNC_DEF("getOwnPropertyDescriptors", 1, js_object_getOwnPropertyDescriptors ),
  44805. JS_CFUNC_DEF("is", 2, js_object_is ),
  44806. JS_CFUNC_DEF("assign", 2, js_object_assign ),
  44807. JS_CFUNC_MAGIC_DEF("seal", 1, js_object_seal, 0 ),
  44808. JS_CFUNC_MAGIC_DEF("freeze", 1, js_object_seal, 1 ),
  44809. JS_CFUNC_MAGIC_DEF("isSealed", 1, js_object_isSealed, 0 ),
  44810. JS_CFUNC_MAGIC_DEF("isFrozen", 1, js_object_isSealed, 1 ),
  44811. JS_CFUNC_DEF("fromEntries", 1, js_object_fromEntries ),
  44812. JS_CFUNC_DEF("hasOwn", 2, js_object_hasOwn ),
  44813. };
  44814. static const JSCFunctionListEntry js_object_proto_funcs[] = {
  44815. JS_CFUNC_DEF("toString", 0, js_object_toString ),
  44816. JS_CFUNC_DEF("toLocaleString", 0, js_object_toLocaleString ),
  44817. JS_CFUNC_DEF("valueOf", 0, js_object_valueOf ),
  44818. JS_CFUNC_DEF("hasOwnProperty", 1, js_object_hasOwnProperty ),
  44819. JS_CFUNC_DEF("isPrototypeOf", 1, js_object_isPrototypeOf ),
  44820. JS_CFUNC_DEF("propertyIsEnumerable", 1, js_object_propertyIsEnumerable ),
  44821. JS_CGETSET_DEF("__proto__", js_object_get___proto__, js_object_set___proto__ ),
  44822. JS_CFUNC_MAGIC_DEF("__defineGetter__", 2, js_object___defineGetter__, 0 ),
  44823. JS_CFUNC_MAGIC_DEF("__defineSetter__", 2, js_object___defineGetter__, 1 ),
  44824. JS_CFUNC_MAGIC_DEF("__lookupGetter__", 1, js_object___lookupGetter__, 0 ),
  44825. JS_CFUNC_MAGIC_DEF("__lookupSetter__", 1, js_object___lookupGetter__, 1 ),
  44826. };
  44827. /* Function class */
  44828. static JSValue js_function_proto(JSContext *ctx, JSValueConst this_val,
  44829. int argc, JSValueConst *argv)
  44830. {
  44831. return JS_UNDEFINED;
  44832. }
  44833. /* XXX: add a specific eval mode so that Function("}), ({") is rejected */
  44834. static JSValue js_function_constructor(JSContext *ctx, JSValueConst new_target,
  44835. int argc, JSValueConst *argv, int magic)
  44836. {
  44837. JSFunctionKindEnum func_kind = magic;
  44838. int i, n, ret;
  44839. JSValue s, proto, obj = JS_UNDEFINED;
  44840. StringBuffer b_s, *b = &b_s;
  44841. string_buffer_init(ctx, b, 0);
  44842. string_buffer_putc8(b, '(');
  44843. if (func_kind == JS_FUNC_ASYNC || func_kind == JS_FUNC_ASYNC_GENERATOR) {
  44844. string_buffer_puts8(b, "async ");
  44845. }
  44846. string_buffer_puts8(b, "function");
  44847. if (func_kind == JS_FUNC_GENERATOR || func_kind == JS_FUNC_ASYNC_GENERATOR) {
  44848. string_buffer_putc8(b, '*');
  44849. }
  44850. string_buffer_puts8(b, " anonymous(");
  44851. n = argc - 1;
  44852. for(i = 0; i < n; i++) {
  44853. if (i != 0) {
  44854. string_buffer_putc8(b, ',');
  44855. }
  44856. if (string_buffer_concat_value(b, argv[i]))
  44857. goto fail;
  44858. }
  44859. string_buffer_puts8(b, "\n) {\n");
  44860. if (n >= 0) {
  44861. if (string_buffer_concat_value(b, argv[n]))
  44862. goto fail;
  44863. }
  44864. string_buffer_puts8(b, "\n})");
  44865. s = string_buffer_end(b);
  44866. if (JS_IsException(s))
  44867. goto fail1;
  44868. obj = JS_EvalObject(ctx, ctx->global_obj, s, JS_EVAL_TYPE_INDIRECT, -1);
  44869. JS_FreeValue(ctx, s);
  44870. if (JS_IsException(obj))
  44871. goto fail1;
  44872. if (!JS_IsUndefined(new_target)) {
  44873. /* set the prototype */
  44874. proto = JS_GetProperty(ctx, new_target, JS_ATOM_prototype);
  44875. if (JS_IsException(proto))
  44876. goto fail1;
  44877. if (!JS_IsObject(proto)) {
  44878. JSContext *realm;
  44879. JS_FreeValue(ctx, proto);
  44880. realm = JS_GetFunctionRealm(ctx, new_target);
  44881. if (!realm)
  44882. goto fail1;
  44883. proto = js_dup(realm->class_proto[func_kind_to_class_id[func_kind]]);
  44884. }
  44885. ret = JS_SetPrototypeInternal(ctx, obj, proto, true);
  44886. JS_FreeValue(ctx, proto);
  44887. if (ret < 0)
  44888. goto fail1;
  44889. }
  44890. return obj;
  44891. fail:
  44892. string_buffer_free(b);
  44893. fail1:
  44894. JS_FreeValue(ctx, obj);
  44895. return JS_EXCEPTION;
  44896. }
  44897. static __exception int js_get_length32(JSContext *ctx, uint32_t *pres,
  44898. JSValueConst obj)
  44899. {
  44900. JSValue len_val;
  44901. len_val = JS_GetProperty(ctx, obj, JS_ATOM_length);
  44902. if (JS_IsException(len_val)) {
  44903. *pres = 0;
  44904. return -1;
  44905. }
  44906. return JS_ToUint32Free(ctx, pres, len_val);
  44907. }
  44908. static __exception int js_get_length64(JSContext *ctx, int64_t *pres,
  44909. JSValueConst obj)
  44910. {
  44911. JSValue len_val;
  44912. len_val = JS_GetProperty(ctx, obj, JS_ATOM_length);
  44913. if (JS_IsException(len_val)) {
  44914. *pres = 0;
  44915. return -1;
  44916. }
  44917. return JS_ToLengthFree(ctx, pres, len_val);
  44918. }
  44919. static __exception int js_set_length64(JSContext *ctx, JSValueConst obj,
  44920. int64_t len)
  44921. {
  44922. return JS_SetProperty(ctx, obj, JS_ATOM_length, js_int64(len));
  44923. }
  44924. static void free_arg_list(JSContext *ctx, JSValue *tab, uint32_t len)
  44925. {
  44926. uint32_t i;
  44927. for(i = 0; i < len; i++) {
  44928. JS_FreeValue(ctx, tab[i]);
  44929. }
  44930. js_free(ctx, tab);
  44931. }
  44932. /* XXX: should use ValueArray */
  44933. static JSValue *build_arg_list(JSContext *ctx, uint32_t *plen,
  44934. JSValueConst array_arg)
  44935. {
  44936. uint32_t len, i;
  44937. JSValue *tab, ret;
  44938. JSObject *p;
  44939. if (JS_VALUE_GET_TAG(array_arg) != JS_TAG_OBJECT) {
  44940. JS_ThrowTypeError(ctx, "not a object");
  44941. return NULL;
  44942. }
  44943. if (js_get_length32(ctx, &len, array_arg))
  44944. return NULL;
  44945. if (len > JS_MAX_LOCAL_VARS) {
  44946. // XXX: check for stack overflow?
  44947. JS_ThrowRangeError(ctx, "too many arguments in function call (only %d allowed)",
  44948. JS_MAX_LOCAL_VARS);
  44949. return NULL;
  44950. }
  44951. /* avoid allocating 0 bytes */
  44952. tab = js_mallocz(ctx, sizeof(tab[0]) * max_uint32(1, len));
  44953. if (!tab)
  44954. return NULL;
  44955. p = JS_VALUE_GET_OBJ(array_arg);
  44956. if ((p->class_id == JS_CLASS_ARRAY || p->class_id == JS_CLASS_ARGUMENTS) &&
  44957. p->fast_array &&
  44958. len == p->u.array.count) {
  44959. for(i = 0; i < len; i++) {
  44960. tab[i] = js_dup(p->u.array.u.values[i]);
  44961. }
  44962. } else {
  44963. for(i = 0; i < len; i++) {
  44964. ret = JS_GetPropertyUint32(ctx, array_arg, i);
  44965. if (JS_IsException(ret)) {
  44966. free_arg_list(ctx, tab, i);
  44967. return NULL;
  44968. }
  44969. tab[i] = ret;
  44970. }
  44971. }
  44972. *plen = len;
  44973. return tab;
  44974. }
  44975. /* magic value: 0 = normal apply, 1 = apply for constructor, 2 =
  44976. Reflect.apply */
  44977. static JSValue js_function_apply(JSContext *ctx, JSValueConst this_val,
  44978. int argc, JSValueConst *argv, int magic)
  44979. {
  44980. JSValueConst this_arg, array_arg;
  44981. uint32_t len;
  44982. JSValue *tab, ret;
  44983. if (check_function(ctx, this_val))
  44984. return JS_EXCEPTION;
  44985. this_arg = argv[0];
  44986. array_arg = argv[1];
  44987. if ((JS_VALUE_GET_TAG(array_arg) == JS_TAG_UNDEFINED ||
  44988. JS_VALUE_GET_TAG(array_arg) == JS_TAG_NULL) && magic != 2) {
  44989. return JS_Call(ctx, this_val, this_arg, 0, NULL);
  44990. }
  44991. tab = build_arg_list(ctx, &len, array_arg);
  44992. if (!tab)
  44993. return JS_EXCEPTION;
  44994. if (magic & 1) {
  44995. ret = JS_CallConstructor2(ctx, this_val, this_arg, len, vc(tab));
  44996. } else {
  44997. ret = JS_Call(ctx, this_val, this_arg, len, vc(tab));
  44998. }
  44999. free_arg_list(ctx, tab, len);
  45000. return ret;
  45001. }
  45002. static JSValue js_function_call(JSContext *ctx, JSValueConst this_val,
  45003. int argc, JSValueConst *argv)
  45004. {
  45005. if (argc <= 0) {
  45006. return JS_Call(ctx, this_val, JS_UNDEFINED, 0, NULL);
  45007. } else {
  45008. return JS_Call(ctx, this_val, argv[0], argc - 1, argv + 1);
  45009. }
  45010. }
  45011. static JSValue js_function_bind(JSContext *ctx, JSValueConst this_val,
  45012. int argc, JSValueConst *argv)
  45013. {
  45014. JSBoundFunction *bf;
  45015. JSValue func_obj, name1, len_val;
  45016. JSObject *p;
  45017. int arg_count, i, ret;
  45018. if (check_function(ctx, this_val))
  45019. return JS_EXCEPTION;
  45020. func_obj = JS_NewObjectProtoClass(ctx, ctx->function_proto,
  45021. JS_CLASS_BOUND_FUNCTION);
  45022. if (JS_IsException(func_obj))
  45023. return JS_EXCEPTION;
  45024. p = JS_VALUE_GET_OBJ(func_obj);
  45025. p->is_constructor = JS_IsConstructor(ctx, this_val);
  45026. arg_count = max_int(0, argc - 1);
  45027. bf = js_malloc(ctx, sizeof(*bf) + arg_count * sizeof(JSValue));
  45028. if (!bf)
  45029. goto exception;
  45030. bf->func_obj = js_dup(this_val);
  45031. bf->this_val = js_dup(argv[0]);
  45032. bf->argc = arg_count;
  45033. for(i = 0; i < arg_count; i++) {
  45034. bf->argv[i] = js_dup(argv[i + 1]);
  45035. }
  45036. p->u.bound_function = bf;
  45037. /* XXX: the spec could be simpler by only using GetOwnProperty */
  45038. ret = JS_GetOwnProperty(ctx, NULL, this_val, JS_ATOM_length);
  45039. if (ret < 0)
  45040. goto exception;
  45041. if (!ret) {
  45042. len_val = js_int32(0);
  45043. } else {
  45044. len_val = JS_GetProperty(ctx, this_val, JS_ATOM_length);
  45045. if (JS_IsException(len_val))
  45046. goto exception;
  45047. if (JS_VALUE_GET_TAG(len_val) == JS_TAG_INT) {
  45048. /* most common case */
  45049. int len1 = JS_VALUE_GET_INT(len_val);
  45050. if (len1 <= arg_count)
  45051. len1 = 0;
  45052. else
  45053. len1 -= arg_count;
  45054. len_val = js_int32(len1);
  45055. } else if (JS_VALUE_GET_NORM_TAG(len_val) == JS_TAG_FLOAT64) {
  45056. double d = JS_VALUE_GET_FLOAT64(len_val);
  45057. if (isnan(d)) {
  45058. d = 0.0;
  45059. } else {
  45060. d = trunc(d);
  45061. if (d <= (double)arg_count)
  45062. d = 0.0;
  45063. else
  45064. d -= (double)arg_count; /* also converts -0 to +0 */
  45065. }
  45066. len_val = js_number(d);
  45067. } else {
  45068. JS_FreeValue(ctx, len_val);
  45069. len_val = js_int32(0);
  45070. }
  45071. }
  45072. JS_DefinePropertyValue(ctx, func_obj, JS_ATOM_length,
  45073. len_val, JS_PROP_CONFIGURABLE);
  45074. name1 = JS_GetProperty(ctx, this_val, JS_ATOM_name);
  45075. if (JS_IsException(name1))
  45076. goto exception;
  45077. if (!JS_IsString(name1)) {
  45078. JS_FreeValue(ctx, name1);
  45079. name1 = JS_AtomToString(ctx, JS_ATOM_empty_string);
  45080. }
  45081. name1 = JS_ConcatString3(ctx, "bound ", name1, "");
  45082. if (JS_IsException(name1))
  45083. goto exception;
  45084. JS_DefinePropertyValue(ctx, func_obj, JS_ATOM_name, name1,
  45085. JS_PROP_CONFIGURABLE);
  45086. return func_obj;
  45087. exception:
  45088. JS_FreeValue(ctx, func_obj);
  45089. return JS_EXCEPTION;
  45090. }
  45091. static JSValue js_function_toString(JSContext *ctx, JSValueConst this_val,
  45092. int argc, JSValueConst *argv)
  45093. {
  45094. JSObject *p;
  45095. JSFunctionKindEnum func_kind = JS_FUNC_NORMAL;
  45096. if (check_function(ctx, this_val))
  45097. return JS_EXCEPTION;
  45098. p = JS_VALUE_GET_OBJ(this_val);
  45099. if (js_class_has_bytecode(p->class_id)) {
  45100. JSFunctionBytecode *b = p->u.func.function_bytecode;
  45101. /* `b->source` must be pure ASCII or UTF-8 encoded */
  45102. if (b->source)
  45103. return JS_NewStringLen(ctx, b->source, b->source_len);
  45104. }
  45105. {
  45106. JSValue name;
  45107. const char *pref, *suff;
  45108. switch(func_kind) {
  45109. default:
  45110. case JS_FUNC_NORMAL:
  45111. pref = "function ";
  45112. break;
  45113. case JS_FUNC_GENERATOR:
  45114. pref = "function *";
  45115. break;
  45116. case JS_FUNC_ASYNC:
  45117. pref = "async function ";
  45118. break;
  45119. case JS_FUNC_ASYNC_GENERATOR:
  45120. pref = "async function *";
  45121. break;
  45122. }
  45123. suff = "() {\n [native code]\n}";
  45124. name = JS_GetProperty(ctx, this_val, JS_ATOM_name);
  45125. if (JS_IsUndefined(name))
  45126. name = JS_AtomToString(ctx, JS_ATOM_empty_string);
  45127. return JS_ConcatString3(ctx, pref, name, suff);
  45128. }
  45129. }
  45130. static JSValue js_function_hasInstance(JSContext *ctx, JSValueConst this_val,
  45131. int argc, JSValueConst *argv)
  45132. {
  45133. int ret;
  45134. ret = JS_OrdinaryIsInstanceOf(ctx, argv[0], this_val);
  45135. if (ret < 0)
  45136. return JS_EXCEPTION;
  45137. else
  45138. return js_bool(ret);
  45139. }
  45140. static const JSCFunctionListEntry js_function_proto_funcs[] = {
  45141. JS_CFUNC_DEF("call", 1, js_function_call ),
  45142. JS_CFUNC_MAGIC_DEF("apply", 2, js_function_apply, 0 ),
  45143. JS_CFUNC_DEF("bind", 1, js_function_bind ),
  45144. JS_CFUNC_DEF("toString", 0, js_function_toString ),
  45145. JS_CFUNC_DEF("[Symbol.hasInstance]", 1, js_function_hasInstance ),
  45146. JS_CGETSET_DEF("fileName", js_function_proto_fileName, NULL ),
  45147. JS_CGETSET_MAGIC_DEF("lineNumber", js_function_proto_int32, NULL,
  45148. offsetof(JSFunctionBytecode, line_num)),
  45149. JS_CGETSET_MAGIC_DEF("columnNumber", js_function_proto_int32, NULL,
  45150. offsetof(JSFunctionBytecode, col_num)),
  45151. };
  45152. /* Error class */
  45153. static JSValue iterator_to_array(JSContext *ctx, JSValueConst items)
  45154. {
  45155. JSValue iter, next_method = JS_UNDEFINED;
  45156. JSValue v, r = JS_UNDEFINED;
  45157. int64_t k;
  45158. int done;
  45159. iter = JS_GetIterator(ctx, items, false);
  45160. if (JS_IsException(iter))
  45161. goto exception;
  45162. next_method = JS_GetProperty(ctx, iter, JS_ATOM_next);
  45163. if (JS_IsException(next_method))
  45164. goto exception;
  45165. r = JS_NewArray(ctx);
  45166. if (JS_IsException(r))
  45167. goto exception;
  45168. for (k = 0;; k++) {
  45169. v = JS_IteratorNext(ctx, iter, next_method, 0, NULL, &done);
  45170. if (JS_IsException(v))
  45171. goto exception_close;
  45172. if (done)
  45173. break;
  45174. if (JS_DefinePropertyValueInt64(ctx, r, k, v,
  45175. JS_PROP_C_W_E | JS_PROP_THROW) < 0)
  45176. goto exception_close;
  45177. }
  45178. done:
  45179. JS_FreeValue(ctx, next_method);
  45180. JS_FreeValue(ctx, iter);
  45181. return r;
  45182. exception_close:
  45183. JS_IteratorClose(ctx, iter, true);
  45184. exception:
  45185. JS_FreeValue(ctx, r);
  45186. r = JS_EXCEPTION;
  45187. goto done;
  45188. }
  45189. static JSValue js_error_constructor(JSContext *ctx, JSValueConst new_target,
  45190. int argc, JSValueConst *argv, int magic)
  45191. {
  45192. JSValue obj, msg, proto, cause;
  45193. JSValueConst message;
  45194. int present, opts;
  45195. if (JS_IsUndefined(new_target))
  45196. new_target = JS_GetActiveFunction(ctx);
  45197. proto = JS_GetProperty(ctx, new_target, JS_ATOM_prototype);
  45198. if (JS_IsException(proto))
  45199. return proto;
  45200. if (!JS_IsObject(proto)) {
  45201. JSContext *realm;
  45202. JSValue proto1;
  45203. JS_FreeValue(ctx, proto);
  45204. realm = JS_GetFunctionRealm(ctx, new_target);
  45205. if (!realm)
  45206. return JS_EXCEPTION;
  45207. if (magic < 0) {
  45208. proto1 = realm->class_proto[JS_CLASS_ERROR];
  45209. } else {
  45210. proto1 = realm->native_error_proto[magic];
  45211. }
  45212. proto = js_dup(proto1);
  45213. }
  45214. obj = JS_NewObjectProtoClass(ctx, proto, JS_CLASS_ERROR);
  45215. JS_FreeValue(ctx, proto);
  45216. if (JS_IsException(obj))
  45217. return obj;
  45218. if (magic == JS_AGGREGATE_ERROR) {
  45219. message = argv[1];
  45220. opts = 2;
  45221. } else {
  45222. message = argv[0];
  45223. opts = 1;
  45224. }
  45225. if (!JS_IsUndefined(message)) {
  45226. msg = JS_ToString(ctx, message);
  45227. if (unlikely(JS_IsException(msg)))
  45228. goto exception;
  45229. JS_DefinePropertyValue(ctx, obj, JS_ATOM_message, msg,
  45230. JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);
  45231. }
  45232. if (argc > opts && JS_VALUE_GET_TAG(argv[opts]) == JS_TAG_OBJECT) {
  45233. present = JS_HasProperty(ctx, argv[opts], JS_ATOM_cause);
  45234. if (unlikely(present < 0))
  45235. goto exception;
  45236. if (present) {
  45237. cause = JS_GetProperty(ctx, argv[opts], JS_ATOM_cause);
  45238. if (unlikely(JS_IsException(cause)))
  45239. goto exception;
  45240. JS_DefinePropertyValue(ctx, obj, JS_ATOM_cause, cause,
  45241. JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);
  45242. }
  45243. }
  45244. if (magic == JS_AGGREGATE_ERROR) {
  45245. JSValue error_list = iterator_to_array(ctx, argv[0]);
  45246. if (JS_IsException(error_list))
  45247. goto exception;
  45248. JS_DefinePropertyValue(ctx, obj, JS_ATOM_errors, error_list,
  45249. JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);
  45250. }
  45251. /* skip the Error() function in the backtrace */
  45252. build_backtrace(ctx, obj, JS_UNDEFINED, NULL, 0, 0, JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL);
  45253. return obj;
  45254. exception:
  45255. JS_FreeValue(ctx, obj);
  45256. return JS_EXCEPTION;
  45257. }
  45258. static JSValue js_error_toString(JSContext *ctx, JSValueConst this_val,
  45259. int argc, JSValueConst *argv)
  45260. {
  45261. JSValue name, msg;
  45262. if (!JS_IsObject(this_val))
  45263. return JS_ThrowTypeErrorNotAnObject(ctx);
  45264. name = JS_GetProperty(ctx, this_val, JS_ATOM_name);
  45265. if (JS_IsUndefined(name))
  45266. name = JS_AtomToString(ctx, JS_ATOM_Error);
  45267. else
  45268. name = JS_ToStringFree(ctx, name);
  45269. if (JS_IsException(name))
  45270. return JS_EXCEPTION;
  45271. msg = JS_GetProperty(ctx, this_val, JS_ATOM_message);
  45272. if (JS_IsUndefined(msg))
  45273. msg = JS_AtomToString(ctx, JS_ATOM_empty_string);
  45274. else
  45275. msg = JS_ToStringFree(ctx, msg);
  45276. if (JS_IsException(msg)) {
  45277. JS_FreeValue(ctx, name);
  45278. return JS_EXCEPTION;
  45279. }
  45280. if (!JS_IsEmptyString(name) && !JS_IsEmptyString(msg))
  45281. name = JS_ConcatString3(ctx, "", name, ": ");
  45282. return JS_ConcatString(ctx, name, msg);
  45283. }
  45284. static const JSCFunctionListEntry js_error_proto_funcs[] = {
  45285. JS_CFUNC_DEF("toString", 0, js_error_toString ),
  45286. JS_PROP_STRING_DEF("name", "Error", JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE ),
  45287. JS_PROP_STRING_DEF("message", "", JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE ),
  45288. };
  45289. static JSValue js_error_isError(JSContext *ctx, JSValueConst this_val,
  45290. int argc, JSValueConst *argv)
  45291. {
  45292. return js_bool(JS_IsError(ctx, argv[0]));
  45293. }
  45294. static JSValue js_error_get_stackTraceLimit(JSContext *ctx, JSValueConst this_val)
  45295. {
  45296. JSValue val;
  45297. val = JS_ToObject(ctx, this_val);
  45298. if (JS_IsException(val))
  45299. return val;
  45300. JS_FreeValue(ctx, val);
  45301. return js_dup(ctx->error_stack_trace_limit);
  45302. }
  45303. static JSValue js_error_set_stackTraceLimit(JSContext *ctx, JSValueConst this_val, JSValueConst value)
  45304. {
  45305. if (JS_IsUndefined(this_val) || JS_IsNull(this_val))
  45306. return JS_ThrowTypeErrorNotAnObject(ctx);
  45307. ctx->error_stack_trace_limit = js_dup(value);
  45308. return JS_UNDEFINED;
  45309. }
  45310. static JSValue js_error_get_prepareStackTrace(JSContext *ctx, JSValueConst this_val)
  45311. {
  45312. JSValue val;
  45313. val = JS_ToObject(ctx, this_val);
  45314. if (JS_IsException(val))
  45315. return val;
  45316. JS_FreeValue(ctx, val);
  45317. return js_dup(ctx->error_prepare_stack);
  45318. }
  45319. static JSValue js_error_set_prepareStackTrace(JSContext *ctx, JSValueConst this_val, JSValueConst value)
  45320. {
  45321. if (JS_IsUndefined(this_val) || JS_IsNull(this_val))
  45322. return JS_ThrowTypeErrorNotAnObject(ctx);
  45323. JS_FreeValue(ctx, ctx->error_prepare_stack);
  45324. ctx->error_prepare_stack = js_dup(value);
  45325. return JS_UNDEFINED;
  45326. }
  45327. static JSValue js_error_capture_stack_trace(JSContext *ctx, JSValueConst this_val,
  45328. int argc, JSValueConst *argv)
  45329. {
  45330. JSValueConst v = argv[0];
  45331. if (JS_VALUE_GET_TAG(v) != JS_TAG_OBJECT)
  45332. return JS_ThrowTypeErrorNotAnObject(ctx);
  45333. build_backtrace(ctx, v, argv[1], NULL, 0, 0, JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL|JS_BACKTRACE_FLAG_FILTER_FUNC);
  45334. return JS_UNDEFINED;
  45335. }
  45336. static const JSCFunctionListEntry js_error_funcs[] = {
  45337. JS_CFUNC_DEF("isError", 1, js_error_isError ),
  45338. JS_CFUNC_DEF("captureStackTrace", 2, js_error_capture_stack_trace),
  45339. JS_CGETSET_DEF("stackTraceLimit", js_error_get_stackTraceLimit, js_error_set_stackTraceLimit ),
  45340. JS_CGETSET_DEF("prepareStackTrace", js_error_get_prepareStackTrace, js_error_set_prepareStackTrace ),
  45341. };
  45342. /* AggregateError */
  45343. /* used by C code. */
  45344. static JSValue js_aggregate_error_constructor(JSContext *ctx,
  45345. JSValueConst errors)
  45346. {
  45347. JSValue obj;
  45348. obj = JS_NewObjectProtoClass(ctx,
  45349. ctx->native_error_proto[JS_AGGREGATE_ERROR],
  45350. JS_CLASS_ERROR);
  45351. if (JS_IsException(obj))
  45352. return obj;
  45353. JS_DefinePropertyValue(ctx, obj, JS_ATOM_errors, js_dup(errors),
  45354. JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);
  45355. return obj;
  45356. }
  45357. /* Array */
  45358. static int JS_CopySubArray(JSContext *ctx,
  45359. JSValue obj, int64_t to_pos,
  45360. int64_t from_pos, int64_t count, int dir)
  45361. {
  45362. JSObject *p;
  45363. int64_t i, from, to, len;
  45364. JSValue val;
  45365. int fromPresent;
  45366. p = NULL;
  45367. if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) {
  45368. p = JS_VALUE_GET_OBJ(obj);
  45369. if (p->class_id != JS_CLASS_ARRAY || !p->fast_array) {
  45370. p = NULL;
  45371. }
  45372. }
  45373. for (i = 0; i < count; ) {
  45374. if (dir < 0) {
  45375. from = from_pos + count - i - 1;
  45376. to = to_pos + count - i - 1;
  45377. } else {
  45378. from = from_pos + i;
  45379. to = to_pos + i;
  45380. }
  45381. if (p && p->fast_array &&
  45382. from >= 0 && from < (len = p->u.array.count) &&
  45383. to >= 0 && to < len) {
  45384. int64_t l, j;
  45385. /* Fast path for fast arrays. Since we don't look at the
  45386. prototype chain, we can optimize only the cases where
  45387. all the elements are present in the array. */
  45388. l = count - i;
  45389. if (dir < 0) {
  45390. l = min_int64(l, from + 1);
  45391. l = min_int64(l, to + 1);
  45392. for(j = 0; j < l; j++) {
  45393. set_value(ctx, &p->u.array.u.values[to - j],
  45394. js_dup(p->u.array.u.values[from - j]));
  45395. }
  45396. } else {
  45397. l = min_int64(l, len - from);
  45398. l = min_int64(l, len - to);
  45399. for(j = 0; j < l; j++) {
  45400. set_value(ctx, &p->u.array.u.values[to + j],
  45401. js_dup(p->u.array.u.values[from + j]));
  45402. }
  45403. }
  45404. i += l;
  45405. } else {
  45406. fromPresent = JS_TryGetPropertyInt64(ctx, obj, from, &val);
  45407. if (fromPresent < 0)
  45408. goto exception;
  45409. if (fromPresent) {
  45410. if (JS_SetPropertyInt64(ctx, obj, to, val) < 0)
  45411. goto exception;
  45412. } else {
  45413. if (JS_DeletePropertyInt64(ctx, obj, to, JS_PROP_THROW) < 0)
  45414. goto exception;
  45415. }
  45416. i++;
  45417. }
  45418. }
  45419. return 0;
  45420. exception:
  45421. return -1;
  45422. }
  45423. static JSValue js_array_constructor(JSContext *ctx, JSValueConst new_target,
  45424. int argc, JSValueConst *argv)
  45425. {
  45426. JSValue obj;
  45427. int i;
  45428. obj = js_create_from_ctor(ctx, new_target, JS_CLASS_ARRAY);
  45429. if (JS_IsException(obj))
  45430. return obj;
  45431. if (argc == 1 && JS_IsNumber(argv[0])) {
  45432. uint32_t len;
  45433. if (JS_ToArrayLengthFree(ctx, &len, js_dup(argv[0]), true))
  45434. goto fail;
  45435. if (JS_SetProperty(ctx, obj, JS_ATOM_length, js_uint32(len)) < 0)
  45436. goto fail;
  45437. } else {
  45438. for(i = 0; i < argc; i++) {
  45439. if (JS_SetPropertyUint32(ctx, obj, i, js_dup(argv[i])) < 0)
  45440. goto fail;
  45441. }
  45442. }
  45443. return obj;
  45444. fail:
  45445. JS_FreeValue(ctx, obj);
  45446. return JS_EXCEPTION;
  45447. }
  45448. static JSValue js_array_from(JSContext *ctx, JSValueConst this_val,
  45449. int argc, JSValueConst *argv)
  45450. {
  45451. // from(items, mapfn = void 0, this_arg = void 0)
  45452. JSValueConst items = argv[0], mapfn, this_arg;
  45453. JSValueConst args[2];
  45454. JSValue stack[2];
  45455. JSValue iter, r, v, v2, arrayLike;
  45456. int64_t k, len;
  45457. int done, mapping;
  45458. mapping = false;
  45459. mapfn = JS_UNDEFINED;
  45460. this_arg = JS_UNDEFINED;
  45461. r = JS_UNDEFINED;
  45462. arrayLike = JS_UNDEFINED;
  45463. stack[0] = JS_UNDEFINED;
  45464. stack[1] = JS_UNDEFINED;
  45465. if (argc > 1) {
  45466. mapfn = argv[1];
  45467. if (!JS_IsUndefined(mapfn)) {
  45468. if (check_function(ctx, mapfn))
  45469. goto exception;
  45470. mapping = 1;
  45471. if (argc > 2)
  45472. this_arg = argv[2];
  45473. }
  45474. }
  45475. iter = JS_GetProperty(ctx, items, JS_ATOM_Symbol_iterator);
  45476. if (JS_IsException(iter))
  45477. goto exception;
  45478. if (!JS_IsUndefined(iter)) {
  45479. JS_FreeValue(ctx, iter);
  45480. if (JS_IsConstructor(ctx, this_val))
  45481. r = JS_CallConstructor(ctx, this_val, 0, NULL);
  45482. else
  45483. r = JS_NewArray(ctx);
  45484. if (JS_IsException(r))
  45485. goto exception;
  45486. stack[0] = js_dup(items);
  45487. if (js_for_of_start(ctx, &stack[1], false))
  45488. goto exception;
  45489. for (k = 0;; k++) {
  45490. v = JS_IteratorNext(ctx, stack[0], stack[1], 0, NULL, &done);
  45491. if (JS_IsException(v))
  45492. goto exception_close;
  45493. if (done)
  45494. break;
  45495. if (mapping) {
  45496. args[0] = v;
  45497. args[1] = js_int32(k);
  45498. v2 = JS_Call(ctx, mapfn, this_arg, 2, args);
  45499. JS_FreeValue(ctx, v);
  45500. v = v2;
  45501. if (JS_IsException(v))
  45502. goto exception_close;
  45503. }
  45504. if (JS_DefinePropertyValueInt64(ctx, r, k, v,
  45505. JS_PROP_C_W_E | JS_PROP_THROW) < 0)
  45506. goto exception_close;
  45507. }
  45508. } else {
  45509. arrayLike = JS_ToObject(ctx, items);
  45510. if (JS_IsException(arrayLike))
  45511. goto exception;
  45512. if (js_get_length64(ctx, &len, arrayLike) < 0)
  45513. goto exception;
  45514. v = js_int64(len);
  45515. args[0] = v;
  45516. if (JS_IsConstructor(ctx, this_val)) {
  45517. r = JS_CallConstructor(ctx, this_val, 1, args);
  45518. } else {
  45519. r = js_array_constructor(ctx, JS_UNDEFINED, 1, args);
  45520. }
  45521. JS_FreeValue(ctx, v);
  45522. if (JS_IsException(r))
  45523. goto exception;
  45524. for(k = 0; k < len; k++) {
  45525. v = JS_GetPropertyInt64(ctx, arrayLike, k);
  45526. if (JS_IsException(v))
  45527. goto exception;
  45528. if (mapping) {
  45529. args[0] = v;
  45530. args[1] = js_int32(k);
  45531. v2 = JS_Call(ctx, mapfn, this_arg, 2, args);
  45532. JS_FreeValue(ctx, v);
  45533. v = v2;
  45534. if (JS_IsException(v))
  45535. goto exception;
  45536. }
  45537. if (JS_DefinePropertyValueInt64(ctx, r, k, v,
  45538. JS_PROP_C_W_E | JS_PROP_THROW) < 0)
  45539. goto exception;
  45540. }
  45541. }
  45542. if (JS_SetProperty(ctx, r, JS_ATOM_length, js_uint32(k)) < 0)
  45543. goto exception;
  45544. goto done;
  45545. exception_close:
  45546. if (!JS_IsUndefined(stack[0]))
  45547. JS_IteratorClose(ctx, stack[0], true);
  45548. exception:
  45549. JS_FreeValue(ctx, r);
  45550. r = JS_EXCEPTION;
  45551. done:
  45552. JS_FreeValue(ctx, arrayLike);
  45553. JS_FreeValue(ctx, stack[0]);
  45554. JS_FreeValue(ctx, stack[1]);
  45555. return r;
  45556. }
  45557. static JSValue js_array_of(JSContext *ctx, JSValueConst this_val,
  45558. int argc, JSValueConst *argv)
  45559. {
  45560. JSValue n, obj;
  45561. int i;
  45562. if (JS_IsConstructor(ctx, this_val)) {
  45563. n = js_int32(argc);
  45564. obj = JS_CallConstructor(ctx, this_val, 1, vc(&n));
  45565. } else {
  45566. obj = JS_NewArray(ctx);
  45567. }
  45568. if (JS_IsException(obj))
  45569. return JS_EXCEPTION;
  45570. for(i = 0; i < argc; i++) {
  45571. if (JS_CreateDataPropertyUint32(ctx, obj, i, js_dup(argv[i]),
  45572. JS_PROP_THROW) < 0) {
  45573. goto fail;
  45574. }
  45575. }
  45576. if (JS_SetProperty(ctx, obj, JS_ATOM_length, js_uint32(argc)) < 0) {
  45577. fail:
  45578. JS_FreeValue(ctx, obj);
  45579. return JS_EXCEPTION;
  45580. }
  45581. return obj;
  45582. }
  45583. static JSValue js_array_isArray(JSContext *ctx, JSValueConst this_val,
  45584. int argc, JSValueConst *argv)
  45585. {
  45586. int ret;
  45587. ret = js_is_array(ctx, argv[0]);
  45588. if (ret < 0)
  45589. return JS_EXCEPTION;
  45590. else
  45591. return js_bool(ret);
  45592. }
  45593. static JSValue js_get_this(JSContext *ctx, JSValueConst this_val)
  45594. {
  45595. return js_dup(this_val);
  45596. }
  45597. static JSValue JS_ArraySpeciesCreate(JSContext *ctx, JSValueConst obj,
  45598. JSValueConst len_val)
  45599. {
  45600. JSValue ctor, ret, species;
  45601. int res;
  45602. JSContext *realm;
  45603. res = js_is_array(ctx, obj);
  45604. if (res < 0)
  45605. return JS_EXCEPTION;
  45606. if (!res)
  45607. return js_array_constructor(ctx, JS_UNDEFINED, 1, &len_val);
  45608. ctor = JS_GetProperty(ctx, obj, JS_ATOM_constructor);
  45609. if (JS_IsException(ctor))
  45610. return ctor;
  45611. if (JS_IsConstructor(ctx, ctor)) {
  45612. /* legacy web compatibility */
  45613. realm = JS_GetFunctionRealm(ctx, ctor);
  45614. if (!realm) {
  45615. JS_FreeValue(ctx, ctor);
  45616. return JS_EXCEPTION;
  45617. }
  45618. if (realm != ctx &&
  45619. js_same_value(ctx, ctor, realm->array_ctor)) {
  45620. JS_FreeValue(ctx, ctor);
  45621. ctor = JS_UNDEFINED;
  45622. }
  45623. }
  45624. if (JS_IsObject(ctor)) {
  45625. species = JS_GetProperty(ctx, ctor, JS_ATOM_Symbol_species);
  45626. JS_FreeValue(ctx, ctor);
  45627. if (JS_IsException(species))
  45628. return species;
  45629. ctor = species;
  45630. if (JS_IsNull(ctor))
  45631. ctor = JS_UNDEFINED;
  45632. }
  45633. if (JS_IsUndefined(ctor)) {
  45634. return js_array_constructor(ctx, JS_UNDEFINED, 1, &len_val);
  45635. } else {
  45636. ret = JS_CallConstructor(ctx, ctor, 1, &len_val);
  45637. JS_FreeValue(ctx, ctor);
  45638. return ret;
  45639. }
  45640. }
  45641. static const JSCFunctionListEntry js_array_funcs[] = {
  45642. JS_CFUNC_DEF("isArray", 1, js_array_isArray ),
  45643. JS_CFUNC_DEF("from", 1, js_array_from ),
  45644. JS_CFUNC_DEF("of", 0, js_array_of ),
  45645. JS_CGETSET_DEF("[Symbol.species]", js_get_this, NULL ),
  45646. };
  45647. static int JS_isConcatSpreadable(JSContext *ctx, JSValueConst obj)
  45648. {
  45649. JSValue val;
  45650. if (!JS_IsObject(obj))
  45651. return false;
  45652. val = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_isConcatSpreadable);
  45653. if (JS_IsException(val))
  45654. return -1;
  45655. if (!JS_IsUndefined(val))
  45656. return JS_ToBoolFree(ctx, val);
  45657. return js_is_array(ctx, obj);
  45658. }
  45659. static JSValue js_array_at(JSContext *ctx, JSValueConst this_val,
  45660. int argc, JSValueConst *argv)
  45661. {
  45662. JSValue obj, ret;
  45663. int64_t len, idx;
  45664. ret = JS_EXCEPTION;
  45665. obj = JS_ToObject(ctx, this_val);
  45666. if (js_get_length64(ctx, &len, obj))
  45667. goto exception;
  45668. if (JS_ToInt64Sat(ctx, &idx, argv[0]))
  45669. goto exception;
  45670. if (idx < 0)
  45671. idx = len + idx;
  45672. if (idx < 0 || idx >= len) {
  45673. ret = JS_UNDEFINED;
  45674. } else {
  45675. ret = JS_GetPropertyInt64(ctx, obj, idx);
  45676. }
  45677. exception:
  45678. JS_FreeValue(ctx, obj);
  45679. return ret;
  45680. }
  45681. static JSValue js_array_with(JSContext *ctx, JSValueConst this_val,
  45682. int argc, JSValueConst *argv)
  45683. {
  45684. JSValue arr, obj, ret, *arrp, *pval;
  45685. JSObject *p;
  45686. int64_t i, len, idx;
  45687. uint32_t count32;
  45688. ret = JS_EXCEPTION;
  45689. arr = JS_UNDEFINED;
  45690. obj = JS_ToObject(ctx, this_val);
  45691. if (js_get_length64(ctx, &len, obj))
  45692. goto exception;
  45693. if (len > UINT32_MAX) {
  45694. JS_ThrowRangeError(ctx, "invalid array length");
  45695. goto exception;
  45696. }
  45697. if (JS_ToInt64Sat(ctx, &idx, argv[0]))
  45698. goto exception;
  45699. if (idx < 0)
  45700. idx = len + idx;
  45701. if (idx < 0 || idx >= len) {
  45702. JS_ThrowRangeError(ctx, "invalid array index: %" PRId64, idx);
  45703. goto exception;
  45704. }
  45705. arr = JS_NewArray(ctx);
  45706. if (JS_IsException(arr))
  45707. goto exception;
  45708. p = JS_VALUE_GET_OBJ(arr);
  45709. if (expand_fast_array(ctx, p, len) < 0)
  45710. goto exception;
  45711. p->u.array.count = len;
  45712. i = 0;
  45713. pval = p->u.array.u.values;
  45714. if (js_get_fast_array(ctx, obj, &arrp, &count32) && count32 == len) {
  45715. for (; i < idx; i++, pval++)
  45716. *pval = js_dup(arrp[i]);
  45717. *pval = js_dup(argv[1]);
  45718. for (i++, pval++; i < len; i++, pval++)
  45719. *pval = js_dup(arrp[i]);
  45720. } else {
  45721. for (; i < idx; i++, pval++)
  45722. if (-1 == JS_TryGetPropertyInt64(ctx, obj, i, pval))
  45723. goto fill_and_fail;
  45724. *pval = js_dup(argv[1]);
  45725. for (i++, pval++; i < len; i++, pval++) {
  45726. if (-1 == JS_TryGetPropertyInt64(ctx, obj, i, pval)) {
  45727. fill_and_fail:
  45728. for (; i < len; i++, pval++)
  45729. *pval = JS_UNDEFINED;
  45730. goto exception;
  45731. }
  45732. }
  45733. }
  45734. if (JS_SetProperty(ctx, arr, JS_ATOM_length, js_int64(len)) < 0)
  45735. goto exception;
  45736. ret = arr;
  45737. arr = JS_UNDEFINED;
  45738. exception:
  45739. JS_FreeValue(ctx, arr);
  45740. JS_FreeValue(ctx, obj);
  45741. return ret;
  45742. }
  45743. static JSValue js_array_concat(JSContext *ctx, JSValueConst this_val,
  45744. int argc, JSValueConst *argv)
  45745. {
  45746. JSValue obj, arr, val;
  45747. JSValueConst e;
  45748. int64_t len, k, n;
  45749. int i, res;
  45750. arr = JS_UNDEFINED;
  45751. obj = JS_ToObject(ctx, this_val);
  45752. if (JS_IsException(obj))
  45753. goto exception;
  45754. arr = JS_ArraySpeciesCreate(ctx, obj, js_int32(0));
  45755. if (JS_IsException(arr))
  45756. goto exception;
  45757. n = 0;
  45758. for (i = -1; i < argc; i++) {
  45759. if (i < 0)
  45760. e = obj;
  45761. else
  45762. e = argv[i];
  45763. res = JS_isConcatSpreadable(ctx, e);
  45764. if (res < 0)
  45765. goto exception;
  45766. if (res) {
  45767. if (js_get_length64(ctx, &len, e))
  45768. goto exception;
  45769. if (n + len > MAX_SAFE_INTEGER) {
  45770. JS_ThrowTypeError(ctx, "Array loo long");
  45771. goto exception;
  45772. }
  45773. for (k = 0; k < len; k++, n++) {
  45774. res = JS_TryGetPropertyInt64(ctx, e, k, &val);
  45775. if (res < 0)
  45776. goto exception;
  45777. if (res) {
  45778. if (JS_DefinePropertyValueInt64(ctx, arr, n, val,
  45779. JS_PROP_C_W_E | JS_PROP_THROW) < 0)
  45780. goto exception;
  45781. }
  45782. }
  45783. } else {
  45784. if (n >= MAX_SAFE_INTEGER) {
  45785. JS_ThrowTypeError(ctx, "Array loo long");
  45786. goto exception;
  45787. }
  45788. if (JS_DefinePropertyValueInt64(ctx, arr, n, js_dup(e),
  45789. JS_PROP_C_W_E | JS_PROP_THROW) < 0)
  45790. goto exception;
  45791. n++;
  45792. }
  45793. }
  45794. if (JS_SetProperty(ctx, arr, JS_ATOM_length, js_int64(n)) < 0)
  45795. goto exception;
  45796. JS_FreeValue(ctx, obj);
  45797. return arr;
  45798. exception:
  45799. JS_FreeValue(ctx, arr);
  45800. JS_FreeValue(ctx, obj);
  45801. return JS_EXCEPTION;
  45802. }
  45803. #define special_every 0
  45804. #define special_some 1
  45805. #define special_forEach 2
  45806. #define special_map 3
  45807. #define special_filter 4
  45808. #define special_TA 8
  45809. static JSObject *get_typed_array(JSContext *ctx, JSValueConst this_val)
  45810. {
  45811. JSObject *p;
  45812. if (JS_VALUE_GET_TAG(this_val) != JS_TAG_OBJECT)
  45813. goto fail;
  45814. p = JS_VALUE_GET_OBJ(this_val);
  45815. if (!is_typed_array(p->class_id)) {
  45816. fail:
  45817. JS_ThrowTypeError(ctx, "not a TypedArray");
  45818. return NULL;
  45819. }
  45820. return p;
  45821. }
  45822. // Be *very* careful if you touch the typed array's memory directly:
  45823. // the length is only valid until the next call into JS land because
  45824. // JS code can detach or resize the backing array buffer. Functions
  45825. // like JS_GetProperty and JS_ToIndex call JS code.
  45826. //
  45827. // Exclusively reading or writing elements with JS_GetProperty,
  45828. // JS_GetPropertyInt64, JS_SetProperty, etc. is safe because they
  45829. // perform bounds checks, as does js_get_fast_array_element.
  45830. static int js_typed_array_get_length_unsafe(JSContext *ctx, JSValueConst obj)
  45831. {
  45832. JSObject *p;
  45833. p = get_typed_array(ctx, obj);
  45834. if (!p)
  45835. return -1;
  45836. if (typed_array_is_oob(p)) {
  45837. JS_ThrowTypeErrorArrayBufferOOB(ctx);
  45838. return -1;
  45839. }
  45840. return p->u.array.count;
  45841. }
  45842. static JSValue js_typed_array___speciesCreate(JSContext *ctx,
  45843. JSValueConst this_val,
  45844. int argc, JSValueConst *argv);
  45845. static JSValue js_array_every(JSContext *ctx, JSValueConst this_val,
  45846. int argc, JSValueConst *argv, int special)
  45847. {
  45848. JSValue obj, val, index_val, res, ret;
  45849. JSValueConst args[3];
  45850. JSValueConst func, this_arg;
  45851. int64_t len, k, n;
  45852. int present;
  45853. ret = JS_UNDEFINED;
  45854. val = JS_UNDEFINED;
  45855. if (special & special_TA) {
  45856. obj = js_dup(this_val);
  45857. len = js_typed_array_get_length_unsafe(ctx, obj);
  45858. if (len < 0)
  45859. goto exception;
  45860. } else {
  45861. obj = JS_ToObject(ctx, this_val);
  45862. if (js_get_length64(ctx, &len, obj))
  45863. goto exception;
  45864. }
  45865. func = argv[0];
  45866. this_arg = JS_UNDEFINED;
  45867. if (argc > 1)
  45868. this_arg = argv[1];
  45869. if (check_function(ctx, func))
  45870. goto exception;
  45871. switch (special) {
  45872. case special_every:
  45873. case special_every | special_TA:
  45874. ret = JS_TRUE;
  45875. break;
  45876. case special_some:
  45877. case special_some | special_TA:
  45878. ret = JS_FALSE;
  45879. break;
  45880. case special_map:
  45881. /* XXX: JS_ArraySpeciesCreate should take int64_t */
  45882. ret = JS_ArraySpeciesCreate(ctx, obj, js_int64(len));
  45883. if (JS_IsException(ret))
  45884. goto exception;
  45885. break;
  45886. case special_filter:
  45887. ret = JS_ArraySpeciesCreate(ctx, obj, js_int32(0));
  45888. if (JS_IsException(ret))
  45889. goto exception;
  45890. break;
  45891. case special_map | special_TA:
  45892. args[0] = obj;
  45893. args[1] = js_int32(len);
  45894. ret = js_typed_array___speciesCreate(ctx, JS_UNDEFINED, 2, args);
  45895. if (JS_IsException(ret))
  45896. goto exception;
  45897. break;
  45898. case special_filter | special_TA:
  45899. ret = JS_NewArray(ctx);
  45900. if (JS_IsException(ret))
  45901. goto exception;
  45902. break;
  45903. }
  45904. n = 0;
  45905. for(k = 0; k < len; k++) {
  45906. if (special & special_TA) {
  45907. val = JS_GetPropertyInt64(ctx, obj, k);
  45908. if (JS_IsException(val))
  45909. goto exception;
  45910. present = true;
  45911. } else {
  45912. present = JS_TryGetPropertyInt64(ctx, obj, k, &val);
  45913. if (present < 0)
  45914. goto exception;
  45915. }
  45916. if (present) {
  45917. index_val = js_int64(k);
  45918. args[0] = val;
  45919. args[1] = index_val;
  45920. args[2] = obj;
  45921. res = JS_Call(ctx, func, this_arg, 3, args);
  45922. JS_FreeValue(ctx, index_val);
  45923. if (JS_IsException(res))
  45924. goto exception;
  45925. switch (special) {
  45926. case special_every:
  45927. case special_every | special_TA:
  45928. if (!JS_ToBoolFree(ctx, res)) {
  45929. ret = JS_FALSE;
  45930. goto done;
  45931. }
  45932. break;
  45933. case special_some:
  45934. case special_some | special_TA:
  45935. if (JS_ToBoolFree(ctx, res)) {
  45936. ret = JS_TRUE;
  45937. goto done;
  45938. }
  45939. break;
  45940. case special_map:
  45941. if (JS_DefinePropertyValueInt64(ctx, ret, k, res,
  45942. JS_PROP_C_W_E | JS_PROP_THROW) < 0)
  45943. goto exception;
  45944. break;
  45945. case special_map | special_TA:
  45946. if (JS_SetPropertyValue(ctx, ret, js_int32(k), res, JS_PROP_THROW) < 0)
  45947. goto exception;
  45948. break;
  45949. case special_filter:
  45950. case special_filter | special_TA:
  45951. if (JS_ToBoolFree(ctx, res)) {
  45952. if (JS_DefinePropertyValueInt64(ctx, ret, n++, js_dup(val),
  45953. JS_PROP_C_W_E | JS_PROP_THROW) < 0)
  45954. goto exception;
  45955. }
  45956. break;
  45957. default:
  45958. JS_FreeValue(ctx, res);
  45959. break;
  45960. }
  45961. JS_FreeValue(ctx, val);
  45962. val = JS_UNDEFINED;
  45963. }
  45964. }
  45965. done:
  45966. if (special == (special_filter | special_TA)) {
  45967. JSValue arr;
  45968. args[0] = obj;
  45969. args[1] = js_int32(n);
  45970. arr = js_typed_array___speciesCreate(ctx, JS_UNDEFINED, 2, args);
  45971. if (JS_IsException(arr))
  45972. goto exception;
  45973. args[0] = ret;
  45974. res = JS_Invoke(ctx, arr, JS_ATOM_set, 1, args);
  45975. if (check_exception_free(ctx, res))
  45976. goto exception;
  45977. JS_FreeValue(ctx, ret);
  45978. ret = arr;
  45979. }
  45980. JS_FreeValue(ctx, val);
  45981. JS_FreeValue(ctx, obj);
  45982. return ret;
  45983. exception:
  45984. JS_FreeValue(ctx, ret);
  45985. JS_FreeValue(ctx, val);
  45986. JS_FreeValue(ctx, obj);
  45987. return JS_EXCEPTION;
  45988. }
  45989. #define special_reduce 0
  45990. #define special_reduceRight 1
  45991. static JSValue js_array_reduce(JSContext *ctx, JSValueConst this_val,
  45992. int argc, JSValueConst *argv, int special)
  45993. {
  45994. JSValue obj, val, index_val, acc, acc1;
  45995. JSValueConst args[4];
  45996. JSValueConst func;
  45997. int64_t len, k, k1;
  45998. int present;
  45999. acc = JS_UNDEFINED;
  46000. val = JS_UNDEFINED;
  46001. if (special & special_TA) {
  46002. obj = js_dup(this_val);
  46003. len = js_typed_array_get_length_unsafe(ctx, obj);
  46004. if (len < 0)
  46005. goto exception;
  46006. } else {
  46007. obj = JS_ToObject(ctx, this_val);
  46008. if (js_get_length64(ctx, &len, obj))
  46009. goto exception;
  46010. }
  46011. func = argv[0];
  46012. if (check_function(ctx, func))
  46013. goto exception;
  46014. k = 0;
  46015. if (argc > 1) {
  46016. acc = js_dup(argv[1]);
  46017. } else {
  46018. for(;;) {
  46019. if (k >= len) {
  46020. JS_ThrowTypeError(ctx, "empty array");
  46021. goto exception;
  46022. }
  46023. k1 = (special & special_reduceRight) ? len - k - 1 : k;
  46024. k++;
  46025. if (special & special_TA) {
  46026. acc = JS_GetPropertyInt64(ctx, obj, k1);
  46027. if (JS_IsException(acc))
  46028. goto exception;
  46029. break;
  46030. } else {
  46031. present = JS_TryGetPropertyInt64(ctx, obj, k1, &acc);
  46032. if (present < 0)
  46033. goto exception;
  46034. if (present)
  46035. break;
  46036. }
  46037. }
  46038. }
  46039. for (; k < len; k++) {
  46040. k1 = (special & special_reduceRight) ? len - k - 1 : k;
  46041. if (special & special_TA) {
  46042. val = JS_GetPropertyInt64(ctx, obj, k1);
  46043. if (JS_IsException(val))
  46044. goto exception;
  46045. present = true;
  46046. } else {
  46047. present = JS_TryGetPropertyInt64(ctx, obj, k1, &val);
  46048. if (present < 0)
  46049. goto exception;
  46050. }
  46051. if (present) {
  46052. index_val = js_int64(k1);
  46053. args[0] = acc;
  46054. args[1] = val;
  46055. args[2] = index_val;
  46056. args[3] = obj;
  46057. acc1 = JS_Call(ctx, func, JS_UNDEFINED, 4, args);
  46058. JS_FreeValue(ctx, index_val);
  46059. JS_FreeValue(ctx, val);
  46060. val = JS_UNDEFINED;
  46061. if (JS_IsException(acc1))
  46062. goto exception;
  46063. JS_FreeValue(ctx, acc);
  46064. acc = acc1;
  46065. }
  46066. }
  46067. JS_FreeValue(ctx, obj);
  46068. return acc;
  46069. exception:
  46070. JS_FreeValue(ctx, acc);
  46071. JS_FreeValue(ctx, val);
  46072. JS_FreeValue(ctx, obj);
  46073. return JS_EXCEPTION;
  46074. }
  46075. static JSValue js_array_fill(JSContext *ctx, JSValueConst this_val,
  46076. int argc, JSValueConst *argv)
  46077. {
  46078. JSValue obj;
  46079. int64_t len, start, end;
  46080. obj = JS_ToObject(ctx, this_val);
  46081. if (js_get_length64(ctx, &len, obj))
  46082. goto exception;
  46083. start = 0;
  46084. if (argc > 1 && !JS_IsUndefined(argv[1])) {
  46085. if (JS_ToInt64Clamp(ctx, &start, argv[1], 0, len, len))
  46086. goto exception;
  46087. }
  46088. end = len;
  46089. if (argc > 2 && !JS_IsUndefined(argv[2])) {
  46090. if (JS_ToInt64Clamp(ctx, &end, argv[2], 0, len, len))
  46091. goto exception;
  46092. }
  46093. /* XXX: should special case fast arrays */
  46094. while (start < end) {
  46095. if (JS_SetPropertyInt64(ctx, obj, start, js_dup(argv[0])) < 0)
  46096. goto exception;
  46097. start++;
  46098. }
  46099. return obj;
  46100. exception:
  46101. JS_FreeValue(ctx, obj);
  46102. return JS_EXCEPTION;
  46103. }
  46104. static JSValue js_array_includes(JSContext *ctx, JSValueConst this_val,
  46105. int argc, JSValueConst *argv)
  46106. {
  46107. JSValue obj, val;
  46108. int64_t len, n;
  46109. JSValue *arrp;
  46110. uint32_t count;
  46111. int res;
  46112. obj = JS_ToObject(ctx, this_val);
  46113. if (js_get_length64(ctx, &len, obj))
  46114. goto exception;
  46115. res = true;
  46116. if (len > 0) {
  46117. n = 0;
  46118. if (argc > 1) {
  46119. if (JS_ToInt64Clamp(ctx, &n, argv[1], 0, len, len))
  46120. goto exception;
  46121. }
  46122. if (js_get_fast_array(ctx, obj, &arrp, &count)) {
  46123. for (; n < count; n++) {
  46124. if (js_strict_eq2(ctx, js_dup(argv[0]), js_dup(arrp[n]),
  46125. JS_EQ_SAME_VALUE_ZERO)) {
  46126. goto done;
  46127. }
  46128. }
  46129. }
  46130. for (; n < len; n++) {
  46131. val = JS_GetPropertyInt64(ctx, obj, n);
  46132. if (JS_IsException(val))
  46133. goto exception;
  46134. if (js_strict_eq2(ctx, js_dup(argv[0]), val,
  46135. JS_EQ_SAME_VALUE_ZERO)) {
  46136. goto done;
  46137. }
  46138. }
  46139. }
  46140. res = false;
  46141. done:
  46142. JS_FreeValue(ctx, obj);
  46143. return js_bool(res);
  46144. exception:
  46145. JS_FreeValue(ctx, obj);
  46146. return JS_EXCEPTION;
  46147. }
  46148. static JSValue js_array_indexOf(JSContext *ctx, JSValueConst this_val,
  46149. int argc, JSValueConst *argv)
  46150. {
  46151. JSValue obj, val;
  46152. int64_t len, n;
  46153. JSValue *arrp;
  46154. uint32_t count;
  46155. obj = JS_ToObject(ctx, this_val);
  46156. if (js_get_length64(ctx, &len, obj))
  46157. goto exception;
  46158. if (len > 0) {
  46159. n = 0;
  46160. if (argc > 1) {
  46161. if (JS_ToInt64Clamp(ctx, &n, argv[1], 0, len, len))
  46162. goto exception;
  46163. }
  46164. if (js_get_fast_array(ctx, obj, &arrp, &count)) {
  46165. for (; n < count; n++) {
  46166. if (js_strict_eq2(ctx, js_dup(argv[0]), js_dup(arrp[n]),
  46167. JS_EQ_STRICT)) {
  46168. goto done;
  46169. }
  46170. }
  46171. }
  46172. for (; n < len; n++) {
  46173. int present = JS_TryGetPropertyInt64(ctx, obj, n, &val);
  46174. if (present < 0)
  46175. goto exception;
  46176. if (present) {
  46177. if (js_strict_eq2(ctx, js_dup(argv[0]), val, JS_EQ_STRICT)) {
  46178. goto done;
  46179. }
  46180. }
  46181. }
  46182. }
  46183. n = -1;
  46184. done:
  46185. JS_FreeValue(ctx, obj);
  46186. return js_int64(n);
  46187. exception:
  46188. JS_FreeValue(ctx, obj);
  46189. return JS_EXCEPTION;
  46190. }
  46191. static JSValue js_array_lastIndexOf(JSContext *ctx, JSValueConst this_val,
  46192. int argc, JSValueConst *argv)
  46193. {
  46194. JSValue obj, val;
  46195. int64_t len, n;
  46196. JSValue *arrp;
  46197. uint32_t count;
  46198. obj = JS_ToObject(ctx, this_val);
  46199. if (js_get_length64(ctx, &len, obj))
  46200. goto exception;
  46201. if (len > 0) {
  46202. n = len - 1;
  46203. if (argc > 1) {
  46204. if (JS_ToInt64Clamp(ctx, &n, argv[1], -1, len - 1, len))
  46205. goto exception;
  46206. }
  46207. if (js_get_fast_array(ctx, obj, &arrp, &count) && count == len) {
  46208. for (; n >= 0; n--) {
  46209. if (js_strict_eq2(ctx, js_dup(argv[0]), js_dup(arrp[n]),
  46210. JS_EQ_STRICT)) {
  46211. goto done;
  46212. }
  46213. }
  46214. }
  46215. for (; n >= 0; n--) {
  46216. int present = JS_TryGetPropertyInt64(ctx, obj, n, &val);
  46217. if (present < 0)
  46218. goto exception;
  46219. if (present) {
  46220. if (js_strict_eq2(ctx, js_dup(argv[0]), val, JS_EQ_STRICT)) {
  46221. goto done;
  46222. }
  46223. }
  46224. }
  46225. }
  46226. n = -1;
  46227. done:
  46228. JS_FreeValue(ctx, obj);
  46229. return js_int64(n);
  46230. exception:
  46231. JS_FreeValue(ctx, obj);
  46232. return JS_EXCEPTION;
  46233. }
  46234. enum {
  46235. ArrayFind,
  46236. ArrayFindIndex,
  46237. ArrayFindLast,
  46238. ArrayFindLastIndex,
  46239. };
  46240. static JSValue js_array_find(JSContext *ctx, JSValueConst this_val,
  46241. int argc, JSValueConst *argv, int mode)
  46242. {
  46243. JSValueConst func, this_arg;
  46244. JSValueConst args[3];
  46245. JSValue obj, val, index_val, res;
  46246. int64_t len, k, end;
  46247. int dir;
  46248. index_val = JS_UNDEFINED;
  46249. val = JS_UNDEFINED;
  46250. obj = JS_ToObject(ctx, this_val);
  46251. if (js_get_length64(ctx, &len, obj))
  46252. goto exception;
  46253. func = argv[0];
  46254. if (check_function(ctx, func))
  46255. goto exception;
  46256. this_arg = JS_UNDEFINED;
  46257. if (argc > 1)
  46258. this_arg = argv[1];
  46259. k = 0;
  46260. dir = 1;
  46261. end = len;
  46262. if (mode == ArrayFindLast || mode == ArrayFindLastIndex) {
  46263. k = len - 1;
  46264. dir = -1;
  46265. end = -1;
  46266. }
  46267. // TODO(bnoordhuis) add fast path for fast arrays
  46268. for(; k != end; k += dir) {
  46269. index_val = js_int64(k);
  46270. val = JS_GetPropertyValue(ctx, obj, index_val);
  46271. if (JS_IsException(val))
  46272. goto exception;
  46273. args[0] = val;
  46274. args[1] = index_val;
  46275. args[2] = this_val;
  46276. res = JS_Call(ctx, func, this_arg, 3, args);
  46277. if (JS_IsException(res))
  46278. goto exception;
  46279. if (JS_ToBoolFree(ctx, res)) {
  46280. if (mode == ArrayFindIndex || mode == ArrayFindLastIndex) {
  46281. JS_FreeValue(ctx, val);
  46282. JS_FreeValue(ctx, obj);
  46283. return index_val;
  46284. } else {
  46285. JS_FreeValue(ctx, index_val);
  46286. JS_FreeValue(ctx, obj);
  46287. return val;
  46288. }
  46289. }
  46290. JS_FreeValue(ctx, val);
  46291. JS_FreeValue(ctx, index_val);
  46292. }
  46293. JS_FreeValue(ctx, obj);
  46294. if (mode == ArrayFindIndex || mode == ArrayFindLastIndex)
  46295. return js_int32(-1);
  46296. else
  46297. return JS_UNDEFINED;
  46298. exception:
  46299. JS_FreeValue(ctx, index_val);
  46300. JS_FreeValue(ctx, val);
  46301. JS_FreeValue(ctx, obj);
  46302. return JS_EXCEPTION;
  46303. }
  46304. static JSValue js_array_toString(JSContext *ctx, JSValueConst this_val,
  46305. int argc, JSValueConst *argv)
  46306. {
  46307. JSValue obj, method, ret;
  46308. obj = JS_ToObject(ctx, this_val);
  46309. if (JS_IsException(obj))
  46310. return JS_EXCEPTION;
  46311. method = JS_GetProperty(ctx, obj, JS_ATOM_join);
  46312. if (JS_IsException(method)) {
  46313. ret = JS_EXCEPTION;
  46314. } else
  46315. if (!JS_IsFunction(ctx, method)) {
  46316. /* Use intrinsic Object.prototype.toString */
  46317. JS_FreeValue(ctx, method);
  46318. ret = js_object_toString(ctx, obj, 0, NULL);
  46319. } else {
  46320. ret = JS_CallFree(ctx, method, obj, 0, NULL);
  46321. }
  46322. JS_FreeValue(ctx, obj);
  46323. return ret;
  46324. }
  46325. static JSValue js_array_join(JSContext *ctx, JSValueConst this_val,
  46326. int argc, JSValueConst *argv, int toLocaleString)
  46327. {
  46328. JSValue obj, sep = JS_UNDEFINED, el;
  46329. StringBuffer b_s, *b = &b_s;
  46330. JSString *p = NULL;
  46331. int64_t i, n;
  46332. int c;
  46333. obj = JS_ToObject(ctx, this_val);
  46334. if (js_get_length64(ctx, &n, obj))
  46335. goto exception;
  46336. c = ','; /* default separator */
  46337. if (!toLocaleString && argc > 0 && !JS_IsUndefined(argv[0])) {
  46338. sep = JS_ToString(ctx, argv[0]);
  46339. if (JS_IsException(sep))
  46340. goto exception;
  46341. p = JS_VALUE_GET_STRING(sep);
  46342. if (p->len == 1 && !p->is_wide_char)
  46343. c = str8(p)[0];
  46344. else
  46345. c = -1;
  46346. }
  46347. string_buffer_init(ctx, b, 0);
  46348. for(i = 0; i < n; i++) {
  46349. if (i > 0) {
  46350. if (c >= 0) {
  46351. string_buffer_putc8(b, c);
  46352. } else {
  46353. string_buffer_concat(b, p, 0, p->len);
  46354. }
  46355. }
  46356. el = JS_GetPropertyUint32(ctx, obj, i);
  46357. if (JS_IsException(el))
  46358. goto fail;
  46359. if (!JS_IsNull(el) && !JS_IsUndefined(el)) {
  46360. if (toLocaleString) {
  46361. el = JS_ToLocaleStringFree(ctx, el);
  46362. }
  46363. if (string_buffer_concat_value_free(b, el))
  46364. goto fail;
  46365. }
  46366. }
  46367. JS_FreeValue(ctx, sep);
  46368. JS_FreeValue(ctx, obj);
  46369. return string_buffer_end(b);
  46370. fail:
  46371. string_buffer_free(b);
  46372. JS_FreeValue(ctx, sep);
  46373. exception:
  46374. JS_FreeValue(ctx, obj);
  46375. return JS_EXCEPTION;
  46376. }
  46377. static JSValue js_array_pop(JSContext *ctx, JSValueConst this_val,
  46378. int argc, JSValueConst *argv, int shift)
  46379. {
  46380. JSValue obj, res = JS_UNDEFINED;
  46381. int64_t len, newLen;
  46382. JSValue *arrp;
  46383. uint32_t count32;
  46384. obj = JS_ToObject(ctx, this_val);
  46385. if (js_get_length64(ctx, &len, obj))
  46386. goto exception;
  46387. newLen = 0;
  46388. if (len > 0) {
  46389. newLen = len - 1;
  46390. /* Special case fast arrays */
  46391. if (js_get_fast_array(ctx, obj, &arrp, &count32) && count32 == len) {
  46392. JSObject *p = JS_VALUE_GET_OBJ(obj);
  46393. if (shift) {
  46394. res = arrp[0];
  46395. memmove(arrp, arrp + 1, (count32 - 1) * sizeof(*arrp));
  46396. p->u.array.count--;
  46397. } else {
  46398. res = arrp[count32 - 1];
  46399. p->u.array.count--;
  46400. }
  46401. } else {
  46402. if (shift) {
  46403. res = JS_GetPropertyInt64(ctx, obj, 0);
  46404. if (JS_IsException(res))
  46405. goto exception;
  46406. if (JS_CopySubArray(ctx, obj, 0, 1, len - 1, +1))
  46407. goto exception;
  46408. } else {
  46409. res = JS_GetPropertyInt64(ctx, obj, newLen);
  46410. if (JS_IsException(res))
  46411. goto exception;
  46412. }
  46413. if (JS_DeletePropertyInt64(ctx, obj, newLen, JS_PROP_THROW) < 0)
  46414. goto exception;
  46415. }
  46416. }
  46417. if (JS_SetProperty(ctx, obj, JS_ATOM_length, js_int64(newLen)) < 0)
  46418. goto exception;
  46419. JS_FreeValue(ctx, obj);
  46420. return res;
  46421. exception:
  46422. JS_FreeValue(ctx, res);
  46423. JS_FreeValue(ctx, obj);
  46424. return JS_EXCEPTION;
  46425. }
  46426. static JSValue js_array_push(JSContext *ctx, JSValueConst this_val,
  46427. int argc, JSValueConst *argv, int unshift)
  46428. {
  46429. JSValue obj;
  46430. int i;
  46431. int64_t len, from, newLen;
  46432. obj = JS_ToObject(ctx, this_val);
  46433. if (js_get_length64(ctx, &len, obj))
  46434. goto exception;
  46435. newLen = len + argc;
  46436. if (newLen > MAX_SAFE_INTEGER) {
  46437. JS_ThrowTypeError(ctx, "Array loo long");
  46438. goto exception;
  46439. }
  46440. from = len;
  46441. if (unshift && argc > 0) {
  46442. if (JS_CopySubArray(ctx, obj, argc, 0, len, -1))
  46443. goto exception;
  46444. from = 0;
  46445. }
  46446. for(i = 0; i < argc; i++) {
  46447. if (JS_SetPropertyInt64(ctx, obj, from + i, js_dup(argv[i])) < 0)
  46448. goto exception;
  46449. }
  46450. if (JS_SetProperty(ctx, obj, JS_ATOM_length, js_int64(newLen)) < 0)
  46451. goto exception;
  46452. JS_FreeValue(ctx, obj);
  46453. return js_int64(newLen);
  46454. exception:
  46455. JS_FreeValue(ctx, obj);
  46456. return JS_EXCEPTION;
  46457. }
  46458. static JSValue js_array_reverse(JSContext *ctx, JSValueConst this_val,
  46459. int argc, JSValueConst *argv)
  46460. {
  46461. JSValue obj, lval, hval;
  46462. JSValue *arrp;
  46463. int64_t len, l, h;
  46464. int l_present, h_present;
  46465. uint32_t count32;
  46466. lval = JS_UNDEFINED;
  46467. obj = JS_ToObject(ctx, this_val);
  46468. if (js_get_length64(ctx, &len, obj))
  46469. goto exception;
  46470. /* Special case fast arrays */
  46471. if (js_get_fast_array(ctx, obj, &arrp, &count32) && count32 == len) {
  46472. uint32_t ll, hh;
  46473. if (count32 > 1) {
  46474. for (ll = 0, hh = count32 - 1; ll < hh; ll++, hh--) {
  46475. lval = arrp[ll];
  46476. arrp[ll] = arrp[hh];
  46477. arrp[hh] = lval;
  46478. }
  46479. }
  46480. return obj;
  46481. }
  46482. for (l = 0, h = len - 1; l < h; l++, h--) {
  46483. l_present = JS_TryGetPropertyInt64(ctx, obj, l, &lval);
  46484. if (l_present < 0)
  46485. goto exception;
  46486. h_present = JS_TryGetPropertyInt64(ctx, obj, h, &hval);
  46487. if (h_present < 0)
  46488. goto exception;
  46489. if (h_present) {
  46490. if (JS_SetPropertyInt64(ctx, obj, l, hval) < 0)
  46491. goto exception;
  46492. if (l_present) {
  46493. if (JS_SetPropertyInt64(ctx, obj, h, lval) < 0) {
  46494. lval = JS_UNDEFINED;
  46495. goto exception;
  46496. }
  46497. lval = JS_UNDEFINED;
  46498. } else {
  46499. if (JS_DeletePropertyInt64(ctx, obj, h, JS_PROP_THROW) < 0)
  46500. goto exception;
  46501. }
  46502. } else {
  46503. if (l_present) {
  46504. if (JS_DeletePropertyInt64(ctx, obj, l, JS_PROP_THROW) < 0)
  46505. goto exception;
  46506. if (JS_SetPropertyInt64(ctx, obj, h, lval) < 0) {
  46507. lval = JS_UNDEFINED;
  46508. goto exception;
  46509. }
  46510. lval = JS_UNDEFINED;
  46511. }
  46512. }
  46513. }
  46514. return obj;
  46515. exception:
  46516. JS_FreeValue(ctx, lval);
  46517. JS_FreeValue(ctx, obj);
  46518. return JS_EXCEPTION;
  46519. }
  46520. // Note: a.toReversed() is a.slice().reverse() with the twist that a.slice()
  46521. // leaves holes in sparse arrays intact whereas a.toReversed() replaces them
  46522. // with undefined, thus in effect creating a dense array.
  46523. // Does not use Array[@@species], always returns a base Array.
  46524. static JSValue js_array_toReversed(JSContext *ctx, JSValueConst this_val,
  46525. int argc, JSValueConst *argv)
  46526. {
  46527. JSValue arr, obj, ret, *arrp, *pval;
  46528. JSObject *p;
  46529. int64_t i, len;
  46530. uint32_t count32;
  46531. ret = JS_EXCEPTION;
  46532. arr = JS_UNDEFINED;
  46533. obj = JS_ToObject(ctx, this_val);
  46534. if (js_get_length64(ctx, &len, obj))
  46535. goto exception;
  46536. if (len > UINT32_MAX) {
  46537. JS_ThrowRangeError(ctx, "invalid array length");
  46538. goto exception;
  46539. }
  46540. arr = JS_NewArray(ctx);
  46541. if (JS_IsException(arr))
  46542. goto exception;
  46543. if (len > 0) {
  46544. p = JS_VALUE_GET_OBJ(arr);
  46545. if (expand_fast_array(ctx, p, len) < 0)
  46546. goto exception;
  46547. p->u.array.count = len;
  46548. i = len - 1;
  46549. pval = p->u.array.u.values;
  46550. if (js_get_fast_array(ctx, obj, &arrp, &count32) && count32 == len) {
  46551. for (; i >= 0; i--, pval++)
  46552. *pval = js_dup(arrp[i]);
  46553. } else {
  46554. // Query order is observable; test262 expects descending order.
  46555. for (; i >= 0; i--, pval++) {
  46556. if (-1 == JS_TryGetPropertyInt64(ctx, obj, i, pval)) {
  46557. // Exception; initialize remaining elements.
  46558. for (; i >= 0; i--, pval++)
  46559. *pval = JS_UNDEFINED;
  46560. goto exception;
  46561. }
  46562. }
  46563. }
  46564. if (JS_SetProperty(ctx, arr, JS_ATOM_length, js_int64(len)) < 0)
  46565. goto exception;
  46566. }
  46567. ret = arr;
  46568. arr = JS_UNDEFINED;
  46569. exception:
  46570. JS_FreeValue(ctx, arr);
  46571. JS_FreeValue(ctx, obj);
  46572. return ret;
  46573. }
  46574. static JSValue js_array_slice(JSContext *ctx, JSValueConst this_val,
  46575. int argc, JSValueConst *argv, int splice)
  46576. {
  46577. JSValue obj, arr, val, len_val;
  46578. int64_t len, start, k, final, n, count, del_count, new_len;
  46579. int kPresent;
  46580. JSValue *arrp;
  46581. uint32_t count32, i, item_count;
  46582. arr = JS_UNDEFINED;
  46583. obj = JS_ToObject(ctx, this_val);
  46584. if (js_get_length64(ctx, &len, obj))
  46585. goto exception;
  46586. if (JS_ToInt64Clamp(ctx, &start, argv[0], 0, len, len))
  46587. goto exception;
  46588. if (splice) {
  46589. if (argc == 0) {
  46590. item_count = 0;
  46591. del_count = 0;
  46592. } else if (argc == 1) {
  46593. item_count = 0;
  46594. del_count = len - start;
  46595. } else {
  46596. item_count = argc - 2;
  46597. if (JS_ToInt64Clamp(ctx, &del_count, argv[1], 0, len - start, 0))
  46598. goto exception;
  46599. }
  46600. if (len + item_count - del_count > MAX_SAFE_INTEGER) {
  46601. JS_ThrowTypeError(ctx, "Array loo long");
  46602. goto exception;
  46603. }
  46604. count = del_count;
  46605. } else {
  46606. item_count = 0; /* avoid warning */
  46607. final = len;
  46608. if (!JS_IsUndefined(argv[1])) {
  46609. if (JS_ToInt64Clamp(ctx, &final, argv[1], 0, len, len))
  46610. goto exception;
  46611. }
  46612. count = max_int64(final - start, 0);
  46613. }
  46614. len_val = js_int64(count);
  46615. arr = JS_ArraySpeciesCreate(ctx, obj, len_val);
  46616. JS_FreeValue(ctx, len_val);
  46617. if (JS_IsException(arr))
  46618. goto exception;
  46619. k = start;
  46620. final = start + count;
  46621. n = 0;
  46622. /* The fast array test on arr ensures that
  46623. JS_CreateDataPropertyUint32() won't modify obj in case arr is
  46624. an exotic object */
  46625. /* Special case fast arrays */
  46626. if (js_get_fast_array(ctx, obj, &arrp, &count32) &&
  46627. js_is_fast_array(ctx, arr)) {
  46628. /* XXX: should share code with fast array constructor */
  46629. for (; k < final && k < count32; k++, n++) {
  46630. if (JS_CreateDataPropertyUint32(ctx, arr, n, js_dup(arrp[k]), JS_PROP_THROW) < 0)
  46631. goto exception;
  46632. }
  46633. }
  46634. /* Copy the remaining elements if any (handle case of inherited properties) */
  46635. for (; k < final; k++, n++) {
  46636. kPresent = JS_TryGetPropertyInt64(ctx, obj, k, &val);
  46637. if (kPresent < 0)
  46638. goto exception;
  46639. if (kPresent) {
  46640. if (JS_CreateDataPropertyUint32(ctx, arr, n, val, JS_PROP_THROW) < 0)
  46641. goto exception;
  46642. }
  46643. }
  46644. if (JS_SetProperty(ctx, arr, JS_ATOM_length, js_int64(n)) < 0)
  46645. goto exception;
  46646. if (splice) {
  46647. new_len = len + item_count - del_count;
  46648. if (item_count != del_count) {
  46649. if (JS_CopySubArray(ctx, obj, start + item_count,
  46650. start + del_count, len - (start + del_count),
  46651. item_count <= del_count ? +1 : -1) < 0)
  46652. goto exception;
  46653. for (k = len; k-- > new_len; ) {
  46654. if (JS_DeletePropertyInt64(ctx, obj, k, JS_PROP_THROW) < 0)
  46655. goto exception;
  46656. }
  46657. }
  46658. for (i = 0; i < item_count; i++) {
  46659. if (JS_SetPropertyInt64(ctx, obj, start + i, js_dup(argv[i + 2])) < 0)
  46660. goto exception;
  46661. }
  46662. if (JS_SetProperty(ctx, obj, JS_ATOM_length, js_int64(new_len)) < 0)
  46663. goto exception;
  46664. }
  46665. JS_FreeValue(ctx, obj);
  46666. return arr;
  46667. exception:
  46668. JS_FreeValue(ctx, obj);
  46669. JS_FreeValue(ctx, arr);
  46670. return JS_EXCEPTION;
  46671. }
  46672. static JSValue js_array_toSpliced(JSContext *ctx, JSValueConst this_val,
  46673. int argc, JSValueConst *argv)
  46674. {
  46675. JSValue arr, obj, ret, *arrp, *pval, *last;
  46676. JSObject *p;
  46677. int64_t i, j, len, newlen, start, add, del;
  46678. uint32_t count32;
  46679. pval = NULL;
  46680. last = NULL;
  46681. ret = JS_EXCEPTION;
  46682. arr = JS_UNDEFINED;
  46683. obj = JS_ToObject(ctx, this_val);
  46684. if (js_get_length64(ctx, &len, obj))
  46685. goto exception;
  46686. start = 0;
  46687. if (argc > 0)
  46688. if (JS_ToInt64Clamp(ctx, &start, argv[0], 0, len, len))
  46689. goto exception;
  46690. del = 0;
  46691. if (argc > 0)
  46692. del = len - start;
  46693. if (argc > 1)
  46694. if (JS_ToInt64Clamp(ctx, &del, argv[1], 0, del, 0))
  46695. goto exception;
  46696. add = 0;
  46697. if (argc > 2)
  46698. add = argc - 2;
  46699. newlen = len + add - del;
  46700. if (newlen > UINT32_MAX) {
  46701. // Per spec: TypeError if newlen >= 2**53, RangeError below
  46702. if (newlen > MAX_SAFE_INTEGER) {
  46703. JS_ThrowTypeError(ctx, "invalid array length");
  46704. } else {
  46705. JS_ThrowRangeError(ctx, "invalid array length");
  46706. }
  46707. goto exception;
  46708. }
  46709. arr = JS_NewArray(ctx);
  46710. if (JS_IsException(arr))
  46711. goto exception;
  46712. if (newlen <= 0)
  46713. goto done;
  46714. p = JS_VALUE_GET_OBJ(arr);
  46715. if (expand_fast_array(ctx, p, newlen) < 0)
  46716. goto exception;
  46717. p->u.array.count = newlen;
  46718. pval = &p->u.array.u.values[0];
  46719. last = &p->u.array.u.values[newlen];
  46720. if (js_get_fast_array(ctx, obj, &arrp, &count32) && count32 == len) {
  46721. for (i = 0; i < start; i++, pval++)
  46722. *pval = js_dup(arrp[i]);
  46723. for (j = 0; j < add; j++, pval++)
  46724. *pval = js_dup(argv[2 + j]);
  46725. for (i += del; i < len; i++, pval++)
  46726. *pval = js_dup(arrp[i]);
  46727. } else {
  46728. for (i = 0; i < start; i++, pval++)
  46729. if (-1 == JS_TryGetPropertyInt64(ctx, obj, i, pval))
  46730. goto exception;
  46731. for (j = 0; j < add; j++, pval++)
  46732. *pval = js_dup(argv[2 + j]);
  46733. for (i += del; i < len; i++, pval++)
  46734. if (-1 == JS_TryGetPropertyInt64(ctx, obj, i, pval))
  46735. goto exception;
  46736. }
  46737. assert(pval == last);
  46738. if (JS_SetProperty(ctx, arr, JS_ATOM_length, js_int64(newlen)) < 0)
  46739. goto exception;
  46740. done:
  46741. ret = arr;
  46742. arr = JS_UNDEFINED;
  46743. exception:
  46744. while (pval != last)
  46745. *pval++ = JS_UNDEFINED;
  46746. JS_FreeValue(ctx, arr);
  46747. JS_FreeValue(ctx, obj);
  46748. return ret;
  46749. }
  46750. static JSValue js_array_copyWithin(JSContext *ctx, JSValueConst this_val,
  46751. int argc, JSValueConst *argv)
  46752. {
  46753. JSValue obj;
  46754. int64_t len, from, to, final, count;
  46755. obj = JS_ToObject(ctx, this_val);
  46756. if (js_get_length64(ctx, &len, obj))
  46757. goto exception;
  46758. if (JS_ToInt64Clamp(ctx, &to, argv[0], 0, len, len))
  46759. goto exception;
  46760. if (JS_ToInt64Clamp(ctx, &from, argv[1], 0, len, len))
  46761. goto exception;
  46762. final = len;
  46763. if (argc > 2 && !JS_IsUndefined(argv[2])) {
  46764. if (JS_ToInt64Clamp(ctx, &final, argv[2], 0, len, len))
  46765. goto exception;
  46766. }
  46767. count = min_int64(final - from, len - to);
  46768. if (JS_CopySubArray(ctx, obj, to, from, count,
  46769. (from < to && to < from + count) ? -1 : +1))
  46770. goto exception;
  46771. return obj;
  46772. exception:
  46773. JS_FreeValue(ctx, obj);
  46774. return JS_EXCEPTION;
  46775. }
  46776. static int64_t JS_FlattenIntoArray(JSContext *ctx, JSValueConst target,
  46777. JSValueConst source, int64_t sourceLen,
  46778. int64_t targetIndex, int depth,
  46779. JSValueConst mapperFunction,
  46780. JSValueConst thisArg)
  46781. {
  46782. JSValue element;
  46783. int64_t sourceIndex, elementLen;
  46784. int present, is_array;
  46785. if (js_check_stack_overflow(ctx->rt, 0)) {
  46786. JS_ThrowStackOverflow(ctx);
  46787. return -1;
  46788. }
  46789. for (sourceIndex = 0; sourceIndex < sourceLen; sourceIndex++) {
  46790. present = JS_TryGetPropertyInt64(ctx, source, sourceIndex, &element);
  46791. if (present < 0)
  46792. return -1;
  46793. if (!present)
  46794. continue;
  46795. if (!JS_IsUndefined(mapperFunction)) {
  46796. JSValue index = js_int64(sourceIndex);
  46797. JSValueConst args[3] = { element, index, source };
  46798. JSValue ret = JS_Call(ctx, mapperFunction, thisArg, 3, args);
  46799. JS_FreeValue(ctx, element);
  46800. JS_FreeValue(ctx, index);
  46801. if (JS_IsException(ret))
  46802. return -1;
  46803. element = ret;
  46804. }
  46805. if (depth > 0) {
  46806. is_array = js_is_array(ctx, element);
  46807. if (is_array < 0)
  46808. goto fail;
  46809. if (is_array) {
  46810. if (js_get_length64(ctx, &elementLen, element) < 0)
  46811. goto fail;
  46812. targetIndex = JS_FlattenIntoArray(ctx, target, element,
  46813. elementLen, targetIndex,
  46814. depth - 1,
  46815. JS_UNDEFINED, JS_UNDEFINED);
  46816. if (targetIndex < 0)
  46817. goto fail;
  46818. JS_FreeValue(ctx, element);
  46819. continue;
  46820. }
  46821. }
  46822. if (targetIndex >= MAX_SAFE_INTEGER) {
  46823. JS_ThrowTypeError(ctx, "Array too long");
  46824. goto fail;
  46825. }
  46826. if (JS_DefinePropertyValueInt64(ctx, target, targetIndex, element,
  46827. JS_PROP_C_W_E | JS_PROP_THROW) < 0)
  46828. return -1;
  46829. targetIndex++;
  46830. }
  46831. return targetIndex;
  46832. fail:
  46833. JS_FreeValue(ctx, element);
  46834. return -1;
  46835. }
  46836. static JSValue js_array_flatten(JSContext *ctx, JSValueConst this_val,
  46837. int argc, JSValueConst *argv, int map)
  46838. {
  46839. JSValue obj, arr;
  46840. JSValueConst mapperFunction, thisArg;
  46841. int64_t sourceLen;
  46842. int depthNum;
  46843. arr = JS_UNDEFINED;
  46844. obj = JS_ToObject(ctx, this_val);
  46845. if (js_get_length64(ctx, &sourceLen, obj))
  46846. goto exception;
  46847. depthNum = 1;
  46848. mapperFunction = JS_UNDEFINED;
  46849. thisArg = JS_UNDEFINED;
  46850. if (map) {
  46851. mapperFunction = argv[0];
  46852. if (argc > 1) {
  46853. thisArg = argv[1];
  46854. }
  46855. if (check_function(ctx, mapperFunction))
  46856. goto exception;
  46857. } else {
  46858. if (argc > 0 && !JS_IsUndefined(argv[0])) {
  46859. if (JS_ToInt32Sat(ctx, &depthNum, argv[0]) < 0)
  46860. goto exception;
  46861. }
  46862. }
  46863. arr = JS_ArraySpeciesCreate(ctx, obj, js_int32(0));
  46864. if (JS_IsException(arr))
  46865. goto exception;
  46866. if (JS_FlattenIntoArray(ctx, arr, obj, sourceLen, 0, depthNum,
  46867. mapperFunction, thisArg) < 0)
  46868. goto exception;
  46869. JS_FreeValue(ctx, obj);
  46870. return arr;
  46871. exception:
  46872. JS_FreeValue(ctx, obj);
  46873. JS_FreeValue(ctx, arr);
  46874. return JS_EXCEPTION;
  46875. }
  46876. /* Array sort */
  46877. typedef struct ValueSlot {
  46878. JSValue val;
  46879. JSString *str;
  46880. int64_t pos;
  46881. } ValueSlot;
  46882. struct array_sort_context {
  46883. JSContext *ctx;
  46884. int exception;
  46885. int has_method;
  46886. JSValueConst method;
  46887. };
  46888. static int js_array_cmp_generic(const void *a, const void *b, void *opaque) {
  46889. struct array_sort_context *psc = opaque;
  46890. JSContext *ctx = psc->ctx;
  46891. JSValueConst argv[2];
  46892. JSValue res;
  46893. ValueSlot *ap = (ValueSlot *)(void *)a;
  46894. ValueSlot *bp = (ValueSlot *)(void *)b;
  46895. int cmp;
  46896. if (psc->exception)
  46897. return 0;
  46898. if (psc->has_method) {
  46899. /* custom sort function is specified as returning 0 for identical
  46900. * objects: avoid method call overhead.
  46901. */
  46902. if (!memcmp(&ap->val, &bp->val, sizeof(ap->val)))
  46903. goto cmp_same;
  46904. argv[0] = ap->val;
  46905. argv[1] = bp->val;
  46906. res = JS_Call(ctx, psc->method, JS_UNDEFINED, 2, argv);
  46907. if (JS_IsException(res))
  46908. goto exception;
  46909. if (JS_VALUE_GET_TAG(res) == JS_TAG_INT) {
  46910. int val = JS_VALUE_GET_INT(res);
  46911. cmp = (val > 0) - (val < 0);
  46912. } else {
  46913. double val;
  46914. if (JS_ToFloat64Free(ctx, &val, res) < 0)
  46915. goto exception;
  46916. cmp = (val > 0) - (val < 0);
  46917. }
  46918. } else {
  46919. /* Not supposed to bypass ToString even for identical objects as
  46920. * tested in test262/test/built-ins/Array/prototype/sort/bug_596_1.js
  46921. */
  46922. if (!ap->str) {
  46923. JSValue str = JS_ToString(ctx, ap->val);
  46924. if (JS_IsException(str))
  46925. goto exception;
  46926. ap->str = JS_VALUE_GET_STRING(str);
  46927. }
  46928. if (!bp->str) {
  46929. JSValue str = JS_ToString(ctx, bp->val);
  46930. if (JS_IsException(str))
  46931. goto exception;
  46932. bp->str = JS_VALUE_GET_STRING(str);
  46933. }
  46934. cmp = js_string_compare(ap->str, bp->str);
  46935. }
  46936. if (cmp != 0)
  46937. return cmp;
  46938. cmp_same:
  46939. /* make sort stable: compare array offsets */
  46940. return (ap->pos > bp->pos) - (ap->pos < bp->pos);
  46941. exception:
  46942. psc->exception = 1;
  46943. return 0;
  46944. }
  46945. static JSValue js_array_sort(JSContext *ctx, JSValueConst this_val,
  46946. int argc, JSValueConst *argv)
  46947. {
  46948. struct array_sort_context asc = { ctx, 0, 0, argv[0] };
  46949. JSValue obj = JS_UNDEFINED;
  46950. ValueSlot *array = NULL;
  46951. size_t array_size = 0, pos = 0, n = 0;
  46952. int64_t i, len, undefined_count = 0;
  46953. int present;
  46954. if (!JS_IsUndefined(asc.method)) {
  46955. if (check_function(ctx, asc.method))
  46956. goto exception;
  46957. asc.has_method = 1;
  46958. }
  46959. obj = JS_ToObject(ctx, this_val);
  46960. if (js_get_length64(ctx, &len, obj))
  46961. goto exception;
  46962. /* XXX: should special case fast arrays */
  46963. for (i = 0; i < len; i++) {
  46964. if (pos >= array_size) {
  46965. size_t new_size, slack;
  46966. ValueSlot *new_array;
  46967. new_size = (array_size + (array_size >> 1) + 31) & ~15;
  46968. new_array = js_realloc2(ctx, array, new_size * sizeof(*array), &slack);
  46969. if (new_array == NULL)
  46970. goto exception;
  46971. new_size += slack / sizeof(*new_array);
  46972. array = new_array;
  46973. array_size = new_size;
  46974. }
  46975. present = JS_TryGetPropertyInt64(ctx, obj, i, &array[pos].val);
  46976. if (present < 0)
  46977. goto exception;
  46978. if (present == 0)
  46979. continue;
  46980. if (JS_IsUndefined(array[pos].val)) {
  46981. undefined_count++;
  46982. continue;
  46983. }
  46984. array[pos].str = NULL;
  46985. array[pos].pos = i;
  46986. pos++;
  46987. }
  46988. rqsort(array, pos, sizeof(*array), js_array_cmp_generic, &asc);
  46989. if (asc.exception)
  46990. goto exception;
  46991. /* XXX: should special case fast arrays */
  46992. while (n < pos) {
  46993. if (array[n].str)
  46994. JS_FreeValue(ctx, JS_MKPTR(JS_TAG_STRING, array[n].str));
  46995. if (array[n].pos == n) {
  46996. JS_FreeValue(ctx, array[n].val);
  46997. } else {
  46998. if (JS_SetPropertyInt64(ctx, obj, n, array[n].val) < 0) {
  46999. n++;
  47000. goto exception;
  47001. }
  47002. }
  47003. n++;
  47004. }
  47005. js_free(ctx, array);
  47006. for (i = n; undefined_count-- > 0; i++) {
  47007. if (JS_SetPropertyInt64(ctx, obj, i, JS_UNDEFINED) < 0)
  47008. goto fail;
  47009. }
  47010. for (; i < len; i++) {
  47011. if (JS_DeletePropertyInt64(ctx, obj, i, JS_PROP_THROW) < 0)
  47012. goto fail;
  47013. }
  47014. return obj;
  47015. exception:
  47016. for (; n < pos; n++) {
  47017. JS_FreeValue(ctx, array[n].val);
  47018. if (array[n].str)
  47019. JS_FreeValue(ctx, JS_MKPTR(JS_TAG_STRING, array[n].str));
  47020. }
  47021. js_free(ctx, array);
  47022. fail:
  47023. JS_FreeValue(ctx, obj);
  47024. return JS_EXCEPTION;
  47025. }
  47026. // Note: a.toSorted() is a.slice().sort() with the twist that a.slice()
  47027. // leaves holes in sparse arrays intact whereas a.toSorted() replaces them
  47028. // with undefined, thus in effect creating a dense array.
  47029. // Does not use Array[@@species], always returns a base Array.
  47030. static JSValue js_array_toSorted(JSContext *ctx, JSValueConst this_val,
  47031. int argc, JSValueConst *argv)
  47032. {
  47033. JSValue arr, obj, ret, *arrp, *pval;
  47034. JSObject *p;
  47035. int64_t i, len;
  47036. uint32_t count32;
  47037. int ok;
  47038. ok = JS_IsUndefined(argv[0]) || JS_IsFunction(ctx, argv[0]);
  47039. if (!ok)
  47040. return JS_ThrowTypeErrorNotAFunction(ctx);
  47041. ret = JS_EXCEPTION;
  47042. arr = JS_UNDEFINED;
  47043. obj = JS_ToObject(ctx, this_val);
  47044. if (js_get_length64(ctx, &len, obj))
  47045. goto exception;
  47046. if (len > UINT32_MAX) {
  47047. JS_ThrowRangeError(ctx, "invalid array length");
  47048. goto exception;
  47049. }
  47050. arr = JS_NewArray(ctx);
  47051. if (JS_IsException(arr))
  47052. goto exception;
  47053. if (len > 0) {
  47054. p = JS_VALUE_GET_OBJ(arr);
  47055. if (expand_fast_array(ctx, p, len) < 0)
  47056. goto exception;
  47057. p->u.array.count = len;
  47058. i = 0;
  47059. pval = p->u.array.u.values;
  47060. if (js_get_fast_array(ctx, obj, &arrp, &count32) && count32 == len) {
  47061. for (; i < len; i++, pval++)
  47062. *pval = js_dup(arrp[i]);
  47063. } else {
  47064. for (; i < len; i++, pval++) {
  47065. if (-1 == JS_TryGetPropertyInt64(ctx, obj, i, pval)) {
  47066. for (; i < len; i++, pval++)
  47067. *pval = JS_UNDEFINED;
  47068. goto exception;
  47069. }
  47070. }
  47071. }
  47072. if (JS_SetProperty(ctx, arr, JS_ATOM_length, js_int64(len)) < 0)
  47073. goto exception;
  47074. }
  47075. ret = js_array_sort(ctx, arr, argc, argv);
  47076. if (JS_IsException(ret))
  47077. goto exception;
  47078. JS_FreeValue(ctx, ret);
  47079. ret = arr;
  47080. arr = JS_UNDEFINED;
  47081. exception:
  47082. JS_FreeValue(ctx, arr);
  47083. JS_FreeValue(ctx, obj);
  47084. return ret;
  47085. }
  47086. typedef struct JSArrayIteratorData {
  47087. JSValue obj;
  47088. JSIteratorKindEnum kind;
  47089. uint32_t idx;
  47090. } JSArrayIteratorData;
  47091. static void js_array_iterator_finalizer(JSRuntime *rt, JSValueConst val)
  47092. {
  47093. JSObject *p = JS_VALUE_GET_OBJ(val);
  47094. JSArrayIteratorData *it = p->u.array_iterator_data;
  47095. if (it) {
  47096. JS_FreeValueRT(rt, it->obj);
  47097. js_free_rt(rt, it);
  47098. }
  47099. }
  47100. static void js_array_iterator_mark(JSRuntime *rt, JSValueConst val,
  47101. JS_MarkFunc *mark_func)
  47102. {
  47103. JSObject *p = JS_VALUE_GET_OBJ(val);
  47104. JSArrayIteratorData *it = p->u.array_iterator_data;
  47105. if (it) {
  47106. JS_MarkValue(rt, it->obj, mark_func);
  47107. }
  47108. }
  47109. static JSValue js_create_array(JSContext *ctx, int len, JSValueConst *tab)
  47110. {
  47111. JSValue obj;
  47112. int i;
  47113. obj = JS_NewArray(ctx);
  47114. if (JS_IsException(obj))
  47115. return JS_EXCEPTION;
  47116. for(i = 0; i < len; i++) {
  47117. if (JS_CreateDataPropertyUint32(ctx, obj, i, js_dup(tab[i]), 0) < 0) {
  47118. JS_FreeValue(ctx, obj);
  47119. return JS_EXCEPTION;
  47120. }
  47121. }
  47122. return obj;
  47123. }
  47124. static JSValue js_create_array_iterator(JSContext *ctx, JSValueConst this_val,
  47125. int argc, JSValueConst *argv, int magic)
  47126. {
  47127. JSValue enum_obj, arr;
  47128. JSArrayIteratorData *it;
  47129. JSIteratorKindEnum kind;
  47130. int class_id;
  47131. kind = magic & 3;
  47132. if (magic & 4) {
  47133. /* string iterator case */
  47134. arr = JS_ToStringCheckObject(ctx, this_val);
  47135. class_id = JS_CLASS_STRING_ITERATOR;
  47136. } else {
  47137. arr = JS_ToObject(ctx, this_val);
  47138. class_id = JS_CLASS_ARRAY_ITERATOR;
  47139. }
  47140. if (JS_IsException(arr))
  47141. goto fail;
  47142. enum_obj = JS_NewObjectClass(ctx, class_id);
  47143. if (JS_IsException(enum_obj))
  47144. goto fail;
  47145. it = js_malloc(ctx, sizeof(*it));
  47146. if (!it)
  47147. goto fail1;
  47148. it->obj = arr;
  47149. it->kind = kind;
  47150. it->idx = 0;
  47151. JS_SetOpaqueInternal(enum_obj, it);
  47152. return enum_obj;
  47153. fail1:
  47154. JS_FreeValue(ctx, enum_obj);
  47155. fail:
  47156. JS_FreeValue(ctx, arr);
  47157. return JS_EXCEPTION;
  47158. }
  47159. static JSValue js_array_iterator_next(JSContext *ctx, JSValueConst this_val,
  47160. int argc, JSValueConst *argv,
  47161. int *pdone, int magic)
  47162. {
  47163. JSArrayIteratorData *it;
  47164. uint32_t len, idx;
  47165. JSValue val, obj;
  47166. JSObject *p;
  47167. it = JS_GetOpaque2(ctx, this_val, JS_CLASS_ARRAY_ITERATOR);
  47168. if (!it)
  47169. goto fail1;
  47170. if (JS_IsUndefined(it->obj))
  47171. goto done;
  47172. p = JS_VALUE_GET_OBJ(it->obj);
  47173. if (is_typed_array(p->class_id)) {
  47174. if (typed_array_is_oob(p)) {
  47175. JS_ThrowTypeErrorArrayBufferOOB(ctx);
  47176. goto fail1;
  47177. }
  47178. len = p->u.array.count;
  47179. } else {
  47180. if (js_get_length32(ctx, &len, it->obj)) {
  47181. fail1:
  47182. *pdone = false;
  47183. return JS_EXCEPTION;
  47184. }
  47185. }
  47186. idx = it->idx;
  47187. if (idx >= len) {
  47188. JS_FreeValue(ctx, it->obj);
  47189. it->obj = JS_UNDEFINED;
  47190. done:
  47191. *pdone = true;
  47192. return JS_UNDEFINED;
  47193. }
  47194. it->idx = idx + 1;
  47195. *pdone = false;
  47196. if (it->kind == JS_ITERATOR_KIND_KEY) {
  47197. return js_uint32(idx);
  47198. } else {
  47199. val = JS_GetPropertyUint32(ctx, it->obj, idx);
  47200. if (JS_IsException(val))
  47201. return JS_EXCEPTION;
  47202. if (it->kind == JS_ITERATOR_KIND_VALUE) {
  47203. return val;
  47204. } else {
  47205. JSValueConst args[2];
  47206. JSValue num;
  47207. num = js_uint32(idx);
  47208. args[0] = num;
  47209. args[1] = val;
  47210. obj = js_create_array(ctx, 2, args);
  47211. JS_FreeValue(ctx, val);
  47212. JS_FreeValue(ctx, num);
  47213. return obj;
  47214. }
  47215. }
  47216. }
  47217. typedef struct JSIteratorWrapData {
  47218. JSValue wrapped_iter;
  47219. JSValue wrapped_next;
  47220. } JSIteratorWrapData;
  47221. static void js_iterator_wrap_finalizer(JSRuntime *rt, JSValueConst val)
  47222. {
  47223. JSObject *p = JS_VALUE_GET_OBJ(val);
  47224. JSIteratorWrapData *it = p->u.iterator_wrap_data;
  47225. if (it) {
  47226. JS_FreeValueRT(rt, it->wrapped_iter);
  47227. JS_FreeValueRT(rt, it->wrapped_next);
  47228. js_free_rt(rt, it);
  47229. }
  47230. }
  47231. static void js_iterator_wrap_mark(JSRuntime *rt, JSValueConst val,
  47232. JS_MarkFunc *mark_func)
  47233. {
  47234. JSObject *p = JS_VALUE_GET_OBJ(val);
  47235. JSIteratorWrapData *it = p->u.iterator_wrap_data;
  47236. if (it) {
  47237. JS_MarkValue(rt, it->wrapped_iter, mark_func);
  47238. JS_MarkValue(rt, it->wrapped_next, mark_func);
  47239. }
  47240. }
  47241. static JSValue js_iterator_wrap_next(JSContext *ctx, JSValueConst this_val,
  47242. int argc, JSValueConst *argv,
  47243. int *pdone, int magic)
  47244. {
  47245. JSIteratorWrapData *it;
  47246. JSValue method, ret;
  47247. it = JS_GetOpaque2(ctx, this_val, JS_CLASS_ITERATOR_WRAP);
  47248. if (!it)
  47249. return JS_EXCEPTION;
  47250. if (magic == GEN_MAGIC_NEXT)
  47251. return JS_IteratorNext(ctx, it->wrapped_iter, it->wrapped_next, argc, argv, pdone);
  47252. method = JS_GetProperty(ctx, it->wrapped_iter, JS_ATOM_return);
  47253. if (JS_IsException(method))
  47254. return JS_EXCEPTION;
  47255. if (JS_IsNull(method) || JS_IsUndefined(method)) {
  47256. *pdone = true;
  47257. return JS_UNDEFINED;
  47258. }
  47259. ret = JS_IteratorNext2(ctx, it->wrapped_iter, method, argc, argv, pdone);
  47260. JS_FreeValue(ctx, method);
  47261. return ret;
  47262. }
  47263. static const JSCFunctionListEntry js_iterator_wrap_proto_funcs[] = {
  47264. JS_ITERATOR_NEXT_DEF("next", 0, js_iterator_wrap_next, GEN_MAGIC_NEXT ),
  47265. JS_ITERATOR_NEXT_DEF("return", 0, js_iterator_wrap_next, GEN_MAGIC_RETURN ),
  47266. };
  47267. static JSValue js_iterator_constructor(JSContext *ctx, JSValueConst new_target,
  47268. int argc, JSValueConst *argv)
  47269. {
  47270. JSObject *p;
  47271. if (JS_TAG_OBJECT != JS_VALUE_GET_TAG(new_target))
  47272. return JS_ThrowTypeError(ctx, "constructor requires 'new'");
  47273. p = JS_VALUE_GET_OBJ(new_target);
  47274. if (p->class_id == JS_CLASS_C_FUNCTION)
  47275. if (p->u.cfunc.c_function.generic == js_iterator_constructor)
  47276. return JS_ThrowTypeError(ctx, "abstract class not constructable");
  47277. return js_create_from_ctor(ctx, new_target, JS_CLASS_ITERATOR);
  47278. }
  47279. static JSValue js_iterator_from(JSContext *ctx, JSValueConst this_val,
  47280. int argc, JSValueConst *argv)
  47281. {
  47282. JSValue method, iter;
  47283. JSIteratorWrapData *it;
  47284. int ret;
  47285. JSValueConst obj = argv[0];
  47286. if (JS_IsString(obj)) {
  47287. method = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_iterator);
  47288. if (JS_IsException(method))
  47289. return JS_EXCEPTION;
  47290. return JS_CallFree(ctx, method, obj, 0, NULL);
  47291. }
  47292. if (!JS_IsObject(obj))
  47293. return JS_ThrowTypeError(ctx, "Iterator.from called on non-object");
  47294. ret = JS_OrdinaryIsInstanceOf(ctx, obj, ctx->iterator_ctor);
  47295. if (ret < 0)
  47296. return JS_EXCEPTION;
  47297. if (ret)
  47298. return js_dup(obj);
  47299. method = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_iterator);
  47300. if (JS_IsException(method))
  47301. return JS_EXCEPTION;
  47302. if (JS_IsNull(method) || JS_IsUndefined(method)) {
  47303. method = JS_GetProperty(ctx, obj, JS_ATOM_next);
  47304. if (JS_IsException(method))
  47305. return JS_EXCEPTION;
  47306. iter = JS_NewObjectClass(ctx, JS_CLASS_ITERATOR_WRAP);
  47307. if (JS_IsException(iter))
  47308. goto fail;
  47309. it = js_malloc(ctx, sizeof(*it));
  47310. if (!it)
  47311. goto fail;
  47312. it->wrapped_iter = js_dup(obj);
  47313. it->wrapped_next = method;
  47314. JS_SetOpaqueInternal(iter, it);
  47315. } else {
  47316. iter = JS_GetIterator2(ctx, obj, method);
  47317. JS_FreeValue(ctx, method);
  47318. if (JS_IsException(iter))
  47319. return JS_EXCEPTION;
  47320. }
  47321. return iter;
  47322. fail:
  47323. JS_FreeValue(ctx, method);
  47324. JS_FreeValue(ctx, iter);
  47325. return JS_EXCEPTION;
  47326. }
  47327. static int check_iterator(JSContext *ctx, JSValueConst obj)
  47328. {
  47329. if (!JS_IsObject(obj)) {
  47330. JS_ThrowTypeErrorNotAnObject(ctx);
  47331. return -1;
  47332. }
  47333. return 0;
  47334. }
  47335. typedef struct JSIteratorHelperData {
  47336. JSValue obj;
  47337. JSValue next;
  47338. JSValue func; // predicate (filter) or mapper (flatMap, map)
  47339. JSValue inner; // innerValue (flatMap)
  47340. int64_t count; // limit (drop, take) or counter (filter, map, flatMap)
  47341. JSIteratorHelperKindEnum kind : 8;
  47342. uint8_t executing : 1;
  47343. uint8_t done : 1;
  47344. } JSIteratorHelperData;
  47345. static JSValue js_create_iterator_helper(JSContext *ctx, JSValueConst this_val,
  47346. int argc, JSValueConst *argv, int magic)
  47347. {
  47348. JSValueConst func;
  47349. JSValue obj, method;
  47350. int64_t count;
  47351. JSIteratorHelperData *it;
  47352. if (check_iterator(ctx, this_val) < 0)
  47353. return JS_EXCEPTION;
  47354. func = JS_UNDEFINED;
  47355. count = 0;
  47356. switch(magic) {
  47357. case JS_ITERATOR_HELPER_KIND_DROP:
  47358. case JS_ITERATOR_HELPER_KIND_TAKE:
  47359. {
  47360. JSValue v;
  47361. double dlimit;
  47362. v = JS_ToNumber(ctx, argv[0]);
  47363. if (JS_IsException(v))
  47364. return JS_EXCEPTION;
  47365. // Check for Infinity.
  47366. if (JS_ToFloat64(ctx, &dlimit, v)) {
  47367. JS_FreeValue(ctx, v);
  47368. return JS_EXCEPTION;
  47369. }
  47370. if (isnan(dlimit)) {
  47371. JS_FreeValue(ctx, v);
  47372. goto fail;
  47373. }
  47374. if (!isfinite(dlimit)) {
  47375. JS_FreeValue(ctx, v);
  47376. if (dlimit < 0)
  47377. goto fail;
  47378. else
  47379. count = MAX_SAFE_INTEGER;
  47380. } else {
  47381. v = JS_ToIntegerFree(ctx, v);
  47382. if (JS_IsException(v))
  47383. return JS_EXCEPTION;
  47384. if (JS_ToInt64Free(ctx, &count, v))
  47385. return JS_EXCEPTION;
  47386. }
  47387. if (count < 0) {
  47388. fail:
  47389. return JS_ThrowRangeError(ctx, "must be positive");
  47390. }
  47391. }
  47392. break;
  47393. case JS_ITERATOR_HELPER_KIND_FILTER:
  47394. case JS_ITERATOR_HELPER_KIND_FLAT_MAP:
  47395. case JS_ITERATOR_HELPER_KIND_MAP:
  47396. {
  47397. func = argv[0];
  47398. if (check_function(ctx, func))
  47399. return JS_EXCEPTION;
  47400. }
  47401. break;
  47402. default:
  47403. abort();
  47404. break;
  47405. }
  47406. method = JS_GetProperty(ctx, this_val, JS_ATOM_next);
  47407. if (JS_IsException(method))
  47408. return JS_EXCEPTION;
  47409. obj = JS_NewObjectClass(ctx, JS_CLASS_ITERATOR_HELPER);
  47410. if (JS_IsException(obj)) {
  47411. JS_FreeValue(ctx, method);
  47412. return JS_EXCEPTION;
  47413. }
  47414. it = js_malloc(ctx, sizeof(*it));
  47415. if (!it) {
  47416. JS_FreeValue(ctx, obj);
  47417. JS_FreeValue(ctx, method);
  47418. return JS_EXCEPTION;
  47419. }
  47420. it->kind = magic;
  47421. it->obj = js_dup(this_val);
  47422. it->func = js_dup(func);
  47423. it->next = method;
  47424. it->inner = JS_UNDEFINED;
  47425. it->count = count;
  47426. it->executing = 0;
  47427. it->done = 0;
  47428. JS_SetOpaqueInternal(obj, it);
  47429. return obj;
  47430. }
  47431. static JSValue js_iterator_proto_func(JSContext *ctx, JSValueConst this_val,
  47432. int argc, JSValueConst *argv, int magic)
  47433. {
  47434. JSValue item, method, ret, func, index_val, r;
  47435. JSValueConst args[2];
  47436. int64_t idx;
  47437. int done;
  47438. if (check_iterator(ctx, this_val) < 0)
  47439. return JS_EXCEPTION;
  47440. if (check_function(ctx, argv[0]))
  47441. return JS_EXCEPTION;
  47442. func = js_dup(argv[0]);
  47443. method = JS_GetProperty(ctx, this_val, JS_ATOM_next);
  47444. if (JS_IsException(method))
  47445. goto fail;
  47446. r = JS_UNDEFINED;
  47447. switch(magic) {
  47448. case JS_ITERATOR_HELPER_KIND_EVERY:
  47449. {
  47450. r = JS_TRUE;
  47451. for (idx = 0; /*empty*/; idx++) {
  47452. item = JS_IteratorNext(ctx, this_val, method, 0, NULL, &done);
  47453. if (JS_IsException(item))
  47454. goto fail;
  47455. if (done)
  47456. break;
  47457. index_val = js_int64(idx);
  47458. args[0] = item;
  47459. args[1] = index_val;
  47460. ret = JS_Call(ctx, func, JS_UNDEFINED, countof(args), args);
  47461. JS_FreeValue(ctx, item);
  47462. JS_FreeValue(ctx, index_val);
  47463. if (JS_IsException(ret))
  47464. goto fail;
  47465. if (!JS_ToBoolFree(ctx, ret)) {
  47466. if (JS_IteratorClose(ctx, this_val, false) < 0)
  47467. r = JS_EXCEPTION;
  47468. else
  47469. r = JS_FALSE;
  47470. break;
  47471. }
  47472. index_val = JS_UNDEFINED;
  47473. ret = JS_UNDEFINED;
  47474. item = JS_UNDEFINED;
  47475. }
  47476. }
  47477. break;
  47478. case JS_ITERATOR_HELPER_KIND_FIND:
  47479. {
  47480. for (idx = 0; /*empty*/; idx++) {
  47481. item = JS_IteratorNext(ctx, this_val, method, 0, NULL, &done);
  47482. if (JS_IsException(item))
  47483. goto fail;
  47484. if (done)
  47485. break;
  47486. index_val = js_int64(idx);
  47487. args[0] = item;
  47488. args[1] = index_val;
  47489. ret = JS_Call(ctx, func, JS_UNDEFINED, countof(args), args);
  47490. JS_FreeValue(ctx, index_val);
  47491. if (JS_IsException(ret)) {
  47492. JS_FreeValue(ctx, item);
  47493. goto fail;
  47494. }
  47495. if (JS_ToBoolFree(ctx, ret)) {
  47496. if (JS_IteratorClose(ctx, this_val, false) < 0) {
  47497. JS_FreeValue(ctx, item);
  47498. r = JS_EXCEPTION;
  47499. } else {
  47500. r = item;
  47501. }
  47502. break;
  47503. }
  47504. index_val = JS_UNDEFINED;
  47505. ret = JS_UNDEFINED;
  47506. item = JS_UNDEFINED;
  47507. }
  47508. }
  47509. break;
  47510. case JS_ITERATOR_HELPER_KIND_FOR_EACH:
  47511. {
  47512. for (idx = 0; /*empty*/; idx++) {
  47513. item = JS_IteratorNext(ctx, this_val, method, 0, NULL, &done);
  47514. if (JS_IsException(item))
  47515. goto fail;
  47516. if (done)
  47517. break;
  47518. index_val = js_int64(idx);
  47519. args[0] = item;
  47520. args[1] = index_val;
  47521. ret = JS_Call(ctx, func, JS_UNDEFINED, countof(args), args);
  47522. JS_FreeValue(ctx, item);
  47523. JS_FreeValue(ctx, index_val);
  47524. if (JS_IsException(ret))
  47525. goto fail;
  47526. JS_FreeValue(ctx, ret);
  47527. index_val = JS_UNDEFINED;
  47528. ret = JS_UNDEFINED;
  47529. item = JS_UNDEFINED;
  47530. }
  47531. }
  47532. break;
  47533. case JS_ITERATOR_HELPER_KIND_SOME:
  47534. {
  47535. r = JS_FALSE;
  47536. for (idx = 0; /*empty*/; idx++) {
  47537. item = JS_IteratorNext(ctx, this_val, method, 0, NULL, &done);
  47538. if (JS_IsException(item))
  47539. goto fail;
  47540. if (done)
  47541. break;
  47542. index_val = js_int64(idx);
  47543. args[0] = item;
  47544. args[1] = index_val;
  47545. ret = JS_Call(ctx, func, JS_UNDEFINED, countof(args), args);
  47546. JS_FreeValue(ctx, item);
  47547. JS_FreeValue(ctx, index_val);
  47548. if (JS_IsException(ret))
  47549. goto fail;
  47550. if (JS_ToBoolFree(ctx, ret)) {
  47551. if (JS_IteratorClose(ctx, this_val, false) < 0)
  47552. r = JS_EXCEPTION;
  47553. else
  47554. r = JS_TRUE;
  47555. break;
  47556. }
  47557. index_val = JS_UNDEFINED;
  47558. ret = JS_UNDEFINED;
  47559. item = JS_UNDEFINED;
  47560. }
  47561. }
  47562. break;
  47563. default:
  47564. abort();
  47565. break;
  47566. }
  47567. JS_FreeValue(ctx, func);
  47568. JS_FreeValue(ctx, method);
  47569. return r;
  47570. fail:
  47571. JS_IteratorClose(ctx, this_val, true);
  47572. JS_FreeValue(ctx, func);
  47573. JS_FreeValue(ctx, method);
  47574. return JS_EXCEPTION;
  47575. }
  47576. static JSValue js_iterator_proto_reduce(JSContext *ctx, JSValueConst this_val,
  47577. int argc, JSValueConst *argv)
  47578. {
  47579. JSValue item, method, ret, func, index_val, acc;
  47580. JSValueConst args[3];
  47581. int64_t idx;
  47582. int done;
  47583. if (check_iterator(ctx, this_val) < 0)
  47584. return JS_EXCEPTION;
  47585. if (check_function(ctx, argv[0]))
  47586. return JS_EXCEPTION;
  47587. acc = JS_UNDEFINED;
  47588. func = js_dup(argv[0]);
  47589. method = JS_GetProperty(ctx, this_val, JS_ATOM_next);
  47590. if (JS_IsException(method))
  47591. goto exception;
  47592. if (argc > 1) {
  47593. acc = js_dup(argv[1]);
  47594. idx = 0;
  47595. } else {
  47596. acc = JS_IteratorNext(ctx, this_val, method, 0, NULL, &done);
  47597. if (JS_IsException(acc))
  47598. goto exception;
  47599. if (done) {
  47600. JS_ThrowTypeError(ctx, "empty iterator");
  47601. goto exception;
  47602. }
  47603. idx = 1;
  47604. }
  47605. for (/* empty */; /*empty*/; idx++) {
  47606. item = JS_IteratorNext(ctx, this_val, method, 0, NULL, &done);
  47607. if (JS_IsException(item))
  47608. goto exception;
  47609. if (done)
  47610. break;
  47611. index_val = js_int64(idx);
  47612. args[0] = acc;
  47613. args[1] = item;
  47614. args[2] = index_val;
  47615. ret = JS_Call(ctx, func, JS_UNDEFINED, countof(args), args);
  47616. JS_FreeValue(ctx, item);
  47617. JS_FreeValue(ctx, index_val);
  47618. if (JS_IsException(ret))
  47619. goto exception;
  47620. JS_FreeValue(ctx, acc);
  47621. acc = ret;
  47622. index_val = JS_UNDEFINED;
  47623. ret = JS_UNDEFINED;
  47624. item = JS_UNDEFINED;
  47625. }
  47626. JS_FreeValue(ctx, func);
  47627. JS_FreeValue(ctx, method);
  47628. return acc;
  47629. exception:
  47630. JS_IteratorClose(ctx, this_val, true);
  47631. JS_FreeValue(ctx, acc);
  47632. JS_FreeValue(ctx, func);
  47633. JS_FreeValue(ctx, method);
  47634. return JS_EXCEPTION;
  47635. }
  47636. static JSValue js_iterator_proto_toArray(JSContext *ctx, JSValueConst this_val,
  47637. int argc, JSValueConst *argv)
  47638. {
  47639. JSValue item, method, result;
  47640. int64_t idx;
  47641. int done;
  47642. result = JS_UNDEFINED;
  47643. if (check_iterator(ctx, this_val) < 0)
  47644. return JS_EXCEPTION;
  47645. method = JS_GetProperty(ctx, this_val, JS_ATOM_next);
  47646. if (JS_IsException(method))
  47647. return JS_EXCEPTION;
  47648. result = JS_NewArray(ctx);
  47649. if (JS_IsException(result))
  47650. goto exception;
  47651. for (idx = 0; /*empty*/; idx++) {
  47652. item = JS_IteratorNext(ctx, this_val, method, 0, NULL, &done);
  47653. if (JS_IsException(item))
  47654. goto exception;
  47655. if (done)
  47656. break;
  47657. if (JS_DefinePropertyValueInt64(ctx, result, idx, item,
  47658. JS_PROP_C_W_E | JS_PROP_THROW) < 0)
  47659. goto exception;
  47660. }
  47661. if (JS_SetProperty(ctx, result, JS_ATOM_length, js_uint32(idx)) < 0)
  47662. goto exception;
  47663. JS_FreeValue(ctx, method);
  47664. return result;
  47665. exception:
  47666. JS_FreeValue(ctx, result);
  47667. JS_FreeValue(ctx, method);
  47668. return JS_EXCEPTION;
  47669. }
  47670. static JSValue js_iterator_proto_iterator(JSContext *ctx, JSValueConst this_val,
  47671. int argc, JSValueConst *argv)
  47672. {
  47673. return js_dup(this_val);
  47674. }
  47675. static JSValue js_iterator_proto_get_toStringTag(JSContext *ctx, JSValueConst this_val)
  47676. {
  47677. return JS_AtomToString(ctx, JS_ATOM_Iterator);
  47678. }
  47679. static JSValue js_iterator_proto_set_toStringTag(JSContext *ctx, JSValueConst this_val, JSValueConst val)
  47680. {
  47681. int res;
  47682. if (check_iterator(ctx, this_val) < 0)
  47683. return JS_EXCEPTION;
  47684. if (js_same_value(ctx, this_val, ctx->class_proto[JS_CLASS_ITERATOR]))
  47685. return JS_ThrowTypeError(ctx, "Cannot assign to read only property");
  47686. res = JS_GetOwnProperty(ctx, NULL, this_val, JS_ATOM_Symbol_toStringTag);
  47687. if (res < 0)
  47688. return JS_EXCEPTION;
  47689. if (res) {
  47690. if (JS_SetProperty(ctx, this_val, JS_ATOM_Symbol_toStringTag, js_dup(val)) < 0)
  47691. return JS_EXCEPTION;
  47692. } else {
  47693. if (JS_DefinePropertyValue(ctx, this_val, JS_ATOM_Symbol_toStringTag, js_dup(val), JS_PROP_C_W_E) < 0)
  47694. return JS_EXCEPTION;
  47695. }
  47696. return JS_UNDEFINED;
  47697. }
  47698. static void js_iterator_helper_finalizer(JSRuntime *rt, JSValueConst val)
  47699. {
  47700. JSObject *p = JS_VALUE_GET_OBJ(val);
  47701. JSIteratorHelperData *it = p->u.iterator_helper_data;
  47702. if (it) {
  47703. JS_FreeValueRT(rt, it->obj);
  47704. JS_FreeValueRT(rt, it->func);
  47705. JS_FreeValueRT(rt, it->next);
  47706. JS_FreeValueRT(rt, it->inner);
  47707. js_free_rt(rt, it);
  47708. }
  47709. }
  47710. static void js_iterator_helper_mark(JSRuntime *rt, JSValueConst val,
  47711. JS_MarkFunc *mark_func)
  47712. {
  47713. JSObject *p = JS_VALUE_GET_OBJ(val);
  47714. JSIteratorHelperData *it = p->u.iterator_helper_data;
  47715. if (it) {
  47716. JS_MarkValue(rt, it->obj, mark_func);
  47717. JS_MarkValue(rt, it->func, mark_func);
  47718. JS_MarkValue(rt, it->next, mark_func);
  47719. JS_MarkValue(rt, it->inner, mark_func);
  47720. }
  47721. }
  47722. static JSValue js_iterator_helper_next(JSContext *ctx, JSValueConst this_val,
  47723. int argc, JSValueConst *argv,
  47724. int *pdone, int magic)
  47725. {
  47726. JSIteratorHelperData *it;
  47727. JSValue ret;
  47728. *pdone = false;
  47729. it = JS_GetOpaque2(ctx, this_val, JS_CLASS_ITERATOR_HELPER);
  47730. if (!it)
  47731. return JS_EXCEPTION;
  47732. if (it->executing)
  47733. return JS_ThrowTypeError(ctx, "cannot invoke a running iterator");
  47734. if (it->done) {
  47735. *pdone = true;
  47736. return JS_UNDEFINED;
  47737. }
  47738. it->executing = 1;
  47739. switch (it->kind) {
  47740. case JS_ITERATOR_HELPER_KIND_DROP:
  47741. {
  47742. JSValue item, method;
  47743. if (magic == GEN_MAGIC_NEXT) {
  47744. method = js_dup(it->next);
  47745. } else {
  47746. method = JS_GetProperty(ctx, it->obj, JS_ATOM_return);
  47747. if (JS_IsException(method))
  47748. goto fail;
  47749. }
  47750. while (it->count > 0) {
  47751. it->count--;
  47752. item = JS_IteratorNext(ctx, it->obj, method, 0, NULL, pdone);
  47753. if (JS_IsException(item)) {
  47754. JS_FreeValue(ctx, method);
  47755. goto fail;
  47756. }
  47757. JS_FreeValue(ctx, item);
  47758. if (magic == GEN_MAGIC_RETURN)
  47759. *pdone = true;
  47760. if (*pdone) {
  47761. JS_FreeValue(ctx, method);
  47762. ret = JS_UNDEFINED;
  47763. goto done;
  47764. }
  47765. }
  47766. item = JS_IteratorNext(ctx, it->obj, method, 0, NULL, pdone);
  47767. JS_FreeValue(ctx, method);
  47768. if (JS_IsException(item))
  47769. goto fail;
  47770. ret = item;
  47771. goto done;
  47772. }
  47773. break;
  47774. case JS_ITERATOR_HELPER_KIND_FILTER:
  47775. {
  47776. JSValue item, method, selected, index_val;
  47777. JSValueConst args[2];
  47778. if (magic == GEN_MAGIC_NEXT) {
  47779. method = js_dup(it->next);
  47780. } else {
  47781. method = JS_GetProperty(ctx, it->obj, JS_ATOM_return);
  47782. if (JS_IsException(method))
  47783. goto fail;
  47784. }
  47785. filter_again:
  47786. item = JS_IteratorNext(ctx, it->obj, method, 0, NULL, pdone);
  47787. if (JS_IsException(item)) {
  47788. JS_FreeValue(ctx, method);
  47789. goto fail;
  47790. }
  47791. if (*pdone || magic == GEN_MAGIC_RETURN) {
  47792. JS_FreeValue(ctx, method);
  47793. ret = item;
  47794. goto done;
  47795. }
  47796. index_val = js_int64(it->count++);
  47797. args[0] = item;
  47798. args[1] = index_val;
  47799. selected = JS_Call(ctx, it->func, JS_UNDEFINED, countof(args), args);
  47800. JS_FreeValue(ctx, index_val);
  47801. if (JS_IsException(selected)) {
  47802. JS_FreeValue(ctx, method);
  47803. goto fail;
  47804. }
  47805. if (JS_ToBoolFree(ctx, selected)) {
  47806. JS_FreeValue(ctx, method);
  47807. ret = item;
  47808. goto done;
  47809. }
  47810. goto filter_again;
  47811. }
  47812. break;
  47813. case JS_ITERATOR_HELPER_KIND_FLAT_MAP:
  47814. {
  47815. JSValue item, method, index_val, iter;
  47816. JSValueConst args[2];
  47817. flat_map_again:
  47818. if (JS_IsUndefined(it->inner)) {
  47819. if (magic == GEN_MAGIC_NEXT) {
  47820. method = js_dup(it->next);
  47821. } else {
  47822. method = JS_GetProperty(ctx, it->obj, JS_ATOM_return);
  47823. if (JS_IsException(method))
  47824. goto fail;
  47825. }
  47826. item = JS_IteratorNext(ctx, it->obj, method, 0, NULL, pdone);
  47827. JS_FreeValue(ctx, method);
  47828. if (JS_IsException(item))
  47829. goto fail;
  47830. if (*pdone || magic == GEN_MAGIC_RETURN) {
  47831. ret = item;
  47832. goto done;
  47833. }
  47834. index_val = js_int64(it->count++);
  47835. args[0] = item;
  47836. args[1] = index_val;
  47837. ret = JS_Call(ctx, it->func, JS_UNDEFINED, countof(args), args);
  47838. JS_FreeValue(ctx, item);
  47839. JS_FreeValue(ctx, index_val);
  47840. if (JS_IsException(ret))
  47841. goto fail;
  47842. if (!JS_IsObject(ret)) {
  47843. JS_FreeValue(ctx, ret);
  47844. JS_ThrowTypeError(ctx, "not an object");
  47845. goto fail;
  47846. }
  47847. method = JS_GetProperty(ctx, ret, JS_ATOM_Symbol_iterator);
  47848. if (JS_IsException(method)) {
  47849. JS_FreeValue(ctx, ret);
  47850. goto fail;
  47851. }
  47852. if (JS_IsNull(method) || JS_IsUndefined(method)) {
  47853. JS_FreeValue(ctx, method);
  47854. iter = ret;
  47855. } else {
  47856. iter = JS_GetIterator2(ctx, ret, method);
  47857. JS_FreeValue(ctx, method);
  47858. JS_FreeValue(ctx, ret);
  47859. if (JS_IsException(iter))
  47860. goto fail;
  47861. }
  47862. it->inner = iter;
  47863. }
  47864. if (magic == GEN_MAGIC_NEXT)
  47865. method = JS_GetProperty(ctx, it->inner, JS_ATOM_next);
  47866. else
  47867. method = JS_GetProperty(ctx, it->inner, JS_ATOM_return);
  47868. if (JS_IsException(method)) {
  47869. inner_fail:
  47870. JS_IteratorClose(ctx, it->inner, false);
  47871. JS_FreeValue(ctx, it->inner);
  47872. it->inner = JS_UNDEFINED;
  47873. goto fail;
  47874. }
  47875. if (magic == GEN_MAGIC_RETURN && (JS_IsUndefined(method) || JS_IsNull(method))) {
  47876. goto inner_end;
  47877. } else {
  47878. item = JS_IteratorNext(ctx, it->inner, method, 0, NULL, pdone);
  47879. JS_FreeValue(ctx, method);
  47880. if (JS_IsException(item))
  47881. goto inner_fail;
  47882. }
  47883. if (*pdone) {
  47884. inner_end:
  47885. *pdone = false; // The outer iterator must continue.
  47886. JS_IteratorClose(ctx, it->inner, false);
  47887. JS_FreeValue(ctx, it->inner);
  47888. it->inner = JS_UNDEFINED;
  47889. goto flat_map_again;
  47890. }
  47891. ret = item;
  47892. goto done;
  47893. }
  47894. break;
  47895. case JS_ITERATOR_HELPER_KIND_MAP:
  47896. {
  47897. JSValue item, method, index_val;
  47898. JSValueConst args[2];
  47899. if (magic == GEN_MAGIC_NEXT) {
  47900. method = js_dup(it->next);
  47901. } else {
  47902. method = JS_GetProperty(ctx, it->obj, JS_ATOM_return);
  47903. if (JS_IsException(method))
  47904. goto fail;
  47905. }
  47906. item = JS_IteratorNext(ctx, it->obj, method, 0, NULL, pdone);
  47907. JS_FreeValue(ctx, method);
  47908. if (JS_IsException(item))
  47909. goto fail;
  47910. if (*pdone || magic == GEN_MAGIC_RETURN) {
  47911. ret = item;
  47912. goto done;
  47913. }
  47914. index_val = js_int64(it->count++);
  47915. args[0] = item;
  47916. args[1] = index_val;
  47917. ret = JS_Call(ctx, it->func, JS_UNDEFINED, countof(args), args);
  47918. JS_FreeValue(ctx, index_val);
  47919. if (JS_IsException(ret))
  47920. goto fail;
  47921. goto done;
  47922. }
  47923. break;
  47924. case JS_ITERATOR_HELPER_KIND_TAKE:
  47925. {
  47926. JSValue item, method;
  47927. if (it->count > 0) {
  47928. if (magic == GEN_MAGIC_NEXT) {
  47929. method = js_dup(it->next);
  47930. } else {
  47931. method = JS_GetProperty(ctx, it->obj, JS_ATOM_return);
  47932. if (JS_IsException(method))
  47933. goto fail;
  47934. }
  47935. it->count--;
  47936. item = JS_IteratorNext(ctx, it->obj, method, 0, NULL, pdone);
  47937. JS_FreeValue(ctx, method);
  47938. if (JS_IsException(item))
  47939. goto fail;
  47940. ret = item;
  47941. goto done;
  47942. }
  47943. *pdone = true;
  47944. if (JS_IteratorClose(ctx, it->obj, false))
  47945. ret = JS_EXCEPTION;
  47946. else
  47947. ret = JS_UNDEFINED;
  47948. goto done;
  47949. }
  47950. break;
  47951. default:
  47952. abort();
  47953. }
  47954. done:
  47955. it->done = magic == GEN_MAGIC_NEXT ? *pdone : 1;
  47956. it->executing = 0;
  47957. return ret;
  47958. fail:
  47959. /* close the iterator object, preserving pending exception */
  47960. JS_IteratorClose(ctx, it->obj, true);
  47961. ret = JS_EXCEPTION;
  47962. goto done;
  47963. }
  47964. static const JSCFunctionListEntry js_iterator_funcs[] = {
  47965. JS_CFUNC_DEF("from", 1, js_iterator_from ),
  47966. };
  47967. static const JSCFunctionListEntry js_iterator_proto_funcs[] = {
  47968. JS_CFUNC_MAGIC_DEF("drop", 1, js_create_iterator_helper, JS_ITERATOR_HELPER_KIND_DROP ),
  47969. JS_CFUNC_MAGIC_DEF("filter", 1, js_create_iterator_helper, JS_ITERATOR_HELPER_KIND_FILTER ),
  47970. JS_CFUNC_MAGIC_DEF("flatMap", 1, js_create_iterator_helper, JS_ITERATOR_HELPER_KIND_FLAT_MAP ),
  47971. JS_CFUNC_MAGIC_DEF("map", 1, js_create_iterator_helper, JS_ITERATOR_HELPER_KIND_MAP ),
  47972. JS_CFUNC_MAGIC_DEF("take", 1, js_create_iterator_helper, JS_ITERATOR_HELPER_KIND_TAKE ),
  47973. JS_CFUNC_MAGIC_DEF("every", 1, js_iterator_proto_func, JS_ITERATOR_HELPER_KIND_EVERY ),
  47974. JS_CFUNC_MAGIC_DEF("find", 1, js_iterator_proto_func, JS_ITERATOR_HELPER_KIND_FIND),
  47975. JS_CFUNC_MAGIC_DEF("forEach", 1, js_iterator_proto_func, JS_ITERATOR_HELPER_KIND_FOR_EACH ),
  47976. JS_CFUNC_MAGIC_DEF("some", 1, js_iterator_proto_func, JS_ITERATOR_HELPER_KIND_SOME ),
  47977. JS_CFUNC_DEF("reduce", 1, js_iterator_proto_reduce ),
  47978. JS_CFUNC_DEF("toArray", 0, js_iterator_proto_toArray ),
  47979. JS_CFUNC_DEF("[Symbol.iterator]", 0, js_iterator_proto_iterator ),
  47980. JS_CGETSET_DEF("[Symbol.toStringTag]", js_iterator_proto_get_toStringTag, js_iterator_proto_set_toStringTag),
  47981. };
  47982. static const JSCFunctionListEntry js_iterator_helper_proto_funcs[] = {
  47983. JS_ITERATOR_NEXT_DEF("next", 0, js_iterator_helper_next, GEN_MAGIC_NEXT ),
  47984. JS_ITERATOR_NEXT_DEF("return", 0, js_iterator_helper_next, GEN_MAGIC_RETURN ),
  47985. JS_PROP_STRING_DEF("[Symbol.toStringTag]", "Iterator Helper", JS_PROP_CONFIGURABLE ),
  47986. };
  47987. static const JSCFunctionListEntry js_array_proto_funcs[] = {
  47988. JS_CFUNC_DEF("at", 1, js_array_at ),
  47989. JS_CFUNC_DEF("with", 2, js_array_with ),
  47990. JS_CFUNC_DEF("concat", 1, js_array_concat ),
  47991. JS_CFUNC_MAGIC_DEF("every", 1, js_array_every, special_every ),
  47992. JS_CFUNC_MAGIC_DEF("some", 1, js_array_every, special_some ),
  47993. JS_CFUNC_MAGIC_DEF("forEach", 1, js_array_every, special_forEach ),
  47994. JS_CFUNC_MAGIC_DEF("map", 1, js_array_every, special_map ),
  47995. JS_CFUNC_MAGIC_DEF("filter", 1, js_array_every, special_filter ),
  47996. JS_CFUNC_MAGIC_DEF("reduce", 1, js_array_reduce, special_reduce ),
  47997. JS_CFUNC_MAGIC_DEF("reduceRight", 1, js_array_reduce, special_reduceRight ),
  47998. JS_CFUNC_DEF("fill", 1, js_array_fill ),
  47999. JS_CFUNC_MAGIC_DEF("find", 1, js_array_find, ArrayFind ),
  48000. JS_CFUNC_MAGIC_DEF("findIndex", 1, js_array_find, ArrayFindIndex ),
  48001. JS_CFUNC_MAGIC_DEF("findLast", 1, js_array_find, ArrayFindLast ),
  48002. JS_CFUNC_MAGIC_DEF("findLastIndex", 1, js_array_find, ArrayFindLastIndex ),
  48003. JS_CFUNC_DEF("indexOf", 1, js_array_indexOf ),
  48004. JS_CFUNC_DEF("lastIndexOf", 1, js_array_lastIndexOf ),
  48005. JS_CFUNC_DEF("includes", 1, js_array_includes ),
  48006. JS_CFUNC_MAGIC_DEF("join", 1, js_array_join, 0 ),
  48007. JS_CFUNC_DEF("toString", 0, js_array_toString ),
  48008. JS_CFUNC_MAGIC_DEF("toLocaleString", 0, js_array_join, 1 ),
  48009. JS_CFUNC_MAGIC_DEF("pop", 0, js_array_pop, 0 ),
  48010. JS_CFUNC_MAGIC_DEF("push", 1, js_array_push, 0 ),
  48011. JS_CFUNC_MAGIC_DEF("shift", 0, js_array_pop, 1 ),
  48012. JS_CFUNC_MAGIC_DEF("unshift", 1, js_array_push, 1 ),
  48013. JS_CFUNC_DEF("reverse", 0, js_array_reverse ),
  48014. JS_CFUNC_DEF("toReversed", 0, js_array_toReversed ),
  48015. JS_CFUNC_DEF("sort", 1, js_array_sort ),
  48016. JS_CFUNC_DEF("toSorted", 1, js_array_toSorted ),
  48017. JS_CFUNC_MAGIC_DEF("slice", 2, js_array_slice, 0 ),
  48018. JS_CFUNC_MAGIC_DEF("splice", 2, js_array_slice, 1 ),
  48019. JS_CFUNC_DEF("toSpliced", 2, js_array_toSpliced ),
  48020. JS_CFUNC_DEF("copyWithin", 2, js_array_copyWithin ),
  48021. JS_CFUNC_MAGIC_DEF("flatMap", 1, js_array_flatten, 1 ),
  48022. JS_CFUNC_MAGIC_DEF("flat", 0, js_array_flatten, 0 ),
  48023. JS_CFUNC_MAGIC_DEF("values", 0, js_create_array_iterator, JS_ITERATOR_KIND_VALUE ),
  48024. JS_ALIAS_DEF("[Symbol.iterator]", "values" ),
  48025. JS_CFUNC_MAGIC_DEF("keys", 0, js_create_array_iterator, JS_ITERATOR_KIND_KEY ),
  48026. JS_CFUNC_MAGIC_DEF("entries", 0, js_create_array_iterator, JS_ITERATOR_KIND_KEY_AND_VALUE ),
  48027. };
  48028. static const JSCFunctionListEntry js_array_iterator_proto_funcs[] = {
  48029. JS_ITERATOR_NEXT_DEF("next", 0, js_array_iterator_next, 0 ),
  48030. JS_PROP_STRING_DEF("[Symbol.toStringTag]", "Array Iterator", JS_PROP_CONFIGURABLE ),
  48031. };
  48032. /* Number */
  48033. static JSValue js_number_constructor(JSContext *ctx, JSValueConst new_target,
  48034. int argc, JSValueConst *argv)
  48035. {
  48036. JSValue val, obj;
  48037. if (argc == 0) {
  48038. val = js_int32(0);
  48039. } else {
  48040. val = JS_ToNumeric(ctx, argv[0]);
  48041. if (JS_IsException(val))
  48042. return val;
  48043. switch(JS_VALUE_GET_TAG(val)) {
  48044. case JS_TAG_BIG_INT:
  48045. {
  48046. JSBigInt *p = JS_VALUE_GET_PTR(val);
  48047. double d;
  48048. bf_get_float64(&p->num, &d, BF_RNDN);
  48049. JS_FreeValue(ctx, val);
  48050. val = js_float64(d);
  48051. }
  48052. break;
  48053. default:
  48054. break;
  48055. }
  48056. }
  48057. if (!JS_IsUndefined(new_target)) {
  48058. obj = js_create_from_ctor(ctx, new_target, JS_CLASS_NUMBER);
  48059. if (!JS_IsException(obj))
  48060. JS_SetObjectData(ctx, obj, val);
  48061. return obj;
  48062. } else {
  48063. return val;
  48064. }
  48065. }
  48066. static JSValue js_number_isNaN(JSContext *ctx, JSValueConst this_val,
  48067. int argc, JSValueConst *argv)
  48068. {
  48069. if (!JS_IsNumber(argv[0]))
  48070. return JS_FALSE;
  48071. return js_global_isNaN(ctx, this_val, argc, argv);
  48072. }
  48073. static JSValue js_number_isFinite(JSContext *ctx, JSValueConst this_val,
  48074. int argc, JSValueConst *argv)
  48075. {
  48076. if (!JS_IsNumber(argv[0]))
  48077. return JS_FALSE;
  48078. return js_global_isFinite(ctx, this_val, argc, argv);
  48079. }
  48080. static JSValue js_number_isInteger(JSContext *ctx, JSValueConst this_val,
  48081. int argc, JSValueConst *argv)
  48082. {
  48083. int ret;
  48084. ret = JS_NumberIsInteger(ctx, argv[0]);
  48085. if (ret < 0)
  48086. return JS_EXCEPTION;
  48087. else
  48088. return js_bool(ret);
  48089. }
  48090. static JSValue js_number_isSafeInteger(JSContext *ctx, JSValueConst this_val,
  48091. int argc, JSValueConst *argv)
  48092. {
  48093. double d;
  48094. if (!JS_IsNumber(argv[0]))
  48095. return JS_FALSE;
  48096. if (unlikely(JS_ToFloat64(ctx, &d, argv[0])))
  48097. return JS_EXCEPTION;
  48098. return js_bool(is_safe_integer(d));
  48099. }
  48100. static const JSCFunctionListEntry js_number_funcs[] = {
  48101. /* global ParseInt and parseFloat should be defined already or delayed */
  48102. JS_ALIAS_BASE_DEF("parseInt", "parseInt", 0 ),
  48103. JS_ALIAS_BASE_DEF("parseFloat", "parseFloat", 0 ),
  48104. JS_CFUNC_DEF("isNaN", 1, js_number_isNaN ),
  48105. JS_CFUNC_DEF("isFinite", 1, js_number_isFinite ),
  48106. JS_CFUNC_DEF("isInteger", 1, js_number_isInteger ),
  48107. JS_CFUNC_DEF("isSafeInteger", 1, js_number_isSafeInteger ),
  48108. JS_PROP_DOUBLE_DEF("MAX_VALUE", 1.7976931348623157e+308, 0 ),
  48109. JS_PROP_DOUBLE_DEF("MIN_VALUE", 5e-324, 0 ),
  48110. JS_PROP_U2D_DEF("NaN", 0x7FF8ull<<48, 0 ), // workaround for msvc
  48111. JS_PROP_DOUBLE_DEF("NEGATIVE_INFINITY", -INFINITY, 0 ),
  48112. JS_PROP_DOUBLE_DEF("POSITIVE_INFINITY", INFINITY, 0 ),
  48113. JS_PROP_DOUBLE_DEF("EPSILON", 2.220446049250313e-16, 0 ), /* ES6 */
  48114. JS_PROP_DOUBLE_DEF("MAX_SAFE_INTEGER", 9007199254740991.0, 0 ), /* ES6 */
  48115. JS_PROP_DOUBLE_DEF("MIN_SAFE_INTEGER", -9007199254740991.0, 0 ), /* ES6 */
  48116. };
  48117. static JSValue js_thisNumberValue(JSContext *ctx, JSValueConst this_val)
  48118. {
  48119. if (JS_IsNumber(this_val))
  48120. return js_dup(this_val);
  48121. if (JS_VALUE_GET_TAG(this_val) == JS_TAG_OBJECT) {
  48122. JSObject *p = JS_VALUE_GET_OBJ(this_val);
  48123. if (p->class_id == JS_CLASS_NUMBER) {
  48124. if (JS_IsNumber(p->u.object_data))
  48125. return js_dup(p->u.object_data);
  48126. }
  48127. }
  48128. return JS_ThrowTypeError(ctx, "not a number");
  48129. }
  48130. static JSValue js_number_valueOf(JSContext *ctx, JSValueConst this_val,
  48131. int argc, JSValueConst *argv)
  48132. {
  48133. return js_thisNumberValue(ctx, this_val);
  48134. }
  48135. static int js_get_radix(JSContext *ctx, JSValueConst val)
  48136. {
  48137. int radix;
  48138. if (JS_ToInt32Sat(ctx, &radix, val))
  48139. return -1;
  48140. if (radix < 2 || radix > 36) {
  48141. JS_ThrowRangeError(ctx, "toString() radix argument must be between 2 and 36");
  48142. return -1;
  48143. }
  48144. return radix;
  48145. }
  48146. static JSValue js_number_toString(JSContext *ctx, JSValueConst this_val,
  48147. int argc, JSValueConst *argv, int magic)
  48148. {
  48149. char buf[72];
  48150. JSValue val;
  48151. int base;
  48152. double d;
  48153. val = js_thisNumberValue(ctx, this_val);
  48154. if (JS_IsException(val))
  48155. return val;
  48156. if (magic || JS_IsUndefined(argv[0])) {
  48157. if (JS_VALUE_GET_TAG(val) == JS_TAG_INT) {
  48158. size_t len = i32toa(buf, JS_VALUE_GET_INT(val));
  48159. return js_new_string8_len(ctx, buf, len);
  48160. }
  48161. base = 10;
  48162. } else {
  48163. base = js_get_radix(ctx, argv[0]);
  48164. if (base < 0) {
  48165. JS_FreeValue(ctx, val);
  48166. return JS_EXCEPTION;
  48167. }
  48168. }
  48169. if (JS_VALUE_GET_TAG(val) == JS_TAG_INT) {
  48170. size_t len = i32toa_radix(buf, JS_VALUE_GET_INT(val), base);
  48171. return js_new_string8_len(ctx, buf, len);
  48172. }
  48173. if (JS_ToFloat64Free(ctx, &d, val))
  48174. return JS_EXCEPTION;
  48175. if (base != 10)
  48176. return js_dtoa_radix(ctx, d, base);
  48177. return js_dtoa(ctx, d, 0, JS_DTOA_TOSTRING);
  48178. }
  48179. static JSValue js_number_toFixed(JSContext *ctx, JSValueConst this_val,
  48180. int argc, JSValueConst *argv)
  48181. {
  48182. JSValue val;
  48183. int f;
  48184. double d;
  48185. val = js_thisNumberValue(ctx, this_val);
  48186. if (JS_IsException(val))
  48187. return val;
  48188. if (JS_ToFloat64Free(ctx, &d, val))
  48189. return JS_EXCEPTION;
  48190. if (JS_ToInt32Sat(ctx, &f, argv[0]))
  48191. return JS_EXCEPTION;
  48192. if (f < 0 || f > 100) {
  48193. return JS_ThrowRangeError(ctx, "toFixed() digits argument must be between 0 and 100");
  48194. }
  48195. if (fabs(d) >= 1e21) {
  48196. // use ToString(d)
  48197. return js_dtoa(ctx, d, 0, JS_DTOA_TOSTRING);
  48198. } else {
  48199. return js_dtoa(ctx, d, f, JS_DTOA_FIXED);
  48200. }
  48201. }
  48202. static JSValue js_number_toExponential(JSContext *ctx, JSValueConst this_val,
  48203. int argc, JSValueConst *argv)
  48204. {
  48205. JSValue val;
  48206. double d;
  48207. int f;
  48208. val = js_thisNumberValue(ctx, this_val);
  48209. if (JS_IsException(val))
  48210. return val;
  48211. if (JS_ToFloat64Free(ctx, &d, val))
  48212. return JS_EXCEPTION;
  48213. if (JS_ToInt32Sat(ctx, &f, argv[0]))
  48214. return JS_EXCEPTION;
  48215. if (!isfinite(d))
  48216. return js_dtoa_infinite(ctx, d);
  48217. if (!JS_IsUndefined(argv[0])) {
  48218. if (f < 0 || f > 100) {
  48219. return JS_ThrowRangeError(ctx, "toExponential() argument must be between 0 and 100");
  48220. }
  48221. f += 1; /* number of significant digits between 1 and 101 */
  48222. }
  48223. return js_dtoa(ctx, d, f, JS_DTOA_EXPONENTIAL);
  48224. }
  48225. static JSValue js_number_toPrecision(JSContext *ctx, JSValueConst this_val,
  48226. int argc, JSValueConst *argv)
  48227. {
  48228. JSValue val;
  48229. int p;
  48230. double d;
  48231. val = js_thisNumberValue(ctx, this_val);
  48232. if (JS_IsException(val))
  48233. return val;
  48234. if (JS_ToFloat64Free(ctx, &d, val))
  48235. return JS_EXCEPTION;
  48236. if (JS_IsUndefined(argv[0]))
  48237. return js_dtoa(ctx, d, 0, JS_DTOA_TOSTRING);
  48238. if (JS_ToInt32Sat(ctx, &p, argv[0]))
  48239. return JS_EXCEPTION;
  48240. if (!isfinite(d))
  48241. return js_dtoa_infinite(ctx, d);
  48242. if (p < 1 || p > 100) {
  48243. return JS_ThrowRangeError(ctx, "toPrecision() argument must be between 1 and 100");
  48244. }
  48245. return js_dtoa(ctx, d, p, JS_DTOA_PRECISION);
  48246. }
  48247. static const JSCFunctionListEntry js_number_proto_funcs[] = {
  48248. JS_CFUNC_DEF("toExponential", 1, js_number_toExponential ),
  48249. JS_CFUNC_DEF("toFixed", 1, js_number_toFixed ),
  48250. JS_CFUNC_DEF("toPrecision", 1, js_number_toPrecision ),
  48251. JS_CFUNC_MAGIC_DEF("toString", 1, js_number_toString, 0 ),
  48252. JS_CFUNC_MAGIC_DEF("toLocaleString", 0, js_number_toString, 1 ),
  48253. JS_CFUNC_DEF("valueOf", 0, js_number_valueOf ),
  48254. };
  48255. static JSValue js_parseInt(JSContext *ctx, JSValueConst this_val,
  48256. int argc, JSValueConst *argv)
  48257. {
  48258. const char *str;
  48259. int radix, flags;
  48260. JSValue ret;
  48261. size_t len;
  48262. str = JS_ToCStringLen(ctx, &len, argv[0]);
  48263. if (!str)
  48264. return JS_EXCEPTION;
  48265. if (JS_ToInt32(ctx, &radix, argv[1])) {
  48266. JS_FreeCString(ctx, str);
  48267. return JS_EXCEPTION;
  48268. }
  48269. flags = ATOD_TRIM_SPACES;
  48270. if (radix == 0) {
  48271. flags |= ATOD_ACCEPT_HEX_PREFIX; // Only 0x and 0X are supported
  48272. radix = 10;
  48273. }
  48274. ret = js_atof(ctx, str, len, NULL, radix, flags);
  48275. JS_FreeCString(ctx, str);
  48276. return ret;
  48277. }
  48278. static JSValue js_parseFloat(JSContext *ctx, JSValueConst this_val,
  48279. int argc, JSValueConst *argv)
  48280. {
  48281. const char *str;
  48282. JSValue ret;
  48283. int flags;
  48284. size_t len;
  48285. str = JS_ToCStringLen(ctx, &len, argv[0]);
  48286. if (!str)
  48287. return JS_EXCEPTION;
  48288. flags = ATOD_TRIM_SPACES | ATOD_ACCEPT_FLOAT | ATOD_ACCEPT_INFINITY;
  48289. ret = js_atof(ctx, str, len, NULL, 10, flags);
  48290. JS_FreeCString(ctx, str);
  48291. return ret;
  48292. }
  48293. /* Boolean */
  48294. static JSValue js_boolean_constructor(JSContext *ctx, JSValueConst new_target,
  48295. int argc, JSValueConst *argv)
  48296. {
  48297. JSValue val, obj;
  48298. val = js_bool(JS_ToBool(ctx, argv[0]));
  48299. if (!JS_IsUndefined(new_target)) {
  48300. obj = js_create_from_ctor(ctx, new_target, JS_CLASS_BOOLEAN);
  48301. if (!JS_IsException(obj))
  48302. JS_SetObjectData(ctx, obj, val);
  48303. return obj;
  48304. } else {
  48305. return val;
  48306. }
  48307. }
  48308. static JSValue js_thisBooleanValue(JSContext *ctx, JSValueConst this_val)
  48309. {
  48310. if (JS_VALUE_GET_TAG(this_val) == JS_TAG_BOOL)
  48311. return js_dup(this_val);
  48312. if (JS_VALUE_GET_TAG(this_val) == JS_TAG_OBJECT) {
  48313. JSObject *p = JS_VALUE_GET_OBJ(this_val);
  48314. if (p->class_id == JS_CLASS_BOOLEAN) {
  48315. if (JS_VALUE_GET_TAG(p->u.object_data) == JS_TAG_BOOL)
  48316. return p->u.object_data;
  48317. }
  48318. }
  48319. return JS_ThrowTypeError(ctx, "not a boolean");
  48320. }
  48321. static JSValue js_boolean_toString(JSContext *ctx, JSValueConst this_val,
  48322. int argc, JSValueConst *argv)
  48323. {
  48324. JSValue val = js_thisBooleanValue(ctx, this_val);
  48325. if (JS_IsException(val))
  48326. return val;
  48327. return JS_AtomToString(ctx, JS_VALUE_GET_BOOL(val) ?
  48328. JS_ATOM_true : JS_ATOM_false);
  48329. }
  48330. static JSValue js_boolean_valueOf(JSContext *ctx, JSValueConst this_val,
  48331. int argc, JSValueConst *argv)
  48332. {
  48333. return js_thisBooleanValue(ctx, this_val);
  48334. }
  48335. static const JSCFunctionListEntry js_boolean_proto_funcs[] = {
  48336. JS_CFUNC_DEF("toString", 0, js_boolean_toString ),
  48337. JS_CFUNC_DEF("valueOf", 0, js_boolean_valueOf ),
  48338. };
  48339. /* String */
  48340. static int js_string_get_own_property(JSContext *ctx,
  48341. JSPropertyDescriptor *desc,
  48342. JSValueConst obj, JSAtom prop)
  48343. {
  48344. JSObject *p;
  48345. JSString *p1;
  48346. uint32_t idx, ch;
  48347. /* This is a class exotic method: obj class_id is JS_CLASS_STRING */
  48348. if (__JS_AtomIsTaggedInt(prop)) {
  48349. p = JS_VALUE_GET_OBJ(obj);
  48350. if (JS_VALUE_GET_TAG(p->u.object_data) == JS_TAG_STRING) {
  48351. p1 = JS_VALUE_GET_STRING(p->u.object_data);
  48352. idx = __JS_AtomToUInt32(prop);
  48353. if (idx < p1->len) {
  48354. if (desc) {
  48355. ch = string_get(p1, idx);
  48356. desc->flags = JS_PROP_ENUMERABLE;
  48357. desc->value = js_new_string_char(ctx, ch);
  48358. desc->getter = JS_UNDEFINED;
  48359. desc->setter = JS_UNDEFINED;
  48360. }
  48361. return true;
  48362. }
  48363. }
  48364. }
  48365. return false;
  48366. }
  48367. static int js_string_define_own_property(JSContext *ctx,
  48368. JSValueConst this_obj,
  48369. JSAtom prop, JSValueConst val,
  48370. JSValueConst getter,
  48371. JSValueConst setter, int flags)
  48372. {
  48373. uint32_t idx;
  48374. JSObject *p;
  48375. JSString *p1, *p2;
  48376. if (__JS_AtomIsTaggedInt(prop)) {
  48377. idx = __JS_AtomToUInt32(prop);
  48378. p = JS_VALUE_GET_OBJ(this_obj);
  48379. if (JS_VALUE_GET_TAG(p->u.object_data) != JS_TAG_STRING)
  48380. goto def;
  48381. p1 = JS_VALUE_GET_STRING(p->u.object_data);
  48382. if (idx >= p1->len)
  48383. goto def;
  48384. if (!check_define_prop_flags(JS_PROP_ENUMERABLE, flags))
  48385. goto fail;
  48386. /* check that the same value is configured */
  48387. if (flags & JS_PROP_HAS_VALUE) {
  48388. if (JS_VALUE_GET_TAG(val) != JS_TAG_STRING)
  48389. goto fail;
  48390. p2 = JS_VALUE_GET_STRING(val);
  48391. if (p2->len != 1)
  48392. goto fail;
  48393. if (string_get(p1, idx) != string_get(p2, 0)) {
  48394. fail:
  48395. return JS_ThrowTypeErrorOrFalse(ctx, flags, "property is not configurable");
  48396. }
  48397. }
  48398. return true;
  48399. } else {
  48400. def:
  48401. return JS_DefineProperty(ctx, this_obj, prop, val, getter, setter,
  48402. flags | JS_PROP_NO_EXOTIC);
  48403. }
  48404. }
  48405. static int js_string_delete_property(JSContext *ctx,
  48406. JSValueConst obj, JSAtom prop)
  48407. {
  48408. uint32_t idx;
  48409. if (__JS_AtomIsTaggedInt(prop)) {
  48410. idx = __JS_AtomToUInt32(prop);
  48411. if (idx < js_string_obj_get_length(ctx, obj)) {
  48412. return false;
  48413. }
  48414. }
  48415. return true;
  48416. }
  48417. static const JSClassExoticMethods js_string_exotic_methods = {
  48418. .get_own_property = js_string_get_own_property,
  48419. .define_own_property = js_string_define_own_property,
  48420. .delete_property = js_string_delete_property,
  48421. };
  48422. static JSValue js_string_constructor(JSContext *ctx, JSValueConst new_target,
  48423. int argc, JSValueConst *argv)
  48424. {
  48425. JSValue val, obj;
  48426. if (argc == 0) {
  48427. val = JS_AtomToString(ctx, JS_ATOM_empty_string);
  48428. } else {
  48429. if (JS_IsUndefined(new_target) && JS_IsSymbol(argv[0])) {
  48430. JSAtomStruct *p = JS_VALUE_GET_PTR(argv[0]);
  48431. val = JS_ConcatString3(ctx, "Symbol(", JS_AtomToString(ctx, js_get_atom_index(ctx->rt, p)), ")");
  48432. } else {
  48433. val = JS_ToString(ctx, argv[0]);
  48434. }
  48435. if (JS_IsException(val))
  48436. return val;
  48437. }
  48438. if (!JS_IsUndefined(new_target)) {
  48439. JSString *p1 = JS_VALUE_GET_STRING(val);
  48440. obj = js_create_from_ctor(ctx, new_target, JS_CLASS_STRING);
  48441. if (!JS_IsException(obj)) {
  48442. JS_SetObjectData(ctx, obj, val);
  48443. JS_DefinePropertyValue(ctx, obj, JS_ATOM_length, js_int32(p1->len), 0);
  48444. }
  48445. return obj;
  48446. } else {
  48447. return val;
  48448. }
  48449. }
  48450. static JSValue js_thisStringValue(JSContext *ctx, JSValueConst this_val)
  48451. {
  48452. if (JS_VALUE_GET_TAG(this_val) == JS_TAG_STRING)
  48453. return js_dup(this_val);
  48454. if (JS_VALUE_GET_TAG(this_val) == JS_TAG_OBJECT) {
  48455. JSObject *p = JS_VALUE_GET_OBJ(this_val);
  48456. if (p->class_id == JS_CLASS_STRING) {
  48457. if (JS_VALUE_GET_TAG(p->u.object_data) == JS_TAG_STRING)
  48458. return js_dup(p->u.object_data);
  48459. }
  48460. }
  48461. return JS_ThrowTypeError(ctx, "not a string");
  48462. }
  48463. static JSValue js_string_fromCharCode(JSContext *ctx, JSValueConst this_val,
  48464. int argc, JSValueConst *argv)
  48465. {
  48466. int i;
  48467. StringBuffer b_s, *b = &b_s;
  48468. // shortcut for single argument common case
  48469. if (argc == 1 && JS_VALUE_GET_TAG(argv[0]) == JS_TAG_INT) {
  48470. uint16_t c16 = JS_VALUE_GET_INT(argv[0]);
  48471. return js_new_string_char(ctx, c16);
  48472. }
  48473. string_buffer_init(ctx, b, argc);
  48474. for(i = 0; i < argc; i++) {
  48475. int32_t c;
  48476. if (JS_ToInt32(ctx, &c, argv[i]) || string_buffer_putc16(b, c & 0xffff)) {
  48477. string_buffer_free(b);
  48478. return JS_EXCEPTION;
  48479. }
  48480. }
  48481. return string_buffer_end(b);
  48482. }
  48483. static JSValue js_string_fromCodePoint(JSContext *ctx, JSValueConst this_val,
  48484. int argc, JSValueConst *argv)
  48485. {
  48486. double d;
  48487. int i, c;
  48488. StringBuffer b_s, *b = NULL;
  48489. // shortcut for single argument common case
  48490. if (argc == 1 && JS_VALUE_GET_TAG(argv[0]) == JS_TAG_INT) {
  48491. c = JS_VALUE_GET_INT(argv[0]);
  48492. if (c < 0 || c > 0x10ffff)
  48493. goto range_error;
  48494. if (c <= 0xffff) {
  48495. return js_new_string_char(ctx, c);
  48496. } else {
  48497. uint16_t c16[2];
  48498. c16[0] = get_hi_surrogate(c);
  48499. c16[1] = get_lo_surrogate(c);
  48500. return js_new_string16_len(ctx, c16, 2);
  48501. }
  48502. }
  48503. /* XXX: could pre-compute string length if all arguments are JS_TAG_INT */
  48504. b = &b_s;
  48505. if (string_buffer_init(ctx, b, argc))
  48506. goto fail;
  48507. for(i = 0; i < argc; i++) {
  48508. if (JS_VALUE_GET_TAG(argv[i]) == JS_TAG_INT) {
  48509. c = JS_VALUE_GET_INT(argv[i]);
  48510. if (c < 0 || c > 0x10ffff)
  48511. goto range_error;
  48512. } else {
  48513. if (JS_ToFloat64(ctx, &d, argv[i]))
  48514. goto fail;
  48515. if (!(d >= 0 && d <= 0x10ffff) || (c = (int)d) != d)
  48516. goto range_error;
  48517. }
  48518. if (string_buffer_putc(b, c))
  48519. goto fail;
  48520. }
  48521. return string_buffer_end(b);
  48522. range_error:
  48523. JS_ThrowRangeError(ctx, "invalid code point");
  48524. fail:
  48525. if (b) string_buffer_free(b);
  48526. return JS_EXCEPTION;
  48527. }
  48528. static JSValue js_string_raw(JSContext *ctx, JSValueConst this_val,
  48529. int argc, JSValueConst *argv)
  48530. {
  48531. // raw(temp,...a)
  48532. JSValue cooked, val, raw;
  48533. StringBuffer b_s, *b = &b_s;
  48534. int64_t i, n;
  48535. string_buffer_init(ctx, b, 0);
  48536. raw = JS_UNDEFINED;
  48537. cooked = JS_ToObject(ctx, argv[0]);
  48538. if (JS_IsException(cooked))
  48539. goto exception;
  48540. raw = JS_ToObjectFree(ctx, JS_GetProperty(ctx, cooked, JS_ATOM_raw));
  48541. if (JS_IsException(raw))
  48542. goto exception;
  48543. if (js_get_length64(ctx, &n, raw) < 0)
  48544. goto exception;
  48545. for (i = 0; i < n; i++) {
  48546. val = JS_ToStringFree(ctx, JS_GetPropertyInt64(ctx, raw, i));
  48547. if (JS_IsException(val))
  48548. goto exception;
  48549. string_buffer_concat_value_free(b, val);
  48550. if (i < n - 1 && i + 1 < argc) {
  48551. if (string_buffer_concat_value(b, argv[i + 1]))
  48552. goto exception;
  48553. }
  48554. }
  48555. JS_FreeValue(ctx, cooked);
  48556. JS_FreeValue(ctx, raw);
  48557. return string_buffer_end(b);
  48558. exception:
  48559. JS_FreeValue(ctx, cooked);
  48560. JS_FreeValue(ctx, raw);
  48561. string_buffer_free(b);
  48562. return JS_EXCEPTION;
  48563. }
  48564. /* only used in test262 */
  48565. JSValue js_string_codePointRange(JSContext *ctx, JSValueConst this_val,
  48566. int argc, JSValueConst *argv)
  48567. {
  48568. uint32_t start, end, i, n;
  48569. StringBuffer b_s, *b = &b_s;
  48570. if (JS_ToUint32(ctx, &start, argv[0]) ||
  48571. JS_ToUint32(ctx, &end, argv[1]))
  48572. return JS_EXCEPTION;
  48573. end = min_uint32(end, 0x10ffff + 1);
  48574. if (start > end) {
  48575. start = end;
  48576. }
  48577. n = end - start;
  48578. if (end > 0x10000) {
  48579. n += end - max_uint32(start, 0x10000);
  48580. }
  48581. if (string_buffer_init2(ctx, b, n, end >= 0x100))
  48582. return JS_EXCEPTION;
  48583. for(i = start; i < end; i++) {
  48584. string_buffer_putc(b, i);
  48585. }
  48586. return string_buffer_end(b);
  48587. }
  48588. static JSValue js_string_at(JSContext *ctx, JSValueConst this_val,
  48589. int argc, JSValueConst *argv)
  48590. {
  48591. JSValue val, ret;
  48592. JSString *p;
  48593. int idx, c;
  48594. val = JS_ToStringCheckObject(ctx, this_val);
  48595. if (JS_IsException(val))
  48596. return val;
  48597. p = JS_VALUE_GET_STRING(val);
  48598. if (JS_ToInt32Sat(ctx, &idx, argv[0])) {
  48599. JS_FreeValue(ctx, val);
  48600. return JS_EXCEPTION;
  48601. }
  48602. if (idx < 0)
  48603. idx = p->len + idx;
  48604. if (idx < 0 || idx >= p->len) {
  48605. ret = JS_UNDEFINED;
  48606. } else {
  48607. c = string_get(p, idx);
  48608. ret = js_new_string_char(ctx, c);
  48609. }
  48610. JS_FreeValue(ctx, val);
  48611. return ret;
  48612. }
  48613. static JSValue js_string_charCodeAt(JSContext *ctx, JSValueConst this_val,
  48614. int argc, JSValueConst *argv)
  48615. {
  48616. JSValue val, ret;
  48617. JSString *p;
  48618. int idx, c;
  48619. val = JS_ToStringCheckObject(ctx, this_val);
  48620. if (JS_IsException(val))
  48621. return val;
  48622. p = JS_VALUE_GET_STRING(val);
  48623. if (JS_ToInt32Sat(ctx, &idx, argv[0])) {
  48624. JS_FreeValue(ctx, val);
  48625. return JS_EXCEPTION;
  48626. }
  48627. if (idx < 0 || idx >= p->len) {
  48628. ret = JS_NAN;
  48629. } else {
  48630. c = string_get(p, idx);
  48631. ret = js_int32(c);
  48632. }
  48633. JS_FreeValue(ctx, val);
  48634. return ret;
  48635. }
  48636. static JSValue js_string_charAt(JSContext *ctx, JSValueConst this_val,
  48637. int argc, JSValueConst *argv)
  48638. {
  48639. JSValue val, ret;
  48640. JSString *p;
  48641. int idx, c;
  48642. val = JS_ToStringCheckObject(ctx, this_val);
  48643. if (JS_IsException(val))
  48644. return val;
  48645. p = JS_VALUE_GET_STRING(val);
  48646. if (JS_ToInt32Sat(ctx, &idx, argv[0])) {
  48647. JS_FreeValue(ctx, val);
  48648. return JS_EXCEPTION;
  48649. }
  48650. if (idx < 0 || idx >= p->len) {
  48651. ret = JS_AtomToString(ctx, JS_ATOM_empty_string);
  48652. } else {
  48653. c = string_get(p, idx);
  48654. ret = js_new_string_char(ctx, c);
  48655. }
  48656. JS_FreeValue(ctx, val);
  48657. return ret;
  48658. }
  48659. static JSValue js_string_codePointAt(JSContext *ctx, JSValueConst this_val,
  48660. int argc, JSValueConst *argv)
  48661. {
  48662. JSValue val, ret;
  48663. JSString *p;
  48664. int idx, c;
  48665. val = JS_ToStringCheckObject(ctx, this_val);
  48666. if (JS_IsException(val))
  48667. return val;
  48668. p = JS_VALUE_GET_STRING(val);
  48669. if (JS_ToInt32Sat(ctx, &idx, argv[0])) {
  48670. JS_FreeValue(ctx, val);
  48671. return JS_EXCEPTION;
  48672. }
  48673. if (idx < 0 || idx >= p->len) {
  48674. ret = JS_UNDEFINED;
  48675. } else {
  48676. c = string_getc(p, &idx);
  48677. ret = js_int32(c);
  48678. }
  48679. JS_FreeValue(ctx, val);
  48680. return ret;
  48681. }
  48682. static JSValue js_string_concat(JSContext *ctx, JSValueConst this_val,
  48683. int argc, JSValueConst *argv)
  48684. {
  48685. JSValue r;
  48686. int i;
  48687. /* XXX: Use more efficient method */
  48688. /* XXX: This method is OK if r has a single refcount */
  48689. /* XXX: should use string_buffer? */
  48690. r = JS_ToStringCheckObject(ctx, this_val);
  48691. for (i = 0; i < argc; i++) {
  48692. if (JS_IsException(r))
  48693. break;
  48694. r = JS_ConcatString(ctx, r, js_dup(argv[i]));
  48695. }
  48696. return r;
  48697. }
  48698. static int string_cmp(JSString *p1, JSString *p2, int x1, int x2, int len)
  48699. {
  48700. int i, c1, c2;
  48701. for (i = 0; i < len; i++) {
  48702. if ((c1 = string_get(p1, x1 + i)) != (c2 = string_get(p2, x2 + i)))
  48703. return c1 - c2;
  48704. }
  48705. return 0;
  48706. }
  48707. static int string_indexof_char(JSString *p, int c, int from)
  48708. {
  48709. /* assuming 0 <= from <= p->len */
  48710. int i, len = p->len;
  48711. if (p->is_wide_char) {
  48712. for (i = from; i < len; i++) {
  48713. if (str16(p)[i] == c)
  48714. return i;
  48715. }
  48716. } else {
  48717. if ((c & ~0xff) == 0) {
  48718. for (i = from; i < len; i++) {
  48719. if (str8(p)[i] == (uint8_t)c)
  48720. return i;
  48721. }
  48722. }
  48723. }
  48724. return -1;
  48725. }
  48726. static int string_indexof(JSString *p1, JSString *p2, int from)
  48727. {
  48728. /* assuming 0 <= from <= p1->len */
  48729. int c, i, j, len1 = p1->len, len2 = p2->len;
  48730. if (len2 == 0)
  48731. return from;
  48732. for (i = from, c = string_get(p2, 0); i + len2 <= len1; i = j + 1) {
  48733. j = string_indexof_char(p1, c, i);
  48734. if (j < 0 || j + len2 > len1)
  48735. break;
  48736. if (!string_cmp(p1, p2, j + 1, 1, len2 - 1))
  48737. return j;
  48738. }
  48739. return -1;
  48740. }
  48741. static int64_t string_advance_index(JSString *p, int64_t index, bool unicode)
  48742. {
  48743. if (!unicode || index >= p->len || !p->is_wide_char) {
  48744. index++;
  48745. } else {
  48746. int index32 = (int)index;
  48747. string_getc(p, &index32);
  48748. index = index32;
  48749. }
  48750. return index;
  48751. }
  48752. static JSValue js_string_isWellFormed(JSContext *ctx, JSValueConst this_val,
  48753. int argc, JSValueConst *argv)
  48754. {
  48755. JSValue str;
  48756. JSValue ret;
  48757. JSString *p;
  48758. uint32_t c, i, n;
  48759. ret = JS_TRUE;
  48760. str = JS_ToStringCheckObject(ctx, this_val);
  48761. if (JS_IsException(str))
  48762. return JS_EXCEPTION;
  48763. p = JS_VALUE_GET_STRING(str);
  48764. if (!p->is_wide_char || p->len == 0)
  48765. goto done; // by definition well-formed
  48766. for (i = 0, n = p->len; i < n; i++) {
  48767. c = str16(p)[i];
  48768. if (!is_surrogate(c))
  48769. continue;
  48770. if (is_lo_surrogate(c) || i + 1 == n)
  48771. break;
  48772. c = str16(p)[++i];
  48773. if (!is_lo_surrogate(c))
  48774. break;
  48775. }
  48776. if (i < n)
  48777. ret = JS_FALSE;
  48778. done:
  48779. JS_FreeValue(ctx, str);
  48780. return ret;
  48781. }
  48782. static JSValue js_string_toWellFormed(JSContext *ctx, JSValueConst this_val,
  48783. int argc, JSValueConst *argv)
  48784. {
  48785. JSValue str;
  48786. JSValue ret;
  48787. JSString *p;
  48788. uint32_t c, i, n;
  48789. str = JS_ToStringCheckObject(ctx, this_val);
  48790. if (JS_IsException(str))
  48791. return JS_EXCEPTION;
  48792. p = JS_VALUE_GET_STRING(str);
  48793. if (!p->is_wide_char || p->len == 0)
  48794. return str; // by definition well-formed
  48795. // TODO(bnoordhuis) don't clone when input is well-formed
  48796. ret = js_new_string16_len(ctx, str16(p), p->len);
  48797. JS_FreeValue(ctx, str);
  48798. if (JS_IsException(ret))
  48799. return JS_EXCEPTION;
  48800. p = JS_VALUE_GET_STRING(ret);
  48801. for (i = 0, n = p->len; i < n; i++) {
  48802. c = str16(p)[i];
  48803. if (!is_surrogate(c))
  48804. continue;
  48805. if (is_lo_surrogate(c) || i + 1 == n) {
  48806. str16(p)[i] = 0xFFFD;
  48807. continue;
  48808. }
  48809. c = str16(p)[++i];
  48810. if (!is_lo_surrogate(c))
  48811. str16(p)[--i] = 0xFFFD;
  48812. }
  48813. return ret;
  48814. }
  48815. static JSValue js_string_indexOf(JSContext *ctx, JSValueConst this_val,
  48816. int argc, JSValueConst *argv, int lastIndexOf)
  48817. {
  48818. JSValue str, v;
  48819. int i, len, v_len, pos, start, stop, ret, inc;
  48820. JSString *p;
  48821. JSString *p1;
  48822. str = JS_ToStringCheckObject(ctx, this_val);
  48823. if (JS_IsException(str))
  48824. return str;
  48825. v = JS_ToString(ctx, argv[0]);
  48826. if (JS_IsException(v))
  48827. goto fail;
  48828. p = JS_VALUE_GET_STRING(str);
  48829. p1 = JS_VALUE_GET_STRING(v);
  48830. len = p->len;
  48831. v_len = p1->len;
  48832. if (lastIndexOf) {
  48833. pos = len - v_len;
  48834. if (argc > 1) {
  48835. double d;
  48836. if (JS_ToFloat64(ctx, &d, argv[1]))
  48837. goto fail;
  48838. if (!isnan(d)) {
  48839. if (d <= 0)
  48840. pos = 0;
  48841. else if (d < pos)
  48842. pos = d;
  48843. }
  48844. }
  48845. start = pos;
  48846. stop = 0;
  48847. inc = -1;
  48848. } else {
  48849. pos = 0;
  48850. if (argc > 1) {
  48851. if (JS_ToInt32Clamp(ctx, &pos, argv[1], 0, len, 0))
  48852. goto fail;
  48853. }
  48854. start = pos;
  48855. stop = len - v_len;
  48856. inc = 1;
  48857. }
  48858. ret = -1;
  48859. if (len >= v_len && inc * (stop - start) >= 0) {
  48860. for (i = start;; i += inc) {
  48861. if (!string_cmp(p, p1, i, 0, v_len)) {
  48862. ret = i;
  48863. break;
  48864. }
  48865. if (i == stop)
  48866. break;
  48867. }
  48868. }
  48869. JS_FreeValue(ctx, str);
  48870. JS_FreeValue(ctx, v);
  48871. return js_int32(ret);
  48872. fail:
  48873. JS_FreeValue(ctx, str);
  48874. JS_FreeValue(ctx, v);
  48875. return JS_EXCEPTION;
  48876. }
  48877. /* return < 0 if exception or true/false */
  48878. static int js_is_regexp(JSContext *ctx, JSValueConst obj);
  48879. static JSValue js_string_includes(JSContext *ctx, JSValueConst this_val,
  48880. int argc, JSValueConst *argv, int magic)
  48881. {
  48882. JSValue str, v = JS_UNDEFINED;
  48883. int i, len, v_len, pos, start, stop, ret;
  48884. JSString *p;
  48885. JSString *p1;
  48886. str = JS_ToStringCheckObject(ctx, this_val);
  48887. if (JS_IsException(str))
  48888. return str;
  48889. ret = js_is_regexp(ctx, argv[0]);
  48890. if (ret) {
  48891. if (ret > 0)
  48892. JS_ThrowTypeError(ctx, "regexp not supported");
  48893. goto fail;
  48894. }
  48895. v = JS_ToString(ctx, argv[0]);
  48896. if (JS_IsException(v))
  48897. goto fail;
  48898. p = JS_VALUE_GET_STRING(str);
  48899. p1 = JS_VALUE_GET_STRING(v);
  48900. len = p->len;
  48901. v_len = p1->len;
  48902. pos = (magic == 2) ? len : 0;
  48903. if (argc > 1 && !JS_IsUndefined(argv[1])) {
  48904. if (JS_ToInt32Clamp(ctx, &pos, argv[1], 0, len, 0))
  48905. goto fail;
  48906. }
  48907. len -= v_len;
  48908. ret = 0;
  48909. if (magic == 0) {
  48910. start = pos;
  48911. stop = len;
  48912. } else {
  48913. if (magic == 1) {
  48914. if (pos > len)
  48915. goto done;
  48916. } else {
  48917. pos -= v_len;
  48918. }
  48919. start = stop = pos;
  48920. }
  48921. if (start >= 0 && start <= stop) {
  48922. for (i = start;; i++) {
  48923. if (!string_cmp(p, p1, i, 0, v_len)) {
  48924. ret = 1;
  48925. break;
  48926. }
  48927. if (i == stop)
  48928. break;
  48929. }
  48930. }
  48931. done:
  48932. JS_FreeValue(ctx, str);
  48933. JS_FreeValue(ctx, v);
  48934. return js_bool(ret);
  48935. fail:
  48936. JS_FreeValue(ctx, str);
  48937. JS_FreeValue(ctx, v);
  48938. return JS_EXCEPTION;
  48939. }
  48940. static int check_regexp_g_flag(JSContext *ctx, JSValueConst regexp)
  48941. {
  48942. int ret;
  48943. JSValue flags;
  48944. ret = js_is_regexp(ctx, regexp);
  48945. if (ret < 0)
  48946. return -1;
  48947. if (ret) {
  48948. flags = JS_GetProperty(ctx, regexp, JS_ATOM_flags);
  48949. if (JS_IsException(flags))
  48950. return -1;
  48951. if (JS_IsUndefined(flags) || JS_IsNull(flags)) {
  48952. JS_ThrowTypeError(ctx, "cannot convert to object");
  48953. return -1;
  48954. }
  48955. flags = JS_ToStringFree(ctx, flags);
  48956. if (JS_IsException(flags))
  48957. return -1;
  48958. ret = string_indexof_char(JS_VALUE_GET_STRING(flags), 'g', 0);
  48959. JS_FreeValue(ctx, flags);
  48960. if (ret < 0) {
  48961. JS_ThrowTypeError(ctx, "regexp must have the 'g' flag");
  48962. return -1;
  48963. }
  48964. }
  48965. return 0;
  48966. }
  48967. static JSValue js_string_match(JSContext *ctx, JSValueConst this_val,
  48968. int argc, JSValueConst *argv, int atom)
  48969. {
  48970. // match(rx), search(rx), matchAll(rx)
  48971. // atom is JS_ATOM_Symbol_match, JS_ATOM_Symbol_search, or JS_ATOM_Symbol_matchAll
  48972. JSValueConst O = this_val, regexp = argv[0], args[2];
  48973. JSValue matcher, S, rx, result, str;
  48974. int args_len;
  48975. if (JS_IsUndefined(O) || JS_IsNull(O))
  48976. return JS_ThrowTypeError(ctx, "cannot convert to object");
  48977. if (!JS_IsUndefined(regexp) && !JS_IsNull(regexp)) {
  48978. matcher = JS_GetProperty(ctx, regexp, atom);
  48979. if (JS_IsException(matcher))
  48980. return JS_EXCEPTION;
  48981. if (atom == JS_ATOM_Symbol_matchAll) {
  48982. if (check_regexp_g_flag(ctx, regexp) < 0) {
  48983. JS_FreeValue(ctx, matcher);
  48984. return JS_EXCEPTION;
  48985. }
  48986. }
  48987. if (!JS_IsUndefined(matcher) && !JS_IsNull(matcher)) {
  48988. return JS_CallFree(ctx, matcher, regexp, 1, &O);
  48989. }
  48990. }
  48991. S = JS_ToString(ctx, O);
  48992. if (JS_IsException(S))
  48993. return JS_EXCEPTION;
  48994. args_len = 1;
  48995. args[0] = regexp;
  48996. str = JS_UNDEFINED;
  48997. if (atom == JS_ATOM_Symbol_matchAll) {
  48998. str = js_new_string8(ctx, "g");
  48999. if (JS_IsException(str))
  49000. goto fail;
  49001. args[args_len++] = str;
  49002. }
  49003. rx = JS_CallConstructor(ctx, ctx->regexp_ctor, args_len, args);
  49004. JS_FreeValue(ctx, str);
  49005. if (JS_IsException(rx)) {
  49006. fail:
  49007. JS_FreeValue(ctx, S);
  49008. return JS_EXCEPTION;
  49009. }
  49010. result = JS_InvokeFree(ctx, rx, atom, 1, vc(&S));
  49011. JS_FreeValue(ctx, S);
  49012. return result;
  49013. }
  49014. static JSValue js_string___GetSubstitution(JSContext *ctx, JSValueConst this_val,
  49015. int argc, JSValueConst *argv)
  49016. {
  49017. // GetSubstitution(matched, str, position, captures, namedCaptures, rep)
  49018. JSValueConst matched, str, captures, namedCaptures, rep;
  49019. JSValue capture, name, s;
  49020. uint32_t position, len, matched_len, captures_len;
  49021. int i, j, j0, k, k1;
  49022. int c, c1;
  49023. StringBuffer b_s, *b = &b_s;
  49024. JSString *sp, *rp;
  49025. matched = argv[0];
  49026. str = argv[1];
  49027. captures = argv[3];
  49028. namedCaptures = argv[4];
  49029. rep = argv[5];
  49030. if (!JS_IsString(rep) || !JS_IsString(str))
  49031. return JS_ThrowTypeError(ctx, "not a string");
  49032. sp = JS_VALUE_GET_STRING(str);
  49033. rp = JS_VALUE_GET_STRING(rep);
  49034. string_buffer_init(ctx, b, 0);
  49035. captures_len = 0;
  49036. if (!JS_IsUndefined(captures)) {
  49037. if (js_get_length32(ctx, &captures_len, captures))
  49038. goto exception;
  49039. }
  49040. if (js_get_length32(ctx, &matched_len, matched))
  49041. goto exception;
  49042. if (JS_ToUint32(ctx, &position, argv[2]) < 0)
  49043. goto exception;
  49044. len = rp->len;
  49045. i = 0;
  49046. for(;;) {
  49047. j = string_indexof_char(rp, '$', i);
  49048. if (j < 0 || j + 1 >= len)
  49049. break;
  49050. string_buffer_concat(b, rp, i, j);
  49051. j0 = j++;
  49052. c = string_get(rp, j++);
  49053. if (c == '$') {
  49054. string_buffer_putc8(b, '$');
  49055. } else if (c == '&') {
  49056. if (string_buffer_concat_value(b, matched))
  49057. goto exception;
  49058. } else if (c == '`') {
  49059. string_buffer_concat(b, sp, 0, position);
  49060. } else if (c == '\'') {
  49061. string_buffer_concat(b, sp, position + matched_len, sp->len);
  49062. } else if (c >= '0' && c <= '9') {
  49063. k = c - '0';
  49064. if (j < len) {
  49065. c1 = string_get(rp, j);
  49066. if (c1 >= '0' && c1 <= '9') {
  49067. /* This behavior is specified in ES6 and refined in ECMA 2019 */
  49068. /* ECMA 2019 does not have the extra test, but
  49069. Test262 S15.5.4.11_A3_T1..3 require this behavior */
  49070. k1 = k * 10 + c1 - '0';
  49071. if (k1 >= 1 && k1 < captures_len) {
  49072. k = k1;
  49073. j++;
  49074. }
  49075. }
  49076. }
  49077. if (k >= 1 && k < captures_len) {
  49078. s = JS_GetPropertyInt64(ctx, captures, k);
  49079. if (JS_IsException(s))
  49080. goto exception;
  49081. if (!JS_IsUndefined(s)) {
  49082. if (string_buffer_concat_value_free(b, s))
  49083. goto exception;
  49084. }
  49085. } else {
  49086. goto norep;
  49087. }
  49088. } else if (c == '<' && !JS_IsUndefined(namedCaptures)) {
  49089. k = string_indexof_char(rp, '>', j);
  49090. if (k < 0)
  49091. goto norep;
  49092. name = js_sub_string(ctx, rp, j, k);
  49093. if (JS_IsException(name))
  49094. goto exception;
  49095. capture = JS_GetPropertyValue(ctx, namedCaptures, name);
  49096. if (JS_IsException(capture))
  49097. goto exception;
  49098. if (!JS_IsUndefined(capture)) {
  49099. if (string_buffer_concat_value_free(b, capture))
  49100. goto exception;
  49101. }
  49102. j = k + 1;
  49103. } else {
  49104. norep:
  49105. string_buffer_concat(b, rp, j0, j);
  49106. }
  49107. i = j;
  49108. }
  49109. string_buffer_concat(b, rp, i, rp->len);
  49110. return string_buffer_end(b);
  49111. exception:
  49112. string_buffer_free(b);
  49113. return JS_EXCEPTION;
  49114. }
  49115. static JSValue js_string_replace(JSContext *ctx, JSValueConst this_val,
  49116. int argc, JSValueConst *argv,
  49117. int is_replaceAll)
  49118. {
  49119. // replace(rx, rep)
  49120. JSValueConst O = this_val, searchValue = argv[0], replaceValue = argv[1];
  49121. JSValueConst args[6];
  49122. JSValue str, search_str, replaceValue_str, repl_str;
  49123. JSString *sp, *searchp;
  49124. StringBuffer b_s, *b = &b_s;
  49125. int pos, functionalReplace, endOfLastMatch;
  49126. bool is_first;
  49127. if (JS_IsUndefined(O) || JS_IsNull(O))
  49128. return JS_ThrowTypeError(ctx, "cannot convert to object");
  49129. search_str = JS_UNDEFINED;
  49130. replaceValue_str = JS_UNDEFINED;
  49131. repl_str = JS_UNDEFINED;
  49132. if (!JS_IsUndefined(searchValue) && !JS_IsNull(searchValue)) {
  49133. JSValue replacer;
  49134. if (is_replaceAll) {
  49135. if (check_regexp_g_flag(ctx, searchValue) < 0)
  49136. return JS_EXCEPTION;
  49137. }
  49138. replacer = JS_GetProperty(ctx, searchValue, JS_ATOM_Symbol_replace);
  49139. if (JS_IsException(replacer))
  49140. return JS_EXCEPTION;
  49141. if (!JS_IsUndefined(replacer) && !JS_IsNull(replacer)) {
  49142. args[0] = O;
  49143. args[1] = replaceValue;
  49144. return JS_CallFree(ctx, replacer, searchValue, 2, args);
  49145. }
  49146. }
  49147. string_buffer_init(ctx, b, 0);
  49148. str = JS_ToString(ctx, O);
  49149. if (JS_IsException(str))
  49150. goto exception;
  49151. search_str = JS_ToString(ctx, searchValue);
  49152. if (JS_IsException(search_str))
  49153. goto exception;
  49154. functionalReplace = JS_IsFunction(ctx, replaceValue);
  49155. if (!functionalReplace) {
  49156. replaceValue_str = JS_ToString(ctx, replaceValue);
  49157. if (JS_IsException(replaceValue_str))
  49158. goto exception;
  49159. }
  49160. sp = JS_VALUE_GET_STRING(str);
  49161. searchp = JS_VALUE_GET_STRING(search_str);
  49162. endOfLastMatch = 0;
  49163. is_first = true;
  49164. for(;;) {
  49165. if (unlikely(searchp->len == 0)) {
  49166. if (is_first)
  49167. pos = 0;
  49168. else if (endOfLastMatch >= sp->len)
  49169. pos = -1;
  49170. else
  49171. pos = endOfLastMatch + 1;
  49172. } else {
  49173. pos = string_indexof(sp, searchp, endOfLastMatch);
  49174. }
  49175. if (pos < 0) {
  49176. if (is_first) {
  49177. string_buffer_free(b);
  49178. JS_FreeValue(ctx, search_str);
  49179. JS_FreeValue(ctx, replaceValue_str);
  49180. return str;
  49181. } else {
  49182. break;
  49183. }
  49184. }
  49185. if (functionalReplace) {
  49186. args[0] = search_str;
  49187. args[1] = js_int32(pos);
  49188. args[2] = str;
  49189. repl_str = JS_ToStringFree(ctx, JS_Call(ctx, replaceValue, JS_UNDEFINED, 3, args));
  49190. } else {
  49191. args[0] = search_str;
  49192. args[1] = str;
  49193. args[2] = js_int32(pos);
  49194. args[3] = JS_UNDEFINED;
  49195. args[4] = JS_UNDEFINED;
  49196. args[5] = replaceValue_str;
  49197. repl_str = js_string___GetSubstitution(ctx, JS_UNDEFINED, 6, args);
  49198. }
  49199. if (JS_IsException(repl_str))
  49200. goto exception;
  49201. string_buffer_concat(b, sp, endOfLastMatch, pos);
  49202. string_buffer_concat_value_free(b, repl_str);
  49203. endOfLastMatch = pos + searchp->len;
  49204. is_first = false;
  49205. if (!is_replaceAll)
  49206. break;
  49207. }
  49208. string_buffer_concat(b, sp, endOfLastMatch, sp->len);
  49209. JS_FreeValue(ctx, search_str);
  49210. JS_FreeValue(ctx, replaceValue_str);
  49211. JS_FreeValue(ctx, str);
  49212. return string_buffer_end(b);
  49213. exception:
  49214. string_buffer_free(b);
  49215. JS_FreeValue(ctx, search_str);
  49216. JS_FreeValue(ctx, replaceValue_str);
  49217. JS_FreeValue(ctx, str);
  49218. return JS_EXCEPTION;
  49219. }
  49220. static JSValue js_string_split(JSContext *ctx, JSValueConst this_val,
  49221. int argc, JSValueConst *argv)
  49222. {
  49223. // split(sep, limit)
  49224. JSValueConst O = this_val, separator = argv[0], limit = argv[1];
  49225. JSValueConst args[2];
  49226. JSValue S, A, R, T;
  49227. uint32_t lim, lengthA;
  49228. int64_t p, q, s, r, e;
  49229. JSString *sp, *rp;
  49230. if (JS_IsUndefined(O) || JS_IsNull(O))
  49231. return JS_ThrowTypeError(ctx, "cannot convert to object");
  49232. S = JS_UNDEFINED;
  49233. A = JS_UNDEFINED;
  49234. R = JS_UNDEFINED;
  49235. if (!JS_IsUndefined(separator) && !JS_IsNull(separator)) {
  49236. JSValue splitter;
  49237. splitter = JS_GetProperty(ctx, separator, JS_ATOM_Symbol_split);
  49238. if (JS_IsException(splitter))
  49239. return JS_EXCEPTION;
  49240. if (!JS_IsUndefined(splitter) && !JS_IsNull(splitter)) {
  49241. args[0] = O;
  49242. args[1] = limit;
  49243. return JS_CallFree(ctx, splitter, separator, 2, args);
  49244. }
  49245. }
  49246. S = JS_ToString(ctx, O);
  49247. if (JS_IsException(S))
  49248. goto exception;
  49249. A = JS_NewArray(ctx);
  49250. if (JS_IsException(A))
  49251. goto exception;
  49252. lengthA = 0;
  49253. if (JS_IsUndefined(limit)) {
  49254. lim = 0xffffffff;
  49255. } else {
  49256. if (JS_ToUint32(ctx, &lim, limit) < 0)
  49257. goto exception;
  49258. }
  49259. sp = JS_VALUE_GET_STRING(S);
  49260. s = sp->len;
  49261. R = JS_ToString(ctx, separator);
  49262. if (JS_IsException(R))
  49263. goto exception;
  49264. rp = JS_VALUE_GET_STRING(R);
  49265. r = rp->len;
  49266. p = 0;
  49267. if (lim == 0)
  49268. goto done;
  49269. if (JS_IsUndefined(separator))
  49270. goto add_tail;
  49271. if (s == 0) {
  49272. if (r != 0)
  49273. goto add_tail;
  49274. goto done;
  49275. }
  49276. q = p;
  49277. for (q = p; (q += !r) <= s - r - !r; q = p = e + r) {
  49278. e = string_indexof(sp, rp, q);
  49279. if (e < 0)
  49280. break;
  49281. T = js_sub_string(ctx, sp, p, e);
  49282. if (JS_IsException(T))
  49283. goto exception;
  49284. if (JS_CreateDataPropertyUint32(ctx, A, lengthA++, T, 0) < 0)
  49285. goto exception;
  49286. if (lengthA == lim)
  49287. goto done;
  49288. }
  49289. add_tail:
  49290. T = js_sub_string(ctx, sp, p, s);
  49291. if (JS_IsException(T))
  49292. goto exception;
  49293. if (JS_CreateDataPropertyUint32(ctx, A, lengthA++, T,0 ) < 0)
  49294. goto exception;
  49295. done:
  49296. JS_FreeValue(ctx, S);
  49297. JS_FreeValue(ctx, R);
  49298. return A;
  49299. exception:
  49300. JS_FreeValue(ctx, A);
  49301. JS_FreeValue(ctx, S);
  49302. JS_FreeValue(ctx, R);
  49303. return JS_EXCEPTION;
  49304. }
  49305. static JSValue js_string_substring(JSContext *ctx, JSValueConst this_val,
  49306. int argc, JSValueConst *argv)
  49307. {
  49308. JSValue str, ret;
  49309. int a, b, start, end;
  49310. JSString *p;
  49311. str = JS_ToStringCheckObject(ctx, this_val);
  49312. if (JS_IsException(str))
  49313. return str;
  49314. p = JS_VALUE_GET_STRING(str);
  49315. if (JS_ToInt32Clamp(ctx, &a, argv[0], 0, p->len, 0)) {
  49316. JS_FreeValue(ctx, str);
  49317. return JS_EXCEPTION;
  49318. }
  49319. b = p->len;
  49320. if (!JS_IsUndefined(argv[1])) {
  49321. if (JS_ToInt32Clamp(ctx, &b, argv[1], 0, p->len, 0)) {
  49322. JS_FreeValue(ctx, str);
  49323. return JS_EXCEPTION;
  49324. }
  49325. }
  49326. if (a < b) {
  49327. start = a;
  49328. end = b;
  49329. } else {
  49330. start = b;
  49331. end = a;
  49332. }
  49333. ret = js_sub_string(ctx, p, start, end);
  49334. JS_FreeValue(ctx, str);
  49335. return ret;
  49336. }
  49337. static JSValue js_string_substr(JSContext *ctx, JSValueConst this_val,
  49338. int argc, JSValueConst *argv)
  49339. {
  49340. JSValue str, ret;
  49341. int a, len, n;
  49342. JSString *p;
  49343. str = JS_ToStringCheckObject(ctx, this_val);
  49344. if (JS_IsException(str))
  49345. return str;
  49346. p = JS_VALUE_GET_STRING(str);
  49347. len = p->len;
  49348. if (JS_ToInt32Clamp(ctx, &a, argv[0], 0, len, len)) {
  49349. JS_FreeValue(ctx, str);
  49350. return JS_EXCEPTION;
  49351. }
  49352. n = len - a;
  49353. if (!JS_IsUndefined(argv[1])) {
  49354. if (JS_ToInt32Clamp(ctx, &n, argv[1], 0, len - a, 0)) {
  49355. JS_FreeValue(ctx, str);
  49356. return JS_EXCEPTION;
  49357. }
  49358. }
  49359. ret = js_sub_string(ctx, p, a, a + n);
  49360. JS_FreeValue(ctx, str);
  49361. return ret;
  49362. }
  49363. static JSValue js_string_slice(JSContext *ctx, JSValueConst this_val,
  49364. int argc, JSValueConst *argv)
  49365. {
  49366. JSValue str, ret;
  49367. int len, start, end;
  49368. JSString *p;
  49369. str = JS_ToStringCheckObject(ctx, this_val);
  49370. if (JS_IsException(str))
  49371. return str;
  49372. p = JS_VALUE_GET_STRING(str);
  49373. len = p->len;
  49374. if (JS_ToInt32Clamp(ctx, &start, argv[0], 0, len, len)) {
  49375. JS_FreeValue(ctx, str);
  49376. return JS_EXCEPTION;
  49377. }
  49378. end = len;
  49379. if (!JS_IsUndefined(argv[1])) {
  49380. if (JS_ToInt32Clamp(ctx, &end, argv[1], 0, len, len)) {
  49381. JS_FreeValue(ctx, str);
  49382. return JS_EXCEPTION;
  49383. }
  49384. }
  49385. ret = js_sub_string(ctx, p, start, max_int(end, start));
  49386. JS_FreeValue(ctx, str);
  49387. return ret;
  49388. }
  49389. static JSValue js_string_pad(JSContext *ctx, JSValueConst this_val,
  49390. int argc, JSValueConst *argv, int padEnd)
  49391. {
  49392. JSValue str, v = JS_UNDEFINED;
  49393. StringBuffer b_s, *b = &b_s;
  49394. JSString *p, *p1 = NULL;
  49395. int n, len, c = ' ';
  49396. str = JS_ToStringCheckObject(ctx, this_val);
  49397. if (JS_IsException(str))
  49398. goto fail1;
  49399. if (JS_ToInt32Sat(ctx, &n, argv[0]))
  49400. goto fail2;
  49401. p = JS_VALUE_GET_STRING(str);
  49402. len = p->len;
  49403. if (len >= n)
  49404. return str;
  49405. if (argc > 1 && !JS_IsUndefined(argv[1])) {
  49406. v = JS_ToString(ctx, argv[1]);
  49407. if (JS_IsException(v))
  49408. goto fail2;
  49409. p1 = JS_VALUE_GET_STRING(v);
  49410. if (p1->len == 0) {
  49411. JS_FreeValue(ctx, v);
  49412. return str;
  49413. }
  49414. if (p1->len == 1) {
  49415. c = string_get(p1, 0);
  49416. p1 = NULL;
  49417. }
  49418. }
  49419. if (n > JS_STRING_LEN_MAX) {
  49420. JS_ThrowRangeError(ctx, "invalid string length");
  49421. goto fail2;
  49422. }
  49423. if (string_buffer_init(ctx, b, n))
  49424. goto fail3;
  49425. n -= len;
  49426. if (padEnd) {
  49427. if (string_buffer_concat(b, p, 0, len))
  49428. goto fail;
  49429. }
  49430. if (p1) {
  49431. while (n > 0) {
  49432. int chunk = min_int(n, p1->len);
  49433. if (string_buffer_concat(b, p1, 0, chunk))
  49434. goto fail;
  49435. n -= chunk;
  49436. }
  49437. } else {
  49438. if (string_buffer_fill(b, c, n))
  49439. goto fail;
  49440. }
  49441. if (!padEnd) {
  49442. if (string_buffer_concat(b, p, 0, len))
  49443. goto fail;
  49444. }
  49445. JS_FreeValue(ctx, v);
  49446. JS_FreeValue(ctx, str);
  49447. return string_buffer_end(b);
  49448. fail:
  49449. string_buffer_free(b);
  49450. fail3:
  49451. JS_FreeValue(ctx, v);
  49452. fail2:
  49453. JS_FreeValue(ctx, str);
  49454. fail1:
  49455. return JS_EXCEPTION;
  49456. }
  49457. static JSValue js_string_repeat(JSContext *ctx, JSValueConst this_val,
  49458. int argc, JSValueConst *argv)
  49459. {
  49460. JSValue str;
  49461. StringBuffer b_s, *b = &b_s;
  49462. JSString *p;
  49463. int64_t val;
  49464. int n, len;
  49465. str = JS_ToStringCheckObject(ctx, this_val);
  49466. if (JS_IsException(str))
  49467. goto fail;
  49468. if (JS_ToInt64Sat(ctx, &val, argv[0]))
  49469. goto fail;
  49470. if (val < 0 || val > 2147483647) {
  49471. JS_ThrowRangeError(ctx, "invalid repeat count");
  49472. goto fail;
  49473. }
  49474. n = val;
  49475. p = JS_VALUE_GET_STRING(str);
  49476. len = p->len;
  49477. if (len == 0 || n == 1)
  49478. return str;
  49479. if (val * len > JS_STRING_LEN_MAX) {
  49480. JS_ThrowRangeError(ctx, "invalid string length");
  49481. goto fail;
  49482. }
  49483. if (string_buffer_init2(ctx, b, n * len, p->is_wide_char))
  49484. goto fail;
  49485. if (len == 1) {
  49486. string_buffer_fill(b, string_get(p, 0), n);
  49487. } else {
  49488. while (n-- > 0) {
  49489. string_buffer_concat(b, p, 0, len);
  49490. }
  49491. }
  49492. JS_FreeValue(ctx, str);
  49493. return string_buffer_end(b);
  49494. fail:
  49495. JS_FreeValue(ctx, str);
  49496. return JS_EXCEPTION;
  49497. }
  49498. static JSValue js_string_trim(JSContext *ctx, JSValueConst this_val,
  49499. int argc, JSValueConst *argv, int magic)
  49500. {
  49501. JSValue str, ret;
  49502. int a, b, len;
  49503. JSString *p;
  49504. str = JS_ToStringCheckObject(ctx, this_val);
  49505. if (JS_IsException(str))
  49506. return str;
  49507. p = JS_VALUE_GET_STRING(str);
  49508. a = 0;
  49509. b = len = p->len;
  49510. if (magic & 1) {
  49511. while (a < len && lre_is_space(string_get(p, a)))
  49512. a++;
  49513. }
  49514. if (magic & 2) {
  49515. while (b > a && lre_is_space(string_get(p, b - 1)))
  49516. b--;
  49517. }
  49518. ret = js_sub_string(ctx, p, a, b);
  49519. JS_FreeValue(ctx, str);
  49520. return ret;
  49521. }
  49522. /* return 0 if before the first char */
  49523. static int string_prevc(JSString *p, int *pidx)
  49524. {
  49525. int idx, c, c1;
  49526. idx = *pidx;
  49527. if (idx <= 0)
  49528. return 0;
  49529. idx--;
  49530. if (p->is_wide_char) {
  49531. c = str16(p)[idx];
  49532. if (is_lo_surrogate(c) && idx > 0) {
  49533. c1 = str16(p)[idx - 1];
  49534. if (is_hi_surrogate(c1)) {
  49535. c = from_surrogate(c1, c);
  49536. idx--;
  49537. }
  49538. }
  49539. } else {
  49540. c = str8(p)[idx];
  49541. }
  49542. *pidx = idx;
  49543. return c;
  49544. }
  49545. static bool test_final_sigma(JSString *p, int sigma_pos)
  49546. {
  49547. int k, c1;
  49548. /* before C: skip case ignorable chars and check there is
  49549. a cased letter */
  49550. k = sigma_pos;
  49551. for(;;) {
  49552. c1 = string_prevc(p, &k);
  49553. if (!lre_is_case_ignorable(c1))
  49554. break;
  49555. }
  49556. if (!lre_is_cased(c1))
  49557. return false;
  49558. /* after C: skip case ignorable chars and check there is
  49559. no cased letter */
  49560. k = sigma_pos + 1;
  49561. for(;;) {
  49562. if (k >= p->len)
  49563. return true;
  49564. c1 = string_getc(p, &k);
  49565. if (!lre_is_case_ignorable(c1))
  49566. break;
  49567. }
  49568. return !lre_is_cased(c1);
  49569. }
  49570. static int to_utf32_buf(JSContext *ctx, JSString *p, uint32_t **pbuf)
  49571. {
  49572. uint32_t *b;
  49573. int i, j, n;
  49574. j = -1;
  49575. n = p->len;
  49576. b = js_malloc(ctx, max_int(1, n) * sizeof(*b));
  49577. if (b)
  49578. for (i = j = 0; i < n;)
  49579. b[j++] = string_getc(p, &i);
  49580. *pbuf = b;
  49581. return j;
  49582. }
  49583. static JSValue js_string_localeCompare(JSContext *ctx, JSValueConst this_val,
  49584. int argc, JSValueConst *argv)
  49585. {
  49586. int i, n, an, bn, cmp;
  49587. uint32_t *as, *bs, *ts;
  49588. JSValue a, b, ret;
  49589. ret = JS_EXCEPTION;
  49590. as = NULL;
  49591. bs = NULL;
  49592. a = JS_ToStringCheckObject(ctx, this_val);
  49593. if (JS_IsException(a))
  49594. return JS_EXCEPTION;
  49595. b = JS_ToString(ctx, argv[0]);
  49596. if (JS_IsException(b))
  49597. goto exception;
  49598. an = to_utf32_buf(ctx, JS_VALUE_GET_STRING(a), &as);
  49599. if (an == -1)
  49600. goto exception;
  49601. bn = to_utf32_buf(ctx, JS_VALUE_GET_STRING(b), &bs);
  49602. if (bn == -1)
  49603. goto exception;
  49604. // TODO(bnoordhuis) skip normalization when input is latin1
  49605. an = unicode_normalize(&ts, as, an, UNICODE_NFC, ctx,
  49606. (DynBufReallocFunc *)js_realloc);
  49607. if (an == -1)
  49608. goto exception;
  49609. js_free(ctx, as);
  49610. as = ts;
  49611. // TODO(bnoordhuis) skip normalization when input is latin1
  49612. bn = unicode_normalize(&ts, bs, bn, UNICODE_NFC, ctx,
  49613. (DynBufReallocFunc *)js_realloc);
  49614. if (bn == -1)
  49615. goto exception;
  49616. js_free(ctx, bs);
  49617. bs = ts;
  49618. n = min_int(an, bn);
  49619. for (i = 0; i < n; i++)
  49620. if (as[i] != bs[i])
  49621. break;
  49622. if (i < n)
  49623. cmp = compare_u32(as[i], bs[i]);
  49624. else
  49625. cmp = compare_u32(an, bn);
  49626. ret = js_int32(cmp);
  49627. exception:
  49628. JS_FreeValue(ctx, a);
  49629. JS_FreeValue(ctx, b);
  49630. js_free(ctx, as);
  49631. js_free(ctx, bs);
  49632. return ret;
  49633. }
  49634. static JSValue js_string_toLowerCase(JSContext *ctx, JSValueConst this_val,
  49635. int argc, JSValueConst *argv, int to_lower)
  49636. {
  49637. JSValue val;
  49638. StringBuffer b_s, *b = &b_s;
  49639. JSString *p;
  49640. int i, c, j, l;
  49641. uint32_t res[LRE_CC_RES_LEN_MAX];
  49642. val = JS_ToStringCheckObject(ctx, this_val);
  49643. if (JS_IsException(val))
  49644. return val;
  49645. p = JS_VALUE_GET_STRING(val);
  49646. if (p->len == 0)
  49647. return val;
  49648. if (string_buffer_init(ctx, b, p->len))
  49649. goto fail;
  49650. for(i = 0; i < p->len;) {
  49651. c = string_getc(p, &i);
  49652. if (c == 0x3a3 && to_lower && test_final_sigma(p, i - 1)) {
  49653. res[0] = 0x3c2; /* final sigma */
  49654. l = 1;
  49655. } else {
  49656. l = lre_case_conv(res, c, to_lower);
  49657. }
  49658. for(j = 0; j < l; j++) {
  49659. if (string_buffer_putc(b, res[j]))
  49660. goto fail;
  49661. }
  49662. }
  49663. JS_FreeValue(ctx, val);
  49664. return string_buffer_end(b);
  49665. fail:
  49666. JS_FreeValue(ctx, val);
  49667. string_buffer_free(b);
  49668. return JS_EXCEPTION;
  49669. }
  49670. /* return (-1, NULL) if exception, otherwise (len, buf) */
  49671. static int JS_ToUTF32String(JSContext *ctx, uint32_t **pbuf, JSValue val1)
  49672. {
  49673. JSValue val;
  49674. int len;
  49675. val = JS_ToString(ctx, val1);
  49676. if (JS_IsException(val))
  49677. return -1;
  49678. len = to_utf32_buf(ctx, JS_VALUE_GET_STRING(val), pbuf);
  49679. JS_FreeValue(ctx, val);
  49680. return len;
  49681. }
  49682. static JSValue JS_NewUTF32String(JSContext *ctx, const uint32_t *buf, int len)
  49683. {
  49684. int i;
  49685. StringBuffer b_s, *b = &b_s;
  49686. if (string_buffer_init(ctx, b, len))
  49687. return JS_EXCEPTION;
  49688. for(i = 0; i < len; i++) {
  49689. if (string_buffer_putc(b, buf[i]))
  49690. goto fail;
  49691. }
  49692. return string_buffer_end(b);
  49693. fail:
  49694. string_buffer_free(b);
  49695. return JS_EXCEPTION;
  49696. }
  49697. static JSValue js_string_normalize(JSContext *ctx, JSValueConst this_val,
  49698. int argc, JSValueConst *argv)
  49699. {
  49700. const char *form, *p;
  49701. size_t form_len;
  49702. int is_compat, buf_len, out_len;
  49703. UnicodeNormalizationEnum n_type;
  49704. JSValue val;
  49705. uint32_t *buf, *out_buf;
  49706. val = JS_ToStringCheckObject(ctx, this_val);
  49707. if (JS_IsException(val))
  49708. return val;
  49709. buf = NULL; // appease bogus -Wmaybe-uninitialized warning
  49710. buf_len = JS_ToUTF32String(ctx, &buf, val);
  49711. JS_FreeValue(ctx, val);
  49712. if (buf_len < 0)
  49713. return JS_EXCEPTION;
  49714. if (argc == 0 || JS_IsUndefined(argv[0])) {
  49715. n_type = UNICODE_NFC;
  49716. } else {
  49717. form = JS_ToCStringLen(ctx, &form_len, argv[0]);
  49718. if (!form)
  49719. goto fail1;
  49720. p = form;
  49721. if (p[0] != 'N' || p[1] != 'F')
  49722. goto bad_form;
  49723. p += 2;
  49724. is_compat = false;
  49725. if (*p == 'K') {
  49726. is_compat = true;
  49727. p++;
  49728. }
  49729. if (*p == 'C' || *p == 'D') {
  49730. n_type = UNICODE_NFC + is_compat * 2 + (*p - 'C');
  49731. if ((p + 1 - form) != form_len)
  49732. goto bad_form;
  49733. } else {
  49734. bad_form:
  49735. JS_FreeCString(ctx, form);
  49736. JS_ThrowRangeError(ctx, "bad normalization form");
  49737. fail1:
  49738. js_free(ctx, buf);
  49739. return JS_EXCEPTION;
  49740. }
  49741. JS_FreeCString(ctx, form);
  49742. }
  49743. out_len = unicode_normalize(&out_buf, buf, buf_len, n_type,
  49744. ctx->rt, (DynBufReallocFunc *)js_realloc_rt);
  49745. js_free(ctx, buf);
  49746. if (out_len < 0)
  49747. return JS_EXCEPTION;
  49748. val = JS_NewUTF32String(ctx, out_buf, out_len);
  49749. js_free(ctx, out_buf);
  49750. return val;
  49751. }
  49752. /* also used for String.prototype.valueOf */
  49753. static JSValue js_string_toString(JSContext *ctx, JSValueConst this_val,
  49754. int argc, JSValueConst *argv)
  49755. {
  49756. return js_thisStringValue(ctx, this_val);
  49757. }
  49758. /* String Iterator */
  49759. static JSValue js_string_iterator_next(JSContext *ctx, JSValueConst this_val,
  49760. int argc, JSValueConst *argv,
  49761. int *pdone, int magic)
  49762. {
  49763. JSArrayIteratorData *it;
  49764. uint32_t idx, c, start;
  49765. JSString *p;
  49766. it = JS_GetOpaque2(ctx, this_val, JS_CLASS_STRING_ITERATOR);
  49767. if (!it) {
  49768. *pdone = false;
  49769. return JS_EXCEPTION;
  49770. }
  49771. if (JS_IsUndefined(it->obj))
  49772. goto done;
  49773. p = JS_VALUE_GET_STRING(it->obj);
  49774. idx = it->idx;
  49775. if (idx >= p->len) {
  49776. JS_FreeValue(ctx, it->obj);
  49777. it->obj = JS_UNDEFINED;
  49778. done:
  49779. *pdone = true;
  49780. return JS_UNDEFINED;
  49781. }
  49782. start = idx;
  49783. c = string_getc(p, (int *)&idx);
  49784. it->idx = idx;
  49785. *pdone = false;
  49786. if (c <= 0xffff) {
  49787. return js_new_string_char(ctx, c);
  49788. } else {
  49789. return js_new_string16_len(ctx, str16(p) + start, 2);
  49790. }
  49791. }
  49792. /* ES6 Annex B 2.3.2 etc. */
  49793. enum {
  49794. magic_string_anchor,
  49795. magic_string_big,
  49796. magic_string_blink,
  49797. magic_string_bold,
  49798. magic_string_fixed,
  49799. magic_string_fontcolor,
  49800. magic_string_fontsize,
  49801. magic_string_italics,
  49802. magic_string_link,
  49803. magic_string_small,
  49804. magic_string_strike,
  49805. magic_string_sub,
  49806. magic_string_sup,
  49807. };
  49808. static JSValue js_string_CreateHTML(JSContext *ctx, JSValueConst this_val,
  49809. int argc, JSValueConst *argv, int magic)
  49810. {
  49811. JSValue str;
  49812. JSString *p;
  49813. StringBuffer b_s, *b = &b_s;
  49814. static struct { const char *tag, *attr; } const defs[] = {
  49815. { "a", "name" }, { "big", NULL }, { "blink", NULL }, { "b", NULL },
  49816. { "tt", NULL }, { "font", "color" }, { "font", "size" }, { "i", NULL },
  49817. { "a", "href" }, { "small", NULL }, { "strike", NULL },
  49818. { "sub", NULL }, { "sup", NULL },
  49819. };
  49820. str = JS_ToStringCheckObject(ctx, this_val);
  49821. if (JS_IsException(str))
  49822. return JS_EXCEPTION;
  49823. string_buffer_init(ctx, b, 7);
  49824. string_buffer_putc8(b, '<');
  49825. string_buffer_puts8(b, defs[magic].tag);
  49826. if (defs[magic].attr) {
  49827. // r += " " + attr + "=\"" + value + "\"";
  49828. JSValue value;
  49829. int i;
  49830. string_buffer_putc8(b, ' ');
  49831. string_buffer_puts8(b, defs[magic].attr);
  49832. string_buffer_puts8(b, "=\"");
  49833. value = JS_ToStringCheckObject(ctx, argv[0]);
  49834. if (JS_IsException(value)) {
  49835. JS_FreeValue(ctx, str);
  49836. string_buffer_free(b);
  49837. return JS_EXCEPTION;
  49838. }
  49839. p = JS_VALUE_GET_STRING(value);
  49840. for (i = 0; i < p->len; i++) {
  49841. int c = string_get(p, i);
  49842. if (c == '"') {
  49843. string_buffer_puts8(b, "&quot;");
  49844. } else {
  49845. string_buffer_putc16(b, c);
  49846. }
  49847. }
  49848. JS_FreeValue(ctx, value);
  49849. string_buffer_putc8(b, '\"');
  49850. }
  49851. // return r + ">" + str + "</" + tag + ">";
  49852. string_buffer_putc8(b, '>');
  49853. string_buffer_concat_value_free(b, str);
  49854. string_buffer_puts8(b, "</");
  49855. string_buffer_puts8(b, defs[magic].tag);
  49856. string_buffer_putc8(b, '>');
  49857. return string_buffer_end(b);
  49858. }
  49859. static const JSCFunctionListEntry js_string_funcs[] = {
  49860. JS_CFUNC_DEF("fromCharCode", 1, js_string_fromCharCode ),
  49861. JS_CFUNC_DEF("fromCodePoint", 1, js_string_fromCodePoint ),
  49862. JS_CFUNC_DEF("raw", 1, js_string_raw ),
  49863. };
  49864. static const JSCFunctionListEntry js_string_proto_funcs[] = {
  49865. JS_PROP_INT32_DEF("length", 0, JS_PROP_CONFIGURABLE ),
  49866. JS_CFUNC_DEF("at", 1, js_string_at ),
  49867. JS_CFUNC_DEF("charCodeAt", 1, js_string_charCodeAt ),
  49868. JS_CFUNC_DEF("charAt", 1, js_string_charAt ),
  49869. JS_CFUNC_DEF("concat", 1, js_string_concat ),
  49870. JS_CFUNC_DEF("codePointAt", 1, js_string_codePointAt ),
  49871. JS_CFUNC_DEF("isWellFormed", 0, js_string_isWellFormed ),
  49872. JS_CFUNC_DEF("toWellFormed", 0, js_string_toWellFormed ),
  49873. JS_CFUNC_MAGIC_DEF("indexOf", 1, js_string_indexOf, 0 ),
  49874. JS_CFUNC_MAGIC_DEF("lastIndexOf", 1, js_string_indexOf, 1 ),
  49875. JS_CFUNC_MAGIC_DEF("includes", 1, js_string_includes, 0 ),
  49876. JS_CFUNC_MAGIC_DEF("endsWith", 1, js_string_includes, 2 ),
  49877. JS_CFUNC_MAGIC_DEF("startsWith", 1, js_string_includes, 1 ),
  49878. JS_CFUNC_MAGIC_DEF("match", 1, js_string_match, JS_ATOM_Symbol_match ),
  49879. JS_CFUNC_MAGIC_DEF("matchAll", 1, js_string_match, JS_ATOM_Symbol_matchAll ),
  49880. JS_CFUNC_MAGIC_DEF("search", 1, js_string_match, JS_ATOM_Symbol_search ),
  49881. JS_CFUNC_DEF("split", 2, js_string_split ),
  49882. JS_CFUNC_DEF("substring", 2, js_string_substring ),
  49883. JS_CFUNC_DEF("substr", 2, js_string_substr ),
  49884. JS_CFUNC_DEF("slice", 2, js_string_slice ),
  49885. JS_CFUNC_DEF("repeat", 1, js_string_repeat ),
  49886. JS_CFUNC_MAGIC_DEF("replace", 2, js_string_replace, 0 ),
  49887. JS_CFUNC_MAGIC_DEF("replaceAll", 2, js_string_replace, 1 ),
  49888. JS_CFUNC_MAGIC_DEF("padEnd", 1, js_string_pad, 1 ),
  49889. JS_CFUNC_MAGIC_DEF("padStart", 1, js_string_pad, 0 ),
  49890. JS_CFUNC_MAGIC_DEF("trim", 0, js_string_trim, 3 ),
  49891. JS_CFUNC_MAGIC_DEF("trimEnd", 0, js_string_trim, 2 ),
  49892. JS_ALIAS_DEF("trimRight", "trimEnd" ),
  49893. JS_CFUNC_MAGIC_DEF("trimStart", 0, js_string_trim, 1 ),
  49894. JS_ALIAS_DEF("trimLeft", "trimStart" ),
  49895. JS_CFUNC_DEF("toString", 0, js_string_toString ),
  49896. JS_CFUNC_DEF("valueOf", 0, js_string_toString ),
  49897. JS_CFUNC_DEF("localeCompare", 1, js_string_localeCompare ),
  49898. JS_CFUNC_DEF("normalize", 0, js_string_normalize ),
  49899. JS_CFUNC_MAGIC_DEF("toLowerCase", 0, js_string_toLowerCase, 1 ),
  49900. JS_CFUNC_MAGIC_DEF("toUpperCase", 0, js_string_toLowerCase, 0 ),
  49901. JS_CFUNC_MAGIC_DEF("toLocaleLowerCase", 0, js_string_toLowerCase, 1 ),
  49902. JS_CFUNC_MAGIC_DEF("toLocaleUpperCase", 0, js_string_toLowerCase, 0 ),
  49903. JS_CFUNC_MAGIC_DEF("[Symbol.iterator]", 0, js_create_array_iterator, JS_ITERATOR_KIND_VALUE | 4 ),
  49904. /* ES6 Annex B 2.3.2 etc. */
  49905. JS_CFUNC_MAGIC_DEF("anchor", 1, js_string_CreateHTML, magic_string_anchor ),
  49906. JS_CFUNC_MAGIC_DEF("big", 0, js_string_CreateHTML, magic_string_big ),
  49907. JS_CFUNC_MAGIC_DEF("blink", 0, js_string_CreateHTML, magic_string_blink ),
  49908. JS_CFUNC_MAGIC_DEF("bold", 0, js_string_CreateHTML, magic_string_bold ),
  49909. JS_CFUNC_MAGIC_DEF("fixed", 0, js_string_CreateHTML, magic_string_fixed ),
  49910. JS_CFUNC_MAGIC_DEF("fontcolor", 1, js_string_CreateHTML, magic_string_fontcolor ),
  49911. JS_CFUNC_MAGIC_DEF("fontsize", 1, js_string_CreateHTML, magic_string_fontsize ),
  49912. JS_CFUNC_MAGIC_DEF("italics", 0, js_string_CreateHTML, magic_string_italics ),
  49913. JS_CFUNC_MAGIC_DEF("link", 1, js_string_CreateHTML, magic_string_link ),
  49914. JS_CFUNC_MAGIC_DEF("small", 0, js_string_CreateHTML, magic_string_small ),
  49915. JS_CFUNC_MAGIC_DEF("strike", 0, js_string_CreateHTML, magic_string_strike ),
  49916. JS_CFUNC_MAGIC_DEF("sub", 0, js_string_CreateHTML, magic_string_sub ),
  49917. JS_CFUNC_MAGIC_DEF("sup", 0, js_string_CreateHTML, magic_string_sup ),
  49918. };
  49919. static const JSCFunctionListEntry js_string_iterator_proto_funcs[] = {
  49920. JS_ITERATOR_NEXT_DEF("next", 0, js_string_iterator_next, 0 ),
  49921. JS_PROP_STRING_DEF("[Symbol.toStringTag]", "String Iterator", JS_PROP_CONFIGURABLE ),
  49922. };
  49923. /* Math */
  49924. /* precondition: a and b are not NaN */
  49925. static double js_fmin(double a, double b)
  49926. {
  49927. if (a == 0 && b == 0) {
  49928. JSFloat64Union a1, b1;
  49929. a1.d = a;
  49930. b1.d = b;
  49931. a1.u64 |= b1.u64;
  49932. return a1.d;
  49933. } else {
  49934. return fmin(a, b);
  49935. }
  49936. }
  49937. /* precondition: a and b are not NaN */
  49938. static double js_fmax(double a, double b)
  49939. {
  49940. if (a == 0 && b == 0) {
  49941. JSFloat64Union a1, b1;
  49942. a1.d = a;
  49943. b1.d = b;
  49944. a1.u64 &= b1.u64;
  49945. return a1.d;
  49946. } else {
  49947. return fmax(a, b);
  49948. }
  49949. }
  49950. static JSValue js_math_min_max(JSContext *ctx, JSValueConst this_val,
  49951. int argc, JSValueConst *argv, int magic)
  49952. {
  49953. bool is_max = magic;
  49954. double r, a;
  49955. int i;
  49956. uint32_t tag;
  49957. if (unlikely(argc == 0)) {
  49958. return js_float64(is_max ? NEG_INF : INF);
  49959. }
  49960. tag = JS_VALUE_GET_TAG(argv[0]);
  49961. if (tag == JS_TAG_INT) {
  49962. int a1, r1 = JS_VALUE_GET_INT(argv[0]);
  49963. for(i = 1; i < argc; i++) {
  49964. tag = JS_VALUE_GET_TAG(argv[i]);
  49965. if (tag != JS_TAG_INT) {
  49966. r = r1;
  49967. goto generic_case;
  49968. }
  49969. a1 = JS_VALUE_GET_INT(argv[i]);
  49970. if (is_max)
  49971. r1 = max_int(r1, a1);
  49972. else
  49973. r1 = min_int(r1, a1);
  49974. }
  49975. return js_int32(r1);
  49976. } else {
  49977. if (JS_ToFloat64(ctx, &r, argv[0]))
  49978. return JS_EXCEPTION;
  49979. i = 1;
  49980. generic_case:
  49981. while (i < argc) {
  49982. if (JS_ToFloat64(ctx, &a, argv[i]))
  49983. return JS_EXCEPTION;
  49984. if (!isnan(r)) {
  49985. if (isnan(a)) {
  49986. r = a;
  49987. } else {
  49988. if (is_max)
  49989. r = js_fmax(r, a);
  49990. else
  49991. r = js_fmin(r, a);
  49992. }
  49993. }
  49994. i++;
  49995. }
  49996. return js_number(r);
  49997. }
  49998. }
  49999. static double js_math_sign(double a)
  50000. {
  50001. if (isnan(a) || a == 0.0)
  50002. return a;
  50003. if (a < 0)
  50004. return -1;
  50005. else
  50006. return 1;
  50007. }
  50008. static double js_math_round(double a)
  50009. {
  50010. JSFloat64Union u;
  50011. uint64_t frac_mask, one;
  50012. unsigned int e, s;
  50013. u.d = a;
  50014. e = (u.u64 >> 52) & 0x7ff;
  50015. if (e < 1023) {
  50016. /* abs(a) < 1 */
  50017. if (e == (1023 - 1) && u.u64 != 0xbfe0000000000000) {
  50018. /* abs(a) > 0.5 or a = 0.5: return +/-1.0 */
  50019. u.u64 = (u.u64 & ((uint64_t)1 << 63)) | ((uint64_t)1023 << 52);
  50020. } else {
  50021. /* return +/-0.0 */
  50022. u.u64 &= (uint64_t)1 << 63;
  50023. }
  50024. } else if (e < (1023 + 52)) {
  50025. s = u.u64 >> 63;
  50026. one = (uint64_t)1 << (52 - (e - 1023));
  50027. frac_mask = one - 1;
  50028. u.u64 += (one >> 1) - s;
  50029. u.u64 &= ~frac_mask; /* truncate to an integer */
  50030. }
  50031. /* otherwise: abs(a) >= 2^52, or NaN, +/-Infinity: no change */
  50032. return u.d;
  50033. }
  50034. static JSValue js_math_hypot(JSContext *ctx, JSValueConst this_val,
  50035. int argc, JSValueConst *argv)
  50036. {
  50037. double r, a;
  50038. int i;
  50039. r = 0;
  50040. if (argc > 0) {
  50041. if (JS_ToFloat64(ctx, &r, argv[0]))
  50042. return JS_EXCEPTION;
  50043. if (argc == 1) {
  50044. r = fabs(r);
  50045. } else {
  50046. /* use the built-in function to minimize precision loss */
  50047. for (i = 1; i < argc; i++) {
  50048. if (JS_ToFloat64(ctx, &a, argv[i]))
  50049. return JS_EXCEPTION;
  50050. r = hypot(r, a);
  50051. }
  50052. }
  50053. }
  50054. return js_float64(r);
  50055. }
  50056. static double js_math_f16round(double a)
  50057. {
  50058. return fromfp16(tofp16(a));
  50059. }
  50060. static double js_math_fround(double a)
  50061. {
  50062. return (float)a;
  50063. }
  50064. static JSValue js_math_imul(JSContext *ctx, JSValueConst this_val,
  50065. int argc, JSValueConst *argv)
  50066. {
  50067. uint32_t a, b, c;
  50068. int32_t d;
  50069. if (JS_ToUint32(ctx, &a, argv[0]))
  50070. return JS_EXCEPTION;
  50071. if (JS_ToUint32(ctx, &b, argv[1]))
  50072. return JS_EXCEPTION;
  50073. c = a * b;
  50074. memcpy(&d, &c, sizeof(d));
  50075. return js_int32(d);
  50076. }
  50077. static JSValue js_math_clz32(JSContext *ctx, JSValueConst this_val,
  50078. int argc, JSValueConst *argv)
  50079. {
  50080. uint32_t a, r;
  50081. if (JS_ToUint32(ctx, &a, argv[0]))
  50082. return JS_EXCEPTION;
  50083. if (a == 0)
  50084. r = 32;
  50085. else
  50086. r = clz32(a);
  50087. return js_int32(r);
  50088. }
  50089. static JSValue js_math_sumPrecise(JSContext *ctx, JSValueConst this_val,
  50090. int argc, JSValueConst *argv)
  50091. {
  50092. JSValue iter, next, item, ret;
  50093. bf_t a, b;
  50094. int done;
  50095. double d;
  50096. int r;
  50097. iter = JS_GetIterator(ctx, argv[0], /*async*/false);
  50098. if (JS_IsException(iter))
  50099. return JS_EXCEPTION;
  50100. bf_init(ctx->bf_ctx, &a);
  50101. bf_init(ctx->bf_ctx, &b);
  50102. ret = JS_EXCEPTION;
  50103. next = JS_GetProperty(ctx, iter, JS_ATOM_next);
  50104. if (JS_IsException(next))
  50105. goto fail;
  50106. bf_set_zero(&a, /*is_neg*/true);
  50107. for (;;) {
  50108. item = JS_IteratorNext(ctx, iter, next, 0, NULL, &done);
  50109. if (JS_IsException(item))
  50110. goto fail;
  50111. if (done)
  50112. break; // item == JS_UNDEFINED
  50113. switch (JS_VALUE_GET_TAG(item)) {
  50114. default:
  50115. JS_FreeValue(ctx, item);
  50116. JS_ThrowTypeError(ctx, "not a number");
  50117. goto fail;
  50118. case JS_TAG_INT:
  50119. d = JS_VALUE_GET_INT(item);
  50120. break;
  50121. case JS_TAG_FLOAT64:
  50122. d = JS_VALUE_GET_FLOAT64(item);
  50123. break;
  50124. }
  50125. if (bf_set_float64(&b, d))
  50126. goto oom;
  50127. // Infinity + -Infinity results in BF_ST_INVALID_OP, sets |a| to nan
  50128. if ((r = bf_add(&a, &a, &b, BF_PREC_INF, BF_RNDN)))
  50129. if (r != BF_ST_INVALID_OP)
  50130. goto oom;
  50131. }
  50132. bf_get_float64(&a, &d, BF_RNDN); // return value deliberately ignored
  50133. ret = js_float64(d);
  50134. fail:
  50135. JS_IteratorClose(ctx, iter, JS_IsException(ret));
  50136. JS_FreeValue(ctx, iter);
  50137. JS_FreeValue(ctx, next);
  50138. bf_delete(&a);
  50139. bf_delete(&b);
  50140. return ret;
  50141. oom:
  50142. JS_ThrowOutOfMemory(ctx);
  50143. goto fail;
  50144. }
  50145. /* xorshift* random number generator by Marsaglia */
  50146. static uint64_t xorshift64star(uint64_t *pstate)
  50147. {
  50148. uint64_t x;
  50149. x = *pstate;
  50150. x ^= x >> 12;
  50151. x ^= x << 25;
  50152. x ^= x >> 27;
  50153. *pstate = x;
  50154. return x * 0x2545F4914F6CDD1D;
  50155. }
  50156. static void js_random_init(JSContext *ctx)
  50157. {
  50158. ctx->random_state = js__gettimeofday_us();
  50159. /* the state must be non zero */
  50160. if (ctx->random_state == 0)
  50161. ctx->random_state = 1;
  50162. }
  50163. static JSValue js_math_random(JSContext *ctx, JSValueConst this_val,
  50164. int argc, JSValueConst *argv)
  50165. {
  50166. JSFloat64Union u;
  50167. uint64_t v;
  50168. v = xorshift64star(&ctx->random_state);
  50169. /* 1.0 <= u.d < 2 */
  50170. u.u64 = ((uint64_t)0x3ff << 52) | (v >> 12);
  50171. return js_float64(u.d - 1.0);
  50172. }
  50173. /* use local wrappers for math functions to
  50174. - avoid initializing data with dynamic library entry points.
  50175. - avoid some overhead if the call can be inlined at compile or link time.
  50176. */
  50177. static double js_math_fabs(double d) { return fabs(d); }
  50178. static double js_math_floor(double d) { return floor(d); }
  50179. static double js_math_ceil(double d) { return ceil(d); }
  50180. static double js_math_sqrt(double d) { return sqrt(d); }
  50181. static double js_math_acos(double d) { return acos(d); }
  50182. static double js_math_asin(double d) { return asin(d); }
  50183. static double js_math_atan(double d) { return atan(d); }
  50184. static double js_math_atan2(double a, double b) { return atan2(a, b); }
  50185. static double js_math_cos(double d) { return cos(d); }
  50186. static double js_math_exp(double d) { return exp(d); }
  50187. static double js_math_log(double d) { return log(d); }
  50188. static double js_math_sin(double d) { return sin(d); }
  50189. static double js_math_tan(double d) { return tan(d); }
  50190. static double js_math_trunc(double d) { return trunc(d); }
  50191. static double js_math_cosh(double d) { return cosh(d); }
  50192. static double js_math_sinh(double d) { return sinh(d); }
  50193. static double js_math_tanh(double d) { return tanh(d); }
  50194. static double js_math_acosh(double d) { return acosh(d); }
  50195. static double js_math_asinh(double d) { return asinh(d); }
  50196. static double js_math_atanh(double d) { return atanh(d); }
  50197. static double js_math_expm1(double d) { return expm1(d); }
  50198. static double js_math_log1p(double d) { return log1p(d); }
  50199. static double js_math_log2(double d) { return log2(d); }
  50200. static double js_math_log10(double d) { return log10(d); }
  50201. static double js_math_cbrt(double d) { return cbrt(d); }
  50202. static const JSCFunctionListEntry js_math_funcs[] = {
  50203. JS_CFUNC_MAGIC_DEF("min", 2, js_math_min_max, 0 ),
  50204. JS_CFUNC_MAGIC_DEF("max", 2, js_math_min_max, 1 ),
  50205. JS_CFUNC_SPECIAL_DEF("abs", 1, f_f, js_math_fabs ),
  50206. JS_CFUNC_SPECIAL_DEF("floor", 1, f_f, js_math_floor ),
  50207. JS_CFUNC_SPECIAL_DEF("ceil", 1, f_f, js_math_ceil ),
  50208. JS_CFUNC_SPECIAL_DEF("round", 1, f_f, js_math_round ),
  50209. JS_CFUNC_SPECIAL_DEF("sqrt", 1, f_f, js_math_sqrt ),
  50210. JS_CFUNC_SPECIAL_DEF("acos", 1, f_f, js_math_acos ),
  50211. JS_CFUNC_SPECIAL_DEF("asin", 1, f_f, js_math_asin ),
  50212. JS_CFUNC_SPECIAL_DEF("atan", 1, f_f, js_math_atan ),
  50213. JS_CFUNC_SPECIAL_DEF("atan2", 2, f_f_f, js_math_atan2 ),
  50214. JS_CFUNC_SPECIAL_DEF("cos", 1, f_f, js_math_cos ),
  50215. JS_CFUNC_SPECIAL_DEF("exp", 1, f_f, js_math_exp ),
  50216. JS_CFUNC_SPECIAL_DEF("log", 1, f_f, js_math_log ),
  50217. JS_CFUNC_SPECIAL_DEF("pow", 2, f_f_f, js_math_pow ),
  50218. JS_CFUNC_SPECIAL_DEF("sin", 1, f_f, js_math_sin ),
  50219. JS_CFUNC_SPECIAL_DEF("tan", 1, f_f, js_math_tan ),
  50220. /* ES6 */
  50221. JS_CFUNC_SPECIAL_DEF("trunc", 1, f_f, js_math_trunc ),
  50222. JS_CFUNC_SPECIAL_DEF("sign", 1, f_f, js_math_sign ),
  50223. JS_CFUNC_SPECIAL_DEF("cosh", 1, f_f, js_math_cosh ),
  50224. JS_CFUNC_SPECIAL_DEF("sinh", 1, f_f, js_math_sinh ),
  50225. JS_CFUNC_SPECIAL_DEF("tanh", 1, f_f, js_math_tanh ),
  50226. JS_CFUNC_SPECIAL_DEF("acosh", 1, f_f, js_math_acosh ),
  50227. JS_CFUNC_SPECIAL_DEF("asinh", 1, f_f, js_math_asinh ),
  50228. JS_CFUNC_SPECIAL_DEF("atanh", 1, f_f, js_math_atanh ),
  50229. JS_CFUNC_SPECIAL_DEF("expm1", 1, f_f, js_math_expm1 ),
  50230. JS_CFUNC_SPECIAL_DEF("log1p", 1, f_f, js_math_log1p ),
  50231. JS_CFUNC_SPECIAL_DEF("log2", 1, f_f, js_math_log2 ),
  50232. JS_CFUNC_SPECIAL_DEF("log10", 1, f_f, js_math_log10 ),
  50233. JS_CFUNC_SPECIAL_DEF("cbrt", 1, f_f, js_math_cbrt ),
  50234. JS_CFUNC_DEF("hypot", 2, js_math_hypot ),
  50235. JS_CFUNC_DEF("random", 0, js_math_random ),
  50236. JS_CFUNC_SPECIAL_DEF("f16round", 1, f_f, js_math_f16round ),
  50237. JS_CFUNC_SPECIAL_DEF("fround", 1, f_f, js_math_fround ),
  50238. JS_CFUNC_DEF("imul", 2, js_math_imul ),
  50239. JS_CFUNC_DEF("clz32", 1, js_math_clz32 ),
  50240. JS_CFUNC_DEF("sumPrecise", 1, js_math_sumPrecise ),
  50241. JS_PROP_STRING_DEF("[Symbol.toStringTag]", "Math", JS_PROP_CONFIGURABLE ),
  50242. JS_PROP_DOUBLE_DEF("E", 2.718281828459045, 0 ),
  50243. JS_PROP_DOUBLE_DEF("LN10", 2.302585092994046, 0 ),
  50244. JS_PROP_DOUBLE_DEF("LN2", 0.6931471805599453, 0 ),
  50245. JS_PROP_DOUBLE_DEF("LOG2E", 1.4426950408889634, 0 ),
  50246. JS_PROP_DOUBLE_DEF("LOG10E", 0.4342944819032518, 0 ),
  50247. JS_PROP_DOUBLE_DEF("PI", 3.141592653589793, 0 ),
  50248. JS_PROP_DOUBLE_DEF("SQRT1_2", 0.7071067811865476, 0 ),
  50249. JS_PROP_DOUBLE_DEF("SQRT2", 1.4142135623730951, 0 ),
  50250. };
  50251. static const JSCFunctionListEntry js_math_obj[] = {
  50252. JS_OBJECT_DEF("Math", js_math_funcs, countof(js_math_funcs), JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE ),
  50253. };
  50254. /* Date */
  50255. /* OS dependent. d = argv[0] is in ms from 1970. Return the difference
  50256. between UTC time and local time 'd' in minutes */
  50257. static int getTimezoneOffset(int64_t time) {
  50258. #if defined(_WIN32)
  50259. DWORD r;
  50260. TIME_ZONE_INFORMATION t;
  50261. r = GetTimeZoneInformation(&t);
  50262. if (r == TIME_ZONE_ID_INVALID)
  50263. return 0;
  50264. if (r == TIME_ZONE_ID_DAYLIGHT)
  50265. return (int)(t.Bias + t.DaylightBias);
  50266. return (int)t.Bias;
  50267. #else
  50268. time_t ti;
  50269. struct tm tm;
  50270. time /= 1000; /* convert to seconds */
  50271. if (sizeof(time_t) == 4) {
  50272. /* on 32-bit systems, we need to clamp the time value to the
  50273. range of `time_t`. This is better than truncating values to
  50274. 32 bits and hopefully provides the same result as 64-bit
  50275. implementation of localtime_r.
  50276. */
  50277. if ((time_t)-1 < 0) {
  50278. if (time < INT32_MIN) {
  50279. time = INT32_MIN;
  50280. } else if (time > INT32_MAX) {
  50281. time = INT32_MAX;
  50282. }
  50283. } else {
  50284. if (time < 0) {
  50285. time = 0;
  50286. } else if (time > UINT32_MAX) {
  50287. time = UINT32_MAX;
  50288. }
  50289. }
  50290. }
  50291. ti = time;
  50292. localtime_r(&ti, &tm);
  50293. #ifdef NO_TM_GMTOFF
  50294. struct tm gmt;
  50295. gmtime_r(&ti, &gmt);
  50296. /* disable DST adjustment on the local tm struct */
  50297. tm.tm_isdst = 0;
  50298. return (int)difftime(mktime(&gmt), mktime(&tm)) / 60;
  50299. #else
  50300. return -tm.tm_gmtoff / 60;
  50301. #endif /* NO_TM_GMTOFF */
  50302. #endif
  50303. }
  50304. /* RegExp */
  50305. static void js_regexp_finalizer(JSRuntime *rt, JSValueConst val)
  50306. {
  50307. JSObject *p = JS_VALUE_GET_OBJ(val);
  50308. JSRegExp *re = &p->u.regexp;
  50309. JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_STRING, re->bytecode));
  50310. JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_STRING, re->pattern));
  50311. }
  50312. /* create a string containing the RegExp bytecode */
  50313. static JSValue js_compile_regexp(JSContext *ctx, JSValueConst pattern,
  50314. JSValueConst flags)
  50315. {
  50316. const char *str;
  50317. int re_flags, mask;
  50318. uint8_t *re_bytecode_buf;
  50319. size_t i, len;
  50320. int re_bytecode_len;
  50321. JSValue ret;
  50322. char error_msg[64];
  50323. re_flags = 0;
  50324. if (!JS_IsUndefined(flags)) {
  50325. str = JS_ToCStringLen(ctx, &len, flags);
  50326. if (!str)
  50327. return JS_EXCEPTION;
  50328. /* XXX: re_flags = LRE_FLAG_OCTAL unless strict mode? */
  50329. for (i = 0; i < len; i++) {
  50330. switch(str[i]) {
  50331. case 'd':
  50332. mask = LRE_FLAG_INDICES;
  50333. break;
  50334. case 'g':
  50335. mask = LRE_FLAG_GLOBAL;
  50336. break;
  50337. case 'i':
  50338. mask = LRE_FLAG_IGNORECASE;
  50339. break;
  50340. case 'm':
  50341. mask = LRE_FLAG_MULTILINE;
  50342. break;
  50343. case 's':
  50344. mask = LRE_FLAG_DOTALL;
  50345. break;
  50346. case 'u':
  50347. mask = LRE_FLAG_UNICODE;
  50348. break;
  50349. case 'v':
  50350. mask = LRE_FLAG_UNICODE_SETS;
  50351. break;
  50352. case 'y':
  50353. mask = LRE_FLAG_STICKY;
  50354. break;
  50355. default:
  50356. goto bad_flags;
  50357. }
  50358. if ((re_flags & mask) != 0) {
  50359. bad_flags:
  50360. JS_FreeCString(ctx, str);
  50361. return JS_ThrowSyntaxError(ctx, "invalid regular expression flags");
  50362. }
  50363. re_flags |= mask;
  50364. }
  50365. JS_FreeCString(ctx, str);
  50366. }
  50367. if (re_flags & LRE_FLAG_UNICODE)
  50368. if (re_flags & LRE_FLAG_UNICODE_SETS)
  50369. return JS_ThrowSyntaxError(ctx, "invalid regular expression flags");
  50370. str = JS_ToCStringLen2(ctx, &len, pattern, !(re_flags & LRE_FLAG_UNICODE));
  50371. if (!str)
  50372. return JS_EXCEPTION;
  50373. re_bytecode_buf = lre_compile(&re_bytecode_len, error_msg,
  50374. sizeof(error_msg), str, len, re_flags, ctx);
  50375. JS_FreeCString(ctx, str);
  50376. if (!re_bytecode_buf) {
  50377. JS_ThrowSyntaxError(ctx, "%s", error_msg);
  50378. return JS_EXCEPTION;
  50379. }
  50380. ret = js_new_string8_len(ctx, (char *)re_bytecode_buf, re_bytecode_len);
  50381. js_free(ctx, re_bytecode_buf);
  50382. return ret;
  50383. }
  50384. /* create a RegExp object from a string containing the RegExp bytecode
  50385. and the source pattern */
  50386. static JSValue js_regexp_constructor_internal(JSContext *ctx, JSValueConst ctor,
  50387. JSValue pattern, JSValue bc)
  50388. {
  50389. JSValue obj;
  50390. JSObject *p;
  50391. JSRegExp *re;
  50392. /* sanity check */
  50393. if (JS_VALUE_GET_TAG(bc) != JS_TAG_STRING ||
  50394. JS_VALUE_GET_TAG(pattern) != JS_TAG_STRING) {
  50395. JS_ThrowTypeError(ctx, "string expected");
  50396. fail:
  50397. JS_FreeValue(ctx, bc);
  50398. JS_FreeValue(ctx, pattern);
  50399. return JS_EXCEPTION;
  50400. }
  50401. obj = js_create_from_ctor(ctx, ctor, JS_CLASS_REGEXP);
  50402. if (JS_IsException(obj))
  50403. goto fail;
  50404. p = JS_VALUE_GET_OBJ(obj);
  50405. re = &p->u.regexp;
  50406. re->pattern = JS_VALUE_GET_STRING(pattern);
  50407. re->bytecode = JS_VALUE_GET_STRING(bc);
  50408. JS_DefinePropertyValue(ctx, obj, JS_ATOM_lastIndex, js_int32(0),
  50409. JS_PROP_WRITABLE);
  50410. return obj;
  50411. }
  50412. static JSRegExp *js_get_regexp(JSContext *ctx, JSValueConst obj,
  50413. bool throw_error)
  50414. {
  50415. if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) {
  50416. JSObject *p = JS_VALUE_GET_OBJ(obj);
  50417. if (p->class_id == JS_CLASS_REGEXP)
  50418. return &p->u.regexp;
  50419. }
  50420. if (throw_error) {
  50421. JS_ThrowTypeErrorInvalidClass(ctx, JS_CLASS_REGEXP);
  50422. }
  50423. return NULL;
  50424. }
  50425. /* return < 0 if exception or true/false */
  50426. static int js_is_regexp(JSContext *ctx, JSValueConst obj)
  50427. {
  50428. JSValue m;
  50429. if (!JS_IsObject(obj))
  50430. return false;
  50431. m = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_match);
  50432. if (JS_IsException(m))
  50433. return -1;
  50434. if (!JS_IsUndefined(m))
  50435. return JS_ToBoolFree(ctx, m);
  50436. return js_get_regexp(ctx, obj, false) != NULL;
  50437. }
  50438. static JSValue js_regexp_constructor(JSContext *ctx, JSValueConst new_target,
  50439. int argc, JSValueConst *argv)
  50440. {
  50441. JSValue pattern, flags, bc, val;
  50442. JSValueConst pat, flags1;
  50443. JSRegExp *re;
  50444. int pat_is_regexp;
  50445. pat = argv[0];
  50446. flags1 = argv[1];
  50447. pat_is_regexp = js_is_regexp(ctx, pat);
  50448. if (pat_is_regexp < 0)
  50449. return JS_EXCEPTION;
  50450. if (JS_IsUndefined(new_target)) {
  50451. /* called as a function */
  50452. new_target = JS_GetActiveFunction(ctx);
  50453. if (pat_is_regexp && JS_IsUndefined(flags1)) {
  50454. JSValue ctor;
  50455. bool res;
  50456. ctor = JS_GetProperty(ctx, pat, JS_ATOM_constructor);
  50457. if (JS_IsException(ctor))
  50458. return ctor;
  50459. res = js_same_value(ctx, ctor, new_target);
  50460. JS_FreeValue(ctx, ctor);
  50461. if (res)
  50462. return js_dup(pat);
  50463. }
  50464. }
  50465. re = js_get_regexp(ctx, pat, false);
  50466. if (re) {
  50467. pattern = js_dup(JS_MKPTR(JS_TAG_STRING, re->pattern));
  50468. if (JS_IsUndefined(flags1)) {
  50469. bc = js_dup(JS_MKPTR(JS_TAG_STRING, re->bytecode));
  50470. goto no_compilation;
  50471. } else {
  50472. flags = JS_ToString(ctx, flags1);
  50473. if (JS_IsException(flags))
  50474. goto fail;
  50475. }
  50476. } else {
  50477. flags = JS_UNDEFINED;
  50478. if (pat_is_regexp) {
  50479. pattern = JS_GetProperty(ctx, pat, JS_ATOM_source);
  50480. if (JS_IsException(pattern))
  50481. goto fail;
  50482. if (JS_IsUndefined(flags1)) {
  50483. flags = JS_GetProperty(ctx, pat, JS_ATOM_flags);
  50484. if (JS_IsException(flags))
  50485. goto fail;
  50486. } else {
  50487. flags = js_dup(flags1);
  50488. }
  50489. } else {
  50490. pattern = js_dup(pat);
  50491. flags = js_dup(flags1);
  50492. }
  50493. if (JS_IsUndefined(pattern)) {
  50494. pattern = JS_AtomToString(ctx, JS_ATOM_empty_string);
  50495. } else {
  50496. val = pattern;
  50497. pattern = JS_ToString(ctx, val);
  50498. JS_FreeValue(ctx, val);
  50499. if (JS_IsException(pattern))
  50500. goto fail;
  50501. }
  50502. }
  50503. bc = js_compile_regexp(ctx, pattern, flags);
  50504. if (JS_IsException(bc))
  50505. goto fail;
  50506. JS_FreeValue(ctx, flags);
  50507. no_compilation:
  50508. return js_regexp_constructor_internal(ctx, new_target, pattern, bc);
  50509. fail:
  50510. JS_FreeValue(ctx, pattern);
  50511. JS_FreeValue(ctx, flags);
  50512. return JS_EXCEPTION;
  50513. }
  50514. static JSValue js_regexp_compile(JSContext *ctx, JSValueConst this_val,
  50515. int argc, JSValueConst *argv)
  50516. {
  50517. JSRegExp *re1, *re;
  50518. JSValueConst pattern1, flags1;
  50519. JSValue bc, pattern;
  50520. re = js_get_regexp(ctx, this_val, true);
  50521. if (!re)
  50522. return JS_EXCEPTION;
  50523. pattern1 = argv[0];
  50524. flags1 = argv[1];
  50525. re1 = js_get_regexp(ctx, pattern1, false);
  50526. if (re1) {
  50527. if (!JS_IsUndefined(flags1))
  50528. return JS_ThrowTypeError(ctx, "flags must be undefined");
  50529. pattern = js_dup(JS_MKPTR(JS_TAG_STRING, re1->pattern));
  50530. bc = js_dup(JS_MKPTR(JS_TAG_STRING, re1->bytecode));
  50531. } else {
  50532. bc = JS_UNDEFINED;
  50533. if (JS_IsUndefined(pattern1))
  50534. pattern = JS_AtomToString(ctx, JS_ATOM_empty_string);
  50535. else
  50536. pattern = JS_ToString(ctx, pattern1);
  50537. if (JS_IsException(pattern))
  50538. goto fail;
  50539. bc = js_compile_regexp(ctx, pattern, flags1);
  50540. if (JS_IsException(bc))
  50541. goto fail;
  50542. }
  50543. JS_FreeValue(ctx, JS_MKPTR(JS_TAG_STRING, re->pattern));
  50544. JS_FreeValue(ctx, JS_MKPTR(JS_TAG_STRING, re->bytecode));
  50545. re->pattern = JS_VALUE_GET_STRING(pattern);
  50546. re->bytecode = JS_VALUE_GET_STRING(bc);
  50547. if (JS_SetProperty(ctx, this_val, JS_ATOM_lastIndex,
  50548. js_int32(0)) < 0)
  50549. return JS_EXCEPTION;
  50550. return js_dup(this_val);
  50551. fail:
  50552. JS_FreeValue(ctx, pattern);
  50553. JS_FreeValue(ctx, bc);
  50554. return JS_EXCEPTION;
  50555. }
  50556. static JSValue js_regexp_get_source(JSContext *ctx, JSValueConst this_val)
  50557. {
  50558. JSRegExp *re;
  50559. JSString *p;
  50560. StringBuffer b_s, *b = &b_s;
  50561. int i, n, c, c2, bra;
  50562. if (JS_VALUE_GET_TAG(this_val) != JS_TAG_OBJECT)
  50563. return JS_ThrowTypeErrorNotAnObject(ctx);
  50564. if (js_same_value(ctx, this_val, ctx->class_proto[JS_CLASS_REGEXP]))
  50565. goto empty_regex;
  50566. re = js_get_regexp(ctx, this_val, true);
  50567. if (!re)
  50568. return JS_EXCEPTION;
  50569. p = re->pattern;
  50570. if (p->len == 0) {
  50571. empty_regex:
  50572. return js_new_string8(ctx, "(?:)");
  50573. }
  50574. string_buffer_init2(ctx, b, p->len, p->is_wide_char);
  50575. /* Escape '/' and newline sequences as needed */
  50576. bra = 0;
  50577. for (i = 0, n = p->len; i < n;) {
  50578. c2 = -1;
  50579. switch (c = string_get(p, i++)) {
  50580. case '\\':
  50581. if (i < n)
  50582. c2 = string_get(p, i++);
  50583. break;
  50584. case ']':
  50585. bra = 0;
  50586. break;
  50587. case '[':
  50588. if (!bra) {
  50589. if (i < n && string_get(p, i) == ']')
  50590. c2 = string_get(p, i++);
  50591. bra = 1;
  50592. }
  50593. break;
  50594. case '\n':
  50595. c = '\\';
  50596. c2 = 'n';
  50597. break;
  50598. case '\r':
  50599. c = '\\';
  50600. c2 = 'r';
  50601. break;
  50602. case '/':
  50603. if (!bra) {
  50604. c = '\\';
  50605. c2 = '/';
  50606. }
  50607. break;
  50608. }
  50609. string_buffer_putc16(b, c);
  50610. if (c2 >= 0)
  50611. string_buffer_putc16(b, c2);
  50612. }
  50613. return string_buffer_end(b);
  50614. }
  50615. static JSValue js_regexp_get_flag(JSContext *ctx, JSValueConst this_val, int mask)
  50616. {
  50617. JSRegExp *re;
  50618. int flags;
  50619. if (JS_VALUE_GET_TAG(this_val) != JS_TAG_OBJECT)
  50620. return JS_ThrowTypeErrorNotAnObject(ctx);
  50621. re = js_get_regexp(ctx, this_val, false);
  50622. if (!re) {
  50623. if (js_same_value(ctx, this_val, ctx->class_proto[JS_CLASS_REGEXP]))
  50624. return JS_UNDEFINED;
  50625. else
  50626. return JS_ThrowTypeErrorInvalidClass(ctx, JS_CLASS_REGEXP);
  50627. }
  50628. flags = lre_get_flags(str8(re->bytecode));
  50629. return js_bool(flags & mask);
  50630. }
  50631. static JSValue js_regexp_get_flags(JSContext *ctx, JSValueConst this_val)
  50632. {
  50633. char str[8], *p = str;
  50634. int res;
  50635. if (JS_VALUE_GET_TAG(this_val) != JS_TAG_OBJECT)
  50636. return JS_ThrowTypeErrorNotAnObject(ctx);
  50637. res = JS_ToBoolFree(ctx, JS_GetPropertyStr(ctx, this_val, "hasIndices"));
  50638. if (res < 0)
  50639. goto exception;
  50640. if (res)
  50641. *p++ = 'd';
  50642. res = JS_ToBoolFree(ctx, JS_GetProperty(ctx, this_val, JS_ATOM_global));
  50643. if (res < 0)
  50644. goto exception;
  50645. if (res)
  50646. *p++ = 'g';
  50647. res = JS_ToBoolFree(ctx, JS_GetPropertyStr(ctx, this_val, "ignoreCase"));
  50648. if (res < 0)
  50649. goto exception;
  50650. if (res)
  50651. *p++ = 'i';
  50652. res = JS_ToBoolFree(ctx, JS_GetPropertyStr(ctx, this_val, "multiline"));
  50653. if (res < 0)
  50654. goto exception;
  50655. if (res)
  50656. *p++ = 'm';
  50657. res = JS_ToBoolFree(ctx, JS_GetPropertyStr(ctx, this_val, "dotAll"));
  50658. if (res < 0)
  50659. goto exception;
  50660. if (res)
  50661. *p++ = 's';
  50662. res = JS_ToBoolFree(ctx, JS_GetProperty(ctx, this_val, JS_ATOM_unicode));
  50663. if (res < 0)
  50664. goto exception;
  50665. if (res)
  50666. *p++ = 'u';
  50667. res = JS_ToBoolFree(ctx, JS_GetPropertyStr(ctx, this_val, "unicodeSets"));
  50668. if (res < 0)
  50669. goto exception;
  50670. if (res)
  50671. *p++ = 'v';
  50672. res = JS_ToBoolFree(ctx, JS_GetPropertyStr(ctx, this_val, "sticky"));
  50673. if (res < 0)
  50674. goto exception;
  50675. if (res)
  50676. *p++ = 'y';
  50677. if (p == str)
  50678. return JS_AtomToString(ctx, JS_ATOM_empty_string);
  50679. return js_new_string8_len(ctx, str, p - str);
  50680. exception:
  50681. return JS_EXCEPTION;
  50682. }
  50683. static JSValue js_regexp_toString(JSContext *ctx, JSValueConst this_val,
  50684. int argc, JSValueConst *argv)
  50685. {
  50686. JSValue pattern, flags;
  50687. StringBuffer b_s, *b = &b_s;
  50688. if (!JS_IsObject(this_val))
  50689. return JS_ThrowTypeErrorNotAnObject(ctx);
  50690. string_buffer_init(ctx, b, 0);
  50691. string_buffer_putc8(b, '/');
  50692. pattern = JS_GetProperty(ctx, this_val, JS_ATOM_source);
  50693. if (string_buffer_concat_value_free(b, pattern))
  50694. goto fail;
  50695. string_buffer_putc8(b, '/');
  50696. flags = JS_GetProperty(ctx, this_val, JS_ATOM_flags);
  50697. if (string_buffer_concat_value_free(b, flags))
  50698. goto fail;
  50699. return string_buffer_end(b);
  50700. fail:
  50701. string_buffer_free(b);
  50702. return JS_EXCEPTION;
  50703. }
  50704. bool lre_check_stack_overflow(void *opaque, size_t alloca_size)
  50705. {
  50706. JSContext *ctx = opaque;
  50707. return js_check_stack_overflow(ctx->rt, alloca_size);
  50708. }
  50709. void *lre_realloc(void *opaque, void *ptr, size_t size)
  50710. {
  50711. JSContext *ctx = opaque;
  50712. /* No JS exception is raised here */
  50713. return js_realloc_rt(ctx->rt, ptr, size);
  50714. }
  50715. static JSValue js_regexp_escape(JSContext *ctx, JSValueConst this_val,
  50716. int argc, JSValueConst *argv)
  50717. {
  50718. StringBuffer b_s, *b = &b_s;
  50719. JSString *p;
  50720. uint32_t c, i;
  50721. char s[16];
  50722. if (!JS_IsString(argv[0]))
  50723. return JS_ThrowTypeError(ctx, "not a string");
  50724. p = JS_VALUE_GET_STRING(argv[0]);
  50725. string_buffer_init2(ctx, b, 0, p->is_wide_char);
  50726. for (i = 0; i < p->len; i++) {
  50727. c = p->is_wide_char ? (uint32_t)str16(p)[i] : (uint32_t)str8(p)[i];
  50728. if (c < 33) {
  50729. if (c >= 9 && c <= 13) {
  50730. string_buffer_putc8(b, '\\');
  50731. string_buffer_putc8(b, "tnvfr"[c - 9]);
  50732. } else {
  50733. goto hex2;
  50734. }
  50735. } else if (c < 128) {
  50736. if ((c >= '0' && c <= '9')
  50737. || (c >= 'A' && c <= 'Z')
  50738. || (c >= 'a' && c <= 'z')) {
  50739. if (i == 0)
  50740. goto hex2;
  50741. } else if (strchr(",-=<>#&!%:;@~'`\"", c)) {
  50742. goto hex2;
  50743. } else if (c != '_') {
  50744. string_buffer_putc8(b, '\\');
  50745. }
  50746. string_buffer_putc8(b, c);
  50747. } else if (c < 256) {
  50748. hex2:
  50749. snprintf(s, sizeof(s), "\\x%02x", c);
  50750. string_buffer_puts8(b, s);
  50751. } else if (is_surrogate(c) || lre_is_white_space(c) || c == 0xFEFF) {
  50752. snprintf(s, sizeof(s), "\\u%04x", c);
  50753. string_buffer_puts8(b, s);
  50754. } else {
  50755. string_buffer_putc16(b, c);
  50756. }
  50757. }
  50758. return string_buffer_end(b);
  50759. }
  50760. static JSValue js_regexp_exec(JSContext *ctx, JSValueConst this_val,
  50761. int argc, JSValueConst *argv)
  50762. {
  50763. JSRegExp *re = js_get_regexp(ctx, this_val, true);
  50764. JSString *str;
  50765. JSValue t, ret, str_val, obj, val, groups;
  50766. JSValue indices, indices_groups;
  50767. uint8_t *re_bytecode;
  50768. uint8_t **capture, *str_buf;
  50769. int rc, capture_count, shift, i, re_flags;
  50770. int64_t last_index;
  50771. const char *group_name_ptr;
  50772. if (!re)
  50773. return JS_EXCEPTION;
  50774. str_val = JS_ToString(ctx, argv[0]);
  50775. if (JS_IsException(str_val))
  50776. return JS_EXCEPTION;
  50777. ret = JS_EXCEPTION;
  50778. obj = JS_NULL;
  50779. groups = JS_UNDEFINED;
  50780. indices = JS_UNDEFINED;
  50781. indices_groups = JS_UNDEFINED;
  50782. capture = NULL;
  50783. val = JS_GetProperty(ctx, this_val, JS_ATOM_lastIndex);
  50784. if (JS_IsException(val) || JS_ToLengthFree(ctx, &last_index, val))
  50785. goto fail;
  50786. re_bytecode = str8(re->bytecode);
  50787. re_flags = lre_get_flags(re_bytecode);
  50788. if ((re_flags & (LRE_FLAG_GLOBAL | LRE_FLAG_STICKY)) == 0) {
  50789. last_index = 0;
  50790. }
  50791. str = JS_VALUE_GET_STRING(str_val);
  50792. capture_count = lre_get_capture_count(re_bytecode);
  50793. if (capture_count > 0) {
  50794. capture = js_malloc(ctx, sizeof(capture[0]) * capture_count * 2);
  50795. if (!capture)
  50796. goto fail;
  50797. }
  50798. shift = str->is_wide_char;
  50799. str_buf = str8(str);
  50800. if (last_index > str->len) {
  50801. rc = 2;
  50802. } else {
  50803. rc = lre_exec(capture, re_bytecode,
  50804. str_buf, last_index, str->len,
  50805. shift, ctx);
  50806. }
  50807. if (rc != 1) {
  50808. if (rc >= 0) {
  50809. if (rc == 2 || (re_flags & (LRE_FLAG_GLOBAL | LRE_FLAG_STICKY))) {
  50810. if (JS_SetProperty(ctx, this_val, JS_ATOM_lastIndex,
  50811. js_int32(0)) < 0)
  50812. goto fail;
  50813. }
  50814. } else {
  50815. JS_ThrowInternalError(ctx, "out of memory in regexp execution");
  50816. goto fail;
  50817. }
  50818. } else {
  50819. int prop_flags;
  50820. if (re_flags & (LRE_FLAG_GLOBAL | LRE_FLAG_STICKY)) {
  50821. if (JS_SetProperty(ctx, this_val, JS_ATOM_lastIndex,
  50822. js_int32((capture[1] - str_buf) >> shift)) < 0)
  50823. goto fail;
  50824. }
  50825. obj = JS_NewArray(ctx);
  50826. if (JS_IsException(obj))
  50827. goto fail;
  50828. prop_flags = JS_PROP_C_W_E | JS_PROP_THROW;
  50829. group_name_ptr = lre_get_groupnames(re_bytecode);
  50830. if (group_name_ptr) {
  50831. groups = JS_NewObjectProto(ctx, JS_NULL);
  50832. if (JS_IsException(groups))
  50833. goto fail;
  50834. }
  50835. if (re_flags & LRE_FLAG_INDICES) {
  50836. indices = JS_NewArray(ctx);
  50837. if (JS_IsException(indices))
  50838. goto fail;
  50839. if (group_name_ptr) {
  50840. indices_groups = JS_NewObjectProto(ctx, JS_NULL);
  50841. if (JS_IsException(indices_groups))
  50842. goto fail;
  50843. }
  50844. }
  50845. for(i = 0; i < capture_count; i++) {
  50846. const char *name = NULL;
  50847. uint8_t **match = &capture[2 * i];
  50848. int start = -1;
  50849. int end = -1;
  50850. if (group_name_ptr && i > 0) {
  50851. if (*group_name_ptr) name = group_name_ptr;
  50852. group_name_ptr += strlen(group_name_ptr) + 1;
  50853. }
  50854. if (match[0] && match[1]) {
  50855. start = (match[0] - str_buf) >> shift;
  50856. end = (match[1] - str_buf) >> shift;
  50857. }
  50858. if (!JS_IsUndefined(indices)) {
  50859. JSValue val = JS_UNDEFINED;
  50860. if (start != -1) {
  50861. val = JS_NewArray(ctx);
  50862. if (JS_IsException(val))
  50863. goto fail;
  50864. if (JS_DefinePropertyValueUint32(ctx, val, 0,
  50865. js_int32(start),
  50866. prop_flags) < 0) {
  50867. JS_FreeValue(ctx, val);
  50868. goto fail;
  50869. }
  50870. if (JS_DefinePropertyValueUint32(ctx, val, 1,
  50871. js_int32(end),
  50872. prop_flags) < 0) {
  50873. JS_FreeValue(ctx, val);
  50874. goto fail;
  50875. }
  50876. }
  50877. if (name && !JS_IsUndefined(indices_groups)) {
  50878. val = js_dup(val);
  50879. if (JS_DefinePropertyValueStr(ctx, indices_groups,
  50880. name, val, prop_flags) < 0) {
  50881. JS_FreeValue(ctx, val);
  50882. goto fail;
  50883. }
  50884. }
  50885. if (JS_DefinePropertyValueUint32(ctx, indices, i, val,
  50886. prop_flags) < 0) {
  50887. goto fail;
  50888. }
  50889. }
  50890. JSValue val = JS_UNDEFINED;
  50891. if (start != -1) {
  50892. val = js_sub_string(ctx, str, start, end);
  50893. if (JS_IsException(val))
  50894. goto fail;
  50895. }
  50896. if (name) {
  50897. if (JS_DefinePropertyValueStr(ctx, groups, name,
  50898. js_dup(val),
  50899. prop_flags) < 0) {
  50900. JS_FreeValue(ctx, val);
  50901. goto fail;
  50902. }
  50903. }
  50904. if (JS_DefinePropertyValueUint32(ctx, obj, i, val, prop_flags) < 0)
  50905. goto fail;
  50906. }
  50907. t = groups, groups = JS_UNDEFINED;
  50908. if (JS_DefinePropertyValue(ctx, obj, JS_ATOM_groups,
  50909. t, prop_flags) < 0) {
  50910. goto fail;
  50911. }
  50912. t = js_int32((capture[0] - str_buf) >> shift);
  50913. if (JS_DefinePropertyValue(ctx, obj, JS_ATOM_index, t, prop_flags) < 0)
  50914. goto fail;
  50915. t = str_val, str_val = JS_UNDEFINED;
  50916. if (JS_DefinePropertyValue(ctx, obj, JS_ATOM_input, t, prop_flags) < 0)
  50917. goto fail;
  50918. if (!JS_IsUndefined(indices)) {
  50919. t = indices_groups, indices_groups = JS_UNDEFINED;
  50920. if (JS_DefinePropertyValue(ctx, indices, JS_ATOM_groups,
  50921. t, prop_flags) < 0) {
  50922. goto fail;
  50923. }
  50924. t = indices, indices = JS_UNDEFINED;
  50925. if (JS_DefinePropertyValue(ctx, obj, JS_ATOM_indices,
  50926. t, prop_flags) < 0) {
  50927. goto fail;
  50928. }
  50929. }
  50930. }
  50931. ret = obj;
  50932. obj = JS_UNDEFINED;
  50933. fail:
  50934. JS_FreeValue(ctx, indices_groups);
  50935. JS_FreeValue(ctx, indices);
  50936. JS_FreeValue(ctx, str_val);
  50937. JS_FreeValue(ctx, groups);
  50938. JS_FreeValue(ctx, obj);
  50939. js_free(ctx, capture);
  50940. return ret;
  50941. }
  50942. /* delete portions of a string that match a given regex */
  50943. static JSValue JS_RegExpDelete(JSContext *ctx, JSValueConst this_val, JSValue arg)
  50944. {
  50945. JSRegExp *re = js_get_regexp(ctx, this_val, true);
  50946. JSString *str;
  50947. JSValue str_val, val;
  50948. uint8_t *re_bytecode;
  50949. int ret;
  50950. uint8_t **capture, *str_buf;
  50951. int capture_count, shift, re_flags;
  50952. int next_src_pos, start, end;
  50953. int64_t last_index;
  50954. StringBuffer b_s, *b = &b_s;
  50955. if (!re)
  50956. return JS_EXCEPTION;
  50957. string_buffer_init(ctx, b, 0);
  50958. capture = NULL;
  50959. str_val = JS_ToString(ctx, arg);
  50960. if (JS_IsException(str_val))
  50961. goto fail;
  50962. str = JS_VALUE_GET_STRING(str_val);
  50963. re_bytecode = str8(re->bytecode);
  50964. re_flags = lre_get_flags(re_bytecode);
  50965. if ((re_flags & (LRE_FLAG_GLOBAL | LRE_FLAG_STICKY)) == 0) {
  50966. last_index = 0;
  50967. } else {
  50968. val = JS_GetProperty(ctx, this_val, JS_ATOM_lastIndex);
  50969. if (JS_IsException(val) || JS_ToLengthFree(ctx, &last_index, val))
  50970. goto fail;
  50971. }
  50972. capture_count = lre_get_capture_count(re_bytecode);
  50973. if (capture_count > 0) {
  50974. capture = js_malloc(ctx, sizeof(capture[0]) * capture_count * 2);
  50975. if (!capture)
  50976. goto fail;
  50977. }
  50978. shift = str->is_wide_char;
  50979. str_buf = str8(str);
  50980. next_src_pos = 0;
  50981. for (;;) {
  50982. if (last_index > str->len)
  50983. break;
  50984. ret = lre_exec(capture, re_bytecode,
  50985. str_buf, last_index, str->len, shift, ctx);
  50986. if (ret != 1) {
  50987. if (ret >= 0) {
  50988. if (ret == 2 || (re_flags & (LRE_FLAG_GLOBAL | LRE_FLAG_STICKY))) {
  50989. if (JS_SetProperty(ctx, this_val, JS_ATOM_lastIndex,
  50990. js_int32(0)) < 0)
  50991. goto fail;
  50992. }
  50993. } else {
  50994. JS_ThrowInternalError(ctx, "out of memory in regexp execution");
  50995. goto fail;
  50996. }
  50997. break;
  50998. }
  50999. start = (capture[0] - str_buf) >> shift;
  51000. end = (capture[1] - str_buf) >> shift;
  51001. last_index = end;
  51002. if (next_src_pos < start) {
  51003. if (string_buffer_concat(b, str, next_src_pos, start))
  51004. goto fail;
  51005. }
  51006. next_src_pos = end;
  51007. if (!(re_flags & LRE_FLAG_GLOBAL)) {
  51008. if (JS_SetProperty(ctx, this_val, JS_ATOM_lastIndex,
  51009. js_int32(end)) < 0)
  51010. goto fail;
  51011. break;
  51012. }
  51013. if (end == start) {
  51014. if (!(re_flags & LRE_FLAG_UNICODE) || (unsigned)end >= str->len || !str->is_wide_char) {
  51015. end++;
  51016. } else {
  51017. string_getc(str, &end);
  51018. }
  51019. }
  51020. last_index = end;
  51021. }
  51022. if (string_buffer_concat(b, str, next_src_pos, str->len))
  51023. goto fail;
  51024. JS_FreeValue(ctx, str_val);
  51025. js_free(ctx, capture);
  51026. return string_buffer_end(b);
  51027. fail:
  51028. JS_FreeValue(ctx, str_val);
  51029. js_free(ctx, capture);
  51030. string_buffer_free(b);
  51031. return JS_EXCEPTION;
  51032. }
  51033. static JSValue JS_RegExpExec(JSContext *ctx, JSValueConst r, JSValueConst s)
  51034. {
  51035. JSValue method, ret;
  51036. method = JS_GetProperty(ctx, r, JS_ATOM_exec);
  51037. if (JS_IsException(method))
  51038. return method;
  51039. if (JS_IsFunction(ctx, method)) {
  51040. ret = JS_CallFree(ctx, method, r, 1, &s);
  51041. if (JS_IsException(ret))
  51042. return ret;
  51043. if (!JS_IsObject(ret) && !JS_IsNull(ret)) {
  51044. JS_FreeValue(ctx, ret);
  51045. return JS_ThrowTypeError(ctx, "RegExp exec method must return an object or null");
  51046. }
  51047. return ret;
  51048. }
  51049. JS_FreeValue(ctx, method);
  51050. return js_regexp_exec(ctx, r, 1, &s);
  51051. }
  51052. static JSValue js_regexp_test(JSContext *ctx, JSValueConst this_val,
  51053. int argc, JSValueConst *argv)
  51054. {
  51055. JSValue val;
  51056. bool ret;
  51057. val = JS_RegExpExec(ctx, this_val, argv[0]);
  51058. if (JS_IsException(val))
  51059. return JS_EXCEPTION;
  51060. ret = !JS_IsNull(val);
  51061. JS_FreeValue(ctx, val);
  51062. return js_bool(ret);
  51063. }
  51064. static JSValue js_regexp_Symbol_match(JSContext *ctx, JSValueConst this_val,
  51065. int argc, JSValueConst *argv)
  51066. {
  51067. // [Symbol.match](str)
  51068. JSValueConst rx = this_val;
  51069. JSValue A, S, flags, result, matchStr;
  51070. int global, n, fullUnicode, isEmpty;
  51071. JSString *p;
  51072. if (!JS_IsObject(rx))
  51073. return JS_ThrowTypeErrorNotAnObject(ctx);
  51074. A = JS_UNDEFINED;
  51075. flags = JS_UNDEFINED;
  51076. result = JS_UNDEFINED;
  51077. matchStr = JS_UNDEFINED;
  51078. S = JS_ToString(ctx, argv[0]);
  51079. if (JS_IsException(S))
  51080. goto exception;
  51081. flags = JS_GetProperty(ctx, rx, JS_ATOM_flags);
  51082. if (JS_IsException(flags))
  51083. goto exception;
  51084. flags = JS_ToStringFree(ctx, flags);
  51085. if (JS_IsException(flags))
  51086. goto exception;
  51087. p = JS_VALUE_GET_STRING(flags);
  51088. // TODO(bnoordhuis) query 'u' flag the same way?
  51089. global = (-1 != string_indexof_char(p, 'g', 0));
  51090. if (!global) {
  51091. A = JS_RegExpExec(ctx, rx, S);
  51092. } else {
  51093. fullUnicode = JS_ToBoolFree(ctx, JS_GetProperty(ctx, rx, JS_ATOM_unicode));
  51094. if (fullUnicode < 0)
  51095. goto exception;
  51096. if (JS_SetProperty(ctx, rx, JS_ATOM_lastIndex, js_int32(0)) < 0)
  51097. goto exception;
  51098. A = JS_NewArray(ctx);
  51099. if (JS_IsException(A))
  51100. goto exception;
  51101. n = 0;
  51102. for(;;) {
  51103. JS_FreeValue(ctx, result);
  51104. result = JS_RegExpExec(ctx, rx, S);
  51105. if (JS_IsException(result))
  51106. goto exception;
  51107. if (JS_IsNull(result))
  51108. break;
  51109. matchStr = JS_ToStringFree(ctx, JS_GetPropertyInt64(ctx, result, 0));
  51110. if (JS_IsException(matchStr))
  51111. goto exception;
  51112. isEmpty = JS_IsEmptyString(matchStr);
  51113. if (JS_SetPropertyInt64(ctx, A, n++, matchStr) < 0)
  51114. goto exception;
  51115. if (isEmpty) {
  51116. int64_t thisIndex, nextIndex;
  51117. if (JS_ToLengthFree(ctx, &thisIndex,
  51118. JS_GetProperty(ctx, rx, JS_ATOM_lastIndex)) < 0)
  51119. goto exception;
  51120. p = JS_VALUE_GET_STRING(S);
  51121. nextIndex = string_advance_index(p, thisIndex, fullUnicode);
  51122. if (JS_SetProperty(ctx, rx, JS_ATOM_lastIndex, js_int64(nextIndex)) < 0)
  51123. goto exception;
  51124. }
  51125. }
  51126. if (n == 0) {
  51127. JS_FreeValue(ctx, A);
  51128. A = JS_NULL;
  51129. }
  51130. }
  51131. JS_FreeValue(ctx, result);
  51132. JS_FreeValue(ctx, flags);
  51133. JS_FreeValue(ctx, S);
  51134. return A;
  51135. exception:
  51136. JS_FreeValue(ctx, A);
  51137. JS_FreeValue(ctx, result);
  51138. JS_FreeValue(ctx, flags);
  51139. JS_FreeValue(ctx, S);
  51140. return JS_EXCEPTION;
  51141. }
  51142. typedef struct JSRegExpStringIteratorData {
  51143. JSValue iterating_regexp;
  51144. JSValue iterated_string;
  51145. bool global;
  51146. bool unicode;
  51147. int done;
  51148. } JSRegExpStringIteratorData;
  51149. static void js_regexp_string_iterator_finalizer(JSRuntime *rt,
  51150. JSValueConst val)
  51151. {
  51152. JSObject *p = JS_VALUE_GET_OBJ(val);
  51153. JSRegExpStringIteratorData *it = p->u.regexp_string_iterator_data;
  51154. if (it) {
  51155. JS_FreeValueRT(rt, it->iterating_regexp);
  51156. JS_FreeValueRT(rt, it->iterated_string);
  51157. js_free_rt(rt, it);
  51158. }
  51159. }
  51160. static void js_regexp_string_iterator_mark(JSRuntime *rt, JSValueConst val,
  51161. JS_MarkFunc *mark_func)
  51162. {
  51163. JSObject *p = JS_VALUE_GET_OBJ(val);
  51164. JSRegExpStringIteratorData *it = p->u.regexp_string_iterator_data;
  51165. if (it) {
  51166. JS_MarkValue(rt, it->iterating_regexp, mark_func);
  51167. JS_MarkValue(rt, it->iterated_string, mark_func);
  51168. }
  51169. }
  51170. static JSValue js_regexp_string_iterator_next(JSContext *ctx,
  51171. JSValueConst this_val,
  51172. int argc, JSValueConst *argv,
  51173. int *pdone, int magic)
  51174. {
  51175. JSRegExpStringIteratorData *it;
  51176. JSValue R, S;
  51177. JSValue matchStr = JS_UNDEFINED, match = JS_UNDEFINED;
  51178. JSString *sp;
  51179. it = JS_GetOpaque2(ctx, this_val, JS_CLASS_REGEXP_STRING_ITERATOR);
  51180. if (!it)
  51181. goto exception;
  51182. if (it->done) {
  51183. *pdone = true;
  51184. return JS_UNDEFINED;
  51185. }
  51186. R = it->iterating_regexp;
  51187. S = it->iterated_string;
  51188. match = JS_RegExpExec(ctx, R, S);
  51189. if (JS_IsException(match))
  51190. goto exception;
  51191. if (JS_IsNull(match)) {
  51192. it->done = true;
  51193. *pdone = true;
  51194. return JS_UNDEFINED;
  51195. } else if (it->global) {
  51196. matchStr = JS_ToStringFree(ctx, JS_GetPropertyInt64(ctx, match, 0));
  51197. if (JS_IsException(matchStr))
  51198. goto exception;
  51199. if (JS_IsEmptyString(matchStr)) {
  51200. int64_t thisIndex, nextIndex;
  51201. if (JS_ToLengthFree(ctx, &thisIndex,
  51202. JS_GetProperty(ctx, R, JS_ATOM_lastIndex)) < 0)
  51203. goto exception;
  51204. sp = JS_VALUE_GET_STRING(S);
  51205. nextIndex = string_advance_index(sp, thisIndex, it->unicode);
  51206. if (JS_SetProperty(ctx, R, JS_ATOM_lastIndex, js_int64(nextIndex)) < 0)
  51207. goto exception;
  51208. }
  51209. JS_FreeValue(ctx, matchStr);
  51210. } else {
  51211. it->done = true;
  51212. }
  51213. *pdone = false;
  51214. return match;
  51215. exception:
  51216. JS_FreeValue(ctx, match);
  51217. JS_FreeValue(ctx, matchStr);
  51218. *pdone = false;
  51219. return JS_EXCEPTION;
  51220. }
  51221. static JSValue js_regexp_Symbol_matchAll(JSContext *ctx, JSValueConst this_val,
  51222. int argc, JSValueConst *argv)
  51223. {
  51224. // [Symbol.matchAll](str)
  51225. JSValueConst R = this_val;
  51226. JSValue S, C, flags, matcher, iter;
  51227. JSValueConst args[2];
  51228. JSString *strp;
  51229. int64_t lastIndex;
  51230. JSRegExpStringIteratorData *it;
  51231. if (!JS_IsObject(R))
  51232. return JS_ThrowTypeErrorNotAnObject(ctx);
  51233. C = JS_UNDEFINED;
  51234. flags = JS_UNDEFINED;
  51235. matcher = JS_UNDEFINED;
  51236. iter = JS_UNDEFINED;
  51237. S = JS_ToString(ctx, argv[0]);
  51238. if (JS_IsException(S))
  51239. goto exception;
  51240. C = JS_SpeciesConstructor(ctx, R, ctx->regexp_ctor);
  51241. if (JS_IsException(C))
  51242. goto exception;
  51243. flags = JS_ToStringFree(ctx, JS_GetProperty(ctx, R, JS_ATOM_flags));
  51244. if (JS_IsException(flags))
  51245. goto exception;
  51246. args[0] = R;
  51247. args[1] = flags;
  51248. matcher = JS_CallConstructor(ctx, C, 2, args);
  51249. if (JS_IsException(matcher))
  51250. goto exception;
  51251. if (JS_ToLengthFree(ctx, &lastIndex,
  51252. JS_GetProperty(ctx, R, JS_ATOM_lastIndex)))
  51253. goto exception;
  51254. if (JS_SetProperty(ctx, matcher, JS_ATOM_lastIndex, js_int64(lastIndex)) < 0)
  51255. goto exception;
  51256. iter = JS_NewObjectClass(ctx, JS_CLASS_REGEXP_STRING_ITERATOR);
  51257. if (JS_IsException(iter))
  51258. goto exception;
  51259. it = js_malloc(ctx, sizeof(*it));
  51260. if (!it)
  51261. goto exception;
  51262. it->iterating_regexp = matcher;
  51263. it->iterated_string = S;
  51264. strp = JS_VALUE_GET_STRING(flags);
  51265. it->global = string_indexof_char(strp, 'g', 0) >= 0;
  51266. it->unicode = string_indexof_char(strp, 'u', 0) >= 0;
  51267. it->done = false;
  51268. JS_SetOpaqueInternal(iter, it);
  51269. JS_FreeValue(ctx, C);
  51270. JS_FreeValue(ctx, flags);
  51271. return iter;
  51272. exception:
  51273. JS_FreeValue(ctx, S);
  51274. JS_FreeValue(ctx, C);
  51275. JS_FreeValue(ctx, flags);
  51276. JS_FreeValue(ctx, matcher);
  51277. JS_FreeValue(ctx, iter);
  51278. return JS_EXCEPTION;
  51279. }
  51280. typedef struct ValueBuffer {
  51281. JSContext *ctx;
  51282. JSValue *arr;
  51283. JSValue def[4];
  51284. int len;
  51285. int size;
  51286. int error_status;
  51287. } ValueBuffer;
  51288. static int value_buffer_init(JSContext *ctx, ValueBuffer *b)
  51289. {
  51290. b->ctx = ctx;
  51291. b->len = 0;
  51292. b->size = 4;
  51293. b->error_status = 0;
  51294. b->arr = b->def;
  51295. return 0;
  51296. }
  51297. static void value_buffer_free(ValueBuffer *b)
  51298. {
  51299. while (b->len > 0)
  51300. JS_FreeValue(b->ctx, b->arr[--b->len]);
  51301. if (b->arr != b->def)
  51302. js_free(b->ctx, b->arr);
  51303. b->arr = b->def;
  51304. b->size = 4;
  51305. }
  51306. static int value_buffer_append(ValueBuffer *b, JSValue val)
  51307. {
  51308. if (b->error_status)
  51309. return -1;
  51310. if (b->len >= b->size) {
  51311. int new_size = (b->len + (b->len >> 1) + 31) & ~16;
  51312. size_t slack;
  51313. JSValue *new_arr;
  51314. if (b->arr == b->def) {
  51315. new_arr = js_realloc2(b->ctx, NULL, sizeof(*b->arr) * new_size, &slack);
  51316. if (new_arr)
  51317. memcpy(new_arr, b->def, sizeof b->def);
  51318. } else {
  51319. new_arr = js_realloc2(b->ctx, b->arr, sizeof(*b->arr) * new_size, &slack);
  51320. }
  51321. if (!new_arr) {
  51322. value_buffer_free(b);
  51323. JS_FreeValue(b->ctx, val);
  51324. b->error_status = -1;
  51325. return -1;
  51326. }
  51327. new_size += slack / sizeof(*new_arr);
  51328. b->arr = new_arr;
  51329. b->size = new_size;
  51330. }
  51331. b->arr[b->len++] = val;
  51332. return 0;
  51333. }
  51334. static int js_is_standard_regexp(JSContext *ctx, JSValueConst rx)
  51335. {
  51336. JSValue val;
  51337. int res;
  51338. val = JS_GetProperty(ctx, rx, JS_ATOM_constructor);
  51339. if (JS_IsException(val))
  51340. return -1;
  51341. // rx.constructor === RegExp
  51342. res = js_same_value(ctx, val, ctx->regexp_ctor);
  51343. JS_FreeValue(ctx, val);
  51344. if (res) {
  51345. val = JS_GetProperty(ctx, rx, JS_ATOM_exec);
  51346. if (JS_IsException(val))
  51347. return -1;
  51348. // rx.exec === RE_exec
  51349. res = JS_IsCFunction(ctx, val, js_regexp_exec, 0);
  51350. JS_FreeValue(ctx, val);
  51351. }
  51352. return res;
  51353. }
  51354. static JSValue js_regexp_Symbol_replace(JSContext *ctx, JSValueConst this_val,
  51355. int argc, JSValueConst *argv)
  51356. {
  51357. // [Symbol.replace](str, rep)
  51358. JSValueConst rx = this_val, rep = argv[1];
  51359. JSValueConst args[6];
  51360. JSValue flags, str, rep_val, matched, tab, rep_str, namedCaptures, res;
  51361. JSString *p, *sp, *rp;
  51362. StringBuffer b_s, *b = &b_s;
  51363. ValueBuffer v_b, *results = &v_b;
  51364. int nextSourcePosition, n, j, functionalReplace, is_global, fullUnicode;
  51365. uint32_t nCaptures;
  51366. int64_t position;
  51367. if (!JS_IsObject(rx))
  51368. return JS_ThrowTypeErrorNotAnObject(ctx);
  51369. string_buffer_init(ctx, b, 0);
  51370. value_buffer_init(ctx, results);
  51371. rep_val = JS_UNDEFINED;
  51372. matched = JS_UNDEFINED;
  51373. tab = JS_UNDEFINED;
  51374. flags = JS_UNDEFINED;
  51375. rep_str = JS_UNDEFINED;
  51376. namedCaptures = JS_UNDEFINED;
  51377. str = JS_ToString(ctx, argv[0]);
  51378. if (JS_IsException(str))
  51379. goto exception;
  51380. sp = JS_VALUE_GET_STRING(str);
  51381. rp = NULL;
  51382. functionalReplace = JS_IsFunction(ctx, rep);
  51383. if (!functionalReplace) {
  51384. rep_val = JS_ToString(ctx, rep);
  51385. if (JS_IsException(rep_val))
  51386. goto exception;
  51387. rp = JS_VALUE_GET_STRING(rep_val);
  51388. }
  51389. flags = JS_GetProperty(ctx, rx, JS_ATOM_flags);
  51390. if (JS_IsException(flags))
  51391. goto exception;
  51392. flags = JS_ToStringFree(ctx, flags);
  51393. if (JS_IsException(flags))
  51394. goto exception;
  51395. p = JS_VALUE_GET_STRING(flags);
  51396. // TODO(bnoordhuis) query 'u' flag the same way?
  51397. fullUnicode = 0;
  51398. is_global = (-1 != string_indexof_char(p, 'g', 0));
  51399. if (is_global) {
  51400. fullUnicode = JS_ToBoolFree(ctx, JS_GetProperty(ctx, rx, JS_ATOM_unicode));
  51401. if (fullUnicode < 0)
  51402. goto exception;
  51403. if (JS_SetProperty(ctx, rx, JS_ATOM_lastIndex, js_int32(0)) < 0)
  51404. goto exception;
  51405. }
  51406. if (rp && rp->len == 0 && is_global && js_is_standard_regexp(ctx, rx)) {
  51407. /* use faster version for simple cases */
  51408. res = JS_RegExpDelete(ctx, rx, str);
  51409. goto done;
  51410. }
  51411. for(;;) {
  51412. JSValue result;
  51413. result = JS_RegExpExec(ctx, rx, str);
  51414. if (JS_IsException(result))
  51415. goto exception;
  51416. if (JS_IsNull(result))
  51417. break;
  51418. if (value_buffer_append(results, result) < 0)
  51419. goto exception;
  51420. if (!is_global)
  51421. break;
  51422. JS_FreeValue(ctx, matched);
  51423. matched = JS_ToStringFree(ctx, JS_GetPropertyInt64(ctx, result, 0));
  51424. if (JS_IsException(matched))
  51425. goto exception;
  51426. if (JS_IsEmptyString(matched)) {
  51427. /* always advance of at least one char */
  51428. int64_t thisIndex, nextIndex;
  51429. if (JS_ToLengthFree(ctx, &thisIndex, JS_GetProperty(ctx, rx, JS_ATOM_lastIndex)) < 0)
  51430. goto exception;
  51431. nextIndex = string_advance_index(sp, thisIndex, fullUnicode);
  51432. if (JS_SetProperty(ctx, rx, JS_ATOM_lastIndex, js_int64(nextIndex)) < 0)
  51433. goto exception;
  51434. }
  51435. }
  51436. nextSourcePosition = 0;
  51437. for(j = 0; j < results->len; j++) {
  51438. JSValue result;
  51439. result = results->arr[j];
  51440. if (js_get_length32(ctx, &nCaptures, result) < 0)
  51441. goto exception;
  51442. JS_FreeValue(ctx, matched);
  51443. matched = JS_ToStringFree(ctx, JS_GetPropertyInt64(ctx, result, 0));
  51444. if (JS_IsException(matched))
  51445. goto exception;
  51446. if (JS_ToLengthFree(ctx, &position, JS_GetProperty(ctx, result, JS_ATOM_index)))
  51447. goto exception;
  51448. if (position > sp->len)
  51449. position = sp->len;
  51450. else if (position < 0)
  51451. position = 0;
  51452. /* ignore substition if going backward (can happen
  51453. with custom regexp object) */
  51454. JS_FreeValue(ctx, tab);
  51455. tab = JS_NewArray(ctx);
  51456. if (JS_IsException(tab))
  51457. goto exception;
  51458. if (JS_DefinePropertyValueInt64(ctx, tab, 0, js_dup(matched),
  51459. JS_PROP_C_W_E | JS_PROP_THROW) < 0)
  51460. goto exception;
  51461. for(n = 1; n < nCaptures; n++) {
  51462. JSValue capN;
  51463. capN = JS_GetPropertyInt64(ctx, result, n);
  51464. if (JS_IsException(capN))
  51465. goto exception;
  51466. if (!JS_IsUndefined(capN)) {
  51467. capN = JS_ToStringFree(ctx, capN);
  51468. if (JS_IsException(capN))
  51469. goto exception;
  51470. }
  51471. if (JS_DefinePropertyValueInt64(ctx, tab, n, capN,
  51472. JS_PROP_C_W_E | JS_PROP_THROW) < 0)
  51473. goto exception;
  51474. }
  51475. JS_FreeValue(ctx, namedCaptures);
  51476. namedCaptures = JS_GetProperty(ctx, result, JS_ATOM_groups);
  51477. if (JS_IsException(namedCaptures))
  51478. goto exception;
  51479. if (functionalReplace) {
  51480. if (JS_DefinePropertyValueInt64(ctx, tab, n++, js_int32(position), JS_PROP_C_W_E | JS_PROP_THROW) < 0)
  51481. goto exception;
  51482. if (JS_DefinePropertyValueInt64(ctx, tab, n++, js_dup(str), JS_PROP_C_W_E | JS_PROP_THROW) < 0)
  51483. goto exception;
  51484. if (!JS_IsUndefined(namedCaptures)) {
  51485. if (JS_DefinePropertyValueInt64(ctx, tab, n++, js_dup(namedCaptures), JS_PROP_C_W_E | JS_PROP_THROW) < 0)
  51486. goto exception;
  51487. }
  51488. args[0] = JS_UNDEFINED;
  51489. args[1] = tab;
  51490. JS_FreeValue(ctx, rep_str);
  51491. rep_str = JS_ToStringFree(ctx, js_function_apply(ctx, rep, 2, args, 0));
  51492. } else {
  51493. JSValue namedCaptures1;
  51494. if (!JS_IsUndefined(namedCaptures)) {
  51495. namedCaptures1 = JS_ToObject(ctx, namedCaptures);
  51496. if (JS_IsException(namedCaptures1))
  51497. goto exception;
  51498. } else {
  51499. namedCaptures1 = JS_UNDEFINED;
  51500. }
  51501. args[0] = matched;
  51502. args[1] = str;
  51503. args[2] = js_int32(position);
  51504. args[3] = tab;
  51505. args[4] = namedCaptures1;
  51506. args[5] = rep_val;
  51507. JS_FreeValue(ctx, rep_str);
  51508. rep_str = js_string___GetSubstitution(ctx, JS_UNDEFINED, 6, args);
  51509. JS_FreeValue(ctx, namedCaptures1);
  51510. }
  51511. if (JS_IsException(rep_str))
  51512. goto exception;
  51513. if (position >= nextSourcePosition) {
  51514. string_buffer_concat(b, sp, nextSourcePosition, position);
  51515. string_buffer_concat_value(b, rep_str);
  51516. nextSourcePosition = position + JS_VALUE_GET_STRING(matched)->len;
  51517. }
  51518. }
  51519. string_buffer_concat(b, sp, nextSourcePosition, sp->len);
  51520. res = string_buffer_end(b);
  51521. goto done1;
  51522. exception:
  51523. res = JS_EXCEPTION;
  51524. done:
  51525. string_buffer_free(b);
  51526. done1:
  51527. value_buffer_free(results);
  51528. JS_FreeValue(ctx, rep_val);
  51529. JS_FreeValue(ctx, matched);
  51530. JS_FreeValue(ctx, flags);
  51531. JS_FreeValue(ctx, tab);
  51532. JS_FreeValue(ctx, rep_str);
  51533. JS_FreeValue(ctx, namedCaptures);
  51534. JS_FreeValue(ctx, str);
  51535. return res;
  51536. }
  51537. static JSValue js_regexp_Symbol_search(JSContext *ctx, JSValueConst this_val,
  51538. int argc, JSValueConst *argv)
  51539. {
  51540. JSValueConst rx = this_val;
  51541. JSValue str, previousLastIndex, currentLastIndex, result, index;
  51542. if (!JS_IsObject(rx))
  51543. return JS_ThrowTypeErrorNotAnObject(ctx);
  51544. result = JS_UNDEFINED;
  51545. currentLastIndex = JS_UNDEFINED;
  51546. previousLastIndex = JS_UNDEFINED;
  51547. str = JS_ToString(ctx, argv[0]);
  51548. if (JS_IsException(str))
  51549. goto exception;
  51550. previousLastIndex = JS_GetProperty(ctx, rx, JS_ATOM_lastIndex);
  51551. if (JS_IsException(previousLastIndex))
  51552. goto exception;
  51553. if (!js_same_value(ctx, previousLastIndex, js_int32(0))) {
  51554. if (JS_SetProperty(ctx, rx, JS_ATOM_lastIndex, js_int32(0)) < 0) {
  51555. goto exception;
  51556. }
  51557. }
  51558. result = JS_RegExpExec(ctx, rx, str);
  51559. if (JS_IsException(result))
  51560. goto exception;
  51561. currentLastIndex = JS_GetProperty(ctx, rx, JS_ATOM_lastIndex);
  51562. if (JS_IsException(currentLastIndex))
  51563. goto exception;
  51564. if (js_same_value(ctx, currentLastIndex, previousLastIndex)) {
  51565. JS_FreeValue(ctx, previousLastIndex);
  51566. } else {
  51567. if (JS_SetProperty(ctx, rx, JS_ATOM_lastIndex, previousLastIndex) < 0) {
  51568. previousLastIndex = JS_UNDEFINED;
  51569. goto exception;
  51570. }
  51571. }
  51572. JS_FreeValue(ctx, str);
  51573. JS_FreeValue(ctx, currentLastIndex);
  51574. if (JS_IsNull(result)) {
  51575. return js_int32(-1);
  51576. } else {
  51577. index = JS_GetProperty(ctx, result, JS_ATOM_index);
  51578. JS_FreeValue(ctx, result);
  51579. return index;
  51580. }
  51581. exception:
  51582. JS_FreeValue(ctx, result);
  51583. JS_FreeValue(ctx, str);
  51584. JS_FreeValue(ctx, currentLastIndex);
  51585. JS_FreeValue(ctx, previousLastIndex);
  51586. return JS_EXCEPTION;
  51587. }
  51588. static JSValue js_regexp_Symbol_split(JSContext *ctx, JSValueConst this_val,
  51589. int argc, JSValueConst *argv)
  51590. {
  51591. // [Symbol.split](str, limit)
  51592. JSValueConst rx = this_val;
  51593. JSValueConst args[2];
  51594. JSValue str, ctor, splitter, A, flags, z, sub;
  51595. JSString *strp;
  51596. uint32_t lim, size, p, q;
  51597. int unicodeMatching;
  51598. int64_t lengthA, e, numberOfCaptures, i;
  51599. if (!JS_IsObject(rx))
  51600. return JS_ThrowTypeErrorNotAnObject(ctx);
  51601. ctor = JS_UNDEFINED;
  51602. splitter = JS_UNDEFINED;
  51603. A = JS_UNDEFINED;
  51604. flags = JS_UNDEFINED;
  51605. z = JS_UNDEFINED;
  51606. str = JS_ToString(ctx, argv[0]);
  51607. if (JS_IsException(str))
  51608. goto exception;
  51609. ctor = JS_SpeciesConstructor(ctx, rx, ctx->regexp_ctor);
  51610. if (JS_IsException(ctor))
  51611. goto exception;
  51612. flags = JS_ToStringFree(ctx, JS_GetProperty(ctx, rx, JS_ATOM_flags));
  51613. if (JS_IsException(flags))
  51614. goto exception;
  51615. strp = JS_VALUE_GET_STRING(flags);
  51616. unicodeMatching = string_indexof_char(strp, 'u', 0) >= 0;
  51617. if (string_indexof_char(strp, 'y', 0) < 0) {
  51618. flags = JS_ConcatString3(ctx, "", flags, "y");
  51619. if (JS_IsException(flags))
  51620. goto exception;
  51621. }
  51622. args[0] = rx;
  51623. args[1] = flags;
  51624. splitter = JS_CallConstructor(ctx, ctor, 2, args);
  51625. if (JS_IsException(splitter))
  51626. goto exception;
  51627. A = JS_NewArray(ctx);
  51628. if (JS_IsException(A))
  51629. goto exception;
  51630. lengthA = 0;
  51631. if (JS_IsUndefined(argv[1])) {
  51632. lim = 0xffffffff;
  51633. } else {
  51634. if (JS_ToUint32(ctx, &lim, argv[1]) < 0)
  51635. goto exception;
  51636. if (lim == 0)
  51637. goto done;
  51638. }
  51639. strp = JS_VALUE_GET_STRING(str);
  51640. p = q = 0;
  51641. size = strp->len;
  51642. if (size == 0) {
  51643. z = JS_RegExpExec(ctx, splitter, str);
  51644. if (JS_IsException(z))
  51645. goto exception;
  51646. if (JS_IsNull(z))
  51647. goto add_tail;
  51648. goto done;
  51649. }
  51650. while (q < size) {
  51651. if (JS_SetProperty(ctx, splitter, JS_ATOM_lastIndex, js_int32(q)) < 0)
  51652. goto exception;
  51653. JS_FreeValue(ctx, z);
  51654. z = JS_RegExpExec(ctx, splitter, str);
  51655. if (JS_IsException(z))
  51656. goto exception;
  51657. if (JS_IsNull(z)) {
  51658. q = string_advance_index(strp, q, unicodeMatching);
  51659. } else {
  51660. if (JS_ToLengthFree(ctx, &e, JS_GetProperty(ctx, splitter, JS_ATOM_lastIndex)))
  51661. goto exception;
  51662. if (e > size)
  51663. e = size;
  51664. if (e == p) {
  51665. q = string_advance_index(strp, q, unicodeMatching);
  51666. } else {
  51667. sub = js_sub_string(ctx, strp, p, q);
  51668. if (JS_IsException(sub))
  51669. goto exception;
  51670. if (JS_DefinePropertyValueInt64(ctx, A, lengthA++, sub,
  51671. JS_PROP_C_W_E | JS_PROP_THROW) < 0)
  51672. goto exception;
  51673. if (lengthA == lim)
  51674. goto done;
  51675. p = e;
  51676. if (js_get_length64(ctx, &numberOfCaptures, z))
  51677. goto exception;
  51678. for(i = 1; i < numberOfCaptures; i++) {
  51679. sub = JS_GetPropertyInt64(ctx, z, i);
  51680. if (JS_IsException(sub))
  51681. goto exception;
  51682. if (!JS_IsUndefined(sub)) {
  51683. sub = JS_ToStringFree(ctx, sub);
  51684. if (JS_IsException(sub))
  51685. goto exception;
  51686. }
  51687. if (JS_DefinePropertyValueInt64(ctx, A, lengthA++, sub, JS_PROP_C_W_E | JS_PROP_THROW) < 0)
  51688. goto exception;
  51689. if (lengthA == lim)
  51690. goto done;
  51691. }
  51692. q = p;
  51693. }
  51694. }
  51695. }
  51696. add_tail:
  51697. if (p > size)
  51698. p = size;
  51699. sub = js_sub_string(ctx, strp, p, size);
  51700. if (JS_IsException(sub))
  51701. goto exception;
  51702. if (JS_DefinePropertyValueInt64(ctx, A, lengthA++, sub, JS_PROP_C_W_E | JS_PROP_THROW) < 0)
  51703. goto exception;
  51704. goto done;
  51705. exception:
  51706. JS_FreeValue(ctx, A);
  51707. A = JS_EXCEPTION;
  51708. done:
  51709. JS_FreeValue(ctx, str);
  51710. JS_FreeValue(ctx, ctor);
  51711. JS_FreeValue(ctx, splitter);
  51712. JS_FreeValue(ctx, flags);
  51713. JS_FreeValue(ctx, z);
  51714. return A;
  51715. }
  51716. static const JSCFunctionListEntry js_regexp_funcs[] = {
  51717. JS_CFUNC_DEF("escape", 1, js_regexp_escape ),
  51718. JS_CGETSET_DEF("[Symbol.species]", js_get_this, NULL ),
  51719. };
  51720. static const JSCFunctionListEntry js_regexp_proto_funcs[] = {
  51721. JS_CGETSET_DEF("flags", js_regexp_get_flags, NULL ),
  51722. JS_CGETSET_DEF("source", js_regexp_get_source, NULL ),
  51723. JS_CGETSET_MAGIC_DEF("global", js_regexp_get_flag, NULL, LRE_FLAG_GLOBAL ),
  51724. JS_CGETSET_MAGIC_DEF("ignoreCase", js_regexp_get_flag, NULL, LRE_FLAG_IGNORECASE ),
  51725. JS_CGETSET_MAGIC_DEF("multiline", js_regexp_get_flag, NULL, LRE_FLAG_MULTILINE ),
  51726. JS_CGETSET_MAGIC_DEF("dotAll", js_regexp_get_flag, NULL, LRE_FLAG_DOTALL ),
  51727. JS_CGETSET_MAGIC_DEF("unicode", js_regexp_get_flag, NULL, LRE_FLAG_UNICODE ),
  51728. JS_CGETSET_MAGIC_DEF("unicodeSets", js_regexp_get_flag, NULL, LRE_FLAG_UNICODE_SETS ),
  51729. JS_CGETSET_MAGIC_DEF("sticky", js_regexp_get_flag, NULL, LRE_FLAG_STICKY ),
  51730. JS_CGETSET_MAGIC_DEF("hasIndices", js_regexp_get_flag, NULL, LRE_FLAG_INDICES ),
  51731. JS_CFUNC_DEF("exec", 1, js_regexp_exec ),
  51732. JS_CFUNC_DEF("compile", 2, js_regexp_compile ),
  51733. JS_CFUNC_DEF("test", 1, js_regexp_test ),
  51734. JS_CFUNC_DEF("toString", 0, js_regexp_toString ),
  51735. JS_CFUNC_DEF("[Symbol.replace]", 2, js_regexp_Symbol_replace ),
  51736. JS_CFUNC_DEF("[Symbol.match]", 1, js_regexp_Symbol_match ),
  51737. JS_CFUNC_DEF("[Symbol.matchAll]", 1, js_regexp_Symbol_matchAll ),
  51738. JS_CFUNC_DEF("[Symbol.search]", 1, js_regexp_Symbol_search ),
  51739. JS_CFUNC_DEF("[Symbol.split]", 2, js_regexp_Symbol_split ),
  51740. };
  51741. static const JSCFunctionListEntry js_regexp_string_iterator_proto_funcs[] = {
  51742. JS_ITERATOR_NEXT_DEF("next", 0, js_regexp_string_iterator_next, 0 ),
  51743. JS_PROP_STRING_DEF("[Symbol.toStringTag]", "RegExp String Iterator", JS_PROP_CONFIGURABLE ),
  51744. };
  51745. void JS_AddIntrinsicRegExpCompiler(JSContext *ctx)
  51746. {
  51747. ctx->compile_regexp = js_compile_regexp;
  51748. }
  51749. void JS_AddIntrinsicRegExp(JSContext *ctx)
  51750. {
  51751. JSValue obj;
  51752. JS_AddIntrinsicRegExpCompiler(ctx);
  51753. ctx->class_proto[JS_CLASS_REGEXP] = JS_NewObject(ctx);
  51754. JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_REGEXP], js_regexp_proto_funcs,
  51755. countof(js_regexp_proto_funcs));
  51756. obj = JS_NewGlobalCConstructor(ctx, "RegExp", js_regexp_constructor, 2,
  51757. ctx->class_proto[JS_CLASS_REGEXP]);
  51758. ctx->regexp_ctor = js_dup(obj);
  51759. JS_SetPropertyFunctionList(ctx, obj, js_regexp_funcs, countof(js_regexp_funcs));
  51760. ctx->class_proto[JS_CLASS_REGEXP_STRING_ITERATOR] =
  51761. JS_NewObjectProto(ctx, ctx->class_proto[JS_CLASS_ITERATOR]);
  51762. JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_REGEXP_STRING_ITERATOR],
  51763. js_regexp_string_iterator_proto_funcs,
  51764. countof(js_regexp_string_iterator_proto_funcs));
  51765. }
  51766. /* JSON */
  51767. static JSValue json_parse_value(JSParseState *s)
  51768. {
  51769. JSContext *ctx = s->ctx;
  51770. JSValue val = JS_NULL;
  51771. int ret;
  51772. switch(s->token.val) {
  51773. case '{':
  51774. {
  51775. JSValue prop_val;
  51776. JSAtom prop_name;
  51777. if (json_next_token(s))
  51778. goto fail;
  51779. val = JS_NewObject(ctx);
  51780. if (JS_IsException(val))
  51781. goto fail;
  51782. if (s->token.val != '}') {
  51783. for(;;) {
  51784. if (s->token.val == TOK_STRING) {
  51785. prop_name = JS_ValueToAtom(ctx, s->token.u.str.str);
  51786. if (prop_name == JS_ATOM_NULL)
  51787. goto fail;
  51788. } else {
  51789. json_parse_error(s, s->token.ptr, "Expected property name or '}'");
  51790. goto fail;
  51791. }
  51792. if (json_next_token(s))
  51793. goto fail1;
  51794. if (s->token.val != ':') {
  51795. json_parse_error(s, s->token.ptr, "Expected ':' after property name");
  51796. goto fail1;
  51797. }
  51798. if (json_next_token(s))
  51799. goto fail1;
  51800. prop_val = json_parse_value(s);
  51801. if (JS_IsException(prop_val)) {
  51802. fail1:
  51803. JS_FreeAtom(ctx, prop_name);
  51804. goto fail;
  51805. }
  51806. ret = JS_DefinePropertyValue(ctx, val, prop_name,
  51807. prop_val, JS_PROP_C_W_E);
  51808. JS_FreeAtom(ctx, prop_name);
  51809. if (ret < 0)
  51810. goto fail;
  51811. if (s->token.val == '}')
  51812. break;
  51813. if (s->token.val != ',') {
  51814. json_parse_error(s, s->token.ptr, "Expected ',' or '}' after property value");
  51815. goto fail;
  51816. }
  51817. if (json_next_token(s))
  51818. goto fail;
  51819. }
  51820. }
  51821. if (json_next_token(s))
  51822. goto fail;
  51823. }
  51824. break;
  51825. case '[':
  51826. {
  51827. JSValue el;
  51828. uint32_t idx;
  51829. if (json_next_token(s))
  51830. goto fail;
  51831. val = JS_NewArray(ctx);
  51832. if (JS_IsException(val))
  51833. goto fail;
  51834. if (s->token.val != ']') {
  51835. for(idx = 0;; idx++) {
  51836. el = json_parse_value(s);
  51837. if (JS_IsException(el))
  51838. goto fail;
  51839. ret = JS_DefinePropertyValueUint32(ctx, val, idx, el, JS_PROP_C_W_E);
  51840. if (ret < 0)
  51841. goto fail;
  51842. if (s->token.val == ']')
  51843. break;
  51844. if (s->token.val != ',') {
  51845. json_parse_error(s, s->token.ptr, "Expected ',' or ']' after array element");
  51846. goto fail;
  51847. }
  51848. if (json_next_token(s))
  51849. goto fail;
  51850. }
  51851. }
  51852. if (json_next_token(s))
  51853. goto fail;
  51854. }
  51855. break;
  51856. case TOK_STRING:
  51857. val = js_dup(s->token.u.str.str);
  51858. if (json_next_token(s))
  51859. goto fail;
  51860. break;
  51861. case TOK_NUMBER:
  51862. val = s->token.u.num.val;
  51863. if (json_next_token(s))
  51864. goto fail;
  51865. break;
  51866. case TOK_IDENT:
  51867. if (s->token.u.ident.atom == JS_ATOM_false ||
  51868. s->token.u.ident.atom == JS_ATOM_true) {
  51869. val = js_bool(s->token.u.ident.atom == JS_ATOM_true);
  51870. } else if (s->token.u.ident.atom == JS_ATOM_null) {
  51871. val = JS_NULL;
  51872. } else {
  51873. goto def_token;
  51874. }
  51875. if (json_next_token(s))
  51876. goto fail;
  51877. break;
  51878. default:
  51879. def_token:
  51880. if (s->token.val == TOK_EOF) {
  51881. js_parse_error(s, "Unexpected end of JSON input");
  51882. } else {
  51883. js_parse_error(s, "unexpected token: '%.*s'",
  51884. (int)(s->buf_ptr - s->token.ptr), s->token.ptr);
  51885. }
  51886. goto fail;
  51887. }
  51888. return val;
  51889. fail:
  51890. JS_FreeValue(ctx, val);
  51891. return JS_EXCEPTION;
  51892. }
  51893. /* 'buf' must be zero terminated i.e. buf[buf_len] = '\0'. */
  51894. JSValue JS_ParseJSON(JSContext *ctx, const char *buf, size_t buf_len, const char *filename)
  51895. {
  51896. JSParseState s1, *s = &s1;
  51897. JSValue val = JS_UNDEFINED;
  51898. js_parse_init(ctx, s, buf, buf_len, filename, 1);
  51899. if (json_next_token(s))
  51900. goto fail;
  51901. val = json_parse_value(s);
  51902. if (JS_IsException(val))
  51903. goto fail;
  51904. if (s->token.val != TOK_EOF) {
  51905. if (js_parse_error(s, "unexpected data at the end"))
  51906. goto fail;
  51907. }
  51908. return val;
  51909. fail:
  51910. JS_FreeValue(ctx, val);
  51911. free_token(s, &s->token);
  51912. return JS_EXCEPTION;
  51913. }
  51914. static JSValue internalize_json_property(JSContext *ctx, JSValueConst holder,
  51915. JSAtom name, JSValueConst reviver)
  51916. {
  51917. JSValue val, new_el, name_val, res;
  51918. JSValueConst args[2];
  51919. int ret, is_array;
  51920. uint32_t i, len = 0;
  51921. JSAtom prop;
  51922. JSPropertyEnum *atoms = NULL;
  51923. if (js_check_stack_overflow(ctx->rt, 0)) {
  51924. return JS_ThrowStackOverflow(ctx);
  51925. }
  51926. val = JS_GetProperty(ctx, holder, name);
  51927. if (JS_IsException(val))
  51928. return val;
  51929. if (JS_IsObject(val)) {
  51930. is_array = js_is_array(ctx, val);
  51931. if (is_array < 0)
  51932. goto fail;
  51933. if (is_array) {
  51934. if (js_get_length32(ctx, &len, val))
  51935. goto fail;
  51936. } else {
  51937. ret = JS_GetOwnPropertyNamesInternal(ctx, &atoms, &len, JS_VALUE_GET_OBJ(val), JS_GPN_ENUM_ONLY | JS_GPN_STRING_MASK);
  51938. if (ret < 0)
  51939. goto fail;
  51940. }
  51941. for(i = 0; i < len; i++) {
  51942. if (is_array) {
  51943. prop = JS_NewAtomUInt32(ctx, i);
  51944. if (prop == JS_ATOM_NULL)
  51945. goto fail;
  51946. } else {
  51947. prop = JS_DupAtom(ctx, atoms[i].atom);
  51948. }
  51949. new_el = internalize_json_property(ctx, val, prop, reviver);
  51950. if (JS_IsException(new_el)) {
  51951. JS_FreeAtom(ctx, prop);
  51952. goto fail;
  51953. }
  51954. if (JS_IsUndefined(new_el)) {
  51955. ret = JS_DeleteProperty(ctx, val, prop, 0);
  51956. } else {
  51957. ret = JS_DefinePropertyValue(ctx, val, prop, new_el, JS_PROP_C_W_E);
  51958. }
  51959. JS_FreeAtom(ctx, prop);
  51960. if (ret < 0)
  51961. goto fail;
  51962. }
  51963. }
  51964. js_free_prop_enum(ctx, atoms, len);
  51965. atoms = NULL;
  51966. name_val = JS_AtomToValue(ctx, name);
  51967. if (JS_IsException(name_val))
  51968. goto fail;
  51969. args[0] = name_val;
  51970. args[1] = val;
  51971. res = JS_Call(ctx, reviver, holder, 2, args);
  51972. JS_FreeValue(ctx, name_val);
  51973. JS_FreeValue(ctx, val);
  51974. return res;
  51975. fail:
  51976. js_free_prop_enum(ctx, atoms, len);
  51977. JS_FreeValue(ctx, val);
  51978. return JS_EXCEPTION;
  51979. }
  51980. static JSValue js_json_parse(JSContext *ctx, JSValueConst this_val,
  51981. int argc, JSValueConst *argv)
  51982. {
  51983. JSValue obj, root;
  51984. JSValueConst reviver;
  51985. const char *str;
  51986. size_t len;
  51987. str = JS_ToCStringLen(ctx, &len, argv[0]);
  51988. if (!str)
  51989. return JS_EXCEPTION;
  51990. obj = JS_ParseJSON(ctx, str, len, "<input>");
  51991. JS_FreeCString(ctx, str);
  51992. if (JS_IsException(obj))
  51993. return obj;
  51994. if (argc > 1 && JS_IsFunction(ctx, argv[1])) {
  51995. reviver = argv[1];
  51996. root = JS_NewObject(ctx);
  51997. if (JS_IsException(root)) {
  51998. JS_FreeValue(ctx, obj);
  51999. return JS_EXCEPTION;
  52000. }
  52001. if (JS_DefinePropertyValue(ctx, root, JS_ATOM_empty_string, obj,
  52002. JS_PROP_C_W_E) < 0) {
  52003. JS_FreeValue(ctx, root);
  52004. return JS_EXCEPTION;
  52005. }
  52006. obj = internalize_json_property(ctx, root, JS_ATOM_empty_string,
  52007. reviver);
  52008. JS_FreeValue(ctx, root);
  52009. }
  52010. return obj;
  52011. }
  52012. typedef struct JSONStringifyContext {
  52013. JSValueConst replacer_func;
  52014. JSValue stack;
  52015. JSValue property_list;
  52016. JSValue gap;
  52017. JSValue empty;
  52018. StringBuffer *b;
  52019. } JSONStringifyContext;
  52020. static JSValue JS_ToQuotedStringFree(JSContext *ctx, JSValue val) {
  52021. JSValue r = JS_ToQuotedString(ctx, val);
  52022. JS_FreeValue(ctx, val);
  52023. return r;
  52024. }
  52025. static JSValue js_json_check(JSContext *ctx, JSONStringifyContext *jsc,
  52026. JSValueConst holder, JSValue val,
  52027. JSValueConst key)
  52028. {
  52029. JSValue v;
  52030. JSValueConst args[2];
  52031. if (JS_IsObject(val) || JS_IsBigInt(ctx, val)) {
  52032. JSValue f = JS_GetProperty(ctx, val, JS_ATOM_toJSON);
  52033. if (JS_IsException(f))
  52034. goto exception;
  52035. if (JS_IsFunction(ctx, f)) {
  52036. v = JS_CallFree(ctx, f, val, 1, &key);
  52037. JS_FreeValue(ctx, val);
  52038. val = v;
  52039. if (JS_IsException(val))
  52040. goto exception;
  52041. } else {
  52042. JS_FreeValue(ctx, f);
  52043. }
  52044. }
  52045. if (!JS_IsUndefined(jsc->replacer_func)) {
  52046. args[0] = key;
  52047. args[1] = val;
  52048. v = JS_Call(ctx, jsc->replacer_func, holder, 2, args);
  52049. JS_FreeValue(ctx, val);
  52050. val = v;
  52051. if (JS_IsException(val))
  52052. goto exception;
  52053. }
  52054. switch (JS_VALUE_GET_NORM_TAG(val)) {
  52055. case JS_TAG_OBJECT:
  52056. if (JS_IsFunction(ctx, val))
  52057. break;
  52058. case JS_TAG_STRING:
  52059. case JS_TAG_INT:
  52060. case JS_TAG_FLOAT64:
  52061. case JS_TAG_BOOL:
  52062. case JS_TAG_NULL:
  52063. case JS_TAG_BIG_INT:
  52064. case JS_TAG_EXCEPTION:
  52065. return val;
  52066. default:
  52067. break;
  52068. }
  52069. JS_FreeValue(ctx, val);
  52070. return JS_UNDEFINED;
  52071. exception:
  52072. JS_FreeValue(ctx, val);
  52073. return JS_EXCEPTION;
  52074. }
  52075. static int js_json_to_str(JSContext *ctx, JSONStringifyContext *jsc,
  52076. JSValueConst holder, JSValue val,
  52077. JSValueConst indent)
  52078. {
  52079. JSValue indent1, sep, sep1, tab, v, prop;
  52080. JSObject *p;
  52081. int64_t i, len;
  52082. int cl, ret;
  52083. bool has_content;
  52084. indent1 = JS_UNDEFINED;
  52085. sep = JS_UNDEFINED;
  52086. sep1 = JS_UNDEFINED;
  52087. tab = JS_UNDEFINED;
  52088. prop = JS_UNDEFINED;
  52089. if (JS_IsObject(val)) {
  52090. p = JS_VALUE_GET_OBJ(val);
  52091. cl = p->class_id;
  52092. if (cl == JS_CLASS_STRING) {
  52093. val = JS_ToStringFree(ctx, val);
  52094. if (JS_IsException(val))
  52095. goto exception;
  52096. goto concat_primitive;
  52097. } else if (cl == JS_CLASS_NUMBER) {
  52098. val = JS_ToNumberFree(ctx, val);
  52099. if (JS_IsException(val))
  52100. goto exception;
  52101. goto concat_primitive;
  52102. } else if (cl == JS_CLASS_BOOLEAN || cl == JS_CLASS_BIG_INT) {
  52103. set_value(ctx, &val, js_dup(p->u.object_data));
  52104. goto concat_primitive;
  52105. }
  52106. v = js_array_includes(ctx, jsc->stack, 1, vc(&val));
  52107. if (JS_IsException(v))
  52108. goto exception;
  52109. if (JS_ToBoolFree(ctx, v)) {
  52110. JS_ThrowTypeError(ctx, "circular reference");
  52111. goto exception;
  52112. }
  52113. indent1 = JS_ConcatString(ctx, js_dup(indent), js_dup(jsc->gap));
  52114. if (JS_IsException(indent1))
  52115. goto exception;
  52116. if (!JS_IsEmptyString(jsc->gap)) {
  52117. sep = JS_ConcatString3(ctx, "\n", js_dup(indent1), "");
  52118. if (JS_IsException(sep))
  52119. goto exception;
  52120. sep1 = js_new_string8(ctx, " ");
  52121. if (JS_IsException(sep1))
  52122. goto exception;
  52123. } else {
  52124. sep = js_dup(jsc->empty);
  52125. sep1 = js_dup(jsc->empty);
  52126. }
  52127. v = js_array_push(ctx, jsc->stack, 1, vc(&val), 0);
  52128. if (check_exception_free(ctx, v))
  52129. goto exception;
  52130. ret = js_is_array(ctx, val);
  52131. if (ret < 0)
  52132. goto exception;
  52133. if (ret) {
  52134. if (js_get_length64(ctx, &len, val))
  52135. goto exception;
  52136. string_buffer_putc8(jsc->b, '[');
  52137. for(i = 0; i < len; i++) {
  52138. if (i > 0)
  52139. string_buffer_putc8(jsc->b, ',');
  52140. string_buffer_concat_value(jsc->b, sep);
  52141. v = JS_GetPropertyInt64(ctx, val, i);
  52142. if (JS_IsException(v))
  52143. goto exception;
  52144. /* XXX: could do this string conversion only when needed */
  52145. prop = JS_ToStringFree(ctx, js_int64(i));
  52146. if (JS_IsException(prop))
  52147. goto exception;
  52148. v = js_json_check(ctx, jsc, val, v, prop);
  52149. JS_FreeValue(ctx, prop);
  52150. prop = JS_UNDEFINED;
  52151. if (JS_IsException(v))
  52152. goto exception;
  52153. if (JS_IsUndefined(v))
  52154. v = JS_NULL;
  52155. if (js_json_to_str(ctx, jsc, val, v, indent1))
  52156. goto exception;
  52157. }
  52158. if (len > 0 && !JS_IsEmptyString(jsc->gap)) {
  52159. string_buffer_putc8(jsc->b, '\n');
  52160. string_buffer_concat_value(jsc->b, indent);
  52161. }
  52162. string_buffer_putc8(jsc->b, ']');
  52163. } else {
  52164. if (!JS_IsUndefined(jsc->property_list))
  52165. tab = js_dup(jsc->property_list);
  52166. else
  52167. tab = js_object_keys(ctx, JS_UNDEFINED, 1, vc(&val),
  52168. JS_ITERATOR_KIND_KEY);
  52169. if (JS_IsException(tab))
  52170. goto exception;
  52171. if (js_get_length64(ctx, &len, tab))
  52172. goto exception;
  52173. string_buffer_putc8(jsc->b, '{');
  52174. has_content = false;
  52175. for(i = 0; i < len; i++) {
  52176. JS_FreeValue(ctx, prop);
  52177. prop = JS_GetPropertyInt64(ctx, tab, i);
  52178. if (JS_IsException(prop))
  52179. goto exception;
  52180. v = JS_GetPropertyValue(ctx, val, js_dup(prop));
  52181. if (JS_IsException(v))
  52182. goto exception;
  52183. v = js_json_check(ctx, jsc, val, v, prop);
  52184. if (JS_IsException(v))
  52185. goto exception;
  52186. if (!JS_IsUndefined(v)) {
  52187. if (has_content)
  52188. string_buffer_putc8(jsc->b, ',');
  52189. prop = JS_ToQuotedStringFree(ctx, prop);
  52190. if (JS_IsException(prop)) {
  52191. JS_FreeValue(ctx, v);
  52192. goto exception;
  52193. }
  52194. string_buffer_concat_value(jsc->b, sep);
  52195. string_buffer_concat_value(jsc->b, prop);
  52196. string_buffer_putc8(jsc->b, ':');
  52197. string_buffer_concat_value(jsc->b, sep1);
  52198. if (js_json_to_str(ctx, jsc, val, v, indent1))
  52199. goto exception;
  52200. has_content = true;
  52201. }
  52202. }
  52203. if (has_content && JS_VALUE_GET_STRING(jsc->gap)->len != 0) {
  52204. string_buffer_putc8(jsc->b, '\n');
  52205. string_buffer_concat_value(jsc->b, indent);
  52206. }
  52207. string_buffer_putc8(jsc->b, '}');
  52208. }
  52209. if (check_exception_free(ctx, js_array_pop(ctx, jsc->stack, 0, NULL, 0)))
  52210. goto exception;
  52211. JS_FreeValue(ctx, val);
  52212. JS_FreeValue(ctx, tab);
  52213. JS_FreeValue(ctx, sep);
  52214. JS_FreeValue(ctx, sep1);
  52215. JS_FreeValue(ctx, indent1);
  52216. JS_FreeValue(ctx, prop);
  52217. return 0;
  52218. }
  52219. concat_primitive:
  52220. switch (JS_VALUE_GET_NORM_TAG(val)) {
  52221. case JS_TAG_STRING:
  52222. val = JS_ToQuotedStringFree(ctx, val);
  52223. if (JS_IsException(val))
  52224. goto exception;
  52225. goto concat_value;
  52226. case JS_TAG_FLOAT64:
  52227. if (!isfinite(JS_VALUE_GET_FLOAT64(val))) {
  52228. val = JS_NULL;
  52229. }
  52230. goto concat_value;
  52231. case JS_TAG_INT:
  52232. case JS_TAG_BOOL:
  52233. case JS_TAG_NULL:
  52234. concat_value:
  52235. return string_buffer_concat_value_free(jsc->b, val);
  52236. case JS_TAG_BIG_INT:
  52237. JS_ThrowTypeError(ctx, "BigInt are forbidden in JSON.stringify");
  52238. goto exception;
  52239. default:
  52240. JS_FreeValue(ctx, val);
  52241. return 0;
  52242. }
  52243. exception:
  52244. JS_FreeValue(ctx, val);
  52245. JS_FreeValue(ctx, tab);
  52246. JS_FreeValue(ctx, sep);
  52247. JS_FreeValue(ctx, sep1);
  52248. JS_FreeValue(ctx, indent1);
  52249. JS_FreeValue(ctx, prop);
  52250. return -1;
  52251. }
  52252. JSValue JS_JSONStringify(JSContext *ctx, JSValueConst obj,
  52253. JSValueConst replacer, JSValueConst space0)
  52254. {
  52255. StringBuffer b_s;
  52256. JSONStringifyContext jsc_s, *jsc = &jsc_s;
  52257. JSValue val, v, space, ret, wrapper;
  52258. int res;
  52259. int64_t i, j, n;
  52260. jsc->replacer_func = JS_UNDEFINED;
  52261. jsc->stack = JS_UNDEFINED;
  52262. jsc->property_list = JS_UNDEFINED;
  52263. jsc->gap = JS_UNDEFINED;
  52264. jsc->b = &b_s;
  52265. jsc->empty = JS_AtomToString(ctx, JS_ATOM_empty_string);
  52266. ret = JS_UNDEFINED;
  52267. wrapper = JS_UNDEFINED;
  52268. string_buffer_init(ctx, jsc->b, 0);
  52269. jsc->stack = JS_NewArray(ctx);
  52270. if (JS_IsException(jsc->stack))
  52271. goto exception;
  52272. if (JS_IsFunction(ctx, replacer)) {
  52273. jsc->replacer_func = replacer;
  52274. } else {
  52275. res = js_is_array(ctx, replacer);
  52276. if (res < 0)
  52277. goto exception;
  52278. if (res) {
  52279. /* XXX: enumeration is not fully correct */
  52280. jsc->property_list = JS_NewArray(ctx);
  52281. if (JS_IsException(jsc->property_list))
  52282. goto exception;
  52283. if (js_get_length64(ctx, &n, replacer))
  52284. goto exception;
  52285. for (i = j = 0; i < n; i++) {
  52286. JSValue present;
  52287. v = JS_GetPropertyInt64(ctx, replacer, i);
  52288. if (JS_IsException(v))
  52289. goto exception;
  52290. if (JS_IsObject(v)) {
  52291. JSObject *p = JS_VALUE_GET_OBJ(v);
  52292. if (p->class_id == JS_CLASS_STRING ||
  52293. p->class_id == JS_CLASS_NUMBER) {
  52294. v = JS_ToStringFree(ctx, v);
  52295. if (JS_IsException(v))
  52296. goto exception;
  52297. } else {
  52298. JS_FreeValue(ctx, v);
  52299. continue;
  52300. }
  52301. } else if (JS_IsNumber(v)) {
  52302. v = JS_ToStringFree(ctx, v);
  52303. if (JS_IsException(v))
  52304. goto exception;
  52305. } else if (!JS_IsString(v)) {
  52306. JS_FreeValue(ctx, v);
  52307. continue;
  52308. }
  52309. present = js_array_includes(ctx, jsc->property_list,
  52310. 1, vc(&v));
  52311. if (JS_IsException(present)) {
  52312. JS_FreeValue(ctx, v);
  52313. goto exception;
  52314. }
  52315. if (!JS_ToBoolFree(ctx, present)) {
  52316. JS_SetPropertyInt64(ctx, jsc->property_list, j++, v);
  52317. } else {
  52318. JS_FreeValue(ctx, v);
  52319. }
  52320. }
  52321. }
  52322. }
  52323. space = js_dup(space0);
  52324. if (JS_IsObject(space)) {
  52325. JSObject *p = JS_VALUE_GET_OBJ(space);
  52326. if (p->class_id == JS_CLASS_NUMBER) {
  52327. space = JS_ToNumberFree(ctx, space);
  52328. } else if (p->class_id == JS_CLASS_STRING) {
  52329. space = JS_ToStringFree(ctx, space);
  52330. }
  52331. if (JS_IsException(space)) {
  52332. JS_FreeValue(ctx, space);
  52333. goto exception;
  52334. }
  52335. }
  52336. if (JS_IsNumber(space)) {
  52337. int n;
  52338. if (JS_ToInt32Clamp(ctx, &n, space, 0, 10, 0))
  52339. goto exception;
  52340. jsc->gap = JS_NewStringLen(ctx, " ", n);
  52341. } else if (JS_IsString(space)) {
  52342. JSString *p = JS_VALUE_GET_STRING(space);
  52343. jsc->gap = js_sub_string(ctx, p, 0, min_int(p->len, 10));
  52344. } else {
  52345. jsc->gap = js_dup(jsc->empty);
  52346. }
  52347. JS_FreeValue(ctx, space);
  52348. if (JS_IsException(jsc->gap))
  52349. goto exception;
  52350. wrapper = JS_NewObject(ctx);
  52351. if (JS_IsException(wrapper))
  52352. goto exception;
  52353. if (JS_DefinePropertyValue(ctx, wrapper, JS_ATOM_empty_string,
  52354. js_dup(obj), JS_PROP_C_W_E) < 0)
  52355. goto exception;
  52356. val = js_dup(obj);
  52357. val = js_json_check(ctx, jsc, wrapper, val, jsc->empty);
  52358. if (JS_IsException(val))
  52359. goto exception;
  52360. if (JS_IsUndefined(val)) {
  52361. ret = JS_UNDEFINED;
  52362. goto done1;
  52363. }
  52364. if (js_json_to_str(ctx, jsc, wrapper, val, jsc->empty))
  52365. goto exception;
  52366. ret = string_buffer_end(jsc->b);
  52367. goto done;
  52368. exception:
  52369. ret = JS_EXCEPTION;
  52370. done1:
  52371. string_buffer_free(jsc->b);
  52372. done:
  52373. JS_FreeValue(ctx, wrapper);
  52374. JS_FreeValue(ctx, jsc->empty);
  52375. JS_FreeValue(ctx, jsc->gap);
  52376. JS_FreeValue(ctx, jsc->property_list);
  52377. JS_FreeValue(ctx, jsc->stack);
  52378. return ret;
  52379. }
  52380. static JSValue js_json_stringify(JSContext *ctx, JSValueConst this_val,
  52381. int argc, JSValueConst *argv)
  52382. {
  52383. // stringify(val, replacer, space)
  52384. return JS_JSONStringify(ctx, argv[0], argv[1], argv[2]);
  52385. }
  52386. static const JSCFunctionListEntry js_json_funcs[] = {
  52387. JS_CFUNC_DEF("parse", 2, js_json_parse ),
  52388. JS_CFUNC_DEF("stringify", 3, js_json_stringify ),
  52389. JS_PROP_STRING_DEF("[Symbol.toStringTag]", "JSON", JS_PROP_CONFIGURABLE ),
  52390. };
  52391. static const JSCFunctionListEntry js_json_obj[] = {
  52392. JS_OBJECT_DEF("JSON", js_json_funcs, countof(js_json_funcs), JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE ),
  52393. };
  52394. void JS_AddIntrinsicJSON(JSContext *ctx)
  52395. {
  52396. /* add JSON as autoinit object */
  52397. JS_SetPropertyFunctionList(ctx, ctx->global_obj, js_json_obj, countof(js_json_obj));
  52398. }
  52399. /* Reflect */
  52400. static JSValue js_reflect_apply(JSContext *ctx, JSValueConst this_val,
  52401. int argc, JSValueConst *argv)
  52402. {
  52403. return js_function_apply(ctx, argv[0], max_int(0, argc - 1), argv + 1, 2);
  52404. }
  52405. static JSValue js_reflect_construct(JSContext *ctx, JSValueConst this_val,
  52406. int argc, JSValueConst *argv)
  52407. {
  52408. JSValueConst func, array_arg, new_target;
  52409. JSValue *tab, ret;
  52410. uint32_t len;
  52411. func = argv[0];
  52412. array_arg = argv[1];
  52413. if (argc > 2) {
  52414. new_target = argv[2];
  52415. if (!JS_IsConstructor(ctx, new_target))
  52416. return JS_ThrowTypeError(ctx, "not a constructor");
  52417. } else {
  52418. new_target = func;
  52419. }
  52420. tab = build_arg_list(ctx, &len, array_arg);
  52421. if (!tab)
  52422. return JS_EXCEPTION;
  52423. ret = JS_CallConstructor2(ctx, func, new_target, len, vc(tab));
  52424. free_arg_list(ctx, tab, len);
  52425. return ret;
  52426. }
  52427. static JSValue js_reflect_deleteProperty(JSContext *ctx, JSValueConst this_val,
  52428. int argc, JSValueConst *argv)
  52429. {
  52430. JSValueConst obj;
  52431. JSAtom atom;
  52432. int ret;
  52433. obj = argv[0];
  52434. if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)
  52435. return JS_ThrowTypeErrorNotAnObject(ctx);
  52436. atom = JS_ValueToAtom(ctx, argv[1]);
  52437. if (unlikely(atom == JS_ATOM_NULL))
  52438. return JS_EXCEPTION;
  52439. ret = JS_DeleteProperty(ctx, obj, atom, 0);
  52440. JS_FreeAtom(ctx, atom);
  52441. if (ret < 0)
  52442. return JS_EXCEPTION;
  52443. else
  52444. return js_bool(ret);
  52445. }
  52446. static JSValue js_reflect_get(JSContext *ctx, JSValueConst this_val,
  52447. int argc, JSValueConst *argv)
  52448. {
  52449. JSValueConst obj, prop, receiver;
  52450. JSAtom atom;
  52451. JSValue ret;
  52452. obj = argv[0];
  52453. prop = argv[1];
  52454. if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)
  52455. return JS_ThrowTypeErrorNotAnObject(ctx);
  52456. if (argc > 2)
  52457. receiver = argv[2];
  52458. else
  52459. receiver = obj;
  52460. atom = JS_ValueToAtom(ctx, prop);
  52461. if (unlikely(atom == JS_ATOM_NULL))
  52462. return JS_EXCEPTION;
  52463. ret = JS_GetPropertyInternal(ctx, obj, atom, receiver, false);
  52464. JS_FreeAtom(ctx, atom);
  52465. return ret;
  52466. }
  52467. static JSValue js_reflect_has(JSContext *ctx, JSValueConst this_val,
  52468. int argc, JSValueConst *argv)
  52469. {
  52470. JSValueConst obj, prop;
  52471. JSAtom atom;
  52472. int ret;
  52473. obj = argv[0];
  52474. prop = argv[1];
  52475. if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)
  52476. return JS_ThrowTypeErrorNotAnObject(ctx);
  52477. atom = JS_ValueToAtom(ctx, prop);
  52478. if (unlikely(atom == JS_ATOM_NULL))
  52479. return JS_EXCEPTION;
  52480. ret = JS_HasProperty(ctx, obj, atom);
  52481. JS_FreeAtom(ctx, atom);
  52482. if (ret < 0)
  52483. return JS_EXCEPTION;
  52484. else
  52485. return js_bool(ret);
  52486. }
  52487. static JSValue js_reflect_set(JSContext *ctx, JSValueConst this_val,
  52488. int argc, JSValueConst *argv)
  52489. {
  52490. JSValueConst obj, prop, val, receiver;
  52491. int ret;
  52492. JSAtom atom;
  52493. obj = argv[0];
  52494. prop = argv[1];
  52495. val = argv[2];
  52496. if (argc > 3)
  52497. receiver = argv[3];
  52498. else
  52499. receiver = obj;
  52500. if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)
  52501. return JS_ThrowTypeErrorNotAnObject(ctx);
  52502. atom = JS_ValueToAtom(ctx, prop);
  52503. if (unlikely(atom == JS_ATOM_NULL))
  52504. return JS_EXCEPTION;
  52505. ret = JS_SetPropertyInternal2(ctx, obj, atom, js_dup(val), receiver, 0);
  52506. JS_FreeAtom(ctx, atom);
  52507. if (ret < 0)
  52508. return JS_EXCEPTION;
  52509. else
  52510. return js_bool(ret);
  52511. }
  52512. static JSValue js_reflect_setPrototypeOf(JSContext *ctx, JSValueConst this_val,
  52513. int argc, JSValueConst *argv)
  52514. {
  52515. int ret;
  52516. ret = JS_SetPrototypeInternal(ctx, argv[0], argv[1], false);
  52517. if (ret < 0)
  52518. return JS_EXCEPTION;
  52519. else
  52520. return js_bool(ret);
  52521. }
  52522. static JSValue js_reflect_ownKeys(JSContext *ctx, JSValueConst this_val,
  52523. int argc, JSValueConst *argv)
  52524. {
  52525. if (JS_VALUE_GET_TAG(argv[0]) != JS_TAG_OBJECT)
  52526. return JS_ThrowTypeErrorNotAnObject(ctx);
  52527. return JS_GetOwnPropertyNames2(ctx, argv[0],
  52528. JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK,
  52529. JS_ITERATOR_KIND_KEY);
  52530. }
  52531. static const JSCFunctionListEntry js_reflect_funcs[] = {
  52532. JS_CFUNC_DEF("apply", 3, js_reflect_apply ),
  52533. JS_CFUNC_DEF("construct", 2, js_reflect_construct ),
  52534. JS_CFUNC_MAGIC_DEF("defineProperty", 3, js_object_defineProperty, 1 ),
  52535. JS_CFUNC_DEF("deleteProperty", 2, js_reflect_deleteProperty ),
  52536. JS_CFUNC_DEF("get", 2, js_reflect_get ),
  52537. JS_CFUNC_MAGIC_DEF("getOwnPropertyDescriptor", 2, js_object_getOwnPropertyDescriptor, 1 ),
  52538. JS_CFUNC_MAGIC_DEF("getPrototypeOf", 1, js_object_getPrototypeOf, 1 ),
  52539. JS_CFUNC_DEF("has", 2, js_reflect_has ),
  52540. JS_CFUNC_MAGIC_DEF("isExtensible", 1, js_object_isExtensible, 1 ),
  52541. JS_CFUNC_DEF("ownKeys", 1, js_reflect_ownKeys ),
  52542. JS_CFUNC_MAGIC_DEF("preventExtensions", 1, js_object_preventExtensions, 1 ),
  52543. JS_CFUNC_DEF("set", 3, js_reflect_set ),
  52544. JS_CFUNC_DEF("setPrototypeOf", 2, js_reflect_setPrototypeOf ),
  52545. JS_PROP_STRING_DEF("[Symbol.toStringTag]", "Reflect", JS_PROP_CONFIGURABLE ),
  52546. };
  52547. static const JSCFunctionListEntry js_reflect_obj[] = {
  52548. JS_OBJECT_DEF("Reflect", js_reflect_funcs, countof(js_reflect_funcs), JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE ),
  52549. };
  52550. /* Proxy */
  52551. static void js_proxy_finalizer(JSRuntime *rt, JSValueConst val)
  52552. {
  52553. JSProxyData *s = JS_GetOpaque(val, JS_CLASS_PROXY);
  52554. if (s) {
  52555. JS_FreeValueRT(rt, s->target);
  52556. JS_FreeValueRT(rt, s->handler);
  52557. js_free_rt(rt, s);
  52558. }
  52559. }
  52560. static void js_proxy_mark(JSRuntime *rt, JSValueConst val,
  52561. JS_MarkFunc *mark_func)
  52562. {
  52563. JSProxyData *s = JS_GetOpaque(val, JS_CLASS_PROXY);
  52564. if (s) {
  52565. JS_MarkValue(rt, s->target, mark_func);
  52566. JS_MarkValue(rt, s->handler, mark_func);
  52567. }
  52568. }
  52569. static JSValue JS_ThrowTypeErrorRevokedProxy(JSContext *ctx)
  52570. {
  52571. return JS_ThrowTypeError(ctx, "revoked proxy");
  52572. }
  52573. static JSProxyData *get_proxy_method(JSContext *ctx, JSValue *pmethod,
  52574. JSValueConst obj, JSAtom name)
  52575. {
  52576. JSProxyData *s = JS_GetOpaque(obj, JS_CLASS_PROXY);
  52577. JSValue method;
  52578. /* safer to test recursion in all proxy methods */
  52579. if (js_check_stack_overflow(ctx->rt, 0)) {
  52580. JS_ThrowStackOverflow(ctx);
  52581. return NULL;
  52582. }
  52583. /* 's' should never be NULL */
  52584. if (s->is_revoked) {
  52585. JS_ThrowTypeErrorRevokedProxy(ctx);
  52586. return NULL;
  52587. }
  52588. method = JS_GetProperty(ctx, s->handler, name);
  52589. if (JS_IsException(method))
  52590. return NULL;
  52591. if (JS_IsNull(method))
  52592. method = JS_UNDEFINED;
  52593. *pmethod = method;
  52594. return s;
  52595. }
  52596. static JSValue js_proxy_getPrototypeOf(JSContext *ctx, JSValueConst obj)
  52597. {
  52598. JSProxyData *s;
  52599. JSValue method, ret, proto1;
  52600. int res;
  52601. s = get_proxy_method(ctx, &method, obj, JS_ATOM_getPrototypeOf);
  52602. if (!s)
  52603. return JS_EXCEPTION;
  52604. if (JS_IsUndefined(method))
  52605. return JS_GetPrototype(ctx, s->target);
  52606. ret = JS_CallFree(ctx, method, s->handler, 1, vc(&s->target));
  52607. if (JS_IsException(ret))
  52608. return ret;
  52609. if (JS_VALUE_GET_TAG(ret) != JS_TAG_NULL &&
  52610. JS_VALUE_GET_TAG(ret) != JS_TAG_OBJECT) {
  52611. goto fail;
  52612. }
  52613. res = JS_IsExtensible(ctx, s->target);
  52614. if (res < 0) {
  52615. JS_FreeValue(ctx, ret);
  52616. return JS_EXCEPTION;
  52617. }
  52618. if (!res) {
  52619. /* check invariant */
  52620. proto1 = JS_GetPrototype(ctx, s->target);
  52621. if (JS_IsException(proto1)) {
  52622. JS_FreeValue(ctx, ret);
  52623. return JS_EXCEPTION;
  52624. }
  52625. if (JS_VALUE_GET_OBJ(proto1) != JS_VALUE_GET_OBJ(ret)) {
  52626. JS_FreeValue(ctx, proto1);
  52627. fail:
  52628. JS_FreeValue(ctx, ret);
  52629. return JS_ThrowTypeError(ctx, "proxy: inconsistent prototype");
  52630. }
  52631. JS_FreeValue(ctx, proto1);
  52632. }
  52633. return ret;
  52634. }
  52635. static int js_proxy_setPrototypeOf(JSContext *ctx, JSValueConst obj,
  52636. JSValueConst proto_val, bool throw_flag)
  52637. {
  52638. JSProxyData *s;
  52639. JSValue method, ret, proto1;
  52640. JSValueConst args[2];
  52641. bool res;
  52642. int res2;
  52643. s = get_proxy_method(ctx, &method, obj, JS_ATOM_setPrototypeOf);
  52644. if (!s)
  52645. return -1;
  52646. if (JS_IsUndefined(method))
  52647. return JS_SetPrototypeInternal(ctx, s->target, proto_val, throw_flag);
  52648. args[0] = s->target;
  52649. args[1] = proto_val;
  52650. ret = JS_CallFree(ctx, method, s->handler, 2, args);
  52651. if (JS_IsException(ret))
  52652. return -1;
  52653. res = JS_ToBoolFree(ctx, ret);
  52654. if (!res) {
  52655. if (throw_flag) {
  52656. JS_ThrowTypeError(ctx, "proxy: bad prototype");
  52657. return -1;
  52658. } else {
  52659. return false;
  52660. }
  52661. }
  52662. res2 = JS_IsExtensible(ctx, s->target);
  52663. if (res2 < 0)
  52664. return -1;
  52665. if (!res2) {
  52666. proto1 = JS_GetPrototype(ctx, s->target);
  52667. if (JS_IsException(proto1))
  52668. return -1;
  52669. if (JS_VALUE_GET_OBJ(proto_val) != JS_VALUE_GET_OBJ(proto1)) {
  52670. JS_FreeValue(ctx, proto1);
  52671. JS_ThrowTypeError(ctx, "proxy: inconsistent prototype");
  52672. return -1;
  52673. }
  52674. JS_FreeValue(ctx, proto1);
  52675. }
  52676. return true;
  52677. }
  52678. static int js_proxy_isExtensible(JSContext *ctx, JSValueConst obj)
  52679. {
  52680. JSProxyData *s;
  52681. JSValue method, ret;
  52682. bool res;
  52683. int res2;
  52684. s = get_proxy_method(ctx, &method, obj, JS_ATOM_isExtensible);
  52685. if (!s)
  52686. return -1;
  52687. if (JS_IsUndefined(method))
  52688. return JS_IsExtensible(ctx, s->target);
  52689. ret = JS_CallFree(ctx, method, s->handler, 1, vc(&s->target));
  52690. if (JS_IsException(ret))
  52691. return -1;
  52692. res = JS_ToBoolFree(ctx, ret);
  52693. res2 = JS_IsExtensible(ctx, s->target);
  52694. if (res2 < 0)
  52695. return res2;
  52696. if (res != res2) {
  52697. JS_ThrowTypeError(ctx, "proxy: inconsistent isExtensible");
  52698. return -1;
  52699. }
  52700. return res;
  52701. }
  52702. static int js_proxy_preventExtensions(JSContext *ctx, JSValueConst obj)
  52703. {
  52704. JSProxyData *s;
  52705. JSValue method, ret;
  52706. bool res;
  52707. int res2;
  52708. s = get_proxy_method(ctx, &method, obj, JS_ATOM_preventExtensions);
  52709. if (!s)
  52710. return -1;
  52711. if (JS_IsUndefined(method))
  52712. return JS_PreventExtensions(ctx, s->target);
  52713. ret = JS_CallFree(ctx, method, s->handler, 1, vc(&s->target));
  52714. if (JS_IsException(ret))
  52715. return -1;
  52716. res = JS_ToBoolFree(ctx, ret);
  52717. if (res) {
  52718. res2 = JS_IsExtensible(ctx, s->target);
  52719. if (res2 < 0)
  52720. return res2;
  52721. if (res2) {
  52722. JS_ThrowTypeError(ctx, "proxy: inconsistent preventExtensions");
  52723. return -1;
  52724. }
  52725. }
  52726. return res;
  52727. }
  52728. static int js_proxy_has(JSContext *ctx, JSValueConst obj, JSAtom atom)
  52729. {
  52730. JSProxyData *s;
  52731. JSValue method, ret1, atom_val;
  52732. int res;
  52733. JSObject *p;
  52734. JSValueConst args[2];
  52735. bool ret, res2;
  52736. s = get_proxy_method(ctx, &method, obj, JS_ATOM_has);
  52737. if (!s)
  52738. return -1;
  52739. if (JS_IsUndefined(method))
  52740. return JS_HasProperty(ctx, s->target, atom);
  52741. atom_val = JS_AtomToValue(ctx, atom);
  52742. if (JS_IsException(atom_val)) {
  52743. JS_FreeValue(ctx, method);
  52744. return -1;
  52745. }
  52746. args[0] = s->target;
  52747. args[1] = atom_val;
  52748. ret1 = JS_CallFree(ctx, method, s->handler, 2, args);
  52749. JS_FreeValue(ctx, atom_val);
  52750. if (JS_IsException(ret1))
  52751. return -1;
  52752. ret = JS_ToBoolFree(ctx, ret1);
  52753. if (!ret) {
  52754. JSPropertyDescriptor desc;
  52755. p = JS_VALUE_GET_OBJ(s->target);
  52756. res = JS_GetOwnPropertyInternal(ctx, &desc, p, atom);
  52757. if (res < 0)
  52758. return -1;
  52759. if (res) {
  52760. res2 = !(desc.flags & JS_PROP_CONFIGURABLE);
  52761. js_free_desc(ctx, &desc);
  52762. if (res2 || !p->extensible) {
  52763. JS_ThrowTypeError(ctx, "proxy: inconsistent has");
  52764. return -1;
  52765. }
  52766. }
  52767. }
  52768. return ret;
  52769. }
  52770. static JSValue js_proxy_get(JSContext *ctx, JSValueConst obj, JSAtom atom,
  52771. JSValueConst receiver)
  52772. {
  52773. JSProxyData *s;
  52774. JSValue method, ret, atom_val;
  52775. int res;
  52776. JSValueConst args[3];
  52777. JSPropertyDescriptor desc;
  52778. s = get_proxy_method(ctx, &method, obj, JS_ATOM_get);
  52779. if (!s)
  52780. return JS_EXCEPTION;
  52781. /* Note: recursion is possible thru the prototype of s->target */
  52782. if (JS_IsUndefined(method))
  52783. return JS_GetPropertyInternal(ctx, s->target, atom, receiver, false);
  52784. atom_val = JS_AtomToValue(ctx, atom);
  52785. if (JS_IsException(atom_val)) {
  52786. JS_FreeValue(ctx, method);
  52787. return JS_EXCEPTION;
  52788. }
  52789. args[0] = s->target;
  52790. args[1] = atom_val;
  52791. args[2] = receiver;
  52792. ret = JS_CallFree(ctx, method, s->handler, 3, args);
  52793. JS_FreeValue(ctx, atom_val);
  52794. if (JS_IsException(ret))
  52795. return JS_EXCEPTION;
  52796. res = JS_GetOwnPropertyInternal(ctx, &desc, JS_VALUE_GET_OBJ(s->target), atom);
  52797. if (res < 0) {
  52798. JS_FreeValue(ctx, ret);
  52799. return JS_EXCEPTION;
  52800. }
  52801. if (res) {
  52802. if ((desc.flags & (JS_PROP_GETSET | JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE)) == 0) {
  52803. if (!js_same_value(ctx, desc.value, ret)) {
  52804. goto fail;
  52805. }
  52806. } else if ((desc.flags & (JS_PROP_GETSET | JS_PROP_CONFIGURABLE)) == JS_PROP_GETSET) {
  52807. if (JS_IsUndefined(desc.getter) && !JS_IsUndefined(ret)) {
  52808. fail:
  52809. js_free_desc(ctx, &desc);
  52810. JS_FreeValue(ctx, ret);
  52811. return JS_ThrowTypeError(ctx, "proxy: inconsistent get");
  52812. }
  52813. }
  52814. js_free_desc(ctx, &desc);
  52815. }
  52816. return ret;
  52817. }
  52818. static int js_proxy_set(JSContext *ctx, JSValueConst obj, JSAtom atom,
  52819. JSValueConst value, JSValueConst receiver, int flags)
  52820. {
  52821. JSProxyData *s;
  52822. JSValue method, ret1, atom_val;
  52823. bool ret;
  52824. int res;
  52825. JSValueConst args[4];
  52826. s = get_proxy_method(ctx, &method, obj, JS_ATOM_set);
  52827. if (!s)
  52828. return -1;
  52829. if (JS_IsUndefined(method)) {
  52830. return JS_SetPropertyInternal2(ctx, s->target, atom,
  52831. js_dup(value), receiver, flags);
  52832. }
  52833. atom_val = JS_AtomToValue(ctx, atom);
  52834. if (JS_IsException(atom_val)) {
  52835. JS_FreeValue(ctx, method);
  52836. return -1;
  52837. }
  52838. args[0] = s->target;
  52839. args[1] = atom_val;
  52840. args[2] = value;
  52841. args[3] = receiver;
  52842. ret1 = JS_CallFree(ctx, method, s->handler, 4, args);
  52843. JS_FreeValue(ctx, atom_val);
  52844. if (JS_IsException(ret1))
  52845. return -1;
  52846. ret = JS_ToBoolFree(ctx, ret1);
  52847. if (ret) {
  52848. JSPropertyDescriptor desc;
  52849. res = JS_GetOwnPropertyInternal(ctx, &desc, JS_VALUE_GET_OBJ(s->target), atom);
  52850. if (res < 0)
  52851. return -1;
  52852. if (res) {
  52853. if ((desc.flags & (JS_PROP_GETSET | JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE)) == 0) {
  52854. if (!js_same_value(ctx, desc.value, value)) {
  52855. goto fail;
  52856. }
  52857. } else if ((desc.flags & (JS_PROP_GETSET | JS_PROP_CONFIGURABLE)) == JS_PROP_GETSET && JS_IsUndefined(desc.setter)) {
  52858. fail:
  52859. js_free_desc(ctx, &desc);
  52860. JS_ThrowTypeError(ctx, "proxy: inconsistent set");
  52861. return -1;
  52862. }
  52863. js_free_desc(ctx, &desc);
  52864. }
  52865. } else {
  52866. if ((flags & JS_PROP_THROW) ||
  52867. ((flags & JS_PROP_THROW_STRICT) && is_strict_mode(ctx))) {
  52868. JS_ThrowTypeError(ctx, "proxy: cannot set property");
  52869. return -1;
  52870. }
  52871. }
  52872. return ret;
  52873. }
  52874. static JSValue js_create_desc(JSContext *ctx, JSValueConst val,
  52875. JSValueConst getter, JSValueConst setter,
  52876. int flags)
  52877. {
  52878. JSValue ret;
  52879. ret = JS_NewObject(ctx);
  52880. if (JS_IsException(ret))
  52881. return ret;
  52882. if (flags & JS_PROP_HAS_GET) {
  52883. JS_DefinePropertyValue(ctx, ret, JS_ATOM_get, js_dup(getter),
  52884. JS_PROP_C_W_E);
  52885. }
  52886. if (flags & JS_PROP_HAS_SET) {
  52887. JS_DefinePropertyValue(ctx, ret, JS_ATOM_set, js_dup(setter),
  52888. JS_PROP_C_W_E);
  52889. }
  52890. if (flags & JS_PROP_HAS_VALUE) {
  52891. JS_DefinePropertyValue(ctx, ret, JS_ATOM_value, js_dup(val),
  52892. JS_PROP_C_W_E);
  52893. }
  52894. if (flags & JS_PROP_HAS_WRITABLE) {
  52895. JS_DefinePropertyValue(ctx, ret, JS_ATOM_writable,
  52896. js_bool(flags & JS_PROP_WRITABLE),
  52897. JS_PROP_C_W_E);
  52898. }
  52899. if (flags & JS_PROP_HAS_ENUMERABLE) {
  52900. JS_DefinePropertyValue(ctx, ret, JS_ATOM_enumerable,
  52901. js_bool(flags & JS_PROP_ENUMERABLE),
  52902. JS_PROP_C_W_E);
  52903. }
  52904. if (flags & JS_PROP_HAS_CONFIGURABLE) {
  52905. JS_DefinePropertyValue(ctx, ret, JS_ATOM_configurable,
  52906. js_bool(flags & JS_PROP_CONFIGURABLE),
  52907. JS_PROP_C_W_E);
  52908. }
  52909. return ret;
  52910. }
  52911. static int js_proxy_get_own_property(JSContext *ctx, JSPropertyDescriptor *pdesc,
  52912. JSValueConst obj, JSAtom prop)
  52913. {
  52914. JSProxyData *s;
  52915. JSValue method, trap_result_obj, prop_val;
  52916. int res, target_desc_ret, ret;
  52917. JSObject *p;
  52918. JSValueConst args[2];
  52919. JSPropertyDescriptor result_desc, target_desc;
  52920. s = get_proxy_method(ctx, &method, obj, JS_ATOM_getOwnPropertyDescriptor);
  52921. if (!s)
  52922. return -1;
  52923. p = JS_VALUE_GET_OBJ(s->target);
  52924. if (JS_IsUndefined(method)) {
  52925. return JS_GetOwnPropertyInternal(ctx, pdesc, p, prop);
  52926. }
  52927. prop_val = JS_AtomToValue(ctx, prop);
  52928. if (JS_IsException(prop_val)) {
  52929. JS_FreeValue(ctx, method);
  52930. return -1;
  52931. }
  52932. args[0] = s->target;
  52933. args[1] = prop_val;
  52934. trap_result_obj = JS_CallFree(ctx, method, s->handler, 2, args);
  52935. JS_FreeValue(ctx, prop_val);
  52936. if (JS_IsException(trap_result_obj))
  52937. return -1;
  52938. if (!JS_IsObject(trap_result_obj) && !JS_IsUndefined(trap_result_obj)) {
  52939. JS_FreeValue(ctx, trap_result_obj);
  52940. goto fail;
  52941. }
  52942. target_desc_ret = JS_GetOwnPropertyInternal(ctx, &target_desc, p, prop);
  52943. if (target_desc_ret < 0) {
  52944. JS_FreeValue(ctx, trap_result_obj);
  52945. return -1;
  52946. }
  52947. if (target_desc_ret)
  52948. js_free_desc(ctx, &target_desc);
  52949. if (JS_IsUndefined(trap_result_obj)) {
  52950. if (target_desc_ret) {
  52951. if (!(target_desc.flags & JS_PROP_CONFIGURABLE) || !p->extensible)
  52952. goto fail;
  52953. }
  52954. ret = false;
  52955. } else {
  52956. int flags1, extensible_target;
  52957. extensible_target = JS_IsExtensible(ctx, s->target);
  52958. if (extensible_target < 0) {
  52959. JS_FreeValue(ctx, trap_result_obj);
  52960. return -1;
  52961. }
  52962. res = js_obj_to_desc(ctx, &result_desc, trap_result_obj);
  52963. JS_FreeValue(ctx, trap_result_obj);
  52964. if (res < 0)
  52965. return -1;
  52966. if (target_desc_ret) {
  52967. /* convert result_desc.flags to defineProperty flags */
  52968. flags1 = result_desc.flags | JS_PROP_HAS_CONFIGURABLE | JS_PROP_HAS_ENUMERABLE;
  52969. if (result_desc.flags & JS_PROP_GETSET)
  52970. flags1 |= JS_PROP_HAS_GET | JS_PROP_HAS_SET;
  52971. else
  52972. flags1 |= JS_PROP_HAS_VALUE | JS_PROP_HAS_WRITABLE;
  52973. /* XXX: not complete check: need to compare value &
  52974. getter/setter as in defineproperty */
  52975. if (!check_define_prop_flags(target_desc.flags, flags1))
  52976. goto fail1;
  52977. } else {
  52978. if (!extensible_target)
  52979. goto fail1;
  52980. }
  52981. if (!(result_desc.flags & JS_PROP_CONFIGURABLE)) {
  52982. if (!target_desc_ret || (target_desc.flags & JS_PROP_CONFIGURABLE))
  52983. goto fail1;
  52984. if ((result_desc.flags &
  52985. (JS_PROP_GETSET | JS_PROP_WRITABLE)) == 0 &&
  52986. target_desc_ret &&
  52987. (target_desc.flags & JS_PROP_WRITABLE) != 0) {
  52988. /* proxy-missing-checks */
  52989. fail1:
  52990. js_free_desc(ctx, &result_desc);
  52991. fail:
  52992. JS_ThrowTypeError(ctx, "proxy: inconsistent getOwnPropertyDescriptor");
  52993. return -1;
  52994. }
  52995. }
  52996. ret = true;
  52997. if (pdesc) {
  52998. *pdesc = result_desc;
  52999. } else {
  53000. js_free_desc(ctx, &result_desc);
  53001. }
  53002. }
  53003. return ret;
  53004. }
  53005. static int js_proxy_define_own_property(JSContext *ctx, JSValueConst obj,
  53006. JSAtom prop, JSValueConst val,
  53007. JSValueConst getter,
  53008. JSValueConst setter, int flags)
  53009. {
  53010. JSProxyData *s;
  53011. JSValue method, ret1, prop_val, desc_val;
  53012. int res;
  53013. JSObject *p;
  53014. JSValueConst args[3];
  53015. JSPropertyDescriptor desc;
  53016. bool ret, setting_not_configurable;
  53017. s = get_proxy_method(ctx, &method, obj, JS_ATOM_defineProperty);
  53018. if (!s)
  53019. return -1;
  53020. if (JS_IsUndefined(method)) {
  53021. return JS_DefineProperty(ctx, s->target, prop, val, getter, setter, flags);
  53022. }
  53023. prop_val = JS_AtomToValue(ctx, prop);
  53024. if (JS_IsException(prop_val)) {
  53025. JS_FreeValue(ctx, method);
  53026. return -1;
  53027. }
  53028. desc_val = js_create_desc(ctx, val, getter, setter, flags);
  53029. if (JS_IsException(desc_val)) {
  53030. JS_FreeValue(ctx, prop_val);
  53031. JS_FreeValue(ctx, method);
  53032. return -1;
  53033. }
  53034. args[0] = s->target;
  53035. args[1] = prop_val;
  53036. args[2] = desc_val;
  53037. ret1 = JS_CallFree(ctx, method, s->handler, 3, args);
  53038. JS_FreeValue(ctx, prop_val);
  53039. JS_FreeValue(ctx, desc_val);
  53040. if (JS_IsException(ret1))
  53041. return -1;
  53042. ret = JS_ToBoolFree(ctx, ret1);
  53043. if (!ret) {
  53044. if (flags & JS_PROP_THROW) {
  53045. JS_ThrowTypeError(ctx, "proxy: defineProperty exception");
  53046. return -1;
  53047. } else {
  53048. return 0;
  53049. }
  53050. }
  53051. p = JS_VALUE_GET_OBJ(s->target);
  53052. res = JS_GetOwnPropertyInternal(ctx, &desc, p, prop);
  53053. if (res < 0)
  53054. return -1;
  53055. setting_not_configurable = ((flags & (JS_PROP_HAS_CONFIGURABLE |
  53056. JS_PROP_CONFIGURABLE)) ==
  53057. JS_PROP_HAS_CONFIGURABLE);
  53058. if (!res) {
  53059. if (!p->extensible || setting_not_configurable)
  53060. goto fail;
  53061. } else {
  53062. if (!check_define_prop_flags(desc.flags, flags) ||
  53063. ((desc.flags & JS_PROP_CONFIGURABLE) && setting_not_configurable)) {
  53064. goto fail1;
  53065. }
  53066. if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET)) {
  53067. if ((desc.flags & (JS_PROP_GETSET | JS_PROP_CONFIGURABLE)) ==
  53068. JS_PROP_GETSET) {
  53069. if ((flags & JS_PROP_HAS_GET) &&
  53070. !js_same_value(ctx, getter, desc.getter)) {
  53071. goto fail1;
  53072. }
  53073. if ((flags & JS_PROP_HAS_SET) &&
  53074. !js_same_value(ctx, setter, desc.setter)) {
  53075. goto fail1;
  53076. }
  53077. }
  53078. } else if (flags & JS_PROP_HAS_VALUE) {
  53079. if ((desc.flags & (JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE)) ==
  53080. JS_PROP_WRITABLE && !(flags & JS_PROP_WRITABLE)) {
  53081. /* missing-proxy-check feature */
  53082. goto fail1;
  53083. } else if ((desc.flags & (JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE)) == 0 &&
  53084. !js_same_value(ctx, val, desc.value)) {
  53085. goto fail1;
  53086. }
  53087. }
  53088. if (flags & JS_PROP_HAS_WRITABLE) {
  53089. if ((desc.flags & (JS_PROP_GETSET | JS_PROP_CONFIGURABLE |
  53090. JS_PROP_WRITABLE)) == JS_PROP_WRITABLE) {
  53091. /* proxy-missing-checks */
  53092. fail1:
  53093. js_free_desc(ctx, &desc);
  53094. fail:
  53095. JS_ThrowTypeError(ctx, "proxy: inconsistent defineProperty");
  53096. return -1;
  53097. }
  53098. }
  53099. js_free_desc(ctx, &desc);
  53100. }
  53101. return 1;
  53102. }
  53103. static int js_proxy_delete_property(JSContext *ctx, JSValueConst obj,
  53104. JSAtom atom)
  53105. {
  53106. JSProxyData *s;
  53107. JSValue method, ret, atom_val;
  53108. int res2, is_extensible;
  53109. bool res;
  53110. JSValueConst args[2];
  53111. s = get_proxy_method(ctx, &method, obj, JS_ATOM_deleteProperty);
  53112. if (!s)
  53113. return -1;
  53114. if (JS_IsUndefined(method)) {
  53115. return JS_DeleteProperty(ctx, s->target, atom, 0);
  53116. }
  53117. atom_val = JS_AtomToValue(ctx, atom);;
  53118. if (JS_IsException(atom_val)) {
  53119. JS_FreeValue(ctx, method);
  53120. return -1;
  53121. }
  53122. args[0] = s->target;
  53123. args[1] = atom_val;
  53124. ret = JS_CallFree(ctx, method, s->handler, 2, args);
  53125. JS_FreeValue(ctx, atom_val);
  53126. if (JS_IsException(ret))
  53127. return -1;
  53128. res = JS_ToBoolFree(ctx, ret);
  53129. if (res) {
  53130. JSPropertyDescriptor desc;
  53131. res2 = JS_GetOwnPropertyInternal(ctx, &desc, JS_VALUE_GET_OBJ(s->target), atom);
  53132. if (res2 < 0)
  53133. return -1;
  53134. if (res2) {
  53135. if (!(desc.flags & JS_PROP_CONFIGURABLE))
  53136. goto fail;
  53137. is_extensible = JS_IsExtensible(ctx, s->target);
  53138. if (is_extensible < 0)
  53139. goto fail1;
  53140. if (!is_extensible) {
  53141. /* proxy-missing-checks */
  53142. fail:
  53143. JS_ThrowTypeError(ctx, "proxy: inconsistent deleteProperty");
  53144. fail1:
  53145. js_free_desc(ctx, &desc);
  53146. return -1;
  53147. }
  53148. js_free_desc(ctx, &desc);
  53149. }
  53150. }
  53151. return res;
  53152. }
  53153. /* return the index of the property or -1 if not found */
  53154. static int find_prop_key(const JSPropertyEnum *tab, int n, JSAtom atom)
  53155. {
  53156. int i;
  53157. for(i = 0; i < n; i++) {
  53158. if (tab[i].atom == atom)
  53159. return i;
  53160. }
  53161. return -1;
  53162. }
  53163. static int js_proxy_get_own_property_names(JSContext *ctx,
  53164. JSPropertyEnum **ptab,
  53165. uint32_t *plen,
  53166. JSValueConst obj)
  53167. {
  53168. JSProxyData *s;
  53169. JSValue method, prop_array, val;
  53170. uint32_t len, i, len2;
  53171. JSPropertyEnum *tab, *tab2;
  53172. JSAtom atom;
  53173. JSPropertyDescriptor desc;
  53174. int res, is_extensible, idx;
  53175. s = get_proxy_method(ctx, &method, obj, JS_ATOM_ownKeys);
  53176. if (!s)
  53177. return -1;
  53178. if (JS_IsUndefined(method)) {
  53179. return JS_GetOwnPropertyNamesInternal(ctx, ptab, plen,
  53180. JS_VALUE_GET_OBJ(s->target),
  53181. JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK);
  53182. }
  53183. prop_array = JS_CallFree(ctx, method, s->handler, 1, vc(&s->target));
  53184. if (JS_IsException(prop_array))
  53185. return -1;
  53186. tab = NULL;
  53187. len = 0;
  53188. tab2 = NULL;
  53189. len2 = 0;
  53190. if (js_get_length32(ctx, &len, prop_array))
  53191. goto fail;
  53192. if (len > 0) {
  53193. tab = js_mallocz(ctx, sizeof(tab[0]) * len);
  53194. if (!tab)
  53195. goto fail;
  53196. }
  53197. for(i = 0; i < len; i++) {
  53198. val = JS_GetPropertyUint32(ctx, prop_array, i);
  53199. if (JS_IsException(val))
  53200. goto fail;
  53201. if (!JS_IsString(val) && !JS_IsSymbol(val)) {
  53202. JS_FreeValue(ctx, val);
  53203. JS_ThrowTypeError(ctx, "proxy: properties must be strings or symbols");
  53204. goto fail;
  53205. }
  53206. atom = JS_ValueToAtom(ctx, val);
  53207. JS_FreeValue(ctx, val);
  53208. if (atom == JS_ATOM_NULL)
  53209. goto fail;
  53210. tab[i].atom = atom;
  53211. tab[i].is_enumerable = false; /* XXX: redundant? */
  53212. }
  53213. /* check duplicate properties (XXX: inefficient, could store the
  53214. * properties an a temporary object to use the hash) */
  53215. for(i = 1; i < len; i++) {
  53216. if (find_prop_key(tab, i, tab[i].atom) >= 0) {
  53217. JS_ThrowTypeError(ctx, "proxy: duplicate property");
  53218. goto fail;
  53219. }
  53220. }
  53221. is_extensible = JS_IsExtensible(ctx, s->target);
  53222. if (is_extensible < 0)
  53223. goto fail;
  53224. /* check if there are non configurable properties */
  53225. if (s->is_revoked) {
  53226. JS_ThrowTypeErrorRevokedProxy(ctx);
  53227. goto fail;
  53228. }
  53229. if (JS_GetOwnPropertyNamesInternal(ctx, &tab2, &len2, JS_VALUE_GET_OBJ(s->target),
  53230. JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK))
  53231. goto fail;
  53232. for(i = 0; i < len2; i++) {
  53233. if (s->is_revoked) {
  53234. JS_ThrowTypeErrorRevokedProxy(ctx);
  53235. goto fail;
  53236. }
  53237. res = JS_GetOwnPropertyInternal(ctx, &desc, JS_VALUE_GET_OBJ(s->target),
  53238. tab2[i].atom);
  53239. if (res < 0)
  53240. goto fail;
  53241. if (res) { /* safety, property should be found */
  53242. js_free_desc(ctx, &desc);
  53243. if (!(desc.flags & JS_PROP_CONFIGURABLE) || !is_extensible) {
  53244. idx = find_prop_key(tab, len, tab2[i].atom);
  53245. if (idx < 0) {
  53246. JS_ThrowTypeError(ctx, "proxy: target property must be present in proxy ownKeys");
  53247. goto fail;
  53248. }
  53249. /* mark the property as found */
  53250. if (!is_extensible)
  53251. tab[idx].is_enumerable = true;
  53252. }
  53253. }
  53254. }
  53255. if (!is_extensible) {
  53256. /* check that all property in 'tab' were checked */
  53257. for(i = 0; i < len; i++) {
  53258. if (!tab[i].is_enumerable) {
  53259. JS_ThrowTypeError(ctx, "proxy: property not present in target were returned by non extensible proxy");
  53260. goto fail;
  53261. }
  53262. }
  53263. }
  53264. js_free_prop_enum(ctx, tab2, len2);
  53265. JS_FreeValue(ctx, prop_array);
  53266. *ptab = tab;
  53267. *plen = len;
  53268. return 0;
  53269. fail:
  53270. js_free_prop_enum(ctx, tab2, len2);
  53271. js_free_prop_enum(ctx, tab, len);
  53272. JS_FreeValue(ctx, prop_array);
  53273. return -1;
  53274. }
  53275. static JSValue js_proxy_call_constructor(JSContext *ctx, JSValueConst func_obj,
  53276. JSValueConst new_target,
  53277. int argc, JSValueConst *argv)
  53278. {
  53279. JSProxyData *s;
  53280. JSValue method, arg_array, ret;
  53281. JSValueConst args[3];
  53282. s = get_proxy_method(ctx, &method, func_obj, JS_ATOM_construct);
  53283. if (!s)
  53284. return JS_EXCEPTION;
  53285. if (!JS_IsConstructor(ctx, s->target))
  53286. return JS_ThrowTypeError(ctx, "not a constructor");
  53287. if (JS_IsUndefined(method))
  53288. return JS_CallConstructor2(ctx, s->target, new_target, argc, argv);
  53289. arg_array = js_create_array(ctx, argc, argv);
  53290. if (JS_IsException(arg_array)) {
  53291. ret = JS_EXCEPTION;
  53292. goto fail;
  53293. }
  53294. args[0] = s->target;
  53295. args[1] = arg_array;
  53296. args[2] = new_target;
  53297. ret = JS_Call(ctx, method, s->handler, 3, args);
  53298. if (!JS_IsException(ret) && JS_VALUE_GET_TAG(ret) != JS_TAG_OBJECT) {
  53299. JS_FreeValue(ctx, ret);
  53300. ret = JS_ThrowTypeErrorNotAnObject(ctx);
  53301. }
  53302. fail:
  53303. JS_FreeValue(ctx, method);
  53304. JS_FreeValue(ctx, arg_array);
  53305. return ret;
  53306. }
  53307. static JSValue js_proxy_call(JSContext *ctx, JSValueConst func_obj,
  53308. JSValueConst this_obj,
  53309. int argc, JSValueConst *argv, int flags)
  53310. {
  53311. JSProxyData *s;
  53312. JSValue method, arg_array, ret;
  53313. JSValueConst args[3];
  53314. if (flags & JS_CALL_FLAG_CONSTRUCTOR)
  53315. return js_proxy_call_constructor(ctx, func_obj, this_obj, argc, argv);
  53316. s = get_proxy_method(ctx, &method, func_obj, JS_ATOM_apply);
  53317. if (!s)
  53318. return JS_EXCEPTION;
  53319. if (!s->is_func) {
  53320. JS_FreeValue(ctx, method);
  53321. return JS_ThrowTypeErrorNotAFunction(ctx);
  53322. }
  53323. if (JS_IsUndefined(method))
  53324. return JS_Call(ctx, s->target, this_obj, argc, argv);
  53325. arg_array = js_create_array(ctx, argc, argv);
  53326. if (JS_IsException(arg_array)) {
  53327. ret = JS_EXCEPTION;
  53328. goto fail;
  53329. }
  53330. args[0] = s->target;
  53331. args[1] = this_obj;
  53332. args[2] = arg_array;
  53333. ret = JS_Call(ctx, method, s->handler, 3, args);
  53334. fail:
  53335. JS_FreeValue(ctx, method);
  53336. JS_FreeValue(ctx, arg_array);
  53337. return ret;
  53338. }
  53339. static int js_proxy_isArray(JSContext *ctx, JSValueConst obj)
  53340. {
  53341. JSProxyData *s = JS_GetOpaque(obj, JS_CLASS_PROXY);
  53342. if (!s)
  53343. return false;
  53344. if (js_check_stack_overflow(ctx->rt, 0)) {
  53345. JS_ThrowStackOverflow(ctx);
  53346. return -1;
  53347. }
  53348. if (s->is_revoked) {
  53349. JS_ThrowTypeErrorRevokedProxy(ctx);
  53350. return -1;
  53351. }
  53352. return js_is_array(ctx, s->target);
  53353. }
  53354. static const JSClassExoticMethods js_proxy_exotic_methods = {
  53355. .get_own_property = js_proxy_get_own_property,
  53356. .define_own_property = js_proxy_define_own_property,
  53357. .delete_property = js_proxy_delete_property,
  53358. .get_own_property_names = js_proxy_get_own_property_names,
  53359. .has_property = js_proxy_has,
  53360. .get_property = js_proxy_get,
  53361. .set_property = js_proxy_set,
  53362. };
  53363. static JSValue js_proxy_constructor(JSContext *ctx, JSValueConst this_val,
  53364. int argc, JSValueConst *argv)
  53365. {
  53366. JSValueConst target, handler;
  53367. JSValue obj;
  53368. JSProxyData *s;
  53369. target = argv[0];
  53370. handler = argv[1];
  53371. if (JS_VALUE_GET_TAG(target) != JS_TAG_OBJECT ||
  53372. JS_VALUE_GET_TAG(handler) != JS_TAG_OBJECT)
  53373. return JS_ThrowTypeErrorNotAnObject(ctx);
  53374. obj = JS_NewObjectProtoClass(ctx, JS_NULL, JS_CLASS_PROXY);
  53375. if (JS_IsException(obj))
  53376. return obj;
  53377. s = js_malloc(ctx, sizeof(JSProxyData));
  53378. if (!s) {
  53379. JS_FreeValue(ctx, obj);
  53380. return JS_EXCEPTION;
  53381. }
  53382. s->target = js_dup(target);
  53383. s->handler = js_dup(handler);
  53384. s->is_func = JS_IsFunction(ctx, target);
  53385. s->is_revoked = false;
  53386. JS_SetOpaqueInternal(obj, s);
  53387. JS_SetConstructorBit(ctx, obj, JS_IsConstructor(ctx, target));
  53388. return obj;
  53389. }
  53390. static JSValue js_proxy_revoke(JSContext *ctx, JSValueConst this_val,
  53391. int argc, JSValueConst *argv, int magic,
  53392. JSValueConst *func_data)
  53393. {
  53394. JSProxyData *s = JS_GetOpaque(func_data[0], JS_CLASS_PROXY);
  53395. if (s) {
  53396. /* We do not free the handler and target in case they are
  53397. referenced as constants in the C call stack */
  53398. s->is_revoked = true;
  53399. JS_FreeValue(ctx, unsafe_unconst(func_data[0]));
  53400. func_data[0] = JS_NULL;
  53401. }
  53402. return JS_UNDEFINED;
  53403. }
  53404. static JSValue js_proxy_revoke_constructor(JSContext *ctx,
  53405. JSValueConst proxy_obj)
  53406. {
  53407. return JS_NewCFunctionData(ctx, js_proxy_revoke, 0, 0, 1, &proxy_obj);
  53408. }
  53409. static JSValue js_proxy_revocable(JSContext *ctx, JSValueConst this_val,
  53410. int argc, JSValueConst *argv)
  53411. {
  53412. JSValue proxy_obj, revoke_obj = JS_UNDEFINED, obj;
  53413. proxy_obj = js_proxy_constructor(ctx, JS_UNDEFINED, argc, argv);
  53414. if (JS_IsException(proxy_obj))
  53415. goto fail;
  53416. revoke_obj = js_proxy_revoke_constructor(ctx, proxy_obj);
  53417. if (JS_IsException(revoke_obj))
  53418. goto fail;
  53419. obj = JS_NewObject(ctx);
  53420. if (JS_IsException(obj))
  53421. goto fail;
  53422. // XXX: exceptions?
  53423. JS_DefinePropertyValue(ctx, obj, JS_ATOM_proxy, proxy_obj, JS_PROP_C_W_E);
  53424. JS_DefinePropertyValue(ctx, obj, JS_ATOM_revoke, revoke_obj, JS_PROP_C_W_E);
  53425. return obj;
  53426. fail:
  53427. JS_FreeValue(ctx, proxy_obj);
  53428. JS_FreeValue(ctx, revoke_obj);
  53429. return JS_EXCEPTION;
  53430. }
  53431. static const JSCFunctionListEntry js_proxy_funcs[] = {
  53432. JS_CFUNC_DEF("revocable", 2, js_proxy_revocable ),
  53433. };
  53434. static const JSClassShortDef js_proxy_class_def[] = {
  53435. { JS_ATOM_Object, js_proxy_finalizer, js_proxy_mark }, /* JS_CLASS_PROXY */
  53436. };
  53437. void JS_AddIntrinsicProxy(JSContext *ctx)
  53438. {
  53439. JSRuntime *rt = ctx->rt;
  53440. JSValue obj1;
  53441. if (!JS_IsRegisteredClass(rt, JS_CLASS_PROXY)) {
  53442. init_class_range(rt, js_proxy_class_def, JS_CLASS_PROXY,
  53443. countof(js_proxy_class_def));
  53444. rt->class_array[JS_CLASS_PROXY].exotic = &js_proxy_exotic_methods;
  53445. rt->class_array[JS_CLASS_PROXY].call = js_proxy_call;
  53446. }
  53447. obj1 = JS_NewCFunction2(ctx, js_proxy_constructor, "Proxy", 2,
  53448. JS_CFUNC_constructor, 0);
  53449. JS_SetConstructorBit(ctx, obj1, true);
  53450. JS_SetPropertyFunctionList(ctx, obj1, js_proxy_funcs,
  53451. countof(js_proxy_funcs));
  53452. JS_DefinePropertyValueStr(ctx, ctx->global_obj, "Proxy",
  53453. obj1, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);
  53454. }
  53455. bool JS_IsProxy(JSValueConst val)
  53456. {
  53457. if (JS_VALUE_GET_TAG(val) == JS_TAG_OBJECT) {
  53458. JSObject *p = JS_VALUE_GET_OBJ(val);
  53459. return p->class_id == JS_CLASS_PROXY;
  53460. }
  53461. return false;
  53462. }
  53463. static JSValue js_get_proxy_field(JSContext *ctx, JSValueConst proxy,
  53464. int offset)
  53465. {
  53466. if (JS_VALUE_GET_TAG(proxy) == JS_TAG_OBJECT) {
  53467. JSObject *p = JS_VALUE_GET_OBJ(proxy);
  53468. if (p->class_id == JS_CLASS_PROXY) {
  53469. JSProxyData *s = JS_GetOpaque(proxy, JS_CLASS_PROXY);
  53470. if (s->is_revoked)
  53471. return JS_ThrowTypeErrorRevokedProxy(ctx);
  53472. return js_dup(*(JSValue *)((char *)s + offset));
  53473. }
  53474. }
  53475. return JS_ThrowTypeError(ctx, "not a proxy");
  53476. }
  53477. JSValue JS_GetProxyTarget(JSContext *ctx, JSValueConst proxy)
  53478. {
  53479. return js_get_proxy_field(ctx, proxy, offsetof(JSProxyData, target));
  53480. }
  53481. JSValue JS_GetProxyHandler(JSContext *ctx, JSValueConst proxy)
  53482. {
  53483. return js_get_proxy_field(ctx, proxy, offsetof(JSProxyData, handler));
  53484. }
  53485. /* Symbol */
  53486. static JSValue js_symbol_constructor(JSContext *ctx, JSValueConst new_target,
  53487. int argc, JSValueConst *argv)
  53488. {
  53489. JSValue str;
  53490. JSString *p;
  53491. if (!JS_IsUndefined(new_target))
  53492. return JS_ThrowTypeError(ctx, "not a constructor");
  53493. if (argc == 0 || JS_IsUndefined(argv[0])) {
  53494. p = NULL;
  53495. } else {
  53496. str = JS_ToString(ctx, argv[0]);
  53497. if (JS_IsException(str))
  53498. return JS_EXCEPTION;
  53499. p = JS_VALUE_GET_STRING(str);
  53500. }
  53501. return JS_NewSymbolInternal(ctx, p, JS_ATOM_TYPE_SYMBOL);
  53502. }
  53503. static JSValue js_thisSymbolValue(JSContext *ctx, JSValueConst this_val)
  53504. {
  53505. if (JS_VALUE_GET_TAG(this_val) == JS_TAG_SYMBOL)
  53506. return js_dup(this_val);
  53507. if (JS_VALUE_GET_TAG(this_val) == JS_TAG_OBJECT) {
  53508. JSObject *p = JS_VALUE_GET_OBJ(this_val);
  53509. if (p->class_id == JS_CLASS_SYMBOL) {
  53510. if (JS_VALUE_GET_TAG(p->u.object_data) == JS_TAG_SYMBOL)
  53511. return js_dup(p->u.object_data);
  53512. }
  53513. }
  53514. return JS_ThrowTypeError(ctx, "not a symbol");
  53515. }
  53516. static JSValue js_symbol_toString(JSContext *ctx, JSValueConst this_val,
  53517. int argc, JSValueConst *argv)
  53518. {
  53519. JSValue val, ret;
  53520. val = js_thisSymbolValue(ctx, this_val);
  53521. if (JS_IsException(val))
  53522. return val;
  53523. /* XXX: use JS_ToStringInternal() with a flags */
  53524. ret = js_string_constructor(ctx, JS_UNDEFINED, 1, vc(&val));
  53525. JS_FreeValue(ctx, val);
  53526. return ret;
  53527. }
  53528. static JSValue js_symbol_valueOf(JSContext *ctx, JSValueConst this_val,
  53529. int argc, JSValueConst *argv)
  53530. {
  53531. return js_thisSymbolValue(ctx, this_val);
  53532. }
  53533. static JSValue js_symbol_get_description(JSContext *ctx, JSValueConst this_val)
  53534. {
  53535. JSValue val, ret;
  53536. JSAtomStruct *p;
  53537. val = js_thisSymbolValue(ctx, this_val);
  53538. if (JS_IsException(val))
  53539. return val;
  53540. p = JS_VALUE_GET_PTR(val);
  53541. if (p->len == 0 && p->is_wide_char != 0) {
  53542. ret = JS_UNDEFINED;
  53543. } else {
  53544. ret = JS_AtomToString(ctx, js_get_atom_index(ctx->rt, p));
  53545. }
  53546. JS_FreeValue(ctx, val);
  53547. return ret;
  53548. }
  53549. static const JSCFunctionListEntry js_symbol_proto_funcs[] = {
  53550. JS_CFUNC_DEF("toString", 0, js_symbol_toString ),
  53551. JS_CFUNC_DEF("valueOf", 0, js_symbol_valueOf ),
  53552. // XXX: should have writable: false
  53553. JS_CFUNC_DEF("[Symbol.toPrimitive]", 1, js_symbol_valueOf ),
  53554. JS_PROP_STRING_DEF("[Symbol.toStringTag]", "Symbol", JS_PROP_CONFIGURABLE ),
  53555. JS_CGETSET_DEF("description", js_symbol_get_description, NULL ),
  53556. };
  53557. static JSValue js_symbol_for(JSContext *ctx, JSValueConst this_val,
  53558. int argc, JSValueConst *argv)
  53559. {
  53560. JSValue str;
  53561. str = JS_ToString(ctx, argv[0]);
  53562. if (JS_IsException(str))
  53563. return JS_EXCEPTION;
  53564. return JS_NewSymbolInternal(ctx, JS_VALUE_GET_STRING(str), JS_ATOM_TYPE_GLOBAL_SYMBOL);
  53565. }
  53566. static JSValue js_symbol_keyFor(JSContext *ctx, JSValueConst this_val,
  53567. int argc, JSValueConst *argv)
  53568. {
  53569. JSAtomStruct *p;
  53570. if (!JS_IsSymbol(argv[0]))
  53571. return JS_ThrowTypeError(ctx, "not a symbol");
  53572. p = JS_VALUE_GET_PTR(argv[0]);
  53573. if (p->atom_type != JS_ATOM_TYPE_GLOBAL_SYMBOL)
  53574. return JS_UNDEFINED;
  53575. return js_dup(JS_MKPTR(JS_TAG_STRING, p));
  53576. }
  53577. static const JSCFunctionListEntry js_symbol_funcs[] = {
  53578. JS_CFUNC_DEF("for", 1, js_symbol_for ),
  53579. JS_CFUNC_DEF("keyFor", 1, js_symbol_keyFor ),
  53580. };
  53581. /* Set/Map/WeakSet/WeakMap */
  53582. typedef struct JSMapRecord {
  53583. int ref_count; /* used during enumeration to avoid freeing the record */
  53584. bool empty; /* true if the record is deleted */
  53585. struct JSMapState *map;
  53586. struct list_head link;
  53587. struct list_head hash_link;
  53588. JSValue key;
  53589. JSValue value;
  53590. } JSMapRecord;
  53591. typedef struct JSMapState {
  53592. bool is_weak; /* true if WeakSet/WeakMap */
  53593. struct list_head records; /* list of JSMapRecord.link */
  53594. uint32_t record_count;
  53595. struct list_head *hash_table;
  53596. uint32_t hash_size; /* must be a power of two */
  53597. uint32_t record_count_threshold; /* count at which a hash table
  53598. resize is needed */
  53599. } JSMapState;
  53600. #define MAGIC_SET (1 << 0)
  53601. #define MAGIC_WEAK (1 << 1)
  53602. static JSValue js_map_constructor(JSContext *ctx, JSValueConst new_target,
  53603. int argc, JSValueConst *argv, int magic)
  53604. {
  53605. JSMapState *s;
  53606. JSValue obj, adder = JS_UNDEFINED, iter = JS_UNDEFINED, next_method = JS_UNDEFINED;
  53607. JSValueConst arr;
  53608. bool is_set, is_weak;
  53609. is_set = magic & MAGIC_SET;
  53610. is_weak = ((magic & MAGIC_WEAK) != 0);
  53611. obj = js_create_from_ctor(ctx, new_target, JS_CLASS_MAP + magic);
  53612. if (JS_IsException(obj))
  53613. return JS_EXCEPTION;
  53614. s = js_mallocz(ctx, sizeof(*s));
  53615. if (!s)
  53616. goto fail;
  53617. init_list_head(&s->records);
  53618. s->is_weak = is_weak;
  53619. JS_SetOpaqueInternal(obj, s);
  53620. s->hash_size = 1;
  53621. s->hash_table = js_malloc(ctx, sizeof(s->hash_table[0]) * s->hash_size);
  53622. if (!s->hash_table)
  53623. goto fail;
  53624. init_list_head(&s->hash_table[0]);
  53625. s->record_count_threshold = 4;
  53626. arr = JS_UNDEFINED;
  53627. if (argc > 0)
  53628. arr = argv[0];
  53629. if (!JS_IsUndefined(arr) && !JS_IsNull(arr)) {
  53630. JSValue item, ret;
  53631. int done;
  53632. adder = JS_GetProperty(ctx, obj, is_set ? JS_ATOM_add : JS_ATOM_set);
  53633. if (JS_IsException(adder))
  53634. goto fail;
  53635. if (!JS_IsFunction(ctx, adder)) {
  53636. JS_ThrowTypeError(ctx, "set/add is not a function");
  53637. goto fail;
  53638. }
  53639. iter = JS_GetIterator(ctx, arr, false);
  53640. if (JS_IsException(iter))
  53641. goto fail;
  53642. next_method = JS_GetProperty(ctx, iter, JS_ATOM_next);
  53643. if (JS_IsException(next_method))
  53644. goto fail;
  53645. for(;;) {
  53646. item = JS_IteratorNext(ctx, iter, next_method, 0, NULL, &done);
  53647. if (JS_IsException(item))
  53648. goto fail;
  53649. if (done) {
  53650. JS_FreeValue(ctx, item);
  53651. break;
  53652. }
  53653. if (is_set) {
  53654. ret = JS_Call(ctx, adder, obj, 1, vc(&item));
  53655. if (JS_IsException(ret)) {
  53656. JS_FreeValue(ctx, item);
  53657. goto fail;
  53658. }
  53659. } else {
  53660. JSValue key, value;
  53661. JSValueConst args[2];
  53662. key = JS_UNDEFINED;
  53663. value = JS_UNDEFINED;
  53664. if (!JS_IsObject(item)) {
  53665. JS_ThrowTypeErrorNotAnObject(ctx);
  53666. goto fail1;
  53667. }
  53668. key = JS_GetPropertyUint32(ctx, item, 0);
  53669. if (JS_IsException(key))
  53670. goto fail1;
  53671. value = JS_GetPropertyUint32(ctx, item, 1);
  53672. if (JS_IsException(value))
  53673. goto fail1;
  53674. args[0] = key;
  53675. args[1] = value;
  53676. ret = JS_Call(ctx, adder, obj, 2, args);
  53677. if (JS_IsException(ret)) {
  53678. fail1:
  53679. JS_FreeValue(ctx, item);
  53680. JS_FreeValue(ctx, key);
  53681. JS_FreeValue(ctx, value);
  53682. goto fail;
  53683. }
  53684. JS_FreeValue(ctx, key);
  53685. JS_FreeValue(ctx, value);
  53686. }
  53687. JS_FreeValue(ctx, ret);
  53688. JS_FreeValue(ctx, item);
  53689. }
  53690. JS_FreeValue(ctx, next_method);
  53691. JS_FreeValue(ctx, iter);
  53692. JS_FreeValue(ctx, adder);
  53693. }
  53694. return obj;
  53695. fail:
  53696. if (JS_IsObject(iter)) {
  53697. /* close the iterator object, preserving pending exception */
  53698. JS_IteratorClose(ctx, iter, true);
  53699. }
  53700. JS_FreeValue(ctx, next_method);
  53701. JS_FreeValue(ctx, iter);
  53702. JS_FreeValue(ctx, adder);
  53703. JS_FreeValue(ctx, obj);
  53704. return JS_EXCEPTION;
  53705. }
  53706. /* XXX: could normalize strings to speed up comparison */
  53707. static JSValue map_normalize_key(JSContext *ctx, JSValue key)
  53708. {
  53709. uint32_t tag = JS_VALUE_GET_TAG(key);
  53710. // convert -0.0 to +0.0
  53711. // not a leak; |key| and return value are not heap-allocated
  53712. if (JS_TAG_IS_FLOAT64(tag) && JS_VALUE_GET_FLOAT64(key) == 0.0)
  53713. return js_int32(0);
  53714. return key;
  53715. }
  53716. static JSValueConst map_normalize_key_const(JSContext *ctx, JSValueConst key)
  53717. {
  53718. return safe_const(map_normalize_key(ctx, unsafe_unconst(key)));
  53719. }
  53720. /* XXX: better hash ? */
  53721. static uint32_t map_hash_key(JSContext *ctx, JSValueConst key)
  53722. {
  53723. uint32_t tag = JS_VALUE_GET_NORM_TAG(key);
  53724. uint32_t h;
  53725. double d;
  53726. JSFloat64Union u;
  53727. bf_t *a;
  53728. switch(tag) {
  53729. case JS_TAG_BOOL:
  53730. h = JS_VALUE_GET_INT(key);
  53731. break;
  53732. case JS_TAG_STRING:
  53733. h = hash_string(JS_VALUE_GET_STRING(key), 0);
  53734. break;
  53735. case JS_TAG_OBJECT:
  53736. case JS_TAG_SYMBOL:
  53737. h = (uintptr_t)JS_VALUE_GET_PTR(key) * 3163;
  53738. break;
  53739. case JS_TAG_INT:
  53740. d = JS_VALUE_GET_INT(key);
  53741. goto hash_float64;
  53742. case JS_TAG_BIG_INT:
  53743. a = JS_GetBigInt(key);
  53744. h = hash_string8((void *)a->tab, a->len * sizeof(*a->tab), 0);
  53745. break;
  53746. case JS_TAG_FLOAT64:
  53747. d = JS_VALUE_GET_FLOAT64(key);
  53748. /* normalize the NaN */
  53749. if (isnan(d))
  53750. d = NAN;
  53751. hash_float64:
  53752. u.d = d;
  53753. h = (u.u32[0] ^ u.u32[1]) * 3163;
  53754. return h ^= JS_TAG_FLOAT64;
  53755. default:
  53756. h = 0;
  53757. break;
  53758. }
  53759. h ^= tag;
  53760. return h;
  53761. }
  53762. static JSMapRecord *map_find_record(JSContext *ctx, JSMapState *s,
  53763. JSValueConst key)
  53764. {
  53765. struct list_head *el;
  53766. JSMapRecord *mr;
  53767. uint32_t h;
  53768. h = map_hash_key(ctx, key) & (s->hash_size - 1);
  53769. list_for_each(el, &s->hash_table[h]) {
  53770. mr = list_entry(el, JSMapRecord, hash_link);
  53771. if (js_same_value_zero(ctx, mr->key, key))
  53772. return mr;
  53773. }
  53774. return NULL;
  53775. }
  53776. static void map_hash_resize(JSContext *ctx, JSMapState *s)
  53777. {
  53778. uint32_t new_hash_size, i, h;
  53779. size_t slack;
  53780. struct list_head *new_hash_table, *el;
  53781. JSMapRecord *mr;
  53782. /* XXX: no reporting of memory allocation failure */
  53783. if (s->hash_size == 1)
  53784. new_hash_size = 4;
  53785. else
  53786. new_hash_size = s->hash_size * 2;
  53787. new_hash_table = js_realloc2(ctx, s->hash_table,
  53788. sizeof(new_hash_table[0]) * new_hash_size, &slack);
  53789. if (!new_hash_table)
  53790. return;
  53791. new_hash_size += slack / sizeof(*new_hash_table);
  53792. for(i = 0; i < new_hash_size; i++)
  53793. init_list_head(&new_hash_table[i]);
  53794. list_for_each(el, &s->records) {
  53795. mr = list_entry(el, JSMapRecord, link);
  53796. if (!mr->empty) {
  53797. h = map_hash_key(ctx, mr->key) & (new_hash_size - 1);
  53798. list_add_tail(&mr->hash_link, &new_hash_table[h]);
  53799. }
  53800. }
  53801. s->hash_table = new_hash_table;
  53802. s->hash_size = new_hash_size;
  53803. s->record_count_threshold = new_hash_size * 2;
  53804. }
  53805. static JSWeakRefRecord **get_first_weak_ref(JSValueConst key)
  53806. {
  53807. switch (JS_VALUE_GET_TAG(key)) {
  53808. case JS_TAG_OBJECT:
  53809. {
  53810. JSObject *p = JS_VALUE_GET_OBJ(key);
  53811. return &p->first_weak_ref;
  53812. }
  53813. break;
  53814. case JS_TAG_SYMBOL:
  53815. {
  53816. JSAtomStruct *p = JS_VALUE_GET_PTR(key);
  53817. return &p->first_weak_ref;
  53818. }
  53819. break;
  53820. default:
  53821. abort();
  53822. }
  53823. return NULL; // pacify compiler
  53824. }
  53825. static JSMapRecord *map_add_record(JSContext *ctx, JSMapState *s,
  53826. JSValueConst key)
  53827. {
  53828. uint32_t h;
  53829. JSMapRecord *mr;
  53830. mr = js_malloc(ctx, sizeof(*mr));
  53831. if (!mr)
  53832. return NULL;
  53833. mr->ref_count = 1;
  53834. mr->map = s;
  53835. mr->empty = false;
  53836. if (s->is_weak) {
  53837. JSWeakRefRecord *wr = js_malloc(ctx, sizeof(*wr));
  53838. if (!wr) {
  53839. js_free(ctx, mr);
  53840. return NULL;
  53841. }
  53842. wr->kind = JS_WEAK_REF_KIND_MAP;
  53843. wr->u.map_record = mr;
  53844. insert_weakref_record(key, wr);
  53845. mr->key = unsafe_unconst(key);
  53846. } else {
  53847. mr->key = js_dup(key);
  53848. }
  53849. h = map_hash_key(ctx, key) & (s->hash_size - 1);
  53850. list_add_tail(&mr->hash_link, &s->hash_table[h]);
  53851. list_add_tail(&mr->link, &s->records);
  53852. s->record_count++;
  53853. if (s->record_count >= s->record_count_threshold) {
  53854. map_hash_resize(ctx, s);
  53855. }
  53856. return mr;
  53857. }
  53858. /* Remove the weak reference from the object weak
  53859. reference list. we don't use a doubly linked list to
  53860. save space, assuming a given object has few weak
  53861. references to it */
  53862. static void delete_map_weak_ref(JSRuntime *rt, JSMapRecord *mr)
  53863. {
  53864. JSWeakRefRecord **pwr, *wr;
  53865. pwr = get_first_weak_ref(mr->key);
  53866. for(;;) {
  53867. wr = *pwr;
  53868. assert(wr != NULL);
  53869. if (wr->kind == JS_WEAK_REF_KIND_MAP && wr->u.map_record == mr)
  53870. break;
  53871. pwr = &wr->next_weak_ref;
  53872. }
  53873. *pwr = wr->next_weak_ref;
  53874. js_free_rt(rt, wr);
  53875. }
  53876. static void map_delete_record(JSRuntime *rt, JSMapState *s, JSMapRecord *mr)
  53877. {
  53878. if (mr->empty)
  53879. return;
  53880. list_del(&mr->hash_link);
  53881. if (s->is_weak) {
  53882. delete_map_weak_ref(rt, mr);
  53883. } else {
  53884. JS_FreeValueRT(rt, mr->key);
  53885. }
  53886. JS_FreeValueRT(rt, mr->value);
  53887. if (--mr->ref_count == 0) {
  53888. list_del(&mr->link);
  53889. js_free_rt(rt, mr);
  53890. } else {
  53891. /* keep a zombie record for iterators */
  53892. mr->empty = true;
  53893. mr->key = JS_UNDEFINED;
  53894. mr->value = JS_UNDEFINED;
  53895. }
  53896. s->record_count--;
  53897. }
  53898. static void map_decref_record(JSRuntime *rt, JSMapRecord *mr)
  53899. {
  53900. if (--mr->ref_count == 0) {
  53901. /* the record can be safely removed */
  53902. assert(mr->empty);
  53903. list_del(&mr->link);
  53904. js_free_rt(rt, mr);
  53905. }
  53906. }
  53907. static JSValue js_map_set(JSContext *ctx, JSValueConst this_val,
  53908. int argc, JSValueConst *argv, int magic)
  53909. {
  53910. JSMapState *s = JS_GetOpaque2(ctx, this_val, JS_CLASS_MAP + magic);
  53911. JSMapRecord *mr;
  53912. JSValueConst key, value;
  53913. int is_set;
  53914. if (!s)
  53915. return JS_EXCEPTION;
  53916. is_set = (magic & MAGIC_SET);
  53917. key = map_normalize_key_const(ctx, argv[0]);
  53918. if (s->is_weak && !is_valid_weakref_target(key))
  53919. return JS_ThrowTypeError(ctx, "invalid value used as %s key", is_set ? "WeakSet" : "WeakMap");
  53920. if (is_set)
  53921. value = JS_UNDEFINED;
  53922. else
  53923. value = argv[1];
  53924. mr = map_find_record(ctx, s, key);
  53925. if (mr) {
  53926. JS_FreeValue(ctx, mr->value);
  53927. } else {
  53928. mr = map_add_record(ctx, s, key);
  53929. if (!mr)
  53930. return JS_EXCEPTION;
  53931. }
  53932. mr->value = js_dup(value);
  53933. return js_dup(this_val);
  53934. }
  53935. static JSValue js_map_get(JSContext *ctx, JSValueConst this_val,
  53936. int argc, JSValueConst *argv, int magic)
  53937. {
  53938. JSMapState *s = JS_GetOpaque2(ctx, this_val, JS_CLASS_MAP + magic);
  53939. JSMapRecord *mr;
  53940. JSValueConst key;
  53941. if (!s)
  53942. return JS_EXCEPTION;
  53943. key = map_normalize_key_const(ctx, argv[0]);
  53944. mr = map_find_record(ctx, s, key);
  53945. if (!mr)
  53946. return JS_UNDEFINED;
  53947. else
  53948. return js_dup(mr->value);
  53949. }
  53950. static JSValue js_map_has(JSContext *ctx, JSValueConst this_val,
  53951. int argc, JSValueConst *argv, int magic)
  53952. {
  53953. JSMapState *s = JS_GetOpaque2(ctx, this_val, JS_CLASS_MAP + magic);
  53954. JSMapRecord *mr;
  53955. JSValueConst key;
  53956. if (!s)
  53957. return JS_EXCEPTION;
  53958. key = map_normalize_key_const(ctx, argv[0]);
  53959. mr = map_find_record(ctx, s, key);
  53960. return js_bool(mr != NULL);
  53961. }
  53962. static JSValue js_map_delete(JSContext *ctx, JSValueConst this_val,
  53963. int argc, JSValueConst *argv, int magic)
  53964. {
  53965. JSMapState *s = JS_GetOpaque2(ctx, this_val, JS_CLASS_MAP + magic);
  53966. JSMapRecord *mr;
  53967. JSValueConst key;
  53968. if (!s)
  53969. return JS_EXCEPTION;
  53970. key = map_normalize_key_const(ctx, argv[0]);
  53971. mr = map_find_record(ctx, s, key);
  53972. if (!mr)
  53973. return JS_FALSE;
  53974. map_delete_record(ctx->rt, s, mr);
  53975. return JS_TRUE;
  53976. }
  53977. static JSValue js_map_clear(JSContext *ctx, JSValueConst this_val,
  53978. int argc, JSValueConst *argv, int magic)
  53979. {
  53980. JSMapState *s = JS_GetOpaque2(ctx, this_val, JS_CLASS_MAP + magic);
  53981. struct list_head *el, *el1;
  53982. JSMapRecord *mr;
  53983. if (!s)
  53984. return JS_EXCEPTION;
  53985. list_for_each_safe(el, el1, &s->records) {
  53986. mr = list_entry(el, JSMapRecord, link);
  53987. map_delete_record(ctx->rt, s, mr);
  53988. }
  53989. return JS_UNDEFINED;
  53990. }
  53991. static JSValue js_map_get_size(JSContext *ctx, JSValueConst this_val, int magic)
  53992. {
  53993. JSMapState *s = JS_GetOpaque2(ctx, this_val, JS_CLASS_MAP + magic);
  53994. if (!s)
  53995. return JS_EXCEPTION;
  53996. return js_uint32(s->record_count);
  53997. }
  53998. static JSValue js_map_forEach(JSContext *ctx, JSValueConst this_val,
  53999. int argc, JSValueConst *argv, int magic)
  54000. {
  54001. JSMapState *s = JS_GetOpaque2(ctx, this_val, JS_CLASS_MAP + magic);
  54002. JSValueConst func, this_arg;
  54003. JSValue ret, args[3];
  54004. struct list_head *el;
  54005. JSMapRecord *mr;
  54006. if (!s)
  54007. return JS_EXCEPTION;
  54008. func = argv[0];
  54009. if (argc > 1)
  54010. this_arg = argv[1];
  54011. else
  54012. this_arg = JS_UNDEFINED;
  54013. if (check_function(ctx, func))
  54014. return JS_EXCEPTION;
  54015. /* Note: the list can be modified while traversing it, but the
  54016. current element is locked */
  54017. el = s->records.next;
  54018. while (el != &s->records) {
  54019. mr = list_entry(el, JSMapRecord, link);
  54020. if (!mr->empty) {
  54021. mr->ref_count++;
  54022. /* must duplicate in case the record is deleted */
  54023. args[1] = js_dup(mr->key);
  54024. if (magic)
  54025. args[0] = args[1];
  54026. else
  54027. args[0] = js_dup(mr->value);
  54028. args[2] = unsafe_unconst(this_val);
  54029. ret = JS_Call(ctx, func, this_arg, 3, vc(args));
  54030. JS_FreeValue(ctx, args[0]);
  54031. if (!magic)
  54032. JS_FreeValue(ctx, args[1]);
  54033. el = el->next;
  54034. map_decref_record(ctx->rt, mr);
  54035. if (JS_IsException(ret))
  54036. return ret;
  54037. JS_FreeValue(ctx, ret);
  54038. } else {
  54039. el = el->next;
  54040. }
  54041. }
  54042. return JS_UNDEFINED;
  54043. }
  54044. static JSValue js_map_groupBy(JSContext *ctx, JSValueConst this_val,
  54045. int argc, JSValueConst *argv)
  54046. {
  54047. JSValue res, iter, next, groups, k, v, prop;
  54048. JSValueConst cb, args[2];
  54049. int64_t idx;
  54050. int done;
  54051. // "is function?" check must be observed before argv[0] is accessed
  54052. cb = argv[1];
  54053. if (check_function(ctx, cb))
  54054. return JS_EXCEPTION;
  54055. iter = JS_GetIterator(ctx, argv[0], /*is_async*/false);
  54056. if (JS_IsException(iter))
  54057. return JS_EXCEPTION;
  54058. k = JS_UNDEFINED;
  54059. v = JS_UNDEFINED;
  54060. prop = JS_UNDEFINED;
  54061. groups = JS_UNDEFINED;
  54062. next = JS_GetProperty(ctx, iter, JS_ATOM_next);
  54063. if (JS_IsException(next))
  54064. goto exception;
  54065. groups = js_map_constructor(ctx, JS_UNDEFINED, 0, NULL, 0);
  54066. if (JS_IsException(groups))
  54067. goto exception;
  54068. for (idx = 0; ; idx++) {
  54069. v = JS_IteratorNext(ctx, iter, next, 0, NULL, &done);
  54070. if (JS_IsException(v))
  54071. goto exception;
  54072. if (done)
  54073. break; // v is JS_UNDEFINED
  54074. args[0] = v;
  54075. args[1] = js_int64(idx);
  54076. k = JS_Call(ctx, cb, ctx->global_obj, 2, args);
  54077. if (JS_IsException(k))
  54078. goto exception;
  54079. prop = js_map_get(ctx, groups, 1, vc(&k), 0);
  54080. if (JS_IsException(prop))
  54081. goto exception;
  54082. if (JS_IsUndefined(prop)) {
  54083. prop = JS_NewArray(ctx);
  54084. if (JS_IsException(prop))
  54085. goto exception;
  54086. args[0] = k;
  54087. args[1] = prop;
  54088. res = js_map_set(ctx, groups, 2, args, 0);
  54089. if (JS_IsException(res))
  54090. goto exception;
  54091. JS_FreeValue(ctx, res);
  54092. }
  54093. res = js_array_push(ctx, prop, 1, vc(&v), /*unshift*/0);
  54094. if (JS_IsException(res))
  54095. goto exception;
  54096. // res is an int64
  54097. JS_FreeValue(ctx, prop);
  54098. JS_FreeValue(ctx, k);
  54099. JS_FreeValue(ctx, v);
  54100. prop = JS_UNDEFINED;
  54101. k = JS_UNDEFINED;
  54102. v = JS_UNDEFINED;
  54103. }
  54104. JS_FreeValue(ctx, iter);
  54105. JS_FreeValue(ctx, next);
  54106. return groups;
  54107. exception:
  54108. JS_FreeValue(ctx, prop);
  54109. JS_FreeValue(ctx, k);
  54110. JS_FreeValue(ctx, v);
  54111. JS_FreeValue(ctx, groups);
  54112. JS_FreeValue(ctx, iter);
  54113. JS_FreeValue(ctx, next);
  54114. return JS_EXCEPTION;
  54115. }
  54116. static void js_map_finalizer(JSRuntime *rt, JSValueConst val)
  54117. {
  54118. JSObject *p;
  54119. JSMapState *s;
  54120. struct list_head *el, *el1;
  54121. JSMapRecord *mr;
  54122. p = JS_VALUE_GET_OBJ(val);
  54123. s = p->u.map_state;
  54124. if (s) {
  54125. /* if the object is deleted we are sure that no iterator is
  54126. using it */
  54127. list_for_each_safe(el, el1, &s->records) {
  54128. mr = list_entry(el, JSMapRecord, link);
  54129. if (!mr->empty) {
  54130. if (s->is_weak)
  54131. delete_map_weak_ref(rt, mr);
  54132. else
  54133. JS_FreeValueRT(rt, mr->key);
  54134. JS_FreeValueRT(rt, mr->value);
  54135. }
  54136. js_free_rt(rt, mr);
  54137. }
  54138. js_free_rt(rt, s->hash_table);
  54139. js_free_rt(rt, s);
  54140. }
  54141. }
  54142. static void js_map_mark(JSRuntime *rt, JSValueConst val,
  54143. JS_MarkFunc *mark_func)
  54144. {
  54145. JSObject *p = JS_VALUE_GET_OBJ(val);
  54146. JSMapState *s;
  54147. struct list_head *el;
  54148. JSMapRecord *mr;
  54149. s = p->u.map_state;
  54150. if (s) {
  54151. list_for_each(el, &s->records) {
  54152. mr = list_entry(el, JSMapRecord, link);
  54153. if (!s->is_weak)
  54154. JS_MarkValue(rt, mr->key, mark_func);
  54155. JS_MarkValue(rt, mr->value, mark_func);
  54156. }
  54157. }
  54158. }
  54159. /* Map Iterator */
  54160. typedef struct JSMapIteratorData {
  54161. JSValue obj;
  54162. JSIteratorKindEnum kind;
  54163. JSMapRecord *cur_record;
  54164. } JSMapIteratorData;
  54165. static void js_map_iterator_finalizer(JSRuntime *rt, JSValueConst val)
  54166. {
  54167. JSObject *p;
  54168. JSMapIteratorData *it;
  54169. p = JS_VALUE_GET_OBJ(val);
  54170. it = p->u.map_iterator_data;
  54171. if (it) {
  54172. /* During the GC sweep phase the Map finalizer may be
  54173. called before the Map iterator finalizer */
  54174. if (JS_IsLiveObject(rt, it->obj) && it->cur_record) {
  54175. map_decref_record(rt, it->cur_record);
  54176. }
  54177. JS_FreeValueRT(rt, it->obj);
  54178. js_free_rt(rt, it);
  54179. }
  54180. }
  54181. static void js_map_iterator_mark(JSRuntime *rt, JSValueConst val,
  54182. JS_MarkFunc *mark_func)
  54183. {
  54184. JSObject *p = JS_VALUE_GET_OBJ(val);
  54185. JSMapIteratorData *it;
  54186. it = p->u.map_iterator_data;
  54187. if (it) {
  54188. /* the record is already marked by the object */
  54189. JS_MarkValue(rt, it->obj, mark_func);
  54190. }
  54191. }
  54192. static JSValue js_create_map_iterator(JSContext *ctx, JSValueConst this_val,
  54193. int argc, JSValueConst *argv, int magic)
  54194. {
  54195. JSIteratorKindEnum kind;
  54196. JSMapState *s;
  54197. JSMapIteratorData *it;
  54198. JSValue enum_obj;
  54199. kind = magic >> 2;
  54200. magic &= 3;
  54201. s = JS_GetOpaque2(ctx, this_val, JS_CLASS_MAP + magic);
  54202. if (!s)
  54203. return JS_EXCEPTION;
  54204. enum_obj = JS_NewObjectClass(ctx, JS_CLASS_MAP_ITERATOR + magic);
  54205. if (JS_IsException(enum_obj))
  54206. goto fail;
  54207. it = js_malloc(ctx, sizeof(*it));
  54208. if (!it) {
  54209. JS_FreeValue(ctx, enum_obj);
  54210. goto fail;
  54211. }
  54212. it->obj = js_dup(this_val);
  54213. it->kind = kind;
  54214. it->cur_record = NULL;
  54215. JS_SetOpaqueInternal(enum_obj, it);
  54216. return enum_obj;
  54217. fail:
  54218. return JS_EXCEPTION;
  54219. }
  54220. static JSValue js_map_iterator_next(JSContext *ctx, JSValueConst this_val,
  54221. int argc, JSValueConst *argv,
  54222. int *pdone, int magic)
  54223. {
  54224. JSMapIteratorData *it;
  54225. JSMapState *s;
  54226. JSMapRecord *mr;
  54227. struct list_head *el;
  54228. it = JS_GetOpaque2(ctx, this_val, JS_CLASS_MAP_ITERATOR + magic);
  54229. if (!it) {
  54230. *pdone = false;
  54231. return JS_EXCEPTION;
  54232. }
  54233. if (JS_IsUndefined(it->obj))
  54234. goto done;
  54235. s = JS_GetOpaque(it->obj, JS_CLASS_MAP + magic);
  54236. assert(s != NULL);
  54237. if (!it->cur_record) {
  54238. el = s->records.next;
  54239. } else {
  54240. mr = it->cur_record;
  54241. el = mr->link.next;
  54242. map_decref_record(ctx->rt, mr); /* the record can be freed here */
  54243. }
  54244. for(;;) {
  54245. if (el == &s->records) {
  54246. /* no more record */
  54247. it->cur_record = NULL;
  54248. JS_FreeValue(ctx, it->obj);
  54249. it->obj = JS_UNDEFINED;
  54250. done:
  54251. /* end of enumeration */
  54252. *pdone = true;
  54253. return JS_UNDEFINED;
  54254. }
  54255. mr = list_entry(el, JSMapRecord, link);
  54256. if (!mr->empty)
  54257. break;
  54258. /* get the next record */
  54259. el = mr->link.next;
  54260. }
  54261. /* lock the record so that it won't be freed */
  54262. mr->ref_count++;
  54263. it->cur_record = mr;
  54264. *pdone = false;
  54265. if (it->kind == JS_ITERATOR_KIND_KEY) {
  54266. return js_dup(mr->key);
  54267. } else {
  54268. JSValueConst args[2];
  54269. args[0] = mr->key;
  54270. if (magic)
  54271. args[1] = mr->key;
  54272. else
  54273. args[1] = mr->value;
  54274. if (it->kind == JS_ITERATOR_KIND_VALUE) {
  54275. return js_dup(args[1]);
  54276. } else {
  54277. return js_create_array(ctx, 2, args);
  54278. }
  54279. }
  54280. }
  54281. static JSValue js_map_read(BCReaderState *s, int magic)
  54282. {
  54283. JSContext *ctx = s->ctx;
  54284. JSValue obj, rv, argv[2];
  54285. uint32_t i, prop_count;
  54286. argv[0] = JS_UNDEFINED;
  54287. argv[1] = JS_UNDEFINED;
  54288. obj = js_map_constructor(ctx, JS_UNDEFINED, 0, NULL, magic);
  54289. if (JS_IsException(obj))
  54290. return JS_EXCEPTION;
  54291. if (BC_add_object_ref(s, obj))
  54292. goto fail;
  54293. if (bc_get_leb128(s, &prop_count))
  54294. goto fail;
  54295. for(i = 0; i < prop_count; i++) {
  54296. argv[0] = JS_ReadObjectRec(s);
  54297. if (JS_IsException(argv[0]))
  54298. goto fail;
  54299. if (!(magic & MAGIC_SET)) {
  54300. argv[1] = JS_ReadObjectRec(s);
  54301. if (JS_IsException(argv[1]))
  54302. goto fail;
  54303. }
  54304. rv = js_map_set(ctx, obj, countof(argv), vc(argv), magic);
  54305. if (JS_IsException(rv))
  54306. goto fail;
  54307. JS_FreeValue(ctx, rv);
  54308. JS_FreeValue(ctx, argv[0]);
  54309. JS_FreeValue(ctx, argv[1]);
  54310. argv[0] = JS_UNDEFINED;
  54311. argv[1] = JS_UNDEFINED;
  54312. }
  54313. return obj;
  54314. fail:
  54315. JS_FreeValue(ctx, obj);
  54316. JS_FreeValue(ctx, argv[0]);
  54317. JS_FreeValue(ctx, argv[1]);
  54318. return JS_EXCEPTION;
  54319. }
  54320. static int js_map_write(BCWriterState *s, struct JSMapState *map_state,
  54321. int magic)
  54322. {
  54323. struct list_head *el;
  54324. JSMapRecord *mr;
  54325. bc_put_leb128(s, map_state ? map_state->record_count : 0);
  54326. if (map_state) {
  54327. list_for_each(el, &map_state->records) {
  54328. mr = list_entry(el, JSMapRecord, link);
  54329. if (JS_WriteObjectRec(s, mr->key))
  54330. return -1;
  54331. // mr->value is always JS_UNDEFINED for sets
  54332. if (!(magic & MAGIC_SET))
  54333. if (JS_WriteObjectRec(s, mr->value))
  54334. return -1;
  54335. }
  54336. }
  54337. return 0;
  54338. }
  54339. static JSValue JS_ReadMap(BCReaderState *s)
  54340. {
  54341. return js_map_read(s, 0);
  54342. }
  54343. static JSValue JS_ReadSet(BCReaderState *s)
  54344. {
  54345. return js_map_read(s, MAGIC_SET);
  54346. }
  54347. static int JS_WriteMap(BCWriterState *s, struct JSMapState *map_state)
  54348. {
  54349. return js_map_write(s, map_state, 0);
  54350. }
  54351. static int JS_WriteSet(BCWriterState *s, struct JSMapState *map_state)
  54352. {
  54353. return js_map_write(s, map_state, MAGIC_SET);
  54354. }
  54355. static int js_setlike_get_size(JSContext *ctx, JSValueConst setlike,
  54356. int64_t *pout)
  54357. {
  54358. JSMapState *s;
  54359. JSValue v;
  54360. double d;
  54361. s = JS_GetOpaque(setlike, JS_CLASS_SET);
  54362. if (s) {
  54363. *pout = s->record_count;
  54364. } else {
  54365. v = JS_GetProperty(ctx, setlike, JS_ATOM_size);
  54366. if (JS_IsException(v))
  54367. return -1;
  54368. if (JS_IsUndefined(v)) {
  54369. JS_ThrowTypeError(ctx, ".size is undefined");
  54370. return -1;
  54371. }
  54372. if (JS_ToFloat64Free(ctx, &d, v) < 0)
  54373. return -1;
  54374. if (isnan(d)) {
  54375. JS_ThrowTypeError(ctx, ".size is not a number");
  54376. return -1;
  54377. }
  54378. *pout = d;
  54379. }
  54380. return 0;
  54381. }
  54382. static int js_setlike_get_has(JSContext *ctx, JSValueConst setlike,
  54383. JSValue *pout)
  54384. {
  54385. JSValue v;
  54386. v = JS_GetProperty(ctx, setlike, JS_ATOM_has);
  54387. if (JS_IsException(v))
  54388. return -1;
  54389. if (JS_IsUndefined(v)) {
  54390. JS_ThrowTypeError(ctx, ".has is undefined");
  54391. return -1;
  54392. }
  54393. if (!JS_IsFunction(ctx, v)) {
  54394. JS_ThrowTypeError(ctx, ".has is not a function");
  54395. JS_FreeValue(ctx, v);
  54396. return -1;
  54397. }
  54398. *pout = v;
  54399. return 0;
  54400. }
  54401. static int js_setlike_get_keys(JSContext *ctx, JSValueConst setlike,
  54402. JSValue *pout)
  54403. {
  54404. JSValue v;
  54405. v = JS_GetProperty(ctx, setlike, JS_ATOM_keys);
  54406. if (JS_IsException(v))
  54407. return -1;
  54408. if (JS_IsUndefined(v)) {
  54409. JS_ThrowTypeError(ctx, ".keys is undefined");
  54410. return -1;
  54411. }
  54412. if (!JS_IsFunction(ctx, v)) {
  54413. JS_ThrowTypeError(ctx, ".keys is not a function");
  54414. JS_FreeValue(ctx, v);
  54415. return -1;
  54416. }
  54417. *pout = v;
  54418. return 0;
  54419. }
  54420. static JSValue js_set_isDisjointFrom(JSContext *ctx, JSValueConst this_val,
  54421. int argc, JSValueConst *argv)
  54422. {
  54423. JSValue item, iter, keys, has, next, rv, rval;
  54424. int done;
  54425. bool found;
  54426. JSMapState *s;
  54427. int64_t size;
  54428. int ok;
  54429. has = JS_UNDEFINED;
  54430. iter = JS_UNDEFINED;
  54431. keys = JS_UNDEFINED;
  54432. next = JS_UNDEFINED;
  54433. rval = JS_EXCEPTION;
  54434. s = JS_GetOpaque2(ctx, this_val, JS_CLASS_SET);
  54435. if (!s)
  54436. goto exception;
  54437. // order matters!
  54438. if (js_setlike_get_size(ctx, argv[0], &size) < 0)
  54439. goto exception;
  54440. if (js_setlike_get_has(ctx, argv[0], &has) < 0)
  54441. goto exception;
  54442. if (js_setlike_get_keys(ctx, argv[0], &keys) < 0)
  54443. goto exception;
  54444. if (s->record_count > size) {
  54445. iter = JS_Call(ctx, keys, argv[0], 0, NULL);
  54446. if (JS_IsException(iter))
  54447. goto exception;
  54448. next = JS_GetProperty(ctx, iter, JS_ATOM_next);
  54449. if (JS_IsException(next))
  54450. goto exception;
  54451. found = false;
  54452. do {
  54453. item = JS_IteratorNext(ctx, iter, next, 0, NULL, &done);
  54454. if (JS_IsException(item))
  54455. goto exception;
  54456. if (done) // item is JS_UNDEFINED
  54457. break;
  54458. item = map_normalize_key(ctx, item);
  54459. found = (NULL != map_find_record(ctx, s, item));
  54460. JS_FreeValue(ctx, item);
  54461. } while (!found);
  54462. } else {
  54463. iter = js_create_map_iterator(ctx, this_val, 0, NULL, MAGIC_SET);
  54464. if (JS_IsException(iter))
  54465. goto exception;
  54466. found = false;
  54467. do {
  54468. item = js_map_iterator_next(ctx, iter, 0, NULL, &done, MAGIC_SET);
  54469. if (JS_IsException(item))
  54470. goto exception;
  54471. if (done) // item is JS_UNDEFINED
  54472. break;
  54473. rv = JS_Call(ctx, has, argv[0], 1, vc(&item));
  54474. JS_FreeValue(ctx, item);
  54475. ok = JS_ToBoolFree(ctx, rv); // returns -1 if rv is JS_EXCEPTION
  54476. if (ok < 0)
  54477. goto exception;
  54478. found = (ok > 0);
  54479. } while (!found);
  54480. }
  54481. rval = !found ? JS_TRUE : JS_FALSE;
  54482. exception:
  54483. JS_FreeValue(ctx, has);
  54484. JS_FreeValue(ctx, keys);
  54485. JS_FreeValue(ctx, iter);
  54486. JS_FreeValue(ctx, next);
  54487. return rval;
  54488. }
  54489. static JSValue js_set_isSubsetOf(JSContext *ctx, JSValueConst this_val,
  54490. int argc, JSValueConst *argv)
  54491. {
  54492. JSValue item, iter, keys, has, next, rv, rval;
  54493. bool found;
  54494. JSMapState *s;
  54495. int64_t size;
  54496. int done, ok;
  54497. has = JS_UNDEFINED;
  54498. iter = JS_UNDEFINED;
  54499. keys = JS_UNDEFINED;
  54500. next = JS_UNDEFINED;
  54501. rval = JS_EXCEPTION;
  54502. s = JS_GetOpaque2(ctx, this_val, JS_CLASS_SET);
  54503. if (!s)
  54504. goto exception;
  54505. // order matters!
  54506. if (js_setlike_get_size(ctx, argv[0], &size) < 0)
  54507. goto exception;
  54508. if (js_setlike_get_has(ctx, argv[0], &has) < 0)
  54509. goto exception;
  54510. if (js_setlike_get_keys(ctx, argv[0], &keys) < 0)
  54511. goto exception;
  54512. found = false;
  54513. if (s->record_count > size)
  54514. goto fini;
  54515. iter = js_create_map_iterator(ctx, this_val, 0, NULL, MAGIC_SET);
  54516. if (JS_IsException(iter))
  54517. goto exception;
  54518. found = true;
  54519. do {
  54520. item = js_map_iterator_next(ctx, iter, 0, NULL, &done, MAGIC_SET);
  54521. if (JS_IsException(item))
  54522. goto exception;
  54523. if (done) // item is JS_UNDEFINED
  54524. break;
  54525. rv = JS_Call(ctx, has, argv[0], 1, vc(&item));
  54526. JS_FreeValue(ctx, item);
  54527. ok = JS_ToBoolFree(ctx, rv); // returns -1 if rv is JS_EXCEPTION
  54528. if (ok < 0)
  54529. goto exception;
  54530. found = (ok > 0);
  54531. } while (found);
  54532. fini:
  54533. rval = found ? JS_TRUE : JS_FALSE;
  54534. exception:
  54535. JS_FreeValue(ctx, has);
  54536. JS_FreeValue(ctx, keys);
  54537. JS_FreeValue(ctx, iter);
  54538. JS_FreeValue(ctx, next);
  54539. return rval;
  54540. }
  54541. static JSValue js_set_isSupersetOf(JSContext *ctx, JSValueConst this_val,
  54542. int argc, JSValueConst *argv)
  54543. {
  54544. JSValue item, iter, keys, has, next, rval;
  54545. int done;
  54546. bool found;
  54547. JSMapState *s;
  54548. int64_t size;
  54549. has = JS_UNDEFINED;
  54550. iter = JS_UNDEFINED;
  54551. keys = JS_UNDEFINED;
  54552. next = JS_UNDEFINED;
  54553. rval = JS_EXCEPTION;
  54554. s = JS_GetOpaque2(ctx, this_val, JS_CLASS_SET);
  54555. if (!s)
  54556. goto exception;
  54557. // order matters!
  54558. if (js_setlike_get_size(ctx, argv[0], &size) < 0)
  54559. goto exception;
  54560. if (js_setlike_get_has(ctx, argv[0], &has) < 0)
  54561. goto exception;
  54562. if (js_setlike_get_keys(ctx, argv[0], &keys) < 0)
  54563. goto exception;
  54564. found = false;
  54565. if (s->record_count < size)
  54566. goto fini;
  54567. iter = JS_Call(ctx, keys, argv[0], 0, NULL);
  54568. if (JS_IsException(iter))
  54569. goto exception;
  54570. next = JS_GetProperty(ctx, iter, JS_ATOM_next);
  54571. if (JS_IsException(next))
  54572. goto exception;
  54573. found = true;
  54574. do {
  54575. item = JS_IteratorNext(ctx, iter, next, 0, NULL, &done);
  54576. if (JS_IsException(item))
  54577. goto exception;
  54578. if (done) // item is JS_UNDEFINED
  54579. break;
  54580. item = map_normalize_key(ctx, item);
  54581. found = (NULL != map_find_record(ctx, s, item));
  54582. JS_FreeValue(ctx, item);
  54583. } while (found);
  54584. fini:
  54585. rval = found ? JS_TRUE : JS_FALSE;
  54586. exception:
  54587. JS_FreeValue(ctx, has);
  54588. JS_FreeValue(ctx, keys);
  54589. JS_FreeValue(ctx, iter);
  54590. JS_FreeValue(ctx, next);
  54591. return rval;
  54592. }
  54593. static JSValue js_set_intersection(JSContext *ctx, JSValueConst this_val,
  54594. int argc, JSValueConst *argv)
  54595. {
  54596. JSValue newset, item, iter, keys, has, next, rv;
  54597. JSMapState *s, *t;
  54598. JSMapRecord *mr;
  54599. int64_t size;
  54600. int done, ok;
  54601. has = JS_UNDEFINED;
  54602. iter = JS_UNDEFINED;
  54603. keys = JS_UNDEFINED;
  54604. next = JS_UNDEFINED;
  54605. newset = JS_UNDEFINED;
  54606. s = JS_GetOpaque2(ctx, this_val, JS_CLASS_SET);
  54607. if (!s)
  54608. goto exception;
  54609. // order matters!
  54610. if (js_setlike_get_size(ctx, argv[0], &size) < 0)
  54611. goto exception;
  54612. if (js_setlike_get_has(ctx, argv[0], &has) < 0)
  54613. goto exception;
  54614. if (js_setlike_get_keys(ctx, argv[0], &keys) < 0)
  54615. goto exception;
  54616. if (s->record_count > size) {
  54617. iter = JS_Call(ctx, keys, argv[0], 0, NULL);
  54618. if (JS_IsException(iter))
  54619. goto exception;
  54620. next = JS_GetProperty(ctx, iter, JS_ATOM_next);
  54621. if (JS_IsException(next))
  54622. goto exception;
  54623. newset = js_map_constructor(ctx, JS_UNDEFINED, 0, NULL, MAGIC_SET);
  54624. if (JS_IsException(newset))
  54625. goto exception;
  54626. t = JS_GetOpaque(newset, JS_CLASS_SET);
  54627. for (;;) {
  54628. item = JS_IteratorNext(ctx, iter, next, 0, NULL, &done);
  54629. if (JS_IsException(item))
  54630. goto exception;
  54631. if (done) // item is JS_UNDEFINED
  54632. break;
  54633. item = map_normalize_key(ctx, item);
  54634. if (!map_find_record(ctx, s, item)) {
  54635. JS_FreeValue(ctx, item);
  54636. } else if (map_find_record(ctx, t, item)) {
  54637. JS_FreeValue(ctx, item); // no duplicates
  54638. } else if ((mr = map_add_record(ctx, t, item))) {
  54639. mr->value = JS_UNDEFINED;
  54640. } else {
  54641. JS_FreeValue(ctx, item);
  54642. goto exception;
  54643. }
  54644. }
  54645. } else {
  54646. iter = js_create_map_iterator(ctx, this_val, 0, NULL, MAGIC_SET);
  54647. if (JS_IsException(iter))
  54648. goto exception;
  54649. newset = js_map_constructor(ctx, JS_UNDEFINED, 0, NULL, MAGIC_SET);
  54650. if (JS_IsException(newset))
  54651. goto exception;
  54652. t = JS_GetOpaque(newset, JS_CLASS_SET);
  54653. for (;;) {
  54654. item = js_map_iterator_next(ctx, iter, 0, NULL, &done, MAGIC_SET);
  54655. if (JS_IsException(item))
  54656. goto exception;
  54657. if (done) // item is JS_UNDEFINED
  54658. break;
  54659. rv = JS_Call(ctx, has, argv[0], 1, vc(&item));
  54660. ok = JS_ToBoolFree(ctx, rv); // returns -1 if rv is JS_EXCEPTION
  54661. if (ok > 0) {
  54662. item = map_normalize_key(ctx, item);
  54663. if (map_find_record(ctx, t, item)) {
  54664. JS_FreeValue(ctx, item); // no duplicates
  54665. } else if ((mr = map_add_record(ctx, t, item))) {
  54666. mr->value = JS_UNDEFINED;
  54667. } else {
  54668. JS_FreeValue(ctx, item);
  54669. goto exception;
  54670. }
  54671. } else {
  54672. JS_FreeValue(ctx, item);
  54673. if (ok < 0)
  54674. goto exception;
  54675. }
  54676. }
  54677. }
  54678. goto fini;
  54679. exception:
  54680. JS_FreeValue(ctx, newset);
  54681. newset = JS_EXCEPTION;
  54682. fini:
  54683. JS_FreeValue(ctx, has);
  54684. JS_FreeValue(ctx, keys);
  54685. JS_FreeValue(ctx, iter);
  54686. JS_FreeValue(ctx, next);
  54687. return newset;
  54688. }
  54689. static JSValue js_set_difference(JSContext *ctx, JSValueConst this_val,
  54690. int argc, JSValueConst *argv)
  54691. {
  54692. JSValue newset, item, iter, keys, has, next, rv;
  54693. JSMapState *s, *t;
  54694. JSMapRecord *mr;
  54695. int64_t size;
  54696. int done;
  54697. int ok;
  54698. has = JS_UNDEFINED;
  54699. iter = JS_UNDEFINED;
  54700. keys = JS_UNDEFINED;
  54701. next = JS_UNDEFINED;
  54702. newset = JS_UNDEFINED;
  54703. s = JS_GetOpaque2(ctx, this_val, JS_CLASS_SET);
  54704. if (!s)
  54705. goto exception;
  54706. // order matters!
  54707. if (js_setlike_get_size(ctx, argv[0], &size) < 0)
  54708. goto exception;
  54709. if (js_setlike_get_has(ctx, argv[0], &has) < 0)
  54710. goto exception;
  54711. if (js_setlike_get_keys(ctx, argv[0], &keys) < 0)
  54712. goto exception;
  54713. if (s->record_count > size) {
  54714. iter = JS_Call(ctx, keys, argv[0], 0, NULL);
  54715. if (JS_IsException(iter))
  54716. goto exception;
  54717. next = JS_GetProperty(ctx, iter, JS_ATOM_next);
  54718. if (JS_IsException(next))
  54719. goto exception;
  54720. newset = js_map_constructor(ctx, JS_UNDEFINED, 1, &this_val, MAGIC_SET);
  54721. if (JS_IsException(newset))
  54722. goto exception;
  54723. t = JS_GetOpaque(newset, JS_CLASS_SET);
  54724. for (;;) {
  54725. item = JS_IteratorNext(ctx, iter, next, 0, NULL, &done);
  54726. if (JS_IsException(item))
  54727. goto exception;
  54728. if (done) // item is JS_UNDEFINED
  54729. break;
  54730. item = map_normalize_key(ctx, item);
  54731. mr = map_find_record(ctx, t, item);
  54732. if (mr)
  54733. map_delete_record(ctx->rt, t, mr);
  54734. JS_FreeValue(ctx, item);
  54735. }
  54736. } else {
  54737. iter = js_create_map_iterator(ctx, this_val, 0, NULL, MAGIC_SET);
  54738. if (JS_IsException(iter))
  54739. goto exception;
  54740. newset = js_map_constructor(ctx, JS_UNDEFINED, 0, NULL, MAGIC_SET);
  54741. if (JS_IsException(newset))
  54742. goto exception;
  54743. t = JS_GetOpaque(newset, JS_CLASS_SET);
  54744. for (;;) {
  54745. item = js_map_iterator_next(ctx, iter, 0, NULL, &done, MAGIC_SET);
  54746. if (JS_IsException(item))
  54747. goto exception;
  54748. if (done) // item is JS_UNDEFINED
  54749. break;
  54750. rv = JS_Call(ctx, has, argv[0], 1, vc(&item));
  54751. ok = JS_ToBoolFree(ctx, rv); // returns -1 if rv is JS_EXCEPTION
  54752. if (ok == 0) {
  54753. item = map_normalize_key(ctx, item);
  54754. if (map_find_record(ctx, t, item)) {
  54755. JS_FreeValue(ctx, item); // no duplicates
  54756. } else if ((mr = map_add_record(ctx, t, item))) {
  54757. mr->value = JS_UNDEFINED;
  54758. } else {
  54759. JS_FreeValue(ctx, item);
  54760. goto exception;
  54761. }
  54762. } else {
  54763. JS_FreeValue(ctx, item);
  54764. if (ok < 0)
  54765. goto exception;
  54766. }
  54767. }
  54768. }
  54769. goto fini;
  54770. exception:
  54771. JS_FreeValue(ctx, newset);
  54772. newset = JS_EXCEPTION;
  54773. fini:
  54774. JS_FreeValue(ctx, has);
  54775. JS_FreeValue(ctx, keys);
  54776. JS_FreeValue(ctx, iter);
  54777. JS_FreeValue(ctx, next);
  54778. return newset;
  54779. }
  54780. static JSValue js_set_symmetricDifference(JSContext *ctx, JSValueConst this_val,
  54781. int argc, JSValueConst *argv)
  54782. {
  54783. JSValue newset, item, iter, next, rv;
  54784. struct list_head *el;
  54785. JSMapState *s, *t;
  54786. JSMapRecord *mr;
  54787. int64_t size;
  54788. int done;
  54789. bool present;
  54790. s = JS_GetOpaque2(ctx, this_val, JS_CLASS_SET);
  54791. if (!s)
  54792. return JS_EXCEPTION;
  54793. // order matters! they're JS-observable side effects
  54794. if (js_setlike_get_size(ctx, argv[0], &size) < 0)
  54795. return JS_EXCEPTION;
  54796. if (js_setlike_get_has(ctx, argv[0], &rv) < 0)
  54797. return JS_EXCEPTION;
  54798. JS_FreeValue(ctx, rv);
  54799. newset = js_map_constructor(ctx, JS_UNDEFINED, 0, NULL, MAGIC_SET);
  54800. if (JS_IsException(newset))
  54801. return JS_EXCEPTION;
  54802. t = JS_GetOpaque(newset, JS_CLASS_SET);
  54803. iter = JS_UNDEFINED;
  54804. next = JS_UNDEFINED;
  54805. // can't clone this_val using js_map_constructor(),
  54806. // test262 mandates we don't call the .add method
  54807. list_for_each(el, &s->records) {
  54808. mr = list_entry(el, JSMapRecord, link);
  54809. if (mr->empty)
  54810. continue;
  54811. mr = map_add_record(ctx, t, js_dup(mr->key));
  54812. if (!mr)
  54813. goto exception;
  54814. mr->value = JS_UNDEFINED;
  54815. }
  54816. iter = JS_GetProperty(ctx, argv[0], JS_ATOM_keys);
  54817. if (JS_IsException(iter))
  54818. goto exception;
  54819. iter = JS_CallFree(ctx, iter, argv[0], 0, NULL);
  54820. if (JS_IsException(iter))
  54821. goto exception;
  54822. next = JS_GetProperty(ctx, iter, JS_ATOM_next);
  54823. if (JS_IsException(next))
  54824. goto exception;
  54825. for (;;) {
  54826. item = JS_IteratorNext(ctx, iter, next, 0, NULL, &done);
  54827. if (JS_IsException(item))
  54828. goto exception;
  54829. if (done) // item is JS_UNDEFINED
  54830. break;
  54831. // note the subtlety here: due to mutating iterators, it's
  54832. // possible for keys to disappear during iteration; test262
  54833. // still expects us to maintain insertion order though, so
  54834. // we first check |this|, then |new|; |new| is a copy of |this|
  54835. // - if item exists in |this|, delete (if it exists) from |new|
  54836. // - if item misses in |this| and |new|, add to |new|
  54837. // - if item exists in |new| but misses in |this|, *don't* add it,
  54838. // mutating iterator erased it
  54839. item = map_normalize_key(ctx, item);
  54840. present = (NULL != map_find_record(ctx, s, item));
  54841. mr = map_find_record(ctx, t, item);
  54842. if (present) {
  54843. if (mr)
  54844. map_delete_record(ctx->rt, t, mr);
  54845. JS_FreeValue(ctx, item);
  54846. } else if (mr) {
  54847. JS_FreeValue(ctx, item);
  54848. } else {
  54849. mr = map_add_record(ctx, t, item);
  54850. if (!mr) {
  54851. JS_FreeValue(ctx, item);
  54852. goto exception;
  54853. }
  54854. mr->value = JS_UNDEFINED;
  54855. }
  54856. }
  54857. goto fini;
  54858. exception:
  54859. JS_FreeValue(ctx, newset);
  54860. newset = JS_EXCEPTION;
  54861. fini:
  54862. JS_FreeValue(ctx, next);
  54863. JS_FreeValue(ctx, iter);
  54864. return newset;
  54865. }
  54866. static JSValue js_set_union(JSContext *ctx, JSValueConst this_val,
  54867. int argc, JSValueConst *argv)
  54868. {
  54869. JSValue newset, item, iter, next, rv;
  54870. struct list_head *el;
  54871. JSMapState *s, *t;
  54872. JSMapRecord *mr;
  54873. int64_t size;
  54874. int done;
  54875. s = JS_GetOpaque2(ctx, this_val, JS_CLASS_SET);
  54876. if (!s)
  54877. return JS_EXCEPTION;
  54878. // order matters! they're JS-observable side effects
  54879. if (js_setlike_get_size(ctx, argv[0], &size) < 0)
  54880. return JS_EXCEPTION;
  54881. if (js_setlike_get_has(ctx, argv[0], &rv) < 0)
  54882. return JS_EXCEPTION;
  54883. JS_FreeValue(ctx, rv);
  54884. newset = js_map_constructor(ctx, JS_UNDEFINED, 0, NULL, MAGIC_SET);
  54885. if (JS_IsException(newset))
  54886. return JS_EXCEPTION;
  54887. t = JS_GetOpaque(newset, JS_CLASS_SET);
  54888. iter = JS_UNDEFINED;
  54889. next = JS_UNDEFINED;
  54890. list_for_each(el, &s->records) {
  54891. mr = list_entry(el, JSMapRecord, link);
  54892. if (mr->empty)
  54893. continue;
  54894. mr = map_add_record(ctx, t, js_dup(mr->key));
  54895. if (!mr)
  54896. goto exception;
  54897. mr->value = JS_UNDEFINED;
  54898. }
  54899. iter = JS_GetProperty(ctx, argv[0], JS_ATOM_keys);
  54900. if (JS_IsException(iter))
  54901. goto exception;
  54902. iter = JS_CallFree(ctx, iter, argv[0], 0, NULL);
  54903. if (JS_IsException(iter))
  54904. goto exception;
  54905. next = JS_GetProperty(ctx, iter, JS_ATOM_next);
  54906. if (JS_IsException(next))
  54907. goto exception;
  54908. for (;;) {
  54909. item = JS_IteratorNext(ctx, iter, next, 0, NULL, &done);
  54910. if (JS_IsException(item))
  54911. goto exception;
  54912. if (done) // item is JS_UNDEFINED
  54913. break;
  54914. rv = js_map_set(ctx, newset, 1, vc(&item), MAGIC_SET);
  54915. JS_FreeValue(ctx, item);
  54916. if (JS_IsException(rv))
  54917. goto exception;
  54918. JS_FreeValue(ctx, rv);
  54919. }
  54920. goto fini;
  54921. exception:
  54922. JS_FreeValue(ctx, newset);
  54923. newset = JS_EXCEPTION;
  54924. fini:
  54925. JS_FreeValue(ctx, next);
  54926. JS_FreeValue(ctx, iter);
  54927. return newset;
  54928. }
  54929. static const JSCFunctionListEntry js_map_funcs[] = {
  54930. JS_CFUNC_DEF("groupBy", 2, js_map_groupBy ),
  54931. JS_CGETSET_DEF("[Symbol.species]", js_get_this, NULL ),
  54932. };
  54933. static const JSCFunctionListEntry js_set_funcs[] = {
  54934. JS_CGETSET_DEF("[Symbol.species]", js_get_this, NULL ),
  54935. };
  54936. static const JSCFunctionListEntry js_map_proto_funcs[] = {
  54937. JS_CFUNC_MAGIC_DEF("set", 2, js_map_set, 0 ),
  54938. JS_CFUNC_MAGIC_DEF("get", 1, js_map_get, 0 ),
  54939. JS_CFUNC_MAGIC_DEF("has", 1, js_map_has, 0 ),
  54940. JS_CFUNC_MAGIC_DEF("delete", 1, js_map_delete, 0 ),
  54941. JS_CFUNC_MAGIC_DEF("clear", 0, js_map_clear, 0 ),
  54942. JS_CGETSET_MAGIC_DEF("size", js_map_get_size, NULL, 0),
  54943. JS_CFUNC_MAGIC_DEF("forEach", 1, js_map_forEach, 0 ),
  54944. JS_CFUNC_MAGIC_DEF("values", 0, js_create_map_iterator, (JS_ITERATOR_KIND_VALUE << 2) | 0 ),
  54945. JS_CFUNC_MAGIC_DEF("keys", 0, js_create_map_iterator, (JS_ITERATOR_KIND_KEY << 2) | 0 ),
  54946. JS_CFUNC_MAGIC_DEF("entries", 0, js_create_map_iterator, (JS_ITERATOR_KIND_KEY_AND_VALUE << 2) | 0 ),
  54947. JS_ALIAS_DEF("[Symbol.iterator]", "entries" ),
  54948. JS_PROP_STRING_DEF("[Symbol.toStringTag]", "Map", JS_PROP_CONFIGURABLE ),
  54949. };
  54950. static const JSCFunctionListEntry js_map_iterator_proto_funcs[] = {
  54951. JS_ITERATOR_NEXT_DEF("next", 0, js_map_iterator_next, 0 ),
  54952. JS_PROP_STRING_DEF("[Symbol.toStringTag]", "Map Iterator", JS_PROP_CONFIGURABLE ),
  54953. };
  54954. static const JSCFunctionListEntry js_set_proto_funcs[] = {
  54955. JS_CFUNC_MAGIC_DEF("add", 1, js_map_set, MAGIC_SET ),
  54956. JS_CFUNC_MAGIC_DEF("has", 1, js_map_has, MAGIC_SET ),
  54957. JS_CFUNC_MAGIC_DEF("delete", 1, js_map_delete, MAGIC_SET ),
  54958. JS_CFUNC_MAGIC_DEF("clear", 0, js_map_clear, MAGIC_SET ),
  54959. JS_CGETSET_MAGIC_DEF("size", js_map_get_size, NULL, MAGIC_SET ),
  54960. JS_CFUNC_MAGIC_DEF("forEach", 1, js_map_forEach, MAGIC_SET ),
  54961. JS_CFUNC_DEF("isDisjointFrom", 1, js_set_isDisjointFrom ),
  54962. JS_CFUNC_DEF("isSubsetOf", 1, js_set_isSubsetOf ),
  54963. JS_CFUNC_DEF("isSupersetOf", 1, js_set_isSupersetOf ),
  54964. JS_CFUNC_DEF("intersection", 1, js_set_intersection ),
  54965. JS_CFUNC_DEF("difference", 1, js_set_difference ),
  54966. JS_CFUNC_DEF("symmetricDifference", 1, js_set_symmetricDifference ),
  54967. JS_CFUNC_DEF("union", 1, js_set_union ),
  54968. JS_CFUNC_MAGIC_DEF("values", 0, js_create_map_iterator, (JS_ITERATOR_KIND_KEY << 2) | MAGIC_SET ),
  54969. JS_ALIAS_DEF("keys", "values" ),
  54970. JS_ALIAS_DEF("[Symbol.iterator]", "values" ),
  54971. JS_CFUNC_MAGIC_DEF("entries", 0, js_create_map_iterator, (JS_ITERATOR_KIND_KEY_AND_VALUE << 2) | MAGIC_SET ),
  54972. JS_PROP_STRING_DEF("[Symbol.toStringTag]", "Set", JS_PROP_CONFIGURABLE ),
  54973. };
  54974. static const JSCFunctionListEntry js_set_iterator_proto_funcs[] = {
  54975. JS_ITERATOR_NEXT_DEF("next", 0, js_map_iterator_next, MAGIC_SET ),
  54976. JS_PROP_STRING_DEF("[Symbol.toStringTag]", "Set Iterator", JS_PROP_CONFIGURABLE ),
  54977. };
  54978. static const JSCFunctionListEntry js_weak_map_proto_funcs[] = {
  54979. JS_CFUNC_MAGIC_DEF("set", 2, js_map_set, MAGIC_WEAK ),
  54980. JS_CFUNC_MAGIC_DEF("get", 1, js_map_get, MAGIC_WEAK ),
  54981. JS_CFUNC_MAGIC_DEF("has", 1, js_map_has, MAGIC_WEAK ),
  54982. JS_CFUNC_MAGIC_DEF("delete", 1, js_map_delete, MAGIC_WEAK ),
  54983. JS_PROP_STRING_DEF("[Symbol.toStringTag]", "WeakMap", JS_PROP_CONFIGURABLE ),
  54984. };
  54985. static const JSCFunctionListEntry js_weak_set_proto_funcs[] = {
  54986. JS_CFUNC_MAGIC_DEF("add", 1, js_map_set, MAGIC_SET | MAGIC_WEAK ),
  54987. JS_CFUNC_MAGIC_DEF("has", 1, js_map_has, MAGIC_SET | MAGIC_WEAK ),
  54988. JS_CFUNC_MAGIC_DEF("delete", 1, js_map_delete, MAGIC_SET | MAGIC_WEAK ),
  54989. JS_PROP_STRING_DEF("[Symbol.toStringTag]", "WeakSet", JS_PROP_CONFIGURABLE ),
  54990. };
  54991. static const JSCFunctionListEntry * const js_map_proto_funcs_ptr[6] = {
  54992. js_map_proto_funcs,
  54993. js_set_proto_funcs,
  54994. js_weak_map_proto_funcs,
  54995. js_weak_set_proto_funcs,
  54996. js_map_iterator_proto_funcs,
  54997. js_set_iterator_proto_funcs,
  54998. };
  54999. static const uint8_t js_map_proto_funcs_count[6] = {
  55000. countof(js_map_proto_funcs),
  55001. countof(js_set_proto_funcs),
  55002. countof(js_weak_map_proto_funcs),
  55003. countof(js_weak_set_proto_funcs),
  55004. countof(js_map_iterator_proto_funcs),
  55005. countof(js_set_iterator_proto_funcs),
  55006. };
  55007. void JS_AddIntrinsicMapSet(JSContext *ctx)
  55008. {
  55009. int i;
  55010. JSValue obj1;
  55011. char buf[ATOM_GET_STR_BUF_SIZE];
  55012. for(i = 0; i < 4; i++) {
  55013. const char *name = JS_AtomGetStr(ctx, buf, sizeof(buf),
  55014. JS_ATOM_Map + i);
  55015. int class_id = JS_CLASS_MAP + i;
  55016. ctx->class_proto[class_id] = JS_NewObject(ctx);
  55017. JS_SetPropertyFunctionList(ctx, ctx->class_proto[class_id],
  55018. js_map_proto_funcs_ptr[i],
  55019. js_map_proto_funcs_count[i]);
  55020. obj1 = JS_NewCFunctionMagic(ctx, js_map_constructor, name, 0,
  55021. JS_CFUNC_constructor_magic, i);
  55022. if (class_id == JS_CLASS_MAP)
  55023. JS_SetPropertyFunctionList(ctx, obj1, js_map_funcs, countof(js_map_funcs));
  55024. else if (class_id == JS_CLASS_SET)
  55025. JS_SetPropertyFunctionList(ctx, obj1, js_set_funcs, countof(js_set_funcs));
  55026. JS_NewGlobalCConstructor2(ctx, obj1, name, ctx->class_proto[class_id]);
  55027. }
  55028. for(i = 0; i < 2; i++) {
  55029. ctx->class_proto[JS_CLASS_MAP_ITERATOR + i] =
  55030. JS_NewObjectProto(ctx, ctx->class_proto[JS_CLASS_ITERATOR]);
  55031. JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_MAP_ITERATOR + i],
  55032. js_map_proto_funcs_ptr[i + 4],
  55033. js_map_proto_funcs_count[i + 4]);
  55034. }
  55035. }
  55036. /* Generator */
  55037. static const JSCFunctionListEntry js_generator_function_proto_funcs[] = {
  55038. JS_PROP_STRING_DEF("[Symbol.toStringTag]", "GeneratorFunction", JS_PROP_CONFIGURABLE),
  55039. };
  55040. static const JSCFunctionListEntry js_generator_proto_funcs[] = {
  55041. JS_ITERATOR_NEXT_DEF("next", 1, js_generator_next, GEN_MAGIC_NEXT ),
  55042. JS_ITERATOR_NEXT_DEF("return", 1, js_generator_next, GEN_MAGIC_RETURN ),
  55043. JS_ITERATOR_NEXT_DEF("throw", 1, js_generator_next, GEN_MAGIC_THROW ),
  55044. JS_PROP_STRING_DEF("[Symbol.toStringTag]", "Generator", JS_PROP_CONFIGURABLE),
  55045. };
  55046. /* Promise */
  55047. typedef struct JSPromiseData {
  55048. JSPromiseStateEnum promise_state;
  55049. /* 0=fulfill, 1=reject, list of JSPromiseReactionData.link */
  55050. struct list_head promise_reactions[2];
  55051. bool is_handled; /* Note: only useful to debug */
  55052. JSValue promise_result;
  55053. } JSPromiseData;
  55054. typedef struct JSPromiseFunctionDataResolved {
  55055. int ref_count;
  55056. bool already_resolved;
  55057. } JSPromiseFunctionDataResolved;
  55058. typedef struct JSPromiseFunctionData {
  55059. JSValue promise;
  55060. JSPromiseFunctionDataResolved *presolved;
  55061. } JSPromiseFunctionData;
  55062. typedef struct JSPromiseReactionData {
  55063. struct list_head link; /* not used in promise_reaction_job */
  55064. JSValue resolving_funcs[2];
  55065. JSValue handler;
  55066. } JSPromiseReactionData;
  55067. JSPromiseStateEnum JS_PromiseState(JSContext *ctx, JSValueConst promise)
  55068. {
  55069. JSPromiseData *s = JS_GetOpaque(promise, JS_CLASS_PROMISE);
  55070. if (!s)
  55071. return -1;
  55072. return s->promise_state;
  55073. }
  55074. JSValue JS_PromiseResult(JSContext *ctx, JSValueConst promise)
  55075. {
  55076. JSPromiseData *s = JS_GetOpaque(promise, JS_CLASS_PROMISE);
  55077. if (!s)
  55078. return JS_UNDEFINED;
  55079. return js_dup(s->promise_result);
  55080. }
  55081. bool JS_IsPromise(JSValueConst val)
  55082. {
  55083. if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT)
  55084. return false;
  55085. return JS_VALUE_GET_OBJ(val)->class_id == JS_CLASS_PROMISE;
  55086. }
  55087. static int js_create_resolving_functions(JSContext *ctx, JSValue *args,
  55088. JSValueConst promise);
  55089. static void promise_reaction_data_free(JSRuntime *rt,
  55090. JSPromiseReactionData *rd)
  55091. {
  55092. JS_FreeValueRT(rt, rd->resolving_funcs[0]);
  55093. JS_FreeValueRT(rt, rd->resolving_funcs[1]);
  55094. JS_FreeValueRT(rt, rd->handler);
  55095. js_free_rt(rt, rd);
  55096. }
  55097. #ifdef ENABLE_DUMPS // JS_DUMP_PROMISE
  55098. #define promise_trace(ctx, ...) \
  55099. do { \
  55100. if (check_dump_flag(ctx->rt, JS_DUMP_PROMISE)) \
  55101. printf(__VA_ARGS__); \
  55102. } while (0)
  55103. #else
  55104. #define promise_trace(...)
  55105. #endif
  55106. static JSValue promise_reaction_job(JSContext *ctx, int argc,
  55107. JSValueConst *argv)
  55108. {
  55109. JSValueConst handler, func;
  55110. JSValue res, res2;
  55111. JSValueConst arg;
  55112. bool is_reject;
  55113. assert(argc == 5);
  55114. handler = argv[2];
  55115. is_reject = JS_ToBool(ctx, argv[3]);
  55116. arg = argv[4];
  55117. promise_trace(ctx, "promise_reaction_job: is_reject=%d\n", is_reject);
  55118. if (JS_IsUndefined(handler)) {
  55119. if (is_reject) {
  55120. res = JS_Throw(ctx, js_dup(arg));
  55121. } else {
  55122. res = js_dup(arg);
  55123. }
  55124. } else {
  55125. res = JS_Call(ctx, handler, JS_UNDEFINED, 1, &arg);
  55126. }
  55127. is_reject = JS_IsException(res);
  55128. if (is_reject) {
  55129. if (unlikely(JS_IsUncatchableError(ctx, ctx->rt->current_exception)))
  55130. return JS_EXCEPTION;
  55131. res = JS_GetException(ctx);
  55132. }
  55133. func = argv[is_reject];
  55134. /* as an extension, we support undefined as value to avoid
  55135. creating a dummy promise in the 'await' implementation of async
  55136. functions */
  55137. if (!JS_IsUndefined(func)) {
  55138. res2 = JS_Call(ctx, func, JS_UNDEFINED, 1, vc(&res));
  55139. } else {
  55140. res2 = JS_UNDEFINED;
  55141. }
  55142. JS_FreeValue(ctx, res);
  55143. return res2;
  55144. }
  55145. void JS_SetHostPromiseRejectionTracker(JSRuntime *rt,
  55146. JSHostPromiseRejectionTracker *cb,
  55147. void *opaque)
  55148. {
  55149. rt->host_promise_rejection_tracker = cb;
  55150. rt->host_promise_rejection_tracker_opaque = opaque;
  55151. }
  55152. static void fulfill_or_reject_promise(JSContext *ctx, JSValueConst promise,
  55153. JSValueConst value, bool is_reject)
  55154. {
  55155. JSPromiseData *s = JS_GetOpaque(promise, JS_CLASS_PROMISE);
  55156. struct list_head *el, *el1;
  55157. JSPromiseReactionData *rd;
  55158. JSValueConst args[5];
  55159. if (!s || s->promise_state != JS_PROMISE_PENDING)
  55160. return; /* should never happen */
  55161. set_value(ctx, &s->promise_result, js_dup(value));
  55162. s->promise_state = JS_PROMISE_FULFILLED + is_reject;
  55163. promise_trace(ctx, "fulfill_or_reject_promise: is_reject=%d\n", is_reject);
  55164. if (s->promise_state == JS_PROMISE_REJECTED && !s->is_handled) {
  55165. JSRuntime *rt = ctx->rt;
  55166. if (rt->host_promise_rejection_tracker) {
  55167. rt->host_promise_rejection_tracker(ctx, promise, value, false,
  55168. rt->host_promise_rejection_tracker_opaque);
  55169. }
  55170. }
  55171. list_for_each_safe(el, el1, &s->promise_reactions[is_reject]) {
  55172. rd = list_entry(el, JSPromiseReactionData, link);
  55173. args[0] = rd->resolving_funcs[0];
  55174. args[1] = rd->resolving_funcs[1];
  55175. args[2] = rd->handler;
  55176. args[3] = js_bool(is_reject);
  55177. args[4] = value;
  55178. JS_EnqueueJob(ctx, promise_reaction_job, 5, args);
  55179. list_del(&rd->link);
  55180. promise_reaction_data_free(ctx->rt, rd);
  55181. }
  55182. list_for_each_safe(el, el1, &s->promise_reactions[1 - is_reject]) {
  55183. rd = list_entry(el, JSPromiseReactionData, link);
  55184. list_del(&rd->link);
  55185. promise_reaction_data_free(ctx->rt, rd);
  55186. }
  55187. }
  55188. static void reject_promise(JSContext *ctx, JSValueConst promise,
  55189. JSValueConst value)
  55190. {
  55191. fulfill_or_reject_promise(ctx, promise, value, true);
  55192. }
  55193. static JSValue js_promise_resolve_thenable_job(JSContext *ctx,
  55194. int argc, JSValueConst *argv)
  55195. {
  55196. JSValueConst promise, thenable, then;
  55197. JSValue args[2], res;
  55198. promise_trace(ctx, "js_promise_resolve_thenable_job\n");
  55199. assert(argc == 3);
  55200. promise = argv[0];
  55201. thenable = argv[1];
  55202. then = argv[2];
  55203. if (js_create_resolving_functions(ctx, args, promise) < 0)
  55204. return JS_EXCEPTION;
  55205. res = JS_Call(ctx, then, thenable, 2, vc(args));
  55206. if (JS_IsException(res)) {
  55207. JSValue error = JS_GetException(ctx);
  55208. res = JS_Call(ctx, args[1], JS_UNDEFINED, 1, vc(&error));
  55209. JS_FreeValue(ctx, error);
  55210. }
  55211. JS_FreeValue(ctx, args[0]);
  55212. JS_FreeValue(ctx, args[1]);
  55213. return res;
  55214. }
  55215. static void js_promise_resolve_function_free_resolved(JSRuntime *rt,
  55216. JSPromiseFunctionDataResolved *sr)
  55217. {
  55218. if (--sr->ref_count == 0) {
  55219. js_free_rt(rt, sr);
  55220. }
  55221. }
  55222. static int js_create_resolving_functions(JSContext *ctx,
  55223. JSValue *resolving_funcs,
  55224. JSValueConst promise)
  55225. {
  55226. JSValue obj;
  55227. JSPromiseFunctionData *s;
  55228. JSPromiseFunctionDataResolved *sr;
  55229. int i, ret;
  55230. sr = js_malloc(ctx, sizeof(*sr));
  55231. if (!sr)
  55232. return -1;
  55233. sr->ref_count = 1;
  55234. sr->already_resolved = false; /* must be shared between the two functions */
  55235. ret = 0;
  55236. for(i = 0; i < 2; i++) {
  55237. obj = JS_NewObjectProtoClass(ctx, ctx->function_proto,
  55238. JS_CLASS_PROMISE_RESOLVE_FUNCTION + i);
  55239. if (JS_IsException(obj))
  55240. goto fail;
  55241. s = js_malloc(ctx, sizeof(*s));
  55242. if (!s) {
  55243. JS_FreeValue(ctx, obj);
  55244. fail:
  55245. if (i != 0)
  55246. JS_FreeValue(ctx, resolving_funcs[0]);
  55247. ret = -1;
  55248. break;
  55249. }
  55250. sr->ref_count++;
  55251. s->presolved = sr;
  55252. s->promise = js_dup(promise);
  55253. JS_SetOpaqueInternal(obj, s);
  55254. js_function_set_properties(ctx, obj, JS_ATOM_empty_string, 1);
  55255. resolving_funcs[i] = obj;
  55256. }
  55257. js_promise_resolve_function_free_resolved(ctx->rt, sr);
  55258. return ret;
  55259. }
  55260. static void js_promise_resolve_function_finalizer(JSRuntime *rt,
  55261. JSValueConst val)
  55262. {
  55263. JSPromiseFunctionData *s = JS_VALUE_GET_OBJ(val)->u.promise_function_data;
  55264. if (s) {
  55265. js_promise_resolve_function_free_resolved(rt, s->presolved);
  55266. JS_FreeValueRT(rt, s->promise);
  55267. js_free_rt(rt, s);
  55268. }
  55269. }
  55270. static void js_promise_resolve_function_mark(JSRuntime *rt, JSValueConst val,
  55271. JS_MarkFunc *mark_func)
  55272. {
  55273. JSPromiseFunctionData *s = JS_VALUE_GET_OBJ(val)->u.promise_function_data;
  55274. if (s) {
  55275. JS_MarkValue(rt, s->promise, mark_func);
  55276. }
  55277. }
  55278. static JSValue js_promise_resolve_function_call(JSContext *ctx,
  55279. JSValueConst func_obj,
  55280. JSValueConst this_val,
  55281. int argc, JSValueConst *argv,
  55282. int flags)
  55283. {
  55284. JSObject *p = JS_VALUE_GET_OBJ(func_obj);
  55285. JSPromiseFunctionData *s;
  55286. JSValueConst args[3];
  55287. JSValueConst resolution;
  55288. JSValue then;
  55289. bool is_reject;
  55290. s = p->u.promise_function_data;
  55291. if (!s || s->presolved->already_resolved)
  55292. return JS_UNDEFINED;
  55293. s->presolved->already_resolved = true;
  55294. is_reject = p->class_id - JS_CLASS_PROMISE_RESOLVE_FUNCTION;
  55295. if (argc > 0)
  55296. resolution = argv[0];
  55297. else
  55298. resolution = JS_UNDEFINED;
  55299. #ifdef ENABLE_DUMPS // JS_DUMP_PROMISE
  55300. if (check_dump_flag(ctx->rt, JS_DUMP_PROMISE)) {
  55301. printf("js_promise_resolving_function_call: is_reject=%d resolution=", is_reject);
  55302. JS_DumpValue(ctx->rt, resolution);
  55303. printf("\n");
  55304. }
  55305. #endif
  55306. if (is_reject || !JS_IsObject(resolution)) {
  55307. goto done;
  55308. } else if (js_same_value(ctx, resolution, s->promise)) {
  55309. JS_ThrowTypeError(ctx, "promise self resolution");
  55310. goto fail_reject;
  55311. }
  55312. then = JS_GetProperty(ctx, resolution, JS_ATOM_then);
  55313. if (JS_IsException(then)) {
  55314. JSValue error;
  55315. fail_reject:
  55316. error = JS_GetException(ctx);
  55317. reject_promise(ctx, s->promise, error);
  55318. JS_FreeValue(ctx, error);
  55319. } else if (!JS_IsFunction(ctx, then)) {
  55320. JS_FreeValue(ctx, then);
  55321. done:
  55322. fulfill_or_reject_promise(ctx, s->promise, resolution, is_reject);
  55323. } else {
  55324. args[0] = s->promise;
  55325. args[1] = resolution;
  55326. args[2] = then;
  55327. JS_EnqueueJob(ctx, js_promise_resolve_thenable_job, 3, args);
  55328. JS_FreeValue(ctx, then);
  55329. }
  55330. return JS_UNDEFINED;
  55331. }
  55332. static void js_promise_finalizer(JSRuntime *rt, JSValueConst val)
  55333. {
  55334. JSPromiseData *s = JS_GetOpaque(val, JS_CLASS_PROMISE);
  55335. struct list_head *el, *el1;
  55336. int i;
  55337. if (!s)
  55338. return;
  55339. for(i = 0; i < 2; i++) {
  55340. list_for_each_safe(el, el1, &s->promise_reactions[i]) {
  55341. JSPromiseReactionData *rd =
  55342. list_entry(el, JSPromiseReactionData, link);
  55343. promise_reaction_data_free(rt, rd);
  55344. }
  55345. }
  55346. JS_FreeValueRT(rt, s->promise_result);
  55347. js_free_rt(rt, s);
  55348. }
  55349. static void js_promise_mark(JSRuntime *rt, JSValueConst val,
  55350. JS_MarkFunc *mark_func)
  55351. {
  55352. JSPromiseData *s = JS_GetOpaque(val, JS_CLASS_PROMISE);
  55353. struct list_head *el;
  55354. int i;
  55355. if (!s)
  55356. return;
  55357. for(i = 0; i < 2; i++) {
  55358. list_for_each(el, &s->promise_reactions[i]) {
  55359. JSPromiseReactionData *rd =
  55360. list_entry(el, JSPromiseReactionData, link);
  55361. JS_MarkValue(rt, rd->resolving_funcs[0], mark_func);
  55362. JS_MarkValue(rt, rd->resolving_funcs[1], mark_func);
  55363. JS_MarkValue(rt, rd->handler, mark_func);
  55364. }
  55365. }
  55366. JS_MarkValue(rt, s->promise_result, mark_func);
  55367. }
  55368. static JSValue js_promise_constructor(JSContext *ctx, JSValueConst new_target,
  55369. int argc, JSValueConst *argv)
  55370. {
  55371. JSValueConst executor;
  55372. JSValue obj;
  55373. JSPromiseData *s;
  55374. JSValue args[2], ret;
  55375. int i;
  55376. executor = argv[0];
  55377. if (check_function(ctx, executor))
  55378. return JS_EXCEPTION;
  55379. obj = js_create_from_ctor(ctx, new_target, JS_CLASS_PROMISE);
  55380. if (JS_IsException(obj))
  55381. return JS_EXCEPTION;
  55382. s = js_mallocz(ctx, sizeof(*s));
  55383. if (!s)
  55384. goto fail;
  55385. s->promise_state = JS_PROMISE_PENDING;
  55386. s->is_handled = false;
  55387. for(i = 0; i < 2; i++)
  55388. init_list_head(&s->promise_reactions[i]);
  55389. s->promise_result = JS_UNDEFINED;
  55390. JS_SetOpaqueInternal(obj, s);
  55391. if (js_create_resolving_functions(ctx, args, obj))
  55392. goto fail;
  55393. ret = JS_Call(ctx, executor, JS_UNDEFINED, 2, vc(args));
  55394. if (JS_IsException(ret)) {
  55395. JSValue ret2, error;
  55396. error = JS_GetException(ctx);
  55397. ret2 = JS_Call(ctx, args[1], JS_UNDEFINED, 1, vc(&error));
  55398. JS_FreeValue(ctx, error);
  55399. if (JS_IsException(ret2))
  55400. goto fail1;
  55401. JS_FreeValue(ctx, ret2);
  55402. }
  55403. JS_FreeValue(ctx, ret);
  55404. JS_FreeValue(ctx, args[0]);
  55405. JS_FreeValue(ctx, args[1]);
  55406. return obj;
  55407. fail1:
  55408. JS_FreeValue(ctx, args[0]);
  55409. JS_FreeValue(ctx, args[1]);
  55410. fail:
  55411. JS_FreeValue(ctx, obj);
  55412. return JS_EXCEPTION;
  55413. }
  55414. static JSValue js_promise_executor(JSContext *ctx,
  55415. JSValueConst this_val,
  55416. int argc, JSValueConst *argv,
  55417. int magic, JSValueConst *func_data)
  55418. {
  55419. int i;
  55420. for(i = 0; i < 2; i++) {
  55421. if (!JS_IsUndefined(func_data[i]))
  55422. return JS_ThrowTypeError(ctx, "resolving function already set");
  55423. func_data[i] = js_dup(argv[i]);
  55424. }
  55425. return JS_UNDEFINED;
  55426. }
  55427. static JSValue js_promise_executor_new(JSContext *ctx)
  55428. {
  55429. JSValueConst func_data[2];
  55430. func_data[0] = JS_UNDEFINED;
  55431. func_data[1] = JS_UNDEFINED;
  55432. return JS_NewCFunctionData(ctx, js_promise_executor, 2,
  55433. 0, 2, func_data);
  55434. }
  55435. static JSValue js_new_promise_capability(JSContext *ctx,
  55436. JSValue *resolving_funcs,
  55437. JSValueConst ctor)
  55438. {
  55439. JSValue executor, result_promise;
  55440. JSCFunctionDataRecord *s;
  55441. int i;
  55442. executor = js_promise_executor_new(ctx);
  55443. if (JS_IsException(executor))
  55444. return executor;
  55445. if (JS_IsUndefined(ctor)) {
  55446. result_promise = js_promise_constructor(ctx, ctor, 1, vc(&executor));
  55447. } else {
  55448. result_promise = JS_CallConstructor(ctx, ctor, 1, vc(&executor));
  55449. }
  55450. if (JS_IsException(result_promise))
  55451. goto fail;
  55452. s = JS_GetOpaque(executor, JS_CLASS_C_FUNCTION_DATA);
  55453. for(i = 0; i < 2; i++) {
  55454. if (check_function(ctx, s->data[i]))
  55455. goto fail;
  55456. }
  55457. for(i = 0; i < 2; i++)
  55458. resolving_funcs[i] = js_dup(s->data[i]);
  55459. JS_FreeValue(ctx, executor);
  55460. return result_promise;
  55461. fail:
  55462. JS_FreeValue(ctx, executor);
  55463. JS_FreeValue(ctx, result_promise);
  55464. return JS_EXCEPTION;
  55465. }
  55466. JSValue JS_NewPromiseCapability(JSContext *ctx, JSValue *resolving_funcs)
  55467. {
  55468. return js_new_promise_capability(ctx, resolving_funcs, JS_UNDEFINED);
  55469. }
  55470. static JSValue js_promise_resolve(JSContext *ctx, JSValueConst this_val,
  55471. int argc, JSValueConst *argv, int magic)
  55472. {
  55473. JSValue result_promise, resolving_funcs[2], ret;
  55474. bool is_reject = magic;
  55475. if (!JS_IsObject(this_val))
  55476. return JS_ThrowTypeErrorNotAnObject(ctx);
  55477. if (!is_reject && JS_GetOpaque(argv[0], JS_CLASS_PROMISE)) {
  55478. JSValue ctor;
  55479. bool is_same;
  55480. ctor = JS_GetProperty(ctx, argv[0], JS_ATOM_constructor);
  55481. if (JS_IsException(ctor))
  55482. return ctor;
  55483. is_same = js_same_value(ctx, ctor, this_val);
  55484. JS_FreeValue(ctx, ctor);
  55485. if (is_same)
  55486. return js_dup(argv[0]);
  55487. }
  55488. result_promise = js_new_promise_capability(ctx, resolving_funcs, this_val);
  55489. if (JS_IsException(result_promise))
  55490. return result_promise;
  55491. ret = JS_Call(ctx, resolving_funcs[is_reject], JS_UNDEFINED, 1, argv);
  55492. JS_FreeValue(ctx, resolving_funcs[0]);
  55493. JS_FreeValue(ctx, resolving_funcs[1]);
  55494. if (JS_IsException(ret)) {
  55495. JS_FreeValue(ctx, result_promise);
  55496. return ret;
  55497. }
  55498. JS_FreeValue(ctx, ret);
  55499. return result_promise;
  55500. }
  55501. static JSValue js_promise_withResolvers(JSContext *ctx, JSValueConst this_val,
  55502. int argc, JSValueConst *argv)
  55503. {
  55504. JSValue result_promise, resolving_funcs[2], obj;
  55505. if (!JS_IsObject(this_val))
  55506. return JS_ThrowTypeErrorNotAnObject(ctx);
  55507. result_promise = js_new_promise_capability(ctx, resolving_funcs, this_val);
  55508. if (JS_IsException(result_promise))
  55509. return JS_EXCEPTION;
  55510. obj = JS_NewObject(ctx);
  55511. if (JS_IsException(obj)) {
  55512. JS_FreeValue(ctx, resolving_funcs[0]);
  55513. JS_FreeValue(ctx, resolving_funcs[1]);
  55514. JS_FreeValue(ctx, result_promise);
  55515. return JS_EXCEPTION;
  55516. }
  55517. JS_DefinePropertyValue(ctx, obj, JS_ATOM_promise, result_promise, JS_PROP_C_W_E);
  55518. JS_DefinePropertyValue(ctx, obj, JS_ATOM_resolve, resolving_funcs[0], JS_PROP_C_W_E);
  55519. JS_DefinePropertyValue(ctx, obj, JS_ATOM_reject, resolving_funcs[1], JS_PROP_C_W_E);
  55520. return obj;
  55521. }
  55522. static JSValue js_promise_try(JSContext *ctx, JSValueConst this_val,
  55523. int argc, JSValueConst *argv)
  55524. {
  55525. JSValue result_promise, resolving_funcs[2], ret, ret2;
  55526. bool is_reject = 0;
  55527. if (!JS_IsObject(this_val))
  55528. return JS_ThrowTypeErrorNotAnObject(ctx);
  55529. result_promise = js_new_promise_capability(ctx, resolving_funcs, this_val);
  55530. if (JS_IsException(result_promise))
  55531. return result_promise;
  55532. ret = JS_Call(ctx, argv[0], JS_UNDEFINED, argc - 1, argv + 1);
  55533. if (JS_IsException(ret)) {
  55534. is_reject = 1;
  55535. ret = JS_GetException(ctx);
  55536. }
  55537. ret2 = JS_Call(ctx, resolving_funcs[is_reject], JS_UNDEFINED, 1, vc(&ret));
  55538. JS_FreeValue(ctx, resolving_funcs[0]);
  55539. JS_FreeValue(ctx, resolving_funcs[1]);
  55540. JS_FreeValue(ctx, ret);
  55541. if (JS_IsException(ret2)) {
  55542. JS_FreeValue(ctx, result_promise);
  55543. return ret2;
  55544. }
  55545. JS_FreeValue(ctx, ret2);
  55546. return result_promise;
  55547. }
  55548. static __exception int remainingElementsCount_add(JSContext *ctx,
  55549. JSValueConst resolve_element_env,
  55550. int addend)
  55551. {
  55552. JSValue val;
  55553. int remainingElementsCount;
  55554. val = JS_GetPropertyUint32(ctx, resolve_element_env, 0);
  55555. if (JS_IsException(val))
  55556. return -1;
  55557. if (JS_ToInt32Free(ctx, &remainingElementsCount, val))
  55558. return -1;
  55559. remainingElementsCount += addend;
  55560. if (JS_SetPropertyUint32(ctx, resolve_element_env, 0,
  55561. js_int32(remainingElementsCount)) < 0)
  55562. return -1;
  55563. return (remainingElementsCount == 0);
  55564. }
  55565. #define PROMISE_MAGIC_all 0
  55566. #define PROMISE_MAGIC_allSettled 1
  55567. #define PROMISE_MAGIC_any 2
  55568. static JSValue js_promise_all_resolve_element(JSContext *ctx,
  55569. JSValueConst this_val,
  55570. int argc, JSValueConst *argv,
  55571. int magic,
  55572. JSValueConst *func_data)
  55573. {
  55574. int resolve_type = magic & 3;
  55575. int is_reject = magic & 4;
  55576. bool alreadyCalled = JS_ToBool(ctx, func_data[0]);
  55577. JSValueConst values = func_data[2];
  55578. JSValueConst resolve = func_data[3];
  55579. JSValueConst resolve_element_env = func_data[4];
  55580. JSValue ret, obj;
  55581. int is_zero, index;
  55582. if (JS_ToInt32(ctx, &index, func_data[1]))
  55583. return JS_EXCEPTION;
  55584. if (alreadyCalled)
  55585. return JS_UNDEFINED;
  55586. func_data[0] = JS_TRUE;
  55587. if (resolve_type == PROMISE_MAGIC_allSettled) {
  55588. JSValue str;
  55589. obj = JS_NewObject(ctx);
  55590. if (JS_IsException(obj))
  55591. return JS_EXCEPTION;
  55592. str = js_new_string8(ctx, is_reject ? "rejected" : "fulfilled");
  55593. if (JS_IsException(str))
  55594. goto fail1;
  55595. if (JS_DefinePropertyValue(ctx, obj, JS_ATOM_status,
  55596. str,
  55597. JS_PROP_C_W_E) < 0)
  55598. goto fail1;
  55599. if (JS_DefinePropertyValue(ctx, obj,
  55600. is_reject ? JS_ATOM_reason : JS_ATOM_value,
  55601. js_dup(argv[0]),
  55602. JS_PROP_C_W_E) < 0) {
  55603. fail1:
  55604. JS_FreeValue(ctx, obj);
  55605. return JS_EXCEPTION;
  55606. }
  55607. } else {
  55608. obj = js_dup(argv[0]);
  55609. }
  55610. if (JS_DefinePropertyValueUint32(ctx, values, index,
  55611. obj, JS_PROP_C_W_E) < 0)
  55612. return JS_EXCEPTION;
  55613. is_zero = remainingElementsCount_add(ctx, resolve_element_env, -1);
  55614. if (is_zero < 0)
  55615. return JS_EXCEPTION;
  55616. if (is_zero) {
  55617. if (resolve_type == PROMISE_MAGIC_any) {
  55618. JSValue error;
  55619. error = js_aggregate_error_constructor(ctx, values);
  55620. if (JS_IsException(error))
  55621. return JS_EXCEPTION;
  55622. ret = JS_Call(ctx, resolve, JS_UNDEFINED, 1, vc(&error));
  55623. JS_FreeValue(ctx, error);
  55624. } else {
  55625. ret = JS_Call(ctx, resolve, JS_UNDEFINED, 1, &values);
  55626. }
  55627. if (JS_IsException(ret))
  55628. return ret;
  55629. JS_FreeValue(ctx, ret);
  55630. }
  55631. return JS_UNDEFINED;
  55632. }
  55633. /* magic = 0: Promise.all 1: Promise.allSettled */
  55634. static JSValue js_promise_all(JSContext *ctx, JSValueConst this_val,
  55635. int argc, JSValueConst *argv, int magic)
  55636. {
  55637. JSValue result_promise, resolving_funcs[2], item, next_promise, ret;
  55638. JSValue next_method = JS_UNDEFINED, values = JS_UNDEFINED;
  55639. JSValue resolve_element_env = JS_UNDEFINED, resolve_element, reject_element;
  55640. JSValue promise_resolve = JS_UNDEFINED, iter = JS_UNDEFINED;
  55641. JSValueConst then_args[2], resolve_element_data[5];
  55642. int done, index, is_zero, is_promise_any = (magic == PROMISE_MAGIC_any);
  55643. if (!JS_IsObject(this_val))
  55644. return JS_ThrowTypeErrorNotAnObject(ctx);
  55645. result_promise = js_new_promise_capability(ctx, resolving_funcs, this_val);
  55646. if (JS_IsException(result_promise))
  55647. return result_promise;
  55648. promise_resolve = JS_GetProperty(ctx, this_val, JS_ATOM_resolve);
  55649. if (JS_IsException(promise_resolve) ||
  55650. check_function(ctx, promise_resolve))
  55651. goto fail_reject;
  55652. iter = JS_GetIterator(ctx, argv[0], false);
  55653. if (JS_IsException(iter)) {
  55654. JSValue error;
  55655. fail_reject:
  55656. error = JS_GetException(ctx);
  55657. ret = JS_Call(ctx, resolving_funcs[1], JS_UNDEFINED, 1, vc(&error));
  55658. JS_FreeValue(ctx, error);
  55659. if (JS_IsException(ret))
  55660. goto fail;
  55661. JS_FreeValue(ctx, ret);
  55662. } else {
  55663. next_method = JS_GetProperty(ctx, iter, JS_ATOM_next);
  55664. if (JS_IsException(next_method))
  55665. goto fail_reject;
  55666. values = JS_NewArray(ctx);
  55667. if (JS_IsException(values))
  55668. goto fail_reject;
  55669. resolve_element_env = JS_NewArray(ctx);
  55670. if (JS_IsException(resolve_element_env))
  55671. goto fail_reject;
  55672. /* remainingElementsCount field */
  55673. if (JS_DefinePropertyValueUint32(ctx, resolve_element_env, 0,
  55674. js_int32(1),
  55675. JS_PROP_CONFIGURABLE | JS_PROP_ENUMERABLE | JS_PROP_WRITABLE) < 0)
  55676. goto fail_reject;
  55677. index = 0;
  55678. for(;;) {
  55679. /* XXX: conformance: should close the iterator if error on 'done'
  55680. access, but not on 'value' access */
  55681. item = JS_IteratorNext(ctx, iter, next_method, 0, NULL, &done);
  55682. if (JS_IsException(item))
  55683. goto fail_reject;
  55684. if (done)
  55685. break;
  55686. next_promise = JS_Call(ctx, promise_resolve,
  55687. this_val, 1, vc(&item));
  55688. JS_FreeValue(ctx, item);
  55689. if (JS_IsException(next_promise)) {
  55690. fail_reject1:
  55691. JS_IteratorClose(ctx, iter, true);
  55692. goto fail_reject;
  55693. }
  55694. resolve_element_data[0] = JS_FALSE;
  55695. resolve_element_data[1] = js_int32(index);
  55696. resolve_element_data[2] = values;
  55697. resolve_element_data[3] = resolving_funcs[is_promise_any];
  55698. resolve_element_data[4] = resolve_element_env;
  55699. resolve_element =
  55700. JS_NewCFunctionData(ctx, js_promise_all_resolve_element, 1,
  55701. magic, 5, resolve_element_data);
  55702. if (JS_IsException(resolve_element)) {
  55703. JS_FreeValue(ctx, next_promise);
  55704. goto fail_reject1;
  55705. }
  55706. if (magic == PROMISE_MAGIC_allSettled) {
  55707. reject_element =
  55708. JS_NewCFunctionData(ctx, js_promise_all_resolve_element, 1,
  55709. magic | 4, 5, resolve_element_data);
  55710. if (JS_IsException(reject_element)) {
  55711. JS_FreeValue(ctx, next_promise);
  55712. goto fail_reject1;
  55713. }
  55714. } else if (magic == PROMISE_MAGIC_any) {
  55715. if (JS_DefinePropertyValueUint32(ctx, values, index,
  55716. JS_UNDEFINED, JS_PROP_C_W_E) < 0)
  55717. goto fail_reject1;
  55718. reject_element = resolve_element;
  55719. resolve_element = js_dup(resolving_funcs[0]);
  55720. } else {
  55721. reject_element = js_dup(resolving_funcs[1]);
  55722. }
  55723. if (remainingElementsCount_add(ctx, resolve_element_env, 1) < 0) {
  55724. JS_FreeValue(ctx, next_promise);
  55725. JS_FreeValue(ctx, resolve_element);
  55726. JS_FreeValue(ctx, reject_element);
  55727. goto fail_reject1;
  55728. }
  55729. then_args[0] = resolve_element;
  55730. then_args[1] = reject_element;
  55731. ret = JS_InvokeFree(ctx, next_promise, JS_ATOM_then, 2, then_args);
  55732. JS_FreeValue(ctx, resolve_element);
  55733. JS_FreeValue(ctx, reject_element);
  55734. if (check_exception_free(ctx, ret))
  55735. goto fail_reject1;
  55736. index++;
  55737. }
  55738. is_zero = remainingElementsCount_add(ctx, resolve_element_env, -1);
  55739. if (is_zero < 0)
  55740. goto fail_reject;
  55741. if (is_zero) {
  55742. if (magic == PROMISE_MAGIC_any) {
  55743. JSValue error;
  55744. error = js_aggregate_error_constructor(ctx, values);
  55745. if (JS_IsException(error))
  55746. goto fail_reject;
  55747. JS_FreeValue(ctx, values);
  55748. values = error;
  55749. }
  55750. ret = JS_Call(ctx, resolving_funcs[is_promise_any], JS_UNDEFINED,
  55751. 1, vc(&values));
  55752. if (check_exception_free(ctx, ret))
  55753. goto fail_reject;
  55754. }
  55755. }
  55756. done:
  55757. JS_FreeValue(ctx, promise_resolve);
  55758. JS_FreeValue(ctx, resolve_element_env);
  55759. JS_FreeValue(ctx, values);
  55760. JS_FreeValue(ctx, next_method);
  55761. JS_FreeValue(ctx, iter);
  55762. JS_FreeValue(ctx, resolving_funcs[0]);
  55763. JS_FreeValue(ctx, resolving_funcs[1]);
  55764. return result_promise;
  55765. fail:
  55766. JS_FreeValue(ctx, result_promise);
  55767. result_promise = JS_EXCEPTION;
  55768. goto done;
  55769. }
  55770. static JSValue js_promise_race(JSContext *ctx, JSValueConst this_val,
  55771. int argc, JSValueConst *argv)
  55772. {
  55773. JSValue result_promise, resolving_funcs[2], item, next_promise, ret;
  55774. JSValue next_method = JS_UNDEFINED, iter = JS_UNDEFINED;
  55775. JSValue promise_resolve = JS_UNDEFINED;
  55776. int done;
  55777. if (!JS_IsObject(this_val))
  55778. return JS_ThrowTypeErrorNotAnObject(ctx);
  55779. result_promise = js_new_promise_capability(ctx, resolving_funcs, this_val);
  55780. if (JS_IsException(result_promise))
  55781. return result_promise;
  55782. promise_resolve = JS_GetProperty(ctx, this_val, JS_ATOM_resolve);
  55783. if (JS_IsException(promise_resolve) ||
  55784. check_function(ctx, promise_resolve))
  55785. goto fail_reject;
  55786. iter = JS_GetIterator(ctx, argv[0], false);
  55787. if (JS_IsException(iter)) {
  55788. JSValue error;
  55789. fail_reject:
  55790. error = JS_GetException(ctx);
  55791. ret = JS_Call(ctx, resolving_funcs[1], JS_UNDEFINED, 1, vc(&error));
  55792. JS_FreeValue(ctx, error);
  55793. if (JS_IsException(ret))
  55794. goto fail;
  55795. JS_FreeValue(ctx, ret);
  55796. } else {
  55797. next_method = JS_GetProperty(ctx, iter, JS_ATOM_next);
  55798. if (JS_IsException(next_method))
  55799. goto fail_reject;
  55800. for(;;) {
  55801. /* XXX: conformance: should close the iterator if error on 'done'
  55802. access, but not on 'value' access */
  55803. item = JS_IteratorNext(ctx, iter, next_method, 0, NULL, &done);
  55804. if (JS_IsException(item))
  55805. goto fail_reject;
  55806. if (done)
  55807. break;
  55808. next_promise = JS_Call(ctx, promise_resolve,
  55809. this_val, 1, vc(&item));
  55810. JS_FreeValue(ctx, item);
  55811. if (JS_IsException(next_promise)) {
  55812. fail_reject1:
  55813. JS_IteratorClose(ctx, iter, true);
  55814. goto fail_reject;
  55815. }
  55816. ret = JS_InvokeFree(ctx, next_promise, JS_ATOM_then, 2,
  55817. vc(resolving_funcs));
  55818. if (check_exception_free(ctx, ret))
  55819. goto fail_reject1;
  55820. }
  55821. }
  55822. done:
  55823. JS_FreeValue(ctx, promise_resolve);
  55824. JS_FreeValue(ctx, next_method);
  55825. JS_FreeValue(ctx, iter);
  55826. JS_FreeValue(ctx, resolving_funcs[0]);
  55827. JS_FreeValue(ctx, resolving_funcs[1]);
  55828. return result_promise;
  55829. fail:
  55830. //JS_FreeValue(ctx, next_method); // why not???
  55831. JS_FreeValue(ctx, result_promise);
  55832. result_promise = JS_EXCEPTION;
  55833. goto done;
  55834. }
  55835. static __exception int perform_promise_then(JSContext *ctx,
  55836. JSValueConst promise,
  55837. JSValueConst *resolve_reject,
  55838. JSValueConst *cap_resolving_funcs)
  55839. {
  55840. JSPromiseData *s = JS_GetOpaque(promise, JS_CLASS_PROMISE);
  55841. JSPromiseReactionData *rd_array[2], *rd;
  55842. int i, j;
  55843. rd_array[0] = NULL;
  55844. rd_array[1] = NULL;
  55845. for(i = 0; i < 2; i++) {
  55846. JSValueConst handler;
  55847. rd = js_mallocz(ctx, sizeof(*rd));
  55848. if (!rd) {
  55849. if (i == 1)
  55850. promise_reaction_data_free(ctx->rt, rd_array[0]);
  55851. return -1;
  55852. }
  55853. for(j = 0; j < 2; j++)
  55854. rd->resolving_funcs[j] = js_dup(cap_resolving_funcs[j]);
  55855. handler = resolve_reject[i];
  55856. if (!JS_IsFunction(ctx, handler))
  55857. handler = JS_UNDEFINED;
  55858. rd->handler = js_dup(handler);
  55859. rd_array[i] = rd;
  55860. }
  55861. if (s->promise_state == JS_PROMISE_PENDING) {
  55862. for(i = 0; i < 2; i++)
  55863. list_add_tail(&rd_array[i]->link, &s->promise_reactions[i]);
  55864. } else {
  55865. JSValueConst args[5];
  55866. if (s->promise_state == JS_PROMISE_REJECTED && !s->is_handled) {
  55867. JSRuntime *rt = ctx->rt;
  55868. if (rt->host_promise_rejection_tracker) {
  55869. rt->host_promise_rejection_tracker(ctx, promise, s->promise_result,
  55870. true, rt->host_promise_rejection_tracker_opaque);
  55871. }
  55872. }
  55873. i = s->promise_state - JS_PROMISE_FULFILLED;
  55874. rd = rd_array[i];
  55875. args[0] = rd->resolving_funcs[0];
  55876. args[1] = rd->resolving_funcs[1];
  55877. args[2] = rd->handler;
  55878. args[3] = js_bool(i);
  55879. args[4] = s->promise_result;
  55880. JS_EnqueueJob(ctx, promise_reaction_job, 5, args);
  55881. for(i = 0; i < 2; i++)
  55882. promise_reaction_data_free(ctx->rt, rd_array[i]);
  55883. }
  55884. s->is_handled = true;
  55885. return 0;
  55886. }
  55887. static JSValue js_promise_then(JSContext *ctx, JSValueConst this_val,
  55888. int argc, JSValueConst *argv)
  55889. {
  55890. JSValue ctor, result_promise, resolving_funcs[2];
  55891. JSPromiseData *s;
  55892. int i, ret;
  55893. s = JS_GetOpaque2(ctx, this_val, JS_CLASS_PROMISE);
  55894. if (!s)
  55895. return JS_EXCEPTION;
  55896. ctor = JS_SpeciesConstructor(ctx, this_val, JS_UNDEFINED);
  55897. if (JS_IsException(ctor))
  55898. return ctor;
  55899. result_promise = js_new_promise_capability(ctx, resolving_funcs, ctor);
  55900. JS_FreeValue(ctx, ctor);
  55901. if (JS_IsException(result_promise))
  55902. return result_promise;
  55903. ret = perform_promise_then(ctx, this_val, argv, vc(resolving_funcs));
  55904. for(i = 0; i < 2; i++)
  55905. JS_FreeValue(ctx, resolving_funcs[i]);
  55906. if (ret) {
  55907. JS_FreeValue(ctx, result_promise);
  55908. return JS_EXCEPTION;
  55909. }
  55910. return result_promise;
  55911. }
  55912. static JSValue js_promise_catch(JSContext *ctx, JSValueConst this_val,
  55913. int argc, JSValueConst *argv)
  55914. {
  55915. JSValueConst args[2];
  55916. args[0] = JS_UNDEFINED;
  55917. args[1] = argv[0];
  55918. return JS_Invoke(ctx, this_val, JS_ATOM_then, 2, args);
  55919. }
  55920. static JSValue js_promise_finally_value_thunk(JSContext *ctx, JSValueConst this_val,
  55921. int argc, JSValueConst *argv,
  55922. int magic, JSValueConst *func_data)
  55923. {
  55924. return js_dup(func_data[0]);
  55925. }
  55926. static JSValue js_promise_finally_thrower(JSContext *ctx, JSValueConst this_val,
  55927. int argc, JSValueConst *argv,
  55928. int magic, JSValueConst *func_data)
  55929. {
  55930. return JS_Throw(ctx, js_dup(func_data[0]));
  55931. }
  55932. static JSValue js_promise_then_finally_func(JSContext *ctx, JSValueConst this_val,
  55933. int argc, JSValueConst *argv,
  55934. int magic, JSValueConst *func_data)
  55935. {
  55936. JSValueConst ctor = func_data[0];
  55937. JSValueConst onFinally = func_data[1];
  55938. JSValue res, promise, ret, then_func;
  55939. res = JS_Call(ctx, onFinally, JS_UNDEFINED, 0, NULL);
  55940. if (JS_IsException(res))
  55941. return res;
  55942. promise = js_promise_resolve(ctx, ctor, 1, vc(&res), 0);
  55943. JS_FreeValue(ctx, res);
  55944. if (JS_IsException(promise))
  55945. return promise;
  55946. if (magic == 0) {
  55947. then_func = JS_NewCFunctionData(ctx, js_promise_finally_value_thunk, 0,
  55948. 0, 1, argv);
  55949. } else {
  55950. then_func = JS_NewCFunctionData(ctx, js_promise_finally_thrower, 0,
  55951. 0, 1, argv);
  55952. }
  55953. if (JS_IsException(then_func)) {
  55954. JS_FreeValue(ctx, promise);
  55955. return then_func;
  55956. }
  55957. ret = JS_InvokeFree(ctx, promise, JS_ATOM_then, 1, vc(&then_func));
  55958. JS_FreeValue(ctx, then_func);
  55959. return ret;
  55960. }
  55961. static JSValue js_promise_finally(JSContext *ctx, JSValueConst this_val,
  55962. int argc, JSValueConst *argv)
  55963. {
  55964. JSValueConst onFinally = argv[0];
  55965. JSValue ctor, ret;
  55966. JSValue then_funcs[2];
  55967. JSValueConst func_data[2];
  55968. int i;
  55969. ctor = JS_SpeciesConstructor(ctx, this_val, JS_UNDEFINED);
  55970. if (JS_IsException(ctor))
  55971. return ctor;
  55972. if (!JS_IsFunction(ctx, onFinally)) {
  55973. then_funcs[0] = js_dup(onFinally);
  55974. then_funcs[1] = js_dup(onFinally);
  55975. } else {
  55976. func_data[0] = ctor;
  55977. func_data[1] = onFinally;
  55978. for(i = 0; i < 2; i++) {
  55979. then_funcs[i] = JS_NewCFunctionData(ctx, js_promise_then_finally_func, 1, i, 2, func_data);
  55980. if (JS_IsException(then_funcs[i])) {
  55981. if (i == 1)
  55982. JS_FreeValue(ctx, then_funcs[0]);
  55983. JS_FreeValue(ctx, ctor);
  55984. return JS_EXCEPTION;
  55985. }
  55986. }
  55987. }
  55988. JS_FreeValue(ctx, ctor);
  55989. ret = JS_Invoke(ctx, this_val, JS_ATOM_then, 2, vc(then_funcs));
  55990. JS_FreeValue(ctx, then_funcs[0]);
  55991. JS_FreeValue(ctx, then_funcs[1]);
  55992. return ret;
  55993. }
  55994. static const JSCFunctionListEntry js_promise_funcs[] = {
  55995. JS_CFUNC_MAGIC_DEF("resolve", 1, js_promise_resolve, 0 ),
  55996. JS_CFUNC_MAGIC_DEF("reject", 1, js_promise_resolve, 1 ),
  55997. JS_CFUNC_MAGIC_DEF("all", 1, js_promise_all, PROMISE_MAGIC_all ),
  55998. JS_CFUNC_MAGIC_DEF("allSettled", 1, js_promise_all, PROMISE_MAGIC_allSettled ),
  55999. JS_CFUNC_MAGIC_DEF("any", 1, js_promise_all, PROMISE_MAGIC_any ),
  56000. JS_CFUNC_DEF("try", 1, js_promise_try ),
  56001. JS_CFUNC_DEF("race", 1, js_promise_race ),
  56002. JS_CFUNC_DEF("withResolvers", 0, js_promise_withResolvers ),
  56003. JS_CGETSET_DEF("[Symbol.species]", js_get_this, NULL),
  56004. };
  56005. static const JSCFunctionListEntry js_promise_proto_funcs[] = {
  56006. JS_CFUNC_DEF("then", 2, js_promise_then ),
  56007. JS_CFUNC_DEF("catch", 1, js_promise_catch ),
  56008. JS_CFUNC_DEF("finally", 1, js_promise_finally ),
  56009. JS_PROP_STRING_DEF("[Symbol.toStringTag]", "Promise", JS_PROP_CONFIGURABLE ),
  56010. };
  56011. /* AsyncFunction */
  56012. static const JSCFunctionListEntry js_async_function_proto_funcs[] = {
  56013. JS_PROP_STRING_DEF("[Symbol.toStringTag]", "AsyncFunction", JS_PROP_CONFIGURABLE ),
  56014. };
  56015. static JSValue js_async_from_sync_iterator_unwrap(JSContext *ctx,
  56016. JSValueConst this_val,
  56017. int argc, JSValueConst *argv,
  56018. int magic, JSValueConst *func_data)
  56019. {
  56020. return js_create_iterator_result(ctx, js_dup(argv[0]),
  56021. JS_ToBool(ctx, func_data[0]));
  56022. }
  56023. static JSValue js_async_from_sync_iterator_unwrap_func_create(JSContext *ctx,
  56024. bool done)
  56025. {
  56026. JSValueConst func_data[1];
  56027. func_data[0] = js_bool(done);
  56028. return JS_NewCFunctionData(ctx, js_async_from_sync_iterator_unwrap,
  56029. 1, 0, 1, func_data);
  56030. }
  56031. /* AsyncIteratorPrototype */
  56032. static const JSCFunctionListEntry js_async_iterator_proto_funcs[] = {
  56033. JS_CFUNC_DEF("[Symbol.asyncIterator]", 0, js_iterator_proto_iterator ),
  56034. };
  56035. /* AsyncFromSyncIteratorPrototype */
  56036. typedef struct JSAsyncFromSyncIteratorData {
  56037. JSValue sync_iter;
  56038. JSValue next_method;
  56039. } JSAsyncFromSyncIteratorData;
  56040. static void js_async_from_sync_iterator_finalizer(JSRuntime *rt,
  56041. JSValueConst val)
  56042. {
  56043. JSAsyncFromSyncIteratorData *s =
  56044. JS_GetOpaque(val, JS_CLASS_ASYNC_FROM_SYNC_ITERATOR);
  56045. if (s) {
  56046. JS_FreeValueRT(rt, s->sync_iter);
  56047. JS_FreeValueRT(rt, s->next_method);
  56048. js_free_rt(rt, s);
  56049. }
  56050. }
  56051. static void js_async_from_sync_iterator_mark(JSRuntime *rt, JSValueConst val,
  56052. JS_MarkFunc *mark_func)
  56053. {
  56054. JSAsyncFromSyncIteratorData *s =
  56055. JS_GetOpaque(val, JS_CLASS_ASYNC_FROM_SYNC_ITERATOR);
  56056. if (s) {
  56057. JS_MarkValue(rt, s->sync_iter, mark_func);
  56058. JS_MarkValue(rt, s->next_method, mark_func);
  56059. }
  56060. }
  56061. static JSValue JS_CreateAsyncFromSyncIterator(JSContext *ctx,
  56062. JSValue sync_iter)
  56063. {
  56064. JSValue async_iter, next_method;
  56065. JSAsyncFromSyncIteratorData *s;
  56066. next_method = JS_GetProperty(ctx, sync_iter, JS_ATOM_next);
  56067. if (JS_IsException(next_method))
  56068. return JS_EXCEPTION;
  56069. async_iter = JS_NewObjectClass(ctx, JS_CLASS_ASYNC_FROM_SYNC_ITERATOR);
  56070. if (JS_IsException(async_iter)) {
  56071. JS_FreeValue(ctx, next_method);
  56072. return async_iter;
  56073. }
  56074. s = js_mallocz(ctx, sizeof(*s));
  56075. if (!s) {
  56076. JS_FreeValue(ctx, async_iter);
  56077. JS_FreeValue(ctx, next_method);
  56078. return JS_EXCEPTION;
  56079. }
  56080. s->sync_iter = js_dup(sync_iter);
  56081. s->next_method = next_method;
  56082. JS_SetOpaqueInternal(async_iter, s);
  56083. return async_iter;
  56084. }
  56085. static JSValue js_async_from_sync_iterator_next(JSContext *ctx, JSValueConst this_val,
  56086. int argc, JSValueConst *argv,
  56087. int magic)
  56088. {
  56089. JSValue promise, resolving_funcs[2], value, err, method;
  56090. JSAsyncFromSyncIteratorData *s;
  56091. int done;
  56092. int is_reject;
  56093. promise = JS_NewPromiseCapability(ctx, resolving_funcs);
  56094. if (JS_IsException(promise))
  56095. return JS_EXCEPTION;
  56096. s = JS_GetOpaque(this_val, JS_CLASS_ASYNC_FROM_SYNC_ITERATOR);
  56097. if (!s) {
  56098. JS_ThrowTypeError(ctx, "not an Async-from-Sync Iterator");
  56099. goto reject;
  56100. }
  56101. if (magic == GEN_MAGIC_NEXT) {
  56102. method = js_dup(s->next_method);
  56103. } else {
  56104. method = JS_GetProperty(ctx, s->sync_iter,
  56105. magic == GEN_MAGIC_RETURN ? JS_ATOM_return :
  56106. JS_ATOM_throw);
  56107. if (JS_IsException(method))
  56108. goto reject;
  56109. if (JS_IsUndefined(method) || JS_IsNull(method)) {
  56110. if (magic == GEN_MAGIC_RETURN) {
  56111. err = js_create_iterator_result(ctx, js_dup(argv[0]), true);
  56112. is_reject = 0;
  56113. } else {
  56114. err = JS_MakeError(ctx, JS_TYPE_ERROR, "throw is not a method",
  56115. true);
  56116. is_reject = 1;
  56117. }
  56118. goto done_resolve;
  56119. }
  56120. }
  56121. value = JS_IteratorNext2(ctx, s->sync_iter, method,
  56122. argc >= 1 ? 1 : 0, argv, &done);
  56123. JS_FreeValue(ctx, method);
  56124. if (JS_IsException(value))
  56125. goto reject;
  56126. if (done == 2) {
  56127. JSValue obj = value;
  56128. value = JS_IteratorGetCompleteValue(ctx, obj, &done);
  56129. JS_FreeValue(ctx, obj);
  56130. if (JS_IsException(value))
  56131. goto reject;
  56132. }
  56133. if (JS_IsException(value)) {
  56134. JSValue res2;
  56135. reject:
  56136. err = JS_GetException(ctx);
  56137. is_reject = 1;
  56138. done_resolve:
  56139. res2 = JS_Call(ctx, resolving_funcs[is_reject], JS_UNDEFINED,
  56140. 1, vc(&err));
  56141. JS_FreeValue(ctx, err);
  56142. JS_FreeValue(ctx, res2);
  56143. JS_FreeValue(ctx, resolving_funcs[0]);
  56144. JS_FreeValue(ctx, resolving_funcs[1]);
  56145. return promise;
  56146. }
  56147. {
  56148. JSValue value_wrapper_promise, resolve_reject[2];
  56149. int res;
  56150. value_wrapper_promise = js_promise_resolve(ctx, ctx->promise_ctor,
  56151. 1, vc(&value), 0);
  56152. if (JS_IsException(value_wrapper_promise)) {
  56153. JS_FreeValue(ctx, value);
  56154. goto reject;
  56155. }
  56156. resolve_reject[0] =
  56157. js_async_from_sync_iterator_unwrap_func_create(ctx, done);
  56158. if (JS_IsException(resolve_reject[0])) {
  56159. JS_FreeValue(ctx, value_wrapper_promise);
  56160. goto fail;
  56161. }
  56162. JS_FreeValue(ctx, value);
  56163. resolve_reject[1] = JS_UNDEFINED;
  56164. res = perform_promise_then(ctx, value_wrapper_promise,
  56165. vc(resolve_reject),
  56166. vc(resolving_funcs));
  56167. JS_FreeValue(ctx, resolve_reject[0]);
  56168. JS_FreeValue(ctx, value_wrapper_promise);
  56169. JS_FreeValue(ctx, resolving_funcs[0]);
  56170. JS_FreeValue(ctx, resolving_funcs[1]);
  56171. if (res) {
  56172. JS_FreeValue(ctx, promise);
  56173. return JS_EXCEPTION;
  56174. }
  56175. }
  56176. return promise;
  56177. fail:
  56178. JS_FreeValue(ctx, value);
  56179. JS_FreeValue(ctx, resolving_funcs[0]);
  56180. JS_FreeValue(ctx, resolving_funcs[1]);
  56181. JS_FreeValue(ctx, promise);
  56182. return JS_EXCEPTION;
  56183. }
  56184. static const JSCFunctionListEntry js_async_from_sync_iterator_proto_funcs[] = {
  56185. JS_CFUNC_MAGIC_DEF("next", 1, js_async_from_sync_iterator_next, GEN_MAGIC_NEXT ),
  56186. JS_CFUNC_MAGIC_DEF("return", 1, js_async_from_sync_iterator_next, GEN_MAGIC_RETURN ),
  56187. JS_CFUNC_MAGIC_DEF("throw", 1, js_async_from_sync_iterator_next, GEN_MAGIC_THROW ),
  56188. };
  56189. /* AsyncGeneratorFunction */
  56190. static const JSCFunctionListEntry js_async_generator_function_proto_funcs[] = {
  56191. JS_PROP_STRING_DEF("[Symbol.toStringTag]", "AsyncGeneratorFunction", JS_PROP_CONFIGURABLE ),
  56192. };
  56193. /* AsyncGenerator prototype */
  56194. static const JSCFunctionListEntry js_async_generator_proto_funcs[] = {
  56195. JS_CFUNC_MAGIC_DEF("next", 1, js_async_generator_next, GEN_MAGIC_NEXT ),
  56196. JS_CFUNC_MAGIC_DEF("return", 1, js_async_generator_next, GEN_MAGIC_RETURN ),
  56197. JS_CFUNC_MAGIC_DEF("throw", 1, js_async_generator_next, GEN_MAGIC_THROW ),
  56198. JS_PROP_STRING_DEF("[Symbol.toStringTag]", "AsyncGenerator", JS_PROP_CONFIGURABLE ),
  56199. };
  56200. static JSClassShortDef const js_async_class_def[] = {
  56201. { JS_ATOM_Promise, js_promise_finalizer, js_promise_mark }, /* JS_CLASS_PROMISE */
  56202. { JS_ATOM_PromiseResolveFunction, js_promise_resolve_function_finalizer, js_promise_resolve_function_mark }, /* JS_CLASS_PROMISE_RESOLVE_FUNCTION */
  56203. { JS_ATOM_PromiseRejectFunction, js_promise_resolve_function_finalizer, js_promise_resolve_function_mark }, /* JS_CLASS_PROMISE_REJECT_FUNCTION */
  56204. { JS_ATOM_AsyncFunction, js_bytecode_function_finalizer, js_bytecode_function_mark }, /* JS_CLASS_ASYNC_FUNCTION */
  56205. { JS_ATOM_AsyncFunctionResolve, js_async_function_resolve_finalizer, js_async_function_resolve_mark }, /* JS_CLASS_ASYNC_FUNCTION_RESOLVE */
  56206. { JS_ATOM_AsyncFunctionReject, js_async_function_resolve_finalizer, js_async_function_resolve_mark }, /* JS_CLASS_ASYNC_FUNCTION_REJECT */
  56207. { JS_ATOM_empty_string, js_async_from_sync_iterator_finalizer, js_async_from_sync_iterator_mark }, /* JS_CLASS_ASYNC_FROM_SYNC_ITERATOR */
  56208. { JS_ATOM_AsyncGeneratorFunction, js_bytecode_function_finalizer, js_bytecode_function_mark }, /* JS_CLASS_ASYNC_GENERATOR_FUNCTION */
  56209. { JS_ATOM_AsyncGenerator, js_async_generator_finalizer, js_async_generator_mark }, /* JS_CLASS_ASYNC_GENERATOR */
  56210. };
  56211. void JS_AddIntrinsicPromise(JSContext *ctx)
  56212. {
  56213. JSRuntime *rt = ctx->rt;
  56214. JSValue obj1;
  56215. if (!JS_IsRegisteredClass(rt, JS_CLASS_PROMISE)) {
  56216. init_class_range(rt, js_async_class_def, JS_CLASS_PROMISE,
  56217. countof(js_async_class_def));
  56218. rt->class_array[JS_CLASS_PROMISE_RESOLVE_FUNCTION].call = js_promise_resolve_function_call;
  56219. rt->class_array[JS_CLASS_PROMISE_REJECT_FUNCTION].call = js_promise_resolve_function_call;
  56220. rt->class_array[JS_CLASS_ASYNC_FUNCTION].call = js_async_function_call;
  56221. rt->class_array[JS_CLASS_ASYNC_FUNCTION_RESOLVE].call = js_async_function_resolve_call;
  56222. rt->class_array[JS_CLASS_ASYNC_FUNCTION_REJECT].call = js_async_function_resolve_call;
  56223. rt->class_array[JS_CLASS_ASYNC_GENERATOR_FUNCTION].call = js_async_generator_function_call;
  56224. }
  56225. /* Promise */
  56226. ctx->class_proto[JS_CLASS_PROMISE] = JS_NewObject(ctx);
  56227. JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_PROMISE],
  56228. js_promise_proto_funcs,
  56229. countof(js_promise_proto_funcs));
  56230. obj1 = JS_NewCFunction2(ctx, js_promise_constructor, "Promise", 1,
  56231. JS_CFUNC_constructor, 0);
  56232. ctx->promise_ctor = js_dup(obj1);
  56233. JS_SetPropertyFunctionList(ctx, obj1,
  56234. js_promise_funcs,
  56235. countof(js_promise_funcs));
  56236. JS_NewGlobalCConstructor2(ctx, obj1, "Promise",
  56237. ctx->class_proto[JS_CLASS_PROMISE]);
  56238. /* Used to squelch a -Wcast-function-type warning. */
  56239. JSCFunctionType ft;
  56240. /* AsyncFunction */
  56241. ctx->class_proto[JS_CLASS_ASYNC_FUNCTION] = JS_NewObjectProto(ctx, ctx->function_proto);
  56242. ft.generic_magic = js_function_constructor;
  56243. obj1 = JS_NewCFunction3(ctx, ft.generic,
  56244. "AsyncFunction", 1,
  56245. JS_CFUNC_constructor_or_func_magic, JS_FUNC_ASYNC,
  56246. ctx->function_ctor);
  56247. JS_SetPropertyFunctionList(ctx,
  56248. ctx->class_proto[JS_CLASS_ASYNC_FUNCTION],
  56249. js_async_function_proto_funcs,
  56250. countof(js_async_function_proto_funcs));
  56251. JS_SetConstructor2(ctx, obj1, ctx->class_proto[JS_CLASS_ASYNC_FUNCTION],
  56252. 0, JS_PROP_CONFIGURABLE);
  56253. JS_FreeValue(ctx, obj1);
  56254. /* AsyncIteratorPrototype */
  56255. ctx->async_iterator_proto = JS_NewObject(ctx);
  56256. JS_SetPropertyFunctionList(ctx, ctx->async_iterator_proto,
  56257. js_async_iterator_proto_funcs,
  56258. countof(js_async_iterator_proto_funcs));
  56259. /* AsyncFromSyncIteratorPrototype */
  56260. ctx->class_proto[JS_CLASS_ASYNC_FROM_SYNC_ITERATOR] =
  56261. JS_NewObjectProto(ctx, ctx->async_iterator_proto);
  56262. JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_ASYNC_FROM_SYNC_ITERATOR],
  56263. js_async_from_sync_iterator_proto_funcs,
  56264. countof(js_async_from_sync_iterator_proto_funcs));
  56265. /* AsyncGeneratorPrototype */
  56266. ctx->class_proto[JS_CLASS_ASYNC_GENERATOR] =
  56267. JS_NewObjectProto(ctx, ctx->async_iterator_proto);
  56268. JS_SetPropertyFunctionList(ctx,
  56269. ctx->class_proto[JS_CLASS_ASYNC_GENERATOR],
  56270. js_async_generator_proto_funcs,
  56271. countof(js_async_generator_proto_funcs));
  56272. /* AsyncGeneratorFunction */
  56273. ctx->class_proto[JS_CLASS_ASYNC_GENERATOR_FUNCTION] =
  56274. JS_NewObjectProto(ctx, ctx->function_proto);
  56275. ft.generic_magic = js_function_constructor;
  56276. obj1 = JS_NewCFunction3(ctx, ft.generic,
  56277. "AsyncGeneratorFunction", 1,
  56278. JS_CFUNC_constructor_or_func_magic,
  56279. JS_FUNC_ASYNC_GENERATOR,
  56280. ctx->function_ctor);
  56281. JS_SetPropertyFunctionList(ctx,
  56282. ctx->class_proto[JS_CLASS_ASYNC_GENERATOR_FUNCTION],
  56283. js_async_generator_function_proto_funcs,
  56284. countof(js_async_generator_function_proto_funcs));
  56285. JS_SetConstructor2(ctx, ctx->class_proto[JS_CLASS_ASYNC_GENERATOR_FUNCTION],
  56286. ctx->class_proto[JS_CLASS_ASYNC_GENERATOR],
  56287. JS_PROP_CONFIGURABLE, JS_PROP_CONFIGURABLE);
  56288. JS_SetConstructor2(ctx, obj1, ctx->class_proto[JS_CLASS_ASYNC_GENERATOR_FUNCTION],
  56289. 0, JS_PROP_CONFIGURABLE);
  56290. JS_FreeValue(ctx, obj1);
  56291. }
  56292. /* URI handling */
  56293. static int string_get_hex(JSString *p, int k, int n) {
  56294. int c = 0, h;
  56295. while (n-- > 0) {
  56296. if ((h = from_hex(string_get(p, k++))) < 0)
  56297. return -1;
  56298. c = (c << 4) | h;
  56299. }
  56300. return c;
  56301. }
  56302. static int isURIReserved(int c) {
  56303. return c < 0x100 && memchr(";/?:@&=+$,#", c, sizeof(";/?:@&=+$,#") - 1) != NULL;
  56304. }
  56305. static int JS_PRINTF_FORMAT_ATTR(2, 3) js_throw_URIError(JSContext *ctx, JS_PRINTF_FORMAT const char *fmt, ...)
  56306. {
  56307. va_list ap;
  56308. va_start(ap, fmt);
  56309. JS_ThrowError(ctx, JS_URI_ERROR, fmt, ap);
  56310. va_end(ap);
  56311. return -1;
  56312. }
  56313. static int hex_decode(JSContext *ctx, JSString *p, int k) {
  56314. int c;
  56315. if (k >= p->len || string_get(p, k) != '%')
  56316. return js_throw_URIError(ctx, "expecting %%");
  56317. if (k + 2 >= p->len || (c = string_get_hex(p, k + 1, 2)) < 0)
  56318. return js_throw_URIError(ctx, "expecting hex digit");
  56319. return c;
  56320. }
  56321. static JSValue js_global_decodeURI(JSContext *ctx, JSValueConst this_val,
  56322. int argc, JSValueConst *argv, int isComponent)
  56323. {
  56324. JSValue str;
  56325. StringBuffer b_s, *b = &b_s;
  56326. JSString *p;
  56327. int k, c, c1, n, c_min;
  56328. str = JS_ToString(ctx, argv[0]);
  56329. if (JS_IsException(str))
  56330. return str;
  56331. string_buffer_init(ctx, b, 0);
  56332. p = JS_VALUE_GET_STRING(str);
  56333. for (k = 0; k < p->len;) {
  56334. c = string_get(p, k);
  56335. if (c == '%') {
  56336. c = hex_decode(ctx, p, k);
  56337. if (c < 0)
  56338. goto fail;
  56339. k += 3;
  56340. if (c < 0x80) {
  56341. if (!isComponent && isURIReserved(c)) {
  56342. c = '%';
  56343. k -= 2;
  56344. }
  56345. } else {
  56346. /* Decode URI-encoded UTF-8 sequence */
  56347. if (c >= 0xc0 && c <= 0xdf) {
  56348. n = 1;
  56349. c_min = 0x80;
  56350. c &= 0x1f;
  56351. } else if (c >= 0xe0 && c <= 0xef) {
  56352. n = 2;
  56353. c_min = 0x800;
  56354. c &= 0xf;
  56355. } else if (c >= 0xf0 && c <= 0xf7) {
  56356. n = 3;
  56357. c_min = 0x10000;
  56358. c &= 0x7;
  56359. } else {
  56360. n = 0;
  56361. c_min = 1;
  56362. c = 0;
  56363. }
  56364. while (n-- > 0) {
  56365. c1 = hex_decode(ctx, p, k);
  56366. if (c1 < 0)
  56367. goto fail;
  56368. k += 3;
  56369. if ((c1 & 0xc0) != 0x80) {
  56370. c = 0;
  56371. break;
  56372. }
  56373. c = (c << 6) | (c1 & 0x3f);
  56374. }
  56375. if (c < c_min || c > 0x10FFFF || is_surrogate(c)) {
  56376. js_throw_URIError(ctx, "malformed UTF-8");
  56377. goto fail;
  56378. }
  56379. }
  56380. } else {
  56381. k++;
  56382. }
  56383. string_buffer_putc(b, c);
  56384. }
  56385. JS_FreeValue(ctx, str);
  56386. return string_buffer_end(b);
  56387. fail:
  56388. JS_FreeValue(ctx, str);
  56389. string_buffer_free(b);
  56390. return JS_EXCEPTION;
  56391. }
  56392. static int isUnescaped(int c) {
  56393. static char const unescaped_chars[] =
  56394. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  56395. "abcdefghijklmnopqrstuvwxyz"
  56396. "0123456789"
  56397. "@*_+-./";
  56398. return c < 0x100 &&
  56399. memchr(unescaped_chars, c, sizeof(unescaped_chars) - 1);
  56400. }
  56401. static int isURIUnescaped(int c, int isComponent) {
  56402. return c < 0x100 &&
  56403. ((c >= 0x61 && c <= 0x7a) ||
  56404. (c >= 0x41 && c <= 0x5a) ||
  56405. (c >= 0x30 && c <= 0x39) ||
  56406. memchr("-_.!~*'()", c, sizeof("-_.!~*'()") - 1) != NULL ||
  56407. (!isComponent && isURIReserved(c)));
  56408. }
  56409. static int encodeURI_hex(StringBuffer *b, int c) {
  56410. uint8_t buf[6];
  56411. int n = 0;
  56412. const char *hex = "0123456789ABCDEF";
  56413. buf[n++] = '%';
  56414. if (c >= 256) {
  56415. buf[n++] = 'u';
  56416. buf[n++] = hex[(c >> 12) & 15];
  56417. buf[n++] = hex[(c >> 8) & 15];
  56418. }
  56419. buf[n++] = hex[(c >> 4) & 15];
  56420. buf[n++] = hex[(c >> 0) & 15];
  56421. return string_buffer_write8(b, buf, n);
  56422. }
  56423. static JSValue js_global_encodeURI(JSContext *ctx, JSValueConst this_val,
  56424. int argc, JSValueConst *argv,
  56425. int isComponent)
  56426. {
  56427. JSValue str;
  56428. StringBuffer b_s, *b = &b_s;
  56429. JSString *p;
  56430. int k, c, c1;
  56431. str = JS_ToString(ctx, argv[0]);
  56432. if (JS_IsException(str))
  56433. return str;
  56434. p = JS_VALUE_GET_STRING(str);
  56435. string_buffer_init(ctx, b, p->len);
  56436. for (k = 0; k < p->len;) {
  56437. c = string_get(p, k);
  56438. k++;
  56439. if (isURIUnescaped(c, isComponent)) {
  56440. string_buffer_putc16(b, c);
  56441. } else {
  56442. if (is_lo_surrogate(c)) {
  56443. js_throw_URIError(ctx, "invalid character");
  56444. goto fail;
  56445. } else if (is_hi_surrogate(c)) {
  56446. if (k >= p->len) {
  56447. js_throw_URIError(ctx, "expecting surrogate pair");
  56448. goto fail;
  56449. }
  56450. c1 = string_get(p, k);
  56451. k++;
  56452. if (!is_lo_surrogate(c1)) {
  56453. js_throw_URIError(ctx, "expecting surrogate pair");
  56454. goto fail;
  56455. }
  56456. c = from_surrogate(c, c1);
  56457. }
  56458. if (c < 0x80) {
  56459. encodeURI_hex(b, c);
  56460. } else {
  56461. /* XXX: use C UTF-8 conversion ? */
  56462. if (c < 0x800) {
  56463. encodeURI_hex(b, (c >> 6) | 0xc0);
  56464. } else {
  56465. if (c < 0x10000) {
  56466. encodeURI_hex(b, (c >> 12) | 0xe0);
  56467. } else {
  56468. encodeURI_hex(b, (c >> 18) | 0xf0);
  56469. encodeURI_hex(b, ((c >> 12) & 0x3f) | 0x80);
  56470. }
  56471. encodeURI_hex(b, ((c >> 6) & 0x3f) | 0x80);
  56472. }
  56473. encodeURI_hex(b, (c & 0x3f) | 0x80);
  56474. }
  56475. }
  56476. }
  56477. JS_FreeValue(ctx, str);
  56478. return string_buffer_end(b);
  56479. fail:
  56480. JS_FreeValue(ctx, str);
  56481. string_buffer_free(b);
  56482. return JS_EXCEPTION;
  56483. }
  56484. static JSValue js_global_escape(JSContext *ctx, JSValueConst this_val,
  56485. int argc, JSValueConst *argv)
  56486. {
  56487. JSValue str;
  56488. StringBuffer b_s, *b = &b_s;
  56489. JSString *p;
  56490. int i, len, c;
  56491. str = JS_ToString(ctx, argv[0]);
  56492. if (JS_IsException(str))
  56493. return str;
  56494. p = JS_VALUE_GET_STRING(str);
  56495. string_buffer_init(ctx, b, p->len);
  56496. for (i = 0, len = p->len; i < len; i++) {
  56497. c = string_get(p, i);
  56498. if (isUnescaped(c)) {
  56499. string_buffer_putc16(b, c);
  56500. } else {
  56501. encodeURI_hex(b, c);
  56502. }
  56503. }
  56504. JS_FreeValue(ctx, str);
  56505. return string_buffer_end(b);
  56506. }
  56507. static JSValue js_global_unescape(JSContext *ctx, JSValueConst this_val,
  56508. int argc, JSValueConst *argv)
  56509. {
  56510. JSValue str;
  56511. StringBuffer b_s, *b = &b_s;
  56512. JSString *p;
  56513. int i, len, c, n;
  56514. str = JS_ToString(ctx, argv[0]);
  56515. if (JS_IsException(str))
  56516. return str;
  56517. string_buffer_init(ctx, b, 0);
  56518. p = JS_VALUE_GET_STRING(str);
  56519. for (i = 0, len = p->len; i < len; i++) {
  56520. c = string_get(p, i);
  56521. if (c == '%') {
  56522. if (i + 6 <= len
  56523. && string_get(p, i + 1) == 'u'
  56524. && (n = string_get_hex(p, i + 2, 4)) >= 0) {
  56525. c = n;
  56526. i += 6 - 1;
  56527. } else
  56528. if (i + 3 <= len
  56529. && (n = string_get_hex(p, i + 1, 2)) >= 0) {
  56530. c = n;
  56531. i += 3 - 1;
  56532. }
  56533. }
  56534. string_buffer_putc16(b, c);
  56535. }
  56536. JS_FreeValue(ctx, str);
  56537. return string_buffer_end(b);
  56538. }
  56539. /* global object */
  56540. static const JSCFunctionListEntry js_global_funcs[] = {
  56541. JS_CFUNC_DEF("parseInt", 2, js_parseInt ),
  56542. JS_CFUNC_DEF("parseFloat", 1, js_parseFloat ),
  56543. JS_CFUNC_DEF("isNaN", 1, js_global_isNaN ),
  56544. JS_CFUNC_DEF("isFinite", 1, js_global_isFinite ),
  56545. JS_CFUNC_DEF("queueMicrotask", 1, js_global_queueMicrotask ),
  56546. JS_CFUNC_MAGIC_DEF("decodeURI", 1, js_global_decodeURI, 0 ),
  56547. JS_CFUNC_MAGIC_DEF("decodeURIComponent", 1, js_global_decodeURI, 1 ),
  56548. JS_CFUNC_MAGIC_DEF("encodeURI", 1, js_global_encodeURI, 0 ),
  56549. JS_CFUNC_MAGIC_DEF("encodeURIComponent", 1, js_global_encodeURI, 1 ),
  56550. JS_CFUNC_DEF("escape", 1, js_global_escape ),
  56551. JS_CFUNC_DEF("unescape", 1, js_global_unescape ),
  56552. JS_PROP_DOUBLE_DEF("Infinity", 1.0 / 0.0, 0 ),
  56553. JS_PROP_U2D_DEF("NaN", 0x7FF8ull<<48, 0 ), // workaround for msvc
  56554. JS_PROP_UNDEFINED_DEF("undefined", 0 ),
  56555. JS_PROP_STRING_DEF("[Symbol.toStringTag]", "global", JS_PROP_CONFIGURABLE ),
  56556. };
  56557. /* Date */
  56558. static int64_t math_mod(int64_t a, int64_t b) {
  56559. /* return positive modulo */
  56560. int64_t m = a % b;
  56561. return m + (m < 0) * b;
  56562. }
  56563. static int64_t floor_div_int64(int64_t a, int64_t b) {
  56564. /* integer division rounding toward -Infinity */
  56565. int64_t m = a % b;
  56566. return (a - (m + (m < 0) * b)) / b;
  56567. }
  56568. static JSValue js_Date_parse(JSContext *ctx, JSValueConst this_val,
  56569. int argc, JSValueConst *argv);
  56570. static __exception int JS_ThisTimeValue(JSContext *ctx, double *valp,
  56571. JSValueConst this_val)
  56572. {
  56573. if (JS_VALUE_GET_TAG(this_val) == JS_TAG_OBJECT) {
  56574. JSObject *p = JS_VALUE_GET_OBJ(this_val);
  56575. if (p->class_id == JS_CLASS_DATE && JS_IsNumber(p->u.object_data))
  56576. return JS_ToFloat64(ctx, valp, p->u.object_data);
  56577. }
  56578. JS_ThrowTypeError(ctx, "not a Date object");
  56579. return -1;
  56580. }
  56581. static JSValue JS_SetThisTimeValue(JSContext *ctx, JSValueConst this_val, double v)
  56582. {
  56583. if (JS_VALUE_GET_TAG(this_val) == JS_TAG_OBJECT) {
  56584. JSObject *p = JS_VALUE_GET_OBJ(this_val);
  56585. if (p->class_id == JS_CLASS_DATE) {
  56586. JS_FreeValue(ctx, p->u.object_data);
  56587. p->u.object_data = js_float64(v);
  56588. return js_dup(p->u.object_data);
  56589. }
  56590. }
  56591. return JS_ThrowTypeError(ctx, "not a Date object");
  56592. }
  56593. static int64_t days_from_year(int64_t y) {
  56594. return 365 * (y - 1970) + floor_div_int64(y - 1969, 4) -
  56595. floor_div_int64(y - 1901, 100) + floor_div_int64(y - 1601, 400);
  56596. }
  56597. static int64_t days_in_year(int64_t y) {
  56598. return 365 + !(y % 4) - !(y % 100) + !(y % 400);
  56599. }
  56600. /* return the year, update days */
  56601. static int64_t year_from_days(int64_t *days) {
  56602. int64_t y, d1, nd, d = *days;
  56603. y = floor_div_int64(d * 10000, 3652425) + 1970;
  56604. /* the initial approximation is very good, so only a few
  56605. iterations are necessary */
  56606. for(;;) {
  56607. d1 = d - days_from_year(y);
  56608. if (d1 < 0) {
  56609. y--;
  56610. d1 += days_in_year(y);
  56611. } else {
  56612. nd = days_in_year(y);
  56613. if (d1 < nd)
  56614. break;
  56615. d1 -= nd;
  56616. y++;
  56617. }
  56618. }
  56619. *days = d1;
  56620. return y;
  56621. }
  56622. static int const month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
  56623. static char const month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
  56624. static char const day_names[] = "SunMonTueWedThuFriSat";
  56625. static __exception int get_date_fields(JSContext *ctx, JSValueConst obj,
  56626. double fields[minimum_length(9)],
  56627. int is_local, int force)
  56628. {
  56629. double dval;
  56630. int64_t d, days, wd, y, i, md, h, m, s, ms, tz = 0;
  56631. if (JS_ThisTimeValue(ctx, &dval, obj))
  56632. return -1;
  56633. if (isnan(dval)) {
  56634. if (!force)
  56635. return false; /* NaN */
  56636. d = 0; /* initialize all fields to 0 */
  56637. } else {
  56638. d = dval; /* assuming -8.64e15 <= dval <= -8.64e15 */
  56639. if (is_local) {
  56640. tz = -getTimezoneOffset(d);
  56641. d += tz * 60000;
  56642. }
  56643. }
  56644. /* result is >= 0, we can use % */
  56645. h = math_mod(d, 86400000);
  56646. days = (d - h) / 86400000;
  56647. ms = h % 1000;
  56648. h = (h - ms) / 1000;
  56649. s = h % 60;
  56650. h = (h - s) / 60;
  56651. m = h % 60;
  56652. h = (h - m) / 60;
  56653. wd = math_mod(days + 4, 7); /* week day */
  56654. y = year_from_days(&days);
  56655. for(i = 0; i < 11; i++) {
  56656. md = month_days[i];
  56657. if (i == 1)
  56658. md += days_in_year(y) - 365;
  56659. if (days < md)
  56660. break;
  56661. days -= md;
  56662. }
  56663. fields[0] = y;
  56664. fields[1] = i;
  56665. fields[2] = days + 1;
  56666. fields[3] = h;
  56667. fields[4] = m;
  56668. fields[5] = s;
  56669. fields[6] = ms;
  56670. fields[7] = wd;
  56671. fields[8] = tz;
  56672. return true;
  56673. }
  56674. static double time_clip(double t) {
  56675. if (t >= -8.64e15 && t <= 8.64e15)
  56676. return trunc(t) + 0.0; /* convert -0 to +0 */
  56677. else
  56678. return NAN;
  56679. }
  56680. /* The spec mandates the use of 'double' and it specifies the order
  56681. of the operations */
  56682. static double set_date_fields(double fields[minimum_length(7)], int is_local) {
  56683. double y, m, dt, ym, mn, day, h, s, milli, time, tv;
  56684. int yi, mi, i;
  56685. int64_t days;
  56686. volatile double temp; /* enforce evaluation order */
  56687. /* emulate 21.4.1.15 MakeDay ( year, month, date ) */
  56688. y = fields[0];
  56689. m = fields[1];
  56690. dt = fields[2];
  56691. ym = y + floor(m / 12);
  56692. mn = fmod(m, 12);
  56693. if (mn < 0)
  56694. mn += 12;
  56695. if (ym < -271821 || ym > 275760)
  56696. return NAN;
  56697. yi = ym;
  56698. mi = mn;
  56699. days = days_from_year(yi);
  56700. for(i = 0; i < mi; i++) {
  56701. days += month_days[i];
  56702. if (i == 1)
  56703. days += days_in_year(yi) - 365;
  56704. }
  56705. day = days + dt - 1;
  56706. /* emulate 21.4.1.14 MakeTime ( hour, min, sec, ms ) */
  56707. h = fields[3];
  56708. m = fields[4];
  56709. s = fields[5];
  56710. milli = fields[6];
  56711. /* Use a volatile intermediary variable to ensure order of evaluation
  56712. * as specified in ECMA. This fixes a test262 error on
  56713. * test262/test/built-ins/Date/UTC/fp-evaluation-order.js.
  56714. * Without the volatile qualifier, the compile can generate code
  56715. * that performs the computation in a different order or with instructions
  56716. * that produce a different result such as FMA (float multiply and add).
  56717. */
  56718. time = h * 3600000;
  56719. time += (temp = m * 60000);
  56720. time += (temp = s * 1000);
  56721. time += milli;
  56722. /* emulate 21.4.1.16 MakeDate ( day, time ) */
  56723. tv = (temp = day * 86400000) + time; /* prevent generation of FMA */
  56724. if (!isfinite(tv))
  56725. return NAN;
  56726. /* adjust for local time and clip */
  56727. if (is_local) {
  56728. int64_t ti = tv < INT64_MIN ? INT64_MIN : tv >= 0x1p63 ? INT64_MAX : (int64_t)tv;
  56729. tv += getTimezoneOffset(ti) * 60000;
  56730. }
  56731. return time_clip(tv);
  56732. }
  56733. static JSValue get_date_field(JSContext *ctx, JSValueConst this_val,
  56734. int argc, JSValueConst *argv, int magic)
  56735. {
  56736. // get_date_field(obj, n, is_local)
  56737. double fields[9];
  56738. int res, n, is_local;
  56739. is_local = magic & 0x0F;
  56740. n = (magic >> 4) & 0x0F;
  56741. res = get_date_fields(ctx, this_val, fields, is_local, 0);
  56742. if (res < 0)
  56743. return JS_EXCEPTION;
  56744. if (!res)
  56745. return JS_NAN;
  56746. if (magic & 0x100) { // getYear
  56747. fields[0] -= 1900;
  56748. }
  56749. return js_number(fields[n]);
  56750. }
  56751. static JSValue set_date_field(JSContext *ctx, JSValueConst this_val,
  56752. int argc, JSValueConst *argv, int magic)
  56753. {
  56754. // _field(obj, first_field, end_field, args, is_local)
  56755. double fields[9];
  56756. int res, first_field, end_field, is_local, i, n;
  56757. double d, a;
  56758. d = NAN;
  56759. first_field = (magic >> 8) & 0x0F;
  56760. end_field = (magic >> 4) & 0x0F;
  56761. is_local = magic & 0x0F;
  56762. res = get_date_fields(ctx, this_val, fields, is_local, first_field == 0);
  56763. if (res < 0)
  56764. return JS_EXCEPTION;
  56765. // Argument coercion is observable and must be done unconditionally.
  56766. n = min_int(argc, end_field - first_field);
  56767. for(i = 0; i < n; i++) {
  56768. if (JS_ToFloat64(ctx, &a, argv[i]))
  56769. return JS_EXCEPTION;
  56770. if (!isfinite(a))
  56771. res = false;
  56772. fields[first_field + i] = trunc(a);
  56773. }
  56774. if (!res)
  56775. return JS_NAN;
  56776. if (argc > 0)
  56777. d = set_date_fields(fields, is_local);
  56778. return JS_SetThisTimeValue(ctx, this_val, d);
  56779. }
  56780. /* fmt:
  56781. 0: toUTCString: "Tue, 02 Jan 2018 23:04:46 GMT"
  56782. 1: toString: "Wed Jan 03 2018 00:05:22 GMT+0100 (CET)"
  56783. 2: toISOString: "2018-01-02T23:02:56.927Z"
  56784. 3: toLocaleString: "1/2/2018, 11:40:40 PM"
  56785. part: 1=date, 2=time 3=all
  56786. XXX: should use a variant of strftime().
  56787. */
  56788. static JSValue get_date_string(JSContext *ctx, JSValueConst this_val,
  56789. int argc, JSValueConst *argv, int magic)
  56790. {
  56791. // _string(obj, fmt, part)
  56792. char buf[64];
  56793. double fields[9];
  56794. int res, fmt, part, pos;
  56795. int y, mon, d, h, m, s, ms, wd, tz;
  56796. fmt = (magic >> 4) & 0x0F;
  56797. part = magic & 0x0F;
  56798. res = get_date_fields(ctx, this_val, fields, fmt & 1, 0);
  56799. if (res < 0)
  56800. return JS_EXCEPTION;
  56801. if (!res) {
  56802. if (fmt == 2)
  56803. return JS_ThrowRangeError(ctx, "Date value is NaN");
  56804. else
  56805. return js_new_string8(ctx, "Invalid Date");
  56806. }
  56807. y = fields[0];
  56808. mon = fields[1];
  56809. d = fields[2];
  56810. h = fields[3];
  56811. m = fields[4];
  56812. s = fields[5];
  56813. ms = fields[6];
  56814. wd = fields[7];
  56815. tz = fields[8];
  56816. pos = 0;
  56817. if (part & 1) { /* date part */
  56818. switch(fmt) {
  56819. case 0:
  56820. pos += snprintf(buf + pos, sizeof(buf) - pos,
  56821. "%.3s, %02d %.3s %0*d ",
  56822. day_names + wd * 3, d,
  56823. month_names + mon * 3, 4 + (y < 0), y);
  56824. break;
  56825. case 1:
  56826. pos += snprintf(buf + pos, sizeof(buf) - pos,
  56827. "%.3s %.3s %02d %0*d",
  56828. day_names + wd * 3,
  56829. month_names + mon * 3, d, 4 + (y < 0), y);
  56830. if (part == 3) {
  56831. buf[pos++] = ' ';
  56832. }
  56833. break;
  56834. case 2:
  56835. if (y >= 0 && y <= 9999) {
  56836. pos += snprintf(buf + pos, sizeof(buf) - pos,
  56837. "%04d", y);
  56838. } else {
  56839. pos += snprintf(buf + pos, sizeof(buf) - pos,
  56840. "%+07d", y);
  56841. }
  56842. pos += snprintf(buf + pos, sizeof(buf) - pos,
  56843. "-%02d-%02dT", mon + 1, d);
  56844. break;
  56845. case 3:
  56846. pos += snprintf(buf + pos, sizeof(buf) - pos,
  56847. "%02d/%02d/%0*d", mon + 1, d, 4 + (y < 0), y);
  56848. if (part == 3) {
  56849. buf[pos++] = ',';
  56850. buf[pos++] = ' ';
  56851. }
  56852. break;
  56853. }
  56854. }
  56855. if (part & 2) { /* time part */
  56856. switch(fmt) {
  56857. case 0:
  56858. pos += snprintf(buf + pos, sizeof(buf) - pos,
  56859. "%02d:%02d:%02d GMT", h, m, s);
  56860. break;
  56861. case 1:
  56862. pos += snprintf(buf + pos, sizeof(buf) - pos,
  56863. "%02d:%02d:%02d GMT", h, m, s);
  56864. if (tz < 0) {
  56865. buf[pos++] = '-';
  56866. tz = -tz;
  56867. } else {
  56868. buf[pos++] = '+';
  56869. }
  56870. /* tz is >= 0, can use % */
  56871. pos += snprintf(buf + pos, sizeof(buf) - pos,
  56872. "%02d%02d", tz / 60, tz % 60);
  56873. /* XXX: tack the time zone code? */
  56874. break;
  56875. case 2:
  56876. pos += snprintf(buf + pos, sizeof(buf) - pos,
  56877. "%02d:%02d:%02d.%03dZ", h, m, s, ms);
  56878. break;
  56879. case 3:
  56880. pos += snprintf(buf + pos, sizeof(buf) - pos,
  56881. "%02d:%02d:%02d %cM", (h + 11) % 12 + 1, m, s,
  56882. (h < 12) ? 'A' : 'P');
  56883. break;
  56884. }
  56885. }
  56886. if (!pos) {
  56887. // XXX: should throw exception?
  56888. return JS_AtomToString(ctx, JS_ATOM_empty_string);
  56889. }
  56890. return js_new_string8_len(ctx, buf, pos);
  56891. }
  56892. /* OS dependent: return the UTC time in ms since 1970. */
  56893. static int64_t date_now(void) {
  56894. return js__gettimeofday_us() / 1000;
  56895. }
  56896. static JSValue js_date_constructor(JSContext *ctx, JSValueConst new_target,
  56897. int argc, JSValueConst *argv)
  56898. {
  56899. // Date(y, mon, d, h, m, s, ms)
  56900. JSValue rv;
  56901. int i, n;
  56902. double a, val;
  56903. if (JS_IsUndefined(new_target)) {
  56904. /* invoked as function */
  56905. argc = 0;
  56906. }
  56907. n = argc;
  56908. if (n == 0) {
  56909. val = date_now();
  56910. } else if (n == 1) {
  56911. JSValue v, dv;
  56912. if (JS_VALUE_GET_TAG(argv[0]) == JS_TAG_OBJECT) {
  56913. JSObject *p = JS_VALUE_GET_OBJ(argv[0]);
  56914. if (p->class_id == JS_CLASS_DATE && JS_IsNumber(p->u.object_data)) {
  56915. if (JS_ToFloat64(ctx, &val, p->u.object_data))
  56916. return JS_EXCEPTION;
  56917. val = time_clip(val);
  56918. goto has_val;
  56919. }
  56920. }
  56921. v = JS_ToPrimitive(ctx, argv[0], HINT_NONE);
  56922. if (JS_IsString(v)) {
  56923. dv = js_Date_parse(ctx, JS_UNDEFINED, 1, vc(&v));
  56924. JS_FreeValue(ctx, v);
  56925. if (JS_IsException(dv))
  56926. return JS_EXCEPTION;
  56927. if (JS_ToFloat64Free(ctx, &val, dv))
  56928. return JS_EXCEPTION;
  56929. } else {
  56930. if (JS_ToFloat64Free(ctx, &val, v))
  56931. return JS_EXCEPTION;
  56932. }
  56933. val = time_clip(val);
  56934. } else {
  56935. double fields[] = { 0, 0, 1, 0, 0, 0, 0 };
  56936. if (n > 7)
  56937. n = 7;
  56938. for(i = 0; i < n; i++) {
  56939. if (JS_ToFloat64(ctx, &a, argv[i]))
  56940. return JS_EXCEPTION;
  56941. if (!isfinite(a))
  56942. break;
  56943. fields[i] = trunc(a);
  56944. if (i == 0 && fields[0] >= 0 && fields[0] < 100)
  56945. fields[0] += 1900;
  56946. }
  56947. val = (i == n) ? set_date_fields(fields, 1) : NAN;
  56948. }
  56949. has_val:
  56950. rv = js_create_from_ctor(ctx, new_target, JS_CLASS_DATE);
  56951. if (!JS_IsException(rv))
  56952. JS_SetObjectData(ctx, rv, js_float64(val));
  56953. if (!JS_IsException(rv) && JS_IsUndefined(new_target)) {
  56954. /* invoked as a function, return (new Date()).toString(); */
  56955. JSValue s;
  56956. s = get_date_string(ctx, rv, 0, NULL, 0x13);
  56957. JS_FreeValue(ctx, rv);
  56958. rv = s;
  56959. }
  56960. return rv;
  56961. }
  56962. static JSValue js_Date_UTC(JSContext *ctx, JSValueConst this_val,
  56963. int argc, JSValueConst *argv)
  56964. {
  56965. // UTC(y, mon, d, h, m, s, ms)
  56966. double fields[] = { 0, 0, 1, 0, 0, 0, 0 };
  56967. int i, n;
  56968. double a;
  56969. n = argc;
  56970. if (n == 0)
  56971. return JS_NAN;
  56972. if (n > 7)
  56973. n = 7;
  56974. for(i = 0; i < n; i++) {
  56975. if (JS_ToFloat64(ctx, &a, argv[i]))
  56976. return JS_EXCEPTION;
  56977. if (!isfinite(a))
  56978. return JS_NAN;
  56979. fields[i] = trunc(a);
  56980. if (i == 0 && fields[0] >= 0 && fields[0] < 100)
  56981. fields[0] += 1900;
  56982. }
  56983. return js_float64(set_date_fields(fields, 0));
  56984. }
  56985. /* Date string parsing */
  56986. static bool string_skip_char(const uint8_t *sp, int *pp, int c) {
  56987. if (sp[*pp] == c) {
  56988. *pp += 1;
  56989. return true;
  56990. } else {
  56991. return false;
  56992. }
  56993. }
  56994. /* skip spaces, update offset, return next char */
  56995. static int string_skip_spaces(const uint8_t *sp, int *pp) {
  56996. int c;
  56997. while ((c = sp[*pp]) == ' ')
  56998. *pp += 1;
  56999. return c;
  57000. }
  57001. /* skip dashes dots and commas */
  57002. static int string_skip_separators(const uint8_t *sp, int *pp) {
  57003. int c;
  57004. while ((c = sp[*pp]) == '-' || c == '/' || c == '.' || c == ',')
  57005. *pp += 1;
  57006. return c;
  57007. }
  57008. /* skip a word, stop on spaces, digits and separators, update offset */
  57009. static int string_skip_until(const uint8_t *sp, int *pp, const char *stoplist) {
  57010. int c;
  57011. while (!strchr(stoplist, c = sp[*pp]))
  57012. *pp += 1;
  57013. return c;
  57014. }
  57015. /* parse a numeric field (max_digits = 0 -> no maximum) */
  57016. static bool string_get_digits(const uint8_t *sp, int *pp, int *pval,
  57017. int min_digits, int max_digits)
  57018. {
  57019. int v = 0;
  57020. int c, p = *pp, p_start;
  57021. p_start = p;
  57022. while ((c = sp[p]) >= '0' && c <= '9') {
  57023. v = v * 10 + c - '0';
  57024. p++;
  57025. if (p - p_start == max_digits)
  57026. break;
  57027. }
  57028. if (p - p_start < min_digits)
  57029. return false;
  57030. *pval = v;
  57031. *pp = p;
  57032. return true;
  57033. }
  57034. static bool string_get_milliseconds(const uint8_t *sp, int *pp, int *pval) {
  57035. /* parse optional fractional part as milliseconds and truncate. */
  57036. /* spec does not indicate which rounding should be used */
  57037. int mul = 100, ms = 0, c, p_start, p = *pp;
  57038. c = sp[p];
  57039. if (c == '.' || c == ',') {
  57040. p++;
  57041. p_start = p;
  57042. while ((c = sp[p]) >= '0' && c <= '9') {
  57043. ms += (c - '0') * mul;
  57044. mul /= 10;
  57045. p++;
  57046. if (p - p_start == 9)
  57047. break;
  57048. }
  57049. if (p > p_start) {
  57050. /* only consume the separator if digits are present */
  57051. *pval = ms;
  57052. *pp = p;
  57053. }
  57054. }
  57055. return true;
  57056. }
  57057. static bool string_get_tzoffset(const uint8_t *sp, int *pp, int *tzp, bool strict) {
  57058. int tz = 0, sgn, hh, mm, p = *pp;
  57059. sgn = sp[p++];
  57060. if (sgn == '+' || sgn == '-') {
  57061. int n = p;
  57062. if (!string_get_digits(sp, &p, &hh, 1, 9))
  57063. return false;
  57064. n = p - n;
  57065. if (strict && n != 2 && n != 4)
  57066. return false;
  57067. while (n > 4) {
  57068. n -= 2;
  57069. hh /= 100;
  57070. }
  57071. if (n > 2) {
  57072. mm = hh % 100;
  57073. hh = hh / 100;
  57074. } else {
  57075. mm = 0;
  57076. if (string_skip_char(sp, &p, ':') /* optional separator */
  57077. && !string_get_digits(sp, &p, &mm, 2, 2))
  57078. return false;
  57079. }
  57080. if (hh > 23 || mm > 59)
  57081. return false;
  57082. tz = hh * 60 + mm;
  57083. if (sgn != '+')
  57084. tz = -tz;
  57085. } else
  57086. if (sgn != 'Z') {
  57087. return false;
  57088. }
  57089. *pp = p;
  57090. *tzp = tz;
  57091. return true;
  57092. }
  57093. static bool string_match(const uint8_t *sp, int *pp, const char *s) {
  57094. int p = *pp;
  57095. while (*s != '\0') {
  57096. if (to_upper_ascii(sp[p]) != to_upper_ascii(*s++))
  57097. return false;
  57098. p++;
  57099. }
  57100. *pp = p;
  57101. return true;
  57102. }
  57103. static int find_abbrev(const uint8_t *sp, int p, const char *list, int count) {
  57104. int n, i;
  57105. for (n = 0; n < count; n++) {
  57106. for (i = 0;; i++) {
  57107. if (to_upper_ascii(sp[p + i]) != to_upper_ascii(list[n * 3 + i]))
  57108. break;
  57109. if (i == 2)
  57110. return n;
  57111. }
  57112. }
  57113. return -1;
  57114. }
  57115. static bool string_get_month(const uint8_t *sp, int *pp, int *pval) {
  57116. int n;
  57117. n = find_abbrev(sp, *pp, month_names, 12);
  57118. if (n < 0)
  57119. return false;
  57120. *pval = n + 1;
  57121. *pp += 3;
  57122. return true;
  57123. }
  57124. /* parse toISOString format */
  57125. static bool js_date_parse_isostring(const uint8_t *sp, int fields[9], bool *is_local) {
  57126. int sgn, i, p = 0;
  57127. /* initialize fields to the beginning of the Epoch */
  57128. for (i = 0; i < 9; i++) {
  57129. fields[i] = (i == 2);
  57130. }
  57131. *is_local = false;
  57132. /* year is either yyyy digits or [+-]yyyyyy */
  57133. sgn = sp[p];
  57134. if (sgn == '-' || sgn == '+') {
  57135. p++;
  57136. if (!string_get_digits(sp, &p, &fields[0], 6, 6))
  57137. return false;
  57138. if (sgn == '-') {
  57139. if (fields[0] == 0)
  57140. return false; // reject -000000
  57141. fields[0] = -fields[0];
  57142. }
  57143. } else {
  57144. if (!string_get_digits(sp, &p, &fields[0], 4, 4))
  57145. return false;
  57146. }
  57147. if (string_skip_char(sp, &p, '-')) {
  57148. if (!string_get_digits(sp, &p, &fields[1], 2, 2)) /* month */
  57149. return false;
  57150. if (fields[1] < 1)
  57151. return false;
  57152. fields[1] -= 1;
  57153. if (string_skip_char(sp, &p, '-')) {
  57154. if (!string_get_digits(sp, &p, &fields[2], 2, 2)) /* day */
  57155. return false;
  57156. if (fields[2] < 1)
  57157. return false;
  57158. }
  57159. }
  57160. if (string_skip_char(sp, &p, 'T')) {
  57161. *is_local = true;
  57162. if (!string_get_digits(sp, &p, &fields[3], 2, 2) /* hour */
  57163. || !string_skip_char(sp, &p, ':')
  57164. || !string_get_digits(sp, &p, &fields[4], 2, 2)) { /* minute */
  57165. fields[3] = 100; // reject unconditionally
  57166. return true;
  57167. }
  57168. if (string_skip_char(sp, &p, ':')) {
  57169. if (!string_get_digits(sp, &p, &fields[5], 2, 2)) /* second */
  57170. return false;
  57171. string_get_milliseconds(sp, &p, &fields[6]);
  57172. }
  57173. }
  57174. /* parse the time zone offset if present: [+-]HH:mm or [+-]HHmm */
  57175. if (sp[p]) {
  57176. *is_local = false;
  57177. if (!string_get_tzoffset(sp, &p, &fields[8], true))
  57178. return false;
  57179. }
  57180. /* error if extraneous characters */
  57181. return sp[p] == '\0';
  57182. }
  57183. static struct {
  57184. char name[6];
  57185. int16_t offset;
  57186. } const js_tzabbr[] = {
  57187. { "GMT", 0 }, // Greenwich Mean Time
  57188. { "UTC", 0 }, // Coordinated Universal Time
  57189. { "UT", 0 }, // Universal Time
  57190. { "Z", 0 }, // Zulu Time
  57191. { "EDT", -4 * 60 }, // Eastern Daylight Time
  57192. { "EST", -5 * 60 }, // Eastern Standard Time
  57193. { "CDT", -5 * 60 }, // Central Daylight Time
  57194. { "CST", -6 * 60 }, // Central Standard Time
  57195. { "MDT", -6 * 60 }, // Mountain Daylight Time
  57196. { "MST", -7 * 60 }, // Mountain Standard Time
  57197. { "PDT", -7 * 60 }, // Pacific Daylight Time
  57198. { "PST", -8 * 60 }, // Pacific Standard Time
  57199. { "WET", +0 * 60 }, // Western European Time
  57200. { "WEST", +1 * 60 }, // Western European Summer Time
  57201. { "CET", +1 * 60 }, // Central European Time
  57202. { "CEST", +2 * 60 }, // Central European Summer Time
  57203. { "EET", +2 * 60 }, // Eastern European Time
  57204. { "EEST", +3 * 60 }, // Eastern European Summer Time
  57205. };
  57206. static bool string_get_tzabbr(const uint8_t *sp, int *pp, int *offset) {
  57207. size_t i;
  57208. for (i = 0; i < countof(js_tzabbr); i++) {
  57209. if (string_match(sp, pp, js_tzabbr[i].name)) {
  57210. *offset = js_tzabbr[i].offset;
  57211. return true;
  57212. }
  57213. }
  57214. return false;
  57215. }
  57216. /* parse toString, toUTCString and other formats */
  57217. static bool js_date_parse_otherstring(const uint8_t *sp,
  57218. int fields[minimum_length(9)],
  57219. bool *is_local) {
  57220. int c, i, val, p = 0, p_start;
  57221. int num[3];
  57222. bool has_year = false;
  57223. bool has_mon = false;
  57224. bool has_time = false;
  57225. int num_index = 0;
  57226. /* initialize fields to the beginning of 2001-01-01 */
  57227. fields[0] = 2001;
  57228. fields[1] = 1;
  57229. fields[2] = 1;
  57230. for (i = 3; i < 9; i++) {
  57231. fields[i] = 0;
  57232. }
  57233. *is_local = true;
  57234. while (string_skip_spaces(sp, &p)) {
  57235. p_start = p;
  57236. if ((c = sp[p]) == '+' || c == '-') {
  57237. if (has_time && string_get_tzoffset(sp, &p, &fields[8], false)) {
  57238. *is_local = false;
  57239. } else {
  57240. p++;
  57241. if (string_get_digits(sp, &p, &val, 1, 9)) {
  57242. if (c == '-') {
  57243. if (val == 0)
  57244. return false;
  57245. val = -val;
  57246. }
  57247. fields[0] = val;
  57248. has_year = true;
  57249. }
  57250. }
  57251. } else
  57252. if (string_get_digits(sp, &p, &val, 1, 9)) {
  57253. if (string_skip_char(sp, &p, ':')) {
  57254. /* time part */
  57255. fields[3] = val;
  57256. if (!string_get_digits(sp, &p, &fields[4], 1, 2))
  57257. return false;
  57258. if (string_skip_char(sp, &p, ':')) {
  57259. if (!string_get_digits(sp, &p, &fields[5], 1, 2))
  57260. return false;
  57261. string_get_milliseconds(sp, &p, &fields[6]);
  57262. } else
  57263. if (sp[p] != '\0' && sp[p] != ' ')
  57264. return false;
  57265. has_time = true;
  57266. } else {
  57267. if (p - p_start > 2) {
  57268. fields[0] = val;
  57269. has_year = true;
  57270. } else
  57271. if (val < 1 || val > 31) {
  57272. fields[0] = val + (val < 100) * 1900 + (val < 50) * 100;
  57273. has_year = true;
  57274. } else {
  57275. if (num_index == 3)
  57276. return false;
  57277. num[num_index++] = val;
  57278. }
  57279. }
  57280. } else
  57281. if (string_get_month(sp, &p, &fields[1])) {
  57282. has_mon = true;
  57283. string_skip_until(sp, &p, "0123456789 -/(");
  57284. } else
  57285. if (has_time && string_match(sp, &p, "PM")) {
  57286. /* hours greater than 12 will be incremented and
  57287. rejected by the range check in js_Date_parse */
  57288. /* 00:00 PM will be silently converted as 12:00 */
  57289. if (fields[3] != 12)
  57290. fields[3] += 12;
  57291. continue;
  57292. } else
  57293. if (has_time && string_match(sp, &p, "AM")) {
  57294. /* 00:00 AM will be silently accepted */
  57295. if (fields[3] > 12)
  57296. return false;
  57297. if (fields[3] == 12)
  57298. fields[3] -= 12;
  57299. continue;
  57300. } else
  57301. if (string_get_tzabbr(sp, &p, &fields[8])) {
  57302. *is_local = false;
  57303. continue;
  57304. } else
  57305. if (c == '(') { /* skip parenthesized phrase */
  57306. int level = 0;
  57307. while ((c = sp[p]) != '\0') {
  57308. p++;
  57309. level += (c == '(');
  57310. level -= (c == ')');
  57311. if (!level)
  57312. break;
  57313. }
  57314. if (level > 0)
  57315. return false;
  57316. } else
  57317. if (c == ')') {
  57318. return false;
  57319. } else {
  57320. if (has_year + has_mon + has_time + num_index)
  57321. return false;
  57322. /* skip a word */
  57323. string_skip_until(sp, &p, " -/(");
  57324. }
  57325. string_skip_separators(sp, &p);
  57326. }
  57327. if (num_index + has_year + has_mon > 3)
  57328. return false;
  57329. switch (num_index) {
  57330. case 0:
  57331. if (!has_year)
  57332. return false;
  57333. break;
  57334. case 1:
  57335. if (has_mon)
  57336. fields[2] = num[0];
  57337. else
  57338. fields[1] = num[0];
  57339. break;
  57340. case 2:
  57341. if (has_year) {
  57342. fields[1] = num[0];
  57343. fields[2] = num[1];
  57344. } else
  57345. if (has_mon) {
  57346. fields[0] = num[1] + (num[1] < 100) * 1900 + (num[1] < 50) * 100;
  57347. fields[2] = num[0];
  57348. } else {
  57349. fields[1] = num[0];
  57350. fields[2] = num[1];
  57351. }
  57352. break;
  57353. case 3:
  57354. fields[0] = num[2] + (num[2] < 100) * 1900 + (num[2] < 50) * 100;
  57355. fields[1] = num[0];
  57356. fields[2] = num[1];
  57357. break;
  57358. default:
  57359. return false;
  57360. }
  57361. if (fields[1] < 1 || fields[2] < 1)
  57362. return false;
  57363. fields[1] -= 1;
  57364. return true;
  57365. }
  57366. static JSValue js_Date_parse(JSContext *ctx, JSValueConst this_val,
  57367. int argc, JSValueConst *argv)
  57368. {
  57369. JSValue s, rv;
  57370. int fields[9];
  57371. double fields1[9];
  57372. double d;
  57373. int i, c;
  57374. JSString *sp;
  57375. uint8_t buf[128];
  57376. bool is_local;
  57377. rv = JS_NAN;
  57378. s = JS_ToString(ctx, argv[0]);
  57379. if (JS_IsException(s))
  57380. return JS_EXCEPTION;
  57381. sp = JS_VALUE_GET_STRING(s);
  57382. /* convert the string as a byte array */
  57383. for (i = 0; i < sp->len && i < (int)countof(buf) - 1; i++) {
  57384. c = string_get(sp, i);
  57385. if (c > 255)
  57386. c = (c == 0x2212) ? '-' : 'x';
  57387. buf[i] = c;
  57388. }
  57389. buf[i] = '\0';
  57390. if (js_date_parse_isostring(buf, fields, &is_local)
  57391. || js_date_parse_otherstring(buf, fields, &is_local)) {
  57392. static int const field_max[6] = { 0, 11, 31, 24, 59, 59 };
  57393. bool valid = true;
  57394. /* check field maximum values */
  57395. for (i = 1; i < 6; i++) {
  57396. if (fields[i] > field_max[i])
  57397. valid = false;
  57398. }
  57399. /* special case 24:00:00.000 */
  57400. if (fields[3] == 24 && (fields[4] | fields[5] | fields[6]))
  57401. valid = false;
  57402. if (valid) {
  57403. for(i = 0; i < 7; i++)
  57404. fields1[i] = fields[i];
  57405. d = set_date_fields(fields1, is_local) - fields[8] * 60000;
  57406. rv = JS_NewFloat64(ctx, d);
  57407. }
  57408. }
  57409. JS_FreeValue(ctx, s);
  57410. return rv;
  57411. }
  57412. static JSValue js_Date_now(JSContext *ctx, JSValueConst this_val,
  57413. int argc, JSValueConst *argv)
  57414. {
  57415. // now()
  57416. return js_int64(date_now());
  57417. }
  57418. static JSValue js_date_Symbol_toPrimitive(JSContext *ctx, JSValueConst this_val,
  57419. int argc, JSValueConst *argv)
  57420. {
  57421. // Symbol_toPrimitive(hint)
  57422. JSValueConst obj = this_val;
  57423. JSAtom hint = JS_ATOM_NULL;
  57424. int hint_num;
  57425. if (!JS_IsObject(obj))
  57426. return JS_ThrowTypeErrorNotAnObject(ctx);
  57427. if (JS_IsString(argv[0])) {
  57428. hint = JS_ValueToAtom(ctx, argv[0]);
  57429. if (hint == JS_ATOM_NULL)
  57430. return JS_EXCEPTION;
  57431. JS_FreeAtom(ctx, hint);
  57432. }
  57433. switch (hint) {
  57434. case JS_ATOM_number:
  57435. case JS_ATOM_integer:
  57436. hint_num = HINT_NUMBER;
  57437. break;
  57438. case JS_ATOM_string:
  57439. case JS_ATOM_default:
  57440. hint_num = HINT_STRING;
  57441. break;
  57442. default:
  57443. return JS_ThrowTypeError(ctx, "invalid hint");
  57444. }
  57445. return JS_ToPrimitive(ctx, obj, hint_num | HINT_FORCE_ORDINARY);
  57446. }
  57447. static JSValue js_date_getTimezoneOffset(JSContext *ctx, JSValueConst this_val,
  57448. int argc, JSValueConst *argv)
  57449. {
  57450. // getTimezoneOffset()
  57451. double v;
  57452. if (JS_ThisTimeValue(ctx, &v, this_val))
  57453. return JS_EXCEPTION;
  57454. if (isnan(v))
  57455. return JS_NAN;
  57456. else
  57457. /* assuming -8.64e15 <= v <= -8.64e15 */
  57458. return js_int64(getTimezoneOffset((int64_t)trunc(v)));
  57459. }
  57460. static JSValue js_date_getTime(JSContext *ctx, JSValueConst this_val,
  57461. int argc, JSValueConst *argv)
  57462. {
  57463. // getTime()
  57464. double v;
  57465. if (JS_ThisTimeValue(ctx, &v, this_val))
  57466. return JS_EXCEPTION;
  57467. return js_float64(v);
  57468. }
  57469. static JSValue js_date_setTime(JSContext *ctx, JSValueConst this_val,
  57470. int argc, JSValueConst *argv)
  57471. {
  57472. // setTime(v)
  57473. double v;
  57474. if (JS_ThisTimeValue(ctx, &v, this_val) || JS_ToFloat64(ctx, &v, argv[0]))
  57475. return JS_EXCEPTION;
  57476. return JS_SetThisTimeValue(ctx, this_val, time_clip(v));
  57477. }
  57478. static JSValue js_date_setYear(JSContext *ctx, JSValueConst this_val,
  57479. int argc, JSValueConst *argv)
  57480. {
  57481. // setYear(y)
  57482. double y;
  57483. JSValue d, ret;
  57484. if (JS_ThisTimeValue(ctx, &y, this_val) || JS_ToFloat64(ctx, &y, argv[0]))
  57485. return JS_EXCEPTION;
  57486. y = +y;
  57487. if (isnan(y))
  57488. return JS_SetThisTimeValue(ctx, this_val, y);
  57489. if (isfinite(y)) {
  57490. y = trunc(y);
  57491. if (y >= 0 && y < 100)
  57492. y += 1900;
  57493. }
  57494. d = js_float64(y);
  57495. ret = set_date_field(ctx, this_val, 1, vc(&d), 0x011);
  57496. JS_FreeValue(ctx, d);
  57497. return ret;
  57498. }
  57499. static JSValue js_date_toJSON(JSContext *ctx, JSValueConst this_val,
  57500. int argc, JSValueConst *argv)
  57501. {
  57502. // toJSON(key)
  57503. JSValue obj, tv, method, rv;
  57504. double d;
  57505. rv = JS_EXCEPTION;
  57506. tv = JS_UNDEFINED;
  57507. obj = JS_ToObject(ctx, this_val);
  57508. tv = JS_ToPrimitive(ctx, obj, HINT_NUMBER);
  57509. if (JS_IsException(tv))
  57510. goto exception;
  57511. if (JS_IsNumber(tv)) {
  57512. if (JS_ToFloat64(ctx, &d, tv) < 0)
  57513. goto exception;
  57514. if (!isfinite(d)) {
  57515. rv = JS_NULL;
  57516. goto done;
  57517. }
  57518. }
  57519. method = JS_GetPropertyStr(ctx, obj, "toISOString");
  57520. if (JS_IsException(method))
  57521. goto exception;
  57522. if (!JS_IsFunction(ctx, method)) {
  57523. JS_ThrowTypeError(ctx, "object needs toISOString method");
  57524. JS_FreeValue(ctx, method);
  57525. goto exception;
  57526. }
  57527. rv = JS_CallFree(ctx, method, obj, 0, NULL);
  57528. exception:
  57529. done:
  57530. JS_FreeValue(ctx, obj);
  57531. JS_FreeValue(ctx, tv);
  57532. return rv;
  57533. }
  57534. static const JSCFunctionListEntry js_date_funcs[] = {
  57535. JS_CFUNC_DEF("now", 0, js_Date_now ),
  57536. JS_CFUNC_DEF("parse", 1, js_Date_parse ),
  57537. JS_CFUNC_DEF("UTC", 7, js_Date_UTC ),
  57538. };
  57539. static const JSCFunctionListEntry js_date_proto_funcs[] = {
  57540. JS_CFUNC_DEF("valueOf", 0, js_date_getTime ),
  57541. JS_CFUNC_MAGIC_DEF("toString", 0, get_date_string, 0x13 ),
  57542. JS_CFUNC_DEF("[Symbol.toPrimitive]", 1, js_date_Symbol_toPrimitive ),
  57543. JS_CFUNC_MAGIC_DEF("toUTCString", 0, get_date_string, 0x03 ),
  57544. JS_ALIAS_DEF("toGMTString", "toUTCString" ),
  57545. JS_CFUNC_MAGIC_DEF("toISOString", 0, get_date_string, 0x23 ),
  57546. JS_CFUNC_MAGIC_DEF("toDateString", 0, get_date_string, 0x11 ),
  57547. JS_CFUNC_MAGIC_DEF("toTimeString", 0, get_date_string, 0x12 ),
  57548. JS_CFUNC_MAGIC_DEF("toLocaleString", 0, get_date_string, 0x33 ),
  57549. JS_CFUNC_MAGIC_DEF("toLocaleDateString", 0, get_date_string, 0x31 ),
  57550. JS_CFUNC_MAGIC_DEF("toLocaleTimeString", 0, get_date_string, 0x32 ),
  57551. JS_CFUNC_DEF("getTimezoneOffset", 0, js_date_getTimezoneOffset ),
  57552. JS_CFUNC_DEF("getTime", 0, js_date_getTime ),
  57553. JS_CFUNC_MAGIC_DEF("getYear", 0, get_date_field, 0x101 ),
  57554. JS_CFUNC_MAGIC_DEF("getFullYear", 0, get_date_field, 0x01 ),
  57555. JS_CFUNC_MAGIC_DEF("getUTCFullYear", 0, get_date_field, 0x00 ),
  57556. JS_CFUNC_MAGIC_DEF("getMonth", 0, get_date_field, 0x11 ),
  57557. JS_CFUNC_MAGIC_DEF("getUTCMonth", 0, get_date_field, 0x10 ),
  57558. JS_CFUNC_MAGIC_DEF("getDate", 0, get_date_field, 0x21 ),
  57559. JS_CFUNC_MAGIC_DEF("getUTCDate", 0, get_date_field, 0x20 ),
  57560. JS_CFUNC_MAGIC_DEF("getHours", 0, get_date_field, 0x31 ),
  57561. JS_CFUNC_MAGIC_DEF("getUTCHours", 0, get_date_field, 0x30 ),
  57562. JS_CFUNC_MAGIC_DEF("getMinutes", 0, get_date_field, 0x41 ),
  57563. JS_CFUNC_MAGIC_DEF("getUTCMinutes", 0, get_date_field, 0x40 ),
  57564. JS_CFUNC_MAGIC_DEF("getSeconds", 0, get_date_field, 0x51 ),
  57565. JS_CFUNC_MAGIC_DEF("getUTCSeconds", 0, get_date_field, 0x50 ),
  57566. JS_CFUNC_MAGIC_DEF("getMilliseconds", 0, get_date_field, 0x61 ),
  57567. JS_CFUNC_MAGIC_DEF("getUTCMilliseconds", 0, get_date_field, 0x60 ),
  57568. JS_CFUNC_MAGIC_DEF("getDay", 0, get_date_field, 0x71 ),
  57569. JS_CFUNC_MAGIC_DEF("getUTCDay", 0, get_date_field, 0x70 ),
  57570. JS_CFUNC_DEF("setTime", 1, js_date_setTime ),
  57571. JS_CFUNC_MAGIC_DEF("setMilliseconds", 1, set_date_field, 0x671 ),
  57572. JS_CFUNC_MAGIC_DEF("setUTCMilliseconds", 1, set_date_field, 0x670 ),
  57573. JS_CFUNC_MAGIC_DEF("setSeconds", 2, set_date_field, 0x571 ),
  57574. JS_CFUNC_MAGIC_DEF("setUTCSeconds", 2, set_date_field, 0x570 ),
  57575. JS_CFUNC_MAGIC_DEF("setMinutes", 3, set_date_field, 0x471 ),
  57576. JS_CFUNC_MAGIC_DEF("setUTCMinutes", 3, set_date_field, 0x470 ),
  57577. JS_CFUNC_MAGIC_DEF("setHours", 4, set_date_field, 0x371 ),
  57578. JS_CFUNC_MAGIC_DEF("setUTCHours", 4, set_date_field, 0x370 ),
  57579. JS_CFUNC_MAGIC_DEF("setDate", 1, set_date_field, 0x231 ),
  57580. JS_CFUNC_MAGIC_DEF("setUTCDate", 1, set_date_field, 0x230 ),
  57581. JS_CFUNC_MAGIC_DEF("setMonth", 2, set_date_field, 0x131 ),
  57582. JS_CFUNC_MAGIC_DEF("setUTCMonth", 2, set_date_field, 0x130 ),
  57583. JS_CFUNC_DEF("setYear", 1, js_date_setYear ),
  57584. JS_CFUNC_MAGIC_DEF("setFullYear", 3, set_date_field, 0x031 ),
  57585. JS_CFUNC_MAGIC_DEF("setUTCFullYear", 3, set_date_field, 0x030 ),
  57586. JS_CFUNC_DEF("toJSON", 1, js_date_toJSON ),
  57587. };
  57588. JSValue JS_NewDate(JSContext *ctx, double epoch_ms)
  57589. {
  57590. JSValue obj = js_create_from_ctor(ctx, JS_UNDEFINED, JS_CLASS_DATE);
  57591. if (JS_IsException(obj))
  57592. return JS_EXCEPTION;
  57593. JS_SetObjectData(ctx, obj, js_float64(time_clip(epoch_ms)));
  57594. return obj;
  57595. }
  57596. bool JS_IsDate(JSValueConst v)
  57597. {
  57598. if (JS_VALUE_GET_TAG(v) != JS_TAG_OBJECT)
  57599. return false;
  57600. return JS_VALUE_GET_OBJ(v)->class_id == JS_CLASS_DATE;
  57601. }
  57602. void JS_AddIntrinsicDate(JSContext *ctx)
  57603. {
  57604. JSValue obj;
  57605. /* Date */
  57606. ctx->class_proto[JS_CLASS_DATE] = JS_NewObject(ctx);
  57607. JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_DATE], js_date_proto_funcs,
  57608. countof(js_date_proto_funcs));
  57609. obj = JS_NewGlobalCConstructor(ctx, "Date", js_date_constructor, 7,
  57610. ctx->class_proto[JS_CLASS_DATE]);
  57611. JS_SetPropertyFunctionList(ctx, obj, js_date_funcs, countof(js_date_funcs));
  57612. }
  57613. /* eval */
  57614. void JS_AddIntrinsicEval(JSContext *ctx)
  57615. {
  57616. ctx->eval_internal = __JS_EvalInternal;
  57617. }
  57618. /* BigInt */
  57619. static JSValue JS_ToBigIntCtorFree(JSContext *ctx, JSValue val)
  57620. {
  57621. uint32_t tag;
  57622. redo:
  57623. tag = JS_VALUE_GET_NORM_TAG(val);
  57624. switch(tag) {
  57625. case JS_TAG_INT:
  57626. case JS_TAG_BOOL:
  57627. val = JS_NewBigInt64(ctx, JS_VALUE_GET_INT(val));
  57628. break;
  57629. case JS_TAG_BIG_INT:
  57630. break;
  57631. case JS_TAG_FLOAT64:
  57632. {
  57633. bf_t *a, a_s;
  57634. a = JS_ToBigInt1(ctx, &a_s, val);
  57635. if (!bf_is_finite(a)) {
  57636. JS_FreeValue(ctx, val);
  57637. val = JS_ThrowRangeError(ctx, "cannot convert NaN or Infinity to BigInt");
  57638. } else {
  57639. JSValue val1 = JS_NewBigInt(ctx);
  57640. bf_t *r;
  57641. int ret;
  57642. if (JS_IsException(val1)) {
  57643. JS_FreeValue(ctx, val);
  57644. return JS_EXCEPTION;
  57645. }
  57646. r = JS_GetBigInt(val1);
  57647. ret = bf_set(r, a);
  57648. ret |= bf_rint(r, BF_RNDZ);
  57649. JS_FreeValue(ctx, val);
  57650. if (ret & BF_ST_MEM_ERROR) {
  57651. JS_FreeValue(ctx, val1);
  57652. val = JS_ThrowOutOfMemory(ctx);
  57653. } else if (ret & BF_ST_INEXACT) {
  57654. JS_FreeValue(ctx, val1);
  57655. val = JS_ThrowRangeError(ctx, "cannot convert to BigInt: not an integer");
  57656. } else {
  57657. val = JS_CompactBigInt(ctx, val1);
  57658. }
  57659. }
  57660. if (a == &a_s)
  57661. bf_delete(a);
  57662. }
  57663. break;
  57664. case JS_TAG_STRING:
  57665. val = JS_StringToBigIntErr(ctx, val);
  57666. break;
  57667. case JS_TAG_OBJECT:
  57668. val = JS_ToPrimitiveFree(ctx, val, HINT_NUMBER);
  57669. if (JS_IsException(val))
  57670. break;
  57671. goto redo;
  57672. case JS_TAG_NULL:
  57673. case JS_TAG_UNDEFINED:
  57674. default:
  57675. JS_FreeValue(ctx, val);
  57676. return JS_ThrowTypeError(ctx, "cannot convert to BigInt");
  57677. }
  57678. return val;
  57679. }
  57680. static JSValue js_bigint_constructor(JSContext *ctx,
  57681. JSValueConst new_target,
  57682. int argc, JSValueConst *argv)
  57683. {
  57684. if (!JS_IsUndefined(new_target))
  57685. return JS_ThrowTypeError(ctx, "not a constructor");
  57686. return JS_ToBigIntCtorFree(ctx, js_dup(argv[0]));
  57687. }
  57688. static JSValue js_thisBigIntValue(JSContext *ctx, JSValueConst this_val)
  57689. {
  57690. if (JS_IsBigInt(ctx, this_val))
  57691. return js_dup(this_val);
  57692. if (JS_VALUE_GET_TAG(this_val) == JS_TAG_OBJECT) {
  57693. JSObject *p = JS_VALUE_GET_OBJ(this_val);
  57694. if (p->class_id == JS_CLASS_BIG_INT) {
  57695. if (JS_IsBigInt(ctx, p->u.object_data))
  57696. return js_dup(p->u.object_data);
  57697. }
  57698. }
  57699. return JS_ThrowTypeError(ctx, "not a BigInt");
  57700. }
  57701. static JSValue js_bigint_toString(JSContext *ctx, JSValueConst this_val,
  57702. int argc, JSValueConst *argv)
  57703. {
  57704. JSValue val;
  57705. int base;
  57706. JSValue ret;
  57707. val = js_thisBigIntValue(ctx, this_val);
  57708. if (JS_IsException(val))
  57709. return val;
  57710. if (argc == 0 || JS_IsUndefined(argv[0])) {
  57711. base = 10;
  57712. } else {
  57713. base = js_get_radix(ctx, argv[0]);
  57714. if (base < 0)
  57715. goto fail;
  57716. }
  57717. ret = js_bigint_to_string1(ctx, val, base);
  57718. JS_FreeValue(ctx, val);
  57719. return ret;
  57720. fail:
  57721. JS_FreeValue(ctx, val);
  57722. return JS_EXCEPTION;
  57723. }
  57724. static JSValue js_bigint_valueOf(JSContext *ctx, JSValueConst this_val,
  57725. int argc, JSValueConst *argv)
  57726. {
  57727. return js_thisBigIntValue(ctx, this_val);
  57728. }
  57729. static JSValue js_bigint_asUintN(JSContext *ctx,
  57730. JSValueConst this_val,
  57731. int argc, JSValueConst *argv, int asIntN)
  57732. {
  57733. uint64_t bits;
  57734. bf_t a_s, *a = &a_s, *r, mask_s, *mask = &mask_s;
  57735. JSValue res;
  57736. if (JS_ToIndex(ctx, &bits, argv[0]))
  57737. return JS_EXCEPTION;
  57738. res = JS_NewBigInt(ctx);
  57739. if (JS_IsException(res))
  57740. return JS_EXCEPTION;
  57741. a = JS_ToBigInt(ctx, &a_s, argv[1]);
  57742. if (!a) {
  57743. JS_FreeValue(ctx, res);
  57744. return JS_EXCEPTION;
  57745. }
  57746. /* XXX: optimize */
  57747. r = JS_GetBigInt(res);
  57748. bf_init(ctx->bf_ctx, mask);
  57749. bf_set_ui(mask, 1);
  57750. bf_mul_2exp(mask, bits, BF_PREC_INF, BF_RNDZ);
  57751. bf_add_si(mask, mask, -1, BF_PREC_INF, BF_RNDZ);
  57752. bf_logic_and(r, a, mask);
  57753. if (asIntN && bits != 0) {
  57754. bf_set_ui(mask, 1);
  57755. bf_mul_2exp(mask, bits - 1, BF_PREC_INF, BF_RNDZ);
  57756. if (bf_cmpu(r, mask) >= 0) {
  57757. bf_set_ui(mask, 1);
  57758. bf_mul_2exp(mask, bits, BF_PREC_INF, BF_RNDZ);
  57759. bf_sub(r, r, mask, BF_PREC_INF, BF_RNDZ);
  57760. }
  57761. }
  57762. bf_delete(mask);
  57763. JS_FreeBigInt(ctx, a, &a_s);
  57764. return JS_CompactBigInt(ctx, res);
  57765. }
  57766. static const JSCFunctionListEntry js_bigint_funcs[] = {
  57767. JS_CFUNC_MAGIC_DEF("asUintN", 2, js_bigint_asUintN, 0 ),
  57768. JS_CFUNC_MAGIC_DEF("asIntN", 2, js_bigint_asUintN, 1 ),
  57769. };
  57770. static const JSCFunctionListEntry js_bigint_proto_funcs[] = {
  57771. JS_CFUNC_DEF("toString", 0, js_bigint_toString ),
  57772. JS_CFUNC_DEF("valueOf", 0, js_bigint_valueOf ),
  57773. JS_PROP_STRING_DEF("[Symbol.toStringTag]", "BigInt", JS_PROP_CONFIGURABLE ),
  57774. };
  57775. void JS_AddIntrinsicBigInt(JSContext *ctx)
  57776. {
  57777. JSValue obj1;
  57778. ctx->class_proto[JS_CLASS_BIG_INT] = JS_NewObject(ctx);
  57779. JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_BIG_INT],
  57780. js_bigint_proto_funcs,
  57781. countof(js_bigint_proto_funcs));
  57782. obj1 = JS_NewGlobalCConstructor(ctx, "BigInt", js_bigint_constructor, 1,
  57783. ctx->class_proto[JS_CLASS_BIG_INT]);
  57784. JS_SetPropertyFunctionList(ctx, obj1, js_bigint_funcs,
  57785. countof(js_bigint_funcs));
  57786. }
  57787. static const char * const native_error_name[JS_NATIVE_ERROR_COUNT] = {
  57788. "EvalError", "RangeError", "ReferenceError",
  57789. "SyntaxError", "TypeError", "URIError",
  57790. "InternalError", "AggregateError",
  57791. };
  57792. /* Minimum amount of objects to be able to compile code and display
  57793. error messages. No JSAtom should be allocated by this function. */
  57794. static void JS_AddIntrinsicBasicObjects(JSContext *ctx)
  57795. {
  57796. JSValue proto;
  57797. int i;
  57798. ctx->class_proto[JS_CLASS_OBJECT] = JS_NewObjectProto(ctx, JS_NULL);
  57799. ctx->global_obj = JS_NewObject(ctx);
  57800. ctx->global_var_obj = JS_NewObjectProto(ctx, JS_NULL);
  57801. ctx->function_proto = JS_NewCFunction3(ctx, js_function_proto, "", 0,
  57802. JS_CFUNC_generic, 0,
  57803. ctx->class_proto[JS_CLASS_OBJECT]);
  57804. ctx->class_proto[JS_CLASS_BYTECODE_FUNCTION] = js_dup(ctx->function_proto);
  57805. ctx->class_proto[JS_CLASS_ERROR] = JS_NewObject(ctx);
  57806. JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_ERROR],
  57807. js_error_proto_funcs,
  57808. countof(js_error_proto_funcs));
  57809. for(i = 0; i < JS_NATIVE_ERROR_COUNT; i++) {
  57810. proto = JS_NewObjectProto(ctx, ctx->class_proto[JS_CLASS_ERROR]);
  57811. JS_DefinePropertyValue(ctx, proto, JS_ATOM_name,
  57812. JS_NewAtomString(ctx, native_error_name[i]),
  57813. JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);
  57814. JS_DefinePropertyValue(ctx, proto, JS_ATOM_message,
  57815. JS_AtomToString(ctx, JS_ATOM_empty_string),
  57816. JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);
  57817. ctx->native_error_proto[i] = proto;
  57818. }
  57819. /* the array prototype is an array */
  57820. ctx->class_proto[JS_CLASS_ARRAY] =
  57821. JS_NewObjectProtoClass(ctx, ctx->class_proto[JS_CLASS_OBJECT],
  57822. JS_CLASS_ARRAY);
  57823. ctx->array_shape = js_new_shape2(ctx, get_proto_obj(ctx->class_proto[JS_CLASS_ARRAY]),
  57824. JS_PROP_INITIAL_HASH_SIZE, 1);
  57825. add_shape_property(ctx, &ctx->array_shape, NULL,
  57826. JS_ATOM_length, JS_PROP_WRITABLE | JS_PROP_LENGTH);
  57827. /* XXX: could test it on first context creation to ensure that no
  57828. new atoms are created in JS_AddIntrinsicBasicObjects(). It is
  57829. necessary to avoid useless renumbering of atoms after
  57830. JS_EvalBinary() if it is done just after
  57831. JS_AddIntrinsicBasicObjects(). */
  57832. // assert(ctx->rt->atom_count == JS_ATOM_END);
  57833. }
  57834. void JS_AddIntrinsicBaseObjects(JSContext *ctx)
  57835. {
  57836. int i;
  57837. JSValue obj, number_obj;
  57838. JSValue obj1;
  57839. ctx->throw_type_error = JS_NewCFunction(ctx, js_throw_type_error, NULL, 0);
  57840. /* add caller and arguments properties to throw a TypeError */
  57841. obj1 = JS_NewCFunction(ctx, js_function_proto_caller, NULL, 0);
  57842. JS_DefineProperty(ctx, ctx->function_proto, JS_ATOM_caller, JS_UNDEFINED,
  57843. obj1, ctx->throw_type_error,
  57844. JS_PROP_HAS_GET | JS_PROP_HAS_SET |
  57845. JS_PROP_HAS_CONFIGURABLE | JS_PROP_CONFIGURABLE);
  57846. JS_DefineProperty(ctx, ctx->function_proto, JS_ATOM_arguments, JS_UNDEFINED,
  57847. obj1, ctx->throw_type_error,
  57848. JS_PROP_HAS_GET | JS_PROP_HAS_SET |
  57849. JS_PROP_HAS_CONFIGURABLE | JS_PROP_CONFIGURABLE);
  57850. JS_FreeValue(ctx, obj1);
  57851. JS_FreeValue(ctx, js_object_seal(ctx, JS_UNDEFINED, 1, vc(&ctx->throw_type_error), 1));
  57852. /* Object */
  57853. obj = JS_NewGlobalCConstructor(ctx, "Object", js_object_constructor, 1,
  57854. ctx->class_proto[JS_CLASS_OBJECT]);
  57855. JS_SetPropertyFunctionList(ctx, obj, js_object_funcs, countof(js_object_funcs));
  57856. JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_OBJECT],
  57857. js_object_proto_funcs, countof(js_object_proto_funcs));
  57858. /* Function */
  57859. JS_SetPropertyFunctionList(ctx, ctx->function_proto, js_function_proto_funcs, countof(js_function_proto_funcs));
  57860. ctx->function_ctor = JS_NewCFunctionMagic(ctx, js_function_constructor,
  57861. "Function", 1, JS_CFUNC_constructor_or_func_magic,
  57862. JS_FUNC_NORMAL);
  57863. JS_NewGlobalCConstructor2(ctx, js_dup(ctx->function_ctor), "Function",
  57864. ctx->function_proto);
  57865. /* Error */
  57866. ctx->error_ctor = JS_NewCFunctionMagic(ctx, js_error_constructor,
  57867. "Error", 1, JS_CFUNC_constructor_or_func_magic, -1);
  57868. JS_NewGlobalCConstructor2(ctx, js_dup(ctx->error_ctor),
  57869. "Error", ctx->class_proto[JS_CLASS_ERROR]);
  57870. JS_SetPropertyFunctionList(ctx, ctx->error_ctor, js_error_funcs, countof(js_error_funcs));
  57871. /* Used to squelch a -Wcast-function-type warning. */
  57872. JSCFunctionType ft = { .generic_magic = js_error_constructor };
  57873. for(i = 0; i < JS_NATIVE_ERROR_COUNT; i++) {
  57874. JSValue func_obj;
  57875. int n_args;
  57876. n_args = 1 + (i == JS_AGGREGATE_ERROR);
  57877. func_obj = JS_NewCFunction3(ctx, ft.generic,
  57878. native_error_name[i], n_args,
  57879. JS_CFUNC_constructor_or_func_magic, i,
  57880. ctx->error_ctor);
  57881. JS_NewGlobalCConstructor2(ctx, func_obj, native_error_name[i],
  57882. ctx->native_error_proto[i]);
  57883. }
  57884. /* CallSite */
  57885. _JS_AddIntrinsicCallSite(ctx);
  57886. /* Iterator */
  57887. ctx->class_proto[JS_CLASS_ITERATOR] = JS_NewObject(ctx);
  57888. JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_ITERATOR],
  57889. js_iterator_proto_funcs,
  57890. countof(js_iterator_proto_funcs));
  57891. obj = JS_NewGlobalCConstructor(ctx, "Iterator", js_iterator_constructor, 0,
  57892. ctx->class_proto[JS_CLASS_ITERATOR]);
  57893. ctx->iterator_ctor = js_dup(obj);
  57894. JS_SetPropertyFunctionList(ctx, obj,
  57895. js_iterator_funcs,
  57896. countof(js_iterator_funcs));
  57897. ctx->class_proto[JS_CLASS_ITERATOR_HELPER] = JS_NewObjectProto(ctx, ctx->class_proto[JS_CLASS_ITERATOR]);
  57898. JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_ITERATOR_HELPER],
  57899. js_iterator_helper_proto_funcs,
  57900. countof(js_iterator_helper_proto_funcs));
  57901. ctx->class_proto[JS_CLASS_ITERATOR_WRAP] = JS_NewObjectProto(ctx, ctx->class_proto[JS_CLASS_ITERATOR]);
  57902. JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_ITERATOR_WRAP],
  57903. js_iterator_wrap_proto_funcs,
  57904. countof(js_iterator_wrap_proto_funcs));
  57905. /* Array */
  57906. JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_ARRAY],
  57907. js_array_proto_funcs,
  57908. countof(js_array_proto_funcs));
  57909. obj = JS_NewGlobalCConstructor(ctx, "Array", js_array_constructor, 1,
  57910. ctx->class_proto[JS_CLASS_ARRAY]);
  57911. ctx->array_ctor = js_dup(obj);
  57912. JS_SetPropertyFunctionList(ctx, obj, js_array_funcs,
  57913. countof(js_array_funcs));
  57914. /* XXX: create auto_initializer */
  57915. {
  57916. /* initialize Array.prototype[Symbol.unscopables] */
  57917. static const char unscopables[] =
  57918. "copyWithin" "\0"
  57919. "entries" "\0"
  57920. "fill" "\0"
  57921. "find" "\0"
  57922. "findIndex" "\0"
  57923. "findLast" "\0"
  57924. "findLastIndex" "\0"
  57925. "flat" "\0"
  57926. "flatMap" "\0"
  57927. "includes" "\0"
  57928. "keys" "\0"
  57929. "toReversed" "\0"
  57930. "toSorted" "\0"
  57931. "toSpliced" "\0"
  57932. "values" "\0";
  57933. const char *p = unscopables;
  57934. obj1 = JS_NewObjectProto(ctx, JS_NULL);
  57935. for(p = unscopables; *p; p += strlen(p) + 1) {
  57936. JS_DefinePropertyValueStr(ctx, obj1, p, JS_TRUE, JS_PROP_C_W_E);
  57937. }
  57938. JS_DefinePropertyValue(ctx, ctx->class_proto[JS_CLASS_ARRAY],
  57939. JS_ATOM_Symbol_unscopables, obj1,
  57940. JS_PROP_CONFIGURABLE);
  57941. }
  57942. /* needed to initialize arguments[Symbol.iterator] */
  57943. ctx->array_proto_values =
  57944. JS_GetProperty(ctx, ctx->class_proto[JS_CLASS_ARRAY], JS_ATOM_values);
  57945. ctx->class_proto[JS_CLASS_ARRAY_ITERATOR] = JS_NewObjectProto(ctx, ctx->class_proto[JS_CLASS_ITERATOR]);
  57946. JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_ARRAY_ITERATOR],
  57947. js_array_iterator_proto_funcs,
  57948. countof(js_array_iterator_proto_funcs));
  57949. /* parseFloat and parseInteger must be defined before Number
  57950. because of the Number.parseFloat and Number.parseInteger
  57951. aliases */
  57952. JS_SetPropertyFunctionList(ctx, ctx->global_obj, js_global_funcs,
  57953. countof(js_global_funcs));
  57954. /* Number */
  57955. ctx->class_proto[JS_CLASS_NUMBER] = JS_NewObjectProtoClass(ctx, ctx->class_proto[JS_CLASS_OBJECT],
  57956. JS_CLASS_NUMBER);
  57957. JS_SetObjectData(ctx, ctx->class_proto[JS_CLASS_NUMBER], js_int32(0));
  57958. JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_NUMBER],
  57959. js_number_proto_funcs,
  57960. countof(js_number_proto_funcs));
  57961. number_obj = JS_NewGlobalCConstructor(ctx, "Number", js_number_constructor, 1,
  57962. ctx->class_proto[JS_CLASS_NUMBER]);
  57963. JS_SetPropertyFunctionList(ctx, number_obj, js_number_funcs, countof(js_number_funcs));
  57964. /* Boolean */
  57965. ctx->class_proto[JS_CLASS_BOOLEAN] = JS_NewObjectProtoClass(ctx, ctx->class_proto[JS_CLASS_OBJECT],
  57966. JS_CLASS_BOOLEAN);
  57967. JS_SetObjectData(ctx, ctx->class_proto[JS_CLASS_BOOLEAN], JS_FALSE);
  57968. JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_BOOLEAN], js_boolean_proto_funcs,
  57969. countof(js_boolean_proto_funcs));
  57970. JS_NewGlobalCConstructor(ctx, "Boolean", js_boolean_constructor, 1,
  57971. ctx->class_proto[JS_CLASS_BOOLEAN]);
  57972. /* String */
  57973. ctx->class_proto[JS_CLASS_STRING] = JS_NewObjectProtoClass(ctx, ctx->class_proto[JS_CLASS_OBJECT],
  57974. JS_CLASS_STRING);
  57975. JS_SetObjectData(ctx, ctx->class_proto[JS_CLASS_STRING], JS_AtomToString(ctx, JS_ATOM_empty_string));
  57976. obj = JS_NewGlobalCConstructor(ctx, "String", js_string_constructor, 1,
  57977. ctx->class_proto[JS_CLASS_STRING]);
  57978. JS_SetPropertyFunctionList(ctx, obj, js_string_funcs,
  57979. countof(js_string_funcs));
  57980. JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_STRING], js_string_proto_funcs,
  57981. countof(js_string_proto_funcs));
  57982. ctx->class_proto[JS_CLASS_STRING_ITERATOR] = JS_NewObjectProto(ctx, ctx->class_proto[JS_CLASS_ITERATOR]);
  57983. JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_STRING_ITERATOR],
  57984. js_string_iterator_proto_funcs,
  57985. countof(js_string_iterator_proto_funcs));
  57986. /* Math: create as autoinit object */
  57987. js_random_init(ctx);
  57988. JS_SetPropertyFunctionList(ctx, ctx->global_obj, js_math_obj, countof(js_math_obj));
  57989. /* ES6 Reflect: create as autoinit object */
  57990. JS_SetPropertyFunctionList(ctx, ctx->global_obj, js_reflect_obj, countof(js_reflect_obj));
  57991. /* ES6 Symbol */
  57992. ctx->class_proto[JS_CLASS_SYMBOL] = JS_NewObject(ctx);
  57993. JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_SYMBOL], js_symbol_proto_funcs,
  57994. countof(js_symbol_proto_funcs));
  57995. obj = JS_NewGlobalCConstructor(ctx, "Symbol", js_symbol_constructor, 0,
  57996. ctx->class_proto[JS_CLASS_SYMBOL]);
  57997. JS_SetPropertyFunctionList(ctx, obj, js_symbol_funcs,
  57998. countof(js_symbol_funcs));
  57999. for(i = JS_ATOM_Symbol_toPrimitive; i < JS_ATOM_END; i++) {
  58000. char buf[ATOM_GET_STR_BUF_SIZE];
  58001. const char *str, *p;
  58002. str = JS_AtomGetStr(ctx, buf, sizeof(buf), i);
  58003. /* skip "Symbol." */
  58004. p = strchr(str, '.');
  58005. if (p)
  58006. str = p + 1;
  58007. JS_DefinePropertyValueStr(ctx, obj, str, JS_AtomToValue(ctx, i), 0);
  58008. }
  58009. /* ES6 Generator */
  58010. ctx->class_proto[JS_CLASS_GENERATOR] = JS_NewObjectProto(ctx, ctx->class_proto[JS_CLASS_ITERATOR]);
  58011. JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_GENERATOR],
  58012. js_generator_proto_funcs,
  58013. countof(js_generator_proto_funcs));
  58014. ctx->class_proto[JS_CLASS_GENERATOR_FUNCTION] = JS_NewObjectProto(ctx, ctx->function_proto);
  58015. obj1 = JS_NewCFunctionMagic(ctx, js_function_constructor,
  58016. "GeneratorFunction", 1,
  58017. JS_CFUNC_constructor_or_func_magic, JS_FUNC_GENERATOR);
  58018. JS_SetPropertyFunctionList(ctx,
  58019. ctx->class_proto[JS_CLASS_GENERATOR_FUNCTION],
  58020. js_generator_function_proto_funcs,
  58021. countof(js_generator_function_proto_funcs));
  58022. JS_SetConstructor2(ctx, ctx->class_proto[JS_CLASS_GENERATOR_FUNCTION],
  58023. ctx->class_proto[JS_CLASS_GENERATOR],
  58024. JS_PROP_CONFIGURABLE, JS_PROP_CONFIGURABLE);
  58025. JS_SetConstructor2(ctx, obj1, ctx->class_proto[JS_CLASS_GENERATOR_FUNCTION],
  58026. 0, JS_PROP_CONFIGURABLE);
  58027. JS_FreeValue(ctx, obj1);
  58028. /* global properties */
  58029. ctx->eval_obj = JS_NewCFunction(ctx, js_global_eval, "eval", 1);
  58030. JS_DefinePropertyValue(ctx, ctx->global_obj, JS_ATOM_eval,
  58031. js_dup(ctx->eval_obj),
  58032. JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);
  58033. JS_DefinePropertyValue(ctx, ctx->global_obj, JS_ATOM_globalThis,
  58034. js_dup(ctx->global_obj),
  58035. JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE);
  58036. }
  58037. /* Typed Arrays */
  58038. static uint8_t const typed_array_size_log2[JS_TYPED_ARRAY_COUNT] = {
  58039. 0, 0, 0, 1, 1, 2, 2,
  58040. 3, 3, // BigInt64Array, BigUint64Array
  58041. 1, 2, 3 // Float16Array, Float32Array, Float64Array
  58042. };
  58043. static JSValue js_array_buffer_constructor3(JSContext *ctx,
  58044. JSValueConst new_target,
  58045. uint64_t len, uint64_t *max_len,
  58046. JSClassID class_id,
  58047. uint8_t *buf,
  58048. JSFreeArrayBufferDataFunc *free_func,
  58049. void *opaque, bool alloc_flag)
  58050. {
  58051. JSRuntime *rt = ctx->rt;
  58052. JSValue obj;
  58053. JSArrayBuffer *abuf = NULL;
  58054. uint64_t sab_alloc_len;
  58055. if (!alloc_flag && buf && max_len && free_func != js_array_buffer_free) {
  58056. // not observable from JS land, only through C API misuse;
  58057. // JS code cannot create externally managed buffers directly
  58058. return JS_ThrowInternalError(ctx,
  58059. "resizable ArrayBuffers not supported "
  58060. "for externally managed buffers");
  58061. }
  58062. obj = js_create_from_ctor(ctx, new_target, class_id);
  58063. if (JS_IsException(obj))
  58064. return obj;
  58065. /* XXX: we are currently limited to 2 GB */
  58066. if (len > INT32_MAX) {
  58067. JS_ThrowRangeError(ctx, "invalid array buffer length");
  58068. goto fail;
  58069. }
  58070. if (max_len && *max_len > INT32_MAX) {
  58071. JS_ThrowRangeError(ctx, "invalid max array buffer length");
  58072. goto fail;
  58073. }
  58074. abuf = js_malloc(ctx, sizeof(*abuf));
  58075. if (!abuf)
  58076. goto fail;
  58077. abuf->byte_length = len;
  58078. abuf->max_byte_length = max_len ? *max_len : -1;
  58079. if (alloc_flag) {
  58080. if (class_id == JS_CLASS_SHARED_ARRAY_BUFFER &&
  58081. rt->sab_funcs.sab_alloc) {
  58082. // TOOD(bnoordhuis) resizing backing memory for SABs atomically
  58083. // is hard so we cheat and allocate |maxByteLength| bytes upfront
  58084. sab_alloc_len = max_len ? *max_len : len;
  58085. abuf->data = rt->sab_funcs.sab_alloc(rt->sab_funcs.sab_opaque,
  58086. max_int(sab_alloc_len, 1));
  58087. if (!abuf->data)
  58088. goto fail;
  58089. memset(abuf->data, 0, sab_alloc_len);
  58090. } else {
  58091. /* the allocation must be done after the object creation */
  58092. abuf->data = js_mallocz(ctx, max_int(len, 1));
  58093. if (!abuf->data)
  58094. goto fail;
  58095. }
  58096. } else {
  58097. if (class_id == JS_CLASS_SHARED_ARRAY_BUFFER &&
  58098. rt->sab_funcs.sab_dup) {
  58099. rt->sab_funcs.sab_dup(rt->sab_funcs.sab_opaque, buf);
  58100. }
  58101. abuf->data = buf;
  58102. }
  58103. init_list_head(&abuf->array_list);
  58104. abuf->detached = false;
  58105. abuf->shared = (class_id == JS_CLASS_SHARED_ARRAY_BUFFER);
  58106. abuf->opaque = opaque;
  58107. abuf->free_func = free_func;
  58108. if (alloc_flag && buf)
  58109. memcpy(abuf->data, buf, len);
  58110. JS_SetOpaqueInternal(obj, abuf);
  58111. return obj;
  58112. fail:
  58113. JS_FreeValue(ctx, obj);
  58114. js_free(ctx, abuf);
  58115. return JS_EXCEPTION;
  58116. }
  58117. static void js_array_buffer_free(JSRuntime *rt, void *opaque, void *ptr)
  58118. {
  58119. js_free_rt(rt, ptr);
  58120. }
  58121. static JSValue js_array_buffer_constructor2(JSContext *ctx,
  58122. JSValueConst new_target,
  58123. uint64_t len, uint64_t *max_len,
  58124. JSClassID class_id)
  58125. {
  58126. return js_array_buffer_constructor3(ctx, new_target, len, max_len,
  58127. class_id, NULL, js_array_buffer_free,
  58128. NULL, true);
  58129. }
  58130. static JSValue js_array_buffer_constructor1(JSContext *ctx,
  58131. JSValueConst new_target,
  58132. uint64_t len, uint64_t *max_len)
  58133. {
  58134. return js_array_buffer_constructor2(ctx, new_target, len, max_len,
  58135. JS_CLASS_ARRAY_BUFFER);
  58136. }
  58137. JSValue JS_NewArrayBuffer(JSContext *ctx, uint8_t *buf, size_t len,
  58138. JSFreeArrayBufferDataFunc *free_func, void *opaque,
  58139. bool is_shared)
  58140. {
  58141. JSClassID class_id =
  58142. is_shared ? JS_CLASS_SHARED_ARRAY_BUFFER : JS_CLASS_ARRAY_BUFFER;
  58143. return js_array_buffer_constructor3(ctx, JS_UNDEFINED, len, NULL, class_id,
  58144. buf, free_func, opaque, false);
  58145. }
  58146. bool JS_IsArrayBuffer(JSValueConst obj) {
  58147. return JS_GetClassID(obj) == JS_CLASS_ARRAY_BUFFER;
  58148. }
  58149. /* create a new ArrayBuffer of length 'len' and copy 'buf' to it */
  58150. JSValue JS_NewArrayBufferCopy(JSContext *ctx, const uint8_t *buf, size_t len)
  58151. {
  58152. return js_array_buffer_constructor3(ctx, JS_UNDEFINED, len, NULL,
  58153. JS_CLASS_ARRAY_BUFFER,
  58154. (uint8_t *)buf,
  58155. js_array_buffer_free, NULL,
  58156. true);
  58157. }
  58158. static JSValue js_array_buffer_constructor0(JSContext *ctx, JSValueConst new_target,
  58159. int argc, JSValueConst *argv,
  58160. JSClassID class_id)
  58161. {
  58162. uint64_t len, max_len, *pmax_len = NULL;
  58163. JSValue obj, val;
  58164. int64_t i;
  58165. if (JS_ToIndex(ctx, &len, argv[0]))
  58166. return JS_EXCEPTION;
  58167. if (argc < 2)
  58168. goto next;
  58169. if (!JS_IsObject(argv[1]))
  58170. goto next;
  58171. obj = JS_ToObject(ctx, argv[1]);
  58172. if (JS_IsException(obj))
  58173. return JS_EXCEPTION;
  58174. val = JS_GetProperty(ctx, obj, JS_ATOM_maxByteLength);
  58175. JS_FreeValue(ctx, obj);
  58176. if (JS_IsException(val))
  58177. return JS_EXCEPTION;
  58178. if (JS_IsUndefined(val))
  58179. goto next;
  58180. if (JS_ToInt64Free(ctx, &i, val))
  58181. return JS_EXCEPTION;
  58182. // don't have to check i < 0 because len >= 0
  58183. if (len > i || i > MAX_SAFE_INTEGER)
  58184. return JS_ThrowRangeError(ctx, "invalid array buffer max length");
  58185. max_len = i;
  58186. pmax_len = &max_len;
  58187. next:
  58188. return js_array_buffer_constructor2(ctx, new_target, len, pmax_len,
  58189. class_id);
  58190. }
  58191. static JSValue js_array_buffer_constructor(JSContext *ctx, JSValueConst new_target,
  58192. int argc, JSValueConst *argv)
  58193. {
  58194. return js_array_buffer_constructor0(ctx, new_target, argc, argv,
  58195. JS_CLASS_ARRAY_BUFFER);
  58196. }
  58197. static JSValue js_shared_array_buffer_constructor(JSContext *ctx,
  58198. JSValueConst new_target,
  58199. int argc, JSValueConst *argv)
  58200. {
  58201. return js_array_buffer_constructor0(ctx, new_target, argc, argv,
  58202. JS_CLASS_SHARED_ARRAY_BUFFER);
  58203. }
  58204. /* also used for SharedArrayBuffer */
  58205. static void js_array_buffer_finalizer(JSRuntime *rt, JSValueConst val)
  58206. {
  58207. JSObject *p = JS_VALUE_GET_OBJ(val);
  58208. JSArrayBuffer *abuf = p->u.array_buffer;
  58209. struct list_head *el, *el1;
  58210. if (abuf) {
  58211. /* The ArrayBuffer finalizer may be called before the typed
  58212. array finalizers using it, so abuf->array_list is not
  58213. necessarily empty. */
  58214. list_for_each_safe(el, el1, &abuf->array_list) {
  58215. JSTypedArray *ta;
  58216. JSObject *p1;
  58217. ta = list_entry(el, JSTypedArray, link);
  58218. ta->link.prev = NULL;
  58219. ta->link.next = NULL;
  58220. p1 = ta->obj;
  58221. /* Note: the typed array length and offset fields are not modified */
  58222. if (p1->class_id != JS_CLASS_DATAVIEW) {
  58223. p1->u.array.count = 0;
  58224. p1->u.array.u.ptr = NULL;
  58225. }
  58226. }
  58227. if (abuf->shared && rt->sab_funcs.sab_free) {
  58228. rt->sab_funcs.sab_free(rt->sab_funcs.sab_opaque, abuf->data);
  58229. } else {
  58230. if (abuf->free_func)
  58231. abuf->free_func(rt, abuf->opaque, abuf->data);
  58232. }
  58233. js_free_rt(rt, abuf);
  58234. }
  58235. }
  58236. static JSValue js_array_buffer_isView(JSContext *ctx,
  58237. JSValueConst this_val,
  58238. int argc, JSValueConst *argv)
  58239. {
  58240. JSObject *p;
  58241. if (JS_VALUE_GET_TAG(argv[0]) == JS_TAG_OBJECT) {
  58242. p = JS_VALUE_GET_OBJ(argv[0]);
  58243. return js_bool(is_typed_array(p->class_id) ||
  58244. p->class_id == JS_CLASS_DATAVIEW);
  58245. }
  58246. return JS_FALSE;
  58247. }
  58248. static const JSCFunctionListEntry js_array_buffer_funcs[] = {
  58249. JS_CFUNC_DEF("isView", 1, js_array_buffer_isView ),
  58250. JS_CGETSET_DEF("[Symbol.species]", js_get_this, NULL ),
  58251. };
  58252. static JSValue JS_ThrowTypeErrorDetachedArrayBuffer(JSContext *ctx)
  58253. {
  58254. return JS_ThrowTypeError(ctx, "ArrayBuffer is detached");
  58255. }
  58256. static JSValue JS_ThrowTypeErrorArrayBufferOOB(JSContext *ctx)
  58257. {
  58258. return JS_ThrowTypeError(ctx, "ArrayBuffer is detached or resized");
  58259. }
  58260. // #sec-get-arraybuffer.prototype.detached
  58261. static JSValue js_array_buffer_get_detached(JSContext *ctx,
  58262. JSValueConst this_val)
  58263. {
  58264. JSArrayBuffer *abuf = JS_GetOpaque2(ctx, this_val, JS_CLASS_ARRAY_BUFFER);
  58265. if (!abuf)
  58266. return JS_EXCEPTION;
  58267. if (abuf->shared)
  58268. return JS_ThrowTypeError(ctx, "detached called on SharedArrayBuffer");
  58269. return js_bool(abuf->detached);
  58270. }
  58271. static JSValue js_array_buffer_get_byteLength(JSContext *ctx,
  58272. JSValueConst this_val,
  58273. int class_id)
  58274. {
  58275. JSArrayBuffer *abuf = JS_GetOpaque2(ctx, this_val, class_id);
  58276. if (!abuf)
  58277. return JS_EXCEPTION;
  58278. /* return 0 if detached */
  58279. return js_uint32(abuf->byte_length);
  58280. }
  58281. static JSValue js_array_buffer_get_maxByteLength(JSContext *ctx,
  58282. JSValueConst this_val,
  58283. int class_id)
  58284. {
  58285. JSArrayBuffer *abuf = JS_GetOpaque2(ctx, this_val, class_id);
  58286. if (!abuf)
  58287. return JS_EXCEPTION;
  58288. if (array_buffer_is_resizable(abuf))
  58289. return js_uint32(abuf->max_byte_length);
  58290. return js_uint32(abuf->byte_length);
  58291. }
  58292. static JSValue js_array_buffer_get_resizable(JSContext *ctx,
  58293. JSValueConst this_val,
  58294. int class_id)
  58295. {
  58296. JSArrayBuffer *abuf = JS_GetOpaque2(ctx, this_val, class_id);
  58297. if (!abuf)
  58298. return JS_EXCEPTION;
  58299. return js_bool(array_buffer_is_resizable(abuf));
  58300. }
  58301. void JS_DetachArrayBuffer(JSContext *ctx, JSValueConst obj)
  58302. {
  58303. JSArrayBuffer *abuf = JS_GetOpaque(obj, JS_CLASS_ARRAY_BUFFER);
  58304. struct list_head *el;
  58305. if (!abuf || abuf->detached)
  58306. return;
  58307. if (abuf->free_func)
  58308. abuf->free_func(ctx->rt, abuf->opaque, abuf->data);
  58309. abuf->data = NULL;
  58310. abuf->byte_length = 0;
  58311. abuf->detached = true;
  58312. list_for_each(el, &abuf->array_list) {
  58313. JSTypedArray *ta;
  58314. JSObject *p;
  58315. ta = list_entry(el, JSTypedArray, link);
  58316. p = ta->obj;
  58317. /* Note: the typed array length and offset fields are not modified */
  58318. if (p->class_id != JS_CLASS_DATAVIEW) {
  58319. p->u.array.count = 0;
  58320. p->u.array.u.ptr = NULL;
  58321. }
  58322. }
  58323. }
  58324. /* get an ArrayBuffer or SharedArrayBuffer */
  58325. static JSArrayBuffer *js_get_array_buffer(JSContext *ctx, JSValueConst obj)
  58326. {
  58327. JSObject *p;
  58328. if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)
  58329. goto fail;
  58330. p = JS_VALUE_GET_OBJ(obj);
  58331. if (p->class_id != JS_CLASS_ARRAY_BUFFER &&
  58332. p->class_id != JS_CLASS_SHARED_ARRAY_BUFFER) {
  58333. fail:
  58334. JS_ThrowTypeErrorInvalidClass(ctx, JS_CLASS_ARRAY_BUFFER);
  58335. return NULL;
  58336. }
  58337. return p->u.array_buffer;
  58338. }
  58339. /* return NULL if exception. WARNING: any JS call can detach the
  58340. buffer and render the returned pointer invalid */
  58341. uint8_t *JS_GetArrayBuffer(JSContext *ctx, size_t *psize, JSValueConst obj)
  58342. {
  58343. JSArrayBuffer *abuf = js_get_array_buffer(ctx, obj);
  58344. if (!abuf)
  58345. goto fail;
  58346. if (abuf->detached) {
  58347. JS_ThrowTypeErrorDetachedArrayBuffer(ctx);
  58348. goto fail;
  58349. }
  58350. *psize = abuf->byte_length;
  58351. return abuf->data;
  58352. fail:
  58353. *psize = 0;
  58354. return NULL;
  58355. }
  58356. static bool array_buffer_is_resizable(const JSArrayBuffer *abuf)
  58357. {
  58358. return abuf->max_byte_length >= 0;
  58359. }
  58360. // ES #sec-arraybuffer.prototype.transfer
  58361. static JSValue js_array_buffer_transfer(JSContext *ctx, JSValueConst this_val,
  58362. int argc, JSValueConst *argv, int magic)
  58363. {
  58364. bool transfer_to_fixed_length = magic & 1;
  58365. JSArrayBuffer *abuf;
  58366. uint64_t new_len, old_len, max_len, *pmax_len;
  58367. uint8_t *bs, *new_bs;
  58368. abuf = JS_GetOpaque2(ctx, this_val, JS_CLASS_ARRAY_BUFFER);
  58369. if (!abuf)
  58370. return JS_EXCEPTION;
  58371. if (abuf->shared)
  58372. return JS_ThrowTypeError(ctx, "cannot transfer a SharedArrayBuffer");
  58373. if (argc < 1 || JS_IsUndefined(argv[0]))
  58374. new_len = abuf->byte_length;
  58375. else if (JS_ToIndex(ctx, &new_len, argv[0]))
  58376. return JS_EXCEPTION;
  58377. if (abuf->detached)
  58378. return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);
  58379. pmax_len = NULL;
  58380. if (!transfer_to_fixed_length) {
  58381. if (array_buffer_is_resizable(abuf)) { // carry over maxByteLength
  58382. max_len = abuf->max_byte_length;
  58383. if (new_len > max_len)
  58384. return JS_ThrowTypeError(ctx, "invalid array buffer length");
  58385. // TODO(bnoordhuis) support externally managed RABs
  58386. if (abuf->free_func == js_array_buffer_free)
  58387. pmax_len = &max_len;
  58388. }
  58389. }
  58390. /* create an empty AB */
  58391. if (new_len == 0) {
  58392. JS_DetachArrayBuffer(ctx, this_val);
  58393. return js_array_buffer_constructor2(ctx, JS_UNDEFINED, 0, pmax_len,
  58394. JS_CLASS_ARRAY_BUFFER);
  58395. }
  58396. bs = abuf->data;
  58397. old_len = abuf->byte_length;
  58398. /* if length mismatch, realloc. Otherwise, use the same backing buffer. */
  58399. if (new_len != old_len) {
  58400. new_bs = js_realloc(ctx, bs, new_len);
  58401. if (!new_bs)
  58402. return JS_EXCEPTION;
  58403. bs = new_bs;
  58404. if (new_len > old_len)
  58405. memset(bs + old_len, 0, new_len - old_len);
  58406. }
  58407. /* neuter the backing buffer */
  58408. abuf->data = NULL;
  58409. abuf->byte_length = 0;
  58410. abuf->detached = true;
  58411. return js_array_buffer_constructor3(ctx, JS_UNDEFINED, new_len, pmax_len,
  58412. JS_CLASS_ARRAY_BUFFER,
  58413. bs, abuf->free_func,
  58414. NULL, false);
  58415. }
  58416. static JSValue js_array_buffer_resize(JSContext *ctx, JSValueConst this_val,
  58417. int argc, JSValueConst *argv, int class_id)
  58418. {
  58419. uint32_t size_log2, size_elem;
  58420. struct list_head *el;
  58421. JSArrayBuffer *abuf;
  58422. JSTypedArray *ta;
  58423. JSObject *p;
  58424. uint8_t *data;
  58425. int64_t len;
  58426. abuf = JS_GetOpaque2(ctx, this_val, class_id);
  58427. if (!abuf)
  58428. return JS_EXCEPTION;
  58429. if (JS_ToInt64(ctx, &len, argv[0]))
  58430. return JS_EXCEPTION;
  58431. if (abuf->detached)
  58432. return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);
  58433. if (!array_buffer_is_resizable(abuf))
  58434. return JS_ThrowTypeError(ctx, "array buffer is not resizable");
  58435. // TODO(bnoordhuis) support externally managed RABs
  58436. if (abuf->free_func != js_array_buffer_free)
  58437. return JS_ThrowTypeError(ctx, "external array buffer is not resizable");
  58438. if (len < 0 || len > abuf->max_byte_length) {
  58439. bad_length:
  58440. return JS_ThrowRangeError(ctx, "invalid array buffer length");
  58441. }
  58442. // SABs can only grow and we don't need to realloc because
  58443. // js_array_buffer_constructor3 commits all memory upfront;
  58444. // regular RABs are resizable both ways and realloc
  58445. if (abuf->shared) {
  58446. if (len < abuf->byte_length)
  58447. goto bad_length;
  58448. // Note this is off-spec; there's supposed to be a single atomic
  58449. // |byteLength| property that's shared across SABs but we store
  58450. // it per SAB instead. That means when thread A calls sab.grow(2)
  58451. // at time t0, and thread B calls sab.grow(1) at time t1, we don't
  58452. // throw a TypeError in thread B as the spec says we should,
  58453. // instead both threads get their own view of the backing memory,
  58454. // 2 bytes big in A, and 1 byte big in B
  58455. abuf->byte_length = len;
  58456. } else {
  58457. data = js_realloc(ctx, abuf->data, max_int(len, 1));
  58458. if (!data)
  58459. return JS_EXCEPTION;
  58460. if (len > abuf->byte_length)
  58461. memset(&data[abuf->byte_length], 0, len - abuf->byte_length);
  58462. abuf->byte_length = len;
  58463. abuf->data = data;
  58464. }
  58465. data = abuf->data;
  58466. // update lengths of all typed arrays backed by this array buffer
  58467. list_for_each(el, &abuf->array_list) {
  58468. ta = list_entry(el, JSTypedArray, link);
  58469. p = ta->obj;
  58470. if (p->class_id == JS_CLASS_DATAVIEW)
  58471. continue;
  58472. p->u.array.count = 0;
  58473. p->u.array.u.ptr = NULL;
  58474. size_log2 = typed_array_size_log2(p->class_id);
  58475. size_elem = 1 << size_log2;
  58476. if (ta->track_rab) {
  58477. if (len >= (int64_t)ta->offset + size_elem) {
  58478. p->u.array.count = (len - ta->offset) >> size_log2;
  58479. p->u.array.u.ptr = &data[ta->offset];
  58480. }
  58481. } else {
  58482. if (len >= (int64_t)ta->offset + ta->length) {
  58483. p->u.array.count = ta->length >> size_log2;
  58484. p->u.array.u.ptr = &data[ta->offset];
  58485. }
  58486. }
  58487. }
  58488. return JS_UNDEFINED;
  58489. }
  58490. static JSValue js_array_buffer_slice(JSContext *ctx,
  58491. JSValueConst this_val,
  58492. int argc, JSValueConst *argv, int class_id)
  58493. {
  58494. JSArrayBuffer *abuf, *new_abuf;
  58495. int64_t len, start, end, new_len;
  58496. JSValue ctor, new_obj;
  58497. abuf = JS_GetOpaque2(ctx, this_val, class_id);
  58498. if (!abuf)
  58499. return JS_EXCEPTION;
  58500. if (abuf->detached)
  58501. return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);
  58502. len = abuf->byte_length;
  58503. if (JS_ToInt64Clamp(ctx, &start, argv[0], 0, len, len))
  58504. return JS_EXCEPTION;
  58505. end = len;
  58506. if (!JS_IsUndefined(argv[1])) {
  58507. if (JS_ToInt64Clamp(ctx, &end, argv[1], 0, len, len))
  58508. return JS_EXCEPTION;
  58509. }
  58510. new_len = max_int64(end - start, 0);
  58511. ctor = JS_SpeciesConstructor(ctx, this_val, JS_UNDEFINED);
  58512. if (JS_IsException(ctor))
  58513. return ctor;
  58514. if (JS_IsUndefined(ctor)) {
  58515. new_obj = js_array_buffer_constructor2(ctx, JS_UNDEFINED, new_len,
  58516. NULL, class_id);
  58517. } else {
  58518. JSValue args[1];
  58519. args[0] = js_int64(new_len);
  58520. new_obj = JS_CallConstructor(ctx, ctor, 1, vc(args));
  58521. JS_FreeValue(ctx, ctor);
  58522. JS_FreeValue(ctx, args[0]);
  58523. }
  58524. if (JS_IsException(new_obj))
  58525. return new_obj;
  58526. new_abuf = JS_GetOpaque2(ctx, new_obj, class_id);
  58527. if (!new_abuf)
  58528. goto fail;
  58529. if (js_same_value(ctx, new_obj, this_val)) {
  58530. JS_ThrowTypeError(ctx, "cannot use identical ArrayBuffer");
  58531. goto fail;
  58532. }
  58533. if (new_abuf->detached) {
  58534. JS_ThrowTypeErrorDetachedArrayBuffer(ctx);
  58535. goto fail;
  58536. }
  58537. if (new_abuf->byte_length < new_len) {
  58538. JS_ThrowTypeError(ctx, "new ArrayBuffer is too small");
  58539. goto fail;
  58540. }
  58541. /* must test again because of side effects */
  58542. if (abuf->detached) {
  58543. JS_ThrowTypeErrorDetachedArrayBuffer(ctx);
  58544. goto fail;
  58545. }
  58546. memcpy(new_abuf->data, abuf->data + start, new_len);
  58547. return new_obj;
  58548. fail:
  58549. JS_FreeValue(ctx, new_obj);
  58550. return JS_EXCEPTION;
  58551. }
  58552. static const JSCFunctionListEntry js_array_buffer_proto_funcs[] = {
  58553. JS_CGETSET_MAGIC_DEF("byteLength", js_array_buffer_get_byteLength, NULL, JS_CLASS_ARRAY_BUFFER ),
  58554. JS_CGETSET_MAGIC_DEF("maxByteLength", js_array_buffer_get_maxByteLength, NULL, JS_CLASS_ARRAY_BUFFER ),
  58555. JS_CGETSET_MAGIC_DEF("resizable", js_array_buffer_get_resizable, NULL, JS_CLASS_ARRAY_BUFFER ),
  58556. JS_CGETSET_DEF("detached", js_array_buffer_get_detached, NULL ),
  58557. JS_CFUNC_MAGIC_DEF("resize", 1, js_array_buffer_resize, JS_CLASS_ARRAY_BUFFER ),
  58558. JS_CFUNC_MAGIC_DEF("slice", 2, js_array_buffer_slice, JS_CLASS_ARRAY_BUFFER ),
  58559. JS_CFUNC_MAGIC_DEF("transfer", 0, js_array_buffer_transfer, 0 ),
  58560. JS_CFUNC_MAGIC_DEF("transferToFixedLength", 0, js_array_buffer_transfer, 1 ),
  58561. JS_PROP_STRING_DEF("[Symbol.toStringTag]", "ArrayBuffer", JS_PROP_CONFIGURABLE ),
  58562. };
  58563. /* SharedArrayBuffer */
  58564. static const JSCFunctionListEntry js_shared_array_buffer_funcs[] = {
  58565. JS_CGETSET_DEF("[Symbol.species]", js_get_this, NULL ),
  58566. };
  58567. static const JSCFunctionListEntry js_shared_array_buffer_proto_funcs[] = {
  58568. JS_CGETSET_MAGIC_DEF("byteLength", js_array_buffer_get_byteLength, NULL, JS_CLASS_SHARED_ARRAY_BUFFER ),
  58569. JS_CGETSET_MAGIC_DEF("maxByteLength", js_array_buffer_get_maxByteLength, NULL, JS_CLASS_SHARED_ARRAY_BUFFER ),
  58570. JS_CGETSET_MAGIC_DEF("growable", js_array_buffer_get_resizable, NULL, JS_CLASS_SHARED_ARRAY_BUFFER ),
  58571. JS_CFUNC_MAGIC_DEF("grow", 1, js_array_buffer_resize, JS_CLASS_SHARED_ARRAY_BUFFER ),
  58572. JS_CFUNC_MAGIC_DEF("slice", 2, js_array_buffer_slice, JS_CLASS_SHARED_ARRAY_BUFFER ),
  58573. JS_PROP_STRING_DEF("[Symbol.toStringTag]", "SharedArrayBuffer", JS_PROP_CONFIGURABLE ),
  58574. };
  58575. static bool is_typed_array(JSClassID class_id)
  58576. {
  58577. return class_id >= JS_CLASS_UINT8C_ARRAY && class_id <= JS_CLASS_FLOAT64_ARRAY;
  58578. }
  58579. // is the typed array detached or out of bounds relative to its RAB?
  58580. // |p| must be a typed array, *not* a DataView
  58581. static bool typed_array_is_oob(JSObject *p)
  58582. {
  58583. JSArrayBuffer *abuf;
  58584. JSTypedArray *ta;
  58585. int len, size_elem;
  58586. int64_t end;
  58587. assert(is_typed_array(p->class_id));
  58588. ta = p->u.typed_array;
  58589. abuf = ta->buffer->u.array_buffer;
  58590. if (abuf->detached)
  58591. return true;
  58592. len = abuf->byte_length;
  58593. if (ta->offset > len)
  58594. return true;
  58595. if (ta->track_rab)
  58596. return false;
  58597. if (len < (int64_t)ta->offset + ta->length)
  58598. return true;
  58599. size_elem = 1 << typed_array_size_log2(p->class_id);
  58600. end = (int64_t)ta->offset + (int64_t)p->u.array.count * size_elem;
  58601. return end > len;
  58602. }
  58603. /* WARNING: 'p' must be a typed array. Works even if the array buffer
  58604. is detached */
  58605. static uint32_t typed_array_get_length(JSContext *ctx, JSObject *p)
  58606. {
  58607. JSTypedArray *ta = p->u.typed_array;
  58608. int size_log2 = typed_array_size_log2(p->class_id);
  58609. return ta->length >> size_log2;
  58610. }
  58611. static int validate_typed_array(JSContext *ctx, JSValueConst this_val)
  58612. {
  58613. JSObject *p;
  58614. p = get_typed_array(ctx, this_val);
  58615. if (!p)
  58616. return -1;
  58617. if (typed_array_is_oob(p)) {
  58618. JS_ThrowTypeErrorArrayBufferOOB(ctx);
  58619. return -1;
  58620. }
  58621. return 0;
  58622. }
  58623. static JSValue js_typed_array_get_length(JSContext *ctx, JSValueConst this_val)
  58624. {
  58625. JSObject *p;
  58626. p = get_typed_array(ctx, this_val);
  58627. if (!p)
  58628. return JS_EXCEPTION;
  58629. return js_int32(p->u.array.count);
  58630. }
  58631. static JSValue js_typed_array_get_buffer(JSContext *ctx, JSValueConst this_val)
  58632. {
  58633. JSObject *p;
  58634. JSTypedArray *ta;
  58635. p = get_typed_array(ctx, this_val);
  58636. if (!p)
  58637. return JS_EXCEPTION;
  58638. ta = p->u.typed_array;
  58639. return js_dup(JS_MKPTR(JS_TAG_OBJECT, ta->buffer));
  58640. }
  58641. static JSValue js_typed_array_get_byteLength(JSContext *ctx, JSValueConst this_val)
  58642. {
  58643. uint32_t size_log2;
  58644. JSTypedArray *ta;
  58645. JSObject *p;
  58646. p = get_typed_array(ctx, this_val);
  58647. if (!p)
  58648. return JS_EXCEPTION;
  58649. if (typed_array_is_oob(p))
  58650. return js_int32(0);
  58651. ta = p->u.typed_array;
  58652. if (!ta->track_rab)
  58653. return js_uint32(ta->length);
  58654. size_log2 = typed_array_size_log2(p->class_id);
  58655. return js_int64((int64_t)p->u.array.count << size_log2);
  58656. }
  58657. static JSValue js_typed_array_get_byteOffset(JSContext *ctx, JSValueConst this_val)
  58658. {
  58659. JSObject *p;
  58660. JSTypedArray *ta;
  58661. p = get_typed_array(ctx, this_val);
  58662. if (!p)
  58663. return JS_EXCEPTION;
  58664. if (typed_array_is_oob(p))
  58665. return js_int32(0);
  58666. ta = p->u.typed_array;
  58667. return js_uint32(ta->offset);
  58668. }
  58669. JSValue JS_NewTypedArray(JSContext *ctx, int argc, JSValueConst *argv,
  58670. JSTypedArrayEnum type)
  58671. {
  58672. if (type < JS_TYPED_ARRAY_UINT8C || type > JS_TYPED_ARRAY_FLOAT64)
  58673. return JS_ThrowRangeError(ctx, "invalid typed array type");
  58674. return js_typed_array_constructor(ctx, JS_UNDEFINED, argc, argv,
  58675. JS_CLASS_UINT8C_ARRAY + type);
  58676. }
  58677. /* Return the buffer associated to the typed array or an exception if
  58678. it is not a typed array or if the buffer is detached. pbyte_offset,
  58679. pbyte_length or pbytes_per_element can be NULL. */
  58680. JSValue JS_GetTypedArrayBuffer(JSContext *ctx, JSValueConst obj,
  58681. size_t *pbyte_offset,
  58682. size_t *pbyte_length,
  58683. size_t *pbytes_per_element)
  58684. {
  58685. JSObject *p;
  58686. JSTypedArray *ta;
  58687. p = get_typed_array(ctx, obj);
  58688. if (!p)
  58689. return JS_EXCEPTION;
  58690. if (typed_array_is_oob(p))
  58691. return JS_ThrowTypeErrorArrayBufferOOB(ctx);
  58692. ta = p->u.typed_array;
  58693. if (pbyte_offset)
  58694. *pbyte_offset = ta->offset;
  58695. if (pbyte_length)
  58696. *pbyte_length = ta->length;
  58697. if (pbytes_per_element) {
  58698. *pbytes_per_element = 1 << typed_array_size_log2(p->class_id);
  58699. }
  58700. return js_dup(JS_MKPTR(JS_TAG_OBJECT, ta->buffer));
  58701. }
  58702. /* return NULL if exception. WARNING: any JS call can detach the
  58703. buffer and render the returned pointer invalid */
  58704. uint8_t *JS_GetUint8Array(JSContext *ctx, size_t *psize, JSValueConst obj)
  58705. {
  58706. JSObject *p;
  58707. JSTypedArray *ta;
  58708. JSArrayBuffer *abuf;
  58709. p = get_typed_array(ctx, obj);
  58710. if (!p)
  58711. goto fail;
  58712. if (typed_array_is_oob(p)) {
  58713. JS_ThrowTypeErrorArrayBufferOOB(ctx);
  58714. goto fail;
  58715. }
  58716. if (p->class_id != JS_CLASS_UINT8_ARRAY && p->class_id != JS_CLASS_UINT8C_ARRAY) {
  58717. JS_ThrowTypeError(ctx, "not a Uint8Array");
  58718. goto fail;
  58719. }
  58720. ta = p->u.typed_array;
  58721. abuf = ta->buffer->u.array_buffer;
  58722. *psize = ta->length;
  58723. return abuf->data + ta->offset;
  58724. fail:
  58725. *psize = 0;
  58726. return NULL;
  58727. }
  58728. static JSValue js_typed_array_get_toStringTag(JSContext *ctx,
  58729. JSValueConst this_val)
  58730. {
  58731. JSObject *p;
  58732. if (JS_VALUE_GET_TAG(this_val) != JS_TAG_OBJECT)
  58733. return JS_UNDEFINED;
  58734. p = JS_VALUE_GET_OBJ(this_val);
  58735. if (!is_typed_array(p->class_id))
  58736. return JS_UNDEFINED;
  58737. return JS_AtomToString(ctx, ctx->rt->class_array[p->class_id].class_name);
  58738. }
  58739. static JSValue js_typed_array_set_internal(JSContext *ctx,
  58740. JSValueConst dst,
  58741. JSValueConst src,
  58742. JSValueConst off)
  58743. {
  58744. JSObject *p;
  58745. JSObject *src_p;
  58746. uint32_t i;
  58747. int64_t dst_len, src_len, offset;
  58748. JSValue val, src_obj = JS_UNDEFINED;
  58749. p = get_typed_array(ctx, dst);
  58750. if (!p)
  58751. goto fail;
  58752. if (JS_ToInt64Sat(ctx, &offset, off))
  58753. goto fail;
  58754. if (offset < 0)
  58755. goto range_error;
  58756. if (typed_array_is_oob(p)) {
  58757. detached:
  58758. JS_ThrowTypeErrorArrayBufferOOB(ctx);
  58759. goto fail;
  58760. }
  58761. dst_len = p->u.array.count;
  58762. src_obj = JS_ToObject(ctx, src);
  58763. if (JS_IsException(src_obj))
  58764. goto fail;
  58765. src_p = JS_VALUE_GET_OBJ(src_obj);
  58766. if (is_typed_array(src_p->class_id)) {
  58767. JSTypedArray *dest_ta = p->u.typed_array;
  58768. JSArrayBuffer *dest_abuf = dest_ta->buffer->u.array_buffer;
  58769. JSTypedArray *src_ta = src_p->u.typed_array;
  58770. JSArrayBuffer *src_abuf = src_ta->buffer->u.array_buffer;
  58771. int shift = typed_array_size_log2(p->class_id);
  58772. if (typed_array_is_oob(src_p))
  58773. goto detached;
  58774. src_len = src_p->u.array.count;
  58775. if (offset > dst_len - src_len)
  58776. goto range_error;
  58777. /* copying between typed objects */
  58778. if (src_p->class_id == p->class_id) {
  58779. /* same type, use memmove */
  58780. memmove(dest_abuf->data + dest_ta->offset + (offset << shift),
  58781. src_abuf->data + src_ta->offset, src_len << shift);
  58782. goto done;
  58783. }
  58784. if (dest_abuf->data == src_abuf->data) {
  58785. /* copying between the same buffer using different types of mappings
  58786. would require a temporary buffer */
  58787. }
  58788. /* otherwise, default behavior is slow but correct */
  58789. } else {
  58790. // can change |dst| as a side effect; per spec,
  58791. // perform the range check against its old length
  58792. if (js_get_length64(ctx, &src_len, src_obj))
  58793. goto fail;
  58794. if (offset > dst_len - src_len) {
  58795. range_error:
  58796. JS_ThrowRangeError(ctx, "invalid array length");
  58797. goto fail;
  58798. }
  58799. }
  58800. for(i = 0; i < src_len; i++) {
  58801. val = JS_GetPropertyUint32(ctx, src_obj, i);
  58802. if (JS_IsException(val))
  58803. goto fail;
  58804. // Per spec: detaching the TA mid-iteration is allowed and should
  58805. // not throw an exception. Because iteration over the source array is
  58806. // observable, we cannot bail out early when the TA is first detached.
  58807. if (typed_array_is_oob(p)) {
  58808. JS_FreeValue(ctx, val);
  58809. } else if (JS_SetPropertyUint32(ctx, dst, offset + i, val) < 0) {
  58810. goto fail;
  58811. }
  58812. }
  58813. done:
  58814. JS_FreeValue(ctx, src_obj);
  58815. return JS_UNDEFINED;
  58816. fail:
  58817. JS_FreeValue(ctx, src_obj);
  58818. return JS_EXCEPTION;
  58819. }
  58820. static JSValue js_typed_array_at(JSContext *ctx, JSValueConst this_val,
  58821. int argc, JSValueConst *argv)
  58822. {
  58823. JSObject *p;
  58824. int64_t idx, len;
  58825. p = get_typed_array(ctx, this_val);
  58826. if (!p)
  58827. return JS_EXCEPTION;
  58828. if (typed_array_is_oob(p))
  58829. return JS_ThrowTypeErrorArrayBufferOOB(ctx);
  58830. len = p->u.array.count;
  58831. // note: can change p->u.array.count
  58832. if (JS_ToInt64Sat(ctx, &idx, argv[0]))
  58833. return JS_EXCEPTION;
  58834. if (idx < 0)
  58835. idx = len + idx;
  58836. if (idx < 0 || idx >= p->u.array.count)
  58837. return JS_UNDEFINED;
  58838. switch (p->class_id) {
  58839. case JS_CLASS_INT8_ARRAY:
  58840. return js_int32(p->u.array.u.int8_ptr[idx]);
  58841. case JS_CLASS_UINT8C_ARRAY:
  58842. case JS_CLASS_UINT8_ARRAY:
  58843. return js_int32(p->u.array.u.uint8_ptr[idx]);
  58844. case JS_CLASS_INT16_ARRAY:
  58845. return js_int32(p->u.array.u.int16_ptr[idx]);
  58846. case JS_CLASS_UINT16_ARRAY:
  58847. return js_int32(p->u.array.u.uint16_ptr[idx]);
  58848. case JS_CLASS_INT32_ARRAY:
  58849. return js_int32(p->u.array.u.int32_ptr[idx]);
  58850. case JS_CLASS_UINT32_ARRAY:
  58851. return js_uint32(p->u.array.u.uint32_ptr[idx]);
  58852. case JS_CLASS_FLOAT16_ARRAY:
  58853. return js_float64(fromfp16(p->u.array.u.fp16_ptr[idx]));
  58854. case JS_CLASS_FLOAT32_ARRAY:
  58855. return js_float64(p->u.array.u.float_ptr[idx]);
  58856. case JS_CLASS_FLOAT64_ARRAY:
  58857. return js_float64(p->u.array.u.double_ptr[idx]);
  58858. case JS_CLASS_BIG_INT64_ARRAY:
  58859. return JS_NewBigInt64(ctx, p->u.array.u.int64_ptr[idx]);
  58860. case JS_CLASS_BIG_UINT64_ARRAY:
  58861. return JS_NewBigUint64(ctx, p->u.array.u.uint64_ptr[idx]);
  58862. }
  58863. abort(); /* unreachable */
  58864. return JS_UNDEFINED;
  58865. }
  58866. static JSValue js_typed_array_with(JSContext *ctx, JSValueConst this_val,
  58867. int argc, JSValueConst *argv)
  58868. {
  58869. JSValue arr, val;
  58870. JSObject *p;
  58871. int64_t idx;
  58872. uint32_t len, oldlen, newlen;
  58873. p = get_typed_array(ctx, this_val);
  58874. if (!p)
  58875. return JS_EXCEPTION;
  58876. oldlen = p->u.array.count;
  58877. if (JS_ToInt64Sat(ctx, &idx, argv[0]))
  58878. return JS_EXCEPTION;
  58879. val = JS_ToPrimitive(ctx, argv[1], HINT_NUMBER);
  58880. if (JS_IsException(val))
  58881. return JS_EXCEPTION;
  58882. newlen = p->u.array.count;
  58883. if (idx < 0)
  58884. idx = newlen + idx;
  58885. if (idx < 0 || idx >= newlen) {
  58886. JS_FreeValue(ctx, val);
  58887. return JS_ThrowRangeError(ctx, "invalid array index");
  58888. }
  58889. len = min_uint32(oldlen, newlen);
  58890. arr = js_typed_array_constructor_ta(ctx, JS_UNDEFINED, this_val,
  58891. p->class_id, len);
  58892. if (JS_IsException(arr)) {
  58893. JS_FreeValue(ctx, val);
  58894. return JS_EXCEPTION;
  58895. }
  58896. if (idx < len && JS_SetPropertyInt64(ctx, arr, idx, val) < 0) {
  58897. JS_FreeValue(ctx, arr);
  58898. return JS_EXCEPTION;
  58899. }
  58900. return arr;
  58901. }
  58902. static JSValue js_typed_array_set(JSContext *ctx,
  58903. JSValueConst this_val,
  58904. int argc, JSValueConst *argv)
  58905. {
  58906. JSValueConst offset = JS_UNDEFINED;
  58907. if (argc > 1) {
  58908. offset = argv[1];
  58909. }
  58910. return js_typed_array_set_internal(ctx, this_val, argv[0], offset);
  58911. }
  58912. static JSValue js_create_typed_array_iterator(JSContext *ctx, JSValueConst this_val,
  58913. int argc, JSValueConst *argv, int magic)
  58914. {
  58915. if (validate_typed_array(ctx, this_val))
  58916. return JS_EXCEPTION;
  58917. return js_create_array_iterator(ctx, this_val, argc, argv, magic);
  58918. }
  58919. static JSValue js_typed_array_create(JSContext *ctx, JSValueConst ctor,
  58920. int argc, JSValueConst *argv)
  58921. {
  58922. JSValue ret;
  58923. int new_len;
  58924. int64_t len;
  58925. ret = JS_CallConstructor(ctx, ctor, argc, argv);
  58926. if (JS_IsException(ret))
  58927. return ret;
  58928. /* validate the typed array */
  58929. new_len = js_typed_array_get_length_unsafe(ctx, ret);
  58930. if (new_len < 0)
  58931. goto fail;
  58932. if (argc == 1) {
  58933. /* ensure that it is large enough */
  58934. if (JS_ToLengthFree(ctx, &len, js_dup(argv[0])))
  58935. goto fail;
  58936. if (new_len < len) {
  58937. JS_ThrowTypeError(ctx, "TypedArray length is too small");
  58938. fail:
  58939. JS_FreeValue(ctx, ret);
  58940. return JS_EXCEPTION;
  58941. }
  58942. }
  58943. return ret;
  58944. }
  58945. static JSValue js_typed_array___speciesCreate(JSContext *ctx,
  58946. JSValueConst this_val,
  58947. int argc, JSValueConst *argv)
  58948. {
  58949. JSValueConst obj;
  58950. JSObject *p;
  58951. JSValue ctor, ret;
  58952. int argc1;
  58953. obj = argv[0];
  58954. p = get_typed_array(ctx, obj);
  58955. if (!p)
  58956. return JS_EXCEPTION;
  58957. ctor = JS_SpeciesConstructor(ctx, obj, JS_UNDEFINED);
  58958. if (JS_IsException(ctor))
  58959. return ctor;
  58960. argc1 = max_int(argc - 1, 0);
  58961. if (JS_IsUndefined(ctor)) {
  58962. ret = js_typed_array_constructor(ctx, JS_UNDEFINED, argc1, argv + 1,
  58963. p->class_id);
  58964. } else {
  58965. ret = js_typed_array_create(ctx, ctor, argc1, argv + 1);
  58966. JS_FreeValue(ctx, ctor);
  58967. }
  58968. return ret;
  58969. }
  58970. static JSValue js_typed_array_from(JSContext *ctx, JSValueConst this_val,
  58971. int argc, JSValueConst *argv)
  58972. {
  58973. // from(items, mapfn = void 0, this_arg = void 0)
  58974. JSValueConst items = argv[0], mapfn, this_arg;
  58975. JSValueConst args[2];
  58976. JSValue stack[2];
  58977. JSValue iter, arr, r, v, v2;
  58978. int64_t k, len;
  58979. int done, mapping;
  58980. mapping = false;
  58981. mapfn = JS_UNDEFINED;
  58982. this_arg = JS_UNDEFINED;
  58983. r = JS_UNDEFINED;
  58984. arr = JS_UNDEFINED;
  58985. stack[0] = JS_UNDEFINED;
  58986. stack[1] = JS_UNDEFINED;
  58987. if (argc > 1) {
  58988. mapfn = argv[1];
  58989. if (!JS_IsUndefined(mapfn)) {
  58990. if (check_function(ctx, mapfn))
  58991. goto exception;
  58992. mapping = 1;
  58993. if (argc > 2)
  58994. this_arg = argv[2];
  58995. }
  58996. }
  58997. iter = JS_GetProperty(ctx, items, JS_ATOM_Symbol_iterator);
  58998. if (JS_IsException(iter))
  58999. goto exception;
  59000. if (!JS_IsUndefined(iter)) {
  59001. JS_FreeValue(ctx, iter);
  59002. arr = JS_NewArray(ctx);
  59003. if (JS_IsException(arr))
  59004. goto exception;
  59005. stack[0] = js_dup(items);
  59006. if (js_for_of_start(ctx, &stack[1], false))
  59007. goto exception;
  59008. for (k = 0;; k++) {
  59009. v = JS_IteratorNext(ctx, stack[0], stack[1], 0, NULL, &done);
  59010. if (JS_IsException(v))
  59011. goto exception_close;
  59012. if (done)
  59013. break;
  59014. if (JS_DefinePropertyValueInt64(ctx, arr, k, v, JS_PROP_C_W_E | JS_PROP_THROW) < 0)
  59015. goto exception_close;
  59016. }
  59017. } else {
  59018. arr = JS_ToObject(ctx, items);
  59019. if (JS_IsException(arr))
  59020. goto exception;
  59021. }
  59022. if (js_get_length64(ctx, &len, arr) < 0)
  59023. goto exception;
  59024. v = js_int64(len);
  59025. r = js_typed_array_create(ctx, this_val, 1, vc(&v));
  59026. JS_FreeValue(ctx, v);
  59027. if (JS_IsException(r))
  59028. goto exception;
  59029. for(k = 0; k < len; k++) {
  59030. v = JS_GetPropertyInt64(ctx, arr, k);
  59031. if (JS_IsException(v))
  59032. goto exception;
  59033. if (mapping) {
  59034. args[0] = v;
  59035. args[1] = js_int32(k);
  59036. v2 = JS_Call(ctx, mapfn, this_arg, 2, args);
  59037. JS_FreeValue(ctx, v);
  59038. v = v2;
  59039. if (JS_IsException(v))
  59040. goto exception;
  59041. }
  59042. if (JS_SetPropertyInt64(ctx, r, k, v) < 0)
  59043. goto exception;
  59044. }
  59045. goto done;
  59046. exception_close:
  59047. if (!JS_IsUndefined(stack[0]))
  59048. JS_IteratorClose(ctx, stack[0], true);
  59049. exception:
  59050. JS_FreeValue(ctx, r);
  59051. r = JS_EXCEPTION;
  59052. done:
  59053. JS_FreeValue(ctx, arr);
  59054. JS_FreeValue(ctx, stack[0]);
  59055. JS_FreeValue(ctx, stack[1]);
  59056. return r;
  59057. }
  59058. static JSValue js_typed_array_of(JSContext *ctx, JSValueConst this_val,
  59059. int argc, JSValueConst *argv)
  59060. {
  59061. JSValue v, obj;
  59062. int i;
  59063. v = js_int32(argc);
  59064. obj = js_typed_array_create(ctx, this_val, 1, vc(&v));
  59065. if (JS_IsException(obj))
  59066. return obj;
  59067. for(i = 0; i < argc; i++) {
  59068. if (JS_SetPropertyUint32(ctx, obj, i, js_dup(argv[i])) < 0) {
  59069. JS_FreeValue(ctx, obj);
  59070. return JS_EXCEPTION;
  59071. }
  59072. }
  59073. return obj;
  59074. }
  59075. static JSValue js_typed_array_copyWithin(JSContext *ctx, JSValueConst this_val,
  59076. int argc, JSValueConst *argv)
  59077. {
  59078. JSObject *p;
  59079. int len, to, from, final, count, shift, space;
  59080. p = get_typed_array(ctx, this_val);
  59081. if (!p)
  59082. return JS_EXCEPTION;
  59083. if (typed_array_is_oob(p))
  59084. return JS_ThrowTypeErrorArrayBufferOOB(ctx);
  59085. len = p->u.array.count;
  59086. if (JS_ToInt32Clamp(ctx, &to, argv[0], 0, len, len))
  59087. return JS_EXCEPTION;
  59088. if (JS_ToInt32Clamp(ctx, &from, argv[1], 0, len, len))
  59089. return JS_EXCEPTION;
  59090. final = len;
  59091. if (argc > 2 && !JS_IsUndefined(argv[2])) {
  59092. if (JS_ToInt32Clamp(ctx, &final, argv[2], 0, len, len))
  59093. return JS_EXCEPTION;
  59094. }
  59095. if (typed_array_is_oob(p))
  59096. return JS_ThrowTypeErrorArrayBufferOOB(ctx);
  59097. // RAB may have been resized by evil .valueOf method
  59098. space = p->u.array.count - max_int(to, from);
  59099. count = min_int(final - from, len - to);
  59100. count = min_int(count, space);
  59101. if (count > 0) {
  59102. shift = typed_array_size_log2(p->class_id);
  59103. memmove(p->u.array.u.uint8_ptr + (to << shift),
  59104. p->u.array.u.uint8_ptr + (from << shift),
  59105. count << shift);
  59106. }
  59107. return js_dup(this_val);
  59108. }
  59109. static JSValue js_typed_array_fill(JSContext *ctx, JSValueConst this_val,
  59110. int argc, JSValueConst *argv)
  59111. {
  59112. JSObject *p;
  59113. int len, k, final, shift;
  59114. uint64_t v64;
  59115. p = get_typed_array(ctx, this_val);
  59116. if (!p)
  59117. return JS_EXCEPTION;
  59118. if (typed_array_is_oob(p))
  59119. return JS_ThrowTypeErrorArrayBufferOOB(ctx);
  59120. len = p->u.array.count;
  59121. if (p->class_id == JS_CLASS_UINT8C_ARRAY) {
  59122. int32_t v;
  59123. if (JS_ToUint8ClampFree(ctx, &v, js_dup(argv[0])))
  59124. return JS_EXCEPTION;
  59125. v64 = v;
  59126. } else if (p->class_id <= JS_CLASS_UINT32_ARRAY) {
  59127. uint32_t v;
  59128. if (JS_ToUint32(ctx, &v, argv[0]))
  59129. return JS_EXCEPTION;
  59130. v64 = v;
  59131. } else
  59132. if (p->class_id <= JS_CLASS_BIG_UINT64_ARRAY) {
  59133. if (JS_ToBigInt64(ctx, (int64_t *)&v64, argv[0]))
  59134. return JS_EXCEPTION;
  59135. } else {
  59136. double d;
  59137. if (JS_ToFloat64(ctx, &d, argv[0]))
  59138. return JS_EXCEPTION;
  59139. if (p->class_id == JS_CLASS_FLOAT16_ARRAY) {
  59140. v64 = tofp16(d);
  59141. } else if (p->class_id == JS_CLASS_FLOAT32_ARRAY) {
  59142. union {
  59143. float f;
  59144. uint32_t u32;
  59145. } u;
  59146. u.f = d;
  59147. v64 = u.u32;
  59148. } else {
  59149. JSFloat64Union u;
  59150. u.d = d;
  59151. v64 = u.u64;
  59152. }
  59153. }
  59154. k = 0;
  59155. if (argc > 1) {
  59156. if (JS_ToInt32Clamp(ctx, &k, argv[1], 0, len, len))
  59157. return JS_EXCEPTION;
  59158. }
  59159. final = len;
  59160. if (argc > 2 && !JS_IsUndefined(argv[2])) {
  59161. if (JS_ToInt32Clamp(ctx, &final, argv[2], 0, len, len))
  59162. return JS_EXCEPTION;
  59163. }
  59164. if (typed_array_is_oob(p))
  59165. return JS_ThrowTypeErrorArrayBufferOOB(ctx);
  59166. // RAB may have been resized by evil .valueOf method
  59167. final = min_int(final, p->u.array.count);
  59168. shift = typed_array_size_log2(p->class_id);
  59169. switch(shift) {
  59170. case 0:
  59171. if (k < final) {
  59172. memset(p->u.array.u.uint8_ptr + k, v64, final - k);
  59173. }
  59174. break;
  59175. case 1:
  59176. for(; k < final; k++) {
  59177. p->u.array.u.uint16_ptr[k] = v64;
  59178. }
  59179. break;
  59180. case 2:
  59181. for(; k < final; k++) {
  59182. p->u.array.u.uint32_ptr[k] = v64;
  59183. }
  59184. break;
  59185. case 3:
  59186. for(; k < final; k++) {
  59187. p->u.array.u.uint64_ptr[k] = v64;
  59188. }
  59189. break;
  59190. default:
  59191. abort();
  59192. }
  59193. return js_dup(this_val);
  59194. }
  59195. static JSValue js_typed_array_find(JSContext *ctx, JSValueConst this_val,
  59196. int argc, JSValueConst *argv, int mode)
  59197. {
  59198. JSValueConst func, this_arg, args[3];
  59199. JSValue val, index_val, res;
  59200. int len, k, end;
  59201. int dir;
  59202. val = JS_UNDEFINED;
  59203. len = js_typed_array_get_length_unsafe(ctx, this_val);
  59204. if (len < 0)
  59205. goto exception;
  59206. func = argv[0];
  59207. if (check_function(ctx, func))
  59208. goto exception;
  59209. this_arg = JS_UNDEFINED;
  59210. if (argc > 1)
  59211. this_arg = argv[1];
  59212. k = 0;
  59213. dir = 1;
  59214. end = len;
  59215. if (mode == ArrayFindLast || mode == ArrayFindLastIndex) {
  59216. k = len - 1;
  59217. dir = -1;
  59218. end = -1;
  59219. }
  59220. for(; k != end; k += dir) {
  59221. index_val = js_int32(k);
  59222. val = JS_GetPropertyValue(ctx, this_val, index_val);
  59223. if (JS_IsException(val))
  59224. goto exception;
  59225. args[0] = val;
  59226. args[1] = index_val;
  59227. args[2] = this_val;
  59228. res = JS_Call(ctx, func, this_arg, 3, args);
  59229. if (JS_IsException(res))
  59230. goto exception;
  59231. if (JS_ToBoolFree(ctx, res)) {
  59232. if (mode == ArrayFindIndex || mode == ArrayFindLastIndex) {
  59233. JS_FreeValue(ctx, val);
  59234. return index_val;
  59235. } else {
  59236. return val;
  59237. }
  59238. }
  59239. JS_FreeValue(ctx, val);
  59240. }
  59241. if (mode == ArrayFindIndex || mode == ArrayFindLastIndex)
  59242. return js_int32(-1);
  59243. else
  59244. return JS_UNDEFINED;
  59245. exception:
  59246. JS_FreeValue(ctx, val);
  59247. return JS_EXCEPTION;
  59248. }
  59249. #define special_indexOf 0
  59250. #define special_lastIndexOf 1
  59251. #define special_includes -1
  59252. static JSValue js_typed_array_indexOf(JSContext *ctx, JSValueConst this_val,
  59253. int argc, JSValueConst *argv, int special)
  59254. {
  59255. JSObject *p;
  59256. int len, tag, is_int, is_bigint, k, stop, inc, res = -1;
  59257. int64_t v64;
  59258. double d;
  59259. float f;
  59260. uint16_t hf;
  59261. bool oob;
  59262. p = get_typed_array(ctx, this_val);
  59263. if (!p)
  59264. return JS_EXCEPTION;
  59265. if (typed_array_is_oob(p))
  59266. return JS_ThrowTypeErrorArrayBufferOOB(ctx);
  59267. len = p->u.array.count;
  59268. if (len == 0)
  59269. goto done;
  59270. oob = false;
  59271. if (special == special_lastIndexOf) {
  59272. k = len - 1;
  59273. if (argc > 1) {
  59274. if (JS_ToFloat64(ctx, &d, argv[1]))
  59275. goto exception;
  59276. if (isnan(d)) {
  59277. k = 0;
  59278. } else {
  59279. if (d >= 0) {
  59280. if (d < k) {
  59281. k = d;
  59282. }
  59283. } else {
  59284. d += len;
  59285. if (d < 0)
  59286. goto done;
  59287. k = d;
  59288. }
  59289. }
  59290. }
  59291. stop = -1;
  59292. inc = -1;
  59293. } else {
  59294. k = 0;
  59295. if (argc > 1) {
  59296. if (JS_ToInt32Sat(ctx, &k, argv[1]))
  59297. goto exception;
  59298. if (k < 0) {
  59299. k += len;
  59300. if (k < 0)
  59301. k = 0;
  59302. } else if (k > len) {
  59303. k = len;
  59304. oob = true;
  59305. }
  59306. }
  59307. stop = len;
  59308. inc = 1;
  59309. }
  59310. /* if the array was detached, no need to go further (but no
  59311. exception is raised) */
  59312. if (typed_array_is_oob(p) || len > p->u.array.count) {
  59313. /* "includes" scans all the properties, so "undefined" can match */
  59314. if (special == special_includes && JS_IsUndefined(argv[0]) && len > 0)
  59315. res = oob ? -1 : 0;
  59316. goto done;
  59317. }
  59318. // RAB may have been resized by evil .valueOf method
  59319. len = min_int(len, p->u.array.count);
  59320. if (len == 0)
  59321. goto done;
  59322. k = min_int(k, len);
  59323. stop = min_int(stop, len);
  59324. is_bigint = 0;
  59325. is_int = 0; /* avoid warning */
  59326. v64 = 0; /* avoid warning */
  59327. tag = JS_VALUE_GET_NORM_TAG(argv[0]);
  59328. if (tag == JS_TAG_INT) {
  59329. is_int = 1;
  59330. v64 = JS_VALUE_GET_INT(argv[0]);
  59331. d = v64;
  59332. } else
  59333. if (tag == JS_TAG_FLOAT64) {
  59334. d = JS_VALUE_GET_FLOAT64(argv[0]);
  59335. if (d >= INT64_MIN && d < 0x1p63) {
  59336. v64 = d;
  59337. is_int = (v64 == d);
  59338. }
  59339. } else
  59340. if (tag == JS_TAG_BIG_INT) {
  59341. JSBigInt *p1 = JS_VALUE_GET_PTR(argv[0]);
  59342. if (p->class_id == JS_CLASS_BIG_INT64_ARRAY) {
  59343. if (bf_get_int64(&v64, &p1->num, 0) != 0)
  59344. goto done;
  59345. } else if (p->class_id == JS_CLASS_BIG_UINT64_ARRAY) {
  59346. if (bf_get_uint64((uint64_t *)&v64, &p1->num) != 0)
  59347. goto done;
  59348. } else {
  59349. goto done;
  59350. }
  59351. d = 0;
  59352. is_bigint = 1;
  59353. } else {
  59354. goto done;
  59355. }
  59356. switch (p->class_id) {
  59357. case JS_CLASS_INT8_ARRAY:
  59358. if (is_int && (int8_t)v64 == v64)
  59359. goto scan8;
  59360. break;
  59361. case JS_CLASS_UINT8C_ARRAY:
  59362. case JS_CLASS_UINT8_ARRAY:
  59363. if (is_int && (uint8_t)v64 == v64) {
  59364. const uint8_t *pv, *pp;
  59365. uint16_t v;
  59366. scan8:
  59367. pv = p->u.array.u.uint8_ptr;
  59368. v = v64;
  59369. if (inc > 0) {
  59370. pp = NULL;
  59371. if (pv)
  59372. pp = memchr(pv + k, v, len - k);
  59373. if (pp)
  59374. res = pp - pv;
  59375. } else {
  59376. for (; k != stop; k += inc) {
  59377. if (pv[k] == v) {
  59378. res = k;
  59379. break;
  59380. }
  59381. }
  59382. }
  59383. }
  59384. break;
  59385. case JS_CLASS_INT16_ARRAY:
  59386. if (is_int && (int16_t)v64 == v64)
  59387. goto scan16;
  59388. break;
  59389. case JS_CLASS_UINT16_ARRAY:
  59390. if (is_int && (uint16_t)v64 == v64) {
  59391. const uint16_t *pv;
  59392. uint16_t v;
  59393. scan16:
  59394. pv = p->u.array.u.uint16_ptr;
  59395. v = v64;
  59396. for (; k != stop; k += inc) {
  59397. if (pv[k] == v) {
  59398. res = k;
  59399. break;
  59400. }
  59401. }
  59402. }
  59403. break;
  59404. case JS_CLASS_INT32_ARRAY:
  59405. if (is_int && (int32_t)v64 == v64)
  59406. goto scan32;
  59407. break;
  59408. case JS_CLASS_UINT32_ARRAY:
  59409. if (is_int && (uint32_t)v64 == v64) {
  59410. const uint32_t *pv;
  59411. uint32_t v;
  59412. scan32:
  59413. pv = p->u.array.u.uint32_ptr;
  59414. v = v64;
  59415. for (; k != stop; k += inc) {
  59416. if (pv[k] == v) {
  59417. res = k;
  59418. break;
  59419. }
  59420. }
  59421. }
  59422. break;
  59423. case JS_CLASS_FLOAT16_ARRAY:
  59424. if (is_bigint)
  59425. break;
  59426. if (isnan(d)) {
  59427. const uint16_t *pv = p->u.array.u.fp16_ptr;
  59428. /* special case: indexOf returns -1, includes finds NaN */
  59429. if (special != special_includes)
  59430. goto done;
  59431. for (; k != stop; k += inc) {
  59432. if (isfp16nan(pv[k])) {
  59433. res = k;
  59434. break;
  59435. }
  59436. }
  59437. } else if (d == 0) {
  59438. // special case: includes also finds negative zero
  59439. const uint16_t *pv = p->u.array.u.fp16_ptr;
  59440. for (; k != stop; k += inc) {
  59441. if (isfp16zero(pv[k])) {
  59442. res = k;
  59443. break;
  59444. }
  59445. }
  59446. } else if (hf = tofp16(d), d == fromfp16(hf)) {
  59447. const uint16_t *pv = p->u.array.u.fp16_ptr;
  59448. for (; k != stop; k += inc) {
  59449. if (pv[k] == hf) {
  59450. res = k;
  59451. break;
  59452. }
  59453. }
  59454. }
  59455. break;
  59456. case JS_CLASS_FLOAT32_ARRAY:
  59457. if (is_bigint)
  59458. break;
  59459. if (isnan(d)) {
  59460. const float *pv = p->u.array.u.float_ptr;
  59461. /* special case: indexOf returns -1, includes finds NaN */
  59462. if (special != special_includes)
  59463. goto done;
  59464. for (; k != stop; k += inc) {
  59465. if (isnan(pv[k])) {
  59466. res = k;
  59467. break;
  59468. }
  59469. }
  59470. } else if ((f = (float)d) == d) {
  59471. const float *pv = p->u.array.u.float_ptr;
  59472. for (; k != stop; k += inc) {
  59473. if (pv[k] == f) {
  59474. res = k;
  59475. break;
  59476. }
  59477. }
  59478. }
  59479. break;
  59480. case JS_CLASS_FLOAT64_ARRAY:
  59481. if (is_bigint)
  59482. break;
  59483. if (isnan(d)) {
  59484. const double *pv = p->u.array.u.double_ptr;
  59485. /* special case: indexOf returns -1, includes finds NaN */
  59486. if (special != special_includes)
  59487. goto done;
  59488. for (; k != stop; k += inc) {
  59489. if (isnan(pv[k])) {
  59490. res = k;
  59491. break;
  59492. }
  59493. }
  59494. } else {
  59495. const double *pv = p->u.array.u.double_ptr;
  59496. for (; k != stop; k += inc) {
  59497. if (pv[k] == d) {
  59498. res = k;
  59499. break;
  59500. }
  59501. }
  59502. }
  59503. break;
  59504. case JS_CLASS_BIG_INT64_ARRAY:
  59505. if (is_bigint) {
  59506. goto scan64;
  59507. }
  59508. break;
  59509. case JS_CLASS_BIG_UINT64_ARRAY:
  59510. if (is_bigint) {
  59511. const uint64_t *pv;
  59512. uint64_t v;
  59513. scan64:
  59514. pv = p->u.array.u.uint64_ptr;
  59515. v = v64;
  59516. for (; k != stop; k += inc) {
  59517. if (pv[k] == v) {
  59518. res = k;
  59519. break;
  59520. }
  59521. }
  59522. }
  59523. break;
  59524. }
  59525. done:
  59526. if (special == special_includes)
  59527. return js_bool(res >= 0);
  59528. else
  59529. return js_int32(res);
  59530. exception:
  59531. return JS_EXCEPTION;
  59532. }
  59533. static JSValue js_typed_array_join(JSContext *ctx, JSValueConst this_val,
  59534. int argc, JSValueConst *argv, int toLocaleString)
  59535. {
  59536. JSValue sep = JS_UNDEFINED, el;
  59537. StringBuffer b_s, *b = &b_s;
  59538. JSString *s = NULL;
  59539. JSObject *p;
  59540. int i, len, oldlen, newlen;
  59541. int c;
  59542. p = get_typed_array(ctx, this_val);
  59543. if (!p)
  59544. return JS_EXCEPTION;
  59545. if (typed_array_is_oob(p))
  59546. return JS_ThrowTypeErrorArrayBufferOOB(ctx);
  59547. len = oldlen = newlen = p->u.array.count;
  59548. c = ','; /* default separator */
  59549. if (!toLocaleString && argc > 0 && !JS_IsUndefined(argv[0])) {
  59550. sep = JS_ToString(ctx, argv[0]);
  59551. if (JS_IsException(sep))
  59552. goto exception;
  59553. s = JS_VALUE_GET_STRING(sep);
  59554. if (s->len == 1 && !s->is_wide_char)
  59555. c = str8(s)[0];
  59556. else
  59557. c = -1;
  59558. // ToString(sep) can detach or resize the arraybuffer as a side effect
  59559. newlen = p->u.array.count;
  59560. len = min_int(len, newlen);
  59561. }
  59562. string_buffer_init(ctx, b, 0);
  59563. /* XXX: optimize with direct access */
  59564. for(i = 0; i < len; i++) {
  59565. if (i > 0) {
  59566. if (c >= 0) {
  59567. if (string_buffer_putc8(b, c))
  59568. goto fail;
  59569. } else {
  59570. if (string_buffer_concat(b, s, 0, s->len))
  59571. goto fail;
  59572. }
  59573. }
  59574. el = JS_GetPropertyUint32(ctx, this_val, i);
  59575. /* Can return undefined for example if the typed array is detached */
  59576. if (!JS_IsNull(el) && !JS_IsUndefined(el)) {
  59577. if (JS_IsException(el))
  59578. goto fail;
  59579. if (toLocaleString) {
  59580. el = JS_ToLocaleStringFree(ctx, el);
  59581. }
  59582. if (string_buffer_concat_value_free(b, el))
  59583. goto fail;
  59584. }
  59585. }
  59586. // add extra separators in case RAB was resized by evil .valueOf method
  59587. i = max_int(1, newlen);
  59588. for(/*empty*/; i < oldlen; i++) {
  59589. if (c >= 0) {
  59590. if (string_buffer_putc8(b, c))
  59591. goto fail;
  59592. } else {
  59593. if (string_buffer_concat(b, s, 0, s->len))
  59594. goto fail;
  59595. }
  59596. }
  59597. JS_FreeValue(ctx, sep);
  59598. return string_buffer_end(b);
  59599. fail:
  59600. string_buffer_free(b);
  59601. JS_FreeValue(ctx, sep);
  59602. exception:
  59603. return JS_EXCEPTION;
  59604. }
  59605. static JSValue js_typed_array_reverse(JSContext *ctx, JSValueConst this_val,
  59606. int argc, JSValueConst *argv)
  59607. {
  59608. JSObject *p;
  59609. int len;
  59610. len = js_typed_array_get_length_unsafe(ctx, this_val);
  59611. if (len < 0)
  59612. return JS_EXCEPTION;
  59613. if (len > 0) {
  59614. p = JS_VALUE_GET_OBJ(this_val);
  59615. switch (typed_array_size_log2(p->class_id)) {
  59616. case 0:
  59617. {
  59618. uint8_t *p1 = p->u.array.u.uint8_ptr;
  59619. uint8_t *p2 = p1 + len - 1;
  59620. while (p1 < p2) {
  59621. uint8_t v = *p1;
  59622. *p1++ = *p2;
  59623. *p2-- = v;
  59624. }
  59625. }
  59626. break;
  59627. case 1:
  59628. {
  59629. uint16_t *p1 = p->u.array.u.uint16_ptr;
  59630. uint16_t *p2 = p1 + len - 1;
  59631. while (p1 < p2) {
  59632. uint16_t v = *p1;
  59633. *p1++ = *p2;
  59634. *p2-- = v;
  59635. }
  59636. }
  59637. break;
  59638. case 2:
  59639. {
  59640. uint32_t *p1 = p->u.array.u.uint32_ptr;
  59641. uint32_t *p2 = p1 + len - 1;
  59642. while (p1 < p2) {
  59643. uint32_t v = *p1;
  59644. *p1++ = *p2;
  59645. *p2-- = v;
  59646. }
  59647. }
  59648. break;
  59649. case 3:
  59650. {
  59651. uint64_t *p1 = p->u.array.u.uint64_ptr;
  59652. uint64_t *p2 = p1 + len - 1;
  59653. while (p1 < p2) {
  59654. uint64_t v = *p1;
  59655. *p1++ = *p2;
  59656. *p2-- = v;
  59657. }
  59658. }
  59659. break;
  59660. default:
  59661. abort();
  59662. }
  59663. }
  59664. return js_dup(this_val);
  59665. }
  59666. static JSValue js_typed_array_toReversed(JSContext *ctx, JSValueConst this_val,
  59667. int argc, JSValueConst *argv)
  59668. {
  59669. JSValue arr, ret;
  59670. JSObject *p;
  59671. p = get_typed_array(ctx, this_val);
  59672. if (!p)
  59673. return JS_EXCEPTION;
  59674. arr = js_typed_array_constructor_ta(ctx, JS_UNDEFINED, this_val,
  59675. p->class_id, p->u.array.count);
  59676. if (JS_IsException(arr))
  59677. return JS_EXCEPTION;
  59678. ret = js_typed_array_reverse(ctx, arr, argc, argv);
  59679. JS_FreeValue(ctx, arr);
  59680. return ret;
  59681. }
  59682. static JSValue js_typed_array_slice(JSContext *ctx, JSValueConst this_val,
  59683. int argc, JSValueConst *argv)
  59684. {
  59685. JSValueConst args[2];
  59686. JSValue arr, val;
  59687. JSObject *p, *p1;
  59688. int n, len, start, final, count, shift, space;
  59689. arr = JS_UNDEFINED;
  59690. p = get_typed_array(ctx, this_val);
  59691. if (!p)
  59692. return JS_EXCEPTION;
  59693. if (typed_array_is_oob(p))
  59694. return JS_ThrowTypeErrorArrayBufferOOB(ctx);
  59695. len = p->u.array.count;
  59696. if (JS_ToInt32Clamp(ctx, &start, argv[0], 0, len, len))
  59697. goto exception;
  59698. final = len;
  59699. if (!JS_IsUndefined(argv[1])) {
  59700. if (JS_ToInt32Clamp(ctx, &final, argv[1], 0, len, len))
  59701. goto exception;
  59702. }
  59703. count = max_int(final - start, 0);
  59704. args[0] = this_val;
  59705. args[1] = js_int32(count);
  59706. arr = js_typed_array___speciesCreate(ctx, JS_UNDEFINED, 2, args);
  59707. if (JS_IsException(arr))
  59708. goto exception;
  59709. if (count > 0) {
  59710. if (validate_typed_array(ctx, this_val)
  59711. || validate_typed_array(ctx, arr))
  59712. goto exception;
  59713. if (len != p->u.array.count)
  59714. goto slow_path;
  59715. p1 = get_typed_array(ctx, arr);
  59716. if (p1 != NULL && p->class_id == p1->class_id &&
  59717. typed_array_get_length(ctx, p1) >= count &&
  59718. typed_array_get_length(ctx, p) >= start + count) {
  59719. shift = typed_array_size_log2(p->class_id);
  59720. memmove(p1->u.array.u.uint8_ptr,
  59721. p->u.array.u.uint8_ptr + (start << shift),
  59722. count << shift);
  59723. } else {
  59724. slow_path:
  59725. space = max_int(0, p->u.array.count - start);
  59726. count = min_int(count, space);
  59727. for (n = 0; n < count; n++) {
  59728. val = JS_GetPropertyValue(ctx, this_val, js_int32(start + n));
  59729. if (JS_IsException(val))
  59730. goto exception;
  59731. if (JS_SetPropertyValue(ctx, arr, js_int32(n), val,
  59732. JS_PROP_THROW) < 0)
  59733. goto exception;
  59734. }
  59735. }
  59736. }
  59737. return arr;
  59738. exception:
  59739. JS_FreeValue(ctx, arr);
  59740. return JS_EXCEPTION;
  59741. }
  59742. static JSValue js_typed_array_subarray(JSContext *ctx, JSValueConst this_val,
  59743. int argc, JSValueConst *argv)
  59744. {
  59745. JSArrayBuffer *abuf;
  59746. JSTypedArray *ta;
  59747. JSValueConst args[4];
  59748. JSValue arr, byteOffset, ta_buffer;
  59749. JSObject *p;
  59750. int len, start, final, count, shift, offset;
  59751. p = get_typed_array(ctx, this_val);
  59752. if (!p)
  59753. goto exception;
  59754. len = p->u.array.count;
  59755. if (JS_ToInt32Clamp(ctx, &start, argv[0], 0, len, len))
  59756. goto exception;
  59757. final = len;
  59758. if (!JS_IsUndefined(argv[1])) {
  59759. if (JS_ToInt32Clamp(ctx, &final, argv[1], 0, len, len))
  59760. goto exception;
  59761. }
  59762. count = max_int(final - start, 0);
  59763. byteOffset = js_typed_array_get_byteOffset(ctx, this_val);
  59764. if (JS_IsException(byteOffset))
  59765. goto exception;
  59766. ta = p->u.typed_array;
  59767. abuf = ta->buffer->u.array_buffer;
  59768. if (ta->offset > abuf->byte_length)
  59769. goto range_error;
  59770. if (ta->offset == abuf->byte_length && count > 0) {
  59771. range_error:
  59772. JS_ThrowRangeError(ctx, "invalid offset");
  59773. goto exception;
  59774. }
  59775. shift = typed_array_size_log2(p->class_id);
  59776. offset = JS_VALUE_GET_INT(byteOffset) + (start << shift);
  59777. JS_FreeValue(ctx, byteOffset);
  59778. ta_buffer = js_typed_array_get_buffer(ctx, this_val);
  59779. if (JS_IsException(ta_buffer))
  59780. goto exception;
  59781. args[0] = this_val;
  59782. args[1] = safe_const(ta_buffer);
  59783. args[2] = safe_const(js_int32(offset));
  59784. args[3] = safe_const(js_int32(count));
  59785. // result is length-tracking if source TA is and no explicit count is given
  59786. if (ta->track_rab && JS_IsUndefined(argv[1]))
  59787. args[3] = JS_UNDEFINED;
  59788. arr = js_typed_array___speciesCreate(ctx, JS_UNDEFINED, 4, args);
  59789. JS_FreeValue(ctx, ta_buffer);
  59790. return arr;
  59791. exception:
  59792. return JS_EXCEPTION;
  59793. }
  59794. /* TypedArray.prototype.sort */
  59795. static int js_cmp_doubles(double x, double y)
  59796. {
  59797. if (isnan(x)) return isnan(y) ? 0 : +1;
  59798. if (isnan(y)) return -1;
  59799. if (x < y) return -1;
  59800. if (x > y) return 1;
  59801. if (x != 0) return 0;
  59802. if (signbit(x)) return signbit(y) ? 0 : -1;
  59803. else return signbit(y) ? 1 : 0;
  59804. }
  59805. static int js_TA_cmp_int8(const void *a, const void *b, void *opaque) {
  59806. return *(const int8_t *)a - *(const int8_t *)b;
  59807. }
  59808. static int js_TA_cmp_uint8(const void *a, const void *b, void *opaque) {
  59809. return *(const uint8_t *)a - *(const uint8_t *)b;
  59810. }
  59811. static int js_TA_cmp_int16(const void *a, const void *b, void *opaque) {
  59812. return *(const int16_t *)a - *(const int16_t *)b;
  59813. }
  59814. static int js_TA_cmp_uint16(const void *a, const void *b, void *opaque) {
  59815. return *(const uint16_t *)a - *(const uint16_t *)b;
  59816. }
  59817. static int js_TA_cmp_int32(const void *a, const void *b, void *opaque) {
  59818. int32_t x = *(const int32_t *)a;
  59819. int32_t y = *(const int32_t *)b;
  59820. return (y < x) - (y > x);
  59821. }
  59822. static int js_TA_cmp_uint32(const void *a, const void *b, void *opaque) {
  59823. uint32_t x = *(const uint32_t *)a;
  59824. uint32_t y = *(const uint32_t *)b;
  59825. return (y < x) - (y > x);
  59826. }
  59827. static int js_TA_cmp_int64(const void *a, const void *b, void *opaque) {
  59828. int64_t x = *(const int64_t *)a;
  59829. int64_t y = *(const int64_t *)b;
  59830. return (y < x) - (y > x);
  59831. }
  59832. static int js_TA_cmp_uint64(const void *a, const void *b, void *opaque) {
  59833. uint64_t x = *(const uint64_t *)a;
  59834. uint64_t y = *(const uint64_t *)b;
  59835. return (y < x) - (y > x);
  59836. }
  59837. static int js_TA_cmp_float16(const void *a, const void *b, void *opaque) {
  59838. return js_cmp_doubles(fromfp16(*(const uint16_t *)a),
  59839. fromfp16(*(const uint16_t *)b));
  59840. }
  59841. static int js_TA_cmp_float32(const void *a, const void *b, void *opaque) {
  59842. return js_cmp_doubles(*(const float *)a, *(const float *)b);
  59843. }
  59844. static int js_TA_cmp_float64(const void *a, const void *b, void *opaque) {
  59845. return js_cmp_doubles(*(const double *)a, *(const double *)b);
  59846. }
  59847. static JSValue js_TA_get_int8(JSContext *ctx, const void *a) {
  59848. return js_int32(*(const int8_t *)a);
  59849. }
  59850. static JSValue js_TA_get_uint8(JSContext *ctx, const void *a) {
  59851. return js_int32(*(const uint8_t *)a);
  59852. }
  59853. static JSValue js_TA_get_int16(JSContext *ctx, const void *a) {
  59854. return js_int32(*(const int16_t *)a);
  59855. }
  59856. static JSValue js_TA_get_uint16(JSContext *ctx, const void *a) {
  59857. return js_int32(*(const uint16_t *)a);
  59858. }
  59859. static JSValue js_TA_get_int32(JSContext *ctx, const void *a) {
  59860. return js_int32(*(const int32_t *)a);
  59861. }
  59862. static JSValue js_TA_get_uint32(JSContext *ctx, const void *a) {
  59863. return js_uint32(*(const uint32_t *)a);
  59864. }
  59865. static JSValue js_TA_get_int64(JSContext *ctx, const void *a) {
  59866. return JS_NewBigInt64(ctx, *(int64_t *)a);
  59867. }
  59868. static JSValue js_TA_get_uint64(JSContext *ctx, const void *a) {
  59869. return JS_NewBigUint64(ctx, *(uint64_t *)a);
  59870. }
  59871. static JSValue js_TA_get_float16(JSContext *ctx, const void *a) {
  59872. return js_float64(fromfp16(*(const uint16_t *)a));
  59873. }
  59874. static JSValue js_TA_get_float32(JSContext *ctx, const void *a) {
  59875. return js_float64(*(const float *)a);
  59876. }
  59877. static JSValue js_TA_get_float64(JSContext *ctx, const void *a) {
  59878. return js_float64(*(const double *)a);
  59879. }
  59880. struct TA_sort_context {
  59881. JSContext *ctx;
  59882. int exception;
  59883. JSValueConst arr;
  59884. JSValueConst cmp;
  59885. JSValue (*getfun)(JSContext *ctx, const void *a);
  59886. int elt_size;
  59887. };
  59888. static int js_TA_cmp_generic(const void *a, const void *b, void *opaque) {
  59889. struct TA_sort_context *psc = opaque;
  59890. JSContext *ctx = psc->ctx;
  59891. uint32_t a_idx, b_idx;
  59892. JSValue argv[2];
  59893. JSValue res;
  59894. JSObject *p;
  59895. int cmp;
  59896. p = JS_VALUE_GET_OBJ(psc->arr);
  59897. if (typed_array_is_oob(p))
  59898. return 0;
  59899. cmp = 0;
  59900. if (!psc->exception) {
  59901. a_idx = *(uint32_t *)a;
  59902. b_idx = *(uint32_t *)b;
  59903. if (a_idx >= p->u.array.count || b_idx >= p->u.array.count)
  59904. return 0;
  59905. argv[0] = psc->getfun(ctx, (char *)p->u.array.u.ptr +
  59906. a_idx * (size_t)psc->elt_size);
  59907. argv[1] = psc->getfun(ctx, (char *)p->u.array.u.ptr +
  59908. b_idx * (size_t)(psc->elt_size));
  59909. res = JS_Call(ctx, psc->cmp, JS_UNDEFINED, 2, vc(argv));
  59910. if (JS_IsException(res)) {
  59911. psc->exception = 1;
  59912. goto done;
  59913. }
  59914. if (JS_VALUE_GET_TAG(res) == JS_TAG_INT) {
  59915. int val = JS_VALUE_GET_INT(res);
  59916. cmp = (val > 0) - (val < 0);
  59917. } else {
  59918. double val;
  59919. if (JS_ToFloat64Free(ctx, &val, res) < 0) {
  59920. psc->exception = 1;
  59921. goto done;
  59922. } else {
  59923. cmp = (val > 0) - (val < 0);
  59924. }
  59925. }
  59926. if (cmp == 0) {
  59927. /* make sort stable: compare array offsets */
  59928. cmp = (a_idx > b_idx) - (a_idx < b_idx);
  59929. }
  59930. done:
  59931. JS_FreeValue(ctx, argv[0]);
  59932. JS_FreeValue(ctx, argv[1]);
  59933. }
  59934. return cmp;
  59935. }
  59936. static JSValue js_typed_array_sort(JSContext *ctx, JSValueConst this_val,
  59937. int argc, JSValueConst *argv)
  59938. {
  59939. JSObject *p;
  59940. int len;
  59941. size_t elt_size;
  59942. struct TA_sort_context tsc;
  59943. int (*cmpfun)(const void *a, const void *b, void *opaque);
  59944. p = get_typed_array(ctx, this_val);
  59945. if (!p)
  59946. return JS_EXCEPTION;
  59947. if (typed_array_is_oob(p))
  59948. return JS_ThrowTypeErrorArrayBufferOOB(ctx);
  59949. tsc.ctx = ctx;
  59950. tsc.exception = 0;
  59951. tsc.arr = this_val;
  59952. tsc.cmp = argv[0];
  59953. if (!JS_IsUndefined(tsc.cmp) && check_function(ctx, tsc.cmp))
  59954. return JS_EXCEPTION;
  59955. len = p->u.array.count;
  59956. if (len > 1) {
  59957. switch (p->class_id) {
  59958. case JS_CLASS_INT8_ARRAY:
  59959. tsc.getfun = js_TA_get_int8;
  59960. cmpfun = js_TA_cmp_int8;
  59961. break;
  59962. case JS_CLASS_UINT8C_ARRAY:
  59963. case JS_CLASS_UINT8_ARRAY:
  59964. tsc.getfun = js_TA_get_uint8;
  59965. cmpfun = js_TA_cmp_uint8;
  59966. break;
  59967. case JS_CLASS_INT16_ARRAY:
  59968. tsc.getfun = js_TA_get_int16;
  59969. cmpfun = js_TA_cmp_int16;
  59970. break;
  59971. case JS_CLASS_UINT16_ARRAY:
  59972. tsc.getfun = js_TA_get_uint16;
  59973. cmpfun = js_TA_cmp_uint16;
  59974. break;
  59975. case JS_CLASS_INT32_ARRAY:
  59976. tsc.getfun = js_TA_get_int32;
  59977. cmpfun = js_TA_cmp_int32;
  59978. break;
  59979. case JS_CLASS_UINT32_ARRAY:
  59980. tsc.getfun = js_TA_get_uint32;
  59981. cmpfun = js_TA_cmp_uint32;
  59982. break;
  59983. case JS_CLASS_BIG_INT64_ARRAY:
  59984. tsc.getfun = js_TA_get_int64;
  59985. cmpfun = js_TA_cmp_int64;
  59986. break;
  59987. case JS_CLASS_BIG_UINT64_ARRAY:
  59988. tsc.getfun = js_TA_get_uint64;
  59989. cmpfun = js_TA_cmp_uint64;
  59990. break;
  59991. case JS_CLASS_FLOAT16_ARRAY:
  59992. tsc.getfun = js_TA_get_float16;
  59993. cmpfun = js_TA_cmp_float16;
  59994. break;
  59995. case JS_CLASS_FLOAT32_ARRAY:
  59996. tsc.getfun = js_TA_get_float32;
  59997. cmpfun = js_TA_cmp_float32;
  59998. break;
  59999. case JS_CLASS_FLOAT64_ARRAY:
  60000. tsc.getfun = js_TA_get_float64;
  60001. cmpfun = js_TA_cmp_float64;
  60002. break;
  60003. default:
  60004. abort();
  60005. }
  60006. elt_size = 1 << typed_array_size_log2(p->class_id);
  60007. if (!JS_IsUndefined(tsc.cmp)) {
  60008. uint32_t *array_idx;
  60009. void *array_tmp;
  60010. size_t i, j;
  60011. /* XXX: a stable sort would use less memory */
  60012. array_idx = js_malloc(ctx, len * sizeof(array_idx[0]));
  60013. if (!array_idx)
  60014. return JS_EXCEPTION;
  60015. for(i = 0; i < len; i++)
  60016. array_idx[i] = i;
  60017. tsc.elt_size = elt_size;
  60018. rqsort(array_idx, len, sizeof(array_idx[0]),
  60019. js_TA_cmp_generic, &tsc);
  60020. if (tsc.exception)
  60021. goto fail;
  60022. // per spec: typed array can be detached mid-iteration
  60023. if (typed_array_is_oob(p))
  60024. goto done;
  60025. len = min_int(len, p->u.array.count);
  60026. if (len == 0)
  60027. goto done;
  60028. array_tmp = js_malloc(ctx, len * elt_size);
  60029. if (!array_tmp) {
  60030. fail:
  60031. js_free(ctx, array_idx);
  60032. return JS_EXCEPTION;
  60033. }
  60034. memcpy(array_tmp, p->u.array.u.ptr, len * elt_size);
  60035. switch(elt_size) {
  60036. case 1:
  60037. for(i = 0; i < len; i++) {
  60038. j = array_idx[i];
  60039. p->u.array.u.uint8_ptr[i] = ((uint8_t *)array_tmp)[j];
  60040. }
  60041. break;
  60042. case 2:
  60043. for(i = 0; i < len; i++) {
  60044. j = array_idx[i];
  60045. p->u.array.u.uint16_ptr[i] = ((uint16_t *)array_tmp)[j];
  60046. }
  60047. break;
  60048. case 4:
  60049. for(i = 0; i < len; i++) {
  60050. j = array_idx[i];
  60051. p->u.array.u.uint32_ptr[i] = ((uint32_t *)array_tmp)[j];
  60052. }
  60053. break;
  60054. case 8:
  60055. for(i = 0; i < len; i++) {
  60056. j = array_idx[i];
  60057. p->u.array.u.uint64_ptr[i] = ((uint64_t *)array_tmp)[j];
  60058. }
  60059. break;
  60060. default:
  60061. abort();
  60062. }
  60063. js_free(ctx, array_tmp);
  60064. done:
  60065. js_free(ctx, array_idx);
  60066. } else {
  60067. rqsort(p->u.array.u.ptr, len, elt_size, cmpfun, &tsc);
  60068. if (tsc.exception)
  60069. return JS_EXCEPTION;
  60070. }
  60071. }
  60072. return js_dup(this_val);
  60073. }
  60074. static JSValue js_typed_array_toSorted(JSContext *ctx, JSValueConst this_val,
  60075. int argc, JSValueConst *argv)
  60076. {
  60077. JSValue arr, ret;
  60078. JSObject *p;
  60079. p = get_typed_array(ctx, this_val);
  60080. if (!p)
  60081. return JS_EXCEPTION;
  60082. arr = js_typed_array_constructor_ta(ctx, JS_UNDEFINED, this_val,
  60083. p->class_id, p->u.array.count);
  60084. if (JS_IsException(arr))
  60085. return JS_EXCEPTION;
  60086. ret = js_typed_array_sort(ctx, arr, argc, argv);
  60087. JS_FreeValue(ctx, arr);
  60088. return ret;
  60089. }
  60090. static const JSCFunctionListEntry js_typed_array_base_funcs[] = {
  60091. JS_CFUNC_DEF("from", 1, js_typed_array_from ),
  60092. JS_CFUNC_DEF("of", 0, js_typed_array_of ),
  60093. JS_CGETSET_DEF("[Symbol.species]", js_get_this, NULL ),
  60094. };
  60095. static const JSCFunctionListEntry js_typed_array_base_proto_funcs[] = {
  60096. JS_CGETSET_DEF("length", js_typed_array_get_length, NULL ),
  60097. JS_CFUNC_DEF("at", 1, js_typed_array_at ),
  60098. JS_CFUNC_DEF("with", 2, js_typed_array_with ),
  60099. JS_CGETSET_DEF("buffer", js_typed_array_get_buffer, NULL ),
  60100. JS_CGETSET_DEF("byteLength", js_typed_array_get_byteLength, NULL ),
  60101. JS_CGETSET_DEF("byteOffset", js_typed_array_get_byteOffset, NULL ),
  60102. JS_CFUNC_DEF("set", 1, js_typed_array_set ),
  60103. JS_CFUNC_MAGIC_DEF("values", 0, js_create_typed_array_iterator, JS_ITERATOR_KIND_VALUE ),
  60104. JS_ALIAS_DEF("[Symbol.iterator]", "values" ),
  60105. JS_CFUNC_MAGIC_DEF("keys", 0, js_create_typed_array_iterator, JS_ITERATOR_KIND_KEY ),
  60106. JS_CFUNC_MAGIC_DEF("entries", 0, js_create_typed_array_iterator, JS_ITERATOR_KIND_KEY_AND_VALUE ),
  60107. JS_CGETSET_DEF("[Symbol.toStringTag]", js_typed_array_get_toStringTag, NULL ),
  60108. JS_CFUNC_DEF("copyWithin", 2, js_typed_array_copyWithin ),
  60109. JS_CFUNC_MAGIC_DEF("every", 1, js_array_every, special_every | special_TA ),
  60110. JS_CFUNC_MAGIC_DEF("some", 1, js_array_every, special_some | special_TA ),
  60111. JS_CFUNC_MAGIC_DEF("forEach", 1, js_array_every, special_forEach | special_TA ),
  60112. JS_CFUNC_MAGIC_DEF("map", 1, js_array_every, special_map | special_TA ),
  60113. JS_CFUNC_MAGIC_DEF("filter", 1, js_array_every, special_filter | special_TA ),
  60114. JS_CFUNC_MAGIC_DEF("reduce", 1, js_array_reduce, special_reduce | special_TA ),
  60115. JS_CFUNC_MAGIC_DEF("reduceRight", 1, js_array_reduce, special_reduceRight | special_TA ),
  60116. JS_CFUNC_DEF("fill", 1, js_typed_array_fill ),
  60117. JS_CFUNC_MAGIC_DEF("find", 1, js_typed_array_find, ArrayFind ),
  60118. JS_CFUNC_MAGIC_DEF("findIndex", 1, js_typed_array_find, ArrayFindIndex ),
  60119. JS_CFUNC_MAGIC_DEF("findLast", 1, js_typed_array_find, ArrayFindLast ),
  60120. JS_CFUNC_MAGIC_DEF("findLastIndex", 1, js_typed_array_find, ArrayFindLastIndex ),
  60121. JS_CFUNC_DEF("reverse", 0, js_typed_array_reverse ),
  60122. JS_CFUNC_DEF("toReversed", 0, js_typed_array_toReversed ),
  60123. JS_CFUNC_DEF("slice", 2, js_typed_array_slice ),
  60124. JS_CFUNC_DEF("subarray", 2, js_typed_array_subarray ),
  60125. JS_CFUNC_DEF("sort", 1, js_typed_array_sort ),
  60126. JS_CFUNC_DEF("toSorted", 1, js_typed_array_toSorted ),
  60127. JS_CFUNC_MAGIC_DEF("join", 1, js_typed_array_join, 0 ),
  60128. JS_CFUNC_MAGIC_DEF("toLocaleString", 0, js_typed_array_join, 1 ),
  60129. JS_CFUNC_MAGIC_DEF("indexOf", 1, js_typed_array_indexOf, special_indexOf ),
  60130. JS_CFUNC_MAGIC_DEF("lastIndexOf", 1, js_typed_array_indexOf, special_lastIndexOf ),
  60131. JS_CFUNC_MAGIC_DEF("includes", 1, js_typed_array_indexOf, special_includes ),
  60132. //JS_ALIAS_BASE_DEF("toString", "toString", 2 /* Array.prototype. */), @@@
  60133. };
  60134. static JSValue js_typed_array_base_constructor(JSContext *ctx,
  60135. JSValueConst this_val,
  60136. int argc, JSValueConst *argv)
  60137. {
  60138. return JS_ThrowTypeError(ctx, "cannot be called");
  60139. }
  60140. /* 'obj' must be an allocated typed array object */
  60141. static int typed_array_init(JSContext *ctx, JSValue obj, JSValue buffer,
  60142. uint64_t offset, uint64_t len, bool track_rab)
  60143. {
  60144. JSTypedArray *ta;
  60145. JSObject *p, *pbuffer;
  60146. JSArrayBuffer *abuf;
  60147. int size_log2;
  60148. p = JS_VALUE_GET_OBJ(obj);
  60149. size_log2 = typed_array_size_log2(p->class_id);
  60150. ta = js_malloc(ctx, sizeof(*ta));
  60151. if (!ta) {
  60152. JS_FreeValue(ctx, buffer);
  60153. return -1;
  60154. }
  60155. pbuffer = JS_VALUE_GET_OBJ(buffer);
  60156. abuf = pbuffer->u.array_buffer;
  60157. ta->obj = p;
  60158. ta->buffer = pbuffer;
  60159. ta->offset = offset;
  60160. ta->length = len << size_log2;
  60161. ta->track_rab = track_rab;
  60162. list_add_tail(&ta->link, &abuf->array_list);
  60163. p->u.typed_array = ta;
  60164. p->u.array.count = len;
  60165. p->u.array.u.ptr = abuf->data + offset;
  60166. return 0;
  60167. }
  60168. static JSValue js_array_from_iterator(JSContext *ctx, uint32_t *plen,
  60169. JSValueConst obj, JSValueConst method)
  60170. {
  60171. JSValue arr, iter, next_method = JS_UNDEFINED, val;
  60172. int done;
  60173. uint32_t k;
  60174. *plen = 0;
  60175. arr = JS_NewArray(ctx);
  60176. if (JS_IsException(arr))
  60177. return arr;
  60178. iter = JS_GetIterator2(ctx, obj, method);
  60179. if (JS_IsException(iter))
  60180. goto fail;
  60181. next_method = JS_GetProperty(ctx, iter, JS_ATOM_next);
  60182. if (JS_IsException(next_method))
  60183. goto fail;
  60184. k = 0;
  60185. for(;;) {
  60186. val = JS_IteratorNext(ctx, iter, next_method, 0, NULL, &done);
  60187. if (JS_IsException(val))
  60188. goto fail;
  60189. if (done) {
  60190. JS_FreeValue(ctx, val);
  60191. break;
  60192. }
  60193. if (JS_CreateDataPropertyUint32(ctx, arr, k, val, JS_PROP_THROW) < 0)
  60194. goto fail;
  60195. k++;
  60196. }
  60197. JS_FreeValue(ctx, next_method);
  60198. JS_FreeValue(ctx, iter);
  60199. *plen = k;
  60200. return arr;
  60201. fail:
  60202. JS_FreeValue(ctx, next_method);
  60203. JS_FreeValue(ctx, iter);
  60204. JS_FreeValue(ctx, arr);
  60205. return JS_EXCEPTION;
  60206. }
  60207. static JSValue js_typed_array_constructor_obj(JSContext *ctx,
  60208. JSValueConst new_target,
  60209. JSValueConst obj,
  60210. int classid)
  60211. {
  60212. JSValue iter, ret, arr = JS_UNDEFINED, val, buffer;
  60213. uint32_t i;
  60214. int size_log2;
  60215. int64_t len;
  60216. size_log2 = typed_array_size_log2(classid);
  60217. ret = js_create_from_ctor(ctx, new_target, classid);
  60218. if (JS_IsException(ret))
  60219. return JS_EXCEPTION;
  60220. iter = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_iterator);
  60221. if (JS_IsException(iter))
  60222. goto fail;
  60223. if (!JS_IsUndefined(iter) && !JS_IsNull(iter)) {
  60224. uint32_t len1;
  60225. arr = js_array_from_iterator(ctx, &len1, obj, iter);
  60226. JS_FreeValue(ctx, iter);
  60227. if (JS_IsException(arr))
  60228. goto fail;
  60229. len = len1;
  60230. } else {
  60231. if (js_get_length64(ctx, &len, obj))
  60232. goto fail;
  60233. arr = js_dup(obj);
  60234. }
  60235. buffer = js_array_buffer_constructor1(ctx, JS_UNDEFINED,
  60236. len << size_log2,
  60237. NULL);
  60238. if (JS_IsException(buffer))
  60239. goto fail;
  60240. if (typed_array_init(ctx, ret, buffer, 0, len, /*track_rab*/false))
  60241. goto fail;
  60242. for(i = 0; i < len; i++) {
  60243. val = JS_GetPropertyUint32(ctx, arr, i);
  60244. if (JS_IsException(val))
  60245. goto fail;
  60246. if (JS_SetPropertyUint32(ctx, ret, i, val) < 0)
  60247. goto fail;
  60248. }
  60249. JS_FreeValue(ctx, arr);
  60250. return ret;
  60251. fail:
  60252. JS_FreeValue(ctx, arr);
  60253. JS_FreeValue(ctx, ret);
  60254. return JS_EXCEPTION;
  60255. }
  60256. static JSValue js_typed_array_constructor_ta(JSContext *ctx,
  60257. JSValueConst new_target,
  60258. JSValueConst src_obj,
  60259. int classid, uint32_t len)
  60260. {
  60261. JSObject *p, *src_buffer;
  60262. JSTypedArray *ta;
  60263. JSValue obj, buffer;
  60264. uint32_t i;
  60265. int size_log2;
  60266. JSArrayBuffer *src_abuf, *abuf;
  60267. obj = js_create_from_ctor(ctx, new_target, classid);
  60268. if (JS_IsException(obj))
  60269. return obj;
  60270. p = JS_VALUE_GET_OBJ(src_obj);
  60271. if (typed_array_is_oob(p)) {
  60272. JS_ThrowTypeErrorArrayBufferOOB(ctx);
  60273. goto fail;
  60274. }
  60275. ta = p->u.typed_array;
  60276. src_buffer = ta->buffer;
  60277. src_abuf = src_buffer->u.array_buffer;
  60278. size_log2 = typed_array_size_log2(classid);
  60279. buffer = js_array_buffer_constructor1(ctx, JS_UNDEFINED,
  60280. (uint64_t)len << size_log2,
  60281. NULL);
  60282. if (JS_IsException(buffer))
  60283. goto fail;
  60284. /* necessary because it could have been detached */
  60285. if (typed_array_is_oob(p)) {
  60286. JS_FreeValue(ctx, buffer);
  60287. JS_ThrowTypeErrorArrayBufferOOB(ctx);
  60288. goto fail;
  60289. }
  60290. abuf = JS_GetOpaque(buffer, JS_CLASS_ARRAY_BUFFER);
  60291. if (typed_array_init(ctx, obj, buffer, 0, len, /*track_rab*/false))
  60292. goto fail;
  60293. if (p->class_id == classid) {
  60294. /* same type: copy the content */
  60295. memcpy(abuf->data, src_abuf->data + ta->offset, abuf->byte_length);
  60296. } else {
  60297. for(i = 0; i < len; i++) {
  60298. JSValue val;
  60299. val = JS_GetPropertyUint32(ctx, src_obj, i);
  60300. if (JS_IsException(val))
  60301. goto fail;
  60302. if (JS_SetPropertyUint32(ctx, obj, i, val) < 0)
  60303. goto fail;
  60304. }
  60305. }
  60306. return obj;
  60307. fail:
  60308. JS_FreeValue(ctx, obj);
  60309. return JS_EXCEPTION;
  60310. }
  60311. static JSValue js_typed_array_constructor(JSContext *ctx,
  60312. JSValueConst new_target,
  60313. int argc, JSValueConst *argv,
  60314. int classid)
  60315. {
  60316. bool track_rab = false;
  60317. JSValue buffer, obj;
  60318. JSArrayBuffer *abuf;
  60319. int size_log2;
  60320. uint64_t len, offset;
  60321. size_log2 = typed_array_size_log2(classid);
  60322. if (JS_VALUE_GET_TAG(argv[0]) != JS_TAG_OBJECT) {
  60323. if (JS_ToIndex(ctx, &len, argv[0]))
  60324. return JS_EXCEPTION;
  60325. buffer = js_array_buffer_constructor1(ctx, JS_UNDEFINED,
  60326. len << size_log2,
  60327. NULL);
  60328. if (JS_IsException(buffer))
  60329. return JS_EXCEPTION;
  60330. offset = 0;
  60331. } else {
  60332. JSObject *p = JS_VALUE_GET_OBJ(argv[0]);
  60333. if (p->class_id == JS_CLASS_ARRAY_BUFFER ||
  60334. p->class_id == JS_CLASS_SHARED_ARRAY_BUFFER) {
  60335. abuf = p->u.array_buffer;
  60336. if (JS_ToIndex(ctx, &offset, argv[1]))
  60337. return JS_EXCEPTION;
  60338. if (abuf->detached)
  60339. return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);
  60340. if ((offset & ((1 << size_log2) - 1)) != 0 ||
  60341. offset > abuf->byte_length)
  60342. return JS_ThrowRangeError(ctx, "invalid offset");
  60343. if (JS_IsUndefined(argv[2])) {
  60344. track_rab = array_buffer_is_resizable(abuf);
  60345. if (!track_rab)
  60346. if ((abuf->byte_length & ((1 << size_log2) - 1)) != 0)
  60347. goto invalid_length;
  60348. len = (abuf->byte_length - offset) >> size_log2;
  60349. } else {
  60350. if (JS_ToIndex(ctx, &len, argv[2]))
  60351. return JS_EXCEPTION;
  60352. if (abuf->detached)
  60353. return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);
  60354. if ((offset + (len << size_log2)) > abuf->byte_length) {
  60355. invalid_length:
  60356. return JS_ThrowRangeError(ctx, "invalid length");
  60357. }
  60358. }
  60359. buffer = js_dup(argv[0]);
  60360. } else {
  60361. if (is_typed_array(p->class_id)) {
  60362. return js_typed_array_constructor_ta(ctx, new_target, argv[0],
  60363. classid, p->u.array.count);
  60364. } else {
  60365. return js_typed_array_constructor_obj(ctx, new_target, argv[0], classid);
  60366. }
  60367. }
  60368. }
  60369. obj = js_create_from_ctor(ctx, new_target, classid);
  60370. if (JS_IsException(obj)) {
  60371. JS_FreeValue(ctx, buffer);
  60372. return JS_EXCEPTION;
  60373. }
  60374. if (typed_array_init(ctx, obj, buffer, offset, len, track_rab)) {
  60375. JS_FreeValue(ctx, obj);
  60376. return JS_EXCEPTION;
  60377. }
  60378. return obj;
  60379. }
  60380. static void js_typed_array_finalizer(JSRuntime *rt, JSValueConst val)
  60381. {
  60382. JSObject *p = JS_VALUE_GET_OBJ(val);
  60383. JSTypedArray *ta = p->u.typed_array;
  60384. if (ta) {
  60385. /* during the GC the finalizers are called in an arbitrary
  60386. order so the ArrayBuffer finalizer may have been called */
  60387. if (ta->link.next) {
  60388. list_del(&ta->link);
  60389. }
  60390. JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_OBJECT, ta->buffer));
  60391. js_free_rt(rt, ta);
  60392. }
  60393. }
  60394. static void js_typed_array_mark(JSRuntime *rt, JSValueConst val,
  60395. JS_MarkFunc *mark_func)
  60396. {
  60397. JSObject *p = JS_VALUE_GET_OBJ(val);
  60398. JSTypedArray *ta = p->u.typed_array;
  60399. if (ta) {
  60400. JS_MarkValue(rt, JS_MKPTR(JS_TAG_OBJECT, ta->buffer), mark_func);
  60401. }
  60402. }
  60403. static JSValue js_dataview_constructor(JSContext *ctx,
  60404. JSValueConst new_target,
  60405. int argc, JSValueConst *argv)
  60406. {
  60407. bool recompute_len = false;
  60408. bool track_rab = false;
  60409. JSArrayBuffer *abuf;
  60410. uint64_t offset;
  60411. uint32_t len;
  60412. JSValueConst buffer;
  60413. JSValue obj;
  60414. JSTypedArray *ta;
  60415. JSObject *p;
  60416. buffer = argv[0];
  60417. abuf = js_get_array_buffer(ctx, buffer);
  60418. if (!abuf)
  60419. return JS_EXCEPTION;
  60420. offset = 0;
  60421. if (argc > 1) {
  60422. if (JS_ToIndex(ctx, &offset, argv[1]))
  60423. return JS_EXCEPTION;
  60424. }
  60425. if (abuf->detached)
  60426. return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);
  60427. if (offset > abuf->byte_length)
  60428. return JS_ThrowRangeError(ctx, "invalid byteOffset");
  60429. len = abuf->byte_length - offset;
  60430. if (argc > 2 && !JS_IsUndefined(argv[2])) {
  60431. uint64_t l;
  60432. if (JS_ToIndex(ctx, &l, argv[2]))
  60433. return JS_EXCEPTION;
  60434. if (l > len)
  60435. return JS_ThrowRangeError(ctx, "invalid byteLength");
  60436. len = l;
  60437. } else {
  60438. recompute_len = true;
  60439. track_rab = array_buffer_is_resizable(abuf);
  60440. }
  60441. obj = js_create_from_ctor(ctx, new_target, JS_CLASS_DATAVIEW);
  60442. if (JS_IsException(obj))
  60443. return JS_EXCEPTION;
  60444. if (abuf->detached) {
  60445. /* could have been detached in js_create_from_ctor() */
  60446. JS_ThrowTypeErrorDetachedArrayBuffer(ctx);
  60447. goto fail;
  60448. }
  60449. // RAB could have been resized in js_create_from_ctor()
  60450. if (offset > abuf->byte_length) {
  60451. goto out_of_bound;
  60452. } else if (recompute_len) {
  60453. len = abuf->byte_length - offset;
  60454. } else if (offset + len > abuf->byte_length) {
  60455. out_of_bound:
  60456. JS_ThrowRangeError(ctx, "invalid byteOffset or byteLength");
  60457. goto fail;
  60458. }
  60459. ta = js_malloc(ctx, sizeof(*ta));
  60460. if (!ta) {
  60461. fail:
  60462. JS_FreeValue(ctx, obj);
  60463. return JS_EXCEPTION;
  60464. }
  60465. p = JS_VALUE_GET_OBJ(obj);
  60466. ta->obj = p;
  60467. ta->buffer = JS_VALUE_GET_OBJ(js_dup(buffer));
  60468. ta->offset = offset;
  60469. ta->length = len;
  60470. ta->track_rab = track_rab;
  60471. list_add_tail(&ta->link, &abuf->array_list);
  60472. p->u.typed_array = ta;
  60473. return obj;
  60474. }
  60475. // is the DataView out of bounds relative to its parent arraybuffer?
  60476. static bool dataview_is_oob(JSObject *p)
  60477. {
  60478. JSArrayBuffer *abuf;
  60479. JSTypedArray *ta;
  60480. assert(p->class_id == JS_CLASS_DATAVIEW);
  60481. ta = p->u.typed_array;
  60482. abuf = ta->buffer->u.array_buffer;
  60483. if (abuf->detached)
  60484. return true;
  60485. if (ta->offset > abuf->byte_length)
  60486. return true;
  60487. if (ta->track_rab)
  60488. return false;
  60489. return (int64_t)ta->offset + ta->length > abuf->byte_length;
  60490. }
  60491. static JSObject *get_dataview(JSContext *ctx, JSValueConst this_val)
  60492. {
  60493. JSObject *p;
  60494. if (JS_VALUE_GET_TAG(this_val) != JS_TAG_OBJECT)
  60495. goto fail;
  60496. p = JS_VALUE_GET_OBJ(this_val);
  60497. if (p->class_id != JS_CLASS_DATAVIEW) {
  60498. fail:
  60499. JS_ThrowTypeError(ctx, "not a DataView");
  60500. return NULL;
  60501. }
  60502. return p;
  60503. }
  60504. static JSValue js_dataview_get_buffer(JSContext *ctx, JSValueConst this_val)
  60505. {
  60506. JSObject *p;
  60507. JSTypedArray *ta;
  60508. p = get_dataview(ctx, this_val);
  60509. if (!p)
  60510. return JS_EXCEPTION;
  60511. ta = p->u.typed_array;
  60512. return js_dup(JS_MKPTR(JS_TAG_OBJECT, ta->buffer));
  60513. }
  60514. static JSValue js_dataview_get_byteLength(JSContext *ctx, JSValueConst this_val)
  60515. {
  60516. JSArrayBuffer *abuf;
  60517. JSTypedArray *ta;
  60518. JSObject *p;
  60519. p = get_dataview(ctx, this_val);
  60520. if (!p)
  60521. return JS_EXCEPTION;
  60522. if (dataview_is_oob(p))
  60523. return JS_ThrowTypeErrorArrayBufferOOB(ctx);
  60524. ta = p->u.typed_array;
  60525. if (ta->track_rab) {
  60526. abuf = ta->buffer->u.array_buffer;
  60527. return js_uint32(abuf->byte_length - ta->offset);
  60528. }
  60529. return js_uint32(ta->length);
  60530. }
  60531. static JSValue js_dataview_get_byteOffset(JSContext *ctx, JSValueConst this_val)
  60532. {
  60533. JSTypedArray *ta;
  60534. JSObject *p;
  60535. p = get_dataview(ctx, this_val);
  60536. if (!p)
  60537. return JS_EXCEPTION;
  60538. if (dataview_is_oob(p))
  60539. return JS_ThrowTypeErrorArrayBufferOOB(ctx);
  60540. ta = p->u.typed_array;
  60541. return js_uint32(ta->offset);
  60542. }
  60543. static JSValue js_dataview_getValue(JSContext *ctx,
  60544. JSValueConst this_obj,
  60545. int argc, JSValueConst *argv, int class_id)
  60546. {
  60547. JSTypedArray *ta;
  60548. JSArrayBuffer *abuf;
  60549. bool littleEndian, is_swap;
  60550. int size;
  60551. uint8_t *ptr;
  60552. uint32_t v;
  60553. uint64_t pos;
  60554. ta = JS_GetOpaque2(ctx, this_obj, JS_CLASS_DATAVIEW);
  60555. if (!ta)
  60556. return JS_EXCEPTION;
  60557. size = 1 << typed_array_size_log2(class_id);
  60558. if (JS_ToIndex(ctx, &pos, argv[0]))
  60559. return JS_EXCEPTION;
  60560. littleEndian = argc > 1 && JS_ToBool(ctx, argv[1]);
  60561. is_swap = littleEndian ^ !is_be();
  60562. abuf = ta->buffer->u.array_buffer;
  60563. if (abuf->detached)
  60564. return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);
  60565. // order matters: this check should come before the next one
  60566. if ((pos + size) > ta->length)
  60567. return JS_ThrowRangeError(ctx, "out of bound");
  60568. // test262 expects a TypeError for this and V8, in its infinite wisdom,
  60569. // throws a "detached array buffer" exception, but IMO that doesn't make
  60570. // sense because the buffer is not in fact detached, it's still there
  60571. if ((int64_t)ta->offset + ta->length > abuf->byte_length)
  60572. return JS_ThrowTypeError(ctx, "out of bound");
  60573. ptr = abuf->data + ta->offset + pos;
  60574. switch(class_id) {
  60575. case JS_CLASS_INT8_ARRAY:
  60576. return js_int32(*(int8_t *)ptr);
  60577. case JS_CLASS_UINT8_ARRAY:
  60578. return js_int32(*(uint8_t *)ptr);
  60579. case JS_CLASS_INT16_ARRAY:
  60580. v = get_u16(ptr);
  60581. if (is_swap)
  60582. v = bswap16(v);
  60583. return js_int32((int16_t)v);
  60584. case JS_CLASS_UINT16_ARRAY:
  60585. v = get_u16(ptr);
  60586. if (is_swap)
  60587. v = bswap16(v);
  60588. return js_int32(v);
  60589. case JS_CLASS_INT32_ARRAY:
  60590. v = get_u32(ptr);
  60591. if (is_swap)
  60592. v = bswap32(v);
  60593. return js_int32(v);
  60594. case JS_CLASS_UINT32_ARRAY:
  60595. v = get_u32(ptr);
  60596. if (is_swap)
  60597. v = bswap32(v);
  60598. return js_uint32(v);
  60599. case JS_CLASS_BIG_INT64_ARRAY:
  60600. {
  60601. uint64_t v;
  60602. v = get_u64(ptr);
  60603. if (is_swap)
  60604. v = bswap64(v);
  60605. return JS_NewBigInt64(ctx, v);
  60606. }
  60607. break;
  60608. case JS_CLASS_BIG_UINT64_ARRAY:
  60609. {
  60610. uint64_t v;
  60611. v = get_u64(ptr);
  60612. if (is_swap)
  60613. v = bswap64(v);
  60614. return JS_NewBigUint64(ctx, v);
  60615. }
  60616. break;
  60617. case JS_CLASS_FLOAT16_ARRAY:
  60618. {
  60619. uint16_t v;
  60620. v = get_u16(ptr);
  60621. if (is_swap)
  60622. v = bswap16(v);
  60623. return js_float64(fromfp16(v));
  60624. }
  60625. case JS_CLASS_FLOAT32_ARRAY:
  60626. {
  60627. union {
  60628. float f;
  60629. uint32_t i;
  60630. } u;
  60631. v = get_u32(ptr);
  60632. if (is_swap)
  60633. v = bswap32(v);
  60634. u.i = v;
  60635. return js_float64(u.f);
  60636. }
  60637. case JS_CLASS_FLOAT64_ARRAY:
  60638. {
  60639. union {
  60640. double f;
  60641. uint64_t i;
  60642. } u;
  60643. u.i = get_u64(ptr);
  60644. if (is_swap)
  60645. u.i = bswap64(u.i);
  60646. return js_float64(u.f);
  60647. }
  60648. default:
  60649. abort();
  60650. }
  60651. return JS_EXCEPTION; // pacify compiler
  60652. }
  60653. static JSValue js_dataview_setValue(JSContext *ctx,
  60654. JSValueConst this_obj,
  60655. int argc, JSValueConst *argv, int class_id)
  60656. {
  60657. JSTypedArray *ta;
  60658. JSArrayBuffer *abuf;
  60659. bool littleEndian, is_swap;
  60660. int size;
  60661. uint8_t *ptr;
  60662. uint64_t v64;
  60663. uint32_t v;
  60664. uint64_t pos;
  60665. JSValueConst val;
  60666. ta = JS_GetOpaque2(ctx, this_obj, JS_CLASS_DATAVIEW);
  60667. if (!ta)
  60668. return JS_EXCEPTION;
  60669. size = 1 << typed_array_size_log2(class_id);
  60670. if (JS_ToIndex(ctx, &pos, argv[0]))
  60671. return JS_EXCEPTION;
  60672. val = argv[1];
  60673. v = 0; /* avoid warning */
  60674. v64 = 0; /* avoid warning */
  60675. if (class_id <= JS_CLASS_UINT32_ARRAY) {
  60676. if (JS_ToUint32(ctx, &v, val))
  60677. return JS_EXCEPTION;
  60678. } else
  60679. if (class_id <= JS_CLASS_BIG_UINT64_ARRAY) {
  60680. if (JS_ToBigInt64(ctx, (int64_t *)&v64, val))
  60681. return JS_EXCEPTION;
  60682. } else {
  60683. double d;
  60684. if (JS_ToFloat64(ctx, &d, val))
  60685. return JS_EXCEPTION;
  60686. if (class_id == JS_CLASS_FLOAT16_ARRAY) {
  60687. v = tofp16(d);
  60688. } else if (class_id == JS_CLASS_FLOAT32_ARRAY) {
  60689. union {
  60690. float f;
  60691. uint32_t i;
  60692. } u;
  60693. u.f = d;
  60694. v = u.i;
  60695. } else {
  60696. JSFloat64Union u;
  60697. u.d = d;
  60698. v64 = u.u64;
  60699. }
  60700. }
  60701. littleEndian = argc > 2 && JS_ToBool(ctx, argv[2]);
  60702. is_swap = littleEndian ^ !is_be();
  60703. abuf = ta->buffer->u.array_buffer;
  60704. if (abuf->detached)
  60705. return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);
  60706. // order matters: this check should come before the next one
  60707. if ((pos + size) > ta->length)
  60708. return JS_ThrowRangeError(ctx, "out of bound");
  60709. // test262 expects a TypeError for this and V8, in its infinite wisdom,
  60710. // throws a "detached array buffer" exception, but IMO that doesn't make
  60711. // sense because the buffer is not in fact detached, it's still there
  60712. if ((int64_t)ta->offset + ta->length > abuf->byte_length)
  60713. return JS_ThrowTypeError(ctx, "out of bound");
  60714. ptr = abuf->data + ta->offset + pos;
  60715. switch(class_id) {
  60716. case JS_CLASS_INT8_ARRAY:
  60717. case JS_CLASS_UINT8_ARRAY:
  60718. *ptr = v;
  60719. break;
  60720. case JS_CLASS_INT16_ARRAY:
  60721. case JS_CLASS_UINT16_ARRAY:
  60722. case JS_CLASS_FLOAT16_ARRAY:
  60723. if (is_swap)
  60724. v = bswap16(v);
  60725. put_u16(ptr, v);
  60726. break;
  60727. case JS_CLASS_INT32_ARRAY:
  60728. case JS_CLASS_UINT32_ARRAY:
  60729. case JS_CLASS_FLOAT32_ARRAY:
  60730. if (is_swap)
  60731. v = bswap32(v);
  60732. put_u32(ptr, v);
  60733. break;
  60734. case JS_CLASS_BIG_INT64_ARRAY:
  60735. case JS_CLASS_BIG_UINT64_ARRAY:
  60736. case JS_CLASS_FLOAT64_ARRAY:
  60737. if (is_swap)
  60738. v64 = bswap64(v64);
  60739. put_u64(ptr, v64);
  60740. break;
  60741. default:
  60742. abort();
  60743. }
  60744. return JS_UNDEFINED;
  60745. }
  60746. static const JSCFunctionListEntry js_dataview_proto_funcs[] = {
  60747. JS_CGETSET_DEF("buffer", js_dataview_get_buffer, NULL ),
  60748. JS_CGETSET_DEF("byteLength", js_dataview_get_byteLength, NULL ),
  60749. JS_CGETSET_DEF("byteOffset", js_dataview_get_byteOffset, NULL ),
  60750. JS_CFUNC_MAGIC_DEF("getInt8", 1, js_dataview_getValue, JS_CLASS_INT8_ARRAY ),
  60751. JS_CFUNC_MAGIC_DEF("getUint8", 1, js_dataview_getValue, JS_CLASS_UINT8_ARRAY ),
  60752. JS_CFUNC_MAGIC_DEF("getInt16", 1, js_dataview_getValue, JS_CLASS_INT16_ARRAY ),
  60753. JS_CFUNC_MAGIC_DEF("getUint16", 1, js_dataview_getValue, JS_CLASS_UINT16_ARRAY ),
  60754. JS_CFUNC_MAGIC_DEF("getInt32", 1, js_dataview_getValue, JS_CLASS_INT32_ARRAY ),
  60755. JS_CFUNC_MAGIC_DEF("getUint32", 1, js_dataview_getValue, JS_CLASS_UINT32_ARRAY ),
  60756. JS_CFUNC_MAGIC_DEF("getBigInt64", 1, js_dataview_getValue, JS_CLASS_BIG_INT64_ARRAY ),
  60757. JS_CFUNC_MAGIC_DEF("getBigUint64", 1, js_dataview_getValue, JS_CLASS_BIG_UINT64_ARRAY ),
  60758. JS_CFUNC_MAGIC_DEF("getFloat16", 1, js_dataview_getValue, JS_CLASS_FLOAT16_ARRAY ),
  60759. JS_CFUNC_MAGIC_DEF("getFloat32", 1, js_dataview_getValue, JS_CLASS_FLOAT32_ARRAY ),
  60760. JS_CFUNC_MAGIC_DEF("getFloat64", 1, js_dataview_getValue, JS_CLASS_FLOAT64_ARRAY ),
  60761. JS_CFUNC_MAGIC_DEF("setInt8", 2, js_dataview_setValue, JS_CLASS_INT8_ARRAY ),
  60762. JS_CFUNC_MAGIC_DEF("setUint8", 2, js_dataview_setValue, JS_CLASS_UINT8_ARRAY ),
  60763. JS_CFUNC_MAGIC_DEF("setInt16", 2, js_dataview_setValue, JS_CLASS_INT16_ARRAY ),
  60764. JS_CFUNC_MAGIC_DEF("setUint16", 2, js_dataview_setValue, JS_CLASS_UINT16_ARRAY ),
  60765. JS_CFUNC_MAGIC_DEF("setInt32", 2, js_dataview_setValue, JS_CLASS_INT32_ARRAY ),
  60766. JS_CFUNC_MAGIC_DEF("setUint32", 2, js_dataview_setValue, JS_CLASS_UINT32_ARRAY ),
  60767. JS_CFUNC_MAGIC_DEF("setBigInt64", 2, js_dataview_setValue, JS_CLASS_BIG_INT64_ARRAY ),
  60768. JS_CFUNC_MAGIC_DEF("setBigUint64", 2, js_dataview_setValue, JS_CLASS_BIG_UINT64_ARRAY ),
  60769. JS_CFUNC_MAGIC_DEF("setFloat16", 2, js_dataview_setValue, JS_CLASS_FLOAT16_ARRAY ),
  60770. JS_CFUNC_MAGIC_DEF("setFloat32", 2, js_dataview_setValue, JS_CLASS_FLOAT32_ARRAY ),
  60771. JS_CFUNC_MAGIC_DEF("setFloat64", 2, js_dataview_setValue, JS_CLASS_FLOAT64_ARRAY ),
  60772. JS_PROP_STRING_DEF("[Symbol.toStringTag]", "DataView", JS_PROP_CONFIGURABLE ),
  60773. };
  60774. static JSValue js_new_uint8array(JSContext *ctx, JSValue buffer)
  60775. {
  60776. if (JS_IsException(buffer))
  60777. return JS_EXCEPTION;
  60778. JSValue obj = js_create_from_ctor(ctx, JS_UNDEFINED, JS_CLASS_UINT8_ARRAY);
  60779. if (JS_IsException(obj)) {
  60780. JS_FreeValue(ctx, buffer);
  60781. return JS_EXCEPTION;
  60782. }
  60783. JSArrayBuffer *abuf = js_get_array_buffer(ctx, buffer);
  60784. assert(abuf != NULL);
  60785. if (typed_array_init(ctx, obj, buffer, 0, abuf->byte_length, /*track_rab*/false)) {
  60786. // 'buffer' is freed on error above.
  60787. JS_FreeValue(ctx, obj);
  60788. return JS_EXCEPTION;
  60789. }
  60790. return obj;
  60791. }
  60792. JSValue JS_NewUint8Array(JSContext *ctx, uint8_t *buf, size_t len,
  60793. JSFreeArrayBufferDataFunc *free_func, void *opaque,
  60794. bool is_shared)
  60795. {
  60796. JSClassID class_id =
  60797. is_shared ? JS_CLASS_SHARED_ARRAY_BUFFER : JS_CLASS_ARRAY_BUFFER;
  60798. JSValue buffer = js_array_buffer_constructor3(ctx, JS_UNDEFINED, len, NULL,
  60799. class_id, buf, free_func,
  60800. opaque, false);
  60801. return js_new_uint8array(ctx, buffer);
  60802. }
  60803. JSValue JS_NewUint8ArrayCopy(JSContext *ctx, const uint8_t *buf, size_t len)
  60804. {
  60805. JSValue buffer = js_array_buffer_constructor3(ctx, JS_UNDEFINED, len, NULL,
  60806. JS_CLASS_ARRAY_BUFFER,
  60807. (uint8_t *)buf,
  60808. js_array_buffer_free, NULL,
  60809. true);
  60810. return js_new_uint8array(ctx, buffer);
  60811. }
  60812. int JS_GetTypedArrayType(JSValueConst obj)
  60813. {
  60814. JSClassID class_id = JS_GetClassID(obj);
  60815. if (is_typed_array(class_id))
  60816. return class_id - JS_CLASS_UINT8C_ARRAY;
  60817. else
  60818. return -1;
  60819. }
  60820. /* Atomics */
  60821. #ifdef CONFIG_ATOMICS
  60822. typedef enum AtomicsOpEnum {
  60823. ATOMICS_OP_ADD,
  60824. ATOMICS_OP_AND,
  60825. ATOMICS_OP_OR,
  60826. ATOMICS_OP_SUB,
  60827. ATOMICS_OP_XOR,
  60828. ATOMICS_OP_EXCHANGE,
  60829. ATOMICS_OP_COMPARE_EXCHANGE,
  60830. ATOMICS_OP_LOAD,
  60831. } AtomicsOpEnum;
  60832. static void *js_atomics_get_ptr(JSContext *ctx,
  60833. JSArrayBuffer **pabuf,
  60834. int *psize_log2, JSClassID *pclass_id,
  60835. JSValueConst obj, JSValueConst idx_val,
  60836. int is_waitable)
  60837. {
  60838. JSObject *p;
  60839. JSTypedArray *ta;
  60840. JSArrayBuffer *abuf;
  60841. void *ptr;
  60842. uint64_t idx;
  60843. bool err;
  60844. int size_log2;
  60845. if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)
  60846. goto fail;
  60847. p = JS_VALUE_GET_OBJ(obj);
  60848. if (is_waitable)
  60849. err = (p->class_id != JS_CLASS_INT32_ARRAY &&
  60850. p->class_id != JS_CLASS_BIG_INT64_ARRAY);
  60851. else
  60852. err = !(p->class_id >= JS_CLASS_INT8_ARRAY &&
  60853. p->class_id <= JS_CLASS_BIG_UINT64_ARRAY);
  60854. if (err) {
  60855. fail:
  60856. JS_ThrowTypeError(ctx, "integer TypedArray expected");
  60857. return NULL;
  60858. }
  60859. ta = p->u.typed_array;
  60860. abuf = ta->buffer->u.array_buffer;
  60861. if (!abuf->shared) {
  60862. if (is_waitable == 2) {
  60863. JS_ThrowTypeError(ctx, "not a SharedArrayBuffer TypedArray");
  60864. return NULL;
  60865. }
  60866. if (abuf->detached) {
  60867. JS_ThrowTypeErrorDetachedArrayBuffer(ctx);
  60868. return NULL;
  60869. }
  60870. }
  60871. if (JS_ToIndex(ctx, &idx, idx_val)) {
  60872. return NULL;
  60873. }
  60874. /* if the array buffer is detached, p->u.array.count = 0 */
  60875. if (idx >= p->u.array.count) {
  60876. JS_ThrowRangeError(ctx, "out-of-bound access");
  60877. return NULL;
  60878. }
  60879. size_log2 = typed_array_size_log2(p->class_id);
  60880. ptr = p->u.array.u.uint8_ptr + ((uintptr_t)idx << size_log2);
  60881. if (pabuf)
  60882. *pabuf = abuf;
  60883. if (psize_log2)
  60884. *psize_log2 = size_log2;
  60885. if (pclass_id)
  60886. *pclass_id = p->class_id;
  60887. return ptr;
  60888. }
  60889. static JSValue js_atomics_op(JSContext *ctx,
  60890. JSValueConst this_obj,
  60891. int argc, JSValueConst *argv, int op)
  60892. {
  60893. int size_log2;
  60894. uint64_t v, a, rep_val;
  60895. void *ptr;
  60896. JSValue ret;
  60897. JSClassID class_id;
  60898. JSArrayBuffer *abuf;
  60899. ptr = js_atomics_get_ptr(ctx, &abuf, &size_log2, &class_id,
  60900. argv[0], argv[1], 0);
  60901. if (!ptr)
  60902. return JS_EXCEPTION;
  60903. rep_val = 0;
  60904. if (op == ATOMICS_OP_LOAD) {
  60905. v = 0;
  60906. } else {
  60907. if (size_log2 == 3) {
  60908. int64_t v64;
  60909. if (JS_ToBigInt64(ctx, &v64, argv[2]))
  60910. return JS_EXCEPTION;
  60911. v = v64;
  60912. if (op == ATOMICS_OP_COMPARE_EXCHANGE) {
  60913. if (JS_ToBigInt64(ctx, &v64, argv[3]))
  60914. return JS_EXCEPTION;
  60915. rep_val = v64;
  60916. }
  60917. } else {
  60918. uint32_t v32;
  60919. if (JS_ToUint32(ctx, &v32, argv[2]))
  60920. return JS_EXCEPTION;
  60921. v = v32;
  60922. if (op == ATOMICS_OP_COMPARE_EXCHANGE) {
  60923. if (JS_ToUint32(ctx, &v32, argv[3]))
  60924. return JS_EXCEPTION;
  60925. rep_val = v32;
  60926. }
  60927. }
  60928. if (abuf->detached)
  60929. return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);
  60930. }
  60931. switch(op | (size_log2 << 3)) {
  60932. #define OP(op_name, func_name) \
  60933. case ATOMICS_OP_ ## op_name | (0 << 3): \
  60934. a = func_name((_Atomic uint8_t *)ptr, v); \
  60935. break; \
  60936. case ATOMICS_OP_ ## op_name | (1 << 3): \
  60937. a = func_name((_Atomic uint16_t *)ptr, v); \
  60938. break; \
  60939. case ATOMICS_OP_ ## op_name | (2 << 3): \
  60940. a = func_name((_Atomic uint32_t *)ptr, v); \
  60941. break; \
  60942. case ATOMICS_OP_ ## op_name | (3 << 3): \
  60943. a = func_name((_Atomic uint64_t *)ptr, v); \
  60944. break;
  60945. OP(ADD, atomic_fetch_add)
  60946. OP(AND, atomic_fetch_and)
  60947. OP(OR, atomic_fetch_or)
  60948. OP(SUB, atomic_fetch_sub)
  60949. OP(XOR, atomic_fetch_xor)
  60950. OP(EXCHANGE, atomic_exchange)
  60951. #undef OP
  60952. case ATOMICS_OP_LOAD | (0 << 3):
  60953. a = atomic_load((_Atomic uint8_t *)ptr);
  60954. break;
  60955. case ATOMICS_OP_LOAD | (1 << 3):
  60956. a = atomic_load((_Atomic uint16_t *)ptr);
  60957. break;
  60958. case ATOMICS_OP_LOAD | (2 << 3):
  60959. a = atomic_load((_Atomic uint32_t *)ptr);
  60960. break;
  60961. case ATOMICS_OP_LOAD | (3 << 3):
  60962. a = atomic_load((_Atomic uint64_t *)ptr);
  60963. break;
  60964. case ATOMICS_OP_COMPARE_EXCHANGE | (0 << 3):
  60965. {
  60966. uint8_t v1 = v;
  60967. atomic_compare_exchange_strong((_Atomic uint8_t *)ptr, &v1, rep_val);
  60968. a = v1;
  60969. }
  60970. break;
  60971. case ATOMICS_OP_COMPARE_EXCHANGE | (1 << 3):
  60972. {
  60973. uint16_t v1 = v;
  60974. atomic_compare_exchange_strong((_Atomic uint16_t *)ptr, &v1, rep_val);
  60975. a = v1;
  60976. }
  60977. break;
  60978. case ATOMICS_OP_COMPARE_EXCHANGE | (2 << 3):
  60979. {
  60980. uint32_t v1 = v;
  60981. atomic_compare_exchange_strong((_Atomic uint32_t *)ptr, &v1, rep_val);
  60982. a = v1;
  60983. }
  60984. break;
  60985. case ATOMICS_OP_COMPARE_EXCHANGE | (3 << 3):
  60986. {
  60987. uint64_t v1 = v;
  60988. atomic_compare_exchange_strong((_Atomic uint64_t *)ptr, &v1, rep_val);
  60989. a = v1;
  60990. }
  60991. break;
  60992. default:
  60993. abort();
  60994. }
  60995. switch(class_id) {
  60996. case JS_CLASS_INT8_ARRAY:
  60997. a = (int8_t)a;
  60998. goto done;
  60999. case JS_CLASS_UINT8_ARRAY:
  61000. a = (uint8_t)a;
  61001. goto done;
  61002. case JS_CLASS_INT16_ARRAY:
  61003. a = (int16_t)a;
  61004. goto done;
  61005. case JS_CLASS_UINT16_ARRAY:
  61006. a = (uint16_t)a;
  61007. goto done;
  61008. case JS_CLASS_INT32_ARRAY:
  61009. done:
  61010. ret = js_int32(a);
  61011. break;
  61012. case JS_CLASS_UINT32_ARRAY:
  61013. ret = js_uint32(a);
  61014. break;
  61015. case JS_CLASS_BIG_INT64_ARRAY:
  61016. ret = JS_NewBigInt64(ctx, a);
  61017. break;
  61018. case JS_CLASS_BIG_UINT64_ARRAY:
  61019. ret = JS_NewBigUint64(ctx, a);
  61020. break;
  61021. default:
  61022. abort();
  61023. }
  61024. return ret;
  61025. }
  61026. static JSValue js_atomics_store(JSContext *ctx,
  61027. JSValueConst this_obj,
  61028. int argc, JSValueConst *argv)
  61029. {
  61030. int size_log2;
  61031. void *ptr;
  61032. JSValue ret;
  61033. JSArrayBuffer *abuf;
  61034. ptr = js_atomics_get_ptr(ctx, &abuf, &size_log2, NULL,
  61035. argv[0], argv[1], 0);
  61036. if (!ptr)
  61037. return JS_EXCEPTION;
  61038. if (size_log2 == 3) {
  61039. int64_t v64;
  61040. ret = JS_ToBigIntValueFree(ctx, js_dup(argv[2]));
  61041. if (JS_IsException(ret))
  61042. return ret;
  61043. if (JS_ToBigInt64(ctx, &v64, ret)) {
  61044. JS_FreeValue(ctx, ret);
  61045. return JS_EXCEPTION;
  61046. }
  61047. if (abuf->detached)
  61048. return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);
  61049. atomic_store((_Atomic uint64_t *)ptr, v64);
  61050. } else {
  61051. uint32_t v;
  61052. /* XXX: spec, would be simpler to return the written value */
  61053. ret = JS_ToIntegerFree(ctx, js_dup(argv[2]));
  61054. if (JS_IsException(ret))
  61055. return ret;
  61056. if (JS_ToUint32(ctx, &v, ret)) {
  61057. JS_FreeValue(ctx, ret);
  61058. return JS_EXCEPTION;
  61059. }
  61060. if (abuf->detached)
  61061. return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);
  61062. switch(size_log2) {
  61063. case 0:
  61064. atomic_store((_Atomic uint8_t *)ptr, v);
  61065. break;
  61066. case 1:
  61067. atomic_store((_Atomic uint16_t *)ptr, v);
  61068. break;
  61069. case 2:
  61070. atomic_store((_Atomic uint32_t *)ptr, v);
  61071. break;
  61072. default:
  61073. abort();
  61074. }
  61075. }
  61076. return ret;
  61077. }
  61078. static JSValue js_atomics_isLockFree(JSContext *ctx,
  61079. JSValueConst this_obj,
  61080. int argc, JSValueConst *argv)
  61081. {
  61082. int v, ret;
  61083. if (JS_ToInt32Sat(ctx, &v, argv[0]))
  61084. return JS_EXCEPTION;
  61085. ret = (v == 1 || v == 2 || v == 4 || v == 8);
  61086. return js_bool(ret);
  61087. }
  61088. typedef struct JSAtomicsWaiter {
  61089. struct list_head link;
  61090. bool linked;
  61091. js_cond_t cond;
  61092. int32_t *ptr;
  61093. } JSAtomicsWaiter;
  61094. static js_once_t js_atomics_once = JS_ONCE_INIT;
  61095. static js_mutex_t js_atomics_mutex;
  61096. static struct list_head js_atomics_waiter_list =
  61097. LIST_HEAD_INIT(js_atomics_waiter_list);
  61098. // no-op: Atomics.pause() is not allowed to block or yield to another
  61099. // thread, only to hint the CPU that it should back off for a bit;
  61100. // the amount of work we do here is a good enough substitute
  61101. static JSValue js_atomics_pause(JSContext *ctx, JSValueConst this_obj,
  61102. int argc, JSValueConst *argv)
  61103. {
  61104. double d;
  61105. if (argc > 0) {
  61106. switch (JS_VALUE_GET_TAG(argv[0])) {
  61107. case JS_TAG_FLOAT64: // accepted if and only if fraction == 0.0
  61108. d = JS_VALUE_GET_FLOAT64(argv[0]);
  61109. if (isfinite(d))
  61110. if (0 == modf(d, &d))
  61111. break;
  61112. // fallthru
  61113. default:
  61114. return JS_ThrowTypeError(ctx, "not an integral number");
  61115. case JS_TAG_UNDEFINED:
  61116. case JS_TAG_INT:
  61117. break;
  61118. }
  61119. }
  61120. return JS_UNDEFINED;
  61121. }
  61122. static JSValue js_atomics_wait(JSContext *ctx,
  61123. JSValueConst this_obj,
  61124. int argc, JSValueConst *argv)
  61125. {
  61126. int64_t v;
  61127. int32_t v32;
  61128. void *ptr;
  61129. int64_t timeout;
  61130. JSAtomicsWaiter waiter_s, *waiter;
  61131. int ret, size_log2, res;
  61132. double d;
  61133. ptr = js_atomics_get_ptr(ctx, NULL, &size_log2, NULL,
  61134. argv[0], argv[1], 2);
  61135. if (!ptr)
  61136. return JS_EXCEPTION;
  61137. if (size_log2 == 3) {
  61138. if (JS_ToBigInt64(ctx, &v, argv[2]))
  61139. return JS_EXCEPTION;
  61140. } else {
  61141. if (JS_ToInt32(ctx, &v32, argv[2]))
  61142. return JS_EXCEPTION;
  61143. v = v32;
  61144. }
  61145. if (JS_ToFloat64(ctx, &d, argv[3]))
  61146. return JS_EXCEPTION;
  61147. if (isnan(d) || d >= 0x1p63)
  61148. timeout = INT64_MAX;
  61149. else if (d < 0)
  61150. timeout = 0;
  61151. else
  61152. timeout = (int64_t)d;
  61153. if (!ctx->rt->can_block)
  61154. return JS_ThrowTypeError(ctx, "cannot block in this thread");
  61155. /* XXX: inefficient if large number of waiters, should hash on
  61156. 'ptr' value */
  61157. js_mutex_lock(&js_atomics_mutex);
  61158. if (size_log2 == 3) {
  61159. res = *(int64_t *)ptr != v;
  61160. } else {
  61161. res = *(int32_t *)ptr != v;
  61162. }
  61163. if (res) {
  61164. js_mutex_unlock(&js_atomics_mutex);
  61165. return JS_AtomToString(ctx, JS_ATOM_not_equal);
  61166. }
  61167. waiter = &waiter_s;
  61168. waiter->ptr = ptr;
  61169. js_cond_init(&waiter->cond);
  61170. waiter->linked = true;
  61171. list_add_tail(&waiter->link, &js_atomics_waiter_list);
  61172. if (timeout == INT64_MAX) {
  61173. js_cond_wait(&waiter->cond, &js_atomics_mutex);
  61174. ret = 0;
  61175. } else {
  61176. ret = js_cond_timedwait(&waiter->cond, &js_atomics_mutex, timeout * 1e6 /* to ns */);
  61177. }
  61178. if (waiter->linked)
  61179. list_del(&waiter->link);
  61180. js_mutex_unlock(&js_atomics_mutex);
  61181. js_cond_destroy(&waiter->cond);
  61182. if (ret == -1) {
  61183. return JS_AtomToString(ctx, JS_ATOM_timed_out);
  61184. } else {
  61185. return JS_AtomToString(ctx, JS_ATOM_ok);
  61186. }
  61187. }
  61188. static JSValue js_atomics_notify(JSContext *ctx,
  61189. JSValueConst this_obj,
  61190. int argc, JSValueConst *argv)
  61191. {
  61192. struct list_head *el, *el1, waiter_list;
  61193. int32_t count, n;
  61194. void *ptr;
  61195. JSAtomicsWaiter *waiter;
  61196. JSArrayBuffer *abuf;
  61197. ptr = js_atomics_get_ptr(ctx, &abuf, NULL, NULL, argv[0], argv[1], 1);
  61198. if (!ptr)
  61199. return JS_EXCEPTION;
  61200. if (JS_IsUndefined(argv[2])) {
  61201. count = INT32_MAX;
  61202. } else {
  61203. if (JS_ToInt32Clamp(ctx, &count, argv[2], 0, INT32_MAX, 0))
  61204. return JS_EXCEPTION;
  61205. }
  61206. if (abuf->detached)
  61207. return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);
  61208. n = 0;
  61209. if (abuf->shared && count > 0) {
  61210. js_mutex_lock(&js_atomics_mutex);
  61211. init_list_head(&waiter_list);
  61212. list_for_each_safe(el, el1, &js_atomics_waiter_list) {
  61213. waiter = list_entry(el, JSAtomicsWaiter, link);
  61214. if (waiter->ptr == ptr) {
  61215. list_del(&waiter->link);
  61216. waiter->linked = false;
  61217. list_add_tail(&waiter->link, &waiter_list);
  61218. n++;
  61219. if (n >= count)
  61220. break;
  61221. }
  61222. }
  61223. list_for_each(el, &waiter_list) {
  61224. waiter = list_entry(el, JSAtomicsWaiter, link);
  61225. js_cond_signal(&waiter->cond);
  61226. }
  61227. js_mutex_unlock(&js_atomics_mutex);
  61228. }
  61229. return js_int32(n);
  61230. }
  61231. static const JSCFunctionListEntry js_atomics_funcs[] = {
  61232. JS_CFUNC_MAGIC_DEF("add", 3, js_atomics_op, ATOMICS_OP_ADD ),
  61233. JS_CFUNC_MAGIC_DEF("and", 3, js_atomics_op, ATOMICS_OP_AND ),
  61234. JS_CFUNC_MAGIC_DEF("or", 3, js_atomics_op, ATOMICS_OP_OR ),
  61235. JS_CFUNC_MAGIC_DEF("sub", 3, js_atomics_op, ATOMICS_OP_SUB ),
  61236. JS_CFUNC_MAGIC_DEF("xor", 3, js_atomics_op, ATOMICS_OP_XOR ),
  61237. JS_CFUNC_MAGIC_DEF("exchange", 3, js_atomics_op, ATOMICS_OP_EXCHANGE ),
  61238. JS_CFUNC_MAGIC_DEF("compareExchange", 4, js_atomics_op, ATOMICS_OP_COMPARE_EXCHANGE ),
  61239. JS_CFUNC_MAGIC_DEF("load", 2, js_atomics_op, ATOMICS_OP_LOAD ),
  61240. JS_CFUNC_DEF("store", 3, js_atomics_store ),
  61241. JS_CFUNC_DEF("isLockFree", 1, js_atomics_isLockFree ),
  61242. JS_CFUNC_DEF("pause", 0, js_atomics_pause ),
  61243. JS_CFUNC_DEF("wait", 4, js_atomics_wait ),
  61244. JS_CFUNC_DEF("notify", 3, js_atomics_notify ),
  61245. JS_PROP_STRING_DEF("[Symbol.toStringTag]", "Atomics", JS_PROP_CONFIGURABLE ),
  61246. };
  61247. static const JSCFunctionListEntry js_atomics_obj[] = {
  61248. JS_OBJECT_DEF("Atomics", js_atomics_funcs, countof(js_atomics_funcs), JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE ),
  61249. };
  61250. static void js__atomics_init(void) {
  61251. js_mutex_init(&js_atomics_mutex);
  61252. }
  61253. /* TODO(saghul) make this public and not dependent on typed arrays? */
  61254. void JS_AddIntrinsicAtomics(JSContext *ctx)
  61255. {
  61256. js_once(&js_atomics_once, js__atomics_init);
  61257. /* add Atomics as autoinit object */
  61258. JS_SetPropertyFunctionList(ctx, ctx->global_obj, js_atomics_obj, countof(js_atomics_obj));
  61259. }
  61260. #endif /* CONFIG_ATOMICS */
  61261. void JS_AddIntrinsicTypedArrays(JSContext *ctx)
  61262. {
  61263. JSValue typed_array_base_proto, typed_array_base_func;
  61264. JSValue array_buffer_func, shared_array_buffer_func;
  61265. int i;
  61266. ctx->class_proto[JS_CLASS_ARRAY_BUFFER] = JS_NewObject(ctx);
  61267. JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_ARRAY_BUFFER],
  61268. js_array_buffer_proto_funcs,
  61269. countof(js_array_buffer_proto_funcs));
  61270. array_buffer_func = JS_NewGlobalCConstructorOnly(ctx, "ArrayBuffer",
  61271. js_array_buffer_constructor, 1,
  61272. ctx->class_proto[JS_CLASS_ARRAY_BUFFER]);
  61273. JS_SetPropertyFunctionList(ctx, array_buffer_func,
  61274. js_array_buffer_funcs,
  61275. countof(js_array_buffer_funcs));
  61276. ctx->class_proto[JS_CLASS_SHARED_ARRAY_BUFFER] = JS_NewObject(ctx);
  61277. JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_SHARED_ARRAY_BUFFER],
  61278. js_shared_array_buffer_proto_funcs,
  61279. countof(js_shared_array_buffer_proto_funcs));
  61280. shared_array_buffer_func = JS_NewGlobalCConstructorOnly(ctx, "SharedArrayBuffer",
  61281. js_shared_array_buffer_constructor, 1,
  61282. ctx->class_proto[JS_CLASS_SHARED_ARRAY_BUFFER]);
  61283. JS_SetPropertyFunctionList(ctx, shared_array_buffer_func,
  61284. js_shared_array_buffer_funcs,
  61285. countof(js_shared_array_buffer_funcs));
  61286. typed_array_base_proto = JS_NewObject(ctx);
  61287. JS_SetPropertyFunctionList(ctx, typed_array_base_proto,
  61288. js_typed_array_base_proto_funcs,
  61289. countof(js_typed_array_base_proto_funcs));
  61290. /* TypedArray.prototype.toString must be the same object as Array.prototype.toString */
  61291. JSValue obj = JS_GetProperty(ctx, ctx->class_proto[JS_CLASS_ARRAY], JS_ATOM_toString);
  61292. /* XXX: should use alias method in JSCFunctionListEntry */ //@@@
  61293. JS_DefinePropertyValue(ctx, typed_array_base_proto, JS_ATOM_toString, obj,
  61294. JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);
  61295. typed_array_base_func = JS_NewCFunction(ctx, js_typed_array_base_constructor,
  61296. "TypedArray", 0);
  61297. JS_SetPropertyFunctionList(ctx, typed_array_base_func,
  61298. js_typed_array_base_funcs,
  61299. countof(js_typed_array_base_funcs));
  61300. JS_SetConstructor(ctx, typed_array_base_func, typed_array_base_proto);
  61301. /* Used to squelch a -Wcast-function-type warning. */
  61302. JSCFunctionType ft = { .generic_magic = js_typed_array_constructor };
  61303. for(i = JS_CLASS_UINT8C_ARRAY; i < JS_CLASS_UINT8C_ARRAY + JS_TYPED_ARRAY_COUNT; i++) {
  61304. JSValue func_obj;
  61305. char buf[ATOM_GET_STR_BUF_SIZE];
  61306. const char *name;
  61307. ctx->class_proto[i] = JS_NewObjectProto(ctx, typed_array_base_proto);
  61308. JS_DefinePropertyValueStr(ctx, ctx->class_proto[i],
  61309. "BYTES_PER_ELEMENT",
  61310. js_int32(1 << typed_array_size_log2(i)),
  61311. 0);
  61312. name = JS_AtomGetStr(ctx, buf, sizeof(buf),
  61313. JS_ATOM_Uint8ClampedArray + i - JS_CLASS_UINT8C_ARRAY);
  61314. func_obj = JS_NewCFunction3(ctx, ft.generic,
  61315. name, 3, JS_CFUNC_constructor_magic, i,
  61316. typed_array_base_func);
  61317. JS_NewGlobalCConstructor2(ctx, func_obj, name, ctx->class_proto[i]);
  61318. JS_DefinePropertyValueStr(ctx, func_obj,
  61319. "BYTES_PER_ELEMENT",
  61320. js_int32(1 << typed_array_size_log2(i)),
  61321. 0);
  61322. }
  61323. JS_FreeValue(ctx, typed_array_base_proto);
  61324. JS_FreeValue(ctx, typed_array_base_func);
  61325. /* DataView */
  61326. ctx->class_proto[JS_CLASS_DATAVIEW] = JS_NewObject(ctx);
  61327. JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_DATAVIEW],
  61328. js_dataview_proto_funcs,
  61329. countof(js_dataview_proto_funcs));
  61330. JS_NewGlobalCConstructorOnly(ctx, "DataView",
  61331. js_dataview_constructor, 1,
  61332. ctx->class_proto[JS_CLASS_DATAVIEW]);
  61333. /* Atomics */
  61334. #ifdef CONFIG_ATOMICS
  61335. JS_AddIntrinsicAtomics(ctx);
  61336. #endif
  61337. }
  61338. /* Performance */
  61339. static double js__now_ms(void)
  61340. {
  61341. return js__hrtime_ns() / 1e6;
  61342. }
  61343. static JSValue js_perf_now(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)
  61344. {
  61345. return js_float64(js__now_ms() - ctx->time_origin);
  61346. }
  61347. static const JSCFunctionListEntry js_perf_proto_funcs[] = {
  61348. JS_CFUNC_DEF2("now", 0, js_perf_now, JS_PROP_ENUMERABLE),
  61349. };
  61350. void JS_AddPerformance(JSContext *ctx)
  61351. {
  61352. ctx->time_origin = js__now_ms();
  61353. JSValue performance = JS_NewObject(ctx);
  61354. JS_SetPropertyFunctionList(ctx, performance, js_perf_proto_funcs, countof(js_perf_proto_funcs));
  61355. JS_DefinePropertyValueStr(ctx, performance, "timeOrigin",
  61356. js_float64(ctx->time_origin),
  61357. JS_PROP_ENUMERABLE);
  61358. JS_DefinePropertyValueStr(ctx, ctx->global_obj, "performance",
  61359. js_dup(performance),
  61360. JS_PROP_WRITABLE | JS_PROP_ENUMERABLE | JS_PROP_CONFIGURABLE);
  61361. JS_FreeValue(ctx, performance);
  61362. }
  61363. /* Equality comparisons and sameness */
  61364. int JS_IsEqual(JSContext *ctx, JSValueConst op1, JSValueConst op2)
  61365. {
  61366. JSValue sp[2] = { js_dup(op1), js_dup(op2) };
  61367. if (js_eq_slow(ctx, endof(sp), 0))
  61368. return -1;
  61369. return JS_VALUE_GET_BOOL(sp[0]);
  61370. }
  61371. bool JS_IsStrictEqual(JSContext *ctx, JSValueConst op1, JSValueConst op2)
  61372. {
  61373. return js_strict_eq2(ctx, js_dup(op1), js_dup(op2), JS_EQ_STRICT);
  61374. }
  61375. bool JS_IsSameValue(JSContext *ctx, JSValueConst op1, JSValueConst op2)
  61376. {
  61377. return js_same_value(ctx, op1, op2);
  61378. }
  61379. bool JS_IsSameValueZero(JSContext *ctx, JSValueConst op1, JSValueConst op2)
  61380. {
  61381. return js_same_value_zero(ctx, op1, op2);
  61382. }
  61383. /* WeakRef */
  61384. typedef struct JSWeakRefData {
  61385. JSValueConst target;
  61386. JSValue obj;
  61387. } JSWeakRefData;
  61388. static JSWeakRefData js_weakref_sentinel;
  61389. static void js_weakref_finalizer(JSRuntime *rt, JSValueConst val)
  61390. {
  61391. JSWeakRefData *wrd = JS_GetOpaque(val, JS_CLASS_WEAK_REF);
  61392. if (!wrd || wrd == &js_weakref_sentinel)
  61393. return;
  61394. /* Delete weak ref */
  61395. JSWeakRefRecord **pwr, *wr;
  61396. pwr = get_first_weak_ref(wrd->target);
  61397. for(;;) {
  61398. wr = *pwr;
  61399. assert(wr != NULL);
  61400. if (wr->kind == JS_WEAK_REF_KIND_WEAK_REF && wr->u.weak_ref_data == wrd)
  61401. break;
  61402. pwr = &wr->next_weak_ref;
  61403. }
  61404. *pwr = wr->next_weak_ref;
  61405. js_free_rt(rt, wrd);
  61406. js_free_rt(rt, wr);
  61407. }
  61408. static JSValue js_weakref_constructor(JSContext *ctx, JSValueConst new_target,
  61409. int argc, JSValueConst *argv)
  61410. {
  61411. if (JS_IsUndefined(new_target))
  61412. return JS_ThrowTypeError(ctx, "constructor requires 'new'");
  61413. JSValueConst arg = argv[0];
  61414. if (!is_valid_weakref_target(arg))
  61415. return JS_ThrowTypeError(ctx, "invalid target");
  61416. // TODO(saghul): short-circuit if the refcount is 1?
  61417. JSValue obj = js_create_from_ctor(ctx, new_target, JS_CLASS_WEAK_REF);
  61418. if (JS_IsException(obj))
  61419. return JS_EXCEPTION;
  61420. JSWeakRefData *wrd = js_malloc(ctx, sizeof(*wrd));
  61421. if (!wrd) {
  61422. JS_FreeValue(ctx, obj);
  61423. return JS_EXCEPTION;
  61424. }
  61425. JSWeakRefRecord *wr = js_malloc(ctx, sizeof(*wr));
  61426. if (!wr) {
  61427. JS_FreeValue(ctx, obj);
  61428. js_free(ctx, wrd);
  61429. return JS_EXCEPTION;
  61430. }
  61431. wrd->target = arg;
  61432. wrd->obj = obj;
  61433. wr->kind = JS_WEAK_REF_KIND_WEAK_REF;
  61434. wr->u.weak_ref_data = wrd;
  61435. insert_weakref_record(arg, wr);
  61436. JS_SetOpaqueInternal(obj, wrd);
  61437. return obj;
  61438. }
  61439. static JSValue js_weakref_deref(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)
  61440. {
  61441. JSWeakRefData *wrd = JS_GetOpaque2(ctx, this_val, JS_CLASS_WEAK_REF);
  61442. if (!wrd)
  61443. return JS_EXCEPTION;
  61444. if (wrd == &js_weakref_sentinel)
  61445. return JS_UNDEFINED;
  61446. return js_dup(wrd->target);
  61447. }
  61448. static const JSCFunctionListEntry js_weakref_proto_funcs[] = {
  61449. JS_CFUNC_DEF("deref", 0, js_weakref_deref ),
  61450. JS_PROP_STRING_DEF("[Symbol.toStringTag]", "WeakRef", JS_PROP_CONFIGURABLE ),
  61451. };
  61452. static const JSClassShortDef js_weakref_class_def[] = {
  61453. { JS_ATOM_WeakRef, js_weakref_finalizer, NULL }, /* JS_CLASS_WEAK_REF */
  61454. };
  61455. typedef struct JSFinRecEntry {
  61456. struct list_head link;
  61457. JSValueConst obj;
  61458. JSValueConst target;
  61459. JSValue held_val;
  61460. JSValue token;
  61461. } JSFinRecEntry;
  61462. typedef struct JSFinalizationRegistryData {
  61463. struct list_head entries;
  61464. JSContext *ctx;
  61465. JSValue cb;
  61466. } JSFinalizationRegistryData;
  61467. static void delete_finrec_weakref(JSRuntime *rt, JSFinRecEntry *fre)
  61468. {
  61469. JSWeakRefRecord **pwr, *wr;
  61470. pwr = get_first_weak_ref(fre->target);
  61471. for(;;) {
  61472. wr = *pwr;
  61473. assert(wr != NULL);
  61474. if (wr->kind == JS_WEAK_REF_KIND_FINALIZATION_REGISTRY_ENTRY && wr->u.fin_rec_entry == fre)
  61475. break;
  61476. pwr = &wr->next_weak_ref;
  61477. }
  61478. *pwr = wr->next_weak_ref;
  61479. js_free_rt(rt, wr);
  61480. }
  61481. static void js_finrec_finalizer(JSRuntime *rt, JSValueConst val)
  61482. {
  61483. JSFinalizationRegistryData *frd = JS_GetOpaque(val, JS_CLASS_FINALIZATION_REGISTRY);
  61484. if (frd) {
  61485. struct list_head *el, *el1;
  61486. /* first pass to remove the weak ref entries and avoid having them modified
  61487. by freeing a token / held value. */
  61488. list_for_each_safe(el, el1, &frd->entries) {
  61489. JSFinRecEntry *fre = list_entry(el, JSFinRecEntry, link);
  61490. delete_finrec_weakref(rt, fre);
  61491. }
  61492. /* second pass to actually free all objects. */
  61493. list_for_each_safe(el, el1, &frd->entries) {
  61494. JSFinRecEntry *fre = list_entry(el, JSFinRecEntry, link);
  61495. list_del(&fre->link);
  61496. JS_FreeValueRT(rt, fre->held_val);
  61497. JS_FreeValueRT(rt, fre->token);
  61498. js_free_rt(rt, fre);
  61499. }
  61500. JS_FreeValueRT(rt, frd->cb);
  61501. js_free_rt(rt, frd);
  61502. }
  61503. }
  61504. static void js_finrec_mark(JSRuntime *rt, JSValueConst val,
  61505. JS_MarkFunc *mark_func)
  61506. {
  61507. JSFinalizationRegistryData *frd = JS_GetOpaque(val, JS_CLASS_FINALIZATION_REGISTRY);
  61508. if (frd) {
  61509. JS_MarkValue(rt, frd->cb, mark_func);
  61510. struct list_head *el;
  61511. list_for_each(el, &frd->entries) {
  61512. JSFinRecEntry *fre = list_entry(el, JSFinRecEntry, link);
  61513. JS_MarkValue(rt, fre->held_val, mark_func);
  61514. JS_MarkValue(rt, fre->token, mark_func);
  61515. }
  61516. }
  61517. }
  61518. static JSValue js_finrec_constructor(JSContext *ctx, JSValueConst new_target,
  61519. int argc, JSValueConst *argv)
  61520. {
  61521. if (JS_IsUndefined(new_target))
  61522. return JS_ThrowTypeError(ctx, "constructor requires 'new'");
  61523. JSValueConst cb = argv[0];
  61524. if (!JS_IsFunction(ctx, cb))
  61525. return JS_ThrowTypeError(ctx, "argument must be a function");
  61526. JSValue obj = js_create_from_ctor(ctx, new_target, JS_CLASS_FINALIZATION_REGISTRY);
  61527. if (JS_IsException(obj))
  61528. return JS_EXCEPTION;
  61529. JSFinalizationRegistryData *frd = js_malloc(ctx, sizeof(*frd));
  61530. if (!frd) {
  61531. JS_FreeValue(ctx, obj);
  61532. return JS_EXCEPTION;
  61533. }
  61534. init_list_head(&frd->entries);
  61535. frd->ctx = ctx;
  61536. frd->cb = js_dup(cb);
  61537. JS_SetOpaqueInternal(obj, frd);
  61538. return obj;
  61539. }
  61540. static JSValue js_finrec_register(JSContext *ctx, JSValueConst this_val,
  61541. int argc, JSValueConst *argv)
  61542. {
  61543. JSFinalizationRegistryData *frd = JS_GetOpaque2(ctx, this_val, JS_CLASS_FINALIZATION_REGISTRY);
  61544. if (!frd)
  61545. return JS_EXCEPTION;
  61546. JSValueConst target = argv[0];
  61547. JSValueConst held_val = argv[1];
  61548. // The function length needs to return 2, so the 3rd argument won't be initialized.
  61549. JSValueConst token = argc > 2 ? argv[2] : JS_UNDEFINED;
  61550. if (!is_valid_weakref_target(target))
  61551. return JS_ThrowTypeError(ctx, "invalid target");
  61552. if (js_same_value(ctx, target, this_val))
  61553. return JS_UNDEFINED;
  61554. if (!JS_IsUndefined(held_val) && js_same_value(ctx, target, held_val))
  61555. return JS_ThrowTypeError(ctx, "held value cannot be the target");
  61556. if (!JS_IsUndefined(token) && !is_valid_weakref_target(token))
  61557. return JS_ThrowTypeError(ctx, "invalid unregister token");
  61558. JSFinRecEntry *fre = js_malloc(ctx, sizeof(*fre));
  61559. if (!fre)
  61560. return JS_EXCEPTION;
  61561. JSWeakRefRecord *wr = js_malloc(ctx, sizeof(*wr));
  61562. if (!wr) {
  61563. js_free(ctx, fre);
  61564. return JS_EXCEPTION;
  61565. }
  61566. fre->obj = this_val;
  61567. fre->target = target;
  61568. fre->held_val = js_dup(held_val);
  61569. fre->token = js_dup(token);
  61570. list_add_tail(&fre->link, &frd->entries);
  61571. wr->kind = JS_WEAK_REF_KIND_FINALIZATION_REGISTRY_ENTRY;
  61572. wr->u.fin_rec_entry = fre;
  61573. insert_weakref_record(target, wr);
  61574. return JS_UNDEFINED;
  61575. }
  61576. static JSValue js_finrec_unregister(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)
  61577. {
  61578. JSFinalizationRegistryData *frd = JS_GetOpaque2(ctx, this_val, JS_CLASS_FINALIZATION_REGISTRY);
  61579. if (!frd)
  61580. return JS_EXCEPTION;
  61581. JSValueConst token = argv[0];
  61582. if (!is_valid_weakref_target(token))
  61583. return JS_ThrowTypeError(ctx, "invalid unregister token");
  61584. struct list_head *el, *el1;
  61585. bool removed = false;
  61586. list_for_each_safe(el, el1, &frd->entries) {
  61587. JSFinRecEntry *fre = list_entry(el, JSFinRecEntry, link);
  61588. if (js_same_value(ctx, fre->token, token)) {
  61589. list_del(&fre->link);
  61590. delete_finrec_weakref(ctx->rt, fre);
  61591. JS_FreeValue(ctx, fre->held_val);
  61592. JS_FreeValue(ctx, fre->token);
  61593. js_free(ctx, fre);
  61594. removed = true;
  61595. }
  61596. }
  61597. return js_bool(removed);
  61598. }
  61599. static const JSCFunctionListEntry js_finrec_proto_funcs[] = {
  61600. JS_CFUNC_DEF("register", 2, js_finrec_register ),
  61601. JS_CFUNC_DEF("unregister", 1, js_finrec_unregister ),
  61602. JS_PROP_STRING_DEF("[Symbol.toStringTag]", "FinalizationRegistry", JS_PROP_CONFIGURABLE ),
  61603. };
  61604. static const JSClassShortDef js_finrec_class_def[] = {
  61605. { JS_ATOM_FinalizationRegistry, js_finrec_finalizer, js_finrec_mark }, /* JS_CLASS_FINALIZATION_REGISTRY */
  61606. };
  61607. static JSValue js_finrec_job(JSContext *ctx, int argc, JSValueConst *argv)
  61608. {
  61609. return JS_Call(ctx, argv[0], JS_UNDEFINED, 1, &argv[1]);
  61610. }
  61611. void JS_AddIntrinsicWeakRef(JSContext *ctx)
  61612. {
  61613. JSRuntime *rt = ctx->rt;
  61614. /* WeakRef */
  61615. if (!JS_IsRegisteredClass(rt, JS_CLASS_WEAK_REF)) {
  61616. init_class_range(rt, js_weakref_class_def, JS_CLASS_WEAK_REF,
  61617. countof(js_weakref_class_def));
  61618. }
  61619. ctx->class_proto[JS_CLASS_WEAK_REF] = JS_NewObject(ctx);
  61620. JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_WEAK_REF],
  61621. js_weakref_proto_funcs,
  61622. countof(js_weakref_proto_funcs));
  61623. JS_NewGlobalCConstructor(ctx, "WeakRef", js_weakref_constructor, 1, ctx->class_proto[JS_CLASS_WEAK_REF]);
  61624. /* FinalizationRegistry */
  61625. if (!JS_IsRegisteredClass(rt, JS_CLASS_FINALIZATION_REGISTRY)) {
  61626. init_class_range(rt, js_finrec_class_def, JS_CLASS_FINALIZATION_REGISTRY,
  61627. countof(js_finrec_class_def));
  61628. }
  61629. ctx->class_proto[JS_CLASS_FINALIZATION_REGISTRY] = JS_NewObject(ctx);
  61630. JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_FINALIZATION_REGISTRY],
  61631. js_finrec_proto_funcs,
  61632. countof(js_finrec_proto_funcs));
  61633. JS_NewGlobalCConstructor(ctx, "FinalizationRegistry", js_finrec_constructor, 1, ctx->class_proto[JS_CLASS_FINALIZATION_REGISTRY]);
  61634. }
  61635. static void reset_weak_ref(JSRuntime *rt, JSWeakRefRecord **first_weak_ref)
  61636. {
  61637. JSWeakRefRecord *wr, *wr_next;
  61638. JSWeakRefData *wrd;
  61639. JSMapRecord *mr;
  61640. JSMapState *s;
  61641. JSFinRecEntry *fre;
  61642. /* first pass to remove the records from the WeakMap/WeakSet
  61643. lists */
  61644. for(wr = *first_weak_ref; wr != NULL; wr = wr->next_weak_ref) {
  61645. switch(wr->kind) {
  61646. case JS_WEAK_REF_KIND_MAP:
  61647. mr = wr->u.map_record;
  61648. s = mr->map;
  61649. assert(s->is_weak);
  61650. assert(!mr->empty); /* no iterator on WeakMap/WeakSet */
  61651. list_del(&mr->hash_link);
  61652. list_del(&mr->link);
  61653. break;
  61654. case JS_WEAK_REF_KIND_WEAK_REF:
  61655. wrd = wr->u.weak_ref_data;
  61656. wrd->target = JS_UNDEFINED;
  61657. break;
  61658. case JS_WEAK_REF_KIND_FINALIZATION_REGISTRY_ENTRY:
  61659. fre = wr->u.fin_rec_entry;
  61660. list_del(&fre->link);
  61661. break;
  61662. default:
  61663. abort();
  61664. }
  61665. }
  61666. /* second pass to free the values to avoid modifying the weak
  61667. reference list while traversing it. */
  61668. for(wr = *first_weak_ref; wr != NULL; wr = wr_next) {
  61669. wr_next = wr->next_weak_ref;
  61670. switch(wr->kind) {
  61671. case JS_WEAK_REF_KIND_MAP:
  61672. mr = wr->u.map_record;
  61673. JS_FreeValueRT(rt, mr->value);
  61674. js_free_rt(rt, mr);
  61675. break;
  61676. case JS_WEAK_REF_KIND_WEAK_REF:
  61677. wrd = wr->u.weak_ref_data;
  61678. JS_SetOpaqueInternal(wrd->obj, &js_weakref_sentinel);
  61679. js_free_rt(rt, wrd);
  61680. break;
  61681. case JS_WEAK_REF_KIND_FINALIZATION_REGISTRY_ENTRY: {
  61682. fre = wr->u.fin_rec_entry;
  61683. JSFinalizationRegistryData *frd = JS_GetOpaque(fre->obj, JS_CLASS_FINALIZATION_REGISTRY);
  61684. assert(frd != NULL);
  61685. /**
  61686. * During the GC sweep phase the held object might be collected first.
  61687. */
  61688. if (!rt->in_free && (!JS_IsObject(fre->held_val) || JS_IsLiveObject(rt, fre->held_val))) {
  61689. JSValueConst args[2];
  61690. args[0] = frd->cb;
  61691. args[1] = fre->held_val;
  61692. JS_EnqueueJob(frd->ctx, js_finrec_job, 2, args);
  61693. }
  61694. JS_FreeValueRT(rt, fre->held_val);
  61695. JS_FreeValueRT(rt, fre->token);
  61696. js_free_rt(rt, fre);
  61697. break;
  61698. }
  61699. default:
  61700. abort();
  61701. }
  61702. js_free_rt(rt, wr);
  61703. }
  61704. *first_weak_ref = NULL; /* fail safe */
  61705. }
  61706. static bool is_valid_weakref_target(JSValueConst val)
  61707. {
  61708. switch (JS_VALUE_GET_TAG(val)) {
  61709. case JS_TAG_OBJECT:
  61710. break;
  61711. case JS_TAG_SYMBOL: {
  61712. // Per spec: prohibit symbols registered with Symbol.for()
  61713. JSAtomStruct *p = JS_VALUE_GET_PTR(val);
  61714. if (p->atom_type != JS_ATOM_TYPE_GLOBAL_SYMBOL)
  61715. break;
  61716. // fallthru
  61717. }
  61718. default:
  61719. return false;
  61720. }
  61721. return true;
  61722. }
  61723. static void insert_weakref_record(JSValueConst target,
  61724. struct JSWeakRefRecord *wr)
  61725. {
  61726. JSWeakRefRecord **pwr = get_first_weak_ref(target);
  61727. /* Add the weak reference */
  61728. wr->next_weak_ref = *pwr;
  61729. *pwr = wr;
  61730. }
  61731. /* CallSite */
  61732. static void js_callsite_finalizer(JSRuntime *rt, JSValueConst val)
  61733. {
  61734. JSCallSiteData *csd = JS_GetOpaque(val, JS_CLASS_CALL_SITE);
  61735. if (csd) {
  61736. JS_FreeValueRT(rt, csd->filename);
  61737. JS_FreeValueRT(rt, csd->func);
  61738. JS_FreeValueRT(rt, csd->func_name);
  61739. js_free_rt(rt, csd);
  61740. }
  61741. }
  61742. static void js_callsite_mark(JSRuntime *rt, JSValueConst val,
  61743. JS_MarkFunc *mark_func)
  61744. {
  61745. JSCallSiteData *csd = JS_GetOpaque(val, JS_CLASS_CALL_SITE);
  61746. if (csd) {
  61747. JS_MarkValue(rt, csd->filename, mark_func);
  61748. JS_MarkValue(rt, csd->func, mark_func);
  61749. JS_MarkValue(rt, csd->func_name, mark_func);
  61750. }
  61751. }
  61752. static JSValue js_new_callsite(JSContext *ctx, JSCallSiteData *csd) {
  61753. JSValue obj = js_create_from_ctor(ctx, JS_UNDEFINED, JS_CLASS_CALL_SITE);
  61754. if (JS_IsException(obj))
  61755. return JS_EXCEPTION;
  61756. JSCallSiteData *csd1 = js_malloc(ctx, sizeof(*csd));
  61757. if (!csd1) {
  61758. JS_FreeValue(ctx, obj);
  61759. return JS_EXCEPTION;
  61760. }
  61761. memcpy(csd1, csd, sizeof(*csd));
  61762. JS_SetOpaqueInternal(obj, csd1);
  61763. return obj;
  61764. }
  61765. static void js_new_callsite_data(JSContext *ctx, JSCallSiteData *csd, JSStackFrame *sf)
  61766. {
  61767. const char *func_name_str;
  61768. JSObject *p;
  61769. csd->func = js_dup(sf->cur_func);
  61770. /* func_name_str is UTF-8 encoded if needed */
  61771. func_name_str = get_func_name(ctx, sf->cur_func);
  61772. if (!func_name_str || func_name_str[0] == '\0')
  61773. csd->func_name = JS_NULL;
  61774. else
  61775. csd->func_name = JS_NewString(ctx, func_name_str);
  61776. JS_FreeCString(ctx, func_name_str);
  61777. if (JS_IsException(csd->func_name))
  61778. csd->func_name = JS_NULL;
  61779. p = JS_VALUE_GET_OBJ(sf->cur_func);
  61780. if (js_class_has_bytecode(p->class_id)) {
  61781. JSFunctionBytecode *b = p->u.func.function_bytecode;
  61782. int line_num1, col_num1;
  61783. line_num1 = find_line_num(ctx, b,
  61784. sf->cur_pc - b->byte_code_buf - 1,
  61785. &col_num1);
  61786. csd->native = false;
  61787. csd->line_num = line_num1;
  61788. csd->col_num = col_num1;
  61789. csd->filename = JS_AtomToString(ctx, b->filename);
  61790. if (JS_IsException(csd->filename)) {
  61791. csd->filename = JS_NULL;
  61792. JS_FreeValue(ctx, JS_GetException(ctx)); // Clear exception.
  61793. }
  61794. } else {
  61795. csd->native = true;
  61796. csd->line_num = -1;
  61797. csd->col_num = -1;
  61798. csd->filename = JS_NULL;
  61799. }
  61800. }
  61801. static void js_new_callsite_data2(JSContext *ctx, JSCallSiteData *csd, const char *filename, int line_num, int col_num)
  61802. {
  61803. csd->func = JS_NULL;
  61804. csd->func_name = JS_NULL;
  61805. csd->native = false;
  61806. csd->line_num = line_num;
  61807. csd->col_num = col_num;
  61808. /* filename is UTF-8 encoded if needed (original argument to __JS_EvalInternal()) */
  61809. csd->filename = JS_NewString(ctx, filename);
  61810. if (JS_IsException(csd->filename)) {
  61811. csd->filename = JS_NULL;
  61812. JS_FreeValue(ctx, JS_GetException(ctx)); // Clear exception.
  61813. }
  61814. }
  61815. static JSValue js_callsite_getfield(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic)
  61816. {
  61817. JSCallSiteData *csd = JS_GetOpaque2(ctx, this_val, JS_CLASS_CALL_SITE);
  61818. if (!csd)
  61819. return JS_EXCEPTION;
  61820. JSValue *field = (void *)((char *)csd + magic);
  61821. return js_dup(*field);
  61822. }
  61823. static JSValue js_callsite_isnative(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)
  61824. {
  61825. JSCallSiteData *csd = JS_GetOpaque2(ctx, this_val, JS_CLASS_CALL_SITE);
  61826. if (!csd)
  61827. return JS_EXCEPTION;
  61828. return JS_NewBool(ctx, csd->native);
  61829. }
  61830. static JSValue js_callsite_getnumber(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic)
  61831. {
  61832. JSCallSiteData *csd = JS_GetOpaque2(ctx, this_val, JS_CLASS_CALL_SITE);
  61833. if (!csd)
  61834. return JS_EXCEPTION;
  61835. int *field = (void *)((char *)csd + magic);
  61836. return JS_NewInt32(ctx, *field);
  61837. }
  61838. static const JSCFunctionListEntry js_callsite_proto_funcs[] = {
  61839. JS_CFUNC_DEF("isNative", 0, js_callsite_isnative),
  61840. JS_CFUNC_MAGIC_DEF("getFileName", 0, js_callsite_getfield, offsetof(JSCallSiteData, filename)),
  61841. JS_CFUNC_MAGIC_DEF("getFunction", 0, js_callsite_getfield, offsetof(JSCallSiteData, func)),
  61842. JS_CFUNC_MAGIC_DEF("getFunctionName", 0, js_callsite_getfield, offsetof(JSCallSiteData, func_name)),
  61843. JS_CFUNC_MAGIC_DEF("getColumnNumber", 0, js_callsite_getnumber, offsetof(JSCallSiteData, col_num)),
  61844. JS_CFUNC_MAGIC_DEF("getLineNumber", 0, js_callsite_getnumber, offsetof(JSCallSiteData, line_num)),
  61845. JS_PROP_STRING_DEF("[Symbol.toStringTag]", "CallSite", JS_PROP_CONFIGURABLE ),
  61846. };
  61847. static const JSClassShortDef js_callsite_class_def[] = {
  61848. { JS_ATOM_CallSite, js_callsite_finalizer, js_callsite_mark }, /* JS_CLASS_CALL_SITE */
  61849. };
  61850. static void _JS_AddIntrinsicCallSite(JSContext *ctx)
  61851. {
  61852. JSRuntime *rt = ctx->rt;
  61853. if (!JS_IsRegisteredClass(rt, JS_CLASS_CALL_SITE)) {
  61854. init_class_range(rt, js_callsite_class_def, JS_CLASS_CALL_SITE,
  61855. countof(js_callsite_class_def));
  61856. }
  61857. ctx->class_proto[JS_CLASS_CALL_SITE] = JS_NewObject(ctx);
  61858. JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_CALL_SITE],
  61859. js_callsite_proto_funcs,
  61860. countof(js_callsite_proto_funcs));
  61861. }
  61862. bool JS_DetectModule(const char *input, size_t input_len)
  61863. {
  61864. JSRuntime *rt;
  61865. JSContext *ctx;
  61866. JSValue val;
  61867. bool is_module;
  61868. is_module = true;
  61869. rt = JS_NewRuntime();
  61870. if (!rt)
  61871. return false;
  61872. ctx = JS_NewContextRaw(rt);
  61873. if (!ctx) {
  61874. JS_FreeRuntime(rt);
  61875. return false;
  61876. }
  61877. JS_AddIntrinsicRegExpCompiler(ctx); // otherwise regexp literals don't parse
  61878. val = __JS_EvalInternal(ctx, JS_UNDEFINED, input, input_len, "<unnamed>", 1,
  61879. JS_EVAL_TYPE_MODULE|JS_EVAL_FLAG_COMPILE_ONLY, -1);
  61880. if (JS_IsException(val)) {
  61881. const char *msg = JS_ToCString(ctx, rt->current_exception);
  61882. // gruesome hack to recognize exceptions from import statements;
  61883. // necessary because we don't pass in a module loader
  61884. is_module = !!strstr(msg, "ReferenceError: could not load module");
  61885. JS_FreeCString(ctx, msg);
  61886. }
  61887. JS_FreeValue(ctx, val);
  61888. JS_FreeContext(ctx);
  61889. JS_FreeRuntime(rt);
  61890. return is_module;
  61891. }
  61892. uintptr_t js_std_cmd(int cmd, ...) {
  61893. JSContext *ctx;
  61894. JSRuntime *rt;
  61895. JSValue *pv;
  61896. uintptr_t rv;
  61897. va_list ap;
  61898. rv = 0;
  61899. va_start(ap, cmd);
  61900. switch (cmd) {
  61901. case 0: // GetOpaque
  61902. rt = va_arg(ap, JSRuntime *);
  61903. rv = (uintptr_t)rt->libc_opaque;
  61904. break;
  61905. case 1: // SetOpaque
  61906. rt = va_arg(ap, JSRuntime *);
  61907. rt->libc_opaque = va_arg(ap, void *);
  61908. break;
  61909. case 2: // ErrorBackTrace
  61910. ctx = va_arg(ap, JSContext *);
  61911. pv = va_arg(ap, JSValue *);
  61912. *pv = ctx->error_back_trace;
  61913. ctx->error_back_trace = JS_UNDEFINED;
  61914. break;
  61915. default:
  61916. rv = -1;
  61917. }
  61918. va_end(ap);
  61919. return rv;
  61920. }
  61921. #undef malloc
  61922. #undef free
  61923. #undef realloc
  61924. /*
  61925. * C utilities
  61926. *
  61927. * Copyright (c) 2017 Fabrice Bellard
  61928. * Copyright (c) 2018 Charlie Gordon
  61929. *
  61930. * Permission is hereby granted, free of charge, to any person obtaining a copy
  61931. * of this software and associated documentation files (the "Software"), to deal
  61932. * in the Software without restriction, including without limitation the rights
  61933. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  61934. * copies of the Software, and to permit persons to whom the Software is
  61935. * furnished to do so, subject to the following conditions:
  61936. *
  61937. * The above copyright notice and this permission notice shall be included in
  61938. * all copies or substantial portions of the Software.
  61939. *
  61940. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  61941. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  61942. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  61943. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  61944. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  61945. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  61946. * THE SOFTWARE.
  61947. */
  61948. #include <assert.h>
  61949. #include <stdlib.h>
  61950. #include <stdio.h>
  61951. #include <stdarg.h>
  61952. #include <string.h>
  61953. #include <time.h>
  61954. #if !defined(_MSC_VER)
  61955. #include <sys/time.h>
  61956. #endif
  61957. #undef NANOSEC
  61958. #define NANOSEC ((uint64_t) 1e9)
  61959. #ifdef __GNUC__
  61960. #pragma GCC visibility push(default)
  61961. #endif
  61962. void js__pstrcpy(char *buf, int buf_size, const char *str)
  61963. {
  61964. int c;
  61965. char *q = buf;
  61966. if (buf_size <= 0)
  61967. return;
  61968. for(;;) {
  61969. c = *str++;
  61970. if (c == 0 || q >= buf + buf_size - 1)
  61971. break;
  61972. *q++ = c;
  61973. }
  61974. *q = '\0';
  61975. }
  61976. /* strcat and truncate. */
  61977. char *js__pstrcat(char *buf, int buf_size, const char *s)
  61978. {
  61979. int len;
  61980. len = strlen(buf);
  61981. if (len < buf_size)
  61982. js__pstrcpy(buf + len, buf_size - len, s);
  61983. return buf;
  61984. }
  61985. int js__strstart(const char *str, const char *val, const char **ptr)
  61986. {
  61987. const char *p, *q;
  61988. p = str;
  61989. q = val;
  61990. while (*q != '\0') {
  61991. if (*p != *q)
  61992. return 0;
  61993. p++;
  61994. q++;
  61995. }
  61996. if (ptr)
  61997. *ptr = p;
  61998. return 1;
  61999. }
  62000. int js__has_suffix(const char *str, const char *suffix)
  62001. {
  62002. size_t len = strlen(str);
  62003. size_t slen = strlen(suffix);
  62004. return (len >= slen && !memcmp(str + len - slen, suffix, slen));
  62005. }
  62006. /* Dynamic buffer package */
  62007. static void *dbuf_default_realloc(void *opaque, void *ptr, size_t size)
  62008. {
  62009. return realloc(ptr, size);
  62010. }
  62011. void dbuf_init2(DynBuf *s, void *opaque, DynBufReallocFunc *realloc_func)
  62012. {
  62013. memset(s, 0, sizeof(*s));
  62014. if (!realloc_func)
  62015. realloc_func = dbuf_default_realloc;
  62016. s->opaque = opaque;
  62017. s->realloc_func = realloc_func;
  62018. }
  62019. void dbuf_init(DynBuf *s)
  62020. {
  62021. dbuf_init2(s, NULL, NULL);
  62022. }
  62023. /* return < 0 if error */
  62024. int dbuf_realloc(DynBuf *s, size_t new_size)
  62025. {
  62026. size_t size;
  62027. uint8_t *new_buf;
  62028. if (new_size > s->allocated_size) {
  62029. if (s->error)
  62030. return -1;
  62031. size = s->allocated_size * 3 / 2;
  62032. if (size > new_size)
  62033. new_size = size;
  62034. new_buf = s->realloc_func(s->opaque, s->buf, new_size);
  62035. if (!new_buf) {
  62036. s->error = true;
  62037. return -1;
  62038. }
  62039. s->buf = new_buf;
  62040. s->allocated_size = new_size;
  62041. }
  62042. return 0;
  62043. }
  62044. int dbuf_write(DynBuf *s, size_t offset, const void *data, size_t len)
  62045. {
  62046. size_t end;
  62047. end = offset + len;
  62048. if (dbuf_realloc(s, end))
  62049. return -1;
  62050. memcpy(s->buf + offset, data, len);
  62051. if (end > s->size)
  62052. s->size = end;
  62053. return 0;
  62054. }
  62055. int dbuf_put(DynBuf *s, const void *data, size_t len)
  62056. {
  62057. if (unlikely((s->size + len) > s->allocated_size)) {
  62058. if (dbuf_realloc(s, s->size + len))
  62059. return -1;
  62060. }
  62061. if (len > 0) {
  62062. memcpy(s->buf + s->size, data, len);
  62063. s->size += len;
  62064. }
  62065. return 0;
  62066. }
  62067. int dbuf_put_self(DynBuf *s, size_t offset, size_t len)
  62068. {
  62069. if (unlikely((s->size + len) > s->allocated_size)) {
  62070. if (dbuf_realloc(s, s->size + len))
  62071. return -1;
  62072. }
  62073. memcpy(s->buf + s->size, s->buf + offset, len);
  62074. s->size += len;
  62075. return 0;
  62076. }
  62077. int dbuf_putc(DynBuf *s, uint8_t c)
  62078. {
  62079. return dbuf_put(s, &c, 1);
  62080. }
  62081. int dbuf_putstr(DynBuf *s, const char *str)
  62082. {
  62083. return dbuf_put(s, (const uint8_t *)str, strlen(str));
  62084. }
  62085. int JS_PRINTF_FORMAT_ATTR(2, 3) dbuf_printf(DynBuf *s, JS_PRINTF_FORMAT const char *fmt, ...)
  62086. {
  62087. va_list ap;
  62088. char buf[128];
  62089. int len;
  62090. va_start(ap, fmt);
  62091. len = vsnprintf(buf, sizeof(buf), fmt, ap);
  62092. va_end(ap);
  62093. if (len < (int)sizeof(buf)) {
  62094. /* fast case */
  62095. return dbuf_put(s, (uint8_t *)buf, len);
  62096. } else {
  62097. if (dbuf_realloc(s, s->size + len + 1))
  62098. return -1;
  62099. va_start(ap, fmt);
  62100. vsnprintf((char *)(s->buf + s->size), s->allocated_size - s->size,
  62101. fmt, ap);
  62102. va_end(ap);
  62103. s->size += len;
  62104. }
  62105. return 0;
  62106. }
  62107. void dbuf_free(DynBuf *s)
  62108. {
  62109. /* we test s->buf as a fail safe to avoid crashing if dbuf_free()
  62110. is called twice */
  62111. if (s->buf) {
  62112. s->realloc_func(s->opaque, s->buf, 0);
  62113. }
  62114. memset(s, 0, sizeof(*s));
  62115. }
  62116. /*--- UTF-8 utility functions --*/
  62117. /* Note: only encode valid codepoints (0x0000..0x10FFFF).
  62118. At most UTF8_CHAR_LEN_MAX bytes are output. */
  62119. /* Compute the number of bytes of the UTF-8 encoding for a codepoint
  62120. `c` is a code-point.
  62121. Returns the number of bytes. If a codepoint is beyond 0x10FFFF the
  62122. return value is 3 as the codepoint would be encoded as 0xFFFD.
  62123. */
  62124. size_t utf8_encode_len(uint32_t c)
  62125. {
  62126. if (c < 0x80)
  62127. return 1;
  62128. if (c < 0x800)
  62129. return 2;
  62130. if (c < 0x10000)
  62131. return 3;
  62132. if (c < 0x110000)
  62133. return 4;
  62134. return 3;
  62135. }
  62136. /* Encode a codepoint in UTF-8
  62137. `buf` points to an array of at least `UTF8_CHAR_LEN_MAX` bytes
  62138. `c` is a code-point.
  62139. Returns the number of bytes. If a codepoint is beyond 0x10FFFF the
  62140. return value is 3 and the codepoint is encoded as 0xFFFD.
  62141. No null byte is stored after the encoded bytes.
  62142. Return value is in range 1..4
  62143. */
  62144. size_t utf8_encode(uint8_t buf[minimum_length(UTF8_CHAR_LEN_MAX)], uint32_t c)
  62145. {
  62146. if (c < 0x80) {
  62147. buf[0] = c;
  62148. return 1;
  62149. }
  62150. if (c < 0x800) {
  62151. buf[0] = (c >> 6) | 0xC0;
  62152. buf[1] = (c & 0x3F) | 0x80;
  62153. return 2;
  62154. }
  62155. if (c < 0x10000) {
  62156. buf[0] = (c >> 12) | 0xE0;
  62157. buf[1] = ((c >> 6) & 0x3F) | 0x80;
  62158. buf[2] = (c & 0x3F) | 0x80;
  62159. return 3;
  62160. }
  62161. if (c < 0x110000) {
  62162. buf[0] = (c >> 18) | 0xF0;
  62163. buf[1] = ((c >> 12) & 0x3F) | 0x80;
  62164. buf[2] = ((c >> 6) & 0x3F) | 0x80;
  62165. buf[3] = (c & 0x3F) | 0x80;
  62166. return 4;
  62167. }
  62168. buf[0] = (0xFFFD >> 12) | 0xE0;
  62169. buf[1] = ((0xFFFD >> 6) & 0x3F) | 0x80;
  62170. buf[2] = (0xFFFD & 0x3F) | 0x80;
  62171. return 3;
  62172. }
  62173. /* Decode a single code point from a UTF-8 encoded array of bytes
  62174. `p` is a valid pointer to an array of bytes
  62175. `pp` is a valid pointer to a `const uint8_t *` to store a pointer
  62176. to the byte following the current sequence.
  62177. Return the code point at `p`, in the range `0..0x10FFFF`
  62178. Return 0xFFFD on error. Only a single byte is consumed in this case
  62179. The maximum length for a UTF-8 byte sequence is 4 bytes.
  62180. This implements the algorithm specified in whatwg.org, except it accepts
  62181. UTF-8 encoded surrogates as JavaScript allows them in strings.
  62182. The source string is assumed to have at least UTF8_CHAR_LEN_MAX bytes
  62183. or be null terminated.
  62184. If `p[0]` is '\0', the return value is `0` and the byte is consumed.
  62185. cf: https://encoding.spec.whatwg.org/#utf-8-encoder
  62186. */
  62187. uint32_t utf8_decode(const uint8_t *p, const uint8_t **pp)
  62188. {
  62189. uint32_t c;
  62190. uint8_t lower, upper;
  62191. c = *p++;
  62192. if (c < 0x80) {
  62193. *pp = p;
  62194. return c;
  62195. }
  62196. switch(c) {
  62197. case 0xC2: case 0xC3:
  62198. case 0xC4: case 0xC5: case 0xC6: case 0xC7:
  62199. case 0xC8: case 0xC9: case 0xCA: case 0xCB:
  62200. case 0xCC: case 0xCD: case 0xCE: case 0xCF:
  62201. case 0xD0: case 0xD1: case 0xD2: case 0xD3:
  62202. case 0xD4: case 0xD5: case 0xD6: case 0xD7:
  62203. case 0xD8: case 0xD9: case 0xDA: case 0xDB:
  62204. case 0xDC: case 0xDD: case 0xDE: case 0xDF:
  62205. if (*p >= 0x80 && *p <= 0xBF) {
  62206. *pp = p + 1;
  62207. return ((c - 0xC0) << 6) + (*p - 0x80);
  62208. }
  62209. // otherwise encoding error
  62210. break;
  62211. case 0xE0:
  62212. lower = 0xA0; /* reject invalid encoding */
  62213. goto need2;
  62214. case 0xE1: case 0xE2: case 0xE3:
  62215. case 0xE4: case 0xE5: case 0xE6: case 0xE7:
  62216. case 0xE8: case 0xE9: case 0xEA: case 0xEB:
  62217. case 0xEC: case 0xED: case 0xEE: case 0xEF:
  62218. lower = 0x80;
  62219. need2:
  62220. if (*p >= lower && *p <= 0xBF && p[1] >= 0x80 && p[1] <= 0xBF) {
  62221. *pp = p + 2;
  62222. return ((c - 0xE0) << 12) + ((*p - 0x80) << 6) + (p[1] - 0x80);
  62223. }
  62224. // otherwise encoding error
  62225. break;
  62226. case 0xF0:
  62227. lower = 0x90; /* reject invalid encoding */
  62228. upper = 0xBF;
  62229. goto need3;
  62230. case 0xF4:
  62231. lower = 0x80;
  62232. upper = 0x8F; /* reject values above 0x10FFFF */
  62233. goto need3;
  62234. case 0xF1: case 0xF2: case 0xF3:
  62235. lower = 0x80;
  62236. upper = 0xBF;
  62237. need3:
  62238. if (*p >= lower && *p <= upper && p[1] >= 0x80 && p[1] <= 0xBF
  62239. && p[2] >= 0x80 && p[2] <= 0xBF) {
  62240. *pp = p + 3;
  62241. return ((c - 0xF0) << 18) + ((*p - 0x80) << 12) +
  62242. ((p[1] - 0x80) << 6) + (p[2] - 0x80);
  62243. }
  62244. // otherwise encoding error
  62245. break;
  62246. default:
  62247. // invalid lead byte
  62248. break;
  62249. }
  62250. *pp = p;
  62251. return 0xFFFD;
  62252. }
  62253. uint32_t utf8_decode_len(const uint8_t *p, size_t max_len, const uint8_t **pp) {
  62254. switch (max_len) {
  62255. case 0:
  62256. *pp = p;
  62257. return 0xFFFD;
  62258. case 1:
  62259. if (*p < 0x80)
  62260. goto good;
  62261. break;
  62262. case 2:
  62263. if (*p < 0xE0)
  62264. goto good;
  62265. break;
  62266. case 3:
  62267. if (*p < 0xF0)
  62268. goto good;
  62269. break;
  62270. default:
  62271. good:
  62272. return utf8_decode(p, pp);
  62273. }
  62274. *pp = p + 1;
  62275. return 0xFFFD;
  62276. }
  62277. /* Scan a UTF-8 encoded buffer for content type
  62278. `buf` is a valid pointer to a UTF-8 encoded string
  62279. `len` is the number of bytes to scan
  62280. `plen` points to a `size_t` variable to receive the number of units
  62281. Return value is a mask of bits.
  62282. - `UTF8_PLAIN_ASCII`: return value for 7-bit ASCII plain text
  62283. - `UTF8_NON_ASCII`: bit for non ASCII code points (8-bit or more)
  62284. - `UTF8_HAS_16BIT`: bit for 16-bit code points
  62285. - `UTF8_HAS_NON_BMP1`: bit for non-BMP1 code points, needs UTF-16 surrogate pairs
  62286. - `UTF8_HAS_ERRORS`: bit for encoding errors
  62287. */
  62288. int utf8_scan(const char *buf, size_t buf_len, size_t *plen)
  62289. {
  62290. const uint8_t *p, *p_end, *p_next;
  62291. size_t i, len;
  62292. int kind;
  62293. uint8_t cbits;
  62294. kind = UTF8_PLAIN_ASCII;
  62295. cbits = 0;
  62296. len = buf_len;
  62297. // TODO: handle more than 1 byte at a time
  62298. for (i = 0; i < buf_len; i++)
  62299. cbits |= buf[i];
  62300. if (cbits >= 0x80) {
  62301. p = (const uint8_t *)buf;
  62302. p_end = p + buf_len;
  62303. kind = UTF8_NON_ASCII;
  62304. len = 0;
  62305. while (p < p_end) {
  62306. len++;
  62307. if (*p++ >= 0x80) {
  62308. /* parse UTF-8 sequence, check for encoding error */
  62309. uint32_t c = utf8_decode_len(p - 1, p_end - (p - 1), &p_next);
  62310. if (p_next == p)
  62311. kind |= UTF8_HAS_ERRORS;
  62312. p = p_next;
  62313. if (c > 0xFF) {
  62314. kind |= UTF8_HAS_16BIT;
  62315. if (c > 0xFFFF) {
  62316. len++;
  62317. kind |= UTF8_HAS_NON_BMP1;
  62318. }
  62319. }
  62320. }
  62321. }
  62322. }
  62323. *plen = len;
  62324. return kind;
  62325. }
  62326. /* Decode a string encoded in UTF-8 into an array of bytes
  62327. `src` points to the source string. It is assumed to be correctly encoded
  62328. and only contains code points below 0x800
  62329. `src_len` is the length of the source string
  62330. `dest` points to the destination array, it can be null if `dest_len` is `0`
  62331. `dest_len` is the length of the destination array. A null
  62332. terminator is stored at the end of the array unless `dest_len` is `0`.
  62333. */
  62334. size_t utf8_decode_buf8(uint8_t *dest, size_t dest_len, const char *src, size_t src_len)
  62335. {
  62336. const uint8_t *p, *p_end;
  62337. size_t i;
  62338. p = (const uint8_t *)src;
  62339. p_end = p + src_len;
  62340. for (i = 0; p < p_end; i++) {
  62341. uint32_t c = *p++;
  62342. if (c >= 0xC0)
  62343. c = (c << 6) + *p++ - ((0xC0 << 6) + 0x80);
  62344. if (i < dest_len)
  62345. dest[i] = c;
  62346. }
  62347. if (i < dest_len)
  62348. dest[i] = '\0';
  62349. else if (dest_len > 0)
  62350. dest[dest_len - 1] = '\0';
  62351. return i;
  62352. }
  62353. /* Decode a string encoded in UTF-8 into an array of 16-bit words
  62354. `src` points to the source string. It is assumed to be correctly encoded.
  62355. `src_len` is the length of the source string
  62356. `dest` points to the destination array, it can be null if `dest_len` is `0`
  62357. `dest_len` is the length of the destination array. No null terminator is
  62358. stored at the end of the array.
  62359. */
  62360. size_t utf8_decode_buf16(uint16_t *dest, size_t dest_len, const char *src, size_t src_len)
  62361. {
  62362. const uint8_t *p, *p_end;
  62363. size_t i;
  62364. p = (const uint8_t *)src;
  62365. p_end = p + src_len;
  62366. for (i = 0; p < p_end; i++) {
  62367. uint32_t c = *p++;
  62368. if (c >= 0x80) {
  62369. /* parse utf-8 sequence */
  62370. c = utf8_decode_len(p - 1, p_end - (p - 1), &p);
  62371. /* encoding errors are converted as 0xFFFD and use a single byte */
  62372. if (c > 0xFFFF) {
  62373. if (i < dest_len)
  62374. dest[i] = get_hi_surrogate(c);
  62375. i++;
  62376. c = get_lo_surrogate(c);
  62377. }
  62378. }
  62379. if (i < dest_len)
  62380. dest[i] = c;
  62381. }
  62382. return i;
  62383. }
  62384. /* Encode a buffer of 8-bit bytes as a UTF-8 encoded string
  62385. `src` points to the source buffer.
  62386. `src_len` is the length of the source buffer
  62387. `dest` points to the destination array, it can be null if `dest_len` is `0`
  62388. `dest_len` is the length in bytes of the destination array. A null
  62389. terminator is stored at the end of the array unless `dest_len` is `0`.
  62390. */
  62391. size_t utf8_encode_buf8(char *dest, size_t dest_len, const uint8_t *src, size_t src_len)
  62392. {
  62393. size_t i, j;
  62394. uint32_t c;
  62395. for (i = j = 0; i < src_len; i++) {
  62396. c = src[i];
  62397. if (c < 0x80) {
  62398. if (j + 1 >= dest_len)
  62399. goto overflow;
  62400. dest[j++] = c;
  62401. } else {
  62402. if (j + 2 >= dest_len)
  62403. goto overflow;
  62404. dest[j++] = (c >> 6) | 0xC0;
  62405. dest[j++] = (c & 0x3F) | 0x80;
  62406. }
  62407. }
  62408. if (j < dest_len)
  62409. dest[j] = '\0';
  62410. return j;
  62411. overflow:
  62412. if (j < dest_len)
  62413. dest[j] = '\0';
  62414. while (i < src_len)
  62415. j += 1 + (src[i++] >= 0x80);
  62416. return j;
  62417. }
  62418. /* Encode a buffer of 16-bit code points as a UTF-8 encoded string
  62419. `src` points to the source buffer.
  62420. `src_len` is the length of the source buffer
  62421. `dest` points to the destination array, it can be null if `dest_len` is `0`
  62422. `dest_len` is the length in bytes of the destination array. A null
  62423. terminator is stored at the end of the array unless `dest_len` is `0`.
  62424. */
  62425. size_t utf8_encode_buf16(char *dest, size_t dest_len, const uint16_t *src, size_t src_len)
  62426. {
  62427. size_t i, j;
  62428. uint32_t c;
  62429. for (i = j = 0; i < src_len;) {
  62430. c = src[i++];
  62431. if (c < 0x80) {
  62432. if (j + 1 >= dest_len)
  62433. goto overflow;
  62434. dest[j++] = c;
  62435. } else {
  62436. if (is_hi_surrogate(c) && i < src_len && is_lo_surrogate(src[i]))
  62437. c = from_surrogate(c, src[i++]);
  62438. if (j + utf8_encode_len(c) >= dest_len)
  62439. goto overflow;
  62440. j += utf8_encode((uint8_t *)dest + j, c);
  62441. }
  62442. }
  62443. if (j < dest_len)
  62444. dest[j] = '\0';
  62445. return j;
  62446. overflow:
  62447. i -= 1 + (c > 0xFFFF);
  62448. if (j < dest_len)
  62449. dest[j] = '\0';
  62450. while (i < src_len) {
  62451. c = src[i++];
  62452. if (c < 0x80) {
  62453. j++;
  62454. } else {
  62455. if (is_hi_surrogate(c) && i < src_len && is_lo_surrogate(src[i]))
  62456. c = from_surrogate(c, src[i++]);
  62457. j += utf8_encode_len(c);
  62458. }
  62459. }
  62460. return j;
  62461. }
  62462. /*--- integer to string conversions --*/
  62463. /* All conversion functions:
  62464. - require a destination array `buf` of sufficient length
  62465. - write the string representation at the beginning of `buf`
  62466. - null terminate the string
  62467. - return the string length
  62468. */
  62469. /* 2 <= base <= 36 */
  62470. char const digits36[36] = {
  62471. '0','1','2','3','4','5','6','7','8','9',
  62472. 'a','b','c','d','e','f','g','h','i','j',
  62473. 'k','l','m','n','o','p','q','r','s','t',
  62474. 'u','v','w','x','y','z'
  62475. };
  62476. #define USE_SPECIAL_RADIX_10 1 // special case base 10 radix conversions
  62477. #define USE_SINGLE_CASE_FAST 1 // special case single digit numbers
  62478. /* using u32toa_shift variant */
  62479. #define gen_digit(buf, c) if (is_be()) \
  62480. buf = (buf >> 8) | ((uint64_t)(c) << ((sizeof(buf) - 1) * 8)); \
  62481. else \
  62482. buf = (buf << 8) | (c)
  62483. static size_t u7toa_shift(char dest[minimum_length(8)], uint32_t n)
  62484. {
  62485. size_t len = 1;
  62486. uint64_t buf = 0;
  62487. while (n >= 10) {
  62488. uint32_t quo = n % 10;
  62489. n /= 10;
  62490. gen_digit(buf, '0' + quo);
  62491. len++;
  62492. }
  62493. gen_digit(buf, '0' + n);
  62494. memcpy(dest, &buf, sizeof buf);
  62495. return len;
  62496. }
  62497. static size_t u07toa_shift(char dest[minimum_length(8)], uint32_t n, size_t len)
  62498. {
  62499. size_t i;
  62500. dest += len;
  62501. dest[7] = '\0';
  62502. for (i = 7; i-- > 1;) {
  62503. uint32_t quo = n % 10;
  62504. n /= 10;
  62505. dest[i] = (char)('0' + quo);
  62506. }
  62507. dest[i] = (char)('0' + n);
  62508. return len + 7;
  62509. }
  62510. size_t u32toa(char buf[minimum_length(11)], uint32_t n)
  62511. {
  62512. #ifdef USE_SINGLE_CASE_FAST /* 10% */
  62513. if (n < 10) {
  62514. buf[0] = (char)('0' + n);
  62515. buf[1] = '\0';
  62516. return 1;
  62517. }
  62518. #endif
  62519. #define TEN_POW_7 10000000
  62520. if (n >= TEN_POW_7) {
  62521. uint32_t quo = n / TEN_POW_7;
  62522. n %= TEN_POW_7;
  62523. size_t len = u7toa_shift(buf, quo);
  62524. return u07toa_shift(buf, n, len);
  62525. }
  62526. return u7toa_shift(buf, n);
  62527. }
  62528. size_t u64toa(char buf[minimum_length(21)], uint64_t n)
  62529. {
  62530. if (likely(n < 0x100000000))
  62531. return u32toa(buf, n);
  62532. size_t len;
  62533. if (n >= TEN_POW_7) {
  62534. uint64_t n1 = n / TEN_POW_7;
  62535. n %= TEN_POW_7;
  62536. if (n1 >= TEN_POW_7) {
  62537. uint32_t quo = n1 / TEN_POW_7;
  62538. n1 %= TEN_POW_7;
  62539. len = u7toa_shift(buf, quo);
  62540. len = u07toa_shift(buf, n1, len);
  62541. } else {
  62542. len = u7toa_shift(buf, n1);
  62543. }
  62544. return u07toa_shift(buf, n, len);
  62545. }
  62546. return u7toa_shift(buf, n);
  62547. }
  62548. size_t i32toa(char buf[minimum_length(12)], int32_t n)
  62549. {
  62550. if (likely(n >= 0))
  62551. return u32toa(buf, n);
  62552. buf[0] = '-';
  62553. return 1 + u32toa(buf + 1, -(uint32_t)n);
  62554. }
  62555. size_t i64toa(char buf[minimum_length(22)], int64_t n)
  62556. {
  62557. if (likely(n >= 0))
  62558. return u64toa(buf, n);
  62559. buf[0] = '-';
  62560. return 1 + u64toa(buf + 1, -(uint64_t)n);
  62561. }
  62562. /* using u32toa_radix_length variant */
  62563. static uint8_t const radix_shift[64] = {
  62564. 0, 0, 1, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0,
  62565. 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  62566. 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  62567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  62568. };
  62569. size_t u32toa_radix(char buf[minimum_length(33)], uint32_t n, unsigned base)
  62570. {
  62571. int shift;
  62572. #ifdef USE_SPECIAL_RADIX_10
  62573. if (likely(base == 10))
  62574. return u32toa(buf, n);
  62575. #endif
  62576. if (n < base) {
  62577. buf[0] = digits36[n];
  62578. buf[1] = '\0';
  62579. return 1;
  62580. }
  62581. shift = radix_shift[base & 63];
  62582. if (shift) {
  62583. uint32_t mask = (1 << shift) - 1;
  62584. size_t len = (32 - clz32(n) + shift - 1) / shift;
  62585. size_t last = n & mask;
  62586. char *end = buf + len;
  62587. n >>= shift;
  62588. *end-- = '\0';
  62589. *end-- = digits36[last];
  62590. while (n >= base) {
  62591. size_t quo = n & mask;
  62592. n >>= shift;
  62593. *end-- = digits36[quo];
  62594. }
  62595. *end = digits36[n];
  62596. return len;
  62597. } else {
  62598. size_t len = 2;
  62599. size_t last = n % base;
  62600. n /= base;
  62601. uint32_t nbase = base;
  62602. while (n >= nbase) {
  62603. nbase *= base;
  62604. len++;
  62605. }
  62606. char *end = buf + len;
  62607. *end-- = '\0';
  62608. *end-- = digits36[last];
  62609. while (n >= base) {
  62610. size_t quo = n % base;
  62611. n /= base;
  62612. *end-- = digits36[quo];
  62613. }
  62614. *end = digits36[n];
  62615. return len;
  62616. }
  62617. }
  62618. size_t u64toa_radix(char buf[minimum_length(65)], uint64_t n, unsigned base)
  62619. {
  62620. int shift;
  62621. #ifdef USE_SPECIAL_RADIX_10
  62622. if (likely(base == 10))
  62623. return u64toa(buf, n);
  62624. #endif
  62625. shift = radix_shift[base & 63];
  62626. if (shift) {
  62627. if (n < base) {
  62628. buf[0] = digits36[n];
  62629. buf[1] = '\0';
  62630. return 1;
  62631. }
  62632. uint64_t mask = (1 << shift) - 1;
  62633. size_t len = (64 - clz64(n) + shift - 1) / shift;
  62634. size_t last = n & mask;
  62635. char *end = buf + len;
  62636. n >>= shift;
  62637. *end-- = '\0';
  62638. *end-- = digits36[last];
  62639. while (n >= base) {
  62640. size_t quo = n & mask;
  62641. n >>= shift;
  62642. *end-- = digits36[quo];
  62643. }
  62644. *end = digits36[n];
  62645. return len;
  62646. } else {
  62647. if (likely(n < 0x100000000))
  62648. return u32toa_radix(buf, n, base);
  62649. size_t last = n % base;
  62650. n /= base;
  62651. uint64_t nbase = base;
  62652. size_t len = 2;
  62653. while (n >= nbase) {
  62654. nbase *= base;
  62655. len++;
  62656. }
  62657. char *end = buf + len;
  62658. *end-- = '\0';
  62659. *end-- = digits36[last];
  62660. while (n >= base) {
  62661. size_t quo = n % base;
  62662. n /= base;
  62663. *end-- = digits36[quo];
  62664. }
  62665. *end = digits36[n];
  62666. return len;
  62667. }
  62668. }
  62669. size_t i32toa_radix(char buf[minimum_length(34)], int32_t n, unsigned int base)
  62670. {
  62671. if (likely(n >= 0))
  62672. return u32toa_radix(buf, n, base);
  62673. buf[0] = '-';
  62674. return 1 + u32toa_radix(buf + 1, -(uint32_t)n, base);
  62675. }
  62676. size_t i64toa_radix(char buf[minimum_length(66)], int64_t n, unsigned int base)
  62677. {
  62678. if (likely(n >= 0))
  62679. return u64toa_radix(buf, n, base);
  62680. buf[0] = '-';
  62681. return 1 + u64toa_radix(buf + 1, -(uint64_t)n, base);
  62682. }
  62683. #undef gen_digit
  62684. #undef TEN_POW_7
  62685. #undef USE_SPECIAL_RADIX_10
  62686. #undef USE_SINGLE_CASE_FAST
  62687. /*---- sorting with opaque argument ----*/
  62688. typedef void (*exchange_f)(void *a, void *b, size_t size);
  62689. typedef int (*cmp_f)(const void *, const void *, void *opaque);
  62690. static void exchange_bytes(void *a, void *b, size_t size) {
  62691. uint8_t *ap = (uint8_t *)a;
  62692. uint8_t *bp = (uint8_t *)b;
  62693. while (size-- != 0) {
  62694. uint8_t t = *ap;
  62695. *ap++ = *bp;
  62696. *bp++ = t;
  62697. }
  62698. }
  62699. static void exchange_one_byte(void *a, void *b, size_t size) {
  62700. uint8_t *ap = (uint8_t *)a;
  62701. uint8_t *bp = (uint8_t *)b;
  62702. uint8_t t = *ap;
  62703. *ap = *bp;
  62704. *bp = t;
  62705. }
  62706. static void exchange_int16s(void *a, void *b, size_t size) {
  62707. uint16_t *ap = (uint16_t *)a;
  62708. uint16_t *bp = (uint16_t *)b;
  62709. for (size /= sizeof(uint16_t); size-- != 0;) {
  62710. uint16_t t = *ap;
  62711. *ap++ = *bp;
  62712. *bp++ = t;
  62713. }
  62714. }
  62715. static void exchange_one_int16(void *a, void *b, size_t size) {
  62716. uint16_t *ap = (uint16_t *)a;
  62717. uint16_t *bp = (uint16_t *)b;
  62718. uint16_t t = *ap;
  62719. *ap = *bp;
  62720. *bp = t;
  62721. }
  62722. static void exchange_int32s(void *a, void *b, size_t size) {
  62723. uint32_t *ap = (uint32_t *)a;
  62724. uint32_t *bp = (uint32_t *)b;
  62725. for (size /= sizeof(uint32_t); size-- != 0;) {
  62726. uint32_t t = *ap;
  62727. *ap++ = *bp;
  62728. *bp++ = t;
  62729. }
  62730. }
  62731. static void exchange_one_int32(void *a, void *b, size_t size) {
  62732. uint32_t *ap = (uint32_t *)a;
  62733. uint32_t *bp = (uint32_t *)b;
  62734. uint32_t t = *ap;
  62735. *ap = *bp;
  62736. *bp = t;
  62737. }
  62738. static void exchange_int64s(void *a, void *b, size_t size) {
  62739. uint64_t *ap = (uint64_t *)a;
  62740. uint64_t *bp = (uint64_t *)b;
  62741. for (size /= sizeof(uint64_t); size-- != 0;) {
  62742. uint64_t t = *ap;
  62743. *ap++ = *bp;
  62744. *bp++ = t;
  62745. }
  62746. }
  62747. static void exchange_one_int64(void *a, void *b, size_t size) {
  62748. uint64_t *ap = (uint64_t *)a;
  62749. uint64_t *bp = (uint64_t *)b;
  62750. uint64_t t = *ap;
  62751. *ap = *bp;
  62752. *bp = t;
  62753. }
  62754. static void exchange_int128s(void *a, void *b, size_t size) {
  62755. uint64_t *ap = (uint64_t *)a;
  62756. uint64_t *bp = (uint64_t *)b;
  62757. for (size /= sizeof(uint64_t) * 2; size-- != 0; ap += 2, bp += 2) {
  62758. uint64_t t = ap[0];
  62759. uint64_t u = ap[1];
  62760. ap[0] = bp[0];
  62761. ap[1] = bp[1];
  62762. bp[0] = t;
  62763. bp[1] = u;
  62764. }
  62765. }
  62766. static void exchange_one_int128(void *a, void *b, size_t size) {
  62767. uint64_t *ap = (uint64_t *)a;
  62768. uint64_t *bp = (uint64_t *)b;
  62769. uint64_t t = ap[0];
  62770. uint64_t u = ap[1];
  62771. ap[0] = bp[0];
  62772. ap[1] = bp[1];
  62773. bp[0] = t;
  62774. bp[1] = u;
  62775. }
  62776. static inline exchange_f exchange_func(const void *base, size_t size) {
  62777. switch (((uintptr_t)base | (uintptr_t)size) & 15) {
  62778. case 0:
  62779. if (size == sizeof(uint64_t) * 2)
  62780. return exchange_one_int128;
  62781. else
  62782. return exchange_int128s;
  62783. case 8:
  62784. if (size == sizeof(uint64_t))
  62785. return exchange_one_int64;
  62786. else
  62787. return exchange_int64s;
  62788. case 4:
  62789. case 12:
  62790. if (size == sizeof(uint32_t))
  62791. return exchange_one_int32;
  62792. else
  62793. return exchange_int32s;
  62794. case 2:
  62795. case 6:
  62796. case 10:
  62797. case 14:
  62798. if (size == sizeof(uint16_t))
  62799. return exchange_one_int16;
  62800. else
  62801. return exchange_int16s;
  62802. default:
  62803. if (size == 1)
  62804. return exchange_one_byte;
  62805. else
  62806. return exchange_bytes;
  62807. }
  62808. }
  62809. static void heapsortx(void *base, size_t nmemb, size_t size, cmp_f cmp, void *opaque)
  62810. {
  62811. uint8_t *basep = (uint8_t *)base;
  62812. size_t i, n, c, r;
  62813. exchange_f swap = exchange_func(base, size);
  62814. if (nmemb > 1) {
  62815. i = (nmemb / 2) * size;
  62816. n = nmemb * size;
  62817. while (i > 0) {
  62818. i -= size;
  62819. for (r = i; (c = r * 2 + size) < n; r = c) {
  62820. if (c < n - size && cmp(basep + c, basep + c + size, opaque) <= 0)
  62821. c += size;
  62822. if (cmp(basep + r, basep + c, opaque) > 0)
  62823. break;
  62824. swap(basep + r, basep + c, size);
  62825. }
  62826. }
  62827. for (i = n - size; i > 0; i -= size) {
  62828. swap(basep, basep + i, size);
  62829. for (r = 0; (c = r * 2 + size) < i; r = c) {
  62830. if (c < i - size && cmp(basep + c, basep + c + size, opaque) <= 0)
  62831. c += size;
  62832. if (cmp(basep + r, basep + c, opaque) > 0)
  62833. break;
  62834. swap(basep + r, basep + c, size);
  62835. }
  62836. }
  62837. }
  62838. }
  62839. static inline void *med3(void *a, void *b, void *c, cmp_f cmp, void *opaque)
  62840. {
  62841. return cmp(a, b, opaque) < 0 ?
  62842. (cmp(b, c, opaque) < 0 ? b : (cmp(a, c, opaque) < 0 ? c : a )) :
  62843. (cmp(b, c, opaque) > 0 ? b : (cmp(a, c, opaque) < 0 ? a : c ));
  62844. }
  62845. /* pointer based version with local stack and insertion sort threshhold */
  62846. void rqsort(void *base, size_t nmemb, size_t size, cmp_f cmp, void *opaque)
  62847. {
  62848. struct { uint8_t *base; size_t count; int depth; } stack[50], *sp = stack;
  62849. uint8_t *ptr, *pi, *pj, *plt, *pgt, *top, *m;
  62850. size_t m4, i, lt, gt, span, span2;
  62851. int c, depth;
  62852. exchange_f swap = exchange_func(base, size);
  62853. exchange_f swap_block = exchange_func(base, size | 128);
  62854. if (nmemb < 2 || size <= 0)
  62855. return;
  62856. sp->base = (uint8_t *)base;
  62857. sp->count = nmemb;
  62858. sp->depth = 0;
  62859. sp++;
  62860. while (sp > stack) {
  62861. sp--;
  62862. ptr = sp->base;
  62863. nmemb = sp->count;
  62864. depth = sp->depth;
  62865. while (nmemb > 6) {
  62866. if (++depth > 50) {
  62867. /* depth check to ensure worst case logarithmic time */
  62868. heapsortx(ptr, nmemb, size, cmp, opaque);
  62869. nmemb = 0;
  62870. break;
  62871. }
  62872. /* select median of 3 from 1/4, 1/2, 3/4 positions */
  62873. /* should use median of 5 or 9? */
  62874. m4 = (nmemb >> 2) * size;
  62875. m = med3(ptr + m4, ptr + 2 * m4, ptr + 3 * m4, cmp, opaque);
  62876. swap(ptr, m, size); /* move the pivot to the start or the array */
  62877. i = lt = 1;
  62878. pi = plt = ptr + size;
  62879. gt = nmemb;
  62880. pj = pgt = top = ptr + nmemb * size;
  62881. for (;;) {
  62882. while (pi < pj && (c = cmp(ptr, pi, opaque)) >= 0) {
  62883. if (c == 0) {
  62884. swap(plt, pi, size);
  62885. lt++;
  62886. plt += size;
  62887. }
  62888. i++;
  62889. pi += size;
  62890. }
  62891. while (pi < (pj -= size) && (c = cmp(ptr, pj, opaque)) <= 0) {
  62892. if (c == 0) {
  62893. gt--;
  62894. pgt -= size;
  62895. swap(pgt, pj, size);
  62896. }
  62897. }
  62898. if (pi >= pj)
  62899. break;
  62900. swap(pi, pj, size);
  62901. i++;
  62902. pi += size;
  62903. }
  62904. /* array has 4 parts:
  62905. * from 0 to lt excluded: elements identical to pivot
  62906. * from lt to pi excluded: elements smaller than pivot
  62907. * from pi to gt excluded: elements greater than pivot
  62908. * from gt to n excluded: elements identical to pivot
  62909. */
  62910. /* move elements identical to pivot in the middle of the array: */
  62911. /* swap values in ranges [0..lt[ and [i-lt..i[
  62912. swapping the smallest span between lt and i-lt is sufficient
  62913. */
  62914. span = plt - ptr;
  62915. span2 = pi - plt;
  62916. lt = i - lt;
  62917. if (span > span2)
  62918. span = span2;
  62919. swap_block(ptr, pi - span, span);
  62920. /* swap values in ranges [gt..top[ and [i..top-(top-gt)[
  62921. swapping the smallest span between top-gt and gt-i is sufficient
  62922. */
  62923. span = top - pgt;
  62924. span2 = pgt - pi;
  62925. pgt = top - span2;
  62926. gt = nmemb - (gt - i);
  62927. if (span > span2)
  62928. span = span2;
  62929. swap_block(pi, top - span, span);
  62930. /* now array has 3 parts:
  62931. * from 0 to lt excluded: elements smaller than pivot
  62932. * from lt to gt excluded: elements identical to pivot
  62933. * from gt to n excluded: elements greater than pivot
  62934. */
  62935. /* stack the larger segment and keep processing the smaller one
  62936. to minimize stack use for pathological distributions */
  62937. if (lt > nmemb - gt) {
  62938. sp->base = ptr;
  62939. sp->count = lt;
  62940. sp->depth = depth;
  62941. sp++;
  62942. ptr = pgt;
  62943. nmemb -= gt;
  62944. } else {
  62945. sp->base = pgt;
  62946. sp->count = nmemb - gt;
  62947. sp->depth = depth;
  62948. sp++;
  62949. nmemb = lt;
  62950. }
  62951. }
  62952. /* Use insertion sort for small fragments */
  62953. for (pi = ptr + size, top = ptr + nmemb * size; pi < top; pi += size) {
  62954. for (pj = pi; pj > ptr && cmp(pj - size, pj, opaque) > 0; pj -= size)
  62955. swap(pj, pj - size, size);
  62956. }
  62957. }
  62958. }
  62959. /*---- Portable time functions ----*/
  62960. #ifdef _WIN32
  62961. // From: https://stackoverflow.com/a/26085827
  62962. static int gettimeofday_msvc(struct timeval *tp)
  62963. {
  62964. static const uint64_t EPOCH = ((uint64_t)116444736000000000ULL);
  62965. SYSTEMTIME system_time;
  62966. FILETIME file_time;
  62967. uint64_t time;
  62968. GetSystemTime(&system_time);
  62969. SystemTimeToFileTime(&system_time, &file_time);
  62970. time = ((uint64_t)file_time.dwLowDateTime);
  62971. time += ((uint64_t)file_time.dwHighDateTime) << 32;
  62972. tp->tv_sec = (long)((time - EPOCH) / 10000000L);
  62973. tp->tv_usec = (long)(system_time.wMilliseconds * 1000);
  62974. return 0;
  62975. }
  62976. uint64_t js__hrtime_ns(void) {
  62977. LARGE_INTEGER counter, frequency;
  62978. double scaled_freq;
  62979. double result;
  62980. if (!QueryPerformanceFrequency(&frequency))
  62981. abort();
  62982. assert(frequency.QuadPart != 0);
  62983. if (!QueryPerformanceCounter(&counter))
  62984. abort();
  62985. assert(counter.QuadPart != 0);
  62986. /* Because we have no guarantee about the order of magnitude of the
  62987. * performance counter interval, integer math could cause this computation
  62988. * to overflow. Therefore we resort to floating point math.
  62989. */
  62990. scaled_freq = (double) frequency.QuadPart / NANOSEC;
  62991. result = (double) counter.QuadPart / scaled_freq;
  62992. return (uint64_t) result;
  62993. }
  62994. #else
  62995. uint64_t js__hrtime_ns(void) {
  62996. struct timespec t;
  62997. if (clock_gettime(CLOCK_MONOTONIC, &t))
  62998. abort();
  62999. return t.tv_sec * NANOSEC + t.tv_nsec;
  63000. }
  63001. #endif
  63002. int64_t js__gettimeofday_us(void) {
  63003. struct timeval tv;
  63004. #ifdef _WIN32
  63005. gettimeofday_msvc(&tv);
  63006. #else
  63007. gettimeofday(&tv, NULL);
  63008. #endif
  63009. return ((int64_t)tv.tv_sec * 1000000) + tv.tv_usec;
  63010. }
  63011. /*--- Cross-platform threading APIs. ----*/
  63012. #if !defined(EMSCRIPTEN) && !defined(__wasi__)
  63013. #if defined(_WIN32)
  63014. typedef void (*js__once_cb)(void);
  63015. typedef struct {
  63016. js__once_cb callback;
  63017. } js__once_data_t;
  63018. static int WINAPI js__once_inner(INIT_ONCE *once, void *param, void **context) {
  63019. js__once_data_t *data = param;
  63020. data->callback();
  63021. return 1;
  63022. }
  63023. void js_once(js_once_t *guard, js__once_cb callback) {
  63024. js__once_data_t data = { .callback = callback };
  63025. InitOnceExecuteOnce(guard, js__once_inner, (void*) &data, NULL);
  63026. }
  63027. void js_mutex_init(js_mutex_t *mutex) {
  63028. InitializeCriticalSection(mutex);
  63029. }
  63030. void js_mutex_destroy(js_mutex_t *mutex) {
  63031. DeleteCriticalSection(mutex);
  63032. }
  63033. void js_mutex_lock(js_mutex_t *mutex) {
  63034. EnterCriticalSection(mutex);
  63035. }
  63036. void js_mutex_unlock(js_mutex_t *mutex) {
  63037. LeaveCriticalSection(mutex);
  63038. }
  63039. void js_cond_init(js_cond_t *cond) {
  63040. InitializeConditionVariable(cond);
  63041. }
  63042. void js_cond_destroy(js_cond_t *cond) {
  63043. /* nothing to do */
  63044. (void) cond;
  63045. }
  63046. void js_cond_signal(js_cond_t *cond) {
  63047. WakeConditionVariable(cond);
  63048. }
  63049. void js_cond_broadcast(js_cond_t *cond) {
  63050. WakeAllConditionVariable(cond);
  63051. }
  63052. void js_cond_wait(js_cond_t *cond, js_mutex_t *mutex) {
  63053. if (!SleepConditionVariableCS(cond, mutex, INFINITE))
  63054. abort();
  63055. }
  63056. int js_cond_timedwait(js_cond_t *cond, js_mutex_t *mutex, uint64_t timeout) {
  63057. if (SleepConditionVariableCS(cond, mutex, (DWORD)(timeout / 1e6)))
  63058. return 0;
  63059. if (GetLastError() != ERROR_TIMEOUT)
  63060. abort();
  63061. return -1;
  63062. }
  63063. #else /* !defined(_WIN32) */
  63064. void js_once(js_once_t *guard, void (*callback)(void)) {
  63065. if (pthread_once(guard, callback))
  63066. abort();
  63067. }
  63068. void js_mutex_init(js_mutex_t *mutex) {
  63069. if (pthread_mutex_init(mutex, NULL))
  63070. abort();
  63071. }
  63072. void js_mutex_destroy(js_mutex_t *mutex) {
  63073. if (pthread_mutex_destroy(mutex))
  63074. abort();
  63075. }
  63076. void js_mutex_lock(js_mutex_t *mutex) {
  63077. if (pthread_mutex_lock(mutex))
  63078. abort();
  63079. }
  63080. void js_mutex_unlock(js_mutex_t *mutex) {
  63081. if (pthread_mutex_unlock(mutex))
  63082. abort();
  63083. }
  63084. void js_cond_init(js_cond_t *cond) {
  63085. #if defined(__APPLE__) && defined(__MACH__)
  63086. if (pthread_cond_init(cond, NULL))
  63087. abort();
  63088. #else
  63089. pthread_condattr_t attr;
  63090. if (pthread_condattr_init(&attr))
  63091. abort();
  63092. if (pthread_condattr_setclock(&attr, CLOCK_MONOTONIC))
  63093. abort();
  63094. if (pthread_cond_init(cond, &attr))
  63095. abort();
  63096. if (pthread_condattr_destroy(&attr))
  63097. abort();
  63098. #endif
  63099. }
  63100. void js_cond_destroy(js_cond_t *cond) {
  63101. #if defined(__APPLE__) && defined(__MACH__)
  63102. /* It has been reported that destroying condition variables that have been
  63103. * signalled but not waited on can sometimes result in application crashes.
  63104. * See https://codereview.chromium.org/1323293005.
  63105. */
  63106. pthread_mutex_t mutex;
  63107. struct timespec ts;
  63108. int err;
  63109. if (pthread_mutex_init(&mutex, NULL))
  63110. abort();
  63111. if (pthread_mutex_lock(&mutex))
  63112. abort();
  63113. ts.tv_sec = 0;
  63114. ts.tv_nsec = 1;
  63115. err = pthread_cond_timedwait_relative_np(cond, &mutex, &ts);
  63116. if (err != 0 && err != ETIMEDOUT)
  63117. abort();
  63118. if (pthread_mutex_unlock(&mutex))
  63119. abort();
  63120. if (pthread_mutex_destroy(&mutex))
  63121. abort();
  63122. #endif /* defined(__APPLE__) && defined(__MACH__) */
  63123. if (pthread_cond_destroy(cond))
  63124. abort();
  63125. }
  63126. void js_cond_signal(js_cond_t *cond) {
  63127. if (pthread_cond_signal(cond))
  63128. abort();
  63129. }
  63130. void js_cond_broadcast(js_cond_t *cond) {
  63131. if (pthread_cond_broadcast(cond))
  63132. abort();
  63133. }
  63134. void js_cond_wait(js_cond_t *cond, js_mutex_t *mutex) {
  63135. #if defined(__APPLE__) && defined(__MACH__)
  63136. int r;
  63137. errno = 0;
  63138. r = pthread_cond_wait(cond, mutex);
  63139. /* Workaround for a bug in OS X at least up to 13.6
  63140. * See https://github.com/libuv/libuv/issues/4165
  63141. */
  63142. if (r == EINVAL && errno == EBUSY)
  63143. return;
  63144. if (r)
  63145. abort();
  63146. #else
  63147. if (pthread_cond_wait(cond, mutex))
  63148. abort();
  63149. #endif
  63150. }
  63151. int js_cond_timedwait(js_cond_t *cond, js_mutex_t *mutex, uint64_t timeout) {
  63152. int r;
  63153. struct timespec ts;
  63154. #if !defined(__APPLE__)
  63155. timeout += js__hrtime_ns();
  63156. #endif
  63157. ts.tv_sec = timeout / NANOSEC;
  63158. ts.tv_nsec = timeout % NANOSEC;
  63159. #if defined(__APPLE__) && defined(__MACH__)
  63160. r = pthread_cond_timedwait_relative_np(cond, mutex, &ts);
  63161. #else
  63162. r = pthread_cond_timedwait(cond, mutex, &ts);
  63163. #endif
  63164. if (r == 0)
  63165. return 0;
  63166. if (r == ETIMEDOUT)
  63167. return -1;
  63168. abort();
  63169. /* Pacify some compilers. */
  63170. return -1;
  63171. }
  63172. #endif
  63173. #endif /* !defined(EMSCRIPTEN) && !defined(__wasi__) */
  63174. #ifdef __GNUC__
  63175. #pragma GCC visibility pop
  63176. #endif
  63177. /*
  63178. * Tiny arbitrary precision floating point library
  63179. *
  63180. * Copyright (c) 2017-2021 Fabrice Bellard
  63181. *
  63182. * Permission is hereby granted, free of charge, to any person obtaining a copy
  63183. * of this software and associated documentation files (the "Software"), to deal
  63184. * in the Software without restriction, including without limitation the rights
  63185. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  63186. * copies of the Software, and to permit persons to whom the Software is
  63187. * furnished to do so, subject to the following conditions:
  63188. *
  63189. * The above copyright notice and this permission notice shall be included in
  63190. * all copies or substantial portions of the Software.
  63191. *
  63192. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  63193. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  63194. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  63195. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  63196. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  63197. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  63198. * THE SOFTWARE.
  63199. */
  63200. #include <stdlib.h>
  63201. #include <stdio.h>
  63202. #include <inttypes.h>
  63203. #include <math.h>
  63204. #include <string.h>
  63205. #include <assert.h>
  63206. #ifdef __AVX2__
  63207. #include <immintrin.h>
  63208. #endif
  63209. /* enable it to check the multiplication result */
  63210. //#define USE_MUL_CHECK
  63211. /* enable it to use FFT/NTT multiplication */
  63212. #define USE_FFT_MUL
  63213. /* enable decimal floating point support */
  63214. #define USE_BF_DEC
  63215. //#define inline __attribute__((always_inline))
  63216. #ifdef __AVX2__
  63217. #define FFT_MUL_THRESHOLD 100 /* in limbs of the smallest factor */
  63218. #else
  63219. #define FFT_MUL_THRESHOLD 100 /* in limbs of the smallest factor */
  63220. #endif
  63221. /* XXX: adjust */
  63222. #define DIVNORM_LARGE_THRESHOLD 50
  63223. #define UDIV1NORM_THRESHOLD 3
  63224. #if LIMB_BITS == 64
  63225. #define FMT_LIMB1 "%" PRIx64
  63226. #define FMT_LIMB "%016" PRIx64
  63227. #define PRId_LIMB PRId64
  63228. #define PRIu_LIMB PRIu64
  63229. #else
  63230. #define FMT_LIMB1 "%x"
  63231. #define FMT_LIMB "%08x"
  63232. #define PRId_LIMB "d"
  63233. #define PRIu_LIMB "u"
  63234. #endif
  63235. typedef intptr_t mp_size_t;
  63236. typedef int bf_op2_func_t(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,
  63237. bf_flags_t flags);
  63238. #ifdef USE_FFT_MUL
  63239. #define FFT_MUL_R_OVERLAP_A (1 << 0)
  63240. #define FFT_MUL_R_OVERLAP_B (1 << 1)
  63241. #define FFT_MUL_R_NORESIZE (1 << 2)
  63242. static no_inline int fft_mul(bf_context_t *s,
  63243. bf_t *res, limb_t *a_tab, limb_t a_len,
  63244. limb_t *b_tab, limb_t b_len, int mul_flags);
  63245. static void fft_clear_cache(bf_context_t *s);
  63246. #endif
  63247. #ifdef USE_BF_DEC
  63248. static limb_t get_digit(const limb_t *tab, limb_t len, slimb_t pos);
  63249. #endif
  63250. /* could leading zeros */
  63251. static inline int clz(limb_t a)
  63252. {
  63253. if (a == 0) {
  63254. return LIMB_BITS;
  63255. } else {
  63256. #if LIMB_BITS == 64
  63257. return clz64(a);
  63258. #else
  63259. return clz32(a);
  63260. #endif
  63261. }
  63262. }
  63263. static inline int ctz(limb_t a)
  63264. {
  63265. if (a == 0) {
  63266. return LIMB_BITS;
  63267. } else {
  63268. #if LIMB_BITS == 64
  63269. return ctz64(a);
  63270. #else
  63271. return ctz32(a);
  63272. #endif
  63273. }
  63274. }
  63275. static inline int ceil_log2(limb_t a)
  63276. {
  63277. if (a <= 1)
  63278. return 0;
  63279. else
  63280. return LIMB_BITS - clz(a - 1);
  63281. }
  63282. /* b must be >= 1 */
  63283. static inline slimb_t ceil_div(slimb_t a, slimb_t b)
  63284. {
  63285. if (a >= 0)
  63286. return (a + b - 1) / b;
  63287. else
  63288. return a / b;
  63289. }
  63290. /* b must be >= 1 */
  63291. static inline slimb_t floor_div(slimb_t a, slimb_t b)
  63292. {
  63293. if (a >= 0) {
  63294. return a / b;
  63295. } else {
  63296. return (a - b + 1) / b;
  63297. }
  63298. }
  63299. /* return r = a modulo b (0 <= r <= b - 1. b must be >= 1 */
  63300. static inline limb_t smod(slimb_t a, slimb_t b)
  63301. {
  63302. a = a % (slimb_t)b;
  63303. if (a < 0)
  63304. a += b;
  63305. return a;
  63306. }
  63307. /* signed addition with saturation */
  63308. static inline slimb_t sat_add(slimb_t a, slimb_t b)
  63309. {
  63310. slimb_t r;
  63311. r = a + b;
  63312. /* overflow ? */
  63313. if (((a ^ r) & (b ^ r)) < 0)
  63314. r = (a >> (LIMB_BITS - 1)) ^ (((limb_t)1 << (LIMB_BITS - 1)) - 1);
  63315. return r;
  63316. }
  63317. static inline __maybe_unused limb_t shrd(limb_t low, limb_t high, long shift)
  63318. {
  63319. if (shift != 0)
  63320. low = (low >> shift) | (high << (LIMB_BITS - shift));
  63321. return low;
  63322. }
  63323. static inline __maybe_unused limb_t shld(limb_t a1, limb_t a0, long shift)
  63324. {
  63325. if (shift != 0)
  63326. return (a1 << shift) | (a0 >> (LIMB_BITS - shift));
  63327. else
  63328. return a1;
  63329. }
  63330. #define malloc(s) malloc_is_forbidden(s)
  63331. #define free(p) free_is_forbidden(p)
  63332. #define realloc(p, s) realloc_is_forbidden(p, s)
  63333. void bf_context_init(bf_context_t *s, bf_realloc_func_t *realloc_func,
  63334. void *realloc_opaque)
  63335. {
  63336. memset(s, 0, sizeof(*s));
  63337. s->realloc_func = realloc_func;
  63338. s->realloc_opaque = realloc_opaque;
  63339. }
  63340. void bf_context_end(bf_context_t *s)
  63341. {
  63342. bf_clear_cache(s);
  63343. }
  63344. void bf_init(bf_context_t *s, bf_t *r)
  63345. {
  63346. r->ctx = s;
  63347. r->sign = 0;
  63348. r->expn = BF_EXP_ZERO;
  63349. r->len = 0;
  63350. r->tab = NULL;
  63351. }
  63352. /* return 0 if OK, -1 if alloc error */
  63353. int bf_resize(bf_t *r, limb_t len)
  63354. {
  63355. limb_t *tab;
  63356. if (len != r->len) {
  63357. tab = bf_realloc(r->ctx, r->tab, len * sizeof(limb_t));
  63358. if (!tab && len != 0)
  63359. return -1;
  63360. r->tab = tab;
  63361. r->len = len;
  63362. }
  63363. return 0;
  63364. }
  63365. /* return 0 or BF_ST_MEM_ERROR */
  63366. int bf_set_ui(bf_t *r, uint64_t a)
  63367. {
  63368. r->sign = 0;
  63369. if (a == 0) {
  63370. r->expn = BF_EXP_ZERO;
  63371. bf_resize(r, 0); /* cannot fail */
  63372. }
  63373. #if LIMB_BITS == 32
  63374. else if (a <= 0xffffffff)
  63375. #else
  63376. else
  63377. #endif
  63378. {
  63379. int shift;
  63380. if (bf_resize(r, 1))
  63381. goto fail;
  63382. shift = clz(a);
  63383. r->tab[0] = a << shift;
  63384. r->expn = LIMB_BITS - shift;
  63385. }
  63386. #if LIMB_BITS == 32
  63387. else {
  63388. uint32_t a1, a0;
  63389. int shift;
  63390. if (bf_resize(r, 2))
  63391. goto fail;
  63392. a0 = a;
  63393. a1 = a >> 32;
  63394. shift = clz(a1);
  63395. r->tab[0] = a0 << shift;
  63396. r->tab[1] = shld(a1, a0, shift);
  63397. r->expn = 2 * LIMB_BITS - shift;
  63398. }
  63399. #endif
  63400. return 0;
  63401. fail:
  63402. bf_set_nan(r);
  63403. return BF_ST_MEM_ERROR;
  63404. }
  63405. /* return 0 or BF_ST_MEM_ERROR */
  63406. int bf_set_si(bf_t *r, int64_t a)
  63407. {
  63408. int ret;
  63409. if (a < 0) {
  63410. ret = bf_set_ui(r, -a);
  63411. r->sign = 1;
  63412. } else {
  63413. ret = bf_set_ui(r, a);
  63414. }
  63415. return ret;
  63416. }
  63417. void bf_set_nan(bf_t *r)
  63418. {
  63419. bf_resize(r, 0); /* cannot fail */
  63420. r->expn = BF_EXP_NAN;
  63421. r->sign = 0;
  63422. }
  63423. void bf_set_zero(bf_t *r, int is_neg)
  63424. {
  63425. bf_resize(r, 0); /* cannot fail */
  63426. r->expn = BF_EXP_ZERO;
  63427. r->sign = is_neg;
  63428. }
  63429. void bf_set_inf(bf_t *r, int is_neg)
  63430. {
  63431. bf_resize(r, 0); /* cannot fail */
  63432. r->expn = BF_EXP_INF;
  63433. r->sign = is_neg;
  63434. }
  63435. /* return 0 or BF_ST_MEM_ERROR */
  63436. int bf_set(bf_t *r, const bf_t *a)
  63437. {
  63438. if (r == a)
  63439. return 0;
  63440. if (bf_resize(r, a->len)) {
  63441. bf_set_nan(r);
  63442. return BF_ST_MEM_ERROR;
  63443. }
  63444. r->sign = a->sign;
  63445. r->expn = a->expn;
  63446. if (a->len > 0)
  63447. memcpy(r->tab, a->tab, a->len * sizeof(limb_t));
  63448. return 0;
  63449. }
  63450. /* equivalent to bf_set(r, a); bf_delete(a) */
  63451. void bf_move(bf_t *r, bf_t *a)
  63452. {
  63453. bf_context_t *s = r->ctx;
  63454. if (r == a)
  63455. return;
  63456. bf_free(s, r->tab);
  63457. *r = *a;
  63458. }
  63459. static limb_t get_limbz(const bf_t *a, limb_t idx)
  63460. {
  63461. if (idx >= a->len)
  63462. return 0;
  63463. else
  63464. return a->tab[idx];
  63465. }
  63466. /* get LIMB_BITS at bit position 'pos' in tab */
  63467. static inline limb_t get_bits(const limb_t *tab, limb_t len, slimb_t pos)
  63468. {
  63469. limb_t i, a0, a1;
  63470. int p;
  63471. i = pos >> LIMB_LOG2_BITS;
  63472. p = pos & (LIMB_BITS - 1);
  63473. if (i < len)
  63474. a0 = tab[i];
  63475. else
  63476. a0 = 0;
  63477. if (p == 0) {
  63478. return a0;
  63479. } else {
  63480. i++;
  63481. if (i < len)
  63482. a1 = tab[i];
  63483. else
  63484. a1 = 0;
  63485. return (a0 >> p) | (a1 << (LIMB_BITS - p));
  63486. }
  63487. }
  63488. static inline limb_t get_bit(const limb_t *tab, limb_t len, slimb_t pos)
  63489. {
  63490. slimb_t i;
  63491. i = pos >> LIMB_LOG2_BITS;
  63492. if (i < 0 || i >= len)
  63493. return 0;
  63494. return (tab[i] >> (pos & (LIMB_BITS - 1))) & 1;
  63495. }
  63496. static inline limb_t limb_mask(int start, int last)
  63497. {
  63498. limb_t v;
  63499. int n;
  63500. n = last - start + 1;
  63501. if (n == LIMB_BITS)
  63502. v = -1;
  63503. else
  63504. v = (((limb_t)1 << n) - 1) << start;
  63505. return v;
  63506. }
  63507. static limb_t mp_scan_nz(const limb_t *tab, mp_size_t n)
  63508. {
  63509. mp_size_t i;
  63510. for(i = 0; i < n; i++) {
  63511. if (tab[i] != 0)
  63512. return 1;
  63513. }
  63514. return 0;
  63515. }
  63516. /* return != 0 if one bit between 0 and bit_pos inclusive is not zero. */
  63517. static inline limb_t scan_bit_nz(const bf_t *r, slimb_t bit_pos)
  63518. {
  63519. slimb_t pos;
  63520. limb_t v;
  63521. pos = bit_pos >> LIMB_LOG2_BITS;
  63522. if (pos < 0)
  63523. return 0;
  63524. v = r->tab[pos] & limb_mask(0, bit_pos & (LIMB_BITS - 1));
  63525. if (v != 0)
  63526. return 1;
  63527. pos--;
  63528. while (pos >= 0) {
  63529. if (r->tab[pos] != 0)
  63530. return 1;
  63531. pos--;
  63532. }
  63533. return 0;
  63534. }
  63535. /* return the addend for rounding. Note that prec can be <= 0 (for
  63536. BF_FLAG_RADPNT_PREC) */
  63537. static int bf_get_rnd_add(int *pret, const bf_t *r, limb_t l,
  63538. slimb_t prec, int rnd_mode)
  63539. {
  63540. int add_one, inexact;
  63541. limb_t bit1, bit0;
  63542. if (rnd_mode == BF_RNDF) {
  63543. bit0 = 1; /* faithful rounding does not honor the INEXACT flag */
  63544. } else {
  63545. /* starting limb for bit 'prec + 1' */
  63546. bit0 = scan_bit_nz(r, l * LIMB_BITS - 1 - bf_max(0, prec + 1));
  63547. }
  63548. /* get the bit at 'prec' */
  63549. bit1 = get_bit(r->tab, l, l * LIMB_BITS - 1 - prec);
  63550. inexact = (bit1 | bit0) != 0;
  63551. add_one = 0;
  63552. switch(rnd_mode) {
  63553. case BF_RNDZ:
  63554. break;
  63555. case BF_RNDN:
  63556. if (bit1) {
  63557. if (bit0) {
  63558. add_one = 1;
  63559. } else {
  63560. /* round to even */
  63561. add_one =
  63562. get_bit(r->tab, l, l * LIMB_BITS - 1 - (prec - 1));
  63563. }
  63564. }
  63565. break;
  63566. case BF_RNDD:
  63567. case BF_RNDU:
  63568. if (r->sign == (rnd_mode == BF_RNDD))
  63569. add_one = inexact;
  63570. break;
  63571. case BF_RNDA:
  63572. add_one = inexact;
  63573. break;
  63574. case BF_RNDNA:
  63575. case BF_RNDF:
  63576. add_one = bit1;
  63577. break;
  63578. default:
  63579. abort();
  63580. }
  63581. if (inexact)
  63582. *pret |= BF_ST_INEXACT;
  63583. return add_one;
  63584. }
  63585. static int bf_set_overflow(bf_t *r, int sign, limb_t prec, bf_flags_t flags)
  63586. {
  63587. slimb_t i, l, e_max;
  63588. int rnd_mode;
  63589. rnd_mode = flags & BF_RND_MASK;
  63590. if (prec == BF_PREC_INF ||
  63591. rnd_mode == BF_RNDN ||
  63592. rnd_mode == BF_RNDNA ||
  63593. rnd_mode == BF_RNDA ||
  63594. (rnd_mode == BF_RNDD && sign == 1) ||
  63595. (rnd_mode == BF_RNDU && sign == 0)) {
  63596. bf_set_inf(r, sign);
  63597. } else {
  63598. /* set to maximum finite number */
  63599. l = (prec + LIMB_BITS - 1) / LIMB_BITS;
  63600. if (bf_resize(r, l)) {
  63601. bf_set_nan(r);
  63602. return BF_ST_MEM_ERROR;
  63603. }
  63604. r->tab[0] = limb_mask((-prec) & (LIMB_BITS - 1),
  63605. LIMB_BITS - 1);
  63606. for(i = 1; i < l; i++)
  63607. r->tab[i] = (limb_t)-1;
  63608. e_max = (limb_t)1 << (bf_get_exp_bits(flags) - 1);
  63609. r->expn = e_max;
  63610. r->sign = sign;
  63611. }
  63612. return BF_ST_OVERFLOW | BF_ST_INEXACT;
  63613. }
  63614. /* round to prec1 bits assuming 'r' is non zero and finite. 'r' is
  63615. assumed to have length 'l' (1 <= l <= r->len). Note: 'prec1' can be
  63616. infinite (BF_PREC_INF). 'ret' is 0 or BF_ST_INEXACT if the result
  63617. is known to be inexact. Can fail with BF_ST_MEM_ERROR in case of
  63618. overflow not returning infinity. */
  63619. static int __bf_round(bf_t *r, limb_t prec1, bf_flags_t flags, limb_t l,
  63620. int ret)
  63621. {
  63622. limb_t v, a;
  63623. int shift, add_one, rnd_mode;
  63624. slimb_t i, bit_pos, pos, e_min, e_max, e_range, prec;
  63625. /* e_min and e_max are computed to match the IEEE 754 conventions */
  63626. e_range = (limb_t)1 << (bf_get_exp_bits(flags) - 1);
  63627. e_min = -e_range + 3;
  63628. e_max = e_range;
  63629. if (flags & BF_FLAG_RADPNT_PREC) {
  63630. /* 'prec' is the precision after the radix point */
  63631. if (prec1 != BF_PREC_INF)
  63632. prec = r->expn + prec1;
  63633. else
  63634. prec = prec1;
  63635. } else if (unlikely(r->expn < e_min) && (flags & BF_FLAG_SUBNORMAL)) {
  63636. /* restrict the precision in case of potentially subnormal
  63637. result */
  63638. assert(prec1 != BF_PREC_INF);
  63639. prec = prec1 - (e_min - r->expn);
  63640. } else {
  63641. prec = prec1;
  63642. }
  63643. /* round to prec bits */
  63644. rnd_mode = flags & BF_RND_MASK;
  63645. add_one = bf_get_rnd_add(&ret, r, l, prec, rnd_mode);
  63646. if (prec <= 0) {
  63647. if (add_one) {
  63648. bf_resize(r, 1); /* cannot fail */
  63649. r->tab[0] = (limb_t)1 << (LIMB_BITS - 1);
  63650. r->expn += 1 - prec;
  63651. ret |= BF_ST_UNDERFLOW | BF_ST_INEXACT;
  63652. return ret;
  63653. } else {
  63654. goto underflow;
  63655. }
  63656. } else if (add_one) {
  63657. limb_t carry;
  63658. /* add one starting at digit 'prec - 1' */
  63659. bit_pos = l * LIMB_BITS - 1 - (prec - 1);
  63660. pos = bit_pos >> LIMB_LOG2_BITS;
  63661. carry = (limb_t)1 << (bit_pos & (LIMB_BITS - 1));
  63662. for(i = pos; i < l; i++) {
  63663. v = r->tab[i] + carry;
  63664. carry = (v < carry);
  63665. r->tab[i] = v;
  63666. if (carry == 0)
  63667. break;
  63668. }
  63669. if (carry) {
  63670. /* shift right by one digit */
  63671. v = 1;
  63672. for(i = l - 1; i >= pos; i--) {
  63673. a = r->tab[i];
  63674. r->tab[i] = (a >> 1) | (v << (LIMB_BITS - 1));
  63675. v = a;
  63676. }
  63677. r->expn++;
  63678. }
  63679. }
  63680. /* check underflow */
  63681. if (unlikely(r->expn < e_min)) {
  63682. if (flags & BF_FLAG_SUBNORMAL) {
  63683. /* if inexact, also set the underflow flag */
  63684. if (ret & BF_ST_INEXACT)
  63685. ret |= BF_ST_UNDERFLOW;
  63686. } else {
  63687. underflow:
  63688. ret |= BF_ST_UNDERFLOW | BF_ST_INEXACT;
  63689. bf_set_zero(r, r->sign);
  63690. return ret;
  63691. }
  63692. }
  63693. /* check overflow */
  63694. if (unlikely(r->expn > e_max))
  63695. return bf_set_overflow(r, r->sign, prec1, flags);
  63696. /* keep the bits starting at 'prec - 1' */
  63697. bit_pos = l * LIMB_BITS - 1 - (prec - 1);
  63698. i = bit_pos >> LIMB_LOG2_BITS;
  63699. if (i >= 0) {
  63700. shift = bit_pos & (LIMB_BITS - 1);
  63701. if (shift != 0)
  63702. r->tab[i] &= limb_mask(shift, LIMB_BITS - 1);
  63703. } else {
  63704. i = 0;
  63705. }
  63706. /* remove trailing zeros */
  63707. while (r->tab[i] == 0)
  63708. i++;
  63709. if (i > 0) {
  63710. l -= i;
  63711. memmove(r->tab, r->tab + i, l * sizeof(limb_t));
  63712. }
  63713. bf_resize(r, l); /* cannot fail */
  63714. return ret;
  63715. }
  63716. /* 'r' must be a finite number. */
  63717. int bf_normalize_and_round(bf_t *r, limb_t prec1, bf_flags_t flags)
  63718. {
  63719. limb_t l, v, a;
  63720. int shift, ret;
  63721. slimb_t i;
  63722. // bf_print_str("bf_renorm", r);
  63723. l = r->len;
  63724. while (l > 0 && r->tab[l - 1] == 0)
  63725. l--;
  63726. if (l == 0) {
  63727. /* zero */
  63728. r->expn = BF_EXP_ZERO;
  63729. bf_resize(r, 0); /* cannot fail */
  63730. ret = 0;
  63731. } else {
  63732. r->expn -= (r->len - l) * LIMB_BITS;
  63733. /* shift to have the MSB set to '1' */
  63734. v = r->tab[l - 1];
  63735. shift = clz(v);
  63736. if (shift != 0) {
  63737. v = 0;
  63738. for(i = 0; i < l; i++) {
  63739. a = r->tab[i];
  63740. r->tab[i] = (a << shift) | (v >> (LIMB_BITS - shift));
  63741. v = a;
  63742. }
  63743. r->expn -= shift;
  63744. }
  63745. ret = __bf_round(r, prec1, flags, l, 0);
  63746. }
  63747. // bf_print_str("r_final", r);
  63748. return ret;
  63749. }
  63750. /* return true if rounding can be done at precision 'prec' assuming
  63751. the exact result r is such that |r-a| <= 2^(EXP(a)-k). */
  63752. /* XXX: check the case where the exponent would be incremented by the
  63753. rounding */
  63754. int bf_can_round(const bf_t *a, slimb_t prec, bf_rnd_t rnd_mode, slimb_t k)
  63755. {
  63756. bool is_rndn;
  63757. slimb_t bit_pos, n;
  63758. limb_t bit;
  63759. if (a->expn == BF_EXP_INF || a->expn == BF_EXP_NAN)
  63760. return false;
  63761. if (rnd_mode == BF_RNDF) {
  63762. return (k >= (prec + 1));
  63763. }
  63764. if (a->expn == BF_EXP_ZERO)
  63765. return false;
  63766. is_rndn = (rnd_mode == BF_RNDN || rnd_mode == BF_RNDNA);
  63767. if (k < (prec + 2))
  63768. return false;
  63769. bit_pos = a->len * LIMB_BITS - 1 - prec;
  63770. n = k - prec;
  63771. /* bit pattern for RNDN or RNDNA: 0111.. or 1000...
  63772. for other rounding modes: 000... or 111...
  63773. */
  63774. bit = get_bit(a->tab, a->len, bit_pos);
  63775. bit_pos--;
  63776. n--;
  63777. bit ^= is_rndn;
  63778. /* XXX: slow, but a few iterations on average */
  63779. while (n != 0) {
  63780. if (get_bit(a->tab, a->len, bit_pos) != bit)
  63781. return true;
  63782. bit_pos--;
  63783. n--;
  63784. }
  63785. return false;
  63786. }
  63787. /* Cannot fail with BF_ST_MEM_ERROR. */
  63788. int bf_round(bf_t *r, limb_t prec, bf_flags_t flags)
  63789. {
  63790. if (r->len == 0)
  63791. return 0;
  63792. return __bf_round(r, prec, flags, r->len, 0);
  63793. }
  63794. /* for debugging */
  63795. static __maybe_unused void dump_limbs(const char *str, const limb_t *tab, limb_t n)
  63796. {
  63797. limb_t i;
  63798. printf("%s: len=%" PRId_LIMB "\n", str, n);
  63799. for(i = 0; i < n; i++) {
  63800. printf("%" PRId_LIMB ": " FMT_LIMB "\n",
  63801. i, tab[i]);
  63802. }
  63803. }
  63804. void mp_print_str(const char *str, const limb_t *tab, limb_t n)
  63805. {
  63806. slimb_t i;
  63807. printf("%s= 0x", str);
  63808. for(i = n - 1; i >= 0; i--) {
  63809. if (i != (n - 1))
  63810. printf("_");
  63811. printf(FMT_LIMB, tab[i]);
  63812. }
  63813. printf("\n");
  63814. }
  63815. static __maybe_unused void mp_print_str_h(const char *str,
  63816. const limb_t *tab, limb_t n,
  63817. limb_t high)
  63818. {
  63819. slimb_t i;
  63820. printf("%s= 0x", str);
  63821. printf(FMT_LIMB, high);
  63822. for(i = n - 1; i >= 0; i--) {
  63823. printf("_");
  63824. printf(FMT_LIMB, tab[i]);
  63825. }
  63826. printf("\n");
  63827. }
  63828. /* for debugging */
  63829. void bf_print_str(const char *str, const bf_t *a)
  63830. {
  63831. slimb_t i;
  63832. printf("%s=", str);
  63833. if (a->expn == BF_EXP_NAN) {
  63834. printf("NaN");
  63835. } else {
  63836. if (a->sign)
  63837. putchar('-');
  63838. if (a->expn == BF_EXP_ZERO) {
  63839. putchar('0');
  63840. } else if (a->expn == BF_EXP_INF) {
  63841. printf("Inf");
  63842. } else {
  63843. printf("0x0.");
  63844. for(i = a->len - 1; i >= 0; i--)
  63845. printf(FMT_LIMB, a->tab[i]);
  63846. printf("p%" PRId_LIMB, a->expn);
  63847. }
  63848. }
  63849. printf("\n");
  63850. }
  63851. /* compare the absolute value of 'a' and 'b'. Return < 0 if a < b, 0
  63852. if a = b and > 0 otherwise. */
  63853. int bf_cmpu(const bf_t *a, const bf_t *b)
  63854. {
  63855. slimb_t i;
  63856. limb_t len, v1, v2;
  63857. if (a->expn != b->expn) {
  63858. if (a->expn < b->expn)
  63859. return -1;
  63860. else
  63861. return 1;
  63862. }
  63863. len = bf_max(a->len, b->len);
  63864. for(i = len - 1; i >= 0; i--) {
  63865. v1 = get_limbz(a, a->len - len + i);
  63866. v2 = get_limbz(b, b->len - len + i);
  63867. if (v1 != v2) {
  63868. if (v1 < v2)
  63869. return -1;
  63870. else
  63871. return 1;
  63872. }
  63873. }
  63874. return 0;
  63875. }
  63876. /* Full order: -0 < 0, NaN == NaN and NaN is larger than all other numbers */
  63877. int bf_cmp_full(const bf_t *a, const bf_t *b)
  63878. {
  63879. int res;
  63880. if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) {
  63881. if (a->expn == b->expn)
  63882. res = 0;
  63883. else if (a->expn == BF_EXP_NAN)
  63884. res = 1;
  63885. else
  63886. res = -1;
  63887. } else if (a->sign != b->sign) {
  63888. res = 1 - 2 * a->sign;
  63889. } else {
  63890. res = bf_cmpu(a, b);
  63891. if (a->sign)
  63892. res = -res;
  63893. }
  63894. return res;
  63895. }
  63896. /* Standard floating point comparison: return 2 if one of the operands
  63897. is NaN (unordered) or -1, 0, 1 depending on the ordering assuming
  63898. -0 == +0 */
  63899. int bf_cmp(const bf_t *a, const bf_t *b)
  63900. {
  63901. int res;
  63902. if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) {
  63903. res = 2;
  63904. } else if (a->sign != b->sign) {
  63905. if (a->expn == BF_EXP_ZERO && b->expn == BF_EXP_ZERO)
  63906. res = 0;
  63907. else
  63908. res = 1 - 2 * a->sign;
  63909. } else {
  63910. res = bf_cmpu(a, b);
  63911. if (a->sign)
  63912. res = -res;
  63913. }
  63914. return res;
  63915. }
  63916. /* Compute the number of bits 'n' matching the pattern:
  63917. a= X1000..0
  63918. b= X0111..1
  63919. When computing a-b, the result will have at least n leading zero
  63920. bits.
  63921. Precondition: a > b and a.expn - b.expn = 0 or 1
  63922. */
  63923. static limb_t count_cancelled_bits(const bf_t *a, const bf_t *b)
  63924. {
  63925. slimb_t bit_offset, b_offset, n;
  63926. int p, p1;
  63927. limb_t v1, v2, mask;
  63928. bit_offset = a->len * LIMB_BITS - 1;
  63929. b_offset = (b->len - a->len) * LIMB_BITS - (LIMB_BITS - 1) +
  63930. a->expn - b->expn;
  63931. n = 0;
  63932. /* first search the equals bits */
  63933. for(;;) {
  63934. v1 = get_limbz(a, bit_offset >> LIMB_LOG2_BITS);
  63935. v2 = get_bits(b->tab, b->len, bit_offset + b_offset);
  63936. // printf("v1=" FMT_LIMB " v2=" FMT_LIMB "\n", v1, v2);
  63937. if (v1 != v2)
  63938. break;
  63939. n += LIMB_BITS;
  63940. bit_offset -= LIMB_BITS;
  63941. }
  63942. /* find the position of the first different bit */
  63943. p = clz(v1 ^ v2) + 1;
  63944. n += p;
  63945. /* then search for '0' in a and '1' in b */
  63946. p = LIMB_BITS - p;
  63947. if (p > 0) {
  63948. /* search in the trailing p bits of v1 and v2 */
  63949. mask = limb_mask(0, p - 1);
  63950. p1 = bf_min(clz(v1 & mask), clz((~v2) & mask)) - (LIMB_BITS - p);
  63951. n += p1;
  63952. if (p1 != p)
  63953. goto done;
  63954. }
  63955. bit_offset -= LIMB_BITS;
  63956. for(;;) {
  63957. v1 = get_limbz(a, bit_offset >> LIMB_LOG2_BITS);
  63958. v2 = get_bits(b->tab, b->len, bit_offset + b_offset);
  63959. // printf("v1=" FMT_LIMB " v2=" FMT_LIMB "\n", v1, v2);
  63960. if (v1 != 0 || v2 != -1) {
  63961. /* different: count the matching bits */
  63962. p1 = bf_min(clz(v1), clz(~v2));
  63963. n += p1;
  63964. break;
  63965. }
  63966. n += LIMB_BITS;
  63967. bit_offset -= LIMB_BITS;
  63968. }
  63969. done:
  63970. return n;
  63971. }
  63972. static int bf_add_internal(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,
  63973. bf_flags_t flags, int b_neg)
  63974. {
  63975. const bf_t *tmp;
  63976. int is_sub, ret, cmp_res, a_sign, b_sign;
  63977. a_sign = a->sign;
  63978. b_sign = b->sign ^ b_neg;
  63979. is_sub = a_sign ^ b_sign;
  63980. cmp_res = bf_cmpu(a, b);
  63981. if (cmp_res < 0) {
  63982. tmp = a;
  63983. a = b;
  63984. b = tmp;
  63985. a_sign = b_sign; /* b_sign is never used later */
  63986. }
  63987. /* abs(a) >= abs(b) */
  63988. if (cmp_res == 0 && is_sub && a->expn < BF_EXP_INF) {
  63989. /* zero result */
  63990. bf_set_zero(r, (flags & BF_RND_MASK) == BF_RNDD);
  63991. ret = 0;
  63992. } else if (a->len == 0 || b->len == 0) {
  63993. ret = 0;
  63994. if (a->expn >= BF_EXP_INF) {
  63995. if (a->expn == BF_EXP_NAN) {
  63996. /* at least one operand is NaN */
  63997. bf_set_nan(r);
  63998. } else if (b->expn == BF_EXP_INF && is_sub) {
  63999. /* infinities with different signs */
  64000. bf_set_nan(r);
  64001. ret = BF_ST_INVALID_OP;
  64002. } else {
  64003. bf_set_inf(r, a_sign);
  64004. }
  64005. } else {
  64006. /* at least one zero and not subtract */
  64007. bf_set(r, a);
  64008. r->sign = a_sign;
  64009. goto renorm;
  64010. }
  64011. } else {
  64012. slimb_t d, a_offset, b_bit_offset, i, cancelled_bits;
  64013. limb_t carry, v1, v2, u, r_len, carry1, precl, tot_len, z, sub_mask;
  64014. r->sign = a_sign;
  64015. r->expn = a->expn;
  64016. d = a->expn - b->expn;
  64017. /* must add more precision for the leading cancelled bits in
  64018. subtraction */
  64019. if (is_sub) {
  64020. if (d <= 1)
  64021. cancelled_bits = count_cancelled_bits(a, b);
  64022. else
  64023. cancelled_bits = 1;
  64024. } else {
  64025. cancelled_bits = 0;
  64026. }
  64027. /* add two extra bits for rounding */
  64028. precl = (cancelled_bits + prec + 2 + LIMB_BITS - 1) / LIMB_BITS;
  64029. tot_len = bf_max(a->len, b->len + (d + LIMB_BITS - 1) / LIMB_BITS);
  64030. r_len = bf_min(precl, tot_len);
  64031. if (bf_resize(r, r_len))
  64032. goto fail;
  64033. a_offset = a->len - r_len;
  64034. b_bit_offset = (b->len - r_len) * LIMB_BITS + d;
  64035. /* compute the bits before for the rounding */
  64036. carry = is_sub;
  64037. z = 0;
  64038. sub_mask = -is_sub;
  64039. i = r_len - tot_len;
  64040. while (i < 0) {
  64041. slimb_t ap, bp;
  64042. bool inflag;
  64043. ap = a_offset + i;
  64044. bp = b_bit_offset + i * LIMB_BITS;
  64045. inflag = false;
  64046. if (ap >= 0 && ap < a->len) {
  64047. v1 = a->tab[ap];
  64048. inflag = true;
  64049. } else {
  64050. v1 = 0;
  64051. }
  64052. if (bp + LIMB_BITS > 0 && bp < (slimb_t)(b->len * LIMB_BITS)) {
  64053. v2 = get_bits(b->tab, b->len, bp);
  64054. inflag = true;
  64055. } else {
  64056. v2 = 0;
  64057. }
  64058. if (!inflag) {
  64059. /* outside 'a' and 'b': go directly to the next value
  64060. inside a or b so that the running time does not
  64061. depend on the exponent difference */
  64062. i = 0;
  64063. if (ap < 0)
  64064. i = bf_min(i, -a_offset);
  64065. /* b_bit_offset + i * LIMB_BITS + LIMB_BITS >= 1
  64066. equivalent to
  64067. i >= ceil(-b_bit_offset + 1 - LIMB_BITS) / LIMB_BITS)
  64068. */
  64069. if (bp + LIMB_BITS <= 0)
  64070. i = bf_min(i, (-b_bit_offset) >> LIMB_LOG2_BITS);
  64071. } else {
  64072. i++;
  64073. }
  64074. v2 ^= sub_mask;
  64075. u = v1 + v2;
  64076. carry1 = u < v1;
  64077. u += carry;
  64078. carry = (u < carry) | carry1;
  64079. z |= u;
  64080. }
  64081. /* and the result */
  64082. for(i = 0; i < r_len; i++) {
  64083. v1 = get_limbz(a, a_offset + i);
  64084. v2 = get_bits(b->tab, b->len, b_bit_offset + i * LIMB_BITS);
  64085. v2 ^= sub_mask;
  64086. u = v1 + v2;
  64087. carry1 = u < v1;
  64088. u += carry;
  64089. carry = (u < carry) | carry1;
  64090. r->tab[i] = u;
  64091. }
  64092. /* set the extra bits for the rounding */
  64093. r->tab[0] |= (z != 0);
  64094. /* carry is only possible in add case */
  64095. if (!is_sub && carry) {
  64096. if (bf_resize(r, r_len + 1))
  64097. goto fail;
  64098. r->tab[r_len] = 1;
  64099. r->expn += LIMB_BITS;
  64100. }
  64101. renorm:
  64102. ret = bf_normalize_and_round(r, prec, flags);
  64103. }
  64104. return ret;
  64105. fail:
  64106. bf_set_nan(r);
  64107. return BF_ST_MEM_ERROR;
  64108. }
  64109. static int __bf_add(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,
  64110. bf_flags_t flags)
  64111. {
  64112. return bf_add_internal(r, a, b, prec, flags, 0);
  64113. }
  64114. static int __bf_sub(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,
  64115. bf_flags_t flags)
  64116. {
  64117. return bf_add_internal(r, a, b, prec, flags, 1);
  64118. }
  64119. limb_t mp_add(limb_t *res, const limb_t *op1, const limb_t *op2,
  64120. limb_t n, limb_t carry)
  64121. {
  64122. slimb_t i;
  64123. limb_t k, a, v, k1;
  64124. k = carry;
  64125. for(i=0;i<n;i++) {
  64126. v = op1[i];
  64127. a = v + op2[i];
  64128. k1 = a < v;
  64129. a = a + k;
  64130. k = (a < k) | k1;
  64131. res[i] = a;
  64132. }
  64133. return k;
  64134. }
  64135. limb_t mp_add_ui(limb_t *tab, limb_t b, size_t n)
  64136. {
  64137. size_t i;
  64138. limb_t k, a;
  64139. k=b;
  64140. for(i=0;i<n;i++) {
  64141. if (k == 0)
  64142. break;
  64143. a = tab[i] + k;
  64144. k = (a < k);
  64145. tab[i] = a;
  64146. }
  64147. return k;
  64148. }
  64149. limb_t mp_sub(limb_t *res, const limb_t *op1, const limb_t *op2,
  64150. mp_size_t n, limb_t carry)
  64151. {
  64152. int i;
  64153. limb_t k, a, v, k1;
  64154. k = carry;
  64155. for(i=0;i<n;i++) {
  64156. v = op1[i];
  64157. a = v - op2[i];
  64158. k1 = a > v;
  64159. v = a - k;
  64160. k = (v > a) | k1;
  64161. res[i] = v;
  64162. }
  64163. return k;
  64164. }
  64165. /* compute 0 - op2 */
  64166. static limb_t mp_neg(limb_t *res, const limb_t *op2, mp_size_t n, limb_t carry)
  64167. {
  64168. int i;
  64169. limb_t k, a, v, k1;
  64170. k = carry;
  64171. for(i=0;i<n;i++) {
  64172. v = 0;
  64173. a = v - op2[i];
  64174. k1 = a > v;
  64175. v = a - k;
  64176. k = (v > a) | k1;
  64177. res[i] = v;
  64178. }
  64179. return k;
  64180. }
  64181. limb_t mp_sub_ui(limb_t *tab, limb_t b, mp_size_t n)
  64182. {
  64183. mp_size_t i;
  64184. limb_t k, a, v;
  64185. k=b;
  64186. for(i=0;i<n;i++) {
  64187. v = tab[i];
  64188. a = v - k;
  64189. k = a > v;
  64190. tab[i] = a;
  64191. if (k == 0)
  64192. break;
  64193. }
  64194. return k;
  64195. }
  64196. /* r = (a + high*B^n) >> shift. Return the remainder r (0 <= r < 2^shift).
  64197. 1 <= shift <= LIMB_BITS - 1 */
  64198. static limb_t mp_shr(limb_t *tab_r, const limb_t *tab, mp_size_t n,
  64199. int shift, limb_t high)
  64200. {
  64201. mp_size_t i;
  64202. limb_t l, a;
  64203. assert(shift >= 1 && shift < LIMB_BITS);
  64204. l = high;
  64205. for(i = n - 1; i >= 0; i--) {
  64206. a = tab[i];
  64207. tab_r[i] = (a >> shift) | (l << (LIMB_BITS - shift));
  64208. l = a;
  64209. }
  64210. return l & (((limb_t)1 << shift) - 1);
  64211. }
  64212. /* tabr[] = taba[] * b + l. Return the high carry */
  64213. static limb_t mp_mul1(limb_t *tabr, const limb_t *taba, limb_t n,
  64214. limb_t b, limb_t l)
  64215. {
  64216. limb_t i;
  64217. dlimb_t t;
  64218. for(i = 0; i < n; i++) {
  64219. t = (dlimb_t)taba[i] * (dlimb_t)b + l;
  64220. tabr[i] = t;
  64221. l = t >> LIMB_BITS;
  64222. }
  64223. return l;
  64224. }
  64225. /* tabr[] += taba[] * b, return the high word. */
  64226. static limb_t mp_add_mul1(limb_t *tabr, const limb_t *taba, limb_t n,
  64227. limb_t b)
  64228. {
  64229. limb_t i, l;
  64230. dlimb_t t;
  64231. l = 0;
  64232. for(i = 0; i < n; i++) {
  64233. t = (dlimb_t)taba[i] * (dlimb_t)b + l + tabr[i];
  64234. tabr[i] = t;
  64235. l = t >> LIMB_BITS;
  64236. }
  64237. return l;
  64238. }
  64239. /* size of the result : op1_size + op2_size. */
  64240. static void mp_mul_basecase(limb_t *result,
  64241. const limb_t *op1, limb_t op1_size,
  64242. const limb_t *op2, limb_t op2_size)
  64243. {
  64244. limb_t i, r;
  64245. result[op1_size] = mp_mul1(result, op1, op1_size, op2[0], 0);
  64246. for(i=1;i<op2_size;i++) {
  64247. r = mp_add_mul1(result + i, op1, op1_size, op2[i]);
  64248. result[i + op1_size] = r;
  64249. }
  64250. }
  64251. /* return 0 if OK, -1 if memory error */
  64252. /* XXX: change API so that result can be allocated */
  64253. int mp_mul(bf_context_t *s, limb_t *result,
  64254. const limb_t *op1, limb_t op1_size,
  64255. const limb_t *op2, limb_t op2_size)
  64256. {
  64257. #ifdef USE_FFT_MUL
  64258. if (unlikely(bf_min(op1_size, op2_size) >= FFT_MUL_THRESHOLD)) {
  64259. bf_t r_s, *r = &r_s;
  64260. r->tab = result;
  64261. /* XXX: optimize memory usage in API */
  64262. if (fft_mul(s, r, (limb_t *)op1, op1_size,
  64263. (limb_t *)op2, op2_size, FFT_MUL_R_NORESIZE))
  64264. return -1;
  64265. } else
  64266. #endif
  64267. {
  64268. mp_mul_basecase(result, op1, op1_size, op2, op2_size);
  64269. }
  64270. return 0;
  64271. }
  64272. /* tabr[] -= taba[] * b. Return the value to substract to the high
  64273. word. */
  64274. static limb_t mp_sub_mul1(limb_t *tabr, const limb_t *taba, limb_t n,
  64275. limb_t b)
  64276. {
  64277. limb_t i, l;
  64278. dlimb_t t;
  64279. l = 0;
  64280. for(i = 0; i < n; i++) {
  64281. t = tabr[i] - (dlimb_t)taba[i] * (dlimb_t)b - l;
  64282. tabr[i] = t;
  64283. l = -(t >> LIMB_BITS);
  64284. }
  64285. return l;
  64286. }
  64287. /* WARNING: d must be >= 2^(LIMB_BITS-1) */
  64288. static inline limb_t udiv1norm_init(limb_t d)
  64289. {
  64290. limb_t a0, a1;
  64291. a1 = -d - 1;
  64292. a0 = -1;
  64293. return (((dlimb_t)a1 << LIMB_BITS) | a0) / d;
  64294. }
  64295. /* return the quotient and the remainder in '*pr'of 'a1*2^LIMB_BITS+a0
  64296. / d' with 0 <= a1 < d. */
  64297. static inline limb_t udiv1norm(limb_t *pr, limb_t a1, limb_t a0,
  64298. limb_t d, limb_t d_inv)
  64299. {
  64300. limb_t n1m, n_adj, q, r, ah;
  64301. dlimb_t a;
  64302. n1m = ((slimb_t)a0 >> (LIMB_BITS - 1));
  64303. n_adj = a0 + (n1m & d);
  64304. a = (dlimb_t)d_inv * (a1 - n1m) + n_adj;
  64305. q = (a >> LIMB_BITS) + a1;
  64306. /* compute a - q * r and update q so that the remainder is\
  64307. between 0 and d - 1 */
  64308. a = ((dlimb_t)a1 << LIMB_BITS) | a0;
  64309. a = a - (dlimb_t)q * d - d;
  64310. ah = a >> LIMB_BITS;
  64311. q += 1 + ah;
  64312. r = (limb_t)a + (ah & d);
  64313. *pr = r;
  64314. return q;
  64315. }
  64316. /* b must be >= 1 << (LIMB_BITS - 1) */
  64317. static limb_t mp_div1norm(limb_t *tabr, const limb_t *taba, limb_t n,
  64318. limb_t b, limb_t r)
  64319. {
  64320. slimb_t i;
  64321. if (n >= UDIV1NORM_THRESHOLD) {
  64322. limb_t b_inv;
  64323. b_inv = udiv1norm_init(b);
  64324. for(i = n - 1; i >= 0; i--) {
  64325. tabr[i] = udiv1norm(&r, r, taba[i], b, b_inv);
  64326. }
  64327. } else {
  64328. dlimb_t a1;
  64329. for(i = n - 1; i >= 0; i--) {
  64330. a1 = ((dlimb_t)r << LIMB_BITS) | taba[i];
  64331. tabr[i] = a1 / b;
  64332. r = a1 % b;
  64333. }
  64334. }
  64335. return r;
  64336. }
  64337. static int mp_divnorm_large(bf_context_t *s,
  64338. limb_t *tabq, limb_t *taba, limb_t na,
  64339. const limb_t *tabb, limb_t nb);
  64340. /* base case division: divides taba[0..na-1] by tabb[0..nb-1]. tabb[nb
  64341. - 1] must be >= 1 << (LIMB_BITS - 1). na - nb must be >= 0. 'taba'
  64342. is modified and contains the remainder (nb limbs). tabq[0..na-nb]
  64343. contains the quotient with tabq[na - nb] <= 1. */
  64344. static int mp_divnorm(bf_context_t *s, limb_t *tabq, limb_t *taba, limb_t na,
  64345. const limb_t *tabb, limb_t nb)
  64346. {
  64347. limb_t r, a, c, q, v, b1, b1_inv, n, dummy_r;
  64348. slimb_t i, j;
  64349. b1 = tabb[nb - 1];
  64350. if (nb == 1) {
  64351. taba[0] = mp_div1norm(tabq, taba, na, b1, 0);
  64352. return 0;
  64353. }
  64354. n = na - nb;
  64355. if (bf_min(n, nb) >= DIVNORM_LARGE_THRESHOLD) {
  64356. return mp_divnorm_large(s, tabq, taba, na, tabb, nb);
  64357. }
  64358. if (n >= UDIV1NORM_THRESHOLD)
  64359. b1_inv = udiv1norm_init(b1);
  64360. else
  64361. b1_inv = 0;
  64362. /* first iteration: the quotient is only 0 or 1 */
  64363. q = 1;
  64364. for(j = nb - 1; j >= 0; j--) {
  64365. if (taba[n + j] != tabb[j]) {
  64366. if (taba[n + j] < tabb[j])
  64367. q = 0;
  64368. break;
  64369. }
  64370. }
  64371. tabq[n] = q;
  64372. if (q) {
  64373. mp_sub(taba + n, taba + n, tabb, nb, 0);
  64374. }
  64375. for(i = n - 1; i >= 0; i--) {
  64376. if (unlikely(taba[i + nb] >= b1)) {
  64377. q = -1;
  64378. } else if (b1_inv) {
  64379. q = udiv1norm(&dummy_r, taba[i + nb], taba[i + nb - 1], b1, b1_inv);
  64380. } else {
  64381. dlimb_t al;
  64382. al = ((dlimb_t)taba[i + nb] << LIMB_BITS) | taba[i + nb - 1];
  64383. q = al / b1;
  64384. r = al % b1;
  64385. }
  64386. r = mp_sub_mul1(taba + i, tabb, nb, q);
  64387. v = taba[i + nb];
  64388. a = v - r;
  64389. c = (a > v);
  64390. taba[i + nb] = a;
  64391. if (c != 0) {
  64392. /* negative result */
  64393. for(;;) {
  64394. q--;
  64395. c = mp_add(taba + i, taba + i, tabb, nb, 0);
  64396. /* propagate carry and test if positive result */
  64397. if (c != 0) {
  64398. if (++taba[i + nb] == 0) {
  64399. break;
  64400. }
  64401. }
  64402. }
  64403. }
  64404. tabq[i] = q;
  64405. }
  64406. return 0;
  64407. }
  64408. /* compute r=B^(2*n)/a such as a*r < B^(2*n) < a*r + 2 with n >= 1. 'a'
  64409. has n limbs with a[n-1] >= B/2 and 'r' has n+1 limbs with r[n] = 1.
  64410. See Modern Computer Arithmetic by Richard P. Brent and Paul
  64411. Zimmermann, algorithm 3.5 */
  64412. int mp_recip(bf_context_t *s, limb_t *tabr, const limb_t *taba, limb_t n)
  64413. {
  64414. mp_size_t l, h, k, i;
  64415. limb_t *tabxh, *tabt, c, *tabu;
  64416. if (n <= 2) {
  64417. /* return ceil(B^(2*n)/a) - 1 */
  64418. /* XXX: could avoid allocation */
  64419. tabu = bf_malloc(s, sizeof(limb_t) * (2 * n + 1));
  64420. tabt = bf_malloc(s, sizeof(limb_t) * (n + 2));
  64421. if (!tabt || !tabu)
  64422. goto fail;
  64423. for(i = 0; i < 2 * n; i++)
  64424. tabu[i] = 0;
  64425. tabu[2 * n] = 1;
  64426. if (mp_divnorm(s, tabt, tabu, 2 * n + 1, taba, n))
  64427. goto fail;
  64428. for(i = 0; i < n + 1; i++)
  64429. tabr[i] = tabt[i];
  64430. if (mp_scan_nz(tabu, n) == 0) {
  64431. /* only happens for a=B^n/2 */
  64432. mp_sub_ui(tabr, 1, n + 1);
  64433. }
  64434. } else {
  64435. l = (n - 1) / 2;
  64436. h = n - l;
  64437. /* n=2p -> l=p-1, h = p + 1, k = p + 3
  64438. n=2p+1-> l=p, h = p + 1; k = p + 2
  64439. */
  64440. tabt = bf_malloc(s, sizeof(limb_t) * (n + h + 1));
  64441. tabu = bf_malloc(s, sizeof(limb_t) * (n + 2 * h - l + 2));
  64442. if (!tabt || !tabu)
  64443. goto fail;
  64444. tabxh = tabr + l;
  64445. if (mp_recip(s, tabxh, taba + l, h))
  64446. goto fail;
  64447. if (mp_mul(s, tabt, taba, n, tabxh, h + 1)) /* n + h + 1 limbs */
  64448. goto fail;
  64449. while (tabt[n + h] != 0) {
  64450. mp_sub_ui(tabxh, 1, h + 1);
  64451. c = mp_sub(tabt, tabt, taba, n, 0);
  64452. mp_sub_ui(tabt + n, c, h + 1);
  64453. }
  64454. /* T = B^(n+h) - T */
  64455. mp_neg(tabt, tabt, n + h + 1, 0);
  64456. tabt[n + h]++;
  64457. if (mp_mul(s, tabu, tabt + l, n + h + 1 - l, tabxh, h + 1))
  64458. goto fail;
  64459. /* n + 2*h - l + 2 limbs */
  64460. k = 2 * h - l;
  64461. for(i = 0; i < l; i++)
  64462. tabr[i] = tabu[i + k];
  64463. mp_add(tabr + l, tabr + l, tabu + 2 * h, h, 0);
  64464. }
  64465. bf_free(s, tabt);
  64466. bf_free(s, tabu);
  64467. return 0;
  64468. fail:
  64469. bf_free(s, tabt);
  64470. bf_free(s, tabu);
  64471. return -1;
  64472. }
  64473. /* return -1, 0 or 1 */
  64474. static int mp_cmp(const limb_t *taba, const limb_t *tabb, mp_size_t n)
  64475. {
  64476. mp_size_t i;
  64477. for(i = n - 1; i >= 0; i--) {
  64478. if (taba[i] != tabb[i]) {
  64479. if (taba[i] < tabb[i])
  64480. return -1;
  64481. else
  64482. return 1;
  64483. }
  64484. }
  64485. return 0;
  64486. }
  64487. //#define DEBUG_DIVNORM_LARGE
  64488. //#define DEBUG_DIVNORM_LARGE2
  64489. /* subquadratic divnorm */
  64490. static int mp_divnorm_large(bf_context_t *s,
  64491. limb_t *tabq, limb_t *taba, limb_t na,
  64492. const limb_t *tabb, limb_t nb)
  64493. {
  64494. limb_t *tabb_inv, nq, *tabt, i, n;
  64495. nq = na - nb;
  64496. #ifdef DEBUG_DIVNORM_LARGE
  64497. printf("na=%d nb=%d nq=%d\n", (int)na, (int)nb, (int)nq);
  64498. mp_print_str("a", taba, na);
  64499. mp_print_str("b", tabb, nb);
  64500. #endif
  64501. assert(nq >= 1);
  64502. n = nq;
  64503. if (nq < nb)
  64504. n++;
  64505. tabb_inv = bf_malloc(s, sizeof(limb_t) * (n + 1));
  64506. tabt = bf_malloc(s, sizeof(limb_t) * 2 * (n + 1));
  64507. if (!tabb_inv || !tabt)
  64508. goto fail;
  64509. if (n >= nb) {
  64510. for(i = 0; i < n - nb; i++)
  64511. tabt[i] = 0;
  64512. for(i = 0; i < nb; i++)
  64513. tabt[i + n - nb] = tabb[i];
  64514. } else {
  64515. /* truncate B: need to increment it so that the approximate
  64516. inverse is smaller that the exact inverse */
  64517. for(i = 0; i < n; i++)
  64518. tabt[i] = tabb[i + nb - n];
  64519. if (mp_add_ui(tabt, 1, n)) {
  64520. /* tabt = B^n : tabb_inv = B^n */
  64521. memset(tabb_inv, 0, n * sizeof(limb_t));
  64522. tabb_inv[n] = 1;
  64523. goto recip_done;
  64524. }
  64525. }
  64526. if (mp_recip(s, tabb_inv, tabt, n))
  64527. goto fail;
  64528. recip_done:
  64529. /* Q=A*B^-1 */
  64530. if (mp_mul(s, tabt, tabb_inv, n + 1, taba + na - (n + 1), n + 1))
  64531. goto fail;
  64532. for(i = 0; i < nq + 1; i++)
  64533. tabq[i] = tabt[i + 2 * (n + 1) - (nq + 1)];
  64534. #ifdef DEBUG_DIVNORM_LARGE
  64535. mp_print_str("q", tabq, nq + 1);
  64536. #endif
  64537. bf_free(s, tabt);
  64538. bf_free(s, tabb_inv);
  64539. tabb_inv = NULL;
  64540. /* R=A-B*Q */
  64541. tabt = bf_malloc(s, sizeof(limb_t) * (na + 1));
  64542. if (!tabt)
  64543. goto fail;
  64544. if (mp_mul(s, tabt, tabq, nq + 1, tabb, nb))
  64545. goto fail;
  64546. /* we add one more limb for the result */
  64547. mp_sub(taba, taba, tabt, nb + 1, 0);
  64548. bf_free(s, tabt);
  64549. /* the approximated quotient is smaller than than the exact one,
  64550. hence we may have to increment it */
  64551. #ifdef DEBUG_DIVNORM_LARGE2
  64552. int cnt = 0;
  64553. static int cnt_max;
  64554. #endif
  64555. for(;;) {
  64556. if (taba[nb] == 0 && mp_cmp(taba, tabb, nb) < 0)
  64557. break;
  64558. taba[nb] -= mp_sub(taba, taba, tabb, nb, 0);
  64559. mp_add_ui(tabq, 1, nq + 1);
  64560. #ifdef DEBUG_DIVNORM_LARGE2
  64561. cnt++;
  64562. #endif
  64563. }
  64564. #ifdef DEBUG_DIVNORM_LARGE2
  64565. if (cnt > cnt_max) {
  64566. cnt_max = cnt;
  64567. printf("\ncnt=%d nq=%d nb=%d\n", cnt_max, (int)nq, (int)nb);
  64568. }
  64569. #endif
  64570. return 0;
  64571. fail:
  64572. bf_free(s, tabb_inv);
  64573. bf_free(s, tabt);
  64574. return -1;
  64575. }
  64576. int bf_mul(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,
  64577. bf_flags_t flags)
  64578. {
  64579. int ret, r_sign;
  64580. if (a->len < b->len) {
  64581. const bf_t *tmp = a;
  64582. a = b;
  64583. b = tmp;
  64584. }
  64585. r_sign = a->sign ^ b->sign;
  64586. /* here b->len <= a->len */
  64587. if (b->len == 0) {
  64588. if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) {
  64589. bf_set_nan(r);
  64590. ret = 0;
  64591. } else if (a->expn == BF_EXP_INF || b->expn == BF_EXP_INF) {
  64592. if ((a->expn == BF_EXP_INF && b->expn == BF_EXP_ZERO) ||
  64593. (a->expn == BF_EXP_ZERO && b->expn == BF_EXP_INF)) {
  64594. bf_set_nan(r);
  64595. ret = BF_ST_INVALID_OP;
  64596. } else {
  64597. bf_set_inf(r, r_sign);
  64598. ret = 0;
  64599. }
  64600. } else {
  64601. bf_set_zero(r, r_sign);
  64602. ret = 0;
  64603. }
  64604. } else {
  64605. bf_t tmp, *r1 = NULL;
  64606. limb_t a_len, b_len, precl;
  64607. limb_t *a_tab, *b_tab;
  64608. a_len = a->len;
  64609. b_len = b->len;
  64610. if ((flags & BF_RND_MASK) == BF_RNDF) {
  64611. /* faithful rounding does not require using the full inputs */
  64612. precl = (prec + 2 + LIMB_BITS - 1) / LIMB_BITS;
  64613. a_len = bf_min(a_len, precl);
  64614. b_len = bf_min(b_len, precl);
  64615. }
  64616. a_tab = a->tab + a->len - a_len;
  64617. b_tab = b->tab + b->len - b_len;
  64618. #ifdef USE_FFT_MUL
  64619. if (b_len >= FFT_MUL_THRESHOLD) {
  64620. int mul_flags = 0;
  64621. if (r == a)
  64622. mul_flags |= FFT_MUL_R_OVERLAP_A;
  64623. if (r == b)
  64624. mul_flags |= FFT_MUL_R_OVERLAP_B;
  64625. if (fft_mul(r->ctx, r, a_tab, a_len, b_tab, b_len, mul_flags))
  64626. goto fail;
  64627. } else
  64628. #endif
  64629. {
  64630. if (r == a || r == b) {
  64631. bf_init(r->ctx, &tmp);
  64632. r1 = r;
  64633. r = &tmp;
  64634. }
  64635. if (bf_resize(r, a_len + b_len)) {
  64636. fail:
  64637. bf_set_nan(r);
  64638. ret = BF_ST_MEM_ERROR;
  64639. goto done;
  64640. }
  64641. mp_mul_basecase(r->tab, a_tab, a_len, b_tab, b_len);
  64642. }
  64643. r->sign = r_sign;
  64644. r->expn = a->expn + b->expn;
  64645. ret = bf_normalize_and_round(r, prec, flags);
  64646. done:
  64647. if (r == &tmp)
  64648. bf_move(r1, &tmp);
  64649. }
  64650. return ret;
  64651. }
  64652. /* multiply 'r' by 2^e */
  64653. int bf_mul_2exp(bf_t *r, slimb_t e, limb_t prec, bf_flags_t flags)
  64654. {
  64655. slimb_t e_max;
  64656. if (r->len == 0)
  64657. return 0;
  64658. e_max = ((limb_t)1 << BF_EXT_EXP_BITS_MAX) - 1;
  64659. e = bf_max(e, -e_max);
  64660. e = bf_min(e, e_max);
  64661. r->expn += e;
  64662. return __bf_round(r, prec, flags, r->len, 0);
  64663. }
  64664. /* Return e such as a=m*2^e with m odd integer. return 0 if a is zero,
  64665. Infinite or Nan. */
  64666. slimb_t bf_get_exp_min(const bf_t *a)
  64667. {
  64668. slimb_t i;
  64669. limb_t v;
  64670. int k;
  64671. for(i = 0; i < a->len; i++) {
  64672. v = a->tab[i];
  64673. if (v != 0) {
  64674. k = ctz(v);
  64675. return a->expn - (a->len - i) * LIMB_BITS + k;
  64676. }
  64677. }
  64678. return 0;
  64679. }
  64680. /* a and b must be finite numbers with a >= 0 and b > 0. 'q' is the
  64681. integer defined as floor(a/b) and r = a - q * b. */
  64682. static void bf_tdivremu(bf_t *q, bf_t *r,
  64683. const bf_t *a, const bf_t *b)
  64684. {
  64685. if (bf_cmpu(a, b) < 0) {
  64686. bf_set_ui(q, 0);
  64687. bf_set(r, a);
  64688. } else {
  64689. bf_div(q, a, b, bf_max(a->expn - b->expn + 1, 2), BF_RNDZ);
  64690. bf_rint(q, BF_RNDZ);
  64691. bf_mul(r, q, b, BF_PREC_INF, BF_RNDZ);
  64692. bf_sub(r, a, r, BF_PREC_INF, BF_RNDZ);
  64693. }
  64694. }
  64695. static int __bf_div(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,
  64696. bf_flags_t flags)
  64697. {
  64698. bf_context_t *s = r->ctx;
  64699. int ret, r_sign;
  64700. limb_t n, nb, precl;
  64701. r_sign = a->sign ^ b->sign;
  64702. if (a->expn >= BF_EXP_INF || b->expn >= BF_EXP_INF) {
  64703. if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) {
  64704. bf_set_nan(r);
  64705. return 0;
  64706. } else if (a->expn == BF_EXP_INF && b->expn == BF_EXP_INF) {
  64707. bf_set_nan(r);
  64708. return BF_ST_INVALID_OP;
  64709. } else if (a->expn == BF_EXP_INF) {
  64710. bf_set_inf(r, r_sign);
  64711. return 0;
  64712. } else {
  64713. bf_set_zero(r, r_sign);
  64714. return 0;
  64715. }
  64716. } else if (a->expn == BF_EXP_ZERO) {
  64717. if (b->expn == BF_EXP_ZERO) {
  64718. bf_set_nan(r);
  64719. return BF_ST_INVALID_OP;
  64720. } else {
  64721. bf_set_zero(r, r_sign);
  64722. return 0;
  64723. }
  64724. } else if (b->expn == BF_EXP_ZERO) {
  64725. bf_set_inf(r, r_sign);
  64726. return BF_ST_DIVIDE_ZERO;
  64727. }
  64728. /* number of limbs of the quotient (2 extra bits for rounding) */
  64729. precl = (prec + 2 + LIMB_BITS - 1) / LIMB_BITS;
  64730. nb = b->len;
  64731. n = bf_max(a->len, precl);
  64732. {
  64733. limb_t *taba, na;
  64734. slimb_t d;
  64735. na = n + nb;
  64736. #if LIMB_LOG2_BITS == 6
  64737. if (na >= (SIZE_MAX / sizeof(limb_t)) - 1) {
  64738. return BF_ST_MEM_ERROR; /* Return memory error status */
  64739. }
  64740. #endif
  64741. taba = bf_malloc(s, (na + 1) * sizeof(limb_t));
  64742. if (!taba)
  64743. goto fail;
  64744. d = na - a->len;
  64745. memset(taba, 0, d * sizeof(limb_t));
  64746. memcpy(taba + d, a->tab, a->len * sizeof(limb_t));
  64747. if (bf_resize(r, n + 1))
  64748. goto fail1;
  64749. if (mp_divnorm(s, r->tab, taba, na, b->tab, nb)) {
  64750. fail1:
  64751. bf_free(s, taba);
  64752. goto fail;
  64753. }
  64754. /* see if non zero remainder */
  64755. if (mp_scan_nz(taba, nb))
  64756. r->tab[0] |= 1;
  64757. bf_free(r->ctx, taba);
  64758. r->expn = a->expn - b->expn + LIMB_BITS;
  64759. r->sign = r_sign;
  64760. ret = bf_normalize_and_round(r, prec, flags);
  64761. }
  64762. return ret;
  64763. fail:
  64764. bf_set_nan(r);
  64765. return BF_ST_MEM_ERROR;
  64766. }
  64767. /* division and remainder.
  64768. rnd_mode is the rounding mode for the quotient. The additional
  64769. rounding mode BF_RND_EUCLIDIAN is supported.
  64770. 'q' is an integer. 'r' is rounded with prec and flags (prec can be
  64771. BF_PREC_INF).
  64772. */
  64773. int bf_divrem(bf_t *q, bf_t *r, const bf_t *a, const bf_t *b,
  64774. limb_t prec, bf_flags_t flags, int rnd_mode)
  64775. {
  64776. bf_t a1_s, *a1 = &a1_s;
  64777. bf_t b1_s, *b1 = &b1_s;
  64778. int q_sign, ret;
  64779. bool is_ceil, is_rndn;
  64780. assert(q != a && q != b);
  64781. assert(r != a && r != b);
  64782. assert(q != r);
  64783. if (a->len == 0 || b->len == 0) {
  64784. bf_set_zero(q, 0);
  64785. if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) {
  64786. bf_set_nan(r);
  64787. return 0;
  64788. } else if (a->expn == BF_EXP_INF || b->expn == BF_EXP_ZERO) {
  64789. bf_set_nan(r);
  64790. return BF_ST_INVALID_OP;
  64791. } else {
  64792. bf_set(r, a);
  64793. return bf_round(r, prec, flags);
  64794. }
  64795. }
  64796. q_sign = a->sign ^ b->sign;
  64797. is_rndn = (rnd_mode == BF_RNDN || rnd_mode == BF_RNDNA);
  64798. switch(rnd_mode) {
  64799. default:
  64800. case BF_RNDZ:
  64801. case BF_RNDN:
  64802. case BF_RNDNA:
  64803. is_ceil = false;
  64804. break;
  64805. case BF_RNDD:
  64806. is_ceil = q_sign;
  64807. break;
  64808. case BF_RNDU:
  64809. is_ceil = q_sign ^ 1;
  64810. break;
  64811. case BF_RNDA:
  64812. is_ceil = true;
  64813. break;
  64814. case BF_DIVREM_EUCLIDIAN:
  64815. is_ceil = a->sign;
  64816. break;
  64817. }
  64818. a1->expn = a->expn;
  64819. a1->tab = a->tab;
  64820. a1->len = a->len;
  64821. a1->sign = 0;
  64822. b1->expn = b->expn;
  64823. b1->tab = b->tab;
  64824. b1->len = b->len;
  64825. b1->sign = 0;
  64826. /* XXX: could improve to avoid having a large 'q' */
  64827. bf_tdivremu(q, r, a1, b1);
  64828. if (bf_is_nan(q) || bf_is_nan(r))
  64829. goto fail;
  64830. if (r->len != 0) {
  64831. if (is_rndn) {
  64832. int res;
  64833. b1->expn--;
  64834. res = bf_cmpu(r, b1);
  64835. b1->expn++;
  64836. if (res > 0 ||
  64837. (res == 0 &&
  64838. (rnd_mode == BF_RNDNA ||
  64839. get_bit(q->tab, q->len, q->len * LIMB_BITS - q->expn)))) {
  64840. goto do_sub_r;
  64841. }
  64842. } else if (is_ceil) {
  64843. do_sub_r:
  64844. ret = bf_add_si(q, q, 1, BF_PREC_INF, BF_RNDZ);
  64845. ret |= bf_sub(r, r, b1, BF_PREC_INF, BF_RNDZ);
  64846. if (ret & BF_ST_MEM_ERROR)
  64847. goto fail;
  64848. }
  64849. }
  64850. r->sign ^= a->sign;
  64851. q->sign = q_sign;
  64852. return bf_round(r, prec, flags);
  64853. fail:
  64854. bf_set_nan(q);
  64855. bf_set_nan(r);
  64856. return BF_ST_MEM_ERROR;
  64857. }
  64858. int bf_rem(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,
  64859. bf_flags_t flags, int rnd_mode)
  64860. {
  64861. bf_t q_s, *q = &q_s;
  64862. int ret;
  64863. bf_init(r->ctx, q);
  64864. ret = bf_divrem(q, r, a, b, prec, flags, rnd_mode);
  64865. bf_delete(q);
  64866. return ret;
  64867. }
  64868. static inline int bf_get_limb(slimb_t *pres, const bf_t *a, int flags)
  64869. {
  64870. #if LIMB_BITS == 32
  64871. return bf_get_int32(pres, a, flags);
  64872. #else
  64873. return bf_get_int64(pres, a, flags);
  64874. #endif
  64875. }
  64876. int bf_remquo(slimb_t *pq, bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,
  64877. bf_flags_t flags, int rnd_mode)
  64878. {
  64879. bf_t q_s, *q = &q_s;
  64880. int ret;
  64881. bf_init(r->ctx, q);
  64882. ret = bf_divrem(q, r, a, b, prec, flags, rnd_mode);
  64883. bf_get_limb(pq, q, BF_GET_INT_MOD);
  64884. bf_delete(q);
  64885. return ret;
  64886. }
  64887. static __maybe_unused inline limb_t mul_mod(limb_t a, limb_t b, limb_t m)
  64888. {
  64889. dlimb_t t;
  64890. t = (dlimb_t)a * (dlimb_t)b;
  64891. return t % m;
  64892. }
  64893. #if defined(USE_MUL_CHECK)
  64894. static limb_t mp_mod1(const limb_t *tab, limb_t n, limb_t m, limb_t r)
  64895. {
  64896. slimb_t i;
  64897. dlimb_t t;
  64898. for(i = n - 1; i >= 0; i--) {
  64899. t = ((dlimb_t)r << LIMB_BITS) | tab[i];
  64900. r = t % m;
  64901. }
  64902. return r;
  64903. }
  64904. #endif
  64905. static const uint16_t sqrt_table[192] = {
  64906. 128,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,144,145,146,147,148,149,150,150,151,152,153,154,155,155,156,157,158,159,160,160,161,162,163,163,164,165,166,167,167,168,169,170,170,171,172,173,173,174,175,176,176,177,178,178,179,180,181,181,182,183,183,184,185,185,186,187,187,188,189,189,190,191,192,192,193,193,194,195,195,196,197,197,198,199,199,200,201,201,202,203,203,204,204,205,206,206,207,208,208,209,209,210,211,211,212,212,213,214,214,215,215,216,217,217,218,218,219,219,220,221,221,222,222,223,224,224,225,225,226,226,227,227,228,229,229,230,230,231,231,232,232,233,234,234,235,235,236,236,237,237,238,238,239,240,240,241,241,242,242,243,243,244,244,245,245,246,246,247,247,248,248,249,249,250,250,251,251,252,252,253,253,254,254,255,
  64907. };
  64908. /* a >= 2^(LIMB_BITS - 2). Return (s, r) with s=floor(sqrt(a)) and
  64909. r=a-s^2. 0 <= r <= 2 * s */
  64910. static limb_t mp_sqrtrem1(limb_t *pr, limb_t a)
  64911. {
  64912. limb_t s1, r1, s, r, q, u, num;
  64913. /* use a table for the 16 -> 8 bit sqrt */
  64914. s1 = sqrt_table[(a >> (LIMB_BITS - 8)) - 64];
  64915. r1 = (a >> (LIMB_BITS - 16)) - s1 * s1;
  64916. if (r1 > 2 * s1) {
  64917. r1 -= 2 * s1 + 1;
  64918. s1++;
  64919. }
  64920. /* one iteration to get a 32 -> 16 bit sqrt */
  64921. num = (r1 << 8) | ((a >> (LIMB_BITS - 32 + 8)) & 0xff);
  64922. q = num / (2 * s1); /* q <= 2^8 */
  64923. u = num % (2 * s1);
  64924. s = (s1 << 8) + q;
  64925. r = (u << 8) | ((a >> (LIMB_BITS - 32)) & 0xff);
  64926. r -= q * q;
  64927. if ((slimb_t)r < 0) {
  64928. s--;
  64929. r += 2 * s + 1;
  64930. }
  64931. #if LIMB_BITS == 64
  64932. s1 = s;
  64933. r1 = r;
  64934. /* one more iteration for 64 -> 32 bit sqrt */
  64935. num = (r1 << 16) | ((a >> (LIMB_BITS - 64 + 16)) & 0xffff);
  64936. q = num / (2 * s1); /* q <= 2^16 */
  64937. u = num % (2 * s1);
  64938. s = (s1 << 16) + q;
  64939. r = (u << 16) | ((a >> (LIMB_BITS - 64)) & 0xffff);
  64940. r -= q * q;
  64941. if ((slimb_t)r < 0) {
  64942. s--;
  64943. r += 2 * s + 1;
  64944. }
  64945. #endif
  64946. *pr = r;
  64947. return s;
  64948. }
  64949. /* return floor(sqrt(a)) */
  64950. limb_t bf_isqrt(limb_t a)
  64951. {
  64952. limb_t s, r;
  64953. int k;
  64954. if (a == 0)
  64955. return 0;
  64956. k = clz(a) & ~1;
  64957. s = mp_sqrtrem1(&r, a << k);
  64958. s >>= (k >> 1);
  64959. return s;
  64960. }
  64961. static limb_t mp_sqrtrem2(limb_t *tabs, limb_t *taba)
  64962. {
  64963. limb_t s1, r1, s, q, u, a0, a1;
  64964. dlimb_t r, num;
  64965. int l;
  64966. a0 = taba[0];
  64967. a1 = taba[1];
  64968. s1 = mp_sqrtrem1(&r1, a1);
  64969. l = LIMB_BITS / 2;
  64970. num = ((dlimb_t)r1 << l) | (a0 >> l);
  64971. q = num / (2 * s1);
  64972. u = num % (2 * s1);
  64973. s = (s1 << l) + q;
  64974. r = ((dlimb_t)u << l) | (a0 & (((limb_t)1 << l) - 1));
  64975. if (unlikely((q >> l) != 0))
  64976. r -= (dlimb_t)1 << LIMB_BITS; /* special case when q=2^l */
  64977. else
  64978. r -= q * q;
  64979. if ((slimb_t)(r >> LIMB_BITS) < 0) {
  64980. s--;
  64981. r += 2 * (dlimb_t)s + 1;
  64982. }
  64983. tabs[0] = s;
  64984. taba[0] = r;
  64985. return r >> LIMB_BITS;
  64986. }
  64987. //#define DEBUG_SQRTREM
  64988. /* tmp_buf must contain (n / 2 + 1 limbs). *prh contains the highest
  64989. limb of the remainder. */
  64990. static int mp_sqrtrem_rec(bf_context_t *s, limb_t *tabs, limb_t *taba, limb_t n,
  64991. limb_t *tmp_buf, limb_t *prh)
  64992. {
  64993. limb_t l, h, rh, ql, qh, c, i;
  64994. if (n == 1) {
  64995. *prh = mp_sqrtrem2(tabs, taba);
  64996. return 0;
  64997. }
  64998. #ifdef DEBUG_SQRTREM
  64999. mp_print_str("a", taba, 2 * n);
  65000. #endif
  65001. l = n / 2;
  65002. h = n - l;
  65003. if (mp_sqrtrem_rec(s, tabs + l, taba + 2 * l, h, tmp_buf, &qh))
  65004. return -1;
  65005. #ifdef DEBUG_SQRTREM
  65006. mp_print_str("s1", tabs + l, h);
  65007. mp_print_str_h("r1", taba + 2 * l, h, qh);
  65008. mp_print_str_h("r2", taba + l, n, qh);
  65009. #endif
  65010. /* the remainder is in taba + 2 * l. Its high bit is in qh */
  65011. if (qh) {
  65012. mp_sub(taba + 2 * l, taba + 2 * l, tabs + l, h, 0);
  65013. }
  65014. /* instead of dividing by 2*s, divide by s (which is normalized)
  65015. and update q and r */
  65016. if (mp_divnorm(s, tmp_buf, taba + l, n, tabs + l, h))
  65017. return -1;
  65018. qh += tmp_buf[l];
  65019. for(i = 0; i < l; i++)
  65020. tabs[i] = tmp_buf[i];
  65021. ql = mp_shr(tabs, tabs, l, 1, qh & 1);
  65022. qh = qh >> 1; /* 0 or 1 */
  65023. if (ql)
  65024. rh = mp_add(taba + l, taba + l, tabs + l, h, 0);
  65025. else
  65026. rh = 0;
  65027. #ifdef DEBUG_SQRTREM
  65028. mp_print_str_h("q", tabs, l, qh);
  65029. mp_print_str_h("u", taba + l, h, rh);
  65030. #endif
  65031. mp_add_ui(tabs + l, qh, h);
  65032. #ifdef DEBUG_SQRTREM
  65033. mp_print_str_h("s2", tabs, n, sh);
  65034. #endif
  65035. /* q = qh, tabs[l - 1 ... 0], r = taba[n - 1 ... l] */
  65036. /* subtract q^2. if qh = 1 then q = B^l, so we can take shortcuts */
  65037. if (qh) {
  65038. c = qh;
  65039. } else {
  65040. if (mp_mul(s, taba + n, tabs, l, tabs, l))
  65041. return -1;
  65042. c = mp_sub(taba, taba, taba + n, 2 * l, 0);
  65043. }
  65044. rh -= mp_sub_ui(taba + 2 * l, c, n - 2 * l);
  65045. if ((slimb_t)rh < 0) {
  65046. mp_sub_ui(tabs, 1, n);
  65047. rh += mp_add_mul1(taba, tabs, n, 2);
  65048. rh += mp_add_ui(taba, 1, n);
  65049. }
  65050. *prh = rh;
  65051. return 0;
  65052. }
  65053. /* 'taba' has 2*n limbs with n >= 1 and taba[2*n-1] >= 2 ^ (LIMB_BITS
  65054. - 2). Return (s, r) with s=floor(sqrt(a)) and r=a-s^2. 0 <= r <= 2
  65055. * s. tabs has n limbs. r is returned in the lower n limbs of
  65056. taba. Its r[n] is the returned value of the function. */
  65057. /* Algorithm from the article "Karatsuba Square Root" by Paul Zimmermann and
  65058. inspirated from its GMP implementation */
  65059. int mp_sqrtrem(bf_context_t *s, limb_t *tabs, limb_t *taba, limb_t n)
  65060. {
  65061. limb_t tmp_buf1[8];
  65062. limb_t *tmp_buf;
  65063. mp_size_t n2;
  65064. int ret;
  65065. n2 = n / 2 + 1;
  65066. if (n2 <= countof(tmp_buf1)) {
  65067. tmp_buf = tmp_buf1;
  65068. } else {
  65069. tmp_buf = bf_malloc(s, sizeof(limb_t) * n2);
  65070. if (!tmp_buf)
  65071. return -1;
  65072. }
  65073. ret = mp_sqrtrem_rec(s, tabs, taba, n, tmp_buf, taba + n);
  65074. if (tmp_buf != tmp_buf1)
  65075. bf_free(s, tmp_buf);
  65076. return ret;
  65077. }
  65078. /* Integer square root with remainder. 'a' must be an integer. r =
  65079. floor(sqrt(a)) and rem = a - r^2. BF_ST_INEXACT is set if the result
  65080. is inexact. 'rem' can be NULL if the remainder is not needed. */
  65081. int bf_sqrtrem(bf_t *r, bf_t *rem1, const bf_t *a)
  65082. {
  65083. int ret;
  65084. if (a->len == 0) {
  65085. if (a->expn == BF_EXP_NAN) {
  65086. bf_set_nan(r);
  65087. } else if (a->expn == BF_EXP_INF && a->sign) {
  65088. goto invalid_op;
  65089. } else {
  65090. bf_set(r, a);
  65091. }
  65092. if (rem1)
  65093. bf_set_ui(rem1, 0);
  65094. ret = 0;
  65095. } else if (a->sign) {
  65096. invalid_op:
  65097. bf_set_nan(r);
  65098. if (rem1)
  65099. bf_set_ui(rem1, 0);
  65100. ret = BF_ST_INVALID_OP;
  65101. } else {
  65102. bf_t rem_s, *rem;
  65103. bf_sqrt(r, a, (a->expn + 1) / 2, BF_RNDZ);
  65104. bf_rint(r, BF_RNDZ);
  65105. /* see if the result is exact by computing the remainder */
  65106. if (rem1) {
  65107. rem = rem1;
  65108. } else {
  65109. rem = &rem_s;
  65110. bf_init(r->ctx, rem);
  65111. }
  65112. /* XXX: could avoid recomputing the remainder */
  65113. bf_mul(rem, r, r, BF_PREC_INF, BF_RNDZ);
  65114. bf_neg(rem);
  65115. bf_add(rem, rem, a, BF_PREC_INF, BF_RNDZ);
  65116. if (bf_is_nan(rem)) {
  65117. ret = BF_ST_MEM_ERROR;
  65118. goto done;
  65119. }
  65120. if (rem->len != 0) {
  65121. ret = BF_ST_INEXACT;
  65122. } else {
  65123. ret = 0;
  65124. }
  65125. done:
  65126. if (!rem1)
  65127. bf_delete(rem);
  65128. }
  65129. return ret;
  65130. }
  65131. int bf_sqrt(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags)
  65132. {
  65133. bf_context_t *s = a->ctx;
  65134. int ret;
  65135. assert(r != a);
  65136. if (a->len == 0) {
  65137. if (a->expn == BF_EXP_NAN) {
  65138. bf_set_nan(r);
  65139. } else if (a->expn == BF_EXP_INF && a->sign) {
  65140. goto invalid_op;
  65141. } else {
  65142. bf_set(r, a);
  65143. }
  65144. ret = 0;
  65145. } else if (a->sign) {
  65146. invalid_op:
  65147. bf_set_nan(r);
  65148. ret = BF_ST_INVALID_OP;
  65149. } else {
  65150. limb_t *a1;
  65151. slimb_t n, n1;
  65152. limb_t res;
  65153. /* convert the mantissa to an integer with at least 2 *
  65154. prec + 4 bits */
  65155. n = (2 * (prec + 2) + 2 * LIMB_BITS - 1) / (2 * LIMB_BITS);
  65156. if (bf_resize(r, n))
  65157. goto fail;
  65158. a1 = bf_malloc(s, sizeof(limb_t) * 2 * n);
  65159. if (!a1)
  65160. goto fail;
  65161. n1 = bf_min(2 * n, a->len);
  65162. memset(a1, 0, (2 * n - n1) * sizeof(limb_t));
  65163. memcpy(a1 + 2 * n - n1, a->tab + a->len - n1, n1 * sizeof(limb_t));
  65164. if (a->expn & 1) {
  65165. res = mp_shr(a1, a1, 2 * n, 1, 0);
  65166. } else {
  65167. res = 0;
  65168. }
  65169. if (mp_sqrtrem(s, r->tab, a1, n)) {
  65170. bf_free(s, a1);
  65171. goto fail;
  65172. }
  65173. if (!res) {
  65174. res = mp_scan_nz(a1, n + 1);
  65175. }
  65176. bf_free(s, a1);
  65177. if (!res) {
  65178. res = mp_scan_nz(a->tab, a->len - n1);
  65179. }
  65180. if (res != 0)
  65181. r->tab[0] |= 1;
  65182. r->sign = 0;
  65183. r->expn = (a->expn + 1) >> 1;
  65184. ret = bf_round(r, prec, flags);
  65185. }
  65186. return ret;
  65187. fail:
  65188. bf_set_nan(r);
  65189. return BF_ST_MEM_ERROR;
  65190. }
  65191. static no_inline int bf_op2(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,
  65192. bf_flags_t flags, bf_op2_func_t *func)
  65193. {
  65194. bf_t tmp;
  65195. int ret;
  65196. if (r == a || r == b) {
  65197. bf_init(r->ctx, &tmp);
  65198. ret = func(&tmp, a, b, prec, flags);
  65199. bf_move(r, &tmp);
  65200. } else {
  65201. ret = func(r, a, b, prec, flags);
  65202. }
  65203. return ret;
  65204. }
  65205. int bf_add(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,
  65206. bf_flags_t flags)
  65207. {
  65208. return bf_op2(r, a, b, prec, flags, __bf_add);
  65209. }
  65210. int bf_sub(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,
  65211. bf_flags_t flags)
  65212. {
  65213. return bf_op2(r, a, b, prec, flags, __bf_sub);
  65214. }
  65215. int bf_div(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,
  65216. bf_flags_t flags)
  65217. {
  65218. return bf_op2(r, a, b, prec, flags, __bf_div);
  65219. }
  65220. int bf_mul_ui(bf_t *r, const bf_t *a, uint64_t b1, limb_t prec,
  65221. bf_flags_t flags)
  65222. {
  65223. bf_t b;
  65224. int ret;
  65225. bf_init(r->ctx, &b);
  65226. ret = bf_set_ui(&b, b1);
  65227. ret |= bf_mul(r, a, &b, prec, flags);
  65228. bf_delete(&b);
  65229. return ret;
  65230. }
  65231. int bf_mul_si(bf_t *r, const bf_t *a, int64_t b1, limb_t prec,
  65232. bf_flags_t flags)
  65233. {
  65234. bf_t b;
  65235. int ret;
  65236. bf_init(r->ctx, &b);
  65237. ret = bf_set_si(&b, b1);
  65238. ret |= bf_mul(r, a, &b, prec, flags);
  65239. bf_delete(&b);
  65240. return ret;
  65241. }
  65242. int bf_add_si(bf_t *r, const bf_t *a, int64_t b1, limb_t prec,
  65243. bf_flags_t flags)
  65244. {
  65245. bf_t b;
  65246. int ret;
  65247. bf_init(r->ctx, &b);
  65248. ret = bf_set_si(&b, b1);
  65249. ret |= bf_add(r, a, &b, prec, flags);
  65250. bf_delete(&b);
  65251. return ret;
  65252. }
  65253. static int bf_pow_ui(bf_t *r, const bf_t *a, limb_t b, limb_t prec,
  65254. bf_flags_t flags)
  65255. {
  65256. int ret, n_bits, i;
  65257. assert(r != a);
  65258. if (b == 0)
  65259. return bf_set_ui(r, 1);
  65260. ret = bf_set(r, a);
  65261. n_bits = LIMB_BITS - clz(b);
  65262. for(i = n_bits - 2; i >= 0; i--) {
  65263. ret |= bf_mul(r, r, r, prec, flags);
  65264. if ((b >> i) & 1)
  65265. ret |= bf_mul(r, r, a, prec, flags);
  65266. }
  65267. return ret;
  65268. }
  65269. static int bf_pow_ui_ui(bf_t *r, limb_t a1, limb_t b,
  65270. limb_t prec, bf_flags_t flags)
  65271. {
  65272. bf_t a;
  65273. int ret;
  65274. if (a1 == 10 && b <= LIMB_DIGITS) {
  65275. /* use precomputed powers. We do not round at this point
  65276. because we expect the caller to do it */
  65277. ret = bf_set_ui(r, mp_pow_dec[b]);
  65278. } else {
  65279. bf_init(r->ctx, &a);
  65280. ret = bf_set_ui(&a, a1);
  65281. ret |= bf_pow_ui(r, &a, b, prec, flags);
  65282. bf_delete(&a);
  65283. }
  65284. return ret;
  65285. }
  65286. /* convert to integer (infinite precision) */
  65287. int bf_rint(bf_t *r, int rnd_mode)
  65288. {
  65289. return bf_round(r, 0, rnd_mode | BF_FLAG_RADPNT_PREC);
  65290. }
  65291. /* logical operations */
  65292. #define BF_LOGIC_OR 0
  65293. #define BF_LOGIC_XOR 1
  65294. #define BF_LOGIC_AND 2
  65295. static inline limb_t bf_logic_op1(limb_t a, limb_t b, int op)
  65296. {
  65297. switch(op) {
  65298. case BF_LOGIC_OR:
  65299. return a | b;
  65300. case BF_LOGIC_XOR:
  65301. return a ^ b;
  65302. default:
  65303. case BF_LOGIC_AND:
  65304. return a & b;
  65305. }
  65306. }
  65307. static int bf_logic_op(bf_t *r, const bf_t *a1, const bf_t *b1, int op)
  65308. {
  65309. bf_t b1_s, a1_s, *a, *b;
  65310. limb_t a_sign, b_sign, r_sign;
  65311. slimb_t l, i, a_bit_offset, b_bit_offset;
  65312. limb_t v1, v2, v1_mask, v2_mask, r_mask;
  65313. int ret;
  65314. assert(r != a1 && r != b1);
  65315. if (a1->expn <= 0)
  65316. a_sign = 0; /* minus zero is considered as positive */
  65317. else
  65318. a_sign = a1->sign;
  65319. if (b1->expn <= 0)
  65320. b_sign = 0; /* minus zero is considered as positive */
  65321. else
  65322. b_sign = b1->sign;
  65323. if (a_sign) {
  65324. a = &a1_s;
  65325. bf_init(r->ctx, a);
  65326. if (bf_add_si(a, a1, 1, BF_PREC_INF, BF_RNDZ)) {
  65327. b = NULL;
  65328. goto fail;
  65329. }
  65330. } else {
  65331. a = (bf_t *)a1;
  65332. }
  65333. if (b_sign) {
  65334. b = &b1_s;
  65335. bf_init(r->ctx, b);
  65336. if (bf_add_si(b, b1, 1, BF_PREC_INF, BF_RNDZ))
  65337. goto fail;
  65338. } else {
  65339. b = (bf_t *)b1;
  65340. }
  65341. r_sign = bf_logic_op1(a_sign, b_sign, op);
  65342. if (op == BF_LOGIC_AND && r_sign == 0) {
  65343. /* no need to compute extra zeros for and */
  65344. if (a_sign == 0 && b_sign == 0)
  65345. l = bf_min(a->expn, b->expn);
  65346. else if (a_sign == 0)
  65347. l = a->expn;
  65348. else
  65349. l = b->expn;
  65350. } else {
  65351. l = bf_max(a->expn, b->expn);
  65352. }
  65353. /* Note: a or b can be zero */
  65354. l = (bf_max(l, 1) + LIMB_BITS - 1) / LIMB_BITS;
  65355. if (bf_resize(r, l))
  65356. goto fail;
  65357. a_bit_offset = a->len * LIMB_BITS - a->expn;
  65358. b_bit_offset = b->len * LIMB_BITS - b->expn;
  65359. v1_mask = -a_sign;
  65360. v2_mask = -b_sign;
  65361. r_mask = -r_sign;
  65362. for(i = 0; i < l; i++) {
  65363. v1 = get_bits(a->tab, a->len, a_bit_offset + i * LIMB_BITS) ^ v1_mask;
  65364. v2 = get_bits(b->tab, b->len, b_bit_offset + i * LIMB_BITS) ^ v2_mask;
  65365. r->tab[i] = bf_logic_op1(v1, v2, op) ^ r_mask;
  65366. }
  65367. r->expn = l * LIMB_BITS;
  65368. r->sign = r_sign;
  65369. bf_normalize_and_round(r, BF_PREC_INF, BF_RNDZ); /* cannot fail */
  65370. if (r_sign) {
  65371. if (bf_add_si(r, r, -1, BF_PREC_INF, BF_RNDZ))
  65372. goto fail;
  65373. }
  65374. ret = 0;
  65375. done:
  65376. if (a == &a1_s)
  65377. bf_delete(a);
  65378. if (b == &b1_s)
  65379. bf_delete(b);
  65380. return ret;
  65381. fail:
  65382. bf_set_nan(r);
  65383. ret = BF_ST_MEM_ERROR;
  65384. goto done;
  65385. }
  65386. /* 'a' and 'b' must be integers. Return 0 or BF_ST_MEM_ERROR. */
  65387. int bf_logic_or(bf_t *r, const bf_t *a, const bf_t *b)
  65388. {
  65389. return bf_logic_op(r, a, b, BF_LOGIC_OR);
  65390. }
  65391. /* 'a' and 'b' must be integers. Return 0 or BF_ST_MEM_ERROR. */
  65392. int bf_logic_xor(bf_t *r, const bf_t *a, const bf_t *b)
  65393. {
  65394. return bf_logic_op(r, a, b, BF_LOGIC_XOR);
  65395. }
  65396. /* 'a' and 'b' must be integers. Return 0 or BF_ST_MEM_ERROR. */
  65397. int bf_logic_and(bf_t *r, const bf_t *a, const bf_t *b)
  65398. {
  65399. return bf_logic_op(r, a, b, BF_LOGIC_AND);
  65400. }
  65401. /* conversion between fixed size types */
  65402. typedef union {
  65403. double d;
  65404. uint64_t u;
  65405. } Float64Union;
  65406. int bf_get_float64(const bf_t *a, double *pres, bf_rnd_t rnd_mode)
  65407. {
  65408. Float64Union u;
  65409. int e, ret;
  65410. uint64_t m;
  65411. ret = 0;
  65412. if (a->expn == BF_EXP_NAN) {
  65413. u.u = 0x7ff8000000000000; /* quiet nan */
  65414. } else {
  65415. bf_t b_s, *b = &b_s;
  65416. bf_init(a->ctx, b);
  65417. bf_set(b, a);
  65418. if (bf_is_finite(b)) {
  65419. ret = bf_round(b, 53, rnd_mode | BF_FLAG_SUBNORMAL | bf_set_exp_bits(11));
  65420. }
  65421. if (b->expn == BF_EXP_INF) {
  65422. e = (1 << 11) - 1;
  65423. m = 0;
  65424. } else if (b->expn == BF_EXP_ZERO) {
  65425. e = 0;
  65426. m = 0;
  65427. } else {
  65428. e = b->expn + 1023 - 1;
  65429. #if LIMB_BITS == 32
  65430. if (b->len == 2) {
  65431. m = ((uint64_t)b->tab[1] << 32) | b->tab[0];
  65432. } else {
  65433. m = ((uint64_t)b->tab[0] << 32);
  65434. }
  65435. #else
  65436. m = b->tab[0];
  65437. #endif
  65438. if (e <= 0) {
  65439. /* subnormal */
  65440. m = m >> (12 - e);
  65441. e = 0;
  65442. } else {
  65443. m = (m << 1) >> 12;
  65444. }
  65445. }
  65446. u.u = m | ((uint64_t)e << 52) | ((uint64_t)b->sign << 63);
  65447. bf_delete(b);
  65448. }
  65449. *pres = u.d;
  65450. return ret;
  65451. }
  65452. int bf_set_float64(bf_t *a, double d)
  65453. {
  65454. Float64Union u;
  65455. uint64_t m;
  65456. int shift, e, sgn;
  65457. u.d = d;
  65458. sgn = u.u >> 63;
  65459. e = (u.u >> 52) & ((1 << 11) - 1);
  65460. m = u.u & (((uint64_t)1 << 52) - 1);
  65461. if (e == ((1 << 11) - 1)) {
  65462. if (m != 0) {
  65463. bf_set_nan(a);
  65464. } else {
  65465. bf_set_inf(a, sgn);
  65466. }
  65467. } else if (e == 0) {
  65468. if (m == 0) {
  65469. bf_set_zero(a, sgn);
  65470. } else {
  65471. /* subnormal number */
  65472. m <<= 12;
  65473. shift = clz64(m);
  65474. m <<= shift;
  65475. e = -shift;
  65476. goto norm;
  65477. }
  65478. } else {
  65479. m = (m << 11) | ((uint64_t)1 << 63);
  65480. norm:
  65481. a->expn = e - 1023 + 1;
  65482. #if LIMB_BITS == 32
  65483. if (bf_resize(a, 2))
  65484. goto fail;
  65485. a->tab[0] = m;
  65486. a->tab[1] = m >> 32;
  65487. #else
  65488. if (bf_resize(a, 1))
  65489. goto fail;
  65490. a->tab[0] = m;
  65491. #endif
  65492. a->sign = sgn;
  65493. }
  65494. return 0;
  65495. fail:
  65496. bf_set_nan(a);
  65497. return BF_ST_MEM_ERROR;
  65498. }
  65499. /* The rounding mode is always BF_RNDZ. Return BF_ST_INVALID_OP if there
  65500. is an overflow and 0 otherwise. */
  65501. int bf_get_int32(int *pres, const bf_t *a, int flags)
  65502. {
  65503. uint32_t v;
  65504. int ret;
  65505. if (a->expn >= BF_EXP_INF) {
  65506. ret = BF_ST_INVALID_OP;
  65507. if (flags & BF_GET_INT_MOD) {
  65508. v = 0;
  65509. } else if (a->expn == BF_EXP_INF) {
  65510. v = (uint32_t)INT32_MAX + a->sign;
  65511. } else {
  65512. v = INT32_MAX;
  65513. }
  65514. } else if (a->expn <= 0) {
  65515. v = 0;
  65516. ret = 0;
  65517. } else if (a->expn <= 31) {
  65518. v = a->tab[a->len - 1] >> (LIMB_BITS - a->expn);
  65519. if (a->sign)
  65520. v = -v;
  65521. ret = 0;
  65522. } else if (!(flags & BF_GET_INT_MOD)) {
  65523. ret = BF_ST_INVALID_OP;
  65524. if (a->sign) {
  65525. v = (uint32_t)INT32_MAX + 1;
  65526. if (a->expn == 32 &&
  65527. (a->tab[a->len - 1] >> (LIMB_BITS - 32)) == v) {
  65528. ret = 0;
  65529. }
  65530. } else {
  65531. v = INT32_MAX;
  65532. }
  65533. } else {
  65534. v = get_bits(a->tab, a->len, a->len * LIMB_BITS - a->expn);
  65535. if (a->sign)
  65536. v = -v;
  65537. ret = 0;
  65538. }
  65539. *pres = v;
  65540. return ret;
  65541. }
  65542. /* The rounding mode is always BF_RNDZ. Return BF_ST_INVALID_OP if there
  65543. is an overflow and 0 otherwise. */
  65544. int bf_get_int64(int64_t *pres, const bf_t *a, int flags)
  65545. {
  65546. uint64_t v;
  65547. int ret;
  65548. if (a->expn >= BF_EXP_INF) {
  65549. ret = BF_ST_INVALID_OP;
  65550. if (flags & BF_GET_INT_MOD) {
  65551. v = 0;
  65552. } else if (a->expn == BF_EXP_INF) {
  65553. v = (uint64_t)INT64_MAX + a->sign;
  65554. } else {
  65555. v = INT64_MAX;
  65556. }
  65557. } else if (a->expn <= 0) {
  65558. v = 0;
  65559. ret = 0;
  65560. } else if (a->expn <= 63) {
  65561. #if LIMB_BITS == 32
  65562. if (a->expn <= 32)
  65563. v = a->tab[a->len - 1] >> (LIMB_BITS - a->expn);
  65564. else
  65565. v = (((uint64_t)a->tab[a->len - 1] << 32) |
  65566. get_limbz(a, a->len - 2)) >> (64 - a->expn);
  65567. #else
  65568. v = a->tab[a->len - 1] >> (LIMB_BITS - a->expn);
  65569. #endif
  65570. if (a->sign)
  65571. v = -v;
  65572. ret = 0;
  65573. } else if (!(flags & BF_GET_INT_MOD)) {
  65574. ret = BF_ST_INVALID_OP;
  65575. if (a->sign) {
  65576. uint64_t v1;
  65577. v = (uint64_t)INT64_MAX + 1;
  65578. if (a->expn == 64) {
  65579. v1 = a->tab[a->len - 1];
  65580. #if LIMB_BITS == 32
  65581. v1 = (v1 << 32) | get_limbz(a, a->len - 2);
  65582. #endif
  65583. if (v1 == v)
  65584. ret = 0;
  65585. }
  65586. } else {
  65587. v = INT64_MAX;
  65588. }
  65589. } else {
  65590. slimb_t bit_pos = a->len * LIMB_BITS - a->expn;
  65591. v = get_bits(a->tab, a->len, bit_pos);
  65592. #if LIMB_BITS == 32
  65593. v |= (uint64_t)get_bits(a->tab, a->len, bit_pos + 32) << 32;
  65594. #endif
  65595. if (a->sign)
  65596. v = -v;
  65597. ret = 0;
  65598. }
  65599. *pres = v;
  65600. return ret;
  65601. }
  65602. /* The rounding mode is always BF_RNDZ. Return BF_ST_INVALID_OP if there
  65603. is an overflow and 0 otherwise. */
  65604. int bf_get_uint64(uint64_t *pres, const bf_t *a)
  65605. {
  65606. uint64_t v;
  65607. int ret;
  65608. if (a->expn == BF_EXP_NAN) {
  65609. goto overflow;
  65610. } else if (a->expn <= 0) {
  65611. v = 0;
  65612. ret = 0;
  65613. } else if (a->sign) {
  65614. v = 0;
  65615. ret = BF_ST_INVALID_OP;
  65616. } else if (a->expn <= 64) {
  65617. #if LIMB_BITS == 32
  65618. if (a->expn <= 32)
  65619. v = a->tab[a->len - 1] >> (LIMB_BITS - a->expn);
  65620. else
  65621. v = (((uint64_t)a->tab[a->len - 1] << 32) |
  65622. get_limbz(a, a->len - 2)) >> (64 - a->expn);
  65623. #else
  65624. v = a->tab[a->len - 1] >> (LIMB_BITS - a->expn);
  65625. #endif
  65626. ret = 0;
  65627. } else {
  65628. overflow:
  65629. v = UINT64_MAX;
  65630. ret = BF_ST_INVALID_OP;
  65631. }
  65632. *pres = v;
  65633. return ret;
  65634. }
  65635. /* base conversion from radix */
  65636. static const uint8_t digits_per_limb_table[BF_RADIX_MAX - 1] = {
  65637. #if LIMB_BITS == 32
  65638. 32,20,16,13,12,11,10,10, 9, 9, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  65639. #else
  65640. 64,40,32,27,24,22,21,20,19,18,17,17,16,16,16,15,15,15,14,14,14,14,13,13,13,13,13,13,13,12,12,12,12,12,12,
  65641. #endif
  65642. };
  65643. static limb_t get_limb_radix(int radix)
  65644. {
  65645. int i, k;
  65646. limb_t radixl;
  65647. k = digits_per_limb_table[radix - 2];
  65648. radixl = radix;
  65649. for(i = 1; i < k; i++)
  65650. radixl *= radix;
  65651. return radixl;
  65652. }
  65653. /* return != 0 if error */
  65654. static int bf_integer_from_radix_rec(bf_t *r, const limb_t *tab,
  65655. limb_t n, int level, limb_t n0,
  65656. limb_t radix, bf_t *pow_tab)
  65657. {
  65658. int ret;
  65659. if (n == 1) {
  65660. ret = bf_set_ui(r, tab[0]);
  65661. } else {
  65662. bf_t T_s, *T = &T_s, *B;
  65663. limb_t n1, n2;
  65664. n2 = (((n0 * 2) >> (level + 1)) + 1) / 2;
  65665. n1 = n - n2;
  65666. // printf("level=%d n0=%ld n1=%ld n2=%ld\n", level, n0, n1, n2);
  65667. B = &pow_tab[level];
  65668. if (B->len == 0) {
  65669. ret = bf_pow_ui_ui(B, radix, n2, BF_PREC_INF, BF_RNDZ);
  65670. if (ret)
  65671. return ret;
  65672. }
  65673. ret = bf_integer_from_radix_rec(r, tab + n2, n1, level + 1, n0,
  65674. radix, pow_tab);
  65675. if (ret)
  65676. return ret;
  65677. ret = bf_mul(r, r, B, BF_PREC_INF, BF_RNDZ);
  65678. if (ret)
  65679. return ret;
  65680. bf_init(r->ctx, T);
  65681. ret = bf_integer_from_radix_rec(T, tab, n2, level + 1, n0,
  65682. radix, pow_tab);
  65683. if (!ret)
  65684. ret = bf_add(r, r, T, BF_PREC_INF, BF_RNDZ);
  65685. bf_delete(T);
  65686. }
  65687. return ret;
  65688. // bf_print_str(" r=", r);
  65689. }
  65690. /* return 0 if OK != 0 if memory error */
  65691. static int bf_integer_from_radix(bf_t *r, const limb_t *tab,
  65692. limb_t n, limb_t radix)
  65693. {
  65694. bf_context_t *s = r->ctx;
  65695. int pow_tab_len, i, ret;
  65696. limb_t radixl;
  65697. bf_t *pow_tab;
  65698. radixl = get_limb_radix(radix);
  65699. pow_tab_len = ceil_log2(n) + 2; /* XXX: check */
  65700. pow_tab = bf_malloc(s, sizeof(pow_tab[0]) * pow_tab_len);
  65701. if (!pow_tab)
  65702. return -1;
  65703. for(i = 0; i < pow_tab_len; i++)
  65704. bf_init(r->ctx, &pow_tab[i]);
  65705. ret = bf_integer_from_radix_rec(r, tab, n, 0, n, radixl, pow_tab);
  65706. for(i = 0; i < pow_tab_len; i++) {
  65707. bf_delete(&pow_tab[i]);
  65708. }
  65709. bf_free(s, pow_tab);
  65710. return ret;
  65711. }
  65712. /* compute and round T * radix^expn. */
  65713. int bf_mul_pow_radix(bf_t *r, const bf_t *T, limb_t radix,
  65714. slimb_t expn, limb_t prec, bf_flags_t flags)
  65715. {
  65716. int ret, expn_sign, overflow;
  65717. slimb_t e, extra_bits, prec1, ziv_extra_bits;
  65718. bf_t B_s, *B = &B_s;
  65719. if (T->len == 0) {
  65720. return bf_set(r, T);
  65721. } else if (expn == 0) {
  65722. ret = bf_set(r, T);
  65723. ret |= bf_round(r, prec, flags);
  65724. return ret;
  65725. }
  65726. e = expn;
  65727. expn_sign = 0;
  65728. if (e < 0) {
  65729. e = -e;
  65730. expn_sign = 1;
  65731. }
  65732. bf_init(r->ctx, B);
  65733. if (prec == BF_PREC_INF) {
  65734. /* infinite precision: only used if the result is known to be exact */
  65735. ret = bf_pow_ui_ui(B, radix, e, BF_PREC_INF, BF_RNDN);
  65736. if (expn_sign) {
  65737. ret |= bf_div(r, T, B, T->len * LIMB_BITS, BF_RNDN);
  65738. } else {
  65739. ret |= bf_mul(r, T, B, BF_PREC_INF, BF_RNDN);
  65740. }
  65741. } else {
  65742. ziv_extra_bits = 16;
  65743. for(;;) {
  65744. prec1 = prec + ziv_extra_bits;
  65745. /* XXX: correct overflow/underflow handling */
  65746. /* XXX: rigorous error analysis needed */
  65747. extra_bits = ceil_log2(e) * 2 + 1;
  65748. ret = bf_pow_ui_ui(B, radix, e, prec1 + extra_bits, BF_RNDN | BF_FLAG_EXT_EXP);
  65749. overflow = !bf_is_finite(B);
  65750. /* XXX: if bf_pow_ui_ui returns an exact result, can stop
  65751. after the next operation */
  65752. if (expn_sign)
  65753. ret |= bf_div(r, T, B, prec1 + extra_bits, BF_RNDN | BF_FLAG_EXT_EXP);
  65754. else
  65755. ret |= bf_mul(r, T, B, prec1 + extra_bits, BF_RNDN | BF_FLAG_EXT_EXP);
  65756. if (ret & BF_ST_MEM_ERROR)
  65757. break;
  65758. if ((ret & BF_ST_INEXACT) &&
  65759. !bf_can_round(r, prec, flags & BF_RND_MASK, prec1) &&
  65760. !overflow) {
  65761. /* and more precision and retry */
  65762. ziv_extra_bits = ziv_extra_bits + (ziv_extra_bits / 2);
  65763. } else {
  65764. /* XXX: need to use __bf_round() to pass the inexact
  65765. flag for the subnormal case */
  65766. ret = bf_round(r, prec, flags) | (ret & BF_ST_INEXACT);
  65767. break;
  65768. }
  65769. }
  65770. }
  65771. bf_delete(B);
  65772. return ret;
  65773. }
  65774. static inline int bf_to_digit(int c)
  65775. {
  65776. if (c >= '0' && c <= '9')
  65777. return c - '0';
  65778. else if (c >= 'A' && c <= 'Z')
  65779. return c - 'A' + 10;
  65780. else if (c >= 'a' && c <= 'z')
  65781. return c - 'a' + 10;
  65782. else
  65783. return 36;
  65784. }
  65785. /* add a limb at 'pos' and decrement pos. new space is created if
  65786. needed. Return 0 if OK, -1 if memory error */
  65787. static int bf_add_limb(bf_t *a, slimb_t *ppos, limb_t v)
  65788. {
  65789. slimb_t pos;
  65790. pos = *ppos;
  65791. if (unlikely(pos < 0)) {
  65792. limb_t new_size, d, *new_tab;
  65793. new_size = bf_max(a->len + 1, a->len * 3 / 2);
  65794. new_tab = bf_realloc(a->ctx, a->tab, sizeof(limb_t) * new_size);
  65795. if (!new_tab)
  65796. return -1;
  65797. a->tab = new_tab;
  65798. d = new_size - a->len;
  65799. memmove(a->tab + d, a->tab, a->len * sizeof(limb_t));
  65800. a->len = new_size;
  65801. pos += d;
  65802. }
  65803. a->tab[pos--] = v;
  65804. *ppos = pos;
  65805. return 0;
  65806. }
  65807. static int bf_tolower(int c)
  65808. {
  65809. if (c >= 'A' && c <= 'Z')
  65810. c = c - 'A' + 'a';
  65811. return c;
  65812. }
  65813. static int strcasestart(const char *str, const char *val, const char **ptr)
  65814. {
  65815. const char *p, *q;
  65816. p = str;
  65817. q = val;
  65818. while (*q != '\0') {
  65819. if (bf_tolower(*p) != *q)
  65820. return 0;
  65821. p++;
  65822. q++;
  65823. }
  65824. if (ptr)
  65825. *ptr = p;
  65826. return 1;
  65827. }
  65828. static int bf_atof_internal(bf_t *r, slimb_t *pexponent,
  65829. const char *str, const char **pnext, int radix,
  65830. limb_t prec, bf_flags_t flags, bool is_dec)
  65831. {
  65832. const char *p, *p_start;
  65833. int is_neg, radix_bits, exp_is_neg, ret, digits_per_limb, shift;
  65834. limb_t cur_limb;
  65835. slimb_t pos, expn, int_len, digit_count;
  65836. bool has_decpt, is_bin_exp;
  65837. bf_t a_s, *a;
  65838. *pexponent = 0;
  65839. p = str;
  65840. if (!(flags & BF_ATOF_NO_NAN_INF) && radix <= 16 &&
  65841. strcasestart(p, "nan", &p)) {
  65842. bf_set_nan(r);
  65843. ret = 0;
  65844. goto done;
  65845. }
  65846. is_neg = 0;
  65847. if (p[0] == '+') {
  65848. p++;
  65849. p_start = p;
  65850. } else if (p[0] == '-') {
  65851. is_neg = 1;
  65852. p++;
  65853. p_start = p;
  65854. } else {
  65855. p_start = p;
  65856. }
  65857. if (p[0] == '0') {
  65858. if ((p[1] == 'x' || p[1] == 'X') &&
  65859. (radix == 0 || radix == 16) &&
  65860. !(flags & BF_ATOF_NO_HEX)) {
  65861. radix = 16;
  65862. p += 2;
  65863. } else if ((p[1] == 'o' || p[1] == 'O') &&
  65864. radix == 0 && (flags & BF_ATOF_BIN_OCT)) {
  65865. p += 2;
  65866. radix = 8;
  65867. } else if ((p[1] == 'b' || p[1] == 'B') &&
  65868. radix == 0 && (flags & BF_ATOF_BIN_OCT)) {
  65869. p += 2;
  65870. radix = 2;
  65871. } else {
  65872. goto no_prefix;
  65873. }
  65874. /* there must be a digit after the prefix */
  65875. if (bf_to_digit((uint8_t)*p) >= radix) {
  65876. bf_set_nan(r);
  65877. ret = 0;
  65878. goto done;
  65879. }
  65880. no_prefix: ;
  65881. } else {
  65882. if (!(flags & BF_ATOF_NO_NAN_INF) && radix <= 16 &&
  65883. strcasestart(p, "inf", &p)) {
  65884. bf_set_inf(r, is_neg);
  65885. ret = 0;
  65886. goto done;
  65887. }
  65888. }
  65889. if (radix == 0)
  65890. radix = 10;
  65891. if (is_dec) {
  65892. assert(radix == 10);
  65893. radix_bits = 0;
  65894. a = r;
  65895. } else if ((radix & (radix - 1)) != 0) {
  65896. radix_bits = 0; /* base is not a power of two */
  65897. a = &a_s;
  65898. bf_init(r->ctx, a);
  65899. } else {
  65900. radix_bits = ceil_log2(radix);
  65901. a = r;
  65902. }
  65903. /* skip leading zeros */
  65904. /* XXX: could also skip zeros after the decimal point */
  65905. while (*p == '0')
  65906. p++;
  65907. if (radix_bits) {
  65908. shift = digits_per_limb = LIMB_BITS;
  65909. } else {
  65910. radix_bits = 0;
  65911. shift = digits_per_limb = digits_per_limb_table[radix - 2];
  65912. }
  65913. cur_limb = 0;
  65914. bf_resize(a, 1);
  65915. pos = 0;
  65916. has_decpt = false;
  65917. int_len = digit_count = 0;
  65918. for(;;) {
  65919. limb_t c;
  65920. if (*p == '.' && (p > p_start || bf_to_digit(p[1]) < radix)) {
  65921. if (has_decpt)
  65922. break;
  65923. has_decpt = true;
  65924. int_len = digit_count;
  65925. p++;
  65926. }
  65927. c = bf_to_digit(*p);
  65928. if (c >= radix)
  65929. break;
  65930. digit_count++;
  65931. p++;
  65932. if (radix_bits) {
  65933. shift -= radix_bits;
  65934. if (shift <= 0) {
  65935. cur_limb |= c >> (-shift);
  65936. if (bf_add_limb(a, &pos, cur_limb))
  65937. goto mem_error;
  65938. if (shift < 0)
  65939. cur_limb = c << (LIMB_BITS + shift);
  65940. else
  65941. cur_limb = 0;
  65942. shift += LIMB_BITS;
  65943. } else {
  65944. cur_limb |= c << shift;
  65945. }
  65946. } else {
  65947. cur_limb = cur_limb * radix + c;
  65948. shift--;
  65949. if (shift == 0) {
  65950. if (bf_add_limb(a, &pos, cur_limb))
  65951. goto mem_error;
  65952. shift = digits_per_limb;
  65953. cur_limb = 0;
  65954. }
  65955. }
  65956. }
  65957. if (!has_decpt)
  65958. int_len = digit_count;
  65959. /* add the last limb and pad with zeros */
  65960. if (shift != digits_per_limb) {
  65961. if (radix_bits == 0) {
  65962. while (shift != 0) {
  65963. cur_limb *= radix;
  65964. shift--;
  65965. }
  65966. }
  65967. if (bf_add_limb(a, &pos, cur_limb)) {
  65968. mem_error:
  65969. ret = BF_ST_MEM_ERROR;
  65970. if (!radix_bits)
  65971. bf_delete(a);
  65972. bf_set_nan(r);
  65973. goto done;
  65974. }
  65975. }
  65976. /* reset the next limbs to zero (we prefer to reallocate in the
  65977. renormalization) */
  65978. memset(a->tab, 0, (pos + 1) * sizeof(limb_t));
  65979. if (p == p_start) {
  65980. ret = 0;
  65981. if (!radix_bits)
  65982. bf_delete(a);
  65983. bf_set_nan(r);
  65984. goto done;
  65985. }
  65986. /* parse the exponent, if any */
  65987. expn = 0;
  65988. is_bin_exp = false;
  65989. if (((radix == 10 && (*p == 'e' || *p == 'E')) ||
  65990. (radix != 10 && (*p == '@' ||
  65991. (radix_bits && (*p == 'p' || *p == 'P'))))) &&
  65992. p > p_start) {
  65993. is_bin_exp = (*p == 'p' || *p == 'P');
  65994. p++;
  65995. exp_is_neg = 0;
  65996. if (*p == '+') {
  65997. p++;
  65998. } else if (*p == '-') {
  65999. exp_is_neg = 1;
  66000. p++;
  66001. }
  66002. for(;;) {
  66003. int c;
  66004. c = bf_to_digit(*p);
  66005. if (c >= 10)
  66006. break;
  66007. if (unlikely(expn > ((BF_RAW_EXP_MAX - 2 - 9) / 10))) {
  66008. /* exponent overflow */
  66009. if (exp_is_neg) {
  66010. bf_set_zero(r, is_neg);
  66011. ret = BF_ST_UNDERFLOW | BF_ST_INEXACT;
  66012. } else {
  66013. bf_set_inf(r, is_neg);
  66014. ret = BF_ST_OVERFLOW | BF_ST_INEXACT;
  66015. }
  66016. goto done;
  66017. }
  66018. p++;
  66019. expn = expn * 10 + c;
  66020. }
  66021. if (exp_is_neg)
  66022. expn = -expn;
  66023. }
  66024. if (is_dec) {
  66025. a->expn = expn + int_len;
  66026. a->sign = is_neg;
  66027. ret = bfdec_normalize_and_round((bfdec_t *)a, prec, flags);
  66028. } else if (radix_bits) {
  66029. /* XXX: may overflow */
  66030. if (!is_bin_exp)
  66031. expn *= radix_bits;
  66032. a->expn = expn + (int_len * radix_bits);
  66033. a->sign = is_neg;
  66034. ret = bf_normalize_and_round(a, prec, flags);
  66035. } else {
  66036. limb_t l;
  66037. pos++;
  66038. l = a->len - pos; /* number of limbs */
  66039. if (l == 0) {
  66040. bf_set_zero(r, is_neg);
  66041. ret = 0;
  66042. } else {
  66043. bf_t T_s, *T = &T_s;
  66044. expn -= l * digits_per_limb - int_len;
  66045. bf_init(r->ctx, T);
  66046. if (bf_integer_from_radix(T, a->tab + pos, l, radix)) {
  66047. bf_set_nan(r);
  66048. ret = BF_ST_MEM_ERROR;
  66049. } else {
  66050. T->sign = is_neg;
  66051. if (flags & BF_ATOF_EXPONENT) {
  66052. /* return the exponent */
  66053. *pexponent = expn;
  66054. ret = bf_set(r, T);
  66055. } else {
  66056. ret = bf_mul_pow_radix(r, T, radix, expn, prec, flags);
  66057. }
  66058. }
  66059. bf_delete(T);
  66060. }
  66061. bf_delete(a);
  66062. }
  66063. done:
  66064. if (pnext)
  66065. *pnext = p;
  66066. return ret;
  66067. }
  66068. /*
  66069. Return (status, n, exp). 'status' is the floating point status. 'n'
  66070. is the parsed number.
  66071. If (flags & BF_ATOF_EXPONENT) and if the radix is not a power of
  66072. two, the parsed number is equal to r *
  66073. (*pexponent)^radix. Otherwise *pexponent = 0.
  66074. */
  66075. int bf_atof2(bf_t *r, slimb_t *pexponent,
  66076. const char *str, const char **pnext, int radix,
  66077. limb_t prec, bf_flags_t flags)
  66078. {
  66079. return bf_atof_internal(r, pexponent, str, pnext, radix, prec, flags,
  66080. false);
  66081. }
  66082. int bf_atof(bf_t *r, const char *str, const char **pnext, int radix,
  66083. limb_t prec, bf_flags_t flags)
  66084. {
  66085. slimb_t dummy_exp;
  66086. return bf_atof_internal(r, &dummy_exp, str, pnext, radix, prec, flags, false);
  66087. }
  66088. /* base conversion to radix */
  66089. #if LIMB_BITS == 64
  66090. #define RADIXL_10 UINT64_C(10000000000000000000)
  66091. #else
  66092. #define RADIXL_10 UINT64_C(1000000000)
  66093. #endif
  66094. static const uint32_t inv_log2_radix[BF_RADIX_MAX - 1][LIMB_BITS / 32 + 1] = {
  66095. #if LIMB_BITS == 32
  66096. { 0x80000000, 0x00000000,},
  66097. { 0x50c24e60, 0xd4d4f4a7,},
  66098. { 0x40000000, 0x00000000,},
  66099. { 0x372068d2, 0x0a1ee5ca,},
  66100. { 0x3184648d, 0xb8153e7a,},
  66101. { 0x2d983275, 0x9d5369c4,},
  66102. { 0x2aaaaaaa, 0xaaaaaaab,},
  66103. { 0x28612730, 0x6a6a7a54,},
  66104. { 0x268826a1, 0x3ef3fde6,},
  66105. { 0x25001383, 0xbac8a744,},
  66106. { 0x23b46706, 0x82c0c709,},
  66107. { 0x229729f1, 0xb2c83ded,},
  66108. { 0x219e7ffd, 0xa5ad572b,},
  66109. { 0x20c33b88, 0xda7c29ab,},
  66110. { 0x20000000, 0x00000000,},
  66111. { 0x1f50b57e, 0xac5884b3,},
  66112. { 0x1eb22cc6, 0x8aa6e26f,},
  66113. { 0x1e21e118, 0x0c5daab2,},
  66114. { 0x1d9dcd21, 0x439834e4,},
  66115. { 0x1d244c78, 0x367a0d65,},
  66116. { 0x1cb40589, 0xac173e0c,},
  66117. { 0x1c4bd95b, 0xa8d72b0d,},
  66118. { 0x1bead768, 0x98f8ce4c,},
  66119. { 0x1b903469, 0x050f72e5,},
  66120. { 0x1b3b433f, 0x2eb06f15,},
  66121. { 0x1aeb6f75, 0x9c46fc38,},
  66122. { 0x1aa038eb, 0x0e3bfd17,},
  66123. { 0x1a593062, 0xb38d8c56,},
  66124. { 0x1a15f4c3, 0x2b95a2e6,},
  66125. { 0x19d630dc, 0xcc7ddef9,},
  66126. { 0x19999999, 0x9999999a,},
  66127. { 0x195fec80, 0x8a609431,},
  66128. { 0x1928ee7b, 0x0b4f22f9,},
  66129. { 0x18f46acf, 0x8c06e318,},
  66130. { 0x18c23246, 0xdc0a9f3d,},
  66131. #else
  66132. { 0x80000000, 0x00000000, 0x00000000,},
  66133. { 0x50c24e60, 0xd4d4f4a7, 0x021f57bc,},
  66134. { 0x40000000, 0x00000000, 0x00000000,},
  66135. { 0x372068d2, 0x0a1ee5ca, 0x19ea911b,},
  66136. { 0x3184648d, 0xb8153e7a, 0x7fc2d2e1,},
  66137. { 0x2d983275, 0x9d5369c4, 0x4dec1661,},
  66138. { 0x2aaaaaaa, 0xaaaaaaaa, 0xaaaaaaab,},
  66139. { 0x28612730, 0x6a6a7a53, 0x810fabde,},
  66140. { 0x268826a1, 0x3ef3fde6, 0x23e2566b,},
  66141. { 0x25001383, 0xbac8a744, 0x385a3349,},
  66142. { 0x23b46706, 0x82c0c709, 0x3f891718,},
  66143. { 0x229729f1, 0xb2c83ded, 0x15fba800,},
  66144. { 0x219e7ffd, 0xa5ad572a, 0xe169744b,},
  66145. { 0x20c33b88, 0xda7c29aa, 0x9bddee52,},
  66146. { 0x20000000, 0x00000000, 0x00000000,},
  66147. { 0x1f50b57e, 0xac5884b3, 0x70e28eee,},
  66148. { 0x1eb22cc6, 0x8aa6e26f, 0x06d1a2a2,},
  66149. { 0x1e21e118, 0x0c5daab1, 0x81b4f4bf,},
  66150. { 0x1d9dcd21, 0x439834e3, 0x81667575,},
  66151. { 0x1d244c78, 0x367a0d64, 0xc8204d6d,},
  66152. { 0x1cb40589, 0xac173e0c, 0x3b7b16ba,},
  66153. { 0x1c4bd95b, 0xa8d72b0d, 0x5879f25a,},
  66154. { 0x1bead768, 0x98f8ce4c, 0x66cc2858,},
  66155. { 0x1b903469, 0x050f72e5, 0x0cf5488e,},
  66156. { 0x1b3b433f, 0x2eb06f14, 0x8c89719c,},
  66157. { 0x1aeb6f75, 0x9c46fc37, 0xab5fc7e9,},
  66158. { 0x1aa038eb, 0x0e3bfd17, 0x1bd62080,},
  66159. { 0x1a593062, 0xb38d8c56, 0x7998ab45,},
  66160. { 0x1a15f4c3, 0x2b95a2e6, 0x46aed6a0,},
  66161. { 0x19d630dc, 0xcc7ddef9, 0x5aadd61b,},
  66162. { 0x19999999, 0x99999999, 0x9999999a,},
  66163. { 0x195fec80, 0x8a609430, 0xe1106014,},
  66164. { 0x1928ee7b, 0x0b4f22f9, 0x5f69791d,},
  66165. { 0x18f46acf, 0x8c06e318, 0x4d2aeb2c,},
  66166. { 0x18c23246, 0xdc0a9f3d, 0x3fe16970,},
  66167. #endif
  66168. };
  66169. static const limb_t log2_radix[BF_RADIX_MAX - 1] = {
  66170. #if LIMB_BITS == 32
  66171. 0x20000000,
  66172. 0x32b80347,
  66173. 0x40000000,
  66174. 0x4a4d3c26,
  66175. 0x52b80347,
  66176. 0x59d5d9fd,
  66177. 0x60000000,
  66178. 0x6570068e,
  66179. 0x6a4d3c26,
  66180. 0x6eb3a9f0,
  66181. 0x72b80347,
  66182. 0x766a008e,
  66183. 0x79d5d9fd,
  66184. 0x7d053f6d,
  66185. 0x80000000,
  66186. 0x82cc7edf,
  66187. 0x8570068e,
  66188. 0x87ef05ae,
  66189. 0x8a4d3c26,
  66190. 0x8c8ddd45,
  66191. 0x8eb3a9f0,
  66192. 0x90c10501,
  66193. 0x92b80347,
  66194. 0x949a784c,
  66195. 0x966a008e,
  66196. 0x982809d6,
  66197. 0x99d5d9fd,
  66198. 0x9b74948f,
  66199. 0x9d053f6d,
  66200. 0x9e88c6b3,
  66201. 0xa0000000,
  66202. 0xa16bad37,
  66203. 0xa2cc7edf,
  66204. 0xa4231623,
  66205. 0xa570068e,
  66206. #else
  66207. 0x2000000000000000,
  66208. 0x32b803473f7ad0f4,
  66209. 0x4000000000000000,
  66210. 0x4a4d3c25e68dc57f,
  66211. 0x52b803473f7ad0f4,
  66212. 0x59d5d9fd5010b366,
  66213. 0x6000000000000000,
  66214. 0x6570068e7ef5a1e8,
  66215. 0x6a4d3c25e68dc57f,
  66216. 0x6eb3a9f01975077f,
  66217. 0x72b803473f7ad0f4,
  66218. 0x766a008e4788cbcd,
  66219. 0x79d5d9fd5010b366,
  66220. 0x7d053f6d26089673,
  66221. 0x8000000000000000,
  66222. 0x82cc7edf592262d0,
  66223. 0x8570068e7ef5a1e8,
  66224. 0x87ef05ae409a0289,
  66225. 0x8a4d3c25e68dc57f,
  66226. 0x8c8ddd448f8b845a,
  66227. 0x8eb3a9f01975077f,
  66228. 0x90c10500d63aa659,
  66229. 0x92b803473f7ad0f4,
  66230. 0x949a784bcd1b8afe,
  66231. 0x966a008e4788cbcd,
  66232. 0x982809d5be7072dc,
  66233. 0x99d5d9fd5010b366,
  66234. 0x9b74948f5532da4b,
  66235. 0x9d053f6d26089673,
  66236. 0x9e88c6b3626a72aa,
  66237. 0xa000000000000000,
  66238. 0xa16bad3758efd873,
  66239. 0xa2cc7edf592262d0,
  66240. 0xa4231623369e78e6,
  66241. 0xa570068e7ef5a1e8,
  66242. #endif
  66243. };
  66244. /* compute floor(a*b) or ceil(a*b) with b = log2(radix) or
  66245. b=1/log2(radix). For is_inv = 0, strict accuracy is not guaranteed
  66246. when radix is not a power of two. */
  66247. slimb_t bf_mul_log2_radix(slimb_t a1, unsigned int radix, int is_inv,
  66248. int is_ceil1)
  66249. {
  66250. int is_neg;
  66251. limb_t a;
  66252. bool is_ceil;
  66253. is_ceil = is_ceil1;
  66254. a = a1;
  66255. if (a1 < 0) {
  66256. a = -a;
  66257. is_neg = 1;
  66258. } else {
  66259. is_neg = 0;
  66260. }
  66261. is_ceil ^= is_neg;
  66262. if ((radix & (radix - 1)) == 0) {
  66263. int radix_bits;
  66264. /* radix is a power of two */
  66265. radix_bits = ceil_log2(radix);
  66266. if (is_inv) {
  66267. if (is_ceil)
  66268. a += radix_bits - 1;
  66269. a = a / radix_bits;
  66270. } else {
  66271. a = a * radix_bits;
  66272. }
  66273. } else {
  66274. const uint32_t *tab;
  66275. limb_t b0, b1;
  66276. dlimb_t t;
  66277. if (is_inv) {
  66278. tab = inv_log2_radix[radix - 2];
  66279. #if LIMB_BITS == 32
  66280. b1 = tab[0];
  66281. b0 = tab[1];
  66282. #else
  66283. b1 = ((limb_t)tab[0] << 32) | tab[1];
  66284. b0 = (limb_t)tab[2] << 32;
  66285. #endif
  66286. t = (dlimb_t)b0 * (dlimb_t)a;
  66287. t = (dlimb_t)b1 * (dlimb_t)a + (t >> LIMB_BITS);
  66288. a = t >> (LIMB_BITS - 1);
  66289. } else {
  66290. b0 = log2_radix[radix - 2];
  66291. t = (dlimb_t)b0 * (dlimb_t)a;
  66292. a = t >> (LIMB_BITS - 3);
  66293. }
  66294. /* a = floor(result) and 'result' cannot be an integer */
  66295. a += is_ceil;
  66296. }
  66297. if (is_neg)
  66298. a = -a;
  66299. return a;
  66300. }
  66301. /* 'n' is the number of output limbs */
  66302. static int bf_integer_to_radix_rec(bf_t *pow_tab,
  66303. limb_t *out, const bf_t *a, limb_t n,
  66304. int level, limb_t n0, limb_t radixl,
  66305. unsigned int radixl_bits)
  66306. {
  66307. limb_t n1, n2, q_prec;
  66308. int ret;
  66309. assert(n >= 1);
  66310. if (n == 1) {
  66311. out[0] = get_bits(a->tab, a->len, a->len * LIMB_BITS - a->expn);
  66312. } else if (n == 2) {
  66313. dlimb_t t;
  66314. slimb_t pos;
  66315. pos = a->len * LIMB_BITS - a->expn;
  66316. t = ((dlimb_t)get_bits(a->tab, a->len, pos + LIMB_BITS) << LIMB_BITS) |
  66317. get_bits(a->tab, a->len, pos);
  66318. if (likely(radixl == RADIXL_10)) {
  66319. /* use division by a constant when possible */
  66320. out[0] = t % RADIXL_10;
  66321. out[1] = t / RADIXL_10;
  66322. } else {
  66323. out[0] = t % radixl;
  66324. out[1] = t / radixl;
  66325. }
  66326. } else {
  66327. bf_t Q, R, *B, *B_inv;
  66328. int q_add;
  66329. bf_init(a->ctx, &Q);
  66330. bf_init(a->ctx, &R);
  66331. n2 = (((n0 * 2) >> (level + 1)) + 1) / 2;
  66332. n1 = n - n2;
  66333. B = &pow_tab[2 * level];
  66334. B_inv = &pow_tab[2 * level + 1];
  66335. ret = 0;
  66336. if (B->len == 0) {
  66337. /* compute BASE^n2 */
  66338. ret |= bf_pow_ui_ui(B, radixl, n2, BF_PREC_INF, BF_RNDZ);
  66339. /* we use enough bits for the maximum possible 'n1' value,
  66340. i.e. n2 + 1 */
  66341. ret |= bf_set_ui(&R, 1);
  66342. ret |= bf_div(B_inv, &R, B, (n2 + 1) * radixl_bits + 2, BF_RNDN);
  66343. }
  66344. // printf("%d: n1=% " PRId64 " n2=%" PRId64 "\n", level, n1, n2);
  66345. q_prec = n1 * radixl_bits;
  66346. ret |= bf_mul(&Q, a, B_inv, q_prec, BF_RNDN);
  66347. ret |= bf_rint(&Q, BF_RNDZ);
  66348. ret |= bf_mul(&R, &Q, B, BF_PREC_INF, BF_RNDZ);
  66349. ret |= bf_sub(&R, a, &R, BF_PREC_INF, BF_RNDZ);
  66350. if (ret & BF_ST_MEM_ERROR)
  66351. goto fail;
  66352. /* adjust if necessary */
  66353. q_add = 0;
  66354. while (R.sign && R.len != 0) {
  66355. if (bf_add(&R, &R, B, BF_PREC_INF, BF_RNDZ))
  66356. goto fail;
  66357. q_add--;
  66358. }
  66359. while (bf_cmpu(&R, B) >= 0) {
  66360. if (bf_sub(&R, &R, B, BF_PREC_INF, BF_RNDZ))
  66361. goto fail;
  66362. q_add++;
  66363. }
  66364. if (q_add != 0) {
  66365. if (bf_add_si(&Q, &Q, q_add, BF_PREC_INF, BF_RNDZ))
  66366. goto fail;
  66367. }
  66368. if (bf_integer_to_radix_rec(pow_tab, out + n2, &Q, n1, level + 1, n0,
  66369. radixl, radixl_bits))
  66370. goto fail;
  66371. if (bf_integer_to_radix_rec(pow_tab, out, &R, n2, level + 1, n0,
  66372. radixl, radixl_bits)) {
  66373. fail:
  66374. bf_delete(&Q);
  66375. bf_delete(&R);
  66376. return -1;
  66377. }
  66378. bf_delete(&Q);
  66379. bf_delete(&R);
  66380. }
  66381. return 0;
  66382. }
  66383. /* return 0 if OK != 0 if memory error */
  66384. static int bf_integer_to_radix(bf_t *r, const bf_t *a, limb_t radixl)
  66385. {
  66386. bf_context_t *s = r->ctx;
  66387. limb_t r_len;
  66388. bf_t *pow_tab;
  66389. int i, pow_tab_len, ret;
  66390. r_len = r->len;
  66391. pow_tab_len = (ceil_log2(r_len) + 2) * 2; /* XXX: check */
  66392. pow_tab = bf_malloc(s, sizeof(pow_tab[0]) * pow_tab_len);
  66393. if (!pow_tab)
  66394. return -1;
  66395. for(i = 0; i < pow_tab_len; i++)
  66396. bf_init(r->ctx, &pow_tab[i]);
  66397. ret = bf_integer_to_radix_rec(pow_tab, r->tab, a, r_len, 0, r_len, radixl,
  66398. ceil_log2(radixl));
  66399. for(i = 0; i < pow_tab_len; i++) {
  66400. bf_delete(&pow_tab[i]);
  66401. }
  66402. bf_free(s, pow_tab);
  66403. return ret;
  66404. }
  66405. /* a must be >= 0. 'P' is the wanted number of digits in radix
  66406. 'radix'. 'r' is the mantissa represented as an integer. *pE
  66407. contains the exponent. Return != 0 if memory error. */
  66408. static int bf_convert_to_radix(bf_t *r, slimb_t *pE,
  66409. const bf_t *a, int radix,
  66410. limb_t P, bf_rnd_t rnd_mode,
  66411. bool is_fixed_exponent)
  66412. {
  66413. slimb_t E, e, prec, extra_bits, ziv_extra_bits, prec0;
  66414. bf_t B_s, *B = &B_s;
  66415. int e_sign, ret, res;
  66416. if (a->len == 0) {
  66417. /* zero case */
  66418. *pE = 0;
  66419. return bf_set(r, a);
  66420. }
  66421. if (is_fixed_exponent) {
  66422. E = *pE;
  66423. } else {
  66424. /* compute the new exponent */
  66425. E = 1 + bf_mul_log2_radix(a->expn - 1, radix, true, false);
  66426. }
  66427. // bf_print_str("a", a);
  66428. // printf("E=%ld P=%ld radix=%d\n", E, P, radix);
  66429. for(;;) {
  66430. e = P - E;
  66431. e_sign = 0;
  66432. if (e < 0) {
  66433. e = -e;
  66434. e_sign = 1;
  66435. }
  66436. /* Note: precision for log2(radix) is not critical here */
  66437. prec0 = bf_mul_log2_radix(P, radix, false, true);
  66438. ziv_extra_bits = 16;
  66439. for(;;) {
  66440. prec = prec0 + ziv_extra_bits;
  66441. /* XXX: rigorous error analysis needed */
  66442. extra_bits = ceil_log2(e) * 2 + 1;
  66443. ret = bf_pow_ui_ui(r, radix, e, prec + extra_bits,
  66444. BF_RNDN | BF_FLAG_EXT_EXP);
  66445. if (!e_sign)
  66446. ret |= bf_mul(r, r, a, prec + extra_bits,
  66447. BF_RNDN | BF_FLAG_EXT_EXP);
  66448. else
  66449. ret |= bf_div(r, a, r, prec + extra_bits,
  66450. BF_RNDN | BF_FLAG_EXT_EXP);
  66451. if (ret & BF_ST_MEM_ERROR)
  66452. return BF_ST_MEM_ERROR;
  66453. /* if the result is not exact, check that it can be safely
  66454. rounded to an integer */
  66455. if ((ret & BF_ST_INEXACT) &&
  66456. !bf_can_round(r, r->expn, rnd_mode, prec)) {
  66457. /* and more precision and retry */
  66458. ziv_extra_bits = ziv_extra_bits + (ziv_extra_bits / 2);
  66459. continue;
  66460. } else {
  66461. ret = bf_rint(r, rnd_mode);
  66462. if (ret & BF_ST_MEM_ERROR)
  66463. return BF_ST_MEM_ERROR;
  66464. break;
  66465. }
  66466. }
  66467. if (is_fixed_exponent)
  66468. break;
  66469. /* check that the result is < B^P */
  66470. /* XXX: do a fast approximate test first ? */
  66471. bf_init(r->ctx, B);
  66472. ret = bf_pow_ui_ui(B, radix, P, BF_PREC_INF, BF_RNDZ);
  66473. if (ret) {
  66474. bf_delete(B);
  66475. return ret;
  66476. }
  66477. res = bf_cmpu(r, B);
  66478. bf_delete(B);
  66479. if (res < 0)
  66480. break;
  66481. /* try a larger exponent */
  66482. E++;
  66483. }
  66484. *pE = E;
  66485. return 0;
  66486. }
  66487. static void limb_to_a(char *buf, limb_t n, unsigned int radix, int len)
  66488. {
  66489. int digit, i;
  66490. if (radix == 10) {
  66491. /* specific case with constant divisor */
  66492. for(i = len - 1; i >= 0; i--) {
  66493. digit = (limb_t)n % 10;
  66494. n = (limb_t)n / 10;
  66495. buf[i] = digit + '0';
  66496. }
  66497. } else {
  66498. for(i = len - 1; i >= 0; i--) {
  66499. digit = (limb_t)n % radix;
  66500. n = (limb_t)n / radix;
  66501. if (digit < 10)
  66502. digit += '0';
  66503. else
  66504. digit += 'a' - 10;
  66505. buf[i] = digit;
  66506. }
  66507. }
  66508. }
  66509. /* for power of 2 radixes */
  66510. static void limb_to_a2(char *buf, limb_t n, unsigned int radix_bits, int len)
  66511. {
  66512. int digit, i;
  66513. unsigned int mask;
  66514. mask = (1 << radix_bits) - 1;
  66515. for(i = len - 1; i >= 0; i--) {
  66516. digit = n & mask;
  66517. n >>= radix_bits;
  66518. if (digit < 10)
  66519. digit += '0';
  66520. else
  66521. digit += 'a' - 10;
  66522. buf[i] = digit;
  66523. }
  66524. }
  66525. /* 'a' must be an integer if the is_dec = false or if the radix is not
  66526. a power of two. A dot is added before the 'dot_pos' digit. dot_pos
  66527. = n_digits does not display the dot. 0 <= dot_pos <=
  66528. n_digits. n_digits >= 1. */
  66529. static void output_digits(DynBuf *s, const bf_t *a1, int radix, limb_t n_digits,
  66530. limb_t dot_pos, bool is_dec)
  66531. {
  66532. limb_t i, v, l;
  66533. slimb_t pos, pos_incr;
  66534. int digits_per_limb, buf_pos, radix_bits, first_buf_pos;
  66535. char buf[65];
  66536. bf_t a_s, *a;
  66537. if (is_dec) {
  66538. digits_per_limb = LIMB_DIGITS;
  66539. a = (bf_t *)a1;
  66540. radix_bits = 0;
  66541. pos = a->len;
  66542. pos_incr = 1;
  66543. first_buf_pos = 0;
  66544. } else if ((radix & (radix - 1)) == 0) {
  66545. a = (bf_t *)a1;
  66546. radix_bits = ceil_log2(radix);
  66547. digits_per_limb = LIMB_BITS / radix_bits;
  66548. pos_incr = digits_per_limb * radix_bits;
  66549. /* digits are aligned relative to the radix point */
  66550. pos = a->len * LIMB_BITS + smod(-a->expn, radix_bits);
  66551. first_buf_pos = 0;
  66552. } else {
  66553. limb_t n, radixl;
  66554. digits_per_limb = digits_per_limb_table[radix - 2];
  66555. radixl = get_limb_radix(radix);
  66556. a = &a_s;
  66557. bf_init(a1->ctx, a);
  66558. n = (n_digits + digits_per_limb - 1) / digits_per_limb;
  66559. if (bf_resize(a, n)) {
  66560. dbuf_set_error(s);
  66561. goto done;
  66562. }
  66563. if (bf_integer_to_radix(a, a1, radixl)) {
  66564. dbuf_set_error(s);
  66565. goto done;
  66566. }
  66567. radix_bits = 0;
  66568. pos = n;
  66569. pos_incr = 1;
  66570. first_buf_pos = pos * digits_per_limb - n_digits;
  66571. }
  66572. buf_pos = digits_per_limb;
  66573. i = 0;
  66574. while (i < n_digits) {
  66575. if (buf_pos == digits_per_limb) {
  66576. pos -= pos_incr;
  66577. if (radix_bits == 0) {
  66578. v = get_limbz(a, pos);
  66579. limb_to_a(buf, v, radix, digits_per_limb);
  66580. } else {
  66581. v = get_bits(a->tab, a->len, pos);
  66582. limb_to_a2(buf, v, radix_bits, digits_per_limb);
  66583. }
  66584. buf_pos = first_buf_pos;
  66585. first_buf_pos = 0;
  66586. }
  66587. if (i < dot_pos) {
  66588. l = dot_pos;
  66589. } else {
  66590. if (i == dot_pos)
  66591. dbuf_putc(s, '.');
  66592. l = n_digits;
  66593. }
  66594. l = bf_min(digits_per_limb - buf_pos, l - i);
  66595. dbuf_put(s, (uint8_t *)(buf + buf_pos), l);
  66596. buf_pos += l;
  66597. i += l;
  66598. }
  66599. done:
  66600. if (a != a1)
  66601. bf_delete(a);
  66602. }
  66603. static void *bf_dbuf_realloc(void *opaque, void *ptr, size_t size)
  66604. {
  66605. bf_context_t *s = opaque;
  66606. return bf_realloc(s, ptr, size);
  66607. }
  66608. /* return the length in bytes. A trailing '\0' is added */
  66609. static char *bf_ftoa_internal(size_t *plen, const bf_t *a2, int radix,
  66610. limb_t prec, bf_flags_t flags, bool is_dec)
  66611. {
  66612. bf_context_t *ctx = a2->ctx;
  66613. DynBuf s_s, *s = &s_s;
  66614. int radix_bits;
  66615. // bf_print_str("ftoa", a2);
  66616. // printf("radix=%d\n", radix);
  66617. dbuf_init2(s, ctx, bf_dbuf_realloc);
  66618. if (a2->expn == BF_EXP_NAN) {
  66619. dbuf_putstr(s, "NaN");
  66620. } else {
  66621. if (a2->sign)
  66622. dbuf_putc(s, '-');
  66623. if (a2->expn == BF_EXP_INF) {
  66624. if (flags & BF_FTOA_JS_QUIRKS)
  66625. dbuf_putstr(s, "Infinity");
  66626. else
  66627. dbuf_putstr(s, "Inf");
  66628. } else {
  66629. int fmt, ret;
  66630. slimb_t n_digits, n, i, n_max, n1;
  66631. bf_t a1_s, *a1 = &a1_s;
  66632. if ((radix & (radix - 1)) != 0)
  66633. radix_bits = 0;
  66634. else
  66635. radix_bits = ceil_log2(radix);
  66636. fmt = flags & BF_FTOA_FORMAT_MASK;
  66637. bf_init(ctx, a1);
  66638. if (fmt == BF_FTOA_FORMAT_FRAC) {
  66639. if (is_dec || radix_bits != 0) {
  66640. if (bf_set(a1, a2))
  66641. goto fail1;
  66642. #ifdef USE_BF_DEC
  66643. if (is_dec) {
  66644. if (bfdec_round((bfdec_t *)a1, prec, (flags & BF_RND_MASK) | BF_FLAG_RADPNT_PREC) & BF_ST_MEM_ERROR)
  66645. goto fail1;
  66646. n = a1->expn;
  66647. } else
  66648. #endif
  66649. {
  66650. if (bf_round(a1, prec * radix_bits, (flags & BF_RND_MASK) | BF_FLAG_RADPNT_PREC) & BF_ST_MEM_ERROR)
  66651. goto fail1;
  66652. n = ceil_div(a1->expn, radix_bits);
  66653. }
  66654. if (flags & BF_FTOA_ADD_PREFIX) {
  66655. if (radix == 16)
  66656. dbuf_putstr(s, "0x");
  66657. else if (radix == 8)
  66658. dbuf_putstr(s, "0o");
  66659. else if (radix == 2)
  66660. dbuf_putstr(s, "0b");
  66661. }
  66662. if (a1->expn == BF_EXP_ZERO) {
  66663. dbuf_putstr(s, "0");
  66664. if (prec > 0) {
  66665. dbuf_putstr(s, ".");
  66666. for(i = 0; i < prec; i++) {
  66667. dbuf_putc(s, '0');
  66668. }
  66669. }
  66670. } else {
  66671. n_digits = prec + n;
  66672. if (n <= 0) {
  66673. /* 0.x */
  66674. dbuf_putstr(s, "0.");
  66675. for(i = 0; i < -n; i++) {
  66676. dbuf_putc(s, '0');
  66677. }
  66678. if (n_digits > 0) {
  66679. output_digits(s, a1, radix, n_digits, n_digits, is_dec);
  66680. }
  66681. } else {
  66682. output_digits(s, a1, radix, n_digits, n, is_dec);
  66683. }
  66684. }
  66685. } else {
  66686. size_t pos, start;
  66687. bf_t a_s, *a = &a_s;
  66688. /* make a positive number */
  66689. a->tab = a2->tab;
  66690. a->len = a2->len;
  66691. a->expn = a2->expn;
  66692. a->sign = 0;
  66693. /* one more digit for the rounding */
  66694. n = 1 + bf_mul_log2_radix(bf_max(a->expn, 0), radix, true, true);
  66695. n_digits = n + prec;
  66696. n1 = n;
  66697. if (bf_convert_to_radix(a1, &n1, a, radix, n_digits,
  66698. flags & BF_RND_MASK, true))
  66699. goto fail1;
  66700. start = s->size;
  66701. output_digits(s, a1, radix, n_digits, n, is_dec);
  66702. /* remove leading zeros because we allocated one more digit */
  66703. pos = start;
  66704. while ((pos + 1) < s->size && s->buf[pos] == '0' &&
  66705. s->buf[pos + 1] != '.')
  66706. pos++;
  66707. if (pos > start) {
  66708. memmove(s->buf + start, s->buf + pos, s->size - pos);
  66709. s->size -= (pos - start);
  66710. }
  66711. }
  66712. } else {
  66713. #ifdef USE_BF_DEC
  66714. if (is_dec) {
  66715. if (bf_set(a1, a2))
  66716. goto fail1;
  66717. if (fmt == BF_FTOA_FORMAT_FIXED) {
  66718. n_digits = prec;
  66719. n_max = n_digits;
  66720. if (bfdec_round((bfdec_t *)a1, prec, (flags & BF_RND_MASK)) & BF_ST_MEM_ERROR)
  66721. goto fail1;
  66722. } else {
  66723. /* prec is ignored */
  66724. prec = n_digits = a1->len * LIMB_DIGITS;
  66725. /* remove the trailing zero digits */
  66726. while (n_digits > 1 &&
  66727. get_digit(a1->tab, a1->len, prec - n_digits) == 0) {
  66728. n_digits--;
  66729. }
  66730. n_max = n_digits + 4;
  66731. }
  66732. n = a1->expn;
  66733. } else
  66734. #endif
  66735. if (radix_bits != 0) {
  66736. if (bf_set(a1, a2))
  66737. goto fail1;
  66738. if (fmt == BF_FTOA_FORMAT_FIXED) {
  66739. slimb_t prec_bits;
  66740. n_digits = prec;
  66741. n_max = n_digits;
  66742. /* align to the radix point */
  66743. prec_bits = prec * radix_bits -
  66744. smod(-a1->expn, radix_bits);
  66745. if (bf_round(a1, prec_bits,
  66746. (flags & BF_RND_MASK)) & BF_ST_MEM_ERROR)
  66747. goto fail1;
  66748. } else {
  66749. limb_t digit_mask;
  66750. slimb_t pos;
  66751. /* position of the digit before the most
  66752. significant digit in bits */
  66753. pos = a1->len * LIMB_BITS +
  66754. smod(-a1->expn, radix_bits);
  66755. n_digits = ceil_div(pos, radix_bits);
  66756. /* remove the trailing zero digits */
  66757. digit_mask = ((limb_t)1 << radix_bits) - 1;
  66758. while (n_digits > 1 &&
  66759. (get_bits(a1->tab, a1->len, pos - n_digits * radix_bits) & digit_mask) == 0) {
  66760. n_digits--;
  66761. }
  66762. n_max = n_digits + 4;
  66763. }
  66764. n = ceil_div(a1->expn, radix_bits);
  66765. } else {
  66766. bf_t a_s, *a = &a_s;
  66767. /* make a positive number */
  66768. a->tab = a2->tab;
  66769. a->len = a2->len;
  66770. a->expn = a2->expn;
  66771. a->sign = 0;
  66772. if (fmt == BF_FTOA_FORMAT_FIXED) {
  66773. n_digits = prec;
  66774. n_max = n_digits;
  66775. } else {
  66776. slimb_t n_digits_max, n_digits_min;
  66777. assert(prec != BF_PREC_INF);
  66778. n_digits = 1 + bf_mul_log2_radix(prec, radix, true, true);
  66779. /* max number of digits for non exponential
  66780. notation. The rational is to have the same rule
  66781. as JS i.e. n_max = 21 for 64 bit float in base 10. */
  66782. n_max = n_digits + 4;
  66783. if (fmt == BF_FTOA_FORMAT_FREE_MIN) {
  66784. bf_t b_s, *b = &b_s;
  66785. /* find the minimum number of digits by
  66786. dichotomy. */
  66787. /* XXX: inefficient */
  66788. n_digits_max = n_digits;
  66789. n_digits_min = 1;
  66790. bf_init(ctx, b);
  66791. while (n_digits_min < n_digits_max) {
  66792. n_digits = (n_digits_min + n_digits_max) / 2;
  66793. if (bf_convert_to_radix(a1, &n, a, radix, n_digits,
  66794. flags & BF_RND_MASK, false)) {
  66795. bf_delete(b);
  66796. goto fail1;
  66797. }
  66798. /* convert back to a number and compare */
  66799. ret = bf_mul_pow_radix(b, a1, radix, n - n_digits,
  66800. prec,
  66801. (flags & ~BF_RND_MASK) |
  66802. BF_RNDN);
  66803. if (ret & BF_ST_MEM_ERROR) {
  66804. bf_delete(b);
  66805. goto fail1;
  66806. }
  66807. if (bf_cmpu(b, a) == 0) {
  66808. n_digits_max = n_digits;
  66809. } else {
  66810. n_digits_min = n_digits + 1;
  66811. }
  66812. }
  66813. bf_delete(b);
  66814. n_digits = n_digits_max;
  66815. }
  66816. }
  66817. if (bf_convert_to_radix(a1, &n, a, radix, n_digits,
  66818. flags & BF_RND_MASK, false)) {
  66819. fail1:
  66820. bf_delete(a1);
  66821. goto fail;
  66822. }
  66823. }
  66824. if (a1->expn == BF_EXP_ZERO &&
  66825. fmt != BF_FTOA_FORMAT_FIXED &&
  66826. !(flags & BF_FTOA_FORCE_EXP)) {
  66827. /* just output zero */
  66828. dbuf_putstr(s, "0");
  66829. } else {
  66830. if (flags & BF_FTOA_ADD_PREFIX) {
  66831. if (radix == 16)
  66832. dbuf_putstr(s, "0x");
  66833. else if (radix == 8)
  66834. dbuf_putstr(s, "0o");
  66835. else if (radix == 2)
  66836. dbuf_putstr(s, "0b");
  66837. }
  66838. if (a1->expn == BF_EXP_ZERO)
  66839. n = 1;
  66840. if ((flags & BF_FTOA_FORCE_EXP) ||
  66841. n <= -6 || n > n_max) {
  66842. /* exponential notation */
  66843. output_digits(s, a1, radix, n_digits, 1, is_dec);
  66844. if (radix_bits != 0 && radix <= 16) {
  66845. slimb_t exp_n = (n - 1) * radix_bits;
  66846. if (flags & BF_FTOA_JS_QUIRKS)
  66847. dbuf_printf(s, "p%+" PRId_LIMB, exp_n);
  66848. else
  66849. dbuf_printf(s, "p%" PRId_LIMB, exp_n);
  66850. } else {
  66851. const char c = radix <= 10 ? 'e' : '@';
  66852. if (flags & BF_FTOA_JS_QUIRKS)
  66853. dbuf_printf(s, "%c%+" PRId_LIMB, c, n - 1);
  66854. else
  66855. dbuf_printf(s, "%c%" PRId_LIMB, c, n - 1);
  66856. }
  66857. } else if (n <= 0) {
  66858. /* 0.x */
  66859. dbuf_putstr(s, "0.");
  66860. for(i = 0; i < -n; i++) {
  66861. dbuf_putc(s, '0');
  66862. }
  66863. output_digits(s, a1, radix, n_digits, n_digits, is_dec);
  66864. } else {
  66865. if (n_digits <= n) {
  66866. /* no dot */
  66867. output_digits(s, a1, radix, n_digits, n_digits, is_dec);
  66868. for(i = 0; i < (n - n_digits); i++)
  66869. dbuf_putc(s, '0');
  66870. } else {
  66871. output_digits(s, a1, radix, n_digits, n, is_dec);
  66872. }
  66873. }
  66874. }
  66875. }
  66876. bf_delete(a1);
  66877. }
  66878. }
  66879. dbuf_putc(s, '\0');
  66880. if (dbuf_error(s))
  66881. goto fail;
  66882. if (plen)
  66883. *plen = s->size - 1;
  66884. return (char *)s->buf;
  66885. fail:
  66886. bf_free(ctx, s->buf);
  66887. if (plen)
  66888. *plen = 0;
  66889. return NULL;
  66890. }
  66891. char *bf_ftoa(size_t *plen, const bf_t *a, int radix, limb_t prec,
  66892. bf_flags_t flags)
  66893. {
  66894. return bf_ftoa_internal(plen, a, radix, prec, flags, false);
  66895. }
  66896. /***************************************************************/
  66897. /* transcendental functions */
  66898. /* Note: the algorithm is from MPFR */
  66899. static void bf_const_log2_rec(bf_t *T, bf_t *P, bf_t *Q, limb_t n1,
  66900. limb_t n2, bool need_P)
  66901. {
  66902. bf_context_t *s = T->ctx;
  66903. if ((n2 - n1) == 1) {
  66904. if (n1 == 0) {
  66905. bf_set_ui(P, 3);
  66906. } else {
  66907. bf_set_ui(P, n1);
  66908. P->sign = 1;
  66909. }
  66910. bf_set_ui(Q, 2 * n1 + 1);
  66911. Q->expn += 2;
  66912. bf_set(T, P);
  66913. } else {
  66914. limb_t m;
  66915. bf_t T1_s, *T1 = &T1_s;
  66916. bf_t P1_s, *P1 = &P1_s;
  66917. bf_t Q1_s, *Q1 = &Q1_s;
  66918. m = n1 + ((n2 - n1) >> 1);
  66919. bf_const_log2_rec(T, P, Q, n1, m, true);
  66920. bf_init(s, T1);
  66921. bf_init(s, P1);
  66922. bf_init(s, Q1);
  66923. bf_const_log2_rec(T1, P1, Q1, m, n2, need_P);
  66924. bf_mul(T, T, Q1, BF_PREC_INF, BF_RNDZ);
  66925. bf_mul(T1, T1, P, BF_PREC_INF, BF_RNDZ);
  66926. bf_add(T, T, T1, BF_PREC_INF, BF_RNDZ);
  66927. if (need_P)
  66928. bf_mul(P, P, P1, BF_PREC_INF, BF_RNDZ);
  66929. bf_mul(Q, Q, Q1, BF_PREC_INF, BF_RNDZ);
  66930. bf_delete(T1);
  66931. bf_delete(P1);
  66932. bf_delete(Q1);
  66933. }
  66934. }
  66935. /* compute log(2) with faithful rounding at precision 'prec' */
  66936. static void bf_const_log2_internal(bf_t *T, limb_t prec)
  66937. {
  66938. limb_t w, N;
  66939. bf_t P_s, *P = &P_s;
  66940. bf_t Q_s, *Q = &Q_s;
  66941. w = prec + 15;
  66942. N = w / 3 + 1;
  66943. bf_init(T->ctx, P);
  66944. bf_init(T->ctx, Q);
  66945. bf_const_log2_rec(T, P, Q, 0, N, false);
  66946. bf_div(T, T, Q, prec, BF_RNDN);
  66947. bf_delete(P);
  66948. bf_delete(Q);
  66949. }
  66950. /* PI constant */
  66951. #define CHUD_A 13591409
  66952. #define CHUD_B 545140134
  66953. #define CHUD_C 640320
  66954. #define CHUD_BITS_PER_TERM 47
  66955. static void chud_bs(bf_t *P, bf_t *Q, bf_t *G, int64_t a, int64_t b, int need_g,
  66956. limb_t prec)
  66957. {
  66958. bf_context_t *s = P->ctx;
  66959. int64_t c;
  66960. if (a == (b - 1)) {
  66961. bf_t T0, T1;
  66962. bf_init(s, &T0);
  66963. bf_init(s, &T1);
  66964. bf_set_ui(G, 2 * b - 1);
  66965. bf_mul_ui(G, G, 6 * b - 1, prec, BF_RNDN);
  66966. bf_mul_ui(G, G, 6 * b - 5, prec, BF_RNDN);
  66967. bf_set_ui(&T0, CHUD_B);
  66968. bf_mul_ui(&T0, &T0, b, prec, BF_RNDN);
  66969. bf_set_ui(&T1, CHUD_A);
  66970. bf_add(&T0, &T0, &T1, prec, BF_RNDN);
  66971. bf_mul(P, G, &T0, prec, BF_RNDN);
  66972. P->sign = b & 1;
  66973. bf_set_ui(Q, b);
  66974. bf_mul_ui(Q, Q, b, prec, BF_RNDN);
  66975. bf_mul_ui(Q, Q, b, prec, BF_RNDN);
  66976. bf_mul_ui(Q, Q, (uint64_t)CHUD_C * CHUD_C * CHUD_C / 24, prec, BF_RNDN);
  66977. bf_delete(&T0);
  66978. bf_delete(&T1);
  66979. } else {
  66980. bf_t P2, Q2, G2;
  66981. bf_init(s, &P2);
  66982. bf_init(s, &Q2);
  66983. bf_init(s, &G2);
  66984. c = (a + b) / 2;
  66985. chud_bs(P, Q, G, a, c, 1, prec);
  66986. chud_bs(&P2, &Q2, &G2, c, b, need_g, prec);
  66987. /* Q = Q1 * Q2 */
  66988. /* G = G1 * G2 */
  66989. /* P = P1 * Q2 + P2 * G1 */
  66990. bf_mul(&P2, &P2, G, prec, BF_RNDN);
  66991. if (!need_g)
  66992. bf_set_ui(G, 0);
  66993. bf_mul(P, P, &Q2, prec, BF_RNDN);
  66994. bf_add(P, P, &P2, prec, BF_RNDN);
  66995. bf_delete(&P2);
  66996. bf_mul(Q, Q, &Q2, prec, BF_RNDN);
  66997. bf_delete(&Q2);
  66998. if (need_g)
  66999. bf_mul(G, G, &G2, prec, BF_RNDN);
  67000. bf_delete(&G2);
  67001. }
  67002. }
  67003. /* compute Pi with faithful rounding at precision 'prec' using the
  67004. Chudnovsky formula */
  67005. static void bf_const_pi_internal(bf_t *Q, limb_t prec)
  67006. {
  67007. bf_context_t *s = Q->ctx;
  67008. int64_t n, prec1;
  67009. bf_t P, G;
  67010. /* number of serie terms */
  67011. n = prec / CHUD_BITS_PER_TERM + 1;
  67012. /* XXX: precision analysis */
  67013. prec1 = prec + 32;
  67014. bf_init(s, &P);
  67015. bf_init(s, &G);
  67016. chud_bs(&P, Q, &G, 0, n, 0, BF_PREC_INF);
  67017. bf_mul_ui(&G, Q, CHUD_A, prec1, BF_RNDN);
  67018. bf_add(&P, &G, &P, prec1, BF_RNDN);
  67019. bf_div(Q, Q, &P, prec1, BF_RNDF);
  67020. bf_set_ui(&P, CHUD_C);
  67021. bf_sqrt(&G, &P, prec1, BF_RNDF);
  67022. bf_mul_ui(&G, &G, (uint64_t)CHUD_C / 12, prec1, BF_RNDF);
  67023. bf_mul(Q, Q, &G, prec, BF_RNDN);
  67024. bf_delete(&P);
  67025. bf_delete(&G);
  67026. }
  67027. static int bf_const_get(bf_t *T, limb_t prec, bf_flags_t flags,
  67028. BFConstCache *c,
  67029. void (*func)(bf_t *res, limb_t prec), int sign)
  67030. {
  67031. limb_t ziv_extra_bits, prec1;
  67032. ziv_extra_bits = 32;
  67033. for(;;) {
  67034. prec1 = prec + ziv_extra_bits;
  67035. if (c->prec < prec1) {
  67036. if (c->val.len == 0)
  67037. bf_init(T->ctx, &c->val);
  67038. func(&c->val, prec1);
  67039. c->prec = prec1;
  67040. } else {
  67041. prec1 = c->prec;
  67042. }
  67043. bf_set(T, &c->val);
  67044. T->sign = sign;
  67045. if (!bf_can_round(T, prec, flags & BF_RND_MASK, prec1)) {
  67046. /* and more precision and retry */
  67047. ziv_extra_bits = ziv_extra_bits + (ziv_extra_bits / 2);
  67048. } else {
  67049. break;
  67050. }
  67051. }
  67052. return bf_round(T, prec, flags);
  67053. }
  67054. static void bf_const_free(BFConstCache *c)
  67055. {
  67056. bf_delete(&c->val);
  67057. memset(c, 0, sizeof(*c));
  67058. }
  67059. int bf_const_log2(bf_t *T, limb_t prec, bf_flags_t flags)
  67060. {
  67061. bf_context_t *s = T->ctx;
  67062. return bf_const_get(T, prec, flags, &s->log2_cache, bf_const_log2_internal, 0);
  67063. }
  67064. /* return rounded pi * (1 - 2 * sign) */
  67065. static int bf_const_pi_signed(bf_t *T, int sign, limb_t prec, bf_flags_t flags)
  67066. {
  67067. bf_context_t *s = T->ctx;
  67068. return bf_const_get(T, prec, flags, &s->pi_cache, bf_const_pi_internal,
  67069. sign);
  67070. }
  67071. int bf_const_pi(bf_t *T, limb_t prec, bf_flags_t flags)
  67072. {
  67073. return bf_const_pi_signed(T, 0, prec, flags);
  67074. }
  67075. void bf_clear_cache(bf_context_t *s)
  67076. {
  67077. #ifdef USE_FFT_MUL
  67078. fft_clear_cache(s);
  67079. #endif
  67080. bf_const_free(&s->log2_cache);
  67081. bf_const_free(&s->pi_cache);
  67082. }
  67083. /* ZivFunc should compute the result 'r' with faithful rounding at
  67084. precision 'prec'. For efficiency purposes, the final bf_round()
  67085. does not need to be done in the function. */
  67086. typedef int ZivFunc(bf_t *r, const bf_t *a, limb_t prec, void *opaque);
  67087. static int bf_ziv_rounding(bf_t *r, const bf_t *a,
  67088. limb_t prec, bf_flags_t flags,
  67089. ZivFunc *f, void *opaque)
  67090. {
  67091. int rnd_mode, ret;
  67092. slimb_t prec1, ziv_extra_bits;
  67093. rnd_mode = flags & BF_RND_MASK;
  67094. if (rnd_mode == BF_RNDF) {
  67095. /* no need to iterate */
  67096. f(r, a, prec, opaque);
  67097. ret = 0;
  67098. } else {
  67099. ziv_extra_bits = 32;
  67100. for(;;) {
  67101. prec1 = prec + ziv_extra_bits;
  67102. ret = f(r, a, prec1, opaque);
  67103. if (ret & (BF_ST_OVERFLOW | BF_ST_UNDERFLOW | BF_ST_MEM_ERROR)) {
  67104. /* overflow or underflow should never happen because
  67105. it indicates the rounding cannot be done correctly,
  67106. but we do not catch all the cases */
  67107. return ret;
  67108. }
  67109. /* if the result is exact, we can stop */
  67110. if (!(ret & BF_ST_INEXACT)) {
  67111. ret = 0;
  67112. break;
  67113. }
  67114. if (bf_can_round(r, prec, rnd_mode, prec1)) {
  67115. ret = BF_ST_INEXACT;
  67116. break;
  67117. }
  67118. ziv_extra_bits = ziv_extra_bits * 2;
  67119. // printf("ziv_extra_bits=%" PRId64 "\n", (int64_t)ziv_extra_bits);
  67120. }
  67121. }
  67122. if (r->len == 0)
  67123. return ret;
  67124. else
  67125. return __bf_round(r, prec, flags, r->len, ret);
  67126. }
  67127. /* add (1 - 2*e_sign) * 2^e */
  67128. static int bf_add_epsilon(bf_t *r, const bf_t *a, slimb_t e, int e_sign,
  67129. limb_t prec, int flags)
  67130. {
  67131. bf_t T_s, *T = &T_s;
  67132. int ret;
  67133. /* small argument case: result = 1 + epsilon * sign(x) */
  67134. bf_init(a->ctx, T);
  67135. bf_set_ui(T, 1);
  67136. T->sign = e_sign;
  67137. T->expn += e;
  67138. ret = bf_add(r, r, T, prec, flags);
  67139. bf_delete(T);
  67140. return ret;
  67141. }
  67142. /* Compute the exponential using faithful rounding at precision 'prec'.
  67143. Note: the algorithm is from MPFR */
  67144. static int bf_exp_internal(bf_t *r, const bf_t *a, limb_t prec, void *opaque)
  67145. {
  67146. bf_context_t *s = r->ctx;
  67147. bf_t T_s, *T = &T_s;
  67148. slimb_t n, K, l, i, prec1;
  67149. assert(r != a);
  67150. /* argument reduction:
  67151. T = a - n*log(2) with 0 <= T < log(2) and n integer.
  67152. */
  67153. bf_init(s, T);
  67154. if (a->expn <= -1) {
  67155. /* 0 <= abs(a) <= 0.5 */
  67156. if (a->sign)
  67157. n = -1;
  67158. else
  67159. n = 0;
  67160. } else {
  67161. bf_const_log2(T, LIMB_BITS, BF_RNDZ);
  67162. bf_div(T, a, T, LIMB_BITS, BF_RNDD);
  67163. bf_get_limb(&n, T, 0);
  67164. }
  67165. K = bf_isqrt((prec + 1) / 2);
  67166. l = (prec - 1) / K + 1;
  67167. /* XXX: precision analysis ? */
  67168. prec1 = prec + (K + 2 * l + 18) + K + 8;
  67169. if (a->expn > 0)
  67170. prec1 += a->expn;
  67171. // printf("n=%ld K=%ld prec1=%ld\n", n, K, prec1);
  67172. bf_const_log2(T, prec1, BF_RNDF);
  67173. bf_mul_si(T, T, n, prec1, BF_RNDN);
  67174. bf_sub(T, a, T, prec1, BF_RNDN);
  67175. /* reduce the range of T */
  67176. bf_mul_2exp(T, -K, BF_PREC_INF, BF_RNDZ);
  67177. /* Taylor expansion around zero :
  67178. 1 + x + x^2/2 + ... + x^n/n!
  67179. = (1 + x * (1 + x/2 * (1 + ... (x/n))))
  67180. */
  67181. {
  67182. bf_t U_s, *U = &U_s;
  67183. bf_init(s, U);
  67184. bf_set_ui(r, 1);
  67185. for(i = l ; i >= 1; i--) {
  67186. bf_set_ui(U, i);
  67187. bf_div(U, T, U, prec1, BF_RNDN);
  67188. bf_mul(r, r, U, prec1, BF_RNDN);
  67189. bf_add_si(r, r, 1, prec1, BF_RNDN);
  67190. }
  67191. bf_delete(U);
  67192. }
  67193. bf_delete(T);
  67194. /* undo the range reduction */
  67195. for(i = 0; i < K; i++) {
  67196. bf_mul(r, r, r, prec1, BF_RNDN | BF_FLAG_EXT_EXP);
  67197. }
  67198. /* undo the argument reduction */
  67199. bf_mul_2exp(r, n, BF_PREC_INF, BF_RNDZ | BF_FLAG_EXT_EXP);
  67200. return BF_ST_INEXACT;
  67201. }
  67202. /* crude overflow and underflow tests for exp(a). a_low <= a <= a_high */
  67203. static int check_exp_underflow_overflow(bf_context_t *s, bf_t *r,
  67204. const bf_t *a_low, const bf_t *a_high,
  67205. limb_t prec, bf_flags_t flags)
  67206. {
  67207. bf_t T_s, *T = &T_s;
  67208. bf_t log2_s, *log2 = &log2_s;
  67209. slimb_t e_min, e_max;
  67210. if (a_high->expn <= 0)
  67211. return 0;
  67212. e_max = (limb_t)1 << (bf_get_exp_bits(flags) - 1);
  67213. e_min = -e_max + 3;
  67214. if (flags & BF_FLAG_SUBNORMAL)
  67215. e_min -= (prec - 1);
  67216. bf_init(s, T);
  67217. bf_init(s, log2);
  67218. bf_const_log2(log2, LIMB_BITS, BF_RNDU);
  67219. bf_mul_ui(T, log2, e_max, LIMB_BITS, BF_RNDU);
  67220. /* a_low > e_max * log(2) implies exp(a) > e_max */
  67221. if (bf_cmp_lt(T, a_low) > 0) {
  67222. /* overflow */
  67223. bf_delete(T);
  67224. bf_delete(log2);
  67225. return bf_set_overflow(r, 0, prec, flags);
  67226. }
  67227. /* a_high < (e_min - 2) * log(2) implies exp(a) < (e_min - 2) */
  67228. bf_const_log2(log2, LIMB_BITS, BF_RNDD);
  67229. bf_mul_si(T, log2, e_min - 2, LIMB_BITS, BF_RNDD);
  67230. if (bf_cmp_lt(a_high, T)) {
  67231. int rnd_mode = flags & BF_RND_MASK;
  67232. /* underflow */
  67233. bf_delete(T);
  67234. bf_delete(log2);
  67235. if (rnd_mode == BF_RNDU) {
  67236. /* set the smallest value */
  67237. bf_set_ui(r, 1);
  67238. r->expn = e_min;
  67239. } else {
  67240. bf_set_zero(r, 0);
  67241. }
  67242. return BF_ST_UNDERFLOW | BF_ST_INEXACT;
  67243. }
  67244. bf_delete(log2);
  67245. bf_delete(T);
  67246. return 0;
  67247. }
  67248. int bf_exp(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags)
  67249. {
  67250. bf_context_t *s = r->ctx;
  67251. int ret;
  67252. assert(r != a);
  67253. if (a->len == 0) {
  67254. if (a->expn == BF_EXP_NAN) {
  67255. bf_set_nan(r);
  67256. } else if (a->expn == BF_EXP_INF) {
  67257. if (a->sign)
  67258. bf_set_zero(r, 0);
  67259. else
  67260. bf_set_inf(r, 0);
  67261. } else {
  67262. bf_set_ui(r, 1);
  67263. }
  67264. return 0;
  67265. }
  67266. ret = check_exp_underflow_overflow(s, r, a, a, prec, flags);
  67267. if (ret)
  67268. return ret;
  67269. if (a->expn < 0 && (-a->expn) >= (prec + 2)) {
  67270. /* small argument case: result = 1 + epsilon * sign(x) */
  67271. bf_set_ui(r, 1);
  67272. return bf_add_epsilon(r, r, -(prec + 2), a->sign, prec, flags);
  67273. }
  67274. return bf_ziv_rounding(r, a, prec, flags, bf_exp_internal, NULL);
  67275. }
  67276. static int bf_log_internal(bf_t *r, const bf_t *a, limb_t prec, void *opaque)
  67277. {
  67278. bf_context_t *s = r->ctx;
  67279. bf_t T_s, *T = &T_s;
  67280. bf_t U_s, *U = &U_s;
  67281. bf_t V_s, *V = &V_s;
  67282. slimb_t n, prec1, l, i, K;
  67283. assert(r != a);
  67284. bf_init(s, T);
  67285. /* argument reduction 1 */
  67286. /* T=a*2^n with 2/3 <= T <= 4/3 */
  67287. {
  67288. bf_t U_s, *U = &U_s;
  67289. bf_set(T, a);
  67290. n = T->expn;
  67291. T->expn = 0;
  67292. /* U= ~ 2/3 */
  67293. bf_init(s, U);
  67294. bf_set_ui(U, 0xaaaaaaaa);
  67295. U->expn = 0;
  67296. if (bf_cmp_lt(T, U)) {
  67297. T->expn++;
  67298. n--;
  67299. }
  67300. bf_delete(U);
  67301. }
  67302. // printf("n=%ld\n", n);
  67303. // bf_print_str("T", T);
  67304. /* XXX: precision analysis */
  67305. /* number of iterations for argument reduction 2 */
  67306. K = bf_isqrt((prec + 1) / 2);
  67307. /* order of Taylor expansion */
  67308. l = prec / (2 * K) + 1;
  67309. /* precision of the intermediate computations */
  67310. prec1 = prec + K + 2 * l + 32;
  67311. bf_init(s, U);
  67312. bf_init(s, V);
  67313. /* Note: cancellation occurs here, so we use more precision (XXX:
  67314. reduce the precision by computing the exact cancellation) */
  67315. bf_add_si(T, T, -1, BF_PREC_INF, BF_RNDN);
  67316. /* argument reduction 2 */
  67317. for(i = 0; i < K; i++) {
  67318. /* T = T / (1 + sqrt(1 + T)) */
  67319. bf_add_si(U, T, 1, prec1, BF_RNDN);
  67320. bf_sqrt(V, U, prec1, BF_RNDF);
  67321. bf_add_si(U, V, 1, prec1, BF_RNDN);
  67322. bf_div(T, T, U, prec1, BF_RNDN);
  67323. }
  67324. {
  67325. bf_t Y_s, *Y = &Y_s;
  67326. bf_t Y2_s, *Y2 = &Y2_s;
  67327. bf_init(s, Y);
  67328. bf_init(s, Y2);
  67329. /* compute ln(1+x) = ln((1+y)/(1-y)) with y=x/(2+x)
  67330. = y + y^3/3 + ... + y^(2*l + 1) / (2*l+1)
  67331. with Y=Y^2
  67332. = y*(1+Y/3+Y^2/5+...) = y*(1+Y*(1/3+Y*(1/5 + ...)))
  67333. */
  67334. bf_add_si(Y, T, 2, prec1, BF_RNDN);
  67335. bf_div(Y, T, Y, prec1, BF_RNDN);
  67336. bf_mul(Y2, Y, Y, prec1, BF_RNDN);
  67337. bf_set_ui(r, 0);
  67338. for(i = l; i >= 1; i--) {
  67339. bf_set_ui(U, 1);
  67340. bf_set_ui(V, 2 * i + 1);
  67341. bf_div(U, U, V, prec1, BF_RNDN);
  67342. bf_add(r, r, U, prec1, BF_RNDN);
  67343. bf_mul(r, r, Y2, prec1, BF_RNDN);
  67344. }
  67345. bf_add_si(r, r, 1, prec1, BF_RNDN);
  67346. bf_mul(r, r, Y, prec1, BF_RNDN);
  67347. bf_delete(Y);
  67348. bf_delete(Y2);
  67349. }
  67350. bf_delete(V);
  67351. bf_delete(U);
  67352. /* multiplication by 2 for the Taylor expansion and undo the
  67353. argument reduction 2*/
  67354. bf_mul_2exp(r, K + 1, BF_PREC_INF, BF_RNDZ);
  67355. /* undo the argument reduction 1 */
  67356. bf_const_log2(T, prec1, BF_RNDF);
  67357. bf_mul_si(T, T, n, prec1, BF_RNDN);
  67358. bf_add(r, r, T, prec1, BF_RNDN);
  67359. bf_delete(T);
  67360. return BF_ST_INEXACT;
  67361. }
  67362. int bf_log(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags)
  67363. {
  67364. bf_context_t *s = r->ctx;
  67365. bf_t T_s, *T = &T_s;
  67366. assert(r != a);
  67367. if (a->len == 0) {
  67368. if (a->expn == BF_EXP_NAN) {
  67369. bf_set_nan(r);
  67370. return 0;
  67371. } else if (a->expn == BF_EXP_INF) {
  67372. if (a->sign) {
  67373. bf_set_nan(r);
  67374. return BF_ST_INVALID_OP;
  67375. } else {
  67376. bf_set_inf(r, 0);
  67377. return 0;
  67378. }
  67379. } else {
  67380. bf_set_inf(r, 1);
  67381. return 0;
  67382. }
  67383. }
  67384. if (a->sign) {
  67385. bf_set_nan(r);
  67386. return BF_ST_INVALID_OP;
  67387. }
  67388. bf_init(s, T);
  67389. bf_set_ui(T, 1);
  67390. if (bf_cmp_eq(a, T)) {
  67391. bf_set_zero(r, 0);
  67392. bf_delete(T);
  67393. return 0;
  67394. }
  67395. bf_delete(T);
  67396. return bf_ziv_rounding(r, a, prec, flags, bf_log_internal, NULL);
  67397. }
  67398. /* x and y finite and x > 0 */
  67399. static int bf_pow_generic(bf_t *r, const bf_t *x, limb_t prec, void *opaque)
  67400. {
  67401. bf_context_t *s = r->ctx;
  67402. const bf_t *y = opaque;
  67403. bf_t T_s, *T = &T_s;
  67404. limb_t prec1;
  67405. bf_init(s, T);
  67406. /* XXX: proof for the added precision */
  67407. prec1 = prec + 32;
  67408. bf_log(T, x, prec1, BF_RNDF | BF_FLAG_EXT_EXP);
  67409. bf_mul(T, T, y, prec1, BF_RNDF | BF_FLAG_EXT_EXP);
  67410. if (bf_is_nan(T))
  67411. bf_set_nan(r);
  67412. else
  67413. bf_exp_internal(r, T, prec1, NULL); /* no overflow/underlow test needed */
  67414. bf_delete(T);
  67415. return BF_ST_INEXACT;
  67416. }
  67417. /* x and y finite, x > 0, y integer and y fits on one limb */
  67418. static int bf_pow_int(bf_t *r, const bf_t *x, limb_t prec, void *opaque)
  67419. {
  67420. bf_context_t *s = r->ctx;
  67421. const bf_t *y = opaque;
  67422. bf_t T_s, *T = &T_s;
  67423. limb_t prec1;
  67424. int ret;
  67425. slimb_t y1;
  67426. bf_get_limb(&y1, y, 0);
  67427. if (y1 < 0)
  67428. y1 = -y1;
  67429. /* XXX: proof for the added precision */
  67430. prec1 = prec + ceil_log2(y1) * 2 + 8;
  67431. ret = bf_pow_ui(r, x, y1 < 0 ? -y1 : y1, prec1, BF_RNDN | BF_FLAG_EXT_EXP);
  67432. if (y->sign) {
  67433. bf_init(s, T);
  67434. bf_set_ui(T, 1);
  67435. ret |= bf_div(r, T, r, prec1, BF_RNDN | BF_FLAG_EXT_EXP);
  67436. bf_delete(T);
  67437. }
  67438. return ret;
  67439. }
  67440. /* x must be a finite non zero float. Return true if there is a
  67441. floating point number r such as x=r^(2^n) and return this floating
  67442. point number 'r'. Otherwise return false and r is undefined. */
  67443. static bool check_exact_power2n(bf_t *r, const bf_t *x, slimb_t n)
  67444. {
  67445. bf_context_t *s = r->ctx;
  67446. bf_t T_s, *T = &T_s;
  67447. slimb_t e, i, er;
  67448. limb_t v;
  67449. /* x = m*2^e with m odd integer */
  67450. e = bf_get_exp_min(x);
  67451. /* fast check on the exponent */
  67452. if (n > (LIMB_BITS - 1)) {
  67453. if (e != 0)
  67454. return false;
  67455. er = 0;
  67456. } else {
  67457. if ((e & (((limb_t)1 << n) - 1)) != 0)
  67458. return false;
  67459. er = e >> n;
  67460. }
  67461. /* every perfect odd square = 1 modulo 8 */
  67462. v = get_bits(x->tab, x->len, x->len * LIMB_BITS - x->expn + e);
  67463. if ((v & 7) != 1)
  67464. return false;
  67465. bf_init(s, T);
  67466. bf_set(T, x);
  67467. T->expn -= e;
  67468. for(i = 0; i < n; i++) {
  67469. if (i != 0)
  67470. bf_set(T, r);
  67471. if (bf_sqrtrem(r, NULL, T) != 0)
  67472. return false;
  67473. }
  67474. r->expn += er;
  67475. return true;
  67476. }
  67477. /* prec = BF_PREC_INF is accepted for x and y integers and y >= 0 */
  67478. int bf_pow(bf_t *r, const bf_t *x, const bf_t *y, limb_t prec, bf_flags_t flags)
  67479. {
  67480. bf_context_t *s = r->ctx;
  67481. bf_t T_s, *T = &T_s;
  67482. bf_t ytmp_s;
  67483. bool y_is_int, y_is_odd;
  67484. int r_sign, ret, rnd_mode;
  67485. slimb_t y_emin;
  67486. if (x->len == 0 || y->len == 0) {
  67487. if (y->expn == BF_EXP_ZERO) {
  67488. /* pow(x, 0) = 1 */
  67489. bf_set_ui(r, 1);
  67490. } else if (x->expn == BF_EXP_NAN) {
  67491. bf_set_nan(r);
  67492. } else {
  67493. int cmp_x_abs_1;
  67494. bf_set_ui(r, 1);
  67495. cmp_x_abs_1 = bf_cmpu(x, r);
  67496. if (cmp_x_abs_1 == 0 && (flags & BF_POW_JS_QUIRKS) &&
  67497. (y->expn >= BF_EXP_INF)) {
  67498. bf_set_nan(r);
  67499. } else if (cmp_x_abs_1 == 0 &&
  67500. (!x->sign || y->expn != BF_EXP_NAN)) {
  67501. /* pow(1, y) = 1 even if y = NaN */
  67502. /* pow(-1, +/-inf) = 1 */
  67503. } else if (y->expn == BF_EXP_NAN) {
  67504. bf_set_nan(r);
  67505. } else if (y->expn == BF_EXP_INF) {
  67506. if (y->sign == (cmp_x_abs_1 > 0)) {
  67507. bf_set_zero(r, 0);
  67508. } else {
  67509. bf_set_inf(r, 0);
  67510. }
  67511. } else {
  67512. y_emin = bf_get_exp_min(y);
  67513. y_is_odd = (y_emin == 0);
  67514. if (y->sign == (x->expn == BF_EXP_ZERO)) {
  67515. bf_set_inf(r, y_is_odd & x->sign);
  67516. if (y->sign) {
  67517. /* pow(0, y) with y < 0 */
  67518. return BF_ST_DIVIDE_ZERO;
  67519. }
  67520. } else {
  67521. bf_set_zero(r, y_is_odd & x->sign);
  67522. }
  67523. }
  67524. }
  67525. return 0;
  67526. }
  67527. bf_init(s, T);
  67528. bf_set(T, x);
  67529. y_emin = bf_get_exp_min(y);
  67530. y_is_int = (y_emin >= 0);
  67531. rnd_mode = flags & BF_RND_MASK;
  67532. if (x->sign) {
  67533. if (!y_is_int) {
  67534. bf_set_nan(r);
  67535. bf_delete(T);
  67536. return BF_ST_INVALID_OP;
  67537. }
  67538. y_is_odd = (y_emin == 0);
  67539. r_sign = y_is_odd;
  67540. /* change the directed rounding mode if the sign of the result
  67541. is changed */
  67542. if (r_sign && (rnd_mode == BF_RNDD || rnd_mode == BF_RNDU))
  67543. flags ^= 1;
  67544. bf_neg(T);
  67545. } else {
  67546. r_sign = 0;
  67547. }
  67548. bf_set_ui(r, 1);
  67549. if (bf_cmp_eq(T, r)) {
  67550. /* abs(x) = 1: nothing more to do */
  67551. ret = 0;
  67552. } else {
  67553. /* check the overflow/underflow cases */
  67554. {
  67555. bf_t al_s, *al = &al_s;
  67556. bf_t ah_s, *ah = &ah_s;
  67557. limb_t precl = LIMB_BITS;
  67558. bf_init(s, al);
  67559. bf_init(s, ah);
  67560. /* compute bounds of log(abs(x)) * y with a low precision */
  67561. /* XXX: compute bf_log() once */
  67562. /* XXX: add a fast test before this slow test */
  67563. bf_log(al, T, precl, BF_RNDD);
  67564. bf_log(ah, T, precl, BF_RNDU);
  67565. bf_mul(al, al, y, precl, BF_RNDD ^ y->sign);
  67566. bf_mul(ah, ah, y, precl, BF_RNDU ^ y->sign);
  67567. ret = check_exp_underflow_overflow(s, r, al, ah, prec, flags);
  67568. bf_delete(al);
  67569. bf_delete(ah);
  67570. if (ret)
  67571. goto done;
  67572. }
  67573. if (y_is_int) {
  67574. slimb_t T_bits, e;
  67575. int_pow:
  67576. T_bits = T->expn - bf_get_exp_min(T);
  67577. if (T_bits == 1) {
  67578. /* pow(2^b, y) = 2^(b*y) */
  67579. bf_mul_si(T, y, T->expn - 1, LIMB_BITS, BF_RNDZ);
  67580. bf_get_limb(&e, T, 0);
  67581. bf_set_ui(r, 1);
  67582. ret = bf_mul_2exp(r, e, prec, flags);
  67583. } else if (prec == BF_PREC_INF) {
  67584. slimb_t y1;
  67585. /* specific case for infinite precision (integer case) */
  67586. bf_get_limb(&y1, y, 0);
  67587. assert(!y->sign);
  67588. /* x must be an integer, so abs(x) >= 2 */
  67589. if (y1 >= ((slimb_t)1 << BF_EXP_BITS_MAX)) {
  67590. bf_delete(T);
  67591. return bf_set_overflow(r, 0, BF_PREC_INF, flags);
  67592. }
  67593. ret = bf_pow_ui(r, T, y1, BF_PREC_INF, BF_RNDZ);
  67594. } else {
  67595. if (y->expn <= 31) {
  67596. /* small enough power: use exponentiation in all cases */
  67597. } else if (y->sign) {
  67598. /* cannot be exact */
  67599. goto general_case;
  67600. } else {
  67601. if (rnd_mode == BF_RNDF)
  67602. goto general_case; /* no need to track exact results */
  67603. /* see if the result has a chance to be exact:
  67604. if x=a*2^b (a odd), x^y=a^y*2^(b*y)
  67605. x^y needs a precision of at least floor_log2(a)*y bits
  67606. */
  67607. bf_mul_si(r, y, T_bits - 1, LIMB_BITS, BF_RNDZ);
  67608. bf_get_limb(&e, r, 0);
  67609. if (prec < e)
  67610. goto general_case;
  67611. }
  67612. ret = bf_ziv_rounding(r, T, prec, flags, bf_pow_int, (void *)y);
  67613. }
  67614. } else {
  67615. if (rnd_mode != BF_RNDF) {
  67616. bf_t *y1;
  67617. if (y_emin < 0 && check_exact_power2n(r, T, -y_emin)) {
  67618. /* the problem is reduced to a power to an integer */
  67619. bf_set(T, r);
  67620. y1 = &ytmp_s;
  67621. y1->tab = y->tab;
  67622. y1->len = y->len;
  67623. y1->sign = y->sign;
  67624. y1->expn = y->expn - y_emin;
  67625. y = y1;
  67626. goto int_pow;
  67627. }
  67628. }
  67629. general_case:
  67630. ret = bf_ziv_rounding(r, T, prec, flags, bf_pow_generic, (void *)y);
  67631. }
  67632. }
  67633. done:
  67634. bf_delete(T);
  67635. r->sign = r_sign;
  67636. return ret;
  67637. }
  67638. /* compute sqrt(-2*x-x^2) to get |sin(x)| from cos(x) - 1. */
  67639. static void bf_sqrt_sin(bf_t *r, const bf_t *x, limb_t prec1)
  67640. {
  67641. bf_context_t *s = r->ctx;
  67642. bf_t T_s, *T = &T_s;
  67643. bf_init(s, T);
  67644. bf_set(T, x);
  67645. bf_mul(r, T, T, prec1, BF_RNDN);
  67646. bf_mul_2exp(T, 1, BF_PREC_INF, BF_RNDZ);
  67647. bf_add(T, T, r, prec1, BF_RNDN);
  67648. bf_neg(T);
  67649. bf_sqrt(r, T, prec1, BF_RNDF);
  67650. bf_delete(T);
  67651. }
  67652. static int bf_sincos(bf_t *s, bf_t *c, const bf_t *a, limb_t prec)
  67653. {
  67654. bf_context_t *s1 = a->ctx;
  67655. bf_t T_s, *T = &T_s;
  67656. bf_t U_s, *U = &U_s;
  67657. bf_t r_s, *r = &r_s;
  67658. slimb_t K, prec1, i, l, mod, prec2;
  67659. int is_neg;
  67660. assert(c != a && s != a);
  67661. bf_init(s1, T);
  67662. bf_init(s1, U);
  67663. bf_init(s1, r);
  67664. /* XXX: precision analysis */
  67665. K = bf_isqrt(prec / 2);
  67666. l = prec / (2 * K) + 1;
  67667. prec1 = prec + 2 * K + l + 8;
  67668. /* after the modulo reduction, -pi/4 <= T <= pi/4 */
  67669. if (a->expn <= -1) {
  67670. /* abs(a) <= 0.25: no modulo reduction needed */
  67671. bf_set(T, a);
  67672. mod = 0;
  67673. } else {
  67674. slimb_t cancel;
  67675. cancel = 0;
  67676. for(;;) {
  67677. prec2 = prec1 + a->expn + cancel;
  67678. bf_const_pi(U, prec2, BF_RNDF);
  67679. bf_mul_2exp(U, -1, BF_PREC_INF, BF_RNDZ);
  67680. bf_remquo(&mod, T, a, U, prec2, BF_RNDN, BF_RNDN);
  67681. // printf("T.expn=%ld prec2=%ld\n", T->expn, prec2);
  67682. if (mod == 0 || (T->expn != BF_EXP_ZERO &&
  67683. (T->expn + prec2) >= (prec1 - 1)))
  67684. break;
  67685. /* increase the number of bits until the precision is good enough */
  67686. cancel = bf_max(-T->expn, (cancel + 1) * 3 / 2);
  67687. }
  67688. mod &= 3;
  67689. }
  67690. is_neg = T->sign;
  67691. /* compute cosm1(x) = cos(x) - 1 */
  67692. bf_mul(T, T, T, prec1, BF_RNDN);
  67693. bf_mul_2exp(T, -2 * K, BF_PREC_INF, BF_RNDZ);
  67694. /* Taylor expansion:
  67695. -x^2/2 + x^4/4! - x^6/6! + ...
  67696. */
  67697. bf_set_ui(r, 1);
  67698. for(i = l ; i >= 1; i--) {
  67699. bf_set_ui(U, 2 * i - 1);
  67700. bf_mul_ui(U, U, 2 * i, BF_PREC_INF, BF_RNDZ);
  67701. bf_div(U, T, U, prec1, BF_RNDN);
  67702. bf_mul(r, r, U, prec1, BF_RNDN);
  67703. bf_neg(r);
  67704. if (i != 1)
  67705. bf_add_si(r, r, 1, prec1, BF_RNDN);
  67706. }
  67707. bf_delete(U);
  67708. /* undo argument reduction:
  67709. cosm1(2*x)= 2*(2*cosm1(x)+cosm1(x)^2)
  67710. */
  67711. for(i = 0; i < K; i++) {
  67712. bf_mul(T, r, r, prec1, BF_RNDN);
  67713. bf_mul_2exp(r, 1, BF_PREC_INF, BF_RNDZ);
  67714. bf_add(r, r, T, prec1, BF_RNDN);
  67715. bf_mul_2exp(r, 1, BF_PREC_INF, BF_RNDZ);
  67716. }
  67717. bf_delete(T);
  67718. if (c) {
  67719. if ((mod & 1) == 0) {
  67720. bf_add_si(c, r, 1, prec1, BF_RNDN);
  67721. } else {
  67722. bf_sqrt_sin(c, r, prec1);
  67723. c->sign = is_neg ^ 1;
  67724. }
  67725. c->sign ^= mod >> 1;
  67726. }
  67727. if (s) {
  67728. if ((mod & 1) == 0) {
  67729. bf_sqrt_sin(s, r, prec1);
  67730. s->sign = is_neg;
  67731. } else {
  67732. bf_add_si(s, r, 1, prec1, BF_RNDN);
  67733. }
  67734. s->sign ^= mod >> 1;
  67735. }
  67736. bf_delete(r);
  67737. return BF_ST_INEXACT;
  67738. }
  67739. static int bf_cos_internal(bf_t *r, const bf_t *a, limb_t prec, void *opaque)
  67740. {
  67741. return bf_sincos(NULL, r, a, prec);
  67742. }
  67743. int bf_cos(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags)
  67744. {
  67745. if (a->len == 0) {
  67746. if (a->expn == BF_EXP_NAN) {
  67747. bf_set_nan(r);
  67748. return 0;
  67749. } else if (a->expn == BF_EXP_INF) {
  67750. bf_set_nan(r);
  67751. return BF_ST_INVALID_OP;
  67752. } else {
  67753. bf_set_ui(r, 1);
  67754. return 0;
  67755. }
  67756. }
  67757. /* small argument case: result = 1+r(x) with r(x) = -x^2/2 +
  67758. O(X^4). We assume r(x) < 2^(2*EXP(x) - 1). */
  67759. if (a->expn < 0) {
  67760. slimb_t e;
  67761. e = 2 * a->expn - 1;
  67762. if (e < -(prec + 2)) {
  67763. bf_set_ui(r, 1);
  67764. return bf_add_epsilon(r, r, e, 1, prec, flags);
  67765. }
  67766. }
  67767. return bf_ziv_rounding(r, a, prec, flags, bf_cos_internal, NULL);
  67768. }
  67769. static int bf_sin_internal(bf_t *r, const bf_t *a, limb_t prec, void *opaque)
  67770. {
  67771. return bf_sincos(r, NULL, a, prec);
  67772. }
  67773. int bf_sin(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags)
  67774. {
  67775. if (a->len == 0) {
  67776. if (a->expn == BF_EXP_NAN) {
  67777. bf_set_nan(r);
  67778. return 0;
  67779. } else if (a->expn == BF_EXP_INF) {
  67780. bf_set_nan(r);
  67781. return BF_ST_INVALID_OP;
  67782. } else {
  67783. bf_set_zero(r, a->sign);
  67784. return 0;
  67785. }
  67786. }
  67787. /* small argument case: result = x+r(x) with r(x) = -x^3/6 +
  67788. O(X^5). We assume r(x) < 2^(3*EXP(x) - 2). */
  67789. if (a->expn < 0) {
  67790. slimb_t e;
  67791. e = sat_add(2 * a->expn, a->expn - 2);
  67792. if (e < a->expn - bf_max(prec + 2, a->len * LIMB_BITS + 2)) {
  67793. bf_set(r, a);
  67794. return bf_add_epsilon(r, r, e, 1 - a->sign, prec, flags);
  67795. }
  67796. }
  67797. return bf_ziv_rounding(r, a, prec, flags, bf_sin_internal, NULL);
  67798. }
  67799. static int bf_tan_internal(bf_t *r, const bf_t *a, limb_t prec, void *opaque)
  67800. {
  67801. bf_context_t *s = r->ctx;
  67802. bf_t T_s, *T = &T_s;
  67803. limb_t prec1;
  67804. /* XXX: precision analysis */
  67805. prec1 = prec + 8;
  67806. bf_init(s, T);
  67807. bf_sincos(r, T, a, prec1);
  67808. bf_div(r, r, T, prec1, BF_RNDF);
  67809. bf_delete(T);
  67810. return BF_ST_INEXACT;
  67811. }
  67812. int bf_tan(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags)
  67813. {
  67814. assert(r != a);
  67815. if (a->len == 0) {
  67816. if (a->expn == BF_EXP_NAN) {
  67817. bf_set_nan(r);
  67818. return 0;
  67819. } else if (a->expn == BF_EXP_INF) {
  67820. bf_set_nan(r);
  67821. return BF_ST_INVALID_OP;
  67822. } else {
  67823. bf_set_zero(r, a->sign);
  67824. return 0;
  67825. }
  67826. }
  67827. /* small argument case: result = x+r(x) with r(x) = x^3/3 +
  67828. O(X^5). We assume r(x) < 2^(3*EXP(x) - 1). */
  67829. if (a->expn < 0) {
  67830. slimb_t e;
  67831. e = sat_add(2 * a->expn, a->expn - 1);
  67832. if (e < a->expn - bf_max(prec + 2, a->len * LIMB_BITS + 2)) {
  67833. bf_set(r, a);
  67834. return bf_add_epsilon(r, r, e, a->sign, prec, flags);
  67835. }
  67836. }
  67837. return bf_ziv_rounding(r, a, prec, flags, bf_tan_internal, NULL);
  67838. }
  67839. /* if add_pi2 is true, add pi/2 to the result (used for acos(x) to
  67840. avoid cancellation) */
  67841. static int bf_atan_internal(bf_t *r, const bf_t *a, limb_t prec,
  67842. void *opaque)
  67843. {
  67844. bf_context_t *s = r->ctx;
  67845. bool add_pi2 = (bool)(intptr_t)opaque;
  67846. bf_t T_s, *T = &T_s;
  67847. bf_t U_s, *U = &U_s;
  67848. bf_t V_s, *V = &V_s;
  67849. bf_t X2_s, *X2 = &X2_s;
  67850. int cmp_1;
  67851. slimb_t prec1, i, K, l;
  67852. /* XXX: precision analysis */
  67853. K = bf_isqrt((prec + 1) / 2);
  67854. l = prec / (2 * K) + 1;
  67855. prec1 = prec + K + 2 * l + 32;
  67856. // printf("prec=%d K=%d l=%d prec1=%d\n", (int)prec, (int)K, (int)l, (int)prec1);
  67857. bf_init(s, T);
  67858. cmp_1 = (a->expn >= 1); /* a >= 1 */
  67859. if (cmp_1) {
  67860. bf_set_ui(T, 1);
  67861. bf_div(T, T, a, prec1, BF_RNDN);
  67862. } else {
  67863. bf_set(T, a);
  67864. }
  67865. /* abs(T) <= 1 */
  67866. /* argument reduction */
  67867. bf_init(s, U);
  67868. bf_init(s, V);
  67869. bf_init(s, X2);
  67870. for(i = 0; i < K; i++) {
  67871. /* T = T / (1 + sqrt(1 + T^2)) */
  67872. bf_mul(U, T, T, prec1, BF_RNDN);
  67873. bf_add_si(U, U, 1, prec1, BF_RNDN);
  67874. bf_sqrt(V, U, prec1, BF_RNDN);
  67875. bf_add_si(V, V, 1, prec1, BF_RNDN);
  67876. bf_div(T, T, V, prec1, BF_RNDN);
  67877. }
  67878. /* Taylor series:
  67879. x - x^3/3 + ... + (-1)^ l * y^(2*l + 1) / (2*l+1)
  67880. */
  67881. bf_mul(X2, T, T, prec1, BF_RNDN);
  67882. bf_set_ui(r, 0);
  67883. for(i = l; i >= 1; i--) {
  67884. bf_set_si(U, 1);
  67885. bf_set_ui(V, 2 * i + 1);
  67886. bf_div(U, U, V, prec1, BF_RNDN);
  67887. bf_neg(r);
  67888. bf_add(r, r, U, prec1, BF_RNDN);
  67889. bf_mul(r, r, X2, prec1, BF_RNDN);
  67890. }
  67891. bf_neg(r);
  67892. bf_add_si(r, r, 1, prec1, BF_RNDN);
  67893. bf_mul(r, r, T, prec1, BF_RNDN);
  67894. /* undo the argument reduction */
  67895. bf_mul_2exp(r, K, BF_PREC_INF, BF_RNDZ);
  67896. bf_delete(U);
  67897. bf_delete(V);
  67898. bf_delete(X2);
  67899. i = add_pi2;
  67900. if (cmp_1 > 0) {
  67901. /* undo the inversion : r = sign(a)*PI/2 - r */
  67902. bf_neg(r);
  67903. i += 1 - 2 * a->sign;
  67904. }
  67905. /* add i*(pi/2) with -1 <= i <= 2 */
  67906. if (i != 0) {
  67907. bf_const_pi(T, prec1, BF_RNDF);
  67908. if (i != 2)
  67909. bf_mul_2exp(T, -1, BF_PREC_INF, BF_RNDZ);
  67910. T->sign = (i < 0);
  67911. bf_add(r, T, r, prec1, BF_RNDN);
  67912. }
  67913. bf_delete(T);
  67914. return BF_ST_INEXACT;
  67915. }
  67916. int bf_atan(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags)
  67917. {
  67918. bf_context_t *s = r->ctx;
  67919. bf_t T_s, *T = &T_s;
  67920. int res;
  67921. if (a->len == 0) {
  67922. if (a->expn == BF_EXP_NAN) {
  67923. bf_set_nan(r);
  67924. return 0;
  67925. } else if (a->expn == BF_EXP_INF) {
  67926. /* -PI/2 or PI/2 */
  67927. bf_const_pi_signed(r, a->sign, prec, flags);
  67928. bf_mul_2exp(r, -1, BF_PREC_INF, BF_RNDZ);
  67929. return BF_ST_INEXACT;
  67930. } else {
  67931. bf_set_zero(r, a->sign);
  67932. return 0;
  67933. }
  67934. }
  67935. bf_init(s, T);
  67936. bf_set_ui(T, 1);
  67937. res = bf_cmpu(a, T);
  67938. bf_delete(T);
  67939. if (res == 0) {
  67940. /* short cut: abs(a) == 1 -> +/-pi/4 */
  67941. bf_const_pi_signed(r, a->sign, prec, flags);
  67942. bf_mul_2exp(r, -2, BF_PREC_INF, BF_RNDZ);
  67943. return BF_ST_INEXACT;
  67944. }
  67945. /* small argument case: result = x+r(x) with r(x) = -x^3/3 +
  67946. O(X^5). We assume r(x) < 2^(3*EXP(x) - 1). */
  67947. if (a->expn < 0) {
  67948. slimb_t e;
  67949. e = sat_add(2 * a->expn, a->expn - 1);
  67950. if (e < a->expn - bf_max(prec + 2, a->len * LIMB_BITS + 2)) {
  67951. bf_set(r, a);
  67952. return bf_add_epsilon(r, r, e, 1 - a->sign, prec, flags);
  67953. }
  67954. }
  67955. return bf_ziv_rounding(r, a, prec, flags, bf_atan_internal, (void *)false);
  67956. }
  67957. static int bf_atan2_internal(bf_t *r, const bf_t *y, limb_t prec, void *opaque)
  67958. {
  67959. bf_context_t *s = r->ctx;
  67960. const bf_t *x = opaque;
  67961. bf_t T_s, *T = &T_s;
  67962. limb_t prec1;
  67963. int ret;
  67964. if (y->expn == BF_EXP_NAN || x->expn == BF_EXP_NAN) {
  67965. bf_set_nan(r);
  67966. return 0;
  67967. }
  67968. /* compute atan(y/x) assumming inf/inf = 1 and 0/0 = 0 */
  67969. bf_init(s, T);
  67970. prec1 = prec + 32;
  67971. if (y->expn == BF_EXP_INF && x->expn == BF_EXP_INF) {
  67972. bf_set_ui(T, 1);
  67973. T->sign = y->sign ^ x->sign;
  67974. } else if (y->expn == BF_EXP_ZERO && x->expn == BF_EXP_ZERO) {
  67975. bf_set_zero(T, y->sign ^ x->sign);
  67976. } else {
  67977. bf_div(T, y, x, prec1, BF_RNDF);
  67978. }
  67979. ret = bf_atan(r, T, prec1, BF_RNDF);
  67980. if (x->sign) {
  67981. /* if x < 0 (it includes -0), return sign(y)*pi + atan(y/x) */
  67982. bf_const_pi(T, prec1, BF_RNDF);
  67983. T->sign = y->sign;
  67984. bf_add(r, r, T, prec1, BF_RNDN);
  67985. ret |= BF_ST_INEXACT;
  67986. }
  67987. bf_delete(T);
  67988. return ret;
  67989. }
  67990. int bf_atan2(bf_t *r, const bf_t *y, const bf_t *x,
  67991. limb_t prec, bf_flags_t flags)
  67992. {
  67993. return bf_ziv_rounding(r, y, prec, flags, bf_atan2_internal, (void *)x);
  67994. }
  67995. static int bf_asin_internal(bf_t *r, const bf_t *a, limb_t prec, void *opaque)
  67996. {
  67997. bf_context_t *s = r->ctx;
  67998. bool is_acos = (bool)(intptr_t)opaque;
  67999. bf_t T_s, *T = &T_s;
  68000. limb_t prec1, prec2;
  68001. /* asin(x) = atan(x/sqrt(1-x^2))
  68002. acos(x) = pi/2 - asin(x) */
  68003. prec1 = prec + 8;
  68004. /* increase the precision in x^2 to compensate the cancellation in
  68005. (1-x^2) if x is close to 1 */
  68006. /* XXX: use less precision when possible */
  68007. if (a->expn >= 0)
  68008. prec2 = BF_PREC_INF;
  68009. else
  68010. prec2 = prec1;
  68011. bf_init(s, T);
  68012. bf_mul(T, a, a, prec2, BF_RNDN);
  68013. bf_neg(T);
  68014. bf_add_si(T, T, 1, prec2, BF_RNDN);
  68015. bf_sqrt(r, T, prec1, BF_RNDN);
  68016. bf_div(T, a, r, prec1, BF_RNDN);
  68017. if (is_acos)
  68018. bf_neg(T);
  68019. bf_atan_internal(r, T, prec1, (void *)(intptr_t)is_acos);
  68020. bf_delete(T);
  68021. return BF_ST_INEXACT;
  68022. }
  68023. int bf_asin(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags)
  68024. {
  68025. bf_context_t *s = r->ctx;
  68026. bf_t T_s, *T = &T_s;
  68027. int res;
  68028. if (a->len == 0) {
  68029. if (a->expn == BF_EXP_NAN) {
  68030. bf_set_nan(r);
  68031. return 0;
  68032. } else if (a->expn == BF_EXP_INF) {
  68033. bf_set_nan(r);
  68034. return BF_ST_INVALID_OP;
  68035. } else {
  68036. bf_set_zero(r, a->sign);
  68037. return 0;
  68038. }
  68039. }
  68040. bf_init(s, T);
  68041. bf_set_ui(T, 1);
  68042. res = bf_cmpu(a, T);
  68043. bf_delete(T);
  68044. if (res > 0) {
  68045. bf_set_nan(r);
  68046. return BF_ST_INVALID_OP;
  68047. }
  68048. /* small argument case: result = x+r(x) with r(x) = x^3/6 +
  68049. O(X^5). We assume r(x) < 2^(3*EXP(x) - 2). */
  68050. if (a->expn < 0) {
  68051. slimb_t e;
  68052. e = sat_add(2 * a->expn, a->expn - 2);
  68053. if (e < a->expn - bf_max(prec + 2, a->len * LIMB_BITS + 2)) {
  68054. bf_set(r, a);
  68055. return bf_add_epsilon(r, r, e, a->sign, prec, flags);
  68056. }
  68057. }
  68058. return bf_ziv_rounding(r, a, prec, flags, bf_asin_internal, (void *)false);
  68059. }
  68060. int bf_acos(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags)
  68061. {
  68062. bf_context_t *s = r->ctx;
  68063. bf_t T_s, *T = &T_s;
  68064. int res;
  68065. if (a->len == 0) {
  68066. if (a->expn == BF_EXP_NAN) {
  68067. bf_set_nan(r);
  68068. return 0;
  68069. } else if (a->expn == BF_EXP_INF) {
  68070. bf_set_nan(r);
  68071. return BF_ST_INVALID_OP;
  68072. } else {
  68073. bf_const_pi(r, prec, flags);
  68074. bf_mul_2exp(r, -1, BF_PREC_INF, BF_RNDZ);
  68075. return BF_ST_INEXACT;
  68076. }
  68077. }
  68078. bf_init(s, T);
  68079. bf_set_ui(T, 1);
  68080. res = bf_cmpu(a, T);
  68081. bf_delete(T);
  68082. if (res > 0) {
  68083. bf_set_nan(r);
  68084. return BF_ST_INVALID_OP;
  68085. } else if (res == 0 && a->sign == 0) {
  68086. bf_set_zero(r, 0);
  68087. return 0;
  68088. }
  68089. return bf_ziv_rounding(r, a, prec, flags, bf_asin_internal, (void *)true);
  68090. }
  68091. /***************************************************************/
  68092. /* decimal floating point numbers */
  68093. #ifdef USE_BF_DEC
  68094. #define adddq(r1, r0, a1, a0) \
  68095. do { \
  68096. limb_t __t = r0; \
  68097. r0 += (a0); \
  68098. r1 += (a1) + (r0 < __t); \
  68099. } while (0)
  68100. #define subdq(r1, r0, a1, a0) \
  68101. do { \
  68102. limb_t __t = r0; \
  68103. r0 -= (a0); \
  68104. r1 -= (a1) + (r0 > __t); \
  68105. } while (0)
  68106. #if LIMB_BITS == 64
  68107. /* Note: we assume __int128 is available */
  68108. /* uint128_t defined in libbf.h */
  68109. #define muldq(r1, r0, a, b) \
  68110. do { \
  68111. uint128_t __t; \
  68112. __t = (uint128_t)(a) * (uint128_t)(b); \
  68113. r0 = __t; \
  68114. r1 = __t >> 64; \
  68115. } while (0)
  68116. #define divdq(q, r, a1, a0, b) \
  68117. do { \
  68118. uint128_t __t; \
  68119. limb_t __b = (b); \
  68120. __t = ((uint128_t)(a1) << 64) | (a0); \
  68121. q = __t / __b; \
  68122. r = __t % __b; \
  68123. } while (0)
  68124. #else
  68125. #define muldq(r1, r0, a, b) \
  68126. do { \
  68127. uint64_t __t; \
  68128. __t = (uint64_t)(a) * (uint64_t)(b); \
  68129. r0 = __t; \
  68130. r1 = __t >> 32; \
  68131. } while (0)
  68132. #define divdq(q, r, a1, a0, b) \
  68133. do { \
  68134. uint64_t __t; \
  68135. limb_t __b = (b); \
  68136. __t = ((uint64_t)(a1) << 32) | (a0); \
  68137. q = __t / __b; \
  68138. r = __t % __b; \
  68139. } while (0)
  68140. #endif /* LIMB_BITS != 64 */
  68141. #if LIMB_DIGITS == 19
  68142. /* WARNING: hardcoded for b = 1e19. It is assumed that:
  68143. 0 <= a1 < 2^63 */
  68144. #define divdq_base(q, r, a1, a0)\
  68145. do {\
  68146. uint64_t __a0, __a1, __t0, __t1, __b = BF_DEC_BASE; \
  68147. __a0 = a0;\
  68148. __a1 = a1;\
  68149. __t0 = __a1;\
  68150. __t0 = shld(__t0, __a0, 1);\
  68151. muldq(q, __t1, __t0, UINT64_C(17014118346046923173)); \
  68152. muldq(__t1, __t0, q, __b);\
  68153. subdq(__a1, __a0, __t1, __t0);\
  68154. subdq(__a1, __a0, 1, __b * 2); \
  68155. __t0 = (slimb_t)__a1 >> 1; \
  68156. q += 2 + __t0;\
  68157. adddq(__a1, __a0, 0, __b & __t0);\
  68158. q += __a1; \
  68159. __a0 += __b & __a1; \
  68160. r = __a0;\
  68161. } while(0)
  68162. #elif LIMB_DIGITS == 9
  68163. /* WARNING: hardcoded for b = 1e9. It is assumed that:
  68164. 0 <= a1 < 2^29 */
  68165. #define divdq_base(q, r, a1, a0)\
  68166. do {\
  68167. uint32_t __t0, __t1, __b = BF_DEC_BASE; \
  68168. __t0 = a1;\
  68169. __t1 = a0;\
  68170. __t0 = (__t0 << 3) | (__t1 >> (32 - 3)); \
  68171. muldq(q, __t1, __t0, 2305843009U);\
  68172. r = a0 - q * __b;\
  68173. __t1 = (r >= __b);\
  68174. q += __t1;\
  68175. if (__t1)\
  68176. r -= __b;\
  68177. } while(0)
  68178. #endif
  68179. /* fast integer division by a fixed constant */
  68180. typedef struct FastDivData {
  68181. limb_t m1; /* multiplier */
  68182. int8_t shift1;
  68183. int8_t shift2;
  68184. } FastDivData;
  68185. /* From "Division by Invariant Integers using Multiplication" by
  68186. Torborn Granlund and Peter L. Montgomery */
  68187. /* d must be != 0 */
  68188. static inline __maybe_unused void fast_udiv_init(FastDivData *s, limb_t d)
  68189. {
  68190. int l;
  68191. limb_t q, r, m1;
  68192. if (d == 1)
  68193. l = 0;
  68194. else
  68195. l = 64 - clz64(d - 1);
  68196. divdq(q, r, ((limb_t)1 << l) - d, 0, d);
  68197. (void)r;
  68198. m1 = q + 1;
  68199. // printf("d=%lu l=%d m1=0x%016lx\n", d, l, m1);
  68200. s->m1 = m1;
  68201. s->shift1 = l;
  68202. if (s->shift1 > 1)
  68203. s->shift1 = 1;
  68204. s->shift2 = l - 1;
  68205. if (s->shift2 < 0)
  68206. s->shift2 = 0;
  68207. }
  68208. static inline limb_t fast_udiv(limb_t a, const FastDivData *s)
  68209. {
  68210. limb_t t0, t1;
  68211. muldq(t1, t0, s->m1, a);
  68212. t0 = (a - t1) >> s->shift1;
  68213. return (t1 + t0) >> s->shift2;
  68214. }
  68215. /* contains 10^i */
  68216. const limb_t mp_pow_dec[LIMB_DIGITS + 1] = {
  68217. 1U,
  68218. 10U,
  68219. 100U,
  68220. 1000U,
  68221. 10000U,
  68222. 100000U,
  68223. 1000000U,
  68224. 10000000U,
  68225. 100000000U,
  68226. 1000000000U,
  68227. #if LIMB_BITS == 64
  68228. 10000000000U,
  68229. 100000000000U,
  68230. 1000000000000U,
  68231. 10000000000000U,
  68232. 100000000000000U,
  68233. 1000000000000000U,
  68234. 10000000000000000U,
  68235. 100000000000000000U,
  68236. 1000000000000000000U,
  68237. 10000000000000000000U,
  68238. #endif
  68239. };
  68240. /* precomputed from fast_udiv_init(10^i) */
  68241. static const FastDivData mp_pow_div[LIMB_DIGITS + 1] = {
  68242. #if LIMB_BITS == 32
  68243. { 0x00000001, 0, 0 },
  68244. { 0x9999999a, 1, 3 },
  68245. { 0x47ae147b, 1, 6 },
  68246. { 0x0624dd30, 1, 9 },
  68247. { 0xa36e2eb2, 1, 13 },
  68248. { 0x4f8b588f, 1, 16 },
  68249. { 0x0c6f7a0c, 1, 19 },
  68250. { 0xad7f29ac, 1, 23 },
  68251. { 0x5798ee24, 1, 26 },
  68252. { 0x12e0be83, 1, 29 },
  68253. #else
  68254. { 0x0000000000000001, 0, 0 },
  68255. { 0x999999999999999a, 1, 3 },
  68256. { 0x47ae147ae147ae15, 1, 6 },
  68257. { 0x0624dd2f1a9fbe77, 1, 9 },
  68258. { 0xa36e2eb1c432ca58, 1, 13 },
  68259. { 0x4f8b588e368f0847, 1, 16 },
  68260. { 0x0c6f7a0b5ed8d36c, 1, 19 },
  68261. { 0xad7f29abcaf48579, 1, 23 },
  68262. { 0x5798ee2308c39dfa, 1, 26 },
  68263. { 0x12e0be826d694b2f, 1, 29 },
  68264. { 0xb7cdfd9d7bdbab7e, 1, 33 },
  68265. { 0x5fd7fe17964955fe, 1, 36 },
  68266. { 0x19799812dea11198, 1, 39 },
  68267. { 0xc25c268497681c27, 1, 43 },
  68268. { 0x6849b86a12b9b01f, 1, 46 },
  68269. { 0x203af9ee756159b3, 1, 49 },
  68270. { 0xcd2b297d889bc2b7, 1, 53 },
  68271. { 0x70ef54646d496893, 1, 56 },
  68272. { 0x2725dd1d243aba0f, 1, 59 },
  68273. { 0xd83c94fb6d2ac34d, 1, 63 },
  68274. #endif
  68275. };
  68276. /* divide by 10^shift with 0 <= shift <= LIMB_DIGITS */
  68277. static inline limb_t fast_shr_dec(limb_t a, int shift)
  68278. {
  68279. return fast_udiv(a, &mp_pow_div[shift]);
  68280. }
  68281. /* division and remainder by 10^shift */
  68282. #define fast_shr_rem_dec(q, r, a, shift) q = fast_shr_dec(a, shift), r = a - q * mp_pow_dec[shift]
  68283. limb_t mp_add_dec(limb_t *res, const limb_t *op1, const limb_t *op2,
  68284. mp_size_t n, limb_t carry)
  68285. {
  68286. limb_t base = BF_DEC_BASE;
  68287. mp_size_t i;
  68288. limb_t k, a, v;
  68289. k=carry;
  68290. for(i=0;i<n;i++) {
  68291. /* XXX: reuse the trick in add_mod */
  68292. v = op1[i];
  68293. a = v + op2[i] + k - base;
  68294. k = a <= v;
  68295. if (!k)
  68296. a += base;
  68297. res[i]=a;
  68298. }
  68299. return k;
  68300. }
  68301. limb_t mp_add_ui_dec(limb_t *tab, limb_t b, mp_size_t n)
  68302. {
  68303. limb_t base = BF_DEC_BASE;
  68304. mp_size_t i;
  68305. limb_t k, a, v;
  68306. k=b;
  68307. for(i=0;i<n;i++) {
  68308. v = tab[i];
  68309. a = v + k - base;
  68310. k = a <= v;
  68311. if (!k)
  68312. a += base;
  68313. tab[i] = a;
  68314. if (k == 0)
  68315. break;
  68316. }
  68317. return k;
  68318. }
  68319. limb_t mp_sub_dec(limb_t *res, const limb_t *op1, const limb_t *op2,
  68320. mp_size_t n, limb_t carry)
  68321. {
  68322. limb_t base = BF_DEC_BASE;
  68323. mp_size_t i;
  68324. limb_t k, v, a;
  68325. k=carry;
  68326. for(i=0;i<n;i++) {
  68327. v = op1[i];
  68328. a = v - op2[i] - k;
  68329. k = a > v;
  68330. if (k)
  68331. a += base;
  68332. res[i] = a;
  68333. }
  68334. return k;
  68335. }
  68336. limb_t mp_sub_ui_dec(limb_t *tab, limb_t b, mp_size_t n)
  68337. {
  68338. limb_t base = BF_DEC_BASE;
  68339. mp_size_t i;
  68340. limb_t k, v, a;
  68341. k=b;
  68342. for(i=0;i<n;i++) {
  68343. v = tab[i];
  68344. a = v - k;
  68345. k = a > v;
  68346. if (k)
  68347. a += base;
  68348. tab[i]=a;
  68349. if (k == 0)
  68350. break;
  68351. }
  68352. return k;
  68353. }
  68354. /* taba[] = taba[] * b + l. 0 <= b, l <= base - 1. Return the high carry */
  68355. limb_t mp_mul1_dec(limb_t *tabr, const limb_t *taba, mp_size_t n,
  68356. limb_t b, limb_t l)
  68357. {
  68358. mp_size_t i;
  68359. limb_t t0, t1, r;
  68360. for(i = 0; i < n; i++) {
  68361. muldq(t1, t0, taba[i], b);
  68362. adddq(t1, t0, 0, l);
  68363. divdq_base(l, r, t1, t0);
  68364. tabr[i] = r;
  68365. }
  68366. return l;
  68367. }
  68368. /* tabr[] += taba[] * b. 0 <= b <= base - 1. Return the value to add
  68369. to the high word */
  68370. limb_t mp_add_mul1_dec(limb_t *tabr, const limb_t *taba, mp_size_t n,
  68371. limb_t b)
  68372. {
  68373. mp_size_t i;
  68374. limb_t l, t0, t1, r;
  68375. l = 0;
  68376. for(i = 0; i < n; i++) {
  68377. muldq(t1, t0, taba[i], b);
  68378. adddq(t1, t0, 0, l);
  68379. adddq(t1, t0, 0, tabr[i]);
  68380. divdq_base(l, r, t1, t0);
  68381. tabr[i] = r;
  68382. }
  68383. return l;
  68384. }
  68385. /* tabr[] -= taba[] * b. 0 <= b <= base - 1. Return the value to
  68386. substract to the high word. */
  68387. limb_t mp_sub_mul1_dec(limb_t *tabr, const limb_t *taba, mp_size_t n,
  68388. limb_t b)
  68389. {
  68390. limb_t base = BF_DEC_BASE;
  68391. mp_size_t i;
  68392. limb_t l, t0, t1, r, a, v, c;
  68393. /* XXX: optimize */
  68394. l = 0;
  68395. for(i = 0; i < n; i++) {
  68396. muldq(t1, t0, taba[i], b);
  68397. adddq(t1, t0, 0, l);
  68398. divdq_base(l, r, t1, t0);
  68399. v = tabr[i];
  68400. a = v - r;
  68401. c = a > v;
  68402. if (c)
  68403. a += base;
  68404. /* never bigger than base because r = 0 when l = base - 1 */
  68405. l += c;
  68406. tabr[i] = a;
  68407. }
  68408. return l;
  68409. }
  68410. /* size of the result : op1_size + op2_size. */
  68411. void mp_mul_basecase_dec(limb_t *result,
  68412. const limb_t *op1, mp_size_t op1_size,
  68413. const limb_t *op2, mp_size_t op2_size)
  68414. {
  68415. mp_size_t i;
  68416. limb_t r;
  68417. result[op1_size] = mp_mul1_dec(result, op1, op1_size, op2[0], 0);
  68418. for(i=1;i<op2_size;i++) {
  68419. r = mp_add_mul1_dec(result + i, op1, op1_size, op2[i]);
  68420. result[i + op1_size] = r;
  68421. }
  68422. }
  68423. /* taba[] = (taba[] + r*base^na) / b. 0 <= b < base. 0 <= r <
  68424. b. Return the remainder. */
  68425. limb_t mp_div1_dec(limb_t *tabr, const limb_t *taba, mp_size_t na,
  68426. limb_t b, limb_t r)
  68427. {
  68428. limb_t base = BF_DEC_BASE;
  68429. mp_size_t i;
  68430. limb_t t0, t1, q;
  68431. int shift;
  68432. #if (BF_DEC_BASE % 2) == 0
  68433. if (b == 2) {
  68434. limb_t base_div2;
  68435. /* Note: only works if base is even */
  68436. base_div2 = base >> 1;
  68437. if (r)
  68438. r = base_div2;
  68439. for(i = na - 1; i >= 0; i--) {
  68440. t0 = taba[i];
  68441. tabr[i] = (t0 >> 1) + r;
  68442. r = 0;
  68443. if (t0 & 1)
  68444. r = base_div2;
  68445. }
  68446. if (r)
  68447. r = 1;
  68448. } else
  68449. #endif
  68450. if (na >= UDIV1NORM_THRESHOLD) {
  68451. shift = clz(b);
  68452. if (shift == 0) {
  68453. /* normalized case: b >= 2^(LIMB_BITS-1) */
  68454. limb_t b_inv;
  68455. b_inv = udiv1norm_init(b);
  68456. for(i = na - 1; i >= 0; i--) {
  68457. muldq(t1, t0, r, base);
  68458. adddq(t1, t0, 0, taba[i]);
  68459. q = udiv1norm(&r, t1, t0, b, b_inv);
  68460. tabr[i] = q;
  68461. }
  68462. } else {
  68463. limb_t b_inv;
  68464. b <<= shift;
  68465. b_inv = udiv1norm_init(b);
  68466. for(i = na - 1; i >= 0; i--) {
  68467. muldq(t1, t0, r, base);
  68468. adddq(t1, t0, 0, taba[i]);
  68469. t1 = (t1 << shift) | (t0 >> (LIMB_BITS - shift));
  68470. t0 <<= shift;
  68471. q = udiv1norm(&r, t1, t0, b, b_inv);
  68472. r >>= shift;
  68473. tabr[i] = q;
  68474. }
  68475. }
  68476. } else {
  68477. for(i = na - 1; i >= 0; i--) {
  68478. muldq(t1, t0, r, base);
  68479. adddq(t1, t0, 0, taba[i]);
  68480. divdq(q, r, t1, t0, b);
  68481. tabr[i] = q;
  68482. }
  68483. }
  68484. return r;
  68485. }
  68486. static __maybe_unused void mp_print_str_dec(const char *str,
  68487. const limb_t *tab, slimb_t n)
  68488. {
  68489. slimb_t i;
  68490. printf("%s=", str);
  68491. for(i = n - 1; i >= 0; i--) {
  68492. if (i != n - 1)
  68493. printf("_");
  68494. printf("%0*" PRIu_LIMB, LIMB_DIGITS, tab[i]);
  68495. }
  68496. printf("\n");
  68497. }
  68498. static __maybe_unused void mp_print_str_h_dec(const char *str,
  68499. const limb_t *tab, slimb_t n,
  68500. limb_t high)
  68501. {
  68502. slimb_t i;
  68503. printf("%s=", str);
  68504. printf("%0*" PRIu_LIMB, LIMB_DIGITS, high);
  68505. for(i = n - 1; i >= 0; i--) {
  68506. printf("_");
  68507. printf("%0*" PRIu_LIMB, LIMB_DIGITS, tab[i]);
  68508. }
  68509. printf("\n");
  68510. }
  68511. //#define DEBUG_DIV_SLOW
  68512. #define DIV_STATIC_ALLOC_LEN 16
  68513. /* return q = a / b and r = a % b.
  68514. taba[na] must be allocated if tabb1[nb - 1] < B / 2. tabb1[nb - 1]
  68515. must be != zero. na must be >= nb. 's' can be NULL if tabb1[nb - 1]
  68516. >= B / 2.
  68517. The remainder is is returned in taba and contains nb libms. tabq
  68518. contains na - nb + 1 limbs. No overlap is permitted.
  68519. Running time of the standard method: (na - nb + 1) * nb
  68520. Return 0 if OK, -1 if memory alloc error
  68521. */
  68522. /* XXX: optimize */
  68523. static int mp_div_dec(bf_context_t *s, limb_t *tabq,
  68524. limb_t *taba, mp_size_t na,
  68525. const limb_t *tabb1, mp_size_t nb)
  68526. {
  68527. limb_t base = BF_DEC_BASE;
  68528. limb_t r, mult, t0, t1, a, c, q, v, *tabb;
  68529. mp_size_t i, j;
  68530. limb_t static_tabb[DIV_STATIC_ALLOC_LEN];
  68531. #ifdef DEBUG_DIV_SLOW
  68532. mp_print_str_dec("a", taba, na);
  68533. mp_print_str_dec("b", tabb1, nb);
  68534. #endif
  68535. /* normalize tabb */
  68536. r = tabb1[nb - 1];
  68537. assert(r != 0);
  68538. i = na - nb;
  68539. if (r >= BF_DEC_BASE / 2) {
  68540. mult = 1;
  68541. tabb = (limb_t *)tabb1;
  68542. q = 1;
  68543. for(j = nb - 1; j >= 0; j--) {
  68544. if (taba[i + j] != tabb[j]) {
  68545. if (taba[i + j] < tabb[j])
  68546. q = 0;
  68547. break;
  68548. }
  68549. }
  68550. tabq[i] = q;
  68551. if (q) {
  68552. mp_sub_dec(taba + i, taba + i, tabb, nb, 0);
  68553. }
  68554. i--;
  68555. } else {
  68556. mult = base / (r + 1);
  68557. if (likely(nb <= DIV_STATIC_ALLOC_LEN)) {
  68558. tabb = static_tabb;
  68559. } else {
  68560. tabb = bf_malloc(s, sizeof(limb_t) * nb);
  68561. if (!tabb)
  68562. return -1;
  68563. }
  68564. mp_mul1_dec(tabb, tabb1, nb, mult, 0);
  68565. taba[na] = mp_mul1_dec(taba, taba, na, mult, 0);
  68566. }
  68567. #ifdef DEBUG_DIV_SLOW
  68568. printf("mult=" FMT_LIMB "\n", mult);
  68569. mp_print_str_dec("a_norm", taba, na + 1);
  68570. mp_print_str_dec("b_norm", tabb, nb);
  68571. #endif
  68572. for(; i >= 0; i--) {
  68573. if (unlikely(taba[i + nb] >= tabb[nb - 1])) {
  68574. /* XXX: check if it is really possible */
  68575. q = base - 1;
  68576. } else {
  68577. muldq(t1, t0, taba[i + nb], base);
  68578. adddq(t1, t0, 0, taba[i + nb - 1]);
  68579. divdq(q, r, t1, t0, tabb[nb - 1]);
  68580. }
  68581. // printf("i=%d q1=%ld\n", i, q);
  68582. r = mp_sub_mul1_dec(taba + i, tabb, nb, q);
  68583. // mp_dump("r1", taba + i, nb, bd);
  68584. // printf("r2=%ld\n", r);
  68585. v = taba[i + nb];
  68586. a = v - r;
  68587. c = a > v;
  68588. if (c)
  68589. a += base;
  68590. taba[i + nb] = a;
  68591. if (c != 0) {
  68592. /* negative result */
  68593. for(;;) {
  68594. q--;
  68595. c = mp_add_dec(taba + i, taba + i, tabb, nb, 0);
  68596. /* propagate carry and test if positive result */
  68597. if (c != 0) {
  68598. if (++taba[i + nb] == base) {
  68599. break;
  68600. }
  68601. }
  68602. }
  68603. }
  68604. tabq[i] = q;
  68605. }
  68606. #ifdef DEBUG_DIV_SLOW
  68607. mp_print_str_dec("q", tabq, na - nb + 1);
  68608. mp_print_str_dec("r", taba, nb);
  68609. #endif
  68610. /* remove the normalization */
  68611. if (mult != 1) {
  68612. mp_div1_dec(taba, taba, nb, mult, 0);
  68613. if (unlikely(tabb != static_tabb))
  68614. bf_free(s, tabb);
  68615. }
  68616. return 0;
  68617. }
  68618. /* divide by 10^shift */
  68619. static limb_t mp_shr_dec(limb_t *tab_r, const limb_t *tab, mp_size_t n,
  68620. limb_t shift, limb_t high)
  68621. {
  68622. mp_size_t i;
  68623. limb_t l, a, q, r;
  68624. assert(shift >= 1 && shift < LIMB_DIGITS);
  68625. l = high;
  68626. for(i = n - 1; i >= 0; i--) {
  68627. a = tab[i];
  68628. fast_shr_rem_dec(q, r, a, shift);
  68629. tab_r[i] = q + l * mp_pow_dec[LIMB_DIGITS - shift];
  68630. l = r;
  68631. }
  68632. return l;
  68633. }
  68634. /* multiply by 10^shift */
  68635. static limb_t mp_shl_dec(limb_t *tab_r, const limb_t *tab, mp_size_t n,
  68636. limb_t shift, limb_t low)
  68637. {
  68638. mp_size_t i;
  68639. limb_t l, a, q, r;
  68640. assert(shift >= 1 && shift < LIMB_DIGITS);
  68641. l = low;
  68642. for(i = 0; i < n; i++) {
  68643. a = tab[i];
  68644. fast_shr_rem_dec(q, r, a, LIMB_DIGITS - shift);
  68645. tab_r[i] = r * mp_pow_dec[shift] + l;
  68646. l = q;
  68647. }
  68648. return l;
  68649. }
  68650. static limb_t mp_sqrtrem2_dec(limb_t *tabs, limb_t *taba)
  68651. {
  68652. int k;
  68653. dlimb_t a, b, r;
  68654. limb_t taba1[2], s, r0, r1;
  68655. /* convert to binary and normalize */
  68656. a = (dlimb_t)taba[1] * BF_DEC_BASE + taba[0];
  68657. k = clz(a >> LIMB_BITS) & ~1;
  68658. b = a << k;
  68659. taba1[0] = b;
  68660. taba1[1] = b >> LIMB_BITS;
  68661. mp_sqrtrem2(&s, taba1);
  68662. s >>= (k >> 1);
  68663. /* convert the remainder back to decimal */
  68664. r = a - (dlimb_t)s * (dlimb_t)s;
  68665. divdq_base(r1, r0, r >> LIMB_BITS, r);
  68666. taba[0] = r0;
  68667. tabs[0] = s;
  68668. return r1;
  68669. }
  68670. //#define DEBUG_SQRTREM_DEC
  68671. /* tmp_buf must contain (n / 2 + 1 limbs) */
  68672. static limb_t mp_sqrtrem_rec_dec(limb_t *tabs, limb_t *taba, limb_t n,
  68673. limb_t *tmp_buf)
  68674. {
  68675. limb_t l, h, rh, ql, qh, c, i;
  68676. if (n == 1)
  68677. return mp_sqrtrem2_dec(tabs, taba);
  68678. #ifdef DEBUG_SQRTREM_DEC
  68679. mp_print_str_dec("a", taba, 2 * n);
  68680. #endif
  68681. l = n / 2;
  68682. h = n - l;
  68683. qh = mp_sqrtrem_rec_dec(tabs + l, taba + 2 * l, h, tmp_buf);
  68684. #ifdef DEBUG_SQRTREM_DEC
  68685. mp_print_str_dec("s1", tabs + l, h);
  68686. mp_print_str_h_dec("r1", taba + 2 * l, h, qh);
  68687. mp_print_str_h_dec("r2", taba + l, n, qh);
  68688. #endif
  68689. /* the remainder is in taba + 2 * l. Its high bit is in qh */
  68690. if (qh) {
  68691. mp_sub_dec(taba + 2 * l, taba + 2 * l, tabs + l, h, 0);
  68692. }
  68693. /* instead of dividing by 2*s, divide by s (which is normalized)
  68694. and update q and r */
  68695. mp_div_dec(NULL, tmp_buf, taba + l, n, tabs + l, h);
  68696. qh += tmp_buf[l];
  68697. for(i = 0; i < l; i++)
  68698. tabs[i] = tmp_buf[i];
  68699. ql = mp_div1_dec(tabs, tabs, l, 2, qh & 1);
  68700. qh = qh >> 1; /* 0 or 1 */
  68701. if (ql)
  68702. rh = mp_add_dec(taba + l, taba + l, tabs + l, h, 0);
  68703. else
  68704. rh = 0;
  68705. #ifdef DEBUG_SQRTREM_DEC
  68706. mp_print_str_h_dec("q", tabs, l, qh);
  68707. mp_print_str_h_dec("u", taba + l, h, rh);
  68708. #endif
  68709. mp_add_ui_dec(tabs + l, qh, h);
  68710. #ifdef DEBUG_SQRTREM_DEC
  68711. mp_print_str_dec("s2", tabs, n);
  68712. #endif
  68713. /* q = qh, tabs[l - 1 ... 0], r = taba[n - 1 ... l] */
  68714. /* subtract q^2. if qh = 1 then q = B^l, so we can take shortcuts */
  68715. if (qh) {
  68716. c = qh;
  68717. } else {
  68718. mp_mul_basecase_dec(taba + n, tabs, l, tabs, l);
  68719. c = mp_sub_dec(taba, taba, taba + n, 2 * l, 0);
  68720. }
  68721. rh -= mp_sub_ui_dec(taba + 2 * l, c, n - 2 * l);
  68722. if ((slimb_t)rh < 0) {
  68723. mp_sub_ui_dec(tabs, 1, n);
  68724. rh += mp_add_mul1_dec(taba, tabs, n, 2);
  68725. rh += mp_add_ui_dec(taba, 1, n);
  68726. }
  68727. return rh;
  68728. }
  68729. /* 'taba' has 2*n limbs with n >= 1 and taba[2*n-1] >= B/4. Return (s,
  68730. r) with s=floor(sqrt(a)) and r=a-s^2. 0 <= r <= 2 * s. tabs has n
  68731. limbs. r is returned in the lower n limbs of taba. Its r[n] is the
  68732. returned value of the function. */
  68733. int mp_sqrtrem_dec(bf_context_t *s, limb_t *tabs, limb_t *taba, limb_t n)
  68734. {
  68735. limb_t tmp_buf1[8];
  68736. limb_t *tmp_buf;
  68737. mp_size_t n2;
  68738. n2 = n / 2 + 1;
  68739. if (n2 <= countof(tmp_buf1)) {
  68740. tmp_buf = tmp_buf1;
  68741. } else {
  68742. tmp_buf = bf_malloc(s, sizeof(limb_t) * n2);
  68743. if (!tmp_buf)
  68744. return -1;
  68745. }
  68746. taba[n] = mp_sqrtrem_rec_dec(tabs, taba, n, tmp_buf);
  68747. if (tmp_buf != tmp_buf1)
  68748. bf_free(s, tmp_buf);
  68749. return 0;
  68750. }
  68751. /* return the number of leading zero digits, from 0 to LIMB_DIGITS */
  68752. static int clz_dec(limb_t a)
  68753. {
  68754. if (a == 0)
  68755. return LIMB_DIGITS;
  68756. switch(LIMB_BITS - 1 - clz(a)) {
  68757. case 0: /* 1-1 */
  68758. return LIMB_DIGITS - 1;
  68759. case 1: /* 2-3 */
  68760. return LIMB_DIGITS - 1;
  68761. case 2: /* 4-7 */
  68762. return LIMB_DIGITS - 1;
  68763. case 3: /* 8-15 */
  68764. if (a < 10)
  68765. return LIMB_DIGITS - 1;
  68766. else
  68767. return LIMB_DIGITS - 2;
  68768. case 4: /* 16-31 */
  68769. return LIMB_DIGITS - 2;
  68770. case 5: /* 32-63 */
  68771. return LIMB_DIGITS - 2;
  68772. case 6: /* 64-127 */
  68773. if (a < 100)
  68774. return LIMB_DIGITS - 2;
  68775. else
  68776. return LIMB_DIGITS - 3;
  68777. case 7: /* 128-255 */
  68778. return LIMB_DIGITS - 3;
  68779. case 8: /* 256-511 */
  68780. return LIMB_DIGITS - 3;
  68781. case 9: /* 512-1023 */
  68782. if (a < 1000)
  68783. return LIMB_DIGITS - 3;
  68784. else
  68785. return LIMB_DIGITS - 4;
  68786. case 10: /* 1024-2047 */
  68787. return LIMB_DIGITS - 4;
  68788. case 11: /* 2048-4095 */
  68789. return LIMB_DIGITS - 4;
  68790. case 12: /* 4096-8191 */
  68791. return LIMB_DIGITS - 4;
  68792. case 13: /* 8192-16383 */
  68793. if (a < 10000)
  68794. return LIMB_DIGITS - 4;
  68795. else
  68796. return LIMB_DIGITS - 5;
  68797. case 14: /* 16384-32767 */
  68798. return LIMB_DIGITS - 5;
  68799. case 15: /* 32768-65535 */
  68800. return LIMB_DIGITS - 5;
  68801. case 16: /* 65536-131071 */
  68802. if (a < 100000)
  68803. return LIMB_DIGITS - 5;
  68804. else
  68805. return LIMB_DIGITS - 6;
  68806. case 17: /* 131072-262143 */
  68807. return LIMB_DIGITS - 6;
  68808. case 18: /* 262144-524287 */
  68809. return LIMB_DIGITS - 6;
  68810. case 19: /* 524288-1048575 */
  68811. if (a < 1000000)
  68812. return LIMB_DIGITS - 6;
  68813. else
  68814. return LIMB_DIGITS - 7;
  68815. case 20: /* 1048576-2097151 */
  68816. return LIMB_DIGITS - 7;
  68817. case 21: /* 2097152-4194303 */
  68818. return LIMB_DIGITS - 7;
  68819. case 22: /* 4194304-8388607 */
  68820. return LIMB_DIGITS - 7;
  68821. case 23: /* 8388608-16777215 */
  68822. if (a < 10000000)
  68823. return LIMB_DIGITS - 7;
  68824. else
  68825. return LIMB_DIGITS - 8;
  68826. case 24: /* 16777216-33554431 */
  68827. return LIMB_DIGITS - 8;
  68828. case 25: /* 33554432-67108863 */
  68829. return LIMB_DIGITS - 8;
  68830. case 26: /* 67108864-134217727 */
  68831. if (a < 100000000)
  68832. return LIMB_DIGITS - 8;
  68833. else
  68834. return LIMB_DIGITS - 9;
  68835. #if LIMB_BITS == 64
  68836. case 27: /* 134217728-268435455 */
  68837. return LIMB_DIGITS - 9;
  68838. case 28: /* 268435456-536870911 */
  68839. return LIMB_DIGITS - 9;
  68840. case 29: /* 536870912-1073741823 */
  68841. if (a < 1000000000)
  68842. return LIMB_DIGITS - 9;
  68843. else
  68844. return LIMB_DIGITS - 10;
  68845. case 30: /* 1073741824-2147483647 */
  68846. return LIMB_DIGITS - 10;
  68847. case 31: /* 2147483648-4294967295 */
  68848. return LIMB_DIGITS - 10;
  68849. case 32: /* 4294967296-8589934591 */
  68850. return LIMB_DIGITS - 10;
  68851. case 33: /* 8589934592-17179869183 */
  68852. if (a < 10000000000)
  68853. return LIMB_DIGITS - 10;
  68854. else
  68855. return LIMB_DIGITS - 11;
  68856. case 34: /* 17179869184-34359738367 */
  68857. return LIMB_DIGITS - 11;
  68858. case 35: /* 34359738368-68719476735 */
  68859. return LIMB_DIGITS - 11;
  68860. case 36: /* 68719476736-137438953471 */
  68861. if (a < 100000000000)
  68862. return LIMB_DIGITS - 11;
  68863. else
  68864. return LIMB_DIGITS - 12;
  68865. case 37: /* 137438953472-274877906943 */
  68866. return LIMB_DIGITS - 12;
  68867. case 38: /* 274877906944-549755813887 */
  68868. return LIMB_DIGITS - 12;
  68869. case 39: /* 549755813888-1099511627775 */
  68870. if (a < 1000000000000)
  68871. return LIMB_DIGITS - 12;
  68872. else
  68873. return LIMB_DIGITS - 13;
  68874. case 40: /* 1099511627776-2199023255551 */
  68875. return LIMB_DIGITS - 13;
  68876. case 41: /* 2199023255552-4398046511103 */
  68877. return LIMB_DIGITS - 13;
  68878. case 42: /* 4398046511104-8796093022207 */
  68879. return LIMB_DIGITS - 13;
  68880. case 43: /* 8796093022208-17592186044415 */
  68881. if (a < 10000000000000)
  68882. return LIMB_DIGITS - 13;
  68883. else
  68884. return LIMB_DIGITS - 14;
  68885. case 44: /* 17592186044416-35184372088831 */
  68886. return LIMB_DIGITS - 14;
  68887. case 45: /* 35184372088832-70368744177663 */
  68888. return LIMB_DIGITS - 14;
  68889. case 46: /* 70368744177664-140737488355327 */
  68890. if (a < 100000000000000)
  68891. return LIMB_DIGITS - 14;
  68892. else
  68893. return LIMB_DIGITS - 15;
  68894. case 47: /* 140737488355328-281474976710655 */
  68895. return LIMB_DIGITS - 15;
  68896. case 48: /* 281474976710656-562949953421311 */
  68897. return LIMB_DIGITS - 15;
  68898. case 49: /* 562949953421312-1125899906842623 */
  68899. if (a < 1000000000000000)
  68900. return LIMB_DIGITS - 15;
  68901. else
  68902. return LIMB_DIGITS - 16;
  68903. case 50: /* 1125899906842624-2251799813685247 */
  68904. return LIMB_DIGITS - 16;
  68905. case 51: /* 2251799813685248-4503599627370495 */
  68906. return LIMB_DIGITS - 16;
  68907. case 52: /* 4503599627370496-9007199254740991 */
  68908. return LIMB_DIGITS - 16;
  68909. case 53: /* 9007199254740992-18014398509481983 */
  68910. if (a < 10000000000000000)
  68911. return LIMB_DIGITS - 16;
  68912. else
  68913. return LIMB_DIGITS - 17;
  68914. case 54: /* 18014398509481984-36028797018963967 */
  68915. return LIMB_DIGITS - 17;
  68916. case 55: /* 36028797018963968-72057594037927935 */
  68917. return LIMB_DIGITS - 17;
  68918. case 56: /* 72057594037927936-144115188075855871 */
  68919. if (a < 100000000000000000)
  68920. return LIMB_DIGITS - 17;
  68921. else
  68922. return LIMB_DIGITS - 18;
  68923. case 57: /* 144115188075855872-288230376151711743 */
  68924. return LIMB_DIGITS - 18;
  68925. case 58: /* 288230376151711744-576460752303423487 */
  68926. return LIMB_DIGITS - 18;
  68927. case 59: /* 576460752303423488-1152921504606846975 */
  68928. if (a < 1000000000000000000)
  68929. return LIMB_DIGITS - 18;
  68930. else
  68931. return LIMB_DIGITS - 19;
  68932. #endif
  68933. default:
  68934. return 0;
  68935. }
  68936. }
  68937. /* for debugging */
  68938. void bfdec_print_str(const char *str, const bfdec_t *a)
  68939. {
  68940. slimb_t i;
  68941. printf("%s=", str);
  68942. if (a->expn == BF_EXP_NAN) {
  68943. printf("NaN");
  68944. } else {
  68945. if (a->sign)
  68946. putchar('-');
  68947. if (a->expn == BF_EXP_ZERO) {
  68948. putchar('0');
  68949. } else if (a->expn == BF_EXP_INF) {
  68950. printf("Inf");
  68951. } else {
  68952. printf("0.");
  68953. for(i = a->len - 1; i >= 0; i--)
  68954. printf("%0*" PRIu_LIMB, LIMB_DIGITS, a->tab[i]);
  68955. printf("e%" PRId_LIMB, a->expn);
  68956. }
  68957. }
  68958. printf("\n");
  68959. }
  68960. /* return != 0 if one digit between 0 and bit_pos inclusive is not zero. */
  68961. static inline limb_t scan_digit_nz(const bfdec_t *r, slimb_t bit_pos)
  68962. {
  68963. slimb_t pos;
  68964. limb_t v, q;
  68965. int shift;
  68966. if (bit_pos < 0)
  68967. return 0;
  68968. pos = (limb_t)bit_pos / LIMB_DIGITS;
  68969. shift = (limb_t)bit_pos % LIMB_DIGITS;
  68970. fast_shr_rem_dec(q, v, r->tab[pos], shift + 1);
  68971. (void)q;
  68972. if (v != 0)
  68973. return 1;
  68974. pos--;
  68975. while (pos >= 0) {
  68976. if (r->tab[pos] != 0)
  68977. return 1;
  68978. pos--;
  68979. }
  68980. return 0;
  68981. }
  68982. static limb_t get_digit(const limb_t *tab, limb_t len, slimb_t pos)
  68983. {
  68984. slimb_t i;
  68985. int shift;
  68986. i = floor_div(pos, LIMB_DIGITS);
  68987. if (i < 0 || i >= len)
  68988. return 0;
  68989. shift = pos - i * LIMB_DIGITS;
  68990. return fast_shr_dec(tab[i], shift) % 10;
  68991. }
  68992. /* return the addend for rounding. Note that prec can be <= 0 for bf_rint() */
  68993. static int bfdec_get_rnd_add(int *pret, const bfdec_t *r, limb_t l,
  68994. slimb_t prec, int rnd_mode)
  68995. {
  68996. int add_one, inexact;
  68997. limb_t digit1, digit0;
  68998. // bfdec_print_str("get_rnd_add", r);
  68999. if (rnd_mode == BF_RNDF) {
  69000. digit0 = 1; /* faithful rounding does not honor the INEXACT flag */
  69001. } else {
  69002. /* starting limb for bit 'prec + 1' */
  69003. digit0 = scan_digit_nz(r, l * LIMB_DIGITS - 1 - bf_max(0, prec + 1));
  69004. }
  69005. /* get the digit at 'prec' */
  69006. digit1 = get_digit(r->tab, l, l * LIMB_DIGITS - 1 - prec);
  69007. inexact = (digit1 | digit0) != 0;
  69008. add_one = 0;
  69009. switch(rnd_mode) {
  69010. case BF_RNDZ:
  69011. break;
  69012. case BF_RNDN:
  69013. if (digit1 == 5) {
  69014. if (digit0) {
  69015. add_one = 1;
  69016. } else {
  69017. /* round to even */
  69018. add_one =
  69019. get_digit(r->tab, l, l * LIMB_DIGITS - 1 - (prec - 1)) & 1;
  69020. }
  69021. } else if (digit1 > 5) {
  69022. add_one = 1;
  69023. }
  69024. break;
  69025. case BF_RNDD:
  69026. case BF_RNDU:
  69027. if (r->sign == (rnd_mode == BF_RNDD))
  69028. add_one = inexact;
  69029. break;
  69030. case BF_RNDNA:
  69031. case BF_RNDF:
  69032. add_one = (digit1 >= 5);
  69033. break;
  69034. case BF_RNDA:
  69035. add_one = inexact;
  69036. break;
  69037. default:
  69038. abort();
  69039. }
  69040. if (inexact)
  69041. *pret |= BF_ST_INEXACT;
  69042. return add_one;
  69043. }
  69044. /* round to prec1 bits assuming 'r' is non zero and finite. 'r' is
  69045. assumed to have length 'l' (1 <= l <= r->len). prec1 can be
  69046. BF_PREC_INF. BF_FLAG_SUBNORMAL is not supported. Cannot fail with
  69047. BF_ST_MEM_ERROR.
  69048. */
  69049. static int __bfdec_round(bfdec_t *r, limb_t prec1, bf_flags_t flags, limb_t l)
  69050. {
  69051. int shift, add_one, rnd_mode, ret;
  69052. slimb_t i, bit_pos, pos, e_min, e_max, e_range, prec;
  69053. /* XXX: align to IEEE 754 2008 for decimal numbers ? */
  69054. e_range = (limb_t)1 << (bf_get_exp_bits(flags) - 1);
  69055. e_min = -e_range + 3;
  69056. e_max = e_range;
  69057. if (flags & BF_FLAG_RADPNT_PREC) {
  69058. /* 'prec' is the precision after the decimal point */
  69059. if (prec1 != BF_PREC_INF)
  69060. prec = r->expn + prec1;
  69061. else
  69062. prec = prec1;
  69063. } else if (unlikely(r->expn < e_min) && (flags & BF_FLAG_SUBNORMAL)) {
  69064. /* restrict the precision in case of potentially subnormal
  69065. result */
  69066. assert(prec1 != BF_PREC_INF);
  69067. prec = prec1 - (e_min - r->expn);
  69068. } else {
  69069. prec = prec1;
  69070. }
  69071. /* round to prec bits */
  69072. rnd_mode = flags & BF_RND_MASK;
  69073. ret = 0;
  69074. add_one = bfdec_get_rnd_add(&ret, r, l, prec, rnd_mode);
  69075. if (prec <= 0) {
  69076. if (add_one) {
  69077. bfdec_resize(r, 1); /* cannot fail because r is non zero */
  69078. r->tab[0] = BF_DEC_BASE / 10;
  69079. r->expn += 1 - prec;
  69080. ret |= BF_ST_UNDERFLOW | BF_ST_INEXACT;
  69081. return ret;
  69082. } else {
  69083. goto underflow;
  69084. }
  69085. } else if (add_one) {
  69086. limb_t carry;
  69087. /* add one starting at digit 'prec - 1' */
  69088. bit_pos = l * LIMB_DIGITS - 1 - (prec - 1);
  69089. pos = bit_pos / LIMB_DIGITS;
  69090. carry = mp_pow_dec[bit_pos % LIMB_DIGITS];
  69091. carry = mp_add_ui_dec(r->tab + pos, carry, l - pos);
  69092. if (carry) {
  69093. /* shift right by one digit */
  69094. mp_shr_dec(r->tab + pos, r->tab + pos, l - pos, 1, 1);
  69095. r->expn++;
  69096. }
  69097. }
  69098. /* check underflow */
  69099. if (unlikely(r->expn < e_min)) {
  69100. if (flags & BF_FLAG_SUBNORMAL) {
  69101. /* if inexact, also set the underflow flag */
  69102. if (ret & BF_ST_INEXACT)
  69103. ret |= BF_ST_UNDERFLOW;
  69104. } else {
  69105. underflow:
  69106. bfdec_set_zero(r, r->sign);
  69107. ret |= BF_ST_UNDERFLOW | BF_ST_INEXACT;
  69108. return ret;
  69109. }
  69110. }
  69111. /* check overflow */
  69112. if (unlikely(r->expn > e_max)) {
  69113. bfdec_set_inf(r, r->sign);
  69114. ret |= BF_ST_OVERFLOW | BF_ST_INEXACT;
  69115. return ret;
  69116. }
  69117. /* keep the bits starting at 'prec - 1' */
  69118. bit_pos = l * LIMB_DIGITS - 1 - (prec - 1);
  69119. i = floor_div(bit_pos, LIMB_DIGITS);
  69120. if (i >= 0) {
  69121. shift = smod(bit_pos, LIMB_DIGITS);
  69122. if (shift != 0) {
  69123. r->tab[i] = fast_shr_dec(r->tab[i], shift) *
  69124. mp_pow_dec[shift];
  69125. }
  69126. } else {
  69127. i = 0;
  69128. }
  69129. /* remove trailing zeros */
  69130. while (r->tab[i] == 0)
  69131. i++;
  69132. if (i > 0) {
  69133. l -= i;
  69134. memmove(r->tab, r->tab + i, l * sizeof(limb_t));
  69135. }
  69136. bfdec_resize(r, l); /* cannot fail */
  69137. return ret;
  69138. }
  69139. /* Cannot fail with BF_ST_MEM_ERROR. */
  69140. int bfdec_round(bfdec_t *r, limb_t prec, bf_flags_t flags)
  69141. {
  69142. if (r->len == 0)
  69143. return 0;
  69144. return __bfdec_round(r, prec, flags, r->len);
  69145. }
  69146. /* 'r' must be a finite number. Cannot fail with BF_ST_MEM_ERROR. */
  69147. int bfdec_normalize_and_round(bfdec_t *r, limb_t prec1, bf_flags_t flags)
  69148. {
  69149. limb_t l, v;
  69150. int shift, ret;
  69151. // bfdec_print_str("bf_renorm", r);
  69152. l = r->len;
  69153. while (l > 0 && r->tab[l - 1] == 0)
  69154. l--;
  69155. if (l == 0) {
  69156. /* zero */
  69157. r->expn = BF_EXP_ZERO;
  69158. bfdec_resize(r, 0); /* cannot fail */
  69159. ret = 0;
  69160. } else {
  69161. r->expn -= (r->len - l) * LIMB_DIGITS;
  69162. /* shift to have the MSB set to '1' */
  69163. v = r->tab[l - 1];
  69164. shift = clz_dec(v);
  69165. if (shift != 0) {
  69166. mp_shl_dec(r->tab, r->tab, l, shift, 0);
  69167. r->expn -= shift;
  69168. }
  69169. ret = __bfdec_round(r, prec1, flags, l);
  69170. }
  69171. // bf_print_str("r_final", r);
  69172. return ret;
  69173. }
  69174. int bfdec_set_ui(bfdec_t *r, uint64_t v)
  69175. {
  69176. #if LIMB_BITS == 32
  69177. if (v >= BF_DEC_BASE * BF_DEC_BASE) {
  69178. if (bfdec_resize(r, 3))
  69179. goto fail;
  69180. r->tab[0] = v % BF_DEC_BASE;
  69181. v /= BF_DEC_BASE;
  69182. r->tab[1] = v % BF_DEC_BASE;
  69183. r->tab[2] = v / BF_DEC_BASE;
  69184. r->expn = 3 * LIMB_DIGITS;
  69185. } else
  69186. #endif
  69187. if (v >= BF_DEC_BASE) {
  69188. if (bfdec_resize(r, 2))
  69189. goto fail;
  69190. r->tab[0] = v % BF_DEC_BASE;
  69191. r->tab[1] = v / BF_DEC_BASE;
  69192. r->expn = 2 * LIMB_DIGITS;
  69193. } else {
  69194. if (bfdec_resize(r, 1))
  69195. goto fail;
  69196. r->tab[0] = v;
  69197. r->expn = LIMB_DIGITS;
  69198. }
  69199. r->sign = 0;
  69200. return bfdec_normalize_and_round(r, BF_PREC_INF, 0);
  69201. fail:
  69202. bfdec_set_nan(r);
  69203. return BF_ST_MEM_ERROR;
  69204. }
  69205. int bfdec_set_si(bfdec_t *r, int64_t v)
  69206. {
  69207. int ret;
  69208. if (v < 0) {
  69209. ret = bfdec_set_ui(r, -v);
  69210. r->sign = 1;
  69211. } else {
  69212. ret = bfdec_set_ui(r, v);
  69213. }
  69214. return ret;
  69215. }
  69216. static int bfdec_add_internal(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec, bf_flags_t flags, int b_neg)
  69217. {
  69218. bf_context_t *s = r->ctx;
  69219. int is_sub, cmp_res, a_sign, b_sign, ret;
  69220. a_sign = a->sign;
  69221. b_sign = b->sign ^ b_neg;
  69222. is_sub = a_sign ^ b_sign;
  69223. cmp_res = bfdec_cmpu(a, b);
  69224. if (cmp_res < 0) {
  69225. const bfdec_t *tmp;
  69226. tmp = a;
  69227. a = b;
  69228. b = tmp;
  69229. a_sign = b_sign; /* b_sign is never used later */
  69230. }
  69231. /* abs(a) >= abs(b) */
  69232. if (cmp_res == 0 && is_sub && a->expn < BF_EXP_INF) {
  69233. /* zero result */
  69234. bfdec_set_zero(r, (flags & BF_RND_MASK) == BF_RNDD);
  69235. ret = 0;
  69236. } else if (a->len == 0 || b->len == 0) {
  69237. ret = 0;
  69238. if (a->expn >= BF_EXP_INF) {
  69239. if (a->expn == BF_EXP_NAN) {
  69240. /* at least one operand is NaN */
  69241. bfdec_set_nan(r);
  69242. ret = 0;
  69243. } else if (b->expn == BF_EXP_INF && is_sub) {
  69244. /* infinities with different signs */
  69245. bfdec_set_nan(r);
  69246. ret = BF_ST_INVALID_OP;
  69247. } else {
  69248. bfdec_set_inf(r, a_sign);
  69249. }
  69250. } else {
  69251. /* at least one zero and not subtract */
  69252. if (bfdec_set(r, a))
  69253. return BF_ST_MEM_ERROR;
  69254. r->sign = a_sign;
  69255. goto renorm;
  69256. }
  69257. } else {
  69258. slimb_t d, a_offset, b_offset, i, r_len;
  69259. limb_t carry;
  69260. limb_t *b1_tab;
  69261. int b_shift;
  69262. mp_size_t b1_len;
  69263. d = a->expn - b->expn;
  69264. /* XXX: not efficient in time and memory if the precision is
  69265. not infinite */
  69266. r_len = bf_max(a->len, b->len + (d + LIMB_DIGITS - 1) / LIMB_DIGITS);
  69267. if (bfdec_resize(r, r_len))
  69268. goto fail;
  69269. r->sign = a_sign;
  69270. r->expn = a->expn;
  69271. a_offset = r_len - a->len;
  69272. for(i = 0; i < a_offset; i++)
  69273. r->tab[i] = 0;
  69274. for(i = 0; i < a->len; i++)
  69275. r->tab[a_offset + i] = a->tab[i];
  69276. b_shift = d % LIMB_DIGITS;
  69277. if (b_shift == 0) {
  69278. b1_len = b->len;
  69279. b1_tab = (limb_t *)b->tab;
  69280. } else {
  69281. b1_len = b->len + 1;
  69282. b1_tab = bf_malloc(s, sizeof(limb_t) * b1_len);
  69283. if (!b1_tab)
  69284. goto fail;
  69285. b1_tab[0] = mp_shr_dec(b1_tab + 1, b->tab, b->len, b_shift, 0) *
  69286. mp_pow_dec[LIMB_DIGITS - b_shift];
  69287. }
  69288. b_offset = r_len - (b->len + (d + LIMB_DIGITS - 1) / LIMB_DIGITS);
  69289. if (is_sub) {
  69290. carry = mp_sub_dec(r->tab + b_offset, r->tab + b_offset,
  69291. b1_tab, b1_len, 0);
  69292. if (carry != 0) {
  69293. carry = mp_sub_ui_dec(r->tab + b_offset + b1_len, carry,
  69294. r_len - (b_offset + b1_len));
  69295. assert(carry == 0);
  69296. }
  69297. } else {
  69298. carry = mp_add_dec(r->tab + b_offset, r->tab + b_offset,
  69299. b1_tab, b1_len, 0);
  69300. if (carry != 0) {
  69301. carry = mp_add_ui_dec(r->tab + b_offset + b1_len, carry,
  69302. r_len - (b_offset + b1_len));
  69303. }
  69304. if (carry != 0) {
  69305. if (bfdec_resize(r, r_len + 1)) {
  69306. if (b_shift != 0)
  69307. bf_free(s, b1_tab);
  69308. goto fail;
  69309. }
  69310. r->tab[r_len] = 1;
  69311. r->expn += LIMB_DIGITS;
  69312. }
  69313. }
  69314. if (b_shift != 0)
  69315. bf_free(s, b1_tab);
  69316. renorm:
  69317. ret = bfdec_normalize_and_round(r, prec, flags);
  69318. }
  69319. return ret;
  69320. fail:
  69321. bfdec_set_nan(r);
  69322. return BF_ST_MEM_ERROR;
  69323. }
  69324. static int __bfdec_add(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,
  69325. bf_flags_t flags)
  69326. {
  69327. return bfdec_add_internal(r, a, b, prec, flags, 0);
  69328. }
  69329. static int __bfdec_sub(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,
  69330. bf_flags_t flags)
  69331. {
  69332. return bfdec_add_internal(r, a, b, prec, flags, 1);
  69333. }
  69334. int bfdec_add(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,
  69335. bf_flags_t flags)
  69336. {
  69337. return bf_op2((bf_t *)r, (bf_t *)a, (bf_t *)b, prec, flags,
  69338. (bf_op2_func_t *)__bfdec_add);
  69339. }
  69340. int bfdec_sub(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,
  69341. bf_flags_t flags)
  69342. {
  69343. return bf_op2((bf_t *)r, (bf_t *)a, (bf_t *)b, prec, flags,
  69344. (bf_op2_func_t *)__bfdec_sub);
  69345. }
  69346. int bfdec_mul(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,
  69347. bf_flags_t flags)
  69348. {
  69349. int ret, r_sign;
  69350. if (a->len < b->len) {
  69351. const bfdec_t *tmp = a;
  69352. a = b;
  69353. b = tmp;
  69354. }
  69355. r_sign = a->sign ^ b->sign;
  69356. /* here b->len <= a->len */
  69357. if (b->len == 0) {
  69358. if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) {
  69359. bfdec_set_nan(r);
  69360. ret = 0;
  69361. } else if (a->expn == BF_EXP_INF || b->expn == BF_EXP_INF) {
  69362. if ((a->expn == BF_EXP_INF && b->expn == BF_EXP_ZERO) ||
  69363. (a->expn == BF_EXP_ZERO && b->expn == BF_EXP_INF)) {
  69364. bfdec_set_nan(r);
  69365. ret = BF_ST_INVALID_OP;
  69366. } else {
  69367. bfdec_set_inf(r, r_sign);
  69368. ret = 0;
  69369. }
  69370. } else {
  69371. bfdec_set_zero(r, r_sign);
  69372. ret = 0;
  69373. }
  69374. } else {
  69375. bfdec_t tmp, *r1 = NULL;
  69376. limb_t a_len, b_len;
  69377. limb_t *a_tab, *b_tab;
  69378. a_len = a->len;
  69379. b_len = b->len;
  69380. a_tab = a->tab;
  69381. b_tab = b->tab;
  69382. if (r == a || r == b) {
  69383. bfdec_init(r->ctx, &tmp);
  69384. r1 = r;
  69385. r = &tmp;
  69386. }
  69387. if (bfdec_resize(r, a_len + b_len)) {
  69388. bfdec_set_nan(r);
  69389. ret = BF_ST_MEM_ERROR;
  69390. goto done;
  69391. }
  69392. mp_mul_basecase_dec(r->tab, a_tab, a_len, b_tab, b_len);
  69393. r->sign = r_sign;
  69394. r->expn = a->expn + b->expn;
  69395. ret = bfdec_normalize_and_round(r, prec, flags);
  69396. done:
  69397. if (r == &tmp)
  69398. bfdec_move(r1, &tmp);
  69399. }
  69400. return ret;
  69401. }
  69402. int bfdec_mul_si(bfdec_t *r, const bfdec_t *a, int64_t b1, limb_t prec,
  69403. bf_flags_t flags)
  69404. {
  69405. bfdec_t b;
  69406. int ret;
  69407. bfdec_init(r->ctx, &b);
  69408. ret = bfdec_set_si(&b, b1);
  69409. ret |= bfdec_mul(r, a, &b, prec, flags);
  69410. bfdec_delete(&b);
  69411. return ret;
  69412. }
  69413. int bfdec_add_si(bfdec_t *r, const bfdec_t *a, int64_t b1, limb_t prec,
  69414. bf_flags_t flags)
  69415. {
  69416. bfdec_t b;
  69417. int ret;
  69418. bfdec_init(r->ctx, &b);
  69419. ret = bfdec_set_si(&b, b1);
  69420. ret |= bfdec_add(r, a, &b, prec, flags);
  69421. bfdec_delete(&b);
  69422. return ret;
  69423. }
  69424. static int __bfdec_div(bfdec_t *r, const bfdec_t *a, const bfdec_t *b,
  69425. limb_t prec, bf_flags_t flags)
  69426. {
  69427. int ret, r_sign;
  69428. limb_t n, nb, precl;
  69429. r_sign = a->sign ^ b->sign;
  69430. if (a->expn >= BF_EXP_INF || b->expn >= BF_EXP_INF) {
  69431. if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) {
  69432. bfdec_set_nan(r);
  69433. return 0;
  69434. } else if (a->expn == BF_EXP_INF && b->expn == BF_EXP_INF) {
  69435. bfdec_set_nan(r);
  69436. return BF_ST_INVALID_OP;
  69437. } else if (a->expn == BF_EXP_INF) {
  69438. bfdec_set_inf(r, r_sign);
  69439. return 0;
  69440. } else {
  69441. bfdec_set_zero(r, r_sign);
  69442. return 0;
  69443. }
  69444. } else if (a->expn == BF_EXP_ZERO) {
  69445. if (b->expn == BF_EXP_ZERO) {
  69446. bfdec_set_nan(r);
  69447. return BF_ST_INVALID_OP;
  69448. } else {
  69449. bfdec_set_zero(r, r_sign);
  69450. return 0;
  69451. }
  69452. } else if (b->expn == BF_EXP_ZERO) {
  69453. bfdec_set_inf(r, r_sign);
  69454. return BF_ST_DIVIDE_ZERO;
  69455. }
  69456. nb = b->len;
  69457. if (prec == BF_PREC_INF) {
  69458. /* infinite precision: return BF_ST_INVALID_OP if not an exact
  69459. result */
  69460. /* XXX: check */
  69461. precl = nb + 1;
  69462. } else if (flags & BF_FLAG_RADPNT_PREC) {
  69463. /* number of digits after the decimal point */
  69464. /* XXX: check (2 extra digits for rounding + 2 digits) */
  69465. precl = (bf_max(a->expn - b->expn, 0) + 2 +
  69466. prec + 2 + LIMB_DIGITS - 1) / LIMB_DIGITS;
  69467. } else {
  69468. /* number of limbs of the quotient (2 extra digits for rounding) */
  69469. precl = (prec + 2 + LIMB_DIGITS - 1) / LIMB_DIGITS;
  69470. }
  69471. n = bf_max(a->len, precl);
  69472. {
  69473. limb_t *taba, na, i;
  69474. slimb_t d;
  69475. na = n + nb;
  69476. taba = bf_malloc(r->ctx, (na + 1) * sizeof(limb_t));
  69477. if (!taba)
  69478. goto fail;
  69479. d = na - a->len;
  69480. memset(taba, 0, d * sizeof(limb_t));
  69481. memcpy(taba + d, a->tab, a->len * sizeof(limb_t));
  69482. if (bfdec_resize(r, n + 1))
  69483. goto fail1;
  69484. if (mp_div_dec(r->ctx, r->tab, taba, na, b->tab, nb)) {
  69485. fail1:
  69486. bf_free(r->ctx, taba);
  69487. goto fail;
  69488. }
  69489. /* see if non zero remainder */
  69490. for(i = 0; i < nb; i++) {
  69491. if (taba[i] != 0)
  69492. break;
  69493. }
  69494. bf_free(r->ctx, taba);
  69495. if (i != nb) {
  69496. if (prec == BF_PREC_INF) {
  69497. bfdec_set_nan(r);
  69498. return BF_ST_INVALID_OP;
  69499. } else {
  69500. r->tab[0] |= 1;
  69501. }
  69502. }
  69503. r->expn = a->expn - b->expn + LIMB_DIGITS;
  69504. r->sign = r_sign;
  69505. ret = bfdec_normalize_and_round(r, prec, flags);
  69506. }
  69507. return ret;
  69508. fail:
  69509. bfdec_set_nan(r);
  69510. return BF_ST_MEM_ERROR;
  69511. }
  69512. int bfdec_div(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,
  69513. bf_flags_t flags)
  69514. {
  69515. return bf_op2((bf_t *)r, (bf_t *)a, (bf_t *)b, prec, flags,
  69516. (bf_op2_func_t *)__bfdec_div);
  69517. }
  69518. /* a and b must be finite numbers with a >= 0 and b > 0. 'q' is the
  69519. integer defined as floor(a/b) and r = a - q * b. */
  69520. static void bfdec_tdivremu(bf_context_t *s, bfdec_t *q, bfdec_t *r,
  69521. const bfdec_t *a, const bfdec_t *b)
  69522. {
  69523. if (bfdec_cmpu(a, b) < 0) {
  69524. bfdec_set_ui(q, 0);
  69525. bfdec_set(r, a);
  69526. } else {
  69527. bfdec_div(q, a, b, 0, BF_RNDZ | BF_FLAG_RADPNT_PREC);
  69528. bfdec_mul(r, q, b, BF_PREC_INF, BF_RNDZ);
  69529. bfdec_sub(r, a, r, BF_PREC_INF, BF_RNDZ);
  69530. }
  69531. }
  69532. /* division and remainder.
  69533. rnd_mode is the rounding mode for the quotient. The additional
  69534. rounding mode BF_RND_EUCLIDIAN is supported.
  69535. 'q' is an integer. 'r' is rounded with prec and flags (prec can be
  69536. BF_PREC_INF).
  69537. */
  69538. int bfdec_divrem(bfdec_t *q, bfdec_t *r, const bfdec_t *a, const bfdec_t *b,
  69539. limb_t prec, bf_flags_t flags, int rnd_mode)
  69540. {
  69541. bf_context_t *s = q->ctx;
  69542. bfdec_t a1_s, *a1 = &a1_s;
  69543. bfdec_t b1_s, *b1 = &b1_s;
  69544. bfdec_t r1_s, *r1 = &r1_s;
  69545. int q_sign, res;
  69546. bool is_ceil, is_rndn;
  69547. assert(q != a && q != b);
  69548. assert(r != a && r != b);
  69549. assert(q != r);
  69550. if (a->len == 0 || b->len == 0) {
  69551. bfdec_set_zero(q, 0);
  69552. if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) {
  69553. bfdec_set_nan(r);
  69554. return 0;
  69555. } else if (a->expn == BF_EXP_INF || b->expn == BF_EXP_ZERO) {
  69556. bfdec_set_nan(r);
  69557. return BF_ST_INVALID_OP;
  69558. } else {
  69559. bfdec_set(r, a);
  69560. return bfdec_round(r, prec, flags);
  69561. }
  69562. }
  69563. q_sign = a->sign ^ b->sign;
  69564. is_rndn = (rnd_mode == BF_RNDN || rnd_mode == BF_RNDNA);
  69565. switch(rnd_mode) {
  69566. default:
  69567. case BF_RNDZ:
  69568. case BF_RNDN:
  69569. case BF_RNDNA:
  69570. is_ceil = false;
  69571. break;
  69572. case BF_RNDD:
  69573. is_ceil = q_sign;
  69574. break;
  69575. case BF_RNDU:
  69576. is_ceil = q_sign ^ 1;
  69577. break;
  69578. case BF_RNDA:
  69579. is_ceil = true;
  69580. break;
  69581. case BF_DIVREM_EUCLIDIAN:
  69582. is_ceil = a->sign;
  69583. break;
  69584. }
  69585. a1->expn = a->expn;
  69586. a1->tab = a->tab;
  69587. a1->len = a->len;
  69588. a1->sign = 0;
  69589. b1->expn = b->expn;
  69590. b1->tab = b->tab;
  69591. b1->len = b->len;
  69592. b1->sign = 0;
  69593. // bfdec_print_str("a1", a1);
  69594. // bfdec_print_str("b1", b1);
  69595. /* XXX: could improve to avoid having a large 'q' */
  69596. bfdec_tdivremu(s, q, r, a1, b1);
  69597. if (bfdec_is_nan(q) || bfdec_is_nan(r))
  69598. goto fail;
  69599. // bfdec_print_str("q", q);
  69600. // bfdec_print_str("r", r);
  69601. if (r->len != 0) {
  69602. if (is_rndn) {
  69603. bfdec_init(s, r1);
  69604. if (bfdec_set(r1, r))
  69605. goto fail;
  69606. if (bfdec_mul_si(r1, r1, 2, BF_PREC_INF, BF_RNDZ)) {
  69607. bfdec_delete(r1);
  69608. goto fail;
  69609. }
  69610. res = bfdec_cmpu(r1, b);
  69611. bfdec_delete(r1);
  69612. if (res > 0 ||
  69613. (res == 0 &&
  69614. (rnd_mode == BF_RNDNA ||
  69615. (get_digit(q->tab, q->len, q->len * LIMB_DIGITS - q->expn) & 1) != 0))) {
  69616. goto do_sub_r;
  69617. }
  69618. } else if (is_ceil) {
  69619. do_sub_r:
  69620. res = bfdec_add_si(q, q, 1, BF_PREC_INF, BF_RNDZ);
  69621. res |= bfdec_sub(r, r, b1, BF_PREC_INF, BF_RNDZ);
  69622. if (res & BF_ST_MEM_ERROR)
  69623. goto fail;
  69624. }
  69625. }
  69626. r->sign ^= a->sign;
  69627. q->sign = q_sign;
  69628. return bfdec_round(r, prec, flags);
  69629. fail:
  69630. bfdec_set_nan(q);
  69631. bfdec_set_nan(r);
  69632. return BF_ST_MEM_ERROR;
  69633. }
  69634. int bfdec_rem(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,
  69635. bf_flags_t flags, int rnd_mode)
  69636. {
  69637. bfdec_t q_s, *q = &q_s;
  69638. int ret;
  69639. bfdec_init(r->ctx, q);
  69640. ret = bfdec_divrem(q, r, a, b, prec, flags, rnd_mode);
  69641. bfdec_delete(q);
  69642. return ret;
  69643. }
  69644. /* convert to integer (infinite precision) */
  69645. int bfdec_rint(bfdec_t *r, int rnd_mode)
  69646. {
  69647. return bfdec_round(r, 0, rnd_mode | BF_FLAG_RADPNT_PREC);
  69648. }
  69649. int bfdec_sqrt(bfdec_t *r, const bfdec_t *a, limb_t prec, bf_flags_t flags)
  69650. {
  69651. bf_context_t *s = a->ctx;
  69652. int ret, k;
  69653. limb_t *a1, v;
  69654. slimb_t n, n1, prec1;
  69655. limb_t res;
  69656. assert(r != a);
  69657. if (a->len == 0) {
  69658. if (a->expn == BF_EXP_NAN) {
  69659. bfdec_set_nan(r);
  69660. } else if (a->expn == BF_EXP_INF && a->sign) {
  69661. goto invalid_op;
  69662. } else {
  69663. bfdec_set(r, a);
  69664. }
  69665. ret = 0;
  69666. } else if (a->sign || prec == BF_PREC_INF) {
  69667. invalid_op:
  69668. bfdec_set_nan(r);
  69669. ret = BF_ST_INVALID_OP;
  69670. } else {
  69671. if (flags & BF_FLAG_RADPNT_PREC) {
  69672. prec1 = bf_max(floor_div(a->expn + 1, 2) + prec, 1);
  69673. } else {
  69674. prec1 = prec;
  69675. }
  69676. /* convert the mantissa to an integer with at least 2 *
  69677. prec + 4 digits */
  69678. n = (2 * (prec1 + 2) + 2 * LIMB_DIGITS - 1) / (2 * LIMB_DIGITS);
  69679. if (bfdec_resize(r, n))
  69680. goto fail;
  69681. a1 = bf_malloc(s, sizeof(limb_t) * 2 * n);
  69682. if (!a1)
  69683. goto fail;
  69684. n1 = bf_min(2 * n, a->len);
  69685. memset(a1, 0, (2 * n - n1) * sizeof(limb_t));
  69686. memcpy(a1 + 2 * n - n1, a->tab + a->len - n1, n1 * sizeof(limb_t));
  69687. if (a->expn & 1) {
  69688. res = mp_shr_dec(a1, a1, 2 * n, 1, 0);
  69689. } else {
  69690. res = 0;
  69691. }
  69692. /* normalize so that a1 >= B^(2*n)/4. Not need for n = 1
  69693. because mp_sqrtrem2_dec already does it */
  69694. k = 0;
  69695. if (n > 1) {
  69696. v = a1[2 * n - 1];
  69697. while (v < BF_DEC_BASE / 4) {
  69698. k++;
  69699. v *= 4;
  69700. }
  69701. if (k != 0)
  69702. mp_mul1_dec(a1, a1, 2 * n, 1 << (2 * k), 0);
  69703. }
  69704. if (mp_sqrtrem_dec(s, r->tab, a1, n)) {
  69705. bf_free(s, a1);
  69706. goto fail;
  69707. }
  69708. if (k != 0)
  69709. mp_div1_dec(r->tab, r->tab, n, 1 << k, 0);
  69710. if (!res) {
  69711. res = mp_scan_nz(a1, n + 1);
  69712. }
  69713. bf_free(s, a1);
  69714. if (!res) {
  69715. res = mp_scan_nz(a->tab, a->len - n1);
  69716. }
  69717. if (res != 0)
  69718. r->tab[0] |= 1;
  69719. r->sign = 0;
  69720. r->expn = (a->expn + 1) >> 1;
  69721. ret = bfdec_round(r, prec, flags);
  69722. }
  69723. return ret;
  69724. fail:
  69725. bfdec_set_nan(r);
  69726. return BF_ST_MEM_ERROR;
  69727. }
  69728. /* The rounding mode is always BF_RNDZ. Return BF_ST_OVERFLOW if there
  69729. is an overflow and 0 otherwise. No memory error is possible. */
  69730. int bfdec_get_int32(int *pres, const bfdec_t *a)
  69731. {
  69732. uint32_t v;
  69733. int ret;
  69734. if (a->expn >= BF_EXP_INF) {
  69735. ret = 0;
  69736. if (a->expn == BF_EXP_INF) {
  69737. v = (uint32_t)INT32_MAX + a->sign;
  69738. /* XXX: return overflow ? */
  69739. } else {
  69740. v = INT32_MAX;
  69741. }
  69742. } else if (a->expn <= 0) {
  69743. v = 0;
  69744. ret = 0;
  69745. } else if (a->expn <= 9) {
  69746. v = fast_shr_dec(a->tab[a->len - 1], LIMB_DIGITS - a->expn);
  69747. if (a->sign)
  69748. v = -v;
  69749. ret = 0;
  69750. } else if (a->expn == 10) {
  69751. uint64_t v1;
  69752. uint32_t v_max;
  69753. #if LIMB_BITS == 64
  69754. v1 = fast_shr_dec(a->tab[a->len - 1], LIMB_DIGITS - a->expn);
  69755. #else
  69756. v1 = (uint64_t)a->tab[a->len - 1] * 10 +
  69757. get_digit(a->tab, a->len, (a->len - 1) * LIMB_DIGITS - 1);
  69758. #endif
  69759. v_max = (uint32_t)INT32_MAX + a->sign;
  69760. if (v1 > v_max) {
  69761. v = v_max;
  69762. ret = BF_ST_OVERFLOW;
  69763. } else {
  69764. v = v1;
  69765. if (a->sign)
  69766. v = -v;
  69767. ret = 0;
  69768. }
  69769. } else {
  69770. v = (uint32_t)INT32_MAX + a->sign;
  69771. ret = BF_ST_OVERFLOW;
  69772. }
  69773. *pres = v;
  69774. return ret;
  69775. }
  69776. /* power to an integer with infinite precision */
  69777. int bfdec_pow_ui(bfdec_t *r, const bfdec_t *a, limb_t b)
  69778. {
  69779. int ret, n_bits, i;
  69780. assert(r != a);
  69781. if (b == 0)
  69782. return bfdec_set_ui(r, 1);
  69783. ret = bfdec_set(r, a);
  69784. n_bits = LIMB_BITS - clz(b);
  69785. for(i = n_bits - 2; i >= 0; i--) {
  69786. ret |= bfdec_mul(r, r, r, BF_PREC_INF, BF_RNDZ);
  69787. if ((b >> i) & 1)
  69788. ret |= bfdec_mul(r, r, a, BF_PREC_INF, BF_RNDZ);
  69789. }
  69790. return ret;
  69791. }
  69792. char *bfdec_ftoa(size_t *plen, const bfdec_t *a, limb_t prec, bf_flags_t flags)
  69793. {
  69794. return bf_ftoa_internal(plen, (const bf_t *)a, 10, prec, flags, true);
  69795. }
  69796. int bfdec_atof(bfdec_t *r, const char *str, const char **pnext,
  69797. limb_t prec, bf_flags_t flags)
  69798. {
  69799. slimb_t dummy_exp;
  69800. return bf_atof_internal((bf_t *)r, &dummy_exp, str, pnext, 10, prec,
  69801. flags, true);
  69802. }
  69803. #endif /* USE_BF_DEC */
  69804. #ifdef USE_FFT_MUL
  69805. /***************************************************************/
  69806. /* Integer multiplication with FFT */
  69807. /* or LIMB_BITS at bit position 'pos' in tab */
  69808. static inline void put_bits(limb_t *tab, limb_t len, slimb_t pos, limb_t val)
  69809. {
  69810. limb_t i;
  69811. int p;
  69812. i = pos >> LIMB_LOG2_BITS;
  69813. p = pos & (LIMB_BITS - 1);
  69814. if (i < len)
  69815. tab[i] |= val << p;
  69816. if (p != 0) {
  69817. i++;
  69818. if (i < len) {
  69819. tab[i] |= val >> (LIMB_BITS - p);
  69820. }
  69821. }
  69822. }
  69823. #if defined(__AVX2__)
  69824. typedef double NTTLimb;
  69825. /* we must have: modulo >= 1 << NTT_MOD_LOG2_MIN */
  69826. #define NTT_MOD_LOG2_MIN 50
  69827. #define NTT_MOD_LOG2_MAX 51
  69828. #define NB_MODS 5
  69829. #define NTT_PROOT_2EXP 39
  69830. static const int ntt_int_bits[NB_MODS] = { 254, 203, 152, 101, 50, };
  69831. static const limb_t ntt_mods[NB_MODS] = { 0x00073a8000000001, 0x0007858000000001, 0x0007a38000000001, 0x0007a68000000001, 0x0007fd8000000001,
  69832. };
  69833. static const limb_t ntt_proot[2][NB_MODS] = {
  69834. { 0x00056198d44332c8, 0x0002eb5d640aad39, 0x00047e31eaa35fd0, 0x0005271ac118a150, 0x00075e0ce8442bd5, },
  69835. { 0x000461169761bcc5, 0x0002dac3cb2da688, 0x0004abc97751e3bf, 0x000656778fc8c485, 0x0000dc6469c269fa, },
  69836. };
  69837. static const limb_t ntt_mods_cr[NB_MODS * (NB_MODS - 1) / 2] = {
  69838. 0x00020e4da740da8e, 0x0004c3dc09c09c1d, 0x000063bd097b4271, 0x000799d8f18f18fd,
  69839. 0x0005384222222264, 0x000572b07c1f07fe, 0x00035cd08888889a,
  69840. 0x00066015555557e3, 0x000725960b60b623,
  69841. 0x0002fc1fa1d6ce12,
  69842. };
  69843. #else
  69844. typedef limb_t NTTLimb;
  69845. #if LIMB_BITS == 64
  69846. #define NTT_MOD_LOG2_MIN 61
  69847. #define NTT_MOD_LOG2_MAX 62
  69848. #define NB_MODS 5
  69849. #define NTT_PROOT_2EXP 51
  69850. static const int ntt_int_bits[NB_MODS] = { 307, 246, 185, 123, 61, };
  69851. static const limb_t ntt_mods[NB_MODS] = { 0x28d8000000000001, 0x2a88000000000001, 0x2ed8000000000001, 0x3508000000000001, 0x3aa8000000000001,
  69852. };
  69853. static const limb_t ntt_proot[2][NB_MODS] = {
  69854. { 0x1b8ea61034a2bea7, 0x21a9762de58206fb, 0x02ca782f0756a8ea, 0x278384537a3e50a1, 0x106e13fee74ce0ab, },
  69855. { 0x233513af133e13b8, 0x1d13140d1c6f75f1, 0x12cde57f97e3eeda, 0x0d6149e23cbe654f, 0x36cd204f522a1379, },
  69856. };
  69857. static const limb_t ntt_mods_cr[NB_MODS * (NB_MODS - 1) / 2] = {
  69858. 0x08a9ed097b425eea, 0x18a44aaaaaaaaab3, 0x2493f57f57f57f5d, 0x126b8d0649a7f8d4,
  69859. 0x09d80ed7303b5ccc, 0x25b8bcf3cf3cf3d5, 0x2ce6ce63398ce638,
  69860. 0x0e31fad40a57eb59, 0x02a3529fd4a7f52f,
  69861. 0x3a5493e93e93e94a,
  69862. };
  69863. #elif LIMB_BITS == 32
  69864. /* we must have: modulo >= 1 << NTT_MOD_LOG2_MIN */
  69865. #define NTT_MOD_LOG2_MIN 29
  69866. #define NTT_MOD_LOG2_MAX 30
  69867. #define NB_MODS 5
  69868. #define NTT_PROOT_2EXP 20
  69869. static const int ntt_int_bits[NB_MODS] = { 148, 119, 89, 59, 29, };
  69870. static const limb_t ntt_mods[NB_MODS] = { 0x0000000032b00001, 0x0000000033700001, 0x0000000036d00001, 0x0000000037300001, 0x000000003e500001,
  69871. };
  69872. static const limb_t ntt_proot[2][NB_MODS] = {
  69873. { 0x0000000032525f31, 0x0000000005eb3b37, 0x00000000246eda9f, 0x0000000035f25901, 0x00000000022f5768, },
  69874. { 0x00000000051eba1a, 0x00000000107be10e, 0x000000001cd574e0, 0x00000000053806e6, 0x000000002cd6bf98, },
  69875. };
  69876. static const limb_t ntt_mods_cr[NB_MODS * (NB_MODS - 1) / 2] = {
  69877. 0x000000000449559a, 0x000000001eba6ca9, 0x000000002ec18e46, 0x000000000860160b,
  69878. 0x000000000d321307, 0x000000000bf51120, 0x000000000f662938,
  69879. 0x000000000932ab3e, 0x000000002f40eef8,
  69880. 0x000000002e760905,
  69881. };
  69882. #endif /* LIMB_BITS */
  69883. #endif /* !AVX2 */
  69884. #if defined(__AVX2__)
  69885. #define NTT_TRIG_K_MAX 18
  69886. #else
  69887. #define NTT_TRIG_K_MAX 19
  69888. #endif
  69889. typedef struct BFNTTState {
  69890. bf_context_t *ctx;
  69891. /* used for mul_mod_fast() */
  69892. limb_t ntt_mods_div[NB_MODS];
  69893. limb_t ntt_proot_pow[NB_MODS][2][NTT_PROOT_2EXP + 1];
  69894. limb_t ntt_proot_pow_inv[NB_MODS][2][NTT_PROOT_2EXP + 1];
  69895. NTTLimb *ntt_trig[NB_MODS][2][NTT_TRIG_K_MAX + 1];
  69896. /* 1/2^n mod m */
  69897. limb_t ntt_len_inv[NB_MODS][NTT_PROOT_2EXP + 1][2];
  69898. #if defined(__AVX2__)
  69899. __m256d ntt_mods_cr_vec[NB_MODS * (NB_MODS - 1) / 2];
  69900. __m256d ntt_mods_vec[NB_MODS];
  69901. __m256d ntt_mods_inv_vec[NB_MODS];
  69902. #else
  69903. limb_t ntt_mods_cr_inv[NB_MODS * (NB_MODS - 1) / 2];
  69904. #endif
  69905. } BFNTTState;
  69906. static NTTLimb *get_trig(BFNTTState *s, int k, int inverse, int m_idx);
  69907. /* add modulo with up to (LIMB_BITS-1) bit modulo */
  69908. static inline limb_t add_mod(limb_t a, limb_t b, limb_t m)
  69909. {
  69910. limb_t r;
  69911. r = a + b;
  69912. if (r >= m)
  69913. r -= m;
  69914. return r;
  69915. }
  69916. /* sub modulo with up to LIMB_BITS bit modulo */
  69917. static inline limb_t sub_mod(limb_t a, limb_t b, limb_t m)
  69918. {
  69919. limb_t r;
  69920. r = a - b;
  69921. if (r > a)
  69922. r += m;
  69923. return r;
  69924. }
  69925. /* return (r0+r1*B) mod m
  69926. precondition: 0 <= r0+r1*B < 2^(64+NTT_MOD_LOG2_MIN)
  69927. */
  69928. static inline limb_t mod_fast(dlimb_t r,
  69929. limb_t m, limb_t m_inv)
  69930. {
  69931. limb_t a1, q, t0, r1, r0;
  69932. a1 = r >> NTT_MOD_LOG2_MIN;
  69933. q = ((dlimb_t)a1 * m_inv) >> LIMB_BITS;
  69934. r = r - (dlimb_t)q * m - m * 2;
  69935. r1 = r >> LIMB_BITS;
  69936. t0 = (slimb_t)r1 >> 1;
  69937. r += m & t0;
  69938. r0 = r;
  69939. r1 = r >> LIMB_BITS;
  69940. r0 += m & r1;
  69941. return r0;
  69942. }
  69943. /* faster version using precomputed modulo inverse.
  69944. precondition: 0 <= a * b < 2^(64+NTT_MOD_LOG2_MIN) */
  69945. static inline limb_t mul_mod_fast(limb_t a, limb_t b,
  69946. limb_t m, limb_t m_inv)
  69947. {
  69948. dlimb_t r;
  69949. r = (dlimb_t)a * (dlimb_t)b;
  69950. return mod_fast(r, m, m_inv);
  69951. }
  69952. static inline limb_t init_mul_mod_fast(limb_t m)
  69953. {
  69954. dlimb_t t;
  69955. assert(m < (limb_t)1 << NTT_MOD_LOG2_MAX);
  69956. assert(m >= (limb_t)1 << NTT_MOD_LOG2_MIN);
  69957. t = (dlimb_t)1 << (LIMB_BITS + NTT_MOD_LOG2_MIN);
  69958. return t / m;
  69959. }
  69960. /* Faster version used when the multiplier is constant. 0 <= a < 2^64,
  69961. 0 <= b < m. */
  69962. static inline limb_t mul_mod_fast2(limb_t a, limb_t b,
  69963. limb_t m, limb_t b_inv)
  69964. {
  69965. limb_t r, q;
  69966. q = ((dlimb_t)a * (dlimb_t)b_inv) >> LIMB_BITS;
  69967. r = a * b - q * m;
  69968. if (r >= m)
  69969. r -= m;
  69970. return r;
  69971. }
  69972. /* Faster version used when the multiplier is constant. 0 <= a < 2^64,
  69973. 0 <= b < m. Let r = a * b mod m. The return value is 'r' or 'r +
  69974. m'. */
  69975. static inline limb_t mul_mod_fast3(limb_t a, limb_t b,
  69976. limb_t m, limb_t b_inv)
  69977. {
  69978. limb_t r, q;
  69979. q = ((dlimb_t)a * (dlimb_t)b_inv) >> LIMB_BITS;
  69980. r = a * b - q * m;
  69981. return r;
  69982. }
  69983. static inline limb_t init_mul_mod_fast2(limb_t b, limb_t m)
  69984. {
  69985. return ((dlimb_t)b << LIMB_BITS) / m;
  69986. }
  69987. #ifdef __AVX2__
  69988. static inline limb_t ntt_limb_to_int(NTTLimb a, limb_t m)
  69989. {
  69990. slimb_t v;
  69991. v = a;
  69992. if (v < 0)
  69993. v += m;
  69994. if (v >= m)
  69995. v -= m;
  69996. return v;
  69997. }
  69998. static inline NTTLimb int_to_ntt_limb(limb_t a, limb_t m)
  69999. {
  70000. return (slimb_t)a;
  70001. }
  70002. static inline NTTLimb int_to_ntt_limb2(limb_t a, limb_t m)
  70003. {
  70004. if (a >= (m / 2))
  70005. a -= m;
  70006. return (slimb_t)a;
  70007. }
  70008. /* return r + m if r < 0 otherwise r. */
  70009. static inline __m256d ntt_mod1(__m256d r, __m256d m)
  70010. {
  70011. return _mm256_blendv_pd(r, r + m, r);
  70012. }
  70013. /* input: abs(r) < 2 * m. Output: abs(r) < m */
  70014. static inline __m256d ntt_mod(__m256d r, __m256d mf, __m256d m2f)
  70015. {
  70016. return _mm256_blendv_pd(r, r + m2f, r) - mf;
  70017. }
  70018. /* input: abs(a*b) < 2 * m^2, output: abs(r) < m */
  70019. static inline __m256d ntt_mul_mod(__m256d a, __m256d b, __m256d mf,
  70020. __m256d m_inv)
  70021. {
  70022. __m256d r, q, ab1, ab0, qm0, qm1;
  70023. ab1 = a * b;
  70024. q = _mm256_round_pd(ab1 * m_inv, 0); /* round to nearest */
  70025. qm1 = q * mf;
  70026. qm0 = _mm256_fmsub_pd(q, mf, qm1); /* low part */
  70027. ab0 = _mm256_fmsub_pd(a, b, ab1); /* low part */
  70028. r = (ab1 - qm1) + (ab0 - qm0);
  70029. return r;
  70030. }
  70031. static void *bf_aligned_malloc(bf_context_t *s, size_t size, size_t align)
  70032. {
  70033. void *ptr;
  70034. void **ptr1;
  70035. ptr = bf_malloc(s, size + sizeof(void *) + align - 1);
  70036. if (!ptr)
  70037. return NULL;
  70038. ptr1 = (void **)(((uintptr_t)ptr + sizeof(void *) + align - 1) &
  70039. ~(align - 1));
  70040. ptr1[-1] = ptr;
  70041. return ptr1;
  70042. }
  70043. static void bf_aligned_free(bf_context_t *s, void *ptr)
  70044. {
  70045. if (!ptr)
  70046. return;
  70047. bf_free(s, ((void **)ptr)[-1]);
  70048. }
  70049. static void *ntt_malloc(BFNTTState *s, size_t size)
  70050. {
  70051. return bf_aligned_malloc(s->ctx, size, 64);
  70052. }
  70053. static void ntt_free(BFNTTState *s, void *ptr)
  70054. {
  70055. bf_aligned_free(s->ctx, ptr);
  70056. }
  70057. static no_inline int ntt_fft(BFNTTState *s,
  70058. NTTLimb *out_buf, NTTLimb *in_buf,
  70059. NTTLimb *tmp_buf, int fft_len_log2,
  70060. int inverse, int m_idx)
  70061. {
  70062. limb_t nb_blocks, fft_per_block, p, k, n, stride_in, i, j;
  70063. NTTLimb *tab_in, *tab_out, *tmp, *trig;
  70064. __m256d m_inv, mf, m2f, c, a0, a1, b0, b1;
  70065. limb_t m;
  70066. int l;
  70067. m = ntt_mods[m_idx];
  70068. m_inv = _mm256_set1_pd(1.0 / (double)m);
  70069. mf = _mm256_set1_pd(m);
  70070. m2f = _mm256_set1_pd(m * 2);
  70071. n = (limb_t)1 << fft_len_log2;
  70072. assert(n >= 8);
  70073. stride_in = n / 2;
  70074. tab_in = in_buf;
  70075. tab_out = tmp_buf;
  70076. trig = get_trig(s, fft_len_log2, inverse, m_idx);
  70077. if (!trig)
  70078. return -1;
  70079. p = 0;
  70080. for(k = 0; k < stride_in; k += 4) {
  70081. a0 = _mm256_load_pd(&tab_in[k]);
  70082. a1 = _mm256_load_pd(&tab_in[k + stride_in]);
  70083. c = _mm256_load_pd(trig);
  70084. trig += 4;
  70085. b0 = ntt_mod(a0 + a1, mf, m2f);
  70086. b1 = ntt_mul_mod(a0 - a1, c, mf, m_inv);
  70087. a0 = _mm256_permute2f128_pd(b0, b1, 0x20);
  70088. a1 = _mm256_permute2f128_pd(b0, b1, 0x31);
  70089. a0 = _mm256_permute4x64_pd(a0, 0xd8);
  70090. a1 = _mm256_permute4x64_pd(a1, 0xd8);
  70091. _mm256_store_pd(&tab_out[p], a0);
  70092. _mm256_store_pd(&tab_out[p + 4], a1);
  70093. p += 2 * 4;
  70094. }
  70095. tmp = tab_in;
  70096. tab_in = tab_out;
  70097. tab_out = tmp;
  70098. trig = get_trig(s, fft_len_log2 - 1, inverse, m_idx);
  70099. if (!trig)
  70100. return -1;
  70101. p = 0;
  70102. for(k = 0; k < stride_in; k += 4) {
  70103. a0 = _mm256_load_pd(&tab_in[k]);
  70104. a1 = _mm256_load_pd(&tab_in[k + stride_in]);
  70105. c = _mm256_setr_pd(trig[0], trig[0], trig[1], trig[1]);
  70106. trig += 2;
  70107. b0 = ntt_mod(a0 + a1, mf, m2f);
  70108. b1 = ntt_mul_mod(a0 - a1, c, mf, m_inv);
  70109. a0 = _mm256_permute2f128_pd(b0, b1, 0x20);
  70110. a1 = _mm256_permute2f128_pd(b0, b1, 0x31);
  70111. _mm256_store_pd(&tab_out[p], a0);
  70112. _mm256_store_pd(&tab_out[p + 4], a1);
  70113. p += 2 * 4;
  70114. }
  70115. tmp = tab_in;
  70116. tab_in = tab_out;
  70117. tab_out = tmp;
  70118. nb_blocks = n / 4;
  70119. fft_per_block = 4;
  70120. l = fft_len_log2 - 2;
  70121. while (nb_blocks != 2) {
  70122. nb_blocks >>= 1;
  70123. p = 0;
  70124. k = 0;
  70125. trig = get_trig(s, l, inverse, m_idx);
  70126. if (!trig)
  70127. return -1;
  70128. for(i = 0; i < nb_blocks; i++) {
  70129. c = _mm256_set1_pd(trig[0]);
  70130. trig++;
  70131. for(j = 0; j < fft_per_block; j += 4) {
  70132. a0 = _mm256_load_pd(&tab_in[k + j]);
  70133. a1 = _mm256_load_pd(&tab_in[k + j + stride_in]);
  70134. b0 = ntt_mod(a0 + a1, mf, m2f);
  70135. b1 = ntt_mul_mod(a0 - a1, c, mf, m_inv);
  70136. _mm256_store_pd(&tab_out[p + j], b0);
  70137. _mm256_store_pd(&tab_out[p + j + fft_per_block], b1);
  70138. }
  70139. k += fft_per_block;
  70140. p += 2 * fft_per_block;
  70141. }
  70142. fft_per_block <<= 1;
  70143. l--;
  70144. tmp = tab_in;
  70145. tab_in = tab_out;
  70146. tab_out = tmp;
  70147. }
  70148. tab_out = out_buf;
  70149. for(k = 0; k < stride_in; k += 4) {
  70150. a0 = _mm256_load_pd(&tab_in[k]);
  70151. a1 = _mm256_load_pd(&tab_in[k + stride_in]);
  70152. b0 = ntt_mod(a0 + a1, mf, m2f);
  70153. b1 = ntt_mod(a0 - a1, mf, m2f);
  70154. _mm256_store_pd(&tab_out[k], b0);
  70155. _mm256_store_pd(&tab_out[k + stride_in], b1);
  70156. }
  70157. return 0;
  70158. }
  70159. static void ntt_vec_mul(BFNTTState *s,
  70160. NTTLimb *tab1, NTTLimb *tab2, limb_t fft_len_log2,
  70161. int k_tot, int m_idx)
  70162. {
  70163. limb_t i, c_inv, n, m;
  70164. __m256d m_inv, mf, a, b, c;
  70165. m = ntt_mods[m_idx];
  70166. c_inv = s->ntt_len_inv[m_idx][k_tot][0];
  70167. m_inv = _mm256_set1_pd(1.0 / (double)m);
  70168. mf = _mm256_set1_pd(m);
  70169. c = _mm256_set1_pd(int_to_ntt_limb(c_inv, m));
  70170. n = (limb_t)1 << fft_len_log2;
  70171. for(i = 0; i < n; i += 4) {
  70172. a = _mm256_load_pd(&tab1[i]);
  70173. b = _mm256_load_pd(&tab2[i]);
  70174. a = ntt_mul_mod(a, b, mf, m_inv);
  70175. a = ntt_mul_mod(a, c, mf, m_inv);
  70176. _mm256_store_pd(&tab1[i], a);
  70177. }
  70178. }
  70179. static no_inline void mul_trig(NTTLimb *buf,
  70180. limb_t n, limb_t c1, limb_t m, limb_t m_inv1)
  70181. {
  70182. limb_t i, c2, c3, c4;
  70183. __m256d c, c_mul, a0, mf, m_inv;
  70184. assert(n >= 2);
  70185. mf = _mm256_set1_pd(m);
  70186. m_inv = _mm256_set1_pd(1.0 / (double)m);
  70187. c2 = mul_mod_fast(c1, c1, m, m_inv1);
  70188. c3 = mul_mod_fast(c2, c1, m, m_inv1);
  70189. c4 = mul_mod_fast(c2, c2, m, m_inv1);
  70190. c = _mm256_setr_pd(1, int_to_ntt_limb(c1, m),
  70191. int_to_ntt_limb(c2, m), int_to_ntt_limb(c3, m));
  70192. c_mul = _mm256_set1_pd(int_to_ntt_limb(c4, m));
  70193. for(i = 0; i < n; i += 4) {
  70194. a0 = _mm256_load_pd(&buf[i]);
  70195. a0 = ntt_mul_mod(a0, c, mf, m_inv);
  70196. _mm256_store_pd(&buf[i], a0);
  70197. c = ntt_mul_mod(c, c_mul, mf, m_inv);
  70198. }
  70199. }
  70200. #else
  70201. static void *ntt_malloc(BFNTTState *s, size_t size)
  70202. {
  70203. return bf_malloc(s->ctx, size);
  70204. }
  70205. static void ntt_free(BFNTTState *s, void *ptr)
  70206. {
  70207. bf_free(s->ctx, ptr);
  70208. }
  70209. static inline limb_t ntt_limb_to_int(NTTLimb a, limb_t m)
  70210. {
  70211. if (a >= m)
  70212. a -= m;
  70213. return a;
  70214. }
  70215. static inline NTTLimb int_to_ntt_limb(slimb_t a, limb_t m)
  70216. {
  70217. return a;
  70218. }
  70219. static no_inline int ntt_fft(BFNTTState *s, NTTLimb *out_buf, NTTLimb *in_buf,
  70220. NTTLimb *tmp_buf, int fft_len_log2,
  70221. int inverse, int m_idx)
  70222. {
  70223. limb_t nb_blocks, fft_per_block, p, k, n, stride_in, i, j, m, m2;
  70224. NTTLimb *tab_in, *tab_out, *tmp, a0, a1, b0, b1, c, *trig, c_inv;
  70225. int l;
  70226. m = ntt_mods[m_idx];
  70227. m2 = 2 * m;
  70228. n = (limb_t)1 << fft_len_log2;
  70229. nb_blocks = n;
  70230. fft_per_block = 1;
  70231. stride_in = n / 2;
  70232. tab_in = in_buf;
  70233. tab_out = tmp_buf;
  70234. l = fft_len_log2;
  70235. while (nb_blocks != 2) {
  70236. nb_blocks >>= 1;
  70237. p = 0;
  70238. k = 0;
  70239. trig = get_trig(s, l, inverse, m_idx);
  70240. if (!trig)
  70241. return -1;
  70242. for(i = 0; i < nb_blocks; i++) {
  70243. c = trig[0];
  70244. c_inv = trig[1];
  70245. trig += 2;
  70246. for(j = 0; j < fft_per_block; j++) {
  70247. a0 = tab_in[k + j];
  70248. a1 = tab_in[k + j + stride_in];
  70249. b0 = add_mod(a0, a1, m2);
  70250. b1 = a0 - a1 + m2;
  70251. b1 = mul_mod_fast3(b1, c, m, c_inv);
  70252. tab_out[p + j] = b0;
  70253. tab_out[p + j + fft_per_block] = b1;
  70254. }
  70255. k += fft_per_block;
  70256. p += 2 * fft_per_block;
  70257. }
  70258. fft_per_block <<= 1;
  70259. l--;
  70260. tmp = tab_in;
  70261. tab_in = tab_out;
  70262. tab_out = tmp;
  70263. }
  70264. /* no twiddle in last step */
  70265. tab_out = out_buf;
  70266. for(k = 0; k < stride_in; k++) {
  70267. a0 = tab_in[k];
  70268. a1 = tab_in[k + stride_in];
  70269. b0 = add_mod(a0, a1, m2);
  70270. b1 = sub_mod(a0, a1, m2);
  70271. tab_out[k] = b0;
  70272. tab_out[k + stride_in] = b1;
  70273. }
  70274. return 0;
  70275. }
  70276. static void ntt_vec_mul(BFNTTState *s,
  70277. NTTLimb *tab1, NTTLimb *tab2, int fft_len_log2,
  70278. int k_tot, int m_idx)
  70279. {
  70280. limb_t i, norm, norm_inv, a, n, m, m_inv;
  70281. m = ntt_mods[m_idx];
  70282. m_inv = s->ntt_mods_div[m_idx];
  70283. norm = s->ntt_len_inv[m_idx][k_tot][0];
  70284. norm_inv = s->ntt_len_inv[m_idx][k_tot][1];
  70285. n = (limb_t)1 << fft_len_log2;
  70286. for(i = 0; i < n; i++) {
  70287. a = tab1[i];
  70288. /* need to reduce the range so that the product is <
  70289. 2^(LIMB_BITS+NTT_MOD_LOG2_MIN) */
  70290. if (a >= m)
  70291. a -= m;
  70292. a = mul_mod_fast(a, tab2[i], m, m_inv);
  70293. a = mul_mod_fast3(a, norm, m, norm_inv);
  70294. tab1[i] = a;
  70295. }
  70296. }
  70297. static no_inline void mul_trig(NTTLimb *buf,
  70298. limb_t n, limb_t c_mul, limb_t m, limb_t m_inv)
  70299. {
  70300. limb_t i, c0, c_mul_inv;
  70301. c0 = 1;
  70302. c_mul_inv = init_mul_mod_fast2(c_mul, m);
  70303. for(i = 0; i < n; i++) {
  70304. buf[i] = mul_mod_fast(buf[i], c0, m, m_inv);
  70305. c0 = mul_mod_fast2(c0, c_mul, m, c_mul_inv);
  70306. }
  70307. }
  70308. #endif /* !AVX2 */
  70309. static no_inline NTTLimb *get_trig(BFNTTState *s,
  70310. int k, int inverse, int m_idx)
  70311. {
  70312. NTTLimb *tab;
  70313. limb_t i, n2, c, c_mul, m, c_mul_inv;
  70314. if (k > NTT_TRIG_K_MAX)
  70315. return NULL;
  70316. tab = s->ntt_trig[m_idx][inverse][k];
  70317. if (tab)
  70318. return tab;
  70319. n2 = (limb_t)1 << (k - 1);
  70320. m = ntt_mods[m_idx];
  70321. #ifdef __AVX2__
  70322. tab = ntt_malloc(s, sizeof(NTTLimb) * n2);
  70323. #else
  70324. tab = ntt_malloc(s, sizeof(NTTLimb) * n2 * 2);
  70325. #endif
  70326. if (!tab)
  70327. return NULL;
  70328. c = 1;
  70329. c_mul = s->ntt_proot_pow[m_idx][inverse][k];
  70330. c_mul_inv = s->ntt_proot_pow_inv[m_idx][inverse][k];
  70331. for(i = 0; i < n2; i++) {
  70332. #ifdef __AVX2__
  70333. tab[i] = int_to_ntt_limb2(c, m);
  70334. #else
  70335. tab[2 * i] = int_to_ntt_limb(c, m);
  70336. tab[2 * i + 1] = init_mul_mod_fast2(c, m);
  70337. #endif
  70338. c = mul_mod_fast2(c, c_mul, m, c_mul_inv);
  70339. }
  70340. s->ntt_trig[m_idx][inverse][k] = tab;
  70341. return tab;
  70342. }
  70343. void fft_clear_cache(bf_context_t *s1)
  70344. {
  70345. int m_idx, inverse, k;
  70346. BFNTTState *s = s1->ntt_state;
  70347. if (s) {
  70348. for(m_idx = 0; m_idx < NB_MODS; m_idx++) {
  70349. for(inverse = 0; inverse < 2; inverse++) {
  70350. for(k = 0; k < NTT_TRIG_K_MAX + 1; k++) {
  70351. if (s->ntt_trig[m_idx][inverse][k]) {
  70352. ntt_free(s, s->ntt_trig[m_idx][inverse][k]);
  70353. s->ntt_trig[m_idx][inverse][k] = NULL;
  70354. }
  70355. }
  70356. }
  70357. }
  70358. #if defined(__AVX2__)
  70359. bf_aligned_free(s1, s);
  70360. #else
  70361. bf_free(s1, s);
  70362. #endif
  70363. s1->ntt_state = NULL;
  70364. }
  70365. }
  70366. #define STRIP_LEN 16
  70367. /* dst = buf1, src = buf2 */
  70368. static int ntt_fft_partial(BFNTTState *s, NTTLimb *buf1,
  70369. int k1, int k2, limb_t n1, limb_t n2, int inverse,
  70370. limb_t m_idx)
  70371. {
  70372. limb_t i, j, c_mul, c0, m, m_inv, strip_len, l;
  70373. NTTLimb *buf2, *buf3;
  70374. buf2 = NULL;
  70375. buf3 = ntt_malloc(s, sizeof(NTTLimb) * n1);
  70376. if (!buf3)
  70377. goto fail;
  70378. if (k2 == 0) {
  70379. if (ntt_fft(s, buf1, buf1, buf3, k1, inverse, m_idx))
  70380. goto fail;
  70381. } else {
  70382. strip_len = STRIP_LEN;
  70383. buf2 = ntt_malloc(s, sizeof(NTTLimb) * n1 * strip_len);
  70384. if (!buf2)
  70385. goto fail;
  70386. m = ntt_mods[m_idx];
  70387. m_inv = s->ntt_mods_div[m_idx];
  70388. c0 = s->ntt_proot_pow[m_idx][inverse][k1 + k2];
  70389. c_mul = 1;
  70390. assert((n2 % strip_len) == 0);
  70391. for(j = 0; j < n2; j += strip_len) {
  70392. for(i = 0; i < n1; i++) {
  70393. for(l = 0; l < strip_len; l++) {
  70394. buf2[i + l * n1] = buf1[i * n2 + (j + l)];
  70395. }
  70396. }
  70397. for(l = 0; l < strip_len; l++) {
  70398. if (inverse)
  70399. mul_trig(buf2 + l * n1, n1, c_mul, m, m_inv);
  70400. if (ntt_fft(s, buf2 + l * n1, buf2 + l * n1, buf3, k1, inverse, m_idx))
  70401. goto fail;
  70402. if (!inverse)
  70403. mul_trig(buf2 + l * n1, n1, c_mul, m, m_inv);
  70404. c_mul = mul_mod_fast(c_mul, c0, m, m_inv);
  70405. }
  70406. for(i = 0; i < n1; i++) {
  70407. for(l = 0; l < strip_len; l++) {
  70408. buf1[i * n2 + (j + l)] = buf2[i + l *n1];
  70409. }
  70410. }
  70411. }
  70412. ntt_free(s, buf2);
  70413. }
  70414. ntt_free(s, buf3);
  70415. return 0;
  70416. fail:
  70417. ntt_free(s, buf2);
  70418. ntt_free(s, buf3);
  70419. return -1;
  70420. }
  70421. /* dst = buf1, src = buf2, tmp = buf3 */
  70422. static int ntt_conv(BFNTTState *s, NTTLimb *buf1, NTTLimb *buf2,
  70423. int k, int k_tot, limb_t m_idx)
  70424. {
  70425. limb_t n1, n2, i;
  70426. int k1, k2;
  70427. if (k <= NTT_TRIG_K_MAX) {
  70428. k1 = k;
  70429. } else {
  70430. /* recursive split of the FFT */
  70431. k1 = bf_min(k / 2, NTT_TRIG_K_MAX);
  70432. }
  70433. k2 = k - k1;
  70434. n1 = (limb_t)1 << k1;
  70435. n2 = (limb_t)1 << k2;
  70436. if (ntt_fft_partial(s, buf1, k1, k2, n1, n2, 0, m_idx))
  70437. return -1;
  70438. if (ntt_fft_partial(s, buf2, k1, k2, n1, n2, 0, m_idx))
  70439. return -1;
  70440. if (k2 == 0) {
  70441. ntt_vec_mul(s, buf1, buf2, k, k_tot, m_idx);
  70442. } else {
  70443. for(i = 0; i < n1; i++) {
  70444. ntt_conv(s, buf1 + i * n2, buf2 + i * n2, k2, k_tot, m_idx);
  70445. }
  70446. }
  70447. if (ntt_fft_partial(s, buf1, k1, k2, n1, n2, 1, m_idx))
  70448. return -1;
  70449. return 0;
  70450. }
  70451. static no_inline void limb_to_ntt(BFNTTState *s,
  70452. NTTLimb *tabr, limb_t fft_len,
  70453. const limb_t *taba, limb_t a_len, int dpl,
  70454. int first_m_idx, int nb_mods)
  70455. {
  70456. slimb_t i, n;
  70457. dlimb_t a, b;
  70458. int j, shift;
  70459. limb_t base_mask1, a0, a1, a2, r, m, m_inv;
  70460. memset(tabr, 0, sizeof(NTTLimb) * fft_len * nb_mods);
  70461. shift = dpl & (LIMB_BITS - 1);
  70462. if (shift == 0)
  70463. base_mask1 = -1;
  70464. else
  70465. base_mask1 = ((limb_t)1 << shift) - 1;
  70466. n = bf_min(fft_len, (a_len * LIMB_BITS + dpl - 1) / dpl);
  70467. for(i = 0; i < n; i++) {
  70468. a0 = get_bits(taba, a_len, i * dpl);
  70469. if (dpl <= LIMB_BITS) {
  70470. a0 &= base_mask1;
  70471. a = a0;
  70472. } else {
  70473. a1 = get_bits(taba, a_len, i * dpl + LIMB_BITS);
  70474. if (dpl <= (LIMB_BITS + NTT_MOD_LOG2_MIN)) {
  70475. a = a0 | ((dlimb_t)(a1 & base_mask1) << LIMB_BITS);
  70476. } else {
  70477. if (dpl > 2 * LIMB_BITS) {
  70478. a2 = get_bits(taba, a_len, i * dpl + LIMB_BITS * 2) &
  70479. base_mask1;
  70480. } else {
  70481. a1 &= base_mask1;
  70482. a2 = 0;
  70483. }
  70484. // printf("a=0x%016lx%016lx%016lx\n", a2, a1, a0);
  70485. a = (a0 >> (LIMB_BITS - NTT_MOD_LOG2_MAX + NTT_MOD_LOG2_MIN)) |
  70486. ((dlimb_t)a1 << (NTT_MOD_LOG2_MAX - NTT_MOD_LOG2_MIN)) |
  70487. ((dlimb_t)a2 << (LIMB_BITS + NTT_MOD_LOG2_MAX - NTT_MOD_LOG2_MIN));
  70488. a0 &= ((limb_t)1 << (LIMB_BITS - NTT_MOD_LOG2_MAX + NTT_MOD_LOG2_MIN)) - 1;
  70489. }
  70490. }
  70491. for(j = 0; j < nb_mods; j++) {
  70492. m = ntt_mods[first_m_idx + j];
  70493. m_inv = s->ntt_mods_div[first_m_idx + j];
  70494. r = mod_fast(a, m, m_inv);
  70495. if (dpl > (LIMB_BITS + NTT_MOD_LOG2_MIN)) {
  70496. b = ((dlimb_t)r << (LIMB_BITS - NTT_MOD_LOG2_MAX + NTT_MOD_LOG2_MIN)) | a0;
  70497. r = mod_fast(b, m, m_inv);
  70498. }
  70499. tabr[i + j * fft_len] = int_to_ntt_limb(r, m);
  70500. }
  70501. }
  70502. }
  70503. #if defined(__AVX2__)
  70504. #define VEC_LEN 4
  70505. typedef union {
  70506. __m256d v;
  70507. double d[4];
  70508. } VecUnion;
  70509. static no_inline void ntt_to_limb(BFNTTState *s, limb_t *tabr, limb_t r_len,
  70510. const NTTLimb *buf, int fft_len_log2, int dpl,
  70511. int nb_mods)
  70512. {
  70513. const limb_t *mods = ntt_mods + NB_MODS - nb_mods;
  70514. const __m256d *mods_cr_vec, *mf, *m_inv;
  70515. VecUnion y[NB_MODS];
  70516. limb_t u[NB_MODS], carry[NB_MODS], fft_len, base_mask1, r;
  70517. slimb_t i, len, pos;
  70518. int j, k, l, shift, n_limb1, p;
  70519. dlimb_t t;
  70520. j = NB_MODS * (NB_MODS - 1) / 2 - nb_mods * (nb_mods - 1) / 2;
  70521. mods_cr_vec = s->ntt_mods_cr_vec + j;
  70522. mf = s->ntt_mods_vec + NB_MODS - nb_mods;
  70523. m_inv = s->ntt_mods_inv_vec + NB_MODS - nb_mods;
  70524. shift = dpl & (LIMB_BITS - 1);
  70525. if (shift == 0)
  70526. base_mask1 = -1;
  70527. else
  70528. base_mask1 = ((limb_t)1 << shift) - 1;
  70529. n_limb1 = ((unsigned)dpl - 1) / LIMB_BITS;
  70530. for(j = 0; j < NB_MODS; j++)
  70531. carry[j] = 0;
  70532. for(j = 0; j < NB_MODS; j++)
  70533. u[j] = 0; /* avoid warnings */
  70534. memset(tabr, 0, sizeof(limb_t) * r_len);
  70535. fft_len = (limb_t)1 << fft_len_log2;
  70536. len = bf_min(fft_len, (r_len * LIMB_BITS + dpl - 1) / dpl);
  70537. len = (len + VEC_LEN - 1) & ~(VEC_LEN - 1);
  70538. i = 0;
  70539. while (i < len) {
  70540. for(j = 0; j < nb_mods; j++)
  70541. y[j].v = *(__m256d *)&buf[i + fft_len * j];
  70542. /* Chinese remainder to get mixed radix representation */
  70543. l = 0;
  70544. for(j = 0; j < nb_mods - 1; j++) {
  70545. y[j].v = ntt_mod1(y[j].v, mf[j]);
  70546. for(k = j + 1; k < nb_mods; k++) {
  70547. y[k].v = ntt_mul_mod(y[k].v - y[j].v,
  70548. mods_cr_vec[l], mf[k], m_inv[k]);
  70549. l++;
  70550. }
  70551. }
  70552. y[j].v = ntt_mod1(y[j].v, mf[j]);
  70553. for(p = 0; p < VEC_LEN; p++) {
  70554. /* back to normal representation */
  70555. u[0] = (int64_t)y[nb_mods - 1].d[p];
  70556. l = 1;
  70557. for(j = nb_mods - 2; j >= 1; j--) {
  70558. r = (int64_t)y[j].d[p];
  70559. for(k = 0; k < l; k++) {
  70560. t = (dlimb_t)u[k] * mods[j] + r;
  70561. r = t >> LIMB_BITS;
  70562. u[k] = t;
  70563. }
  70564. u[l] = r;
  70565. l++;
  70566. }
  70567. /* XXX: for nb_mods = 5, l should be 4 */
  70568. /* last step adds the carry */
  70569. r = (int64_t)y[0].d[p];
  70570. for(k = 0; k < l; k++) {
  70571. t = (dlimb_t)u[k] * mods[j] + r + carry[k];
  70572. r = t >> LIMB_BITS;
  70573. u[k] = t;
  70574. }
  70575. u[l] = r + carry[l];
  70576. /* write the digits */
  70577. pos = i * dpl;
  70578. for(j = 0; j < n_limb1; j++) {
  70579. put_bits(tabr, r_len, pos, u[j]);
  70580. pos += LIMB_BITS;
  70581. }
  70582. put_bits(tabr, r_len, pos, u[n_limb1] & base_mask1);
  70583. /* shift by dpl digits and set the carry */
  70584. if (shift == 0) {
  70585. for(j = n_limb1 + 1; j < nb_mods; j++)
  70586. carry[j - (n_limb1 + 1)] = u[j];
  70587. } else {
  70588. for(j = n_limb1; j < nb_mods - 1; j++) {
  70589. carry[j - n_limb1] = (u[j] >> shift) |
  70590. (u[j + 1] << (LIMB_BITS - shift));
  70591. }
  70592. carry[nb_mods - 1 - n_limb1] = u[nb_mods - 1] >> shift;
  70593. }
  70594. i++;
  70595. }
  70596. }
  70597. }
  70598. #else
  70599. static no_inline void ntt_to_limb(BFNTTState *s, limb_t *tabr, limb_t r_len,
  70600. const NTTLimb *buf, int fft_len_log2, int dpl,
  70601. int nb_mods)
  70602. {
  70603. const limb_t *mods = ntt_mods + NB_MODS - nb_mods;
  70604. const limb_t *mods_cr, *mods_cr_inv;
  70605. limb_t y[NB_MODS], u[NB_MODS], carry[NB_MODS], fft_len, base_mask1, r;
  70606. slimb_t i, len, pos;
  70607. int j, k, l, shift, n_limb1;
  70608. dlimb_t t;
  70609. j = NB_MODS * (NB_MODS - 1) / 2 - nb_mods * (nb_mods - 1) / 2;
  70610. mods_cr = ntt_mods_cr + j;
  70611. mods_cr_inv = s->ntt_mods_cr_inv + j;
  70612. shift = dpl & (LIMB_BITS - 1);
  70613. if (shift == 0)
  70614. base_mask1 = -1;
  70615. else
  70616. base_mask1 = ((limb_t)1 << shift) - 1;
  70617. n_limb1 = ((unsigned)dpl - 1) / LIMB_BITS;
  70618. for(j = 0; j < NB_MODS; j++)
  70619. carry[j] = 0;
  70620. for(j = 0; j < NB_MODS; j++)
  70621. u[j] = 0; /* avoid warnings */
  70622. memset(tabr, 0, sizeof(limb_t) * r_len);
  70623. fft_len = (limb_t)1 << fft_len_log2;
  70624. len = bf_min(fft_len, (r_len * LIMB_BITS + dpl - 1) / dpl);
  70625. for(i = 0; i < len; i++) {
  70626. for(j = 0; j < nb_mods; j++) {
  70627. y[j] = ntt_limb_to_int(buf[i + fft_len * j], mods[j]);
  70628. }
  70629. /* Chinese remainder to get mixed radix representation */
  70630. l = 0;
  70631. for(j = 0; j < nb_mods - 1; j++) {
  70632. for(k = j + 1; k < nb_mods; k++) {
  70633. limb_t m;
  70634. m = mods[k];
  70635. /* Note: there is no overflow in the sub_mod() because
  70636. the modulos are sorted by increasing order */
  70637. y[k] = mul_mod_fast2(y[k] - y[j] + m,
  70638. mods_cr[l], m, mods_cr_inv[l]);
  70639. l++;
  70640. }
  70641. }
  70642. /* back to normal representation */
  70643. u[0] = y[nb_mods - 1];
  70644. l = 1;
  70645. for(j = nb_mods - 2; j >= 1; j--) {
  70646. r = y[j];
  70647. for(k = 0; k < l; k++) {
  70648. t = (dlimb_t)u[k] * mods[j] + r;
  70649. r = t >> LIMB_BITS;
  70650. u[k] = t;
  70651. }
  70652. u[l] = r;
  70653. l++;
  70654. }
  70655. /* last step adds the carry */
  70656. r = y[0];
  70657. for(k = 0; k < l; k++) {
  70658. t = (dlimb_t)u[k] * mods[j] + r + carry[k];
  70659. r = t >> LIMB_BITS;
  70660. u[k] = t;
  70661. }
  70662. u[l] = r + carry[l];
  70663. /* write the digits */
  70664. pos = i * dpl;
  70665. for(j = 0; j < n_limb1; j++) {
  70666. put_bits(tabr, r_len, pos, u[j]);
  70667. pos += LIMB_BITS;
  70668. }
  70669. put_bits(tabr, r_len, pos, u[n_limb1] & base_mask1);
  70670. /* shift by dpl digits and set the carry */
  70671. if (shift == 0) {
  70672. for(j = n_limb1 + 1; j < nb_mods; j++)
  70673. carry[j - (n_limb1 + 1)] = u[j];
  70674. } else {
  70675. for(j = n_limb1; j < nb_mods - 1; j++) {
  70676. carry[j - n_limb1] = (u[j] >> shift) |
  70677. (u[j + 1] << (LIMB_BITS - shift));
  70678. }
  70679. carry[nb_mods - 1 - n_limb1] = u[nb_mods - 1] >> shift;
  70680. }
  70681. }
  70682. }
  70683. #endif
  70684. static int ntt_static_init(bf_context_t *s1)
  70685. {
  70686. BFNTTState *s;
  70687. int inverse, i, j, k, l;
  70688. limb_t c, c_inv, c_inv2, m, m_inv;
  70689. if (s1->ntt_state)
  70690. return 0;
  70691. #if defined(__AVX2__)
  70692. s = bf_aligned_malloc(s1, sizeof(*s), 64);
  70693. #else
  70694. s = bf_malloc(s1, sizeof(*s));
  70695. #endif
  70696. if (!s)
  70697. return -1;
  70698. memset(s, 0, sizeof(*s));
  70699. s1->ntt_state = s;
  70700. s->ctx = s1;
  70701. for(j = 0; j < NB_MODS; j++) {
  70702. m = ntt_mods[j];
  70703. m_inv = init_mul_mod_fast(m);
  70704. s->ntt_mods_div[j] = m_inv;
  70705. #if defined(__AVX2__)
  70706. s->ntt_mods_vec[j] = _mm256_set1_pd(m);
  70707. s->ntt_mods_inv_vec[j] = _mm256_set1_pd(1.0 / (double)m);
  70708. #endif
  70709. c_inv2 = (m + 1) / 2; /* 1/2 */
  70710. c_inv = 1;
  70711. for(i = 0; i <= NTT_PROOT_2EXP; i++) {
  70712. s->ntt_len_inv[j][i][0] = c_inv;
  70713. s->ntt_len_inv[j][i][1] = init_mul_mod_fast2(c_inv, m);
  70714. c_inv = mul_mod_fast(c_inv, c_inv2, m, m_inv);
  70715. }
  70716. for(inverse = 0; inverse < 2; inverse++) {
  70717. c = ntt_proot[inverse][j];
  70718. for(i = 0; i < NTT_PROOT_2EXP; i++) {
  70719. s->ntt_proot_pow[j][inverse][NTT_PROOT_2EXP - i] = c;
  70720. s->ntt_proot_pow_inv[j][inverse][NTT_PROOT_2EXP - i] =
  70721. init_mul_mod_fast2(c, m);
  70722. c = mul_mod_fast(c, c, m, m_inv);
  70723. }
  70724. }
  70725. }
  70726. l = 0;
  70727. for(j = 0; j < NB_MODS - 1; j++) {
  70728. for(k = j + 1; k < NB_MODS; k++) {
  70729. #if defined(__AVX2__)
  70730. s->ntt_mods_cr_vec[l] = _mm256_set1_pd(int_to_ntt_limb2(ntt_mods_cr[l],
  70731. ntt_mods[k]));
  70732. #else
  70733. s->ntt_mods_cr_inv[l] = init_mul_mod_fast2(ntt_mods_cr[l],
  70734. ntt_mods[k]);
  70735. #endif
  70736. l++;
  70737. }
  70738. }
  70739. return 0;
  70740. }
  70741. int bf_get_fft_size(int *pdpl, int *pnb_mods, limb_t len)
  70742. {
  70743. int dpl, fft_len_log2, n_bits, nb_mods, dpl_found, fft_len_log2_found;
  70744. int int_bits, nb_mods_found;
  70745. limb_t cost, min_cost;
  70746. min_cost = -1;
  70747. dpl_found = 0;
  70748. nb_mods_found = 4;
  70749. fft_len_log2_found = 0;
  70750. for(nb_mods = 3; nb_mods <= NB_MODS; nb_mods++) {
  70751. int_bits = ntt_int_bits[NB_MODS - nb_mods];
  70752. dpl = bf_min((int_bits - 4) / 2,
  70753. 2 * LIMB_BITS + 2 * NTT_MOD_LOG2_MIN - NTT_MOD_LOG2_MAX);
  70754. for(;;) {
  70755. fft_len_log2 = ceil_log2((len * LIMB_BITS + dpl - 1) / dpl);
  70756. if (fft_len_log2 > NTT_PROOT_2EXP)
  70757. goto next;
  70758. n_bits = fft_len_log2 + 2 * dpl;
  70759. if (n_bits <= int_bits) {
  70760. cost = ((limb_t)(fft_len_log2 + 1) << fft_len_log2) * nb_mods;
  70761. // printf("n=%d dpl=%d: cost=%" PRId64 "\n", nb_mods, dpl, (int64_t)cost);
  70762. if (cost < min_cost) {
  70763. min_cost = cost;
  70764. dpl_found = dpl;
  70765. nb_mods_found = nb_mods;
  70766. fft_len_log2_found = fft_len_log2;
  70767. }
  70768. break;
  70769. }
  70770. dpl--;
  70771. if (dpl == 0)
  70772. break;
  70773. }
  70774. next: ;
  70775. }
  70776. if (!dpl_found)
  70777. abort();
  70778. /* limit dpl if possible to reduce fixed cost of limb/NTT conversion */
  70779. if (dpl_found > (LIMB_BITS + NTT_MOD_LOG2_MIN) &&
  70780. ((limb_t)(LIMB_BITS + NTT_MOD_LOG2_MIN) << fft_len_log2_found) >=
  70781. len * LIMB_BITS) {
  70782. dpl_found = LIMB_BITS + NTT_MOD_LOG2_MIN;
  70783. }
  70784. *pnb_mods = nb_mods_found;
  70785. *pdpl = dpl_found;
  70786. return fft_len_log2_found;
  70787. }
  70788. /* return 0 if OK, -1 if memory error */
  70789. static no_inline int fft_mul(bf_context_t *s1,
  70790. bf_t *res, limb_t *a_tab, limb_t a_len,
  70791. limb_t *b_tab, limb_t b_len, int mul_flags)
  70792. {
  70793. BFNTTState *s;
  70794. int dpl, fft_len_log2, j, nb_mods, reduced_mem;
  70795. slimb_t len, fft_len;
  70796. NTTLimb *buf1, *buf2, *ptr;
  70797. #if defined(USE_MUL_CHECK)
  70798. limb_t ha, hb, hr, h_ref;
  70799. #endif
  70800. if (ntt_static_init(s1))
  70801. return -1;
  70802. s = s1->ntt_state;
  70803. /* find the optimal number of digits per limb (dpl) */
  70804. len = a_len + b_len;
  70805. fft_len_log2 = bf_get_fft_size(&dpl, &nb_mods, len);
  70806. fft_len = (uint64_t)1 << fft_len_log2;
  70807. // printf("len=%" PRId64 " fft_len_log2=%d dpl=%d\n", len, fft_len_log2, dpl);
  70808. #if defined(USE_MUL_CHECK)
  70809. ha = mp_mod1(a_tab, a_len, BF_CHKSUM_MOD, 0);
  70810. hb = mp_mod1(b_tab, b_len, BF_CHKSUM_MOD, 0);
  70811. #endif
  70812. if ((mul_flags & (FFT_MUL_R_OVERLAP_A | FFT_MUL_R_OVERLAP_B)) == 0) {
  70813. if (!(mul_flags & FFT_MUL_R_NORESIZE))
  70814. bf_resize(res, 0);
  70815. } else if (mul_flags & FFT_MUL_R_OVERLAP_B) {
  70816. limb_t *tmp_tab, tmp_len;
  70817. /* it is better to free 'b' first */
  70818. tmp_tab = a_tab;
  70819. a_tab = b_tab;
  70820. b_tab = tmp_tab;
  70821. tmp_len = a_len;
  70822. a_len = b_len;
  70823. b_len = tmp_len;
  70824. }
  70825. buf1 = ntt_malloc(s, sizeof(NTTLimb) * fft_len * nb_mods);
  70826. if (!buf1)
  70827. return -1;
  70828. limb_to_ntt(s, buf1, fft_len, a_tab, a_len, dpl,
  70829. NB_MODS - nb_mods, nb_mods);
  70830. if ((mul_flags & (FFT_MUL_R_OVERLAP_A | FFT_MUL_R_OVERLAP_B)) ==
  70831. FFT_MUL_R_OVERLAP_A) {
  70832. if (!(mul_flags & FFT_MUL_R_NORESIZE))
  70833. bf_resize(res, 0);
  70834. }
  70835. reduced_mem = (fft_len_log2 >= 14);
  70836. if (!reduced_mem) {
  70837. buf2 = ntt_malloc(s, sizeof(NTTLimb) * fft_len * nb_mods);
  70838. if (!buf2)
  70839. goto fail;
  70840. limb_to_ntt(s, buf2, fft_len, b_tab, b_len, dpl,
  70841. NB_MODS - nb_mods, nb_mods);
  70842. if (!(mul_flags & FFT_MUL_R_NORESIZE))
  70843. bf_resize(res, 0); /* in case res == b */
  70844. } else {
  70845. buf2 = ntt_malloc(s, sizeof(NTTLimb) * fft_len);
  70846. if (!buf2)
  70847. goto fail;
  70848. }
  70849. for(j = 0; j < nb_mods; j++) {
  70850. if (reduced_mem) {
  70851. limb_to_ntt(s, buf2, fft_len, b_tab, b_len, dpl,
  70852. NB_MODS - nb_mods + j, 1);
  70853. ptr = buf2;
  70854. } else {
  70855. ptr = buf2 + fft_len * j;
  70856. }
  70857. if (ntt_conv(s, buf1 + fft_len * j, ptr,
  70858. fft_len_log2, fft_len_log2, j + NB_MODS - nb_mods))
  70859. goto fail;
  70860. }
  70861. if (!(mul_flags & FFT_MUL_R_NORESIZE))
  70862. bf_resize(res, 0); /* in case res == b and reduced mem */
  70863. ntt_free(s, buf2);
  70864. buf2 = NULL;
  70865. if (!(mul_flags & FFT_MUL_R_NORESIZE)) {
  70866. if (bf_resize(res, len))
  70867. goto fail;
  70868. }
  70869. ntt_to_limb(s, res->tab, len, buf1, fft_len_log2, dpl, nb_mods);
  70870. ntt_free(s, buf1);
  70871. #if defined(USE_MUL_CHECK)
  70872. hr = mp_mod1(res->tab, len, BF_CHKSUM_MOD, 0);
  70873. h_ref = mul_mod(ha, hb, BF_CHKSUM_MOD);
  70874. if (hr != h_ref) {
  70875. printf("ntt_mul_error: len=%" PRId_LIMB " fft_len_log2=%d dpl=%d nb_mods=%d\n",
  70876. len, fft_len_log2, dpl, nb_mods);
  70877. // printf("ha=0x" FMT_LIMB" hb=0x" FMT_LIMB " hr=0x" FMT_LIMB " expected=0x" FMT_LIMB "\n", ha, hb, hr, h_ref);
  70878. exit(1);
  70879. }
  70880. #endif
  70881. return 0;
  70882. fail:
  70883. ntt_free(s, buf1);
  70884. ntt_free(s, buf2);
  70885. return -1;
  70886. }
  70887. #else /* USE_FFT_MUL */
  70888. int bf_get_fft_size(int *pdpl, int *pnb_mods, limb_t len)
  70889. {
  70890. return 0;
  70891. }
  70892. #endif /* !USE_FFT_MUL */
  70893. #undef malloc
  70894. #undef free
  70895. #undef realloc
  70896. /*
  70897. * Regular Expression Engine
  70898. *
  70899. * Copyright (c) 2017-2018 Fabrice Bellard
  70900. *
  70901. * Permission is hereby granted, free of charge, to any person obtaining a copy
  70902. * of this software and associated documentation files (the "Software"), to deal
  70903. * in the Software without restriction, including without limitation the rights
  70904. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  70905. * copies of the Software, and to permit persons to whom the Software is
  70906. * furnished to do so, subject to the following conditions:
  70907. *
  70908. * The above copyright notice and this permission notice shall be included in
  70909. * all copies or substantial portions of the Software.
  70910. *
  70911. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  70912. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  70913. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  70914. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  70915. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  70916. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  70917. * THE SOFTWARE.
  70918. */
  70919. #include <stdlib.h>
  70920. #include <stdio.h>
  70921. #include <stdarg.h>
  70922. #include <inttypes.h>
  70923. #include <string.h>
  70924. #include <assert.h>
  70925. /*
  70926. TODO:
  70927. - Add a lock step execution mode (=linear time execution guaranteed)
  70928. when the regular expression is "simple" i.e. no backreference nor
  70929. complicated lookahead. The opcodes are designed for this execution
  70930. model.
  70931. */
  70932. #if defined(TEST)
  70933. #define DUMP_REOP
  70934. #endif
  70935. typedef enum {
  70936. #define DEF(id, size) REOP_ ## id,
  70937. /*
  70938. * Regular Expression Engine
  70939. *
  70940. * Copyright (c) 2017-2018 Fabrice Bellard
  70941. *
  70942. * Permission is hereby granted, free of charge, to any person obtaining a copy
  70943. * of this software and associated documentation files (the "Software"), to deal
  70944. * in the Software without restriction, including without limitation the rights
  70945. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  70946. * copies of the Software, and to permit persons to whom the Software is
  70947. * furnished to do so, subject to the following conditions:
  70948. *
  70949. * The above copyright notice and this permission notice shall be included in
  70950. * all copies or substantial portions of the Software.
  70951. *
  70952. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  70953. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  70954. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  70955. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  70956. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  70957. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  70958. * THE SOFTWARE.
  70959. */
  70960. #ifdef DEF
  70961. DEF(invalid, 1) /* never used */
  70962. DEF(char8, 2) /* 7 bits in fact */
  70963. DEF(char16, 3)
  70964. DEF(char32, 5)
  70965. DEF(dot, 1)
  70966. DEF(any, 1) /* same as dot but match any character including line terminator */
  70967. DEF(line_start, 1)
  70968. DEF(line_end, 1)
  70969. DEF(goto, 5)
  70970. DEF(split_goto_first, 5)
  70971. DEF(split_next_first, 5)
  70972. DEF(match, 1)
  70973. DEF(save_start, 2) /* save start position */
  70974. DEF(save_end, 2) /* save end position, must come after saved_start */
  70975. DEF(save_reset, 3) /* reset save positions */
  70976. DEF(loop, 5) /* decrement the top the stack and goto if != 0 */
  70977. DEF(push_i32, 5) /* push integer on the stack */
  70978. DEF(drop, 1)
  70979. DEF(word_boundary, 1)
  70980. DEF(not_word_boundary, 1)
  70981. DEF(back_reference, 2)
  70982. DEF(backward_back_reference, 2) /* must come after back_reference */
  70983. DEF(range, 3) /* variable length */
  70984. DEF(range32, 3) /* variable length */
  70985. DEF(lookahead, 5)
  70986. DEF(negative_lookahead, 5)
  70987. DEF(push_char_pos, 1) /* push the character position on the stack */
  70988. DEF(check_advance, 1) /* pop one stack element and check that it is different from the character position */
  70989. DEF(prev, 1) /* go to the previous char */
  70990. DEF(simple_greedy_quant, 17)
  70991. #endif /* DEF */
  70992. #undef DEF
  70993. REOP_COUNT,
  70994. } REOPCodeEnum;
  70995. #define CAPTURE_COUNT_MAX 255
  70996. #define STACK_SIZE_MAX 255
  70997. /* unicode code points */
  70998. #define CP_LS 0x2028
  70999. #define CP_PS 0x2029
  71000. #define TMP_BUF_SIZE 128
  71001. // invariant: is_unicode ^ unicode_sets (or neither, but not both)
  71002. typedef struct {
  71003. DynBuf byte_code;
  71004. const uint8_t *buf_ptr;
  71005. const uint8_t *buf_end;
  71006. const uint8_t *buf_start;
  71007. int re_flags;
  71008. bool is_unicode;
  71009. bool unicode_sets;
  71010. bool ignore_case;
  71011. bool dotall;
  71012. int capture_count;
  71013. int total_capture_count; /* -1 = not computed yet */
  71014. int has_named_captures; /* -1 = don't know, 0 = no, 1 = yes */
  71015. void *opaque;
  71016. DynBuf group_names;
  71017. union {
  71018. char error_msg[TMP_BUF_SIZE];
  71019. char tmp_buf[TMP_BUF_SIZE];
  71020. } u;
  71021. } REParseState;
  71022. typedef struct {
  71023. #ifdef DUMP_REOP
  71024. const char *name;
  71025. #endif
  71026. uint8_t size;
  71027. } REOpCode;
  71028. static const REOpCode reopcode_info[REOP_COUNT] = {
  71029. #ifdef DUMP_REOP
  71030. #define DEF(id, size) { #id, size },
  71031. #else
  71032. #define DEF(id, size) { size },
  71033. #endif
  71034. /*
  71035. * Regular Expression Engine
  71036. *
  71037. * Copyright (c) 2017-2018 Fabrice Bellard
  71038. *
  71039. * Permission is hereby granted, free of charge, to any person obtaining a copy
  71040. * of this software and associated documentation files (the "Software"), to deal
  71041. * in the Software without restriction, including without limitation the rights
  71042. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  71043. * copies of the Software, and to permit persons to whom the Software is
  71044. * furnished to do so, subject to the following conditions:
  71045. *
  71046. * The above copyright notice and this permission notice shall be included in
  71047. * all copies or substantial portions of the Software.
  71048. *
  71049. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  71050. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  71051. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  71052. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  71053. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  71054. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  71055. * THE SOFTWARE.
  71056. */
  71057. #ifdef DEF
  71058. DEF(invalid, 1) /* never used */
  71059. DEF(char8, 2) /* 7 bits in fact */
  71060. DEF(char16, 3)
  71061. DEF(char32, 5)
  71062. DEF(dot, 1)
  71063. DEF(any, 1) /* same as dot but match any character including line terminator */
  71064. DEF(line_start, 1)
  71065. DEF(line_end, 1)
  71066. DEF(goto, 5)
  71067. DEF(split_goto_first, 5)
  71068. DEF(split_next_first, 5)
  71069. DEF(match, 1)
  71070. DEF(save_start, 2) /* save start position */
  71071. DEF(save_end, 2) /* save end position, must come after saved_start */
  71072. DEF(save_reset, 3) /* reset save positions */
  71073. DEF(loop, 5) /* decrement the top the stack and goto if != 0 */
  71074. DEF(push_i32, 5) /* push integer on the stack */
  71075. DEF(drop, 1)
  71076. DEF(word_boundary, 1)
  71077. DEF(not_word_boundary, 1)
  71078. DEF(back_reference, 2)
  71079. DEF(backward_back_reference, 2) /* must come after back_reference */
  71080. DEF(range, 3) /* variable length */
  71081. DEF(range32, 3) /* variable length */
  71082. DEF(lookahead, 5)
  71083. DEF(negative_lookahead, 5)
  71084. DEF(push_char_pos, 1) /* push the character position on the stack */
  71085. DEF(check_advance, 1) /* pop one stack element and check that it is different from the character position */
  71086. DEF(prev, 1) /* go to the previous char */
  71087. DEF(simple_greedy_quant, 17)
  71088. #endif /* DEF */
  71089. #undef DEF
  71090. };
  71091. #define RE_HEADER_FLAGS 0
  71092. #define RE_HEADER_CAPTURE_COUNT 2
  71093. #define RE_HEADER_STACK_SIZE 3
  71094. #define RE_HEADER_BYTECODE_LEN 4
  71095. #define RE_HEADER_LEN 8
  71096. static inline int lre_is_digit(int c) {
  71097. return c >= '0' && c <= '9';
  71098. }
  71099. /* insert 'len' bytes at position 'pos'. Return < 0 if error. */
  71100. static int dbuf_insert(DynBuf *s, int pos, int len)
  71101. {
  71102. if (dbuf_realloc(s, s->size + len))
  71103. return -1;
  71104. memmove(s->buf + pos + len, s->buf + pos, s->size - pos);
  71105. s->size += len;
  71106. return 0;
  71107. }
  71108. static const uint16_t char_range_d[] = {
  71109. 1,
  71110. 0x0030, 0x0039 + 1,
  71111. };
  71112. /* code point ranges for Zs,Zl or Zp property */
  71113. static const uint16_t char_range_s[] = {
  71114. 10,
  71115. 0x0009, 0x000D + 1,
  71116. 0x0020, 0x0020 + 1,
  71117. 0x00A0, 0x00A0 + 1,
  71118. 0x1680, 0x1680 + 1,
  71119. 0x2000, 0x200A + 1,
  71120. /* 2028;LINE SEPARATOR;Zl;0;WS;;;;;N;;;;; */
  71121. /* 2029;PARAGRAPH SEPARATOR;Zp;0;B;;;;;N;;;;; */
  71122. 0x2028, 0x2029 + 1,
  71123. 0x202F, 0x202F + 1,
  71124. 0x205F, 0x205F + 1,
  71125. 0x3000, 0x3000 + 1,
  71126. /* FEFF;ZERO WIDTH NO-BREAK SPACE;Cf;0;BN;;;;;N;BYTE ORDER MARK;;;; */
  71127. 0xFEFF, 0xFEFF + 1,
  71128. };
  71129. bool lre_is_space(int c)
  71130. {
  71131. int i, n, low, high;
  71132. n = (countof(char_range_s) - 1) / 2;
  71133. for(i = 0; i < n; i++) {
  71134. low = char_range_s[2 * i + 1];
  71135. if (c < low)
  71136. return false;
  71137. high = char_range_s[2 * i + 2];
  71138. if (c < high)
  71139. return true;
  71140. }
  71141. return false;
  71142. }
  71143. uint32_t const lre_id_start_table_ascii[4] = {
  71144. /* $ A-Z _ a-z */
  71145. 0x00000000, 0x00000010, 0x87FFFFFE, 0x07FFFFFE
  71146. };
  71147. uint32_t const lre_id_continue_table_ascii[4] = {
  71148. /* $ 0-9 A-Z _ a-z */
  71149. 0x00000000, 0x03FF0010, 0x87FFFFFE, 0x07FFFFFE
  71150. };
  71151. static const uint16_t char_range_w[] = {
  71152. 4,
  71153. 0x0030, 0x0039 + 1,
  71154. 0x0041, 0x005A + 1,
  71155. 0x005F, 0x005F + 1,
  71156. 0x0061, 0x007A + 1,
  71157. };
  71158. #define CLASS_RANGE_BASE 0x40000000
  71159. typedef enum {
  71160. CHAR_RANGE_d,
  71161. CHAR_RANGE_D,
  71162. CHAR_RANGE_s,
  71163. CHAR_RANGE_S,
  71164. CHAR_RANGE_w,
  71165. CHAR_RANGE_W,
  71166. } CharRangeEnum;
  71167. static const uint16_t *char_range_table[] = {
  71168. char_range_d,
  71169. char_range_s,
  71170. char_range_w,
  71171. };
  71172. static int cr_init_char_range(REParseState *s, CharRange *cr, uint32_t c)
  71173. {
  71174. bool invert;
  71175. const uint16_t *c_pt;
  71176. int len, i;
  71177. invert = c & 1;
  71178. c_pt = char_range_table[c >> 1];
  71179. len = *c_pt++;
  71180. cr_init(cr, s->opaque, lre_realloc);
  71181. for(i = 0; i < len * 2; i++) {
  71182. if (cr_add_point(cr, c_pt[i]))
  71183. goto fail;
  71184. }
  71185. if (invert) {
  71186. if (cr_invert(cr))
  71187. goto fail;
  71188. }
  71189. return 0;
  71190. fail:
  71191. cr_free(cr);
  71192. return -1;
  71193. }
  71194. #ifdef DUMP_REOP
  71195. static __maybe_unused void lre_dump_bytecode(const uint8_t *buf,
  71196. int buf_len)
  71197. {
  71198. int pos, len, opcode, bc_len, re_flags, i;
  71199. uint32_t val;
  71200. assert(buf_len >= RE_HEADER_LEN);
  71201. re_flags = lre_get_flags(buf);
  71202. bc_len = get_u32(buf + RE_HEADER_BYTECODE_LEN);
  71203. assert(bc_len + RE_HEADER_LEN <= buf_len);
  71204. printf("flags: 0x%x capture_count=%d stack_size=%d\n",
  71205. re_flags, buf[RE_HEADER_CAPTURE_COUNT], buf[RE_HEADER_STACK_SIZE]);
  71206. if (re_flags & LRE_FLAG_NAMED_GROUPS) {
  71207. const char *p;
  71208. p = (char *)buf + RE_HEADER_LEN + bc_len;
  71209. printf("named groups: ");
  71210. for(i = 1; i < buf[RE_HEADER_CAPTURE_COUNT]; i++) {
  71211. if (i != 1)
  71212. printf(",");
  71213. printf("<%s>", p);
  71214. p += strlen(p) + 1;
  71215. }
  71216. printf("\n");
  71217. assert(p == (char *)(buf + buf_len));
  71218. }
  71219. printf("bytecode_len=%d\n", bc_len);
  71220. buf += RE_HEADER_LEN;
  71221. pos = 0;
  71222. while (pos < bc_len) {
  71223. printf("%5u: ", pos);
  71224. opcode = buf[pos];
  71225. len = reopcode_info[opcode].size;
  71226. if (opcode >= REOP_COUNT) {
  71227. printf(" invalid opcode=0x%02x\n", opcode);
  71228. break;
  71229. }
  71230. if ((pos + len) > bc_len) {
  71231. printf(" buffer overflow (opcode=0x%02x)\n", opcode);
  71232. break;
  71233. }
  71234. printf("%s", reopcode_info[opcode].name);
  71235. switch(opcode) {
  71236. case REOP_char8:
  71237. val = get_u8(buf + pos + 1);
  71238. goto printchar;
  71239. case REOP_char16:
  71240. val = get_u16(buf + pos + 1);
  71241. goto printchar;
  71242. case REOP_char32:
  71243. val = get_u32(buf + pos + 1);
  71244. printchar:
  71245. if (val >= ' ' && val <= 126)
  71246. printf(" '%c'", val);
  71247. else
  71248. printf(" 0x%08x", val);
  71249. break;
  71250. case REOP_goto:
  71251. case REOP_split_goto_first:
  71252. case REOP_split_next_first:
  71253. case REOP_loop:
  71254. case REOP_lookahead:
  71255. case REOP_negative_lookahead:
  71256. val = get_u32(buf + pos + 1);
  71257. val += (pos + 5);
  71258. printf(" %u", val);
  71259. break;
  71260. case REOP_simple_greedy_quant:
  71261. printf(" %u %u %u %u",
  71262. get_u32(buf + pos + 1) + (pos + 17),
  71263. get_u32(buf + pos + 1 + 4),
  71264. get_u32(buf + pos + 1 + 8),
  71265. get_u32(buf + pos + 1 + 12));
  71266. break;
  71267. case REOP_save_start:
  71268. case REOP_save_end:
  71269. case REOP_back_reference:
  71270. case REOP_backward_back_reference:
  71271. printf(" %u", buf[pos + 1]);
  71272. break;
  71273. case REOP_save_reset:
  71274. printf(" %u %u", buf[pos + 1], buf[pos + 2]);
  71275. break;
  71276. case REOP_push_i32:
  71277. val = get_u32(buf + pos + 1);
  71278. printf(" %d", val);
  71279. break;
  71280. case REOP_range:
  71281. {
  71282. int n, i;
  71283. n = get_u16(buf + pos + 1);
  71284. len += n * 4;
  71285. for(i = 0; i < n * 2; i++) {
  71286. val = get_u16(buf + pos + 3 + i * 2);
  71287. printf(" 0x%04x", val);
  71288. }
  71289. }
  71290. break;
  71291. case REOP_range32:
  71292. {
  71293. int n, i;
  71294. n = get_u16(buf + pos + 1);
  71295. len += n * 8;
  71296. for(i = 0; i < n * 2; i++) {
  71297. val = get_u32(buf + pos + 3 + i * 4);
  71298. printf(" 0x%08x", val);
  71299. }
  71300. }
  71301. break;
  71302. default:
  71303. break;
  71304. }
  71305. printf("\n");
  71306. pos += len;
  71307. }
  71308. }
  71309. #endif
  71310. static void re_emit_op(REParseState *s, int op)
  71311. {
  71312. dbuf_putc(&s->byte_code, op);
  71313. }
  71314. /* return the offset of the u32 value */
  71315. static int re_emit_op_u32(REParseState *s, int op, uint32_t val)
  71316. {
  71317. int pos;
  71318. dbuf_putc(&s->byte_code, op);
  71319. pos = s->byte_code.size;
  71320. dbuf_put_u32(&s->byte_code, val);
  71321. return pos;
  71322. }
  71323. static int re_emit_goto(REParseState *s, int op, uint32_t val)
  71324. {
  71325. int pos;
  71326. dbuf_putc(&s->byte_code, op);
  71327. pos = s->byte_code.size;
  71328. dbuf_put_u32(&s->byte_code, val - (pos + 4));
  71329. return pos;
  71330. }
  71331. static void re_emit_op_u8(REParseState *s, int op, uint32_t val)
  71332. {
  71333. dbuf_putc(&s->byte_code, op);
  71334. dbuf_putc(&s->byte_code, val);
  71335. }
  71336. static void re_emit_op_u16(REParseState *s, int op, uint32_t val)
  71337. {
  71338. dbuf_putc(&s->byte_code, op);
  71339. dbuf_put_u16(&s->byte_code, val);
  71340. }
  71341. static int JS_PRINTF_FORMAT_ATTR(2, 3) re_parse_error(REParseState *s, const char *fmt, ...)
  71342. {
  71343. va_list ap;
  71344. va_start(ap, fmt);
  71345. vsnprintf(s->u.error_msg, sizeof(s->u.error_msg), fmt, ap);
  71346. va_end(ap);
  71347. return -1;
  71348. }
  71349. static int re_parse_out_of_memory(REParseState *s)
  71350. {
  71351. return re_parse_error(s, "out of memory");
  71352. }
  71353. /* If allow_overflow is false, return -1 in case of
  71354. overflow. Otherwise return INT32_MAX. */
  71355. static int parse_digits(const uint8_t **pp, bool allow_overflow)
  71356. {
  71357. const uint8_t *p;
  71358. uint64_t v;
  71359. int c;
  71360. p = *pp;
  71361. v = 0;
  71362. for(;;) {
  71363. c = *p;
  71364. if (c < '0' || c > '9')
  71365. break;
  71366. v = v * 10 + c - '0';
  71367. if (v >= INT32_MAX) {
  71368. if (allow_overflow)
  71369. v = INT32_MAX;
  71370. else
  71371. return -1;
  71372. }
  71373. p++;
  71374. }
  71375. *pp = p;
  71376. return v;
  71377. }
  71378. static int re_parse_expect(REParseState *s, const uint8_t **pp, int c)
  71379. {
  71380. const uint8_t *p;
  71381. p = *pp;
  71382. if (*p != c)
  71383. return re_parse_error(s, "expecting '%c'", c);
  71384. p++;
  71385. *pp = p;
  71386. return 0;
  71387. }
  71388. /* Parse an escape sequence, *pp points after the '\':
  71389. allow_utf16 value:
  71390. 0 : no UTF-16 escapes allowed
  71391. 1 : UTF-16 escapes allowed
  71392. 2 : UTF-16 escapes allowed and escapes of surrogate pairs are
  71393. converted to a unicode character (unicode regexp case).
  71394. Return the unicode char and update *pp if recognized,
  71395. return -1 if malformed escape,
  71396. return -2 otherwise. */
  71397. int lre_parse_escape(const uint8_t **pp, int allow_utf16)
  71398. {
  71399. const uint8_t *p;
  71400. uint32_t c;
  71401. p = *pp;
  71402. c = *p++;
  71403. switch(c) {
  71404. case 'b':
  71405. c = '\b';
  71406. break;
  71407. case 'f':
  71408. c = '\f';
  71409. break;
  71410. case 'n':
  71411. c = '\n';
  71412. break;
  71413. case 'r':
  71414. c = '\r';
  71415. break;
  71416. case 't':
  71417. c = '\t';
  71418. break;
  71419. case 'v':
  71420. c = '\v';
  71421. break;
  71422. case 'x':
  71423. case 'u':
  71424. {
  71425. int h, n, i;
  71426. uint32_t c1;
  71427. if (*p == '{' && allow_utf16) {
  71428. p++;
  71429. c = 0;
  71430. for(;;) {
  71431. h = from_hex(*p++);
  71432. if (h < 0)
  71433. return -1;
  71434. c = (c << 4) | h;
  71435. if (c > 0x10FFFF)
  71436. return -1;
  71437. if (*p == '}')
  71438. break;
  71439. }
  71440. p++;
  71441. } else {
  71442. if (c == 'x') {
  71443. n = 2;
  71444. } else {
  71445. n = 4;
  71446. }
  71447. c = 0;
  71448. for(i = 0; i < n; i++) {
  71449. h = from_hex(*p++);
  71450. if (h < 0) {
  71451. return -1;
  71452. }
  71453. c = (c << 4) | h;
  71454. }
  71455. if (is_hi_surrogate(c) &&
  71456. allow_utf16 == 2 && p[0] == '\\' && p[1] == 'u') {
  71457. /* convert an escaped surrogate pair into a
  71458. unicode char */
  71459. c1 = 0;
  71460. for(i = 0; i < 4; i++) {
  71461. h = from_hex(p[2 + i]);
  71462. if (h < 0)
  71463. break;
  71464. c1 = (c1 << 4) | h;
  71465. }
  71466. if (i == 4 && is_lo_surrogate(c1)) {
  71467. p += 6;
  71468. c = from_surrogate(c, c1);
  71469. }
  71470. }
  71471. }
  71472. }
  71473. break;
  71474. case '0': case '1': case '2': case '3':
  71475. case '4': case '5': case '6': case '7':
  71476. c -= '0';
  71477. if (allow_utf16 == 2) {
  71478. /* only accept \0 not followed by digit */
  71479. if (c != 0 || lre_is_digit(*p))
  71480. return -1;
  71481. } else {
  71482. /* parse a legacy octal sequence */
  71483. uint32_t v;
  71484. v = *p - '0';
  71485. if (v > 7)
  71486. break;
  71487. c = (c << 3) | v;
  71488. p++;
  71489. if (c >= 32)
  71490. break;
  71491. v = *p - '0';
  71492. if (v > 7)
  71493. break;
  71494. c = (c << 3) | v;
  71495. p++;
  71496. }
  71497. break;
  71498. default:
  71499. return -2;
  71500. }
  71501. *pp = p;
  71502. return c;
  71503. }
  71504. /* XXX: we use the same chars for name and value */
  71505. static bool is_unicode_char(int c)
  71506. {
  71507. return ((c >= '0' && c <= '9') ||
  71508. (c >= 'A' && c <= 'Z') ||
  71509. (c >= 'a' && c <= 'z') ||
  71510. (c == '_'));
  71511. }
  71512. static int parse_unicode_property(REParseState *s, CharRange *cr,
  71513. const uint8_t **pp, bool is_inv)
  71514. {
  71515. const uint8_t *p;
  71516. char name[64], value[64];
  71517. char *q;
  71518. bool script_ext;
  71519. int ret;
  71520. p = *pp;
  71521. if (*p != '{')
  71522. return re_parse_error(s, "expecting '{' after \\p");
  71523. p++;
  71524. q = name;
  71525. while (is_unicode_char(*p)) {
  71526. if ((q - name) >= sizeof(name) - 1)
  71527. goto unknown_property_name;
  71528. *q++ = *p++;
  71529. }
  71530. *q = '\0';
  71531. q = value;
  71532. if (*p == '=') {
  71533. p++;
  71534. while (is_unicode_char(*p)) {
  71535. if ((q - value) >= sizeof(value) - 1)
  71536. return re_parse_error(s, "unknown unicode property value");
  71537. *q++ = *p++;
  71538. }
  71539. }
  71540. *q = '\0';
  71541. if (*p != '}')
  71542. return re_parse_error(s, "expecting '}'");
  71543. p++;
  71544. // printf("name=%s value=%s\n", name, value);
  71545. if (!strcmp(name, "Script") || !strcmp(name, "sc")) {
  71546. script_ext = false;
  71547. goto do_script;
  71548. } else if (!strcmp(name, "Script_Extensions") || !strcmp(name, "scx")) {
  71549. script_ext = true;
  71550. do_script:
  71551. cr_init(cr, s->opaque, lre_realloc);
  71552. ret = unicode_script(cr, value, script_ext);
  71553. if (ret) {
  71554. cr_free(cr);
  71555. if (ret == -2)
  71556. return re_parse_error(s, "unknown unicode script");
  71557. else
  71558. goto out_of_memory;
  71559. }
  71560. } else if (!strcmp(name, "General_Category") || !strcmp(name, "gc")) {
  71561. cr_init(cr, s->opaque, lre_realloc);
  71562. ret = unicode_general_category(cr, value);
  71563. if (ret) {
  71564. cr_free(cr);
  71565. if (ret == -2)
  71566. return re_parse_error(s, "unknown unicode general category");
  71567. else
  71568. goto out_of_memory;
  71569. }
  71570. } else if (value[0] == '\0') {
  71571. cr_init(cr, s->opaque, lre_realloc);
  71572. ret = unicode_general_category(cr, name);
  71573. if (ret == -1) {
  71574. cr_free(cr);
  71575. goto out_of_memory;
  71576. }
  71577. if (ret < 0) {
  71578. ret = unicode_prop(cr, name);
  71579. if (ret) {
  71580. cr_free(cr);
  71581. if (ret == -2)
  71582. goto unknown_property_name;
  71583. else
  71584. goto out_of_memory;
  71585. }
  71586. }
  71587. } else {
  71588. unknown_property_name:
  71589. return re_parse_error(s, "unknown unicode property name");
  71590. }
  71591. if (is_inv) {
  71592. if (cr_invert(cr)) {
  71593. cr_free(cr);
  71594. return -1;
  71595. }
  71596. }
  71597. *pp = p;
  71598. return 0;
  71599. out_of_memory:
  71600. return re_parse_out_of_memory(s);
  71601. }
  71602. /* return -1 if error otherwise the character or a class range
  71603. (CLASS_RANGE_BASE). In case of class range, 'cr' is
  71604. initialized. Otherwise, it is ignored. */
  71605. static int get_class_atom(REParseState *s, CharRange *cr,
  71606. const uint8_t **pp, bool inclass)
  71607. {
  71608. const uint8_t *p, *p_next;
  71609. uint32_t c;
  71610. int ret;
  71611. p = *pp;
  71612. c = *p;
  71613. switch(c) {
  71614. case '\\':
  71615. p++;
  71616. if (p >= s->buf_end)
  71617. goto unexpected_end;
  71618. c = *p++;
  71619. switch(c) {
  71620. case 'd':
  71621. c = CHAR_RANGE_d;
  71622. goto class_range;
  71623. case 'D':
  71624. c = CHAR_RANGE_D;
  71625. goto class_range;
  71626. case 's':
  71627. c = CHAR_RANGE_s;
  71628. goto class_range;
  71629. case 'S':
  71630. c = CHAR_RANGE_S;
  71631. goto class_range;
  71632. case 'w':
  71633. c = CHAR_RANGE_w;
  71634. goto class_range;
  71635. case 'W':
  71636. c = CHAR_RANGE_W;
  71637. class_range:
  71638. if (cr_init_char_range(s, cr, c))
  71639. return -1;
  71640. c = CLASS_RANGE_BASE;
  71641. break;
  71642. case 'c':
  71643. c = *p;
  71644. if ((c >= 'a' && c <= 'z') ||
  71645. (c >= 'A' && c <= 'Z') ||
  71646. (((c >= '0' && c <= '9') || c == '_') &&
  71647. inclass && !s->is_unicode)) { /* Annex B.1.4 */
  71648. c &= 0x1f;
  71649. p++;
  71650. } else if (s->is_unicode) {
  71651. goto invalid_escape;
  71652. } else {
  71653. /* otherwise return '\' and 'c' */
  71654. p--;
  71655. c = '\\';
  71656. }
  71657. break;
  71658. case 'p':
  71659. case 'P':
  71660. if (s->is_unicode) {
  71661. if (parse_unicode_property(s, cr, &p, (c == 'P')))
  71662. return -1;
  71663. c = CLASS_RANGE_BASE;
  71664. break;
  71665. }
  71666. /* fall thru */
  71667. default:
  71668. p--;
  71669. ret = lre_parse_escape(&p, s->is_unicode * 2);
  71670. if (ret >= 0) {
  71671. c = ret;
  71672. } else {
  71673. if (ret == -2 && *p != '\0' && strchr("^$\\.*+?()[]{}|/", *p)) {
  71674. /* always valid to escape these characters */
  71675. goto normal_char;
  71676. } else if (s->is_unicode) {
  71677. // special case: allowed inside [] but not outside
  71678. if (ret == -2 && *p == '-' && inclass)
  71679. goto normal_char;
  71680. invalid_escape:
  71681. return re_parse_error(s, "invalid escape sequence in regular expression");
  71682. } else {
  71683. /* just ignore the '\' */
  71684. goto normal_char;
  71685. }
  71686. }
  71687. break;
  71688. }
  71689. break;
  71690. case '\0':
  71691. if (p >= s->buf_end) {
  71692. unexpected_end:
  71693. return re_parse_error(s, "unexpected end");
  71694. }
  71695. /* fall thru */
  71696. default:
  71697. normal_char:
  71698. p++;
  71699. if (c >= 0x80) {
  71700. c = utf8_decode(p - 1, &p_next);
  71701. if (p_next == p)
  71702. return re_parse_error(s, "invalid UTF-8 sequence");
  71703. p = p_next;
  71704. if (c > 0xFFFF && !s->is_unicode) {
  71705. // TODO(chqrlie): should handle non BMP-1 code points in
  71706. // the calling function and no require the source string
  71707. // to be CESU-8 encoded if not s->is_unicode
  71708. return re_parse_error(s, "malformed unicode char");
  71709. }
  71710. }
  71711. break;
  71712. }
  71713. *pp = p;
  71714. return c;
  71715. }
  71716. static int re_emit_range(REParseState *s, const CharRange *cr)
  71717. {
  71718. int len, i;
  71719. uint32_t high;
  71720. len = (unsigned)cr->len / 2;
  71721. if (len >= 65535)
  71722. return re_parse_error(s, "too many ranges");
  71723. if (len == 0) {
  71724. /* not sure it can really happen. Emit a match that is always
  71725. false */
  71726. re_emit_op_u32(s, REOP_char32, -1);
  71727. } else {
  71728. high = cr->points[cr->len - 1];
  71729. if (high == UINT32_MAX)
  71730. high = cr->points[cr->len - 2];
  71731. if (high <= 0xffff) {
  71732. /* can use 16 bit ranges with the conversion that 0xffff =
  71733. infinity */
  71734. re_emit_op_u16(s, REOP_range, len);
  71735. for(i = 0; i < cr->len; i += 2) {
  71736. dbuf_put_u16(&s->byte_code, cr->points[i]);
  71737. high = cr->points[i + 1] - 1;
  71738. if (high == UINT32_MAX - 1)
  71739. high = 0xffff;
  71740. dbuf_put_u16(&s->byte_code, high);
  71741. }
  71742. } else {
  71743. re_emit_op_u16(s, REOP_range32, len);
  71744. for(i = 0; i < cr->len; i += 2) {
  71745. dbuf_put_u32(&s->byte_code, cr->points[i]);
  71746. dbuf_put_u32(&s->byte_code, cr->points[i + 1] - 1);
  71747. }
  71748. }
  71749. }
  71750. return 0;
  71751. }
  71752. // s->unicode turns patterns like []] into syntax errors
  71753. // s->unicode_sets turns more patterns into errors, like [a-] or [[]
  71754. static int re_parse_char_class(REParseState *s, const uint8_t **pp)
  71755. {
  71756. const uint8_t *p;
  71757. uint32_t c1, c2;
  71758. CharRange cr_s, *cr = &cr_s;
  71759. CharRange cr1_s, *cr1 = &cr1_s;
  71760. bool invert;
  71761. cr_init(cr, s->opaque, lre_realloc);
  71762. p = *pp;
  71763. p++; /* skip '[' */
  71764. if (s->unicode_sets) {
  71765. static const char verboten[] =
  71766. "()[{}/-|" "\0"
  71767. "&&!!##$$%%**++,,..::;;<<==>>??@@``~~" "\0"
  71768. "^^^_^^";
  71769. const char *s = verboten;
  71770. int n = 1;
  71771. do {
  71772. if (!memcmp(s, p, n))
  71773. if (p[n] == ']')
  71774. goto invalid_class_range;
  71775. s += n;
  71776. if (!*s) {
  71777. s++;
  71778. n++;
  71779. }
  71780. } while (n < 4);
  71781. }
  71782. invert = false;
  71783. if (*p == '^') {
  71784. p++;
  71785. invert = true;
  71786. }
  71787. for(;;) {
  71788. if (*p == ']')
  71789. break;
  71790. c1 = get_class_atom(s, cr1, &p, true);
  71791. if ((int)c1 < 0)
  71792. goto fail;
  71793. if (*p == '-' && p[1] == ']' && s->unicode_sets) {
  71794. if (c1 >= CLASS_RANGE_BASE)
  71795. cr_free(cr1);
  71796. goto invalid_class_range;
  71797. }
  71798. if (*p == '-' && p[1] != ']') {
  71799. const uint8_t *p0 = p + 1;
  71800. if (c1 >= CLASS_RANGE_BASE) {
  71801. if (s->is_unicode) {
  71802. cr_free(cr1);
  71803. goto invalid_class_range;
  71804. }
  71805. /* Annex B: match '-' character */
  71806. goto class_atom;
  71807. }
  71808. c2 = get_class_atom(s, cr1, &p0, true);
  71809. if ((int)c2 < 0)
  71810. goto fail;
  71811. if (c2 >= CLASS_RANGE_BASE) {
  71812. cr_free(cr1);
  71813. if (s->is_unicode) {
  71814. goto invalid_class_range;
  71815. }
  71816. /* Annex B: match '-' character */
  71817. goto class_atom;
  71818. }
  71819. p = p0;
  71820. if (c2 < c1) {
  71821. invalid_class_range:
  71822. re_parse_error(s, "invalid class range");
  71823. goto fail;
  71824. }
  71825. if (cr_union_interval(cr, c1, c2))
  71826. goto memory_error;
  71827. } else {
  71828. class_atom:
  71829. if (c1 >= CLASS_RANGE_BASE) {
  71830. int ret;
  71831. ret = cr_union1(cr, cr1->points, cr1->len);
  71832. cr_free(cr1);
  71833. if (ret)
  71834. goto memory_error;
  71835. } else {
  71836. if (cr_union_interval(cr, c1, c1))
  71837. goto memory_error;
  71838. }
  71839. }
  71840. }
  71841. if (s->ignore_case) {
  71842. if (cr_regexp_canonicalize(cr, s->is_unicode))
  71843. goto memory_error;
  71844. }
  71845. if (invert) {
  71846. if (cr_invert(cr))
  71847. goto memory_error;
  71848. }
  71849. if (re_emit_range(s, cr))
  71850. goto fail;
  71851. cr_free(cr);
  71852. p++; /* skip ']' */
  71853. *pp = p;
  71854. return 0;
  71855. memory_error:
  71856. re_parse_out_of_memory(s);
  71857. fail:
  71858. cr_free(cr);
  71859. return -1;
  71860. }
  71861. /* Return:
  71862. - true if the opcodes may not advance the char pointer
  71863. - false if the opcodes always advance the char pointer
  71864. */
  71865. static bool re_need_check_advance(const uint8_t *bc_buf, int bc_buf_len)
  71866. {
  71867. int pos, opcode, len;
  71868. uint32_t val;
  71869. bool ret;
  71870. ret = true;
  71871. pos = 0;
  71872. while (pos < bc_buf_len) {
  71873. opcode = bc_buf[pos];
  71874. len = reopcode_info[opcode].size;
  71875. switch(opcode) {
  71876. case REOP_range:
  71877. val = get_u16(bc_buf + pos + 1);
  71878. len += val * 4;
  71879. goto simple_char;
  71880. case REOP_range32:
  71881. val = get_u16(bc_buf + pos + 1);
  71882. len += val * 8;
  71883. goto simple_char;
  71884. case REOP_char32:
  71885. case REOP_char16:
  71886. case REOP_char8:
  71887. case REOP_dot:
  71888. case REOP_any:
  71889. simple_char:
  71890. ret = false;
  71891. break;
  71892. case REOP_line_start:
  71893. case REOP_line_end:
  71894. case REOP_push_i32:
  71895. case REOP_push_char_pos:
  71896. case REOP_drop:
  71897. case REOP_word_boundary:
  71898. case REOP_not_word_boundary:
  71899. case REOP_prev:
  71900. /* no effect */
  71901. break;
  71902. case REOP_save_start:
  71903. case REOP_save_end:
  71904. case REOP_save_reset:
  71905. case REOP_back_reference:
  71906. case REOP_backward_back_reference:
  71907. break;
  71908. default:
  71909. /* safe behvior: we cannot predict the outcome */
  71910. return true;
  71911. }
  71912. pos += len;
  71913. }
  71914. return ret;
  71915. }
  71916. /* return -1 if a simple quantifier cannot be used. Otherwise return
  71917. the number of characters in the atom. */
  71918. static int re_is_simple_quantifier(const uint8_t *bc_buf, int bc_buf_len)
  71919. {
  71920. int pos, opcode, len, count;
  71921. uint32_t val;
  71922. count = 0;
  71923. pos = 0;
  71924. while (pos < bc_buf_len) {
  71925. opcode = bc_buf[pos];
  71926. len = reopcode_info[opcode].size;
  71927. switch(opcode) {
  71928. case REOP_range:
  71929. val = get_u16(bc_buf + pos + 1);
  71930. len += val * 4;
  71931. goto simple_char;
  71932. case REOP_range32:
  71933. val = get_u16(bc_buf + pos + 1);
  71934. len += val * 8;
  71935. goto simple_char;
  71936. case REOP_char32:
  71937. case REOP_char16:
  71938. case REOP_char8:
  71939. case REOP_dot:
  71940. case REOP_any:
  71941. simple_char:
  71942. count++;
  71943. break;
  71944. case REOP_line_start:
  71945. case REOP_line_end:
  71946. case REOP_word_boundary:
  71947. case REOP_not_word_boundary:
  71948. break;
  71949. default:
  71950. return -1;
  71951. }
  71952. pos += len;
  71953. }
  71954. return count;
  71955. }
  71956. /* '*pp' is the first char after '<' */
  71957. static int re_parse_group_name(char *buf, int buf_size, const uint8_t **pp)
  71958. {
  71959. const uint8_t *p, *p_next;
  71960. uint32_t c, d;
  71961. char *q;
  71962. p = *pp;
  71963. q = buf;
  71964. for(;;) {
  71965. c = *p++;
  71966. if (c == '\\') {
  71967. if (*p != 'u')
  71968. return -1;
  71969. c = lre_parse_escape(&p, 2); // accept surrogate pairs
  71970. if ((int)c < 0)
  71971. return -1;
  71972. } else if (c == '>') {
  71973. break;
  71974. } else if (c >= 0x80) {
  71975. c = utf8_decode(p - 1, &p_next);
  71976. if (p_next == p)
  71977. return -1;
  71978. p = p_next;
  71979. if (is_hi_surrogate(c)) {
  71980. d = utf8_decode(p, &p_next);
  71981. if (is_lo_surrogate(d)) {
  71982. c = from_surrogate(c, d);
  71983. p = p_next;
  71984. }
  71985. }
  71986. }
  71987. if (q == buf) {
  71988. if (!lre_js_is_ident_first(c))
  71989. return -1;
  71990. } else {
  71991. if (!lre_js_is_ident_next(c))
  71992. return -1;
  71993. }
  71994. if ((q - buf + UTF8_CHAR_LEN_MAX + 1) > buf_size)
  71995. return -1;
  71996. if (c < 0x80) {
  71997. *q++ = c;
  71998. } else {
  71999. q += utf8_encode((uint8_t*)q, c);
  72000. }
  72001. }
  72002. if (q == buf)
  72003. return -1;
  72004. *q = '\0';
  72005. *pp = p;
  72006. return 0;
  72007. }
  72008. /* if capture_name = NULL: return the number of captures + 1.
  72009. Otherwise, return the capture index corresponding to capture_name
  72010. or -1 if none */
  72011. static int re_parse_captures(REParseState *s, int *phas_named_captures,
  72012. const char *capture_name)
  72013. {
  72014. const uint8_t *p;
  72015. int capture_index;
  72016. char name[TMP_BUF_SIZE];
  72017. capture_index = 1;
  72018. *phas_named_captures = 0;
  72019. for (p = s->buf_start; p < s->buf_end; p++) {
  72020. switch (*p) {
  72021. case '(':
  72022. if (p[1] == '?') {
  72023. if (p[2] == '<' && p[3] != '=' && p[3] != '!') {
  72024. *phas_named_captures = 1;
  72025. /* potential named capture */
  72026. if (capture_name) {
  72027. p += 3;
  72028. if (re_parse_group_name(name, sizeof(name), &p) == 0) {
  72029. if (!strcmp(name, capture_name))
  72030. return capture_index;
  72031. }
  72032. }
  72033. capture_index++;
  72034. if (capture_index >= CAPTURE_COUNT_MAX)
  72035. goto done;
  72036. }
  72037. } else {
  72038. capture_index++;
  72039. if (capture_index >= CAPTURE_COUNT_MAX)
  72040. goto done;
  72041. }
  72042. break;
  72043. case '\\':
  72044. p++;
  72045. break;
  72046. case '[':
  72047. for (p += 1 + (*p == ']'); p < s->buf_end && *p != ']'; p++) {
  72048. if (*p == '\\')
  72049. p++;
  72050. }
  72051. break;
  72052. }
  72053. }
  72054. done:
  72055. if (capture_name)
  72056. return -1;
  72057. else
  72058. return capture_index;
  72059. }
  72060. static int re_count_captures(REParseState *s)
  72061. {
  72062. if (s->total_capture_count < 0) {
  72063. s->total_capture_count = re_parse_captures(s, &s->has_named_captures,
  72064. NULL);
  72065. }
  72066. return s->total_capture_count;
  72067. }
  72068. static bool re_has_named_captures(REParseState *s)
  72069. {
  72070. if (s->has_named_captures < 0)
  72071. re_count_captures(s);
  72072. return s->has_named_captures;
  72073. }
  72074. static int find_group_name(REParseState *s, const char *name)
  72075. {
  72076. const char *p, *buf_end;
  72077. size_t len, name_len;
  72078. int capture_index;
  72079. p = (char *)s->group_names.buf;
  72080. if (!p) return -1;
  72081. buf_end = (char *)s->group_names.buf + s->group_names.size;
  72082. name_len = strlen(name);
  72083. capture_index = 1;
  72084. while (p < buf_end) {
  72085. len = strlen(p);
  72086. if (len == name_len && memcmp(name, p, name_len) == 0)
  72087. return capture_index;
  72088. p += len + 1;
  72089. capture_index++;
  72090. }
  72091. return -1;
  72092. }
  72093. static int re_parse_disjunction(REParseState *s, bool is_backward_dir);
  72094. static int re_parse_term(REParseState *s, bool is_backward_dir)
  72095. {
  72096. const uint8_t *p;
  72097. int c, last_atom_start, quant_min, quant_max, last_capture_count;
  72098. bool greedy, add_zero_advance_check, is_neg, is_backward_lookahead;
  72099. CharRange cr_s, *cr = &cr_s;
  72100. last_atom_start = -1;
  72101. last_capture_count = 0;
  72102. p = s->buf_ptr;
  72103. c = *p;
  72104. switch(c) {
  72105. case '^':
  72106. p++;
  72107. re_emit_op(s, REOP_line_start);
  72108. break;
  72109. case '$':
  72110. p++;
  72111. re_emit_op(s, REOP_line_end);
  72112. break;
  72113. case '.':
  72114. p++;
  72115. last_atom_start = s->byte_code.size;
  72116. last_capture_count = s->capture_count;
  72117. if (is_backward_dir)
  72118. re_emit_op(s, REOP_prev);
  72119. re_emit_op(s, s->dotall ? REOP_any : REOP_dot);
  72120. if (is_backward_dir)
  72121. re_emit_op(s, REOP_prev);
  72122. break;
  72123. case '{':
  72124. if (s->is_unicode) {
  72125. return re_parse_error(s, "syntax error");
  72126. } else if (!lre_is_digit(p[1])) {
  72127. /* Annex B: we accept '{' not followed by digits as a
  72128. normal atom */
  72129. goto parse_class_atom;
  72130. } else {
  72131. const uint8_t *p1 = p + 1;
  72132. /* Annex B: error if it is like a repetition count */
  72133. parse_digits(&p1, true);
  72134. if (*p1 == ',') {
  72135. p1++;
  72136. if (lre_is_digit(*p1)) {
  72137. parse_digits(&p1, true);
  72138. }
  72139. }
  72140. if (*p1 != '}') {
  72141. goto parse_class_atom;
  72142. }
  72143. }
  72144. /* fall thru */
  72145. case '*':
  72146. case '+':
  72147. case '?':
  72148. return re_parse_error(s, "nothing to repeat");
  72149. case '(':
  72150. if (p[1] == '?') {
  72151. if (p[2] == ':') {
  72152. p += 3;
  72153. last_atom_start = s->byte_code.size;
  72154. last_capture_count = s->capture_count;
  72155. s->buf_ptr = p;
  72156. if (re_parse_disjunction(s, is_backward_dir))
  72157. return -1;
  72158. p = s->buf_ptr;
  72159. if (re_parse_expect(s, &p, ')'))
  72160. return -1;
  72161. } else if ((p[2] == '=' || p[2] == '!')) {
  72162. is_neg = (p[2] == '!');
  72163. is_backward_lookahead = false;
  72164. p += 3;
  72165. goto lookahead;
  72166. } else if (p[2] == '<' &&
  72167. (p[3] == '=' || p[3] == '!')) {
  72168. int pos;
  72169. is_neg = (p[3] == '!');
  72170. is_backward_lookahead = true;
  72171. p += 4;
  72172. /* lookahead */
  72173. lookahead:
  72174. /* Annex B allows lookahead to be used as an atom for
  72175. the quantifiers */
  72176. if (!s->is_unicode && !is_backward_lookahead) {
  72177. last_atom_start = s->byte_code.size;
  72178. last_capture_count = s->capture_count;
  72179. }
  72180. pos = re_emit_op_u32(s, REOP_lookahead + is_neg, 0);
  72181. s->buf_ptr = p;
  72182. if (re_parse_disjunction(s, is_backward_lookahead))
  72183. return -1;
  72184. p = s->buf_ptr;
  72185. if (re_parse_expect(s, &p, ')'))
  72186. return -1;
  72187. re_emit_op(s, REOP_match);
  72188. /* jump after the 'match' after the lookahead is successful */
  72189. if (dbuf_error(&s->byte_code))
  72190. return -1;
  72191. put_u32(s->byte_code.buf + pos, s->byte_code.size - (pos + 4));
  72192. } else if (p[2] == '<') {
  72193. p += 3;
  72194. if (re_parse_group_name(s->u.tmp_buf, sizeof(s->u.tmp_buf),
  72195. &p)) {
  72196. return re_parse_error(s, "invalid group name");
  72197. }
  72198. if (find_group_name(s, s->u.tmp_buf) > 0) {
  72199. return re_parse_error(s, "duplicate group name");
  72200. }
  72201. /* group name with a trailing zero */
  72202. dbuf_put(&s->group_names, (uint8_t *)s->u.tmp_buf,
  72203. strlen(s->u.tmp_buf) + 1);
  72204. s->has_named_captures = 1;
  72205. goto parse_capture;
  72206. } else {
  72207. return re_parse_error(s, "invalid group");
  72208. }
  72209. } else {
  72210. int capture_index;
  72211. p++;
  72212. /* capture without group name */
  72213. dbuf_putc(&s->group_names, 0);
  72214. parse_capture:
  72215. if (s->capture_count >= CAPTURE_COUNT_MAX)
  72216. return re_parse_error(s, "too many captures");
  72217. last_atom_start = s->byte_code.size;
  72218. last_capture_count = s->capture_count;
  72219. capture_index = s->capture_count++;
  72220. re_emit_op_u8(s, REOP_save_start + is_backward_dir,
  72221. capture_index);
  72222. s->buf_ptr = p;
  72223. if (re_parse_disjunction(s, is_backward_dir))
  72224. return -1;
  72225. p = s->buf_ptr;
  72226. re_emit_op_u8(s, REOP_save_start + 1 - is_backward_dir,
  72227. capture_index);
  72228. if (re_parse_expect(s, &p, ')'))
  72229. return -1;
  72230. }
  72231. break;
  72232. case '\\':
  72233. switch(p[1]) {
  72234. case 'b':
  72235. case 'B':
  72236. re_emit_op(s, REOP_word_boundary + (p[1] != 'b'));
  72237. p += 2;
  72238. break;
  72239. case 'k':
  72240. {
  72241. const uint8_t *p1;
  72242. int dummy_res;
  72243. p1 = p;
  72244. if (p1[2] != '<') {
  72245. /* annex B: we tolerate invalid group names in non
  72246. unicode mode if there is no named capture
  72247. definition */
  72248. if (s->is_unicode || re_has_named_captures(s))
  72249. return re_parse_error(s, "expecting group name");
  72250. else
  72251. goto parse_class_atom;
  72252. }
  72253. p1 += 3;
  72254. if (re_parse_group_name(s->u.tmp_buf, sizeof(s->u.tmp_buf),
  72255. &p1)) {
  72256. if (s->is_unicode || re_has_named_captures(s))
  72257. return re_parse_error(s, "invalid group name");
  72258. else
  72259. goto parse_class_atom;
  72260. }
  72261. c = find_group_name(s, s->u.tmp_buf);
  72262. if (c < 0) {
  72263. /* no capture name parsed before, try to look
  72264. after (inefficient, but hopefully not common */
  72265. c = re_parse_captures(s, &dummy_res, s->u.tmp_buf);
  72266. if (c < 0) {
  72267. if (s->is_unicode || re_has_named_captures(s))
  72268. return re_parse_error(s, "group name not defined");
  72269. else
  72270. goto parse_class_atom;
  72271. }
  72272. }
  72273. p = p1;
  72274. }
  72275. goto emit_back_reference;
  72276. case '0':
  72277. p += 2;
  72278. c = 0;
  72279. if (s->is_unicode) {
  72280. if (lre_is_digit(*p)) {
  72281. return re_parse_error(s, "invalid decimal escape in regular expression");
  72282. }
  72283. } else {
  72284. /* Annex B.1.4: accept legacy octal */
  72285. if (*p >= '0' && *p <= '7') {
  72286. c = *p++ - '0';
  72287. if (*p >= '0' && *p <= '7') {
  72288. c = (c << 3) + *p++ - '0';
  72289. }
  72290. }
  72291. }
  72292. goto normal_char;
  72293. case '1': case '2': case '3': case '4':
  72294. case '5': case '6': case '7': case '8':
  72295. case '9':
  72296. {
  72297. const uint8_t *q = ++p;
  72298. c = parse_digits(&p, false);
  72299. if (c < 0 || (c >= s->capture_count && c >= re_count_captures(s))) {
  72300. if (!s->is_unicode) {
  72301. /* Annex B.1.4: accept legacy octal */
  72302. p = q;
  72303. if (*p <= '7') {
  72304. c = 0;
  72305. if (*p <= '3')
  72306. c = *p++ - '0';
  72307. if (*p >= '0' && *p <= '7') {
  72308. c = (c << 3) + *p++ - '0';
  72309. if (*p >= '0' && *p <= '7') {
  72310. c = (c << 3) + *p++ - '0';
  72311. }
  72312. }
  72313. } else {
  72314. c = *p++;
  72315. }
  72316. goto normal_char;
  72317. }
  72318. return re_parse_error(s, "back reference out of range in regular expression");
  72319. }
  72320. emit_back_reference:
  72321. last_atom_start = s->byte_code.size;
  72322. last_capture_count = s->capture_count;
  72323. re_emit_op_u8(s, REOP_back_reference + is_backward_dir, c);
  72324. }
  72325. break;
  72326. default:
  72327. goto parse_class_atom;
  72328. }
  72329. break;
  72330. case '[':
  72331. last_atom_start = s->byte_code.size;
  72332. last_capture_count = s->capture_count;
  72333. if (is_backward_dir)
  72334. re_emit_op(s, REOP_prev);
  72335. if (re_parse_char_class(s, &p))
  72336. return -1;
  72337. if (is_backward_dir)
  72338. re_emit_op(s, REOP_prev);
  72339. break;
  72340. case ']':
  72341. case '}':
  72342. if (s->is_unicode)
  72343. return re_parse_error(s, "syntax error");
  72344. goto parse_class_atom;
  72345. default:
  72346. parse_class_atom:
  72347. c = get_class_atom(s, cr, &p, false);
  72348. if ((int)c < 0)
  72349. return -1;
  72350. normal_char:
  72351. last_atom_start = s->byte_code.size;
  72352. last_capture_count = s->capture_count;
  72353. if (is_backward_dir)
  72354. re_emit_op(s, REOP_prev);
  72355. if (c >= CLASS_RANGE_BASE) {
  72356. int ret;
  72357. /* Note: canonicalization is not needed */
  72358. ret = re_emit_range(s, cr);
  72359. cr_free(cr);
  72360. if (ret)
  72361. return -1;
  72362. } else {
  72363. if (s->ignore_case)
  72364. c = lre_canonicalize(c, s->is_unicode);
  72365. if (c <= 0x7f)
  72366. re_emit_op_u8(s, REOP_char8, c);
  72367. else if (c <= 0xffff)
  72368. re_emit_op_u16(s, REOP_char16, c);
  72369. else
  72370. re_emit_op_u32(s, REOP_char32, c);
  72371. }
  72372. if (is_backward_dir)
  72373. re_emit_op(s, REOP_prev);
  72374. break;
  72375. }
  72376. /* quantifier */
  72377. if (last_atom_start >= 0) {
  72378. c = *p;
  72379. switch(c) {
  72380. case '*':
  72381. p++;
  72382. quant_min = 0;
  72383. quant_max = INT32_MAX;
  72384. goto quantifier;
  72385. case '+':
  72386. p++;
  72387. quant_min = 1;
  72388. quant_max = INT32_MAX;
  72389. goto quantifier;
  72390. case '?':
  72391. p++;
  72392. quant_min = 0;
  72393. quant_max = 1;
  72394. goto quantifier;
  72395. case '{':
  72396. {
  72397. const uint8_t *p1 = p;
  72398. /* As an extension (see ES6 annex B), we accept '{' not
  72399. followed by digits as a normal atom */
  72400. if (!lre_is_digit(p[1])) {
  72401. if (s->is_unicode)
  72402. goto invalid_quant_count;
  72403. break;
  72404. }
  72405. p++;
  72406. quant_min = parse_digits(&p, true);
  72407. quant_max = quant_min;
  72408. if (*p == ',') {
  72409. p++;
  72410. if (lre_is_digit(*p)) {
  72411. quant_max = parse_digits(&p, true);
  72412. if (quant_max < quant_min) {
  72413. invalid_quant_count:
  72414. return re_parse_error(s, "invalid repetition count");
  72415. }
  72416. } else {
  72417. quant_max = INT32_MAX; /* infinity */
  72418. }
  72419. }
  72420. if (*p != '}' && !s->is_unicode) {
  72421. /* Annex B: normal atom if invalid '{' syntax */
  72422. p = p1;
  72423. break;
  72424. }
  72425. if (re_parse_expect(s, &p, '}'))
  72426. return -1;
  72427. }
  72428. quantifier:
  72429. greedy = true;
  72430. if (*p == '?') {
  72431. p++;
  72432. greedy = false;
  72433. }
  72434. if (last_atom_start < 0) {
  72435. return re_parse_error(s, "nothing to repeat");
  72436. }
  72437. if (greedy) {
  72438. int len, pos;
  72439. if (quant_max > 0) {
  72440. /* specific optimization for simple quantifiers */
  72441. if (dbuf_error(&s->byte_code))
  72442. goto out_of_memory;
  72443. len = re_is_simple_quantifier(s->byte_code.buf + last_atom_start,
  72444. s->byte_code.size - last_atom_start);
  72445. if (len > 0) {
  72446. re_emit_op(s, REOP_match);
  72447. if (dbuf_insert(&s->byte_code, last_atom_start, 17))
  72448. goto out_of_memory;
  72449. pos = last_atom_start;
  72450. s->byte_code.buf[pos++] = REOP_simple_greedy_quant;
  72451. put_u32(&s->byte_code.buf[pos],
  72452. s->byte_code.size - last_atom_start - 17);
  72453. pos += 4;
  72454. put_u32(&s->byte_code.buf[pos], quant_min);
  72455. pos += 4;
  72456. put_u32(&s->byte_code.buf[pos], quant_max);
  72457. pos += 4;
  72458. put_u32(&s->byte_code.buf[pos], len);
  72459. pos += 4;
  72460. goto done;
  72461. }
  72462. }
  72463. if (dbuf_error(&s->byte_code))
  72464. goto out_of_memory;
  72465. }
  72466. /* the spec tells that if there is no advance when
  72467. running the atom after the first quant_min times,
  72468. then there is no match. We remove this test when we
  72469. are sure the atom always advances the position. */
  72470. add_zero_advance_check = re_need_check_advance(s->byte_code.buf + last_atom_start,
  72471. s->byte_code.size - last_atom_start);
  72472. {
  72473. int len, pos;
  72474. len = s->byte_code.size - last_atom_start;
  72475. if (quant_min == 0) {
  72476. /* need to reset the capture in case the atom is
  72477. not executed */
  72478. if (last_capture_count != s->capture_count) {
  72479. if (dbuf_insert(&s->byte_code, last_atom_start, 3))
  72480. goto out_of_memory;
  72481. s->byte_code.buf[last_atom_start++] = REOP_save_reset;
  72482. s->byte_code.buf[last_atom_start++] = last_capture_count;
  72483. s->byte_code.buf[last_atom_start++] = s->capture_count - 1;
  72484. }
  72485. if (quant_max == 0) {
  72486. s->byte_code.size = last_atom_start;
  72487. } else if (quant_max == 1 || quant_max == INT32_MAX) {
  72488. bool has_goto = (quant_max == INT32_MAX);
  72489. if (dbuf_insert(&s->byte_code, last_atom_start, 5 + add_zero_advance_check))
  72490. goto out_of_memory;
  72491. s->byte_code.buf[last_atom_start] = REOP_split_goto_first +
  72492. greedy;
  72493. put_u32(s->byte_code.buf + last_atom_start + 1,
  72494. len + 5 * has_goto + add_zero_advance_check * 2);
  72495. if (add_zero_advance_check) {
  72496. s->byte_code.buf[last_atom_start + 1 + 4] = REOP_push_char_pos;
  72497. re_emit_op(s, REOP_check_advance);
  72498. }
  72499. if (has_goto)
  72500. re_emit_goto(s, REOP_goto, last_atom_start);
  72501. } else {
  72502. if (dbuf_insert(&s->byte_code, last_atom_start, 10 + add_zero_advance_check))
  72503. goto out_of_memory;
  72504. pos = last_atom_start;
  72505. s->byte_code.buf[pos++] = REOP_push_i32;
  72506. put_u32(s->byte_code.buf + pos, quant_max);
  72507. pos += 4;
  72508. s->byte_code.buf[pos++] = REOP_split_goto_first + greedy;
  72509. put_u32(s->byte_code.buf + pos, len + 5 + add_zero_advance_check * 2);
  72510. pos += 4;
  72511. if (add_zero_advance_check) {
  72512. s->byte_code.buf[pos++] = REOP_push_char_pos;
  72513. re_emit_op(s, REOP_check_advance);
  72514. }
  72515. re_emit_goto(s, REOP_loop, last_atom_start + 5);
  72516. re_emit_op(s, REOP_drop);
  72517. }
  72518. } else if (quant_min == 1 && quant_max == INT32_MAX &&
  72519. !add_zero_advance_check) {
  72520. re_emit_goto(s, REOP_split_next_first - greedy,
  72521. last_atom_start);
  72522. } else {
  72523. if (quant_min == 1) {
  72524. /* nothing to add */
  72525. } else {
  72526. if (dbuf_insert(&s->byte_code, last_atom_start, 5))
  72527. goto out_of_memory;
  72528. s->byte_code.buf[last_atom_start] = REOP_push_i32;
  72529. put_u32(s->byte_code.buf + last_atom_start + 1,
  72530. quant_min);
  72531. last_atom_start += 5;
  72532. re_emit_goto(s, REOP_loop, last_atom_start);
  72533. re_emit_op(s, REOP_drop);
  72534. }
  72535. if (quant_max == INT32_MAX) {
  72536. pos = s->byte_code.size;
  72537. re_emit_op_u32(s, REOP_split_goto_first + greedy,
  72538. len + 5 + add_zero_advance_check * 2);
  72539. if (add_zero_advance_check)
  72540. re_emit_op(s, REOP_push_char_pos);
  72541. /* copy the atom */
  72542. dbuf_put_self(&s->byte_code, last_atom_start, len);
  72543. if (add_zero_advance_check)
  72544. re_emit_op(s, REOP_check_advance);
  72545. re_emit_goto(s, REOP_goto, pos);
  72546. } else if (quant_max > quant_min) {
  72547. re_emit_op_u32(s, REOP_push_i32, quant_max - quant_min);
  72548. pos = s->byte_code.size;
  72549. re_emit_op_u32(s, REOP_split_goto_first + greedy,
  72550. len + 5 + add_zero_advance_check * 2);
  72551. if (add_zero_advance_check)
  72552. re_emit_op(s, REOP_push_char_pos);
  72553. /* copy the atom */
  72554. dbuf_put_self(&s->byte_code, last_atom_start, len);
  72555. if (add_zero_advance_check)
  72556. re_emit_op(s, REOP_check_advance);
  72557. re_emit_goto(s, REOP_loop, pos);
  72558. re_emit_op(s, REOP_drop);
  72559. }
  72560. }
  72561. last_atom_start = -1;
  72562. }
  72563. break;
  72564. default:
  72565. break;
  72566. }
  72567. }
  72568. done:
  72569. s->buf_ptr = p;
  72570. return 0;
  72571. out_of_memory:
  72572. return re_parse_out_of_memory(s);
  72573. }
  72574. static int re_parse_alternative(REParseState *s, bool is_backward_dir)
  72575. {
  72576. const uint8_t *p;
  72577. int ret;
  72578. size_t start, term_start, end, term_size;
  72579. start = s->byte_code.size;
  72580. for(;;) {
  72581. p = s->buf_ptr;
  72582. if (p >= s->buf_end)
  72583. break;
  72584. if (*p == '|' || *p == ')')
  72585. break;
  72586. term_start = s->byte_code.size;
  72587. ret = re_parse_term(s, is_backward_dir);
  72588. if (ret)
  72589. return ret;
  72590. if (is_backward_dir) {
  72591. /* reverse the order of the terms (XXX: inefficient, but
  72592. speed is not really critical here) */
  72593. end = s->byte_code.size;
  72594. term_size = end - term_start;
  72595. if (dbuf_realloc(&s->byte_code, end + term_size))
  72596. return -1;
  72597. memmove(s->byte_code.buf + start + term_size,
  72598. s->byte_code.buf + start,
  72599. end - start);
  72600. memcpy(s->byte_code.buf + start, s->byte_code.buf + end,
  72601. term_size);
  72602. }
  72603. }
  72604. return 0;
  72605. }
  72606. static int re_parse_disjunction(REParseState *s, bool is_backward_dir)
  72607. {
  72608. int start, len, pos;
  72609. if (lre_check_stack_overflow(s->opaque, 0))
  72610. return re_parse_error(s, "stack overflow");
  72611. start = s->byte_code.size;
  72612. if (re_parse_alternative(s, is_backward_dir))
  72613. return -1;
  72614. while (*s->buf_ptr == '|') {
  72615. s->buf_ptr++;
  72616. len = s->byte_code.size - start;
  72617. /* insert a split before the first alternative */
  72618. if (dbuf_insert(&s->byte_code, start, 5)) {
  72619. return re_parse_out_of_memory(s);
  72620. }
  72621. s->byte_code.buf[start] = REOP_split_next_first;
  72622. put_u32(s->byte_code.buf + start + 1, len + 5);
  72623. pos = re_emit_op_u32(s, REOP_goto, 0);
  72624. if (re_parse_alternative(s, is_backward_dir))
  72625. return -1;
  72626. /* patch the goto */
  72627. len = s->byte_code.size - (pos + 4);
  72628. put_u32(s->byte_code.buf + pos, len);
  72629. }
  72630. return 0;
  72631. }
  72632. /* the control flow is recursive so the analysis can be linear */
  72633. static int lre_compute_stack_size(const uint8_t *bc_buf, int bc_buf_len)
  72634. {
  72635. int stack_size, stack_size_max, pos, opcode, len;
  72636. uint32_t val;
  72637. stack_size = 0;
  72638. stack_size_max = 0;
  72639. bc_buf += RE_HEADER_LEN;
  72640. bc_buf_len -= RE_HEADER_LEN;
  72641. pos = 0;
  72642. while (pos < bc_buf_len) {
  72643. opcode = bc_buf[pos];
  72644. len = reopcode_info[opcode].size;
  72645. assert(opcode < REOP_COUNT);
  72646. assert((pos + len) <= bc_buf_len);
  72647. switch(opcode) {
  72648. case REOP_push_i32:
  72649. case REOP_push_char_pos:
  72650. stack_size++;
  72651. if (stack_size > stack_size_max) {
  72652. if (stack_size > STACK_SIZE_MAX)
  72653. return -1;
  72654. stack_size_max = stack_size;
  72655. }
  72656. break;
  72657. case REOP_drop:
  72658. case REOP_check_advance:
  72659. assert(stack_size > 0);
  72660. stack_size--;
  72661. break;
  72662. case REOP_range:
  72663. val = get_u16(bc_buf + pos + 1);
  72664. len += val * 4;
  72665. break;
  72666. case REOP_range32:
  72667. val = get_u16(bc_buf + pos + 1);
  72668. len += val * 8;
  72669. break;
  72670. }
  72671. pos += len;
  72672. }
  72673. return stack_size_max;
  72674. }
  72675. /* 'buf' must be a zero terminated UTF-8 string of length buf_len.
  72676. Return NULL if error and allocate an error message in *perror_msg,
  72677. otherwise the compiled bytecode and its length in plen.
  72678. */
  72679. uint8_t *lre_compile(int *plen, char *error_msg, int error_msg_size,
  72680. const char *buf, size_t buf_len, int re_flags,
  72681. void *opaque)
  72682. {
  72683. REParseState s_s, *s = &s_s;
  72684. int stack_size;
  72685. bool is_sticky;
  72686. memset(s, 0, sizeof(*s));
  72687. s->opaque = opaque;
  72688. s->buf_ptr = (const uint8_t *)buf;
  72689. s->buf_end = s->buf_ptr + buf_len;
  72690. s->buf_start = s->buf_ptr;
  72691. s->re_flags = re_flags;
  72692. s->is_unicode = ((re_flags & LRE_FLAG_UNICODE) != 0);
  72693. is_sticky = ((re_flags & LRE_FLAG_STICKY) != 0);
  72694. s->ignore_case = ((re_flags & LRE_FLAG_IGNORECASE) != 0);
  72695. s->dotall = ((re_flags & LRE_FLAG_DOTALL) != 0);
  72696. s->unicode_sets = ((re_flags & LRE_FLAG_UNICODE_SETS) != 0);
  72697. s->capture_count = 1;
  72698. s->total_capture_count = -1;
  72699. s->has_named_captures = -1;
  72700. dbuf_init2(&s->byte_code, opaque, lre_realloc);
  72701. dbuf_init2(&s->group_names, opaque, lre_realloc);
  72702. dbuf_put_u16(&s->byte_code, re_flags); /* first element is the flags */
  72703. dbuf_putc(&s->byte_code, 0); /* second element is the number of captures */
  72704. dbuf_putc(&s->byte_code, 0); /* stack size */
  72705. dbuf_put_u32(&s->byte_code, 0); /* bytecode length */
  72706. if (!is_sticky) {
  72707. /* iterate thru all positions (about the same as .*?( ... ) )
  72708. . We do it without an explicit loop so that lock step
  72709. thread execution will be possible in an optimized
  72710. implementation */
  72711. re_emit_op_u32(s, REOP_split_goto_first, 1 + 5);
  72712. re_emit_op(s, REOP_any);
  72713. re_emit_op_u32(s, REOP_goto, -(5 + 1 + 5));
  72714. }
  72715. re_emit_op_u8(s, REOP_save_start, 0);
  72716. if (re_parse_disjunction(s, false)) {
  72717. error:
  72718. dbuf_free(&s->byte_code);
  72719. dbuf_free(&s->group_names);
  72720. js__pstrcpy(error_msg, error_msg_size, s->u.error_msg);
  72721. *plen = 0;
  72722. return NULL;
  72723. }
  72724. re_emit_op_u8(s, REOP_save_end, 0);
  72725. re_emit_op(s, REOP_match);
  72726. if (*s->buf_ptr != '\0') {
  72727. re_parse_error(s, "extraneous characters at the end");
  72728. goto error;
  72729. }
  72730. if (dbuf_error(&s->byte_code)) {
  72731. re_parse_out_of_memory(s);
  72732. goto error;
  72733. }
  72734. stack_size = lre_compute_stack_size(s->byte_code.buf, s->byte_code.size);
  72735. if (stack_size < 0) {
  72736. re_parse_error(s, "too many imbricated quantifiers");
  72737. goto error;
  72738. }
  72739. s->byte_code.buf[RE_HEADER_CAPTURE_COUNT] = s->capture_count;
  72740. s->byte_code.buf[RE_HEADER_STACK_SIZE] = stack_size;
  72741. put_u32(s->byte_code.buf + RE_HEADER_BYTECODE_LEN,
  72742. s->byte_code.size - RE_HEADER_LEN);
  72743. /* add the named groups if needed */
  72744. if (s->group_names.size > (s->capture_count - 1)) {
  72745. dbuf_put(&s->byte_code, s->group_names.buf, s->group_names.size);
  72746. put_u16(s->byte_code.buf + RE_HEADER_FLAGS,
  72747. LRE_FLAG_NAMED_GROUPS | lre_get_flags(s->byte_code.buf));
  72748. }
  72749. dbuf_free(&s->group_names);
  72750. #ifdef DUMP_REOP
  72751. lre_dump_bytecode(s->byte_code.buf, s->byte_code.size);
  72752. #endif
  72753. error_msg[0] = '\0';
  72754. *plen = s->byte_code.size;
  72755. return s->byte_code.buf;
  72756. }
  72757. static bool is_line_terminator(uint32_t c)
  72758. {
  72759. return (c == '\n' || c == '\r' || c == CP_LS || c == CP_PS);
  72760. }
  72761. static bool is_word_char(uint32_t c)
  72762. {
  72763. return ((c >= '0' && c <= '9') ||
  72764. (c >= 'a' && c <= 'z') ||
  72765. (c >= 'A' && c <= 'Z') ||
  72766. (c == '_'));
  72767. }
  72768. #define GET_CHAR(c, cptr, cbuf_end, cbuf_type) \
  72769. do { \
  72770. if (cbuf_type == 0) { \
  72771. c = *cptr++; \
  72772. } else { \
  72773. const uint16_t *_p = (const uint16_t *)cptr; \
  72774. const uint16_t *_end = (const uint16_t *)cbuf_end; \
  72775. c = *_p++; \
  72776. if (is_hi_surrogate(c)) \
  72777. if (cbuf_type == 2) \
  72778. if (_p < _end) \
  72779. if (is_lo_surrogate(*_p)) \
  72780. c = from_surrogate(c, *_p++); \
  72781. cptr = (const void *)_p; \
  72782. } \
  72783. } while (0)
  72784. #define PEEK_CHAR(c, cptr, cbuf_end, cbuf_type) \
  72785. do { \
  72786. if (cbuf_type == 0) { \
  72787. c = cptr[0]; \
  72788. } else { \
  72789. const uint16_t *_p = (const uint16_t *)cptr; \
  72790. const uint16_t *_end = (const uint16_t *)cbuf_end; \
  72791. c = *_p++; \
  72792. if (is_hi_surrogate(c)) \
  72793. if (cbuf_type == 2) \
  72794. if (_p < _end) \
  72795. if (is_lo_surrogate(*_p)) \
  72796. c = from_surrogate(c, *_p); \
  72797. } \
  72798. } while (0)
  72799. #define PEEK_PREV_CHAR(c, cptr, cbuf_start, cbuf_type) \
  72800. do { \
  72801. if (cbuf_type == 0) { \
  72802. c = cptr[-1]; \
  72803. } else { \
  72804. const uint16_t *_p = (const uint16_t *)cptr - 1; \
  72805. const uint16_t *_start = (const uint16_t *)cbuf_start; \
  72806. c = *_p; \
  72807. if (is_lo_surrogate(c)) \
  72808. if (cbuf_type == 2) \
  72809. if (_p > _start) \
  72810. if (is_hi_surrogate(_p[-1])) \
  72811. c = from_surrogate(*--_p, c); \
  72812. } \
  72813. } while (0)
  72814. #define GET_PREV_CHAR(c, cptr, cbuf_start, cbuf_type) \
  72815. do { \
  72816. if (cbuf_type == 0) { \
  72817. cptr--; \
  72818. c = cptr[0]; \
  72819. } else { \
  72820. const uint16_t *_p = (const uint16_t *)cptr - 1; \
  72821. const uint16_t *_start = (const uint16_t *)cbuf_start; \
  72822. c = *_p; \
  72823. if (is_lo_surrogate(c)) \
  72824. if (cbuf_type == 2) \
  72825. if (_p > _start) \
  72826. if (is_hi_surrogate(_p[-1])) \
  72827. c = from_surrogate(*--_p, c); \
  72828. cptr = (const void *)_p; \
  72829. } \
  72830. } while (0)
  72831. #define PREV_CHAR(cptr, cbuf_start, cbuf_type) \
  72832. do { \
  72833. if (cbuf_type == 0) { \
  72834. cptr--; \
  72835. } else { \
  72836. const uint16_t *_p = (const uint16_t *)cptr - 1; \
  72837. const uint16_t *_start = (const uint16_t *)cbuf_start; \
  72838. if (is_lo_surrogate(*_p)) \
  72839. if (cbuf_type == 2) \
  72840. if (_p > _start) \
  72841. if (is_hi_surrogate(_p[-1])) \
  72842. _p--; \
  72843. cptr = (const void *)_p; \
  72844. } \
  72845. } while (0)
  72846. typedef uintptr_t StackInt;
  72847. typedef enum {
  72848. RE_EXEC_STATE_SPLIT,
  72849. RE_EXEC_STATE_LOOKAHEAD,
  72850. RE_EXEC_STATE_NEGATIVE_LOOKAHEAD,
  72851. RE_EXEC_STATE_GREEDY_QUANT,
  72852. } REExecStateEnum;
  72853. typedef struct REExecState {
  72854. REExecStateEnum type : 8;
  72855. uint8_t stack_len;
  72856. size_t count; /* only used for RE_EXEC_STATE_GREEDY_QUANT */
  72857. const uint8_t *cptr;
  72858. const uint8_t *pc;
  72859. void *buf[];
  72860. } REExecState;
  72861. typedef struct {
  72862. const uint8_t *cbuf;
  72863. const uint8_t *cbuf_end;
  72864. /* 0 = 8 bit chars, 1 = 16 bit chars, 2 = 16 bit chars, UTF-16 */
  72865. int cbuf_type;
  72866. int capture_count;
  72867. int stack_size_max;
  72868. bool multi_line;
  72869. bool ignore_case;
  72870. bool is_unicode;
  72871. void *opaque; /* used for stack overflow check */
  72872. size_t state_size;
  72873. uint8_t *state_stack;
  72874. size_t state_stack_size;
  72875. size_t state_stack_len;
  72876. } REExecContext;
  72877. static int push_state(REExecContext *s,
  72878. uint8_t **capture,
  72879. StackInt *stack, size_t stack_len,
  72880. const uint8_t *pc, const uint8_t *cptr,
  72881. REExecStateEnum type, size_t count)
  72882. {
  72883. REExecState *rs;
  72884. uint8_t *new_stack;
  72885. size_t new_size, i, n;
  72886. StackInt *stack_buf;
  72887. if (unlikely((s->state_stack_len + 1) > s->state_stack_size)) {
  72888. /* reallocate the stack */
  72889. new_size = s->state_stack_size * 3 / 2;
  72890. if (new_size < 8)
  72891. new_size = 8;
  72892. new_stack = lre_realloc(s->opaque, s->state_stack, new_size * s->state_size);
  72893. if (!new_stack)
  72894. return -1;
  72895. s->state_stack_size = new_size;
  72896. s->state_stack = new_stack;
  72897. }
  72898. rs = (REExecState *)(s->state_stack + s->state_stack_len * s->state_size);
  72899. s->state_stack_len++;
  72900. rs->type = type;
  72901. rs->count = count;
  72902. rs->stack_len = stack_len;
  72903. rs->cptr = cptr;
  72904. rs->pc = pc;
  72905. n = 2 * s->capture_count;
  72906. for(i = 0; i < n; i++)
  72907. rs->buf[i] = capture[i];
  72908. stack_buf = (StackInt *)(rs->buf + n);
  72909. for(i = 0; i < stack_len; i++)
  72910. stack_buf[i] = stack[i];
  72911. return 0;
  72912. }
  72913. /* return 1 if match, 0 if not match or -1 if error. */
  72914. static intptr_t lre_exec_backtrack(REExecContext *s, uint8_t **capture,
  72915. StackInt *stack, int stack_len,
  72916. const uint8_t *pc, const uint8_t *cptr,
  72917. bool no_recurse)
  72918. {
  72919. int opcode, ret;
  72920. int cbuf_type;
  72921. uint32_t val, c;
  72922. const uint8_t *cbuf_end;
  72923. cbuf_type = s->cbuf_type;
  72924. cbuf_end = s->cbuf_end;
  72925. for(;;) {
  72926. // printf("top=%p: pc=%d\n", th_list.top, (int)(pc - (bc_buf + RE_HEADER_LEN)));
  72927. opcode = *pc++;
  72928. switch(opcode) {
  72929. case REOP_match:
  72930. {
  72931. REExecState *rs;
  72932. if (no_recurse)
  72933. return (intptr_t)cptr;
  72934. ret = 1;
  72935. goto recurse;
  72936. no_match:
  72937. if (no_recurse)
  72938. return 0;
  72939. ret = 0;
  72940. recurse:
  72941. for(;;) {
  72942. if (s->state_stack_len == 0)
  72943. return ret;
  72944. rs = (REExecState *)(s->state_stack +
  72945. (s->state_stack_len - 1) * s->state_size);
  72946. if (rs->type == RE_EXEC_STATE_SPLIT) {
  72947. if (!ret) {
  72948. pop_state:
  72949. memcpy(capture, rs->buf,
  72950. sizeof(capture[0]) * 2 * s->capture_count);
  72951. pop_state1:
  72952. pc = rs->pc;
  72953. cptr = rs->cptr;
  72954. stack_len = rs->stack_len;
  72955. memcpy(stack, rs->buf + 2 * s->capture_count,
  72956. stack_len * sizeof(stack[0]));
  72957. s->state_stack_len--;
  72958. break;
  72959. }
  72960. } else if (rs->type == RE_EXEC_STATE_GREEDY_QUANT) {
  72961. if (!ret) {
  72962. uint32_t char_count, i;
  72963. memcpy(capture, rs->buf,
  72964. sizeof(capture[0]) * 2 * s->capture_count);
  72965. stack_len = rs->stack_len;
  72966. memcpy(stack, rs->buf + 2 * s->capture_count,
  72967. stack_len * sizeof(stack[0]));
  72968. pc = rs->pc;
  72969. cptr = rs->cptr;
  72970. /* go backward */
  72971. char_count = get_u32(pc + 12);
  72972. for(i = 0; i < char_count; i++) {
  72973. PREV_CHAR(cptr, s->cbuf, cbuf_type);
  72974. }
  72975. pc = (pc + 16) + (int)get_u32(pc);
  72976. rs->cptr = cptr;
  72977. rs->count--;
  72978. if (rs->count == 0) {
  72979. s->state_stack_len--;
  72980. }
  72981. break;
  72982. }
  72983. } else {
  72984. ret = ((rs->type == RE_EXEC_STATE_LOOKAHEAD && ret) ||
  72985. (rs->type == RE_EXEC_STATE_NEGATIVE_LOOKAHEAD && !ret));
  72986. if (ret) {
  72987. /* keep the capture in case of positive lookahead */
  72988. if (rs->type == RE_EXEC_STATE_LOOKAHEAD)
  72989. goto pop_state1;
  72990. else
  72991. goto pop_state;
  72992. }
  72993. }
  72994. s->state_stack_len--;
  72995. }
  72996. }
  72997. break;
  72998. case REOP_char32:
  72999. val = get_u32(pc);
  73000. pc += 4;
  73001. goto test_char;
  73002. case REOP_char16:
  73003. val = get_u16(pc);
  73004. pc += 2;
  73005. goto test_char;
  73006. case REOP_char8:
  73007. val = get_u8(pc);
  73008. pc += 1;
  73009. test_char:
  73010. if (cptr >= cbuf_end)
  73011. goto no_match;
  73012. GET_CHAR(c, cptr, cbuf_end, cbuf_type);
  73013. if (s->ignore_case) {
  73014. c = lre_canonicalize(c, s->is_unicode);
  73015. }
  73016. if (val != c)
  73017. goto no_match;
  73018. break;
  73019. case REOP_split_goto_first:
  73020. case REOP_split_next_first:
  73021. {
  73022. const uint8_t *pc1;
  73023. val = get_u32(pc);
  73024. pc += 4;
  73025. if (opcode == REOP_split_next_first) {
  73026. pc1 = pc + (int)val;
  73027. } else {
  73028. pc1 = pc;
  73029. pc = pc + (int)val;
  73030. }
  73031. ret = push_state(s, capture, stack, stack_len,
  73032. pc1, cptr, RE_EXEC_STATE_SPLIT, 0);
  73033. if (ret < 0)
  73034. return -1;
  73035. break;
  73036. }
  73037. case REOP_lookahead:
  73038. case REOP_negative_lookahead:
  73039. val = get_u32(pc);
  73040. pc += 4;
  73041. ret = push_state(s, capture, stack, stack_len,
  73042. pc + (int)val, cptr,
  73043. RE_EXEC_STATE_LOOKAHEAD + opcode - REOP_lookahead,
  73044. 0);
  73045. if (ret < 0)
  73046. return -1;
  73047. break;
  73048. case REOP_goto:
  73049. val = get_u32(pc);
  73050. pc += 4 + (int)val;
  73051. break;
  73052. case REOP_line_start:
  73053. if (cptr == s->cbuf)
  73054. break;
  73055. if (!s->multi_line)
  73056. goto no_match;
  73057. PEEK_PREV_CHAR(c, cptr, s->cbuf, cbuf_type);
  73058. if (!is_line_terminator(c))
  73059. goto no_match;
  73060. break;
  73061. case REOP_line_end:
  73062. if (cptr == cbuf_end)
  73063. break;
  73064. if (!s->multi_line)
  73065. goto no_match;
  73066. PEEK_CHAR(c, cptr, cbuf_end, cbuf_type);
  73067. if (!is_line_terminator(c))
  73068. goto no_match;
  73069. break;
  73070. case REOP_dot:
  73071. if (cptr == cbuf_end)
  73072. goto no_match;
  73073. GET_CHAR(c, cptr, cbuf_end, cbuf_type);
  73074. if (is_line_terminator(c))
  73075. goto no_match;
  73076. break;
  73077. case REOP_any:
  73078. if (cptr == cbuf_end)
  73079. goto no_match;
  73080. GET_CHAR(c, cptr, cbuf_end, cbuf_type);
  73081. break;
  73082. case REOP_save_start:
  73083. case REOP_save_end:
  73084. val = *pc++;
  73085. assert(val < s->capture_count);
  73086. capture[2 * val + opcode - REOP_save_start] = (uint8_t *)cptr;
  73087. break;
  73088. case REOP_save_reset:
  73089. {
  73090. uint32_t val2;
  73091. val = pc[0];
  73092. val2 = pc[1];
  73093. pc += 2;
  73094. assert(val2 < s->capture_count);
  73095. while (val <= val2) {
  73096. capture[2 * val] = NULL;
  73097. capture[2 * val + 1] = NULL;
  73098. val++;
  73099. }
  73100. }
  73101. break;
  73102. case REOP_push_i32:
  73103. val = get_u32(pc);
  73104. pc += 4;
  73105. stack[stack_len++] = val;
  73106. break;
  73107. case REOP_drop:
  73108. stack_len--;
  73109. break;
  73110. case REOP_loop:
  73111. val = get_u32(pc);
  73112. pc += 4;
  73113. if (--stack[stack_len - 1] != 0) {
  73114. pc += (int)val;
  73115. }
  73116. break;
  73117. case REOP_push_char_pos:
  73118. stack[stack_len++] = (uintptr_t)cptr;
  73119. break;
  73120. case REOP_check_advance:
  73121. if (stack[--stack_len] == (uintptr_t)cptr)
  73122. goto no_match;
  73123. break;
  73124. case REOP_word_boundary:
  73125. case REOP_not_word_boundary:
  73126. {
  73127. bool v1, v2;
  73128. /* char before */
  73129. if (cptr == s->cbuf) {
  73130. v1 = false;
  73131. } else {
  73132. PEEK_PREV_CHAR(c, cptr, s->cbuf, cbuf_type);
  73133. v1 = is_word_char(c);
  73134. }
  73135. /* current char */
  73136. if (cptr >= cbuf_end) {
  73137. v2 = false;
  73138. } else {
  73139. PEEK_CHAR(c, cptr, cbuf_end, cbuf_type);
  73140. v2 = is_word_char(c);
  73141. }
  73142. if (v1 ^ v2 ^ (REOP_not_word_boundary - opcode))
  73143. goto no_match;
  73144. }
  73145. break;
  73146. case REOP_back_reference:
  73147. case REOP_backward_back_reference:
  73148. {
  73149. const uint8_t *cptr1, *cptr1_end, *cptr1_start;
  73150. uint32_t c1, c2;
  73151. val = *pc++;
  73152. if (val >= s->capture_count)
  73153. goto no_match;
  73154. cptr1_start = capture[2 * val];
  73155. cptr1_end = capture[2 * val + 1];
  73156. if (!cptr1_start || !cptr1_end)
  73157. break;
  73158. if (opcode == REOP_back_reference) {
  73159. cptr1 = cptr1_start;
  73160. while (cptr1 < cptr1_end) {
  73161. if (cptr >= cbuf_end)
  73162. goto no_match;
  73163. GET_CHAR(c1, cptr1, cptr1_end, cbuf_type);
  73164. GET_CHAR(c2, cptr, cbuf_end, cbuf_type);
  73165. if (s->ignore_case) {
  73166. c1 = lre_canonicalize(c1, s->is_unicode);
  73167. c2 = lre_canonicalize(c2, s->is_unicode);
  73168. }
  73169. if (c1 != c2)
  73170. goto no_match;
  73171. }
  73172. } else {
  73173. cptr1 = cptr1_end;
  73174. while (cptr1 > cptr1_start) {
  73175. if (cptr == s->cbuf)
  73176. goto no_match;
  73177. GET_PREV_CHAR(c1, cptr1, cptr1_start, cbuf_type);
  73178. GET_PREV_CHAR(c2, cptr, s->cbuf, cbuf_type);
  73179. if (s->ignore_case) {
  73180. c1 = lre_canonicalize(c1, s->is_unicode);
  73181. c2 = lre_canonicalize(c2, s->is_unicode);
  73182. }
  73183. if (c1 != c2)
  73184. goto no_match;
  73185. }
  73186. }
  73187. }
  73188. break;
  73189. case REOP_range:
  73190. {
  73191. int n;
  73192. uint32_t low, high, idx_min, idx_max, idx;
  73193. n = get_u16(pc); /* n must be >= 1 */
  73194. pc += 2;
  73195. if (cptr >= cbuf_end)
  73196. goto no_match;
  73197. GET_CHAR(c, cptr, cbuf_end, cbuf_type);
  73198. if (s->ignore_case) {
  73199. c = lre_canonicalize(c, s->is_unicode);
  73200. }
  73201. idx_min = 0;
  73202. low = get_u16(pc + 0 * 4);
  73203. if (c < low)
  73204. goto no_match;
  73205. idx_max = n - 1;
  73206. high = get_u16(pc + idx_max * 4 + 2);
  73207. /* 0xffff in for last value means +infinity */
  73208. if (unlikely(c >= 0xffff) && high == 0xffff)
  73209. goto range_match;
  73210. if (c > high)
  73211. goto no_match;
  73212. while (idx_min <= idx_max) {
  73213. idx = (idx_min + idx_max) / 2;
  73214. low = get_u16(pc + idx * 4);
  73215. high = get_u16(pc + idx * 4 + 2);
  73216. if (c < low)
  73217. idx_max = idx - 1;
  73218. else if (c > high)
  73219. idx_min = idx + 1;
  73220. else
  73221. goto range_match;
  73222. }
  73223. goto no_match;
  73224. range_match:
  73225. pc += 4 * n;
  73226. }
  73227. break;
  73228. case REOP_range32:
  73229. {
  73230. int n;
  73231. uint32_t low, high, idx_min, idx_max, idx;
  73232. n = get_u16(pc); /* n must be >= 1 */
  73233. pc += 2;
  73234. if (cptr >= cbuf_end)
  73235. goto no_match;
  73236. GET_CHAR(c, cptr, cbuf_end, cbuf_type);
  73237. if (s->ignore_case) {
  73238. c = lre_canonicalize(c, s->is_unicode);
  73239. }
  73240. idx_min = 0;
  73241. low = get_u32(pc + 0 * 8);
  73242. if (c < low)
  73243. goto no_match;
  73244. idx_max = n - 1;
  73245. high = get_u32(pc + idx_max * 8 + 4);
  73246. if (c > high)
  73247. goto no_match;
  73248. while (idx_min <= idx_max) {
  73249. idx = (idx_min + idx_max) / 2;
  73250. low = get_u32(pc + idx * 8);
  73251. high = get_u32(pc + idx * 8 + 4);
  73252. if (c < low)
  73253. idx_max = idx - 1;
  73254. else if (c > high)
  73255. idx_min = idx + 1;
  73256. else
  73257. goto range32_match;
  73258. }
  73259. goto no_match;
  73260. range32_match:
  73261. pc += 8 * n;
  73262. }
  73263. break;
  73264. case REOP_prev:
  73265. /* go to the previous char */
  73266. if (cptr == s->cbuf)
  73267. goto no_match;
  73268. PREV_CHAR(cptr, s->cbuf, cbuf_type);
  73269. break;
  73270. case REOP_simple_greedy_quant:
  73271. {
  73272. uint32_t next_pos, quant_min, quant_max;
  73273. size_t q;
  73274. intptr_t res;
  73275. const uint8_t *pc1;
  73276. next_pos = get_u32(pc);
  73277. quant_min = get_u32(pc + 4);
  73278. quant_max = get_u32(pc + 8);
  73279. pc += 16;
  73280. pc1 = pc;
  73281. pc += (int)next_pos;
  73282. q = 0;
  73283. for(;;) {
  73284. res = lre_exec_backtrack(s, capture, stack, stack_len,
  73285. pc1, cptr, true);
  73286. if (res == -1)
  73287. return res;
  73288. if (!res)
  73289. break;
  73290. cptr = (uint8_t *)res;
  73291. q++;
  73292. if (q >= quant_max && quant_max != INT32_MAX)
  73293. break;
  73294. }
  73295. if (q < quant_min)
  73296. goto no_match;
  73297. if (q > quant_min) {
  73298. /* will examine all matches down to quant_min */
  73299. ret = push_state(s, capture, stack, stack_len,
  73300. pc1 - 16, cptr,
  73301. RE_EXEC_STATE_GREEDY_QUANT,
  73302. q - quant_min);
  73303. if (ret < 0)
  73304. return -1;
  73305. }
  73306. }
  73307. break;
  73308. default:
  73309. abort();
  73310. }
  73311. }
  73312. }
  73313. /* Return 1 if match, 0 if not match or -1 if error. cindex is the
  73314. starting position of the match and must be such as 0 <= cindex <=
  73315. clen. */
  73316. int lre_exec(uint8_t **capture,
  73317. const uint8_t *bc_buf, const uint8_t *cbuf, int cindex, int clen,
  73318. int cbuf_type, void *opaque)
  73319. {
  73320. REExecContext s_s, *s = &s_s;
  73321. int re_flags, i, alloca_size, ret;
  73322. StackInt *stack_buf;
  73323. re_flags = lre_get_flags(bc_buf);
  73324. s->multi_line = (re_flags & LRE_FLAG_MULTILINE) != 0;
  73325. s->ignore_case = (re_flags & LRE_FLAG_IGNORECASE) != 0;
  73326. s->is_unicode = (re_flags & LRE_FLAG_UNICODE) != 0;
  73327. s->capture_count = bc_buf[RE_HEADER_CAPTURE_COUNT];
  73328. s->stack_size_max = bc_buf[RE_HEADER_STACK_SIZE];
  73329. s->cbuf = cbuf;
  73330. s->cbuf_end = cbuf + (clen << cbuf_type);
  73331. s->cbuf_type = cbuf_type;
  73332. if (s->cbuf_type == 1 && s->is_unicode)
  73333. s->cbuf_type = 2;
  73334. s->opaque = opaque;
  73335. s->state_size = sizeof(REExecState) +
  73336. s->capture_count * sizeof(capture[0]) * 2 +
  73337. s->stack_size_max * sizeof(stack_buf[0]);
  73338. s->state_stack = NULL;
  73339. s->state_stack_len = 0;
  73340. s->state_stack_size = 0;
  73341. for(i = 0; i < s->capture_count * 2; i++)
  73342. capture[i] = NULL;
  73343. alloca_size = s->stack_size_max * sizeof(stack_buf[0]);
  73344. stack_buf = alloca(alloca_size);
  73345. ret = lre_exec_backtrack(s, capture, stack_buf, 0, bc_buf + RE_HEADER_LEN,
  73346. cbuf + (cindex << cbuf_type), false);
  73347. lre_realloc(s->opaque, s->state_stack, 0);
  73348. return ret;
  73349. }
  73350. int lre_get_capture_count(const uint8_t *bc_buf)
  73351. {
  73352. return bc_buf[RE_HEADER_CAPTURE_COUNT];
  73353. }
  73354. int lre_get_flags(const uint8_t *bc_buf)
  73355. {
  73356. return get_u16(bc_buf + RE_HEADER_FLAGS);
  73357. }
  73358. /* Return NULL if no group names. Otherwise, return a pointer to
  73359. 'capture_count - 1' zero terminated UTF-8 strings. */
  73360. const char *lre_get_groupnames(const uint8_t *bc_buf)
  73361. {
  73362. uint32_t re_bytecode_len;
  73363. if ((lre_get_flags(bc_buf) & LRE_FLAG_NAMED_GROUPS) == 0)
  73364. return NULL;
  73365. re_bytecode_len = get_u32(bc_buf + RE_HEADER_BYTECODE_LEN);
  73366. return (const char *)(bc_buf + RE_HEADER_LEN + re_bytecode_len);
  73367. }
  73368. void lre_byte_swap(uint8_t *buf, size_t len, bool is_byte_swapped)
  73369. {
  73370. uint8_t *p, *pe;
  73371. uint32_t n, r, nw;
  73372. p = buf;
  73373. if (len < RE_HEADER_LEN)
  73374. abort();
  73375. // format is:
  73376. // <header>
  73377. // <bytecode>
  73378. // <capture group name 1>
  73379. // <capture group name 2>
  73380. // etc.
  73381. inplace_bswap16(&p[RE_HEADER_FLAGS]);
  73382. n = get_u32(&p[RE_HEADER_BYTECODE_LEN]);
  73383. inplace_bswap32(&p[RE_HEADER_BYTECODE_LEN]);
  73384. if (is_byte_swapped)
  73385. n = bswap32(n);
  73386. if (n > len - RE_HEADER_LEN)
  73387. abort();
  73388. p = &buf[RE_HEADER_LEN];
  73389. pe = &p[n];
  73390. while (p < pe) {
  73391. n = reopcode_info[*p].size;
  73392. switch (n) {
  73393. case 1:
  73394. case 2:
  73395. break;
  73396. case 3:
  73397. switch (*p) {
  73398. case REOP_save_reset: // has two 8 bit arguments
  73399. break;
  73400. case REOP_range32: // variable length
  73401. nw = get_u16(&p[1]); // number of pairs of uint32_t
  73402. if (is_byte_swapped)
  73403. n = bswap16(n);
  73404. for (r = 3 + 8 * nw; n < r; n += 4)
  73405. inplace_bswap32(&p[n]);
  73406. goto doswap16;
  73407. case REOP_range: // variable length
  73408. nw = get_u16(&p[1]); // number of pairs of uint16_t
  73409. if (is_byte_swapped)
  73410. n = bswap16(n);
  73411. for (r = 3 + 4 * nw; n < r; n += 2)
  73412. inplace_bswap16(&p[n]);
  73413. goto doswap16;
  73414. default:
  73415. doswap16:
  73416. inplace_bswap16(&p[1]);
  73417. break;
  73418. }
  73419. break;
  73420. case 5:
  73421. inplace_bswap32(&p[1]);
  73422. break;
  73423. case 17:
  73424. assert(*p == REOP_simple_greedy_quant);
  73425. inplace_bswap32(&p[1]);
  73426. inplace_bswap32(&p[5]);
  73427. inplace_bswap32(&p[9]);
  73428. inplace_bswap32(&p[13]);
  73429. break;
  73430. default:
  73431. abort();
  73432. }
  73433. p = &p[n];
  73434. }
  73435. }
  73436. #ifdef TEST
  73437. bool lre_check_stack_overflow(void *opaque, size_t alloca_size)
  73438. {
  73439. return false;
  73440. }
  73441. void *lre_realloc(void *opaque, void *ptr, size_t size)
  73442. {
  73443. return realloc(ptr, size);
  73444. }
  73445. int main(int argc, char **argv)
  73446. {
  73447. int len, flags, ret, i;
  73448. uint8_t *bc;
  73449. char error_msg[64];
  73450. uint8_t *capture[CAPTURE_COUNT_MAX * 2];
  73451. const char *input;
  73452. int input_len, capture_count;
  73453. if (argc < 4) {
  73454. printf("usage: %s regexp flags input\n", argv[0]);
  73455. exit(1);
  73456. }
  73457. flags = atoi(argv[2]);
  73458. bc = lre_compile(&len, error_msg, sizeof(error_msg), argv[1],
  73459. strlen(argv[1]), flags, NULL);
  73460. if (!bc) {
  73461. fprintf(stderr, "error: %s\n", error_msg);
  73462. exit(1);
  73463. }
  73464. input = argv[3];
  73465. input_len = strlen(input);
  73466. ret = lre_exec(capture, bc, (uint8_t *)input, 0, input_len, 0, NULL);
  73467. printf("ret=%d\n", ret);
  73468. if (ret == 1) {
  73469. capture_count = lre_get_capture_count(bc);
  73470. for(i = 0; i < 2 * capture_count; i++) {
  73471. uint8_t *ptr;
  73472. ptr = capture[i];
  73473. printf("%d: ", i);
  73474. if (!ptr)
  73475. printf("<nil>");
  73476. else
  73477. printf("%u", (int)(ptr - (uint8_t *)input));
  73478. printf("\n");
  73479. }
  73480. }
  73481. return 0;
  73482. }
  73483. #endif
  73484. /*
  73485. * Unicode utilities
  73486. *
  73487. * Copyright (c) 2017-2018 Fabrice Bellard
  73488. *
  73489. * Permission is hereby granted, free of charge, to any person obtaining a copy
  73490. * of this software and associated documentation files (the "Software"), to deal
  73491. * in the Software without restriction, including without limitation the rights
  73492. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  73493. * copies of the Software, and to permit persons to whom the Software is
  73494. * furnished to do so, subject to the following conditions:
  73495. *
  73496. * The above copyright notice and this permission notice shall be included in
  73497. * all copies or substantial portions of the Software.
  73498. *
  73499. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  73500. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  73501. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  73502. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  73503. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  73504. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  73505. * THE SOFTWARE.
  73506. */
  73507. #include <stdlib.h>
  73508. #include <stdio.h>
  73509. #include <stdarg.h>
  73510. #include <string.h>
  73511. #include <assert.h>
  73512. // note: stored as 4 bit tag, not much room left
  73513. enum {
  73514. RUN_TYPE_U,
  73515. RUN_TYPE_L,
  73516. RUN_TYPE_UF,
  73517. RUN_TYPE_LF,
  73518. RUN_TYPE_UL,
  73519. RUN_TYPE_LSU,
  73520. RUN_TYPE_U2L_399_EXT2,
  73521. RUN_TYPE_UF_D20,
  73522. RUN_TYPE_UF_D1_EXT,
  73523. RUN_TYPE_U_EXT,
  73524. RUN_TYPE_LF_EXT,
  73525. RUN_TYPE_UF_EXT2,
  73526. RUN_TYPE_LF_EXT2,
  73527. RUN_TYPE_UF_EXT3,
  73528. };
  73529. static int lre_case_conv1(uint32_t c, int conv_type)
  73530. {
  73531. uint32_t res[LRE_CC_RES_LEN_MAX];
  73532. lre_case_conv(res, c, conv_type);
  73533. return res[0];
  73534. }
  73535. /* case conversion using the table entry 'idx' with value 'v' */
  73536. static int lre_case_conv_entry(uint32_t *res, uint32_t c, int conv_type, uint32_t idx, uint32_t v)
  73537. {
  73538. uint32_t code, data, type, a, is_lower;
  73539. is_lower = (conv_type != 0);
  73540. type = (v >> (32 - 17 - 7 - 4)) & 0xf;
  73541. data = ((v & 0xf) << 8) | case_conv_table2[idx];
  73542. code = v >> (32 - 17);
  73543. switch(type) {
  73544. case RUN_TYPE_U:
  73545. case RUN_TYPE_L:
  73546. case RUN_TYPE_UF:
  73547. case RUN_TYPE_LF:
  73548. if (conv_type == (type & 1) ||
  73549. (type >= RUN_TYPE_UF && conv_type == 2)) {
  73550. c = c - code + (case_conv_table1[data] >> (32 - 17));
  73551. }
  73552. break;
  73553. case RUN_TYPE_UL:
  73554. a = c - code;
  73555. if ((a & 1) != (1 - is_lower))
  73556. break;
  73557. c = (a ^ 1) + code;
  73558. break;
  73559. case RUN_TYPE_LSU:
  73560. a = c - code;
  73561. if (a == 1) {
  73562. c += 2 * is_lower - 1;
  73563. } else if (a == (1 - is_lower) * 2) {
  73564. c += (2 * is_lower - 1) * 2;
  73565. }
  73566. break;
  73567. case RUN_TYPE_U2L_399_EXT2:
  73568. if (!is_lower) {
  73569. res[0] = c - code + case_conv_ext[data >> 6];
  73570. res[1] = 0x399;
  73571. return 2;
  73572. } else {
  73573. c = c - code + case_conv_ext[data & 0x3f];
  73574. }
  73575. break;
  73576. case RUN_TYPE_UF_D20:
  73577. if (conv_type == 1)
  73578. break;
  73579. c = data + (conv_type == 2) * 0x20;
  73580. break;
  73581. case RUN_TYPE_UF_D1_EXT:
  73582. if (conv_type == 1)
  73583. break;
  73584. c = case_conv_ext[data] + (conv_type == 2);
  73585. break;
  73586. case RUN_TYPE_U_EXT:
  73587. case RUN_TYPE_LF_EXT:
  73588. if (is_lower != (type - RUN_TYPE_U_EXT))
  73589. break;
  73590. c = case_conv_ext[data];
  73591. break;
  73592. case RUN_TYPE_LF_EXT2:
  73593. if (!is_lower)
  73594. break;
  73595. res[0] = c - code + case_conv_ext[data >> 6];
  73596. res[1] = case_conv_ext[data & 0x3f];
  73597. return 2;
  73598. case RUN_TYPE_UF_EXT2:
  73599. if (conv_type == 1)
  73600. break;
  73601. res[0] = c - code + case_conv_ext[data >> 6];
  73602. res[1] = case_conv_ext[data & 0x3f];
  73603. if (conv_type == 2) {
  73604. /* convert to lower */
  73605. res[0] = lre_case_conv1(res[0], 1);
  73606. res[1] = lre_case_conv1(res[1], 1);
  73607. }
  73608. return 2;
  73609. default:
  73610. case RUN_TYPE_UF_EXT3:
  73611. if (conv_type == 1)
  73612. break;
  73613. res[0] = case_conv_ext[data >> 8];
  73614. res[1] = case_conv_ext[(data >> 4) & 0xf];
  73615. res[2] = case_conv_ext[data & 0xf];
  73616. if (conv_type == 2) {
  73617. /* convert to lower */
  73618. res[0] = lre_case_conv1(res[0], 1);
  73619. res[1] = lre_case_conv1(res[1], 1);
  73620. res[2] = lre_case_conv1(res[2], 1);
  73621. }
  73622. return 3;
  73623. }
  73624. res[0] = c;
  73625. return 1;
  73626. }
  73627. /* conv_type:
  73628. 0 = to upper
  73629. 1 = to lower
  73630. 2 = case folding (= to lower with modifications)
  73631. */
  73632. int lre_case_conv(uint32_t *res, uint32_t c, int conv_type)
  73633. {
  73634. if (c < 128) {
  73635. if (conv_type) {
  73636. if (c >= 'A' && c <= 'Z') {
  73637. c = c - 'A' + 'a';
  73638. }
  73639. } else {
  73640. if (c >= 'a' && c <= 'z') {
  73641. c = c - 'a' + 'A';
  73642. }
  73643. }
  73644. } else {
  73645. uint32_t v, code, len;
  73646. int idx, idx_min, idx_max;
  73647. idx_min = 0;
  73648. idx_max = countof(case_conv_table1) - 1;
  73649. while (idx_min <= idx_max) {
  73650. idx = (unsigned)(idx_max + idx_min) / 2;
  73651. v = case_conv_table1[idx];
  73652. code = v >> (32 - 17);
  73653. len = (v >> (32 - 17 - 7)) & 0x7f;
  73654. if (c < code) {
  73655. idx_max = idx - 1;
  73656. } else if (c >= code + len) {
  73657. idx_min = idx + 1;
  73658. } else {
  73659. return lre_case_conv_entry(res, c, conv_type, idx, v);
  73660. }
  73661. }
  73662. }
  73663. res[0] = c;
  73664. return 1;
  73665. }
  73666. static int lre_case_folding_entry(uint32_t c, uint32_t idx, uint32_t v, bool is_unicode)
  73667. {
  73668. uint32_t res[LRE_CC_RES_LEN_MAX];
  73669. int len;
  73670. if (is_unicode) {
  73671. len = lre_case_conv_entry(res, c, 2, idx, v);
  73672. if (len == 1) {
  73673. c = res[0];
  73674. } else {
  73675. /* handle the few specific multi-character cases (see
  73676. unicode_gen.c:dump_case_folding_special_cases()) */
  73677. if (c == 0xfb06) {
  73678. c = 0xfb05;
  73679. } else if (c == 0x01fd3) {
  73680. c = 0x390;
  73681. } else if (c == 0x01fe3) {
  73682. c = 0x3b0;
  73683. }
  73684. }
  73685. } else {
  73686. if (likely(c < 128)) {
  73687. if (c >= 'a' && c <= 'z')
  73688. c = c - 'a' + 'A';
  73689. } else {
  73690. /* legacy regexp: to upper case if single char >= 128 */
  73691. len = lre_case_conv_entry(res, c, false, idx, v);
  73692. if (len == 1 && res[0] >= 128)
  73693. c = res[0];
  73694. }
  73695. }
  73696. return c;
  73697. }
  73698. /* JS regexp specific rules for case folding */
  73699. int lre_canonicalize(uint32_t c, bool is_unicode)
  73700. {
  73701. if (c < 128) {
  73702. /* fast case */
  73703. if (is_unicode) {
  73704. if (c >= 'A' && c <= 'Z') {
  73705. c = c - 'A' + 'a';
  73706. }
  73707. } else {
  73708. if (c >= 'a' && c <= 'z') {
  73709. c = c - 'a' + 'A';
  73710. }
  73711. }
  73712. } else {
  73713. uint32_t v, code, len;
  73714. int idx, idx_min, idx_max;
  73715. idx_min = 0;
  73716. idx_max = countof(case_conv_table1) - 1;
  73717. while (idx_min <= idx_max) {
  73718. idx = (unsigned)(idx_max + idx_min) / 2;
  73719. v = case_conv_table1[idx];
  73720. code = v >> (32 - 17);
  73721. len = (v >> (32 - 17 - 7)) & 0x7f;
  73722. if (c < code) {
  73723. idx_max = idx - 1;
  73724. } else if (c >= code + len) {
  73725. idx_min = idx + 1;
  73726. } else {
  73727. return lre_case_folding_entry(c, idx, v, is_unicode);
  73728. }
  73729. }
  73730. }
  73731. return c;
  73732. }
  73733. static uint32_t get_le24(const uint8_t *ptr)
  73734. {
  73735. return ptr[0] | (ptr[1] << 8) | (ptr[2] << 16);
  73736. }
  73737. #define UNICODE_INDEX_BLOCK_LEN 32
  73738. /* return -1 if not in table, otherwise the offset in the block */
  73739. static int get_index_pos(uint32_t *pcode, uint32_t c,
  73740. const uint8_t *index_table, int index_table_len)
  73741. {
  73742. uint32_t code, v;
  73743. int idx_min, idx_max, idx;
  73744. idx_min = 0;
  73745. v = get_le24(index_table);
  73746. code = v & ((1 << 21) - 1);
  73747. if (c < code) {
  73748. *pcode = 0;
  73749. return 0;
  73750. }
  73751. idx_max = index_table_len - 1;
  73752. code = get_le24(index_table + idx_max * 3);
  73753. if (c >= code)
  73754. return -1;
  73755. /* invariant: tab[idx_min] <= c < tab2[idx_max] */
  73756. while ((idx_max - idx_min) > 1) {
  73757. idx = (idx_max + idx_min) / 2;
  73758. v = get_le24(index_table + idx * 3);
  73759. code = v & ((1 << 21) - 1);
  73760. if (c < code) {
  73761. idx_max = idx;
  73762. } else {
  73763. idx_min = idx;
  73764. }
  73765. }
  73766. v = get_le24(index_table + idx_min * 3);
  73767. *pcode = v & ((1 << 21) - 1);
  73768. return (idx_min + 1) * UNICODE_INDEX_BLOCK_LEN + (v >> 21);
  73769. }
  73770. static bool lre_is_in_table(uint32_t c, const uint8_t *table,
  73771. const uint8_t *index_table, int index_table_len)
  73772. {
  73773. uint32_t code, b, bit;
  73774. int pos;
  73775. const uint8_t *p;
  73776. pos = get_index_pos(&code, c, index_table, index_table_len);
  73777. if (pos < 0)
  73778. return false; /* outside the table */
  73779. p = table + pos;
  73780. bit = 0;
  73781. for(;;) {
  73782. b = *p++;
  73783. if (b < 64) {
  73784. code += (b >> 3) + 1;
  73785. if (c < code)
  73786. return bit;
  73787. bit ^= 1;
  73788. code += (b & 7) + 1;
  73789. } else if (b >= 0x80) {
  73790. code += b - 0x80 + 1;
  73791. } else if (b < 0x60) {
  73792. code += (((b - 0x40) << 8) | p[0]) + 1;
  73793. p++;
  73794. } else {
  73795. code += (((b - 0x60) << 16) | (p[0] << 8) | p[1]) + 1;
  73796. p += 2;
  73797. }
  73798. if (c < code)
  73799. return bit;
  73800. bit ^= 1;
  73801. }
  73802. }
  73803. bool lre_is_cased(uint32_t c)
  73804. {
  73805. uint32_t v, code, len;
  73806. int idx, idx_min, idx_max;
  73807. idx_min = 0;
  73808. idx_max = countof(case_conv_table1) - 1;
  73809. while (idx_min <= idx_max) {
  73810. idx = (unsigned)(idx_max + idx_min) / 2;
  73811. v = case_conv_table1[idx];
  73812. code = v >> (32 - 17);
  73813. len = (v >> (32 - 17 - 7)) & 0x7f;
  73814. if (c < code) {
  73815. idx_max = idx - 1;
  73816. } else if (c >= code + len) {
  73817. idx_min = idx + 1;
  73818. } else {
  73819. return true;
  73820. }
  73821. }
  73822. return lre_is_in_table(c, unicode_prop_Cased1_table,
  73823. unicode_prop_Cased1_index,
  73824. sizeof(unicode_prop_Cased1_index) / 3);
  73825. }
  73826. bool lre_is_case_ignorable(uint32_t c)
  73827. {
  73828. return lre_is_in_table(c, unicode_prop_Case_Ignorable_table,
  73829. unicode_prop_Case_Ignorable_index,
  73830. sizeof(unicode_prop_Case_Ignorable_index) / 3);
  73831. }
  73832. /* character range */
  73833. static __maybe_unused void cr_dump(CharRange *cr)
  73834. {
  73835. int i;
  73836. for(i = 0; i < cr->len; i++)
  73837. printf("%d: 0x%04x\n", i, cr->points[i]);
  73838. }
  73839. static void *cr_default_realloc(void *opaque, void *ptr, size_t size)
  73840. {
  73841. return realloc(ptr, size);
  73842. }
  73843. void cr_init(CharRange *cr, void *mem_opaque, DynBufReallocFunc *realloc_func)
  73844. {
  73845. cr->len = cr->size = 0;
  73846. cr->points = NULL;
  73847. cr->mem_opaque = mem_opaque;
  73848. cr->realloc_func = realloc_func ? realloc_func : cr_default_realloc;
  73849. }
  73850. void cr_free(CharRange *cr)
  73851. {
  73852. cr->realloc_func(cr->mem_opaque, cr->points, 0);
  73853. }
  73854. int cr_realloc(CharRange *cr, int size)
  73855. {
  73856. int new_size;
  73857. uint32_t *new_buf;
  73858. if (size > cr->size) {
  73859. new_size = max_int(size, cr->size * 3 / 2);
  73860. new_buf = cr->realloc_func(cr->mem_opaque, cr->points,
  73861. new_size * sizeof(cr->points[0]));
  73862. if (!new_buf)
  73863. return -1;
  73864. cr->points = new_buf;
  73865. cr->size = new_size;
  73866. }
  73867. return 0;
  73868. }
  73869. int cr_copy(CharRange *cr, const CharRange *cr1)
  73870. {
  73871. if (cr_realloc(cr, cr1->len))
  73872. return -1;
  73873. memcpy(cr->points, cr1->points, sizeof(cr->points[0]) * cr1->len);
  73874. cr->len = cr1->len;
  73875. return 0;
  73876. }
  73877. /* merge consecutive intervals and remove empty intervals */
  73878. static void cr_compress(CharRange *cr)
  73879. {
  73880. int i, j, k, len;
  73881. uint32_t *pt;
  73882. pt = cr->points;
  73883. len = cr->len;
  73884. i = 0;
  73885. j = 0;
  73886. k = 0;
  73887. while ((i + 1) < len) {
  73888. if (pt[i] == pt[i + 1]) {
  73889. /* empty interval */
  73890. i += 2;
  73891. } else {
  73892. j = i;
  73893. while ((j + 3) < len && pt[j + 1] == pt[j + 2])
  73894. j += 2;
  73895. /* just copy */
  73896. pt[k] = pt[i];
  73897. pt[k + 1] = pt[j + 1];
  73898. k += 2;
  73899. i = j + 2;
  73900. }
  73901. }
  73902. cr->len = k;
  73903. }
  73904. /* union or intersection */
  73905. int cr_op(CharRange *cr, const uint32_t *a_pt, int a_len,
  73906. const uint32_t *b_pt, int b_len, int op)
  73907. {
  73908. int a_idx, b_idx, is_in;
  73909. uint32_t v;
  73910. a_idx = 0;
  73911. b_idx = 0;
  73912. for(;;) {
  73913. /* get one more point from a or b in increasing order */
  73914. if (a_idx < a_len && b_idx < b_len) {
  73915. if (a_pt[a_idx] < b_pt[b_idx]) {
  73916. goto a_add;
  73917. } else if (a_pt[a_idx] == b_pt[b_idx]) {
  73918. v = a_pt[a_idx];
  73919. a_idx++;
  73920. b_idx++;
  73921. } else {
  73922. goto b_add;
  73923. }
  73924. } else if (a_idx < a_len) {
  73925. a_add:
  73926. v = a_pt[a_idx++];
  73927. } else if (b_idx < b_len) {
  73928. b_add:
  73929. v = b_pt[b_idx++];
  73930. } else {
  73931. break;
  73932. }
  73933. /* add the point if the in/out status changes */
  73934. switch(op) {
  73935. case CR_OP_UNION:
  73936. is_in = (a_idx & 1) | (b_idx & 1);
  73937. break;
  73938. case CR_OP_INTER:
  73939. is_in = (a_idx & 1) & (b_idx & 1);
  73940. break;
  73941. case CR_OP_XOR:
  73942. is_in = (a_idx & 1) ^ (b_idx & 1);
  73943. break;
  73944. default:
  73945. abort();
  73946. }
  73947. if (is_in != (cr->len & 1)) {
  73948. if (cr_add_point(cr, v))
  73949. return -1;
  73950. }
  73951. }
  73952. cr_compress(cr);
  73953. return 0;
  73954. }
  73955. int cr_union1(CharRange *cr, const uint32_t *b_pt, int b_len)
  73956. {
  73957. CharRange a = *cr;
  73958. int ret;
  73959. cr->len = 0;
  73960. cr->size = 0;
  73961. cr->points = NULL;
  73962. ret = cr_op(cr, a.points, a.len, b_pt, b_len, CR_OP_UNION);
  73963. cr_free(&a);
  73964. return ret;
  73965. }
  73966. int cr_invert(CharRange *cr)
  73967. {
  73968. int len;
  73969. len = cr->len;
  73970. if (cr_realloc(cr, len + 2))
  73971. return -1;
  73972. memmove(cr->points + 1, cr->points, len * sizeof(cr->points[0]));
  73973. cr->points[0] = 0;
  73974. cr->points[len + 1] = UINT32_MAX;
  73975. cr->len = len + 2;
  73976. cr_compress(cr);
  73977. return 0;
  73978. }
  73979. bool lre_is_id_start(uint32_t c)
  73980. {
  73981. return lre_is_in_table(c, unicode_prop_ID_Start_table,
  73982. unicode_prop_ID_Start_index,
  73983. sizeof(unicode_prop_ID_Start_index) / 3);
  73984. }
  73985. bool lre_is_id_continue(uint32_t c)
  73986. {
  73987. return lre_is_id_start(c) ||
  73988. lre_is_in_table(c, unicode_prop_ID_Continue1_table,
  73989. unicode_prop_ID_Continue1_index,
  73990. sizeof(unicode_prop_ID_Continue1_index) / 3);
  73991. }
  73992. bool lre_is_white_space(uint32_t c)
  73993. {
  73994. return lre_is_in_table(c, unicode_prop_White_Space_table,
  73995. unicode_prop_White_Space_index,
  73996. sizeof(unicode_prop_White_Space_index) / 3);
  73997. }
  73998. #define UNICODE_DECOMP_LEN_MAX 18
  73999. typedef enum {
  74000. DECOMP_TYPE_C1, /* 16 bit char */
  74001. DECOMP_TYPE_L1, /* 16 bit char table */
  74002. DECOMP_TYPE_L2,
  74003. DECOMP_TYPE_L3,
  74004. DECOMP_TYPE_L4,
  74005. DECOMP_TYPE_L5, /* XXX: not used */
  74006. DECOMP_TYPE_L6, /* XXX: could remove */
  74007. DECOMP_TYPE_L7, /* XXX: could remove */
  74008. DECOMP_TYPE_LL1, /* 18 bit char table */
  74009. DECOMP_TYPE_LL2,
  74010. DECOMP_TYPE_S1, /* 8 bit char table */
  74011. DECOMP_TYPE_S2,
  74012. DECOMP_TYPE_S3,
  74013. DECOMP_TYPE_S4,
  74014. DECOMP_TYPE_S5,
  74015. DECOMP_TYPE_I1, /* increment 16 bit char value */
  74016. DECOMP_TYPE_I2_0,
  74017. DECOMP_TYPE_I2_1,
  74018. DECOMP_TYPE_I3_1,
  74019. DECOMP_TYPE_I3_2,
  74020. DECOMP_TYPE_I4_1,
  74021. DECOMP_TYPE_I4_2,
  74022. DECOMP_TYPE_B1, /* 16 bit base + 8 bit offset */
  74023. DECOMP_TYPE_B2,
  74024. DECOMP_TYPE_B3,
  74025. DECOMP_TYPE_B4,
  74026. DECOMP_TYPE_B5,
  74027. DECOMP_TYPE_B6,
  74028. DECOMP_TYPE_B7,
  74029. DECOMP_TYPE_B8,
  74030. DECOMP_TYPE_B18,
  74031. DECOMP_TYPE_LS2,
  74032. DECOMP_TYPE_PAT3,
  74033. DECOMP_TYPE_S2_UL,
  74034. DECOMP_TYPE_LS2_UL,
  74035. } DecompTypeEnum;
  74036. static uint32_t unicode_get_short_code(uint32_t c)
  74037. {
  74038. static const uint16_t unicode_short_table[2] = { 0x2044, 0x2215 };
  74039. if (c < 0x80)
  74040. return c;
  74041. else if (c < 0x80 + 0x50)
  74042. return c - 0x80 + 0x300;
  74043. else
  74044. return unicode_short_table[c - 0x80 - 0x50];
  74045. }
  74046. static uint32_t unicode_get_lower_simple(uint32_t c)
  74047. {
  74048. if (c < 0x100 || (c >= 0x410 && c <= 0x42f))
  74049. c += 0x20;
  74050. else
  74051. c++;
  74052. return c;
  74053. }
  74054. static uint16_t unicode_get16(const uint8_t *p)
  74055. {
  74056. return p[0] | (p[1] << 8);
  74057. }
  74058. static int unicode_decomp_entry(uint32_t *res, uint32_t c,
  74059. int idx, uint32_t code, uint32_t len,
  74060. uint32_t type)
  74061. {
  74062. uint32_t c1;
  74063. int l, i, p;
  74064. const uint8_t *d;
  74065. if (type == DECOMP_TYPE_C1) {
  74066. res[0] = unicode_decomp_table2[idx];
  74067. return 1;
  74068. } else {
  74069. d = unicode_decomp_data + unicode_decomp_table2[idx];
  74070. switch(type) {
  74071. case DECOMP_TYPE_L1:
  74072. case DECOMP_TYPE_L2:
  74073. case DECOMP_TYPE_L3:
  74074. case DECOMP_TYPE_L4:
  74075. case DECOMP_TYPE_L5:
  74076. case DECOMP_TYPE_L6:
  74077. case DECOMP_TYPE_L7:
  74078. l = type - DECOMP_TYPE_L1 + 1;
  74079. d += (c - code) * l * 2;
  74080. for(i = 0; i < l; i++) {
  74081. if ((res[i] = unicode_get16(d + 2 * i)) == 0)
  74082. return 0;
  74083. }
  74084. return l;
  74085. case DECOMP_TYPE_LL1:
  74086. case DECOMP_TYPE_LL2:
  74087. {
  74088. uint32_t k, p;
  74089. l = type - DECOMP_TYPE_LL1 + 1;
  74090. k = (c - code) * l;
  74091. p = len * l * 2;
  74092. for(i = 0; i < l; i++) {
  74093. c1 = unicode_get16(d + 2 * k) |
  74094. (((d[p + (k / 4)] >> ((k % 4) * 2)) & 3) << 16);
  74095. if (!c1)
  74096. return 0;
  74097. res[i] = c1;
  74098. k++;
  74099. }
  74100. }
  74101. return l;
  74102. case DECOMP_TYPE_S1:
  74103. case DECOMP_TYPE_S2:
  74104. case DECOMP_TYPE_S3:
  74105. case DECOMP_TYPE_S4:
  74106. case DECOMP_TYPE_S5:
  74107. l = type - DECOMP_TYPE_S1 + 1;
  74108. d += (c - code) * l;
  74109. for(i = 0; i < l; i++) {
  74110. if ((res[i] = unicode_get_short_code(d[i])) == 0)
  74111. return 0;
  74112. }
  74113. return l;
  74114. case DECOMP_TYPE_I1:
  74115. l = 1;
  74116. p = 0;
  74117. goto decomp_type_i;
  74118. case DECOMP_TYPE_I2_0:
  74119. case DECOMP_TYPE_I2_1:
  74120. case DECOMP_TYPE_I3_1:
  74121. case DECOMP_TYPE_I3_2:
  74122. case DECOMP_TYPE_I4_1:
  74123. case DECOMP_TYPE_I4_2:
  74124. l = 2 + ((type - DECOMP_TYPE_I2_0) >> 1);
  74125. p = ((type - DECOMP_TYPE_I2_0) & 1) + (l > 2);
  74126. decomp_type_i:
  74127. for(i = 0; i < l; i++) {
  74128. c1 = unicode_get16(d + 2 * i);
  74129. if (i == p)
  74130. c1 += c - code;
  74131. res[i] = c1;
  74132. }
  74133. return l;
  74134. case DECOMP_TYPE_B18:
  74135. l = 18;
  74136. goto decomp_type_b;
  74137. case DECOMP_TYPE_B1:
  74138. case DECOMP_TYPE_B2:
  74139. case DECOMP_TYPE_B3:
  74140. case DECOMP_TYPE_B4:
  74141. case DECOMP_TYPE_B5:
  74142. case DECOMP_TYPE_B6:
  74143. case DECOMP_TYPE_B7:
  74144. case DECOMP_TYPE_B8:
  74145. l = type - DECOMP_TYPE_B1 + 1;
  74146. decomp_type_b:
  74147. {
  74148. uint32_t c_min;
  74149. c_min = unicode_get16(d);
  74150. d += 2 + (c - code) * l;
  74151. for(i = 0; i < l; i++) {
  74152. c1 = d[i];
  74153. if (c1 == 0xff)
  74154. c1 = 0x20;
  74155. else
  74156. c1 += c_min;
  74157. res[i] = c1;
  74158. }
  74159. }
  74160. return l;
  74161. case DECOMP_TYPE_LS2:
  74162. d += (c - code) * 3;
  74163. if (!(res[0] = unicode_get16(d)))
  74164. return 0;
  74165. res[1] = unicode_get_short_code(d[2]);
  74166. return 2;
  74167. case DECOMP_TYPE_PAT3:
  74168. res[0] = unicode_get16(d);
  74169. res[2] = unicode_get16(d + 2);
  74170. d += 4 + (c - code) * 2;
  74171. res[1] = unicode_get16(d);
  74172. return 3;
  74173. case DECOMP_TYPE_S2_UL:
  74174. case DECOMP_TYPE_LS2_UL:
  74175. c1 = c - code;
  74176. if (type == DECOMP_TYPE_S2_UL) {
  74177. d += c1 & ~1;
  74178. c = unicode_get_short_code(*d);
  74179. d++;
  74180. } else {
  74181. d += (c1 >> 1) * 3;
  74182. c = unicode_get16(d);
  74183. d += 2;
  74184. }
  74185. if (c1 & 1)
  74186. c = unicode_get_lower_simple(c);
  74187. res[0] = c;
  74188. res[1] = unicode_get_short_code(*d);
  74189. return 2;
  74190. }
  74191. }
  74192. return 0;
  74193. }
  74194. /* return the length of the decomposition (length <=
  74195. UNICODE_DECOMP_LEN_MAX) or 0 if no decomposition */
  74196. static int unicode_decomp_char(uint32_t *res, uint32_t c, bool is_compat1)
  74197. {
  74198. uint32_t v, type, is_compat, code, len;
  74199. int idx_min, idx_max, idx;
  74200. idx_min = 0;
  74201. idx_max = countof(unicode_decomp_table1) - 1;
  74202. while (idx_min <= idx_max) {
  74203. idx = (idx_max + idx_min) / 2;
  74204. v = unicode_decomp_table1[idx];
  74205. code = v >> (32 - 18);
  74206. len = (v >> (32 - 18 - 7)) & 0x7f;
  74207. // printf("idx=%d code=%05x len=%d\n", idx, code, len);
  74208. if (c < code) {
  74209. idx_max = idx - 1;
  74210. } else if (c >= code + len) {
  74211. idx_min = idx + 1;
  74212. } else {
  74213. is_compat = v & 1;
  74214. if (is_compat1 < is_compat)
  74215. break;
  74216. type = (v >> (32 - 18 - 7 - 6)) & 0x3f;
  74217. return unicode_decomp_entry(res, c, idx, code, len, type);
  74218. }
  74219. }
  74220. return 0;
  74221. }
  74222. /* return 0 if no pair found */
  74223. static int unicode_compose_pair(uint32_t c0, uint32_t c1)
  74224. {
  74225. uint32_t code, len, type, v, idx1, d_idx, d_offset, ch;
  74226. int idx_min, idx_max, idx, d;
  74227. uint32_t pair[2];
  74228. idx_min = 0;
  74229. idx_max = countof(unicode_comp_table) - 1;
  74230. while (idx_min <= idx_max) {
  74231. idx = (idx_max + idx_min) / 2;
  74232. idx1 = unicode_comp_table[idx];
  74233. /* idx1 represent an entry of the decomposition table */
  74234. d_idx = idx1 >> 6;
  74235. d_offset = idx1 & 0x3f;
  74236. v = unicode_decomp_table1[d_idx];
  74237. code = v >> (32 - 18);
  74238. len = (v >> (32 - 18 - 7)) & 0x7f;
  74239. type = (v >> (32 - 18 - 7 - 6)) & 0x3f;
  74240. ch = code + d_offset;
  74241. unicode_decomp_entry(pair, ch, d_idx, code, len, type);
  74242. d = c0 - pair[0];
  74243. if (d == 0)
  74244. d = c1 - pair[1];
  74245. if (d < 0) {
  74246. idx_max = idx - 1;
  74247. } else if (d > 0) {
  74248. idx_min = idx + 1;
  74249. } else {
  74250. return ch;
  74251. }
  74252. }
  74253. return 0;
  74254. }
  74255. /* return the combining class of character c (between 0 and 255) */
  74256. static int unicode_get_cc(uint32_t c)
  74257. {
  74258. uint32_t code, n, type, cc, c1, b;
  74259. int pos;
  74260. const uint8_t *p;
  74261. pos = get_index_pos(&code, c,
  74262. unicode_cc_index, sizeof(unicode_cc_index) / 3);
  74263. if (pos < 0)
  74264. return 0;
  74265. p = unicode_cc_table + pos;
  74266. for(;;) {
  74267. b = *p++;
  74268. type = b >> 6;
  74269. n = b & 0x3f;
  74270. if (n < 48) {
  74271. } else if (n < 56) {
  74272. n = (n - 48) << 8;
  74273. n |= *p++;
  74274. n += 48;
  74275. } else {
  74276. n = (n - 56) << 8;
  74277. n |= *p++ << 8;
  74278. n |= *p++;
  74279. n += 48 + (1 << 11);
  74280. }
  74281. if (type <= 1)
  74282. p++;
  74283. c1 = code + n + 1;
  74284. if (c < c1) {
  74285. switch(type) {
  74286. case 0:
  74287. cc = p[-1];
  74288. break;
  74289. case 1:
  74290. cc = p[-1] + c - code;
  74291. break;
  74292. case 2:
  74293. cc = 0;
  74294. break;
  74295. default:
  74296. case 3:
  74297. cc = 230;
  74298. break;
  74299. }
  74300. return cc;
  74301. }
  74302. code = c1;
  74303. }
  74304. }
  74305. static void sort_cc(int *buf, int len)
  74306. {
  74307. int i, j, k, cc, cc1, start, ch1;
  74308. for(i = 0; i < len; i++) {
  74309. cc = unicode_get_cc(buf[i]);
  74310. if (cc != 0) {
  74311. start = i;
  74312. j = i + 1;
  74313. while (j < len) {
  74314. ch1 = buf[j];
  74315. cc1 = unicode_get_cc(ch1);
  74316. if (cc1 == 0)
  74317. break;
  74318. k = j - 1;
  74319. while (k >= start) {
  74320. if (unicode_get_cc(buf[k]) <= cc1)
  74321. break;
  74322. buf[k + 1] = buf[k];
  74323. k--;
  74324. }
  74325. buf[k + 1] = ch1;
  74326. j++;
  74327. }
  74328. i = j;
  74329. }
  74330. }
  74331. }
  74332. static void to_nfd_rec(DynBuf *dbuf,
  74333. const int *src, int src_len, int is_compat)
  74334. {
  74335. uint32_t c, v;
  74336. int i, l;
  74337. uint32_t res[UNICODE_DECOMP_LEN_MAX];
  74338. for(i = 0; i < src_len; i++) {
  74339. c = src[i];
  74340. if (c >= 0xac00 && c < 0xd7a4) {
  74341. /* Hangul decomposition */
  74342. c -= 0xac00;
  74343. dbuf_put_u32(dbuf, 0x1100 + c / 588);
  74344. dbuf_put_u32(dbuf, 0x1161 + (c % 588) / 28);
  74345. v = c % 28;
  74346. if (v != 0)
  74347. dbuf_put_u32(dbuf, 0x11a7 + v);
  74348. } else {
  74349. l = unicode_decomp_char(res, c, is_compat);
  74350. if (l) {
  74351. to_nfd_rec(dbuf, (int *)res, l, is_compat);
  74352. } else {
  74353. dbuf_put_u32(dbuf, c);
  74354. }
  74355. }
  74356. }
  74357. }
  74358. /* return 0 if not found */
  74359. static int compose_pair(uint32_t c0, uint32_t c1)
  74360. {
  74361. /* Hangul composition */
  74362. if (c0 >= 0x1100 && c0 < 0x1100 + 19 &&
  74363. c1 >= 0x1161 && c1 < 0x1161 + 21) {
  74364. return 0xac00 + (c0 - 0x1100) * 588 + (c1 - 0x1161) * 28;
  74365. } else if (c0 >= 0xac00 && c0 < 0xac00 + 11172 &&
  74366. (c0 - 0xac00) % 28 == 0 &&
  74367. c1 >= 0x11a7 && c1 < 0x11a7 + 28) {
  74368. return c0 + c1 - 0x11a7;
  74369. } else {
  74370. return unicode_compose_pair(c0, c1);
  74371. }
  74372. }
  74373. int unicode_normalize(uint32_t **pdst, const uint32_t *src, int src_len,
  74374. UnicodeNormalizationEnum n_type,
  74375. void *opaque, DynBufReallocFunc *realloc_func)
  74376. {
  74377. int *buf, buf_len, i, p, starter_pos, cc, last_cc, out_len;
  74378. bool is_compat;
  74379. DynBuf dbuf_s, *dbuf = &dbuf_s;
  74380. is_compat = n_type >> 1;
  74381. dbuf_init2(dbuf, opaque, realloc_func);
  74382. if (dbuf_realloc(dbuf, sizeof(int) * src_len))
  74383. goto fail;
  74384. /* common case: latin1 is unaffected by NFC */
  74385. if (n_type == UNICODE_NFC) {
  74386. for(i = 0; i < src_len; i++) {
  74387. if (src[i] >= 0x100)
  74388. goto not_latin1;
  74389. }
  74390. buf = (int *)dbuf->buf;
  74391. memcpy(buf, src, src_len * sizeof(int));
  74392. *pdst = (uint32_t *)buf;
  74393. return src_len;
  74394. not_latin1: ;
  74395. }
  74396. to_nfd_rec(dbuf, (const int *)src, src_len, is_compat);
  74397. if (dbuf_error(dbuf)) {
  74398. fail:
  74399. *pdst = NULL;
  74400. return -1;
  74401. }
  74402. buf = (int *)dbuf->buf;
  74403. buf_len = dbuf->size / sizeof(int);
  74404. sort_cc(buf, buf_len);
  74405. if (buf_len <= 1 || (n_type & 1) != 0) {
  74406. /* NFD / NFKD */
  74407. *pdst = (uint32_t *)buf;
  74408. return buf_len;
  74409. }
  74410. i = 1;
  74411. out_len = 1;
  74412. while (i < buf_len) {
  74413. /* find the starter character and test if it is blocked from
  74414. the character at 'i' */
  74415. last_cc = unicode_get_cc(buf[i]);
  74416. starter_pos = out_len - 1;
  74417. while (starter_pos >= 0) {
  74418. cc = unicode_get_cc(buf[starter_pos]);
  74419. if (cc == 0)
  74420. break;
  74421. if (cc >= last_cc)
  74422. goto next;
  74423. last_cc = 256;
  74424. starter_pos--;
  74425. }
  74426. if (starter_pos >= 0 &&
  74427. (p = compose_pair(buf[starter_pos], buf[i])) != 0) {
  74428. buf[starter_pos] = p;
  74429. i++;
  74430. } else {
  74431. next:
  74432. buf[out_len++] = buf[i++];
  74433. }
  74434. }
  74435. *pdst = (uint32_t *)buf;
  74436. return out_len;
  74437. }
  74438. /* char ranges for various unicode properties */
  74439. static int unicode_find_name(const char *name_table, const char *name)
  74440. {
  74441. const char *p, *r;
  74442. int pos;
  74443. size_t name_len, len;
  74444. p = name_table;
  74445. pos = 0;
  74446. name_len = strlen(name);
  74447. while (*p) {
  74448. for(;;) {
  74449. r = strchr(p, ',');
  74450. if (!r)
  74451. len = strlen(p);
  74452. else
  74453. len = r - p;
  74454. if (len == name_len && !memcmp(p, name, name_len))
  74455. return pos;
  74456. p += len + 1;
  74457. if (!r)
  74458. break;
  74459. }
  74460. pos++;
  74461. }
  74462. return -1;
  74463. }
  74464. /* 'cr' must be initialized and empty. Return 0 if OK, -1 if error, -2
  74465. if not found */
  74466. int unicode_script(CharRange *cr,
  74467. const char *script_name, bool is_ext)
  74468. {
  74469. int script_idx;
  74470. const uint8_t *p, *p_end;
  74471. uint32_t c, c1, b, n, v, v_len, i, type;
  74472. CharRange cr1_s = { 0 }, *cr1 = NULL;
  74473. CharRange cr2_s = { 0 }, *cr2 = &cr2_s;
  74474. bool is_common;
  74475. script_idx = unicode_find_name(unicode_script_name_table, script_name);
  74476. if (script_idx < 0)
  74477. return -2;
  74478. /* Note: we remove the "Unknown" Script */
  74479. script_idx += UNICODE_SCRIPT_Unknown + 1;
  74480. is_common = (script_idx == UNICODE_SCRIPT_Common ||
  74481. script_idx == UNICODE_SCRIPT_Inherited);
  74482. if (is_ext) {
  74483. cr1 = &cr1_s;
  74484. cr_init(cr1, cr->mem_opaque, cr->realloc_func);
  74485. cr_init(cr2, cr->mem_opaque, cr->realloc_func);
  74486. } else {
  74487. cr1 = cr;
  74488. }
  74489. p = unicode_script_table;
  74490. p_end = unicode_script_table + countof(unicode_script_table);
  74491. c = 0;
  74492. while (p < p_end) {
  74493. b = *p++;
  74494. type = b >> 7;
  74495. n = b & 0x7f;
  74496. if (n < 96) {
  74497. } else if (n < 112) {
  74498. n = (n - 96) << 8;
  74499. n |= *p++;
  74500. n += 96;
  74501. } else {
  74502. n = (n - 112) << 16;
  74503. n |= *p++ << 8;
  74504. n |= *p++;
  74505. n += 96 + (1 << 12);
  74506. }
  74507. if (type == 0)
  74508. v = 0;
  74509. else
  74510. v = *p++;
  74511. c1 = c + n + 1;
  74512. if (v == script_idx) {
  74513. if (cr_add_interval(cr1, c, c1))
  74514. goto fail;
  74515. }
  74516. c = c1;
  74517. }
  74518. if (is_ext) {
  74519. /* add the script extensions */
  74520. p = unicode_script_ext_table;
  74521. p_end = unicode_script_ext_table + countof(unicode_script_ext_table);
  74522. c = 0;
  74523. while (p < p_end) {
  74524. b = *p++;
  74525. if (b < 128) {
  74526. n = b;
  74527. } else if (b < 128 + 64) {
  74528. n = (b - 128) << 8;
  74529. n |= *p++;
  74530. n += 128;
  74531. } else {
  74532. n = (b - 128 - 64) << 16;
  74533. n |= *p++ << 8;
  74534. n |= *p++;
  74535. n += 128 + (1 << 14);
  74536. }
  74537. c1 = c + n + 1;
  74538. v_len = *p++;
  74539. if (is_common) {
  74540. if (v_len != 0) {
  74541. if (cr_add_interval(cr2, c, c1))
  74542. goto fail;
  74543. }
  74544. } else {
  74545. for(i = 0; i < v_len; i++) {
  74546. if (p[i] == script_idx) {
  74547. if (cr_add_interval(cr2, c, c1))
  74548. goto fail;
  74549. break;
  74550. }
  74551. }
  74552. }
  74553. p += v_len;
  74554. c = c1;
  74555. }
  74556. if (is_common) {
  74557. /* remove all the characters with script extensions */
  74558. if (cr_invert(cr2))
  74559. goto fail;
  74560. if (cr_op(cr, cr1->points, cr1->len, cr2->points, cr2->len,
  74561. CR_OP_INTER))
  74562. goto fail;
  74563. } else {
  74564. if (cr_op(cr, cr1->points, cr1->len, cr2->points, cr2->len,
  74565. CR_OP_UNION))
  74566. goto fail;
  74567. }
  74568. cr_free(cr1);
  74569. cr_free(cr2);
  74570. }
  74571. return 0;
  74572. fail:
  74573. if (is_ext) {
  74574. cr_free(cr1);
  74575. cr_free(cr2);
  74576. }
  74577. goto fail;
  74578. }
  74579. #define M(id) (1U << UNICODE_GC_ ## id)
  74580. static int unicode_general_category1(CharRange *cr, uint32_t gc_mask)
  74581. {
  74582. const uint8_t *p, *p_end;
  74583. uint32_t c, c0, b, n, v;
  74584. p = unicode_gc_table;
  74585. p_end = unicode_gc_table + countof(unicode_gc_table);
  74586. c = 0;
  74587. while (p < p_end) {
  74588. b = *p++;
  74589. n = b >> 5;
  74590. v = b & 0x1f;
  74591. if (n == 7) {
  74592. n = *p++;
  74593. if (n < 128) {
  74594. n += 7;
  74595. } else if (n < 128 + 64) {
  74596. n = (n - 128) << 8;
  74597. n |= *p++;
  74598. n += 7 + 128;
  74599. } else {
  74600. n = (n - 128 - 64) << 16;
  74601. n |= *p++ << 8;
  74602. n |= *p++;
  74603. n += 7 + 128 + (1 << 14);
  74604. }
  74605. }
  74606. c0 = c;
  74607. c += n + 1;
  74608. if (v == 31) {
  74609. /* run of Lu / Ll */
  74610. b = gc_mask & (M(Lu) | M(Ll));
  74611. if (b != 0) {
  74612. if (b == (M(Lu) | M(Ll))) {
  74613. goto add_range;
  74614. } else {
  74615. c0 += ((gc_mask & M(Ll)) != 0);
  74616. for(; c0 < c; c0 += 2) {
  74617. if (cr_add_interval(cr, c0, c0 + 1))
  74618. return -1;
  74619. }
  74620. }
  74621. }
  74622. } else if ((gc_mask >> v) & 1) {
  74623. add_range:
  74624. if (cr_add_interval(cr, c0, c))
  74625. return -1;
  74626. }
  74627. }
  74628. return 0;
  74629. }
  74630. static int unicode_prop1(CharRange *cr, int prop_idx)
  74631. {
  74632. const uint8_t *p, *p_end;
  74633. uint32_t c, c0, b, bit;
  74634. p = unicode_prop_table[prop_idx];
  74635. p_end = p + unicode_prop_len_table[prop_idx];
  74636. c = 0;
  74637. bit = 0;
  74638. while (p < p_end) {
  74639. c0 = c;
  74640. b = *p++;
  74641. if (b < 64) {
  74642. c += (b >> 3) + 1;
  74643. if (bit) {
  74644. if (cr_add_interval(cr, c0, c))
  74645. return -1;
  74646. }
  74647. bit ^= 1;
  74648. c0 = c;
  74649. c += (b & 7) + 1;
  74650. } else if (b >= 0x80) {
  74651. c += b - 0x80 + 1;
  74652. } else if (b < 0x60) {
  74653. c += (((b - 0x40) << 8) | p[0]) + 1;
  74654. p++;
  74655. } else {
  74656. c += (((b - 0x60) << 16) | (p[0] << 8) | p[1]) + 1;
  74657. p += 2;
  74658. }
  74659. if (bit) {
  74660. if (cr_add_interval(cr, c0, c))
  74661. return -1;
  74662. }
  74663. bit ^= 1;
  74664. }
  74665. return 0;
  74666. }
  74667. #define CASE_U (1 << 0)
  74668. #define CASE_L (1 << 1)
  74669. #define CASE_F (1 << 2)
  74670. /* use the case conversion table to generate range of characters.
  74671. CASE_U: set char if modified by uppercasing,
  74672. CASE_L: set char if modified by lowercasing,
  74673. CASE_F: set char if modified by case folding,
  74674. */
  74675. static int unicode_case1(CharRange *cr, int case_mask)
  74676. {
  74677. #define MR(x) (1 << RUN_TYPE_ ## x)
  74678. const uint32_t tab_run_mask[3] = {
  74679. MR(U) | MR(UF) | MR(UL) | MR(LSU) | MR(U2L_399_EXT2) | MR(UF_D20) |
  74680. MR(UF_D1_EXT) | MR(U_EXT) | MR(UF_EXT2) | MR(UF_EXT3),
  74681. MR(L) | MR(LF) | MR(UL) | MR(LSU) | MR(U2L_399_EXT2) | MR(LF_EXT) | MR(LF_EXT2),
  74682. MR(UF) | MR(LF) | MR(UL) | MR(LSU) | MR(U2L_399_EXT2) | MR(LF_EXT) | MR(LF_EXT2) | MR(UF_D20) | MR(UF_D1_EXT) | MR(LF_EXT) | MR(UF_EXT2) | MR(UF_EXT3),
  74683. };
  74684. #undef MR
  74685. uint32_t mask, v, code, type, len, i, idx;
  74686. if (case_mask == 0)
  74687. return 0;
  74688. mask = 0;
  74689. for(i = 0; i < 3; i++) {
  74690. if ((case_mask >> i) & 1)
  74691. mask |= tab_run_mask[i];
  74692. }
  74693. for(idx = 0; idx < countof(case_conv_table1); idx++) {
  74694. v = case_conv_table1[idx];
  74695. type = (v >> (32 - 17 - 7 - 4)) & 0xf;
  74696. code = v >> (32 - 17);
  74697. len = (v >> (32 - 17 - 7)) & 0x7f;
  74698. if ((mask >> type) & 1) {
  74699. // printf("%d: type=%d %04x %04x\n", idx, type, code, code + len - 1);
  74700. switch(type) {
  74701. case RUN_TYPE_UL:
  74702. if ((case_mask & CASE_U) && (case_mask & (CASE_L | CASE_F)))
  74703. goto def_case;
  74704. code += ((case_mask & CASE_U) != 0);
  74705. for(i = 0; i < len; i += 2) {
  74706. if (cr_add_interval(cr, code + i, code + i + 1))
  74707. return -1;
  74708. }
  74709. break;
  74710. case RUN_TYPE_LSU:
  74711. if ((case_mask & CASE_U) && (case_mask & (CASE_L | CASE_F)))
  74712. goto def_case;
  74713. if (!(case_mask & CASE_U)) {
  74714. if (cr_add_interval(cr, code, code + 1))
  74715. return -1;
  74716. }
  74717. if (cr_add_interval(cr, code + 1, code + 2))
  74718. return -1;
  74719. if (case_mask & CASE_U) {
  74720. if (cr_add_interval(cr, code + 2, code + 3))
  74721. return -1;
  74722. }
  74723. break;
  74724. default:
  74725. def_case:
  74726. if (cr_add_interval(cr, code, code + len))
  74727. return -1;
  74728. break;
  74729. }
  74730. }
  74731. }
  74732. return 0;
  74733. }
  74734. static int point_cmp(const void *p1, const void *p2, void *arg)
  74735. {
  74736. uint32_t v1 = *(uint32_t *)p1;
  74737. uint32_t v2 = *(uint32_t *)p2;
  74738. return (v1 > v2) - (v1 < v2);
  74739. }
  74740. static void cr_sort_and_remove_overlap(CharRange *cr)
  74741. {
  74742. uint32_t start, end, start1, end1, i, j;
  74743. /* the resulting ranges are not necessarily sorted and may overlap */
  74744. rqsort(cr->points, cr->len / 2, sizeof(cr->points[0]) * 2, point_cmp, NULL);
  74745. j = 0;
  74746. for(i = 0; i < cr->len; ) {
  74747. start = cr->points[i];
  74748. end = cr->points[i + 1];
  74749. i += 2;
  74750. while (i < cr->len) {
  74751. start1 = cr->points[i];
  74752. end1 = cr->points[i + 1];
  74753. if (start1 > end) {
  74754. /* |------|
  74755. * |-------| */
  74756. break;
  74757. } else if (end1 <= end) {
  74758. /* |------|
  74759. * |--| */
  74760. i += 2;
  74761. } else {
  74762. /* |------|
  74763. * |-------| */
  74764. end = end1;
  74765. i += 2;
  74766. }
  74767. }
  74768. cr->points[j] = start;
  74769. cr->points[j + 1] = end;
  74770. j += 2;
  74771. }
  74772. cr->len = j;
  74773. }
  74774. /* canonicalize a character set using the JS regex case folding rules
  74775. (see lre_canonicalize()) */
  74776. int cr_regexp_canonicalize(CharRange *cr, bool is_unicode)
  74777. {
  74778. CharRange cr_inter, cr_mask, cr_result, cr_sub;
  74779. uint32_t v, code, len, i, idx, start, end, c, d_start, d_end, d;
  74780. cr_init(&cr_mask, cr->mem_opaque, cr->realloc_func);
  74781. cr_init(&cr_inter, cr->mem_opaque, cr->realloc_func);
  74782. cr_init(&cr_result, cr->mem_opaque, cr->realloc_func);
  74783. cr_init(&cr_sub, cr->mem_opaque, cr->realloc_func);
  74784. if (unicode_case1(&cr_mask, is_unicode ? CASE_F : CASE_U))
  74785. goto fail;
  74786. if (cr_op(&cr_inter, cr_mask.points, cr_mask.len, cr->points, cr->len, CR_OP_INTER))
  74787. goto fail;
  74788. if (cr_invert(&cr_mask))
  74789. goto fail;
  74790. if (cr_op(&cr_sub, cr_mask.points, cr_mask.len, cr->points, cr->len, CR_OP_INTER))
  74791. goto fail;
  74792. /* cr_inter = cr & cr_mask */
  74793. /* cr_sub = cr & ~cr_mask */
  74794. /* use the case conversion table to compute the result */
  74795. d_start = -1;
  74796. d_end = -1;
  74797. idx = 0;
  74798. v = case_conv_table1[idx];
  74799. code = v >> (32 - 17);
  74800. len = (v >> (32 - 17 - 7)) & 0x7f;
  74801. for(i = 0; i < cr_inter.len; i += 2) {
  74802. start = cr_inter.points[i];
  74803. end = cr_inter.points[i + 1];
  74804. for(c = start; c < end; c++) {
  74805. for(;;) {
  74806. if (c >= code && c < code + len)
  74807. break;
  74808. idx++;
  74809. assert(idx < countof(case_conv_table1));
  74810. v = case_conv_table1[idx];
  74811. code = v >> (32 - 17);
  74812. len = (v >> (32 - 17 - 7)) & 0x7f;
  74813. }
  74814. d = lre_case_folding_entry(c, idx, v, is_unicode);
  74815. /* try to merge with the current interval */
  74816. if (d_start == -1) {
  74817. d_start = d;
  74818. d_end = d + 1;
  74819. } else if (d_end == d) {
  74820. d_end++;
  74821. } else {
  74822. cr_add_interval(&cr_result, d_start, d_end);
  74823. d_start = d;
  74824. d_end = d + 1;
  74825. }
  74826. }
  74827. }
  74828. if (d_start != -1) {
  74829. if (cr_add_interval(&cr_result, d_start, d_end))
  74830. goto fail;
  74831. }
  74832. /* the resulting ranges are not necessarily sorted and may overlap */
  74833. cr_sort_and_remove_overlap(&cr_result);
  74834. /* or with the character not affected by the case folding */
  74835. cr->len = 0;
  74836. if (cr_op(cr, cr_result.points, cr_result.len, cr_sub.points, cr_sub.len, CR_OP_UNION))
  74837. goto fail;
  74838. cr_free(&cr_inter);
  74839. cr_free(&cr_mask);
  74840. cr_free(&cr_result);
  74841. cr_free(&cr_sub);
  74842. return 0;
  74843. fail:
  74844. cr_free(&cr_inter);
  74845. cr_free(&cr_mask);
  74846. cr_free(&cr_result);
  74847. cr_free(&cr_sub);
  74848. return -1;
  74849. }
  74850. typedef enum {
  74851. POP_GC,
  74852. POP_PROP,
  74853. POP_CASE,
  74854. POP_UNION,
  74855. POP_INTER,
  74856. POP_XOR,
  74857. POP_INVERT,
  74858. POP_END,
  74859. } PropOPEnum;
  74860. #define POP_STACK_LEN_MAX 4
  74861. static int unicode_prop_ops(CharRange *cr, ...)
  74862. {
  74863. va_list ap;
  74864. CharRange stack[POP_STACK_LEN_MAX];
  74865. int stack_len, op, ret, i;
  74866. uint32_t a;
  74867. va_start(ap, cr);
  74868. stack_len = 0;
  74869. for(;;) {
  74870. op = va_arg(ap, int);
  74871. switch(op) {
  74872. case POP_GC:
  74873. assert(stack_len < POP_STACK_LEN_MAX);
  74874. a = va_arg(ap, int);
  74875. cr_init(&stack[stack_len++], cr->mem_opaque, cr->realloc_func);
  74876. if (unicode_general_category1(&stack[stack_len - 1], a))
  74877. goto fail;
  74878. break;
  74879. case POP_PROP:
  74880. assert(stack_len < POP_STACK_LEN_MAX);
  74881. a = va_arg(ap, int);
  74882. cr_init(&stack[stack_len++], cr->mem_opaque, cr->realloc_func);
  74883. if (unicode_prop1(&stack[stack_len - 1], a))
  74884. goto fail;
  74885. break;
  74886. case POP_CASE:
  74887. assert(stack_len < POP_STACK_LEN_MAX);
  74888. a = va_arg(ap, int);
  74889. cr_init(&stack[stack_len++], cr->mem_opaque, cr->realloc_func);
  74890. if (unicode_case1(&stack[stack_len - 1], a))
  74891. goto fail;
  74892. break;
  74893. case POP_UNION:
  74894. case POP_INTER:
  74895. case POP_XOR:
  74896. {
  74897. CharRange *cr1, *cr2, *cr3;
  74898. assert(stack_len >= 2);
  74899. assert(stack_len < POP_STACK_LEN_MAX);
  74900. cr1 = &stack[stack_len - 2];
  74901. cr2 = &stack[stack_len - 1];
  74902. cr3 = &stack[stack_len++];
  74903. cr_init(cr3, cr->mem_opaque, cr->realloc_func);
  74904. if (cr_op(cr3, cr1->points, cr1->len,
  74905. cr2->points, cr2->len, op - POP_UNION + CR_OP_UNION))
  74906. goto fail;
  74907. cr_free(cr1);
  74908. cr_free(cr2);
  74909. *cr1 = *cr3;
  74910. stack_len -= 2;
  74911. }
  74912. break;
  74913. case POP_INVERT:
  74914. assert(stack_len >= 1);
  74915. if (cr_invert(&stack[stack_len - 1]))
  74916. goto fail;
  74917. break;
  74918. case POP_END:
  74919. goto done;
  74920. default:
  74921. abort();
  74922. }
  74923. }
  74924. done:
  74925. va_end(ap);
  74926. assert(stack_len == 1);
  74927. ret = cr_copy(cr, &stack[0]);
  74928. cr_free(&stack[0]);
  74929. return ret;
  74930. fail:
  74931. va_end(ap);
  74932. for(i = 0; i < stack_len; i++)
  74933. cr_free(&stack[i]);
  74934. return -1;
  74935. }
  74936. static const uint32_t unicode_gc_mask_table[] = {
  74937. M(Lu) | M(Ll) | M(Lt), /* LC */
  74938. M(Lu) | M(Ll) | M(Lt) | M(Lm) | M(Lo), /* L */
  74939. M(Mn) | M(Mc) | M(Me), /* M */
  74940. M(Nd) | M(Nl) | M(No), /* N */
  74941. M(Sm) | M(Sc) | M(Sk) | M(So), /* S */
  74942. M(Pc) | M(Pd) | M(Ps) | M(Pe) | M(Pi) | M(Pf) | M(Po), /* P */
  74943. M(Zs) | M(Zl) | M(Zp), /* Z */
  74944. M(Cc) | M(Cf) | M(Cs) | M(Co) | M(Cn), /* C */
  74945. };
  74946. /* 'cr' must be initialized and empty. Return 0 if OK, -1 if error, -2
  74947. if not found */
  74948. int unicode_general_category(CharRange *cr, const char *gc_name)
  74949. {
  74950. int gc_idx;
  74951. uint32_t gc_mask;
  74952. gc_idx = unicode_find_name(unicode_gc_name_table, gc_name);
  74953. if (gc_idx < 0)
  74954. return -2;
  74955. if (gc_idx <= UNICODE_GC_Co) {
  74956. gc_mask = (uint64_t)1 << gc_idx;
  74957. } else {
  74958. gc_mask = unicode_gc_mask_table[gc_idx - UNICODE_GC_LC];
  74959. }
  74960. return unicode_general_category1(cr, gc_mask);
  74961. }
  74962. /* 'cr' must be initialized and empty. Return 0 if OK, -1 if error, -2
  74963. if not found */
  74964. int unicode_prop(CharRange *cr, const char *prop_name)
  74965. {
  74966. int prop_idx, ret;
  74967. prop_idx = unicode_find_name(unicode_prop_name_table, prop_name);
  74968. if (prop_idx < 0)
  74969. return -2;
  74970. prop_idx += UNICODE_PROP_ASCII_Hex_Digit;
  74971. ret = 0;
  74972. switch(prop_idx) {
  74973. case UNICODE_PROP_ASCII:
  74974. if (cr_add_interval(cr, 0x00, 0x7f + 1))
  74975. return -1;
  74976. break;
  74977. case UNICODE_PROP_Any:
  74978. if (cr_add_interval(cr, 0x00000, 0x10ffff + 1))
  74979. return -1;
  74980. break;
  74981. case UNICODE_PROP_Assigned:
  74982. ret = unicode_prop_ops(cr,
  74983. POP_GC, M(Cn),
  74984. POP_INVERT,
  74985. POP_END);
  74986. break;
  74987. case UNICODE_PROP_Math:
  74988. ret = unicode_prop_ops(cr,
  74989. POP_GC, M(Sm),
  74990. POP_PROP, UNICODE_PROP_Other_Math,
  74991. POP_UNION,
  74992. POP_END);
  74993. break;
  74994. case UNICODE_PROP_Lowercase:
  74995. ret = unicode_prop_ops(cr,
  74996. POP_GC, M(Ll),
  74997. POP_PROP, UNICODE_PROP_Other_Lowercase,
  74998. POP_UNION,
  74999. POP_END);
  75000. break;
  75001. case UNICODE_PROP_Uppercase:
  75002. ret = unicode_prop_ops(cr,
  75003. POP_GC, M(Lu),
  75004. POP_PROP, UNICODE_PROP_Other_Uppercase,
  75005. POP_UNION,
  75006. POP_END);
  75007. break;
  75008. case UNICODE_PROP_Cased:
  75009. ret = unicode_prop_ops(cr,
  75010. POP_GC, M(Lu) | M(Ll) | M(Lt),
  75011. POP_PROP, UNICODE_PROP_Other_Uppercase,
  75012. POP_UNION,
  75013. POP_PROP, UNICODE_PROP_Other_Lowercase,
  75014. POP_UNION,
  75015. POP_END);
  75016. break;
  75017. case UNICODE_PROP_Alphabetic:
  75018. ret = unicode_prop_ops(cr,
  75019. POP_GC, M(Lu) | M(Ll) | M(Lt) | M(Lm) | M(Lo) | M(Nl),
  75020. POP_PROP, UNICODE_PROP_Other_Uppercase,
  75021. POP_UNION,
  75022. POP_PROP, UNICODE_PROP_Other_Lowercase,
  75023. POP_UNION,
  75024. POP_PROP, UNICODE_PROP_Other_Alphabetic,
  75025. POP_UNION,
  75026. POP_END);
  75027. break;
  75028. case UNICODE_PROP_Grapheme_Base:
  75029. ret = unicode_prop_ops(cr,
  75030. POP_GC, M(Cc) | M(Cf) | M(Cs) | M(Co) | M(Cn) | M(Zl) | M(Zp) | M(Me) | M(Mn),
  75031. POP_PROP, UNICODE_PROP_Other_Grapheme_Extend,
  75032. POP_UNION,
  75033. POP_INVERT,
  75034. POP_END);
  75035. break;
  75036. case UNICODE_PROP_Grapheme_Extend:
  75037. ret = unicode_prop_ops(cr,
  75038. POP_GC, M(Me) | M(Mn),
  75039. POP_PROP, UNICODE_PROP_Other_Grapheme_Extend,
  75040. POP_UNION,
  75041. POP_END);
  75042. break;
  75043. case UNICODE_PROP_XID_Start:
  75044. ret = unicode_prop_ops(cr,
  75045. POP_GC, M(Lu) | M(Ll) | M(Lt) | M(Lm) | M(Lo) | M(Nl),
  75046. POP_PROP, UNICODE_PROP_Other_ID_Start,
  75047. POP_UNION,
  75048. POP_PROP, UNICODE_PROP_Pattern_Syntax,
  75049. POP_PROP, UNICODE_PROP_Pattern_White_Space,
  75050. POP_UNION,
  75051. POP_PROP, UNICODE_PROP_XID_Start1,
  75052. POP_UNION,
  75053. POP_INVERT,
  75054. POP_INTER,
  75055. POP_END);
  75056. break;
  75057. case UNICODE_PROP_XID_Continue:
  75058. ret = unicode_prop_ops(cr,
  75059. POP_GC, M(Lu) | M(Ll) | M(Lt) | M(Lm) | M(Lo) | M(Nl) |
  75060. M(Mn) | M(Mc) | M(Nd) | M(Pc),
  75061. POP_PROP, UNICODE_PROP_Other_ID_Start,
  75062. POP_UNION,
  75063. POP_PROP, UNICODE_PROP_Other_ID_Continue,
  75064. POP_UNION,
  75065. POP_PROP, UNICODE_PROP_Pattern_Syntax,
  75066. POP_PROP, UNICODE_PROP_Pattern_White_Space,
  75067. POP_UNION,
  75068. POP_PROP, UNICODE_PROP_XID_Continue1,
  75069. POP_UNION,
  75070. POP_INVERT,
  75071. POP_INTER,
  75072. POP_END);
  75073. break;
  75074. case UNICODE_PROP_Changes_When_Uppercased:
  75075. ret = unicode_case1(cr, CASE_U);
  75076. break;
  75077. case UNICODE_PROP_Changes_When_Lowercased:
  75078. ret = unicode_case1(cr, CASE_L);
  75079. break;
  75080. case UNICODE_PROP_Changes_When_Casemapped:
  75081. ret = unicode_case1(cr, CASE_U | CASE_L | CASE_F);
  75082. break;
  75083. case UNICODE_PROP_Changes_When_Titlecased:
  75084. ret = unicode_prop_ops(cr,
  75085. POP_CASE, CASE_U,
  75086. POP_PROP, UNICODE_PROP_Changes_When_Titlecased1,
  75087. POP_XOR,
  75088. POP_END);
  75089. break;
  75090. case UNICODE_PROP_Changes_When_Casefolded:
  75091. ret = unicode_prop_ops(cr,
  75092. POP_CASE, CASE_F,
  75093. POP_PROP, UNICODE_PROP_Changes_When_Casefolded1,
  75094. POP_XOR,
  75095. POP_END);
  75096. break;
  75097. case UNICODE_PROP_Changes_When_NFKC_Casefolded:
  75098. ret = unicode_prop_ops(cr,
  75099. POP_CASE, CASE_F,
  75100. POP_PROP, UNICODE_PROP_Changes_When_NFKC_Casefolded1,
  75101. POP_XOR,
  75102. POP_END);
  75103. break;
  75104. /* we use the existing tables */
  75105. case UNICODE_PROP_ID_Continue:
  75106. ret = unicode_prop_ops(cr,
  75107. POP_PROP, UNICODE_PROP_ID_Start,
  75108. POP_PROP, UNICODE_PROP_ID_Continue1,
  75109. POP_XOR,
  75110. POP_END);
  75111. break;
  75112. default:
  75113. if (prop_idx >= countof(unicode_prop_table))
  75114. return -2;
  75115. ret = unicode_prop1(cr, prop_idx);
  75116. break;
  75117. }
  75118. return ret;
  75119. }
  75120. #ifdef QJS_BUILD_LIBC
  75121. /*
  75122. * QuickJS C library
  75123. *
  75124. * Copyright (c) 2017-2018 Fabrice Bellard
  75125. *
  75126. * Permission is hereby granted, free of charge, to any person obtaining a copy
  75127. * of this software and associated documentation files (the "Software"), to deal
  75128. * in the Software without restriction, including without limitation the rights
  75129. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  75130. * copies of the Software, and to permit persons to whom the Software is
  75131. * furnished to do so, subject to the following conditions:
  75132. *
  75133. * The above copyright notice and this permission notice shall be included in
  75134. * all copies or substantial portions of the Software.
  75135. *
  75136. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  75137. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  75138. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  75139. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  75140. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  75141. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  75142. * THE SOFTWARE.
  75143. */
  75144. #ifndef QUICKJS_LIBC_H
  75145. #define QUICKJS_LIBC_H
  75146. #include <stdbool.h>
  75147. #include <stdio.h>
  75148. #include <stdlib.h>
  75149. #ifdef __cplusplus
  75150. extern "C" {
  75151. #endif
  75152. JSModuleDef *js_init_module_std(JSContext *ctx, const char *module_name);
  75153. JSModuleDef *js_init_module_os(JSContext *ctx, const char *module_name);
  75154. JSModuleDef *js_init_module_bjson(JSContext *ctx, const char *module_name);
  75155. void js_std_add_helpers(JSContext *ctx, int argc, char **argv);
  75156. int js_std_loop(JSContext *ctx);
  75157. JSValue js_std_await(JSContext *ctx, JSValue obj);
  75158. void js_std_init_handlers(JSRuntime *rt);
  75159. void js_std_free_handlers(JSRuntime *rt);
  75160. void js_std_dump_error(JSContext *ctx);
  75161. uint8_t *js_load_file(JSContext *ctx, size_t *pbuf_len, const char *filename);
  75162. int js_module_set_import_meta(JSContext *ctx, JSValueConst func_val,
  75163. bool use_realpath, bool is_main);
  75164. JSModuleDef *js_module_loader(JSContext *ctx,
  75165. const char *module_name, void *opaque);
  75166. void js_std_eval_binary(JSContext *ctx, const uint8_t *buf, size_t buf_len,
  75167. int flags);
  75168. void js_std_promise_rejection_tracker(JSContext *ctx, JSValueConst promise,
  75169. JSValueConst reason,
  75170. bool is_handled, void *opaque);
  75171. void js_std_set_worker_new_context_func(JSContext *(*func)(JSRuntime *rt));
  75172. #ifdef __cplusplus
  75173. } /* extern "C" { */
  75174. #endif
  75175. #endif /* QUICKJS_LIBC_H */
  75176. /*
  75177. * QuickJS C library
  75178. *
  75179. * Copyright (c) 2017-2021 Fabrice Bellard
  75180. * Copyright (c) 2017-2021 Charlie Gordon
  75181. *
  75182. * Permission is hereby granted, free of charge, to any person obtaining a copy
  75183. * of this software and associated documentation files (the "Software"), to deal
  75184. * in the Software without restriction, including without limitation the rights
  75185. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  75186. * copies of the Software, and to permit persons to whom the Software is
  75187. * furnished to do so, subject to the following conditions:
  75188. *
  75189. * The above copyright notice and this permission notice shall be included in
  75190. * all copies or substantial portions of the Software.
  75191. *
  75192. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  75193. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  75194. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  75195. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  75196. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  75197. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  75198. * THE SOFTWARE.
  75199. */
  75200. #include <stdlib.h>
  75201. #include <stdio.h>
  75202. #include <stdarg.h>
  75203. #include <inttypes.h>
  75204. #include <string.h>
  75205. #include <assert.h>
  75206. #if !defined(_MSC_VER)
  75207. #include <unistd.h>
  75208. #endif
  75209. #include <errno.h>
  75210. #include <fcntl.h>
  75211. #if !defined(_MSC_VER)
  75212. #include <sys/time.h>
  75213. #endif
  75214. #include <time.h>
  75215. #include <signal.h>
  75216. #include <limits.h>
  75217. #include <sys/stat.h>
  75218. #if defined(_MSC_VER)
  75219. #else
  75220. #include <dirent.h>
  75221. #endif
  75222. #if defined(_WIN32)
  75223. #include <windows.h>
  75224. #include <direct.h>
  75225. #include <io.h>
  75226. #include <conio.h>
  75227. #include <sys/stat.h>
  75228. #include <sys/types.h>
  75229. #include <sys/utime.h>
  75230. #define popen _popen
  75231. #define pclose _pclose
  75232. #define rmdir _rmdir
  75233. #define getcwd _getcwd
  75234. #define chdir _chdir
  75235. #else
  75236. #include <sys/ioctl.h>
  75237. #if !defined(__wasi__)
  75238. #include <dlfcn.h>
  75239. #include <termios.h>
  75240. #include <sys/resource.h>
  75241. #include <sys/wait.h>
  75242. #endif
  75243. #if defined(__APPLE__)
  75244. typedef sig_t sighandler_t;
  75245. #include <crt_externs.h>
  75246. #define environ (*_NSGetEnviron())
  75247. #endif
  75248. #if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__)
  75249. typedef sig_t sighandler_t;
  75250. extern char **environ;
  75251. #endif
  75252. #endif /* _WIN32 */
  75253. #if !defined(_WIN32) && !defined(__wasi__)
  75254. /* enable the os.Worker API. IT relies on POSIX threads */
  75255. #define USE_WORKER
  75256. #endif
  75257. #ifdef USE_WORKER
  75258. #include <pthread.h>
  75259. #endif
  75260. #ifndef MAX_SAFE_INTEGER // already defined in amalgamation builds
  75261. #define MAX_SAFE_INTEGER (((int64_t) 1 << 53) - 1)
  75262. #endif
  75263. #ifndef QJS_NATIVE_MODULE_SUFFIX
  75264. #ifdef _WIN32
  75265. #define QJS_NATIVE_MODULE_SUFFIX ".dll"
  75266. #else
  75267. #define QJS_NATIVE_MODULE_SUFFIX ".so"
  75268. #endif
  75269. #endif
  75270. /* TODO:
  75271. - add socket calls
  75272. */
  75273. typedef struct {
  75274. struct list_head link;
  75275. int fd;
  75276. JSValue rw_func[2];
  75277. } JSOSRWHandler;
  75278. typedef struct {
  75279. struct list_head link;
  75280. int sig_num;
  75281. JSValue func;
  75282. } JSOSSignalHandler;
  75283. typedef struct {
  75284. struct list_head link;
  75285. int64_t timer_id;
  75286. uint8_t repeats:1;
  75287. int64_t timeout;
  75288. int64_t delay;
  75289. JSValue func;
  75290. } JSOSTimer;
  75291. typedef struct {
  75292. struct list_head link;
  75293. uint8_t *data;
  75294. size_t data_len;
  75295. /* list of SharedArrayBuffers, necessary to free the message */
  75296. uint8_t **sab_tab;
  75297. size_t sab_tab_len;
  75298. } JSWorkerMessage;
  75299. typedef struct {
  75300. int ref_count;
  75301. #ifdef USE_WORKER
  75302. pthread_mutex_t mutex;
  75303. #endif
  75304. struct list_head msg_queue; /* list of JSWorkerMessage.link */
  75305. int read_fd;
  75306. int write_fd;
  75307. } JSWorkerMessagePipe;
  75308. typedef struct {
  75309. struct list_head link;
  75310. JSWorkerMessagePipe *recv_pipe;
  75311. JSValue on_message_func;
  75312. } JSWorkerMessageHandler;
  75313. typedef struct JSThreadState {
  75314. struct list_head os_rw_handlers; /* list of JSOSRWHandler.link */
  75315. struct list_head os_signal_handlers; /* list JSOSSignalHandler.link */
  75316. struct list_head os_timers; /* list of JSOSTimer.link */
  75317. struct list_head port_list; /* list of JSWorkerMessageHandler.link */
  75318. int eval_script_recurse; /* only used in the main thread */
  75319. int64_t next_timer_id; /* for setTimeout / setInterval */
  75320. bool can_js_os_poll;
  75321. /* not used in the main thread */
  75322. JSWorkerMessagePipe *recv_pipe, *send_pipe;
  75323. JSClassID std_file_class_id;
  75324. JSClassID worker_class_id;
  75325. } JSThreadState;
  75326. static uint64_t os_pending_signals;
  75327. static void *js_std_dbuf_realloc(void *opaque, void *ptr, size_t size)
  75328. {
  75329. JSRuntime *rt = opaque;
  75330. return js_realloc_rt(rt, ptr, size);
  75331. }
  75332. static void js_std_dbuf_init(JSContext *ctx, DynBuf *s)
  75333. {
  75334. dbuf_init2(s, JS_GetRuntime(ctx), js_std_dbuf_realloc);
  75335. }
  75336. static bool my_isdigit(int c)
  75337. {
  75338. return (c >= '0' && c <= '9');
  75339. }
  75340. static JSThreadState *js_get_thread_state(JSRuntime *rt)
  75341. {
  75342. return (JSThreadState *)js_std_cmd(/*GetOpaque*/0, rt);
  75343. }
  75344. static void js_set_thread_state(JSRuntime *rt, JSThreadState *ts)
  75345. {
  75346. js_std_cmd(/*SetOpaque*/1, rt, ts);
  75347. }
  75348. #ifdef __GNUC__
  75349. #pragma GCC diagnostic push
  75350. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  75351. #endif // __GNUC__
  75352. static JSValue js_printf_internal(JSContext *ctx,
  75353. int argc, JSValueConst *argv, FILE *fp)
  75354. {
  75355. char fmtbuf[32];
  75356. uint8_t cbuf[UTF8_CHAR_LEN_MAX+1];
  75357. JSValue res;
  75358. DynBuf dbuf;
  75359. const char *fmt_str = NULL;
  75360. const uint8_t *fmt, *fmt_end;
  75361. const uint8_t *p;
  75362. char *q;
  75363. int i, c, len, mod;
  75364. size_t fmt_len;
  75365. int32_t int32_arg;
  75366. int64_t int64_arg;
  75367. double double_arg;
  75368. const char *string_arg;
  75369. js_std_dbuf_init(ctx, &dbuf);
  75370. if (argc > 0) {
  75371. fmt_str = JS_ToCStringLen(ctx, &fmt_len, argv[0]);
  75372. if (!fmt_str)
  75373. goto fail;
  75374. i = 1;
  75375. fmt = (const uint8_t *)fmt_str;
  75376. fmt_end = fmt + fmt_len;
  75377. while (fmt < fmt_end) {
  75378. for (p = fmt; fmt < fmt_end && *fmt != '%'; fmt++)
  75379. continue;
  75380. dbuf_put(&dbuf, p, fmt - p);
  75381. if (fmt >= fmt_end)
  75382. break;
  75383. q = fmtbuf;
  75384. *q++ = *fmt++; /* copy '%' */
  75385. /* flags */
  75386. for(;;) {
  75387. c = *fmt;
  75388. if (c == '0' || c == '#' || c == '+' || c == '-' || c == ' ' ||
  75389. c == '\'') {
  75390. if (q >= fmtbuf + sizeof(fmtbuf) - 1)
  75391. goto invalid;
  75392. *q++ = c;
  75393. fmt++;
  75394. } else {
  75395. break;
  75396. }
  75397. }
  75398. /* width */
  75399. if (*fmt == '*') {
  75400. if (i >= argc)
  75401. goto missing;
  75402. if (JS_ToInt32(ctx, &int32_arg, argv[i++]))
  75403. goto fail;
  75404. q += snprintf(q, fmtbuf + sizeof(fmtbuf) - q, "%d", int32_arg);
  75405. fmt++;
  75406. } else {
  75407. while (my_isdigit(*fmt)) {
  75408. if (q >= fmtbuf + sizeof(fmtbuf) - 1)
  75409. goto invalid;
  75410. *q++ = *fmt++;
  75411. }
  75412. }
  75413. if (*fmt == '.') {
  75414. if (q >= fmtbuf + sizeof(fmtbuf) - 1)
  75415. goto invalid;
  75416. *q++ = *fmt++;
  75417. if (*fmt == '*') {
  75418. if (i >= argc)
  75419. goto missing;
  75420. if (JS_ToInt32(ctx, &int32_arg, argv[i++]))
  75421. goto fail;
  75422. q += snprintf(q, fmtbuf + sizeof(fmtbuf) - q, "%d", int32_arg);
  75423. fmt++;
  75424. } else {
  75425. while (my_isdigit(*fmt)) {
  75426. if (q >= fmtbuf + sizeof(fmtbuf) - 1)
  75427. goto invalid;
  75428. *q++ = *fmt++;
  75429. }
  75430. }
  75431. }
  75432. /* we only support the "l" modifier for 64 bit numbers */
  75433. mod = ' ';
  75434. if (*fmt == 'l') {
  75435. mod = *fmt++;
  75436. }
  75437. /* type */
  75438. c = *fmt++;
  75439. if (q >= fmtbuf + sizeof(fmtbuf) - 1)
  75440. goto invalid;
  75441. *q++ = c;
  75442. *q = '\0';
  75443. switch (c) {
  75444. case 'c':
  75445. if (i >= argc)
  75446. goto missing;
  75447. if (JS_IsString(argv[i])) {
  75448. // TODO(chqrlie) need an API to wrap charCodeAt and codePointAt */
  75449. string_arg = JS_ToCString(ctx, argv[i++]);
  75450. if (!string_arg)
  75451. goto fail;
  75452. int32_arg = utf8_decode((const uint8_t *)string_arg, &p);
  75453. JS_FreeCString(ctx, string_arg);
  75454. } else {
  75455. if (JS_ToInt32(ctx, &int32_arg, argv[i++]))
  75456. goto fail;
  75457. }
  75458. // XXX: throw an exception?
  75459. if ((unsigned)int32_arg > 0x10FFFF)
  75460. int32_arg = 0xFFFD;
  75461. /* ignore conversion flags, width and precision */
  75462. len = utf8_encode(cbuf, int32_arg);
  75463. dbuf_put(&dbuf, cbuf, len);
  75464. break;
  75465. case 'd':
  75466. case 'i':
  75467. case 'o':
  75468. case 'u':
  75469. case 'x':
  75470. case 'X':
  75471. if (i >= argc)
  75472. goto missing;
  75473. if (JS_ToInt64Ext(ctx, &int64_arg, argv[i++]))
  75474. goto fail;
  75475. if (mod == 'l') {
  75476. /* 64 bit number */
  75477. #if defined(_WIN32)
  75478. if (q >= fmtbuf + sizeof(fmtbuf) - 3)
  75479. goto invalid;
  75480. q[2] = q[-1];
  75481. q[-1] = 'I';
  75482. q[0] = '6';
  75483. q[1] = '4';
  75484. q[3] = '\0';
  75485. dbuf_printf(&dbuf, fmtbuf, (int64_t)int64_arg);
  75486. #else
  75487. if (q >= fmtbuf + sizeof(fmtbuf) - 2)
  75488. goto invalid;
  75489. q[1] = q[-1];
  75490. q[-1] = q[0] = 'l';
  75491. q[2] = '\0';
  75492. dbuf_printf(&dbuf, fmtbuf, (long long)int64_arg);
  75493. #endif
  75494. } else {
  75495. dbuf_printf(&dbuf, fmtbuf, (int)int64_arg);
  75496. }
  75497. break;
  75498. case 's':
  75499. if (i >= argc)
  75500. goto missing;
  75501. /* XXX: handle strings containing null characters */
  75502. string_arg = JS_ToCString(ctx, argv[i++]);
  75503. if (!string_arg)
  75504. goto fail;
  75505. dbuf_printf(&dbuf, fmtbuf, string_arg);
  75506. JS_FreeCString(ctx, string_arg);
  75507. break;
  75508. case 'e':
  75509. case 'f':
  75510. case 'g':
  75511. case 'a':
  75512. case 'E':
  75513. case 'F':
  75514. case 'G':
  75515. case 'A':
  75516. if (i >= argc)
  75517. goto missing;
  75518. if (JS_ToFloat64(ctx, &double_arg, argv[i++]))
  75519. goto fail;
  75520. dbuf_printf(&dbuf, fmtbuf, double_arg);
  75521. break;
  75522. case '%':
  75523. dbuf_putc(&dbuf, '%');
  75524. break;
  75525. default:
  75526. /* XXX: should support an extension mechanism */
  75527. invalid:
  75528. JS_ThrowTypeError(ctx, "invalid conversion specifier in format string");
  75529. goto fail;
  75530. missing:
  75531. JS_ThrowReferenceError(ctx, "missing argument for conversion specifier");
  75532. goto fail;
  75533. }
  75534. }
  75535. JS_FreeCString(ctx, fmt_str);
  75536. }
  75537. if (dbuf.error) {
  75538. res = JS_ThrowOutOfMemory(ctx);
  75539. } else {
  75540. if (fp) {
  75541. len = fwrite(dbuf.buf, 1, dbuf.size, fp);
  75542. res = JS_NewInt32(ctx, len);
  75543. } else {
  75544. res = JS_NewStringLen(ctx, (char *)dbuf.buf, dbuf.size);
  75545. }
  75546. }
  75547. dbuf_free(&dbuf);
  75548. return res;
  75549. fail:
  75550. JS_FreeCString(ctx, fmt_str);
  75551. dbuf_free(&dbuf);
  75552. return JS_EXCEPTION;
  75553. }
  75554. #ifdef __GNUC__
  75555. #pragma GCC diagnostic pop // ignored "-Wformat-nonliteral"
  75556. #endif // __GNUC__
  75557. uint8_t *js_load_file(JSContext *ctx, size_t *pbuf_len, const char *filename)
  75558. {
  75559. FILE *f;
  75560. size_t n, len;
  75561. uint8_t *p, *buf, tmp[8192];
  75562. f = fopen(filename, "rb");
  75563. if (!f)
  75564. return NULL;
  75565. buf = NULL;
  75566. len = 0;
  75567. do {
  75568. n = fread(tmp, 1, sizeof(tmp), f);
  75569. if (ctx) {
  75570. p = js_realloc(ctx, buf, len + n + 1);
  75571. } else {
  75572. p = realloc(buf, len + n + 1);
  75573. }
  75574. if (!p) {
  75575. if (ctx) {
  75576. js_free(ctx, buf);
  75577. } else {
  75578. free(buf);
  75579. }
  75580. fclose(f);
  75581. return NULL;
  75582. }
  75583. memcpy(&p[len], tmp, n);
  75584. buf = p;
  75585. len += n;
  75586. buf[len] = '\0';
  75587. } while (n == sizeof(tmp));
  75588. fclose(f);
  75589. *pbuf_len = len;
  75590. return buf;
  75591. }
  75592. /* load and evaluate a file */
  75593. static JSValue js_loadScript(JSContext *ctx, JSValueConst this_val,
  75594. int argc, JSValueConst *argv)
  75595. {
  75596. uint8_t *buf;
  75597. const char *filename;
  75598. JSValue ret;
  75599. size_t buf_len;
  75600. filename = JS_ToCString(ctx, argv[0]);
  75601. if (!filename)
  75602. return JS_EXCEPTION;
  75603. buf = js_load_file(ctx, &buf_len, filename);
  75604. if (!buf) {
  75605. JS_ThrowReferenceError(ctx, "could not load '%s'", filename);
  75606. JS_FreeCString(ctx, filename);
  75607. return JS_EXCEPTION;
  75608. }
  75609. ret = JS_Eval(ctx, (char *)buf, buf_len, filename,
  75610. JS_EVAL_TYPE_GLOBAL);
  75611. js_free(ctx, buf);
  75612. JS_FreeCString(ctx, filename);
  75613. return ret;
  75614. }
  75615. static int get_bool_option(JSContext *ctx, bool *pbool,
  75616. JSValueConst obj,
  75617. const char *option)
  75618. {
  75619. JSValue val;
  75620. val = JS_GetPropertyStr(ctx, obj, option);
  75621. if (JS_IsException(val))
  75622. return -1;
  75623. if (!JS_IsUndefined(val)) {
  75624. *pbool = JS_ToBool(ctx, val);
  75625. }
  75626. JS_FreeValue(ctx, val);
  75627. return 0;
  75628. }
  75629. static void free_buf(JSRuntime *rt, void *opaque, void *ptr) {
  75630. js_free_rt(rt, ptr);
  75631. }
  75632. /* load a file as a UTF-8 encoded string or Uint8Array */
  75633. static JSValue js_std_loadFile(JSContext *ctx, JSValueConst this_val,
  75634. int argc, JSValueConst *argv)
  75635. {
  75636. uint8_t *buf;
  75637. const char *filename;
  75638. JSValueConst options_obj;
  75639. JSValue ret;
  75640. size_t buf_len;
  75641. bool binary = false;
  75642. if (argc >= 2) {
  75643. options_obj = argv[1];
  75644. if (get_bool_option(ctx, &binary, options_obj,
  75645. "binary"))
  75646. return JS_EXCEPTION;
  75647. }
  75648. filename = JS_ToCString(ctx, argv[0]);
  75649. if (!filename)
  75650. return JS_EXCEPTION;
  75651. buf = js_load_file(ctx, &buf_len, filename);
  75652. JS_FreeCString(ctx, filename);
  75653. if (!buf)
  75654. return JS_NULL;
  75655. if (binary) {
  75656. ret = JS_NewUint8Array(ctx, buf, buf_len, free_buf, NULL, false);
  75657. } else {
  75658. ret = JS_NewStringLen(ctx, (char *)buf, buf_len);
  75659. js_free(ctx, buf);
  75660. }
  75661. return ret;
  75662. }
  75663. static JSValue js_std_writeFile(JSContext *ctx, JSValueConst this_val,
  75664. int argc, JSValueConst *argv)
  75665. {
  75666. const char *filename;
  75667. const char *mode;
  75668. const void *buf;
  75669. size_t len, n;
  75670. JSValueConst data;
  75671. JSValue val, ret, unref;
  75672. bool release;
  75673. FILE *fp;
  75674. ret = JS_EXCEPTION;
  75675. len = 0;
  75676. buf = "";
  75677. mode = "w";
  75678. data = argv[1];
  75679. unref = JS_UNDEFINED;
  75680. release = false;
  75681. filename = JS_ToCString(ctx, argv[0]);
  75682. if (!filename)
  75683. return JS_EXCEPTION;
  75684. if (JS_IsObject(data)) {
  75685. val = JS_GetPropertyStr(ctx, data, "buffer");
  75686. if (JS_IsException(val))
  75687. goto exception;
  75688. if (JS_IsArrayBuffer(val)) {
  75689. data = unref = val;
  75690. } else {
  75691. JS_FreeValue(ctx, val);
  75692. }
  75693. }
  75694. if (JS_IsArrayBuffer(data)) {
  75695. buf = JS_GetArrayBuffer(ctx, &len, data);
  75696. mode = "wb";
  75697. } else if (!JS_IsUndefined(data)) {
  75698. buf = JS_ToCStringLen(ctx, &len, data);
  75699. release = true;
  75700. }
  75701. if (!buf)
  75702. goto exception;
  75703. fp = fopen(filename, mode);
  75704. if (!fp) {
  75705. JS_ThrowPlainError(ctx, "error opening %s for writing", filename);
  75706. goto exception;
  75707. }
  75708. n = fwrite(buf, len, 1, fp);
  75709. fclose(fp);
  75710. if (n != 1) {
  75711. JS_ThrowPlainError(ctx, "error writing to %s", filename);
  75712. goto exception;
  75713. }
  75714. ret = JS_UNDEFINED;
  75715. exception:
  75716. JS_FreeCString(ctx, filename);
  75717. if (release)
  75718. JS_FreeCString(ctx, buf);
  75719. JS_FreeValue(ctx, unref);
  75720. return ret;
  75721. }
  75722. typedef JSModuleDef *(JSInitModuleFunc)(JSContext *ctx,
  75723. const char *module_name);
  75724. #if defined(_WIN32)
  75725. static JSModuleDef *js_module_loader_so(JSContext *ctx,
  75726. const char *module_name)
  75727. {
  75728. JSModuleDef *m;
  75729. HINSTANCE hd;
  75730. JSInitModuleFunc *init;
  75731. char *filename = NULL;
  75732. size_t len = strlen(module_name);
  75733. bool is_absolute = len > 2 && ((module_name[0] >= 'A' && module_name[0] <= 'Z') ||
  75734. (module_name[0] >= 'a' && module_name[0] <= 'z')) && module_name[1] == ':';
  75735. bool is_relative = len > 2 && module_name[0] == '.' && (module_name[1] == '/' || module_name[1] == '\\');
  75736. if (is_absolute || is_relative) {
  75737. filename = (char *)module_name;
  75738. } else {
  75739. filename = js_malloc(ctx, len + 2 + 1);
  75740. if (!filename)
  75741. return NULL;
  75742. strcpy(filename, "./");
  75743. strcpy(filename + 2, module_name);
  75744. }
  75745. hd = LoadLibraryA(filename);
  75746. if (filename != module_name)
  75747. js_free(ctx, filename);
  75748. if (hd == NULL) {
  75749. JS_ThrowReferenceError(ctx, "js_load_module '%s' error: %lu",
  75750. module_name, GetLastError());
  75751. goto fail;
  75752. }
  75753. init = (JSInitModuleFunc *)(uintptr_t)GetProcAddress(hd, "js_init_module");
  75754. if (!init) {
  75755. JS_ThrowReferenceError(ctx, "js_init_module '%s' not found: %lu",
  75756. module_name, GetLastError());
  75757. goto fail;
  75758. }
  75759. m = init(ctx, module_name);
  75760. if (!m) {
  75761. JS_ThrowReferenceError(ctx, "js_call_module '%s' initialization error",
  75762. module_name);
  75763. fail:
  75764. if (hd != NULL)
  75765. FreeLibrary(hd);
  75766. return NULL;
  75767. }
  75768. return m;
  75769. }
  75770. #elif defined(__wasi__)
  75771. static JSModuleDef *js_module_loader_so(JSContext *ctx,
  75772. const char *module_name)
  75773. {
  75774. JS_ThrowReferenceError(ctx, "shared library modules are not supported yet");
  75775. return NULL;
  75776. }
  75777. #else
  75778. static JSModuleDef *js_module_loader_so(JSContext *ctx,
  75779. const char *module_name)
  75780. {
  75781. JSModuleDef *m;
  75782. void *hd;
  75783. JSInitModuleFunc *init;
  75784. char *filename;
  75785. if (!strchr(module_name, '/')) {
  75786. /* must add a '/' so that the DLL is not searched in the
  75787. system library paths */
  75788. filename = js_malloc(ctx, strlen(module_name) + 2 + 1);
  75789. if (!filename)
  75790. return NULL;
  75791. strcpy(filename, "./");
  75792. strcpy(filename + 2, module_name);
  75793. } else {
  75794. filename = (char *)module_name;
  75795. }
  75796. /* C module */
  75797. hd = dlopen(filename, RTLD_NOW | RTLD_LOCAL);
  75798. if (filename != module_name)
  75799. js_free(ctx, filename);
  75800. if (!hd) {
  75801. JS_ThrowReferenceError(ctx, "could not load module filename '%s' as shared library: %s",
  75802. module_name, dlerror());
  75803. goto fail;
  75804. }
  75805. *(void **) (&init) = dlsym(hd, "js_init_module");
  75806. if (!init) {
  75807. JS_ThrowReferenceError(ctx, "could not load module filename '%s': js_init_module not found",
  75808. module_name);
  75809. goto fail;
  75810. }
  75811. m = init(ctx, module_name);
  75812. if (!m) {
  75813. JS_ThrowReferenceError(ctx, "could not load module filename '%s': initialization error",
  75814. module_name);
  75815. fail:
  75816. if (hd)
  75817. dlclose(hd);
  75818. return NULL;
  75819. }
  75820. return m;
  75821. }
  75822. #endif /* !_WIN32 */
  75823. int js_module_set_import_meta(JSContext *ctx, JSValueConst func_val,
  75824. bool use_realpath, bool is_main)
  75825. {
  75826. JSModuleDef *m;
  75827. char buf[PATH_MAX + 16];
  75828. JSValue meta_obj;
  75829. JSAtom module_name_atom;
  75830. const char *module_name;
  75831. assert(JS_VALUE_GET_TAG(func_val) == JS_TAG_MODULE);
  75832. m = JS_VALUE_GET_PTR(func_val);
  75833. module_name_atom = JS_GetModuleName(ctx, m);
  75834. module_name = JS_AtomToCString(ctx, module_name_atom);
  75835. JS_FreeAtom(ctx, module_name_atom);
  75836. if (!module_name)
  75837. return -1;
  75838. if (!strchr(module_name, ':')) {
  75839. strcpy(buf, "file://");
  75840. #if !defined(_WIN32) && !defined(__wasi__)
  75841. /* realpath() cannot be used with modules compiled with qjsc
  75842. because the corresponding module source code is not
  75843. necessarily present */
  75844. if (use_realpath) {
  75845. char *res = realpath(module_name, buf + strlen(buf));
  75846. if (!res) {
  75847. JS_ThrowTypeError(ctx, "realpath failure");
  75848. JS_FreeCString(ctx, module_name);
  75849. return -1;
  75850. }
  75851. } else
  75852. #endif
  75853. {
  75854. js__pstrcat(buf, sizeof(buf), module_name);
  75855. }
  75856. } else {
  75857. js__pstrcpy(buf, sizeof(buf), module_name);
  75858. }
  75859. JS_FreeCString(ctx, module_name);
  75860. meta_obj = JS_GetImportMeta(ctx, m);
  75861. if (JS_IsException(meta_obj))
  75862. return -1;
  75863. JS_DefinePropertyValueStr(ctx, meta_obj, "url",
  75864. JS_NewString(ctx, buf),
  75865. JS_PROP_C_W_E);
  75866. JS_DefinePropertyValueStr(ctx, meta_obj, "main",
  75867. JS_NewBool(ctx, is_main),
  75868. JS_PROP_C_W_E);
  75869. JS_FreeValue(ctx, meta_obj);
  75870. return 0;
  75871. }
  75872. JSModuleDef *js_module_loader(JSContext *ctx,
  75873. const char *module_name, void *opaque)
  75874. {
  75875. JSModuleDef *m;
  75876. if (js__has_suffix(module_name, QJS_NATIVE_MODULE_SUFFIX)) {
  75877. m = js_module_loader_so(ctx, module_name);
  75878. } else {
  75879. size_t buf_len;
  75880. uint8_t *buf;
  75881. JSValue func_val;
  75882. buf = js_load_file(ctx, &buf_len, module_name);
  75883. if (!buf) {
  75884. JS_ThrowReferenceError(ctx, "could not load module filename '%s'",
  75885. module_name);
  75886. return NULL;
  75887. }
  75888. /* compile the module */
  75889. func_val = JS_Eval(ctx, (char *)buf, buf_len, module_name,
  75890. JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);
  75891. js_free(ctx, buf);
  75892. if (JS_IsException(func_val))
  75893. return NULL;
  75894. if (js_module_set_import_meta(ctx, func_val, true, false) < 0) {
  75895. JS_FreeValue(ctx, func_val);
  75896. return NULL;
  75897. }
  75898. /* the module is already referenced, so we must free it */
  75899. m = JS_VALUE_GET_PTR(func_val);
  75900. JS_FreeValue(ctx, func_val);
  75901. }
  75902. return m;
  75903. }
  75904. static JSValue js_std_exit(JSContext *ctx, JSValueConst this_val,
  75905. int argc, JSValueConst *argv)
  75906. {
  75907. int status;
  75908. if (JS_ToInt32(ctx, &status, argv[0]))
  75909. status = -1;
  75910. exit(status);
  75911. return JS_UNDEFINED;
  75912. }
  75913. static JSValue js_std_getenv(JSContext *ctx, JSValueConst this_val,
  75914. int argc, JSValueConst *argv)
  75915. {
  75916. const char *name, *str;
  75917. name = JS_ToCString(ctx, argv[0]);
  75918. if (!name)
  75919. return JS_EXCEPTION;
  75920. str = getenv(name);
  75921. JS_FreeCString(ctx, name);
  75922. if (!str)
  75923. return JS_UNDEFINED;
  75924. else
  75925. return JS_NewString(ctx, str);
  75926. }
  75927. #if defined(_WIN32)
  75928. static void setenv(const char *name, const char *value, int overwrite)
  75929. {
  75930. char *str;
  75931. size_t name_len, value_len;
  75932. name_len = strlen(name);
  75933. value_len = strlen(value);
  75934. str = malloc(name_len + 1 + value_len + 1);
  75935. memcpy(str, name, name_len);
  75936. str[name_len] = '=';
  75937. memcpy(str + name_len + 1, value, value_len);
  75938. str[name_len + 1 + value_len] = '\0';
  75939. _putenv(str);
  75940. free(str);
  75941. }
  75942. static void unsetenv(const char *name)
  75943. {
  75944. setenv(name, "", true);
  75945. }
  75946. #endif /* _WIN32 */
  75947. static JSValue js_std_setenv(JSContext *ctx, JSValueConst this_val,
  75948. int argc, JSValueConst *argv)
  75949. {
  75950. const char *name, *value;
  75951. name = JS_ToCString(ctx, argv[0]);
  75952. if (!name)
  75953. return JS_EXCEPTION;
  75954. value = JS_ToCString(ctx, argv[1]);
  75955. if (!value) {
  75956. JS_FreeCString(ctx, name);
  75957. return JS_EXCEPTION;
  75958. }
  75959. setenv(name, value, true);
  75960. JS_FreeCString(ctx, name);
  75961. JS_FreeCString(ctx, value);
  75962. return JS_UNDEFINED;
  75963. }
  75964. static JSValue js_std_unsetenv(JSContext *ctx, JSValueConst this_val,
  75965. int argc, JSValueConst *argv)
  75966. {
  75967. const char *name;
  75968. name = JS_ToCString(ctx, argv[0]);
  75969. if (!name)
  75970. return JS_EXCEPTION;
  75971. unsetenv(name);
  75972. JS_FreeCString(ctx, name);
  75973. return JS_UNDEFINED;
  75974. }
  75975. /* return an object containing the list of the available environment
  75976. variables. */
  75977. static JSValue js_std_getenviron(JSContext *ctx, JSValueConst this_val,
  75978. int argc, JSValueConst *argv)
  75979. {
  75980. char **envp;
  75981. const char *name, *p, *value;
  75982. JSValue obj;
  75983. uint32_t idx;
  75984. size_t name_len;
  75985. JSAtom atom;
  75986. int ret;
  75987. obj = JS_NewObject(ctx);
  75988. if (JS_IsException(obj))
  75989. return JS_EXCEPTION;
  75990. envp = environ;
  75991. for(idx = 0; envp[idx] != NULL; idx++) {
  75992. name = envp[idx];
  75993. p = strchr(name, '=');
  75994. name_len = p - name;
  75995. if (!p)
  75996. continue;
  75997. value = p + 1;
  75998. atom = JS_NewAtomLen(ctx, name, name_len);
  75999. if (atom == JS_ATOM_NULL)
  76000. goto fail;
  76001. ret = JS_DefinePropertyValue(ctx, obj, atom, JS_NewString(ctx, value),
  76002. JS_PROP_C_W_E);
  76003. JS_FreeAtom(ctx, atom);
  76004. if (ret < 0)
  76005. goto fail;
  76006. }
  76007. return obj;
  76008. fail:
  76009. JS_FreeValue(ctx, obj);
  76010. return JS_EXCEPTION;
  76011. }
  76012. static JSValue js_std_gc(JSContext *ctx, JSValueConst this_val,
  76013. int argc, JSValueConst *argv)
  76014. {
  76015. JS_RunGC(JS_GetRuntime(ctx));
  76016. return JS_UNDEFINED;
  76017. }
  76018. static int interrupt_handler(JSRuntime *rt, void *opaque)
  76019. {
  76020. return (os_pending_signals >> SIGINT) & 1;
  76021. }
  76022. static JSValue js_evalScript(JSContext *ctx, JSValueConst this_val,
  76023. int argc, JSValueConst *argv)
  76024. {
  76025. JSRuntime *rt = JS_GetRuntime(ctx);
  76026. JSThreadState *ts = js_get_thread_state(rt);
  76027. const char *str = NULL;
  76028. size_t len;
  76029. JSValue ret, obj;
  76030. JSValueConst options_obj, arg;
  76031. bool backtrace_barrier = false;
  76032. bool eval_function = false;
  76033. bool eval_module = false;
  76034. bool compile_only = false;
  76035. bool compile_module = false;
  76036. bool is_async = false;
  76037. int flags;
  76038. if (argc >= 2) {
  76039. options_obj = argv[1];
  76040. if (get_bool_option(ctx, &backtrace_barrier, options_obj,
  76041. "backtrace_barrier"))
  76042. return JS_EXCEPTION;
  76043. if (get_bool_option(ctx, &eval_function, options_obj,
  76044. "eval_function"))
  76045. return JS_EXCEPTION;
  76046. if (get_bool_option(ctx, &eval_module, options_obj,
  76047. "eval_module"))
  76048. return JS_EXCEPTION;
  76049. if (get_bool_option(ctx, &compile_only, options_obj,
  76050. "compile_only"))
  76051. return JS_EXCEPTION;
  76052. if (get_bool_option(ctx, &compile_module, options_obj,
  76053. "compile_module"))
  76054. return JS_EXCEPTION;
  76055. if (get_bool_option(ctx, &is_async, options_obj,
  76056. "async"))
  76057. return JS_EXCEPTION;
  76058. }
  76059. if (eval_module) {
  76060. arg = argv[0];
  76061. if (JS_VALUE_GET_TAG(arg) != JS_TAG_MODULE)
  76062. return JS_ThrowTypeError(ctx, "not a module");
  76063. if (JS_ResolveModule(ctx, arg) < 0)
  76064. return JS_EXCEPTION;
  76065. if (js_module_set_import_meta(ctx, arg, false, false) < 0)
  76066. return JS_EXCEPTION;
  76067. return JS_EvalFunction(ctx, JS_DupValue(ctx, arg));
  76068. }
  76069. if (!eval_function) {
  76070. str = JS_ToCStringLen(ctx, &len, argv[0]);
  76071. if (!str)
  76072. return JS_EXCEPTION;
  76073. }
  76074. if (!ts->recv_pipe && ++ts->eval_script_recurse == 1) {
  76075. /* install the interrupt handler */
  76076. JS_SetInterruptHandler(JS_GetRuntime(ctx), interrupt_handler, NULL);
  76077. }
  76078. flags = compile_module ? JS_EVAL_TYPE_MODULE : JS_EVAL_TYPE_GLOBAL;
  76079. if (backtrace_barrier)
  76080. flags |= JS_EVAL_FLAG_BACKTRACE_BARRIER;
  76081. if (compile_only)
  76082. flags |= JS_EVAL_FLAG_COMPILE_ONLY;
  76083. if (is_async)
  76084. flags |= JS_EVAL_FLAG_ASYNC;
  76085. if (eval_function) {
  76086. obj = JS_DupValue(ctx, argv[0]);
  76087. ret = JS_EvalFunction(ctx, obj); // takes ownership of |obj|
  76088. } else {
  76089. ret = JS_Eval(ctx, str, len, "<evalScript>", flags);
  76090. }
  76091. JS_FreeCString(ctx, str);
  76092. if (!ts->recv_pipe && --ts->eval_script_recurse == 0) {
  76093. /* remove the interrupt handler */
  76094. JS_SetInterruptHandler(JS_GetRuntime(ctx), NULL, NULL);
  76095. os_pending_signals &= ~((uint64_t)1 << SIGINT);
  76096. /* convert the uncatchable "interrupted" error into a normal error
  76097. so that it can be caught by the REPL */
  76098. if (JS_IsException(ret))
  76099. JS_ResetUncatchableError(ctx);
  76100. }
  76101. return ret;
  76102. }
  76103. typedef struct {
  76104. FILE *f;
  76105. bool is_popen;
  76106. } JSSTDFile;
  76107. static bool is_stdio(FILE *f)
  76108. {
  76109. return f == stdin || f == stdout || f == stderr;
  76110. }
  76111. static void js_std_file_finalizer(JSRuntime *rt, JSValueConst val)
  76112. {
  76113. JSThreadState *ts = js_get_thread_state(rt);
  76114. JSSTDFile *s = JS_GetOpaque(val, ts->std_file_class_id);
  76115. if (s) {
  76116. if (s->f && !is_stdio(s->f)) {
  76117. #if !defined(__wasi__)
  76118. if (s->is_popen)
  76119. pclose(s->f);
  76120. else
  76121. #endif
  76122. fclose(s->f);
  76123. }
  76124. js_free_rt(rt, s);
  76125. }
  76126. }
  76127. static ssize_t js_get_errno(ssize_t ret)
  76128. {
  76129. if (ret == -1)
  76130. ret = -errno;
  76131. return ret;
  76132. }
  76133. static JSValue js_std_strerror(JSContext *ctx, JSValueConst this_val,
  76134. int argc, JSValueConst *argv)
  76135. {
  76136. int err;
  76137. if (JS_ToInt32(ctx, &err, argv[0]))
  76138. return JS_EXCEPTION;
  76139. return JS_NewString(ctx, strerror(err));
  76140. }
  76141. static JSValue js_new_std_file(JSContext *ctx, FILE *f, bool is_popen)
  76142. {
  76143. JSRuntime *rt = JS_GetRuntime(ctx);
  76144. JSThreadState *ts = js_get_thread_state(rt);
  76145. JSSTDFile *s;
  76146. JSValue obj;
  76147. obj = JS_NewObjectClass(ctx, ts->std_file_class_id);
  76148. if (JS_IsException(obj))
  76149. return obj;
  76150. s = js_mallocz(ctx, sizeof(*s));
  76151. if (!s) {
  76152. JS_FreeValue(ctx, obj);
  76153. return JS_EXCEPTION;
  76154. }
  76155. s->is_popen = is_popen;
  76156. s->f = f;
  76157. JS_SetOpaque(obj, s);
  76158. return obj;
  76159. }
  76160. static void js_set_error_object(JSContext *ctx, JSValueConst obj, int err)
  76161. {
  76162. if (!JS_IsUndefined(obj)) {
  76163. JS_SetPropertyStr(ctx, obj, "errno", JS_NewInt32(ctx, err));
  76164. }
  76165. }
  76166. static JSValue js_std_open(JSContext *ctx, JSValueConst this_val,
  76167. int argc, JSValueConst *argv)
  76168. {
  76169. const char *filename, *mode = NULL;
  76170. FILE *f;
  76171. int err;
  76172. filename = JS_ToCString(ctx, argv[0]);
  76173. if (!filename)
  76174. goto fail;
  76175. mode = JS_ToCString(ctx, argv[1]);
  76176. if (!mode)
  76177. goto fail;
  76178. if (mode[strspn(mode, "rwa+bx")] != '\0') {
  76179. JS_ThrowTypeError(ctx, "invalid file mode");
  76180. goto fail;
  76181. }
  76182. f = fopen(filename, mode);
  76183. if (!f)
  76184. err = errno;
  76185. else
  76186. err = 0;
  76187. if (argc >= 3)
  76188. js_set_error_object(ctx, argv[2], err);
  76189. JS_FreeCString(ctx, filename);
  76190. JS_FreeCString(ctx, mode);
  76191. if (!f)
  76192. return JS_NULL;
  76193. return js_new_std_file(ctx, f, false);
  76194. fail:
  76195. JS_FreeCString(ctx, filename);
  76196. JS_FreeCString(ctx, mode);
  76197. return JS_EXCEPTION;
  76198. }
  76199. #if !defined(__wasi__)
  76200. static JSValue js_std_popen(JSContext *ctx, JSValueConst this_val,
  76201. int argc, JSValueConst *argv)
  76202. {
  76203. const char *filename, *mode = NULL;
  76204. FILE *f;
  76205. int err;
  76206. filename = JS_ToCString(ctx, argv[0]);
  76207. if (!filename)
  76208. goto fail;
  76209. mode = JS_ToCString(ctx, argv[1]);
  76210. if (!mode)
  76211. goto fail;
  76212. if (mode[strspn(mode, "rw")] != '\0') {
  76213. JS_ThrowTypeError(ctx, "invalid file mode");
  76214. goto fail;
  76215. }
  76216. f = popen(filename, mode);
  76217. if (!f)
  76218. err = errno;
  76219. else
  76220. err = 0;
  76221. if (argc >= 3)
  76222. js_set_error_object(ctx, argv[2], err);
  76223. JS_FreeCString(ctx, filename);
  76224. JS_FreeCString(ctx, mode);
  76225. if (!f)
  76226. return JS_NULL;
  76227. return js_new_std_file(ctx, f, true);
  76228. fail:
  76229. JS_FreeCString(ctx, filename);
  76230. JS_FreeCString(ctx, mode);
  76231. return JS_EXCEPTION;
  76232. }
  76233. #endif // !defined(__wasi__)
  76234. static JSValue js_std_fdopen(JSContext *ctx, JSValueConst this_val,
  76235. int argc, JSValueConst *argv)
  76236. {
  76237. const char *mode;
  76238. FILE *f;
  76239. int fd, err;
  76240. if (JS_ToInt32(ctx, &fd, argv[0]))
  76241. return JS_EXCEPTION;
  76242. mode = JS_ToCString(ctx, argv[1]);
  76243. if (!mode)
  76244. goto fail;
  76245. if (mode[strspn(mode, "rwa+")] != '\0') {
  76246. JS_ThrowTypeError(ctx, "invalid file mode");
  76247. goto fail;
  76248. }
  76249. f = fdopen(fd, mode);
  76250. if (!f)
  76251. err = errno;
  76252. else
  76253. err = 0;
  76254. if (argc >= 3)
  76255. js_set_error_object(ctx, argv[2], err);
  76256. JS_FreeCString(ctx, mode);
  76257. if (!f)
  76258. return JS_NULL;
  76259. return js_new_std_file(ctx, f, false);
  76260. fail:
  76261. JS_FreeCString(ctx, mode);
  76262. return JS_EXCEPTION;
  76263. }
  76264. #if !defined(__wasi__)
  76265. static JSValue js_std_tmpfile(JSContext *ctx, JSValueConst this_val,
  76266. int argc, JSValueConst *argv)
  76267. {
  76268. FILE *f;
  76269. f = tmpfile();
  76270. if (argc >= 1)
  76271. js_set_error_object(ctx, argv[0], f ? 0 : errno);
  76272. if (!f)
  76273. return JS_NULL;
  76274. return js_new_std_file(ctx, f, false);
  76275. }
  76276. #endif
  76277. static JSValue js_std_sprintf(JSContext *ctx, JSValueConst this_val,
  76278. int argc, JSValueConst *argv)
  76279. {
  76280. return js_printf_internal(ctx, argc, argv, NULL);
  76281. }
  76282. static JSValue js_std_printf(JSContext *ctx, JSValueConst this_val,
  76283. int argc, JSValueConst *argv)
  76284. {
  76285. return js_printf_internal(ctx, argc, argv, stdout);
  76286. }
  76287. static FILE *js_std_file_get(JSContext *ctx, JSValueConst obj)
  76288. {
  76289. JSRuntime *rt = JS_GetRuntime(ctx);
  76290. JSThreadState *ts = js_get_thread_state(rt);
  76291. JSSTDFile *s = JS_GetOpaque2(ctx, obj, ts->std_file_class_id);
  76292. if (!s)
  76293. return NULL;
  76294. if (!s->f) {
  76295. JS_ThrowTypeError(ctx, "invalid file handle");
  76296. return NULL;
  76297. }
  76298. return s->f;
  76299. }
  76300. static JSValue js_std_file_puts(JSContext *ctx, JSValueConst this_val,
  76301. int argc, JSValueConst *argv, int magic)
  76302. {
  76303. FILE *f;
  76304. int i;
  76305. const char *str;
  76306. size_t len;
  76307. if (magic == 0) {
  76308. f = stdout;
  76309. } else {
  76310. f = js_std_file_get(ctx, this_val);
  76311. if (!f)
  76312. return JS_EXCEPTION;
  76313. }
  76314. for(i = 0; i < argc; i++) {
  76315. str = JS_ToCStringLen(ctx, &len, argv[i]);
  76316. if (!str)
  76317. return JS_EXCEPTION;
  76318. fwrite(str, 1, len, f);
  76319. JS_FreeCString(ctx, str);
  76320. }
  76321. return JS_UNDEFINED;
  76322. }
  76323. static JSValue js_std_file_close(JSContext *ctx, JSValueConst this_val,
  76324. int argc, JSValueConst *argv)
  76325. {
  76326. JSRuntime *rt = JS_GetRuntime(ctx);
  76327. JSThreadState *ts = js_get_thread_state(rt);
  76328. JSSTDFile *s = JS_GetOpaque2(ctx, this_val, ts->std_file_class_id);
  76329. int err;
  76330. if (!s)
  76331. return JS_EXCEPTION;
  76332. if (!s->f)
  76333. return JS_ThrowTypeError(ctx, "invalid file handle");
  76334. if (is_stdio(s->f))
  76335. return JS_ThrowTypeError(ctx, "cannot close stdio");
  76336. #if !defined(__wasi__)
  76337. if (s->is_popen)
  76338. err = js_get_errno(pclose(s->f));
  76339. else
  76340. #endif
  76341. err = js_get_errno(fclose(s->f));
  76342. s->f = NULL;
  76343. return JS_NewInt32(ctx, err);
  76344. }
  76345. static JSValue js_std_file_printf(JSContext *ctx, JSValueConst this_val,
  76346. int argc, JSValueConst *argv)
  76347. {
  76348. FILE *f = js_std_file_get(ctx, this_val);
  76349. if (!f)
  76350. return JS_EXCEPTION;
  76351. return js_printf_internal(ctx, argc, argv, f);
  76352. }
  76353. static JSValue js_std_file_flush(JSContext *ctx, JSValueConst this_val,
  76354. int argc, JSValueConst *argv)
  76355. {
  76356. FILE *f = js_std_file_get(ctx, this_val);
  76357. if (!f)
  76358. return JS_EXCEPTION;
  76359. fflush(f);
  76360. return JS_UNDEFINED;
  76361. }
  76362. static JSValue js_std_file_tell(JSContext *ctx, JSValueConst this_val,
  76363. int argc, JSValueConst *argv, int is_bigint)
  76364. {
  76365. FILE *f = js_std_file_get(ctx, this_val);
  76366. int64_t pos;
  76367. if (!f)
  76368. return JS_EXCEPTION;
  76369. #if defined(__linux__)
  76370. pos = ftello(f);
  76371. #else
  76372. pos = ftell(f);
  76373. #endif
  76374. if (is_bigint)
  76375. return JS_NewBigInt64(ctx, pos);
  76376. else
  76377. return JS_NewInt64(ctx, pos);
  76378. }
  76379. static JSValue js_std_file_seek(JSContext *ctx, JSValueConst this_val,
  76380. int argc, JSValueConst *argv)
  76381. {
  76382. FILE *f = js_std_file_get(ctx, this_val);
  76383. int64_t pos;
  76384. int whence, ret;
  76385. if (!f)
  76386. return JS_EXCEPTION;
  76387. if (JS_ToInt64Ext(ctx, &pos, argv[0]))
  76388. return JS_EXCEPTION;
  76389. if (JS_ToInt32(ctx, &whence, argv[1]))
  76390. return JS_EXCEPTION;
  76391. #if defined(__linux__)
  76392. ret = fseeko(f, pos, whence);
  76393. #else
  76394. ret = fseek(f, pos, whence);
  76395. #endif
  76396. if (ret < 0)
  76397. ret = -errno;
  76398. return JS_NewInt32(ctx, ret);
  76399. }
  76400. static JSValue js_std_file_eof(JSContext *ctx, JSValueConst this_val,
  76401. int argc, JSValueConst *argv)
  76402. {
  76403. FILE *f = js_std_file_get(ctx, this_val);
  76404. if (!f)
  76405. return JS_EXCEPTION;
  76406. return JS_NewBool(ctx, feof(f));
  76407. }
  76408. static JSValue js_std_file_error(JSContext *ctx, JSValueConst this_val,
  76409. int argc, JSValueConst *argv)
  76410. {
  76411. FILE *f = js_std_file_get(ctx, this_val);
  76412. if (!f)
  76413. return JS_EXCEPTION;
  76414. return JS_NewBool(ctx, ferror(f));
  76415. }
  76416. static JSValue js_std_file_clearerr(JSContext *ctx, JSValueConst this_val,
  76417. int argc, JSValueConst *argv)
  76418. {
  76419. FILE *f = js_std_file_get(ctx, this_val);
  76420. if (!f)
  76421. return JS_EXCEPTION;
  76422. clearerr(f);
  76423. return JS_UNDEFINED;
  76424. }
  76425. static JSValue js_std_file_fileno(JSContext *ctx, JSValueConst this_val,
  76426. int argc, JSValueConst *argv)
  76427. {
  76428. FILE *f = js_std_file_get(ctx, this_val);
  76429. if (!f)
  76430. return JS_EXCEPTION;
  76431. return JS_NewInt32(ctx, fileno(f));
  76432. }
  76433. static JSValue js_std_file_read_write(JSContext *ctx, JSValueConst this_val,
  76434. int argc, JSValueConst *argv, int magic)
  76435. {
  76436. FILE *f = js_std_file_get(ctx, this_val);
  76437. uint64_t pos, len;
  76438. size_t size, ret;
  76439. uint8_t *buf;
  76440. if (!f)
  76441. return JS_EXCEPTION;
  76442. if (JS_ToIndex(ctx, &pos, argv[1]))
  76443. return JS_EXCEPTION;
  76444. if (JS_ToIndex(ctx, &len, argv[2]))
  76445. return JS_EXCEPTION;
  76446. buf = JS_GetArrayBuffer(ctx, &size, argv[0]);
  76447. if (!buf)
  76448. return JS_EXCEPTION;
  76449. if (pos + len > size)
  76450. return JS_ThrowRangeError(ctx, "read/write array buffer overflow");
  76451. if (magic)
  76452. ret = fwrite(buf + pos, 1, len, f);
  76453. else
  76454. ret = fread(buf + pos, 1, len, f);
  76455. return JS_NewInt64(ctx, ret);
  76456. }
  76457. /* XXX: could use less memory and go faster */
  76458. static JSValue js_std_file_getline(JSContext *ctx, JSValueConst this_val,
  76459. int argc, JSValueConst *argv)
  76460. {
  76461. FILE *f = js_std_file_get(ctx, this_val);
  76462. int c;
  76463. DynBuf dbuf;
  76464. JSValue obj;
  76465. if (!f)
  76466. return JS_EXCEPTION;
  76467. js_std_dbuf_init(ctx, &dbuf);
  76468. for(;;) {
  76469. c = fgetc(f);
  76470. if (c == EOF) {
  76471. if (dbuf.size == 0) {
  76472. /* EOF */
  76473. dbuf_free(&dbuf);
  76474. return JS_NULL;
  76475. } else {
  76476. break;
  76477. }
  76478. }
  76479. if (c == '\n')
  76480. break;
  76481. if (dbuf_putc(&dbuf, c)) {
  76482. dbuf_free(&dbuf);
  76483. return JS_ThrowOutOfMemory(ctx);
  76484. }
  76485. }
  76486. obj = JS_NewStringLen(ctx, (const char *)dbuf.buf, dbuf.size);
  76487. dbuf_free(&dbuf);
  76488. return obj;
  76489. }
  76490. /* XXX: could use less memory and go faster */
  76491. static JSValue js_std_file_readAs(JSContext *ctx, JSValueConst this_val,
  76492. int argc, JSValueConst *argv, int magic)
  76493. {
  76494. FILE *f = js_std_file_get(ctx, this_val);
  76495. int c;
  76496. DynBuf dbuf;
  76497. JSValue obj;
  76498. uint64_t max_size64;
  76499. size_t max_size;
  76500. JSValueConst max_size_val;
  76501. if (!f)
  76502. return JS_EXCEPTION;
  76503. if (argc >= 1)
  76504. max_size_val = argv[0];
  76505. else
  76506. max_size_val = JS_UNDEFINED;
  76507. max_size = (size_t)-1;
  76508. if (!JS_IsUndefined(max_size_val)) {
  76509. if (JS_ToIndex(ctx, &max_size64, max_size_val))
  76510. return JS_EXCEPTION;
  76511. if (max_size64 < max_size)
  76512. max_size = max_size64;
  76513. }
  76514. js_std_dbuf_init(ctx, &dbuf);
  76515. while (max_size != 0) {
  76516. c = fgetc(f);
  76517. if (c == EOF)
  76518. break;
  76519. if (dbuf_putc(&dbuf, c)) {
  76520. dbuf_free(&dbuf);
  76521. return JS_EXCEPTION;
  76522. }
  76523. max_size--;
  76524. }
  76525. if (magic) {
  76526. obj = JS_NewStringLen(ctx, (const char *)dbuf.buf, dbuf.size);
  76527. } else {
  76528. obj = JS_NewArrayBufferCopy(ctx, dbuf.buf, dbuf.size);
  76529. }
  76530. dbuf_free(&dbuf);
  76531. return obj;
  76532. }
  76533. static JSValue js_std_file_getByte(JSContext *ctx, JSValueConst this_val,
  76534. int argc, JSValueConst *argv)
  76535. {
  76536. FILE *f = js_std_file_get(ctx, this_val);
  76537. if (!f)
  76538. return JS_EXCEPTION;
  76539. return JS_NewInt32(ctx, fgetc(f));
  76540. }
  76541. static JSValue js_std_file_putByte(JSContext *ctx, JSValueConst this_val,
  76542. int argc, JSValueConst *argv)
  76543. {
  76544. FILE *f = js_std_file_get(ctx, this_val);
  76545. int c;
  76546. if (!f)
  76547. return JS_EXCEPTION;
  76548. if (JS_ToInt32(ctx, &c, argv[0]))
  76549. return JS_EXCEPTION;
  76550. c = fputc(c, f);
  76551. return JS_NewInt32(ctx, c);
  76552. }
  76553. /* urlGet */
  76554. #if !defined(__wasi__)
  76555. #define URL_GET_PROGRAM "curl -s -i --"
  76556. #define URL_GET_BUF_SIZE 4096
  76557. static int http_get_header_line(FILE *f, char *buf, size_t buf_size,
  76558. DynBuf *dbuf)
  76559. {
  76560. int c;
  76561. char *p;
  76562. p = buf;
  76563. for(;;) {
  76564. c = fgetc(f);
  76565. if (c < 0)
  76566. return -1;
  76567. if ((p - buf) < buf_size - 1)
  76568. *p++ = c;
  76569. if (dbuf)
  76570. dbuf_putc(dbuf, c);
  76571. if (c == '\n')
  76572. break;
  76573. }
  76574. *p = '\0';
  76575. return 0;
  76576. }
  76577. static int http_get_status(const char *buf)
  76578. {
  76579. const char *p = buf;
  76580. while (*p != ' ' && *p != '\0')
  76581. p++;
  76582. if (*p != ' ')
  76583. return 0;
  76584. while (*p == ' ')
  76585. p++;
  76586. return atoi(p);
  76587. }
  76588. static JSValue js_std_urlGet(JSContext *ctx, JSValueConst this_val,
  76589. int argc, JSValueConst *argv)
  76590. {
  76591. const char *url;
  76592. DynBuf cmd_buf;
  76593. DynBuf data_buf_s, *data_buf = &data_buf_s;
  76594. DynBuf header_buf_s, *header_buf = &header_buf_s;
  76595. char *buf;
  76596. size_t i, len;
  76597. int status;
  76598. JSValue response = JS_UNDEFINED, ret_obj;
  76599. JSValueConst options_obj;
  76600. FILE *f;
  76601. bool binary_flag, full_flag;
  76602. url = JS_ToCString(ctx, argv[0]);
  76603. if (!url)
  76604. return JS_EXCEPTION;
  76605. binary_flag = false;
  76606. full_flag = false;
  76607. if (argc >= 2) {
  76608. options_obj = argv[1];
  76609. if (get_bool_option(ctx, &binary_flag, options_obj, "binary"))
  76610. goto fail_obj;
  76611. if (get_bool_option(ctx, &full_flag, options_obj, "full")) {
  76612. fail_obj:
  76613. JS_FreeCString(ctx, url);
  76614. return JS_EXCEPTION;
  76615. }
  76616. }
  76617. js_std_dbuf_init(ctx, &cmd_buf);
  76618. dbuf_printf(&cmd_buf, "%s '", URL_GET_PROGRAM);
  76619. for(i = 0; url[i] != '\0'; i++) {
  76620. unsigned char c = url[i];
  76621. switch (c) {
  76622. case '\'':
  76623. /* shell single quoted string does not support \' */
  76624. dbuf_putstr(&cmd_buf, "'\\''");
  76625. break;
  76626. case '[': case ']': case '{': case '}': case '\\':
  76627. /* prevent interpretation by curl as range or set specification */
  76628. dbuf_putc(&cmd_buf, '\\');
  76629. /* FALLTHROUGH */
  76630. default:
  76631. dbuf_putc(&cmd_buf, c);
  76632. break;
  76633. }
  76634. }
  76635. JS_FreeCString(ctx, url);
  76636. dbuf_putstr(&cmd_buf, "'");
  76637. dbuf_putc(&cmd_buf, '\0');
  76638. if (dbuf_error(&cmd_buf)) {
  76639. dbuf_free(&cmd_buf);
  76640. return JS_EXCEPTION;
  76641. }
  76642. // printf("%s\n", (char *)cmd_buf.buf);
  76643. f = popen((char *)cmd_buf.buf, "r");
  76644. dbuf_free(&cmd_buf);
  76645. if (!f) {
  76646. return JS_ThrowTypeError(ctx, "could not start curl");
  76647. }
  76648. js_std_dbuf_init(ctx, data_buf);
  76649. js_std_dbuf_init(ctx, header_buf);
  76650. buf = js_malloc(ctx, URL_GET_BUF_SIZE);
  76651. if (!buf)
  76652. goto fail;
  76653. /* get the HTTP status */
  76654. if (http_get_header_line(f, buf, URL_GET_BUF_SIZE, NULL) < 0) {
  76655. status = 0;
  76656. goto bad_header;
  76657. }
  76658. status = http_get_status(buf);
  76659. if (!full_flag && !(status >= 200 && status <= 299)) {
  76660. goto bad_header;
  76661. }
  76662. /* wait until there is an empty line */
  76663. for(;;) {
  76664. if (http_get_header_line(f, buf, URL_GET_BUF_SIZE, header_buf) < 0) {
  76665. bad_header:
  76666. response = JS_NULL;
  76667. goto done;
  76668. }
  76669. if (!strcmp(buf, "\r\n"))
  76670. break;
  76671. }
  76672. if (dbuf_error(header_buf))
  76673. goto fail;
  76674. header_buf->size -= 2; /* remove the trailing CRLF */
  76675. /* download the data */
  76676. for(;;) {
  76677. len = fread(buf, 1, URL_GET_BUF_SIZE, f);
  76678. if (len == 0)
  76679. break;
  76680. dbuf_put(data_buf, (uint8_t *)buf, len);
  76681. }
  76682. if (dbuf_error(data_buf))
  76683. goto fail;
  76684. if (binary_flag) {
  76685. response = JS_NewArrayBufferCopy(ctx,
  76686. data_buf->buf, data_buf->size);
  76687. } else {
  76688. response = JS_NewStringLen(ctx, (char *)data_buf->buf, data_buf->size);
  76689. }
  76690. if (JS_IsException(response))
  76691. goto fail;
  76692. done:
  76693. js_free(ctx, buf);
  76694. buf = NULL;
  76695. pclose(f);
  76696. f = NULL;
  76697. dbuf_free(data_buf);
  76698. data_buf = NULL;
  76699. if (full_flag) {
  76700. ret_obj = JS_NewObject(ctx);
  76701. if (JS_IsException(ret_obj))
  76702. goto fail;
  76703. JS_DefinePropertyValueStr(ctx, ret_obj, "response",
  76704. response,
  76705. JS_PROP_C_W_E);
  76706. if (!JS_IsNull(response)) {
  76707. JS_DefinePropertyValueStr(ctx, ret_obj, "responseHeaders",
  76708. JS_NewStringLen(ctx, (char *)header_buf->buf,
  76709. header_buf->size),
  76710. JS_PROP_C_W_E);
  76711. JS_DefinePropertyValueStr(ctx, ret_obj, "status",
  76712. JS_NewInt32(ctx, status),
  76713. JS_PROP_C_W_E);
  76714. }
  76715. } else {
  76716. ret_obj = response;
  76717. }
  76718. dbuf_free(header_buf);
  76719. return ret_obj;
  76720. fail:
  76721. if (f)
  76722. pclose(f);
  76723. js_free(ctx, buf);
  76724. if (data_buf)
  76725. dbuf_free(data_buf);
  76726. if (header_buf)
  76727. dbuf_free(header_buf);
  76728. JS_FreeValue(ctx, response);
  76729. return JS_EXCEPTION;
  76730. }
  76731. #endif // !defined(__wasi__)
  76732. static JSClassDef js_std_file_class = {
  76733. "FILE",
  76734. .finalizer = js_std_file_finalizer,
  76735. };
  76736. static const JSCFunctionListEntry js_std_error_props[] = {
  76737. /* various errno values */
  76738. #define DEF(x) JS_PROP_INT32_DEF(#x, x, JS_PROP_CONFIGURABLE )
  76739. DEF(EINVAL),
  76740. DEF(EIO),
  76741. DEF(EACCES),
  76742. DEF(EEXIST),
  76743. DEF(ENOSPC),
  76744. DEF(ENOSYS),
  76745. DEF(EBUSY),
  76746. DEF(ENOENT),
  76747. DEF(EPERM),
  76748. DEF(EPIPE),
  76749. DEF(EBADF),
  76750. #undef DEF
  76751. };
  76752. static const JSCFunctionListEntry js_std_funcs[] = {
  76753. JS_CFUNC_DEF("exit", 1, js_std_exit ),
  76754. JS_CFUNC_DEF("gc", 0, js_std_gc ),
  76755. JS_CFUNC_DEF("evalScript", 1, js_evalScript ),
  76756. JS_CFUNC_DEF("loadScript", 1, js_loadScript ),
  76757. JS_CFUNC_DEF("getenv", 1, js_std_getenv ),
  76758. JS_CFUNC_DEF("setenv", 1, js_std_setenv ),
  76759. JS_CFUNC_DEF("unsetenv", 1, js_std_unsetenv ),
  76760. JS_CFUNC_DEF("getenviron", 1, js_std_getenviron ),
  76761. #if !defined(__wasi__)
  76762. JS_CFUNC_DEF("urlGet", 1, js_std_urlGet ),
  76763. #endif
  76764. JS_CFUNC_DEF("loadFile", 1, js_std_loadFile ),
  76765. JS_CFUNC_DEF("writeFile", 2, js_std_writeFile ),
  76766. JS_CFUNC_DEF("strerror", 1, js_std_strerror ),
  76767. /* FILE I/O */
  76768. JS_CFUNC_DEF("open", 2, js_std_open ),
  76769. #if !defined(__wasi__)
  76770. JS_CFUNC_DEF("popen", 2, js_std_popen ),
  76771. JS_CFUNC_DEF("tmpfile", 0, js_std_tmpfile ),
  76772. #endif
  76773. JS_CFUNC_DEF("fdopen", 2, js_std_fdopen ),
  76774. JS_CFUNC_MAGIC_DEF("puts", 1, js_std_file_puts, 0 ),
  76775. JS_CFUNC_DEF("printf", 1, js_std_printf ),
  76776. JS_CFUNC_DEF("sprintf", 1, js_std_sprintf ),
  76777. JS_PROP_INT32_DEF("SEEK_SET", SEEK_SET, JS_PROP_CONFIGURABLE ),
  76778. JS_PROP_INT32_DEF("SEEK_CUR", SEEK_CUR, JS_PROP_CONFIGURABLE ),
  76779. JS_PROP_INT32_DEF("SEEK_END", SEEK_END, JS_PROP_CONFIGURABLE ),
  76780. JS_OBJECT_DEF("Error", js_std_error_props, countof(js_std_error_props), JS_PROP_CONFIGURABLE),
  76781. };
  76782. static const JSCFunctionListEntry js_std_file_proto_funcs[] = {
  76783. JS_CFUNC_DEF("close", 0, js_std_file_close ),
  76784. JS_CFUNC_MAGIC_DEF("puts", 1, js_std_file_puts, 1 ),
  76785. JS_CFUNC_DEF("printf", 1, js_std_file_printf ),
  76786. JS_CFUNC_DEF("flush", 0, js_std_file_flush ),
  76787. JS_CFUNC_MAGIC_DEF("tell", 0, js_std_file_tell, 0 ),
  76788. JS_CFUNC_MAGIC_DEF("tello", 0, js_std_file_tell, 1 ),
  76789. JS_CFUNC_DEF("seek", 2, js_std_file_seek ),
  76790. JS_CFUNC_DEF("eof", 0, js_std_file_eof ),
  76791. JS_CFUNC_DEF("fileno", 0, js_std_file_fileno ),
  76792. JS_CFUNC_DEF("error", 0, js_std_file_error ),
  76793. JS_CFUNC_DEF("clearerr", 0, js_std_file_clearerr ),
  76794. JS_CFUNC_MAGIC_DEF("read", 3, js_std_file_read_write, 0 ),
  76795. JS_CFUNC_MAGIC_DEF("write", 3, js_std_file_read_write, 1 ),
  76796. JS_CFUNC_DEF("getline", 0, js_std_file_getline ),
  76797. JS_CFUNC_MAGIC_DEF("readAsArrayBuffer", 0, js_std_file_readAs, 0 ),
  76798. JS_CFUNC_MAGIC_DEF("readAsString", 0, js_std_file_readAs, 1 ),
  76799. JS_CFUNC_DEF("getByte", 0, js_std_file_getByte ),
  76800. JS_CFUNC_DEF("putByte", 1, js_std_file_putByte ),
  76801. /* setvbuf, ... */
  76802. };
  76803. static int js_std_init(JSContext *ctx, JSModuleDef *m)
  76804. {
  76805. JSValue proto;
  76806. JSRuntime *rt = JS_GetRuntime(ctx);
  76807. JSThreadState *ts = js_get_thread_state(rt);
  76808. /* FILE class */
  76809. /* the class ID is created once */
  76810. JS_NewClassID(rt, &ts->std_file_class_id);
  76811. /* the class is created once per runtime */
  76812. JS_NewClass(rt, ts->std_file_class_id, &js_std_file_class);
  76813. proto = JS_NewObject(ctx);
  76814. JS_SetPropertyFunctionList(ctx, proto, js_std_file_proto_funcs,
  76815. countof(js_std_file_proto_funcs));
  76816. JS_SetClassProto(ctx, ts->std_file_class_id, proto);
  76817. JS_SetModuleExportList(ctx, m, js_std_funcs,
  76818. countof(js_std_funcs));
  76819. JS_SetModuleExport(ctx, m, "in", js_new_std_file(ctx, stdin, false));
  76820. JS_SetModuleExport(ctx, m, "out", js_new_std_file(ctx, stdout, false));
  76821. JS_SetModuleExport(ctx, m, "err", js_new_std_file(ctx, stderr, false));
  76822. return 0;
  76823. }
  76824. JSModuleDef *js_init_module_std(JSContext *ctx, const char *module_name)
  76825. {
  76826. JSModuleDef *m;
  76827. m = JS_NewCModule(ctx, module_name, js_std_init);
  76828. if (!m)
  76829. return NULL;
  76830. JS_AddModuleExportList(ctx, m, js_std_funcs, countof(js_std_funcs));
  76831. JS_AddModuleExport(ctx, m, "in");
  76832. JS_AddModuleExport(ctx, m, "out");
  76833. JS_AddModuleExport(ctx, m, "err");
  76834. return m;
  76835. }
  76836. /**********************************************************/
  76837. /* 'os' object */
  76838. static JSValue js_os_open(JSContext *ctx, JSValueConst this_val,
  76839. int argc, JSValueConst *argv)
  76840. {
  76841. const char *filename;
  76842. int flags, mode, ret;
  76843. filename = JS_ToCString(ctx, argv[0]);
  76844. if (!filename)
  76845. return JS_EXCEPTION;
  76846. if (JS_ToInt32(ctx, &flags, argv[1]))
  76847. goto fail;
  76848. if (argc >= 3 && !JS_IsUndefined(argv[2])) {
  76849. if (JS_ToInt32(ctx, &mode, argv[2])) {
  76850. fail:
  76851. JS_FreeCString(ctx, filename);
  76852. return JS_EXCEPTION;
  76853. }
  76854. } else {
  76855. mode = 0666;
  76856. }
  76857. #if defined(_WIN32)
  76858. /* force binary mode by default */
  76859. if (!(flags & O_TEXT))
  76860. flags |= O_BINARY;
  76861. #endif
  76862. ret = js_get_errno(open(filename, flags, mode));
  76863. JS_FreeCString(ctx, filename);
  76864. return JS_NewInt32(ctx, ret);
  76865. }
  76866. static JSValue js_os_close(JSContext *ctx, JSValueConst this_val,
  76867. int argc, JSValueConst *argv)
  76868. {
  76869. int fd, ret;
  76870. if (JS_ToInt32(ctx, &fd, argv[0]))
  76871. return JS_EXCEPTION;
  76872. ret = js_get_errno(close(fd));
  76873. return JS_NewInt32(ctx, ret);
  76874. }
  76875. static JSValue js_os_seek(JSContext *ctx, JSValueConst this_val,
  76876. int argc, JSValueConst *argv)
  76877. {
  76878. int fd, whence;
  76879. int64_t pos, ret;
  76880. bool is_bigint;
  76881. if (JS_ToInt32(ctx, &fd, argv[0]))
  76882. return JS_EXCEPTION;
  76883. is_bigint = JS_IsBigInt(ctx, argv[1]);
  76884. if (JS_ToInt64Ext(ctx, &pos, argv[1]))
  76885. return JS_EXCEPTION;
  76886. if (JS_ToInt32(ctx, &whence, argv[2]))
  76887. return JS_EXCEPTION;
  76888. ret = lseek(fd, pos, whence);
  76889. if (ret == -1)
  76890. ret = -errno;
  76891. if (is_bigint)
  76892. return JS_NewBigInt64(ctx, ret);
  76893. else
  76894. return JS_NewInt64(ctx, ret);
  76895. }
  76896. static JSValue js_os_read_write(JSContext *ctx, JSValueConst this_val,
  76897. int argc, JSValueConst *argv, int magic)
  76898. {
  76899. int fd;
  76900. uint64_t pos, len;
  76901. size_t size;
  76902. ssize_t ret;
  76903. uint8_t *buf;
  76904. if (JS_ToInt32(ctx, &fd, argv[0]))
  76905. return JS_EXCEPTION;
  76906. if (JS_ToIndex(ctx, &pos, argv[2]))
  76907. return JS_EXCEPTION;
  76908. if (JS_ToIndex(ctx, &len, argv[3]))
  76909. return JS_EXCEPTION;
  76910. buf = JS_GetArrayBuffer(ctx, &size, argv[1]);
  76911. if (!buf)
  76912. return JS_EXCEPTION;
  76913. if (pos + len > size)
  76914. return JS_ThrowRangeError(ctx, "read/write array buffer overflow");
  76915. if (magic)
  76916. ret = js_get_errno(write(fd, buf + pos, len));
  76917. else
  76918. ret = js_get_errno(read(fd, buf + pos, len));
  76919. return JS_NewInt64(ctx, ret);
  76920. }
  76921. static JSValue js_os_isatty(JSContext *ctx, JSValueConst this_val,
  76922. int argc, JSValueConst *argv)
  76923. {
  76924. int fd;
  76925. if (JS_ToInt32(ctx, &fd, argv[0]))
  76926. return JS_EXCEPTION;
  76927. return JS_NewBool(ctx, (isatty(fd) != 0));
  76928. }
  76929. #if defined(_WIN32)
  76930. static JSValue js_os_ttyGetWinSize(JSContext *ctx, JSValueConst this_val,
  76931. int argc, JSValueConst *argv)
  76932. {
  76933. int fd;
  76934. HANDLE handle;
  76935. CONSOLE_SCREEN_BUFFER_INFO info;
  76936. JSValue obj;
  76937. if (JS_ToInt32(ctx, &fd, argv[0]))
  76938. return JS_EXCEPTION;
  76939. handle = (HANDLE)_get_osfhandle(fd);
  76940. if (!GetConsoleScreenBufferInfo(handle, &info))
  76941. return JS_NULL;
  76942. obj = JS_NewArray(ctx);
  76943. if (JS_IsException(obj))
  76944. return obj;
  76945. JS_DefinePropertyValueUint32(ctx, obj, 0, JS_NewInt32(ctx, info.dwSize.X), JS_PROP_C_W_E);
  76946. JS_DefinePropertyValueUint32(ctx, obj, 1, JS_NewInt32(ctx, info.dwSize.Y), JS_PROP_C_W_E);
  76947. return obj;
  76948. }
  76949. /* Windows 10 built-in VT100 emulation */
  76950. #define __ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
  76951. #define __ENABLE_VIRTUAL_TERMINAL_INPUT 0x0200
  76952. static JSValue js_os_ttySetRaw(JSContext *ctx, JSValueConst this_val,
  76953. int argc, JSValueConst *argv)
  76954. {
  76955. int fd;
  76956. HANDLE handle;
  76957. if (JS_ToInt32(ctx, &fd, argv[0]))
  76958. return JS_EXCEPTION;
  76959. handle = (HANDLE)_get_osfhandle(fd);
  76960. SetConsoleMode(handle, ENABLE_WINDOW_INPUT | __ENABLE_VIRTUAL_TERMINAL_INPUT);
  76961. _setmode(fd, _O_BINARY);
  76962. if (fd == 0) {
  76963. handle = (HANDLE)_get_osfhandle(1); /* corresponding output */
  76964. SetConsoleMode(handle, ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT | __ENABLE_VIRTUAL_TERMINAL_PROCESSING);
  76965. }
  76966. return JS_UNDEFINED;
  76967. }
  76968. #elif !defined(__wasi__)
  76969. static JSValue js_os_ttyGetWinSize(JSContext *ctx, JSValueConst this_val,
  76970. int argc, JSValueConst *argv)
  76971. {
  76972. int fd;
  76973. struct winsize ws;
  76974. JSValue obj;
  76975. if (JS_ToInt32(ctx, &fd, argv[0]))
  76976. return JS_EXCEPTION;
  76977. if (ioctl(fd, TIOCGWINSZ, &ws) == 0 &&
  76978. ws.ws_col >= 4 && ws.ws_row >= 4) {
  76979. obj = JS_NewArray(ctx);
  76980. if (JS_IsException(obj))
  76981. return obj;
  76982. JS_DefinePropertyValueUint32(ctx, obj, 0, JS_NewInt32(ctx, ws.ws_col), JS_PROP_C_W_E);
  76983. JS_DefinePropertyValueUint32(ctx, obj, 1, JS_NewInt32(ctx, ws.ws_row), JS_PROP_C_W_E);
  76984. return obj;
  76985. } else {
  76986. return JS_NULL;
  76987. }
  76988. }
  76989. static struct termios oldtty;
  76990. static void term_exit(void)
  76991. {
  76992. tcsetattr(0, TCSANOW, &oldtty);
  76993. }
  76994. /* XXX: should add a way to go back to normal mode */
  76995. static JSValue js_os_ttySetRaw(JSContext *ctx, JSValueConst this_val,
  76996. int argc, JSValueConst *argv)
  76997. {
  76998. struct termios tty;
  76999. int fd;
  77000. if (JS_ToInt32(ctx, &fd, argv[0]))
  77001. return JS_EXCEPTION;
  77002. memset(&tty, 0, sizeof(tty));
  77003. tcgetattr(fd, &tty);
  77004. oldtty = tty;
  77005. tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
  77006. |INLCR|IGNCR|ICRNL|IXON);
  77007. tty.c_oflag |= OPOST;
  77008. tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
  77009. tty.c_cflag &= ~(CSIZE|PARENB);
  77010. tty.c_cflag |= CS8;
  77011. tty.c_cc[VMIN] = 1;
  77012. tty.c_cc[VTIME] = 0;
  77013. tcsetattr(fd, TCSANOW, &tty);
  77014. atexit(term_exit);
  77015. return JS_UNDEFINED;
  77016. }
  77017. #endif /* !_WIN32 && !__wasi__ */
  77018. static JSValue js_os_remove(JSContext *ctx, JSValueConst this_val,
  77019. int argc, JSValueConst *argv)
  77020. {
  77021. const char *filename;
  77022. int ret;
  77023. filename = JS_ToCString(ctx, argv[0]);
  77024. if (!filename)
  77025. return JS_EXCEPTION;
  77026. #if defined(_WIN32)
  77027. {
  77028. struct stat st;
  77029. if (stat(filename, &st) == 0 && S_ISDIR(st.st_mode)) {
  77030. ret = rmdir(filename);
  77031. } else {
  77032. ret = unlink(filename);
  77033. }
  77034. }
  77035. #else
  77036. ret = remove(filename);
  77037. #endif
  77038. ret = js_get_errno(ret);
  77039. JS_FreeCString(ctx, filename);
  77040. return JS_NewInt32(ctx, ret);
  77041. }
  77042. static JSValue js_os_rename(JSContext *ctx, JSValueConst this_val,
  77043. int argc, JSValueConst *argv)
  77044. {
  77045. const char *oldpath, *newpath;
  77046. int ret;
  77047. oldpath = JS_ToCString(ctx, argv[0]);
  77048. if (!oldpath)
  77049. return JS_EXCEPTION;
  77050. newpath = JS_ToCString(ctx, argv[1]);
  77051. if (!newpath) {
  77052. JS_FreeCString(ctx, oldpath);
  77053. return JS_EXCEPTION;
  77054. }
  77055. ret = js_get_errno(rename(oldpath, newpath));
  77056. JS_FreeCString(ctx, oldpath);
  77057. JS_FreeCString(ctx, newpath);
  77058. return JS_NewInt32(ctx, ret);
  77059. }
  77060. static bool is_main_thread(JSRuntime *rt)
  77061. {
  77062. JSThreadState *ts = js_get_thread_state(rt);
  77063. return !ts->recv_pipe;
  77064. }
  77065. static JSOSRWHandler *find_rh(JSThreadState *ts, int fd)
  77066. {
  77067. JSOSRWHandler *rh;
  77068. struct list_head *el;
  77069. list_for_each(el, &ts->os_rw_handlers) {
  77070. rh = list_entry(el, JSOSRWHandler, link);
  77071. if (rh->fd == fd)
  77072. return rh;
  77073. }
  77074. return NULL;
  77075. }
  77076. static void free_rw_handler(JSRuntime *rt, JSOSRWHandler *rh)
  77077. {
  77078. int i;
  77079. list_del(&rh->link);
  77080. for(i = 0; i < 2; i++) {
  77081. JS_FreeValueRT(rt, rh->rw_func[i]);
  77082. }
  77083. js_free_rt(rt, rh);
  77084. }
  77085. static JSValue js_os_setReadHandler(JSContext *ctx, JSValueConst this_val,
  77086. int argc, JSValueConst *argv, int magic)
  77087. {
  77088. JSRuntime *rt = JS_GetRuntime(ctx);
  77089. JSThreadState *ts = js_get_thread_state(rt);
  77090. JSOSRWHandler *rh;
  77091. int fd;
  77092. JSValueConst func;
  77093. if (JS_ToInt32(ctx, &fd, argv[0]))
  77094. return JS_EXCEPTION;
  77095. func = argv[1];
  77096. if (JS_IsNull(func)) {
  77097. rh = find_rh(ts, fd);
  77098. if (rh) {
  77099. JS_FreeValue(ctx, rh->rw_func[magic]);
  77100. rh->rw_func[magic] = JS_NULL;
  77101. if (JS_IsNull(rh->rw_func[0]) &&
  77102. JS_IsNull(rh->rw_func[1])) {
  77103. /* remove the entry */
  77104. free_rw_handler(JS_GetRuntime(ctx), rh);
  77105. }
  77106. }
  77107. } else {
  77108. if (!JS_IsFunction(ctx, func))
  77109. return JS_ThrowTypeError(ctx, "not a function");
  77110. rh = find_rh(ts, fd);
  77111. if (!rh) {
  77112. rh = js_mallocz(ctx, sizeof(*rh));
  77113. if (!rh)
  77114. return JS_EXCEPTION;
  77115. rh->fd = fd;
  77116. rh->rw_func[0] = JS_NULL;
  77117. rh->rw_func[1] = JS_NULL;
  77118. list_add_tail(&rh->link, &ts->os_rw_handlers);
  77119. }
  77120. JS_FreeValue(ctx, rh->rw_func[magic]);
  77121. rh->rw_func[magic] = JS_DupValue(ctx, func);
  77122. }
  77123. return JS_UNDEFINED;
  77124. }
  77125. static JSOSSignalHandler *find_sh(JSThreadState *ts, int sig_num)
  77126. {
  77127. JSOSSignalHandler *sh;
  77128. struct list_head *el;
  77129. list_for_each(el, &ts->os_signal_handlers) {
  77130. sh = list_entry(el, JSOSSignalHandler, link);
  77131. if (sh->sig_num == sig_num)
  77132. return sh;
  77133. }
  77134. return NULL;
  77135. }
  77136. static void free_sh(JSRuntime *rt, JSOSSignalHandler *sh)
  77137. {
  77138. list_del(&sh->link);
  77139. JS_FreeValueRT(rt, sh->func);
  77140. js_free_rt(rt, sh);
  77141. }
  77142. static void os_signal_handler(int sig_num)
  77143. {
  77144. os_pending_signals |= ((uint64_t)1 << sig_num);
  77145. }
  77146. #if defined(_WIN32)
  77147. typedef void (*sighandler_t)(int sig_num);
  77148. #endif
  77149. static JSValue js_os_signal(JSContext *ctx, JSValueConst this_val,
  77150. int argc, JSValueConst *argv)
  77151. {
  77152. JSRuntime *rt = JS_GetRuntime(ctx);
  77153. JSThreadState *ts = js_get_thread_state(rt);
  77154. JSOSSignalHandler *sh;
  77155. uint32_t sig_num;
  77156. JSValueConst func;
  77157. sighandler_t handler;
  77158. if (!is_main_thread(rt))
  77159. return JS_ThrowTypeError(ctx, "signal handler can only be set in the main thread");
  77160. if (JS_ToUint32(ctx, &sig_num, argv[0]))
  77161. return JS_EXCEPTION;
  77162. if (sig_num >= 64)
  77163. return JS_ThrowRangeError(ctx, "invalid signal number");
  77164. func = argv[1];
  77165. /* func = null: SIG_DFL, func = undefined, SIG_IGN */
  77166. if (JS_IsNull(func) || JS_IsUndefined(func)) {
  77167. sh = find_sh(ts, sig_num);
  77168. if (sh) {
  77169. free_sh(JS_GetRuntime(ctx), sh);
  77170. }
  77171. if (JS_IsNull(func))
  77172. handler = SIG_DFL;
  77173. else
  77174. handler = SIG_IGN;
  77175. signal(sig_num, handler);
  77176. } else {
  77177. if (!JS_IsFunction(ctx, func))
  77178. return JS_ThrowTypeError(ctx, "not a function");
  77179. sh = find_sh(ts, sig_num);
  77180. if (!sh) {
  77181. sh = js_mallocz(ctx, sizeof(*sh));
  77182. if (!sh)
  77183. return JS_EXCEPTION;
  77184. sh->sig_num = sig_num;
  77185. list_add_tail(&sh->link, &ts->os_signal_handlers);
  77186. }
  77187. JS_FreeValue(ctx, sh->func);
  77188. sh->func = JS_DupValue(ctx, func);
  77189. signal(sig_num, os_signal_handler);
  77190. }
  77191. return JS_UNDEFINED;
  77192. }
  77193. #if !defined(_WIN32) && !defined(__wasi__)
  77194. static JSValue js_os_cputime(JSContext *ctx, JSValueConst this_val,
  77195. int argc, JSValueConst *argv)
  77196. {
  77197. struct rusage ru;
  77198. int64_t cputime;
  77199. cputime = 0;
  77200. if (!getrusage(RUSAGE_SELF, &ru))
  77201. cputime = (int64_t)ru.ru_utime.tv_sec * 1000000 + ru.ru_utime.tv_usec;
  77202. return JS_NewInt64(ctx, cputime);
  77203. }
  77204. #endif
  77205. static JSValue js_os_now(JSContext *ctx, JSValueConst this_val,
  77206. int argc, JSValueConst *argv)
  77207. {
  77208. return JS_NewInt64(ctx, js__hrtime_ns() / 1000);
  77209. }
  77210. static uint64_t js__hrtime_ms(void)
  77211. {
  77212. return js__hrtime_ns() / (1000 * 1000);
  77213. }
  77214. static void free_timer(JSRuntime *rt, JSOSTimer *th)
  77215. {
  77216. list_del(&th->link);
  77217. JS_FreeValueRT(rt, th->func);
  77218. js_free_rt(rt, th);
  77219. }
  77220. // TODO(bnoordhuis) accept string as first arg and eval at timer expiry
  77221. // TODO(bnoordhuis) retain argv[2..] as args for callback if argc > 2
  77222. static JSValue js_os_setTimeout(JSContext *ctx, JSValueConst this_val,
  77223. int argc, JSValueConst *argv, int magic)
  77224. {
  77225. JSRuntime *rt = JS_GetRuntime(ctx);
  77226. JSThreadState *ts = js_get_thread_state(rt);
  77227. int64_t delay;
  77228. JSValueConst func;
  77229. JSOSTimer *th;
  77230. func = argv[0];
  77231. if (!JS_IsFunction(ctx, func))
  77232. return JS_ThrowTypeError(ctx, "not a function");
  77233. if (JS_ToInt64(ctx, &delay, argv[1]))
  77234. return JS_EXCEPTION;
  77235. if (delay < 1)
  77236. delay = 1;
  77237. th = js_mallocz(ctx, sizeof(*th));
  77238. if (!th)
  77239. return JS_EXCEPTION;
  77240. th->timer_id = ts->next_timer_id++;
  77241. if (ts->next_timer_id > MAX_SAFE_INTEGER)
  77242. ts->next_timer_id = 1;
  77243. th->repeats = (magic > 0);
  77244. th->timeout = js__hrtime_ms() + delay;
  77245. th->delay = delay;
  77246. th->func = JS_DupValue(ctx, func);
  77247. list_add_tail(&th->link, &ts->os_timers);
  77248. return JS_NewInt64(ctx, th->timer_id);
  77249. }
  77250. static JSOSTimer *find_timer_by_id(JSThreadState *ts, int timer_id)
  77251. {
  77252. struct list_head *el;
  77253. if (timer_id <= 0)
  77254. return NULL;
  77255. list_for_each(el, &ts->os_timers) {
  77256. JSOSTimer *th = list_entry(el, JSOSTimer, link);
  77257. if (th->timer_id == timer_id)
  77258. return th;
  77259. }
  77260. return NULL;
  77261. }
  77262. static JSValue js_os_clearTimeout(JSContext *ctx, JSValueConst this_val,
  77263. int argc, JSValueConst *argv)
  77264. {
  77265. JSRuntime *rt = JS_GetRuntime(ctx);
  77266. JSThreadState *ts = js_get_thread_state(rt);
  77267. JSOSTimer *th;
  77268. int64_t timer_id;
  77269. if (JS_ToInt64(ctx, &timer_id, argv[0]))
  77270. return JS_EXCEPTION;
  77271. th = find_timer_by_id(ts, timer_id);
  77272. if (!th)
  77273. return JS_UNDEFINED;
  77274. free_timer(rt, th);
  77275. return JS_UNDEFINED;
  77276. }
  77277. /* return a promise */
  77278. static JSValue js_os_sleepAsync(JSContext *ctx, JSValueConst this_val,
  77279. int argc, JSValueConst *argv)
  77280. {
  77281. JSRuntime *rt = JS_GetRuntime(ctx);
  77282. JSThreadState *ts = js_get_thread_state(rt);
  77283. int64_t delay;
  77284. JSOSTimer *th;
  77285. JSValue promise, resolving_funcs[2];
  77286. if (JS_ToInt64(ctx, &delay, argv[0]))
  77287. return JS_EXCEPTION;
  77288. promise = JS_NewPromiseCapability(ctx, resolving_funcs);
  77289. if (JS_IsException(promise))
  77290. return JS_EXCEPTION;
  77291. th = js_mallocz(ctx, sizeof(*th));
  77292. if (!th) {
  77293. JS_FreeValue(ctx, promise);
  77294. JS_FreeValue(ctx, resolving_funcs[0]);
  77295. JS_FreeValue(ctx, resolving_funcs[1]);
  77296. return JS_EXCEPTION;
  77297. }
  77298. th->timer_id = -1;
  77299. th->timeout = js__hrtime_ms() + delay;
  77300. th->func = JS_DupValue(ctx, resolving_funcs[0]);
  77301. list_add_tail(&th->link, &ts->os_timers);
  77302. JS_FreeValue(ctx, resolving_funcs[0]);
  77303. JS_FreeValue(ctx, resolving_funcs[1]);
  77304. return promise;
  77305. }
  77306. static int call_handler(JSContext *ctx, JSValue func)
  77307. {
  77308. int r;
  77309. JSValue ret, func1;
  77310. /* 'func' might be destroyed when calling itself (if it frees the
  77311. handler), so must take extra care */
  77312. func1 = JS_DupValue(ctx, func);
  77313. ret = JS_Call(ctx, func1, JS_UNDEFINED, 0, NULL);
  77314. JS_FreeValue(ctx, func1);
  77315. r = 0;
  77316. if (JS_IsException(ret))
  77317. r = -1;
  77318. JS_FreeValue(ctx, ret);
  77319. return r;
  77320. }
  77321. static int js_os_run_timers(JSRuntime *rt, JSContext *ctx, JSThreadState *ts, int *min_delay)
  77322. {
  77323. JSValue func;
  77324. JSOSTimer *th;
  77325. int64_t cur_time, delay;
  77326. struct list_head *el;
  77327. int r;
  77328. if (list_empty(&ts->os_timers)) {
  77329. *min_delay = -1;
  77330. return 0;
  77331. }
  77332. cur_time = js__hrtime_ms();
  77333. *min_delay = INT32_MAX;
  77334. list_for_each(el, &ts->os_timers) {
  77335. th = list_entry(el, JSOSTimer, link);
  77336. delay = th->timeout - cur_time;
  77337. if (delay > 0) {
  77338. *min_delay = min_int(*min_delay, delay);
  77339. } else {
  77340. *min_delay = 0;
  77341. func = JS_DupValueRT(rt, th->func);
  77342. if (th->repeats)
  77343. th->timeout = cur_time + th->delay;
  77344. else
  77345. free_timer(rt, th);
  77346. r = call_handler(ctx, func);
  77347. JS_FreeValueRT(rt, func);
  77348. return r;
  77349. }
  77350. }
  77351. return 0;
  77352. }
  77353. #if defined(_WIN32)
  77354. static int js_os_poll(JSContext *ctx)
  77355. {
  77356. JSRuntime *rt = JS_GetRuntime(ctx);
  77357. JSThreadState *ts = js_get_thread_state(rt);
  77358. int min_delay, console_fd;
  77359. JSOSRWHandler *rh;
  77360. struct list_head *el;
  77361. /* XXX: handle signals if useful */
  77362. if (js_os_run_timers(rt, ctx, ts, &min_delay))
  77363. return -1;
  77364. if (min_delay == 0)
  77365. return 0; // expired timer
  77366. if (min_delay < 0)
  77367. if (list_empty(&ts->os_rw_handlers))
  77368. return -1; /* no more events */
  77369. console_fd = -1;
  77370. list_for_each(el, &ts->os_rw_handlers) {
  77371. rh = list_entry(el, JSOSRWHandler, link);
  77372. if (rh->fd == 0 && !JS_IsNull(rh->rw_func[0])) {
  77373. console_fd = rh->fd;
  77374. break;
  77375. }
  77376. }
  77377. if (console_fd >= 0) {
  77378. DWORD ti, ret;
  77379. HANDLE handle;
  77380. if (min_delay == -1)
  77381. ti = INFINITE;
  77382. else
  77383. ti = min_delay;
  77384. handle = (HANDLE)_get_osfhandle(console_fd);
  77385. ret = WaitForSingleObject(handle, ti);
  77386. if (ret == WAIT_OBJECT_0) {
  77387. list_for_each(el, &ts->os_rw_handlers) {
  77388. rh = list_entry(el, JSOSRWHandler, link);
  77389. if (rh->fd == console_fd && !JS_IsNull(rh->rw_func[0])) {
  77390. return call_handler(ctx, rh->rw_func[0]);
  77391. /* must stop because the list may have been modified */
  77392. }
  77393. }
  77394. }
  77395. } else {
  77396. Sleep(min_delay);
  77397. }
  77398. return 0;
  77399. }
  77400. #else
  77401. #ifdef USE_WORKER
  77402. static void js_free_message(JSWorkerMessage *msg);
  77403. /* return 1 if a message was handled, 0 if no message */
  77404. static int handle_posted_message(JSRuntime *rt, JSContext *ctx,
  77405. JSWorkerMessageHandler *port)
  77406. {
  77407. JSWorkerMessagePipe *ps = port->recv_pipe;
  77408. int ret;
  77409. struct list_head *el;
  77410. JSWorkerMessage *msg;
  77411. JSValue obj, data_obj, func, retval;
  77412. pthread_mutex_lock(&ps->mutex);
  77413. if (!list_empty(&ps->msg_queue)) {
  77414. el = ps->msg_queue.next;
  77415. msg = list_entry(el, JSWorkerMessage, link);
  77416. /* remove the message from the queue */
  77417. list_del(&msg->link);
  77418. if (list_empty(&ps->msg_queue)) {
  77419. uint8_t buf[16];
  77420. int ret;
  77421. for(;;) {
  77422. ret = read(ps->read_fd, buf, sizeof(buf));
  77423. if (ret >= 0)
  77424. break;
  77425. if (errno != EAGAIN && errno != EINTR)
  77426. break;
  77427. }
  77428. }
  77429. pthread_mutex_unlock(&ps->mutex);
  77430. data_obj = JS_ReadObject(ctx, msg->data, msg->data_len,
  77431. JS_READ_OBJ_SAB | JS_READ_OBJ_REFERENCE);
  77432. js_free_message(msg);
  77433. if (JS_IsException(data_obj))
  77434. goto fail;
  77435. obj = JS_NewObject(ctx);
  77436. if (JS_IsException(obj)) {
  77437. JS_FreeValue(ctx, data_obj);
  77438. goto fail;
  77439. }
  77440. JS_DefinePropertyValueStr(ctx, obj, "data", data_obj, JS_PROP_C_W_E);
  77441. /* 'func' might be destroyed when calling itself (if it frees the
  77442. handler), so must take extra care */
  77443. func = JS_DupValue(ctx, port->on_message_func);
  77444. retval = JS_Call(ctx, func, JS_UNDEFINED, 1, (JSValueConst *)&obj);
  77445. JS_FreeValue(ctx, obj);
  77446. JS_FreeValue(ctx, func);
  77447. if (JS_IsException(retval)) {
  77448. fail:
  77449. js_std_dump_error(ctx);
  77450. } else {
  77451. JS_FreeValue(ctx, retval);
  77452. }
  77453. ret = 1;
  77454. } else {
  77455. pthread_mutex_unlock(&ps->mutex);
  77456. ret = 0;
  77457. }
  77458. return ret;
  77459. }
  77460. #else
  77461. static int handle_posted_message(JSRuntime *rt, JSContext *ctx,
  77462. JSWorkerMessageHandler *port)
  77463. {
  77464. return 0;
  77465. }
  77466. #endif
  77467. static int js_os_poll(JSContext *ctx)
  77468. {
  77469. JSRuntime *rt = JS_GetRuntime(ctx);
  77470. JSThreadState *ts = js_get_thread_state(rt);
  77471. int ret, fd_max, min_delay;
  77472. fd_set rfds, wfds;
  77473. JSOSRWHandler *rh;
  77474. struct list_head *el;
  77475. struct timeval tv, *tvp;
  77476. /* only check signals in the main thread */
  77477. if (!ts->recv_pipe &&
  77478. unlikely(os_pending_signals != 0)) {
  77479. JSOSSignalHandler *sh;
  77480. uint64_t mask;
  77481. list_for_each(el, &ts->os_signal_handlers) {
  77482. sh = list_entry(el, JSOSSignalHandler, link);
  77483. mask = (uint64_t)1 << sh->sig_num;
  77484. if (os_pending_signals & mask) {
  77485. os_pending_signals &= ~mask;
  77486. return call_handler(ctx, sh->func);
  77487. }
  77488. }
  77489. }
  77490. if (js_os_run_timers(rt, ctx, ts, &min_delay))
  77491. return -1;
  77492. if (min_delay == 0)
  77493. return 0; // expired timer
  77494. if (min_delay < 0)
  77495. if (list_empty(&ts->os_rw_handlers) && list_empty(&ts->port_list))
  77496. return -1; /* no more events */
  77497. tvp = NULL;
  77498. if (min_delay >= 0) {
  77499. tv.tv_sec = min_delay / 1000;
  77500. tv.tv_usec = (min_delay % 1000) * 1000;
  77501. tvp = &tv;
  77502. }
  77503. FD_ZERO(&rfds);
  77504. FD_ZERO(&wfds);
  77505. fd_max = -1;
  77506. list_for_each(el, &ts->os_rw_handlers) {
  77507. rh = list_entry(el, JSOSRWHandler, link);
  77508. fd_max = max_int(fd_max, rh->fd);
  77509. if (!JS_IsNull(rh->rw_func[0]))
  77510. FD_SET(rh->fd, &rfds);
  77511. if (!JS_IsNull(rh->rw_func[1]))
  77512. FD_SET(rh->fd, &wfds);
  77513. }
  77514. list_for_each(el, &ts->port_list) {
  77515. JSWorkerMessageHandler *port = list_entry(el, JSWorkerMessageHandler, link);
  77516. if (!JS_IsNull(port->on_message_func)) {
  77517. JSWorkerMessagePipe *ps = port->recv_pipe;
  77518. fd_max = max_int(fd_max, ps->read_fd);
  77519. FD_SET(ps->read_fd, &rfds);
  77520. }
  77521. }
  77522. ret = select(fd_max + 1, &rfds, &wfds, NULL, tvp);
  77523. if (ret > 0) {
  77524. list_for_each(el, &ts->os_rw_handlers) {
  77525. rh = list_entry(el, JSOSRWHandler, link);
  77526. if (!JS_IsNull(rh->rw_func[0]) &&
  77527. FD_ISSET(rh->fd, &rfds)) {
  77528. return call_handler(ctx, rh->rw_func[0]);
  77529. /* must stop because the list may have been modified */
  77530. }
  77531. if (!JS_IsNull(rh->rw_func[1]) &&
  77532. FD_ISSET(rh->fd, &wfds)) {
  77533. return call_handler(ctx, rh->rw_func[1]);
  77534. /* must stop because the list may have been modified */
  77535. }
  77536. }
  77537. list_for_each(el, &ts->port_list) {
  77538. JSWorkerMessageHandler *port = list_entry(el, JSWorkerMessageHandler, link);
  77539. if (!JS_IsNull(port->on_message_func)) {
  77540. JSWorkerMessagePipe *ps = port->recv_pipe;
  77541. if (FD_ISSET(ps->read_fd, &rfds)) {
  77542. if (handle_posted_message(rt, ctx, port))
  77543. goto done;
  77544. }
  77545. }
  77546. }
  77547. }
  77548. done:
  77549. return 0;
  77550. }
  77551. #endif /* !_WIN32 */
  77552. static JSValue make_obj_error(JSContext *ctx,
  77553. JSValue obj,
  77554. int err)
  77555. {
  77556. JSValue arr;
  77557. if (JS_IsException(obj))
  77558. return obj;
  77559. arr = JS_NewArray(ctx);
  77560. if (JS_IsException(arr))
  77561. return JS_EXCEPTION;
  77562. JS_DefinePropertyValueUint32(ctx, arr, 0, obj,
  77563. JS_PROP_C_W_E);
  77564. JS_DefinePropertyValueUint32(ctx, arr, 1, JS_NewInt32(ctx, err),
  77565. JS_PROP_C_W_E);
  77566. return arr;
  77567. }
  77568. static JSValue make_string_error(JSContext *ctx,
  77569. const char *buf,
  77570. int err)
  77571. {
  77572. return make_obj_error(ctx, JS_NewString(ctx, buf), err);
  77573. }
  77574. /* return [cwd, errorcode] */
  77575. static JSValue js_os_getcwd(JSContext *ctx, JSValueConst this_val,
  77576. int argc, JSValueConst *argv)
  77577. {
  77578. char buf[PATH_MAX];
  77579. int err;
  77580. if (!getcwd(buf, sizeof(buf))) {
  77581. buf[0] = '\0';
  77582. err = errno;
  77583. } else {
  77584. err = 0;
  77585. }
  77586. return make_string_error(ctx, buf, err);
  77587. }
  77588. static JSValue js_os_chdir(JSContext *ctx, JSValueConst this_val,
  77589. int argc, JSValueConst *argv)
  77590. {
  77591. const char *target;
  77592. int err;
  77593. target = JS_ToCString(ctx, argv[0]);
  77594. if (!target)
  77595. return JS_EXCEPTION;
  77596. err = js_get_errno(chdir(target));
  77597. JS_FreeCString(ctx, target);
  77598. return JS_NewInt32(ctx, err);
  77599. }
  77600. static JSValue js_os_mkdir(JSContext *ctx, JSValueConst this_val,
  77601. int argc, JSValueConst *argv)
  77602. {
  77603. int mode, ret;
  77604. const char *path;
  77605. if (argc >= 2) {
  77606. if (JS_ToInt32(ctx, &mode, argv[1]))
  77607. return JS_EXCEPTION;
  77608. } else {
  77609. mode = 0777;
  77610. }
  77611. path = JS_ToCString(ctx, argv[0]);
  77612. if (!path)
  77613. return JS_EXCEPTION;
  77614. #if defined(_WIN32)
  77615. (void)mode;
  77616. ret = js_get_errno(mkdir(path));
  77617. #else
  77618. ret = js_get_errno(mkdir(path, mode));
  77619. #endif
  77620. JS_FreeCString(ctx, path);
  77621. return JS_NewInt32(ctx, ret);
  77622. }
  77623. /* return [array, errorcode] */
  77624. static JSValue js_os_readdir(JSContext *ctx, JSValueConst this_val,
  77625. int argc, JSValueConst *argv)
  77626. {
  77627. const char *path;
  77628. DIR *f;
  77629. struct dirent *d;
  77630. JSValue obj;
  77631. int err;
  77632. uint32_t len;
  77633. path = JS_ToCString(ctx, argv[0]);
  77634. if (!path)
  77635. return JS_EXCEPTION;
  77636. obj = JS_NewArray(ctx);
  77637. if (JS_IsException(obj)) {
  77638. JS_FreeCString(ctx, path);
  77639. return JS_EXCEPTION;
  77640. }
  77641. f = opendir(path);
  77642. if (!f)
  77643. err = errno;
  77644. else
  77645. err = 0;
  77646. JS_FreeCString(ctx, path);
  77647. if (!f)
  77648. goto done;
  77649. len = 0;
  77650. for(;;) {
  77651. errno = 0;
  77652. d = readdir(f);
  77653. if (!d) {
  77654. err = errno;
  77655. break;
  77656. }
  77657. JS_DefinePropertyValueUint32(ctx, obj, len++,
  77658. JS_NewString(ctx, d->d_name),
  77659. JS_PROP_C_W_E);
  77660. }
  77661. closedir(f);
  77662. done:
  77663. return make_obj_error(ctx, obj, err);
  77664. }
  77665. #if !defined(_WIN32)
  77666. static int64_t timespec_to_ms(const struct timespec *tv)
  77667. {
  77668. return (int64_t)tv->tv_sec * 1000 + (tv->tv_nsec / 1000000);
  77669. }
  77670. #endif
  77671. /* return [obj, errcode] */
  77672. static JSValue js_os_stat(JSContext *ctx, JSValueConst this_val,
  77673. int argc, JSValueConst *argv, int is_lstat)
  77674. {
  77675. const char *path;
  77676. int err, res;
  77677. struct stat st;
  77678. JSValue obj;
  77679. path = JS_ToCString(ctx, argv[0]);
  77680. if (!path)
  77681. return JS_EXCEPTION;
  77682. #if defined(_WIN32)
  77683. res = stat(path, &st);
  77684. #else
  77685. if (is_lstat)
  77686. res = lstat(path, &st);
  77687. else
  77688. res = stat(path, &st);
  77689. #endif
  77690. err = (res < 0) ? errno : 0;
  77691. JS_FreeCString(ctx, path);
  77692. if (res < 0) {
  77693. obj = JS_NULL;
  77694. } else {
  77695. obj = JS_NewObject(ctx);
  77696. if (JS_IsException(obj))
  77697. return JS_EXCEPTION;
  77698. JS_DefinePropertyValueStr(ctx, obj, "dev",
  77699. JS_NewInt64(ctx, st.st_dev),
  77700. JS_PROP_C_W_E);
  77701. JS_DefinePropertyValueStr(ctx, obj, "ino",
  77702. JS_NewInt64(ctx, st.st_ino),
  77703. JS_PROP_C_W_E);
  77704. JS_DefinePropertyValueStr(ctx, obj, "mode",
  77705. JS_NewInt32(ctx, st.st_mode),
  77706. JS_PROP_C_W_E);
  77707. JS_DefinePropertyValueStr(ctx, obj, "nlink",
  77708. JS_NewInt64(ctx, st.st_nlink),
  77709. JS_PROP_C_W_E);
  77710. JS_DefinePropertyValueStr(ctx, obj, "uid",
  77711. JS_NewInt64(ctx, st.st_uid),
  77712. JS_PROP_C_W_E);
  77713. JS_DefinePropertyValueStr(ctx, obj, "gid",
  77714. JS_NewInt64(ctx, st.st_gid),
  77715. JS_PROP_C_W_E);
  77716. JS_DefinePropertyValueStr(ctx, obj, "rdev",
  77717. JS_NewInt64(ctx, st.st_rdev),
  77718. JS_PROP_C_W_E);
  77719. JS_DefinePropertyValueStr(ctx, obj, "size",
  77720. JS_NewInt64(ctx, st.st_size),
  77721. JS_PROP_C_W_E);
  77722. #if !defined(_WIN32)
  77723. JS_DefinePropertyValueStr(ctx, obj, "blocks",
  77724. JS_NewInt64(ctx, st.st_blocks),
  77725. JS_PROP_C_W_E);
  77726. #endif
  77727. #if defined(_WIN32)
  77728. JS_DefinePropertyValueStr(ctx, obj, "atime",
  77729. JS_NewInt64(ctx, (int64_t)st.st_atime * 1000),
  77730. JS_PROP_C_W_E);
  77731. JS_DefinePropertyValueStr(ctx, obj, "mtime",
  77732. JS_NewInt64(ctx, (int64_t)st.st_mtime * 1000),
  77733. JS_PROP_C_W_E);
  77734. JS_DefinePropertyValueStr(ctx, obj, "ctime",
  77735. JS_NewInt64(ctx, (int64_t)st.st_ctime * 1000),
  77736. JS_PROP_C_W_E);
  77737. #elif defined(__APPLE__)
  77738. JS_DefinePropertyValueStr(ctx, obj, "atime",
  77739. JS_NewInt64(ctx, timespec_to_ms(&st.st_atimespec)),
  77740. JS_PROP_C_W_E);
  77741. JS_DefinePropertyValueStr(ctx, obj, "mtime",
  77742. JS_NewInt64(ctx, timespec_to_ms(&st.st_mtimespec)),
  77743. JS_PROP_C_W_E);
  77744. JS_DefinePropertyValueStr(ctx, obj, "ctime",
  77745. JS_NewInt64(ctx, timespec_to_ms(&st.st_ctimespec)),
  77746. JS_PROP_C_W_E);
  77747. #else
  77748. JS_DefinePropertyValueStr(ctx, obj, "atime",
  77749. JS_NewInt64(ctx, timespec_to_ms(&st.st_atim)),
  77750. JS_PROP_C_W_E);
  77751. JS_DefinePropertyValueStr(ctx, obj, "mtime",
  77752. JS_NewInt64(ctx, timespec_to_ms(&st.st_mtim)),
  77753. JS_PROP_C_W_E);
  77754. JS_DefinePropertyValueStr(ctx, obj, "ctime",
  77755. JS_NewInt64(ctx, timespec_to_ms(&st.st_ctim)),
  77756. JS_PROP_C_W_E);
  77757. #endif
  77758. }
  77759. return make_obj_error(ctx, obj, err);
  77760. }
  77761. #if !defined(_WIN32)
  77762. static void ms_to_timeval(struct timeval *tv, uint64_t v)
  77763. {
  77764. tv->tv_sec = v / 1000;
  77765. tv->tv_usec = (v % 1000) * 1000;
  77766. }
  77767. #endif
  77768. static JSValue js_os_utimes(JSContext *ctx, JSValueConst this_val,
  77769. int argc, JSValueConst *argv)
  77770. {
  77771. const char *path;
  77772. int64_t atime, mtime;
  77773. int ret;
  77774. if (JS_ToInt64(ctx, &atime, argv[1]))
  77775. return JS_EXCEPTION;
  77776. if (JS_ToInt64(ctx, &mtime, argv[2]))
  77777. return JS_EXCEPTION;
  77778. path = JS_ToCString(ctx, argv[0]);
  77779. if (!path)
  77780. return JS_EXCEPTION;
  77781. #if defined(_WIN32)
  77782. {
  77783. struct _utimbuf times;
  77784. times.actime = atime / 1000;
  77785. times.modtime = mtime / 1000;
  77786. ret = js_get_errno(_utime(path, &times));
  77787. }
  77788. #else
  77789. {
  77790. struct timeval times[2];
  77791. ms_to_timeval(&times[0], atime);
  77792. ms_to_timeval(&times[1], mtime);
  77793. ret = js_get_errno(utimes(path, times));
  77794. }
  77795. #endif
  77796. JS_FreeCString(ctx, path);
  77797. return JS_NewInt32(ctx, ret);
  77798. }
  77799. /* sleep(delay_ms) */
  77800. static JSValue js_os_sleep(JSContext *ctx, JSValueConst this_val,
  77801. int argc, JSValueConst *argv)
  77802. {
  77803. int64_t delay;
  77804. int ret;
  77805. if (JS_ToInt64(ctx, &delay, argv[0]))
  77806. return JS_EXCEPTION;
  77807. if (delay < 0)
  77808. delay = 0;
  77809. #if defined(_WIN32)
  77810. {
  77811. if (delay > INT32_MAX)
  77812. delay = INT32_MAX;
  77813. Sleep(delay);
  77814. ret = 0;
  77815. }
  77816. #else
  77817. {
  77818. struct timespec ts;
  77819. ts.tv_sec = delay / 1000;
  77820. ts.tv_nsec = (delay % 1000) * 1000000;
  77821. ret = js_get_errno(nanosleep(&ts, NULL));
  77822. }
  77823. #endif
  77824. return JS_NewInt32(ctx, ret);
  77825. }
  77826. #if defined(_WIN32)
  77827. static char *realpath(const char *path, char *buf)
  77828. {
  77829. if (!_fullpath(buf, path, PATH_MAX)) {
  77830. errno = ENOENT;
  77831. return NULL;
  77832. } else {
  77833. return buf;
  77834. }
  77835. }
  77836. #endif
  77837. #if !defined(__wasi__)
  77838. /* return [path, errorcode] */
  77839. static JSValue js_os_realpath(JSContext *ctx, JSValueConst this_val,
  77840. int argc, JSValueConst *argv)
  77841. {
  77842. const char *path;
  77843. char buf[PATH_MAX], *res;
  77844. int err;
  77845. path = JS_ToCString(ctx, argv[0]);
  77846. if (!path)
  77847. return JS_EXCEPTION;
  77848. res = realpath(path, buf);
  77849. JS_FreeCString(ctx, path);
  77850. if (!res) {
  77851. buf[0] = '\0';
  77852. err = errno;
  77853. } else {
  77854. err = 0;
  77855. }
  77856. return make_string_error(ctx, buf, err);
  77857. }
  77858. #endif
  77859. #if !defined(_WIN32) && !defined(__wasi__)
  77860. static JSValue js_os_symlink(JSContext *ctx, JSValueConst this_val,
  77861. int argc, JSValueConst *argv)
  77862. {
  77863. const char *target, *linkpath;
  77864. int err;
  77865. target = JS_ToCString(ctx, argv[0]);
  77866. if (!target)
  77867. return JS_EXCEPTION;
  77868. linkpath = JS_ToCString(ctx, argv[1]);
  77869. if (!linkpath) {
  77870. JS_FreeCString(ctx, target);
  77871. return JS_EXCEPTION;
  77872. }
  77873. err = js_get_errno(symlink(target, linkpath));
  77874. JS_FreeCString(ctx, target);
  77875. JS_FreeCString(ctx, linkpath);
  77876. return JS_NewInt32(ctx, err);
  77877. }
  77878. /* return [path, errorcode] */
  77879. static JSValue js_os_readlink(JSContext *ctx, JSValueConst this_val,
  77880. int argc, JSValueConst *argv)
  77881. {
  77882. const char *path;
  77883. char buf[PATH_MAX];
  77884. int err;
  77885. ssize_t res;
  77886. path = JS_ToCString(ctx, argv[0]);
  77887. if (!path)
  77888. return JS_EXCEPTION;
  77889. res = readlink(path, buf, sizeof(buf) - 1);
  77890. if (res < 0) {
  77891. buf[0] = '\0';
  77892. err = errno;
  77893. } else {
  77894. buf[res] = '\0';
  77895. err = 0;
  77896. }
  77897. JS_FreeCString(ctx, path);
  77898. return make_string_error(ctx, buf, err);
  77899. }
  77900. static char **build_envp(JSContext *ctx, JSValue obj)
  77901. {
  77902. uint32_t len, i;
  77903. JSPropertyEnum *tab;
  77904. char **envp, *pair;
  77905. const char *key, *str;
  77906. JSValue val;
  77907. size_t key_len, str_len;
  77908. if (JS_GetOwnPropertyNames(ctx, &tab, &len, obj,
  77909. JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY) < 0)
  77910. return NULL;
  77911. envp = js_mallocz(ctx, sizeof(envp[0]) * ((size_t)len + 1));
  77912. if (!envp)
  77913. goto fail;
  77914. for(i = 0; i < len; i++) {
  77915. val = JS_GetProperty(ctx, obj, tab[i].atom);
  77916. if (JS_IsException(val))
  77917. goto fail;
  77918. str = JS_ToCString(ctx, val);
  77919. JS_FreeValue(ctx, val);
  77920. if (!str)
  77921. goto fail;
  77922. key = JS_AtomToCString(ctx, tab[i].atom);
  77923. if (!key) {
  77924. JS_FreeCString(ctx, str);
  77925. goto fail;
  77926. }
  77927. key_len = strlen(key);
  77928. str_len = strlen(str);
  77929. pair = js_malloc(ctx, key_len + str_len + 2);
  77930. if (!pair) {
  77931. JS_FreeCString(ctx, key);
  77932. JS_FreeCString(ctx, str);
  77933. goto fail;
  77934. }
  77935. memcpy(pair, key, key_len);
  77936. pair[key_len] = '=';
  77937. memcpy(pair + key_len + 1, str, str_len);
  77938. pair[key_len + 1 + str_len] = '\0';
  77939. envp[i] = pair;
  77940. JS_FreeCString(ctx, key);
  77941. JS_FreeCString(ctx, str);
  77942. }
  77943. done:
  77944. for(i = 0; i < len; i++)
  77945. JS_FreeAtom(ctx, tab[i].atom);
  77946. js_free(ctx, tab);
  77947. return envp;
  77948. fail:
  77949. if (envp) {
  77950. for(i = 0; i < len; i++)
  77951. js_free(ctx, envp[i]);
  77952. js_free(ctx, envp);
  77953. envp = NULL;
  77954. }
  77955. goto done;
  77956. }
  77957. /* execvpe is not available on non GNU systems */
  77958. static int my_execvpe(const char *filename, char **argv, char **envp)
  77959. {
  77960. char *path, *p, *p_next, *p1;
  77961. char buf[PATH_MAX];
  77962. size_t filename_len, path_len;
  77963. bool eacces_error;
  77964. filename_len = strlen(filename);
  77965. if (filename_len == 0) {
  77966. errno = ENOENT;
  77967. return -1;
  77968. }
  77969. if (strchr(filename, '/'))
  77970. return execve(filename, argv, envp);
  77971. path = getenv("PATH");
  77972. if (!path)
  77973. path = (char *)"/bin:/usr/bin";
  77974. eacces_error = false;
  77975. p = path;
  77976. for(p = path; p != NULL; p = p_next) {
  77977. p1 = strchr(p, ':');
  77978. if (!p1) {
  77979. p_next = NULL;
  77980. path_len = strlen(p);
  77981. } else {
  77982. p_next = p1 + 1;
  77983. path_len = p1 - p;
  77984. }
  77985. /* path too long */
  77986. if ((path_len + 1 + filename_len + 1) > PATH_MAX)
  77987. continue;
  77988. memcpy(buf, p, path_len);
  77989. buf[path_len] = '/';
  77990. memcpy(buf + path_len + 1, filename, filename_len);
  77991. buf[path_len + 1 + filename_len] = '\0';
  77992. execve(buf, argv, envp);
  77993. switch(errno) {
  77994. case EACCES:
  77995. eacces_error = true;
  77996. break;
  77997. case ENOENT:
  77998. case ENOTDIR:
  77999. break;
  78000. default:
  78001. return -1;
  78002. }
  78003. }
  78004. if (eacces_error)
  78005. errno = EACCES;
  78006. return -1;
  78007. }
  78008. static void (*js_os_exec_closefrom)(int);
  78009. #if !defined(EMSCRIPTEN) && !defined(__wasi__)
  78010. static js_once_t js_os_exec_once = JS_ONCE_INIT;
  78011. static void js_os_exec_once_init(void)
  78012. {
  78013. js_os_exec_closefrom = dlsym(RTLD_DEFAULT, "closefrom");
  78014. }
  78015. #endif
  78016. /* exec(args[, options]) -> exitcode */
  78017. static JSValue js_os_exec(JSContext *ctx, JSValueConst this_val,
  78018. int argc, JSValueConst *argv)
  78019. {
  78020. JSValueConst options, args = argv[0];
  78021. JSValue val, ret_val;
  78022. const char **exec_argv, *file = NULL, *str, *cwd = NULL;
  78023. char **envp = environ;
  78024. uint32_t exec_argc, i;
  78025. int ret, pid, status;
  78026. bool block_flag = true, use_path = true;
  78027. static const char *std_name[3] = { "stdin", "stdout", "stderr" };
  78028. int std_fds[3];
  78029. uint32_t uid = -1, gid = -1;
  78030. val = JS_GetPropertyStr(ctx, args, "length");
  78031. if (JS_IsException(val))
  78032. return JS_EXCEPTION;
  78033. ret = JS_ToUint32(ctx, &exec_argc, val);
  78034. JS_FreeValue(ctx, val);
  78035. if (ret)
  78036. return JS_EXCEPTION;
  78037. /* arbitrary limit to avoid overflow */
  78038. if (exec_argc < 1 || exec_argc > 65535) {
  78039. return JS_ThrowTypeError(ctx, "invalid number of arguments");
  78040. }
  78041. exec_argv = js_mallocz(ctx, sizeof(exec_argv[0]) * (exec_argc + 1));
  78042. if (!exec_argv)
  78043. return JS_EXCEPTION;
  78044. for(i = 0; i < exec_argc; i++) {
  78045. val = JS_GetPropertyUint32(ctx, args, i);
  78046. if (JS_IsException(val))
  78047. goto exception;
  78048. str = JS_ToCString(ctx, val);
  78049. JS_FreeValue(ctx, val);
  78050. if (!str)
  78051. goto exception;
  78052. exec_argv[i] = str;
  78053. }
  78054. exec_argv[exec_argc] = NULL;
  78055. for(i = 0; i < 3; i++)
  78056. std_fds[i] = i;
  78057. /* get the options, if any */
  78058. if (argc >= 2) {
  78059. options = argv[1];
  78060. if (get_bool_option(ctx, &block_flag, options, "block"))
  78061. goto exception;
  78062. if (get_bool_option(ctx, &use_path, options, "usePath"))
  78063. goto exception;
  78064. val = JS_GetPropertyStr(ctx, options, "file");
  78065. if (JS_IsException(val))
  78066. goto exception;
  78067. if (!JS_IsUndefined(val)) {
  78068. file = JS_ToCString(ctx, val);
  78069. JS_FreeValue(ctx, val);
  78070. if (!file)
  78071. goto exception;
  78072. }
  78073. val = JS_GetPropertyStr(ctx, options, "cwd");
  78074. if (JS_IsException(val))
  78075. goto exception;
  78076. if (!JS_IsUndefined(val)) {
  78077. cwd = JS_ToCString(ctx, val);
  78078. JS_FreeValue(ctx, val);
  78079. if (!cwd)
  78080. goto exception;
  78081. }
  78082. /* stdin/stdout/stderr handles */
  78083. for(i = 0; i < 3; i++) {
  78084. val = JS_GetPropertyStr(ctx, options, std_name[i]);
  78085. if (JS_IsException(val))
  78086. goto exception;
  78087. if (!JS_IsUndefined(val)) {
  78088. int fd;
  78089. ret = JS_ToInt32(ctx, &fd, val);
  78090. JS_FreeValue(ctx, val);
  78091. if (ret)
  78092. goto exception;
  78093. std_fds[i] = fd;
  78094. }
  78095. }
  78096. val = JS_GetPropertyStr(ctx, options, "env");
  78097. if (JS_IsException(val))
  78098. goto exception;
  78099. if (!JS_IsUndefined(val)) {
  78100. envp = build_envp(ctx, val);
  78101. JS_FreeValue(ctx, val);
  78102. if (!envp)
  78103. goto exception;
  78104. }
  78105. val = JS_GetPropertyStr(ctx, options, "uid");
  78106. if (JS_IsException(val))
  78107. goto exception;
  78108. if (!JS_IsUndefined(val)) {
  78109. ret = JS_ToUint32(ctx, &uid, val);
  78110. JS_FreeValue(ctx, val);
  78111. if (ret)
  78112. goto exception;
  78113. }
  78114. val = JS_GetPropertyStr(ctx, options, "gid");
  78115. if (JS_IsException(val))
  78116. goto exception;
  78117. if (!JS_IsUndefined(val)) {
  78118. ret = JS_ToUint32(ctx, &gid, val);
  78119. JS_FreeValue(ctx, val);
  78120. if (ret)
  78121. goto exception;
  78122. }
  78123. }
  78124. #if !defined(EMSCRIPTEN) && !defined(__wasi__)
  78125. // should happen pre-fork because it calls dlsym()
  78126. // and that's not an async-signal-safe function
  78127. js_once(&js_os_exec_once, js_os_exec_once_init);
  78128. #endif
  78129. pid = fork();
  78130. if (pid < 0) {
  78131. JS_ThrowTypeError(ctx, "fork error");
  78132. goto exception;
  78133. }
  78134. if (pid == 0) {
  78135. /* child */
  78136. /* remap the stdin/stdout/stderr handles if necessary */
  78137. for(i = 0; i < 3; i++) {
  78138. if (std_fds[i] != i) {
  78139. if (dup2(std_fds[i], i) < 0)
  78140. _exit(127);
  78141. }
  78142. }
  78143. if (js_os_exec_closefrom) {
  78144. js_os_exec_closefrom(3);
  78145. } else {
  78146. int fd_max = sysconf(_SC_OPEN_MAX);
  78147. for(i = 3; i < fd_max; i++)
  78148. close(i);
  78149. }
  78150. if (cwd) {
  78151. if (chdir(cwd) < 0)
  78152. _exit(127);
  78153. }
  78154. if (uid != -1) {
  78155. if (setuid(uid) < 0)
  78156. _exit(127);
  78157. }
  78158. if (gid != -1) {
  78159. if (setgid(gid) < 0)
  78160. _exit(127);
  78161. }
  78162. if (!file)
  78163. file = exec_argv[0];
  78164. if (use_path)
  78165. ret = my_execvpe(file, (char **)exec_argv, envp);
  78166. else
  78167. ret = execve(file, (char **)exec_argv, envp);
  78168. _exit(127);
  78169. }
  78170. /* parent */
  78171. if (block_flag) {
  78172. for(;;) {
  78173. ret = waitpid(pid, &status, 0);
  78174. if (ret == pid) {
  78175. if (WIFEXITED(status)) {
  78176. ret = WEXITSTATUS(status);
  78177. break;
  78178. } else if (WIFSIGNALED(status)) {
  78179. ret = -WTERMSIG(status);
  78180. break;
  78181. }
  78182. }
  78183. }
  78184. } else {
  78185. ret = pid;
  78186. }
  78187. ret_val = JS_NewInt32(ctx, ret);
  78188. done:
  78189. JS_FreeCString(ctx, file);
  78190. JS_FreeCString(ctx, cwd);
  78191. for(i = 0; i < exec_argc; i++)
  78192. JS_FreeCString(ctx, exec_argv[i]);
  78193. js_free(ctx, exec_argv);
  78194. if (envp != environ) {
  78195. char **p;
  78196. p = envp;
  78197. while (*p != NULL) {
  78198. js_free(ctx, *p);
  78199. p++;
  78200. }
  78201. js_free(ctx, envp);
  78202. }
  78203. return ret_val;
  78204. exception:
  78205. ret_val = JS_EXCEPTION;
  78206. goto done;
  78207. }
  78208. /* getpid() -> pid */
  78209. static JSValue js_os_getpid(JSContext *ctx, JSValueConst this_val,
  78210. int argc, JSValueConst *argv)
  78211. {
  78212. return JS_NewInt32(ctx, getpid());
  78213. }
  78214. /* waitpid(pid, block) -> [pid, status] */
  78215. static JSValue js_os_waitpid(JSContext *ctx, JSValueConst this_val,
  78216. int argc, JSValueConst *argv)
  78217. {
  78218. int pid, status, options, ret;
  78219. JSValue obj;
  78220. if (JS_ToInt32(ctx, &pid, argv[0]))
  78221. return JS_EXCEPTION;
  78222. if (JS_ToInt32(ctx, &options, argv[1]))
  78223. return JS_EXCEPTION;
  78224. ret = waitpid(pid, &status, options);
  78225. if (ret < 0) {
  78226. ret = -errno;
  78227. status = 0;
  78228. }
  78229. obj = JS_NewArray(ctx);
  78230. if (JS_IsException(obj))
  78231. return obj;
  78232. JS_DefinePropertyValueUint32(ctx, obj, 0, JS_NewInt32(ctx, ret),
  78233. JS_PROP_C_W_E);
  78234. JS_DefinePropertyValueUint32(ctx, obj, 1, JS_NewInt32(ctx, status),
  78235. JS_PROP_C_W_E);
  78236. return obj;
  78237. }
  78238. /* pipe() -> [read_fd, write_fd] or null if error */
  78239. static JSValue js_os_pipe(JSContext *ctx, JSValueConst this_val,
  78240. int argc, JSValueConst *argv)
  78241. {
  78242. int pipe_fds[2], ret;
  78243. JSValue obj;
  78244. ret = pipe(pipe_fds);
  78245. if (ret < 0)
  78246. return JS_NULL;
  78247. obj = JS_NewArray(ctx);
  78248. if (JS_IsException(obj))
  78249. return obj;
  78250. JS_DefinePropertyValueUint32(ctx, obj, 0, JS_NewInt32(ctx, pipe_fds[0]),
  78251. JS_PROP_C_W_E);
  78252. JS_DefinePropertyValueUint32(ctx, obj, 1, JS_NewInt32(ctx, pipe_fds[1]),
  78253. JS_PROP_C_W_E);
  78254. return obj;
  78255. }
  78256. /* kill(pid, sig) */
  78257. static JSValue js_os_kill(JSContext *ctx, JSValueConst this_val,
  78258. int argc, JSValueConst *argv)
  78259. {
  78260. int pid, sig, ret;
  78261. if (JS_ToInt32(ctx, &pid, argv[0]))
  78262. return JS_EXCEPTION;
  78263. if (JS_ToInt32(ctx, &sig, argv[1]))
  78264. return JS_EXCEPTION;
  78265. ret = js_get_errno(kill(pid, sig));
  78266. return JS_NewInt32(ctx, ret);
  78267. }
  78268. /* dup(fd) */
  78269. static JSValue js_os_dup(JSContext *ctx, JSValueConst this_val,
  78270. int argc, JSValueConst *argv)
  78271. {
  78272. int fd, ret;
  78273. if (JS_ToInt32(ctx, &fd, argv[0]))
  78274. return JS_EXCEPTION;
  78275. ret = js_get_errno(dup(fd));
  78276. return JS_NewInt32(ctx, ret);
  78277. }
  78278. /* dup2(fd) */
  78279. static JSValue js_os_dup2(JSContext *ctx, JSValueConst this_val,
  78280. int argc, JSValueConst *argv)
  78281. {
  78282. int fd, fd2, ret;
  78283. if (JS_ToInt32(ctx, &fd, argv[0]))
  78284. return JS_EXCEPTION;
  78285. if (JS_ToInt32(ctx, &fd2, argv[1]))
  78286. return JS_EXCEPTION;
  78287. ret = js_get_errno(dup2(fd, fd2));
  78288. return JS_NewInt32(ctx, ret);
  78289. }
  78290. #endif /* !_WIN32 */
  78291. #ifdef USE_WORKER
  78292. /* Worker */
  78293. typedef struct {
  78294. JSWorkerMessagePipe *recv_pipe;
  78295. JSWorkerMessagePipe *send_pipe;
  78296. JSWorkerMessageHandler *msg_handler;
  78297. } JSWorkerData;
  78298. typedef struct {
  78299. char *filename; /* module filename */
  78300. char *basename; /* module base name */
  78301. JSWorkerMessagePipe *recv_pipe, *send_pipe;
  78302. } WorkerFuncArgs;
  78303. typedef struct {
  78304. int ref_count;
  78305. uint64_t buf[];
  78306. } JSSABHeader;
  78307. static JSContext *(*js_worker_new_context_func)(JSRuntime *rt);
  78308. static int atomic_add_int(int *ptr, int v)
  78309. {
  78310. return atomic_fetch_add((_Atomic uint32_t*)ptr, v) + v;
  78311. }
  78312. /* shared array buffer allocator */
  78313. static void *js_sab_alloc(void *opaque, size_t size)
  78314. {
  78315. JSSABHeader *sab;
  78316. sab = malloc(sizeof(JSSABHeader) + size);
  78317. if (!sab)
  78318. return NULL;
  78319. sab->ref_count = 1;
  78320. return sab->buf;
  78321. }
  78322. static void js_sab_free(void *opaque, void *ptr)
  78323. {
  78324. JSSABHeader *sab;
  78325. int ref_count;
  78326. sab = (JSSABHeader *)((uint8_t *)ptr - sizeof(JSSABHeader));
  78327. ref_count = atomic_add_int(&sab->ref_count, -1);
  78328. assert(ref_count >= 0);
  78329. if (ref_count == 0) {
  78330. free(sab);
  78331. }
  78332. }
  78333. static void js_sab_dup(void *opaque, void *ptr)
  78334. {
  78335. JSSABHeader *sab;
  78336. sab = (JSSABHeader *)((uint8_t *)ptr - sizeof(JSSABHeader));
  78337. atomic_add_int(&sab->ref_count, 1);
  78338. }
  78339. static JSWorkerMessagePipe *js_new_message_pipe(void)
  78340. {
  78341. JSWorkerMessagePipe *ps;
  78342. int pipe_fds[2];
  78343. if (pipe(pipe_fds) < 0)
  78344. return NULL;
  78345. ps = malloc(sizeof(*ps));
  78346. if (!ps) {
  78347. close(pipe_fds[0]);
  78348. close(pipe_fds[1]);
  78349. return NULL;
  78350. }
  78351. ps->ref_count = 1;
  78352. init_list_head(&ps->msg_queue);
  78353. pthread_mutex_init(&ps->mutex, NULL);
  78354. ps->read_fd = pipe_fds[0];
  78355. ps->write_fd = pipe_fds[1];
  78356. return ps;
  78357. }
  78358. static JSWorkerMessagePipe *js_dup_message_pipe(JSWorkerMessagePipe *ps)
  78359. {
  78360. atomic_add_int(&ps->ref_count, 1);
  78361. return ps;
  78362. }
  78363. static void js_free_message(JSWorkerMessage *msg)
  78364. {
  78365. size_t i;
  78366. /* free the SAB */
  78367. for(i = 0; i < msg->sab_tab_len; i++) {
  78368. js_sab_free(NULL, msg->sab_tab[i]);
  78369. }
  78370. free(msg->sab_tab);
  78371. free(msg->data);
  78372. free(msg);
  78373. }
  78374. static void js_free_message_pipe(JSWorkerMessagePipe *ps)
  78375. {
  78376. struct list_head *el, *el1;
  78377. JSWorkerMessage *msg;
  78378. int ref_count;
  78379. if (!ps)
  78380. return;
  78381. ref_count = atomic_add_int(&ps->ref_count, -1);
  78382. assert(ref_count >= 0);
  78383. if (ref_count == 0) {
  78384. list_for_each_safe(el, el1, &ps->msg_queue) {
  78385. msg = list_entry(el, JSWorkerMessage, link);
  78386. js_free_message(msg);
  78387. }
  78388. pthread_mutex_destroy(&ps->mutex);
  78389. close(ps->read_fd);
  78390. close(ps->write_fd);
  78391. free(ps);
  78392. }
  78393. }
  78394. static void js_free_port(JSRuntime *rt, JSWorkerMessageHandler *port)
  78395. {
  78396. if (port) {
  78397. js_free_message_pipe(port->recv_pipe);
  78398. JS_FreeValueRT(rt, port->on_message_func);
  78399. list_del(&port->link);
  78400. js_free_rt(rt, port);
  78401. }
  78402. }
  78403. static void js_worker_finalizer(JSRuntime *rt, JSValueConst val)
  78404. {
  78405. JSThreadState *ts = js_get_thread_state(rt);
  78406. JSWorkerData *worker = JS_GetOpaque(val, ts->worker_class_id);
  78407. if (worker) {
  78408. js_free_message_pipe(worker->recv_pipe);
  78409. js_free_message_pipe(worker->send_pipe);
  78410. js_free_port(rt, worker->msg_handler);
  78411. js_free_rt(rt, worker);
  78412. }
  78413. }
  78414. static JSClassDef js_worker_class = {
  78415. "Worker",
  78416. .finalizer = js_worker_finalizer,
  78417. };
  78418. static void *worker_func(void *opaque)
  78419. {
  78420. WorkerFuncArgs *args = opaque;
  78421. JSRuntime *rt;
  78422. JSThreadState *ts;
  78423. JSContext *ctx;
  78424. JSValue val;
  78425. rt = JS_NewRuntime();
  78426. if (rt == NULL) {
  78427. fprintf(stderr, "JS_NewRuntime failure");
  78428. exit(1);
  78429. }
  78430. js_std_init_handlers(rt);
  78431. JS_SetModuleLoaderFunc(rt, NULL, js_module_loader, NULL);
  78432. /* set the pipe to communicate with the parent */
  78433. ts = js_get_thread_state(rt);
  78434. ts->recv_pipe = args->recv_pipe;
  78435. ts->send_pipe = args->send_pipe;
  78436. /* function pointer to avoid linking the whole JS_NewContext() if
  78437. not needed */
  78438. ctx = js_worker_new_context_func(rt);
  78439. if (ctx == NULL) {
  78440. fprintf(stderr, "JS_NewContext failure");
  78441. }
  78442. JS_SetCanBlock(rt, true);
  78443. js_std_add_helpers(ctx, -1, NULL);
  78444. val = JS_LoadModule(ctx, args->basename, args->filename);
  78445. free(args->filename);
  78446. free(args->basename);
  78447. free(args);
  78448. val = js_std_await(ctx, val);
  78449. if (JS_IsException(val))
  78450. js_std_dump_error(ctx);
  78451. JS_FreeValue(ctx, val);
  78452. js_std_loop(ctx);
  78453. js_std_free_handlers(rt);
  78454. JS_FreeContext(ctx);
  78455. JS_FreeRuntime(rt);
  78456. return NULL;
  78457. }
  78458. static JSValue js_worker_ctor_internal(JSContext *ctx, JSValueConst new_target,
  78459. JSWorkerMessagePipe *recv_pipe,
  78460. JSWorkerMessagePipe *send_pipe)
  78461. {
  78462. JSRuntime *rt = JS_GetRuntime(ctx);
  78463. JSThreadState *ts = js_get_thread_state(rt);
  78464. JSValue obj = JS_UNDEFINED, proto;
  78465. JSWorkerData *s;
  78466. /* create the object */
  78467. if (JS_IsUndefined(new_target)) {
  78468. proto = JS_GetClassProto(ctx, ts->worker_class_id);
  78469. } else {
  78470. proto = JS_GetPropertyStr(ctx, new_target, "prototype");
  78471. if (JS_IsException(proto))
  78472. goto fail;
  78473. }
  78474. obj = JS_NewObjectProtoClass(ctx, proto, ts->worker_class_id);
  78475. JS_FreeValue(ctx, proto);
  78476. if (JS_IsException(obj))
  78477. goto fail;
  78478. s = js_mallocz(ctx, sizeof(*s));
  78479. if (!s)
  78480. goto fail;
  78481. s->recv_pipe = js_dup_message_pipe(recv_pipe);
  78482. s->send_pipe = js_dup_message_pipe(send_pipe);
  78483. JS_SetOpaque(obj, s);
  78484. return obj;
  78485. fail:
  78486. JS_FreeValue(ctx, obj);
  78487. return JS_EXCEPTION;
  78488. }
  78489. static JSValue js_worker_ctor(JSContext *ctx, JSValueConst new_target,
  78490. int argc, JSValueConst *argv)
  78491. {
  78492. JSRuntime *rt = JS_GetRuntime(ctx);
  78493. WorkerFuncArgs *args = NULL;
  78494. pthread_t tid;
  78495. pthread_attr_t attr;
  78496. JSValue obj = JS_UNDEFINED;
  78497. int ret;
  78498. const char *filename = NULL, *basename;
  78499. JSAtom basename_atom;
  78500. /* XXX: in order to avoid problems with resource liberation, we
  78501. don't support creating workers inside workers */
  78502. if (!is_main_thread(rt))
  78503. return JS_ThrowTypeError(ctx, "cannot create a worker inside a worker");
  78504. /* base name, assuming the calling function is a normal JS
  78505. function */
  78506. basename_atom = JS_GetScriptOrModuleName(ctx, 1);
  78507. if (basename_atom == JS_ATOM_NULL) {
  78508. return JS_ThrowTypeError(ctx, "could not determine calling script or module name");
  78509. }
  78510. basename = JS_AtomToCString(ctx, basename_atom);
  78511. JS_FreeAtom(ctx, basename_atom);
  78512. if (!basename)
  78513. goto fail;
  78514. /* module name */
  78515. filename = JS_ToCString(ctx, argv[0]);
  78516. if (!filename)
  78517. goto fail;
  78518. args = malloc(sizeof(*args));
  78519. if (!args)
  78520. goto oom_fail;
  78521. memset(args, 0, sizeof(*args));
  78522. args->filename = strdup(filename);
  78523. args->basename = strdup(basename);
  78524. /* ports */
  78525. args->recv_pipe = js_new_message_pipe();
  78526. if (!args->recv_pipe)
  78527. goto oom_fail;
  78528. args->send_pipe = js_new_message_pipe();
  78529. if (!args->send_pipe)
  78530. goto oom_fail;
  78531. obj = js_worker_ctor_internal(ctx, new_target,
  78532. args->send_pipe, args->recv_pipe);
  78533. if (JS_IsException(obj))
  78534. goto fail;
  78535. pthread_attr_init(&attr);
  78536. /* no join at the end */
  78537. pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  78538. // musl libc gives threads 80 kb stacks, much smaller than
  78539. // JS_DEFAULT_STACK_SIZE (1 MB)
  78540. pthread_attr_setstacksize(&attr, 2 << 20); // 2 MB, glibc default
  78541. ret = pthread_create(&tid, &attr, worker_func, args);
  78542. pthread_attr_destroy(&attr);
  78543. if (ret != 0) {
  78544. JS_ThrowTypeError(ctx, "could not create worker");
  78545. goto fail;
  78546. }
  78547. JS_FreeCString(ctx, basename);
  78548. JS_FreeCString(ctx, filename);
  78549. return obj;
  78550. oom_fail:
  78551. JS_ThrowOutOfMemory(ctx);
  78552. fail:
  78553. JS_FreeCString(ctx, basename);
  78554. JS_FreeCString(ctx, filename);
  78555. if (args) {
  78556. free(args->filename);
  78557. free(args->basename);
  78558. js_free_message_pipe(args->recv_pipe);
  78559. js_free_message_pipe(args->send_pipe);
  78560. free(args);
  78561. }
  78562. JS_FreeValue(ctx, obj);
  78563. return JS_EXCEPTION;
  78564. }
  78565. static JSValue js_worker_postMessage(JSContext *ctx, JSValueConst this_val,
  78566. int argc, JSValueConst *argv)
  78567. {
  78568. JSRuntime *rt = JS_GetRuntime(ctx);
  78569. JSThreadState *ts = js_get_thread_state(rt);
  78570. JSWorkerData *worker = JS_GetOpaque2(ctx, this_val, ts->worker_class_id);
  78571. JSWorkerMessagePipe *ps;
  78572. size_t data_len, i;
  78573. uint8_t *data;
  78574. JSWorkerMessage *msg;
  78575. JSSABTab sab_tab;
  78576. if (!worker)
  78577. return JS_EXCEPTION;
  78578. data = JS_WriteObject2(ctx, &data_len, argv[0],
  78579. JS_WRITE_OBJ_SAB | JS_WRITE_OBJ_REFERENCE,
  78580. &sab_tab);
  78581. if (!data)
  78582. return JS_EXCEPTION;
  78583. msg = malloc(sizeof(*msg));
  78584. if (!msg)
  78585. goto fail;
  78586. msg->data = NULL;
  78587. msg->sab_tab = NULL;
  78588. /* must reallocate because the allocator may be different */
  78589. msg->data = malloc(data_len);
  78590. if (!msg->data)
  78591. goto fail;
  78592. memcpy(msg->data, data, data_len);
  78593. msg->data_len = data_len;
  78594. if (sab_tab.len > 0) {
  78595. msg->sab_tab = malloc(sizeof(msg->sab_tab[0]) * sab_tab.len);
  78596. if (!msg->sab_tab)
  78597. goto fail;
  78598. memcpy(msg->sab_tab, sab_tab.tab, sizeof(msg->sab_tab[0]) * sab_tab.len);
  78599. }
  78600. msg->sab_tab_len = sab_tab.len;
  78601. js_free(ctx, data);
  78602. js_free(ctx, sab_tab.tab);
  78603. /* increment the SAB reference counts */
  78604. for(i = 0; i < msg->sab_tab_len; i++) {
  78605. js_sab_dup(NULL, msg->sab_tab[i]);
  78606. }
  78607. ps = worker->send_pipe;
  78608. pthread_mutex_lock(&ps->mutex);
  78609. /* indicate that data is present */
  78610. if (list_empty(&ps->msg_queue)) {
  78611. uint8_t ch = '\0';
  78612. int ret;
  78613. for(;;) {
  78614. ret = write(ps->write_fd, &ch, 1);
  78615. if (ret == 1)
  78616. break;
  78617. if (ret < 0 && (errno != EAGAIN || errno != EINTR))
  78618. break;
  78619. }
  78620. }
  78621. list_add_tail(&msg->link, &ps->msg_queue);
  78622. pthread_mutex_unlock(&ps->mutex);
  78623. return JS_UNDEFINED;
  78624. fail:
  78625. if (msg) {
  78626. free(msg->data);
  78627. free(msg->sab_tab);
  78628. free(msg);
  78629. }
  78630. js_free(ctx, data);
  78631. js_free(ctx, sab_tab.tab);
  78632. return JS_EXCEPTION;
  78633. }
  78634. static JSValue js_worker_set_onmessage(JSContext *ctx, JSValueConst this_val,
  78635. JSValueConst func)
  78636. {
  78637. JSRuntime *rt = JS_GetRuntime(ctx);
  78638. JSThreadState *ts = js_get_thread_state(rt);
  78639. JSWorkerData *worker = JS_GetOpaque2(ctx, this_val, ts->worker_class_id);
  78640. JSWorkerMessageHandler *port;
  78641. if (!worker)
  78642. return JS_EXCEPTION;
  78643. port = worker->msg_handler;
  78644. if (JS_IsNull(func)) {
  78645. if (port) {
  78646. js_free_port(rt, port);
  78647. worker->msg_handler = NULL;
  78648. }
  78649. } else {
  78650. if (!JS_IsFunction(ctx, func))
  78651. return JS_ThrowTypeError(ctx, "not a function");
  78652. if (!port) {
  78653. port = js_mallocz(ctx, sizeof(*port));
  78654. if (!port)
  78655. return JS_EXCEPTION;
  78656. port->recv_pipe = js_dup_message_pipe(worker->recv_pipe);
  78657. port->on_message_func = JS_NULL;
  78658. list_add_tail(&port->link, &ts->port_list);
  78659. worker->msg_handler = port;
  78660. }
  78661. JS_FreeValue(ctx, port->on_message_func);
  78662. port->on_message_func = JS_DupValue(ctx, func);
  78663. }
  78664. return JS_UNDEFINED;
  78665. }
  78666. static JSValue js_worker_get_onmessage(JSContext *ctx, JSValueConst this_val)
  78667. {
  78668. JSRuntime *rt = JS_GetRuntime(ctx);
  78669. JSThreadState *ts = js_get_thread_state(rt);
  78670. JSWorkerData *worker = JS_GetOpaque2(ctx, this_val, ts->worker_class_id);
  78671. JSWorkerMessageHandler *port;
  78672. if (!worker)
  78673. return JS_EXCEPTION;
  78674. port = worker->msg_handler;
  78675. if (port) {
  78676. return JS_DupValue(ctx, port->on_message_func);
  78677. } else {
  78678. return JS_NULL;
  78679. }
  78680. }
  78681. static const JSCFunctionListEntry js_worker_proto_funcs[] = {
  78682. JS_CFUNC_DEF("postMessage", 1, js_worker_postMessage ),
  78683. JS_CGETSET_DEF("onmessage", js_worker_get_onmessage, js_worker_set_onmessage ),
  78684. };
  78685. #endif /* USE_WORKER */
  78686. void js_std_set_worker_new_context_func(JSContext *(*func)(JSRuntime *rt))
  78687. {
  78688. #ifdef USE_WORKER
  78689. js_worker_new_context_func = func;
  78690. #endif
  78691. }
  78692. #if defined(_WIN32)
  78693. #define OS_PLATFORM "win32"
  78694. #elif defined(__APPLE__)
  78695. #define OS_PLATFORM "darwin"
  78696. #elif defined(EMSCRIPTEN)
  78697. #define OS_PLATFORM "js"
  78698. #elif defined(__CYGWIN__)
  78699. #define OS_PLATFORM "cygwin"
  78700. #elif defined(__linux__)
  78701. #define OS_PLATFORM "linux"
  78702. #elif defined(__OpenBSD__)
  78703. #define OS_PLATFORM "openbsd"
  78704. #elif defined(__NetBSD__)
  78705. #define OS_PLATFORM "netbsd"
  78706. #elif defined(__FreeBSD__)
  78707. #define OS_PLATFORM "freebsd"
  78708. #elif defined(__wasi__)
  78709. #define OS_PLATFORM "wasi"
  78710. #else
  78711. #define OS_PLATFORM "unknown"
  78712. #endif
  78713. #define OS_FLAG(x) JS_PROP_INT32_DEF(#x, x, JS_PROP_CONFIGURABLE )
  78714. static const JSCFunctionListEntry js_os_funcs[] = {
  78715. JS_CFUNC_DEF("open", 2, js_os_open ),
  78716. OS_FLAG(O_RDONLY),
  78717. OS_FLAG(O_WRONLY),
  78718. OS_FLAG(O_RDWR),
  78719. OS_FLAG(O_APPEND),
  78720. OS_FLAG(O_CREAT),
  78721. OS_FLAG(O_EXCL),
  78722. OS_FLAG(O_TRUNC),
  78723. #if defined(_WIN32)
  78724. OS_FLAG(O_BINARY),
  78725. OS_FLAG(O_TEXT),
  78726. #endif
  78727. JS_CFUNC_DEF("close", 1, js_os_close ),
  78728. JS_CFUNC_DEF("seek", 3, js_os_seek ),
  78729. JS_CFUNC_MAGIC_DEF("read", 4, js_os_read_write, 0 ),
  78730. JS_CFUNC_MAGIC_DEF("write", 4, js_os_read_write, 1 ),
  78731. JS_CFUNC_DEF("isatty", 1, js_os_isatty ),
  78732. #if !defined(__wasi__)
  78733. JS_CFUNC_DEF("ttyGetWinSize", 1, js_os_ttyGetWinSize ),
  78734. JS_CFUNC_DEF("ttySetRaw", 1, js_os_ttySetRaw ),
  78735. #endif
  78736. JS_CFUNC_DEF("remove", 1, js_os_remove ),
  78737. JS_CFUNC_DEF("rename", 2, js_os_rename ),
  78738. JS_CFUNC_MAGIC_DEF("setReadHandler", 2, js_os_setReadHandler, 0 ),
  78739. JS_CFUNC_MAGIC_DEF("setWriteHandler", 2, js_os_setReadHandler, 1 ),
  78740. JS_CFUNC_DEF("signal", 2, js_os_signal ),
  78741. OS_FLAG(SIGINT),
  78742. OS_FLAG(SIGABRT),
  78743. OS_FLAG(SIGFPE),
  78744. OS_FLAG(SIGILL),
  78745. OS_FLAG(SIGSEGV),
  78746. OS_FLAG(SIGTERM),
  78747. #if !defined(_WIN32) && !defined(__wasi__)
  78748. OS_FLAG(SIGQUIT),
  78749. OS_FLAG(SIGPIPE),
  78750. OS_FLAG(SIGALRM),
  78751. OS_FLAG(SIGUSR1),
  78752. OS_FLAG(SIGUSR2),
  78753. OS_FLAG(SIGCHLD),
  78754. OS_FLAG(SIGCONT),
  78755. OS_FLAG(SIGSTOP),
  78756. OS_FLAG(SIGTSTP),
  78757. OS_FLAG(SIGTTIN),
  78758. OS_FLAG(SIGTTOU),
  78759. JS_CFUNC_DEF("cputime", 0, js_os_cputime ),
  78760. #endif
  78761. JS_CFUNC_DEF("now", 0, js_os_now ),
  78762. JS_CFUNC_MAGIC_DEF("setTimeout", 2, js_os_setTimeout, 0 ),
  78763. JS_CFUNC_MAGIC_DEF("setInterval", 2, js_os_setTimeout, 1 ),
  78764. // per spec: both functions can cancel timeouts and intervals
  78765. JS_CFUNC_DEF("clearTimeout", 1, js_os_clearTimeout ),
  78766. JS_CFUNC_DEF("clearInterval", 1, js_os_clearTimeout ),
  78767. JS_CFUNC_DEF("sleepAsync", 1, js_os_sleepAsync ),
  78768. JS_PROP_STRING_DEF("platform", OS_PLATFORM, 0 ),
  78769. JS_CFUNC_DEF("getcwd", 0, js_os_getcwd ),
  78770. JS_CFUNC_DEF("chdir", 0, js_os_chdir ),
  78771. JS_CFUNC_DEF("mkdir", 1, js_os_mkdir ),
  78772. JS_CFUNC_DEF("readdir", 1, js_os_readdir ),
  78773. /* st_mode constants */
  78774. OS_FLAG(S_IFMT),
  78775. OS_FLAG(S_IFIFO),
  78776. OS_FLAG(S_IFCHR),
  78777. OS_FLAG(S_IFDIR),
  78778. OS_FLAG(S_IFBLK),
  78779. OS_FLAG(S_IFREG),
  78780. #if !defined(_WIN32)
  78781. OS_FLAG(S_IFSOCK),
  78782. OS_FLAG(S_IFLNK),
  78783. OS_FLAG(S_ISGID),
  78784. OS_FLAG(S_ISUID),
  78785. #endif
  78786. JS_CFUNC_MAGIC_DEF("stat", 1, js_os_stat, 0 ),
  78787. JS_CFUNC_DEF("utimes", 3, js_os_utimes ),
  78788. JS_CFUNC_DEF("sleep", 1, js_os_sleep ),
  78789. #if !defined(__wasi__)
  78790. JS_CFUNC_DEF("realpath", 1, js_os_realpath ),
  78791. #endif
  78792. #if !defined(_WIN32) && !defined(__wasi__)
  78793. JS_CFUNC_MAGIC_DEF("lstat", 1, js_os_stat, 1 ),
  78794. JS_CFUNC_DEF("symlink", 2, js_os_symlink ),
  78795. JS_CFUNC_DEF("readlink", 1, js_os_readlink ),
  78796. JS_CFUNC_DEF("exec", 1, js_os_exec ),
  78797. JS_CFUNC_DEF("getpid", 0, js_os_getpid ),
  78798. JS_CFUNC_DEF("waitpid", 2, js_os_waitpid ),
  78799. OS_FLAG(WNOHANG),
  78800. JS_CFUNC_DEF("pipe", 0, js_os_pipe ),
  78801. JS_CFUNC_DEF("kill", 2, js_os_kill ),
  78802. JS_CFUNC_DEF("dup", 1, js_os_dup ),
  78803. JS_CFUNC_DEF("dup2", 2, js_os_dup2 ),
  78804. #endif
  78805. };
  78806. static int js_os_init(JSContext *ctx, JSModuleDef *m)
  78807. {
  78808. JSRuntime *rt = JS_GetRuntime(ctx);
  78809. JSThreadState *ts = js_get_thread_state(rt);
  78810. ts->can_js_os_poll = true;
  78811. #ifdef USE_WORKER
  78812. {
  78813. JSValue proto, obj;
  78814. /* Worker class */
  78815. JS_NewClassID(rt, &ts->worker_class_id);
  78816. JS_NewClass(rt, ts->worker_class_id, &js_worker_class);
  78817. proto = JS_NewObject(ctx);
  78818. JS_SetPropertyFunctionList(ctx, proto, js_worker_proto_funcs, countof(js_worker_proto_funcs));
  78819. obj = JS_NewCFunction2(ctx, js_worker_ctor, "Worker", 1,
  78820. JS_CFUNC_constructor, 0);
  78821. JS_SetConstructor(ctx, obj, proto);
  78822. JS_SetClassProto(ctx, ts->worker_class_id, proto);
  78823. /* set 'Worker.parent' if necessary */
  78824. if (ts->recv_pipe && ts->send_pipe) {
  78825. JS_DefinePropertyValueStr(ctx, obj, "parent",
  78826. js_worker_ctor_internal(ctx, JS_UNDEFINED, ts->recv_pipe, ts->send_pipe),
  78827. JS_PROP_C_W_E);
  78828. }
  78829. JS_SetModuleExport(ctx, m, "Worker", obj);
  78830. }
  78831. #endif /* USE_WORKER */
  78832. return JS_SetModuleExportList(ctx, m, js_os_funcs, countof(js_os_funcs));
  78833. }
  78834. JSModuleDef *js_init_module_os(JSContext *ctx, const char *module_name)
  78835. {
  78836. JSModuleDef *m;
  78837. m = JS_NewCModule(ctx, module_name, js_os_init);
  78838. if (!m)
  78839. return NULL;
  78840. JS_AddModuleExportList(ctx, m, js_os_funcs, countof(js_os_funcs));
  78841. #ifdef USE_WORKER
  78842. JS_AddModuleExport(ctx, m, "Worker");
  78843. #endif
  78844. return m;
  78845. }
  78846. /**********************************************************/
  78847. static JSValue js_print(JSContext *ctx, JSValueConst this_val,
  78848. int argc, JSValueConst *argv)
  78849. {
  78850. #ifdef _WIN32
  78851. HANDLE handle;
  78852. DWORD mode;
  78853. #endif
  78854. const char *s;
  78855. JSValueConst v;
  78856. DynBuf b;
  78857. int i;
  78858. dbuf_init(&b);
  78859. for(i = 0; i < argc; i++) {
  78860. v = argv[i];
  78861. s = JS_ToCString(ctx, v);
  78862. if (!s && JS_IsObject(v)) {
  78863. JS_FreeValue(ctx, JS_GetException(ctx));
  78864. JSValue t = JS_ToObjectString(ctx, v);
  78865. s = JS_ToCString(ctx, t);
  78866. JS_FreeValue(ctx, t);
  78867. }
  78868. if (s) {
  78869. dbuf_printf(&b, "%s%s", &" "[!i], s);
  78870. JS_FreeCString(ctx, s);
  78871. } else {
  78872. dbuf_printf(&b, "%s<exception>", &" "[!i]);
  78873. JS_FreeValue(ctx, JS_GetException(ctx));
  78874. }
  78875. }
  78876. dbuf_putc(&b, '\n');
  78877. #ifdef _WIN32
  78878. // use WriteConsoleA with CP_UTF8 for better Unicode handling vis-a-vis
  78879. // the mangling that happens when going through msvcrt's stdio layer,
  78880. // *except* when stdout is redirected to something that is not a console
  78881. handle = (HANDLE)_get_osfhandle(/*STDOUT_FILENO*/1); // don't CloseHandle
  78882. if (GetFileType(handle) != FILE_TYPE_CHAR)
  78883. goto fallback;
  78884. if (!GetConsoleMode(handle, &mode))
  78885. goto fallback;
  78886. handle = GetStdHandle(STD_OUTPUT_HANDLE);
  78887. if (handle == INVALID_HANDLE_VALUE)
  78888. goto fallback;
  78889. mode = GetConsoleOutputCP();
  78890. SetConsoleOutputCP(CP_UTF8);
  78891. WriteConsoleA(handle, b.buf, b.size, NULL, NULL);
  78892. SetConsoleOutputCP(mode);
  78893. FlushFileBuffers(handle);
  78894. goto done;
  78895. fallback:
  78896. #endif
  78897. fwrite(b.buf, 1, b.size, stdout);
  78898. fflush(stdout);
  78899. goto done; // avoid unused label warning
  78900. done:
  78901. dbuf_free(&b);
  78902. return JS_UNDEFINED;
  78903. }
  78904. void js_std_add_helpers(JSContext *ctx, int argc, char **argv)
  78905. {
  78906. JSValue global_obj, console, args;
  78907. int i;
  78908. /* XXX: should these global definitions be enumerable? */
  78909. global_obj = JS_GetGlobalObject(ctx);
  78910. console = JS_NewObject(ctx);
  78911. JS_SetPropertyStr(ctx, console, "log",
  78912. JS_NewCFunction(ctx, js_print, "log", 1));
  78913. JS_SetPropertyStr(ctx, global_obj, "console", console);
  78914. /* same methods as the mozilla JS shell */
  78915. if (argc >= 0) {
  78916. args = JS_NewArray(ctx);
  78917. for(i = 0; i < argc; i++) {
  78918. JS_SetPropertyUint32(ctx, args, i, JS_NewString(ctx, argv[i]));
  78919. }
  78920. JS_SetPropertyStr(ctx, global_obj, "scriptArgs", args);
  78921. }
  78922. JS_SetPropertyStr(ctx, global_obj, "print",
  78923. JS_NewCFunction(ctx, js_print, "print", 1));
  78924. JS_FreeValue(ctx, global_obj);
  78925. }
  78926. static void js_std_finalize(JSRuntime *rt, void *arg)
  78927. {
  78928. JSThreadState *ts = arg;
  78929. js_set_thread_state(rt, NULL);
  78930. js_free_rt(rt, ts);
  78931. }
  78932. void js_std_init_handlers(JSRuntime *rt)
  78933. {
  78934. JSThreadState *ts;
  78935. ts = js_mallocz_rt(rt, sizeof(*ts));
  78936. if (!ts) {
  78937. fprintf(stderr, "Could not allocate memory for the worker");
  78938. exit(1);
  78939. }
  78940. init_list_head(&ts->os_rw_handlers);
  78941. init_list_head(&ts->os_signal_handlers);
  78942. init_list_head(&ts->os_timers);
  78943. init_list_head(&ts->port_list);
  78944. ts->next_timer_id = 1;
  78945. js_set_thread_state(rt, ts);
  78946. JS_AddRuntimeFinalizer(rt, js_std_finalize, ts);
  78947. #ifdef USE_WORKER
  78948. /* set the SharedArrayBuffer memory handlers */
  78949. {
  78950. JSSharedArrayBufferFunctions sf;
  78951. memset(&sf, 0, sizeof(sf));
  78952. sf.sab_alloc = js_sab_alloc;
  78953. sf.sab_free = js_sab_free;
  78954. sf.sab_dup = js_sab_dup;
  78955. JS_SetSharedArrayBufferFunctions(rt, &sf);
  78956. }
  78957. #endif
  78958. }
  78959. void js_std_free_handlers(JSRuntime *rt)
  78960. {
  78961. JSThreadState *ts = js_get_thread_state(rt);
  78962. struct list_head *el, *el1;
  78963. list_for_each_safe(el, el1, &ts->os_rw_handlers) {
  78964. JSOSRWHandler *rh = list_entry(el, JSOSRWHandler, link);
  78965. free_rw_handler(rt, rh);
  78966. }
  78967. list_for_each_safe(el, el1, &ts->os_signal_handlers) {
  78968. JSOSSignalHandler *sh = list_entry(el, JSOSSignalHandler, link);
  78969. free_sh(rt, sh);
  78970. }
  78971. list_for_each_safe(el, el1, &ts->os_timers) {
  78972. JSOSTimer *th = list_entry(el, JSOSTimer, link);
  78973. free_timer(rt, th);
  78974. }
  78975. #ifdef USE_WORKER
  78976. /* XXX: free port_list ? */
  78977. js_free_message_pipe(ts->recv_pipe);
  78978. js_free_message_pipe(ts->send_pipe);
  78979. #endif
  78980. }
  78981. static void js_dump_obj(JSContext *ctx, FILE *f, JSValueConst val)
  78982. {
  78983. const char *str;
  78984. str = JS_ToCString(ctx, val);
  78985. if (str) {
  78986. fprintf(f, "%s\n", str);
  78987. JS_FreeCString(ctx, str);
  78988. } else {
  78989. fprintf(f, "[exception]\n");
  78990. }
  78991. }
  78992. static void js_std_dump_error1(JSContext *ctx, JSValueConst exception_val)
  78993. {
  78994. JSValue val;
  78995. bool is_error;
  78996. is_error = JS_IsError(ctx, exception_val);
  78997. js_dump_obj(ctx, stderr, exception_val);
  78998. if (is_error) {
  78999. val = JS_GetPropertyStr(ctx, exception_val, "stack");
  79000. } else {
  79001. js_std_cmd(/*ErrorBackTrace*/2, ctx, &val);
  79002. }
  79003. if (!JS_IsUndefined(val)) {
  79004. js_dump_obj(ctx, stderr, val);
  79005. JS_FreeValue(ctx, val);
  79006. }
  79007. }
  79008. void js_std_dump_error(JSContext *ctx)
  79009. {
  79010. JSValue exception_val;
  79011. exception_val = JS_GetException(ctx);
  79012. js_std_dump_error1(ctx, exception_val);
  79013. JS_FreeValue(ctx, exception_val);
  79014. }
  79015. void js_std_promise_rejection_tracker(JSContext *ctx, JSValueConst promise,
  79016. JSValueConst reason,
  79017. bool is_handled, void *opaque)
  79018. {
  79019. if (!is_handled) {
  79020. fprintf(stderr, "Possibly unhandled promise rejection: ");
  79021. js_std_dump_error1(ctx, reason);
  79022. fflush(stderr);
  79023. exit(1);
  79024. }
  79025. }
  79026. /* main loop which calls the user JS callbacks */
  79027. int js_std_loop(JSContext *ctx)
  79028. {
  79029. JSRuntime *rt = JS_GetRuntime(ctx);
  79030. JSThreadState *ts = js_get_thread_state(rt);
  79031. JSContext *ctx1;
  79032. int err;
  79033. for(;;) {
  79034. /* execute the pending jobs */
  79035. for(;;) {
  79036. err = JS_ExecutePendingJob(JS_GetRuntime(ctx), &ctx1);
  79037. if (err <= 0) {
  79038. if (err < 0)
  79039. goto done;
  79040. break;
  79041. }
  79042. }
  79043. if (!ts->can_js_os_poll || js_os_poll(ctx))
  79044. break;
  79045. }
  79046. done:
  79047. return JS_HasException(ctx);
  79048. }
  79049. /* Wait for a promise and execute pending jobs while waiting for
  79050. it. Return the promise result or JS_EXCEPTION in case of promise
  79051. rejection. */
  79052. JSValue js_std_await(JSContext *ctx, JSValue obj)
  79053. {
  79054. JSRuntime *rt = JS_GetRuntime(ctx);
  79055. JSThreadState *ts = js_get_thread_state(rt);
  79056. JSValue ret;
  79057. int state;
  79058. for(;;) {
  79059. state = JS_PromiseState(ctx, obj);
  79060. if (state == JS_PROMISE_FULFILLED) {
  79061. ret = JS_PromiseResult(ctx, obj);
  79062. JS_FreeValue(ctx, obj);
  79063. break;
  79064. } else if (state == JS_PROMISE_REJECTED) {
  79065. ret = JS_Throw(ctx, JS_PromiseResult(ctx, obj));
  79066. JS_FreeValue(ctx, obj);
  79067. break;
  79068. } else if (state == JS_PROMISE_PENDING) {
  79069. JSContext *ctx1;
  79070. int err;
  79071. err = JS_ExecutePendingJob(JS_GetRuntime(ctx), &ctx1);
  79072. if (err < 0) {
  79073. js_std_dump_error(ctx1);
  79074. }
  79075. if (ts->can_js_os_poll)
  79076. js_os_poll(ctx);
  79077. } else {
  79078. /* not a promise */
  79079. ret = obj;
  79080. break;
  79081. }
  79082. }
  79083. return ret;
  79084. }
  79085. void js_std_eval_binary(JSContext *ctx, const uint8_t *buf, size_t buf_len,
  79086. int load_only)
  79087. {
  79088. JSValue obj, val;
  79089. obj = JS_ReadObject(ctx, buf, buf_len, JS_READ_OBJ_BYTECODE);
  79090. if (JS_IsException(obj))
  79091. goto exception;
  79092. if (load_only) {
  79093. if (JS_VALUE_GET_TAG(obj) == JS_TAG_MODULE) {
  79094. if (js_module_set_import_meta(ctx, obj, false, false) < 0)
  79095. goto exception;
  79096. }
  79097. } else {
  79098. if (JS_VALUE_GET_TAG(obj) == JS_TAG_MODULE) {
  79099. if (JS_ResolveModule(ctx, obj) < 0) {
  79100. JS_FreeValue(ctx, obj);
  79101. goto exception;
  79102. }
  79103. if (js_module_set_import_meta(ctx, obj, false, true) < 0)
  79104. goto exception;
  79105. val = JS_EvalFunction(ctx, obj);
  79106. val = js_std_await(ctx, val);
  79107. } else {
  79108. val = JS_EvalFunction(ctx, obj);
  79109. }
  79110. if (JS_IsException(val)) {
  79111. exception:
  79112. js_std_dump_error(ctx);
  79113. exit(1);
  79114. }
  79115. JS_FreeValue(ctx, val);
  79116. }
  79117. }
  79118. static JSValue js_bjson_read(JSContext *ctx, JSValueConst this_val,
  79119. int argc, JSValueConst *argv)
  79120. {
  79121. uint8_t *buf;
  79122. uint64_t pos, len;
  79123. JSValue obj;
  79124. size_t size;
  79125. int flags;
  79126. if (JS_ToIndex(ctx, &pos, argv[1]))
  79127. return JS_EXCEPTION;
  79128. if (JS_ToIndex(ctx, &len, argv[2]))
  79129. return JS_EXCEPTION;
  79130. if (JS_ToInt32(ctx, &flags, argv[3]))
  79131. return JS_EXCEPTION;
  79132. buf = JS_GetArrayBuffer(ctx, &size, argv[0]);
  79133. if (!buf)
  79134. return JS_EXCEPTION;
  79135. if (pos + len > size)
  79136. return JS_ThrowRangeError(ctx, "array buffer overflow");
  79137. obj = JS_ReadObject(ctx, buf + pos, len, flags);
  79138. return obj;
  79139. }
  79140. static JSValue js_bjson_write(JSContext *ctx, JSValueConst this_val,
  79141. int argc, JSValueConst *argv)
  79142. {
  79143. size_t len;
  79144. uint8_t *buf;
  79145. JSValue array;
  79146. int flags;
  79147. if (JS_ToInt32(ctx, &flags, argv[1]))
  79148. return JS_EXCEPTION;
  79149. buf = JS_WriteObject(ctx, &len, argv[0], flags);
  79150. if (!buf)
  79151. return JS_EXCEPTION;
  79152. array = JS_NewArrayBufferCopy(ctx, buf, len);
  79153. js_free(ctx, buf);
  79154. return array;
  79155. }
  79156. static const JSCFunctionListEntry js_bjson_funcs[] = {
  79157. JS_CFUNC_DEF("read", 4, js_bjson_read ),
  79158. JS_CFUNC_DEF("write", 2, js_bjson_write ),
  79159. #define DEF(x) JS_PROP_INT32_DEF(#x, JS_##x, JS_PROP_CONFIGURABLE)
  79160. DEF(READ_OBJ_BYTECODE),
  79161. DEF(READ_OBJ_REFERENCE),
  79162. DEF(READ_OBJ_SAB),
  79163. DEF(WRITE_OBJ_BYTECODE),
  79164. DEF(WRITE_OBJ_REFERENCE),
  79165. DEF(WRITE_OBJ_SAB),
  79166. DEF(WRITE_OBJ_STRIP_DEBUG),
  79167. DEF(WRITE_OBJ_STRIP_SOURCE),
  79168. #undef DEF
  79169. };
  79170. static int js_bjson_init(JSContext *ctx, JSModuleDef *m)
  79171. {
  79172. return JS_SetModuleExportList(ctx, m, js_bjson_funcs,
  79173. countof(js_bjson_funcs));
  79174. }
  79175. JSModuleDef *js_init_module_bjson(JSContext *ctx, const char *module_name)
  79176. {
  79177. JSModuleDef *m;
  79178. m = JS_NewCModule(ctx, module_name, js_bjson_init);
  79179. if (!m)
  79180. return NULL;
  79181. JS_AddModuleExportList(ctx, m, js_bjson_funcs, countof(js_bjson_funcs));
  79182. return m;
  79183. }
  79184. #endif // QJS_BUILD_LIBC