Turn audio into a shareable video. forked from nypublicradio/audiogram

v8.h 360KB

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