v8.h 380 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779
  1. // Copyright 2012 the V8 project authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. /** \mainpage V8 API Reference Guide
  5. *
  6. * V8 is Google's open source JavaScript engine.
  7. *
  8. * This set of documents provides reference material generated from the
  9. * V8 header file, include/v8.h.
  10. *
  11. * For other documentation see http://code.google.com/apis/v8/
  12. */
  13. #ifndef INCLUDE_V8_H_
  14. #define INCLUDE_V8_H_
  15. #include <stddef.h>
  16. #include <stdint.h>
  17. #include <stdio.h>
  18. #include <memory>
  19. #include <string>
  20. #include <type_traits>
  21. #include <utility>
  22. #include <vector>
  23. #include "v8-internal.h" // NOLINT(build/include)
  24. #include "v8-version.h" // NOLINT(build/include)
  25. #include "v8config.h" // NOLINT(build/include)
  26. // We reserve the V8_* prefix for macros defined in V8 public API and
  27. // assume there are no name conflicts with the embedder's code.
  28. /**
  29. * The v8 JavaScript engine.
  30. */
  31. namespace v8 {
  32. class AccessorSignature;
  33. class Array;
  34. class ArrayBuffer;
  35. class BigInt;
  36. class BigIntObject;
  37. class Boolean;
  38. class BooleanObject;
  39. class Context;
  40. class Data;
  41. class Date;
  42. class External;
  43. class Function;
  44. class FunctionTemplate;
  45. class HeapProfiler;
  46. class ImplementationUtilities;
  47. class Int32;
  48. class Integer;
  49. class Isolate;
  50. template <class T>
  51. class Maybe;
  52. class MicrotaskQueue;
  53. class Name;
  54. class Number;
  55. class NumberObject;
  56. class Object;
  57. class ObjectOperationDescriptor;
  58. class ObjectTemplate;
  59. class Platform;
  60. class Primitive;
  61. class Promise;
  62. class PropertyDescriptor;
  63. class Proxy;
  64. class RawOperationDescriptor;
  65. class Script;
  66. class SharedArrayBuffer;
  67. class Signature;
  68. class StartupData;
  69. class StackFrame;
  70. class StackTrace;
  71. class String;
  72. class StringObject;
  73. class Symbol;
  74. class SymbolObject;
  75. class PrimitiveArray;
  76. class Private;
  77. class Uint32;
  78. class Utils;
  79. class Value;
  80. class WasmModuleObject;
  81. template <class T> class Local;
  82. template <class T>
  83. class MaybeLocal;
  84. template <class T> class Eternal;
  85. template<class T> class NonCopyablePersistentTraits;
  86. template<class T> class PersistentBase;
  87. template <class T, class M = NonCopyablePersistentTraits<T> >
  88. class Persistent;
  89. template <class T>
  90. class Global;
  91. template <class T>
  92. class TracedGlobal;
  93. template <class T>
  94. class TracedReference;
  95. template <class T>
  96. class TracedReferenceBase;
  97. template<class K, class V, class T> class PersistentValueMap;
  98. template <class K, class V, class T>
  99. class PersistentValueMapBase;
  100. template <class K, class V, class T>
  101. class GlobalValueMap;
  102. template<class V, class T> class PersistentValueVector;
  103. template<class T, class P> class WeakCallbackObject;
  104. class FunctionTemplate;
  105. class ObjectTemplate;
  106. template<typename T> class FunctionCallbackInfo;
  107. template<typename T> class PropertyCallbackInfo;
  108. class StackTrace;
  109. class StackFrame;
  110. class Isolate;
  111. class CallHandlerHelper;
  112. class EscapableHandleScope;
  113. template<typename T> class ReturnValue;
  114. namespace internal {
  115. class Arguments;
  116. class DeferredHandles;
  117. class Heap;
  118. class HeapObject;
  119. class ExternalString;
  120. class Isolate;
  121. class LocalEmbedderHeapTracer;
  122. class MicrotaskQueue;
  123. struct ScriptStreamingData;
  124. template<typename T> class CustomArguments;
  125. class PropertyCallbackArguments;
  126. class FunctionCallbackArguments;
  127. class GlobalHandles;
  128. class ScopedExternalStringLock;
  129. class ThreadLocalTop;
  130. namespace wasm {
  131. class NativeModule;
  132. class StreamingDecoder;
  133. } // namespace wasm
  134. } // namespace internal
  135. namespace debug {
  136. class ConsoleCallArguments;
  137. } // namespace debug
  138. // --- Handles ---
  139. #define TYPE_CHECK(T, S) \
  140. while (false) { \
  141. *(static_cast<T* volatile*>(0)) = static_cast<S*>(0); \
  142. }
  143. /**
  144. * An object reference managed by the v8 garbage collector.
  145. *
  146. * All objects returned from v8 have to be tracked by the garbage
  147. * collector so that it knows that the objects are still alive. Also,
  148. * because the garbage collector may move objects, it is unsafe to
  149. * point directly to an object. Instead, all objects are stored in
  150. * handles which are known by the garbage collector and updated
  151. * whenever an object moves. Handles should always be passed by value
  152. * (except in cases like out-parameters) and they should never be
  153. * allocated on the heap.
  154. *
  155. * There are two types of handles: local and persistent handles.
  156. *
  157. * Local handles are light-weight and transient and typically used in
  158. * local operations. They are managed by HandleScopes. That means that a
  159. * HandleScope must exist on the stack when they are created and that they are
  160. * only valid inside of the HandleScope active during their creation.
  161. * For passing a local handle to an outer HandleScope, an EscapableHandleScope
  162. * and its Escape() method must be used.
  163. *
  164. * Persistent handles can be used when storing objects across several
  165. * independent operations and have to be explicitly deallocated when they're no
  166. * longer used.
  167. *
  168. * It is safe to extract the object stored in the handle by
  169. * dereferencing the handle (for instance, to extract the Object* from
  170. * a Local<Object>); the value will still be governed by a handle
  171. * behind the scenes and the same rules apply to these values as to
  172. * their handles.
  173. */
  174. template <class T>
  175. class Local {
  176. public:
  177. V8_INLINE Local() : val_(nullptr) {}
  178. template <class S>
  179. V8_INLINE Local(Local<S> that)
  180. : val_(reinterpret_cast<T*>(*that)) {
  181. /**
  182. * This check fails when trying to convert between incompatible
  183. * handles. For example, converting from a Local<String> to a
  184. * Local<Number>.
  185. */
  186. TYPE_CHECK(T, S);
  187. }
  188. /**
  189. * Returns true if the handle is empty.
  190. */
  191. V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
  192. /**
  193. * Sets the handle to be empty. IsEmpty() will then return true.
  194. */
  195. V8_INLINE void Clear() { val_ = nullptr; }
  196. V8_INLINE T* operator->() const { return val_; }
  197. V8_INLINE T* operator*() const { return val_; }
  198. /**
  199. * Checks whether two handles are the same.
  200. * Returns true if both are empty, or if the objects
  201. * to which they refer are identical.
  202. * The handles' references are not checked.
  203. */
  204. template <class S>
  205. V8_INLINE bool operator==(const Local<S>& that) const {
  206. internal::Address* a = reinterpret_cast<internal::Address*>(this->val_);
  207. internal::Address* b = reinterpret_cast<internal::Address*>(that.val_);
  208. if (a == nullptr) return b == nullptr;
  209. if (b == nullptr) return false;
  210. return *a == *b;
  211. }
  212. template <class S> V8_INLINE bool operator==(
  213. const PersistentBase<S>& that) const {
  214. internal::Address* a = reinterpret_cast<internal::Address*>(this->val_);
  215. internal::Address* b = reinterpret_cast<internal::Address*>(that.val_);
  216. if (a == nullptr) return b == nullptr;
  217. if (b == nullptr) return false;
  218. return *a == *b;
  219. }
  220. /**
  221. * Checks whether two handles are different.
  222. * Returns true if only one of the handles is empty, or if
  223. * the objects to which they refer are different.
  224. * The handles' references are not checked.
  225. */
  226. template <class S>
  227. V8_INLINE bool operator!=(const Local<S>& that) const {
  228. return !operator==(that);
  229. }
  230. template <class S> V8_INLINE bool operator!=(
  231. const Persistent<S>& that) const {
  232. return !operator==(that);
  233. }
  234. /**
  235. * Cast a handle to a subclass, e.g. Local<Value> to Local<Object>.
  236. * This is only valid if the handle actually refers to a value of the
  237. * target type.
  238. */
  239. template <class S> V8_INLINE static Local<T> Cast(Local<S> that) {
  240. #ifdef V8_ENABLE_CHECKS
  241. // If we're going to perform the type check then we have to check
  242. // that the handle isn't empty before doing the checked cast.
  243. if (that.IsEmpty()) return Local<T>();
  244. #endif
  245. return Local<T>(T::Cast(*that));
  246. }
  247. /**
  248. * Calling this is equivalent to Local<S>::Cast().
  249. * In particular, this is only valid if the handle actually refers to a value
  250. * of the target type.
  251. */
  252. template <class S>
  253. V8_INLINE Local<S> As() const {
  254. return Local<S>::Cast(*this);
  255. }
  256. /**
  257. * Create a local handle for the content of another handle.
  258. * The referee is kept alive by the local handle even when
  259. * the original handle is destroyed/disposed.
  260. */
  261. V8_INLINE static Local<T> New(Isolate* isolate, Local<T> that);
  262. V8_INLINE static Local<T> New(Isolate* isolate,
  263. const PersistentBase<T>& that);
  264. V8_INLINE static Local<T> New(Isolate* isolate,
  265. const TracedReferenceBase<T>& that);
  266. private:
  267. friend class Utils;
  268. template<class F> friend class Eternal;
  269. template<class F> friend class PersistentBase;
  270. template<class F, class M> friend class Persistent;
  271. template<class F> friend class Local;
  272. template <class F>
  273. friend class MaybeLocal;
  274. template<class F> friend class FunctionCallbackInfo;
  275. template<class F> friend class PropertyCallbackInfo;
  276. friend class String;
  277. friend class Object;
  278. friend class Context;
  279. friend class Isolate;
  280. friend class Private;
  281. template<class F> friend class internal::CustomArguments;
  282. friend Local<Primitive> Undefined(Isolate* isolate);
  283. friend Local<Primitive> Null(Isolate* isolate);
  284. friend Local<Boolean> True(Isolate* isolate);
  285. friend Local<Boolean> False(Isolate* isolate);
  286. friend class HandleScope;
  287. friend class EscapableHandleScope;
  288. template <class F1, class F2, class F3>
  289. friend class PersistentValueMapBase;
  290. template<class F1, class F2> friend class PersistentValueVector;
  291. template <class F>
  292. friend class ReturnValue;
  293. template <class F>
  294. friend class Traced;
  295. template <class F>
  296. friend class TracedGlobal;
  297. template <class F>
  298. friend class TracedReferenceBase;
  299. template <class F>
  300. friend class TracedReference;
  301. explicit V8_INLINE Local(T* that) : val_(that) {}
  302. V8_INLINE static Local<T> New(Isolate* isolate, T* that);
  303. T* val_;
  304. };
  305. #if !defined(V8_IMMINENT_DEPRECATION_WARNINGS)
  306. // Handle is an alias for Local for historical reasons.
  307. template <class T>
  308. using Handle = Local<T>;
  309. #endif
  310. /**
  311. * A MaybeLocal<> is a wrapper around Local<> that enforces a check whether
  312. * the Local<> is empty before it can be used.
  313. *
  314. * If an API method returns a MaybeLocal<>, the API method can potentially fail
  315. * either because an exception is thrown, or because an exception is pending,
  316. * e.g. because a previous API call threw an exception that hasn't been caught
  317. * yet, or because a TerminateExecution exception was thrown. In that case, an
  318. * empty MaybeLocal is returned.
  319. */
  320. template <class T>
  321. class MaybeLocal {
  322. public:
  323. V8_INLINE MaybeLocal() : val_(nullptr) {}
  324. template <class S>
  325. V8_INLINE MaybeLocal(Local<S> that)
  326. : val_(reinterpret_cast<T*>(*that)) {
  327. TYPE_CHECK(T, S);
  328. }
  329. V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
  330. /**
  331. * Converts this MaybeLocal<> to a Local<>. If this MaybeLocal<> is empty,
  332. * |false| is returned and |out| is left untouched.
  333. */
  334. template <class S>
  335. V8_WARN_UNUSED_RESULT V8_INLINE bool ToLocal(Local<S>* out) const {
  336. out->val_ = IsEmpty() ? nullptr : this->val_;
  337. return !IsEmpty();
  338. }
  339. /**
  340. * Converts this MaybeLocal<> to a Local<>. If this MaybeLocal<> is empty,
  341. * V8 will crash the process.
  342. */
  343. V8_INLINE Local<T> ToLocalChecked();
  344. /**
  345. * Converts this MaybeLocal<> to a Local<>, using a default value if this
  346. * MaybeLocal<> is empty.
  347. */
  348. template <class S>
  349. V8_INLINE Local<S> FromMaybe(Local<S> default_value) const {
  350. return IsEmpty() ? default_value : Local<S>(val_);
  351. }
  352. private:
  353. T* val_;
  354. };
  355. /**
  356. * Eternal handles are set-once handles that live for the lifetime of the
  357. * isolate.
  358. */
  359. template <class T> class Eternal {
  360. public:
  361. V8_INLINE Eternal() : val_(nullptr) {}
  362. template <class S>
  363. V8_INLINE Eternal(Isolate* isolate, Local<S> handle) : val_(nullptr) {
  364. Set(isolate, handle);
  365. }
  366. // Can only be safely called if already set.
  367. V8_INLINE Local<T> Get(Isolate* isolate) const;
  368. V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
  369. template<class S> V8_INLINE void Set(Isolate* isolate, Local<S> handle);
  370. private:
  371. T* val_;
  372. };
  373. static const int kInternalFieldsInWeakCallback = 2;
  374. static const int kEmbedderFieldsInWeakCallback = 2;
  375. template <typename T>
  376. class WeakCallbackInfo {
  377. public:
  378. typedef void (*Callback)(const WeakCallbackInfo<T>& data);
  379. WeakCallbackInfo(Isolate* isolate, T* parameter,
  380. void* embedder_fields[kEmbedderFieldsInWeakCallback],
  381. Callback* callback)
  382. : isolate_(isolate), parameter_(parameter), callback_(callback) {
  383. for (int i = 0; i < kEmbedderFieldsInWeakCallback; ++i) {
  384. embedder_fields_[i] = embedder_fields[i];
  385. }
  386. }
  387. V8_INLINE Isolate* GetIsolate() const { return isolate_; }
  388. V8_INLINE T* GetParameter() const { return parameter_; }
  389. V8_INLINE void* GetInternalField(int index) const;
  390. // When first called, the embedder MUST Reset() the Global which triggered the
  391. // callback. The Global itself is unusable for anything else. No v8 other api
  392. // calls may be called in the first callback. Should additional work be
  393. // required, the embedder must set a second pass callback, which will be
  394. // called after all the initial callbacks are processed.
  395. // Calling SetSecondPassCallback on the second pass will immediately crash.
  396. void SetSecondPassCallback(Callback callback) const { *callback_ = callback; }
  397. private:
  398. Isolate* isolate_;
  399. T* parameter_;
  400. Callback* callback_;
  401. void* embedder_fields_[kEmbedderFieldsInWeakCallback];
  402. };
  403. // kParameter will pass a void* parameter back to the callback, kInternalFields
  404. // will pass the first two internal fields back to the callback, kFinalizer
  405. // will pass a void* parameter back, but is invoked before the object is
  406. // actually collected, so it can be resurrected. In the last case, it is not
  407. // possible to request a second pass callback.
  408. enum class WeakCallbackType { kParameter, kInternalFields, kFinalizer };
  409. /**
  410. * An object reference that is independent of any handle scope. Where
  411. * a Local handle only lives as long as the HandleScope in which it was
  412. * allocated, a PersistentBase handle remains valid until it is explicitly
  413. * disposed using Reset().
  414. *
  415. * A persistent handle contains a reference to a storage cell within
  416. * the V8 engine which holds an object value and which is updated by
  417. * the garbage collector whenever the object is moved. A new storage
  418. * cell can be created using the constructor or PersistentBase::Reset and
  419. * existing handles can be disposed using PersistentBase::Reset.
  420. *
  421. */
  422. template <class T> class PersistentBase {
  423. public:
  424. /**
  425. * If non-empty, destroy the underlying storage cell
  426. * IsEmpty() will return true after this call.
  427. */
  428. V8_INLINE void Reset();
  429. /**
  430. * If non-empty, destroy the underlying storage cell
  431. * and create a new one with the contents of other if other is non empty
  432. */
  433. template <class S>
  434. V8_INLINE void Reset(Isolate* isolate, const Local<S>& other);
  435. /**
  436. * If non-empty, destroy the underlying storage cell
  437. * and create a new one with the contents of other if other is non empty
  438. */
  439. template <class S>
  440. V8_INLINE void Reset(Isolate* isolate, const PersistentBase<S>& other);
  441. V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
  442. V8_INLINE void Empty() { val_ = 0; }
  443. V8_INLINE Local<T> Get(Isolate* isolate) const {
  444. return Local<T>::New(isolate, *this);
  445. }
  446. template <class S>
  447. V8_INLINE bool operator==(const PersistentBase<S>& that) const {
  448. internal::Address* a = reinterpret_cast<internal::Address*>(this->val_);
  449. internal::Address* b = reinterpret_cast<internal::Address*>(that.val_);
  450. if (a == nullptr) return b == nullptr;
  451. if (b == nullptr) return false;
  452. return *a == *b;
  453. }
  454. template <class S>
  455. V8_INLINE bool operator==(const Local<S>& that) const {
  456. internal::Address* a = reinterpret_cast<internal::Address*>(this->val_);
  457. internal::Address* b = reinterpret_cast<internal::Address*>(that.val_);
  458. if (a == nullptr) return b == nullptr;
  459. if (b == nullptr) return false;
  460. return *a == *b;
  461. }
  462. template <class S>
  463. V8_INLINE bool operator!=(const PersistentBase<S>& that) const {
  464. return !operator==(that);
  465. }
  466. template <class S>
  467. V8_INLINE bool operator!=(const Local<S>& that) const {
  468. return !operator==(that);
  469. }
  470. /**
  471. * Install a finalization callback on this object.
  472. * NOTE: There is no guarantee as to *when* or even *if* the callback is
  473. * invoked. The invocation is performed solely on a best effort basis.
  474. * As always, GC-based finalization should *not* be relied upon for any
  475. * critical form of resource management!
  476. */
  477. template <typename P>
  478. V8_INLINE void SetWeak(P* parameter,
  479. typename WeakCallbackInfo<P>::Callback callback,
  480. WeakCallbackType type);
  481. /**
  482. * Turns this handle into a weak phantom handle without finalization callback.
  483. * The handle will be reset automatically when the garbage collector detects
  484. * that the object is no longer reachable.
  485. * A related function Isolate::NumberOfPhantomHandleResetsSinceLastCall
  486. * returns how many phantom handles were reset by the garbage collector.
  487. */
  488. V8_INLINE void SetWeak();
  489. template<typename P>
  490. V8_INLINE P* ClearWeak();
  491. // TODO(dcarney): remove this.
  492. V8_INLINE void ClearWeak() { ClearWeak<void>(); }
  493. /**
  494. * Annotates the strong handle with the given label, which is then used by the
  495. * heap snapshot generator as a name of the edge from the root to the handle.
  496. * The function does not take ownership of the label and assumes that the
  497. * label is valid as long as the handle is valid.
  498. */
  499. V8_INLINE void AnnotateStrongRetainer(const char* label);
  500. /** Returns true if the handle's reference is weak. */
  501. V8_INLINE bool IsWeak() const;
  502. /**
  503. * Assigns a wrapper class ID to the handle.
  504. */
  505. V8_INLINE void SetWrapperClassId(uint16_t class_id);
  506. /**
  507. * Returns the class ID previously assigned to this handle or 0 if no class ID
  508. * was previously assigned.
  509. */
  510. V8_INLINE uint16_t WrapperClassId() const;
  511. PersistentBase(const PersistentBase& other) = delete; // NOLINT
  512. void operator=(const PersistentBase&) = delete;
  513. private:
  514. friend class Isolate;
  515. friend class Utils;
  516. template<class F> friend class Local;
  517. template<class F1, class F2> friend class Persistent;
  518. template <class F>
  519. friend class Global;
  520. template<class F> friend class PersistentBase;
  521. template<class F> friend class ReturnValue;
  522. template <class F1, class F2, class F3>
  523. friend class PersistentValueMapBase;
  524. template<class F1, class F2> friend class PersistentValueVector;
  525. friend class Object;
  526. explicit V8_INLINE PersistentBase(T* val) : val_(val) {}
  527. V8_INLINE static T* New(Isolate* isolate, T* that);
  528. T* val_;
  529. };
  530. /**
  531. * Default traits for Persistent. This class does not allow
  532. * use of the copy constructor or assignment operator.
  533. * At present kResetInDestructor is not set, but that will change in a future
  534. * version.
  535. */
  536. template<class T>
  537. class NonCopyablePersistentTraits {
  538. public:
  539. typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent;
  540. static const bool kResetInDestructor = false;
  541. template<class S, class M>
  542. V8_INLINE static void Copy(const Persistent<S, M>& source,
  543. NonCopyablePersistent* dest) {
  544. Uncompilable<Object>();
  545. }
  546. // TODO(dcarney): come up with a good compile error here.
  547. template<class O> V8_INLINE static void Uncompilable() {
  548. TYPE_CHECK(O, Primitive);
  549. }
  550. };
  551. /**
  552. * Helper class traits to allow copying and assignment of Persistent.
  553. * This will clone the contents of storage cell, but not any of the flags, etc.
  554. */
  555. template<class T>
  556. struct CopyablePersistentTraits {
  557. typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent;
  558. static const bool kResetInDestructor = true;
  559. template<class S, class M>
  560. static V8_INLINE void Copy(const Persistent<S, M>& source,
  561. CopyablePersistent* dest) {
  562. // do nothing, just allow copy
  563. }
  564. };
  565. /**
  566. * A PersistentBase which allows copy and assignment.
  567. *
  568. * Copy, assignment and destructor behavior is controlled by the traits
  569. * class M.
  570. *
  571. * Note: Persistent class hierarchy is subject to future changes.
  572. */
  573. template <class T, class M> class Persistent : public PersistentBase<T> {
  574. public:
  575. /**
  576. * A Persistent with no storage cell.
  577. */
  578. V8_INLINE Persistent() : PersistentBase<T>(nullptr) {}
  579. /**
  580. * Construct a Persistent from a Local.
  581. * When the Local is non-empty, a new storage cell is created
  582. * pointing to the same object, and no flags are set.
  583. */
  584. template <class S>
  585. V8_INLINE Persistent(Isolate* isolate, Local<S> that)
  586. : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
  587. TYPE_CHECK(T, S);
  588. }
  589. /**
  590. * Construct a Persistent from a Persistent.
  591. * When the Persistent is non-empty, a new storage cell is created
  592. * pointing to the same object, and no flags are set.
  593. */
  594. template <class S, class M2>
  595. V8_INLINE Persistent(Isolate* isolate, const Persistent<S, M2>& that)
  596. : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
  597. TYPE_CHECK(T, S);
  598. }
  599. /**
  600. * The copy constructors and assignment operator create a Persistent
  601. * exactly as the Persistent constructor, but the Copy function from the
  602. * traits class is called, allowing the setting of flags based on the
  603. * copied Persistent.
  604. */
  605. V8_INLINE Persistent(const Persistent& that) : PersistentBase<T>(nullptr) {
  606. Copy(that);
  607. }
  608. template <class S, class M2>
  609. V8_INLINE Persistent(const Persistent<S, M2>& that) : PersistentBase<T>(0) {
  610. Copy(that);
  611. }
  612. V8_INLINE Persistent& operator=(const Persistent& that) {
  613. Copy(that);
  614. return *this;
  615. }
  616. template <class S, class M2>
  617. V8_INLINE Persistent& operator=(const Persistent<S, M2>& that) { // NOLINT
  618. Copy(that);
  619. return *this;
  620. }
  621. /**
  622. * The destructor will dispose the Persistent based on the
  623. * kResetInDestructor flags in the traits class. Since not calling dispose
  624. * can result in a memory leak, it is recommended to always set this flag.
  625. */
  626. V8_INLINE ~Persistent() {
  627. if (M::kResetInDestructor) this->Reset();
  628. }
  629. // TODO(dcarney): this is pretty useless, fix or remove
  630. template <class S>
  631. V8_INLINE static Persistent<T>& Cast(const Persistent<S>& that) { // NOLINT
  632. #ifdef V8_ENABLE_CHECKS
  633. // If we're going to perform the type check then we have to check
  634. // that the handle isn't empty before doing the checked cast.
  635. if (!that.IsEmpty()) T::Cast(*that);
  636. #endif
  637. return reinterpret_cast<Persistent<T>&>(const_cast<Persistent<S>&>(that));
  638. }
  639. // TODO(dcarney): this is pretty useless, fix or remove
  640. template <class S>
  641. V8_INLINE Persistent<S>& As() const { // NOLINT
  642. return Persistent<S>::Cast(*this);
  643. }
  644. private:
  645. friend class Isolate;
  646. friend class Utils;
  647. template<class F> friend class Local;
  648. template<class F1, class F2> friend class Persistent;
  649. template<class F> friend class ReturnValue;
  650. explicit V8_INLINE Persistent(T* that) : PersistentBase<T>(that) {}
  651. V8_INLINE T* operator*() const { return this->val_; }
  652. template<class S, class M2>
  653. V8_INLINE void Copy(const Persistent<S, M2>& that);
  654. };
  655. /**
  656. * A PersistentBase which has move semantics.
  657. *
  658. * Note: Persistent class hierarchy is subject to future changes.
  659. */
  660. template <class T>
  661. class Global : public PersistentBase<T> {
  662. public:
  663. /**
  664. * A Global with no storage cell.
  665. */
  666. V8_INLINE Global() : PersistentBase<T>(nullptr) {}
  667. /**
  668. * Construct a Global from a Local.
  669. * When the Local is non-empty, a new storage cell is created
  670. * pointing to the same object, and no flags are set.
  671. */
  672. template <class S>
  673. V8_INLINE Global(Isolate* isolate, Local<S> that)
  674. : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
  675. TYPE_CHECK(T, S);
  676. }
  677. /**
  678. * Construct a Global from a PersistentBase.
  679. * When the Persistent is non-empty, a new storage cell is created
  680. * pointing to the same object, and no flags are set.
  681. */
  682. template <class S>
  683. V8_INLINE Global(Isolate* isolate, const PersistentBase<S>& that)
  684. : PersistentBase<T>(PersistentBase<T>::New(isolate, that.val_)) {
  685. TYPE_CHECK(T, S);
  686. }
  687. /**
  688. * Move constructor.
  689. */
  690. V8_INLINE Global(Global&& other);
  691. V8_INLINE ~Global() { this->Reset(); }
  692. /**
  693. * Move via assignment.
  694. */
  695. template <class S>
  696. V8_INLINE Global& operator=(Global<S>&& rhs);
  697. /**
  698. * Pass allows returning uniques from functions, etc.
  699. */
  700. Global Pass() { return static_cast<Global&&>(*this); } // NOLINT
  701. /*
  702. * For compatibility with Chromium's base::Bind (base::Passed).
  703. */
  704. typedef void MoveOnlyTypeForCPP03;
  705. Global(const Global&) = delete;
  706. void operator=(const Global&) = delete;
  707. private:
  708. template <class F>
  709. friend class ReturnValue;
  710. V8_INLINE T* operator*() const { return this->val_; }
  711. };
  712. // UniquePersistent is an alias for Global for historical reason.
  713. template <class T>
  714. using UniquePersistent = Global<T>;
  715. /**
  716. * Deprecated. Use |TracedReference<T>| instead.
  717. */
  718. template <typename T>
  719. struct TracedGlobalTrait {};
  720. /**
  721. * A traced handle with copy and move semantics. The handle is to be used
  722. * together with |v8::EmbedderHeapTracer| and specifies edges from the embedder
  723. * into V8's heap.
  724. *
  725. * The exact semantics are:
  726. * - Tracing garbage collections use |v8::EmbedderHeapTracer|.
  727. * - Non-tracing garbage collections refer to
  728. * |v8::EmbedderHeapTracer::IsRootForNonTracingGC()| whether the handle should
  729. * be treated as root or not.
  730. *
  731. * Note that the base class cannot be instantiated itself. Choose from
  732. * - TracedGlobal
  733. * - TracedReference
  734. */
  735. template <typename T>
  736. class TracedReferenceBase {
  737. public:
  738. /**
  739. * Returns true if this TracedReferenceBase is empty, i.e., has not been
  740. * assigned an object.
  741. */
  742. bool IsEmpty() const { return val_ == nullptr; }
  743. /**
  744. * If non-empty, destroy the underlying storage cell. |IsEmpty| will return
  745. * true after this call.
  746. */
  747. V8_INLINE void Reset();
  748. /**
  749. * Construct a Local<T> from this handle.
  750. */
  751. Local<T> Get(Isolate* isolate) const { return Local<T>::New(isolate, *this); }
  752. template <class S>
  753. V8_INLINE bool operator==(const TracedReferenceBase<S>& that) const {
  754. internal::Address* a = reinterpret_cast<internal::Address*>(val_);
  755. internal::Address* b = reinterpret_cast<internal::Address*>(that.val_);
  756. if (a == nullptr) return b == nullptr;
  757. if (b == nullptr) return false;
  758. return *a == *b;
  759. }
  760. template <class S>
  761. V8_INLINE bool operator==(const Local<S>& that) const {
  762. internal::Address* a = reinterpret_cast<internal::Address*>(val_);
  763. internal::Address* b = reinterpret_cast<internal::Address*>(that.val_);
  764. if (a == nullptr) return b == nullptr;
  765. if (b == nullptr) return false;
  766. return *a == *b;
  767. }
  768. template <class S>
  769. V8_INLINE bool operator!=(const TracedReferenceBase<S>& that) const {
  770. return !operator==(that);
  771. }
  772. template <class S>
  773. V8_INLINE bool operator!=(const Local<S>& that) const {
  774. return !operator==(that);
  775. }
  776. /**
  777. * Assigns a wrapper class ID to the handle.
  778. */
  779. V8_INLINE void SetWrapperClassId(uint16_t class_id);
  780. /**
  781. * Returns the class ID previously assigned to this handle or 0 if no class ID
  782. * was previously assigned.
  783. */
  784. V8_INLINE uint16_t WrapperClassId() const;
  785. template <class S>
  786. V8_INLINE TracedReferenceBase<S>& As() const {
  787. return reinterpret_cast<TracedReferenceBase<S>&>(
  788. const_cast<TracedReferenceBase<T>&>(*this));
  789. }
  790. private:
  791. enum DestructionMode { kWithDestructor, kWithoutDestructor };
  792. /**
  793. * An empty TracedReferenceBase without storage cell.
  794. */
  795. TracedReferenceBase() = default;
  796. V8_INLINE static T* New(Isolate* isolate, T* that, void* slot,
  797. DestructionMode destruction_mode);
  798. T* val_ = nullptr;
  799. friend class EmbedderHeapTracer;
  800. template <typename F>
  801. friend class Local;
  802. friend class Object;
  803. template <typename F>
  804. friend class TracedGlobal;
  805. template <typename F>
  806. friend class TracedReference;
  807. template <typename F>
  808. friend class ReturnValue;
  809. };
  810. /**
  811. * A traced handle with destructor that clears the handle. For more details see
  812. * TracedReferenceBase.
  813. */
  814. template <typename T>
  815. class TracedGlobal : public TracedReferenceBase<T> {
  816. public:
  817. using TracedReferenceBase<T>::Reset;
  818. /**
  819. * Destructor resetting the handle.
  820. */
  821. ~TracedGlobal() { this->Reset(); }
  822. /**
  823. * An empty TracedGlobal without storage cell.
  824. */
  825. TracedGlobal() : TracedReferenceBase<T>() {}
  826. /**
  827. * Construct a TracedGlobal from a Local.
  828. *
  829. * When the Local is non-empty, a new storage cell is created
  830. * pointing to the same object.
  831. */
  832. template <class S>
  833. TracedGlobal(Isolate* isolate, Local<S> that) : TracedReferenceBase<T>() {
  834. this->val_ = this->New(isolate, that.val_, &this->val_,
  835. TracedReferenceBase<T>::kWithDestructor);
  836. TYPE_CHECK(T, S);
  837. }
  838. /**
  839. * Move constructor initializing TracedGlobal from an existing one.
  840. */
  841. V8_INLINE TracedGlobal(TracedGlobal&& other) {
  842. // Forward to operator=.
  843. *this = std::move(other);
  844. }
  845. /**
  846. * Move constructor initializing TracedGlobal from an existing one.
  847. */
  848. template <typename S>
  849. V8_INLINE TracedGlobal(TracedGlobal<S>&& other) {
  850. // Forward to operator=.
  851. *this = std::move(other);
  852. }
  853. /**
  854. * Copy constructor initializing TracedGlobal from an existing one.
  855. */
  856. V8_INLINE TracedGlobal(const TracedGlobal& other) {
  857. // Forward to operator=;
  858. *this = other;
  859. }
  860. /**
  861. * Copy constructor initializing TracedGlobal from an existing one.
  862. */
  863. template <typename S>
  864. V8_INLINE TracedGlobal(const TracedGlobal<S>& other) {
  865. // Forward to operator=;
  866. *this = other;
  867. }
  868. /**
  869. * Move assignment operator initializing TracedGlobal from an existing one.
  870. */
  871. V8_INLINE TracedGlobal& operator=(TracedGlobal&& rhs);
  872. /**
  873. * Move assignment operator initializing TracedGlobal from an existing one.
  874. */
  875. template <class S>
  876. V8_INLINE TracedGlobal& operator=(TracedGlobal<S>&& rhs);
  877. /**
  878. * Copy assignment operator initializing TracedGlobal from an existing one.
  879. *
  880. * Note: Prohibited when |other| has a finalization callback set through
  881. * |SetFinalizationCallback|.
  882. */
  883. V8_INLINE TracedGlobal& operator=(const TracedGlobal& rhs);
  884. /**
  885. * Copy assignment operator initializing TracedGlobal from an existing one.
  886. *
  887. * Note: Prohibited when |other| has a finalization callback set through
  888. * |SetFinalizationCallback|.
  889. */
  890. template <class S>
  891. V8_INLINE TracedGlobal& operator=(const TracedGlobal<S>& rhs);
  892. /**
  893. * If non-empty, destroy the underlying storage cell and create a new one with
  894. * the contents of other if other is non empty
  895. */
  896. template <class S>
  897. V8_INLINE void Reset(Isolate* isolate, const Local<S>& other);
  898. template <class S>
  899. V8_INLINE TracedGlobal<S>& As() const {
  900. return reinterpret_cast<TracedGlobal<S>&>(
  901. const_cast<TracedGlobal<T>&>(*this));
  902. }
  903. /**
  904. * Adds a finalization callback to the handle. The type of this callback is
  905. * similar to WeakCallbackType::kInternalFields, i.e., it will pass the
  906. * parameter and the first two internal fields of the object.
  907. *
  908. * The callback is then supposed to reset the handle in the callback. No
  909. * further V8 API may be called in this callback. In case additional work
  910. * involving V8 needs to be done, a second callback can be scheduled using
  911. * WeakCallbackInfo<void>::SetSecondPassCallback.
  912. */
  913. V8_INLINE void SetFinalizationCallback(
  914. void* parameter, WeakCallbackInfo<void>::Callback callback);
  915. };
  916. /**
  917. * A traced handle without destructor that clears the handle. The embedder needs
  918. * to ensure that the handle is not accessed once the V8 object has been
  919. * reclaimed. This can happen when the handle is not passed through the
  920. * EmbedderHeapTracer. For more details see TracedReferenceBase.
  921. */
  922. template <typename T>
  923. class TracedReference : public TracedReferenceBase<T> {
  924. public:
  925. using TracedReferenceBase<T>::Reset;
  926. /**
  927. * An empty TracedReference without storage cell.
  928. */
  929. TracedReference() : TracedReferenceBase<T>() {}
  930. /**
  931. * Construct a TracedReference from a Local.
  932. *
  933. * When the Local is non-empty, a new storage cell is created
  934. * pointing to the same object.
  935. */
  936. template <class S>
  937. TracedReference(Isolate* isolate, Local<S> that) : TracedReferenceBase<T>() {
  938. this->val_ = this->New(isolate, that.val_, &this->val_,
  939. TracedReferenceBase<T>::kWithoutDestructor);
  940. TYPE_CHECK(T, S);
  941. }
  942. /**
  943. * Move constructor initializing TracedReference from an
  944. * existing one.
  945. */
  946. V8_INLINE TracedReference(TracedReference&& other) {
  947. // Forward to operator=.
  948. *this = std::move(other);
  949. }
  950. /**
  951. * Move constructor initializing TracedReference from an
  952. * existing one.
  953. */
  954. template <typename S>
  955. V8_INLINE TracedReference(TracedReference<S>&& other) {
  956. // Forward to operator=.
  957. *this = std::move(other);
  958. }
  959. /**
  960. * Copy constructor initializing TracedReference from an
  961. * existing one.
  962. */
  963. V8_INLINE TracedReference(const TracedReference& other) {
  964. // Forward to operator=;
  965. *this = other;
  966. }
  967. /**
  968. * Copy constructor initializing TracedReference from an
  969. * existing one.
  970. */
  971. template <typename S>
  972. V8_INLINE TracedReference(const TracedReference<S>& other) {
  973. // Forward to operator=;
  974. *this = other;
  975. }
  976. /**
  977. * Move assignment operator initializing TracedGlobal from an existing one.
  978. */
  979. V8_INLINE TracedReference& operator=(TracedReference&& rhs);
  980. /**
  981. * Move assignment operator initializing TracedGlobal from an existing one.
  982. */
  983. template <class S>
  984. V8_INLINE TracedReference& operator=(TracedReference<S>&& rhs);
  985. /**
  986. * Copy assignment operator initializing TracedGlobal from an existing one.
  987. *
  988. * Note: Prohibited when |other| has a finalization callback set through
  989. * |SetFinalizationCallback|.
  990. */
  991. V8_INLINE TracedReference& operator=(const TracedReference& rhs);
  992. /**
  993. * Copy assignment operator initializing TracedGlobal from an existing one.
  994. *
  995. * Note: Prohibited when |other| has a finalization callback set through
  996. * |SetFinalizationCallback|.
  997. */
  998. template <class S>
  999. V8_INLINE TracedReference& operator=(const TracedReference<S>& rhs);
  1000. /**
  1001. * If non-empty, destroy the underlying storage cell and create a new one with
  1002. * the contents of other if other is non empty
  1003. */
  1004. template <class S>
  1005. V8_INLINE void Reset(Isolate* isolate, const Local<S>& other);
  1006. template <class S>
  1007. V8_INLINE TracedReference<S>& As() const {
  1008. return reinterpret_cast<TracedReference<S>&>(
  1009. const_cast<TracedReference<T>&>(*this));
  1010. }
  1011. /**
  1012. * Adds a finalization callback to the handle. The type of this callback is
  1013. * similar to WeakCallbackType::kInternalFields, i.e., it will pass the
  1014. * parameter and the first two internal fields of the object.
  1015. *
  1016. * The callback is then supposed to reset the handle in the callback. No
  1017. * further V8 API may be called in this callback. In case additional work
  1018. * involving V8 needs to be done, a second callback can be scheduled using
  1019. * WeakCallbackInfo<void>::SetSecondPassCallback.
  1020. */
  1021. V8_DEPRECATE_SOON("Use TracedGlobal<> if callbacks are required.")
  1022. V8_INLINE void SetFinalizationCallback(
  1023. void* parameter, WeakCallbackInfo<void>::Callback callback);
  1024. };
  1025. /**
  1026. * A stack-allocated class that governs a number of local handles.
  1027. * After a handle scope has been created, all local handles will be
  1028. * allocated within that handle scope until either the handle scope is
  1029. * deleted or another handle scope is created. If there is already a
  1030. * handle scope and a new one is created, all allocations will take
  1031. * place in the new handle scope until it is deleted. After that,
  1032. * new handles will again be allocated in the original handle scope.
  1033. *
  1034. * After the handle scope of a local handle has been deleted the
  1035. * garbage collector will no longer track the object stored in the
  1036. * handle and may deallocate it. The behavior of accessing a handle
  1037. * for which the handle scope has been deleted is undefined.
  1038. */
  1039. class V8_EXPORT HandleScope {
  1040. public:
  1041. explicit HandleScope(Isolate* isolate);
  1042. ~HandleScope();
  1043. /**
  1044. * Counts the number of allocated handles.
  1045. */
  1046. static int NumberOfHandles(Isolate* isolate);
  1047. V8_INLINE Isolate* GetIsolate() const {
  1048. return reinterpret_cast<Isolate*>(isolate_);
  1049. }
  1050. HandleScope(const HandleScope&) = delete;
  1051. void operator=(const HandleScope&) = delete;
  1052. protected:
  1053. V8_INLINE HandleScope() = default;
  1054. void Initialize(Isolate* isolate);
  1055. static internal::Address* CreateHandle(internal::Isolate* isolate,
  1056. internal::Address value);
  1057. private:
  1058. // Declaring operator new and delete as deleted is not spec compliant.
  1059. // Therefore declare them private instead to disable dynamic alloc
  1060. void* operator new(size_t size);
  1061. void* operator new[](size_t size);
  1062. void operator delete(void*, size_t);
  1063. void operator delete[](void*, size_t);
  1064. internal::Isolate* isolate_;
  1065. internal::Address* prev_next_;
  1066. internal::Address* prev_limit_;
  1067. // Local::New uses CreateHandle with an Isolate* parameter.
  1068. template<class F> friend class Local;
  1069. // Object::GetInternalField and Context::GetEmbedderData use CreateHandle with
  1070. // a HeapObject in their shortcuts.
  1071. friend class Object;
  1072. friend class Context;
  1073. };
  1074. /**
  1075. * A HandleScope which first allocates a handle in the current scope
  1076. * which will be later filled with the escape value.
  1077. */
  1078. class V8_EXPORT EscapableHandleScope : public HandleScope {
  1079. public:
  1080. explicit EscapableHandleScope(Isolate* isolate);
  1081. V8_INLINE ~EscapableHandleScope() = default;
  1082. /**
  1083. * Pushes the value into the previous scope and returns a handle to it.
  1084. * Cannot be called twice.
  1085. */
  1086. template <class T>
  1087. V8_INLINE Local<T> Escape(Local<T> value) {
  1088. internal::Address* slot =
  1089. Escape(reinterpret_cast<internal::Address*>(*value));
  1090. return Local<T>(reinterpret_cast<T*>(slot));
  1091. }
  1092. template <class T>
  1093. V8_INLINE MaybeLocal<T> EscapeMaybe(MaybeLocal<T> value) {
  1094. return Escape(value.FromMaybe(Local<T>()));
  1095. }
  1096. EscapableHandleScope(const EscapableHandleScope&) = delete;
  1097. void operator=(const EscapableHandleScope&) = delete;
  1098. private:
  1099. // Declaring operator new and delete as deleted is not spec compliant.
  1100. // Therefore declare them private instead to disable dynamic alloc
  1101. void* operator new(size_t size);
  1102. void* operator new[](size_t size);
  1103. void operator delete(void*, size_t);
  1104. void operator delete[](void*, size_t);
  1105. internal::Address* Escape(internal::Address* escape_value);
  1106. internal::Address* escape_slot_;
  1107. };
  1108. /**
  1109. * A SealHandleScope acts like a handle scope in which no handle allocations
  1110. * are allowed. It can be useful for debugging handle leaks.
  1111. * Handles can be allocated within inner normal HandleScopes.
  1112. */
  1113. class V8_EXPORT SealHandleScope {
  1114. public:
  1115. explicit SealHandleScope(Isolate* isolate);
  1116. ~SealHandleScope();
  1117. SealHandleScope(const SealHandleScope&) = delete;
  1118. void operator=(const SealHandleScope&) = delete;
  1119. private:
  1120. // Declaring operator new and delete as deleted is not spec compliant.
  1121. // Therefore declare them private instead to disable dynamic alloc
  1122. void* operator new(size_t size);
  1123. void* operator new[](size_t size);
  1124. void operator delete(void*, size_t);
  1125. void operator delete[](void*, size_t);
  1126. internal::Isolate* const isolate_;
  1127. internal::Address* prev_limit_;
  1128. int prev_sealed_level_;
  1129. };
  1130. // --- Special objects ---
  1131. /**
  1132. * The superclass of objects that can reside on V8's heap.
  1133. */
  1134. class V8_EXPORT Data {
  1135. private:
  1136. Data();
  1137. };
  1138. /**
  1139. * A container type that holds relevant metadata for module loading.
  1140. *
  1141. * This is passed back to the embedder as part of
  1142. * HostImportModuleDynamicallyCallback for module loading.
  1143. */
  1144. class V8_EXPORT ScriptOrModule {
  1145. public:
  1146. /**
  1147. * The name that was passed by the embedder as ResourceName to the
  1148. * ScriptOrigin. This can be either a v8::String or v8::Undefined.
  1149. */
  1150. Local<Value> GetResourceName();
  1151. /**
  1152. * The options that were passed by the embedder as HostDefinedOptions to
  1153. * the ScriptOrigin.
  1154. */
  1155. Local<PrimitiveArray> GetHostDefinedOptions();
  1156. };
  1157. /**
  1158. * An array to hold Primitive values. This is used by the embedder to
  1159. * pass host defined options to the ScriptOptions during compilation.
  1160. *
  1161. * This is passed back to the embedder as part of
  1162. * HostImportModuleDynamicallyCallback for module loading.
  1163. *
  1164. */
  1165. class V8_EXPORT PrimitiveArray {
  1166. public:
  1167. static Local<PrimitiveArray> New(Isolate* isolate, int length);
  1168. int Length() const;
  1169. void Set(Isolate* isolate, int index, Local<Primitive> item);
  1170. Local<Primitive> Get(Isolate* isolate, int index);
  1171. };
  1172. /**
  1173. * The optional attributes of ScriptOrigin.
  1174. */
  1175. class ScriptOriginOptions {
  1176. public:
  1177. V8_INLINE ScriptOriginOptions(bool is_shared_cross_origin = false,
  1178. bool is_opaque = false, bool is_wasm = false,
  1179. bool is_module = false)
  1180. : flags_((is_shared_cross_origin ? kIsSharedCrossOrigin : 0) |
  1181. (is_wasm ? kIsWasm : 0) | (is_opaque ? kIsOpaque : 0) |
  1182. (is_module ? kIsModule : 0)) {}
  1183. V8_INLINE ScriptOriginOptions(int flags)
  1184. : flags_(flags &
  1185. (kIsSharedCrossOrigin | kIsOpaque | kIsWasm | kIsModule)) {}
  1186. bool IsSharedCrossOrigin() const {
  1187. return (flags_ & kIsSharedCrossOrigin) != 0;
  1188. }
  1189. bool IsOpaque() const { return (flags_ & kIsOpaque) != 0; }
  1190. bool IsWasm() const { return (flags_ & kIsWasm) != 0; }
  1191. bool IsModule() const { return (flags_ & kIsModule) != 0; }
  1192. int Flags() const { return flags_; }
  1193. private:
  1194. enum {
  1195. kIsSharedCrossOrigin = 1,
  1196. kIsOpaque = 1 << 1,
  1197. kIsWasm = 1 << 2,
  1198. kIsModule = 1 << 3
  1199. };
  1200. const int flags_;
  1201. };
  1202. /**
  1203. * The origin, within a file, of a script.
  1204. */
  1205. class ScriptOrigin {
  1206. public:
  1207. V8_INLINE ScriptOrigin(
  1208. Local<Value> resource_name,
  1209. Local<Integer> resource_line_offset = Local<Integer>(),
  1210. Local<Integer> resource_column_offset = Local<Integer>(),
  1211. Local<Boolean> resource_is_shared_cross_origin = Local<Boolean>(),
  1212. Local<Integer> script_id = Local<Integer>(),
  1213. Local<Value> source_map_url = Local<Value>(),
  1214. Local<Boolean> resource_is_opaque = Local<Boolean>(),
  1215. Local<Boolean> is_wasm = Local<Boolean>(),
  1216. Local<Boolean> is_module = Local<Boolean>(),
  1217. Local<PrimitiveArray> host_defined_options = Local<PrimitiveArray>());
  1218. V8_INLINE Local<Value> ResourceName() const;
  1219. V8_INLINE Local<Integer> ResourceLineOffset() const;
  1220. V8_INLINE Local<Integer> ResourceColumnOffset() const;
  1221. V8_INLINE Local<Integer> ScriptID() const;
  1222. V8_INLINE Local<Value> SourceMapUrl() const;
  1223. V8_INLINE Local<PrimitiveArray> HostDefinedOptions() const;
  1224. V8_INLINE ScriptOriginOptions Options() const { return options_; }
  1225. private:
  1226. Local<Value> resource_name_;
  1227. Local<Integer> resource_line_offset_;
  1228. Local<Integer> resource_column_offset_;
  1229. ScriptOriginOptions options_;
  1230. Local<Integer> script_id_;
  1231. Local<Value> source_map_url_;
  1232. Local<PrimitiveArray> host_defined_options_;
  1233. };
  1234. /**
  1235. * A compiled JavaScript script, not yet tied to a Context.
  1236. */
  1237. class V8_EXPORT UnboundScript {
  1238. public:
  1239. /**
  1240. * Binds the script to the currently entered context.
  1241. */
  1242. Local<Script> BindToCurrentContext();
  1243. int GetId();
  1244. Local<Value> GetScriptName();
  1245. /**
  1246. * Data read from magic sourceURL comments.
  1247. */
  1248. Local<Value> GetSourceURL();
  1249. /**
  1250. * Data read from magic sourceMappingURL comments.
  1251. */
  1252. Local<Value> GetSourceMappingURL();
  1253. /**
  1254. * Returns zero based line number of the code_pos location in the script.
  1255. * -1 will be returned if no information available.
  1256. */
  1257. int GetLineNumber(int code_pos);
  1258. static const int kNoScriptId = 0;
  1259. };
  1260. /**
  1261. * A compiled JavaScript module, not yet tied to a Context.
  1262. */
  1263. class V8_EXPORT UnboundModuleScript : public Data {
  1264. // Only used as a container for code caching.
  1265. };
  1266. /**
  1267. * A location in JavaScript source.
  1268. */
  1269. class V8_EXPORT Location {
  1270. public:
  1271. int GetLineNumber() { return line_number_; }
  1272. int GetColumnNumber() { return column_number_; }
  1273. Location(int line_number, int column_number)
  1274. : line_number_(line_number), column_number_(column_number) {}
  1275. private:
  1276. int line_number_;
  1277. int column_number_;
  1278. };
  1279. /**
  1280. * A compiled JavaScript module.
  1281. */
  1282. class V8_EXPORT Module : public Data {
  1283. public:
  1284. /**
  1285. * The different states a module can be in.
  1286. *
  1287. * This corresponds to the states used in ECMAScript except that "evaluated"
  1288. * is split into kEvaluated and kErrored, indicating success and failure,
  1289. * respectively.
  1290. */
  1291. enum Status {
  1292. kUninstantiated,
  1293. kInstantiating,
  1294. kInstantiated,
  1295. kEvaluating,
  1296. kEvaluated,
  1297. kErrored
  1298. };
  1299. /**
  1300. * Returns the module's current status.
  1301. */
  1302. Status GetStatus() const;
  1303. /**
  1304. * For a module in kErrored status, this returns the corresponding exception.
  1305. */
  1306. Local<Value> GetException() const;
  1307. /**
  1308. * Returns the number of modules requested by this module.
  1309. */
  1310. int GetModuleRequestsLength() const;
  1311. /**
  1312. * Returns the ith module specifier in this module.
  1313. * i must be < GetModuleRequestsLength() and >= 0.
  1314. */
  1315. Local<String> GetModuleRequest(int i) const;
  1316. /**
  1317. * Returns the source location (line number and column number) of the ith
  1318. * module specifier's first occurrence in this module.
  1319. */
  1320. Location GetModuleRequestLocation(int i) const;
  1321. /**
  1322. * Returns the identity hash for this object.
  1323. */
  1324. int GetIdentityHash() const;
  1325. typedef MaybeLocal<Module> (*ResolveCallback)(Local<Context> context,
  1326. Local<String> specifier,
  1327. Local<Module> referrer);
  1328. /**
  1329. * Instantiates the module and its dependencies.
  1330. *
  1331. * Returns an empty Maybe<bool> if an exception occurred during
  1332. * instantiation. (In the case where the callback throws an exception, that
  1333. * exception is propagated.)
  1334. */
  1335. V8_WARN_UNUSED_RESULT Maybe<bool> InstantiateModule(Local<Context> context,
  1336. ResolveCallback callback);
  1337. /**
  1338. * Evaluates the module and its dependencies.
  1339. *
  1340. * If status is kInstantiated, run the module's code. On success, set status
  1341. * to kEvaluated and return the completion value; on failure, set status to
  1342. * kErrored and propagate the thrown exception (which is then also available
  1343. * via |GetException|).
  1344. */
  1345. V8_WARN_UNUSED_RESULT MaybeLocal<Value> Evaluate(Local<Context> context);
  1346. /**
  1347. * Returns the namespace object of this module.
  1348. *
  1349. * The module's status must be at least kInstantiated.
  1350. */
  1351. Local<Value> GetModuleNamespace();
  1352. /**
  1353. * Returns the corresponding context-unbound module script.
  1354. *
  1355. * The module must be unevaluated, i.e. its status must not be kEvaluating,
  1356. * kEvaluated or kErrored.
  1357. */
  1358. Local<UnboundModuleScript> GetUnboundModuleScript();
  1359. /*
  1360. * Callback defined in the embedder. This is responsible for setting
  1361. * the module's exported values with calls to SetSyntheticModuleExport().
  1362. * The callback must return a Value to indicate success (where no
  1363. * exception was thrown) and return an empy MaybeLocal to indicate falure
  1364. * (where an exception was thrown).
  1365. */
  1366. typedef MaybeLocal<Value> (*SyntheticModuleEvaluationSteps)(
  1367. Local<Context> context, Local<Module> module);
  1368. /**
  1369. * Creates a new SyntheticModule with the specified export names, where
  1370. * evaluation_steps will be executed upon module evaluation.
  1371. * export_names must not contain duplicates.
  1372. * module_name is used solely for logging/debugging and doesn't affect module
  1373. * behavior.
  1374. */
  1375. static Local<Module> CreateSyntheticModule(
  1376. Isolate* isolate, Local<String> module_name,
  1377. const std::vector<Local<String>>& export_names,
  1378. SyntheticModuleEvaluationSteps evaluation_steps);
  1379. /**
  1380. * Set this module's exported value for the name export_name to the specified
  1381. * export_value. This method must be called only on Modules created via
  1382. * CreateSyntheticModule. An error will be thrown if export_name is not one
  1383. * of the export_names that were passed in that CreateSyntheticModule call.
  1384. * Returns Just(true) on success, Nothing<bool>() if an error was thrown.
  1385. */
  1386. V8_WARN_UNUSED_RESULT Maybe<bool> SetSyntheticModuleExport(
  1387. Isolate* isolate, Local<String> export_name, Local<Value> export_value);
  1388. V8_DEPRECATE_SOON(
  1389. "Use the preceding SetSyntheticModuleExport with an Isolate parameter, "
  1390. "instead of the one that follows. The former will throw a runtime "
  1391. "error if called for an export that doesn't exist (as per spec); "
  1392. "the latter will crash with a failed CHECK().")
  1393. void SetSyntheticModuleExport(Local<String> export_name,
  1394. Local<Value> export_value);
  1395. };
  1396. /**
  1397. * A compiled JavaScript script, tied to a Context which was active when the
  1398. * script was compiled.
  1399. */
  1400. class V8_EXPORT Script {
  1401. public:
  1402. /**
  1403. * A shorthand for ScriptCompiler::Compile().
  1404. */
  1405. static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile(
  1406. Local<Context> context, Local<String> source,
  1407. ScriptOrigin* origin = nullptr);
  1408. /**
  1409. * Runs the script returning the resulting value. It will be run in the
  1410. * context in which it was created (ScriptCompiler::CompileBound or
  1411. * UnboundScript::BindToCurrentContext()).
  1412. */
  1413. V8_WARN_UNUSED_RESULT MaybeLocal<Value> Run(Local<Context> context);
  1414. /**
  1415. * Returns the corresponding context-unbound script.
  1416. */
  1417. Local<UnboundScript> GetUnboundScript();
  1418. };
  1419. /**
  1420. * For compiling scripts.
  1421. */
  1422. class V8_EXPORT ScriptCompiler {
  1423. public:
  1424. /**
  1425. * Compilation data that the embedder can cache and pass back to speed up
  1426. * future compilations. The data is produced if the CompilerOptions passed to
  1427. * the compilation functions in ScriptCompiler contains produce_data_to_cache
  1428. * = true. The data to cache can then can be retrieved from
  1429. * UnboundScript.
  1430. */
  1431. struct V8_EXPORT CachedData {
  1432. enum BufferPolicy {
  1433. BufferNotOwned,
  1434. BufferOwned
  1435. };
  1436. CachedData()
  1437. : data(nullptr),
  1438. length(0),
  1439. rejected(false),
  1440. buffer_policy(BufferNotOwned) {}
  1441. // If buffer_policy is BufferNotOwned, the caller keeps the ownership of
  1442. // data and guarantees that it stays alive until the CachedData object is
  1443. // destroyed. If the policy is BufferOwned, the given data will be deleted
  1444. // (with delete[]) when the CachedData object is destroyed.
  1445. CachedData(const uint8_t* data, int length,
  1446. BufferPolicy buffer_policy = BufferNotOwned);
  1447. ~CachedData();
  1448. // TODO(marja): Async compilation; add constructors which take a callback
  1449. // which will be called when V8 no longer needs the data.
  1450. const uint8_t* data;
  1451. int length;
  1452. bool rejected;
  1453. BufferPolicy buffer_policy;
  1454. // Prevent copying.
  1455. CachedData(const CachedData&) = delete;
  1456. CachedData& operator=(const CachedData&) = delete;
  1457. };
  1458. /**
  1459. * Source code which can be then compiled to a UnboundScript or Script.
  1460. */
  1461. class Source {
  1462. public:
  1463. // Source takes ownership of CachedData.
  1464. V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin,
  1465. CachedData* cached_data = nullptr);
  1466. V8_INLINE Source(Local<String> source_string,
  1467. CachedData* cached_data = nullptr);
  1468. V8_INLINE ~Source();
  1469. // Ownership of the CachedData or its buffers is *not* transferred to the
  1470. // caller. The CachedData object is alive as long as the Source object is
  1471. // alive.
  1472. V8_INLINE const CachedData* GetCachedData() const;
  1473. V8_INLINE const ScriptOriginOptions& GetResourceOptions() const;
  1474. // Prevent copying.
  1475. Source(const Source&) = delete;
  1476. Source& operator=(const Source&) = delete;
  1477. private:
  1478. friend class ScriptCompiler;
  1479. Local<String> source_string;
  1480. // Origin information
  1481. Local<Value> resource_name;
  1482. Local<Integer> resource_line_offset;
  1483. Local<Integer> resource_column_offset;
  1484. ScriptOriginOptions resource_options;
  1485. Local<Value> source_map_url;
  1486. Local<PrimitiveArray> host_defined_options;
  1487. // Cached data from previous compilation (if a kConsume*Cache flag is
  1488. // set), or hold newly generated cache data (kProduce*Cache flags) are
  1489. // set when calling a compile method.
  1490. CachedData* cached_data;
  1491. };
  1492. /**
  1493. * For streaming incomplete script data to V8. The embedder should implement a
  1494. * subclass of this class.
  1495. */
  1496. class V8_EXPORT ExternalSourceStream {
  1497. public:
  1498. virtual ~ExternalSourceStream() = default;
  1499. /**
  1500. * V8 calls this to request the next chunk of data from the embedder. This
  1501. * function will be called on a background thread, so it's OK to block and
  1502. * wait for the data, if the embedder doesn't have data yet. Returns the
  1503. * length of the data returned. When the data ends, GetMoreData should
  1504. * return 0. Caller takes ownership of the data.
  1505. *
  1506. * When streaming UTF-8 data, V8 handles multi-byte characters split between
  1507. * two data chunks, but doesn't handle multi-byte characters split between
  1508. * more than two data chunks. The embedder can avoid this problem by always
  1509. * returning at least 2 bytes of data.
  1510. *
  1511. * When streaming UTF-16 data, V8 does not handle characters split between
  1512. * two data chunks. The embedder has to make sure that chunks have an even
  1513. * length.
  1514. *
  1515. * If the embedder wants to cancel the streaming, they should make the next
  1516. * GetMoreData call return 0. V8 will interpret it as end of data (and most
  1517. * probably, parsing will fail). The streaming task will return as soon as
  1518. * V8 has parsed the data it received so far.
  1519. */
  1520. virtual size_t GetMoreData(const uint8_t** src) = 0;
  1521. /**
  1522. * V8 calls this method to set a 'bookmark' at the current position in
  1523. * the source stream, for the purpose of (maybe) later calling
  1524. * ResetToBookmark. If ResetToBookmark is called later, then subsequent
  1525. * calls to GetMoreData should return the same data as they did when
  1526. * SetBookmark was called earlier.
  1527. *
  1528. * The embedder may return 'false' to indicate it cannot provide this
  1529. * functionality.
  1530. */
  1531. virtual bool SetBookmark();
  1532. /**
  1533. * V8 calls this to return to a previously set bookmark.
  1534. */
  1535. virtual void ResetToBookmark();
  1536. };
  1537. /**
  1538. * Source code which can be streamed into V8 in pieces. It will be parsed
  1539. * while streaming and compiled after parsing has completed. StreamedSource
  1540. * must be kept alive while the streaming task is run (see ScriptStreamingTask
  1541. * below).
  1542. */
  1543. class V8_EXPORT StreamedSource {
  1544. public:
  1545. enum Encoding { ONE_BYTE, TWO_BYTE, UTF8 };
  1546. V8_DEPRECATE_SOON(
  1547. "This class takes ownership of source_stream, so use the constructor "
  1548. "taking a unique_ptr to make these semantics clearer")
  1549. StreamedSource(ExternalSourceStream* source_stream, Encoding encoding);
  1550. StreamedSource(std::unique_ptr<ExternalSourceStream> source_stream,
  1551. Encoding encoding);
  1552. ~StreamedSource();
  1553. internal::ScriptStreamingData* impl() const { return impl_.get(); }
  1554. // Prevent copying.
  1555. StreamedSource(const StreamedSource&) = delete;
  1556. StreamedSource& operator=(const StreamedSource&) = delete;
  1557. private:
  1558. std::unique_ptr<internal::ScriptStreamingData> impl_;
  1559. };
  1560. /**
  1561. * A streaming task which the embedder must run on a background thread to
  1562. * stream scripts into V8. Returned by ScriptCompiler::StartStreamingScript.
  1563. */
  1564. class V8_EXPORT ScriptStreamingTask final {
  1565. public:
  1566. void Run();
  1567. private:
  1568. friend class ScriptCompiler;
  1569. explicit ScriptStreamingTask(internal::ScriptStreamingData* data)
  1570. : data_(data) {}
  1571. internal::ScriptStreamingData* data_;
  1572. };
  1573. enum CompileOptions {
  1574. kNoCompileOptions = 0,
  1575. kConsumeCodeCache,
  1576. kEagerCompile
  1577. };
  1578. /**
  1579. * The reason for which we are not requesting or providing a code cache.
  1580. */
  1581. enum NoCacheReason {
  1582. kNoCacheNoReason = 0,
  1583. kNoCacheBecauseCachingDisabled,
  1584. kNoCacheBecauseNoResource,
  1585. kNoCacheBecauseInlineScript,
  1586. kNoCacheBecauseModule,
  1587. kNoCacheBecauseStreamingSource,
  1588. kNoCacheBecauseInspector,
  1589. kNoCacheBecauseScriptTooSmall,
  1590. kNoCacheBecauseCacheTooCold,
  1591. kNoCacheBecauseV8Extension,
  1592. kNoCacheBecauseExtensionModule,
  1593. kNoCacheBecausePacScript,
  1594. kNoCacheBecauseInDocumentWrite,
  1595. kNoCacheBecauseResourceWithNoCacheHandler,
  1596. kNoCacheBecauseDeferredProduceCodeCache
  1597. };
  1598. /**
  1599. * Compiles the specified script (context-independent).
  1600. * Cached data as part of the source object can be optionally produced to be
  1601. * consumed later to speed up compilation of identical source scripts.
  1602. *
  1603. * Note that when producing cached data, the source must point to NULL for
  1604. * cached data. When consuming cached data, the cached data must have been
  1605. * produced by the same version of V8.
  1606. *
  1607. * \param source Script source code.
  1608. * \return Compiled script object (context independent; for running it must be
  1609. * bound to a context).
  1610. */
  1611. static V8_WARN_UNUSED_RESULT MaybeLocal<UnboundScript> CompileUnboundScript(
  1612. Isolate* isolate, Source* source,
  1613. CompileOptions options = kNoCompileOptions,
  1614. NoCacheReason no_cache_reason = kNoCacheNoReason);
  1615. /**
  1616. * Compiles the specified script (bound to current context).
  1617. *
  1618. * \param source Script source code.
  1619. * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
  1620. * using pre_data speeds compilation if it's done multiple times.
  1621. * Owned by caller, no references are kept when this function returns.
  1622. * \return Compiled script object, bound to the context that was active
  1623. * when this function was called. When run it will always use this
  1624. * context.
  1625. */
  1626. static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile(
  1627. Local<Context> context, Source* source,
  1628. CompileOptions options = kNoCompileOptions,
  1629. NoCacheReason no_cache_reason = kNoCacheNoReason);
  1630. /**
  1631. * Returns a task which streams script data into V8, or NULL if the script
  1632. * cannot be streamed. The user is responsible for running the task on a
  1633. * background thread and deleting it. When ran, the task starts parsing the
  1634. * script, and it will request data from the StreamedSource as needed. When
  1635. * ScriptStreamingTask::Run exits, all data has been streamed and the script
  1636. * can be compiled (see Compile below).
  1637. *
  1638. * This API allows to start the streaming with as little data as possible, and
  1639. * the remaining data (for example, the ScriptOrigin) is passed to Compile.
  1640. */
  1641. static ScriptStreamingTask* StartStreamingScript(
  1642. Isolate* isolate, StreamedSource* source,
  1643. CompileOptions options = kNoCompileOptions);
  1644. /**
  1645. * Compiles a streamed script (bound to current context).
  1646. *
  1647. * This can only be called after the streaming has finished
  1648. * (ScriptStreamingTask has been run). V8 doesn't construct the source string
  1649. * during streaming, so the embedder needs to pass the full source here.
  1650. */
  1651. static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile(
  1652. Local<Context> context, StreamedSource* source,
  1653. Local<String> full_source_string, const ScriptOrigin& origin);
  1654. /**
  1655. * Return a version tag for CachedData for the current V8 version & flags.
  1656. *
  1657. * This value is meant only for determining whether a previously generated
  1658. * CachedData instance is still valid; the tag has no other meaing.
  1659. *
  1660. * Background: The data carried by CachedData may depend on the exact
  1661. * V8 version number or current compiler flags. This means that when
  1662. * persisting CachedData, the embedder must take care to not pass in
  1663. * data from another V8 version, or the same version with different
  1664. * features enabled.
  1665. *
  1666. * The easiest way to do so is to clear the embedder's cache on any
  1667. * such change.
  1668. *
  1669. * Alternatively, this tag can be stored alongside the cached data and
  1670. * compared when it is being used.
  1671. */
  1672. static uint32_t CachedDataVersionTag();
  1673. /**
  1674. * Compile an ES module, returning a Module that encapsulates
  1675. * the compiled code.
  1676. *
  1677. * Corresponds to the ParseModule abstract operation in the
  1678. * ECMAScript specification.
  1679. */
  1680. static V8_WARN_UNUSED_RESULT MaybeLocal<Module> CompileModule(
  1681. Isolate* isolate, Source* source,
  1682. CompileOptions options = kNoCompileOptions,
  1683. NoCacheReason no_cache_reason = kNoCacheNoReason);
  1684. /**
  1685. * Compile a function for a given context. This is equivalent to running
  1686. *
  1687. * with (obj) {
  1688. * return function(args) { ... }
  1689. * }
  1690. *
  1691. * It is possible to specify multiple context extensions (obj in the above
  1692. * example).
  1693. */
  1694. static V8_WARN_UNUSED_RESULT MaybeLocal<Function> CompileFunctionInContext(
  1695. Local<Context> context, Source* source, size_t arguments_count,
  1696. Local<String> arguments[], size_t context_extension_count,
  1697. Local<Object> context_extensions[],
  1698. CompileOptions options = kNoCompileOptions,
  1699. NoCacheReason no_cache_reason = kNoCacheNoReason,
  1700. Local<ScriptOrModule>* script_or_module_out = nullptr);
  1701. /**
  1702. * Creates and returns code cache for the specified unbound_script.
  1703. * This will return nullptr if the script cannot be serialized. The
  1704. * CachedData returned by this function should be owned by the caller.
  1705. */
  1706. static CachedData* CreateCodeCache(Local<UnboundScript> unbound_script);
  1707. /**
  1708. * Creates and returns code cache for the specified unbound_module_script.
  1709. * This will return nullptr if the script cannot be serialized. The
  1710. * CachedData returned by this function should be owned by the caller.
  1711. */
  1712. static CachedData* CreateCodeCache(
  1713. Local<UnboundModuleScript> unbound_module_script);
  1714. /**
  1715. * Creates and returns code cache for the specified function that was
  1716. * previously produced by CompileFunctionInContext.
  1717. * This will return nullptr if the script cannot be serialized. The
  1718. * CachedData returned by this function should be owned by the caller.
  1719. */
  1720. static CachedData* CreateCodeCacheForFunction(Local<Function> function);
  1721. private:
  1722. static V8_WARN_UNUSED_RESULT MaybeLocal<UnboundScript> CompileUnboundInternal(
  1723. Isolate* isolate, Source* source, CompileOptions options,
  1724. NoCacheReason no_cache_reason);
  1725. };
  1726. /**
  1727. * An error message.
  1728. */
  1729. class V8_EXPORT Message {
  1730. public:
  1731. Local<String> Get() const;
  1732. /**
  1733. * Return the isolate to which the Message belongs.
  1734. */
  1735. Isolate* GetIsolate() const;
  1736. V8_WARN_UNUSED_RESULT MaybeLocal<String> GetSourceLine(
  1737. Local<Context> context) const;
  1738. /**
  1739. * Returns the origin for the script from where the function causing the
  1740. * error originates.
  1741. */
  1742. ScriptOrigin GetScriptOrigin() const;
  1743. /**
  1744. * Returns the resource name for the script from where the function causing
  1745. * the error originates.
  1746. */
  1747. Local<Value> GetScriptResourceName() const;
  1748. /**
  1749. * Exception stack trace. By default stack traces are not captured for
  1750. * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
  1751. * to change this option.
  1752. */
  1753. Local<StackTrace> GetStackTrace() const;
  1754. /**
  1755. * Returns the number, 1-based, of the line where the error occurred.
  1756. */
  1757. V8_WARN_UNUSED_RESULT Maybe<int> GetLineNumber(Local<Context> context) const;
  1758. /**
  1759. * Returns the index within the script of the first character where
  1760. * the error occurred.
  1761. */
  1762. int GetStartPosition() const;
  1763. /**
  1764. * Returns the index within the script of the last character where
  1765. * the error occurred.
  1766. */
  1767. int GetEndPosition() const;
  1768. /**
  1769. * Returns the Wasm function index where the error occurred. Returns -1 if
  1770. * message is not from a Wasm script.
  1771. */
  1772. int GetWasmFunctionIndex() const;
  1773. /**
  1774. * Returns the error level of the message.
  1775. */
  1776. int ErrorLevel() const;
  1777. /**
  1778. * Returns the index within the line of the first character where
  1779. * the error occurred.
  1780. */
  1781. int GetStartColumn() const;
  1782. V8_WARN_UNUSED_RESULT Maybe<int> GetStartColumn(Local<Context> context) const;
  1783. /**
  1784. * Returns the index within the line of the last character where
  1785. * the error occurred.
  1786. */
  1787. int GetEndColumn() const;
  1788. V8_WARN_UNUSED_RESULT Maybe<int> GetEndColumn(Local<Context> context) const;
  1789. /**
  1790. * Passes on the value set by the embedder when it fed the script from which
  1791. * this Message was generated to V8.
  1792. */
  1793. bool IsSharedCrossOrigin() const;
  1794. bool IsOpaque() const;
  1795. // TODO(1245381): Print to a string instead of on a FILE.
  1796. static void PrintCurrentStackTrace(Isolate* isolate, FILE* out);
  1797. static const int kNoLineNumberInfo = 0;
  1798. static const int kNoColumnInfo = 0;
  1799. static const int kNoScriptIdInfo = 0;
  1800. static const int kNoWasmFunctionIndexInfo = -1;
  1801. };
  1802. /**
  1803. * Representation of a JavaScript stack trace. The information collected is a
  1804. * snapshot of the execution stack and the information remains valid after
  1805. * execution continues.
  1806. */
  1807. class V8_EXPORT StackTrace {
  1808. public:
  1809. /**
  1810. * Flags that determine what information is placed captured for each
  1811. * StackFrame when grabbing the current stack trace.
  1812. * Note: these options are deprecated and we always collect all available
  1813. * information (kDetailed).
  1814. */
  1815. enum StackTraceOptions {
  1816. kLineNumber = 1,
  1817. kColumnOffset = 1 << 1 | kLineNumber,
  1818. kScriptName = 1 << 2,
  1819. kFunctionName = 1 << 3,
  1820. kIsEval = 1 << 4,
  1821. kIsConstructor = 1 << 5,
  1822. kScriptNameOrSourceURL = 1 << 6,
  1823. kScriptId = 1 << 7,
  1824. kExposeFramesAcrossSecurityOrigins = 1 << 8,
  1825. kOverview = kLineNumber | kColumnOffset | kScriptName | kFunctionName,
  1826. kDetailed = kOverview | kIsEval | kIsConstructor | kScriptNameOrSourceURL
  1827. };
  1828. /**
  1829. * Returns a StackFrame at a particular index.
  1830. */
  1831. Local<StackFrame> GetFrame(Isolate* isolate, uint32_t index) const;
  1832. /**
  1833. * Returns the number of StackFrames.
  1834. */
  1835. int GetFrameCount() const;
  1836. /**
  1837. * Grab a snapshot of the current JavaScript execution stack.
  1838. *
  1839. * \param frame_limit The maximum number of stack frames we want to capture.
  1840. * \param options Enumerates the set of things we will capture for each
  1841. * StackFrame.
  1842. */
  1843. static Local<StackTrace> CurrentStackTrace(
  1844. Isolate* isolate, int frame_limit, StackTraceOptions options = kDetailed);
  1845. };
  1846. /**
  1847. * A single JavaScript stack frame.
  1848. */
  1849. class V8_EXPORT StackFrame {
  1850. public:
  1851. /**
  1852. * Returns the number, 1-based, of the line for the associate function call.
  1853. * This method will return Message::kNoLineNumberInfo if it is unable to
  1854. * retrieve the line number, or if kLineNumber was not passed as an option
  1855. * when capturing the StackTrace.
  1856. */
  1857. int GetLineNumber() const;
  1858. /**
  1859. * Returns the 1-based column offset on the line for the associated function
  1860. * call.
  1861. * This method will return Message::kNoColumnInfo if it is unable to retrieve
  1862. * the column number, or if kColumnOffset was not passed as an option when
  1863. * capturing the StackTrace.
  1864. */
  1865. int GetColumn() const;
  1866. /**
  1867. * Returns the id of the script for the function for this StackFrame.
  1868. * This method will return Message::kNoScriptIdInfo if it is unable to
  1869. * retrieve the script id, or if kScriptId was not passed as an option when
  1870. * capturing the StackTrace.
  1871. */
  1872. int GetScriptId() const;
  1873. /**
  1874. * Returns the name of the resource that contains the script for the
  1875. * function for this StackFrame.
  1876. */
  1877. Local<String> GetScriptName() const;
  1878. /**
  1879. * Returns the name of the resource that contains the script for the
  1880. * function for this StackFrame or sourceURL value if the script name
  1881. * is undefined and its source ends with //# sourceURL=... string or
  1882. * deprecated //@ sourceURL=... string.
  1883. */
  1884. Local<String> GetScriptNameOrSourceURL() const;
  1885. /**
  1886. * Returns the name of the function associated with this stack frame.
  1887. */
  1888. Local<String> GetFunctionName() const;
  1889. /**
  1890. * Returns whether or not the associated function is compiled via a call to
  1891. * eval().
  1892. */
  1893. bool IsEval() const;
  1894. /**
  1895. * Returns whether or not the associated function is called as a
  1896. * constructor via "new".
  1897. */
  1898. bool IsConstructor() const;
  1899. /**
  1900. * Returns whether or not the associated functions is defined in wasm.
  1901. */
  1902. bool IsWasm() const;
  1903. /**
  1904. * Returns whether or not the associated function is defined by the user.
  1905. */
  1906. bool IsUserJavaScript() const;
  1907. };
  1908. // A StateTag represents a possible state of the VM.
  1909. enum StateTag {
  1910. JS,
  1911. GC,
  1912. PARSER,
  1913. BYTECODE_COMPILER,
  1914. COMPILER,
  1915. OTHER,
  1916. EXTERNAL,
  1917. IDLE
  1918. };
  1919. // A RegisterState represents the current state of registers used
  1920. // by the sampling profiler API.
  1921. struct RegisterState {
  1922. RegisterState() : pc(nullptr), sp(nullptr), fp(nullptr), lr(nullptr) {}
  1923. void* pc; // Instruction pointer.
  1924. void* sp; // Stack pointer.
  1925. void* fp; // Frame pointer.
  1926. void* lr; // Link register (or nullptr on platforms without a link register).
  1927. };
  1928. // The output structure filled up by GetStackSample API function.
  1929. struct SampleInfo {
  1930. size_t frames_count; // Number of frames collected.
  1931. StateTag vm_state; // Current VM state.
  1932. void* external_callback_entry; // External callback address if VM is
  1933. // executing an external callback.
  1934. void* top_context; // Incumbent native context address.
  1935. };
  1936. struct MemoryRange {
  1937. const void* start = nullptr;
  1938. size_t length_in_bytes = 0;
  1939. };
  1940. struct JSEntryStub {
  1941. MemoryRange code;
  1942. };
  1943. struct UnwindState {
  1944. MemoryRange code_range;
  1945. MemoryRange embedded_code_range;
  1946. JSEntryStub js_entry_stub;
  1947. JSEntryStub js_construct_entry_stub;
  1948. JSEntryStub js_run_microtasks_entry_stub;
  1949. };
  1950. /**
  1951. * A JSON Parser and Stringifier.
  1952. */
  1953. class V8_EXPORT JSON {
  1954. public:
  1955. /**
  1956. * Tries to parse the string |json_string| and returns it as value if
  1957. * successful.
  1958. *
  1959. * \param the context in which to parse and create the value.
  1960. * \param json_string The string to parse.
  1961. * \return The corresponding value if successfully parsed.
  1962. */
  1963. static V8_WARN_UNUSED_RESULT MaybeLocal<Value> Parse(
  1964. Local<Context> context, Local<String> json_string);
  1965. /**
  1966. * Tries to stringify the JSON-serializable object |json_object| and returns
  1967. * it as string if successful.
  1968. *
  1969. * \param json_object The JSON-serializable object to stringify.
  1970. * \return The corresponding string if successfully stringified.
  1971. */
  1972. static V8_WARN_UNUSED_RESULT MaybeLocal<String> Stringify(
  1973. Local<Context> context, Local<Value> json_object,
  1974. Local<String> gap = Local<String>());
  1975. };
  1976. /**
  1977. * Value serialization compatible with the HTML structured clone algorithm.
  1978. * The format is backward-compatible (i.e. safe to store to disk).
  1979. */
  1980. class V8_EXPORT ValueSerializer {
  1981. public:
  1982. class V8_EXPORT Delegate {
  1983. public:
  1984. virtual ~Delegate() = default;
  1985. /**
  1986. * Handles the case where a DataCloneError would be thrown in the structured
  1987. * clone spec. Other V8 embedders may throw some other appropriate exception
  1988. * type.
  1989. */
  1990. virtual void ThrowDataCloneError(Local<String> message) = 0;
  1991. /**
  1992. * The embedder overrides this method to write some kind of host object, if
  1993. * possible. If not, a suitable exception should be thrown and
  1994. * Nothing<bool>() returned.
  1995. */
  1996. virtual Maybe<bool> WriteHostObject(Isolate* isolate, Local<Object> object);
  1997. /**
  1998. * Called when the ValueSerializer is going to serialize a
  1999. * SharedArrayBuffer object. The embedder must return an ID for the
  2000. * object, using the same ID if this SharedArrayBuffer has already been
  2001. * serialized in this buffer. When deserializing, this ID will be passed to
  2002. * ValueDeserializer::GetSharedArrayBufferFromId as |clone_id|.
  2003. *
  2004. * If the object cannot be serialized, an
  2005. * exception should be thrown and Nothing<uint32_t>() returned.
  2006. */
  2007. virtual Maybe<uint32_t> GetSharedArrayBufferId(
  2008. Isolate* isolate, Local<SharedArrayBuffer> shared_array_buffer);
  2009. virtual Maybe<uint32_t> GetWasmModuleTransferId(
  2010. Isolate* isolate, Local<WasmModuleObject> module);
  2011. /**
  2012. * Allocates memory for the buffer of at least the size provided. The actual
  2013. * size (which may be greater or equal) is written to |actual_size|. If no
  2014. * buffer has been allocated yet, nullptr will be provided.
  2015. *
  2016. * If the memory cannot be allocated, nullptr should be returned.
  2017. * |actual_size| will be ignored. It is assumed that |old_buffer| is still
  2018. * valid in this case and has not been modified.
  2019. *
  2020. * The default implementation uses the stdlib's `realloc()` function.
  2021. */
  2022. virtual void* ReallocateBufferMemory(void* old_buffer, size_t size,
  2023. size_t* actual_size);
  2024. /**
  2025. * Frees a buffer allocated with |ReallocateBufferMemory|.
  2026. *
  2027. * The default implementation uses the stdlib's `free()` function.
  2028. */
  2029. virtual void FreeBufferMemory(void* buffer);
  2030. };
  2031. explicit ValueSerializer(Isolate* isolate);
  2032. ValueSerializer(Isolate* isolate, Delegate* delegate);
  2033. ~ValueSerializer();
  2034. /**
  2035. * Writes out a header, which includes the format version.
  2036. */
  2037. void WriteHeader();
  2038. /**
  2039. * Serializes a JavaScript value into the buffer.
  2040. */
  2041. V8_WARN_UNUSED_RESULT Maybe<bool> WriteValue(Local<Context> context,
  2042. Local<Value> value);
  2043. /**
  2044. * Returns the stored data (allocated using the delegate's
  2045. * ReallocateBufferMemory) and its size. This serializer should not be used
  2046. * once the buffer is released. The contents are undefined if a previous write
  2047. * has failed. Ownership of the buffer is transferred to the caller.
  2048. */
  2049. V8_WARN_UNUSED_RESULT std::pair<uint8_t*, size_t> Release();
  2050. /**
  2051. * Marks an ArrayBuffer as havings its contents transferred out of band.
  2052. * Pass the corresponding ArrayBuffer in the deserializing context to
  2053. * ValueDeserializer::TransferArrayBuffer.
  2054. */
  2055. void TransferArrayBuffer(uint32_t transfer_id,
  2056. Local<ArrayBuffer> array_buffer);
  2057. /**
  2058. * Indicate whether to treat ArrayBufferView objects as host objects,
  2059. * i.e. pass them to Delegate::WriteHostObject. This should not be
  2060. * called when no Delegate was passed.
  2061. *
  2062. * The default is not to treat ArrayBufferViews as host objects.
  2063. */
  2064. void SetTreatArrayBufferViewsAsHostObjects(bool mode);
  2065. /**
  2066. * Write raw data in various common formats to the buffer.
  2067. * Note that integer types are written in base-128 varint format, not with a
  2068. * binary copy. For use during an override of Delegate::WriteHostObject.
  2069. */
  2070. void WriteUint32(uint32_t value);
  2071. void WriteUint64(uint64_t value);
  2072. void WriteDouble(double value);
  2073. void WriteRawBytes(const void* source, size_t length);
  2074. ValueSerializer(const ValueSerializer&) = delete;
  2075. void operator=(const ValueSerializer&) = delete;
  2076. private:
  2077. struct PrivateData;
  2078. PrivateData* private_;
  2079. };
  2080. /**
  2081. * Deserializes values from data written with ValueSerializer, or a compatible
  2082. * implementation.
  2083. */
  2084. class V8_EXPORT ValueDeserializer {
  2085. public:
  2086. class V8_EXPORT Delegate {
  2087. public:
  2088. virtual ~Delegate() = default;
  2089. /**
  2090. * The embedder overrides this method to read some kind of host object, if
  2091. * possible. If not, a suitable exception should be thrown and
  2092. * MaybeLocal<Object>() returned.
  2093. */
  2094. virtual MaybeLocal<Object> ReadHostObject(Isolate* isolate);
  2095. /**
  2096. * Get a WasmModuleObject given a transfer_id previously provided
  2097. * by ValueSerializer::GetWasmModuleTransferId
  2098. */
  2099. virtual MaybeLocal<WasmModuleObject> GetWasmModuleFromId(
  2100. Isolate* isolate, uint32_t transfer_id);
  2101. /**
  2102. * Get a SharedArrayBuffer given a clone_id previously provided
  2103. * by ValueSerializer::GetSharedArrayBufferId
  2104. */
  2105. virtual MaybeLocal<SharedArrayBuffer> GetSharedArrayBufferFromId(
  2106. Isolate* isolate, uint32_t clone_id);
  2107. };
  2108. ValueDeserializer(Isolate* isolate, const uint8_t* data, size_t size);
  2109. ValueDeserializer(Isolate* isolate, const uint8_t* data, size_t size,
  2110. Delegate* delegate);
  2111. ~ValueDeserializer();
  2112. /**
  2113. * Reads and validates a header (including the format version).
  2114. * May, for example, reject an invalid or unsupported wire format.
  2115. */
  2116. V8_WARN_UNUSED_RESULT Maybe<bool> ReadHeader(Local<Context> context);
  2117. /**
  2118. * Deserializes a JavaScript value from the buffer.
  2119. */
  2120. V8_WARN_UNUSED_RESULT MaybeLocal<Value> ReadValue(Local<Context> context);
  2121. /**
  2122. * Accepts the array buffer corresponding to the one passed previously to
  2123. * ValueSerializer::TransferArrayBuffer.
  2124. */
  2125. void TransferArrayBuffer(uint32_t transfer_id,
  2126. Local<ArrayBuffer> array_buffer);
  2127. /**
  2128. * Similar to TransferArrayBuffer, but for SharedArrayBuffer.
  2129. * The id is not necessarily in the same namespace as unshared ArrayBuffer
  2130. * objects.
  2131. */
  2132. void TransferSharedArrayBuffer(uint32_t id,
  2133. Local<SharedArrayBuffer> shared_array_buffer);
  2134. /**
  2135. * Must be called before ReadHeader to enable support for reading the legacy
  2136. * wire format (i.e., which predates this being shipped).
  2137. *
  2138. * Don't use this unless you need to read data written by previous versions of
  2139. * blink::ScriptValueSerializer.
  2140. */
  2141. void SetSupportsLegacyWireFormat(bool supports_legacy_wire_format);
  2142. /**
  2143. * Expect inline wasm in the data stream (rather than in-memory transfer)
  2144. */
  2145. void SetExpectInlineWasm(bool allow_inline_wasm);
  2146. /**
  2147. * Reads the underlying wire format version. Likely mostly to be useful to
  2148. * legacy code reading old wire format versions. Must be called after
  2149. * ReadHeader.
  2150. */
  2151. uint32_t GetWireFormatVersion() const;
  2152. /**
  2153. * Reads raw data in various common formats to the buffer.
  2154. * Note that integer types are read in base-128 varint format, not with a
  2155. * binary copy. For use during an override of Delegate::ReadHostObject.
  2156. */
  2157. V8_WARN_UNUSED_RESULT bool ReadUint32(uint32_t* value);
  2158. V8_WARN_UNUSED_RESULT bool ReadUint64(uint64_t* value);
  2159. V8_WARN_UNUSED_RESULT bool ReadDouble(double* value);
  2160. V8_WARN_UNUSED_RESULT bool ReadRawBytes(size_t length, const void** data);
  2161. ValueDeserializer(const ValueDeserializer&) = delete;
  2162. void operator=(const ValueDeserializer&) = delete;
  2163. private:
  2164. struct PrivateData;
  2165. PrivateData* private_;
  2166. };
  2167. // --- Value ---
  2168. /**
  2169. * The superclass of all JavaScript values and objects.
  2170. */
  2171. class V8_EXPORT Value : public Data {
  2172. public:
  2173. /**
  2174. * Returns true if this value is the undefined value. See ECMA-262
  2175. * 4.3.10.
  2176. */
  2177. V8_INLINE bool IsUndefined() const;
  2178. /**
  2179. * Returns true if this value is the null value. See ECMA-262
  2180. * 4.3.11.
  2181. */
  2182. V8_INLINE bool IsNull() const;
  2183. /**
  2184. * Returns true if this value is either the null or the undefined value.
  2185. * See ECMA-262
  2186. * 4.3.11. and 4.3.12
  2187. */
  2188. V8_INLINE bool IsNullOrUndefined() const;
  2189. /**
  2190. * Returns true if this value is true.
  2191. */
  2192. bool IsTrue() const;
  2193. /**
  2194. * Returns true if this value is false.
  2195. */
  2196. bool IsFalse() const;
  2197. /**
  2198. * Returns true if this value is a symbol or a string.
  2199. */
  2200. bool IsName() const;
  2201. /**
  2202. * Returns true if this value is an instance of the String type.
  2203. * See ECMA-262 8.4.
  2204. */
  2205. V8_INLINE bool IsString() const;
  2206. /**
  2207. * Returns true if this value is a symbol.
  2208. */
  2209. bool IsSymbol() const;
  2210. /**
  2211. * Returns true if this value is a function.
  2212. */
  2213. bool IsFunction() const;
  2214. /**
  2215. * Returns true if this value is an array. Note that it will return false for
  2216. * an Proxy for an array.
  2217. */
  2218. bool IsArray() const;
  2219. /**
  2220. * Returns true if this value is an object.
  2221. */
  2222. bool IsObject() const;
  2223. /**
  2224. * Returns true if this value is a bigint.
  2225. */
  2226. bool IsBigInt() const;
  2227. /**
  2228. * Returns true if this value is boolean.
  2229. */
  2230. bool IsBoolean() const;
  2231. /**
  2232. * Returns true if this value is a number.
  2233. */
  2234. bool IsNumber() const;
  2235. /**
  2236. * Returns true if this value is external.
  2237. */
  2238. bool IsExternal() const;
  2239. /**
  2240. * Returns true if this value is a 32-bit signed integer.
  2241. */
  2242. bool IsInt32() const;
  2243. /**
  2244. * Returns true if this value is a 32-bit unsigned integer.
  2245. */
  2246. bool IsUint32() const;
  2247. /**
  2248. * Returns true if this value is a Date.
  2249. */
  2250. bool IsDate() const;
  2251. /**
  2252. * Returns true if this value is an Arguments object.
  2253. */
  2254. bool IsArgumentsObject() const;
  2255. /**
  2256. * Returns true if this value is a BigInt object.
  2257. */
  2258. bool IsBigIntObject() const;
  2259. /**
  2260. * Returns true if this value is a Boolean object.
  2261. */
  2262. bool IsBooleanObject() const;
  2263. /**
  2264. * Returns true if this value is a Number object.
  2265. */
  2266. bool IsNumberObject() const;
  2267. /**
  2268. * Returns true if this value is a String object.
  2269. */
  2270. bool IsStringObject() const;
  2271. /**
  2272. * Returns true if this value is a Symbol object.
  2273. */
  2274. bool IsSymbolObject() const;
  2275. /**
  2276. * Returns true if this value is a NativeError.
  2277. */
  2278. bool IsNativeError() const;
  2279. /**
  2280. * Returns true if this value is a RegExp.
  2281. */
  2282. bool IsRegExp() const;
  2283. /**
  2284. * Returns true if this value is an async function.
  2285. */
  2286. bool IsAsyncFunction() const;
  2287. /**
  2288. * Returns true if this value is a Generator function.
  2289. */
  2290. bool IsGeneratorFunction() const;
  2291. /**
  2292. * Returns true if this value is a Generator object (iterator).
  2293. */
  2294. bool IsGeneratorObject() const;
  2295. /**
  2296. * Returns true if this value is a Promise.
  2297. */
  2298. bool IsPromise() const;
  2299. /**
  2300. * Returns true if this value is a Map.
  2301. */
  2302. bool IsMap() const;
  2303. /**
  2304. * Returns true if this value is a Set.
  2305. */
  2306. bool IsSet() const;
  2307. /**
  2308. * Returns true if this value is a Map Iterator.
  2309. */
  2310. bool IsMapIterator() const;
  2311. /**
  2312. * Returns true if this value is a Set Iterator.
  2313. */
  2314. bool IsSetIterator() const;
  2315. /**
  2316. * Returns true if this value is a WeakMap.
  2317. */
  2318. bool IsWeakMap() const;
  2319. /**
  2320. * Returns true if this value is a WeakSet.
  2321. */
  2322. bool IsWeakSet() const;
  2323. /**
  2324. * Returns true if this value is an ArrayBuffer.
  2325. */
  2326. bool IsArrayBuffer() const;
  2327. /**
  2328. * Returns true if this value is an ArrayBufferView.
  2329. */
  2330. bool IsArrayBufferView() const;
  2331. /**
  2332. * Returns true if this value is one of TypedArrays.
  2333. */
  2334. bool IsTypedArray() const;
  2335. /**
  2336. * Returns true if this value is an Uint8Array.
  2337. */
  2338. bool IsUint8Array() const;
  2339. /**
  2340. * Returns true if this value is an Uint8ClampedArray.
  2341. */
  2342. bool IsUint8ClampedArray() const;
  2343. /**
  2344. * Returns true if this value is an Int8Array.
  2345. */
  2346. bool IsInt8Array() const;
  2347. /**
  2348. * Returns true if this value is an Uint16Array.
  2349. */
  2350. bool IsUint16Array() const;
  2351. /**
  2352. * Returns true if this value is an Int16Array.
  2353. */
  2354. bool IsInt16Array() const;
  2355. /**
  2356. * Returns true if this value is an Uint32Array.
  2357. */
  2358. bool IsUint32Array() const;
  2359. /**
  2360. * Returns true if this value is an Int32Array.
  2361. */
  2362. bool IsInt32Array() const;
  2363. /**
  2364. * Returns true if this value is a Float32Array.
  2365. */
  2366. bool IsFloat32Array() const;
  2367. /**
  2368. * Returns true if this value is a Float64Array.
  2369. */
  2370. bool IsFloat64Array() const;
  2371. /**
  2372. * Returns true if this value is a BigInt64Array.
  2373. */
  2374. bool IsBigInt64Array() const;
  2375. /**
  2376. * Returns true if this value is a BigUint64Array.
  2377. */
  2378. bool IsBigUint64Array() const;
  2379. /**
  2380. * Returns true if this value is a DataView.
  2381. */
  2382. bool IsDataView() const;
  2383. /**
  2384. * Returns true if this value is a SharedArrayBuffer.
  2385. * This is an experimental feature.
  2386. */
  2387. bool IsSharedArrayBuffer() const;
  2388. /**
  2389. * Returns true if this value is a JavaScript Proxy.
  2390. */
  2391. bool IsProxy() const;
  2392. bool IsWebAssemblyCompiledModule() const;
  2393. /**
  2394. * Returns true if the value is a Module Namespace Object.
  2395. */
  2396. bool IsModuleNamespaceObject() const;
  2397. V8_WARN_UNUSED_RESULT MaybeLocal<BigInt> ToBigInt(
  2398. Local<Context> context) const;
  2399. V8_WARN_UNUSED_RESULT MaybeLocal<Number> ToNumber(
  2400. Local<Context> context) const;
  2401. V8_WARN_UNUSED_RESULT MaybeLocal<String> ToString(
  2402. Local<Context> context) const;
  2403. V8_WARN_UNUSED_RESULT MaybeLocal<String> ToDetailString(
  2404. Local<Context> context) const;
  2405. V8_WARN_UNUSED_RESULT MaybeLocal<Object> ToObject(
  2406. Local<Context> context) const;
  2407. V8_WARN_UNUSED_RESULT MaybeLocal<Integer> ToInteger(
  2408. Local<Context> context) const;
  2409. V8_WARN_UNUSED_RESULT MaybeLocal<Uint32> ToUint32(
  2410. Local<Context> context) const;
  2411. V8_WARN_UNUSED_RESULT MaybeLocal<Int32> ToInt32(Local<Context> context) const;
  2412. Local<Boolean> ToBoolean(Isolate* isolate) const;
  2413. /**
  2414. * Attempts to convert a string to an array index.
  2415. * Returns an empty handle if the conversion fails.
  2416. */
  2417. V8_WARN_UNUSED_RESULT MaybeLocal<Uint32> ToArrayIndex(
  2418. Local<Context> context) const;
  2419. bool BooleanValue(Isolate* isolate) const;
  2420. V8_WARN_UNUSED_RESULT Maybe<double> NumberValue(Local<Context> context) const;
  2421. V8_WARN_UNUSED_RESULT Maybe<int64_t> IntegerValue(
  2422. Local<Context> context) const;
  2423. V8_WARN_UNUSED_RESULT Maybe<uint32_t> Uint32Value(
  2424. Local<Context> context) const;
  2425. V8_WARN_UNUSED_RESULT Maybe<int32_t> Int32Value(Local<Context> context) const;
  2426. /** JS == */
  2427. V8_WARN_UNUSED_RESULT Maybe<bool> Equals(Local<Context> context,
  2428. Local<Value> that) const;
  2429. bool StrictEquals(Local<Value> that) const;
  2430. bool SameValue(Local<Value> that) const;
  2431. template <class T> V8_INLINE static Value* Cast(T* value);
  2432. Local<String> TypeOf(Isolate*);
  2433. Maybe<bool> InstanceOf(Local<Context> context, Local<Object> object);
  2434. private:
  2435. V8_INLINE bool QuickIsUndefined() const;
  2436. V8_INLINE bool QuickIsNull() const;
  2437. V8_INLINE bool QuickIsNullOrUndefined() const;
  2438. V8_INLINE bool QuickIsString() const;
  2439. bool FullIsUndefined() const;
  2440. bool FullIsNull() const;
  2441. bool FullIsString() const;
  2442. };
  2443. /**
  2444. * The superclass of primitive values. See ECMA-262 4.3.2.
  2445. */
  2446. class V8_EXPORT Primitive : public Value { };
  2447. /**
  2448. * A primitive boolean value (ECMA-262, 4.3.14). Either the true
  2449. * or false value.
  2450. */
  2451. class V8_EXPORT Boolean : public Primitive {
  2452. public:
  2453. bool Value() const;
  2454. V8_INLINE static Boolean* Cast(v8::Value* obj);
  2455. V8_INLINE static Local<Boolean> New(Isolate* isolate, bool value);
  2456. private:
  2457. static void CheckCast(v8::Value* obj);
  2458. };
  2459. /**
  2460. * A superclass for symbols and strings.
  2461. */
  2462. class V8_EXPORT Name : public Primitive {
  2463. public:
  2464. /**
  2465. * Returns the identity hash for this object. The current implementation
  2466. * uses an inline property on the object to store the identity hash.
  2467. *
  2468. * The return value will never be 0. Also, it is not guaranteed to be
  2469. * unique.
  2470. */
  2471. int GetIdentityHash();
  2472. V8_INLINE static Name* Cast(Value* obj);
  2473. private:
  2474. static void CheckCast(Value* obj);
  2475. };
  2476. /**
  2477. * A flag describing different modes of string creation.
  2478. *
  2479. * Aside from performance implications there are no differences between the two
  2480. * creation modes.
  2481. */
  2482. enum class NewStringType {
  2483. /**
  2484. * Create a new string, always allocating new storage memory.
  2485. */
  2486. kNormal,
  2487. /**
  2488. * Acts as a hint that the string should be created in the
  2489. * old generation heap space and be deduplicated if an identical string
  2490. * already exists.
  2491. */
  2492. kInternalized
  2493. };
  2494. /**
  2495. * A JavaScript string value (ECMA-262, 4.3.17).
  2496. */
  2497. class V8_EXPORT String : public Name {
  2498. public:
  2499. static constexpr int kMaxLength = internal::kApiTaggedSize == 4
  2500. ? (1 << 28) - 16
  2501. : internal::kSmiMaxValue / 2 - 24;
  2502. enum Encoding {
  2503. UNKNOWN_ENCODING = 0x1,
  2504. TWO_BYTE_ENCODING = 0x0,
  2505. ONE_BYTE_ENCODING = 0x8
  2506. };
  2507. /**
  2508. * Returns the number of characters (UTF-16 code units) in this string.
  2509. */
  2510. int Length() const;
  2511. /**
  2512. * Returns the number of bytes in the UTF-8 encoded
  2513. * representation of this string.
  2514. */
  2515. int Utf8Length(Isolate* isolate) const;
  2516. /**
  2517. * Returns whether this string is known to contain only one byte data,
  2518. * i.e. ISO-8859-1 code points.
  2519. * Does not read the string.
  2520. * False negatives are possible.
  2521. */
  2522. bool IsOneByte() const;
  2523. /**
  2524. * Returns whether this string contain only one byte data,
  2525. * i.e. ISO-8859-1 code points.
  2526. * Will read the entire string in some cases.
  2527. */
  2528. bool ContainsOnlyOneByte() const;
  2529. /**
  2530. * Write the contents of the string to an external buffer.
  2531. * If no arguments are given, expects the buffer to be large
  2532. * enough to hold the entire string and NULL terminator. Copies
  2533. * the contents of the string and the NULL terminator into the
  2534. * buffer.
  2535. *
  2536. * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
  2537. * before the end of the buffer.
  2538. *
  2539. * Copies up to length characters into the output buffer.
  2540. * Only null-terminates if there is enough space in the buffer.
  2541. *
  2542. * \param buffer The buffer into which the string will be copied.
  2543. * \param start The starting position within the string at which
  2544. * copying begins.
  2545. * \param length The number of characters to copy from the string. For
  2546. * WriteUtf8 the number of bytes in the buffer.
  2547. * \param nchars_ref The number of characters written, can be NULL.
  2548. * \param options Various options that might affect performance of this or
  2549. * subsequent operations.
  2550. * \return The number of characters copied to the buffer excluding the null
  2551. * terminator. For WriteUtf8: The number of bytes copied to the buffer
  2552. * including the null terminator (if written).
  2553. */
  2554. enum WriteOptions {
  2555. NO_OPTIONS = 0,
  2556. HINT_MANY_WRITES_EXPECTED = 1,
  2557. NO_NULL_TERMINATION = 2,
  2558. PRESERVE_ONE_BYTE_NULL = 4,
  2559. // Used by WriteUtf8 to replace orphan surrogate code units with the
  2560. // unicode replacement character. Needs to be set to guarantee valid UTF-8
  2561. // output.
  2562. REPLACE_INVALID_UTF8 = 8
  2563. };
  2564. // 16-bit character codes.
  2565. int Write(Isolate* isolate, uint16_t* buffer, int start = 0, int length = -1,
  2566. int options = NO_OPTIONS) const;
  2567. // One byte characters.
  2568. int WriteOneByte(Isolate* isolate, uint8_t* buffer, int start = 0,
  2569. int length = -1, int options = NO_OPTIONS) const;
  2570. // UTF-8 encoded characters.
  2571. int WriteUtf8(Isolate* isolate, char* buffer, int length = -1,
  2572. int* nchars_ref = nullptr, int options = NO_OPTIONS) const;
  2573. /**
  2574. * A zero length string.
  2575. */
  2576. V8_INLINE static Local<String> Empty(Isolate* isolate);
  2577. /**
  2578. * Returns true if the string is external
  2579. */
  2580. bool IsExternal() const;
  2581. /**
  2582. * Returns true if the string is both external and one-byte.
  2583. */
  2584. bool IsExternalOneByte() const;
  2585. class V8_EXPORT ExternalStringResourceBase { // NOLINT
  2586. public:
  2587. virtual ~ExternalStringResourceBase() = default;
  2588. /**
  2589. * If a string is cacheable, the value returned by
  2590. * ExternalStringResource::data() may be cached, otherwise it is not
  2591. * expected to be stable beyond the current top-level task.
  2592. */
  2593. virtual bool IsCacheable() const { return true; }
  2594. // Disallow copying and assigning.
  2595. ExternalStringResourceBase(const ExternalStringResourceBase&) = delete;
  2596. void operator=(const ExternalStringResourceBase&) = delete;
  2597. protected:
  2598. ExternalStringResourceBase() = default;
  2599. /**
  2600. * Internally V8 will call this Dispose method when the external string
  2601. * resource is no longer needed. The default implementation will use the
  2602. * delete operator. This method can be overridden in subclasses to
  2603. * control how allocated external string resources are disposed.
  2604. */
  2605. virtual void Dispose() { delete this; }
  2606. /**
  2607. * For a non-cacheable string, the value returned by
  2608. * |ExternalStringResource::data()| has to be stable between |Lock()| and
  2609. * |Unlock()|, that is the string must behave as is |IsCacheable()| returned
  2610. * true.
  2611. *
  2612. * These two functions must be thread-safe, and can be called from anywhere.
  2613. * They also must handle lock depth, in the sense that each can be called
  2614. * several times, from different threads, and unlocking should only happen
  2615. * when the balance of Lock() and Unlock() calls is 0.
  2616. */
  2617. virtual void Lock() const {}
  2618. /**
  2619. * Unlocks the string.
  2620. */
  2621. virtual void Unlock() const {}
  2622. private:
  2623. friend class internal::ExternalString;
  2624. friend class v8::String;
  2625. friend class internal::ScopedExternalStringLock;
  2626. };
  2627. /**
  2628. * An ExternalStringResource is a wrapper around a two-byte string
  2629. * buffer that resides outside V8's heap. Implement an
  2630. * ExternalStringResource to manage the life cycle of the underlying
  2631. * buffer. Note that the string data must be immutable.
  2632. */
  2633. class V8_EXPORT ExternalStringResource
  2634. : public ExternalStringResourceBase {
  2635. public:
  2636. /**
  2637. * Override the destructor to manage the life cycle of the underlying
  2638. * buffer.
  2639. */
  2640. ~ExternalStringResource() override = default;
  2641. /**
  2642. * The string data from the underlying buffer.
  2643. */
  2644. virtual const uint16_t* data() const = 0;
  2645. /**
  2646. * The length of the string. That is, the number of two-byte characters.
  2647. */
  2648. virtual size_t length() const = 0;
  2649. protected:
  2650. ExternalStringResource() = default;
  2651. };
  2652. /**
  2653. * An ExternalOneByteStringResource is a wrapper around an one-byte
  2654. * string buffer that resides outside V8's heap. Implement an
  2655. * ExternalOneByteStringResource to manage the life cycle of the
  2656. * underlying buffer. Note that the string data must be immutable
  2657. * and that the data must be Latin-1 and not UTF-8, which would require
  2658. * special treatment internally in the engine and do not allow efficient
  2659. * indexing. Use String::New or convert to 16 bit data for non-Latin1.
  2660. */
  2661. class V8_EXPORT ExternalOneByteStringResource
  2662. : public ExternalStringResourceBase {
  2663. public:
  2664. /**
  2665. * Override the destructor to manage the life cycle of the underlying
  2666. * buffer.
  2667. */
  2668. ~ExternalOneByteStringResource() override = default;
  2669. /** The string data from the underlying buffer.*/
  2670. virtual const char* data() const = 0;
  2671. /** The number of Latin-1 characters in the string.*/
  2672. virtual size_t length() const = 0;
  2673. protected:
  2674. ExternalOneByteStringResource() = default;
  2675. };
  2676. /**
  2677. * If the string is an external string, return the ExternalStringResourceBase
  2678. * regardless of the encoding, otherwise return NULL. The encoding of the
  2679. * string is returned in encoding_out.
  2680. */
  2681. V8_INLINE ExternalStringResourceBase* GetExternalStringResourceBase(
  2682. Encoding* encoding_out) const;
  2683. /**
  2684. * Get the ExternalStringResource for an external string. Returns
  2685. * NULL if IsExternal() doesn't return true.
  2686. */
  2687. V8_INLINE ExternalStringResource* GetExternalStringResource() const;
  2688. /**
  2689. * Get the ExternalOneByteStringResource for an external one-byte string.
  2690. * Returns NULL if IsExternalOneByte() doesn't return true.
  2691. */
  2692. const ExternalOneByteStringResource* GetExternalOneByteStringResource() const;
  2693. V8_INLINE static String* Cast(v8::Value* obj);
  2694. /** Allocates a new string from UTF-8 data. Only returns an empty value when
  2695. * length > kMaxLength. **/
  2696. static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromUtf8(
  2697. Isolate* isolate, const char* data,
  2698. NewStringType type = NewStringType::kNormal, int length = -1);
  2699. /** Allocates a new string from Latin-1 data. Only returns an empty value
  2700. * when length > kMaxLength. **/
  2701. static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromOneByte(
  2702. Isolate* isolate, const uint8_t* data,
  2703. NewStringType type = NewStringType::kNormal, int length = -1);
  2704. /** Allocates a new string from UTF-16 data. Only returns an empty value when
  2705. * length > kMaxLength. **/
  2706. static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromTwoByte(
  2707. Isolate* isolate, const uint16_t* data,
  2708. NewStringType type = NewStringType::kNormal, int length = -1);
  2709. /**
  2710. * Creates a new string by concatenating the left and the right strings
  2711. * passed in as parameters.
  2712. */
  2713. static Local<String> Concat(Isolate* isolate, Local<String> left,
  2714. Local<String> right);
  2715. /**
  2716. * Creates a new external string using the data defined in the given
  2717. * resource. When the external string is no longer live on V8's heap the
  2718. * resource will be disposed by calling its Dispose method. The caller of
  2719. * this function should not otherwise delete or modify the resource. Neither
  2720. * should the underlying buffer be deallocated or modified except through the
  2721. * destructor of the external string resource.
  2722. */
  2723. static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewExternalTwoByte(
  2724. Isolate* isolate, ExternalStringResource* resource);
  2725. /**
  2726. * Associate an external string resource with this string by transforming it
  2727. * in place so that existing references to this string in the JavaScript heap
  2728. * will use the external string resource. The external string resource's
  2729. * character contents need to be equivalent to this string.
  2730. * Returns true if the string has been changed to be an external string.
  2731. * The string is not modified if the operation fails. See NewExternal for
  2732. * information on the lifetime of the resource.
  2733. */
  2734. bool MakeExternal(ExternalStringResource* resource);
  2735. /**
  2736. * Creates a new external string using the one-byte data defined in the given
  2737. * resource. When the external string is no longer live on V8's heap the
  2738. * resource will be disposed by calling its Dispose method. The caller of
  2739. * this function should not otherwise delete or modify the resource. Neither
  2740. * should the underlying buffer be deallocated or modified except through the
  2741. * destructor of the external string resource.
  2742. */
  2743. static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewExternalOneByte(
  2744. Isolate* isolate, ExternalOneByteStringResource* resource);
  2745. /**
  2746. * Associate an external string resource with this string by transforming it
  2747. * in place so that existing references to this string in the JavaScript heap
  2748. * will use the external string resource. The external string resource's
  2749. * character contents need to be equivalent to this string.
  2750. * Returns true if the string has been changed to be an external string.
  2751. * The string is not modified if the operation fails. See NewExternal for
  2752. * information on the lifetime of the resource.
  2753. */
  2754. bool MakeExternal(ExternalOneByteStringResource* resource);
  2755. /**
  2756. * Returns true if this string can be made external.
  2757. */
  2758. bool CanMakeExternal();
  2759. /**
  2760. * Returns true if the strings values are equal. Same as JS ==/===.
  2761. */
  2762. bool StringEquals(Local<String> str);
  2763. /**
  2764. * Converts an object to a UTF-8-encoded character array. Useful if
  2765. * you want to print the object. If conversion to a string fails
  2766. * (e.g. due to an exception in the toString() method of the object)
  2767. * then the length() method returns 0 and the * operator returns
  2768. * NULL.
  2769. */
  2770. class V8_EXPORT Utf8Value {
  2771. public:
  2772. Utf8Value(Isolate* isolate, Local<v8::Value> obj);
  2773. ~Utf8Value();
  2774. char* operator*() { return str_; }
  2775. const char* operator*() const { return str_; }
  2776. int length() const { return length_; }
  2777. // Disallow copying and assigning.
  2778. Utf8Value(const Utf8Value&) = delete;
  2779. void operator=(const Utf8Value&) = delete;
  2780. private:
  2781. char* str_;
  2782. int length_;
  2783. };
  2784. /**
  2785. * Converts an object to a two-byte (UTF-16-encoded) string.
  2786. * If conversion to a string fails (eg. due to an exception in the toString()
  2787. * method of the object) then the length() method returns 0 and the * operator
  2788. * returns NULL.
  2789. */
  2790. class V8_EXPORT Value {
  2791. public:
  2792. Value(Isolate* isolate, Local<v8::Value> obj);
  2793. ~Value();
  2794. uint16_t* operator*() { return str_; }
  2795. const uint16_t* operator*() const { return str_; }
  2796. int length() const { return length_; }
  2797. // Disallow copying and assigning.
  2798. Value(const Value&) = delete;
  2799. void operator=(const Value&) = delete;
  2800. private:
  2801. uint16_t* str_;
  2802. int length_;
  2803. };
  2804. private:
  2805. void VerifyExternalStringResourceBase(ExternalStringResourceBase* v,
  2806. Encoding encoding) const;
  2807. void VerifyExternalStringResource(ExternalStringResource* val) const;
  2808. ExternalStringResource* GetExternalStringResourceSlow() const;
  2809. ExternalStringResourceBase* GetExternalStringResourceBaseSlow(
  2810. String::Encoding* encoding_out) const;
  2811. static void CheckCast(v8::Value* obj);
  2812. };
  2813. /**
  2814. * A JavaScript symbol (ECMA-262 edition 6)
  2815. */
  2816. class V8_EXPORT Symbol : public Name {
  2817. public:
  2818. /**
  2819. * Returns the description string of the symbol, or undefined if none.
  2820. */
  2821. Local<Value> Description() const;
  2822. V8_DEPRECATE_SOON("Use Symbol::Description()")
  2823. Local<Value> Name() const { return Description(); }
  2824. /**
  2825. * Create a symbol. If description is not empty, it will be used as the
  2826. * description.
  2827. */
  2828. static Local<Symbol> New(Isolate* isolate,
  2829. Local<String> description = Local<String>());
  2830. /**
  2831. * Access global symbol registry.
  2832. * Note that symbols created this way are never collected, so
  2833. * they should only be used for statically fixed properties.
  2834. * Also, there is only one global name space for the descriptions used as
  2835. * keys.
  2836. * To minimize the potential for clashes, use qualified names as keys.
  2837. */
  2838. static Local<Symbol> For(Isolate* isolate, Local<String> description);
  2839. /**
  2840. * Retrieve a global symbol. Similar to |For|, but using a separate
  2841. * registry that is not accessible by (and cannot clash with) JavaScript code.
  2842. */
  2843. static Local<Symbol> ForApi(Isolate* isolate, Local<String> description);
  2844. // Well-known symbols
  2845. static Local<Symbol> GetAsyncIterator(Isolate* isolate);
  2846. static Local<Symbol> GetHasInstance(Isolate* isolate);
  2847. static Local<Symbol> GetIsConcatSpreadable(Isolate* isolate);
  2848. static Local<Symbol> GetIterator(Isolate* isolate);
  2849. static Local<Symbol> GetMatch(Isolate* isolate);
  2850. static Local<Symbol> GetReplace(Isolate* isolate);
  2851. static Local<Symbol> GetSearch(Isolate* isolate);
  2852. static Local<Symbol> GetSplit(Isolate* isolate);
  2853. static Local<Symbol> GetToPrimitive(Isolate* isolate);
  2854. static Local<Symbol> GetToStringTag(Isolate* isolate);
  2855. static Local<Symbol> GetUnscopables(Isolate* isolate);
  2856. V8_INLINE static Symbol* Cast(Value* obj);
  2857. private:
  2858. Symbol();
  2859. static void CheckCast(Value* obj);
  2860. };
  2861. /**
  2862. * A private symbol
  2863. *
  2864. * This is an experimental feature. Use at your own risk.
  2865. */
  2866. class V8_EXPORT Private : public Data {
  2867. public:
  2868. /**
  2869. * Returns the print name string of the private symbol, or undefined if none.
  2870. */
  2871. Local<Value> Name() const;
  2872. /**
  2873. * Create a private symbol. If name is not empty, it will be the description.
  2874. */
  2875. static Local<Private> New(Isolate* isolate,
  2876. Local<String> name = Local<String>());
  2877. /**
  2878. * Retrieve a global private symbol. If a symbol with this name has not
  2879. * been retrieved in the same isolate before, it is created.
  2880. * Note that private symbols created this way are never collected, so
  2881. * they should only be used for statically fixed properties.
  2882. * Also, there is only one global name space for the names used as keys.
  2883. * To minimize the potential for clashes, use qualified names as keys,
  2884. * e.g., "Class#property".
  2885. */
  2886. static Local<Private> ForApi(Isolate* isolate, Local<String> name);
  2887. V8_INLINE static Private* Cast(Data* data);
  2888. private:
  2889. Private();
  2890. static void CheckCast(Data* that);
  2891. };
  2892. /**
  2893. * A JavaScript number value (ECMA-262, 4.3.20)
  2894. */
  2895. class V8_EXPORT Number : public Primitive {
  2896. public:
  2897. double Value() const;
  2898. static Local<Number> New(Isolate* isolate, double value);
  2899. V8_INLINE static Number* Cast(v8::Value* obj);
  2900. private:
  2901. Number();
  2902. static void CheckCast(v8::Value* obj);
  2903. };
  2904. /**
  2905. * A JavaScript value representing a signed integer.
  2906. */
  2907. class V8_EXPORT Integer : public Number {
  2908. public:
  2909. static Local<Integer> New(Isolate* isolate, int32_t value);
  2910. static Local<Integer> NewFromUnsigned(Isolate* isolate, uint32_t value);
  2911. int64_t Value() const;
  2912. V8_INLINE static Integer* Cast(v8::Value* obj);
  2913. private:
  2914. Integer();
  2915. static void CheckCast(v8::Value* obj);
  2916. };
  2917. /**
  2918. * A JavaScript value representing a 32-bit signed integer.
  2919. */
  2920. class V8_EXPORT Int32 : public Integer {
  2921. public:
  2922. int32_t Value() const;
  2923. V8_INLINE static Int32* Cast(v8::Value* obj);
  2924. private:
  2925. Int32();
  2926. static void CheckCast(v8::Value* obj);
  2927. };
  2928. /**
  2929. * A JavaScript value representing a 32-bit unsigned integer.
  2930. */
  2931. class V8_EXPORT Uint32 : public Integer {
  2932. public:
  2933. uint32_t Value() const;
  2934. V8_INLINE static Uint32* Cast(v8::Value* obj);
  2935. private:
  2936. Uint32();
  2937. static void CheckCast(v8::Value* obj);
  2938. };
  2939. /**
  2940. * A JavaScript BigInt value (https://tc39.github.io/proposal-bigint)
  2941. */
  2942. class V8_EXPORT BigInt : public Primitive {
  2943. public:
  2944. static Local<BigInt> New(Isolate* isolate, int64_t value);
  2945. static Local<BigInt> NewFromUnsigned(Isolate* isolate, uint64_t value);
  2946. /**
  2947. * Creates a new BigInt object using a specified sign bit and a
  2948. * specified list of digits/words.
  2949. * The resulting number is calculated as:
  2950. *
  2951. * (-1)^sign_bit * (words[0] * (2^64)^0 + words[1] * (2^64)^1 + ...)
  2952. */
  2953. static MaybeLocal<BigInt> NewFromWords(Local<Context> context, int sign_bit,
  2954. int word_count, const uint64_t* words);
  2955. /**
  2956. * Returns the value of this BigInt as an unsigned 64-bit integer.
  2957. * If `lossless` is provided, it will reflect whether the return value was
  2958. * truncated or wrapped around. In particular, it is set to `false` if this
  2959. * BigInt is negative.
  2960. */
  2961. uint64_t Uint64Value(bool* lossless = nullptr) const;
  2962. /**
  2963. * Returns the value of this BigInt as a signed 64-bit integer.
  2964. * If `lossless` is provided, it will reflect whether this BigInt was
  2965. * truncated or not.
  2966. */
  2967. int64_t Int64Value(bool* lossless = nullptr) const;
  2968. /**
  2969. * Returns the number of 64-bit words needed to store the result of
  2970. * ToWordsArray().
  2971. */
  2972. int WordCount() const;
  2973. /**
  2974. * Writes the contents of this BigInt to a specified memory location.
  2975. * `sign_bit` must be provided and will be set to 1 if this BigInt is
  2976. * negative.
  2977. * `*word_count` has to be initialized to the length of the `words` array.
  2978. * Upon return, it will be set to the actual number of words that would
  2979. * be needed to store this BigInt (i.e. the return value of `WordCount()`).
  2980. */
  2981. void ToWordsArray(int* sign_bit, int* word_count, uint64_t* words) const;
  2982. V8_INLINE static BigInt* Cast(v8::Value* obj);
  2983. private:
  2984. BigInt();
  2985. static void CheckCast(v8::Value* obj);
  2986. };
  2987. /**
  2988. * PropertyAttribute.
  2989. */
  2990. enum PropertyAttribute {
  2991. /** None. **/
  2992. None = 0,
  2993. /** ReadOnly, i.e., not writable. **/
  2994. ReadOnly = 1 << 0,
  2995. /** DontEnum, i.e., not enumerable. **/
  2996. DontEnum = 1 << 1,
  2997. /** DontDelete, i.e., not configurable. **/
  2998. DontDelete = 1 << 2
  2999. };
  3000. /**
  3001. * Accessor[Getter|Setter] are used as callback functions when
  3002. * setting|getting a particular property. See Object and ObjectTemplate's
  3003. * method SetAccessor.
  3004. */
  3005. typedef void (*AccessorGetterCallback)(
  3006. Local<String> property,
  3007. const PropertyCallbackInfo<Value>& info);
  3008. typedef void (*AccessorNameGetterCallback)(
  3009. Local<Name> property,
  3010. const PropertyCallbackInfo<Value>& info);
  3011. typedef void (*AccessorSetterCallback)(
  3012. Local<String> property,
  3013. Local<Value> value,
  3014. const PropertyCallbackInfo<void>& info);
  3015. typedef void (*AccessorNameSetterCallback)(
  3016. Local<Name> property,
  3017. Local<Value> value,
  3018. const PropertyCallbackInfo<void>& info);
  3019. /**
  3020. * Access control specifications.
  3021. *
  3022. * Some accessors should be accessible across contexts. These
  3023. * accessors have an explicit access control parameter which specifies
  3024. * the kind of cross-context access that should be allowed.
  3025. *
  3026. * TODO(dcarney): Remove PROHIBITS_OVERWRITING as it is now unused.
  3027. */
  3028. enum AccessControl {
  3029. DEFAULT = 0,
  3030. ALL_CAN_READ = 1,
  3031. ALL_CAN_WRITE = 1 << 1,
  3032. PROHIBITS_OVERWRITING = 1 << 2
  3033. };
  3034. /**
  3035. * Property filter bits. They can be or'ed to build a composite filter.
  3036. */
  3037. enum PropertyFilter {
  3038. ALL_PROPERTIES = 0,
  3039. ONLY_WRITABLE = 1,
  3040. ONLY_ENUMERABLE = 2,
  3041. ONLY_CONFIGURABLE = 4,
  3042. SKIP_STRINGS = 8,
  3043. SKIP_SYMBOLS = 16
  3044. };
  3045. /**
  3046. * Options for marking whether callbacks may trigger JS-observable side effects.
  3047. * Side-effect-free callbacks are whitelisted during debug evaluation with
  3048. * throwOnSideEffect. It applies when calling a Function, FunctionTemplate,
  3049. * or an Accessor callback. For Interceptors, please see
  3050. * PropertyHandlerFlags's kHasNoSideEffect.
  3051. * Callbacks that only cause side effects to the receiver are whitelisted if
  3052. * invoked on receiver objects that are created within the same debug-evaluate
  3053. * call, as these objects are temporary and the side effect does not escape.
  3054. */
  3055. enum class SideEffectType {
  3056. kHasSideEffect,
  3057. kHasNoSideEffect,
  3058. kHasSideEffectToReceiver
  3059. };
  3060. /**
  3061. * Keys/Properties filter enums:
  3062. *
  3063. * KeyCollectionMode limits the range of collected properties. kOwnOnly limits
  3064. * the collected properties to the given Object only. kIncludesPrototypes will
  3065. * include all keys of the objects's prototype chain as well.
  3066. */
  3067. enum class KeyCollectionMode { kOwnOnly, kIncludePrototypes };
  3068. /**
  3069. * kIncludesIndices allows for integer indices to be collected, while
  3070. * kSkipIndices will exclude integer indices from being collected.
  3071. */
  3072. enum class IndexFilter { kIncludeIndices, kSkipIndices };
  3073. /**
  3074. * kConvertToString will convert integer indices to strings.
  3075. * kKeepNumbers will return numbers for integer indices.
  3076. */
  3077. enum class KeyConversionMode { kConvertToString, kKeepNumbers, kNoNumbers };
  3078. /**
  3079. * Integrity level for objects.
  3080. */
  3081. enum class IntegrityLevel { kFrozen, kSealed };
  3082. /**
  3083. * A JavaScript object (ECMA-262, 4.3.3)
  3084. */
  3085. class V8_EXPORT Object : public Value {
  3086. public:
  3087. /**
  3088. * Set only return Just(true) or Empty(), so if it should never fail, use
  3089. * result.Check().
  3090. */
  3091. V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context,
  3092. Local<Value> key, Local<Value> value);
  3093. V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context, uint32_t index,
  3094. Local<Value> value);
  3095. // Implements CreateDataProperty (ECMA-262, 7.3.4).
  3096. //
  3097. // Defines a configurable, writable, enumerable property with the given value
  3098. // on the object unless the property already exists and is not configurable
  3099. // or the object is not extensible.
  3100. //
  3101. // Returns true on success.
  3102. V8_WARN_UNUSED_RESULT Maybe<bool> CreateDataProperty(Local<Context> context,
  3103. Local<Name> key,
  3104. Local<Value> value);
  3105. V8_WARN_UNUSED_RESULT Maybe<bool> CreateDataProperty(Local<Context> context,
  3106. uint32_t index,
  3107. Local<Value> value);
  3108. // Implements DefineOwnProperty.
  3109. //
  3110. // In general, CreateDataProperty will be faster, however, does not allow
  3111. // for specifying attributes.
  3112. //
  3113. // Returns true on success.
  3114. V8_WARN_UNUSED_RESULT Maybe<bool> DefineOwnProperty(
  3115. Local<Context> context, Local<Name> key, Local<Value> value,
  3116. PropertyAttribute attributes = None);
  3117. // Implements Object.DefineProperty(O, P, Attributes), see Ecma-262 19.1.2.4.
  3118. //
  3119. // The defineProperty function is used to add an own property or
  3120. // update the attributes of an existing own property of an object.
  3121. //
  3122. // Both data and accessor descriptors can be used.
  3123. //
  3124. // In general, CreateDataProperty is faster, however, does not allow
  3125. // for specifying attributes or an accessor descriptor.
  3126. //
  3127. // The PropertyDescriptor can change when redefining a property.
  3128. //
  3129. // Returns true on success.
  3130. V8_WARN_UNUSED_RESULT Maybe<bool> DefineProperty(
  3131. Local<Context> context, Local<Name> key,
  3132. PropertyDescriptor& descriptor); // NOLINT(runtime/references)
  3133. V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
  3134. Local<Value> key);
  3135. V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
  3136. uint32_t index);
  3137. /**
  3138. * Gets the property attributes of a property which can be None or
  3139. * any combination of ReadOnly, DontEnum and DontDelete. Returns
  3140. * None when the property doesn't exist.
  3141. */
  3142. V8_WARN_UNUSED_RESULT Maybe<PropertyAttribute> GetPropertyAttributes(
  3143. Local<Context> context, Local<Value> key);
  3144. /**
  3145. * Returns Object.getOwnPropertyDescriptor as per ES2016 section 19.1.2.6.
  3146. */
  3147. V8_WARN_UNUSED_RESULT MaybeLocal<Value> GetOwnPropertyDescriptor(
  3148. Local<Context> context, Local<Name> key);
  3149. /**
  3150. * Object::Has() calls the abstract operation HasProperty(O, P) described
  3151. * in ECMA-262, 7.3.10. Has() returns
  3152. * true, if the object has the property, either own or on the prototype chain.
  3153. * Interceptors, i.e., PropertyQueryCallbacks, are called if present.
  3154. *
  3155. * Has() has the same side effects as JavaScript's `variable in object`.
  3156. * For example, calling Has() on a revoked proxy will throw an exception.
  3157. *
  3158. * \note Has() converts the key to a name, which possibly calls back into
  3159. * JavaScript.
  3160. *
  3161. * See also v8::Object::HasOwnProperty() and
  3162. * v8::Object::HasRealNamedProperty().
  3163. */
  3164. V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
  3165. Local<Value> key);
  3166. V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context,
  3167. Local<Value> key);
  3168. V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context, uint32_t index);
  3169. V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context,
  3170. uint32_t index);
  3171. /**
  3172. * Note: SideEffectType affects the getter only, not the setter.
  3173. */
  3174. V8_WARN_UNUSED_RESULT Maybe<bool> SetAccessor(
  3175. Local<Context> context, Local<Name> name,
  3176. AccessorNameGetterCallback getter,
  3177. AccessorNameSetterCallback setter = nullptr,
  3178. MaybeLocal<Value> data = MaybeLocal<Value>(),
  3179. AccessControl settings = DEFAULT, PropertyAttribute attribute = None,
  3180. SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect,
  3181. SideEffectType setter_side_effect_type = SideEffectType::kHasSideEffect);
  3182. void SetAccessorProperty(Local<Name> name, Local<Function> getter,
  3183. Local<Function> setter = Local<Function>(),
  3184. PropertyAttribute attribute = None,
  3185. AccessControl settings = DEFAULT);
  3186. /**
  3187. * Sets a native data property like Template::SetNativeDataProperty, but
  3188. * this method sets on this object directly.
  3189. */
  3190. V8_WARN_UNUSED_RESULT Maybe<bool> SetNativeDataProperty(
  3191. Local<Context> context, Local<Name> name,
  3192. AccessorNameGetterCallback getter,
  3193. AccessorNameSetterCallback setter = nullptr,
  3194. Local<Value> data = Local<Value>(), PropertyAttribute attributes = None,
  3195. SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect,
  3196. SideEffectType setter_side_effect_type = SideEffectType::kHasSideEffect);
  3197. /**
  3198. * Attempts to create a property with the given name which behaves like a data
  3199. * property, except that the provided getter is invoked (and provided with the
  3200. * data value) to supply its value the first time it is read. After the
  3201. * property is accessed once, it is replaced with an ordinary data property.
  3202. *
  3203. * Analogous to Template::SetLazyDataProperty.
  3204. */
  3205. V8_WARN_UNUSED_RESULT Maybe<bool> SetLazyDataProperty(
  3206. Local<Context> context, Local<Name> name,
  3207. AccessorNameGetterCallback getter, Local<Value> data = Local<Value>(),
  3208. PropertyAttribute attributes = None,
  3209. SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect,
  3210. SideEffectType setter_side_effect_type = SideEffectType::kHasSideEffect);
  3211. /**
  3212. * Functionality for private properties.
  3213. * This is an experimental feature, use at your own risk.
  3214. * Note: Private properties are not inherited. Do not rely on this, since it
  3215. * may change.
  3216. */
  3217. Maybe<bool> HasPrivate(Local<Context> context, Local<Private> key);
  3218. Maybe<bool> SetPrivate(Local<Context> context, Local<Private> key,
  3219. Local<Value> value);
  3220. Maybe<bool> DeletePrivate(Local<Context> context, Local<Private> key);
  3221. MaybeLocal<Value> GetPrivate(Local<Context> context, Local<Private> key);
  3222. /**
  3223. * Returns an array containing the names of the enumerable properties
  3224. * of this object, including properties from prototype objects. The
  3225. * array returned by this method contains the same values as would
  3226. * be enumerated by a for-in statement over this object.
  3227. */
  3228. V8_WARN_UNUSED_RESULT MaybeLocal<Array> GetPropertyNames(
  3229. Local<Context> context);
  3230. V8_WARN_UNUSED_RESULT MaybeLocal<Array> GetPropertyNames(
  3231. Local<Context> context, KeyCollectionMode mode,
  3232. PropertyFilter property_filter, IndexFilter index_filter,
  3233. KeyConversionMode key_conversion = KeyConversionMode::kKeepNumbers);
  3234. /**
  3235. * This function has the same functionality as GetPropertyNames but
  3236. * the returned array doesn't contain the names of properties from
  3237. * prototype objects.
  3238. */
  3239. V8_WARN_UNUSED_RESULT MaybeLocal<Array> GetOwnPropertyNames(
  3240. Local<Context> context);
  3241. /**
  3242. * Returns an array containing the names of the filtered properties
  3243. * of this object, including properties from prototype objects. The
  3244. * array returned by this method contains the same values as would
  3245. * be enumerated by a for-in statement over this object.
  3246. */
  3247. V8_WARN_UNUSED_RESULT MaybeLocal<Array> GetOwnPropertyNames(
  3248. Local<Context> context, PropertyFilter filter,
  3249. KeyConversionMode key_conversion = KeyConversionMode::kKeepNumbers);
  3250. /**
  3251. * Get the prototype object. This does not skip objects marked to
  3252. * be skipped by __proto__ and it does not consult the security
  3253. * handler.
  3254. */
  3255. Local<Value> GetPrototype();
  3256. /**
  3257. * Set the prototype object. This does not skip objects marked to
  3258. * be skipped by __proto__ and it does not consult the security
  3259. * handler.
  3260. */
  3261. V8_WARN_UNUSED_RESULT Maybe<bool> SetPrototype(Local<Context> context,
  3262. Local<Value> prototype);
  3263. /**
  3264. * Finds an instance of the given function template in the prototype
  3265. * chain.
  3266. */
  3267. Local<Object> FindInstanceInPrototypeChain(Local<FunctionTemplate> tmpl);
  3268. /**
  3269. * Call builtin Object.prototype.toString on this object.
  3270. * This is different from Value::ToString() that may call
  3271. * user-defined toString function. This one does not.
  3272. */
  3273. V8_WARN_UNUSED_RESULT MaybeLocal<String> ObjectProtoToString(
  3274. Local<Context> context);
  3275. /**
  3276. * Returns the name of the function invoked as a constructor for this object.
  3277. */
  3278. Local<String> GetConstructorName();
  3279. /**
  3280. * Sets the integrity level of the object.
  3281. */
  3282. Maybe<bool> SetIntegrityLevel(Local<Context> context, IntegrityLevel level);
  3283. /** Gets the number of internal fields for this Object. */
  3284. int InternalFieldCount();
  3285. /** Same as above, but works for PersistentBase. */
  3286. V8_INLINE static int InternalFieldCount(
  3287. const PersistentBase<Object>& object) {
  3288. return object.val_->InternalFieldCount();
  3289. }
  3290. /** Same as above, but works for TracedReferenceBase. */
  3291. V8_INLINE static int InternalFieldCount(
  3292. const TracedReferenceBase<Object>& object) {
  3293. return object.val_->InternalFieldCount();
  3294. }
  3295. /** Gets the value from an internal field. */
  3296. V8_INLINE Local<Value> GetInternalField(int index);
  3297. /** Sets the value in an internal field. */
  3298. void SetInternalField(int index, Local<Value> value);
  3299. /**
  3300. * Gets a 2-byte-aligned native pointer from an internal field. This field
  3301. * must have been set by SetAlignedPointerInInternalField, everything else
  3302. * leads to undefined behavior.
  3303. */
  3304. V8_INLINE void* GetAlignedPointerFromInternalField(int index);
  3305. /** Same as above, but works for PersistentBase. */
  3306. V8_INLINE static void* GetAlignedPointerFromInternalField(
  3307. const PersistentBase<Object>& object, int index) {
  3308. return object.val_->GetAlignedPointerFromInternalField(index);
  3309. }
  3310. /** Same as above, but works for TracedGlobal. */
  3311. V8_INLINE static void* GetAlignedPointerFromInternalField(
  3312. const TracedReferenceBase<Object>& object, int index) {
  3313. return object.val_->GetAlignedPointerFromInternalField(index);
  3314. }
  3315. /**
  3316. * Sets a 2-byte-aligned native pointer in an internal field. To retrieve such
  3317. * a field, GetAlignedPointerFromInternalField must be used, everything else
  3318. * leads to undefined behavior.
  3319. */
  3320. void SetAlignedPointerInInternalField(int index, void* value);
  3321. void SetAlignedPointerInInternalFields(int argc, int indices[],
  3322. void* values[]);
  3323. /**
  3324. * HasOwnProperty() is like JavaScript's Object.prototype.hasOwnProperty().
  3325. *
  3326. * See also v8::Object::Has() and v8::Object::HasRealNamedProperty().
  3327. */
  3328. V8_WARN_UNUSED_RESULT Maybe<bool> HasOwnProperty(Local<Context> context,
  3329. Local<Name> key);
  3330. V8_WARN_UNUSED_RESULT Maybe<bool> HasOwnProperty(Local<Context> context,
  3331. uint32_t index);
  3332. /**
  3333. * Use HasRealNamedProperty() if you want to check if an object has an own
  3334. * property without causing side effects, i.e., without calling interceptors.
  3335. *
  3336. * This function is similar to v8::Object::HasOwnProperty(), but it does not
  3337. * call interceptors.
  3338. *
  3339. * \note Consider using non-masking interceptors, i.e., the interceptors are
  3340. * not called if the receiver has the real named property. See
  3341. * `v8::PropertyHandlerFlags::kNonMasking`.
  3342. *
  3343. * See also v8::Object::Has().
  3344. */
  3345. V8_WARN_UNUSED_RESULT Maybe<bool> HasRealNamedProperty(Local<Context> context,
  3346. Local<Name> key);
  3347. V8_WARN_UNUSED_RESULT Maybe<bool> HasRealIndexedProperty(
  3348. Local<Context> context, uint32_t index);
  3349. V8_WARN_UNUSED_RESULT Maybe<bool> HasRealNamedCallbackProperty(
  3350. Local<Context> context, Local<Name> key);
  3351. /**
  3352. * If result.IsEmpty() no real property was located in the prototype chain.
  3353. * This means interceptors in the prototype chain are not called.
  3354. */
  3355. V8_WARN_UNUSED_RESULT MaybeLocal<Value> GetRealNamedPropertyInPrototypeChain(
  3356. Local<Context> context, Local<Name> key);
  3357. /**
  3358. * Gets the property attributes of a real property in the prototype chain,
  3359. * which can be None or any combination of ReadOnly, DontEnum and DontDelete.
  3360. * Interceptors in the prototype chain are not called.
  3361. */
  3362. V8_WARN_UNUSED_RESULT Maybe<PropertyAttribute>
  3363. GetRealNamedPropertyAttributesInPrototypeChain(Local<Context> context,
  3364. Local<Name> key);
  3365. /**
  3366. * If result.IsEmpty() no real property was located on the object or
  3367. * in the prototype chain.
  3368. * This means interceptors in the prototype chain are not called.
  3369. */
  3370. V8_WARN_UNUSED_RESULT MaybeLocal<Value> GetRealNamedProperty(
  3371. Local<Context> context, Local<Name> key);
  3372. /**
  3373. * Gets the property attributes of a real property which can be
  3374. * None or any combination of ReadOnly, DontEnum and DontDelete.
  3375. * Interceptors in the prototype chain are not called.
  3376. */
  3377. V8_WARN_UNUSED_RESULT Maybe<PropertyAttribute> GetRealNamedPropertyAttributes(
  3378. Local<Context> context, Local<Name> key);
  3379. /** Tests for a named lookup interceptor.*/
  3380. bool HasNamedLookupInterceptor();
  3381. /** Tests for an index lookup interceptor.*/
  3382. bool HasIndexedLookupInterceptor();
  3383. /**
  3384. * Returns the identity hash for this object. The current implementation
  3385. * uses a hidden property on the object to store the identity hash.
  3386. *
  3387. * The return value will never be 0. Also, it is not guaranteed to be
  3388. * unique.
  3389. */
  3390. int GetIdentityHash();
  3391. /**
  3392. * Clone this object with a fast but shallow copy. Values will point
  3393. * to the same values as the original object.
  3394. */
  3395. // TODO(dcarney): take an isolate and optionally bail out?
  3396. Local<Object> Clone();
  3397. /**
  3398. * Returns the context in which the object was created.
  3399. */
  3400. Local<Context> CreationContext();
  3401. /** Same as above, but works for Persistents */
  3402. V8_INLINE static Local<Context> CreationContext(
  3403. const PersistentBase<Object>& object) {
  3404. return object.val_->CreationContext();
  3405. }
  3406. /**
  3407. * Checks whether a callback is set by the
  3408. * ObjectTemplate::SetCallAsFunctionHandler method.
  3409. * When an Object is callable this method returns true.
  3410. */
  3411. bool IsCallable();
  3412. /**
  3413. * True if this object is a constructor.
  3414. */
  3415. bool IsConstructor();
  3416. /**
  3417. * True if this object can carry information relevant to the embedder in its
  3418. * embedder fields, false otherwise. This is generally true for objects
  3419. * constructed through function templates but also holds for other types where
  3420. * V8 automatically adds internal fields at compile time, such as e.g.
  3421. * v8::ArrayBuffer.
  3422. */
  3423. bool IsApiWrapper();
  3424. /**
  3425. * Call an Object as a function if a callback is set by the
  3426. * ObjectTemplate::SetCallAsFunctionHandler method.
  3427. */
  3428. V8_WARN_UNUSED_RESULT MaybeLocal<Value> CallAsFunction(Local<Context> context,
  3429. Local<Value> recv,
  3430. int argc,
  3431. Local<Value> argv[]);
  3432. /**
  3433. * Call an Object as a constructor if a callback is set by the
  3434. * ObjectTemplate::SetCallAsFunctionHandler method.
  3435. * Note: This method behaves like the Function::NewInstance method.
  3436. */
  3437. V8_WARN_UNUSED_RESULT MaybeLocal<Value> CallAsConstructor(
  3438. Local<Context> context, int argc, Local<Value> argv[]);
  3439. /**
  3440. * Return the isolate to which the Object belongs to.
  3441. */
  3442. Isolate* GetIsolate();
  3443. /**
  3444. * If this object is a Set, Map, WeakSet or WeakMap, this returns a
  3445. * representation of the elements of this object as an array.
  3446. * If this object is a SetIterator or MapIterator, this returns all
  3447. * elements of the underlying collection, starting at the iterator's current
  3448. * position.
  3449. * For other types, this will return an empty MaybeLocal<Array> (without
  3450. * scheduling an exception).
  3451. */
  3452. MaybeLocal<Array> PreviewEntries(bool* is_key_value);
  3453. static Local<Object> New(Isolate* isolate);
  3454. /**
  3455. * Creates a JavaScript object with the given properties, and
  3456. * a the given prototype_or_null (which can be any JavaScript
  3457. * value, and if it's null, the newly created object won't have
  3458. * a prototype at all). This is similar to Object.create().
  3459. * All properties will be created as enumerable, configurable
  3460. * and writable properties.
  3461. */
  3462. static Local<Object> New(Isolate* isolate, Local<Value> prototype_or_null,
  3463. Local<Name>* names, Local<Value>* values,
  3464. size_t length);
  3465. V8_INLINE static Object* Cast(Value* obj);
  3466. private:
  3467. Object();
  3468. static void CheckCast(Value* obj);
  3469. Local<Value> SlowGetInternalField(int index);
  3470. void* SlowGetAlignedPointerFromInternalField(int index);
  3471. };
  3472. /**
  3473. * An instance of the built-in array constructor (ECMA-262, 15.4.2).
  3474. */
  3475. class V8_EXPORT Array : public Object {
  3476. public:
  3477. uint32_t Length() const;
  3478. /**
  3479. * Creates a JavaScript array with the given length. If the length
  3480. * is negative the returned array will have length 0.
  3481. */
  3482. static Local<Array> New(Isolate* isolate, int length = 0);
  3483. /**
  3484. * Creates a JavaScript array out of a Local<Value> array in C++
  3485. * with a known length.
  3486. */
  3487. static Local<Array> New(Isolate* isolate, Local<Value>* elements,
  3488. size_t length);
  3489. V8_INLINE static Array* Cast(Value* obj);
  3490. private:
  3491. Array();
  3492. static void CheckCast(Value* obj);
  3493. };
  3494. /**
  3495. * An instance of the built-in Map constructor (ECMA-262, 6th Edition, 23.1.1).
  3496. */
  3497. class V8_EXPORT Map : public Object {
  3498. public:
  3499. size_t Size() const;
  3500. void Clear();
  3501. V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
  3502. Local<Value> key);
  3503. V8_WARN_UNUSED_RESULT MaybeLocal<Map> Set(Local<Context> context,
  3504. Local<Value> key,
  3505. Local<Value> value);
  3506. V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
  3507. Local<Value> key);
  3508. V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context,
  3509. Local<Value> key);
  3510. /**
  3511. * Returns an array of length Size() * 2, where index N is the Nth key and
  3512. * index N + 1 is the Nth value.
  3513. */
  3514. Local<Array> AsArray() const;
  3515. /**
  3516. * Creates a new empty Map.
  3517. */
  3518. static Local<Map> New(Isolate* isolate);
  3519. V8_INLINE static Map* Cast(Value* obj);
  3520. private:
  3521. Map();
  3522. static void CheckCast(Value* obj);
  3523. };
  3524. /**
  3525. * An instance of the built-in Set constructor (ECMA-262, 6th Edition, 23.2.1).
  3526. */
  3527. class V8_EXPORT Set : public Object {
  3528. public:
  3529. size_t Size() const;
  3530. void Clear();
  3531. V8_WARN_UNUSED_RESULT MaybeLocal<Set> Add(Local<Context> context,
  3532. Local<Value> key);
  3533. V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
  3534. Local<Value> key);
  3535. V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context,
  3536. Local<Value> key);
  3537. /**
  3538. * Returns an array of the keys in this Set.
  3539. */
  3540. Local<Array> AsArray() const;
  3541. /**
  3542. * Creates a new empty Set.
  3543. */
  3544. static Local<Set> New(Isolate* isolate);
  3545. V8_INLINE static Set* Cast(Value* obj);
  3546. private:
  3547. Set();
  3548. static void CheckCast(Value* obj);
  3549. };
  3550. template<typename T>
  3551. class ReturnValue {
  3552. public:
  3553. template <class S> V8_INLINE ReturnValue(const ReturnValue<S>& that)
  3554. : value_(that.value_) {
  3555. TYPE_CHECK(T, S);
  3556. }
  3557. // Local setters
  3558. template <typename S>
  3559. V8_INLINE void Set(const Global<S>& handle);
  3560. template <typename S>
  3561. V8_INLINE void Set(const TracedReferenceBase<S>& handle);
  3562. template <typename S>
  3563. V8_INLINE void Set(const Local<S> handle);
  3564. // Fast primitive setters
  3565. V8_INLINE void Set(bool value);
  3566. V8_INLINE void Set(double i);
  3567. V8_INLINE void Set(int32_t i);
  3568. V8_INLINE void Set(uint32_t i);
  3569. // Fast JS primitive setters
  3570. V8_INLINE void SetNull();
  3571. V8_INLINE void SetUndefined();
  3572. V8_INLINE void SetEmptyString();
  3573. // Convenience getter for Isolate
  3574. V8_INLINE Isolate* GetIsolate() const;
  3575. // Pointer setter: Uncompilable to prevent inadvertent misuse.
  3576. template <typename S>
  3577. V8_INLINE void Set(S* whatever);
  3578. // Getter. Creates a new Local<> so it comes with a certain performance
  3579. // hit. If the ReturnValue was not yet set, this will return the undefined
  3580. // value.
  3581. V8_INLINE Local<Value> Get() const;
  3582. private:
  3583. template<class F> friend class ReturnValue;
  3584. template<class F> friend class FunctionCallbackInfo;
  3585. template<class F> friend class PropertyCallbackInfo;
  3586. template <class F, class G, class H>
  3587. friend class PersistentValueMapBase;
  3588. V8_INLINE void SetInternal(internal::Address value) { *value_ = value; }
  3589. V8_INLINE internal::Address GetDefaultValue();
  3590. V8_INLINE explicit ReturnValue(internal::Address* slot);
  3591. internal::Address* value_;
  3592. };
  3593. /**
  3594. * The argument information given to function call callbacks. This
  3595. * class provides access to information about the context of the call,
  3596. * including the receiver, the number and values of arguments, and
  3597. * the holder of the function.
  3598. */
  3599. template<typename T>
  3600. class FunctionCallbackInfo {
  3601. public:
  3602. /** The number of available arguments. */
  3603. V8_INLINE int Length() const;
  3604. /** Accessor for the available arguments. */
  3605. V8_INLINE Local<Value> operator[](int i) const;
  3606. /** Returns the receiver. This corresponds to the "this" value. */
  3607. V8_INLINE Local<Object> This() const;
  3608. /**
  3609. * If the callback was created without a Signature, this is the same
  3610. * value as This(). If there is a signature, and the signature didn't match
  3611. * This() but one of its hidden prototypes, this will be the respective
  3612. * hidden prototype.
  3613. *
  3614. * Note that this is not the prototype of This() on which the accessor
  3615. * referencing this callback was found (which in V8 internally is often
  3616. * referred to as holder [sic]).
  3617. */
  3618. V8_INLINE Local<Object> Holder() const;
  3619. /** For construct calls, this returns the "new.target" value. */
  3620. V8_INLINE Local<Value> NewTarget() const;
  3621. /** Indicates whether this is a regular call or a construct call. */
  3622. V8_INLINE bool IsConstructCall() const;
  3623. /** The data argument specified when creating the callback. */
  3624. V8_INLINE Local<Value> Data() const;
  3625. /** The current Isolate. */
  3626. V8_INLINE Isolate* GetIsolate() const;
  3627. /** The ReturnValue for the call. */
  3628. V8_INLINE ReturnValue<T> GetReturnValue() const;
  3629. // This shouldn't be public, but the arm compiler needs it.
  3630. static const int kArgsLength = 6;
  3631. protected:
  3632. friend class internal::FunctionCallbackArguments;
  3633. friend class internal::CustomArguments<FunctionCallbackInfo>;
  3634. friend class debug::ConsoleCallArguments;
  3635. static const int kHolderIndex = 0;
  3636. static const int kIsolateIndex = 1;
  3637. static const int kReturnValueDefaultValueIndex = 2;
  3638. static const int kReturnValueIndex = 3;
  3639. static const int kDataIndex = 4;
  3640. static const int kNewTargetIndex = 5;
  3641. V8_INLINE FunctionCallbackInfo(internal::Address* implicit_args,
  3642. internal::Address* values, int length);
  3643. internal::Address* implicit_args_;
  3644. internal::Address* values_;
  3645. int length_;
  3646. };
  3647. /**
  3648. * The information passed to a property callback about the context
  3649. * of the property access.
  3650. */
  3651. template<typename T>
  3652. class PropertyCallbackInfo {
  3653. public:
  3654. /**
  3655. * \return The isolate of the property access.
  3656. */
  3657. V8_INLINE Isolate* GetIsolate() const;
  3658. /**
  3659. * \return The data set in the configuration, i.e., in
  3660. * `NamedPropertyHandlerConfiguration` or
  3661. * `IndexedPropertyHandlerConfiguration.`
  3662. */
  3663. V8_INLINE Local<Value> Data() const;
  3664. /**
  3665. * \return The receiver. In many cases, this is the object on which the
  3666. * property access was intercepted. When using
  3667. * `Reflect.get`, `Function.prototype.call`, or similar functions, it is the
  3668. * object passed in as receiver or thisArg.
  3669. *
  3670. * \code
  3671. * void GetterCallback(Local<Name> name,
  3672. * const v8::PropertyCallbackInfo<v8::Value>& info) {
  3673. * auto context = info.GetIsolate()->GetCurrentContext();
  3674. *
  3675. * v8::Local<v8::Value> a_this =
  3676. * info.This()
  3677. * ->GetRealNamedProperty(context, v8_str("a"))
  3678. * .ToLocalChecked();
  3679. * v8::Local<v8::Value> a_holder =
  3680. * info.Holder()
  3681. * ->GetRealNamedProperty(context, v8_str("a"))
  3682. * .ToLocalChecked();
  3683. *
  3684. * CHECK(v8_str("r")->Equals(context, a_this).FromJust());
  3685. * CHECK(v8_str("obj")->Equals(context, a_holder).FromJust());
  3686. *
  3687. * info.GetReturnValue().Set(name);
  3688. * }
  3689. *
  3690. * v8::Local<v8::FunctionTemplate> templ =
  3691. * v8::FunctionTemplate::New(isolate);
  3692. * templ->InstanceTemplate()->SetHandler(
  3693. * v8::NamedPropertyHandlerConfiguration(GetterCallback));
  3694. * LocalContext env;
  3695. * env->Global()
  3696. * ->Set(env.local(), v8_str("obj"), templ->GetFunction(env.local())
  3697. * .ToLocalChecked()
  3698. * ->NewInstance(env.local())
  3699. * .ToLocalChecked())
  3700. * .FromJust();
  3701. *
  3702. * CompileRun("obj.a = 'obj'; var r = {a: 'r'}; Reflect.get(obj, 'x', r)");
  3703. * \endcode
  3704. */
  3705. V8_INLINE Local<Object> This() const;
  3706. /**
  3707. * \return The object in the prototype chain of the receiver that has the
  3708. * interceptor. Suppose you have `x` and its prototype is `y`, and `y`
  3709. * has an interceptor. Then `info.This()` is `x` and `info.Holder()` is `y`.
  3710. * The Holder() could be a hidden object (the global object, rather
  3711. * than the global proxy).
  3712. *
  3713. * \note For security reasons, do not pass the object back into the runtime.
  3714. */
  3715. V8_INLINE Local<Object> Holder() const;
  3716. /**
  3717. * \return The return value of the callback.
  3718. * Can be changed by calling Set().
  3719. * \code
  3720. * info.GetReturnValue().Set(...)
  3721. * \endcode
  3722. *
  3723. */
  3724. V8_INLINE ReturnValue<T> GetReturnValue() const;
  3725. /**
  3726. * \return True if the intercepted function should throw if an error occurs.
  3727. * Usually, `true` corresponds to `'use strict'`.
  3728. *
  3729. * \note Always `false` when intercepting `Reflect.set()`
  3730. * independent of the language mode.
  3731. */
  3732. V8_INLINE bool ShouldThrowOnError() const;
  3733. // This shouldn't be public, but the arm compiler needs it.
  3734. static const int kArgsLength = 7;
  3735. protected:
  3736. friend class MacroAssembler;
  3737. friend class internal::PropertyCallbackArguments;
  3738. friend class internal::CustomArguments<PropertyCallbackInfo>;
  3739. static const int kShouldThrowOnErrorIndex = 0;
  3740. static const int kHolderIndex = 1;
  3741. static const int kIsolateIndex = 2;
  3742. static const int kReturnValueDefaultValueIndex = 3;
  3743. static const int kReturnValueIndex = 4;
  3744. static const int kDataIndex = 5;
  3745. static const int kThisIndex = 6;
  3746. V8_INLINE PropertyCallbackInfo(internal::Address* args) : args_(args) {}
  3747. internal::Address* args_;
  3748. };
  3749. typedef void (*FunctionCallback)(const FunctionCallbackInfo<Value>& info);
  3750. enum class ConstructorBehavior { kThrow, kAllow };
  3751. /**
  3752. * A JavaScript function object (ECMA-262, 15.3).
  3753. */
  3754. class V8_EXPORT Function : public Object {
  3755. public:
  3756. /**
  3757. * Create a function in the current execution context
  3758. * for a given FunctionCallback.
  3759. */
  3760. static MaybeLocal<Function> New(
  3761. Local<Context> context, FunctionCallback callback,
  3762. Local<Value> data = Local<Value>(), int length = 0,
  3763. ConstructorBehavior behavior = ConstructorBehavior::kAllow,
  3764. SideEffectType side_effect_type = SideEffectType::kHasSideEffect);
  3765. V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstance(
  3766. Local<Context> context, int argc, Local<Value> argv[]) const;
  3767. V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstance(
  3768. Local<Context> context) const {
  3769. return NewInstance(context, 0, nullptr);
  3770. }
  3771. /**
  3772. * When side effect checks are enabled, passing kHasNoSideEffect allows the
  3773. * constructor to be invoked without throwing. Calls made within the
  3774. * constructor are still checked.
  3775. */
  3776. V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstanceWithSideEffectType(
  3777. Local<Context> context, int argc, Local<Value> argv[],
  3778. SideEffectType side_effect_type = SideEffectType::kHasSideEffect) const;
  3779. V8_WARN_UNUSED_RESULT MaybeLocal<Value> Call(Local<Context> context,
  3780. Local<Value> recv, int argc,
  3781. Local<Value> argv[]);
  3782. void SetName(Local<String> name);
  3783. Local<Value> GetName() const;
  3784. /**
  3785. * Name inferred from variable or property assignment of this function.
  3786. * Used to facilitate debugging and profiling of JavaScript code written
  3787. * in an OO style, where many functions are anonymous but are assigned
  3788. * to object properties.
  3789. */
  3790. Local<Value> GetInferredName() const;
  3791. /**
  3792. * displayName if it is set, otherwise name if it is configured, otherwise
  3793. * function name, otherwise inferred name.
  3794. */
  3795. Local<Value> GetDebugName() const;
  3796. /**
  3797. * User-defined name assigned to the "displayName" property of this function.
  3798. * Used to facilitate debugging and profiling of JavaScript code.
  3799. */
  3800. Local<Value> GetDisplayName() const;
  3801. /**
  3802. * Returns zero based line number of function body and
  3803. * kLineOffsetNotFound if no information available.
  3804. */
  3805. int GetScriptLineNumber() const;
  3806. /**
  3807. * Returns zero based column number of function body and
  3808. * kLineOffsetNotFound if no information available.
  3809. */
  3810. int GetScriptColumnNumber() const;
  3811. /**
  3812. * Returns scriptId.
  3813. */
  3814. int ScriptId() const;
  3815. /**
  3816. * Returns the original function if this function is bound, else returns
  3817. * v8::Undefined.
  3818. */
  3819. Local<Value> GetBoundFunction() const;
  3820. ScriptOrigin GetScriptOrigin() const;
  3821. V8_INLINE static Function* Cast(Value* obj);
  3822. static const int kLineOffsetNotFound;
  3823. private:
  3824. Function();
  3825. static void CheckCast(Value* obj);
  3826. };
  3827. #ifndef V8_PROMISE_INTERNAL_FIELD_COUNT
  3828. // The number of required internal fields can be defined by embedder.
  3829. #define V8_PROMISE_INTERNAL_FIELD_COUNT 0
  3830. #endif
  3831. /**
  3832. * An instance of the built-in Promise constructor (ES6 draft).
  3833. */
  3834. class V8_EXPORT Promise : public Object {
  3835. public:
  3836. /**
  3837. * State of the promise. Each value corresponds to one of the possible values
  3838. * of the [[PromiseState]] field.
  3839. */
  3840. enum PromiseState { kPending, kFulfilled, kRejected };
  3841. class V8_EXPORT Resolver : public Object {
  3842. public:
  3843. /**
  3844. * Create a new resolver, along with an associated promise in pending state.
  3845. */
  3846. static V8_WARN_UNUSED_RESULT MaybeLocal<Resolver> New(
  3847. Local<Context> context);
  3848. /**
  3849. * Extract the associated promise.
  3850. */
  3851. Local<Promise> GetPromise();
  3852. /**
  3853. * Resolve/reject the associated promise with a given value.
  3854. * Ignored if the promise is no longer pending.
  3855. */
  3856. V8_WARN_UNUSED_RESULT Maybe<bool> Resolve(Local<Context> context,
  3857. Local<Value> value);
  3858. V8_WARN_UNUSED_RESULT Maybe<bool> Reject(Local<Context> context,
  3859. Local<Value> value);
  3860. V8_INLINE static Resolver* Cast(Value* obj);
  3861. private:
  3862. Resolver();
  3863. static void CheckCast(Value* obj);
  3864. };
  3865. /**
  3866. * Register a resolution/rejection handler with a promise.
  3867. * The handler is given the respective resolution/rejection value as
  3868. * an argument. If the promise is already resolved/rejected, the handler is
  3869. * invoked at the end of turn.
  3870. */
  3871. V8_WARN_UNUSED_RESULT MaybeLocal<Promise> Catch(Local<Context> context,
  3872. Local<Function> handler);
  3873. V8_WARN_UNUSED_RESULT MaybeLocal<Promise> Then(Local<Context> context,
  3874. Local<Function> handler);
  3875. V8_WARN_UNUSED_RESULT MaybeLocal<Promise> Then(Local<Context> context,
  3876. Local<Function> on_fulfilled,
  3877. Local<Function> on_rejected);
  3878. /**
  3879. * Returns true if the promise has at least one derived promise, and
  3880. * therefore resolve/reject handlers (including default handler).
  3881. */
  3882. bool HasHandler();
  3883. /**
  3884. * Returns the content of the [[PromiseResult]] field. The Promise must not
  3885. * be pending.
  3886. */
  3887. Local<Value> Result();
  3888. /**
  3889. * Returns the value of the [[PromiseState]] field.
  3890. */
  3891. PromiseState State();
  3892. /**
  3893. * Marks this promise as handled to avoid reporting unhandled rejections.
  3894. */
  3895. void MarkAsHandled();
  3896. V8_INLINE static Promise* Cast(Value* obj);
  3897. static const int kEmbedderFieldCount = V8_PROMISE_INTERNAL_FIELD_COUNT;
  3898. private:
  3899. Promise();
  3900. static void CheckCast(Value* obj);
  3901. };
  3902. /**
  3903. * An instance of a Property Descriptor, see Ecma-262 6.2.4.
  3904. *
  3905. * Properties in a descriptor are present or absent. If you do not set
  3906. * `enumerable`, `configurable`, and `writable`, they are absent. If `value`,
  3907. * `get`, or `set` are absent, but you must specify them in the constructor, use
  3908. * empty handles.
  3909. *
  3910. * Accessors `get` and `set` must be callable or undefined if they are present.
  3911. *
  3912. * \note Only query properties if they are present, i.e., call `x()` only if
  3913. * `has_x()` returns true.
  3914. *
  3915. * \code
  3916. * // var desc = {writable: false}
  3917. * v8::PropertyDescriptor d(Local<Value>()), false);
  3918. * d.value(); // error, value not set
  3919. * if (d.has_writable()) {
  3920. * d.writable(); // false
  3921. * }
  3922. *
  3923. * // var desc = {value: undefined}
  3924. * v8::PropertyDescriptor d(v8::Undefined(isolate));
  3925. *
  3926. * // var desc = {get: undefined}
  3927. * v8::PropertyDescriptor d(v8::Undefined(isolate), Local<Value>()));
  3928. * \endcode
  3929. */
  3930. class V8_EXPORT PropertyDescriptor {
  3931. public:
  3932. // GenericDescriptor
  3933. PropertyDescriptor();
  3934. // DataDescriptor
  3935. explicit PropertyDescriptor(Local<Value> value);
  3936. // DataDescriptor with writable property
  3937. PropertyDescriptor(Local<Value> value, bool writable);
  3938. // AccessorDescriptor
  3939. PropertyDescriptor(Local<Value> get, Local<Value> set);
  3940. ~PropertyDescriptor();
  3941. Local<Value> value() const;
  3942. bool has_value() const;
  3943. Local<Value> get() const;
  3944. bool has_get() const;
  3945. Local<Value> set() const;
  3946. bool has_set() const;
  3947. void set_enumerable(bool enumerable);
  3948. bool enumerable() const;
  3949. bool has_enumerable() const;
  3950. void set_configurable(bool configurable);
  3951. bool configurable() const;
  3952. bool has_configurable() const;
  3953. bool writable() const;
  3954. bool has_writable() const;
  3955. struct PrivateData;
  3956. PrivateData* get_private() const { return private_; }
  3957. PropertyDescriptor(const PropertyDescriptor&) = delete;
  3958. void operator=(const PropertyDescriptor&) = delete;
  3959. private:
  3960. PrivateData* private_;
  3961. };
  3962. /**
  3963. * An instance of the built-in Proxy constructor (ECMA-262, 6th Edition,
  3964. * 26.2.1).
  3965. */
  3966. class V8_EXPORT Proxy : public Object {
  3967. public:
  3968. Local<Value> GetTarget();
  3969. Local<Value> GetHandler();
  3970. bool IsRevoked();
  3971. void Revoke();
  3972. /**
  3973. * Creates a new Proxy for the target object.
  3974. */
  3975. static MaybeLocal<Proxy> New(Local<Context> context,
  3976. Local<Object> local_target,
  3977. Local<Object> local_handler);
  3978. V8_INLINE static Proxy* Cast(Value* obj);
  3979. private:
  3980. Proxy();
  3981. static void CheckCast(Value* obj);
  3982. };
  3983. /**
  3984. * Points to an unowned continous buffer holding a known number of elements.
  3985. *
  3986. * This is similar to std::span (under consideration for C++20), but does not
  3987. * require advanced C++ support. In the (far) future, this may be replaced with
  3988. * or aliased to std::span.
  3989. *
  3990. * To facilitate future migration, this class exposes a subset of the interface
  3991. * implemented by std::span.
  3992. */
  3993. template <typename T>
  3994. class V8_EXPORT MemorySpan {
  3995. public:
  3996. /** The default constructor creates an empty span. */
  3997. constexpr MemorySpan() = default;
  3998. constexpr MemorySpan(T* data, size_t size) : data_(data), size_(size) {}
  3999. /** Returns a pointer to the beginning of the buffer. */
  4000. constexpr T* data() const { return data_; }
  4001. /** Returns the number of elements that the buffer holds. */
  4002. constexpr size_t size() const { return size_; }
  4003. private:
  4004. T* data_ = nullptr;
  4005. size_t size_ = 0;
  4006. };
  4007. /**
  4008. * An owned byte buffer with associated size.
  4009. */
  4010. struct OwnedBuffer {
  4011. std::unique_ptr<const uint8_t[]> buffer;
  4012. size_t size = 0;
  4013. OwnedBuffer(std::unique_ptr<const uint8_t[]> buffer, size_t size)
  4014. : buffer(std::move(buffer)), size(size) {}
  4015. OwnedBuffer() = default;
  4016. };
  4017. // Wrapper around a compiled WebAssembly module, which is potentially shared by
  4018. // different WasmModuleObjects.
  4019. class V8_EXPORT CompiledWasmModule {
  4020. public:
  4021. /**
  4022. * Serialize the compiled module. The serialized data does not include the
  4023. * wire bytes.
  4024. */
  4025. OwnedBuffer Serialize();
  4026. /**
  4027. * Get the (wasm-encoded) wire bytes that were used to compile this module.
  4028. */
  4029. MemorySpan<const uint8_t> GetWireBytesRef();
  4030. private:
  4031. explicit CompiledWasmModule(std::shared_ptr<internal::wasm::NativeModule>);
  4032. friend class Utils;
  4033. const std::shared_ptr<internal::wasm::NativeModule> native_module_;
  4034. };
  4035. // An instance of WebAssembly.Module.
  4036. class V8_EXPORT WasmModuleObject : public Object {
  4037. public:
  4038. WasmModuleObject() = delete;
  4039. /**
  4040. * Efficiently re-create a WasmModuleObject, without recompiling, from
  4041. * a CompiledWasmModule.
  4042. */
  4043. static MaybeLocal<WasmModuleObject> FromCompiledModule(
  4044. Isolate* isolate, const CompiledWasmModule&);
  4045. /**
  4046. * Get the compiled module for this module object. The compiled module can be
  4047. * shared by several module objects.
  4048. */
  4049. CompiledWasmModule GetCompiledModule();
  4050. /**
  4051. * If possible, deserialize the module, otherwise compile it from the provided
  4052. * uncompiled bytes.
  4053. */
  4054. static MaybeLocal<WasmModuleObject> DeserializeOrCompile(
  4055. Isolate* isolate, MemorySpan<const uint8_t> serialized_module,
  4056. MemorySpan<const uint8_t> wire_bytes);
  4057. V8_INLINE static WasmModuleObject* Cast(Value* obj);
  4058. private:
  4059. static MaybeLocal<WasmModuleObject> Deserialize(
  4060. Isolate* isolate, MemorySpan<const uint8_t> serialized_module,
  4061. MemorySpan<const uint8_t> wire_bytes);
  4062. static MaybeLocal<WasmModuleObject> Compile(Isolate* isolate,
  4063. const uint8_t* start,
  4064. size_t length);
  4065. static void CheckCast(Value* obj);
  4066. };
  4067. /**
  4068. * The V8 interface for WebAssembly streaming compilation. When streaming
  4069. * compilation is initiated, V8 passes a {WasmStreaming} object to the embedder
  4070. * such that the embedder can pass the input bytes for streaming compilation to
  4071. * V8.
  4072. */
  4073. class V8_EXPORT WasmStreaming final {
  4074. public:
  4075. class WasmStreamingImpl;
  4076. /**
  4077. * Client to receive streaming event notifications.
  4078. */
  4079. class Client {
  4080. public:
  4081. virtual ~Client() = default;
  4082. /**
  4083. * Passes the fully compiled module to the client. This can be used to
  4084. * implement code caching.
  4085. */
  4086. virtual void OnModuleCompiled(CompiledWasmModule compiled_module) = 0;
  4087. };
  4088. explicit WasmStreaming(std::unique_ptr<WasmStreamingImpl> impl);
  4089. ~WasmStreaming();
  4090. /**
  4091. * Pass a new chunk of bytes to WebAssembly streaming compilation.
  4092. * The buffer passed into {OnBytesReceived} is owned by the caller.
  4093. */
  4094. void OnBytesReceived(const uint8_t* bytes, size_t size);
  4095. /**
  4096. * {Finish} should be called after all received bytes where passed to
  4097. * {OnBytesReceived} to tell V8 that there will be no more bytes. {Finish}
  4098. * does not have to be called after {Abort} has been called already.
  4099. */
  4100. void Finish();
  4101. /**
  4102. * Abort streaming compilation. If {exception} has a value, then the promise
  4103. * associated with streaming compilation is rejected with that value. If
  4104. * {exception} does not have value, the promise does not get rejected.
  4105. */
  4106. void Abort(MaybeLocal<Value> exception);
  4107. /**
  4108. * Passes previously compiled module bytes. This must be called before
  4109. * {OnBytesReceived}, {Finish}, or {Abort}. Returns true if the module bytes
  4110. * can be used, false otherwise. The buffer passed via {bytes} and {size}
  4111. * is owned by the caller. If {SetCompiledModuleBytes} returns true, the
  4112. * buffer must remain valid until either {Finish} or {Abort} completes.
  4113. */
  4114. bool SetCompiledModuleBytes(const uint8_t* bytes, size_t size);
  4115. /**
  4116. * Sets the client object that will receive streaming event notifications.
  4117. * This must be called before {OnBytesReceived}, {Finish}, or {Abort}.
  4118. */
  4119. void SetClient(std::shared_ptr<Client> client);
  4120. /**
  4121. * Unpacks a {WasmStreaming} object wrapped in a {Managed} for the embedder.
  4122. * Since the embedder is on the other side of the API, it cannot unpack the
  4123. * {Managed} itself.
  4124. */
  4125. static std::shared_ptr<WasmStreaming> Unpack(Isolate* isolate,
  4126. Local<Value> value);
  4127. private:
  4128. std::unique_ptr<WasmStreamingImpl> impl_;
  4129. };
  4130. // TODO(mtrofin): when streaming compilation is done, we can rename this
  4131. // to simply WasmModuleObjectBuilder
  4132. class V8_EXPORT WasmModuleObjectBuilderStreaming final {
  4133. public:
  4134. explicit WasmModuleObjectBuilderStreaming(Isolate* isolate);
  4135. /**
  4136. * The buffer passed into OnBytesReceived is owned by the caller.
  4137. */
  4138. void OnBytesReceived(const uint8_t*, size_t size);
  4139. void Finish();
  4140. /**
  4141. * Abort streaming compilation. If {exception} has a value, then the promise
  4142. * associated with streaming compilation is rejected with that value. If
  4143. * {exception} does not have value, the promise does not get rejected.
  4144. */
  4145. void Abort(MaybeLocal<Value> exception);
  4146. Local<Promise> GetPromise();
  4147. ~WasmModuleObjectBuilderStreaming() = default;
  4148. private:
  4149. WasmModuleObjectBuilderStreaming(const WasmModuleObjectBuilderStreaming&) =
  4150. delete;
  4151. WasmModuleObjectBuilderStreaming(WasmModuleObjectBuilderStreaming&&) =
  4152. default;
  4153. WasmModuleObjectBuilderStreaming& operator=(
  4154. const WasmModuleObjectBuilderStreaming&) = delete;
  4155. WasmModuleObjectBuilderStreaming& operator=(
  4156. WasmModuleObjectBuilderStreaming&&) = default;
  4157. Isolate* isolate_ = nullptr;
  4158. #if V8_CC_MSVC
  4159. /**
  4160. * We don't need the static Copy API, so the default
  4161. * NonCopyablePersistentTraits would be sufficient, however,
  4162. * MSVC eagerly instantiates the Copy.
  4163. * We ensure we don't use Copy, however, by compiling with the
  4164. * defaults everywhere else.
  4165. */
  4166. Persistent<Promise, CopyablePersistentTraits<Promise>> promise_;
  4167. #else
  4168. Persistent<Promise> promise_;
  4169. #endif
  4170. std::shared_ptr<internal::wasm::StreamingDecoder> streaming_decoder_;
  4171. };
  4172. #ifndef V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT
  4173. // The number of required internal fields can be defined by embedder.
  4174. #define V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT 2
  4175. #endif
  4176. enum class ArrayBufferCreationMode { kInternalized, kExternalized };
  4177. /**
  4178. * A wrapper around the backing store (i.e. the raw memory) of an array buffer.
  4179. * See a document linked in http://crbug.com/v8/9908 for more information.
  4180. *
  4181. * The allocation and destruction of backing stores is generally managed by
  4182. * V8. Clients should always use standard C++ memory ownership types (i.e.
  4183. * std::unique_ptr and std::shared_ptr) to manage lifetimes of backing stores
  4184. * properly, since V8 internal objects may alias backing stores.
  4185. *
  4186. * This object does not keep the underlying |ArrayBuffer::Allocator| alive by
  4187. * default. Use Isolate::CreateParams::array_buffer_allocator_shared when
  4188. * creating the Isolate to make it hold a reference to the allocator itself.
  4189. */
  4190. class V8_EXPORT BackingStore : public v8::internal::BackingStoreBase {
  4191. public:
  4192. ~BackingStore();
  4193. /**
  4194. * Return a pointer to the beginning of the memory block for this backing
  4195. * store. The pointer is only valid as long as this backing store object
  4196. * lives.
  4197. */
  4198. void* Data() const;
  4199. /**
  4200. * The length (in bytes) of this backing store.
  4201. */
  4202. size_t ByteLength() const;
  4203. /**
  4204. * Indicates whether the backing store was created for an ArrayBuffer or
  4205. * a SharedArrayBuffer.
  4206. */
  4207. bool IsShared() const;
  4208. private:
  4209. /**
  4210. * See [Shared]ArrayBuffer::GetBackingStore and
  4211. * [Shared]ArrayBuffer::NewBackingStore.
  4212. */
  4213. BackingStore();
  4214. };
  4215. /**
  4216. * This callback is used only if the memory block for this backing store cannot
  4217. * be allocated with an ArrayBuffer::Allocator. In such cases the destructor
  4218. * of this backing store object invokes the callback to free the memory block.
  4219. */
  4220. using BackingStoreDeleterCallback = void (*)(void* data, size_t length,
  4221. void* deleter_data);
  4222. /**
  4223. * An instance of the built-in ArrayBuffer constructor (ES6 draft 15.13.5).
  4224. */
  4225. class V8_EXPORT ArrayBuffer : public Object {
  4226. public:
  4227. /**
  4228. * A thread-safe allocator that V8 uses to allocate |ArrayBuffer|'s memory.
  4229. * The allocator is a global V8 setting. It has to be set via
  4230. * Isolate::CreateParams.
  4231. *
  4232. * Memory allocated through this allocator by V8 is accounted for as external
  4233. * memory by V8. Note that V8 keeps track of the memory for all internalized
  4234. * |ArrayBuffer|s. Responsibility for tracking external memory (using
  4235. * Isolate::AdjustAmountOfExternalAllocatedMemory) is handed over to the
  4236. * embedder upon externalization and taken over upon internalization (creating
  4237. * an internalized buffer from an existing buffer).
  4238. *
  4239. * Note that it is unsafe to call back into V8 from any of the allocator
  4240. * functions.
  4241. */
  4242. class V8_EXPORT Allocator { // NOLINT
  4243. public:
  4244. virtual ~Allocator() = default;
  4245. /**
  4246. * Allocate |length| bytes. Return NULL if allocation is not successful.
  4247. * Memory should be initialized to zeroes.
  4248. */
  4249. virtual void* Allocate(size_t length) = 0;
  4250. /**
  4251. * Allocate |length| bytes. Return NULL if allocation is not successful.
  4252. * Memory does not have to be initialized.
  4253. */
  4254. virtual void* AllocateUninitialized(size_t length) = 0;
  4255. /**
  4256. * Free the memory block of size |length|, pointed to by |data|.
  4257. * That memory is guaranteed to be previously allocated by |Allocate|.
  4258. */
  4259. virtual void Free(void* data, size_t length) = 0;
  4260. /**
  4261. * ArrayBuffer allocation mode. kNormal is a malloc/free style allocation,
  4262. * while kReservation is for larger allocations with the ability to set
  4263. * access permissions.
  4264. */
  4265. enum class AllocationMode { kNormal, kReservation };
  4266. /**
  4267. * malloc/free based convenience allocator.
  4268. *
  4269. * Caller takes ownership, i.e. the returned object needs to be freed using
  4270. * |delete allocator| once it is no longer in use.
  4271. */
  4272. static Allocator* NewDefaultAllocator();
  4273. };
  4274. /**
  4275. * The contents of an |ArrayBuffer|. Externalization of |ArrayBuffer|
  4276. * returns an instance of this class, populated, with a pointer to data
  4277. * and byte length.
  4278. *
  4279. * The Data pointer of ArrayBuffer::Contents must be freed using the provided
  4280. * deleter, which will call ArrayBuffer::Allocator::Free if the buffer
  4281. * was allocated with ArraryBuffer::Allocator::Allocate.
  4282. */
  4283. class V8_EXPORT Contents { // NOLINT
  4284. public:
  4285. using DeleterCallback = void (*)(void* buffer, size_t length, void* info);
  4286. Contents()
  4287. : data_(nullptr),
  4288. byte_length_(0),
  4289. allocation_base_(nullptr),
  4290. allocation_length_(0),
  4291. allocation_mode_(Allocator::AllocationMode::kNormal),
  4292. deleter_(nullptr),
  4293. deleter_data_(nullptr) {}
  4294. void* AllocationBase() const { return allocation_base_; }
  4295. size_t AllocationLength() const { return allocation_length_; }
  4296. Allocator::AllocationMode AllocationMode() const {
  4297. return allocation_mode_;
  4298. }
  4299. void* Data() const { return data_; }
  4300. size_t ByteLength() const { return byte_length_; }
  4301. DeleterCallback Deleter() const { return deleter_; }
  4302. void* DeleterData() const { return deleter_data_; }
  4303. private:
  4304. Contents(void* data, size_t byte_length, void* allocation_base,
  4305. size_t allocation_length,
  4306. Allocator::AllocationMode allocation_mode, DeleterCallback deleter,
  4307. void* deleter_data);
  4308. void* data_;
  4309. size_t byte_length_;
  4310. void* allocation_base_;
  4311. size_t allocation_length_;
  4312. Allocator::AllocationMode allocation_mode_;
  4313. DeleterCallback deleter_;
  4314. void* deleter_data_;
  4315. friend class ArrayBuffer;
  4316. };
  4317. /**
  4318. * Data length in bytes.
  4319. */
  4320. size_t ByteLength() const;
  4321. /**
  4322. * Create a new ArrayBuffer. Allocate |byte_length| bytes.
  4323. * Allocated memory will be owned by a created ArrayBuffer and
  4324. * will be deallocated when it is garbage-collected,
  4325. * unless the object is externalized.
  4326. */
  4327. static Local<ArrayBuffer> New(Isolate* isolate, size_t byte_length);
  4328. /**
  4329. * Create a new ArrayBuffer over an existing memory block.
  4330. * The created array buffer is by default immediately in externalized state.
  4331. * In externalized state, the memory block will not be reclaimed when a
  4332. * created ArrayBuffer is garbage-collected.
  4333. * In internalized state, the memory block will be released using
  4334. * |Allocator::Free| once all ArrayBuffers referencing it are collected by
  4335. * the garbage collector.
  4336. */
  4337. V8_DEPRECATE_SOON(
  4338. "Use the version that takes a BackingStore. "
  4339. "See http://crbug.com/v8/9908.")
  4340. static Local<ArrayBuffer> New(
  4341. Isolate* isolate, void* data, size_t byte_length,
  4342. ArrayBufferCreationMode mode = ArrayBufferCreationMode::kExternalized);
  4343. /**
  4344. * Create a new ArrayBuffer with an existing backing store.
  4345. * The created array keeps a reference to the backing store until the array
  4346. * is garbage collected. Note that the IsExternal bit does not affect this
  4347. * reference from the array to the backing store.
  4348. *
  4349. * In future IsExternal bit will be removed. Until then the bit is set as
  4350. * follows. If the backing store does not own the underlying buffer, then
  4351. * the array is created in externalized state. Otherwise, the array is created
  4352. * in internalized state. In the latter case the array can be transitioned
  4353. * to the externalized state using Externalize(backing_store).
  4354. */
  4355. static Local<ArrayBuffer> New(Isolate* isolate,
  4356. std::shared_ptr<BackingStore> backing_store);
  4357. /**
  4358. * Returns a new standalone BackingStore that is allocated using the array
  4359. * buffer allocator of the isolate. The result can be later passed to
  4360. * ArrayBuffer::New.
  4361. *
  4362. * If the allocator returns nullptr, then the function may cause GCs in the
  4363. * given isolate and re-try the allocation. If GCs do not help, then the
  4364. * function will crash with an out-of-memory error.
  4365. */
  4366. static std::unique_ptr<BackingStore> NewBackingStore(Isolate* isolate,
  4367. size_t byte_length);
  4368. /**
  4369. * Returns a new standalone BackingStore that takes over the ownership of
  4370. * the given buffer. The destructor of the BackingStore invokes the given
  4371. * deleter callback.
  4372. *
  4373. * The result can be later passed to ArrayBuffer::New. The raw pointer
  4374. * to the buffer must not be passed again to any V8 API function.
  4375. */
  4376. static std::unique_ptr<BackingStore> NewBackingStore(
  4377. void* data, size_t byte_length, BackingStoreDeleterCallback deleter,
  4378. void* deleter_data);
  4379. /**
  4380. * Returns true if ArrayBuffer is externalized, that is, does not
  4381. * own its memory block.
  4382. */
  4383. V8_DEPRECATE_SOON(
  4384. "With v8::BackingStore externalized ArrayBuffers are "
  4385. "the same as ordinary ArrayBuffers. See http://crbug.com/v8/9908.")
  4386. bool IsExternal() const;
  4387. /**
  4388. * Returns true if this ArrayBuffer may be detached.
  4389. */
  4390. bool IsDetachable() const;
  4391. /**
  4392. * Detaches this ArrayBuffer and all its views (typed arrays).
  4393. * Detaching sets the byte length of the buffer and all typed arrays to zero,
  4394. * preventing JavaScript from ever accessing underlying backing store.
  4395. * ArrayBuffer should have been externalized and must be detachable.
  4396. */
  4397. void Detach();
  4398. /**
  4399. * Make this ArrayBuffer external. The pointer to underlying memory block
  4400. * and byte length are returned as |Contents| structure. After ArrayBuffer
  4401. * had been externalized, it does no longer own the memory block. The caller
  4402. * should take steps to free memory when it is no longer needed.
  4403. *
  4404. * The Data pointer of ArrayBuffer::Contents must be freed using the provided
  4405. * deleter, which will call ArrayBuffer::Allocator::Free if the buffer
  4406. * was allocated with ArrayBuffer::Allocator::Allocate.
  4407. */
  4408. V8_DEPRECATE_SOON(
  4409. "Use GetBackingStore or Detach. See http://crbug.com/v8/9908.")
  4410. Contents Externalize();
  4411. /**
  4412. * Marks this ArrayBuffer external given a witness that the embedder
  4413. * has fetched the backing store using the new GetBackingStore() function.
  4414. *
  4415. * With the new lifetime management of backing stores there is no need for
  4416. * externalizing, so this function exists only to make the transition easier.
  4417. */
  4418. V8_DEPRECATE_SOON("This will be removed together with IsExternal.")
  4419. void Externalize(const std::shared_ptr<BackingStore>& backing_store);
  4420. /**
  4421. * Get a pointer to the ArrayBuffer's underlying memory block without
  4422. * externalizing it. If the ArrayBuffer is not externalized, this pointer
  4423. * will become invalid as soon as the ArrayBuffer gets garbage collected.
  4424. *
  4425. * The embedder should make sure to hold a strong reference to the
  4426. * ArrayBuffer while accessing this pointer.
  4427. */
  4428. V8_DEPRECATE_SOON("Use GetBackingStore. See http://crbug.com/v8/9908.")
  4429. Contents GetContents();
  4430. /**
  4431. * Get a shared pointer to the backing store of this array buffer. This
  4432. * pointer coordinates the lifetime management of the internal storage
  4433. * with any live ArrayBuffers on the heap, even across isolates. The embedder
  4434. * should not attempt to manage lifetime of the storage through other means.
  4435. *
  4436. * This function replaces both Externalize() and GetContents().
  4437. */
  4438. std::shared_ptr<BackingStore> GetBackingStore();
  4439. V8_INLINE static ArrayBuffer* Cast(Value* obj);
  4440. static const int kInternalFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
  4441. static const int kEmbedderFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
  4442. private:
  4443. ArrayBuffer();
  4444. static void CheckCast(Value* obj);
  4445. Contents GetContents(bool externalize);
  4446. };
  4447. #ifndef V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT
  4448. // The number of required internal fields can be defined by embedder.
  4449. #define V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT 2
  4450. #endif
  4451. /**
  4452. * A base class for an instance of one of "views" over ArrayBuffer,
  4453. * including TypedArrays and DataView (ES6 draft 15.13).
  4454. */
  4455. class V8_EXPORT ArrayBufferView : public Object {
  4456. public:
  4457. /**
  4458. * Returns underlying ArrayBuffer.
  4459. */
  4460. Local<ArrayBuffer> Buffer();
  4461. /**
  4462. * Byte offset in |Buffer|.
  4463. */
  4464. size_t ByteOffset();
  4465. /**
  4466. * Size of a view in bytes.
  4467. */
  4468. size_t ByteLength();
  4469. /**
  4470. * Copy the contents of the ArrayBufferView's buffer to an embedder defined
  4471. * memory without additional overhead that calling ArrayBufferView::Buffer
  4472. * might incur.
  4473. *
  4474. * Will write at most min(|byte_length|, ByteLength) bytes starting at
  4475. * ByteOffset of the underlying buffer to the memory starting at |dest|.
  4476. * Returns the number of bytes actually written.
  4477. */
  4478. size_t CopyContents(void* dest, size_t byte_length);
  4479. /**
  4480. * Returns true if ArrayBufferView's backing ArrayBuffer has already been
  4481. * allocated.
  4482. */
  4483. bool HasBuffer() const;
  4484. V8_INLINE static ArrayBufferView* Cast(Value* obj);
  4485. static const int kInternalFieldCount =
  4486. V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT;
  4487. static const int kEmbedderFieldCount =
  4488. V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT;
  4489. private:
  4490. ArrayBufferView();
  4491. static void CheckCast(Value* obj);
  4492. };
  4493. /**
  4494. * A base class for an instance of TypedArray series of constructors
  4495. * (ES6 draft 15.13.6).
  4496. */
  4497. class V8_EXPORT TypedArray : public ArrayBufferView {
  4498. public:
  4499. /*
  4500. * The largest typed array size that can be constructed using New.
  4501. */
  4502. static constexpr size_t kMaxLength = internal::kApiSystemPointerSize == 4
  4503. ? internal::kSmiMaxValue
  4504. : 0x7FFFFFFF; // kMaxInt32
  4505. /**
  4506. * Number of elements in this typed array
  4507. * (e.g. for Int16Array, |ByteLength|/2).
  4508. */
  4509. size_t Length();
  4510. V8_INLINE static TypedArray* Cast(Value* obj);
  4511. private:
  4512. TypedArray();
  4513. static void CheckCast(Value* obj);
  4514. };
  4515. /**
  4516. * An instance of Uint8Array constructor (ES6 draft 15.13.6).
  4517. */
  4518. class V8_EXPORT Uint8Array : public TypedArray {
  4519. public:
  4520. static Local<Uint8Array> New(Local<ArrayBuffer> array_buffer,
  4521. size_t byte_offset, size_t length);
  4522. static Local<Uint8Array> New(Local<SharedArrayBuffer> shared_array_buffer,
  4523. size_t byte_offset, size_t length);
  4524. V8_INLINE static Uint8Array* Cast(Value* obj);
  4525. private:
  4526. Uint8Array();
  4527. static void CheckCast(Value* obj);
  4528. };
  4529. /**
  4530. * An instance of Uint8ClampedArray constructor (ES6 draft 15.13.6).
  4531. */
  4532. class V8_EXPORT Uint8ClampedArray : public TypedArray {
  4533. public:
  4534. static Local<Uint8ClampedArray> New(Local<ArrayBuffer> array_buffer,
  4535. size_t byte_offset, size_t length);
  4536. static Local<Uint8ClampedArray> New(
  4537. Local<SharedArrayBuffer> shared_array_buffer, size_t byte_offset,
  4538. size_t length);
  4539. V8_INLINE static Uint8ClampedArray* Cast(Value* obj);
  4540. private:
  4541. Uint8ClampedArray();
  4542. static void CheckCast(Value* obj);
  4543. };
  4544. /**
  4545. * An instance of Int8Array constructor (ES6 draft 15.13.6).
  4546. */
  4547. class V8_EXPORT Int8Array : public TypedArray {
  4548. public:
  4549. static Local<Int8Array> New(Local<ArrayBuffer> array_buffer,
  4550. size_t byte_offset, size_t length);
  4551. static Local<Int8Array> New(Local<SharedArrayBuffer> shared_array_buffer,
  4552. size_t byte_offset, size_t length);
  4553. V8_INLINE static Int8Array* Cast(Value* obj);
  4554. private:
  4555. Int8Array();
  4556. static void CheckCast(Value* obj);
  4557. };
  4558. /**
  4559. * An instance of Uint16Array constructor (ES6 draft 15.13.6).
  4560. */
  4561. class V8_EXPORT Uint16Array : public TypedArray {
  4562. public:
  4563. static Local<Uint16Array> New(Local<ArrayBuffer> array_buffer,
  4564. size_t byte_offset, size_t length);
  4565. static Local<Uint16Array> New(Local<SharedArrayBuffer> shared_array_buffer,
  4566. size_t byte_offset, size_t length);
  4567. V8_INLINE static Uint16Array* Cast(Value* obj);
  4568. private:
  4569. Uint16Array();
  4570. static void CheckCast(Value* obj);
  4571. };
  4572. /**
  4573. * An instance of Int16Array constructor (ES6 draft 15.13.6).
  4574. */
  4575. class V8_EXPORT Int16Array : public TypedArray {
  4576. public:
  4577. static Local<Int16Array> New(Local<ArrayBuffer> array_buffer,
  4578. size_t byte_offset, size_t length);
  4579. static Local<Int16Array> New(Local<SharedArrayBuffer> shared_array_buffer,
  4580. size_t byte_offset, size_t length);
  4581. V8_INLINE static Int16Array* Cast(Value* obj);
  4582. private:
  4583. Int16Array();
  4584. static void CheckCast(Value* obj);
  4585. };
  4586. /**
  4587. * An instance of Uint32Array constructor (ES6 draft 15.13.6).
  4588. */
  4589. class V8_EXPORT Uint32Array : public TypedArray {
  4590. public:
  4591. static Local<Uint32Array> New(Local<ArrayBuffer> array_buffer,
  4592. size_t byte_offset, size_t length);
  4593. static Local<Uint32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
  4594. size_t byte_offset, size_t length);
  4595. V8_INLINE static Uint32Array* Cast(Value* obj);
  4596. private:
  4597. Uint32Array();
  4598. static void CheckCast(Value* obj);
  4599. };
  4600. /**
  4601. * An instance of Int32Array constructor (ES6 draft 15.13.6).
  4602. */
  4603. class V8_EXPORT Int32Array : public TypedArray {
  4604. public:
  4605. static Local<Int32Array> New(Local<ArrayBuffer> array_buffer,
  4606. size_t byte_offset, size_t length);
  4607. static Local<Int32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
  4608. size_t byte_offset, size_t length);
  4609. V8_INLINE static Int32Array* Cast(Value* obj);
  4610. private:
  4611. Int32Array();
  4612. static void CheckCast(Value* obj);
  4613. };
  4614. /**
  4615. * An instance of Float32Array constructor (ES6 draft 15.13.6).
  4616. */
  4617. class V8_EXPORT Float32Array : public TypedArray {
  4618. public:
  4619. static Local<Float32Array> New(Local<ArrayBuffer> array_buffer,
  4620. size_t byte_offset, size_t length);
  4621. static Local<Float32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
  4622. size_t byte_offset, size_t length);
  4623. V8_INLINE static Float32Array* Cast(Value* obj);
  4624. private:
  4625. Float32Array();
  4626. static void CheckCast(Value* obj);
  4627. };
  4628. /**
  4629. * An instance of Float64Array constructor (ES6 draft 15.13.6).
  4630. */
  4631. class V8_EXPORT Float64Array : public TypedArray {
  4632. public:
  4633. static Local<Float64Array> New(Local<ArrayBuffer> array_buffer,
  4634. size_t byte_offset, size_t length);
  4635. static Local<Float64Array> New(Local<SharedArrayBuffer> shared_array_buffer,
  4636. size_t byte_offset, size_t length);
  4637. V8_INLINE static Float64Array* Cast(Value* obj);
  4638. private:
  4639. Float64Array();
  4640. static void CheckCast(Value* obj);
  4641. };
  4642. /**
  4643. * An instance of BigInt64Array constructor.
  4644. */
  4645. class V8_EXPORT BigInt64Array : public TypedArray {
  4646. public:
  4647. static Local<BigInt64Array> New(Local<ArrayBuffer> array_buffer,
  4648. size_t byte_offset, size_t length);
  4649. static Local<BigInt64Array> New(Local<SharedArrayBuffer> shared_array_buffer,
  4650. size_t byte_offset, size_t length);
  4651. V8_INLINE static BigInt64Array* Cast(Value* obj);
  4652. private:
  4653. BigInt64Array();
  4654. static void CheckCast(Value* obj);
  4655. };
  4656. /**
  4657. * An instance of BigUint64Array constructor.
  4658. */
  4659. class V8_EXPORT BigUint64Array : public TypedArray {
  4660. public:
  4661. static Local<BigUint64Array> New(Local<ArrayBuffer> array_buffer,
  4662. size_t byte_offset, size_t length);
  4663. static Local<BigUint64Array> New(Local<SharedArrayBuffer> shared_array_buffer,
  4664. size_t byte_offset, size_t length);
  4665. V8_INLINE static BigUint64Array* Cast(Value* obj);
  4666. private:
  4667. BigUint64Array();
  4668. static void CheckCast(Value* obj);
  4669. };
  4670. /**
  4671. * An instance of DataView constructor (ES6 draft 15.13.7).
  4672. */
  4673. class V8_EXPORT DataView : public ArrayBufferView {
  4674. public:
  4675. static Local<DataView> New(Local<ArrayBuffer> array_buffer,
  4676. size_t byte_offset, size_t length);
  4677. static Local<DataView> New(Local<SharedArrayBuffer> shared_array_buffer,
  4678. size_t byte_offset, size_t length);
  4679. V8_INLINE static DataView* Cast(Value* obj);
  4680. private:
  4681. DataView();
  4682. static void CheckCast(Value* obj);
  4683. };
  4684. /**
  4685. * An instance of the built-in SharedArrayBuffer constructor.
  4686. * This API is experimental and may change significantly.
  4687. */
  4688. class V8_EXPORT SharedArrayBuffer : public Object {
  4689. public:
  4690. /**
  4691. * The contents of an |SharedArrayBuffer|. Externalization of
  4692. * |SharedArrayBuffer| returns an instance of this class, populated, with a
  4693. * pointer to data and byte length.
  4694. *
  4695. * The Data pointer of ArrayBuffer::Contents must be freed using the provided
  4696. * deleter, which will call ArrayBuffer::Allocator::Free if the buffer
  4697. * was allocated with ArraryBuffer::Allocator::Allocate.
  4698. *
  4699. * This API is experimental and may change significantly.
  4700. */
  4701. class V8_EXPORT Contents { // NOLINT
  4702. public:
  4703. using Allocator = v8::ArrayBuffer::Allocator;
  4704. using DeleterCallback = void (*)(void* buffer, size_t length, void* info);
  4705. Contents()
  4706. : data_(nullptr),
  4707. byte_length_(0),
  4708. allocation_base_(nullptr),
  4709. allocation_length_(0),
  4710. allocation_mode_(Allocator::AllocationMode::kNormal),
  4711. deleter_(nullptr),
  4712. deleter_data_(nullptr) {}
  4713. void* AllocationBase() const { return allocation_base_; }
  4714. size_t AllocationLength() const { return allocation_length_; }
  4715. Allocator::AllocationMode AllocationMode() const {
  4716. return allocation_mode_;
  4717. }
  4718. void* Data() const { return data_; }
  4719. size_t ByteLength() const { return byte_length_; }
  4720. DeleterCallback Deleter() const { return deleter_; }
  4721. void* DeleterData() const { return deleter_data_; }
  4722. private:
  4723. Contents(void* data, size_t byte_length, void* allocation_base,
  4724. size_t allocation_length,
  4725. Allocator::AllocationMode allocation_mode, DeleterCallback deleter,
  4726. void* deleter_data);
  4727. void* data_;
  4728. size_t byte_length_;
  4729. void* allocation_base_;
  4730. size_t allocation_length_;
  4731. Allocator::AllocationMode allocation_mode_;
  4732. DeleterCallback deleter_;
  4733. void* deleter_data_;
  4734. friend class SharedArrayBuffer;
  4735. };
  4736. /**
  4737. * Data length in bytes.
  4738. */
  4739. size_t ByteLength() const;
  4740. /**
  4741. * Create a new SharedArrayBuffer. Allocate |byte_length| bytes.
  4742. * Allocated memory will be owned by a created SharedArrayBuffer and
  4743. * will be deallocated when it is garbage-collected,
  4744. * unless the object is externalized.
  4745. */
  4746. static Local<SharedArrayBuffer> New(Isolate* isolate, size_t byte_length);
  4747. /**
  4748. * Create a new SharedArrayBuffer over an existing memory block. The created
  4749. * array buffer is immediately in externalized state unless otherwise
  4750. * specified. The memory block will not be reclaimed when a created
  4751. * SharedArrayBuffer is garbage-collected.
  4752. */
  4753. V8_DEPRECATE_SOON(
  4754. "Use the version that takes a BackingStore. "
  4755. "See http://crbug.com/v8/9908.")
  4756. static Local<SharedArrayBuffer> New(
  4757. Isolate* isolate, void* data, size_t byte_length,
  4758. ArrayBufferCreationMode mode = ArrayBufferCreationMode::kExternalized);
  4759. /**
  4760. * Create a new SharedArrayBuffer with an existing backing store.
  4761. * The created array keeps a reference to the backing store until the array
  4762. * is garbage collected. Note that the IsExternal bit does not affect this
  4763. * reference from the array to the backing store.
  4764. *
  4765. * In future IsExternal bit will be removed. Until then the bit is set as
  4766. * follows. If the backing store does not own the underlying buffer, then
  4767. * the array is created in externalized state. Otherwise, the array is created
  4768. * in internalized state. In the latter case the array can be transitioned
  4769. * to the externalized state using Externalize(backing_store).
  4770. */
  4771. static Local<SharedArrayBuffer> New(
  4772. Isolate* isolate, std::shared_ptr<BackingStore> backing_store);
  4773. /**
  4774. * Returns a new standalone BackingStore that is allocated using the array
  4775. * buffer allocator of the isolate. The result can be later passed to
  4776. * SharedArrayBuffer::New.
  4777. *
  4778. * If the allocator returns nullptr, then the function may cause GCs in the
  4779. * given isolate and re-try the allocation. If GCs do not help, then the
  4780. * function will crash with an out-of-memory error.
  4781. */
  4782. static std::unique_ptr<BackingStore> NewBackingStore(Isolate* isolate,
  4783. size_t byte_length);
  4784. /**
  4785. * Returns a new standalone BackingStore that takes over the ownership of
  4786. * the given buffer. The destructor of the BackingStore invokes the given
  4787. * deleter callback.
  4788. *
  4789. * The result can be later passed to SharedArrayBuffer::New. The raw pointer
  4790. * to the buffer must not be passed again to any V8 functions.
  4791. */
  4792. static std::unique_ptr<BackingStore> NewBackingStore(
  4793. void* data, size_t byte_length, BackingStoreDeleterCallback deleter,
  4794. void* deleter_data);
  4795. /**
  4796. * Create a new SharedArrayBuffer over an existing memory block. Propagate
  4797. * flags to indicate whether the underlying buffer can be grown.
  4798. */
  4799. V8_DEPRECATED(
  4800. "Use the version that takes a BackingStore. "
  4801. "See http://crbug.com/v8/9908.")
  4802. static Local<SharedArrayBuffer> New(
  4803. Isolate* isolate, const SharedArrayBuffer::Contents&,
  4804. ArrayBufferCreationMode mode = ArrayBufferCreationMode::kExternalized);
  4805. /**
  4806. * Returns true if SharedArrayBuffer is externalized, that is, does not
  4807. * own its memory block.
  4808. */
  4809. V8_DEPRECATE_SOON(
  4810. "With v8::BackingStore externalized SharedArrayBuffers are the same "
  4811. "as ordinary SharedArrayBuffers. See http://crbug.com/v8/9908.")
  4812. bool IsExternal() const;
  4813. /**
  4814. * Make this SharedArrayBuffer external. The pointer to underlying memory
  4815. * block and byte length are returned as |Contents| structure. After
  4816. * SharedArrayBuffer had been externalized, it does no longer own the memory
  4817. * block. The caller should take steps to free memory when it is no longer
  4818. * needed.
  4819. *
  4820. * The memory block is guaranteed to be allocated with |Allocator::Allocate|
  4821. * by the allocator specified in
  4822. * v8::Isolate::CreateParams::array_buffer_allocator.
  4823. *
  4824. */
  4825. V8_DEPRECATE_SOON(
  4826. "Use GetBackingStore or Detach. See http://crbug.com/v8/9908.")
  4827. Contents Externalize();
  4828. /**
  4829. * Marks this SharedArrayBuffer external given a witness that the embedder
  4830. * has fetched the backing store using the new GetBackingStore() function.
  4831. *
  4832. * With the new lifetime management of backing stores there is no need for
  4833. * externalizing, so this function exists only to make the transition easier.
  4834. */
  4835. V8_DEPRECATE_SOON("This will be removed together with IsExternal.")
  4836. void Externalize(const std::shared_ptr<BackingStore>& backing_store);
  4837. /**
  4838. * Get a pointer to the ArrayBuffer's underlying memory block without
  4839. * externalizing it. If the ArrayBuffer is not externalized, this pointer
  4840. * will become invalid as soon as the ArrayBuffer became garbage collected.
  4841. *
  4842. * The embedder should make sure to hold a strong reference to the
  4843. * ArrayBuffer while accessing this pointer.
  4844. *
  4845. * The memory block is guaranteed to be allocated with |Allocator::Allocate|
  4846. * by the allocator specified in
  4847. * v8::Isolate::CreateParams::array_buffer_allocator.
  4848. */
  4849. V8_DEPRECATE_SOON("Use GetBackingStore. See http://crbug.com/v8/9908.")
  4850. Contents GetContents();
  4851. /**
  4852. * Get a shared pointer to the backing store of this array buffer. This
  4853. * pointer coordinates the lifetime management of the internal storage
  4854. * with any live ArrayBuffers on the heap, even across isolates. The embedder
  4855. * should not attempt to manage lifetime of the storage through other means.
  4856. *
  4857. * This function replaces both Externalize() and GetContents().
  4858. */
  4859. std::shared_ptr<BackingStore> GetBackingStore();
  4860. V8_INLINE static SharedArrayBuffer* Cast(Value* obj);
  4861. static const int kInternalFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
  4862. private:
  4863. SharedArrayBuffer();
  4864. static void CheckCast(Value* obj);
  4865. Contents GetContents(bool externalize);
  4866. };
  4867. /**
  4868. * An instance of the built-in Date constructor (ECMA-262, 15.9).
  4869. */
  4870. class V8_EXPORT Date : public Object {
  4871. public:
  4872. static V8_WARN_UNUSED_RESULT MaybeLocal<Value> New(Local<Context> context,
  4873. double time);
  4874. /**
  4875. * A specialization of Value::NumberValue that is more efficient
  4876. * because we know the structure of this object.
  4877. */
  4878. double ValueOf() const;
  4879. V8_INLINE static Date* Cast(Value* obj);
  4880. private:
  4881. static void CheckCast(Value* obj);
  4882. };
  4883. /**
  4884. * A Number object (ECMA-262, 4.3.21).
  4885. */
  4886. class V8_EXPORT NumberObject : public Object {
  4887. public:
  4888. static Local<Value> New(Isolate* isolate, double value);
  4889. double ValueOf() const;
  4890. V8_INLINE static NumberObject* Cast(Value* obj);
  4891. private:
  4892. static void CheckCast(Value* obj);
  4893. };
  4894. /**
  4895. * A BigInt object (https://tc39.github.io/proposal-bigint)
  4896. */
  4897. class V8_EXPORT BigIntObject : public Object {
  4898. public:
  4899. static Local<Value> New(Isolate* isolate, int64_t value);
  4900. Local<BigInt> ValueOf() const;
  4901. V8_INLINE static BigIntObject* Cast(Value* obj);
  4902. private:
  4903. static void CheckCast(Value* obj);
  4904. };
  4905. /**
  4906. * A Boolean object (ECMA-262, 4.3.15).
  4907. */
  4908. class V8_EXPORT BooleanObject : public Object {
  4909. public:
  4910. static Local<Value> New(Isolate* isolate, bool value);
  4911. bool ValueOf() const;
  4912. V8_INLINE static BooleanObject* Cast(Value* obj);
  4913. private:
  4914. static void CheckCast(Value* obj);
  4915. };
  4916. /**
  4917. * A String object (ECMA-262, 4.3.18).
  4918. */
  4919. class V8_EXPORT StringObject : public Object {
  4920. public:
  4921. static Local<Value> New(Isolate* isolate, Local<String> value);
  4922. Local<String> ValueOf() const;
  4923. V8_INLINE static StringObject* Cast(Value* obj);
  4924. private:
  4925. static void CheckCast(Value* obj);
  4926. };
  4927. /**
  4928. * A Symbol object (ECMA-262 edition 6).
  4929. */
  4930. class V8_EXPORT SymbolObject : public Object {
  4931. public:
  4932. static Local<Value> New(Isolate* isolate, Local<Symbol> value);
  4933. Local<Symbol> ValueOf() const;
  4934. V8_INLINE static SymbolObject* Cast(Value* obj);
  4935. private:
  4936. static void CheckCast(Value* obj);
  4937. };
  4938. /**
  4939. * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
  4940. */
  4941. class V8_EXPORT RegExp : public Object {
  4942. public:
  4943. /**
  4944. * Regular expression flag bits. They can be or'ed to enable a set
  4945. * of flags.
  4946. */
  4947. enum Flags {
  4948. kNone = 0,
  4949. kGlobal = 1 << 0,
  4950. kIgnoreCase = 1 << 1,
  4951. kMultiline = 1 << 2,
  4952. kSticky = 1 << 3,
  4953. kUnicode = 1 << 4,
  4954. kDotAll = 1 << 5,
  4955. };
  4956. static constexpr int kFlagCount = 6;
  4957. /**
  4958. * Creates a regular expression from the given pattern string and
  4959. * the flags bit field. May throw a JavaScript exception as
  4960. * described in ECMA-262, 15.10.4.1.
  4961. *
  4962. * For example,
  4963. * RegExp::New(v8::String::New("foo"),
  4964. * static_cast<RegExp::Flags>(kGlobal | kMultiline))
  4965. * is equivalent to evaluating "/foo/gm".
  4966. */
  4967. static V8_WARN_UNUSED_RESULT MaybeLocal<RegExp> New(Local<Context> context,
  4968. Local<String> pattern,
  4969. Flags flags);
  4970. /**
  4971. * Like New, but additionally specifies a backtrack limit. If the number of
  4972. * backtracks done in one Exec call hits the limit, a match failure is
  4973. * immediately returned.
  4974. */
  4975. static V8_WARN_UNUSED_RESULT MaybeLocal<RegExp> NewWithBacktrackLimit(
  4976. Local<Context> context, Local<String> pattern, Flags flags,
  4977. uint32_t backtrack_limit);
  4978. /**
  4979. * Executes the current RegExp instance on the given subject string.
  4980. * Equivalent to RegExp.prototype.exec as described in
  4981. *
  4982. * https://tc39.es/ecma262/#sec-regexp.prototype.exec
  4983. *
  4984. * On success, an Array containing the matched strings is returned. On
  4985. * failure, returns Null.
  4986. *
  4987. * Note: modifies global context state, accessible e.g. through RegExp.input.
  4988. */
  4989. V8_WARN_UNUSED_RESULT MaybeLocal<Object> Exec(Local<Context> context,
  4990. Local<String> subject);
  4991. /**
  4992. * Returns the value of the source property: a string representing
  4993. * the regular expression.
  4994. */
  4995. Local<String> GetSource() const;
  4996. /**
  4997. * Returns the flags bit field.
  4998. */
  4999. Flags GetFlags() const;
  5000. V8_INLINE static RegExp* Cast(Value* obj);
  5001. private:
  5002. static void CheckCast(Value* obj);
  5003. };
  5004. /**
  5005. * An instance of the built-in FinalizationGroup constructor.
  5006. *
  5007. * This API is experimental and may change significantly.
  5008. */
  5009. class V8_EXPORT FinalizationGroup : public Object {
  5010. public:
  5011. /**
  5012. * Runs the cleanup callback of the given FinalizationGroup.
  5013. *
  5014. * V8 will inform the embedder that there are finalizer callbacks be
  5015. * called through HostCleanupFinalizationGroupCallback.
  5016. *
  5017. * HostCleanupFinalizationGroupCallback should schedule a task to
  5018. * call FinalizationGroup::Cleanup() at some point in the
  5019. * future. It's the embedders responsiblity to make this call at a
  5020. * time which does not interrupt synchronous ECMAScript code
  5021. * execution.
  5022. *
  5023. * If the result is Nothing<bool> then an exception has
  5024. * occurred. Otherwise the result is |true| if the cleanup callback
  5025. * was called successfully. The result is never |false|.
  5026. */
  5027. static V8_WARN_UNUSED_RESULT Maybe<bool> Cleanup(
  5028. Local<FinalizationGroup> finalization_group);
  5029. };
  5030. /**
  5031. * A JavaScript value that wraps a C++ void*. This type of value is mainly used
  5032. * to associate C++ data structures with JavaScript objects.
  5033. */
  5034. class V8_EXPORT External : public Value {
  5035. public:
  5036. static Local<External> New(Isolate* isolate, void* value);
  5037. V8_INLINE static External* Cast(Value* obj);
  5038. void* Value() const;
  5039. private:
  5040. static void CheckCast(v8::Value* obj);
  5041. };
  5042. #define V8_INTRINSICS_LIST(F) \
  5043. F(ArrayProto_entries, array_entries_iterator) \
  5044. F(ArrayProto_forEach, array_for_each_iterator) \
  5045. F(ArrayProto_keys, array_keys_iterator) \
  5046. F(ArrayProto_values, array_values_iterator) \
  5047. F(ErrorPrototype, initial_error_prototype) \
  5048. F(IteratorPrototype, initial_iterator_prototype)
  5049. enum Intrinsic {
  5050. #define V8_DECL_INTRINSIC(name, iname) k##name,
  5051. V8_INTRINSICS_LIST(V8_DECL_INTRINSIC)
  5052. #undef V8_DECL_INTRINSIC
  5053. };
  5054. // --- Templates ---
  5055. /**
  5056. * The superclass of object and function templates.
  5057. */
  5058. class V8_EXPORT Template : public Data {
  5059. public:
  5060. /**
  5061. * Adds a property to each instance created by this template.
  5062. *
  5063. * The property must be defined either as a primitive value, or a template.
  5064. */
  5065. void Set(Local<Name> name, Local<Data> value,
  5066. PropertyAttribute attributes = None);
  5067. void SetPrivate(Local<Private> name, Local<Data> value,
  5068. PropertyAttribute attributes = None);
  5069. V8_INLINE void Set(Isolate* isolate, const char* name, Local<Data> value);
  5070. void SetAccessorProperty(
  5071. Local<Name> name,
  5072. Local<FunctionTemplate> getter = Local<FunctionTemplate>(),
  5073. Local<FunctionTemplate> setter = Local<FunctionTemplate>(),
  5074. PropertyAttribute attribute = None,
  5075. AccessControl settings = DEFAULT);
  5076. /**
  5077. * Whenever the property with the given name is accessed on objects
  5078. * created from this Template the getter and setter callbacks
  5079. * are called instead of getting and setting the property directly
  5080. * on the JavaScript object.
  5081. *
  5082. * \param name The name of the property for which an accessor is added.
  5083. * \param getter The callback to invoke when getting the property.
  5084. * \param setter The callback to invoke when setting the property.
  5085. * \param data A piece of data that will be passed to the getter and setter
  5086. * callbacks whenever they are invoked.
  5087. * \param settings Access control settings for the accessor. This is a bit
  5088. * field consisting of one of more of
  5089. * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
  5090. * The default is to not allow cross-context access.
  5091. * ALL_CAN_READ means that all cross-context reads are allowed.
  5092. * ALL_CAN_WRITE means that all cross-context writes are allowed.
  5093. * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
  5094. * cross-context access.
  5095. * \param attribute The attributes of the property for which an accessor
  5096. * is added.
  5097. * \param signature The signature describes valid receivers for the accessor
  5098. * and is used to perform implicit instance checks against them. If the
  5099. * receiver is incompatible (i.e. is not an instance of the constructor as
  5100. * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
  5101. * thrown and no callback is invoked.
  5102. */
  5103. void SetNativeDataProperty(
  5104. Local<String> name, AccessorGetterCallback getter,
  5105. AccessorSetterCallback setter = nullptr,
  5106. // TODO(dcarney): gcc can't handle Local below
  5107. Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
  5108. Local<AccessorSignature> signature = Local<AccessorSignature>(),
  5109. AccessControl settings = DEFAULT,
  5110. SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect,
  5111. SideEffectType setter_side_effect_type = SideEffectType::kHasSideEffect);
  5112. void SetNativeDataProperty(
  5113. Local<Name> name, AccessorNameGetterCallback getter,
  5114. AccessorNameSetterCallback setter = nullptr,
  5115. // TODO(dcarney): gcc can't handle Local below
  5116. Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
  5117. Local<AccessorSignature> signature = Local<AccessorSignature>(),
  5118. AccessControl settings = DEFAULT,
  5119. SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect,
  5120. SideEffectType setter_side_effect_type = SideEffectType::kHasSideEffect);
  5121. /**
  5122. * Like SetNativeDataProperty, but V8 will replace the native data property
  5123. * with a real data property on first access.
  5124. */
  5125. void SetLazyDataProperty(
  5126. Local<Name> name, AccessorNameGetterCallback getter,
  5127. Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
  5128. SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect,
  5129. SideEffectType setter_side_effect_type = SideEffectType::kHasSideEffect);
  5130. /**
  5131. * During template instantiation, sets the value with the intrinsic property
  5132. * from the correct context.
  5133. */
  5134. void SetIntrinsicDataProperty(Local<Name> name, Intrinsic intrinsic,
  5135. PropertyAttribute attribute = None);
  5136. private:
  5137. Template();
  5138. friend class ObjectTemplate;
  5139. friend class FunctionTemplate;
  5140. };
  5141. // TODO(dcarney): Replace GenericNamedPropertyFooCallback with just
  5142. // NamedPropertyFooCallback.
  5143. /**
  5144. * Interceptor for get requests on an object.
  5145. *
  5146. * Use `info.GetReturnValue().Set()` to set the return value of the
  5147. * intercepted get request.
  5148. *
  5149. * \param property The name of the property for which the request was
  5150. * intercepted.
  5151. * \param info Information about the intercepted request, such as
  5152. * isolate, receiver, return value, or whether running in `'use strict`' mode.
  5153. * See `PropertyCallbackInfo`.
  5154. *
  5155. * \code
  5156. * void GetterCallback(
  5157. * Local<Name> name,
  5158. * const v8::PropertyCallbackInfo<v8::Value>& info) {
  5159. * info.GetReturnValue().Set(v8_num(42));
  5160. * }
  5161. *
  5162. * v8::Local<v8::FunctionTemplate> templ =
  5163. * v8::FunctionTemplate::New(isolate);
  5164. * templ->InstanceTemplate()->SetHandler(
  5165. * v8::NamedPropertyHandlerConfiguration(GetterCallback));
  5166. * LocalContext env;
  5167. * env->Global()
  5168. * ->Set(env.local(), v8_str("obj"), templ->GetFunction(env.local())
  5169. * .ToLocalChecked()
  5170. * ->NewInstance(env.local())
  5171. * .ToLocalChecked())
  5172. * .FromJust();
  5173. * v8::Local<v8::Value> result = CompileRun("obj.a = 17; obj.a");
  5174. * CHECK(v8_num(42)->Equals(env.local(), result).FromJust());
  5175. * \endcode
  5176. *
  5177. * See also `ObjectTemplate::SetHandler`.
  5178. */
  5179. typedef void (*GenericNamedPropertyGetterCallback)(
  5180. Local<Name> property, const PropertyCallbackInfo<Value>& info);
  5181. /**
  5182. * Interceptor for set requests on an object.
  5183. *
  5184. * Use `info.GetReturnValue()` to indicate whether the request was intercepted
  5185. * or not. If the setter successfully intercepts the request, i.e., if the
  5186. * request should not be further executed, call
  5187. * `info.GetReturnValue().Set(value)`. If the setter
  5188. * did not intercept the request, i.e., if the request should be handled as
  5189. * if no interceptor is present, do not not call `Set()`.
  5190. *
  5191. * \param property The name of the property for which the request was
  5192. * intercepted.
  5193. * \param value The value which the property will have if the request
  5194. * is not intercepted.
  5195. * \param info Information about the intercepted request, such as
  5196. * isolate, receiver, return value, or whether running in `'use strict'` mode.
  5197. * See `PropertyCallbackInfo`.
  5198. *
  5199. * See also
  5200. * `ObjectTemplate::SetHandler.`
  5201. */
  5202. typedef void (*GenericNamedPropertySetterCallback)(
  5203. Local<Name> property, Local<Value> value,
  5204. const PropertyCallbackInfo<Value>& info);
  5205. /**
  5206. * Intercepts all requests that query the attributes of the
  5207. * property, e.g., getOwnPropertyDescriptor(), propertyIsEnumerable(), and
  5208. * defineProperty().
  5209. *
  5210. * Use `info.GetReturnValue().Set(value)` to set the property attributes. The
  5211. * value is an integer encoding a `v8::PropertyAttribute`.
  5212. *
  5213. * \param property The name of the property for which the request was
  5214. * intercepted.
  5215. * \param info Information about the intercepted request, such as
  5216. * isolate, receiver, return value, or whether running in `'use strict'` mode.
  5217. * See `PropertyCallbackInfo`.
  5218. *
  5219. * \note Some functions query the property attributes internally, even though
  5220. * they do not return the attributes. For example, `hasOwnProperty()` can
  5221. * trigger this interceptor depending on the state of the object.
  5222. *
  5223. * See also
  5224. * `ObjectTemplate::SetHandler.`
  5225. */
  5226. typedef void (*GenericNamedPropertyQueryCallback)(
  5227. Local<Name> property, const PropertyCallbackInfo<Integer>& info);
  5228. /**
  5229. * Interceptor for delete requests on an object.
  5230. *
  5231. * Use `info.GetReturnValue()` to indicate whether the request was intercepted
  5232. * or not. If the deleter successfully intercepts the request, i.e., if the
  5233. * request should not be further executed, call
  5234. * `info.GetReturnValue().Set(value)` with a boolean `value`. The `value` is
  5235. * used as the return value of `delete`.
  5236. *
  5237. * \param property The name of the property for which the request was
  5238. * intercepted.
  5239. * \param info Information about the intercepted request, such as
  5240. * isolate, receiver, return value, or whether running in `'use strict'` mode.
  5241. * See `PropertyCallbackInfo`.
  5242. *
  5243. * \note If you need to mimic the behavior of `delete`, i.e., throw in strict
  5244. * mode instead of returning false, use `info.ShouldThrowOnError()` to determine
  5245. * if you are in strict mode.
  5246. *
  5247. * See also `ObjectTemplate::SetHandler.`
  5248. */
  5249. typedef void (*GenericNamedPropertyDeleterCallback)(
  5250. Local<Name> property, const PropertyCallbackInfo<Boolean>& info);
  5251. /**
  5252. * Returns an array containing the names of the properties the named
  5253. * property getter intercepts.
  5254. *
  5255. * Note: The values in the array must be of type v8::Name.
  5256. */
  5257. typedef void (*GenericNamedPropertyEnumeratorCallback)(
  5258. const PropertyCallbackInfo<Array>& info);
  5259. /**
  5260. * Interceptor for defineProperty requests on an object.
  5261. *
  5262. * Use `info.GetReturnValue()` to indicate whether the request was intercepted
  5263. * or not. If the definer successfully intercepts the request, i.e., if the
  5264. * request should not be further executed, call
  5265. * `info.GetReturnValue().Set(value)`. If the definer
  5266. * did not intercept the request, i.e., if the request should be handled as
  5267. * if no interceptor is present, do not not call `Set()`.
  5268. *
  5269. * \param property The name of the property for which the request was
  5270. * intercepted.
  5271. * \param desc The property descriptor which is used to define the
  5272. * property if the request is not intercepted.
  5273. * \param info Information about the intercepted request, such as
  5274. * isolate, receiver, return value, or whether running in `'use strict'` mode.
  5275. * See `PropertyCallbackInfo`.
  5276. *
  5277. * See also `ObjectTemplate::SetHandler`.
  5278. */
  5279. typedef void (*GenericNamedPropertyDefinerCallback)(
  5280. Local<Name> property, const PropertyDescriptor& desc,
  5281. const PropertyCallbackInfo<Value>& info);
  5282. /**
  5283. * Interceptor for getOwnPropertyDescriptor requests on an object.
  5284. *
  5285. * Use `info.GetReturnValue().Set()` to set the return value of the
  5286. * intercepted request. The return value must be an object that
  5287. * can be converted to a PropertyDescriptor, e.g., a `v8::value` returned from
  5288. * `v8::Object::getOwnPropertyDescriptor`.
  5289. *
  5290. * \param property The name of the property for which the request was
  5291. * intercepted.
  5292. * \info Information about the intercepted request, such as
  5293. * isolate, receiver, return value, or whether running in `'use strict'` mode.
  5294. * See `PropertyCallbackInfo`.
  5295. *
  5296. * \note If GetOwnPropertyDescriptor is intercepted, it will
  5297. * always return true, i.e., indicate that the property was found.
  5298. *
  5299. * See also `ObjectTemplate::SetHandler`.
  5300. */
  5301. typedef void (*GenericNamedPropertyDescriptorCallback)(
  5302. Local<Name> property, const PropertyCallbackInfo<Value>& info);
  5303. /**
  5304. * See `v8::GenericNamedPropertyGetterCallback`.
  5305. */
  5306. typedef void (*IndexedPropertyGetterCallback)(
  5307. uint32_t index,
  5308. const PropertyCallbackInfo<Value>& info);
  5309. /**
  5310. * See `v8::GenericNamedPropertySetterCallback`.
  5311. */
  5312. typedef void (*IndexedPropertySetterCallback)(
  5313. uint32_t index,
  5314. Local<Value> value,
  5315. const PropertyCallbackInfo<Value>& info);
  5316. /**
  5317. * See `v8::GenericNamedPropertyQueryCallback`.
  5318. */
  5319. typedef void (*IndexedPropertyQueryCallback)(
  5320. uint32_t index,
  5321. const PropertyCallbackInfo<Integer>& info);
  5322. /**
  5323. * See `v8::GenericNamedPropertyDeleterCallback`.
  5324. */
  5325. typedef void (*IndexedPropertyDeleterCallback)(
  5326. uint32_t index,
  5327. const PropertyCallbackInfo<Boolean>& info);
  5328. /**
  5329. * Returns an array containing the indices of the properties the indexed
  5330. * property getter intercepts.
  5331. *
  5332. * Note: The values in the array must be uint32_t.
  5333. */
  5334. typedef void (*IndexedPropertyEnumeratorCallback)(
  5335. const PropertyCallbackInfo<Array>& info);
  5336. /**
  5337. * See `v8::GenericNamedPropertyDefinerCallback`.
  5338. */
  5339. typedef void (*IndexedPropertyDefinerCallback)(
  5340. uint32_t index, const PropertyDescriptor& desc,
  5341. const PropertyCallbackInfo<Value>& info);
  5342. /**
  5343. * See `v8::GenericNamedPropertyDescriptorCallback`.
  5344. */
  5345. typedef void (*IndexedPropertyDescriptorCallback)(
  5346. uint32_t index, const PropertyCallbackInfo<Value>& info);
  5347. /**
  5348. * Access type specification.
  5349. */
  5350. enum AccessType {
  5351. ACCESS_GET,
  5352. ACCESS_SET,
  5353. ACCESS_HAS,
  5354. ACCESS_DELETE,
  5355. ACCESS_KEYS
  5356. };
  5357. /**
  5358. * Returns true if the given context should be allowed to access the given
  5359. * object.
  5360. */
  5361. typedef bool (*AccessCheckCallback)(Local<Context> accessing_context,
  5362. Local<Object> accessed_object,
  5363. Local<Value> data);
  5364. /**
  5365. * A FunctionTemplate is used to create functions at runtime. There
  5366. * can only be one function created from a FunctionTemplate in a
  5367. * context. The lifetime of the created function is equal to the
  5368. * lifetime of the context. So in case the embedder needs to create
  5369. * temporary functions that can be collected using Scripts is
  5370. * preferred.
  5371. *
  5372. * Any modification of a FunctionTemplate after first instantiation will trigger
  5373. * a crash.
  5374. *
  5375. * A FunctionTemplate can have properties, these properties are added to the
  5376. * function object when it is created.
  5377. *
  5378. * A FunctionTemplate has a corresponding instance template which is
  5379. * used to create object instances when the function is used as a
  5380. * constructor. Properties added to the instance template are added to
  5381. * each object instance.
  5382. *
  5383. * A FunctionTemplate can have a prototype template. The prototype template
  5384. * is used to create the prototype object of the function.
  5385. *
  5386. * The following example shows how to use a FunctionTemplate:
  5387. *
  5388. * \code
  5389. * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(isolate);
  5390. * t->Set(isolate, "func_property", v8::Number::New(isolate, 1));
  5391. *
  5392. * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
  5393. * proto_t->Set(isolate,
  5394. * "proto_method",
  5395. * v8::FunctionTemplate::New(isolate, InvokeCallback));
  5396. * proto_t->Set(isolate, "proto_const", v8::Number::New(isolate, 2));
  5397. *
  5398. * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
  5399. * instance_t->SetAccessor(String::NewFromUtf8(isolate, "instance_accessor"),
  5400. * InstanceAccessorCallback);
  5401. * instance_t->SetHandler(
  5402. * NamedPropertyHandlerConfiguration(PropertyHandlerCallback));
  5403. * instance_t->Set(String::NewFromUtf8(isolate, "instance_property"),
  5404. * Number::New(isolate, 3));
  5405. *
  5406. * v8::Local<v8::Function> function = t->GetFunction();
  5407. * v8::Local<v8::Object> instance = function->NewInstance();
  5408. * \endcode
  5409. *
  5410. * Let's use "function" as the JS variable name of the function object
  5411. * and "instance" for the instance object created above. The function
  5412. * and the instance will have the following properties:
  5413. *
  5414. * \code
  5415. * func_property in function == true;
  5416. * function.func_property == 1;
  5417. *
  5418. * function.prototype.proto_method() invokes 'InvokeCallback'
  5419. * function.prototype.proto_const == 2;
  5420. *
  5421. * instance instanceof function == true;
  5422. * instance.instance_accessor calls 'InstanceAccessorCallback'
  5423. * instance.instance_property == 3;
  5424. * \endcode
  5425. *
  5426. * A FunctionTemplate can inherit from another one by calling the
  5427. * FunctionTemplate::Inherit method. The following graph illustrates
  5428. * the semantics of inheritance:
  5429. *
  5430. * \code
  5431. * FunctionTemplate Parent -> Parent() . prototype -> { }
  5432. * ^ ^
  5433. * | Inherit(Parent) | .__proto__
  5434. * | |
  5435. * FunctionTemplate Child -> Child() . prototype -> { }
  5436. * \endcode
  5437. *
  5438. * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
  5439. * object of the Child() function has __proto__ pointing to the
  5440. * Parent() function's prototype object. An instance of the Child
  5441. * function has all properties on Parent's instance templates.
  5442. *
  5443. * Let Parent be the FunctionTemplate initialized in the previous
  5444. * section and create a Child FunctionTemplate by:
  5445. *
  5446. * \code
  5447. * Local<FunctionTemplate> parent = t;
  5448. * Local<FunctionTemplate> child = FunctionTemplate::New();
  5449. * child->Inherit(parent);
  5450. *
  5451. * Local<Function> child_function = child->GetFunction();
  5452. * Local<Object> child_instance = child_function->NewInstance();
  5453. * \endcode
  5454. *
  5455. * The Child function and Child instance will have the following
  5456. * properties:
  5457. *
  5458. * \code
  5459. * child_func.prototype.__proto__ == function.prototype;
  5460. * child_instance.instance_accessor calls 'InstanceAccessorCallback'
  5461. * child_instance.instance_property == 3;
  5462. * \endcode
  5463. */
  5464. class V8_EXPORT FunctionTemplate : public Template {
  5465. public:
  5466. /** Creates a function template.*/
  5467. static Local<FunctionTemplate> New(
  5468. Isolate* isolate, FunctionCallback callback = nullptr,
  5469. Local<Value> data = Local<Value>(),
  5470. Local<Signature> signature = Local<Signature>(), int length = 0,
  5471. ConstructorBehavior behavior = ConstructorBehavior::kAllow,
  5472. SideEffectType side_effect_type = SideEffectType::kHasSideEffect);
  5473. /** Get a template included in the snapshot by index. */
  5474. V8_DEPRECATED("Use v8::Isolate::GetDataFromSnapshotOnce instead")
  5475. static MaybeLocal<FunctionTemplate> FromSnapshot(Isolate* isolate,
  5476. size_t index);
  5477. /**
  5478. * Creates a function template backed/cached by a private property.
  5479. */
  5480. static Local<FunctionTemplate> NewWithCache(
  5481. Isolate* isolate, FunctionCallback callback,
  5482. Local<Private> cache_property, Local<Value> data = Local<Value>(),
  5483. Local<Signature> signature = Local<Signature>(), int length = 0,
  5484. SideEffectType side_effect_type = SideEffectType::kHasSideEffect);
  5485. /** Returns the unique function instance in the current execution context.*/
  5486. V8_WARN_UNUSED_RESULT MaybeLocal<Function> GetFunction(
  5487. Local<Context> context);
  5488. /**
  5489. * Similar to Context::NewRemoteContext, this creates an instance that
  5490. * isn't backed by an actual object.
  5491. *
  5492. * The InstanceTemplate of this FunctionTemplate must have access checks with
  5493. * handlers installed.
  5494. */
  5495. V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewRemoteInstance();
  5496. /**
  5497. * Set the call-handler callback for a FunctionTemplate. This
  5498. * callback is called whenever the function created from this
  5499. * FunctionTemplate is called.
  5500. */
  5501. void SetCallHandler(
  5502. FunctionCallback callback, Local<Value> data = Local<Value>(),
  5503. SideEffectType side_effect_type = SideEffectType::kHasSideEffect);
  5504. /** Set the predefined length property for the FunctionTemplate. */
  5505. void SetLength(int length);
  5506. /** Get the InstanceTemplate. */
  5507. Local<ObjectTemplate> InstanceTemplate();
  5508. /**
  5509. * Causes the function template to inherit from a parent function template.
  5510. * This means the function's prototype.__proto__ is set to the parent
  5511. * function's prototype.
  5512. **/
  5513. void Inherit(Local<FunctionTemplate> parent);
  5514. /**
  5515. * A PrototypeTemplate is the template used to create the prototype object
  5516. * of the function created by this template.
  5517. */
  5518. Local<ObjectTemplate> PrototypeTemplate();
  5519. /**
  5520. * A PrototypeProviderTemplate is another function template whose prototype
  5521. * property is used for this template. This is mutually exclusive with setting
  5522. * a prototype template indirectly by calling PrototypeTemplate() or using
  5523. * Inherit().
  5524. **/
  5525. void SetPrototypeProviderTemplate(Local<FunctionTemplate> prototype_provider);
  5526. /**
  5527. * Set the class name of the FunctionTemplate. This is used for
  5528. * printing objects created with the function created from the
  5529. * FunctionTemplate as its constructor.
  5530. */
  5531. void SetClassName(Local<String> name);
  5532. /**
  5533. * When set to true, no access check will be performed on the receiver of a
  5534. * function call. Currently defaults to true, but this is subject to change.
  5535. */
  5536. void SetAcceptAnyReceiver(bool value);
  5537. /**
  5538. * Sets the ReadOnly flag in the attributes of the 'prototype' property
  5539. * of functions created from this FunctionTemplate to true.
  5540. */
  5541. void ReadOnlyPrototype();
  5542. /**
  5543. * Removes the prototype property from functions created from this
  5544. * FunctionTemplate.
  5545. */
  5546. void RemovePrototype();
  5547. /**
  5548. * Returns true if the given object is an instance of this function
  5549. * template.
  5550. */
  5551. bool HasInstance(Local<Value> object);
  5552. V8_INLINE static FunctionTemplate* Cast(Data* data);
  5553. private:
  5554. FunctionTemplate();
  5555. static void CheckCast(Data* that);
  5556. friend class Context;
  5557. friend class ObjectTemplate;
  5558. };
  5559. /**
  5560. * Configuration flags for v8::NamedPropertyHandlerConfiguration or
  5561. * v8::IndexedPropertyHandlerConfiguration.
  5562. */
  5563. enum class PropertyHandlerFlags {
  5564. /**
  5565. * None.
  5566. */
  5567. kNone = 0,
  5568. /**
  5569. * See ALL_CAN_READ above.
  5570. */
  5571. kAllCanRead = 1,
  5572. /** Will not call into interceptor for properties on the receiver or prototype
  5573. * chain, i.e., only call into interceptor for properties that do not exist.
  5574. * Currently only valid for named interceptors.
  5575. */
  5576. kNonMasking = 1 << 1,
  5577. /**
  5578. * Will not call into interceptor for symbol lookup. Only meaningful for
  5579. * named interceptors.
  5580. */
  5581. kOnlyInterceptStrings = 1 << 2,
  5582. /**
  5583. * The getter, query, enumerator callbacks do not produce side effects.
  5584. */
  5585. kHasNoSideEffect = 1 << 3,
  5586. };
  5587. struct NamedPropertyHandlerConfiguration {
  5588. NamedPropertyHandlerConfiguration(
  5589. GenericNamedPropertyGetterCallback getter,
  5590. GenericNamedPropertySetterCallback setter,
  5591. GenericNamedPropertyQueryCallback query,
  5592. GenericNamedPropertyDeleterCallback deleter,
  5593. GenericNamedPropertyEnumeratorCallback enumerator,
  5594. GenericNamedPropertyDefinerCallback definer,
  5595. GenericNamedPropertyDescriptorCallback descriptor,
  5596. Local<Value> data = Local<Value>(),
  5597. PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
  5598. : getter(getter),
  5599. setter(setter),
  5600. query(query),
  5601. deleter(deleter),
  5602. enumerator(enumerator),
  5603. definer(definer),
  5604. descriptor(descriptor),
  5605. data(data),
  5606. flags(flags) {}
  5607. NamedPropertyHandlerConfiguration(
  5608. /** Note: getter is required */
  5609. GenericNamedPropertyGetterCallback getter = nullptr,
  5610. GenericNamedPropertySetterCallback setter = nullptr,
  5611. GenericNamedPropertyQueryCallback query = nullptr,
  5612. GenericNamedPropertyDeleterCallback deleter = nullptr,
  5613. GenericNamedPropertyEnumeratorCallback enumerator = nullptr,
  5614. Local<Value> data = Local<Value>(),
  5615. PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
  5616. : getter(getter),
  5617. setter(setter),
  5618. query(query),
  5619. deleter(deleter),
  5620. enumerator(enumerator),
  5621. definer(nullptr),
  5622. descriptor(nullptr),
  5623. data(data),
  5624. flags(flags) {}
  5625. NamedPropertyHandlerConfiguration(
  5626. GenericNamedPropertyGetterCallback getter,
  5627. GenericNamedPropertySetterCallback setter,
  5628. GenericNamedPropertyDescriptorCallback descriptor,
  5629. GenericNamedPropertyDeleterCallback deleter,
  5630. GenericNamedPropertyEnumeratorCallback enumerator,
  5631. GenericNamedPropertyDefinerCallback definer,
  5632. Local<Value> data = Local<Value>(),
  5633. PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
  5634. : getter(getter),
  5635. setter(setter),
  5636. query(nullptr),
  5637. deleter(deleter),
  5638. enumerator(enumerator),
  5639. definer(definer),
  5640. descriptor(descriptor),
  5641. data(data),
  5642. flags(flags) {}
  5643. GenericNamedPropertyGetterCallback getter;
  5644. GenericNamedPropertySetterCallback setter;
  5645. GenericNamedPropertyQueryCallback query;
  5646. GenericNamedPropertyDeleterCallback deleter;
  5647. GenericNamedPropertyEnumeratorCallback enumerator;
  5648. GenericNamedPropertyDefinerCallback definer;
  5649. GenericNamedPropertyDescriptorCallback descriptor;
  5650. Local<Value> data;
  5651. PropertyHandlerFlags flags;
  5652. };
  5653. struct IndexedPropertyHandlerConfiguration {
  5654. IndexedPropertyHandlerConfiguration(
  5655. IndexedPropertyGetterCallback getter,
  5656. IndexedPropertySetterCallback setter, IndexedPropertyQueryCallback query,
  5657. IndexedPropertyDeleterCallback deleter,
  5658. IndexedPropertyEnumeratorCallback enumerator,
  5659. IndexedPropertyDefinerCallback definer,
  5660. IndexedPropertyDescriptorCallback descriptor,
  5661. Local<Value> data = Local<Value>(),
  5662. PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
  5663. : getter(getter),
  5664. setter(setter),
  5665. query(query),
  5666. deleter(deleter),
  5667. enumerator(enumerator),
  5668. definer(definer),
  5669. descriptor(descriptor),
  5670. data(data),
  5671. flags(flags) {}
  5672. IndexedPropertyHandlerConfiguration(
  5673. /** Note: getter is required */
  5674. IndexedPropertyGetterCallback getter = nullptr,
  5675. IndexedPropertySetterCallback setter = nullptr,
  5676. IndexedPropertyQueryCallback query = nullptr,
  5677. IndexedPropertyDeleterCallback deleter = nullptr,
  5678. IndexedPropertyEnumeratorCallback enumerator = nullptr,
  5679. Local<Value> data = Local<Value>(),
  5680. PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
  5681. : getter(getter),
  5682. setter(setter),
  5683. query(query),
  5684. deleter(deleter),
  5685. enumerator(enumerator),
  5686. definer(nullptr),
  5687. descriptor(nullptr),
  5688. data(data),
  5689. flags(flags) {}
  5690. IndexedPropertyHandlerConfiguration(
  5691. IndexedPropertyGetterCallback getter,
  5692. IndexedPropertySetterCallback setter,
  5693. IndexedPropertyDescriptorCallback descriptor,
  5694. IndexedPropertyDeleterCallback deleter,
  5695. IndexedPropertyEnumeratorCallback enumerator,
  5696. IndexedPropertyDefinerCallback definer,
  5697. Local<Value> data = Local<Value>(),
  5698. PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
  5699. : getter(getter),
  5700. setter(setter),
  5701. query(nullptr),
  5702. deleter(deleter),
  5703. enumerator(enumerator),
  5704. definer(definer),
  5705. descriptor(descriptor),
  5706. data(data),
  5707. flags(flags) {}
  5708. IndexedPropertyGetterCallback getter;
  5709. IndexedPropertySetterCallback setter;
  5710. IndexedPropertyQueryCallback query;
  5711. IndexedPropertyDeleterCallback deleter;
  5712. IndexedPropertyEnumeratorCallback enumerator;
  5713. IndexedPropertyDefinerCallback definer;
  5714. IndexedPropertyDescriptorCallback descriptor;
  5715. Local<Value> data;
  5716. PropertyHandlerFlags flags;
  5717. };
  5718. /**
  5719. * An ObjectTemplate is used to create objects at runtime.
  5720. *
  5721. * Properties added to an ObjectTemplate are added to each object
  5722. * created from the ObjectTemplate.
  5723. */
  5724. class V8_EXPORT ObjectTemplate : public Template {
  5725. public:
  5726. /** Creates an ObjectTemplate. */
  5727. static Local<ObjectTemplate> New(
  5728. Isolate* isolate,
  5729. Local<FunctionTemplate> constructor = Local<FunctionTemplate>());
  5730. /** Get a template included in the snapshot by index. */
  5731. V8_DEPRECATED("Use v8::Isolate::GetDataFromSnapshotOnce instead")
  5732. static MaybeLocal<ObjectTemplate> FromSnapshot(Isolate* isolate,
  5733. size_t index);
  5734. /** Creates a new instance of this template.*/
  5735. V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstance(Local<Context> context);
  5736. /**
  5737. * Sets an accessor on the object template.
  5738. *
  5739. * Whenever the property with the given name is accessed on objects
  5740. * created from this ObjectTemplate the getter and setter callbacks
  5741. * are called instead of getting and setting the property directly
  5742. * on the JavaScript object.
  5743. *
  5744. * \param name The name of the property for which an accessor is added.
  5745. * \param getter The callback to invoke when getting the property.
  5746. * \param setter The callback to invoke when setting the property.
  5747. * \param data A piece of data that will be passed to the getter and setter
  5748. * callbacks whenever they are invoked.
  5749. * \param settings Access control settings for the accessor. This is a bit
  5750. * field consisting of one of more of
  5751. * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
  5752. * The default is to not allow cross-context access.
  5753. * ALL_CAN_READ means that all cross-context reads are allowed.
  5754. * ALL_CAN_WRITE means that all cross-context writes are allowed.
  5755. * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
  5756. * cross-context access.
  5757. * \param attribute The attributes of the property for which an accessor
  5758. * is added.
  5759. * \param signature The signature describes valid receivers for the accessor
  5760. * and is used to perform implicit instance checks against them. If the
  5761. * receiver is incompatible (i.e. is not an instance of the constructor as
  5762. * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
  5763. * thrown and no callback is invoked.
  5764. */
  5765. void SetAccessor(
  5766. Local<String> name, AccessorGetterCallback getter,
  5767. AccessorSetterCallback setter = nullptr,
  5768. Local<Value> data = Local<Value>(), AccessControl settings = DEFAULT,
  5769. PropertyAttribute attribute = None,
  5770. Local<AccessorSignature> signature = Local<AccessorSignature>(),
  5771. SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect,
  5772. SideEffectType setter_side_effect_type = SideEffectType::kHasSideEffect);
  5773. void SetAccessor(
  5774. Local<Name> name, AccessorNameGetterCallback getter,
  5775. AccessorNameSetterCallback setter = nullptr,
  5776. Local<Value> data = Local<Value>(), AccessControl settings = DEFAULT,
  5777. PropertyAttribute attribute = None,
  5778. Local<AccessorSignature> signature = Local<AccessorSignature>(),
  5779. SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect,
  5780. SideEffectType setter_side_effect_type = SideEffectType::kHasSideEffect);
  5781. /**
  5782. * Sets a named property handler on the object template.
  5783. *
  5784. * Whenever a property whose name is a string or a symbol is accessed on
  5785. * objects created from this object template, the provided callback is
  5786. * invoked instead of accessing the property directly on the JavaScript
  5787. * object.
  5788. *
  5789. * @param configuration The NamedPropertyHandlerConfiguration that defines the
  5790. * callbacks to invoke when accessing a property.
  5791. */
  5792. void SetHandler(const NamedPropertyHandlerConfiguration& configuration);
  5793. /**
  5794. * Sets an indexed property handler on the object template.
  5795. *
  5796. * Whenever an indexed property is accessed on objects created from
  5797. * this object template, the provided callback is invoked instead of
  5798. * accessing the property directly on the JavaScript object.
  5799. *
  5800. * \param getter The callback to invoke when getting a property.
  5801. * \param setter The callback to invoke when setting a property.
  5802. * \param query The callback to invoke to check if an object has a property.
  5803. * \param deleter The callback to invoke when deleting a property.
  5804. * \param enumerator The callback to invoke to enumerate all the indexed
  5805. * properties of an object.
  5806. * \param data A piece of data that will be passed to the callbacks
  5807. * whenever they are invoked.
  5808. */
  5809. // TODO(dcarney): deprecate
  5810. void SetIndexedPropertyHandler(
  5811. IndexedPropertyGetterCallback getter,
  5812. IndexedPropertySetterCallback setter = nullptr,
  5813. IndexedPropertyQueryCallback query = nullptr,
  5814. IndexedPropertyDeleterCallback deleter = nullptr,
  5815. IndexedPropertyEnumeratorCallback enumerator = nullptr,
  5816. Local<Value> data = Local<Value>()) {
  5817. SetHandler(IndexedPropertyHandlerConfiguration(getter, setter, query,
  5818. deleter, enumerator, data));
  5819. }
  5820. /**
  5821. * Sets an indexed property handler on the object template.
  5822. *
  5823. * Whenever an indexed property is accessed on objects created from
  5824. * this object template, the provided callback is invoked instead of
  5825. * accessing the property directly on the JavaScript object.
  5826. *
  5827. * @param configuration The IndexedPropertyHandlerConfiguration that defines
  5828. * the callbacks to invoke when accessing a property.
  5829. */
  5830. void SetHandler(const IndexedPropertyHandlerConfiguration& configuration);
  5831. /**
  5832. * Sets the callback to be used when calling instances created from
  5833. * this template as a function. If no callback is set, instances
  5834. * behave like normal JavaScript objects that cannot be called as a
  5835. * function.
  5836. */
  5837. void SetCallAsFunctionHandler(FunctionCallback callback,
  5838. Local<Value> data = Local<Value>());
  5839. /**
  5840. * Mark object instances of the template as undetectable.
  5841. *
  5842. * In many ways, undetectable objects behave as though they are not
  5843. * there. They behave like 'undefined' in conditionals and when
  5844. * printed. However, properties can be accessed and called as on
  5845. * normal objects.
  5846. */
  5847. void MarkAsUndetectable();
  5848. /**
  5849. * Sets access check callback on the object template and enables access
  5850. * checks.
  5851. *
  5852. * When accessing properties on instances of this object template,
  5853. * the access check callback will be called to determine whether or
  5854. * not to allow cross-context access to the properties.
  5855. */
  5856. void SetAccessCheckCallback(AccessCheckCallback callback,
  5857. Local<Value> data = Local<Value>());
  5858. /**
  5859. * Like SetAccessCheckCallback but invokes an interceptor on failed access
  5860. * checks instead of looking up all-can-read properties. You can only use
  5861. * either this method or SetAccessCheckCallback, but not both at the same
  5862. * time.
  5863. */
  5864. void SetAccessCheckCallbackAndHandler(
  5865. AccessCheckCallback callback,
  5866. const NamedPropertyHandlerConfiguration& named_handler,
  5867. const IndexedPropertyHandlerConfiguration& indexed_handler,
  5868. Local<Value> data = Local<Value>());
  5869. /**
  5870. * Gets the number of internal fields for objects generated from
  5871. * this template.
  5872. */
  5873. int InternalFieldCount();
  5874. /**
  5875. * Sets the number of internal fields for objects generated from
  5876. * this template.
  5877. */
  5878. void SetInternalFieldCount(int value);
  5879. /**
  5880. * Returns true if the object will be an immutable prototype exotic object.
  5881. */
  5882. bool IsImmutableProto();
  5883. /**
  5884. * Makes the ObjectTemplate for an immutable prototype exotic object, with an
  5885. * immutable __proto__.
  5886. */
  5887. void SetImmutableProto();
  5888. V8_INLINE static ObjectTemplate* Cast(Data* data);
  5889. private:
  5890. ObjectTemplate();
  5891. static Local<ObjectTemplate> New(internal::Isolate* isolate,
  5892. Local<FunctionTemplate> constructor);
  5893. static void CheckCast(Data* that);
  5894. friend class FunctionTemplate;
  5895. };
  5896. /**
  5897. * A Signature specifies which receiver is valid for a function.
  5898. *
  5899. * A receiver matches a given signature if the receiver (or any of its
  5900. * hidden prototypes) was created from the signature's FunctionTemplate, or
  5901. * from a FunctionTemplate that inherits directly or indirectly from the
  5902. * signature's FunctionTemplate.
  5903. */
  5904. class V8_EXPORT Signature : public Data {
  5905. public:
  5906. static Local<Signature> New(
  5907. Isolate* isolate,
  5908. Local<FunctionTemplate> receiver = Local<FunctionTemplate>());
  5909. V8_INLINE static Signature* Cast(Data* data);
  5910. private:
  5911. Signature();
  5912. static void CheckCast(Data* that);
  5913. };
  5914. /**
  5915. * An AccessorSignature specifies which receivers are valid parameters
  5916. * to an accessor callback.
  5917. */
  5918. class V8_EXPORT AccessorSignature : public Data {
  5919. public:
  5920. static Local<AccessorSignature> New(
  5921. Isolate* isolate,
  5922. Local<FunctionTemplate> receiver = Local<FunctionTemplate>());
  5923. V8_INLINE static AccessorSignature* Cast(Data* data);
  5924. private:
  5925. AccessorSignature();
  5926. static void CheckCast(Data* that);
  5927. };
  5928. // --- Extensions ---
  5929. /**
  5930. * Ignore
  5931. */
  5932. class V8_EXPORT Extension { // NOLINT
  5933. public:
  5934. // Note that the strings passed into this constructor must live as long
  5935. // as the Extension itself.
  5936. Extension(const char* name, const char* source = nullptr, int dep_count = 0,
  5937. const char** deps = nullptr, int source_length = -1);
  5938. virtual ~Extension() { delete source_; }
  5939. virtual Local<FunctionTemplate> GetNativeFunctionTemplate(
  5940. Isolate* isolate, Local<String> name) {
  5941. return Local<FunctionTemplate>();
  5942. }
  5943. const char* name() const { return name_; }
  5944. size_t source_length() const { return source_length_; }
  5945. const String::ExternalOneByteStringResource* source() const {
  5946. return source_;
  5947. }
  5948. int dependency_count() const { return dep_count_; }
  5949. const char** dependencies() const { return deps_; }
  5950. void set_auto_enable(bool value) { auto_enable_ = value; }
  5951. bool auto_enable() { return auto_enable_; }
  5952. // Disallow copying and assigning.
  5953. Extension(const Extension&) = delete;
  5954. void operator=(const Extension&) = delete;
  5955. private:
  5956. const char* name_;
  5957. size_t source_length_; // expected to initialize before source_
  5958. String::ExternalOneByteStringResource* source_;
  5959. int dep_count_;
  5960. const char** deps_;
  5961. bool auto_enable_;
  5962. };
  5963. void V8_EXPORT RegisterExtension(std::unique_ptr<Extension>);
  5964. // --- Statics ---
  5965. V8_INLINE Local<Primitive> Undefined(Isolate* isolate);
  5966. V8_INLINE Local<Primitive> Null(Isolate* isolate);
  5967. V8_INLINE Local<Boolean> True(Isolate* isolate);
  5968. V8_INLINE Local<Boolean> False(Isolate* isolate);
  5969. /**
  5970. * A set of constraints that specifies the limits of the runtime's memory use.
  5971. * You must set the heap size before initializing the VM - the size cannot be
  5972. * adjusted after the VM is initialized.
  5973. *
  5974. * If you are using threads then you should hold the V8::Locker lock while
  5975. * setting the stack limit and you must set a non-default stack limit separately
  5976. * for each thread.
  5977. *
  5978. * The arguments for set_max_semi_space_size, set_max_old_space_size,
  5979. * set_max_executable_size, set_code_range_size specify limits in MB.
  5980. *
  5981. * The argument for set_max_semi_space_size_in_kb is in KB.
  5982. */
  5983. class V8_EXPORT ResourceConstraints {
  5984. public:
  5985. /**
  5986. * Configures the constraints with reasonable default values based on the
  5987. * provided heap size limit. The heap size includes both the young and
  5988. * the old generation.
  5989. *
  5990. * \param initial_heap_size_in_bytes The initial heap size or zero.
  5991. * By default V8 starts with a small heap and dynamically grows it to
  5992. * match the set of live objects. This may lead to ineffective
  5993. * garbage collections at startup if the live set is large.
  5994. * Setting the initial heap size avoids such garbage collections.
  5995. * Note that this does not affect young generation garbage collections.
  5996. *
  5997. * \param maximum_heap_size_in_bytes The hard limit for the heap size.
  5998. * When the heap size approaches this limit, V8 will perform series of
  5999. * garbage collections and invoke the NearHeapLimitCallback. If the garbage
  6000. * collections do not help and the callback does not increase the limit,
  6001. * then V8 will crash with V8::FatalProcessOutOfMemory.
  6002. */
  6003. void ConfigureDefaultsFromHeapSize(size_t initial_heap_size_in_bytes,
  6004. size_t maximum_heap_size_in_bytes);
  6005. /**
  6006. * Configures the constraints with reasonable default values based on the
  6007. * capabilities of the current device the VM is running on.
  6008. *
  6009. * \param physical_memory The total amount of physical memory on the current
  6010. * device, in bytes.
  6011. * \param virtual_memory_limit The amount of virtual memory on the current
  6012. * device, in bytes, or zero, if there is no limit.
  6013. */
  6014. void ConfigureDefaults(uint64_t physical_memory,
  6015. uint64_t virtual_memory_limit);
  6016. /**
  6017. * The address beyond which the VM's stack may not grow.
  6018. */
  6019. uint32_t* stack_limit() const { return stack_limit_; }
  6020. void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
  6021. /**
  6022. * The amount of virtual memory reserved for generated code. This is relevant
  6023. * for 64-bit architectures that rely on code range for calls in code.
  6024. */
  6025. size_t code_range_size_in_bytes() const { return code_range_size_; }
  6026. void set_code_range_size_in_bytes(size_t limit) { code_range_size_ = limit; }
  6027. /**
  6028. * The maximum size of the old generation.
  6029. * When the old generation approaches this limit, V8 will perform series of
  6030. * garbage collections and invoke the NearHeapLimitCallback.
  6031. * If the garbage collections do not help and the callback does not
  6032. * increase the limit, then V8 will crash with V8::FatalProcessOutOfMemory.
  6033. */
  6034. size_t max_old_generation_size_in_bytes() const {
  6035. return max_old_generation_size_;
  6036. }
  6037. void set_max_old_generation_size_in_bytes(size_t limit) {
  6038. max_old_generation_size_ = limit;
  6039. }
  6040. /**
  6041. * The maximum size of the young generation, which consists of two semi-spaces
  6042. * and a large object space. This affects frequency of Scavenge garbage
  6043. * collections and should be typically much smaller that the old generation.
  6044. */
  6045. size_t max_young_generation_size_in_bytes() const {
  6046. return max_young_generation_size_;
  6047. }
  6048. void set_max_young_generation_size_in_bytes(size_t limit) {
  6049. max_young_generation_size_ = limit;
  6050. }
  6051. size_t initial_old_generation_size_in_bytes() const {
  6052. return initial_old_generation_size_;
  6053. }
  6054. void set_initial_old_generation_size_in_bytes(size_t initial_size) {
  6055. initial_old_generation_size_ = initial_size;
  6056. }
  6057. size_t initial_young_generation_size_in_bytes() const {
  6058. return initial_young_generation_size_;
  6059. }
  6060. void set_initial_young_generation_size_in_bytes(size_t initial_size) {
  6061. initial_young_generation_size_ = initial_size;
  6062. }
  6063. /**
  6064. * Deprecated functions. Do not use in new code.
  6065. */
  6066. V8_DEPRECATE_SOON("Use code_range_size_in_bytes.")
  6067. size_t code_range_size() const { return code_range_size_ / kMB; }
  6068. V8_DEPRECATE_SOON("Use set_code_range_size_in_bytes.")
  6069. void set_code_range_size(size_t limit_in_mb) {
  6070. code_range_size_ = limit_in_mb * kMB;
  6071. }
  6072. V8_DEPRECATE_SOON("Use max_young_generation_size_in_bytes.")
  6073. size_t max_semi_space_size_in_kb() const;
  6074. V8_DEPRECATE_SOON("Use set_max_young_generation_size_in_bytes.")
  6075. void set_max_semi_space_size_in_kb(size_t limit_in_kb);
  6076. V8_DEPRECATE_SOON("Use max_old_generation_size_in_bytes.")
  6077. size_t max_old_space_size() const { return max_old_generation_size_ / kMB; }
  6078. V8_DEPRECATE_SOON("Use set_max_old_generation_size_in_bytes.")
  6079. void set_max_old_space_size(size_t limit_in_mb) {
  6080. max_old_generation_size_ = limit_in_mb * kMB;
  6081. }
  6082. V8_DEPRECATE_SOON("Zone does not pool memory any more.")
  6083. size_t max_zone_pool_size() const { return max_zone_pool_size_; }
  6084. V8_DEPRECATE_SOON("Zone does not pool memory any more.")
  6085. void set_max_zone_pool_size(size_t bytes) { max_zone_pool_size_ = bytes; }
  6086. private:
  6087. static constexpr size_t kMB = 1048576u;
  6088. size_t code_range_size_ = 0;
  6089. size_t max_old_generation_size_ = 0;
  6090. size_t max_young_generation_size_ = 0;
  6091. size_t max_zone_pool_size_ = 0;
  6092. size_t initial_old_generation_size_ = 0;
  6093. size_t initial_young_generation_size_ = 0;
  6094. uint32_t* stack_limit_ = nullptr;
  6095. };
  6096. // --- Exceptions ---
  6097. typedef void (*FatalErrorCallback)(const char* location, const char* message);
  6098. typedef void (*OOMErrorCallback)(const char* location, bool is_heap_oom);
  6099. typedef void (*DcheckErrorCallback)(const char* file, int line,
  6100. const char* message);
  6101. typedef void (*MessageCallback)(Local<Message> message, Local<Value> data);
  6102. // --- Tracing ---
  6103. typedef void (*LogEventCallback)(const char* name, int event);
  6104. /**
  6105. * Create new error objects by calling the corresponding error object
  6106. * constructor with the message.
  6107. */
  6108. class V8_EXPORT Exception {
  6109. public:
  6110. static Local<Value> RangeError(Local<String> message);
  6111. static Local<Value> ReferenceError(Local<String> message);
  6112. static Local<Value> SyntaxError(Local<String> message);
  6113. static Local<Value> TypeError(Local<String> message);
  6114. static Local<Value> Error(Local<String> message);
  6115. /**
  6116. * Creates an error message for the given exception.
  6117. * Will try to reconstruct the original stack trace from the exception value,
  6118. * or capture the current stack trace if not available.
  6119. */
  6120. static Local<Message> CreateMessage(Isolate* isolate, Local<Value> exception);
  6121. /**
  6122. * Returns the original stack trace that was captured at the creation time
  6123. * of a given exception, or an empty handle if not available.
  6124. */
  6125. static Local<StackTrace> GetStackTrace(Local<Value> exception);
  6126. };
  6127. // --- Counters Callbacks ---
  6128. typedef int* (*CounterLookupCallback)(const char* name);
  6129. typedef void* (*CreateHistogramCallback)(const char* name,
  6130. int min,
  6131. int max,
  6132. size_t buckets);
  6133. typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
  6134. // --- Crashkeys Callback ---
  6135. enum class CrashKeyId {
  6136. kIsolateAddress,
  6137. kReadonlySpaceFirstPageAddress,
  6138. kMapSpaceFirstPageAddress,
  6139. kCodeSpaceFirstPageAddress,
  6140. kDumpType,
  6141. };
  6142. typedef void (*AddCrashKeyCallback)(CrashKeyId id, const std::string& value);
  6143. // --- Enter/Leave Script Callback ---
  6144. typedef void (*BeforeCallEnteredCallback)(Isolate*);
  6145. typedef void (*CallCompletedCallback)(Isolate*);
  6146. /**
  6147. * HostCleanupFinalizationGroupCallback is called when we require the
  6148. * embedder to enqueue a task that would call
  6149. * FinalizationGroup::Cleanup().
  6150. *
  6151. * The FinalizationGroup is the one for which the embedder needs to
  6152. * call FinalizationGroup::Cleanup() on.
  6153. *
  6154. * The context provided is the one in which the FinalizationGroup was
  6155. * created in.
  6156. */
  6157. typedef void (*HostCleanupFinalizationGroupCallback)(
  6158. Local<Context> context, Local<FinalizationGroup> fg);
  6159. /**
  6160. * HostImportModuleDynamicallyCallback is called when we require the
  6161. * embedder to load a module. This is used as part of the dynamic
  6162. * import syntax.
  6163. *
  6164. * The referrer contains metadata about the script/module that calls
  6165. * import.
  6166. *
  6167. * The specifier is the name of the module that should be imported.
  6168. *
  6169. * The embedder must compile, instantiate, evaluate the Module, and
  6170. * obtain it's namespace object.
  6171. *
  6172. * The Promise returned from this function is forwarded to userland
  6173. * JavaScript. The embedder must resolve this promise with the module
  6174. * namespace object. In case of an exception, the embedder must reject
  6175. * this promise with the exception. If the promise creation itself
  6176. * fails (e.g. due to stack overflow), the embedder must propagate
  6177. * that exception by returning an empty MaybeLocal.
  6178. */
  6179. typedef MaybeLocal<Promise> (*HostImportModuleDynamicallyCallback)(
  6180. Local<Context> context, Local<ScriptOrModule> referrer,
  6181. Local<String> specifier);
  6182. /**
  6183. * HostInitializeImportMetaObjectCallback is called the first time import.meta
  6184. * is accessed for a module. Subsequent access will reuse the same value.
  6185. *
  6186. * The method combines two implementation-defined abstract operations into one:
  6187. * HostGetImportMetaProperties and HostFinalizeImportMeta.
  6188. *
  6189. * The embedder should use v8::Object::CreateDataProperty to add properties on
  6190. * the meta object.
  6191. */
  6192. typedef void (*HostInitializeImportMetaObjectCallback)(Local<Context> context,
  6193. Local<Module> module,
  6194. Local<Object> meta);
  6195. /**
  6196. * PrepareStackTraceCallback is called when the stack property of an error is
  6197. * first accessed. The return value will be used as the stack value. If this
  6198. * callback is registed, the |Error.prepareStackTrace| API will be disabled.
  6199. * |sites| is an array of call sites, specified in
  6200. * https://v8.dev/docs/stack-trace-api
  6201. */
  6202. typedef MaybeLocal<Value> (*PrepareStackTraceCallback)(Local<Context> context,
  6203. Local<Value> error,
  6204. Local<Array> sites);
  6205. /**
  6206. * PromiseHook with type kInit is called when a new promise is
  6207. * created. When a new promise is created as part of the chain in the
  6208. * case of Promise.then or in the intermediate promises created by
  6209. * Promise.{race, all}/AsyncFunctionAwait, we pass the parent promise
  6210. * otherwise we pass undefined.
  6211. *
  6212. * PromiseHook with type kResolve is called at the beginning of
  6213. * resolve or reject function defined by CreateResolvingFunctions.
  6214. *
  6215. * PromiseHook with type kBefore is called at the beginning of the
  6216. * PromiseReactionJob.
  6217. *
  6218. * PromiseHook with type kAfter is called right at the end of the
  6219. * PromiseReactionJob.
  6220. */
  6221. enum class PromiseHookType { kInit, kResolve, kBefore, kAfter };
  6222. typedef void (*PromiseHook)(PromiseHookType type, Local<Promise> promise,
  6223. Local<Value> parent);
  6224. // --- Promise Reject Callback ---
  6225. enum PromiseRejectEvent {
  6226. kPromiseRejectWithNoHandler = 0,
  6227. kPromiseHandlerAddedAfterReject = 1,
  6228. kPromiseRejectAfterResolved = 2,
  6229. kPromiseResolveAfterResolved = 3,
  6230. };
  6231. class PromiseRejectMessage {
  6232. public:
  6233. PromiseRejectMessage(Local<Promise> promise, PromiseRejectEvent event,
  6234. Local<Value> value)
  6235. : promise_(promise), event_(event), value_(value) {}
  6236. V8_INLINE Local<Promise> GetPromise() const { return promise_; }
  6237. V8_INLINE PromiseRejectEvent GetEvent() const { return event_; }
  6238. V8_INLINE Local<Value> GetValue() const { return value_; }
  6239. private:
  6240. Local<Promise> promise_;
  6241. PromiseRejectEvent event_;
  6242. Local<Value> value_;
  6243. };
  6244. typedef void (*PromiseRejectCallback)(PromiseRejectMessage message);
  6245. // --- Microtasks Callbacks ---
  6246. V8_DEPRECATE_SOON("Use *WithData version.")
  6247. typedef void (*MicrotasksCompletedCallback)(Isolate*);
  6248. typedef void (*MicrotasksCompletedCallbackWithData)(Isolate*, void*);
  6249. typedef void (*MicrotaskCallback)(void* data);
  6250. /**
  6251. * Policy for running microtasks:
  6252. * - explicit: microtasks are invoked with Isolate::RunMicrotasks() method;
  6253. * - scoped: microtasks invocation is controlled by MicrotasksScope objects;
  6254. * - auto: microtasks are invoked when the script call depth decrements
  6255. * to zero.
  6256. */
  6257. enum class MicrotasksPolicy { kExplicit, kScoped, kAuto };
  6258. /**
  6259. * Represents the microtask queue, where microtasks are stored and processed.
  6260. * https://html.spec.whatwg.org/multipage/webappapis.html#microtask-queue
  6261. * https://html.spec.whatwg.org/multipage/webappapis.html#enqueuejob(queuename,-job,-arguments)
  6262. * https://html.spec.whatwg.org/multipage/webappapis.html#perform-a-microtask-checkpoint
  6263. *
  6264. * A MicrotaskQueue instance may be associated to multiple Contexts by passing
  6265. * it to Context::New(), and they can be detached by Context::DetachGlobal().
  6266. * The embedder must keep the MicrotaskQueue instance alive until all associated
  6267. * Contexts are gone or detached.
  6268. *
  6269. * Use the same instance of MicrotaskQueue for all Contexts that may access each
  6270. * other synchronously. E.g. for Web embedding, use the same instance for all
  6271. * origins that share the same URL scheme and eTLD+1.
  6272. */
  6273. class V8_EXPORT MicrotaskQueue {
  6274. public:
  6275. /**
  6276. * Creates an empty MicrotaskQueue instance.
  6277. */
  6278. static std::unique_ptr<MicrotaskQueue> New(
  6279. Isolate* isolate, MicrotasksPolicy policy = MicrotasksPolicy::kAuto);
  6280. virtual ~MicrotaskQueue() = default;
  6281. /**
  6282. * Enqueues the callback to the queue.
  6283. */
  6284. virtual void EnqueueMicrotask(Isolate* isolate,
  6285. Local<Function> microtask) = 0;
  6286. /**
  6287. * Enqueues the callback to the queue.
  6288. */
  6289. virtual void EnqueueMicrotask(v8::Isolate* isolate,
  6290. MicrotaskCallback callback,
  6291. void* data = nullptr) = 0;
  6292. /**
  6293. * Adds a callback to notify the embedder after microtasks were run. The
  6294. * callback is triggered by explicit RunMicrotasks call or automatic
  6295. * microtasks execution (see Isolate::SetMicrotasksPolicy).
  6296. *
  6297. * Callback will trigger even if microtasks were attempted to run,
  6298. * but the microtasks queue was empty and no single microtask was actually
  6299. * executed.
  6300. *
  6301. * Executing scripts inside the callback will not re-trigger microtasks and
  6302. * the callback.
  6303. */
  6304. virtual void AddMicrotasksCompletedCallback(
  6305. MicrotasksCompletedCallbackWithData callback, void* data = nullptr) = 0;
  6306. /**
  6307. * Removes callback that was installed by AddMicrotasksCompletedCallback.
  6308. */
  6309. virtual void RemoveMicrotasksCompletedCallback(
  6310. MicrotasksCompletedCallbackWithData callback, void* data = nullptr) = 0;
  6311. /**
  6312. * Runs microtasks if no microtask is running on this MicrotaskQueue instance.
  6313. */
  6314. virtual void PerformCheckpoint(Isolate* isolate) = 0;
  6315. /**
  6316. * Returns true if a microtask is running on this MicrotaskQueue instance.
  6317. */
  6318. virtual bool IsRunningMicrotasks() const = 0;
  6319. /**
  6320. * Returns the current depth of nested MicrotasksScope that has
  6321. * kRunMicrotasks.
  6322. */
  6323. virtual int GetMicrotasksScopeDepth() const = 0;
  6324. MicrotaskQueue(const MicrotaskQueue&) = delete;
  6325. MicrotaskQueue& operator=(const MicrotaskQueue&) = delete;
  6326. private:
  6327. friend class internal::MicrotaskQueue;
  6328. MicrotaskQueue() = default;
  6329. };
  6330. /**
  6331. * This scope is used to control microtasks when kScopeMicrotasksInvocation
  6332. * is used on Isolate. In this mode every non-primitive call to V8 should be
  6333. * done inside some MicrotasksScope.
  6334. * Microtasks are executed when topmost MicrotasksScope marked as kRunMicrotasks
  6335. * exits.
  6336. * kDoNotRunMicrotasks should be used to annotate calls not intended to trigger
  6337. * microtasks.
  6338. */
  6339. class V8_EXPORT MicrotasksScope {
  6340. public:
  6341. enum Type { kRunMicrotasks, kDoNotRunMicrotasks };
  6342. MicrotasksScope(Isolate* isolate, Type type);
  6343. MicrotasksScope(Isolate* isolate, MicrotaskQueue* microtask_queue, Type type);
  6344. ~MicrotasksScope();
  6345. /**
  6346. * Runs microtasks if no kRunMicrotasks scope is currently active.
  6347. */
  6348. static void PerformCheckpoint(Isolate* isolate);
  6349. /**
  6350. * Returns current depth of nested kRunMicrotasks scopes.
  6351. */
  6352. static int GetCurrentDepth(Isolate* isolate);
  6353. /**
  6354. * Returns true while microtasks are being executed.
  6355. */
  6356. static bool IsRunningMicrotasks(Isolate* isolate);
  6357. // Prevent copying.
  6358. MicrotasksScope(const MicrotasksScope&) = delete;
  6359. MicrotasksScope& operator=(const MicrotasksScope&) = delete;
  6360. private:
  6361. internal::Isolate* const isolate_;
  6362. internal::MicrotaskQueue* const microtask_queue_;
  6363. bool run_;
  6364. };
  6365. // --- Failed Access Check Callback ---
  6366. typedef void (*FailedAccessCheckCallback)(Local<Object> target,
  6367. AccessType type,
  6368. Local<Value> data);
  6369. // --- AllowCodeGenerationFromStrings callbacks ---
  6370. /**
  6371. * Callback to check if code generation from strings is allowed. See
  6372. * Context::AllowCodeGenerationFromStrings.
  6373. */
  6374. typedef bool (*AllowCodeGenerationFromStringsCallback)(Local<Context> context,
  6375. Local<String> source);
  6376. struct ModifyCodeGenerationFromStringsResult {
  6377. // If true, proceed with the codegen algorithm. Otherwise, block it.
  6378. bool codegen_allowed = false;
  6379. // Overwrite the original source with this string, if present.
  6380. // Use the original source if empty.
  6381. // This field is considered only if codegen_allowed is true.
  6382. MaybeLocal<String> modified_source;
  6383. };
  6384. /**
  6385. * Callback to check if codegen is allowed from a source object, and convert
  6386. * the source to string if necessary.See ModifyCodeGenerationFromStrings.
  6387. */
  6388. typedef ModifyCodeGenerationFromStringsResult (
  6389. *ModifyCodeGenerationFromStringsCallback)(Local<Context> context,
  6390. Local<Value> source);
  6391. // --- WebAssembly compilation callbacks ---
  6392. typedef bool (*ExtensionCallback)(const FunctionCallbackInfo<Value>&);
  6393. typedef bool (*AllowWasmCodeGenerationCallback)(Local<Context> context,
  6394. Local<String> source);
  6395. // --- Callback for APIs defined on v8-supported objects, but implemented
  6396. // by the embedder. Example: WebAssembly.{compile|instantiate}Streaming ---
  6397. typedef void (*ApiImplementationCallback)(const FunctionCallbackInfo<Value>&);
  6398. // --- Callback for WebAssembly.compileStreaming ---
  6399. typedef void (*WasmStreamingCallback)(const FunctionCallbackInfo<Value>&);
  6400. // --- Callback for checking if WebAssembly threads are enabled ---
  6401. typedef bool (*WasmThreadsEnabledCallback)(Local<Context> context);
  6402. // --- Callback for loading source map file for WASM profiling support
  6403. typedef Local<String> (*WasmLoadSourceMapCallback)(Isolate* isolate,
  6404. const char* name);
  6405. // --- Garbage Collection Callbacks ---
  6406. /**
  6407. * Applications can register callback functions which will be called before and
  6408. * after certain garbage collection operations. Allocations are not allowed in
  6409. * the callback functions, you therefore cannot manipulate objects (set or
  6410. * delete properties for example) since it is possible such operations will
  6411. * result in the allocation of objects.
  6412. */
  6413. enum GCType {
  6414. kGCTypeScavenge = 1 << 0,
  6415. kGCTypeMarkSweepCompact = 1 << 1,
  6416. kGCTypeIncrementalMarking = 1 << 2,
  6417. kGCTypeProcessWeakCallbacks = 1 << 3,
  6418. kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact |
  6419. kGCTypeIncrementalMarking | kGCTypeProcessWeakCallbacks
  6420. };
  6421. /**
  6422. * GCCallbackFlags is used to notify additional information about the GC
  6423. * callback.
  6424. * - kGCCallbackFlagConstructRetainedObjectInfos: The GC callback is for
  6425. * constructing retained object infos.
  6426. * - kGCCallbackFlagForced: The GC callback is for a forced GC for testing.
  6427. * - kGCCallbackFlagSynchronousPhantomCallbackProcessing: The GC callback
  6428. * is called synchronously without getting posted to an idle task.
  6429. * - kGCCallbackFlagCollectAllAvailableGarbage: The GC callback is called
  6430. * in a phase where V8 is trying to collect all available garbage
  6431. * (e.g., handling a low memory notification).
  6432. * - kGCCallbackScheduleIdleGarbageCollection: The GC callback is called to
  6433. * trigger an idle garbage collection.
  6434. */
  6435. enum GCCallbackFlags {
  6436. kNoGCCallbackFlags = 0,
  6437. kGCCallbackFlagConstructRetainedObjectInfos = 1 << 1,
  6438. kGCCallbackFlagForced = 1 << 2,
  6439. kGCCallbackFlagSynchronousPhantomCallbackProcessing = 1 << 3,
  6440. kGCCallbackFlagCollectAllAvailableGarbage = 1 << 4,
  6441. kGCCallbackFlagCollectAllExternalMemory = 1 << 5,
  6442. kGCCallbackScheduleIdleGarbageCollection = 1 << 6,
  6443. };
  6444. typedef void (*GCCallback)(GCType type, GCCallbackFlags flags);
  6445. typedef void (*InterruptCallback)(Isolate* isolate, void* data);
  6446. /**
  6447. * This callback is invoked when the heap size is close to the heap limit and
  6448. * V8 is likely to abort with out-of-memory error.
  6449. * The callback can extend the heap limit by returning a value that is greater
  6450. * than the current_heap_limit. The initial heap limit is the limit that was
  6451. * set after heap setup.
  6452. */
  6453. typedef size_t (*NearHeapLimitCallback)(void* data, size_t current_heap_limit,
  6454. size_t initial_heap_limit);
  6455. /**
  6456. * Collection of shared per-process V8 memory information.
  6457. *
  6458. * Instances of this class can be passed to
  6459. * v8::V8::GetSharedMemoryStatistics to get shared memory statistics from V8.
  6460. */
  6461. class V8_EXPORT SharedMemoryStatistics {
  6462. public:
  6463. SharedMemoryStatistics();
  6464. size_t read_only_space_size() { return read_only_space_size_; }
  6465. size_t read_only_space_used_size() { return read_only_space_used_size_; }
  6466. size_t read_only_space_physical_size() {
  6467. return read_only_space_physical_size_;
  6468. }
  6469. private:
  6470. size_t read_only_space_size_;
  6471. size_t read_only_space_used_size_;
  6472. size_t read_only_space_physical_size_;
  6473. friend class V8;
  6474. };
  6475. /**
  6476. * Collection of V8 heap information.
  6477. *
  6478. * Instances of this class can be passed to v8::Isolate::GetHeapStatistics to
  6479. * get heap statistics from V8.
  6480. */
  6481. class V8_EXPORT HeapStatistics {
  6482. public:
  6483. HeapStatistics();
  6484. size_t total_heap_size() { return total_heap_size_; }
  6485. size_t total_heap_size_executable() { return total_heap_size_executable_; }
  6486. size_t total_physical_size() { return total_physical_size_; }
  6487. size_t total_available_size() { return total_available_size_; }
  6488. size_t used_heap_size() { return used_heap_size_; }
  6489. size_t heap_size_limit() { return heap_size_limit_; }
  6490. size_t malloced_memory() { return malloced_memory_; }
  6491. size_t external_memory() { return external_memory_; }
  6492. size_t peak_malloced_memory() { return peak_malloced_memory_; }
  6493. size_t number_of_native_contexts() { return number_of_native_contexts_; }
  6494. size_t number_of_detached_contexts() { return number_of_detached_contexts_; }
  6495. /**
  6496. * Returns a 0/1 boolean, which signifies whether the V8 overwrite heap
  6497. * garbage with a bit pattern.
  6498. */
  6499. size_t does_zap_garbage() { return does_zap_garbage_; }
  6500. private:
  6501. size_t total_heap_size_;
  6502. size_t total_heap_size_executable_;
  6503. size_t total_physical_size_;
  6504. size_t total_available_size_;
  6505. size_t used_heap_size_;
  6506. size_t heap_size_limit_;
  6507. size_t malloced_memory_;
  6508. size_t external_memory_;
  6509. size_t peak_malloced_memory_;
  6510. bool does_zap_garbage_;
  6511. size_t number_of_native_contexts_;
  6512. size_t number_of_detached_contexts_;
  6513. friend class V8;
  6514. friend class Isolate;
  6515. };
  6516. class V8_EXPORT HeapSpaceStatistics {
  6517. public:
  6518. HeapSpaceStatistics();
  6519. const char* space_name() { return space_name_; }
  6520. size_t space_size() { return space_size_; }
  6521. size_t space_used_size() { return space_used_size_; }
  6522. size_t space_available_size() { return space_available_size_; }
  6523. size_t physical_space_size() { return physical_space_size_; }
  6524. private:
  6525. const char* space_name_;
  6526. size_t space_size_;
  6527. size_t space_used_size_;
  6528. size_t space_available_size_;
  6529. size_t physical_space_size_;
  6530. friend class Isolate;
  6531. };
  6532. class V8_EXPORT HeapObjectStatistics {
  6533. public:
  6534. HeapObjectStatistics();
  6535. const char* object_type() { return object_type_; }
  6536. const char* object_sub_type() { return object_sub_type_; }
  6537. size_t object_count() { return object_count_; }
  6538. size_t object_size() { return object_size_; }
  6539. private:
  6540. const char* object_type_;
  6541. const char* object_sub_type_;
  6542. size_t object_count_;
  6543. size_t object_size_;
  6544. friend class Isolate;
  6545. };
  6546. class V8_EXPORT HeapCodeStatistics {
  6547. public:
  6548. HeapCodeStatistics();
  6549. size_t code_and_metadata_size() { return code_and_metadata_size_; }
  6550. size_t bytecode_and_metadata_size() { return bytecode_and_metadata_size_; }
  6551. size_t external_script_source_size() { return external_script_source_size_; }
  6552. private:
  6553. size_t code_and_metadata_size_;
  6554. size_t bytecode_and_metadata_size_;
  6555. size_t external_script_source_size_;
  6556. friend class Isolate;
  6557. };
  6558. /**
  6559. * A JIT code event is issued each time code is added, moved or removed.
  6560. *
  6561. * \note removal events are not currently issued.
  6562. */
  6563. struct JitCodeEvent {
  6564. enum EventType {
  6565. CODE_ADDED,
  6566. CODE_MOVED,
  6567. CODE_REMOVED,
  6568. CODE_ADD_LINE_POS_INFO,
  6569. CODE_START_LINE_INFO_RECORDING,
  6570. CODE_END_LINE_INFO_RECORDING
  6571. };
  6572. // Definition of the code position type. The "POSITION" type means the place
  6573. // in the source code which are of interest when making stack traces to
  6574. // pin-point the source location of a stack frame as close as possible.
  6575. // The "STATEMENT_POSITION" means the place at the beginning of each
  6576. // statement, and is used to indicate possible break locations.
  6577. enum PositionType { POSITION, STATEMENT_POSITION };
  6578. // There are two different kinds of JitCodeEvents, one for JIT code generated
  6579. // by the optimizing compiler, and one for byte code generated for the
  6580. // interpreter. For JIT_CODE events, the |code_start| member of the event
  6581. // points to the beginning of jitted assembly code, while for BYTE_CODE
  6582. // events, |code_start| points to the first bytecode of the interpreted
  6583. // function.
  6584. enum CodeType { BYTE_CODE, JIT_CODE };
  6585. // Type of event.
  6586. EventType type;
  6587. CodeType code_type;
  6588. // Start of the instructions.
  6589. void* code_start;
  6590. // Size of the instructions.
  6591. size_t code_len;
  6592. // Script info for CODE_ADDED event.
  6593. Local<UnboundScript> script;
  6594. // User-defined data for *_LINE_INFO_* event. It's used to hold the source
  6595. // code line information which is returned from the
  6596. // CODE_START_LINE_INFO_RECORDING event. And it's passed to subsequent
  6597. // CODE_ADD_LINE_POS_INFO and CODE_END_LINE_INFO_RECORDING events.
  6598. void* user_data;
  6599. struct name_t {
  6600. // Name of the object associated with the code, note that the string is not
  6601. // zero-terminated.
  6602. const char* str;
  6603. // Number of chars in str.
  6604. size_t len;
  6605. };
  6606. struct line_info_t {
  6607. // PC offset
  6608. size_t offset;
  6609. // Code position
  6610. size_t pos;
  6611. // The position type.
  6612. PositionType position_type;
  6613. };
  6614. struct wasm_source_info_t {
  6615. // Source file name.
  6616. const char* filename;
  6617. // Length of filename.
  6618. size_t filename_size;
  6619. // Line number table, which maps offsets of JITted code to line numbers of
  6620. // source file.
  6621. const line_info_t* line_number_table;
  6622. // Number of entries in the line number table.
  6623. size_t line_number_table_size;
  6624. };
  6625. wasm_source_info_t* wasm_source_info;
  6626. union {
  6627. // Only valid for CODE_ADDED.
  6628. struct name_t name;
  6629. // Only valid for CODE_ADD_LINE_POS_INFO
  6630. struct line_info_t line_info;
  6631. // New location of instructions. Only valid for CODE_MOVED.
  6632. void* new_code_start;
  6633. };
  6634. Isolate* isolate;
  6635. };
  6636. /**
  6637. * Option flags passed to the SetRAILMode function.
  6638. * See documentation https://developers.google.com/web/tools/chrome-devtools/
  6639. * profile/evaluate-performance/rail
  6640. */
  6641. enum RAILMode : unsigned {
  6642. // Response performance mode: In this mode very low virtual machine latency
  6643. // is provided. V8 will try to avoid JavaScript execution interruptions.
  6644. // Throughput may be throttled.
  6645. PERFORMANCE_RESPONSE,
  6646. // Animation performance mode: In this mode low virtual machine latency is
  6647. // provided. V8 will try to avoid as many JavaScript execution interruptions
  6648. // as possible. Throughput may be throttled. This is the default mode.
  6649. PERFORMANCE_ANIMATION,
  6650. // Idle performance mode: The embedder is idle. V8 can complete deferred work
  6651. // in this mode.
  6652. PERFORMANCE_IDLE,
  6653. // Load performance mode: In this mode high throughput is provided. V8 may
  6654. // turn off latency optimizations.
  6655. PERFORMANCE_LOAD
  6656. };
  6657. /**
  6658. * Option flags passed to the SetJitCodeEventHandler function.
  6659. */
  6660. enum JitCodeEventOptions {
  6661. kJitCodeEventDefault = 0,
  6662. // Generate callbacks for already existent code.
  6663. kJitCodeEventEnumExisting = 1
  6664. };
  6665. /**
  6666. * Callback function passed to SetJitCodeEventHandler.
  6667. *
  6668. * \param event code add, move or removal event.
  6669. */
  6670. typedef void (*JitCodeEventHandler)(const JitCodeEvent* event);
  6671. /**
  6672. * Callback function passed to SetUnhandledExceptionCallback.
  6673. */
  6674. #if defined(V8_OS_WIN)
  6675. typedef int (*UnhandledExceptionCallback)(
  6676. _EXCEPTION_POINTERS* exception_pointers);
  6677. #endif
  6678. /**
  6679. * Interface for iterating through all external resources in the heap.
  6680. */
  6681. class V8_EXPORT ExternalResourceVisitor { // NOLINT
  6682. public:
  6683. virtual ~ExternalResourceVisitor() = default;
  6684. virtual void VisitExternalString(Local<String> string) {}
  6685. };
  6686. /**
  6687. * Interface for iterating through all the persistent handles in the heap.
  6688. */
  6689. class V8_EXPORT PersistentHandleVisitor { // NOLINT
  6690. public:
  6691. virtual ~PersistentHandleVisitor() = default;
  6692. virtual void VisitPersistentHandle(Persistent<Value>* value,
  6693. uint16_t class_id) {}
  6694. };
  6695. /**
  6696. * Memory pressure level for the MemoryPressureNotification.
  6697. * kNone hints V8 that there is no memory pressure.
  6698. * kModerate hints V8 to speed up incremental garbage collection at the cost of
  6699. * of higher latency due to garbage collection pauses.
  6700. * kCritical hints V8 to free memory as soon as possible. Garbage collection
  6701. * pauses at this level will be large.
  6702. */
  6703. enum class MemoryPressureLevel { kNone, kModerate, kCritical };
  6704. /**
  6705. * Interface for tracing through the embedder heap. During a V8 garbage
  6706. * collection, V8 collects hidden fields of all potential wrappers, and at the
  6707. * end of its marking phase iterates the collection and asks the embedder to
  6708. * trace through its heap and use reporter to report each JavaScript object
  6709. * reachable from any of the given wrappers.
  6710. */
  6711. class V8_EXPORT EmbedderHeapTracer {
  6712. public:
  6713. enum TraceFlags : uint64_t {
  6714. kNoFlags = 0,
  6715. kReduceMemory = 1 << 0,
  6716. };
  6717. // Indicator for the stack state of the embedder.
  6718. enum EmbedderStackState {
  6719. kUnknown,
  6720. kNonEmpty,
  6721. kEmpty,
  6722. };
  6723. /**
  6724. * Interface for iterating through TracedGlobal handles.
  6725. */
  6726. class V8_EXPORT TracedGlobalHandleVisitor {
  6727. public:
  6728. virtual ~TracedGlobalHandleVisitor() = default;
  6729. virtual void VisitTracedGlobalHandle(const TracedGlobal<Value>& handle) {}
  6730. virtual void VisitTracedReference(const TracedReference<Value>& handle) {}
  6731. };
  6732. /**
  6733. * Summary of a garbage collection cycle. See |TraceEpilogue| on how the
  6734. * summary is reported.
  6735. */
  6736. struct TraceSummary {
  6737. /**
  6738. * Time spent managing the retained memory in milliseconds. This can e.g.
  6739. * include the time tracing through objects in the embedder.
  6740. */
  6741. double time = 0.0;
  6742. /**
  6743. * Memory retained by the embedder through the |EmbedderHeapTracer|
  6744. * mechanism in bytes.
  6745. */
  6746. size_t allocated_size = 0;
  6747. };
  6748. virtual ~EmbedderHeapTracer() = default;
  6749. /**
  6750. * Iterates all TracedGlobal handles created for the v8::Isolate the tracer is
  6751. * attached to.
  6752. */
  6753. void IterateTracedGlobalHandles(TracedGlobalHandleVisitor* visitor);
  6754. /**
  6755. * Called by v8 to register internal fields of found wrappers.
  6756. *
  6757. * The embedder is expected to store them somewhere and trace reachable
  6758. * wrappers from them when called through |AdvanceTracing|.
  6759. */
  6760. virtual void RegisterV8References(
  6761. const std::vector<std::pair<void*, void*> >& embedder_fields) = 0;
  6762. V8_DEPRECATED("Use version taking TracedReferenceBase<v8::Data> argument")
  6763. void RegisterEmbedderReference(const TracedReferenceBase<v8::Value>& ref);
  6764. void RegisterEmbedderReference(const TracedReferenceBase<v8::Data>& ref);
  6765. /**
  6766. * Called at the beginning of a GC cycle.
  6767. */
  6768. virtual void TracePrologue(TraceFlags flags) {}
  6769. /**
  6770. * Called to advance tracing in the embedder.
  6771. *
  6772. * The embedder is expected to trace its heap starting from wrappers reported
  6773. * by RegisterV8References method, and report back all reachable wrappers.
  6774. * Furthermore, the embedder is expected to stop tracing by the given
  6775. * deadline. A deadline of infinity means that tracing should be finished.
  6776. *
  6777. * Returns |true| if tracing is done, and false otherwise.
  6778. */
  6779. virtual bool AdvanceTracing(double deadline_in_ms) = 0;
  6780. /*
  6781. * Returns true if there no more tracing work to be done (see AdvanceTracing)
  6782. * and false otherwise.
  6783. */
  6784. virtual bool IsTracingDone() = 0;
  6785. /**
  6786. * Called at the end of a GC cycle.
  6787. *
  6788. * Note that allocation is *not* allowed within |TraceEpilogue|. Can be
  6789. * overriden to fill a |TraceSummary| that is used by V8 to schedule future
  6790. * garbage collections.
  6791. */
  6792. virtual void TraceEpilogue(TraceSummary* trace_summary) {}
  6793. /**
  6794. * Called upon entering the final marking pause. No more incremental marking
  6795. * steps will follow this call.
  6796. */
  6797. virtual void EnterFinalPause(EmbedderStackState stack_state) = 0;
  6798. /*
  6799. * Called by the embedder to request immediate finalization of the currently
  6800. * running tracing phase that has been started with TracePrologue and not
  6801. * yet finished with TraceEpilogue.
  6802. *
  6803. * Will be a noop when currently not in tracing.
  6804. *
  6805. * This is an experimental feature.
  6806. */
  6807. void FinalizeTracing();
  6808. /**
  6809. * Returns true if the TracedGlobal handle should be considered as root for
  6810. * the currently running non-tracing garbage collection and false otherwise.
  6811. * The default implementation will keep all TracedGlobal references as roots.
  6812. *
  6813. * If this returns false, then V8 may decide that the object referred to by
  6814. * such a handle is reclaimed. In that case:
  6815. * - No action is required if handles are used with destructors, i.e., by just
  6816. * using |TracedGlobal|.
  6817. * - When run without destructors, i.e., by using
  6818. * |TracedReference|, V8 calls |ResetHandleInNonTracingGC|.
  6819. *
  6820. * Note that the |handle| is different from the handle that the embedder holds
  6821. * for retaining the object. The embedder may use |WrapperClassId()| to
  6822. * distinguish cases where it wants handles to be treated as roots from not
  6823. * being treated as roots.
  6824. */
  6825. virtual bool IsRootForNonTracingGC(
  6826. const v8::TracedReference<v8::Value>& handle);
  6827. virtual bool IsRootForNonTracingGC(const v8::TracedGlobal<v8::Value>& handle);
  6828. /**
  6829. * Used in combination with |IsRootForNonTracingGC|. Called by V8 when an
  6830. * object that is backed by a handle is reclaimed by a non-tracing garbage
  6831. * collection. It is up to the embedder to reset the original handle.
  6832. *
  6833. * Note that the |handle| is different from the handle that the embedder holds
  6834. * for retaining the object. It is up to the embedder to find the original
  6835. * handle via the object or class id.
  6836. */
  6837. virtual void ResetHandleInNonTracingGC(
  6838. const v8::TracedReference<v8::Value>& handle);
  6839. V8_DEPRECATED("Use TracedReference version when not requiring destructors.")
  6840. virtual void ResetHandleInNonTracingGC(
  6841. const v8::TracedGlobal<v8::Value>& handle);
  6842. /*
  6843. * Called by the embedder to immediately perform a full garbage collection.
  6844. *
  6845. * Should only be used in testing code.
  6846. */
  6847. void GarbageCollectionForTesting(EmbedderStackState stack_state);
  6848. /*
  6849. * Called by the embedder to signal newly allocated or freed memory. Not bound
  6850. * to tracing phases. Embedders should trade off when increments are reported
  6851. * as V8 may consult global heuristics on whether to trigger garbage
  6852. * collection on this change.
  6853. */
  6854. void IncreaseAllocatedSize(size_t bytes);
  6855. void DecreaseAllocatedSize(size_t bytes);
  6856. /*
  6857. * Returns the v8::Isolate this tracer is attached too and |nullptr| if it
  6858. * is not attached to any v8::Isolate.
  6859. */
  6860. v8::Isolate* isolate() const { return isolate_; }
  6861. protected:
  6862. v8::Isolate* isolate_ = nullptr;
  6863. friend class internal::LocalEmbedderHeapTracer;
  6864. };
  6865. /**
  6866. * Callback and supporting data used in SnapshotCreator to implement embedder
  6867. * logic to serialize internal fields.
  6868. * Internal fields that directly reference V8 objects are serialized without
  6869. * calling this callback. Internal fields that contain aligned pointers are
  6870. * serialized by this callback if it returns non-zero result. Otherwise it is
  6871. * serialized verbatim.
  6872. */
  6873. struct SerializeInternalFieldsCallback {
  6874. typedef StartupData (*CallbackFunction)(Local<Object> holder, int index,
  6875. void* data);
  6876. SerializeInternalFieldsCallback(CallbackFunction function = nullptr,
  6877. void* data_arg = nullptr)
  6878. : callback(function), data(data_arg) {}
  6879. CallbackFunction callback;
  6880. void* data;
  6881. };
  6882. // Note that these fields are called "internal fields" in the API and called
  6883. // "embedder fields" within V8.
  6884. typedef SerializeInternalFieldsCallback SerializeEmbedderFieldsCallback;
  6885. /**
  6886. * Callback and supporting data used to implement embedder logic to deserialize
  6887. * internal fields.
  6888. */
  6889. struct DeserializeInternalFieldsCallback {
  6890. typedef void (*CallbackFunction)(Local<Object> holder, int index,
  6891. StartupData payload, void* data);
  6892. DeserializeInternalFieldsCallback(CallbackFunction function = nullptr,
  6893. void* data_arg = nullptr)
  6894. : callback(function), data(data_arg) {}
  6895. void (*callback)(Local<Object> holder, int index, StartupData payload,
  6896. void* data);
  6897. void* data;
  6898. };
  6899. typedef DeserializeInternalFieldsCallback DeserializeEmbedderFieldsCallback;
  6900. enum class MeasureMemoryMode { kSummary, kDetailed };
  6901. /**
  6902. * Isolate represents an isolated instance of the V8 engine. V8 isolates have
  6903. * completely separate states. Objects from one isolate must not be used in
  6904. * other isolates. The embedder can create multiple isolates and use them in
  6905. * parallel in multiple threads. An isolate can be entered by at most one
  6906. * thread at any given time. The Locker/Unlocker API must be used to
  6907. * synchronize.
  6908. */
  6909. class V8_EXPORT Isolate {
  6910. public:
  6911. /**
  6912. * Initial configuration parameters for a new Isolate.
  6913. */
  6914. struct CreateParams {
  6915. CreateParams()
  6916. : code_event_handler(nullptr),
  6917. snapshot_blob(nullptr),
  6918. counter_lookup_callback(nullptr),
  6919. create_histogram_callback(nullptr),
  6920. add_histogram_sample_callback(nullptr),
  6921. array_buffer_allocator(nullptr),
  6922. array_buffer_allocator_shared(),
  6923. external_references(nullptr),
  6924. allow_atomics_wait(true),
  6925. only_terminate_in_safe_scope(false) {}
  6926. /**
  6927. * Allows the host application to provide the address of a function that is
  6928. * notified each time code is added, moved or removed.
  6929. */
  6930. JitCodeEventHandler code_event_handler;
  6931. /**
  6932. * ResourceConstraints to use for the new Isolate.
  6933. */
  6934. ResourceConstraints constraints;
  6935. /**
  6936. * Explicitly specify a startup snapshot blob. The embedder owns the blob.
  6937. */
  6938. StartupData* snapshot_blob;
  6939. /**
  6940. * Enables the host application to provide a mechanism for recording
  6941. * statistics counters.
  6942. */
  6943. CounterLookupCallback counter_lookup_callback;
  6944. /**
  6945. * Enables the host application to provide a mechanism for recording
  6946. * histograms. The CreateHistogram function returns a
  6947. * histogram which will later be passed to the AddHistogramSample
  6948. * function.
  6949. */
  6950. CreateHistogramCallback create_histogram_callback;
  6951. AddHistogramSampleCallback add_histogram_sample_callback;
  6952. /**
  6953. * The ArrayBuffer::Allocator to use for allocating and freeing the backing
  6954. * store of ArrayBuffers.
  6955. *
  6956. * If the shared_ptr version is used, the Isolate instance and every
  6957. * |BackingStore| allocated using this allocator hold a std::shared_ptr
  6958. * to the allocator, in order to facilitate lifetime
  6959. * management for the allocator instance.
  6960. */
  6961. ArrayBuffer::Allocator* array_buffer_allocator;
  6962. std::shared_ptr<ArrayBuffer::Allocator> array_buffer_allocator_shared;
  6963. /**
  6964. * Specifies an optional nullptr-terminated array of raw addresses in the
  6965. * embedder that V8 can match against during serialization and use for
  6966. * deserialization. This array and its content must stay valid for the
  6967. * entire lifetime of the isolate.
  6968. */
  6969. const intptr_t* external_references;
  6970. /**
  6971. * Whether calling Atomics.wait (a function that may block) is allowed in
  6972. * this isolate. This can also be configured via SetAllowAtomicsWait.
  6973. */
  6974. bool allow_atomics_wait;
  6975. /**
  6976. * Termination is postponed when there is no active SafeForTerminationScope.
  6977. */
  6978. bool only_terminate_in_safe_scope;
  6979. };
  6980. /**
  6981. * Stack-allocated class which sets the isolate for all operations
  6982. * executed within a local scope.
  6983. */
  6984. class V8_EXPORT Scope {
  6985. public:
  6986. explicit Scope(Isolate* isolate) : isolate_(isolate) {
  6987. isolate->Enter();
  6988. }
  6989. ~Scope() { isolate_->Exit(); }
  6990. // Prevent copying of Scope objects.
  6991. Scope(const Scope&) = delete;
  6992. Scope& operator=(const Scope&) = delete;
  6993. private:
  6994. Isolate* const isolate_;
  6995. };
  6996. /**
  6997. * Assert that no Javascript code is invoked.
  6998. */
  6999. class V8_EXPORT DisallowJavascriptExecutionScope {
  7000. public:
  7001. enum OnFailure { CRASH_ON_FAILURE, THROW_ON_FAILURE, DUMP_ON_FAILURE };
  7002. DisallowJavascriptExecutionScope(Isolate* isolate, OnFailure on_failure);
  7003. ~DisallowJavascriptExecutionScope();
  7004. // Prevent copying of Scope objects.
  7005. DisallowJavascriptExecutionScope(const DisallowJavascriptExecutionScope&) =
  7006. delete;
  7007. DisallowJavascriptExecutionScope& operator=(
  7008. const DisallowJavascriptExecutionScope&) = delete;
  7009. private:
  7010. OnFailure on_failure_;
  7011. void* internal_;
  7012. };
  7013. /**
  7014. * Introduce exception to DisallowJavascriptExecutionScope.
  7015. */
  7016. class V8_EXPORT AllowJavascriptExecutionScope {
  7017. public:
  7018. explicit AllowJavascriptExecutionScope(Isolate* isolate);
  7019. ~AllowJavascriptExecutionScope();
  7020. // Prevent copying of Scope objects.
  7021. AllowJavascriptExecutionScope(const AllowJavascriptExecutionScope&) =
  7022. delete;
  7023. AllowJavascriptExecutionScope& operator=(
  7024. const AllowJavascriptExecutionScope&) = delete;
  7025. private:
  7026. void* internal_throws_;
  7027. void* internal_assert_;
  7028. void* internal_dump_;
  7029. };
  7030. /**
  7031. * Do not run microtasks while this scope is active, even if microtasks are
  7032. * automatically executed otherwise.
  7033. */
  7034. class V8_EXPORT SuppressMicrotaskExecutionScope {
  7035. public:
  7036. explicit SuppressMicrotaskExecutionScope(
  7037. Isolate* isolate, MicrotaskQueue* microtask_queue = nullptr);
  7038. ~SuppressMicrotaskExecutionScope();
  7039. // Prevent copying of Scope objects.
  7040. SuppressMicrotaskExecutionScope(const SuppressMicrotaskExecutionScope&) =
  7041. delete;
  7042. SuppressMicrotaskExecutionScope& operator=(
  7043. const SuppressMicrotaskExecutionScope&) = delete;
  7044. private:
  7045. internal::Isolate* const isolate_;
  7046. internal::MicrotaskQueue* const microtask_queue_;
  7047. internal::Address previous_stack_height_;
  7048. friend class internal::ThreadLocalTop;
  7049. };
  7050. /**
  7051. * This scope allows terminations inside direct V8 API calls and forbid them
  7052. * inside any recursice API calls without explicit SafeForTerminationScope.
  7053. */
  7054. class V8_EXPORT SafeForTerminationScope {
  7055. public:
  7056. explicit SafeForTerminationScope(v8::Isolate* isolate);
  7057. ~SafeForTerminationScope();
  7058. // Prevent copying of Scope objects.
  7059. SafeForTerminationScope(const SafeForTerminationScope&) = delete;
  7060. SafeForTerminationScope& operator=(const SafeForTerminationScope&) = delete;
  7061. private:
  7062. internal::Isolate* isolate_;
  7063. bool prev_value_;
  7064. };
  7065. /**
  7066. * Types of garbage collections that can be requested via
  7067. * RequestGarbageCollectionForTesting.
  7068. */
  7069. enum GarbageCollectionType {
  7070. kFullGarbageCollection,
  7071. kMinorGarbageCollection
  7072. };
  7073. /**
  7074. * Features reported via the SetUseCounterCallback callback. Do not change
  7075. * assigned numbers of existing items; add new features to the end of this
  7076. * list.
  7077. */
  7078. enum UseCounterFeature {
  7079. kUseAsm = 0,
  7080. kBreakIterator = 1,
  7081. kLegacyConst = 2,
  7082. kMarkDequeOverflow = 3,
  7083. kStoreBufferOverflow = 4,
  7084. kSlotsBufferOverflow = 5,
  7085. kObjectObserve = 6,
  7086. kForcedGC = 7,
  7087. kSloppyMode = 8,
  7088. kStrictMode = 9,
  7089. kStrongMode = 10,
  7090. kRegExpPrototypeStickyGetter = 11,
  7091. kRegExpPrototypeToString = 12,
  7092. kRegExpPrototypeUnicodeGetter = 13,
  7093. kIntlV8Parse = 14,
  7094. kIntlPattern = 15,
  7095. kIntlResolved = 16,
  7096. kPromiseChain = 17,
  7097. kPromiseAccept = 18,
  7098. kPromiseDefer = 19,
  7099. kHtmlCommentInExternalScript = 20,
  7100. kHtmlComment = 21,
  7101. kSloppyModeBlockScopedFunctionRedefinition = 22,
  7102. kForInInitializer = 23,
  7103. kArrayProtectorDirtied = 24,
  7104. kArraySpeciesModified = 25,
  7105. kArrayPrototypeConstructorModified = 26,
  7106. kArrayInstanceProtoModified = 27,
  7107. kArrayInstanceConstructorModified = 28,
  7108. kLegacyFunctionDeclaration = 29,
  7109. kRegExpPrototypeSourceGetter = 30,
  7110. kRegExpPrototypeOldFlagGetter = 31,
  7111. kDecimalWithLeadingZeroInStrictMode = 32,
  7112. kLegacyDateParser = 33,
  7113. kDefineGetterOrSetterWouldThrow = 34,
  7114. kFunctionConstructorReturnedUndefined = 35,
  7115. kAssigmentExpressionLHSIsCallInSloppy = 36,
  7116. kAssigmentExpressionLHSIsCallInStrict = 37,
  7117. kPromiseConstructorReturnedUndefined = 38,
  7118. kConstructorNonUndefinedPrimitiveReturn = 39,
  7119. kLabeledExpressionStatement = 40,
  7120. kLineOrParagraphSeparatorAsLineTerminator = 41,
  7121. kIndexAccessor = 42,
  7122. kErrorCaptureStackTrace = 43,
  7123. kErrorPrepareStackTrace = 44,
  7124. kErrorStackTraceLimit = 45,
  7125. kWebAssemblyInstantiation = 46,
  7126. kDeoptimizerDisableSpeculation = 47,
  7127. kArrayPrototypeSortJSArrayModifiedPrototype = 48,
  7128. kFunctionTokenOffsetTooLongForToString = 49,
  7129. kWasmSharedMemory = 50,
  7130. kWasmThreadOpcodes = 51,
  7131. kAtomicsNotify = 52,
  7132. kAtomicsWake = 53,
  7133. kCollator = 54,
  7134. kNumberFormat = 55,
  7135. kDateTimeFormat = 56,
  7136. kPluralRules = 57,
  7137. kRelativeTimeFormat = 58,
  7138. kLocale = 59,
  7139. kListFormat = 60,
  7140. kSegmenter = 61,
  7141. kStringLocaleCompare = 62,
  7142. kStringToLocaleUpperCase = 63,
  7143. kStringToLocaleLowerCase = 64,
  7144. kNumberToLocaleString = 65,
  7145. kDateToLocaleString = 66,
  7146. kDateToLocaleDateString = 67,
  7147. kDateToLocaleTimeString = 68,
  7148. kAttemptOverrideReadOnlyOnPrototypeSloppy = 69,
  7149. kAttemptOverrideReadOnlyOnPrototypeStrict = 70,
  7150. kOptimizedFunctionWithOneShotBytecode = 71,
  7151. kRegExpMatchIsTrueishOnNonJSRegExp = 72,
  7152. kRegExpMatchIsFalseishOnJSRegExp = 73,
  7153. kDateGetTimezoneOffset = 74,
  7154. kStringNormalize = 75,
  7155. kCallSiteAPIGetFunctionSloppyCall = 76,
  7156. kCallSiteAPIGetThisSloppyCall = 77,
  7157. kRegExpMatchAllWithNonGlobalRegExp = 78,
  7158. kRegExpExecCalledOnSlowRegExp = 79,
  7159. kRegExpReplaceCalledOnSlowRegExp = 80,
  7160. kDisplayNames = 81,
  7161. kSharedArrayBufferConstructed = 82,
  7162. // Temporary kCallInDetachedWindowBy* counters are for reporting function
  7163. // calls within contexts marked using |SetDetachedWindowReason|.
  7164. // TODO(bartekn,chromium:1018156): Remove once not needed.
  7165. kCallInDetachedWindowByNavigation = 83,
  7166. kCallInDetachedWindowByNavigationAfter10s = 84,
  7167. kCallInDetachedWindowByNavigationAfter1min = 85,
  7168. kCallInDetachedWindowByClosing = 86,
  7169. kCallInDetachedWindowByClosingAfter10s = 87,
  7170. kCallInDetachedWindowByClosingAfter1min = 88,
  7171. kCallInDetachedWindowByOtherReason = 89,
  7172. kCallInDetachedWindowByOtherReasonAfter10s = 90,
  7173. kCallInDetachedWindowByOtherReasonAfter1min = 91,
  7174. // If you add new values here, you'll also need to update Chromium's:
  7175. // web_feature.mojom, use_counter_callback.cc, and enums.xml. V8 changes to
  7176. // this list need to be landed first, then changes on the Chromium side.
  7177. kUseCounterFeatureCount // This enum value must be last.
  7178. };
  7179. enum MessageErrorLevel {
  7180. kMessageLog = (1 << 0),
  7181. kMessageDebug = (1 << 1),
  7182. kMessageInfo = (1 << 2),
  7183. kMessageError = (1 << 3),
  7184. kMessageWarning = (1 << 4),
  7185. kMessageAll = kMessageLog | kMessageDebug | kMessageInfo | kMessageError |
  7186. kMessageWarning,
  7187. };
  7188. typedef void (*UseCounterCallback)(Isolate* isolate,
  7189. UseCounterFeature feature);
  7190. /**
  7191. * Allocates a new isolate but does not initialize it. Does not change the
  7192. * currently entered isolate.
  7193. *
  7194. * Only Isolate::GetData() and Isolate::SetData(), which access the
  7195. * embedder-controlled parts of the isolate, are allowed to be called on the
  7196. * uninitialized isolate. To initialize the isolate, call
  7197. * Isolate::Initialize().
  7198. *
  7199. * When an isolate is no longer used its resources should be freed
  7200. * by calling Dispose(). Using the delete operator is not allowed.
  7201. *
  7202. * V8::Initialize() must have run prior to this.
  7203. */
  7204. static Isolate* Allocate();
  7205. /**
  7206. * Initialize an Isolate previously allocated by Isolate::Allocate().
  7207. */
  7208. static void Initialize(Isolate* isolate, const CreateParams& params);
  7209. /**
  7210. * Creates a new isolate. Does not change the currently entered
  7211. * isolate.
  7212. *
  7213. * When an isolate is no longer used its resources should be freed
  7214. * by calling Dispose(). Using the delete operator is not allowed.
  7215. *
  7216. * V8::Initialize() must have run prior to this.
  7217. */
  7218. static Isolate* New(const CreateParams& params);
  7219. /**
  7220. * Returns the entered isolate for the current thread or NULL in
  7221. * case there is no current isolate.
  7222. *
  7223. * This method must not be invoked before V8::Initialize() was invoked.
  7224. */
  7225. static Isolate* GetCurrent();
  7226. /**
  7227. * Clears the set of objects held strongly by the heap. This set of
  7228. * objects are originally built when a WeakRef is created or
  7229. * successfully dereferenced.
  7230. *
  7231. * The embedder is expected to call this when a synchronous sequence
  7232. * of ECMAScript execution completes. It's the embedders
  7233. * responsiblity to make this call at a time which does not
  7234. * interrupt synchronous ECMAScript code execution.
  7235. */
  7236. void ClearKeptObjects();
  7237. /**
  7238. * Custom callback used by embedders to help V8 determine if it should abort
  7239. * when it throws and no internal handler is predicted to catch the
  7240. * exception. If --abort-on-uncaught-exception is used on the command line,
  7241. * then V8 will abort if either:
  7242. * - no custom callback is set.
  7243. * - the custom callback set returns true.
  7244. * Otherwise, the custom callback will not be called and V8 will not abort.
  7245. */
  7246. typedef bool (*AbortOnUncaughtExceptionCallback)(Isolate*);
  7247. void SetAbortOnUncaughtExceptionCallback(
  7248. AbortOnUncaughtExceptionCallback callback);
  7249. /**
  7250. * This specifies the callback to be called when finalization groups
  7251. * are ready to be cleaned up and require FinalizationGroup::Cleanup()
  7252. * to be called in a future task.
  7253. */
  7254. void SetHostCleanupFinalizationGroupCallback(
  7255. HostCleanupFinalizationGroupCallback callback);
  7256. /**
  7257. * This specifies the callback called by the upcoming dynamic
  7258. * import() language feature to load modules.
  7259. */
  7260. void SetHostImportModuleDynamicallyCallback(
  7261. HostImportModuleDynamicallyCallback callback);
  7262. /**
  7263. * This specifies the callback called by the upcoming importa.meta
  7264. * language feature to retrieve host-defined meta data for a module.
  7265. */
  7266. void SetHostInitializeImportMetaObjectCallback(
  7267. HostInitializeImportMetaObjectCallback callback);
  7268. /**
  7269. * This specifies the callback called when the stack property of Error
  7270. * is accessed.
  7271. */
  7272. void SetPrepareStackTraceCallback(PrepareStackTraceCallback callback);
  7273. /**
  7274. * Optional notification that the system is running low on memory.
  7275. * V8 uses these notifications to guide heuristics.
  7276. * It is allowed to call this function from another thread while
  7277. * the isolate is executing long running JavaScript code.
  7278. */
  7279. void MemoryPressureNotification(MemoryPressureLevel level);
  7280. /**
  7281. * Methods below this point require holding a lock (using Locker) in
  7282. * a multi-threaded environment.
  7283. */
  7284. /**
  7285. * Sets this isolate as the entered one for the current thread.
  7286. * Saves the previously entered one (if any), so that it can be
  7287. * restored when exiting. Re-entering an isolate is allowed.
  7288. */
  7289. void Enter();
  7290. /**
  7291. * Exits this isolate by restoring the previously entered one in the
  7292. * current thread. The isolate may still stay the same, if it was
  7293. * entered more than once.
  7294. *
  7295. * Requires: this == Isolate::GetCurrent().
  7296. */
  7297. void Exit();
  7298. /**
  7299. * Disposes the isolate. The isolate must not be entered by any
  7300. * thread to be disposable.
  7301. */
  7302. void Dispose();
  7303. /**
  7304. * Dumps activated low-level V8 internal stats. This can be used instead
  7305. * of performing a full isolate disposal.
  7306. */
  7307. void DumpAndResetStats();
  7308. /**
  7309. * Discards all V8 thread-specific data for the Isolate. Should be used
  7310. * if a thread is terminating and it has used an Isolate that will outlive
  7311. * the thread -- all thread-specific data for an Isolate is discarded when
  7312. * an Isolate is disposed so this call is pointless if an Isolate is about
  7313. * to be Disposed.
  7314. */
  7315. void DiscardThreadSpecificMetadata();
  7316. /**
  7317. * Associate embedder-specific data with the isolate. |slot| has to be
  7318. * between 0 and GetNumberOfDataSlots() - 1.
  7319. */
  7320. V8_INLINE void SetData(uint32_t slot, void* data);
  7321. /**
  7322. * Retrieve embedder-specific data from the isolate.
  7323. * Returns NULL if SetData has never been called for the given |slot|.
  7324. */
  7325. V8_INLINE void* GetData(uint32_t slot);
  7326. /**
  7327. * Returns the maximum number of available embedder data slots. Valid slots
  7328. * are in the range of 0 - GetNumberOfDataSlots() - 1.
  7329. */
  7330. V8_INLINE static uint32_t GetNumberOfDataSlots();
  7331. /**
  7332. * Return data that was previously attached to the isolate snapshot via
  7333. * SnapshotCreator, and removes the reference to it.
  7334. * Repeated call with the same index returns an empty MaybeLocal.
  7335. */
  7336. template <class T>
  7337. V8_INLINE MaybeLocal<T> GetDataFromSnapshotOnce(size_t index);
  7338. /**
  7339. * Get statistics about the heap memory usage.
  7340. */
  7341. void GetHeapStatistics(HeapStatistics* heap_statistics);
  7342. /**
  7343. * Returns the number of spaces in the heap.
  7344. */
  7345. size_t NumberOfHeapSpaces();
  7346. /**
  7347. * Get the memory usage of a space in the heap.
  7348. *
  7349. * \param space_statistics The HeapSpaceStatistics object to fill in
  7350. * statistics.
  7351. * \param index The index of the space to get statistics from, which ranges
  7352. * from 0 to NumberOfHeapSpaces() - 1.
  7353. * \returns true on success.
  7354. */
  7355. bool GetHeapSpaceStatistics(HeapSpaceStatistics* space_statistics,
  7356. size_t index);
  7357. /**
  7358. * Returns the number of types of objects tracked in the heap at GC.
  7359. */
  7360. size_t NumberOfTrackedHeapObjectTypes();
  7361. /**
  7362. * Get statistics about objects in the heap.
  7363. *
  7364. * \param object_statistics The HeapObjectStatistics object to fill in
  7365. * statistics of objects of given type, which were live in the previous GC.
  7366. * \param type_index The index of the type of object to fill details about,
  7367. * which ranges from 0 to NumberOfTrackedHeapObjectTypes() - 1.
  7368. * \returns true on success.
  7369. */
  7370. bool GetHeapObjectStatisticsAtLastGC(HeapObjectStatistics* object_statistics,
  7371. size_t type_index);
  7372. /**
  7373. * Get statistics about code and its metadata in the heap.
  7374. *
  7375. * \param object_statistics The HeapCodeStatistics object to fill in
  7376. * statistics of code, bytecode and their metadata.
  7377. * \returns true on success.
  7378. */
  7379. bool GetHeapCodeAndMetadataStatistics(HeapCodeStatistics* object_statistics);
  7380. /**
  7381. * Enqueues a memory measurement request for the given context and mode.
  7382. * This API is experimental and may change significantly.
  7383. *
  7384. * \param mode Indicates whether the result should include per-context
  7385. * memory usage or just the total memory usage.
  7386. * \returns a promise that will be resolved with memory usage estimate.
  7387. */
  7388. v8::MaybeLocal<v8::Promise> MeasureMemory(v8::Local<v8::Context> context,
  7389. MeasureMemoryMode mode);
  7390. /**
  7391. * Get a call stack sample from the isolate.
  7392. * \param state Execution state.
  7393. * \param frames Caller allocated buffer to store stack frames.
  7394. * \param frames_limit Maximum number of frames to capture. The buffer must
  7395. * be large enough to hold the number of frames.
  7396. * \param sample_info The sample info is filled up by the function
  7397. * provides number of actual captured stack frames and
  7398. * the current VM state.
  7399. * \note GetStackSample should only be called when the JS thread is paused or
  7400. * interrupted. Otherwise the behavior is undefined.
  7401. */
  7402. void GetStackSample(const RegisterState& state, void** frames,
  7403. size_t frames_limit, SampleInfo* sample_info);
  7404. /**
  7405. * Adjusts the amount of registered external memory. Used to give V8 an
  7406. * indication of the amount of externally allocated memory that is kept alive
  7407. * by JavaScript objects. V8 uses this to decide when to perform global
  7408. * garbage collections. Registering externally allocated memory will trigger
  7409. * global garbage collections more often than it would otherwise in an attempt
  7410. * to garbage collect the JavaScript objects that keep the externally
  7411. * allocated memory alive.
  7412. *
  7413. * \param change_in_bytes the change in externally allocated memory that is
  7414. * kept alive by JavaScript objects.
  7415. * \returns the adjusted value.
  7416. */
  7417. V8_INLINE int64_t
  7418. AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes);
  7419. /**
  7420. * Returns the number of phantom handles without callbacks that were reset
  7421. * by the garbage collector since the last call to this function.
  7422. */
  7423. size_t NumberOfPhantomHandleResetsSinceLastCall();
  7424. /**
  7425. * Returns heap profiler for this isolate. Will return NULL until the isolate
  7426. * is initialized.
  7427. */
  7428. HeapProfiler* GetHeapProfiler();
  7429. /**
  7430. * Tells the VM whether the embedder is idle or not.
  7431. */
  7432. void SetIdle(bool is_idle);
  7433. /** Returns the ArrayBuffer::Allocator used in this isolate. */
  7434. ArrayBuffer::Allocator* GetArrayBufferAllocator();
  7435. /** Returns true if this isolate has a current context. */
  7436. bool InContext();
  7437. /**
  7438. * Returns the context of the currently running JavaScript, or the context
  7439. * on the top of the stack if no JavaScript is running.
  7440. */
  7441. Local<Context> GetCurrentContext();
  7442. /** Returns the last context entered through V8's C++ API. */
  7443. V8_DEPRECATED("Use GetEnteredOrMicrotaskContext().")
  7444. Local<Context> GetEnteredContext();
  7445. /**
  7446. * Returns either the last context entered through V8's C++ API, or the
  7447. * context of the currently running microtask while processing microtasks.
  7448. * If a context is entered while executing a microtask, that context is
  7449. * returned.
  7450. */
  7451. Local<Context> GetEnteredOrMicrotaskContext();
  7452. /**
  7453. * Returns the Context that corresponds to the Incumbent realm in HTML spec.
  7454. * https://html.spec.whatwg.org/multipage/webappapis.html#incumbent
  7455. */
  7456. Local<Context> GetIncumbentContext();
  7457. /**
  7458. * Schedules an exception to be thrown when returning to JavaScript. When an
  7459. * exception has been scheduled it is illegal to invoke any JavaScript
  7460. * operation; the caller must return immediately and only after the exception
  7461. * has been handled does it become legal to invoke JavaScript operations.
  7462. */
  7463. Local<Value> ThrowException(Local<Value> exception);
  7464. typedef void (*GCCallback)(Isolate* isolate, GCType type,
  7465. GCCallbackFlags flags);
  7466. typedef void (*GCCallbackWithData)(Isolate* isolate, GCType type,
  7467. GCCallbackFlags flags, void* data);
  7468. /**
  7469. * Enables the host application to receive a notification before a
  7470. * garbage collection. Allocations are allowed in the callback function,
  7471. * but the callback is not re-entrant: if the allocation inside it will
  7472. * trigger the garbage collection, the callback won't be called again.
  7473. * It is possible to specify the GCType filter for your callback. But it is
  7474. * not possible to register the same callback function two times with
  7475. * different GCType filters.
  7476. */
  7477. void AddGCPrologueCallback(GCCallbackWithData callback, void* data = nullptr,
  7478. GCType gc_type_filter = kGCTypeAll);
  7479. void AddGCPrologueCallback(GCCallback callback,
  7480. GCType gc_type_filter = kGCTypeAll);
  7481. /**
  7482. * This function removes callback which was installed by
  7483. * AddGCPrologueCallback function.
  7484. */
  7485. void RemoveGCPrologueCallback(GCCallbackWithData, void* data = nullptr);
  7486. void RemoveGCPrologueCallback(GCCallback callback);
  7487. /**
  7488. * Sets the embedder heap tracer for the isolate.
  7489. */
  7490. void SetEmbedderHeapTracer(EmbedderHeapTracer* tracer);
  7491. /*
  7492. * Gets the currently active heap tracer for the isolate.
  7493. */
  7494. EmbedderHeapTracer* GetEmbedderHeapTracer();
  7495. /**
  7496. * Use for |AtomicsWaitCallback| to indicate the type of event it receives.
  7497. */
  7498. enum class AtomicsWaitEvent {
  7499. /** Indicates that this call is happening before waiting. */
  7500. kStartWait,
  7501. /** `Atomics.wait()` finished because of an `Atomics.wake()` call. */
  7502. kWokenUp,
  7503. /** `Atomics.wait()` finished because it timed out. */
  7504. kTimedOut,
  7505. /** `Atomics.wait()` was interrupted through |TerminateExecution()|. */
  7506. kTerminatedExecution,
  7507. /** `Atomics.wait()` was stopped through |AtomicsWaitWakeHandle|. */
  7508. kAPIStopped,
  7509. /** `Atomics.wait()` did not wait, as the initial condition was not met. */
  7510. kNotEqual
  7511. };
  7512. /**
  7513. * Passed to |AtomicsWaitCallback| as a means of stopping an ongoing
  7514. * `Atomics.wait` call.
  7515. */
  7516. class V8_EXPORT AtomicsWaitWakeHandle {
  7517. public:
  7518. /**
  7519. * Stop this `Atomics.wait()` call and call the |AtomicsWaitCallback|
  7520. * with |kAPIStopped|.
  7521. *
  7522. * This function may be called from another thread. The caller has to ensure
  7523. * through proper synchronization that it is not called after
  7524. * the finishing |AtomicsWaitCallback|.
  7525. *
  7526. * Note that the ECMAScript specification does not plan for the possibility
  7527. * of wakeups that are neither coming from a timeout or an `Atomics.wake()`
  7528. * call, so this may invalidate assumptions made by existing code.
  7529. * The embedder may accordingly wish to schedule an exception in the
  7530. * finishing |AtomicsWaitCallback|.
  7531. */
  7532. void Wake();
  7533. };
  7534. /**
  7535. * Embedder callback for `Atomics.wait()` that can be added through
  7536. * |SetAtomicsWaitCallback|.
  7537. *
  7538. * This will be called just before starting to wait with the |event| value
  7539. * |kStartWait| and after finishing waiting with one of the other
  7540. * values of |AtomicsWaitEvent| inside of an `Atomics.wait()` call.
  7541. *
  7542. * |array_buffer| will refer to the underlying SharedArrayBuffer,
  7543. * |offset_in_bytes| to the location of the waited-on memory address inside
  7544. * the SharedArrayBuffer.
  7545. *
  7546. * |value| and |timeout_in_ms| will be the values passed to
  7547. * the `Atomics.wait()` call. If no timeout was used, |timeout_in_ms|
  7548. * will be `INFINITY`.
  7549. *
  7550. * In the |kStartWait| callback, |stop_handle| will be an object that
  7551. * is only valid until the corresponding finishing callback and that
  7552. * can be used to stop the wait process while it is happening.
  7553. *
  7554. * This callback may schedule exceptions, *unless* |event| is equal to
  7555. * |kTerminatedExecution|.
  7556. */
  7557. typedef void (*AtomicsWaitCallback)(AtomicsWaitEvent event,
  7558. Local<SharedArrayBuffer> array_buffer,
  7559. size_t offset_in_bytes, int64_t value,
  7560. double timeout_in_ms,
  7561. AtomicsWaitWakeHandle* stop_handle,
  7562. void* data);
  7563. /**
  7564. * Set a new |AtomicsWaitCallback|. This overrides an earlier
  7565. * |AtomicsWaitCallback|, if there was any. If |callback| is nullptr,
  7566. * this unsets the callback. |data| will be passed to the callback
  7567. * as its last parameter.
  7568. */
  7569. void SetAtomicsWaitCallback(AtomicsWaitCallback callback, void* data);
  7570. /**
  7571. * Enables the host application to receive a notification after a
  7572. * garbage collection. Allocations are allowed in the callback function,
  7573. * but the callback is not re-entrant: if the allocation inside it will
  7574. * trigger the garbage collection, the callback won't be called again.
  7575. * It is possible to specify the GCType filter for your callback. But it is
  7576. * not possible to register the same callback function two times with
  7577. * different GCType filters.
  7578. */
  7579. void AddGCEpilogueCallback(GCCallbackWithData callback, void* data = nullptr,
  7580. GCType gc_type_filter = kGCTypeAll);
  7581. void AddGCEpilogueCallback(GCCallback callback,
  7582. GCType gc_type_filter = kGCTypeAll);
  7583. /**
  7584. * This function removes callback which was installed by
  7585. * AddGCEpilogueCallback function.
  7586. */
  7587. void RemoveGCEpilogueCallback(GCCallbackWithData callback,
  7588. void* data = nullptr);
  7589. void RemoveGCEpilogueCallback(GCCallback callback);
  7590. typedef size_t (*GetExternallyAllocatedMemoryInBytesCallback)();
  7591. /**
  7592. * Set the callback that tells V8 how much memory is currently allocated
  7593. * externally of the V8 heap. Ideally this memory is somehow connected to V8
  7594. * objects and may get freed-up when the corresponding V8 objects get
  7595. * collected by a V8 garbage collection.
  7596. */
  7597. void SetGetExternallyAllocatedMemoryInBytesCallback(
  7598. GetExternallyAllocatedMemoryInBytesCallback callback);
  7599. /**
  7600. * Forcefully terminate the current thread of JavaScript execution
  7601. * in the given isolate.
  7602. *
  7603. * This method can be used by any thread even if that thread has not
  7604. * acquired the V8 lock with a Locker object.
  7605. */
  7606. void TerminateExecution();
  7607. /**
  7608. * Is V8 terminating JavaScript execution.
  7609. *
  7610. * Returns true if JavaScript execution is currently terminating
  7611. * because of a call to TerminateExecution. In that case there are
  7612. * still JavaScript frames on the stack and the termination
  7613. * exception is still active.
  7614. */
  7615. bool IsExecutionTerminating();
  7616. /**
  7617. * Resume execution capability in the given isolate, whose execution
  7618. * was previously forcefully terminated using TerminateExecution().
  7619. *
  7620. * When execution is forcefully terminated using TerminateExecution(),
  7621. * the isolate can not resume execution until all JavaScript frames
  7622. * have propagated the uncatchable exception which is generated. This
  7623. * method allows the program embedding the engine to handle the
  7624. * termination event and resume execution capability, even if
  7625. * JavaScript frames remain on the stack.
  7626. *
  7627. * This method can be used by any thread even if that thread has not
  7628. * acquired the V8 lock with a Locker object.
  7629. */
  7630. void CancelTerminateExecution();
  7631. /**
  7632. * Request V8 to interrupt long running JavaScript code and invoke
  7633. * the given |callback| passing the given |data| to it. After |callback|
  7634. * returns control will be returned to the JavaScript code.
  7635. * There may be a number of interrupt requests in flight.
  7636. * Can be called from another thread without acquiring a |Locker|.
  7637. * Registered |callback| must not reenter interrupted Isolate.
  7638. */
  7639. void RequestInterrupt(InterruptCallback callback, void* data);
  7640. /**
  7641. * Request garbage collection in this Isolate. It is only valid to call this
  7642. * function if --expose_gc was specified.
  7643. *
  7644. * This should only be used for testing purposes and not to enforce a garbage
  7645. * collection schedule. It has strong negative impact on the garbage
  7646. * collection performance. Use IdleNotificationDeadline() or
  7647. * LowMemoryNotification() instead to influence the garbage collection
  7648. * schedule.
  7649. */
  7650. void RequestGarbageCollectionForTesting(GarbageCollectionType type);
  7651. /**
  7652. * Set the callback to invoke for logging event.
  7653. */
  7654. void SetEventLogger(LogEventCallback that);
  7655. /**
  7656. * Adds a callback to notify the host application right before a script
  7657. * is about to run. If a script re-enters the runtime during executing, the
  7658. * BeforeCallEnteredCallback is invoked for each re-entrance.
  7659. * Executing scripts inside the callback will re-trigger the callback.
  7660. */
  7661. void AddBeforeCallEnteredCallback(BeforeCallEnteredCallback callback);
  7662. /**
  7663. * Removes callback that was installed by AddBeforeCallEnteredCallback.
  7664. */
  7665. void RemoveBeforeCallEnteredCallback(BeforeCallEnteredCallback callback);
  7666. /**
  7667. * Adds a callback to notify the host application when a script finished
  7668. * running. If a script re-enters the runtime during executing, the
  7669. * CallCompletedCallback is only invoked when the outer-most script
  7670. * execution ends. Executing scripts inside the callback do not trigger
  7671. * further callbacks.
  7672. */
  7673. void AddCallCompletedCallback(CallCompletedCallback callback);
  7674. /**
  7675. * Removes callback that was installed by AddCallCompletedCallback.
  7676. */
  7677. void RemoveCallCompletedCallback(CallCompletedCallback callback);
  7678. /**
  7679. * Set the PromiseHook callback for various promise lifecycle
  7680. * events.
  7681. */
  7682. void SetPromiseHook(PromiseHook hook);
  7683. /**
  7684. * Set callback to notify about promise reject with no handler, or
  7685. * revocation of such a previous notification once the handler is added.
  7686. */
  7687. void SetPromiseRejectCallback(PromiseRejectCallback callback);
  7688. /**
  7689. * Runs the default MicrotaskQueue until it gets empty.
  7690. * Any exceptions thrown by microtask callbacks are swallowed.
  7691. */
  7692. void RunMicrotasks();
  7693. /**
  7694. * Enqueues the callback to the default MicrotaskQueue
  7695. */
  7696. void EnqueueMicrotask(Local<Function> microtask);
  7697. /**
  7698. * Enqueues the callback to the default MicrotaskQueue
  7699. */
  7700. void EnqueueMicrotask(MicrotaskCallback callback, void* data = nullptr);
  7701. /**
  7702. * Controls how Microtasks are invoked. See MicrotasksPolicy for details.
  7703. */
  7704. void SetMicrotasksPolicy(MicrotasksPolicy policy);
  7705. /**
  7706. * Returns the policy controlling how Microtasks are invoked.
  7707. */
  7708. MicrotasksPolicy GetMicrotasksPolicy() const;
  7709. /**
  7710. * Adds a callback to notify the host application after
  7711. * microtasks were run on the default MicrotaskQueue. The callback is
  7712. * triggered by explicit RunMicrotasks call or automatic microtasks execution
  7713. * (see SetMicrotaskPolicy).
  7714. *
  7715. * Callback will trigger even if microtasks were attempted to run,
  7716. * but the microtasks queue was empty and no single microtask was actually
  7717. * executed.
  7718. *
  7719. * Executing scripts inside the callback will not re-trigger microtasks and
  7720. * the callback.
  7721. */
  7722. V8_DEPRECATE_SOON("Use *WithData version.")
  7723. void AddMicrotasksCompletedCallback(MicrotasksCompletedCallback callback);
  7724. void AddMicrotasksCompletedCallback(
  7725. MicrotasksCompletedCallbackWithData callback, void* data = nullptr);
  7726. /**
  7727. * Removes callback that was installed by AddMicrotasksCompletedCallback.
  7728. */
  7729. V8_DEPRECATE_SOON("Use *WithData version.")
  7730. void RemoveMicrotasksCompletedCallback(MicrotasksCompletedCallback callback);
  7731. void RemoveMicrotasksCompletedCallback(
  7732. MicrotasksCompletedCallbackWithData callback, void* data = nullptr);
  7733. /**
  7734. * Sets a callback for counting the number of times a feature of V8 is used.
  7735. */
  7736. void SetUseCounterCallback(UseCounterCallback callback);
  7737. /**
  7738. * Enables the host application to provide a mechanism for recording
  7739. * statistics counters.
  7740. */
  7741. void SetCounterFunction(CounterLookupCallback);
  7742. /**
  7743. * Enables the host application to provide a mechanism for recording
  7744. * histograms. The CreateHistogram function returns a
  7745. * histogram which will later be passed to the AddHistogramSample
  7746. * function.
  7747. */
  7748. void SetCreateHistogramFunction(CreateHistogramCallback);
  7749. void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
  7750. /**
  7751. * Enables the host application to provide a mechanism for recording a
  7752. * predefined set of data as crash keys to be used in postmortem debugging in
  7753. * case of a crash.
  7754. */
  7755. void SetAddCrashKeyCallback(AddCrashKeyCallback);
  7756. /**
  7757. * Optional notification that the embedder is idle.
  7758. * V8 uses the notification to perform garbage collection.
  7759. * This call can be used repeatedly if the embedder remains idle.
  7760. * Returns true if the embedder should stop calling IdleNotificationDeadline
  7761. * until real work has been done. This indicates that V8 has done
  7762. * as much cleanup as it will be able to do.
  7763. *
  7764. * The deadline_in_seconds argument specifies the deadline V8 has to finish
  7765. * garbage collection work. deadline_in_seconds is compared with
  7766. * MonotonicallyIncreasingTime() and should be based on the same timebase as
  7767. * that function. There is no guarantee that the actual work will be done
  7768. * within the time limit.
  7769. */
  7770. bool IdleNotificationDeadline(double deadline_in_seconds);
  7771. /**
  7772. * Optional notification that the system is running low on memory.
  7773. * V8 uses these notifications to attempt to free memory.
  7774. */
  7775. void LowMemoryNotification();
  7776. /**
  7777. * Optional notification that a context has been disposed. V8 uses
  7778. * these notifications to guide the GC heuristic. Returns the number
  7779. * of context disposals - including this one - since the last time
  7780. * V8 had a chance to clean up.
  7781. *
  7782. * The optional parameter |dependant_context| specifies whether the disposed
  7783. * context was depending on state from other contexts or not.
  7784. */
  7785. int ContextDisposedNotification(bool dependant_context = true);
  7786. /**
  7787. * Optional notification that the isolate switched to the foreground.
  7788. * V8 uses these notifications to guide heuristics.
  7789. */
  7790. void IsolateInForegroundNotification();
  7791. /**
  7792. * Optional notification that the isolate switched to the background.
  7793. * V8 uses these notifications to guide heuristics.
  7794. */
  7795. void IsolateInBackgroundNotification();
  7796. /**
  7797. * Optional notification which will enable the memory savings mode.
  7798. * V8 uses this notification to guide heuristics which may result in a
  7799. * smaller memory footprint at the cost of reduced runtime performance.
  7800. */
  7801. void EnableMemorySavingsMode();
  7802. /**
  7803. * Optional notification which will disable the memory savings mode.
  7804. */
  7805. void DisableMemorySavingsMode();
  7806. /**
  7807. * Optional notification to tell V8 the current performance requirements
  7808. * of the embedder based on RAIL.
  7809. * V8 uses these notifications to guide heuristics.
  7810. * This is an unfinished experimental feature. Semantics and implementation
  7811. * may change frequently.
  7812. */
  7813. void SetRAILMode(RAILMode rail_mode);
  7814. /**
  7815. * Optional notification to tell V8 the current isolate is used for debugging
  7816. * and requires higher heap limit.
  7817. */
  7818. void IncreaseHeapLimitForDebugging();
  7819. /**
  7820. * Restores the original heap limit after IncreaseHeapLimitForDebugging().
  7821. */
  7822. void RestoreOriginalHeapLimit();
  7823. /**
  7824. * Returns true if the heap limit was increased for debugging and the
  7825. * original heap limit was not restored yet.
  7826. */
  7827. bool IsHeapLimitIncreasedForDebugging();
  7828. /**
  7829. * Allows the host application to provide the address of a function that is
  7830. * notified each time code is added, moved or removed.
  7831. *
  7832. * \param options options for the JIT code event handler.
  7833. * \param event_handler the JIT code event handler, which will be invoked
  7834. * each time code is added, moved or removed.
  7835. * \note \p event_handler won't get notified of existent code.
  7836. * \note since code removal notifications are not currently issued, the
  7837. * \p event_handler may get notifications of code that overlaps earlier
  7838. * code notifications. This happens when code areas are reused, and the
  7839. * earlier overlapping code areas should therefore be discarded.
  7840. * \note the events passed to \p event_handler and the strings they point to
  7841. * are not guaranteed to live past each call. The \p event_handler must
  7842. * copy strings and other parameters it needs to keep around.
  7843. * \note the set of events declared in JitCodeEvent::EventType is expected to
  7844. * grow over time, and the JitCodeEvent structure is expected to accrue
  7845. * new members. The \p event_handler function must ignore event codes
  7846. * it does not recognize to maintain future compatibility.
  7847. * \note Use Isolate::CreateParams to get events for code executed during
  7848. * Isolate setup.
  7849. */
  7850. void SetJitCodeEventHandler(JitCodeEventOptions options,
  7851. JitCodeEventHandler event_handler);
  7852. /**
  7853. * Modifies the stack limit for this Isolate.
  7854. *
  7855. * \param stack_limit An address beyond which the Vm's stack may not grow.
  7856. *
  7857. * \note If you are using threads then you should hold the V8::Locker lock
  7858. * while setting the stack limit and you must set a non-default stack
  7859. * limit separately for each thread.
  7860. */
  7861. void SetStackLimit(uintptr_t stack_limit);
  7862. /**
  7863. * Returns a memory range that can potentially contain jitted code. Code for
  7864. * V8's 'builtins' will not be in this range if embedded builtins is enabled.
  7865. *
  7866. * On Win64, embedders are advised to install function table callbacks for
  7867. * these ranges, as default SEH won't be able to unwind through jitted code.
  7868. * The first page of the code range is reserved for the embedder and is
  7869. * committed, writable, and executable, to be used to store unwind data, as
  7870. * documented in
  7871. * https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64.
  7872. *
  7873. * Might be empty on other platforms.
  7874. *
  7875. * https://code.google.com/p/v8/issues/detail?id=3598
  7876. */
  7877. void GetCodeRange(void** start, size_t* length_in_bytes);
  7878. /**
  7879. * Returns the UnwindState necessary for use with the Unwinder API.
  7880. */
  7881. UnwindState GetUnwindState();
  7882. /** Set the callback to invoke in case of fatal errors. */
  7883. void SetFatalErrorHandler(FatalErrorCallback that);
  7884. /** Set the callback to invoke in case of OOM errors. */
  7885. void SetOOMErrorHandler(OOMErrorCallback that);
  7886. /**
  7887. * Add a callback to invoke in case the heap size is close to the heap limit.
  7888. * If multiple callbacks are added, only the most recently added callback is
  7889. * invoked.
  7890. */
  7891. void AddNearHeapLimitCallback(NearHeapLimitCallback callback, void* data);
  7892. /**
  7893. * Remove the given callback and restore the heap limit to the
  7894. * given limit. If the given limit is zero, then it is ignored.
  7895. * If the current heap size is greater than the given limit,
  7896. * then the heap limit is restored to the minimal limit that
  7897. * is possible for the current heap size.
  7898. */
  7899. void RemoveNearHeapLimitCallback(NearHeapLimitCallback callback,
  7900. size_t heap_limit);
  7901. /**
  7902. * If the heap limit was changed by the NearHeapLimitCallback, then the
  7903. * initial heap limit will be restored once the heap size falls below the
  7904. * given threshold percentage of the initial heap limit.
  7905. * The threshold percentage is a number in (0.0, 1.0) range.
  7906. */
  7907. void AutomaticallyRestoreInitialHeapLimit(double threshold_percent = 0.5);
  7908. /**
  7909. * Set the callback to invoke to check if code generation from
  7910. * strings should be allowed.
  7911. */
  7912. void SetAllowCodeGenerationFromStringsCallback(
  7913. AllowCodeGenerationFromStringsCallback callback);
  7914. void SetModifyCodeGenerationFromStringsCallback(
  7915. ModifyCodeGenerationFromStringsCallback callback);
  7916. /**
  7917. * Set the callback to invoke to check if wasm code generation should
  7918. * be allowed.
  7919. */
  7920. void SetAllowWasmCodeGenerationCallback(
  7921. AllowWasmCodeGenerationCallback callback);
  7922. /**
  7923. * Embedder over{ride|load} injection points for wasm APIs. The expectation
  7924. * is that the embedder sets them at most once.
  7925. */
  7926. void SetWasmModuleCallback(ExtensionCallback callback);
  7927. void SetWasmInstanceCallback(ExtensionCallback callback);
  7928. void SetWasmStreamingCallback(WasmStreamingCallback callback);
  7929. void SetWasmThreadsEnabledCallback(WasmThreadsEnabledCallback callback);
  7930. void SetWasmLoadSourceMapCallback(WasmLoadSourceMapCallback callback);
  7931. /**
  7932. * Check if V8 is dead and therefore unusable. This is the case after
  7933. * fatal errors such as out-of-memory situations.
  7934. */
  7935. bool IsDead();
  7936. /**
  7937. * Adds a message listener (errors only).
  7938. *
  7939. * The same message listener can be added more than once and in that
  7940. * case it will be called more than once for each message.
  7941. *
  7942. * If data is specified, it will be passed to the callback when it is called.
  7943. * Otherwise, the exception object will be passed to the callback instead.
  7944. */
  7945. bool AddMessageListener(MessageCallback that,
  7946. Local<Value> data = Local<Value>());
  7947. /**
  7948. * Adds a message listener.
  7949. *
  7950. * The same message listener can be added more than once and in that
  7951. * case it will be called more than once for each message.
  7952. *
  7953. * If data is specified, it will be passed to the callback when it is called.
  7954. * Otherwise, the exception object will be passed to the callback instead.
  7955. *
  7956. * A listener can listen for particular error levels by providing a mask.
  7957. */
  7958. bool AddMessageListenerWithErrorLevel(MessageCallback that,
  7959. int message_levels,
  7960. Local<Value> data = Local<Value>());
  7961. /**
  7962. * Remove all message listeners from the specified callback function.
  7963. */
  7964. void RemoveMessageListeners(MessageCallback that);
  7965. /** Callback function for reporting failed access checks.*/
  7966. void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
  7967. /**
  7968. * Tells V8 to capture current stack trace when uncaught exception occurs
  7969. * and report it to the message listeners. The option is off by default.
  7970. */
  7971. void SetCaptureStackTraceForUncaughtExceptions(
  7972. bool capture, int frame_limit = 10,
  7973. StackTrace::StackTraceOptions options = StackTrace::kOverview);
  7974. /**
  7975. * Iterates through all external resources referenced from current isolate
  7976. * heap. GC is not invoked prior to iterating, therefore there is no
  7977. * guarantee that visited objects are still alive.
  7978. */
  7979. void VisitExternalResources(ExternalResourceVisitor* visitor);
  7980. /**
  7981. * Iterates through all the persistent handles in the current isolate's heap
  7982. * that have class_ids.
  7983. */
  7984. void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor);
  7985. /**
  7986. * Iterates through all the persistent handles in the current isolate's heap
  7987. * that have class_ids and are weak to be marked as inactive if there is no
  7988. * pending activity for the handle.
  7989. */
  7990. void VisitWeakHandles(PersistentHandleVisitor* visitor);
  7991. /**
  7992. * Check if this isolate is in use.
  7993. * True if at least one thread Enter'ed this isolate.
  7994. */
  7995. bool IsInUse();
  7996. /**
  7997. * Set whether calling Atomics.wait (a function that may block) is allowed in
  7998. * this isolate. This can also be configured via
  7999. * CreateParams::allow_atomics_wait.
  8000. */
  8001. void SetAllowAtomicsWait(bool allow);
  8002. /**
  8003. * Time zone redetection indicator for
  8004. * DateTimeConfigurationChangeNotification.
  8005. *
  8006. * kSkip indicates V8 that the notification should not trigger redetecting
  8007. * host time zone. kRedetect indicates V8 that host time zone should be
  8008. * redetected, and used to set the default time zone.
  8009. *
  8010. * The host time zone detection may require file system access or similar
  8011. * operations unlikely to be available inside a sandbox. If v8 is run inside a
  8012. * sandbox, the host time zone has to be detected outside the sandbox before
  8013. * calling DateTimeConfigurationChangeNotification function.
  8014. */
  8015. enum class TimeZoneDetection { kSkip, kRedetect };
  8016. /**
  8017. * Notification that the embedder has changed the time zone, daylight savings
  8018. * time or other date / time configuration parameters. V8 keeps a cache of
  8019. * various values used for date / time computation. This notification will
  8020. * reset those cached values for the current context so that date / time
  8021. * configuration changes would be reflected.
  8022. *
  8023. * This API should not be called more than needed as it will negatively impact
  8024. * the performance of date operations.
  8025. */
  8026. void DateTimeConfigurationChangeNotification(
  8027. TimeZoneDetection time_zone_detection = TimeZoneDetection::kSkip);
  8028. /**
  8029. * Notification that the embedder has changed the locale. V8 keeps a cache of
  8030. * various values used for locale computation. This notification will reset
  8031. * those cached values for the current context so that locale configuration
  8032. * changes would be reflected.
  8033. *
  8034. * This API should not be called more than needed as it will negatively impact
  8035. * the performance of locale operations.
  8036. */
  8037. void LocaleConfigurationChangeNotification();
  8038. Isolate() = delete;
  8039. ~Isolate() = delete;
  8040. Isolate(const Isolate&) = delete;
  8041. Isolate& operator=(const Isolate&) = delete;
  8042. // Deleting operator new and delete here is allowed as ctor and dtor is also
  8043. // deleted.
  8044. void* operator new(size_t size) = delete;
  8045. void* operator new[](size_t size) = delete;
  8046. void operator delete(void*, size_t) = delete;
  8047. void operator delete[](void*, size_t) = delete;
  8048. private:
  8049. template <class K, class V, class Traits>
  8050. friend class PersistentValueMapBase;
  8051. internal::Address* GetDataFromSnapshotOnce(size_t index);
  8052. void ReportExternalAllocationLimitReached();
  8053. void CheckMemoryPressure();
  8054. };
  8055. class V8_EXPORT StartupData {
  8056. public:
  8057. /**
  8058. * Whether the data created can be rehashed and and the hash seed can be
  8059. * recomputed when deserialized.
  8060. * Only valid for StartupData returned by SnapshotCreator::CreateBlob().
  8061. */
  8062. bool CanBeRehashed() const;
  8063. const char* data;
  8064. int raw_size;
  8065. };
  8066. /**
  8067. * EntropySource is used as a callback function when v8 needs a source
  8068. * of entropy.
  8069. */
  8070. typedef bool (*EntropySource)(unsigned char* buffer, size_t length);
  8071. /**
  8072. * ReturnAddressLocationResolver is used as a callback function when v8 is
  8073. * resolving the location of a return address on the stack. Profilers that
  8074. * change the return address on the stack can use this to resolve the stack
  8075. * location to wherever the profiler stashed the original return address.
  8076. *
  8077. * \param return_addr_location A location on stack where a machine
  8078. * return address resides.
  8079. * \returns Either return_addr_location, or else a pointer to the profiler's
  8080. * copy of the original return address.
  8081. *
  8082. * \note The resolver function must not cause garbage collection.
  8083. */
  8084. typedef uintptr_t (*ReturnAddressLocationResolver)(
  8085. uintptr_t return_addr_location);
  8086. /**
  8087. * Container class for static utility functions.
  8088. */
  8089. class V8_EXPORT V8 {
  8090. public:
  8091. /**
  8092. * Hand startup data to V8, in case the embedder has chosen to build
  8093. * V8 with external startup data.
  8094. *
  8095. * Note:
  8096. * - By default the startup data is linked into the V8 library, in which
  8097. * case this function is not meaningful.
  8098. * - If this needs to be called, it needs to be called before V8
  8099. * tries to make use of its built-ins.
  8100. * - To avoid unnecessary copies of data, V8 will point directly into the
  8101. * given data blob, so pretty please keep it around until V8 exit.
  8102. * - Compression of the startup blob might be useful, but needs to
  8103. * handled entirely on the embedders' side.
  8104. * - The call will abort if the data is invalid.
  8105. */
  8106. static void SetSnapshotDataBlob(StartupData* startup_blob);
  8107. /** Set the callback to invoke in case of Dcheck failures. */
  8108. static void SetDcheckErrorHandler(DcheckErrorCallback that);
  8109. /**
  8110. * Sets V8 flags from a string.
  8111. */
  8112. static void SetFlagsFromString(const char* str);
  8113. static void SetFlagsFromString(const char* str, size_t length);
  8114. /**
  8115. * Sets V8 flags from the command line.
  8116. */
  8117. static void SetFlagsFromCommandLine(int* argc,
  8118. char** argv,
  8119. bool remove_flags);
  8120. /** Get the version string. */
  8121. static const char* GetVersion();
  8122. /**
  8123. * Initializes V8. This function needs to be called before the first Isolate
  8124. * is created. It always returns true.
  8125. */
  8126. static bool Initialize();
  8127. /**
  8128. * Allows the host application to provide a callback which can be used
  8129. * as a source of entropy for random number generators.
  8130. */
  8131. static void SetEntropySource(EntropySource source);
  8132. /**
  8133. * Allows the host application to provide a callback that allows v8 to
  8134. * cooperate with a profiler that rewrites return addresses on stack.
  8135. */
  8136. static void SetReturnAddressLocationResolver(
  8137. ReturnAddressLocationResolver return_address_resolver);
  8138. /**
  8139. * Releases any resources used by v8 and stops any utility threads
  8140. * that may be running. Note that disposing v8 is permanent, it
  8141. * cannot be reinitialized.
  8142. *
  8143. * It should generally not be necessary to dispose v8 before exiting
  8144. * a process, this should happen automatically. It is only necessary
  8145. * to use if the process needs the resources taken up by v8.
  8146. */
  8147. static bool Dispose();
  8148. /**
  8149. * Initialize the ICU library bundled with V8. The embedder should only
  8150. * invoke this method when using the bundled ICU. Returns true on success.
  8151. *
  8152. * If V8 was compiled with the ICU data in an external file, the location
  8153. * of the data file has to be provided.
  8154. */
  8155. static bool InitializeICU(const char* icu_data_file = nullptr);
  8156. /**
  8157. * Initialize the ICU library bundled with V8. The embedder should only
  8158. * invoke this method when using the bundled ICU. If V8 was compiled with
  8159. * the ICU data in an external file and when the default location of that
  8160. * file should be used, a path to the executable must be provided.
  8161. * Returns true on success.
  8162. *
  8163. * The default is a file called icudtl.dat side-by-side with the executable.
  8164. *
  8165. * Optionally, the location of the data file can be provided to override the
  8166. * default.
  8167. */
  8168. static bool InitializeICUDefaultLocation(const char* exec_path,
  8169. const char* icu_data_file = nullptr);
  8170. /**
  8171. * Initialize the external startup data. The embedder only needs to
  8172. * invoke this method when external startup data was enabled in a build.
  8173. *
  8174. * If V8 was compiled with the startup data in an external file, then
  8175. * V8 needs to be given those external files during startup. There are
  8176. * three ways to do this:
  8177. * - InitializeExternalStartupData(const char*)
  8178. * This will look in the given directory for the file "snapshot_blob.bin".
  8179. * - InitializeExternalStartupDataFromFile(const char*)
  8180. * As above, but will directly use the given file name.
  8181. * - Call SetSnapshotDataBlob.
  8182. * This will read the blobs from the given data structure and will
  8183. * not perform any file IO.
  8184. */
  8185. static void InitializeExternalStartupData(const char* directory_path);
  8186. static void InitializeExternalStartupDataFromFile(const char* snapshot_blob);
  8187. /**
  8188. * Sets the v8::Platform to use. This should be invoked before V8 is
  8189. * initialized.
  8190. */
  8191. static void InitializePlatform(Platform* platform);
  8192. /**
  8193. * Clears all references to the v8::Platform. This should be invoked after
  8194. * V8 was disposed.
  8195. */
  8196. static void ShutdownPlatform();
  8197. #if V8_OS_POSIX
  8198. /**
  8199. * Give the V8 signal handler a chance to handle a fault.
  8200. *
  8201. * This function determines whether a memory access violation can be recovered
  8202. * by V8. If so, it will return true and modify context to return to a code
  8203. * fragment that can recover from the fault. Otherwise, TryHandleSignal will
  8204. * return false.
  8205. *
  8206. * The parameters to this function correspond to those passed to a Linux
  8207. * signal handler.
  8208. *
  8209. * \param signal_number The signal number.
  8210. *
  8211. * \param info A pointer to the siginfo_t structure provided to the signal
  8212. * handler.
  8213. *
  8214. * \param context The third argument passed to the Linux signal handler, which
  8215. * points to a ucontext_t structure.
  8216. */
  8217. V8_DEPRECATE_SOON("Use TryHandleWebAssemblyTrapPosix")
  8218. static bool TryHandleSignal(int signal_number, void* info, void* context);
  8219. #endif // V8_OS_POSIX
  8220. /**
  8221. * Activate trap-based bounds checking for WebAssembly.
  8222. *
  8223. * \param use_v8_signal_handler Whether V8 should install its own signal
  8224. * handler or rely on the embedder's.
  8225. */
  8226. static bool EnableWebAssemblyTrapHandler(bool use_v8_signal_handler);
  8227. #if defined(V8_OS_WIN)
  8228. /**
  8229. * On Win64, by default V8 does not emit unwinding data for jitted code,
  8230. * which means the OS cannot walk the stack frames and the system Structured
  8231. * Exception Handling (SEH) cannot unwind through V8-generated code:
  8232. * https://code.google.com/p/v8/issues/detail?id=3598.
  8233. *
  8234. * This function allows embedders to register a custom exception handler for
  8235. * exceptions in V8-generated code.
  8236. */
  8237. static void SetUnhandledExceptionCallback(
  8238. UnhandledExceptionCallback unhandled_exception_callback);
  8239. #endif
  8240. /**
  8241. * Get statistics about the shared memory usage.
  8242. */
  8243. static void GetSharedMemoryStatistics(SharedMemoryStatistics* statistics);
  8244. private:
  8245. V8();
  8246. static internal::Address* GlobalizeReference(internal::Isolate* isolate,
  8247. internal::Address* handle);
  8248. static internal::Address* GlobalizeTracedReference(internal::Isolate* isolate,
  8249. internal::Address* handle,
  8250. internal::Address* slot,
  8251. bool has_destructor);
  8252. static void MoveGlobalReference(internal::Address** from,
  8253. internal::Address** to);
  8254. static void MoveTracedGlobalReference(internal::Address** from,
  8255. internal::Address** to);
  8256. static void CopyTracedGlobalReference(const internal::Address* const* from,
  8257. internal::Address** to);
  8258. static internal::Address* CopyGlobalReference(internal::Address* from);
  8259. static void DisposeGlobal(internal::Address* global_handle);
  8260. static void DisposeTracedGlobal(internal::Address* global_handle);
  8261. static void MakeWeak(internal::Address* location, void* data,
  8262. WeakCallbackInfo<void>::Callback weak_callback,
  8263. WeakCallbackType type);
  8264. static void MakeWeak(internal::Address** location_addr);
  8265. static void* ClearWeak(internal::Address* location);
  8266. static void SetFinalizationCallbackTraced(
  8267. internal::Address* location, void* parameter,
  8268. WeakCallbackInfo<void>::Callback callback);
  8269. static void AnnotateStrongRetainer(internal::Address* location,
  8270. const char* label);
  8271. static Value* Eternalize(Isolate* isolate, Value* handle);
  8272. template <class K, class V, class T>
  8273. friend class PersistentValueMapBase;
  8274. static void FromJustIsNothing();
  8275. static void ToLocalEmpty();
  8276. static void InternalFieldOutOfBounds(int index);
  8277. template <class T>
  8278. friend class Global;
  8279. template <class T> friend class Local;
  8280. template <class T>
  8281. friend class MaybeLocal;
  8282. template <class T>
  8283. friend class Maybe;
  8284. template <class T>
  8285. friend class TracedReferenceBase;
  8286. template <class T>
  8287. friend class TracedGlobal;
  8288. template <class T>
  8289. friend class TracedReference;
  8290. template <class T>
  8291. friend class WeakCallbackInfo;
  8292. template <class T> friend class Eternal;
  8293. template <class T> friend class PersistentBase;
  8294. template <class T, class M> friend class Persistent;
  8295. friend class Context;
  8296. };
  8297. /**
  8298. * Helper class to create a snapshot data blob.
  8299. */
  8300. class V8_EXPORT SnapshotCreator {
  8301. public:
  8302. enum class FunctionCodeHandling { kClear, kKeep };
  8303. /**
  8304. * Initialize and enter an isolate, and set it up for serialization.
  8305. * The isolate is either created from scratch or from an existing snapshot.
  8306. * The caller keeps ownership of the argument snapshot.
  8307. * \param existing_blob existing snapshot from which to create this one.
  8308. * \param external_references a null-terminated array of external references
  8309. * that must be equivalent to CreateParams::external_references.
  8310. */
  8311. SnapshotCreator(Isolate* isolate,
  8312. const intptr_t* external_references = nullptr,
  8313. StartupData* existing_blob = nullptr);
  8314. /**
  8315. * Create and enter an isolate, and set it up for serialization.
  8316. * The isolate is either created from scratch or from an existing snapshot.
  8317. * The caller keeps ownership of the argument snapshot.
  8318. * \param existing_blob existing snapshot from which to create this one.
  8319. * \param external_references a null-terminated array of external references
  8320. * that must be equivalent to CreateParams::external_references.
  8321. */
  8322. SnapshotCreator(const intptr_t* external_references = nullptr,
  8323. StartupData* existing_blob = nullptr);
  8324. ~SnapshotCreator();
  8325. /**
  8326. * \returns the isolate prepared by the snapshot creator.
  8327. */
  8328. Isolate* GetIsolate();
  8329. /**
  8330. * Set the default context to be included in the snapshot blob.
  8331. * The snapshot will not contain the global proxy, and we expect one or a
  8332. * global object template to create one, to be provided upon deserialization.
  8333. *
  8334. * \param callback optional callback to serialize internal fields.
  8335. */
  8336. void SetDefaultContext(Local<Context> context,
  8337. SerializeInternalFieldsCallback callback =
  8338. SerializeInternalFieldsCallback());
  8339. /**
  8340. * Add additional context to be included in the snapshot blob.
  8341. * The snapshot will include the global proxy.
  8342. *
  8343. * \param callback optional callback to serialize internal fields.
  8344. *
  8345. * \returns the index of the context in the snapshot blob.
  8346. */
  8347. size_t AddContext(Local<Context> context,
  8348. SerializeInternalFieldsCallback callback =
  8349. SerializeInternalFieldsCallback());
  8350. /**
  8351. * Add a template to be included in the snapshot blob.
  8352. * \returns the index of the template in the snapshot blob.
  8353. */
  8354. V8_DEPRECATED("use AddData instead")
  8355. size_t AddTemplate(Local<Template> template_obj);
  8356. /**
  8357. * Attach arbitrary V8::Data to the context snapshot, which can be retrieved
  8358. * via Context::GetDataFromSnapshot after deserialization. This data does not
  8359. * survive when a new snapshot is created from an existing snapshot.
  8360. * \returns the index for retrieval.
  8361. */
  8362. template <class T>
  8363. V8_INLINE size_t AddData(Local<Context> context, Local<T> object);
  8364. /**
  8365. * Attach arbitrary V8::Data to the isolate snapshot, which can be retrieved
  8366. * via Isolate::GetDataFromSnapshot after deserialization. This data does not
  8367. * survive when a new snapshot is created from an existing snapshot.
  8368. * \returns the index for retrieval.
  8369. */
  8370. template <class T>
  8371. V8_INLINE size_t AddData(Local<T> object);
  8372. /**
  8373. * Created a snapshot data blob.
  8374. * This must not be called from within a handle scope.
  8375. * \param function_code_handling whether to include compiled function code
  8376. * in the snapshot.
  8377. * \returns { nullptr, 0 } on failure, and a startup snapshot on success. The
  8378. * caller acquires ownership of the data array in the return value.
  8379. */
  8380. StartupData CreateBlob(FunctionCodeHandling function_code_handling);
  8381. // Disallow copying and assigning.
  8382. SnapshotCreator(const SnapshotCreator&) = delete;
  8383. void operator=(const SnapshotCreator&) = delete;
  8384. private:
  8385. size_t AddData(Local<Context> context, internal::Address object);
  8386. size_t AddData(internal::Address object);
  8387. void* data_;
  8388. };
  8389. /**
  8390. * A simple Maybe type, representing an object which may or may not have a
  8391. * value, see https://hackage.haskell.org/package/base/docs/Data-Maybe.html.
  8392. *
  8393. * If an API method returns a Maybe<>, the API method can potentially fail
  8394. * either because an exception is thrown, or because an exception is pending,
  8395. * e.g. because a previous API call threw an exception that hasn't been caught
  8396. * yet, or because a TerminateExecution exception was thrown. In that case, a
  8397. * "Nothing" value is returned.
  8398. */
  8399. template <class T>
  8400. class Maybe {
  8401. public:
  8402. V8_INLINE bool IsNothing() const { return !has_value_; }
  8403. V8_INLINE bool IsJust() const { return has_value_; }
  8404. /**
  8405. * An alias for |FromJust|. Will crash if the Maybe<> is nothing.
  8406. */
  8407. V8_INLINE T ToChecked() const { return FromJust(); }
  8408. /**
  8409. * Short-hand for ToChecked(), which doesn't return a value. To be used, where
  8410. * the actual value of the Maybe is not needed like Object::Set.
  8411. */
  8412. V8_INLINE void Check() const {
  8413. if (V8_UNLIKELY(!IsJust())) V8::FromJustIsNothing();
  8414. }
  8415. /**
  8416. * Converts this Maybe<> to a value of type T. If this Maybe<> is
  8417. * nothing (empty), |false| is returned and |out| is left untouched.
  8418. */
  8419. V8_WARN_UNUSED_RESULT V8_INLINE bool To(T* out) const {
  8420. if (V8_LIKELY(IsJust())) *out = value_;
  8421. return IsJust();
  8422. }
  8423. /**
  8424. * Converts this Maybe<> to a value of type T. If this Maybe<> is
  8425. * nothing (empty), V8 will crash the process.
  8426. */
  8427. V8_INLINE T FromJust() const {
  8428. if (V8_UNLIKELY(!IsJust())) V8::FromJustIsNothing();
  8429. return value_;
  8430. }
  8431. /**
  8432. * Converts this Maybe<> to a value of type T, using a default value if this
  8433. * Maybe<> is nothing (empty).
  8434. */
  8435. V8_INLINE T FromMaybe(const T& default_value) const {
  8436. return has_value_ ? value_ : default_value;
  8437. }
  8438. V8_INLINE bool operator==(const Maybe& other) const {
  8439. return (IsJust() == other.IsJust()) &&
  8440. (!IsJust() || FromJust() == other.FromJust());
  8441. }
  8442. V8_INLINE bool operator!=(const Maybe& other) const {
  8443. return !operator==(other);
  8444. }
  8445. private:
  8446. Maybe() : has_value_(false) {}
  8447. explicit Maybe(const T& t) : has_value_(true), value_(t) {}
  8448. bool has_value_;
  8449. T value_;
  8450. template <class U>
  8451. friend Maybe<U> Nothing();
  8452. template <class U>
  8453. friend Maybe<U> Just(const U& u);
  8454. };
  8455. template <class T>
  8456. inline Maybe<T> Nothing() {
  8457. return Maybe<T>();
  8458. }
  8459. template <class T>
  8460. inline Maybe<T> Just(const T& t) {
  8461. return Maybe<T>(t);
  8462. }
  8463. // A template specialization of Maybe<T> for the case of T = void.
  8464. template <>
  8465. class Maybe<void> {
  8466. public:
  8467. V8_INLINE bool IsNothing() const { return !is_valid_; }
  8468. V8_INLINE bool IsJust() const { return is_valid_; }
  8469. V8_INLINE bool operator==(const Maybe& other) const {
  8470. return IsJust() == other.IsJust();
  8471. }
  8472. V8_INLINE bool operator!=(const Maybe& other) const {
  8473. return !operator==(other);
  8474. }
  8475. private:
  8476. struct JustTag {};
  8477. Maybe() : is_valid_(false) {}
  8478. explicit Maybe(JustTag) : is_valid_(true) {}
  8479. bool is_valid_;
  8480. template <class U>
  8481. friend Maybe<U> Nothing();
  8482. friend Maybe<void> JustVoid();
  8483. };
  8484. inline Maybe<void> JustVoid() { return Maybe<void>(Maybe<void>::JustTag()); }
  8485. /**
  8486. * An external exception handler.
  8487. */
  8488. class V8_EXPORT TryCatch {
  8489. public:
  8490. /**
  8491. * Creates a new try/catch block and registers it with v8. Note that
  8492. * all TryCatch blocks should be stack allocated because the memory
  8493. * location itself is compared against JavaScript try/catch blocks.
  8494. */
  8495. explicit TryCatch(Isolate* isolate);
  8496. /**
  8497. * Unregisters and deletes this try/catch block.
  8498. */
  8499. ~TryCatch();
  8500. /**
  8501. * Returns true if an exception has been caught by this try/catch block.
  8502. */
  8503. bool HasCaught() const;
  8504. /**
  8505. * For certain types of exceptions, it makes no sense to continue execution.
  8506. *
  8507. * If CanContinue returns false, the correct action is to perform any C++
  8508. * cleanup needed and then return. If CanContinue returns false and
  8509. * HasTerminated returns true, it is possible to call
  8510. * CancelTerminateExecution in order to continue calling into the engine.
  8511. */
  8512. bool CanContinue() const;
  8513. /**
  8514. * Returns true if an exception has been caught due to script execution
  8515. * being terminated.
  8516. *
  8517. * There is no JavaScript representation of an execution termination
  8518. * exception. Such exceptions are thrown when the TerminateExecution
  8519. * methods are called to terminate a long-running script.
  8520. *
  8521. * If such an exception has been thrown, HasTerminated will return true,
  8522. * indicating that it is possible to call CancelTerminateExecution in order
  8523. * to continue calling into the engine.
  8524. */
  8525. bool HasTerminated() const;
  8526. /**
  8527. * Throws the exception caught by this TryCatch in a way that avoids
  8528. * it being caught again by this same TryCatch. As with ThrowException
  8529. * it is illegal to execute any JavaScript operations after calling
  8530. * ReThrow; the caller must return immediately to where the exception
  8531. * is caught.
  8532. */
  8533. Local<Value> ReThrow();
  8534. /**
  8535. * Returns the exception caught by this try/catch block. If no exception has
  8536. * been caught an empty handle is returned.
  8537. *
  8538. * The returned handle is valid until this TryCatch block has been destroyed.
  8539. */
  8540. Local<Value> Exception() const;
  8541. /**
  8542. * Returns the .stack property of the thrown object. If no .stack
  8543. * property is present an empty handle is returned.
  8544. */
  8545. V8_WARN_UNUSED_RESULT MaybeLocal<Value> StackTrace(
  8546. Local<Context> context) const;
  8547. /**
  8548. * Returns the message associated with this exception. If there is
  8549. * no message associated an empty handle is returned.
  8550. *
  8551. * The returned handle is valid until this TryCatch block has been
  8552. * destroyed.
  8553. */
  8554. Local<v8::Message> Message() const;
  8555. /**
  8556. * Clears any exceptions that may have been caught by this try/catch block.
  8557. * After this method has been called, HasCaught() will return false. Cancels
  8558. * the scheduled exception if it is caught and ReThrow() is not called before.
  8559. *
  8560. * It is not necessary to clear a try/catch block before using it again; if
  8561. * another exception is thrown the previously caught exception will just be
  8562. * overwritten. However, it is often a good idea since it makes it easier
  8563. * to determine which operation threw a given exception.
  8564. */
  8565. void Reset();
  8566. /**
  8567. * Set verbosity of the external exception handler.
  8568. *
  8569. * By default, exceptions that are caught by an external exception
  8570. * handler are not reported. Call SetVerbose with true on an
  8571. * external exception handler to have exceptions caught by the
  8572. * handler reported as if they were not caught.
  8573. */
  8574. void SetVerbose(bool value);
  8575. /**
  8576. * Returns true if verbosity is enabled.
  8577. */
  8578. bool IsVerbose() const;
  8579. /**
  8580. * Set whether or not this TryCatch should capture a Message object
  8581. * which holds source information about where the exception
  8582. * occurred. True by default.
  8583. */
  8584. void SetCaptureMessage(bool value);
  8585. /**
  8586. * There are cases when the raw address of C++ TryCatch object cannot be
  8587. * used for comparisons with addresses into the JS stack. The cases are:
  8588. * 1) ARM, ARM64 and MIPS simulators which have separate JS stack.
  8589. * 2) Address sanitizer allocates local C++ object in the heap when
  8590. * UseAfterReturn mode is enabled.
  8591. * This method returns address that can be used for comparisons with
  8592. * addresses into the JS stack. When neither simulator nor ASAN's
  8593. * UseAfterReturn is enabled, then the address returned will be the address
  8594. * of the C++ try catch handler itself.
  8595. */
  8596. static void* JSStackComparableAddress(TryCatch* handler) {
  8597. if (handler == nullptr) return nullptr;
  8598. return handler->js_stack_comparable_address_;
  8599. }
  8600. TryCatch(const TryCatch&) = delete;
  8601. void operator=(const TryCatch&) = delete;
  8602. private:
  8603. // Declaring operator new and delete as deleted is not spec compliant.
  8604. // Therefore declare them private instead to disable dynamic alloc
  8605. void* operator new(size_t size);
  8606. void* operator new[](size_t size);
  8607. void operator delete(void*, size_t);
  8608. void operator delete[](void*, size_t);
  8609. void ResetInternal();
  8610. internal::Isolate* isolate_;
  8611. TryCatch* next_;
  8612. void* exception_;
  8613. void* message_obj_;
  8614. void* js_stack_comparable_address_;
  8615. bool is_verbose_ : 1;
  8616. bool can_continue_ : 1;
  8617. bool capture_message_ : 1;
  8618. bool rethrow_ : 1;
  8619. bool has_terminated_ : 1;
  8620. friend class internal::Isolate;
  8621. };
  8622. // --- Context ---
  8623. /**
  8624. * A container for extension names.
  8625. */
  8626. class V8_EXPORT ExtensionConfiguration {
  8627. public:
  8628. ExtensionConfiguration() : name_count_(0), names_(nullptr) {}
  8629. ExtensionConfiguration(int name_count, const char* names[])
  8630. : name_count_(name_count), names_(names) { }
  8631. const char** begin() const { return &names_[0]; }
  8632. const char** end() const { return &names_[name_count_]; }
  8633. private:
  8634. const int name_count_;
  8635. const char** names_;
  8636. };
  8637. /**
  8638. * A sandboxed execution context with its own set of built-in objects
  8639. * and functions.
  8640. */
  8641. class V8_EXPORT Context {
  8642. public:
  8643. /**
  8644. * Returns the global proxy object.
  8645. *
  8646. * Global proxy object is a thin wrapper whose prototype points to actual
  8647. * context's global object with the properties like Object, etc. This is done
  8648. * that way for security reasons (for more details see
  8649. * https://wiki.mozilla.org/Gecko:SplitWindow).
  8650. *
  8651. * Please note that changes to global proxy object prototype most probably
  8652. * would break VM---v8 expects only global object as a prototype of global
  8653. * proxy object.
  8654. */
  8655. Local<Object> Global();
  8656. /**
  8657. * Detaches the global object from its context before
  8658. * the global object can be reused to create a new context.
  8659. */
  8660. void DetachGlobal();
  8661. /**
  8662. * Reason for detaching a window.
  8663. */
  8664. enum DetachedWindowReason {
  8665. kWindowNotDetached = 0,
  8666. kDetachedWindowByNavigation,
  8667. kDetachedWindowByClosing,
  8668. kDetachedWindowByOtherReason
  8669. };
  8670. /**
  8671. * Sets a reason for detaching window, for reporting purposes.
  8672. *
  8673. * This API is experimental and may change or be deleted. Do not use!
  8674. *
  8675. * A window is a Blink concept. This API marks the context as backing
  8676. * a detached window. This doesn't necessarily mean that the context is
  8677. * detached.
  8678. *
  8679. * Every time a JS function is called within a context that has a non-zero
  8680. * DetachedWindowReason, Runtime::kReportDetachedWindowAccess is invoked,
  8681. * which will report this call to Blink via a callback, which in turn can
  8682. * report number of such calls via UKM metrics.
  8683. */
  8684. void SetDetachedWindowReason(DetachedWindowReason reason);
  8685. /**
  8686. * Creates a new context and returns a handle to the newly allocated
  8687. * context.
  8688. *
  8689. * \param isolate The isolate in which to create the context.
  8690. *
  8691. * \param extensions An optional extension configuration containing
  8692. * the extensions to be installed in the newly created context.
  8693. *
  8694. * \param global_template An optional object template from which the
  8695. * global object for the newly created context will be created.
  8696. *
  8697. * \param global_object An optional global object to be reused for
  8698. * the newly created context. This global object must have been
  8699. * created by a previous call to Context::New with the same global
  8700. * template. The state of the global object will be completely reset
  8701. * and only object identify will remain.
  8702. */
  8703. static Local<Context> New(
  8704. Isolate* isolate, ExtensionConfiguration* extensions = nullptr,
  8705. MaybeLocal<ObjectTemplate> global_template = MaybeLocal<ObjectTemplate>(),
  8706. MaybeLocal<Value> global_object = MaybeLocal<Value>(),
  8707. DeserializeInternalFieldsCallback internal_fields_deserializer =
  8708. DeserializeInternalFieldsCallback(),
  8709. MicrotaskQueue* microtask_queue = nullptr);
  8710. /**
  8711. * Create a new context from a (non-default) context snapshot. There
  8712. * is no way to provide a global object template since we do not create
  8713. * a new global object from template, but we can reuse a global object.
  8714. *
  8715. * \param isolate See v8::Context::New.
  8716. *
  8717. * \param context_snapshot_index The index of the context snapshot to
  8718. * deserialize from. Use v8::Context::New for the default snapshot.
  8719. *
  8720. * \param embedder_fields_deserializer Optional callback to deserialize
  8721. * internal fields. It should match the SerializeInternalFieldCallback used
  8722. * to serialize.
  8723. *
  8724. * \param extensions See v8::Context::New.
  8725. *
  8726. * \param global_object See v8::Context::New.
  8727. */
  8728. static MaybeLocal<Context> FromSnapshot(
  8729. Isolate* isolate, size_t context_snapshot_index,
  8730. DeserializeInternalFieldsCallback embedder_fields_deserializer =
  8731. DeserializeInternalFieldsCallback(),
  8732. ExtensionConfiguration* extensions = nullptr,
  8733. MaybeLocal<Value> global_object = MaybeLocal<Value>(),
  8734. MicrotaskQueue* microtask_queue = nullptr);
  8735. /**
  8736. * Returns an global object that isn't backed by an actual context.
  8737. *
  8738. * The global template needs to have access checks with handlers installed.
  8739. * If an existing global object is passed in, the global object is detached
  8740. * from its context.
  8741. *
  8742. * Note that this is different from a detached context where all accesses to
  8743. * the global proxy will fail. Instead, the access check handlers are invoked.
  8744. *
  8745. * It is also not possible to detach an object returned by this method.
  8746. * Instead, the access check handlers need to return nothing to achieve the
  8747. * same effect.
  8748. *
  8749. * It is possible, however, to create a new context from the global object
  8750. * returned by this method.
  8751. */
  8752. static MaybeLocal<Object> NewRemoteContext(
  8753. Isolate* isolate, Local<ObjectTemplate> global_template,
  8754. MaybeLocal<Value> global_object = MaybeLocal<Value>());
  8755. /**
  8756. * Sets the security token for the context. To access an object in
  8757. * another context, the security tokens must match.
  8758. */
  8759. void SetSecurityToken(Local<Value> token);
  8760. /** Restores the security token to the default value. */
  8761. void UseDefaultSecurityToken();
  8762. /** Returns the security token of this context.*/
  8763. Local<Value> GetSecurityToken();
  8764. /**
  8765. * Enter this context. After entering a context, all code compiled
  8766. * and run is compiled and run in this context. If another context
  8767. * is already entered, this old context is saved so it can be
  8768. * restored when the new context is exited.
  8769. */
  8770. void Enter();
  8771. /**
  8772. * Exit this context. Exiting the current context restores the
  8773. * context that was in place when entering the current context.
  8774. */
  8775. void Exit();
  8776. /** Returns an isolate associated with a current context. */
  8777. Isolate* GetIsolate();
  8778. /**
  8779. * The field at kDebugIdIndex used to be reserved for the inspector.
  8780. * It now serves no purpose.
  8781. */
  8782. enum EmbedderDataFields { kDebugIdIndex = 0 };
  8783. /**
  8784. * Return the number of fields allocated for embedder data.
  8785. */
  8786. uint32_t GetNumberOfEmbedderDataFields();
  8787. /**
  8788. * Gets the embedder data with the given index, which must have been set by a
  8789. * previous call to SetEmbedderData with the same index.
  8790. */
  8791. V8_INLINE Local<Value> GetEmbedderData(int index);
  8792. /**
  8793. * Gets the binding object used by V8 extras. Extra natives get a reference
  8794. * to this object and can use it to "export" functionality by adding
  8795. * properties. Extra natives can also "import" functionality by accessing
  8796. * properties added by the embedder using the V8 API.
  8797. */
  8798. Local<Object> GetExtrasBindingObject();
  8799. /**
  8800. * Sets the embedder data with the given index, growing the data as
  8801. * needed. Note that index 0 currently has a special meaning for Chrome's
  8802. * debugger.
  8803. */
  8804. void SetEmbedderData(int index, Local<Value> value);
  8805. /**
  8806. * Gets a 2-byte-aligned native pointer from the embedder data with the given
  8807. * index, which must have been set by a previous call to
  8808. * SetAlignedPointerInEmbedderData with the same index. Note that index 0
  8809. * currently has a special meaning for Chrome's debugger.
  8810. */
  8811. V8_INLINE void* GetAlignedPointerFromEmbedderData(int index);
  8812. /**
  8813. * Sets a 2-byte-aligned native pointer in the embedder data with the given
  8814. * index, growing the data as needed. Note that index 0 currently has a
  8815. * special meaning for Chrome's debugger.
  8816. */
  8817. void SetAlignedPointerInEmbedderData(int index, void* value);
  8818. /**
  8819. * Control whether code generation from strings is allowed. Calling
  8820. * this method with false will disable 'eval' and the 'Function'
  8821. * constructor for code running in this context. If 'eval' or the
  8822. * 'Function' constructor are used an exception will be thrown.
  8823. *
  8824. * If code generation from strings is not allowed the
  8825. * V8::AllowCodeGenerationFromStrings callback will be invoked if
  8826. * set before blocking the call to 'eval' or the 'Function'
  8827. * constructor. If that callback returns true, the call will be
  8828. * allowed, otherwise an exception will be thrown. If no callback is
  8829. * set an exception will be thrown.
  8830. */
  8831. void AllowCodeGenerationFromStrings(bool allow);
  8832. /**
  8833. * Returns true if code generation from strings is allowed for the context.
  8834. * For more details see AllowCodeGenerationFromStrings(bool) documentation.
  8835. */
  8836. bool IsCodeGenerationFromStringsAllowed();
  8837. /**
  8838. * Sets the error description for the exception that is thrown when
  8839. * code generation from strings is not allowed and 'eval' or the 'Function'
  8840. * constructor are called.
  8841. */
  8842. void SetErrorMessageForCodeGenerationFromStrings(Local<String> message);
  8843. /**
  8844. * Return data that was previously attached to the context snapshot via
  8845. * SnapshotCreator, and removes the reference to it.
  8846. * Repeated call with the same index returns an empty MaybeLocal.
  8847. */
  8848. template <class T>
  8849. V8_INLINE MaybeLocal<T> GetDataFromSnapshotOnce(size_t index);
  8850. /**
  8851. * If callback is set, abort any attempt to execute JavaScript in this
  8852. * context, call the specified callback, and throw an exception.
  8853. * To unset abort, pass nullptr as callback.
  8854. */
  8855. typedef void (*AbortScriptExecutionCallback)(Isolate* isolate,
  8856. Local<Context> context);
  8857. void SetAbortScriptExecution(AbortScriptExecutionCallback callback);
  8858. /**
  8859. * Stack-allocated class which sets the execution context for all
  8860. * operations executed within a local scope.
  8861. */
  8862. class Scope {
  8863. public:
  8864. explicit V8_INLINE Scope(Local<Context> context) : context_(context) {
  8865. context_->Enter();
  8866. }
  8867. V8_INLINE ~Scope() { context_->Exit(); }
  8868. private:
  8869. Local<Context> context_;
  8870. };
  8871. /**
  8872. * Stack-allocated class to support the backup incumbent settings object
  8873. * stack.
  8874. * https://html.spec.whatwg.org/multipage/webappapis.html#backup-incumbent-settings-object-stack
  8875. */
  8876. class V8_EXPORT BackupIncumbentScope final {
  8877. public:
  8878. /**
  8879. * |backup_incumbent_context| is pushed onto the backup incumbent settings
  8880. * object stack.
  8881. */
  8882. explicit BackupIncumbentScope(Local<Context> backup_incumbent_context);
  8883. ~BackupIncumbentScope();
  8884. /**
  8885. * Returns address that is comparable with JS stack address. Note that JS
  8886. * stack may be allocated separately from the native stack. See also
  8887. * |TryCatch::JSStackComparableAddress| for details.
  8888. */
  8889. uintptr_t JSStackComparableAddress() const {
  8890. return js_stack_comparable_address_;
  8891. }
  8892. private:
  8893. friend class internal::Isolate;
  8894. Local<Context> backup_incumbent_context_;
  8895. uintptr_t js_stack_comparable_address_ = 0;
  8896. const BackupIncumbentScope* prev_ = nullptr;
  8897. };
  8898. private:
  8899. friend class Value;
  8900. friend class Script;
  8901. friend class Object;
  8902. friend class Function;
  8903. internal::Address* GetDataFromSnapshotOnce(size_t index);
  8904. Local<Value> SlowGetEmbedderData(int index);
  8905. void* SlowGetAlignedPointerFromEmbedderData(int index);
  8906. };
  8907. /**
  8908. * Multiple threads in V8 are allowed, but only one thread at a time is allowed
  8909. * to use any given V8 isolate, see the comments in the Isolate class. The
  8910. * definition of 'using a V8 isolate' includes accessing handles or holding onto
  8911. * object pointers obtained from V8 handles while in the particular V8 isolate.
  8912. * It is up to the user of V8 to ensure, perhaps with locking, that this
  8913. * constraint is not violated. In addition to any other synchronization
  8914. * mechanism that may be used, the v8::Locker and v8::Unlocker classes must be
  8915. * used to signal thread switches to V8.
  8916. *
  8917. * v8::Locker is a scoped lock object. While it's active, i.e. between its
  8918. * construction and destruction, the current thread is allowed to use the locked
  8919. * isolate. V8 guarantees that an isolate can be locked by at most one thread at
  8920. * any time. In other words, the scope of a v8::Locker is a critical section.
  8921. *
  8922. * Sample usage:
  8923. * \code
  8924. * ...
  8925. * {
  8926. * v8::Locker locker(isolate);
  8927. * v8::Isolate::Scope isolate_scope(isolate);
  8928. * ...
  8929. * // Code using V8 and isolate goes here.
  8930. * ...
  8931. * } // Destructor called here
  8932. * \endcode
  8933. *
  8934. * If you wish to stop using V8 in a thread A you can do this either by
  8935. * destroying the v8::Locker object as above or by constructing a v8::Unlocker
  8936. * object:
  8937. *
  8938. * \code
  8939. * {
  8940. * isolate->Exit();
  8941. * v8::Unlocker unlocker(isolate);
  8942. * ...
  8943. * // Code not using V8 goes here while V8 can run in another thread.
  8944. * ...
  8945. * } // Destructor called here.
  8946. * isolate->Enter();
  8947. * \endcode
  8948. *
  8949. * The Unlocker object is intended for use in a long-running callback from V8,
  8950. * where you want to release the V8 lock for other threads to use.
  8951. *
  8952. * The v8::Locker is a recursive lock, i.e. you can lock more than once in a
  8953. * given thread. This can be useful if you have code that can be called either
  8954. * from code that holds the lock or from code that does not. The Unlocker is
  8955. * not recursive so you can not have several Unlockers on the stack at once, and
  8956. * you can not use an Unlocker in a thread that is not inside a Locker's scope.
  8957. *
  8958. * An unlocker will unlock several lockers if it has to and reinstate the
  8959. * correct depth of locking on its destruction, e.g.:
  8960. *
  8961. * \code
  8962. * // V8 not locked.
  8963. * {
  8964. * v8::Locker locker(isolate);
  8965. * Isolate::Scope isolate_scope(isolate);
  8966. * // V8 locked.
  8967. * {
  8968. * v8::Locker another_locker(isolate);
  8969. * // V8 still locked (2 levels).
  8970. * {
  8971. * isolate->Exit();
  8972. * v8::Unlocker unlocker(isolate);
  8973. * // V8 not locked.
  8974. * }
  8975. * isolate->Enter();
  8976. * // V8 locked again (2 levels).
  8977. * }
  8978. * // V8 still locked (1 level).
  8979. * }
  8980. * // V8 Now no longer locked.
  8981. * \endcode
  8982. */
  8983. class V8_EXPORT Unlocker {
  8984. public:
  8985. /**
  8986. * Initialize Unlocker for a given Isolate.
  8987. */
  8988. V8_INLINE explicit Unlocker(Isolate* isolate) { Initialize(isolate); }
  8989. ~Unlocker();
  8990. private:
  8991. void Initialize(Isolate* isolate);
  8992. internal::Isolate* isolate_;
  8993. };
  8994. class V8_EXPORT Locker {
  8995. public:
  8996. /**
  8997. * Initialize Locker for a given Isolate.
  8998. */
  8999. V8_INLINE explicit Locker(Isolate* isolate) { Initialize(isolate); }
  9000. ~Locker();
  9001. /**
  9002. * Returns whether or not the locker for a given isolate, is locked by the
  9003. * current thread.
  9004. */
  9005. static bool IsLocked(Isolate* isolate);
  9006. /**
  9007. * Returns whether v8::Locker is being used by this V8 instance.
  9008. */
  9009. static bool IsActive();
  9010. // Disallow copying and assigning.
  9011. Locker(const Locker&) = delete;
  9012. void operator=(const Locker&) = delete;
  9013. private:
  9014. void Initialize(Isolate* isolate);
  9015. bool has_lock_;
  9016. bool top_level_;
  9017. internal::Isolate* isolate_;
  9018. };
  9019. /**
  9020. * Various helpers for skipping over V8 frames in a given stack.
  9021. *
  9022. * The unwinder API is only supported on the x64 architecture.
  9023. */
  9024. class V8_EXPORT Unwinder {
  9025. public:
  9026. /**
  9027. * Attempt to unwind the stack to the most recent C++ frame. This function is
  9028. * signal-safe and does not access any V8 state and thus doesn't require an
  9029. * Isolate.
  9030. *
  9031. * The unwinder needs to know the location of the JS Entry Stub (a piece of
  9032. * code that is run when C++ code calls into generated JS code). This is used
  9033. * for edge cases where the current frame is being constructed or torn down
  9034. * when the stack sample occurs.
  9035. *
  9036. * The unwinder also needs the virtual memory range of all possible V8 code
  9037. * objects. There are two ranges required - the heap code range and the range
  9038. * for code embedded in the binary. The V8 API provides all required inputs
  9039. * via an UnwindState object through the Isolate::GetUnwindState() API. These
  9040. * values will not change after Isolate initialization, so the same
  9041. * |unwind_state| can be used for multiple calls.
  9042. *
  9043. * \param unwind_state Input state for the Isolate that the stack comes from.
  9044. * \param register_state The current registers. This is an in-out param that
  9045. * will be overwritten with the register values after unwinding, on success.
  9046. * \param stack_base The resulting stack pointer and frame pointer values are
  9047. * bounds-checked against the stack_base and the original stack pointer value
  9048. * to ensure that they are valid locations in the given stack. If these values
  9049. * or any intermediate frame pointer values used during unwinding are ever out
  9050. * of these bounds, unwinding will fail.
  9051. *
  9052. * \return True on success.
  9053. */
  9054. static bool TryUnwindV8Frames(const UnwindState& unwind_state,
  9055. RegisterState* register_state,
  9056. const void* stack_base);
  9057. /**
  9058. * Whether the PC is within the V8 code range represented by code_range or
  9059. * embedded_code_range in |unwind_state|.
  9060. *
  9061. * If this returns false, then calling UnwindV8Frames() with the same PC
  9062. * and unwind_state will always fail. If it returns true, then unwinding may
  9063. * (but not necessarily) be successful.
  9064. */
  9065. static bool PCIsInV8(const UnwindState& unwind_state, void* pc);
  9066. };
  9067. // --- Implementation ---
  9068. template <class T>
  9069. Local<T> Local<T>::New(Isolate* isolate, Local<T> that) {
  9070. return New(isolate, that.val_);
  9071. }
  9072. template <class T>
  9073. Local<T> Local<T>::New(Isolate* isolate, const PersistentBase<T>& that) {
  9074. return New(isolate, that.val_);
  9075. }
  9076. template <class T>
  9077. Local<T> Local<T>::New(Isolate* isolate, const TracedReferenceBase<T>& that) {
  9078. return New(isolate, that.val_);
  9079. }
  9080. template <class T>
  9081. Local<T> Local<T>::New(Isolate* isolate, T* that) {
  9082. if (that == nullptr) return Local<T>();
  9083. T* that_ptr = that;
  9084. internal::Address* p = reinterpret_cast<internal::Address*>(that_ptr);
  9085. return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
  9086. reinterpret_cast<internal::Isolate*>(isolate), *p)));
  9087. }
  9088. template<class T>
  9089. template<class S>
  9090. void Eternal<T>::Set(Isolate* isolate, Local<S> handle) {
  9091. TYPE_CHECK(T, S);
  9092. val_ = reinterpret_cast<T*>(
  9093. V8::Eternalize(isolate, reinterpret_cast<Value*>(*handle)));
  9094. }
  9095. template <class T>
  9096. Local<T> Eternal<T>::Get(Isolate* isolate) const {
  9097. // The eternal handle will never go away, so as with the roots, we don't even
  9098. // need to open a handle.
  9099. return Local<T>(val_);
  9100. }
  9101. template <class T>
  9102. Local<T> MaybeLocal<T>::ToLocalChecked() {
  9103. if (V8_UNLIKELY(val_ == nullptr)) V8::ToLocalEmpty();
  9104. return Local<T>(val_);
  9105. }
  9106. template <class T>
  9107. void* WeakCallbackInfo<T>::GetInternalField(int index) const {
  9108. #ifdef V8_ENABLE_CHECKS
  9109. if (index < 0 || index >= kEmbedderFieldsInWeakCallback) {
  9110. V8::InternalFieldOutOfBounds(index);
  9111. }
  9112. #endif
  9113. return embedder_fields_[index];
  9114. }
  9115. template <class T>
  9116. T* PersistentBase<T>::New(Isolate* isolate, T* that) {
  9117. if (that == nullptr) return nullptr;
  9118. internal::Address* p = reinterpret_cast<internal::Address*>(that);
  9119. return reinterpret_cast<T*>(
  9120. V8::GlobalizeReference(reinterpret_cast<internal::Isolate*>(isolate),
  9121. p));
  9122. }
  9123. template <class T, class M>
  9124. template <class S, class M2>
  9125. void Persistent<T, M>::Copy(const Persistent<S, M2>& that) {
  9126. TYPE_CHECK(T, S);
  9127. this->Reset();
  9128. if (that.IsEmpty()) return;
  9129. internal::Address* p = reinterpret_cast<internal::Address*>(that.val_);
  9130. this->val_ = reinterpret_cast<T*>(V8::CopyGlobalReference(p));
  9131. M::Copy(that, this);
  9132. }
  9133. template <class T>
  9134. bool PersistentBase<T>::IsWeak() const {
  9135. typedef internal::Internals I;
  9136. if (this->IsEmpty()) return false;
  9137. return I::GetNodeState(reinterpret_cast<internal::Address*>(this->val_)) ==
  9138. I::kNodeStateIsWeakValue;
  9139. }
  9140. template <class T>
  9141. void PersistentBase<T>::Reset() {
  9142. if (this->IsEmpty()) return;
  9143. V8::DisposeGlobal(reinterpret_cast<internal::Address*>(this->val_));
  9144. val_ = nullptr;
  9145. }
  9146. template <class T>
  9147. template <class S>
  9148. void PersistentBase<T>::Reset(Isolate* isolate, const Local<S>& other) {
  9149. TYPE_CHECK(T, S);
  9150. Reset();
  9151. if (other.IsEmpty()) return;
  9152. this->val_ = New(isolate, other.val_);
  9153. }
  9154. template <class T>
  9155. template <class S>
  9156. void PersistentBase<T>::Reset(Isolate* isolate,
  9157. const PersistentBase<S>& other) {
  9158. TYPE_CHECK(T, S);
  9159. Reset();
  9160. if (other.IsEmpty()) return;
  9161. this->val_ = New(isolate, other.val_);
  9162. }
  9163. template <class T>
  9164. template <typename P>
  9165. V8_INLINE void PersistentBase<T>::SetWeak(
  9166. P* parameter, typename WeakCallbackInfo<P>::Callback callback,
  9167. WeakCallbackType type) {
  9168. typedef typename WeakCallbackInfo<void>::Callback Callback;
  9169. V8::MakeWeak(reinterpret_cast<internal::Address*>(this->val_), parameter,
  9170. reinterpret_cast<Callback>(callback), type);
  9171. }
  9172. template <class T>
  9173. void PersistentBase<T>::SetWeak() {
  9174. V8::MakeWeak(reinterpret_cast<internal::Address**>(&this->val_));
  9175. }
  9176. template <class T>
  9177. template <typename P>
  9178. P* PersistentBase<T>::ClearWeak() {
  9179. return reinterpret_cast<P*>(
  9180. V8::ClearWeak(reinterpret_cast<internal::Address*>(this->val_)));
  9181. }
  9182. template <class T>
  9183. void PersistentBase<T>::AnnotateStrongRetainer(const char* label) {
  9184. V8::AnnotateStrongRetainer(reinterpret_cast<internal::Address*>(this->val_),
  9185. label);
  9186. }
  9187. template <class T>
  9188. void PersistentBase<T>::SetWrapperClassId(uint16_t class_id) {
  9189. typedef internal::Internals I;
  9190. if (this->IsEmpty()) return;
  9191. internal::Address* obj = reinterpret_cast<internal::Address*>(this->val_);
  9192. uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
  9193. *reinterpret_cast<uint16_t*>(addr) = class_id;
  9194. }
  9195. template <class T>
  9196. uint16_t PersistentBase<T>::WrapperClassId() const {
  9197. typedef internal::Internals I;
  9198. if (this->IsEmpty()) return 0;
  9199. internal::Address* obj = reinterpret_cast<internal::Address*>(this->val_);
  9200. uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
  9201. return *reinterpret_cast<uint16_t*>(addr);
  9202. }
  9203. template <class T>
  9204. Global<T>::Global(Global&& other) : PersistentBase<T>(other.val_) {
  9205. if (other.val_ != nullptr) {
  9206. V8::MoveGlobalReference(reinterpret_cast<internal::Address**>(&other.val_),
  9207. reinterpret_cast<internal::Address**>(&this->val_));
  9208. other.val_ = nullptr;
  9209. }
  9210. }
  9211. template <class T>
  9212. template <class S>
  9213. Global<T>& Global<T>::operator=(Global<S>&& rhs) {
  9214. TYPE_CHECK(T, S);
  9215. if (this != &rhs) {
  9216. this->Reset();
  9217. if (rhs.val_ != nullptr) {
  9218. this->val_ = rhs.val_;
  9219. V8::MoveGlobalReference(
  9220. reinterpret_cast<internal::Address**>(&rhs.val_),
  9221. reinterpret_cast<internal::Address**>(&this->val_));
  9222. rhs.val_ = nullptr;
  9223. }
  9224. }
  9225. return *this;
  9226. }
  9227. template <class T>
  9228. T* TracedReferenceBase<T>::New(Isolate* isolate, T* that, void* slot,
  9229. DestructionMode destruction_mode) {
  9230. if (that == nullptr) return nullptr;
  9231. internal::Address* p = reinterpret_cast<internal::Address*>(that);
  9232. return reinterpret_cast<T*>(V8::GlobalizeTracedReference(
  9233. reinterpret_cast<internal::Isolate*>(isolate), p,
  9234. reinterpret_cast<internal::Address*>(slot),
  9235. destruction_mode == kWithDestructor));
  9236. }
  9237. template <class T>
  9238. void TracedReferenceBase<T>::Reset() {
  9239. if (IsEmpty()) return;
  9240. V8::DisposeTracedGlobal(reinterpret_cast<internal::Address*>(val_));
  9241. val_ = nullptr;
  9242. }
  9243. template <class T>
  9244. template <class S>
  9245. void TracedGlobal<T>::Reset(Isolate* isolate, const Local<S>& other) {
  9246. TYPE_CHECK(T, S);
  9247. Reset();
  9248. if (other.IsEmpty()) return;
  9249. this->val_ = this->New(isolate, other.val_, &this->val_,
  9250. TracedReferenceBase<T>::kWithDestructor);
  9251. }
  9252. template <class T>
  9253. template <class S>
  9254. TracedGlobal<T>& TracedGlobal<T>::operator=(TracedGlobal<S>&& rhs) {
  9255. TYPE_CHECK(T, S);
  9256. *this = std::move(rhs.template As<T>());
  9257. return *this;
  9258. }
  9259. template <class T>
  9260. template <class S>
  9261. TracedGlobal<T>& TracedGlobal<T>::operator=(const TracedGlobal<S>& rhs) {
  9262. TYPE_CHECK(T, S);
  9263. *this = rhs.template As<T>();
  9264. return *this;
  9265. }
  9266. template <class T>
  9267. TracedGlobal<T>& TracedGlobal<T>::operator=(TracedGlobal&& rhs) {
  9268. if (this != &rhs) {
  9269. this->Reset();
  9270. if (rhs.val_ != nullptr) {
  9271. this->val_ = rhs.val_;
  9272. V8::MoveTracedGlobalReference(
  9273. reinterpret_cast<internal::Address**>(&rhs.val_),
  9274. reinterpret_cast<internal::Address**>(&this->val_));
  9275. rhs.val_ = nullptr;
  9276. }
  9277. }
  9278. return *this;
  9279. }
  9280. template <class T>
  9281. TracedGlobal<T>& TracedGlobal<T>::operator=(const TracedGlobal& rhs) {
  9282. if (this != &rhs) {
  9283. this->Reset();
  9284. if (rhs.val_ != nullptr) {
  9285. V8::CopyTracedGlobalReference(
  9286. reinterpret_cast<const internal::Address* const*>(&rhs.val_),
  9287. reinterpret_cast<internal::Address**>(&this->val_));
  9288. }
  9289. }
  9290. return *this;
  9291. }
  9292. template <class T>
  9293. template <class S>
  9294. void TracedReference<T>::Reset(Isolate* isolate, const Local<S>& other) {
  9295. TYPE_CHECK(T, S);
  9296. Reset();
  9297. if (other.IsEmpty()) return;
  9298. this->val_ = this->New(isolate, other.val_, &this->val_,
  9299. TracedReferenceBase<T>::kWithoutDestructor);
  9300. }
  9301. template <class T>
  9302. template <class S>
  9303. TracedReference<T>& TracedReference<T>::operator=(TracedReference<S>&& rhs) {
  9304. TYPE_CHECK(T, S);
  9305. *this = std::move(rhs.template As<T>());
  9306. return *this;
  9307. }
  9308. template <class T>
  9309. template <class S>
  9310. TracedReference<T>& TracedReference<T>::operator=(
  9311. const TracedReference<S>& rhs) {
  9312. TYPE_CHECK(T, S);
  9313. *this = rhs.template As<T>();
  9314. return *this;
  9315. }
  9316. template <class T>
  9317. TracedReference<T>& TracedReference<T>::operator=(TracedReference&& rhs) {
  9318. if (this != &rhs) {
  9319. this->Reset();
  9320. if (rhs.val_ != nullptr) {
  9321. this->val_ = rhs.val_;
  9322. V8::MoveTracedGlobalReference(
  9323. reinterpret_cast<internal::Address**>(&rhs.val_),
  9324. reinterpret_cast<internal::Address**>(&this->val_));
  9325. rhs.val_ = nullptr;
  9326. }
  9327. }
  9328. return *this;
  9329. }
  9330. template <class T>
  9331. TracedReference<T>& TracedReference<T>::operator=(const TracedReference& rhs) {
  9332. if (this != &rhs) {
  9333. this->Reset();
  9334. if (rhs.val_ != nullptr) {
  9335. V8::CopyTracedGlobalReference(
  9336. reinterpret_cast<const internal::Address* const*>(&rhs.val_),
  9337. reinterpret_cast<internal::Address**>(&this->val_));
  9338. }
  9339. }
  9340. return *this;
  9341. }
  9342. template <class T>
  9343. void TracedReferenceBase<T>::SetWrapperClassId(uint16_t class_id) {
  9344. typedef internal::Internals I;
  9345. if (IsEmpty()) return;
  9346. internal::Address* obj = reinterpret_cast<internal::Address*>(val_);
  9347. uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
  9348. *reinterpret_cast<uint16_t*>(addr) = class_id;
  9349. }
  9350. template <class T>
  9351. uint16_t TracedReferenceBase<T>::WrapperClassId() const {
  9352. typedef internal::Internals I;
  9353. if (IsEmpty()) return 0;
  9354. internal::Address* obj = reinterpret_cast<internal::Address*>(val_);
  9355. uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
  9356. return *reinterpret_cast<uint16_t*>(addr);
  9357. }
  9358. template <class T>
  9359. void TracedGlobal<T>::SetFinalizationCallback(
  9360. void* parameter, typename WeakCallbackInfo<void>::Callback callback) {
  9361. V8::SetFinalizationCallbackTraced(
  9362. reinterpret_cast<internal::Address*>(this->val_), parameter, callback);
  9363. }
  9364. template <class T>
  9365. void TracedReference<T>::SetFinalizationCallback(
  9366. void* parameter, typename WeakCallbackInfo<void>::Callback callback) {
  9367. V8::SetFinalizationCallbackTraced(
  9368. reinterpret_cast<internal::Address*>(this->val_), parameter, callback);
  9369. }
  9370. template <typename T>
  9371. ReturnValue<T>::ReturnValue(internal::Address* slot) : value_(slot) {}
  9372. template <typename T>
  9373. template <typename S>
  9374. void ReturnValue<T>::Set(const Global<S>& handle) {
  9375. TYPE_CHECK(T, S);
  9376. if (V8_UNLIKELY(handle.IsEmpty())) {
  9377. *value_ = GetDefaultValue();
  9378. } else {
  9379. *value_ = *reinterpret_cast<internal::Address*>(*handle);
  9380. }
  9381. }
  9382. template <typename T>
  9383. template <typename S>
  9384. void ReturnValue<T>::Set(const TracedReferenceBase<S>& handle) {
  9385. TYPE_CHECK(T, S);
  9386. if (V8_UNLIKELY(handle.IsEmpty())) {
  9387. *value_ = GetDefaultValue();
  9388. } else {
  9389. *value_ = *reinterpret_cast<internal::Address*>(handle.val_);
  9390. }
  9391. }
  9392. template <typename T>
  9393. template <typename S>
  9394. void ReturnValue<T>::Set(const Local<S> handle) {
  9395. TYPE_CHECK(T, S);
  9396. if (V8_UNLIKELY(handle.IsEmpty())) {
  9397. *value_ = GetDefaultValue();
  9398. } else {
  9399. *value_ = *reinterpret_cast<internal::Address*>(*handle);
  9400. }
  9401. }
  9402. template<typename T>
  9403. void ReturnValue<T>::Set(double i) {
  9404. TYPE_CHECK(T, Number);
  9405. Set(Number::New(GetIsolate(), i));
  9406. }
  9407. template<typename T>
  9408. void ReturnValue<T>::Set(int32_t i) {
  9409. TYPE_CHECK(T, Integer);
  9410. typedef internal::Internals I;
  9411. if (V8_LIKELY(I::IsValidSmi(i))) {
  9412. *value_ = I::IntToSmi(i);
  9413. return;
  9414. }
  9415. Set(Integer::New(GetIsolate(), i));
  9416. }
  9417. template<typename T>
  9418. void ReturnValue<T>::Set(uint32_t i) {
  9419. TYPE_CHECK(T, Integer);
  9420. // Can't simply use INT32_MAX here for whatever reason.
  9421. bool fits_into_int32_t = (i & (1U << 31)) == 0;
  9422. if (V8_LIKELY(fits_into_int32_t)) {
  9423. Set(static_cast<int32_t>(i));
  9424. return;
  9425. }
  9426. Set(Integer::NewFromUnsigned(GetIsolate(), i));
  9427. }
  9428. template<typename T>
  9429. void ReturnValue<T>::Set(bool value) {
  9430. TYPE_CHECK(T, Boolean);
  9431. typedef internal::Internals I;
  9432. int root_index;
  9433. if (value) {
  9434. root_index = I::kTrueValueRootIndex;
  9435. } else {
  9436. root_index = I::kFalseValueRootIndex;
  9437. }
  9438. *value_ = *I::GetRoot(GetIsolate(), root_index);
  9439. }
  9440. template<typename T>
  9441. void ReturnValue<T>::SetNull() {
  9442. TYPE_CHECK(T, Primitive);
  9443. typedef internal::Internals I;
  9444. *value_ = *I::GetRoot(GetIsolate(), I::kNullValueRootIndex);
  9445. }
  9446. template<typename T>
  9447. void ReturnValue<T>::SetUndefined() {
  9448. TYPE_CHECK(T, Primitive);
  9449. typedef internal::Internals I;
  9450. *value_ = *I::GetRoot(GetIsolate(), I::kUndefinedValueRootIndex);
  9451. }
  9452. template<typename T>
  9453. void ReturnValue<T>::SetEmptyString() {
  9454. TYPE_CHECK(T, String);
  9455. typedef internal::Internals I;
  9456. *value_ = *I::GetRoot(GetIsolate(), I::kEmptyStringRootIndex);
  9457. }
  9458. template <typename T>
  9459. Isolate* ReturnValue<T>::GetIsolate() const {
  9460. // Isolate is always the pointer below the default value on the stack.
  9461. return *reinterpret_cast<Isolate**>(&value_[-2]);
  9462. }
  9463. template <typename T>
  9464. Local<Value> ReturnValue<T>::Get() const {
  9465. typedef internal::Internals I;
  9466. if (*value_ == *I::GetRoot(GetIsolate(), I::kTheHoleValueRootIndex))
  9467. return Local<Value>(*Undefined(GetIsolate()));
  9468. return Local<Value>::New(GetIsolate(), reinterpret_cast<Value*>(value_));
  9469. }
  9470. template <typename T>
  9471. template <typename S>
  9472. void ReturnValue<T>::Set(S* whatever) {
  9473. // Uncompilable to prevent inadvertent misuse.
  9474. TYPE_CHECK(S*, Primitive);
  9475. }
  9476. template <typename T>
  9477. internal::Address ReturnValue<T>::GetDefaultValue() {
  9478. // Default value is always the pointer below value_ on the stack.
  9479. return value_[-1];
  9480. }
  9481. template <typename T>
  9482. FunctionCallbackInfo<T>::FunctionCallbackInfo(internal::Address* implicit_args,
  9483. internal::Address* values,
  9484. int length)
  9485. : implicit_args_(implicit_args), values_(values), length_(length) {}
  9486. template<typename T>
  9487. Local<Value> FunctionCallbackInfo<T>::operator[](int i) const {
  9488. if (i < 0 || length_ <= i) return Local<Value>(*Undefined(GetIsolate()));
  9489. return Local<Value>(reinterpret_cast<Value*>(values_ - i));
  9490. }
  9491. template<typename T>
  9492. Local<Object> FunctionCallbackInfo<T>::This() const {
  9493. return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
  9494. }
  9495. template<typename T>
  9496. Local<Object> FunctionCallbackInfo<T>::Holder() const {
  9497. return Local<Object>(reinterpret_cast<Object*>(
  9498. &implicit_args_[kHolderIndex]));
  9499. }
  9500. template <typename T>
  9501. Local<Value> FunctionCallbackInfo<T>::NewTarget() const {
  9502. return Local<Value>(
  9503. reinterpret_cast<Value*>(&implicit_args_[kNewTargetIndex]));
  9504. }
  9505. template <typename T>
  9506. Local<Value> FunctionCallbackInfo<T>::Data() const {
  9507. return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
  9508. }
  9509. template<typename T>
  9510. Isolate* FunctionCallbackInfo<T>::GetIsolate() const {
  9511. return *reinterpret_cast<Isolate**>(&implicit_args_[kIsolateIndex]);
  9512. }
  9513. template<typename T>
  9514. ReturnValue<T> FunctionCallbackInfo<T>::GetReturnValue() const {
  9515. return ReturnValue<T>(&implicit_args_[kReturnValueIndex]);
  9516. }
  9517. template<typename T>
  9518. bool FunctionCallbackInfo<T>::IsConstructCall() const {
  9519. return !NewTarget()->IsUndefined();
  9520. }
  9521. template<typename T>
  9522. int FunctionCallbackInfo<T>::Length() const {
  9523. return length_;
  9524. }
  9525. ScriptOrigin::ScriptOrigin(Local<Value> resource_name,
  9526. Local<Integer> resource_line_offset,
  9527. Local<Integer> resource_column_offset,
  9528. Local<Boolean> resource_is_shared_cross_origin,
  9529. Local<Integer> script_id,
  9530. Local<Value> source_map_url,
  9531. Local<Boolean> resource_is_opaque,
  9532. Local<Boolean> is_wasm, Local<Boolean> is_module,
  9533. Local<PrimitiveArray> host_defined_options)
  9534. : resource_name_(resource_name),
  9535. resource_line_offset_(resource_line_offset),
  9536. resource_column_offset_(resource_column_offset),
  9537. options_(!resource_is_shared_cross_origin.IsEmpty() &&
  9538. resource_is_shared_cross_origin->IsTrue(),
  9539. !resource_is_opaque.IsEmpty() && resource_is_opaque->IsTrue(),
  9540. !is_wasm.IsEmpty() && is_wasm->IsTrue(),
  9541. !is_module.IsEmpty() && is_module->IsTrue()),
  9542. script_id_(script_id),
  9543. source_map_url_(source_map_url),
  9544. host_defined_options_(host_defined_options) {}
  9545. Local<Value> ScriptOrigin::ResourceName() const { return resource_name_; }
  9546. Local<PrimitiveArray> ScriptOrigin::HostDefinedOptions() const {
  9547. return host_defined_options_;
  9548. }
  9549. Local<Integer> ScriptOrigin::ResourceLineOffset() const {
  9550. return resource_line_offset_;
  9551. }
  9552. Local<Integer> ScriptOrigin::ResourceColumnOffset() const {
  9553. return resource_column_offset_;
  9554. }
  9555. Local<Integer> ScriptOrigin::ScriptID() const { return script_id_; }
  9556. Local<Value> ScriptOrigin::SourceMapUrl() const { return source_map_url_; }
  9557. ScriptCompiler::Source::Source(Local<String> string, const ScriptOrigin& origin,
  9558. CachedData* data)
  9559. : source_string(string),
  9560. resource_name(origin.ResourceName()),
  9561. resource_line_offset(origin.ResourceLineOffset()),
  9562. resource_column_offset(origin.ResourceColumnOffset()),
  9563. resource_options(origin.Options()),
  9564. source_map_url(origin.SourceMapUrl()),
  9565. host_defined_options(origin.HostDefinedOptions()),
  9566. cached_data(data) {}
  9567. ScriptCompiler::Source::Source(Local<String> string,
  9568. CachedData* data)
  9569. : source_string(string), cached_data(data) {}
  9570. ScriptCompiler::Source::~Source() {
  9571. delete cached_data;
  9572. }
  9573. const ScriptCompiler::CachedData* ScriptCompiler::Source::GetCachedData()
  9574. const {
  9575. return cached_data;
  9576. }
  9577. const ScriptOriginOptions& ScriptCompiler::Source::GetResourceOptions() const {
  9578. return resource_options;
  9579. }
  9580. Local<Boolean> Boolean::New(Isolate* isolate, bool value) {
  9581. return value ? True(isolate) : False(isolate);
  9582. }
  9583. void Template::Set(Isolate* isolate, const char* name, Local<Data> value) {
  9584. Set(String::NewFromUtf8(isolate, name, NewStringType::kInternalized)
  9585. .ToLocalChecked(),
  9586. value);
  9587. }
  9588. FunctionTemplate* FunctionTemplate::Cast(Data* data) {
  9589. #ifdef V8_ENABLE_CHECKS
  9590. CheckCast(data);
  9591. #endif
  9592. return reinterpret_cast<FunctionTemplate*>(data);
  9593. }
  9594. ObjectTemplate* ObjectTemplate::Cast(Data* data) {
  9595. #ifdef V8_ENABLE_CHECKS
  9596. CheckCast(data);
  9597. #endif
  9598. return reinterpret_cast<ObjectTemplate*>(data);
  9599. }
  9600. Signature* Signature::Cast(Data* data) {
  9601. #ifdef V8_ENABLE_CHECKS
  9602. CheckCast(data);
  9603. #endif
  9604. return reinterpret_cast<Signature*>(data);
  9605. }
  9606. AccessorSignature* AccessorSignature::Cast(Data* data) {
  9607. #ifdef V8_ENABLE_CHECKS
  9608. CheckCast(data);
  9609. #endif
  9610. return reinterpret_cast<AccessorSignature*>(data);
  9611. }
  9612. Local<Value> Object::GetInternalField(int index) {
  9613. #ifndef V8_ENABLE_CHECKS
  9614. typedef internal::Address A;
  9615. typedef internal::Internals I;
  9616. A obj = *reinterpret_cast<A*>(this);
  9617. // Fast path: If the object is a plain JSObject, which is the common case, we
  9618. // know where to find the internal fields and can return the value directly.
  9619. auto instance_type = I::GetInstanceType(obj);
  9620. if (instance_type == I::kJSObjectType ||
  9621. instance_type == I::kJSApiObjectType ||
  9622. instance_type == I::kJSSpecialApiObjectType) {
  9623. int offset = I::kJSObjectHeaderSize + (I::kEmbedderDataSlotSize * index);
  9624. A value = I::ReadRawField<A>(obj, offset);
  9625. #ifdef V8_COMPRESS_POINTERS
  9626. // We read the full pointer value and then decompress it in order to avoid
  9627. // dealing with potential endiannes issues.
  9628. value = I::DecompressTaggedAnyField(obj, static_cast<int32_t>(value));
  9629. #endif
  9630. internal::Isolate* isolate =
  9631. internal::IsolateFromNeverReadOnlySpaceObject(obj);
  9632. A* result = HandleScope::CreateHandle(isolate, value);
  9633. return Local<Value>(reinterpret_cast<Value*>(result));
  9634. }
  9635. #endif
  9636. return SlowGetInternalField(index);
  9637. }
  9638. void* Object::GetAlignedPointerFromInternalField(int index) {
  9639. #ifndef V8_ENABLE_CHECKS
  9640. typedef internal::Address A;
  9641. typedef internal::Internals I;
  9642. A obj = *reinterpret_cast<A*>(this);
  9643. // Fast path: If the object is a plain JSObject, which is the common case, we
  9644. // know where to find the internal fields and can return the value directly.
  9645. auto instance_type = I::GetInstanceType(obj);
  9646. if (V8_LIKELY(instance_type == I::kJSObjectType ||
  9647. instance_type == I::kJSApiObjectType ||
  9648. instance_type == I::kJSSpecialApiObjectType)) {
  9649. int offset = I::kJSObjectHeaderSize + (I::kEmbedderDataSlotSize * index);
  9650. return I::ReadRawField<void*>(obj, offset);
  9651. }
  9652. #endif
  9653. return SlowGetAlignedPointerFromInternalField(index);
  9654. }
  9655. String* String::Cast(v8::Value* value) {
  9656. #ifdef V8_ENABLE_CHECKS
  9657. CheckCast(value);
  9658. #endif
  9659. return static_cast<String*>(value);
  9660. }
  9661. Local<String> String::Empty(Isolate* isolate) {
  9662. typedef internal::Address S;
  9663. typedef internal::Internals I;
  9664. I::CheckInitialized(isolate);
  9665. S* slot = I::GetRoot(isolate, I::kEmptyStringRootIndex);
  9666. return Local<String>(reinterpret_cast<String*>(slot));
  9667. }
  9668. String::ExternalStringResource* String::GetExternalStringResource() const {
  9669. typedef internal::Address A;
  9670. typedef internal::Internals I;
  9671. A obj = *reinterpret_cast<const A*>(this);
  9672. ExternalStringResource* result;
  9673. if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
  9674. void* value = I::ReadRawField<void*>(obj, I::kStringResourceOffset);
  9675. result = reinterpret_cast<String::ExternalStringResource*>(value);
  9676. } else {
  9677. result = GetExternalStringResourceSlow();
  9678. }
  9679. #ifdef V8_ENABLE_CHECKS
  9680. VerifyExternalStringResource(result);
  9681. #endif
  9682. return result;
  9683. }
  9684. String::ExternalStringResourceBase* String::GetExternalStringResourceBase(
  9685. String::Encoding* encoding_out) const {
  9686. typedef internal::Address A;
  9687. typedef internal::Internals I;
  9688. A obj = *reinterpret_cast<const A*>(this);
  9689. int type = I::GetInstanceType(obj) & I::kFullStringRepresentationMask;
  9690. *encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask);
  9691. ExternalStringResourceBase* resource;
  9692. if (type == I::kExternalOneByteRepresentationTag ||
  9693. type == I::kExternalTwoByteRepresentationTag) {
  9694. void* value = I::ReadRawField<void*>(obj, I::kStringResourceOffset);
  9695. resource = static_cast<ExternalStringResourceBase*>(value);
  9696. } else {
  9697. resource = GetExternalStringResourceBaseSlow(encoding_out);
  9698. }
  9699. #ifdef V8_ENABLE_CHECKS
  9700. VerifyExternalStringResourceBase(resource, *encoding_out);
  9701. #endif
  9702. return resource;
  9703. }
  9704. bool Value::IsUndefined() const {
  9705. #ifdef V8_ENABLE_CHECKS
  9706. return FullIsUndefined();
  9707. #else
  9708. return QuickIsUndefined();
  9709. #endif
  9710. }
  9711. bool Value::QuickIsUndefined() const {
  9712. typedef internal::Address A;
  9713. typedef internal::Internals I;
  9714. A obj = *reinterpret_cast<const A*>(this);
  9715. if (!I::HasHeapObjectTag(obj)) return false;
  9716. if (I::GetInstanceType(obj) != I::kOddballType) return false;
  9717. return (I::GetOddballKind(obj) == I::kUndefinedOddballKind);
  9718. }
  9719. bool Value::IsNull() const {
  9720. #ifdef V8_ENABLE_CHECKS
  9721. return FullIsNull();
  9722. #else
  9723. return QuickIsNull();
  9724. #endif
  9725. }
  9726. bool Value::QuickIsNull() const {
  9727. typedef internal::Address A;
  9728. typedef internal::Internals I;
  9729. A obj = *reinterpret_cast<const A*>(this);
  9730. if (!I::HasHeapObjectTag(obj)) return false;
  9731. if (I::GetInstanceType(obj) != I::kOddballType) return false;
  9732. return (I::GetOddballKind(obj) == I::kNullOddballKind);
  9733. }
  9734. bool Value::IsNullOrUndefined() const {
  9735. #ifdef V8_ENABLE_CHECKS
  9736. return FullIsNull() || FullIsUndefined();
  9737. #else
  9738. return QuickIsNullOrUndefined();
  9739. #endif
  9740. }
  9741. bool Value::QuickIsNullOrUndefined() const {
  9742. typedef internal::Address A;
  9743. typedef internal::Internals I;
  9744. A obj = *reinterpret_cast<const A*>(this);
  9745. if (!I::HasHeapObjectTag(obj)) return false;
  9746. if (I::GetInstanceType(obj) != I::kOddballType) return false;
  9747. int kind = I::GetOddballKind(obj);
  9748. return kind == I::kNullOddballKind || kind == I::kUndefinedOddballKind;
  9749. }
  9750. bool Value::IsString() const {
  9751. #ifdef V8_ENABLE_CHECKS
  9752. return FullIsString();
  9753. #else
  9754. return QuickIsString();
  9755. #endif
  9756. }
  9757. bool Value::QuickIsString() const {
  9758. typedef internal::Address A;
  9759. typedef internal::Internals I;
  9760. A obj = *reinterpret_cast<const A*>(this);
  9761. if (!I::HasHeapObjectTag(obj)) return false;
  9762. return (I::GetInstanceType(obj) < I::kFirstNonstringType);
  9763. }
  9764. template <class T> Value* Value::Cast(T* value) {
  9765. return static_cast<Value*>(value);
  9766. }
  9767. Boolean* Boolean::Cast(v8::Value* value) {
  9768. #ifdef V8_ENABLE_CHECKS
  9769. CheckCast(value);
  9770. #endif
  9771. return static_cast<Boolean*>(value);
  9772. }
  9773. Name* Name::Cast(v8::Value* value) {
  9774. #ifdef V8_ENABLE_CHECKS
  9775. CheckCast(value);
  9776. #endif
  9777. return static_cast<Name*>(value);
  9778. }
  9779. Symbol* Symbol::Cast(v8::Value* value) {
  9780. #ifdef V8_ENABLE_CHECKS
  9781. CheckCast(value);
  9782. #endif
  9783. return static_cast<Symbol*>(value);
  9784. }
  9785. Private* Private::Cast(Data* data) {
  9786. #ifdef V8_ENABLE_CHECKS
  9787. CheckCast(data);
  9788. #endif
  9789. return reinterpret_cast<Private*>(data);
  9790. }
  9791. Number* Number::Cast(v8::Value* value) {
  9792. #ifdef V8_ENABLE_CHECKS
  9793. CheckCast(value);
  9794. #endif
  9795. return static_cast<Number*>(value);
  9796. }
  9797. Integer* Integer::Cast(v8::Value* value) {
  9798. #ifdef V8_ENABLE_CHECKS
  9799. CheckCast(value);
  9800. #endif
  9801. return static_cast<Integer*>(value);
  9802. }
  9803. Int32* Int32::Cast(v8::Value* value) {
  9804. #ifdef V8_ENABLE_CHECKS
  9805. CheckCast(value);
  9806. #endif
  9807. return static_cast<Int32*>(value);
  9808. }
  9809. Uint32* Uint32::Cast(v8::Value* value) {
  9810. #ifdef V8_ENABLE_CHECKS
  9811. CheckCast(value);
  9812. #endif
  9813. return static_cast<Uint32*>(value);
  9814. }
  9815. BigInt* BigInt::Cast(v8::Value* value) {
  9816. #ifdef V8_ENABLE_CHECKS
  9817. CheckCast(value);
  9818. #endif
  9819. return static_cast<BigInt*>(value);
  9820. }
  9821. Date* Date::Cast(v8::Value* value) {
  9822. #ifdef V8_ENABLE_CHECKS
  9823. CheckCast(value);
  9824. #endif
  9825. return static_cast<Date*>(value);
  9826. }
  9827. StringObject* StringObject::Cast(v8::Value* value) {
  9828. #ifdef V8_ENABLE_CHECKS
  9829. CheckCast(value);
  9830. #endif
  9831. return static_cast<StringObject*>(value);
  9832. }
  9833. SymbolObject* SymbolObject::Cast(v8::Value* value) {
  9834. #ifdef V8_ENABLE_CHECKS
  9835. CheckCast(value);
  9836. #endif
  9837. return static_cast<SymbolObject*>(value);
  9838. }
  9839. NumberObject* NumberObject::Cast(v8::Value* value) {
  9840. #ifdef V8_ENABLE_CHECKS
  9841. CheckCast(value);
  9842. #endif
  9843. return static_cast<NumberObject*>(value);
  9844. }
  9845. BigIntObject* BigIntObject::Cast(v8::Value* value) {
  9846. #ifdef V8_ENABLE_CHECKS
  9847. CheckCast(value);
  9848. #endif
  9849. return static_cast<BigIntObject*>(value);
  9850. }
  9851. BooleanObject* BooleanObject::Cast(v8::Value* value) {
  9852. #ifdef V8_ENABLE_CHECKS
  9853. CheckCast(value);
  9854. #endif
  9855. return static_cast<BooleanObject*>(value);
  9856. }
  9857. RegExp* RegExp::Cast(v8::Value* value) {
  9858. #ifdef V8_ENABLE_CHECKS
  9859. CheckCast(value);
  9860. #endif
  9861. return static_cast<RegExp*>(value);
  9862. }
  9863. Object* Object::Cast(v8::Value* value) {
  9864. #ifdef V8_ENABLE_CHECKS
  9865. CheckCast(value);
  9866. #endif
  9867. return static_cast<Object*>(value);
  9868. }
  9869. Array* Array::Cast(v8::Value* value) {
  9870. #ifdef V8_ENABLE_CHECKS
  9871. CheckCast(value);
  9872. #endif
  9873. return static_cast<Array*>(value);
  9874. }
  9875. Map* Map::Cast(v8::Value* value) {
  9876. #ifdef V8_ENABLE_CHECKS
  9877. CheckCast(value);
  9878. #endif
  9879. return static_cast<Map*>(value);
  9880. }
  9881. Set* Set::Cast(v8::Value* value) {
  9882. #ifdef V8_ENABLE_CHECKS
  9883. CheckCast(value);
  9884. #endif
  9885. return static_cast<Set*>(value);
  9886. }
  9887. Promise* Promise::Cast(v8::Value* value) {
  9888. #ifdef V8_ENABLE_CHECKS
  9889. CheckCast(value);
  9890. #endif
  9891. return static_cast<Promise*>(value);
  9892. }
  9893. Proxy* Proxy::Cast(v8::Value* value) {
  9894. #ifdef V8_ENABLE_CHECKS
  9895. CheckCast(value);
  9896. #endif
  9897. return static_cast<Proxy*>(value);
  9898. }
  9899. WasmModuleObject* WasmModuleObject::Cast(v8::Value* value) {
  9900. #ifdef V8_ENABLE_CHECKS
  9901. CheckCast(value);
  9902. #endif
  9903. return static_cast<WasmModuleObject*>(value);
  9904. }
  9905. Promise::Resolver* Promise::Resolver::Cast(v8::Value* value) {
  9906. #ifdef V8_ENABLE_CHECKS
  9907. CheckCast(value);
  9908. #endif
  9909. return static_cast<Promise::Resolver*>(value);
  9910. }
  9911. ArrayBuffer* ArrayBuffer::Cast(v8::Value* value) {
  9912. #ifdef V8_ENABLE_CHECKS
  9913. CheckCast(value);
  9914. #endif
  9915. return static_cast<ArrayBuffer*>(value);
  9916. }
  9917. ArrayBufferView* ArrayBufferView::Cast(v8::Value* value) {
  9918. #ifdef V8_ENABLE_CHECKS
  9919. CheckCast(value);
  9920. #endif
  9921. return static_cast<ArrayBufferView*>(value);
  9922. }
  9923. TypedArray* TypedArray::Cast(v8::Value* value) {
  9924. #ifdef V8_ENABLE_CHECKS
  9925. CheckCast(value);
  9926. #endif
  9927. return static_cast<TypedArray*>(value);
  9928. }
  9929. Uint8Array* Uint8Array::Cast(v8::Value* value) {
  9930. #ifdef V8_ENABLE_CHECKS
  9931. CheckCast(value);
  9932. #endif
  9933. return static_cast<Uint8Array*>(value);
  9934. }
  9935. Int8Array* Int8Array::Cast(v8::Value* value) {
  9936. #ifdef V8_ENABLE_CHECKS
  9937. CheckCast(value);
  9938. #endif
  9939. return static_cast<Int8Array*>(value);
  9940. }
  9941. Uint16Array* Uint16Array::Cast(v8::Value* value) {
  9942. #ifdef V8_ENABLE_CHECKS
  9943. CheckCast(value);
  9944. #endif
  9945. return static_cast<Uint16Array*>(value);
  9946. }
  9947. Int16Array* Int16Array::Cast(v8::Value* value) {
  9948. #ifdef V8_ENABLE_CHECKS
  9949. CheckCast(value);
  9950. #endif
  9951. return static_cast<Int16Array*>(value);
  9952. }
  9953. Uint32Array* Uint32Array::Cast(v8::Value* value) {
  9954. #ifdef V8_ENABLE_CHECKS
  9955. CheckCast(value);
  9956. #endif
  9957. return static_cast<Uint32Array*>(value);
  9958. }
  9959. Int32Array* Int32Array::Cast(v8::Value* value) {
  9960. #ifdef V8_ENABLE_CHECKS
  9961. CheckCast(value);
  9962. #endif
  9963. return static_cast<Int32Array*>(value);
  9964. }
  9965. Float32Array* Float32Array::Cast(v8::Value* value) {
  9966. #ifdef V8_ENABLE_CHECKS
  9967. CheckCast(value);
  9968. #endif
  9969. return static_cast<Float32Array*>(value);
  9970. }
  9971. Float64Array* Float64Array::Cast(v8::Value* value) {
  9972. #ifdef V8_ENABLE_CHECKS
  9973. CheckCast(value);
  9974. #endif
  9975. return static_cast<Float64Array*>(value);
  9976. }
  9977. BigInt64Array* BigInt64Array::Cast(v8::Value* value) {
  9978. #ifdef V8_ENABLE_CHECKS
  9979. CheckCast(value);
  9980. #endif
  9981. return static_cast<BigInt64Array*>(value);
  9982. }
  9983. BigUint64Array* BigUint64Array::Cast(v8::Value* value) {
  9984. #ifdef V8_ENABLE_CHECKS
  9985. CheckCast(value);
  9986. #endif
  9987. return static_cast<BigUint64Array*>(value);
  9988. }
  9989. Uint8ClampedArray* Uint8ClampedArray::Cast(v8::Value* value) {
  9990. #ifdef V8_ENABLE_CHECKS
  9991. CheckCast(value);
  9992. #endif
  9993. return static_cast<Uint8ClampedArray*>(value);
  9994. }
  9995. DataView* DataView::Cast(v8::Value* value) {
  9996. #ifdef V8_ENABLE_CHECKS
  9997. CheckCast(value);
  9998. #endif
  9999. return static_cast<DataView*>(value);
  10000. }
  10001. SharedArrayBuffer* SharedArrayBuffer::Cast(v8::Value* value) {
  10002. #ifdef V8_ENABLE_CHECKS
  10003. CheckCast(value);
  10004. #endif
  10005. return static_cast<SharedArrayBuffer*>(value);
  10006. }
  10007. Function* Function::Cast(v8::Value* value) {
  10008. #ifdef V8_ENABLE_CHECKS
  10009. CheckCast(value);
  10010. #endif
  10011. return static_cast<Function*>(value);
  10012. }
  10013. External* External::Cast(v8::Value* value) {
  10014. #ifdef V8_ENABLE_CHECKS
  10015. CheckCast(value);
  10016. #endif
  10017. return static_cast<External*>(value);
  10018. }
  10019. template<typename T>
  10020. Isolate* PropertyCallbackInfo<T>::GetIsolate() const {
  10021. return *reinterpret_cast<Isolate**>(&args_[kIsolateIndex]);
  10022. }
  10023. template<typename T>
  10024. Local<Value> PropertyCallbackInfo<T>::Data() const {
  10025. return Local<Value>(reinterpret_cast<Value*>(&args_[kDataIndex]));
  10026. }
  10027. template<typename T>
  10028. Local<Object> PropertyCallbackInfo<T>::This() const {
  10029. return Local<Object>(reinterpret_cast<Object*>(&args_[kThisIndex]));
  10030. }
  10031. template<typename T>
  10032. Local<Object> PropertyCallbackInfo<T>::Holder() const {
  10033. return Local<Object>(reinterpret_cast<Object*>(&args_[kHolderIndex]));
  10034. }
  10035. template<typename T>
  10036. ReturnValue<T> PropertyCallbackInfo<T>::GetReturnValue() const {
  10037. return ReturnValue<T>(&args_[kReturnValueIndex]);
  10038. }
  10039. template <typename T>
  10040. bool PropertyCallbackInfo<T>::ShouldThrowOnError() const {
  10041. typedef internal::Internals I;
  10042. if (args_[kShouldThrowOnErrorIndex] !=
  10043. I::IntToSmi(I::kInferShouldThrowMode)) {
  10044. return args_[kShouldThrowOnErrorIndex] != I::IntToSmi(I::kDontThrow);
  10045. }
  10046. return v8::internal::ShouldThrowOnError(
  10047. reinterpret_cast<v8::internal::Isolate*>(GetIsolate()));
  10048. }
  10049. Local<Primitive> Undefined(Isolate* isolate) {
  10050. typedef internal::Address S;
  10051. typedef internal::Internals I;
  10052. I::CheckInitialized(isolate);
  10053. S* slot = I::GetRoot(isolate, I::kUndefinedValueRootIndex);
  10054. return Local<Primitive>(reinterpret_cast<Primitive*>(slot));
  10055. }
  10056. Local<Primitive> Null(Isolate* isolate) {
  10057. typedef internal::Address S;
  10058. typedef internal::Internals I;
  10059. I::CheckInitialized(isolate);
  10060. S* slot = I::GetRoot(isolate, I::kNullValueRootIndex);
  10061. return Local<Primitive>(reinterpret_cast<Primitive*>(slot));
  10062. }
  10063. Local<Boolean> True(Isolate* isolate) {
  10064. typedef internal::Address S;
  10065. typedef internal::Internals I;
  10066. I::CheckInitialized(isolate);
  10067. S* slot = I::GetRoot(isolate, I::kTrueValueRootIndex);
  10068. return Local<Boolean>(reinterpret_cast<Boolean*>(slot));
  10069. }
  10070. Local<Boolean> False(Isolate* isolate) {
  10071. typedef internal::Address S;
  10072. typedef internal::Internals I;
  10073. I::CheckInitialized(isolate);
  10074. S* slot = I::GetRoot(isolate, I::kFalseValueRootIndex);
  10075. return Local<Boolean>(reinterpret_cast<Boolean*>(slot));
  10076. }
  10077. void Isolate::SetData(uint32_t slot, void* data) {
  10078. typedef internal::Internals I;
  10079. I::SetEmbedderData(this, slot, data);
  10080. }
  10081. void* Isolate::GetData(uint32_t slot) {
  10082. typedef internal::Internals I;
  10083. return I::GetEmbedderData(this, slot);
  10084. }
  10085. uint32_t Isolate::GetNumberOfDataSlots() {
  10086. typedef internal::Internals I;
  10087. return I::kNumIsolateDataSlots;
  10088. }
  10089. template <class T>
  10090. MaybeLocal<T> Isolate::GetDataFromSnapshotOnce(size_t index) {
  10091. T* data = reinterpret_cast<T*>(GetDataFromSnapshotOnce(index));
  10092. if (data) internal::PerformCastCheck(data);
  10093. return Local<T>(data);
  10094. }
  10095. int64_t Isolate::AdjustAmountOfExternalAllocatedMemory(
  10096. int64_t change_in_bytes) {
  10097. typedef internal::Internals I;
  10098. constexpr int64_t kMemoryReducerActivationLimit = 32 * 1024 * 1024;
  10099. int64_t* external_memory = reinterpret_cast<int64_t*>(
  10100. reinterpret_cast<uint8_t*>(this) + I::kExternalMemoryOffset);
  10101. int64_t* external_memory_limit = reinterpret_cast<int64_t*>(
  10102. reinterpret_cast<uint8_t*>(this) + I::kExternalMemoryLimitOffset);
  10103. int64_t* external_memory_at_last_mc =
  10104. reinterpret_cast<int64_t*>(reinterpret_cast<uint8_t*>(this) +
  10105. I::kExternalMemoryAtLastMarkCompactOffset);
  10106. // Embedders are weird: we see both over- and underflows here. Perform the
  10107. // addition with unsigned types to avoid undefined behavior.
  10108. const int64_t amount =
  10109. static_cast<int64_t>(static_cast<uint64_t>(change_in_bytes) +
  10110. static_cast<uint64_t>(*external_memory));
  10111. *external_memory = amount;
  10112. int64_t allocation_diff_since_last_mc =
  10113. static_cast<int64_t>(static_cast<uint64_t>(*external_memory) -
  10114. static_cast<uint64_t>(*external_memory_at_last_mc));
  10115. // Only check memory pressure and potentially trigger GC if the amount of
  10116. // external memory increased.
  10117. if (allocation_diff_since_last_mc > kMemoryReducerActivationLimit) {
  10118. CheckMemoryPressure();
  10119. }
  10120. if (change_in_bytes < 0) {
  10121. const int64_t lower_limit =
  10122. static_cast<int64_t>(static_cast<uint64_t>(*external_memory_limit) +
  10123. static_cast<uint64_t>(change_in_bytes));
  10124. if (lower_limit > I::kExternalAllocationSoftLimit) {
  10125. *external_memory_limit = lower_limit;
  10126. }
  10127. } else if (change_in_bytes > 0 && amount > *external_memory_limit) {
  10128. ReportExternalAllocationLimitReached();
  10129. }
  10130. return *external_memory;
  10131. }
  10132. Local<Value> Context::GetEmbedderData(int index) {
  10133. #ifndef V8_ENABLE_CHECKS
  10134. typedef internal::Address A;
  10135. typedef internal::Internals I;
  10136. A ctx = *reinterpret_cast<const A*>(this);
  10137. A embedder_data =
  10138. I::ReadTaggedPointerField(ctx, I::kNativeContextEmbedderDataOffset);
  10139. int value_offset =
  10140. I::kEmbedderDataArrayHeaderSize + (I::kEmbedderDataSlotSize * index);
  10141. A value = I::ReadRawField<A>(embedder_data, value_offset);
  10142. #ifdef V8_COMPRESS_POINTERS
  10143. // We read the full pointer value and then decompress it in order to avoid
  10144. // dealing with potential endiannes issues.
  10145. value =
  10146. I::DecompressTaggedAnyField(embedder_data, static_cast<int32_t>(value));
  10147. #endif
  10148. internal::Isolate* isolate = internal::IsolateFromNeverReadOnlySpaceObject(
  10149. *reinterpret_cast<A*>(this));
  10150. A* result = HandleScope::CreateHandle(isolate, value);
  10151. return Local<Value>(reinterpret_cast<Value*>(result));
  10152. #else
  10153. return SlowGetEmbedderData(index);
  10154. #endif
  10155. }
  10156. void* Context::GetAlignedPointerFromEmbedderData(int index) {
  10157. #ifndef V8_ENABLE_CHECKS
  10158. typedef internal::Address A;
  10159. typedef internal::Internals I;
  10160. A ctx = *reinterpret_cast<const A*>(this);
  10161. A embedder_data =
  10162. I::ReadTaggedPointerField(ctx, I::kNativeContextEmbedderDataOffset);
  10163. int value_offset =
  10164. I::kEmbedderDataArrayHeaderSize + (I::kEmbedderDataSlotSize * index);
  10165. return I::ReadRawField<void*>(embedder_data, value_offset);
  10166. #else
  10167. return SlowGetAlignedPointerFromEmbedderData(index);
  10168. #endif
  10169. }
  10170. template <class T>
  10171. MaybeLocal<T> Context::GetDataFromSnapshotOnce(size_t index) {
  10172. T* data = reinterpret_cast<T*>(GetDataFromSnapshotOnce(index));
  10173. if (data) internal::PerformCastCheck(data);
  10174. return Local<T>(data);
  10175. }
  10176. template <class T>
  10177. size_t SnapshotCreator::AddData(Local<Context> context, Local<T> object) {
  10178. T* object_ptr = *object;
  10179. internal::Address* p = reinterpret_cast<internal::Address*>(object_ptr);
  10180. return AddData(context, *p);
  10181. }
  10182. template <class T>
  10183. size_t SnapshotCreator::AddData(Local<T> object) {
  10184. T* object_ptr = *object;
  10185. internal::Address* p = reinterpret_cast<internal::Address*>(object_ptr);
  10186. return AddData(*p);
  10187. }
  10188. /**
  10189. * \example shell.cc
  10190. * A simple shell that takes a list of expressions on the
  10191. * command-line and executes them.
  10192. */
  10193. /**
  10194. * \example process.cc
  10195. */
  10196. } // namespace v8
  10197. #undef TYPE_CHECK
  10198. #endif // INCLUDE_V8_H_