upb.c 533 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559
  1. // Amalgamated source file
  2. #include "upb.h"
  3. #if UINTPTR_MAX == 0xffffffff
  4. #define UPB_SIZE(size32, size64) size32
  5. #else
  6. #define UPB_SIZE(size32, size64) size64
  7. #endif
  8. #define UPB_FIELD_AT(msg, fieldtype, offset) \
  9. *(fieldtype*)((const char*)(msg) + offset)
  10. #define UPB_READ_ONEOF(msg, fieldtype, offset, case_offset, case_val, default) \
  11. UPB_FIELD_AT(msg, int, case_offset) == case_val \
  12. ? UPB_FIELD_AT(msg, fieldtype, offset) \
  13. : default
  14. #define UPB_WRITE_ONEOF(msg, fieldtype, offset, value, case_offset, case_val) \
  15. UPB_FIELD_AT(msg, int, case_offset) = case_val; \
  16. UPB_FIELD_AT(msg, fieldtype, offset) = value;
  17. /* This file was generated by upbc (the upb compiler) from the input
  18. * file:
  19. *
  20. * google/protobuf/descriptor.proto
  21. *
  22. * Do not edit -- your changes will be discarded when the file is
  23. * regenerated. */
  24. #include <stddef.h>
  25. static const upb_msglayout *const google_protobuf_FileDescriptorSet_submsgs[1] = {
  26. &google_protobuf_FileDescriptorProto_msginit,
  27. };
  28. static const upb_msglayout_field google_protobuf_FileDescriptorSet__fields[1] = {
  29. {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
  30. };
  31. const upb_msglayout google_protobuf_FileDescriptorSet_msginit = {
  32. &google_protobuf_FileDescriptorSet_submsgs[0],
  33. &google_protobuf_FileDescriptorSet__fields[0],
  34. UPB_SIZE(4, 8), 1, false,
  35. };
  36. static const upb_msglayout *const google_protobuf_FileDescriptorProto_submsgs[6] = {
  37. &google_protobuf_DescriptorProto_msginit,
  38. &google_protobuf_EnumDescriptorProto_msginit,
  39. &google_protobuf_FieldDescriptorProto_msginit,
  40. &google_protobuf_FileOptions_msginit,
  41. &google_protobuf_ServiceDescriptorProto_msginit,
  42. &google_protobuf_SourceCodeInfo_msginit,
  43. };
  44. static const upb_msglayout_field google_protobuf_FileDescriptorProto__fields[12] = {
  45. {1, UPB_SIZE(8, 16), 1, 0, 9, 1},
  46. {2, UPB_SIZE(16, 32), 2, 0, 9, 1},
  47. {3, UPB_SIZE(40, 80), 0, 0, 9, 3},
  48. {4, UPB_SIZE(44, 88), 0, 0, 11, 3},
  49. {5, UPB_SIZE(48, 96), 0, 1, 11, 3},
  50. {6, UPB_SIZE(52, 104), 0, 4, 11, 3},
  51. {7, UPB_SIZE(56, 112), 0, 2, 11, 3},
  52. {8, UPB_SIZE(32, 64), 4, 3, 11, 1},
  53. {9, UPB_SIZE(36, 72), 5, 5, 11, 1},
  54. {10, UPB_SIZE(60, 120), 0, 0, 5, 3},
  55. {11, UPB_SIZE(64, 128), 0, 0, 5, 3},
  56. {12, UPB_SIZE(24, 48), 3, 0, 9, 1},
  57. };
  58. const upb_msglayout google_protobuf_FileDescriptorProto_msginit = {
  59. &google_protobuf_FileDescriptorProto_submsgs[0],
  60. &google_protobuf_FileDescriptorProto__fields[0],
  61. UPB_SIZE(72, 144), 12, false,
  62. };
  63. static const upb_msglayout *const google_protobuf_DescriptorProto_submsgs[8] = {
  64. &google_protobuf_DescriptorProto_msginit,
  65. &google_protobuf_DescriptorProto_ExtensionRange_msginit,
  66. &google_protobuf_DescriptorProto_ReservedRange_msginit,
  67. &google_protobuf_EnumDescriptorProto_msginit,
  68. &google_protobuf_FieldDescriptorProto_msginit,
  69. &google_protobuf_MessageOptions_msginit,
  70. &google_protobuf_OneofDescriptorProto_msginit,
  71. };
  72. static const upb_msglayout_field google_protobuf_DescriptorProto__fields[10] = {
  73. {1, UPB_SIZE(8, 16), 1, 0, 9, 1},
  74. {2, UPB_SIZE(20, 40), 0, 4, 11, 3},
  75. {3, UPB_SIZE(24, 48), 0, 0, 11, 3},
  76. {4, UPB_SIZE(28, 56), 0, 3, 11, 3},
  77. {5, UPB_SIZE(32, 64), 0, 1, 11, 3},
  78. {6, UPB_SIZE(36, 72), 0, 4, 11, 3},
  79. {7, UPB_SIZE(16, 32), 2, 5, 11, 1},
  80. {8, UPB_SIZE(40, 80), 0, 6, 11, 3},
  81. {9, UPB_SIZE(44, 88), 0, 2, 11, 3},
  82. {10, UPB_SIZE(48, 96), 0, 0, 9, 3},
  83. };
  84. const upb_msglayout google_protobuf_DescriptorProto_msginit = {
  85. &google_protobuf_DescriptorProto_submsgs[0],
  86. &google_protobuf_DescriptorProto__fields[0],
  87. UPB_SIZE(56, 112), 10, false,
  88. };
  89. static const upb_msglayout *const google_protobuf_DescriptorProto_ExtensionRange_submsgs[1] = {
  90. &google_protobuf_ExtensionRangeOptions_msginit,
  91. };
  92. static const upb_msglayout_field google_protobuf_DescriptorProto_ExtensionRange__fields[3] = {
  93. {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
  94. {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
  95. {3, UPB_SIZE(12, 16), 3, 0, 11, 1},
  96. };
  97. const upb_msglayout google_protobuf_DescriptorProto_ExtensionRange_msginit = {
  98. &google_protobuf_DescriptorProto_ExtensionRange_submsgs[0],
  99. &google_protobuf_DescriptorProto_ExtensionRange__fields[0],
  100. UPB_SIZE(16, 24), 3, false,
  101. };
  102. static const upb_msglayout_field google_protobuf_DescriptorProto_ReservedRange__fields[2] = {
  103. {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
  104. {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
  105. };
  106. const upb_msglayout google_protobuf_DescriptorProto_ReservedRange_msginit = {
  107. NULL,
  108. &google_protobuf_DescriptorProto_ReservedRange__fields[0],
  109. UPB_SIZE(12, 12), 2, false,
  110. };
  111. static const upb_msglayout *const google_protobuf_ExtensionRangeOptions_submsgs[1] = {
  112. &google_protobuf_UninterpretedOption_msginit,
  113. };
  114. static const upb_msglayout_field google_protobuf_ExtensionRangeOptions__fields[1] = {
  115. {999, UPB_SIZE(0, 0), 0, 0, 11, 3},
  116. };
  117. const upb_msglayout google_protobuf_ExtensionRangeOptions_msginit = {
  118. &google_protobuf_ExtensionRangeOptions_submsgs[0],
  119. &google_protobuf_ExtensionRangeOptions__fields[0],
  120. UPB_SIZE(4, 8), 1, false,
  121. };
  122. static const upb_msglayout *const google_protobuf_FieldDescriptorProto_submsgs[1] = {
  123. &google_protobuf_FieldOptions_msginit,
  124. };
  125. static const upb_msglayout_field google_protobuf_FieldDescriptorProto__fields[10] = {
  126. {1, UPB_SIZE(32, 32), 5, 0, 9, 1},
  127. {2, UPB_SIZE(40, 48), 6, 0, 9, 1},
  128. {3, UPB_SIZE(24, 24), 3, 0, 5, 1},
  129. {4, UPB_SIZE(8, 8), 1, 0, 14, 1},
  130. {5, UPB_SIZE(16, 16), 2, 0, 14, 1},
  131. {6, UPB_SIZE(48, 64), 7, 0, 9, 1},
  132. {7, UPB_SIZE(56, 80), 8, 0, 9, 1},
  133. {8, UPB_SIZE(72, 112), 10, 0, 11, 1},
  134. {9, UPB_SIZE(28, 28), 4, 0, 5, 1},
  135. {10, UPB_SIZE(64, 96), 9, 0, 9, 1},
  136. };
  137. const upb_msglayout google_protobuf_FieldDescriptorProto_msginit = {
  138. &google_protobuf_FieldDescriptorProto_submsgs[0],
  139. &google_protobuf_FieldDescriptorProto__fields[0],
  140. UPB_SIZE(80, 128), 10, false,
  141. };
  142. static const upb_msglayout *const google_protobuf_OneofDescriptorProto_submsgs[1] = {
  143. &google_protobuf_OneofOptions_msginit,
  144. };
  145. static const upb_msglayout_field google_protobuf_OneofDescriptorProto__fields[2] = {
  146. {1, UPB_SIZE(8, 16), 1, 0, 9, 1},
  147. {2, UPB_SIZE(16, 32), 2, 0, 11, 1},
  148. };
  149. const upb_msglayout google_protobuf_OneofDescriptorProto_msginit = {
  150. &google_protobuf_OneofDescriptorProto_submsgs[0],
  151. &google_protobuf_OneofDescriptorProto__fields[0],
  152. UPB_SIZE(24, 48), 2, false,
  153. };
  154. static const upb_msglayout *const google_protobuf_EnumDescriptorProto_submsgs[3] = {
  155. &google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit,
  156. &google_protobuf_EnumOptions_msginit,
  157. &google_protobuf_EnumValueDescriptorProto_msginit,
  158. };
  159. static const upb_msglayout_field google_protobuf_EnumDescriptorProto__fields[5] = {
  160. {1, UPB_SIZE(8, 16), 1, 0, 9, 1},
  161. {2, UPB_SIZE(20, 40), 0, 2, 11, 3},
  162. {3, UPB_SIZE(16, 32), 2, 1, 11, 1},
  163. {4, UPB_SIZE(24, 48), 0, 0, 11, 3},
  164. {5, UPB_SIZE(28, 56), 0, 0, 9, 3},
  165. };
  166. const upb_msglayout google_protobuf_EnumDescriptorProto_msginit = {
  167. &google_protobuf_EnumDescriptorProto_submsgs[0],
  168. &google_protobuf_EnumDescriptorProto__fields[0],
  169. UPB_SIZE(32, 64), 5, false,
  170. };
  171. static const upb_msglayout_field google_protobuf_EnumDescriptorProto_EnumReservedRange__fields[2] = {
  172. {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
  173. {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
  174. };
  175. const upb_msglayout google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit = {
  176. NULL,
  177. &google_protobuf_EnumDescriptorProto_EnumReservedRange__fields[0],
  178. UPB_SIZE(12, 12), 2, false,
  179. };
  180. static const upb_msglayout *const google_protobuf_EnumValueDescriptorProto_submsgs[1] = {
  181. &google_protobuf_EnumValueOptions_msginit,
  182. };
  183. static const upb_msglayout_field google_protobuf_EnumValueDescriptorProto__fields[3] = {
  184. {1, UPB_SIZE(8, 16), 2, 0, 9, 1},
  185. {2, UPB_SIZE(4, 4), 1, 0, 5, 1},
  186. {3, UPB_SIZE(16, 32), 3, 0, 11, 1},
  187. };
  188. const upb_msglayout google_protobuf_EnumValueDescriptorProto_msginit = {
  189. &google_protobuf_EnumValueDescriptorProto_submsgs[0],
  190. &google_protobuf_EnumValueDescriptorProto__fields[0],
  191. UPB_SIZE(24, 48), 3, false,
  192. };
  193. static const upb_msglayout *const google_protobuf_ServiceDescriptorProto_submsgs[2] = {
  194. &google_protobuf_MethodDescriptorProto_msginit,
  195. &google_protobuf_ServiceOptions_msginit,
  196. };
  197. static const upb_msglayout_field google_protobuf_ServiceDescriptorProto__fields[3] = {
  198. {1, UPB_SIZE(8, 16), 1, 0, 9, 1},
  199. {2, UPB_SIZE(20, 40), 0, 0, 11, 3},
  200. {3, UPB_SIZE(16, 32), 2, 1, 11, 1},
  201. };
  202. const upb_msglayout google_protobuf_ServiceDescriptorProto_msginit = {
  203. &google_protobuf_ServiceDescriptorProto_submsgs[0],
  204. &google_protobuf_ServiceDescriptorProto__fields[0],
  205. UPB_SIZE(24, 48), 3, false,
  206. };
  207. static const upb_msglayout *const google_protobuf_MethodDescriptorProto_submsgs[1] = {
  208. &google_protobuf_MethodOptions_msginit,
  209. };
  210. static const upb_msglayout_field google_protobuf_MethodDescriptorProto__fields[6] = {
  211. {1, UPB_SIZE(8, 16), 3, 0, 9, 1},
  212. {2, UPB_SIZE(16, 32), 4, 0, 9, 1},
  213. {3, UPB_SIZE(24, 48), 5, 0, 9, 1},
  214. {4, UPB_SIZE(32, 64), 6, 0, 11, 1},
  215. {5, UPB_SIZE(1, 1), 1, 0, 8, 1},
  216. {6, UPB_SIZE(2, 2), 2, 0, 8, 1},
  217. };
  218. const upb_msglayout google_protobuf_MethodDescriptorProto_msginit = {
  219. &google_protobuf_MethodDescriptorProto_submsgs[0],
  220. &google_protobuf_MethodDescriptorProto__fields[0],
  221. UPB_SIZE(40, 80), 6, false,
  222. };
  223. static const upb_msglayout *const google_protobuf_FileOptions_submsgs[1] = {
  224. &google_protobuf_UninterpretedOption_msginit,
  225. };
  226. static const upb_msglayout_field google_protobuf_FileOptions__fields[19] = {
  227. {1, UPB_SIZE(32, 32), 11, 0, 9, 1},
  228. {8, UPB_SIZE(40, 48), 12, 0, 9, 1},
  229. {9, UPB_SIZE(8, 8), 1, 0, 14, 1},
  230. {10, UPB_SIZE(16, 16), 2, 0, 8, 1},
  231. {11, UPB_SIZE(48, 64), 13, 0, 9, 1},
  232. {16, UPB_SIZE(17, 17), 3, 0, 8, 1},
  233. {17, UPB_SIZE(18, 18), 4, 0, 8, 1},
  234. {18, UPB_SIZE(19, 19), 5, 0, 8, 1},
  235. {20, UPB_SIZE(20, 20), 6, 0, 8, 1},
  236. {23, UPB_SIZE(21, 21), 7, 0, 8, 1},
  237. {27, UPB_SIZE(22, 22), 8, 0, 8, 1},
  238. {31, UPB_SIZE(23, 23), 9, 0, 8, 1},
  239. {36, UPB_SIZE(56, 80), 14, 0, 9, 1},
  240. {37, UPB_SIZE(64, 96), 15, 0, 9, 1},
  241. {39, UPB_SIZE(72, 112), 16, 0, 9, 1},
  242. {40, UPB_SIZE(80, 128), 17, 0, 9, 1},
  243. {41, UPB_SIZE(88, 144), 18, 0, 9, 1},
  244. {42, UPB_SIZE(24, 24), 10, 0, 8, 1},
  245. {999, UPB_SIZE(96, 160), 0, 0, 11, 3},
  246. };
  247. const upb_msglayout google_protobuf_FileOptions_msginit = {
  248. &google_protobuf_FileOptions_submsgs[0],
  249. &google_protobuf_FileOptions__fields[0],
  250. UPB_SIZE(104, 176), 19, false,
  251. };
  252. static const upb_msglayout *const google_protobuf_MessageOptions_submsgs[1] = {
  253. &google_protobuf_UninterpretedOption_msginit,
  254. };
  255. static const upb_msglayout_field google_protobuf_MessageOptions__fields[5] = {
  256. {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
  257. {2, UPB_SIZE(2, 2), 2, 0, 8, 1},
  258. {3, UPB_SIZE(3, 3), 3, 0, 8, 1},
  259. {7, UPB_SIZE(4, 4), 4, 0, 8, 1},
  260. {999, UPB_SIZE(8, 8), 0, 0, 11, 3},
  261. };
  262. const upb_msglayout google_protobuf_MessageOptions_msginit = {
  263. &google_protobuf_MessageOptions_submsgs[0],
  264. &google_protobuf_MessageOptions__fields[0],
  265. UPB_SIZE(12, 16), 5, false,
  266. };
  267. static const upb_msglayout *const google_protobuf_FieldOptions_submsgs[1] = {
  268. &google_protobuf_UninterpretedOption_msginit,
  269. };
  270. static const upb_msglayout_field google_protobuf_FieldOptions__fields[7] = {
  271. {1, UPB_SIZE(8, 8), 1, 0, 14, 1},
  272. {2, UPB_SIZE(24, 24), 3, 0, 8, 1},
  273. {3, UPB_SIZE(25, 25), 4, 0, 8, 1},
  274. {5, UPB_SIZE(26, 26), 5, 0, 8, 1},
  275. {6, UPB_SIZE(16, 16), 2, 0, 14, 1},
  276. {10, UPB_SIZE(27, 27), 6, 0, 8, 1},
  277. {999, UPB_SIZE(28, 32), 0, 0, 11, 3},
  278. };
  279. const upb_msglayout google_protobuf_FieldOptions_msginit = {
  280. &google_protobuf_FieldOptions_submsgs[0],
  281. &google_protobuf_FieldOptions__fields[0],
  282. UPB_SIZE(32, 40), 7, false,
  283. };
  284. static const upb_msglayout *const google_protobuf_OneofOptions_submsgs[1] = {
  285. &google_protobuf_UninterpretedOption_msginit,
  286. };
  287. static const upb_msglayout_field google_protobuf_OneofOptions__fields[1] = {
  288. {999, UPB_SIZE(0, 0), 0, 0, 11, 3},
  289. };
  290. const upb_msglayout google_protobuf_OneofOptions_msginit = {
  291. &google_protobuf_OneofOptions_submsgs[0],
  292. &google_protobuf_OneofOptions__fields[0],
  293. UPB_SIZE(4, 8), 1, false,
  294. };
  295. static const upb_msglayout *const google_protobuf_EnumOptions_submsgs[1] = {
  296. &google_protobuf_UninterpretedOption_msginit,
  297. };
  298. static const upb_msglayout_field google_protobuf_EnumOptions__fields[3] = {
  299. {2, UPB_SIZE(1, 1), 1, 0, 8, 1},
  300. {3, UPB_SIZE(2, 2), 2, 0, 8, 1},
  301. {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
  302. };
  303. const upb_msglayout google_protobuf_EnumOptions_msginit = {
  304. &google_protobuf_EnumOptions_submsgs[0],
  305. &google_protobuf_EnumOptions__fields[0],
  306. UPB_SIZE(8, 16), 3, false,
  307. };
  308. static const upb_msglayout *const google_protobuf_EnumValueOptions_submsgs[1] = {
  309. &google_protobuf_UninterpretedOption_msginit,
  310. };
  311. static const upb_msglayout_field google_protobuf_EnumValueOptions__fields[2] = {
  312. {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
  313. {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
  314. };
  315. const upb_msglayout google_protobuf_EnumValueOptions_msginit = {
  316. &google_protobuf_EnumValueOptions_submsgs[0],
  317. &google_protobuf_EnumValueOptions__fields[0],
  318. UPB_SIZE(8, 16), 2, false,
  319. };
  320. static const upb_msglayout *const google_protobuf_ServiceOptions_submsgs[1] = {
  321. &google_protobuf_UninterpretedOption_msginit,
  322. };
  323. static const upb_msglayout_field google_protobuf_ServiceOptions__fields[2] = {
  324. {33, UPB_SIZE(1, 1), 1, 0, 8, 1},
  325. {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
  326. };
  327. const upb_msglayout google_protobuf_ServiceOptions_msginit = {
  328. &google_protobuf_ServiceOptions_submsgs[0],
  329. &google_protobuf_ServiceOptions__fields[0],
  330. UPB_SIZE(8, 16), 2, false,
  331. };
  332. static const upb_msglayout *const google_protobuf_MethodOptions_submsgs[1] = {
  333. &google_protobuf_UninterpretedOption_msginit,
  334. };
  335. static const upb_msglayout_field google_protobuf_MethodOptions__fields[3] = {
  336. {33, UPB_SIZE(16, 16), 2, 0, 8, 1},
  337. {34, UPB_SIZE(8, 8), 1, 0, 14, 1},
  338. {999, UPB_SIZE(20, 24), 0, 0, 11, 3},
  339. };
  340. const upb_msglayout google_protobuf_MethodOptions_msginit = {
  341. &google_protobuf_MethodOptions_submsgs[0],
  342. &google_protobuf_MethodOptions__fields[0],
  343. UPB_SIZE(24, 32), 3, false,
  344. };
  345. static const upb_msglayout *const google_protobuf_UninterpretedOption_submsgs[1] = {
  346. &google_protobuf_UninterpretedOption_NamePart_msginit,
  347. };
  348. static const upb_msglayout_field google_protobuf_UninterpretedOption__fields[7] = {
  349. {2, UPB_SIZE(56, 80), 0, 0, 11, 3},
  350. {3, UPB_SIZE(32, 32), 4, 0, 9, 1},
  351. {4, UPB_SIZE(8, 8), 1, 0, 4, 1},
  352. {5, UPB_SIZE(16, 16), 2, 0, 3, 1},
  353. {6, UPB_SIZE(24, 24), 3, 0, 1, 1},
  354. {7, UPB_SIZE(40, 48), 5, 0, 12, 1},
  355. {8, UPB_SIZE(48, 64), 6, 0, 9, 1},
  356. };
  357. const upb_msglayout google_protobuf_UninterpretedOption_msginit = {
  358. &google_protobuf_UninterpretedOption_submsgs[0],
  359. &google_protobuf_UninterpretedOption__fields[0],
  360. UPB_SIZE(64, 96), 7, false,
  361. };
  362. static const upb_msglayout_field google_protobuf_UninterpretedOption_NamePart__fields[2] = {
  363. {1, UPB_SIZE(8, 16), 2, 0, 9, 2},
  364. {2, UPB_SIZE(1, 1), 1, 0, 8, 2},
  365. };
  366. const upb_msglayout google_protobuf_UninterpretedOption_NamePart_msginit = {
  367. NULL,
  368. &google_protobuf_UninterpretedOption_NamePart__fields[0],
  369. UPB_SIZE(16, 32), 2, false,
  370. };
  371. static const upb_msglayout *const google_protobuf_SourceCodeInfo_submsgs[1] = {
  372. &google_protobuf_SourceCodeInfo_Location_msginit,
  373. };
  374. static const upb_msglayout_field google_protobuf_SourceCodeInfo__fields[1] = {
  375. {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
  376. };
  377. const upb_msglayout google_protobuf_SourceCodeInfo_msginit = {
  378. &google_protobuf_SourceCodeInfo_submsgs[0],
  379. &google_protobuf_SourceCodeInfo__fields[0],
  380. UPB_SIZE(4, 8), 1, false,
  381. };
  382. static const upb_msglayout_field google_protobuf_SourceCodeInfo_Location__fields[5] = {
  383. {1, UPB_SIZE(24, 48), 0, 0, 5, 3},
  384. {2, UPB_SIZE(28, 56), 0, 0, 5, 3},
  385. {3, UPB_SIZE(8, 16), 1, 0, 9, 1},
  386. {4, UPB_SIZE(16, 32), 2, 0, 9, 1},
  387. {6, UPB_SIZE(32, 64), 0, 0, 9, 3},
  388. };
  389. const upb_msglayout google_protobuf_SourceCodeInfo_Location_msginit = {
  390. NULL,
  391. &google_protobuf_SourceCodeInfo_Location__fields[0],
  392. UPB_SIZE(40, 80), 5, false,
  393. };
  394. static const upb_msglayout *const google_protobuf_GeneratedCodeInfo_submsgs[1] = {
  395. &google_protobuf_GeneratedCodeInfo_Annotation_msginit,
  396. };
  397. static const upb_msglayout_field google_protobuf_GeneratedCodeInfo__fields[1] = {
  398. {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
  399. };
  400. const upb_msglayout google_protobuf_GeneratedCodeInfo_msginit = {
  401. &google_protobuf_GeneratedCodeInfo_submsgs[0],
  402. &google_protobuf_GeneratedCodeInfo__fields[0],
  403. UPB_SIZE(4, 8), 1, false,
  404. };
  405. static const upb_msglayout_field google_protobuf_GeneratedCodeInfo_Annotation__fields[4] = {
  406. {1, UPB_SIZE(24, 32), 0, 0, 5, 3},
  407. {2, UPB_SIZE(16, 16), 3, 0, 9, 1},
  408. {3, UPB_SIZE(4, 4), 1, 0, 5, 1},
  409. {4, UPB_SIZE(8, 8), 2, 0, 5, 1},
  410. };
  411. const upb_msglayout google_protobuf_GeneratedCodeInfo_Annotation_msginit = {
  412. NULL,
  413. &google_protobuf_GeneratedCodeInfo_Annotation__fields[0],
  414. UPB_SIZE(32, 48), 4, false,
  415. };
  416. /* Maps descriptor type -> upb field type. */
  417. const uint8_t upb_desctype_to_fieldtype[] = {
  418. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  419. UPB_TYPE_DOUBLE, /* DOUBLE */
  420. UPB_TYPE_FLOAT, /* FLOAT */
  421. UPB_TYPE_INT64, /* INT64 */
  422. UPB_TYPE_UINT64, /* UINT64 */
  423. UPB_TYPE_INT32, /* INT32 */
  424. UPB_TYPE_UINT64, /* FIXED64 */
  425. UPB_TYPE_UINT32, /* FIXED32 */
  426. UPB_TYPE_BOOL, /* BOOL */
  427. UPB_TYPE_STRING, /* STRING */
  428. UPB_TYPE_MESSAGE, /* GROUP */
  429. UPB_TYPE_MESSAGE, /* MESSAGE */
  430. UPB_TYPE_BYTES, /* BYTES */
  431. UPB_TYPE_UINT32, /* UINT32 */
  432. UPB_TYPE_ENUM, /* ENUM */
  433. UPB_TYPE_INT32, /* SFIXED32 */
  434. UPB_TYPE_INT64, /* SFIXED64 */
  435. UPB_TYPE_INT32, /* SINT32 */
  436. UPB_TYPE_INT64, /* SINT64 */
  437. };
  438. /* Data pertaining to the parse. */
  439. typedef struct {
  440. /* Current decoding pointer. Points to the beginning of a field until we
  441. * have finished decoding the whole field. */
  442. const char *ptr;
  443. } upb_decstate;
  444. /* Data pertaining to a single message frame. */
  445. typedef struct {
  446. const char *limit;
  447. int32_t group_number; /* 0 if we are not parsing a group. */
  448. /* These members are unset for an unknown group frame. */
  449. char *msg;
  450. const upb_msglayout *m;
  451. } upb_decframe;
  452. #define CHK(x) if (!(x)) { return false; }
  453. static bool upb_skip_unknowngroup(upb_decstate *d, int field_number,
  454. const char *limit);
  455. static bool upb_decode_message(upb_decstate *d, const char *limit,
  456. int group_number, char *msg,
  457. const upb_msglayout *l);
  458. static bool upb_decode_varint(const char **ptr, const char *limit,
  459. uint64_t *val) {
  460. uint8_t byte;
  461. int bitpos = 0;
  462. const char *p = *ptr;
  463. *val = 0;
  464. do {
  465. CHK(bitpos < 70 && p < limit);
  466. byte = *p;
  467. *val |= (uint64_t)(byte & 0x7F) << bitpos;
  468. p++;
  469. bitpos += 7;
  470. } while (byte & 0x80);
  471. *ptr = p;
  472. return true;
  473. }
  474. static bool upb_decode_varint32(const char **ptr, const char *limit,
  475. uint32_t *val) {
  476. uint64_t u64;
  477. CHK(upb_decode_varint(ptr, limit, &u64) && u64 <= UINT32_MAX);
  478. *val = u64;
  479. return true;
  480. }
  481. static bool upb_decode_64bit(const char **ptr, const char *limit,
  482. uint64_t *val) {
  483. CHK(limit - *ptr >= 8);
  484. memcpy(val, *ptr, 8);
  485. *ptr += 8;
  486. return true;
  487. }
  488. static bool upb_decode_32bit(const char **ptr, const char *limit,
  489. uint32_t *val) {
  490. CHK(limit - *ptr >= 4);
  491. memcpy(val, *ptr, 4);
  492. *ptr += 4;
  493. return true;
  494. }
  495. static bool upb_decode_tag(const char **ptr, const char *limit,
  496. int *field_number, int *wire_type) {
  497. uint32_t tag = 0;
  498. CHK(upb_decode_varint32(ptr, limit, &tag));
  499. *field_number = tag >> 3;
  500. *wire_type = tag & 7;
  501. return true;
  502. }
  503. static int32_t upb_zzdecode_32(uint32_t n) {
  504. return (n >> 1) ^ -(int32_t)(n & 1);
  505. }
  506. static int64_t upb_zzdecode_64(uint64_t n) {
  507. return (n >> 1) ^ -(int64_t)(n & 1);
  508. }
  509. static bool upb_decode_string(const char **ptr, const char *limit,
  510. upb_stringview *val) {
  511. uint32_t len;
  512. CHK(upb_decode_varint32(ptr, limit, &len) &&
  513. len < INT32_MAX &&
  514. limit - *ptr >= (int32_t)len);
  515. *val = upb_stringview_make(*ptr, len);
  516. *ptr += len;
  517. return true;
  518. }
  519. static void upb_set32(void *msg, size_t ofs, uint32_t val) {
  520. memcpy((char*)msg + ofs, &val, sizeof(val));
  521. }
  522. static bool upb_append_unknown(upb_decstate *d, upb_decframe *frame,
  523. const char *start) {
  524. upb_msg_addunknown(frame->msg, start, d->ptr - start);
  525. return true;
  526. }
  527. static bool upb_skip_unknownfielddata(upb_decstate *d, upb_decframe *frame,
  528. int field_number, int wire_type) {
  529. switch (wire_type) {
  530. case UPB_WIRE_TYPE_VARINT: {
  531. uint64_t val;
  532. return upb_decode_varint(&d->ptr, frame->limit, &val);
  533. }
  534. case UPB_WIRE_TYPE_32BIT: {
  535. uint32_t val;
  536. return upb_decode_32bit(&d->ptr, frame->limit, &val);
  537. }
  538. case UPB_WIRE_TYPE_64BIT: {
  539. uint64_t val;
  540. return upb_decode_64bit(&d->ptr, frame->limit, &val);
  541. }
  542. case UPB_WIRE_TYPE_DELIMITED: {
  543. upb_stringview val;
  544. return upb_decode_string(&d->ptr, frame->limit, &val);
  545. }
  546. case UPB_WIRE_TYPE_START_GROUP:
  547. return upb_skip_unknowngroup(d, field_number, frame->limit);
  548. case UPB_WIRE_TYPE_END_GROUP:
  549. CHK(field_number == frame->group_number);
  550. frame->limit = d->ptr;
  551. return true;
  552. }
  553. return false;
  554. }
  555. static bool upb_array_grow(upb_array *arr, size_t elements) {
  556. size_t needed = arr->len + elements;
  557. size_t new_size = UPB_MAX(arr->size, 8);
  558. size_t new_bytes;
  559. size_t old_bytes;
  560. void *new_data;
  561. upb_alloc *alloc = upb_arena_alloc(arr->arena);
  562. while (new_size < needed) {
  563. new_size *= 2;
  564. }
  565. old_bytes = arr->len * arr->element_size;
  566. new_bytes = new_size * arr->element_size;
  567. new_data = upb_realloc(alloc, arr->data, old_bytes, new_bytes);
  568. CHK(new_data);
  569. arr->data = new_data;
  570. arr->size = new_size;
  571. return true;
  572. }
  573. static void *upb_array_reserve(upb_array *arr, size_t elements) {
  574. if (arr->size - arr->len < elements) {
  575. CHK(upb_array_grow(arr, elements));
  576. }
  577. return (char*)arr->data + (arr->len * arr->element_size);
  578. }
  579. static void *upb_array_add(upb_array *arr, size_t elements) {
  580. void *ret = upb_array_reserve(arr, elements);
  581. arr->len += elements;
  582. return ret;
  583. }
  584. static upb_array *upb_getarr(upb_decframe *frame,
  585. const upb_msglayout_field *field) {
  586. UPB_ASSERT(field->label == UPB_LABEL_REPEATED);
  587. return *(upb_array**)&frame->msg[field->offset];
  588. }
  589. static upb_array *upb_getorcreatearr(upb_decframe *frame,
  590. const upb_msglayout_field *field) {
  591. upb_array *arr = upb_getarr(frame, field);
  592. if (!arr) {
  593. upb_fieldtype_t type = upb_desctype_to_fieldtype[field->descriptortype];
  594. arr = upb_array_new(type, upb_msg_arena(frame->msg));
  595. if (!arr) {
  596. return NULL;
  597. }
  598. *(upb_array**)&frame->msg[field->offset] = arr;
  599. }
  600. return arr;
  601. }
  602. static void upb_sethasbit(upb_decframe *frame,
  603. const upb_msglayout_field *field) {
  604. int32_t hasbit = field->presence;
  605. UPB_ASSERT(field->presence > 0);
  606. frame->msg[hasbit / 8] |= (1 << (hasbit % 8));
  607. }
  608. static void upb_setoneofcase(upb_decframe *frame,
  609. const upb_msglayout_field *field) {
  610. UPB_ASSERT(field->presence < 0);
  611. upb_set32(frame->msg, ~field->presence, field->number);
  612. }
  613. static char *upb_decode_prepareslot(upb_decframe *frame,
  614. const upb_msglayout_field *field) {
  615. char *field_mem = frame->msg + field->offset;
  616. upb_array *arr;
  617. if (field->label == UPB_LABEL_REPEATED) {
  618. arr = upb_getorcreatearr(frame, field);
  619. field_mem = upb_array_reserve(arr, 1);
  620. }
  621. return field_mem;
  622. }
  623. static void upb_decode_setpresent(upb_decframe *frame,
  624. const upb_msglayout_field *field) {
  625. if (field->label == UPB_LABEL_REPEATED) {
  626. upb_array *arr = upb_getarr(frame, field);
  627. UPB_ASSERT(arr->len < arr->size);
  628. arr->len++;
  629. } else if (field->presence < 0) {
  630. upb_setoneofcase(frame, field);
  631. } else if (field->presence > 0) {
  632. upb_sethasbit(frame, field);
  633. }
  634. }
  635. static bool upb_decode_submsg(upb_decstate *d, upb_decframe *frame,
  636. const char *limit,
  637. const upb_msglayout_field *field,
  638. int group_number) {
  639. char *submsg_slot = upb_decode_prepareslot(frame, field);
  640. char *submsg = *(void **)submsg_slot;
  641. const upb_msglayout *subm;
  642. subm = frame->m->submsgs[field->submsg_index];
  643. UPB_ASSERT(subm);
  644. if (!submsg) {
  645. submsg = upb_msg_new(subm, upb_msg_arena(frame->msg));
  646. CHK(submsg);
  647. *(void**)submsg_slot = submsg;
  648. }
  649. upb_decode_message(d, limit, group_number, submsg, subm);
  650. return true;
  651. }
  652. static bool upb_decode_varintfield(upb_decstate *d, upb_decframe *frame,
  653. const char *field_start,
  654. const upb_msglayout_field *field) {
  655. uint64_t val;
  656. void *field_mem;
  657. field_mem = upb_decode_prepareslot(frame, field);
  658. CHK(field_mem);
  659. CHK(upb_decode_varint(&d->ptr, frame->limit, &val));
  660. switch ((upb_descriptortype_t)field->descriptortype) {
  661. case UPB_DESCRIPTOR_TYPE_INT64:
  662. case UPB_DESCRIPTOR_TYPE_UINT64:
  663. memcpy(field_mem, &val, sizeof(val));
  664. break;
  665. case UPB_DESCRIPTOR_TYPE_INT32:
  666. case UPB_DESCRIPTOR_TYPE_UINT32:
  667. case UPB_DESCRIPTOR_TYPE_ENUM: {
  668. uint32_t val32 = val;
  669. memcpy(field_mem, &val32, sizeof(val32));
  670. break;
  671. }
  672. case UPB_DESCRIPTOR_TYPE_BOOL: {
  673. bool valbool = val != 0;
  674. memcpy(field_mem, &valbool, sizeof(valbool));
  675. break;
  676. }
  677. case UPB_DESCRIPTOR_TYPE_SINT32: {
  678. int32_t decoded = upb_zzdecode_32(val);
  679. memcpy(field_mem, &decoded, sizeof(decoded));
  680. break;
  681. }
  682. case UPB_DESCRIPTOR_TYPE_SINT64: {
  683. int64_t decoded = upb_zzdecode_64(val);
  684. memcpy(field_mem, &decoded, sizeof(decoded));
  685. break;
  686. }
  687. default:
  688. return upb_append_unknown(d, frame, field_start);
  689. }
  690. upb_decode_setpresent(frame, field);
  691. return true;
  692. }
  693. static bool upb_decode_64bitfield(upb_decstate *d, upb_decframe *frame,
  694. const char *field_start,
  695. const upb_msglayout_field *field) {
  696. void *field_mem;
  697. uint64_t val;
  698. field_mem = upb_decode_prepareslot(frame, field);
  699. CHK(field_mem);
  700. CHK(upb_decode_64bit(&d->ptr, frame->limit, &val));
  701. switch ((upb_descriptortype_t)field->descriptortype) {
  702. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  703. case UPB_DESCRIPTOR_TYPE_FIXED64:
  704. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  705. memcpy(field_mem, &val, sizeof(val));
  706. break;
  707. default:
  708. return upb_append_unknown(d, frame, field_start);
  709. }
  710. upb_decode_setpresent(frame, field);
  711. return true;
  712. }
  713. static bool upb_decode_32bitfield(upb_decstate *d, upb_decframe *frame,
  714. const char *field_start,
  715. const upb_msglayout_field *field) {
  716. void *field_mem;
  717. uint32_t val;
  718. field_mem = upb_decode_prepareslot(frame, field);
  719. CHK(field_mem);
  720. CHK(upb_decode_32bit(&d->ptr, frame->limit, &val));
  721. switch ((upb_descriptortype_t)field->descriptortype) {
  722. case UPB_DESCRIPTOR_TYPE_FLOAT:
  723. case UPB_DESCRIPTOR_TYPE_FIXED32:
  724. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  725. memcpy(field_mem, &val, sizeof(val));
  726. break;
  727. default:
  728. return upb_append_unknown(d, frame, field_start);
  729. }
  730. upb_decode_setpresent(frame, field);
  731. return true;
  732. }
  733. static bool upb_decode_fixedpacked(upb_array *arr, upb_stringview data,
  734. int elem_size) {
  735. int elements = data.size / elem_size;
  736. void *field_mem;
  737. CHK((size_t)(elements * elem_size) == data.size);
  738. field_mem = upb_array_add(arr, elements);
  739. CHK(field_mem);
  740. memcpy(field_mem, data.data, data.size);
  741. return true;
  742. }
  743. static bool upb_decode_toarray(upb_decstate *d, upb_decframe *frame,
  744. const char *field_start,
  745. const upb_msglayout_field *field,
  746. upb_stringview val) {
  747. upb_array *arr = upb_getorcreatearr(frame, field);
  748. #define VARINT_CASE(ctype, decode) { \
  749. const char *ptr = val.data; \
  750. const char *limit = ptr + val.size; \
  751. while (ptr < limit) { \
  752. uint64_t val; \
  753. void *field_mem; \
  754. ctype decoded; \
  755. CHK(upb_decode_varint(&ptr, limit, &val)); \
  756. decoded = (decode)(val); \
  757. field_mem = upb_array_add(arr, 1); \
  758. CHK(field_mem); \
  759. memcpy(field_mem, &decoded, sizeof(ctype)); \
  760. } \
  761. return true; \
  762. }
  763. switch ((upb_descriptortype_t)field->descriptortype) {
  764. case UPB_DESCRIPTOR_TYPE_STRING:
  765. case UPB_DESCRIPTOR_TYPE_BYTES: {
  766. void *field_mem = upb_array_add(arr, 1);
  767. CHK(field_mem);
  768. memcpy(field_mem, &val, sizeof(val));
  769. return true;
  770. }
  771. case UPB_DESCRIPTOR_TYPE_FLOAT:
  772. case UPB_DESCRIPTOR_TYPE_FIXED32:
  773. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  774. return upb_decode_fixedpacked(arr, val, sizeof(int32_t));
  775. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  776. case UPB_DESCRIPTOR_TYPE_FIXED64:
  777. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  778. return upb_decode_fixedpacked(arr, val, sizeof(int64_t));
  779. case UPB_DESCRIPTOR_TYPE_INT32:
  780. case UPB_DESCRIPTOR_TYPE_UINT32:
  781. case UPB_DESCRIPTOR_TYPE_ENUM:
  782. /* TODO: proto2 enum field that isn't in the enum. */
  783. VARINT_CASE(uint32_t, uint32_t);
  784. case UPB_DESCRIPTOR_TYPE_INT64:
  785. case UPB_DESCRIPTOR_TYPE_UINT64:
  786. VARINT_CASE(uint64_t, uint64_t);
  787. case UPB_DESCRIPTOR_TYPE_BOOL:
  788. VARINT_CASE(bool, bool);
  789. case UPB_DESCRIPTOR_TYPE_SINT32:
  790. VARINT_CASE(int32_t, upb_zzdecode_32);
  791. case UPB_DESCRIPTOR_TYPE_SINT64:
  792. VARINT_CASE(int64_t, upb_zzdecode_64);
  793. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  794. const upb_msglayout *subm;
  795. char *submsg;
  796. void *field_mem;
  797. CHK(val.size <= (size_t)(frame->limit - val.data));
  798. d->ptr -= val.size;
  799. /* Create elemente message. */
  800. subm = frame->m->submsgs[field->submsg_index];
  801. UPB_ASSERT(subm);
  802. submsg = upb_msg_new(subm, upb_msg_arena(frame->msg));
  803. CHK(submsg);
  804. field_mem = upb_array_add(arr, 1);
  805. CHK(field_mem);
  806. *(void**)field_mem = submsg;
  807. return upb_decode_message(
  808. d, val.data + val.size, frame->group_number, submsg, subm);
  809. }
  810. case UPB_DESCRIPTOR_TYPE_GROUP:
  811. return upb_append_unknown(d, frame, field_start);
  812. }
  813. #undef VARINT_CASE
  814. UPB_UNREACHABLE();
  815. }
  816. static bool upb_decode_delimitedfield(upb_decstate *d, upb_decframe *frame,
  817. const char *field_start,
  818. const upb_msglayout_field *field) {
  819. upb_stringview val;
  820. CHK(upb_decode_string(&d->ptr, frame->limit, &val));
  821. if (field->label == UPB_LABEL_REPEATED) {
  822. return upb_decode_toarray(d, frame, field_start, field, val);
  823. } else {
  824. switch ((upb_descriptortype_t)field->descriptortype) {
  825. case UPB_DESCRIPTOR_TYPE_STRING:
  826. case UPB_DESCRIPTOR_TYPE_BYTES: {
  827. void *field_mem = upb_decode_prepareslot(frame, field);
  828. CHK(field_mem);
  829. memcpy(field_mem, &val, sizeof(val));
  830. break;
  831. }
  832. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  833. CHK(val.size <= (size_t)(frame->limit - val.data));
  834. d->ptr -= val.size;
  835. CHK(upb_decode_submsg(d, frame, val.data + val.size, field, 0));
  836. break;
  837. default:
  838. /* TODO(haberman): should we accept the last element of a packed? */
  839. return upb_append_unknown(d, frame, field_start);
  840. }
  841. upb_decode_setpresent(frame, field);
  842. return true;
  843. }
  844. }
  845. static const upb_msglayout_field *upb_find_field(const upb_msglayout *l,
  846. uint32_t field_number) {
  847. /* Lots of optimization opportunities here. */
  848. int i;
  849. for (i = 0; i < l->field_count; i++) {
  850. if (l->fields[i].number == field_number) {
  851. return &l->fields[i];
  852. }
  853. }
  854. return NULL; /* Unknown field. */
  855. }
  856. static bool upb_decode_field(upb_decstate *d, upb_decframe *frame) {
  857. int field_number;
  858. int wire_type;
  859. const char *field_start = d->ptr;
  860. const upb_msglayout_field *field;
  861. CHK(upb_decode_tag(&d->ptr, frame->limit, &field_number, &wire_type));
  862. field = upb_find_field(frame->m, field_number);
  863. if (field) {
  864. switch (wire_type) {
  865. case UPB_WIRE_TYPE_VARINT:
  866. return upb_decode_varintfield(d, frame, field_start, field);
  867. case UPB_WIRE_TYPE_32BIT:
  868. return upb_decode_32bitfield(d, frame, field_start, field);
  869. case UPB_WIRE_TYPE_64BIT:
  870. return upb_decode_64bitfield(d, frame, field_start, field);
  871. case UPB_WIRE_TYPE_DELIMITED:
  872. return upb_decode_delimitedfield(d, frame, field_start, field);
  873. case UPB_WIRE_TYPE_START_GROUP:
  874. CHK(field->descriptortype == UPB_DESCRIPTOR_TYPE_GROUP);
  875. return upb_decode_submsg(d, frame, frame->limit, field, field_number);
  876. case UPB_WIRE_TYPE_END_GROUP:
  877. CHK(frame->group_number == field_number)
  878. frame->limit = d->ptr;
  879. return true;
  880. default:
  881. return false;
  882. }
  883. } else {
  884. CHK(field_number != 0);
  885. CHK(upb_skip_unknownfielddata(d, frame, field_number, wire_type));
  886. CHK(upb_append_unknown(d, frame, field_start));
  887. return true;
  888. }
  889. }
  890. static bool upb_skip_unknowngroup(upb_decstate *d, int field_number,
  891. const char *limit) {
  892. upb_decframe frame;
  893. frame.msg = NULL;
  894. frame.m = NULL;
  895. frame.group_number = field_number;
  896. frame.limit = limit;
  897. while (d->ptr < frame.limit) {
  898. int wire_type;
  899. int field_number;
  900. CHK(upb_decode_tag(&d->ptr, frame.limit, &field_number, &wire_type));
  901. CHK(upb_skip_unknownfielddata(d, &frame, field_number, wire_type));
  902. }
  903. return true;
  904. }
  905. static bool upb_decode_message(upb_decstate *d, const char *limit,
  906. int group_number, char *msg,
  907. const upb_msglayout *l) {
  908. upb_decframe frame;
  909. frame.group_number = group_number;
  910. frame.limit = limit;
  911. frame.msg = msg;
  912. frame.m = l;
  913. while (d->ptr < frame.limit) {
  914. CHK(upb_decode_field(d, &frame));
  915. }
  916. return true;
  917. }
  918. bool upb_decode(upb_stringview buf, void *msg, const upb_msglayout *l) {
  919. upb_decstate state;
  920. state.ptr = buf.data;
  921. return upb_decode_message(&state, buf.data + buf.size, 0, msg, l);
  922. }
  923. #undef CHK
  924. #include <ctype.h>
  925. #include <stdlib.h>
  926. #include <string.h>
  927. typedef struct {
  928. size_t len;
  929. char str[1]; /* Null-terminated string data follows. */
  930. } str_t;
  931. static str_t *newstr(const char *data, size_t len) {
  932. str_t *ret = upb_gmalloc(sizeof(*ret) + len);
  933. if (!ret) return NULL;
  934. ret->len = len;
  935. memcpy(ret->str, data, len);
  936. ret->str[len] = '\0';
  937. return ret;
  938. }
  939. static void freestr(str_t *s) { upb_gfree(s); }
  940. /* isalpha() etc. from <ctype.h> are locale-dependent, which we don't want. */
  941. static bool upb_isbetween(char c, char low, char high) {
  942. return c >= low && c <= high;
  943. }
  944. static bool upb_isletter(char c) {
  945. return upb_isbetween(c, 'A', 'Z') || upb_isbetween(c, 'a', 'z') || c == '_';
  946. }
  947. static bool upb_isalphanum(char c) {
  948. return upb_isletter(c) || upb_isbetween(c, '0', '9');
  949. }
  950. static bool upb_isident(const char *str, size_t len, bool full, upb_status *s) {
  951. bool start = true;
  952. size_t i;
  953. for (i = 0; i < len; i++) {
  954. char c = str[i];
  955. if (c == '.') {
  956. if (start || !full) {
  957. upb_status_seterrf(s, "invalid name: unexpected '.' (%s)", str);
  958. return false;
  959. }
  960. start = true;
  961. } else if (start) {
  962. if (!upb_isletter(c)) {
  963. upb_status_seterrf(
  964. s, "invalid name: path components must start with a letter (%s)",
  965. str);
  966. return false;
  967. }
  968. start = false;
  969. } else {
  970. if (!upb_isalphanum(c)) {
  971. upb_status_seterrf(s, "invalid name: non-alphanumeric character (%s)",
  972. str);
  973. return false;
  974. }
  975. }
  976. }
  977. return !start;
  978. }
  979. static bool upb_isoneof(const upb_refcounted *def) {
  980. return def->vtbl == &upb_oneofdef_vtbl;
  981. }
  982. static bool upb_isfield(const upb_refcounted *def) {
  983. return def->vtbl == &upb_fielddef_vtbl;
  984. }
  985. static const upb_oneofdef *upb_trygetoneof(const upb_refcounted *def) {
  986. return upb_isoneof(def) ? (const upb_oneofdef*)def : NULL;
  987. }
  988. static const upb_fielddef *upb_trygetfield(const upb_refcounted *def) {
  989. return upb_isfield(def) ? (const upb_fielddef*)def : NULL;
  990. }
  991. /* upb_def ********************************************************************/
  992. upb_deftype_t upb_def_type(const upb_def *d) { return d->type; }
  993. const char *upb_def_fullname(const upb_def *d) { return d->fullname; }
  994. const char *upb_def_name(const upb_def *d) {
  995. const char *p;
  996. if (d->fullname == NULL) {
  997. return NULL;
  998. } else if ((p = strrchr(d->fullname, '.')) == NULL) {
  999. /* No '.' in the name, return the full string. */
  1000. return d->fullname;
  1001. } else {
  1002. /* Return one past the last '.'. */
  1003. return p + 1;
  1004. }
  1005. }
  1006. bool upb_def_setfullname(upb_def *def, const char *fullname, upb_status *s) {
  1007. UPB_ASSERT(!upb_def_isfrozen(def));
  1008. if (!upb_isident(fullname, strlen(fullname), true, s)) {
  1009. return false;
  1010. }
  1011. fullname = upb_gstrdup(fullname);
  1012. if (!fullname) {
  1013. upb_upberr_setoom(s);
  1014. return false;
  1015. }
  1016. upb_gfree((void*)def->fullname);
  1017. def->fullname = fullname;
  1018. return true;
  1019. }
  1020. const upb_filedef *upb_def_file(const upb_def *d) { return d->file; }
  1021. static bool upb_def_init(upb_def *def, upb_deftype_t type,
  1022. const struct upb_refcounted_vtbl *vtbl,
  1023. const void *owner) {
  1024. if (!upb_refcounted_init(upb_def_upcast_mutable(def), vtbl, owner)) return false;
  1025. def->type = type;
  1026. def->fullname = NULL;
  1027. def->came_from_user = false;
  1028. def->file = NULL;
  1029. return true;
  1030. }
  1031. static void upb_def_uninit(upb_def *def) {
  1032. upb_gfree((void*)def->fullname);
  1033. }
  1034. static const char *msgdef_name(const upb_msgdef *m) {
  1035. const char *name = upb_def_fullname(upb_msgdef_upcast(m));
  1036. return name ? name : "(anonymous)";
  1037. }
  1038. static bool upb_validate_field(upb_fielddef *f, upb_status *s) {
  1039. if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  1040. upb_status_seterrmsg(s, "fielddef must have name and number set");
  1041. return false;
  1042. }
  1043. if (!f->type_is_set_) {
  1044. upb_status_seterrmsg(s, "fielddef type was not initialized");
  1045. return false;
  1046. }
  1047. if (upb_fielddef_lazy(f) &&
  1048. upb_fielddef_descriptortype(f) != UPB_DESCRIPTOR_TYPE_MESSAGE) {
  1049. upb_status_seterrmsg(s,
  1050. "only length-delimited submessage fields may be lazy");
  1051. return false;
  1052. }
  1053. if (upb_fielddef_hassubdef(f)) {
  1054. const upb_def *subdef;
  1055. if (f->subdef_is_symbolic) {
  1056. upb_status_seterrf(s, "field '%s.%s' has not been resolved",
  1057. msgdef_name(f->msg.def), upb_fielddef_name(f));
  1058. return false;
  1059. }
  1060. subdef = upb_fielddef_subdef(f);
  1061. if (subdef == NULL) {
  1062. upb_status_seterrf(s, "field %s.%s is missing required subdef",
  1063. msgdef_name(f->msg.def), upb_fielddef_name(f));
  1064. return false;
  1065. }
  1066. if (!upb_def_isfrozen(subdef) && !subdef->came_from_user) {
  1067. upb_status_seterrf(s,
  1068. "subdef of field %s.%s is not frozen or being frozen",
  1069. msgdef_name(f->msg.def), upb_fielddef_name(f));
  1070. return false;
  1071. }
  1072. }
  1073. if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  1074. bool has_default_name = upb_fielddef_enumhasdefaultstr(f);
  1075. bool has_default_number = upb_fielddef_enumhasdefaultint32(f);
  1076. /* Previously verified by upb_validate_enumdef(). */
  1077. UPB_ASSERT(upb_enumdef_numvals(upb_fielddef_enumsubdef(f)) > 0);
  1078. /* We've already validated that we have an associated enumdef and that it
  1079. * has at least one member, so at least one of these should be true.
  1080. * Because if the user didn't set anything, we'll pick up the enum's
  1081. * default, but if the user *did* set something we should at least pick up
  1082. * the one they set (int32 or string). */
  1083. UPB_ASSERT(has_default_name || has_default_number);
  1084. if (!has_default_name) {
  1085. upb_status_seterrf(s,
  1086. "enum default for field %s.%s (%d) is not in the enum",
  1087. msgdef_name(f->msg.def), upb_fielddef_name(f),
  1088. upb_fielddef_defaultint32(f));
  1089. return false;
  1090. }
  1091. if (!has_default_number) {
  1092. upb_status_seterrf(s,
  1093. "enum default for field %s.%s (%s) is not in the enum",
  1094. msgdef_name(f->msg.def), upb_fielddef_name(f),
  1095. upb_fielddef_defaultstr(f, NULL));
  1096. return false;
  1097. }
  1098. /* Lift the effective numeric default into the field's default slot, in case
  1099. * we were only getting it "by reference" from the enumdef. */
  1100. upb_fielddef_setdefaultint32(f, upb_fielddef_defaultint32(f));
  1101. }
  1102. /* Ensure that MapEntry submessages only appear as repeated fields, not
  1103. * optional/required (singular) fields. */
  1104. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  1105. upb_fielddef_msgsubdef(f) != NULL) {
  1106. const upb_msgdef *subdef = upb_fielddef_msgsubdef(f);
  1107. if (upb_msgdef_mapentry(subdef) && !upb_fielddef_isseq(f)) {
  1108. upb_status_seterrf(s,
  1109. "Field %s refers to mapentry message but is not "
  1110. "a repeated field",
  1111. upb_fielddef_name(f) ? upb_fielddef_name(f) :
  1112. "(unnamed)");
  1113. return false;
  1114. }
  1115. }
  1116. return true;
  1117. }
  1118. static bool upb_validate_enumdef(const upb_enumdef *e, upb_status *s) {
  1119. if (upb_enumdef_numvals(e) == 0) {
  1120. upb_status_seterrf(s, "enum %s has no members (must have at least one)",
  1121. upb_enumdef_fullname(e));
  1122. return false;
  1123. }
  1124. return true;
  1125. }
  1126. /* All submessage fields are lower than all other fields.
  1127. * Secondly, fields are increasing in order. */
  1128. uint32_t field_rank(const upb_fielddef *f) {
  1129. uint32_t ret = upb_fielddef_number(f);
  1130. const uint32_t high_bit = 1 << 30;
  1131. UPB_ASSERT(ret < high_bit);
  1132. if (!upb_fielddef_issubmsg(f))
  1133. ret |= high_bit;
  1134. return ret;
  1135. }
  1136. int cmp_fields(const void *p1, const void *p2) {
  1137. const upb_fielddef *f1 = *(upb_fielddef*const*)p1;
  1138. const upb_fielddef *f2 = *(upb_fielddef*const*)p2;
  1139. return field_rank(f1) - field_rank(f2);
  1140. }
  1141. static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
  1142. /* Sort fields. upb internally relies on UPB_TYPE_MESSAGE fields having the
  1143. * lowest indexes, but we do not publicly guarantee this. */
  1144. upb_msg_field_iter j;
  1145. upb_msg_oneof_iter k;
  1146. int i;
  1147. uint32_t selector;
  1148. int n = upb_msgdef_numfields(m);
  1149. upb_fielddef **fields;
  1150. if (n == 0) {
  1151. m->selector_count = UPB_STATIC_SELECTOR_COUNT;
  1152. m->submsg_field_count = 0;
  1153. return true;
  1154. }
  1155. fields = upb_gmalloc(n * sizeof(*fields));
  1156. if (!fields) {
  1157. upb_upberr_setoom(s);
  1158. return false;
  1159. }
  1160. m->submsg_field_count = 0;
  1161. for(i = 0, upb_msg_field_begin(&j, m);
  1162. !upb_msg_field_done(&j);
  1163. upb_msg_field_next(&j), i++) {
  1164. upb_fielddef *f = upb_msg_iter_field(&j);
  1165. UPB_ASSERT(f->msg.def == m);
  1166. if (!upb_validate_field(f, s)) {
  1167. upb_gfree(fields);
  1168. return false;
  1169. }
  1170. if (upb_fielddef_issubmsg(f)) {
  1171. m->submsg_field_count++;
  1172. }
  1173. fields[i] = f;
  1174. }
  1175. qsort(fields, n, sizeof(*fields), cmp_fields);
  1176. selector = UPB_STATIC_SELECTOR_COUNT + m->submsg_field_count;
  1177. for (i = 0; i < n; i++) {
  1178. upb_fielddef *f = fields[i];
  1179. f->index_ = i;
  1180. f->selector_base = selector + upb_handlers_selectorbaseoffset(f);
  1181. selector += upb_handlers_selectorcount(f);
  1182. }
  1183. m->selector_count = selector;
  1184. #ifndef NDEBUG
  1185. {
  1186. /* Verify that all selectors for the message are distinct. */
  1187. #define TRY(type) \
  1188. if (upb_handlers_getselector(f, type, &sel)) upb_inttable_insert(&t, sel, v);
  1189. upb_inttable t;
  1190. upb_value v;
  1191. upb_selector_t sel;
  1192. upb_inttable_init(&t, UPB_CTYPE_BOOL);
  1193. v = upb_value_bool(true);
  1194. upb_inttable_insert(&t, UPB_STARTMSG_SELECTOR, v);
  1195. upb_inttable_insert(&t, UPB_ENDMSG_SELECTOR, v);
  1196. upb_inttable_insert(&t, UPB_UNKNOWN_SELECTOR, v);
  1197. for(upb_msg_field_begin(&j, m);
  1198. !upb_msg_field_done(&j);
  1199. upb_msg_field_next(&j)) {
  1200. upb_fielddef *f = upb_msg_iter_field(&j);
  1201. /* These calls will assert-fail in upb_table if the value already
  1202. * exists. */
  1203. TRY(UPB_HANDLER_INT32);
  1204. TRY(UPB_HANDLER_INT64)
  1205. TRY(UPB_HANDLER_UINT32)
  1206. TRY(UPB_HANDLER_UINT64)
  1207. TRY(UPB_HANDLER_FLOAT)
  1208. TRY(UPB_HANDLER_DOUBLE)
  1209. TRY(UPB_HANDLER_BOOL)
  1210. TRY(UPB_HANDLER_STARTSTR)
  1211. TRY(UPB_HANDLER_STRING)
  1212. TRY(UPB_HANDLER_ENDSTR)
  1213. TRY(UPB_HANDLER_STARTSUBMSG)
  1214. TRY(UPB_HANDLER_ENDSUBMSG)
  1215. TRY(UPB_HANDLER_STARTSEQ)
  1216. TRY(UPB_HANDLER_ENDSEQ)
  1217. }
  1218. upb_inttable_uninit(&t);
  1219. }
  1220. #undef TRY
  1221. #endif
  1222. for(upb_msg_oneof_begin(&k, m), i = 0;
  1223. !upb_msg_oneof_done(&k);
  1224. upb_msg_oneof_next(&k), i++) {
  1225. upb_oneofdef *o = upb_msg_iter_oneof(&k);
  1226. o->index = i;
  1227. }
  1228. upb_gfree(fields);
  1229. return true;
  1230. }
  1231. static void assign_msg_wellknowntype(upb_msgdef *m) {
  1232. const char *name = upb_msgdef_fullname(m);
  1233. if (name == NULL) {
  1234. m->well_known_type = UPB_WELLKNOWN_UNSPECIFIED;
  1235. return;
  1236. }
  1237. if (!strcmp(name, "google.protobuf.Duration")) {
  1238. m->well_known_type = UPB_WELLKNOWN_DURATION;
  1239. } else if (!strcmp(name, "google.protobuf.Timestamp")) {
  1240. m->well_known_type = UPB_WELLKNOWN_TIMESTAMP;
  1241. } else if (!strcmp(name, "google.protobuf.DoubleValue")) {
  1242. m->well_known_type = UPB_WELLKNOWN_DOUBLEVALUE;
  1243. } else if (!strcmp(name, "google.protobuf.FloatValue")) {
  1244. m->well_known_type = UPB_WELLKNOWN_FLOATVALUE;
  1245. } else if (!strcmp(name, "google.protobuf.Int64Value")) {
  1246. m->well_known_type = UPB_WELLKNOWN_INT64VALUE;
  1247. } else if (!strcmp(name, "google.protobuf.UInt64Value")) {
  1248. m->well_known_type = UPB_WELLKNOWN_UINT64VALUE;
  1249. } else if (!strcmp(name, "google.protobuf.Int32Value")) {
  1250. m->well_known_type = UPB_WELLKNOWN_INT32VALUE;
  1251. } else if (!strcmp(name, "google.protobuf.UInt32Value")) {
  1252. m->well_known_type = UPB_WELLKNOWN_UINT32VALUE;
  1253. } else if (!strcmp(name, "google.protobuf.BoolValue")) {
  1254. m->well_known_type = UPB_WELLKNOWN_BOOLVALUE;
  1255. } else if (!strcmp(name, "google.protobuf.StringValue")) {
  1256. m->well_known_type = UPB_WELLKNOWN_STRINGVALUE;
  1257. } else if (!strcmp(name, "google.protobuf.BytesValue")) {
  1258. m->well_known_type = UPB_WELLKNOWN_BYTESVALUE;
  1259. } else if (!strcmp(name, "google.protobuf.Value")) {
  1260. m->well_known_type = UPB_WELLKNOWN_VALUE;
  1261. } else if (!strcmp(name, "google.protobuf.ListValue")) {
  1262. m->well_known_type = UPB_WELLKNOWN_LISTVALUE;
  1263. } else if (!strcmp(name, "google.protobuf.Struct")) {
  1264. m->well_known_type = UPB_WELLKNOWN_STRUCT;
  1265. } else {
  1266. m->well_known_type = UPB_WELLKNOWN_UNSPECIFIED;
  1267. }
  1268. }
  1269. bool _upb_def_validate(upb_def *const*defs, size_t n, upb_status *s) {
  1270. size_t i;
  1271. /* First perform validation, in two passes so we can check that we have a
  1272. * transitive closure without needing to search. */
  1273. for (i = 0; i < n; i++) {
  1274. upb_def *def = defs[i];
  1275. if (upb_def_isfrozen(def)) {
  1276. /* Could relax this requirement if it's annoying. */
  1277. upb_status_seterrmsg(s, "def is already frozen");
  1278. goto err;
  1279. } else if (def->type == UPB_DEF_FIELD) {
  1280. upb_status_seterrmsg(s, "standalone fielddefs can not be frozen");
  1281. goto err;
  1282. } else {
  1283. /* Set now to detect transitive closure in the second pass. */
  1284. def->came_from_user = true;
  1285. if (def->type == UPB_DEF_ENUM &&
  1286. !upb_validate_enumdef(upb_dyncast_enumdef(def), s)) {
  1287. goto err;
  1288. }
  1289. }
  1290. }
  1291. /* Second pass of validation. Also assign selector bases and indexes, and
  1292. * compact tables. */
  1293. for (i = 0; i < n; i++) {
  1294. upb_def *def = defs[i];
  1295. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  1296. upb_enumdef *e = upb_dyncast_enumdef_mutable(def);
  1297. if (m) {
  1298. upb_inttable_compact(&m->itof);
  1299. if (!assign_msg_indices(m, s)) {
  1300. goto err;
  1301. }
  1302. assign_msg_wellknowntype(m);
  1303. /* m->well_known_type = UPB_WELLKNOWN_UNSPECIFIED; */
  1304. } else if (e) {
  1305. upb_inttable_compact(&e->iton);
  1306. }
  1307. }
  1308. return true;
  1309. err:
  1310. for (i = 0; i < n; i++) {
  1311. upb_def *def = defs[i];
  1312. def->came_from_user = false;
  1313. }
  1314. UPB_ASSERT(!(s && upb_ok(s)));
  1315. return false;
  1316. }
  1317. bool upb_def_freeze(upb_def *const* defs, size_t n, upb_status *s) {
  1318. /* Def graph contains FieldDefs between each MessageDef, so double the
  1319. * limit. */
  1320. const size_t maxdepth = UPB_MAX_MESSAGE_DEPTH * 2;
  1321. if (!_upb_def_validate(defs, n, s)) {
  1322. return false;
  1323. }
  1324. /* Validation all passed; freeze the objects. */
  1325. return upb_refcounted_freeze((upb_refcounted *const*)defs, n, s, maxdepth);
  1326. }
  1327. /* upb_enumdef ****************************************************************/
  1328. static void visitenum(const upb_refcounted *r, upb_refcounted_visit *visit,
  1329. void *closure) {
  1330. const upb_enumdef *e = (const upb_enumdef*)r;
  1331. const upb_def *def = upb_enumdef_upcast(e);
  1332. if (upb_def_file(def)) {
  1333. visit(r, upb_filedef_upcast(upb_def_file(def)), closure);
  1334. }
  1335. }
  1336. static void freeenum(upb_refcounted *r) {
  1337. upb_enumdef *e = (upb_enumdef*)r;
  1338. upb_inttable_iter i;
  1339. upb_inttable_begin(&i, &e->iton);
  1340. for( ; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  1341. /* To clean up the upb_gstrdup() from upb_enumdef_addval(). */
  1342. upb_gfree(upb_value_getcstr(upb_inttable_iter_value(&i)));
  1343. }
  1344. upb_strtable_uninit(&e->ntoi);
  1345. upb_inttable_uninit(&e->iton);
  1346. upb_def_uninit(upb_enumdef_upcast_mutable(e));
  1347. upb_gfree(e);
  1348. }
  1349. const struct upb_refcounted_vtbl upb_enumdef_vtbl = {&visitenum, &freeenum};
  1350. upb_enumdef *upb_enumdef_new(const void *owner) {
  1351. upb_enumdef *e = upb_gmalloc(sizeof(*e));
  1352. if (!e) return NULL;
  1353. if (!upb_def_init(upb_enumdef_upcast_mutable(e), UPB_DEF_ENUM,
  1354. &upb_enumdef_vtbl, owner)) {
  1355. goto err2;
  1356. }
  1357. if (!upb_strtable_init(&e->ntoi, UPB_CTYPE_INT32)) goto err2;
  1358. if (!upb_inttable_init(&e->iton, UPB_CTYPE_CSTR)) goto err1;
  1359. return e;
  1360. err1:
  1361. upb_strtable_uninit(&e->ntoi);
  1362. err2:
  1363. upb_gfree(e);
  1364. return NULL;
  1365. }
  1366. bool upb_enumdef_freeze(upb_enumdef *e, upb_status *status) {
  1367. upb_def *d = upb_enumdef_upcast_mutable(e);
  1368. return upb_def_freeze(&d, 1, status);
  1369. }
  1370. const char *upb_enumdef_fullname(const upb_enumdef *e) {
  1371. return upb_def_fullname(upb_enumdef_upcast(e));
  1372. }
  1373. const char *upb_enumdef_name(const upb_enumdef *e) {
  1374. return upb_def_name(upb_enumdef_upcast(e));
  1375. }
  1376. bool upb_enumdef_setfullname(upb_enumdef *e, const char *fullname,
  1377. upb_status *s) {
  1378. return upb_def_setfullname(upb_enumdef_upcast_mutable(e), fullname, s);
  1379. }
  1380. bool upb_enumdef_addval(upb_enumdef *e, const char *name, int32_t num,
  1381. upb_status *status) {
  1382. char *name2;
  1383. if (!upb_isident(name, strlen(name), false, status)) {
  1384. return false;
  1385. }
  1386. if (upb_enumdef_ntoiz(e, name, NULL)) {
  1387. upb_status_seterrf(status, "name '%s' is already defined", name);
  1388. return false;
  1389. }
  1390. if (!upb_strtable_insert(&e->ntoi, name, upb_value_int32(num))) {
  1391. upb_status_seterrmsg(status, "out of memory");
  1392. return false;
  1393. }
  1394. if (!upb_inttable_lookup(&e->iton, num, NULL)) {
  1395. name2 = upb_gstrdup(name);
  1396. if (!name2 || !upb_inttable_insert(&e->iton, num, upb_value_cstr(name2))) {
  1397. upb_status_seterrmsg(status, "out of memory");
  1398. upb_strtable_remove(&e->ntoi, name, NULL);
  1399. return false;
  1400. }
  1401. }
  1402. if (upb_enumdef_numvals(e) == 1) {
  1403. bool ok = upb_enumdef_setdefault(e, num, NULL);
  1404. UPB_ASSERT(ok);
  1405. }
  1406. return true;
  1407. }
  1408. int32_t upb_enumdef_default(const upb_enumdef *e) {
  1409. UPB_ASSERT(upb_enumdef_iton(e, e->defaultval));
  1410. return e->defaultval;
  1411. }
  1412. bool upb_enumdef_setdefault(upb_enumdef *e, int32_t val, upb_status *s) {
  1413. UPB_ASSERT(!upb_enumdef_isfrozen(e));
  1414. if (!upb_enumdef_iton(e, val)) {
  1415. upb_status_seterrf(s, "number '%d' is not in the enum.", val);
  1416. return false;
  1417. }
  1418. e->defaultval = val;
  1419. return true;
  1420. }
  1421. int upb_enumdef_numvals(const upb_enumdef *e) {
  1422. return upb_strtable_count(&e->ntoi);
  1423. }
  1424. void upb_enum_begin(upb_enum_iter *i, const upb_enumdef *e) {
  1425. /* We iterate over the ntoi table, to account for duplicate numbers. */
  1426. upb_strtable_begin(i, &e->ntoi);
  1427. }
  1428. void upb_enum_next(upb_enum_iter *iter) { upb_strtable_next(iter); }
  1429. bool upb_enum_done(upb_enum_iter *iter) { return upb_strtable_done(iter); }
  1430. bool upb_enumdef_ntoi(const upb_enumdef *def, const char *name,
  1431. size_t len, int32_t *num) {
  1432. upb_value v;
  1433. if (!upb_strtable_lookup2(&def->ntoi, name, len, &v)) {
  1434. return false;
  1435. }
  1436. if (num) *num = upb_value_getint32(v);
  1437. return true;
  1438. }
  1439. const char *upb_enumdef_iton(const upb_enumdef *def, int32_t num) {
  1440. upb_value v;
  1441. return upb_inttable_lookup32(&def->iton, num, &v) ?
  1442. upb_value_getcstr(v) : NULL;
  1443. }
  1444. const char *upb_enum_iter_name(upb_enum_iter *iter) {
  1445. return upb_strtable_iter_key(iter);
  1446. }
  1447. int32_t upb_enum_iter_number(upb_enum_iter *iter) {
  1448. return upb_value_getint32(upb_strtable_iter_value(iter));
  1449. }
  1450. /* upb_fielddef ***************************************************************/
  1451. static void upb_fielddef_init_default(upb_fielddef *f);
  1452. static void upb_fielddef_uninit_default(upb_fielddef *f) {
  1453. if (f->type_is_set_ && f->default_is_string && f->defaultval.bytes)
  1454. freestr(f->defaultval.bytes);
  1455. }
  1456. const char *upb_fielddef_fullname(const upb_fielddef *e) {
  1457. return upb_def_fullname(upb_fielddef_upcast(e));
  1458. }
  1459. static void visitfield(const upb_refcounted *r, upb_refcounted_visit *visit,
  1460. void *closure) {
  1461. const upb_fielddef *f = (const upb_fielddef*)r;
  1462. const upb_def *def = upb_fielddef_upcast(f);
  1463. if (upb_fielddef_containingtype(f)) {
  1464. visit(r, upb_msgdef_upcast2(upb_fielddef_containingtype(f)), closure);
  1465. }
  1466. if (upb_fielddef_containingoneof(f)) {
  1467. visit(r, upb_oneofdef_upcast(upb_fielddef_containingoneof(f)), closure);
  1468. }
  1469. if (upb_fielddef_subdef(f)) {
  1470. visit(r, upb_def_upcast(upb_fielddef_subdef(f)), closure);
  1471. }
  1472. if (upb_def_file(def)) {
  1473. visit(r, upb_filedef_upcast(upb_def_file(def)), closure);
  1474. }
  1475. }
  1476. static void freefield(upb_refcounted *r) {
  1477. upb_fielddef *f = (upb_fielddef*)r;
  1478. upb_fielddef_uninit_default(f);
  1479. if (f->subdef_is_symbolic)
  1480. upb_gfree(f->sub.name);
  1481. upb_def_uninit(upb_fielddef_upcast_mutable(f));
  1482. upb_gfree(f);
  1483. }
  1484. static const char *enumdefaultstr(const upb_fielddef *f) {
  1485. const upb_enumdef *e;
  1486. UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  1487. e = upb_fielddef_enumsubdef(f);
  1488. if (f->default_is_string && f->defaultval.bytes) {
  1489. /* Default was explicitly set as a string. */
  1490. str_t *s = f->defaultval.bytes;
  1491. return s->str;
  1492. } else if (e) {
  1493. if (!f->default_is_string) {
  1494. /* Default was explicitly set as an integer; look it up in enumdef. */
  1495. const char *name = upb_enumdef_iton(e, f->defaultval.sint);
  1496. if (name) {
  1497. return name;
  1498. }
  1499. } else {
  1500. /* Default is completely unset; pull enumdef default. */
  1501. if (upb_enumdef_numvals(e) > 0) {
  1502. const char *name = upb_enumdef_iton(e, upb_enumdef_default(e));
  1503. UPB_ASSERT(name);
  1504. return name;
  1505. }
  1506. }
  1507. }
  1508. return NULL;
  1509. }
  1510. static bool enumdefaultint32(const upb_fielddef *f, int32_t *val) {
  1511. const upb_enumdef *e;
  1512. UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  1513. e = upb_fielddef_enumsubdef(f);
  1514. if (!f->default_is_string) {
  1515. /* Default was explicitly set as an integer. */
  1516. *val = f->defaultval.sint;
  1517. return true;
  1518. } else if (e) {
  1519. if (f->defaultval.bytes) {
  1520. /* Default was explicitly set as a str; try to lookup corresponding int. */
  1521. str_t *s = f->defaultval.bytes;
  1522. if (upb_enumdef_ntoiz(e, s->str, val)) {
  1523. return true;
  1524. }
  1525. } else {
  1526. /* Default is unset; try to pull in enumdef default. */
  1527. if (upb_enumdef_numvals(e) > 0) {
  1528. *val = upb_enumdef_default(e);
  1529. return true;
  1530. }
  1531. }
  1532. }
  1533. return false;
  1534. }
  1535. const struct upb_refcounted_vtbl upb_fielddef_vtbl = {visitfield, freefield};
  1536. upb_fielddef *upb_fielddef_new(const void *o) {
  1537. upb_fielddef *f = upb_gmalloc(sizeof(*f));
  1538. if (!f) return NULL;
  1539. if (!upb_def_init(upb_fielddef_upcast_mutable(f), UPB_DEF_FIELD,
  1540. &upb_fielddef_vtbl, o)) {
  1541. upb_gfree(f);
  1542. return NULL;
  1543. }
  1544. f->msg.def = NULL;
  1545. f->sub.def = NULL;
  1546. f->oneof = NULL;
  1547. f->subdef_is_symbolic = false;
  1548. f->msg_is_symbolic = false;
  1549. f->label_ = UPB_LABEL_OPTIONAL;
  1550. f->type_ = UPB_TYPE_INT32;
  1551. f->number_ = 0;
  1552. f->type_is_set_ = false;
  1553. f->tagdelim = false;
  1554. f->is_extension_ = false;
  1555. f->lazy_ = false;
  1556. f->packed_ = true;
  1557. /* For the moment we default this to UPB_INTFMT_VARIABLE, since it will work
  1558. * with all integer types and is in some since more "default" since the most
  1559. * normal-looking proto2 types int32/int64/uint32/uint64 use variable.
  1560. *
  1561. * Other options to consider:
  1562. * - there is no default; users must set this manually (like type).
  1563. * - default signed integers to UPB_INTFMT_ZIGZAG, since it's more likely to
  1564. * be an optimal default for signed integers. */
  1565. f->intfmt = UPB_INTFMT_VARIABLE;
  1566. return f;
  1567. }
  1568. bool upb_fielddef_typeisset(const upb_fielddef *f) {
  1569. return f->type_is_set_;
  1570. }
  1571. upb_fieldtype_t upb_fielddef_type(const upb_fielddef *f) {
  1572. UPB_ASSERT(f->type_is_set_);
  1573. return f->type_;
  1574. }
  1575. uint32_t upb_fielddef_index(const upb_fielddef *f) {
  1576. return f->index_;
  1577. }
  1578. upb_label_t upb_fielddef_label(const upb_fielddef *f) {
  1579. return f->label_;
  1580. }
  1581. upb_intfmt_t upb_fielddef_intfmt(const upb_fielddef *f) {
  1582. return f->intfmt;
  1583. }
  1584. bool upb_fielddef_istagdelim(const upb_fielddef *f) {
  1585. return f->tagdelim;
  1586. }
  1587. uint32_t upb_fielddef_number(const upb_fielddef *f) {
  1588. return f->number_;
  1589. }
  1590. bool upb_fielddef_isextension(const upb_fielddef *f) {
  1591. return f->is_extension_;
  1592. }
  1593. bool upb_fielddef_lazy(const upb_fielddef *f) {
  1594. return f->lazy_;
  1595. }
  1596. bool upb_fielddef_packed(const upb_fielddef *f) {
  1597. return f->packed_;
  1598. }
  1599. const char *upb_fielddef_name(const upb_fielddef *f) {
  1600. return upb_def_fullname(upb_fielddef_upcast(f));
  1601. }
  1602. size_t upb_fielddef_getjsonname(const upb_fielddef *f, char *buf, size_t len) {
  1603. const char *name = upb_fielddef_name(f);
  1604. size_t src, dst = 0;
  1605. bool ucase_next = false;
  1606. #define WRITE(byte) \
  1607. ++dst; \
  1608. if (dst < len) buf[dst - 1] = byte; \
  1609. else if (dst == len) buf[dst - 1] = '\0'
  1610. if (!name) {
  1611. WRITE('\0');
  1612. return 0;
  1613. }
  1614. /* Implement the transformation as described in the spec:
  1615. * 1. upper case all letters after an underscore.
  1616. * 2. remove all underscores.
  1617. */
  1618. for (src = 0; name[src]; src++) {
  1619. if (name[src] == '_') {
  1620. ucase_next = true;
  1621. continue;
  1622. }
  1623. if (ucase_next) {
  1624. WRITE(toupper(name[src]));
  1625. ucase_next = false;
  1626. } else {
  1627. WRITE(name[src]);
  1628. }
  1629. }
  1630. WRITE('\0');
  1631. return dst;
  1632. #undef WRITE
  1633. }
  1634. const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f) {
  1635. return f->msg_is_symbolic ? NULL : f->msg.def;
  1636. }
  1637. const upb_oneofdef *upb_fielddef_containingoneof(const upb_fielddef *f) {
  1638. return f->oneof;
  1639. }
  1640. upb_msgdef *upb_fielddef_containingtype_mutable(upb_fielddef *f) {
  1641. return (upb_msgdef*)upb_fielddef_containingtype(f);
  1642. }
  1643. const char *upb_fielddef_containingtypename(upb_fielddef *f) {
  1644. return f->msg_is_symbolic ? f->msg.name : NULL;
  1645. }
  1646. static void release_containingtype(upb_fielddef *f) {
  1647. if (f->msg_is_symbolic) upb_gfree(f->msg.name);
  1648. }
  1649. bool upb_fielddef_setcontainingtypename(upb_fielddef *f, const char *name,
  1650. upb_status *s) {
  1651. char *name_copy;
  1652. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1653. if (upb_fielddef_containingtype(f)) {
  1654. upb_status_seterrmsg(s, "field has already been added to a message.");
  1655. return false;
  1656. }
  1657. /* TODO: validate name (upb_isident() doesn't quite work atm because this name
  1658. * may have a leading "."). */
  1659. name_copy = upb_gstrdup(name);
  1660. if (!name_copy) {
  1661. upb_upberr_setoom(s);
  1662. return false;
  1663. }
  1664. release_containingtype(f);
  1665. f->msg.name = name_copy;
  1666. f->msg_is_symbolic = true;
  1667. return true;
  1668. }
  1669. bool upb_fielddef_setname(upb_fielddef *f, const char *name, upb_status *s) {
  1670. if (upb_fielddef_containingtype(f) || upb_fielddef_containingoneof(f)) {
  1671. upb_status_seterrmsg(s, "Already added to message or oneof");
  1672. return false;
  1673. }
  1674. return upb_def_setfullname(upb_fielddef_upcast_mutable(f), name, s);
  1675. }
  1676. static void chkdefaulttype(const upb_fielddef *f, upb_fieldtype_t type) {
  1677. UPB_UNUSED(f);
  1678. UPB_UNUSED(type);
  1679. UPB_ASSERT(f->type_is_set_ && upb_fielddef_type(f) == type);
  1680. }
  1681. int64_t upb_fielddef_defaultint64(const upb_fielddef *f) {
  1682. chkdefaulttype(f, UPB_TYPE_INT64);
  1683. return f->defaultval.sint;
  1684. }
  1685. int32_t upb_fielddef_defaultint32(const upb_fielddef *f) {
  1686. if (f->type_is_set_ && upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  1687. int32_t val;
  1688. bool ok = enumdefaultint32(f, &val);
  1689. UPB_ASSERT(ok);
  1690. return val;
  1691. } else {
  1692. chkdefaulttype(f, UPB_TYPE_INT32);
  1693. return f->defaultval.sint;
  1694. }
  1695. }
  1696. uint64_t upb_fielddef_defaultuint64(const upb_fielddef *f) {
  1697. chkdefaulttype(f, UPB_TYPE_UINT64);
  1698. return f->defaultval.uint;
  1699. }
  1700. uint32_t upb_fielddef_defaultuint32(const upb_fielddef *f) {
  1701. chkdefaulttype(f, UPB_TYPE_UINT32);
  1702. return f->defaultval.uint;
  1703. }
  1704. bool upb_fielddef_defaultbool(const upb_fielddef *f) {
  1705. chkdefaulttype(f, UPB_TYPE_BOOL);
  1706. return f->defaultval.uint;
  1707. }
  1708. float upb_fielddef_defaultfloat(const upb_fielddef *f) {
  1709. chkdefaulttype(f, UPB_TYPE_FLOAT);
  1710. return f->defaultval.flt;
  1711. }
  1712. double upb_fielddef_defaultdouble(const upb_fielddef *f) {
  1713. chkdefaulttype(f, UPB_TYPE_DOUBLE);
  1714. return f->defaultval.dbl;
  1715. }
  1716. const char *upb_fielddef_defaultstr(const upb_fielddef *f, size_t *len) {
  1717. UPB_ASSERT(f->type_is_set_);
  1718. UPB_ASSERT(upb_fielddef_type(f) == UPB_TYPE_STRING ||
  1719. upb_fielddef_type(f) == UPB_TYPE_BYTES ||
  1720. upb_fielddef_type(f) == UPB_TYPE_ENUM);
  1721. if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  1722. const char *ret = enumdefaultstr(f);
  1723. UPB_ASSERT(ret);
  1724. /* Enum defaults can't have embedded NULLs. */
  1725. if (len) *len = strlen(ret);
  1726. return ret;
  1727. }
  1728. if (f->default_is_string) {
  1729. str_t *str = f->defaultval.bytes;
  1730. if (len) *len = str->len;
  1731. return str->str;
  1732. }
  1733. return NULL;
  1734. }
  1735. static void upb_fielddef_init_default(upb_fielddef *f) {
  1736. f->default_is_string = false;
  1737. switch (upb_fielddef_type(f)) {
  1738. case UPB_TYPE_DOUBLE: f->defaultval.dbl = 0; break;
  1739. case UPB_TYPE_FLOAT: f->defaultval.flt = 0; break;
  1740. case UPB_TYPE_INT32:
  1741. case UPB_TYPE_INT64: f->defaultval.sint = 0; break;
  1742. case UPB_TYPE_UINT64:
  1743. case UPB_TYPE_UINT32:
  1744. case UPB_TYPE_BOOL: f->defaultval.uint = 0; break;
  1745. case UPB_TYPE_STRING:
  1746. case UPB_TYPE_BYTES:
  1747. f->defaultval.bytes = newstr("", 0);
  1748. f->default_is_string = true;
  1749. break;
  1750. case UPB_TYPE_MESSAGE: break;
  1751. case UPB_TYPE_ENUM:
  1752. /* This is our special sentinel that indicates "not set" for an enum. */
  1753. f->default_is_string = true;
  1754. f->defaultval.bytes = NULL;
  1755. break;
  1756. }
  1757. }
  1758. const upb_def *upb_fielddef_subdef(const upb_fielddef *f) {
  1759. return f->subdef_is_symbolic ? NULL : f->sub.def;
  1760. }
  1761. const upb_msgdef *upb_fielddef_msgsubdef(const upb_fielddef *f) {
  1762. const upb_def *def = upb_fielddef_subdef(f);
  1763. return def ? upb_dyncast_msgdef(def) : NULL;
  1764. }
  1765. const upb_enumdef *upb_fielddef_enumsubdef(const upb_fielddef *f) {
  1766. const upb_def *def = upb_fielddef_subdef(f);
  1767. return def ? upb_dyncast_enumdef(def) : NULL;
  1768. }
  1769. upb_def *upb_fielddef_subdef_mutable(upb_fielddef *f) {
  1770. return (upb_def*)upb_fielddef_subdef(f);
  1771. }
  1772. const char *upb_fielddef_subdefname(const upb_fielddef *f) {
  1773. if (f->subdef_is_symbolic) {
  1774. return f->sub.name;
  1775. } else if (f->sub.def) {
  1776. return upb_def_fullname(f->sub.def);
  1777. } else {
  1778. return NULL;
  1779. }
  1780. }
  1781. bool upb_fielddef_setnumber(upb_fielddef *f, uint32_t number, upb_status *s) {
  1782. if (upb_fielddef_containingtype(f)) {
  1783. upb_status_seterrmsg(
  1784. s, "cannot change field number after adding to a message");
  1785. return false;
  1786. }
  1787. if (number == 0 || number > UPB_MAX_FIELDNUMBER) {
  1788. upb_status_seterrf(s, "invalid field number (%u)", number);
  1789. return false;
  1790. }
  1791. f->number_ = number;
  1792. return true;
  1793. }
  1794. void upb_fielddef_settype(upb_fielddef *f, upb_fieldtype_t type) {
  1795. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1796. UPB_ASSERT(upb_fielddef_checktype(type));
  1797. upb_fielddef_uninit_default(f);
  1798. f->type_ = type;
  1799. f->type_is_set_ = true;
  1800. upb_fielddef_init_default(f);
  1801. }
  1802. void upb_fielddef_setdescriptortype(upb_fielddef *f, int type) {
  1803. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1804. switch (type) {
  1805. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  1806. upb_fielddef_settype(f, UPB_TYPE_DOUBLE);
  1807. break;
  1808. case UPB_DESCRIPTOR_TYPE_FLOAT:
  1809. upb_fielddef_settype(f, UPB_TYPE_FLOAT);
  1810. break;
  1811. case UPB_DESCRIPTOR_TYPE_INT64:
  1812. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  1813. case UPB_DESCRIPTOR_TYPE_SINT64:
  1814. upb_fielddef_settype(f, UPB_TYPE_INT64);
  1815. break;
  1816. case UPB_DESCRIPTOR_TYPE_UINT64:
  1817. case UPB_DESCRIPTOR_TYPE_FIXED64:
  1818. upb_fielddef_settype(f, UPB_TYPE_UINT64);
  1819. break;
  1820. case UPB_DESCRIPTOR_TYPE_INT32:
  1821. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  1822. case UPB_DESCRIPTOR_TYPE_SINT32:
  1823. upb_fielddef_settype(f, UPB_TYPE_INT32);
  1824. break;
  1825. case UPB_DESCRIPTOR_TYPE_UINT32:
  1826. case UPB_DESCRIPTOR_TYPE_FIXED32:
  1827. upb_fielddef_settype(f, UPB_TYPE_UINT32);
  1828. break;
  1829. case UPB_DESCRIPTOR_TYPE_BOOL:
  1830. upb_fielddef_settype(f, UPB_TYPE_BOOL);
  1831. break;
  1832. case UPB_DESCRIPTOR_TYPE_STRING:
  1833. upb_fielddef_settype(f, UPB_TYPE_STRING);
  1834. break;
  1835. case UPB_DESCRIPTOR_TYPE_BYTES:
  1836. upb_fielddef_settype(f, UPB_TYPE_BYTES);
  1837. break;
  1838. case UPB_DESCRIPTOR_TYPE_GROUP:
  1839. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  1840. upb_fielddef_settype(f, UPB_TYPE_MESSAGE);
  1841. break;
  1842. case UPB_DESCRIPTOR_TYPE_ENUM:
  1843. upb_fielddef_settype(f, UPB_TYPE_ENUM);
  1844. break;
  1845. default: UPB_ASSERT(false);
  1846. }
  1847. if (type == UPB_DESCRIPTOR_TYPE_FIXED64 ||
  1848. type == UPB_DESCRIPTOR_TYPE_FIXED32 ||
  1849. type == UPB_DESCRIPTOR_TYPE_SFIXED64 ||
  1850. type == UPB_DESCRIPTOR_TYPE_SFIXED32) {
  1851. upb_fielddef_setintfmt(f, UPB_INTFMT_FIXED);
  1852. } else if (type == UPB_DESCRIPTOR_TYPE_SINT64 ||
  1853. type == UPB_DESCRIPTOR_TYPE_SINT32) {
  1854. upb_fielddef_setintfmt(f, UPB_INTFMT_ZIGZAG);
  1855. } else {
  1856. upb_fielddef_setintfmt(f, UPB_INTFMT_VARIABLE);
  1857. }
  1858. upb_fielddef_settagdelim(f, type == UPB_DESCRIPTOR_TYPE_GROUP);
  1859. }
  1860. upb_descriptortype_t upb_fielddef_descriptortype(const upb_fielddef *f) {
  1861. switch (upb_fielddef_type(f)) {
  1862. case UPB_TYPE_FLOAT: return UPB_DESCRIPTOR_TYPE_FLOAT;
  1863. case UPB_TYPE_DOUBLE: return UPB_DESCRIPTOR_TYPE_DOUBLE;
  1864. case UPB_TYPE_BOOL: return UPB_DESCRIPTOR_TYPE_BOOL;
  1865. case UPB_TYPE_STRING: return UPB_DESCRIPTOR_TYPE_STRING;
  1866. case UPB_TYPE_BYTES: return UPB_DESCRIPTOR_TYPE_BYTES;
  1867. case UPB_TYPE_ENUM: return UPB_DESCRIPTOR_TYPE_ENUM;
  1868. case UPB_TYPE_INT32:
  1869. switch (upb_fielddef_intfmt(f)) {
  1870. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT32;
  1871. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED32;
  1872. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT32;
  1873. }
  1874. case UPB_TYPE_INT64:
  1875. switch (upb_fielddef_intfmt(f)) {
  1876. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT64;
  1877. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED64;
  1878. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT64;
  1879. }
  1880. case UPB_TYPE_UINT32:
  1881. switch (upb_fielddef_intfmt(f)) {
  1882. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT32;
  1883. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED32;
  1884. case UPB_INTFMT_ZIGZAG: return -1;
  1885. }
  1886. case UPB_TYPE_UINT64:
  1887. switch (upb_fielddef_intfmt(f)) {
  1888. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT64;
  1889. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED64;
  1890. case UPB_INTFMT_ZIGZAG: return -1;
  1891. }
  1892. case UPB_TYPE_MESSAGE:
  1893. return upb_fielddef_istagdelim(f) ?
  1894. UPB_DESCRIPTOR_TYPE_GROUP : UPB_DESCRIPTOR_TYPE_MESSAGE;
  1895. }
  1896. return 0;
  1897. }
  1898. void upb_fielddef_setisextension(upb_fielddef *f, bool is_extension) {
  1899. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1900. f->is_extension_ = is_extension;
  1901. }
  1902. void upb_fielddef_setlazy(upb_fielddef *f, bool lazy) {
  1903. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1904. f->lazy_ = lazy;
  1905. }
  1906. void upb_fielddef_setpacked(upb_fielddef *f, bool packed) {
  1907. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1908. f->packed_ = packed;
  1909. }
  1910. void upb_fielddef_setlabel(upb_fielddef *f, upb_label_t label) {
  1911. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1912. UPB_ASSERT(upb_fielddef_checklabel(label));
  1913. f->label_ = label;
  1914. }
  1915. void upb_fielddef_setintfmt(upb_fielddef *f, upb_intfmt_t fmt) {
  1916. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1917. UPB_ASSERT(upb_fielddef_checkintfmt(fmt));
  1918. f->intfmt = fmt;
  1919. }
  1920. void upb_fielddef_settagdelim(upb_fielddef *f, bool tag_delim) {
  1921. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1922. f->tagdelim = tag_delim;
  1923. f->tagdelim = tag_delim;
  1924. }
  1925. static bool checksetdefault(upb_fielddef *f, upb_fieldtype_t type) {
  1926. if (!f->type_is_set_ || upb_fielddef_isfrozen(f) ||
  1927. upb_fielddef_type(f) != type) {
  1928. UPB_ASSERT(false);
  1929. return false;
  1930. }
  1931. if (f->default_is_string) {
  1932. str_t *s = f->defaultval.bytes;
  1933. UPB_ASSERT(s || type == UPB_TYPE_ENUM);
  1934. if (s) freestr(s);
  1935. }
  1936. f->default_is_string = false;
  1937. return true;
  1938. }
  1939. void upb_fielddef_setdefaultint64(upb_fielddef *f, int64_t value) {
  1940. if (checksetdefault(f, UPB_TYPE_INT64))
  1941. f->defaultval.sint = value;
  1942. }
  1943. void upb_fielddef_setdefaultint32(upb_fielddef *f, int32_t value) {
  1944. if ((upb_fielddef_type(f) == UPB_TYPE_ENUM &&
  1945. checksetdefault(f, UPB_TYPE_ENUM)) ||
  1946. checksetdefault(f, UPB_TYPE_INT32)) {
  1947. f->defaultval.sint = value;
  1948. }
  1949. }
  1950. void upb_fielddef_setdefaultuint64(upb_fielddef *f, uint64_t value) {
  1951. if (checksetdefault(f, UPB_TYPE_UINT64))
  1952. f->defaultval.uint = value;
  1953. }
  1954. void upb_fielddef_setdefaultuint32(upb_fielddef *f, uint32_t value) {
  1955. if (checksetdefault(f, UPB_TYPE_UINT32))
  1956. f->defaultval.uint = value;
  1957. }
  1958. void upb_fielddef_setdefaultbool(upb_fielddef *f, bool value) {
  1959. if (checksetdefault(f, UPB_TYPE_BOOL))
  1960. f->defaultval.uint = value;
  1961. }
  1962. void upb_fielddef_setdefaultfloat(upb_fielddef *f, float value) {
  1963. if (checksetdefault(f, UPB_TYPE_FLOAT))
  1964. f->defaultval.flt = value;
  1965. }
  1966. void upb_fielddef_setdefaultdouble(upb_fielddef *f, double value) {
  1967. if (checksetdefault(f, UPB_TYPE_DOUBLE))
  1968. f->defaultval.dbl = value;
  1969. }
  1970. bool upb_fielddef_setdefaultstr(upb_fielddef *f, const void *str, size_t len,
  1971. upb_status *s) {
  1972. str_t *str2;
  1973. UPB_ASSERT(upb_fielddef_isstring(f) || f->type_ == UPB_TYPE_ENUM);
  1974. if (f->type_ == UPB_TYPE_ENUM && !upb_isident(str, len, false, s))
  1975. return false;
  1976. if (f->default_is_string) {
  1977. str_t *s = f->defaultval.bytes;
  1978. UPB_ASSERT(s || f->type_ == UPB_TYPE_ENUM);
  1979. if (s) freestr(s);
  1980. } else {
  1981. UPB_ASSERT(f->type_ == UPB_TYPE_ENUM);
  1982. }
  1983. str2 = newstr(str, len);
  1984. f->defaultval.bytes = str2;
  1985. f->default_is_string = true;
  1986. return true;
  1987. }
  1988. void upb_fielddef_setdefaultcstr(upb_fielddef *f, const char *str,
  1989. upb_status *s) {
  1990. UPB_ASSERT(f->type_is_set_);
  1991. upb_fielddef_setdefaultstr(f, str, str ? strlen(str) : 0, s);
  1992. }
  1993. bool upb_fielddef_enumhasdefaultint32(const upb_fielddef *f) {
  1994. int32_t val;
  1995. UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  1996. return enumdefaultint32(f, &val);
  1997. }
  1998. bool upb_fielddef_enumhasdefaultstr(const upb_fielddef *f) {
  1999. UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  2000. return enumdefaultstr(f) != NULL;
  2001. }
  2002. static bool upb_subdef_typecheck(upb_fielddef *f, const upb_def *subdef,
  2003. upb_status *s) {
  2004. if (f->type_ == UPB_TYPE_MESSAGE) {
  2005. if (upb_dyncast_msgdef(subdef)) return true;
  2006. upb_status_seterrmsg(s, "invalid subdef type for this submessage field");
  2007. return false;
  2008. } else if (f->type_ == UPB_TYPE_ENUM) {
  2009. if (upb_dyncast_enumdef(subdef)) return true;
  2010. upb_status_seterrmsg(s, "invalid subdef type for this enum field");
  2011. return false;
  2012. } else {
  2013. upb_status_seterrmsg(s, "only message and enum fields can have a subdef");
  2014. return false;
  2015. }
  2016. }
  2017. static void release_subdef(upb_fielddef *f) {
  2018. if (f->subdef_is_symbolic) {
  2019. upb_gfree(f->sub.name);
  2020. } else if (f->sub.def) {
  2021. upb_unref2(f->sub.def, f);
  2022. }
  2023. }
  2024. bool upb_fielddef_setsubdef(upb_fielddef *f, const upb_def *subdef,
  2025. upb_status *s) {
  2026. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  2027. UPB_ASSERT(upb_fielddef_hassubdef(f));
  2028. if (subdef && !upb_subdef_typecheck(f, subdef, s)) return false;
  2029. release_subdef(f);
  2030. f->sub.def = subdef;
  2031. f->subdef_is_symbolic = false;
  2032. if (f->sub.def) upb_ref2(f->sub.def, f);
  2033. return true;
  2034. }
  2035. bool upb_fielddef_setmsgsubdef(upb_fielddef *f, const upb_msgdef *subdef,
  2036. upb_status *s) {
  2037. return upb_fielddef_setsubdef(f, upb_msgdef_upcast(subdef), s);
  2038. }
  2039. bool upb_fielddef_setenumsubdef(upb_fielddef *f, const upb_enumdef *subdef,
  2040. upb_status *s) {
  2041. return upb_fielddef_setsubdef(f, upb_enumdef_upcast(subdef), s);
  2042. }
  2043. bool upb_fielddef_setsubdefname(upb_fielddef *f, const char *name,
  2044. upb_status *s) {
  2045. char *name_copy;
  2046. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  2047. if (!upb_fielddef_hassubdef(f)) {
  2048. upb_status_seterrmsg(s, "field type does not accept a subdef");
  2049. return false;
  2050. }
  2051. name_copy = upb_gstrdup(name);
  2052. if (!name_copy) {
  2053. upb_upberr_setoom(s);
  2054. return false;
  2055. }
  2056. /* TODO: validate name (upb_isident() doesn't quite work atm because this name
  2057. * may have a leading "."). */
  2058. release_subdef(f);
  2059. f->sub.name = name_copy;
  2060. f->subdef_is_symbolic = true;
  2061. return true;
  2062. }
  2063. bool upb_fielddef_issubmsg(const upb_fielddef *f) {
  2064. return upb_fielddef_type(f) == UPB_TYPE_MESSAGE;
  2065. }
  2066. bool upb_fielddef_isstring(const upb_fielddef *f) {
  2067. return upb_fielddef_type(f) == UPB_TYPE_STRING ||
  2068. upb_fielddef_type(f) == UPB_TYPE_BYTES;
  2069. }
  2070. bool upb_fielddef_isseq(const upb_fielddef *f) {
  2071. return upb_fielddef_label(f) == UPB_LABEL_REPEATED;
  2072. }
  2073. bool upb_fielddef_isprimitive(const upb_fielddef *f) {
  2074. return !upb_fielddef_isstring(f) && !upb_fielddef_issubmsg(f);
  2075. }
  2076. bool upb_fielddef_ismap(const upb_fielddef *f) {
  2077. return upb_fielddef_isseq(f) && upb_fielddef_issubmsg(f) &&
  2078. upb_msgdef_mapentry(upb_fielddef_msgsubdef(f));
  2079. }
  2080. bool upb_fielddef_haspresence(const upb_fielddef *f) {
  2081. if (upb_fielddef_isseq(f)) return false;
  2082. if (upb_fielddef_issubmsg(f)) return true;
  2083. /* Primitive field: return true unless there is a message that specifies
  2084. * presence should not exist. */
  2085. if (f->msg_is_symbolic || !f->msg.def) return true;
  2086. return f->msg.def->syntax == UPB_SYNTAX_PROTO2;
  2087. }
  2088. bool upb_fielddef_hassubdef(const upb_fielddef *f) {
  2089. return upb_fielddef_issubmsg(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM;
  2090. }
  2091. static bool between(int32_t x, int32_t low, int32_t high) {
  2092. return x >= low && x <= high;
  2093. }
  2094. bool upb_fielddef_checklabel(int32_t label) { return between(label, 1, 3); }
  2095. bool upb_fielddef_checktype(int32_t type) { return between(type, 1, 11); }
  2096. bool upb_fielddef_checkintfmt(int32_t fmt) { return between(fmt, 1, 3); }
  2097. bool upb_fielddef_checkdescriptortype(int32_t type) {
  2098. return between(type, 1, 18);
  2099. }
  2100. /* upb_msgdef *****************************************************************/
  2101. static void visitmsg(const upb_refcounted *r, upb_refcounted_visit *visit,
  2102. void *closure) {
  2103. upb_msg_oneof_iter o;
  2104. const upb_msgdef *m = (const upb_msgdef*)r;
  2105. const upb_def *def = upb_msgdef_upcast(m);
  2106. upb_msg_field_iter i;
  2107. for(upb_msg_field_begin(&i, m);
  2108. !upb_msg_field_done(&i);
  2109. upb_msg_field_next(&i)) {
  2110. upb_fielddef *f = upb_msg_iter_field(&i);
  2111. visit(r, upb_fielddef_upcast2(f), closure);
  2112. }
  2113. for(upb_msg_oneof_begin(&o, m);
  2114. !upb_msg_oneof_done(&o);
  2115. upb_msg_oneof_next(&o)) {
  2116. upb_oneofdef *f = upb_msg_iter_oneof(&o);
  2117. visit(r, upb_oneofdef_upcast(f), closure);
  2118. }
  2119. if (upb_def_file(def)) {
  2120. visit(r, upb_filedef_upcast(upb_def_file(def)), closure);
  2121. }
  2122. }
  2123. static void freemsg(upb_refcounted *r) {
  2124. upb_msgdef *m = (upb_msgdef*)r;
  2125. upb_strtable_uninit(&m->ntof);
  2126. upb_inttable_uninit(&m->itof);
  2127. upb_def_uninit(upb_msgdef_upcast_mutable(m));
  2128. upb_gfree(m);
  2129. }
  2130. const struct upb_refcounted_vtbl upb_msgdef_vtbl = {visitmsg, freemsg};
  2131. upb_msgdef *upb_msgdef_new(const void *owner) {
  2132. upb_msgdef *m = upb_gmalloc(sizeof(*m));
  2133. if (!m) return NULL;
  2134. if (!upb_def_init(upb_msgdef_upcast_mutable(m), UPB_DEF_MSG, &upb_msgdef_vtbl,
  2135. owner)) {
  2136. goto err2;
  2137. }
  2138. if (!upb_inttable_init(&m->itof, UPB_CTYPE_PTR)) goto err2;
  2139. if (!upb_strtable_init(&m->ntof, UPB_CTYPE_PTR)) goto err1;
  2140. m->map_entry = false;
  2141. m->syntax = UPB_SYNTAX_PROTO2;
  2142. return m;
  2143. err1:
  2144. upb_inttable_uninit(&m->itof);
  2145. err2:
  2146. upb_gfree(m);
  2147. return NULL;
  2148. }
  2149. bool upb_msgdef_freeze(upb_msgdef *m, upb_status *status) {
  2150. upb_def *d = upb_msgdef_upcast_mutable(m);
  2151. return upb_def_freeze(&d, 1, status);
  2152. }
  2153. const char *upb_msgdef_fullname(const upb_msgdef *m) {
  2154. return upb_def_fullname(upb_msgdef_upcast(m));
  2155. }
  2156. const char *upb_msgdef_name(const upb_msgdef *m) {
  2157. return upb_def_name(upb_msgdef_upcast(m));
  2158. }
  2159. bool upb_msgdef_setfullname(upb_msgdef *m, const char *fullname,
  2160. upb_status *s) {
  2161. return upb_def_setfullname(upb_msgdef_upcast_mutable(m), fullname, s);
  2162. }
  2163. bool upb_msgdef_setsyntax(upb_msgdef *m, upb_syntax_t syntax) {
  2164. if (syntax != UPB_SYNTAX_PROTO2 && syntax != UPB_SYNTAX_PROTO3) {
  2165. return false;
  2166. }
  2167. m->syntax = syntax;
  2168. return true;
  2169. }
  2170. upb_syntax_t upb_msgdef_syntax(const upb_msgdef *m) {
  2171. return m->syntax;
  2172. }
  2173. /* Helper: check that the field |f| is safe to add to msgdef |m|. Set an error
  2174. * on status |s| and return false if not. */
  2175. static bool check_field_add(const upb_msgdef *m, const upb_fielddef *f,
  2176. upb_status *s) {
  2177. if (upb_fielddef_containingtype(f) != NULL) {
  2178. upb_status_seterrmsg(s, "fielddef already belongs to a message");
  2179. return false;
  2180. } else if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  2181. upb_status_seterrmsg(s, "field name or number were not set");
  2182. return false;
  2183. } else if (upb_msgdef_itof(m, upb_fielddef_number(f))) {
  2184. upb_status_seterrmsg(s, "duplicate field number");
  2185. return false;
  2186. } else if (upb_strtable_lookup(&m->ntof, upb_fielddef_name(f), NULL)) {
  2187. upb_status_seterrmsg(s, "name conflicts with existing field or oneof");
  2188. return false;
  2189. }
  2190. return true;
  2191. }
  2192. static void add_field(upb_msgdef *m, upb_fielddef *f, const void *ref_donor) {
  2193. release_containingtype(f);
  2194. f->msg.def = m;
  2195. f->msg_is_symbolic = false;
  2196. upb_inttable_insert(&m->itof, upb_fielddef_number(f), upb_value_ptr(f));
  2197. upb_strtable_insert(&m->ntof, upb_fielddef_name(f), upb_value_ptr(f));
  2198. upb_ref2(f, m);
  2199. upb_ref2(m, f);
  2200. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  2201. }
  2202. bool upb_msgdef_addfield(upb_msgdef *m, upb_fielddef *f, const void *ref_donor,
  2203. upb_status *s) {
  2204. /* TODO: extensions need to have a separate namespace, because proto2 allows a
  2205. * top-level extension (ie. one not in any package) to have the same name as a
  2206. * field from the message.
  2207. *
  2208. * This also implies that there needs to be a separate lookup-by-name method
  2209. * for extensions. It seems desirable for iteration to return both extensions
  2210. * and non-extensions though.
  2211. *
  2212. * We also need to validate that the field number is in an extension range iff
  2213. * it is an extension.
  2214. *
  2215. * This method is idempotent. Check if |f| is already part of this msgdef and
  2216. * return immediately if so. */
  2217. if (upb_fielddef_containingtype(f) == m) {
  2218. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  2219. return true;
  2220. }
  2221. /* Check constraints for all fields before performing any action. */
  2222. if (!check_field_add(m, f, s)) {
  2223. return false;
  2224. } else if (upb_fielddef_containingoneof(f) != NULL) {
  2225. /* Fields in a oneof can only be added by adding the oneof to the msgdef. */
  2226. upb_status_seterrmsg(s, "fielddef is part of a oneof");
  2227. return false;
  2228. }
  2229. /* Constraint checks ok, perform the action. */
  2230. add_field(m, f, ref_donor);
  2231. return true;
  2232. }
  2233. bool upb_msgdef_addoneof(upb_msgdef *m, upb_oneofdef *o, const void *ref_donor,
  2234. upb_status *s) {
  2235. upb_oneof_iter it;
  2236. /* Check various conditions that would prevent this oneof from being added. */
  2237. if (upb_oneofdef_containingtype(o)) {
  2238. upb_status_seterrmsg(s, "oneofdef already belongs to a message");
  2239. return false;
  2240. } else if (upb_oneofdef_name(o) == NULL) {
  2241. upb_status_seterrmsg(s, "oneofdef name was not set");
  2242. return false;
  2243. } else if (upb_strtable_lookup(&m->ntof, upb_oneofdef_name(o), NULL)) {
  2244. upb_status_seterrmsg(s, "name conflicts with existing field or oneof");
  2245. return false;
  2246. }
  2247. /* Check that all of the oneof's fields do not conflict with names or numbers
  2248. * of fields already in the message. */
  2249. for (upb_oneof_begin(&it, o); !upb_oneof_done(&it); upb_oneof_next(&it)) {
  2250. const upb_fielddef *f = upb_oneof_iter_field(&it);
  2251. if (!check_field_add(m, f, s)) {
  2252. return false;
  2253. }
  2254. }
  2255. /* Everything checks out -- commit now. */
  2256. /* Add oneof itself first. */
  2257. o->parent = m;
  2258. upb_strtable_insert(&m->ntof, upb_oneofdef_name(o), upb_value_ptr(o));
  2259. upb_ref2(o, m);
  2260. upb_ref2(m, o);
  2261. /* Add each field of the oneof directly to the msgdef. */
  2262. for (upb_oneof_begin(&it, o); !upb_oneof_done(&it); upb_oneof_next(&it)) {
  2263. upb_fielddef *f = upb_oneof_iter_field(&it);
  2264. add_field(m, f, NULL);
  2265. }
  2266. if (ref_donor) upb_oneofdef_unref(o, ref_donor);
  2267. return true;
  2268. }
  2269. const upb_fielddef *upb_msgdef_itof(const upb_msgdef *m, uint32_t i) {
  2270. upb_value val;
  2271. return upb_inttable_lookup32(&m->itof, i, &val) ?
  2272. upb_value_getptr(val) : NULL;
  2273. }
  2274. const upb_fielddef *upb_msgdef_ntof(const upb_msgdef *m, const char *name,
  2275. size_t len) {
  2276. upb_value val;
  2277. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  2278. return NULL;
  2279. }
  2280. return upb_trygetfield(upb_value_getptr(val));
  2281. }
  2282. const upb_oneofdef *upb_msgdef_ntoo(const upb_msgdef *m, const char *name,
  2283. size_t len) {
  2284. upb_value val;
  2285. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  2286. return NULL;
  2287. }
  2288. return upb_trygetoneof(upb_value_getptr(val));
  2289. }
  2290. bool upb_msgdef_lookupname(const upb_msgdef *m, const char *name, size_t len,
  2291. const upb_fielddef **f, const upb_oneofdef **o) {
  2292. upb_value val;
  2293. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  2294. return false;
  2295. }
  2296. *o = upb_trygetoneof(upb_value_getptr(val));
  2297. *f = upb_trygetfield(upb_value_getptr(val));
  2298. UPB_ASSERT((*o != NULL) ^ (*f != NULL)); /* Exactly one of the two should be set. */
  2299. return true;
  2300. }
  2301. int upb_msgdef_numfields(const upb_msgdef *m) {
  2302. /* The number table contains only fields. */
  2303. return upb_inttable_count(&m->itof);
  2304. }
  2305. int upb_msgdef_numoneofs(const upb_msgdef *m) {
  2306. /* The name table includes oneofs, and the number table does not. */
  2307. return upb_strtable_count(&m->ntof) - upb_inttable_count(&m->itof);
  2308. }
  2309. void upb_msgdef_setmapentry(upb_msgdef *m, bool map_entry) {
  2310. UPB_ASSERT(!upb_msgdef_isfrozen(m));
  2311. m->map_entry = map_entry;
  2312. }
  2313. bool upb_msgdef_mapentry(const upb_msgdef *m) {
  2314. return m->map_entry;
  2315. }
  2316. upb_wellknowntype_t upb_msgdef_wellknowntype(const upb_msgdef *m) {
  2317. return m->well_known_type;
  2318. }
  2319. bool upb_msgdef_isnumberwrapper(const upb_msgdef *m) {
  2320. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  2321. return type >= UPB_WELLKNOWN_DOUBLEVALUE &&
  2322. type <= UPB_WELLKNOWN_UINT32VALUE;
  2323. }
  2324. void upb_msg_field_begin(upb_msg_field_iter *iter, const upb_msgdef *m) {
  2325. upb_inttable_begin(iter, &m->itof);
  2326. }
  2327. void upb_msg_field_next(upb_msg_field_iter *iter) { upb_inttable_next(iter); }
  2328. bool upb_msg_field_done(const upb_msg_field_iter *iter) {
  2329. return upb_inttable_done(iter);
  2330. }
  2331. upb_fielddef *upb_msg_iter_field(const upb_msg_field_iter *iter) {
  2332. return (upb_fielddef*)upb_value_getptr(upb_inttable_iter_value(iter));
  2333. }
  2334. void upb_msg_field_iter_setdone(upb_msg_field_iter *iter) {
  2335. upb_inttable_iter_setdone(iter);
  2336. }
  2337. void upb_msg_oneof_begin(upb_msg_oneof_iter *iter, const upb_msgdef *m) {
  2338. upb_strtable_begin(iter, &m->ntof);
  2339. /* We need to skip past any initial fields. */
  2340. while (!upb_strtable_done(iter) &&
  2341. !upb_isoneof(upb_value_getptr(upb_strtable_iter_value(iter)))) {
  2342. upb_strtable_next(iter);
  2343. }
  2344. }
  2345. void upb_msg_oneof_next(upb_msg_oneof_iter *iter) {
  2346. /* We need to skip past fields to return only oneofs. */
  2347. do {
  2348. upb_strtable_next(iter);
  2349. } while (!upb_strtable_done(iter) &&
  2350. !upb_isoneof(upb_value_getptr(upb_strtable_iter_value(iter))));
  2351. }
  2352. bool upb_msg_oneof_done(const upb_msg_oneof_iter *iter) {
  2353. return upb_strtable_done(iter);
  2354. }
  2355. upb_oneofdef *upb_msg_iter_oneof(const upb_msg_oneof_iter *iter) {
  2356. return (upb_oneofdef*)upb_value_getptr(upb_strtable_iter_value(iter));
  2357. }
  2358. void upb_msg_oneof_iter_setdone(upb_msg_oneof_iter *iter) {
  2359. upb_strtable_iter_setdone(iter);
  2360. }
  2361. /* upb_oneofdef ***************************************************************/
  2362. static void visitoneof(const upb_refcounted *r, upb_refcounted_visit *visit,
  2363. void *closure) {
  2364. const upb_oneofdef *o = (const upb_oneofdef*)r;
  2365. upb_oneof_iter i;
  2366. for (upb_oneof_begin(&i, o); !upb_oneof_done(&i); upb_oneof_next(&i)) {
  2367. const upb_fielddef *f = upb_oneof_iter_field(&i);
  2368. visit(r, upb_fielddef_upcast2(f), closure);
  2369. }
  2370. if (o->parent) {
  2371. visit(r, upb_msgdef_upcast2(o->parent), closure);
  2372. }
  2373. }
  2374. static void freeoneof(upb_refcounted *r) {
  2375. upb_oneofdef *o = (upb_oneofdef*)r;
  2376. upb_strtable_uninit(&o->ntof);
  2377. upb_inttable_uninit(&o->itof);
  2378. upb_gfree((void*)o->name);
  2379. upb_gfree(o);
  2380. }
  2381. const struct upb_refcounted_vtbl upb_oneofdef_vtbl = {visitoneof, freeoneof};
  2382. upb_oneofdef *upb_oneofdef_new(const void *owner) {
  2383. upb_oneofdef *o = upb_gmalloc(sizeof(*o));
  2384. if (!o) {
  2385. return NULL;
  2386. }
  2387. o->parent = NULL;
  2388. o->name = NULL;
  2389. if (!upb_refcounted_init(upb_oneofdef_upcast_mutable(o), &upb_oneofdef_vtbl,
  2390. owner)) {
  2391. goto err2;
  2392. }
  2393. if (!upb_inttable_init(&o->itof, UPB_CTYPE_PTR)) goto err2;
  2394. if (!upb_strtable_init(&o->ntof, UPB_CTYPE_PTR)) goto err1;
  2395. return o;
  2396. err1:
  2397. upb_inttable_uninit(&o->itof);
  2398. err2:
  2399. upb_gfree(o);
  2400. return NULL;
  2401. }
  2402. const char *upb_oneofdef_name(const upb_oneofdef *o) { return o->name; }
  2403. bool upb_oneofdef_setname(upb_oneofdef *o, const char *name, upb_status *s) {
  2404. UPB_ASSERT(!upb_oneofdef_isfrozen(o));
  2405. if (upb_oneofdef_containingtype(o)) {
  2406. upb_status_seterrmsg(s, "oneof already added to a message");
  2407. return false;
  2408. }
  2409. if (!upb_isident(name, strlen(name), true, s)) {
  2410. return false;
  2411. }
  2412. name = upb_gstrdup(name);
  2413. if (!name) {
  2414. upb_status_seterrmsg(s, "One of memory");
  2415. return false;
  2416. }
  2417. upb_gfree((void*)o->name);
  2418. o->name = name;
  2419. return true;
  2420. }
  2421. const upb_msgdef *upb_oneofdef_containingtype(const upb_oneofdef *o) {
  2422. return o->parent;
  2423. }
  2424. int upb_oneofdef_numfields(const upb_oneofdef *o) {
  2425. return upb_strtable_count(&o->ntof);
  2426. }
  2427. uint32_t upb_oneofdef_index(const upb_oneofdef *o) {
  2428. return o->index;
  2429. }
  2430. bool upb_oneofdef_addfield(upb_oneofdef *o, upb_fielddef *f,
  2431. const void *ref_donor,
  2432. upb_status *s) {
  2433. UPB_ASSERT(!upb_oneofdef_isfrozen(o));
  2434. UPB_ASSERT(!o->parent || !upb_msgdef_isfrozen(o->parent));
  2435. /* This method is idempotent. Check if |f| is already part of this oneofdef
  2436. * and return immediately if so. */
  2437. if (upb_fielddef_containingoneof(f) == o) {
  2438. return true;
  2439. }
  2440. /* The field must have an OPTIONAL label. */
  2441. if (upb_fielddef_label(f) != UPB_LABEL_OPTIONAL) {
  2442. upb_status_seterrmsg(s, "fields in oneof must have OPTIONAL label");
  2443. return false;
  2444. }
  2445. /* Check that no field with this name or number exists already in the oneof.
  2446. * Also check that the field is not already part of a oneof. */
  2447. if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  2448. upb_status_seterrmsg(s, "field name or number were not set");
  2449. return false;
  2450. } else if (upb_oneofdef_itof(o, upb_fielddef_number(f)) ||
  2451. upb_oneofdef_ntofz(o, upb_fielddef_name(f))) {
  2452. upb_status_seterrmsg(s, "duplicate field name or number");
  2453. return false;
  2454. } else if (upb_fielddef_containingoneof(f) != NULL) {
  2455. upb_status_seterrmsg(s, "fielddef already belongs to a oneof");
  2456. return false;
  2457. }
  2458. /* We allow adding a field to the oneof either if the field is not part of a
  2459. * msgdef, or if it is and we are also part of the same msgdef. */
  2460. if (o->parent == NULL) {
  2461. /* If we're not in a msgdef, the field cannot be either. Otherwise we would
  2462. * need to magically add this oneof to a msgdef to remain consistent, which
  2463. * is surprising behavior. */
  2464. if (upb_fielddef_containingtype(f) != NULL) {
  2465. upb_status_seterrmsg(s, "fielddef already belongs to a message, but "
  2466. "oneof does not");
  2467. return false;
  2468. }
  2469. } else {
  2470. /* If we're in a msgdef, the user can add fields that either aren't in any
  2471. * msgdef (in which case they're added to our msgdef) or already a part of
  2472. * our msgdef. */
  2473. if (upb_fielddef_containingtype(f) != NULL &&
  2474. upb_fielddef_containingtype(f) != o->parent) {
  2475. upb_status_seterrmsg(s, "fielddef belongs to a different message "
  2476. "than oneof");
  2477. return false;
  2478. }
  2479. }
  2480. /* Commit phase. First add the field to our parent msgdef, if any, because
  2481. * that may fail; then add the field to our own tables. */
  2482. if (o->parent != NULL && upb_fielddef_containingtype(f) == NULL) {
  2483. if (!upb_msgdef_addfield((upb_msgdef*)o->parent, f, NULL, s)) {
  2484. return false;
  2485. }
  2486. }
  2487. release_containingtype(f);
  2488. f->oneof = o;
  2489. upb_inttable_insert(&o->itof, upb_fielddef_number(f), upb_value_ptr(f));
  2490. upb_strtable_insert(&o->ntof, upb_fielddef_name(f), upb_value_ptr(f));
  2491. upb_ref2(f, o);
  2492. upb_ref2(o, f);
  2493. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  2494. return true;
  2495. }
  2496. const upb_fielddef *upb_oneofdef_ntof(const upb_oneofdef *o,
  2497. const char *name, size_t length) {
  2498. upb_value val;
  2499. return upb_strtable_lookup2(&o->ntof, name, length, &val) ?
  2500. upb_value_getptr(val) : NULL;
  2501. }
  2502. const upb_fielddef *upb_oneofdef_itof(const upb_oneofdef *o, uint32_t num) {
  2503. upb_value val;
  2504. return upb_inttable_lookup32(&o->itof, num, &val) ?
  2505. upb_value_getptr(val) : NULL;
  2506. }
  2507. void upb_oneof_begin(upb_oneof_iter *iter, const upb_oneofdef *o) {
  2508. upb_inttable_begin(iter, &o->itof);
  2509. }
  2510. void upb_oneof_next(upb_oneof_iter *iter) {
  2511. upb_inttable_next(iter);
  2512. }
  2513. bool upb_oneof_done(upb_oneof_iter *iter) {
  2514. return upb_inttable_done(iter);
  2515. }
  2516. upb_fielddef *upb_oneof_iter_field(const upb_oneof_iter *iter) {
  2517. return (upb_fielddef*)upb_value_getptr(upb_inttable_iter_value(iter));
  2518. }
  2519. void upb_oneof_iter_setdone(upb_oneof_iter *iter) {
  2520. upb_inttable_iter_setdone(iter);
  2521. }
  2522. /* upb_filedef ****************************************************************/
  2523. static void visitfiledef(const upb_refcounted *r, upb_refcounted_visit *visit,
  2524. void *closure) {
  2525. const upb_filedef *f = (const upb_filedef*)r;
  2526. size_t i;
  2527. for(i = 0; i < upb_filedef_defcount(f); i++) {
  2528. visit(r, upb_def_upcast(upb_filedef_def(f, i)), closure);
  2529. }
  2530. }
  2531. static void freefiledef(upb_refcounted *r) {
  2532. upb_filedef *f = (upb_filedef*)r;
  2533. size_t i;
  2534. for(i = 0; i < upb_filedef_depcount(f); i++) {
  2535. upb_filedef_unref(upb_filedef_dep(f, i), f);
  2536. }
  2537. upb_inttable_uninit(&f->defs);
  2538. upb_inttable_uninit(&f->deps);
  2539. upb_gfree((void*)f->name);
  2540. upb_gfree((void*)f->package);
  2541. upb_gfree((void*)f->phpprefix);
  2542. upb_gfree((void*)f->phpnamespace);
  2543. upb_gfree(f);
  2544. }
  2545. const struct upb_refcounted_vtbl upb_filedef_vtbl = {visitfiledef, freefiledef};
  2546. upb_filedef *upb_filedef_new(const void *owner) {
  2547. upb_filedef *f = upb_gmalloc(sizeof(*f));
  2548. if (!f) {
  2549. return NULL;
  2550. }
  2551. f->package = NULL;
  2552. f->name = NULL;
  2553. f->phpprefix = NULL;
  2554. f->phpnamespace = NULL;
  2555. f->syntax = UPB_SYNTAX_PROTO2;
  2556. if (!upb_refcounted_init(upb_filedef_upcast_mutable(f), &upb_filedef_vtbl,
  2557. owner)) {
  2558. goto err;
  2559. }
  2560. if (!upb_inttable_init(&f->defs, UPB_CTYPE_CONSTPTR)) {
  2561. goto err;
  2562. }
  2563. if (!upb_inttable_init(&f->deps, UPB_CTYPE_CONSTPTR)) {
  2564. goto err2;
  2565. }
  2566. return f;
  2567. err2:
  2568. upb_inttable_uninit(&f->defs);
  2569. err:
  2570. upb_gfree(f);
  2571. return NULL;
  2572. }
  2573. const char *upb_filedef_name(const upb_filedef *f) {
  2574. return f->name;
  2575. }
  2576. const char *upb_filedef_package(const upb_filedef *f) {
  2577. return f->package;
  2578. }
  2579. const char *upb_filedef_phpprefix(const upb_filedef *f) {
  2580. return f->phpprefix;
  2581. }
  2582. const char *upb_filedef_phpnamespace(const upb_filedef *f) {
  2583. return f->phpnamespace;
  2584. }
  2585. upb_syntax_t upb_filedef_syntax(const upb_filedef *f) {
  2586. return f->syntax;
  2587. }
  2588. size_t upb_filedef_defcount(const upb_filedef *f) {
  2589. return upb_inttable_count(&f->defs);
  2590. }
  2591. size_t upb_filedef_depcount(const upb_filedef *f) {
  2592. return upb_inttable_count(&f->deps);
  2593. }
  2594. const upb_def *upb_filedef_def(const upb_filedef *f, size_t i) {
  2595. upb_value v;
  2596. if (upb_inttable_lookup32(&f->defs, i, &v)) {
  2597. return upb_value_getconstptr(v);
  2598. } else {
  2599. return NULL;
  2600. }
  2601. }
  2602. const upb_filedef *upb_filedef_dep(const upb_filedef *f, size_t i) {
  2603. upb_value v;
  2604. if (upb_inttable_lookup32(&f->deps, i, &v)) {
  2605. return upb_value_getconstptr(v);
  2606. } else {
  2607. return NULL;
  2608. }
  2609. }
  2610. bool upb_filedef_setname(upb_filedef *f, const char *name, upb_status *s) {
  2611. name = upb_gstrdup(name);
  2612. if (!name) {
  2613. upb_upberr_setoom(s);
  2614. return false;
  2615. }
  2616. upb_gfree((void*)f->name);
  2617. f->name = name;
  2618. return true;
  2619. }
  2620. bool upb_filedef_setpackage(upb_filedef *f, const char *package,
  2621. upb_status *s) {
  2622. if (!upb_isident(package, strlen(package), true, s)) return false;
  2623. package = upb_gstrdup(package);
  2624. if (!package) {
  2625. upb_upberr_setoom(s);
  2626. return false;
  2627. }
  2628. upb_gfree((void*)f->package);
  2629. f->package = package;
  2630. return true;
  2631. }
  2632. bool upb_filedef_setphpprefix(upb_filedef *f, const char *phpprefix,
  2633. upb_status *s) {
  2634. phpprefix = upb_gstrdup(phpprefix);
  2635. if (!phpprefix) {
  2636. upb_upberr_setoom(s);
  2637. return false;
  2638. }
  2639. upb_gfree((void*)f->phpprefix);
  2640. f->phpprefix = phpprefix;
  2641. return true;
  2642. }
  2643. bool upb_filedef_setphpnamespace(upb_filedef *f, const char *phpnamespace,
  2644. upb_status *s) {
  2645. phpnamespace = upb_gstrdup(phpnamespace);
  2646. if (!phpnamespace) {
  2647. upb_upberr_setoom(s);
  2648. return false;
  2649. }
  2650. upb_gfree((void*)f->phpnamespace);
  2651. f->phpnamespace = phpnamespace;
  2652. return true;
  2653. }
  2654. bool upb_filedef_setsyntax(upb_filedef *f, upb_syntax_t syntax,
  2655. upb_status *s) {
  2656. UPB_UNUSED(s);
  2657. if (syntax != UPB_SYNTAX_PROTO2 &&
  2658. syntax != UPB_SYNTAX_PROTO3) {
  2659. upb_status_seterrmsg(s, "Unknown syntax value.");
  2660. return false;
  2661. }
  2662. f->syntax = syntax;
  2663. {
  2664. /* Set all messages in this file to match. */
  2665. size_t i;
  2666. for (i = 0; i < upb_filedef_defcount(f); i++) {
  2667. /* Casting const away is safe since all defs in mutable filedef must
  2668. * also be mutable. */
  2669. upb_def *def = (upb_def*)upb_filedef_def(f, i);
  2670. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  2671. if (m) {
  2672. m->syntax = syntax;
  2673. }
  2674. }
  2675. }
  2676. return true;
  2677. }
  2678. bool upb_filedef_adddef(upb_filedef *f, upb_def *def, const void *ref_donor,
  2679. upb_status *s) {
  2680. if (def->file) {
  2681. upb_status_seterrmsg(s, "Def is already part of another filedef.");
  2682. return false;
  2683. }
  2684. if (upb_inttable_push(&f->defs, upb_value_constptr(def))) {
  2685. def->file = f;
  2686. upb_ref2(def, f);
  2687. upb_ref2(f, def);
  2688. if (ref_donor) upb_def_unref(def, ref_donor);
  2689. if (def->type == UPB_DEF_MSG) {
  2690. upb_downcast_msgdef_mutable(def)->syntax = f->syntax;
  2691. }
  2692. return true;
  2693. } else {
  2694. upb_upberr_setoom(s);
  2695. return false;
  2696. }
  2697. }
  2698. bool upb_filedef_adddep(upb_filedef *f, const upb_filedef *dep) {
  2699. if (upb_inttable_push(&f->deps, upb_value_constptr(dep))) {
  2700. /* Regular ref instead of ref2 because files can't form cycles. */
  2701. upb_filedef_ref(dep, f);
  2702. return true;
  2703. } else {
  2704. return false;
  2705. }
  2706. }
  2707. void upb_symtab_free(upb_symtab *s) {
  2708. upb_strtable_iter i;
  2709. upb_strtable_begin(&i, &s->symtab);
  2710. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  2711. const upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  2712. upb_def_unref(def, s);
  2713. }
  2714. upb_strtable_uninit(&s->symtab);
  2715. upb_gfree(s);
  2716. }
  2717. upb_symtab *upb_symtab_new() {
  2718. upb_symtab *s = upb_gmalloc(sizeof(*s));
  2719. if (!s) {
  2720. return NULL;
  2721. }
  2722. upb_strtable_init(&s->symtab, UPB_CTYPE_PTR);
  2723. return s;
  2724. }
  2725. const upb_def *upb_symtab_lookup(const upb_symtab *s, const char *sym) {
  2726. upb_value v;
  2727. upb_def *ret = upb_strtable_lookup(&s->symtab, sym, &v) ?
  2728. upb_value_getptr(v) : NULL;
  2729. return ret;
  2730. }
  2731. const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym) {
  2732. upb_value v;
  2733. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  2734. upb_value_getptr(v) : NULL;
  2735. return def ? upb_dyncast_msgdef(def) : NULL;
  2736. }
  2737. const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym) {
  2738. upb_value v;
  2739. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  2740. upb_value_getptr(v) : NULL;
  2741. return def ? upb_dyncast_enumdef(def) : NULL;
  2742. }
  2743. /* Given a symbol and the base symbol inside which it is defined, find the
  2744. * symbol's definition in t. */
  2745. static upb_def *upb_resolvename(const upb_strtable *t,
  2746. const char *base, const char *sym) {
  2747. if(strlen(sym) == 0) return NULL;
  2748. if(sym[0] == '.') {
  2749. /* Symbols starting with '.' are absolute, so we do a single lookup.
  2750. * Slice to omit the leading '.' */
  2751. upb_value v;
  2752. return upb_strtable_lookup(t, sym + 1, &v) ? upb_value_getptr(v) : NULL;
  2753. } else {
  2754. /* Remove components from base until we find an entry or run out.
  2755. * TODO: This branch is totally broken, but currently not used. */
  2756. (void)base;
  2757. UPB_ASSERT(false);
  2758. return NULL;
  2759. }
  2760. }
  2761. const upb_def *upb_symtab_resolve(const upb_symtab *s, const char *base,
  2762. const char *sym) {
  2763. upb_def *ret = upb_resolvename(&s->symtab, base, sym);
  2764. return ret;
  2765. }
  2766. /* TODO(haberman): we need a lot more testing of error conditions. */
  2767. static bool symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
  2768. void *ref_donor, upb_refcounted *freeze_also,
  2769. upb_status *status) {
  2770. size_t i;
  2771. size_t add_n;
  2772. size_t freeze_n;
  2773. upb_strtable_iter iter;
  2774. upb_refcounted **add_objs = NULL;
  2775. upb_def **add_defs = NULL;
  2776. size_t add_objs_size;
  2777. upb_strtable addtab;
  2778. if (n == 0 && !freeze_also) {
  2779. return true;
  2780. }
  2781. if (!upb_strtable_init(&addtab, UPB_CTYPE_PTR)) {
  2782. upb_status_seterrmsg(status, "out of memory");
  2783. return false;
  2784. }
  2785. /* Add new defs to our "add" set. */
  2786. for (i = 0; i < n; i++) {
  2787. upb_def *def = defs[i];
  2788. const char *fullname;
  2789. upb_fielddef *f;
  2790. if (upb_def_isfrozen(def)) {
  2791. upb_status_seterrmsg(status, "added defs must be mutable");
  2792. goto err;
  2793. }
  2794. UPB_ASSERT(!upb_def_isfrozen(def));
  2795. fullname = upb_def_fullname(def);
  2796. if (!fullname) {
  2797. upb_status_seterrmsg(
  2798. status, "Anonymous defs cannot be added to a symtab");
  2799. goto err;
  2800. }
  2801. f = upb_dyncast_fielddef_mutable(def);
  2802. if (f) {
  2803. if (!upb_fielddef_containingtypename(f)) {
  2804. upb_status_seterrmsg(status,
  2805. "Standalone fielddefs must have a containing type "
  2806. "(extendee) name set");
  2807. goto err;
  2808. }
  2809. } else {
  2810. if (upb_strtable_lookup(&addtab, fullname, NULL)) {
  2811. upb_status_seterrf(status, "Conflicting defs named '%s'", fullname);
  2812. goto err;
  2813. }
  2814. if (upb_strtable_lookup(&s->symtab, fullname, NULL)) {
  2815. upb_status_seterrf(status, "Symtab already has a def named '%s'",
  2816. fullname);
  2817. goto err;
  2818. }
  2819. if (!upb_strtable_insert(&addtab, fullname, upb_value_ptr(def)))
  2820. goto oom_err;
  2821. upb_def_donateref(def, ref_donor, s);
  2822. }
  2823. if (upb_dyncast_fielddef_mutable(def)) {
  2824. /* TODO(haberman): allow adding extensions attached to files. */
  2825. upb_status_seterrf(status, "Can't add extensions to symtab.\n");
  2826. goto err;
  2827. }
  2828. }
  2829. /* Now using the table, resolve symbolic references for subdefs. */
  2830. upb_strtable_begin(&iter, &addtab);
  2831. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  2832. const char *base;
  2833. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
  2834. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  2835. upb_msg_field_iter j;
  2836. if (!m) continue;
  2837. /* Type names are resolved relative to the message in which they appear. */
  2838. base = upb_msgdef_fullname(m);
  2839. for(upb_msg_field_begin(&j, m);
  2840. !upb_msg_field_done(&j);
  2841. upb_msg_field_next(&j)) {
  2842. upb_fielddef *f = upb_msg_iter_field(&j);
  2843. const char *name = upb_fielddef_subdefname(f);
  2844. if (name && !upb_fielddef_subdef(f)) {
  2845. /* Try the lookup in the current set of to-be-added defs first. If not
  2846. * there, try existing defs. */
  2847. upb_def *subdef = upb_resolvename(&addtab, base, name);
  2848. if (subdef == NULL) {
  2849. subdef = upb_resolvename(&s->symtab, base, name);
  2850. }
  2851. if (subdef == NULL) {
  2852. upb_status_seterrf(
  2853. status, "couldn't resolve name '%s' in message '%s'", name, base);
  2854. goto err;
  2855. } else if (!upb_fielddef_setsubdef(f, subdef, status)) {
  2856. goto err;
  2857. }
  2858. }
  2859. }
  2860. }
  2861. /* We need an array of the defs in addtab, for passing to
  2862. * upb_refcounted_freeze(). */
  2863. add_objs_size = upb_strtable_count(&addtab);
  2864. if (freeze_also) {
  2865. add_objs_size++;
  2866. }
  2867. add_defs = upb_gmalloc(sizeof(void*) * add_objs_size);
  2868. if (add_defs == NULL) goto oom_err;
  2869. upb_strtable_begin(&iter, &addtab);
  2870. for (add_n = 0; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  2871. add_defs[add_n++] = upb_value_getptr(upb_strtable_iter_value(&iter));
  2872. }
  2873. /* Validate defs. */
  2874. if (!_upb_def_validate(add_defs, add_n, status)) {
  2875. goto err;
  2876. }
  2877. /* Cheat a little and give the array a new type.
  2878. * This is probably undefined behavior, but this code will be deleted soon. */
  2879. add_objs = (upb_refcounted**)add_defs;
  2880. freeze_n = add_n;
  2881. if (freeze_also) {
  2882. add_objs[freeze_n++] = freeze_also;
  2883. }
  2884. if (!upb_refcounted_freeze(add_objs, freeze_n, status,
  2885. UPB_MAX_MESSAGE_DEPTH * 2)) {
  2886. goto err;
  2887. }
  2888. /* This must be delayed until all errors have been detected, since error
  2889. * recovery code uses this table to cleanup defs. */
  2890. upb_strtable_uninit(&addtab);
  2891. /* TODO(haberman) we don't properly handle errors after this point (like
  2892. * OOM in upb_strtable_insert() below). */
  2893. for (i = 0; i < add_n; i++) {
  2894. upb_def *def = (upb_def*)add_objs[i];
  2895. const char *name = upb_def_fullname(def);
  2896. bool success;
  2897. success = upb_strtable_insert(&s->symtab, name, upb_value_ptr(def));
  2898. UPB_ASSERT(success);
  2899. }
  2900. upb_gfree(add_defs);
  2901. return true;
  2902. oom_err:
  2903. upb_status_seterrmsg(status, "out of memory");
  2904. err: {
  2905. /* We need to donate the refs back. */
  2906. upb_strtable_begin(&iter, &addtab);
  2907. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  2908. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
  2909. upb_def_donateref(def, s, ref_donor);
  2910. }
  2911. }
  2912. upb_strtable_uninit(&addtab);
  2913. upb_gfree(add_defs);
  2914. UPB_ASSERT(!upb_ok(status));
  2915. return false;
  2916. }
  2917. bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
  2918. void *ref_donor, upb_status *status) {
  2919. return symtab_add(s, defs, n, ref_donor, NULL, status);
  2920. }
  2921. bool upb_symtab_addfile(upb_symtab *s, upb_filedef *file, upb_status *status) {
  2922. size_t n;
  2923. size_t i;
  2924. upb_def **defs;
  2925. bool ret;
  2926. n = upb_filedef_defcount(file);
  2927. if (n == 0) {
  2928. return true;
  2929. }
  2930. defs = upb_gmalloc(sizeof(*defs) * n);
  2931. if (defs == NULL) {
  2932. upb_status_seterrmsg(status, "Out of memory");
  2933. return false;
  2934. }
  2935. for (i = 0; i < n; i++) {
  2936. defs[i] = upb_filedef_mutabledef(file, i);
  2937. }
  2938. ret = symtab_add(s, defs, n, NULL, upb_filedef_upcast_mutable(file), status);
  2939. upb_gfree(defs);
  2940. return ret;
  2941. }
  2942. /* Iteration. */
  2943. static void advance_to_matching(upb_symtab_iter *iter) {
  2944. if (iter->type == UPB_DEF_ANY)
  2945. return;
  2946. while (!upb_strtable_done(&iter->iter) &&
  2947. iter->type != upb_symtab_iter_def(iter)->type) {
  2948. upb_strtable_next(&iter->iter);
  2949. }
  2950. }
  2951. void upb_symtab_begin(upb_symtab_iter *iter, const upb_symtab *s,
  2952. upb_deftype_t type) {
  2953. upb_strtable_begin(&iter->iter, &s->symtab);
  2954. iter->type = type;
  2955. advance_to_matching(iter);
  2956. }
  2957. void upb_symtab_next(upb_symtab_iter *iter) {
  2958. upb_strtable_next(&iter->iter);
  2959. advance_to_matching(iter);
  2960. }
  2961. bool upb_symtab_done(const upb_symtab_iter *iter) {
  2962. return upb_strtable_done(&iter->iter);
  2963. }
  2964. const upb_def *upb_symtab_iter_def(const upb_symtab_iter *iter) {
  2965. return upb_value_getptr(upb_strtable_iter_value(&iter->iter));
  2966. }
  2967. /* We encode backwards, to avoid pre-computing lengths (one-pass encode). */
  2968. #define UPB_PB_VARINT_MAX_LEN 10
  2969. #define CHK(x) do { if (!(x)) { return false; } } while(0)
  2970. /* Maps descriptor type -> upb field type. */
  2971. static const uint8_t upb_desctype_to_fieldtype2[] = {
  2972. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  2973. UPB_TYPE_DOUBLE, /* DOUBLE */
  2974. UPB_TYPE_FLOAT, /* FLOAT */
  2975. UPB_TYPE_INT64, /* INT64 */
  2976. UPB_TYPE_UINT64, /* UINT64 */
  2977. UPB_TYPE_INT32, /* INT32 */
  2978. UPB_TYPE_UINT64, /* FIXED64 */
  2979. UPB_TYPE_UINT32, /* FIXED32 */
  2980. UPB_TYPE_BOOL, /* BOOL */
  2981. UPB_TYPE_STRING, /* STRING */
  2982. UPB_TYPE_MESSAGE, /* GROUP */
  2983. UPB_TYPE_MESSAGE, /* MESSAGE */
  2984. UPB_TYPE_BYTES, /* BYTES */
  2985. UPB_TYPE_UINT32, /* UINT32 */
  2986. UPB_TYPE_ENUM, /* ENUM */
  2987. UPB_TYPE_INT32, /* SFIXED32 */
  2988. UPB_TYPE_INT64, /* SFIXED64 */
  2989. UPB_TYPE_INT32, /* SINT32 */
  2990. UPB_TYPE_INT64, /* SINT64 */
  2991. };
  2992. static size_t upb_encode_varint(uint64_t val, char *buf) {
  2993. size_t i;
  2994. if (val < 128) { buf[0] = val; return 1; }
  2995. i = 0;
  2996. while (val) {
  2997. uint8_t byte = val & 0x7fU;
  2998. val >>= 7;
  2999. if (val) byte |= 0x80U;
  3000. buf[i++] = byte;
  3001. }
  3002. return i;
  3003. }
  3004. static uint32_t upb_zzencode_32(int32_t n) { return (n << 1) ^ (n >> 31); }
  3005. static uint64_t upb_zzencode_64(int64_t n) { return (n << 1) ^ (n >> 63); }
  3006. typedef struct {
  3007. upb_alloc *alloc;
  3008. char *buf, *ptr, *limit;
  3009. } upb_encstate;
  3010. static size_t upb_roundup_pow2(size_t bytes) {
  3011. size_t ret = 128;
  3012. while (ret < bytes) {
  3013. ret *= 2;
  3014. }
  3015. return ret;
  3016. }
  3017. static bool upb_encode_growbuffer(upb_encstate *e, size_t bytes) {
  3018. size_t old_size = e->limit - e->buf;
  3019. size_t new_size = upb_roundup_pow2(bytes + (e->limit - e->ptr));
  3020. char *new_buf = upb_realloc(e->alloc, e->buf, old_size, new_size);
  3021. CHK(new_buf);
  3022. /* We want previous data at the end, realloc() put it at the beginning. */
  3023. memmove(new_buf + new_size - old_size, e->buf, old_size);
  3024. e->ptr = new_buf + new_size - (e->limit - e->ptr);
  3025. e->limit = new_buf + new_size;
  3026. e->buf = new_buf;
  3027. return true;
  3028. }
  3029. /* Call to ensure that at least "bytes" bytes are available for writing at
  3030. * e->ptr. Returns false if the bytes could not be allocated. */
  3031. static bool upb_encode_reserve(upb_encstate *e, size_t bytes) {
  3032. CHK(UPB_LIKELY((size_t)(e->ptr - e->buf) >= bytes) ||
  3033. upb_encode_growbuffer(e, bytes));
  3034. e->ptr -= bytes;
  3035. return true;
  3036. }
  3037. /* Writes the given bytes to the buffer, handling reserve/advance. */
  3038. static bool upb_put_bytes(upb_encstate *e, const void *data, size_t len) {
  3039. CHK(upb_encode_reserve(e, len));
  3040. memcpy(e->ptr, data, len);
  3041. return true;
  3042. }
  3043. static bool upb_put_fixed64(upb_encstate *e, uint64_t val) {
  3044. /* TODO(haberman): byte-swap for big endian. */
  3045. return upb_put_bytes(e, &val, sizeof(uint64_t));
  3046. }
  3047. static bool upb_put_fixed32(upb_encstate *e, uint32_t val) {
  3048. /* TODO(haberman): byte-swap for big endian. */
  3049. return upb_put_bytes(e, &val, sizeof(uint32_t));
  3050. }
  3051. static bool upb_put_varint(upb_encstate *e, uint64_t val) {
  3052. size_t len;
  3053. char *start;
  3054. CHK(upb_encode_reserve(e, UPB_PB_VARINT_MAX_LEN));
  3055. len = upb_encode_varint(val, e->ptr);
  3056. start = e->ptr + UPB_PB_VARINT_MAX_LEN - len;
  3057. memmove(start, e->ptr, len);
  3058. e->ptr = start;
  3059. return true;
  3060. }
  3061. static bool upb_put_double(upb_encstate *e, double d) {
  3062. uint64_t u64;
  3063. UPB_ASSERT(sizeof(double) == sizeof(uint64_t));
  3064. memcpy(&u64, &d, sizeof(uint64_t));
  3065. return upb_put_fixed64(e, u64);
  3066. }
  3067. static bool upb_put_float(upb_encstate *e, float d) {
  3068. uint32_t u32;
  3069. UPB_ASSERT(sizeof(float) == sizeof(uint32_t));
  3070. memcpy(&u32, &d, sizeof(uint32_t));
  3071. return upb_put_fixed32(e, u32);
  3072. }
  3073. static uint32_t upb_readcase(const char *msg, const upb_msglayout_field *f) {
  3074. uint32_t ret;
  3075. uint32_t offset = ~f->presence;
  3076. memcpy(&ret, msg + offset, sizeof(ret));
  3077. return ret;
  3078. }
  3079. static bool upb_readhasbit(const char *msg, const upb_msglayout_field *f) {
  3080. uint32_t hasbit = f->presence;
  3081. UPB_ASSERT(f->presence > 0);
  3082. return msg[hasbit / 8] & (1 << (hasbit % 8));
  3083. }
  3084. static bool upb_put_tag(upb_encstate *e, int field_number, int wire_type) {
  3085. return upb_put_varint(e, (field_number << 3) | wire_type);
  3086. }
  3087. static bool upb_put_fixedarray(upb_encstate *e, const upb_array *arr,
  3088. size_t size) {
  3089. size_t bytes = arr->len * size;
  3090. return upb_put_bytes(e, arr->data, bytes) && upb_put_varint(e, bytes);
  3091. }
  3092. bool upb_encode_message(upb_encstate *e, const char *msg,
  3093. const upb_msglayout *m, size_t *size);
  3094. static bool upb_encode_array(upb_encstate *e, const char *field_mem,
  3095. const upb_msglayout *m,
  3096. const upb_msglayout_field *f) {
  3097. const upb_array *arr = *(const upb_array**)field_mem;
  3098. if (arr == NULL || arr->len == 0) {
  3099. return true;
  3100. }
  3101. UPB_ASSERT(arr->type == upb_desctype_to_fieldtype2[f->descriptortype]);
  3102. #define VARINT_CASE(ctype, encode) { \
  3103. ctype *start = arr->data; \
  3104. ctype *ptr = start + arr->len; \
  3105. size_t pre_len = e->limit - e->ptr; \
  3106. do { \
  3107. ptr--; \
  3108. CHK(upb_put_varint(e, encode)); \
  3109. } while (ptr != start); \
  3110. CHK(upb_put_varint(e, e->limit - e->ptr - pre_len)); \
  3111. } \
  3112. break; \
  3113. do { ; } while(0)
  3114. switch (f->descriptortype) {
  3115. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  3116. CHK(upb_put_fixedarray(e, arr, sizeof(double)));
  3117. break;
  3118. case UPB_DESCRIPTOR_TYPE_FLOAT:
  3119. CHK(upb_put_fixedarray(e, arr, sizeof(float)));
  3120. break;
  3121. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  3122. case UPB_DESCRIPTOR_TYPE_FIXED64:
  3123. CHK(upb_put_fixedarray(e, arr, sizeof(uint64_t)));
  3124. break;
  3125. case UPB_DESCRIPTOR_TYPE_FIXED32:
  3126. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  3127. CHK(upb_put_fixedarray(e, arr, sizeof(uint32_t)));
  3128. break;
  3129. case UPB_DESCRIPTOR_TYPE_INT64:
  3130. case UPB_DESCRIPTOR_TYPE_UINT64:
  3131. VARINT_CASE(uint64_t, *ptr);
  3132. case UPB_DESCRIPTOR_TYPE_UINT32:
  3133. VARINT_CASE(uint32_t, *ptr);
  3134. case UPB_DESCRIPTOR_TYPE_INT32:
  3135. case UPB_DESCRIPTOR_TYPE_ENUM:
  3136. VARINT_CASE(int32_t, (int64_t)*ptr);
  3137. case UPB_DESCRIPTOR_TYPE_BOOL:
  3138. VARINT_CASE(bool, *ptr);
  3139. case UPB_DESCRIPTOR_TYPE_SINT32:
  3140. VARINT_CASE(int32_t, upb_zzencode_32(*ptr));
  3141. case UPB_DESCRIPTOR_TYPE_SINT64:
  3142. VARINT_CASE(int64_t, upb_zzencode_64(*ptr));
  3143. case UPB_DESCRIPTOR_TYPE_STRING:
  3144. case UPB_DESCRIPTOR_TYPE_BYTES: {
  3145. upb_stringview *start = arr->data;
  3146. upb_stringview *ptr = start + arr->len;
  3147. do {
  3148. ptr--;
  3149. CHK(upb_put_bytes(e, ptr->data, ptr->size) &&
  3150. upb_put_varint(e, ptr->size) &&
  3151. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  3152. } while (ptr != start);
  3153. return true;
  3154. }
  3155. case UPB_DESCRIPTOR_TYPE_GROUP: {
  3156. void **start = arr->data;
  3157. void **ptr = start + arr->len;
  3158. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  3159. do {
  3160. size_t size;
  3161. ptr--;
  3162. CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
  3163. upb_encode_message(e, *ptr, subm, &size) &&
  3164. upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP));
  3165. } while (ptr != start);
  3166. return true;
  3167. }
  3168. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  3169. void **start = arr->data;
  3170. void **ptr = start + arr->len;
  3171. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  3172. do {
  3173. size_t size;
  3174. ptr--;
  3175. CHK(upb_encode_message(e, *ptr, subm, &size) &&
  3176. upb_put_varint(e, size) &&
  3177. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  3178. } while (ptr != start);
  3179. return true;
  3180. }
  3181. }
  3182. #undef VARINT_CASE
  3183. /* We encode all primitive arrays as packed, regardless of what was specified
  3184. * in the .proto file. Could special case 1-sized arrays. */
  3185. CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  3186. return true;
  3187. }
  3188. static bool upb_encode_scalarfield(upb_encstate *e, const char *field_mem,
  3189. const upb_msglayout *m,
  3190. const upb_msglayout_field *f,
  3191. bool skip_zero_value) {
  3192. #define CASE(ctype, type, wire_type, encodeval) do { \
  3193. ctype val = *(ctype*)field_mem; \
  3194. if (skip_zero_value && val == 0) { \
  3195. return true; \
  3196. } \
  3197. return upb_put_ ## type(e, encodeval) && \
  3198. upb_put_tag(e, f->number, wire_type); \
  3199. } while(0)
  3200. switch (f->descriptortype) {
  3201. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  3202. CASE(double, double, UPB_WIRE_TYPE_64BIT, val);
  3203. case UPB_DESCRIPTOR_TYPE_FLOAT:
  3204. CASE(float, float, UPB_WIRE_TYPE_32BIT, val);
  3205. case UPB_DESCRIPTOR_TYPE_INT64:
  3206. case UPB_DESCRIPTOR_TYPE_UINT64:
  3207. CASE(uint64_t, varint, UPB_WIRE_TYPE_VARINT, val);
  3208. case UPB_DESCRIPTOR_TYPE_UINT32:
  3209. CASE(uint32_t, varint, UPB_WIRE_TYPE_VARINT, val);
  3210. case UPB_DESCRIPTOR_TYPE_INT32:
  3211. case UPB_DESCRIPTOR_TYPE_ENUM:
  3212. CASE(int32_t, varint, UPB_WIRE_TYPE_VARINT, (int64_t)val);
  3213. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  3214. case UPB_DESCRIPTOR_TYPE_FIXED64:
  3215. CASE(uint64_t, fixed64, UPB_WIRE_TYPE_64BIT, val);
  3216. case UPB_DESCRIPTOR_TYPE_FIXED32:
  3217. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  3218. CASE(uint32_t, fixed32, UPB_WIRE_TYPE_32BIT, val);
  3219. case UPB_DESCRIPTOR_TYPE_BOOL:
  3220. CASE(bool, varint, UPB_WIRE_TYPE_VARINT, val);
  3221. case UPB_DESCRIPTOR_TYPE_SINT32:
  3222. CASE(int32_t, varint, UPB_WIRE_TYPE_VARINT, upb_zzencode_32(val));
  3223. case UPB_DESCRIPTOR_TYPE_SINT64:
  3224. CASE(int64_t, varint, UPB_WIRE_TYPE_VARINT, upb_zzencode_64(val));
  3225. case UPB_DESCRIPTOR_TYPE_STRING:
  3226. case UPB_DESCRIPTOR_TYPE_BYTES: {
  3227. upb_stringview view = *(upb_stringview*)field_mem;
  3228. if (skip_zero_value && view.size == 0) {
  3229. return true;
  3230. }
  3231. return upb_put_bytes(e, view.data, view.size) &&
  3232. upb_put_varint(e, view.size) &&
  3233. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED);
  3234. }
  3235. case UPB_DESCRIPTOR_TYPE_GROUP: {
  3236. size_t size;
  3237. void *submsg = *(void **)field_mem;
  3238. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  3239. if (submsg == NULL) {
  3240. return true;
  3241. }
  3242. return upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
  3243. upb_encode_message(e, submsg, subm, &size) &&
  3244. upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP);
  3245. }
  3246. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  3247. size_t size;
  3248. void *submsg = *(void **)field_mem;
  3249. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  3250. if (submsg == NULL) {
  3251. return true;
  3252. }
  3253. return upb_encode_message(e, submsg, subm, &size) &&
  3254. upb_put_varint(e, size) &&
  3255. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED);
  3256. }
  3257. }
  3258. #undef CASE
  3259. UPB_UNREACHABLE();
  3260. }
  3261. bool upb_encode_message(upb_encstate *e, const char *msg,
  3262. const upb_msglayout *m, size_t *size) {
  3263. int i;
  3264. size_t pre_len = e->limit - e->ptr;
  3265. const char *unknown;
  3266. size_t unknown_size;
  3267. for (i = m->field_count - 1; i >= 0; i--) {
  3268. const upb_msglayout_field *f = &m->fields[i];
  3269. if (f->label == UPB_LABEL_REPEATED) {
  3270. CHK(upb_encode_array(e, msg + f->offset, m, f));
  3271. } else {
  3272. bool skip_empty = false;
  3273. if (f->presence == 0) {
  3274. /* Proto3 presence. */
  3275. skip_empty = true;
  3276. } else if (f->presence > 0) {
  3277. /* Proto2 presence: hasbit. */
  3278. if (!upb_readhasbit(msg, f)) {
  3279. continue;
  3280. }
  3281. } else {
  3282. /* Field is in a oneof. */
  3283. if (upb_readcase(msg, f) != f->number) {
  3284. continue;
  3285. }
  3286. }
  3287. CHK(upb_encode_scalarfield(e, msg + f->offset, m, f, skip_empty));
  3288. }
  3289. }
  3290. unknown = upb_msg_getunknown(msg, &unknown_size);
  3291. if (unknown) {
  3292. upb_put_bytes(e, unknown, unknown_size);
  3293. }
  3294. *size = (e->limit - e->ptr) - pre_len;
  3295. return true;
  3296. }
  3297. char *upb_encode(const void *msg, const upb_msglayout *m, upb_arena *arena,
  3298. size_t *size) {
  3299. upb_encstate e;
  3300. e.alloc = upb_arena_alloc(arena);
  3301. e.buf = NULL;
  3302. e.limit = NULL;
  3303. e.ptr = NULL;
  3304. if (!upb_encode_message(&e, msg, m, size)) {
  3305. *size = 0;
  3306. return NULL;
  3307. }
  3308. *size = e.limit - e.ptr;
  3309. if (*size == 0) {
  3310. static char ch;
  3311. return &ch;
  3312. } else {
  3313. UPB_ASSERT(e.ptr);
  3314. return e.ptr;
  3315. }
  3316. }
  3317. #undef CHK
  3318. /*
  3319. ** TODO(haberman): it's unclear whether a lot of the consistency checks should
  3320. ** UPB_ASSERT() or return false.
  3321. */
  3322. #include <string.h>
  3323. static void *upb_calloc(size_t size) {
  3324. void *mem = upb_gmalloc(size);
  3325. if (mem) {
  3326. memset(mem, 0, size);
  3327. }
  3328. return mem;
  3329. }
  3330. /* Defined for the sole purpose of having a unique pointer value for
  3331. * UPB_NO_CLOSURE. */
  3332. char _upb_noclosure;
  3333. static void freehandlers(upb_refcounted *r) {
  3334. upb_handlers *h = (upb_handlers*)r;
  3335. upb_inttable_iter i;
  3336. upb_inttable_begin(&i, &h->cleanup_);
  3337. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  3338. void *val = (void*)upb_inttable_iter_key(&i);
  3339. upb_value func_val = upb_inttable_iter_value(&i);
  3340. upb_handlerfree *func = upb_value_getfptr(func_val);
  3341. func(val);
  3342. }
  3343. upb_inttable_uninit(&h->cleanup_);
  3344. upb_msgdef_unref(h->msg, h);
  3345. upb_gfree(h->sub);
  3346. upb_gfree(h);
  3347. }
  3348. static void visithandlers(const upb_refcounted *r, upb_refcounted_visit *visit,
  3349. void *closure) {
  3350. const upb_handlers *h = (const upb_handlers*)r;
  3351. upb_msg_field_iter i;
  3352. for(upb_msg_field_begin(&i, h->msg);
  3353. !upb_msg_field_done(&i);
  3354. upb_msg_field_next(&i)) {
  3355. upb_fielddef *f = upb_msg_iter_field(&i);
  3356. const upb_handlers *sub;
  3357. if (!upb_fielddef_issubmsg(f)) continue;
  3358. sub = upb_handlers_getsubhandlers(h, f);
  3359. if (sub) visit(r, upb_handlers_upcast(sub), closure);
  3360. }
  3361. }
  3362. static const struct upb_refcounted_vtbl vtbl = {visithandlers, freehandlers};
  3363. typedef struct {
  3364. upb_inttable tab; /* maps upb_msgdef* -> upb_handlers*. */
  3365. upb_handlers_callback *callback;
  3366. const void *closure;
  3367. } dfs_state;
  3368. /* TODO(haberman): discard upb_handlers* objects that do not actually have any
  3369. * handlers set and cannot reach any upb_handlers* object that does. This is
  3370. * slightly tricky to do correctly. */
  3371. static upb_handlers *newformsg(const upb_msgdef *m, const void *owner,
  3372. dfs_state *s) {
  3373. upb_msg_field_iter i;
  3374. upb_handlers *h = upb_handlers_new(m, owner);
  3375. if (!h) return NULL;
  3376. if (!upb_inttable_insertptr(&s->tab, m, upb_value_ptr(h))) goto oom;
  3377. s->callback(s->closure, h);
  3378. /* For each submessage field, get or create a handlers object and set it as
  3379. * the subhandlers. */
  3380. for(upb_msg_field_begin(&i, m);
  3381. !upb_msg_field_done(&i);
  3382. upb_msg_field_next(&i)) {
  3383. upb_fielddef *f = upb_msg_iter_field(&i);
  3384. const upb_msgdef *subdef;
  3385. upb_value subm_ent;
  3386. if (!upb_fielddef_issubmsg(f)) continue;
  3387. subdef = upb_downcast_msgdef(upb_fielddef_subdef(f));
  3388. if (upb_inttable_lookupptr(&s->tab, subdef, &subm_ent)) {
  3389. upb_handlers_setsubhandlers(h, f, upb_value_getptr(subm_ent));
  3390. } else {
  3391. upb_handlers *sub_mh = newformsg(subdef, &sub_mh, s);
  3392. if (!sub_mh) goto oom;
  3393. upb_handlers_setsubhandlers(h, f, sub_mh);
  3394. upb_handlers_unref(sub_mh, &sub_mh);
  3395. }
  3396. }
  3397. return h;
  3398. oom:
  3399. upb_handlers_unref(h, owner);
  3400. return NULL;
  3401. }
  3402. /* Given a selector for a STARTSUBMSG handler, resolves to a pointer to the
  3403. * subhandlers for this submessage field. */
  3404. #define SUBH(h, selector) (h->sub[selector])
  3405. /* The selector for a submessage field is the field index. */
  3406. #define SUBH_F(h, f) SUBH(h, f->index_)
  3407. static int32_t trygetsel(upb_handlers *h, const upb_fielddef *f,
  3408. upb_handlertype_t type) {
  3409. upb_selector_t sel;
  3410. UPB_ASSERT(!upb_handlers_isfrozen(h));
  3411. if (upb_handlers_msgdef(h) != upb_fielddef_containingtype(f)) {
  3412. upb_status_seterrf(
  3413. &h->status_, "type mismatch: field %s does not belong to message %s",
  3414. upb_fielddef_name(f), upb_msgdef_fullname(upb_handlers_msgdef(h)));
  3415. return -1;
  3416. }
  3417. if (!upb_handlers_getselector(f, type, &sel)) {
  3418. upb_status_seterrf(
  3419. &h->status_,
  3420. "type mismatch: cannot register handler type %d for field %s",
  3421. type, upb_fielddef_name(f));
  3422. return -1;
  3423. }
  3424. return sel;
  3425. }
  3426. static upb_selector_t handlers_getsel(upb_handlers *h, const upb_fielddef *f,
  3427. upb_handlertype_t type) {
  3428. int32_t sel = trygetsel(h, f, type);
  3429. UPB_ASSERT(sel >= 0);
  3430. return sel;
  3431. }
  3432. static const void **returntype(upb_handlers *h, const upb_fielddef *f,
  3433. upb_handlertype_t type) {
  3434. return &h->table[handlers_getsel(h, f, type)].attr.return_closure_type_;
  3435. }
  3436. static bool doset(upb_handlers *h, int32_t sel, const upb_fielddef *f,
  3437. upb_handlertype_t type, upb_func *func,
  3438. upb_handlerattr *attr) {
  3439. upb_handlerattr set_attr = UPB_HANDLERATTR_INITIALIZER;
  3440. const void *closure_type;
  3441. const void **context_closure_type;
  3442. UPB_ASSERT(!upb_handlers_isfrozen(h));
  3443. if (sel < 0) {
  3444. upb_status_seterrmsg(&h->status_,
  3445. "incorrect handler type for this field.");
  3446. return false;
  3447. }
  3448. if (h->table[sel].func) {
  3449. upb_status_seterrmsg(&h->status_,
  3450. "cannot change handler once it has been set.");
  3451. return false;
  3452. }
  3453. if (attr) {
  3454. set_attr = *attr;
  3455. }
  3456. /* Check that the given closure type matches the closure type that has been
  3457. * established for this context (if any). */
  3458. closure_type = upb_handlerattr_closuretype(&set_attr);
  3459. if (type == UPB_HANDLER_STRING) {
  3460. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSTR);
  3461. } else if (f && upb_fielddef_isseq(f) &&
  3462. type != UPB_HANDLER_STARTSEQ &&
  3463. type != UPB_HANDLER_ENDSEQ) {
  3464. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSEQ);
  3465. } else {
  3466. context_closure_type = &h->top_closure_type;
  3467. }
  3468. if (closure_type && *context_closure_type &&
  3469. closure_type != *context_closure_type) {
  3470. /* TODO(haberman): better message for debugging. */
  3471. if (f) {
  3472. upb_status_seterrf(&h->status_,
  3473. "closure type does not match for field %s",
  3474. upb_fielddef_name(f));
  3475. } else {
  3476. upb_status_seterrmsg(
  3477. &h->status_, "closure type does not match for message-level handler");
  3478. }
  3479. return false;
  3480. }
  3481. if (closure_type)
  3482. *context_closure_type = closure_type;
  3483. /* If this is a STARTSEQ or STARTSTR handler, check that the returned pointer
  3484. * matches any pre-existing expectations about what type is expected. */
  3485. if (type == UPB_HANDLER_STARTSEQ || type == UPB_HANDLER_STARTSTR) {
  3486. const void *return_type = upb_handlerattr_returnclosuretype(&set_attr);
  3487. const void *table_return_type =
  3488. upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  3489. if (return_type && table_return_type && return_type != table_return_type) {
  3490. upb_status_seterrmsg(&h->status_, "closure return type does not match");
  3491. return false;
  3492. }
  3493. if (table_return_type && !return_type)
  3494. upb_handlerattr_setreturnclosuretype(&set_attr, table_return_type);
  3495. }
  3496. h->table[sel].func = (upb_func*)func;
  3497. h->table[sel].attr = set_attr;
  3498. return true;
  3499. }
  3500. /* Returns the effective closure type for this handler (which will propagate
  3501. * from outer frames if this frame has no START* handler). Not implemented for
  3502. * UPB_HANDLER_STRING at the moment since this is not needed. Returns NULL is
  3503. * the effective closure type is unspecified (either no handler was registered
  3504. * to specify it or the handler that was registered did not specify the closure
  3505. * type). */
  3506. const void *effective_closure_type(upb_handlers *h, const upb_fielddef *f,
  3507. upb_handlertype_t type) {
  3508. const void *ret;
  3509. upb_selector_t sel;
  3510. UPB_ASSERT(type != UPB_HANDLER_STRING);
  3511. ret = h->top_closure_type;
  3512. if (upb_fielddef_isseq(f) &&
  3513. type != UPB_HANDLER_STARTSEQ &&
  3514. type != UPB_HANDLER_ENDSEQ &&
  3515. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)].func) {
  3516. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  3517. }
  3518. if (type == UPB_HANDLER_STRING &&
  3519. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSTR)].func) {
  3520. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  3521. }
  3522. /* The effective type of the submessage; not used yet.
  3523. * if (type == SUBMESSAGE &&
  3524. * h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)].func) {
  3525. * ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  3526. * } */
  3527. return ret;
  3528. }
  3529. /* Checks whether the START* handler specified by f & type is missing even
  3530. * though it is required to convert the established type of an outer frame
  3531. * ("closure_type") into the established type of an inner frame (represented in
  3532. * the return closure type of this handler's attr. */
  3533. bool checkstart(upb_handlers *h, const upb_fielddef *f, upb_handlertype_t type,
  3534. upb_status *status) {
  3535. const void *closure_type;
  3536. const upb_handlerattr *attr;
  3537. const void *return_closure_type;
  3538. upb_selector_t sel = handlers_getsel(h, f, type);
  3539. if (h->table[sel].func) return true;
  3540. closure_type = effective_closure_type(h, f, type);
  3541. attr = &h->table[sel].attr;
  3542. return_closure_type = upb_handlerattr_returnclosuretype(attr);
  3543. if (closure_type && return_closure_type &&
  3544. closure_type != return_closure_type) {
  3545. upb_status_seterrf(status,
  3546. "expected start handler to return sub type for field %f",
  3547. upb_fielddef_name(f));
  3548. return false;
  3549. }
  3550. return true;
  3551. }
  3552. /* Public interface ***********************************************************/
  3553. upb_handlers *upb_handlers_new(const upb_msgdef *md, const void *owner) {
  3554. int extra;
  3555. upb_handlers *h;
  3556. UPB_ASSERT(upb_msgdef_isfrozen(md));
  3557. extra = sizeof(upb_handlers_tabent) * (md->selector_count - 1);
  3558. h = upb_calloc(sizeof(*h) + extra);
  3559. if (!h) return NULL;
  3560. h->msg = md;
  3561. upb_msgdef_ref(h->msg, h);
  3562. upb_status_clear(&h->status_);
  3563. if (md->submsg_field_count > 0) {
  3564. h->sub = upb_calloc(md->submsg_field_count * sizeof(*h->sub));
  3565. if (!h->sub) goto oom;
  3566. } else {
  3567. h->sub = 0;
  3568. }
  3569. if (!upb_refcounted_init(upb_handlers_upcast_mutable(h), &vtbl, owner))
  3570. goto oom;
  3571. if (!upb_inttable_init(&h->cleanup_, UPB_CTYPE_FPTR)) goto oom;
  3572. /* calloc() above initialized all handlers to NULL. */
  3573. return h;
  3574. oom:
  3575. freehandlers(upb_handlers_upcast_mutable(h));
  3576. return NULL;
  3577. }
  3578. const upb_handlers *upb_handlers_newfrozen(const upb_msgdef *m,
  3579. const void *owner,
  3580. upb_handlers_callback *callback,
  3581. const void *closure) {
  3582. dfs_state state;
  3583. upb_handlers *ret;
  3584. bool ok;
  3585. upb_refcounted *r;
  3586. state.callback = callback;
  3587. state.closure = closure;
  3588. if (!upb_inttable_init(&state.tab, UPB_CTYPE_PTR)) return NULL;
  3589. ret = newformsg(m, owner, &state);
  3590. upb_inttable_uninit(&state.tab);
  3591. if (!ret) return NULL;
  3592. r = upb_handlers_upcast_mutable(ret);
  3593. ok = upb_refcounted_freeze(&r, 1, NULL, UPB_MAX_HANDLER_DEPTH);
  3594. UPB_ASSERT(ok);
  3595. return ret;
  3596. }
  3597. const upb_status *upb_handlers_status(upb_handlers *h) {
  3598. UPB_ASSERT(!upb_handlers_isfrozen(h));
  3599. return &h->status_;
  3600. }
  3601. void upb_handlers_clearerr(upb_handlers *h) {
  3602. UPB_ASSERT(!upb_handlers_isfrozen(h));
  3603. upb_status_clear(&h->status_);
  3604. }
  3605. #define SETTER(name, handlerctype, handlertype) \
  3606. bool upb_handlers_set ## name(upb_handlers *h, const upb_fielddef *f, \
  3607. handlerctype func, upb_handlerattr *attr) { \
  3608. int32_t sel = trygetsel(h, f, handlertype); \
  3609. return doset(h, sel, f, handlertype, (upb_func*)func, attr); \
  3610. }
  3611. SETTER(int32, upb_int32_handlerfunc*, UPB_HANDLER_INT32)
  3612. SETTER(int64, upb_int64_handlerfunc*, UPB_HANDLER_INT64)
  3613. SETTER(uint32, upb_uint32_handlerfunc*, UPB_HANDLER_UINT32)
  3614. SETTER(uint64, upb_uint64_handlerfunc*, UPB_HANDLER_UINT64)
  3615. SETTER(float, upb_float_handlerfunc*, UPB_HANDLER_FLOAT)
  3616. SETTER(double, upb_double_handlerfunc*, UPB_HANDLER_DOUBLE)
  3617. SETTER(bool, upb_bool_handlerfunc*, UPB_HANDLER_BOOL)
  3618. SETTER(startstr, upb_startstr_handlerfunc*, UPB_HANDLER_STARTSTR)
  3619. SETTER(string, upb_string_handlerfunc*, UPB_HANDLER_STRING)
  3620. SETTER(endstr, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSTR)
  3621. SETTER(startseq, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSEQ)
  3622. SETTER(startsubmsg, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSUBMSG)
  3623. SETTER(endsubmsg, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSUBMSG)
  3624. SETTER(endseq, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSEQ)
  3625. #undef SETTER
  3626. bool upb_handlers_setunknown(upb_handlers *h, upb_unknown_handlerfunc *func,
  3627. upb_handlerattr *attr) {
  3628. return doset(h, UPB_UNKNOWN_SELECTOR, NULL, UPB_HANDLER_INT32,
  3629. (upb_func *)func, attr);
  3630. }
  3631. bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
  3632. upb_handlerattr *attr) {
  3633. return doset(h, UPB_STARTMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  3634. (upb_func *)func, attr);
  3635. }
  3636. bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func,
  3637. upb_handlerattr *attr) {
  3638. UPB_ASSERT(!upb_handlers_isfrozen(h));
  3639. return doset(h, UPB_ENDMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  3640. (upb_func *)func, attr);
  3641. }
  3642. bool upb_handlers_setsubhandlers(upb_handlers *h, const upb_fielddef *f,
  3643. const upb_handlers *sub) {
  3644. UPB_ASSERT(sub);
  3645. UPB_ASSERT(!upb_handlers_isfrozen(h));
  3646. UPB_ASSERT(upb_fielddef_issubmsg(f));
  3647. if (SUBH_F(h, f)) return false; /* Can't reset. */
  3648. if (upb_msgdef_upcast(upb_handlers_msgdef(sub)) != upb_fielddef_subdef(f)) {
  3649. return false;
  3650. }
  3651. SUBH_F(h, f) = sub;
  3652. upb_ref2(sub, h);
  3653. return true;
  3654. }
  3655. const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h,
  3656. const upb_fielddef *f) {
  3657. UPB_ASSERT(upb_fielddef_issubmsg(f));
  3658. return SUBH_F(h, f);
  3659. }
  3660. bool upb_handlers_getattr(const upb_handlers *h, upb_selector_t sel,
  3661. upb_handlerattr *attr) {
  3662. if (!upb_handlers_gethandler(h, sel))
  3663. return false;
  3664. *attr = h->table[sel].attr;
  3665. return true;
  3666. }
  3667. const upb_handlers *upb_handlers_getsubhandlers_sel(const upb_handlers *h,
  3668. upb_selector_t sel) {
  3669. /* STARTSUBMSG selector in sel is the field's selector base. */
  3670. return SUBH(h, sel - UPB_STATIC_SELECTOR_COUNT);
  3671. }
  3672. const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h) { return h->msg; }
  3673. bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *func) {
  3674. bool ok;
  3675. if (upb_inttable_lookupptr(&h->cleanup_, p, NULL)) {
  3676. return false;
  3677. }
  3678. ok = upb_inttable_insertptr(&h->cleanup_, p, upb_value_fptr(func));
  3679. UPB_ASSERT(ok);
  3680. return true;
  3681. }
  3682. /* "Static" methods ***********************************************************/
  3683. bool upb_handlers_freeze(upb_handlers *const*handlers, int n, upb_status *s) {
  3684. /* TODO: verify we have a transitive closure. */
  3685. int i;
  3686. for (i = 0; i < n; i++) {
  3687. upb_msg_field_iter j;
  3688. upb_handlers *h = handlers[i];
  3689. if (!upb_ok(&h->status_)) {
  3690. upb_status_seterrf(s, "handlers for message %s had error status: %s",
  3691. upb_msgdef_fullname(upb_handlers_msgdef(h)),
  3692. upb_status_errmsg(&h->status_));
  3693. return false;
  3694. }
  3695. /* Check that there are no closure mismatches due to missing Start* handlers
  3696. * or subhandlers with different type-level types. */
  3697. for(upb_msg_field_begin(&j, h->msg);
  3698. !upb_msg_field_done(&j);
  3699. upb_msg_field_next(&j)) {
  3700. const upb_fielddef *f = upb_msg_iter_field(&j);
  3701. if (upb_fielddef_isseq(f)) {
  3702. if (!checkstart(h, f, UPB_HANDLER_STARTSEQ, s))
  3703. return false;
  3704. }
  3705. if (upb_fielddef_isstring(f)) {
  3706. if (!checkstart(h, f, UPB_HANDLER_STARTSTR, s))
  3707. return false;
  3708. }
  3709. if (upb_fielddef_issubmsg(f)) {
  3710. bool hashandler = false;
  3711. if (upb_handlers_gethandler(
  3712. h, handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)) ||
  3713. upb_handlers_gethandler(
  3714. h, handlers_getsel(h, f, UPB_HANDLER_ENDSUBMSG))) {
  3715. hashandler = true;
  3716. }
  3717. if (upb_fielddef_isseq(f) &&
  3718. (upb_handlers_gethandler(
  3719. h, handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)) ||
  3720. upb_handlers_gethandler(
  3721. h, handlers_getsel(h, f, UPB_HANDLER_ENDSEQ)))) {
  3722. hashandler = true;
  3723. }
  3724. if (hashandler && !upb_handlers_getsubhandlers(h, f)) {
  3725. /* For now we add an empty subhandlers in this case. It makes the
  3726. * decoder code generator simpler, because it only has to handle two
  3727. * cases (submessage has handlers or not) as opposed to three
  3728. * (submessage has handlers in enclosing message but no subhandlers).
  3729. *
  3730. * This makes parsing less efficient in the case that we want to
  3731. * notice a submessage but skip its contents (like if we're testing
  3732. * for submessage presence or counting the number of repeated
  3733. * submessages). In this case we will end up parsing the submessage
  3734. * field by field and throwing away the results for each, instead of
  3735. * skipping the whole delimited thing at once. If this is an issue we
  3736. * can revisit it, but do remember that this only arises when you have
  3737. * handlers (startseq/startsubmsg/endsubmsg/endseq) set for the
  3738. * submessage but no subhandlers. The uses cases for this are
  3739. * limited. */
  3740. upb_handlers *sub = upb_handlers_new(upb_fielddef_msgsubdef(f), &sub);
  3741. upb_handlers_setsubhandlers(h, f, sub);
  3742. upb_handlers_unref(sub, &sub);
  3743. }
  3744. /* TODO(haberman): check type of submessage.
  3745. * This is slightly tricky; also consider whether we should check that
  3746. * they match at setsubhandlers time. */
  3747. }
  3748. }
  3749. }
  3750. if (!upb_refcounted_freeze((upb_refcounted*const*)handlers, n, s,
  3751. UPB_MAX_HANDLER_DEPTH)) {
  3752. return false;
  3753. }
  3754. return true;
  3755. }
  3756. upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f) {
  3757. switch (upb_fielddef_type(f)) {
  3758. case UPB_TYPE_INT32:
  3759. case UPB_TYPE_ENUM: return UPB_HANDLER_INT32;
  3760. case UPB_TYPE_INT64: return UPB_HANDLER_INT64;
  3761. case UPB_TYPE_UINT32: return UPB_HANDLER_UINT32;
  3762. case UPB_TYPE_UINT64: return UPB_HANDLER_UINT64;
  3763. case UPB_TYPE_FLOAT: return UPB_HANDLER_FLOAT;
  3764. case UPB_TYPE_DOUBLE: return UPB_HANDLER_DOUBLE;
  3765. case UPB_TYPE_BOOL: return UPB_HANDLER_BOOL;
  3766. default: UPB_ASSERT(false); return -1; /* Invalid input. */
  3767. }
  3768. }
  3769. bool upb_handlers_getselector(const upb_fielddef *f, upb_handlertype_t type,
  3770. upb_selector_t *s) {
  3771. switch (type) {
  3772. case UPB_HANDLER_INT32:
  3773. case UPB_HANDLER_INT64:
  3774. case UPB_HANDLER_UINT32:
  3775. case UPB_HANDLER_UINT64:
  3776. case UPB_HANDLER_FLOAT:
  3777. case UPB_HANDLER_DOUBLE:
  3778. case UPB_HANDLER_BOOL:
  3779. if (!upb_fielddef_isprimitive(f) ||
  3780. upb_handlers_getprimitivehandlertype(f) != type)
  3781. return false;
  3782. *s = f->selector_base;
  3783. break;
  3784. case UPB_HANDLER_STRING:
  3785. if (upb_fielddef_isstring(f)) {
  3786. *s = f->selector_base;
  3787. } else if (upb_fielddef_lazy(f)) {
  3788. *s = f->selector_base + 3;
  3789. } else {
  3790. return false;
  3791. }
  3792. break;
  3793. case UPB_HANDLER_STARTSTR:
  3794. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  3795. *s = f->selector_base + 1;
  3796. } else {
  3797. return false;
  3798. }
  3799. break;
  3800. case UPB_HANDLER_ENDSTR:
  3801. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  3802. *s = f->selector_base + 2;
  3803. } else {
  3804. return false;
  3805. }
  3806. break;
  3807. case UPB_HANDLER_STARTSEQ:
  3808. if (!upb_fielddef_isseq(f)) return false;
  3809. *s = f->selector_base - 2;
  3810. break;
  3811. case UPB_HANDLER_ENDSEQ:
  3812. if (!upb_fielddef_isseq(f)) return false;
  3813. *s = f->selector_base - 1;
  3814. break;
  3815. case UPB_HANDLER_STARTSUBMSG:
  3816. if (!upb_fielddef_issubmsg(f)) return false;
  3817. /* Selectors for STARTSUBMSG are at the beginning of the table so that the
  3818. * selector can also be used as an index into the "sub" array of
  3819. * subhandlers. The indexes for the two into these two tables are the
  3820. * same, except that in the handler table the static selectors come first. */
  3821. *s = f->index_ + UPB_STATIC_SELECTOR_COUNT;
  3822. break;
  3823. case UPB_HANDLER_ENDSUBMSG:
  3824. if (!upb_fielddef_issubmsg(f)) return false;
  3825. *s = f->selector_base;
  3826. break;
  3827. }
  3828. UPB_ASSERT((size_t)*s < upb_fielddef_containingtype(f)->selector_count);
  3829. return true;
  3830. }
  3831. uint32_t upb_handlers_selectorbaseoffset(const upb_fielddef *f) {
  3832. return upb_fielddef_isseq(f) ? 2 : 0;
  3833. }
  3834. uint32_t upb_handlers_selectorcount(const upb_fielddef *f) {
  3835. uint32_t ret = 1;
  3836. if (upb_fielddef_isseq(f)) ret += 2; /* STARTSEQ/ENDSEQ */
  3837. if (upb_fielddef_isstring(f)) ret += 2; /* [STRING]/STARTSTR/ENDSTR */
  3838. if (upb_fielddef_issubmsg(f)) {
  3839. /* ENDSUBMSG (STARTSUBMSG is at table beginning) */
  3840. ret += 0;
  3841. if (upb_fielddef_lazy(f)) {
  3842. /* STARTSTR/ENDSTR/STRING (for lazy) */
  3843. ret += 3;
  3844. }
  3845. }
  3846. return ret;
  3847. }
  3848. /* upb_handlerattr ************************************************************/
  3849. void upb_handlerattr_init(upb_handlerattr *attr) {
  3850. upb_handlerattr from = UPB_HANDLERATTR_INITIALIZER;
  3851. memcpy(attr, &from, sizeof(*attr));
  3852. }
  3853. void upb_handlerattr_uninit(upb_handlerattr *attr) {
  3854. UPB_UNUSED(attr);
  3855. }
  3856. bool upb_handlerattr_sethandlerdata(upb_handlerattr *attr, const void *hd) {
  3857. attr->handler_data_ = hd;
  3858. return true;
  3859. }
  3860. bool upb_handlerattr_setclosuretype(upb_handlerattr *attr, const void *type) {
  3861. attr->closure_type_ = type;
  3862. return true;
  3863. }
  3864. const void *upb_handlerattr_closuretype(const upb_handlerattr *attr) {
  3865. return attr->closure_type_;
  3866. }
  3867. bool upb_handlerattr_setreturnclosuretype(upb_handlerattr *attr,
  3868. const void *type) {
  3869. attr->return_closure_type_ = type;
  3870. return true;
  3871. }
  3872. const void *upb_handlerattr_returnclosuretype(const upb_handlerattr *attr) {
  3873. return attr->return_closure_type_;
  3874. }
  3875. bool upb_handlerattr_setalwaysok(upb_handlerattr *attr, bool alwaysok) {
  3876. attr->alwaysok_ = alwaysok;
  3877. return true;
  3878. }
  3879. bool upb_handlerattr_alwaysok(const upb_handlerattr *attr) {
  3880. return attr->alwaysok_;
  3881. }
  3882. /* upb_bufhandle **************************************************************/
  3883. size_t upb_bufhandle_objofs(const upb_bufhandle *h) {
  3884. return h->objofs_;
  3885. }
  3886. /* upb_byteshandler ***********************************************************/
  3887. void upb_byteshandler_init(upb_byteshandler* h) {
  3888. memset(h, 0, sizeof(*h));
  3889. }
  3890. /* For when we support handlerfree callbacks. */
  3891. void upb_byteshandler_uninit(upb_byteshandler* h) {
  3892. UPB_UNUSED(h);
  3893. }
  3894. bool upb_byteshandler_setstartstr(upb_byteshandler *h,
  3895. upb_startstr_handlerfunc *func, void *d) {
  3896. h->table[UPB_STARTSTR_SELECTOR].func = (upb_func*)func;
  3897. h->table[UPB_STARTSTR_SELECTOR].attr.handler_data_ = d;
  3898. return true;
  3899. }
  3900. bool upb_byteshandler_setstring(upb_byteshandler *h,
  3901. upb_string_handlerfunc *func, void *d) {
  3902. h->table[UPB_STRING_SELECTOR].func = (upb_func*)func;
  3903. h->table[UPB_STRING_SELECTOR].attr.handler_data_ = d;
  3904. return true;
  3905. }
  3906. bool upb_byteshandler_setendstr(upb_byteshandler *h,
  3907. upb_endfield_handlerfunc *func, void *d) {
  3908. h->table[UPB_ENDSTR_SELECTOR].func = (upb_func*)func;
  3909. h->table[UPB_ENDSTR_SELECTOR].attr.handler_data_ = d;
  3910. return true;
  3911. }
  3912. /** Handlers for upb_msg ******************************************************/
  3913. typedef struct {
  3914. size_t offset;
  3915. int32_t hasbit;
  3916. } upb_msg_handlerdata;
  3917. /* Fallback implementation if the handler is not specialized by the producer. */
  3918. #define MSG_WRITER(type, ctype) \
  3919. bool upb_msg_set ## type (void *c, const void *hd, ctype val) { \
  3920. uint8_t *m = c; \
  3921. const upb_msg_handlerdata *d = hd; \
  3922. if (d->hasbit > 0) \
  3923. *(uint8_t*)&m[d->hasbit / 8] |= 1 << (d->hasbit % 8); \
  3924. *(ctype*)&m[d->offset] = val; \
  3925. return true; \
  3926. } \
  3927. MSG_WRITER(double, double)
  3928. MSG_WRITER(float, float)
  3929. MSG_WRITER(int32, int32_t)
  3930. MSG_WRITER(int64, int64_t)
  3931. MSG_WRITER(uint32, uint32_t)
  3932. MSG_WRITER(uint64, uint64_t)
  3933. MSG_WRITER(bool, bool)
  3934. bool upb_msg_setscalarhandler(upb_handlers *h, const upb_fielddef *f,
  3935. size_t offset, int32_t hasbit) {
  3936. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  3937. bool ok;
  3938. upb_msg_handlerdata *d = upb_gmalloc(sizeof(*d));
  3939. if (!d) return false;
  3940. d->offset = offset;
  3941. d->hasbit = hasbit;
  3942. upb_handlerattr_sethandlerdata(&attr, d);
  3943. upb_handlerattr_setalwaysok(&attr, true);
  3944. upb_handlers_addcleanup(h, d, upb_gfree);
  3945. #define TYPE(u, l) \
  3946. case UPB_TYPE_##u: \
  3947. ok = upb_handlers_set##l(h, f, upb_msg_set##l, &attr); break;
  3948. ok = false;
  3949. switch (upb_fielddef_type(f)) {
  3950. TYPE(INT64, int64);
  3951. TYPE(INT32, int32);
  3952. TYPE(ENUM, int32);
  3953. TYPE(UINT64, uint64);
  3954. TYPE(UINT32, uint32);
  3955. TYPE(DOUBLE, double);
  3956. TYPE(FLOAT, float);
  3957. TYPE(BOOL, bool);
  3958. default: UPB_ASSERT(false); break;
  3959. }
  3960. #undef TYPE
  3961. upb_handlerattr_uninit(&attr);
  3962. return ok;
  3963. }
  3964. bool upb_msg_getscalarhandlerdata(const upb_handlers *h,
  3965. upb_selector_t s,
  3966. upb_fieldtype_t *type,
  3967. size_t *offset,
  3968. int32_t *hasbit) {
  3969. const upb_msg_handlerdata *d;
  3970. upb_func *f = upb_handlers_gethandler(h, s);
  3971. if ((upb_int64_handlerfunc*)f == upb_msg_setint64) {
  3972. *type = UPB_TYPE_INT64;
  3973. } else if ((upb_int32_handlerfunc*)f == upb_msg_setint32) {
  3974. *type = UPB_TYPE_INT32;
  3975. } else if ((upb_uint64_handlerfunc*)f == upb_msg_setuint64) {
  3976. *type = UPB_TYPE_UINT64;
  3977. } else if ((upb_uint32_handlerfunc*)f == upb_msg_setuint32) {
  3978. *type = UPB_TYPE_UINT32;
  3979. } else if ((upb_double_handlerfunc*)f == upb_msg_setdouble) {
  3980. *type = UPB_TYPE_DOUBLE;
  3981. } else if ((upb_float_handlerfunc*)f == upb_msg_setfloat) {
  3982. *type = UPB_TYPE_FLOAT;
  3983. } else if ((upb_bool_handlerfunc*)f == upb_msg_setbool) {
  3984. *type = UPB_TYPE_BOOL;
  3985. } else {
  3986. return false;
  3987. }
  3988. d = upb_handlers_gethandlerdata(h, s);
  3989. *offset = d->offset;
  3990. *hasbit = d->hasbit;
  3991. return true;
  3992. }
  3993. bool upb_fieldtype_mapkeyok(upb_fieldtype_t type) {
  3994. return type == UPB_TYPE_BOOL || type == UPB_TYPE_INT32 ||
  3995. type == UPB_TYPE_UINT32 || type == UPB_TYPE_INT64 ||
  3996. type == UPB_TYPE_UINT64 || type == UPB_TYPE_STRING;
  3997. }
  3998. #define PTR_AT(msg, ofs, type) (type*)((char*)msg + ofs)
  3999. #define VOIDPTR_AT(msg, ofs) PTR_AT(msg, ofs, void)
  4000. #define ENCODE_MAX_NESTING 64
  4001. #define CHECK_TRUE(x) if (!(x)) { return false; }
  4002. /** upb_msgval ****************************************************************/
  4003. #define upb_alignof(t) offsetof(struct { char c; t x; }, x)
  4004. /* These functions will generate real memcpy() calls on ARM sadly, because
  4005. * the compiler assumes they might not be aligned. */
  4006. static upb_msgval upb_msgval_read(const void *p, size_t ofs,
  4007. uint8_t size) {
  4008. upb_msgval val;
  4009. p = (char*)p + ofs;
  4010. memcpy(&val, p, size);
  4011. return val;
  4012. }
  4013. static void upb_msgval_write(void *p, size_t ofs, upb_msgval val,
  4014. uint8_t size) {
  4015. p = (char*)p + ofs;
  4016. memcpy(p, &val, size);
  4017. }
  4018. static size_t upb_msgval_sizeof(upb_fieldtype_t type) {
  4019. switch (type) {
  4020. case UPB_TYPE_DOUBLE:
  4021. case UPB_TYPE_INT64:
  4022. case UPB_TYPE_UINT64:
  4023. return 8;
  4024. case UPB_TYPE_ENUM:
  4025. case UPB_TYPE_INT32:
  4026. case UPB_TYPE_UINT32:
  4027. case UPB_TYPE_FLOAT:
  4028. return 4;
  4029. case UPB_TYPE_BOOL:
  4030. return 1;
  4031. case UPB_TYPE_MESSAGE:
  4032. return sizeof(void*);
  4033. case UPB_TYPE_BYTES:
  4034. case UPB_TYPE_STRING:
  4035. return sizeof(upb_stringview);
  4036. }
  4037. UPB_UNREACHABLE();
  4038. }
  4039. static uint8_t upb_msg_fieldsize(const upb_msglayout_field *field) {
  4040. if (field->label == UPB_LABEL_REPEATED) {
  4041. return sizeof(void*);
  4042. } else {
  4043. return upb_msgval_sizeof(upb_desctype_to_fieldtype[field->descriptortype]);
  4044. }
  4045. }
  4046. /* TODO(haberman): this is broken right now because upb_msgval can contain
  4047. * a char* / size_t pair, which is too big for a upb_value. To fix this
  4048. * we'll probably need to dynamically allocate a upb_msgval and store a
  4049. * pointer to that in the tables for extensions/maps. */
  4050. static upb_value upb_toval(upb_msgval val) {
  4051. upb_value ret;
  4052. UPB_UNUSED(val);
  4053. memset(&ret, 0, sizeof(upb_value)); /* XXX */
  4054. return ret;
  4055. }
  4056. static upb_msgval upb_msgval_fromval(upb_value val) {
  4057. upb_msgval ret;
  4058. UPB_UNUSED(val);
  4059. memset(&ret, 0, sizeof(upb_msgval)); /* XXX */
  4060. return ret;
  4061. }
  4062. static upb_ctype_t upb_fieldtotabtype(upb_fieldtype_t type) {
  4063. switch (type) {
  4064. case UPB_TYPE_FLOAT: return UPB_CTYPE_FLOAT;
  4065. case UPB_TYPE_DOUBLE: return UPB_CTYPE_DOUBLE;
  4066. case UPB_TYPE_BOOL: return UPB_CTYPE_BOOL;
  4067. case UPB_TYPE_BYTES:
  4068. case UPB_TYPE_MESSAGE:
  4069. case UPB_TYPE_STRING: return UPB_CTYPE_CONSTPTR;
  4070. case UPB_TYPE_ENUM:
  4071. case UPB_TYPE_INT32: return UPB_CTYPE_INT32;
  4072. case UPB_TYPE_UINT32: return UPB_CTYPE_UINT32;
  4073. case UPB_TYPE_INT64: return UPB_CTYPE_INT64;
  4074. case UPB_TYPE_UINT64: return UPB_CTYPE_UINT64;
  4075. default: UPB_ASSERT(false); return 0;
  4076. }
  4077. }
  4078. /** upb_msg *******************************************************************/
  4079. /* If we always read/write as a consistent type to each address, this shouldn't
  4080. * violate aliasing.
  4081. */
  4082. #define DEREF(msg, ofs, type) *PTR_AT(msg, ofs, type)
  4083. /* Internal members of a upb_msg. We can change this without breaking binary
  4084. * compatibility. We put these before the user's data. The user's upb_msg*
  4085. * points after the upb_msg_internal. */
  4086. /* Used when a message is not extendable. */
  4087. typedef struct {
  4088. /* TODO(haberman): use pointer tagging so we we are slim when known unknown
  4089. * fields are not present. */
  4090. upb_arena *arena;
  4091. char *unknown;
  4092. size_t unknown_len;
  4093. size_t unknown_size;
  4094. } upb_msg_internal;
  4095. /* Used when a message is extendable. */
  4096. typedef struct {
  4097. upb_inttable *extdict;
  4098. upb_msg_internal base;
  4099. } upb_msg_internal_withext;
  4100. static int upb_msg_internalsize(const upb_msglayout *l) {
  4101. return sizeof(upb_msg_internal) - l->extendable * sizeof(void *);
  4102. }
  4103. static upb_msg_internal *upb_msg_getinternal(upb_msg *msg) {
  4104. return VOIDPTR_AT(msg, -sizeof(upb_msg_internal));
  4105. }
  4106. static const upb_msg_internal *upb_msg_getinternal_const(const upb_msg *msg) {
  4107. return VOIDPTR_AT(msg, -sizeof(upb_msg_internal));
  4108. }
  4109. static upb_msg_internal_withext *upb_msg_getinternalwithext(
  4110. upb_msg *msg, const upb_msglayout *l) {
  4111. UPB_ASSERT(l->extendable);
  4112. return VOIDPTR_AT(msg, -sizeof(upb_msg_internal_withext));
  4113. }
  4114. void upb_msg_addunknown(upb_msg *msg, const char *data, size_t len) {
  4115. upb_msg_internal* in = upb_msg_getinternal(msg);
  4116. if (len > in->unknown_size - in->unknown_len) {
  4117. upb_alloc *alloc = upb_arena_alloc(in->arena);
  4118. size_t need = in->unknown_size + len;
  4119. size_t newsize = UPB_MAX(in->unknown_size * 2, need);
  4120. in->unknown = upb_realloc(alloc, in->unknown, in->unknown_size, newsize);
  4121. in->unknown_size = newsize;
  4122. }
  4123. memcpy(in->unknown + in->unknown_len, data, len);
  4124. in->unknown_len += len;
  4125. }
  4126. const char *upb_msg_getunknown(const upb_msg *msg, size_t *len) {
  4127. const upb_msg_internal* in = upb_msg_getinternal_const(msg);
  4128. *len = in->unknown_len;
  4129. return in->unknown;
  4130. }
  4131. static const upb_msglayout_field *upb_msg_checkfield(int field_index,
  4132. const upb_msglayout *l) {
  4133. UPB_ASSERT(field_index >= 0 && field_index < l->field_count);
  4134. return &l->fields[field_index];
  4135. }
  4136. static bool upb_msg_inoneof(const upb_msglayout_field *field) {
  4137. return field->presence < 0;
  4138. }
  4139. static uint32_t *upb_msg_oneofcase(const upb_msg *msg, int field_index,
  4140. const upb_msglayout *l) {
  4141. const upb_msglayout_field *field = upb_msg_checkfield(field_index, l);
  4142. UPB_ASSERT(upb_msg_inoneof(field));
  4143. return PTR_AT(msg, ~field->presence, uint32_t);
  4144. }
  4145. static size_t upb_msg_sizeof(const upb_msglayout *l) {
  4146. return l->size + upb_msg_internalsize(l);
  4147. }
  4148. upb_msg *upb_msg_new(const upb_msglayout *l, upb_arena *a) {
  4149. upb_alloc *alloc = upb_arena_alloc(a);
  4150. void *mem = upb_malloc(alloc, upb_msg_sizeof(l));
  4151. upb_msg_internal *in;
  4152. upb_msg *msg;
  4153. if (!mem) {
  4154. return NULL;
  4155. }
  4156. msg = VOIDPTR_AT(mem, upb_msg_internalsize(l));
  4157. /* Initialize normal members. */
  4158. memset(msg, 0, l->size);
  4159. /* Initialize internal members. */
  4160. in = upb_msg_getinternal(msg);
  4161. in->arena = a;
  4162. in->unknown = NULL;
  4163. in->unknown_len = 0;
  4164. in->unknown_size = 0;
  4165. if (l->extendable) {
  4166. upb_msg_getinternalwithext(msg, l)->extdict = NULL;
  4167. }
  4168. return msg;
  4169. }
  4170. upb_arena *upb_msg_arena(const upb_msg *msg) {
  4171. return upb_msg_getinternal_const(msg)->arena;
  4172. }
  4173. bool upb_msg_has(const upb_msg *msg,
  4174. int field_index,
  4175. const upb_msglayout *l) {
  4176. const upb_msglayout_field *field = upb_msg_checkfield(field_index, l);
  4177. UPB_ASSERT(field->presence);
  4178. if (upb_msg_inoneof(field)) {
  4179. /* Oneofs are set when the oneof number is set to this field. */
  4180. return *upb_msg_oneofcase(msg, field_index, l) == field->number;
  4181. } else {
  4182. /* Other fields are set when their hasbit is set. */
  4183. uint32_t hasbit = field->presence;
  4184. return DEREF(msg, hasbit / 8, char) | (1 << (hasbit % 8));
  4185. }
  4186. }
  4187. upb_msgval upb_msg_get(const upb_msg *msg, int field_index,
  4188. const upb_msglayout *l) {
  4189. const upb_msglayout_field *field = upb_msg_checkfield(field_index, l);
  4190. int size = upb_msg_fieldsize(field);
  4191. return upb_msgval_read(msg, field->offset, size);
  4192. }
  4193. void upb_msg_set(upb_msg *msg, int field_index, upb_msgval val,
  4194. const upb_msglayout *l) {
  4195. const upb_msglayout_field *field = upb_msg_checkfield(field_index, l);
  4196. int size = upb_msg_fieldsize(field);
  4197. upb_msgval_write(msg, field->offset, val, size);
  4198. }
  4199. /** upb_array *****************************************************************/
  4200. #define DEREF_ARR(arr, i, type) ((type*)arr->data)[i]
  4201. upb_array *upb_array_new(upb_fieldtype_t type, upb_arena *a) {
  4202. upb_alloc *alloc = upb_arena_alloc(a);
  4203. upb_array *ret = upb_malloc(alloc, sizeof(upb_array));
  4204. if (!ret) {
  4205. return NULL;
  4206. }
  4207. ret->type = type;
  4208. ret->data = NULL;
  4209. ret->len = 0;
  4210. ret->size = 0;
  4211. ret->element_size = upb_msgval_sizeof(type);
  4212. ret->arena = a;
  4213. return ret;
  4214. }
  4215. size_t upb_array_size(const upb_array *arr) {
  4216. return arr->len;
  4217. }
  4218. upb_fieldtype_t upb_array_type(const upb_array *arr) {
  4219. return arr->type;
  4220. }
  4221. upb_msgval upb_array_get(const upb_array *arr, size_t i) {
  4222. UPB_ASSERT(i < arr->len);
  4223. return upb_msgval_read(arr->data, i * arr->element_size, arr->element_size);
  4224. }
  4225. bool upb_array_set(upb_array *arr, size_t i, upb_msgval val) {
  4226. UPB_ASSERT(i <= arr->len);
  4227. if (i == arr->len) {
  4228. /* Extending the array. */
  4229. if (i == arr->size) {
  4230. /* Need to reallocate. */
  4231. size_t new_size = UPB_MAX(arr->size * 2, 8);
  4232. size_t new_bytes = new_size * arr->element_size;
  4233. size_t old_bytes = arr->size * arr->element_size;
  4234. upb_alloc *alloc = upb_arena_alloc(arr->arena);
  4235. upb_msgval *new_data =
  4236. upb_realloc(alloc, arr->data, old_bytes, new_bytes);
  4237. if (!new_data) {
  4238. return false;
  4239. }
  4240. arr->data = new_data;
  4241. arr->size = new_size;
  4242. }
  4243. arr->len = i + 1;
  4244. }
  4245. upb_msgval_write(arr->data, i * arr->element_size, val, arr->element_size);
  4246. return true;
  4247. }
  4248. /** upb_map *******************************************************************/
  4249. struct upb_map {
  4250. upb_fieldtype_t key_type;
  4251. upb_fieldtype_t val_type;
  4252. /* We may want to optimize this to use inttable where possible, for greater
  4253. * efficiency and lower memory footprint. */
  4254. upb_strtable strtab;
  4255. upb_arena *arena;
  4256. };
  4257. static void upb_map_tokey(upb_fieldtype_t type, upb_msgval *key,
  4258. const char **out_key, size_t *out_len) {
  4259. switch (type) {
  4260. case UPB_TYPE_STRING:
  4261. /* Point to string data of the input key. */
  4262. *out_key = key->str.data;
  4263. *out_len = key->str.size;
  4264. return;
  4265. case UPB_TYPE_BOOL:
  4266. case UPB_TYPE_INT32:
  4267. case UPB_TYPE_UINT32:
  4268. case UPB_TYPE_INT64:
  4269. case UPB_TYPE_UINT64:
  4270. /* Point to the key itself. XXX: big-endian. */
  4271. *out_key = (const char*)key;
  4272. *out_len = upb_msgval_sizeof(type);
  4273. return;
  4274. case UPB_TYPE_BYTES:
  4275. case UPB_TYPE_DOUBLE:
  4276. case UPB_TYPE_ENUM:
  4277. case UPB_TYPE_FLOAT:
  4278. case UPB_TYPE_MESSAGE:
  4279. break; /* Cannot be a map key. */
  4280. }
  4281. UPB_UNREACHABLE();
  4282. }
  4283. static upb_msgval upb_map_fromkey(upb_fieldtype_t type, const char *key,
  4284. size_t len) {
  4285. switch (type) {
  4286. case UPB_TYPE_STRING:
  4287. return upb_msgval_makestr(key, len);
  4288. case UPB_TYPE_BOOL:
  4289. case UPB_TYPE_INT32:
  4290. case UPB_TYPE_UINT32:
  4291. case UPB_TYPE_INT64:
  4292. case UPB_TYPE_UINT64:
  4293. return upb_msgval_read(key, 0, upb_msgval_sizeof(type));
  4294. case UPB_TYPE_BYTES:
  4295. case UPB_TYPE_DOUBLE:
  4296. case UPB_TYPE_ENUM:
  4297. case UPB_TYPE_FLOAT:
  4298. case UPB_TYPE_MESSAGE:
  4299. break; /* Cannot be a map key. */
  4300. }
  4301. UPB_UNREACHABLE();
  4302. }
  4303. upb_map *upb_map_new(upb_fieldtype_t ktype, upb_fieldtype_t vtype,
  4304. upb_arena *a) {
  4305. upb_ctype_t vtabtype = upb_fieldtotabtype(vtype);
  4306. upb_alloc *alloc = upb_arena_alloc(a);
  4307. upb_map *map = upb_malloc(alloc, sizeof(upb_map));
  4308. if (!map) {
  4309. return NULL;
  4310. }
  4311. UPB_ASSERT(upb_fieldtype_mapkeyok(ktype));
  4312. map->key_type = ktype;
  4313. map->val_type = vtype;
  4314. map->arena = a;
  4315. if (!upb_strtable_init2(&map->strtab, vtabtype, alloc)) {
  4316. return NULL;
  4317. }
  4318. return map;
  4319. }
  4320. size_t upb_map_size(const upb_map *map) {
  4321. return upb_strtable_count(&map->strtab);
  4322. }
  4323. upb_fieldtype_t upb_map_keytype(const upb_map *map) {
  4324. return map->key_type;
  4325. }
  4326. upb_fieldtype_t upb_map_valuetype(const upb_map *map) {
  4327. return map->val_type;
  4328. }
  4329. bool upb_map_get(const upb_map *map, upb_msgval key, upb_msgval *val) {
  4330. upb_value tabval;
  4331. const char *key_str;
  4332. size_t key_len;
  4333. bool ret;
  4334. upb_map_tokey(map->key_type, &key, &key_str, &key_len);
  4335. ret = upb_strtable_lookup2(&map->strtab, key_str, key_len, &tabval);
  4336. if (ret) {
  4337. memcpy(val, &tabval, sizeof(tabval));
  4338. }
  4339. return ret;
  4340. }
  4341. bool upb_map_set(upb_map *map, upb_msgval key, upb_msgval val,
  4342. upb_msgval *removed) {
  4343. const char *key_str;
  4344. size_t key_len;
  4345. upb_value tabval = upb_toval(val);
  4346. upb_value removedtabval;
  4347. upb_alloc *a = upb_arena_alloc(map->arena);
  4348. upb_map_tokey(map->key_type, &key, &key_str, &key_len);
  4349. /* TODO(haberman): add overwrite operation to minimize number of lookups. */
  4350. if (upb_strtable_lookup2(&map->strtab, key_str, key_len, NULL)) {
  4351. upb_strtable_remove3(&map->strtab, key_str, key_len, &removedtabval, a);
  4352. memcpy(&removed, &removedtabval, sizeof(removed));
  4353. }
  4354. return upb_strtable_insert3(&map->strtab, key_str, key_len, tabval, a);
  4355. }
  4356. bool upb_map_del(upb_map *map, upb_msgval key) {
  4357. const char *key_str;
  4358. size_t key_len;
  4359. upb_alloc *a = upb_arena_alloc(map->arena);
  4360. upb_map_tokey(map->key_type, &key, &key_str, &key_len);
  4361. return upb_strtable_remove3(&map->strtab, key_str, key_len, NULL, a);
  4362. }
  4363. /** upb_mapiter ***************************************************************/
  4364. struct upb_mapiter {
  4365. upb_strtable_iter iter;
  4366. upb_fieldtype_t key_type;
  4367. };
  4368. size_t upb_mapiter_sizeof() {
  4369. return sizeof(upb_mapiter);
  4370. }
  4371. void upb_mapiter_begin(upb_mapiter *i, const upb_map *map) {
  4372. upb_strtable_begin(&i->iter, &map->strtab);
  4373. i->key_type = map->key_type;
  4374. }
  4375. upb_mapiter *upb_mapiter_new(const upb_map *t, upb_alloc *a) {
  4376. upb_mapiter *ret = upb_malloc(a, upb_mapiter_sizeof());
  4377. if (!ret) {
  4378. return NULL;
  4379. }
  4380. upb_mapiter_begin(ret, t);
  4381. return ret;
  4382. }
  4383. void upb_mapiter_free(upb_mapiter *i, upb_alloc *a) {
  4384. upb_free(a, i);
  4385. }
  4386. void upb_mapiter_next(upb_mapiter *i) {
  4387. upb_strtable_next(&i->iter);
  4388. }
  4389. bool upb_mapiter_done(const upb_mapiter *i) {
  4390. return upb_strtable_done(&i->iter);
  4391. }
  4392. upb_msgval upb_mapiter_key(const upb_mapiter *i) {
  4393. return upb_map_fromkey(i->key_type, upb_strtable_iter_key(&i->iter),
  4394. upb_strtable_iter_keylength(&i->iter));
  4395. }
  4396. upb_msgval upb_mapiter_value(const upb_mapiter *i) {
  4397. return upb_msgval_fromval(upb_strtable_iter_value(&i->iter));
  4398. }
  4399. void upb_mapiter_setdone(upb_mapiter *i) {
  4400. upb_strtable_iter_setdone(&i->iter);
  4401. }
  4402. bool upb_mapiter_isequal(const upb_mapiter *i1, const upb_mapiter *i2) {
  4403. return upb_strtable_iter_isequal(&i1->iter, &i2->iter);
  4404. }
  4405. static bool is_power_of_two(size_t val) {
  4406. return (val & (val - 1)) == 0;
  4407. }
  4408. /* Align up to the given power of 2. */
  4409. static size_t align_up(size_t val, size_t align) {
  4410. UPB_ASSERT(is_power_of_two(align));
  4411. return (val + align - 1) & ~(align - 1);
  4412. }
  4413. static size_t div_round_up(size_t n, size_t d) {
  4414. return (n + d - 1) / d;
  4415. }
  4416. static size_t upb_msgval_sizeof2(upb_fieldtype_t type) {
  4417. switch (type) {
  4418. case UPB_TYPE_DOUBLE:
  4419. case UPB_TYPE_INT64:
  4420. case UPB_TYPE_UINT64:
  4421. return 8;
  4422. case UPB_TYPE_ENUM:
  4423. case UPB_TYPE_INT32:
  4424. case UPB_TYPE_UINT32:
  4425. case UPB_TYPE_FLOAT:
  4426. return 4;
  4427. case UPB_TYPE_BOOL:
  4428. return 1;
  4429. case UPB_TYPE_MESSAGE:
  4430. return sizeof(void*);
  4431. case UPB_TYPE_BYTES:
  4432. case UPB_TYPE_STRING:
  4433. return sizeof(upb_stringview);
  4434. }
  4435. UPB_UNREACHABLE();
  4436. }
  4437. static uint8_t upb_msg_fielddefsize(const upb_fielddef *f) {
  4438. if (upb_fielddef_isseq(f)) {
  4439. return sizeof(void*);
  4440. } else {
  4441. return upb_msgval_sizeof2(upb_fielddef_type(f));
  4442. }
  4443. }
  4444. /** upb_msglayout *************************************************************/
  4445. static void upb_msglayout_free(upb_msglayout *l) {
  4446. upb_gfree(l);
  4447. }
  4448. static size_t upb_msglayout_place(upb_msglayout *l, size_t size) {
  4449. size_t ret;
  4450. l->size = align_up(l->size, size);
  4451. ret = l->size;
  4452. l->size += size;
  4453. return ret;
  4454. }
  4455. static bool upb_msglayout_init(const upb_msgdef *m,
  4456. upb_msglayout *l,
  4457. upb_msgfactory *factory) {
  4458. upb_msg_field_iter it;
  4459. upb_msg_oneof_iter oit;
  4460. size_t hasbit;
  4461. size_t submsg_count = 0;
  4462. const upb_msglayout **submsgs;
  4463. upb_msglayout_field *fields;
  4464. for (upb_msg_field_begin(&it, m);
  4465. !upb_msg_field_done(&it);
  4466. upb_msg_field_next(&it)) {
  4467. const upb_fielddef* f = upb_msg_iter_field(&it);
  4468. if (upb_fielddef_issubmsg(f)) {
  4469. submsg_count++;
  4470. }
  4471. }
  4472. memset(l, 0, sizeof(*l));
  4473. fields = upb_gmalloc(upb_msgdef_numfields(m) * sizeof(*fields));
  4474. submsgs = upb_gmalloc(submsg_count * sizeof(*submsgs));
  4475. if ((!fields && upb_msgdef_numfields(m)) ||
  4476. (!submsgs && submsg_count)) {
  4477. /* OOM. */
  4478. upb_gfree(fields);
  4479. upb_gfree(submsgs);
  4480. return false;
  4481. }
  4482. l->field_count = upb_msgdef_numfields(m);
  4483. l->fields = fields;
  4484. l->submsgs = submsgs;
  4485. /* Allocate data offsets in three stages:
  4486. *
  4487. * 1. hasbits.
  4488. * 2. regular fields.
  4489. * 3. oneof fields.
  4490. *
  4491. * OPT: There is a lot of room for optimization here to minimize the size.
  4492. */
  4493. /* Allocate hasbits and set basic field attributes. */
  4494. submsg_count = 0;
  4495. for (upb_msg_field_begin(&it, m), hasbit = 0;
  4496. !upb_msg_field_done(&it);
  4497. upb_msg_field_next(&it)) {
  4498. const upb_fielddef* f = upb_msg_iter_field(&it);
  4499. upb_msglayout_field *field = &fields[upb_fielddef_index(f)];
  4500. field->number = upb_fielddef_number(f);
  4501. field->descriptortype = upb_fielddef_descriptortype(f);
  4502. field->label = upb_fielddef_label(f);
  4503. if (upb_fielddef_issubmsg(f)) {
  4504. const upb_msglayout *sub_layout =
  4505. upb_msgfactory_getlayout(factory, upb_fielddef_msgsubdef(f));
  4506. field->submsg_index = submsg_count++;
  4507. submsgs[field->submsg_index] = sub_layout;
  4508. }
  4509. if (upb_fielddef_haspresence(f) && !upb_fielddef_containingoneof(f)) {
  4510. field->presence = (hasbit++);
  4511. } else {
  4512. field->presence = 0;
  4513. }
  4514. }
  4515. /* Account for space used by hasbits. */
  4516. l->size = div_round_up(hasbit, 8);
  4517. /* Allocate non-oneof fields. */
  4518. for (upb_msg_field_begin(&it, m); !upb_msg_field_done(&it);
  4519. upb_msg_field_next(&it)) {
  4520. const upb_fielddef* f = upb_msg_iter_field(&it);
  4521. size_t field_size = upb_msg_fielddefsize(f);
  4522. size_t index = upb_fielddef_index(f);
  4523. if (upb_fielddef_containingoneof(f)) {
  4524. /* Oneofs are handled separately below. */
  4525. continue;
  4526. }
  4527. fields[index].offset = upb_msglayout_place(l, field_size);
  4528. }
  4529. /* Allocate oneof fields. Each oneof field consists of a uint32 for the case
  4530. * and space for the actual data. */
  4531. for (upb_msg_oneof_begin(&oit, m); !upb_msg_oneof_done(&oit);
  4532. upb_msg_oneof_next(&oit)) {
  4533. const upb_oneofdef* o = upb_msg_iter_oneof(&oit);
  4534. upb_oneof_iter fit;
  4535. size_t case_size = sizeof(uint32_t); /* Could potentially optimize this. */
  4536. size_t field_size = 0;
  4537. uint32_t case_offset;
  4538. uint32_t data_offset;
  4539. /* Calculate field size: the max of all field sizes. */
  4540. for (upb_oneof_begin(&fit, o);
  4541. !upb_oneof_done(&fit);
  4542. upb_oneof_next(&fit)) {
  4543. const upb_fielddef* f = upb_oneof_iter_field(&fit);
  4544. field_size = UPB_MAX(field_size, upb_msg_fielddefsize(f));
  4545. }
  4546. /* Align and allocate case offset. */
  4547. case_offset = upb_msglayout_place(l, case_size);
  4548. data_offset = upb_msglayout_place(l, field_size);
  4549. for (upb_oneof_begin(&fit, o);
  4550. !upb_oneof_done(&fit);
  4551. upb_oneof_next(&fit)) {
  4552. const upb_fielddef* f = upb_oneof_iter_field(&fit);
  4553. fields[upb_fielddef_index(f)].offset = data_offset;
  4554. fields[upb_fielddef_index(f)].presence = ~case_offset;
  4555. }
  4556. }
  4557. /* Size of the entire structure should be a multiple of its greatest
  4558. * alignment. TODO: track overall alignment for real? */
  4559. l->size = align_up(l->size, 8);
  4560. return true;
  4561. }
  4562. /** upb_msgfactory ************************************************************/
  4563. struct upb_msgfactory {
  4564. const upb_symtab *symtab; /* We own a ref. */
  4565. upb_inttable layouts;
  4566. upb_inttable mergehandlers;
  4567. };
  4568. upb_msgfactory *upb_msgfactory_new(const upb_symtab *symtab) {
  4569. upb_msgfactory *ret = upb_gmalloc(sizeof(*ret));
  4570. ret->symtab = symtab;
  4571. upb_inttable_init(&ret->layouts, UPB_CTYPE_PTR);
  4572. upb_inttable_init(&ret->mergehandlers, UPB_CTYPE_CONSTPTR);
  4573. return ret;
  4574. }
  4575. void upb_msgfactory_free(upb_msgfactory *f) {
  4576. upb_inttable_iter i;
  4577. upb_inttable_begin(&i, &f->layouts);
  4578. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  4579. upb_msglayout *l = upb_value_getptr(upb_inttable_iter_value(&i));
  4580. upb_msglayout_free(l);
  4581. }
  4582. upb_inttable_begin(&i, &f->mergehandlers);
  4583. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  4584. const upb_handlers *h = upb_value_getconstptr(upb_inttable_iter_value(&i));
  4585. upb_handlers_unref(h, f);
  4586. }
  4587. upb_inttable_uninit(&f->layouts);
  4588. upb_inttable_uninit(&f->mergehandlers);
  4589. upb_gfree(f);
  4590. }
  4591. const upb_symtab *upb_msgfactory_symtab(const upb_msgfactory *f) {
  4592. return f->symtab;
  4593. }
  4594. const upb_msglayout *upb_msgfactory_getlayout(upb_msgfactory *f,
  4595. const upb_msgdef *m) {
  4596. upb_value v;
  4597. UPB_ASSERT(upb_symtab_lookupmsg(f->symtab, upb_msgdef_fullname(m)) == m);
  4598. UPB_ASSERT(!upb_msgdef_mapentry(m));
  4599. if (upb_inttable_lookupptr(&f->layouts, m, &v)) {
  4600. UPB_ASSERT(upb_value_getptr(v));
  4601. return upb_value_getptr(v);
  4602. } else {
  4603. /* In case of circular dependency, layout has to be inserted first. */
  4604. upb_msglayout *l = upb_gmalloc(sizeof(*l));
  4605. upb_msgfactory *mutable_f = (void*)f;
  4606. upb_inttable_insertptr(&mutable_f->layouts, m, upb_value_ptr(l));
  4607. UPB_ASSERT(l);
  4608. if (!upb_msglayout_init(m, l, f)) {
  4609. upb_msglayout_free(l);
  4610. }
  4611. return l;
  4612. }
  4613. }
  4614. /*
  4615. ** upb::RefCounted Implementation
  4616. **
  4617. ** Our key invariants are:
  4618. ** 1. reference cycles never span groups
  4619. ** 2. for ref2(to, from), we increment to's count iff group(from) != group(to)
  4620. **
  4621. ** The previous two are how we avoid leaking cycles. Other important
  4622. ** invariants are:
  4623. ** 3. for mutable objects "from" and "to", if there exists a ref2(to, from)
  4624. ** this implies group(from) == group(to). (In practice, what we implement
  4625. ** is even stronger; "from" and "to" will share a group if there has *ever*
  4626. ** been a ref2(to, from), but all that is necessary for correctness is the
  4627. ** weaker one).
  4628. ** 4. mutable and immutable objects are never in the same group.
  4629. */
  4630. #include <setjmp.h>
  4631. static void freeobj(upb_refcounted *o);
  4632. const char untracked_val;
  4633. const void *UPB_UNTRACKED_REF = &untracked_val;
  4634. /* arch-specific atomic primitives *******************************************/
  4635. #ifdef UPB_THREAD_UNSAFE /*---------------------------------------------------*/
  4636. static void atomic_inc(uint32_t *a) { (*a)++; }
  4637. static bool atomic_dec(uint32_t *a) { return --(*a) == 0; }
  4638. #elif defined(__GNUC__) || defined(__clang__) /*------------------------------*/
  4639. static void atomic_inc(uint32_t *a) { __sync_fetch_and_add(a, 1); }
  4640. static bool atomic_dec(uint32_t *a) { return __sync_sub_and_fetch(a, 1) == 0; }
  4641. #elif defined(WIN32) /*-------------------------------------------------------*/
  4642. #include <Windows.h>
  4643. static void atomic_inc(upb_atomic_t *a) { InterlockedIncrement(&a->val); }
  4644. static bool atomic_dec(upb_atomic_t *a) {
  4645. return InterlockedDecrement(&a->val) == 0;
  4646. }
  4647. #else
  4648. #error Atomic primitives not defined for your platform/CPU. \
  4649. Implement them or compile with UPB_THREAD_UNSAFE.
  4650. #endif
  4651. /* All static objects point to this refcount.
  4652. * It is special-cased in ref/unref below. */
  4653. uint32_t static_refcount = -1;
  4654. /* We can avoid atomic ops for statically-declared objects.
  4655. * This is a minor optimization but nice since we can avoid degrading under
  4656. * contention in this case. */
  4657. static void refgroup(uint32_t *group) {
  4658. if (group != &static_refcount)
  4659. atomic_inc(group);
  4660. }
  4661. static bool unrefgroup(uint32_t *group) {
  4662. if (group == &static_refcount) {
  4663. return false;
  4664. } else {
  4665. return atomic_dec(group);
  4666. }
  4667. }
  4668. /* Reference tracking (debug only) ********************************************/
  4669. #ifdef UPB_DEBUG_REFS
  4670. #ifdef UPB_THREAD_UNSAFE
  4671. static void upb_lock() {}
  4672. static void upb_unlock() {}
  4673. #else
  4674. /* User must define functions that lock/unlock a global mutex and link this
  4675. * file against them. */
  4676. void upb_lock();
  4677. void upb_unlock();
  4678. #endif
  4679. /* UPB_DEBUG_REFS mode counts on being able to malloc() memory in some
  4680. * code-paths that can normally never fail, like upb_refcounted_ref(). Since
  4681. * we have no way to propagage out-of-memory errors back to the user, and since
  4682. * these errors can only occur in UPB_DEBUG_REFS mode, we use an allocator that
  4683. * immediately aborts on failure (avoiding the global allocator, which might
  4684. * inject failures). */
  4685. #include <stdlib.h>
  4686. static void *upb_debugrefs_allocfunc(upb_alloc *alloc, void *ptr,
  4687. size_t oldsize, size_t size) {
  4688. UPB_UNUSED(alloc);
  4689. UPB_UNUSED(oldsize);
  4690. if (size == 0) {
  4691. free(ptr);
  4692. return NULL;
  4693. } else {
  4694. void *ret = realloc(ptr, size);
  4695. if (!ret) {
  4696. abort();
  4697. }
  4698. return ret;
  4699. }
  4700. }
  4701. upb_alloc upb_alloc_debugrefs = {&upb_debugrefs_allocfunc};
  4702. typedef struct {
  4703. int count; /* How many refs there are (duplicates only allowed for ref2). */
  4704. bool is_ref2;
  4705. } trackedref;
  4706. static trackedref *trackedref_new(bool is_ref2) {
  4707. trackedref *ret = upb_malloc(&upb_alloc_debugrefs, sizeof(*ret));
  4708. ret->count = 1;
  4709. ret->is_ref2 = is_ref2;
  4710. return ret;
  4711. }
  4712. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  4713. upb_value v;
  4714. UPB_ASSERT(owner);
  4715. if (owner == UPB_UNTRACKED_REF) return;
  4716. upb_lock();
  4717. if (upb_inttable_lookupptr(r->refs, owner, &v)) {
  4718. trackedref *ref = upb_value_getptr(v);
  4719. /* Since we allow multiple ref2's for the same to/from pair without
  4720. * allocating separate memory for each one, we lose the fine-grained
  4721. * tracking behavior we get with regular refs. Since ref2s only happen
  4722. * inside upb, we'll accept this limitation until/unless there is a really
  4723. * difficult upb-internal bug that can't be figured out without it. */
  4724. UPB_ASSERT(ref2);
  4725. UPB_ASSERT(ref->is_ref2);
  4726. ref->count++;
  4727. } else {
  4728. trackedref *ref = trackedref_new(ref2);
  4729. upb_inttable_insertptr2(r->refs, owner, upb_value_ptr(ref),
  4730. &upb_alloc_debugrefs);
  4731. if (ref2) {
  4732. /* We know this cast is safe when it is a ref2, because it's coming from
  4733. * another refcounted object. */
  4734. const upb_refcounted *from = owner;
  4735. UPB_ASSERT(!upb_inttable_lookupptr(from->ref2s, r, NULL));
  4736. upb_inttable_insertptr2(from->ref2s, r, upb_value_ptr(NULL),
  4737. &upb_alloc_debugrefs);
  4738. }
  4739. }
  4740. upb_unlock();
  4741. }
  4742. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  4743. upb_value v;
  4744. bool found;
  4745. trackedref *ref;
  4746. UPB_ASSERT(owner);
  4747. if (owner == UPB_UNTRACKED_REF) return;
  4748. upb_lock();
  4749. found = upb_inttable_lookupptr(r->refs, owner, &v);
  4750. /* This assert will fail if an owner attempts to release a ref it didn't have. */
  4751. UPB_ASSERT(found);
  4752. ref = upb_value_getptr(v);
  4753. UPB_ASSERT(ref->is_ref2 == ref2);
  4754. if (--ref->count == 0) {
  4755. free(ref);
  4756. upb_inttable_removeptr(r->refs, owner, NULL);
  4757. if (ref2) {
  4758. /* We know this cast is safe when it is a ref2, because it's coming from
  4759. * another refcounted object. */
  4760. const upb_refcounted *from = owner;
  4761. bool removed = upb_inttable_removeptr(from->ref2s, r, NULL);
  4762. UPB_ASSERT(removed);
  4763. }
  4764. }
  4765. upb_unlock();
  4766. }
  4767. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  4768. upb_value v;
  4769. bool found;
  4770. trackedref *ref;
  4771. upb_lock();
  4772. found = upb_inttable_lookupptr(r->refs, owner, &v);
  4773. UPB_ASSERT(found);
  4774. ref = upb_value_getptr(v);
  4775. UPB_ASSERT(ref->is_ref2 == ref2);
  4776. upb_unlock();
  4777. }
  4778. /* Populates the given UPB_CTYPE_INT32 inttable with counts of ref2's that
  4779. * originate from the given owner. */
  4780. static void getref2s(const upb_refcounted *owner, upb_inttable *tab) {
  4781. upb_inttable_iter i;
  4782. upb_lock();
  4783. upb_inttable_begin(&i, owner->ref2s);
  4784. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  4785. upb_value v;
  4786. upb_value count;
  4787. trackedref *ref;
  4788. bool found;
  4789. upb_refcounted *to = (upb_refcounted*)upb_inttable_iter_key(&i);
  4790. /* To get the count we need to look in the target's table. */
  4791. found = upb_inttable_lookupptr(to->refs, owner, &v);
  4792. UPB_ASSERT(found);
  4793. ref = upb_value_getptr(v);
  4794. count = upb_value_int32(ref->count);
  4795. upb_inttable_insertptr2(tab, to, count, &upb_alloc_debugrefs);
  4796. }
  4797. upb_unlock();
  4798. }
  4799. typedef struct {
  4800. upb_inttable ref2;
  4801. const upb_refcounted *obj;
  4802. } check_state;
  4803. static void visit_check(const upb_refcounted *obj, const upb_refcounted *subobj,
  4804. void *closure) {
  4805. check_state *s = closure;
  4806. upb_inttable *ref2 = &s->ref2;
  4807. upb_value v;
  4808. bool removed;
  4809. int32_t newcount;
  4810. UPB_ASSERT(obj == s->obj);
  4811. UPB_ASSERT(subobj);
  4812. removed = upb_inttable_removeptr(ref2, subobj, &v);
  4813. /* The following assertion will fail if the visit() function visits a subobj
  4814. * that it did not have a ref2 on, or visits the same subobj too many times. */
  4815. UPB_ASSERT(removed);
  4816. newcount = upb_value_getint32(v) - 1;
  4817. if (newcount > 0) {
  4818. upb_inttable_insert2(ref2, (uintptr_t)subobj, upb_value_int32(newcount),
  4819. &upb_alloc_debugrefs);
  4820. }
  4821. }
  4822. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  4823. void *closure) {
  4824. /* In DEBUG_REFS mode we know what existing ref2 refs there are, so we know
  4825. * exactly the set of nodes that visit() should visit. So we verify visit()'s
  4826. * correctness here. */
  4827. check_state state;
  4828. state.obj = r;
  4829. upb_inttable_init2(&state.ref2, UPB_CTYPE_INT32, &upb_alloc_debugrefs);
  4830. getref2s(r, &state.ref2);
  4831. /* This should visit any children in the ref2 table. */
  4832. if (r->vtbl->visit) r->vtbl->visit(r, visit_check, &state);
  4833. /* This assertion will fail if the visit() function missed any children. */
  4834. UPB_ASSERT(upb_inttable_count(&state.ref2) == 0);
  4835. upb_inttable_uninit2(&state.ref2, &upb_alloc_debugrefs);
  4836. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  4837. }
  4838. static void trackinit(upb_refcounted *r) {
  4839. r->refs = upb_malloc(&upb_alloc_debugrefs, sizeof(*r->refs));
  4840. r->ref2s = upb_malloc(&upb_alloc_debugrefs, sizeof(*r->ref2s));
  4841. upb_inttable_init2(r->refs, UPB_CTYPE_PTR, &upb_alloc_debugrefs);
  4842. upb_inttable_init2(r->ref2s, UPB_CTYPE_PTR, &upb_alloc_debugrefs);
  4843. }
  4844. static void trackfree(const upb_refcounted *r) {
  4845. upb_inttable_uninit2(r->refs, &upb_alloc_debugrefs);
  4846. upb_inttable_uninit2(r->ref2s, &upb_alloc_debugrefs);
  4847. upb_free(&upb_alloc_debugrefs, r->refs);
  4848. upb_free(&upb_alloc_debugrefs, r->ref2s);
  4849. }
  4850. #else
  4851. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  4852. UPB_UNUSED(r);
  4853. UPB_UNUSED(owner);
  4854. UPB_UNUSED(ref2);
  4855. }
  4856. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  4857. UPB_UNUSED(r);
  4858. UPB_UNUSED(owner);
  4859. UPB_UNUSED(ref2);
  4860. }
  4861. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  4862. UPB_UNUSED(r);
  4863. UPB_UNUSED(owner);
  4864. UPB_UNUSED(ref2);
  4865. }
  4866. static void trackinit(upb_refcounted *r) {
  4867. UPB_UNUSED(r);
  4868. }
  4869. static void trackfree(const upb_refcounted *r) {
  4870. UPB_UNUSED(r);
  4871. }
  4872. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  4873. void *closure) {
  4874. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  4875. }
  4876. #endif /* UPB_DEBUG_REFS */
  4877. /* freeze() *******************************************************************/
  4878. /* The freeze() operation is by far the most complicated part of this scheme.
  4879. * We compute strongly-connected components and then mutate the graph such that
  4880. * we preserve the invariants documented at the top of this file. And we must
  4881. * handle out-of-memory errors gracefully (without leaving the graph
  4882. * inconsistent), which adds to the fun. */
  4883. /* The state used by the freeze operation (shared across many functions). */
  4884. typedef struct {
  4885. int depth;
  4886. int maxdepth;
  4887. uint64_t index;
  4888. /* Maps upb_refcounted* -> attributes (color, etc). attr layout varies by
  4889. * color. */
  4890. upb_inttable objattr;
  4891. upb_inttable stack; /* stack of upb_refcounted* for Tarjan's algorithm. */
  4892. upb_inttable groups; /* array of uint32_t*, malloc'd refcounts for new groups */
  4893. upb_status *status;
  4894. jmp_buf err;
  4895. } tarjan;
  4896. static void release_ref2(const upb_refcounted *obj,
  4897. const upb_refcounted *subobj,
  4898. void *closure);
  4899. /* Node attributes -----------------------------------------------------------*/
  4900. /* After our analysis phase all nodes will be either GRAY or WHITE. */
  4901. typedef enum {
  4902. BLACK = 0, /* Object has not been seen. */
  4903. GRAY, /* Object has been found via a refgroup but may not be reachable. */
  4904. GREEN, /* Object is reachable and is currently on the Tarjan stack. */
  4905. WHITE /* Object is reachable and has been assigned a group (SCC). */
  4906. } color_t;
  4907. UPB_NORETURN static void err(tarjan *t) { longjmp(t->err, 1); }
  4908. UPB_NORETURN static void oom(tarjan *t) {
  4909. upb_status_seterrmsg(t->status, "out of memory");
  4910. err(t);
  4911. }
  4912. static uint64_t trygetattr(const tarjan *t, const upb_refcounted *r) {
  4913. upb_value v;
  4914. return upb_inttable_lookupptr(&t->objattr, r, &v) ?
  4915. upb_value_getuint64(v) : 0;
  4916. }
  4917. static uint64_t getattr(const tarjan *t, const upb_refcounted *r) {
  4918. upb_value v;
  4919. bool found = upb_inttable_lookupptr(&t->objattr, r, &v);
  4920. UPB_ASSERT(found);
  4921. return upb_value_getuint64(v);
  4922. }
  4923. static void setattr(tarjan *t, const upb_refcounted *r, uint64_t attr) {
  4924. upb_inttable_removeptr(&t->objattr, r, NULL);
  4925. upb_inttable_insertptr(&t->objattr, r, upb_value_uint64(attr));
  4926. }
  4927. static color_t color(tarjan *t, const upb_refcounted *r) {
  4928. return trygetattr(t, r) & 0x3; /* Color is always stored in the low 2 bits. */
  4929. }
  4930. static void set_gray(tarjan *t, const upb_refcounted *r) {
  4931. UPB_ASSERT(color(t, r) == BLACK);
  4932. setattr(t, r, GRAY);
  4933. }
  4934. /* Pushes an obj onto the Tarjan stack and sets it to GREEN. */
  4935. static void push(tarjan *t, const upb_refcounted *r) {
  4936. UPB_ASSERT(color(t, r) == BLACK || color(t, r) == GRAY);
  4937. /* This defines the attr layout for the GREEN state. "index" and "lowlink"
  4938. * get 31 bits, which is plenty (limit of 2B objects frozen at a time). */
  4939. setattr(t, r, GREEN | (t->index << 2) | (t->index << 33));
  4940. if (++t->index == 0x80000000) {
  4941. upb_status_seterrmsg(t->status, "too many objects to freeze");
  4942. err(t);
  4943. }
  4944. upb_inttable_push(&t->stack, upb_value_ptr((void*)r));
  4945. }
  4946. /* Pops an obj from the Tarjan stack and sets it to WHITE, with a ptr to its
  4947. * SCC group. */
  4948. static upb_refcounted *pop(tarjan *t) {
  4949. upb_refcounted *r = upb_value_getptr(upb_inttable_pop(&t->stack));
  4950. UPB_ASSERT(color(t, r) == GREEN);
  4951. /* This defines the attr layout for nodes in the WHITE state.
  4952. * Top of group stack is [group, NULL]; we point at group. */
  4953. setattr(t, r, WHITE | (upb_inttable_count(&t->groups) - 2) << 8);
  4954. return r;
  4955. }
  4956. static void tarjan_newgroup(tarjan *t) {
  4957. uint32_t *group = upb_gmalloc(sizeof(*group));
  4958. if (!group) oom(t);
  4959. /* Push group and empty group leader (we'll fill in leader later). */
  4960. if (!upb_inttable_push(&t->groups, upb_value_ptr(group)) ||
  4961. !upb_inttable_push(&t->groups, upb_value_ptr(NULL))) {
  4962. upb_gfree(group);
  4963. oom(t);
  4964. }
  4965. *group = 0;
  4966. }
  4967. static uint32_t idx(tarjan *t, const upb_refcounted *r) {
  4968. UPB_ASSERT(color(t, r) == GREEN);
  4969. return (getattr(t, r) >> 2) & 0x7FFFFFFF;
  4970. }
  4971. static uint32_t lowlink(tarjan *t, const upb_refcounted *r) {
  4972. if (color(t, r) == GREEN) {
  4973. return getattr(t, r) >> 33;
  4974. } else {
  4975. return UINT32_MAX;
  4976. }
  4977. }
  4978. static void set_lowlink(tarjan *t, const upb_refcounted *r, uint32_t lowlink) {
  4979. UPB_ASSERT(color(t, r) == GREEN);
  4980. setattr(t, r, ((uint64_t)lowlink << 33) | (getattr(t, r) & 0x1FFFFFFFF));
  4981. }
  4982. static uint32_t *group(tarjan *t, upb_refcounted *r) {
  4983. uint64_t groupnum;
  4984. upb_value v;
  4985. bool found;
  4986. UPB_ASSERT(color(t, r) == WHITE);
  4987. groupnum = getattr(t, r) >> 8;
  4988. found = upb_inttable_lookup(&t->groups, groupnum, &v);
  4989. UPB_ASSERT(found);
  4990. return upb_value_getptr(v);
  4991. }
  4992. /* If the group leader for this object's group has not previously been set,
  4993. * the given object is assigned to be its leader. */
  4994. static upb_refcounted *groupleader(tarjan *t, upb_refcounted *r) {
  4995. uint64_t leader_slot;
  4996. upb_value v;
  4997. bool found;
  4998. UPB_ASSERT(color(t, r) == WHITE);
  4999. leader_slot = (getattr(t, r) >> 8) + 1;
  5000. found = upb_inttable_lookup(&t->groups, leader_slot, &v);
  5001. UPB_ASSERT(found);
  5002. if (upb_value_getptr(v)) {
  5003. return upb_value_getptr(v);
  5004. } else {
  5005. upb_inttable_remove(&t->groups, leader_slot, NULL);
  5006. upb_inttable_insert(&t->groups, leader_slot, upb_value_ptr(r));
  5007. return r;
  5008. }
  5009. }
  5010. /* Tarjan's algorithm --------------------------------------------------------*/
  5011. /* See:
  5012. * http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm */
  5013. static void do_tarjan(const upb_refcounted *obj, tarjan *t);
  5014. static void tarjan_visit(const upb_refcounted *obj,
  5015. const upb_refcounted *subobj,
  5016. void *closure) {
  5017. tarjan *t = closure;
  5018. if (++t->depth > t->maxdepth) {
  5019. upb_status_seterrf(t->status, "graph too deep to freeze (%d)", t->maxdepth);
  5020. err(t);
  5021. } else if (subobj->is_frozen || color(t, subobj) == WHITE) {
  5022. /* Do nothing: we don't want to visit or color already-frozen nodes,
  5023. * and WHITE nodes have already been assigned a SCC. */
  5024. } else if (color(t, subobj) < GREEN) {
  5025. /* Subdef has not yet been visited; recurse on it. */
  5026. do_tarjan(subobj, t);
  5027. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), lowlink(t, subobj)));
  5028. } else if (color(t, subobj) == GREEN) {
  5029. /* Subdef is in the stack and hence in the current SCC. */
  5030. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), idx(t, subobj)));
  5031. }
  5032. --t->depth;
  5033. }
  5034. static void do_tarjan(const upb_refcounted *obj, tarjan *t) {
  5035. if (color(t, obj) == BLACK) {
  5036. /* We haven't seen this object's group; mark the whole group GRAY. */
  5037. const upb_refcounted *o = obj;
  5038. do { set_gray(t, o); } while ((o = o->next) != obj);
  5039. }
  5040. push(t, obj);
  5041. visit(obj, tarjan_visit, t);
  5042. if (lowlink(t, obj) == idx(t, obj)) {
  5043. tarjan_newgroup(t);
  5044. while (pop(t) != obj)
  5045. ;
  5046. }
  5047. }
  5048. /* freeze() ------------------------------------------------------------------*/
  5049. static void crossref(const upb_refcounted *r, const upb_refcounted *subobj,
  5050. void *_t) {
  5051. tarjan *t = _t;
  5052. UPB_ASSERT(color(t, r) > BLACK);
  5053. if (color(t, subobj) > BLACK && r->group != subobj->group) {
  5054. /* Previously this ref was not reflected in subobj->group because they
  5055. * were in the same group; now that they are split a ref must be taken. */
  5056. refgroup(subobj->group);
  5057. }
  5058. }
  5059. static bool freeze(upb_refcounted *const*roots, int n, upb_status *s,
  5060. int maxdepth) {
  5061. volatile bool ret = false;
  5062. int i;
  5063. upb_inttable_iter iter;
  5064. /* We run in two passes so that we can allocate all memory before performing
  5065. * any mutation of the input -- this allows us to leave the input unchanged
  5066. * in the case of memory allocation failure. */
  5067. tarjan t;
  5068. t.index = 0;
  5069. t.depth = 0;
  5070. t.maxdepth = maxdepth;
  5071. t.status = s;
  5072. if (!upb_inttable_init(&t.objattr, UPB_CTYPE_UINT64)) goto err1;
  5073. if (!upb_inttable_init(&t.stack, UPB_CTYPE_PTR)) goto err2;
  5074. if (!upb_inttable_init(&t.groups, UPB_CTYPE_PTR)) goto err3;
  5075. if (setjmp(t.err) != 0) goto err4;
  5076. for (i = 0; i < n; i++) {
  5077. if (color(&t, roots[i]) < GREEN) {
  5078. do_tarjan(roots[i], &t);
  5079. }
  5080. }
  5081. /* If we've made it this far, no further errors are possible so it's safe to
  5082. * mutate the objects without risk of leaving them in an inconsistent state. */
  5083. ret = true;
  5084. /* The transformation that follows requires care. The preconditions are:
  5085. * - all objects in attr map are WHITE or GRAY, and are in mutable groups
  5086. * (groups of all mutable objs)
  5087. * - no ref2(to, from) refs have incremented count(to) if both "to" and
  5088. * "from" are in our attr map (this follows from invariants (2) and (3)) */
  5089. /* Pass 1: we remove WHITE objects from their mutable groups, and add them to
  5090. * new groups according to the SCC's we computed. These new groups will
  5091. * consist of only frozen objects. None will be immediately collectible,
  5092. * because WHITE objects are by definition reachable from one of "roots",
  5093. * which the caller must own refs on. */
  5094. upb_inttable_begin(&iter, &t.objattr);
  5095. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  5096. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  5097. /* Since removal from a singly-linked list requires access to the object's
  5098. * predecessor, we consider obj->next instead of obj for moving. With the
  5099. * while() loop we guarantee that we will visit every node's predecessor.
  5100. * Proof:
  5101. * 1. every node's predecessor is in our attr map.
  5102. * 2. though the loop body may change a node's predecessor, it will only
  5103. * change it to be the node we are currently operating on, so with a
  5104. * while() loop we guarantee ourselves the chance to remove each node. */
  5105. while (color(&t, obj->next) == WHITE &&
  5106. group(&t, obj->next) != obj->next->group) {
  5107. upb_refcounted *leader;
  5108. /* Remove from old group. */
  5109. upb_refcounted *move = obj->next;
  5110. if (obj == move) {
  5111. /* Removing the last object from a group. */
  5112. UPB_ASSERT(*obj->group == obj->individual_count);
  5113. upb_gfree(obj->group);
  5114. } else {
  5115. obj->next = move->next;
  5116. /* This may decrease to zero; we'll collect GRAY objects (if any) that
  5117. * remain in the group in the third pass. */
  5118. UPB_ASSERT(*move->group >= move->individual_count);
  5119. *move->group -= move->individual_count;
  5120. }
  5121. /* Add to new group. */
  5122. leader = groupleader(&t, move);
  5123. if (move == leader) {
  5124. /* First object added to new group is its leader. */
  5125. move->group = group(&t, move);
  5126. move->next = move;
  5127. *move->group = move->individual_count;
  5128. } else {
  5129. /* Group already has at least one object in it. */
  5130. UPB_ASSERT(leader->group == group(&t, move));
  5131. move->group = group(&t, move);
  5132. move->next = leader->next;
  5133. leader->next = move;
  5134. *move->group += move->individual_count;
  5135. }
  5136. move->is_frozen = true;
  5137. }
  5138. }
  5139. /* Pass 2: GRAY and WHITE objects "obj" with ref2(to, obj) references must
  5140. * increment count(to) if group(obj) != group(to) (which could now be the
  5141. * case if "to" was just frozen). */
  5142. upb_inttable_begin(&iter, &t.objattr);
  5143. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  5144. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  5145. visit(obj, crossref, &t);
  5146. }
  5147. /* Pass 3: GRAY objects are collected if their group's refcount dropped to
  5148. * zero when we removed its white nodes. This can happen if they had only
  5149. * been kept alive by virtue of sharing a group with an object that was just
  5150. * frozen.
  5151. *
  5152. * It is important that we do this last, since the GRAY object's free()
  5153. * function could call unref2() on just-frozen objects, which will decrement
  5154. * refs that were added in pass 2. */
  5155. upb_inttable_begin(&iter, &t.objattr);
  5156. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  5157. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  5158. if (obj->group == NULL || *obj->group == 0) {
  5159. if (obj->group) {
  5160. upb_refcounted *o;
  5161. /* We eagerly free() the group's count (since we can't easily determine
  5162. * the group's remaining size it's the easiest way to ensure it gets
  5163. * done). */
  5164. upb_gfree(obj->group);
  5165. /* Visit to release ref2's (done in a separate pass since release_ref2
  5166. * depends on o->group being unmodified so it can test merged()). */
  5167. o = obj;
  5168. do { visit(o, release_ref2, NULL); } while ((o = o->next) != obj);
  5169. /* Mark "group" fields as NULL so we know to free the objects later in
  5170. * this loop, but also don't try to delete the group twice. */
  5171. o = obj;
  5172. do { o->group = NULL; } while ((o = o->next) != obj);
  5173. }
  5174. freeobj(obj);
  5175. }
  5176. }
  5177. err4:
  5178. if (!ret) {
  5179. upb_inttable_begin(&iter, &t.groups);
  5180. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter))
  5181. upb_gfree(upb_value_getptr(upb_inttable_iter_value(&iter)));
  5182. }
  5183. upb_inttable_uninit(&t.groups);
  5184. err3:
  5185. upb_inttable_uninit(&t.stack);
  5186. err2:
  5187. upb_inttable_uninit(&t.objattr);
  5188. err1:
  5189. return ret;
  5190. }
  5191. /* Misc internal functions ***************************************************/
  5192. static bool merged(const upb_refcounted *r, const upb_refcounted *r2) {
  5193. return r->group == r2->group;
  5194. }
  5195. static void merge(upb_refcounted *r, upb_refcounted *from) {
  5196. upb_refcounted *base;
  5197. upb_refcounted *tmp;
  5198. if (merged(r, from)) return;
  5199. *r->group += *from->group;
  5200. upb_gfree(from->group);
  5201. base = from;
  5202. /* Set all refcount pointers in the "from" chain to the merged refcount.
  5203. *
  5204. * TODO(haberman): this linear algorithm can result in an overall O(n^2) bound
  5205. * if the user continuously extends a group by one object. Prevent this by
  5206. * using one of the techniques in this paper:
  5207. * http://bioinfo.ict.ac.cn/~dbu/AlgorithmCourses/Lectures/Union-Find-Tarjan.pdf */
  5208. do { from->group = r->group; } while ((from = from->next) != base);
  5209. /* Merge the two circularly linked lists by swapping their next pointers. */
  5210. tmp = r->next;
  5211. r->next = base->next;
  5212. base->next = tmp;
  5213. }
  5214. static void unref(const upb_refcounted *r);
  5215. static void release_ref2(const upb_refcounted *obj,
  5216. const upb_refcounted *subobj,
  5217. void *closure) {
  5218. UPB_UNUSED(closure);
  5219. untrack(subobj, obj, true);
  5220. if (!merged(obj, subobj)) {
  5221. UPB_ASSERT(subobj->is_frozen);
  5222. unref(subobj);
  5223. }
  5224. }
  5225. static void unref(const upb_refcounted *r) {
  5226. if (unrefgroup(r->group)) {
  5227. const upb_refcounted *o;
  5228. upb_gfree(r->group);
  5229. /* In two passes, since release_ref2 needs a guarantee that any subobjs
  5230. * are alive. */
  5231. o = r;
  5232. do { visit(o, release_ref2, NULL); } while((o = o->next) != r);
  5233. o = r;
  5234. do {
  5235. const upb_refcounted *next = o->next;
  5236. UPB_ASSERT(o->is_frozen || o->individual_count == 0);
  5237. freeobj((upb_refcounted*)o);
  5238. o = next;
  5239. } while(o != r);
  5240. }
  5241. }
  5242. static void freeobj(upb_refcounted *o) {
  5243. trackfree(o);
  5244. o->vtbl->free((upb_refcounted*)o);
  5245. }
  5246. /* Public interface ***********************************************************/
  5247. bool upb_refcounted_init(upb_refcounted *r,
  5248. const struct upb_refcounted_vtbl *vtbl,
  5249. const void *owner) {
  5250. #ifndef NDEBUG
  5251. /* Endianness check. This is unrelated to upb_refcounted, it's just a
  5252. * convenient place to put the check that we can be assured will run for
  5253. * basically every program using upb. */
  5254. const int x = 1;
  5255. #ifdef UPB_BIG_ENDIAN
  5256. UPB_ASSERT(*(char*)&x != 1);
  5257. #else
  5258. UPB_ASSERT(*(char*)&x == 1);
  5259. #endif
  5260. #endif
  5261. r->next = r;
  5262. r->vtbl = vtbl;
  5263. r->individual_count = 0;
  5264. r->is_frozen = false;
  5265. r->group = upb_gmalloc(sizeof(*r->group));
  5266. if (!r->group) return false;
  5267. *r->group = 0;
  5268. trackinit(r);
  5269. upb_refcounted_ref(r, owner);
  5270. return true;
  5271. }
  5272. bool upb_refcounted_isfrozen(const upb_refcounted *r) {
  5273. return r->is_frozen;
  5274. }
  5275. void upb_refcounted_ref(const upb_refcounted *r, const void *owner) {
  5276. track(r, owner, false);
  5277. if (!r->is_frozen)
  5278. ((upb_refcounted*)r)->individual_count++;
  5279. refgroup(r->group);
  5280. }
  5281. void upb_refcounted_unref(const upb_refcounted *r, const void *owner) {
  5282. untrack(r, owner, false);
  5283. if (!r->is_frozen)
  5284. ((upb_refcounted*)r)->individual_count--;
  5285. unref(r);
  5286. }
  5287. void upb_refcounted_ref2(const upb_refcounted *r, upb_refcounted *from) {
  5288. UPB_ASSERT(!from->is_frozen); /* Non-const pointer implies this. */
  5289. track(r, from, true);
  5290. if (r->is_frozen) {
  5291. refgroup(r->group);
  5292. } else {
  5293. merge((upb_refcounted*)r, from);
  5294. }
  5295. }
  5296. void upb_refcounted_unref2(const upb_refcounted *r, upb_refcounted *from) {
  5297. UPB_ASSERT(!from->is_frozen); /* Non-const pointer implies this. */
  5298. untrack(r, from, true);
  5299. if (r->is_frozen) {
  5300. unref(r);
  5301. } else {
  5302. UPB_ASSERT(merged(r, from));
  5303. }
  5304. }
  5305. void upb_refcounted_donateref(
  5306. const upb_refcounted *r, const void *from, const void *to) {
  5307. UPB_ASSERT(from != to);
  5308. if (to != NULL)
  5309. upb_refcounted_ref(r, to);
  5310. if (from != NULL)
  5311. upb_refcounted_unref(r, from);
  5312. }
  5313. void upb_refcounted_checkref(const upb_refcounted *r, const void *owner) {
  5314. checkref(r, owner, false);
  5315. }
  5316. bool upb_refcounted_freeze(upb_refcounted *const*roots, int n, upb_status *s,
  5317. int maxdepth) {
  5318. int i;
  5319. bool ret;
  5320. for (i = 0; i < n; i++) {
  5321. UPB_ASSERT(!roots[i]->is_frozen);
  5322. }
  5323. ret = freeze(roots, n, s, maxdepth);
  5324. UPB_ASSERT(!s || ret == upb_ok(s));
  5325. return ret;
  5326. }
  5327. bool upb_bufsrc_putbuf(const char *buf, size_t len, upb_bytessink *sink) {
  5328. void *subc;
  5329. bool ret;
  5330. upb_bufhandle handle;
  5331. upb_bufhandle_init(&handle);
  5332. upb_bufhandle_setbuf(&handle, buf, 0);
  5333. ret = upb_bytessink_start(sink, len, &subc);
  5334. if (ret && len != 0) {
  5335. ret = (upb_bytessink_putbuf(sink, subc, buf, len, &handle) >= len);
  5336. }
  5337. if (ret) {
  5338. ret = upb_bytessink_end(sink);
  5339. }
  5340. upb_bufhandle_uninit(&handle);
  5341. return ret;
  5342. }
  5343. struct upb_bufsink {
  5344. upb_byteshandler handler;
  5345. upb_bytessink sink;
  5346. upb_env *env;
  5347. char *ptr;
  5348. size_t len, size;
  5349. };
  5350. static void *upb_bufsink_start(void *_sink, const void *hd, size_t size_hint) {
  5351. upb_bufsink *sink = _sink;
  5352. UPB_UNUSED(hd);
  5353. UPB_UNUSED(size_hint);
  5354. sink->len = 0;
  5355. return sink;
  5356. }
  5357. static size_t upb_bufsink_string(void *_sink, const void *hd, const char *ptr,
  5358. size_t len, const upb_bufhandle *handle) {
  5359. upb_bufsink *sink = _sink;
  5360. size_t new_size = sink->size;
  5361. UPB_ASSERT(new_size > 0);
  5362. UPB_UNUSED(hd);
  5363. UPB_UNUSED(handle);
  5364. while (sink->len + len > new_size) {
  5365. new_size *= 2;
  5366. }
  5367. if (new_size != sink->size) {
  5368. sink->ptr = upb_env_realloc(sink->env, sink->ptr, sink->size, new_size);
  5369. sink->size = new_size;
  5370. }
  5371. memcpy(sink->ptr + sink->len, ptr, len);
  5372. sink->len += len;
  5373. return len;
  5374. }
  5375. upb_bufsink *upb_bufsink_new(upb_env *env) {
  5376. upb_bufsink *sink = upb_env_malloc(env, sizeof(upb_bufsink));
  5377. upb_byteshandler_init(&sink->handler);
  5378. upb_byteshandler_setstartstr(&sink->handler, upb_bufsink_start, NULL);
  5379. upb_byteshandler_setstring(&sink->handler, upb_bufsink_string, NULL);
  5380. upb_bytessink_reset(&sink->sink, &sink->handler, sink);
  5381. sink->env = env;
  5382. sink->size = 32;
  5383. sink->ptr = upb_env_malloc(env, sink->size);
  5384. sink->len = 0;
  5385. return sink;
  5386. }
  5387. void upb_bufsink_free(upb_bufsink *sink) {
  5388. upb_env_free(sink->env, sink->ptr);
  5389. upb_env_free(sink->env, sink);
  5390. }
  5391. upb_bytessink *upb_bufsink_sink(upb_bufsink *sink) {
  5392. return &sink->sink;
  5393. }
  5394. const char *upb_bufsink_getdata(const upb_bufsink *sink, size_t *len) {
  5395. *len = sink->len;
  5396. return sink->ptr;
  5397. }
  5398. /*
  5399. ** upb_table Implementation
  5400. **
  5401. ** Implementation is heavily inspired by Lua's ltable.c.
  5402. */
  5403. #include <string.h>
  5404. #define UPB_MAXARRSIZE 16 /* 64k. */
  5405. /* From Chromium. */
  5406. #define ARRAY_SIZE(x) \
  5407. ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
  5408. static void upb_check_alloc(upb_table *t, upb_alloc *a) {
  5409. UPB_UNUSED(t);
  5410. UPB_UNUSED(a);
  5411. UPB_ASSERT_DEBUGVAR(t->alloc == a);
  5412. }
  5413. static const double MAX_LOAD = 0.85;
  5414. /* The minimum utilization of the array part of a mixed hash/array table. This
  5415. * is a speed/memory-usage tradeoff (though it's not straightforward because of
  5416. * cache effects). The lower this is, the more memory we'll use. */
  5417. static const double MIN_DENSITY = 0.1;
  5418. bool is_pow2(uint64_t v) { return v == 0 || (v & (v - 1)) == 0; }
  5419. int log2ceil(uint64_t v) {
  5420. int ret = 0;
  5421. bool pow2 = is_pow2(v);
  5422. while (v >>= 1) ret++;
  5423. ret = pow2 ? ret : ret + 1; /* Ceiling. */
  5424. return UPB_MIN(UPB_MAXARRSIZE, ret);
  5425. }
  5426. char *upb_strdup(const char *s, upb_alloc *a) {
  5427. return upb_strdup2(s, strlen(s), a);
  5428. }
  5429. char *upb_strdup2(const char *s, size_t len, upb_alloc *a) {
  5430. size_t n;
  5431. char *p;
  5432. /* Prevent overflow errors. */
  5433. if (len == SIZE_MAX) return NULL;
  5434. /* Always null-terminate, even if binary data; but don't rely on the input to
  5435. * have a null-terminating byte since it may be a raw binary buffer. */
  5436. n = len + 1;
  5437. p = upb_malloc(a, n);
  5438. if (p) {
  5439. memcpy(p, s, len);
  5440. p[len] = 0;
  5441. }
  5442. return p;
  5443. }
  5444. /* A type to represent the lookup key of either a strtable or an inttable. */
  5445. typedef union {
  5446. uintptr_t num;
  5447. struct {
  5448. const char *str;
  5449. size_t len;
  5450. } str;
  5451. } lookupkey_t;
  5452. static lookupkey_t strkey2(const char *str, size_t len) {
  5453. lookupkey_t k;
  5454. k.str.str = str;
  5455. k.str.len = len;
  5456. return k;
  5457. }
  5458. static lookupkey_t intkey(uintptr_t key) {
  5459. lookupkey_t k;
  5460. k.num = key;
  5461. return k;
  5462. }
  5463. typedef uint32_t hashfunc_t(upb_tabkey key);
  5464. typedef bool eqlfunc_t(upb_tabkey k1, lookupkey_t k2);
  5465. /* Base table (shared code) ***************************************************/
  5466. /* For when we need to cast away const. */
  5467. static upb_tabent *mutable_entries(upb_table *t) {
  5468. return (upb_tabent*)t->entries;
  5469. }
  5470. static bool isfull(upb_table *t) {
  5471. if (upb_table_size(t) == 0) {
  5472. return true;
  5473. } else {
  5474. return ((double)(t->count + 1) / upb_table_size(t)) > MAX_LOAD;
  5475. }
  5476. }
  5477. static bool init(upb_table *t, upb_ctype_t ctype, uint8_t size_lg2,
  5478. upb_alloc *a) {
  5479. size_t bytes;
  5480. t->count = 0;
  5481. t->ctype = ctype;
  5482. t->size_lg2 = size_lg2;
  5483. t->mask = upb_table_size(t) ? upb_table_size(t) - 1 : 0;
  5484. #ifndef NDEBUG
  5485. t->alloc = a;
  5486. #endif
  5487. bytes = upb_table_size(t) * sizeof(upb_tabent);
  5488. if (bytes > 0) {
  5489. t->entries = upb_malloc(a, bytes);
  5490. if (!t->entries) return false;
  5491. memset(mutable_entries(t), 0, bytes);
  5492. } else {
  5493. t->entries = NULL;
  5494. }
  5495. return true;
  5496. }
  5497. static void uninit(upb_table *t, upb_alloc *a) {
  5498. upb_check_alloc(t, a);
  5499. upb_free(a, mutable_entries(t));
  5500. }
  5501. static upb_tabent *emptyent(upb_table *t) {
  5502. upb_tabent *e = mutable_entries(t) + upb_table_size(t);
  5503. while (1) { if (upb_tabent_isempty(--e)) return e; UPB_ASSERT(e > t->entries); }
  5504. }
  5505. static upb_tabent *getentry_mutable(upb_table *t, uint32_t hash) {
  5506. return (upb_tabent*)upb_getentry(t, hash);
  5507. }
  5508. static const upb_tabent *findentry(const upb_table *t, lookupkey_t key,
  5509. uint32_t hash, eqlfunc_t *eql) {
  5510. const upb_tabent *e;
  5511. if (t->size_lg2 == 0) return NULL;
  5512. e = upb_getentry(t, hash);
  5513. if (upb_tabent_isempty(e)) return NULL;
  5514. while (1) {
  5515. if (eql(e->key, key)) return e;
  5516. if ((e = e->next) == NULL) return NULL;
  5517. }
  5518. }
  5519. static upb_tabent *findentry_mutable(upb_table *t, lookupkey_t key,
  5520. uint32_t hash, eqlfunc_t *eql) {
  5521. return (upb_tabent*)findentry(t, key, hash, eql);
  5522. }
  5523. static bool lookup(const upb_table *t, lookupkey_t key, upb_value *v,
  5524. uint32_t hash, eqlfunc_t *eql) {
  5525. const upb_tabent *e = findentry(t, key, hash, eql);
  5526. if (e) {
  5527. if (v) {
  5528. _upb_value_setval(v, e->val.val, t->ctype);
  5529. }
  5530. return true;
  5531. } else {
  5532. return false;
  5533. }
  5534. }
  5535. /* The given key must not already exist in the table. */
  5536. static void insert(upb_table *t, lookupkey_t key, upb_tabkey tabkey,
  5537. upb_value val, uint32_t hash,
  5538. hashfunc_t *hashfunc, eqlfunc_t *eql) {
  5539. upb_tabent *mainpos_e;
  5540. upb_tabent *our_e;
  5541. UPB_ASSERT(findentry(t, key, hash, eql) == NULL);
  5542. UPB_ASSERT_DEBUGVAR(val.ctype == t->ctype);
  5543. t->count++;
  5544. mainpos_e = getentry_mutable(t, hash);
  5545. our_e = mainpos_e;
  5546. if (upb_tabent_isempty(mainpos_e)) {
  5547. /* Our main position is empty; use it. */
  5548. our_e->next = NULL;
  5549. } else {
  5550. /* Collision. */
  5551. upb_tabent *new_e = emptyent(t);
  5552. /* Head of collider's chain. */
  5553. upb_tabent *chain = getentry_mutable(t, hashfunc(mainpos_e->key));
  5554. if (chain == mainpos_e) {
  5555. /* Existing ent is in its main posisiton (it has the same hash as us, and
  5556. * is the head of our chain). Insert to new ent and append to this chain. */
  5557. new_e->next = mainpos_e->next;
  5558. mainpos_e->next = new_e;
  5559. our_e = new_e;
  5560. } else {
  5561. /* Existing ent is not in its main position (it is a node in some other
  5562. * chain). This implies that no existing ent in the table has our hash.
  5563. * Evict it (updating its chain) and use its ent for head of our chain. */
  5564. *new_e = *mainpos_e; /* copies next. */
  5565. while (chain->next != mainpos_e) {
  5566. chain = (upb_tabent*)chain->next;
  5567. UPB_ASSERT(chain);
  5568. }
  5569. chain->next = new_e;
  5570. our_e = mainpos_e;
  5571. our_e->next = NULL;
  5572. }
  5573. }
  5574. our_e->key = tabkey;
  5575. our_e->val.val = val.val;
  5576. UPB_ASSERT(findentry(t, key, hash, eql) == our_e);
  5577. }
  5578. static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
  5579. upb_tabkey *removed, uint32_t hash, eqlfunc_t *eql) {
  5580. upb_tabent *chain = getentry_mutable(t, hash);
  5581. if (upb_tabent_isempty(chain)) return false;
  5582. if (eql(chain->key, key)) {
  5583. /* Element to remove is at the head of its chain. */
  5584. t->count--;
  5585. if (val) _upb_value_setval(val, chain->val.val, t->ctype);
  5586. if (removed) *removed = chain->key;
  5587. if (chain->next) {
  5588. upb_tabent *move = (upb_tabent*)chain->next;
  5589. *chain = *move;
  5590. move->key = 0; /* Make the slot empty. */
  5591. } else {
  5592. chain->key = 0; /* Make the slot empty. */
  5593. }
  5594. return true;
  5595. } else {
  5596. /* Element to remove is either in a non-head position or not in the
  5597. * table. */
  5598. while (chain->next && !eql(chain->next->key, key)) {
  5599. chain = (upb_tabent*)chain->next;
  5600. }
  5601. if (chain->next) {
  5602. /* Found element to remove. */
  5603. upb_tabent *rm = (upb_tabent*)chain->next;
  5604. t->count--;
  5605. if (val) _upb_value_setval(val, chain->next->val.val, t->ctype);
  5606. if (removed) *removed = rm->key;
  5607. rm->key = 0; /* Make the slot empty. */
  5608. chain->next = rm->next;
  5609. return true;
  5610. } else {
  5611. /* Element to remove is not in the table. */
  5612. return false;
  5613. }
  5614. }
  5615. }
  5616. static size_t next(const upb_table *t, size_t i) {
  5617. do {
  5618. if (++i >= upb_table_size(t))
  5619. return SIZE_MAX;
  5620. } while(upb_tabent_isempty(&t->entries[i]));
  5621. return i;
  5622. }
  5623. static size_t begin(const upb_table *t) {
  5624. return next(t, -1);
  5625. }
  5626. /* upb_strtable ***************************************************************/
  5627. /* A simple "subclass" of upb_table that only adds a hash function for strings. */
  5628. static upb_tabkey strcopy(lookupkey_t k2, upb_alloc *a) {
  5629. uint32_t len = (uint32_t) k2.str.len;
  5630. char *str = upb_malloc(a, k2.str.len + sizeof(uint32_t) + 1);
  5631. if (str == NULL) return 0;
  5632. memcpy(str, &len, sizeof(uint32_t));
  5633. memcpy(str + sizeof(uint32_t), k2.str.str, k2.str.len + 1);
  5634. return (uintptr_t)str;
  5635. }
  5636. static uint32_t strhash(upb_tabkey key) {
  5637. uint32_t len;
  5638. char *str = upb_tabstr(key, &len);
  5639. return MurmurHash2(str, len, 0);
  5640. }
  5641. static bool streql(upb_tabkey k1, lookupkey_t k2) {
  5642. uint32_t len;
  5643. char *str = upb_tabstr(k1, &len);
  5644. return len == k2.str.len && memcmp(str, k2.str.str, len) == 0;
  5645. }
  5646. bool upb_strtable_init2(upb_strtable *t, upb_ctype_t ctype, upb_alloc *a) {
  5647. return init(&t->t, ctype, 2, a);
  5648. }
  5649. void upb_strtable_uninit2(upb_strtable *t, upb_alloc *a) {
  5650. size_t i;
  5651. for (i = 0; i < upb_table_size(&t->t); i++)
  5652. upb_free(a, (void*)t->t.entries[i].key);
  5653. uninit(&t->t, a);
  5654. }
  5655. bool upb_strtable_resize(upb_strtable *t, size_t size_lg2, upb_alloc *a) {
  5656. upb_strtable new_table;
  5657. upb_strtable_iter i;
  5658. upb_check_alloc(&t->t, a);
  5659. if (!init(&new_table.t, t->t.ctype, size_lg2, a))
  5660. return false;
  5661. upb_strtable_begin(&i, t);
  5662. for ( ; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  5663. upb_strtable_insert3(
  5664. &new_table,
  5665. upb_strtable_iter_key(&i),
  5666. upb_strtable_iter_keylength(&i),
  5667. upb_strtable_iter_value(&i),
  5668. a);
  5669. }
  5670. upb_strtable_uninit2(t, a);
  5671. *t = new_table;
  5672. return true;
  5673. }
  5674. bool upb_strtable_insert3(upb_strtable *t, const char *k, size_t len,
  5675. upb_value v, upb_alloc *a) {
  5676. lookupkey_t key;
  5677. upb_tabkey tabkey;
  5678. uint32_t hash;
  5679. upb_check_alloc(&t->t, a);
  5680. if (isfull(&t->t)) {
  5681. /* Need to resize. New table of double the size, add old elements to it. */
  5682. if (!upb_strtable_resize(t, t->t.size_lg2 + 1, a)) {
  5683. return false;
  5684. }
  5685. }
  5686. key = strkey2(k, len);
  5687. tabkey = strcopy(key, a);
  5688. if (tabkey == 0) return false;
  5689. hash = MurmurHash2(key.str.str, key.str.len, 0);
  5690. insert(&t->t, key, tabkey, v, hash, &strhash, &streql);
  5691. return true;
  5692. }
  5693. bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
  5694. upb_value *v) {
  5695. uint32_t hash = MurmurHash2(key, len, 0);
  5696. return lookup(&t->t, strkey2(key, len), v, hash, &streql);
  5697. }
  5698. bool upb_strtable_remove3(upb_strtable *t, const char *key, size_t len,
  5699. upb_value *val, upb_alloc *alloc) {
  5700. uint32_t hash = MurmurHash2(key, len, 0);
  5701. upb_tabkey tabkey;
  5702. if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
  5703. upb_free(alloc, (void*)tabkey);
  5704. return true;
  5705. } else {
  5706. return false;
  5707. }
  5708. }
  5709. /* Iteration */
  5710. static const upb_tabent *str_tabent(const upb_strtable_iter *i) {
  5711. return &i->t->t.entries[i->index];
  5712. }
  5713. void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t) {
  5714. i->t = t;
  5715. i->index = begin(&t->t);
  5716. }
  5717. void upb_strtable_next(upb_strtable_iter *i) {
  5718. i->index = next(&i->t->t, i->index);
  5719. }
  5720. bool upb_strtable_done(const upb_strtable_iter *i) {
  5721. return i->index >= upb_table_size(&i->t->t) ||
  5722. upb_tabent_isempty(str_tabent(i));
  5723. }
  5724. const char *upb_strtable_iter_key(const upb_strtable_iter *i) {
  5725. UPB_ASSERT(!upb_strtable_done(i));
  5726. return upb_tabstr(str_tabent(i)->key, NULL);
  5727. }
  5728. size_t upb_strtable_iter_keylength(const upb_strtable_iter *i) {
  5729. uint32_t len;
  5730. UPB_ASSERT(!upb_strtable_done(i));
  5731. upb_tabstr(str_tabent(i)->key, &len);
  5732. return len;
  5733. }
  5734. upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
  5735. UPB_ASSERT(!upb_strtable_done(i));
  5736. return _upb_value_val(str_tabent(i)->val.val, i->t->t.ctype);
  5737. }
  5738. void upb_strtable_iter_setdone(upb_strtable_iter *i) {
  5739. i->index = SIZE_MAX;
  5740. }
  5741. bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
  5742. const upb_strtable_iter *i2) {
  5743. if (upb_strtable_done(i1) && upb_strtable_done(i2))
  5744. return true;
  5745. return i1->t == i2->t && i1->index == i2->index;
  5746. }
  5747. /* upb_inttable ***************************************************************/
  5748. /* For inttables we use a hybrid structure where small keys are kept in an
  5749. * array and large keys are put in the hash table. */
  5750. static uint32_t inthash(upb_tabkey key) { return upb_inthash(key); }
  5751. static bool inteql(upb_tabkey k1, lookupkey_t k2) {
  5752. return k1 == k2.num;
  5753. }
  5754. static upb_tabval *mutable_array(upb_inttable *t) {
  5755. return (upb_tabval*)t->array;
  5756. }
  5757. static upb_tabval *inttable_val(upb_inttable *t, uintptr_t key) {
  5758. if (key < t->array_size) {
  5759. return upb_arrhas(t->array[key]) ? &(mutable_array(t)[key]) : NULL;
  5760. } else {
  5761. upb_tabent *e =
  5762. findentry_mutable(&t->t, intkey(key), upb_inthash(key), &inteql);
  5763. return e ? &e->val : NULL;
  5764. }
  5765. }
  5766. static const upb_tabval *inttable_val_const(const upb_inttable *t,
  5767. uintptr_t key) {
  5768. return inttable_val((upb_inttable*)t, key);
  5769. }
  5770. size_t upb_inttable_count(const upb_inttable *t) {
  5771. return t->t.count + t->array_count;
  5772. }
  5773. static void check(upb_inttable *t) {
  5774. UPB_UNUSED(t);
  5775. #if defined(UPB_DEBUG_TABLE) && !defined(NDEBUG)
  5776. {
  5777. /* This check is very expensive (makes inserts/deletes O(N)). */
  5778. size_t count = 0;
  5779. upb_inttable_iter i;
  5780. upb_inttable_begin(&i, t);
  5781. for(; !upb_inttable_done(&i); upb_inttable_next(&i), count++) {
  5782. UPB_ASSERT(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
  5783. }
  5784. UPB_ASSERT(count == upb_inttable_count(t));
  5785. }
  5786. #endif
  5787. }
  5788. bool upb_inttable_sizedinit(upb_inttable *t, upb_ctype_t ctype,
  5789. size_t asize, int hsize_lg2, upb_alloc *a) {
  5790. size_t array_bytes;
  5791. if (!init(&t->t, ctype, hsize_lg2, a)) return false;
  5792. /* Always make the array part at least 1 long, so that we know key 0
  5793. * won't be in the hash part, which simplifies things. */
  5794. t->array_size = UPB_MAX(1, asize);
  5795. t->array_count = 0;
  5796. array_bytes = t->array_size * sizeof(upb_value);
  5797. t->array = upb_malloc(a, array_bytes);
  5798. if (!t->array) {
  5799. uninit(&t->t, a);
  5800. return false;
  5801. }
  5802. memset(mutable_array(t), 0xff, array_bytes);
  5803. check(t);
  5804. return true;
  5805. }
  5806. bool upb_inttable_init2(upb_inttable *t, upb_ctype_t ctype, upb_alloc *a) {
  5807. return upb_inttable_sizedinit(t, ctype, 0, 4, a);
  5808. }
  5809. void upb_inttable_uninit2(upb_inttable *t, upb_alloc *a) {
  5810. uninit(&t->t, a);
  5811. upb_free(a, mutable_array(t));
  5812. }
  5813. bool upb_inttable_insert2(upb_inttable *t, uintptr_t key, upb_value val,
  5814. upb_alloc *a) {
  5815. upb_tabval tabval;
  5816. tabval.val = val.val;
  5817. UPB_ASSERT(upb_arrhas(tabval)); /* This will reject (uint64_t)-1. Fix this. */
  5818. upb_check_alloc(&t->t, a);
  5819. if (key < t->array_size) {
  5820. UPB_ASSERT(!upb_arrhas(t->array[key]));
  5821. t->array_count++;
  5822. mutable_array(t)[key].val = val.val;
  5823. } else {
  5824. if (isfull(&t->t)) {
  5825. /* Need to resize the hash part, but we re-use the array part. */
  5826. size_t i;
  5827. upb_table new_table;
  5828. if (!init(&new_table, t->t.ctype, t->t.size_lg2 + 1, a)) {
  5829. return false;
  5830. }
  5831. for (i = begin(&t->t); i < upb_table_size(&t->t); i = next(&t->t, i)) {
  5832. const upb_tabent *e = &t->t.entries[i];
  5833. uint32_t hash;
  5834. upb_value v;
  5835. _upb_value_setval(&v, e->val.val, t->t.ctype);
  5836. hash = upb_inthash(e->key);
  5837. insert(&new_table, intkey(e->key), e->key, v, hash, &inthash, &inteql);
  5838. }
  5839. UPB_ASSERT(t->t.count == new_table.count);
  5840. uninit(&t->t, a);
  5841. t->t = new_table;
  5842. }
  5843. insert(&t->t, intkey(key), key, val, upb_inthash(key), &inthash, &inteql);
  5844. }
  5845. check(t);
  5846. return true;
  5847. }
  5848. bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v) {
  5849. const upb_tabval *table_v = inttable_val_const(t, key);
  5850. if (!table_v) return false;
  5851. if (v) _upb_value_setval(v, table_v->val, t->t.ctype);
  5852. return true;
  5853. }
  5854. bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val) {
  5855. upb_tabval *table_v = inttable_val(t, key);
  5856. if (!table_v) return false;
  5857. table_v->val = val.val;
  5858. return true;
  5859. }
  5860. bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val) {
  5861. bool success;
  5862. if (key < t->array_size) {
  5863. if (upb_arrhas(t->array[key])) {
  5864. upb_tabval empty = UPB_TABVALUE_EMPTY_INIT;
  5865. t->array_count--;
  5866. if (val) {
  5867. _upb_value_setval(val, t->array[key].val, t->t.ctype);
  5868. }
  5869. mutable_array(t)[key] = empty;
  5870. success = true;
  5871. } else {
  5872. success = false;
  5873. }
  5874. } else {
  5875. success = rm(&t->t, intkey(key), val, NULL, upb_inthash(key), &inteql);
  5876. }
  5877. check(t);
  5878. return success;
  5879. }
  5880. bool upb_inttable_push2(upb_inttable *t, upb_value val, upb_alloc *a) {
  5881. upb_check_alloc(&t->t, a);
  5882. return upb_inttable_insert2(t, upb_inttable_count(t), val, a);
  5883. }
  5884. upb_value upb_inttable_pop(upb_inttable *t) {
  5885. upb_value val;
  5886. bool ok = upb_inttable_remove(t, upb_inttable_count(t) - 1, &val);
  5887. UPB_ASSERT(ok);
  5888. return val;
  5889. }
  5890. bool upb_inttable_insertptr2(upb_inttable *t, const void *key, upb_value val,
  5891. upb_alloc *a) {
  5892. upb_check_alloc(&t->t, a);
  5893. return upb_inttable_insert2(t, (uintptr_t)key, val, a);
  5894. }
  5895. bool upb_inttable_lookupptr(const upb_inttable *t, const void *key,
  5896. upb_value *v) {
  5897. return upb_inttable_lookup(t, (uintptr_t)key, v);
  5898. }
  5899. bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val) {
  5900. return upb_inttable_remove(t, (uintptr_t)key, val);
  5901. }
  5902. void upb_inttable_compact2(upb_inttable *t, upb_alloc *a) {
  5903. /* A power-of-two histogram of the table keys. */
  5904. size_t counts[UPB_MAXARRSIZE + 1] = {0};
  5905. /* The max key in each bucket. */
  5906. uintptr_t max[UPB_MAXARRSIZE + 1] = {0};
  5907. upb_inttable_iter i;
  5908. size_t arr_count;
  5909. int size_lg2;
  5910. upb_inttable new_t;
  5911. upb_check_alloc(&t->t, a);
  5912. upb_inttable_begin(&i, t);
  5913. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5914. uintptr_t key = upb_inttable_iter_key(&i);
  5915. int bucket = log2ceil(key);
  5916. max[bucket] = UPB_MAX(max[bucket], key);
  5917. counts[bucket]++;
  5918. }
  5919. /* Find the largest power of two that satisfies the MIN_DENSITY
  5920. * definition (while actually having some keys). */
  5921. arr_count = upb_inttable_count(t);
  5922. for (size_lg2 = ARRAY_SIZE(counts) - 1; size_lg2 > 0; size_lg2--) {
  5923. if (counts[size_lg2] == 0) {
  5924. /* We can halve again without losing any entries. */
  5925. continue;
  5926. } else if (arr_count >= (1 << size_lg2) * MIN_DENSITY) {
  5927. break;
  5928. }
  5929. arr_count -= counts[size_lg2];
  5930. }
  5931. UPB_ASSERT(arr_count <= upb_inttable_count(t));
  5932. {
  5933. /* Insert all elements into new, perfectly-sized table. */
  5934. size_t arr_size = max[size_lg2] + 1; /* +1 so arr[max] will fit. */
  5935. size_t hash_count = upb_inttable_count(t) - arr_count;
  5936. size_t hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
  5937. size_t hashsize_lg2 = log2ceil(hash_size);
  5938. upb_inttable_sizedinit(&new_t, t->t.ctype, arr_size, hashsize_lg2, a);
  5939. upb_inttable_begin(&i, t);
  5940. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5941. uintptr_t k = upb_inttable_iter_key(&i);
  5942. upb_inttable_insert2(&new_t, k, upb_inttable_iter_value(&i), a);
  5943. }
  5944. UPB_ASSERT(new_t.array_size == arr_size);
  5945. UPB_ASSERT(new_t.t.size_lg2 == hashsize_lg2);
  5946. }
  5947. upb_inttable_uninit2(t, a);
  5948. *t = new_t;
  5949. }
  5950. /* Iteration. */
  5951. static const upb_tabent *int_tabent(const upb_inttable_iter *i) {
  5952. UPB_ASSERT(!i->array_part);
  5953. return &i->t->t.entries[i->index];
  5954. }
  5955. static upb_tabval int_arrent(const upb_inttable_iter *i) {
  5956. UPB_ASSERT(i->array_part);
  5957. return i->t->array[i->index];
  5958. }
  5959. void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t) {
  5960. i->t = t;
  5961. i->index = -1;
  5962. i->array_part = true;
  5963. upb_inttable_next(i);
  5964. }
  5965. void upb_inttable_next(upb_inttable_iter *iter) {
  5966. const upb_inttable *t = iter->t;
  5967. if (iter->array_part) {
  5968. while (++iter->index < t->array_size) {
  5969. if (upb_arrhas(int_arrent(iter))) {
  5970. return;
  5971. }
  5972. }
  5973. iter->array_part = false;
  5974. iter->index = begin(&t->t);
  5975. } else {
  5976. iter->index = next(&t->t, iter->index);
  5977. }
  5978. }
  5979. bool upb_inttable_done(const upb_inttable_iter *i) {
  5980. if (i->array_part) {
  5981. return i->index >= i->t->array_size ||
  5982. !upb_arrhas(int_arrent(i));
  5983. } else {
  5984. return i->index >= upb_table_size(&i->t->t) ||
  5985. upb_tabent_isempty(int_tabent(i));
  5986. }
  5987. }
  5988. uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i) {
  5989. UPB_ASSERT(!upb_inttable_done(i));
  5990. return i->array_part ? i->index : int_tabent(i)->key;
  5991. }
  5992. upb_value upb_inttable_iter_value(const upb_inttable_iter *i) {
  5993. UPB_ASSERT(!upb_inttable_done(i));
  5994. return _upb_value_val(
  5995. i->array_part ? i->t->array[i->index].val : int_tabent(i)->val.val,
  5996. i->t->t.ctype);
  5997. }
  5998. void upb_inttable_iter_setdone(upb_inttable_iter *i) {
  5999. i->index = SIZE_MAX;
  6000. i->array_part = false;
  6001. }
  6002. bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
  6003. const upb_inttable_iter *i2) {
  6004. if (upb_inttable_done(i1) && upb_inttable_done(i2))
  6005. return true;
  6006. return i1->t == i2->t && i1->index == i2->index &&
  6007. i1->array_part == i2->array_part;
  6008. }
  6009. #ifdef UPB_UNALIGNED_READS_OK
  6010. /* -----------------------------------------------------------------------------
  6011. * MurmurHash2, by Austin Appleby (released as public domain).
  6012. * Reformatted and C99-ified by Joshua Haberman.
  6013. * Note - This code makes a few assumptions about how your machine behaves -
  6014. * 1. We can read a 4-byte value from any address without crashing
  6015. * 2. sizeof(int) == 4 (in upb this limitation is removed by using uint32_t
  6016. * And it has a few limitations -
  6017. * 1. It will not work incrementally.
  6018. * 2. It will not produce the same results on little-endian and big-endian
  6019. * machines. */
  6020. uint32_t MurmurHash2(const void *key, size_t len, uint32_t seed) {
  6021. /* 'm' and 'r' are mixing constants generated offline.
  6022. * They're not really 'magic', they just happen to work well. */
  6023. const uint32_t m = 0x5bd1e995;
  6024. const int32_t r = 24;
  6025. /* Initialize the hash to a 'random' value */
  6026. uint32_t h = seed ^ len;
  6027. /* Mix 4 bytes at a time into the hash */
  6028. const uint8_t * data = (const uint8_t *)key;
  6029. while(len >= 4) {
  6030. uint32_t k = *(uint32_t *)data;
  6031. k *= m;
  6032. k ^= k >> r;
  6033. k *= m;
  6034. h *= m;
  6035. h ^= k;
  6036. data += 4;
  6037. len -= 4;
  6038. }
  6039. /* Handle the last few bytes of the input array */
  6040. switch(len) {
  6041. case 3: h ^= data[2] << 16;
  6042. case 2: h ^= data[1] << 8;
  6043. case 1: h ^= data[0]; h *= m;
  6044. };
  6045. /* Do a few final mixes of the hash to ensure the last few
  6046. * bytes are well-incorporated. */
  6047. h ^= h >> 13;
  6048. h *= m;
  6049. h ^= h >> 15;
  6050. return h;
  6051. }
  6052. #else /* !UPB_UNALIGNED_READS_OK */
  6053. /* -----------------------------------------------------------------------------
  6054. * MurmurHashAligned2, by Austin Appleby
  6055. * Same algorithm as MurmurHash2, but only does aligned reads - should be safer
  6056. * on certain platforms.
  6057. * Performance will be lower than MurmurHash2 */
  6058. #define MIX(h,k,m) { k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; }
  6059. uint32_t MurmurHash2(const void * key, size_t len, uint32_t seed) {
  6060. const uint32_t m = 0x5bd1e995;
  6061. const int32_t r = 24;
  6062. const uint8_t * data = (const uint8_t *)key;
  6063. uint32_t h = seed ^ len;
  6064. uint8_t align = (uintptr_t)data & 3;
  6065. if(align && (len >= 4)) {
  6066. /* Pre-load the temp registers */
  6067. uint32_t t = 0, d = 0;
  6068. int32_t sl;
  6069. int32_t sr;
  6070. switch(align) {
  6071. case 1: t |= data[2] << 16;
  6072. case 2: t |= data[1] << 8;
  6073. case 3: t |= data[0];
  6074. }
  6075. t <<= (8 * align);
  6076. data += 4-align;
  6077. len -= 4-align;
  6078. sl = 8 * (4-align);
  6079. sr = 8 * align;
  6080. /* Mix */
  6081. while(len >= 4) {
  6082. uint32_t k;
  6083. d = *(uint32_t *)data;
  6084. t = (t >> sr) | (d << sl);
  6085. k = t;
  6086. MIX(h,k,m);
  6087. t = d;
  6088. data += 4;
  6089. len -= 4;
  6090. }
  6091. /* Handle leftover data in temp registers */
  6092. d = 0;
  6093. if(len >= align) {
  6094. uint32_t k;
  6095. switch(align) {
  6096. case 3: d |= data[2] << 16;
  6097. case 2: d |= data[1] << 8;
  6098. case 1: d |= data[0];
  6099. }
  6100. k = (t >> sr) | (d << sl);
  6101. MIX(h,k,m);
  6102. data += align;
  6103. len -= align;
  6104. /* ----------
  6105. * Handle tail bytes */
  6106. switch(len) {
  6107. case 3: h ^= data[2] << 16;
  6108. case 2: h ^= data[1] << 8;
  6109. case 1: h ^= data[0]; h *= m;
  6110. };
  6111. } else {
  6112. switch(len) {
  6113. case 3: d |= data[2] << 16;
  6114. case 2: d |= data[1] << 8;
  6115. case 1: d |= data[0];
  6116. case 0: h ^= (t >> sr) | (d << sl); h *= m;
  6117. }
  6118. }
  6119. h ^= h >> 13;
  6120. h *= m;
  6121. h ^= h >> 15;
  6122. return h;
  6123. } else {
  6124. while(len >= 4) {
  6125. uint32_t k = *(uint32_t *)data;
  6126. MIX(h,k,m);
  6127. data += 4;
  6128. len -= 4;
  6129. }
  6130. /* ----------
  6131. * Handle tail bytes */
  6132. switch(len) {
  6133. case 3: h ^= data[2] << 16;
  6134. case 2: h ^= data[1] << 8;
  6135. case 1: h ^= data[0]; h *= m;
  6136. };
  6137. h ^= h >> 13;
  6138. h *= m;
  6139. h ^= h >> 15;
  6140. return h;
  6141. }
  6142. }
  6143. #undef MIX
  6144. #endif /* UPB_UNALIGNED_READS_OK */
  6145. #include <errno.h>
  6146. #include <stdarg.h>
  6147. #include <stddef.h>
  6148. #include <stdint.h>
  6149. #include <stdio.h>
  6150. #include <stdlib.h>
  6151. #include <string.h>
  6152. bool upb_dumptostderr(void *closure, const upb_status* status) {
  6153. UPB_UNUSED(closure);
  6154. fprintf(stderr, "%s\n", upb_status_errmsg(status));
  6155. return false;
  6156. }
  6157. /* Guarantee null-termination and provide ellipsis truncation.
  6158. * It may be tempting to "optimize" this by initializing these final
  6159. * four bytes up-front and then being careful never to overwrite them,
  6160. * this is safer and simpler. */
  6161. static void nullz(upb_status *status) {
  6162. const char *ellipsis = "...";
  6163. size_t len = strlen(ellipsis);
  6164. UPB_ASSERT(sizeof(status->msg) > len);
  6165. memcpy(status->msg + sizeof(status->msg) - len, ellipsis, len);
  6166. }
  6167. /* upb_upberr *****************************************************************/
  6168. upb_errorspace upb_upberr = {"upb error"};
  6169. void upb_upberr_setoom(upb_status *status) {
  6170. status->error_space_ = &upb_upberr;
  6171. upb_status_seterrmsg(status, "Out of memory");
  6172. }
  6173. /* upb_status *****************************************************************/
  6174. void upb_status_clear(upb_status *status) {
  6175. if (!status) return;
  6176. status->ok_ = true;
  6177. status->code_ = 0;
  6178. status->msg[0] = '\0';
  6179. }
  6180. bool upb_ok(const upb_status *status) { return status->ok_; }
  6181. upb_errorspace *upb_status_errspace(const upb_status *status) {
  6182. return status->error_space_;
  6183. }
  6184. int upb_status_errcode(const upb_status *status) { return status->code_; }
  6185. const char *upb_status_errmsg(const upb_status *status) { return status->msg; }
  6186. void upb_status_seterrmsg(upb_status *status, const char *msg) {
  6187. if (!status) return;
  6188. status->ok_ = false;
  6189. strncpy(status->msg, msg, sizeof(status->msg));
  6190. nullz(status);
  6191. }
  6192. void upb_status_seterrf(upb_status *status, const char *fmt, ...) {
  6193. va_list args;
  6194. va_start(args, fmt);
  6195. upb_status_vseterrf(status, fmt, args);
  6196. va_end(args);
  6197. }
  6198. void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args) {
  6199. if (!status) return;
  6200. status->ok_ = false;
  6201. _upb_vsnprintf(status->msg, sizeof(status->msg), fmt, args);
  6202. nullz(status);
  6203. }
  6204. void upb_status_copy(upb_status *to, const upb_status *from) {
  6205. if (!to) return;
  6206. *to = *from;
  6207. }
  6208. /* upb_alloc ******************************************************************/
  6209. static void *upb_global_allocfunc(upb_alloc *alloc, void *ptr, size_t oldsize,
  6210. size_t size) {
  6211. UPB_UNUSED(alloc);
  6212. UPB_UNUSED(oldsize);
  6213. if (size == 0) {
  6214. free(ptr);
  6215. return NULL;
  6216. } else {
  6217. return realloc(ptr, size);
  6218. }
  6219. }
  6220. upb_alloc upb_alloc_global = {&upb_global_allocfunc};
  6221. /* upb_arena ******************************************************************/
  6222. /* Be conservative and choose 16 in case anyone is using SSE. */
  6223. static const size_t maxalign = 16;
  6224. static size_t align_up_max(size_t size) {
  6225. return ((size + maxalign - 1) / maxalign) * maxalign;
  6226. }
  6227. typedef struct mem_block {
  6228. struct mem_block *next;
  6229. size_t size;
  6230. size_t used;
  6231. bool owned;
  6232. /* Data follows. */
  6233. } mem_block;
  6234. typedef struct cleanup_ent {
  6235. struct cleanup_ent *next;
  6236. upb_cleanup_func *cleanup;
  6237. void *ud;
  6238. } cleanup_ent;
  6239. static void upb_arena_addblock(upb_arena *a, void *ptr, size_t size,
  6240. bool owned) {
  6241. mem_block *block = ptr;
  6242. block->next = a->block_head;
  6243. block->size = size;
  6244. block->used = align_up_max(sizeof(mem_block));
  6245. block->owned = owned;
  6246. a->block_head = block;
  6247. /* TODO(haberman): ASAN poison. */
  6248. }
  6249. static mem_block *upb_arena_allocblock(upb_arena *a, size_t size) {
  6250. size_t block_size = UPB_MAX(size, a->next_block_size) + sizeof(mem_block);
  6251. mem_block *block = upb_malloc(a->block_alloc, block_size);
  6252. if (!block) {
  6253. return NULL;
  6254. }
  6255. upb_arena_addblock(a, block, block_size, true);
  6256. a->next_block_size = UPB_MIN(block_size * 2, a->max_block_size);
  6257. return block;
  6258. }
  6259. static void *upb_arena_doalloc(upb_alloc *alloc, void *ptr, size_t oldsize,
  6260. size_t size) {
  6261. upb_arena *a = (upb_arena*)alloc; /* upb_alloc is initial member. */
  6262. mem_block *block = a->block_head;
  6263. void *ret;
  6264. if (size == 0) {
  6265. return NULL; /* We are an arena, don't need individual frees. */
  6266. }
  6267. size = align_up_max(size);
  6268. /* TODO(haberman): special-case if this is a realloc of the last alloc? */
  6269. if (!block || block->size - block->used < size) {
  6270. /* Slow path: have to allocate a new block. */
  6271. block = upb_arena_allocblock(a, size);
  6272. if (!block) {
  6273. return NULL; /* Out of memory. */
  6274. }
  6275. }
  6276. ret = (char*)block + block->used;
  6277. block->used += size;
  6278. if (oldsize > 0) {
  6279. memcpy(ret, ptr, oldsize); /* Preserve existing data. */
  6280. }
  6281. /* TODO(haberman): ASAN unpoison. */
  6282. a->bytes_allocated += size;
  6283. return ret;
  6284. }
  6285. /* Public Arena API ***********************************************************/
  6286. void upb_arena_init(upb_arena *a) {
  6287. a->alloc.func = &upb_arena_doalloc;
  6288. a->block_alloc = &upb_alloc_global;
  6289. a->bytes_allocated = 0;
  6290. a->next_block_size = 256;
  6291. a->max_block_size = 16384;
  6292. a->cleanup_head = NULL;
  6293. a->block_head = NULL;
  6294. }
  6295. void upb_arena_init2(upb_arena *a, void *mem, size_t size, upb_alloc *alloc) {
  6296. upb_arena_init(a);
  6297. if (size > sizeof(mem_block)) {
  6298. upb_arena_addblock(a, mem, size, false);
  6299. }
  6300. if (alloc) {
  6301. a->block_alloc = alloc;
  6302. }
  6303. }
  6304. void upb_arena_uninit(upb_arena *a) {
  6305. cleanup_ent *ent = a->cleanup_head;
  6306. mem_block *block = a->block_head;
  6307. while (ent) {
  6308. ent->cleanup(ent->ud);
  6309. ent = ent->next;
  6310. }
  6311. /* Must do this after running cleanup functions, because this will delete
  6312. * the memory we store our cleanup entries in! */
  6313. while (block) {
  6314. mem_block *next = block->next;
  6315. if (block->owned) {
  6316. upb_free(a->block_alloc, block);
  6317. }
  6318. block = next;
  6319. }
  6320. /* Protect against multiple-uninit. */
  6321. a->cleanup_head = NULL;
  6322. a->block_head = NULL;
  6323. }
  6324. bool upb_arena_addcleanup(upb_arena *a, upb_cleanup_func *func, void *ud) {
  6325. cleanup_ent *ent = upb_malloc(&a->alloc, sizeof(cleanup_ent));
  6326. if (!ent) {
  6327. return false; /* Out of memory. */
  6328. }
  6329. ent->cleanup = func;
  6330. ent->ud = ud;
  6331. ent->next = a->cleanup_head;
  6332. a->cleanup_head = ent;
  6333. return true;
  6334. }
  6335. size_t upb_arena_bytesallocated(const upb_arena *a) {
  6336. return a->bytes_allocated;
  6337. }
  6338. /* Standard error functions ***************************************************/
  6339. static bool default_err(void *ud, const upb_status *status) {
  6340. UPB_UNUSED(ud);
  6341. UPB_UNUSED(status);
  6342. return false;
  6343. }
  6344. static bool write_err_to(void *ud, const upb_status *status) {
  6345. upb_status *copy_to = ud;
  6346. upb_status_copy(copy_to, status);
  6347. return false;
  6348. }
  6349. /* upb_env ********************************************************************/
  6350. void upb_env_initonly(upb_env *e) {
  6351. e->ok_ = true;
  6352. e->error_func_ = &default_err;
  6353. e->error_ud_ = NULL;
  6354. }
  6355. void upb_env_init(upb_env *e) {
  6356. upb_arena_init(&e->arena_);
  6357. upb_env_initonly(e);
  6358. }
  6359. void upb_env_init2(upb_env *e, void *mem, size_t n, upb_alloc *alloc) {
  6360. upb_arena_init2(&e->arena_, mem, n, alloc);
  6361. upb_env_initonly(e);
  6362. }
  6363. void upb_env_uninit(upb_env *e) {
  6364. upb_arena_uninit(&e->arena_);
  6365. }
  6366. void upb_env_seterrorfunc(upb_env *e, upb_error_func *func, void *ud) {
  6367. e->error_func_ = func;
  6368. e->error_ud_ = ud;
  6369. }
  6370. void upb_env_reporterrorsto(upb_env *e, upb_status *s) {
  6371. e->error_func_ = &write_err_to;
  6372. e->error_ud_ = s;
  6373. }
  6374. bool upb_env_reporterror(upb_env *e, const upb_status *status) {
  6375. e->ok_ = false;
  6376. return e->error_func_(e->error_ud_, status);
  6377. }
  6378. void *upb_env_malloc(upb_env *e, size_t size) {
  6379. return upb_malloc(&e->arena_.alloc, size);
  6380. }
  6381. void *upb_env_realloc(upb_env *e, void *ptr, size_t oldsize, size_t size) {
  6382. return upb_realloc(&e->arena_.alloc, ptr, oldsize, size);
  6383. }
  6384. void upb_env_free(upb_env *e, void *ptr) {
  6385. upb_free(&e->arena_.alloc, ptr);
  6386. }
  6387. bool upb_env_addcleanup(upb_env *e, upb_cleanup_func *func, void *ud) {
  6388. return upb_arena_addcleanup(&e->arena_, func, ud);
  6389. }
  6390. size_t upb_env_bytesallocated(const upb_env *e) {
  6391. return upb_arena_bytesallocated(&e->arena_);
  6392. }
  6393. /* This file was generated by upbc (the upb compiler) from the input
  6394. * file:
  6395. *
  6396. * upb/descriptor/descriptor.proto
  6397. *
  6398. * Do not edit -- your changes will be discarded when the file is
  6399. * regenerated. */
  6400. static const upb_msgdef msgs[22];
  6401. static const upb_fielddef fields[107];
  6402. static const upb_enumdef enums[5];
  6403. static const upb_tabent strentries[236];
  6404. static const upb_tabent intentries[18];
  6405. static const upb_tabval arrays[187];
  6406. #ifdef UPB_DEBUG_REFS
  6407. static upb_inttable reftables[268];
  6408. #endif
  6409. static const upb_msgdef msgs[22] = {
  6410. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto", 41, 8, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[0], 11, 10), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[0]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[0], &reftables[1]),
  6411. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ExtensionRange", 5, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[11], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[16]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[2], &reftables[3]),
  6412. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ReservedRange", 5, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[14], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[20]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[4], &reftables[5]),
  6413. UPB_MSGDEF_INIT("google.protobuf.EnumDescriptorProto", 12, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[17], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[24]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[6], &reftables[7]),
  6414. UPB_MSGDEF_INIT("google.protobuf.EnumOptions", 9, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[0], &arrays[21], 4, 2), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[28]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[8], &reftables[9]),
  6415. UPB_MSGDEF_INIT("google.protobuf.EnumValueDescriptorProto", 9, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[25], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[32]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[10], &reftables[11]),
  6416. UPB_MSGDEF_INIT("google.protobuf.EnumValueOptions", 8, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[2], &arrays[29], 2, 1), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[36]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[12], &reftables[13]),
  6417. UPB_MSGDEF_INIT("google.protobuf.FieldDescriptorProto", 24, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[31], 11, 10), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[40]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[14], &reftables[15]),
  6418. UPB_MSGDEF_INIT("google.protobuf.FieldOptions", 13, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[4], &arrays[42], 11, 6), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[56]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[16], &reftables[17]),
  6419. UPB_MSGDEF_INIT("google.protobuf.FileDescriptorProto", 43, 6, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[53], 13, 12), UPB_STRTABLE_INIT(12, 15, UPB_CTYPE_PTR, 4, &strentries[72]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[18], &reftables[19]),
  6420. UPB_MSGDEF_INIT("google.protobuf.FileDescriptorSet", 7, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[66], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[88]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[20], &reftables[21]),
  6421. UPB_MSGDEF_INIT("google.protobuf.FileOptions", 38, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[6], &arrays[68], 42, 17), UPB_STRTABLE_INIT(18, 31, UPB_CTYPE_PTR, 5, &strentries[92]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[22], &reftables[23]),
  6422. UPB_MSGDEF_INIT("google.protobuf.MessageOptions", 11, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[8], &arrays[110], 8, 4), UPB_STRTABLE_INIT(5, 7, UPB_CTYPE_PTR, 3, &strentries[124]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[24], &reftables[25]),
  6423. UPB_MSGDEF_INIT("google.protobuf.MethodDescriptorProto", 16, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[118], 7, 6), UPB_STRTABLE_INIT(6, 7, UPB_CTYPE_PTR, 3, &strentries[132]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[26], &reftables[27]),
  6424. UPB_MSGDEF_INIT("google.protobuf.MethodOptions", 8, 1, UPB_INTTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &intentries[10], &arrays[125], 1, 0), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[140]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[28], &reftables[29]),
  6425. UPB_MSGDEF_INIT("google.protobuf.OneofDescriptorProto", 6, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[126], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[144]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[30], &reftables[31]),
  6426. UPB_MSGDEF_INIT("google.protobuf.ServiceDescriptorProto", 12, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[128], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[148]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[32], &reftables[33]),
  6427. UPB_MSGDEF_INIT("google.protobuf.ServiceOptions", 8, 1, UPB_INTTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &intentries[14], &arrays[132], 1, 0), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[152]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[34], &reftables[35]),
  6428. UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo", 7, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[133], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[156]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[36], &reftables[37]),
  6429. UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo.Location", 20, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[135], 7, 5), UPB_STRTABLE_INIT(5, 7, UPB_CTYPE_PTR, 3, &strentries[160]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[38], &reftables[39]),
  6430. UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption", 19, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[142], 9, 7), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[168]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[40], &reftables[41]),
  6431. UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption.NamePart", 7, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[151], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[184]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[42], &reftables[43]),
  6432. };
  6433. static const upb_fielddef fields[107] = {
  6434. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "aggregate_value", 8, &msgs[20], NULL, 16, 6, {0},&reftables[44], &reftables[45]),
  6435. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "allow_alias", 2, &msgs[4], NULL, 7, 1, {0},&reftables[46], &reftables[47]),
  6436. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_enable_arenas", 31, &msgs[11], NULL, 24, 12, {0},&reftables[48], &reftables[49]),
  6437. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_generic_services", 16, &msgs[11], NULL, 18, 6, {0},&reftables[50], &reftables[51]),
  6438. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "client_streaming", 5, &msgs[13], NULL, 14, 4, {0},&reftables[52], &reftables[53]),
  6439. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "csharp_namespace", 37, &msgs[11], NULL, 28, 14, {0},&reftables[54], &reftables[55]),
  6440. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "ctype", 1, &msgs[8], (const upb_def*)(&enums[2]), 7, 1, {0},&reftables[56], &reftables[57]),
  6441. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "default_value", 7, &msgs[7], NULL, 17, 7, {0},&reftables[58], &reftables[59]),
  6442. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "dependency", 3, &msgs[9], NULL, 31, 8, {0},&reftables[60], &reftables[61]),
  6443. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[8], NULL, 9, 3, {0},&reftables[62], &reftables[63]),
  6444. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 33, &msgs[14], NULL, 7, 1, {0},&reftables[64], &reftables[65]),
  6445. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[12], NULL, 9, 3, {0},&reftables[66], &reftables[67]),
  6446. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 23, &msgs[11], NULL, 22, 10, {0},&reftables[68], &reftables[69]),
  6447. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 1, &msgs[6], NULL, 7, 1, {0},&reftables[70], &reftables[71]),
  6448. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[4], NULL, 8, 2, {0},&reftables[72], &reftables[73]),
  6449. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 33, &msgs[17], NULL, 7, 1, {0},&reftables[74], &reftables[75]),
  6450. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_DOUBLE, 0, false, false, false, false, "double_value", 6, &msgs[20], NULL, 12, 4, {0},&reftables[76], &reftables[77]),
  6451. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "end", 2, &msgs[2], NULL, 4, 1, {0},&reftables[78], &reftables[79]),
  6452. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "end", 2, &msgs[1], NULL, 4, 1, {0},&reftables[80], &reftables[81]),
  6453. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 5, &msgs[9], (const upb_def*)(&msgs[3]), 14, 1, {0},&reftables[82], &reftables[83]),
  6454. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 4, &msgs[0], (const upb_def*)(&msgs[3]), 19, 2, {0},&reftables[84], &reftables[85]),
  6455. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "extendee", 2, &msgs[7], NULL, 8, 2, {0},&reftables[86], &reftables[87]),
  6456. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 6, &msgs[0], (const upb_def*)(&msgs[7]), 25, 4, {0},&reftables[88], &reftables[89]),
  6457. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 7, &msgs[9], (const upb_def*)(&msgs[7]), 20, 3, {0},&reftables[90], &reftables[91]),
  6458. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension_range", 5, &msgs[0], (const upb_def*)(&msgs[1]), 22, 3, {0},&reftables[92], &reftables[93]),
  6459. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "field", 2, &msgs[0], (const upb_def*)(&msgs[7]), 13, 0, {0},&reftables[94], &reftables[95]),
  6460. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "file", 1, &msgs[10], (const upb_def*)(&msgs[9]), 6, 0, {0},&reftables[96], &reftables[97]),
  6461. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "go_package", 11, &msgs[11], NULL, 15, 5, {0},&reftables[98], &reftables[99]),
  6462. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "identifier_value", 3, &msgs[20], NULL, 7, 1, {0},&reftables[100], &reftables[101]),
  6463. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "input_type", 2, &msgs[13], NULL, 8, 2, {0},&reftables[102], &reftables[103]),
  6464. UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_BOOL, 0, false, false, false, false, "is_extension", 2, &msgs[21], NULL, 6, 1, {0},&reftables[104], &reftables[105]),
  6465. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generate_equals_and_hash", 20, &msgs[11], NULL, 21, 9, {0},&reftables[106], &reftables[107]),
  6466. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generic_services", 17, &msgs[11], NULL, 19, 7, {0},&reftables[108], &reftables[109]),
  6467. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_multiple_files", 10, &msgs[11], NULL, 14, 4, {0},&reftables[110], &reftables[111]),
  6468. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_outer_classname", 8, &msgs[11], NULL, 10, 2, {0},&reftables[112], &reftables[113]),
  6469. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_package", 1, &msgs[11], NULL, 7, 1, {0},&reftables[114], &reftables[115]),
  6470. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_string_check_utf8", 27, &msgs[11], NULL, 23, 11, {0},&reftables[116], &reftables[117]),
  6471. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "javanano_use_deprecated_package", 38, &msgs[11], NULL, 31, 15, {0},&reftables[118], &reftables[119]),
  6472. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "json_name", 10, &msgs[7], NULL, 21, 9, {0},&reftables[120], &reftables[121]),
  6473. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "jstype", 6, &msgs[8], (const upb_def*)(&enums[3]), 11, 5, {0},&reftables[122], &reftables[123]),
  6474. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "label", 4, &msgs[7], (const upb_def*)(&enums[0]), 12, 4, {0},&reftables[124], &reftables[125]),
  6475. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "lazy", 5, &msgs[8], NULL, 10, 4, {0},&reftables[126], &reftables[127]),
  6476. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "leading_comments", 3, &msgs[19], NULL, 9, 2, {0},&reftables[128], &reftables[129]),
  6477. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "leading_detached_comments", 6, &msgs[19], NULL, 17, 4, {0},&reftables[130], &reftables[131]),
  6478. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "location", 1, &msgs[18], (const upb_def*)(&msgs[19]), 6, 0, {0},&reftables[132], &reftables[133]),
  6479. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "map_entry", 7, &msgs[12], NULL, 10, 4, {0},&reftables[134], &reftables[135]),
  6480. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "message_set_wire_format", 1, &msgs[12], NULL, 7, 1, {0},&reftables[136], &reftables[137]),
  6481. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "message_type", 4, &msgs[9], (const upb_def*)(&msgs[0]), 11, 0, {0},&reftables[138], &reftables[139]),
  6482. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "method", 2, &msgs[16], (const upb_def*)(&msgs[13]), 7, 0, {0},&reftables[140], &reftables[141]),
  6483. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "name", 2, &msgs[20], (const upb_def*)(&msgs[21]), 6, 0, {0},&reftables[142], &reftables[143]),
  6484. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[5], NULL, 5, 1, {0},&reftables[144], &reftables[145]),
  6485. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[9], NULL, 23, 6, {0},&reftables[146], &reftables[147]),
  6486. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[3], NULL, 9, 2, {0},&reftables[148], &reftables[149]),
  6487. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[16], NULL, 9, 2, {0},&reftables[150], &reftables[151]),
  6488. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[15], NULL, 3, 0, {0},&reftables[152], &reftables[153]),
  6489. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[13], NULL, 5, 1, {0},&reftables[154], &reftables[155]),
  6490. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[7], NULL, 5, 1, {0},&reftables[156], &reftables[157]),
  6491. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[0], NULL, 33, 8, {0},&reftables[158], &reftables[159]),
  6492. UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_STRING, 0, false, false, false, false, "name_part", 1, &msgs[21], NULL, 3, 0, {0},&reftables[160], &reftables[161]),
  6493. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT64, UPB_INTFMT_VARIABLE, false, false, false, false, "negative_int_value", 5, &msgs[20], NULL, 11, 3, {0},&reftables[162], &reftables[163]),
  6494. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "nested_type", 3, &msgs[0], (const upb_def*)(&msgs[0]), 16, 1, {0},&reftables[164], &reftables[165]),
  6495. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "no_standard_descriptor_accessor", 2, &msgs[12], NULL, 8, 2, {0},&reftables[166], &reftables[167]),
  6496. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 3, &msgs[7], NULL, 11, 3, {0},&reftables[168], &reftables[169]),
  6497. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 2, &msgs[5], NULL, 8, 2, {0},&reftables[170], &reftables[171]),
  6498. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "objc_class_prefix", 36, &msgs[11], NULL, 25, 13, {0},&reftables[172], &reftables[173]),
  6499. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "oneof_decl", 8, &msgs[0], (const upb_def*)(&msgs[15]), 29, 6, {0},&reftables[174], &reftables[175]),
  6500. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "oneof_index", 9, &msgs[7], NULL, 20, 8, {0},&reftables[176], &reftables[177]),
  6501. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "optimize_for", 9, &msgs[11], (const upb_def*)(&enums[4]), 13, 3, {0},&reftables[178], &reftables[179]),
  6502. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 7, &msgs[0], (const upb_def*)(&msgs[12]), 26, 5, {0},&reftables[180], &reftables[181]),
  6503. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[9], (const upb_def*)(&msgs[11]), 21, 4, {0},&reftables[182], &reftables[183]),
  6504. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[7], (const upb_def*)(&msgs[8]), 4, 0, {0},&reftables[184], &reftables[185]),
  6505. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 4, &msgs[13], (const upb_def*)(&msgs[14]), 4, 0, {0},&reftables[186], &reftables[187]),
  6506. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[16], (const upb_def*)(&msgs[17]), 8, 1, {0},&reftables[188], &reftables[189]),
  6507. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[3], (const upb_def*)(&msgs[4]), 8, 1, {0},&reftables[190], &reftables[191]),
  6508. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[5], (const upb_def*)(&msgs[6]), 4, 0, {0},&reftables[192], &reftables[193]),
  6509. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "output_type", 3, &msgs[13], NULL, 11, 3, {0},&reftables[194], &reftables[195]),
  6510. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "package", 2, &msgs[9], NULL, 26, 7, {0},&reftables[196], &reftables[197]),
  6511. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "packed", 2, &msgs[8], NULL, 8, 2, {0},&reftables[198], &reftables[199]),
  6512. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "path", 1, &msgs[19], NULL, 5, 0, {0},&reftables[200], &reftables[201]),
  6513. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "php_class_prefix", 40, &msgs[11], NULL, 32, 16, {0},&reftables[202], &reftables[203]),
  6514. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "php_namespace", 41, &msgs[11], NULL, 35, 17, {0},&reftables[204], &reftables[205]),
  6515. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_UINT64, UPB_INTFMT_VARIABLE, false, false, false, false, "positive_int_value", 4, &msgs[20], NULL, 10, 2, {0},&reftables[206], &reftables[207]),
  6516. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "public_dependency", 10, &msgs[9], NULL, 36, 9, {0},&reftables[208], &reftables[209]),
  6517. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "py_generic_services", 18, &msgs[11], NULL, 20, 8, {0},&reftables[210], &reftables[211]),
  6518. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "reserved_name", 10, &msgs[0], NULL, 38, 9, {0},&reftables[212], &reftables[213]),
  6519. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "reserved_range", 9, &msgs[0], (const upb_def*)(&msgs[2]), 32, 7, {0},&reftables[214], &reftables[215]),
  6520. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "server_streaming", 6, &msgs[13], NULL, 15, 5, {0},&reftables[216], &reftables[217]),
  6521. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "service", 6, &msgs[9], (const upb_def*)(&msgs[16]), 17, 2, {0},&reftables[218], &reftables[219]),
  6522. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "source_code_info", 9, &msgs[9], (const upb_def*)(&msgs[18]), 22, 5, {0},&reftables[220], &reftables[221]),
  6523. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "span", 2, &msgs[19], NULL, 8, 1, {0},&reftables[222], &reftables[223]),
  6524. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "start", 1, &msgs[2], NULL, 3, 0, {0},&reftables[224], &reftables[225]),
  6525. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "start", 1, &msgs[1], NULL, 3, 0, {0},&reftables[226], &reftables[227]),
  6526. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BYTES, 0, false, false, false, false, "string_value", 7, &msgs[20], NULL, 13, 5, {0},&reftables[228], &reftables[229]),
  6527. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "syntax", 12, &msgs[9], NULL, 40, 11, {0},&reftables[230], &reftables[231]),
  6528. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "trailing_comments", 4, &msgs[19], NULL, 12, 3, {0},&reftables[232], &reftables[233]),
  6529. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "type", 5, &msgs[7], (const upb_def*)(&enums[1]), 13, 5, {0},&reftables[234], &reftables[235]),
  6530. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "type_name", 6, &msgs[7], NULL, 14, 6, {0},&reftables[236], &reftables[237]),
  6531. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[12], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[238], &reftables[239]),
  6532. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[17], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[240], &reftables[241]),
  6533. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[11], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[242], &reftables[243]),
  6534. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[14], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[244], &reftables[245]),
  6535. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[8], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[246], &reftables[247]),
  6536. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[6], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[248], &reftables[249]),
  6537. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[4], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[250], &reftables[251]),
  6538. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "value", 2, &msgs[3], (const upb_def*)(&msgs[5]), 7, 0, {0},&reftables[252], &reftables[253]),
  6539. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "weak", 10, &msgs[8], NULL, 12, 6, {0},&reftables[254], &reftables[255]),
  6540. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "weak_dependency", 11, &msgs[9], NULL, 39, 10, {0},&reftables[256], &reftables[257]),
  6541. };
  6542. static const upb_enumdef enums[5] = {
  6543. UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Label", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[188]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[154], 4, 3), 0, &reftables[258], &reftables[259]),
  6544. UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Type", UPB_STRTABLE_INIT(18, 31, UPB_CTYPE_INT32, 5, &strentries[192]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[158], 19, 18), 0, &reftables[260], &reftables[261]),
  6545. UPB_ENUMDEF_INIT("google.protobuf.FieldOptions.CType", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[224]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[177], 3, 3), 0, &reftables[262], &reftables[263]),
  6546. UPB_ENUMDEF_INIT("google.protobuf.FieldOptions.JSType", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[228]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[180], 3, 3), 0, &reftables[264], &reftables[265]),
  6547. UPB_ENUMDEF_INIT("google.protobuf.FileOptions.OptimizeMode", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[232]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[183], 4, 3), 0, &reftables[266], &reftables[267]),
  6548. };
  6549. static const upb_tabent strentries[236] = {
  6550. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "extension"), UPB_TABVALUE_PTR_INIT(&fields[22]), NULL},
  6551. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6552. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "reserved_name"), UPB_TABVALUE_PTR_INIT(&fields[84]), NULL},
  6553. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[57]), NULL},
  6554. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6555. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6556. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6557. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "field"), UPB_TABVALUE_PTR_INIT(&fields[25]), &strentries[12]},
  6558. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "extension_range"), UPB_TABVALUE_PTR_INIT(&fields[24]), &strentries[14]},
  6559. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6560. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "nested_type"), UPB_TABVALUE_PTR_INIT(&fields[60]), NULL},
  6561. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6562. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "reserved_range"), UPB_TABVALUE_PTR_INIT(&fields[85]), NULL},
  6563. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[68]), NULL},
  6564. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "oneof_decl"), UPB_TABVALUE_PTR_INIT(&fields[65]), NULL},
  6565. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[20]), &strentries[13]},
  6566. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[91]), NULL},
  6567. {UPB_TABKEY_STR("\003", "\000", "\000", "\000", "end"), UPB_TABVALUE_PTR_INIT(&fields[18]), NULL},
  6568. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6569. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6570. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[90]), NULL},
  6571. {UPB_TABKEY_STR("\003", "\000", "\000", "\000", "end"), UPB_TABVALUE_PTR_INIT(&fields[17]), NULL},
  6572. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6573. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6574. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6575. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "value"), UPB_TABVALUE_PTR_INIT(&fields[104]), NULL},
  6576. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[73]), NULL},
  6577. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[52]), &strentries[26]},
  6578. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[103]), NULL},
  6579. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[14]), NULL},
  6580. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "allow_alias"), UPB_TABVALUE_PTR_INIT(&fields[1]), NULL},
  6581. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6582. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[63]), NULL},
  6583. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6584. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[74]), NULL},
  6585. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[50]), &strentries[34]},
  6586. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[102]), NULL},
  6587. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[13]), NULL},
  6588. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6589. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6590. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "oneof_index"), UPB_TABVALUE_PTR_INIT(&fields[66]), NULL},
  6591. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "label"), UPB_TABVALUE_PTR_INIT(&fields[40]), NULL},
  6592. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6593. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[56]), NULL},
  6594. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6595. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6596. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6597. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6598. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[62]), &strentries[53]},
  6599. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6600. {UPB_TABKEY_STR("\010", "\000", "\000", "\000", "extendee"), UPB_TABVALUE_PTR_INIT(&fields[21]), NULL},
  6601. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "type_name"), UPB_TABVALUE_PTR_INIT(&fields[96]), NULL},
  6602. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "json_name"), UPB_TABVALUE_PTR_INIT(&fields[38]), NULL},
  6603. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "type"), UPB_TABVALUE_PTR_INIT(&fields[95]), &strentries[50]},
  6604. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "default_value"), UPB_TABVALUE_PTR_INIT(&fields[7]), NULL},
  6605. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[70]), NULL},
  6606. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[101]), NULL},
  6607. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6608. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "weak"), UPB_TABVALUE_PTR_INIT(&fields[105]), NULL},
  6609. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6610. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6611. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6612. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6613. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "packed"), UPB_TABVALUE_PTR_INIT(&fields[77]), NULL},
  6614. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "lazy"), UPB_TABVALUE_PTR_INIT(&fields[41]), NULL},
  6615. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6616. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "ctype"), UPB_TABVALUE_PTR_INIT(&fields[6]), NULL},
  6617. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6618. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "jstype"), UPB_TABVALUE_PTR_INIT(&fields[39]), NULL},
  6619. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[9]), NULL},
  6620. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6621. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6622. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "extension"), UPB_TABVALUE_PTR_INIT(&fields[23]), NULL},
  6623. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "weak_dependency"), UPB_TABVALUE_PTR_INIT(&fields[106]), NULL},
  6624. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6625. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[51]), NULL},
  6626. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "service"), UPB_TABVALUE_PTR_INIT(&fields[87]), NULL},
  6627. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6628. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "source_code_info"), UPB_TABVALUE_PTR_INIT(&fields[88]), NULL},
  6629. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6630. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6631. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "syntax"), UPB_TABVALUE_PTR_INIT(&fields[93]), NULL},
  6632. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "dependency"), UPB_TABVALUE_PTR_INIT(&fields[8]), NULL},
  6633. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "message_type"), UPB_TABVALUE_PTR_INIT(&fields[47]), NULL},
  6634. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "package"), UPB_TABVALUE_PTR_INIT(&fields[76]), NULL},
  6635. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[69]), &strentries[86]},
  6636. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[19]), NULL},
  6637. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "public_dependency"), UPB_TABVALUE_PTR_INIT(&fields[82]), &strentries[85]},
  6638. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6639. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "file"), UPB_TABVALUE_PTR_INIT(&fields[26]), NULL},
  6640. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6641. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6642. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6643. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6644. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "cc_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[3]), NULL},
  6645. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "csharp_namespace"), UPB_TABVALUE_PTR_INIT(&fields[5]), &strentries[116]},
  6646. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6647. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6648. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6649. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6650. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6651. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6652. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6653. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "go_package"), UPB_TABVALUE_PTR_INIT(&fields[27]), NULL},
  6654. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "java_package"), UPB_TABVALUE_PTR_INIT(&fields[35]), &strentries[120]},
  6655. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6656. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6657. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "java_outer_classname"), UPB_TABVALUE_PTR_INIT(&fields[34]), NULL},
  6658. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "php_namespace"), UPB_TABVALUE_PTR_INIT(&fields[80]), &strentries[113]},
  6659. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6660. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6661. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6662. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "java_multiple_files"), UPB_TABVALUE_PTR_INIT(&fields[33]), &strentries[117]},
  6663. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[99]), NULL},
  6664. {UPB_TABKEY_STR("\025", "\000", "\000", "\000", "java_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[32]), &strentries[118]},
  6665. {UPB_TABKEY_STR("\035", "\000", "\000", "\000", "java_generate_equals_and_hash"), UPB_TABVALUE_PTR_INIT(&fields[31]), NULL},
  6666. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "php_class_prefix"), UPB_TABVALUE_PTR_INIT(&fields[79]), NULL},
  6667. {UPB_TABKEY_STR("\037", "\000", "\000", "\000", "javanano_use_deprecated_package"), UPB_TABVALUE_PTR_INIT(&fields[37]), &strentries[123]},
  6668. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "py_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[83]), NULL},
  6669. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "optimize_for"), UPB_TABVALUE_PTR_INIT(&fields[67]), NULL},
  6670. {UPB_TABKEY_STR("\026", "\000", "\000", "\000", "java_string_check_utf8"), UPB_TABVALUE_PTR_INIT(&fields[36]), NULL},
  6671. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[12]), &strentries[119]},
  6672. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "objc_class_prefix"), UPB_TABVALUE_PTR_INIT(&fields[64]), NULL},
  6673. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "cc_enable_arenas"), UPB_TABVALUE_PTR_INIT(&fields[2]), NULL},
  6674. {UPB_TABKEY_STR("\027", "\000", "\000", "\000", "message_set_wire_format"), UPB_TABVALUE_PTR_INIT(&fields[46]), &strentries[128]},
  6675. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6676. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6677. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6678. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[97]), NULL},
  6679. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[11]), NULL},
  6680. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "map_entry"), UPB_TABVALUE_PTR_INIT(&fields[45]), NULL},
  6681. {UPB_TABKEY_STR("\037", "\000", "\000", "\000", "no_standard_descriptor_accessor"), UPB_TABVALUE_PTR_INIT(&fields[61]), NULL},
  6682. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6683. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "client_streaming"), UPB_TABVALUE_PTR_INIT(&fields[4]), NULL},
  6684. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "server_streaming"), UPB_TABVALUE_PTR_INIT(&fields[86]), NULL},
  6685. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[55]), NULL},
  6686. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "input_type"), UPB_TABVALUE_PTR_INIT(&fields[29]), NULL},
  6687. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6688. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "output_type"), UPB_TABVALUE_PTR_INIT(&fields[75]), NULL},
  6689. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[71]), NULL},
  6690. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[100]), NULL},
  6691. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[10]), NULL},
  6692. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6693. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6694. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6695. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6696. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6697. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[54]), NULL},
  6698. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6699. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[72]), &strentries[150]},
  6700. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "method"), UPB_TABVALUE_PTR_INIT(&fields[48]), NULL},
  6701. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[53]), &strentries[149]},
  6702. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[98]), NULL},
  6703. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[15]), NULL},
  6704. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6705. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6706. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6707. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6708. {UPB_TABKEY_STR("\010", "\000", "\000", "\000", "location"), UPB_TABVALUE_PTR_INIT(&fields[44]), NULL},
  6709. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6710. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6711. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6712. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6713. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "span"), UPB_TABVALUE_PTR_INIT(&fields[89]), &strentries[167]},
  6714. {UPB_TABKEY_STR("\031", "\000", "\000", "\000", "leading_detached_comments"), UPB_TABVALUE_PTR_INIT(&fields[43]), &strentries[165]},
  6715. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "trailing_comments"), UPB_TABVALUE_PTR_INIT(&fields[94]), NULL},
  6716. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "leading_comments"), UPB_TABVALUE_PTR_INIT(&fields[42]), &strentries[164]},
  6717. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "path"), UPB_TABVALUE_PTR_INIT(&fields[78]), NULL},
  6718. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "double_value"), UPB_TABVALUE_PTR_INIT(&fields[16]), NULL},
  6719. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6720. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6721. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[49]), NULL},
  6722. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6723. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6724. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6725. {UPB_TABKEY_STR("\022", "\000", "\000", "\000", "negative_int_value"), UPB_TABVALUE_PTR_INIT(&fields[59]), NULL},
  6726. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "aggregate_value"), UPB_TABVALUE_PTR_INIT(&fields[0]), NULL},
  6727. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6728. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6729. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6730. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6731. {UPB_TABKEY_STR("\022", "\000", "\000", "\000", "positive_int_value"), UPB_TABVALUE_PTR_INIT(&fields[81]), NULL},
  6732. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "identifier_value"), UPB_TABVALUE_PTR_INIT(&fields[28]), NULL},
  6733. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "string_value"), UPB_TABVALUE_PTR_INIT(&fields[92]), &strentries[182]},
  6734. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6735. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6736. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "is_extension"), UPB_TABVALUE_PTR_INIT(&fields[30]), NULL},
  6737. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "name_part"), UPB_TABVALUE_PTR_INIT(&fields[58]), NULL},
  6738. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_REQUIRED"), UPB_TABVALUE_INT_INIT(2), &strentries[190]},
  6739. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6740. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_REPEATED"), UPB_TABVALUE_INT_INIT(3), NULL},
  6741. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_OPTIONAL"), UPB_TABVALUE_INT_INIT(1), NULL},
  6742. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_FIXED64"), UPB_TABVALUE_INT_INIT(6), NULL},
  6743. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6744. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6745. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6746. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6747. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_STRING"), UPB_TABVALUE_INT_INIT(9), NULL},
  6748. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_FLOAT"), UPB_TABVALUE_INT_INIT(2), &strentries[221]},
  6749. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_DOUBLE"), UPB_TABVALUE_INT_INIT(1), NULL},
  6750. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6751. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_INT32"), UPB_TABVALUE_INT_INIT(5), NULL},
  6752. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "TYPE_SFIXED32"), UPB_TABVALUE_INT_INIT(15), NULL},
  6753. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_FIXED32"), UPB_TABVALUE_INT_INIT(7), NULL},
  6754. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6755. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_MESSAGE"), UPB_TABVALUE_INT_INIT(11), &strentries[222]},
  6756. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6757. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6758. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_INT64"), UPB_TABVALUE_INT_INIT(3), &strentries[219]},
  6759. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6760. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6761. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6762. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6763. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "TYPE_ENUM"), UPB_TABVALUE_INT_INIT(14), NULL},
  6764. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_UINT32"), UPB_TABVALUE_INT_INIT(13), NULL},
  6765. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6766. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_UINT64"), UPB_TABVALUE_INT_INIT(4), &strentries[218]},
  6767. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6768. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "TYPE_SFIXED64"), UPB_TABVALUE_INT_INIT(16), NULL},
  6769. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_BYTES"), UPB_TABVALUE_INT_INIT(12), NULL},
  6770. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_SINT64"), UPB_TABVALUE_INT_INIT(18), NULL},
  6771. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "TYPE_BOOL"), UPB_TABVALUE_INT_INIT(8), NULL},
  6772. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_GROUP"), UPB_TABVALUE_INT_INIT(10), NULL},
  6773. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_SINT32"), UPB_TABVALUE_INT_INIT(17), NULL},
  6774. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6775. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "CORD"), UPB_TABVALUE_INT_INIT(1), NULL},
  6776. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "STRING"), UPB_TABVALUE_INT_INIT(0), &strentries[225]},
  6777. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "STRING_PIECE"), UPB_TABVALUE_INT_INIT(2), NULL},
  6778. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6779. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "JS_NORMAL"), UPB_TABVALUE_INT_INIT(0), NULL},
  6780. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "JS_NUMBER"), UPB_TABVALUE_INT_INIT(2), NULL},
  6781. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "JS_STRING"), UPB_TABVALUE_INT_INIT(1), NULL},
  6782. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "CODE_SIZE"), UPB_TABVALUE_INT_INIT(2), NULL},
  6783. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "SPEED"), UPB_TABVALUE_INT_INIT(1), &strentries[235]},
  6784. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6785. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "LITE_RUNTIME"), UPB_TABVALUE_INT_INIT(3), NULL},
  6786. };
  6787. static const upb_tabent intentries[18] = {
  6788. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6789. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[103]), NULL},
  6790. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6791. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[102]), NULL},
  6792. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6793. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[101]), NULL},
  6794. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6795. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[99]), NULL},
  6796. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6797. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[97]), NULL},
  6798. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6799. {UPB_TABKEY_NUM(33), UPB_TABVALUE_PTR_INIT(&fields[10]), NULL},
  6800. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6801. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[100]), NULL},
  6802. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6803. {UPB_TABKEY_NUM(33), UPB_TABVALUE_PTR_INIT(&fields[15]), NULL},
  6804. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6805. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[98]), NULL},
  6806. };
  6807. static const upb_tabval arrays[187] = {
  6808. UPB_TABVALUE_EMPTY_INIT,
  6809. UPB_TABVALUE_PTR_INIT(&fields[57]),
  6810. UPB_TABVALUE_PTR_INIT(&fields[25]),
  6811. UPB_TABVALUE_PTR_INIT(&fields[60]),
  6812. UPB_TABVALUE_PTR_INIT(&fields[20]),
  6813. UPB_TABVALUE_PTR_INIT(&fields[24]),
  6814. UPB_TABVALUE_PTR_INIT(&fields[22]),
  6815. UPB_TABVALUE_PTR_INIT(&fields[68]),
  6816. UPB_TABVALUE_PTR_INIT(&fields[65]),
  6817. UPB_TABVALUE_PTR_INIT(&fields[85]),
  6818. UPB_TABVALUE_PTR_INIT(&fields[84]),
  6819. UPB_TABVALUE_EMPTY_INIT,
  6820. UPB_TABVALUE_PTR_INIT(&fields[91]),
  6821. UPB_TABVALUE_PTR_INIT(&fields[18]),
  6822. UPB_TABVALUE_EMPTY_INIT,
  6823. UPB_TABVALUE_PTR_INIT(&fields[90]),
  6824. UPB_TABVALUE_PTR_INIT(&fields[17]),
  6825. UPB_TABVALUE_EMPTY_INIT,
  6826. UPB_TABVALUE_PTR_INIT(&fields[52]),
  6827. UPB_TABVALUE_PTR_INIT(&fields[104]),
  6828. UPB_TABVALUE_PTR_INIT(&fields[73]),
  6829. UPB_TABVALUE_EMPTY_INIT,
  6830. UPB_TABVALUE_EMPTY_INIT,
  6831. UPB_TABVALUE_PTR_INIT(&fields[1]),
  6832. UPB_TABVALUE_PTR_INIT(&fields[14]),
  6833. UPB_TABVALUE_EMPTY_INIT,
  6834. UPB_TABVALUE_PTR_INIT(&fields[50]),
  6835. UPB_TABVALUE_PTR_INIT(&fields[63]),
  6836. UPB_TABVALUE_PTR_INIT(&fields[74]),
  6837. UPB_TABVALUE_EMPTY_INIT,
  6838. UPB_TABVALUE_PTR_INIT(&fields[13]),
  6839. UPB_TABVALUE_EMPTY_INIT,
  6840. UPB_TABVALUE_PTR_INIT(&fields[56]),
  6841. UPB_TABVALUE_PTR_INIT(&fields[21]),
  6842. UPB_TABVALUE_PTR_INIT(&fields[62]),
  6843. UPB_TABVALUE_PTR_INIT(&fields[40]),
  6844. UPB_TABVALUE_PTR_INIT(&fields[95]),
  6845. UPB_TABVALUE_PTR_INIT(&fields[96]),
  6846. UPB_TABVALUE_PTR_INIT(&fields[7]),
  6847. UPB_TABVALUE_PTR_INIT(&fields[70]),
  6848. UPB_TABVALUE_PTR_INIT(&fields[66]),
  6849. UPB_TABVALUE_PTR_INIT(&fields[38]),
  6850. UPB_TABVALUE_EMPTY_INIT,
  6851. UPB_TABVALUE_PTR_INIT(&fields[6]),
  6852. UPB_TABVALUE_PTR_INIT(&fields[77]),
  6853. UPB_TABVALUE_PTR_INIT(&fields[9]),
  6854. UPB_TABVALUE_EMPTY_INIT,
  6855. UPB_TABVALUE_PTR_INIT(&fields[41]),
  6856. UPB_TABVALUE_PTR_INIT(&fields[39]),
  6857. UPB_TABVALUE_EMPTY_INIT,
  6858. UPB_TABVALUE_EMPTY_INIT,
  6859. UPB_TABVALUE_EMPTY_INIT,
  6860. UPB_TABVALUE_PTR_INIT(&fields[105]),
  6861. UPB_TABVALUE_EMPTY_INIT,
  6862. UPB_TABVALUE_PTR_INIT(&fields[51]),
  6863. UPB_TABVALUE_PTR_INIT(&fields[76]),
  6864. UPB_TABVALUE_PTR_INIT(&fields[8]),
  6865. UPB_TABVALUE_PTR_INIT(&fields[47]),
  6866. UPB_TABVALUE_PTR_INIT(&fields[19]),
  6867. UPB_TABVALUE_PTR_INIT(&fields[87]),
  6868. UPB_TABVALUE_PTR_INIT(&fields[23]),
  6869. UPB_TABVALUE_PTR_INIT(&fields[69]),
  6870. UPB_TABVALUE_PTR_INIT(&fields[88]),
  6871. UPB_TABVALUE_PTR_INIT(&fields[82]),
  6872. UPB_TABVALUE_PTR_INIT(&fields[106]),
  6873. UPB_TABVALUE_PTR_INIT(&fields[93]),
  6874. UPB_TABVALUE_EMPTY_INIT,
  6875. UPB_TABVALUE_PTR_INIT(&fields[26]),
  6876. UPB_TABVALUE_EMPTY_INIT,
  6877. UPB_TABVALUE_PTR_INIT(&fields[35]),
  6878. UPB_TABVALUE_EMPTY_INIT,
  6879. UPB_TABVALUE_EMPTY_INIT,
  6880. UPB_TABVALUE_EMPTY_INIT,
  6881. UPB_TABVALUE_EMPTY_INIT,
  6882. UPB_TABVALUE_EMPTY_INIT,
  6883. UPB_TABVALUE_EMPTY_INIT,
  6884. UPB_TABVALUE_PTR_INIT(&fields[34]),
  6885. UPB_TABVALUE_PTR_INIT(&fields[67]),
  6886. UPB_TABVALUE_PTR_INIT(&fields[33]),
  6887. UPB_TABVALUE_PTR_INIT(&fields[27]),
  6888. UPB_TABVALUE_EMPTY_INIT,
  6889. UPB_TABVALUE_EMPTY_INIT,
  6890. UPB_TABVALUE_EMPTY_INIT,
  6891. UPB_TABVALUE_EMPTY_INIT,
  6892. UPB_TABVALUE_PTR_INIT(&fields[3]),
  6893. UPB_TABVALUE_PTR_INIT(&fields[32]),
  6894. UPB_TABVALUE_PTR_INIT(&fields[83]),
  6895. UPB_TABVALUE_EMPTY_INIT,
  6896. UPB_TABVALUE_PTR_INIT(&fields[31]),
  6897. UPB_TABVALUE_EMPTY_INIT,
  6898. UPB_TABVALUE_EMPTY_INIT,
  6899. UPB_TABVALUE_PTR_INIT(&fields[12]),
  6900. UPB_TABVALUE_EMPTY_INIT,
  6901. UPB_TABVALUE_EMPTY_INIT,
  6902. UPB_TABVALUE_EMPTY_INIT,
  6903. UPB_TABVALUE_PTR_INIT(&fields[36]),
  6904. UPB_TABVALUE_EMPTY_INIT,
  6905. UPB_TABVALUE_EMPTY_INIT,
  6906. UPB_TABVALUE_EMPTY_INIT,
  6907. UPB_TABVALUE_PTR_INIT(&fields[2]),
  6908. UPB_TABVALUE_EMPTY_INIT,
  6909. UPB_TABVALUE_EMPTY_INIT,
  6910. UPB_TABVALUE_EMPTY_INIT,
  6911. UPB_TABVALUE_EMPTY_INIT,
  6912. UPB_TABVALUE_PTR_INIT(&fields[64]),
  6913. UPB_TABVALUE_PTR_INIT(&fields[5]),
  6914. UPB_TABVALUE_PTR_INIT(&fields[37]),
  6915. UPB_TABVALUE_EMPTY_INIT,
  6916. UPB_TABVALUE_PTR_INIT(&fields[79]),
  6917. UPB_TABVALUE_PTR_INIT(&fields[80]),
  6918. UPB_TABVALUE_EMPTY_INIT,
  6919. UPB_TABVALUE_PTR_INIT(&fields[46]),
  6920. UPB_TABVALUE_PTR_INIT(&fields[61]),
  6921. UPB_TABVALUE_PTR_INIT(&fields[11]),
  6922. UPB_TABVALUE_EMPTY_INIT,
  6923. UPB_TABVALUE_EMPTY_INIT,
  6924. UPB_TABVALUE_EMPTY_INIT,
  6925. UPB_TABVALUE_PTR_INIT(&fields[45]),
  6926. UPB_TABVALUE_EMPTY_INIT,
  6927. UPB_TABVALUE_PTR_INIT(&fields[55]),
  6928. UPB_TABVALUE_PTR_INIT(&fields[29]),
  6929. UPB_TABVALUE_PTR_INIT(&fields[75]),
  6930. UPB_TABVALUE_PTR_INIT(&fields[71]),
  6931. UPB_TABVALUE_PTR_INIT(&fields[4]),
  6932. UPB_TABVALUE_PTR_INIT(&fields[86]),
  6933. UPB_TABVALUE_EMPTY_INIT,
  6934. UPB_TABVALUE_EMPTY_INIT,
  6935. UPB_TABVALUE_PTR_INIT(&fields[54]),
  6936. UPB_TABVALUE_EMPTY_INIT,
  6937. UPB_TABVALUE_PTR_INIT(&fields[53]),
  6938. UPB_TABVALUE_PTR_INIT(&fields[48]),
  6939. UPB_TABVALUE_PTR_INIT(&fields[72]),
  6940. UPB_TABVALUE_EMPTY_INIT,
  6941. UPB_TABVALUE_EMPTY_INIT,
  6942. UPB_TABVALUE_PTR_INIT(&fields[44]),
  6943. UPB_TABVALUE_EMPTY_INIT,
  6944. UPB_TABVALUE_PTR_INIT(&fields[78]),
  6945. UPB_TABVALUE_PTR_INIT(&fields[89]),
  6946. UPB_TABVALUE_PTR_INIT(&fields[42]),
  6947. UPB_TABVALUE_PTR_INIT(&fields[94]),
  6948. UPB_TABVALUE_EMPTY_INIT,
  6949. UPB_TABVALUE_PTR_INIT(&fields[43]),
  6950. UPB_TABVALUE_EMPTY_INIT,
  6951. UPB_TABVALUE_EMPTY_INIT,
  6952. UPB_TABVALUE_PTR_INIT(&fields[49]),
  6953. UPB_TABVALUE_PTR_INIT(&fields[28]),
  6954. UPB_TABVALUE_PTR_INIT(&fields[81]),
  6955. UPB_TABVALUE_PTR_INIT(&fields[59]),
  6956. UPB_TABVALUE_PTR_INIT(&fields[16]),
  6957. UPB_TABVALUE_PTR_INIT(&fields[92]),
  6958. UPB_TABVALUE_PTR_INIT(&fields[0]),
  6959. UPB_TABVALUE_EMPTY_INIT,
  6960. UPB_TABVALUE_PTR_INIT(&fields[58]),
  6961. UPB_TABVALUE_PTR_INIT(&fields[30]),
  6962. UPB_TABVALUE_EMPTY_INIT,
  6963. UPB_TABVALUE_PTR_INIT("LABEL_OPTIONAL"),
  6964. UPB_TABVALUE_PTR_INIT("LABEL_REQUIRED"),
  6965. UPB_TABVALUE_PTR_INIT("LABEL_REPEATED"),
  6966. UPB_TABVALUE_EMPTY_INIT,
  6967. UPB_TABVALUE_PTR_INIT("TYPE_DOUBLE"),
  6968. UPB_TABVALUE_PTR_INIT("TYPE_FLOAT"),
  6969. UPB_TABVALUE_PTR_INIT("TYPE_INT64"),
  6970. UPB_TABVALUE_PTR_INIT("TYPE_UINT64"),
  6971. UPB_TABVALUE_PTR_INIT("TYPE_INT32"),
  6972. UPB_TABVALUE_PTR_INIT("TYPE_FIXED64"),
  6973. UPB_TABVALUE_PTR_INIT("TYPE_FIXED32"),
  6974. UPB_TABVALUE_PTR_INIT("TYPE_BOOL"),
  6975. UPB_TABVALUE_PTR_INIT("TYPE_STRING"),
  6976. UPB_TABVALUE_PTR_INIT("TYPE_GROUP"),
  6977. UPB_TABVALUE_PTR_INIT("TYPE_MESSAGE"),
  6978. UPB_TABVALUE_PTR_INIT("TYPE_BYTES"),
  6979. UPB_TABVALUE_PTR_INIT("TYPE_UINT32"),
  6980. UPB_TABVALUE_PTR_INIT("TYPE_ENUM"),
  6981. UPB_TABVALUE_PTR_INIT("TYPE_SFIXED32"),
  6982. UPB_TABVALUE_PTR_INIT("TYPE_SFIXED64"),
  6983. UPB_TABVALUE_PTR_INIT("TYPE_SINT32"),
  6984. UPB_TABVALUE_PTR_INIT("TYPE_SINT64"),
  6985. UPB_TABVALUE_PTR_INIT("STRING"),
  6986. UPB_TABVALUE_PTR_INIT("CORD"),
  6987. UPB_TABVALUE_PTR_INIT("STRING_PIECE"),
  6988. UPB_TABVALUE_PTR_INIT("JS_NORMAL"),
  6989. UPB_TABVALUE_PTR_INIT("JS_STRING"),
  6990. UPB_TABVALUE_PTR_INIT("JS_NUMBER"),
  6991. UPB_TABVALUE_EMPTY_INIT,
  6992. UPB_TABVALUE_PTR_INIT("SPEED"),
  6993. UPB_TABVALUE_PTR_INIT("CODE_SIZE"),
  6994. UPB_TABVALUE_PTR_INIT("LITE_RUNTIME"),
  6995. };
  6996. #ifdef UPB_DEBUG_REFS
  6997. static upb_inttable reftables[268] = {
  6998. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6999. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7000. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7001. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7002. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7003. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7004. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7005. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7006. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7007. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7008. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7009. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7010. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7011. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7012. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7013. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7014. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7015. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7016. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7017. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7018. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7019. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7020. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7021. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7022. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7023. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7024. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7025. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7026. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7027. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7028. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7029. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7030. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7031. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7032. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7033. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7034. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7035. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7036. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7037. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7038. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7039. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7040. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7041. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7042. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7043. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7044. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7045. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7046. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7047. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7048. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7049. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7050. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7051. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7052. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7053. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7054. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7055. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7056. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7057. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7058. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7059. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7060. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7061. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7062. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7063. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7064. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7065. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7066. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7067. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7068. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7069. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7070. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7071. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7072. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7073. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7074. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7075. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7076. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7077. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7078. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7079. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7080. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7081. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7082. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7083. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7084. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7085. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7086. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7087. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7088. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7089. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7090. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7091. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7092. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7093. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7094. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7095. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7096. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7097. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7098. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7099. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7100. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7101. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7102. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7103. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7104. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7105. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7106. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7107. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7108. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7109. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7110. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7111. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7112. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7113. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7114. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7115. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7116. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7117. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7118. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7119. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7120. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7121. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7122. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7123. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7124. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7125. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7126. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7127. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7128. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7129. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7130. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7131. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7132. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7133. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7134. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7135. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7136. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7137. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7138. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7139. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7140. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7141. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7142. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7143. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7144. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7145. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7146. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7147. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7148. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7149. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7150. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7151. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7152. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7153. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7154. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7155. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7156. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7157. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7158. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7159. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7160. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7161. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7162. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7163. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7164. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7165. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7166. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7167. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7168. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7169. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7170. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7171. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7172. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7173. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7174. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7175. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7176. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7177. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7178. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7179. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7180. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7181. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7182. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7183. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7184. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7185. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7186. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7187. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7188. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7189. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7190. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7191. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7192. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7193. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7194. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7195. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7196. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7197. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7198. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7199. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7200. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7201. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7202. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7203. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7204. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7205. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7206. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7207. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7208. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7209. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7210. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7211. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7212. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7213. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7214. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7215. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7216. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7217. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7218. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7219. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7220. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7221. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7222. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7223. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7224. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7225. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7226. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7227. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7228. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7229. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7230. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7231. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7232. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7233. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7234. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7235. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7236. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7237. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7238. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7239. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7240. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7241. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7242. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7243. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7244. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7245. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7246. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7247. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7248. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7249. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7250. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7251. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7252. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7253. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7254. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7255. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7256. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7257. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7258. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7259. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7260. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7261. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7262. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7263. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7264. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7265. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7266. };
  7267. #endif
  7268. static const upb_msgdef *refm(const upb_msgdef *m, const void *owner) {
  7269. upb_msgdef_ref(m, owner);
  7270. return m;
  7271. }
  7272. static const upb_enumdef *refe(const upb_enumdef *e, const void *owner) {
  7273. upb_enumdef_ref(e, owner);
  7274. return e;
  7275. }
  7276. /* Public API. */
  7277. const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_get(const void *owner) { return refm(&msgs[0], owner); }
  7278. const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_ExtensionRange_get(const void *owner) { return refm(&msgs[1], owner); }
  7279. const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_ReservedRange_get(const void *owner) { return refm(&msgs[2], owner); }
  7280. const upb_msgdef *upbdefs_google_protobuf_EnumDescriptorProto_get(const void *owner) { return refm(&msgs[3], owner); }
  7281. const upb_msgdef *upbdefs_google_protobuf_EnumOptions_get(const void *owner) { return refm(&msgs[4], owner); }
  7282. const upb_msgdef *upbdefs_google_protobuf_EnumValueDescriptorProto_get(const void *owner) { return refm(&msgs[5], owner); }
  7283. const upb_msgdef *upbdefs_google_protobuf_EnumValueOptions_get(const void *owner) { return refm(&msgs[6], owner); }
  7284. const upb_msgdef *upbdefs_google_protobuf_FieldDescriptorProto_get(const void *owner) { return refm(&msgs[7], owner); }
  7285. const upb_msgdef *upbdefs_google_protobuf_FieldOptions_get(const void *owner) { return refm(&msgs[8], owner); }
  7286. const upb_msgdef *upbdefs_google_protobuf_FileDescriptorProto_get(const void *owner) { return refm(&msgs[9], owner); }
  7287. const upb_msgdef *upbdefs_google_protobuf_FileDescriptorSet_get(const void *owner) { return refm(&msgs[10], owner); }
  7288. const upb_msgdef *upbdefs_google_protobuf_FileOptions_get(const void *owner) { return refm(&msgs[11], owner); }
  7289. const upb_msgdef *upbdefs_google_protobuf_MessageOptions_get(const void *owner) { return refm(&msgs[12], owner); }
  7290. const upb_msgdef *upbdefs_google_protobuf_MethodDescriptorProto_get(const void *owner) { return refm(&msgs[13], owner); }
  7291. const upb_msgdef *upbdefs_google_protobuf_MethodOptions_get(const void *owner) { return refm(&msgs[14], owner); }
  7292. const upb_msgdef *upbdefs_google_protobuf_OneofDescriptorProto_get(const void *owner) { return refm(&msgs[15], owner); }
  7293. const upb_msgdef *upbdefs_google_protobuf_ServiceDescriptorProto_get(const void *owner) { return refm(&msgs[16], owner); }
  7294. const upb_msgdef *upbdefs_google_protobuf_ServiceOptions_get(const void *owner) { return refm(&msgs[17], owner); }
  7295. const upb_msgdef *upbdefs_google_protobuf_SourceCodeInfo_get(const void *owner) { return refm(&msgs[18], owner); }
  7296. const upb_msgdef *upbdefs_google_protobuf_SourceCodeInfo_Location_get(const void *owner) { return refm(&msgs[19], owner); }
  7297. const upb_msgdef *upbdefs_google_protobuf_UninterpretedOption_get(const void *owner) { return refm(&msgs[20], owner); }
  7298. const upb_msgdef *upbdefs_google_protobuf_UninterpretedOption_NamePart_get(const void *owner) { return refm(&msgs[21], owner); }
  7299. const upb_enumdef *upbdefs_google_protobuf_FieldDescriptorProto_Label_get(const void *owner) { return refe(&enums[0], owner); }
  7300. const upb_enumdef *upbdefs_google_protobuf_FieldDescriptorProto_Type_get(const void *owner) { return refe(&enums[1], owner); }
  7301. const upb_enumdef *upbdefs_google_protobuf_FieldOptions_CType_get(const void *owner) { return refe(&enums[2], owner); }
  7302. const upb_enumdef *upbdefs_google_protobuf_FieldOptions_JSType_get(const void *owner) { return refe(&enums[3], owner); }
  7303. const upb_enumdef *upbdefs_google_protobuf_FileOptions_OptimizeMode_get(const void *owner) { return refe(&enums[4], owner); }
  7304. /*
  7305. ** XXX: The routines in this file that consume a string do not currently
  7306. ** support having the string span buffers. In the future, as upb_sink and
  7307. ** its buffering/sharing functionality evolve there should be an easy and
  7308. ** idiomatic way of correctly handling this case. For now, we accept this
  7309. ** limitation since we currently only parse descriptors from single strings.
  7310. */
  7311. #include <errno.h>
  7312. #include <stdlib.h>
  7313. #include <string.h>
  7314. /* Compares a NULL-terminated string with a non-NULL-terminated string. */
  7315. static bool upb_streq(const char *str, const char *buf, size_t n) {
  7316. return strlen(str) == n && memcmp(str, buf, n) == 0;
  7317. }
  7318. /* We keep a stack of all the messages scopes we are currently in, as well as
  7319. * the top-level file scope. This is necessary to correctly qualify the
  7320. * definitions that are contained inside. "name" tracks the name of the
  7321. * message or package (a bare name -- not qualified by any enclosing scopes). */
  7322. typedef struct {
  7323. char *name;
  7324. /* Index of the first def that is under this scope. For msgdefs, the
  7325. * msgdef itself is at start-1. */
  7326. int start;
  7327. uint32_t oneof_start;
  7328. uint32_t oneof_index;
  7329. } upb_descreader_frame;
  7330. /* The maximum number of nested declarations that are allowed, ie.
  7331. * message Foo {
  7332. * message Bar {
  7333. * message Baz {
  7334. * }
  7335. * }
  7336. * }
  7337. *
  7338. * This is a resource limit that affects how big our runtime stack can grow.
  7339. * TODO: make this a runtime-settable property of the Reader instance. */
  7340. #define UPB_MAX_MESSAGE_NESTING 64
  7341. struct upb_descreader {
  7342. upb_sink sink;
  7343. upb_inttable files;
  7344. upb_strtable files_by_name;
  7345. upb_filedef *file; /* The last file in files. */
  7346. upb_descreader_frame stack[UPB_MAX_MESSAGE_NESTING];
  7347. int stack_len;
  7348. upb_inttable oneofs;
  7349. uint32_t number;
  7350. char *name;
  7351. bool saw_number;
  7352. bool saw_name;
  7353. char *default_string;
  7354. upb_fielddef *f;
  7355. };
  7356. static char *upb_gstrndup(const char *buf, size_t n) {
  7357. char *ret = upb_gmalloc(n + 1);
  7358. if (!ret) return NULL;
  7359. memcpy(ret, buf, n);
  7360. ret[n] = '\0';
  7361. return ret;
  7362. }
  7363. /* Returns a newly allocated string that joins input strings together, for
  7364. * example:
  7365. * join("Foo.Bar", "Baz") -> "Foo.Bar.Baz"
  7366. * join("", "Baz") -> "Baz"
  7367. * Caller owns a ref on the returned string. */
  7368. static char *upb_join(const char *base, const char *name) {
  7369. if (!base || strlen(base) == 0) {
  7370. return upb_gstrdup(name);
  7371. } else {
  7372. char *ret = upb_gmalloc(strlen(base) + strlen(name) + 2);
  7373. if (!ret) {
  7374. return NULL;
  7375. }
  7376. ret[0] = '\0';
  7377. strcat(ret, base);
  7378. strcat(ret, ".");
  7379. strcat(ret, name);
  7380. return ret;
  7381. }
  7382. }
  7383. /* Qualify the defname for all defs starting with offset "start" with "str". */
  7384. static bool upb_descreader_qualify(upb_filedef *f, char *str, int32_t start) {
  7385. size_t i;
  7386. for (i = start; i < upb_filedef_defcount(f); i++) {
  7387. upb_def *def = upb_filedef_mutabledef(f, i);
  7388. char *name = upb_join(str, upb_def_fullname(def));
  7389. if (!name) {
  7390. /* Need better logic here; at this point we've qualified some names but
  7391. * not others. */
  7392. return false;
  7393. }
  7394. upb_def_setfullname(def, name, NULL);
  7395. upb_gfree(name);
  7396. }
  7397. return true;
  7398. }
  7399. /* upb_descreader ************************************************************/
  7400. static upb_msgdef *upb_descreader_top(upb_descreader *r) {
  7401. int index;
  7402. UPB_ASSERT(r->stack_len > 1);
  7403. index = r->stack[r->stack_len-1].start - 1;
  7404. UPB_ASSERT(index >= 0);
  7405. return upb_downcast_msgdef_mutable(upb_filedef_mutabledef(r->file, index));
  7406. }
  7407. static upb_def *upb_descreader_last(upb_descreader *r) {
  7408. return upb_filedef_mutabledef(r->file, upb_filedef_defcount(r->file) - 1);
  7409. }
  7410. /* Start/end handlers for FileDescriptorProto and DescriptorProto (the two
  7411. * entities that have names and can contain sub-definitions. */
  7412. void upb_descreader_startcontainer(upb_descreader *r) {
  7413. upb_descreader_frame *f = &r->stack[r->stack_len++];
  7414. f->start = upb_filedef_defcount(r->file);
  7415. f->oneof_start = upb_inttable_count(&r->oneofs);
  7416. f->oneof_index = 0;
  7417. f->name = NULL;
  7418. }
  7419. bool upb_descreader_endcontainer(upb_descreader *r) {
  7420. upb_descreader_frame *f = &r->stack[r->stack_len - 1];
  7421. while (upb_inttable_count(&r->oneofs) > f->oneof_start) {
  7422. upb_oneofdef *o = upb_value_getptr(upb_inttable_pop(&r->oneofs));
  7423. bool ok = upb_msgdef_addoneof(upb_descreader_top(r), o, &r->oneofs, NULL);
  7424. UPB_ASSERT(ok);
  7425. }
  7426. if (!upb_descreader_qualify(r->file, f->name, f->start)) {
  7427. return false;
  7428. }
  7429. upb_gfree(f->name);
  7430. f->name = NULL;
  7431. r->stack_len--;
  7432. return true;
  7433. }
  7434. void upb_descreader_setscopename(upb_descreader *r, char *str) {
  7435. upb_descreader_frame *f = &r->stack[r->stack_len-1];
  7436. upb_gfree(f->name);
  7437. f->name = str;
  7438. }
  7439. static upb_oneofdef *upb_descreader_getoneof(upb_descreader *r,
  7440. uint32_t index) {
  7441. bool found;
  7442. upb_value val;
  7443. upb_descreader_frame *f = &r->stack[r->stack_len-1];
  7444. /* DescriptorProto messages can be nested, so we will see the nested messages
  7445. * between when we see the FieldDescriptorProto and the OneofDescriptorProto.
  7446. * We need to preserve the oneofs in between these two things. */
  7447. index += f->oneof_start;
  7448. while (upb_inttable_count(&r->oneofs) <= index) {
  7449. upb_inttable_push(&r->oneofs, upb_value_ptr(upb_oneofdef_new(&r->oneofs)));
  7450. }
  7451. found = upb_inttable_lookup(&r->oneofs, index, &val);
  7452. UPB_ASSERT(found);
  7453. return upb_value_getptr(val);
  7454. }
  7455. /** Handlers for google.protobuf.FileDescriptorSet. ***************************/
  7456. static void *fileset_startfile(void *closure, const void *hd) {
  7457. upb_descreader *r = closure;
  7458. UPB_UNUSED(hd);
  7459. r->file = upb_filedef_new(&r->files);
  7460. upb_inttable_push(&r->files, upb_value_ptr(r->file));
  7461. return r;
  7462. }
  7463. /** Handlers for google.protobuf.FileDescriptorProto. *************************/
  7464. static bool file_start(void *closure, const void *hd) {
  7465. upb_descreader *r = closure;
  7466. UPB_UNUSED(hd);
  7467. upb_descreader_startcontainer(r);
  7468. return true;
  7469. }
  7470. static bool file_end(void *closure, const void *hd, upb_status *status) {
  7471. upb_descreader *r = closure;
  7472. UPB_UNUSED(hd);
  7473. UPB_UNUSED(status);
  7474. return upb_descreader_endcontainer(r);
  7475. }
  7476. static size_t file_onname(void *closure, const void *hd, const char *buf,
  7477. size_t n, const upb_bufhandle *handle) {
  7478. upb_descreader *r = closure;
  7479. char *name;
  7480. bool ok;
  7481. UPB_UNUSED(hd);
  7482. UPB_UNUSED(handle);
  7483. name = upb_gstrndup(buf, n);
  7484. upb_strtable_insert(&r->files_by_name, name, upb_value_ptr(r->file));
  7485. /* XXX: see comment at the top of the file. */
  7486. ok = upb_filedef_setname(r->file, name, NULL);
  7487. upb_gfree(name);
  7488. UPB_ASSERT(ok);
  7489. return n;
  7490. }
  7491. static size_t file_onpackage(void *closure, const void *hd, const char *buf,
  7492. size_t n, const upb_bufhandle *handle) {
  7493. upb_descreader *r = closure;
  7494. char *package;
  7495. bool ok;
  7496. UPB_UNUSED(hd);
  7497. UPB_UNUSED(handle);
  7498. package = upb_gstrndup(buf, n);
  7499. /* XXX: see comment at the top of the file. */
  7500. upb_descreader_setscopename(r, package);
  7501. ok = upb_filedef_setpackage(r->file, package, NULL);
  7502. UPB_ASSERT(ok);
  7503. return n;
  7504. }
  7505. static void *file_startphpnamespace(void *closure, const void *hd,
  7506. size_t size_hint) {
  7507. upb_descreader *r = closure;
  7508. bool ok;
  7509. UPB_UNUSED(hd);
  7510. UPB_UNUSED(size_hint);
  7511. ok = upb_filedef_setphpnamespace(r->file, "", NULL);
  7512. UPB_ASSERT(ok);
  7513. return closure;
  7514. }
  7515. static size_t file_onphpnamespace(void *closure, const void *hd,
  7516. const char *buf, size_t n,
  7517. const upb_bufhandle *handle) {
  7518. upb_descreader *r = closure;
  7519. char *php_namespace;
  7520. bool ok;
  7521. UPB_UNUSED(hd);
  7522. UPB_UNUSED(handle);
  7523. php_namespace = upb_gstrndup(buf, n);
  7524. ok = upb_filedef_setphpnamespace(r->file, php_namespace, NULL);
  7525. upb_gfree(php_namespace);
  7526. UPB_ASSERT(ok);
  7527. return n;
  7528. }
  7529. static size_t file_onphpprefix(void *closure, const void *hd, const char *buf,
  7530. size_t n, const upb_bufhandle *handle) {
  7531. upb_descreader *r = closure;
  7532. char *prefix;
  7533. bool ok;
  7534. UPB_UNUSED(hd);
  7535. UPB_UNUSED(handle);
  7536. prefix = upb_gstrndup(buf, n);
  7537. ok = upb_filedef_setphpprefix(r->file, prefix, NULL);
  7538. upb_gfree(prefix);
  7539. UPB_ASSERT(ok);
  7540. return n;
  7541. }
  7542. static size_t file_onsyntax(void *closure, const void *hd, const char *buf,
  7543. size_t n, const upb_bufhandle *handle) {
  7544. upb_descreader *r = closure;
  7545. bool ok;
  7546. UPB_UNUSED(hd);
  7547. UPB_UNUSED(handle);
  7548. /* XXX: see comment at the top of the file. */
  7549. if (upb_streq("proto2", buf, n)) {
  7550. ok = upb_filedef_setsyntax(r->file, UPB_SYNTAX_PROTO2, NULL);
  7551. } else if (upb_streq("proto3", buf, n)) {
  7552. ok = upb_filedef_setsyntax(r->file, UPB_SYNTAX_PROTO3, NULL);
  7553. } else {
  7554. ok = false;
  7555. }
  7556. UPB_ASSERT(ok);
  7557. return n;
  7558. }
  7559. static void *file_startmsg(void *closure, const void *hd) {
  7560. upb_descreader *r = closure;
  7561. upb_msgdef *m = upb_msgdef_new(&m);
  7562. bool ok = upb_filedef_addmsg(r->file, m, &m, NULL);
  7563. UPB_UNUSED(hd);
  7564. UPB_ASSERT(ok);
  7565. return r;
  7566. }
  7567. static void *file_startenum(void *closure, const void *hd) {
  7568. upb_descreader *r = closure;
  7569. upb_enumdef *e = upb_enumdef_new(&e);
  7570. bool ok = upb_filedef_addenum(r->file, e, &e, NULL);
  7571. UPB_UNUSED(hd);
  7572. UPB_ASSERT(ok);
  7573. return r;
  7574. }
  7575. static void *file_startext(void *closure, const void *hd) {
  7576. upb_descreader *r = closure;
  7577. bool ok;
  7578. r->f = upb_fielddef_new(r);
  7579. ok = upb_filedef_addext(r->file, r->f, r, NULL);
  7580. UPB_UNUSED(hd);
  7581. UPB_ASSERT(ok);
  7582. return r;
  7583. }
  7584. static size_t file_ondep(void *closure, const void *hd, const char *buf,
  7585. size_t n, const upb_bufhandle *handle) {
  7586. upb_descreader *r = closure;
  7587. upb_value val;
  7588. if (upb_strtable_lookup2(&r->files_by_name, buf, n, &val)) {
  7589. upb_filedef_adddep(r->file, upb_value_getptr(val));
  7590. }
  7591. UPB_UNUSED(hd);
  7592. UPB_UNUSED(handle);
  7593. return n;
  7594. }
  7595. /** Handlers for google.protobuf.EnumValueDescriptorProto. *********************/
  7596. static bool enumval_startmsg(void *closure, const void *hd) {
  7597. upb_descreader *r = closure;
  7598. UPB_UNUSED(hd);
  7599. r->saw_number = false;
  7600. r->saw_name = false;
  7601. return true;
  7602. }
  7603. static size_t enumval_onname(void *closure, const void *hd, const char *buf,
  7604. size_t n, const upb_bufhandle *handle) {
  7605. upb_descreader *r = closure;
  7606. UPB_UNUSED(hd);
  7607. UPB_UNUSED(handle);
  7608. /* XXX: see comment at the top of the file. */
  7609. upb_gfree(r->name);
  7610. r->name = upb_gstrndup(buf, n);
  7611. r->saw_name = true;
  7612. return n;
  7613. }
  7614. static bool enumval_onnumber(void *closure, const void *hd, int32_t val) {
  7615. upb_descreader *r = closure;
  7616. UPB_UNUSED(hd);
  7617. r->number = val;
  7618. r->saw_number = true;
  7619. return true;
  7620. }
  7621. static bool enumval_endmsg(void *closure, const void *hd, upb_status *status) {
  7622. upb_descreader *r = closure;
  7623. upb_enumdef *e;
  7624. UPB_UNUSED(hd);
  7625. if(!r->saw_number || !r->saw_name) {
  7626. upb_status_seterrmsg(status, "Enum value missing name or number.");
  7627. return false;
  7628. }
  7629. e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  7630. upb_enumdef_addval(e, r->name, r->number, status);
  7631. upb_gfree(r->name);
  7632. r->name = NULL;
  7633. return true;
  7634. }
  7635. /** Handlers for google.protobuf.EnumDescriptorProto. *************************/
  7636. static bool enum_endmsg(void *closure, const void *hd, upb_status *status) {
  7637. upb_descreader *r = closure;
  7638. upb_enumdef *e;
  7639. UPB_UNUSED(hd);
  7640. e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  7641. if (upb_def_fullname(upb_descreader_last(r)) == NULL) {
  7642. upb_status_seterrmsg(status, "Enum had no name.");
  7643. return false;
  7644. }
  7645. if (upb_enumdef_numvals(e) == 0) {
  7646. upb_status_seterrmsg(status, "Enum had no values.");
  7647. return false;
  7648. }
  7649. return true;
  7650. }
  7651. static size_t enum_onname(void *closure, const void *hd, const char *buf,
  7652. size_t n, const upb_bufhandle *handle) {
  7653. upb_descreader *r = closure;
  7654. char *fullname = upb_gstrndup(buf, n);
  7655. UPB_UNUSED(hd);
  7656. UPB_UNUSED(handle);
  7657. /* XXX: see comment at the top of the file. */
  7658. upb_def_setfullname(upb_descreader_last(r), fullname, NULL);
  7659. upb_gfree(fullname);
  7660. return n;
  7661. }
  7662. /** Handlers for google.protobuf.FieldDescriptorProto *************************/
  7663. static bool field_startmsg(void *closure, const void *hd) {
  7664. upb_descreader *r = closure;
  7665. UPB_UNUSED(hd);
  7666. UPB_ASSERT(r->f);
  7667. upb_gfree(r->default_string);
  7668. r->default_string = NULL;
  7669. /* fielddefs default to packed, but descriptors default to non-packed. */
  7670. upb_fielddef_setpacked(r->f, false);
  7671. return true;
  7672. }
  7673. /* Converts the default value in string "str" into "d". Passes a ref on str.
  7674. * Returns true on success. */
  7675. static bool parse_default(char *str, upb_fielddef *f) {
  7676. bool success = true;
  7677. char *end;
  7678. switch (upb_fielddef_type(f)) {
  7679. case UPB_TYPE_INT32: {
  7680. long val = strtol(str, &end, 0);
  7681. if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || *end)
  7682. success = false;
  7683. else
  7684. upb_fielddef_setdefaultint32(f, val);
  7685. break;
  7686. }
  7687. case UPB_TYPE_INT64: {
  7688. /* XXX: Need to write our own strtoll, since it's not available in c89. */
  7689. long long val = strtol(str, &end, 0);
  7690. if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || *end)
  7691. success = false;
  7692. else
  7693. upb_fielddef_setdefaultint64(f, val);
  7694. break;
  7695. }
  7696. case UPB_TYPE_UINT32: {
  7697. unsigned long val = strtoul(str, &end, 0);
  7698. if (val > UINT32_MAX || errno == ERANGE || *end)
  7699. success = false;
  7700. else
  7701. upb_fielddef_setdefaultuint32(f, val);
  7702. break;
  7703. }
  7704. case UPB_TYPE_UINT64: {
  7705. /* XXX: Need to write our own strtoull, since it's not available in c89. */
  7706. unsigned long long val = strtoul(str, &end, 0);
  7707. if (val > UINT64_MAX || errno == ERANGE || *end)
  7708. success = false;
  7709. else
  7710. upb_fielddef_setdefaultuint64(f, val);
  7711. break;
  7712. }
  7713. case UPB_TYPE_DOUBLE: {
  7714. double val = strtod(str, &end);
  7715. if (errno == ERANGE || *end)
  7716. success = false;
  7717. else
  7718. upb_fielddef_setdefaultdouble(f, val);
  7719. break;
  7720. }
  7721. case UPB_TYPE_FLOAT: {
  7722. /* XXX: Need to write our own strtof, since it's not available in c89. */
  7723. float val = strtod(str, &end);
  7724. if (errno == ERANGE || *end)
  7725. success = false;
  7726. else
  7727. upb_fielddef_setdefaultfloat(f, val);
  7728. break;
  7729. }
  7730. case UPB_TYPE_BOOL: {
  7731. if (strcmp(str, "false") == 0)
  7732. upb_fielddef_setdefaultbool(f, false);
  7733. else if (strcmp(str, "true") == 0)
  7734. upb_fielddef_setdefaultbool(f, true);
  7735. else
  7736. success = false;
  7737. break;
  7738. }
  7739. default: abort();
  7740. }
  7741. return success;
  7742. }
  7743. static bool field_endmsg(void *closure, const void *hd, upb_status *status) {
  7744. upb_descreader *r = closure;
  7745. upb_fielddef *f = r->f;
  7746. UPB_UNUSED(hd);
  7747. /* TODO: verify that all required fields were present. */
  7748. UPB_ASSERT(upb_fielddef_number(f) != 0);
  7749. UPB_ASSERT(upb_fielddef_name(f) != NULL);
  7750. UPB_ASSERT((upb_fielddef_subdefname(f) != NULL) == upb_fielddef_hassubdef(f));
  7751. if (r->default_string) {
  7752. if (upb_fielddef_issubmsg(f)) {
  7753. upb_status_seterrmsg(status, "Submessages cannot have defaults.");
  7754. return false;
  7755. }
  7756. if (upb_fielddef_isstring(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  7757. upb_fielddef_setdefaultcstr(f, r->default_string, NULL);
  7758. } else {
  7759. if (r->default_string && !parse_default(r->default_string, f)) {
  7760. /* We don't worry too much about giving a great error message since the
  7761. * compiler should have ensured this was correct. */
  7762. upb_status_seterrmsg(status, "Error converting default value.");
  7763. return false;
  7764. }
  7765. }
  7766. }
  7767. return true;
  7768. }
  7769. static bool field_onlazy(void *closure, const void *hd, bool val) {
  7770. upb_descreader *r = closure;
  7771. UPB_UNUSED(hd);
  7772. upb_fielddef_setlazy(r->f, val);
  7773. return true;
  7774. }
  7775. static bool field_onpacked(void *closure, const void *hd, bool val) {
  7776. upb_descreader *r = closure;
  7777. UPB_UNUSED(hd);
  7778. upb_fielddef_setpacked(r->f, val);
  7779. return true;
  7780. }
  7781. static bool field_ontype(void *closure, const void *hd, int32_t val) {
  7782. upb_descreader *r = closure;
  7783. UPB_UNUSED(hd);
  7784. upb_fielddef_setdescriptortype(r->f, val);
  7785. return true;
  7786. }
  7787. static bool field_onlabel(void *closure, const void *hd, int32_t val) {
  7788. upb_descreader *r = closure;
  7789. UPB_UNUSED(hd);
  7790. upb_fielddef_setlabel(r->f, val);
  7791. return true;
  7792. }
  7793. static bool field_onnumber(void *closure, const void *hd, int32_t val) {
  7794. upb_descreader *r = closure;
  7795. bool ok;
  7796. UPB_UNUSED(hd);
  7797. ok = upb_fielddef_setnumber(r->f, val, NULL);
  7798. UPB_ASSERT(ok);
  7799. return true;
  7800. }
  7801. static size_t field_onname(void *closure, const void *hd, const char *buf,
  7802. size_t n, const upb_bufhandle *handle) {
  7803. upb_descreader *r = closure;
  7804. char *name = upb_gstrndup(buf, n);
  7805. UPB_UNUSED(hd);
  7806. UPB_UNUSED(handle);
  7807. /* XXX: see comment at the top of the file. */
  7808. upb_fielddef_setname(r->f, name, NULL);
  7809. upb_gfree(name);
  7810. return n;
  7811. }
  7812. static size_t field_ontypename(void *closure, const void *hd, const char *buf,
  7813. size_t n, const upb_bufhandle *handle) {
  7814. upb_descreader *r = closure;
  7815. char *name = upb_gstrndup(buf, n);
  7816. UPB_UNUSED(hd);
  7817. UPB_UNUSED(handle);
  7818. /* XXX: see comment at the top of the file. */
  7819. upb_fielddef_setsubdefname(r->f, name, NULL);
  7820. upb_gfree(name);
  7821. return n;
  7822. }
  7823. static size_t field_onextendee(void *closure, const void *hd, const char *buf,
  7824. size_t n, const upb_bufhandle *handle) {
  7825. upb_descreader *r = closure;
  7826. char *name = upb_gstrndup(buf, n);
  7827. UPB_UNUSED(hd);
  7828. UPB_UNUSED(handle);
  7829. /* XXX: see comment at the top of the file. */
  7830. upb_fielddef_setcontainingtypename(r->f, name, NULL);
  7831. upb_gfree(name);
  7832. return n;
  7833. }
  7834. static size_t field_ondefaultval(void *closure, const void *hd, const char *buf,
  7835. size_t n, const upb_bufhandle *handle) {
  7836. upb_descreader *r = closure;
  7837. UPB_UNUSED(hd);
  7838. UPB_UNUSED(handle);
  7839. /* Have to convert from string to the correct type, but we might not know the
  7840. * type yet, so we save it as a string until the end of the field.
  7841. * XXX: see comment at the top of the file. */
  7842. upb_gfree(r->default_string);
  7843. r->default_string = upb_gstrndup(buf, n);
  7844. return n;
  7845. }
  7846. static bool field_ononeofindex(void *closure, const void *hd, int32_t index) {
  7847. upb_descreader *r = closure;
  7848. upb_oneofdef *o = upb_descreader_getoneof(r, index);
  7849. bool ok = upb_oneofdef_addfield(o, r->f, &r->f, NULL);
  7850. UPB_UNUSED(hd);
  7851. UPB_ASSERT(ok);
  7852. return true;
  7853. }
  7854. /** Handlers for google.protobuf.OneofDescriptorProto. ************************/
  7855. static size_t oneof_name(void *closure, const void *hd, const char *buf,
  7856. size_t n, const upb_bufhandle *handle) {
  7857. upb_descreader *r = closure;
  7858. upb_descreader_frame *f = &r->stack[r->stack_len-1];
  7859. upb_oneofdef *o = upb_descreader_getoneof(r, f->oneof_index++);
  7860. char *name_null_terminated = upb_gstrndup(buf, n);
  7861. bool ok = upb_oneofdef_setname(o, name_null_terminated, NULL);
  7862. UPB_UNUSED(hd);
  7863. UPB_UNUSED(handle);
  7864. UPB_ASSERT(ok);
  7865. free(name_null_terminated);
  7866. return n;
  7867. }
  7868. /** Handlers for google.protobuf.DescriptorProto ******************************/
  7869. static bool msg_start(void *closure, const void *hd) {
  7870. upb_descreader *r = closure;
  7871. UPB_UNUSED(hd);
  7872. upb_descreader_startcontainer(r);
  7873. return true;
  7874. }
  7875. static bool msg_end(void *closure, const void *hd, upb_status *status) {
  7876. upb_descreader *r = closure;
  7877. upb_msgdef *m = upb_descreader_top(r);
  7878. UPB_UNUSED(hd);
  7879. if(!upb_def_fullname(upb_msgdef_upcast_mutable(m))) {
  7880. upb_status_seterrmsg(status, "Encountered message with no name.");
  7881. return false;
  7882. }
  7883. return upb_descreader_endcontainer(r);
  7884. }
  7885. static size_t msg_name(void *closure, const void *hd, const char *buf,
  7886. size_t n, const upb_bufhandle *handle) {
  7887. upb_descreader *r = closure;
  7888. upb_msgdef *m = upb_descreader_top(r);
  7889. /* XXX: see comment at the top of the file. */
  7890. char *name = upb_gstrndup(buf, n);
  7891. UPB_UNUSED(hd);
  7892. UPB_UNUSED(handle);
  7893. upb_def_setfullname(upb_msgdef_upcast_mutable(m), name, NULL);
  7894. upb_descreader_setscopename(r, name); /* Passes ownership of name. */
  7895. return n;
  7896. }
  7897. static void *msg_startmsg(void *closure, const void *hd) {
  7898. upb_descreader *r = closure;
  7899. upb_msgdef *m = upb_msgdef_new(&m);
  7900. bool ok = upb_filedef_addmsg(r->file, m, &m, NULL);
  7901. UPB_UNUSED(hd);
  7902. UPB_ASSERT(ok);
  7903. return r;
  7904. }
  7905. static void *msg_startext(void *closure, const void *hd) {
  7906. upb_descreader *r = closure;
  7907. upb_fielddef *f = upb_fielddef_new(&f);
  7908. bool ok = upb_filedef_addext(r->file, f, &f, NULL);
  7909. UPB_UNUSED(hd);
  7910. UPB_ASSERT(ok);
  7911. return r;
  7912. }
  7913. static void *msg_startfield(void *closure, const void *hd) {
  7914. upb_descreader *r = closure;
  7915. r->f = upb_fielddef_new(&r->f);
  7916. /* We can't add the new field to the message until its name/number are
  7917. * filled in. */
  7918. UPB_UNUSED(hd);
  7919. return r;
  7920. }
  7921. static bool msg_endfield(void *closure, const void *hd) {
  7922. upb_descreader *r = closure;
  7923. upb_msgdef *m = upb_descreader_top(r);
  7924. bool ok;
  7925. UPB_UNUSED(hd);
  7926. /* Oneof fields are added to the msgdef through their oneof, so don't need to
  7927. * be added here. */
  7928. if (upb_fielddef_containingoneof(r->f) == NULL) {
  7929. ok = upb_msgdef_addfield(m, r->f, &r->f, NULL);
  7930. UPB_ASSERT(ok);
  7931. }
  7932. r->f = NULL;
  7933. return true;
  7934. }
  7935. static bool msg_onmapentry(void *closure, const void *hd, bool mapentry) {
  7936. upb_descreader *r = closure;
  7937. upb_msgdef *m = upb_descreader_top(r);
  7938. UPB_UNUSED(hd);
  7939. upb_msgdef_setmapentry(m, mapentry);
  7940. r->f = NULL;
  7941. return true;
  7942. }
  7943. /** Code to register handlers *************************************************/
  7944. #define F(msg, field) upbdefs_google_protobuf_ ## msg ## _f_ ## field(m)
  7945. static void reghandlers(const void *closure, upb_handlers *h) {
  7946. const upb_msgdef *m = upb_handlers_msgdef(h);
  7947. UPB_UNUSED(closure);
  7948. if (upbdefs_google_protobuf_FileDescriptorSet_is(m)) {
  7949. upb_handlers_setstartsubmsg(h, F(FileDescriptorSet, file),
  7950. &fileset_startfile, NULL);
  7951. } else if (upbdefs_google_protobuf_DescriptorProto_is(m)) {
  7952. upb_handlers_setstartmsg(h, &msg_start, NULL);
  7953. upb_handlers_setendmsg(h, &msg_end, NULL);
  7954. upb_handlers_setstring(h, F(DescriptorProto, name), &msg_name, NULL);
  7955. upb_handlers_setstartsubmsg(h, F(DescriptorProto, extension), &msg_startext,
  7956. NULL);
  7957. upb_handlers_setstartsubmsg(h, F(DescriptorProto, nested_type),
  7958. &msg_startmsg, NULL);
  7959. upb_handlers_setstartsubmsg(h, F(DescriptorProto, field),
  7960. &msg_startfield, NULL);
  7961. upb_handlers_setendsubmsg(h, F(DescriptorProto, field),
  7962. &msg_endfield, NULL);
  7963. upb_handlers_setstartsubmsg(h, F(DescriptorProto, enum_type),
  7964. &file_startenum, NULL);
  7965. } else if (upbdefs_google_protobuf_FileDescriptorProto_is(m)) {
  7966. upb_handlers_setstartmsg(h, &file_start, NULL);
  7967. upb_handlers_setendmsg(h, &file_end, NULL);
  7968. upb_handlers_setstring(h, F(FileDescriptorProto, name), &file_onname,
  7969. NULL);
  7970. upb_handlers_setstring(h, F(FileDescriptorProto, package), &file_onpackage,
  7971. NULL);
  7972. upb_handlers_setstring(h, F(FileDescriptorProto, syntax), &file_onsyntax,
  7973. NULL);
  7974. upb_handlers_setstartsubmsg(h, F(FileDescriptorProto, message_type),
  7975. &file_startmsg, NULL);
  7976. upb_handlers_setstartsubmsg(h, F(FileDescriptorProto, enum_type),
  7977. &file_startenum, NULL);
  7978. upb_handlers_setstartsubmsg(h, F(FileDescriptorProto, extension),
  7979. &file_startext, NULL);
  7980. upb_handlers_setstring(h, F(FileDescriptorProto, dependency),
  7981. &file_ondep, NULL);
  7982. } else if (upbdefs_google_protobuf_EnumValueDescriptorProto_is(m)) {
  7983. upb_handlers_setstartmsg(h, &enumval_startmsg, NULL);
  7984. upb_handlers_setendmsg(h, &enumval_endmsg, NULL);
  7985. upb_handlers_setstring(h, F(EnumValueDescriptorProto, name), &enumval_onname, NULL);
  7986. upb_handlers_setint32(h, F(EnumValueDescriptorProto, number), &enumval_onnumber,
  7987. NULL);
  7988. } else if (upbdefs_google_protobuf_EnumDescriptorProto_is(m)) {
  7989. upb_handlers_setendmsg(h, &enum_endmsg, NULL);
  7990. upb_handlers_setstring(h, F(EnumDescriptorProto, name), &enum_onname, NULL);
  7991. } else if (upbdefs_google_protobuf_FieldDescriptorProto_is(m)) {
  7992. upb_handlers_setstartmsg(h, &field_startmsg, NULL);
  7993. upb_handlers_setendmsg(h, &field_endmsg, NULL);
  7994. upb_handlers_setint32(h, F(FieldDescriptorProto, type), &field_ontype,
  7995. NULL);
  7996. upb_handlers_setint32(h, F(FieldDescriptorProto, label), &field_onlabel,
  7997. NULL);
  7998. upb_handlers_setint32(h, F(FieldDescriptorProto, number), &field_onnumber,
  7999. NULL);
  8000. upb_handlers_setstring(h, F(FieldDescriptorProto, name), &field_onname,
  8001. NULL);
  8002. upb_handlers_setstring(h, F(FieldDescriptorProto, type_name),
  8003. &field_ontypename, NULL);
  8004. upb_handlers_setstring(h, F(FieldDescriptorProto, extendee),
  8005. &field_onextendee, NULL);
  8006. upb_handlers_setstring(h, F(FieldDescriptorProto, default_value),
  8007. &field_ondefaultval, NULL);
  8008. upb_handlers_setint32(h, F(FieldDescriptorProto, oneof_index),
  8009. &field_ononeofindex, NULL);
  8010. } else if (upbdefs_google_protobuf_OneofDescriptorProto_is(m)) {
  8011. upb_handlers_setstring(h, F(OneofDescriptorProto, name), &oneof_name, NULL);
  8012. } else if (upbdefs_google_protobuf_FieldOptions_is(m)) {
  8013. upb_handlers_setbool(h, F(FieldOptions, lazy), &field_onlazy, NULL);
  8014. upb_handlers_setbool(h, F(FieldOptions, packed), &field_onpacked, NULL);
  8015. } else if (upbdefs_google_protobuf_MessageOptions_is(m)) {
  8016. upb_handlers_setbool(h, F(MessageOptions, map_entry), &msg_onmapentry, NULL);
  8017. } else if (upbdefs_google_protobuf_FileOptions_is(m)) {
  8018. upb_handlers_setstring(h, F(FileOptions, php_class_prefix),
  8019. &file_onphpprefix, NULL);
  8020. upb_handlers_setstartstr(h, F(FileOptions, php_namespace),
  8021. &file_startphpnamespace, NULL);
  8022. upb_handlers_setstring(h, F(FileOptions, php_namespace),
  8023. &file_onphpnamespace, NULL);
  8024. }
  8025. UPB_ASSERT(upb_ok(upb_handlers_status(h)));
  8026. }
  8027. #undef F
  8028. void descreader_cleanup(void *_r) {
  8029. upb_descreader *r = _r;
  8030. size_t i;
  8031. for (i = 0; i < upb_descreader_filecount(r); i++) {
  8032. upb_filedef_unref(upb_descreader_file(r, i), &r->files);
  8033. }
  8034. upb_gfree(r->name);
  8035. upb_inttable_uninit(&r->files);
  8036. upb_strtable_uninit(&r->files_by_name);
  8037. upb_inttable_uninit(&r->oneofs);
  8038. upb_gfree(r->default_string);
  8039. while (r->stack_len > 0) {
  8040. upb_descreader_frame *f = &r->stack[--r->stack_len];
  8041. upb_gfree(f->name);
  8042. }
  8043. }
  8044. /* Public API ****************************************************************/
  8045. upb_descreader *upb_descreader_create(upb_env *e, const upb_handlers *h) {
  8046. upb_descreader *r = upb_env_malloc(e, sizeof(upb_descreader));
  8047. if (!r || !upb_env_addcleanup(e, descreader_cleanup, r)) {
  8048. return NULL;
  8049. }
  8050. upb_inttable_init(&r->files, UPB_CTYPE_PTR);
  8051. upb_strtable_init(&r->files_by_name, UPB_CTYPE_PTR);
  8052. upb_inttable_init(&r->oneofs, UPB_CTYPE_PTR);
  8053. upb_sink_reset(upb_descreader_input(r), h, r);
  8054. r->stack_len = 0;
  8055. r->name = NULL;
  8056. r->default_string = NULL;
  8057. return r;
  8058. }
  8059. size_t upb_descreader_filecount(const upb_descreader *r) {
  8060. return upb_inttable_count(&r->files);
  8061. }
  8062. upb_filedef *upb_descreader_file(const upb_descreader *r, size_t i) {
  8063. upb_value v;
  8064. if (upb_inttable_lookup(&r->files, i, &v)) {
  8065. return upb_value_getptr(v);
  8066. } else {
  8067. return NULL;
  8068. }
  8069. }
  8070. upb_sink *upb_descreader_input(upb_descreader *r) {
  8071. return &r->sink;
  8072. }
  8073. const upb_handlers *upb_descreader_newhandlers(const void *owner) {
  8074. const upb_msgdef *m = upbdefs_google_protobuf_FileDescriptorSet_get(&m);
  8075. const upb_handlers *h = upb_handlers_newfrozen(m, owner, reghandlers, NULL);
  8076. upb_msgdef_unref(m, &m);
  8077. return h;
  8078. }
  8079. /*
  8080. ** protobuf decoder bytecode compiler
  8081. **
  8082. ** Code to compile a upb::Handlers into bytecode for decoding a protobuf
  8083. ** according to that specific schema and destination handlers.
  8084. **
  8085. ** Compiling to bytecode is always the first step. If we are using the
  8086. ** interpreted decoder we leave it as bytecode and interpret that. If we are
  8087. ** using a JIT decoder we use a code generator to turn the bytecode into native
  8088. ** code, LLVM IR, etc.
  8089. **
  8090. ** Bytecode definition is in decoder.int.h.
  8091. */
  8092. #include <stdarg.h>
  8093. #ifdef UPB_DUMP_BYTECODE
  8094. #include <stdio.h>
  8095. #endif
  8096. #define MAXLABEL 5
  8097. #define EMPTYLABEL -1
  8098. /* mgroup *********************************************************************/
  8099. static void freegroup(upb_refcounted *r) {
  8100. mgroup *g = (mgroup*)r;
  8101. upb_inttable_uninit(&g->methods);
  8102. #ifdef UPB_USE_JIT_X64
  8103. upb_pbdecoder_freejit(g);
  8104. #endif
  8105. upb_gfree(g->bytecode);
  8106. upb_gfree(g);
  8107. }
  8108. static void visitgroup(const upb_refcounted *r, upb_refcounted_visit *visit,
  8109. void *closure) {
  8110. const mgroup *g = (const mgroup*)r;
  8111. upb_inttable_iter i;
  8112. upb_inttable_begin(&i, &g->methods);
  8113. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  8114. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  8115. visit(r, upb_pbdecodermethod_upcast(method), closure);
  8116. }
  8117. }
  8118. mgroup *newgroup(const void *owner) {
  8119. mgroup *g = upb_gmalloc(sizeof(*g));
  8120. static const struct upb_refcounted_vtbl vtbl = {visitgroup, freegroup};
  8121. upb_refcounted_init(mgroup_upcast_mutable(g), &vtbl, owner);
  8122. upb_inttable_init(&g->methods, UPB_CTYPE_PTR);
  8123. g->bytecode = NULL;
  8124. g->bytecode_end = NULL;
  8125. return g;
  8126. }
  8127. /* upb_pbdecodermethod ********************************************************/
  8128. static void freemethod(upb_refcounted *r) {
  8129. upb_pbdecodermethod *method = (upb_pbdecodermethod*)r;
  8130. if (method->dest_handlers_) {
  8131. upb_handlers_unref(method->dest_handlers_, method);
  8132. }
  8133. upb_inttable_uninit(&method->dispatch);
  8134. upb_gfree(method);
  8135. }
  8136. static void visitmethod(const upb_refcounted *r, upb_refcounted_visit *visit,
  8137. void *closure) {
  8138. const upb_pbdecodermethod *m = (const upb_pbdecodermethod*)r;
  8139. visit(r, m->group, closure);
  8140. }
  8141. static upb_pbdecodermethod *newmethod(const upb_handlers *dest_handlers,
  8142. mgroup *group) {
  8143. static const struct upb_refcounted_vtbl vtbl = {visitmethod, freemethod};
  8144. upb_pbdecodermethod *ret = upb_gmalloc(sizeof(*ret));
  8145. upb_refcounted_init(upb_pbdecodermethod_upcast_mutable(ret), &vtbl, &ret);
  8146. upb_byteshandler_init(&ret->input_handler_);
  8147. /* The method references the group and vice-versa, in a circular reference. */
  8148. upb_ref2(ret, group);
  8149. upb_ref2(group, ret);
  8150. upb_inttable_insertptr(&group->methods, dest_handlers, upb_value_ptr(ret));
  8151. upb_pbdecodermethod_unref(ret, &ret);
  8152. ret->group = mgroup_upcast_mutable(group);
  8153. ret->dest_handlers_ = dest_handlers;
  8154. ret->is_native_ = false; /* If we JIT, it will update this later. */
  8155. upb_inttable_init(&ret->dispatch, UPB_CTYPE_UINT64);
  8156. if (ret->dest_handlers_) {
  8157. upb_handlers_ref(ret->dest_handlers_, ret);
  8158. }
  8159. return ret;
  8160. }
  8161. const upb_handlers *upb_pbdecodermethod_desthandlers(
  8162. const upb_pbdecodermethod *m) {
  8163. return m->dest_handlers_;
  8164. }
  8165. const upb_byteshandler *upb_pbdecodermethod_inputhandler(
  8166. const upb_pbdecodermethod *m) {
  8167. return &m->input_handler_;
  8168. }
  8169. bool upb_pbdecodermethod_isnative(const upb_pbdecodermethod *m) {
  8170. return m->is_native_;
  8171. }
  8172. const upb_pbdecodermethod *upb_pbdecodermethod_new(
  8173. const upb_pbdecodermethodopts *opts, const void *owner) {
  8174. const upb_pbdecodermethod *ret;
  8175. upb_pbcodecache cache;
  8176. upb_pbcodecache_init(&cache);
  8177. ret = upb_pbcodecache_getdecodermethod(&cache, opts);
  8178. upb_pbdecodermethod_ref(ret, owner);
  8179. upb_pbcodecache_uninit(&cache);
  8180. return ret;
  8181. }
  8182. /* bytecode compiler **********************************************************/
  8183. /* Data used only at compilation time. */
  8184. typedef struct {
  8185. mgroup *group;
  8186. uint32_t *pc;
  8187. int fwd_labels[MAXLABEL];
  8188. int back_labels[MAXLABEL];
  8189. /* For fields marked "lazy", parse them lazily or eagerly? */
  8190. bool lazy;
  8191. } compiler;
  8192. static compiler *newcompiler(mgroup *group, bool lazy) {
  8193. compiler *ret = upb_gmalloc(sizeof(*ret));
  8194. int i;
  8195. ret->group = group;
  8196. ret->lazy = lazy;
  8197. for (i = 0; i < MAXLABEL; i++) {
  8198. ret->fwd_labels[i] = EMPTYLABEL;
  8199. ret->back_labels[i] = EMPTYLABEL;
  8200. }
  8201. return ret;
  8202. }
  8203. static void freecompiler(compiler *c) {
  8204. upb_gfree(c);
  8205. }
  8206. const size_t ptr_words = sizeof(void*) / sizeof(uint32_t);
  8207. /* How many words an instruction is. */
  8208. static int instruction_len(uint32_t instr) {
  8209. switch (getop(instr)) {
  8210. case OP_SETDISPATCH: return 1 + ptr_words;
  8211. case OP_TAGN: return 3;
  8212. case OP_SETBIGGROUPNUM: return 2;
  8213. default: return 1;
  8214. }
  8215. }
  8216. bool op_has_longofs(int32_t instruction) {
  8217. switch (getop(instruction)) {
  8218. case OP_CALL:
  8219. case OP_BRANCH:
  8220. case OP_CHECKDELIM:
  8221. return true;
  8222. /* The "tag" instructions only have 8 bytes available for the jump target,
  8223. * but that is ok because these opcodes only require short jumps. */
  8224. case OP_TAG1:
  8225. case OP_TAG2:
  8226. case OP_TAGN:
  8227. return false;
  8228. default:
  8229. UPB_ASSERT(false);
  8230. return false;
  8231. }
  8232. }
  8233. static int32_t getofs(uint32_t instruction) {
  8234. if (op_has_longofs(instruction)) {
  8235. return (int32_t)instruction >> 8;
  8236. } else {
  8237. return (int8_t)(instruction >> 8);
  8238. }
  8239. }
  8240. static void setofs(uint32_t *instruction, int32_t ofs) {
  8241. if (op_has_longofs(*instruction)) {
  8242. *instruction = getop(*instruction) | ofs << 8;
  8243. } else {
  8244. *instruction = (*instruction & ~0xff00) | ((ofs & 0xff) << 8);
  8245. }
  8246. UPB_ASSERT(getofs(*instruction) == ofs); /* Would fail in cases of overflow. */
  8247. }
  8248. static uint32_t pcofs(compiler *c) { return c->pc - c->group->bytecode; }
  8249. /* Defines a local label at the current PC location. All previous forward
  8250. * references are updated to point to this location. The location is noted
  8251. * for any future backward references. */
  8252. static void label(compiler *c, unsigned int label) {
  8253. int val;
  8254. uint32_t *codep;
  8255. UPB_ASSERT(label < MAXLABEL);
  8256. val = c->fwd_labels[label];
  8257. codep = (val == EMPTYLABEL) ? NULL : c->group->bytecode + val;
  8258. while (codep) {
  8259. int ofs = getofs(*codep);
  8260. setofs(codep, c->pc - codep - instruction_len(*codep));
  8261. codep = ofs ? codep + ofs : NULL;
  8262. }
  8263. c->fwd_labels[label] = EMPTYLABEL;
  8264. c->back_labels[label] = pcofs(c);
  8265. }
  8266. /* Creates a reference to a numbered label; either a forward reference
  8267. * (positive arg) or backward reference (negative arg). For forward references
  8268. * the value returned now is actually a "next" pointer into a linked list of all
  8269. * instructions that use this label and will be patched later when the label is
  8270. * defined with label().
  8271. *
  8272. * The returned value is the offset that should be written into the instruction.
  8273. */
  8274. static int32_t labelref(compiler *c, int label) {
  8275. UPB_ASSERT(label < MAXLABEL);
  8276. if (label == LABEL_DISPATCH) {
  8277. /* No resolving required. */
  8278. return 0;
  8279. } else if (label < 0) {
  8280. /* Backward local label. Relative to the next instruction. */
  8281. uint32_t from = (c->pc + 1) - c->group->bytecode;
  8282. return c->back_labels[-label] - from;
  8283. } else {
  8284. /* Forward local label: prepend to (possibly-empty) linked list. */
  8285. int *lptr = &c->fwd_labels[label];
  8286. int32_t ret = (*lptr == EMPTYLABEL) ? 0 : *lptr - pcofs(c);
  8287. *lptr = pcofs(c);
  8288. return ret;
  8289. }
  8290. }
  8291. static void put32(compiler *c, uint32_t v) {
  8292. mgroup *g = c->group;
  8293. if (c->pc == g->bytecode_end) {
  8294. int ofs = pcofs(c);
  8295. size_t oldsize = g->bytecode_end - g->bytecode;
  8296. size_t newsize = UPB_MAX(oldsize * 2, 64);
  8297. /* TODO(haberman): handle OOM. */
  8298. g->bytecode = upb_grealloc(g->bytecode, oldsize * sizeof(uint32_t),
  8299. newsize * sizeof(uint32_t));
  8300. g->bytecode_end = g->bytecode + newsize;
  8301. c->pc = g->bytecode + ofs;
  8302. }
  8303. *c->pc++ = v;
  8304. }
  8305. static void putop(compiler *c, int op, ...) {
  8306. va_list ap;
  8307. va_start(ap, op);
  8308. switch (op) {
  8309. case OP_SETDISPATCH: {
  8310. uintptr_t ptr = (uintptr_t)va_arg(ap, void*);
  8311. put32(c, OP_SETDISPATCH);
  8312. put32(c, ptr);
  8313. if (sizeof(uintptr_t) > sizeof(uint32_t))
  8314. put32(c, (uint64_t)ptr >> 32);
  8315. break;
  8316. }
  8317. case OP_STARTMSG:
  8318. case OP_ENDMSG:
  8319. case OP_PUSHLENDELIM:
  8320. case OP_POP:
  8321. case OP_SETDELIM:
  8322. case OP_HALT:
  8323. case OP_RET:
  8324. case OP_DISPATCH:
  8325. put32(c, op);
  8326. break;
  8327. case OP_PARSE_DOUBLE:
  8328. case OP_PARSE_FLOAT:
  8329. case OP_PARSE_INT64:
  8330. case OP_PARSE_UINT64:
  8331. case OP_PARSE_INT32:
  8332. case OP_PARSE_FIXED64:
  8333. case OP_PARSE_FIXED32:
  8334. case OP_PARSE_BOOL:
  8335. case OP_PARSE_UINT32:
  8336. case OP_PARSE_SFIXED32:
  8337. case OP_PARSE_SFIXED64:
  8338. case OP_PARSE_SINT32:
  8339. case OP_PARSE_SINT64:
  8340. case OP_STARTSEQ:
  8341. case OP_ENDSEQ:
  8342. case OP_STARTSUBMSG:
  8343. case OP_ENDSUBMSG:
  8344. case OP_STARTSTR:
  8345. case OP_STRING:
  8346. case OP_ENDSTR:
  8347. case OP_PUSHTAGDELIM:
  8348. put32(c, op | va_arg(ap, upb_selector_t) << 8);
  8349. break;
  8350. case OP_SETBIGGROUPNUM:
  8351. put32(c, op);
  8352. put32(c, va_arg(ap, int));
  8353. break;
  8354. case OP_CALL: {
  8355. const upb_pbdecodermethod *method = va_arg(ap, upb_pbdecodermethod *);
  8356. put32(c, op | (method->code_base.ofs - (pcofs(c) + 1)) << 8);
  8357. break;
  8358. }
  8359. case OP_CHECKDELIM:
  8360. case OP_BRANCH: {
  8361. uint32_t instruction = op;
  8362. int label = va_arg(ap, int);
  8363. setofs(&instruction, labelref(c, label));
  8364. put32(c, instruction);
  8365. break;
  8366. }
  8367. case OP_TAG1:
  8368. case OP_TAG2: {
  8369. int label = va_arg(ap, int);
  8370. uint64_t tag = va_arg(ap, uint64_t);
  8371. uint32_t instruction = op | (tag << 16);
  8372. UPB_ASSERT(tag <= 0xffff);
  8373. setofs(&instruction, labelref(c, label));
  8374. put32(c, instruction);
  8375. break;
  8376. }
  8377. case OP_TAGN: {
  8378. int label = va_arg(ap, int);
  8379. uint64_t tag = va_arg(ap, uint64_t);
  8380. uint32_t instruction = op | (upb_value_size(tag) << 16);
  8381. setofs(&instruction, labelref(c, label));
  8382. put32(c, instruction);
  8383. put32(c, tag);
  8384. put32(c, tag >> 32);
  8385. break;
  8386. }
  8387. }
  8388. va_end(ap);
  8389. }
  8390. #if defined(UPB_USE_JIT_X64) || defined(UPB_DUMP_BYTECODE)
  8391. const char *upb_pbdecoder_getopname(unsigned int op) {
  8392. #define QUOTE(x) #x
  8393. #define EXPAND_AND_QUOTE(x) QUOTE(x)
  8394. #define OPNAME(x) OP_##x
  8395. #define OP(x) case OPNAME(x): return EXPAND_AND_QUOTE(OPNAME(x));
  8396. #define T(x) OP(PARSE_##x)
  8397. /* Keep in sync with list in decoder.int.h. */
  8398. switch ((opcode)op) {
  8399. T(DOUBLE) T(FLOAT) T(INT64) T(UINT64) T(INT32) T(FIXED64) T(FIXED32)
  8400. T(BOOL) T(UINT32) T(SFIXED32) T(SFIXED64) T(SINT32) T(SINT64)
  8401. OP(STARTMSG) OP(ENDMSG) OP(STARTSEQ) OP(ENDSEQ) OP(STARTSUBMSG)
  8402. OP(ENDSUBMSG) OP(STARTSTR) OP(STRING) OP(ENDSTR) OP(CALL) OP(RET)
  8403. OP(PUSHLENDELIM) OP(PUSHTAGDELIM) OP(SETDELIM) OP(CHECKDELIM)
  8404. OP(BRANCH) OP(TAG1) OP(TAG2) OP(TAGN) OP(SETDISPATCH) OP(POP)
  8405. OP(SETBIGGROUPNUM) OP(DISPATCH) OP(HALT)
  8406. }
  8407. return "<unknown op>";
  8408. #undef OP
  8409. #undef T
  8410. }
  8411. #endif
  8412. #ifdef UPB_DUMP_BYTECODE
  8413. static void dumpbc(uint32_t *p, uint32_t *end, FILE *f) {
  8414. uint32_t *begin = p;
  8415. while (p < end) {
  8416. fprintf(f, "%p %8tx", p, p - begin);
  8417. uint32_t instr = *p++;
  8418. uint8_t op = getop(instr);
  8419. fprintf(f, " %s", upb_pbdecoder_getopname(op));
  8420. switch ((opcode)op) {
  8421. case OP_SETDISPATCH: {
  8422. const upb_inttable *dispatch;
  8423. memcpy(&dispatch, p, sizeof(void*));
  8424. p += ptr_words;
  8425. const upb_pbdecodermethod *method =
  8426. (void *)((char *)dispatch -
  8427. offsetof(upb_pbdecodermethod, dispatch));
  8428. fprintf(f, " %s", upb_msgdef_fullname(
  8429. upb_handlers_msgdef(method->dest_handlers_)));
  8430. break;
  8431. }
  8432. case OP_DISPATCH:
  8433. case OP_STARTMSG:
  8434. case OP_ENDMSG:
  8435. case OP_PUSHLENDELIM:
  8436. case OP_POP:
  8437. case OP_SETDELIM:
  8438. case OP_HALT:
  8439. case OP_RET:
  8440. break;
  8441. case OP_PARSE_DOUBLE:
  8442. case OP_PARSE_FLOAT:
  8443. case OP_PARSE_INT64:
  8444. case OP_PARSE_UINT64:
  8445. case OP_PARSE_INT32:
  8446. case OP_PARSE_FIXED64:
  8447. case OP_PARSE_FIXED32:
  8448. case OP_PARSE_BOOL:
  8449. case OP_PARSE_UINT32:
  8450. case OP_PARSE_SFIXED32:
  8451. case OP_PARSE_SFIXED64:
  8452. case OP_PARSE_SINT32:
  8453. case OP_PARSE_SINT64:
  8454. case OP_STARTSEQ:
  8455. case OP_ENDSEQ:
  8456. case OP_STARTSUBMSG:
  8457. case OP_ENDSUBMSG:
  8458. case OP_STARTSTR:
  8459. case OP_STRING:
  8460. case OP_ENDSTR:
  8461. case OP_PUSHTAGDELIM:
  8462. fprintf(f, " %d", instr >> 8);
  8463. break;
  8464. case OP_SETBIGGROUPNUM:
  8465. fprintf(f, " %d", *p++);
  8466. break;
  8467. case OP_CHECKDELIM:
  8468. case OP_CALL:
  8469. case OP_BRANCH:
  8470. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  8471. break;
  8472. case OP_TAG1:
  8473. case OP_TAG2: {
  8474. fprintf(f, " tag:0x%x", instr >> 16);
  8475. if (getofs(instr)) {
  8476. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  8477. }
  8478. break;
  8479. }
  8480. case OP_TAGN: {
  8481. uint64_t tag = *p++;
  8482. tag |= (uint64_t)*p++ << 32;
  8483. fprintf(f, " tag:0x%llx", (long long)tag);
  8484. fprintf(f, " n:%d", instr >> 16);
  8485. if (getofs(instr)) {
  8486. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  8487. }
  8488. break;
  8489. }
  8490. }
  8491. fputs("\n", f);
  8492. }
  8493. }
  8494. #endif
  8495. static uint64_t get_encoded_tag(const upb_fielddef *f, int wire_type) {
  8496. uint32_t tag = (upb_fielddef_number(f) << 3) | wire_type;
  8497. uint64_t encoded_tag = upb_vencode32(tag);
  8498. /* No tag should be greater than 5 bytes. */
  8499. UPB_ASSERT(encoded_tag <= 0xffffffffff);
  8500. return encoded_tag;
  8501. }
  8502. static void putchecktag(compiler *c, const upb_fielddef *f,
  8503. int wire_type, int dest) {
  8504. uint64_t tag = get_encoded_tag(f, wire_type);
  8505. switch (upb_value_size(tag)) {
  8506. case 1:
  8507. putop(c, OP_TAG1, dest, tag);
  8508. break;
  8509. case 2:
  8510. putop(c, OP_TAG2, dest, tag);
  8511. break;
  8512. default:
  8513. putop(c, OP_TAGN, dest, tag);
  8514. break;
  8515. }
  8516. }
  8517. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  8518. upb_selector_t selector;
  8519. bool ok = upb_handlers_getselector(f, type, &selector);
  8520. UPB_ASSERT(ok);
  8521. return selector;
  8522. }
  8523. /* Takes an existing, primary dispatch table entry and repacks it with a
  8524. * different alternate wire type. Called when we are inserting a secondary
  8525. * dispatch table entry for an alternate wire type. */
  8526. static uint64_t repack(uint64_t dispatch, int new_wt2) {
  8527. uint64_t ofs;
  8528. uint8_t wt1;
  8529. uint8_t old_wt2;
  8530. upb_pbdecoder_unpackdispatch(dispatch, &ofs, &wt1, &old_wt2);
  8531. UPB_ASSERT(old_wt2 == NO_WIRE_TYPE); /* wt2 should not be set yet. */
  8532. return upb_pbdecoder_packdispatch(ofs, wt1, new_wt2);
  8533. }
  8534. /* Marks the current bytecode position as the dispatch target for this message,
  8535. * field, and wire type. */
  8536. static void dispatchtarget(compiler *c, upb_pbdecodermethod *method,
  8537. const upb_fielddef *f, int wire_type) {
  8538. /* Offset is relative to msg base. */
  8539. uint64_t ofs = pcofs(c) - method->code_base.ofs;
  8540. uint32_t fn = upb_fielddef_number(f);
  8541. upb_inttable *d = &method->dispatch;
  8542. upb_value v;
  8543. if (upb_inttable_remove(d, fn, &v)) {
  8544. /* TODO: prioritize based on packed setting in .proto file. */
  8545. uint64_t repacked = repack(upb_value_getuint64(v), wire_type);
  8546. upb_inttable_insert(d, fn, upb_value_uint64(repacked));
  8547. upb_inttable_insert(d, fn + UPB_MAX_FIELDNUMBER, upb_value_uint64(ofs));
  8548. } else {
  8549. uint64_t val = upb_pbdecoder_packdispatch(ofs, wire_type, NO_WIRE_TYPE);
  8550. upb_inttable_insert(d, fn, upb_value_uint64(val));
  8551. }
  8552. }
  8553. static void putpush(compiler *c, const upb_fielddef *f) {
  8554. if (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE) {
  8555. putop(c, OP_PUSHLENDELIM);
  8556. } else {
  8557. uint32_t fn = upb_fielddef_number(f);
  8558. if (fn >= 1 << 24) {
  8559. putop(c, OP_PUSHTAGDELIM, 0);
  8560. putop(c, OP_SETBIGGROUPNUM, fn);
  8561. } else {
  8562. putop(c, OP_PUSHTAGDELIM, fn);
  8563. }
  8564. }
  8565. }
  8566. static upb_pbdecodermethod *find_submethod(const compiler *c,
  8567. const upb_pbdecodermethod *method,
  8568. const upb_fielddef *f) {
  8569. const upb_handlers *sub =
  8570. upb_handlers_getsubhandlers(method->dest_handlers_, f);
  8571. upb_value v;
  8572. return upb_inttable_lookupptr(&c->group->methods, sub, &v)
  8573. ? upb_value_getptr(v)
  8574. : NULL;
  8575. }
  8576. static void putsel(compiler *c, opcode op, upb_selector_t sel,
  8577. const upb_handlers *h) {
  8578. if (upb_handlers_gethandler(h, sel)) {
  8579. putop(c, op, sel);
  8580. }
  8581. }
  8582. /* Puts an opcode to call a callback, but only if a callback actually exists for
  8583. * this field and handler type. */
  8584. static void maybeput(compiler *c, opcode op, const upb_handlers *h,
  8585. const upb_fielddef *f, upb_handlertype_t type) {
  8586. putsel(c, op, getsel(f, type), h);
  8587. }
  8588. static bool haslazyhandlers(const upb_handlers *h, const upb_fielddef *f) {
  8589. if (!upb_fielddef_lazy(f))
  8590. return false;
  8591. return upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STARTSTR)) ||
  8592. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STRING)) ||
  8593. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_ENDSTR));
  8594. }
  8595. /* bytecode compiler code generation ******************************************/
  8596. /* Symbolic names for our local labels. */
  8597. #define LABEL_LOOPSTART 1 /* Top of a repeated field loop. */
  8598. #define LABEL_LOOPBREAK 2 /* To jump out of a repeated loop */
  8599. #define LABEL_FIELD 3 /* Jump backward to find the most recent field. */
  8600. #define LABEL_ENDMSG 4 /* To reach the OP_ENDMSG instr for this msg. */
  8601. /* Generates bytecode to parse a single non-lazy message field. */
  8602. static void generate_msgfield(compiler *c, const upb_fielddef *f,
  8603. upb_pbdecodermethod *method) {
  8604. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  8605. const upb_pbdecodermethod *sub_m = find_submethod(c, method, f);
  8606. int wire_type;
  8607. if (!sub_m) {
  8608. /* Don't emit any code for this field at all; it will be parsed as an
  8609. * unknown field.
  8610. *
  8611. * TODO(haberman): we should change this to parse it as a string field
  8612. * instead. It will probably be faster, but more importantly, once we
  8613. * start vending unknown fields, a field shouldn't be treated as unknown
  8614. * just because it doesn't have subhandlers registered. */
  8615. return;
  8616. }
  8617. label(c, LABEL_FIELD);
  8618. wire_type =
  8619. (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE)
  8620. ? UPB_WIRE_TYPE_DELIMITED
  8621. : UPB_WIRE_TYPE_START_GROUP;
  8622. if (upb_fielddef_isseq(f)) {
  8623. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  8624. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  8625. dispatchtarget(c, method, f, wire_type);
  8626. putop(c, OP_PUSHTAGDELIM, 0);
  8627. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  8628. label(c, LABEL_LOOPSTART);
  8629. putpush(c, f);
  8630. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  8631. putop(c, OP_CALL, sub_m);
  8632. putop(c, OP_POP);
  8633. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  8634. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  8635. putop(c, OP_SETDELIM);
  8636. }
  8637. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  8638. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  8639. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  8640. label(c, LABEL_LOOPBREAK);
  8641. putop(c, OP_POP);
  8642. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  8643. } else {
  8644. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  8645. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  8646. dispatchtarget(c, method, f, wire_type);
  8647. putpush(c, f);
  8648. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  8649. putop(c, OP_CALL, sub_m);
  8650. putop(c, OP_POP);
  8651. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  8652. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  8653. putop(c, OP_SETDELIM);
  8654. }
  8655. }
  8656. }
  8657. /* Generates bytecode to parse a single string or lazy submessage field. */
  8658. static void generate_delimfield(compiler *c, const upb_fielddef *f,
  8659. upb_pbdecodermethod *method) {
  8660. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  8661. label(c, LABEL_FIELD);
  8662. if (upb_fielddef_isseq(f)) {
  8663. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  8664. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  8665. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  8666. putop(c, OP_PUSHTAGDELIM, 0);
  8667. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  8668. label(c, LABEL_LOOPSTART);
  8669. putop(c, OP_PUSHLENDELIM);
  8670. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  8671. /* Need to emit even if no handler to skip past the string. */
  8672. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  8673. putop(c, OP_POP);
  8674. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  8675. putop(c, OP_SETDELIM);
  8676. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  8677. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_LOOPBREAK);
  8678. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  8679. label(c, LABEL_LOOPBREAK);
  8680. putop(c, OP_POP);
  8681. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  8682. } else {
  8683. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  8684. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  8685. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  8686. putop(c, OP_PUSHLENDELIM);
  8687. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  8688. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  8689. putop(c, OP_POP);
  8690. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  8691. putop(c, OP_SETDELIM);
  8692. }
  8693. }
  8694. /* Generates bytecode to parse a single primitive field. */
  8695. static void generate_primitivefield(compiler *c, const upb_fielddef *f,
  8696. upb_pbdecodermethod *method) {
  8697. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  8698. upb_descriptortype_t descriptor_type = upb_fielddef_descriptortype(f);
  8699. opcode parse_type;
  8700. upb_selector_t sel;
  8701. int wire_type;
  8702. label(c, LABEL_FIELD);
  8703. /* From a decoding perspective, ENUM is the same as INT32. */
  8704. if (descriptor_type == UPB_DESCRIPTOR_TYPE_ENUM)
  8705. descriptor_type = UPB_DESCRIPTOR_TYPE_INT32;
  8706. parse_type = (opcode)descriptor_type;
  8707. /* TODO(haberman): generate packed or non-packed first depending on "packed"
  8708. * setting in the fielddef. This will favor (in speed) whichever was
  8709. * specified. */
  8710. UPB_ASSERT((int)parse_type >= 0 && parse_type <= OP_MAX);
  8711. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  8712. wire_type = upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  8713. if (upb_fielddef_isseq(f)) {
  8714. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  8715. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  8716. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  8717. putop(c, OP_PUSHLENDELIM);
  8718. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Packed */
  8719. label(c, LABEL_LOOPSTART);
  8720. putop(c, parse_type, sel);
  8721. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  8722. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  8723. dispatchtarget(c, method, f, wire_type);
  8724. putop(c, OP_PUSHTAGDELIM, 0);
  8725. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Non-packed */
  8726. label(c, LABEL_LOOPSTART);
  8727. putop(c, parse_type, sel);
  8728. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  8729. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  8730. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  8731. label(c, LABEL_LOOPBREAK);
  8732. putop(c, OP_POP); /* Packed and non-packed join. */
  8733. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  8734. putop(c, OP_SETDELIM); /* Could remove for non-packed by dup ENDSEQ. */
  8735. } else {
  8736. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  8737. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  8738. dispatchtarget(c, method, f, wire_type);
  8739. putop(c, parse_type, sel);
  8740. }
  8741. }
  8742. /* Adds bytecode for parsing the given message to the given decoderplan,
  8743. * while adding all dispatch targets to this message's dispatch table. */
  8744. static void compile_method(compiler *c, upb_pbdecodermethod *method) {
  8745. const upb_handlers *h;
  8746. const upb_msgdef *md;
  8747. uint32_t* start_pc;
  8748. upb_msg_field_iter i;
  8749. upb_value val;
  8750. UPB_ASSERT(method);
  8751. /* Clear all entries in the dispatch table. */
  8752. upb_inttable_uninit(&method->dispatch);
  8753. upb_inttable_init(&method->dispatch, UPB_CTYPE_UINT64);
  8754. h = upb_pbdecodermethod_desthandlers(method);
  8755. md = upb_handlers_msgdef(h);
  8756. method->code_base.ofs = pcofs(c);
  8757. putop(c, OP_SETDISPATCH, &method->dispatch);
  8758. putsel(c, OP_STARTMSG, UPB_STARTMSG_SELECTOR, h);
  8759. label(c, LABEL_FIELD);
  8760. start_pc = c->pc;
  8761. for(upb_msg_field_begin(&i, md);
  8762. !upb_msg_field_done(&i);
  8763. upb_msg_field_next(&i)) {
  8764. const upb_fielddef *f = upb_msg_iter_field(&i);
  8765. upb_fieldtype_t type = upb_fielddef_type(f);
  8766. if (type == UPB_TYPE_MESSAGE && !(haslazyhandlers(h, f) && c->lazy)) {
  8767. generate_msgfield(c, f, method);
  8768. } else if (type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES ||
  8769. type == UPB_TYPE_MESSAGE) {
  8770. generate_delimfield(c, f, method);
  8771. } else {
  8772. generate_primitivefield(c, f, method);
  8773. }
  8774. }
  8775. /* If there were no fields, or if no handlers were defined, we need to
  8776. * generate a non-empty loop body so that we can at least dispatch for unknown
  8777. * fields and check for the end of the message. */
  8778. if (c->pc == start_pc) {
  8779. /* Check for end-of-message. */
  8780. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  8781. /* Unconditionally dispatch. */
  8782. putop(c, OP_DISPATCH, 0);
  8783. }
  8784. /* For now we just loop back to the last field of the message (or if none,
  8785. * the DISPATCH opcode for the message). */
  8786. putop(c, OP_BRANCH, -LABEL_FIELD);
  8787. /* Insert both a label and a dispatch table entry for this end-of-msg. */
  8788. label(c, LABEL_ENDMSG);
  8789. val = upb_value_uint64(pcofs(c) - method->code_base.ofs);
  8790. upb_inttable_insert(&method->dispatch, DISPATCH_ENDMSG, val);
  8791. putsel(c, OP_ENDMSG, UPB_ENDMSG_SELECTOR, h);
  8792. putop(c, OP_RET);
  8793. upb_inttable_compact(&method->dispatch);
  8794. }
  8795. /* Populate "methods" with new upb_pbdecodermethod objects reachable from "h".
  8796. * Returns the method for these handlers.
  8797. *
  8798. * Generates a new method for every destination handlers reachable from "h". */
  8799. static void find_methods(compiler *c, const upb_handlers *h) {
  8800. upb_value v;
  8801. upb_msg_field_iter i;
  8802. const upb_msgdef *md;
  8803. if (upb_inttable_lookupptr(&c->group->methods, h, &v))
  8804. return;
  8805. newmethod(h, c->group);
  8806. /* Find submethods. */
  8807. md = upb_handlers_msgdef(h);
  8808. for(upb_msg_field_begin(&i, md);
  8809. !upb_msg_field_done(&i);
  8810. upb_msg_field_next(&i)) {
  8811. const upb_fielddef *f = upb_msg_iter_field(&i);
  8812. const upb_handlers *sub_h;
  8813. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  8814. (sub_h = upb_handlers_getsubhandlers(h, f)) != NULL) {
  8815. /* We only generate a decoder method for submessages with handlers.
  8816. * Others will be parsed as unknown fields. */
  8817. find_methods(c, sub_h);
  8818. }
  8819. }
  8820. }
  8821. /* (Re-)compile bytecode for all messages in "msgs."
  8822. * Overwrites any existing bytecode in "c". */
  8823. static void compile_methods(compiler *c) {
  8824. upb_inttable_iter i;
  8825. /* Start over at the beginning of the bytecode. */
  8826. c->pc = c->group->bytecode;
  8827. upb_inttable_begin(&i, &c->group->methods);
  8828. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  8829. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  8830. compile_method(c, method);
  8831. }
  8832. }
  8833. static void set_bytecode_handlers(mgroup *g) {
  8834. upb_inttable_iter i;
  8835. upb_inttable_begin(&i, &g->methods);
  8836. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  8837. upb_pbdecodermethod *m = upb_value_getptr(upb_inttable_iter_value(&i));
  8838. upb_byteshandler *h = &m->input_handler_;
  8839. m->code_base.ptr = g->bytecode + m->code_base.ofs;
  8840. upb_byteshandler_setstartstr(h, upb_pbdecoder_startbc, m->code_base.ptr);
  8841. upb_byteshandler_setstring(h, upb_pbdecoder_decode, g);
  8842. upb_byteshandler_setendstr(h, upb_pbdecoder_end, m);
  8843. }
  8844. }
  8845. /* JIT setup. *****************************************************************/
  8846. #ifdef UPB_USE_JIT_X64
  8847. static void sethandlers(mgroup *g, bool allowjit) {
  8848. g->jit_code = NULL;
  8849. if (allowjit) {
  8850. /* Compile byte-code into machine code, create handlers. */
  8851. upb_pbdecoder_jit(g);
  8852. } else {
  8853. set_bytecode_handlers(g);
  8854. }
  8855. }
  8856. #else /* UPB_USE_JIT_X64 */
  8857. static void sethandlers(mgroup *g, bool allowjit) {
  8858. /* No JIT compiled in; use bytecode handlers unconditionally. */
  8859. UPB_UNUSED(allowjit);
  8860. set_bytecode_handlers(g);
  8861. }
  8862. #endif /* UPB_USE_JIT_X64 */
  8863. /* TODO(haberman): allow this to be constructed for an arbitrary set of dest
  8864. * handlers and other mgroups (but verify we have a transitive closure). */
  8865. const mgroup *mgroup_new(const upb_handlers *dest, bool allowjit, bool lazy,
  8866. const void *owner) {
  8867. mgroup *g;
  8868. compiler *c;
  8869. UPB_UNUSED(allowjit);
  8870. UPB_ASSERT(upb_handlers_isfrozen(dest));
  8871. g = newgroup(owner);
  8872. c = newcompiler(g, lazy);
  8873. find_methods(c, dest);
  8874. /* We compile in two passes:
  8875. * 1. all messages are assigned relative offsets from the beginning of the
  8876. * bytecode (saved in method->code_base).
  8877. * 2. forwards OP_CALL instructions can be correctly linked since message
  8878. * offsets have been previously assigned.
  8879. *
  8880. * Could avoid the second pass by linking OP_CALL instructions somehow. */
  8881. compile_methods(c);
  8882. compile_methods(c);
  8883. g->bytecode_end = c->pc;
  8884. freecompiler(c);
  8885. #ifdef UPB_DUMP_BYTECODE
  8886. {
  8887. FILE *f = fopen("/tmp/upb-bytecode", "w");
  8888. UPB_ASSERT(f);
  8889. dumpbc(g->bytecode, g->bytecode_end, stderr);
  8890. dumpbc(g->bytecode, g->bytecode_end, f);
  8891. fclose(f);
  8892. f = fopen("/tmp/upb-bytecode.bin", "wb");
  8893. UPB_ASSERT(f);
  8894. fwrite(g->bytecode, 1, g->bytecode_end - g->bytecode, f);
  8895. fclose(f);
  8896. }
  8897. #endif
  8898. sethandlers(g, allowjit);
  8899. return g;
  8900. }
  8901. /* upb_pbcodecache ************************************************************/
  8902. void upb_pbcodecache_init(upb_pbcodecache *c) {
  8903. upb_inttable_init(&c->groups, UPB_CTYPE_CONSTPTR);
  8904. c->allow_jit_ = true;
  8905. }
  8906. void upb_pbcodecache_uninit(upb_pbcodecache *c) {
  8907. upb_inttable_iter i;
  8908. upb_inttable_begin(&i, &c->groups);
  8909. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  8910. const mgroup *group = upb_value_getconstptr(upb_inttable_iter_value(&i));
  8911. mgroup_unref(group, c);
  8912. }
  8913. upb_inttable_uninit(&c->groups);
  8914. }
  8915. bool upb_pbcodecache_allowjit(const upb_pbcodecache *c) {
  8916. return c->allow_jit_;
  8917. }
  8918. bool upb_pbcodecache_setallowjit(upb_pbcodecache *c, bool allow) {
  8919. if (upb_inttable_count(&c->groups) > 0)
  8920. return false;
  8921. c->allow_jit_ = allow;
  8922. return true;
  8923. }
  8924. const upb_pbdecodermethod *upb_pbcodecache_getdecodermethod(
  8925. upb_pbcodecache *c, const upb_pbdecodermethodopts *opts) {
  8926. upb_value v;
  8927. bool ok;
  8928. /* Right now we build a new DecoderMethod every time.
  8929. * TODO(haberman): properly cache methods by their true key. */
  8930. const mgroup *g = mgroup_new(opts->handlers, c->allow_jit_, opts->lazy, c);
  8931. upb_inttable_push(&c->groups, upb_value_constptr(g));
  8932. ok = upb_inttable_lookupptr(&g->methods, opts->handlers, &v);
  8933. UPB_ASSERT(ok);
  8934. return upb_value_getptr(v);
  8935. }
  8936. /* upb_pbdecodermethodopts ****************************************************/
  8937. void upb_pbdecodermethodopts_init(upb_pbdecodermethodopts *opts,
  8938. const upb_handlers *h) {
  8939. opts->handlers = h;
  8940. opts->lazy = false;
  8941. }
  8942. void upb_pbdecodermethodopts_setlazy(upb_pbdecodermethodopts *opts, bool lazy) {
  8943. opts->lazy = lazy;
  8944. }
  8945. /*
  8946. ** upb::Decoder (Bytecode Decoder VM)
  8947. **
  8948. ** Bytecode must previously have been generated using the bytecode compiler in
  8949. ** compile_decoder.c. This decoder then walks through the bytecode op-by-op to
  8950. ** parse the input.
  8951. **
  8952. ** Decoding is fully resumable; we just keep a pointer to the current bytecode
  8953. ** instruction and resume from there. A fair amount of the logic here is to
  8954. ** handle the fact that values can span buffer seams and we have to be able to
  8955. ** be capable of suspending/resuming from any byte in the stream. This
  8956. ** sometimes requires keeping a few trailing bytes from the last buffer around
  8957. ** in the "residual" buffer.
  8958. */
  8959. #include <inttypes.h>
  8960. #include <stddef.h>
  8961. #ifdef UPB_DUMP_BYTECODE
  8962. #include <stdio.h>
  8963. #endif
  8964. #define CHECK_SUSPEND(x) if (!(x)) return upb_pbdecoder_suspend(d);
  8965. /* Error messages that are shared between the bytecode and JIT decoders. */
  8966. const char *kPbDecoderStackOverflow = "Nesting too deep.";
  8967. const char *kPbDecoderSubmessageTooLong =
  8968. "Submessage end extends past enclosing submessage.";
  8969. /* Error messages shared within this file. */
  8970. static const char *kUnterminatedVarint = "Unterminated varint.";
  8971. /* upb_pbdecoder **************************************************************/
  8972. static opcode halt = OP_HALT;
  8973. /* A dummy character we can point to when the user passes us a NULL buffer.
  8974. * We need this because in C (NULL + 0) and (NULL - NULL) are undefined
  8975. * behavior, which would invalidate functions like curbufleft(). */
  8976. static const char dummy_char;
  8977. /* Whether an op consumes any of the input buffer. */
  8978. static bool consumes_input(opcode op) {
  8979. switch (op) {
  8980. case OP_SETDISPATCH:
  8981. case OP_STARTMSG:
  8982. case OP_ENDMSG:
  8983. case OP_STARTSEQ:
  8984. case OP_ENDSEQ:
  8985. case OP_STARTSUBMSG:
  8986. case OP_ENDSUBMSG:
  8987. case OP_STARTSTR:
  8988. case OP_ENDSTR:
  8989. case OP_PUSHTAGDELIM:
  8990. case OP_POP:
  8991. case OP_SETDELIM:
  8992. case OP_SETBIGGROUPNUM:
  8993. case OP_CHECKDELIM:
  8994. case OP_CALL:
  8995. case OP_RET:
  8996. case OP_BRANCH:
  8997. return false;
  8998. default:
  8999. return true;
  9000. }
  9001. }
  9002. static size_t stacksize(upb_pbdecoder *d, size_t entries) {
  9003. UPB_UNUSED(d);
  9004. return entries * sizeof(upb_pbdecoder_frame);
  9005. }
  9006. static size_t callstacksize(upb_pbdecoder *d, size_t entries) {
  9007. UPB_UNUSED(d);
  9008. #ifdef UPB_USE_JIT_X64
  9009. if (d->method_->is_native_) {
  9010. /* Each native stack frame needs two pointers, plus we need a few frames for
  9011. * the enter/exit trampolines. */
  9012. size_t ret = entries * sizeof(void*) * 2;
  9013. ret += sizeof(void*) * 10;
  9014. return ret;
  9015. }
  9016. #endif
  9017. return entries * sizeof(uint32_t*);
  9018. }
  9019. static bool in_residual_buf(const upb_pbdecoder *d, const char *p);
  9020. /* It's unfortunate that we have to micro-manage the compiler with
  9021. * UPB_FORCEINLINE and UPB_NOINLINE, especially since this tuning is necessarily
  9022. * specific to one hardware configuration. But empirically on a Core i7,
  9023. * performance increases 30-50% with these annotations. Every instance where
  9024. * these appear, gcc 4.2.1 made the wrong decision and degraded performance in
  9025. * benchmarks. */
  9026. static void seterr(upb_pbdecoder *d, const char *msg) {
  9027. upb_status status = UPB_STATUS_INIT;
  9028. upb_status_seterrmsg(&status, msg);
  9029. upb_env_reporterror(d->env, &status);
  9030. }
  9031. void upb_pbdecoder_seterr(upb_pbdecoder *d, const char *msg) {
  9032. seterr(d, msg);
  9033. }
  9034. /* Buffering ******************************************************************/
  9035. /* We operate on one buffer at a time, which is either the user's buffer passed
  9036. * to our "decode" callback or some residual bytes from the previous buffer. */
  9037. /* How many bytes can be safely read from d->ptr without reading past end-of-buf
  9038. * or past the current delimited end. */
  9039. static size_t curbufleft(const upb_pbdecoder *d) {
  9040. UPB_ASSERT(d->data_end >= d->ptr);
  9041. return d->data_end - d->ptr;
  9042. }
  9043. /* How many bytes are available before end-of-buffer. */
  9044. static size_t bufleft(const upb_pbdecoder *d) {
  9045. return d->end - d->ptr;
  9046. }
  9047. /* Overall stream offset of d->ptr. */
  9048. uint64_t offset(const upb_pbdecoder *d) {
  9049. return d->bufstart_ofs + (d->ptr - d->buf);
  9050. }
  9051. /* How many bytes are available before the end of this delimited region. */
  9052. size_t delim_remaining(const upb_pbdecoder *d) {
  9053. return d->top->end_ofs - offset(d);
  9054. }
  9055. /* Advances d->ptr. */
  9056. static void advance(upb_pbdecoder *d, size_t len) {
  9057. UPB_ASSERT(curbufleft(d) >= len);
  9058. d->ptr += len;
  9059. }
  9060. static bool in_buf(const char *p, const char *buf, const char *end) {
  9061. return p >= buf && p <= end;
  9062. }
  9063. static bool in_residual_buf(const upb_pbdecoder *d, const char *p) {
  9064. return in_buf(p, d->residual, d->residual_end);
  9065. }
  9066. /* Calculates the delim_end value, which is affected by both the current buffer
  9067. * and the parsing stack, so must be called whenever either is updated. */
  9068. static void set_delim_end(upb_pbdecoder *d) {
  9069. size_t delim_ofs = d->top->end_ofs - d->bufstart_ofs;
  9070. if (delim_ofs <= (size_t)(d->end - d->buf)) {
  9071. d->delim_end = d->buf + delim_ofs;
  9072. d->data_end = d->delim_end;
  9073. } else {
  9074. d->data_end = d->end;
  9075. d->delim_end = NULL;
  9076. }
  9077. }
  9078. static void switchtobuf(upb_pbdecoder *d, const char *buf, const char *end) {
  9079. d->ptr = buf;
  9080. d->buf = buf;
  9081. d->end = end;
  9082. set_delim_end(d);
  9083. }
  9084. static void advancetobuf(upb_pbdecoder *d, const char *buf, size_t len) {
  9085. UPB_ASSERT(curbufleft(d) == 0);
  9086. d->bufstart_ofs += (d->end - d->buf);
  9087. switchtobuf(d, buf, buf + len);
  9088. }
  9089. static void checkpoint(upb_pbdecoder *d) {
  9090. /* The assertion here is in the interests of efficiency, not correctness.
  9091. * We are trying to ensure that we don't checkpoint() more often than
  9092. * necessary. */
  9093. UPB_ASSERT(d->checkpoint != d->ptr);
  9094. d->checkpoint = d->ptr;
  9095. }
  9096. /* Skips "bytes" bytes in the stream, which may be more than available. If we
  9097. * skip more bytes than are available, we return a long read count to the caller
  9098. * indicating how many bytes can be skipped over before passing actual data
  9099. * again. Skipped bytes can pass a NULL buffer and the decoder guarantees they
  9100. * won't actually be read.
  9101. */
  9102. static int32_t skip(upb_pbdecoder *d, size_t bytes) {
  9103. UPB_ASSERT(!in_residual_buf(d, d->ptr) || d->size_param == 0);
  9104. UPB_ASSERT(d->skip == 0);
  9105. if (bytes > delim_remaining(d)) {
  9106. seterr(d, "Skipped value extended beyond enclosing submessage.");
  9107. return upb_pbdecoder_suspend(d);
  9108. } else if (bufleft(d) >= bytes) {
  9109. /* Skipped data is all in current buffer, and more is still available. */
  9110. advance(d, bytes);
  9111. d->skip = 0;
  9112. return DECODE_OK;
  9113. } else {
  9114. /* Skipped data extends beyond currently available buffers. */
  9115. d->pc = d->last;
  9116. d->skip = bytes - curbufleft(d);
  9117. d->bufstart_ofs += (d->end - d->buf);
  9118. d->residual_end = d->residual;
  9119. switchtobuf(d, d->residual, d->residual_end);
  9120. return d->size_param + d->skip;
  9121. }
  9122. }
  9123. /* Resumes the decoder from an initial state or from a previous suspend. */
  9124. int32_t upb_pbdecoder_resume(upb_pbdecoder *d, void *p, const char *buf,
  9125. size_t size, const upb_bufhandle *handle) {
  9126. UPB_UNUSED(p); /* Useless; just for the benefit of the JIT. */
  9127. /* d->skip and d->residual_end could probably elegantly be represented
  9128. * as a single variable, to more easily represent this invariant. */
  9129. UPB_ASSERT(!(d->skip && d->residual_end > d->residual));
  9130. /* We need to remember the original size_param, so that the value we return
  9131. * is relative to it, even if we do some skipping first. */
  9132. d->size_param = size;
  9133. d->handle = handle;
  9134. /* Have to handle this case specially (ie. not with skip()) because the user
  9135. * is allowed to pass a NULL buffer here, which won't allow us to safely
  9136. * calculate a d->end or use our normal functions like curbufleft(). */
  9137. if (d->skip && d->skip >= size) {
  9138. d->skip -= size;
  9139. d->bufstart_ofs += size;
  9140. buf = &dummy_char;
  9141. size = 0;
  9142. /* We can't just return now, because we might need to execute some ops
  9143. * like CHECKDELIM, which could call some callbacks and pop the stack. */
  9144. }
  9145. /* We need to pretend that this was the actual buffer param, since some of the
  9146. * calculations assume that d->ptr/d->buf is relative to this. */
  9147. d->buf_param = buf;
  9148. if (!buf) {
  9149. /* NULL buf is ok if its entire span is covered by the "skip" above, but
  9150. * by this point we know that "skip" doesn't cover the buffer. */
  9151. seterr(d, "Passed NULL buffer over non-skippable region.");
  9152. return upb_pbdecoder_suspend(d);
  9153. }
  9154. if (d->residual_end > d->residual) {
  9155. /* We have residual bytes from the last buffer. */
  9156. UPB_ASSERT(d->ptr == d->residual);
  9157. } else {
  9158. switchtobuf(d, buf, buf + size);
  9159. }
  9160. d->checkpoint = d->ptr;
  9161. /* Handle skips that don't cover the whole buffer (as above). */
  9162. if (d->skip) {
  9163. size_t skip_bytes = d->skip;
  9164. d->skip = 0;
  9165. CHECK_RETURN(skip(d, skip_bytes));
  9166. checkpoint(d);
  9167. }
  9168. /* If we're inside an unknown group, continue to parse unknown values. */
  9169. if (d->top->groupnum < 0) {
  9170. CHECK_RETURN(upb_pbdecoder_skipunknown(d, -1, 0));
  9171. checkpoint(d);
  9172. }
  9173. return DECODE_OK;
  9174. }
  9175. /* Suspends the decoder at the last checkpoint, without saving any residual
  9176. * bytes. If there are any unconsumed bytes, returns a short byte count. */
  9177. size_t upb_pbdecoder_suspend(upb_pbdecoder *d) {
  9178. d->pc = d->last;
  9179. if (d->checkpoint == d->residual) {
  9180. /* Checkpoint was in residual buf; no user bytes were consumed. */
  9181. d->ptr = d->residual;
  9182. return 0;
  9183. } else {
  9184. size_t ret = d->size_param - (d->end - d->checkpoint);
  9185. UPB_ASSERT(!in_residual_buf(d, d->checkpoint));
  9186. UPB_ASSERT(d->buf == d->buf_param || d->buf == &dummy_char);
  9187. d->bufstart_ofs += (d->checkpoint - d->buf);
  9188. d->residual_end = d->residual;
  9189. switchtobuf(d, d->residual, d->residual_end);
  9190. return ret;
  9191. }
  9192. }
  9193. /* Suspends the decoder at the last checkpoint, and saves any unconsumed
  9194. * bytes in our residual buffer. This is necessary if we need more user
  9195. * bytes to form a complete value, which might not be contiguous in the
  9196. * user's buffers. Always consumes all user bytes. */
  9197. static size_t suspend_save(upb_pbdecoder *d) {
  9198. /* We hit end-of-buffer before we could parse a full value.
  9199. * Save any unconsumed bytes (if any) to the residual buffer. */
  9200. d->pc = d->last;
  9201. if (d->checkpoint == d->residual) {
  9202. /* Checkpoint was in residual buf; append user byte(s) to residual buf. */
  9203. UPB_ASSERT((d->residual_end - d->residual) + d->size_param <=
  9204. sizeof(d->residual));
  9205. if (!in_residual_buf(d, d->ptr)) {
  9206. d->bufstart_ofs -= (d->residual_end - d->residual);
  9207. }
  9208. memcpy(d->residual_end, d->buf_param, d->size_param);
  9209. d->residual_end += d->size_param;
  9210. } else {
  9211. /* Checkpoint was in user buf; old residual bytes not needed. */
  9212. size_t save;
  9213. UPB_ASSERT(!in_residual_buf(d, d->checkpoint));
  9214. d->ptr = d->checkpoint;
  9215. save = curbufleft(d);
  9216. UPB_ASSERT(save <= sizeof(d->residual));
  9217. memcpy(d->residual, d->ptr, save);
  9218. d->residual_end = d->residual + save;
  9219. d->bufstart_ofs = offset(d);
  9220. }
  9221. switchtobuf(d, d->residual, d->residual_end);
  9222. return d->size_param;
  9223. }
  9224. /* Copies the next "bytes" bytes into "buf" and advances the stream.
  9225. * Requires that this many bytes are available in the current buffer. */
  9226. UPB_FORCEINLINE static void consumebytes(upb_pbdecoder *d, void *buf,
  9227. size_t bytes) {
  9228. UPB_ASSERT(bytes <= curbufleft(d));
  9229. memcpy(buf, d->ptr, bytes);
  9230. advance(d, bytes);
  9231. }
  9232. /* Slow path for getting the next "bytes" bytes, regardless of whether they are
  9233. * available in the current buffer or not. Returns a status code as described
  9234. * in decoder.int.h. */
  9235. UPB_NOINLINE static int32_t getbytes_slow(upb_pbdecoder *d, void *buf,
  9236. size_t bytes) {
  9237. const size_t avail = curbufleft(d);
  9238. consumebytes(d, buf, avail);
  9239. bytes -= avail;
  9240. UPB_ASSERT(bytes > 0);
  9241. if (in_residual_buf(d, d->ptr)) {
  9242. advancetobuf(d, d->buf_param, d->size_param);
  9243. }
  9244. if (curbufleft(d) >= bytes) {
  9245. consumebytes(d, (char *)buf + avail, bytes);
  9246. return DECODE_OK;
  9247. } else if (d->data_end == d->delim_end) {
  9248. seterr(d, "Submessage ended in the middle of a value or group");
  9249. return upb_pbdecoder_suspend(d);
  9250. } else {
  9251. return suspend_save(d);
  9252. }
  9253. }
  9254. /* Gets the next "bytes" bytes, regardless of whether they are available in the
  9255. * current buffer or not. Returns a status code as described in decoder.int.h.
  9256. */
  9257. UPB_FORCEINLINE static int32_t getbytes(upb_pbdecoder *d, void *buf,
  9258. size_t bytes) {
  9259. if (curbufleft(d) >= bytes) {
  9260. /* Buffer has enough data to satisfy. */
  9261. consumebytes(d, buf, bytes);
  9262. return DECODE_OK;
  9263. } else {
  9264. return getbytes_slow(d, buf, bytes);
  9265. }
  9266. }
  9267. UPB_NOINLINE static size_t peekbytes_slow(upb_pbdecoder *d, void *buf,
  9268. size_t bytes) {
  9269. size_t ret = curbufleft(d);
  9270. memcpy(buf, d->ptr, ret);
  9271. if (in_residual_buf(d, d->ptr)) {
  9272. size_t copy = UPB_MIN(bytes - ret, d->size_param);
  9273. memcpy((char *)buf + ret, d->buf_param, copy);
  9274. ret += copy;
  9275. }
  9276. return ret;
  9277. }
  9278. UPB_FORCEINLINE static size_t peekbytes(upb_pbdecoder *d, void *buf,
  9279. size_t bytes) {
  9280. if (curbufleft(d) >= bytes) {
  9281. memcpy(buf, d->ptr, bytes);
  9282. return bytes;
  9283. } else {
  9284. return peekbytes_slow(d, buf, bytes);
  9285. }
  9286. }
  9287. /* Decoding of wire types *****************************************************/
  9288. /* Slow path for decoding a varint from the current buffer position.
  9289. * Returns a status code as described in decoder.int.h. */
  9290. UPB_NOINLINE int32_t upb_pbdecoder_decode_varint_slow(upb_pbdecoder *d,
  9291. uint64_t *u64) {
  9292. uint8_t byte = 0x80;
  9293. int bitpos;
  9294. *u64 = 0;
  9295. for(bitpos = 0; bitpos < 70 && (byte & 0x80); bitpos += 7) {
  9296. CHECK_RETURN(getbytes(d, &byte, 1));
  9297. *u64 |= (uint64_t)(byte & 0x7F) << bitpos;
  9298. }
  9299. if(bitpos == 70 && (byte & 0x80)) {
  9300. seterr(d, kUnterminatedVarint);
  9301. return upb_pbdecoder_suspend(d);
  9302. }
  9303. return DECODE_OK;
  9304. }
  9305. /* Decodes a varint from the current buffer position.
  9306. * Returns a status code as described in decoder.int.h. */
  9307. UPB_FORCEINLINE static int32_t decode_varint(upb_pbdecoder *d, uint64_t *u64) {
  9308. if (curbufleft(d) > 0 && !(*d->ptr & 0x80)) {
  9309. *u64 = *d->ptr;
  9310. advance(d, 1);
  9311. return DECODE_OK;
  9312. } else if (curbufleft(d) >= 10) {
  9313. /* Fast case. */
  9314. upb_decoderet r = upb_vdecode_fast(d->ptr);
  9315. if (r.p == NULL) {
  9316. seterr(d, kUnterminatedVarint);
  9317. return upb_pbdecoder_suspend(d);
  9318. }
  9319. advance(d, r.p - d->ptr);
  9320. *u64 = r.val;
  9321. return DECODE_OK;
  9322. } else {
  9323. /* Slow case -- varint spans buffer seam. */
  9324. return upb_pbdecoder_decode_varint_slow(d, u64);
  9325. }
  9326. }
  9327. /* Decodes a 32-bit varint from the current buffer position.
  9328. * Returns a status code as described in decoder.int.h. */
  9329. UPB_FORCEINLINE static int32_t decode_v32(upb_pbdecoder *d, uint32_t *u32) {
  9330. uint64_t u64;
  9331. int32_t ret = decode_varint(d, &u64);
  9332. if (ret >= 0) return ret;
  9333. if (u64 > UINT32_MAX) {
  9334. seterr(d, "Unterminated 32-bit varint");
  9335. /* TODO(haberman) guarantee that this function return is >= 0 somehow,
  9336. * so we know this path will always be treated as error by our caller.
  9337. * Right now the size_t -> int32_t can overflow and produce negative values.
  9338. */
  9339. *u32 = 0;
  9340. return upb_pbdecoder_suspend(d);
  9341. }
  9342. *u32 = u64;
  9343. return DECODE_OK;
  9344. }
  9345. /* Decodes a fixed32 from the current buffer position.
  9346. * Returns a status code as described in decoder.int.h.
  9347. * TODO: proper byte swapping for big-endian machines. */
  9348. UPB_FORCEINLINE static int32_t decode_fixed32(upb_pbdecoder *d, uint32_t *u32) {
  9349. return getbytes(d, u32, 4);
  9350. }
  9351. /* Decodes a fixed64 from the current buffer position.
  9352. * Returns a status code as described in decoder.int.h.
  9353. * TODO: proper byte swapping for big-endian machines. */
  9354. UPB_FORCEINLINE static int32_t decode_fixed64(upb_pbdecoder *d, uint64_t *u64) {
  9355. return getbytes(d, u64, 8);
  9356. }
  9357. /* Non-static versions of the above functions.
  9358. * These are called by the JIT for fallback paths. */
  9359. int32_t upb_pbdecoder_decode_f32(upb_pbdecoder *d, uint32_t *u32) {
  9360. return decode_fixed32(d, u32);
  9361. }
  9362. int32_t upb_pbdecoder_decode_f64(upb_pbdecoder *d, uint64_t *u64) {
  9363. return decode_fixed64(d, u64);
  9364. }
  9365. static double as_double(uint64_t n) { double d; memcpy(&d, &n, 8); return d; }
  9366. static float as_float(uint32_t n) { float f; memcpy(&f, &n, 4); return f; }
  9367. /* Pushes a frame onto the decoder stack. */
  9368. static bool decoder_push(upb_pbdecoder *d, uint64_t end) {
  9369. upb_pbdecoder_frame *fr = d->top;
  9370. if (end > fr->end_ofs) {
  9371. seterr(d, kPbDecoderSubmessageTooLong);
  9372. return false;
  9373. } else if (fr == d->limit) {
  9374. seterr(d, kPbDecoderStackOverflow);
  9375. return false;
  9376. }
  9377. fr++;
  9378. fr->end_ofs = end;
  9379. fr->dispatch = NULL;
  9380. fr->groupnum = 0;
  9381. d->top = fr;
  9382. return true;
  9383. }
  9384. static bool pushtagdelim(upb_pbdecoder *d, uint32_t arg) {
  9385. /* While we expect to see an "end" tag (either ENDGROUP or a non-sequence
  9386. * field number) prior to hitting any enclosing submessage end, pushing our
  9387. * existing delim end prevents us from continuing to parse values from a
  9388. * corrupt proto that doesn't give us an END tag in time. */
  9389. if (!decoder_push(d, d->top->end_ofs))
  9390. return false;
  9391. d->top->groupnum = arg;
  9392. return true;
  9393. }
  9394. /* Pops a frame from the decoder stack. */
  9395. static void decoder_pop(upb_pbdecoder *d) { d->top--; }
  9396. UPB_NOINLINE int32_t upb_pbdecoder_checktag_slow(upb_pbdecoder *d,
  9397. uint64_t expected) {
  9398. uint64_t data = 0;
  9399. size_t bytes = upb_value_size(expected);
  9400. size_t read = peekbytes(d, &data, bytes);
  9401. if (read == bytes && data == expected) {
  9402. /* Advance past matched bytes. */
  9403. int32_t ok = getbytes(d, &data, read);
  9404. UPB_ASSERT(ok < 0);
  9405. return DECODE_OK;
  9406. } else if (read < bytes && memcmp(&data, &expected, read) == 0) {
  9407. return suspend_save(d);
  9408. } else {
  9409. return DECODE_MISMATCH;
  9410. }
  9411. }
  9412. int32_t upb_pbdecoder_skipunknown(upb_pbdecoder *d, int32_t fieldnum,
  9413. uint8_t wire_type) {
  9414. if (fieldnum >= 0)
  9415. goto have_tag;
  9416. while (true) {
  9417. uint32_t tag;
  9418. CHECK_RETURN(decode_v32(d, &tag));
  9419. wire_type = tag & 0x7;
  9420. fieldnum = tag >> 3;
  9421. have_tag:
  9422. if (fieldnum == 0) {
  9423. seterr(d, "Saw invalid field number (0)");
  9424. return upb_pbdecoder_suspend(d);
  9425. }
  9426. switch (wire_type) {
  9427. case UPB_WIRE_TYPE_32BIT:
  9428. CHECK_RETURN(skip(d, 4));
  9429. break;
  9430. case UPB_WIRE_TYPE_64BIT:
  9431. CHECK_RETURN(skip(d, 8));
  9432. break;
  9433. case UPB_WIRE_TYPE_VARINT: {
  9434. uint64_t u64;
  9435. CHECK_RETURN(decode_varint(d, &u64));
  9436. break;
  9437. }
  9438. case UPB_WIRE_TYPE_DELIMITED: {
  9439. uint32_t len;
  9440. CHECK_RETURN(decode_v32(d, &len));
  9441. CHECK_RETURN(skip(d, len));
  9442. break;
  9443. }
  9444. case UPB_WIRE_TYPE_START_GROUP:
  9445. CHECK_SUSPEND(pushtagdelim(d, -fieldnum));
  9446. break;
  9447. case UPB_WIRE_TYPE_END_GROUP:
  9448. if (fieldnum == -d->top->groupnum) {
  9449. decoder_pop(d);
  9450. } else if (fieldnum == d->top->groupnum) {
  9451. return DECODE_ENDGROUP;
  9452. } else {
  9453. seterr(d, "Unmatched ENDGROUP tag.");
  9454. return upb_pbdecoder_suspend(d);
  9455. }
  9456. break;
  9457. default:
  9458. seterr(d, "Invalid wire type");
  9459. return upb_pbdecoder_suspend(d);
  9460. }
  9461. if (d->top->groupnum >= 0) {
  9462. /* TODO: More code needed for handling unknown groups. */
  9463. upb_sink_putunknown(&d->top->sink, d->checkpoint, d->ptr - d->checkpoint);
  9464. return DECODE_OK;
  9465. }
  9466. /* Unknown group -- continue looping over unknown fields. */
  9467. checkpoint(d);
  9468. }
  9469. }
  9470. static void goto_endmsg(upb_pbdecoder *d) {
  9471. upb_value v;
  9472. bool found = upb_inttable_lookup32(d->top->dispatch, DISPATCH_ENDMSG, &v);
  9473. UPB_ASSERT(found);
  9474. d->pc = d->top->base + upb_value_getuint64(v);
  9475. }
  9476. /* Parses a tag and jumps to the corresponding bytecode instruction for this
  9477. * field.
  9478. *
  9479. * If the tag is unknown (or the wire type doesn't match), parses the field as
  9480. * unknown. If the tag is a valid ENDGROUP tag, jumps to the bytecode
  9481. * instruction for the end of message. */
  9482. static int32_t dispatch(upb_pbdecoder *d) {
  9483. upb_inttable *dispatch = d->top->dispatch;
  9484. uint32_t tag;
  9485. uint8_t wire_type;
  9486. uint32_t fieldnum;
  9487. upb_value val;
  9488. int32_t retval;
  9489. /* Decode tag. */
  9490. CHECK_RETURN(decode_v32(d, &tag));
  9491. wire_type = tag & 0x7;
  9492. fieldnum = tag >> 3;
  9493. /* Lookup tag. Because of packed/non-packed compatibility, we have to
  9494. * check the wire type against two possibilities. */
  9495. if (fieldnum != DISPATCH_ENDMSG &&
  9496. upb_inttable_lookup32(dispatch, fieldnum, &val)) {
  9497. uint64_t v = upb_value_getuint64(val);
  9498. if (wire_type == (v & 0xff)) {
  9499. d->pc = d->top->base + (v >> 16);
  9500. return DECODE_OK;
  9501. } else if (wire_type == ((v >> 8) & 0xff)) {
  9502. bool found =
  9503. upb_inttable_lookup(dispatch, fieldnum + UPB_MAX_FIELDNUMBER, &val);
  9504. UPB_ASSERT(found);
  9505. d->pc = d->top->base + upb_value_getuint64(val);
  9506. return DECODE_OK;
  9507. }
  9508. }
  9509. /* We have some unknown fields (or ENDGROUP) to parse. The DISPATCH or TAG
  9510. * bytecode that triggered this is preceded by a CHECKDELIM bytecode which
  9511. * we need to back up to, so that when we're done skipping unknown data we
  9512. * can re-check the delimited end. */
  9513. d->last--; /* Necessary if we get suspended */
  9514. d->pc = d->last;
  9515. UPB_ASSERT(getop(*d->last) == OP_CHECKDELIM);
  9516. /* Unknown field or ENDGROUP. */
  9517. retval = upb_pbdecoder_skipunknown(d, fieldnum, wire_type);
  9518. CHECK_RETURN(retval);
  9519. if (retval == DECODE_ENDGROUP) {
  9520. goto_endmsg(d);
  9521. return DECODE_OK;
  9522. }
  9523. return DECODE_OK;
  9524. }
  9525. /* Callers know that the stack is more than one deep because the opcodes that
  9526. * call this only occur after PUSH operations. */
  9527. upb_pbdecoder_frame *outer_frame(upb_pbdecoder *d) {
  9528. UPB_ASSERT(d->top != d->stack);
  9529. return d->top - 1;
  9530. }
  9531. /* The main decoding loop *****************************************************/
  9532. /* The main decoder VM function. Uses traditional bytecode dispatch loop with a
  9533. * switch() statement. */
  9534. size_t run_decoder_vm(upb_pbdecoder *d, const mgroup *group,
  9535. const upb_bufhandle* handle) {
  9536. #define VMCASE(op, code) \
  9537. case op: { code; if (consumes_input(op)) checkpoint(d); break; }
  9538. #define PRIMITIVE_OP(type, wt, name, convfunc, ctype) \
  9539. VMCASE(OP_PARSE_ ## type, { \
  9540. ctype val; \
  9541. CHECK_RETURN(decode_ ## wt(d, &val)); \
  9542. upb_sink_put ## name(&d->top->sink, arg, (convfunc)(val)); \
  9543. })
  9544. while(1) {
  9545. int32_t instruction;
  9546. opcode op;
  9547. uint32_t arg;
  9548. int32_t longofs;
  9549. d->last = d->pc;
  9550. instruction = *d->pc++;
  9551. op = getop(instruction);
  9552. arg = instruction >> 8;
  9553. longofs = arg;
  9554. UPB_ASSERT(d->ptr != d->residual_end);
  9555. UPB_UNUSED(group);
  9556. #ifdef UPB_DUMP_BYTECODE
  9557. fprintf(stderr, "s_ofs=%d buf_ofs=%d data_rem=%d buf_rem=%d delim_rem=%d "
  9558. "%x %s (%d)\n",
  9559. (int)offset(d),
  9560. (int)(d->ptr - d->buf),
  9561. (int)(d->data_end - d->ptr),
  9562. (int)(d->end - d->ptr),
  9563. (int)((d->top->end_ofs - d->bufstart_ofs) - (d->ptr - d->buf)),
  9564. (int)(d->pc - 1 - group->bytecode),
  9565. upb_pbdecoder_getopname(op),
  9566. arg);
  9567. #endif
  9568. switch (op) {
  9569. /* Technically, we are losing data if we see a 32-bit varint that is not
  9570. * properly sign-extended. We could detect this and error about the data
  9571. * loss, but proto2 does not do this, so we pass. */
  9572. PRIMITIVE_OP(INT32, varint, int32, int32_t, uint64_t)
  9573. PRIMITIVE_OP(INT64, varint, int64, int64_t, uint64_t)
  9574. PRIMITIVE_OP(UINT32, varint, uint32, uint32_t, uint64_t)
  9575. PRIMITIVE_OP(UINT64, varint, uint64, uint64_t, uint64_t)
  9576. PRIMITIVE_OP(FIXED32, fixed32, uint32, uint32_t, uint32_t)
  9577. PRIMITIVE_OP(FIXED64, fixed64, uint64, uint64_t, uint64_t)
  9578. PRIMITIVE_OP(SFIXED32, fixed32, int32, int32_t, uint32_t)
  9579. PRIMITIVE_OP(SFIXED64, fixed64, int64, int64_t, uint64_t)
  9580. PRIMITIVE_OP(BOOL, varint, bool, bool, uint64_t)
  9581. PRIMITIVE_OP(DOUBLE, fixed64, double, as_double, uint64_t)
  9582. PRIMITIVE_OP(FLOAT, fixed32, float, as_float, uint32_t)
  9583. PRIMITIVE_OP(SINT32, varint, int32, upb_zzdec_32, uint64_t)
  9584. PRIMITIVE_OP(SINT64, varint, int64, upb_zzdec_64, uint64_t)
  9585. VMCASE(OP_SETDISPATCH,
  9586. d->top->base = d->pc - 1;
  9587. memcpy(&d->top->dispatch, d->pc, sizeof(void*));
  9588. d->pc += sizeof(void*) / sizeof(uint32_t);
  9589. )
  9590. VMCASE(OP_STARTMSG,
  9591. CHECK_SUSPEND(upb_sink_startmsg(&d->top->sink));
  9592. )
  9593. VMCASE(OP_ENDMSG,
  9594. CHECK_SUSPEND(upb_sink_endmsg(&d->top->sink, d->status));
  9595. )
  9596. VMCASE(OP_STARTSEQ,
  9597. upb_pbdecoder_frame *outer = outer_frame(d);
  9598. CHECK_SUSPEND(upb_sink_startseq(&outer->sink, arg, &d->top->sink));
  9599. )
  9600. VMCASE(OP_ENDSEQ,
  9601. CHECK_SUSPEND(upb_sink_endseq(&d->top->sink, arg));
  9602. )
  9603. VMCASE(OP_STARTSUBMSG,
  9604. upb_pbdecoder_frame *outer = outer_frame(d);
  9605. CHECK_SUSPEND(upb_sink_startsubmsg(&outer->sink, arg, &d->top->sink));
  9606. )
  9607. VMCASE(OP_ENDSUBMSG,
  9608. CHECK_SUSPEND(upb_sink_endsubmsg(&d->top->sink, arg));
  9609. )
  9610. VMCASE(OP_STARTSTR,
  9611. uint32_t len = delim_remaining(d);
  9612. upb_pbdecoder_frame *outer = outer_frame(d);
  9613. CHECK_SUSPEND(upb_sink_startstr(&outer->sink, arg, len, &d->top->sink));
  9614. if (len == 0) {
  9615. d->pc++; /* Skip OP_STRING. */
  9616. }
  9617. )
  9618. VMCASE(OP_STRING,
  9619. uint32_t len = curbufleft(d);
  9620. size_t n = upb_sink_putstring(&d->top->sink, arg, d->ptr, len, handle);
  9621. if (n > len) {
  9622. if (n > delim_remaining(d)) {
  9623. seterr(d, "Tried to skip past end of string.");
  9624. return upb_pbdecoder_suspend(d);
  9625. } else {
  9626. int32_t ret = skip(d, n);
  9627. /* This shouldn't return DECODE_OK, because n > len. */
  9628. UPB_ASSERT(ret >= 0);
  9629. return ret;
  9630. }
  9631. }
  9632. advance(d, n);
  9633. if (n < len || d->delim_end == NULL) {
  9634. /* We aren't finished with this string yet. */
  9635. d->pc--; /* Repeat OP_STRING. */
  9636. if (n > 0) checkpoint(d);
  9637. return upb_pbdecoder_suspend(d);
  9638. }
  9639. )
  9640. VMCASE(OP_ENDSTR,
  9641. CHECK_SUSPEND(upb_sink_endstr(&d->top->sink, arg));
  9642. )
  9643. VMCASE(OP_PUSHTAGDELIM,
  9644. CHECK_SUSPEND(pushtagdelim(d, arg));
  9645. )
  9646. VMCASE(OP_SETBIGGROUPNUM,
  9647. d->top->groupnum = *d->pc++;
  9648. )
  9649. VMCASE(OP_POP,
  9650. UPB_ASSERT(d->top > d->stack);
  9651. decoder_pop(d);
  9652. )
  9653. VMCASE(OP_PUSHLENDELIM,
  9654. uint32_t len;
  9655. CHECK_RETURN(decode_v32(d, &len));
  9656. CHECK_SUSPEND(decoder_push(d, offset(d) + len));
  9657. set_delim_end(d);
  9658. )
  9659. VMCASE(OP_SETDELIM,
  9660. set_delim_end(d);
  9661. )
  9662. VMCASE(OP_CHECKDELIM,
  9663. /* We are guaranteed of this assert because we never allow ourselves to
  9664. * consume bytes beyond data_end, which covers delim_end when non-NULL.
  9665. */
  9666. UPB_ASSERT(!(d->delim_end && d->ptr > d->delim_end));
  9667. if (d->ptr == d->delim_end)
  9668. d->pc += longofs;
  9669. )
  9670. VMCASE(OP_CALL,
  9671. d->callstack[d->call_len++] = d->pc;
  9672. d->pc += longofs;
  9673. )
  9674. VMCASE(OP_RET,
  9675. UPB_ASSERT(d->call_len > 0);
  9676. d->pc = d->callstack[--d->call_len];
  9677. )
  9678. VMCASE(OP_BRANCH,
  9679. d->pc += longofs;
  9680. )
  9681. VMCASE(OP_TAG1,
  9682. uint8_t expected;
  9683. CHECK_SUSPEND(curbufleft(d) > 0);
  9684. expected = (arg >> 8) & 0xff;
  9685. if (*d->ptr == expected) {
  9686. advance(d, 1);
  9687. } else {
  9688. int8_t shortofs;
  9689. badtag:
  9690. shortofs = arg;
  9691. if (shortofs == LABEL_DISPATCH) {
  9692. CHECK_RETURN(dispatch(d));
  9693. } else {
  9694. d->pc += shortofs;
  9695. break; /* Avoid checkpoint(). */
  9696. }
  9697. }
  9698. )
  9699. VMCASE(OP_TAG2,
  9700. uint16_t expected;
  9701. CHECK_SUSPEND(curbufleft(d) > 0);
  9702. expected = (arg >> 8) & 0xffff;
  9703. if (curbufleft(d) >= 2) {
  9704. uint16_t actual;
  9705. memcpy(&actual, d->ptr, 2);
  9706. if (expected == actual) {
  9707. advance(d, 2);
  9708. } else {
  9709. goto badtag;
  9710. }
  9711. } else {
  9712. int32_t result = upb_pbdecoder_checktag_slow(d, expected);
  9713. if (result == DECODE_MISMATCH) goto badtag;
  9714. if (result >= 0) return result;
  9715. }
  9716. )
  9717. VMCASE(OP_TAGN, {
  9718. uint64_t expected;
  9719. int32_t result;
  9720. memcpy(&expected, d->pc, 8);
  9721. d->pc += 2;
  9722. result = upb_pbdecoder_checktag_slow(d, expected);
  9723. if (result == DECODE_MISMATCH) goto badtag;
  9724. if (result >= 0) return result;
  9725. })
  9726. VMCASE(OP_DISPATCH, {
  9727. CHECK_RETURN(dispatch(d));
  9728. })
  9729. VMCASE(OP_HALT, {
  9730. return d->size_param;
  9731. })
  9732. }
  9733. }
  9734. }
  9735. /* BytesHandler handlers ******************************************************/
  9736. void *upb_pbdecoder_startbc(void *closure, const void *pc, size_t size_hint) {
  9737. upb_pbdecoder *d = closure;
  9738. UPB_UNUSED(size_hint);
  9739. d->top->end_ofs = UINT64_MAX;
  9740. d->bufstart_ofs = 0;
  9741. d->call_len = 1;
  9742. d->callstack[0] = &halt;
  9743. d->pc = pc;
  9744. d->skip = 0;
  9745. return d;
  9746. }
  9747. void *upb_pbdecoder_startjit(void *closure, const void *hd, size_t size_hint) {
  9748. upb_pbdecoder *d = closure;
  9749. UPB_UNUSED(hd);
  9750. UPB_UNUSED(size_hint);
  9751. d->top->end_ofs = UINT64_MAX;
  9752. d->bufstart_ofs = 0;
  9753. d->call_len = 0;
  9754. d->skip = 0;
  9755. return d;
  9756. }
  9757. bool upb_pbdecoder_end(void *closure, const void *handler_data) {
  9758. upb_pbdecoder *d = closure;
  9759. const upb_pbdecodermethod *method = handler_data;
  9760. uint64_t end;
  9761. char dummy;
  9762. if (d->residual_end > d->residual) {
  9763. seterr(d, "Unexpected EOF: decoder still has buffered unparsed data");
  9764. return false;
  9765. }
  9766. if (d->skip) {
  9767. seterr(d, "Unexpected EOF inside skipped data");
  9768. return false;
  9769. }
  9770. if (d->top->end_ofs != UINT64_MAX) {
  9771. seterr(d, "Unexpected EOF inside delimited string");
  9772. return false;
  9773. }
  9774. /* The user's end() call indicates that the message ends here. */
  9775. end = offset(d);
  9776. d->top->end_ofs = end;
  9777. #ifdef UPB_USE_JIT_X64
  9778. if (method->is_native_) {
  9779. const mgroup *group = (const mgroup*)method->group;
  9780. if (d->top != d->stack)
  9781. d->stack->end_ofs = 0;
  9782. group->jit_code(closure, method->code_base.ptr, &dummy, 0, NULL);
  9783. } else
  9784. #endif
  9785. {
  9786. const uint32_t *p = d->pc;
  9787. d->stack->end_ofs = end;
  9788. /* Check the previous bytecode, but guard against beginning. */
  9789. if (p != method->code_base.ptr) p--;
  9790. if (getop(*p) == OP_CHECKDELIM) {
  9791. /* Rewind from OP_TAG* to OP_CHECKDELIM. */
  9792. UPB_ASSERT(getop(*d->pc) == OP_TAG1 ||
  9793. getop(*d->pc) == OP_TAG2 ||
  9794. getop(*d->pc) == OP_TAGN ||
  9795. getop(*d->pc) == OP_DISPATCH);
  9796. d->pc = p;
  9797. }
  9798. upb_pbdecoder_decode(closure, handler_data, &dummy, 0, NULL);
  9799. }
  9800. if (d->call_len != 0) {
  9801. seterr(d, "Unexpected EOF inside submessage or group");
  9802. return false;
  9803. }
  9804. return true;
  9805. }
  9806. size_t upb_pbdecoder_decode(void *decoder, const void *group, const char *buf,
  9807. size_t size, const upb_bufhandle *handle) {
  9808. int32_t result = upb_pbdecoder_resume(decoder, NULL, buf, size, handle);
  9809. if (result == DECODE_ENDGROUP) goto_endmsg(decoder);
  9810. CHECK_RETURN(result);
  9811. return run_decoder_vm(decoder, group, handle);
  9812. }
  9813. /* Public API *****************************************************************/
  9814. void upb_pbdecoder_reset(upb_pbdecoder *d) {
  9815. d->top = d->stack;
  9816. d->top->groupnum = 0;
  9817. d->ptr = d->residual;
  9818. d->buf = d->residual;
  9819. d->end = d->residual;
  9820. d->residual_end = d->residual;
  9821. }
  9822. upb_pbdecoder *upb_pbdecoder_create(upb_env *e, const upb_pbdecodermethod *m,
  9823. upb_sink *sink) {
  9824. const size_t default_max_nesting = 64;
  9825. #ifndef NDEBUG
  9826. size_t size_before = upb_env_bytesallocated(e);
  9827. #endif
  9828. upb_pbdecoder *d = upb_env_malloc(e, sizeof(upb_pbdecoder));
  9829. if (!d) return NULL;
  9830. d->method_ = m;
  9831. d->callstack = upb_env_malloc(e, callstacksize(d, default_max_nesting));
  9832. d->stack = upb_env_malloc(e, stacksize(d, default_max_nesting));
  9833. if (!d->stack || !d->callstack) {
  9834. return NULL;
  9835. }
  9836. d->env = e;
  9837. d->limit = d->stack + default_max_nesting - 1;
  9838. d->stack_size = default_max_nesting;
  9839. d->status = NULL;
  9840. upb_pbdecoder_reset(d);
  9841. upb_bytessink_reset(&d->input_, &m->input_handler_, d);
  9842. UPB_ASSERT(sink);
  9843. if (d->method_->dest_handlers_) {
  9844. if (sink->handlers != d->method_->dest_handlers_)
  9845. return NULL;
  9846. }
  9847. upb_sink_reset(&d->top->sink, sink->handlers, sink->closure);
  9848. /* If this fails, increase the value in decoder.h. */
  9849. UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(e) - size_before <=
  9850. UPB_PB_DECODER_SIZE);
  9851. return d;
  9852. }
  9853. uint64_t upb_pbdecoder_bytesparsed(const upb_pbdecoder *d) {
  9854. return offset(d);
  9855. }
  9856. const upb_pbdecodermethod *upb_pbdecoder_method(const upb_pbdecoder *d) {
  9857. return d->method_;
  9858. }
  9859. upb_bytessink *upb_pbdecoder_input(upb_pbdecoder *d) {
  9860. return &d->input_;
  9861. }
  9862. size_t upb_pbdecoder_maxnesting(const upb_pbdecoder *d) {
  9863. return d->stack_size;
  9864. }
  9865. bool upb_pbdecoder_setmaxnesting(upb_pbdecoder *d, size_t max) {
  9866. UPB_ASSERT(d->top >= d->stack);
  9867. if (max < (size_t)(d->top - d->stack)) {
  9868. /* Can't set a limit smaller than what we are currently at. */
  9869. return false;
  9870. }
  9871. if (max > d->stack_size) {
  9872. /* Need to reallocate stack and callstack to accommodate. */
  9873. size_t old_size = stacksize(d, d->stack_size);
  9874. size_t new_size = stacksize(d, max);
  9875. void *p = upb_env_realloc(d->env, d->stack, old_size, new_size);
  9876. if (!p) {
  9877. return false;
  9878. }
  9879. d->stack = p;
  9880. old_size = callstacksize(d, d->stack_size);
  9881. new_size = callstacksize(d, max);
  9882. p = upb_env_realloc(d->env, d->callstack, old_size, new_size);
  9883. if (!p) {
  9884. return false;
  9885. }
  9886. d->callstack = p;
  9887. d->stack_size = max;
  9888. }
  9889. d->limit = d->stack + max - 1;
  9890. return true;
  9891. }
  9892. /*
  9893. ** upb::Encoder
  9894. **
  9895. ** Since we are implementing pure handlers (ie. without any out-of-band access
  9896. ** to pre-computed lengths), we have to buffer all submessages before we can
  9897. ** emit even their first byte.
  9898. **
  9899. ** Not knowing the size of submessages also means we can't write a perfect
  9900. ** zero-copy implementation, even with buffering. Lengths are stored as
  9901. ** varints, which means that we don't know how many bytes to reserve for the
  9902. ** length until we know what the length is.
  9903. **
  9904. ** This leaves us with three main choices:
  9905. **
  9906. ** 1. buffer all submessage data in a temporary buffer, then copy it exactly
  9907. ** once into the output buffer.
  9908. **
  9909. ** 2. attempt to buffer data directly into the output buffer, estimating how
  9910. ** many bytes each length will take. When our guesses are wrong, use
  9911. ** memmove() to grow or shrink the allotted space.
  9912. **
  9913. ** 3. buffer directly into the output buffer, allocating a max length
  9914. ** ahead-of-time for each submessage length. If we overallocated, we waste
  9915. ** space, but no memcpy() or memmove() is required. This approach requires
  9916. ** defining a maximum size for submessages and rejecting submessages that
  9917. ** exceed that size.
  9918. **
  9919. ** (2) and (3) have the potential to have better performance, but they are more
  9920. ** complicated and subtle to implement:
  9921. **
  9922. ** (3) requires making an arbitrary choice of the maximum message size; it
  9923. ** wastes space when submessages are shorter than this and fails
  9924. ** completely when they are longer. This makes it more finicky and
  9925. ** requires configuration based on the input. It also makes it impossible
  9926. ** to perfectly match the output of reference encoders that always use the
  9927. ** optimal amount of space for each length.
  9928. **
  9929. ** (2) requires guessing the the size upfront, and if multiple lengths are
  9930. ** guessed wrong the minimum required number of memmove() operations may
  9931. ** be complicated to compute correctly. Implemented properly, it may have
  9932. ** a useful amortized or average cost, but more investigation is required
  9933. ** to determine this and what the optimal algorithm is to achieve it.
  9934. **
  9935. ** (1) makes you always pay for exactly one copy, but its implementation is
  9936. ** the simplest and its performance is predictable.
  9937. **
  9938. ** So for now, we implement (1) only. If we wish to optimize later, we should
  9939. ** be able to do it without affecting users.
  9940. **
  9941. ** The strategy is to buffer the segments of data that do *not* depend on
  9942. ** unknown lengths in one buffer, and keep a separate buffer of segment pointers
  9943. ** and lengths. When the top-level submessage ends, we can go beginning to end,
  9944. ** alternating the writing of lengths with memcpy() of the rest of the data.
  9945. ** At the top level though, no buffering is required.
  9946. */
  9947. /* The output buffer is divided into segments; a segment is a string of data
  9948. * that is "ready to go" -- it does not need any varint lengths inserted into
  9949. * the middle. The seams between segments are where varints will be inserted
  9950. * once they are known.
  9951. *
  9952. * We also use the concept of a "run", which is a range of encoded bytes that
  9953. * occur at a single submessage level. Every segment contains one or more runs.
  9954. *
  9955. * A segment can span messages. Consider:
  9956. *
  9957. * .--Submessage lengths---------.
  9958. * | | |
  9959. * | V V
  9960. * V | |--------------- | |-----------------
  9961. * Submessages: | |-----------------------------------------------
  9962. * Top-level msg: ------------------------------------------------------------
  9963. *
  9964. * Segments: ----- ------------------- -----------------
  9965. * Runs: *---- *--------------*--- *----------------
  9966. * (* marks the start)
  9967. *
  9968. * Note that the top-level menssage is not in any segment because it does not
  9969. * have any length preceding it.
  9970. *
  9971. * A segment is only interrupted when another length needs to be inserted. So
  9972. * observe how the second segment spans both the inner submessage and part of
  9973. * the next enclosing message. */
  9974. typedef struct {
  9975. uint32_t msglen; /* The length to varint-encode before this segment. */
  9976. uint32_t seglen; /* Length of the segment. */
  9977. } upb_pb_encoder_segment;
  9978. struct upb_pb_encoder {
  9979. upb_env *env;
  9980. /* Our input and output. */
  9981. upb_sink input_;
  9982. upb_bytessink *output_;
  9983. /* The "subclosure" -- used as the inner closure as part of the bytessink
  9984. * protocol. */
  9985. void *subc;
  9986. /* The output buffer and limit, and our current write position. "buf"
  9987. * initially points to "initbuf", but is dynamically allocated if we need to
  9988. * grow beyond the initial size. */
  9989. char *buf, *ptr, *limit;
  9990. /* The beginning of the current run, or undefined if we are at the top
  9991. * level. */
  9992. char *runbegin;
  9993. /* The list of segments we are accumulating. */
  9994. upb_pb_encoder_segment *segbuf, *segptr, *seglimit;
  9995. /* The stack of enclosing submessages. Each entry in the stack points to the
  9996. * segment where this submessage's length is being accumulated. */
  9997. int *stack, *top, *stacklimit;
  9998. /* Depth of startmsg/endmsg calls. */
  9999. int depth;
  10000. };
  10001. /* low-level buffering ********************************************************/
  10002. /* Low-level functions for interacting with the output buffer. */
  10003. /* TODO(haberman): handle pushback */
  10004. static void putbuf(upb_pb_encoder *e, const char *buf, size_t len) {
  10005. size_t n = upb_bytessink_putbuf(e->output_, e->subc, buf, len, NULL);
  10006. UPB_ASSERT(n == len);
  10007. }
  10008. static upb_pb_encoder_segment *top(upb_pb_encoder *e) {
  10009. return &e->segbuf[*e->top];
  10010. }
  10011. /* Call to ensure that at least "bytes" bytes are available for writing at
  10012. * e->ptr. Returns false if the bytes could not be allocated. */
  10013. static bool reserve(upb_pb_encoder *e, size_t bytes) {
  10014. if ((size_t)(e->limit - e->ptr) < bytes) {
  10015. /* Grow buffer. */
  10016. char *new_buf;
  10017. size_t needed = bytes + (e->ptr - e->buf);
  10018. size_t old_size = e->limit - e->buf;
  10019. size_t new_size = old_size;
  10020. while (new_size < needed) {
  10021. new_size *= 2;
  10022. }
  10023. new_buf = upb_env_realloc(e->env, e->buf, old_size, new_size);
  10024. if (new_buf == NULL) {
  10025. return false;
  10026. }
  10027. e->ptr = new_buf + (e->ptr - e->buf);
  10028. e->runbegin = new_buf + (e->runbegin - e->buf);
  10029. e->limit = new_buf + new_size;
  10030. e->buf = new_buf;
  10031. }
  10032. return true;
  10033. }
  10034. /* Call when "bytes" bytes have been writte at e->ptr. The caller *must* have
  10035. * previously called reserve() with at least this many bytes. */
  10036. static void encoder_advance(upb_pb_encoder *e, size_t bytes) {
  10037. UPB_ASSERT((size_t)(e->limit - e->ptr) >= bytes);
  10038. e->ptr += bytes;
  10039. }
  10040. /* Call when all of the bytes for a handler have been written. Flushes the
  10041. * bytes if possible and necessary, returning false if this failed. */
  10042. static bool commit(upb_pb_encoder *e) {
  10043. if (!e->top) {
  10044. /* We aren't inside a delimited region. Flush our accumulated bytes to
  10045. * the output.
  10046. *
  10047. * TODO(haberman): in the future we may want to delay flushing for
  10048. * efficiency reasons. */
  10049. putbuf(e, e->buf, e->ptr - e->buf);
  10050. e->ptr = e->buf;
  10051. }
  10052. return true;
  10053. }
  10054. /* Writes the given bytes to the buffer, handling reserve/advance. */
  10055. static bool encode_bytes(upb_pb_encoder *e, const void *data, size_t len) {
  10056. if (!reserve(e, len)) {
  10057. return false;
  10058. }
  10059. memcpy(e->ptr, data, len);
  10060. encoder_advance(e, len);
  10061. return true;
  10062. }
  10063. /* Finish the current run by adding the run totals to the segment and message
  10064. * length. */
  10065. static void accumulate(upb_pb_encoder *e) {
  10066. size_t run_len;
  10067. UPB_ASSERT(e->ptr >= e->runbegin);
  10068. run_len = e->ptr - e->runbegin;
  10069. e->segptr->seglen += run_len;
  10070. top(e)->msglen += run_len;
  10071. e->runbegin = e->ptr;
  10072. }
  10073. /* Call to indicate the start of delimited region for which the full length is
  10074. * not yet known. All data will be buffered until the length is known.
  10075. * Delimited regions may be nested; their lengths will all be tracked properly. */
  10076. static bool start_delim(upb_pb_encoder *e) {
  10077. if (e->top) {
  10078. /* We are already buffering, advance to the next segment and push it on the
  10079. * stack. */
  10080. accumulate(e);
  10081. if (++e->top == e->stacklimit) {
  10082. /* TODO(haberman): grow stack? */
  10083. return false;
  10084. }
  10085. if (++e->segptr == e->seglimit) {
  10086. /* Grow segment buffer. */
  10087. size_t old_size =
  10088. (e->seglimit - e->segbuf) * sizeof(upb_pb_encoder_segment);
  10089. size_t new_size = old_size * 2;
  10090. upb_pb_encoder_segment *new_buf =
  10091. upb_env_realloc(e->env, e->segbuf, old_size, new_size);
  10092. if (new_buf == NULL) {
  10093. return false;
  10094. }
  10095. e->segptr = new_buf + (e->segptr - e->segbuf);
  10096. e->seglimit = new_buf + (new_size / sizeof(upb_pb_encoder_segment));
  10097. e->segbuf = new_buf;
  10098. }
  10099. } else {
  10100. /* We were previously at the top level, start buffering. */
  10101. e->segptr = e->segbuf;
  10102. e->top = e->stack;
  10103. e->runbegin = e->ptr;
  10104. }
  10105. *e->top = e->segptr - e->segbuf;
  10106. e->segptr->seglen = 0;
  10107. e->segptr->msglen = 0;
  10108. return true;
  10109. }
  10110. /* Call to indicate the end of a delimited region. We now know the length of
  10111. * the delimited region. If we are not nested inside any other delimited
  10112. * regions, we can now emit all of the buffered data we accumulated. */
  10113. static bool end_delim(upb_pb_encoder *e) {
  10114. size_t msglen;
  10115. accumulate(e);
  10116. msglen = top(e)->msglen;
  10117. if (e->top == e->stack) {
  10118. /* All lengths are now available, emit all buffered data. */
  10119. char buf[UPB_PB_VARINT_MAX_LEN];
  10120. upb_pb_encoder_segment *s;
  10121. const char *ptr = e->buf;
  10122. for (s = e->segbuf; s <= e->segptr; s++) {
  10123. size_t lenbytes = upb_vencode64(s->msglen, buf);
  10124. putbuf(e, buf, lenbytes);
  10125. putbuf(e, ptr, s->seglen);
  10126. ptr += s->seglen;
  10127. }
  10128. e->ptr = e->buf;
  10129. e->top = NULL;
  10130. } else {
  10131. /* Need to keep buffering; propagate length info into enclosing
  10132. * submessages. */
  10133. --e->top;
  10134. top(e)->msglen += msglen + upb_varint_size(msglen);
  10135. }
  10136. return true;
  10137. }
  10138. /* tag_t **********************************************************************/
  10139. /* A precomputed (pre-encoded) tag and length. */
  10140. typedef struct {
  10141. uint8_t bytes;
  10142. char tag[7];
  10143. } tag_t;
  10144. /* Allocates a new tag for this field, and sets it in these handlerattr. */
  10145. static void new_tag(upb_handlers *h, const upb_fielddef *f, upb_wiretype_t wt,
  10146. upb_handlerattr *attr) {
  10147. uint32_t n = upb_fielddef_number(f);
  10148. tag_t *tag = upb_gmalloc(sizeof(tag_t));
  10149. tag->bytes = upb_vencode64((n << 3) | wt, tag->tag);
  10150. upb_handlerattr_init(attr);
  10151. upb_handlerattr_sethandlerdata(attr, tag);
  10152. upb_handlers_addcleanup(h, tag, upb_gfree);
  10153. }
  10154. static bool encode_tag(upb_pb_encoder *e, const tag_t *tag) {
  10155. return encode_bytes(e, tag->tag, tag->bytes);
  10156. }
  10157. /* encoding of wire types *****************************************************/
  10158. static bool encode_fixed64(upb_pb_encoder *e, uint64_t val) {
  10159. /* TODO(haberman): byte-swap for big endian. */
  10160. return encode_bytes(e, &val, sizeof(uint64_t));
  10161. }
  10162. static bool encode_fixed32(upb_pb_encoder *e, uint32_t val) {
  10163. /* TODO(haberman): byte-swap for big endian. */
  10164. return encode_bytes(e, &val, sizeof(uint32_t));
  10165. }
  10166. static bool encode_varint(upb_pb_encoder *e, uint64_t val) {
  10167. if (!reserve(e, UPB_PB_VARINT_MAX_LEN)) {
  10168. return false;
  10169. }
  10170. encoder_advance(e, upb_vencode64(val, e->ptr));
  10171. return true;
  10172. }
  10173. static uint64_t dbl2uint64(double d) {
  10174. uint64_t ret;
  10175. memcpy(&ret, &d, sizeof(uint64_t));
  10176. return ret;
  10177. }
  10178. static uint32_t flt2uint32(float d) {
  10179. uint32_t ret;
  10180. memcpy(&ret, &d, sizeof(uint32_t));
  10181. return ret;
  10182. }
  10183. /* encoding of proto types ****************************************************/
  10184. static bool startmsg(void *c, const void *hd) {
  10185. upb_pb_encoder *e = c;
  10186. UPB_UNUSED(hd);
  10187. if (e->depth++ == 0) {
  10188. upb_bytessink_start(e->output_, 0, &e->subc);
  10189. }
  10190. return true;
  10191. }
  10192. static bool endmsg(void *c, const void *hd, upb_status *status) {
  10193. upb_pb_encoder *e = c;
  10194. UPB_UNUSED(hd);
  10195. UPB_UNUSED(status);
  10196. if (--e->depth == 0) {
  10197. upb_bytessink_end(e->output_);
  10198. }
  10199. return true;
  10200. }
  10201. static void *encode_startdelimfield(void *c, const void *hd) {
  10202. bool ok = encode_tag(c, hd) && commit(c) && start_delim(c);
  10203. return ok ? c : UPB_BREAK;
  10204. }
  10205. static bool encode_unknown(void *c, const void *hd, const char *buf,
  10206. size_t len) {
  10207. UPB_UNUSED(hd);
  10208. return encode_bytes(c, buf, len) && commit(c);
  10209. }
  10210. static bool encode_enddelimfield(void *c, const void *hd) {
  10211. UPB_UNUSED(hd);
  10212. return end_delim(c);
  10213. }
  10214. static void *encode_startgroup(void *c, const void *hd) {
  10215. return (encode_tag(c, hd) && commit(c)) ? c : UPB_BREAK;
  10216. }
  10217. static bool encode_endgroup(void *c, const void *hd) {
  10218. return encode_tag(c, hd) && commit(c);
  10219. }
  10220. static void *encode_startstr(void *c, const void *hd, size_t size_hint) {
  10221. UPB_UNUSED(size_hint);
  10222. return encode_startdelimfield(c, hd);
  10223. }
  10224. static size_t encode_strbuf(void *c, const void *hd, const char *buf,
  10225. size_t len, const upb_bufhandle *h) {
  10226. UPB_UNUSED(hd);
  10227. UPB_UNUSED(h);
  10228. return encode_bytes(c, buf, len) ? len : 0;
  10229. }
  10230. #define T(type, ctype, convert, encode) \
  10231. static bool encode_scalar_##type(void *e, const void *hd, ctype val) { \
  10232. return encode_tag(e, hd) && encode(e, (convert)(val)) && commit(e); \
  10233. } \
  10234. static bool encode_packed_##type(void *e, const void *hd, ctype val) { \
  10235. UPB_UNUSED(hd); \
  10236. return encode(e, (convert)(val)); \
  10237. }
  10238. T(double, double, dbl2uint64, encode_fixed64)
  10239. T(float, float, flt2uint32, encode_fixed32)
  10240. T(int64, int64_t, uint64_t, encode_varint)
  10241. T(int32, int32_t, int64_t, encode_varint)
  10242. T(fixed64, uint64_t, uint64_t, encode_fixed64)
  10243. T(fixed32, uint32_t, uint32_t, encode_fixed32)
  10244. T(bool, bool, bool, encode_varint)
  10245. T(uint32, uint32_t, uint32_t, encode_varint)
  10246. T(uint64, uint64_t, uint64_t, encode_varint)
  10247. T(enum, int32_t, uint32_t, encode_varint)
  10248. T(sfixed32, int32_t, uint32_t, encode_fixed32)
  10249. T(sfixed64, int64_t, uint64_t, encode_fixed64)
  10250. T(sint32, int32_t, upb_zzenc_32, encode_varint)
  10251. T(sint64, int64_t, upb_zzenc_64, encode_varint)
  10252. #undef T
  10253. /* code to build the handlers *************************************************/
  10254. static void newhandlers_callback(const void *closure, upb_handlers *h) {
  10255. const upb_msgdef *m;
  10256. upb_msg_field_iter i;
  10257. UPB_UNUSED(closure);
  10258. upb_handlers_setstartmsg(h, startmsg, NULL);
  10259. upb_handlers_setendmsg(h, endmsg, NULL);
  10260. upb_handlers_setunknown(h, encode_unknown, NULL);
  10261. m = upb_handlers_msgdef(h);
  10262. for(upb_msg_field_begin(&i, m);
  10263. !upb_msg_field_done(&i);
  10264. upb_msg_field_next(&i)) {
  10265. const upb_fielddef *f = upb_msg_iter_field(&i);
  10266. bool packed = upb_fielddef_isseq(f) && upb_fielddef_isprimitive(f) &&
  10267. upb_fielddef_packed(f);
  10268. upb_handlerattr attr;
  10269. upb_wiretype_t wt =
  10270. packed ? UPB_WIRE_TYPE_DELIMITED
  10271. : upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  10272. /* Pre-encode the tag for this field. */
  10273. new_tag(h, f, wt, &attr);
  10274. if (packed) {
  10275. upb_handlers_setstartseq(h, f, encode_startdelimfield, &attr);
  10276. upb_handlers_setendseq(h, f, encode_enddelimfield, &attr);
  10277. }
  10278. #define T(upper, lower, upbtype) \
  10279. case UPB_DESCRIPTOR_TYPE_##upper: \
  10280. if (packed) { \
  10281. upb_handlers_set##upbtype(h, f, encode_packed_##lower, &attr); \
  10282. } else { \
  10283. upb_handlers_set##upbtype(h, f, encode_scalar_##lower, &attr); \
  10284. } \
  10285. break;
  10286. switch (upb_fielddef_descriptortype(f)) {
  10287. T(DOUBLE, double, double);
  10288. T(FLOAT, float, float);
  10289. T(INT64, int64, int64);
  10290. T(INT32, int32, int32);
  10291. T(FIXED64, fixed64, uint64);
  10292. T(FIXED32, fixed32, uint32);
  10293. T(BOOL, bool, bool);
  10294. T(UINT32, uint32, uint32);
  10295. T(UINT64, uint64, uint64);
  10296. T(ENUM, enum, int32);
  10297. T(SFIXED32, sfixed32, int32);
  10298. T(SFIXED64, sfixed64, int64);
  10299. T(SINT32, sint32, int32);
  10300. T(SINT64, sint64, int64);
  10301. case UPB_DESCRIPTOR_TYPE_STRING:
  10302. case UPB_DESCRIPTOR_TYPE_BYTES:
  10303. upb_handlers_setstartstr(h, f, encode_startstr, &attr);
  10304. upb_handlers_setendstr(h, f, encode_enddelimfield, &attr);
  10305. upb_handlers_setstring(h, f, encode_strbuf, &attr);
  10306. break;
  10307. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  10308. upb_handlers_setstartsubmsg(h, f, encode_startdelimfield, &attr);
  10309. upb_handlers_setendsubmsg(h, f, encode_enddelimfield, &attr);
  10310. break;
  10311. case UPB_DESCRIPTOR_TYPE_GROUP: {
  10312. /* Endgroup takes a different tag (wire_type = END_GROUP). */
  10313. upb_handlerattr attr2;
  10314. new_tag(h, f, UPB_WIRE_TYPE_END_GROUP, &attr2);
  10315. upb_handlers_setstartsubmsg(h, f, encode_startgroup, &attr);
  10316. upb_handlers_setendsubmsg(h, f, encode_endgroup, &attr2);
  10317. upb_handlerattr_uninit(&attr2);
  10318. break;
  10319. }
  10320. }
  10321. #undef T
  10322. upb_handlerattr_uninit(&attr);
  10323. }
  10324. }
  10325. void upb_pb_encoder_reset(upb_pb_encoder *e) {
  10326. e->segptr = NULL;
  10327. e->top = NULL;
  10328. e->depth = 0;
  10329. }
  10330. /* public API *****************************************************************/
  10331. const upb_handlers *upb_pb_encoder_newhandlers(const upb_msgdef *m,
  10332. const void *owner) {
  10333. return upb_handlers_newfrozen(m, owner, newhandlers_callback, NULL);
  10334. }
  10335. upb_pb_encoder *upb_pb_encoder_create(upb_env *env, const upb_handlers *h,
  10336. upb_bytessink *output) {
  10337. const size_t initial_bufsize = 256;
  10338. const size_t initial_segbufsize = 16;
  10339. /* TODO(haberman): make this configurable. */
  10340. const size_t stack_size = 64;
  10341. #ifndef NDEBUG
  10342. const size_t size_before = upb_env_bytesallocated(env);
  10343. #endif
  10344. upb_pb_encoder *e = upb_env_malloc(env, sizeof(upb_pb_encoder));
  10345. if (!e) return NULL;
  10346. e->buf = upb_env_malloc(env, initial_bufsize);
  10347. e->segbuf = upb_env_malloc(env, initial_segbufsize * sizeof(*e->segbuf));
  10348. e->stack = upb_env_malloc(env, stack_size * sizeof(*e->stack));
  10349. if (!e->buf || !e->segbuf || !e->stack) {
  10350. return NULL;
  10351. }
  10352. e->limit = e->buf + initial_bufsize;
  10353. e->seglimit = e->segbuf + initial_segbufsize;
  10354. e->stacklimit = e->stack + stack_size;
  10355. upb_pb_encoder_reset(e);
  10356. upb_sink_reset(&e->input_, h, e);
  10357. e->env = env;
  10358. e->output_ = output;
  10359. e->subc = output->closure;
  10360. e->ptr = e->buf;
  10361. /* If this fails, increase the value in encoder.h. */
  10362. UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(env) - size_before <=
  10363. UPB_PB_ENCODER_SIZE);
  10364. return e;
  10365. }
  10366. upb_sink *upb_pb_encoder_input(upb_pb_encoder *e) { return &e->input_; }
  10367. upb_filedef **upb_loaddescriptor(const char *buf, size_t n, const void *owner,
  10368. upb_status *status) {
  10369. /* Create handlers. */
  10370. const upb_pbdecodermethod *decoder_m;
  10371. const upb_handlers *reader_h = upb_descreader_newhandlers(&reader_h);
  10372. upb_env env;
  10373. upb_pbdecodermethodopts opts;
  10374. upb_pbdecoder *decoder;
  10375. upb_descreader *reader;
  10376. bool ok;
  10377. size_t i;
  10378. upb_filedef **ret = NULL;
  10379. upb_pbdecodermethodopts_init(&opts, reader_h);
  10380. decoder_m = upb_pbdecodermethod_new(&opts, &decoder_m);
  10381. upb_env_init(&env);
  10382. upb_env_reporterrorsto(&env, status);
  10383. reader = upb_descreader_create(&env, reader_h);
  10384. decoder = upb_pbdecoder_create(&env, decoder_m, upb_descreader_input(reader));
  10385. /* Push input data. */
  10386. ok = upb_bufsrc_putbuf(buf, n, upb_pbdecoder_input(decoder));
  10387. if (!ok) {
  10388. goto cleanup;
  10389. }
  10390. ret = upb_gmalloc(sizeof (*ret) * (upb_descreader_filecount(reader) + 1));
  10391. if (!ret) {
  10392. goto cleanup;
  10393. }
  10394. for (i = 0; i < upb_descreader_filecount(reader); i++) {
  10395. ret[i] = upb_descreader_file(reader, i);
  10396. upb_filedef_ref(ret[i], owner);
  10397. }
  10398. ret[i] = NULL;
  10399. cleanup:
  10400. upb_env_uninit(&env);
  10401. upb_handlers_unref(reader_h, &reader_h);
  10402. upb_pbdecodermethod_unref(decoder_m, &decoder_m);
  10403. return ret;
  10404. }
  10405. /*
  10406. * upb::pb::TextPrinter
  10407. *
  10408. * OPT: This is not optimized at all. It uses printf() which parses the format
  10409. * string every time, and it allocates memory for every put.
  10410. */
  10411. #include <ctype.h>
  10412. #include <float.h>
  10413. #include <inttypes.h>
  10414. #include <stdarg.h>
  10415. #include <stdio.h>
  10416. #include <string.h>
  10417. struct upb_textprinter {
  10418. upb_sink input_;
  10419. upb_bytessink *output_;
  10420. int indent_depth_;
  10421. bool single_line_;
  10422. void *subc;
  10423. };
  10424. #define CHECK(x) if ((x) < 0) goto err;
  10425. static const char *shortname(const char *longname) {
  10426. const char *last = strrchr(longname, '.');
  10427. return last ? last + 1 : longname;
  10428. }
  10429. static int indent(upb_textprinter *p) {
  10430. int i;
  10431. if (!p->single_line_)
  10432. for (i = 0; i < p->indent_depth_; i++)
  10433. upb_bytessink_putbuf(p->output_, p->subc, " ", 2, NULL);
  10434. return 0;
  10435. }
  10436. static int endfield(upb_textprinter *p) {
  10437. const char ch = (p->single_line_ ? ' ' : '\n');
  10438. upb_bytessink_putbuf(p->output_, p->subc, &ch, 1, NULL);
  10439. return 0;
  10440. }
  10441. static int putescaped(upb_textprinter *p, const char *buf, size_t len,
  10442. bool preserve_utf8) {
  10443. /* Based on CEscapeInternal() from Google's protobuf release. */
  10444. char dstbuf[4096], *dst = dstbuf, *dstend = dstbuf + sizeof(dstbuf);
  10445. const char *end = buf + len;
  10446. /* I think hex is prettier and more useful, but proto2 uses octal; should
  10447. * investigate whether it can parse hex also. */
  10448. const bool use_hex = false;
  10449. bool last_hex_escape = false; /* true if last output char was \xNN */
  10450. for (; buf < end; buf++) {
  10451. bool is_hex_escape;
  10452. if (dstend - dst < 4) {
  10453. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  10454. dst = dstbuf;
  10455. }
  10456. is_hex_escape = false;
  10457. switch (*buf) {
  10458. case '\n': *(dst++) = '\\'; *(dst++) = 'n'; break;
  10459. case '\r': *(dst++) = '\\'; *(dst++) = 'r'; break;
  10460. case '\t': *(dst++) = '\\'; *(dst++) = 't'; break;
  10461. case '\"': *(dst++) = '\\'; *(dst++) = '\"'; break;
  10462. case '\'': *(dst++) = '\\'; *(dst++) = '\''; break;
  10463. case '\\': *(dst++) = '\\'; *(dst++) = '\\'; break;
  10464. default:
  10465. /* Note that if we emit \xNN and the buf character after that is a hex
  10466. * digit then that digit must be escaped too to prevent it being
  10467. * interpreted as part of the character code by C. */
  10468. if ((!preserve_utf8 || (uint8_t)*buf < 0x80) &&
  10469. (!isprint(*buf) || (last_hex_escape && isxdigit(*buf)))) {
  10470. sprintf(dst, (use_hex ? "\\x%02x" : "\\%03o"), (uint8_t)*buf);
  10471. is_hex_escape = use_hex;
  10472. dst += 4;
  10473. } else {
  10474. *(dst++) = *buf; break;
  10475. }
  10476. }
  10477. last_hex_escape = is_hex_escape;
  10478. }
  10479. /* Flush remaining data. */
  10480. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  10481. return 0;
  10482. }
  10483. bool putf(upb_textprinter *p, const char *fmt, ...) {
  10484. va_list args;
  10485. va_list args_copy;
  10486. char *str;
  10487. int written;
  10488. int len;
  10489. bool ok;
  10490. va_start(args, fmt);
  10491. /* Run once to get the length of the string. */
  10492. _upb_va_copy(args_copy, args);
  10493. len = _upb_vsnprintf(NULL, 0, fmt, args_copy);
  10494. va_end(args_copy);
  10495. /* + 1 for NULL terminator (vsprintf() requires it even if we don't). */
  10496. str = upb_gmalloc(len + 1);
  10497. if (!str) return false;
  10498. written = vsprintf(str, fmt, args);
  10499. va_end(args);
  10500. UPB_ASSERT(written == len);
  10501. ok = upb_bytessink_putbuf(p->output_, p->subc, str, len, NULL);
  10502. upb_gfree(str);
  10503. return ok;
  10504. }
  10505. /* handlers *******************************************************************/
  10506. static bool textprinter_startmsg(void *c, const void *hd) {
  10507. upb_textprinter *p = c;
  10508. UPB_UNUSED(hd);
  10509. if (p->indent_depth_ == 0) {
  10510. upb_bytessink_start(p->output_, 0, &p->subc);
  10511. }
  10512. return true;
  10513. }
  10514. static bool textprinter_endmsg(void *c, const void *hd, upb_status *s) {
  10515. upb_textprinter *p = c;
  10516. UPB_UNUSED(hd);
  10517. UPB_UNUSED(s);
  10518. if (p->indent_depth_ == 0) {
  10519. upb_bytessink_end(p->output_);
  10520. }
  10521. return true;
  10522. }
  10523. #define TYPE(name, ctype, fmt) \
  10524. static bool textprinter_put ## name(void *closure, const void *handler_data, \
  10525. ctype val) { \
  10526. upb_textprinter *p = closure; \
  10527. const upb_fielddef *f = handler_data; \
  10528. CHECK(indent(p)); \
  10529. putf(p, "%s: " fmt, upb_fielddef_name(f), val); \
  10530. CHECK(endfield(p)); \
  10531. return true; \
  10532. err: \
  10533. return false; \
  10534. }
  10535. static bool textprinter_putbool(void *closure, const void *handler_data,
  10536. bool val) {
  10537. upb_textprinter *p = closure;
  10538. const upb_fielddef *f = handler_data;
  10539. CHECK(indent(p));
  10540. putf(p, "%s: %s", upb_fielddef_name(f), val ? "true" : "false");
  10541. CHECK(endfield(p));
  10542. return true;
  10543. err:
  10544. return false;
  10545. }
  10546. #define STRINGIFY_HELPER(x) #x
  10547. #define STRINGIFY_MACROVAL(x) STRINGIFY_HELPER(x)
  10548. TYPE(int32, int32_t, "%" PRId32)
  10549. TYPE(int64, int64_t, "%" PRId64)
  10550. TYPE(uint32, uint32_t, "%" PRIu32)
  10551. TYPE(uint64, uint64_t, "%" PRIu64)
  10552. TYPE(float, float, "%." STRINGIFY_MACROVAL(FLT_DIG) "g")
  10553. TYPE(double, double, "%." STRINGIFY_MACROVAL(DBL_DIG) "g")
  10554. #undef TYPE
  10555. /* Output a symbolic value from the enum if found, else just print as int32. */
  10556. static bool textprinter_putenum(void *closure, const void *handler_data,
  10557. int32_t val) {
  10558. upb_textprinter *p = closure;
  10559. const upb_fielddef *f = handler_data;
  10560. const upb_enumdef *enum_def = upb_downcast_enumdef(upb_fielddef_subdef(f));
  10561. const char *label = upb_enumdef_iton(enum_def, val);
  10562. if (label) {
  10563. indent(p);
  10564. putf(p, "%s: %s", upb_fielddef_name(f), label);
  10565. endfield(p);
  10566. } else {
  10567. if (!textprinter_putint32(closure, handler_data, val))
  10568. return false;
  10569. }
  10570. return true;
  10571. }
  10572. static void *textprinter_startstr(void *closure, const void *handler_data,
  10573. size_t size_hint) {
  10574. upb_textprinter *p = closure;
  10575. const upb_fielddef *f = handler_data;
  10576. UPB_UNUSED(size_hint);
  10577. indent(p);
  10578. putf(p, "%s: \"", upb_fielddef_name(f));
  10579. return p;
  10580. }
  10581. static bool textprinter_endstr(void *closure, const void *handler_data) {
  10582. upb_textprinter *p = closure;
  10583. UPB_UNUSED(handler_data);
  10584. putf(p, "\"");
  10585. endfield(p);
  10586. return true;
  10587. }
  10588. static size_t textprinter_putstr(void *closure, const void *hd, const char *buf,
  10589. size_t len, const upb_bufhandle *handle) {
  10590. upb_textprinter *p = closure;
  10591. const upb_fielddef *f = hd;
  10592. UPB_UNUSED(handle);
  10593. CHECK(putescaped(p, buf, len, upb_fielddef_type(f) == UPB_TYPE_STRING));
  10594. return len;
  10595. err:
  10596. return 0;
  10597. }
  10598. static void *textprinter_startsubmsg(void *closure, const void *handler_data) {
  10599. upb_textprinter *p = closure;
  10600. const char *name = handler_data;
  10601. CHECK(indent(p));
  10602. putf(p, "%s {%c", name, p->single_line_ ? ' ' : '\n');
  10603. p->indent_depth_++;
  10604. return p;
  10605. err:
  10606. return UPB_BREAK;
  10607. }
  10608. static bool textprinter_endsubmsg(void *closure, const void *handler_data) {
  10609. upb_textprinter *p = closure;
  10610. UPB_UNUSED(handler_data);
  10611. p->indent_depth_--;
  10612. CHECK(indent(p));
  10613. upb_bytessink_putbuf(p->output_, p->subc, "}", 1, NULL);
  10614. CHECK(endfield(p));
  10615. return true;
  10616. err:
  10617. return false;
  10618. }
  10619. static void onmreg(const void *c, upb_handlers *h) {
  10620. const upb_msgdef *m = upb_handlers_msgdef(h);
  10621. upb_msg_field_iter i;
  10622. UPB_UNUSED(c);
  10623. upb_handlers_setstartmsg(h, textprinter_startmsg, NULL);
  10624. upb_handlers_setendmsg(h, textprinter_endmsg, NULL);
  10625. for(upb_msg_field_begin(&i, m);
  10626. !upb_msg_field_done(&i);
  10627. upb_msg_field_next(&i)) {
  10628. upb_fielddef *f = upb_msg_iter_field(&i);
  10629. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  10630. upb_handlerattr_sethandlerdata(&attr, f);
  10631. switch (upb_fielddef_type(f)) {
  10632. case UPB_TYPE_INT32:
  10633. upb_handlers_setint32(h, f, textprinter_putint32, &attr);
  10634. break;
  10635. case UPB_TYPE_INT64:
  10636. upb_handlers_setint64(h, f, textprinter_putint64, &attr);
  10637. break;
  10638. case UPB_TYPE_UINT32:
  10639. upb_handlers_setuint32(h, f, textprinter_putuint32, &attr);
  10640. break;
  10641. case UPB_TYPE_UINT64:
  10642. upb_handlers_setuint64(h, f, textprinter_putuint64, &attr);
  10643. break;
  10644. case UPB_TYPE_FLOAT:
  10645. upb_handlers_setfloat(h, f, textprinter_putfloat, &attr);
  10646. break;
  10647. case UPB_TYPE_DOUBLE:
  10648. upb_handlers_setdouble(h, f, textprinter_putdouble, &attr);
  10649. break;
  10650. case UPB_TYPE_BOOL:
  10651. upb_handlers_setbool(h, f, textprinter_putbool, &attr);
  10652. break;
  10653. case UPB_TYPE_STRING:
  10654. case UPB_TYPE_BYTES:
  10655. upb_handlers_setstartstr(h, f, textprinter_startstr, &attr);
  10656. upb_handlers_setstring(h, f, textprinter_putstr, &attr);
  10657. upb_handlers_setendstr(h, f, textprinter_endstr, &attr);
  10658. break;
  10659. case UPB_TYPE_MESSAGE: {
  10660. const char *name =
  10661. upb_fielddef_istagdelim(f)
  10662. ? shortname(upb_msgdef_fullname(upb_fielddef_msgsubdef(f)))
  10663. : upb_fielddef_name(f);
  10664. upb_handlerattr_sethandlerdata(&attr, name);
  10665. upb_handlers_setstartsubmsg(h, f, textprinter_startsubmsg, &attr);
  10666. upb_handlers_setendsubmsg(h, f, textprinter_endsubmsg, &attr);
  10667. break;
  10668. }
  10669. case UPB_TYPE_ENUM:
  10670. upb_handlers_setint32(h, f, textprinter_putenum, &attr);
  10671. break;
  10672. }
  10673. }
  10674. }
  10675. static void textprinter_reset(upb_textprinter *p, bool single_line) {
  10676. p->single_line_ = single_line;
  10677. p->indent_depth_ = 0;
  10678. }
  10679. /* Public API *****************************************************************/
  10680. upb_textprinter *upb_textprinter_create(upb_env *env, const upb_handlers *h,
  10681. upb_bytessink *output) {
  10682. upb_textprinter *p = upb_env_malloc(env, sizeof(upb_textprinter));
  10683. if (!p) return NULL;
  10684. p->output_ = output;
  10685. upb_sink_reset(&p->input_, h, p);
  10686. textprinter_reset(p, false);
  10687. return p;
  10688. }
  10689. const upb_handlers *upb_textprinter_newhandlers(const upb_msgdef *m,
  10690. const void *owner) {
  10691. return upb_handlers_newfrozen(m, owner, &onmreg, NULL);
  10692. }
  10693. upb_sink *upb_textprinter_input(upb_textprinter *p) { return &p->input_; }
  10694. void upb_textprinter_setsingleline(upb_textprinter *p, bool single_line) {
  10695. p->single_line_ = single_line;
  10696. }
  10697. /* Index is descriptor type. */
  10698. const uint8_t upb_pb_native_wire_types[] = {
  10699. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  10700. UPB_WIRE_TYPE_64BIT, /* DOUBLE */
  10701. UPB_WIRE_TYPE_32BIT, /* FLOAT */
  10702. UPB_WIRE_TYPE_VARINT, /* INT64 */
  10703. UPB_WIRE_TYPE_VARINT, /* UINT64 */
  10704. UPB_WIRE_TYPE_VARINT, /* INT32 */
  10705. UPB_WIRE_TYPE_64BIT, /* FIXED64 */
  10706. UPB_WIRE_TYPE_32BIT, /* FIXED32 */
  10707. UPB_WIRE_TYPE_VARINT, /* BOOL */
  10708. UPB_WIRE_TYPE_DELIMITED, /* STRING */
  10709. UPB_WIRE_TYPE_START_GROUP, /* GROUP */
  10710. UPB_WIRE_TYPE_DELIMITED, /* MESSAGE */
  10711. UPB_WIRE_TYPE_DELIMITED, /* BYTES */
  10712. UPB_WIRE_TYPE_VARINT, /* UINT32 */
  10713. UPB_WIRE_TYPE_VARINT, /* ENUM */
  10714. UPB_WIRE_TYPE_32BIT, /* SFIXED32 */
  10715. UPB_WIRE_TYPE_64BIT, /* SFIXED64 */
  10716. UPB_WIRE_TYPE_VARINT, /* SINT32 */
  10717. UPB_WIRE_TYPE_VARINT, /* SINT64 */
  10718. };
  10719. /* A basic branch-based decoder, uses 32-bit values to get good performance
  10720. * on 32-bit architectures (but performs well on 64-bits also).
  10721. * This scheme comes from the original Google Protobuf implementation
  10722. * (proto2). */
  10723. upb_decoderet upb_vdecode_max8_branch32(upb_decoderet r) {
  10724. upb_decoderet err = {NULL, 0};
  10725. const char *p = r.p;
  10726. uint32_t low = (uint32_t)r.val;
  10727. uint32_t high = 0;
  10728. uint32_t b;
  10729. b = *(p++); low |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  10730. b = *(p++); low |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  10731. b = *(p++); low |= (b & 0x7fU) << 28;
  10732. high = (b & 0x7fU) >> 4; if (!(b & 0x80)) goto done;
  10733. b = *(p++); high |= (b & 0x7fU) << 3; if (!(b & 0x80)) goto done;
  10734. b = *(p++); high |= (b & 0x7fU) << 10; if (!(b & 0x80)) goto done;
  10735. b = *(p++); high |= (b & 0x7fU) << 17; if (!(b & 0x80)) goto done;
  10736. b = *(p++); high |= (b & 0x7fU) << 24; if (!(b & 0x80)) goto done;
  10737. b = *(p++); high |= (b & 0x7fU) << 31; if (!(b & 0x80)) goto done;
  10738. return err;
  10739. done:
  10740. r.val = ((uint64_t)high << 32) | low;
  10741. r.p = p;
  10742. return r;
  10743. }
  10744. /* Like the previous, but uses 64-bit values. */
  10745. upb_decoderet upb_vdecode_max8_branch64(upb_decoderet r) {
  10746. const char *p = r.p;
  10747. uint64_t val = r.val;
  10748. uint64_t b;
  10749. upb_decoderet err = {NULL, 0};
  10750. b = *(p++); val |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  10751. b = *(p++); val |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  10752. b = *(p++); val |= (b & 0x7fU) << 28; if (!(b & 0x80)) goto done;
  10753. b = *(p++); val |= (b & 0x7fU) << 35; if (!(b & 0x80)) goto done;
  10754. b = *(p++); val |= (b & 0x7fU) << 42; if (!(b & 0x80)) goto done;
  10755. b = *(p++); val |= (b & 0x7fU) << 49; if (!(b & 0x80)) goto done;
  10756. b = *(p++); val |= (b & 0x7fU) << 56; if (!(b & 0x80)) goto done;
  10757. b = *(p++); val |= (b & 0x7fU) << 63; if (!(b & 0x80)) goto done;
  10758. return err;
  10759. done:
  10760. r.val = val;
  10761. r.p = p;
  10762. return r;
  10763. }
  10764. //#line 1 "upb/json/parser.rl"
  10765. /*
  10766. ** upb::json::Parser (upb_json_parser)
  10767. **
  10768. ** A parser that uses the Ragel State Machine Compiler to generate
  10769. ** the finite automata.
  10770. **
  10771. ** Ragel only natively handles regular languages, but we can manually
  10772. ** program it a bit to handle context-free languages like JSON, by using
  10773. ** the "fcall" and "fret" constructs.
  10774. **
  10775. ** This parser can handle the basics, but needs several things to be fleshed
  10776. ** out:
  10777. **
  10778. ** - handling of unicode escape sequences (including high surrogate pairs).
  10779. ** - properly check and report errors for unknown fields, stack overflow,
  10780. ** improper array nesting (or lack of nesting).
  10781. ** - handling of base64 sequences with padding characters.
  10782. ** - handling of push-back (non-success returns from sink functions).
  10783. ** - handling of keys/escape-sequences/etc that span input buffers.
  10784. */
  10785. #include <errno.h>
  10786. #include <float.h>
  10787. #include <math.h>
  10788. #include <stdint.h>
  10789. #include <stdio.h>
  10790. #include <stdlib.h>
  10791. #include <string.h>
  10792. /* Need to define __USE_XOPEN before including time.h to make strptime work. */
  10793. #ifndef __USE_XOPEN
  10794. #define __USE_XOPEN
  10795. #endif
  10796. #include <time.h>
  10797. #define UPB_JSON_MAX_DEPTH 64
  10798. /* Type of value message */
  10799. enum {
  10800. VALUE_NULLVALUE = 0,
  10801. VALUE_NUMBERVALUE = 1,
  10802. VALUE_STRINGVALUE = 2,
  10803. VALUE_BOOLVALUE = 3,
  10804. VALUE_STRUCTVALUE = 4,
  10805. VALUE_LISTVALUE = 5
  10806. };
  10807. /* Forward declare */
  10808. static bool is_top_level(upb_json_parser *p);
  10809. static bool is_wellknown_msg(upb_json_parser *p, upb_wellknowntype_t type);
  10810. static bool is_wellknown_field(upb_json_parser *p, upb_wellknowntype_t type);
  10811. static bool is_number_wrapper_object(upb_json_parser *p);
  10812. static bool does_number_wrapper_start(upb_json_parser *p);
  10813. static bool does_number_wrapper_end(upb_json_parser *p);
  10814. static bool is_string_wrapper_object(upb_json_parser *p);
  10815. static bool does_string_wrapper_start(upb_json_parser *p);
  10816. static bool does_string_wrapper_end(upb_json_parser *p);
  10817. static void start_wrapper_object(upb_json_parser *p);
  10818. static void end_wrapper_object(upb_json_parser *p);
  10819. static void start_value_object(upb_json_parser *p, int value_type);
  10820. static void end_value_object(upb_json_parser *p);
  10821. static void start_listvalue_object(upb_json_parser *p);
  10822. static void end_listvalue_object(upb_json_parser *p);
  10823. static void start_structvalue_object(upb_json_parser *p);
  10824. static void end_structvalue_object(upb_json_parser *p);
  10825. static void start_object(upb_json_parser *p);
  10826. static void end_object(upb_json_parser *p);
  10827. static bool start_subobject(upb_json_parser *p);
  10828. static void end_subobject(upb_json_parser *p);
  10829. static void start_member(upb_json_parser *p);
  10830. static void end_member(upb_json_parser *p);
  10831. static bool end_membername(upb_json_parser *p);
  10832. static const char eof_ch = 'e';
  10833. typedef struct {
  10834. upb_sink sink;
  10835. /* The current message in which we're parsing, and the field whose value we're
  10836. * expecting next. */
  10837. const upb_msgdef *m;
  10838. const upb_fielddef *f;
  10839. /* The table mapping json name to fielddef for this message. */
  10840. upb_strtable *name_table;
  10841. /* We are in a repeated-field context, ready to emit mapentries as
  10842. * submessages. This flag alters the start-of-object (open-brace) behavior to
  10843. * begin a sequence of mapentry messages rather than a single submessage. */
  10844. bool is_map;
  10845. /* We are in a map-entry message context. This flag is set when parsing the
  10846. * value field of a single map entry and indicates to all value-field parsers
  10847. * (subobjects, strings, numbers, and bools) that the map-entry submessage
  10848. * should end as soon as the value is parsed. */
  10849. bool is_mapentry;
  10850. /* If |is_map| or |is_mapentry| is true, |mapfield| refers to the parent
  10851. * message's map field that we're currently parsing. This differs from |f|
  10852. * because |f| is the field in the *current* message (i.e., the map-entry
  10853. * message itself), not the parent's field that leads to this map. */
  10854. const upb_fielddef *mapfield;
  10855. /* True if the field to be parsed is unknown. */
  10856. bool is_unknown_field;
  10857. } upb_jsonparser_frame;
  10858. struct upb_json_parser {
  10859. upb_env *env;
  10860. const upb_json_parsermethod *method;
  10861. upb_bytessink input_;
  10862. /* Stack to track the JSON scopes we are in. */
  10863. upb_jsonparser_frame stack[UPB_JSON_MAX_DEPTH];
  10864. upb_jsonparser_frame *top;
  10865. upb_jsonparser_frame *limit;
  10866. upb_status status;
  10867. /* Ragel's internal parsing stack for the parsing state machine. */
  10868. int current_state;
  10869. int parser_stack[UPB_JSON_MAX_DEPTH];
  10870. int parser_top;
  10871. /* The handle for the current buffer. */
  10872. const upb_bufhandle *handle;
  10873. /* Accumulate buffer. See details in parser.rl. */
  10874. const char *accumulated;
  10875. size_t accumulated_len;
  10876. char *accumulate_buf;
  10877. size_t accumulate_buf_size;
  10878. /* Multi-part text data. See details in parser.rl. */
  10879. int multipart_state;
  10880. upb_selector_t string_selector;
  10881. /* Input capture. See details in parser.rl. */
  10882. const char *capture;
  10883. /* Intermediate result of parsing a unicode escape sequence. */
  10884. uint32_t digit;
  10885. /* Whether to proceed if unknown field is met. */
  10886. bool ignore_json_unknown;
  10887. /* Cache for parsing timestamp due to base and zone are handled in different
  10888. * handlers. */
  10889. struct tm tm;
  10890. };
  10891. struct upb_json_parsermethod {
  10892. upb_refcounted base;
  10893. upb_byteshandler input_handler_;
  10894. /* Mainly for the purposes of refcounting, so all the fielddefs we point
  10895. * to stay alive. */
  10896. const upb_msgdef *msg;
  10897. /* Keys are upb_msgdef*, values are upb_strtable (json_name -> fielddef) */
  10898. upb_inttable name_tables;
  10899. };
  10900. #define PARSER_CHECK_RETURN(x) if (!(x)) return false
  10901. /* Used to signal that a capture has been suspended. */
  10902. static char suspend_capture;
  10903. static upb_selector_t getsel_for_handlertype(upb_json_parser *p,
  10904. upb_handlertype_t type) {
  10905. upb_selector_t sel;
  10906. bool ok = upb_handlers_getselector(p->top->f, type, &sel);
  10907. UPB_ASSERT(ok);
  10908. return sel;
  10909. }
  10910. static upb_selector_t parser_getsel(upb_json_parser *p) {
  10911. return getsel_for_handlertype(
  10912. p, upb_handlers_getprimitivehandlertype(p->top->f));
  10913. }
  10914. static bool check_stack(upb_json_parser *p) {
  10915. if ((p->top + 1) == p->limit) {
  10916. upb_status_seterrmsg(&p->status, "Nesting too deep");
  10917. upb_env_reporterror(p->env, &p->status);
  10918. return false;
  10919. }
  10920. return true;
  10921. }
  10922. static void set_name_table(upb_json_parser *p, upb_jsonparser_frame *frame) {
  10923. upb_value v;
  10924. bool ok = upb_inttable_lookupptr(&p->method->name_tables, frame->m, &v);
  10925. UPB_ASSERT(ok);
  10926. frame->name_table = upb_value_getptr(v);
  10927. }
  10928. /* There are GCC/Clang built-ins for overflow checking which we could start
  10929. * using if there was any performance benefit to it. */
  10930. static bool checked_add(size_t a, size_t b, size_t *c) {
  10931. if (SIZE_MAX - a < b) return false;
  10932. *c = a + b;
  10933. return true;
  10934. }
  10935. static size_t saturating_multiply(size_t a, size_t b) {
  10936. /* size_t is unsigned, so this is defined behavior even on overflow. */
  10937. size_t ret = a * b;
  10938. if (b != 0 && ret / b != a) {
  10939. ret = SIZE_MAX;
  10940. }
  10941. return ret;
  10942. }
  10943. /* Base64 decoding ************************************************************/
  10944. /* TODO(haberman): make this streaming. */
  10945. static const signed char b64table[] = {
  10946. -1, -1, -1, -1, -1, -1, -1, -1,
  10947. -1, -1, -1, -1, -1, -1, -1, -1,
  10948. -1, -1, -1, -1, -1, -1, -1, -1,
  10949. -1, -1, -1, -1, -1, -1, -1, -1,
  10950. -1, -1, -1, -1, -1, -1, -1, -1,
  10951. -1, -1, -1, 62/*+*/, -1, -1, -1, 63/*/ */,
  10952. 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
  10953. 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1,
  10954. -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
  10955. 07/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
  10956. 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
  10957. 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, -1,
  10958. -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
  10959. 33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
  10960. 41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
  10961. 49/*x*/, 50/*y*/, 51/*z*/, -1, -1, -1, -1, -1,
  10962. -1, -1, -1, -1, -1, -1, -1, -1,
  10963. -1, -1, -1, -1, -1, -1, -1, -1,
  10964. -1, -1, -1, -1, -1, -1, -1, -1,
  10965. -1, -1, -1, -1, -1, -1, -1, -1,
  10966. -1, -1, -1, -1, -1, -1, -1, -1,
  10967. -1, -1, -1, -1, -1, -1, -1, -1,
  10968. -1, -1, -1, -1, -1, -1, -1, -1,
  10969. -1, -1, -1, -1, -1, -1, -1, -1,
  10970. -1, -1, -1, -1, -1, -1, -1, -1,
  10971. -1, -1, -1, -1, -1, -1, -1, -1,
  10972. -1, -1, -1, -1, -1, -1, -1, -1,
  10973. -1, -1, -1, -1, -1, -1, -1, -1,
  10974. -1, -1, -1, -1, -1, -1, -1, -1,
  10975. -1, -1, -1, -1, -1, -1, -1, -1,
  10976. -1, -1, -1, -1, -1, -1, -1, -1,
  10977. -1, -1, -1, -1, -1, -1, -1, -1
  10978. };
  10979. /* Returns the table value sign-extended to 32 bits. Knowing that the upper
  10980. * bits will be 1 for unrecognized characters makes it easier to check for
  10981. * this error condition later (see below). */
  10982. int32_t b64lookup(unsigned char ch) { return b64table[ch]; }
  10983. /* Returns true if the given character is not a valid base64 character or
  10984. * padding. */
  10985. bool nonbase64(unsigned char ch) { return b64lookup(ch) == -1 && ch != '='; }
  10986. static bool base64_push(upb_json_parser *p, upb_selector_t sel, const char *ptr,
  10987. size_t len) {
  10988. const char *limit = ptr + len;
  10989. for (; ptr < limit; ptr += 4) {
  10990. uint32_t val;
  10991. char output[3];
  10992. if (limit - ptr < 4) {
  10993. upb_status_seterrf(&p->status,
  10994. "Base64 input for bytes field not a multiple of 4: %s",
  10995. upb_fielddef_name(p->top->f));
  10996. upb_env_reporterror(p->env, &p->status);
  10997. return false;
  10998. }
  10999. val = b64lookup(ptr[0]) << 18 |
  11000. b64lookup(ptr[1]) << 12 |
  11001. b64lookup(ptr[2]) << 6 |
  11002. b64lookup(ptr[3]);
  11003. /* Test the upper bit; returns true if any of the characters returned -1. */
  11004. if (val & 0x80000000) {
  11005. goto otherchar;
  11006. }
  11007. output[0] = val >> 16;
  11008. output[1] = (val >> 8) & 0xff;
  11009. output[2] = val & 0xff;
  11010. upb_sink_putstring(&p->top->sink, sel, output, 3, NULL);
  11011. }
  11012. return true;
  11013. otherchar:
  11014. if (nonbase64(ptr[0]) || nonbase64(ptr[1]) || nonbase64(ptr[2]) ||
  11015. nonbase64(ptr[3]) ) {
  11016. upb_status_seterrf(&p->status,
  11017. "Non-base64 characters in bytes field: %s",
  11018. upb_fielddef_name(p->top->f));
  11019. upb_env_reporterror(p->env, &p->status);
  11020. return false;
  11021. } if (ptr[2] == '=') {
  11022. uint32_t val;
  11023. char output;
  11024. /* Last group contains only two input bytes, one output byte. */
  11025. if (ptr[0] == '=' || ptr[1] == '=' || ptr[3] != '=') {
  11026. goto badpadding;
  11027. }
  11028. val = b64lookup(ptr[0]) << 18 |
  11029. b64lookup(ptr[1]) << 12;
  11030. UPB_ASSERT(!(val & 0x80000000));
  11031. output = val >> 16;
  11032. upb_sink_putstring(&p->top->sink, sel, &output, 1, NULL);
  11033. return true;
  11034. } else {
  11035. uint32_t val;
  11036. char output[2];
  11037. /* Last group contains only three input bytes, two output bytes. */
  11038. if (ptr[0] == '=' || ptr[1] == '=' || ptr[2] == '=') {
  11039. goto badpadding;
  11040. }
  11041. val = b64lookup(ptr[0]) << 18 |
  11042. b64lookup(ptr[1]) << 12 |
  11043. b64lookup(ptr[2]) << 6;
  11044. output[0] = val >> 16;
  11045. output[1] = (val >> 8) & 0xff;
  11046. upb_sink_putstring(&p->top->sink, sel, output, 2, NULL);
  11047. return true;
  11048. }
  11049. badpadding:
  11050. upb_status_seterrf(&p->status,
  11051. "Incorrect base64 padding for field: %s (%.*s)",
  11052. upb_fielddef_name(p->top->f),
  11053. 4, ptr);
  11054. upb_env_reporterror(p->env, &p->status);
  11055. return false;
  11056. }
  11057. /* Accumulate buffer **********************************************************/
  11058. /* Functionality for accumulating a buffer.
  11059. *
  11060. * Some parts of the parser need an entire value as a contiguous string. For
  11061. * example, to look up a member name in a hash table, or to turn a string into
  11062. * a number, the relevant library routines need the input string to be in
  11063. * contiguous memory, even if the value spanned two or more buffers in the
  11064. * input. These routines handle that.
  11065. *
  11066. * In the common case we can just point to the input buffer to get this
  11067. * contiguous string and avoid any actual copy. So we optimistically begin
  11068. * this way. But there are a few cases where we must instead copy into a
  11069. * separate buffer:
  11070. *
  11071. * 1. The string was not contiguous in the input (it spanned buffers).
  11072. *
  11073. * 2. The string included escape sequences that need to be interpreted to get
  11074. * the true value in a contiguous buffer. */
  11075. static void assert_accumulate_empty(upb_json_parser *p) {
  11076. UPB_ASSERT(p->accumulated == NULL);
  11077. UPB_ASSERT(p->accumulated_len == 0);
  11078. }
  11079. static void accumulate_clear(upb_json_parser *p) {
  11080. p->accumulated = NULL;
  11081. p->accumulated_len = 0;
  11082. }
  11083. /* Used internally by accumulate_append(). */
  11084. static bool accumulate_realloc(upb_json_parser *p, size_t need) {
  11085. void *mem;
  11086. size_t old_size = p->accumulate_buf_size;
  11087. size_t new_size = UPB_MAX(old_size, 128);
  11088. while (new_size < need) {
  11089. new_size = saturating_multiply(new_size, 2);
  11090. }
  11091. mem = upb_env_realloc(p->env, p->accumulate_buf, old_size, new_size);
  11092. if (!mem) {
  11093. upb_status_seterrmsg(&p->status, "Out of memory allocating buffer.");
  11094. upb_env_reporterror(p->env, &p->status);
  11095. return false;
  11096. }
  11097. p->accumulate_buf = mem;
  11098. p->accumulate_buf_size = new_size;
  11099. return true;
  11100. }
  11101. /* Logically appends the given data to the append buffer.
  11102. * If "can_alias" is true, we will try to avoid actually copying, but the buffer
  11103. * must be valid until the next accumulate_append() call (if any). */
  11104. static bool accumulate_append(upb_json_parser *p, const char *buf, size_t len,
  11105. bool can_alias) {
  11106. size_t need;
  11107. if (!p->accumulated && can_alias) {
  11108. p->accumulated = buf;
  11109. p->accumulated_len = len;
  11110. return true;
  11111. }
  11112. if (!checked_add(p->accumulated_len, len, &need)) {
  11113. upb_status_seterrmsg(&p->status, "Integer overflow.");
  11114. upb_env_reporterror(p->env, &p->status);
  11115. return false;
  11116. }
  11117. if (need > p->accumulate_buf_size && !accumulate_realloc(p, need)) {
  11118. return false;
  11119. }
  11120. if (p->accumulated != p->accumulate_buf) {
  11121. memcpy(p->accumulate_buf, p->accumulated, p->accumulated_len);
  11122. p->accumulated = p->accumulate_buf;
  11123. }
  11124. memcpy(p->accumulate_buf + p->accumulated_len, buf, len);
  11125. p->accumulated_len += len;
  11126. return true;
  11127. }
  11128. /* Returns a pointer to the data accumulated since the last accumulate_clear()
  11129. * call, and writes the length to *len. This with point either to the input
  11130. * buffer or a temporary accumulate buffer. */
  11131. static const char *accumulate_getptr(upb_json_parser *p, size_t *len) {
  11132. UPB_ASSERT(p->accumulated);
  11133. *len = p->accumulated_len;
  11134. return p->accumulated;
  11135. }
  11136. /* Mult-part text data ********************************************************/
  11137. /* When we have text data in the input, it can often come in multiple segments.
  11138. * For example, there may be some raw string data followed by an escape
  11139. * sequence. The two segments are processed with different logic. Also buffer
  11140. * seams in the input can cause multiple segments.
  11141. *
  11142. * As we see segments, there are two main cases for how we want to process them:
  11143. *
  11144. * 1. we want to push the captured input directly to string handlers.
  11145. *
  11146. * 2. we need to accumulate all the parts into a contiguous buffer for further
  11147. * processing (field name lookup, string->number conversion, etc). */
  11148. /* This is the set of states for p->multipart_state. */
  11149. enum {
  11150. /* We are not currently processing multipart data. */
  11151. MULTIPART_INACTIVE = 0,
  11152. /* We are processing multipart data by accumulating it into a contiguous
  11153. * buffer. */
  11154. MULTIPART_ACCUMULATE = 1,
  11155. /* We are processing multipart data by pushing each part directly to the
  11156. * current string handlers. */
  11157. MULTIPART_PUSHEAGERLY = 2
  11158. };
  11159. /* Start a multi-part text value where we accumulate the data for processing at
  11160. * the end. */
  11161. static void multipart_startaccum(upb_json_parser *p) {
  11162. assert_accumulate_empty(p);
  11163. UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
  11164. p->multipart_state = MULTIPART_ACCUMULATE;
  11165. }
  11166. /* Start a multi-part text value where we immediately push text data to a string
  11167. * value with the given selector. */
  11168. static void multipart_start(upb_json_parser *p, upb_selector_t sel) {
  11169. assert_accumulate_empty(p);
  11170. UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
  11171. p->multipart_state = MULTIPART_PUSHEAGERLY;
  11172. p->string_selector = sel;
  11173. }
  11174. static bool multipart_text(upb_json_parser *p, const char *buf, size_t len,
  11175. bool can_alias) {
  11176. switch (p->multipart_state) {
  11177. case MULTIPART_INACTIVE:
  11178. upb_status_seterrmsg(
  11179. &p->status, "Internal error: unexpected state MULTIPART_INACTIVE");
  11180. upb_env_reporterror(p->env, &p->status);
  11181. return false;
  11182. case MULTIPART_ACCUMULATE:
  11183. if (!accumulate_append(p, buf, len, can_alias)) {
  11184. return false;
  11185. }
  11186. break;
  11187. case MULTIPART_PUSHEAGERLY: {
  11188. const upb_bufhandle *handle = can_alias ? p->handle : NULL;
  11189. upb_sink_putstring(&p->top->sink, p->string_selector, buf, len, handle);
  11190. break;
  11191. }
  11192. }
  11193. return true;
  11194. }
  11195. /* Note: this invalidates the accumulate buffer! Call only after reading its
  11196. * contents. */
  11197. static void multipart_end(upb_json_parser *p) {
  11198. UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
  11199. p->multipart_state = MULTIPART_INACTIVE;
  11200. accumulate_clear(p);
  11201. }
  11202. /* Input capture **************************************************************/
  11203. /* Functionality for capturing a region of the input as text. Gracefully
  11204. * handles the case where a buffer seam occurs in the middle of the captured
  11205. * region. */
  11206. static void capture_begin(upb_json_parser *p, const char *ptr) {
  11207. UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
  11208. UPB_ASSERT(p->capture == NULL);
  11209. p->capture = ptr;
  11210. }
  11211. static bool capture_end(upb_json_parser *p, const char *ptr) {
  11212. UPB_ASSERT(p->capture);
  11213. if (multipart_text(p, p->capture, ptr - p->capture, true)) {
  11214. p->capture = NULL;
  11215. return true;
  11216. } else {
  11217. return false;
  11218. }
  11219. }
  11220. /* This is called at the end of each input buffer (ie. when we have hit a
  11221. * buffer seam). If we are in the middle of capturing the input, this
  11222. * processes the unprocessed capture region. */
  11223. static void capture_suspend(upb_json_parser *p, const char **ptr) {
  11224. if (!p->capture) return;
  11225. if (multipart_text(p, p->capture, *ptr - p->capture, false)) {
  11226. /* We use this as a signal that we were in the middle of capturing, and
  11227. * that capturing should resume at the beginning of the next buffer.
  11228. *
  11229. * We can't use *ptr here, because we have no guarantee that this pointer
  11230. * will be valid when we resume (if the underlying memory is freed, then
  11231. * using the pointer at all, even to compare to NULL, is likely undefined
  11232. * behavior). */
  11233. p->capture = &suspend_capture;
  11234. } else {
  11235. /* Need to back up the pointer to the beginning of the capture, since
  11236. * we were not able to actually preserve it. */
  11237. *ptr = p->capture;
  11238. }
  11239. }
  11240. static void capture_resume(upb_json_parser *p, const char *ptr) {
  11241. if (p->capture) {
  11242. UPB_ASSERT(p->capture == &suspend_capture);
  11243. p->capture = ptr;
  11244. }
  11245. }
  11246. /* Callbacks from the parser **************************************************/
  11247. /* These are the functions called directly from the parser itself.
  11248. * We define these in the same order as their declarations in the parser. */
  11249. static char escape_char(char in) {
  11250. switch (in) {
  11251. case 'r': return '\r';
  11252. case 't': return '\t';
  11253. case 'n': return '\n';
  11254. case 'f': return '\f';
  11255. case 'b': return '\b';
  11256. case '/': return '/';
  11257. case '"': return '"';
  11258. case '\\': return '\\';
  11259. default:
  11260. UPB_ASSERT(0);
  11261. return 'x';
  11262. }
  11263. }
  11264. static bool escape(upb_json_parser *p, const char *ptr) {
  11265. char ch = escape_char(*ptr);
  11266. return multipart_text(p, &ch, 1, false);
  11267. }
  11268. static void start_hex(upb_json_parser *p) {
  11269. p->digit = 0;
  11270. }
  11271. static void hexdigit(upb_json_parser *p, const char *ptr) {
  11272. char ch = *ptr;
  11273. p->digit <<= 4;
  11274. if (ch >= '0' && ch <= '9') {
  11275. p->digit += (ch - '0');
  11276. } else if (ch >= 'a' && ch <= 'f') {
  11277. p->digit += ((ch - 'a') + 10);
  11278. } else {
  11279. UPB_ASSERT(ch >= 'A' && ch <= 'F');
  11280. p->digit += ((ch - 'A') + 10);
  11281. }
  11282. }
  11283. static bool end_hex(upb_json_parser *p) {
  11284. uint32_t codepoint = p->digit;
  11285. /* emit the codepoint as UTF-8. */
  11286. char utf8[3]; /* support \u0000 -- \uFFFF -- need only three bytes. */
  11287. int length = 0;
  11288. if (codepoint <= 0x7F) {
  11289. utf8[0] = codepoint;
  11290. length = 1;
  11291. } else if (codepoint <= 0x07FF) {
  11292. utf8[1] = (codepoint & 0x3F) | 0x80;
  11293. codepoint >>= 6;
  11294. utf8[0] = (codepoint & 0x1F) | 0xC0;
  11295. length = 2;
  11296. } else /* codepoint <= 0xFFFF */ {
  11297. utf8[2] = (codepoint & 0x3F) | 0x80;
  11298. codepoint >>= 6;
  11299. utf8[1] = (codepoint & 0x3F) | 0x80;
  11300. codepoint >>= 6;
  11301. utf8[0] = (codepoint & 0x0F) | 0xE0;
  11302. length = 3;
  11303. }
  11304. /* TODO(haberman): Handle high surrogates: if codepoint is a high surrogate
  11305. * we have to wait for the next escape to get the full code point). */
  11306. return multipart_text(p, utf8, length, false);
  11307. }
  11308. static void start_text(upb_json_parser *p, const char *ptr) {
  11309. capture_begin(p, ptr);
  11310. }
  11311. static bool end_text(upb_json_parser *p, const char *ptr) {
  11312. return capture_end(p, ptr);
  11313. }
  11314. static bool start_number(upb_json_parser *p, const char *ptr) {
  11315. if (is_top_level(p)) {
  11316. if (is_number_wrapper_object(p)) {
  11317. start_wrapper_object(p);
  11318. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  11319. start_value_object(p, VALUE_NUMBERVALUE);
  11320. } else {
  11321. return false;
  11322. }
  11323. } else if (does_number_wrapper_start(p)) {
  11324. if (!start_subobject(p)) {
  11325. return false;
  11326. }
  11327. start_wrapper_object(p);
  11328. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  11329. if (!start_subobject(p)) {
  11330. return false;
  11331. }
  11332. start_value_object(p, VALUE_NUMBERVALUE);
  11333. }
  11334. multipart_startaccum(p);
  11335. capture_begin(p, ptr);
  11336. return true;
  11337. }
  11338. static bool parse_number(upb_json_parser *p, bool is_quoted);
  11339. static bool end_number_nontop(upb_json_parser *p, const char *ptr) {
  11340. if (!capture_end(p, ptr)) {
  11341. return false;
  11342. }
  11343. if (p->top->f == NULL) {
  11344. multipart_end(p);
  11345. return true;
  11346. }
  11347. return parse_number(p, false);
  11348. }
  11349. static bool end_number(upb_json_parser *p, const char *ptr) {
  11350. if (!end_number_nontop(p, ptr)) {
  11351. return false;
  11352. }
  11353. if (does_number_wrapper_end(p)) {
  11354. end_wrapper_object(p);
  11355. if (!is_top_level(p)) {
  11356. end_subobject(p);
  11357. }
  11358. return true;
  11359. }
  11360. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  11361. end_value_object(p);
  11362. if (!is_top_level(p)) {
  11363. end_subobject(p);
  11364. }
  11365. return true;
  11366. }
  11367. return true;
  11368. }
  11369. /* |buf| is NULL-terminated. |buf| itself will never include quotes;
  11370. * |is_quoted| tells us whether this text originally appeared inside quotes. */
  11371. static bool parse_number_from_buffer(upb_json_parser *p, const char *buf,
  11372. bool is_quoted) {
  11373. size_t len = strlen(buf);
  11374. const char *bufend = buf + len;
  11375. char *end;
  11376. upb_fieldtype_t type = upb_fielddef_type(p->top->f);
  11377. double val;
  11378. double dummy;
  11379. double inf = 1.0 / 0.0; /* C89 does not have an INFINITY macro. */
  11380. errno = 0;
  11381. if (len == 0 || buf[0] == ' ') {
  11382. return false;
  11383. }
  11384. /* For integer types, first try parsing with integer-specific routines.
  11385. * If these succeed, they will be more accurate for int64/uint64 than
  11386. * strtod().
  11387. */
  11388. switch (type) {
  11389. case UPB_TYPE_ENUM:
  11390. case UPB_TYPE_INT32: {
  11391. long val = strtol(buf, &end, 0);
  11392. if (errno == ERANGE || end != bufend) {
  11393. break;
  11394. } else if (val > INT32_MAX || val < INT32_MIN) {
  11395. return false;
  11396. } else {
  11397. upb_sink_putint32(&p->top->sink, parser_getsel(p), val);
  11398. return true;
  11399. }
  11400. }
  11401. case UPB_TYPE_UINT32: {
  11402. unsigned long val = strtoul(buf, &end, 0);
  11403. if (end != bufend) {
  11404. break;
  11405. } else if (val > UINT32_MAX || errno == ERANGE) {
  11406. return false;
  11407. } else {
  11408. upb_sink_putuint32(&p->top->sink, parser_getsel(p), val);
  11409. return true;
  11410. }
  11411. }
  11412. /* XXX: We can't handle [u]int64 properly on 32-bit machines because
  11413. * strto[u]ll isn't in C89. */
  11414. case UPB_TYPE_INT64: {
  11415. long val = strtol(buf, &end, 0);
  11416. if (errno == ERANGE || end != bufend) {
  11417. break;
  11418. } else {
  11419. upb_sink_putint64(&p->top->sink, parser_getsel(p), val);
  11420. return true;
  11421. }
  11422. }
  11423. case UPB_TYPE_UINT64: {
  11424. unsigned long val = strtoul(p->accumulated, &end, 0);
  11425. if (end != bufend) {
  11426. break;
  11427. } else if (errno == ERANGE) {
  11428. return false;
  11429. } else {
  11430. upb_sink_putuint64(&p->top->sink, parser_getsel(p), val);
  11431. return true;
  11432. }
  11433. }
  11434. default:
  11435. break;
  11436. }
  11437. if (type != UPB_TYPE_DOUBLE && type != UPB_TYPE_FLOAT && is_quoted) {
  11438. /* Quoted numbers for integer types are not allowed to be in double form. */
  11439. return false;
  11440. }
  11441. if (len == strlen("Infinity") && strcmp(buf, "Infinity") == 0) {
  11442. /* C89 does not have an INFINITY macro. */
  11443. val = inf;
  11444. } else if (len == strlen("-Infinity") && strcmp(buf, "-Infinity") == 0) {
  11445. val = -inf;
  11446. } else {
  11447. val = strtod(buf, &end);
  11448. if (errno == ERANGE || end != bufend) {
  11449. return false;
  11450. }
  11451. }
  11452. switch (type) {
  11453. #define CASE(capitaltype, smalltype, ctype, min, max) \
  11454. case UPB_TYPE_ ## capitaltype: { \
  11455. if (modf(val, &dummy) != 0 || val > max || val < min) { \
  11456. return false; \
  11457. } else { \
  11458. upb_sink_put ## smalltype(&p->top->sink, parser_getsel(p), \
  11459. (ctype)val); \
  11460. return true; \
  11461. } \
  11462. break; \
  11463. }
  11464. case UPB_TYPE_ENUM:
  11465. CASE(INT32, int32, int32_t, INT32_MIN, INT32_MAX);
  11466. CASE(INT64, int64, int64_t, INT64_MIN, INT64_MAX);
  11467. CASE(UINT32, uint32, uint32_t, 0, UINT32_MAX);
  11468. CASE(UINT64, uint64, uint64_t, 0, UINT64_MAX);
  11469. #undef CASE
  11470. case UPB_TYPE_DOUBLE:
  11471. upb_sink_putdouble(&p->top->sink, parser_getsel(p), val);
  11472. return true;
  11473. case UPB_TYPE_FLOAT:
  11474. if ((val > FLT_MAX || val < -FLT_MAX) && val != inf && val != -inf) {
  11475. return false;
  11476. } else {
  11477. upb_sink_putfloat(&p->top->sink, parser_getsel(p), val);
  11478. return true;
  11479. }
  11480. default:
  11481. return false;
  11482. }
  11483. }
  11484. static bool parse_number(upb_json_parser *p, bool is_quoted) {
  11485. size_t len;
  11486. const char *buf;
  11487. /* strtol() and friends unfortunately do not support specifying the length of
  11488. * the input string, so we need to force a copy into a NULL-terminated buffer. */
  11489. if (!multipart_text(p, "\0", 1, false)) {
  11490. return false;
  11491. }
  11492. buf = accumulate_getptr(p, &len);
  11493. if (parse_number_from_buffer(p, buf, is_quoted)) {
  11494. multipart_end(p);
  11495. return true;
  11496. } else {
  11497. upb_status_seterrf(&p->status, "error parsing number: %s", buf);
  11498. upb_env_reporterror(p->env, &p->status);
  11499. multipart_end(p);
  11500. return false;
  11501. }
  11502. }
  11503. static bool parser_putbool(upb_json_parser *p, bool val) {
  11504. bool ok;
  11505. if (p->top->f == NULL) {
  11506. return true;
  11507. }
  11508. if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL) {
  11509. upb_status_seterrf(&p->status,
  11510. "Boolean value specified for non-bool field: %s",
  11511. upb_fielddef_name(p->top->f));
  11512. upb_env_reporterror(p->env, &p->status);
  11513. return false;
  11514. }
  11515. ok = upb_sink_putbool(&p->top->sink, parser_getsel(p), val);
  11516. UPB_ASSERT(ok);
  11517. return true;
  11518. }
  11519. static bool end_bool(upb_json_parser *p, bool val) {
  11520. if (is_top_level(p)) {
  11521. if (is_wellknown_msg(p, UPB_WELLKNOWN_BOOLVALUE)) {
  11522. start_wrapper_object(p);
  11523. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  11524. start_value_object(p, VALUE_BOOLVALUE);
  11525. } else {
  11526. return false;
  11527. }
  11528. } else if (is_wellknown_field(p, UPB_WELLKNOWN_BOOLVALUE)) {
  11529. if (!start_subobject(p)) {
  11530. return false;
  11531. }
  11532. start_wrapper_object(p);
  11533. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  11534. if (!start_subobject(p)) {
  11535. return false;
  11536. }
  11537. start_value_object(p, VALUE_BOOLVALUE);
  11538. }
  11539. if (p->top->is_unknown_field) {
  11540. return true;
  11541. }
  11542. if (!parser_putbool(p, val)) {
  11543. return false;
  11544. }
  11545. if (is_wellknown_msg(p, UPB_WELLKNOWN_BOOLVALUE)) {
  11546. end_wrapper_object(p);
  11547. if (!is_top_level(p)) {
  11548. end_subobject(p);
  11549. }
  11550. return true;
  11551. }
  11552. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  11553. end_value_object(p);
  11554. if (!is_top_level(p)) {
  11555. end_subobject(p);
  11556. }
  11557. return true;
  11558. }
  11559. return true;
  11560. }
  11561. static bool end_null(upb_json_parser *p) {
  11562. const char *zero_ptr = "0";
  11563. if (is_top_level(p)) {
  11564. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  11565. start_value_object(p, VALUE_NULLVALUE);
  11566. } else {
  11567. return true;
  11568. }
  11569. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  11570. if (!start_subobject(p)) {
  11571. return false;
  11572. }
  11573. start_value_object(p, VALUE_NULLVALUE);
  11574. } else {
  11575. return true;
  11576. }
  11577. /* Fill null_value field. */
  11578. multipart_startaccum(p);
  11579. capture_begin(p, zero_ptr);
  11580. capture_end(p, zero_ptr + 1);
  11581. parse_number(p, false);
  11582. end_value_object(p);
  11583. if (!is_top_level(p)) {
  11584. end_subobject(p);
  11585. }
  11586. return true;
  11587. }
  11588. static bool start_stringval(upb_json_parser *p) {
  11589. if (is_top_level(p)) {
  11590. if (is_string_wrapper_object(p)) {
  11591. start_wrapper_object(p);
  11592. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  11593. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION)) {
  11594. start_object(p);
  11595. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  11596. start_value_object(p, VALUE_STRINGVALUE);
  11597. } else {
  11598. return false;
  11599. }
  11600. } else if (does_string_wrapper_start(p)) {
  11601. if (!start_subobject(p)) {
  11602. return false;
  11603. }
  11604. start_wrapper_object(p);
  11605. } else if (is_wellknown_field(p, UPB_WELLKNOWN_TIMESTAMP) ||
  11606. is_wellknown_field(p, UPB_WELLKNOWN_DURATION)) {
  11607. if (!start_subobject(p)) {
  11608. return false;
  11609. }
  11610. start_object(p);
  11611. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  11612. if (!start_subobject(p)) {
  11613. return false;
  11614. }
  11615. start_value_object(p, VALUE_STRINGVALUE);
  11616. }
  11617. if (p->top->f == NULL) {
  11618. multipart_startaccum(p);
  11619. return true;
  11620. }
  11621. if (upb_fielddef_isstring(p->top->f)) {
  11622. upb_jsonparser_frame *inner;
  11623. upb_selector_t sel;
  11624. if (!check_stack(p)) return false;
  11625. /* Start a new parser frame: parser frames correspond one-to-one with
  11626. * handler frames, and string events occur in a sub-frame. */
  11627. inner = p->top + 1;
  11628. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  11629. upb_sink_startstr(&p->top->sink, sel, 0, &inner->sink);
  11630. inner->m = p->top->m;
  11631. inner->f = p->top->f;
  11632. inner->name_table = NULL;
  11633. inner->is_map = false;
  11634. inner->is_mapentry = false;
  11635. inner->is_unknown_field = false;
  11636. p->top = inner;
  11637. if (upb_fielddef_type(p->top->f) == UPB_TYPE_STRING) {
  11638. /* For STRING fields we push data directly to the handlers as it is
  11639. * parsed. We don't do this yet for BYTES fields, because our base64
  11640. * decoder is not streaming.
  11641. *
  11642. * TODO(haberman): make base64 decoding streaming also. */
  11643. multipart_start(p, getsel_for_handlertype(p, UPB_HANDLER_STRING));
  11644. return true;
  11645. } else {
  11646. multipart_startaccum(p);
  11647. return true;
  11648. }
  11649. } else if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL &&
  11650. upb_fielddef_type(p->top->f) != UPB_TYPE_MESSAGE) {
  11651. /* No need to push a frame -- numeric values in quotes remain in the
  11652. * current parser frame. These values must accmulate so we can convert
  11653. * them all at once at the end. */
  11654. multipart_startaccum(p);
  11655. return true;
  11656. } else {
  11657. upb_status_seterrf(&p->status,
  11658. "String specified for bool or submessage field: %s",
  11659. upb_fielddef_name(p->top->f));
  11660. upb_env_reporterror(p->env, &p->status);
  11661. return false;
  11662. }
  11663. }
  11664. static bool end_stringval_nontop(upb_json_parser *p) {
  11665. bool ok = true;
  11666. if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  11667. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION)) {
  11668. multipart_end(p);
  11669. return true;
  11670. }
  11671. if (p->top->f == NULL) {
  11672. multipart_end(p);
  11673. return true;
  11674. }
  11675. switch (upb_fielddef_type(p->top->f)) {
  11676. case UPB_TYPE_BYTES:
  11677. if (!base64_push(p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  11678. p->accumulated, p->accumulated_len)) {
  11679. return false;
  11680. }
  11681. /* Fall through. */
  11682. case UPB_TYPE_STRING: {
  11683. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  11684. p->top--;
  11685. upb_sink_endstr(&p->top->sink, sel);
  11686. break;
  11687. }
  11688. case UPB_TYPE_ENUM: {
  11689. /* Resolve enum symbolic name to integer value. */
  11690. const upb_enumdef *enumdef =
  11691. (const upb_enumdef*)upb_fielddef_subdef(p->top->f);
  11692. size_t len;
  11693. const char *buf = accumulate_getptr(p, &len);
  11694. int32_t int_val = 0;
  11695. ok = upb_enumdef_ntoi(enumdef, buf, len, &int_val);
  11696. if (ok) {
  11697. upb_selector_t sel = parser_getsel(p);
  11698. upb_sink_putint32(&p->top->sink, sel, int_val);
  11699. } else {
  11700. upb_status_seterrf(&p->status, "Enum value unknown: '%.*s'", len, buf);
  11701. upb_env_reporterror(p->env, &p->status);
  11702. }
  11703. break;
  11704. }
  11705. case UPB_TYPE_INT32:
  11706. case UPB_TYPE_INT64:
  11707. case UPB_TYPE_UINT32:
  11708. case UPB_TYPE_UINT64:
  11709. case UPB_TYPE_DOUBLE:
  11710. case UPB_TYPE_FLOAT:
  11711. ok = parse_number(p, true);
  11712. break;
  11713. default:
  11714. UPB_ASSERT(false);
  11715. upb_status_seterrmsg(&p->status, "Internal error in JSON decoder");
  11716. upb_env_reporterror(p->env, &p->status);
  11717. ok = false;
  11718. break;
  11719. }
  11720. multipart_end(p);
  11721. return ok;
  11722. }
  11723. static bool end_stringval(upb_json_parser *p) {
  11724. if (!end_stringval_nontop(p)) {
  11725. return false;
  11726. }
  11727. if (does_string_wrapper_end(p)) {
  11728. end_wrapper_object(p);
  11729. if (!is_top_level(p)) {
  11730. end_subobject(p);
  11731. }
  11732. return true;
  11733. }
  11734. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  11735. end_value_object(p);
  11736. if (!is_top_level(p)) {
  11737. end_subobject(p);
  11738. }
  11739. return true;
  11740. }
  11741. if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  11742. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION)) {
  11743. end_object(p);
  11744. if (!is_top_level(p)) {
  11745. end_subobject(p);
  11746. }
  11747. return true;
  11748. }
  11749. return true;
  11750. }
  11751. static void start_duration_base(upb_json_parser *p, const char *ptr) {
  11752. capture_begin(p, ptr);
  11753. }
  11754. static bool end_duration_base(upb_json_parser *p, const char *ptr) {
  11755. size_t len;
  11756. const char *buf;
  11757. char seconds_buf[14];
  11758. char nanos_buf[12];
  11759. char *end;
  11760. int64_t seconds = 0;
  11761. int32_t nanos = 0;
  11762. double val = 0.0;
  11763. const char *seconds_membername = "seconds";
  11764. const char *nanos_membername = "nanos";
  11765. size_t fraction_start;
  11766. if (!capture_end(p, ptr)) {
  11767. return false;
  11768. }
  11769. buf = accumulate_getptr(p, &len);
  11770. memset(seconds_buf, 0, 14);
  11771. memset(nanos_buf, 0, 12);
  11772. /* Find out base end. The maximus duration is 315576000000, which cannot be
  11773. * represented by double without losing precision. Thus, we need to handle
  11774. * fraction and base separately. */
  11775. for (fraction_start = 0; fraction_start < len && buf[fraction_start] != '.';
  11776. fraction_start++);
  11777. /* Parse base */
  11778. memcpy(seconds_buf, buf, fraction_start);
  11779. seconds = strtol(seconds_buf, &end, 10);
  11780. if (errno == ERANGE || end != seconds_buf + fraction_start) {
  11781. upb_status_seterrf(&p->status, "error parsing duration: %s",
  11782. seconds_buf);
  11783. upb_env_reporterror(p->env, &p->status);
  11784. return false;
  11785. }
  11786. if (seconds > 315576000000) {
  11787. upb_status_seterrf(&p->status, "error parsing duration: "
  11788. "maximum acceptable value is "
  11789. "315576000000");
  11790. upb_env_reporterror(p->env, &p->status);
  11791. return false;
  11792. }
  11793. if (seconds < -315576000000) {
  11794. upb_status_seterrf(&p->status, "error parsing duration: "
  11795. "minimum acceptable value is "
  11796. "-315576000000");
  11797. upb_env_reporterror(p->env, &p->status);
  11798. return false;
  11799. }
  11800. /* Parse fraction */
  11801. nanos_buf[0] = '0';
  11802. memcpy(nanos_buf + 1, buf + fraction_start, len - fraction_start);
  11803. val = strtod(nanos_buf, &end);
  11804. if (errno == ERANGE || end != nanos_buf + len - fraction_start + 1) {
  11805. upb_status_seterrf(&p->status, "error parsing duration: %s",
  11806. nanos_buf);
  11807. upb_env_reporterror(p->env, &p->status);
  11808. return false;
  11809. }
  11810. nanos = val * 1000000000;
  11811. if (seconds < 0) nanos = -nanos;
  11812. /* Clean up buffer */
  11813. multipart_end(p);
  11814. /* Set seconds */
  11815. start_member(p);
  11816. capture_begin(p, seconds_membername);
  11817. capture_end(p, seconds_membername + 7);
  11818. end_membername(p);
  11819. upb_sink_putint64(&p->top->sink, parser_getsel(p), seconds);
  11820. end_member(p);
  11821. /* Set nanos */
  11822. start_member(p);
  11823. capture_begin(p, nanos_membername);
  11824. capture_end(p, nanos_membername + 5);
  11825. end_membername(p);
  11826. upb_sink_putint32(&p->top->sink, parser_getsel(p), nanos);
  11827. end_member(p);
  11828. /* Continue previous environment */
  11829. multipart_startaccum(p);
  11830. return true;
  11831. }
  11832. static void start_timestamp_base(upb_json_parser *p, const char *ptr) {
  11833. capture_begin(p, ptr);
  11834. }
  11835. #define UPB_TIMESTAMP_BASE_SIZE 19
  11836. static bool end_timestamp_base(upb_json_parser *p, const char *ptr) {
  11837. size_t len;
  11838. const char *buf;
  11839. /* 3 for GMT and 1 for ending 0 */
  11840. char timestamp_buf[UPB_TIMESTAMP_BASE_SIZE + 4];
  11841. if (!capture_end(p, ptr)) {
  11842. return false;
  11843. }
  11844. buf = accumulate_getptr(p, &len);
  11845. UPB_ASSERT(len == UPB_TIMESTAMP_BASE_SIZE);
  11846. memcpy(timestamp_buf, buf, UPB_TIMESTAMP_BASE_SIZE);
  11847. memcpy(timestamp_buf + UPB_TIMESTAMP_BASE_SIZE, "GMT", 3);
  11848. timestamp_buf[UPB_TIMESTAMP_BASE_SIZE + 3] = 0;
  11849. /* Parse seconds */
  11850. if (strptime(timestamp_buf, "%FT%H:%M:%S%Z", &p->tm) == NULL) {
  11851. upb_status_seterrf(&p->status, "error parsing timestamp: %s", buf);
  11852. upb_env_reporterror(p->env, &p->status);
  11853. return false;
  11854. }
  11855. /* Clean up buffer */
  11856. multipart_end(p);
  11857. multipart_startaccum(p);
  11858. return true;
  11859. }
  11860. static void start_timestamp_fraction(upb_json_parser *p, const char *ptr) {
  11861. capture_begin(p, ptr);
  11862. }
  11863. static bool end_timestamp_fraction(upb_json_parser *p, const char *ptr) {
  11864. size_t len;
  11865. const char *buf;
  11866. char nanos_buf[12];
  11867. char *end;
  11868. double val = 0.0;
  11869. int32_t nanos;
  11870. const char *nanos_membername = "nanos";
  11871. memset(nanos_buf, 0, 12);
  11872. if (!capture_end(p, ptr)) {
  11873. return false;
  11874. }
  11875. buf = accumulate_getptr(p, &len);
  11876. if (len > 10) {
  11877. upb_status_seterrf(&p->status,
  11878. "error parsing timestamp: at most 9-digit fraction.");
  11879. upb_env_reporterror(p->env, &p->status);
  11880. return false;
  11881. }
  11882. /* Parse nanos */
  11883. nanos_buf[0] = '0';
  11884. memcpy(nanos_buf + 1, buf, len);
  11885. val = strtod(nanos_buf, &end);
  11886. if (errno == ERANGE || end != nanos_buf + len + 1) {
  11887. upb_status_seterrf(&p->status, "error parsing timestamp nanos: %s",
  11888. nanos_buf);
  11889. upb_env_reporterror(p->env, &p->status);
  11890. return false;
  11891. }
  11892. nanos = val * 1000000000;
  11893. /* Clean up previous environment */
  11894. multipart_end(p);
  11895. /* Set nanos */
  11896. start_member(p);
  11897. capture_begin(p, nanos_membername);
  11898. capture_end(p, nanos_membername + 5);
  11899. end_membername(p);
  11900. upb_sink_putint32(&p->top->sink, parser_getsel(p), nanos);
  11901. end_member(p);
  11902. /* Continue previous environment */
  11903. multipart_startaccum(p);
  11904. return true;
  11905. }
  11906. static void start_timestamp_zone(upb_json_parser *p, const char *ptr) {
  11907. capture_begin(p, ptr);
  11908. }
  11909. static bool end_timestamp_zone(upb_json_parser *p, const char *ptr) {
  11910. size_t len;
  11911. const char *buf;
  11912. int hours;
  11913. int64_t seconds;
  11914. const char *seconds_membername = "seconds";
  11915. if (!capture_end(p, ptr)) {
  11916. return false;
  11917. }
  11918. buf = accumulate_getptr(p, &len);
  11919. if (buf[0] != 'Z') {
  11920. if (sscanf(buf + 1, "%2d:00", &hours) != 1) {
  11921. upb_status_seterrf(&p->status, "error parsing timestamp offset");
  11922. upb_env_reporterror(p->env, &p->status);
  11923. return false;
  11924. }
  11925. if (buf[0] == '+') {
  11926. hours = -hours;
  11927. }
  11928. p->tm.tm_hour += hours;
  11929. }
  11930. /* Normalize tm */
  11931. seconds = mktime(&p->tm);
  11932. /* Check timestamp boundary */
  11933. if (seconds < -62135596800) {
  11934. upb_status_seterrf(&p->status, "error parsing timestamp: "
  11935. "minimum acceptable value is "
  11936. "0001-01-01T00:00:00Z");
  11937. upb_env_reporterror(p->env, &p->status);
  11938. return false;
  11939. }
  11940. /* Clean up previous environment */
  11941. multipart_end(p);
  11942. /* Set seconds */
  11943. start_member(p);
  11944. capture_begin(p, seconds_membername);
  11945. capture_end(p, seconds_membername + 7);
  11946. end_membername(p);
  11947. upb_sink_putint64(&p->top->sink, parser_getsel(p), seconds);
  11948. end_member(p);
  11949. /* Continue previous environment */
  11950. multipart_startaccum(p);
  11951. return true;
  11952. }
  11953. static void start_member(upb_json_parser *p) {
  11954. UPB_ASSERT(!p->top->f);
  11955. multipart_startaccum(p);
  11956. }
  11957. /* Helper: invoked during parse_mapentry() to emit the mapentry message's key
  11958. * field based on the current contents of the accumulate buffer. */
  11959. static bool parse_mapentry_key(upb_json_parser *p) {
  11960. size_t len;
  11961. const char *buf = accumulate_getptr(p, &len);
  11962. /* Emit the key field. We do a bit of ad-hoc parsing here because the
  11963. * parser state machine has already decided that this is a string field
  11964. * name, and we are reinterpreting it as some arbitrary key type. In
  11965. * particular, integer and bool keys are quoted, so we need to parse the
  11966. * quoted string contents here. */
  11967. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_KEY);
  11968. if (p->top->f == NULL) {
  11969. upb_status_seterrmsg(&p->status, "mapentry message has no key");
  11970. upb_env_reporterror(p->env, &p->status);
  11971. return false;
  11972. }
  11973. switch (upb_fielddef_type(p->top->f)) {
  11974. case UPB_TYPE_INT32:
  11975. case UPB_TYPE_INT64:
  11976. case UPB_TYPE_UINT32:
  11977. case UPB_TYPE_UINT64:
  11978. /* Invoke end_number. The accum buffer has the number's text already. */
  11979. if (!parse_number(p, true)) {
  11980. return false;
  11981. }
  11982. break;
  11983. case UPB_TYPE_BOOL:
  11984. if (len == 4 && !strncmp(buf, "true", 4)) {
  11985. if (!parser_putbool(p, true)) {
  11986. return false;
  11987. }
  11988. } else if (len == 5 && !strncmp(buf, "false", 5)) {
  11989. if (!parser_putbool(p, false)) {
  11990. return false;
  11991. }
  11992. } else {
  11993. upb_status_seterrmsg(&p->status,
  11994. "Map bool key not 'true' or 'false'");
  11995. upb_env_reporterror(p->env, &p->status);
  11996. return false;
  11997. }
  11998. multipart_end(p);
  11999. break;
  12000. case UPB_TYPE_STRING:
  12001. case UPB_TYPE_BYTES: {
  12002. upb_sink subsink;
  12003. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  12004. upb_sink_startstr(&p->top->sink, sel, len, &subsink);
  12005. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  12006. upb_sink_putstring(&subsink, sel, buf, len, NULL);
  12007. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  12008. upb_sink_endstr(&p->top->sink, sel);
  12009. multipart_end(p);
  12010. break;
  12011. }
  12012. default:
  12013. upb_status_seterrmsg(&p->status, "Invalid field type for map key");
  12014. upb_env_reporterror(p->env, &p->status);
  12015. return false;
  12016. }
  12017. return true;
  12018. }
  12019. /* Helper: emit one map entry (as a submessage in the map field sequence). This
  12020. * is invoked from end_membername(), at the end of the map entry's key string,
  12021. * with the map key in the accumulate buffer. It parses the key from that
  12022. * buffer, emits the handler calls to start the mapentry submessage (setting up
  12023. * its subframe in the process), and sets up state in the subframe so that the
  12024. * value parser (invoked next) will emit the mapentry's value field and then
  12025. * end the mapentry message. */
  12026. static bool handle_mapentry(upb_json_parser *p) {
  12027. const upb_fielddef *mapfield;
  12028. const upb_msgdef *mapentrymsg;
  12029. upb_jsonparser_frame *inner;
  12030. upb_selector_t sel;
  12031. /* Map entry: p->top->sink is the seq frame, so we need to start a frame
  12032. * for the mapentry itself, and then set |f| in that frame so that the map
  12033. * value field is parsed, and also set a flag to end the frame after the
  12034. * map-entry value is parsed. */
  12035. if (!check_stack(p)) return false;
  12036. mapfield = p->top->mapfield;
  12037. mapentrymsg = upb_fielddef_msgsubdef(mapfield);
  12038. inner = p->top + 1;
  12039. p->top->f = mapfield;
  12040. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  12041. upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
  12042. inner->m = mapentrymsg;
  12043. inner->name_table = NULL;
  12044. inner->mapfield = mapfield;
  12045. inner->is_map = false;
  12046. inner->is_unknown_field = false;
  12047. /* Don't set this to true *yet* -- we reuse parsing handlers below to push
  12048. * the key field value to the sink, and these handlers will pop the frame
  12049. * if they see is_mapentry (when invoked by the parser state machine, they
  12050. * would have just seen the map-entry value, not key). */
  12051. inner->is_mapentry = false;
  12052. p->top = inner;
  12053. /* send STARTMSG in submsg frame. */
  12054. upb_sink_startmsg(&p->top->sink);
  12055. parse_mapentry_key(p);
  12056. /* Set up the value field to receive the map-entry value. */
  12057. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_VALUE);
  12058. p->top->is_mapentry = true; /* set up to pop frame after value is parsed. */
  12059. p->top->mapfield = mapfield;
  12060. if (p->top->f == NULL) {
  12061. upb_status_seterrmsg(&p->status, "mapentry message has no value");
  12062. upb_env_reporterror(p->env, &p->status);
  12063. return false;
  12064. }
  12065. return true;
  12066. }
  12067. static bool end_membername(upb_json_parser *p) {
  12068. UPB_ASSERT(!p->top->f);
  12069. if (!p->top->m) {
  12070. p->top->is_unknown_field = true;
  12071. multipart_end(p);
  12072. return true;
  12073. }
  12074. if (p->top->is_map) {
  12075. return handle_mapentry(p);
  12076. } else {
  12077. size_t len;
  12078. const char *buf = accumulate_getptr(p, &len);
  12079. upb_value v;
  12080. if (upb_strtable_lookup2(p->top->name_table, buf, len, &v)) {
  12081. p->top->f = upb_value_getconstptr(v);
  12082. multipart_end(p);
  12083. return true;
  12084. } else if (p->ignore_json_unknown) {
  12085. p->top->is_unknown_field = true;
  12086. multipart_end(p);
  12087. return true;
  12088. } else {
  12089. upb_status_seterrf(&p->status, "No such field: %.*s\n", (int)len, buf);
  12090. upb_env_reporterror(p->env, &p->status);
  12091. return false;
  12092. }
  12093. }
  12094. }
  12095. static void end_member(upb_json_parser *p) {
  12096. /* If we just parsed a map-entry value, end that frame too. */
  12097. if (p->top->is_mapentry) {
  12098. upb_status s = UPB_STATUS_INIT;
  12099. upb_selector_t sel;
  12100. bool ok;
  12101. const upb_fielddef *mapfield;
  12102. UPB_ASSERT(p->top > p->stack);
  12103. /* send ENDMSG on submsg. */
  12104. upb_sink_endmsg(&p->top->sink, &s);
  12105. mapfield = p->top->mapfield;
  12106. /* send ENDSUBMSG in repeated-field-of-mapentries frame. */
  12107. p->top--;
  12108. ok = upb_handlers_getselector(mapfield, UPB_HANDLER_ENDSUBMSG, &sel);
  12109. UPB_ASSERT(ok);
  12110. upb_sink_endsubmsg(&p->top->sink, sel);
  12111. }
  12112. p->top->f = NULL;
  12113. p->top->is_unknown_field = false;
  12114. }
  12115. static bool start_subobject(upb_json_parser *p) {
  12116. if (p->top->is_unknown_field) {
  12117. upb_jsonparser_frame *inner;
  12118. if (!check_stack(p)) return false;
  12119. inner = p->top + 1;
  12120. inner->m = NULL;
  12121. inner->f = NULL;
  12122. inner->is_map = false;
  12123. inner->is_mapentry = false;
  12124. inner->is_unknown_field = false;
  12125. p->top = inner;
  12126. return true;
  12127. }
  12128. if (upb_fielddef_ismap(p->top->f)) {
  12129. upb_jsonparser_frame *inner;
  12130. upb_selector_t sel;
  12131. /* Beginning of a map. Start a new parser frame in a repeated-field
  12132. * context. */
  12133. if (!check_stack(p)) return false;
  12134. inner = p->top + 1;
  12135. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  12136. upb_sink_startseq(&p->top->sink, sel, &inner->sink);
  12137. inner->m = upb_fielddef_msgsubdef(p->top->f);
  12138. inner->name_table = NULL;
  12139. inner->mapfield = p->top->f;
  12140. inner->f = NULL;
  12141. inner->is_map = true;
  12142. inner->is_mapentry = false;
  12143. inner->is_unknown_field = false;
  12144. p->top = inner;
  12145. return true;
  12146. } else if (upb_fielddef_issubmsg(p->top->f)) {
  12147. upb_jsonparser_frame *inner;
  12148. upb_selector_t sel;
  12149. /* Beginning of a subobject. Start a new parser frame in the submsg
  12150. * context. */
  12151. if (!check_stack(p)) return false;
  12152. inner = p->top + 1;
  12153. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  12154. upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
  12155. inner->m = upb_fielddef_msgsubdef(p->top->f);
  12156. set_name_table(p, inner);
  12157. inner->f = NULL;
  12158. inner->is_map = false;
  12159. inner->is_mapentry = false;
  12160. inner->is_unknown_field = false;
  12161. p->top = inner;
  12162. return true;
  12163. } else {
  12164. upb_status_seterrf(&p->status,
  12165. "Object specified for non-message/group field: %s",
  12166. upb_fielddef_name(p->top->f));
  12167. upb_env_reporterror(p->env, &p->status);
  12168. return false;
  12169. }
  12170. }
  12171. static bool start_subobject_full(upb_json_parser *p) {
  12172. if (is_top_level(p)) {
  12173. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  12174. start_value_object(p, VALUE_STRUCTVALUE);
  12175. if (!start_subobject(p)) return false;
  12176. start_structvalue_object(p);
  12177. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_STRUCT)) {
  12178. start_structvalue_object(p);
  12179. } else {
  12180. return true;
  12181. }
  12182. } else if (is_wellknown_field(p, UPB_WELLKNOWN_STRUCT)) {
  12183. if (!start_subobject(p)) return false;
  12184. start_structvalue_object(p);
  12185. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  12186. if (!start_subobject(p)) return false;
  12187. start_value_object(p, VALUE_STRUCTVALUE);
  12188. if (!start_subobject(p)) return false;
  12189. start_structvalue_object(p);
  12190. }
  12191. return start_subobject(p);
  12192. }
  12193. static void end_subobject(upb_json_parser *p) {
  12194. if (is_top_level(p)) {
  12195. return;
  12196. }
  12197. if (p->top->is_map) {
  12198. upb_selector_t sel;
  12199. p->top--;
  12200. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  12201. upb_sink_endseq(&p->top->sink, sel);
  12202. } else {
  12203. upb_selector_t sel;
  12204. bool is_unknown = p->top->m == NULL;
  12205. p->top--;
  12206. if (!is_unknown) {
  12207. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSUBMSG);
  12208. upb_sink_endsubmsg(&p->top->sink, sel);
  12209. }
  12210. }
  12211. }
  12212. static void end_subobject_full(upb_json_parser *p) {
  12213. end_subobject(p);
  12214. if (is_wellknown_msg(p, UPB_WELLKNOWN_STRUCT)) {
  12215. end_structvalue_object(p);
  12216. if (!is_top_level(p)) {
  12217. end_subobject(p);
  12218. }
  12219. }
  12220. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  12221. end_value_object(p);
  12222. if (!is_top_level(p)) {
  12223. end_subobject(p);
  12224. }
  12225. }
  12226. }
  12227. static bool start_array(upb_json_parser *p) {
  12228. upb_jsonparser_frame *inner;
  12229. upb_selector_t sel;
  12230. if (is_top_level(p)) {
  12231. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  12232. start_value_object(p, VALUE_LISTVALUE);
  12233. if (!start_subobject(p)) return false;
  12234. start_listvalue_object(p);
  12235. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_LISTVALUE)) {
  12236. start_listvalue_object(p);
  12237. } else {
  12238. return false;
  12239. }
  12240. } else if (is_wellknown_field(p, UPB_WELLKNOWN_LISTVALUE)) {
  12241. if (!start_subobject(p)) return false;
  12242. start_listvalue_object(p);
  12243. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  12244. if (!start_subobject(p)) return false;
  12245. start_value_object(p, VALUE_LISTVALUE);
  12246. if (!start_subobject(p)) return false;
  12247. start_listvalue_object(p);
  12248. }
  12249. if (p->top->is_unknown_field) {
  12250. inner = p->top + 1;
  12251. inner->m = NULL;
  12252. inner->name_table = NULL;
  12253. inner->f = NULL;
  12254. inner->is_map = false;
  12255. inner->is_mapentry = false;
  12256. inner->is_unknown_field = true;
  12257. p->top = inner;
  12258. return true;
  12259. }
  12260. if (!upb_fielddef_isseq(p->top->f)) {
  12261. upb_status_seterrf(&p->status,
  12262. "Array specified for non-repeated field: %s",
  12263. upb_fielddef_name(p->top->f));
  12264. upb_env_reporterror(p->env, &p->status);
  12265. return false;
  12266. }
  12267. if (!check_stack(p)) return false;
  12268. inner = p->top + 1;
  12269. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  12270. upb_sink_startseq(&p->top->sink, sel, &inner->sink);
  12271. inner->m = p->top->m;
  12272. inner->name_table = NULL;
  12273. inner->f = p->top->f;
  12274. inner->is_map = false;
  12275. inner->is_mapentry = false;
  12276. inner->is_unknown_field = false;
  12277. p->top = inner;
  12278. return true;
  12279. }
  12280. static void end_array(upb_json_parser *p) {
  12281. upb_selector_t sel;
  12282. UPB_ASSERT(p->top > p->stack);
  12283. p->top--;
  12284. if (p->top->is_unknown_field) {
  12285. return;
  12286. }
  12287. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  12288. upb_sink_endseq(&p->top->sink, sel);
  12289. if (is_wellknown_msg(p, UPB_WELLKNOWN_LISTVALUE)) {
  12290. end_listvalue_object(p);
  12291. if (!is_top_level(p)) {
  12292. end_subobject(p);
  12293. }
  12294. }
  12295. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  12296. end_value_object(p);
  12297. if (!is_top_level(p)) {
  12298. end_subobject(p);
  12299. }
  12300. }
  12301. }
  12302. static void start_object(upb_json_parser *p) {
  12303. if (!p->top->is_map && p->top->m != NULL) {
  12304. upb_sink_startmsg(&p->top->sink);
  12305. }
  12306. }
  12307. static void end_object(upb_json_parser *p) {
  12308. if (!p->top->is_map && p->top->m != NULL) {
  12309. upb_status status;
  12310. upb_status_clear(&status);
  12311. upb_sink_endmsg(&p->top->sink, &status);
  12312. if (!upb_ok(&status)) {
  12313. upb_env_reporterror(p->env, &status);
  12314. }
  12315. }
  12316. }
  12317. static bool is_string_wrapper(const upb_msgdef *m) {
  12318. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  12319. return type == UPB_WELLKNOWN_STRINGVALUE ||
  12320. type == UPB_WELLKNOWN_BYTESVALUE;
  12321. }
  12322. static void start_wrapper_object(upb_json_parser *p) {
  12323. const char *membername = "value";
  12324. start_object(p);
  12325. /* Set up context for parsing value */
  12326. start_member(p);
  12327. capture_begin(p, membername);
  12328. capture_end(p, membername + 5);
  12329. end_membername(p);
  12330. }
  12331. static void end_wrapper_object(upb_json_parser *p) {
  12332. end_member(p);
  12333. end_object(p);
  12334. }
  12335. static void start_value_object(upb_json_parser *p, int value_type) {
  12336. const char *nullmember = "null_value";
  12337. const char *numbermember = "number_value";
  12338. const char *stringmember = "string_value";
  12339. const char *boolmember = "bool_value";
  12340. const char *structmember = "struct_value";
  12341. const char *listmember = "list_value";
  12342. const char *membername = "";
  12343. switch (value_type) {
  12344. case VALUE_NULLVALUE:
  12345. membername = nullmember;
  12346. break;
  12347. case VALUE_NUMBERVALUE:
  12348. membername = numbermember;
  12349. break;
  12350. case VALUE_STRINGVALUE:
  12351. membername = stringmember;
  12352. break;
  12353. case VALUE_BOOLVALUE:
  12354. membername = boolmember;
  12355. break;
  12356. case VALUE_STRUCTVALUE:
  12357. membername = structmember;
  12358. break;
  12359. case VALUE_LISTVALUE:
  12360. membername = listmember;
  12361. break;
  12362. }
  12363. start_object(p);
  12364. /* Set up context for parsing value */
  12365. start_member(p);
  12366. capture_begin(p, membername);
  12367. capture_end(p, membername + strlen(membername));
  12368. end_membername(p);
  12369. }
  12370. static void end_value_object(upb_json_parser *p) {
  12371. end_member(p);
  12372. end_object(p);
  12373. }
  12374. static void start_listvalue_object(upb_json_parser *p) {
  12375. const char *membername = "values";
  12376. start_object(p);
  12377. /* Set up context for parsing value */
  12378. start_member(p);
  12379. capture_begin(p, membername);
  12380. capture_end(p, membername + strlen(membername));
  12381. end_membername(p);
  12382. }
  12383. static void end_listvalue_object(upb_json_parser *p) {
  12384. end_member(p);
  12385. end_object(p);
  12386. }
  12387. static void start_structvalue_object(upb_json_parser *p) {
  12388. const char *membername = "fields";
  12389. start_object(p);
  12390. /* Set up context for parsing value */
  12391. start_member(p);
  12392. capture_begin(p, membername);
  12393. capture_end(p, membername + strlen(membername));
  12394. end_membername(p);
  12395. }
  12396. static void end_structvalue_object(upb_json_parser *p) {
  12397. end_member(p);
  12398. end_object(p);
  12399. }
  12400. static bool is_top_level(upb_json_parser *p) {
  12401. return p->top == p->stack && p->top->f == NULL && !p->top->is_unknown_field;
  12402. }
  12403. static bool is_wellknown_msg(upb_json_parser *p, upb_wellknowntype_t type) {
  12404. return p->top->m != NULL && upb_msgdef_wellknowntype(p->top->m) == type;
  12405. }
  12406. static bool is_wellknown_field(upb_json_parser *p, upb_wellknowntype_t type) {
  12407. return p->top->f != NULL &&
  12408. upb_fielddef_issubmsg(p->top->f) &&
  12409. (upb_msgdef_wellknowntype(upb_fielddef_msgsubdef(p->top->f))
  12410. == type);
  12411. }
  12412. static bool does_number_wrapper_start(upb_json_parser *p) {
  12413. return p->top->f != NULL &&
  12414. upb_fielddef_issubmsg(p->top->f) &&
  12415. upb_msgdef_isnumberwrapper(upb_fielddef_msgsubdef(p->top->f));
  12416. }
  12417. static bool does_number_wrapper_end(upb_json_parser *p) {
  12418. return p->top->m != NULL && upb_msgdef_isnumberwrapper(p->top->m);
  12419. }
  12420. static bool is_number_wrapper_object(upb_json_parser *p) {
  12421. return p->top->m != NULL && upb_msgdef_isnumberwrapper(p->top->m);
  12422. }
  12423. static bool does_string_wrapper_start(upb_json_parser *p) {
  12424. return p->top->f != NULL &&
  12425. upb_fielddef_issubmsg(p->top->f) &&
  12426. is_string_wrapper(upb_fielddef_msgsubdef(p->top->f));
  12427. }
  12428. static bool does_string_wrapper_end(upb_json_parser *p) {
  12429. return p->top->m != NULL && is_string_wrapper(p->top->m);
  12430. }
  12431. static bool is_string_wrapper_object(upb_json_parser *p) {
  12432. return p->top->m != NULL && is_string_wrapper(p->top->m);
  12433. }
  12434. #define CHECK_RETURN_TOP(x) if (!(x)) goto error
  12435. /* The actual parser **********************************************************/
  12436. /* What follows is the Ragel parser itself. The language is specified in Ragel
  12437. * and the actions call our C functions above.
  12438. *
  12439. * Ragel has an extensive set of functionality, and we use only a small part of
  12440. * it. There are many action types but we only use a few:
  12441. *
  12442. * ">" -- transition into a machine
  12443. * "%" -- transition out of a machine
  12444. * "@" -- transition into a final state of a machine.
  12445. *
  12446. * "@" transitions are tricky because a machine can transition into a final
  12447. * state repeatedly. But in some cases we know this can't happen, for example
  12448. * a string which is delimited by a final '"' can only transition into its
  12449. * final state once, when the closing '"' is seen. */
  12450. //#line 2147 "upb/json/parser.rl"
  12451. //#line 2016 "upb/json/parser.c"
  12452. static const char _json_actions[] = {
  12453. 0, 1, 0, 1, 1, 1, 3, 1,
  12454. 4, 1, 6, 1, 7, 1, 8, 1,
  12455. 9, 1, 10, 1, 11, 1, 12, 1,
  12456. 13, 1, 21, 1, 23, 1, 24, 1,
  12457. 25, 1, 27, 1, 28, 1, 30, 1,
  12458. 32, 1, 33, 1, 34, 1, 35, 1,
  12459. 36, 1, 38, 2, 4, 9, 2, 5,
  12460. 6, 2, 7, 3, 2, 7, 9, 2,
  12461. 14, 15, 2, 16, 17, 2, 18, 19,
  12462. 2, 22, 20, 2, 26, 37, 2, 29,
  12463. 2, 2, 30, 38, 2, 31, 20, 2,
  12464. 33, 38, 2, 34, 38, 2, 35, 38,
  12465. 3, 25, 22, 20, 3, 26, 37, 38,
  12466. 4, 14, 15, 16, 17
  12467. };
  12468. static const short _json_key_offsets[] = {
  12469. 0, 0, 12, 13, 18, 23, 28, 29,
  12470. 30, 31, 32, 33, 34, 35, 36, 37,
  12471. 38, 43, 48, 49, 53, 58, 63, 68,
  12472. 72, 76, 79, 82, 84, 88, 92, 94,
  12473. 96, 101, 103, 105, 114, 120, 126, 132,
  12474. 138, 140, 144, 147, 149, 151, 154, 155,
  12475. 159, 161, 163, 165, 167, 168, 170, 172,
  12476. 173, 175, 177, 178, 180, 182, 183, 185,
  12477. 187, 188, 190, 192, 196, 198, 200, 201,
  12478. 202, 203, 204, 206, 211, 220, 221, 221,
  12479. 221, 226, 231, 236, 237, 238, 239, 240,
  12480. 240, 241, 242, 243, 243, 244, 245, 246,
  12481. 246, 251, 256, 257, 261, 266, 271, 276,
  12482. 280, 280, 283, 286, 289, 292, 295, 298,
  12483. 298, 298, 298, 298
  12484. };
  12485. static const char _json_trans_keys[] = {
  12486. 32, 34, 45, 91, 102, 110, 116, 123,
  12487. 9, 13, 48, 57, 34, 32, 93, 125,
  12488. 9, 13, 32, 44, 93, 9, 13, 32,
  12489. 93, 125, 9, 13, 97, 108, 115, 101,
  12490. 117, 108, 108, 114, 117, 101, 32, 34,
  12491. 125, 9, 13, 32, 34, 125, 9, 13,
  12492. 34, 32, 58, 9, 13, 32, 93, 125,
  12493. 9, 13, 32, 44, 125, 9, 13, 32,
  12494. 44, 125, 9, 13, 32, 34, 9, 13,
  12495. 45, 48, 49, 57, 48, 49, 57, 46,
  12496. 69, 101, 48, 57, 69, 101, 48, 57,
  12497. 43, 45, 48, 57, 48, 57, 48, 57,
  12498. 46, 69, 101, 48, 57, 34, 92, 34,
  12499. 92, 34, 47, 92, 98, 102, 110, 114,
  12500. 116, 117, 48, 57, 65, 70, 97, 102,
  12501. 48, 57, 65, 70, 97, 102, 48, 57,
  12502. 65, 70, 97, 102, 48, 57, 65, 70,
  12503. 97, 102, 34, 92, 45, 48, 49, 57,
  12504. 48, 49, 57, 46, 115, 48, 57, 115,
  12505. 48, 57, 34, 46, 115, 48, 57, 48,
  12506. 57, 48, 57, 48, 57, 48, 57, 45,
  12507. 48, 57, 48, 57, 45, 48, 57, 48,
  12508. 57, 84, 48, 57, 48, 57, 58, 48,
  12509. 57, 48, 57, 58, 48, 57, 48, 57,
  12510. 43, 45, 46, 90, 48, 57, 48, 57,
  12511. 58, 48, 48, 34, 48, 57, 43, 45,
  12512. 90, 48, 57, 34, 45, 91, 102, 110,
  12513. 116, 123, 48, 57, 34, 32, 93, 125,
  12514. 9, 13, 32, 44, 93, 9, 13, 32,
  12515. 93, 125, 9, 13, 97, 108, 115, 101,
  12516. 117, 108, 108, 114, 117, 101, 32, 34,
  12517. 125, 9, 13, 32, 34, 125, 9, 13,
  12518. 34, 32, 58, 9, 13, 32, 93, 125,
  12519. 9, 13, 32, 44, 125, 9, 13, 32,
  12520. 44, 125, 9, 13, 32, 34, 9, 13,
  12521. 32, 9, 13, 32, 9, 13, 32, 9,
  12522. 13, 32, 9, 13, 32, 9, 13, 32,
  12523. 9, 13, 0
  12524. };
  12525. static const char _json_single_lengths[] = {
  12526. 0, 8, 1, 3, 3, 3, 1, 1,
  12527. 1, 1, 1, 1, 1, 1, 1, 1,
  12528. 3, 3, 1, 2, 3, 3, 3, 2,
  12529. 2, 1, 3, 0, 2, 2, 0, 0,
  12530. 3, 2, 2, 9, 0, 0, 0, 0,
  12531. 2, 2, 1, 2, 0, 1, 1, 2,
  12532. 0, 0, 0, 0, 1, 0, 0, 1,
  12533. 0, 0, 1, 0, 0, 1, 0, 0,
  12534. 1, 0, 0, 4, 0, 0, 1, 1,
  12535. 1, 1, 0, 3, 7, 1, 0, 0,
  12536. 3, 3, 3, 1, 1, 1, 1, 0,
  12537. 1, 1, 1, 0, 1, 1, 1, 0,
  12538. 3, 3, 1, 2, 3, 3, 3, 2,
  12539. 0, 1, 1, 1, 1, 1, 1, 0,
  12540. 0, 0, 0, 0
  12541. };
  12542. static const char _json_range_lengths[] = {
  12543. 0, 2, 0, 1, 1, 1, 0, 0,
  12544. 0, 0, 0, 0, 0, 0, 0, 0,
  12545. 1, 1, 0, 1, 1, 1, 1, 1,
  12546. 1, 1, 0, 1, 1, 1, 1, 1,
  12547. 1, 0, 0, 0, 3, 3, 3, 3,
  12548. 0, 1, 1, 0, 1, 1, 0, 1,
  12549. 1, 1, 1, 1, 0, 1, 1, 0,
  12550. 1, 1, 0, 1, 1, 0, 1, 1,
  12551. 0, 1, 1, 0, 1, 1, 0, 0,
  12552. 0, 0, 1, 1, 1, 0, 0, 0,
  12553. 1, 1, 1, 0, 0, 0, 0, 0,
  12554. 0, 0, 0, 0, 0, 0, 0, 0,
  12555. 1, 1, 0, 1, 1, 1, 1, 1,
  12556. 0, 1, 1, 1, 1, 1, 1, 0,
  12557. 0, 0, 0, 0
  12558. };
  12559. static const short _json_index_offsets[] = {
  12560. 0, 0, 11, 13, 18, 23, 28, 30,
  12561. 32, 34, 36, 38, 40, 42, 44, 46,
  12562. 48, 53, 58, 60, 64, 69, 74, 79,
  12563. 83, 87, 90, 94, 96, 100, 104, 106,
  12564. 108, 113, 116, 119, 129, 133, 137, 141,
  12565. 145, 148, 152, 155, 158, 160, 163, 165,
  12566. 169, 171, 173, 175, 177, 179, 181, 183,
  12567. 185, 187, 189, 191, 193, 195, 197, 199,
  12568. 201, 203, 205, 207, 212, 214, 216, 218,
  12569. 220, 222, 224, 226, 231, 240, 242, 243,
  12570. 244, 249, 254, 259, 261, 263, 265, 267,
  12571. 268, 270, 272, 274, 275, 277, 279, 281,
  12572. 282, 287, 292, 294, 298, 303, 308, 313,
  12573. 317, 318, 321, 324, 327, 330, 333, 336,
  12574. 337, 338, 339, 340
  12575. };
  12576. static const unsigned char _json_indicies[] = {
  12577. 0, 2, 3, 4, 5, 6, 7, 8,
  12578. 0, 3, 1, 9, 1, 11, 12, 1,
  12579. 11, 10, 13, 14, 12, 13, 1, 14,
  12580. 1, 1, 14, 10, 15, 1, 16, 1,
  12581. 17, 1, 18, 1, 19, 1, 20, 1,
  12582. 21, 1, 22, 1, 23, 1, 24, 1,
  12583. 25, 26, 27, 25, 1, 28, 29, 30,
  12584. 28, 1, 31, 1, 32, 33, 32, 1,
  12585. 33, 1, 1, 33, 34, 35, 36, 37,
  12586. 35, 1, 38, 39, 30, 38, 1, 39,
  12587. 29, 39, 1, 40, 41, 42, 1, 41,
  12588. 42, 1, 44, 45, 45, 43, 46, 1,
  12589. 45, 45, 46, 43, 47, 47, 48, 1,
  12590. 48, 1, 48, 43, 44, 45, 45, 42,
  12591. 43, 50, 51, 49, 53, 54, 52, 55,
  12592. 55, 55, 55, 55, 55, 55, 55, 56,
  12593. 1, 57, 57, 57, 1, 58, 58, 58,
  12594. 1, 59, 59, 59, 1, 60, 60, 60,
  12595. 1, 62, 63, 61, 64, 65, 66, 1,
  12596. 67, 68, 1, 69, 70, 1, 71, 1,
  12597. 70, 71, 1, 72, 1, 69, 70, 68,
  12598. 1, 73, 1, 74, 1, 75, 1, 76,
  12599. 1, 77, 1, 78, 1, 79, 1, 80,
  12600. 1, 81, 1, 82, 1, 83, 1, 84,
  12601. 1, 85, 1, 86, 1, 87, 1, 88,
  12602. 1, 89, 1, 90, 1, 91, 1, 92,
  12603. 92, 93, 94, 1, 95, 1, 96, 1,
  12604. 97, 1, 98, 1, 99, 1, 100, 1,
  12605. 101, 1, 102, 102, 103, 101, 1, 104,
  12606. 105, 106, 107, 108, 109, 110, 105, 1,
  12607. 111, 1, 112, 113, 115, 116, 1, 115,
  12608. 114, 117, 118, 116, 117, 1, 118, 1,
  12609. 1, 118, 114, 119, 1, 120, 1, 121,
  12610. 1, 122, 1, 123, 124, 1, 125, 1,
  12611. 126, 1, 127, 128, 1, 129, 1, 130,
  12612. 1, 131, 132, 133, 134, 132, 1, 135,
  12613. 136, 137, 135, 1, 138, 1, 139, 140,
  12614. 139, 1, 140, 1, 1, 140, 141, 142,
  12615. 143, 144, 142, 1, 145, 146, 137, 145,
  12616. 1, 146, 136, 146, 1, 147, 148, 148,
  12617. 1, 149, 149, 1, 150, 150, 1, 151,
  12618. 151, 1, 152, 152, 1, 153, 153, 1,
  12619. 1, 1, 1, 1, 1, 0
  12620. };
  12621. static const char _json_trans_targs[] = {
  12622. 1, 0, 2, 106, 3, 6, 10, 13,
  12623. 16, 105, 4, 3, 105, 4, 5, 7,
  12624. 8, 9, 107, 11, 12, 108, 14, 15,
  12625. 109, 17, 18, 110, 17, 18, 110, 19,
  12626. 19, 20, 21, 22, 23, 110, 22, 23,
  12627. 25, 26, 32, 111, 27, 29, 28, 30,
  12628. 31, 34, 112, 35, 34, 112, 35, 33,
  12629. 36, 37, 38, 39, 40, 34, 112, 35,
  12630. 42, 43, 47, 43, 47, 44, 46, 45,
  12631. 113, 49, 50, 51, 52, 53, 54, 55,
  12632. 56, 57, 58, 59, 60, 61, 62, 63,
  12633. 64, 65, 66, 67, 68, 74, 73, 69,
  12634. 70, 71, 72, 73, 114, 75, 68, 73,
  12635. 77, 79, 80, 83, 88, 92, 96, 78,
  12636. 115, 115, 81, 80, 78, 81, 82, 84,
  12637. 85, 86, 87, 115, 89, 90, 91, 115,
  12638. 93, 94, 95, 115, 97, 98, 104, 97,
  12639. 98, 104, 99, 99, 100, 101, 102, 103,
  12640. 104, 102, 103, 115, 105, 105, 105, 105,
  12641. 105, 105
  12642. };
  12643. static const char _json_trans_actions[] = {
  12644. 0, 0, 84, 78, 33, 0, 0, 0,
  12645. 47, 39, 25, 0, 35, 0, 0, 0,
  12646. 0, 0, 0, 0, 0, 0, 0, 0,
  12647. 0, 31, 96, 31, 0, 72, 0, 27,
  12648. 0, 0, 25, 29, 29, 29, 0, 0,
  12649. 0, 0, 0, 3, 0, 0, 0, 0,
  12650. 0, 5, 15, 0, 0, 51, 7, 13,
  12651. 0, 54, 9, 9, 9, 57, 60, 11,
  12652. 17, 17, 17, 0, 0, 0, 19, 0,
  12653. 21, 23, 0, 0, 0, 0, 0, 0,
  12654. 0, 0, 0, 0, 0, 0, 0, 0,
  12655. 0, 0, 0, 0, 104, 63, 104, 0,
  12656. 0, 0, 0, 0, 69, 0, 66, 66,
  12657. 84, 78, 33, 0, 0, 0, 47, 39,
  12658. 49, 81, 25, 0, 35, 0, 0, 0,
  12659. 0, 0, 0, 90, 0, 0, 0, 93,
  12660. 0, 0, 0, 87, 31, 96, 31, 0,
  12661. 72, 0, 27, 0, 0, 25, 29, 29,
  12662. 29, 0, 0, 100, 0, 37, 43, 45,
  12663. 41, 75
  12664. };
  12665. static const char _json_eof_actions[] = {
  12666. 0, 0, 0, 0, 0, 0, 0, 0,
  12667. 0, 0, 0, 0, 0, 0, 0, 0,
  12668. 0, 0, 0, 0, 0, 0, 0, 0,
  12669. 0, 0, 1, 0, 1, 0, 0, 1,
  12670. 1, 0, 0, 0, 0, 0, 0, 0,
  12671. 0, 0, 0, 0, 0, 0, 0, 0,
  12672. 0, 0, 0, 0, 0, 0, 0, 0,
  12673. 0, 0, 0, 0, 0, 0, 0, 0,
  12674. 0, 0, 0, 0, 0, 0, 0, 0,
  12675. 0, 0, 0, 0, 0, 0, 0, 0,
  12676. 0, 0, 0, 0, 0, 0, 0, 0,
  12677. 0, 0, 0, 0, 0, 0, 0, 0,
  12678. 0, 0, 0, 0, 0, 0, 0, 0,
  12679. 0, 0, 37, 43, 45, 41, 75, 0,
  12680. 0, 0, 0, 0
  12681. };
  12682. static const int json_start = 1;
  12683. static const int json_en_number_machine = 24;
  12684. static const int json_en_string_machine = 33;
  12685. static const int json_en_duration_machine = 41;
  12686. static const int json_en_timestamp_machine = 48;
  12687. static const int json_en_value_machine = 76;
  12688. static const int json_en_main = 1;
  12689. //#line 2150 "upb/json/parser.rl"
  12690. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  12691. const upb_bufhandle *handle) {
  12692. upb_json_parser *parser = closure;
  12693. /* Variables used by Ragel's generated code. */
  12694. int cs = parser->current_state;
  12695. int *stack = parser->parser_stack;
  12696. int top = parser->parser_top;
  12697. const char *p = buf;
  12698. const char *pe = buf + size;
  12699. const char *eof = &eof_ch;
  12700. parser->handle = handle;
  12701. UPB_UNUSED(hd);
  12702. UPB_UNUSED(handle);
  12703. capture_resume(parser, buf);
  12704. //#line 2290 "upb/json/parser.c"
  12705. {
  12706. int _klen;
  12707. unsigned int _trans;
  12708. const char *_acts;
  12709. unsigned int _nacts;
  12710. const char *_keys;
  12711. if ( p == pe )
  12712. goto _test_eof;
  12713. if ( cs == 0 )
  12714. goto _out;
  12715. _resume:
  12716. _keys = _json_trans_keys + _json_key_offsets[cs];
  12717. _trans = _json_index_offsets[cs];
  12718. _klen = _json_single_lengths[cs];
  12719. if ( _klen > 0 ) {
  12720. const char *_lower = _keys;
  12721. const char *_mid;
  12722. const char *_upper = _keys + _klen - 1;
  12723. while (1) {
  12724. if ( _upper < _lower )
  12725. break;
  12726. _mid = _lower + ((_upper-_lower) >> 1);
  12727. if ( (*p) < *_mid )
  12728. _upper = _mid - 1;
  12729. else if ( (*p) > *_mid )
  12730. _lower = _mid + 1;
  12731. else {
  12732. _trans += (unsigned int)(_mid - _keys);
  12733. goto _match;
  12734. }
  12735. }
  12736. _keys += _klen;
  12737. _trans += _klen;
  12738. }
  12739. _klen = _json_range_lengths[cs];
  12740. if ( _klen > 0 ) {
  12741. const char *_lower = _keys;
  12742. const char *_mid;
  12743. const char *_upper = _keys + (_klen<<1) - 2;
  12744. while (1) {
  12745. if ( _upper < _lower )
  12746. break;
  12747. _mid = _lower + (((_upper-_lower) >> 1) & ~1);
  12748. if ( (*p) < _mid[0] )
  12749. _upper = _mid - 2;
  12750. else if ( (*p) > _mid[1] )
  12751. _lower = _mid + 2;
  12752. else {
  12753. _trans += (unsigned int)((_mid - _keys)>>1);
  12754. goto _match;
  12755. }
  12756. }
  12757. _trans += _klen;
  12758. }
  12759. _match:
  12760. _trans = _json_indicies[_trans];
  12761. cs = _json_trans_targs[_trans];
  12762. if ( _json_trans_actions[_trans] == 0 )
  12763. goto _again;
  12764. _acts = _json_actions + _json_trans_actions[_trans];
  12765. _nacts = (unsigned int) *_acts++;
  12766. while ( _nacts-- > 0 )
  12767. {
  12768. switch ( *_acts++ )
  12769. {
  12770. case 1:
  12771. //#line 2021 "upb/json/parser.rl"
  12772. { p--; {cs = stack[--top]; goto _again;} }
  12773. break;
  12774. case 2:
  12775. //#line 2023 "upb/json/parser.rl"
  12776. { p--; {stack[top++] = cs; cs = 24; goto _again;} }
  12777. break;
  12778. case 3:
  12779. //#line 2027 "upb/json/parser.rl"
  12780. { start_text(parser, p); }
  12781. break;
  12782. case 4:
  12783. //#line 2028 "upb/json/parser.rl"
  12784. { CHECK_RETURN_TOP(end_text(parser, p)); }
  12785. break;
  12786. case 5:
  12787. //#line 2034 "upb/json/parser.rl"
  12788. { start_hex(parser); }
  12789. break;
  12790. case 6:
  12791. //#line 2035 "upb/json/parser.rl"
  12792. { hexdigit(parser, p); }
  12793. break;
  12794. case 7:
  12795. //#line 2036 "upb/json/parser.rl"
  12796. { CHECK_RETURN_TOP(end_hex(parser)); }
  12797. break;
  12798. case 8:
  12799. //#line 2042 "upb/json/parser.rl"
  12800. { CHECK_RETURN_TOP(escape(parser, p)); }
  12801. break;
  12802. case 9:
  12803. //#line 2048 "upb/json/parser.rl"
  12804. { p--; {cs = stack[--top]; goto _again;} }
  12805. break;
  12806. case 10:
  12807. //#line 2060 "upb/json/parser.rl"
  12808. { start_duration_base(parser, p); }
  12809. break;
  12810. case 11:
  12811. //#line 2061 "upb/json/parser.rl"
  12812. { CHECK_RETURN_TOP(end_duration_base(parser, p)); }
  12813. break;
  12814. case 12:
  12815. //#line 2063 "upb/json/parser.rl"
  12816. { p--; {cs = stack[--top]; goto _again;} }
  12817. break;
  12818. case 13:
  12819. //#line 2068 "upb/json/parser.rl"
  12820. { start_timestamp_base(parser, p); }
  12821. break;
  12822. case 14:
  12823. //#line 2069 "upb/json/parser.rl"
  12824. { CHECK_RETURN_TOP(end_timestamp_base(parser, p)); }
  12825. break;
  12826. case 15:
  12827. //#line 2071 "upb/json/parser.rl"
  12828. { start_timestamp_fraction(parser, p); }
  12829. break;
  12830. case 16:
  12831. //#line 2072 "upb/json/parser.rl"
  12832. { CHECK_RETURN_TOP(end_timestamp_fraction(parser, p)); }
  12833. break;
  12834. case 17:
  12835. //#line 2074 "upb/json/parser.rl"
  12836. { start_timestamp_zone(parser, p); }
  12837. break;
  12838. case 18:
  12839. //#line 2075 "upb/json/parser.rl"
  12840. { CHECK_RETURN_TOP(end_timestamp_zone(parser, p)); }
  12841. break;
  12842. case 19:
  12843. //#line 2077 "upb/json/parser.rl"
  12844. { p--; {cs = stack[--top]; goto _again;} }
  12845. break;
  12846. case 20:
  12847. //#line 2082 "upb/json/parser.rl"
  12848. {
  12849. if (is_wellknown_msg(parser, UPB_WELLKNOWN_TIMESTAMP)) {
  12850. {stack[top++] = cs; cs = 48; goto _again;}
  12851. } else if (is_wellknown_msg(parser, UPB_WELLKNOWN_DURATION)) {
  12852. {stack[top++] = cs; cs = 41; goto _again;}
  12853. } else {
  12854. {stack[top++] = cs; cs = 33; goto _again;}
  12855. }
  12856. }
  12857. break;
  12858. case 21:
  12859. //#line 2093 "upb/json/parser.rl"
  12860. { p--; {stack[top++] = cs; cs = 76; goto _again;} }
  12861. break;
  12862. case 22:
  12863. //#line 2098 "upb/json/parser.rl"
  12864. { start_member(parser); }
  12865. break;
  12866. case 23:
  12867. //#line 2099 "upb/json/parser.rl"
  12868. { CHECK_RETURN_TOP(end_membername(parser)); }
  12869. break;
  12870. case 24:
  12871. //#line 2102 "upb/json/parser.rl"
  12872. { end_member(parser); }
  12873. break;
  12874. case 25:
  12875. //#line 2108 "upb/json/parser.rl"
  12876. { start_object(parser); }
  12877. break;
  12878. case 26:
  12879. //#line 2111 "upb/json/parser.rl"
  12880. { end_object(parser); }
  12881. break;
  12882. case 27:
  12883. //#line 2117 "upb/json/parser.rl"
  12884. { CHECK_RETURN_TOP(start_array(parser)); }
  12885. break;
  12886. case 28:
  12887. //#line 2121 "upb/json/parser.rl"
  12888. { end_array(parser); }
  12889. break;
  12890. case 29:
  12891. //#line 2126 "upb/json/parser.rl"
  12892. { CHECK_RETURN_TOP(start_number(parser, p)); }
  12893. break;
  12894. case 30:
  12895. //#line 2127 "upb/json/parser.rl"
  12896. { CHECK_RETURN_TOP(end_number(parser, p)); }
  12897. break;
  12898. case 31:
  12899. //#line 2129 "upb/json/parser.rl"
  12900. { CHECK_RETURN_TOP(start_stringval(parser)); }
  12901. break;
  12902. case 32:
  12903. //#line 2130 "upb/json/parser.rl"
  12904. { CHECK_RETURN_TOP(end_stringval(parser)); }
  12905. break;
  12906. case 33:
  12907. //#line 2132 "upb/json/parser.rl"
  12908. { CHECK_RETURN_TOP(end_bool(parser, true)); }
  12909. break;
  12910. case 34:
  12911. //#line 2134 "upb/json/parser.rl"
  12912. { CHECK_RETURN_TOP(end_bool(parser, false)); }
  12913. break;
  12914. case 35:
  12915. //#line 2136 "upb/json/parser.rl"
  12916. { CHECK_RETURN_TOP(end_null(parser)); }
  12917. break;
  12918. case 36:
  12919. //#line 2138 "upb/json/parser.rl"
  12920. { CHECK_RETURN_TOP(start_subobject_full(parser)); }
  12921. break;
  12922. case 37:
  12923. //#line 2139 "upb/json/parser.rl"
  12924. { end_subobject_full(parser); }
  12925. break;
  12926. case 38:
  12927. //#line 2144 "upb/json/parser.rl"
  12928. { p--; {cs = stack[--top]; goto _again;} }
  12929. break;
  12930. //#line 2524 "upb/json/parser.c"
  12931. }
  12932. }
  12933. _again:
  12934. if ( cs == 0 )
  12935. goto _out;
  12936. if ( ++p != pe )
  12937. goto _resume;
  12938. _test_eof: {}
  12939. if ( p == eof )
  12940. {
  12941. const char *__acts = _json_actions + _json_eof_actions[cs];
  12942. unsigned int __nacts = (unsigned int) *__acts++;
  12943. while ( __nacts-- > 0 ) {
  12944. switch ( *__acts++ ) {
  12945. case 0:
  12946. //#line 2019 "upb/json/parser.rl"
  12947. { p--; {cs = stack[--top]; goto _again;} }
  12948. break;
  12949. case 26:
  12950. //#line 2111 "upb/json/parser.rl"
  12951. { end_object(parser); }
  12952. break;
  12953. case 30:
  12954. //#line 2127 "upb/json/parser.rl"
  12955. { CHECK_RETURN_TOP(end_number(parser, p)); }
  12956. break;
  12957. case 33:
  12958. //#line 2132 "upb/json/parser.rl"
  12959. { CHECK_RETURN_TOP(end_bool(parser, true)); }
  12960. break;
  12961. case 34:
  12962. //#line 2134 "upb/json/parser.rl"
  12963. { CHECK_RETURN_TOP(end_bool(parser, false)); }
  12964. break;
  12965. case 35:
  12966. //#line 2136 "upb/json/parser.rl"
  12967. { CHECK_RETURN_TOP(end_null(parser)); }
  12968. break;
  12969. case 37:
  12970. //#line 2139 "upb/json/parser.rl"
  12971. { end_subobject_full(parser); }
  12972. break;
  12973. //#line 2568 "upb/json/parser.c"
  12974. }
  12975. }
  12976. }
  12977. _out: {}
  12978. }
  12979. //#line 2172 "upb/json/parser.rl"
  12980. if (p != pe) {
  12981. upb_status_seterrf(&parser->status, "Parse error at '%.*s'\n", pe - p, p);
  12982. upb_env_reporterror(parser->env, &parser->status);
  12983. } else {
  12984. capture_suspend(parser, &p);
  12985. }
  12986. error:
  12987. /* Save parsing state back to parser. */
  12988. parser->current_state = cs;
  12989. parser->parser_top = top;
  12990. return p - buf;
  12991. }
  12992. bool end(void *closure, const void *hd) {
  12993. upb_json_parser *parser = closure;
  12994. /* Prevent compile warning on unused static constants. */
  12995. UPB_UNUSED(json_start);
  12996. UPB_UNUSED(json_en_duration_machine);
  12997. UPB_UNUSED(json_en_number_machine);
  12998. UPB_UNUSED(json_en_string_machine);
  12999. UPB_UNUSED(json_en_timestamp_machine);
  13000. UPB_UNUSED(json_en_value_machine);
  13001. UPB_UNUSED(json_en_main);
  13002. parse(parser, hd, &eof_ch, 0, NULL);
  13003. return parser->current_state >=
  13004. //#line 2608 "upb/json/parser.c"
  13005. 105
  13006. //#line 2202 "upb/json/parser.rl"
  13007. ;
  13008. }
  13009. static void json_parser_reset(upb_json_parser *p) {
  13010. int cs;
  13011. int top;
  13012. p->top = p->stack;
  13013. p->top->f = NULL;
  13014. p->top->is_map = false;
  13015. p->top->is_mapentry = false;
  13016. p->top->is_unknown_field = false;
  13017. /* Emit Ragel initialization of the parser. */
  13018. //#line 2626 "upb/json/parser.c"
  13019. {
  13020. cs = json_start;
  13021. top = 0;
  13022. }
  13023. //#line 2217 "upb/json/parser.rl"
  13024. p->current_state = cs;
  13025. p->parser_top = top;
  13026. accumulate_clear(p);
  13027. p->multipart_state = MULTIPART_INACTIVE;
  13028. p->capture = NULL;
  13029. p->accumulated = NULL;
  13030. upb_status_clear(&p->status);
  13031. }
  13032. static void visit_json_parsermethod(const upb_refcounted *r,
  13033. upb_refcounted_visit *visit,
  13034. void *closure) {
  13035. const upb_json_parsermethod *method = (upb_json_parsermethod*)r;
  13036. visit(r, upb_msgdef_upcast2(method->msg), closure);
  13037. }
  13038. static void free_json_parsermethod(upb_refcounted *r) {
  13039. upb_json_parsermethod *method = (upb_json_parsermethod*)r;
  13040. upb_inttable_iter i;
  13041. upb_inttable_begin(&i, &method->name_tables);
  13042. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  13043. upb_value val = upb_inttable_iter_value(&i);
  13044. upb_strtable *t = upb_value_getptr(val);
  13045. upb_strtable_uninit(t);
  13046. upb_gfree(t);
  13047. }
  13048. upb_inttable_uninit(&method->name_tables);
  13049. upb_gfree(r);
  13050. }
  13051. static void add_jsonname_table(upb_json_parsermethod *m, const upb_msgdef* md) {
  13052. upb_msg_field_iter i;
  13053. upb_strtable *t;
  13054. /* It would be nice to stack-allocate this, but protobufs do not limit the
  13055. * length of fields to any reasonable limit. */
  13056. char *buf = NULL;
  13057. size_t len = 0;
  13058. if (upb_inttable_lookupptr(&m->name_tables, md, NULL)) {
  13059. return;
  13060. }
  13061. /* TODO(haberman): handle malloc failure. */
  13062. t = upb_gmalloc(sizeof(*t));
  13063. upb_strtable_init(t, UPB_CTYPE_CONSTPTR);
  13064. upb_inttable_insertptr(&m->name_tables, md, upb_value_ptr(t));
  13065. for(upb_msg_field_begin(&i, md);
  13066. !upb_msg_field_done(&i);
  13067. upb_msg_field_next(&i)) {
  13068. const upb_fielddef *f = upb_msg_iter_field(&i);
  13069. /* Add an entry for the JSON name. */
  13070. size_t field_len = upb_fielddef_getjsonname(f, buf, len);
  13071. if (field_len > len) {
  13072. size_t len2;
  13073. buf = upb_grealloc(buf, 0, field_len);
  13074. len = field_len;
  13075. len2 = upb_fielddef_getjsonname(f, buf, len);
  13076. UPB_ASSERT(len == len2);
  13077. }
  13078. upb_strtable_insert(t, buf, upb_value_constptr(f));
  13079. if (strcmp(buf, upb_fielddef_name(f)) != 0) {
  13080. /* Since the JSON name is different from the regular field name, add an
  13081. * entry for the raw name (compliant proto3 JSON parsers must accept
  13082. * both). */
  13083. upb_strtable_insert(t, upb_fielddef_name(f), upb_value_constptr(f));
  13084. }
  13085. if (upb_fielddef_issubmsg(f)) {
  13086. add_jsonname_table(m, upb_fielddef_msgsubdef(f));
  13087. }
  13088. }
  13089. upb_gfree(buf);
  13090. }
  13091. /* Public API *****************************************************************/
  13092. upb_json_parser *upb_json_parser_create(upb_env *env,
  13093. const upb_json_parsermethod *method,
  13094. upb_sink *output,
  13095. bool ignore_json_unknown) {
  13096. #ifndef NDEBUG
  13097. const size_t size_before = upb_env_bytesallocated(env);
  13098. #endif
  13099. upb_json_parser *p = upb_env_malloc(env, sizeof(upb_json_parser));
  13100. if (!p) return false;
  13101. p->env = env;
  13102. p->method = method;
  13103. p->limit = p->stack + UPB_JSON_MAX_DEPTH;
  13104. p->accumulate_buf = NULL;
  13105. p->accumulate_buf_size = 0;
  13106. upb_bytessink_reset(&p->input_, &method->input_handler_, p);
  13107. json_parser_reset(p);
  13108. upb_sink_reset(&p->top->sink, output->handlers, output->closure);
  13109. p->top->m = upb_handlers_msgdef(output->handlers);
  13110. set_name_table(p, p->top);
  13111. p->ignore_json_unknown = ignore_json_unknown;
  13112. /* If this fails, uncomment and increase the value in parser.h. */
  13113. /* fprintf(stderr, "%zd\n", upb_env_bytesallocated(env) - size_before); */
  13114. UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(env) - size_before <=
  13115. UPB_JSON_PARSER_SIZE);
  13116. return p;
  13117. }
  13118. upb_bytessink *upb_json_parser_input(upb_json_parser *p) {
  13119. return &p->input_;
  13120. }
  13121. upb_json_parsermethod *upb_json_parsermethod_new(const upb_msgdef* md,
  13122. const void* owner) {
  13123. static const struct upb_refcounted_vtbl vtbl = {visit_json_parsermethod,
  13124. free_json_parsermethod};
  13125. upb_json_parsermethod *ret = upb_gmalloc(sizeof(*ret));
  13126. upb_refcounted_init(upb_json_parsermethod_upcast_mutable(ret), &vtbl, owner);
  13127. ret->msg = md;
  13128. upb_ref2(md, ret);
  13129. upb_byteshandler_init(&ret->input_handler_);
  13130. upb_byteshandler_setstring(&ret->input_handler_, parse, ret);
  13131. upb_byteshandler_setendstr(&ret->input_handler_, end, ret);
  13132. upb_inttable_init(&ret->name_tables, UPB_CTYPE_PTR);
  13133. add_jsonname_table(ret, md);
  13134. return ret;
  13135. }
  13136. const upb_byteshandler *upb_json_parsermethod_inputhandler(
  13137. const upb_json_parsermethod *m) {
  13138. return &m->input_handler_;
  13139. }
  13140. /*
  13141. ** This currently uses snprintf() to format primitives, and could be optimized
  13142. ** further.
  13143. */
  13144. #include <string.h>
  13145. #include <stdint.h>
  13146. #include <time.h>
  13147. struct upb_json_printer {
  13148. upb_sink input_;
  13149. /* BytesSink closure. */
  13150. void *subc_;
  13151. upb_bytessink *output_;
  13152. /* We track the depth so that we know when to emit startstr/endstr on the
  13153. * output. */
  13154. int depth_;
  13155. /* Have we emitted the first element? This state is necessary to emit commas
  13156. * without leaving a trailing comma in arrays/maps. We keep this state per
  13157. * frame depth.
  13158. *
  13159. * Why max_depth * 2? UPB_MAX_HANDLER_DEPTH counts depth as nested messages.
  13160. * We count frames (contexts in which we separate elements by commas) as both
  13161. * repeated fields and messages (maps), and the worst case is a
  13162. * message->repeated field->submessage->repeated field->... nesting. */
  13163. bool first_elem_[UPB_MAX_HANDLER_DEPTH * 2];
  13164. /* To print timestamp, printer needs to cache its seconds and nanos values
  13165. * and convert them when ending timestamp message. See comments of
  13166. * printer_sethandlers_timestamp for more detail. */
  13167. int64_t seconds;
  13168. int32_t nanos;
  13169. };
  13170. /* StringPiece; a pointer plus a length. */
  13171. typedef struct {
  13172. char *ptr;
  13173. size_t len;
  13174. } strpc;
  13175. void freestrpc(void *ptr) {
  13176. strpc *pc = ptr;
  13177. upb_gfree(pc->ptr);
  13178. upb_gfree(pc);
  13179. }
  13180. /* Convert fielddef name to JSON name and return as a string piece. */
  13181. strpc *newstrpc(upb_handlers *h, const upb_fielddef *f,
  13182. bool preserve_fieldnames) {
  13183. /* TODO(haberman): handle malloc failure. */
  13184. strpc *ret = upb_gmalloc(sizeof(*ret));
  13185. if (preserve_fieldnames) {
  13186. ret->ptr = upb_gstrdup(upb_fielddef_name(f));
  13187. ret->len = strlen(ret->ptr);
  13188. } else {
  13189. size_t len;
  13190. ret->len = upb_fielddef_getjsonname(f, NULL, 0);
  13191. ret->ptr = upb_gmalloc(ret->len);
  13192. len = upb_fielddef_getjsonname(f, ret->ptr, ret->len);
  13193. UPB_ASSERT(len == ret->len);
  13194. ret->len--; /* NULL */
  13195. }
  13196. upb_handlers_addcleanup(h, ret, freestrpc);
  13197. return ret;
  13198. }
  13199. /* ------------ JSON string printing: values, maps, arrays ------------------ */
  13200. static void print_data(
  13201. upb_json_printer *p, const char *buf, unsigned int len) {
  13202. /* TODO: Will need to change if we support pushback from the sink. */
  13203. size_t n = upb_bytessink_putbuf(p->output_, p->subc_, buf, len, NULL);
  13204. UPB_ASSERT(n == len);
  13205. }
  13206. static void print_comma(upb_json_printer *p) {
  13207. if (!p->first_elem_[p->depth_]) {
  13208. print_data(p, ",", 1);
  13209. }
  13210. p->first_elem_[p->depth_] = false;
  13211. }
  13212. /* Helpers that print properly formatted elements to the JSON output stream. */
  13213. /* Used for escaping control chars in strings. */
  13214. static const char kControlCharLimit = 0x20;
  13215. UPB_INLINE bool is_json_escaped(char c) {
  13216. /* See RFC 4627. */
  13217. unsigned char uc = (unsigned char)c;
  13218. return uc < kControlCharLimit || uc == '"' || uc == '\\';
  13219. }
  13220. UPB_INLINE const char* json_nice_escape(char c) {
  13221. switch (c) {
  13222. case '"': return "\\\"";
  13223. case '\\': return "\\\\";
  13224. case '\b': return "\\b";
  13225. case '\f': return "\\f";
  13226. case '\n': return "\\n";
  13227. case '\r': return "\\r";
  13228. case '\t': return "\\t";
  13229. default: return NULL;
  13230. }
  13231. }
  13232. /* Write a properly escaped string chunk. The surrounding quotes are *not*
  13233. * printed; this is so that the caller has the option of emitting the string
  13234. * content in chunks. */
  13235. static void putstring(upb_json_printer *p, const char *buf, unsigned int len) {
  13236. const char* unescaped_run = NULL;
  13237. unsigned int i;
  13238. for (i = 0; i < len; i++) {
  13239. char c = buf[i];
  13240. /* Handle escaping. */
  13241. if (is_json_escaped(c)) {
  13242. /* Use a "nice" escape, like \n, if one exists for this character. */
  13243. const char* escape = json_nice_escape(c);
  13244. /* If we don't have a specific 'nice' escape code, use a \uXXXX-style
  13245. * escape. */
  13246. char escape_buf[8];
  13247. if (!escape) {
  13248. unsigned char byte = (unsigned char)c;
  13249. _upb_snprintf(escape_buf, sizeof(escape_buf), "\\u%04x", (int)byte);
  13250. escape = escape_buf;
  13251. }
  13252. /* N.B. that we assume that the input encoding is equal to the output
  13253. * encoding (both UTF-8 for now), so for chars >= 0x20 and != \, ", we
  13254. * can simply pass the bytes through. */
  13255. /* If there's a current run of unescaped chars, print that run first. */
  13256. if (unescaped_run) {
  13257. print_data(p, unescaped_run, &buf[i] - unescaped_run);
  13258. unescaped_run = NULL;
  13259. }
  13260. /* Then print the escape code. */
  13261. print_data(p, escape, strlen(escape));
  13262. } else {
  13263. /* Add to the current unescaped run of characters. */
  13264. if (unescaped_run == NULL) {
  13265. unescaped_run = &buf[i];
  13266. }
  13267. }
  13268. }
  13269. /* If the string ended in a run of unescaped characters, print that last run. */
  13270. if (unescaped_run) {
  13271. print_data(p, unescaped_run, &buf[len] - unescaped_run);
  13272. }
  13273. }
  13274. #define CHKLENGTH(x) if (!(x)) return -1;
  13275. /* Helpers that format floating point values according to our custom formats.
  13276. * Right now we use %.8g and %.17g for float/double, respectively, to match
  13277. * proto2::util::JsonFormat's defaults. May want to change this later. */
  13278. const char neginf[] = "\"-Infinity\"";
  13279. const char inf[] = "\"Infinity\"";
  13280. static size_t fmt_double(double val, char* buf, size_t length) {
  13281. if (val == (1.0 / 0.0)) {
  13282. CHKLENGTH(length >= strlen(inf));
  13283. strcpy(buf, inf);
  13284. return strlen(inf);
  13285. } else if (val == (-1.0 / 0.0)) {
  13286. CHKLENGTH(length >= strlen(neginf));
  13287. strcpy(buf, neginf);
  13288. return strlen(neginf);
  13289. } else {
  13290. size_t n = _upb_snprintf(buf, length, "%.17g", val);
  13291. CHKLENGTH(n > 0 && n < length);
  13292. return n;
  13293. }
  13294. }
  13295. static size_t fmt_float(float val, char* buf, size_t length) {
  13296. size_t n = _upb_snprintf(buf, length, "%.8g", val);
  13297. CHKLENGTH(n > 0 && n < length);
  13298. return n;
  13299. }
  13300. static size_t fmt_bool(bool val, char* buf, size_t length) {
  13301. size_t n = _upb_snprintf(buf, length, "%s", (val ? "true" : "false"));
  13302. CHKLENGTH(n > 0 && n < length);
  13303. return n;
  13304. }
  13305. static size_t fmt_int64(long val, char* buf, size_t length) {
  13306. size_t n = _upb_snprintf(buf, length, "%ld", val);
  13307. CHKLENGTH(n > 0 && n < length);
  13308. return n;
  13309. }
  13310. static size_t fmt_uint64(unsigned long long val, char* buf, size_t length) {
  13311. size_t n = _upb_snprintf(buf, length, "%llu", val);
  13312. CHKLENGTH(n > 0 && n < length);
  13313. return n;
  13314. }
  13315. /* Print a map key given a field name. Called by scalar field handlers and by
  13316. * startseq for repeated fields. */
  13317. static bool putkey(void *closure, const void *handler_data) {
  13318. upb_json_printer *p = closure;
  13319. const strpc *key = handler_data;
  13320. print_comma(p);
  13321. print_data(p, "\"", 1);
  13322. putstring(p, key->ptr, key->len);
  13323. print_data(p, "\":", 2);
  13324. return true;
  13325. }
  13326. #define CHKFMT(val) if ((val) == (size_t)-1) return false;
  13327. #define CHK(val) if (!(val)) return false;
  13328. #define TYPE_HANDLERS(type, fmt_func) \
  13329. static bool put##type(void *closure, const void *handler_data, type val) { \
  13330. upb_json_printer *p = closure; \
  13331. char data[64]; \
  13332. size_t length = fmt_func(val, data, sizeof(data)); \
  13333. UPB_UNUSED(handler_data); \
  13334. CHKFMT(length); \
  13335. print_data(p, data, length); \
  13336. return true; \
  13337. } \
  13338. static bool scalar_##type(void *closure, const void *handler_data, \
  13339. type val) { \
  13340. CHK(putkey(closure, handler_data)); \
  13341. CHK(put##type(closure, handler_data, val)); \
  13342. return true; \
  13343. } \
  13344. static bool repeated_##type(void *closure, const void *handler_data, \
  13345. type val) { \
  13346. upb_json_printer *p = closure; \
  13347. print_comma(p); \
  13348. CHK(put##type(closure, handler_data, val)); \
  13349. return true; \
  13350. }
  13351. #define TYPE_HANDLERS_MAPKEY(type, fmt_func) \
  13352. static bool putmapkey_##type(void *closure, const void *handler_data, \
  13353. type val) { \
  13354. upb_json_printer *p = closure; \
  13355. print_data(p, "\"", 1); \
  13356. CHK(put##type(closure, handler_data, val)); \
  13357. print_data(p, "\":", 2); \
  13358. return true; \
  13359. }
  13360. TYPE_HANDLERS(double, fmt_double)
  13361. TYPE_HANDLERS(float, fmt_float)
  13362. TYPE_HANDLERS(bool, fmt_bool)
  13363. TYPE_HANDLERS(int32_t, fmt_int64)
  13364. TYPE_HANDLERS(uint32_t, fmt_int64)
  13365. TYPE_HANDLERS(int64_t, fmt_int64)
  13366. TYPE_HANDLERS(uint64_t, fmt_uint64)
  13367. /* double and float are not allowed to be map keys. */
  13368. TYPE_HANDLERS_MAPKEY(bool, fmt_bool)
  13369. TYPE_HANDLERS_MAPKEY(int32_t, fmt_int64)
  13370. TYPE_HANDLERS_MAPKEY(uint32_t, fmt_int64)
  13371. TYPE_HANDLERS_MAPKEY(int64_t, fmt_int64)
  13372. TYPE_HANDLERS_MAPKEY(uint64_t, fmt_uint64)
  13373. #undef TYPE_HANDLERS
  13374. #undef TYPE_HANDLERS_MAPKEY
  13375. typedef struct {
  13376. void *keyname;
  13377. const upb_enumdef *enumdef;
  13378. } EnumHandlerData;
  13379. static bool scalar_enum(void *closure, const void *handler_data,
  13380. int32_t val) {
  13381. const EnumHandlerData *hd = handler_data;
  13382. upb_json_printer *p = closure;
  13383. const char *symbolic_name;
  13384. CHK(putkey(closure, hd->keyname));
  13385. symbolic_name = upb_enumdef_iton(hd->enumdef, val);
  13386. if (symbolic_name) {
  13387. print_data(p, "\"", 1);
  13388. putstring(p, symbolic_name, strlen(symbolic_name));
  13389. print_data(p, "\"", 1);
  13390. } else {
  13391. putint32_t(closure, NULL, val);
  13392. }
  13393. return true;
  13394. }
  13395. static void print_enum_symbolic_name(upb_json_printer *p,
  13396. const upb_enumdef *def,
  13397. int32_t val) {
  13398. const char *symbolic_name = upb_enumdef_iton(def, val);
  13399. if (symbolic_name) {
  13400. print_data(p, "\"", 1);
  13401. putstring(p, symbolic_name, strlen(symbolic_name));
  13402. print_data(p, "\"", 1);
  13403. } else {
  13404. putint32_t(p, NULL, val);
  13405. }
  13406. }
  13407. static bool repeated_enum(void *closure, const void *handler_data,
  13408. int32_t val) {
  13409. const EnumHandlerData *hd = handler_data;
  13410. upb_json_printer *p = closure;
  13411. print_comma(p);
  13412. print_enum_symbolic_name(p, hd->enumdef, val);
  13413. return true;
  13414. }
  13415. static bool mapvalue_enum(void *closure, const void *handler_data,
  13416. int32_t val) {
  13417. const EnumHandlerData *hd = handler_data;
  13418. upb_json_printer *p = closure;
  13419. print_enum_symbolic_name(p, hd->enumdef, val);
  13420. return true;
  13421. }
  13422. static void *scalar_startsubmsg(void *closure, const void *handler_data) {
  13423. return putkey(closure, handler_data) ? closure : UPB_BREAK;
  13424. }
  13425. static void *repeated_startsubmsg(void *closure, const void *handler_data) {
  13426. upb_json_printer *p = closure;
  13427. UPB_UNUSED(handler_data);
  13428. print_comma(p);
  13429. return closure;
  13430. }
  13431. static void start_frame(upb_json_printer *p) {
  13432. p->depth_++;
  13433. p->first_elem_[p->depth_] = true;
  13434. print_data(p, "{", 1);
  13435. }
  13436. static void end_frame(upb_json_printer *p) {
  13437. print_data(p, "}", 1);
  13438. p->depth_--;
  13439. }
  13440. static bool printer_startmsg(void *closure, const void *handler_data) {
  13441. upb_json_printer *p = closure;
  13442. UPB_UNUSED(handler_data);
  13443. if (p->depth_ == 0) {
  13444. upb_bytessink_start(p->output_, 0, &p->subc_);
  13445. }
  13446. start_frame(p);
  13447. return true;
  13448. }
  13449. static bool printer_endmsg(void *closure, const void *handler_data, upb_status *s) {
  13450. upb_json_printer *p = closure;
  13451. UPB_UNUSED(handler_data);
  13452. UPB_UNUSED(s);
  13453. end_frame(p);
  13454. if (p->depth_ == 0) {
  13455. upb_bytessink_end(p->output_);
  13456. }
  13457. return true;
  13458. }
  13459. static void *startseq(void *closure, const void *handler_data) {
  13460. upb_json_printer *p = closure;
  13461. CHK(putkey(closure, handler_data));
  13462. p->depth_++;
  13463. p->first_elem_[p->depth_] = true;
  13464. print_data(p, "[", 1);
  13465. return closure;
  13466. }
  13467. static bool endseq(void *closure, const void *handler_data) {
  13468. upb_json_printer *p = closure;
  13469. UPB_UNUSED(handler_data);
  13470. print_data(p, "]", 1);
  13471. p->depth_--;
  13472. return true;
  13473. }
  13474. static void *startmap(void *closure, const void *handler_data) {
  13475. upb_json_printer *p = closure;
  13476. CHK(putkey(closure, handler_data));
  13477. p->depth_++;
  13478. p->first_elem_[p->depth_] = true;
  13479. print_data(p, "{", 1);
  13480. return closure;
  13481. }
  13482. static bool endmap(void *closure, const void *handler_data) {
  13483. upb_json_printer *p = closure;
  13484. UPB_UNUSED(handler_data);
  13485. print_data(p, "}", 1);
  13486. p->depth_--;
  13487. return true;
  13488. }
  13489. static size_t putstr(void *closure, const void *handler_data, const char *str,
  13490. size_t len, const upb_bufhandle *handle) {
  13491. upb_json_printer *p = closure;
  13492. UPB_UNUSED(handler_data);
  13493. UPB_UNUSED(handle);
  13494. putstring(p, str, len);
  13495. return len;
  13496. }
  13497. /* This has to Base64 encode the bytes, because JSON has no "bytes" type. */
  13498. static size_t putbytes(void *closure, const void *handler_data, const char *str,
  13499. size_t len, const upb_bufhandle *handle) {
  13500. upb_json_printer *p = closure;
  13501. /* This is the regular base64, not the "web-safe" version. */
  13502. static const char base64[] =
  13503. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  13504. /* Base64-encode. */
  13505. char data[16000];
  13506. const char *limit = data + sizeof(data);
  13507. const unsigned char *from = (const unsigned char*)str;
  13508. char *to = data;
  13509. size_t remaining = len;
  13510. size_t bytes;
  13511. UPB_UNUSED(handler_data);
  13512. UPB_UNUSED(handle);
  13513. while (remaining > 2) {
  13514. /* TODO(haberman): handle encoded lengths > sizeof(data) */
  13515. UPB_ASSERT((limit - to) >= 4);
  13516. to[0] = base64[from[0] >> 2];
  13517. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  13518. to[2] = base64[((from[1] & 0xf) << 2) | (from[2] >> 6)];
  13519. to[3] = base64[from[2] & 0x3f];
  13520. remaining -= 3;
  13521. to += 4;
  13522. from += 3;
  13523. }
  13524. switch (remaining) {
  13525. case 2:
  13526. to[0] = base64[from[0] >> 2];
  13527. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  13528. to[2] = base64[(from[1] & 0xf) << 2];
  13529. to[3] = '=';
  13530. to += 4;
  13531. from += 2;
  13532. break;
  13533. case 1:
  13534. to[0] = base64[from[0] >> 2];
  13535. to[1] = base64[((from[0] & 0x3) << 4)];
  13536. to[2] = '=';
  13537. to[3] = '=';
  13538. to += 4;
  13539. from += 1;
  13540. break;
  13541. }
  13542. bytes = to - data;
  13543. print_data(p, "\"", 1);
  13544. putstring(p, data, bytes);
  13545. print_data(p, "\"", 1);
  13546. return len;
  13547. }
  13548. static void *scalar_startstr(void *closure, const void *handler_data,
  13549. size_t size_hint) {
  13550. upb_json_printer *p = closure;
  13551. UPB_UNUSED(handler_data);
  13552. UPB_UNUSED(size_hint);
  13553. CHK(putkey(closure, handler_data));
  13554. print_data(p, "\"", 1);
  13555. return p;
  13556. }
  13557. static size_t scalar_str(void *closure, const void *handler_data,
  13558. const char *str, size_t len,
  13559. const upb_bufhandle *handle) {
  13560. CHK(putstr(closure, handler_data, str, len, handle));
  13561. return len;
  13562. }
  13563. static bool scalar_endstr(void *closure, const void *handler_data) {
  13564. upb_json_printer *p = closure;
  13565. UPB_UNUSED(handler_data);
  13566. print_data(p, "\"", 1);
  13567. return true;
  13568. }
  13569. static void *repeated_startstr(void *closure, const void *handler_data,
  13570. size_t size_hint) {
  13571. upb_json_printer *p = closure;
  13572. UPB_UNUSED(handler_data);
  13573. UPB_UNUSED(size_hint);
  13574. print_comma(p);
  13575. print_data(p, "\"", 1);
  13576. return p;
  13577. }
  13578. static size_t repeated_str(void *closure, const void *handler_data,
  13579. const char *str, size_t len,
  13580. const upb_bufhandle *handle) {
  13581. CHK(putstr(closure, handler_data, str, len, handle));
  13582. return len;
  13583. }
  13584. static bool repeated_endstr(void *closure, const void *handler_data) {
  13585. upb_json_printer *p = closure;
  13586. UPB_UNUSED(handler_data);
  13587. print_data(p, "\"", 1);
  13588. return true;
  13589. }
  13590. static void *mapkeyval_startstr(void *closure, const void *handler_data,
  13591. size_t size_hint) {
  13592. upb_json_printer *p = closure;
  13593. UPB_UNUSED(handler_data);
  13594. UPB_UNUSED(size_hint);
  13595. print_data(p, "\"", 1);
  13596. return p;
  13597. }
  13598. static size_t mapkey_str(void *closure, const void *handler_data,
  13599. const char *str, size_t len,
  13600. const upb_bufhandle *handle) {
  13601. CHK(putstr(closure, handler_data, str, len, handle));
  13602. return len;
  13603. }
  13604. static bool mapkey_endstr(void *closure, const void *handler_data) {
  13605. upb_json_printer *p = closure;
  13606. UPB_UNUSED(handler_data);
  13607. print_data(p, "\":", 2);
  13608. return true;
  13609. }
  13610. static bool mapvalue_endstr(void *closure, const void *handler_data) {
  13611. upb_json_printer *p = closure;
  13612. UPB_UNUSED(handler_data);
  13613. print_data(p, "\"", 1);
  13614. return true;
  13615. }
  13616. static size_t scalar_bytes(void *closure, const void *handler_data,
  13617. const char *str, size_t len,
  13618. const upb_bufhandle *handle) {
  13619. CHK(putkey(closure, handler_data));
  13620. CHK(putbytes(closure, handler_data, str, len, handle));
  13621. return len;
  13622. }
  13623. static size_t repeated_bytes(void *closure, const void *handler_data,
  13624. const char *str, size_t len,
  13625. const upb_bufhandle *handle) {
  13626. upb_json_printer *p = closure;
  13627. print_comma(p);
  13628. CHK(putbytes(closure, handler_data, str, len, handle));
  13629. return len;
  13630. }
  13631. static size_t mapkey_bytes(void *closure, const void *handler_data,
  13632. const char *str, size_t len,
  13633. const upb_bufhandle *handle) {
  13634. upb_json_printer *p = closure;
  13635. CHK(putbytes(closure, handler_data, str, len, handle));
  13636. print_data(p, ":", 1);
  13637. return len;
  13638. }
  13639. static void set_enum_hd(upb_handlers *h,
  13640. const upb_fielddef *f,
  13641. bool preserve_fieldnames,
  13642. upb_handlerattr *attr) {
  13643. EnumHandlerData *hd = upb_gmalloc(sizeof(EnumHandlerData));
  13644. hd->enumdef = (const upb_enumdef *)upb_fielddef_subdef(f);
  13645. hd->keyname = newstrpc(h, f, preserve_fieldnames);
  13646. upb_handlers_addcleanup(h, hd, upb_gfree);
  13647. upb_handlerattr_sethandlerdata(attr, hd);
  13648. }
  13649. /* Set up handlers for a mapentry submessage (i.e., an individual key/value pair
  13650. * in a map).
  13651. *
  13652. * TODO: Handle missing key, missing value, out-of-order key/value, or repeated
  13653. * key or value cases properly. The right way to do this is to allocate a
  13654. * temporary structure at the start of a mapentry submessage, store key and
  13655. * value data in it as key and value handlers are called, and then print the
  13656. * key/value pair once at the end of the submessage. If we don't do this, we
  13657. * should at least detect the case and throw an error. However, so far all of
  13658. * our sources that emit mapentry messages do so canonically (with one key
  13659. * field, and then one value field), so this is not a pressing concern at the
  13660. * moment. */
  13661. void printer_sethandlers_mapentry(const void *closure, bool preserve_fieldnames,
  13662. upb_handlers *h) {
  13663. const upb_msgdef *md = upb_handlers_msgdef(h);
  13664. /* A mapentry message is printed simply as '"key": value'. Rather than
  13665. * special-case key and value for every type below, we just handle both
  13666. * fields explicitly here. */
  13667. const upb_fielddef* key_field = upb_msgdef_itof(md, UPB_MAPENTRY_KEY);
  13668. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_MAPENTRY_VALUE);
  13669. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  13670. UPB_UNUSED(closure);
  13671. switch (upb_fielddef_type(key_field)) {
  13672. case UPB_TYPE_INT32:
  13673. upb_handlers_setint32(h, key_field, putmapkey_int32_t, &empty_attr);
  13674. break;
  13675. case UPB_TYPE_INT64:
  13676. upb_handlers_setint64(h, key_field, putmapkey_int64_t, &empty_attr);
  13677. break;
  13678. case UPB_TYPE_UINT32:
  13679. upb_handlers_setuint32(h, key_field, putmapkey_uint32_t, &empty_attr);
  13680. break;
  13681. case UPB_TYPE_UINT64:
  13682. upb_handlers_setuint64(h, key_field, putmapkey_uint64_t, &empty_attr);
  13683. break;
  13684. case UPB_TYPE_BOOL:
  13685. upb_handlers_setbool(h, key_field, putmapkey_bool, &empty_attr);
  13686. break;
  13687. case UPB_TYPE_STRING:
  13688. upb_handlers_setstartstr(h, key_field, mapkeyval_startstr, &empty_attr);
  13689. upb_handlers_setstring(h, key_field, mapkey_str, &empty_attr);
  13690. upb_handlers_setendstr(h, key_field, mapkey_endstr, &empty_attr);
  13691. break;
  13692. case UPB_TYPE_BYTES:
  13693. upb_handlers_setstring(h, key_field, mapkey_bytes, &empty_attr);
  13694. break;
  13695. default:
  13696. UPB_ASSERT(false);
  13697. break;
  13698. }
  13699. switch (upb_fielddef_type(value_field)) {
  13700. case UPB_TYPE_INT32:
  13701. upb_handlers_setint32(h, value_field, putint32_t, &empty_attr);
  13702. break;
  13703. case UPB_TYPE_INT64:
  13704. upb_handlers_setint64(h, value_field, putint64_t, &empty_attr);
  13705. break;
  13706. case UPB_TYPE_UINT32:
  13707. upb_handlers_setuint32(h, value_field, putuint32_t, &empty_attr);
  13708. break;
  13709. case UPB_TYPE_UINT64:
  13710. upb_handlers_setuint64(h, value_field, putuint64_t, &empty_attr);
  13711. break;
  13712. case UPB_TYPE_BOOL:
  13713. upb_handlers_setbool(h, value_field, putbool, &empty_attr);
  13714. break;
  13715. case UPB_TYPE_FLOAT:
  13716. upb_handlers_setfloat(h, value_field, putfloat, &empty_attr);
  13717. break;
  13718. case UPB_TYPE_DOUBLE:
  13719. upb_handlers_setdouble(h, value_field, putdouble, &empty_attr);
  13720. break;
  13721. case UPB_TYPE_STRING:
  13722. upb_handlers_setstartstr(h, value_field, mapkeyval_startstr, &empty_attr);
  13723. upb_handlers_setstring(h, value_field, putstr, &empty_attr);
  13724. upb_handlers_setendstr(h, value_field, mapvalue_endstr, &empty_attr);
  13725. break;
  13726. case UPB_TYPE_BYTES:
  13727. upb_handlers_setstring(h, value_field, putbytes, &empty_attr);
  13728. break;
  13729. case UPB_TYPE_ENUM: {
  13730. upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
  13731. set_enum_hd(h, value_field, preserve_fieldnames, &enum_attr);
  13732. upb_handlers_setint32(h, value_field, mapvalue_enum, &enum_attr);
  13733. upb_handlerattr_uninit(&enum_attr);
  13734. break;
  13735. }
  13736. case UPB_TYPE_MESSAGE:
  13737. /* No handler necessary -- the submsg handlers will print the message
  13738. * as appropriate. */
  13739. break;
  13740. }
  13741. upb_handlerattr_uninit(&empty_attr);
  13742. }
  13743. static bool putseconds(void *closure, const void *handler_data,
  13744. int64_t seconds) {
  13745. upb_json_printer *p = closure;
  13746. p->seconds = seconds;
  13747. UPB_UNUSED(handler_data);
  13748. return true;
  13749. }
  13750. static bool putnanos(void *closure, const void *handler_data,
  13751. int32_t nanos) {
  13752. upb_json_printer *p = closure;
  13753. p->nanos = nanos;
  13754. UPB_UNUSED(handler_data);
  13755. return true;
  13756. }
  13757. static void *scalar_startstr_nokey(void *closure, const void *handler_data,
  13758. size_t size_hint) {
  13759. upb_json_printer *p = closure;
  13760. UPB_UNUSED(handler_data);
  13761. UPB_UNUSED(size_hint);
  13762. print_data(p, "\"", 1);
  13763. return p;
  13764. }
  13765. static size_t putstr_nokey(void *closure, const void *handler_data,
  13766. const char *str, size_t len,
  13767. const upb_bufhandle *handle) {
  13768. upb_json_printer *p = closure;
  13769. UPB_UNUSED(handler_data);
  13770. UPB_UNUSED(handle);
  13771. print_data(p, "\"", 1);
  13772. putstring(p, str, len);
  13773. print_data(p, "\"", 1);
  13774. return len + 2;
  13775. }
  13776. static void *startseq_nokey(void *closure, const void *handler_data) {
  13777. upb_json_printer *p = closure;
  13778. UPB_UNUSED(handler_data);
  13779. p->depth_++;
  13780. p->first_elem_[p->depth_] = true;
  13781. print_data(p, "[", 1);
  13782. return closure;
  13783. }
  13784. static void *startmap_nokey(void *closure, const void *handler_data) {
  13785. upb_json_printer *p = closure;
  13786. UPB_UNUSED(handler_data);
  13787. p->depth_++;
  13788. p->first_elem_[p->depth_] = true;
  13789. print_data(p, "{", 1);
  13790. return closure;
  13791. }
  13792. static bool putnull(void *closure, const void *handler_data,
  13793. int32_t null) {
  13794. upb_json_printer *p = closure;
  13795. print_data(p, "null", 4);
  13796. UPB_UNUSED(handler_data);
  13797. UPB_UNUSED(null);
  13798. return true;
  13799. }
  13800. static bool printer_startdurationmsg(void *closure, const void *handler_data) {
  13801. upb_json_printer *p = closure;
  13802. UPB_UNUSED(handler_data);
  13803. if (p->depth_ == 0) {
  13804. upb_bytessink_start(p->output_, 0, &p->subc_);
  13805. }
  13806. return true;
  13807. }
  13808. #define UPB_DURATION_MAX_JSON_LEN 23
  13809. #define UPB_DURATION_MAX_NANO_LEN 9
  13810. static bool printer_enddurationmsg(void *closure, const void *handler_data,
  13811. upb_status *s) {
  13812. upb_json_printer *p = closure;
  13813. char buffer[UPB_DURATION_MAX_JSON_LEN];
  13814. size_t base_len;
  13815. size_t curr;
  13816. size_t i;
  13817. memset(buffer, 0, UPB_DURATION_MAX_JSON_LEN);
  13818. if (p->seconds < -315576000000) {
  13819. upb_status_seterrf(s, "error parsing duration: "
  13820. "minimum acceptable value is "
  13821. "-315576000000");
  13822. return false;
  13823. }
  13824. if (p->seconds > 315576000000) {
  13825. upb_status_seterrf(s, "error serializing duration: "
  13826. "maximum acceptable value is "
  13827. "315576000000");
  13828. return false;
  13829. }
  13830. _upb_snprintf(buffer, sizeof(buffer), "%ld", (long)p->seconds);
  13831. base_len = strlen(buffer);
  13832. if (p->nanos != 0) {
  13833. char nanos_buffer[UPB_DURATION_MAX_NANO_LEN + 3];
  13834. _upb_snprintf(nanos_buffer, sizeof(nanos_buffer), "%.9f",
  13835. p->nanos / 1000000000.0);
  13836. /* Remove trailing 0. */
  13837. for (i = UPB_DURATION_MAX_NANO_LEN + 2;
  13838. nanos_buffer[i] == '0'; i--) {
  13839. nanos_buffer[i] = 0;
  13840. }
  13841. strcpy(buffer + base_len, nanos_buffer + 1);
  13842. }
  13843. curr = strlen(buffer);
  13844. strcpy(buffer + curr, "s");
  13845. p->seconds = 0;
  13846. p->nanos = 0;
  13847. print_data(p, "\"", 1);
  13848. print_data(p, buffer, strlen(buffer));
  13849. print_data(p, "\"", 1);
  13850. if (p->depth_ == 0) {
  13851. upb_bytessink_end(p->output_);
  13852. }
  13853. UPB_UNUSED(handler_data);
  13854. return true;
  13855. }
  13856. static bool printer_starttimestampmsg(void *closure, const void *handler_data) {
  13857. upb_json_printer *p = closure;
  13858. UPB_UNUSED(handler_data);
  13859. if (p->depth_ == 0) {
  13860. upb_bytessink_start(p->output_, 0, &p->subc_);
  13861. }
  13862. return true;
  13863. }
  13864. #define UPB_TIMESTAMP_MAX_JSON_LEN 31
  13865. #define UPB_TIMESTAMP_BEFORE_NANO_LEN 19
  13866. #define UPB_TIMESTAMP_MAX_NANO_LEN 9
  13867. static bool printer_endtimestampmsg(void *closure, const void *handler_data,
  13868. upb_status *s) {
  13869. upb_json_printer *p = closure;
  13870. char buffer[UPB_TIMESTAMP_MAX_JSON_LEN];
  13871. time_t time = p->seconds;
  13872. size_t curr;
  13873. size_t i;
  13874. size_t year_length =
  13875. strftime(buffer, UPB_TIMESTAMP_MAX_JSON_LEN, "%Y", gmtime(&time));
  13876. if (p->seconds < -62135596800) {
  13877. upb_status_seterrf(s, "error parsing timestamp: "
  13878. "minimum acceptable value is "
  13879. "0001-01-01T00:00:00Z");
  13880. return false;
  13881. }
  13882. if (p->seconds > 253402300799) {
  13883. upb_status_seterrf(s, "error parsing timestamp: "
  13884. "maximum acceptable value is "
  13885. "9999-12-31T23:59:59Z");
  13886. return false;
  13887. }
  13888. /* strftime doesn't guarantee 4 digits for year. Prepend 0 by ourselves. */
  13889. for (i = 0; i < 4 - year_length; i++) {
  13890. buffer[i] = '0';
  13891. }
  13892. strftime(buffer + (4 - year_length), UPB_TIMESTAMP_MAX_JSON_LEN,
  13893. "%Y-%m-%dT%H:%M:%S", gmtime(&time));
  13894. if (p->nanos != 0) {
  13895. char nanos_buffer[UPB_TIMESTAMP_MAX_NANO_LEN + 3];
  13896. _upb_snprintf(nanos_buffer, sizeof(nanos_buffer), "%.9f",
  13897. p->nanos / 1000000000.0);
  13898. /* Remove trailing 0. */
  13899. for (i = UPB_TIMESTAMP_MAX_NANO_LEN + 2;
  13900. nanos_buffer[i] == '0'; i--) {
  13901. nanos_buffer[i] = 0;
  13902. }
  13903. strcpy(buffer + UPB_TIMESTAMP_BEFORE_NANO_LEN, nanos_buffer + 1);
  13904. }
  13905. curr = strlen(buffer);
  13906. strcpy(buffer + curr, "Z");
  13907. p->seconds = 0;
  13908. p->nanos = 0;
  13909. print_data(p, "\"", 1);
  13910. print_data(p, buffer, strlen(buffer));
  13911. print_data(p, "\"", 1);
  13912. if (p->depth_ == 0) {
  13913. upb_bytessink_end(p->output_);
  13914. }
  13915. UPB_UNUSED(handler_data);
  13916. UPB_UNUSED(s);
  13917. return true;
  13918. }
  13919. static bool printer_startmsg_noframe(void *closure, const void *handler_data) {
  13920. upb_json_printer *p = closure;
  13921. UPB_UNUSED(handler_data);
  13922. if (p->depth_ == 0) {
  13923. upb_bytessink_start(p->output_, 0, &p->subc_);
  13924. }
  13925. return true;
  13926. }
  13927. static bool printer_endmsg_noframe(
  13928. void *closure, const void *handler_data, upb_status *s) {
  13929. upb_json_printer *p = closure;
  13930. UPB_UNUSED(handler_data);
  13931. UPB_UNUSED(s);
  13932. if (p->depth_ == 0) {
  13933. upb_bytessink_end(p->output_);
  13934. }
  13935. return true;
  13936. }
  13937. /* Set up handlers for a duration submessage. */
  13938. void printer_sethandlers_duration(const void *closure, upb_handlers *h) {
  13939. const upb_msgdef *md = upb_handlers_msgdef(h);
  13940. const upb_fielddef* seconds_field =
  13941. upb_msgdef_itof(md, UPB_DURATION_SECONDS);
  13942. const upb_fielddef* nanos_field =
  13943. upb_msgdef_itof(md, UPB_DURATION_NANOS);
  13944. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  13945. upb_handlers_setstartmsg(h, printer_startdurationmsg, &empty_attr);
  13946. upb_handlers_setint64(h, seconds_field, putseconds, &empty_attr);
  13947. upb_handlers_setint32(h, nanos_field, putnanos, &empty_attr);
  13948. upb_handlers_setendmsg(h, printer_enddurationmsg, &empty_attr);
  13949. UPB_UNUSED(closure);
  13950. }
  13951. /* Set up handlers for a timestamp submessage. Instead of printing fields
  13952. * separately, the json representation of timestamp follows RFC 3339 */
  13953. void printer_sethandlers_timestamp(const void *closure, upb_handlers *h) {
  13954. const upb_msgdef *md = upb_handlers_msgdef(h);
  13955. const upb_fielddef* seconds_field =
  13956. upb_msgdef_itof(md, UPB_TIMESTAMP_SECONDS);
  13957. const upb_fielddef* nanos_field =
  13958. upb_msgdef_itof(md, UPB_TIMESTAMP_NANOS);
  13959. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  13960. upb_handlers_setstartmsg(h, printer_starttimestampmsg, &empty_attr);
  13961. upb_handlers_setint64(h, seconds_field, putseconds, &empty_attr);
  13962. upb_handlers_setint32(h, nanos_field, putnanos, &empty_attr);
  13963. upb_handlers_setendmsg(h, printer_endtimestampmsg, &empty_attr);
  13964. UPB_UNUSED(closure);
  13965. }
  13966. void printer_sethandlers_value(const void *closure, upb_handlers *h) {
  13967. const upb_msgdef *md = upb_handlers_msgdef(h);
  13968. upb_msg_field_iter i;
  13969. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  13970. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  13971. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  13972. upb_msg_field_begin(&i, md);
  13973. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  13974. const upb_fielddef *f = upb_msg_iter_field(&i);
  13975. switch (upb_fielddef_type(f)) {
  13976. case UPB_TYPE_ENUM:
  13977. upb_handlers_setint32(h, f, putnull, &empty_attr);
  13978. break;
  13979. case UPB_TYPE_DOUBLE:
  13980. upb_handlers_setdouble(h, f, putdouble, &empty_attr);
  13981. break;
  13982. case UPB_TYPE_STRING:
  13983. upb_handlers_setstartstr(h, f, scalar_startstr_nokey, &empty_attr);
  13984. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  13985. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  13986. break;
  13987. case UPB_TYPE_BOOL:
  13988. upb_handlers_setbool(h, f, putbool, &empty_attr);
  13989. break;
  13990. case UPB_TYPE_MESSAGE:
  13991. break;
  13992. default:
  13993. UPB_ASSERT(false);
  13994. break;
  13995. }
  13996. }
  13997. UPB_UNUSED(closure);
  13998. }
  13999. #define WRAPPER_SETHANDLERS(wrapper, type, putmethod) \
  14000. void printer_sethandlers_##wrapper(const void *closure, upb_handlers *h) { \
  14001. const upb_msgdef *md = upb_handlers_msgdef(h); \
  14002. const upb_fielddef* f = upb_msgdef_itof(md, 1); \
  14003. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER; \
  14004. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr); \
  14005. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr); \
  14006. upb_handlers_set##type(h, f, putmethod, &empty_attr); \
  14007. UPB_UNUSED(closure); \
  14008. }
  14009. WRAPPER_SETHANDLERS(doublevalue, double, putdouble)
  14010. WRAPPER_SETHANDLERS(floatvalue, float, putfloat)
  14011. WRAPPER_SETHANDLERS(int64value, int64, putint64_t)
  14012. WRAPPER_SETHANDLERS(uint64value, uint64, putuint64_t)
  14013. WRAPPER_SETHANDLERS(int32value, int32, putint32_t)
  14014. WRAPPER_SETHANDLERS(uint32value, uint32, putuint32_t)
  14015. WRAPPER_SETHANDLERS(boolvalue, bool, putbool)
  14016. WRAPPER_SETHANDLERS(stringvalue, string, putstr_nokey)
  14017. WRAPPER_SETHANDLERS(bytesvalue, string, putbytes)
  14018. #undef WRAPPER_SETHANDLERS
  14019. void printer_sethandlers_listvalue(const void *closure, upb_handlers *h) {
  14020. const upb_msgdef *md = upb_handlers_msgdef(h);
  14021. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  14022. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  14023. upb_handlers_setstartseq(h, f, startseq_nokey, &empty_attr);
  14024. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  14025. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  14026. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  14027. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &empty_attr);
  14028. UPB_UNUSED(closure);
  14029. }
  14030. void printer_sethandlers_structvalue(const void *closure, upb_handlers *h) {
  14031. const upb_msgdef *md = upb_handlers_msgdef(h);
  14032. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  14033. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  14034. upb_handlers_setstartseq(h, f, startmap_nokey, &empty_attr);
  14035. upb_handlers_setendseq(h, f, endmap, &empty_attr);
  14036. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  14037. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  14038. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &empty_attr);
  14039. UPB_UNUSED(closure);
  14040. }
  14041. void printer_sethandlers(const void *closure, upb_handlers *h) {
  14042. const upb_msgdef *md = upb_handlers_msgdef(h);
  14043. bool is_mapentry = upb_msgdef_mapentry(md);
  14044. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  14045. upb_msg_field_iter i;
  14046. const bool *preserve_fieldnames_ptr = closure;
  14047. const bool preserve_fieldnames = *preserve_fieldnames_ptr;
  14048. if (is_mapentry) {
  14049. /* mapentry messages are sufficiently different that we handle them
  14050. * separately. */
  14051. printer_sethandlers_mapentry(closure, preserve_fieldnames, h);
  14052. return;
  14053. }
  14054. switch (upb_msgdef_wellknowntype(md)) {
  14055. case UPB_WELLKNOWN_UNSPECIFIED:
  14056. break;
  14057. case UPB_WELLKNOWN_DURATION:
  14058. printer_sethandlers_duration(closure, h);
  14059. return;
  14060. case UPB_WELLKNOWN_TIMESTAMP:
  14061. printer_sethandlers_timestamp(closure, h);
  14062. return;
  14063. case UPB_WELLKNOWN_VALUE:
  14064. printer_sethandlers_value(closure, h);
  14065. return;
  14066. case UPB_WELLKNOWN_LISTVALUE:
  14067. printer_sethandlers_listvalue(closure, h);
  14068. return;
  14069. case UPB_WELLKNOWN_STRUCT:
  14070. printer_sethandlers_structvalue(closure, h);
  14071. return;
  14072. #define WRAPPER(wellknowntype, name) \
  14073. case wellknowntype: \
  14074. printer_sethandlers_##name(closure, h); \
  14075. return; \
  14076. WRAPPER(UPB_WELLKNOWN_DOUBLEVALUE, doublevalue);
  14077. WRAPPER(UPB_WELLKNOWN_FLOATVALUE, floatvalue);
  14078. WRAPPER(UPB_WELLKNOWN_INT64VALUE, int64value);
  14079. WRAPPER(UPB_WELLKNOWN_UINT64VALUE, uint64value);
  14080. WRAPPER(UPB_WELLKNOWN_INT32VALUE, int32value);
  14081. WRAPPER(UPB_WELLKNOWN_UINT32VALUE, uint32value);
  14082. WRAPPER(UPB_WELLKNOWN_BOOLVALUE, boolvalue);
  14083. WRAPPER(UPB_WELLKNOWN_STRINGVALUE, stringvalue);
  14084. WRAPPER(UPB_WELLKNOWN_BYTESVALUE, bytesvalue);
  14085. #undef WRAPPER
  14086. }
  14087. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  14088. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  14089. #define TYPE(type, name, ctype) \
  14090. case type: \
  14091. if (upb_fielddef_isseq(f)) { \
  14092. upb_handlers_set##name(h, f, repeated_##ctype, &empty_attr); \
  14093. } else { \
  14094. upb_handlers_set##name(h, f, scalar_##ctype, &name_attr); \
  14095. } \
  14096. break;
  14097. upb_msg_field_begin(&i, md);
  14098. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  14099. const upb_fielddef *f = upb_msg_iter_field(&i);
  14100. upb_handlerattr name_attr = UPB_HANDLERATTR_INITIALIZER;
  14101. upb_handlerattr_sethandlerdata(&name_attr,
  14102. newstrpc(h, f, preserve_fieldnames));
  14103. if (upb_fielddef_ismap(f)) {
  14104. upb_handlers_setstartseq(h, f, startmap, &name_attr);
  14105. upb_handlers_setendseq(h, f, endmap, &name_attr);
  14106. } else if (upb_fielddef_isseq(f)) {
  14107. upb_handlers_setstartseq(h, f, startseq, &name_attr);
  14108. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  14109. }
  14110. switch (upb_fielddef_type(f)) {
  14111. TYPE(UPB_TYPE_FLOAT, float, float);
  14112. TYPE(UPB_TYPE_DOUBLE, double, double);
  14113. TYPE(UPB_TYPE_BOOL, bool, bool);
  14114. TYPE(UPB_TYPE_INT32, int32, int32_t);
  14115. TYPE(UPB_TYPE_UINT32, uint32, uint32_t);
  14116. TYPE(UPB_TYPE_INT64, int64, int64_t);
  14117. TYPE(UPB_TYPE_UINT64, uint64, uint64_t);
  14118. case UPB_TYPE_ENUM: {
  14119. /* For now, we always emit symbolic names for enums. We may want an
  14120. * option later to control this behavior, but we will wait for a real
  14121. * need first. */
  14122. upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
  14123. set_enum_hd(h, f, preserve_fieldnames, &enum_attr);
  14124. if (upb_fielddef_isseq(f)) {
  14125. upb_handlers_setint32(h, f, repeated_enum, &enum_attr);
  14126. } else {
  14127. upb_handlers_setint32(h, f, scalar_enum, &enum_attr);
  14128. }
  14129. upb_handlerattr_uninit(&enum_attr);
  14130. break;
  14131. }
  14132. case UPB_TYPE_STRING:
  14133. if (upb_fielddef_isseq(f)) {
  14134. upb_handlers_setstartstr(h, f, repeated_startstr, &empty_attr);
  14135. upb_handlers_setstring(h, f, repeated_str, &empty_attr);
  14136. upb_handlers_setendstr(h, f, repeated_endstr, &empty_attr);
  14137. } else {
  14138. upb_handlers_setstartstr(h, f, scalar_startstr, &name_attr);
  14139. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  14140. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  14141. }
  14142. break;
  14143. case UPB_TYPE_BYTES:
  14144. /* XXX: this doesn't support strings that span buffers yet. The base64
  14145. * encoder will need to be made resumable for this to work properly. */
  14146. if (upb_fielddef_isseq(f)) {
  14147. upb_handlers_setstring(h, f, repeated_bytes, &empty_attr);
  14148. } else {
  14149. upb_handlers_setstring(h, f, scalar_bytes, &name_attr);
  14150. }
  14151. break;
  14152. case UPB_TYPE_MESSAGE:
  14153. if (upb_fielddef_isseq(f)) {
  14154. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &name_attr);
  14155. } else {
  14156. upb_handlers_setstartsubmsg(h, f, scalar_startsubmsg, &name_attr);
  14157. }
  14158. break;
  14159. }
  14160. upb_handlerattr_uninit(&name_attr);
  14161. }
  14162. upb_handlerattr_uninit(&empty_attr);
  14163. #undef TYPE
  14164. }
  14165. static void json_printer_reset(upb_json_printer *p) {
  14166. p->depth_ = 0;
  14167. }
  14168. /* Public API *****************************************************************/
  14169. upb_json_printer *upb_json_printer_create(upb_env *e, const upb_handlers *h,
  14170. upb_bytessink *output) {
  14171. #ifndef NDEBUG
  14172. size_t size_before = upb_env_bytesallocated(e);
  14173. #endif
  14174. upb_json_printer *p = upb_env_malloc(e, sizeof(upb_json_printer));
  14175. if (!p) return NULL;
  14176. p->output_ = output;
  14177. json_printer_reset(p);
  14178. upb_sink_reset(&p->input_, h, p);
  14179. p->seconds = 0;
  14180. p->nanos = 0;
  14181. /* If this fails, increase the value in printer.h. */
  14182. UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(e) - size_before <=
  14183. UPB_JSON_PRINTER_SIZE);
  14184. return p;
  14185. }
  14186. upb_sink *upb_json_printer_input(upb_json_printer *p) {
  14187. return &p->input_;
  14188. }
  14189. const upb_handlers *upb_json_printer_newhandlers(const upb_msgdef *md,
  14190. bool preserve_fieldnames,
  14191. const void *owner) {
  14192. return upb_handlers_newfrozen(
  14193. md, owner, printer_sethandlers, &preserve_fieldnames);
  14194. }
  14195. #undef UPB_SIZE
  14196. #undef UPB_FIELD_AT
  14197. #undef UPB_READ_ONEOF
  14198. #undef UPB_WRITE_ONEOF