upb.c 420 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624
  1. // Amalgamated source file
  2. #include "upb.h"
  3. #include <ctype.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. typedef struct {
  7. size_t len;
  8. char str[1]; /* Null-terminated string data follows. */
  9. } str_t;
  10. static str_t *newstr(const char *data, size_t len) {
  11. str_t *ret = malloc(sizeof(*ret) + len);
  12. if (!ret) return NULL;
  13. ret->len = len;
  14. memcpy(ret->str, data, len);
  15. ret->str[len] = '\0';
  16. return ret;
  17. }
  18. static void freestr(str_t *s) { free(s); }
  19. /* isalpha() etc. from <ctype.h> are locale-dependent, which we don't want. */
  20. static bool upb_isbetween(char c, char low, char high) {
  21. return c >= low && c <= high;
  22. }
  23. static bool upb_isletter(char c) {
  24. return upb_isbetween(c, 'A', 'Z') || upb_isbetween(c, 'a', 'z') || c == '_';
  25. }
  26. static bool upb_isalphanum(char c) {
  27. return upb_isletter(c) || upb_isbetween(c, '0', '9');
  28. }
  29. static bool upb_isident(const char *str, size_t len, bool full, upb_status *s) {
  30. bool start = true;
  31. size_t i;
  32. for (i = 0; i < len; i++) {
  33. char c = str[i];
  34. if (c == '.') {
  35. if (start || !full) {
  36. upb_status_seterrf(s, "invalid name: unexpected '.' (%s)", str);
  37. return false;
  38. }
  39. start = true;
  40. } else if (start) {
  41. if (!upb_isletter(c)) {
  42. upb_status_seterrf(
  43. s, "invalid name: path components must start with a letter (%s)",
  44. str);
  45. return false;
  46. }
  47. start = false;
  48. } else {
  49. if (!upb_isalphanum(c)) {
  50. upb_status_seterrf(s, "invalid name: non-alphanumeric character (%s)",
  51. str);
  52. return false;
  53. }
  54. }
  55. }
  56. return !start;
  57. }
  58. /* upb_def ********************************************************************/
  59. upb_deftype_t upb_def_type(const upb_def *d) { return d->type; }
  60. const char *upb_def_fullname(const upb_def *d) { return d->fullname; }
  61. const char *upb_def_name(const upb_def *d) {
  62. const char *p;
  63. if (d->fullname == NULL) {
  64. return NULL;
  65. } else if ((p = strrchr(d->fullname, '.')) == NULL) {
  66. /* No '.' in the name, return the full string. */
  67. return d->fullname;
  68. } else {
  69. /* Return one past the last '.'. */
  70. return p + 1;
  71. }
  72. }
  73. bool upb_def_setfullname(upb_def *def, const char *fullname, upb_status *s) {
  74. assert(!upb_def_isfrozen(def));
  75. if (!upb_isident(fullname, strlen(fullname), true, s)) return false;
  76. free((void*)def->fullname);
  77. def->fullname = upb_strdup(fullname);
  78. return true;
  79. }
  80. const upb_filedef *upb_def_file(const upb_def *d) { return d->file; }
  81. upb_def *upb_def_dup(const upb_def *def, const void *o) {
  82. switch (def->type) {
  83. case UPB_DEF_MSG:
  84. return upb_msgdef_upcast_mutable(
  85. upb_msgdef_dup(upb_downcast_msgdef(def), o));
  86. case UPB_DEF_FIELD:
  87. return upb_fielddef_upcast_mutable(
  88. upb_fielddef_dup(upb_downcast_fielddef(def), o));
  89. case UPB_DEF_ENUM:
  90. return upb_enumdef_upcast_mutable(
  91. upb_enumdef_dup(upb_downcast_enumdef(def), o));
  92. default: assert(false); return NULL;
  93. }
  94. }
  95. static bool upb_def_init(upb_def *def, upb_deftype_t type,
  96. const struct upb_refcounted_vtbl *vtbl,
  97. const void *owner) {
  98. if (!upb_refcounted_init(upb_def_upcast_mutable(def), vtbl, owner)) return false;
  99. def->type = type;
  100. def->fullname = NULL;
  101. def->came_from_user = false;
  102. def->file = NULL;
  103. return true;
  104. }
  105. static void upb_def_uninit(upb_def *def) {
  106. free((void*)def->fullname);
  107. }
  108. static const char *msgdef_name(const upb_msgdef *m) {
  109. const char *name = upb_def_fullname(upb_msgdef_upcast(m));
  110. return name ? name : "(anonymous)";
  111. }
  112. static bool upb_validate_field(upb_fielddef *f, upb_status *s) {
  113. if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  114. upb_status_seterrmsg(s, "fielddef must have name and number set");
  115. return false;
  116. }
  117. if (!f->type_is_set_) {
  118. upb_status_seterrmsg(s, "fielddef type was not initialized");
  119. return false;
  120. }
  121. if (upb_fielddef_lazy(f) &&
  122. upb_fielddef_descriptortype(f) != UPB_DESCRIPTOR_TYPE_MESSAGE) {
  123. upb_status_seterrmsg(s,
  124. "only length-delimited submessage fields may be lazy");
  125. return false;
  126. }
  127. if (upb_fielddef_hassubdef(f)) {
  128. const upb_def *subdef;
  129. if (f->subdef_is_symbolic) {
  130. upb_status_seterrf(s, "field '%s.%s' has not been resolved",
  131. msgdef_name(f->msg.def), upb_fielddef_name(f));
  132. return false;
  133. }
  134. subdef = upb_fielddef_subdef(f);
  135. if (subdef == NULL) {
  136. upb_status_seterrf(s, "field %s.%s is missing required subdef",
  137. msgdef_name(f->msg.def), upb_fielddef_name(f));
  138. return false;
  139. }
  140. if (!upb_def_isfrozen(subdef) && !subdef->came_from_user) {
  141. upb_status_seterrf(s,
  142. "subdef of field %s.%s is not frozen or being frozen",
  143. msgdef_name(f->msg.def), upb_fielddef_name(f));
  144. return false;
  145. }
  146. }
  147. if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  148. bool has_default_name = upb_fielddef_enumhasdefaultstr(f);
  149. bool has_default_number = upb_fielddef_enumhasdefaultint32(f);
  150. /* Previously verified by upb_validate_enumdef(). */
  151. assert(upb_enumdef_numvals(upb_fielddef_enumsubdef(f)) > 0);
  152. /* We've already validated that we have an associated enumdef and that it
  153. * has at least one member, so at least one of these should be true.
  154. * Because if the user didn't set anything, we'll pick up the enum's
  155. * default, but if the user *did* set something we should at least pick up
  156. * the one they set (int32 or string). */
  157. assert(has_default_name || has_default_number);
  158. if (!has_default_name) {
  159. upb_status_seterrf(s,
  160. "enum default for field %s.%s (%d) is not in the enum",
  161. msgdef_name(f->msg.def), upb_fielddef_name(f),
  162. upb_fielddef_defaultint32(f));
  163. return false;
  164. }
  165. if (!has_default_number) {
  166. upb_status_seterrf(s,
  167. "enum default for field %s.%s (%s) is not in the enum",
  168. msgdef_name(f->msg.def), upb_fielddef_name(f),
  169. upb_fielddef_defaultstr(f, NULL));
  170. return false;
  171. }
  172. /* Lift the effective numeric default into the field's default slot, in case
  173. * we were only getting it "by reference" from the enumdef. */
  174. upb_fielddef_setdefaultint32(f, upb_fielddef_defaultint32(f));
  175. }
  176. /* Ensure that MapEntry submessages only appear as repeated fields, not
  177. * optional/required (singular) fields. */
  178. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  179. upb_fielddef_msgsubdef(f) != NULL) {
  180. const upb_msgdef *subdef = upb_fielddef_msgsubdef(f);
  181. if (upb_msgdef_mapentry(subdef) && !upb_fielddef_isseq(f)) {
  182. upb_status_seterrf(s,
  183. "Field %s refers to mapentry message but is not "
  184. "a repeated field",
  185. upb_fielddef_name(f) ? upb_fielddef_name(f) :
  186. "(unnamed)");
  187. return false;
  188. }
  189. }
  190. return true;
  191. }
  192. static bool upb_validate_enumdef(const upb_enumdef *e, upb_status *s) {
  193. if (upb_enumdef_numvals(e) == 0) {
  194. upb_status_seterrf(s, "enum %s has no members (must have at least one)",
  195. upb_enumdef_fullname(e));
  196. return false;
  197. }
  198. return true;
  199. }
  200. /* All submessage fields are lower than all other fields.
  201. * Secondly, fields are increasing in order. */
  202. uint32_t field_rank(const upb_fielddef *f) {
  203. uint32_t ret = upb_fielddef_number(f);
  204. const uint32_t high_bit = 1 << 30;
  205. assert(ret < high_bit);
  206. if (!upb_fielddef_issubmsg(f))
  207. ret |= high_bit;
  208. return ret;
  209. }
  210. int cmp_fields(const void *p1, const void *p2) {
  211. const upb_fielddef *f1 = *(upb_fielddef*const*)p1;
  212. const upb_fielddef *f2 = *(upb_fielddef*const*)p2;
  213. return field_rank(f1) - field_rank(f2);
  214. }
  215. static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
  216. /* Sort fields. upb internally relies on UPB_TYPE_MESSAGE fields having the
  217. * lowest indexes, but we do not publicly guarantee this. */
  218. upb_msg_field_iter j;
  219. int i;
  220. uint32_t selector;
  221. int n = upb_msgdef_numfields(m);
  222. upb_fielddef **fields = malloc(n * sizeof(*fields));
  223. if (!fields) return false;
  224. m->submsg_field_count = 0;
  225. for(i = 0, upb_msg_field_begin(&j, m);
  226. !upb_msg_field_done(&j);
  227. upb_msg_field_next(&j), i++) {
  228. upb_fielddef *f = upb_msg_iter_field(&j);
  229. assert(f->msg.def == m);
  230. if (!upb_validate_field(f, s)) {
  231. free(fields);
  232. return false;
  233. }
  234. if (upb_fielddef_issubmsg(f)) {
  235. m->submsg_field_count++;
  236. }
  237. fields[i] = f;
  238. }
  239. qsort(fields, n, sizeof(*fields), cmp_fields);
  240. selector = UPB_STATIC_SELECTOR_COUNT + m->submsg_field_count;
  241. for (i = 0; i < n; i++) {
  242. upb_fielddef *f = fields[i];
  243. f->index_ = i;
  244. f->selector_base = selector + upb_handlers_selectorbaseoffset(f);
  245. selector += upb_handlers_selectorcount(f);
  246. }
  247. m->selector_count = selector;
  248. #ifndef NDEBUG
  249. {
  250. /* Verify that all selectors for the message are distinct. */
  251. #define TRY(type) \
  252. if (upb_handlers_getselector(f, type, &sel)) upb_inttable_insert(&t, sel, v);
  253. upb_inttable t;
  254. upb_value v;
  255. upb_selector_t sel;
  256. upb_inttable_init(&t, UPB_CTYPE_BOOL);
  257. v = upb_value_bool(true);
  258. upb_inttable_insert(&t, UPB_STARTMSG_SELECTOR, v);
  259. upb_inttable_insert(&t, UPB_ENDMSG_SELECTOR, v);
  260. for(upb_msg_field_begin(&j, m);
  261. !upb_msg_field_done(&j);
  262. upb_msg_field_next(&j)) {
  263. upb_fielddef *f = upb_msg_iter_field(&j);
  264. /* These calls will assert-fail in upb_table if the value already
  265. * exists. */
  266. TRY(UPB_HANDLER_INT32);
  267. TRY(UPB_HANDLER_INT64)
  268. TRY(UPB_HANDLER_UINT32)
  269. TRY(UPB_HANDLER_UINT64)
  270. TRY(UPB_HANDLER_FLOAT)
  271. TRY(UPB_HANDLER_DOUBLE)
  272. TRY(UPB_HANDLER_BOOL)
  273. TRY(UPB_HANDLER_STARTSTR)
  274. TRY(UPB_HANDLER_STRING)
  275. TRY(UPB_HANDLER_ENDSTR)
  276. TRY(UPB_HANDLER_STARTSUBMSG)
  277. TRY(UPB_HANDLER_ENDSUBMSG)
  278. TRY(UPB_HANDLER_STARTSEQ)
  279. TRY(UPB_HANDLER_ENDSEQ)
  280. }
  281. upb_inttable_uninit(&t);
  282. }
  283. #undef TRY
  284. #endif
  285. free(fields);
  286. return true;
  287. }
  288. bool _upb_def_validate(upb_def *const*defs, size_t n, upb_status *s) {
  289. size_t i;
  290. /* First perform validation, in two passes so we can check that we have a
  291. * transitive closure without needing to search. */
  292. for (i = 0; i < n; i++) {
  293. upb_def *def = defs[i];
  294. if (upb_def_isfrozen(def)) {
  295. /* Could relax this requirement if it's annoying. */
  296. upb_status_seterrmsg(s, "def is already frozen");
  297. goto err;
  298. } else if (def->type == UPB_DEF_FIELD) {
  299. upb_status_seterrmsg(s, "standalone fielddefs can not be frozen");
  300. goto err;
  301. } else if (def->type == UPB_DEF_ENUM) {
  302. if (!upb_validate_enumdef(upb_dyncast_enumdef(def), s)) {
  303. goto err;
  304. }
  305. } else {
  306. /* Set now to detect transitive closure in the second pass. */
  307. def->came_from_user = true;
  308. }
  309. }
  310. /* Second pass of validation. Also assign selector bases and indexes, and
  311. * compact tables. */
  312. for (i = 0; i < n; i++) {
  313. upb_def *def = defs[i];
  314. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  315. upb_enumdef *e = upb_dyncast_enumdef_mutable(def);
  316. if (m) {
  317. upb_inttable_compact(&m->itof);
  318. if (!assign_msg_indices(m, s)) {
  319. goto err;
  320. }
  321. } else if (e) {
  322. upb_inttable_compact(&e->iton);
  323. }
  324. }
  325. return true;
  326. err:
  327. for (i = 0; i < n; i++) {
  328. upb_def *def = defs[i];
  329. def->came_from_user = false;
  330. }
  331. assert(!(s && upb_ok(s)));
  332. return false;
  333. }
  334. bool upb_def_freeze(upb_def *const* defs, size_t n, upb_status *s) {
  335. /* Def graph contains FieldDefs between each MessageDef, so double the
  336. * limit. */
  337. const size_t maxdepth = UPB_MAX_MESSAGE_DEPTH * 2;
  338. if (!_upb_def_validate(defs, n, s)) {
  339. return false;
  340. }
  341. /* Validation all passed; freeze the objects. */
  342. return upb_refcounted_freeze((upb_refcounted *const*)defs, n, s, maxdepth);
  343. }
  344. /* upb_enumdef ****************************************************************/
  345. static void upb_enumdef_free(upb_refcounted *r) {
  346. upb_enumdef *e = (upb_enumdef*)r;
  347. upb_inttable_iter i;
  348. upb_inttable_begin(&i, &e->iton);
  349. for( ; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  350. /* To clean up the upb_strdup() from upb_enumdef_addval(). */
  351. free(upb_value_getcstr(upb_inttable_iter_value(&i)));
  352. }
  353. upb_strtable_uninit(&e->ntoi);
  354. upb_inttable_uninit(&e->iton);
  355. upb_def_uninit(upb_enumdef_upcast_mutable(e));
  356. free(e);
  357. }
  358. upb_enumdef *upb_enumdef_new(const void *owner) {
  359. static const struct upb_refcounted_vtbl vtbl = {NULL, &upb_enumdef_free};
  360. upb_enumdef *e = malloc(sizeof(*e));
  361. if (!e) return NULL;
  362. if (!upb_def_init(upb_enumdef_upcast_mutable(e), UPB_DEF_ENUM, &vtbl, owner))
  363. goto err2;
  364. if (!upb_strtable_init(&e->ntoi, UPB_CTYPE_INT32)) goto err2;
  365. if (!upb_inttable_init(&e->iton, UPB_CTYPE_CSTR)) goto err1;
  366. return e;
  367. err1:
  368. upb_strtable_uninit(&e->ntoi);
  369. err2:
  370. free(e);
  371. return NULL;
  372. }
  373. upb_enumdef *upb_enumdef_dup(const upb_enumdef *e, const void *owner) {
  374. upb_enum_iter i;
  375. upb_enumdef *new_e = upb_enumdef_new(owner);
  376. if (!new_e) return NULL;
  377. for(upb_enum_begin(&i, e); !upb_enum_done(&i); upb_enum_next(&i)) {
  378. bool success = upb_enumdef_addval(
  379. new_e, upb_enum_iter_name(&i),upb_enum_iter_number(&i), NULL);
  380. if (!success) {
  381. upb_enumdef_unref(new_e, owner);
  382. return NULL;
  383. }
  384. }
  385. return new_e;
  386. }
  387. bool upb_enumdef_freeze(upb_enumdef *e, upb_status *status) {
  388. upb_def *d = upb_enumdef_upcast_mutable(e);
  389. return upb_def_freeze(&d, 1, status);
  390. }
  391. const char *upb_enumdef_fullname(const upb_enumdef *e) {
  392. return upb_def_fullname(upb_enumdef_upcast(e));
  393. }
  394. const char *upb_enumdef_name(const upb_enumdef *e) {
  395. return upb_def_name(upb_enumdef_upcast(e));
  396. }
  397. bool upb_enumdef_setfullname(upb_enumdef *e, const char *fullname,
  398. upb_status *s) {
  399. return upb_def_setfullname(upb_enumdef_upcast_mutable(e), fullname, s);
  400. }
  401. bool upb_enumdef_addval(upb_enumdef *e, const char *name, int32_t num,
  402. upb_status *status) {
  403. if (!upb_isident(name, strlen(name), false, status)) {
  404. return false;
  405. }
  406. if (upb_enumdef_ntoiz(e, name, NULL)) {
  407. upb_status_seterrf(status, "name '%s' is already defined", name);
  408. return false;
  409. }
  410. if (!upb_strtable_insert(&e->ntoi, name, upb_value_int32(num))) {
  411. upb_status_seterrmsg(status, "out of memory");
  412. return false;
  413. }
  414. if (!upb_inttable_lookup(&e->iton, num, NULL) &&
  415. !upb_inttable_insert(&e->iton, num, upb_value_cstr(upb_strdup(name)))) {
  416. upb_status_seterrmsg(status, "out of memory");
  417. upb_strtable_remove(&e->ntoi, name, NULL);
  418. return false;
  419. }
  420. if (upb_enumdef_numvals(e) == 1) {
  421. bool ok = upb_enumdef_setdefault(e, num, NULL);
  422. UPB_ASSERT_VAR(ok, ok);
  423. }
  424. return true;
  425. }
  426. int32_t upb_enumdef_default(const upb_enumdef *e) {
  427. assert(upb_enumdef_iton(e, e->defaultval));
  428. return e->defaultval;
  429. }
  430. bool upb_enumdef_setdefault(upb_enumdef *e, int32_t val, upb_status *s) {
  431. assert(!upb_enumdef_isfrozen(e));
  432. if (!upb_enumdef_iton(e, val)) {
  433. upb_status_seterrf(s, "number '%d' is not in the enum.", val);
  434. return false;
  435. }
  436. e->defaultval = val;
  437. return true;
  438. }
  439. int upb_enumdef_numvals(const upb_enumdef *e) {
  440. return upb_strtable_count(&e->ntoi);
  441. }
  442. void upb_enum_begin(upb_enum_iter *i, const upb_enumdef *e) {
  443. /* We iterate over the ntoi table, to account for duplicate numbers. */
  444. upb_strtable_begin(i, &e->ntoi);
  445. }
  446. void upb_enum_next(upb_enum_iter *iter) { upb_strtable_next(iter); }
  447. bool upb_enum_done(upb_enum_iter *iter) { return upb_strtable_done(iter); }
  448. bool upb_enumdef_ntoi(const upb_enumdef *def, const char *name,
  449. size_t len, int32_t *num) {
  450. upb_value v;
  451. if (!upb_strtable_lookup2(&def->ntoi, name, len, &v)) {
  452. return false;
  453. }
  454. if (num) *num = upb_value_getint32(v);
  455. return true;
  456. }
  457. const char *upb_enumdef_iton(const upb_enumdef *def, int32_t num) {
  458. upb_value v;
  459. return upb_inttable_lookup32(&def->iton, num, &v) ?
  460. upb_value_getcstr(v) : NULL;
  461. }
  462. const char *upb_enum_iter_name(upb_enum_iter *iter) {
  463. return upb_strtable_iter_key(iter);
  464. }
  465. int32_t upb_enum_iter_number(upb_enum_iter *iter) {
  466. return upb_value_getint32(upb_strtable_iter_value(iter));
  467. }
  468. /* upb_fielddef ***************************************************************/
  469. static void upb_fielddef_init_default(upb_fielddef *f);
  470. static void upb_fielddef_uninit_default(upb_fielddef *f) {
  471. if (f->type_is_set_ && f->default_is_string && f->defaultval.bytes)
  472. freestr(f->defaultval.bytes);
  473. }
  474. const char *upb_fielddef_fullname(const upb_fielddef *e) {
  475. return upb_def_fullname(upb_fielddef_upcast(e));
  476. }
  477. static void visitfield(const upb_refcounted *r, upb_refcounted_visit *visit,
  478. void *closure) {
  479. const upb_fielddef *f = (const upb_fielddef*)r;
  480. if (upb_fielddef_containingtype(f)) {
  481. visit(r, upb_msgdef_upcast2(upb_fielddef_containingtype(f)), closure);
  482. }
  483. if (upb_fielddef_containingoneof(f)) {
  484. visit(r, upb_oneofdef_upcast(upb_fielddef_containingoneof(f)), closure);
  485. }
  486. if (upb_fielddef_subdef(f)) {
  487. visit(r, upb_def_upcast(upb_fielddef_subdef(f)), closure);
  488. }
  489. }
  490. static void freefield(upb_refcounted *r) {
  491. upb_fielddef *f = (upb_fielddef*)r;
  492. upb_fielddef_uninit_default(f);
  493. if (f->subdef_is_symbolic)
  494. free(f->sub.name);
  495. upb_def_uninit(upb_fielddef_upcast_mutable(f));
  496. free(f);
  497. }
  498. static const char *enumdefaultstr(const upb_fielddef *f) {
  499. const upb_enumdef *e;
  500. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  501. e = upb_fielddef_enumsubdef(f);
  502. if (f->default_is_string && f->defaultval.bytes) {
  503. /* Default was explicitly set as a string. */
  504. str_t *s = f->defaultval.bytes;
  505. return s->str;
  506. } else if (e) {
  507. if (!f->default_is_string) {
  508. /* Default was explicitly set as an integer; look it up in enumdef. */
  509. const char *name = upb_enumdef_iton(e, f->defaultval.sint);
  510. if (name) {
  511. return name;
  512. }
  513. } else {
  514. /* Default is completely unset; pull enumdef default. */
  515. if (upb_enumdef_numvals(e) > 0) {
  516. const char *name = upb_enumdef_iton(e, upb_enumdef_default(e));
  517. assert(name);
  518. return name;
  519. }
  520. }
  521. }
  522. return NULL;
  523. }
  524. static bool enumdefaultint32(const upb_fielddef *f, int32_t *val) {
  525. const upb_enumdef *e;
  526. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  527. e = upb_fielddef_enumsubdef(f);
  528. if (!f->default_is_string) {
  529. /* Default was explicitly set as an integer. */
  530. *val = f->defaultval.sint;
  531. return true;
  532. } else if (e) {
  533. if (f->defaultval.bytes) {
  534. /* Default was explicitly set as a str; try to lookup corresponding int. */
  535. str_t *s = f->defaultval.bytes;
  536. if (upb_enumdef_ntoiz(e, s->str, val)) {
  537. return true;
  538. }
  539. } else {
  540. /* Default is unset; try to pull in enumdef default. */
  541. if (upb_enumdef_numvals(e) > 0) {
  542. *val = upb_enumdef_default(e);
  543. return true;
  544. }
  545. }
  546. }
  547. return false;
  548. }
  549. upb_fielddef *upb_fielddef_new(const void *o) {
  550. static const struct upb_refcounted_vtbl vtbl = {visitfield, freefield};
  551. upb_fielddef *f = malloc(sizeof(*f));
  552. if (!f) return NULL;
  553. if (!upb_def_init(upb_fielddef_upcast_mutable(f), UPB_DEF_FIELD, &vtbl, o)) {
  554. free(f);
  555. return NULL;
  556. }
  557. f->msg.def = NULL;
  558. f->sub.def = NULL;
  559. f->oneof = NULL;
  560. f->subdef_is_symbolic = false;
  561. f->msg_is_symbolic = false;
  562. f->label_ = UPB_LABEL_OPTIONAL;
  563. f->type_ = UPB_TYPE_INT32;
  564. f->number_ = 0;
  565. f->type_is_set_ = false;
  566. f->tagdelim = false;
  567. f->is_extension_ = false;
  568. f->lazy_ = false;
  569. f->packed_ = true;
  570. /* For the moment we default this to UPB_INTFMT_VARIABLE, since it will work
  571. * with all integer types and is in some since more "default" since the most
  572. * normal-looking proto2 types int32/int64/uint32/uint64 use variable.
  573. *
  574. * Other options to consider:
  575. * - there is no default; users must set this manually (like type).
  576. * - default signed integers to UPB_INTFMT_ZIGZAG, since it's more likely to
  577. * be an optimal default for signed integers. */
  578. f->intfmt = UPB_INTFMT_VARIABLE;
  579. return f;
  580. }
  581. upb_fielddef *upb_fielddef_dup(const upb_fielddef *f, const void *owner) {
  582. const char *srcname;
  583. upb_fielddef *newf = upb_fielddef_new(owner);
  584. if (!newf) return NULL;
  585. upb_fielddef_settype(newf, upb_fielddef_type(f));
  586. upb_fielddef_setlabel(newf, upb_fielddef_label(f));
  587. upb_fielddef_setnumber(newf, upb_fielddef_number(f), NULL);
  588. upb_fielddef_setname(newf, upb_fielddef_name(f), NULL);
  589. if (f->default_is_string && f->defaultval.bytes) {
  590. str_t *s = f->defaultval.bytes;
  591. upb_fielddef_setdefaultstr(newf, s->str, s->len, NULL);
  592. } else {
  593. newf->default_is_string = f->default_is_string;
  594. newf->defaultval = f->defaultval;
  595. }
  596. if (f->subdef_is_symbolic) {
  597. srcname = f->sub.name; /* Might be NULL. */
  598. } else {
  599. srcname = f->sub.def ? upb_def_fullname(f->sub.def) : NULL;
  600. }
  601. if (srcname) {
  602. char *newname = malloc(strlen(f->sub.def->fullname) + 2);
  603. if (!newname) {
  604. upb_fielddef_unref(newf, owner);
  605. return NULL;
  606. }
  607. strcpy(newname, ".");
  608. strcat(newname, f->sub.def->fullname);
  609. upb_fielddef_setsubdefname(newf, newname, NULL);
  610. free(newname);
  611. }
  612. return newf;
  613. }
  614. bool upb_fielddef_typeisset(const upb_fielddef *f) {
  615. return f->type_is_set_;
  616. }
  617. upb_fieldtype_t upb_fielddef_type(const upb_fielddef *f) {
  618. assert(f->type_is_set_);
  619. return f->type_;
  620. }
  621. uint32_t upb_fielddef_index(const upb_fielddef *f) {
  622. return f->index_;
  623. }
  624. upb_label_t upb_fielddef_label(const upb_fielddef *f) {
  625. return f->label_;
  626. }
  627. upb_intfmt_t upb_fielddef_intfmt(const upb_fielddef *f) {
  628. return f->intfmt;
  629. }
  630. bool upb_fielddef_istagdelim(const upb_fielddef *f) {
  631. return f->tagdelim;
  632. }
  633. uint32_t upb_fielddef_number(const upb_fielddef *f) {
  634. return f->number_;
  635. }
  636. bool upb_fielddef_isextension(const upb_fielddef *f) {
  637. return f->is_extension_;
  638. }
  639. bool upb_fielddef_lazy(const upb_fielddef *f) {
  640. return f->lazy_;
  641. }
  642. bool upb_fielddef_packed(const upb_fielddef *f) {
  643. return f->packed_;
  644. }
  645. const char *upb_fielddef_name(const upb_fielddef *f) {
  646. return upb_def_fullname(upb_fielddef_upcast(f));
  647. }
  648. size_t upb_fielddef_getjsonname(const upb_fielddef *f, char *buf, size_t len) {
  649. const char *name = upb_fielddef_name(f);
  650. size_t src, dst = 0;
  651. bool ucase_next = false;
  652. #define WRITE(byte) \
  653. ++dst; \
  654. if (dst < len) buf[dst - 1] = byte; \
  655. else if (dst == len) buf[dst - 1] = '\0'
  656. if (!name) {
  657. WRITE('\0');
  658. return 0;
  659. }
  660. /* Implement the transformation as described in the spec:
  661. * 1. upper case all letters after an underscore.
  662. * 2. remove all underscores.
  663. */
  664. for (src = 0; name[src]; src++) {
  665. if (name[src] == '_') {
  666. ucase_next = true;
  667. continue;
  668. }
  669. if (ucase_next) {
  670. WRITE(toupper(name[src]));
  671. ucase_next = false;
  672. } else {
  673. WRITE(name[src]);
  674. }
  675. }
  676. WRITE('\0');
  677. return dst;
  678. #undef WRITE
  679. }
  680. const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f) {
  681. return f->msg_is_symbolic ? NULL : f->msg.def;
  682. }
  683. const upb_oneofdef *upb_fielddef_containingoneof(const upb_fielddef *f) {
  684. return f->oneof;
  685. }
  686. upb_msgdef *upb_fielddef_containingtype_mutable(upb_fielddef *f) {
  687. return (upb_msgdef*)upb_fielddef_containingtype(f);
  688. }
  689. const char *upb_fielddef_containingtypename(upb_fielddef *f) {
  690. return f->msg_is_symbolic ? f->msg.name : NULL;
  691. }
  692. static void release_containingtype(upb_fielddef *f) {
  693. if (f->msg_is_symbolic) free(f->msg.name);
  694. }
  695. bool upb_fielddef_setcontainingtypename(upb_fielddef *f, const char *name,
  696. upb_status *s) {
  697. assert(!upb_fielddef_isfrozen(f));
  698. if (upb_fielddef_containingtype(f)) {
  699. upb_status_seterrmsg(s, "field has already been added to a message.");
  700. return false;
  701. }
  702. /* TODO: validate name (upb_isident() doesn't quite work atm because this name
  703. * may have a leading "."). */
  704. release_containingtype(f);
  705. f->msg.name = upb_strdup(name);
  706. f->msg_is_symbolic = true;
  707. return true;
  708. }
  709. bool upb_fielddef_setname(upb_fielddef *f, const char *name, upb_status *s) {
  710. if (upb_fielddef_containingtype(f) || upb_fielddef_containingoneof(f)) {
  711. upb_status_seterrmsg(s, "Already added to message or oneof");
  712. return false;
  713. }
  714. return upb_def_setfullname(upb_fielddef_upcast_mutable(f), name, s);
  715. }
  716. static void chkdefaulttype(const upb_fielddef *f, upb_fieldtype_t type) {
  717. UPB_UNUSED(f);
  718. UPB_UNUSED(type);
  719. assert(f->type_is_set_ && upb_fielddef_type(f) == type);
  720. }
  721. int64_t upb_fielddef_defaultint64(const upb_fielddef *f) {
  722. chkdefaulttype(f, UPB_TYPE_INT64);
  723. return f->defaultval.sint;
  724. }
  725. int32_t upb_fielddef_defaultint32(const upb_fielddef *f) {
  726. if (f->type_is_set_ && upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  727. int32_t val;
  728. bool ok = enumdefaultint32(f, &val);
  729. UPB_ASSERT_VAR(ok, ok);
  730. return val;
  731. } else {
  732. chkdefaulttype(f, UPB_TYPE_INT32);
  733. return f->defaultval.sint;
  734. }
  735. }
  736. uint64_t upb_fielddef_defaultuint64(const upb_fielddef *f) {
  737. chkdefaulttype(f, UPB_TYPE_UINT64);
  738. return f->defaultval.uint;
  739. }
  740. uint32_t upb_fielddef_defaultuint32(const upb_fielddef *f) {
  741. chkdefaulttype(f, UPB_TYPE_UINT32);
  742. return f->defaultval.uint;
  743. }
  744. bool upb_fielddef_defaultbool(const upb_fielddef *f) {
  745. chkdefaulttype(f, UPB_TYPE_BOOL);
  746. return f->defaultval.uint;
  747. }
  748. float upb_fielddef_defaultfloat(const upb_fielddef *f) {
  749. chkdefaulttype(f, UPB_TYPE_FLOAT);
  750. return f->defaultval.flt;
  751. }
  752. double upb_fielddef_defaultdouble(const upb_fielddef *f) {
  753. chkdefaulttype(f, UPB_TYPE_DOUBLE);
  754. return f->defaultval.dbl;
  755. }
  756. const char *upb_fielddef_defaultstr(const upb_fielddef *f, size_t *len) {
  757. assert(f->type_is_set_);
  758. assert(upb_fielddef_type(f) == UPB_TYPE_STRING ||
  759. upb_fielddef_type(f) == UPB_TYPE_BYTES ||
  760. upb_fielddef_type(f) == UPB_TYPE_ENUM);
  761. if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  762. const char *ret = enumdefaultstr(f);
  763. assert(ret);
  764. /* Enum defaults can't have embedded NULLs. */
  765. if (len) *len = strlen(ret);
  766. return ret;
  767. }
  768. if (f->default_is_string) {
  769. str_t *str = f->defaultval.bytes;
  770. if (len) *len = str->len;
  771. return str->str;
  772. }
  773. return NULL;
  774. }
  775. static void upb_fielddef_init_default(upb_fielddef *f) {
  776. f->default_is_string = false;
  777. switch (upb_fielddef_type(f)) {
  778. case UPB_TYPE_DOUBLE: f->defaultval.dbl = 0; break;
  779. case UPB_TYPE_FLOAT: f->defaultval.flt = 0; break;
  780. case UPB_TYPE_INT32:
  781. case UPB_TYPE_INT64: f->defaultval.sint = 0; break;
  782. case UPB_TYPE_UINT64:
  783. case UPB_TYPE_UINT32:
  784. case UPB_TYPE_BOOL: f->defaultval.uint = 0; break;
  785. case UPB_TYPE_STRING:
  786. case UPB_TYPE_BYTES:
  787. f->defaultval.bytes = newstr("", 0);
  788. f->default_is_string = true;
  789. break;
  790. case UPB_TYPE_MESSAGE: break;
  791. case UPB_TYPE_ENUM:
  792. /* This is our special sentinel that indicates "not set" for an enum. */
  793. f->default_is_string = true;
  794. f->defaultval.bytes = NULL;
  795. break;
  796. }
  797. }
  798. const upb_def *upb_fielddef_subdef(const upb_fielddef *f) {
  799. return f->subdef_is_symbolic ? NULL : f->sub.def;
  800. }
  801. const upb_msgdef *upb_fielddef_msgsubdef(const upb_fielddef *f) {
  802. const upb_def *def = upb_fielddef_subdef(f);
  803. return def ? upb_dyncast_msgdef(def) : NULL;
  804. }
  805. const upb_enumdef *upb_fielddef_enumsubdef(const upb_fielddef *f) {
  806. const upb_def *def = upb_fielddef_subdef(f);
  807. return def ? upb_dyncast_enumdef(def) : NULL;
  808. }
  809. upb_def *upb_fielddef_subdef_mutable(upb_fielddef *f) {
  810. return (upb_def*)upb_fielddef_subdef(f);
  811. }
  812. const char *upb_fielddef_subdefname(const upb_fielddef *f) {
  813. if (f->subdef_is_symbolic) {
  814. return f->sub.name;
  815. } else if (f->sub.def) {
  816. return upb_def_fullname(f->sub.def);
  817. } else {
  818. return NULL;
  819. }
  820. }
  821. bool upb_fielddef_setnumber(upb_fielddef *f, uint32_t number, upb_status *s) {
  822. if (upb_fielddef_containingtype(f)) {
  823. upb_status_seterrmsg(
  824. s, "cannot change field number after adding to a message");
  825. return false;
  826. }
  827. if (number == 0 || number > UPB_MAX_FIELDNUMBER) {
  828. upb_status_seterrf(s, "invalid field number (%u)", number);
  829. return false;
  830. }
  831. f->number_ = number;
  832. return true;
  833. }
  834. void upb_fielddef_settype(upb_fielddef *f, upb_fieldtype_t type) {
  835. assert(!upb_fielddef_isfrozen(f));
  836. assert(upb_fielddef_checktype(type));
  837. upb_fielddef_uninit_default(f);
  838. f->type_ = type;
  839. f->type_is_set_ = true;
  840. upb_fielddef_init_default(f);
  841. }
  842. void upb_fielddef_setdescriptortype(upb_fielddef *f, int type) {
  843. assert(!upb_fielddef_isfrozen(f));
  844. switch (type) {
  845. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  846. upb_fielddef_settype(f, UPB_TYPE_DOUBLE);
  847. break;
  848. case UPB_DESCRIPTOR_TYPE_FLOAT:
  849. upb_fielddef_settype(f, UPB_TYPE_FLOAT);
  850. break;
  851. case UPB_DESCRIPTOR_TYPE_INT64:
  852. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  853. case UPB_DESCRIPTOR_TYPE_SINT64:
  854. upb_fielddef_settype(f, UPB_TYPE_INT64);
  855. break;
  856. case UPB_DESCRIPTOR_TYPE_UINT64:
  857. case UPB_DESCRIPTOR_TYPE_FIXED64:
  858. upb_fielddef_settype(f, UPB_TYPE_UINT64);
  859. break;
  860. case UPB_DESCRIPTOR_TYPE_INT32:
  861. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  862. case UPB_DESCRIPTOR_TYPE_SINT32:
  863. upb_fielddef_settype(f, UPB_TYPE_INT32);
  864. break;
  865. case UPB_DESCRIPTOR_TYPE_UINT32:
  866. case UPB_DESCRIPTOR_TYPE_FIXED32:
  867. upb_fielddef_settype(f, UPB_TYPE_UINT32);
  868. break;
  869. case UPB_DESCRIPTOR_TYPE_BOOL:
  870. upb_fielddef_settype(f, UPB_TYPE_BOOL);
  871. break;
  872. case UPB_DESCRIPTOR_TYPE_STRING:
  873. upb_fielddef_settype(f, UPB_TYPE_STRING);
  874. break;
  875. case UPB_DESCRIPTOR_TYPE_BYTES:
  876. upb_fielddef_settype(f, UPB_TYPE_BYTES);
  877. break;
  878. case UPB_DESCRIPTOR_TYPE_GROUP:
  879. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  880. upb_fielddef_settype(f, UPB_TYPE_MESSAGE);
  881. break;
  882. case UPB_DESCRIPTOR_TYPE_ENUM:
  883. upb_fielddef_settype(f, UPB_TYPE_ENUM);
  884. break;
  885. default: assert(false);
  886. }
  887. if (type == UPB_DESCRIPTOR_TYPE_FIXED64 ||
  888. type == UPB_DESCRIPTOR_TYPE_FIXED32 ||
  889. type == UPB_DESCRIPTOR_TYPE_SFIXED64 ||
  890. type == UPB_DESCRIPTOR_TYPE_SFIXED32) {
  891. upb_fielddef_setintfmt(f, UPB_INTFMT_FIXED);
  892. } else if (type == UPB_DESCRIPTOR_TYPE_SINT64 ||
  893. type == UPB_DESCRIPTOR_TYPE_SINT32) {
  894. upb_fielddef_setintfmt(f, UPB_INTFMT_ZIGZAG);
  895. } else {
  896. upb_fielddef_setintfmt(f, UPB_INTFMT_VARIABLE);
  897. }
  898. upb_fielddef_settagdelim(f, type == UPB_DESCRIPTOR_TYPE_GROUP);
  899. }
  900. upb_descriptortype_t upb_fielddef_descriptortype(const upb_fielddef *f) {
  901. switch (upb_fielddef_type(f)) {
  902. case UPB_TYPE_FLOAT: return UPB_DESCRIPTOR_TYPE_FLOAT;
  903. case UPB_TYPE_DOUBLE: return UPB_DESCRIPTOR_TYPE_DOUBLE;
  904. case UPB_TYPE_BOOL: return UPB_DESCRIPTOR_TYPE_BOOL;
  905. case UPB_TYPE_STRING: return UPB_DESCRIPTOR_TYPE_STRING;
  906. case UPB_TYPE_BYTES: return UPB_DESCRIPTOR_TYPE_BYTES;
  907. case UPB_TYPE_ENUM: return UPB_DESCRIPTOR_TYPE_ENUM;
  908. case UPB_TYPE_INT32:
  909. switch (upb_fielddef_intfmt(f)) {
  910. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT32;
  911. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED32;
  912. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT32;
  913. }
  914. case UPB_TYPE_INT64:
  915. switch (upb_fielddef_intfmt(f)) {
  916. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT64;
  917. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED64;
  918. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT64;
  919. }
  920. case UPB_TYPE_UINT32:
  921. switch (upb_fielddef_intfmt(f)) {
  922. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT32;
  923. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED32;
  924. case UPB_INTFMT_ZIGZAG: return -1;
  925. }
  926. case UPB_TYPE_UINT64:
  927. switch (upb_fielddef_intfmt(f)) {
  928. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT64;
  929. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED64;
  930. case UPB_INTFMT_ZIGZAG: return -1;
  931. }
  932. case UPB_TYPE_MESSAGE:
  933. return upb_fielddef_istagdelim(f) ?
  934. UPB_DESCRIPTOR_TYPE_GROUP : UPB_DESCRIPTOR_TYPE_MESSAGE;
  935. }
  936. return 0;
  937. }
  938. void upb_fielddef_setisextension(upb_fielddef *f, bool is_extension) {
  939. assert(!upb_fielddef_isfrozen(f));
  940. f->is_extension_ = is_extension;
  941. }
  942. void upb_fielddef_setlazy(upb_fielddef *f, bool lazy) {
  943. assert(!upb_fielddef_isfrozen(f));
  944. f->lazy_ = lazy;
  945. }
  946. void upb_fielddef_setpacked(upb_fielddef *f, bool packed) {
  947. assert(!upb_fielddef_isfrozen(f));
  948. f->packed_ = packed;
  949. }
  950. void upb_fielddef_setlabel(upb_fielddef *f, upb_label_t label) {
  951. assert(!upb_fielddef_isfrozen(f));
  952. assert(upb_fielddef_checklabel(label));
  953. f->label_ = label;
  954. }
  955. void upb_fielddef_setintfmt(upb_fielddef *f, upb_intfmt_t fmt) {
  956. assert(!upb_fielddef_isfrozen(f));
  957. assert(upb_fielddef_checkintfmt(fmt));
  958. f->intfmt = fmt;
  959. }
  960. void upb_fielddef_settagdelim(upb_fielddef *f, bool tag_delim) {
  961. assert(!upb_fielddef_isfrozen(f));
  962. f->tagdelim = tag_delim;
  963. f->tagdelim = tag_delim;
  964. }
  965. static bool checksetdefault(upb_fielddef *f, upb_fieldtype_t type) {
  966. if (!f->type_is_set_ || upb_fielddef_isfrozen(f) ||
  967. upb_fielddef_type(f) != type) {
  968. assert(false);
  969. return false;
  970. }
  971. if (f->default_is_string) {
  972. str_t *s = f->defaultval.bytes;
  973. assert(s || type == UPB_TYPE_ENUM);
  974. if (s) freestr(s);
  975. }
  976. f->default_is_string = false;
  977. return true;
  978. }
  979. void upb_fielddef_setdefaultint64(upb_fielddef *f, int64_t value) {
  980. if (checksetdefault(f, UPB_TYPE_INT64))
  981. f->defaultval.sint = value;
  982. }
  983. void upb_fielddef_setdefaultint32(upb_fielddef *f, int32_t value) {
  984. if ((upb_fielddef_type(f) == UPB_TYPE_ENUM &&
  985. checksetdefault(f, UPB_TYPE_ENUM)) ||
  986. checksetdefault(f, UPB_TYPE_INT32)) {
  987. f->defaultval.sint = value;
  988. }
  989. }
  990. void upb_fielddef_setdefaultuint64(upb_fielddef *f, uint64_t value) {
  991. if (checksetdefault(f, UPB_TYPE_UINT64))
  992. f->defaultval.uint = value;
  993. }
  994. void upb_fielddef_setdefaultuint32(upb_fielddef *f, uint32_t value) {
  995. if (checksetdefault(f, UPB_TYPE_UINT32))
  996. f->defaultval.uint = value;
  997. }
  998. void upb_fielddef_setdefaultbool(upb_fielddef *f, bool value) {
  999. if (checksetdefault(f, UPB_TYPE_BOOL))
  1000. f->defaultval.uint = value;
  1001. }
  1002. void upb_fielddef_setdefaultfloat(upb_fielddef *f, float value) {
  1003. if (checksetdefault(f, UPB_TYPE_FLOAT))
  1004. f->defaultval.flt = value;
  1005. }
  1006. void upb_fielddef_setdefaultdouble(upb_fielddef *f, double value) {
  1007. if (checksetdefault(f, UPB_TYPE_DOUBLE))
  1008. f->defaultval.dbl = value;
  1009. }
  1010. bool upb_fielddef_setdefaultstr(upb_fielddef *f, const void *str, size_t len,
  1011. upb_status *s) {
  1012. str_t *str2;
  1013. assert(upb_fielddef_isstring(f) || f->type_ == UPB_TYPE_ENUM);
  1014. if (f->type_ == UPB_TYPE_ENUM && !upb_isident(str, len, false, s))
  1015. return false;
  1016. if (f->default_is_string) {
  1017. str_t *s = f->defaultval.bytes;
  1018. assert(s || f->type_ == UPB_TYPE_ENUM);
  1019. if (s) freestr(s);
  1020. } else {
  1021. assert(f->type_ == UPB_TYPE_ENUM);
  1022. }
  1023. str2 = newstr(str, len);
  1024. f->defaultval.bytes = str2;
  1025. f->default_is_string = true;
  1026. return true;
  1027. }
  1028. void upb_fielddef_setdefaultcstr(upb_fielddef *f, const char *str,
  1029. upb_status *s) {
  1030. assert(f->type_is_set_);
  1031. upb_fielddef_setdefaultstr(f, str, str ? strlen(str) : 0, s);
  1032. }
  1033. bool upb_fielddef_enumhasdefaultint32(const upb_fielddef *f) {
  1034. int32_t val;
  1035. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  1036. return enumdefaultint32(f, &val);
  1037. }
  1038. bool upb_fielddef_enumhasdefaultstr(const upb_fielddef *f) {
  1039. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  1040. return enumdefaultstr(f) != NULL;
  1041. }
  1042. static bool upb_subdef_typecheck(upb_fielddef *f, const upb_def *subdef,
  1043. upb_status *s) {
  1044. if (f->type_ == UPB_TYPE_MESSAGE) {
  1045. if (upb_dyncast_msgdef(subdef)) return true;
  1046. upb_status_seterrmsg(s, "invalid subdef type for this submessage field");
  1047. return false;
  1048. } else if (f->type_ == UPB_TYPE_ENUM) {
  1049. if (upb_dyncast_enumdef(subdef)) return true;
  1050. upb_status_seterrmsg(s, "invalid subdef type for this enum field");
  1051. return false;
  1052. } else {
  1053. upb_status_seterrmsg(s, "only message and enum fields can have a subdef");
  1054. return false;
  1055. }
  1056. }
  1057. static void release_subdef(upb_fielddef *f) {
  1058. if (f->subdef_is_symbolic) {
  1059. free(f->sub.name);
  1060. } else if (f->sub.def) {
  1061. upb_unref2(f->sub.def, f);
  1062. }
  1063. }
  1064. bool upb_fielddef_setsubdef(upb_fielddef *f, const upb_def *subdef,
  1065. upb_status *s) {
  1066. assert(!upb_fielddef_isfrozen(f));
  1067. assert(upb_fielddef_hassubdef(f));
  1068. if (subdef && !upb_subdef_typecheck(f, subdef, s)) return false;
  1069. release_subdef(f);
  1070. f->sub.def = subdef;
  1071. f->subdef_is_symbolic = false;
  1072. if (f->sub.def) upb_ref2(f->sub.def, f);
  1073. return true;
  1074. }
  1075. bool upb_fielddef_setmsgsubdef(upb_fielddef *f, const upb_msgdef *subdef,
  1076. upb_status *s) {
  1077. return upb_fielddef_setsubdef(f, upb_msgdef_upcast(subdef), s);
  1078. }
  1079. bool upb_fielddef_setenumsubdef(upb_fielddef *f, const upb_enumdef *subdef,
  1080. upb_status *s) {
  1081. return upb_fielddef_setsubdef(f, upb_enumdef_upcast(subdef), s);
  1082. }
  1083. bool upb_fielddef_setsubdefname(upb_fielddef *f, const char *name,
  1084. upb_status *s) {
  1085. assert(!upb_fielddef_isfrozen(f));
  1086. if (!upb_fielddef_hassubdef(f)) {
  1087. upb_status_seterrmsg(s, "field type does not accept a subdef");
  1088. return false;
  1089. }
  1090. /* TODO: validate name (upb_isident() doesn't quite work atm because this name
  1091. * may have a leading "."). */
  1092. release_subdef(f);
  1093. f->sub.name = upb_strdup(name);
  1094. f->subdef_is_symbolic = true;
  1095. return true;
  1096. }
  1097. bool upb_fielddef_issubmsg(const upb_fielddef *f) {
  1098. return upb_fielddef_type(f) == UPB_TYPE_MESSAGE;
  1099. }
  1100. bool upb_fielddef_isstring(const upb_fielddef *f) {
  1101. return upb_fielddef_type(f) == UPB_TYPE_STRING ||
  1102. upb_fielddef_type(f) == UPB_TYPE_BYTES;
  1103. }
  1104. bool upb_fielddef_isseq(const upb_fielddef *f) {
  1105. return upb_fielddef_label(f) == UPB_LABEL_REPEATED;
  1106. }
  1107. bool upb_fielddef_isprimitive(const upb_fielddef *f) {
  1108. return !upb_fielddef_isstring(f) && !upb_fielddef_issubmsg(f);
  1109. }
  1110. bool upb_fielddef_ismap(const upb_fielddef *f) {
  1111. return upb_fielddef_isseq(f) && upb_fielddef_issubmsg(f) &&
  1112. upb_msgdef_mapentry(upb_fielddef_msgsubdef(f));
  1113. }
  1114. bool upb_fielddef_haspresence(const upb_fielddef *f) {
  1115. if (upb_fielddef_isseq(f)) return false;
  1116. if (upb_fielddef_issubmsg(f)) return true;
  1117. /* Primitive field: return true unless there is a message that specifies
  1118. * presence should not exist. */
  1119. if (f->msg_is_symbolic || !f->msg.def) return true;
  1120. return f->msg.def->syntax == UPB_SYNTAX_PROTO2;
  1121. }
  1122. bool upb_fielddef_hassubdef(const upb_fielddef *f) {
  1123. return upb_fielddef_issubmsg(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM;
  1124. }
  1125. static bool between(int32_t x, int32_t low, int32_t high) {
  1126. return x >= low && x <= high;
  1127. }
  1128. bool upb_fielddef_checklabel(int32_t label) { return between(label, 1, 3); }
  1129. bool upb_fielddef_checktype(int32_t type) { return between(type, 1, 11); }
  1130. bool upb_fielddef_checkintfmt(int32_t fmt) { return between(fmt, 1, 3); }
  1131. bool upb_fielddef_checkdescriptortype(int32_t type) {
  1132. return between(type, 1, 18);
  1133. }
  1134. /* upb_msgdef *****************************************************************/
  1135. static void visitmsg(const upb_refcounted *r, upb_refcounted_visit *visit,
  1136. void *closure) {
  1137. upb_msg_oneof_iter o;
  1138. const upb_msgdef *m = (const upb_msgdef*)r;
  1139. upb_msg_field_iter i;
  1140. for(upb_msg_field_begin(&i, m);
  1141. !upb_msg_field_done(&i);
  1142. upb_msg_field_next(&i)) {
  1143. upb_fielddef *f = upb_msg_iter_field(&i);
  1144. visit(r, upb_fielddef_upcast2(f), closure);
  1145. }
  1146. for(upb_msg_oneof_begin(&o, m);
  1147. !upb_msg_oneof_done(&o);
  1148. upb_msg_oneof_next(&o)) {
  1149. upb_oneofdef *f = upb_msg_iter_oneof(&o);
  1150. visit(r, upb_oneofdef_upcast(f), closure);
  1151. }
  1152. }
  1153. static void freemsg(upb_refcounted *r) {
  1154. upb_msgdef *m = (upb_msgdef*)r;
  1155. upb_strtable_uninit(&m->ntoo);
  1156. upb_strtable_uninit(&m->ntof);
  1157. upb_inttable_uninit(&m->itof);
  1158. upb_def_uninit(upb_msgdef_upcast_mutable(m));
  1159. free(m);
  1160. }
  1161. upb_msgdef *upb_msgdef_new(const void *owner) {
  1162. static const struct upb_refcounted_vtbl vtbl = {visitmsg, freemsg};
  1163. upb_msgdef *m = malloc(sizeof(*m));
  1164. if (!m) return NULL;
  1165. if (!upb_def_init(upb_msgdef_upcast_mutable(m), UPB_DEF_MSG, &vtbl, owner))
  1166. goto err2;
  1167. if (!upb_inttable_init(&m->itof, UPB_CTYPE_PTR)) goto err3;
  1168. if (!upb_strtable_init(&m->ntof, UPB_CTYPE_PTR)) goto err2;
  1169. if (!upb_strtable_init(&m->ntoo, UPB_CTYPE_PTR)) goto err1;
  1170. m->map_entry = false;
  1171. m->syntax = UPB_SYNTAX_PROTO2;
  1172. return m;
  1173. err1:
  1174. upb_strtable_uninit(&m->ntof);
  1175. err2:
  1176. upb_inttable_uninit(&m->itof);
  1177. err3:
  1178. free(m);
  1179. return NULL;
  1180. }
  1181. upb_msgdef *upb_msgdef_dup(const upb_msgdef *m, const void *owner) {
  1182. bool ok;
  1183. upb_msg_field_iter i;
  1184. upb_msg_oneof_iter o;
  1185. upb_msgdef *newm = upb_msgdef_new(owner);
  1186. if (!newm) return NULL;
  1187. ok = upb_def_setfullname(upb_msgdef_upcast_mutable(newm),
  1188. upb_def_fullname(upb_msgdef_upcast(m)),
  1189. NULL);
  1190. newm->map_entry = m->map_entry;
  1191. newm->syntax = m->syntax;
  1192. UPB_ASSERT_VAR(ok, ok);
  1193. for(upb_msg_field_begin(&i, m);
  1194. !upb_msg_field_done(&i);
  1195. upb_msg_field_next(&i)) {
  1196. upb_fielddef *f = upb_fielddef_dup(upb_msg_iter_field(&i), &f);
  1197. /* Fields in oneofs are dup'd below. */
  1198. if (upb_fielddef_containingoneof(f)) continue;
  1199. if (!f || !upb_msgdef_addfield(newm, f, &f, NULL)) {
  1200. upb_msgdef_unref(newm, owner);
  1201. return NULL;
  1202. }
  1203. }
  1204. for(upb_msg_oneof_begin(&o, m);
  1205. !upb_msg_oneof_done(&o);
  1206. upb_msg_oneof_next(&o)) {
  1207. upb_oneofdef *f = upb_oneofdef_dup(upb_msg_iter_oneof(&o), &f);
  1208. if (!f || !upb_msgdef_addoneof(newm, f, &f, NULL)) {
  1209. upb_msgdef_unref(newm, owner);
  1210. return NULL;
  1211. }
  1212. }
  1213. return newm;
  1214. }
  1215. bool upb_msgdef_freeze(upb_msgdef *m, upb_status *status) {
  1216. upb_def *d = upb_msgdef_upcast_mutable(m);
  1217. return upb_def_freeze(&d, 1, status);
  1218. }
  1219. const char *upb_msgdef_fullname(const upb_msgdef *m) {
  1220. return upb_def_fullname(upb_msgdef_upcast(m));
  1221. }
  1222. const char *upb_msgdef_name(const upb_msgdef *m) {
  1223. return upb_def_name(upb_msgdef_upcast(m));
  1224. }
  1225. bool upb_msgdef_setfullname(upb_msgdef *m, const char *fullname,
  1226. upb_status *s) {
  1227. return upb_def_setfullname(upb_msgdef_upcast_mutable(m), fullname, s);
  1228. }
  1229. /* Helper: check that the field |f| is safe to add to msgdef |m|. Set an error
  1230. * on status |s| and return false if not. */
  1231. static bool check_field_add(const upb_msgdef *m, const upb_fielddef *f,
  1232. upb_status *s) {
  1233. if (upb_fielddef_containingtype(f) != NULL) {
  1234. upb_status_seterrmsg(s, "fielddef already belongs to a message");
  1235. return false;
  1236. } else if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  1237. upb_status_seterrmsg(s, "field name or number were not set");
  1238. return false;
  1239. } else if (upb_msgdef_ntofz(m, upb_fielddef_name(f)) ||
  1240. upb_msgdef_itof(m, upb_fielddef_number(f))) {
  1241. upb_status_seterrmsg(s, "duplicate field name or number for field");
  1242. return false;
  1243. }
  1244. return true;
  1245. }
  1246. static void add_field(upb_msgdef *m, upb_fielddef *f, const void *ref_donor) {
  1247. release_containingtype(f);
  1248. f->msg.def = m;
  1249. f->msg_is_symbolic = false;
  1250. upb_inttable_insert(&m->itof, upb_fielddef_number(f), upb_value_ptr(f));
  1251. upb_strtable_insert(&m->ntof, upb_fielddef_name(f), upb_value_ptr(f));
  1252. upb_ref2(f, m);
  1253. upb_ref2(m, f);
  1254. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  1255. }
  1256. bool upb_msgdef_addfield(upb_msgdef *m, upb_fielddef *f, const void *ref_donor,
  1257. upb_status *s) {
  1258. /* TODO: extensions need to have a separate namespace, because proto2 allows a
  1259. * top-level extension (ie. one not in any package) to have the same name as a
  1260. * field from the message.
  1261. *
  1262. * This also implies that there needs to be a separate lookup-by-name method
  1263. * for extensions. It seems desirable for iteration to return both extensions
  1264. * and non-extensions though.
  1265. *
  1266. * We also need to validate that the field number is in an extension range iff
  1267. * it is an extension.
  1268. *
  1269. * This method is idempotent. Check if |f| is already part of this msgdef and
  1270. * return immediately if so. */
  1271. if (upb_fielddef_containingtype(f) == m) {
  1272. return true;
  1273. }
  1274. /* Check constraints for all fields before performing any action. */
  1275. if (!check_field_add(m, f, s)) {
  1276. return false;
  1277. } else if (upb_fielddef_containingoneof(f) != NULL) {
  1278. /* Fields in a oneof can only be added by adding the oneof to the msgdef. */
  1279. upb_status_seterrmsg(s, "fielddef is part of a oneof");
  1280. return false;
  1281. }
  1282. /* Constraint checks ok, perform the action. */
  1283. add_field(m, f, ref_donor);
  1284. return true;
  1285. }
  1286. bool upb_msgdef_addoneof(upb_msgdef *m, upb_oneofdef *o, const void *ref_donor,
  1287. upb_status *s) {
  1288. upb_oneof_iter it;
  1289. /* Check various conditions that would prevent this oneof from being added. */
  1290. if (upb_oneofdef_containingtype(o)) {
  1291. upb_status_seterrmsg(s, "oneofdef already belongs to a message");
  1292. return false;
  1293. } else if (upb_oneofdef_name(o) == NULL) {
  1294. upb_status_seterrmsg(s, "oneofdef name was not set");
  1295. return false;
  1296. } else if (upb_msgdef_ntooz(m, upb_oneofdef_name(o))) {
  1297. upb_status_seterrmsg(s, "duplicate oneof name");
  1298. return false;
  1299. }
  1300. /* Check that all of the oneof's fields do not conflict with names or numbers
  1301. * of fields already in the message. */
  1302. for (upb_oneof_begin(&it, o); !upb_oneof_done(&it); upb_oneof_next(&it)) {
  1303. const upb_fielddef *f = upb_oneof_iter_field(&it);
  1304. if (!check_field_add(m, f, s)) {
  1305. return false;
  1306. }
  1307. }
  1308. /* Everything checks out -- commit now. */
  1309. /* Add oneof itself first. */
  1310. o->parent = m;
  1311. upb_strtable_insert(&m->ntoo, upb_oneofdef_name(o), upb_value_ptr(o));
  1312. upb_ref2(o, m);
  1313. upb_ref2(m, o);
  1314. /* Add each field of the oneof directly to the msgdef. */
  1315. for (upb_oneof_begin(&it, o); !upb_oneof_done(&it); upb_oneof_next(&it)) {
  1316. upb_fielddef *f = upb_oneof_iter_field(&it);
  1317. add_field(m, f, NULL);
  1318. }
  1319. if (ref_donor) upb_oneofdef_unref(o, ref_donor);
  1320. return true;
  1321. }
  1322. const upb_fielddef *upb_msgdef_itof(const upb_msgdef *m, uint32_t i) {
  1323. upb_value val;
  1324. return upb_inttable_lookup32(&m->itof, i, &val) ?
  1325. upb_value_getptr(val) : NULL;
  1326. }
  1327. const upb_fielddef *upb_msgdef_ntof(const upb_msgdef *m, const char *name,
  1328. size_t len) {
  1329. upb_value val;
  1330. return upb_strtable_lookup2(&m->ntof, name, len, &val) ?
  1331. upb_value_getptr(val) : NULL;
  1332. }
  1333. const upb_oneofdef *upb_msgdef_ntoo(const upb_msgdef *m, const char *name,
  1334. size_t len) {
  1335. upb_value val;
  1336. return upb_strtable_lookup2(&m->ntoo, name, len, &val) ?
  1337. upb_value_getptr(val) : NULL;
  1338. }
  1339. int upb_msgdef_numfields(const upb_msgdef *m) {
  1340. return upb_strtable_count(&m->ntof);
  1341. }
  1342. int upb_msgdef_numoneofs(const upb_msgdef *m) {
  1343. return upb_strtable_count(&m->ntoo);
  1344. }
  1345. void upb_msgdef_setmapentry(upb_msgdef *m, bool map_entry) {
  1346. assert(!upb_msgdef_isfrozen(m));
  1347. m->map_entry = map_entry;
  1348. }
  1349. bool upb_msgdef_mapentry(const upb_msgdef *m) {
  1350. return m->map_entry;
  1351. }
  1352. void upb_msg_field_begin(upb_msg_field_iter *iter, const upb_msgdef *m) {
  1353. upb_inttable_begin(iter, &m->itof);
  1354. }
  1355. void upb_msg_field_next(upb_msg_field_iter *iter) { upb_inttable_next(iter); }
  1356. bool upb_msg_field_done(const upb_msg_field_iter *iter) {
  1357. return upb_inttable_done(iter);
  1358. }
  1359. upb_fielddef *upb_msg_iter_field(const upb_msg_field_iter *iter) {
  1360. return (upb_fielddef*)upb_value_getptr(upb_inttable_iter_value(iter));
  1361. }
  1362. void upb_msg_field_iter_setdone(upb_msg_field_iter *iter) {
  1363. upb_inttable_iter_setdone(iter);
  1364. }
  1365. void upb_msg_oneof_begin(upb_msg_oneof_iter *iter, const upb_msgdef *m) {
  1366. upb_strtable_begin(iter, &m->ntoo);
  1367. }
  1368. void upb_msg_oneof_next(upb_msg_oneof_iter *iter) { upb_strtable_next(iter); }
  1369. bool upb_msg_oneof_done(const upb_msg_oneof_iter *iter) {
  1370. return upb_strtable_done(iter);
  1371. }
  1372. upb_oneofdef *upb_msg_iter_oneof(const upb_msg_oneof_iter *iter) {
  1373. return (upb_oneofdef*)upb_value_getptr(upb_strtable_iter_value(iter));
  1374. }
  1375. void upb_msg_oneof_iter_setdone(upb_msg_oneof_iter *iter) {
  1376. upb_strtable_iter_setdone(iter);
  1377. }
  1378. /* upb_oneofdef ***************************************************************/
  1379. static void visitoneof(const upb_refcounted *r, upb_refcounted_visit *visit,
  1380. void *closure) {
  1381. const upb_oneofdef *o = (const upb_oneofdef*)r;
  1382. upb_oneof_iter i;
  1383. for (upb_oneof_begin(&i, o); !upb_oneof_done(&i); upb_oneof_next(&i)) {
  1384. const upb_fielddef *f = upb_oneof_iter_field(&i);
  1385. visit(r, upb_fielddef_upcast2(f), closure);
  1386. }
  1387. if (o->parent) {
  1388. visit(r, upb_msgdef_upcast2(o->parent), closure);
  1389. }
  1390. }
  1391. static void freeoneof(upb_refcounted *r) {
  1392. upb_oneofdef *o = (upb_oneofdef*)r;
  1393. upb_strtable_uninit(&o->ntof);
  1394. upb_inttable_uninit(&o->itof);
  1395. free((void*)o->name);
  1396. free(o);
  1397. }
  1398. upb_oneofdef *upb_oneofdef_new(const void *owner) {
  1399. static const struct upb_refcounted_vtbl vtbl = {visitoneof, freeoneof};
  1400. upb_oneofdef *o = malloc(sizeof(*o));
  1401. o->parent = NULL;
  1402. if (!o) return NULL;
  1403. if (!upb_refcounted_init(upb_oneofdef_upcast_mutable(o), &vtbl, owner))
  1404. goto err2;
  1405. o->name = NULL;
  1406. if (!upb_inttable_init(&o->itof, UPB_CTYPE_PTR)) goto err2;
  1407. if (!upb_strtable_init(&o->ntof, UPB_CTYPE_PTR)) goto err1;
  1408. return o;
  1409. err1:
  1410. upb_inttable_uninit(&o->itof);
  1411. err2:
  1412. free(o);
  1413. return NULL;
  1414. }
  1415. upb_oneofdef *upb_oneofdef_dup(const upb_oneofdef *o, const void *owner) {
  1416. bool ok;
  1417. upb_oneof_iter i;
  1418. upb_oneofdef *newo = upb_oneofdef_new(owner);
  1419. if (!newo) return NULL;
  1420. ok = upb_oneofdef_setname(newo, upb_oneofdef_name(o), NULL);
  1421. UPB_ASSERT_VAR(ok, ok);
  1422. for (upb_oneof_begin(&i, o); !upb_oneof_done(&i); upb_oneof_next(&i)) {
  1423. upb_fielddef *f = upb_fielddef_dup(upb_oneof_iter_field(&i), &f);
  1424. if (!f || !upb_oneofdef_addfield(newo, f, &f, NULL)) {
  1425. upb_oneofdef_unref(newo, owner);
  1426. return NULL;
  1427. }
  1428. }
  1429. return newo;
  1430. }
  1431. const char *upb_oneofdef_name(const upb_oneofdef *o) { return o->name; }
  1432. bool upb_oneofdef_setname(upb_oneofdef *o, const char *name, upb_status *s) {
  1433. assert(!upb_oneofdef_isfrozen(o));
  1434. if (upb_oneofdef_containingtype(o)) {
  1435. upb_status_seterrmsg(s, "oneof already added to a message");
  1436. return false;
  1437. }
  1438. if (!upb_isident(name, strlen(name), true, s)) return false;
  1439. free((void*)o->name);
  1440. o->name = upb_strdup(name);
  1441. return true;
  1442. }
  1443. const upb_msgdef *upb_oneofdef_containingtype(const upb_oneofdef *o) {
  1444. return o->parent;
  1445. }
  1446. int upb_oneofdef_numfields(const upb_oneofdef *o) {
  1447. return upb_strtable_count(&o->ntof);
  1448. }
  1449. bool upb_oneofdef_addfield(upb_oneofdef *o, upb_fielddef *f,
  1450. const void *ref_donor,
  1451. upb_status *s) {
  1452. assert(!upb_oneofdef_isfrozen(o));
  1453. assert(!o->parent || !upb_msgdef_isfrozen(o->parent));
  1454. /* This method is idempotent. Check if |f| is already part of this oneofdef
  1455. * and return immediately if so. */
  1456. if (upb_fielddef_containingoneof(f) == o) {
  1457. return true;
  1458. }
  1459. /* The field must have an OPTIONAL label. */
  1460. if (upb_fielddef_label(f) != UPB_LABEL_OPTIONAL) {
  1461. upb_status_seterrmsg(s, "fields in oneof must have OPTIONAL label");
  1462. return false;
  1463. }
  1464. /* Check that no field with this name or number exists already in the oneof.
  1465. * Also check that the field is not already part of a oneof. */
  1466. if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  1467. upb_status_seterrmsg(s, "field name or number were not set");
  1468. return false;
  1469. } else if (upb_oneofdef_itof(o, upb_fielddef_number(f)) ||
  1470. upb_oneofdef_ntofz(o, upb_fielddef_name(f))) {
  1471. upb_status_seterrmsg(s, "duplicate field name or number");
  1472. return false;
  1473. } else if (upb_fielddef_containingoneof(f) != NULL) {
  1474. upb_status_seterrmsg(s, "fielddef already belongs to a oneof");
  1475. return false;
  1476. }
  1477. /* We allow adding a field to the oneof either if the field is not part of a
  1478. * msgdef, or if it is and we are also part of the same msgdef. */
  1479. if (o->parent == NULL) {
  1480. /* If we're not in a msgdef, the field cannot be either. Otherwise we would
  1481. * need to magically add this oneof to a msgdef to remain consistent, which
  1482. * is surprising behavior. */
  1483. if (upb_fielddef_containingtype(f) != NULL) {
  1484. upb_status_seterrmsg(s, "fielddef already belongs to a message, but "
  1485. "oneof does not");
  1486. return false;
  1487. }
  1488. } else {
  1489. /* If we're in a msgdef, the user can add fields that either aren't in any
  1490. * msgdef (in which case they're added to our msgdef) or already a part of
  1491. * our msgdef. */
  1492. if (upb_fielddef_containingtype(f) != NULL &&
  1493. upb_fielddef_containingtype(f) != o->parent) {
  1494. upb_status_seterrmsg(s, "fielddef belongs to a different message "
  1495. "than oneof");
  1496. return false;
  1497. }
  1498. }
  1499. /* Commit phase. First add the field to our parent msgdef, if any, because
  1500. * that may fail; then add the field to our own tables. */
  1501. if (o->parent != NULL && upb_fielddef_containingtype(f) == NULL) {
  1502. if (!upb_msgdef_addfield((upb_msgdef*)o->parent, f, NULL, s)) {
  1503. return false;
  1504. }
  1505. }
  1506. release_containingtype(f);
  1507. f->oneof = o;
  1508. upb_inttable_insert(&o->itof, upb_fielddef_number(f), upb_value_ptr(f));
  1509. upb_strtable_insert(&o->ntof, upb_fielddef_name(f), upb_value_ptr(f));
  1510. upb_ref2(f, o);
  1511. upb_ref2(o, f);
  1512. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  1513. return true;
  1514. }
  1515. const upb_fielddef *upb_oneofdef_ntof(const upb_oneofdef *o,
  1516. const char *name, size_t length) {
  1517. upb_value val;
  1518. return upb_strtable_lookup2(&o->ntof, name, length, &val) ?
  1519. upb_value_getptr(val) : NULL;
  1520. }
  1521. const upb_fielddef *upb_oneofdef_itof(const upb_oneofdef *o, uint32_t num) {
  1522. upb_value val;
  1523. return upb_inttable_lookup32(&o->itof, num, &val) ?
  1524. upb_value_getptr(val) : NULL;
  1525. }
  1526. void upb_oneof_begin(upb_oneof_iter *iter, const upb_oneofdef *o) {
  1527. upb_inttable_begin(iter, &o->itof);
  1528. }
  1529. void upb_oneof_next(upb_oneof_iter *iter) {
  1530. upb_inttable_next(iter);
  1531. }
  1532. bool upb_oneof_done(upb_oneof_iter *iter) {
  1533. return upb_inttable_done(iter);
  1534. }
  1535. upb_fielddef *upb_oneof_iter_field(const upb_oneof_iter *iter) {
  1536. return (upb_fielddef*)upb_value_getptr(upb_inttable_iter_value(iter));
  1537. }
  1538. void upb_oneof_iter_setdone(upb_oneof_iter *iter) {
  1539. upb_inttable_iter_setdone(iter);
  1540. }
  1541. /* upb_filedef ****************************************************************/
  1542. static void visitfiledef(const upb_refcounted *r, upb_refcounted_visit *visit,
  1543. void *closure) {
  1544. const upb_filedef *f = (const upb_filedef*)r;
  1545. size_t i;
  1546. for(i = 0; i < upb_filedef_defcount(f); i++) {
  1547. visit(r, upb_def_upcast(upb_filedef_def(f, i)), closure);
  1548. }
  1549. }
  1550. static void freefiledef(upb_refcounted *r) {
  1551. upb_filedef *f = (upb_filedef*)r;
  1552. size_t i;
  1553. for(i = 0; i < upb_filedef_depcount(f); i++) {
  1554. upb_filedef_unref(upb_filedef_dep(f, i), f);
  1555. }
  1556. upb_inttable_uninit(&f->defs);
  1557. upb_inttable_uninit(&f->deps);
  1558. free((void*)f->name);
  1559. free((void*)f->package);
  1560. free(f);
  1561. }
  1562. upb_filedef *upb_filedef_new(const void *owner) {
  1563. static const struct upb_refcounted_vtbl vtbl = {visitfiledef, freefiledef};
  1564. upb_filedef *f = malloc(sizeof(*f));
  1565. if (!f) {
  1566. return NULL;
  1567. }
  1568. f->package = NULL;
  1569. f->name = NULL;
  1570. f->syntax = UPB_SYNTAX_PROTO2;
  1571. if (!upb_refcounted_init(upb_filedef_upcast_mutable(f), &vtbl, owner)) {
  1572. goto err;
  1573. }
  1574. if (!upb_inttable_init(&f->defs, UPB_CTYPE_CONSTPTR)) {
  1575. goto err;
  1576. }
  1577. if (!upb_inttable_init(&f->deps, UPB_CTYPE_CONSTPTR)) {
  1578. goto err2;
  1579. }
  1580. return f;
  1581. err2:
  1582. upb_inttable_uninit(&f->defs);
  1583. err:
  1584. free(f);
  1585. return NULL;
  1586. }
  1587. const char *upb_filedef_name(const upb_filedef *f) {
  1588. return f->name;
  1589. }
  1590. const char *upb_filedef_package(const upb_filedef *f) {
  1591. return f->package;
  1592. }
  1593. upb_syntax_t upb_filedef_syntax(const upb_filedef *f) {
  1594. return f->syntax;
  1595. }
  1596. size_t upb_filedef_defcount(const upb_filedef *f) {
  1597. return upb_inttable_count(&f->defs);
  1598. }
  1599. size_t upb_filedef_depcount(const upb_filedef *f) {
  1600. return upb_inttable_count(&f->deps);
  1601. }
  1602. const upb_def *upb_filedef_def(const upb_filedef *f, size_t i) {
  1603. upb_value v;
  1604. if (upb_inttable_lookup32(&f->defs, i, &v)) {
  1605. return upb_value_getconstptr(v);
  1606. } else {
  1607. return NULL;
  1608. }
  1609. }
  1610. const upb_filedef *upb_filedef_dep(const upb_filedef *f, size_t i) {
  1611. upb_value v;
  1612. if (upb_inttable_lookup32(&f->deps, i, &v)) {
  1613. return upb_value_getconstptr(v);
  1614. } else {
  1615. return NULL;
  1616. }
  1617. }
  1618. bool upb_filedef_setname(upb_filedef *f, const char *name, upb_status *s) {
  1619. name = upb_strdup(name);
  1620. if (!name) {
  1621. upb_status_seterrmsg(s, "Out of memory");
  1622. return false;
  1623. }
  1624. free((void*)f->name);
  1625. f->name = name;
  1626. return true;
  1627. }
  1628. bool upb_filedef_setpackage(upb_filedef *f, const char *package,
  1629. upb_status *s) {
  1630. if (!upb_isident(package, strlen(package), true, s)) return false;
  1631. package = upb_strdup(package);
  1632. if (!package) {
  1633. upb_status_seterrmsg(s, "Out of memory");
  1634. return false;
  1635. }
  1636. free((void*)f->package);
  1637. f->package = package;
  1638. return true;
  1639. }
  1640. bool upb_filedef_setsyntax(upb_filedef *f, upb_syntax_t syntax,
  1641. upb_status *s) {
  1642. UPB_UNUSED(s);
  1643. if (syntax != UPB_SYNTAX_PROTO2 &&
  1644. syntax != UPB_SYNTAX_PROTO3) {
  1645. upb_status_seterrmsg(s, "Unknown syntax value.");
  1646. return false;
  1647. }
  1648. f->syntax = syntax;
  1649. {
  1650. /* Set all messages in this file to match. */
  1651. size_t i;
  1652. for (i = 0; i < upb_filedef_defcount(f); i++) {
  1653. /* Casting const away is safe since all defs in mutable filedef must
  1654. * also be mutable. */
  1655. upb_def *def = (upb_def*)upb_filedef_def(f, i);
  1656. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  1657. if (m) {
  1658. m->syntax = syntax;
  1659. }
  1660. }
  1661. }
  1662. return true;
  1663. }
  1664. bool upb_filedef_adddef(upb_filedef *f, upb_def *def, const void *ref_donor,
  1665. upb_status *s) {
  1666. if (def->file) {
  1667. upb_status_seterrmsg(s, "Def is already part of another filedef.");
  1668. return false;
  1669. }
  1670. if (upb_inttable_push(&f->defs, upb_value_constptr(def))) {
  1671. def->file = f;
  1672. upb_ref2(def, f);
  1673. if (ref_donor) upb_def_unref(def, ref_donor);
  1674. if (def->type == UPB_DEF_MSG) {
  1675. upb_downcast_msgdef_mutable(def)->syntax = f->syntax;
  1676. }
  1677. return true;
  1678. } else {
  1679. upb_status_seterrmsg(s, "Out of memory.");
  1680. return false;
  1681. }
  1682. }
  1683. bool upb_filedef_adddep(upb_filedef *f, const upb_filedef *dep) {
  1684. if (upb_inttable_push(&f->deps, upb_value_constptr(dep))) {
  1685. /* Regular ref instead of ref2 because files can't form cycles. */
  1686. upb_filedef_ref(dep, f);
  1687. return true;
  1688. } else {
  1689. return false;
  1690. }
  1691. }
  1692. #include <stdlib.h>
  1693. #include <stdio.h>
  1694. #include <string.h>
  1695. typedef struct cleanup_ent {
  1696. upb_cleanup_func *cleanup;
  1697. void *ud;
  1698. struct cleanup_ent *next;
  1699. } cleanup_ent;
  1700. static void *seeded_alloc(void *ud, void *ptr, size_t oldsize, size_t size);
  1701. /* Default allocator **********************************************************/
  1702. /* Just use realloc, keeping all allocated blocks in a linked list to destroy at
  1703. * the end. */
  1704. typedef struct mem_block {
  1705. /* List is doubly-linked, because in cases where realloc() moves an existing
  1706. * block, we need to be able to remove the old pointer from the list
  1707. * efficiently. */
  1708. struct mem_block *prev, *next;
  1709. #ifndef NDEBUG
  1710. size_t size; /* Doesn't include mem_block structure. */
  1711. #endif
  1712. } mem_block;
  1713. typedef struct {
  1714. mem_block *head;
  1715. } default_alloc_ud;
  1716. static void *default_alloc(void *_ud, void *ptr, size_t oldsize, size_t size) {
  1717. default_alloc_ud *ud = _ud;
  1718. mem_block *from, *block;
  1719. void *ret;
  1720. UPB_UNUSED(oldsize);
  1721. from = ptr ? (void*)((char*)ptr - sizeof(mem_block)) : NULL;
  1722. #ifndef NDEBUG
  1723. if (from) {
  1724. assert(oldsize <= from->size);
  1725. }
  1726. #endif
  1727. /* TODO(haberman): we probably need to provide even better alignment here,
  1728. * like 16-byte alignment of the returned data pointer. */
  1729. block = realloc(from, size + sizeof(mem_block));
  1730. if (!block) return NULL;
  1731. ret = (char*)block + sizeof(*block);
  1732. #ifndef NDEBUG
  1733. block->size = size;
  1734. #endif
  1735. if (from) {
  1736. if (block != from) {
  1737. /* The block was moved, so pointers in next and prev blocks must be
  1738. * updated to its new location. */
  1739. if (block->next) block->next->prev = block;
  1740. if (block->prev) block->prev->next = block;
  1741. if (ud->head == from) ud->head = block;
  1742. }
  1743. } else {
  1744. /* Insert at head of linked list. */
  1745. block->prev = NULL;
  1746. block->next = ud->head;
  1747. if (block->next) block->next->prev = block;
  1748. ud->head = block;
  1749. }
  1750. return ret;
  1751. }
  1752. static void default_alloc_cleanup(void *_ud) {
  1753. default_alloc_ud *ud = _ud;
  1754. mem_block *block = ud->head;
  1755. while (block) {
  1756. void *to_free = block;
  1757. block = block->next;
  1758. free(to_free);
  1759. }
  1760. }
  1761. /* Standard error functions ***************************************************/
  1762. static bool default_err(void *ud, const upb_status *status) {
  1763. UPB_UNUSED(ud);
  1764. UPB_UNUSED(status);
  1765. return false;
  1766. }
  1767. static bool write_err_to(void *ud, const upb_status *status) {
  1768. upb_status *copy_to = ud;
  1769. upb_status_copy(copy_to, status);
  1770. return false;
  1771. }
  1772. /* upb_env ********************************************************************/
  1773. void upb_env_init(upb_env *e) {
  1774. default_alloc_ud *ud = (default_alloc_ud*)&e->default_alloc_ud;
  1775. e->ok_ = true;
  1776. e->bytes_allocated = 0;
  1777. e->cleanup_head = NULL;
  1778. ud->head = NULL;
  1779. /* Set default functions. */
  1780. upb_env_setallocfunc(e, default_alloc, ud);
  1781. upb_env_seterrorfunc(e, default_err, NULL);
  1782. }
  1783. void upb_env_uninit(upb_env *e) {
  1784. cleanup_ent *ent = e->cleanup_head;
  1785. while (ent) {
  1786. ent->cleanup(ent->ud);
  1787. ent = ent->next;
  1788. }
  1789. /* Must do this after running cleanup functions, because this will delete
  1790. the memory we store our cleanup entries in! */
  1791. if (e->alloc == default_alloc) {
  1792. default_alloc_cleanup(e->alloc_ud);
  1793. }
  1794. }
  1795. UPB_FORCEINLINE void upb_env_setallocfunc(upb_env *e, upb_alloc_func *alloc,
  1796. void *ud) {
  1797. e->alloc = alloc;
  1798. e->alloc_ud = ud;
  1799. }
  1800. UPB_FORCEINLINE void upb_env_seterrorfunc(upb_env *e, upb_error_func *func,
  1801. void *ud) {
  1802. e->err = func;
  1803. e->err_ud = ud;
  1804. }
  1805. void upb_env_reporterrorsto(upb_env *e, upb_status *status) {
  1806. e->err = write_err_to;
  1807. e->err_ud = status;
  1808. }
  1809. bool upb_env_ok(const upb_env *e) {
  1810. return e->ok_;
  1811. }
  1812. bool upb_env_reporterror(upb_env *e, const upb_status *status) {
  1813. e->ok_ = false;
  1814. return e->err(e->err_ud, status);
  1815. }
  1816. bool upb_env_addcleanup(upb_env *e, upb_cleanup_func *func, void *ud) {
  1817. cleanup_ent *ent = upb_env_malloc(e, sizeof(cleanup_ent));
  1818. if (!ent) return false;
  1819. ent->cleanup = func;
  1820. ent->ud = ud;
  1821. ent->next = e->cleanup_head;
  1822. e->cleanup_head = ent;
  1823. return true;
  1824. }
  1825. void *upb_env_malloc(upb_env *e, size_t size) {
  1826. e->bytes_allocated += size;
  1827. if (e->alloc == seeded_alloc) {
  1828. /* This is equivalent to the next branch, but allows inlining for a
  1829. * measurable perf benefit. */
  1830. return seeded_alloc(e->alloc_ud, NULL, 0, size);
  1831. } else {
  1832. return e->alloc(e->alloc_ud, NULL, 0, size);
  1833. }
  1834. }
  1835. void *upb_env_realloc(upb_env *e, void *ptr, size_t oldsize, size_t size) {
  1836. char *ret;
  1837. assert(oldsize <= size);
  1838. ret = e->alloc(e->alloc_ud, ptr, oldsize, size);
  1839. #ifndef NDEBUG
  1840. /* Overwrite non-preserved memory to ensure callers are passing the oldsize
  1841. * that they truly require. */
  1842. memset(ret + oldsize, 0xff, size - oldsize);
  1843. #endif
  1844. return ret;
  1845. }
  1846. size_t upb_env_bytesallocated(const upb_env *e) {
  1847. return e->bytes_allocated;
  1848. }
  1849. /* upb_seededalloc ************************************************************/
  1850. /* Be conservative and choose 16 in case anyone is using SSE. */
  1851. static const size_t maxalign = 16;
  1852. static size_t align_up(size_t size) {
  1853. return ((size + maxalign - 1) / maxalign) * maxalign;
  1854. }
  1855. UPB_FORCEINLINE static void *seeded_alloc(void *ud, void *ptr, size_t oldsize,
  1856. size_t size) {
  1857. upb_seededalloc *a = ud;
  1858. size = align_up(size);
  1859. assert(a->mem_limit >= a->mem_ptr);
  1860. if (oldsize == 0 && size <= (size_t)(a->mem_limit - a->mem_ptr)) {
  1861. /* Fast path: we can satisfy from the initial allocation. */
  1862. void *ret = a->mem_ptr;
  1863. a->mem_ptr += size;
  1864. return ret;
  1865. } else {
  1866. char *chptr = ptr;
  1867. /* Slow path: fallback to other allocator. */
  1868. a->need_cleanup = true;
  1869. /* Is `ptr` part of the user-provided initial block? Don't pass it to the
  1870. * default allocator if so; otherwise, it may try to realloc() the block. */
  1871. if (chptr >= a->mem_base && chptr < a->mem_limit) {
  1872. void *ret;
  1873. assert(chptr + oldsize <= a->mem_limit);
  1874. ret = a->alloc(a->alloc_ud, NULL, 0, size);
  1875. if (ret) memcpy(ret, ptr, oldsize);
  1876. return ret;
  1877. } else {
  1878. return a->alloc(a->alloc_ud, ptr, oldsize, size);
  1879. }
  1880. }
  1881. }
  1882. void upb_seededalloc_init(upb_seededalloc *a, void *mem, size_t len) {
  1883. default_alloc_ud *ud = (default_alloc_ud*)&a->default_alloc_ud;
  1884. a->mem_base = mem;
  1885. a->mem_ptr = mem;
  1886. a->mem_limit = (char*)mem + len;
  1887. a->need_cleanup = false;
  1888. a->returned_allocfunc = false;
  1889. ud->head = NULL;
  1890. upb_seededalloc_setfallbackalloc(a, default_alloc, ud);
  1891. }
  1892. void upb_seededalloc_uninit(upb_seededalloc *a) {
  1893. if (a->alloc == default_alloc && a->need_cleanup) {
  1894. default_alloc_cleanup(a->alloc_ud);
  1895. }
  1896. }
  1897. UPB_FORCEINLINE void upb_seededalloc_setfallbackalloc(upb_seededalloc *a,
  1898. upb_alloc_func *alloc,
  1899. void *ud) {
  1900. assert(!a->returned_allocfunc);
  1901. a->alloc = alloc;
  1902. a->alloc_ud = ud;
  1903. }
  1904. upb_alloc_func *upb_seededalloc_getallocfunc(upb_seededalloc *a) {
  1905. a->returned_allocfunc = true;
  1906. return seeded_alloc;
  1907. }
  1908. /*
  1909. ** TODO(haberman): it's unclear whether a lot of the consistency checks should
  1910. ** assert() or return false.
  1911. */
  1912. #include <stdlib.h>
  1913. #include <string.h>
  1914. /* Defined for the sole purpose of having a unique pointer value for
  1915. * UPB_NO_CLOSURE. */
  1916. char _upb_noclosure;
  1917. static void freehandlers(upb_refcounted *r) {
  1918. upb_handlers *h = (upb_handlers*)r;
  1919. upb_inttable_iter i;
  1920. upb_inttable_begin(&i, &h->cleanup_);
  1921. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  1922. void *val = (void*)upb_inttable_iter_key(&i);
  1923. upb_value func_val = upb_inttable_iter_value(&i);
  1924. upb_handlerfree *func = upb_value_getfptr(func_val);
  1925. func(val);
  1926. }
  1927. upb_inttable_uninit(&h->cleanup_);
  1928. upb_msgdef_unref(h->msg, h);
  1929. free(h->sub);
  1930. free(h);
  1931. }
  1932. static void visithandlers(const upb_refcounted *r, upb_refcounted_visit *visit,
  1933. void *closure) {
  1934. const upb_handlers *h = (const upb_handlers*)r;
  1935. upb_msg_field_iter i;
  1936. for(upb_msg_field_begin(&i, h->msg);
  1937. !upb_msg_field_done(&i);
  1938. upb_msg_field_next(&i)) {
  1939. upb_fielddef *f = upb_msg_iter_field(&i);
  1940. const upb_handlers *sub;
  1941. if (!upb_fielddef_issubmsg(f)) continue;
  1942. sub = upb_handlers_getsubhandlers(h, f);
  1943. if (sub) visit(r, upb_handlers_upcast(sub), closure);
  1944. }
  1945. }
  1946. static const struct upb_refcounted_vtbl vtbl = {visithandlers, freehandlers};
  1947. typedef struct {
  1948. upb_inttable tab; /* maps upb_msgdef* -> upb_handlers*. */
  1949. upb_handlers_callback *callback;
  1950. const void *closure;
  1951. } dfs_state;
  1952. /* TODO(haberman): discard upb_handlers* objects that do not actually have any
  1953. * handlers set and cannot reach any upb_handlers* object that does. This is
  1954. * slightly tricky to do correctly. */
  1955. static upb_handlers *newformsg(const upb_msgdef *m, const void *owner,
  1956. dfs_state *s) {
  1957. upb_msg_field_iter i;
  1958. upb_handlers *h = upb_handlers_new(m, owner);
  1959. if (!h) return NULL;
  1960. if (!upb_inttable_insertptr(&s->tab, m, upb_value_ptr(h))) goto oom;
  1961. s->callback(s->closure, h);
  1962. /* For each submessage field, get or create a handlers object and set it as
  1963. * the subhandlers. */
  1964. for(upb_msg_field_begin(&i, m);
  1965. !upb_msg_field_done(&i);
  1966. upb_msg_field_next(&i)) {
  1967. upb_fielddef *f = upb_msg_iter_field(&i);
  1968. const upb_msgdef *subdef;
  1969. upb_value subm_ent;
  1970. if (!upb_fielddef_issubmsg(f)) continue;
  1971. subdef = upb_downcast_msgdef(upb_fielddef_subdef(f));
  1972. if (upb_inttable_lookupptr(&s->tab, subdef, &subm_ent)) {
  1973. upb_handlers_setsubhandlers(h, f, upb_value_getptr(subm_ent));
  1974. } else {
  1975. upb_handlers *sub_mh = newformsg(subdef, &sub_mh, s);
  1976. if (!sub_mh) goto oom;
  1977. upb_handlers_setsubhandlers(h, f, sub_mh);
  1978. upb_handlers_unref(sub_mh, &sub_mh);
  1979. }
  1980. }
  1981. return h;
  1982. oom:
  1983. upb_handlers_unref(h, owner);
  1984. return NULL;
  1985. }
  1986. /* Given a selector for a STARTSUBMSG handler, resolves to a pointer to the
  1987. * subhandlers for this submessage field. */
  1988. #define SUBH(h, selector) (h->sub[selector])
  1989. /* The selector for a submessage field is the field index. */
  1990. #define SUBH_F(h, f) SUBH(h, f->index_)
  1991. static int32_t trygetsel(upb_handlers *h, const upb_fielddef *f,
  1992. upb_handlertype_t type) {
  1993. upb_selector_t sel;
  1994. assert(!upb_handlers_isfrozen(h));
  1995. if (upb_handlers_msgdef(h) != upb_fielddef_containingtype(f)) {
  1996. upb_status_seterrf(
  1997. &h->status_, "type mismatch: field %s does not belong to message %s",
  1998. upb_fielddef_name(f), upb_msgdef_fullname(upb_handlers_msgdef(h)));
  1999. return -1;
  2000. }
  2001. if (!upb_handlers_getselector(f, type, &sel)) {
  2002. upb_status_seterrf(
  2003. &h->status_,
  2004. "type mismatch: cannot register handler type %d for field %s",
  2005. type, upb_fielddef_name(f));
  2006. return -1;
  2007. }
  2008. return sel;
  2009. }
  2010. static upb_selector_t handlers_getsel(upb_handlers *h, const upb_fielddef *f,
  2011. upb_handlertype_t type) {
  2012. int32_t sel = trygetsel(h, f, type);
  2013. assert(sel >= 0);
  2014. return sel;
  2015. }
  2016. static const void **returntype(upb_handlers *h, const upb_fielddef *f,
  2017. upb_handlertype_t type) {
  2018. return &h->table[handlers_getsel(h, f, type)].attr.return_closure_type_;
  2019. }
  2020. static bool doset(upb_handlers *h, int32_t sel, const upb_fielddef *f,
  2021. upb_handlertype_t type, upb_func *func,
  2022. upb_handlerattr *attr) {
  2023. upb_handlerattr set_attr = UPB_HANDLERATTR_INITIALIZER;
  2024. const void *closure_type;
  2025. const void **context_closure_type;
  2026. assert(!upb_handlers_isfrozen(h));
  2027. if (sel < 0) {
  2028. upb_status_seterrmsg(&h->status_,
  2029. "incorrect handler type for this field.");
  2030. return false;
  2031. }
  2032. if (h->table[sel].func) {
  2033. upb_status_seterrmsg(&h->status_,
  2034. "cannot change handler once it has been set.");
  2035. return false;
  2036. }
  2037. if (attr) {
  2038. set_attr = *attr;
  2039. }
  2040. /* Check that the given closure type matches the closure type that has been
  2041. * established for this context (if any). */
  2042. closure_type = upb_handlerattr_closuretype(&set_attr);
  2043. if (type == UPB_HANDLER_STRING) {
  2044. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSTR);
  2045. } else if (f && upb_fielddef_isseq(f) &&
  2046. type != UPB_HANDLER_STARTSEQ &&
  2047. type != UPB_HANDLER_ENDSEQ) {
  2048. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSEQ);
  2049. } else {
  2050. context_closure_type = &h->top_closure_type;
  2051. }
  2052. if (closure_type && *context_closure_type &&
  2053. closure_type != *context_closure_type) {
  2054. /* TODO(haberman): better message for debugging. */
  2055. if (f) {
  2056. upb_status_seterrf(&h->status_,
  2057. "closure type does not match for field %s",
  2058. upb_fielddef_name(f));
  2059. } else {
  2060. upb_status_seterrmsg(
  2061. &h->status_, "closure type does not match for message-level handler");
  2062. }
  2063. return false;
  2064. }
  2065. if (closure_type)
  2066. *context_closure_type = closure_type;
  2067. /* If this is a STARTSEQ or STARTSTR handler, check that the returned pointer
  2068. * matches any pre-existing expectations about what type is expected. */
  2069. if (type == UPB_HANDLER_STARTSEQ || type == UPB_HANDLER_STARTSTR) {
  2070. const void *return_type = upb_handlerattr_returnclosuretype(&set_attr);
  2071. const void *table_return_type =
  2072. upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  2073. if (return_type && table_return_type && return_type != table_return_type) {
  2074. upb_status_seterrmsg(&h->status_, "closure return type does not match");
  2075. return false;
  2076. }
  2077. if (table_return_type && !return_type)
  2078. upb_handlerattr_setreturnclosuretype(&set_attr, table_return_type);
  2079. }
  2080. h->table[sel].func = (upb_func*)func;
  2081. h->table[sel].attr = set_attr;
  2082. return true;
  2083. }
  2084. /* Returns the effective closure type for this handler (which will propagate
  2085. * from outer frames if this frame has no START* handler). Not implemented for
  2086. * UPB_HANDLER_STRING at the moment since this is not needed. Returns NULL is
  2087. * the effective closure type is unspecified (either no handler was registered
  2088. * to specify it or the handler that was registered did not specify the closure
  2089. * type). */
  2090. const void *effective_closure_type(upb_handlers *h, const upb_fielddef *f,
  2091. upb_handlertype_t type) {
  2092. const void *ret;
  2093. upb_selector_t sel;
  2094. assert(type != UPB_HANDLER_STRING);
  2095. ret = h->top_closure_type;
  2096. if (upb_fielddef_isseq(f) &&
  2097. type != UPB_HANDLER_STARTSEQ &&
  2098. type != UPB_HANDLER_ENDSEQ &&
  2099. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)].func) {
  2100. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  2101. }
  2102. if (type == UPB_HANDLER_STRING &&
  2103. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSTR)].func) {
  2104. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  2105. }
  2106. /* The effective type of the submessage; not used yet.
  2107. * if (type == SUBMESSAGE &&
  2108. * h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)].func) {
  2109. * ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  2110. * } */
  2111. return ret;
  2112. }
  2113. /* Checks whether the START* handler specified by f & type is missing even
  2114. * though it is required to convert the established type of an outer frame
  2115. * ("closure_type") into the established type of an inner frame (represented in
  2116. * the return closure type of this handler's attr. */
  2117. bool checkstart(upb_handlers *h, const upb_fielddef *f, upb_handlertype_t type,
  2118. upb_status *status) {
  2119. const void *closure_type;
  2120. const upb_handlerattr *attr;
  2121. const void *return_closure_type;
  2122. upb_selector_t sel = handlers_getsel(h, f, type);
  2123. if (h->table[sel].func) return true;
  2124. closure_type = effective_closure_type(h, f, type);
  2125. attr = &h->table[sel].attr;
  2126. return_closure_type = upb_handlerattr_returnclosuretype(attr);
  2127. if (closure_type && return_closure_type &&
  2128. closure_type != return_closure_type) {
  2129. upb_status_seterrf(status,
  2130. "expected start handler to return sub type for field %f",
  2131. upb_fielddef_name(f));
  2132. return false;
  2133. }
  2134. return true;
  2135. }
  2136. /* Public interface ***********************************************************/
  2137. upb_handlers *upb_handlers_new(const upb_msgdef *md, const void *owner) {
  2138. int extra;
  2139. upb_handlers *h;
  2140. assert(upb_msgdef_isfrozen(md));
  2141. extra = sizeof(upb_handlers_tabent) * (md->selector_count - 1);
  2142. h = calloc(sizeof(*h) + extra, 1);
  2143. if (!h) return NULL;
  2144. h->msg = md;
  2145. upb_msgdef_ref(h->msg, h);
  2146. upb_status_clear(&h->status_);
  2147. h->sub = calloc(md->submsg_field_count, sizeof(*h->sub));
  2148. if (!h->sub) goto oom;
  2149. if (!upb_refcounted_init(upb_handlers_upcast_mutable(h), &vtbl, owner))
  2150. goto oom;
  2151. if (!upb_inttable_init(&h->cleanup_, UPB_CTYPE_FPTR)) goto oom;
  2152. /* calloc() above initialized all handlers to NULL. */
  2153. return h;
  2154. oom:
  2155. freehandlers(upb_handlers_upcast_mutable(h));
  2156. return NULL;
  2157. }
  2158. const upb_handlers *upb_handlers_newfrozen(const upb_msgdef *m,
  2159. const void *owner,
  2160. upb_handlers_callback *callback,
  2161. const void *closure) {
  2162. dfs_state state;
  2163. upb_handlers *ret;
  2164. bool ok;
  2165. upb_refcounted *r;
  2166. state.callback = callback;
  2167. state.closure = closure;
  2168. if (!upb_inttable_init(&state.tab, UPB_CTYPE_PTR)) return NULL;
  2169. ret = newformsg(m, owner, &state);
  2170. upb_inttable_uninit(&state.tab);
  2171. if (!ret) return NULL;
  2172. r = upb_handlers_upcast_mutable(ret);
  2173. ok = upb_refcounted_freeze(&r, 1, NULL, UPB_MAX_HANDLER_DEPTH);
  2174. UPB_ASSERT_VAR(ok, ok);
  2175. return ret;
  2176. }
  2177. const upb_status *upb_handlers_status(upb_handlers *h) {
  2178. assert(!upb_handlers_isfrozen(h));
  2179. return &h->status_;
  2180. }
  2181. void upb_handlers_clearerr(upb_handlers *h) {
  2182. assert(!upb_handlers_isfrozen(h));
  2183. upb_status_clear(&h->status_);
  2184. }
  2185. #define SETTER(name, handlerctype, handlertype) \
  2186. bool upb_handlers_set ## name(upb_handlers *h, const upb_fielddef *f, \
  2187. handlerctype func, upb_handlerattr *attr) { \
  2188. int32_t sel = trygetsel(h, f, handlertype); \
  2189. return doset(h, sel, f, handlertype, (upb_func*)func, attr); \
  2190. }
  2191. SETTER(int32, upb_int32_handlerfunc*, UPB_HANDLER_INT32)
  2192. SETTER(int64, upb_int64_handlerfunc*, UPB_HANDLER_INT64)
  2193. SETTER(uint32, upb_uint32_handlerfunc*, UPB_HANDLER_UINT32)
  2194. SETTER(uint64, upb_uint64_handlerfunc*, UPB_HANDLER_UINT64)
  2195. SETTER(float, upb_float_handlerfunc*, UPB_HANDLER_FLOAT)
  2196. SETTER(double, upb_double_handlerfunc*, UPB_HANDLER_DOUBLE)
  2197. SETTER(bool, upb_bool_handlerfunc*, UPB_HANDLER_BOOL)
  2198. SETTER(startstr, upb_startstr_handlerfunc*, UPB_HANDLER_STARTSTR)
  2199. SETTER(string, upb_string_handlerfunc*, UPB_HANDLER_STRING)
  2200. SETTER(endstr, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSTR)
  2201. SETTER(startseq, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSEQ)
  2202. SETTER(startsubmsg, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSUBMSG)
  2203. SETTER(endsubmsg, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSUBMSG)
  2204. SETTER(endseq, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSEQ)
  2205. #undef SETTER
  2206. bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
  2207. upb_handlerattr *attr) {
  2208. return doset(h, UPB_STARTMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  2209. (upb_func *)func, attr);
  2210. }
  2211. bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func,
  2212. upb_handlerattr *attr) {
  2213. assert(!upb_handlers_isfrozen(h));
  2214. return doset(h, UPB_ENDMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  2215. (upb_func *)func, attr);
  2216. }
  2217. bool upb_handlers_setsubhandlers(upb_handlers *h, const upb_fielddef *f,
  2218. const upb_handlers *sub) {
  2219. assert(sub);
  2220. assert(!upb_handlers_isfrozen(h));
  2221. assert(upb_fielddef_issubmsg(f));
  2222. if (SUBH_F(h, f)) return false; /* Can't reset. */
  2223. if (upb_msgdef_upcast(upb_handlers_msgdef(sub)) != upb_fielddef_subdef(f)) {
  2224. return false;
  2225. }
  2226. SUBH_F(h, f) = sub;
  2227. upb_ref2(sub, h);
  2228. return true;
  2229. }
  2230. const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h,
  2231. const upb_fielddef *f) {
  2232. assert(upb_fielddef_issubmsg(f));
  2233. return SUBH_F(h, f);
  2234. }
  2235. bool upb_handlers_getattr(const upb_handlers *h, upb_selector_t sel,
  2236. upb_handlerattr *attr) {
  2237. if (!upb_handlers_gethandler(h, sel))
  2238. return false;
  2239. *attr = h->table[sel].attr;
  2240. return true;
  2241. }
  2242. const upb_handlers *upb_handlers_getsubhandlers_sel(const upb_handlers *h,
  2243. upb_selector_t sel) {
  2244. /* STARTSUBMSG selector in sel is the field's selector base. */
  2245. return SUBH(h, sel - UPB_STATIC_SELECTOR_COUNT);
  2246. }
  2247. const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h) { return h->msg; }
  2248. bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *func) {
  2249. bool ok;
  2250. if (upb_inttable_lookupptr(&h->cleanup_, p, NULL)) {
  2251. return false;
  2252. }
  2253. ok = upb_inttable_insertptr(&h->cleanup_, p, upb_value_fptr(func));
  2254. UPB_ASSERT_VAR(ok, ok);
  2255. return true;
  2256. }
  2257. /* "Static" methods ***********************************************************/
  2258. bool upb_handlers_freeze(upb_handlers *const*handlers, int n, upb_status *s) {
  2259. /* TODO: verify we have a transitive closure. */
  2260. int i;
  2261. for (i = 0; i < n; i++) {
  2262. upb_msg_field_iter j;
  2263. upb_handlers *h = handlers[i];
  2264. if (!upb_ok(&h->status_)) {
  2265. upb_status_seterrf(s, "handlers for message %s had error status: %s",
  2266. upb_msgdef_fullname(upb_handlers_msgdef(h)),
  2267. upb_status_errmsg(&h->status_));
  2268. return false;
  2269. }
  2270. /* Check that there are no closure mismatches due to missing Start* handlers
  2271. * or subhandlers with different type-level types. */
  2272. for(upb_msg_field_begin(&j, h->msg);
  2273. !upb_msg_field_done(&j);
  2274. upb_msg_field_next(&j)) {
  2275. const upb_fielddef *f = upb_msg_iter_field(&j);
  2276. if (upb_fielddef_isseq(f)) {
  2277. if (!checkstart(h, f, UPB_HANDLER_STARTSEQ, s))
  2278. return false;
  2279. }
  2280. if (upb_fielddef_isstring(f)) {
  2281. if (!checkstart(h, f, UPB_HANDLER_STARTSTR, s))
  2282. return false;
  2283. }
  2284. if (upb_fielddef_issubmsg(f)) {
  2285. bool hashandler = false;
  2286. if (upb_handlers_gethandler(
  2287. h, handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)) ||
  2288. upb_handlers_gethandler(
  2289. h, handlers_getsel(h, f, UPB_HANDLER_ENDSUBMSG))) {
  2290. hashandler = true;
  2291. }
  2292. if (upb_fielddef_isseq(f) &&
  2293. (upb_handlers_gethandler(
  2294. h, handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)) ||
  2295. upb_handlers_gethandler(
  2296. h, handlers_getsel(h, f, UPB_HANDLER_ENDSEQ)))) {
  2297. hashandler = true;
  2298. }
  2299. if (hashandler && !upb_handlers_getsubhandlers(h, f)) {
  2300. /* For now we add an empty subhandlers in this case. It makes the
  2301. * decoder code generator simpler, because it only has to handle two
  2302. * cases (submessage has handlers or not) as opposed to three
  2303. * (submessage has handlers in enclosing message but no subhandlers).
  2304. *
  2305. * This makes parsing less efficient in the case that we want to
  2306. * notice a submessage but skip its contents (like if we're testing
  2307. * for submessage presence or counting the number of repeated
  2308. * submessages). In this case we will end up parsing the submessage
  2309. * field by field and throwing away the results for each, instead of
  2310. * skipping the whole delimited thing at once. If this is an issue we
  2311. * can revisit it, but do remember that this only arises when you have
  2312. * handlers (startseq/startsubmsg/endsubmsg/endseq) set for the
  2313. * submessage but no subhandlers. The uses cases for this are
  2314. * limited. */
  2315. upb_handlers *sub = upb_handlers_new(upb_fielddef_msgsubdef(f), &sub);
  2316. upb_handlers_setsubhandlers(h, f, sub);
  2317. upb_handlers_unref(sub, &sub);
  2318. }
  2319. /* TODO(haberman): check type of submessage.
  2320. * This is slightly tricky; also consider whether we should check that
  2321. * they match at setsubhandlers time. */
  2322. }
  2323. }
  2324. }
  2325. if (!upb_refcounted_freeze((upb_refcounted*const*)handlers, n, s,
  2326. UPB_MAX_HANDLER_DEPTH)) {
  2327. return false;
  2328. }
  2329. return true;
  2330. }
  2331. upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f) {
  2332. switch (upb_fielddef_type(f)) {
  2333. case UPB_TYPE_INT32:
  2334. case UPB_TYPE_ENUM: return UPB_HANDLER_INT32;
  2335. case UPB_TYPE_INT64: return UPB_HANDLER_INT64;
  2336. case UPB_TYPE_UINT32: return UPB_HANDLER_UINT32;
  2337. case UPB_TYPE_UINT64: return UPB_HANDLER_UINT64;
  2338. case UPB_TYPE_FLOAT: return UPB_HANDLER_FLOAT;
  2339. case UPB_TYPE_DOUBLE: return UPB_HANDLER_DOUBLE;
  2340. case UPB_TYPE_BOOL: return UPB_HANDLER_BOOL;
  2341. default: assert(false); return -1; /* Invalid input. */
  2342. }
  2343. }
  2344. bool upb_handlers_getselector(const upb_fielddef *f, upb_handlertype_t type,
  2345. upb_selector_t *s) {
  2346. switch (type) {
  2347. case UPB_HANDLER_INT32:
  2348. case UPB_HANDLER_INT64:
  2349. case UPB_HANDLER_UINT32:
  2350. case UPB_HANDLER_UINT64:
  2351. case UPB_HANDLER_FLOAT:
  2352. case UPB_HANDLER_DOUBLE:
  2353. case UPB_HANDLER_BOOL:
  2354. if (!upb_fielddef_isprimitive(f) ||
  2355. upb_handlers_getprimitivehandlertype(f) != type)
  2356. return false;
  2357. *s = f->selector_base;
  2358. break;
  2359. case UPB_HANDLER_STRING:
  2360. if (upb_fielddef_isstring(f)) {
  2361. *s = f->selector_base;
  2362. } else if (upb_fielddef_lazy(f)) {
  2363. *s = f->selector_base + 3;
  2364. } else {
  2365. return false;
  2366. }
  2367. break;
  2368. case UPB_HANDLER_STARTSTR:
  2369. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  2370. *s = f->selector_base + 1;
  2371. } else {
  2372. return false;
  2373. }
  2374. break;
  2375. case UPB_HANDLER_ENDSTR:
  2376. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  2377. *s = f->selector_base + 2;
  2378. } else {
  2379. return false;
  2380. }
  2381. break;
  2382. case UPB_HANDLER_STARTSEQ:
  2383. if (!upb_fielddef_isseq(f)) return false;
  2384. *s = f->selector_base - 2;
  2385. break;
  2386. case UPB_HANDLER_ENDSEQ:
  2387. if (!upb_fielddef_isseq(f)) return false;
  2388. *s = f->selector_base - 1;
  2389. break;
  2390. case UPB_HANDLER_STARTSUBMSG:
  2391. if (!upb_fielddef_issubmsg(f)) return false;
  2392. /* Selectors for STARTSUBMSG are at the beginning of the table so that the
  2393. * selector can also be used as an index into the "sub" array of
  2394. * subhandlers. The indexes for the two into these two tables are the
  2395. * same, except that in the handler table the static selectors come first. */
  2396. *s = f->index_ + UPB_STATIC_SELECTOR_COUNT;
  2397. break;
  2398. case UPB_HANDLER_ENDSUBMSG:
  2399. if (!upb_fielddef_issubmsg(f)) return false;
  2400. *s = f->selector_base;
  2401. break;
  2402. }
  2403. assert((size_t)*s < upb_fielddef_containingtype(f)->selector_count);
  2404. return true;
  2405. }
  2406. uint32_t upb_handlers_selectorbaseoffset(const upb_fielddef *f) {
  2407. return upb_fielddef_isseq(f) ? 2 : 0;
  2408. }
  2409. uint32_t upb_handlers_selectorcount(const upb_fielddef *f) {
  2410. uint32_t ret = 1;
  2411. if (upb_fielddef_isseq(f)) ret += 2; /* STARTSEQ/ENDSEQ */
  2412. if (upb_fielddef_isstring(f)) ret += 2; /* [STRING]/STARTSTR/ENDSTR */
  2413. if (upb_fielddef_issubmsg(f)) {
  2414. /* ENDSUBMSG (STARTSUBMSG is at table beginning) */
  2415. ret += 0;
  2416. if (upb_fielddef_lazy(f)) {
  2417. /* STARTSTR/ENDSTR/STRING (for lazy) */
  2418. ret += 3;
  2419. }
  2420. }
  2421. return ret;
  2422. }
  2423. /* upb_handlerattr ************************************************************/
  2424. void upb_handlerattr_init(upb_handlerattr *attr) {
  2425. upb_handlerattr from = UPB_HANDLERATTR_INITIALIZER;
  2426. memcpy(attr, &from, sizeof(*attr));
  2427. }
  2428. void upb_handlerattr_uninit(upb_handlerattr *attr) {
  2429. UPB_UNUSED(attr);
  2430. }
  2431. bool upb_handlerattr_sethandlerdata(upb_handlerattr *attr, const void *hd) {
  2432. attr->handler_data_ = hd;
  2433. return true;
  2434. }
  2435. bool upb_handlerattr_setclosuretype(upb_handlerattr *attr, const void *type) {
  2436. attr->closure_type_ = type;
  2437. return true;
  2438. }
  2439. const void *upb_handlerattr_closuretype(const upb_handlerattr *attr) {
  2440. return attr->closure_type_;
  2441. }
  2442. bool upb_handlerattr_setreturnclosuretype(upb_handlerattr *attr,
  2443. const void *type) {
  2444. attr->return_closure_type_ = type;
  2445. return true;
  2446. }
  2447. const void *upb_handlerattr_returnclosuretype(const upb_handlerattr *attr) {
  2448. return attr->return_closure_type_;
  2449. }
  2450. bool upb_handlerattr_setalwaysok(upb_handlerattr *attr, bool alwaysok) {
  2451. attr->alwaysok_ = alwaysok;
  2452. return true;
  2453. }
  2454. bool upb_handlerattr_alwaysok(const upb_handlerattr *attr) {
  2455. return attr->alwaysok_;
  2456. }
  2457. /* upb_bufhandle **************************************************************/
  2458. size_t upb_bufhandle_objofs(const upb_bufhandle *h) {
  2459. return h->objofs_;
  2460. }
  2461. /* upb_byteshandler ***********************************************************/
  2462. void upb_byteshandler_init(upb_byteshandler* h) {
  2463. memset(h, 0, sizeof(*h));
  2464. }
  2465. /* For when we support handlerfree callbacks. */
  2466. void upb_byteshandler_uninit(upb_byteshandler* h) {
  2467. UPB_UNUSED(h);
  2468. }
  2469. bool upb_byteshandler_setstartstr(upb_byteshandler *h,
  2470. upb_startstr_handlerfunc *func, void *d) {
  2471. h->table[UPB_STARTSTR_SELECTOR].func = (upb_func*)func;
  2472. h->table[UPB_STARTSTR_SELECTOR].attr.handler_data_ = d;
  2473. return true;
  2474. }
  2475. bool upb_byteshandler_setstring(upb_byteshandler *h,
  2476. upb_string_handlerfunc *func, void *d) {
  2477. h->table[UPB_STRING_SELECTOR].func = (upb_func*)func;
  2478. h->table[UPB_STRING_SELECTOR].attr.handler_data_ = d;
  2479. return true;
  2480. }
  2481. bool upb_byteshandler_setendstr(upb_byteshandler *h,
  2482. upb_endfield_handlerfunc *func, void *d) {
  2483. h->table[UPB_ENDSTR_SELECTOR].func = (upb_func*)func;
  2484. h->table[UPB_ENDSTR_SELECTOR].attr.handler_data_ = d;
  2485. return true;
  2486. }
  2487. /*
  2488. ** upb::RefCounted Implementation
  2489. **
  2490. ** Our key invariants are:
  2491. ** 1. reference cycles never span groups
  2492. ** 2. for ref2(to, from), we increment to's count iff group(from) != group(to)
  2493. **
  2494. ** The previous two are how we avoid leaking cycles. Other important
  2495. ** invariants are:
  2496. ** 3. for mutable objects "from" and "to", if there exists a ref2(to, from)
  2497. ** this implies group(from) == group(to). (In practice, what we implement
  2498. ** is even stronger; "from" and "to" will share a group if there has *ever*
  2499. ** been a ref2(to, from), but all that is necessary for correctness is the
  2500. ** weaker one).
  2501. ** 4. mutable and immutable objects are never in the same group.
  2502. */
  2503. #include <setjmp.h>
  2504. #include <stdlib.h>
  2505. static void freeobj(upb_refcounted *o);
  2506. const char untracked_val;
  2507. const void *UPB_UNTRACKED_REF = &untracked_val;
  2508. /* arch-specific atomic primitives *******************************************/
  2509. #ifdef UPB_THREAD_UNSAFE /*---------------------------------------------------*/
  2510. static void atomic_inc(uint32_t *a) { (*a)++; }
  2511. static bool atomic_dec(uint32_t *a) { return --(*a) == 0; }
  2512. #elif defined(__GNUC__) || defined(__clang__) /*------------------------------*/
  2513. static void atomic_inc(uint32_t *a) { __sync_fetch_and_add(a, 1); }
  2514. static bool atomic_dec(uint32_t *a) { return __sync_sub_and_fetch(a, 1) == 0; }
  2515. #elif defined(WIN32) /*-------------------------------------------------------*/
  2516. #include <Windows.h>
  2517. static void atomic_inc(upb_atomic_t *a) { InterlockedIncrement(&a->val); }
  2518. static bool atomic_dec(upb_atomic_t *a) {
  2519. return InterlockedDecrement(&a->val) == 0;
  2520. }
  2521. #else
  2522. #error Atomic primitives not defined for your platform/CPU. \
  2523. Implement them or compile with UPB_THREAD_UNSAFE.
  2524. #endif
  2525. /* All static objects point to this refcount.
  2526. * It is special-cased in ref/unref below. */
  2527. uint32_t static_refcount = -1;
  2528. /* We can avoid atomic ops for statically-declared objects.
  2529. * This is a minor optimization but nice since we can avoid degrading under
  2530. * contention in this case. */
  2531. static void refgroup(uint32_t *group) {
  2532. if (group != &static_refcount)
  2533. atomic_inc(group);
  2534. }
  2535. static bool unrefgroup(uint32_t *group) {
  2536. if (group == &static_refcount) {
  2537. return false;
  2538. } else {
  2539. return atomic_dec(group);
  2540. }
  2541. }
  2542. /* Reference tracking (debug only) ********************************************/
  2543. #ifdef UPB_DEBUG_REFS
  2544. #ifdef UPB_THREAD_UNSAFE
  2545. static void upb_lock() {}
  2546. static void upb_unlock() {}
  2547. #else
  2548. /* User must define functions that lock/unlock a global mutex and link this
  2549. * file against them. */
  2550. void upb_lock();
  2551. void upb_unlock();
  2552. #endif
  2553. /* UPB_DEBUG_REFS mode counts on being able to malloc() memory in some
  2554. * code-paths that can normally never fail, like upb_refcounted_ref(). Since
  2555. * we have no way to propagage out-of-memory errors back to the user, and since
  2556. * these errors can only occur in UPB_DEBUG_REFS mode, we immediately fail. */
  2557. #define CHECK_OOM(predicate) if (!(predicate)) { assert(predicate); exit(1); }
  2558. typedef struct {
  2559. int count; /* How many refs there are (duplicates only allowed for ref2). */
  2560. bool is_ref2;
  2561. } trackedref;
  2562. static trackedref *trackedref_new(bool is_ref2) {
  2563. trackedref *ret = malloc(sizeof(*ret));
  2564. CHECK_OOM(ret);
  2565. ret->count = 1;
  2566. ret->is_ref2 = is_ref2;
  2567. return ret;
  2568. }
  2569. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  2570. upb_value v;
  2571. assert(owner);
  2572. if (owner == UPB_UNTRACKED_REF) return;
  2573. upb_lock();
  2574. if (upb_inttable_lookupptr(r->refs, owner, &v)) {
  2575. trackedref *ref = upb_value_getptr(v);
  2576. /* Since we allow multiple ref2's for the same to/from pair without
  2577. * allocating separate memory for each one, we lose the fine-grained
  2578. * tracking behavior we get with regular refs. Since ref2s only happen
  2579. * inside upb, we'll accept this limitation until/unless there is a really
  2580. * difficult upb-internal bug that can't be figured out without it. */
  2581. assert(ref2);
  2582. assert(ref->is_ref2);
  2583. ref->count++;
  2584. } else {
  2585. trackedref *ref = trackedref_new(ref2);
  2586. bool ok = upb_inttable_insertptr(r->refs, owner, upb_value_ptr(ref));
  2587. CHECK_OOM(ok);
  2588. if (ref2) {
  2589. /* We know this cast is safe when it is a ref2, because it's coming from
  2590. * another refcounted object. */
  2591. const upb_refcounted *from = owner;
  2592. assert(!upb_inttable_lookupptr(from->ref2s, r, NULL));
  2593. ok = upb_inttable_insertptr(from->ref2s, r, upb_value_ptr(NULL));
  2594. CHECK_OOM(ok);
  2595. }
  2596. }
  2597. upb_unlock();
  2598. }
  2599. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  2600. upb_value v;
  2601. bool found;
  2602. trackedref *ref;
  2603. assert(owner);
  2604. if (owner == UPB_UNTRACKED_REF) return;
  2605. upb_lock();
  2606. found = upb_inttable_lookupptr(r->refs, owner, &v);
  2607. /* This assert will fail if an owner attempts to release a ref it didn't have. */
  2608. UPB_ASSERT_VAR(found, found);
  2609. ref = upb_value_getptr(v);
  2610. assert(ref->is_ref2 == ref2);
  2611. if (--ref->count == 0) {
  2612. free(ref);
  2613. upb_inttable_removeptr(r->refs, owner, NULL);
  2614. if (ref2) {
  2615. /* We know this cast is safe when it is a ref2, because it's coming from
  2616. * another refcounted object. */
  2617. const upb_refcounted *from = owner;
  2618. bool removed = upb_inttable_removeptr(from->ref2s, r, NULL);
  2619. assert(removed);
  2620. }
  2621. }
  2622. upb_unlock();
  2623. }
  2624. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  2625. upb_value v;
  2626. bool found;
  2627. trackedref *ref;
  2628. upb_lock();
  2629. found = upb_inttable_lookupptr(r->refs, owner, &v);
  2630. UPB_ASSERT_VAR(found, found);
  2631. ref = upb_value_getptr(v);
  2632. assert(ref->is_ref2 == ref2);
  2633. upb_unlock();
  2634. }
  2635. /* Populates the given UPB_CTYPE_INT32 inttable with counts of ref2's that
  2636. * originate from the given owner. */
  2637. static void getref2s(const upb_refcounted *owner, upb_inttable *tab) {
  2638. upb_inttable_iter i;
  2639. upb_lock();
  2640. upb_inttable_begin(&i, owner->ref2s);
  2641. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  2642. upb_value v;
  2643. upb_value count;
  2644. trackedref *ref;
  2645. bool ok;
  2646. bool found;
  2647. upb_refcounted *to = (upb_refcounted*)upb_inttable_iter_key(&i);
  2648. /* To get the count we need to look in the target's table. */
  2649. found = upb_inttable_lookupptr(to->refs, owner, &v);
  2650. assert(found);
  2651. ref = upb_value_getptr(v);
  2652. count = upb_value_int32(ref->count);
  2653. ok = upb_inttable_insertptr(tab, to, count);
  2654. CHECK_OOM(ok);
  2655. }
  2656. upb_unlock();
  2657. }
  2658. typedef struct {
  2659. upb_inttable ref2;
  2660. const upb_refcounted *obj;
  2661. } check_state;
  2662. static void visit_check(const upb_refcounted *obj, const upb_refcounted *subobj,
  2663. void *closure) {
  2664. check_state *s = closure;
  2665. upb_inttable *ref2 = &s->ref2;
  2666. upb_value v;
  2667. bool removed;
  2668. int32_t newcount;
  2669. assert(obj == s->obj);
  2670. assert(subobj);
  2671. removed = upb_inttable_removeptr(ref2, subobj, &v);
  2672. /* The following assertion will fail if the visit() function visits a subobj
  2673. * that it did not have a ref2 on, or visits the same subobj too many times. */
  2674. assert(removed);
  2675. newcount = upb_value_getint32(v) - 1;
  2676. if (newcount > 0) {
  2677. upb_inttable_insert(ref2, (uintptr_t)subobj, upb_value_int32(newcount));
  2678. }
  2679. }
  2680. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  2681. void *closure) {
  2682. bool ok;
  2683. /* In DEBUG_REFS mode we know what existing ref2 refs there are, so we know
  2684. * exactly the set of nodes that visit() should visit. So we verify visit()'s
  2685. * correctness here. */
  2686. check_state state;
  2687. state.obj = r;
  2688. ok = upb_inttable_init(&state.ref2, UPB_CTYPE_INT32);
  2689. CHECK_OOM(ok);
  2690. getref2s(r, &state.ref2);
  2691. /* This should visit any children in the ref2 table. */
  2692. if (r->vtbl->visit) r->vtbl->visit(r, visit_check, &state);
  2693. /* This assertion will fail if the visit() function missed any children. */
  2694. assert(upb_inttable_count(&state.ref2) == 0);
  2695. upb_inttable_uninit(&state.ref2);
  2696. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  2697. }
  2698. static bool trackinit(upb_refcounted *r) {
  2699. r->refs = malloc(sizeof(*r->refs));
  2700. r->ref2s = malloc(sizeof(*r->ref2s));
  2701. if (!r->refs || !r->ref2s) goto err1;
  2702. if (!upb_inttable_init(r->refs, UPB_CTYPE_PTR)) goto err1;
  2703. if (!upb_inttable_init(r->ref2s, UPB_CTYPE_PTR)) goto err2;
  2704. return true;
  2705. err2:
  2706. upb_inttable_uninit(r->refs);
  2707. err1:
  2708. free(r->refs);
  2709. free(r->ref2s);
  2710. return false;
  2711. }
  2712. static void trackfree(const upb_refcounted *r) {
  2713. upb_inttable_uninit(r->refs);
  2714. upb_inttable_uninit(r->ref2s);
  2715. free(r->refs);
  2716. free(r->ref2s);
  2717. }
  2718. #else
  2719. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  2720. UPB_UNUSED(r);
  2721. UPB_UNUSED(owner);
  2722. UPB_UNUSED(ref2);
  2723. }
  2724. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  2725. UPB_UNUSED(r);
  2726. UPB_UNUSED(owner);
  2727. UPB_UNUSED(ref2);
  2728. }
  2729. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  2730. UPB_UNUSED(r);
  2731. UPB_UNUSED(owner);
  2732. UPB_UNUSED(ref2);
  2733. }
  2734. static bool trackinit(upb_refcounted *r) {
  2735. UPB_UNUSED(r);
  2736. return true;
  2737. }
  2738. static void trackfree(const upb_refcounted *r) {
  2739. UPB_UNUSED(r);
  2740. }
  2741. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  2742. void *closure) {
  2743. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  2744. }
  2745. #endif /* UPB_DEBUG_REFS */
  2746. /* freeze() *******************************************************************/
  2747. /* The freeze() operation is by far the most complicated part of this scheme.
  2748. * We compute strongly-connected components and then mutate the graph such that
  2749. * we preserve the invariants documented at the top of this file. And we must
  2750. * handle out-of-memory errors gracefully (without leaving the graph
  2751. * inconsistent), which adds to the fun. */
  2752. /* The state used by the freeze operation (shared across many functions). */
  2753. typedef struct {
  2754. int depth;
  2755. int maxdepth;
  2756. uint64_t index;
  2757. /* Maps upb_refcounted* -> attributes (color, etc). attr layout varies by
  2758. * color. */
  2759. upb_inttable objattr;
  2760. upb_inttable stack; /* stack of upb_refcounted* for Tarjan's algorithm. */
  2761. upb_inttable groups; /* array of uint32_t*, malloc'd refcounts for new groups */
  2762. upb_status *status;
  2763. jmp_buf err;
  2764. } tarjan;
  2765. static void release_ref2(const upb_refcounted *obj,
  2766. const upb_refcounted *subobj,
  2767. void *closure);
  2768. /* Node attributes -----------------------------------------------------------*/
  2769. /* After our analysis phase all nodes will be either GRAY or WHITE. */
  2770. typedef enum {
  2771. BLACK = 0, /* Object has not been seen. */
  2772. GRAY, /* Object has been found via a refgroup but may not be reachable. */
  2773. GREEN, /* Object is reachable and is currently on the Tarjan stack. */
  2774. WHITE /* Object is reachable and has been assigned a group (SCC). */
  2775. } color_t;
  2776. UPB_NORETURN static void err(tarjan *t) { longjmp(t->err, 1); }
  2777. UPB_NORETURN static void oom(tarjan *t) {
  2778. upb_status_seterrmsg(t->status, "out of memory");
  2779. err(t);
  2780. }
  2781. static uint64_t trygetattr(const tarjan *t, const upb_refcounted *r) {
  2782. upb_value v;
  2783. return upb_inttable_lookupptr(&t->objattr, r, &v) ?
  2784. upb_value_getuint64(v) : 0;
  2785. }
  2786. static uint64_t getattr(const tarjan *t, const upb_refcounted *r) {
  2787. upb_value v;
  2788. bool found = upb_inttable_lookupptr(&t->objattr, r, &v);
  2789. UPB_ASSERT_VAR(found, found);
  2790. return upb_value_getuint64(v);
  2791. }
  2792. static void setattr(tarjan *t, const upb_refcounted *r, uint64_t attr) {
  2793. upb_inttable_removeptr(&t->objattr, r, NULL);
  2794. upb_inttable_insertptr(&t->objattr, r, upb_value_uint64(attr));
  2795. }
  2796. static color_t color(tarjan *t, const upb_refcounted *r) {
  2797. return trygetattr(t, r) & 0x3; /* Color is always stored in the low 2 bits. */
  2798. }
  2799. static void set_gray(tarjan *t, const upb_refcounted *r) {
  2800. assert(color(t, r) == BLACK);
  2801. setattr(t, r, GRAY);
  2802. }
  2803. /* Pushes an obj onto the Tarjan stack and sets it to GREEN. */
  2804. static void push(tarjan *t, const upb_refcounted *r) {
  2805. assert(color(t, r) == BLACK || color(t, r) == GRAY);
  2806. /* This defines the attr layout for the GREEN state. "index" and "lowlink"
  2807. * get 31 bits, which is plenty (limit of 2B objects frozen at a time). */
  2808. setattr(t, r, GREEN | (t->index << 2) | (t->index << 33));
  2809. if (++t->index == 0x80000000) {
  2810. upb_status_seterrmsg(t->status, "too many objects to freeze");
  2811. err(t);
  2812. }
  2813. upb_inttable_push(&t->stack, upb_value_ptr((void*)r));
  2814. }
  2815. /* Pops an obj from the Tarjan stack and sets it to WHITE, with a ptr to its
  2816. * SCC group. */
  2817. static upb_refcounted *pop(tarjan *t) {
  2818. upb_refcounted *r = upb_value_getptr(upb_inttable_pop(&t->stack));
  2819. assert(color(t, r) == GREEN);
  2820. /* This defines the attr layout for nodes in the WHITE state.
  2821. * Top of group stack is [group, NULL]; we point at group. */
  2822. setattr(t, r, WHITE | (upb_inttable_count(&t->groups) - 2) << 8);
  2823. return r;
  2824. }
  2825. static void tarjan_newgroup(tarjan *t) {
  2826. uint32_t *group = malloc(sizeof(*group));
  2827. if (!group) oom(t);
  2828. /* Push group and empty group leader (we'll fill in leader later). */
  2829. if (!upb_inttable_push(&t->groups, upb_value_ptr(group)) ||
  2830. !upb_inttable_push(&t->groups, upb_value_ptr(NULL))) {
  2831. free(group);
  2832. oom(t);
  2833. }
  2834. *group = 0;
  2835. }
  2836. static uint32_t idx(tarjan *t, const upb_refcounted *r) {
  2837. assert(color(t, r) == GREEN);
  2838. return (getattr(t, r) >> 2) & 0x7FFFFFFF;
  2839. }
  2840. static uint32_t lowlink(tarjan *t, const upb_refcounted *r) {
  2841. if (color(t, r) == GREEN) {
  2842. return getattr(t, r) >> 33;
  2843. } else {
  2844. return UINT32_MAX;
  2845. }
  2846. }
  2847. static void set_lowlink(tarjan *t, const upb_refcounted *r, uint32_t lowlink) {
  2848. assert(color(t, r) == GREEN);
  2849. setattr(t, r, ((uint64_t)lowlink << 33) | (getattr(t, r) & 0x1FFFFFFFF));
  2850. }
  2851. static uint32_t *group(tarjan *t, upb_refcounted *r) {
  2852. uint64_t groupnum;
  2853. upb_value v;
  2854. bool found;
  2855. assert(color(t, r) == WHITE);
  2856. groupnum = getattr(t, r) >> 8;
  2857. found = upb_inttable_lookup(&t->groups, groupnum, &v);
  2858. UPB_ASSERT_VAR(found, found);
  2859. return upb_value_getptr(v);
  2860. }
  2861. /* If the group leader for this object's group has not previously been set,
  2862. * the given object is assigned to be its leader. */
  2863. static upb_refcounted *groupleader(tarjan *t, upb_refcounted *r) {
  2864. uint64_t leader_slot;
  2865. upb_value v;
  2866. bool found;
  2867. assert(color(t, r) == WHITE);
  2868. leader_slot = (getattr(t, r) >> 8) + 1;
  2869. found = upb_inttable_lookup(&t->groups, leader_slot, &v);
  2870. UPB_ASSERT_VAR(found, found);
  2871. if (upb_value_getptr(v)) {
  2872. return upb_value_getptr(v);
  2873. } else {
  2874. upb_inttable_remove(&t->groups, leader_slot, NULL);
  2875. upb_inttable_insert(&t->groups, leader_slot, upb_value_ptr(r));
  2876. return r;
  2877. }
  2878. }
  2879. /* Tarjan's algorithm --------------------------------------------------------*/
  2880. /* See:
  2881. * http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm */
  2882. static void do_tarjan(const upb_refcounted *obj, tarjan *t);
  2883. static void tarjan_visit(const upb_refcounted *obj,
  2884. const upb_refcounted *subobj,
  2885. void *closure) {
  2886. tarjan *t = closure;
  2887. if (++t->depth > t->maxdepth) {
  2888. upb_status_seterrf(t->status, "graph too deep to freeze (%d)", t->maxdepth);
  2889. err(t);
  2890. } else if (subobj->is_frozen || color(t, subobj) == WHITE) {
  2891. /* Do nothing: we don't want to visit or color already-frozen nodes,
  2892. * and WHITE nodes have already been assigned a SCC. */
  2893. } else if (color(t, subobj) < GREEN) {
  2894. /* Subdef has not yet been visited; recurse on it. */
  2895. do_tarjan(subobj, t);
  2896. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), lowlink(t, subobj)));
  2897. } else if (color(t, subobj) == GREEN) {
  2898. /* Subdef is in the stack and hence in the current SCC. */
  2899. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), idx(t, subobj)));
  2900. }
  2901. --t->depth;
  2902. }
  2903. static void do_tarjan(const upb_refcounted *obj, tarjan *t) {
  2904. if (color(t, obj) == BLACK) {
  2905. /* We haven't seen this object's group; mark the whole group GRAY. */
  2906. const upb_refcounted *o = obj;
  2907. do { set_gray(t, o); } while ((o = o->next) != obj);
  2908. }
  2909. push(t, obj);
  2910. visit(obj, tarjan_visit, t);
  2911. if (lowlink(t, obj) == idx(t, obj)) {
  2912. tarjan_newgroup(t);
  2913. while (pop(t) != obj)
  2914. ;
  2915. }
  2916. }
  2917. /* freeze() ------------------------------------------------------------------*/
  2918. static void crossref(const upb_refcounted *r, const upb_refcounted *subobj,
  2919. void *_t) {
  2920. tarjan *t = _t;
  2921. assert(color(t, r) > BLACK);
  2922. if (color(t, subobj) > BLACK && r->group != subobj->group) {
  2923. /* Previously this ref was not reflected in subobj->group because they
  2924. * were in the same group; now that they are split a ref must be taken. */
  2925. refgroup(subobj->group);
  2926. }
  2927. }
  2928. static bool freeze(upb_refcounted *const*roots, int n, upb_status *s,
  2929. int maxdepth) {
  2930. volatile bool ret = false;
  2931. int i;
  2932. upb_inttable_iter iter;
  2933. /* We run in two passes so that we can allocate all memory before performing
  2934. * any mutation of the input -- this allows us to leave the input unchanged
  2935. * in the case of memory allocation failure. */
  2936. tarjan t;
  2937. t.index = 0;
  2938. t.depth = 0;
  2939. t.maxdepth = maxdepth;
  2940. t.status = s;
  2941. if (!upb_inttable_init(&t.objattr, UPB_CTYPE_UINT64)) goto err1;
  2942. if (!upb_inttable_init(&t.stack, UPB_CTYPE_PTR)) goto err2;
  2943. if (!upb_inttable_init(&t.groups, UPB_CTYPE_PTR)) goto err3;
  2944. if (setjmp(t.err) != 0) goto err4;
  2945. for (i = 0; i < n; i++) {
  2946. if (color(&t, roots[i]) < GREEN) {
  2947. do_tarjan(roots[i], &t);
  2948. }
  2949. }
  2950. /* If we've made it this far, no further errors are possible so it's safe to
  2951. * mutate the objects without risk of leaving them in an inconsistent state. */
  2952. ret = true;
  2953. /* The transformation that follows requires care. The preconditions are:
  2954. * - all objects in attr map are WHITE or GRAY, and are in mutable groups
  2955. * (groups of all mutable objs)
  2956. * - no ref2(to, from) refs have incremented count(to) if both "to" and
  2957. * "from" are in our attr map (this follows from invariants (2) and (3)) */
  2958. /* Pass 1: we remove WHITE objects from their mutable groups, and add them to
  2959. * new groups according to the SCC's we computed. These new groups will
  2960. * consist of only frozen objects. None will be immediately collectible,
  2961. * because WHITE objects are by definition reachable from one of "roots",
  2962. * which the caller must own refs on. */
  2963. upb_inttable_begin(&iter, &t.objattr);
  2964. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  2965. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  2966. /* Since removal from a singly-linked list requires access to the object's
  2967. * predecessor, we consider obj->next instead of obj for moving. With the
  2968. * while() loop we guarantee that we will visit every node's predecessor.
  2969. * Proof:
  2970. * 1. every node's predecessor is in our attr map.
  2971. * 2. though the loop body may change a node's predecessor, it will only
  2972. * change it to be the node we are currently operating on, so with a
  2973. * while() loop we guarantee ourselves the chance to remove each node. */
  2974. while (color(&t, obj->next) == WHITE &&
  2975. group(&t, obj->next) != obj->next->group) {
  2976. upb_refcounted *leader;
  2977. /* Remove from old group. */
  2978. upb_refcounted *move = obj->next;
  2979. if (obj == move) {
  2980. /* Removing the last object from a group. */
  2981. assert(*obj->group == obj->individual_count);
  2982. free(obj->group);
  2983. } else {
  2984. obj->next = move->next;
  2985. /* This may decrease to zero; we'll collect GRAY objects (if any) that
  2986. * remain in the group in the third pass. */
  2987. assert(*move->group >= move->individual_count);
  2988. *move->group -= move->individual_count;
  2989. }
  2990. /* Add to new group. */
  2991. leader = groupleader(&t, move);
  2992. if (move == leader) {
  2993. /* First object added to new group is its leader. */
  2994. move->group = group(&t, move);
  2995. move->next = move;
  2996. *move->group = move->individual_count;
  2997. } else {
  2998. /* Group already has at least one object in it. */
  2999. assert(leader->group == group(&t, move));
  3000. move->group = group(&t, move);
  3001. move->next = leader->next;
  3002. leader->next = move;
  3003. *move->group += move->individual_count;
  3004. }
  3005. move->is_frozen = true;
  3006. }
  3007. }
  3008. /* Pass 2: GRAY and WHITE objects "obj" with ref2(to, obj) references must
  3009. * increment count(to) if group(obj) != group(to) (which could now be the
  3010. * case if "to" was just frozen). */
  3011. upb_inttable_begin(&iter, &t.objattr);
  3012. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  3013. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  3014. visit(obj, crossref, &t);
  3015. }
  3016. /* Pass 3: GRAY objects are collected if their group's refcount dropped to
  3017. * zero when we removed its white nodes. This can happen if they had only
  3018. * been kept alive by virtue of sharing a group with an object that was just
  3019. * frozen.
  3020. *
  3021. * It is important that we do this last, since the GRAY object's free()
  3022. * function could call unref2() on just-frozen objects, which will decrement
  3023. * refs that were added in pass 2. */
  3024. upb_inttable_begin(&iter, &t.objattr);
  3025. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  3026. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  3027. if (obj->group == NULL || *obj->group == 0) {
  3028. if (obj->group) {
  3029. upb_refcounted *o;
  3030. /* We eagerly free() the group's count (since we can't easily determine
  3031. * the group's remaining size it's the easiest way to ensure it gets
  3032. * done). */
  3033. free(obj->group);
  3034. /* Visit to release ref2's (done in a separate pass since release_ref2
  3035. * depends on o->group being unmodified so it can test merged()). */
  3036. o = obj;
  3037. do { visit(o, release_ref2, NULL); } while ((o = o->next) != obj);
  3038. /* Mark "group" fields as NULL so we know to free the objects later in
  3039. * this loop, but also don't try to delete the group twice. */
  3040. o = obj;
  3041. do { o->group = NULL; } while ((o = o->next) != obj);
  3042. }
  3043. freeobj(obj);
  3044. }
  3045. }
  3046. err4:
  3047. if (!ret) {
  3048. upb_inttable_begin(&iter, &t.groups);
  3049. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter))
  3050. free(upb_value_getptr(upb_inttable_iter_value(&iter)));
  3051. }
  3052. upb_inttable_uninit(&t.groups);
  3053. err3:
  3054. upb_inttable_uninit(&t.stack);
  3055. err2:
  3056. upb_inttable_uninit(&t.objattr);
  3057. err1:
  3058. return ret;
  3059. }
  3060. /* Misc internal functions ***************************************************/
  3061. static bool merged(const upb_refcounted *r, const upb_refcounted *r2) {
  3062. return r->group == r2->group;
  3063. }
  3064. static void merge(upb_refcounted *r, upb_refcounted *from) {
  3065. upb_refcounted *base;
  3066. upb_refcounted *tmp;
  3067. if (merged(r, from)) return;
  3068. *r->group += *from->group;
  3069. free(from->group);
  3070. base = from;
  3071. /* Set all refcount pointers in the "from" chain to the merged refcount.
  3072. *
  3073. * TODO(haberman): this linear algorithm can result in an overall O(n^2) bound
  3074. * if the user continuously extends a group by one object. Prevent this by
  3075. * using one of the techniques in this paper:
  3076. * ftp://www.ncedc.org/outgoing/geomorph/dino/orals/p245-tarjan.pdf */
  3077. do { from->group = r->group; } while ((from = from->next) != base);
  3078. /* Merge the two circularly linked lists by swapping their next pointers. */
  3079. tmp = r->next;
  3080. r->next = base->next;
  3081. base->next = tmp;
  3082. }
  3083. static void unref(const upb_refcounted *r);
  3084. static void release_ref2(const upb_refcounted *obj,
  3085. const upb_refcounted *subobj,
  3086. void *closure) {
  3087. UPB_UNUSED(closure);
  3088. untrack(subobj, obj, true);
  3089. if (!merged(obj, subobj)) {
  3090. assert(subobj->is_frozen);
  3091. unref(subobj);
  3092. }
  3093. }
  3094. static void unref(const upb_refcounted *r) {
  3095. if (unrefgroup(r->group)) {
  3096. const upb_refcounted *o;
  3097. free(r->group);
  3098. /* In two passes, since release_ref2 needs a guarantee that any subobjs
  3099. * are alive. */
  3100. o = r;
  3101. do { visit(o, release_ref2, NULL); } while((o = o->next) != r);
  3102. o = r;
  3103. do {
  3104. const upb_refcounted *next = o->next;
  3105. assert(o->is_frozen || o->individual_count == 0);
  3106. freeobj((upb_refcounted*)o);
  3107. o = next;
  3108. } while(o != r);
  3109. }
  3110. }
  3111. static void freeobj(upb_refcounted *o) {
  3112. trackfree(o);
  3113. o->vtbl->free((upb_refcounted*)o);
  3114. }
  3115. /* Public interface ***********************************************************/
  3116. bool upb_refcounted_init(upb_refcounted *r,
  3117. const struct upb_refcounted_vtbl *vtbl,
  3118. const void *owner) {
  3119. #ifndef NDEBUG
  3120. /* Endianness check. This is unrelated to upb_refcounted, it's just a
  3121. * convenient place to put the check that we can be assured will run for
  3122. * basically every program using upb. */
  3123. const int x = 1;
  3124. #ifdef UPB_BIG_ENDIAN
  3125. assert(*(char*)&x != 1);
  3126. #else
  3127. assert(*(char*)&x == 1);
  3128. #endif
  3129. #endif
  3130. r->next = r;
  3131. r->vtbl = vtbl;
  3132. r->individual_count = 0;
  3133. r->is_frozen = false;
  3134. r->group = malloc(sizeof(*r->group));
  3135. if (!r->group) return false;
  3136. *r->group = 0;
  3137. if (!trackinit(r)) {
  3138. free(r->group);
  3139. return false;
  3140. }
  3141. upb_refcounted_ref(r, owner);
  3142. return true;
  3143. }
  3144. bool upb_refcounted_isfrozen(const upb_refcounted *r) {
  3145. return r->is_frozen;
  3146. }
  3147. void upb_refcounted_ref(const upb_refcounted *r, const void *owner) {
  3148. track(r, owner, false);
  3149. if (!r->is_frozen)
  3150. ((upb_refcounted*)r)->individual_count++;
  3151. refgroup(r->group);
  3152. }
  3153. void upb_refcounted_unref(const upb_refcounted *r, const void *owner) {
  3154. untrack(r, owner, false);
  3155. if (!r->is_frozen)
  3156. ((upb_refcounted*)r)->individual_count--;
  3157. unref(r);
  3158. }
  3159. void upb_refcounted_ref2(const upb_refcounted *r, upb_refcounted *from) {
  3160. assert(!from->is_frozen); /* Non-const pointer implies this. */
  3161. track(r, from, true);
  3162. if (r->is_frozen) {
  3163. refgroup(r->group);
  3164. } else {
  3165. merge((upb_refcounted*)r, from);
  3166. }
  3167. }
  3168. void upb_refcounted_unref2(const upb_refcounted *r, upb_refcounted *from) {
  3169. assert(!from->is_frozen); /* Non-const pointer implies this. */
  3170. untrack(r, from, true);
  3171. if (r->is_frozen) {
  3172. unref(r);
  3173. } else {
  3174. assert(merged(r, from));
  3175. }
  3176. }
  3177. void upb_refcounted_donateref(
  3178. const upb_refcounted *r, const void *from, const void *to) {
  3179. assert(from != to);
  3180. if (to != NULL)
  3181. upb_refcounted_ref(r, to);
  3182. if (from != NULL)
  3183. upb_refcounted_unref(r, from);
  3184. }
  3185. void upb_refcounted_checkref(const upb_refcounted *r, const void *owner) {
  3186. checkref(r, owner, false);
  3187. }
  3188. bool upb_refcounted_freeze(upb_refcounted *const*roots, int n, upb_status *s,
  3189. int maxdepth) {
  3190. int i;
  3191. bool ret;
  3192. for (i = 0; i < n; i++) {
  3193. assert(!roots[i]->is_frozen);
  3194. }
  3195. ret = freeze(roots, n, s, maxdepth);
  3196. assert(!s || ret == upb_ok(s));
  3197. return ret;
  3198. }
  3199. #include <stdlib.h>
  3200. /* Fallback implementation if the shim is not specialized by the JIT. */
  3201. #define SHIM_WRITER(type, ctype) \
  3202. bool upb_shim_set ## type (void *c, const void *hd, ctype val) { \
  3203. uint8_t *m = c; \
  3204. const upb_shim_data *d = hd; \
  3205. if (d->hasbit > 0) \
  3206. *(uint8_t*)&m[d->hasbit / 8] |= 1 << (d->hasbit % 8); \
  3207. *(ctype*)&m[d->offset] = val; \
  3208. return true; \
  3209. } \
  3210. SHIM_WRITER(double, double)
  3211. SHIM_WRITER(float, float)
  3212. SHIM_WRITER(int32, int32_t)
  3213. SHIM_WRITER(int64, int64_t)
  3214. SHIM_WRITER(uint32, uint32_t)
  3215. SHIM_WRITER(uint64, uint64_t)
  3216. SHIM_WRITER(bool, bool)
  3217. #undef SHIM_WRITER
  3218. bool upb_shim_set(upb_handlers *h, const upb_fielddef *f, size_t offset,
  3219. int32_t hasbit) {
  3220. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  3221. bool ok;
  3222. upb_shim_data *d = malloc(sizeof(*d));
  3223. if (!d) return false;
  3224. d->offset = offset;
  3225. d->hasbit = hasbit;
  3226. upb_handlerattr_sethandlerdata(&attr, d);
  3227. upb_handlerattr_setalwaysok(&attr, true);
  3228. upb_handlers_addcleanup(h, d, free);
  3229. #define TYPE(u, l) \
  3230. case UPB_TYPE_##u: \
  3231. ok = upb_handlers_set##l(h, f, upb_shim_set##l, &attr); break;
  3232. ok = false;
  3233. switch (upb_fielddef_type(f)) {
  3234. TYPE(INT64, int64);
  3235. TYPE(INT32, int32);
  3236. TYPE(ENUM, int32);
  3237. TYPE(UINT64, uint64);
  3238. TYPE(UINT32, uint32);
  3239. TYPE(DOUBLE, double);
  3240. TYPE(FLOAT, float);
  3241. TYPE(BOOL, bool);
  3242. default: assert(false); break;
  3243. }
  3244. #undef TYPE
  3245. upb_handlerattr_uninit(&attr);
  3246. return ok;
  3247. }
  3248. const upb_shim_data *upb_shim_getdata(const upb_handlers *h, upb_selector_t s,
  3249. upb_fieldtype_t *type) {
  3250. upb_func *f = upb_handlers_gethandler(h, s);
  3251. if ((upb_int64_handlerfunc*)f == upb_shim_setint64) {
  3252. *type = UPB_TYPE_INT64;
  3253. } else if ((upb_int32_handlerfunc*)f == upb_shim_setint32) {
  3254. *type = UPB_TYPE_INT32;
  3255. } else if ((upb_uint64_handlerfunc*)f == upb_shim_setuint64) {
  3256. *type = UPB_TYPE_UINT64;
  3257. } else if ((upb_uint32_handlerfunc*)f == upb_shim_setuint32) {
  3258. *type = UPB_TYPE_UINT32;
  3259. } else if ((upb_double_handlerfunc*)f == upb_shim_setdouble) {
  3260. *type = UPB_TYPE_DOUBLE;
  3261. } else if ((upb_float_handlerfunc*)f == upb_shim_setfloat) {
  3262. *type = UPB_TYPE_FLOAT;
  3263. } else if ((upb_bool_handlerfunc*)f == upb_shim_setbool) {
  3264. *type = UPB_TYPE_BOOL;
  3265. } else {
  3266. return NULL;
  3267. }
  3268. return (const upb_shim_data*)upb_handlers_gethandlerdata(h, s);
  3269. }
  3270. #include <stdlib.h>
  3271. #include <string.h>
  3272. static void upb_symtab_free(upb_refcounted *r) {
  3273. upb_symtab *s = (upb_symtab*)r;
  3274. upb_strtable_iter i;
  3275. upb_strtable_begin(&i, &s->symtab);
  3276. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  3277. const upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  3278. upb_def_unref(def, s);
  3279. }
  3280. upb_strtable_uninit(&s->symtab);
  3281. free(s);
  3282. }
  3283. upb_symtab *upb_symtab_new(const void *owner) {
  3284. static const struct upb_refcounted_vtbl vtbl = {NULL, &upb_symtab_free};
  3285. upb_symtab *s = malloc(sizeof(*s));
  3286. upb_refcounted_init(upb_symtab_upcast_mutable(s), &vtbl, owner);
  3287. upb_strtable_init(&s->symtab, UPB_CTYPE_PTR);
  3288. return s;
  3289. }
  3290. void upb_symtab_freeze(upb_symtab *s) {
  3291. upb_refcounted *r;
  3292. bool ok;
  3293. assert(!upb_symtab_isfrozen(s));
  3294. r = upb_symtab_upcast_mutable(s);
  3295. /* The symtab does not take ref2's (see refcounted.h) on the defs, because
  3296. * defs cannot refer back to the table and therefore cannot create cycles. So
  3297. * 0 will suffice for maxdepth here. */
  3298. ok = upb_refcounted_freeze(&r, 1, NULL, 0);
  3299. UPB_ASSERT_VAR(ok, ok);
  3300. }
  3301. const upb_def *upb_symtab_lookup(const upb_symtab *s, const char *sym) {
  3302. upb_value v;
  3303. upb_def *ret = upb_strtable_lookup(&s->symtab, sym, &v) ?
  3304. upb_value_getptr(v) : NULL;
  3305. return ret;
  3306. }
  3307. const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym) {
  3308. upb_value v;
  3309. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  3310. upb_value_getptr(v) : NULL;
  3311. return def ? upb_dyncast_msgdef(def) : NULL;
  3312. }
  3313. const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym) {
  3314. upb_value v;
  3315. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  3316. upb_value_getptr(v) : NULL;
  3317. return def ? upb_dyncast_enumdef(def) : NULL;
  3318. }
  3319. /* Given a symbol and the base symbol inside which it is defined, find the
  3320. * symbol's definition in t. */
  3321. static upb_def *upb_resolvename(const upb_strtable *t,
  3322. const char *base, const char *sym) {
  3323. if(strlen(sym) == 0) return NULL;
  3324. if(sym[0] == '.') {
  3325. /* Symbols starting with '.' are absolute, so we do a single lookup.
  3326. * Slice to omit the leading '.' */
  3327. upb_value v;
  3328. return upb_strtable_lookup(t, sym + 1, &v) ? upb_value_getptr(v) : NULL;
  3329. } else {
  3330. /* Remove components from base until we find an entry or run out.
  3331. * TODO: This branch is totally broken, but currently not used. */
  3332. (void)base;
  3333. assert(false);
  3334. return NULL;
  3335. }
  3336. }
  3337. const upb_def *upb_symtab_resolve(const upb_symtab *s, const char *base,
  3338. const char *sym) {
  3339. upb_def *ret = upb_resolvename(&s->symtab, base, sym);
  3340. return ret;
  3341. }
  3342. /* Starts a depth-first traversal at "def", recursing into any subdefs
  3343. * (ie. submessage types). Adds duplicates of existing defs to addtab
  3344. * wherever necessary, so that the resulting symtab will be consistent once
  3345. * addtab is added.
  3346. *
  3347. * More specifically, if any def D is found in the DFS that:
  3348. *
  3349. * 1. can reach a def that is being replaced by something in addtab, AND
  3350. *
  3351. * 2. is not itself being replaced already (ie. this name doesn't already
  3352. * exist in addtab)
  3353. *
  3354. * ...then a duplicate (new copy) of D will be added to addtab.
  3355. *
  3356. * Returns true if this happened for any def reachable from "def."
  3357. *
  3358. * It is slightly tricky to do this correctly in the presence of cycles. If we
  3359. * detect that our DFS has hit a cycle, we might not yet know if any SCCs on
  3360. * our stack can reach a def in addtab or not. Once we figure this out, that
  3361. * answer needs to apply to *all* defs in these SCCs, even if we visited them
  3362. * already. So a straight up one-pass cycle-detecting DFS won't work.
  3363. *
  3364. * To work around this problem, we traverse each SCC (which we already
  3365. * computed, since these defs are frozen) as a single node. We first compute
  3366. * whether the SCC as a whole can reach any def in addtab, then we dup (or not)
  3367. * the entire SCC. This requires breaking the encapsulation of upb_refcounted,
  3368. * since that is where we get the data about what SCC we are in. */
  3369. static bool upb_resolve_dfs(const upb_def *def, upb_strtable *addtab,
  3370. const void *new_owner, upb_inttable *seen,
  3371. upb_status *s) {
  3372. upb_value v;
  3373. bool need_dup;
  3374. const upb_def *base;
  3375. const void* memoize_key;
  3376. /* Memoize results of this function for efficiency (since we're traversing a
  3377. * DAG this is not needed to limit the depth of the search).
  3378. *
  3379. * We memoize by SCC instead of by individual def. */
  3380. memoize_key = def->base.group;
  3381. if (upb_inttable_lookupptr(seen, memoize_key, &v))
  3382. return upb_value_getbool(v);
  3383. /* Visit submessages for all messages in the SCC. */
  3384. need_dup = false;
  3385. base = def;
  3386. do {
  3387. upb_value v;
  3388. const upb_msgdef *m;
  3389. assert(upb_def_isfrozen(def));
  3390. if (def->type == UPB_DEF_FIELD) continue;
  3391. if (upb_strtable_lookup(addtab, upb_def_fullname(def), &v)) {
  3392. need_dup = true;
  3393. }
  3394. /* For messages, continue the recursion by visiting all subdefs, but only
  3395. * ones in different SCCs. */
  3396. m = upb_dyncast_msgdef(def);
  3397. if (m) {
  3398. upb_msg_field_iter i;
  3399. for(upb_msg_field_begin(&i, m);
  3400. !upb_msg_field_done(&i);
  3401. upb_msg_field_next(&i)) {
  3402. upb_fielddef *f = upb_msg_iter_field(&i);
  3403. const upb_def *subdef;
  3404. if (!upb_fielddef_hassubdef(f)) continue;
  3405. subdef = upb_fielddef_subdef(f);
  3406. /* Skip subdefs in this SCC. */
  3407. if (def->base.group == subdef->base.group) continue;
  3408. /* |= to avoid short-circuit; we need its side-effects. */
  3409. need_dup |= upb_resolve_dfs(subdef, addtab, new_owner, seen, s);
  3410. if (!upb_ok(s)) return false;
  3411. }
  3412. }
  3413. } while ((def = (upb_def*)def->base.next) != base);
  3414. if (need_dup) {
  3415. /* Dup all defs in this SCC that don't already have entries in addtab. */
  3416. def = base;
  3417. do {
  3418. const char *name;
  3419. if (def->type == UPB_DEF_FIELD) continue;
  3420. name = upb_def_fullname(def);
  3421. if (!upb_strtable_lookup(addtab, name, NULL)) {
  3422. upb_def *newdef = upb_def_dup(def, new_owner);
  3423. if (!newdef) goto oom;
  3424. newdef->came_from_user = false;
  3425. if (!upb_strtable_insert(addtab, name, upb_value_ptr(newdef)))
  3426. goto oom;
  3427. }
  3428. } while ((def = (upb_def*)def->base.next) != base);
  3429. }
  3430. upb_inttable_insertptr(seen, memoize_key, upb_value_bool(need_dup));
  3431. return need_dup;
  3432. oom:
  3433. upb_status_seterrmsg(s, "out of memory");
  3434. return false;
  3435. }
  3436. /* TODO(haberman): we need a lot more testing of error conditions.
  3437. * The came_from_user stuff in particular is not tested. */
  3438. static bool symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
  3439. void *ref_donor, upb_refcounted *freeze_also,
  3440. upb_status *status) {
  3441. size_t i;
  3442. size_t add_n;
  3443. size_t freeze_n;
  3444. upb_strtable_iter iter;
  3445. upb_refcounted **add_objs = NULL;
  3446. upb_def **add_defs = NULL;
  3447. size_t add_objs_size;
  3448. upb_strtable addtab;
  3449. upb_inttable seen;
  3450. assert(!upb_symtab_isfrozen(s));
  3451. if (!upb_strtable_init(&addtab, UPB_CTYPE_PTR)) {
  3452. upb_status_seterrmsg(status, "out of memory");
  3453. return false;
  3454. }
  3455. /* Add new defs to our "add" set. */
  3456. for (i = 0; i < n; i++) {
  3457. upb_def *def = defs[i];
  3458. const char *fullname;
  3459. upb_fielddef *f;
  3460. if (upb_def_isfrozen(def)) {
  3461. upb_status_seterrmsg(status, "added defs must be mutable");
  3462. goto err;
  3463. }
  3464. assert(!upb_def_isfrozen(def));
  3465. fullname = upb_def_fullname(def);
  3466. if (!fullname) {
  3467. upb_status_seterrmsg(
  3468. status, "Anonymous defs cannot be added to a symtab");
  3469. goto err;
  3470. }
  3471. f = upb_dyncast_fielddef_mutable(def);
  3472. if (f) {
  3473. if (!upb_fielddef_containingtypename(f)) {
  3474. upb_status_seterrmsg(status,
  3475. "Standalone fielddefs must have a containing type "
  3476. "(extendee) name set");
  3477. goto err;
  3478. }
  3479. } else {
  3480. if (upb_strtable_lookup(&addtab, fullname, NULL)) {
  3481. upb_status_seterrf(status, "Conflicting defs named '%s'", fullname);
  3482. goto err;
  3483. }
  3484. /* We need this to back out properly, because if there is a failure we
  3485. * need to donate the ref back to the caller. */
  3486. def->came_from_user = true;
  3487. upb_def_donateref(def, ref_donor, s);
  3488. if (!upb_strtable_insert(&addtab, fullname, upb_value_ptr(def)))
  3489. goto oom_err;
  3490. }
  3491. }
  3492. /* Add standalone fielddefs (ie. extensions) to the appropriate messages.
  3493. * If the appropriate message only exists in the existing symtab, duplicate
  3494. * it so we have a mutable copy we can add the fields to. */
  3495. for (i = 0; i < n; i++) {
  3496. upb_def *def = defs[i];
  3497. upb_fielddef *f = upb_dyncast_fielddef_mutable(def);
  3498. const char *msgname;
  3499. upb_value v;
  3500. upb_msgdef *m;
  3501. if (!f) continue;
  3502. msgname = upb_fielddef_containingtypename(f);
  3503. /* We validated this earlier in this function. */
  3504. assert(msgname);
  3505. /* If the extendee name is absolutely qualified, move past the initial ".".
  3506. * TODO(haberman): it is not obvious what it would mean if this was not
  3507. * absolutely qualified. */
  3508. if (msgname[0] == '.') {
  3509. msgname++;
  3510. }
  3511. if (upb_strtable_lookup(&addtab, msgname, &v)) {
  3512. /* Extendee is in the set of defs the user asked us to add. */
  3513. m = upb_value_getptr(v);
  3514. } else {
  3515. /* Need to find and dup the extendee from the existing symtab. */
  3516. const upb_msgdef *frozen_m = upb_symtab_lookupmsg(s, msgname);
  3517. if (!frozen_m) {
  3518. upb_status_seterrf(status,
  3519. "Tried to extend message %s that does not exist "
  3520. "in this SymbolTable.",
  3521. msgname);
  3522. goto err;
  3523. }
  3524. m = upb_msgdef_dup(frozen_m, s);
  3525. if (!m) goto oom_err;
  3526. if (!upb_strtable_insert(&addtab, msgname, upb_value_ptr(m))) {
  3527. upb_msgdef_unref(m, s);
  3528. goto oom_err;
  3529. }
  3530. }
  3531. if (!upb_msgdef_addfield(m, f, ref_donor, status)) {
  3532. goto err;
  3533. }
  3534. }
  3535. /* Add dups of any existing def that can reach a def with the same name as
  3536. * anything in our "add" set. */
  3537. if (!upb_inttable_init(&seen, UPB_CTYPE_BOOL)) goto oom_err;
  3538. upb_strtable_begin(&iter, &s->symtab);
  3539. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  3540. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
  3541. upb_resolve_dfs(def, &addtab, s, &seen, status);
  3542. if (!upb_ok(status)) goto err;
  3543. }
  3544. upb_inttable_uninit(&seen);
  3545. /* Now using the table, resolve symbolic references for subdefs. */
  3546. upb_strtable_begin(&iter, &addtab);
  3547. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  3548. const char *base;
  3549. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
  3550. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  3551. upb_msg_field_iter j;
  3552. if (!m) continue;
  3553. /* Type names are resolved relative to the message in which they appear. */
  3554. base = upb_msgdef_fullname(m);
  3555. for(upb_msg_field_begin(&j, m);
  3556. !upb_msg_field_done(&j);
  3557. upb_msg_field_next(&j)) {
  3558. upb_fielddef *f = upb_msg_iter_field(&j);
  3559. const char *name = upb_fielddef_subdefname(f);
  3560. if (name && !upb_fielddef_subdef(f)) {
  3561. /* Try the lookup in the current set of to-be-added defs first. If not
  3562. * there, try existing defs. */
  3563. upb_def *subdef = upb_resolvename(&addtab, base, name);
  3564. if (subdef == NULL) {
  3565. subdef = upb_resolvename(&s->symtab, base, name);
  3566. }
  3567. if (subdef == NULL) {
  3568. upb_status_seterrf(
  3569. status, "couldn't resolve name '%s' in message '%s'", name, base);
  3570. goto err;
  3571. } else if (!upb_fielddef_setsubdef(f, subdef, status)) {
  3572. goto err;
  3573. }
  3574. }
  3575. }
  3576. }
  3577. /* We need an array of the defs in addtab, for passing to
  3578. * upb_refcounted_freeze(). */
  3579. add_objs_size = upb_strtable_count(&addtab);
  3580. if (freeze_also) {
  3581. add_objs_size++;
  3582. }
  3583. add_defs = malloc(sizeof(void*) * add_objs_size);
  3584. if (add_defs == NULL) goto oom_err;
  3585. upb_strtable_begin(&iter, &addtab);
  3586. for (add_n = 0; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  3587. add_defs[add_n++] = upb_value_getptr(upb_strtable_iter_value(&iter));
  3588. }
  3589. /* Validate defs. */
  3590. if (!_upb_def_validate(add_defs, add_n, status)) {
  3591. goto err;
  3592. }
  3593. /* Cheat a little and give the array a new type.
  3594. * This is probably undefined behavior, but this code will be deleted soon. */
  3595. add_objs = (upb_refcounted**)add_defs;
  3596. freeze_n = add_n;
  3597. if (freeze_also) {
  3598. add_objs[freeze_n++] = freeze_also;
  3599. }
  3600. if (!upb_refcounted_freeze(add_objs, freeze_n, status,
  3601. UPB_MAX_MESSAGE_DEPTH * 2)) {
  3602. goto err;
  3603. }
  3604. /* This must be delayed until all errors have been detected, since error
  3605. * recovery code uses this table to cleanup defs. */
  3606. upb_strtable_uninit(&addtab);
  3607. /* TODO(haberman) we don't properly handle errors after this point (like
  3608. * OOM in upb_strtable_insert() below). */
  3609. for (i = 0; i < add_n; i++) {
  3610. upb_def *def = (upb_def*)add_objs[i];
  3611. const char *name = upb_def_fullname(def);
  3612. upb_value v;
  3613. bool success;
  3614. if (upb_strtable_remove(&s->symtab, name, &v)) {
  3615. const upb_def *def = upb_value_getptr(v);
  3616. upb_def_unref(def, s);
  3617. }
  3618. success = upb_strtable_insert(&s->symtab, name, upb_value_ptr(def));
  3619. UPB_ASSERT_VAR(success, success == true);
  3620. }
  3621. free(add_objs);
  3622. return true;
  3623. oom_err:
  3624. upb_status_seterrmsg(status, "out of memory");
  3625. err: {
  3626. /* For defs the user passed in, we need to donate the refs back. For defs
  3627. * we dup'd, we need to just unref them. */
  3628. upb_strtable_begin(&iter, &addtab);
  3629. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  3630. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
  3631. bool came_from_user = def->came_from_user;
  3632. def->came_from_user = false;
  3633. if (came_from_user) {
  3634. upb_def_donateref(def, s, ref_donor);
  3635. } else {
  3636. upb_def_unref(def, s);
  3637. }
  3638. }
  3639. }
  3640. upb_strtable_uninit(&addtab);
  3641. free(add_objs);
  3642. assert(!upb_ok(status));
  3643. return false;
  3644. }
  3645. bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
  3646. void *ref_donor, upb_status *status) {
  3647. return symtab_add(s, defs, n, ref_donor, NULL, status);
  3648. }
  3649. bool upb_symtab_addfile(upb_symtab *s, upb_filedef *file, upb_status *status) {
  3650. size_t n;
  3651. size_t i;
  3652. upb_def **defs;
  3653. bool ret;
  3654. n = upb_filedef_defcount(file);
  3655. defs = malloc(sizeof(*defs) * n);
  3656. if (defs == NULL) {
  3657. upb_status_seterrmsg(status, "Out of memory");
  3658. return false;
  3659. }
  3660. for (i = 0; i < n; i++) {
  3661. defs[i] = upb_filedef_mutabledef(file, i);
  3662. }
  3663. ret = symtab_add(s, defs, n, NULL, upb_filedef_upcast_mutable(file), status);
  3664. free(defs);
  3665. return ret;
  3666. }
  3667. /* Iteration. */
  3668. static void advance_to_matching(upb_symtab_iter *iter) {
  3669. if (iter->type == UPB_DEF_ANY)
  3670. return;
  3671. while (!upb_strtable_done(&iter->iter) &&
  3672. iter->type != upb_symtab_iter_def(iter)->type) {
  3673. upb_strtable_next(&iter->iter);
  3674. }
  3675. }
  3676. void upb_symtab_begin(upb_symtab_iter *iter, const upb_symtab *s,
  3677. upb_deftype_t type) {
  3678. upb_strtable_begin(&iter->iter, &s->symtab);
  3679. iter->type = type;
  3680. advance_to_matching(iter);
  3681. }
  3682. void upb_symtab_next(upb_symtab_iter *iter) {
  3683. upb_strtable_next(&iter->iter);
  3684. advance_to_matching(iter);
  3685. }
  3686. bool upb_symtab_done(const upb_symtab_iter *iter) {
  3687. return upb_strtable_done(&iter->iter);
  3688. }
  3689. const upb_def *upb_symtab_iter_def(const upb_symtab_iter *iter) {
  3690. return upb_value_getptr(upb_strtable_iter_value(&iter->iter));
  3691. }
  3692. /*
  3693. ** upb_table Implementation
  3694. **
  3695. ** Implementation is heavily inspired by Lua's ltable.c.
  3696. */
  3697. #include <stdlib.h>
  3698. #include <string.h>
  3699. #define UPB_MAXARRSIZE 16 /* 64k. */
  3700. /* From Chromium. */
  3701. #define ARRAY_SIZE(x) \
  3702. ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
  3703. static const double MAX_LOAD = 0.85;
  3704. /* The minimum utilization of the array part of a mixed hash/array table. This
  3705. * is a speed/memory-usage tradeoff (though it's not straightforward because of
  3706. * cache effects). The lower this is, the more memory we'll use. */
  3707. static const double MIN_DENSITY = 0.1;
  3708. bool is_pow2(uint64_t v) { return v == 0 || (v & (v - 1)) == 0; }
  3709. int log2ceil(uint64_t v) {
  3710. int ret = 0;
  3711. bool pow2 = is_pow2(v);
  3712. while (v >>= 1) ret++;
  3713. ret = pow2 ? ret : ret + 1; /* Ceiling. */
  3714. return UPB_MIN(UPB_MAXARRSIZE, ret);
  3715. }
  3716. char *upb_strdup(const char *s) {
  3717. return upb_strdup2(s, strlen(s));
  3718. }
  3719. char *upb_strdup2(const char *s, size_t len) {
  3720. size_t n;
  3721. char *p;
  3722. /* Prevent overflow errors. */
  3723. if (len == SIZE_MAX) return NULL;
  3724. /* Always null-terminate, even if binary data; but don't rely on the input to
  3725. * have a null-terminating byte since it may be a raw binary buffer. */
  3726. n = len + 1;
  3727. p = malloc(n);
  3728. if (p) {
  3729. memcpy(p, s, len);
  3730. p[len] = 0;
  3731. }
  3732. return p;
  3733. }
  3734. /* A type to represent the lookup key of either a strtable or an inttable. */
  3735. typedef union {
  3736. uintptr_t num;
  3737. struct {
  3738. const char *str;
  3739. size_t len;
  3740. } str;
  3741. } lookupkey_t;
  3742. static lookupkey_t strkey2(const char *str, size_t len) {
  3743. lookupkey_t k;
  3744. k.str.str = str;
  3745. k.str.len = len;
  3746. return k;
  3747. }
  3748. static lookupkey_t intkey(uintptr_t key) {
  3749. lookupkey_t k;
  3750. k.num = key;
  3751. return k;
  3752. }
  3753. typedef uint32_t hashfunc_t(upb_tabkey key);
  3754. typedef bool eqlfunc_t(upb_tabkey k1, lookupkey_t k2);
  3755. /* Base table (shared code) ***************************************************/
  3756. /* For when we need to cast away const. */
  3757. static upb_tabent *mutable_entries(upb_table *t) {
  3758. return (upb_tabent*)t->entries;
  3759. }
  3760. static bool isfull(upb_table *t) {
  3761. if (upb_table_size(t) == 0) {
  3762. return true;
  3763. } else {
  3764. return ((double)(t->count + 1) / upb_table_size(t)) > MAX_LOAD;
  3765. }
  3766. }
  3767. static bool init(upb_table *t, upb_ctype_t ctype, uint8_t size_lg2) {
  3768. size_t bytes;
  3769. t->count = 0;
  3770. t->ctype = ctype;
  3771. t->size_lg2 = size_lg2;
  3772. t->mask = upb_table_size(t) ? upb_table_size(t) - 1 : 0;
  3773. bytes = upb_table_size(t) * sizeof(upb_tabent);
  3774. if (bytes > 0) {
  3775. t->entries = malloc(bytes);
  3776. if (!t->entries) return false;
  3777. memset(mutable_entries(t), 0, bytes);
  3778. } else {
  3779. t->entries = NULL;
  3780. }
  3781. return true;
  3782. }
  3783. static void uninit(upb_table *t) { free(mutable_entries(t)); }
  3784. static upb_tabent *emptyent(upb_table *t) {
  3785. upb_tabent *e = mutable_entries(t) + upb_table_size(t);
  3786. while (1) { if (upb_tabent_isempty(--e)) return e; assert(e > t->entries); }
  3787. }
  3788. static upb_tabent *getentry_mutable(upb_table *t, uint32_t hash) {
  3789. return (upb_tabent*)upb_getentry(t, hash);
  3790. }
  3791. static const upb_tabent *findentry(const upb_table *t, lookupkey_t key,
  3792. uint32_t hash, eqlfunc_t *eql) {
  3793. const upb_tabent *e;
  3794. if (t->size_lg2 == 0) return NULL;
  3795. e = upb_getentry(t, hash);
  3796. if (upb_tabent_isempty(e)) return NULL;
  3797. while (1) {
  3798. if (eql(e->key, key)) return e;
  3799. if ((e = e->next) == NULL) return NULL;
  3800. }
  3801. }
  3802. static upb_tabent *findentry_mutable(upb_table *t, lookupkey_t key,
  3803. uint32_t hash, eqlfunc_t *eql) {
  3804. return (upb_tabent*)findentry(t, key, hash, eql);
  3805. }
  3806. static bool lookup(const upb_table *t, lookupkey_t key, upb_value *v,
  3807. uint32_t hash, eqlfunc_t *eql) {
  3808. const upb_tabent *e = findentry(t, key, hash, eql);
  3809. if (e) {
  3810. if (v) {
  3811. _upb_value_setval(v, e->val.val, t->ctype);
  3812. }
  3813. return true;
  3814. } else {
  3815. return false;
  3816. }
  3817. }
  3818. /* The given key must not already exist in the table. */
  3819. static void insert(upb_table *t, lookupkey_t key, upb_tabkey tabkey,
  3820. upb_value val, uint32_t hash,
  3821. hashfunc_t *hashfunc, eqlfunc_t *eql) {
  3822. upb_tabent *mainpos_e;
  3823. upb_tabent *our_e;
  3824. UPB_UNUSED(eql);
  3825. UPB_UNUSED(key);
  3826. assert(findentry(t, key, hash, eql) == NULL);
  3827. assert(val.ctype == t->ctype);
  3828. t->count++;
  3829. mainpos_e = getentry_mutable(t, hash);
  3830. our_e = mainpos_e;
  3831. if (upb_tabent_isempty(mainpos_e)) {
  3832. /* Our main position is empty; use it. */
  3833. our_e->next = NULL;
  3834. } else {
  3835. /* Collision. */
  3836. upb_tabent *new_e = emptyent(t);
  3837. /* Head of collider's chain. */
  3838. upb_tabent *chain = getentry_mutable(t, hashfunc(mainpos_e->key));
  3839. if (chain == mainpos_e) {
  3840. /* Existing ent is in its main posisiton (it has the same hash as us, and
  3841. * is the head of our chain). Insert to new ent and append to this chain. */
  3842. new_e->next = mainpos_e->next;
  3843. mainpos_e->next = new_e;
  3844. our_e = new_e;
  3845. } else {
  3846. /* Existing ent is not in its main position (it is a node in some other
  3847. * chain). This implies that no existing ent in the table has our hash.
  3848. * Evict it (updating its chain) and use its ent for head of our chain. */
  3849. *new_e = *mainpos_e; /* copies next. */
  3850. while (chain->next != mainpos_e) {
  3851. chain = (upb_tabent*)chain->next;
  3852. assert(chain);
  3853. }
  3854. chain->next = new_e;
  3855. our_e = mainpos_e;
  3856. our_e->next = NULL;
  3857. }
  3858. }
  3859. our_e->key = tabkey;
  3860. our_e->val.val = val.val;
  3861. assert(findentry(t, key, hash, eql) == our_e);
  3862. }
  3863. static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
  3864. upb_tabkey *removed, uint32_t hash, eqlfunc_t *eql) {
  3865. upb_tabent *chain = getentry_mutable(t, hash);
  3866. if (upb_tabent_isempty(chain)) return false;
  3867. if (eql(chain->key, key)) {
  3868. /* Element to remove is at the head of its chain. */
  3869. t->count--;
  3870. if (val) {
  3871. _upb_value_setval(val, chain->val.val, t->ctype);
  3872. }
  3873. if (chain->next) {
  3874. upb_tabent *move = (upb_tabent*)chain->next;
  3875. *chain = *move;
  3876. if (removed) *removed = move->key;
  3877. move->key = 0; /* Make the slot empty. */
  3878. } else {
  3879. if (removed) *removed = chain->key;
  3880. chain->key = 0; /* Make the slot empty. */
  3881. }
  3882. return true;
  3883. } else {
  3884. /* Element to remove is either in a non-head position or not in the
  3885. * table. */
  3886. while (chain->next && !eql(chain->next->key, key))
  3887. chain = (upb_tabent*)chain->next;
  3888. if (chain->next) {
  3889. /* Found element to remove. */
  3890. upb_tabent *rm;
  3891. if (val) {
  3892. _upb_value_setval(val, chain->next->val.val, t->ctype);
  3893. }
  3894. rm = (upb_tabent*)chain->next;
  3895. if (removed) *removed = rm->key;
  3896. rm->key = 0;
  3897. chain->next = rm->next;
  3898. t->count--;
  3899. return true;
  3900. } else {
  3901. return false;
  3902. }
  3903. }
  3904. }
  3905. static size_t next(const upb_table *t, size_t i) {
  3906. do {
  3907. if (++i >= upb_table_size(t))
  3908. return SIZE_MAX;
  3909. } while(upb_tabent_isempty(&t->entries[i]));
  3910. return i;
  3911. }
  3912. static size_t begin(const upb_table *t) {
  3913. return next(t, -1);
  3914. }
  3915. /* upb_strtable ***************************************************************/
  3916. /* A simple "subclass" of upb_table that only adds a hash function for strings. */
  3917. static upb_tabkey strcopy(lookupkey_t k2) {
  3918. char *str = malloc(k2.str.len + sizeof(uint32_t) + 1);
  3919. if (str == NULL) return 0;
  3920. memcpy(str, &k2.str.len, sizeof(uint32_t));
  3921. memcpy(str + sizeof(uint32_t), k2.str.str, k2.str.len + 1);
  3922. return (uintptr_t)str;
  3923. }
  3924. static uint32_t strhash(upb_tabkey key) {
  3925. uint32_t len;
  3926. char *str = upb_tabstr(key, &len);
  3927. return MurmurHash2(str, len, 0);
  3928. }
  3929. static bool streql(upb_tabkey k1, lookupkey_t k2) {
  3930. uint32_t len;
  3931. char *str = upb_tabstr(k1, &len);
  3932. return len == k2.str.len && memcmp(str, k2.str.str, len) == 0;
  3933. }
  3934. bool upb_strtable_init(upb_strtable *t, upb_ctype_t ctype) {
  3935. return init(&t->t, ctype, 2);
  3936. }
  3937. void upb_strtable_uninit(upb_strtable *t) {
  3938. size_t i;
  3939. for (i = 0; i < upb_table_size(&t->t); i++)
  3940. free((void*)t->t.entries[i].key);
  3941. uninit(&t->t);
  3942. }
  3943. bool upb_strtable_resize(upb_strtable *t, size_t size_lg2) {
  3944. upb_strtable new_table;
  3945. upb_strtable_iter i;
  3946. if (!init(&new_table.t, t->t.ctype, size_lg2))
  3947. return false;
  3948. upb_strtable_begin(&i, t);
  3949. for ( ; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  3950. upb_strtable_insert2(
  3951. &new_table,
  3952. upb_strtable_iter_key(&i),
  3953. upb_strtable_iter_keylength(&i),
  3954. upb_strtable_iter_value(&i));
  3955. }
  3956. upb_strtable_uninit(t);
  3957. *t = new_table;
  3958. return true;
  3959. }
  3960. bool upb_strtable_insert2(upb_strtable *t, const char *k, size_t len,
  3961. upb_value v) {
  3962. lookupkey_t key;
  3963. upb_tabkey tabkey;
  3964. uint32_t hash;
  3965. if (isfull(&t->t)) {
  3966. /* Need to resize. New table of double the size, add old elements to it. */
  3967. if (!upb_strtable_resize(t, t->t.size_lg2 + 1)) {
  3968. return false;
  3969. }
  3970. }
  3971. key = strkey2(k, len);
  3972. tabkey = strcopy(key);
  3973. if (tabkey == 0) return false;
  3974. hash = MurmurHash2(key.str.str, key.str.len, 0);
  3975. insert(&t->t, key, tabkey, v, hash, &strhash, &streql);
  3976. return true;
  3977. }
  3978. bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
  3979. upb_value *v) {
  3980. uint32_t hash = MurmurHash2(key, len, 0);
  3981. return lookup(&t->t, strkey2(key, len), v, hash, &streql);
  3982. }
  3983. bool upb_strtable_remove2(upb_strtable *t, const char *key, size_t len,
  3984. upb_value *val) {
  3985. uint32_t hash = MurmurHash2(key, strlen(key), 0);
  3986. upb_tabkey tabkey;
  3987. if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
  3988. free((void*)tabkey);
  3989. return true;
  3990. } else {
  3991. return false;
  3992. }
  3993. }
  3994. /* Iteration */
  3995. static const upb_tabent *str_tabent(const upb_strtable_iter *i) {
  3996. return &i->t->t.entries[i->index];
  3997. }
  3998. void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t) {
  3999. i->t = t;
  4000. i->index = begin(&t->t);
  4001. }
  4002. void upb_strtable_next(upb_strtable_iter *i) {
  4003. i->index = next(&i->t->t, i->index);
  4004. }
  4005. bool upb_strtable_done(const upb_strtable_iter *i) {
  4006. return i->index >= upb_table_size(&i->t->t) ||
  4007. upb_tabent_isempty(str_tabent(i));
  4008. }
  4009. const char *upb_strtable_iter_key(upb_strtable_iter *i) {
  4010. assert(!upb_strtable_done(i));
  4011. return upb_tabstr(str_tabent(i)->key, NULL);
  4012. }
  4013. size_t upb_strtable_iter_keylength(upb_strtable_iter *i) {
  4014. uint32_t len;
  4015. assert(!upb_strtable_done(i));
  4016. upb_tabstr(str_tabent(i)->key, &len);
  4017. return len;
  4018. }
  4019. upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
  4020. assert(!upb_strtable_done(i));
  4021. return _upb_value_val(str_tabent(i)->val.val, i->t->t.ctype);
  4022. }
  4023. void upb_strtable_iter_setdone(upb_strtable_iter *i) {
  4024. i->index = SIZE_MAX;
  4025. }
  4026. bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
  4027. const upb_strtable_iter *i2) {
  4028. if (upb_strtable_done(i1) && upb_strtable_done(i2))
  4029. return true;
  4030. return i1->t == i2->t && i1->index == i2->index;
  4031. }
  4032. /* upb_inttable ***************************************************************/
  4033. /* For inttables we use a hybrid structure where small keys are kept in an
  4034. * array and large keys are put in the hash table. */
  4035. static uint32_t inthash(upb_tabkey key) { return upb_inthash(key); }
  4036. static bool inteql(upb_tabkey k1, lookupkey_t k2) {
  4037. return k1 == k2.num;
  4038. }
  4039. static upb_tabval *mutable_array(upb_inttable *t) {
  4040. return (upb_tabval*)t->array;
  4041. }
  4042. static upb_tabval *inttable_val(upb_inttable *t, uintptr_t key) {
  4043. if (key < t->array_size) {
  4044. return upb_arrhas(t->array[key]) ? &(mutable_array(t)[key]) : NULL;
  4045. } else {
  4046. upb_tabent *e =
  4047. findentry_mutable(&t->t, intkey(key), upb_inthash(key), &inteql);
  4048. return e ? &e->val : NULL;
  4049. }
  4050. }
  4051. static const upb_tabval *inttable_val_const(const upb_inttable *t,
  4052. uintptr_t key) {
  4053. return inttable_val((upb_inttable*)t, key);
  4054. }
  4055. size_t upb_inttable_count(const upb_inttable *t) {
  4056. return t->t.count + t->array_count;
  4057. }
  4058. static void check(upb_inttable *t) {
  4059. UPB_UNUSED(t);
  4060. #if defined(UPB_DEBUG_TABLE) && !defined(NDEBUG)
  4061. {
  4062. /* This check is very expensive (makes inserts/deletes O(N)). */
  4063. size_t count = 0;
  4064. upb_inttable_iter i;
  4065. upb_inttable_begin(&i, t);
  4066. for(; !upb_inttable_done(&i); upb_inttable_next(&i), count++) {
  4067. assert(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
  4068. }
  4069. assert(count == upb_inttable_count(t));
  4070. }
  4071. #endif
  4072. }
  4073. bool upb_inttable_sizedinit(upb_inttable *t, upb_ctype_t ctype,
  4074. size_t asize, int hsize_lg2) {
  4075. size_t array_bytes;
  4076. if (!init(&t->t, ctype, hsize_lg2)) return false;
  4077. /* Always make the array part at least 1 long, so that we know key 0
  4078. * won't be in the hash part, which simplifies things. */
  4079. t->array_size = UPB_MAX(1, asize);
  4080. t->array_count = 0;
  4081. array_bytes = t->array_size * sizeof(upb_value);
  4082. t->array = malloc(array_bytes);
  4083. if (!t->array) {
  4084. uninit(&t->t);
  4085. return false;
  4086. }
  4087. memset(mutable_array(t), 0xff, array_bytes);
  4088. check(t);
  4089. return true;
  4090. }
  4091. bool upb_inttable_init(upb_inttable *t, upb_ctype_t ctype) {
  4092. return upb_inttable_sizedinit(t, ctype, 0, 4);
  4093. }
  4094. void upb_inttable_uninit(upb_inttable *t) {
  4095. uninit(&t->t);
  4096. free(mutable_array(t));
  4097. }
  4098. bool upb_inttable_insert(upb_inttable *t, uintptr_t key, upb_value val) {
  4099. /* XXX: Table can't store value (uint64_t)-1. Need to somehow statically
  4100. * guarantee that this is not necessary, or fix the limitation. */
  4101. upb_tabval tabval;
  4102. tabval.val = val.val;
  4103. UPB_UNUSED(tabval);
  4104. assert(upb_arrhas(tabval));
  4105. if (key < t->array_size) {
  4106. assert(!upb_arrhas(t->array[key]));
  4107. t->array_count++;
  4108. mutable_array(t)[key].val = val.val;
  4109. } else {
  4110. if (isfull(&t->t)) {
  4111. /* Need to resize the hash part, but we re-use the array part. */
  4112. size_t i;
  4113. upb_table new_table;
  4114. if (!init(&new_table, t->t.ctype, t->t.size_lg2 + 1))
  4115. return false;
  4116. for (i = begin(&t->t); i < upb_table_size(&t->t); i = next(&t->t, i)) {
  4117. const upb_tabent *e = &t->t.entries[i];
  4118. uint32_t hash;
  4119. upb_value v;
  4120. _upb_value_setval(&v, e->val.val, t->t.ctype);
  4121. hash = upb_inthash(e->key);
  4122. insert(&new_table, intkey(e->key), e->key, v, hash, &inthash, &inteql);
  4123. }
  4124. assert(t->t.count == new_table.count);
  4125. uninit(&t->t);
  4126. t->t = new_table;
  4127. }
  4128. insert(&t->t, intkey(key), key, val, upb_inthash(key), &inthash, &inteql);
  4129. }
  4130. check(t);
  4131. return true;
  4132. }
  4133. bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v) {
  4134. const upb_tabval *table_v = inttable_val_const(t, key);
  4135. if (!table_v) return false;
  4136. if (v) _upb_value_setval(v, table_v->val, t->t.ctype);
  4137. return true;
  4138. }
  4139. bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val) {
  4140. upb_tabval *table_v = inttable_val(t, key);
  4141. if (!table_v) return false;
  4142. table_v->val = val.val;
  4143. return true;
  4144. }
  4145. bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val) {
  4146. bool success;
  4147. if (key < t->array_size) {
  4148. if (upb_arrhas(t->array[key])) {
  4149. upb_tabval empty = UPB_TABVALUE_EMPTY_INIT;
  4150. t->array_count--;
  4151. if (val) {
  4152. _upb_value_setval(val, t->array[key].val, t->t.ctype);
  4153. }
  4154. mutable_array(t)[key] = empty;
  4155. success = true;
  4156. } else {
  4157. success = false;
  4158. }
  4159. } else {
  4160. upb_tabkey removed;
  4161. uint32_t hash = upb_inthash(key);
  4162. success = rm(&t->t, intkey(key), val, &removed, hash, &inteql);
  4163. }
  4164. check(t);
  4165. return success;
  4166. }
  4167. bool upb_inttable_push(upb_inttable *t, upb_value val) {
  4168. return upb_inttable_insert(t, upb_inttable_count(t), val);
  4169. }
  4170. upb_value upb_inttable_pop(upb_inttable *t) {
  4171. upb_value val;
  4172. bool ok = upb_inttable_remove(t, upb_inttable_count(t) - 1, &val);
  4173. UPB_ASSERT_VAR(ok, ok);
  4174. return val;
  4175. }
  4176. bool upb_inttable_insertptr(upb_inttable *t, const void *key, upb_value val) {
  4177. return upb_inttable_insert(t, (uintptr_t)key, val);
  4178. }
  4179. bool upb_inttable_lookupptr(const upb_inttable *t, const void *key,
  4180. upb_value *v) {
  4181. return upb_inttable_lookup(t, (uintptr_t)key, v);
  4182. }
  4183. bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val) {
  4184. return upb_inttable_remove(t, (uintptr_t)key, val);
  4185. }
  4186. void upb_inttable_compact(upb_inttable *t) {
  4187. /* A power-of-two histogram of the table keys. */
  4188. size_t counts[UPB_MAXARRSIZE + 1] = {0};
  4189. /* The max key in each bucket. */
  4190. uintptr_t max[UPB_MAXARRSIZE + 1] = {0};
  4191. upb_inttable_iter i;
  4192. size_t arr_count;
  4193. int size_lg2;
  4194. upb_inttable new_t;
  4195. upb_inttable_begin(&i, t);
  4196. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  4197. uintptr_t key = upb_inttable_iter_key(&i);
  4198. int bucket = log2ceil(key);
  4199. max[bucket] = UPB_MAX(max[bucket], key);
  4200. counts[bucket]++;
  4201. }
  4202. /* Find the largest power of two that satisfies the MIN_DENSITY
  4203. * definition (while actually having some keys). */
  4204. arr_count = upb_inttable_count(t);
  4205. for (size_lg2 = ARRAY_SIZE(counts) - 1; size_lg2 > 0; size_lg2--) {
  4206. if (counts[size_lg2] == 0) {
  4207. /* We can halve again without losing any entries. */
  4208. continue;
  4209. } else if (arr_count >= (1 << size_lg2) * MIN_DENSITY) {
  4210. break;
  4211. }
  4212. arr_count -= counts[size_lg2];
  4213. }
  4214. assert(arr_count <= upb_inttable_count(t));
  4215. {
  4216. /* Insert all elements into new, perfectly-sized table. */
  4217. size_t arr_size = max[size_lg2] + 1; /* +1 so arr[max] will fit. */
  4218. size_t hash_count = upb_inttable_count(t) - arr_count;
  4219. size_t hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
  4220. size_t hashsize_lg2 = log2ceil(hash_size);
  4221. upb_inttable_sizedinit(&new_t, t->t.ctype, arr_size, hashsize_lg2);
  4222. upb_inttable_begin(&i, t);
  4223. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  4224. uintptr_t k = upb_inttable_iter_key(&i);
  4225. upb_inttable_insert(&new_t, k, upb_inttable_iter_value(&i));
  4226. }
  4227. assert(new_t.array_size == arr_size);
  4228. assert(new_t.t.size_lg2 == hashsize_lg2);
  4229. }
  4230. upb_inttable_uninit(t);
  4231. *t = new_t;
  4232. }
  4233. /* Iteration. */
  4234. static const upb_tabent *int_tabent(const upb_inttable_iter *i) {
  4235. assert(!i->array_part);
  4236. return &i->t->t.entries[i->index];
  4237. }
  4238. static upb_tabval int_arrent(const upb_inttable_iter *i) {
  4239. assert(i->array_part);
  4240. return i->t->array[i->index];
  4241. }
  4242. void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t) {
  4243. i->t = t;
  4244. i->index = -1;
  4245. i->array_part = true;
  4246. upb_inttable_next(i);
  4247. }
  4248. void upb_inttable_next(upb_inttable_iter *iter) {
  4249. const upb_inttable *t = iter->t;
  4250. if (iter->array_part) {
  4251. while (++iter->index < t->array_size) {
  4252. if (upb_arrhas(int_arrent(iter))) {
  4253. return;
  4254. }
  4255. }
  4256. iter->array_part = false;
  4257. iter->index = begin(&t->t);
  4258. } else {
  4259. iter->index = next(&t->t, iter->index);
  4260. }
  4261. }
  4262. bool upb_inttable_done(const upb_inttable_iter *i) {
  4263. if (i->array_part) {
  4264. return i->index >= i->t->array_size ||
  4265. !upb_arrhas(int_arrent(i));
  4266. } else {
  4267. return i->index >= upb_table_size(&i->t->t) ||
  4268. upb_tabent_isempty(int_tabent(i));
  4269. }
  4270. }
  4271. uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i) {
  4272. assert(!upb_inttable_done(i));
  4273. return i->array_part ? i->index : int_tabent(i)->key;
  4274. }
  4275. upb_value upb_inttable_iter_value(const upb_inttable_iter *i) {
  4276. assert(!upb_inttable_done(i));
  4277. return _upb_value_val(
  4278. i->array_part ? i->t->array[i->index].val : int_tabent(i)->val.val,
  4279. i->t->t.ctype);
  4280. }
  4281. void upb_inttable_iter_setdone(upb_inttable_iter *i) {
  4282. i->index = SIZE_MAX;
  4283. i->array_part = false;
  4284. }
  4285. bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
  4286. const upb_inttable_iter *i2) {
  4287. if (upb_inttable_done(i1) && upb_inttable_done(i2))
  4288. return true;
  4289. return i1->t == i2->t && i1->index == i2->index &&
  4290. i1->array_part == i2->array_part;
  4291. }
  4292. #ifdef UPB_UNALIGNED_READS_OK
  4293. /* -----------------------------------------------------------------------------
  4294. * MurmurHash2, by Austin Appleby (released as public domain).
  4295. * Reformatted and C99-ified by Joshua Haberman.
  4296. * Note - This code makes a few assumptions about how your machine behaves -
  4297. * 1. We can read a 4-byte value from any address without crashing
  4298. * 2. sizeof(int) == 4 (in upb this limitation is removed by using uint32_t
  4299. * And it has a few limitations -
  4300. * 1. It will not work incrementally.
  4301. * 2. It will not produce the same results on little-endian and big-endian
  4302. * machines. */
  4303. uint32_t MurmurHash2(const void *key, size_t len, uint32_t seed) {
  4304. /* 'm' and 'r' are mixing constants generated offline.
  4305. * They're not really 'magic', they just happen to work well. */
  4306. const uint32_t m = 0x5bd1e995;
  4307. const int32_t r = 24;
  4308. /* Initialize the hash to a 'random' value */
  4309. uint32_t h = seed ^ len;
  4310. /* Mix 4 bytes at a time into the hash */
  4311. const uint8_t * data = (const uint8_t *)key;
  4312. while(len >= 4) {
  4313. uint32_t k = *(uint32_t *)data;
  4314. k *= m;
  4315. k ^= k >> r;
  4316. k *= m;
  4317. h *= m;
  4318. h ^= k;
  4319. data += 4;
  4320. len -= 4;
  4321. }
  4322. /* Handle the last few bytes of the input array */
  4323. switch(len) {
  4324. case 3: h ^= data[2] << 16;
  4325. case 2: h ^= data[1] << 8;
  4326. case 1: h ^= data[0]; h *= m;
  4327. };
  4328. /* Do a few final mixes of the hash to ensure the last few
  4329. * bytes are well-incorporated. */
  4330. h ^= h >> 13;
  4331. h *= m;
  4332. h ^= h >> 15;
  4333. return h;
  4334. }
  4335. #else /* !UPB_UNALIGNED_READS_OK */
  4336. /* -----------------------------------------------------------------------------
  4337. * MurmurHashAligned2, by Austin Appleby
  4338. * Same algorithm as MurmurHash2, but only does aligned reads - should be safer
  4339. * on certain platforms.
  4340. * Performance will be lower than MurmurHash2 */
  4341. #define MIX(h,k,m) { k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; }
  4342. uint32_t MurmurHash2(const void * key, size_t len, uint32_t seed) {
  4343. const uint32_t m = 0x5bd1e995;
  4344. const int32_t r = 24;
  4345. const uint8_t * data = (const uint8_t *)key;
  4346. uint32_t h = seed ^ len;
  4347. uint8_t align = (uintptr_t)data & 3;
  4348. if(align && (len >= 4)) {
  4349. /* Pre-load the temp registers */
  4350. uint32_t t = 0, d = 0;
  4351. int32_t sl;
  4352. int32_t sr;
  4353. switch(align) {
  4354. case 1: t |= data[2] << 16;
  4355. case 2: t |= data[1] << 8;
  4356. case 3: t |= data[0];
  4357. }
  4358. t <<= (8 * align);
  4359. data += 4-align;
  4360. len -= 4-align;
  4361. sl = 8 * (4-align);
  4362. sr = 8 * align;
  4363. /* Mix */
  4364. while(len >= 4) {
  4365. uint32_t k;
  4366. d = *(uint32_t *)data;
  4367. t = (t >> sr) | (d << sl);
  4368. k = t;
  4369. MIX(h,k,m);
  4370. t = d;
  4371. data += 4;
  4372. len -= 4;
  4373. }
  4374. /* Handle leftover data in temp registers */
  4375. d = 0;
  4376. if(len >= align) {
  4377. uint32_t k;
  4378. switch(align) {
  4379. case 3: d |= data[2] << 16;
  4380. case 2: d |= data[1] << 8;
  4381. case 1: d |= data[0];
  4382. }
  4383. k = (t >> sr) | (d << sl);
  4384. MIX(h,k,m);
  4385. data += align;
  4386. len -= align;
  4387. /* ----------
  4388. * Handle tail bytes */
  4389. switch(len) {
  4390. case 3: h ^= data[2] << 16;
  4391. case 2: h ^= data[1] << 8;
  4392. case 1: h ^= data[0]; h *= m;
  4393. };
  4394. } else {
  4395. switch(len) {
  4396. case 3: d |= data[2] << 16;
  4397. case 2: d |= data[1] << 8;
  4398. case 1: d |= data[0];
  4399. case 0: h ^= (t >> sr) | (d << sl); h *= m;
  4400. }
  4401. }
  4402. h ^= h >> 13;
  4403. h *= m;
  4404. h ^= h >> 15;
  4405. return h;
  4406. } else {
  4407. while(len >= 4) {
  4408. uint32_t k = *(uint32_t *)data;
  4409. MIX(h,k,m);
  4410. data += 4;
  4411. len -= 4;
  4412. }
  4413. /* ----------
  4414. * Handle tail bytes */
  4415. switch(len) {
  4416. case 3: h ^= data[2] << 16;
  4417. case 2: h ^= data[1] << 8;
  4418. case 1: h ^= data[0]; h *= m;
  4419. };
  4420. h ^= h >> 13;
  4421. h *= m;
  4422. h ^= h >> 15;
  4423. return h;
  4424. }
  4425. }
  4426. #undef MIX
  4427. #endif /* UPB_UNALIGNED_READS_OK */
  4428. #include <errno.h>
  4429. #include <stdarg.h>
  4430. #include <stddef.h>
  4431. #include <stdint.h>
  4432. #include <stdio.h>
  4433. #include <stdlib.h>
  4434. #include <string.h>
  4435. bool upb_dumptostderr(void *closure, const upb_status* status) {
  4436. UPB_UNUSED(closure);
  4437. fprintf(stderr, "%s\n", upb_status_errmsg(status));
  4438. return false;
  4439. }
  4440. /* Guarantee null-termination and provide ellipsis truncation.
  4441. * It may be tempting to "optimize" this by initializing these final
  4442. * four bytes up-front and then being careful never to overwrite them,
  4443. * this is safer and simpler. */
  4444. static void nullz(upb_status *status) {
  4445. const char *ellipsis = "...";
  4446. size_t len = strlen(ellipsis);
  4447. assert(sizeof(status->msg) > len);
  4448. memcpy(status->msg + sizeof(status->msg) - len, ellipsis, len);
  4449. }
  4450. void upb_status_clear(upb_status *status) {
  4451. if (!status) return;
  4452. status->ok_ = true;
  4453. status->code_ = 0;
  4454. status->msg[0] = '\0';
  4455. }
  4456. bool upb_ok(const upb_status *status) { return status->ok_; }
  4457. upb_errorspace *upb_status_errspace(const upb_status *status) {
  4458. return status->error_space_;
  4459. }
  4460. int upb_status_errcode(const upb_status *status) { return status->code_; }
  4461. const char *upb_status_errmsg(const upb_status *status) { return status->msg; }
  4462. void upb_status_seterrmsg(upb_status *status, const char *msg) {
  4463. if (!status) return;
  4464. status->ok_ = false;
  4465. strncpy(status->msg, msg, sizeof(status->msg));
  4466. nullz(status);
  4467. }
  4468. void upb_status_seterrf(upb_status *status, const char *fmt, ...) {
  4469. va_list args;
  4470. va_start(args, fmt);
  4471. upb_status_vseterrf(status, fmt, args);
  4472. va_end(args);
  4473. }
  4474. void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args) {
  4475. if (!status) return;
  4476. status->ok_ = false;
  4477. _upb_vsnprintf(status->msg, sizeof(status->msg), fmt, args);
  4478. nullz(status);
  4479. }
  4480. void upb_status_seterrcode(upb_status *status, upb_errorspace *space,
  4481. int code) {
  4482. if (!status) return;
  4483. status->ok_ = false;
  4484. status->error_space_ = space;
  4485. status->code_ = code;
  4486. space->set_message(status, code);
  4487. }
  4488. void upb_status_copy(upb_status *to, const upb_status *from) {
  4489. if (!to) return;
  4490. *to = *from;
  4491. }
  4492. /* This file was generated by upbc (the upb compiler).
  4493. * Do not edit -- your changes will be discarded when the file is
  4494. * regenerated. */
  4495. #include <assert.h>
  4496. static const upb_msgdef msgs[22];
  4497. static const upb_fielddef fields[105];
  4498. static const upb_enumdef enums[5];
  4499. static const upb_tabent strentries[236];
  4500. static const upb_tabent intentries[18];
  4501. static const upb_tabval arrays[184];
  4502. #ifdef UPB_DEBUG_REFS
  4503. static upb_inttable reftables[264];
  4504. #endif
  4505. static const upb_msgdef msgs[22] = {
  4506. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto", 40, 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]),&reftables[0], &reftables[1]),
  4507. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ExtensionRange", 4, 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]),&reftables[2], &reftables[3]),
  4508. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ReservedRange", 4, 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]),&reftables[4], &reftables[5]),
  4509. UPB_MSGDEF_INIT("google.protobuf.EnumDescriptorProto", 11, 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]),&reftables[6], &reftables[7]),
  4510. UPB_MSGDEF_INIT("google.protobuf.EnumOptions", 8, 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]),&reftables[8], &reftables[9]),
  4511. UPB_MSGDEF_INIT("google.protobuf.EnumValueDescriptorProto", 8, 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]),&reftables[10], &reftables[11]),
  4512. UPB_MSGDEF_INIT("google.protobuf.EnumValueOptions", 7, 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]),&reftables[12], &reftables[13]),
  4513. UPB_MSGDEF_INIT("google.protobuf.FieldDescriptorProto", 23, 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]),&reftables[14], &reftables[15]),
  4514. UPB_MSGDEF_INIT("google.protobuf.FieldOptions", 12, 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]),&reftables[16], &reftables[17]),
  4515. UPB_MSGDEF_INIT("google.protobuf.FileDescriptorProto", 42, 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]),&reftables[18], &reftables[19]),
  4516. UPB_MSGDEF_INIT("google.protobuf.FileDescriptorSet", 6, 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]),&reftables[20], &reftables[21]),
  4517. UPB_MSGDEF_INIT("google.protobuf.FileOptions", 31, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[6], &arrays[68], 39, 15), UPB_STRTABLE_INIT(16, 31, UPB_CTYPE_PTR, 5, &strentries[92]),&reftables[22], &reftables[23]),
  4518. UPB_MSGDEF_INIT("google.protobuf.MessageOptions", 10, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[8], &arrays[107], 8, 4), UPB_STRTABLE_INIT(5, 7, UPB_CTYPE_PTR, 3, &strentries[124]),&reftables[24], &reftables[25]),
  4519. UPB_MSGDEF_INIT("google.protobuf.MethodDescriptorProto", 15, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[115], 7, 6), UPB_STRTABLE_INIT(6, 7, UPB_CTYPE_PTR, 3, &strentries[132]),&reftables[26], &reftables[27]),
  4520. UPB_MSGDEF_INIT("google.protobuf.MethodOptions", 7, 1, UPB_INTTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &intentries[10], &arrays[122], 1, 0), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[140]),&reftables[28], &reftables[29]),
  4521. UPB_MSGDEF_INIT("google.protobuf.OneofDescriptorProto", 5, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[123], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[144]),&reftables[30], &reftables[31]),
  4522. UPB_MSGDEF_INIT("google.protobuf.ServiceDescriptorProto", 11, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[125], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[148]),&reftables[32], &reftables[33]),
  4523. UPB_MSGDEF_INIT("google.protobuf.ServiceOptions", 7, 1, UPB_INTTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &intentries[14], &arrays[129], 1, 0), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[152]),&reftables[34], &reftables[35]),
  4524. UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo", 6, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[130], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[156]),&reftables[36], &reftables[37]),
  4525. UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo.Location", 19, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[132], 7, 5), UPB_STRTABLE_INIT(5, 7, UPB_CTYPE_PTR, 3, &strentries[160]),&reftables[38], &reftables[39]),
  4526. UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption", 18, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[139], 9, 7), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[168]),&reftables[40], &reftables[41]),
  4527. UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption.NamePart", 6, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[148], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[184]),&reftables[42], &reftables[43]),
  4528. };
  4529. static const upb_fielddef fields[105] = {
  4530. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "aggregate_value", 8, &msgs[20], NULL, 15, 6, {0},&reftables[44], &reftables[45]),
  4531. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "allow_alias", 2, &msgs[4], NULL, 6, 1, {0},&reftables[46], &reftables[47]),
  4532. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_enable_arenas", 31, &msgs[11], NULL, 23, 12, {0},&reftables[48], &reftables[49]),
  4533. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_generic_services", 16, &msgs[11], NULL, 17, 6, {0},&reftables[50], &reftables[51]),
  4534. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "client_streaming", 5, &msgs[13], NULL, 13, 4, {0},&reftables[52], &reftables[53]),
  4535. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "csharp_namespace", 37, &msgs[11], NULL, 27, 14, {0},&reftables[54], &reftables[55]),
  4536. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "ctype", 1, &msgs[8], (const upb_def*)(&enums[2]), 6, 1, {0},&reftables[56], &reftables[57]),
  4537. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "default_value", 7, &msgs[7], NULL, 16, 7, {0},&reftables[58], &reftables[59]),
  4538. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "dependency", 3, &msgs[9], NULL, 30, 8, {0},&reftables[60], &reftables[61]),
  4539. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[12], NULL, 8, 3, {0},&reftables[62], &reftables[63]),
  4540. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[8], NULL, 8, 3, {0},&reftables[64], &reftables[65]),
  4541. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 33, &msgs[14], NULL, 6, 1, {0},&reftables[66], &reftables[67]),
  4542. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 23, &msgs[11], NULL, 21, 10, {0},&reftables[68], &reftables[69]),
  4543. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[4], NULL, 7, 2, {0},&reftables[70], &reftables[71]),
  4544. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 33, &msgs[17], NULL, 6, 1, {0},&reftables[72], &reftables[73]),
  4545. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 1, &msgs[6], NULL, 6, 1, {0},&reftables[74], &reftables[75]),
  4546. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_DOUBLE, 0, false, false, false, false, "double_value", 6, &msgs[20], NULL, 11, 4, {0},&reftables[76], &reftables[77]),
  4547. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "end", 2, &msgs[2], NULL, 3, 1, {0},&reftables[78], &reftables[79]),
  4548. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "end", 2, &msgs[1], NULL, 3, 1, {0},&reftables[80], &reftables[81]),
  4549. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 4, &msgs[0], (const upb_def*)(&msgs[3]), 18, 2, {0},&reftables[82], &reftables[83]),
  4550. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 5, &msgs[9], (const upb_def*)(&msgs[3]), 13, 1, {0},&reftables[84], &reftables[85]),
  4551. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "extendee", 2, &msgs[7], NULL, 7, 2, {0},&reftables[86], &reftables[87]),
  4552. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 6, &msgs[0], (const upb_def*)(&msgs[7]), 24, 4, {0},&reftables[88], &reftables[89]),
  4553. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 7, &msgs[9], (const upb_def*)(&msgs[7]), 19, 3, {0},&reftables[90], &reftables[91]),
  4554. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension_range", 5, &msgs[0], (const upb_def*)(&msgs[1]), 21, 3, {0},&reftables[92], &reftables[93]),
  4555. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "field", 2, &msgs[0], (const upb_def*)(&msgs[7]), 12, 0, {0},&reftables[94], &reftables[95]),
  4556. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "file", 1, &msgs[10], (const upb_def*)(&msgs[9]), 5, 0, {0},&reftables[96], &reftables[97]),
  4557. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "go_package", 11, &msgs[11], NULL, 14, 5, {0},&reftables[98], &reftables[99]),
  4558. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "identifier_value", 3, &msgs[20], NULL, 6, 1, {0},&reftables[100], &reftables[101]),
  4559. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "input_type", 2, &msgs[13], NULL, 7, 2, {0},&reftables[102], &reftables[103]),
  4560. UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_BOOL, 0, false, false, false, false, "is_extension", 2, &msgs[21], NULL, 5, 1, {0},&reftables[104], &reftables[105]),
  4561. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generate_equals_and_hash", 20, &msgs[11], NULL, 20, 9, {0},&reftables[106], &reftables[107]),
  4562. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generic_services", 17, &msgs[11], NULL, 18, 7, {0},&reftables[108], &reftables[109]),
  4563. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_multiple_files", 10, &msgs[11], NULL, 13, 4, {0},&reftables[110], &reftables[111]),
  4564. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_outer_classname", 8, &msgs[11], NULL, 9, 2, {0},&reftables[112], &reftables[113]),
  4565. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_package", 1, &msgs[11], NULL, 6, 1, {0},&reftables[114], &reftables[115]),
  4566. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_string_check_utf8", 27, &msgs[11], NULL, 22, 11, {0},&reftables[116], &reftables[117]),
  4567. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "javanano_use_deprecated_package", 38, &msgs[11], NULL, 30, 15, {0},&reftables[118], &reftables[119]),
  4568. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "json_name", 10, &msgs[7], NULL, 20, 9, {0},&reftables[120], &reftables[121]),
  4569. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "jstype", 6, &msgs[8], (const upb_def*)(&enums[3]), 10, 5, {0},&reftables[122], &reftables[123]),
  4570. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "label", 4, &msgs[7], (const upb_def*)(&enums[0]), 11, 4, {0},&reftables[124], &reftables[125]),
  4571. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "lazy", 5, &msgs[8], NULL, 9, 4, {0},&reftables[126], &reftables[127]),
  4572. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "leading_comments", 3, &msgs[19], NULL, 8, 2, {0},&reftables[128], &reftables[129]),
  4573. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "leading_detached_comments", 6, &msgs[19], NULL, 16, 4, {0},&reftables[130], &reftables[131]),
  4574. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "location", 1, &msgs[18], (const upb_def*)(&msgs[19]), 5, 0, {0},&reftables[132], &reftables[133]),
  4575. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "map_entry", 7, &msgs[12], NULL, 9, 4, {0},&reftables[134], &reftables[135]),
  4576. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "message_set_wire_format", 1, &msgs[12], NULL, 6, 1, {0},&reftables[136], &reftables[137]),
  4577. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "message_type", 4, &msgs[9], (const upb_def*)(&msgs[0]), 10, 0, {0},&reftables[138], &reftables[139]),
  4578. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "method", 2, &msgs[16], (const upb_def*)(&msgs[13]), 6, 0, {0},&reftables[140], &reftables[141]),
  4579. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[3], NULL, 8, 2, {0},&reftables[142], &reftables[143]),
  4580. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[15], NULL, 2, 0, {0},&reftables[144], &reftables[145]),
  4581. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "name", 2, &msgs[20], (const upb_def*)(&msgs[21]), 5, 0, {0},&reftables[146], &reftables[147]),
  4582. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[0], NULL, 32, 8, {0},&reftables[148], &reftables[149]),
  4583. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[5], NULL, 4, 1, {0},&reftables[150], &reftables[151]),
  4584. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[9], NULL, 22, 6, {0},&reftables[152], &reftables[153]),
  4585. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[7], NULL, 4, 1, {0},&reftables[154], &reftables[155]),
  4586. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[13], NULL, 4, 1, {0},&reftables[156], &reftables[157]),
  4587. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[16], NULL, 8, 2, {0},&reftables[158], &reftables[159]),
  4588. UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_STRING, 0, false, false, false, false, "name_part", 1, &msgs[21], NULL, 2, 0, {0},&reftables[160], &reftables[161]),
  4589. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT64, UPB_INTFMT_VARIABLE, false, false, false, false, "negative_int_value", 5, &msgs[20], NULL, 10, 3, {0},&reftables[162], &reftables[163]),
  4590. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "nested_type", 3, &msgs[0], (const upb_def*)(&msgs[0]), 15, 1, {0},&reftables[164], &reftables[165]),
  4591. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "no_standard_descriptor_accessor", 2, &msgs[12], NULL, 7, 2, {0},&reftables[166], &reftables[167]),
  4592. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 2, &msgs[5], NULL, 7, 2, {0},&reftables[168], &reftables[169]),
  4593. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 3, &msgs[7], NULL, 10, 3, {0},&reftables[170], &reftables[171]),
  4594. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "objc_class_prefix", 36, &msgs[11], NULL, 24, 13, {0},&reftables[172], &reftables[173]),
  4595. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "oneof_decl", 8, &msgs[0], (const upb_def*)(&msgs[15]), 28, 6, {0},&reftables[174], &reftables[175]),
  4596. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "oneof_index", 9, &msgs[7], NULL, 19, 8, {0},&reftables[176], &reftables[177]),
  4597. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "optimize_for", 9, &msgs[11], (const upb_def*)(&enums[4]), 12, 3, {0},&reftables[178], &reftables[179]),
  4598. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 7, &msgs[0], (const upb_def*)(&msgs[12]), 25, 5, {0},&reftables[180], &reftables[181]),
  4599. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[9], (const upb_def*)(&msgs[11]), 20, 4, {0},&reftables[182], &reftables[183]),
  4600. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 4, &msgs[13], (const upb_def*)(&msgs[14]), 3, 0, {0},&reftables[184], &reftables[185]),
  4601. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[7], (const upb_def*)(&msgs[8]), 3, 0, {0},&reftables[186], &reftables[187]),
  4602. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[16], (const upb_def*)(&msgs[17]), 7, 1, {0},&reftables[188], &reftables[189]),
  4603. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[5], (const upb_def*)(&msgs[6]), 3, 0, {0},&reftables[190], &reftables[191]),
  4604. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[3], (const upb_def*)(&msgs[4]), 7, 1, {0},&reftables[192], &reftables[193]),
  4605. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "output_type", 3, &msgs[13], NULL, 10, 3, {0},&reftables[194], &reftables[195]),
  4606. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "package", 2, &msgs[9], NULL, 25, 7, {0},&reftables[196], &reftables[197]),
  4607. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "packed", 2, &msgs[8], NULL, 7, 2, {0},&reftables[198], &reftables[199]),
  4608. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "path", 1, &msgs[19], NULL, 4, 0, {0},&reftables[200], &reftables[201]),
  4609. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_UINT64, UPB_INTFMT_VARIABLE, false, false, false, false, "positive_int_value", 4, &msgs[20], NULL, 9, 2, {0},&reftables[202], &reftables[203]),
  4610. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "public_dependency", 10, &msgs[9], NULL, 35, 9, {0},&reftables[204], &reftables[205]),
  4611. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "py_generic_services", 18, &msgs[11], NULL, 19, 8, {0},&reftables[206], &reftables[207]),
  4612. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "reserved_name", 10, &msgs[0], NULL, 37, 9, {0},&reftables[208], &reftables[209]),
  4613. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "reserved_range", 9, &msgs[0], (const upb_def*)(&msgs[2]), 31, 7, {0},&reftables[210], &reftables[211]),
  4614. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "server_streaming", 6, &msgs[13], NULL, 14, 5, {0},&reftables[212], &reftables[213]),
  4615. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "service", 6, &msgs[9], (const upb_def*)(&msgs[16]), 16, 2, {0},&reftables[214], &reftables[215]),
  4616. 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]), 21, 5, {0},&reftables[216], &reftables[217]),
  4617. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "span", 2, &msgs[19], NULL, 7, 1, {0},&reftables[218], &reftables[219]),
  4618. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "start", 1, &msgs[2], NULL, 2, 0, {0},&reftables[220], &reftables[221]),
  4619. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "start", 1, &msgs[1], NULL, 2, 0, {0},&reftables[222], &reftables[223]),
  4620. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BYTES, 0, false, false, false, false, "string_value", 7, &msgs[20], NULL, 12, 5, {0},&reftables[224], &reftables[225]),
  4621. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "syntax", 12, &msgs[9], NULL, 39, 11, {0},&reftables[226], &reftables[227]),
  4622. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "trailing_comments", 4, &msgs[19], NULL, 11, 3, {0},&reftables[228], &reftables[229]),
  4623. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "type", 5, &msgs[7], (const upb_def*)(&enums[1]), 12, 5, {0},&reftables[230], &reftables[231]),
  4624. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "type_name", 6, &msgs[7], NULL, 13, 6, {0},&reftables[232], &reftables[233]),
  4625. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[11], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[234], &reftables[235]),
  4626. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[12], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[236], &reftables[237]),
  4627. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[6], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[238], &reftables[239]),
  4628. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[4], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[240], &reftables[241]),
  4629. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[8], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[242], &reftables[243]),
  4630. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[14], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[244], &reftables[245]),
  4631. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[17], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[246], &reftables[247]),
  4632. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "value", 2, &msgs[3], (const upb_def*)(&msgs[5]), 6, 0, {0},&reftables[248], &reftables[249]),
  4633. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "weak", 10, &msgs[8], NULL, 11, 6, {0},&reftables[250], &reftables[251]),
  4634. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "weak_dependency", 11, &msgs[9], NULL, 38, 10, {0},&reftables[252], &reftables[253]),
  4635. };
  4636. static const upb_enumdef enums[5] = {
  4637. 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[151], 4, 3), 0, &reftables[254], &reftables[255]),
  4638. 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[155], 19, 18), 0, &reftables[256], &reftables[257]),
  4639. 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[174], 3, 3), 0, &reftables[258], &reftables[259]),
  4640. 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[177], 3, 3), 0, &reftables[260], &reftables[261]),
  4641. 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[180], 4, 3), 0, &reftables[262], &reftables[263]),
  4642. };
  4643. static const upb_tabent strentries[236] = {
  4644. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "extension"), UPB_TABVALUE_PTR_INIT(&fields[22]), NULL},
  4645. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4646. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "reserved_name"), UPB_TABVALUE_PTR_INIT(&fields[82]), NULL},
  4647. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[52]), NULL},
  4648. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4649. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4650. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4651. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "field"), UPB_TABVALUE_PTR_INIT(&fields[25]), &strentries[12]},
  4652. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "extension_range"), UPB_TABVALUE_PTR_INIT(&fields[24]), &strentries[14]},
  4653. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4654. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "nested_type"), UPB_TABVALUE_PTR_INIT(&fields[60]), NULL},
  4655. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4656. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "reserved_range"), UPB_TABVALUE_PTR_INIT(&fields[83]), NULL},
  4657. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[68]), NULL},
  4658. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "oneof_decl"), UPB_TABVALUE_PTR_INIT(&fields[65]), NULL},
  4659. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[19]), &strentries[13]},
  4660. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[89]), NULL},
  4661. {UPB_TABKEY_STR("\003", "\000", "\000", "\000", "end"), UPB_TABVALUE_PTR_INIT(&fields[18]), NULL},
  4662. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4663. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4664. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[88]), NULL},
  4665. {UPB_TABKEY_STR("\003", "\000", "\000", "\000", "end"), UPB_TABVALUE_PTR_INIT(&fields[17]), NULL},
  4666. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4667. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4668. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4669. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "value"), UPB_TABVALUE_PTR_INIT(&fields[102]), NULL},
  4670. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[74]), NULL},
  4671. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[49]), &strentries[26]},
  4672. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[98]), NULL},
  4673. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[13]), NULL},
  4674. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "allow_alias"), UPB_TABVALUE_PTR_INIT(&fields[1]), NULL},
  4675. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4676. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[62]), NULL},
  4677. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4678. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[73]), NULL},
  4679. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[53]), &strentries[34]},
  4680. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[97]), NULL},
  4681. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[15]), NULL},
  4682. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4683. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4684. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "oneof_index"), UPB_TABVALUE_PTR_INIT(&fields[66]), NULL},
  4685. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "label"), UPB_TABVALUE_PTR_INIT(&fields[40]), NULL},
  4686. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4687. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[55]), NULL},
  4688. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4689. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4690. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4691. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4692. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[63]), &strentries[53]},
  4693. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4694. {UPB_TABKEY_STR("\010", "\000", "\000", "\000", "extendee"), UPB_TABVALUE_PTR_INIT(&fields[21]), NULL},
  4695. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "type_name"), UPB_TABVALUE_PTR_INIT(&fields[94]), NULL},
  4696. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "json_name"), UPB_TABVALUE_PTR_INIT(&fields[38]), NULL},
  4697. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "type"), UPB_TABVALUE_PTR_INIT(&fields[93]), &strentries[50]},
  4698. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "default_value"), UPB_TABVALUE_PTR_INIT(&fields[7]), NULL},
  4699. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[71]), NULL},
  4700. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[99]), NULL},
  4701. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4702. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "weak"), UPB_TABVALUE_PTR_INIT(&fields[103]), NULL},
  4703. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4704. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4705. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4706. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4707. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "packed"), UPB_TABVALUE_PTR_INIT(&fields[77]), NULL},
  4708. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "lazy"), UPB_TABVALUE_PTR_INIT(&fields[41]), NULL},
  4709. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4710. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "ctype"), UPB_TABVALUE_PTR_INIT(&fields[6]), NULL},
  4711. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4712. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "jstype"), UPB_TABVALUE_PTR_INIT(&fields[39]), NULL},
  4713. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[10]), NULL},
  4714. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4715. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4716. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "extension"), UPB_TABVALUE_PTR_INIT(&fields[23]), NULL},
  4717. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "weak_dependency"), UPB_TABVALUE_PTR_INIT(&fields[104]), NULL},
  4718. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4719. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[54]), NULL},
  4720. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "service"), UPB_TABVALUE_PTR_INIT(&fields[85]), NULL},
  4721. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4722. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "source_code_info"), UPB_TABVALUE_PTR_INIT(&fields[86]), NULL},
  4723. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4724. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4725. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "syntax"), UPB_TABVALUE_PTR_INIT(&fields[91]), NULL},
  4726. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "dependency"), UPB_TABVALUE_PTR_INIT(&fields[8]), NULL},
  4727. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "message_type"), UPB_TABVALUE_PTR_INIT(&fields[47]), NULL},
  4728. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "package"), UPB_TABVALUE_PTR_INIT(&fields[76]), NULL},
  4729. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[69]), &strentries[86]},
  4730. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[20]), NULL},
  4731. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "public_dependency"), UPB_TABVALUE_PTR_INIT(&fields[80]), &strentries[85]},
  4732. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4733. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "file"), UPB_TABVALUE_PTR_INIT(&fields[26]), NULL},
  4734. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4735. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4736. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4737. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4738. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "cc_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[3]), NULL},
  4739. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "csharp_namespace"), UPB_TABVALUE_PTR_INIT(&fields[5]), NULL},
  4740. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4741. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4742. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4743. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4744. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4745. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4746. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4747. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "go_package"), UPB_TABVALUE_PTR_INIT(&fields[27]), NULL},
  4748. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "java_package"), UPB_TABVALUE_PTR_INIT(&fields[35]), &strentries[120]},
  4749. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4750. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4751. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "java_outer_classname"), UPB_TABVALUE_PTR_INIT(&fields[34]), NULL},
  4752. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[95]), NULL},
  4753. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4754. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4755. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4756. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "java_multiple_files"), UPB_TABVALUE_PTR_INIT(&fields[33]), &strentries[117]},
  4757. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4758. {UPB_TABKEY_STR("\025", "\000", "\000", "\000", "java_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[32]), &strentries[118]},
  4759. {UPB_TABKEY_STR("\035", "\000", "\000", "\000", "java_generate_equals_and_hash"), UPB_TABVALUE_PTR_INIT(&fields[31]), NULL},
  4760. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4761. {UPB_TABKEY_STR("\037", "\000", "\000", "\000", "javanano_use_deprecated_package"), UPB_TABVALUE_PTR_INIT(&fields[37]), &strentries[123]},
  4762. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "py_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[81]), NULL},
  4763. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "optimize_for"), UPB_TABVALUE_PTR_INIT(&fields[67]), NULL},
  4764. {UPB_TABKEY_STR("\026", "\000", "\000", "\000", "java_string_check_utf8"), UPB_TABVALUE_PTR_INIT(&fields[36]), NULL},
  4765. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[12]), &strentries[119]},
  4766. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "objc_class_prefix"), UPB_TABVALUE_PTR_INIT(&fields[64]), NULL},
  4767. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "cc_enable_arenas"), UPB_TABVALUE_PTR_INIT(&fields[2]), NULL},
  4768. {UPB_TABKEY_STR("\027", "\000", "\000", "\000", "message_set_wire_format"), UPB_TABVALUE_PTR_INIT(&fields[46]), &strentries[128]},
  4769. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4770. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4771. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4772. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[96]), NULL},
  4773. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[9]), NULL},
  4774. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "map_entry"), UPB_TABVALUE_PTR_INIT(&fields[45]), NULL},
  4775. {UPB_TABKEY_STR("\037", "\000", "\000", "\000", "no_standard_descriptor_accessor"), UPB_TABVALUE_PTR_INIT(&fields[61]), NULL},
  4776. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4777. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "client_streaming"), UPB_TABVALUE_PTR_INIT(&fields[4]), NULL},
  4778. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "server_streaming"), UPB_TABVALUE_PTR_INIT(&fields[84]), NULL},
  4779. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[56]), NULL},
  4780. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "input_type"), UPB_TABVALUE_PTR_INIT(&fields[29]), NULL},
  4781. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4782. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "output_type"), UPB_TABVALUE_PTR_INIT(&fields[75]), NULL},
  4783. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[70]), NULL},
  4784. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[100]), NULL},
  4785. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[11]), NULL},
  4786. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4787. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4788. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4789. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4790. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4791. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[50]), NULL},
  4792. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4793. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[72]), &strentries[150]},
  4794. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "method"), UPB_TABVALUE_PTR_INIT(&fields[48]), NULL},
  4795. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[57]), &strentries[149]},
  4796. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[101]), NULL},
  4797. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[14]), NULL},
  4798. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4799. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4800. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4801. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4802. {UPB_TABKEY_STR("\010", "\000", "\000", "\000", "location"), UPB_TABVALUE_PTR_INIT(&fields[44]), NULL},
  4803. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4804. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4805. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4806. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4807. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "span"), UPB_TABVALUE_PTR_INIT(&fields[87]), &strentries[167]},
  4808. {UPB_TABKEY_STR("\031", "\000", "\000", "\000", "leading_detached_comments"), UPB_TABVALUE_PTR_INIT(&fields[43]), &strentries[165]},
  4809. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "trailing_comments"), UPB_TABVALUE_PTR_INIT(&fields[92]), NULL},
  4810. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "leading_comments"), UPB_TABVALUE_PTR_INIT(&fields[42]), &strentries[164]},
  4811. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "path"), UPB_TABVALUE_PTR_INIT(&fields[78]), NULL},
  4812. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "double_value"), UPB_TABVALUE_PTR_INIT(&fields[16]), NULL},
  4813. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4814. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4815. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[51]), NULL},
  4816. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4817. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4818. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4819. {UPB_TABKEY_STR("\022", "\000", "\000", "\000", "negative_int_value"), UPB_TABVALUE_PTR_INIT(&fields[59]), NULL},
  4820. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "aggregate_value"), UPB_TABVALUE_PTR_INIT(&fields[0]), NULL},
  4821. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4822. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4823. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4824. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4825. {UPB_TABKEY_STR("\022", "\000", "\000", "\000", "positive_int_value"), UPB_TABVALUE_PTR_INIT(&fields[79]), NULL},
  4826. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "identifier_value"), UPB_TABVALUE_PTR_INIT(&fields[28]), NULL},
  4827. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "string_value"), UPB_TABVALUE_PTR_INIT(&fields[90]), &strentries[182]},
  4828. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4829. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4830. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "is_extension"), UPB_TABVALUE_PTR_INIT(&fields[30]), NULL},
  4831. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "name_part"), UPB_TABVALUE_PTR_INIT(&fields[58]), NULL},
  4832. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_REQUIRED"), UPB_TABVALUE_INT_INIT(2), &strentries[190]},
  4833. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4834. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_REPEATED"), UPB_TABVALUE_INT_INIT(3), NULL},
  4835. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_OPTIONAL"), UPB_TABVALUE_INT_INIT(1), NULL},
  4836. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_FIXED64"), UPB_TABVALUE_INT_INIT(6), NULL},
  4837. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4838. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4839. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4840. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4841. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_STRING"), UPB_TABVALUE_INT_INIT(9), NULL},
  4842. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_FLOAT"), UPB_TABVALUE_INT_INIT(2), &strentries[221]},
  4843. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_DOUBLE"), UPB_TABVALUE_INT_INIT(1), NULL},
  4844. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4845. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_INT32"), UPB_TABVALUE_INT_INIT(5), NULL},
  4846. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "TYPE_SFIXED32"), UPB_TABVALUE_INT_INIT(15), NULL},
  4847. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_FIXED32"), UPB_TABVALUE_INT_INIT(7), NULL},
  4848. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4849. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_MESSAGE"), UPB_TABVALUE_INT_INIT(11), &strentries[222]},
  4850. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4851. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4852. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_INT64"), UPB_TABVALUE_INT_INIT(3), &strentries[219]},
  4853. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4854. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4855. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4856. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4857. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "TYPE_ENUM"), UPB_TABVALUE_INT_INIT(14), NULL},
  4858. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_UINT32"), UPB_TABVALUE_INT_INIT(13), NULL},
  4859. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4860. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_UINT64"), UPB_TABVALUE_INT_INIT(4), &strentries[218]},
  4861. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4862. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "TYPE_SFIXED64"), UPB_TABVALUE_INT_INIT(16), NULL},
  4863. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_BYTES"), UPB_TABVALUE_INT_INIT(12), NULL},
  4864. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_SINT64"), UPB_TABVALUE_INT_INIT(18), NULL},
  4865. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "TYPE_BOOL"), UPB_TABVALUE_INT_INIT(8), NULL},
  4866. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_GROUP"), UPB_TABVALUE_INT_INIT(10), NULL},
  4867. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_SINT32"), UPB_TABVALUE_INT_INIT(17), NULL},
  4868. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4869. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "CORD"), UPB_TABVALUE_INT_INIT(1), NULL},
  4870. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "STRING"), UPB_TABVALUE_INT_INIT(0), &strentries[225]},
  4871. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "STRING_PIECE"), UPB_TABVALUE_INT_INIT(2), NULL},
  4872. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4873. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "JS_NORMAL"), UPB_TABVALUE_INT_INIT(0), NULL},
  4874. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "JS_NUMBER"), UPB_TABVALUE_INT_INIT(2), NULL},
  4875. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "JS_STRING"), UPB_TABVALUE_INT_INIT(1), NULL},
  4876. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "CODE_SIZE"), UPB_TABVALUE_INT_INIT(2), NULL},
  4877. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "SPEED"), UPB_TABVALUE_INT_INIT(1), &strentries[235]},
  4878. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4879. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "LITE_RUNTIME"), UPB_TABVALUE_INT_INIT(3), NULL},
  4880. };
  4881. static const upb_tabent intentries[18] = {
  4882. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4883. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[98]), NULL},
  4884. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4885. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[97]), NULL},
  4886. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4887. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[99]), NULL},
  4888. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4889. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[95]), NULL},
  4890. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4891. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[96]), NULL},
  4892. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4893. {UPB_TABKEY_NUM(33), UPB_TABVALUE_PTR_INIT(&fields[11]), NULL},
  4894. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4895. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[100]), NULL},
  4896. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4897. {UPB_TABKEY_NUM(33), UPB_TABVALUE_PTR_INIT(&fields[14]), NULL},
  4898. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4899. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[101]), NULL},
  4900. };
  4901. static const upb_tabval arrays[184] = {
  4902. UPB_TABVALUE_EMPTY_INIT,
  4903. UPB_TABVALUE_PTR_INIT(&fields[52]),
  4904. UPB_TABVALUE_PTR_INIT(&fields[25]),
  4905. UPB_TABVALUE_PTR_INIT(&fields[60]),
  4906. UPB_TABVALUE_PTR_INIT(&fields[19]),
  4907. UPB_TABVALUE_PTR_INIT(&fields[24]),
  4908. UPB_TABVALUE_PTR_INIT(&fields[22]),
  4909. UPB_TABVALUE_PTR_INIT(&fields[68]),
  4910. UPB_TABVALUE_PTR_INIT(&fields[65]),
  4911. UPB_TABVALUE_PTR_INIT(&fields[83]),
  4912. UPB_TABVALUE_PTR_INIT(&fields[82]),
  4913. UPB_TABVALUE_EMPTY_INIT,
  4914. UPB_TABVALUE_PTR_INIT(&fields[89]),
  4915. UPB_TABVALUE_PTR_INIT(&fields[18]),
  4916. UPB_TABVALUE_EMPTY_INIT,
  4917. UPB_TABVALUE_PTR_INIT(&fields[88]),
  4918. UPB_TABVALUE_PTR_INIT(&fields[17]),
  4919. UPB_TABVALUE_EMPTY_INIT,
  4920. UPB_TABVALUE_PTR_INIT(&fields[49]),
  4921. UPB_TABVALUE_PTR_INIT(&fields[102]),
  4922. UPB_TABVALUE_PTR_INIT(&fields[74]),
  4923. UPB_TABVALUE_EMPTY_INIT,
  4924. UPB_TABVALUE_EMPTY_INIT,
  4925. UPB_TABVALUE_PTR_INIT(&fields[1]),
  4926. UPB_TABVALUE_PTR_INIT(&fields[13]),
  4927. UPB_TABVALUE_EMPTY_INIT,
  4928. UPB_TABVALUE_PTR_INIT(&fields[53]),
  4929. UPB_TABVALUE_PTR_INIT(&fields[62]),
  4930. UPB_TABVALUE_PTR_INIT(&fields[73]),
  4931. UPB_TABVALUE_EMPTY_INIT,
  4932. UPB_TABVALUE_PTR_INIT(&fields[15]),
  4933. UPB_TABVALUE_EMPTY_INIT,
  4934. UPB_TABVALUE_PTR_INIT(&fields[55]),
  4935. UPB_TABVALUE_PTR_INIT(&fields[21]),
  4936. UPB_TABVALUE_PTR_INIT(&fields[63]),
  4937. UPB_TABVALUE_PTR_INIT(&fields[40]),
  4938. UPB_TABVALUE_PTR_INIT(&fields[93]),
  4939. UPB_TABVALUE_PTR_INIT(&fields[94]),
  4940. UPB_TABVALUE_PTR_INIT(&fields[7]),
  4941. UPB_TABVALUE_PTR_INIT(&fields[71]),
  4942. UPB_TABVALUE_PTR_INIT(&fields[66]),
  4943. UPB_TABVALUE_PTR_INIT(&fields[38]),
  4944. UPB_TABVALUE_EMPTY_INIT,
  4945. UPB_TABVALUE_PTR_INIT(&fields[6]),
  4946. UPB_TABVALUE_PTR_INIT(&fields[77]),
  4947. UPB_TABVALUE_PTR_INIT(&fields[10]),
  4948. UPB_TABVALUE_EMPTY_INIT,
  4949. UPB_TABVALUE_PTR_INIT(&fields[41]),
  4950. UPB_TABVALUE_PTR_INIT(&fields[39]),
  4951. UPB_TABVALUE_EMPTY_INIT,
  4952. UPB_TABVALUE_EMPTY_INIT,
  4953. UPB_TABVALUE_EMPTY_INIT,
  4954. UPB_TABVALUE_PTR_INIT(&fields[103]),
  4955. UPB_TABVALUE_EMPTY_INIT,
  4956. UPB_TABVALUE_PTR_INIT(&fields[54]),
  4957. UPB_TABVALUE_PTR_INIT(&fields[76]),
  4958. UPB_TABVALUE_PTR_INIT(&fields[8]),
  4959. UPB_TABVALUE_PTR_INIT(&fields[47]),
  4960. UPB_TABVALUE_PTR_INIT(&fields[20]),
  4961. UPB_TABVALUE_PTR_INIT(&fields[85]),
  4962. UPB_TABVALUE_PTR_INIT(&fields[23]),
  4963. UPB_TABVALUE_PTR_INIT(&fields[69]),
  4964. UPB_TABVALUE_PTR_INIT(&fields[86]),
  4965. UPB_TABVALUE_PTR_INIT(&fields[80]),
  4966. UPB_TABVALUE_PTR_INIT(&fields[104]),
  4967. UPB_TABVALUE_PTR_INIT(&fields[91]),
  4968. UPB_TABVALUE_EMPTY_INIT,
  4969. UPB_TABVALUE_PTR_INIT(&fields[26]),
  4970. UPB_TABVALUE_EMPTY_INIT,
  4971. UPB_TABVALUE_PTR_INIT(&fields[35]),
  4972. UPB_TABVALUE_EMPTY_INIT,
  4973. UPB_TABVALUE_EMPTY_INIT,
  4974. UPB_TABVALUE_EMPTY_INIT,
  4975. UPB_TABVALUE_EMPTY_INIT,
  4976. UPB_TABVALUE_EMPTY_INIT,
  4977. UPB_TABVALUE_EMPTY_INIT,
  4978. UPB_TABVALUE_PTR_INIT(&fields[34]),
  4979. UPB_TABVALUE_PTR_INIT(&fields[67]),
  4980. UPB_TABVALUE_PTR_INIT(&fields[33]),
  4981. UPB_TABVALUE_PTR_INIT(&fields[27]),
  4982. UPB_TABVALUE_EMPTY_INIT,
  4983. UPB_TABVALUE_EMPTY_INIT,
  4984. UPB_TABVALUE_EMPTY_INIT,
  4985. UPB_TABVALUE_EMPTY_INIT,
  4986. UPB_TABVALUE_PTR_INIT(&fields[3]),
  4987. UPB_TABVALUE_PTR_INIT(&fields[32]),
  4988. UPB_TABVALUE_PTR_INIT(&fields[81]),
  4989. UPB_TABVALUE_EMPTY_INIT,
  4990. UPB_TABVALUE_PTR_INIT(&fields[31]),
  4991. UPB_TABVALUE_EMPTY_INIT,
  4992. UPB_TABVALUE_EMPTY_INIT,
  4993. UPB_TABVALUE_PTR_INIT(&fields[12]),
  4994. UPB_TABVALUE_EMPTY_INIT,
  4995. UPB_TABVALUE_EMPTY_INIT,
  4996. UPB_TABVALUE_EMPTY_INIT,
  4997. UPB_TABVALUE_PTR_INIT(&fields[36]),
  4998. UPB_TABVALUE_EMPTY_INIT,
  4999. UPB_TABVALUE_EMPTY_INIT,
  5000. UPB_TABVALUE_EMPTY_INIT,
  5001. UPB_TABVALUE_PTR_INIT(&fields[2]),
  5002. UPB_TABVALUE_EMPTY_INIT,
  5003. UPB_TABVALUE_EMPTY_INIT,
  5004. UPB_TABVALUE_EMPTY_INIT,
  5005. UPB_TABVALUE_EMPTY_INIT,
  5006. UPB_TABVALUE_PTR_INIT(&fields[64]),
  5007. UPB_TABVALUE_PTR_INIT(&fields[5]),
  5008. UPB_TABVALUE_PTR_INIT(&fields[37]),
  5009. UPB_TABVALUE_EMPTY_INIT,
  5010. UPB_TABVALUE_PTR_INIT(&fields[46]),
  5011. UPB_TABVALUE_PTR_INIT(&fields[61]),
  5012. UPB_TABVALUE_PTR_INIT(&fields[9]),
  5013. UPB_TABVALUE_EMPTY_INIT,
  5014. UPB_TABVALUE_EMPTY_INIT,
  5015. UPB_TABVALUE_EMPTY_INIT,
  5016. UPB_TABVALUE_PTR_INIT(&fields[45]),
  5017. UPB_TABVALUE_EMPTY_INIT,
  5018. UPB_TABVALUE_PTR_INIT(&fields[56]),
  5019. UPB_TABVALUE_PTR_INIT(&fields[29]),
  5020. UPB_TABVALUE_PTR_INIT(&fields[75]),
  5021. UPB_TABVALUE_PTR_INIT(&fields[70]),
  5022. UPB_TABVALUE_PTR_INIT(&fields[4]),
  5023. UPB_TABVALUE_PTR_INIT(&fields[84]),
  5024. UPB_TABVALUE_EMPTY_INIT,
  5025. UPB_TABVALUE_EMPTY_INIT,
  5026. UPB_TABVALUE_PTR_INIT(&fields[50]),
  5027. UPB_TABVALUE_EMPTY_INIT,
  5028. UPB_TABVALUE_PTR_INIT(&fields[57]),
  5029. UPB_TABVALUE_PTR_INIT(&fields[48]),
  5030. UPB_TABVALUE_PTR_INIT(&fields[72]),
  5031. UPB_TABVALUE_EMPTY_INIT,
  5032. UPB_TABVALUE_EMPTY_INIT,
  5033. UPB_TABVALUE_PTR_INIT(&fields[44]),
  5034. UPB_TABVALUE_EMPTY_INIT,
  5035. UPB_TABVALUE_PTR_INIT(&fields[78]),
  5036. UPB_TABVALUE_PTR_INIT(&fields[87]),
  5037. UPB_TABVALUE_PTR_INIT(&fields[42]),
  5038. UPB_TABVALUE_PTR_INIT(&fields[92]),
  5039. UPB_TABVALUE_EMPTY_INIT,
  5040. UPB_TABVALUE_PTR_INIT(&fields[43]),
  5041. UPB_TABVALUE_EMPTY_INIT,
  5042. UPB_TABVALUE_EMPTY_INIT,
  5043. UPB_TABVALUE_PTR_INIT(&fields[51]),
  5044. UPB_TABVALUE_PTR_INIT(&fields[28]),
  5045. UPB_TABVALUE_PTR_INIT(&fields[79]),
  5046. UPB_TABVALUE_PTR_INIT(&fields[59]),
  5047. UPB_TABVALUE_PTR_INIT(&fields[16]),
  5048. UPB_TABVALUE_PTR_INIT(&fields[90]),
  5049. UPB_TABVALUE_PTR_INIT(&fields[0]),
  5050. UPB_TABVALUE_EMPTY_INIT,
  5051. UPB_TABVALUE_PTR_INIT(&fields[58]),
  5052. UPB_TABVALUE_PTR_INIT(&fields[30]),
  5053. UPB_TABVALUE_EMPTY_INIT,
  5054. UPB_TABVALUE_PTR_INIT("LABEL_OPTIONAL"),
  5055. UPB_TABVALUE_PTR_INIT("LABEL_REQUIRED"),
  5056. UPB_TABVALUE_PTR_INIT("LABEL_REPEATED"),
  5057. UPB_TABVALUE_EMPTY_INIT,
  5058. UPB_TABVALUE_PTR_INIT("TYPE_DOUBLE"),
  5059. UPB_TABVALUE_PTR_INIT("TYPE_FLOAT"),
  5060. UPB_TABVALUE_PTR_INIT("TYPE_INT64"),
  5061. UPB_TABVALUE_PTR_INIT("TYPE_UINT64"),
  5062. UPB_TABVALUE_PTR_INIT("TYPE_INT32"),
  5063. UPB_TABVALUE_PTR_INIT("TYPE_FIXED64"),
  5064. UPB_TABVALUE_PTR_INIT("TYPE_FIXED32"),
  5065. UPB_TABVALUE_PTR_INIT("TYPE_BOOL"),
  5066. UPB_TABVALUE_PTR_INIT("TYPE_STRING"),
  5067. UPB_TABVALUE_PTR_INIT("TYPE_GROUP"),
  5068. UPB_TABVALUE_PTR_INIT("TYPE_MESSAGE"),
  5069. UPB_TABVALUE_PTR_INIT("TYPE_BYTES"),
  5070. UPB_TABVALUE_PTR_INIT("TYPE_UINT32"),
  5071. UPB_TABVALUE_PTR_INIT("TYPE_ENUM"),
  5072. UPB_TABVALUE_PTR_INIT("TYPE_SFIXED32"),
  5073. UPB_TABVALUE_PTR_INIT("TYPE_SFIXED64"),
  5074. UPB_TABVALUE_PTR_INIT("TYPE_SINT32"),
  5075. UPB_TABVALUE_PTR_INIT("TYPE_SINT64"),
  5076. UPB_TABVALUE_PTR_INIT("STRING"),
  5077. UPB_TABVALUE_PTR_INIT("CORD"),
  5078. UPB_TABVALUE_PTR_INIT("STRING_PIECE"),
  5079. UPB_TABVALUE_PTR_INIT("JS_NORMAL"),
  5080. UPB_TABVALUE_PTR_INIT("JS_STRING"),
  5081. UPB_TABVALUE_PTR_INIT("JS_NUMBER"),
  5082. UPB_TABVALUE_EMPTY_INIT,
  5083. UPB_TABVALUE_PTR_INIT("SPEED"),
  5084. UPB_TABVALUE_PTR_INIT("CODE_SIZE"),
  5085. UPB_TABVALUE_PTR_INIT("LITE_RUNTIME"),
  5086. };
  5087. #ifdef UPB_DEBUG_REFS
  5088. static upb_inttable reftables[264] = {
  5089. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5090. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5091. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5092. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5093. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5094. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5095. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5096. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5097. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5098. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5099. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5100. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5101. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5102. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5103. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5104. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5105. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5106. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5107. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5108. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5109. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5110. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5111. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5112. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5113. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5114. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5115. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5116. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5117. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5118. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5119. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5120. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5121. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5122. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5123. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5124. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5125. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5126. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5127. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5128. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5129. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5130. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5131. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5132. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5133. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5134. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5135. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5136. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5137. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5138. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5139. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5140. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5141. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5142. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5143. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5144. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5145. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5146. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5147. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5148. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5149. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5150. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5151. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5152. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5153. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5154. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5155. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5156. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5157. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5158. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5159. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5160. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5161. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5162. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5163. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5164. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5165. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5166. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5167. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5168. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5169. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5170. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5171. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5172. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5173. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5174. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5175. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5176. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5177. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5178. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5179. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5180. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5181. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5182. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5183. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5184. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5185. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5186. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5187. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5188. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5189. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5190. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5191. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5192. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5193. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5194. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5195. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5196. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5197. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5198. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5199. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5200. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5201. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5202. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5203. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5204. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5205. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5206. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5207. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5208. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5209. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5210. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5211. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5212. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5213. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5214. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5215. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5216. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5217. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5218. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5219. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5220. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5221. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5222. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5223. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5224. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5225. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5226. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5227. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5228. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5229. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5230. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5231. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5232. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5233. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5234. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5235. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5236. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5237. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5238. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5239. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5240. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5241. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5242. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5243. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5244. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5245. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5246. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5247. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5248. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5249. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5250. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5251. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5252. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5253. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5254. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5255. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5256. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5257. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5258. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5259. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5260. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5261. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5262. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5263. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5264. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5265. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5266. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5267. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5268. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5269. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5270. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5271. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5272. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5273. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5274. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5275. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5276. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5277. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5278. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5279. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5280. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5281. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5282. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5283. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5284. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5285. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5286. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5287. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5288. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5289. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5290. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5291. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5292. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5293. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5294. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5295. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5296. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5297. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5298. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5299. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5300. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5301. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5302. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5303. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5304. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5305. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5306. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5307. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5308. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5309. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5310. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5311. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5312. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5313. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5314. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5315. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5316. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5317. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5318. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5319. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5320. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5321. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5322. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5323. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5324. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5325. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5326. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5327. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5328. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5329. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5330. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5331. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5332. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5333. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5334. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5335. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5336. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5337. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5338. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5339. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5340. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5341. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5342. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5343. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5344. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5345. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5346. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5347. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5348. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5349. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5350. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5351. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5352. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5353. };
  5354. #endif
  5355. static const upb_msgdef *refm(const upb_msgdef *m, const void *owner) {
  5356. upb_msgdef_ref(m, owner);
  5357. return m;
  5358. }
  5359. static const upb_enumdef *refe(const upb_enumdef *e, const void *owner) {
  5360. upb_enumdef_ref(e, owner);
  5361. return e;
  5362. }
  5363. /* Public API. */
  5364. const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_get(const void *owner) { return refm(&msgs[0], owner); }
  5365. const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_ExtensionRange_get(const void *owner) { return refm(&msgs[1], owner); }
  5366. const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_ReservedRange_get(const void *owner) { return refm(&msgs[2], owner); }
  5367. const upb_msgdef *upbdefs_google_protobuf_EnumDescriptorProto_get(const void *owner) { return refm(&msgs[3], owner); }
  5368. const upb_msgdef *upbdefs_google_protobuf_EnumOptions_get(const void *owner) { return refm(&msgs[4], owner); }
  5369. const upb_msgdef *upbdefs_google_protobuf_EnumValueDescriptorProto_get(const void *owner) { return refm(&msgs[5], owner); }
  5370. const upb_msgdef *upbdefs_google_protobuf_EnumValueOptions_get(const void *owner) { return refm(&msgs[6], owner); }
  5371. const upb_msgdef *upbdefs_google_protobuf_FieldDescriptorProto_get(const void *owner) { return refm(&msgs[7], owner); }
  5372. const upb_msgdef *upbdefs_google_protobuf_FieldOptions_get(const void *owner) { return refm(&msgs[8], owner); }
  5373. const upb_msgdef *upbdefs_google_protobuf_FileDescriptorProto_get(const void *owner) { return refm(&msgs[9], owner); }
  5374. const upb_msgdef *upbdefs_google_protobuf_FileDescriptorSet_get(const void *owner) { return refm(&msgs[10], owner); }
  5375. const upb_msgdef *upbdefs_google_protobuf_FileOptions_get(const void *owner) { return refm(&msgs[11], owner); }
  5376. const upb_msgdef *upbdefs_google_protobuf_MessageOptions_get(const void *owner) { return refm(&msgs[12], owner); }
  5377. const upb_msgdef *upbdefs_google_protobuf_MethodDescriptorProto_get(const void *owner) { return refm(&msgs[13], owner); }
  5378. const upb_msgdef *upbdefs_google_protobuf_MethodOptions_get(const void *owner) { return refm(&msgs[14], owner); }
  5379. const upb_msgdef *upbdefs_google_protobuf_OneofDescriptorProto_get(const void *owner) { return refm(&msgs[15], owner); }
  5380. const upb_msgdef *upbdefs_google_protobuf_ServiceDescriptorProto_get(const void *owner) { return refm(&msgs[16], owner); }
  5381. const upb_msgdef *upbdefs_google_protobuf_ServiceOptions_get(const void *owner) { return refm(&msgs[17], owner); }
  5382. const upb_msgdef *upbdefs_google_protobuf_SourceCodeInfo_get(const void *owner) { return refm(&msgs[18], owner); }
  5383. const upb_msgdef *upbdefs_google_protobuf_SourceCodeInfo_Location_get(const void *owner) { return refm(&msgs[19], owner); }
  5384. const upb_msgdef *upbdefs_google_protobuf_UninterpretedOption_get(const void *owner) { return refm(&msgs[20], owner); }
  5385. const upb_msgdef *upbdefs_google_protobuf_UninterpretedOption_NamePart_get(const void *owner) { return refm(&msgs[21], owner); }
  5386. const upb_enumdef *upbdefs_google_protobuf_FieldDescriptorProto_Label_get(const void *owner) { return refe(&enums[0], owner); }
  5387. const upb_enumdef *upbdefs_google_protobuf_FieldDescriptorProto_Type_get(const void *owner) { return refe(&enums[1], owner); }
  5388. const upb_enumdef *upbdefs_google_protobuf_FieldOptions_CType_get(const void *owner) { return refe(&enums[2], owner); }
  5389. const upb_enumdef *upbdefs_google_protobuf_FieldOptions_JSType_get(const void *owner) { return refe(&enums[3], owner); }
  5390. const upb_enumdef *upbdefs_google_protobuf_FileOptions_OptimizeMode_get(const void *owner) { return refe(&enums[4], owner); }
  5391. /*
  5392. ** XXX: The routines in this file that consume a string do not currently
  5393. ** support having the string span buffers. In the future, as upb_sink and
  5394. ** its buffering/sharing functionality evolve there should be an easy and
  5395. ** idiomatic way of correctly handling this case. For now, we accept this
  5396. ** limitation since we currently only parse descriptors from single strings.
  5397. */
  5398. #include <errno.h>
  5399. #include <stdlib.h>
  5400. #include <string.h>
  5401. /* Compares a NULL-terminated string with a non-NULL-terminated string. */
  5402. static bool upb_streq(const char *str, const char *buf, size_t n) {
  5403. return strlen(str) == n && memcmp(str, buf, n) == 0;
  5404. }
  5405. /* We keep a stack of all the messages scopes we are currently in, as well as
  5406. * the top-level file scope. This is necessary to correctly qualify the
  5407. * definitions that are contained inside. "name" tracks the name of the
  5408. * message or package (a bare name -- not qualified by any enclosing scopes). */
  5409. typedef struct {
  5410. char *name;
  5411. /* Index of the first def that is under this scope. For msgdefs, the
  5412. * msgdef itself is at start-1. */
  5413. int start;
  5414. } upb_descreader_frame;
  5415. /* The maximum number of nested declarations that are allowed, ie.
  5416. * message Foo {
  5417. * message Bar {
  5418. * message Baz {
  5419. * }
  5420. * }
  5421. * }
  5422. *
  5423. * This is a resource limit that affects how big our runtime stack can grow.
  5424. * TODO: make this a runtime-settable property of the Reader instance. */
  5425. #define UPB_MAX_MESSAGE_NESTING 64
  5426. struct upb_descreader {
  5427. upb_sink sink;
  5428. upb_inttable files;
  5429. upb_filedef *file; /* The last file in files. */
  5430. upb_descreader_frame stack[UPB_MAX_MESSAGE_NESTING];
  5431. int stack_len;
  5432. uint32_t number;
  5433. char *name;
  5434. bool saw_number;
  5435. bool saw_name;
  5436. char *default_string;
  5437. upb_fielddef *f;
  5438. };
  5439. static char *upb_strndup(const char *buf, size_t n) {
  5440. char *ret = malloc(n + 1);
  5441. if (!ret) return NULL;
  5442. memcpy(ret, buf, n);
  5443. ret[n] = '\0';
  5444. return ret;
  5445. }
  5446. /* Returns a newly allocated string that joins input strings together, for
  5447. * example:
  5448. * join("Foo.Bar", "Baz") -> "Foo.Bar.Baz"
  5449. * join("", "Baz") -> "Baz"
  5450. * Caller owns a ref on the returned string. */
  5451. static char *upb_join(const char *base, const char *name) {
  5452. if (!base || strlen(base) == 0) {
  5453. return upb_strdup(name);
  5454. } else {
  5455. char *ret = malloc(strlen(base) + strlen(name) + 2);
  5456. ret[0] = '\0';
  5457. strcat(ret, base);
  5458. strcat(ret, ".");
  5459. strcat(ret, name);
  5460. return ret;
  5461. }
  5462. }
  5463. /* Qualify the defname for all defs starting with offset "start" with "str". */
  5464. static void upb_descreader_qualify(upb_filedef *f, char *str, int32_t start) {
  5465. size_t i;
  5466. for (i = start; i < upb_filedef_defcount(f); i++) {
  5467. upb_def *def = upb_filedef_mutabledef(f, i);
  5468. char *name = upb_join(str, upb_def_fullname(def));
  5469. upb_def_setfullname(def, name, NULL);
  5470. free(name);
  5471. }
  5472. }
  5473. /* upb_descreader ************************************************************/
  5474. static upb_msgdef *upb_descreader_top(upb_descreader *r) {
  5475. int index;
  5476. assert(r->stack_len > 1);
  5477. index = r->stack[r->stack_len-1].start - 1;
  5478. assert(index >= 0);
  5479. return upb_downcast_msgdef_mutable(upb_filedef_mutabledef(r->file, index));
  5480. }
  5481. static upb_def *upb_descreader_last(upb_descreader *r) {
  5482. return upb_filedef_mutabledef(r->file, upb_filedef_defcount(r->file) - 1);
  5483. }
  5484. /* Start/end handlers for FileDescriptorProto and DescriptorProto (the two
  5485. * entities that have names and can contain sub-definitions. */
  5486. void upb_descreader_startcontainer(upb_descreader *r) {
  5487. upb_descreader_frame *f = &r->stack[r->stack_len++];
  5488. f->start = upb_filedef_defcount(r->file);
  5489. f->name = NULL;
  5490. }
  5491. void upb_descreader_endcontainer(upb_descreader *r) {
  5492. upb_descreader_frame *f = &r->stack[--r->stack_len];
  5493. upb_descreader_qualify(r->file, f->name, f->start);
  5494. free(f->name);
  5495. f->name = NULL;
  5496. }
  5497. void upb_descreader_setscopename(upb_descreader *r, char *str) {
  5498. upb_descreader_frame *f = &r->stack[r->stack_len-1];
  5499. free(f->name);
  5500. f->name = str;
  5501. }
  5502. /** Handlers for google.protobuf.FileDescriptorSet. ***************************/
  5503. static void *fileset_startfile(void *closure, const void *hd) {
  5504. upb_descreader *r = closure;
  5505. UPB_UNUSED(hd);
  5506. r->file = upb_filedef_new(&r->files);
  5507. upb_inttable_push(&r->files, upb_value_ptr(r->file));
  5508. return r;
  5509. }
  5510. /** Handlers for google.protobuf.FileDescriptorProto. *************************/
  5511. static bool file_start(void *closure, const void *hd) {
  5512. upb_descreader *r = closure;
  5513. UPB_UNUSED(hd);
  5514. upb_descreader_startcontainer(r);
  5515. return true;
  5516. }
  5517. static bool file_end(void *closure, const void *hd, upb_status *status) {
  5518. upb_descreader *r = closure;
  5519. UPB_UNUSED(hd);
  5520. UPB_UNUSED(status);
  5521. upb_descreader_endcontainer(r);
  5522. return true;
  5523. }
  5524. static size_t file_onname(void *closure, const void *hd, const char *buf,
  5525. size_t n, const upb_bufhandle *handle) {
  5526. upb_descreader *r = closure;
  5527. char *name;
  5528. bool ok;
  5529. UPB_UNUSED(hd);
  5530. UPB_UNUSED(handle);
  5531. name = upb_strndup(buf, n);
  5532. /* XXX: see comment at the top of the file. */
  5533. ok = upb_filedef_setname(r->file, name, NULL);
  5534. UPB_ASSERT_VAR(ok, ok);
  5535. return n;
  5536. }
  5537. static size_t file_onpackage(void *closure, const void *hd, const char *buf,
  5538. size_t n, const upb_bufhandle *handle) {
  5539. upb_descreader *r = closure;
  5540. char *package;
  5541. bool ok;
  5542. UPB_UNUSED(hd);
  5543. UPB_UNUSED(handle);
  5544. package = upb_strndup(buf, n);
  5545. /* XXX: see comment at the top of the file. */
  5546. upb_descreader_setscopename(r, package);
  5547. ok = upb_filedef_setpackage(r->file, package, NULL);
  5548. UPB_ASSERT_VAR(ok, ok);
  5549. return n;
  5550. }
  5551. static size_t file_onsyntax(void *closure, const void *hd, const char *buf,
  5552. size_t n, const upb_bufhandle *handle) {
  5553. upb_descreader *r = closure;
  5554. bool ok;
  5555. UPB_UNUSED(hd);
  5556. UPB_UNUSED(handle);
  5557. /* XXX: see comment at the top of the file. */
  5558. if (upb_streq("proto2", buf, n)) {
  5559. ok = upb_filedef_setsyntax(r->file, UPB_SYNTAX_PROTO2, NULL);
  5560. } else if (upb_streq("proto3", buf, n)) {
  5561. ok = upb_filedef_setsyntax(r->file, UPB_SYNTAX_PROTO3, NULL);
  5562. } else {
  5563. ok = false;
  5564. }
  5565. UPB_ASSERT_VAR(ok, ok);
  5566. return n;
  5567. }
  5568. static void *file_startmsg(void *closure, const void *hd) {
  5569. upb_descreader *r = closure;
  5570. upb_msgdef *m = upb_msgdef_new(&m);
  5571. bool ok = upb_filedef_addmsg(r->file, m, &m, NULL);
  5572. UPB_UNUSED(hd);
  5573. UPB_ASSERT_VAR(ok, ok);
  5574. return r;
  5575. }
  5576. static void *file_startenum(void *closure, const void *hd) {
  5577. upb_descreader *r = closure;
  5578. upb_enumdef *e = upb_enumdef_new(&e);
  5579. bool ok = upb_filedef_addenum(r->file, e, &e, NULL);
  5580. UPB_UNUSED(hd);
  5581. UPB_ASSERT_VAR(ok, ok);
  5582. return r;
  5583. }
  5584. static void *file_startext(void *closure, const void *hd) {
  5585. upb_descreader *r = closure;
  5586. bool ok;
  5587. r->f = upb_fielddef_new(r);
  5588. ok = upb_filedef_addext(r->file, r->f, r, NULL);
  5589. UPB_UNUSED(hd);
  5590. UPB_ASSERT_VAR(ok, ok);
  5591. return r;
  5592. }
  5593. /** Handlers for google.protobuf.EnumValueDescriptorProto. *********************/
  5594. static bool enumval_startmsg(void *closure, const void *hd) {
  5595. upb_descreader *r = closure;
  5596. UPB_UNUSED(hd);
  5597. r->saw_number = false;
  5598. r->saw_name = false;
  5599. return true;
  5600. }
  5601. static size_t enumval_onname(void *closure, const void *hd, const char *buf,
  5602. size_t n, const upb_bufhandle *handle) {
  5603. upb_descreader *r = closure;
  5604. UPB_UNUSED(hd);
  5605. UPB_UNUSED(handle);
  5606. /* XXX: see comment at the top of the file. */
  5607. free(r->name);
  5608. r->name = upb_strndup(buf, n);
  5609. r->saw_name = true;
  5610. return n;
  5611. }
  5612. static bool enumval_onnumber(void *closure, const void *hd, int32_t val) {
  5613. upb_descreader *r = closure;
  5614. UPB_UNUSED(hd);
  5615. r->number = val;
  5616. r->saw_number = true;
  5617. return true;
  5618. }
  5619. static bool enumval_endmsg(void *closure, const void *hd, upb_status *status) {
  5620. upb_descreader *r = closure;
  5621. upb_enumdef *e;
  5622. UPB_UNUSED(hd);
  5623. if(!r->saw_number || !r->saw_name) {
  5624. upb_status_seterrmsg(status, "Enum value missing name or number.");
  5625. return false;
  5626. }
  5627. e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  5628. upb_enumdef_addval(e, r->name, r->number, status);
  5629. free(r->name);
  5630. r->name = NULL;
  5631. return true;
  5632. }
  5633. /** Handlers for google.protobuf.EnumDescriptorProto. *************************/
  5634. static bool enum_endmsg(void *closure, const void *hd, upb_status *status) {
  5635. upb_descreader *r = closure;
  5636. upb_enumdef *e;
  5637. UPB_UNUSED(hd);
  5638. e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  5639. if (upb_def_fullname(upb_descreader_last(r)) == NULL) {
  5640. upb_status_seterrmsg(status, "Enum had no name.");
  5641. return false;
  5642. }
  5643. if (upb_enumdef_numvals(e) == 0) {
  5644. upb_status_seterrmsg(status, "Enum had no values.");
  5645. return false;
  5646. }
  5647. return true;
  5648. }
  5649. static size_t enum_onname(void *closure, const void *hd, const char *buf,
  5650. size_t n, const upb_bufhandle *handle) {
  5651. upb_descreader *r = closure;
  5652. char *fullname = upb_strndup(buf, n);
  5653. UPB_UNUSED(hd);
  5654. UPB_UNUSED(handle);
  5655. /* XXX: see comment at the top of the file. */
  5656. upb_def_setfullname(upb_descreader_last(r), fullname, NULL);
  5657. free(fullname);
  5658. return n;
  5659. }
  5660. /** Handlers for google.protobuf.FieldDescriptorProto *************************/
  5661. static bool field_startmsg(void *closure, const void *hd) {
  5662. upb_descreader *r = closure;
  5663. UPB_UNUSED(hd);
  5664. assert(r->f);
  5665. free(r->default_string);
  5666. r->default_string = NULL;
  5667. /* fielddefs default to packed, but descriptors default to non-packed. */
  5668. upb_fielddef_setpacked(r->f, false);
  5669. return true;
  5670. }
  5671. /* Converts the default value in string "str" into "d". Passes a ref on str.
  5672. * Returns true on success. */
  5673. static bool parse_default(char *str, upb_fielddef *f) {
  5674. bool success = true;
  5675. char *end;
  5676. switch (upb_fielddef_type(f)) {
  5677. case UPB_TYPE_INT32: {
  5678. long val = strtol(str, &end, 0);
  5679. if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || *end)
  5680. success = false;
  5681. else
  5682. upb_fielddef_setdefaultint32(f, val);
  5683. break;
  5684. }
  5685. case UPB_TYPE_INT64: {
  5686. /* XXX: Need to write our own strtoll, since it's not available in c89. */
  5687. long long val = strtol(str, &end, 0);
  5688. if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || *end)
  5689. success = false;
  5690. else
  5691. upb_fielddef_setdefaultint64(f, val);
  5692. break;
  5693. }
  5694. case UPB_TYPE_UINT32: {
  5695. unsigned long val = strtoul(str, &end, 0);
  5696. if (val > UINT32_MAX || errno == ERANGE || *end)
  5697. success = false;
  5698. else
  5699. upb_fielddef_setdefaultuint32(f, val);
  5700. break;
  5701. }
  5702. case UPB_TYPE_UINT64: {
  5703. /* XXX: Need to write our own strtoull, since it's not available in c89. */
  5704. unsigned long long val = strtoul(str, &end, 0);
  5705. if (val > UINT64_MAX || errno == ERANGE || *end)
  5706. success = false;
  5707. else
  5708. upb_fielddef_setdefaultuint64(f, val);
  5709. break;
  5710. }
  5711. case UPB_TYPE_DOUBLE: {
  5712. double val = strtod(str, &end);
  5713. if (errno == ERANGE || *end)
  5714. success = false;
  5715. else
  5716. upb_fielddef_setdefaultdouble(f, val);
  5717. break;
  5718. }
  5719. case UPB_TYPE_FLOAT: {
  5720. /* XXX: Need to write our own strtof, since it's not available in c89. */
  5721. float val = strtod(str, &end);
  5722. if (errno == ERANGE || *end)
  5723. success = false;
  5724. else
  5725. upb_fielddef_setdefaultfloat(f, val);
  5726. break;
  5727. }
  5728. case UPB_TYPE_BOOL: {
  5729. if (strcmp(str, "false") == 0)
  5730. upb_fielddef_setdefaultbool(f, false);
  5731. else if (strcmp(str, "true") == 0)
  5732. upb_fielddef_setdefaultbool(f, true);
  5733. else
  5734. success = false;
  5735. break;
  5736. }
  5737. default: abort();
  5738. }
  5739. return success;
  5740. }
  5741. static bool field_endmsg(void *closure, const void *hd, upb_status *status) {
  5742. upb_descreader *r = closure;
  5743. upb_fielddef *f = r->f;
  5744. UPB_UNUSED(hd);
  5745. /* TODO: verify that all required fields were present. */
  5746. assert(upb_fielddef_number(f) != 0);
  5747. assert(upb_fielddef_name(f) != NULL);
  5748. assert((upb_fielddef_subdefname(f) != NULL) == upb_fielddef_hassubdef(f));
  5749. if (r->default_string) {
  5750. if (upb_fielddef_issubmsg(f)) {
  5751. upb_status_seterrmsg(status, "Submessages cannot have defaults.");
  5752. return false;
  5753. }
  5754. if (upb_fielddef_isstring(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  5755. upb_fielddef_setdefaultcstr(f, r->default_string, NULL);
  5756. } else {
  5757. if (r->default_string && !parse_default(r->default_string, f)) {
  5758. /* We don't worry too much about giving a great error message since the
  5759. * compiler should have ensured this was correct. */
  5760. upb_status_seterrmsg(status, "Error converting default value.");
  5761. return false;
  5762. }
  5763. }
  5764. }
  5765. return true;
  5766. }
  5767. static bool field_onlazy(void *closure, const void *hd, bool val) {
  5768. upb_descreader *r = closure;
  5769. UPB_UNUSED(hd);
  5770. upb_fielddef_setlazy(r->f, val);
  5771. return true;
  5772. }
  5773. static bool field_onpacked(void *closure, const void *hd, bool val) {
  5774. upb_descreader *r = closure;
  5775. UPB_UNUSED(hd);
  5776. upb_fielddef_setpacked(r->f, val);
  5777. return true;
  5778. }
  5779. static bool field_ontype(void *closure, const void *hd, int32_t val) {
  5780. upb_descreader *r = closure;
  5781. UPB_UNUSED(hd);
  5782. upb_fielddef_setdescriptortype(r->f, val);
  5783. return true;
  5784. }
  5785. static bool field_onlabel(void *closure, const void *hd, int32_t val) {
  5786. upb_descreader *r = closure;
  5787. UPB_UNUSED(hd);
  5788. upb_fielddef_setlabel(r->f, val);
  5789. return true;
  5790. }
  5791. static bool field_onnumber(void *closure, const void *hd, int32_t val) {
  5792. upb_descreader *r = closure;
  5793. bool ok;
  5794. UPB_UNUSED(hd);
  5795. ok = upb_fielddef_setnumber(r->f, val, NULL);
  5796. UPB_ASSERT_VAR(ok, ok);
  5797. return true;
  5798. }
  5799. static size_t field_onname(void *closure, const void *hd, const char *buf,
  5800. size_t n, const upb_bufhandle *handle) {
  5801. upb_descreader *r = closure;
  5802. char *name = upb_strndup(buf, n);
  5803. UPB_UNUSED(hd);
  5804. UPB_UNUSED(handle);
  5805. /* XXX: see comment at the top of the file. */
  5806. upb_fielddef_setname(r->f, name, NULL);
  5807. free(name);
  5808. return n;
  5809. }
  5810. static size_t field_ontypename(void *closure, const void *hd, const char *buf,
  5811. size_t n, const upb_bufhandle *handle) {
  5812. upb_descreader *r = closure;
  5813. char *name = upb_strndup(buf, n);
  5814. UPB_UNUSED(hd);
  5815. UPB_UNUSED(handle);
  5816. /* XXX: see comment at the top of the file. */
  5817. upb_fielddef_setsubdefname(r->f, name, NULL);
  5818. free(name);
  5819. return n;
  5820. }
  5821. static size_t field_onextendee(void *closure, const void *hd, const char *buf,
  5822. size_t n, const upb_bufhandle *handle) {
  5823. upb_descreader *r = closure;
  5824. char *name = upb_strndup(buf, n);
  5825. UPB_UNUSED(hd);
  5826. UPB_UNUSED(handle);
  5827. /* XXX: see comment at the top of the file. */
  5828. upb_fielddef_setcontainingtypename(r->f, name, NULL);
  5829. free(name);
  5830. return n;
  5831. }
  5832. static size_t field_ondefaultval(void *closure, const void *hd, const char *buf,
  5833. size_t n, const upb_bufhandle *handle) {
  5834. upb_descreader *r = closure;
  5835. UPB_UNUSED(hd);
  5836. UPB_UNUSED(handle);
  5837. /* Have to convert from string to the correct type, but we might not know the
  5838. * type yet, so we save it as a string until the end of the field.
  5839. * XXX: see comment at the top of the file. */
  5840. free(r->default_string);
  5841. r->default_string = upb_strndup(buf, n);
  5842. return n;
  5843. }
  5844. /** Handlers for google.protobuf.DescriptorProto ******************************/
  5845. static bool msg_start(void *closure, const void *hd) {
  5846. upb_descreader *r = closure;
  5847. UPB_UNUSED(hd);
  5848. upb_descreader_startcontainer(r);
  5849. return true;
  5850. }
  5851. static bool msg_end(void *closure, const void *hd, upb_status *status) {
  5852. upb_descreader *r = closure;
  5853. upb_msgdef *m = upb_descreader_top(r);
  5854. UPB_UNUSED(hd);
  5855. if(!upb_def_fullname(upb_msgdef_upcast_mutable(m))) {
  5856. upb_status_seterrmsg(status, "Encountered message with no name.");
  5857. return false;
  5858. }
  5859. upb_descreader_endcontainer(r);
  5860. return true;
  5861. }
  5862. static size_t msg_name(void *closure, const void *hd, const char *buf,
  5863. size_t n, const upb_bufhandle *handle) {
  5864. upb_descreader *r = closure;
  5865. upb_msgdef *m = upb_descreader_top(r);
  5866. /* XXX: see comment at the top of the file. */
  5867. char *name = upb_strndup(buf, n);
  5868. UPB_UNUSED(hd);
  5869. UPB_UNUSED(handle);
  5870. upb_def_setfullname(upb_msgdef_upcast_mutable(m), name, NULL);
  5871. upb_descreader_setscopename(r, name); /* Passes ownership of name. */
  5872. return n;
  5873. }
  5874. static void *msg_startmsg(void *closure, const void *hd) {
  5875. upb_descreader *r = closure;
  5876. upb_msgdef *m = upb_msgdef_new(&m);
  5877. bool ok = upb_filedef_addmsg(r->file, m, &m, NULL);
  5878. UPB_UNUSED(hd);
  5879. UPB_ASSERT_VAR(ok, ok);
  5880. return r;
  5881. }
  5882. static void *msg_startext(void *closure, const void *hd) {
  5883. upb_descreader *r = closure;
  5884. upb_fielddef *f = upb_fielddef_new(&f);
  5885. bool ok = upb_filedef_addext(r->file, f, &f, NULL);
  5886. UPB_UNUSED(hd);
  5887. UPB_ASSERT_VAR(ok, ok);
  5888. return r;
  5889. }
  5890. static void *msg_startfield(void *closure, const void *hd) {
  5891. upb_descreader *r = closure;
  5892. r->f = upb_fielddef_new(&r->f);
  5893. /* We can't add the new field to the message until its name/number are
  5894. * filled in. */
  5895. UPB_UNUSED(hd);
  5896. return r;
  5897. }
  5898. static bool msg_endfield(void *closure, const void *hd) {
  5899. upb_descreader *r = closure;
  5900. upb_msgdef *m = upb_descreader_top(r);
  5901. UPB_UNUSED(hd);
  5902. upb_msgdef_addfield(m, r->f, &r->f, NULL);
  5903. r->f = NULL;
  5904. return true;
  5905. }
  5906. /** Code to register handlers *************************************************/
  5907. #define F(msg, field) upbdefs_google_protobuf_ ## msg ## _f_ ## field(m)
  5908. static void reghandlers(const void *closure, upb_handlers *h) {
  5909. const upb_msgdef *m = upb_handlers_msgdef(h);
  5910. UPB_UNUSED(closure);
  5911. if (upbdefs_google_protobuf_FileDescriptorSet_is(m)) {
  5912. upb_handlers_setstartsubmsg(h, F(FileDescriptorSet, file),
  5913. &fileset_startfile, NULL);
  5914. } else if (upbdefs_google_protobuf_DescriptorProto_is(m)) {
  5915. upb_handlers_setstartmsg(h, &msg_start, NULL);
  5916. upb_handlers_setendmsg(h, &msg_end, NULL);
  5917. upb_handlers_setstring(h, F(DescriptorProto, name), &msg_name, NULL);
  5918. upb_handlers_setstartsubmsg(h, F(DescriptorProto, extension), &msg_startext,
  5919. NULL);
  5920. upb_handlers_setstartsubmsg(h, F(DescriptorProto, nested_type),
  5921. &msg_startmsg, NULL);
  5922. upb_handlers_setstartsubmsg(h, F(DescriptorProto, field),
  5923. &msg_startfield, NULL);
  5924. upb_handlers_setendsubmsg(h, F(DescriptorProto, field),
  5925. &msg_endfield, NULL);
  5926. upb_handlers_setstartsubmsg(h, F(DescriptorProto, enum_type),
  5927. &file_startenum, NULL);
  5928. } else if (upbdefs_google_protobuf_FileDescriptorProto_is(m)) {
  5929. upb_handlers_setstartmsg(h, &file_start, NULL);
  5930. upb_handlers_setendmsg(h, &file_end, NULL);
  5931. upb_handlers_setstring(h, F(FileDescriptorProto, name), &file_onname,
  5932. NULL);
  5933. upb_handlers_setstring(h, F(FileDescriptorProto, package), &file_onpackage,
  5934. NULL);
  5935. upb_handlers_setstring(h, F(FileDescriptorProto, syntax), &file_onsyntax,
  5936. NULL);
  5937. upb_handlers_setstartsubmsg(h, F(FileDescriptorProto, message_type),
  5938. &file_startmsg, NULL);
  5939. upb_handlers_setstartsubmsg(h, F(FileDescriptorProto, enum_type),
  5940. &file_startenum, NULL);
  5941. upb_handlers_setstartsubmsg(h, F(FileDescriptorProto, extension),
  5942. &file_startext, NULL);
  5943. } else if (upbdefs_google_protobuf_EnumValueDescriptorProto_is(m)) {
  5944. upb_handlers_setstartmsg(h, &enumval_startmsg, NULL);
  5945. upb_handlers_setendmsg(h, &enumval_endmsg, NULL);
  5946. upb_handlers_setstring(h, F(EnumValueDescriptorProto, name), &enumval_onname, NULL);
  5947. upb_handlers_setint32(h, F(EnumValueDescriptorProto, number), &enumval_onnumber,
  5948. NULL);
  5949. } else if (upbdefs_google_protobuf_EnumDescriptorProto_is(m)) {
  5950. upb_handlers_setendmsg(h, &enum_endmsg, NULL);
  5951. upb_handlers_setstring(h, F(EnumDescriptorProto, name), &enum_onname, NULL);
  5952. } else if (upbdefs_google_protobuf_FieldDescriptorProto_is(m)) {
  5953. upb_handlers_setstartmsg(h, &field_startmsg, NULL);
  5954. upb_handlers_setendmsg(h, &field_endmsg, NULL);
  5955. upb_handlers_setint32(h, F(FieldDescriptorProto, type), &field_ontype,
  5956. NULL);
  5957. upb_handlers_setint32(h, F(FieldDescriptorProto, label), &field_onlabel,
  5958. NULL);
  5959. upb_handlers_setint32(h, F(FieldDescriptorProto, number), &field_onnumber,
  5960. NULL);
  5961. upb_handlers_setstring(h, F(FieldDescriptorProto, name), &field_onname,
  5962. NULL);
  5963. upb_handlers_setstring(h, F(FieldDescriptorProto, type_name),
  5964. &field_ontypename, NULL);
  5965. upb_handlers_setstring(h, F(FieldDescriptorProto, extendee),
  5966. &field_onextendee, NULL);
  5967. upb_handlers_setstring(h, F(FieldDescriptorProto, default_value),
  5968. &field_ondefaultval, NULL);
  5969. } else if (upbdefs_google_protobuf_FieldOptions_is(m)) {
  5970. upb_handlers_setbool(h, F(FieldOptions, lazy), &field_onlazy, NULL);
  5971. upb_handlers_setbool(h, F(FieldOptions, packed), &field_onpacked, NULL);
  5972. }
  5973. assert(upb_ok(upb_handlers_status(h)));
  5974. }
  5975. #undef F
  5976. void descreader_cleanup(void *_r) {
  5977. upb_descreader *r = _r;
  5978. size_t i;
  5979. for (i = 0; i < upb_descreader_filecount(r); i++) {
  5980. upb_filedef_unref(upb_descreader_file(r, i), &r->files);
  5981. }
  5982. free(r->name);
  5983. upb_inttable_uninit(&r->files);
  5984. free(r->default_string);
  5985. while (r->stack_len > 0) {
  5986. upb_descreader_frame *f = &r->stack[--r->stack_len];
  5987. free(f->name);
  5988. }
  5989. }
  5990. /* Public API ****************************************************************/
  5991. upb_descreader *upb_descreader_create(upb_env *e, const upb_handlers *h) {
  5992. upb_descreader *r = upb_env_malloc(e, sizeof(upb_descreader));
  5993. if (!r || !upb_env_addcleanup(e, descreader_cleanup, r)) {
  5994. return NULL;
  5995. }
  5996. upb_inttable_init(&r->files, UPB_CTYPE_PTR);
  5997. upb_sink_reset(upb_descreader_input(r), h, r);
  5998. r->stack_len = 0;
  5999. r->name = NULL;
  6000. r->default_string = NULL;
  6001. return r;
  6002. }
  6003. size_t upb_descreader_filecount(const upb_descreader *r) {
  6004. return upb_inttable_count(&r->files);
  6005. }
  6006. upb_filedef *upb_descreader_file(const upb_descreader *r, size_t i) {
  6007. upb_value v;
  6008. if (upb_inttable_lookup(&r->files, i, &v)) {
  6009. return upb_value_getptr(v);
  6010. } else {
  6011. return NULL;
  6012. }
  6013. }
  6014. upb_sink *upb_descreader_input(upb_descreader *r) {
  6015. return &r->sink;
  6016. }
  6017. const upb_handlers *upb_descreader_newhandlers(const void *owner) {
  6018. const upb_msgdef *m = upbdefs_google_protobuf_FileDescriptorSet_get(&m);
  6019. const upb_handlers *h = upb_handlers_newfrozen(m, owner, reghandlers, NULL);
  6020. upb_msgdef_unref(m, &m);
  6021. return h;
  6022. }
  6023. /*
  6024. ** protobuf decoder bytecode compiler
  6025. **
  6026. ** Code to compile a upb::Handlers into bytecode for decoding a protobuf
  6027. ** according to that specific schema and destination handlers.
  6028. **
  6029. ** Compiling to bytecode is always the first step. If we are using the
  6030. ** interpreted decoder we leave it as bytecode and interpret that. If we are
  6031. ** using a JIT decoder we use a code generator to turn the bytecode into native
  6032. ** code, LLVM IR, etc.
  6033. **
  6034. ** Bytecode definition is in decoder.int.h.
  6035. */
  6036. #include <stdarg.h>
  6037. #ifdef UPB_DUMP_BYTECODE
  6038. #include <stdio.h>
  6039. #endif
  6040. #define MAXLABEL 5
  6041. #define EMPTYLABEL -1
  6042. /* mgroup *********************************************************************/
  6043. static void freegroup(upb_refcounted *r) {
  6044. mgroup *g = (mgroup*)r;
  6045. upb_inttable_uninit(&g->methods);
  6046. #ifdef UPB_USE_JIT_X64
  6047. upb_pbdecoder_freejit(g);
  6048. #endif
  6049. free(g->bytecode);
  6050. free(g);
  6051. }
  6052. static void visitgroup(const upb_refcounted *r, upb_refcounted_visit *visit,
  6053. void *closure) {
  6054. const mgroup *g = (const mgroup*)r;
  6055. upb_inttable_iter i;
  6056. upb_inttable_begin(&i, &g->methods);
  6057. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  6058. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  6059. visit(r, upb_pbdecodermethod_upcast(method), closure);
  6060. }
  6061. }
  6062. mgroup *newgroup(const void *owner) {
  6063. mgroup *g = malloc(sizeof(*g));
  6064. static const struct upb_refcounted_vtbl vtbl = {visitgroup, freegroup};
  6065. upb_refcounted_init(mgroup_upcast_mutable(g), &vtbl, owner);
  6066. upb_inttable_init(&g->methods, UPB_CTYPE_PTR);
  6067. g->bytecode = NULL;
  6068. g->bytecode_end = NULL;
  6069. return g;
  6070. }
  6071. /* upb_pbdecodermethod ********************************************************/
  6072. static void freemethod(upb_refcounted *r) {
  6073. upb_pbdecodermethod *method = (upb_pbdecodermethod*)r;
  6074. if (method->dest_handlers_) {
  6075. upb_handlers_unref(method->dest_handlers_, method);
  6076. }
  6077. upb_inttable_uninit(&method->dispatch);
  6078. free(method);
  6079. }
  6080. static void visitmethod(const upb_refcounted *r, upb_refcounted_visit *visit,
  6081. void *closure) {
  6082. const upb_pbdecodermethod *m = (const upb_pbdecodermethod*)r;
  6083. visit(r, m->group, closure);
  6084. }
  6085. static upb_pbdecodermethod *newmethod(const upb_handlers *dest_handlers,
  6086. mgroup *group) {
  6087. static const struct upb_refcounted_vtbl vtbl = {visitmethod, freemethod};
  6088. upb_pbdecodermethod *ret = malloc(sizeof(*ret));
  6089. upb_refcounted_init(upb_pbdecodermethod_upcast_mutable(ret), &vtbl, &ret);
  6090. upb_byteshandler_init(&ret->input_handler_);
  6091. /* The method references the group and vice-versa, in a circular reference. */
  6092. upb_ref2(ret, group);
  6093. upb_ref2(group, ret);
  6094. upb_inttable_insertptr(&group->methods, dest_handlers, upb_value_ptr(ret));
  6095. upb_pbdecodermethod_unref(ret, &ret);
  6096. ret->group = mgroup_upcast_mutable(group);
  6097. ret->dest_handlers_ = dest_handlers;
  6098. ret->is_native_ = false; /* If we JIT, it will update this later. */
  6099. upb_inttable_init(&ret->dispatch, UPB_CTYPE_UINT64);
  6100. if (ret->dest_handlers_) {
  6101. upb_handlers_ref(ret->dest_handlers_, ret);
  6102. }
  6103. return ret;
  6104. }
  6105. const upb_handlers *upb_pbdecodermethod_desthandlers(
  6106. const upb_pbdecodermethod *m) {
  6107. return m->dest_handlers_;
  6108. }
  6109. const upb_byteshandler *upb_pbdecodermethod_inputhandler(
  6110. const upb_pbdecodermethod *m) {
  6111. return &m->input_handler_;
  6112. }
  6113. bool upb_pbdecodermethod_isnative(const upb_pbdecodermethod *m) {
  6114. return m->is_native_;
  6115. }
  6116. const upb_pbdecodermethod *upb_pbdecodermethod_new(
  6117. const upb_pbdecodermethodopts *opts, const void *owner) {
  6118. const upb_pbdecodermethod *ret;
  6119. upb_pbcodecache cache;
  6120. upb_pbcodecache_init(&cache);
  6121. ret = upb_pbcodecache_getdecodermethod(&cache, opts);
  6122. upb_pbdecodermethod_ref(ret, owner);
  6123. upb_pbcodecache_uninit(&cache);
  6124. return ret;
  6125. }
  6126. /* bytecode compiler **********************************************************/
  6127. /* Data used only at compilation time. */
  6128. typedef struct {
  6129. mgroup *group;
  6130. uint32_t *pc;
  6131. int fwd_labels[MAXLABEL];
  6132. int back_labels[MAXLABEL];
  6133. /* For fields marked "lazy", parse them lazily or eagerly? */
  6134. bool lazy;
  6135. } compiler;
  6136. static compiler *newcompiler(mgroup *group, bool lazy) {
  6137. compiler *ret = malloc(sizeof(*ret));
  6138. int i;
  6139. ret->group = group;
  6140. ret->lazy = lazy;
  6141. for (i = 0; i < MAXLABEL; i++) {
  6142. ret->fwd_labels[i] = EMPTYLABEL;
  6143. ret->back_labels[i] = EMPTYLABEL;
  6144. }
  6145. return ret;
  6146. }
  6147. static void freecompiler(compiler *c) {
  6148. free(c);
  6149. }
  6150. const size_t ptr_words = sizeof(void*) / sizeof(uint32_t);
  6151. /* How many words an instruction is. */
  6152. static int instruction_len(uint32_t instr) {
  6153. switch (getop(instr)) {
  6154. case OP_SETDISPATCH: return 1 + ptr_words;
  6155. case OP_TAGN: return 3;
  6156. case OP_SETBIGGROUPNUM: return 2;
  6157. default: return 1;
  6158. }
  6159. }
  6160. bool op_has_longofs(int32_t instruction) {
  6161. switch (getop(instruction)) {
  6162. case OP_CALL:
  6163. case OP_BRANCH:
  6164. case OP_CHECKDELIM:
  6165. return true;
  6166. /* The "tag" instructions only have 8 bytes available for the jump target,
  6167. * but that is ok because these opcodes only require short jumps. */
  6168. case OP_TAG1:
  6169. case OP_TAG2:
  6170. case OP_TAGN:
  6171. return false;
  6172. default:
  6173. assert(false);
  6174. return false;
  6175. }
  6176. }
  6177. static int32_t getofs(uint32_t instruction) {
  6178. if (op_has_longofs(instruction)) {
  6179. return (int32_t)instruction >> 8;
  6180. } else {
  6181. return (int8_t)(instruction >> 8);
  6182. }
  6183. }
  6184. static void setofs(uint32_t *instruction, int32_t ofs) {
  6185. if (op_has_longofs(*instruction)) {
  6186. *instruction = getop(*instruction) | ofs << 8;
  6187. } else {
  6188. *instruction = (*instruction & ~0xff00) | ((ofs & 0xff) << 8);
  6189. }
  6190. assert(getofs(*instruction) == ofs); /* Would fail in cases of overflow. */
  6191. }
  6192. static uint32_t pcofs(compiler *c) { return c->pc - c->group->bytecode; }
  6193. /* Defines a local label at the current PC location. All previous forward
  6194. * references are updated to point to this location. The location is noted
  6195. * for any future backward references. */
  6196. static void label(compiler *c, unsigned int label) {
  6197. int val;
  6198. uint32_t *codep;
  6199. assert(label < MAXLABEL);
  6200. val = c->fwd_labels[label];
  6201. codep = (val == EMPTYLABEL) ? NULL : c->group->bytecode + val;
  6202. while (codep) {
  6203. int ofs = getofs(*codep);
  6204. setofs(codep, c->pc - codep - instruction_len(*codep));
  6205. codep = ofs ? codep + ofs : NULL;
  6206. }
  6207. c->fwd_labels[label] = EMPTYLABEL;
  6208. c->back_labels[label] = pcofs(c);
  6209. }
  6210. /* Creates a reference to a numbered label; either a forward reference
  6211. * (positive arg) or backward reference (negative arg). For forward references
  6212. * the value returned now is actually a "next" pointer into a linked list of all
  6213. * instructions that use this label and will be patched later when the label is
  6214. * defined with label().
  6215. *
  6216. * The returned value is the offset that should be written into the instruction.
  6217. */
  6218. static int32_t labelref(compiler *c, int label) {
  6219. assert(label < MAXLABEL);
  6220. if (label == LABEL_DISPATCH) {
  6221. /* No resolving required. */
  6222. return 0;
  6223. } else if (label < 0) {
  6224. /* Backward local label. Relative to the next instruction. */
  6225. uint32_t from = (c->pc + 1) - c->group->bytecode;
  6226. return c->back_labels[-label] - from;
  6227. } else {
  6228. /* Forward local label: prepend to (possibly-empty) linked list. */
  6229. int *lptr = &c->fwd_labels[label];
  6230. int32_t ret = (*lptr == EMPTYLABEL) ? 0 : *lptr - pcofs(c);
  6231. *lptr = pcofs(c);
  6232. return ret;
  6233. }
  6234. }
  6235. static void put32(compiler *c, uint32_t v) {
  6236. mgroup *g = c->group;
  6237. if (c->pc == g->bytecode_end) {
  6238. int ofs = pcofs(c);
  6239. size_t oldsize = g->bytecode_end - g->bytecode;
  6240. size_t newsize = UPB_MAX(oldsize * 2, 64);
  6241. /* TODO(haberman): handle OOM. */
  6242. g->bytecode = realloc(g->bytecode, newsize * sizeof(uint32_t));
  6243. g->bytecode_end = g->bytecode + newsize;
  6244. c->pc = g->bytecode + ofs;
  6245. }
  6246. *c->pc++ = v;
  6247. }
  6248. static void putop(compiler *c, opcode op, ...) {
  6249. va_list ap;
  6250. va_start(ap, op);
  6251. switch (op) {
  6252. case OP_SETDISPATCH: {
  6253. uintptr_t ptr = (uintptr_t)va_arg(ap, void*);
  6254. put32(c, OP_SETDISPATCH);
  6255. put32(c, ptr);
  6256. if (sizeof(uintptr_t) > sizeof(uint32_t))
  6257. put32(c, (uint64_t)ptr >> 32);
  6258. break;
  6259. }
  6260. case OP_STARTMSG:
  6261. case OP_ENDMSG:
  6262. case OP_PUSHLENDELIM:
  6263. case OP_POP:
  6264. case OP_SETDELIM:
  6265. case OP_HALT:
  6266. case OP_RET:
  6267. case OP_DISPATCH:
  6268. put32(c, op);
  6269. break;
  6270. case OP_PARSE_DOUBLE:
  6271. case OP_PARSE_FLOAT:
  6272. case OP_PARSE_INT64:
  6273. case OP_PARSE_UINT64:
  6274. case OP_PARSE_INT32:
  6275. case OP_PARSE_FIXED64:
  6276. case OP_PARSE_FIXED32:
  6277. case OP_PARSE_BOOL:
  6278. case OP_PARSE_UINT32:
  6279. case OP_PARSE_SFIXED32:
  6280. case OP_PARSE_SFIXED64:
  6281. case OP_PARSE_SINT32:
  6282. case OP_PARSE_SINT64:
  6283. case OP_STARTSEQ:
  6284. case OP_ENDSEQ:
  6285. case OP_STARTSUBMSG:
  6286. case OP_ENDSUBMSG:
  6287. case OP_STARTSTR:
  6288. case OP_STRING:
  6289. case OP_ENDSTR:
  6290. case OP_PUSHTAGDELIM:
  6291. put32(c, op | va_arg(ap, upb_selector_t) << 8);
  6292. break;
  6293. case OP_SETBIGGROUPNUM:
  6294. put32(c, op);
  6295. put32(c, va_arg(ap, int));
  6296. break;
  6297. case OP_CALL: {
  6298. const upb_pbdecodermethod *method = va_arg(ap, upb_pbdecodermethod *);
  6299. put32(c, op | (method->code_base.ofs - (pcofs(c) + 1)) << 8);
  6300. break;
  6301. }
  6302. case OP_CHECKDELIM:
  6303. case OP_BRANCH: {
  6304. uint32_t instruction = op;
  6305. int label = va_arg(ap, int);
  6306. setofs(&instruction, labelref(c, label));
  6307. put32(c, instruction);
  6308. break;
  6309. }
  6310. case OP_TAG1:
  6311. case OP_TAG2: {
  6312. int label = va_arg(ap, int);
  6313. uint64_t tag = va_arg(ap, uint64_t);
  6314. uint32_t instruction = op | (tag << 16);
  6315. assert(tag <= 0xffff);
  6316. setofs(&instruction, labelref(c, label));
  6317. put32(c, instruction);
  6318. break;
  6319. }
  6320. case OP_TAGN: {
  6321. int label = va_arg(ap, int);
  6322. uint64_t tag = va_arg(ap, uint64_t);
  6323. uint32_t instruction = op | (upb_value_size(tag) << 16);
  6324. setofs(&instruction, labelref(c, label));
  6325. put32(c, instruction);
  6326. put32(c, tag);
  6327. put32(c, tag >> 32);
  6328. break;
  6329. }
  6330. }
  6331. va_end(ap);
  6332. }
  6333. #if defined(UPB_USE_JIT_X64) || defined(UPB_DUMP_BYTECODE)
  6334. const char *upb_pbdecoder_getopname(unsigned int op) {
  6335. #define QUOTE(x) #x
  6336. #define EXPAND_AND_QUOTE(x) QUOTE(x)
  6337. #define OPNAME(x) OP_##x
  6338. #define OP(x) case OPNAME(x): return EXPAND_AND_QUOTE(OPNAME(x));
  6339. #define T(x) OP(PARSE_##x)
  6340. /* Keep in sync with list in decoder.int.h. */
  6341. switch ((opcode)op) {
  6342. T(DOUBLE) T(FLOAT) T(INT64) T(UINT64) T(INT32) T(FIXED64) T(FIXED32)
  6343. T(BOOL) T(UINT32) T(SFIXED32) T(SFIXED64) T(SINT32) T(SINT64)
  6344. OP(STARTMSG) OP(ENDMSG) OP(STARTSEQ) OP(ENDSEQ) OP(STARTSUBMSG)
  6345. OP(ENDSUBMSG) OP(STARTSTR) OP(STRING) OP(ENDSTR) OP(CALL) OP(RET)
  6346. OP(PUSHLENDELIM) OP(PUSHTAGDELIM) OP(SETDELIM) OP(CHECKDELIM)
  6347. OP(BRANCH) OP(TAG1) OP(TAG2) OP(TAGN) OP(SETDISPATCH) OP(POP)
  6348. OP(SETBIGGROUPNUM) OP(DISPATCH) OP(HALT)
  6349. }
  6350. return "<unknown op>";
  6351. #undef OP
  6352. #undef T
  6353. }
  6354. #endif
  6355. #ifdef UPB_DUMP_BYTECODE
  6356. static void dumpbc(uint32_t *p, uint32_t *end, FILE *f) {
  6357. uint32_t *begin = p;
  6358. while (p < end) {
  6359. fprintf(f, "%p %8tx", p, p - begin);
  6360. uint32_t instr = *p++;
  6361. uint8_t op = getop(instr);
  6362. fprintf(f, " %s", upb_pbdecoder_getopname(op));
  6363. switch ((opcode)op) {
  6364. case OP_SETDISPATCH: {
  6365. const upb_inttable *dispatch;
  6366. memcpy(&dispatch, p, sizeof(void*));
  6367. p += ptr_words;
  6368. const upb_pbdecodermethod *method =
  6369. (void *)((char *)dispatch -
  6370. offsetof(upb_pbdecodermethod, dispatch));
  6371. fprintf(f, " %s", upb_msgdef_fullname(
  6372. upb_handlers_msgdef(method->dest_handlers_)));
  6373. break;
  6374. }
  6375. case OP_DISPATCH:
  6376. case OP_STARTMSG:
  6377. case OP_ENDMSG:
  6378. case OP_PUSHLENDELIM:
  6379. case OP_POP:
  6380. case OP_SETDELIM:
  6381. case OP_HALT:
  6382. case OP_RET:
  6383. break;
  6384. case OP_PARSE_DOUBLE:
  6385. case OP_PARSE_FLOAT:
  6386. case OP_PARSE_INT64:
  6387. case OP_PARSE_UINT64:
  6388. case OP_PARSE_INT32:
  6389. case OP_PARSE_FIXED64:
  6390. case OP_PARSE_FIXED32:
  6391. case OP_PARSE_BOOL:
  6392. case OP_PARSE_UINT32:
  6393. case OP_PARSE_SFIXED32:
  6394. case OP_PARSE_SFIXED64:
  6395. case OP_PARSE_SINT32:
  6396. case OP_PARSE_SINT64:
  6397. case OP_STARTSEQ:
  6398. case OP_ENDSEQ:
  6399. case OP_STARTSUBMSG:
  6400. case OP_ENDSUBMSG:
  6401. case OP_STARTSTR:
  6402. case OP_STRING:
  6403. case OP_ENDSTR:
  6404. case OP_PUSHTAGDELIM:
  6405. fprintf(f, " %d", instr >> 8);
  6406. break;
  6407. case OP_SETBIGGROUPNUM:
  6408. fprintf(f, " %d", *p++);
  6409. break;
  6410. case OP_CHECKDELIM:
  6411. case OP_CALL:
  6412. case OP_BRANCH:
  6413. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  6414. break;
  6415. case OP_TAG1:
  6416. case OP_TAG2: {
  6417. fprintf(f, " tag:0x%x", instr >> 16);
  6418. if (getofs(instr)) {
  6419. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  6420. }
  6421. break;
  6422. }
  6423. case OP_TAGN: {
  6424. uint64_t tag = *p++;
  6425. tag |= (uint64_t)*p++ << 32;
  6426. fprintf(f, " tag:0x%llx", (long long)tag);
  6427. fprintf(f, " n:%d", instr >> 16);
  6428. if (getofs(instr)) {
  6429. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  6430. }
  6431. break;
  6432. }
  6433. }
  6434. fputs("\n", f);
  6435. }
  6436. }
  6437. #endif
  6438. static uint64_t get_encoded_tag(const upb_fielddef *f, int wire_type) {
  6439. uint32_t tag = (upb_fielddef_number(f) << 3) | wire_type;
  6440. uint64_t encoded_tag = upb_vencode32(tag);
  6441. /* No tag should be greater than 5 bytes. */
  6442. assert(encoded_tag <= 0xffffffffff);
  6443. return encoded_tag;
  6444. }
  6445. static void putchecktag(compiler *c, const upb_fielddef *f,
  6446. int wire_type, int dest) {
  6447. uint64_t tag = get_encoded_tag(f, wire_type);
  6448. switch (upb_value_size(tag)) {
  6449. case 1:
  6450. putop(c, OP_TAG1, dest, tag);
  6451. break;
  6452. case 2:
  6453. putop(c, OP_TAG2, dest, tag);
  6454. break;
  6455. default:
  6456. putop(c, OP_TAGN, dest, tag);
  6457. break;
  6458. }
  6459. }
  6460. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  6461. upb_selector_t selector;
  6462. bool ok = upb_handlers_getselector(f, type, &selector);
  6463. UPB_ASSERT_VAR(ok, ok);
  6464. return selector;
  6465. }
  6466. /* Takes an existing, primary dispatch table entry and repacks it with a
  6467. * different alternate wire type. Called when we are inserting a secondary
  6468. * dispatch table entry for an alternate wire type. */
  6469. static uint64_t repack(uint64_t dispatch, int new_wt2) {
  6470. uint64_t ofs;
  6471. uint8_t wt1;
  6472. uint8_t old_wt2;
  6473. upb_pbdecoder_unpackdispatch(dispatch, &ofs, &wt1, &old_wt2);
  6474. assert(old_wt2 == NO_WIRE_TYPE); /* wt2 should not be set yet. */
  6475. return upb_pbdecoder_packdispatch(ofs, wt1, new_wt2);
  6476. }
  6477. /* Marks the current bytecode position as the dispatch target for this message,
  6478. * field, and wire type. */
  6479. static void dispatchtarget(compiler *c, upb_pbdecodermethod *method,
  6480. const upb_fielddef *f, int wire_type) {
  6481. /* Offset is relative to msg base. */
  6482. uint64_t ofs = pcofs(c) - method->code_base.ofs;
  6483. uint32_t fn = upb_fielddef_number(f);
  6484. upb_inttable *d = &method->dispatch;
  6485. upb_value v;
  6486. if (upb_inttable_remove(d, fn, &v)) {
  6487. /* TODO: prioritize based on packed setting in .proto file. */
  6488. uint64_t repacked = repack(upb_value_getuint64(v), wire_type);
  6489. upb_inttable_insert(d, fn, upb_value_uint64(repacked));
  6490. upb_inttable_insert(d, fn + UPB_MAX_FIELDNUMBER, upb_value_uint64(ofs));
  6491. } else {
  6492. uint64_t val = upb_pbdecoder_packdispatch(ofs, wire_type, NO_WIRE_TYPE);
  6493. upb_inttable_insert(d, fn, upb_value_uint64(val));
  6494. }
  6495. }
  6496. static void putpush(compiler *c, const upb_fielddef *f) {
  6497. if (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE) {
  6498. putop(c, OP_PUSHLENDELIM);
  6499. } else {
  6500. uint32_t fn = upb_fielddef_number(f);
  6501. if (fn >= 1 << 24) {
  6502. putop(c, OP_PUSHTAGDELIM, 0);
  6503. putop(c, OP_SETBIGGROUPNUM, fn);
  6504. } else {
  6505. putop(c, OP_PUSHTAGDELIM, fn);
  6506. }
  6507. }
  6508. }
  6509. static upb_pbdecodermethod *find_submethod(const compiler *c,
  6510. const upb_pbdecodermethod *method,
  6511. const upb_fielddef *f) {
  6512. const upb_handlers *sub =
  6513. upb_handlers_getsubhandlers(method->dest_handlers_, f);
  6514. upb_value v;
  6515. return upb_inttable_lookupptr(&c->group->methods, sub, &v)
  6516. ? upb_value_getptr(v)
  6517. : NULL;
  6518. }
  6519. static void putsel(compiler *c, opcode op, upb_selector_t sel,
  6520. const upb_handlers *h) {
  6521. if (upb_handlers_gethandler(h, sel)) {
  6522. putop(c, op, sel);
  6523. }
  6524. }
  6525. /* Puts an opcode to call a callback, but only if a callback actually exists for
  6526. * this field and handler type. */
  6527. static void maybeput(compiler *c, opcode op, const upb_handlers *h,
  6528. const upb_fielddef *f, upb_handlertype_t type) {
  6529. putsel(c, op, getsel(f, type), h);
  6530. }
  6531. static bool haslazyhandlers(const upb_handlers *h, const upb_fielddef *f) {
  6532. if (!upb_fielddef_lazy(f))
  6533. return false;
  6534. return upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STARTSTR)) ||
  6535. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STRING)) ||
  6536. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_ENDSTR));
  6537. }
  6538. /* bytecode compiler code generation ******************************************/
  6539. /* Symbolic names for our local labels. */
  6540. #define LABEL_LOOPSTART 1 /* Top of a repeated field loop. */
  6541. #define LABEL_LOOPBREAK 2 /* To jump out of a repeated loop */
  6542. #define LABEL_FIELD 3 /* Jump backward to find the most recent field. */
  6543. #define LABEL_ENDMSG 4 /* To reach the OP_ENDMSG instr for this msg. */
  6544. /* Generates bytecode to parse a single non-lazy message field. */
  6545. static void generate_msgfield(compiler *c, const upb_fielddef *f,
  6546. upb_pbdecodermethod *method) {
  6547. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  6548. const upb_pbdecodermethod *sub_m = find_submethod(c, method, f);
  6549. int wire_type;
  6550. if (!sub_m) {
  6551. /* Don't emit any code for this field at all; it will be parsed as an
  6552. * unknown field.
  6553. *
  6554. * TODO(haberman): we should change this to parse it as a string field
  6555. * instead. It will probably be faster, but more importantly, once we
  6556. * start vending unknown fields, a field shouldn't be treated as unknown
  6557. * just because it doesn't have subhandlers registered. */
  6558. return;
  6559. }
  6560. label(c, LABEL_FIELD);
  6561. wire_type =
  6562. (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE)
  6563. ? UPB_WIRE_TYPE_DELIMITED
  6564. : UPB_WIRE_TYPE_START_GROUP;
  6565. if (upb_fielddef_isseq(f)) {
  6566. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6567. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  6568. dispatchtarget(c, method, f, wire_type);
  6569. putop(c, OP_PUSHTAGDELIM, 0);
  6570. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  6571. label(c, LABEL_LOOPSTART);
  6572. putpush(c, f);
  6573. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  6574. putop(c, OP_CALL, sub_m);
  6575. putop(c, OP_POP);
  6576. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  6577. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  6578. putop(c, OP_SETDELIM);
  6579. }
  6580. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  6581. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  6582. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  6583. label(c, LABEL_LOOPBREAK);
  6584. putop(c, OP_POP);
  6585. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  6586. } else {
  6587. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6588. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  6589. dispatchtarget(c, method, f, wire_type);
  6590. putpush(c, f);
  6591. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  6592. putop(c, OP_CALL, sub_m);
  6593. putop(c, OP_POP);
  6594. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  6595. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  6596. putop(c, OP_SETDELIM);
  6597. }
  6598. }
  6599. }
  6600. /* Generates bytecode to parse a single string or lazy submessage field. */
  6601. static void generate_delimfield(compiler *c, const upb_fielddef *f,
  6602. upb_pbdecodermethod *method) {
  6603. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  6604. label(c, LABEL_FIELD);
  6605. if (upb_fielddef_isseq(f)) {
  6606. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6607. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  6608. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  6609. putop(c, OP_PUSHTAGDELIM, 0);
  6610. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  6611. label(c, LABEL_LOOPSTART);
  6612. putop(c, OP_PUSHLENDELIM);
  6613. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  6614. /* Need to emit even if no handler to skip past the string. */
  6615. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  6616. putop(c, OP_POP);
  6617. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  6618. putop(c, OP_SETDELIM);
  6619. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  6620. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_LOOPBREAK);
  6621. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  6622. label(c, LABEL_LOOPBREAK);
  6623. putop(c, OP_POP);
  6624. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  6625. } else {
  6626. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6627. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  6628. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  6629. putop(c, OP_PUSHLENDELIM);
  6630. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  6631. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  6632. putop(c, OP_POP);
  6633. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  6634. putop(c, OP_SETDELIM);
  6635. }
  6636. }
  6637. /* Generates bytecode to parse a single primitive field. */
  6638. static void generate_primitivefield(compiler *c, const upb_fielddef *f,
  6639. upb_pbdecodermethod *method) {
  6640. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  6641. upb_descriptortype_t descriptor_type = upb_fielddef_descriptortype(f);
  6642. opcode parse_type;
  6643. upb_selector_t sel;
  6644. int wire_type;
  6645. label(c, LABEL_FIELD);
  6646. /* From a decoding perspective, ENUM is the same as INT32. */
  6647. if (descriptor_type == UPB_DESCRIPTOR_TYPE_ENUM)
  6648. descriptor_type = UPB_DESCRIPTOR_TYPE_INT32;
  6649. parse_type = (opcode)descriptor_type;
  6650. /* TODO(haberman): generate packed or non-packed first depending on "packed"
  6651. * setting in the fielddef. This will favor (in speed) whichever was
  6652. * specified. */
  6653. assert((int)parse_type >= 0 && parse_type <= OP_MAX);
  6654. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  6655. wire_type = upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  6656. if (upb_fielddef_isseq(f)) {
  6657. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6658. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  6659. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  6660. putop(c, OP_PUSHLENDELIM);
  6661. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Packed */
  6662. label(c, LABEL_LOOPSTART);
  6663. putop(c, parse_type, sel);
  6664. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  6665. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  6666. dispatchtarget(c, method, f, wire_type);
  6667. putop(c, OP_PUSHTAGDELIM, 0);
  6668. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Non-packed */
  6669. label(c, LABEL_LOOPSTART);
  6670. putop(c, parse_type, sel);
  6671. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  6672. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  6673. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  6674. label(c, LABEL_LOOPBREAK);
  6675. putop(c, OP_POP); /* Packed and non-packed join. */
  6676. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  6677. putop(c, OP_SETDELIM); /* Could remove for non-packed by dup ENDSEQ. */
  6678. } else {
  6679. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6680. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  6681. dispatchtarget(c, method, f, wire_type);
  6682. putop(c, parse_type, sel);
  6683. }
  6684. }
  6685. /* Adds bytecode for parsing the given message to the given decoderplan,
  6686. * while adding all dispatch targets to this message's dispatch table. */
  6687. static void compile_method(compiler *c, upb_pbdecodermethod *method) {
  6688. const upb_handlers *h;
  6689. const upb_msgdef *md;
  6690. uint32_t* start_pc;
  6691. upb_msg_field_iter i;
  6692. upb_value val;
  6693. assert(method);
  6694. /* Clear all entries in the dispatch table. */
  6695. upb_inttable_uninit(&method->dispatch);
  6696. upb_inttable_init(&method->dispatch, UPB_CTYPE_UINT64);
  6697. h = upb_pbdecodermethod_desthandlers(method);
  6698. md = upb_handlers_msgdef(h);
  6699. method->code_base.ofs = pcofs(c);
  6700. putop(c, OP_SETDISPATCH, &method->dispatch);
  6701. putsel(c, OP_STARTMSG, UPB_STARTMSG_SELECTOR, h);
  6702. label(c, LABEL_FIELD);
  6703. start_pc = c->pc;
  6704. for(upb_msg_field_begin(&i, md);
  6705. !upb_msg_field_done(&i);
  6706. upb_msg_field_next(&i)) {
  6707. const upb_fielddef *f = upb_msg_iter_field(&i);
  6708. upb_fieldtype_t type = upb_fielddef_type(f);
  6709. if (type == UPB_TYPE_MESSAGE && !(haslazyhandlers(h, f) && c->lazy)) {
  6710. generate_msgfield(c, f, method);
  6711. } else if (type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES ||
  6712. type == UPB_TYPE_MESSAGE) {
  6713. generate_delimfield(c, f, method);
  6714. } else {
  6715. generate_primitivefield(c, f, method);
  6716. }
  6717. }
  6718. /* If there were no fields, or if no handlers were defined, we need to
  6719. * generate a non-empty loop body so that we can at least dispatch for unknown
  6720. * fields and check for the end of the message. */
  6721. if (c->pc == start_pc) {
  6722. /* Check for end-of-message. */
  6723. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6724. /* Unconditionally dispatch. */
  6725. putop(c, OP_DISPATCH, 0);
  6726. }
  6727. /* For now we just loop back to the last field of the message (or if none,
  6728. * the DISPATCH opcode for the message). */
  6729. putop(c, OP_BRANCH, -LABEL_FIELD);
  6730. /* Insert both a label and a dispatch table entry for this end-of-msg. */
  6731. label(c, LABEL_ENDMSG);
  6732. val = upb_value_uint64(pcofs(c) - method->code_base.ofs);
  6733. upb_inttable_insert(&method->dispatch, DISPATCH_ENDMSG, val);
  6734. putsel(c, OP_ENDMSG, UPB_ENDMSG_SELECTOR, h);
  6735. putop(c, OP_RET);
  6736. upb_inttable_compact(&method->dispatch);
  6737. }
  6738. /* Populate "methods" with new upb_pbdecodermethod objects reachable from "h".
  6739. * Returns the method for these handlers.
  6740. *
  6741. * Generates a new method for every destination handlers reachable from "h". */
  6742. static void find_methods(compiler *c, const upb_handlers *h) {
  6743. upb_value v;
  6744. upb_msg_field_iter i;
  6745. const upb_msgdef *md;
  6746. if (upb_inttable_lookupptr(&c->group->methods, h, &v))
  6747. return;
  6748. newmethod(h, c->group);
  6749. /* Find submethods. */
  6750. md = upb_handlers_msgdef(h);
  6751. for(upb_msg_field_begin(&i, md);
  6752. !upb_msg_field_done(&i);
  6753. upb_msg_field_next(&i)) {
  6754. const upb_fielddef *f = upb_msg_iter_field(&i);
  6755. const upb_handlers *sub_h;
  6756. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  6757. (sub_h = upb_handlers_getsubhandlers(h, f)) != NULL) {
  6758. /* We only generate a decoder method for submessages with handlers.
  6759. * Others will be parsed as unknown fields. */
  6760. find_methods(c, sub_h);
  6761. }
  6762. }
  6763. }
  6764. /* (Re-)compile bytecode for all messages in "msgs."
  6765. * Overwrites any existing bytecode in "c". */
  6766. static void compile_methods(compiler *c) {
  6767. upb_inttable_iter i;
  6768. /* Start over at the beginning of the bytecode. */
  6769. c->pc = c->group->bytecode;
  6770. upb_inttable_begin(&i, &c->group->methods);
  6771. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  6772. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  6773. compile_method(c, method);
  6774. }
  6775. }
  6776. static void set_bytecode_handlers(mgroup *g) {
  6777. upb_inttable_iter i;
  6778. upb_inttable_begin(&i, &g->methods);
  6779. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  6780. upb_pbdecodermethod *m = upb_value_getptr(upb_inttable_iter_value(&i));
  6781. upb_byteshandler *h = &m->input_handler_;
  6782. m->code_base.ptr = g->bytecode + m->code_base.ofs;
  6783. upb_byteshandler_setstartstr(h, upb_pbdecoder_startbc, m->code_base.ptr);
  6784. upb_byteshandler_setstring(h, upb_pbdecoder_decode, g);
  6785. upb_byteshandler_setendstr(h, upb_pbdecoder_end, m);
  6786. }
  6787. }
  6788. /* JIT setup. *****************************************************************/
  6789. #ifdef UPB_USE_JIT_X64
  6790. static void sethandlers(mgroup *g, bool allowjit) {
  6791. g->jit_code = NULL;
  6792. if (allowjit) {
  6793. /* Compile byte-code into machine code, create handlers. */
  6794. upb_pbdecoder_jit(g);
  6795. } else {
  6796. set_bytecode_handlers(g);
  6797. }
  6798. }
  6799. #else /* UPB_USE_JIT_X64 */
  6800. static void sethandlers(mgroup *g, bool allowjit) {
  6801. /* No JIT compiled in; use bytecode handlers unconditionally. */
  6802. UPB_UNUSED(allowjit);
  6803. set_bytecode_handlers(g);
  6804. }
  6805. #endif /* UPB_USE_JIT_X64 */
  6806. /* TODO(haberman): allow this to be constructed for an arbitrary set of dest
  6807. * handlers and other mgroups (but verify we have a transitive closure). */
  6808. const mgroup *mgroup_new(const upb_handlers *dest, bool allowjit, bool lazy,
  6809. const void *owner) {
  6810. mgroup *g;
  6811. compiler *c;
  6812. UPB_UNUSED(allowjit);
  6813. assert(upb_handlers_isfrozen(dest));
  6814. g = newgroup(owner);
  6815. c = newcompiler(g, lazy);
  6816. find_methods(c, dest);
  6817. /* We compile in two passes:
  6818. * 1. all messages are assigned relative offsets from the beginning of the
  6819. * bytecode (saved in method->code_base).
  6820. * 2. forwards OP_CALL instructions can be correctly linked since message
  6821. * offsets have been previously assigned.
  6822. *
  6823. * Could avoid the second pass by linking OP_CALL instructions somehow. */
  6824. compile_methods(c);
  6825. compile_methods(c);
  6826. g->bytecode_end = c->pc;
  6827. freecompiler(c);
  6828. #ifdef UPB_DUMP_BYTECODE
  6829. {
  6830. FILE *f = fopen("/tmp/upb-bytecode", "w");
  6831. assert(f);
  6832. dumpbc(g->bytecode, g->bytecode_end, stderr);
  6833. dumpbc(g->bytecode, g->bytecode_end, f);
  6834. fclose(f);
  6835. f = fopen("/tmp/upb-bytecode.bin", "wb");
  6836. assert(f);
  6837. fwrite(g->bytecode, 1, g->bytecode_end - g->bytecode, f);
  6838. fclose(f);
  6839. }
  6840. #endif
  6841. sethandlers(g, allowjit);
  6842. return g;
  6843. }
  6844. /* upb_pbcodecache ************************************************************/
  6845. void upb_pbcodecache_init(upb_pbcodecache *c) {
  6846. upb_inttable_init(&c->groups, UPB_CTYPE_CONSTPTR);
  6847. c->allow_jit_ = true;
  6848. }
  6849. void upb_pbcodecache_uninit(upb_pbcodecache *c) {
  6850. upb_inttable_iter i;
  6851. upb_inttable_begin(&i, &c->groups);
  6852. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  6853. const mgroup *group = upb_value_getconstptr(upb_inttable_iter_value(&i));
  6854. mgroup_unref(group, c);
  6855. }
  6856. upb_inttable_uninit(&c->groups);
  6857. }
  6858. bool upb_pbcodecache_allowjit(const upb_pbcodecache *c) {
  6859. return c->allow_jit_;
  6860. }
  6861. bool upb_pbcodecache_setallowjit(upb_pbcodecache *c, bool allow) {
  6862. if (upb_inttable_count(&c->groups) > 0)
  6863. return false;
  6864. c->allow_jit_ = allow;
  6865. return true;
  6866. }
  6867. const upb_pbdecodermethod *upb_pbcodecache_getdecodermethod(
  6868. upb_pbcodecache *c, const upb_pbdecodermethodopts *opts) {
  6869. upb_value v;
  6870. bool ok;
  6871. /* Right now we build a new DecoderMethod every time.
  6872. * TODO(haberman): properly cache methods by their true key. */
  6873. const mgroup *g = mgroup_new(opts->handlers, c->allow_jit_, opts->lazy, c);
  6874. upb_inttable_push(&c->groups, upb_value_constptr(g));
  6875. ok = upb_inttable_lookupptr(&g->methods, opts->handlers, &v);
  6876. UPB_ASSERT_VAR(ok, ok);
  6877. return upb_value_getptr(v);
  6878. }
  6879. /* upb_pbdecodermethodopts ****************************************************/
  6880. void upb_pbdecodermethodopts_init(upb_pbdecodermethodopts *opts,
  6881. const upb_handlers *h) {
  6882. opts->handlers = h;
  6883. opts->lazy = false;
  6884. }
  6885. void upb_pbdecodermethodopts_setlazy(upb_pbdecodermethodopts *opts, bool lazy) {
  6886. opts->lazy = lazy;
  6887. }
  6888. /*
  6889. ** upb::Decoder (Bytecode Decoder VM)
  6890. **
  6891. ** Bytecode must previously have been generated using the bytecode compiler in
  6892. ** compile_decoder.c. This decoder then walks through the bytecode op-by-op to
  6893. ** parse the input.
  6894. **
  6895. ** Decoding is fully resumable; we just keep a pointer to the current bytecode
  6896. ** instruction and resume from there. A fair amount of the logic here is to
  6897. ** handle the fact that values can span buffer seams and we have to be able to
  6898. ** be capable of suspending/resuming from any byte in the stream. This
  6899. ** sometimes requires keeping a few trailing bytes from the last buffer around
  6900. ** in the "residual" buffer.
  6901. */
  6902. #include <inttypes.h>
  6903. #include <stddef.h>
  6904. #ifdef UPB_DUMP_BYTECODE
  6905. #include <stdio.h>
  6906. #endif
  6907. #define CHECK_SUSPEND(x) if (!(x)) return upb_pbdecoder_suspend(d);
  6908. /* Error messages that are shared between the bytecode and JIT decoders. */
  6909. const char *kPbDecoderStackOverflow = "Nesting too deep.";
  6910. const char *kPbDecoderSubmessageTooLong =
  6911. "Submessage end extends past enclosing submessage.";
  6912. /* Error messages shared within this file. */
  6913. static const char *kUnterminatedVarint = "Unterminated varint.";
  6914. /* upb_pbdecoder **************************************************************/
  6915. static opcode halt = OP_HALT;
  6916. /* A dummy character we can point to when the user passes us a NULL buffer.
  6917. * We need this because in C (NULL + 0) and (NULL - NULL) are undefined
  6918. * behavior, which would invalidate functions like curbufleft(). */
  6919. static const char dummy_char;
  6920. /* Whether an op consumes any of the input buffer. */
  6921. static bool consumes_input(opcode op) {
  6922. switch (op) {
  6923. case OP_SETDISPATCH:
  6924. case OP_STARTMSG:
  6925. case OP_ENDMSG:
  6926. case OP_STARTSEQ:
  6927. case OP_ENDSEQ:
  6928. case OP_STARTSUBMSG:
  6929. case OP_ENDSUBMSG:
  6930. case OP_STARTSTR:
  6931. case OP_ENDSTR:
  6932. case OP_PUSHTAGDELIM:
  6933. case OP_POP:
  6934. case OP_SETDELIM:
  6935. case OP_SETBIGGROUPNUM:
  6936. case OP_CHECKDELIM:
  6937. case OP_CALL:
  6938. case OP_RET:
  6939. case OP_BRANCH:
  6940. return false;
  6941. default:
  6942. return true;
  6943. }
  6944. }
  6945. static size_t stacksize(upb_pbdecoder *d, size_t entries) {
  6946. UPB_UNUSED(d);
  6947. return entries * sizeof(upb_pbdecoder_frame);
  6948. }
  6949. static size_t callstacksize(upb_pbdecoder *d, size_t entries) {
  6950. UPB_UNUSED(d);
  6951. #ifdef UPB_USE_JIT_X64
  6952. if (d->method_->is_native_) {
  6953. /* Each native stack frame needs two pointers, plus we need a few frames for
  6954. * the enter/exit trampolines. */
  6955. size_t ret = entries * sizeof(void*) * 2;
  6956. ret += sizeof(void*) * 10;
  6957. return ret;
  6958. }
  6959. #endif
  6960. return entries * sizeof(uint32_t*);
  6961. }
  6962. static bool in_residual_buf(const upb_pbdecoder *d, const char *p);
  6963. /* It's unfortunate that we have to micro-manage the compiler with
  6964. * UPB_FORCEINLINE and UPB_NOINLINE, especially since this tuning is necessarily
  6965. * specific to one hardware configuration. But empirically on a Core i7,
  6966. * performance increases 30-50% with these annotations. Every instance where
  6967. * these appear, gcc 4.2.1 made the wrong decision and degraded performance in
  6968. * benchmarks. */
  6969. static void seterr(upb_pbdecoder *d, const char *msg) {
  6970. upb_status status = UPB_STATUS_INIT;
  6971. upb_status_seterrmsg(&status, msg);
  6972. upb_env_reporterror(d->env, &status);
  6973. }
  6974. void upb_pbdecoder_seterr(upb_pbdecoder *d, const char *msg) {
  6975. seterr(d, msg);
  6976. }
  6977. /* Buffering ******************************************************************/
  6978. /* We operate on one buffer at a time, which is either the user's buffer passed
  6979. * to our "decode" callback or some residual bytes from the previous buffer. */
  6980. /* How many bytes can be safely read from d->ptr without reading past end-of-buf
  6981. * or past the current delimited end. */
  6982. static size_t curbufleft(const upb_pbdecoder *d) {
  6983. assert(d->data_end >= d->ptr);
  6984. return d->data_end - d->ptr;
  6985. }
  6986. /* How many bytes are available before end-of-buffer. */
  6987. static size_t bufleft(const upb_pbdecoder *d) {
  6988. return d->end - d->ptr;
  6989. }
  6990. /* Overall stream offset of d->ptr. */
  6991. uint64_t offset(const upb_pbdecoder *d) {
  6992. return d->bufstart_ofs + (d->ptr - d->buf);
  6993. }
  6994. /* How many bytes are available before the end of this delimited region. */
  6995. size_t delim_remaining(const upb_pbdecoder *d) {
  6996. return d->top->end_ofs - offset(d);
  6997. }
  6998. /* Advances d->ptr. */
  6999. static void advance(upb_pbdecoder *d, size_t len) {
  7000. assert(curbufleft(d) >= len);
  7001. d->ptr += len;
  7002. }
  7003. static bool in_buf(const char *p, const char *buf, const char *end) {
  7004. return p >= buf && p <= end;
  7005. }
  7006. static bool in_residual_buf(const upb_pbdecoder *d, const char *p) {
  7007. return in_buf(p, d->residual, d->residual_end);
  7008. }
  7009. /* Calculates the delim_end value, which is affected by both the current buffer
  7010. * and the parsing stack, so must be called whenever either is updated. */
  7011. static void set_delim_end(upb_pbdecoder *d) {
  7012. size_t delim_ofs = d->top->end_ofs - d->bufstart_ofs;
  7013. if (delim_ofs <= (size_t)(d->end - d->buf)) {
  7014. d->delim_end = d->buf + delim_ofs;
  7015. d->data_end = d->delim_end;
  7016. } else {
  7017. d->data_end = d->end;
  7018. d->delim_end = NULL;
  7019. }
  7020. }
  7021. static void switchtobuf(upb_pbdecoder *d, const char *buf, const char *end) {
  7022. d->ptr = buf;
  7023. d->buf = buf;
  7024. d->end = end;
  7025. set_delim_end(d);
  7026. }
  7027. static void advancetobuf(upb_pbdecoder *d, const char *buf, size_t len) {
  7028. assert(curbufleft(d) == 0);
  7029. d->bufstart_ofs += (d->end - d->buf);
  7030. switchtobuf(d, buf, buf + len);
  7031. }
  7032. static void checkpoint(upb_pbdecoder *d) {
  7033. /* The assertion here is in the interests of efficiency, not correctness.
  7034. * We are trying to ensure that we don't checkpoint() more often than
  7035. * necessary. */
  7036. assert(d->checkpoint != d->ptr);
  7037. d->checkpoint = d->ptr;
  7038. }
  7039. /* Skips "bytes" bytes in the stream, which may be more than available. If we
  7040. * skip more bytes than are available, we return a long read count to the caller
  7041. * indicating how many bytes can be skipped over before passing actual data
  7042. * again. Skipped bytes can pass a NULL buffer and the decoder guarantees they
  7043. * won't actually be read.
  7044. */
  7045. static int32_t skip(upb_pbdecoder *d, size_t bytes) {
  7046. assert(!in_residual_buf(d, d->ptr) || d->size_param == 0);
  7047. assert(d->skip == 0);
  7048. if (bytes > delim_remaining(d)) {
  7049. seterr(d, "Skipped value extended beyond enclosing submessage.");
  7050. return upb_pbdecoder_suspend(d);
  7051. } else if (bufleft(d) >= bytes) {
  7052. /* Skipped data is all in current buffer, and more is still available. */
  7053. advance(d, bytes);
  7054. d->skip = 0;
  7055. return DECODE_OK;
  7056. } else {
  7057. /* Skipped data extends beyond currently available buffers. */
  7058. d->pc = d->last;
  7059. d->skip = bytes - curbufleft(d);
  7060. d->bufstart_ofs += (d->end - d->buf);
  7061. d->residual_end = d->residual;
  7062. switchtobuf(d, d->residual, d->residual_end);
  7063. return d->size_param + d->skip;
  7064. }
  7065. }
  7066. /* Resumes the decoder from an initial state or from a previous suspend. */
  7067. int32_t upb_pbdecoder_resume(upb_pbdecoder *d, void *p, const char *buf,
  7068. size_t size, const upb_bufhandle *handle) {
  7069. UPB_UNUSED(p); /* Useless; just for the benefit of the JIT. */
  7070. /* d->skip and d->residual_end could probably elegantly be represented
  7071. * as a single variable, to more easily represent this invariant. */
  7072. assert(!(d->skip && d->residual_end > d->residual));
  7073. /* We need to remember the original size_param, so that the value we return
  7074. * is relative to it, even if we do some skipping first. */
  7075. d->size_param = size;
  7076. d->handle = handle;
  7077. /* Have to handle this case specially (ie. not with skip()) because the user
  7078. * is allowed to pass a NULL buffer here, which won't allow us to safely
  7079. * calculate a d->end or use our normal functions like curbufleft(). */
  7080. if (d->skip && d->skip >= size) {
  7081. d->skip -= size;
  7082. d->bufstart_ofs += size;
  7083. buf = &dummy_char;
  7084. size = 0;
  7085. /* We can't just return now, because we might need to execute some ops
  7086. * like CHECKDELIM, which could call some callbacks and pop the stack. */
  7087. }
  7088. /* We need to pretend that this was the actual buffer param, since some of the
  7089. * calculations assume that d->ptr/d->buf is relative to this. */
  7090. d->buf_param = buf;
  7091. if (!buf) {
  7092. /* NULL buf is ok if its entire span is covered by the "skip" above, but
  7093. * by this point we know that "skip" doesn't cover the buffer. */
  7094. seterr(d, "Passed NULL buffer over non-skippable region.");
  7095. return upb_pbdecoder_suspend(d);
  7096. }
  7097. if (d->residual_end > d->residual) {
  7098. /* We have residual bytes from the last buffer. */
  7099. assert(d->ptr == d->residual);
  7100. } else {
  7101. switchtobuf(d, buf, buf + size);
  7102. }
  7103. d->checkpoint = d->ptr;
  7104. /* Handle skips that don't cover the whole buffer (as above). */
  7105. if (d->skip) {
  7106. size_t skip_bytes = d->skip;
  7107. d->skip = 0;
  7108. CHECK_RETURN(skip(d, skip_bytes));
  7109. checkpoint(d);
  7110. }
  7111. /* If we're inside an unknown group, continue to parse unknown values. */
  7112. if (d->top->groupnum < 0) {
  7113. CHECK_RETURN(upb_pbdecoder_skipunknown(d, -1, 0));
  7114. checkpoint(d);
  7115. }
  7116. return DECODE_OK;
  7117. }
  7118. /* Suspends the decoder at the last checkpoint, without saving any residual
  7119. * bytes. If there are any unconsumed bytes, returns a short byte count. */
  7120. size_t upb_pbdecoder_suspend(upb_pbdecoder *d) {
  7121. d->pc = d->last;
  7122. if (d->checkpoint == d->residual) {
  7123. /* Checkpoint was in residual buf; no user bytes were consumed. */
  7124. d->ptr = d->residual;
  7125. return 0;
  7126. } else {
  7127. size_t ret = d->size_param - (d->end - d->checkpoint);
  7128. assert(!in_residual_buf(d, d->checkpoint));
  7129. assert(d->buf == d->buf_param || d->buf == &dummy_char);
  7130. d->bufstart_ofs += (d->checkpoint - d->buf);
  7131. d->residual_end = d->residual;
  7132. switchtobuf(d, d->residual, d->residual_end);
  7133. return ret;
  7134. }
  7135. }
  7136. /* Suspends the decoder at the last checkpoint, and saves any unconsumed
  7137. * bytes in our residual buffer. This is necessary if we need more user
  7138. * bytes to form a complete value, which might not be contiguous in the
  7139. * user's buffers. Always consumes all user bytes. */
  7140. static size_t suspend_save(upb_pbdecoder *d) {
  7141. /* We hit end-of-buffer before we could parse a full value.
  7142. * Save any unconsumed bytes (if any) to the residual buffer. */
  7143. d->pc = d->last;
  7144. if (d->checkpoint == d->residual) {
  7145. /* Checkpoint was in residual buf; append user byte(s) to residual buf. */
  7146. assert((d->residual_end - d->residual) + d->size_param <=
  7147. sizeof(d->residual));
  7148. if (!in_residual_buf(d, d->ptr)) {
  7149. d->bufstart_ofs -= (d->residual_end - d->residual);
  7150. }
  7151. memcpy(d->residual_end, d->buf_param, d->size_param);
  7152. d->residual_end += d->size_param;
  7153. } else {
  7154. /* Checkpoint was in user buf; old residual bytes not needed. */
  7155. size_t save;
  7156. assert(!in_residual_buf(d, d->checkpoint));
  7157. d->ptr = d->checkpoint;
  7158. save = curbufleft(d);
  7159. assert(save <= sizeof(d->residual));
  7160. memcpy(d->residual, d->ptr, save);
  7161. d->residual_end = d->residual + save;
  7162. d->bufstart_ofs = offset(d);
  7163. }
  7164. switchtobuf(d, d->residual, d->residual_end);
  7165. return d->size_param;
  7166. }
  7167. /* Copies the next "bytes" bytes into "buf" and advances the stream.
  7168. * Requires that this many bytes are available in the current buffer. */
  7169. UPB_FORCEINLINE static void consumebytes(upb_pbdecoder *d, void *buf,
  7170. size_t bytes) {
  7171. assert(bytes <= curbufleft(d));
  7172. memcpy(buf, d->ptr, bytes);
  7173. advance(d, bytes);
  7174. }
  7175. /* Slow path for getting the next "bytes" bytes, regardless of whether they are
  7176. * available in the current buffer or not. Returns a status code as described
  7177. * in decoder.int.h. */
  7178. UPB_NOINLINE static int32_t getbytes_slow(upb_pbdecoder *d, void *buf,
  7179. size_t bytes) {
  7180. const size_t avail = curbufleft(d);
  7181. consumebytes(d, buf, avail);
  7182. bytes -= avail;
  7183. assert(bytes > 0);
  7184. if (in_residual_buf(d, d->ptr)) {
  7185. advancetobuf(d, d->buf_param, d->size_param);
  7186. }
  7187. if (curbufleft(d) >= bytes) {
  7188. consumebytes(d, (char *)buf + avail, bytes);
  7189. return DECODE_OK;
  7190. } else if (d->data_end == d->delim_end) {
  7191. seterr(d, "Submessage ended in the middle of a value or group");
  7192. return upb_pbdecoder_suspend(d);
  7193. } else {
  7194. return suspend_save(d);
  7195. }
  7196. }
  7197. /* Gets the next "bytes" bytes, regardless of whether they are available in the
  7198. * current buffer or not. Returns a status code as described in decoder.int.h.
  7199. */
  7200. UPB_FORCEINLINE static int32_t getbytes(upb_pbdecoder *d, void *buf,
  7201. size_t bytes) {
  7202. if (curbufleft(d) >= bytes) {
  7203. /* Buffer has enough data to satisfy. */
  7204. consumebytes(d, buf, bytes);
  7205. return DECODE_OK;
  7206. } else {
  7207. return getbytes_slow(d, buf, bytes);
  7208. }
  7209. }
  7210. UPB_NOINLINE static size_t peekbytes_slow(upb_pbdecoder *d, void *buf,
  7211. size_t bytes) {
  7212. size_t ret = curbufleft(d);
  7213. memcpy(buf, d->ptr, ret);
  7214. if (in_residual_buf(d, d->ptr)) {
  7215. size_t copy = UPB_MIN(bytes - ret, d->size_param);
  7216. memcpy((char *)buf + ret, d->buf_param, copy);
  7217. ret += copy;
  7218. }
  7219. return ret;
  7220. }
  7221. UPB_FORCEINLINE static size_t peekbytes(upb_pbdecoder *d, void *buf,
  7222. size_t bytes) {
  7223. if (curbufleft(d) >= bytes) {
  7224. memcpy(buf, d->ptr, bytes);
  7225. return bytes;
  7226. } else {
  7227. return peekbytes_slow(d, buf, bytes);
  7228. }
  7229. }
  7230. /* Decoding of wire types *****************************************************/
  7231. /* Slow path for decoding a varint from the current buffer position.
  7232. * Returns a status code as described in decoder.int.h. */
  7233. UPB_NOINLINE int32_t upb_pbdecoder_decode_varint_slow(upb_pbdecoder *d,
  7234. uint64_t *u64) {
  7235. uint8_t byte = 0x80;
  7236. int bitpos;
  7237. *u64 = 0;
  7238. for(bitpos = 0; bitpos < 70 && (byte & 0x80); bitpos += 7) {
  7239. CHECK_RETURN(getbytes(d, &byte, 1));
  7240. *u64 |= (uint64_t)(byte & 0x7F) << bitpos;
  7241. }
  7242. if(bitpos == 70 && (byte & 0x80)) {
  7243. seterr(d, kUnterminatedVarint);
  7244. return upb_pbdecoder_suspend(d);
  7245. }
  7246. return DECODE_OK;
  7247. }
  7248. /* Decodes a varint from the current buffer position.
  7249. * Returns a status code as described in decoder.int.h. */
  7250. UPB_FORCEINLINE static int32_t decode_varint(upb_pbdecoder *d, uint64_t *u64) {
  7251. if (curbufleft(d) > 0 && !(*d->ptr & 0x80)) {
  7252. *u64 = *d->ptr;
  7253. advance(d, 1);
  7254. return DECODE_OK;
  7255. } else if (curbufleft(d) >= 10) {
  7256. /* Fast case. */
  7257. upb_decoderet r = upb_vdecode_fast(d->ptr);
  7258. if (r.p == NULL) {
  7259. seterr(d, kUnterminatedVarint);
  7260. return upb_pbdecoder_suspend(d);
  7261. }
  7262. advance(d, r.p - d->ptr);
  7263. *u64 = r.val;
  7264. return DECODE_OK;
  7265. } else {
  7266. /* Slow case -- varint spans buffer seam. */
  7267. return upb_pbdecoder_decode_varint_slow(d, u64);
  7268. }
  7269. }
  7270. /* Decodes a 32-bit varint from the current buffer position.
  7271. * Returns a status code as described in decoder.int.h. */
  7272. UPB_FORCEINLINE static int32_t decode_v32(upb_pbdecoder *d, uint32_t *u32) {
  7273. uint64_t u64;
  7274. int32_t ret = decode_varint(d, &u64);
  7275. if (ret >= 0) return ret;
  7276. if (u64 > UINT32_MAX) {
  7277. seterr(d, "Unterminated 32-bit varint");
  7278. /* TODO(haberman) guarantee that this function return is >= 0 somehow,
  7279. * so we know this path will always be treated as error by our caller.
  7280. * Right now the size_t -> int32_t can overflow and produce negative values.
  7281. */
  7282. *u32 = 0;
  7283. return upb_pbdecoder_suspend(d);
  7284. }
  7285. *u32 = u64;
  7286. return DECODE_OK;
  7287. }
  7288. /* Decodes a fixed32 from the current buffer position.
  7289. * Returns a status code as described in decoder.int.h.
  7290. * TODO: proper byte swapping for big-endian machines. */
  7291. UPB_FORCEINLINE static int32_t decode_fixed32(upb_pbdecoder *d, uint32_t *u32) {
  7292. return getbytes(d, u32, 4);
  7293. }
  7294. /* Decodes a fixed64 from the current buffer position.
  7295. * Returns a status code as described in decoder.int.h.
  7296. * TODO: proper byte swapping for big-endian machines. */
  7297. UPB_FORCEINLINE static int32_t decode_fixed64(upb_pbdecoder *d, uint64_t *u64) {
  7298. return getbytes(d, u64, 8);
  7299. }
  7300. /* Non-static versions of the above functions.
  7301. * These are called by the JIT for fallback paths. */
  7302. int32_t upb_pbdecoder_decode_f32(upb_pbdecoder *d, uint32_t *u32) {
  7303. return decode_fixed32(d, u32);
  7304. }
  7305. int32_t upb_pbdecoder_decode_f64(upb_pbdecoder *d, uint64_t *u64) {
  7306. return decode_fixed64(d, u64);
  7307. }
  7308. static double as_double(uint64_t n) { double d; memcpy(&d, &n, 8); return d; }
  7309. static float as_float(uint32_t n) { float f; memcpy(&f, &n, 4); return f; }
  7310. /* Pushes a frame onto the decoder stack. */
  7311. static bool decoder_push(upb_pbdecoder *d, uint64_t end) {
  7312. upb_pbdecoder_frame *fr = d->top;
  7313. if (end > fr->end_ofs) {
  7314. seterr(d, kPbDecoderSubmessageTooLong);
  7315. return false;
  7316. } else if (fr == d->limit) {
  7317. seterr(d, kPbDecoderStackOverflow);
  7318. return false;
  7319. }
  7320. fr++;
  7321. fr->end_ofs = end;
  7322. fr->dispatch = NULL;
  7323. fr->groupnum = 0;
  7324. d->top = fr;
  7325. return true;
  7326. }
  7327. static bool pushtagdelim(upb_pbdecoder *d, uint32_t arg) {
  7328. /* While we expect to see an "end" tag (either ENDGROUP or a non-sequence
  7329. * field number) prior to hitting any enclosing submessage end, pushing our
  7330. * existing delim end prevents us from continuing to parse values from a
  7331. * corrupt proto that doesn't give us an END tag in time. */
  7332. if (!decoder_push(d, d->top->end_ofs))
  7333. return false;
  7334. d->top->groupnum = arg;
  7335. return true;
  7336. }
  7337. /* Pops a frame from the decoder stack. */
  7338. static void decoder_pop(upb_pbdecoder *d) { d->top--; }
  7339. UPB_NOINLINE int32_t upb_pbdecoder_checktag_slow(upb_pbdecoder *d,
  7340. uint64_t expected) {
  7341. uint64_t data = 0;
  7342. size_t bytes = upb_value_size(expected);
  7343. size_t read = peekbytes(d, &data, bytes);
  7344. if (read == bytes && data == expected) {
  7345. /* Advance past matched bytes. */
  7346. int32_t ok = getbytes(d, &data, read);
  7347. UPB_ASSERT_VAR(ok, ok < 0);
  7348. return DECODE_OK;
  7349. } else if (read < bytes && memcmp(&data, &expected, read) == 0) {
  7350. return suspend_save(d);
  7351. } else {
  7352. return DECODE_MISMATCH;
  7353. }
  7354. }
  7355. int32_t upb_pbdecoder_skipunknown(upb_pbdecoder *d, int32_t fieldnum,
  7356. uint8_t wire_type) {
  7357. if (fieldnum >= 0)
  7358. goto have_tag;
  7359. while (true) {
  7360. uint32_t tag;
  7361. CHECK_RETURN(decode_v32(d, &tag));
  7362. wire_type = tag & 0x7;
  7363. fieldnum = tag >> 3;
  7364. have_tag:
  7365. if (fieldnum == 0) {
  7366. seterr(d, "Saw invalid field number (0)");
  7367. return upb_pbdecoder_suspend(d);
  7368. }
  7369. /* TODO: deliver to unknown field callback. */
  7370. switch (wire_type) {
  7371. case UPB_WIRE_TYPE_32BIT:
  7372. CHECK_RETURN(skip(d, 4));
  7373. break;
  7374. case UPB_WIRE_TYPE_64BIT:
  7375. CHECK_RETURN(skip(d, 8));
  7376. break;
  7377. case UPB_WIRE_TYPE_VARINT: {
  7378. uint64_t u64;
  7379. CHECK_RETURN(decode_varint(d, &u64));
  7380. break;
  7381. }
  7382. case UPB_WIRE_TYPE_DELIMITED: {
  7383. uint32_t len;
  7384. CHECK_RETURN(decode_v32(d, &len));
  7385. CHECK_RETURN(skip(d, len));
  7386. break;
  7387. }
  7388. case UPB_WIRE_TYPE_START_GROUP:
  7389. CHECK_SUSPEND(pushtagdelim(d, -fieldnum));
  7390. break;
  7391. case UPB_WIRE_TYPE_END_GROUP:
  7392. if (fieldnum == -d->top->groupnum) {
  7393. decoder_pop(d);
  7394. } else if (fieldnum == d->top->groupnum) {
  7395. return DECODE_ENDGROUP;
  7396. } else {
  7397. seterr(d, "Unmatched ENDGROUP tag.");
  7398. return upb_pbdecoder_suspend(d);
  7399. }
  7400. break;
  7401. default:
  7402. seterr(d, "Invalid wire type");
  7403. return upb_pbdecoder_suspend(d);
  7404. }
  7405. if (d->top->groupnum >= 0) {
  7406. return DECODE_OK;
  7407. }
  7408. /* Unknown group -- continue looping over unknown fields. */
  7409. checkpoint(d);
  7410. }
  7411. }
  7412. static void goto_endmsg(upb_pbdecoder *d) {
  7413. upb_value v;
  7414. bool found = upb_inttable_lookup32(d->top->dispatch, DISPATCH_ENDMSG, &v);
  7415. UPB_ASSERT_VAR(found, found);
  7416. d->pc = d->top->base + upb_value_getuint64(v);
  7417. }
  7418. /* Parses a tag and jumps to the corresponding bytecode instruction for this
  7419. * field.
  7420. *
  7421. * If the tag is unknown (or the wire type doesn't match), parses the field as
  7422. * unknown. If the tag is a valid ENDGROUP tag, jumps to the bytecode
  7423. * instruction for the end of message. */
  7424. static int32_t dispatch(upb_pbdecoder *d) {
  7425. upb_inttable *dispatch = d->top->dispatch;
  7426. uint32_t tag;
  7427. uint8_t wire_type;
  7428. uint32_t fieldnum;
  7429. upb_value val;
  7430. int32_t retval;
  7431. /* Decode tag. */
  7432. CHECK_RETURN(decode_v32(d, &tag));
  7433. wire_type = tag & 0x7;
  7434. fieldnum = tag >> 3;
  7435. /* Lookup tag. Because of packed/non-packed compatibility, we have to
  7436. * check the wire type against two possibilities. */
  7437. if (fieldnum != DISPATCH_ENDMSG &&
  7438. upb_inttable_lookup32(dispatch, fieldnum, &val)) {
  7439. uint64_t v = upb_value_getuint64(val);
  7440. if (wire_type == (v & 0xff)) {
  7441. d->pc = d->top->base + (v >> 16);
  7442. return DECODE_OK;
  7443. } else if (wire_type == ((v >> 8) & 0xff)) {
  7444. bool found =
  7445. upb_inttable_lookup(dispatch, fieldnum + UPB_MAX_FIELDNUMBER, &val);
  7446. UPB_ASSERT_VAR(found, found);
  7447. d->pc = d->top->base + upb_value_getuint64(val);
  7448. return DECODE_OK;
  7449. }
  7450. }
  7451. /* We have some unknown fields (or ENDGROUP) to parse. The DISPATCH or TAG
  7452. * bytecode that triggered this is preceded by a CHECKDELIM bytecode which
  7453. * we need to back up to, so that when we're done skipping unknown data we
  7454. * can re-check the delimited end. */
  7455. d->last--; /* Necessary if we get suspended */
  7456. d->pc = d->last;
  7457. assert(getop(*d->last) == OP_CHECKDELIM);
  7458. /* Unknown field or ENDGROUP. */
  7459. retval = upb_pbdecoder_skipunknown(d, fieldnum, wire_type);
  7460. CHECK_RETURN(retval);
  7461. if (retval == DECODE_ENDGROUP) {
  7462. goto_endmsg(d);
  7463. return DECODE_OK;
  7464. }
  7465. return DECODE_OK;
  7466. }
  7467. /* Callers know that the stack is more than one deep because the opcodes that
  7468. * call this only occur after PUSH operations. */
  7469. upb_pbdecoder_frame *outer_frame(upb_pbdecoder *d) {
  7470. assert(d->top != d->stack);
  7471. return d->top - 1;
  7472. }
  7473. /* The main decoding loop *****************************************************/
  7474. /* The main decoder VM function. Uses traditional bytecode dispatch loop with a
  7475. * switch() statement. */
  7476. size_t run_decoder_vm(upb_pbdecoder *d, const mgroup *group,
  7477. const upb_bufhandle* handle) {
  7478. #define VMCASE(op, code) \
  7479. case op: { code; if (consumes_input(op)) checkpoint(d); break; }
  7480. #define PRIMITIVE_OP(type, wt, name, convfunc, ctype) \
  7481. VMCASE(OP_PARSE_ ## type, { \
  7482. ctype val; \
  7483. CHECK_RETURN(decode_ ## wt(d, &val)); \
  7484. upb_sink_put ## name(&d->top->sink, arg, (convfunc)(val)); \
  7485. })
  7486. while(1) {
  7487. int32_t instruction;
  7488. opcode op;
  7489. uint32_t arg;
  7490. int32_t longofs;
  7491. d->last = d->pc;
  7492. instruction = *d->pc++;
  7493. op = getop(instruction);
  7494. arg = instruction >> 8;
  7495. longofs = arg;
  7496. assert(d->ptr != d->residual_end);
  7497. UPB_UNUSED(group);
  7498. #ifdef UPB_DUMP_BYTECODE
  7499. fprintf(stderr, "s_ofs=%d buf_ofs=%d data_rem=%d buf_rem=%d delim_rem=%d "
  7500. "%x %s (%d)\n",
  7501. (int)offset(d),
  7502. (int)(d->ptr - d->buf),
  7503. (int)(d->data_end - d->ptr),
  7504. (int)(d->end - d->ptr),
  7505. (int)((d->top->end_ofs - d->bufstart_ofs) - (d->ptr - d->buf)),
  7506. (int)(d->pc - 1 - group->bytecode),
  7507. upb_pbdecoder_getopname(op),
  7508. arg);
  7509. #endif
  7510. switch (op) {
  7511. /* Technically, we are losing data if we see a 32-bit varint that is not
  7512. * properly sign-extended. We could detect this and error about the data
  7513. * loss, but proto2 does not do this, so we pass. */
  7514. PRIMITIVE_OP(INT32, varint, int32, int32_t, uint64_t)
  7515. PRIMITIVE_OP(INT64, varint, int64, int64_t, uint64_t)
  7516. PRIMITIVE_OP(UINT32, varint, uint32, uint32_t, uint64_t)
  7517. PRIMITIVE_OP(UINT64, varint, uint64, uint64_t, uint64_t)
  7518. PRIMITIVE_OP(FIXED32, fixed32, uint32, uint32_t, uint32_t)
  7519. PRIMITIVE_OP(FIXED64, fixed64, uint64, uint64_t, uint64_t)
  7520. PRIMITIVE_OP(SFIXED32, fixed32, int32, int32_t, uint32_t)
  7521. PRIMITIVE_OP(SFIXED64, fixed64, int64, int64_t, uint64_t)
  7522. PRIMITIVE_OP(BOOL, varint, bool, bool, uint64_t)
  7523. PRIMITIVE_OP(DOUBLE, fixed64, double, as_double, uint64_t)
  7524. PRIMITIVE_OP(FLOAT, fixed32, float, as_float, uint32_t)
  7525. PRIMITIVE_OP(SINT32, varint, int32, upb_zzdec_32, uint64_t)
  7526. PRIMITIVE_OP(SINT64, varint, int64, upb_zzdec_64, uint64_t)
  7527. VMCASE(OP_SETDISPATCH,
  7528. d->top->base = d->pc - 1;
  7529. memcpy(&d->top->dispatch, d->pc, sizeof(void*));
  7530. d->pc += sizeof(void*) / sizeof(uint32_t);
  7531. )
  7532. VMCASE(OP_STARTMSG,
  7533. CHECK_SUSPEND(upb_sink_startmsg(&d->top->sink));
  7534. )
  7535. VMCASE(OP_ENDMSG,
  7536. CHECK_SUSPEND(upb_sink_endmsg(&d->top->sink, d->status));
  7537. )
  7538. VMCASE(OP_STARTSEQ,
  7539. upb_pbdecoder_frame *outer = outer_frame(d);
  7540. CHECK_SUSPEND(upb_sink_startseq(&outer->sink, arg, &d->top->sink));
  7541. )
  7542. VMCASE(OP_ENDSEQ,
  7543. CHECK_SUSPEND(upb_sink_endseq(&d->top->sink, arg));
  7544. )
  7545. VMCASE(OP_STARTSUBMSG,
  7546. upb_pbdecoder_frame *outer = outer_frame(d);
  7547. CHECK_SUSPEND(upb_sink_startsubmsg(&outer->sink, arg, &d->top->sink));
  7548. )
  7549. VMCASE(OP_ENDSUBMSG,
  7550. CHECK_SUSPEND(upb_sink_endsubmsg(&d->top->sink, arg));
  7551. )
  7552. VMCASE(OP_STARTSTR,
  7553. uint32_t len = delim_remaining(d);
  7554. upb_pbdecoder_frame *outer = outer_frame(d);
  7555. CHECK_SUSPEND(upb_sink_startstr(&outer->sink, arg, len, &d->top->sink));
  7556. if (len == 0) {
  7557. d->pc++; /* Skip OP_STRING. */
  7558. }
  7559. )
  7560. VMCASE(OP_STRING,
  7561. uint32_t len = curbufleft(d);
  7562. size_t n = upb_sink_putstring(&d->top->sink, arg, d->ptr, len, handle);
  7563. if (n > len) {
  7564. if (n > delim_remaining(d)) {
  7565. seterr(d, "Tried to skip past end of string.");
  7566. return upb_pbdecoder_suspend(d);
  7567. } else {
  7568. int32_t ret = skip(d, n);
  7569. /* This shouldn't return DECODE_OK, because n > len. */
  7570. assert(ret >= 0);
  7571. return ret;
  7572. }
  7573. }
  7574. advance(d, n);
  7575. if (n < len || d->delim_end == NULL) {
  7576. /* We aren't finished with this string yet. */
  7577. d->pc--; /* Repeat OP_STRING. */
  7578. if (n > 0) checkpoint(d);
  7579. return upb_pbdecoder_suspend(d);
  7580. }
  7581. )
  7582. VMCASE(OP_ENDSTR,
  7583. CHECK_SUSPEND(upb_sink_endstr(&d->top->sink, arg));
  7584. )
  7585. VMCASE(OP_PUSHTAGDELIM,
  7586. CHECK_SUSPEND(pushtagdelim(d, arg));
  7587. )
  7588. VMCASE(OP_SETBIGGROUPNUM,
  7589. d->top->groupnum = *d->pc++;
  7590. )
  7591. VMCASE(OP_POP,
  7592. assert(d->top > d->stack);
  7593. decoder_pop(d);
  7594. )
  7595. VMCASE(OP_PUSHLENDELIM,
  7596. uint32_t len;
  7597. CHECK_RETURN(decode_v32(d, &len));
  7598. CHECK_SUSPEND(decoder_push(d, offset(d) + len));
  7599. set_delim_end(d);
  7600. )
  7601. VMCASE(OP_SETDELIM,
  7602. set_delim_end(d);
  7603. )
  7604. VMCASE(OP_CHECKDELIM,
  7605. /* We are guaranteed of this assert because we never allow ourselves to
  7606. * consume bytes beyond data_end, which covers delim_end when non-NULL.
  7607. */
  7608. assert(!(d->delim_end && d->ptr > d->delim_end));
  7609. if (d->ptr == d->delim_end)
  7610. d->pc += longofs;
  7611. )
  7612. VMCASE(OP_CALL,
  7613. d->callstack[d->call_len++] = d->pc;
  7614. d->pc += longofs;
  7615. )
  7616. VMCASE(OP_RET,
  7617. assert(d->call_len > 0);
  7618. d->pc = d->callstack[--d->call_len];
  7619. )
  7620. VMCASE(OP_BRANCH,
  7621. d->pc += longofs;
  7622. )
  7623. VMCASE(OP_TAG1,
  7624. uint8_t expected;
  7625. CHECK_SUSPEND(curbufleft(d) > 0);
  7626. expected = (arg >> 8) & 0xff;
  7627. if (*d->ptr == expected) {
  7628. advance(d, 1);
  7629. } else {
  7630. int8_t shortofs;
  7631. badtag:
  7632. shortofs = arg;
  7633. if (shortofs == LABEL_DISPATCH) {
  7634. CHECK_RETURN(dispatch(d));
  7635. } else {
  7636. d->pc += shortofs;
  7637. break; /* Avoid checkpoint(). */
  7638. }
  7639. }
  7640. )
  7641. VMCASE(OP_TAG2,
  7642. uint16_t expected;
  7643. CHECK_SUSPEND(curbufleft(d) > 0);
  7644. expected = (arg >> 8) & 0xffff;
  7645. if (curbufleft(d) >= 2) {
  7646. uint16_t actual;
  7647. memcpy(&actual, d->ptr, 2);
  7648. if (expected == actual) {
  7649. advance(d, 2);
  7650. } else {
  7651. goto badtag;
  7652. }
  7653. } else {
  7654. int32_t result = upb_pbdecoder_checktag_slow(d, expected);
  7655. if (result == DECODE_MISMATCH) goto badtag;
  7656. if (result >= 0) return result;
  7657. }
  7658. )
  7659. VMCASE(OP_TAGN, {
  7660. uint64_t expected;
  7661. int32_t result;
  7662. memcpy(&expected, d->pc, 8);
  7663. d->pc += 2;
  7664. result = upb_pbdecoder_checktag_slow(d, expected);
  7665. if (result == DECODE_MISMATCH) goto badtag;
  7666. if (result >= 0) return result;
  7667. })
  7668. VMCASE(OP_DISPATCH, {
  7669. CHECK_RETURN(dispatch(d));
  7670. })
  7671. VMCASE(OP_HALT, {
  7672. return d->size_param;
  7673. })
  7674. }
  7675. }
  7676. }
  7677. /* BytesHandler handlers ******************************************************/
  7678. void *upb_pbdecoder_startbc(void *closure, const void *pc, size_t size_hint) {
  7679. upb_pbdecoder *d = closure;
  7680. UPB_UNUSED(size_hint);
  7681. d->top->end_ofs = UINT64_MAX;
  7682. d->bufstart_ofs = 0;
  7683. d->call_len = 1;
  7684. d->callstack[0] = &halt;
  7685. d->pc = pc;
  7686. d->skip = 0;
  7687. return d;
  7688. }
  7689. void *upb_pbdecoder_startjit(void *closure, const void *hd, size_t size_hint) {
  7690. upb_pbdecoder *d = closure;
  7691. UPB_UNUSED(hd);
  7692. UPB_UNUSED(size_hint);
  7693. d->top->end_ofs = UINT64_MAX;
  7694. d->bufstart_ofs = 0;
  7695. d->call_len = 0;
  7696. d->skip = 0;
  7697. return d;
  7698. }
  7699. bool upb_pbdecoder_end(void *closure, const void *handler_data) {
  7700. upb_pbdecoder *d = closure;
  7701. const upb_pbdecodermethod *method = handler_data;
  7702. uint64_t end;
  7703. char dummy;
  7704. if (d->residual_end > d->residual) {
  7705. seterr(d, "Unexpected EOF: decoder still has buffered unparsed data");
  7706. return false;
  7707. }
  7708. if (d->skip) {
  7709. seterr(d, "Unexpected EOF inside skipped data");
  7710. return false;
  7711. }
  7712. if (d->top->end_ofs != UINT64_MAX) {
  7713. seterr(d, "Unexpected EOF inside delimited string");
  7714. return false;
  7715. }
  7716. /* The user's end() call indicates that the message ends here. */
  7717. end = offset(d);
  7718. d->top->end_ofs = end;
  7719. #ifdef UPB_USE_JIT_X64
  7720. if (method->is_native_) {
  7721. const mgroup *group = (const mgroup*)method->group;
  7722. if (d->top != d->stack)
  7723. d->stack->end_ofs = 0;
  7724. group->jit_code(closure, method->code_base.ptr, &dummy, 0, NULL);
  7725. } else
  7726. #endif
  7727. {
  7728. const uint32_t *p = d->pc;
  7729. d->stack->end_ofs = end;
  7730. /* Check the previous bytecode, but guard against beginning. */
  7731. if (p != method->code_base.ptr) p--;
  7732. if (getop(*p) == OP_CHECKDELIM) {
  7733. /* Rewind from OP_TAG* to OP_CHECKDELIM. */
  7734. assert(getop(*d->pc) == OP_TAG1 ||
  7735. getop(*d->pc) == OP_TAG2 ||
  7736. getop(*d->pc) == OP_TAGN ||
  7737. getop(*d->pc) == OP_DISPATCH);
  7738. d->pc = p;
  7739. }
  7740. upb_pbdecoder_decode(closure, handler_data, &dummy, 0, NULL);
  7741. }
  7742. if (d->call_len != 0) {
  7743. seterr(d, "Unexpected EOF inside submessage or group");
  7744. return false;
  7745. }
  7746. return true;
  7747. }
  7748. size_t upb_pbdecoder_decode(void *decoder, const void *group, const char *buf,
  7749. size_t size, const upb_bufhandle *handle) {
  7750. int32_t result = upb_pbdecoder_resume(decoder, NULL, buf, size, handle);
  7751. if (result == DECODE_ENDGROUP) goto_endmsg(decoder);
  7752. CHECK_RETURN(result);
  7753. return run_decoder_vm(decoder, group, handle);
  7754. }
  7755. /* Public API *****************************************************************/
  7756. void upb_pbdecoder_reset(upb_pbdecoder *d) {
  7757. d->top = d->stack;
  7758. d->top->groupnum = 0;
  7759. d->ptr = d->residual;
  7760. d->buf = d->residual;
  7761. d->end = d->residual;
  7762. d->residual_end = d->residual;
  7763. }
  7764. upb_pbdecoder *upb_pbdecoder_create(upb_env *e, const upb_pbdecodermethod *m,
  7765. upb_sink *sink) {
  7766. const size_t default_max_nesting = 64;
  7767. #ifndef NDEBUG
  7768. size_t size_before = upb_env_bytesallocated(e);
  7769. #endif
  7770. upb_pbdecoder *d = upb_env_malloc(e, sizeof(upb_pbdecoder));
  7771. if (!d) return NULL;
  7772. d->method_ = m;
  7773. d->callstack = upb_env_malloc(e, callstacksize(d, default_max_nesting));
  7774. d->stack = upb_env_malloc(e, stacksize(d, default_max_nesting));
  7775. if (!d->stack || !d->callstack) {
  7776. return NULL;
  7777. }
  7778. d->env = e;
  7779. d->limit = d->stack + default_max_nesting - 1;
  7780. d->stack_size = default_max_nesting;
  7781. d->status = NULL;
  7782. upb_pbdecoder_reset(d);
  7783. upb_bytessink_reset(&d->input_, &m->input_handler_, d);
  7784. assert(sink);
  7785. if (d->method_->dest_handlers_) {
  7786. if (sink->handlers != d->method_->dest_handlers_)
  7787. return NULL;
  7788. }
  7789. upb_sink_reset(&d->top->sink, sink->handlers, sink->closure);
  7790. /* If this fails, increase the value in decoder.h. */
  7791. assert(upb_env_bytesallocated(e) - size_before <= UPB_PB_DECODER_SIZE);
  7792. return d;
  7793. }
  7794. uint64_t upb_pbdecoder_bytesparsed(const upb_pbdecoder *d) {
  7795. return offset(d);
  7796. }
  7797. const upb_pbdecodermethod *upb_pbdecoder_method(const upb_pbdecoder *d) {
  7798. return d->method_;
  7799. }
  7800. upb_bytessink *upb_pbdecoder_input(upb_pbdecoder *d) {
  7801. return &d->input_;
  7802. }
  7803. size_t upb_pbdecoder_maxnesting(const upb_pbdecoder *d) {
  7804. return d->stack_size;
  7805. }
  7806. bool upb_pbdecoder_setmaxnesting(upb_pbdecoder *d, size_t max) {
  7807. assert(d->top >= d->stack);
  7808. if (max < (size_t)(d->top - d->stack)) {
  7809. /* Can't set a limit smaller than what we are currently at. */
  7810. return false;
  7811. }
  7812. if (max > d->stack_size) {
  7813. /* Need to reallocate stack and callstack to accommodate. */
  7814. size_t old_size = stacksize(d, d->stack_size);
  7815. size_t new_size = stacksize(d, max);
  7816. void *p = upb_env_realloc(d->env, d->stack, old_size, new_size);
  7817. if (!p) {
  7818. return false;
  7819. }
  7820. d->stack = p;
  7821. old_size = callstacksize(d, d->stack_size);
  7822. new_size = callstacksize(d, max);
  7823. p = upb_env_realloc(d->env, d->callstack, old_size, new_size);
  7824. if (!p) {
  7825. return false;
  7826. }
  7827. d->callstack = p;
  7828. d->stack_size = max;
  7829. }
  7830. d->limit = d->stack + max - 1;
  7831. return true;
  7832. }
  7833. /*
  7834. ** upb::Encoder
  7835. **
  7836. ** Since we are implementing pure handlers (ie. without any out-of-band access
  7837. ** to pre-computed lengths), we have to buffer all submessages before we can
  7838. ** emit even their first byte.
  7839. **
  7840. ** Not knowing the size of submessages also means we can't write a perfect
  7841. ** zero-copy implementation, even with buffering. Lengths are stored as
  7842. ** varints, which means that we don't know how many bytes to reserve for the
  7843. ** length until we know what the length is.
  7844. **
  7845. ** This leaves us with three main choices:
  7846. **
  7847. ** 1. buffer all submessage data in a temporary buffer, then copy it exactly
  7848. ** once into the output buffer.
  7849. **
  7850. ** 2. attempt to buffer data directly into the output buffer, estimating how
  7851. ** many bytes each length will take. When our guesses are wrong, use
  7852. ** memmove() to grow or shrink the allotted space.
  7853. **
  7854. ** 3. buffer directly into the output buffer, allocating a max length
  7855. ** ahead-of-time for each submessage length. If we overallocated, we waste
  7856. ** space, but no memcpy() or memmove() is required. This approach requires
  7857. ** defining a maximum size for submessages and rejecting submessages that
  7858. ** exceed that size.
  7859. **
  7860. ** (2) and (3) have the potential to have better performance, but they are more
  7861. ** complicated and subtle to implement:
  7862. **
  7863. ** (3) requires making an arbitrary choice of the maximum message size; it
  7864. ** wastes space when submessages are shorter than this and fails
  7865. ** completely when they are longer. This makes it more finicky and
  7866. ** requires configuration based on the input. It also makes it impossible
  7867. ** to perfectly match the output of reference encoders that always use the
  7868. ** optimal amount of space for each length.
  7869. **
  7870. ** (2) requires guessing the the size upfront, and if multiple lengths are
  7871. ** guessed wrong the minimum required number of memmove() operations may
  7872. ** be complicated to compute correctly. Implemented properly, it may have
  7873. ** a useful amortized or average cost, but more investigation is required
  7874. ** to determine this and what the optimal algorithm is to achieve it.
  7875. **
  7876. ** (1) makes you always pay for exactly one copy, but its implementation is
  7877. ** the simplest and its performance is predictable.
  7878. **
  7879. ** So for now, we implement (1) only. If we wish to optimize later, we should
  7880. ** be able to do it without affecting users.
  7881. **
  7882. ** The strategy is to buffer the segments of data that do *not* depend on
  7883. ** unknown lengths in one buffer, and keep a separate buffer of segment pointers
  7884. ** and lengths. When the top-level submessage ends, we can go beginning to end,
  7885. ** alternating the writing of lengths with memcpy() of the rest of the data.
  7886. ** At the top level though, no buffering is required.
  7887. */
  7888. #include <stdlib.h>
  7889. /* The output buffer is divided into segments; a segment is a string of data
  7890. * that is "ready to go" -- it does not need any varint lengths inserted into
  7891. * the middle. The seams between segments are where varints will be inserted
  7892. * once they are known.
  7893. *
  7894. * We also use the concept of a "run", which is a range of encoded bytes that
  7895. * occur at a single submessage level. Every segment contains one or more runs.
  7896. *
  7897. * A segment can span messages. Consider:
  7898. *
  7899. * .--Submessage lengths---------.
  7900. * | | |
  7901. * | V V
  7902. * V | |--------------- | |-----------------
  7903. * Submessages: | |-----------------------------------------------
  7904. * Top-level msg: ------------------------------------------------------------
  7905. *
  7906. * Segments: ----- ------------------- -----------------
  7907. * Runs: *---- *--------------*--- *----------------
  7908. * (* marks the start)
  7909. *
  7910. * Note that the top-level menssage is not in any segment because it does not
  7911. * have any length preceding it.
  7912. *
  7913. * A segment is only interrupted when another length needs to be inserted. So
  7914. * observe how the second segment spans both the inner submessage and part of
  7915. * the next enclosing message. */
  7916. typedef struct {
  7917. uint32_t msglen; /* The length to varint-encode before this segment. */
  7918. uint32_t seglen; /* Length of the segment. */
  7919. } upb_pb_encoder_segment;
  7920. struct upb_pb_encoder {
  7921. upb_env *env;
  7922. /* Our input and output. */
  7923. upb_sink input_;
  7924. upb_bytessink *output_;
  7925. /* The "subclosure" -- used as the inner closure as part of the bytessink
  7926. * protocol. */
  7927. void *subc;
  7928. /* The output buffer and limit, and our current write position. "buf"
  7929. * initially points to "initbuf", but is dynamically allocated if we need to
  7930. * grow beyond the initial size. */
  7931. char *buf, *ptr, *limit;
  7932. /* The beginning of the current run, or undefined if we are at the top
  7933. * level. */
  7934. char *runbegin;
  7935. /* The list of segments we are accumulating. */
  7936. upb_pb_encoder_segment *segbuf, *segptr, *seglimit;
  7937. /* The stack of enclosing submessages. Each entry in the stack points to the
  7938. * segment where this submessage's length is being accumulated. */
  7939. int *stack, *top, *stacklimit;
  7940. /* Depth of startmsg/endmsg calls. */
  7941. int depth;
  7942. };
  7943. /* low-level buffering ********************************************************/
  7944. /* Low-level functions for interacting with the output buffer. */
  7945. /* TODO(haberman): handle pushback */
  7946. static void putbuf(upb_pb_encoder *e, const char *buf, size_t len) {
  7947. size_t n = upb_bytessink_putbuf(e->output_, e->subc, buf, len, NULL);
  7948. UPB_ASSERT_VAR(n, n == len);
  7949. }
  7950. static upb_pb_encoder_segment *top(upb_pb_encoder *e) {
  7951. return &e->segbuf[*e->top];
  7952. }
  7953. /* Call to ensure that at least "bytes" bytes are available for writing at
  7954. * e->ptr. Returns false if the bytes could not be allocated. */
  7955. static bool reserve(upb_pb_encoder *e, size_t bytes) {
  7956. if ((size_t)(e->limit - e->ptr) < bytes) {
  7957. /* Grow buffer. */
  7958. char *new_buf;
  7959. size_t needed = bytes + (e->ptr - e->buf);
  7960. size_t old_size = e->limit - e->buf;
  7961. size_t new_size = old_size;
  7962. while (new_size < needed) {
  7963. new_size *= 2;
  7964. }
  7965. new_buf = upb_env_realloc(e->env, e->buf, old_size, new_size);
  7966. if (new_buf == NULL) {
  7967. return false;
  7968. }
  7969. e->ptr = new_buf + (e->ptr - e->buf);
  7970. e->runbegin = new_buf + (e->runbegin - e->buf);
  7971. e->limit = new_buf + new_size;
  7972. e->buf = new_buf;
  7973. }
  7974. return true;
  7975. }
  7976. /* Call when "bytes" bytes have been writte at e->ptr. The caller *must* have
  7977. * previously called reserve() with at least this many bytes. */
  7978. static void encoder_advance(upb_pb_encoder *e, size_t bytes) {
  7979. assert((size_t)(e->limit - e->ptr) >= bytes);
  7980. e->ptr += bytes;
  7981. }
  7982. /* Call when all of the bytes for a handler have been written. Flushes the
  7983. * bytes if possible and necessary, returning false if this failed. */
  7984. static bool commit(upb_pb_encoder *e) {
  7985. if (!e->top) {
  7986. /* We aren't inside a delimited region. Flush our accumulated bytes to
  7987. * the output.
  7988. *
  7989. * TODO(haberman): in the future we may want to delay flushing for
  7990. * efficiency reasons. */
  7991. putbuf(e, e->buf, e->ptr - e->buf);
  7992. e->ptr = e->buf;
  7993. }
  7994. return true;
  7995. }
  7996. /* Writes the given bytes to the buffer, handling reserve/advance. */
  7997. static bool encode_bytes(upb_pb_encoder *e, const void *data, size_t len) {
  7998. if (!reserve(e, len)) {
  7999. return false;
  8000. }
  8001. memcpy(e->ptr, data, len);
  8002. encoder_advance(e, len);
  8003. return true;
  8004. }
  8005. /* Finish the current run by adding the run totals to the segment and message
  8006. * length. */
  8007. static void accumulate(upb_pb_encoder *e) {
  8008. size_t run_len;
  8009. assert(e->ptr >= e->runbegin);
  8010. run_len = e->ptr - e->runbegin;
  8011. e->segptr->seglen += run_len;
  8012. top(e)->msglen += run_len;
  8013. e->runbegin = e->ptr;
  8014. }
  8015. /* Call to indicate the start of delimited region for which the full length is
  8016. * not yet known. All data will be buffered until the length is known.
  8017. * Delimited regions may be nested; their lengths will all be tracked properly. */
  8018. static bool start_delim(upb_pb_encoder *e) {
  8019. if (e->top) {
  8020. /* We are already buffering, advance to the next segment and push it on the
  8021. * stack. */
  8022. accumulate(e);
  8023. if (++e->top == e->stacklimit) {
  8024. /* TODO(haberman): grow stack? */
  8025. return false;
  8026. }
  8027. if (++e->segptr == e->seglimit) {
  8028. /* Grow segment buffer. */
  8029. size_t old_size =
  8030. (e->seglimit - e->segbuf) * sizeof(upb_pb_encoder_segment);
  8031. size_t new_size = old_size * 2;
  8032. upb_pb_encoder_segment *new_buf =
  8033. upb_env_realloc(e->env, e->segbuf, old_size, new_size);
  8034. if (new_buf == NULL) {
  8035. return false;
  8036. }
  8037. e->segptr = new_buf + (e->segptr - e->segbuf);
  8038. e->seglimit = new_buf + (new_size / sizeof(upb_pb_encoder_segment));
  8039. e->segbuf = new_buf;
  8040. }
  8041. } else {
  8042. /* We were previously at the top level, start buffering. */
  8043. e->segptr = e->segbuf;
  8044. e->top = e->stack;
  8045. e->runbegin = e->ptr;
  8046. }
  8047. *e->top = e->segptr - e->segbuf;
  8048. e->segptr->seglen = 0;
  8049. e->segptr->msglen = 0;
  8050. return true;
  8051. }
  8052. /* Call to indicate the end of a delimited region. We now know the length of
  8053. * the delimited region. If we are not nested inside any other delimited
  8054. * regions, we can now emit all of the buffered data we accumulated. */
  8055. static bool end_delim(upb_pb_encoder *e) {
  8056. size_t msglen;
  8057. accumulate(e);
  8058. msglen = top(e)->msglen;
  8059. if (e->top == e->stack) {
  8060. /* All lengths are now available, emit all buffered data. */
  8061. char buf[UPB_PB_VARINT_MAX_LEN];
  8062. upb_pb_encoder_segment *s;
  8063. const char *ptr = e->buf;
  8064. for (s = e->segbuf; s <= e->segptr; s++) {
  8065. size_t lenbytes = upb_vencode64(s->msglen, buf);
  8066. putbuf(e, buf, lenbytes);
  8067. putbuf(e, ptr, s->seglen);
  8068. ptr += s->seglen;
  8069. }
  8070. e->ptr = e->buf;
  8071. e->top = NULL;
  8072. } else {
  8073. /* Need to keep buffering; propagate length info into enclosing
  8074. * submessages. */
  8075. --e->top;
  8076. top(e)->msglen += msglen + upb_varint_size(msglen);
  8077. }
  8078. return true;
  8079. }
  8080. /* tag_t **********************************************************************/
  8081. /* A precomputed (pre-encoded) tag and length. */
  8082. typedef struct {
  8083. uint8_t bytes;
  8084. char tag[7];
  8085. } tag_t;
  8086. /* Allocates a new tag for this field, and sets it in these handlerattr. */
  8087. static void new_tag(upb_handlers *h, const upb_fielddef *f, upb_wiretype_t wt,
  8088. upb_handlerattr *attr) {
  8089. uint32_t n = upb_fielddef_number(f);
  8090. tag_t *tag = malloc(sizeof(tag_t));
  8091. tag->bytes = upb_vencode64((n << 3) | wt, tag->tag);
  8092. upb_handlerattr_init(attr);
  8093. upb_handlerattr_sethandlerdata(attr, tag);
  8094. upb_handlers_addcleanup(h, tag, free);
  8095. }
  8096. static bool encode_tag(upb_pb_encoder *e, const tag_t *tag) {
  8097. return encode_bytes(e, tag->tag, tag->bytes);
  8098. }
  8099. /* encoding of wire types *****************************************************/
  8100. static bool encode_fixed64(upb_pb_encoder *e, uint64_t val) {
  8101. /* TODO(haberman): byte-swap for big endian. */
  8102. return encode_bytes(e, &val, sizeof(uint64_t));
  8103. }
  8104. static bool encode_fixed32(upb_pb_encoder *e, uint32_t val) {
  8105. /* TODO(haberman): byte-swap for big endian. */
  8106. return encode_bytes(e, &val, sizeof(uint32_t));
  8107. }
  8108. static bool encode_varint(upb_pb_encoder *e, uint64_t val) {
  8109. if (!reserve(e, UPB_PB_VARINT_MAX_LEN)) {
  8110. return false;
  8111. }
  8112. encoder_advance(e, upb_vencode64(val, e->ptr));
  8113. return true;
  8114. }
  8115. static uint64_t dbl2uint64(double d) {
  8116. uint64_t ret;
  8117. memcpy(&ret, &d, sizeof(uint64_t));
  8118. return ret;
  8119. }
  8120. static uint32_t flt2uint32(float d) {
  8121. uint32_t ret;
  8122. memcpy(&ret, &d, sizeof(uint32_t));
  8123. return ret;
  8124. }
  8125. /* encoding of proto types ****************************************************/
  8126. static bool startmsg(void *c, const void *hd) {
  8127. upb_pb_encoder *e = c;
  8128. UPB_UNUSED(hd);
  8129. if (e->depth++ == 0) {
  8130. upb_bytessink_start(e->output_, 0, &e->subc);
  8131. }
  8132. return true;
  8133. }
  8134. static bool endmsg(void *c, const void *hd, upb_status *status) {
  8135. upb_pb_encoder *e = c;
  8136. UPB_UNUSED(hd);
  8137. UPB_UNUSED(status);
  8138. if (--e->depth == 0) {
  8139. upb_bytessink_end(e->output_);
  8140. }
  8141. return true;
  8142. }
  8143. static void *encode_startdelimfield(void *c, const void *hd) {
  8144. bool ok = encode_tag(c, hd) && commit(c) && start_delim(c);
  8145. return ok ? c : UPB_BREAK;
  8146. }
  8147. static bool encode_enddelimfield(void *c, const void *hd) {
  8148. UPB_UNUSED(hd);
  8149. return end_delim(c);
  8150. }
  8151. static void *encode_startgroup(void *c, const void *hd) {
  8152. return (encode_tag(c, hd) && commit(c)) ? c : UPB_BREAK;
  8153. }
  8154. static bool encode_endgroup(void *c, const void *hd) {
  8155. return encode_tag(c, hd) && commit(c);
  8156. }
  8157. static void *encode_startstr(void *c, const void *hd, size_t size_hint) {
  8158. UPB_UNUSED(size_hint);
  8159. return encode_startdelimfield(c, hd);
  8160. }
  8161. static size_t encode_strbuf(void *c, const void *hd, const char *buf,
  8162. size_t len, const upb_bufhandle *h) {
  8163. UPB_UNUSED(hd);
  8164. UPB_UNUSED(h);
  8165. return encode_bytes(c, buf, len) ? len : 0;
  8166. }
  8167. #define T(type, ctype, convert, encode) \
  8168. static bool encode_scalar_##type(void *e, const void *hd, ctype val) { \
  8169. return encode_tag(e, hd) && encode(e, (convert)(val)) && commit(e); \
  8170. } \
  8171. static bool encode_packed_##type(void *e, const void *hd, ctype val) { \
  8172. UPB_UNUSED(hd); \
  8173. return encode(e, (convert)(val)); \
  8174. }
  8175. T(double, double, dbl2uint64, encode_fixed64)
  8176. T(float, float, flt2uint32, encode_fixed32)
  8177. T(int64, int64_t, uint64_t, encode_varint)
  8178. T(int32, int32_t, uint32_t, encode_varint)
  8179. T(fixed64, uint64_t, uint64_t, encode_fixed64)
  8180. T(fixed32, uint32_t, uint32_t, encode_fixed32)
  8181. T(bool, bool, bool, encode_varint)
  8182. T(uint32, uint32_t, uint32_t, encode_varint)
  8183. T(uint64, uint64_t, uint64_t, encode_varint)
  8184. T(enum, int32_t, uint32_t, encode_varint)
  8185. T(sfixed32, int32_t, uint32_t, encode_fixed32)
  8186. T(sfixed64, int64_t, uint64_t, encode_fixed64)
  8187. T(sint32, int32_t, upb_zzenc_32, encode_varint)
  8188. T(sint64, int64_t, upb_zzenc_64, encode_varint)
  8189. #undef T
  8190. /* code to build the handlers *************************************************/
  8191. static void newhandlers_callback(const void *closure, upb_handlers *h) {
  8192. const upb_msgdef *m;
  8193. upb_msg_field_iter i;
  8194. UPB_UNUSED(closure);
  8195. upb_handlers_setstartmsg(h, startmsg, NULL);
  8196. upb_handlers_setendmsg(h, endmsg, NULL);
  8197. m = upb_handlers_msgdef(h);
  8198. for(upb_msg_field_begin(&i, m);
  8199. !upb_msg_field_done(&i);
  8200. upb_msg_field_next(&i)) {
  8201. const upb_fielddef *f = upb_msg_iter_field(&i);
  8202. bool packed = upb_fielddef_isseq(f) && upb_fielddef_isprimitive(f) &&
  8203. upb_fielddef_packed(f);
  8204. upb_handlerattr attr;
  8205. upb_wiretype_t wt =
  8206. packed ? UPB_WIRE_TYPE_DELIMITED
  8207. : upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  8208. /* Pre-encode the tag for this field. */
  8209. new_tag(h, f, wt, &attr);
  8210. if (packed) {
  8211. upb_handlers_setstartseq(h, f, encode_startdelimfield, &attr);
  8212. upb_handlers_setendseq(h, f, encode_enddelimfield, &attr);
  8213. }
  8214. #define T(upper, lower, upbtype) \
  8215. case UPB_DESCRIPTOR_TYPE_##upper: \
  8216. if (packed) { \
  8217. upb_handlers_set##upbtype(h, f, encode_packed_##lower, &attr); \
  8218. } else { \
  8219. upb_handlers_set##upbtype(h, f, encode_scalar_##lower, &attr); \
  8220. } \
  8221. break;
  8222. switch (upb_fielddef_descriptortype(f)) {
  8223. T(DOUBLE, double, double);
  8224. T(FLOAT, float, float);
  8225. T(INT64, int64, int64);
  8226. T(INT32, int32, int32);
  8227. T(FIXED64, fixed64, uint64);
  8228. T(FIXED32, fixed32, uint32);
  8229. T(BOOL, bool, bool);
  8230. T(UINT32, uint32, uint32);
  8231. T(UINT64, uint64, uint64);
  8232. T(ENUM, enum, int32);
  8233. T(SFIXED32, sfixed32, int32);
  8234. T(SFIXED64, sfixed64, int64);
  8235. T(SINT32, sint32, int32);
  8236. T(SINT64, sint64, int64);
  8237. case UPB_DESCRIPTOR_TYPE_STRING:
  8238. case UPB_DESCRIPTOR_TYPE_BYTES:
  8239. upb_handlers_setstartstr(h, f, encode_startstr, &attr);
  8240. upb_handlers_setendstr(h, f, encode_enddelimfield, &attr);
  8241. upb_handlers_setstring(h, f, encode_strbuf, &attr);
  8242. break;
  8243. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  8244. upb_handlers_setstartsubmsg(h, f, encode_startdelimfield, &attr);
  8245. upb_handlers_setendsubmsg(h, f, encode_enddelimfield, &attr);
  8246. break;
  8247. case UPB_DESCRIPTOR_TYPE_GROUP: {
  8248. /* Endgroup takes a different tag (wire_type = END_GROUP). */
  8249. upb_handlerattr attr2;
  8250. new_tag(h, f, UPB_WIRE_TYPE_END_GROUP, &attr2);
  8251. upb_handlers_setstartsubmsg(h, f, encode_startgroup, &attr);
  8252. upb_handlers_setendsubmsg(h, f, encode_endgroup, &attr2);
  8253. upb_handlerattr_uninit(&attr2);
  8254. break;
  8255. }
  8256. }
  8257. #undef T
  8258. upb_handlerattr_uninit(&attr);
  8259. }
  8260. }
  8261. void upb_pb_encoder_reset(upb_pb_encoder *e) {
  8262. e->segptr = NULL;
  8263. e->top = NULL;
  8264. e->depth = 0;
  8265. }
  8266. /* public API *****************************************************************/
  8267. const upb_handlers *upb_pb_encoder_newhandlers(const upb_msgdef *m,
  8268. const void *owner) {
  8269. return upb_handlers_newfrozen(m, owner, newhandlers_callback, NULL);
  8270. }
  8271. upb_pb_encoder *upb_pb_encoder_create(upb_env *env, const upb_handlers *h,
  8272. upb_bytessink *output) {
  8273. const size_t initial_bufsize = 256;
  8274. const size_t initial_segbufsize = 16;
  8275. /* TODO(haberman): make this configurable. */
  8276. const size_t stack_size = 64;
  8277. #ifndef NDEBUG
  8278. const size_t size_before = upb_env_bytesallocated(env);
  8279. #endif
  8280. upb_pb_encoder *e = upb_env_malloc(env, sizeof(upb_pb_encoder));
  8281. if (!e) return NULL;
  8282. e->buf = upb_env_malloc(env, initial_bufsize);
  8283. e->segbuf = upb_env_malloc(env, initial_segbufsize * sizeof(*e->segbuf));
  8284. e->stack = upb_env_malloc(env, stack_size * sizeof(*e->stack));
  8285. if (!e->buf || !e->segbuf || !e->stack) {
  8286. return NULL;
  8287. }
  8288. e->limit = e->buf + initial_bufsize;
  8289. e->seglimit = e->segbuf + initial_segbufsize;
  8290. e->stacklimit = e->stack + stack_size;
  8291. upb_pb_encoder_reset(e);
  8292. upb_sink_reset(&e->input_, h, e);
  8293. e->env = env;
  8294. e->output_ = output;
  8295. e->subc = output->closure;
  8296. e->ptr = e->buf;
  8297. /* If this fails, increase the value in encoder.h. */
  8298. assert(upb_env_bytesallocated(env) - size_before <= UPB_PB_ENCODER_SIZE);
  8299. return e;
  8300. }
  8301. upb_sink *upb_pb_encoder_input(upb_pb_encoder *e) { return &e->input_; }
  8302. #include <stdio.h>
  8303. #include <stdlib.h>
  8304. #include <string.h>
  8305. upb_filedef **upb_loaddescriptor(const char *buf, size_t n, const void *owner,
  8306. upb_status *status) {
  8307. /* Create handlers. */
  8308. const upb_pbdecodermethod *decoder_m;
  8309. const upb_handlers *reader_h = upb_descreader_newhandlers(&reader_h);
  8310. upb_env env;
  8311. upb_pbdecodermethodopts opts;
  8312. upb_pbdecoder *decoder;
  8313. upb_descreader *reader;
  8314. bool ok;
  8315. size_t i;
  8316. upb_filedef **ret = NULL;
  8317. upb_pbdecodermethodopts_init(&opts, reader_h);
  8318. decoder_m = upb_pbdecodermethod_new(&opts, &decoder_m);
  8319. upb_env_init(&env);
  8320. upb_env_reporterrorsto(&env, status);
  8321. reader = upb_descreader_create(&env, reader_h);
  8322. decoder = upb_pbdecoder_create(&env, decoder_m, upb_descreader_input(reader));
  8323. /* Push input data. */
  8324. ok = upb_bufsrc_putbuf(buf, n, upb_pbdecoder_input(decoder));
  8325. if (!ok) {
  8326. goto cleanup;
  8327. }
  8328. ret = malloc(sizeof (*ret) * (upb_descreader_filecount(reader) + 1));
  8329. if (!ret) {
  8330. goto cleanup;
  8331. }
  8332. for (i = 0; i < upb_descreader_filecount(reader); i++) {
  8333. ret[i] = upb_descreader_file(reader, i);
  8334. upb_filedef_ref(ret[i], owner);
  8335. }
  8336. ret[i] = NULL;
  8337. cleanup:
  8338. upb_env_uninit(&env);
  8339. upb_handlers_unref(reader_h, &reader_h);
  8340. upb_pbdecodermethod_unref(decoder_m, &decoder_m);
  8341. return ret;
  8342. }
  8343. /*
  8344. * upb::pb::TextPrinter
  8345. *
  8346. * OPT: This is not optimized at all. It uses printf() which parses the format
  8347. * string every time, and it allocates memory for every put.
  8348. */
  8349. #include <ctype.h>
  8350. #include <float.h>
  8351. #include <inttypes.h>
  8352. #include <stdarg.h>
  8353. #include <stdio.h>
  8354. #include <stdlib.h>
  8355. #include <string.h>
  8356. struct upb_textprinter {
  8357. upb_sink input_;
  8358. upb_bytessink *output_;
  8359. int indent_depth_;
  8360. bool single_line_;
  8361. void *subc;
  8362. };
  8363. #define CHECK(x) if ((x) < 0) goto err;
  8364. static const char *shortname(const char *longname) {
  8365. const char *last = strrchr(longname, '.');
  8366. return last ? last + 1 : longname;
  8367. }
  8368. static int indent(upb_textprinter *p) {
  8369. int i;
  8370. if (!p->single_line_)
  8371. for (i = 0; i < p->indent_depth_; i++)
  8372. upb_bytessink_putbuf(p->output_, p->subc, " ", 2, NULL);
  8373. return 0;
  8374. }
  8375. static int endfield(upb_textprinter *p) {
  8376. const char ch = (p->single_line_ ? ' ' : '\n');
  8377. upb_bytessink_putbuf(p->output_, p->subc, &ch, 1, NULL);
  8378. return 0;
  8379. }
  8380. static int putescaped(upb_textprinter *p, const char *buf, size_t len,
  8381. bool preserve_utf8) {
  8382. /* Based on CEscapeInternal() from Google's protobuf release. */
  8383. char dstbuf[4096], *dst = dstbuf, *dstend = dstbuf + sizeof(dstbuf);
  8384. const char *end = buf + len;
  8385. /* I think hex is prettier and more useful, but proto2 uses octal; should
  8386. * investigate whether it can parse hex also. */
  8387. const bool use_hex = false;
  8388. bool last_hex_escape = false; /* true if last output char was \xNN */
  8389. for (; buf < end; buf++) {
  8390. bool is_hex_escape;
  8391. if (dstend - dst < 4) {
  8392. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  8393. dst = dstbuf;
  8394. }
  8395. is_hex_escape = false;
  8396. switch (*buf) {
  8397. case '\n': *(dst++) = '\\'; *(dst++) = 'n'; break;
  8398. case '\r': *(dst++) = '\\'; *(dst++) = 'r'; break;
  8399. case '\t': *(dst++) = '\\'; *(dst++) = 't'; break;
  8400. case '\"': *(dst++) = '\\'; *(dst++) = '\"'; break;
  8401. case '\'': *(dst++) = '\\'; *(dst++) = '\''; break;
  8402. case '\\': *(dst++) = '\\'; *(dst++) = '\\'; break;
  8403. default:
  8404. /* Note that if we emit \xNN and the buf character after that is a hex
  8405. * digit then that digit must be escaped too to prevent it being
  8406. * interpreted as part of the character code by C. */
  8407. if ((!preserve_utf8 || (uint8_t)*buf < 0x80) &&
  8408. (!isprint(*buf) || (last_hex_escape && isxdigit(*buf)))) {
  8409. sprintf(dst, (use_hex ? "\\x%02x" : "\\%03o"), (uint8_t)*buf);
  8410. is_hex_escape = use_hex;
  8411. dst += 4;
  8412. } else {
  8413. *(dst++) = *buf; break;
  8414. }
  8415. }
  8416. last_hex_escape = is_hex_escape;
  8417. }
  8418. /* Flush remaining data. */
  8419. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  8420. return 0;
  8421. }
  8422. bool putf(upb_textprinter *p, const char *fmt, ...) {
  8423. va_list args;
  8424. va_list args_copy;
  8425. char *str;
  8426. int written;
  8427. int len;
  8428. bool ok;
  8429. va_start(args, fmt);
  8430. /* Run once to get the length of the string. */
  8431. _upb_va_copy(args_copy, args);
  8432. len = _upb_vsnprintf(NULL, 0, fmt, args_copy);
  8433. va_end(args_copy);
  8434. /* + 1 for NULL terminator (vsprintf() requires it even if we don't). */
  8435. str = malloc(len + 1);
  8436. if (!str) return false;
  8437. written = vsprintf(str, fmt, args);
  8438. va_end(args);
  8439. UPB_ASSERT_VAR(written, written == len);
  8440. ok = upb_bytessink_putbuf(p->output_, p->subc, str, len, NULL);
  8441. free(str);
  8442. return ok;
  8443. }
  8444. /* handlers *******************************************************************/
  8445. static bool textprinter_startmsg(void *c, const void *hd) {
  8446. upb_textprinter *p = c;
  8447. UPB_UNUSED(hd);
  8448. if (p->indent_depth_ == 0) {
  8449. upb_bytessink_start(p->output_, 0, &p->subc);
  8450. }
  8451. return true;
  8452. }
  8453. static bool textprinter_endmsg(void *c, const void *hd, upb_status *s) {
  8454. upb_textprinter *p = c;
  8455. UPB_UNUSED(hd);
  8456. UPB_UNUSED(s);
  8457. if (p->indent_depth_ == 0) {
  8458. upb_bytessink_end(p->output_);
  8459. }
  8460. return true;
  8461. }
  8462. #define TYPE(name, ctype, fmt) \
  8463. static bool textprinter_put ## name(void *closure, const void *handler_data, \
  8464. ctype val) { \
  8465. upb_textprinter *p = closure; \
  8466. const upb_fielddef *f = handler_data; \
  8467. CHECK(indent(p)); \
  8468. putf(p, "%s: " fmt, upb_fielddef_name(f), val); \
  8469. CHECK(endfield(p)); \
  8470. return true; \
  8471. err: \
  8472. return false; \
  8473. }
  8474. static bool textprinter_putbool(void *closure, const void *handler_data,
  8475. bool val) {
  8476. upb_textprinter *p = closure;
  8477. const upb_fielddef *f = handler_data;
  8478. CHECK(indent(p));
  8479. putf(p, "%s: %s", upb_fielddef_name(f), val ? "true" : "false");
  8480. CHECK(endfield(p));
  8481. return true;
  8482. err:
  8483. return false;
  8484. }
  8485. #define STRINGIFY_HELPER(x) #x
  8486. #define STRINGIFY_MACROVAL(x) STRINGIFY_HELPER(x)
  8487. TYPE(int32, int32_t, "%" PRId32)
  8488. TYPE(int64, int64_t, "%" PRId64)
  8489. TYPE(uint32, uint32_t, "%" PRIu32)
  8490. TYPE(uint64, uint64_t, "%" PRIu64)
  8491. TYPE(float, float, "%." STRINGIFY_MACROVAL(FLT_DIG) "g")
  8492. TYPE(double, double, "%." STRINGIFY_MACROVAL(DBL_DIG) "g")
  8493. #undef TYPE
  8494. /* Output a symbolic value from the enum if found, else just print as int32. */
  8495. static bool textprinter_putenum(void *closure, const void *handler_data,
  8496. int32_t val) {
  8497. upb_textprinter *p = closure;
  8498. const upb_fielddef *f = handler_data;
  8499. const upb_enumdef *enum_def = upb_downcast_enumdef(upb_fielddef_subdef(f));
  8500. const char *label = upb_enumdef_iton(enum_def, val);
  8501. if (label) {
  8502. indent(p);
  8503. putf(p, "%s: %s", upb_fielddef_name(f), label);
  8504. endfield(p);
  8505. } else {
  8506. if (!textprinter_putint32(closure, handler_data, val))
  8507. return false;
  8508. }
  8509. return true;
  8510. }
  8511. static void *textprinter_startstr(void *closure, const void *handler_data,
  8512. size_t size_hint) {
  8513. upb_textprinter *p = closure;
  8514. const upb_fielddef *f = handler_data;
  8515. UPB_UNUSED(size_hint);
  8516. indent(p);
  8517. putf(p, "%s: \"", upb_fielddef_name(f));
  8518. return p;
  8519. }
  8520. static bool textprinter_endstr(void *closure, const void *handler_data) {
  8521. upb_textprinter *p = closure;
  8522. UPB_UNUSED(handler_data);
  8523. putf(p, "\"");
  8524. endfield(p);
  8525. return true;
  8526. }
  8527. static size_t textprinter_putstr(void *closure, const void *hd, const char *buf,
  8528. size_t len, const upb_bufhandle *handle) {
  8529. upb_textprinter *p = closure;
  8530. const upb_fielddef *f = hd;
  8531. UPB_UNUSED(handle);
  8532. CHECK(putescaped(p, buf, len, upb_fielddef_type(f) == UPB_TYPE_STRING));
  8533. return len;
  8534. err:
  8535. return 0;
  8536. }
  8537. static void *textprinter_startsubmsg(void *closure, const void *handler_data) {
  8538. upb_textprinter *p = closure;
  8539. const char *name = handler_data;
  8540. CHECK(indent(p));
  8541. putf(p, "%s {%c", name, p->single_line_ ? ' ' : '\n');
  8542. p->indent_depth_++;
  8543. return p;
  8544. err:
  8545. return UPB_BREAK;
  8546. }
  8547. static bool textprinter_endsubmsg(void *closure, const void *handler_data) {
  8548. upb_textprinter *p = closure;
  8549. UPB_UNUSED(handler_data);
  8550. p->indent_depth_--;
  8551. CHECK(indent(p));
  8552. upb_bytessink_putbuf(p->output_, p->subc, "}", 1, NULL);
  8553. CHECK(endfield(p));
  8554. return true;
  8555. err:
  8556. return false;
  8557. }
  8558. static void onmreg(const void *c, upb_handlers *h) {
  8559. const upb_msgdef *m = upb_handlers_msgdef(h);
  8560. upb_msg_field_iter i;
  8561. UPB_UNUSED(c);
  8562. upb_handlers_setstartmsg(h, textprinter_startmsg, NULL);
  8563. upb_handlers_setendmsg(h, textprinter_endmsg, NULL);
  8564. for(upb_msg_field_begin(&i, m);
  8565. !upb_msg_field_done(&i);
  8566. upb_msg_field_next(&i)) {
  8567. upb_fielddef *f = upb_msg_iter_field(&i);
  8568. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  8569. upb_handlerattr_sethandlerdata(&attr, f);
  8570. switch (upb_fielddef_type(f)) {
  8571. case UPB_TYPE_INT32:
  8572. upb_handlers_setint32(h, f, textprinter_putint32, &attr);
  8573. break;
  8574. case UPB_TYPE_INT64:
  8575. upb_handlers_setint64(h, f, textprinter_putint64, &attr);
  8576. break;
  8577. case UPB_TYPE_UINT32:
  8578. upb_handlers_setuint32(h, f, textprinter_putuint32, &attr);
  8579. break;
  8580. case UPB_TYPE_UINT64:
  8581. upb_handlers_setuint64(h, f, textprinter_putuint64, &attr);
  8582. break;
  8583. case UPB_TYPE_FLOAT:
  8584. upb_handlers_setfloat(h, f, textprinter_putfloat, &attr);
  8585. break;
  8586. case UPB_TYPE_DOUBLE:
  8587. upb_handlers_setdouble(h, f, textprinter_putdouble, &attr);
  8588. break;
  8589. case UPB_TYPE_BOOL:
  8590. upb_handlers_setbool(h, f, textprinter_putbool, &attr);
  8591. break;
  8592. case UPB_TYPE_STRING:
  8593. case UPB_TYPE_BYTES:
  8594. upb_handlers_setstartstr(h, f, textprinter_startstr, &attr);
  8595. upb_handlers_setstring(h, f, textprinter_putstr, &attr);
  8596. upb_handlers_setendstr(h, f, textprinter_endstr, &attr);
  8597. break;
  8598. case UPB_TYPE_MESSAGE: {
  8599. const char *name =
  8600. upb_fielddef_istagdelim(f)
  8601. ? shortname(upb_msgdef_fullname(upb_fielddef_msgsubdef(f)))
  8602. : upb_fielddef_name(f);
  8603. upb_handlerattr_sethandlerdata(&attr, name);
  8604. upb_handlers_setstartsubmsg(h, f, textprinter_startsubmsg, &attr);
  8605. upb_handlers_setendsubmsg(h, f, textprinter_endsubmsg, &attr);
  8606. break;
  8607. }
  8608. case UPB_TYPE_ENUM:
  8609. upb_handlers_setint32(h, f, textprinter_putenum, &attr);
  8610. break;
  8611. }
  8612. }
  8613. }
  8614. static void textprinter_reset(upb_textprinter *p, bool single_line) {
  8615. p->single_line_ = single_line;
  8616. p->indent_depth_ = 0;
  8617. }
  8618. /* Public API *****************************************************************/
  8619. upb_textprinter *upb_textprinter_create(upb_env *env, const upb_handlers *h,
  8620. upb_bytessink *output) {
  8621. upb_textprinter *p = upb_env_malloc(env, sizeof(upb_textprinter));
  8622. if (!p) return NULL;
  8623. p->output_ = output;
  8624. upb_sink_reset(&p->input_, h, p);
  8625. textprinter_reset(p, false);
  8626. return p;
  8627. }
  8628. const upb_handlers *upb_textprinter_newhandlers(const upb_msgdef *m,
  8629. const void *owner) {
  8630. return upb_handlers_newfrozen(m, owner, &onmreg, NULL);
  8631. }
  8632. upb_sink *upb_textprinter_input(upb_textprinter *p) { return &p->input_; }
  8633. void upb_textprinter_setsingleline(upb_textprinter *p, bool single_line) {
  8634. p->single_line_ = single_line;
  8635. }
  8636. /* Index is descriptor type. */
  8637. const uint8_t upb_pb_native_wire_types[] = {
  8638. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  8639. UPB_WIRE_TYPE_64BIT, /* DOUBLE */
  8640. UPB_WIRE_TYPE_32BIT, /* FLOAT */
  8641. UPB_WIRE_TYPE_VARINT, /* INT64 */
  8642. UPB_WIRE_TYPE_VARINT, /* UINT64 */
  8643. UPB_WIRE_TYPE_VARINT, /* INT32 */
  8644. UPB_WIRE_TYPE_64BIT, /* FIXED64 */
  8645. UPB_WIRE_TYPE_32BIT, /* FIXED32 */
  8646. UPB_WIRE_TYPE_VARINT, /* BOOL */
  8647. UPB_WIRE_TYPE_DELIMITED, /* STRING */
  8648. UPB_WIRE_TYPE_START_GROUP, /* GROUP */
  8649. UPB_WIRE_TYPE_DELIMITED, /* MESSAGE */
  8650. UPB_WIRE_TYPE_DELIMITED, /* BYTES */
  8651. UPB_WIRE_TYPE_VARINT, /* UINT32 */
  8652. UPB_WIRE_TYPE_VARINT, /* ENUM */
  8653. UPB_WIRE_TYPE_32BIT, /* SFIXED32 */
  8654. UPB_WIRE_TYPE_64BIT, /* SFIXED64 */
  8655. UPB_WIRE_TYPE_VARINT, /* SINT32 */
  8656. UPB_WIRE_TYPE_VARINT, /* SINT64 */
  8657. };
  8658. /* A basic branch-based decoder, uses 32-bit values to get good performance
  8659. * on 32-bit architectures (but performs well on 64-bits also).
  8660. * This scheme comes from the original Google Protobuf implementation
  8661. * (proto2). */
  8662. upb_decoderet upb_vdecode_max8_branch32(upb_decoderet r) {
  8663. upb_decoderet err = {NULL, 0};
  8664. const char *p = r.p;
  8665. uint32_t low = (uint32_t)r.val;
  8666. uint32_t high = 0;
  8667. uint32_t b;
  8668. b = *(p++); low |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  8669. b = *(p++); low |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  8670. b = *(p++); low |= (b & 0x7fU) << 28;
  8671. high = (b & 0x7fU) >> 4; if (!(b & 0x80)) goto done;
  8672. b = *(p++); high |= (b & 0x7fU) << 3; if (!(b & 0x80)) goto done;
  8673. b = *(p++); high |= (b & 0x7fU) << 10; if (!(b & 0x80)) goto done;
  8674. b = *(p++); high |= (b & 0x7fU) << 17; if (!(b & 0x80)) goto done;
  8675. b = *(p++); high |= (b & 0x7fU) << 24; if (!(b & 0x80)) goto done;
  8676. b = *(p++); high |= (b & 0x7fU) << 31; if (!(b & 0x80)) goto done;
  8677. return err;
  8678. done:
  8679. r.val = ((uint64_t)high << 32) | low;
  8680. r.p = p;
  8681. return r;
  8682. }
  8683. /* Like the previous, but uses 64-bit values. */
  8684. upb_decoderet upb_vdecode_max8_branch64(upb_decoderet r) {
  8685. const char *p = r.p;
  8686. uint64_t val = r.val;
  8687. uint64_t b;
  8688. upb_decoderet err = {NULL, 0};
  8689. b = *(p++); val |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  8690. b = *(p++); val |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  8691. b = *(p++); val |= (b & 0x7fU) << 28; if (!(b & 0x80)) goto done;
  8692. b = *(p++); val |= (b & 0x7fU) << 35; if (!(b & 0x80)) goto done;
  8693. b = *(p++); val |= (b & 0x7fU) << 42; if (!(b & 0x80)) goto done;
  8694. b = *(p++); val |= (b & 0x7fU) << 49; if (!(b & 0x80)) goto done;
  8695. b = *(p++); val |= (b & 0x7fU) << 56; if (!(b & 0x80)) goto done;
  8696. b = *(p++); val |= (b & 0x7fU) << 63; if (!(b & 0x80)) goto done;
  8697. return err;
  8698. done:
  8699. r.val = val;
  8700. r.p = p;
  8701. return r;
  8702. }
  8703. /* Given an encoded varint v, returns an integer with a single bit set that
  8704. * indicates the end of the varint. Subtracting one from this value will
  8705. * yield a mask that leaves only bits that are part of the varint. Returns
  8706. * 0 if the varint is unterminated. */
  8707. static uint64_t upb_get_vstopbit(uint64_t v) {
  8708. uint64_t cbits = v | 0x7f7f7f7f7f7f7f7fULL;
  8709. return ~cbits & (cbits+1);
  8710. }
  8711. /* A branchless decoder. Credit to Pascal Massimino for the bit-twiddling. */
  8712. upb_decoderet upb_vdecode_max8_massimino(upb_decoderet r) {
  8713. uint64_t b;
  8714. uint64_t stop_bit;
  8715. upb_decoderet my_r;
  8716. memcpy(&b, r.p, sizeof(b));
  8717. stop_bit = upb_get_vstopbit(b);
  8718. b = (b & 0x7f7f7f7f7f7f7f7fULL) & (stop_bit - 1);
  8719. b += b & 0x007f007f007f007fULL;
  8720. b += 3 * (b & 0x0000ffff0000ffffULL);
  8721. b += 15 * (b & 0x00000000ffffffffULL);
  8722. if (stop_bit == 0) {
  8723. /* Error: unterminated varint. */
  8724. upb_decoderet err_r = {(void*)0, 0};
  8725. return err_r;
  8726. }
  8727. my_r = upb_decoderet_make(r.p + ((__builtin_ctzll(stop_bit) + 1) / 8),
  8728. r.val | (b << 7));
  8729. return my_r;
  8730. }
  8731. /* A branchless decoder. Credit to Daniel Wright for the bit-twiddling. */
  8732. upb_decoderet upb_vdecode_max8_wright(upb_decoderet r) {
  8733. uint64_t b;
  8734. uint64_t stop_bit;
  8735. upb_decoderet my_r;
  8736. memcpy(&b, r.p, sizeof(b));
  8737. stop_bit = upb_get_vstopbit(b);
  8738. b &= (stop_bit - 1);
  8739. b = ((b & 0x7f007f007f007f00ULL) >> 1) | (b & 0x007f007f007f007fULL);
  8740. b = ((b & 0xffff0000ffff0000ULL) >> 2) | (b & 0x0000ffff0000ffffULL);
  8741. b = ((b & 0xffffffff00000000ULL) >> 4) | (b & 0x00000000ffffffffULL);
  8742. if (stop_bit == 0) {
  8743. /* Error: unterminated varint. */
  8744. upb_decoderet err_r = {(void*)0, 0};
  8745. return err_r;
  8746. }
  8747. my_r = upb_decoderet_make(r.p + ((__builtin_ctzll(stop_bit) + 1) / 8),
  8748. r.val | (b << 14));
  8749. return my_r;
  8750. }
  8751. #line 1 "upb/json/parser.rl"
  8752. /*
  8753. ** upb::json::Parser (upb_json_parser)
  8754. **
  8755. ** A parser that uses the Ragel State Machine Compiler to generate
  8756. ** the finite automata.
  8757. **
  8758. ** Ragel only natively handles regular languages, but we can manually
  8759. ** program it a bit to handle context-free languages like JSON, by using
  8760. ** the "fcall" and "fret" constructs.
  8761. **
  8762. ** This parser can handle the basics, but needs several things to be fleshed
  8763. ** out:
  8764. **
  8765. ** - handling of unicode escape sequences (including high surrogate pairs).
  8766. ** - properly check and report errors for unknown fields, stack overflow,
  8767. ** improper array nesting (or lack of nesting).
  8768. ** - handling of base64 sequences with padding characters.
  8769. ** - handling of push-back (non-success returns from sink functions).
  8770. ** - handling of keys/escape-sequences/etc that span input buffers.
  8771. */
  8772. #include <stdio.h>
  8773. #include <stdint.h>
  8774. #include <assert.h>
  8775. #include <string.h>
  8776. #include <stdlib.h>
  8777. #include <errno.h>
  8778. #define UPB_JSON_MAX_DEPTH 64
  8779. typedef struct {
  8780. upb_sink sink;
  8781. /* The current message in which we're parsing, and the field whose value we're
  8782. * expecting next. */
  8783. const upb_msgdef *m;
  8784. const upb_fielddef *f;
  8785. /* The table mapping json name to fielddef for this message. */
  8786. upb_strtable *name_table;
  8787. /* We are in a repeated-field context, ready to emit mapentries as
  8788. * submessages. This flag alters the start-of-object (open-brace) behavior to
  8789. * begin a sequence of mapentry messages rather than a single submessage. */
  8790. bool is_map;
  8791. /* We are in a map-entry message context. This flag is set when parsing the
  8792. * value field of a single map entry and indicates to all value-field parsers
  8793. * (subobjects, strings, numbers, and bools) that the map-entry submessage
  8794. * should end as soon as the value is parsed. */
  8795. bool is_mapentry;
  8796. /* If |is_map| or |is_mapentry| is true, |mapfield| refers to the parent
  8797. * message's map field that we're currently parsing. This differs from |f|
  8798. * because |f| is the field in the *current* message (i.e., the map-entry
  8799. * message itself), not the parent's field that leads to this map. */
  8800. const upb_fielddef *mapfield;
  8801. } upb_jsonparser_frame;
  8802. struct upb_json_parser {
  8803. upb_env *env;
  8804. const upb_json_parsermethod *method;
  8805. upb_bytessink input_;
  8806. /* Stack to track the JSON scopes we are in. */
  8807. upb_jsonparser_frame stack[UPB_JSON_MAX_DEPTH];
  8808. upb_jsonparser_frame *top;
  8809. upb_jsonparser_frame *limit;
  8810. upb_status status;
  8811. /* Ragel's internal parsing stack for the parsing state machine. */
  8812. int current_state;
  8813. int parser_stack[UPB_JSON_MAX_DEPTH];
  8814. int parser_top;
  8815. /* The handle for the current buffer. */
  8816. const upb_bufhandle *handle;
  8817. /* Accumulate buffer. See details in parser.rl. */
  8818. const char *accumulated;
  8819. size_t accumulated_len;
  8820. char *accumulate_buf;
  8821. size_t accumulate_buf_size;
  8822. /* Multi-part text data. See details in parser.rl. */
  8823. int multipart_state;
  8824. upb_selector_t string_selector;
  8825. /* Input capture. See details in parser.rl. */
  8826. const char *capture;
  8827. /* Intermediate result of parsing a unicode escape sequence. */
  8828. uint32_t digit;
  8829. };
  8830. struct upb_json_parsermethod {
  8831. upb_refcounted base;
  8832. upb_byteshandler input_handler_;
  8833. /* Mainly for the purposes of refcounting, so all the fielddefs we point
  8834. * to stay alive. */
  8835. const upb_msgdef *msg;
  8836. /* Keys are upb_msgdef*, values are upb_strtable (json_name -> fielddef) */
  8837. upb_inttable name_tables;
  8838. };
  8839. #define PARSER_CHECK_RETURN(x) if (!(x)) return false
  8840. /* Used to signal that a capture has been suspended. */
  8841. static char suspend_capture;
  8842. static upb_selector_t getsel_for_handlertype(upb_json_parser *p,
  8843. upb_handlertype_t type) {
  8844. upb_selector_t sel;
  8845. bool ok = upb_handlers_getselector(p->top->f, type, &sel);
  8846. UPB_ASSERT_VAR(ok, ok);
  8847. return sel;
  8848. }
  8849. static upb_selector_t parser_getsel(upb_json_parser *p) {
  8850. return getsel_for_handlertype(
  8851. p, upb_handlers_getprimitivehandlertype(p->top->f));
  8852. }
  8853. static bool check_stack(upb_json_parser *p) {
  8854. if ((p->top + 1) == p->limit) {
  8855. upb_status_seterrmsg(&p->status, "Nesting too deep");
  8856. upb_env_reporterror(p->env, &p->status);
  8857. return false;
  8858. }
  8859. return true;
  8860. }
  8861. static void set_name_table(upb_json_parser *p, upb_jsonparser_frame *frame) {
  8862. upb_value v;
  8863. bool ok = upb_inttable_lookupptr(&p->method->name_tables, frame->m, &v);
  8864. UPB_ASSERT_VAR(ok, ok);
  8865. frame->name_table = upb_value_getptr(v);
  8866. }
  8867. /* There are GCC/Clang built-ins for overflow checking which we could start
  8868. * using if there was any performance benefit to it. */
  8869. static bool checked_add(size_t a, size_t b, size_t *c) {
  8870. if (SIZE_MAX - a < b) return false;
  8871. *c = a + b;
  8872. return true;
  8873. }
  8874. static size_t saturating_multiply(size_t a, size_t b) {
  8875. /* size_t is unsigned, so this is defined behavior even on overflow. */
  8876. size_t ret = a * b;
  8877. if (b != 0 && ret / b != a) {
  8878. ret = SIZE_MAX;
  8879. }
  8880. return ret;
  8881. }
  8882. /* Base64 decoding ************************************************************/
  8883. /* TODO(haberman): make this streaming. */
  8884. static const signed char b64table[] = {
  8885. -1, -1, -1, -1, -1, -1, -1, -1,
  8886. -1, -1, -1, -1, -1, -1, -1, -1,
  8887. -1, -1, -1, -1, -1, -1, -1, -1,
  8888. -1, -1, -1, -1, -1, -1, -1, -1,
  8889. -1, -1, -1, -1, -1, -1, -1, -1,
  8890. -1, -1, -1, 62/*+*/, -1, -1, -1, 63/*/ */,
  8891. 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
  8892. 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1,
  8893. -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
  8894. 07/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
  8895. 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
  8896. 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, -1,
  8897. -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
  8898. 33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
  8899. 41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
  8900. 49/*x*/, 50/*y*/, 51/*z*/, -1, -1, -1, -1, -1,
  8901. -1, -1, -1, -1, -1, -1, -1, -1,
  8902. -1, -1, -1, -1, -1, -1, -1, -1,
  8903. -1, -1, -1, -1, -1, -1, -1, -1,
  8904. -1, -1, -1, -1, -1, -1, -1, -1,
  8905. -1, -1, -1, -1, -1, -1, -1, -1,
  8906. -1, -1, -1, -1, -1, -1, -1, -1,
  8907. -1, -1, -1, -1, -1, -1, -1, -1,
  8908. -1, -1, -1, -1, -1, -1, -1, -1,
  8909. -1, -1, -1, -1, -1, -1, -1, -1,
  8910. -1, -1, -1, -1, -1, -1, -1, -1,
  8911. -1, -1, -1, -1, -1, -1, -1, -1,
  8912. -1, -1, -1, -1, -1, -1, -1, -1,
  8913. -1, -1, -1, -1, -1, -1, -1, -1,
  8914. -1, -1, -1, -1, -1, -1, -1, -1,
  8915. -1, -1, -1, -1, -1, -1, -1, -1,
  8916. -1, -1, -1, -1, -1, -1, -1, -1
  8917. };
  8918. /* Returns the table value sign-extended to 32 bits. Knowing that the upper
  8919. * bits will be 1 for unrecognized characters makes it easier to check for
  8920. * this error condition later (see below). */
  8921. int32_t b64lookup(unsigned char ch) { return b64table[ch]; }
  8922. /* Returns true if the given character is not a valid base64 character or
  8923. * padding. */
  8924. bool nonbase64(unsigned char ch) { return b64lookup(ch) == -1 && ch != '='; }
  8925. static bool base64_push(upb_json_parser *p, upb_selector_t sel, const char *ptr,
  8926. size_t len) {
  8927. const char *limit = ptr + len;
  8928. for (; ptr < limit; ptr += 4) {
  8929. uint32_t val;
  8930. char output[3];
  8931. if (limit - ptr < 4) {
  8932. upb_status_seterrf(&p->status,
  8933. "Base64 input for bytes field not a multiple of 4: %s",
  8934. upb_fielddef_name(p->top->f));
  8935. upb_env_reporterror(p->env, &p->status);
  8936. return false;
  8937. }
  8938. val = b64lookup(ptr[0]) << 18 |
  8939. b64lookup(ptr[1]) << 12 |
  8940. b64lookup(ptr[2]) << 6 |
  8941. b64lookup(ptr[3]);
  8942. /* Test the upper bit; returns true if any of the characters returned -1. */
  8943. if (val & 0x80000000) {
  8944. goto otherchar;
  8945. }
  8946. output[0] = val >> 16;
  8947. output[1] = (val >> 8) & 0xff;
  8948. output[2] = val & 0xff;
  8949. upb_sink_putstring(&p->top->sink, sel, output, 3, NULL);
  8950. }
  8951. return true;
  8952. otherchar:
  8953. if (nonbase64(ptr[0]) || nonbase64(ptr[1]) || nonbase64(ptr[2]) ||
  8954. nonbase64(ptr[3]) ) {
  8955. upb_status_seterrf(&p->status,
  8956. "Non-base64 characters in bytes field: %s",
  8957. upb_fielddef_name(p->top->f));
  8958. upb_env_reporterror(p->env, &p->status);
  8959. return false;
  8960. } if (ptr[2] == '=') {
  8961. uint32_t val;
  8962. char output;
  8963. /* Last group contains only two input bytes, one output byte. */
  8964. if (ptr[0] == '=' || ptr[1] == '=' || ptr[3] != '=') {
  8965. goto badpadding;
  8966. }
  8967. val = b64lookup(ptr[0]) << 18 |
  8968. b64lookup(ptr[1]) << 12;
  8969. assert(!(val & 0x80000000));
  8970. output = val >> 16;
  8971. upb_sink_putstring(&p->top->sink, sel, &output, 1, NULL);
  8972. return true;
  8973. } else {
  8974. uint32_t val;
  8975. char output[2];
  8976. /* Last group contains only three input bytes, two output bytes. */
  8977. if (ptr[0] == '=' || ptr[1] == '=' || ptr[2] == '=') {
  8978. goto badpadding;
  8979. }
  8980. val = b64lookup(ptr[0]) << 18 |
  8981. b64lookup(ptr[1]) << 12 |
  8982. b64lookup(ptr[2]) << 6;
  8983. output[0] = val >> 16;
  8984. output[1] = (val >> 8) & 0xff;
  8985. upb_sink_putstring(&p->top->sink, sel, output, 2, NULL);
  8986. return true;
  8987. }
  8988. badpadding:
  8989. upb_status_seterrf(&p->status,
  8990. "Incorrect base64 padding for field: %s (%.*s)",
  8991. upb_fielddef_name(p->top->f),
  8992. 4, ptr);
  8993. upb_env_reporterror(p->env, &p->status);
  8994. return false;
  8995. }
  8996. /* Accumulate buffer **********************************************************/
  8997. /* Functionality for accumulating a buffer.
  8998. *
  8999. * Some parts of the parser need an entire value as a contiguous string. For
  9000. * example, to look up a member name in a hash table, or to turn a string into
  9001. * a number, the relevant library routines need the input string to be in
  9002. * contiguous memory, even if the value spanned two or more buffers in the
  9003. * input. These routines handle that.
  9004. *
  9005. * In the common case we can just point to the input buffer to get this
  9006. * contiguous string and avoid any actual copy. So we optimistically begin
  9007. * this way. But there are a few cases where we must instead copy into a
  9008. * separate buffer:
  9009. *
  9010. * 1. The string was not contiguous in the input (it spanned buffers).
  9011. *
  9012. * 2. The string included escape sequences that need to be interpreted to get
  9013. * the true value in a contiguous buffer. */
  9014. static void assert_accumulate_empty(upb_json_parser *p) {
  9015. UPB_UNUSED(p);
  9016. assert(p->accumulated == NULL);
  9017. assert(p->accumulated_len == 0);
  9018. }
  9019. static void accumulate_clear(upb_json_parser *p) {
  9020. p->accumulated = NULL;
  9021. p->accumulated_len = 0;
  9022. }
  9023. /* Used internally by accumulate_append(). */
  9024. static bool accumulate_realloc(upb_json_parser *p, size_t need) {
  9025. void *mem;
  9026. size_t old_size = p->accumulate_buf_size;
  9027. size_t new_size = UPB_MAX(old_size, 128);
  9028. while (new_size < need) {
  9029. new_size = saturating_multiply(new_size, 2);
  9030. }
  9031. mem = upb_env_realloc(p->env, p->accumulate_buf, old_size, new_size);
  9032. if (!mem) {
  9033. upb_status_seterrmsg(&p->status, "Out of memory allocating buffer.");
  9034. upb_env_reporterror(p->env, &p->status);
  9035. return false;
  9036. }
  9037. p->accumulate_buf = mem;
  9038. p->accumulate_buf_size = new_size;
  9039. return true;
  9040. }
  9041. /* Logically appends the given data to the append buffer.
  9042. * If "can_alias" is true, we will try to avoid actually copying, but the buffer
  9043. * must be valid until the next accumulate_append() call (if any). */
  9044. static bool accumulate_append(upb_json_parser *p, const char *buf, size_t len,
  9045. bool can_alias) {
  9046. size_t need;
  9047. if (!p->accumulated && can_alias) {
  9048. p->accumulated = buf;
  9049. p->accumulated_len = len;
  9050. return true;
  9051. }
  9052. if (!checked_add(p->accumulated_len, len, &need)) {
  9053. upb_status_seterrmsg(&p->status, "Integer overflow.");
  9054. upb_env_reporterror(p->env, &p->status);
  9055. return false;
  9056. }
  9057. if (need > p->accumulate_buf_size && !accumulate_realloc(p, need)) {
  9058. return false;
  9059. }
  9060. if (p->accumulated != p->accumulate_buf) {
  9061. memcpy(p->accumulate_buf, p->accumulated, p->accumulated_len);
  9062. p->accumulated = p->accumulate_buf;
  9063. }
  9064. memcpy(p->accumulate_buf + p->accumulated_len, buf, len);
  9065. p->accumulated_len += len;
  9066. return true;
  9067. }
  9068. /* Returns a pointer to the data accumulated since the last accumulate_clear()
  9069. * call, and writes the length to *len. This with point either to the input
  9070. * buffer or a temporary accumulate buffer. */
  9071. static const char *accumulate_getptr(upb_json_parser *p, size_t *len) {
  9072. assert(p->accumulated);
  9073. *len = p->accumulated_len;
  9074. return p->accumulated;
  9075. }
  9076. /* Mult-part text data ********************************************************/
  9077. /* When we have text data in the input, it can often come in multiple segments.
  9078. * For example, there may be some raw string data followed by an escape
  9079. * sequence. The two segments are processed with different logic. Also buffer
  9080. * seams in the input can cause multiple segments.
  9081. *
  9082. * As we see segments, there are two main cases for how we want to process them:
  9083. *
  9084. * 1. we want to push the captured input directly to string handlers.
  9085. *
  9086. * 2. we need to accumulate all the parts into a contiguous buffer for further
  9087. * processing (field name lookup, string->number conversion, etc). */
  9088. /* This is the set of states for p->multipart_state. */
  9089. enum {
  9090. /* We are not currently processing multipart data. */
  9091. MULTIPART_INACTIVE = 0,
  9092. /* We are processing multipart data by accumulating it into a contiguous
  9093. * buffer. */
  9094. MULTIPART_ACCUMULATE = 1,
  9095. /* We are processing multipart data by pushing each part directly to the
  9096. * current string handlers. */
  9097. MULTIPART_PUSHEAGERLY = 2
  9098. };
  9099. /* Start a multi-part text value where we accumulate the data for processing at
  9100. * the end. */
  9101. static void multipart_startaccum(upb_json_parser *p) {
  9102. assert_accumulate_empty(p);
  9103. assert(p->multipart_state == MULTIPART_INACTIVE);
  9104. p->multipart_state = MULTIPART_ACCUMULATE;
  9105. }
  9106. /* Start a multi-part text value where we immediately push text data to a string
  9107. * value with the given selector. */
  9108. static void multipart_start(upb_json_parser *p, upb_selector_t sel) {
  9109. assert_accumulate_empty(p);
  9110. assert(p->multipart_state == MULTIPART_INACTIVE);
  9111. p->multipart_state = MULTIPART_PUSHEAGERLY;
  9112. p->string_selector = sel;
  9113. }
  9114. static bool multipart_text(upb_json_parser *p, const char *buf, size_t len,
  9115. bool can_alias) {
  9116. switch (p->multipart_state) {
  9117. case MULTIPART_INACTIVE:
  9118. upb_status_seterrmsg(
  9119. &p->status, "Internal error: unexpected state MULTIPART_INACTIVE");
  9120. upb_env_reporterror(p->env, &p->status);
  9121. return false;
  9122. case MULTIPART_ACCUMULATE:
  9123. if (!accumulate_append(p, buf, len, can_alias)) {
  9124. return false;
  9125. }
  9126. break;
  9127. case MULTIPART_PUSHEAGERLY: {
  9128. const upb_bufhandle *handle = can_alias ? p->handle : NULL;
  9129. upb_sink_putstring(&p->top->sink, p->string_selector, buf, len, handle);
  9130. break;
  9131. }
  9132. }
  9133. return true;
  9134. }
  9135. /* Note: this invalidates the accumulate buffer! Call only after reading its
  9136. * contents. */
  9137. static void multipart_end(upb_json_parser *p) {
  9138. assert(p->multipart_state != MULTIPART_INACTIVE);
  9139. p->multipart_state = MULTIPART_INACTIVE;
  9140. accumulate_clear(p);
  9141. }
  9142. /* Input capture **************************************************************/
  9143. /* Functionality for capturing a region of the input as text. Gracefully
  9144. * handles the case where a buffer seam occurs in the middle of the captured
  9145. * region. */
  9146. static void capture_begin(upb_json_parser *p, const char *ptr) {
  9147. assert(p->multipart_state != MULTIPART_INACTIVE);
  9148. assert(p->capture == NULL);
  9149. p->capture = ptr;
  9150. }
  9151. static bool capture_end(upb_json_parser *p, const char *ptr) {
  9152. assert(p->capture);
  9153. if (multipart_text(p, p->capture, ptr - p->capture, true)) {
  9154. p->capture = NULL;
  9155. return true;
  9156. } else {
  9157. return false;
  9158. }
  9159. }
  9160. /* This is called at the end of each input buffer (ie. when we have hit a
  9161. * buffer seam). If we are in the middle of capturing the input, this
  9162. * processes the unprocessed capture region. */
  9163. static void capture_suspend(upb_json_parser *p, const char **ptr) {
  9164. if (!p->capture) return;
  9165. if (multipart_text(p, p->capture, *ptr - p->capture, false)) {
  9166. /* We use this as a signal that we were in the middle of capturing, and
  9167. * that capturing should resume at the beginning of the next buffer.
  9168. *
  9169. * We can't use *ptr here, because we have no guarantee that this pointer
  9170. * will be valid when we resume (if the underlying memory is freed, then
  9171. * using the pointer at all, even to compare to NULL, is likely undefined
  9172. * behavior). */
  9173. p->capture = &suspend_capture;
  9174. } else {
  9175. /* Need to back up the pointer to the beginning of the capture, since
  9176. * we were not able to actually preserve it. */
  9177. *ptr = p->capture;
  9178. }
  9179. }
  9180. static void capture_resume(upb_json_parser *p, const char *ptr) {
  9181. if (p->capture) {
  9182. assert(p->capture == &suspend_capture);
  9183. p->capture = ptr;
  9184. }
  9185. }
  9186. /* Callbacks from the parser **************************************************/
  9187. /* These are the functions called directly from the parser itself.
  9188. * We define these in the same order as their declarations in the parser. */
  9189. static char escape_char(char in) {
  9190. switch (in) {
  9191. case 'r': return '\r';
  9192. case 't': return '\t';
  9193. case 'n': return '\n';
  9194. case 'f': return '\f';
  9195. case 'b': return '\b';
  9196. case '/': return '/';
  9197. case '"': return '"';
  9198. case '\\': return '\\';
  9199. default:
  9200. assert(0);
  9201. return 'x';
  9202. }
  9203. }
  9204. static bool escape(upb_json_parser *p, const char *ptr) {
  9205. char ch = escape_char(*ptr);
  9206. return multipart_text(p, &ch, 1, false);
  9207. }
  9208. static void start_hex(upb_json_parser *p) {
  9209. p->digit = 0;
  9210. }
  9211. static void hexdigit(upb_json_parser *p, const char *ptr) {
  9212. char ch = *ptr;
  9213. p->digit <<= 4;
  9214. if (ch >= '0' && ch <= '9') {
  9215. p->digit += (ch - '0');
  9216. } else if (ch >= 'a' && ch <= 'f') {
  9217. p->digit += ((ch - 'a') + 10);
  9218. } else {
  9219. assert(ch >= 'A' && ch <= 'F');
  9220. p->digit += ((ch - 'A') + 10);
  9221. }
  9222. }
  9223. static bool end_hex(upb_json_parser *p) {
  9224. uint32_t codepoint = p->digit;
  9225. /* emit the codepoint as UTF-8. */
  9226. char utf8[3]; /* support \u0000 -- \uFFFF -- need only three bytes. */
  9227. int length = 0;
  9228. if (codepoint <= 0x7F) {
  9229. utf8[0] = codepoint;
  9230. length = 1;
  9231. } else if (codepoint <= 0x07FF) {
  9232. utf8[1] = (codepoint & 0x3F) | 0x80;
  9233. codepoint >>= 6;
  9234. utf8[0] = (codepoint & 0x1F) | 0xC0;
  9235. length = 2;
  9236. } else /* codepoint <= 0xFFFF */ {
  9237. utf8[2] = (codepoint & 0x3F) | 0x80;
  9238. codepoint >>= 6;
  9239. utf8[1] = (codepoint & 0x3F) | 0x80;
  9240. codepoint >>= 6;
  9241. utf8[0] = (codepoint & 0x0F) | 0xE0;
  9242. length = 3;
  9243. }
  9244. /* TODO(haberman): Handle high surrogates: if codepoint is a high surrogate
  9245. * we have to wait for the next escape to get the full code point). */
  9246. return multipart_text(p, utf8, length, false);
  9247. }
  9248. static void start_text(upb_json_parser *p, const char *ptr) {
  9249. capture_begin(p, ptr);
  9250. }
  9251. static bool end_text(upb_json_parser *p, const char *ptr) {
  9252. return capture_end(p, ptr);
  9253. }
  9254. static void start_number(upb_json_parser *p, const char *ptr) {
  9255. multipart_startaccum(p);
  9256. capture_begin(p, ptr);
  9257. }
  9258. static bool parse_number(upb_json_parser *p);
  9259. static bool end_number(upb_json_parser *p, const char *ptr) {
  9260. if (!capture_end(p, ptr)) {
  9261. return false;
  9262. }
  9263. return parse_number(p);
  9264. }
  9265. static bool parse_number(upb_json_parser *p) {
  9266. size_t len;
  9267. const char *buf;
  9268. const char *myend;
  9269. char *end;
  9270. /* strtol() and friends unfortunately do not support specifying the length of
  9271. * the input string, so we need to force a copy into a NULL-terminated buffer. */
  9272. if (!multipart_text(p, "\0", 1, false)) {
  9273. return false;
  9274. }
  9275. buf = accumulate_getptr(p, &len);
  9276. myend = buf + len - 1; /* One for NULL. */
  9277. /* XXX: We are using strtol to parse integers, but this is wrong as even
  9278. * integers can be represented as 1e6 (for example), which strtol can't
  9279. * handle correctly.
  9280. *
  9281. * XXX: Also, we can't handle large integers properly because strto[u]ll
  9282. * isn't in C89.
  9283. *
  9284. * XXX: Also, we don't properly check floats for overflow, since strtof
  9285. * isn't in C89. */
  9286. switch (upb_fielddef_type(p->top->f)) {
  9287. case UPB_TYPE_ENUM:
  9288. case UPB_TYPE_INT32: {
  9289. long val = strtol(p->accumulated, &end, 0);
  9290. if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || end != myend)
  9291. goto err;
  9292. else
  9293. upb_sink_putint32(&p->top->sink, parser_getsel(p), val);
  9294. break;
  9295. }
  9296. case UPB_TYPE_INT64: {
  9297. long long val = strtol(p->accumulated, &end, 0);
  9298. if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || end != myend)
  9299. goto err;
  9300. else
  9301. upb_sink_putint64(&p->top->sink, parser_getsel(p), val);
  9302. break;
  9303. }
  9304. case UPB_TYPE_UINT32: {
  9305. unsigned long val = strtoul(p->accumulated, &end, 0);
  9306. if (val > UINT32_MAX || errno == ERANGE || end != myend)
  9307. goto err;
  9308. else
  9309. upb_sink_putuint32(&p->top->sink, parser_getsel(p), val);
  9310. break;
  9311. }
  9312. case UPB_TYPE_UINT64: {
  9313. unsigned long long val = strtoul(p->accumulated, &end, 0);
  9314. if (val > UINT64_MAX || errno == ERANGE || end != myend)
  9315. goto err;
  9316. else
  9317. upb_sink_putuint64(&p->top->sink, parser_getsel(p), val);
  9318. break;
  9319. }
  9320. case UPB_TYPE_DOUBLE: {
  9321. double val = strtod(p->accumulated, &end);
  9322. if (errno == ERANGE || end != myend)
  9323. goto err;
  9324. else
  9325. upb_sink_putdouble(&p->top->sink, parser_getsel(p), val);
  9326. break;
  9327. }
  9328. case UPB_TYPE_FLOAT: {
  9329. float val = strtod(p->accumulated, &end);
  9330. if (errno == ERANGE || end != myend)
  9331. goto err;
  9332. else
  9333. upb_sink_putfloat(&p->top->sink, parser_getsel(p), val);
  9334. break;
  9335. }
  9336. default:
  9337. assert(false);
  9338. }
  9339. multipart_end(p);
  9340. return true;
  9341. err:
  9342. upb_status_seterrf(&p->status, "error parsing number: %s", buf);
  9343. upb_env_reporterror(p->env, &p->status);
  9344. multipart_end(p);
  9345. return false;
  9346. }
  9347. static bool parser_putbool(upb_json_parser *p, bool val) {
  9348. bool ok;
  9349. if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL) {
  9350. upb_status_seterrf(&p->status,
  9351. "Boolean value specified for non-bool field: %s",
  9352. upb_fielddef_name(p->top->f));
  9353. upb_env_reporterror(p->env, &p->status);
  9354. return false;
  9355. }
  9356. ok = upb_sink_putbool(&p->top->sink, parser_getsel(p), val);
  9357. UPB_ASSERT_VAR(ok, ok);
  9358. return true;
  9359. }
  9360. static bool start_stringval(upb_json_parser *p) {
  9361. assert(p->top->f);
  9362. if (upb_fielddef_isstring(p->top->f)) {
  9363. upb_jsonparser_frame *inner;
  9364. upb_selector_t sel;
  9365. if (!check_stack(p)) return false;
  9366. /* Start a new parser frame: parser frames correspond one-to-one with
  9367. * handler frames, and string events occur in a sub-frame. */
  9368. inner = p->top + 1;
  9369. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  9370. upb_sink_startstr(&p->top->sink, sel, 0, &inner->sink);
  9371. inner->m = p->top->m;
  9372. inner->f = p->top->f;
  9373. inner->name_table = NULL;
  9374. inner->is_map = false;
  9375. inner->is_mapentry = false;
  9376. p->top = inner;
  9377. if (upb_fielddef_type(p->top->f) == UPB_TYPE_STRING) {
  9378. /* For STRING fields we push data directly to the handlers as it is
  9379. * parsed. We don't do this yet for BYTES fields, because our base64
  9380. * decoder is not streaming.
  9381. *
  9382. * TODO(haberman): make base64 decoding streaming also. */
  9383. multipart_start(p, getsel_for_handlertype(p, UPB_HANDLER_STRING));
  9384. return true;
  9385. } else {
  9386. multipart_startaccum(p);
  9387. return true;
  9388. }
  9389. } else if (upb_fielddef_type(p->top->f) == UPB_TYPE_ENUM) {
  9390. /* No need to push a frame -- symbolic enum names in quotes remain in the
  9391. * current parser frame.
  9392. *
  9393. * Enum string values must accumulate so we can look up the value in a table
  9394. * once it is complete. */
  9395. multipart_startaccum(p);
  9396. return true;
  9397. } else {
  9398. upb_status_seterrf(&p->status,
  9399. "String specified for non-string/non-enum field: %s",
  9400. upb_fielddef_name(p->top->f));
  9401. upb_env_reporterror(p->env, &p->status);
  9402. return false;
  9403. }
  9404. }
  9405. static bool end_stringval(upb_json_parser *p) {
  9406. bool ok = true;
  9407. switch (upb_fielddef_type(p->top->f)) {
  9408. case UPB_TYPE_BYTES:
  9409. if (!base64_push(p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  9410. p->accumulated, p->accumulated_len)) {
  9411. return false;
  9412. }
  9413. /* Fall through. */
  9414. case UPB_TYPE_STRING: {
  9415. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  9416. upb_sink_endstr(&p->top->sink, sel);
  9417. p->top--;
  9418. break;
  9419. }
  9420. case UPB_TYPE_ENUM: {
  9421. /* Resolve enum symbolic name to integer value. */
  9422. const upb_enumdef *enumdef =
  9423. (const upb_enumdef*)upb_fielddef_subdef(p->top->f);
  9424. size_t len;
  9425. const char *buf = accumulate_getptr(p, &len);
  9426. int32_t int_val = 0;
  9427. ok = upb_enumdef_ntoi(enumdef, buf, len, &int_val);
  9428. if (ok) {
  9429. upb_selector_t sel = parser_getsel(p);
  9430. upb_sink_putint32(&p->top->sink, sel, int_val);
  9431. } else {
  9432. upb_status_seterrf(&p->status, "Enum value unknown: '%.*s'", len, buf);
  9433. upb_env_reporterror(p->env, &p->status);
  9434. }
  9435. break;
  9436. }
  9437. default:
  9438. assert(false);
  9439. upb_status_seterrmsg(&p->status, "Internal error in JSON decoder");
  9440. upb_env_reporterror(p->env, &p->status);
  9441. ok = false;
  9442. break;
  9443. }
  9444. multipart_end(p);
  9445. return ok;
  9446. }
  9447. static void start_member(upb_json_parser *p) {
  9448. assert(!p->top->f);
  9449. multipart_startaccum(p);
  9450. }
  9451. /* Helper: invoked during parse_mapentry() to emit the mapentry message's key
  9452. * field based on the current contents of the accumulate buffer. */
  9453. static bool parse_mapentry_key(upb_json_parser *p) {
  9454. size_t len;
  9455. const char *buf = accumulate_getptr(p, &len);
  9456. /* Emit the key field. We do a bit of ad-hoc parsing here because the
  9457. * parser state machine has already decided that this is a string field
  9458. * name, and we are reinterpreting it as some arbitrary key type. In
  9459. * particular, integer and bool keys are quoted, so we need to parse the
  9460. * quoted string contents here. */
  9461. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_KEY);
  9462. if (p->top->f == NULL) {
  9463. upb_status_seterrmsg(&p->status, "mapentry message has no key");
  9464. upb_env_reporterror(p->env, &p->status);
  9465. return false;
  9466. }
  9467. switch (upb_fielddef_type(p->top->f)) {
  9468. case UPB_TYPE_INT32:
  9469. case UPB_TYPE_INT64:
  9470. case UPB_TYPE_UINT32:
  9471. case UPB_TYPE_UINT64:
  9472. /* Invoke end_number. The accum buffer has the number's text already. */
  9473. if (!parse_number(p)) {
  9474. return false;
  9475. }
  9476. break;
  9477. case UPB_TYPE_BOOL:
  9478. if (len == 4 && !strncmp(buf, "true", 4)) {
  9479. if (!parser_putbool(p, true)) {
  9480. return false;
  9481. }
  9482. } else if (len == 5 && !strncmp(buf, "false", 5)) {
  9483. if (!parser_putbool(p, false)) {
  9484. return false;
  9485. }
  9486. } else {
  9487. upb_status_seterrmsg(&p->status,
  9488. "Map bool key not 'true' or 'false'");
  9489. upb_env_reporterror(p->env, &p->status);
  9490. return false;
  9491. }
  9492. multipart_end(p);
  9493. break;
  9494. case UPB_TYPE_STRING:
  9495. case UPB_TYPE_BYTES: {
  9496. upb_sink subsink;
  9497. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  9498. upb_sink_startstr(&p->top->sink, sel, len, &subsink);
  9499. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  9500. upb_sink_putstring(&subsink, sel, buf, len, NULL);
  9501. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  9502. upb_sink_endstr(&subsink, sel);
  9503. multipart_end(p);
  9504. break;
  9505. }
  9506. default:
  9507. upb_status_seterrmsg(&p->status, "Invalid field type for map key");
  9508. upb_env_reporterror(p->env, &p->status);
  9509. return false;
  9510. }
  9511. return true;
  9512. }
  9513. /* Helper: emit one map entry (as a submessage in the map field sequence). This
  9514. * is invoked from end_membername(), at the end of the map entry's key string,
  9515. * with the map key in the accumulate buffer. It parses the key from that
  9516. * buffer, emits the handler calls to start the mapentry submessage (setting up
  9517. * its subframe in the process), and sets up state in the subframe so that the
  9518. * value parser (invoked next) will emit the mapentry's value field and then
  9519. * end the mapentry message. */
  9520. static bool handle_mapentry(upb_json_parser *p) {
  9521. const upb_fielddef *mapfield;
  9522. const upb_msgdef *mapentrymsg;
  9523. upb_jsonparser_frame *inner;
  9524. upb_selector_t sel;
  9525. /* Map entry: p->top->sink is the seq frame, so we need to start a frame
  9526. * for the mapentry itself, and then set |f| in that frame so that the map
  9527. * value field is parsed, and also set a flag to end the frame after the
  9528. * map-entry value is parsed. */
  9529. if (!check_stack(p)) return false;
  9530. mapfield = p->top->mapfield;
  9531. mapentrymsg = upb_fielddef_msgsubdef(mapfield);
  9532. inner = p->top + 1;
  9533. p->top->f = mapfield;
  9534. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  9535. upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
  9536. inner->m = mapentrymsg;
  9537. inner->name_table = NULL;
  9538. inner->mapfield = mapfield;
  9539. inner->is_map = false;
  9540. /* Don't set this to true *yet* -- we reuse parsing handlers below to push
  9541. * the key field value to the sink, and these handlers will pop the frame
  9542. * if they see is_mapentry (when invoked by the parser state machine, they
  9543. * would have just seen the map-entry value, not key). */
  9544. inner->is_mapentry = false;
  9545. p->top = inner;
  9546. /* send STARTMSG in submsg frame. */
  9547. upb_sink_startmsg(&p->top->sink);
  9548. parse_mapentry_key(p);
  9549. /* Set up the value field to receive the map-entry value. */
  9550. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_VALUE);
  9551. p->top->is_mapentry = true; /* set up to pop frame after value is parsed. */
  9552. p->top->mapfield = mapfield;
  9553. if (p->top->f == NULL) {
  9554. upb_status_seterrmsg(&p->status, "mapentry message has no value");
  9555. upb_env_reporterror(p->env, &p->status);
  9556. return false;
  9557. }
  9558. return true;
  9559. }
  9560. static bool end_membername(upb_json_parser *p) {
  9561. assert(!p->top->f);
  9562. if (p->top->is_map) {
  9563. return handle_mapentry(p);
  9564. } else {
  9565. size_t len;
  9566. const char *buf = accumulate_getptr(p, &len);
  9567. upb_value v;
  9568. if (upb_strtable_lookup2(p->top->name_table, buf, len, &v)) {
  9569. p->top->f = upb_value_getconstptr(v);
  9570. multipart_end(p);
  9571. return true;
  9572. } else {
  9573. /* TODO(haberman): Ignore unknown fields if requested/configured to do
  9574. * so. */
  9575. upb_status_seterrf(&p->status, "No such field: %.*s\n", (int)len, buf);
  9576. upb_env_reporterror(p->env, &p->status);
  9577. return false;
  9578. }
  9579. }
  9580. }
  9581. static void end_member(upb_json_parser *p) {
  9582. /* If we just parsed a map-entry value, end that frame too. */
  9583. if (p->top->is_mapentry) {
  9584. upb_status s = UPB_STATUS_INIT;
  9585. upb_selector_t sel;
  9586. bool ok;
  9587. const upb_fielddef *mapfield;
  9588. assert(p->top > p->stack);
  9589. /* send ENDMSG on submsg. */
  9590. upb_sink_endmsg(&p->top->sink, &s);
  9591. mapfield = p->top->mapfield;
  9592. /* send ENDSUBMSG in repeated-field-of-mapentries frame. */
  9593. p->top--;
  9594. ok = upb_handlers_getselector(mapfield, UPB_HANDLER_ENDSUBMSG, &sel);
  9595. UPB_ASSERT_VAR(ok, ok);
  9596. upb_sink_endsubmsg(&p->top->sink, sel);
  9597. }
  9598. p->top->f = NULL;
  9599. }
  9600. static bool start_subobject(upb_json_parser *p) {
  9601. assert(p->top->f);
  9602. if (upb_fielddef_ismap(p->top->f)) {
  9603. upb_jsonparser_frame *inner;
  9604. upb_selector_t sel;
  9605. /* Beginning of a map. Start a new parser frame in a repeated-field
  9606. * context. */
  9607. if (!check_stack(p)) return false;
  9608. inner = p->top + 1;
  9609. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  9610. upb_sink_startseq(&p->top->sink, sel, &inner->sink);
  9611. inner->m = upb_fielddef_msgsubdef(p->top->f);
  9612. inner->name_table = NULL;
  9613. inner->mapfield = p->top->f;
  9614. inner->f = NULL;
  9615. inner->is_map = true;
  9616. inner->is_mapentry = false;
  9617. p->top = inner;
  9618. return true;
  9619. } else if (upb_fielddef_issubmsg(p->top->f)) {
  9620. upb_jsonparser_frame *inner;
  9621. upb_selector_t sel;
  9622. /* Beginning of a subobject. Start a new parser frame in the submsg
  9623. * context. */
  9624. if (!check_stack(p)) return false;
  9625. inner = p->top + 1;
  9626. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  9627. upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
  9628. inner->m = upb_fielddef_msgsubdef(p->top->f);
  9629. set_name_table(p, inner);
  9630. inner->f = NULL;
  9631. inner->is_map = false;
  9632. inner->is_mapentry = false;
  9633. p->top = inner;
  9634. return true;
  9635. } else {
  9636. upb_status_seterrf(&p->status,
  9637. "Object specified for non-message/group field: %s",
  9638. upb_fielddef_name(p->top->f));
  9639. upb_env_reporterror(p->env, &p->status);
  9640. return false;
  9641. }
  9642. }
  9643. static void end_subobject(upb_json_parser *p) {
  9644. if (p->top->is_map) {
  9645. upb_selector_t sel;
  9646. p->top--;
  9647. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  9648. upb_sink_endseq(&p->top->sink, sel);
  9649. } else {
  9650. upb_selector_t sel;
  9651. p->top--;
  9652. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSUBMSG);
  9653. upb_sink_endsubmsg(&p->top->sink, sel);
  9654. }
  9655. }
  9656. static bool start_array(upb_json_parser *p) {
  9657. upb_jsonparser_frame *inner;
  9658. upb_selector_t sel;
  9659. assert(p->top->f);
  9660. if (!upb_fielddef_isseq(p->top->f)) {
  9661. upb_status_seterrf(&p->status,
  9662. "Array specified for non-repeated field: %s",
  9663. upb_fielddef_name(p->top->f));
  9664. upb_env_reporterror(p->env, &p->status);
  9665. return false;
  9666. }
  9667. if (!check_stack(p)) return false;
  9668. inner = p->top + 1;
  9669. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  9670. upb_sink_startseq(&p->top->sink, sel, &inner->sink);
  9671. inner->m = p->top->m;
  9672. inner->name_table = NULL;
  9673. inner->f = p->top->f;
  9674. inner->is_map = false;
  9675. inner->is_mapentry = false;
  9676. p->top = inner;
  9677. return true;
  9678. }
  9679. static void end_array(upb_json_parser *p) {
  9680. upb_selector_t sel;
  9681. assert(p->top > p->stack);
  9682. p->top--;
  9683. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  9684. upb_sink_endseq(&p->top->sink, sel);
  9685. }
  9686. static void start_object(upb_json_parser *p) {
  9687. if (!p->top->is_map) {
  9688. upb_sink_startmsg(&p->top->sink);
  9689. }
  9690. }
  9691. static void end_object(upb_json_parser *p) {
  9692. if (!p->top->is_map) {
  9693. upb_status status;
  9694. upb_status_clear(&status);
  9695. upb_sink_endmsg(&p->top->sink, &status);
  9696. if (!upb_ok(&status)) {
  9697. upb_env_reporterror(p->env, &status);
  9698. }
  9699. }
  9700. }
  9701. #define CHECK_RETURN_TOP(x) if (!(x)) goto error
  9702. /* The actual parser **********************************************************/
  9703. /* What follows is the Ragel parser itself. The language is specified in Ragel
  9704. * and the actions call our C functions above.
  9705. *
  9706. * Ragel has an extensive set of functionality, and we use only a small part of
  9707. * it. There are many action types but we only use a few:
  9708. *
  9709. * ">" -- transition into a machine
  9710. * "%" -- transition out of a machine
  9711. * "@" -- transition into a final state of a machine.
  9712. *
  9713. * "@" transitions are tricky because a machine can transition into a final
  9714. * state repeatedly. But in some cases we know this can't happen, for example
  9715. * a string which is delimited by a final '"' can only transition into its
  9716. * final state once, when the closing '"' is seen. */
  9717. #line 1246 "upb/json/parser.rl"
  9718. #line 1158 "upb/json/parser.c"
  9719. static const char _json_actions[] = {
  9720. 0, 1, 0, 1, 2, 1, 3, 1,
  9721. 5, 1, 6, 1, 7, 1, 8, 1,
  9722. 10, 1, 12, 1, 13, 1, 14, 1,
  9723. 15, 1, 16, 1, 17, 1, 21, 1,
  9724. 25, 1, 27, 2, 3, 8, 2, 4,
  9725. 5, 2, 6, 2, 2, 6, 8, 2,
  9726. 11, 9, 2, 13, 15, 2, 14, 15,
  9727. 2, 18, 1, 2, 19, 27, 2, 20,
  9728. 9, 2, 22, 27, 2, 23, 27, 2,
  9729. 24, 27, 2, 26, 27, 3, 14, 11,
  9730. 9
  9731. };
  9732. static const unsigned char _json_key_offsets[] = {
  9733. 0, 0, 4, 9, 14, 15, 19, 24,
  9734. 29, 34, 38, 42, 45, 48, 50, 54,
  9735. 58, 60, 62, 67, 69, 71, 80, 86,
  9736. 92, 98, 104, 106, 115, 116, 116, 116,
  9737. 121, 126, 131, 132, 133, 134, 135, 135,
  9738. 136, 137, 138, 138, 139, 140, 141, 141,
  9739. 146, 151, 152, 156, 161, 166, 171, 175,
  9740. 175, 178, 178, 178
  9741. };
  9742. static const char _json_trans_keys[] = {
  9743. 32, 123, 9, 13, 32, 34, 125, 9,
  9744. 13, 32, 34, 125, 9, 13, 34, 32,
  9745. 58, 9, 13, 32, 93, 125, 9, 13,
  9746. 32, 44, 125, 9, 13, 32, 44, 125,
  9747. 9, 13, 32, 34, 9, 13, 45, 48,
  9748. 49, 57, 48, 49, 57, 46, 69, 101,
  9749. 48, 57, 69, 101, 48, 57, 43, 45,
  9750. 48, 57, 48, 57, 48, 57, 46, 69,
  9751. 101, 48, 57, 34, 92, 34, 92, 34,
  9752. 47, 92, 98, 102, 110, 114, 116, 117,
  9753. 48, 57, 65, 70, 97, 102, 48, 57,
  9754. 65, 70, 97, 102, 48, 57, 65, 70,
  9755. 97, 102, 48, 57, 65, 70, 97, 102,
  9756. 34, 92, 34, 45, 91, 102, 110, 116,
  9757. 123, 48, 57, 34, 32, 93, 125, 9,
  9758. 13, 32, 44, 93, 9, 13, 32, 93,
  9759. 125, 9, 13, 97, 108, 115, 101, 117,
  9760. 108, 108, 114, 117, 101, 32, 34, 125,
  9761. 9, 13, 32, 34, 125, 9, 13, 34,
  9762. 32, 58, 9, 13, 32, 93, 125, 9,
  9763. 13, 32, 44, 125, 9, 13, 32, 44,
  9764. 125, 9, 13, 32, 34, 9, 13, 32,
  9765. 9, 13, 0
  9766. };
  9767. static const char _json_single_lengths[] = {
  9768. 0, 2, 3, 3, 1, 2, 3, 3,
  9769. 3, 2, 2, 1, 3, 0, 2, 2,
  9770. 0, 0, 3, 2, 2, 9, 0, 0,
  9771. 0, 0, 2, 7, 1, 0, 0, 3,
  9772. 3, 3, 1, 1, 1, 1, 0, 1,
  9773. 1, 1, 0, 1, 1, 1, 0, 3,
  9774. 3, 1, 2, 3, 3, 3, 2, 0,
  9775. 1, 0, 0, 0
  9776. };
  9777. static const char _json_range_lengths[] = {
  9778. 0, 1, 1, 1, 0, 1, 1, 1,
  9779. 1, 1, 1, 1, 0, 1, 1, 1,
  9780. 1, 1, 1, 0, 0, 0, 3, 3,
  9781. 3, 3, 0, 1, 0, 0, 0, 1,
  9782. 1, 1, 0, 0, 0, 0, 0, 0,
  9783. 0, 0, 0, 0, 0, 0, 0, 1,
  9784. 1, 0, 1, 1, 1, 1, 1, 0,
  9785. 1, 0, 0, 0
  9786. };
  9787. static const short _json_index_offsets[] = {
  9788. 0, 0, 4, 9, 14, 16, 20, 25,
  9789. 30, 35, 39, 43, 46, 50, 52, 56,
  9790. 60, 62, 64, 69, 72, 75, 85, 89,
  9791. 93, 97, 101, 104, 113, 115, 116, 117,
  9792. 122, 127, 132, 134, 136, 138, 140, 141,
  9793. 143, 145, 147, 148, 150, 152, 154, 155,
  9794. 160, 165, 167, 171, 176, 181, 186, 190,
  9795. 191, 194, 195, 196
  9796. };
  9797. static const char _json_indicies[] = {
  9798. 0, 2, 0, 1, 3, 4, 5, 3,
  9799. 1, 6, 7, 8, 6, 1, 9, 1,
  9800. 10, 11, 10, 1, 11, 1, 1, 11,
  9801. 12, 13, 14, 15, 13, 1, 16, 17,
  9802. 8, 16, 1, 17, 7, 17, 1, 18,
  9803. 19, 20, 1, 19, 20, 1, 22, 23,
  9804. 23, 21, 24, 1, 23, 23, 24, 21,
  9805. 25, 25, 26, 1, 26, 1, 26, 21,
  9806. 22, 23, 23, 20, 21, 28, 29, 27,
  9807. 31, 32, 30, 33, 33, 33, 33, 33,
  9808. 33, 33, 33, 34, 1, 35, 35, 35,
  9809. 1, 36, 36, 36, 1, 37, 37, 37,
  9810. 1, 38, 38, 38, 1, 40, 41, 39,
  9811. 42, 43, 44, 45, 46, 47, 48, 43,
  9812. 1, 49, 1, 50, 51, 53, 54, 1,
  9813. 53, 52, 55, 56, 54, 55, 1, 56,
  9814. 1, 1, 56, 52, 57, 1, 58, 1,
  9815. 59, 1, 60, 1, 61, 62, 1, 63,
  9816. 1, 64, 1, 65, 66, 1, 67, 1,
  9817. 68, 1, 69, 70, 71, 72, 70, 1,
  9818. 73, 74, 75, 73, 1, 76, 1, 77,
  9819. 78, 77, 1, 78, 1, 1, 78, 79,
  9820. 80, 81, 82, 80, 1, 83, 84, 75,
  9821. 83, 1, 84, 74, 84, 1, 85, 86,
  9822. 86, 1, 1, 1, 1, 0
  9823. };
  9824. static const char _json_trans_targs[] = {
  9825. 1, 0, 2, 3, 4, 56, 3, 4,
  9826. 56, 5, 5, 6, 7, 8, 9, 56,
  9827. 8, 9, 11, 12, 18, 57, 13, 15,
  9828. 14, 16, 17, 20, 58, 21, 20, 58,
  9829. 21, 19, 22, 23, 24, 25, 26, 20,
  9830. 58, 21, 28, 30, 31, 34, 39, 43,
  9831. 47, 29, 59, 59, 32, 31, 29, 32,
  9832. 33, 35, 36, 37, 38, 59, 40, 41,
  9833. 42, 59, 44, 45, 46, 59, 48, 49,
  9834. 55, 48, 49, 55, 50, 50, 51, 52,
  9835. 53, 54, 55, 53, 54, 59, 56
  9836. };
  9837. static const char _json_trans_actions[] = {
  9838. 0, 0, 0, 21, 77, 53, 0, 47,
  9839. 23, 17, 0, 0, 15, 19, 19, 50,
  9840. 0, 0, 0, 0, 0, 1, 0, 0,
  9841. 0, 0, 0, 3, 13, 0, 0, 35,
  9842. 5, 11, 0, 38, 7, 7, 7, 41,
  9843. 44, 9, 62, 56, 25, 0, 0, 0,
  9844. 31, 29, 33, 59, 15, 0, 27, 0,
  9845. 0, 0, 0, 0, 0, 68, 0, 0,
  9846. 0, 71, 0, 0, 0, 65, 21, 77,
  9847. 53, 0, 47, 23, 17, 0, 0, 15,
  9848. 19, 19, 50, 0, 0, 74, 0
  9849. };
  9850. static const int json_start = 1;
  9851. static const int json_en_number_machine = 10;
  9852. static const int json_en_string_machine = 19;
  9853. static const int json_en_value_machine = 27;
  9854. static const int json_en_main = 1;
  9855. #line 1249 "upb/json/parser.rl"
  9856. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  9857. const upb_bufhandle *handle) {
  9858. upb_json_parser *parser = closure;
  9859. /* Variables used by Ragel's generated code. */
  9860. int cs = parser->current_state;
  9861. int *stack = parser->parser_stack;
  9862. int top = parser->parser_top;
  9863. const char *p = buf;
  9864. const char *pe = buf + size;
  9865. parser->handle = handle;
  9866. UPB_UNUSED(hd);
  9867. UPB_UNUSED(handle);
  9868. capture_resume(parser, buf);
  9869. #line 1329 "upb/json/parser.c"
  9870. {
  9871. int _klen;
  9872. unsigned int _trans;
  9873. const char *_acts;
  9874. unsigned int _nacts;
  9875. const char *_keys;
  9876. if ( p == pe )
  9877. goto _test_eof;
  9878. if ( cs == 0 )
  9879. goto _out;
  9880. _resume:
  9881. _keys = _json_trans_keys + _json_key_offsets[cs];
  9882. _trans = _json_index_offsets[cs];
  9883. _klen = _json_single_lengths[cs];
  9884. if ( _klen > 0 ) {
  9885. const char *_lower = _keys;
  9886. const char *_mid;
  9887. const char *_upper = _keys + _klen - 1;
  9888. while (1) {
  9889. if ( _upper < _lower )
  9890. break;
  9891. _mid = _lower + ((_upper-_lower) >> 1);
  9892. if ( (*p) < *_mid )
  9893. _upper = _mid - 1;
  9894. else if ( (*p) > *_mid )
  9895. _lower = _mid + 1;
  9896. else {
  9897. _trans += (unsigned int)(_mid - _keys);
  9898. goto _match;
  9899. }
  9900. }
  9901. _keys += _klen;
  9902. _trans += _klen;
  9903. }
  9904. _klen = _json_range_lengths[cs];
  9905. if ( _klen > 0 ) {
  9906. const char *_lower = _keys;
  9907. const char *_mid;
  9908. const char *_upper = _keys + (_klen<<1) - 2;
  9909. while (1) {
  9910. if ( _upper < _lower )
  9911. break;
  9912. _mid = _lower + (((_upper-_lower) >> 1) & ~1);
  9913. if ( (*p) < _mid[0] )
  9914. _upper = _mid - 2;
  9915. else if ( (*p) > _mid[1] )
  9916. _lower = _mid + 2;
  9917. else {
  9918. _trans += (unsigned int)((_mid - _keys)>>1);
  9919. goto _match;
  9920. }
  9921. }
  9922. _trans += _klen;
  9923. }
  9924. _match:
  9925. _trans = _json_indicies[_trans];
  9926. cs = _json_trans_targs[_trans];
  9927. if ( _json_trans_actions[_trans] == 0 )
  9928. goto _again;
  9929. _acts = _json_actions + _json_trans_actions[_trans];
  9930. _nacts = (unsigned int) *_acts++;
  9931. while ( _nacts-- > 0 )
  9932. {
  9933. switch ( *_acts++ )
  9934. {
  9935. case 0:
  9936. #line 1161 "upb/json/parser.rl"
  9937. { p--; {cs = stack[--top]; goto _again;} }
  9938. break;
  9939. case 1:
  9940. #line 1162 "upb/json/parser.rl"
  9941. { p--; {stack[top++] = cs; cs = 10; goto _again;} }
  9942. break;
  9943. case 2:
  9944. #line 1166 "upb/json/parser.rl"
  9945. { start_text(parser, p); }
  9946. break;
  9947. case 3:
  9948. #line 1167 "upb/json/parser.rl"
  9949. { CHECK_RETURN_TOP(end_text(parser, p)); }
  9950. break;
  9951. case 4:
  9952. #line 1173 "upb/json/parser.rl"
  9953. { start_hex(parser); }
  9954. break;
  9955. case 5:
  9956. #line 1174 "upb/json/parser.rl"
  9957. { hexdigit(parser, p); }
  9958. break;
  9959. case 6:
  9960. #line 1175 "upb/json/parser.rl"
  9961. { CHECK_RETURN_TOP(end_hex(parser)); }
  9962. break;
  9963. case 7:
  9964. #line 1181 "upb/json/parser.rl"
  9965. { CHECK_RETURN_TOP(escape(parser, p)); }
  9966. break;
  9967. case 8:
  9968. #line 1187 "upb/json/parser.rl"
  9969. { p--; {cs = stack[--top]; goto _again;} }
  9970. break;
  9971. case 9:
  9972. #line 1190 "upb/json/parser.rl"
  9973. { {stack[top++] = cs; cs = 19; goto _again;} }
  9974. break;
  9975. case 10:
  9976. #line 1192 "upb/json/parser.rl"
  9977. { p--; {stack[top++] = cs; cs = 27; goto _again;} }
  9978. break;
  9979. case 11:
  9980. #line 1197 "upb/json/parser.rl"
  9981. { start_member(parser); }
  9982. break;
  9983. case 12:
  9984. #line 1198 "upb/json/parser.rl"
  9985. { CHECK_RETURN_TOP(end_membername(parser)); }
  9986. break;
  9987. case 13:
  9988. #line 1201 "upb/json/parser.rl"
  9989. { end_member(parser); }
  9990. break;
  9991. case 14:
  9992. #line 1207 "upb/json/parser.rl"
  9993. { start_object(parser); }
  9994. break;
  9995. case 15:
  9996. #line 1210 "upb/json/parser.rl"
  9997. { end_object(parser); }
  9998. break;
  9999. case 16:
  10000. #line 1216 "upb/json/parser.rl"
  10001. { CHECK_RETURN_TOP(start_array(parser)); }
  10002. break;
  10003. case 17:
  10004. #line 1220 "upb/json/parser.rl"
  10005. { end_array(parser); }
  10006. break;
  10007. case 18:
  10008. #line 1225 "upb/json/parser.rl"
  10009. { start_number(parser, p); }
  10010. break;
  10011. case 19:
  10012. #line 1226 "upb/json/parser.rl"
  10013. { CHECK_RETURN_TOP(end_number(parser, p)); }
  10014. break;
  10015. case 20:
  10016. #line 1228 "upb/json/parser.rl"
  10017. { CHECK_RETURN_TOP(start_stringval(parser)); }
  10018. break;
  10019. case 21:
  10020. #line 1229 "upb/json/parser.rl"
  10021. { CHECK_RETURN_TOP(end_stringval(parser)); }
  10022. break;
  10023. case 22:
  10024. #line 1231 "upb/json/parser.rl"
  10025. { CHECK_RETURN_TOP(parser_putbool(parser, true)); }
  10026. break;
  10027. case 23:
  10028. #line 1233 "upb/json/parser.rl"
  10029. { CHECK_RETURN_TOP(parser_putbool(parser, false)); }
  10030. break;
  10031. case 24:
  10032. #line 1235 "upb/json/parser.rl"
  10033. { /* null value */ }
  10034. break;
  10035. case 25:
  10036. #line 1237 "upb/json/parser.rl"
  10037. { CHECK_RETURN_TOP(start_subobject(parser)); }
  10038. break;
  10039. case 26:
  10040. #line 1238 "upb/json/parser.rl"
  10041. { end_subobject(parser); }
  10042. break;
  10043. case 27:
  10044. #line 1243 "upb/json/parser.rl"
  10045. { p--; {cs = stack[--top]; goto _again;} }
  10046. break;
  10047. #line 1515 "upb/json/parser.c"
  10048. }
  10049. }
  10050. _again:
  10051. if ( cs == 0 )
  10052. goto _out;
  10053. if ( ++p != pe )
  10054. goto _resume;
  10055. _test_eof: {}
  10056. _out: {}
  10057. }
  10058. #line 1270 "upb/json/parser.rl"
  10059. if (p != pe) {
  10060. upb_status_seterrf(&parser->status, "Parse error at '%.*s'\n", pe - p, p);
  10061. upb_env_reporterror(parser->env, &parser->status);
  10062. } else {
  10063. capture_suspend(parser, &p);
  10064. }
  10065. error:
  10066. /* Save parsing state back to parser. */
  10067. parser->current_state = cs;
  10068. parser->parser_top = top;
  10069. return p - buf;
  10070. }
  10071. bool end(void *closure, const void *hd) {
  10072. UPB_UNUSED(closure);
  10073. UPB_UNUSED(hd);
  10074. /* Prevent compile warning on unused static constants. */
  10075. UPB_UNUSED(json_start);
  10076. UPB_UNUSED(json_en_number_machine);
  10077. UPB_UNUSED(json_en_string_machine);
  10078. UPB_UNUSED(json_en_value_machine);
  10079. UPB_UNUSED(json_en_main);
  10080. return true;
  10081. }
  10082. static void json_parser_reset(upb_json_parser *p) {
  10083. int cs;
  10084. int top;
  10085. p->top = p->stack;
  10086. p->top->f = NULL;
  10087. p->top->is_map = false;
  10088. p->top->is_mapentry = false;
  10089. /* Emit Ragel initialization of the parser. */
  10090. #line 1569 "upb/json/parser.c"
  10091. {
  10092. cs = json_start;
  10093. top = 0;
  10094. }
  10095. #line 1310 "upb/json/parser.rl"
  10096. p->current_state = cs;
  10097. p->parser_top = top;
  10098. accumulate_clear(p);
  10099. p->multipart_state = MULTIPART_INACTIVE;
  10100. p->capture = NULL;
  10101. p->accumulated = NULL;
  10102. upb_status_clear(&p->status);
  10103. }
  10104. static void visit_json_parsermethod(const upb_refcounted *r,
  10105. upb_refcounted_visit *visit,
  10106. void *closure) {
  10107. const upb_json_parsermethod *method = (upb_json_parsermethod*)r;
  10108. visit(r, upb_msgdef_upcast2(method->msg), closure);
  10109. }
  10110. static void free_json_parsermethod(upb_refcounted *r) {
  10111. upb_json_parsermethod *method = (upb_json_parsermethod*)r;
  10112. upb_inttable_iter i;
  10113. upb_inttable_begin(&i, &method->name_tables);
  10114. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  10115. upb_value val = upb_inttable_iter_value(&i);
  10116. upb_strtable *t = upb_value_getptr(val);
  10117. upb_strtable_uninit(t);
  10118. free(t);
  10119. }
  10120. upb_inttable_uninit(&method->name_tables);
  10121. free(r);
  10122. }
  10123. static void add_jsonname_table(upb_json_parsermethod *m, const upb_msgdef* md) {
  10124. upb_msg_field_iter i;
  10125. upb_strtable *t;
  10126. /* It would be nice to stack-allocate this, but protobufs do not limit the
  10127. * length of fields to any reasonable limit. */
  10128. char *buf = NULL;
  10129. size_t len = 0;
  10130. if (upb_inttable_lookupptr(&m->name_tables, md, NULL)) {
  10131. return;
  10132. }
  10133. /* TODO(haberman): handle malloc failure. */
  10134. t = malloc(sizeof(*t));
  10135. upb_strtable_init(t, UPB_CTYPE_CONSTPTR);
  10136. upb_inttable_insertptr(&m->name_tables, md, upb_value_ptr(t));
  10137. for(upb_msg_field_begin(&i, md);
  10138. !upb_msg_field_done(&i);
  10139. upb_msg_field_next(&i)) {
  10140. const upb_fielddef *f = upb_msg_iter_field(&i);
  10141. /* Add an entry for the JSON name. */
  10142. size_t field_len = upb_fielddef_getjsonname(f, buf, len);
  10143. if (field_len > len) {
  10144. size_t len2;
  10145. buf = realloc(buf, field_len);
  10146. len = field_len;
  10147. len2 = upb_fielddef_getjsonname(f, buf, len);
  10148. UPB_ASSERT_VAR(len2, len == len2);
  10149. }
  10150. upb_strtable_insert(t, buf, upb_value_constptr(f));
  10151. if (strcmp(buf, upb_fielddef_name(f)) != 0) {
  10152. /* Since the JSON name is different from the regular field name, add an
  10153. * entry for the raw name (compliant proto3 JSON parsers must accept
  10154. * both). */
  10155. upb_strtable_insert(t, upb_fielddef_name(f), upb_value_constptr(f));
  10156. }
  10157. if (upb_fielddef_issubmsg(f)) {
  10158. add_jsonname_table(m, upb_fielddef_msgsubdef(f));
  10159. }
  10160. }
  10161. free(buf);
  10162. }
  10163. /* Public API *****************************************************************/
  10164. upb_json_parser *upb_json_parser_create(upb_env *env,
  10165. const upb_json_parsermethod *method,
  10166. upb_sink *output) {
  10167. #ifndef NDEBUG
  10168. const size_t size_before = upb_env_bytesallocated(env);
  10169. #endif
  10170. upb_json_parser *p = upb_env_malloc(env, sizeof(upb_json_parser));
  10171. if (!p) return false;
  10172. p->env = env;
  10173. p->method = method;
  10174. p->limit = p->stack + UPB_JSON_MAX_DEPTH;
  10175. p->accumulate_buf = NULL;
  10176. p->accumulate_buf_size = 0;
  10177. upb_bytessink_reset(&p->input_, &method->input_handler_, p);
  10178. json_parser_reset(p);
  10179. upb_sink_reset(&p->top->sink, output->handlers, output->closure);
  10180. p->top->m = upb_handlers_msgdef(output->handlers);
  10181. set_name_table(p, p->top);
  10182. /* If this fails, uncomment and increase the value in parser.h. */
  10183. /* fprintf(stderr, "%zd\n", upb_env_bytesallocated(env) - size_before); */
  10184. assert(upb_env_bytesallocated(env) - size_before <= UPB_JSON_PARSER_SIZE);
  10185. return p;
  10186. }
  10187. upb_bytessink *upb_json_parser_input(upb_json_parser *p) {
  10188. return &p->input_;
  10189. }
  10190. upb_json_parsermethod *upb_json_parsermethod_new(const upb_msgdef* md,
  10191. const void* owner) {
  10192. static const struct upb_refcounted_vtbl vtbl = {visit_json_parsermethod,
  10193. free_json_parsermethod};
  10194. upb_json_parsermethod *ret = malloc(sizeof(*ret));
  10195. upb_refcounted_init(upb_json_parsermethod_upcast_mutable(ret), &vtbl, owner);
  10196. ret->msg = md;
  10197. upb_ref2(md, ret);
  10198. upb_byteshandler_init(&ret->input_handler_);
  10199. upb_byteshandler_setstring(&ret->input_handler_, parse, ret);
  10200. upb_byteshandler_setendstr(&ret->input_handler_, end, ret);
  10201. upb_inttable_init(&ret->name_tables, UPB_CTYPE_PTR);
  10202. add_jsonname_table(ret, md);
  10203. return ret;
  10204. }
  10205. const upb_byteshandler *upb_json_parsermethod_inputhandler(
  10206. const upb_json_parsermethod *m) {
  10207. return &m->input_handler_;
  10208. }
  10209. /*
  10210. ** This currently uses snprintf() to format primitives, and could be optimized
  10211. ** further.
  10212. */
  10213. #include <stdlib.h>
  10214. #include <stdio.h>
  10215. #include <string.h>
  10216. #include <stdint.h>
  10217. struct upb_json_printer {
  10218. upb_sink input_;
  10219. /* BytesSink closure. */
  10220. void *subc_;
  10221. upb_bytessink *output_;
  10222. /* We track the depth so that we know when to emit startstr/endstr on the
  10223. * output. */
  10224. int depth_;
  10225. /* Have we emitted the first element? This state is necessary to emit commas
  10226. * without leaving a trailing comma in arrays/maps. We keep this state per
  10227. * frame depth.
  10228. *
  10229. * Why max_depth * 2? UPB_MAX_HANDLER_DEPTH counts depth as nested messages.
  10230. * We count frames (contexts in which we separate elements by commas) as both
  10231. * repeated fields and messages (maps), and the worst case is a
  10232. * message->repeated field->submessage->repeated field->... nesting. */
  10233. bool first_elem_[UPB_MAX_HANDLER_DEPTH * 2];
  10234. };
  10235. /* StringPiece; a pointer plus a length. */
  10236. typedef struct {
  10237. char *ptr;
  10238. size_t len;
  10239. } strpc;
  10240. void freestrpc(void *ptr) {
  10241. strpc *pc = ptr;
  10242. free(pc->ptr);
  10243. free(pc);
  10244. }
  10245. /* Convert fielddef name to JSON name and return as a string piece. */
  10246. strpc *newstrpc(upb_handlers *h, const upb_fielddef *f,
  10247. bool preserve_fieldnames) {
  10248. /* TODO(haberman): handle malloc failure. */
  10249. strpc *ret = malloc(sizeof(*ret));
  10250. if (preserve_fieldnames) {
  10251. ret->ptr = upb_strdup(upb_fielddef_name(f));
  10252. ret->len = strlen(ret->ptr);
  10253. } else {
  10254. size_t len;
  10255. ret->len = upb_fielddef_getjsonname(f, NULL, 0);
  10256. ret->ptr = malloc(ret->len);
  10257. len = upb_fielddef_getjsonname(f, ret->ptr, ret->len);
  10258. UPB_ASSERT_VAR(len, len == ret->len);
  10259. ret->len--; /* NULL */
  10260. }
  10261. upb_handlers_addcleanup(h, ret, freestrpc);
  10262. return ret;
  10263. }
  10264. /* ------------ JSON string printing: values, maps, arrays ------------------ */
  10265. static void print_data(
  10266. upb_json_printer *p, const char *buf, unsigned int len) {
  10267. /* TODO: Will need to change if we support pushback from the sink. */
  10268. size_t n = upb_bytessink_putbuf(p->output_, p->subc_, buf, len, NULL);
  10269. UPB_ASSERT_VAR(n, n == len);
  10270. }
  10271. static void print_comma(upb_json_printer *p) {
  10272. if (!p->first_elem_[p->depth_]) {
  10273. print_data(p, ",", 1);
  10274. }
  10275. p->first_elem_[p->depth_] = false;
  10276. }
  10277. /* Helpers that print properly formatted elements to the JSON output stream. */
  10278. /* Used for escaping control chars in strings. */
  10279. static const char kControlCharLimit = 0x20;
  10280. UPB_INLINE bool is_json_escaped(char c) {
  10281. /* See RFC 4627. */
  10282. unsigned char uc = (unsigned char)c;
  10283. return uc < kControlCharLimit || uc == '"' || uc == '\\';
  10284. }
  10285. UPB_INLINE const char* json_nice_escape(char c) {
  10286. switch (c) {
  10287. case '"': return "\\\"";
  10288. case '\\': return "\\\\";
  10289. case '\b': return "\\b";
  10290. case '\f': return "\\f";
  10291. case '\n': return "\\n";
  10292. case '\r': return "\\r";
  10293. case '\t': return "\\t";
  10294. default: return NULL;
  10295. }
  10296. }
  10297. /* Write a properly escaped string chunk. The surrounding quotes are *not*
  10298. * printed; this is so that the caller has the option of emitting the string
  10299. * content in chunks. */
  10300. static void putstring(upb_json_printer *p, const char *buf, unsigned int len) {
  10301. const char* unescaped_run = NULL;
  10302. unsigned int i;
  10303. for (i = 0; i < len; i++) {
  10304. char c = buf[i];
  10305. /* Handle escaping. */
  10306. if (is_json_escaped(c)) {
  10307. /* Use a "nice" escape, like \n, if one exists for this character. */
  10308. const char* escape = json_nice_escape(c);
  10309. /* If we don't have a specific 'nice' escape code, use a \uXXXX-style
  10310. * escape. */
  10311. char escape_buf[8];
  10312. if (!escape) {
  10313. unsigned char byte = (unsigned char)c;
  10314. _upb_snprintf(escape_buf, sizeof(escape_buf), "\\u%04x", (int)byte);
  10315. escape = escape_buf;
  10316. }
  10317. /* N.B. that we assume that the input encoding is equal to the output
  10318. * encoding (both UTF-8 for now), so for chars >= 0x20 and != \, ", we
  10319. * can simply pass the bytes through. */
  10320. /* If there's a current run of unescaped chars, print that run first. */
  10321. if (unescaped_run) {
  10322. print_data(p, unescaped_run, &buf[i] - unescaped_run);
  10323. unescaped_run = NULL;
  10324. }
  10325. /* Then print the escape code. */
  10326. print_data(p, escape, strlen(escape));
  10327. } else {
  10328. /* Add to the current unescaped run of characters. */
  10329. if (unescaped_run == NULL) {
  10330. unescaped_run = &buf[i];
  10331. }
  10332. }
  10333. }
  10334. /* If the string ended in a run of unescaped characters, print that last run. */
  10335. if (unescaped_run) {
  10336. print_data(p, unescaped_run, &buf[len] - unescaped_run);
  10337. }
  10338. }
  10339. #define CHKLENGTH(x) if (!(x)) return -1;
  10340. /* Helpers that format floating point values according to our custom formats.
  10341. * Right now we use %.8g and %.17g for float/double, respectively, to match
  10342. * proto2::util::JsonFormat's defaults. May want to change this later. */
  10343. static size_t fmt_double(double val, char* buf, size_t length) {
  10344. size_t n = _upb_snprintf(buf, length, "%.17g", val);
  10345. CHKLENGTH(n > 0 && n < length);
  10346. return n;
  10347. }
  10348. static size_t fmt_float(float val, char* buf, size_t length) {
  10349. size_t n = _upb_snprintf(buf, length, "%.8g", val);
  10350. CHKLENGTH(n > 0 && n < length);
  10351. return n;
  10352. }
  10353. static size_t fmt_bool(bool val, char* buf, size_t length) {
  10354. size_t n = _upb_snprintf(buf, length, "%s", (val ? "true" : "false"));
  10355. CHKLENGTH(n > 0 && n < length);
  10356. return n;
  10357. }
  10358. static size_t fmt_int64(long val, char* buf, size_t length) {
  10359. size_t n = _upb_snprintf(buf, length, "%ld", val);
  10360. CHKLENGTH(n > 0 && n < length);
  10361. return n;
  10362. }
  10363. static size_t fmt_uint64(unsigned long long val, char* buf, size_t length) {
  10364. size_t n = _upb_snprintf(buf, length, "%llu", val);
  10365. CHKLENGTH(n > 0 && n < length);
  10366. return n;
  10367. }
  10368. /* Print a map key given a field name. Called by scalar field handlers and by
  10369. * startseq for repeated fields. */
  10370. static bool putkey(void *closure, const void *handler_data) {
  10371. upb_json_printer *p = closure;
  10372. const strpc *key = handler_data;
  10373. print_comma(p);
  10374. print_data(p, "\"", 1);
  10375. putstring(p, key->ptr, key->len);
  10376. print_data(p, "\":", 2);
  10377. return true;
  10378. }
  10379. #define CHKFMT(val) if ((val) == (size_t)-1) return false;
  10380. #define CHK(val) if (!(val)) return false;
  10381. #define TYPE_HANDLERS(type, fmt_func) \
  10382. static bool put##type(void *closure, const void *handler_data, type val) { \
  10383. upb_json_printer *p = closure; \
  10384. char data[64]; \
  10385. size_t length = fmt_func(val, data, sizeof(data)); \
  10386. UPB_UNUSED(handler_data); \
  10387. CHKFMT(length); \
  10388. print_data(p, data, length); \
  10389. return true; \
  10390. } \
  10391. static bool scalar_##type(void *closure, const void *handler_data, \
  10392. type val) { \
  10393. CHK(putkey(closure, handler_data)); \
  10394. CHK(put##type(closure, handler_data, val)); \
  10395. return true; \
  10396. } \
  10397. static bool repeated_##type(void *closure, const void *handler_data, \
  10398. type val) { \
  10399. upb_json_printer *p = closure; \
  10400. print_comma(p); \
  10401. CHK(put##type(closure, handler_data, val)); \
  10402. return true; \
  10403. }
  10404. #define TYPE_HANDLERS_MAPKEY(type, fmt_func) \
  10405. static bool putmapkey_##type(void *closure, const void *handler_data, \
  10406. type val) { \
  10407. upb_json_printer *p = closure; \
  10408. print_data(p, "\"", 1); \
  10409. CHK(put##type(closure, handler_data, val)); \
  10410. print_data(p, "\":", 2); \
  10411. return true; \
  10412. }
  10413. TYPE_HANDLERS(double, fmt_double)
  10414. TYPE_HANDLERS(float, fmt_float)
  10415. TYPE_HANDLERS(bool, fmt_bool)
  10416. TYPE_HANDLERS(int32_t, fmt_int64)
  10417. TYPE_HANDLERS(uint32_t, fmt_int64)
  10418. TYPE_HANDLERS(int64_t, fmt_int64)
  10419. TYPE_HANDLERS(uint64_t, fmt_uint64)
  10420. /* double and float are not allowed to be map keys. */
  10421. TYPE_HANDLERS_MAPKEY(bool, fmt_bool)
  10422. TYPE_HANDLERS_MAPKEY(int32_t, fmt_int64)
  10423. TYPE_HANDLERS_MAPKEY(uint32_t, fmt_int64)
  10424. TYPE_HANDLERS_MAPKEY(int64_t, fmt_int64)
  10425. TYPE_HANDLERS_MAPKEY(uint64_t, fmt_uint64)
  10426. #undef TYPE_HANDLERS
  10427. #undef TYPE_HANDLERS_MAPKEY
  10428. typedef struct {
  10429. void *keyname;
  10430. const upb_enumdef *enumdef;
  10431. } EnumHandlerData;
  10432. static bool scalar_enum(void *closure, const void *handler_data,
  10433. int32_t val) {
  10434. const EnumHandlerData *hd = handler_data;
  10435. upb_json_printer *p = closure;
  10436. const char *symbolic_name;
  10437. CHK(putkey(closure, hd->keyname));
  10438. symbolic_name = upb_enumdef_iton(hd->enumdef, val);
  10439. if (symbolic_name) {
  10440. print_data(p, "\"", 1);
  10441. putstring(p, symbolic_name, strlen(symbolic_name));
  10442. print_data(p, "\"", 1);
  10443. } else {
  10444. putint32_t(closure, NULL, val);
  10445. }
  10446. return true;
  10447. }
  10448. static void print_enum_symbolic_name(upb_json_printer *p,
  10449. const upb_enumdef *def,
  10450. int32_t val) {
  10451. const char *symbolic_name = upb_enumdef_iton(def, val);
  10452. if (symbolic_name) {
  10453. print_data(p, "\"", 1);
  10454. putstring(p, symbolic_name, strlen(symbolic_name));
  10455. print_data(p, "\"", 1);
  10456. } else {
  10457. putint32_t(p, NULL, val);
  10458. }
  10459. }
  10460. static bool repeated_enum(void *closure, const void *handler_data,
  10461. int32_t val) {
  10462. const EnumHandlerData *hd = handler_data;
  10463. upb_json_printer *p = closure;
  10464. print_comma(p);
  10465. print_enum_symbolic_name(p, hd->enumdef, val);
  10466. return true;
  10467. }
  10468. static bool mapvalue_enum(void *closure, const void *handler_data,
  10469. int32_t val) {
  10470. const EnumHandlerData *hd = handler_data;
  10471. upb_json_printer *p = closure;
  10472. print_enum_symbolic_name(p, hd->enumdef, val);
  10473. return true;
  10474. }
  10475. static void *scalar_startsubmsg(void *closure, const void *handler_data) {
  10476. return putkey(closure, handler_data) ? closure : UPB_BREAK;
  10477. }
  10478. static void *repeated_startsubmsg(void *closure, const void *handler_data) {
  10479. upb_json_printer *p = closure;
  10480. UPB_UNUSED(handler_data);
  10481. print_comma(p);
  10482. return closure;
  10483. }
  10484. static void start_frame(upb_json_printer *p) {
  10485. p->depth_++;
  10486. p->first_elem_[p->depth_] = true;
  10487. print_data(p, "{", 1);
  10488. }
  10489. static void end_frame(upb_json_printer *p) {
  10490. print_data(p, "}", 1);
  10491. p->depth_--;
  10492. }
  10493. static bool printer_startmsg(void *closure, const void *handler_data) {
  10494. upb_json_printer *p = closure;
  10495. UPB_UNUSED(handler_data);
  10496. if (p->depth_ == 0) {
  10497. upb_bytessink_start(p->output_, 0, &p->subc_);
  10498. }
  10499. start_frame(p);
  10500. return true;
  10501. }
  10502. static bool printer_endmsg(void *closure, const void *handler_data, upb_status *s) {
  10503. upb_json_printer *p = closure;
  10504. UPB_UNUSED(handler_data);
  10505. UPB_UNUSED(s);
  10506. end_frame(p);
  10507. if (p->depth_ == 0) {
  10508. upb_bytessink_end(p->output_);
  10509. }
  10510. return true;
  10511. }
  10512. static void *startseq(void *closure, const void *handler_data) {
  10513. upb_json_printer *p = closure;
  10514. CHK(putkey(closure, handler_data));
  10515. p->depth_++;
  10516. p->first_elem_[p->depth_] = true;
  10517. print_data(p, "[", 1);
  10518. return closure;
  10519. }
  10520. static bool endseq(void *closure, const void *handler_data) {
  10521. upb_json_printer *p = closure;
  10522. UPB_UNUSED(handler_data);
  10523. print_data(p, "]", 1);
  10524. p->depth_--;
  10525. return true;
  10526. }
  10527. static void *startmap(void *closure, const void *handler_data) {
  10528. upb_json_printer *p = closure;
  10529. CHK(putkey(closure, handler_data));
  10530. p->depth_++;
  10531. p->first_elem_[p->depth_] = true;
  10532. print_data(p, "{", 1);
  10533. return closure;
  10534. }
  10535. static bool endmap(void *closure, const void *handler_data) {
  10536. upb_json_printer *p = closure;
  10537. UPB_UNUSED(handler_data);
  10538. print_data(p, "}", 1);
  10539. p->depth_--;
  10540. return true;
  10541. }
  10542. static size_t putstr(void *closure, const void *handler_data, const char *str,
  10543. size_t len, const upb_bufhandle *handle) {
  10544. upb_json_printer *p = closure;
  10545. UPB_UNUSED(handler_data);
  10546. UPB_UNUSED(handle);
  10547. putstring(p, str, len);
  10548. return len;
  10549. }
  10550. /* This has to Base64 encode the bytes, because JSON has no "bytes" type. */
  10551. static size_t putbytes(void *closure, const void *handler_data, const char *str,
  10552. size_t len, const upb_bufhandle *handle) {
  10553. upb_json_printer *p = closure;
  10554. /* This is the regular base64, not the "web-safe" version. */
  10555. static const char base64[] =
  10556. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  10557. /* Base64-encode. */
  10558. char data[16000];
  10559. const char *limit = data + sizeof(data);
  10560. const unsigned char *from = (const unsigned char*)str;
  10561. char *to = data;
  10562. size_t remaining = len;
  10563. size_t bytes;
  10564. UPB_UNUSED(handler_data);
  10565. UPB_UNUSED(handle);
  10566. while (remaining > 2) {
  10567. /* TODO(haberman): handle encoded lengths > sizeof(data) */
  10568. UPB_ASSERT_VAR(limit, (limit - to) >= 4);
  10569. to[0] = base64[from[0] >> 2];
  10570. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  10571. to[2] = base64[((from[1] & 0xf) << 2) | (from[2] >> 6)];
  10572. to[3] = base64[from[2] & 0x3f];
  10573. remaining -= 3;
  10574. to += 4;
  10575. from += 3;
  10576. }
  10577. switch (remaining) {
  10578. case 2:
  10579. to[0] = base64[from[0] >> 2];
  10580. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  10581. to[2] = base64[(from[1] & 0xf) << 2];
  10582. to[3] = '=';
  10583. to += 4;
  10584. from += 2;
  10585. break;
  10586. case 1:
  10587. to[0] = base64[from[0] >> 2];
  10588. to[1] = base64[((from[0] & 0x3) << 4)];
  10589. to[2] = '=';
  10590. to[3] = '=';
  10591. to += 4;
  10592. from += 1;
  10593. break;
  10594. }
  10595. bytes = to - data;
  10596. print_data(p, "\"", 1);
  10597. putstring(p, data, bytes);
  10598. print_data(p, "\"", 1);
  10599. return len;
  10600. }
  10601. static void *scalar_startstr(void *closure, const void *handler_data,
  10602. size_t size_hint) {
  10603. upb_json_printer *p = closure;
  10604. UPB_UNUSED(handler_data);
  10605. UPB_UNUSED(size_hint);
  10606. CHK(putkey(closure, handler_data));
  10607. print_data(p, "\"", 1);
  10608. return p;
  10609. }
  10610. static size_t scalar_str(void *closure, const void *handler_data,
  10611. const char *str, size_t len,
  10612. const upb_bufhandle *handle) {
  10613. CHK(putstr(closure, handler_data, str, len, handle));
  10614. return len;
  10615. }
  10616. static bool scalar_endstr(void *closure, const void *handler_data) {
  10617. upb_json_printer *p = closure;
  10618. UPB_UNUSED(handler_data);
  10619. print_data(p, "\"", 1);
  10620. return true;
  10621. }
  10622. static void *repeated_startstr(void *closure, const void *handler_data,
  10623. size_t size_hint) {
  10624. upb_json_printer *p = closure;
  10625. UPB_UNUSED(handler_data);
  10626. UPB_UNUSED(size_hint);
  10627. print_comma(p);
  10628. print_data(p, "\"", 1);
  10629. return p;
  10630. }
  10631. static size_t repeated_str(void *closure, const void *handler_data,
  10632. const char *str, size_t len,
  10633. const upb_bufhandle *handle) {
  10634. CHK(putstr(closure, handler_data, str, len, handle));
  10635. return len;
  10636. }
  10637. static bool repeated_endstr(void *closure, const void *handler_data) {
  10638. upb_json_printer *p = closure;
  10639. UPB_UNUSED(handler_data);
  10640. print_data(p, "\"", 1);
  10641. return true;
  10642. }
  10643. static void *mapkeyval_startstr(void *closure, const void *handler_data,
  10644. size_t size_hint) {
  10645. upb_json_printer *p = closure;
  10646. UPB_UNUSED(handler_data);
  10647. UPB_UNUSED(size_hint);
  10648. print_data(p, "\"", 1);
  10649. return p;
  10650. }
  10651. static size_t mapkey_str(void *closure, const void *handler_data,
  10652. const char *str, size_t len,
  10653. const upb_bufhandle *handle) {
  10654. CHK(putstr(closure, handler_data, str, len, handle));
  10655. return len;
  10656. }
  10657. static bool mapkey_endstr(void *closure, const void *handler_data) {
  10658. upb_json_printer *p = closure;
  10659. UPB_UNUSED(handler_data);
  10660. print_data(p, "\":", 2);
  10661. return true;
  10662. }
  10663. static bool mapvalue_endstr(void *closure, const void *handler_data) {
  10664. upb_json_printer *p = closure;
  10665. UPB_UNUSED(handler_data);
  10666. print_data(p, "\"", 1);
  10667. return true;
  10668. }
  10669. static size_t scalar_bytes(void *closure, const void *handler_data,
  10670. const char *str, size_t len,
  10671. const upb_bufhandle *handle) {
  10672. CHK(putkey(closure, handler_data));
  10673. CHK(putbytes(closure, handler_data, str, len, handle));
  10674. return len;
  10675. }
  10676. static size_t repeated_bytes(void *closure, const void *handler_data,
  10677. const char *str, size_t len,
  10678. const upb_bufhandle *handle) {
  10679. upb_json_printer *p = closure;
  10680. print_comma(p);
  10681. CHK(putbytes(closure, handler_data, str, len, handle));
  10682. return len;
  10683. }
  10684. static size_t mapkey_bytes(void *closure, const void *handler_data,
  10685. const char *str, size_t len,
  10686. const upb_bufhandle *handle) {
  10687. upb_json_printer *p = closure;
  10688. CHK(putbytes(closure, handler_data, str, len, handle));
  10689. print_data(p, ":", 1);
  10690. return len;
  10691. }
  10692. static void set_enum_hd(upb_handlers *h,
  10693. const upb_fielddef *f,
  10694. bool preserve_fieldnames,
  10695. upb_handlerattr *attr) {
  10696. EnumHandlerData *hd = malloc(sizeof(EnumHandlerData));
  10697. hd->enumdef = (const upb_enumdef *)upb_fielddef_subdef(f);
  10698. hd->keyname = newstrpc(h, f, preserve_fieldnames);
  10699. upb_handlers_addcleanup(h, hd, free);
  10700. upb_handlerattr_sethandlerdata(attr, hd);
  10701. }
  10702. /* Set up handlers for a mapentry submessage (i.e., an individual key/value pair
  10703. * in a map).
  10704. *
  10705. * TODO: Handle missing key, missing value, out-of-order key/value, or repeated
  10706. * key or value cases properly. The right way to do this is to allocate a
  10707. * temporary structure at the start of a mapentry submessage, store key and
  10708. * value data in it as key and value handlers are called, and then print the
  10709. * key/value pair once at the end of the submessage. If we don't do this, we
  10710. * should at least detect the case and throw an error. However, so far all of
  10711. * our sources that emit mapentry messages do so canonically (with one key
  10712. * field, and then one value field), so this is not a pressing concern at the
  10713. * moment. */
  10714. void printer_sethandlers_mapentry(const void *closure, bool preserve_fieldnames,
  10715. upb_handlers *h) {
  10716. const upb_msgdef *md = upb_handlers_msgdef(h);
  10717. /* A mapentry message is printed simply as '"key": value'. Rather than
  10718. * special-case key and value for every type below, we just handle both
  10719. * fields explicitly here. */
  10720. const upb_fielddef* key_field = upb_msgdef_itof(md, UPB_MAPENTRY_KEY);
  10721. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_MAPENTRY_VALUE);
  10722. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  10723. UPB_UNUSED(closure);
  10724. switch (upb_fielddef_type(key_field)) {
  10725. case UPB_TYPE_INT32:
  10726. upb_handlers_setint32(h, key_field, putmapkey_int32_t, &empty_attr);
  10727. break;
  10728. case UPB_TYPE_INT64:
  10729. upb_handlers_setint64(h, key_field, putmapkey_int64_t, &empty_attr);
  10730. break;
  10731. case UPB_TYPE_UINT32:
  10732. upb_handlers_setuint32(h, key_field, putmapkey_uint32_t, &empty_attr);
  10733. break;
  10734. case UPB_TYPE_UINT64:
  10735. upb_handlers_setuint64(h, key_field, putmapkey_uint64_t, &empty_attr);
  10736. break;
  10737. case UPB_TYPE_BOOL:
  10738. upb_handlers_setbool(h, key_field, putmapkey_bool, &empty_attr);
  10739. break;
  10740. case UPB_TYPE_STRING:
  10741. upb_handlers_setstartstr(h, key_field, mapkeyval_startstr, &empty_attr);
  10742. upb_handlers_setstring(h, key_field, mapkey_str, &empty_attr);
  10743. upb_handlers_setendstr(h, key_field, mapkey_endstr, &empty_attr);
  10744. break;
  10745. case UPB_TYPE_BYTES:
  10746. upb_handlers_setstring(h, key_field, mapkey_bytes, &empty_attr);
  10747. break;
  10748. default:
  10749. assert(false);
  10750. break;
  10751. }
  10752. switch (upb_fielddef_type(value_field)) {
  10753. case UPB_TYPE_INT32:
  10754. upb_handlers_setint32(h, value_field, putint32_t, &empty_attr);
  10755. break;
  10756. case UPB_TYPE_INT64:
  10757. upb_handlers_setint64(h, value_field, putint64_t, &empty_attr);
  10758. break;
  10759. case UPB_TYPE_UINT32:
  10760. upb_handlers_setuint32(h, value_field, putuint32_t, &empty_attr);
  10761. break;
  10762. case UPB_TYPE_UINT64:
  10763. upb_handlers_setuint64(h, value_field, putuint64_t, &empty_attr);
  10764. break;
  10765. case UPB_TYPE_BOOL:
  10766. upb_handlers_setbool(h, value_field, putbool, &empty_attr);
  10767. break;
  10768. case UPB_TYPE_FLOAT:
  10769. upb_handlers_setfloat(h, value_field, putfloat, &empty_attr);
  10770. break;
  10771. case UPB_TYPE_DOUBLE:
  10772. upb_handlers_setdouble(h, value_field, putdouble, &empty_attr);
  10773. break;
  10774. case UPB_TYPE_STRING:
  10775. upb_handlers_setstartstr(h, value_field, mapkeyval_startstr, &empty_attr);
  10776. upb_handlers_setstring(h, value_field, putstr, &empty_attr);
  10777. upb_handlers_setendstr(h, value_field, mapvalue_endstr, &empty_attr);
  10778. break;
  10779. case UPB_TYPE_BYTES:
  10780. upb_handlers_setstring(h, value_field, putbytes, &empty_attr);
  10781. break;
  10782. case UPB_TYPE_ENUM: {
  10783. upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
  10784. set_enum_hd(h, value_field, preserve_fieldnames, &enum_attr);
  10785. upb_handlers_setint32(h, value_field, mapvalue_enum, &enum_attr);
  10786. upb_handlerattr_uninit(&enum_attr);
  10787. break;
  10788. }
  10789. case UPB_TYPE_MESSAGE:
  10790. /* No handler necessary -- the submsg handlers will print the message
  10791. * as appropriate. */
  10792. break;
  10793. }
  10794. upb_handlerattr_uninit(&empty_attr);
  10795. }
  10796. void printer_sethandlers(const void *closure, upb_handlers *h) {
  10797. const upb_msgdef *md = upb_handlers_msgdef(h);
  10798. bool is_mapentry = upb_msgdef_mapentry(md);
  10799. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  10800. upb_msg_field_iter i;
  10801. const bool *preserve_fieldnames_ptr = closure;
  10802. const bool preserve_fieldnames = *preserve_fieldnames_ptr;
  10803. if (is_mapentry) {
  10804. /* mapentry messages are sufficiently different that we handle them
  10805. * separately. */
  10806. printer_sethandlers_mapentry(closure, preserve_fieldnames, h);
  10807. return;
  10808. }
  10809. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  10810. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  10811. #define TYPE(type, name, ctype) \
  10812. case type: \
  10813. if (upb_fielddef_isseq(f)) { \
  10814. upb_handlers_set##name(h, f, repeated_##ctype, &empty_attr); \
  10815. } else { \
  10816. upb_handlers_set##name(h, f, scalar_##ctype, &name_attr); \
  10817. } \
  10818. break;
  10819. upb_msg_field_begin(&i, md);
  10820. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  10821. const upb_fielddef *f = upb_msg_iter_field(&i);
  10822. upb_handlerattr name_attr = UPB_HANDLERATTR_INITIALIZER;
  10823. upb_handlerattr_sethandlerdata(&name_attr,
  10824. newstrpc(h, f, preserve_fieldnames));
  10825. if (upb_fielddef_ismap(f)) {
  10826. upb_handlers_setstartseq(h, f, startmap, &name_attr);
  10827. upb_handlers_setendseq(h, f, endmap, &name_attr);
  10828. } else if (upb_fielddef_isseq(f)) {
  10829. upb_handlers_setstartseq(h, f, startseq, &name_attr);
  10830. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  10831. }
  10832. switch (upb_fielddef_type(f)) {
  10833. TYPE(UPB_TYPE_FLOAT, float, float);
  10834. TYPE(UPB_TYPE_DOUBLE, double, double);
  10835. TYPE(UPB_TYPE_BOOL, bool, bool);
  10836. TYPE(UPB_TYPE_INT32, int32, int32_t);
  10837. TYPE(UPB_TYPE_UINT32, uint32, uint32_t);
  10838. TYPE(UPB_TYPE_INT64, int64, int64_t);
  10839. TYPE(UPB_TYPE_UINT64, uint64, uint64_t);
  10840. case UPB_TYPE_ENUM: {
  10841. /* For now, we always emit symbolic names for enums. We may want an
  10842. * option later to control this behavior, but we will wait for a real
  10843. * need first. */
  10844. upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
  10845. set_enum_hd(h, f, preserve_fieldnames, &enum_attr);
  10846. if (upb_fielddef_isseq(f)) {
  10847. upb_handlers_setint32(h, f, repeated_enum, &enum_attr);
  10848. } else {
  10849. upb_handlers_setint32(h, f, scalar_enum, &enum_attr);
  10850. }
  10851. upb_handlerattr_uninit(&enum_attr);
  10852. break;
  10853. }
  10854. case UPB_TYPE_STRING:
  10855. if (upb_fielddef_isseq(f)) {
  10856. upb_handlers_setstartstr(h, f, repeated_startstr, &empty_attr);
  10857. upb_handlers_setstring(h, f, repeated_str, &empty_attr);
  10858. upb_handlers_setendstr(h, f, repeated_endstr, &empty_attr);
  10859. } else {
  10860. upb_handlers_setstartstr(h, f, scalar_startstr, &name_attr);
  10861. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  10862. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  10863. }
  10864. break;
  10865. case UPB_TYPE_BYTES:
  10866. /* XXX: this doesn't support strings that span buffers yet. The base64
  10867. * encoder will need to be made resumable for this to work properly. */
  10868. if (upb_fielddef_isseq(f)) {
  10869. upb_handlers_setstring(h, f, repeated_bytes, &empty_attr);
  10870. } else {
  10871. upb_handlers_setstring(h, f, scalar_bytes, &name_attr);
  10872. }
  10873. break;
  10874. case UPB_TYPE_MESSAGE:
  10875. if (upb_fielddef_isseq(f)) {
  10876. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &name_attr);
  10877. } else {
  10878. upb_handlers_setstartsubmsg(h, f, scalar_startsubmsg, &name_attr);
  10879. }
  10880. break;
  10881. }
  10882. upb_handlerattr_uninit(&name_attr);
  10883. }
  10884. upb_handlerattr_uninit(&empty_attr);
  10885. #undef TYPE
  10886. }
  10887. static void json_printer_reset(upb_json_printer *p) {
  10888. p->depth_ = 0;
  10889. }
  10890. /* Public API *****************************************************************/
  10891. upb_json_printer *upb_json_printer_create(upb_env *e, const upb_handlers *h,
  10892. upb_bytessink *output) {
  10893. #ifndef NDEBUG
  10894. size_t size_before = upb_env_bytesallocated(e);
  10895. #endif
  10896. upb_json_printer *p = upb_env_malloc(e, sizeof(upb_json_printer));
  10897. if (!p) return NULL;
  10898. p->output_ = output;
  10899. json_printer_reset(p);
  10900. upb_sink_reset(&p->input_, h, p);
  10901. /* If this fails, increase the value in printer.h. */
  10902. assert(upb_env_bytesallocated(e) - size_before <= UPB_JSON_PRINTER_SIZE);
  10903. return p;
  10904. }
  10905. upb_sink *upb_json_printer_input(upb_json_printer *p) {
  10906. return &p->input_;
  10907. }
  10908. const upb_handlers *upb_json_printer_newhandlers(const upb_msgdef *md,
  10909. bool preserve_fieldnames,
  10910. const void *owner) {
  10911. return upb_handlers_newfrozen(
  10912. md, owner, printer_sethandlers, &preserve_fieldnames);
  10913. }