upb.c 395 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964
  1. // Amalgamated source file
  2. #include "upb.h"
  3. #include <stdlib.h>
  4. #include <string.h>
  5. typedef struct {
  6. size_t len;
  7. char str[1]; /* Null-terminated string data follows. */
  8. } str_t;
  9. static str_t *newstr(const char *data, size_t len) {
  10. str_t *ret = malloc(sizeof(*ret) + len);
  11. if (!ret) return NULL;
  12. ret->len = len;
  13. memcpy(ret->str, data, len);
  14. ret->str[len] = '\0';
  15. return ret;
  16. }
  17. static void freestr(str_t *s) { free(s); }
  18. /* isalpha() etc. from <ctype.h> are locale-dependent, which we don't want. */
  19. static bool upb_isbetween(char c, char low, char high) {
  20. return c >= low && c <= high;
  21. }
  22. static bool upb_isletter(char c) {
  23. return upb_isbetween(c, 'A', 'Z') || upb_isbetween(c, 'a', 'z') || c == '_';
  24. }
  25. static bool upb_isalphanum(char c) {
  26. return upb_isletter(c) || upb_isbetween(c, '0', '9');
  27. }
  28. static bool upb_isident(const char *str, size_t len, bool full, upb_status *s) {
  29. bool start = true;
  30. size_t i;
  31. for (i = 0; i < len; i++) {
  32. char c = str[i];
  33. if (c == '.') {
  34. if (start || !full) {
  35. upb_status_seterrf(s, "invalid name: unexpected '.' (%s)", str);
  36. return false;
  37. }
  38. start = true;
  39. } else if (start) {
  40. if (!upb_isletter(c)) {
  41. upb_status_seterrf(
  42. s, "invalid name: path components must start with a letter (%s)",
  43. str);
  44. return false;
  45. }
  46. start = false;
  47. } else {
  48. if (!upb_isalphanum(c)) {
  49. upb_status_seterrf(s, "invalid name: non-alphanumeric character (%s)",
  50. str);
  51. return false;
  52. }
  53. }
  54. }
  55. return !start;
  56. }
  57. /* upb_def ********************************************************************/
  58. upb_deftype_t upb_def_type(const upb_def *d) { return d->type; }
  59. const char *upb_def_fullname(const upb_def *d) { return d->fullname; }
  60. bool upb_def_setfullname(upb_def *def, const char *fullname, upb_status *s) {
  61. assert(!upb_def_isfrozen(def));
  62. if (!upb_isident(fullname, strlen(fullname), true, s)) return false;
  63. free((void*)def->fullname);
  64. def->fullname = upb_strdup(fullname);
  65. return true;
  66. }
  67. upb_def *upb_def_dup(const upb_def *def, const void *o) {
  68. switch (def->type) {
  69. case UPB_DEF_MSG:
  70. return upb_msgdef_upcast_mutable(
  71. upb_msgdef_dup(upb_downcast_msgdef(def), o));
  72. case UPB_DEF_FIELD:
  73. return upb_fielddef_upcast_mutable(
  74. upb_fielddef_dup(upb_downcast_fielddef(def), o));
  75. case UPB_DEF_ENUM:
  76. return upb_enumdef_upcast_mutable(
  77. upb_enumdef_dup(upb_downcast_enumdef(def), o));
  78. default: assert(false); return NULL;
  79. }
  80. }
  81. static bool upb_def_init(upb_def *def, upb_deftype_t type,
  82. const struct upb_refcounted_vtbl *vtbl,
  83. const void *owner) {
  84. if (!upb_refcounted_init(upb_def_upcast_mutable(def), vtbl, owner)) return false;
  85. def->type = type;
  86. def->fullname = NULL;
  87. def->came_from_user = false;
  88. return true;
  89. }
  90. static void upb_def_uninit(upb_def *def) {
  91. free((void*)def->fullname);
  92. }
  93. static const char *msgdef_name(const upb_msgdef *m) {
  94. const char *name = upb_def_fullname(upb_msgdef_upcast(m));
  95. return name ? name : "(anonymous)";
  96. }
  97. static bool upb_validate_field(upb_fielddef *f, upb_status *s) {
  98. if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  99. upb_status_seterrmsg(s, "fielddef must have name and number set");
  100. return false;
  101. }
  102. if (!f->type_is_set_) {
  103. upb_status_seterrmsg(s, "fielddef type was not initialized");
  104. return false;
  105. }
  106. if (upb_fielddef_lazy(f) &&
  107. upb_fielddef_descriptortype(f) != UPB_DESCRIPTOR_TYPE_MESSAGE) {
  108. upb_status_seterrmsg(s,
  109. "only length-delimited submessage fields may be lazy");
  110. return false;
  111. }
  112. if (upb_fielddef_hassubdef(f)) {
  113. const upb_def *subdef;
  114. if (f->subdef_is_symbolic) {
  115. upb_status_seterrf(s, "field '%s.%s' has not been resolved",
  116. msgdef_name(f->msg.def), upb_fielddef_name(f));
  117. return false;
  118. }
  119. subdef = upb_fielddef_subdef(f);
  120. if (subdef == NULL) {
  121. upb_status_seterrf(s, "field %s.%s is missing required subdef",
  122. msgdef_name(f->msg.def), upb_fielddef_name(f));
  123. return false;
  124. }
  125. if (!upb_def_isfrozen(subdef) && !subdef->came_from_user) {
  126. upb_status_seterrf(s,
  127. "subdef of field %s.%s is not frozen or being frozen",
  128. msgdef_name(f->msg.def), upb_fielddef_name(f));
  129. return false;
  130. }
  131. }
  132. if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  133. bool has_default_name = upb_fielddef_enumhasdefaultstr(f);
  134. bool has_default_number = upb_fielddef_enumhasdefaultint32(f);
  135. /* Previously verified by upb_validate_enumdef(). */
  136. assert(upb_enumdef_numvals(upb_fielddef_enumsubdef(f)) > 0);
  137. /* We've already validated that we have an associated enumdef and that it
  138. * has at least one member, so at least one of these should be true.
  139. * Because if the user didn't set anything, we'll pick up the enum's
  140. * default, but if the user *did* set something we should at least pick up
  141. * the one they set (int32 or string). */
  142. assert(has_default_name || has_default_number);
  143. if (!has_default_name) {
  144. upb_status_seterrf(s,
  145. "enum default for field %s.%s (%d) is not in the enum",
  146. msgdef_name(f->msg.def), upb_fielddef_name(f),
  147. upb_fielddef_defaultint32(f));
  148. return false;
  149. }
  150. if (!has_default_number) {
  151. upb_status_seterrf(s,
  152. "enum default for field %s.%s (%s) is not in the enum",
  153. msgdef_name(f->msg.def), upb_fielddef_name(f),
  154. upb_fielddef_defaultstr(f, NULL));
  155. return false;
  156. }
  157. /* Lift the effective numeric default into the field's default slot, in case
  158. * we were only getting it "by reference" from the enumdef. */
  159. upb_fielddef_setdefaultint32(f, upb_fielddef_defaultint32(f));
  160. }
  161. /* Ensure that MapEntry submessages only appear as repeated fields, not
  162. * optional/required (singular) fields. */
  163. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  164. upb_fielddef_msgsubdef(f) != NULL) {
  165. const upb_msgdef *subdef = upb_fielddef_msgsubdef(f);
  166. if (upb_msgdef_mapentry(subdef) && !upb_fielddef_isseq(f)) {
  167. upb_status_seterrf(s,
  168. "Field %s refers to mapentry message but is not "
  169. "a repeated field",
  170. upb_fielddef_name(f) ? upb_fielddef_name(f) :
  171. "(unnamed)");
  172. return false;
  173. }
  174. }
  175. return true;
  176. }
  177. static bool upb_validate_enumdef(const upb_enumdef *e, upb_status *s) {
  178. if (upb_enumdef_numvals(e) == 0) {
  179. upb_status_seterrf(s, "enum %s has no members (must have at least one)",
  180. upb_enumdef_fullname(e));
  181. return false;
  182. }
  183. return true;
  184. }
  185. /* All submessage fields are lower than all other fields.
  186. * Secondly, fields are increasing in order. */
  187. uint32_t field_rank(const upb_fielddef *f) {
  188. uint32_t ret = upb_fielddef_number(f);
  189. const uint32_t high_bit = 1 << 30;
  190. assert(ret < high_bit);
  191. if (!upb_fielddef_issubmsg(f))
  192. ret |= high_bit;
  193. return ret;
  194. }
  195. int cmp_fields(const void *p1, const void *p2) {
  196. const upb_fielddef *f1 = *(upb_fielddef*const*)p1;
  197. const upb_fielddef *f2 = *(upb_fielddef*const*)p2;
  198. return field_rank(f1) - field_rank(f2);
  199. }
  200. static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
  201. /* Sort fields. upb internally relies on UPB_TYPE_MESSAGE fields having the
  202. * lowest indexes, but we do not publicly guarantee this. */
  203. upb_msg_field_iter j;
  204. int i;
  205. uint32_t selector;
  206. int n = upb_msgdef_numfields(m);
  207. upb_fielddef **fields = malloc(n * sizeof(*fields));
  208. if (!fields) return false;
  209. m->submsg_field_count = 0;
  210. for(i = 0, upb_msg_field_begin(&j, m);
  211. !upb_msg_field_done(&j);
  212. upb_msg_field_next(&j), i++) {
  213. upb_fielddef *f = upb_msg_iter_field(&j);
  214. assert(f->msg.def == m);
  215. if (!upb_validate_field(f, s)) {
  216. free(fields);
  217. return false;
  218. }
  219. if (upb_fielddef_issubmsg(f)) {
  220. m->submsg_field_count++;
  221. }
  222. fields[i] = f;
  223. }
  224. qsort(fields, n, sizeof(*fields), cmp_fields);
  225. selector = UPB_STATIC_SELECTOR_COUNT + m->submsg_field_count;
  226. for (i = 0; i < n; i++) {
  227. upb_fielddef *f = fields[i];
  228. f->index_ = i;
  229. f->selector_base = selector + upb_handlers_selectorbaseoffset(f);
  230. selector += upb_handlers_selectorcount(f);
  231. }
  232. m->selector_count = selector;
  233. #ifndef NDEBUG
  234. {
  235. /* Verify that all selectors for the message are distinct. */
  236. #define TRY(type) \
  237. if (upb_handlers_getselector(f, type, &sel)) upb_inttable_insert(&t, sel, v);
  238. upb_inttable t;
  239. upb_value v;
  240. upb_selector_t sel;
  241. upb_inttable_init(&t, UPB_CTYPE_BOOL);
  242. v = upb_value_bool(true);
  243. upb_inttable_insert(&t, UPB_STARTMSG_SELECTOR, v);
  244. upb_inttable_insert(&t, UPB_ENDMSG_SELECTOR, v);
  245. for(upb_msg_field_begin(&j, m);
  246. !upb_msg_field_done(&j);
  247. upb_msg_field_next(&j)) {
  248. upb_fielddef *f = upb_msg_iter_field(&j);
  249. /* These calls will assert-fail in upb_table if the value already
  250. * exists. */
  251. TRY(UPB_HANDLER_INT32);
  252. TRY(UPB_HANDLER_INT64)
  253. TRY(UPB_HANDLER_UINT32)
  254. TRY(UPB_HANDLER_UINT64)
  255. TRY(UPB_HANDLER_FLOAT)
  256. TRY(UPB_HANDLER_DOUBLE)
  257. TRY(UPB_HANDLER_BOOL)
  258. TRY(UPB_HANDLER_STARTSTR)
  259. TRY(UPB_HANDLER_STRING)
  260. TRY(UPB_HANDLER_ENDSTR)
  261. TRY(UPB_HANDLER_STARTSUBMSG)
  262. TRY(UPB_HANDLER_ENDSUBMSG)
  263. TRY(UPB_HANDLER_STARTSEQ)
  264. TRY(UPB_HANDLER_ENDSEQ)
  265. }
  266. upb_inttable_uninit(&t);
  267. }
  268. #undef TRY
  269. #endif
  270. free(fields);
  271. return true;
  272. }
  273. bool upb_def_freeze(upb_def *const* defs, int n, upb_status *s) {
  274. int i;
  275. int maxdepth;
  276. bool ret;
  277. upb_status_clear(s);
  278. /* First perform validation, in two passes so we can check that we have a
  279. * transitive closure without needing to search. */
  280. for (i = 0; i < n; i++) {
  281. upb_def *def = defs[i];
  282. if (upb_def_isfrozen(def)) {
  283. /* Could relax this requirement if it's annoying. */
  284. upb_status_seterrmsg(s, "def is already frozen");
  285. goto err;
  286. } else if (def->type == UPB_DEF_FIELD) {
  287. upb_status_seterrmsg(s, "standalone fielddefs can not be frozen");
  288. goto err;
  289. } else if (def->type == UPB_DEF_ENUM) {
  290. if (!upb_validate_enumdef(upb_dyncast_enumdef(def), s)) {
  291. goto err;
  292. }
  293. } else {
  294. /* Set now to detect transitive closure in the second pass. */
  295. def->came_from_user = true;
  296. }
  297. }
  298. /* Second pass of validation. Also assign selector bases and indexes, and
  299. * compact tables. */
  300. for (i = 0; i < n; i++) {
  301. upb_msgdef *m = upb_dyncast_msgdef_mutable(defs[i]);
  302. upb_enumdef *e = upb_dyncast_enumdef_mutable(defs[i]);
  303. if (m) {
  304. upb_inttable_compact(&m->itof);
  305. if (!assign_msg_indices(m, s)) {
  306. goto err;
  307. }
  308. } else if (e) {
  309. upb_inttable_compact(&e->iton);
  310. }
  311. }
  312. /* Def graph contains FieldDefs between each MessageDef, so double the
  313. * limit. */
  314. maxdepth = UPB_MAX_MESSAGE_DEPTH * 2;
  315. /* Validation all passed; freeze the defs. */
  316. ret = upb_refcounted_freeze((upb_refcounted * const *)defs, n, s, maxdepth);
  317. assert(!(s && ret != upb_ok(s)));
  318. return ret;
  319. err:
  320. for (i = 0; i < n; i++) {
  321. defs[i]->came_from_user = false;
  322. }
  323. assert(!(s && upb_ok(s)));
  324. return false;
  325. }
  326. /* upb_enumdef ****************************************************************/
  327. static void upb_enumdef_free(upb_refcounted *r) {
  328. upb_enumdef *e = (upb_enumdef*)r;
  329. upb_inttable_iter i;
  330. upb_inttable_begin(&i, &e->iton);
  331. for( ; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  332. /* To clean up the upb_strdup() from upb_enumdef_addval(). */
  333. free(upb_value_getcstr(upb_inttable_iter_value(&i)));
  334. }
  335. upb_strtable_uninit(&e->ntoi);
  336. upb_inttable_uninit(&e->iton);
  337. upb_def_uninit(upb_enumdef_upcast_mutable(e));
  338. free(e);
  339. }
  340. upb_enumdef *upb_enumdef_new(const void *owner) {
  341. static const struct upb_refcounted_vtbl vtbl = {NULL, &upb_enumdef_free};
  342. upb_enumdef *e = malloc(sizeof(*e));
  343. if (!e) return NULL;
  344. if (!upb_def_init(upb_enumdef_upcast_mutable(e), UPB_DEF_ENUM, &vtbl, owner))
  345. goto err2;
  346. if (!upb_strtable_init(&e->ntoi, UPB_CTYPE_INT32)) goto err2;
  347. if (!upb_inttable_init(&e->iton, UPB_CTYPE_CSTR)) goto err1;
  348. return e;
  349. err1:
  350. upb_strtable_uninit(&e->ntoi);
  351. err2:
  352. free(e);
  353. return NULL;
  354. }
  355. upb_enumdef *upb_enumdef_dup(const upb_enumdef *e, const void *owner) {
  356. upb_enum_iter i;
  357. upb_enumdef *new_e = upb_enumdef_new(owner);
  358. if (!new_e) return NULL;
  359. for(upb_enum_begin(&i, e); !upb_enum_done(&i); upb_enum_next(&i)) {
  360. bool success = upb_enumdef_addval(
  361. new_e, upb_enum_iter_name(&i),upb_enum_iter_number(&i), NULL);
  362. if (!success) {
  363. upb_enumdef_unref(new_e, owner);
  364. return NULL;
  365. }
  366. }
  367. return new_e;
  368. }
  369. bool upb_enumdef_freeze(upb_enumdef *e, upb_status *status) {
  370. upb_def *d = upb_enumdef_upcast_mutable(e);
  371. return upb_def_freeze(&d, 1, status);
  372. }
  373. const char *upb_enumdef_fullname(const upb_enumdef *e) {
  374. return upb_def_fullname(upb_enumdef_upcast(e));
  375. }
  376. bool upb_enumdef_setfullname(upb_enumdef *e, const char *fullname,
  377. upb_status *s) {
  378. return upb_def_setfullname(upb_enumdef_upcast_mutable(e), fullname, s);
  379. }
  380. bool upb_enumdef_addval(upb_enumdef *e, const char *name, int32_t num,
  381. upb_status *status) {
  382. if (!upb_isident(name, strlen(name), false, status)) {
  383. return false;
  384. }
  385. if (upb_enumdef_ntoiz(e, name, NULL)) {
  386. upb_status_seterrf(status, "name '%s' is already defined", name);
  387. return false;
  388. }
  389. if (!upb_strtable_insert(&e->ntoi, name, upb_value_int32(num))) {
  390. upb_status_seterrmsg(status, "out of memory");
  391. return false;
  392. }
  393. if (!upb_inttable_lookup(&e->iton, num, NULL) &&
  394. !upb_inttable_insert(&e->iton, num, upb_value_cstr(upb_strdup(name)))) {
  395. upb_status_seterrmsg(status, "out of memory");
  396. upb_strtable_remove(&e->ntoi, name, NULL);
  397. return false;
  398. }
  399. if (upb_enumdef_numvals(e) == 1) {
  400. bool ok = upb_enumdef_setdefault(e, num, NULL);
  401. UPB_ASSERT_VAR(ok, ok);
  402. }
  403. return true;
  404. }
  405. int32_t upb_enumdef_default(const upb_enumdef *e) {
  406. assert(upb_enumdef_iton(e, e->defaultval));
  407. return e->defaultval;
  408. }
  409. bool upb_enumdef_setdefault(upb_enumdef *e, int32_t val, upb_status *s) {
  410. assert(!upb_enumdef_isfrozen(e));
  411. if (!upb_enumdef_iton(e, val)) {
  412. upb_status_seterrf(s, "number '%d' is not in the enum.", val);
  413. return false;
  414. }
  415. e->defaultval = val;
  416. return true;
  417. }
  418. int upb_enumdef_numvals(const upb_enumdef *e) {
  419. return upb_strtable_count(&e->ntoi);
  420. }
  421. void upb_enum_begin(upb_enum_iter *i, const upb_enumdef *e) {
  422. /* We iterate over the ntoi table, to account for duplicate numbers. */
  423. upb_strtable_begin(i, &e->ntoi);
  424. }
  425. void upb_enum_next(upb_enum_iter *iter) { upb_strtable_next(iter); }
  426. bool upb_enum_done(upb_enum_iter *iter) { return upb_strtable_done(iter); }
  427. bool upb_enumdef_ntoi(const upb_enumdef *def, const char *name,
  428. size_t len, int32_t *num) {
  429. upb_value v;
  430. if (!upb_strtable_lookup2(&def->ntoi, name, len, &v)) {
  431. return false;
  432. }
  433. if (num) *num = upb_value_getint32(v);
  434. return true;
  435. }
  436. const char *upb_enumdef_iton(const upb_enumdef *def, int32_t num) {
  437. upb_value v;
  438. return upb_inttable_lookup32(&def->iton, num, &v) ?
  439. upb_value_getcstr(v) : NULL;
  440. }
  441. const char *upb_enum_iter_name(upb_enum_iter *iter) {
  442. return upb_strtable_iter_key(iter);
  443. }
  444. int32_t upb_enum_iter_number(upb_enum_iter *iter) {
  445. return upb_value_getint32(upb_strtable_iter_value(iter));
  446. }
  447. /* upb_fielddef ***************************************************************/
  448. static void upb_fielddef_init_default(upb_fielddef *f);
  449. static void upb_fielddef_uninit_default(upb_fielddef *f) {
  450. if (f->type_is_set_ && f->default_is_string && f->defaultval.bytes)
  451. freestr(f->defaultval.bytes);
  452. }
  453. static void visitfield(const upb_refcounted *r, upb_refcounted_visit *visit,
  454. void *closure) {
  455. const upb_fielddef *f = (const upb_fielddef*)r;
  456. if (upb_fielddef_containingtype(f)) {
  457. visit(r, upb_msgdef_upcast2(upb_fielddef_containingtype(f)), closure);
  458. }
  459. if (upb_fielddef_containingoneof(f)) {
  460. visit(r, upb_oneofdef_upcast2(upb_fielddef_containingoneof(f)), closure);
  461. }
  462. if (upb_fielddef_subdef(f)) {
  463. visit(r, upb_def_upcast(upb_fielddef_subdef(f)), closure);
  464. }
  465. }
  466. static void freefield(upb_refcounted *r) {
  467. upb_fielddef *f = (upb_fielddef*)r;
  468. upb_fielddef_uninit_default(f);
  469. if (f->subdef_is_symbolic)
  470. free(f->sub.name);
  471. upb_def_uninit(upb_fielddef_upcast_mutable(f));
  472. free(f);
  473. }
  474. static const char *enumdefaultstr(const upb_fielddef *f) {
  475. const upb_enumdef *e;
  476. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  477. e = upb_fielddef_enumsubdef(f);
  478. if (f->default_is_string && f->defaultval.bytes) {
  479. /* Default was explicitly set as a string. */
  480. str_t *s = f->defaultval.bytes;
  481. return s->str;
  482. } else if (e) {
  483. if (!f->default_is_string) {
  484. /* Default was explicitly set as an integer; look it up in enumdef. */
  485. const char *name = upb_enumdef_iton(e, f->defaultval.sint);
  486. if (name) {
  487. return name;
  488. }
  489. } else {
  490. /* Default is completely unset; pull enumdef default. */
  491. if (upb_enumdef_numvals(e) > 0) {
  492. const char *name = upb_enumdef_iton(e, upb_enumdef_default(e));
  493. assert(name);
  494. return name;
  495. }
  496. }
  497. }
  498. return NULL;
  499. }
  500. static bool enumdefaultint32(const upb_fielddef *f, int32_t *val) {
  501. const upb_enumdef *e;
  502. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  503. e = upb_fielddef_enumsubdef(f);
  504. if (!f->default_is_string) {
  505. /* Default was explicitly set as an integer. */
  506. *val = f->defaultval.sint;
  507. return true;
  508. } else if (e) {
  509. if (f->defaultval.bytes) {
  510. /* Default was explicitly set as a str; try to lookup corresponding int. */
  511. str_t *s = f->defaultval.bytes;
  512. if (upb_enumdef_ntoiz(e, s->str, val)) {
  513. return true;
  514. }
  515. } else {
  516. /* Default is unset; try to pull in enumdef default. */
  517. if (upb_enumdef_numvals(e) > 0) {
  518. *val = upb_enumdef_default(e);
  519. return true;
  520. }
  521. }
  522. }
  523. return false;
  524. }
  525. upb_fielddef *upb_fielddef_new(const void *o) {
  526. static const struct upb_refcounted_vtbl vtbl = {visitfield, freefield};
  527. upb_fielddef *f = malloc(sizeof(*f));
  528. if (!f) return NULL;
  529. if (!upb_def_init(upb_fielddef_upcast_mutable(f), UPB_DEF_FIELD, &vtbl, o)) {
  530. free(f);
  531. return NULL;
  532. }
  533. f->msg.def = NULL;
  534. f->sub.def = NULL;
  535. f->oneof = NULL;
  536. f->subdef_is_symbolic = false;
  537. f->msg_is_symbolic = false;
  538. f->label_ = UPB_LABEL_OPTIONAL;
  539. f->type_ = UPB_TYPE_INT32;
  540. f->number_ = 0;
  541. f->type_is_set_ = false;
  542. f->tagdelim = false;
  543. f->is_extension_ = false;
  544. f->lazy_ = false;
  545. f->packed_ = true;
  546. /* For the moment we default this to UPB_INTFMT_VARIABLE, since it will work
  547. * with all integer types and is in some since more "default" since the most
  548. * normal-looking proto2 types int32/int64/uint32/uint64 use variable.
  549. *
  550. * Other options to consider:
  551. * - there is no default; users must set this manually (like type).
  552. * - default signed integers to UPB_INTFMT_ZIGZAG, since it's more likely to
  553. * be an optimal default for signed integers. */
  554. f->intfmt = UPB_INTFMT_VARIABLE;
  555. return f;
  556. }
  557. upb_fielddef *upb_fielddef_dup(const upb_fielddef *f, const void *owner) {
  558. const char *srcname;
  559. upb_fielddef *newf = upb_fielddef_new(owner);
  560. if (!newf) return NULL;
  561. upb_fielddef_settype(newf, upb_fielddef_type(f));
  562. upb_fielddef_setlabel(newf, upb_fielddef_label(f));
  563. upb_fielddef_setnumber(newf, upb_fielddef_number(f), NULL);
  564. upb_fielddef_setname(newf, upb_fielddef_name(f), NULL);
  565. if (f->default_is_string && f->defaultval.bytes) {
  566. str_t *s = f->defaultval.bytes;
  567. upb_fielddef_setdefaultstr(newf, s->str, s->len, NULL);
  568. } else {
  569. newf->default_is_string = f->default_is_string;
  570. newf->defaultval = f->defaultval;
  571. }
  572. if (f->subdef_is_symbolic) {
  573. srcname = f->sub.name; /* Might be NULL. */
  574. } else {
  575. srcname = f->sub.def ? upb_def_fullname(f->sub.def) : NULL;
  576. }
  577. if (srcname) {
  578. char *newname = malloc(strlen(f->sub.def->fullname) + 2);
  579. if (!newname) {
  580. upb_fielddef_unref(newf, owner);
  581. return NULL;
  582. }
  583. strcpy(newname, ".");
  584. strcat(newname, f->sub.def->fullname);
  585. upb_fielddef_setsubdefname(newf, newname, NULL);
  586. free(newname);
  587. }
  588. return newf;
  589. }
  590. bool upb_fielddef_typeisset(const upb_fielddef *f) {
  591. return f->type_is_set_;
  592. }
  593. upb_fieldtype_t upb_fielddef_type(const upb_fielddef *f) {
  594. assert(f->type_is_set_);
  595. return f->type_;
  596. }
  597. uint32_t upb_fielddef_index(const upb_fielddef *f) {
  598. return f->index_;
  599. }
  600. upb_label_t upb_fielddef_label(const upb_fielddef *f) {
  601. return f->label_;
  602. }
  603. upb_intfmt_t upb_fielddef_intfmt(const upb_fielddef *f) {
  604. return f->intfmt;
  605. }
  606. bool upb_fielddef_istagdelim(const upb_fielddef *f) {
  607. return f->tagdelim;
  608. }
  609. uint32_t upb_fielddef_number(const upb_fielddef *f) {
  610. return f->number_;
  611. }
  612. bool upb_fielddef_isextension(const upb_fielddef *f) {
  613. return f->is_extension_;
  614. }
  615. bool upb_fielddef_lazy(const upb_fielddef *f) {
  616. return f->lazy_;
  617. }
  618. bool upb_fielddef_packed(const upb_fielddef *f) {
  619. return f->packed_;
  620. }
  621. const char *upb_fielddef_name(const upb_fielddef *f) {
  622. return upb_def_fullname(upb_fielddef_upcast(f));
  623. }
  624. const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f) {
  625. return f->msg_is_symbolic ? NULL : f->msg.def;
  626. }
  627. const upb_oneofdef *upb_fielddef_containingoneof(const upb_fielddef *f) {
  628. return f->oneof;
  629. }
  630. upb_msgdef *upb_fielddef_containingtype_mutable(upb_fielddef *f) {
  631. return (upb_msgdef*)upb_fielddef_containingtype(f);
  632. }
  633. const char *upb_fielddef_containingtypename(upb_fielddef *f) {
  634. return f->msg_is_symbolic ? f->msg.name : NULL;
  635. }
  636. static void release_containingtype(upb_fielddef *f) {
  637. if (f->msg_is_symbolic) free(f->msg.name);
  638. }
  639. bool upb_fielddef_setcontainingtypename(upb_fielddef *f, const char *name,
  640. upb_status *s) {
  641. assert(!upb_fielddef_isfrozen(f));
  642. if (upb_fielddef_containingtype(f)) {
  643. upb_status_seterrmsg(s, "field has already been added to a message.");
  644. return false;
  645. }
  646. /* TODO: validate name (upb_isident() doesn't quite work atm because this name
  647. * may have a leading "."). */
  648. release_containingtype(f);
  649. f->msg.name = upb_strdup(name);
  650. f->msg_is_symbolic = true;
  651. return true;
  652. }
  653. bool upb_fielddef_setname(upb_fielddef *f, const char *name, upb_status *s) {
  654. if (upb_fielddef_containingtype(f) || upb_fielddef_containingoneof(f)) {
  655. upb_status_seterrmsg(s, "Already added to message or oneof");
  656. return false;
  657. }
  658. return upb_def_setfullname(upb_fielddef_upcast_mutable(f), name, s);
  659. }
  660. static void chkdefaulttype(const upb_fielddef *f, upb_fieldtype_t type) {
  661. UPB_UNUSED(f);
  662. UPB_UNUSED(type);
  663. assert(f->type_is_set_ && upb_fielddef_type(f) == type);
  664. }
  665. int64_t upb_fielddef_defaultint64(const upb_fielddef *f) {
  666. chkdefaulttype(f, UPB_TYPE_INT64);
  667. return f->defaultval.sint;
  668. }
  669. int32_t upb_fielddef_defaultint32(const upb_fielddef *f) {
  670. if (f->type_is_set_ && upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  671. int32_t val;
  672. bool ok = enumdefaultint32(f, &val);
  673. UPB_ASSERT_VAR(ok, ok);
  674. return val;
  675. } else {
  676. chkdefaulttype(f, UPB_TYPE_INT32);
  677. return f->defaultval.sint;
  678. }
  679. }
  680. uint64_t upb_fielddef_defaultuint64(const upb_fielddef *f) {
  681. chkdefaulttype(f, UPB_TYPE_UINT64);
  682. return f->defaultval.uint;
  683. }
  684. uint32_t upb_fielddef_defaultuint32(const upb_fielddef *f) {
  685. chkdefaulttype(f, UPB_TYPE_UINT32);
  686. return f->defaultval.uint;
  687. }
  688. bool upb_fielddef_defaultbool(const upb_fielddef *f) {
  689. chkdefaulttype(f, UPB_TYPE_BOOL);
  690. return f->defaultval.uint;
  691. }
  692. float upb_fielddef_defaultfloat(const upb_fielddef *f) {
  693. chkdefaulttype(f, UPB_TYPE_FLOAT);
  694. return f->defaultval.flt;
  695. }
  696. double upb_fielddef_defaultdouble(const upb_fielddef *f) {
  697. chkdefaulttype(f, UPB_TYPE_DOUBLE);
  698. return f->defaultval.dbl;
  699. }
  700. const char *upb_fielddef_defaultstr(const upb_fielddef *f, size_t *len) {
  701. assert(f->type_is_set_);
  702. assert(upb_fielddef_type(f) == UPB_TYPE_STRING ||
  703. upb_fielddef_type(f) == UPB_TYPE_BYTES ||
  704. upb_fielddef_type(f) == UPB_TYPE_ENUM);
  705. if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  706. const char *ret = enumdefaultstr(f);
  707. assert(ret);
  708. /* Enum defaults can't have embedded NULLs. */
  709. if (len) *len = strlen(ret);
  710. return ret;
  711. }
  712. if (f->default_is_string) {
  713. str_t *str = f->defaultval.bytes;
  714. if (len) *len = str->len;
  715. return str->str;
  716. }
  717. return NULL;
  718. }
  719. static void upb_fielddef_init_default(upb_fielddef *f) {
  720. f->default_is_string = false;
  721. switch (upb_fielddef_type(f)) {
  722. case UPB_TYPE_DOUBLE: f->defaultval.dbl = 0; break;
  723. case UPB_TYPE_FLOAT: f->defaultval.flt = 0; break;
  724. case UPB_TYPE_INT32:
  725. case UPB_TYPE_INT64: f->defaultval.sint = 0; break;
  726. case UPB_TYPE_UINT64:
  727. case UPB_TYPE_UINT32:
  728. case UPB_TYPE_BOOL: f->defaultval.uint = 0; break;
  729. case UPB_TYPE_STRING:
  730. case UPB_TYPE_BYTES:
  731. f->defaultval.bytes = newstr("", 0);
  732. f->default_is_string = true;
  733. break;
  734. case UPB_TYPE_MESSAGE: break;
  735. case UPB_TYPE_ENUM:
  736. /* This is our special sentinel that indicates "not set" for an enum. */
  737. f->default_is_string = true;
  738. f->defaultval.bytes = NULL;
  739. break;
  740. }
  741. }
  742. const upb_def *upb_fielddef_subdef(const upb_fielddef *f) {
  743. return f->subdef_is_symbolic ? NULL : f->sub.def;
  744. }
  745. const upb_msgdef *upb_fielddef_msgsubdef(const upb_fielddef *f) {
  746. const upb_def *def = upb_fielddef_subdef(f);
  747. return def ? upb_dyncast_msgdef(def) : NULL;
  748. }
  749. const upb_enumdef *upb_fielddef_enumsubdef(const upb_fielddef *f) {
  750. const upb_def *def = upb_fielddef_subdef(f);
  751. return def ? upb_dyncast_enumdef(def) : NULL;
  752. }
  753. upb_def *upb_fielddef_subdef_mutable(upb_fielddef *f) {
  754. return (upb_def*)upb_fielddef_subdef(f);
  755. }
  756. const char *upb_fielddef_subdefname(const upb_fielddef *f) {
  757. if (f->subdef_is_symbolic) {
  758. return f->sub.name;
  759. } else if (f->sub.def) {
  760. return upb_def_fullname(f->sub.def);
  761. } else {
  762. return NULL;
  763. }
  764. }
  765. bool upb_fielddef_setnumber(upb_fielddef *f, uint32_t number, upb_status *s) {
  766. if (upb_fielddef_containingtype(f)) {
  767. upb_status_seterrmsg(
  768. s, "cannot change field number after adding to a message");
  769. return false;
  770. }
  771. if (number == 0 || number > UPB_MAX_FIELDNUMBER) {
  772. upb_status_seterrf(s, "invalid field number (%u)", number);
  773. return false;
  774. }
  775. f->number_ = number;
  776. return true;
  777. }
  778. void upb_fielddef_settype(upb_fielddef *f, upb_fieldtype_t type) {
  779. assert(!upb_fielddef_isfrozen(f));
  780. assert(upb_fielddef_checktype(type));
  781. upb_fielddef_uninit_default(f);
  782. f->type_ = type;
  783. f->type_is_set_ = true;
  784. upb_fielddef_init_default(f);
  785. }
  786. void upb_fielddef_setdescriptortype(upb_fielddef *f, int type) {
  787. assert(!upb_fielddef_isfrozen(f));
  788. switch (type) {
  789. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  790. upb_fielddef_settype(f, UPB_TYPE_DOUBLE);
  791. break;
  792. case UPB_DESCRIPTOR_TYPE_FLOAT:
  793. upb_fielddef_settype(f, UPB_TYPE_FLOAT);
  794. break;
  795. case UPB_DESCRIPTOR_TYPE_INT64:
  796. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  797. case UPB_DESCRIPTOR_TYPE_SINT64:
  798. upb_fielddef_settype(f, UPB_TYPE_INT64);
  799. break;
  800. case UPB_DESCRIPTOR_TYPE_UINT64:
  801. case UPB_DESCRIPTOR_TYPE_FIXED64:
  802. upb_fielddef_settype(f, UPB_TYPE_UINT64);
  803. break;
  804. case UPB_DESCRIPTOR_TYPE_INT32:
  805. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  806. case UPB_DESCRIPTOR_TYPE_SINT32:
  807. upb_fielddef_settype(f, UPB_TYPE_INT32);
  808. break;
  809. case UPB_DESCRIPTOR_TYPE_UINT32:
  810. case UPB_DESCRIPTOR_TYPE_FIXED32:
  811. upb_fielddef_settype(f, UPB_TYPE_UINT32);
  812. break;
  813. case UPB_DESCRIPTOR_TYPE_BOOL:
  814. upb_fielddef_settype(f, UPB_TYPE_BOOL);
  815. break;
  816. case UPB_DESCRIPTOR_TYPE_STRING:
  817. upb_fielddef_settype(f, UPB_TYPE_STRING);
  818. break;
  819. case UPB_DESCRIPTOR_TYPE_BYTES:
  820. upb_fielddef_settype(f, UPB_TYPE_BYTES);
  821. break;
  822. case UPB_DESCRIPTOR_TYPE_GROUP:
  823. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  824. upb_fielddef_settype(f, UPB_TYPE_MESSAGE);
  825. break;
  826. case UPB_DESCRIPTOR_TYPE_ENUM:
  827. upb_fielddef_settype(f, UPB_TYPE_ENUM);
  828. break;
  829. default: assert(false);
  830. }
  831. if (type == UPB_DESCRIPTOR_TYPE_FIXED64 ||
  832. type == UPB_DESCRIPTOR_TYPE_FIXED32 ||
  833. type == UPB_DESCRIPTOR_TYPE_SFIXED64 ||
  834. type == UPB_DESCRIPTOR_TYPE_SFIXED32) {
  835. upb_fielddef_setintfmt(f, UPB_INTFMT_FIXED);
  836. } else if (type == UPB_DESCRIPTOR_TYPE_SINT64 ||
  837. type == UPB_DESCRIPTOR_TYPE_SINT32) {
  838. upb_fielddef_setintfmt(f, UPB_INTFMT_ZIGZAG);
  839. } else {
  840. upb_fielddef_setintfmt(f, UPB_INTFMT_VARIABLE);
  841. }
  842. upb_fielddef_settagdelim(f, type == UPB_DESCRIPTOR_TYPE_GROUP);
  843. }
  844. upb_descriptortype_t upb_fielddef_descriptortype(const upb_fielddef *f) {
  845. switch (upb_fielddef_type(f)) {
  846. case UPB_TYPE_FLOAT: return UPB_DESCRIPTOR_TYPE_FLOAT;
  847. case UPB_TYPE_DOUBLE: return UPB_DESCRIPTOR_TYPE_DOUBLE;
  848. case UPB_TYPE_BOOL: return UPB_DESCRIPTOR_TYPE_BOOL;
  849. case UPB_TYPE_STRING: return UPB_DESCRIPTOR_TYPE_STRING;
  850. case UPB_TYPE_BYTES: return UPB_DESCRIPTOR_TYPE_BYTES;
  851. case UPB_TYPE_ENUM: return UPB_DESCRIPTOR_TYPE_ENUM;
  852. case UPB_TYPE_INT32:
  853. switch (upb_fielddef_intfmt(f)) {
  854. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT32;
  855. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED32;
  856. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT32;
  857. }
  858. case UPB_TYPE_INT64:
  859. switch (upb_fielddef_intfmt(f)) {
  860. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT64;
  861. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED64;
  862. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT64;
  863. }
  864. case UPB_TYPE_UINT32:
  865. switch (upb_fielddef_intfmt(f)) {
  866. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT32;
  867. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED32;
  868. case UPB_INTFMT_ZIGZAG: return -1;
  869. }
  870. case UPB_TYPE_UINT64:
  871. switch (upb_fielddef_intfmt(f)) {
  872. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT64;
  873. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED64;
  874. case UPB_INTFMT_ZIGZAG: return -1;
  875. }
  876. case UPB_TYPE_MESSAGE:
  877. return upb_fielddef_istagdelim(f) ?
  878. UPB_DESCRIPTOR_TYPE_GROUP : UPB_DESCRIPTOR_TYPE_MESSAGE;
  879. }
  880. return 0;
  881. }
  882. void upb_fielddef_setisextension(upb_fielddef *f, bool is_extension) {
  883. assert(!upb_fielddef_isfrozen(f));
  884. f->is_extension_ = is_extension;
  885. }
  886. void upb_fielddef_setlazy(upb_fielddef *f, bool lazy) {
  887. assert(!upb_fielddef_isfrozen(f));
  888. f->lazy_ = lazy;
  889. }
  890. void upb_fielddef_setpacked(upb_fielddef *f, bool packed) {
  891. assert(!upb_fielddef_isfrozen(f));
  892. f->packed_ = packed;
  893. }
  894. void upb_fielddef_setlabel(upb_fielddef *f, upb_label_t label) {
  895. assert(!upb_fielddef_isfrozen(f));
  896. assert(upb_fielddef_checklabel(label));
  897. f->label_ = label;
  898. }
  899. void upb_fielddef_setintfmt(upb_fielddef *f, upb_intfmt_t fmt) {
  900. assert(!upb_fielddef_isfrozen(f));
  901. assert(upb_fielddef_checkintfmt(fmt));
  902. f->intfmt = fmt;
  903. }
  904. void upb_fielddef_settagdelim(upb_fielddef *f, bool tag_delim) {
  905. assert(!upb_fielddef_isfrozen(f));
  906. f->tagdelim = tag_delim;
  907. f->tagdelim = tag_delim;
  908. }
  909. static bool checksetdefault(upb_fielddef *f, upb_fieldtype_t type) {
  910. if (!f->type_is_set_ || upb_fielddef_isfrozen(f) ||
  911. upb_fielddef_type(f) != type) {
  912. assert(false);
  913. return false;
  914. }
  915. if (f->default_is_string) {
  916. str_t *s = f->defaultval.bytes;
  917. assert(s || type == UPB_TYPE_ENUM);
  918. if (s) freestr(s);
  919. }
  920. f->default_is_string = false;
  921. return true;
  922. }
  923. void upb_fielddef_setdefaultint64(upb_fielddef *f, int64_t value) {
  924. if (checksetdefault(f, UPB_TYPE_INT64))
  925. f->defaultval.sint = value;
  926. }
  927. void upb_fielddef_setdefaultint32(upb_fielddef *f, int32_t value) {
  928. if ((upb_fielddef_type(f) == UPB_TYPE_ENUM &&
  929. checksetdefault(f, UPB_TYPE_ENUM)) ||
  930. checksetdefault(f, UPB_TYPE_INT32)) {
  931. f->defaultval.sint = value;
  932. }
  933. }
  934. void upb_fielddef_setdefaultuint64(upb_fielddef *f, uint64_t value) {
  935. if (checksetdefault(f, UPB_TYPE_UINT64))
  936. f->defaultval.uint = value;
  937. }
  938. void upb_fielddef_setdefaultuint32(upb_fielddef *f, uint32_t value) {
  939. if (checksetdefault(f, UPB_TYPE_UINT32))
  940. f->defaultval.uint = value;
  941. }
  942. void upb_fielddef_setdefaultbool(upb_fielddef *f, bool value) {
  943. if (checksetdefault(f, UPB_TYPE_BOOL))
  944. f->defaultval.uint = value;
  945. }
  946. void upb_fielddef_setdefaultfloat(upb_fielddef *f, float value) {
  947. if (checksetdefault(f, UPB_TYPE_FLOAT))
  948. f->defaultval.flt = value;
  949. }
  950. void upb_fielddef_setdefaultdouble(upb_fielddef *f, double value) {
  951. if (checksetdefault(f, UPB_TYPE_DOUBLE))
  952. f->defaultval.dbl = value;
  953. }
  954. bool upb_fielddef_setdefaultstr(upb_fielddef *f, const void *str, size_t len,
  955. upb_status *s) {
  956. str_t *str2;
  957. assert(upb_fielddef_isstring(f) || f->type_ == UPB_TYPE_ENUM);
  958. if (f->type_ == UPB_TYPE_ENUM && !upb_isident(str, len, false, s))
  959. return false;
  960. if (f->default_is_string) {
  961. str_t *s = f->defaultval.bytes;
  962. assert(s || f->type_ == UPB_TYPE_ENUM);
  963. if (s) freestr(s);
  964. } else {
  965. assert(f->type_ == UPB_TYPE_ENUM);
  966. }
  967. str2 = newstr(str, len);
  968. f->defaultval.bytes = str2;
  969. f->default_is_string = true;
  970. return true;
  971. }
  972. void upb_fielddef_setdefaultcstr(upb_fielddef *f, const char *str,
  973. upb_status *s) {
  974. assert(f->type_is_set_);
  975. upb_fielddef_setdefaultstr(f, str, str ? strlen(str) : 0, s);
  976. }
  977. bool upb_fielddef_enumhasdefaultint32(const upb_fielddef *f) {
  978. int32_t val;
  979. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  980. return enumdefaultint32(f, &val);
  981. }
  982. bool upb_fielddef_enumhasdefaultstr(const upb_fielddef *f) {
  983. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  984. return enumdefaultstr(f) != NULL;
  985. }
  986. static bool upb_subdef_typecheck(upb_fielddef *f, const upb_def *subdef,
  987. upb_status *s) {
  988. if (f->type_ == UPB_TYPE_MESSAGE) {
  989. if (upb_dyncast_msgdef(subdef)) return true;
  990. upb_status_seterrmsg(s, "invalid subdef type for this submessage field");
  991. return false;
  992. } else if (f->type_ == UPB_TYPE_ENUM) {
  993. if (upb_dyncast_enumdef(subdef)) return true;
  994. upb_status_seterrmsg(s, "invalid subdef type for this enum field");
  995. return false;
  996. } else {
  997. upb_status_seterrmsg(s, "only message and enum fields can have a subdef");
  998. return false;
  999. }
  1000. }
  1001. static void release_subdef(upb_fielddef *f) {
  1002. if (f->subdef_is_symbolic) {
  1003. free(f->sub.name);
  1004. } else if (f->sub.def) {
  1005. upb_unref2(f->sub.def, f);
  1006. }
  1007. }
  1008. bool upb_fielddef_setsubdef(upb_fielddef *f, const upb_def *subdef,
  1009. upb_status *s) {
  1010. assert(!upb_fielddef_isfrozen(f));
  1011. assert(upb_fielddef_hassubdef(f));
  1012. if (subdef && !upb_subdef_typecheck(f, subdef, s)) return false;
  1013. release_subdef(f);
  1014. f->sub.def = subdef;
  1015. f->subdef_is_symbolic = false;
  1016. if (f->sub.def) upb_ref2(f->sub.def, f);
  1017. return true;
  1018. }
  1019. bool upb_fielddef_setmsgsubdef(upb_fielddef *f, const upb_msgdef *subdef,
  1020. upb_status *s) {
  1021. return upb_fielddef_setsubdef(f, upb_msgdef_upcast(subdef), s);
  1022. }
  1023. bool upb_fielddef_setenumsubdef(upb_fielddef *f, const upb_enumdef *subdef,
  1024. upb_status *s) {
  1025. return upb_fielddef_setsubdef(f, upb_enumdef_upcast(subdef), s);
  1026. }
  1027. bool upb_fielddef_setsubdefname(upb_fielddef *f, const char *name,
  1028. upb_status *s) {
  1029. assert(!upb_fielddef_isfrozen(f));
  1030. if (!upb_fielddef_hassubdef(f)) {
  1031. upb_status_seterrmsg(s, "field type does not accept a subdef");
  1032. return false;
  1033. }
  1034. /* TODO: validate name (upb_isident() doesn't quite work atm because this name
  1035. * may have a leading "."). */
  1036. release_subdef(f);
  1037. f->sub.name = upb_strdup(name);
  1038. f->subdef_is_symbolic = true;
  1039. return true;
  1040. }
  1041. bool upb_fielddef_issubmsg(const upb_fielddef *f) {
  1042. return upb_fielddef_type(f) == UPB_TYPE_MESSAGE;
  1043. }
  1044. bool upb_fielddef_isstring(const upb_fielddef *f) {
  1045. return upb_fielddef_type(f) == UPB_TYPE_STRING ||
  1046. upb_fielddef_type(f) == UPB_TYPE_BYTES;
  1047. }
  1048. bool upb_fielddef_isseq(const upb_fielddef *f) {
  1049. return upb_fielddef_label(f) == UPB_LABEL_REPEATED;
  1050. }
  1051. bool upb_fielddef_isprimitive(const upb_fielddef *f) {
  1052. return !upb_fielddef_isstring(f) && !upb_fielddef_issubmsg(f);
  1053. }
  1054. bool upb_fielddef_ismap(const upb_fielddef *f) {
  1055. return upb_fielddef_isseq(f) && upb_fielddef_issubmsg(f) &&
  1056. upb_msgdef_mapentry(upb_fielddef_msgsubdef(f));
  1057. }
  1058. bool upb_fielddef_hassubdef(const upb_fielddef *f) {
  1059. return upb_fielddef_issubmsg(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM;
  1060. }
  1061. static bool between(int32_t x, int32_t low, int32_t high) {
  1062. return x >= low && x <= high;
  1063. }
  1064. bool upb_fielddef_checklabel(int32_t label) { return between(label, 1, 3); }
  1065. bool upb_fielddef_checktype(int32_t type) { return between(type, 1, 11); }
  1066. bool upb_fielddef_checkintfmt(int32_t fmt) { return between(fmt, 1, 3); }
  1067. bool upb_fielddef_checkdescriptortype(int32_t type) {
  1068. return between(type, 1, 18);
  1069. }
  1070. /* upb_msgdef *****************************************************************/
  1071. static void visitmsg(const upb_refcounted *r, upb_refcounted_visit *visit,
  1072. void *closure) {
  1073. upb_msg_oneof_iter o;
  1074. const upb_msgdef *m = (const upb_msgdef*)r;
  1075. upb_msg_field_iter i;
  1076. for(upb_msg_field_begin(&i, m);
  1077. !upb_msg_field_done(&i);
  1078. upb_msg_field_next(&i)) {
  1079. upb_fielddef *f = upb_msg_iter_field(&i);
  1080. visit(r, upb_fielddef_upcast2(f), closure);
  1081. }
  1082. for(upb_msg_oneof_begin(&o, m);
  1083. !upb_msg_oneof_done(&o);
  1084. upb_msg_oneof_next(&o)) {
  1085. upb_oneofdef *f = upb_msg_iter_oneof(&o);
  1086. visit(r, upb_oneofdef_upcast2(f), closure);
  1087. }
  1088. }
  1089. static void freemsg(upb_refcounted *r) {
  1090. upb_msgdef *m = (upb_msgdef*)r;
  1091. upb_strtable_uninit(&m->ntoo);
  1092. upb_strtable_uninit(&m->ntof);
  1093. upb_inttable_uninit(&m->itof);
  1094. upb_def_uninit(upb_msgdef_upcast_mutable(m));
  1095. free(m);
  1096. }
  1097. upb_msgdef *upb_msgdef_new(const void *owner) {
  1098. static const struct upb_refcounted_vtbl vtbl = {visitmsg, freemsg};
  1099. upb_msgdef *m = malloc(sizeof(*m));
  1100. if (!m) return NULL;
  1101. if (!upb_def_init(upb_msgdef_upcast_mutable(m), UPB_DEF_MSG, &vtbl, owner))
  1102. goto err2;
  1103. if (!upb_inttable_init(&m->itof, UPB_CTYPE_PTR)) goto err3;
  1104. if (!upb_strtable_init(&m->ntof, UPB_CTYPE_PTR)) goto err2;
  1105. if (!upb_strtable_init(&m->ntoo, UPB_CTYPE_PTR)) goto err1;
  1106. m->map_entry = false;
  1107. return m;
  1108. err1:
  1109. upb_strtable_uninit(&m->ntof);
  1110. err2:
  1111. upb_inttable_uninit(&m->itof);
  1112. err3:
  1113. free(m);
  1114. return NULL;
  1115. }
  1116. upb_msgdef *upb_msgdef_dup(const upb_msgdef *m, const void *owner) {
  1117. bool ok;
  1118. upb_msg_field_iter i;
  1119. upb_msg_oneof_iter o;
  1120. upb_msgdef *newm = upb_msgdef_new(owner);
  1121. if (!newm) return NULL;
  1122. ok = upb_def_setfullname(upb_msgdef_upcast_mutable(newm),
  1123. upb_def_fullname(upb_msgdef_upcast(m)),
  1124. NULL);
  1125. newm->map_entry = m->map_entry;
  1126. UPB_ASSERT_VAR(ok, ok);
  1127. for(upb_msg_field_begin(&i, m);
  1128. !upb_msg_field_done(&i);
  1129. upb_msg_field_next(&i)) {
  1130. upb_fielddef *f = upb_fielddef_dup(upb_msg_iter_field(&i), &f);
  1131. /* Fields in oneofs are dup'd below. */
  1132. if (upb_fielddef_containingoneof(f)) continue;
  1133. if (!f || !upb_msgdef_addfield(newm, f, &f, NULL)) {
  1134. upb_msgdef_unref(newm, owner);
  1135. return NULL;
  1136. }
  1137. }
  1138. for(upb_msg_oneof_begin(&o, m);
  1139. !upb_msg_oneof_done(&o);
  1140. upb_msg_oneof_next(&o)) {
  1141. upb_oneofdef *f = upb_oneofdef_dup(upb_msg_iter_oneof(&o), &f);
  1142. if (!f || !upb_msgdef_addoneof(newm, f, &f, NULL)) {
  1143. upb_msgdef_unref(newm, owner);
  1144. return NULL;
  1145. }
  1146. }
  1147. return newm;
  1148. }
  1149. bool upb_msgdef_freeze(upb_msgdef *m, upb_status *status) {
  1150. upb_def *d = upb_msgdef_upcast_mutable(m);
  1151. return upb_def_freeze(&d, 1, status);
  1152. }
  1153. const char *upb_msgdef_fullname(const upb_msgdef *m) {
  1154. return upb_def_fullname(upb_msgdef_upcast(m));
  1155. }
  1156. bool upb_msgdef_setfullname(upb_msgdef *m, const char *fullname,
  1157. upb_status *s) {
  1158. return upb_def_setfullname(upb_msgdef_upcast_mutable(m), fullname, s);
  1159. }
  1160. /* Helper: check that the field |f| is safe to add to msgdef |m|. Set an error
  1161. * on status |s| and return false if not. */
  1162. static bool check_field_add(const upb_msgdef *m, const upb_fielddef *f,
  1163. upb_status *s) {
  1164. if (upb_fielddef_containingtype(f) != NULL) {
  1165. upb_status_seterrmsg(s, "fielddef already belongs to a message");
  1166. return false;
  1167. } else if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  1168. upb_status_seterrmsg(s, "field name or number were not set");
  1169. return false;
  1170. } else if (upb_msgdef_ntofz(m, upb_fielddef_name(f)) ||
  1171. upb_msgdef_itof(m, upb_fielddef_number(f))) {
  1172. upb_status_seterrmsg(s, "duplicate field name or number for field");
  1173. return false;
  1174. }
  1175. return true;
  1176. }
  1177. static void add_field(upb_msgdef *m, upb_fielddef *f, const void *ref_donor) {
  1178. release_containingtype(f);
  1179. f->msg.def = m;
  1180. f->msg_is_symbolic = false;
  1181. upb_inttable_insert(&m->itof, upb_fielddef_number(f), upb_value_ptr(f));
  1182. upb_strtable_insert(&m->ntof, upb_fielddef_name(f), upb_value_ptr(f));
  1183. upb_ref2(f, m);
  1184. upb_ref2(m, f);
  1185. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  1186. }
  1187. bool upb_msgdef_addfield(upb_msgdef *m, upb_fielddef *f, const void *ref_donor,
  1188. upb_status *s) {
  1189. /* TODO: extensions need to have a separate namespace, because proto2 allows a
  1190. * top-level extension (ie. one not in any package) to have the same name as a
  1191. * field from the message.
  1192. *
  1193. * This also implies that there needs to be a separate lookup-by-name method
  1194. * for extensions. It seems desirable for iteration to return both extensions
  1195. * and non-extensions though.
  1196. *
  1197. * We also need to validate that the field number is in an extension range iff
  1198. * it is an extension.
  1199. *
  1200. * This method is idempotent. Check if |f| is already part of this msgdef and
  1201. * return immediately if so. */
  1202. if (upb_fielddef_containingtype(f) == m) {
  1203. return true;
  1204. }
  1205. /* Check constraints for all fields before performing any action. */
  1206. if (!check_field_add(m, f, s)) {
  1207. return false;
  1208. } else if (upb_fielddef_containingoneof(f) != NULL) {
  1209. /* Fields in a oneof can only be added by adding the oneof to the msgdef. */
  1210. upb_status_seterrmsg(s, "fielddef is part of a oneof");
  1211. return false;
  1212. }
  1213. /* Constraint checks ok, perform the action. */
  1214. add_field(m, f, ref_donor);
  1215. return true;
  1216. }
  1217. bool upb_msgdef_addoneof(upb_msgdef *m, upb_oneofdef *o, const void *ref_donor,
  1218. upb_status *s) {
  1219. upb_oneof_iter it;
  1220. /* Check various conditions that would prevent this oneof from being added. */
  1221. if (upb_oneofdef_containingtype(o)) {
  1222. upb_status_seterrmsg(s, "oneofdef already belongs to a message");
  1223. return false;
  1224. } else if (upb_oneofdef_name(o) == NULL) {
  1225. upb_status_seterrmsg(s, "oneofdef name was not set");
  1226. return false;
  1227. } else if (upb_msgdef_ntooz(m, upb_oneofdef_name(o))) {
  1228. upb_status_seterrmsg(s, "duplicate oneof name");
  1229. return false;
  1230. }
  1231. /* Check that all of the oneof's fields do not conflict with names or numbers
  1232. * of fields already in the message. */
  1233. for (upb_oneof_begin(&it, o); !upb_oneof_done(&it); upb_oneof_next(&it)) {
  1234. const upb_fielddef *f = upb_oneof_iter_field(&it);
  1235. if (!check_field_add(m, f, s)) {
  1236. return false;
  1237. }
  1238. }
  1239. /* Everything checks out -- commit now. */
  1240. /* Add oneof itself first. */
  1241. o->parent = m;
  1242. upb_strtable_insert(&m->ntoo, upb_oneofdef_name(o), upb_value_ptr(o));
  1243. upb_ref2(o, m);
  1244. upb_ref2(m, o);
  1245. /* Add each field of the oneof directly to the msgdef. */
  1246. for (upb_oneof_begin(&it, o); !upb_oneof_done(&it); upb_oneof_next(&it)) {
  1247. upb_fielddef *f = upb_oneof_iter_field(&it);
  1248. add_field(m, f, NULL);
  1249. }
  1250. if (ref_donor) upb_oneofdef_unref(o, ref_donor);
  1251. return true;
  1252. }
  1253. const upb_fielddef *upb_msgdef_itof(const upb_msgdef *m, uint32_t i) {
  1254. upb_value val;
  1255. return upb_inttable_lookup32(&m->itof, i, &val) ?
  1256. upb_value_getptr(val) : NULL;
  1257. }
  1258. const upb_fielddef *upb_msgdef_ntof(const upb_msgdef *m, const char *name,
  1259. size_t len) {
  1260. upb_value val;
  1261. return upb_strtable_lookup2(&m->ntof, name, len, &val) ?
  1262. upb_value_getptr(val) : NULL;
  1263. }
  1264. const upb_oneofdef *upb_msgdef_ntoo(const upb_msgdef *m, const char *name,
  1265. size_t len) {
  1266. upb_value val;
  1267. return upb_strtable_lookup2(&m->ntoo, name, len, &val) ?
  1268. upb_value_getptr(val) : NULL;
  1269. }
  1270. int upb_msgdef_numfields(const upb_msgdef *m) {
  1271. return upb_strtable_count(&m->ntof);
  1272. }
  1273. int upb_msgdef_numoneofs(const upb_msgdef *m) {
  1274. return upb_strtable_count(&m->ntoo);
  1275. }
  1276. void upb_msgdef_setmapentry(upb_msgdef *m, bool map_entry) {
  1277. assert(!upb_msgdef_isfrozen(m));
  1278. m->map_entry = map_entry;
  1279. }
  1280. bool upb_msgdef_mapentry(const upb_msgdef *m) {
  1281. return m->map_entry;
  1282. }
  1283. void upb_msg_field_begin(upb_msg_field_iter *iter, const upb_msgdef *m) {
  1284. upb_inttable_begin(iter, &m->itof);
  1285. }
  1286. void upb_msg_field_next(upb_msg_field_iter *iter) { upb_inttable_next(iter); }
  1287. bool upb_msg_field_done(const upb_msg_field_iter *iter) {
  1288. return upb_inttable_done(iter);
  1289. }
  1290. upb_fielddef *upb_msg_iter_field(const upb_msg_field_iter *iter) {
  1291. return (upb_fielddef*)upb_value_getptr(upb_inttable_iter_value(iter));
  1292. }
  1293. void upb_msg_field_iter_setdone(upb_msg_field_iter *iter) {
  1294. upb_inttable_iter_setdone(iter);
  1295. }
  1296. void upb_msg_oneof_begin(upb_msg_oneof_iter *iter, const upb_msgdef *m) {
  1297. upb_strtable_begin(iter, &m->ntoo);
  1298. }
  1299. void upb_msg_oneof_next(upb_msg_oneof_iter *iter) { upb_strtable_next(iter); }
  1300. bool upb_msg_oneof_done(const upb_msg_oneof_iter *iter) {
  1301. return upb_strtable_done(iter);
  1302. }
  1303. upb_oneofdef *upb_msg_iter_oneof(const upb_msg_oneof_iter *iter) {
  1304. return (upb_oneofdef*)upb_value_getptr(upb_strtable_iter_value(iter));
  1305. }
  1306. void upb_msg_oneof_iter_setdone(upb_msg_oneof_iter *iter) {
  1307. upb_strtable_iter_setdone(iter);
  1308. }
  1309. /* upb_oneofdef ***************************************************************/
  1310. static void visitoneof(const upb_refcounted *r, upb_refcounted_visit *visit,
  1311. void *closure) {
  1312. const upb_oneofdef *o = (const upb_oneofdef*)r;
  1313. upb_oneof_iter i;
  1314. for (upb_oneof_begin(&i, o); !upb_oneof_done(&i); upb_oneof_next(&i)) {
  1315. const upb_fielddef *f = upb_oneof_iter_field(&i);
  1316. visit(r, upb_fielddef_upcast2(f), closure);
  1317. }
  1318. if (o->parent) {
  1319. visit(r, upb_msgdef_upcast2(o->parent), closure);
  1320. }
  1321. }
  1322. static void freeoneof(upb_refcounted *r) {
  1323. upb_oneofdef *o = (upb_oneofdef*)r;
  1324. upb_strtable_uninit(&o->ntof);
  1325. upb_inttable_uninit(&o->itof);
  1326. upb_def_uninit(upb_oneofdef_upcast_mutable(o));
  1327. free(o);
  1328. }
  1329. upb_oneofdef *upb_oneofdef_new(const void *owner) {
  1330. static const struct upb_refcounted_vtbl vtbl = {visitoneof, freeoneof};
  1331. upb_oneofdef *o = malloc(sizeof(*o));
  1332. o->parent = NULL;
  1333. if (!o) return NULL;
  1334. if (!upb_def_init(upb_oneofdef_upcast_mutable(o), UPB_DEF_ONEOF, &vtbl,
  1335. owner))
  1336. goto err2;
  1337. if (!upb_inttable_init(&o->itof, UPB_CTYPE_PTR)) goto err2;
  1338. if (!upb_strtable_init(&o->ntof, UPB_CTYPE_PTR)) goto err1;
  1339. return o;
  1340. err1:
  1341. upb_inttable_uninit(&o->itof);
  1342. err2:
  1343. free(o);
  1344. return NULL;
  1345. }
  1346. upb_oneofdef *upb_oneofdef_dup(const upb_oneofdef *o, const void *owner) {
  1347. bool ok;
  1348. upb_oneof_iter i;
  1349. upb_oneofdef *newo = upb_oneofdef_new(owner);
  1350. if (!newo) return NULL;
  1351. ok = upb_def_setfullname(upb_oneofdef_upcast_mutable(newo),
  1352. upb_def_fullname(upb_oneofdef_upcast(o)), NULL);
  1353. UPB_ASSERT_VAR(ok, ok);
  1354. for (upb_oneof_begin(&i, o); !upb_oneof_done(&i); upb_oneof_next(&i)) {
  1355. upb_fielddef *f = upb_fielddef_dup(upb_oneof_iter_field(&i), &f);
  1356. if (!f || !upb_oneofdef_addfield(newo, f, &f, NULL)) {
  1357. upb_oneofdef_unref(newo, owner);
  1358. return NULL;
  1359. }
  1360. }
  1361. return newo;
  1362. }
  1363. const char *upb_oneofdef_name(const upb_oneofdef *o) {
  1364. return upb_def_fullname(upb_oneofdef_upcast(o));
  1365. }
  1366. bool upb_oneofdef_setname(upb_oneofdef *o, const char *fullname,
  1367. upb_status *s) {
  1368. if (upb_oneofdef_containingtype(o)) {
  1369. upb_status_seterrmsg(s, "oneof already added to a message");
  1370. return false;
  1371. }
  1372. return upb_def_setfullname(upb_oneofdef_upcast_mutable(o), fullname, s);
  1373. }
  1374. const upb_msgdef *upb_oneofdef_containingtype(const upb_oneofdef *o) {
  1375. return o->parent;
  1376. }
  1377. int upb_oneofdef_numfields(const upb_oneofdef *o) {
  1378. return upb_strtable_count(&o->ntof);
  1379. }
  1380. bool upb_oneofdef_addfield(upb_oneofdef *o, upb_fielddef *f,
  1381. const void *ref_donor,
  1382. upb_status *s) {
  1383. assert(!upb_oneofdef_isfrozen(o));
  1384. assert(!o->parent || !upb_msgdef_isfrozen(o->parent));
  1385. /* This method is idempotent. Check if |f| is already part of this oneofdef
  1386. * and return immediately if so. */
  1387. if (upb_fielddef_containingoneof(f) == o) {
  1388. return true;
  1389. }
  1390. /* The field must have an OPTIONAL label. */
  1391. if (upb_fielddef_label(f) != UPB_LABEL_OPTIONAL) {
  1392. upb_status_seterrmsg(s, "fields in oneof must have OPTIONAL label");
  1393. return false;
  1394. }
  1395. /* Check that no field with this name or number exists already in the oneof.
  1396. * Also check that the field is not already part of a oneof. */
  1397. if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  1398. upb_status_seterrmsg(s, "field name or number were not set");
  1399. return false;
  1400. } else if (upb_oneofdef_itof(o, upb_fielddef_number(f)) ||
  1401. upb_oneofdef_ntofz(o, upb_fielddef_name(f))) {
  1402. upb_status_seterrmsg(s, "duplicate field name or number");
  1403. return false;
  1404. } else if (upb_fielddef_containingoneof(f) != NULL) {
  1405. upb_status_seterrmsg(s, "fielddef already belongs to a oneof");
  1406. return false;
  1407. }
  1408. /* We allow adding a field to the oneof either if the field is not part of a
  1409. * msgdef, or if it is and we are also part of the same msgdef. */
  1410. if (o->parent == NULL) {
  1411. /* If we're not in a msgdef, the field cannot be either. Otherwise we would
  1412. * need to magically add this oneof to a msgdef to remain consistent, which
  1413. * is surprising behavior. */
  1414. if (upb_fielddef_containingtype(f) != NULL) {
  1415. upb_status_seterrmsg(s, "fielddef already belongs to a message, but "
  1416. "oneof does not");
  1417. return false;
  1418. }
  1419. } else {
  1420. /* If we're in a msgdef, the user can add fields that either aren't in any
  1421. * msgdef (in which case they're added to our msgdef) or already a part of
  1422. * our msgdef. */
  1423. if (upb_fielddef_containingtype(f) != NULL &&
  1424. upb_fielddef_containingtype(f) != o->parent) {
  1425. upb_status_seterrmsg(s, "fielddef belongs to a different message "
  1426. "than oneof");
  1427. return false;
  1428. }
  1429. }
  1430. /* Commit phase. First add the field to our parent msgdef, if any, because
  1431. * that may fail; then add the field to our own tables. */
  1432. if (o->parent != NULL && upb_fielddef_containingtype(f) == NULL) {
  1433. if (!upb_msgdef_addfield((upb_msgdef*)o->parent, f, NULL, s)) {
  1434. return false;
  1435. }
  1436. }
  1437. release_containingtype(f);
  1438. f->oneof = o;
  1439. upb_inttable_insert(&o->itof, upb_fielddef_number(f), upb_value_ptr(f));
  1440. upb_strtable_insert(&o->ntof, upb_fielddef_name(f), upb_value_ptr(f));
  1441. upb_ref2(f, o);
  1442. upb_ref2(o, f);
  1443. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  1444. return true;
  1445. }
  1446. const upb_fielddef *upb_oneofdef_ntof(const upb_oneofdef *o,
  1447. const char *name, size_t length) {
  1448. upb_value val;
  1449. return upb_strtable_lookup2(&o->ntof, name, length, &val) ?
  1450. upb_value_getptr(val) : NULL;
  1451. }
  1452. const upb_fielddef *upb_oneofdef_itof(const upb_oneofdef *o, uint32_t num) {
  1453. upb_value val;
  1454. return upb_inttable_lookup32(&o->itof, num, &val) ?
  1455. upb_value_getptr(val) : NULL;
  1456. }
  1457. void upb_oneof_begin(upb_oneof_iter *iter, const upb_oneofdef *o) {
  1458. upb_inttable_begin(iter, &o->itof);
  1459. }
  1460. void upb_oneof_next(upb_oneof_iter *iter) {
  1461. upb_inttable_next(iter);
  1462. }
  1463. bool upb_oneof_done(upb_oneof_iter *iter) {
  1464. return upb_inttable_done(iter);
  1465. }
  1466. upb_fielddef *upb_oneof_iter_field(const upb_oneof_iter *iter) {
  1467. return (upb_fielddef*)upb_value_getptr(upb_inttable_iter_value(iter));
  1468. }
  1469. void upb_oneof_iter_setdone(upb_oneof_iter *iter) {
  1470. upb_inttable_iter_setdone(iter);
  1471. }
  1472. #include <stdlib.h>
  1473. #include <stdio.h>
  1474. #include <string.h>
  1475. typedef struct cleanup_ent {
  1476. upb_cleanup_func *cleanup;
  1477. void *ud;
  1478. struct cleanup_ent *next;
  1479. } cleanup_ent;
  1480. static void *seeded_alloc(void *ud, void *ptr, size_t oldsize, size_t size);
  1481. /* Default allocator **********************************************************/
  1482. /* Just use realloc, keeping all allocated blocks in a linked list to destroy at
  1483. * the end. */
  1484. typedef struct mem_block {
  1485. /* List is doubly-linked, because in cases where realloc() moves an existing
  1486. * block, we need to be able to remove the old pointer from the list
  1487. * efficiently. */
  1488. struct mem_block *prev, *next;
  1489. #ifndef NDEBUG
  1490. size_t size; /* Doesn't include mem_block structure. */
  1491. #endif
  1492. } mem_block;
  1493. typedef struct {
  1494. mem_block *head;
  1495. } default_alloc_ud;
  1496. static void *default_alloc(void *_ud, void *ptr, size_t oldsize, size_t size) {
  1497. default_alloc_ud *ud = _ud;
  1498. mem_block *from, *block;
  1499. void *ret;
  1500. UPB_UNUSED(oldsize);
  1501. from = ptr ? (void*)((char*)ptr - sizeof(mem_block)) : NULL;
  1502. #ifndef NDEBUG
  1503. if (from) {
  1504. assert(oldsize <= from->size);
  1505. }
  1506. #endif
  1507. /* TODO(haberman): we probably need to provide even better alignment here,
  1508. * like 16-byte alignment of the returned data pointer. */
  1509. block = realloc(from, size + sizeof(mem_block));
  1510. if (!block) return NULL;
  1511. ret = (char*)block + sizeof(*block);
  1512. #ifndef NDEBUG
  1513. block->size = size;
  1514. #endif
  1515. if (from) {
  1516. if (block != from) {
  1517. /* The block was moved, so pointers in next and prev blocks must be
  1518. * updated to its new location. */
  1519. if (block->next) block->next->prev = block;
  1520. if (block->prev) block->prev->next = block;
  1521. if (ud->head == from) ud->head = block;
  1522. }
  1523. } else {
  1524. /* Insert at head of linked list. */
  1525. block->prev = NULL;
  1526. block->next = ud->head;
  1527. if (block->next) block->next->prev = block;
  1528. ud->head = block;
  1529. }
  1530. return ret;
  1531. }
  1532. static void default_alloc_cleanup(void *_ud) {
  1533. default_alloc_ud *ud = _ud;
  1534. mem_block *block = ud->head;
  1535. while (block) {
  1536. void *to_free = block;
  1537. block = block->next;
  1538. free(to_free);
  1539. }
  1540. }
  1541. /* Standard error functions ***************************************************/
  1542. static bool default_err(void *ud, const upb_status *status) {
  1543. UPB_UNUSED(ud);
  1544. UPB_UNUSED(status);
  1545. return false;
  1546. }
  1547. static bool write_err_to(void *ud, const upb_status *status) {
  1548. upb_status *copy_to = ud;
  1549. upb_status_copy(copy_to, status);
  1550. return false;
  1551. }
  1552. /* upb_env ********************************************************************/
  1553. void upb_env_init(upb_env *e) {
  1554. default_alloc_ud *ud = (default_alloc_ud*)&e->default_alloc_ud;
  1555. e->ok_ = true;
  1556. e->bytes_allocated = 0;
  1557. e->cleanup_head = NULL;
  1558. ud->head = NULL;
  1559. /* Set default functions. */
  1560. upb_env_setallocfunc(e, default_alloc, ud);
  1561. upb_env_seterrorfunc(e, default_err, NULL);
  1562. }
  1563. void upb_env_uninit(upb_env *e) {
  1564. cleanup_ent *ent = e->cleanup_head;
  1565. while (ent) {
  1566. ent->cleanup(ent->ud);
  1567. ent = ent->next;
  1568. }
  1569. /* Must do this after running cleanup functions, because this will delete
  1570. the memory we store our cleanup entries in! */
  1571. if (e->alloc == default_alloc) {
  1572. default_alloc_cleanup(e->alloc_ud);
  1573. }
  1574. }
  1575. UPB_FORCEINLINE void upb_env_setallocfunc(upb_env *e, upb_alloc_func *alloc,
  1576. void *ud) {
  1577. e->alloc = alloc;
  1578. e->alloc_ud = ud;
  1579. }
  1580. UPB_FORCEINLINE void upb_env_seterrorfunc(upb_env *e, upb_error_func *func,
  1581. void *ud) {
  1582. e->err = func;
  1583. e->err_ud = ud;
  1584. }
  1585. void upb_env_reporterrorsto(upb_env *e, upb_status *status) {
  1586. e->err = write_err_to;
  1587. e->err_ud = status;
  1588. }
  1589. bool upb_env_ok(const upb_env *e) {
  1590. return e->ok_;
  1591. }
  1592. bool upb_env_reporterror(upb_env *e, const upb_status *status) {
  1593. e->ok_ = false;
  1594. return e->err(e->err_ud, status);
  1595. }
  1596. bool upb_env_addcleanup(upb_env *e, upb_cleanup_func *func, void *ud) {
  1597. cleanup_ent *ent = upb_env_malloc(e, sizeof(cleanup_ent));
  1598. if (!ent) return false;
  1599. ent->cleanup = func;
  1600. ent->ud = ud;
  1601. ent->next = e->cleanup_head;
  1602. e->cleanup_head = ent;
  1603. return true;
  1604. }
  1605. void *upb_env_malloc(upb_env *e, size_t size) {
  1606. e->bytes_allocated += size;
  1607. if (e->alloc == seeded_alloc) {
  1608. /* This is equivalent to the next branch, but allows inlining for a
  1609. * measurable perf benefit. */
  1610. return seeded_alloc(e->alloc_ud, NULL, 0, size);
  1611. } else {
  1612. return e->alloc(e->alloc_ud, NULL, 0, size);
  1613. }
  1614. }
  1615. void *upb_env_realloc(upb_env *e, void *ptr, size_t oldsize, size_t size) {
  1616. char *ret;
  1617. assert(oldsize <= size);
  1618. ret = e->alloc(e->alloc_ud, ptr, oldsize, size);
  1619. #ifndef NDEBUG
  1620. /* Overwrite non-preserved memory to ensure callers are passing the oldsize
  1621. * that they truly require. */
  1622. memset(ret + oldsize, 0xff, size - oldsize);
  1623. #endif
  1624. return ret;
  1625. }
  1626. size_t upb_env_bytesallocated(const upb_env *e) {
  1627. return e->bytes_allocated;
  1628. }
  1629. /* upb_seededalloc ************************************************************/
  1630. /* Be conservative and choose 16 in case anyone is using SSE. */
  1631. static const size_t maxalign = 16;
  1632. static size_t align_up(size_t size) {
  1633. return ((size + maxalign - 1) / maxalign) * maxalign;
  1634. }
  1635. UPB_FORCEINLINE static void *seeded_alloc(void *ud, void *ptr, size_t oldsize,
  1636. size_t size) {
  1637. upb_seededalloc *a = ud;
  1638. size = align_up(size);
  1639. assert(a->mem_limit >= a->mem_ptr);
  1640. if (oldsize == 0 && size <= (size_t)(a->mem_limit - a->mem_ptr)) {
  1641. /* Fast path: we can satisfy from the initial allocation. */
  1642. void *ret = a->mem_ptr;
  1643. a->mem_ptr += size;
  1644. return ret;
  1645. } else {
  1646. char *chptr = ptr;
  1647. /* Slow path: fallback to other allocator. */
  1648. a->need_cleanup = true;
  1649. /* Is `ptr` part of the user-provided initial block? Don't pass it to the
  1650. * default allocator if so; otherwise, it may try to realloc() the block. */
  1651. if (chptr >= a->mem_base && chptr < a->mem_limit) {
  1652. void *ret;
  1653. assert(chptr + oldsize <= a->mem_limit);
  1654. ret = a->alloc(a->alloc_ud, NULL, 0, size);
  1655. if (ret) memcpy(ret, ptr, oldsize);
  1656. return ret;
  1657. } else {
  1658. return a->alloc(a->alloc_ud, ptr, oldsize, size);
  1659. }
  1660. }
  1661. }
  1662. void upb_seededalloc_init(upb_seededalloc *a, void *mem, size_t len) {
  1663. default_alloc_ud *ud = (default_alloc_ud*)&a->default_alloc_ud;
  1664. a->mem_base = mem;
  1665. a->mem_ptr = mem;
  1666. a->mem_limit = (char*)mem + len;
  1667. a->need_cleanup = false;
  1668. a->returned_allocfunc = false;
  1669. ud->head = NULL;
  1670. upb_seededalloc_setfallbackalloc(a, default_alloc, ud);
  1671. }
  1672. void upb_seededalloc_uninit(upb_seededalloc *a) {
  1673. if (a->alloc == default_alloc && a->need_cleanup) {
  1674. default_alloc_cleanup(a->alloc_ud);
  1675. }
  1676. }
  1677. UPB_FORCEINLINE void upb_seededalloc_setfallbackalloc(upb_seededalloc *a,
  1678. upb_alloc_func *alloc,
  1679. void *ud) {
  1680. assert(!a->returned_allocfunc);
  1681. a->alloc = alloc;
  1682. a->alloc_ud = ud;
  1683. }
  1684. upb_alloc_func *upb_seededalloc_getallocfunc(upb_seededalloc *a) {
  1685. a->returned_allocfunc = true;
  1686. return seeded_alloc;
  1687. }
  1688. /*
  1689. ** TODO(haberman): it's unclear whether a lot of the consistency checks should
  1690. ** assert() or return false.
  1691. */
  1692. #include <stdlib.h>
  1693. #include <string.h>
  1694. /* Defined for the sole purpose of having a unique pointer value for
  1695. * UPB_NO_CLOSURE. */
  1696. char _upb_noclosure;
  1697. static void freehandlers(upb_refcounted *r) {
  1698. upb_handlers *h = (upb_handlers*)r;
  1699. upb_inttable_iter i;
  1700. upb_inttable_begin(&i, &h->cleanup_);
  1701. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  1702. void *val = (void*)upb_inttable_iter_key(&i);
  1703. upb_value func_val = upb_inttable_iter_value(&i);
  1704. upb_handlerfree *func = upb_value_getfptr(func_val);
  1705. func(val);
  1706. }
  1707. upb_inttable_uninit(&h->cleanup_);
  1708. upb_msgdef_unref(h->msg, h);
  1709. free(h->sub);
  1710. free(h);
  1711. }
  1712. static void visithandlers(const upb_refcounted *r, upb_refcounted_visit *visit,
  1713. void *closure) {
  1714. const upb_handlers *h = (const upb_handlers*)r;
  1715. upb_msg_field_iter i;
  1716. for(upb_msg_field_begin(&i, h->msg);
  1717. !upb_msg_field_done(&i);
  1718. upb_msg_field_next(&i)) {
  1719. upb_fielddef *f = upb_msg_iter_field(&i);
  1720. const upb_handlers *sub;
  1721. if (!upb_fielddef_issubmsg(f)) continue;
  1722. sub = upb_handlers_getsubhandlers(h, f);
  1723. if (sub) visit(r, upb_handlers_upcast(sub), closure);
  1724. }
  1725. }
  1726. static const struct upb_refcounted_vtbl vtbl = {visithandlers, freehandlers};
  1727. typedef struct {
  1728. upb_inttable tab; /* maps upb_msgdef* -> upb_handlers*. */
  1729. upb_handlers_callback *callback;
  1730. const void *closure;
  1731. } dfs_state;
  1732. /* TODO(haberman): discard upb_handlers* objects that do not actually have any
  1733. * handlers set and cannot reach any upb_handlers* object that does. This is
  1734. * slightly tricky to do correctly. */
  1735. static upb_handlers *newformsg(const upb_msgdef *m, const void *owner,
  1736. dfs_state *s) {
  1737. upb_msg_field_iter i;
  1738. upb_handlers *h = upb_handlers_new(m, owner);
  1739. if (!h) return NULL;
  1740. if (!upb_inttable_insertptr(&s->tab, m, upb_value_ptr(h))) goto oom;
  1741. s->callback(s->closure, h);
  1742. /* For each submessage field, get or create a handlers object and set it as
  1743. * the subhandlers. */
  1744. for(upb_msg_field_begin(&i, m);
  1745. !upb_msg_field_done(&i);
  1746. upb_msg_field_next(&i)) {
  1747. upb_fielddef *f = upb_msg_iter_field(&i);
  1748. const upb_msgdef *subdef;
  1749. upb_value subm_ent;
  1750. if (!upb_fielddef_issubmsg(f)) continue;
  1751. subdef = upb_downcast_msgdef(upb_fielddef_subdef(f));
  1752. if (upb_inttable_lookupptr(&s->tab, subdef, &subm_ent)) {
  1753. upb_handlers_setsubhandlers(h, f, upb_value_getptr(subm_ent));
  1754. } else {
  1755. upb_handlers *sub_mh = newformsg(subdef, &sub_mh, s);
  1756. if (!sub_mh) goto oom;
  1757. upb_handlers_setsubhandlers(h, f, sub_mh);
  1758. upb_handlers_unref(sub_mh, &sub_mh);
  1759. }
  1760. }
  1761. return h;
  1762. oom:
  1763. upb_handlers_unref(h, owner);
  1764. return NULL;
  1765. }
  1766. /* Given a selector for a STARTSUBMSG handler, resolves to a pointer to the
  1767. * subhandlers for this submessage field. */
  1768. #define SUBH(h, selector) (h->sub[selector])
  1769. /* The selector for a submessage field is the field index. */
  1770. #define SUBH_F(h, f) SUBH(h, f->index_)
  1771. static int32_t trygetsel(upb_handlers *h, const upb_fielddef *f,
  1772. upb_handlertype_t type) {
  1773. upb_selector_t sel;
  1774. assert(!upb_handlers_isfrozen(h));
  1775. if (upb_handlers_msgdef(h) != upb_fielddef_containingtype(f)) {
  1776. upb_status_seterrf(
  1777. &h->status_, "type mismatch: field %s does not belong to message %s",
  1778. upb_fielddef_name(f), upb_msgdef_fullname(upb_handlers_msgdef(h)));
  1779. return -1;
  1780. }
  1781. if (!upb_handlers_getselector(f, type, &sel)) {
  1782. upb_status_seterrf(
  1783. &h->status_,
  1784. "type mismatch: cannot register handler type %d for field %s",
  1785. type, upb_fielddef_name(f));
  1786. return -1;
  1787. }
  1788. return sel;
  1789. }
  1790. static upb_selector_t handlers_getsel(upb_handlers *h, const upb_fielddef *f,
  1791. upb_handlertype_t type) {
  1792. int32_t sel = trygetsel(h, f, type);
  1793. assert(sel >= 0);
  1794. return sel;
  1795. }
  1796. static const void **returntype(upb_handlers *h, const upb_fielddef *f,
  1797. upb_handlertype_t type) {
  1798. return &h->table[handlers_getsel(h, f, type)].attr.return_closure_type_;
  1799. }
  1800. static bool doset(upb_handlers *h, int32_t sel, const upb_fielddef *f,
  1801. upb_handlertype_t type, upb_func *func,
  1802. upb_handlerattr *attr) {
  1803. upb_handlerattr set_attr = UPB_HANDLERATTR_INITIALIZER;
  1804. const void *closure_type;
  1805. const void **context_closure_type;
  1806. assert(!upb_handlers_isfrozen(h));
  1807. if (sel < 0) {
  1808. upb_status_seterrmsg(&h->status_,
  1809. "incorrect handler type for this field.");
  1810. return false;
  1811. }
  1812. if (h->table[sel].func) {
  1813. upb_status_seterrmsg(&h->status_,
  1814. "cannot change handler once it has been set.");
  1815. return false;
  1816. }
  1817. if (attr) {
  1818. set_attr = *attr;
  1819. }
  1820. /* Check that the given closure type matches the closure type that has been
  1821. * established for this context (if any). */
  1822. closure_type = upb_handlerattr_closuretype(&set_attr);
  1823. if (type == UPB_HANDLER_STRING) {
  1824. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSTR);
  1825. } else if (f && upb_fielddef_isseq(f) &&
  1826. type != UPB_HANDLER_STARTSEQ &&
  1827. type != UPB_HANDLER_ENDSEQ) {
  1828. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSEQ);
  1829. } else {
  1830. context_closure_type = &h->top_closure_type;
  1831. }
  1832. if (closure_type && *context_closure_type &&
  1833. closure_type != *context_closure_type) {
  1834. /* TODO(haberman): better message for debugging. */
  1835. if (f) {
  1836. upb_status_seterrf(&h->status_,
  1837. "closure type does not match for field %s",
  1838. upb_fielddef_name(f));
  1839. } else {
  1840. upb_status_seterrmsg(
  1841. &h->status_, "closure type does not match for message-level handler");
  1842. }
  1843. return false;
  1844. }
  1845. if (closure_type)
  1846. *context_closure_type = closure_type;
  1847. /* If this is a STARTSEQ or STARTSTR handler, check that the returned pointer
  1848. * matches any pre-existing expectations about what type is expected. */
  1849. if (type == UPB_HANDLER_STARTSEQ || type == UPB_HANDLER_STARTSTR) {
  1850. const void *return_type = upb_handlerattr_returnclosuretype(&set_attr);
  1851. const void *table_return_type =
  1852. upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1853. if (return_type && table_return_type && return_type != table_return_type) {
  1854. upb_status_seterrmsg(&h->status_, "closure return type does not match");
  1855. return false;
  1856. }
  1857. if (table_return_type && !return_type)
  1858. upb_handlerattr_setreturnclosuretype(&set_attr, table_return_type);
  1859. }
  1860. h->table[sel].func = (upb_func*)func;
  1861. h->table[sel].attr = set_attr;
  1862. return true;
  1863. }
  1864. /* Returns the effective closure type for this handler (which will propagate
  1865. * from outer frames if this frame has no START* handler). Not implemented for
  1866. * UPB_HANDLER_STRING at the moment since this is not needed. Returns NULL is
  1867. * the effective closure type is unspecified (either no handler was registered
  1868. * to specify it or the handler that was registered did not specify the closure
  1869. * type). */
  1870. const void *effective_closure_type(upb_handlers *h, const upb_fielddef *f,
  1871. upb_handlertype_t type) {
  1872. const void *ret;
  1873. upb_selector_t sel;
  1874. assert(type != UPB_HANDLER_STRING);
  1875. ret = h->top_closure_type;
  1876. if (upb_fielddef_isseq(f) &&
  1877. type != UPB_HANDLER_STARTSEQ &&
  1878. type != UPB_HANDLER_ENDSEQ &&
  1879. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)].func) {
  1880. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1881. }
  1882. if (type == UPB_HANDLER_STRING &&
  1883. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSTR)].func) {
  1884. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1885. }
  1886. /* The effective type of the submessage; not used yet.
  1887. * if (type == SUBMESSAGE &&
  1888. * h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)].func) {
  1889. * ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1890. * } */
  1891. return ret;
  1892. }
  1893. /* Checks whether the START* handler specified by f & type is missing even
  1894. * though it is required to convert the established type of an outer frame
  1895. * ("closure_type") into the established type of an inner frame (represented in
  1896. * the return closure type of this handler's attr. */
  1897. bool checkstart(upb_handlers *h, const upb_fielddef *f, upb_handlertype_t type,
  1898. upb_status *status) {
  1899. const void *closure_type;
  1900. const upb_handlerattr *attr;
  1901. const void *return_closure_type;
  1902. upb_selector_t sel = handlers_getsel(h, f, type);
  1903. if (h->table[sel].func) return true;
  1904. closure_type = effective_closure_type(h, f, type);
  1905. attr = &h->table[sel].attr;
  1906. return_closure_type = upb_handlerattr_returnclosuretype(attr);
  1907. if (closure_type && return_closure_type &&
  1908. closure_type != return_closure_type) {
  1909. upb_status_seterrf(status,
  1910. "expected start handler to return sub type for field %f",
  1911. upb_fielddef_name(f));
  1912. return false;
  1913. }
  1914. return true;
  1915. }
  1916. /* Public interface ***********************************************************/
  1917. upb_handlers *upb_handlers_new(const upb_msgdef *md, const void *owner) {
  1918. int extra;
  1919. upb_handlers *h;
  1920. assert(upb_msgdef_isfrozen(md));
  1921. extra = sizeof(upb_handlers_tabent) * (md->selector_count - 1);
  1922. h = calloc(sizeof(*h) + extra, 1);
  1923. if (!h) return NULL;
  1924. h->msg = md;
  1925. upb_msgdef_ref(h->msg, h);
  1926. upb_status_clear(&h->status_);
  1927. h->sub = calloc(md->submsg_field_count, sizeof(*h->sub));
  1928. if (!h->sub) goto oom;
  1929. if (!upb_refcounted_init(upb_handlers_upcast_mutable(h), &vtbl, owner))
  1930. goto oom;
  1931. if (!upb_inttable_init(&h->cleanup_, UPB_CTYPE_FPTR)) goto oom;
  1932. /* calloc() above initialized all handlers to NULL. */
  1933. return h;
  1934. oom:
  1935. freehandlers(upb_handlers_upcast_mutable(h));
  1936. return NULL;
  1937. }
  1938. const upb_handlers *upb_handlers_newfrozen(const upb_msgdef *m,
  1939. const void *owner,
  1940. upb_handlers_callback *callback,
  1941. const void *closure) {
  1942. dfs_state state;
  1943. upb_handlers *ret;
  1944. bool ok;
  1945. upb_refcounted *r;
  1946. state.callback = callback;
  1947. state.closure = closure;
  1948. if (!upb_inttable_init(&state.tab, UPB_CTYPE_PTR)) return NULL;
  1949. ret = newformsg(m, owner, &state);
  1950. upb_inttable_uninit(&state.tab);
  1951. if (!ret) return NULL;
  1952. r = upb_handlers_upcast_mutable(ret);
  1953. ok = upb_refcounted_freeze(&r, 1, NULL, UPB_MAX_HANDLER_DEPTH);
  1954. UPB_ASSERT_VAR(ok, ok);
  1955. return ret;
  1956. }
  1957. const upb_status *upb_handlers_status(upb_handlers *h) {
  1958. assert(!upb_handlers_isfrozen(h));
  1959. return &h->status_;
  1960. }
  1961. void upb_handlers_clearerr(upb_handlers *h) {
  1962. assert(!upb_handlers_isfrozen(h));
  1963. upb_status_clear(&h->status_);
  1964. }
  1965. #define SETTER(name, handlerctype, handlertype) \
  1966. bool upb_handlers_set ## name(upb_handlers *h, const upb_fielddef *f, \
  1967. handlerctype func, upb_handlerattr *attr) { \
  1968. int32_t sel = trygetsel(h, f, handlertype); \
  1969. return doset(h, sel, f, handlertype, (upb_func*)func, attr); \
  1970. }
  1971. SETTER(int32, upb_int32_handlerfunc*, UPB_HANDLER_INT32)
  1972. SETTER(int64, upb_int64_handlerfunc*, UPB_HANDLER_INT64)
  1973. SETTER(uint32, upb_uint32_handlerfunc*, UPB_HANDLER_UINT32)
  1974. SETTER(uint64, upb_uint64_handlerfunc*, UPB_HANDLER_UINT64)
  1975. SETTER(float, upb_float_handlerfunc*, UPB_HANDLER_FLOAT)
  1976. SETTER(double, upb_double_handlerfunc*, UPB_HANDLER_DOUBLE)
  1977. SETTER(bool, upb_bool_handlerfunc*, UPB_HANDLER_BOOL)
  1978. SETTER(startstr, upb_startstr_handlerfunc*, UPB_HANDLER_STARTSTR)
  1979. SETTER(string, upb_string_handlerfunc*, UPB_HANDLER_STRING)
  1980. SETTER(endstr, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSTR)
  1981. SETTER(startseq, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSEQ)
  1982. SETTER(startsubmsg, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSUBMSG)
  1983. SETTER(endsubmsg, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSUBMSG)
  1984. SETTER(endseq, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSEQ)
  1985. #undef SETTER
  1986. bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
  1987. upb_handlerattr *attr) {
  1988. return doset(h, UPB_STARTMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  1989. (upb_func *)func, attr);
  1990. }
  1991. bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func,
  1992. upb_handlerattr *attr) {
  1993. assert(!upb_handlers_isfrozen(h));
  1994. return doset(h, UPB_ENDMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  1995. (upb_func *)func, attr);
  1996. }
  1997. bool upb_handlers_setsubhandlers(upb_handlers *h, const upb_fielddef *f,
  1998. const upb_handlers *sub) {
  1999. assert(sub);
  2000. assert(!upb_handlers_isfrozen(h));
  2001. assert(upb_fielddef_issubmsg(f));
  2002. if (SUBH_F(h, f)) return false; /* Can't reset. */
  2003. if (upb_msgdef_upcast(upb_handlers_msgdef(sub)) != upb_fielddef_subdef(f)) {
  2004. return false;
  2005. }
  2006. SUBH_F(h, f) = sub;
  2007. upb_ref2(sub, h);
  2008. return true;
  2009. }
  2010. const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h,
  2011. const upb_fielddef *f) {
  2012. assert(upb_fielddef_issubmsg(f));
  2013. return SUBH_F(h, f);
  2014. }
  2015. bool upb_handlers_getattr(const upb_handlers *h, upb_selector_t sel,
  2016. upb_handlerattr *attr) {
  2017. if (!upb_handlers_gethandler(h, sel))
  2018. return false;
  2019. *attr = h->table[sel].attr;
  2020. return true;
  2021. }
  2022. const upb_handlers *upb_handlers_getsubhandlers_sel(const upb_handlers *h,
  2023. upb_selector_t sel) {
  2024. /* STARTSUBMSG selector in sel is the field's selector base. */
  2025. return SUBH(h, sel - UPB_STATIC_SELECTOR_COUNT);
  2026. }
  2027. const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h) { return h->msg; }
  2028. bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *func) {
  2029. bool ok;
  2030. if (upb_inttable_lookupptr(&h->cleanup_, p, NULL)) {
  2031. return false;
  2032. }
  2033. ok = upb_inttable_insertptr(&h->cleanup_, p, upb_value_fptr(func));
  2034. UPB_ASSERT_VAR(ok, ok);
  2035. return true;
  2036. }
  2037. /* "Static" methods ***********************************************************/
  2038. bool upb_handlers_freeze(upb_handlers *const*handlers, int n, upb_status *s) {
  2039. /* TODO: verify we have a transitive closure. */
  2040. int i;
  2041. for (i = 0; i < n; i++) {
  2042. upb_msg_field_iter j;
  2043. upb_handlers *h = handlers[i];
  2044. if (!upb_ok(&h->status_)) {
  2045. upb_status_seterrf(s, "handlers for message %s had error status: %s",
  2046. upb_msgdef_fullname(upb_handlers_msgdef(h)),
  2047. upb_status_errmsg(&h->status_));
  2048. return false;
  2049. }
  2050. /* Check that there are no closure mismatches due to missing Start* handlers
  2051. * or subhandlers with different type-level types. */
  2052. for(upb_msg_field_begin(&j, h->msg);
  2053. !upb_msg_field_done(&j);
  2054. upb_msg_field_next(&j)) {
  2055. const upb_fielddef *f = upb_msg_iter_field(&j);
  2056. if (upb_fielddef_isseq(f)) {
  2057. if (!checkstart(h, f, UPB_HANDLER_STARTSEQ, s))
  2058. return false;
  2059. }
  2060. if (upb_fielddef_isstring(f)) {
  2061. if (!checkstart(h, f, UPB_HANDLER_STARTSTR, s))
  2062. return false;
  2063. }
  2064. if (upb_fielddef_issubmsg(f)) {
  2065. bool hashandler = false;
  2066. if (upb_handlers_gethandler(
  2067. h, handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)) ||
  2068. upb_handlers_gethandler(
  2069. h, handlers_getsel(h, f, UPB_HANDLER_ENDSUBMSG))) {
  2070. hashandler = true;
  2071. }
  2072. if (upb_fielddef_isseq(f) &&
  2073. (upb_handlers_gethandler(
  2074. h, handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)) ||
  2075. upb_handlers_gethandler(
  2076. h, handlers_getsel(h, f, UPB_HANDLER_ENDSEQ)))) {
  2077. hashandler = true;
  2078. }
  2079. if (hashandler && !upb_handlers_getsubhandlers(h, f)) {
  2080. /* For now we add an empty subhandlers in this case. It makes the
  2081. * decoder code generator simpler, because it only has to handle two
  2082. * cases (submessage has handlers or not) as opposed to three
  2083. * (submessage has handlers in enclosing message but no subhandlers).
  2084. *
  2085. * This makes parsing less efficient in the case that we want to
  2086. * notice a submessage but skip its contents (like if we're testing
  2087. * for submessage presence or counting the number of repeated
  2088. * submessages). In this case we will end up parsing the submessage
  2089. * field by field and throwing away the results for each, instead of
  2090. * skipping the whole delimited thing at once. If this is an issue we
  2091. * can revisit it, but do remember that this only arises when you have
  2092. * handlers (startseq/startsubmsg/endsubmsg/endseq) set for the
  2093. * submessage but no subhandlers. The uses cases for this are
  2094. * limited. */
  2095. upb_handlers *sub = upb_handlers_new(upb_fielddef_msgsubdef(f), &sub);
  2096. upb_handlers_setsubhandlers(h, f, sub);
  2097. upb_handlers_unref(sub, &sub);
  2098. }
  2099. /* TODO(haberman): check type of submessage.
  2100. * This is slightly tricky; also consider whether we should check that
  2101. * they match at setsubhandlers time. */
  2102. }
  2103. }
  2104. }
  2105. if (!upb_refcounted_freeze((upb_refcounted*const*)handlers, n, s,
  2106. UPB_MAX_HANDLER_DEPTH)) {
  2107. return false;
  2108. }
  2109. return true;
  2110. }
  2111. upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f) {
  2112. switch (upb_fielddef_type(f)) {
  2113. case UPB_TYPE_INT32:
  2114. case UPB_TYPE_ENUM: return UPB_HANDLER_INT32;
  2115. case UPB_TYPE_INT64: return UPB_HANDLER_INT64;
  2116. case UPB_TYPE_UINT32: return UPB_HANDLER_UINT32;
  2117. case UPB_TYPE_UINT64: return UPB_HANDLER_UINT64;
  2118. case UPB_TYPE_FLOAT: return UPB_HANDLER_FLOAT;
  2119. case UPB_TYPE_DOUBLE: return UPB_HANDLER_DOUBLE;
  2120. case UPB_TYPE_BOOL: return UPB_HANDLER_BOOL;
  2121. default: assert(false); return -1; /* Invalid input. */
  2122. }
  2123. }
  2124. bool upb_handlers_getselector(const upb_fielddef *f, upb_handlertype_t type,
  2125. upb_selector_t *s) {
  2126. switch (type) {
  2127. case UPB_HANDLER_INT32:
  2128. case UPB_HANDLER_INT64:
  2129. case UPB_HANDLER_UINT32:
  2130. case UPB_HANDLER_UINT64:
  2131. case UPB_HANDLER_FLOAT:
  2132. case UPB_HANDLER_DOUBLE:
  2133. case UPB_HANDLER_BOOL:
  2134. if (!upb_fielddef_isprimitive(f) ||
  2135. upb_handlers_getprimitivehandlertype(f) != type)
  2136. return false;
  2137. *s = f->selector_base;
  2138. break;
  2139. case UPB_HANDLER_STRING:
  2140. if (upb_fielddef_isstring(f)) {
  2141. *s = f->selector_base;
  2142. } else if (upb_fielddef_lazy(f)) {
  2143. *s = f->selector_base + 3;
  2144. } else {
  2145. return false;
  2146. }
  2147. break;
  2148. case UPB_HANDLER_STARTSTR:
  2149. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  2150. *s = f->selector_base + 1;
  2151. } else {
  2152. return false;
  2153. }
  2154. break;
  2155. case UPB_HANDLER_ENDSTR:
  2156. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  2157. *s = f->selector_base + 2;
  2158. } else {
  2159. return false;
  2160. }
  2161. break;
  2162. case UPB_HANDLER_STARTSEQ:
  2163. if (!upb_fielddef_isseq(f)) return false;
  2164. *s = f->selector_base - 2;
  2165. break;
  2166. case UPB_HANDLER_ENDSEQ:
  2167. if (!upb_fielddef_isseq(f)) return false;
  2168. *s = f->selector_base - 1;
  2169. break;
  2170. case UPB_HANDLER_STARTSUBMSG:
  2171. if (!upb_fielddef_issubmsg(f)) return false;
  2172. /* Selectors for STARTSUBMSG are at the beginning of the table so that the
  2173. * selector can also be used as an index into the "sub" array of
  2174. * subhandlers. The indexes for the two into these two tables are the
  2175. * same, except that in the handler table the static selectors come first. */
  2176. *s = f->index_ + UPB_STATIC_SELECTOR_COUNT;
  2177. break;
  2178. case UPB_HANDLER_ENDSUBMSG:
  2179. if (!upb_fielddef_issubmsg(f)) return false;
  2180. *s = f->selector_base;
  2181. break;
  2182. }
  2183. assert((size_t)*s < upb_fielddef_containingtype(f)->selector_count);
  2184. return true;
  2185. }
  2186. uint32_t upb_handlers_selectorbaseoffset(const upb_fielddef *f) {
  2187. return upb_fielddef_isseq(f) ? 2 : 0;
  2188. }
  2189. uint32_t upb_handlers_selectorcount(const upb_fielddef *f) {
  2190. uint32_t ret = 1;
  2191. if (upb_fielddef_isseq(f)) ret += 2; /* STARTSEQ/ENDSEQ */
  2192. if (upb_fielddef_isstring(f)) ret += 2; /* [STRING]/STARTSTR/ENDSTR */
  2193. if (upb_fielddef_issubmsg(f)) {
  2194. /* ENDSUBMSG (STARTSUBMSG is at table beginning) */
  2195. ret += 0;
  2196. if (upb_fielddef_lazy(f)) {
  2197. /* STARTSTR/ENDSTR/STRING (for lazy) */
  2198. ret += 3;
  2199. }
  2200. }
  2201. return ret;
  2202. }
  2203. /* upb_handlerattr ************************************************************/
  2204. void upb_handlerattr_init(upb_handlerattr *attr) {
  2205. upb_handlerattr from = UPB_HANDLERATTR_INITIALIZER;
  2206. memcpy(attr, &from, sizeof(*attr));
  2207. }
  2208. void upb_handlerattr_uninit(upb_handlerattr *attr) {
  2209. UPB_UNUSED(attr);
  2210. }
  2211. bool upb_handlerattr_sethandlerdata(upb_handlerattr *attr, const void *hd) {
  2212. attr->handler_data_ = hd;
  2213. return true;
  2214. }
  2215. bool upb_handlerattr_setclosuretype(upb_handlerattr *attr, const void *type) {
  2216. attr->closure_type_ = type;
  2217. return true;
  2218. }
  2219. const void *upb_handlerattr_closuretype(const upb_handlerattr *attr) {
  2220. return attr->closure_type_;
  2221. }
  2222. bool upb_handlerattr_setreturnclosuretype(upb_handlerattr *attr,
  2223. const void *type) {
  2224. attr->return_closure_type_ = type;
  2225. return true;
  2226. }
  2227. const void *upb_handlerattr_returnclosuretype(const upb_handlerattr *attr) {
  2228. return attr->return_closure_type_;
  2229. }
  2230. bool upb_handlerattr_setalwaysok(upb_handlerattr *attr, bool alwaysok) {
  2231. attr->alwaysok_ = alwaysok;
  2232. return true;
  2233. }
  2234. bool upb_handlerattr_alwaysok(const upb_handlerattr *attr) {
  2235. return attr->alwaysok_;
  2236. }
  2237. /* upb_bufhandle **************************************************************/
  2238. size_t upb_bufhandle_objofs(const upb_bufhandle *h) {
  2239. return h->objofs_;
  2240. }
  2241. /* upb_byteshandler ***********************************************************/
  2242. void upb_byteshandler_init(upb_byteshandler* h) {
  2243. memset(h, 0, sizeof(*h));
  2244. }
  2245. /* For when we support handlerfree callbacks. */
  2246. void upb_byteshandler_uninit(upb_byteshandler* h) {
  2247. UPB_UNUSED(h);
  2248. }
  2249. bool upb_byteshandler_setstartstr(upb_byteshandler *h,
  2250. upb_startstr_handlerfunc *func, void *d) {
  2251. h->table[UPB_STARTSTR_SELECTOR].func = (upb_func*)func;
  2252. h->table[UPB_STARTSTR_SELECTOR].attr.handler_data_ = d;
  2253. return true;
  2254. }
  2255. bool upb_byteshandler_setstring(upb_byteshandler *h,
  2256. upb_string_handlerfunc *func, void *d) {
  2257. h->table[UPB_STRING_SELECTOR].func = (upb_func*)func;
  2258. h->table[UPB_STRING_SELECTOR].attr.handler_data_ = d;
  2259. return true;
  2260. }
  2261. bool upb_byteshandler_setendstr(upb_byteshandler *h,
  2262. upb_endfield_handlerfunc *func, void *d) {
  2263. h->table[UPB_ENDSTR_SELECTOR].func = (upb_func*)func;
  2264. h->table[UPB_ENDSTR_SELECTOR].attr.handler_data_ = d;
  2265. return true;
  2266. }
  2267. /*
  2268. ** upb::RefCounted Implementation
  2269. **
  2270. ** Our key invariants are:
  2271. ** 1. reference cycles never span groups
  2272. ** 2. for ref2(to, from), we increment to's count iff group(from) != group(to)
  2273. **
  2274. ** The previous two are how we avoid leaking cycles. Other important
  2275. ** invariants are:
  2276. ** 3. for mutable objects "from" and "to", if there exists a ref2(to, from)
  2277. ** this implies group(from) == group(to). (In practice, what we implement
  2278. ** is even stronger; "from" and "to" will share a group if there has *ever*
  2279. ** been a ref2(to, from), but all that is necessary for correctness is the
  2280. ** weaker one).
  2281. ** 4. mutable and immutable objects are never in the same group.
  2282. */
  2283. #include <setjmp.h>
  2284. #include <stdlib.h>
  2285. static void freeobj(upb_refcounted *o);
  2286. const char untracked_val;
  2287. const void *UPB_UNTRACKED_REF = &untracked_val;
  2288. /* arch-specific atomic primitives *******************************************/
  2289. #ifdef UPB_THREAD_UNSAFE /*---------------------------------------------------*/
  2290. static void atomic_inc(uint32_t *a) { (*a)++; }
  2291. static bool atomic_dec(uint32_t *a) { return --(*a) == 0; }
  2292. #elif defined(__GNUC__) || defined(__clang__) /*------------------------------*/
  2293. static void atomic_inc(uint32_t *a) { __sync_fetch_and_add(a, 1); }
  2294. static bool atomic_dec(uint32_t *a) { return __sync_sub_and_fetch(a, 1) == 0; }
  2295. #elif defined(WIN32) /*-------------------------------------------------------*/
  2296. #include <Windows.h>
  2297. static void atomic_inc(upb_atomic_t *a) { InterlockedIncrement(&a->val); }
  2298. static bool atomic_dec(upb_atomic_t *a) {
  2299. return InterlockedDecrement(&a->val) == 0;
  2300. }
  2301. #else
  2302. #error Atomic primitives not defined for your platform/CPU. \
  2303. Implement them or compile with UPB_THREAD_UNSAFE.
  2304. #endif
  2305. /* All static objects point to this refcount.
  2306. * It is special-cased in ref/unref below. */
  2307. uint32_t static_refcount = -1;
  2308. /* We can avoid atomic ops for statically-declared objects.
  2309. * This is a minor optimization but nice since we can avoid degrading under
  2310. * contention in this case. */
  2311. static void refgroup(uint32_t *group) {
  2312. if (group != &static_refcount)
  2313. atomic_inc(group);
  2314. }
  2315. static bool unrefgroup(uint32_t *group) {
  2316. if (group == &static_refcount) {
  2317. return false;
  2318. } else {
  2319. return atomic_dec(group);
  2320. }
  2321. }
  2322. /* Reference tracking (debug only) ********************************************/
  2323. #ifdef UPB_DEBUG_REFS
  2324. #ifdef UPB_THREAD_UNSAFE
  2325. static void upb_lock() {}
  2326. static void upb_unlock() {}
  2327. #else
  2328. /* User must define functions that lock/unlock a global mutex and link this
  2329. * file against them. */
  2330. void upb_lock();
  2331. void upb_unlock();
  2332. #endif
  2333. /* UPB_DEBUG_REFS mode counts on being able to malloc() memory in some
  2334. * code-paths that can normally never fail, like upb_refcounted_ref(). Since
  2335. * we have no way to propagage out-of-memory errors back to the user, and since
  2336. * these errors can only occur in UPB_DEBUG_REFS mode, we immediately fail. */
  2337. #define CHECK_OOM(predicate) if (!(predicate)) { assert(predicate); exit(1); }
  2338. typedef struct {
  2339. int count; /* How many refs there are (duplicates only allowed for ref2). */
  2340. bool is_ref2;
  2341. } trackedref;
  2342. static trackedref *trackedref_new(bool is_ref2) {
  2343. trackedref *ret = malloc(sizeof(*ret));
  2344. CHECK_OOM(ret);
  2345. ret->count = 1;
  2346. ret->is_ref2 = is_ref2;
  2347. return ret;
  2348. }
  2349. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  2350. upb_value v;
  2351. assert(owner);
  2352. if (owner == UPB_UNTRACKED_REF) return;
  2353. upb_lock();
  2354. if (upb_inttable_lookupptr(r->refs, owner, &v)) {
  2355. trackedref *ref = upb_value_getptr(v);
  2356. /* Since we allow multiple ref2's for the same to/from pair without
  2357. * allocating separate memory for each one, we lose the fine-grained
  2358. * tracking behavior we get with regular refs. Since ref2s only happen
  2359. * inside upb, we'll accept this limitation until/unless there is a really
  2360. * difficult upb-internal bug that can't be figured out without it. */
  2361. assert(ref2);
  2362. assert(ref->is_ref2);
  2363. ref->count++;
  2364. } else {
  2365. trackedref *ref = trackedref_new(ref2);
  2366. bool ok = upb_inttable_insertptr(r->refs, owner, upb_value_ptr(ref));
  2367. CHECK_OOM(ok);
  2368. if (ref2) {
  2369. /* We know this cast is safe when it is a ref2, because it's coming from
  2370. * another refcounted object. */
  2371. const upb_refcounted *from = owner;
  2372. assert(!upb_inttable_lookupptr(from->ref2s, r, NULL));
  2373. ok = upb_inttable_insertptr(from->ref2s, r, upb_value_ptr(NULL));
  2374. CHECK_OOM(ok);
  2375. }
  2376. }
  2377. upb_unlock();
  2378. }
  2379. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  2380. upb_value v;
  2381. bool found;
  2382. trackedref *ref;
  2383. assert(owner);
  2384. if (owner == UPB_UNTRACKED_REF) return;
  2385. upb_lock();
  2386. found = upb_inttable_lookupptr(r->refs, owner, &v);
  2387. /* This assert will fail if an owner attempts to release a ref it didn't have. */
  2388. UPB_ASSERT_VAR(found, found);
  2389. ref = upb_value_getptr(v);
  2390. assert(ref->is_ref2 == ref2);
  2391. if (--ref->count == 0) {
  2392. free(ref);
  2393. upb_inttable_removeptr(r->refs, owner, NULL);
  2394. if (ref2) {
  2395. /* We know this cast is safe when it is a ref2, because it's coming from
  2396. * another refcounted object. */
  2397. const upb_refcounted *from = owner;
  2398. bool removed = upb_inttable_removeptr(from->ref2s, r, NULL);
  2399. assert(removed);
  2400. }
  2401. }
  2402. upb_unlock();
  2403. }
  2404. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  2405. upb_value v;
  2406. bool found;
  2407. trackedref *ref;
  2408. upb_lock();
  2409. found = upb_inttable_lookupptr(r->refs, owner, &v);
  2410. UPB_ASSERT_VAR(found, found);
  2411. ref = upb_value_getptr(v);
  2412. assert(ref->is_ref2 == ref2);
  2413. upb_unlock();
  2414. }
  2415. /* Populates the given UPB_CTYPE_INT32 inttable with counts of ref2's that
  2416. * originate from the given owner. */
  2417. static void getref2s(const upb_refcounted *owner, upb_inttable *tab) {
  2418. upb_inttable_iter i;
  2419. upb_lock();
  2420. upb_inttable_begin(&i, owner->ref2s);
  2421. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  2422. upb_value v;
  2423. upb_value count;
  2424. trackedref *ref;
  2425. bool ok;
  2426. bool found;
  2427. upb_refcounted *to = (upb_refcounted*)upb_inttable_iter_key(&i);
  2428. /* To get the count we need to look in the target's table. */
  2429. found = upb_inttable_lookupptr(to->refs, owner, &v);
  2430. assert(found);
  2431. ref = upb_value_getptr(v);
  2432. count = upb_value_int32(ref->count);
  2433. ok = upb_inttable_insertptr(tab, to, count);
  2434. CHECK_OOM(ok);
  2435. }
  2436. upb_unlock();
  2437. }
  2438. typedef struct {
  2439. upb_inttable ref2;
  2440. const upb_refcounted *obj;
  2441. } check_state;
  2442. static void visit_check(const upb_refcounted *obj, const upb_refcounted *subobj,
  2443. void *closure) {
  2444. check_state *s = closure;
  2445. upb_inttable *ref2 = &s->ref2;
  2446. upb_value v;
  2447. bool removed;
  2448. int32_t newcount;
  2449. assert(obj == s->obj);
  2450. assert(subobj);
  2451. removed = upb_inttable_removeptr(ref2, subobj, &v);
  2452. /* The following assertion will fail if the visit() function visits a subobj
  2453. * that it did not have a ref2 on, or visits the same subobj too many times. */
  2454. assert(removed);
  2455. newcount = upb_value_getint32(v) - 1;
  2456. if (newcount > 0) {
  2457. upb_inttable_insert(ref2, (uintptr_t)subobj, upb_value_int32(newcount));
  2458. }
  2459. }
  2460. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  2461. void *closure) {
  2462. bool ok;
  2463. /* In DEBUG_REFS mode we know what existing ref2 refs there are, so we know
  2464. * exactly the set of nodes that visit() should visit. So we verify visit()'s
  2465. * correctness here. */
  2466. check_state state;
  2467. state.obj = r;
  2468. ok = upb_inttable_init(&state.ref2, UPB_CTYPE_INT32);
  2469. CHECK_OOM(ok);
  2470. getref2s(r, &state.ref2);
  2471. /* This should visit any children in the ref2 table. */
  2472. if (r->vtbl->visit) r->vtbl->visit(r, visit_check, &state);
  2473. /* This assertion will fail if the visit() function missed any children. */
  2474. assert(upb_inttable_count(&state.ref2) == 0);
  2475. upb_inttable_uninit(&state.ref2);
  2476. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  2477. }
  2478. static bool trackinit(upb_refcounted *r) {
  2479. r->refs = malloc(sizeof(*r->refs));
  2480. r->ref2s = malloc(sizeof(*r->ref2s));
  2481. if (!r->refs || !r->ref2s) goto err1;
  2482. if (!upb_inttable_init(r->refs, UPB_CTYPE_PTR)) goto err1;
  2483. if (!upb_inttable_init(r->ref2s, UPB_CTYPE_PTR)) goto err2;
  2484. return true;
  2485. err2:
  2486. upb_inttable_uninit(r->refs);
  2487. err1:
  2488. free(r->refs);
  2489. free(r->ref2s);
  2490. return false;
  2491. }
  2492. static void trackfree(const upb_refcounted *r) {
  2493. upb_inttable_uninit(r->refs);
  2494. upb_inttable_uninit(r->ref2s);
  2495. free(r->refs);
  2496. free(r->ref2s);
  2497. }
  2498. #else
  2499. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  2500. UPB_UNUSED(r);
  2501. UPB_UNUSED(owner);
  2502. UPB_UNUSED(ref2);
  2503. }
  2504. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  2505. UPB_UNUSED(r);
  2506. UPB_UNUSED(owner);
  2507. UPB_UNUSED(ref2);
  2508. }
  2509. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  2510. UPB_UNUSED(r);
  2511. UPB_UNUSED(owner);
  2512. UPB_UNUSED(ref2);
  2513. }
  2514. static bool trackinit(upb_refcounted *r) {
  2515. UPB_UNUSED(r);
  2516. return true;
  2517. }
  2518. static void trackfree(const upb_refcounted *r) {
  2519. UPB_UNUSED(r);
  2520. }
  2521. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  2522. void *closure) {
  2523. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  2524. }
  2525. #endif /* UPB_DEBUG_REFS */
  2526. /* freeze() *******************************************************************/
  2527. /* The freeze() operation is by far the most complicated part of this scheme.
  2528. * We compute strongly-connected components and then mutate the graph such that
  2529. * we preserve the invariants documented at the top of this file. And we must
  2530. * handle out-of-memory errors gracefully (without leaving the graph
  2531. * inconsistent), which adds to the fun. */
  2532. /* The state used by the freeze operation (shared across many functions). */
  2533. typedef struct {
  2534. int depth;
  2535. int maxdepth;
  2536. uint64_t index;
  2537. /* Maps upb_refcounted* -> attributes (color, etc). attr layout varies by
  2538. * color. */
  2539. upb_inttable objattr;
  2540. upb_inttable stack; /* stack of upb_refcounted* for Tarjan's algorithm. */
  2541. upb_inttable groups; /* array of uint32_t*, malloc'd refcounts for new groups */
  2542. upb_status *status;
  2543. jmp_buf err;
  2544. } tarjan;
  2545. static void release_ref2(const upb_refcounted *obj,
  2546. const upb_refcounted *subobj,
  2547. void *closure);
  2548. /* Node attributes -----------------------------------------------------------*/
  2549. /* After our analysis phase all nodes will be either GRAY or WHITE. */
  2550. typedef enum {
  2551. BLACK = 0, /* Object has not been seen. */
  2552. GRAY, /* Object has been found via a refgroup but may not be reachable. */
  2553. GREEN, /* Object is reachable and is currently on the Tarjan stack. */
  2554. WHITE /* Object is reachable and has been assigned a group (SCC). */
  2555. } color_t;
  2556. UPB_NORETURN static void err(tarjan *t) { longjmp(t->err, 1); }
  2557. UPB_NORETURN static void oom(tarjan *t) {
  2558. upb_status_seterrmsg(t->status, "out of memory");
  2559. err(t);
  2560. }
  2561. static uint64_t trygetattr(const tarjan *t, const upb_refcounted *r) {
  2562. upb_value v;
  2563. return upb_inttable_lookupptr(&t->objattr, r, &v) ?
  2564. upb_value_getuint64(v) : 0;
  2565. }
  2566. static uint64_t getattr(const tarjan *t, const upb_refcounted *r) {
  2567. upb_value v;
  2568. bool found = upb_inttable_lookupptr(&t->objattr, r, &v);
  2569. UPB_ASSERT_VAR(found, found);
  2570. return upb_value_getuint64(v);
  2571. }
  2572. static void setattr(tarjan *t, const upb_refcounted *r, uint64_t attr) {
  2573. upb_inttable_removeptr(&t->objattr, r, NULL);
  2574. upb_inttable_insertptr(&t->objattr, r, upb_value_uint64(attr));
  2575. }
  2576. static color_t color(tarjan *t, const upb_refcounted *r) {
  2577. return trygetattr(t, r) & 0x3; /* Color is always stored in the low 2 bits. */
  2578. }
  2579. static void set_gray(tarjan *t, const upb_refcounted *r) {
  2580. assert(color(t, r) == BLACK);
  2581. setattr(t, r, GRAY);
  2582. }
  2583. /* Pushes an obj onto the Tarjan stack and sets it to GREEN. */
  2584. static void push(tarjan *t, const upb_refcounted *r) {
  2585. assert(color(t, r) == BLACK || color(t, r) == GRAY);
  2586. /* This defines the attr layout for the GREEN state. "index" and "lowlink"
  2587. * get 31 bits, which is plenty (limit of 2B objects frozen at a time). */
  2588. setattr(t, r, GREEN | (t->index << 2) | (t->index << 33));
  2589. if (++t->index == 0x80000000) {
  2590. upb_status_seterrmsg(t->status, "too many objects to freeze");
  2591. err(t);
  2592. }
  2593. upb_inttable_push(&t->stack, upb_value_ptr((void*)r));
  2594. }
  2595. /* Pops an obj from the Tarjan stack and sets it to WHITE, with a ptr to its
  2596. * SCC group. */
  2597. static upb_refcounted *pop(tarjan *t) {
  2598. upb_refcounted *r = upb_value_getptr(upb_inttable_pop(&t->stack));
  2599. assert(color(t, r) == GREEN);
  2600. /* This defines the attr layout for nodes in the WHITE state.
  2601. * Top of group stack is [group, NULL]; we point at group. */
  2602. setattr(t, r, WHITE | (upb_inttable_count(&t->groups) - 2) << 8);
  2603. return r;
  2604. }
  2605. static void tarjan_newgroup(tarjan *t) {
  2606. uint32_t *group = malloc(sizeof(*group));
  2607. if (!group) oom(t);
  2608. /* Push group and empty group leader (we'll fill in leader later). */
  2609. if (!upb_inttable_push(&t->groups, upb_value_ptr(group)) ||
  2610. !upb_inttable_push(&t->groups, upb_value_ptr(NULL))) {
  2611. free(group);
  2612. oom(t);
  2613. }
  2614. *group = 0;
  2615. }
  2616. static uint32_t idx(tarjan *t, const upb_refcounted *r) {
  2617. assert(color(t, r) == GREEN);
  2618. return (getattr(t, r) >> 2) & 0x7FFFFFFF;
  2619. }
  2620. static uint32_t lowlink(tarjan *t, const upb_refcounted *r) {
  2621. if (color(t, r) == GREEN) {
  2622. return getattr(t, r) >> 33;
  2623. } else {
  2624. return UINT32_MAX;
  2625. }
  2626. }
  2627. static void set_lowlink(tarjan *t, const upb_refcounted *r, uint32_t lowlink) {
  2628. assert(color(t, r) == GREEN);
  2629. setattr(t, r, ((uint64_t)lowlink << 33) | (getattr(t, r) & 0x1FFFFFFFF));
  2630. }
  2631. static uint32_t *group(tarjan *t, upb_refcounted *r) {
  2632. uint64_t groupnum;
  2633. upb_value v;
  2634. bool found;
  2635. assert(color(t, r) == WHITE);
  2636. groupnum = getattr(t, r) >> 8;
  2637. found = upb_inttable_lookup(&t->groups, groupnum, &v);
  2638. UPB_ASSERT_VAR(found, found);
  2639. return upb_value_getptr(v);
  2640. }
  2641. /* If the group leader for this object's group has not previously been set,
  2642. * the given object is assigned to be its leader. */
  2643. static upb_refcounted *groupleader(tarjan *t, upb_refcounted *r) {
  2644. uint64_t leader_slot;
  2645. upb_value v;
  2646. bool found;
  2647. assert(color(t, r) == WHITE);
  2648. leader_slot = (getattr(t, r) >> 8) + 1;
  2649. found = upb_inttable_lookup(&t->groups, leader_slot, &v);
  2650. UPB_ASSERT_VAR(found, found);
  2651. if (upb_value_getptr(v)) {
  2652. return upb_value_getptr(v);
  2653. } else {
  2654. upb_inttable_remove(&t->groups, leader_slot, NULL);
  2655. upb_inttable_insert(&t->groups, leader_slot, upb_value_ptr(r));
  2656. return r;
  2657. }
  2658. }
  2659. /* Tarjan's algorithm --------------------------------------------------------*/
  2660. /* See:
  2661. * http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm */
  2662. static void do_tarjan(const upb_refcounted *obj, tarjan *t);
  2663. static void tarjan_visit(const upb_refcounted *obj,
  2664. const upb_refcounted *subobj,
  2665. void *closure) {
  2666. tarjan *t = closure;
  2667. if (++t->depth > t->maxdepth) {
  2668. upb_status_seterrf(t->status, "graph too deep to freeze (%d)", t->maxdepth);
  2669. err(t);
  2670. } else if (subobj->is_frozen || color(t, subobj) == WHITE) {
  2671. /* Do nothing: we don't want to visit or color already-frozen nodes,
  2672. * and WHITE nodes have already been assigned a SCC. */
  2673. } else if (color(t, subobj) < GREEN) {
  2674. /* Subdef has not yet been visited; recurse on it. */
  2675. do_tarjan(subobj, t);
  2676. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), lowlink(t, subobj)));
  2677. } else if (color(t, subobj) == GREEN) {
  2678. /* Subdef is in the stack and hence in the current SCC. */
  2679. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), idx(t, subobj)));
  2680. }
  2681. --t->depth;
  2682. }
  2683. static void do_tarjan(const upb_refcounted *obj, tarjan *t) {
  2684. if (color(t, obj) == BLACK) {
  2685. /* We haven't seen this object's group; mark the whole group GRAY. */
  2686. const upb_refcounted *o = obj;
  2687. do { set_gray(t, o); } while ((o = o->next) != obj);
  2688. }
  2689. push(t, obj);
  2690. visit(obj, tarjan_visit, t);
  2691. if (lowlink(t, obj) == idx(t, obj)) {
  2692. tarjan_newgroup(t);
  2693. while (pop(t) != obj)
  2694. ;
  2695. }
  2696. }
  2697. /* freeze() ------------------------------------------------------------------*/
  2698. static void crossref(const upb_refcounted *r, const upb_refcounted *subobj,
  2699. void *_t) {
  2700. tarjan *t = _t;
  2701. assert(color(t, r) > BLACK);
  2702. if (color(t, subobj) > BLACK && r->group != subobj->group) {
  2703. /* Previously this ref was not reflected in subobj->group because they
  2704. * were in the same group; now that they are split a ref must be taken. */
  2705. refgroup(subobj->group);
  2706. }
  2707. }
  2708. static bool freeze(upb_refcounted *const*roots, int n, upb_status *s,
  2709. int maxdepth) {
  2710. volatile bool ret = false;
  2711. int i;
  2712. upb_inttable_iter iter;
  2713. /* We run in two passes so that we can allocate all memory before performing
  2714. * any mutation of the input -- this allows us to leave the input unchanged
  2715. * in the case of memory allocation failure. */
  2716. tarjan t;
  2717. t.index = 0;
  2718. t.depth = 0;
  2719. t.maxdepth = maxdepth;
  2720. t.status = s;
  2721. if (!upb_inttable_init(&t.objattr, UPB_CTYPE_UINT64)) goto err1;
  2722. if (!upb_inttable_init(&t.stack, UPB_CTYPE_PTR)) goto err2;
  2723. if (!upb_inttable_init(&t.groups, UPB_CTYPE_PTR)) goto err3;
  2724. if (setjmp(t.err) != 0) goto err4;
  2725. for (i = 0; i < n; i++) {
  2726. if (color(&t, roots[i]) < GREEN) {
  2727. do_tarjan(roots[i], &t);
  2728. }
  2729. }
  2730. /* If we've made it this far, no further errors are possible so it's safe to
  2731. * mutate the objects without risk of leaving them in an inconsistent state. */
  2732. ret = true;
  2733. /* The transformation that follows requires care. The preconditions are:
  2734. * - all objects in attr map are WHITE or GRAY, and are in mutable groups
  2735. * (groups of all mutable objs)
  2736. * - no ref2(to, from) refs have incremented count(to) if both "to" and
  2737. * "from" are in our attr map (this follows from invariants (2) and (3)) */
  2738. /* Pass 1: we remove WHITE objects from their mutable groups, and add them to
  2739. * new groups according to the SCC's we computed. These new groups will
  2740. * consist of only frozen objects. None will be immediately collectible,
  2741. * because WHITE objects are by definition reachable from one of "roots",
  2742. * which the caller must own refs on. */
  2743. upb_inttable_begin(&iter, &t.objattr);
  2744. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  2745. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  2746. /* Since removal from a singly-linked list requires access to the object's
  2747. * predecessor, we consider obj->next instead of obj for moving. With the
  2748. * while() loop we guarantee that we will visit every node's predecessor.
  2749. * Proof:
  2750. * 1. every node's predecessor is in our attr map.
  2751. * 2. though the loop body may change a node's predecessor, it will only
  2752. * change it to be the node we are currently operating on, so with a
  2753. * while() loop we guarantee ourselves the chance to remove each node. */
  2754. while (color(&t, obj->next) == WHITE &&
  2755. group(&t, obj->next) != obj->next->group) {
  2756. upb_refcounted *leader;
  2757. /* Remove from old group. */
  2758. upb_refcounted *move = obj->next;
  2759. if (obj == move) {
  2760. /* Removing the last object from a group. */
  2761. assert(*obj->group == obj->individual_count);
  2762. free(obj->group);
  2763. } else {
  2764. obj->next = move->next;
  2765. /* This may decrease to zero; we'll collect GRAY objects (if any) that
  2766. * remain in the group in the third pass. */
  2767. assert(*move->group >= move->individual_count);
  2768. *move->group -= move->individual_count;
  2769. }
  2770. /* Add to new group. */
  2771. leader = groupleader(&t, move);
  2772. if (move == leader) {
  2773. /* First object added to new group is its leader. */
  2774. move->group = group(&t, move);
  2775. move->next = move;
  2776. *move->group = move->individual_count;
  2777. } else {
  2778. /* Group already has at least one object in it. */
  2779. assert(leader->group == group(&t, move));
  2780. move->group = group(&t, move);
  2781. move->next = leader->next;
  2782. leader->next = move;
  2783. *move->group += move->individual_count;
  2784. }
  2785. move->is_frozen = true;
  2786. }
  2787. }
  2788. /* Pass 2: GRAY and WHITE objects "obj" with ref2(to, obj) references must
  2789. * increment count(to) if group(obj) != group(to) (which could now be the
  2790. * case if "to" was just frozen). */
  2791. upb_inttable_begin(&iter, &t.objattr);
  2792. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  2793. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  2794. visit(obj, crossref, &t);
  2795. }
  2796. /* Pass 3: GRAY objects are collected if their group's refcount dropped to
  2797. * zero when we removed its white nodes. This can happen if they had only
  2798. * been kept alive by virtue of sharing a group with an object that was just
  2799. * frozen.
  2800. *
  2801. * It is important that we do this last, since the GRAY object's free()
  2802. * function could call unref2() on just-frozen objects, which will decrement
  2803. * refs that were added in pass 2. */
  2804. upb_inttable_begin(&iter, &t.objattr);
  2805. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  2806. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  2807. if (obj->group == NULL || *obj->group == 0) {
  2808. if (obj->group) {
  2809. upb_refcounted *o;
  2810. /* We eagerly free() the group's count (since we can't easily determine
  2811. * the group's remaining size it's the easiest way to ensure it gets
  2812. * done). */
  2813. free(obj->group);
  2814. /* Visit to release ref2's (done in a separate pass since release_ref2
  2815. * depends on o->group being unmodified so it can test merged()). */
  2816. o = obj;
  2817. do { visit(o, release_ref2, NULL); } while ((o = o->next) != obj);
  2818. /* Mark "group" fields as NULL so we know to free the objects later in
  2819. * this loop, but also don't try to delete the group twice. */
  2820. o = obj;
  2821. do { o->group = NULL; } while ((o = o->next) != obj);
  2822. }
  2823. freeobj(obj);
  2824. }
  2825. }
  2826. err4:
  2827. if (!ret) {
  2828. upb_inttable_begin(&iter, &t.groups);
  2829. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter))
  2830. free(upb_value_getptr(upb_inttable_iter_value(&iter)));
  2831. }
  2832. upb_inttable_uninit(&t.groups);
  2833. err3:
  2834. upb_inttable_uninit(&t.stack);
  2835. err2:
  2836. upb_inttable_uninit(&t.objattr);
  2837. err1:
  2838. return ret;
  2839. }
  2840. /* Misc internal functions ***************************************************/
  2841. static bool merged(const upb_refcounted *r, const upb_refcounted *r2) {
  2842. return r->group == r2->group;
  2843. }
  2844. static void merge(upb_refcounted *r, upb_refcounted *from) {
  2845. upb_refcounted *base;
  2846. upb_refcounted *tmp;
  2847. if (merged(r, from)) return;
  2848. *r->group += *from->group;
  2849. free(from->group);
  2850. base = from;
  2851. /* Set all refcount pointers in the "from" chain to the merged refcount.
  2852. *
  2853. * TODO(haberman): this linear algorithm can result in an overall O(n^2) bound
  2854. * if the user continuously extends a group by one object. Prevent this by
  2855. * using one of the techniques in this paper:
  2856. * ftp://www.ncedc.org/outgoing/geomorph/dino/orals/p245-tarjan.pdf */
  2857. do { from->group = r->group; } while ((from = from->next) != base);
  2858. /* Merge the two circularly linked lists by swapping their next pointers. */
  2859. tmp = r->next;
  2860. r->next = base->next;
  2861. base->next = tmp;
  2862. }
  2863. static void unref(const upb_refcounted *r);
  2864. static void release_ref2(const upb_refcounted *obj,
  2865. const upb_refcounted *subobj,
  2866. void *closure) {
  2867. UPB_UNUSED(closure);
  2868. untrack(subobj, obj, true);
  2869. if (!merged(obj, subobj)) {
  2870. assert(subobj->is_frozen);
  2871. unref(subobj);
  2872. }
  2873. }
  2874. static void unref(const upb_refcounted *r) {
  2875. if (unrefgroup(r->group)) {
  2876. const upb_refcounted *o;
  2877. free(r->group);
  2878. /* In two passes, since release_ref2 needs a guarantee that any subobjs
  2879. * are alive. */
  2880. o = r;
  2881. do { visit(o, release_ref2, NULL); } while((o = o->next) != r);
  2882. o = r;
  2883. do {
  2884. const upb_refcounted *next = o->next;
  2885. assert(o->is_frozen || o->individual_count == 0);
  2886. freeobj((upb_refcounted*)o);
  2887. o = next;
  2888. } while(o != r);
  2889. }
  2890. }
  2891. static void freeobj(upb_refcounted *o) {
  2892. trackfree(o);
  2893. o->vtbl->free((upb_refcounted*)o);
  2894. }
  2895. /* Public interface ***********************************************************/
  2896. bool upb_refcounted_init(upb_refcounted *r,
  2897. const struct upb_refcounted_vtbl *vtbl,
  2898. const void *owner) {
  2899. #ifndef NDEBUG
  2900. /* Endianness check. This is unrelated to upb_refcounted, it's just a
  2901. * convenient place to put the check that we can be assured will run for
  2902. * basically every program using upb. */
  2903. const int x = 1;
  2904. #ifdef UPB_BIG_ENDIAN
  2905. assert(*(char*)&x != 1);
  2906. #else
  2907. assert(*(char*)&x == 1);
  2908. #endif
  2909. #endif
  2910. r->next = r;
  2911. r->vtbl = vtbl;
  2912. r->individual_count = 0;
  2913. r->is_frozen = false;
  2914. r->group = malloc(sizeof(*r->group));
  2915. if (!r->group) return false;
  2916. *r->group = 0;
  2917. if (!trackinit(r)) {
  2918. free(r->group);
  2919. return false;
  2920. }
  2921. upb_refcounted_ref(r, owner);
  2922. return true;
  2923. }
  2924. bool upb_refcounted_isfrozen(const upb_refcounted *r) {
  2925. return r->is_frozen;
  2926. }
  2927. void upb_refcounted_ref(const upb_refcounted *r, const void *owner) {
  2928. track(r, owner, false);
  2929. if (!r->is_frozen)
  2930. ((upb_refcounted*)r)->individual_count++;
  2931. refgroup(r->group);
  2932. }
  2933. void upb_refcounted_unref(const upb_refcounted *r, const void *owner) {
  2934. untrack(r, owner, false);
  2935. if (!r->is_frozen)
  2936. ((upb_refcounted*)r)->individual_count--;
  2937. unref(r);
  2938. }
  2939. void upb_refcounted_ref2(const upb_refcounted *r, upb_refcounted *from) {
  2940. assert(!from->is_frozen); /* Non-const pointer implies this. */
  2941. track(r, from, true);
  2942. if (r->is_frozen) {
  2943. refgroup(r->group);
  2944. } else {
  2945. merge((upb_refcounted*)r, from);
  2946. }
  2947. }
  2948. void upb_refcounted_unref2(const upb_refcounted *r, upb_refcounted *from) {
  2949. assert(!from->is_frozen); /* Non-const pointer implies this. */
  2950. untrack(r, from, true);
  2951. if (r->is_frozen) {
  2952. unref(r);
  2953. } else {
  2954. assert(merged(r, from));
  2955. }
  2956. }
  2957. void upb_refcounted_donateref(
  2958. const upb_refcounted *r, const void *from, const void *to) {
  2959. assert(from != to);
  2960. if (to != NULL)
  2961. upb_refcounted_ref(r, to);
  2962. if (from != NULL)
  2963. upb_refcounted_unref(r, from);
  2964. }
  2965. void upb_refcounted_checkref(const upb_refcounted *r, const void *owner) {
  2966. checkref(r, owner, false);
  2967. }
  2968. bool upb_refcounted_freeze(upb_refcounted *const*roots, int n, upb_status *s,
  2969. int maxdepth) {
  2970. int i;
  2971. for (i = 0; i < n; i++) {
  2972. assert(!roots[i]->is_frozen);
  2973. }
  2974. return freeze(roots, n, s, maxdepth);
  2975. }
  2976. #include <stdlib.h>
  2977. /* Fallback implementation if the shim is not specialized by the JIT. */
  2978. #define SHIM_WRITER(type, ctype) \
  2979. bool upb_shim_set ## type (void *c, const void *hd, ctype val) { \
  2980. uint8_t *m = c; \
  2981. const upb_shim_data *d = hd; \
  2982. if (d->hasbit > 0) \
  2983. *(uint8_t*)&m[d->hasbit / 8] |= 1 << (d->hasbit % 8); \
  2984. *(ctype*)&m[d->offset] = val; \
  2985. return true; \
  2986. } \
  2987. SHIM_WRITER(double, double)
  2988. SHIM_WRITER(float, float)
  2989. SHIM_WRITER(int32, int32_t)
  2990. SHIM_WRITER(int64, int64_t)
  2991. SHIM_WRITER(uint32, uint32_t)
  2992. SHIM_WRITER(uint64, uint64_t)
  2993. SHIM_WRITER(bool, bool)
  2994. #undef SHIM_WRITER
  2995. bool upb_shim_set(upb_handlers *h, const upb_fielddef *f, size_t offset,
  2996. int32_t hasbit) {
  2997. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  2998. bool ok;
  2999. upb_shim_data *d = malloc(sizeof(*d));
  3000. if (!d) return false;
  3001. d->offset = offset;
  3002. d->hasbit = hasbit;
  3003. upb_handlerattr_sethandlerdata(&attr, d);
  3004. upb_handlerattr_setalwaysok(&attr, true);
  3005. upb_handlers_addcleanup(h, d, free);
  3006. #define TYPE(u, l) \
  3007. case UPB_TYPE_##u: \
  3008. ok = upb_handlers_set##l(h, f, upb_shim_set##l, &attr); break;
  3009. ok = false;
  3010. switch (upb_fielddef_type(f)) {
  3011. TYPE(INT64, int64);
  3012. TYPE(INT32, int32);
  3013. TYPE(ENUM, int32);
  3014. TYPE(UINT64, uint64);
  3015. TYPE(UINT32, uint32);
  3016. TYPE(DOUBLE, double);
  3017. TYPE(FLOAT, float);
  3018. TYPE(BOOL, bool);
  3019. default: assert(false); break;
  3020. }
  3021. #undef TYPE
  3022. upb_handlerattr_uninit(&attr);
  3023. return ok;
  3024. }
  3025. const upb_shim_data *upb_shim_getdata(const upb_handlers *h, upb_selector_t s,
  3026. upb_fieldtype_t *type) {
  3027. upb_func *f = upb_handlers_gethandler(h, s);
  3028. if ((upb_int64_handlerfunc*)f == upb_shim_setint64) {
  3029. *type = UPB_TYPE_INT64;
  3030. } else if ((upb_int32_handlerfunc*)f == upb_shim_setint32) {
  3031. *type = UPB_TYPE_INT32;
  3032. } else if ((upb_uint64_handlerfunc*)f == upb_shim_setuint64) {
  3033. *type = UPB_TYPE_UINT64;
  3034. } else if ((upb_uint32_handlerfunc*)f == upb_shim_setuint32) {
  3035. *type = UPB_TYPE_UINT32;
  3036. } else if ((upb_double_handlerfunc*)f == upb_shim_setdouble) {
  3037. *type = UPB_TYPE_DOUBLE;
  3038. } else if ((upb_float_handlerfunc*)f == upb_shim_setfloat) {
  3039. *type = UPB_TYPE_FLOAT;
  3040. } else if ((upb_bool_handlerfunc*)f == upb_shim_setbool) {
  3041. *type = UPB_TYPE_BOOL;
  3042. } else {
  3043. return NULL;
  3044. }
  3045. return (const upb_shim_data*)upb_handlers_gethandlerdata(h, s);
  3046. }
  3047. #include <stdlib.h>
  3048. #include <string.h>
  3049. static void upb_symtab_free(upb_refcounted *r) {
  3050. upb_symtab *s = (upb_symtab*)r;
  3051. upb_strtable_iter i;
  3052. upb_strtable_begin(&i, &s->symtab);
  3053. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  3054. const upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  3055. upb_def_unref(def, s);
  3056. }
  3057. upb_strtable_uninit(&s->symtab);
  3058. free(s);
  3059. }
  3060. upb_symtab *upb_symtab_new(const void *owner) {
  3061. static const struct upb_refcounted_vtbl vtbl = {NULL, &upb_symtab_free};
  3062. upb_symtab *s = malloc(sizeof(*s));
  3063. upb_refcounted_init(upb_symtab_upcast_mutable(s), &vtbl, owner);
  3064. upb_strtable_init(&s->symtab, UPB_CTYPE_PTR);
  3065. return s;
  3066. }
  3067. void upb_symtab_freeze(upb_symtab *s) {
  3068. upb_refcounted *r;
  3069. bool ok;
  3070. assert(!upb_symtab_isfrozen(s));
  3071. r = upb_symtab_upcast_mutable(s);
  3072. /* The symtab does not take ref2's (see refcounted.h) on the defs, because
  3073. * defs cannot refer back to the table and therefore cannot create cycles. So
  3074. * 0 will suffice for maxdepth here. */
  3075. ok = upb_refcounted_freeze(&r, 1, NULL, 0);
  3076. UPB_ASSERT_VAR(ok, ok);
  3077. }
  3078. const upb_def *upb_symtab_lookup(const upb_symtab *s, const char *sym) {
  3079. upb_value v;
  3080. upb_def *ret = upb_strtable_lookup(&s->symtab, sym, &v) ?
  3081. upb_value_getptr(v) : NULL;
  3082. return ret;
  3083. }
  3084. const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym) {
  3085. upb_value v;
  3086. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  3087. upb_value_getptr(v) : NULL;
  3088. return def ? upb_dyncast_msgdef(def) : NULL;
  3089. }
  3090. const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym) {
  3091. upb_value v;
  3092. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  3093. upb_value_getptr(v) : NULL;
  3094. return def ? upb_dyncast_enumdef(def) : NULL;
  3095. }
  3096. /* Given a symbol and the base symbol inside which it is defined, find the
  3097. * symbol's definition in t. */
  3098. static upb_def *upb_resolvename(const upb_strtable *t,
  3099. const char *base, const char *sym) {
  3100. if(strlen(sym) == 0) return NULL;
  3101. if(sym[0] == '.') {
  3102. /* Symbols starting with '.' are absolute, so we do a single lookup.
  3103. * Slice to omit the leading '.' */
  3104. upb_value v;
  3105. return upb_strtable_lookup(t, sym + 1, &v) ? upb_value_getptr(v) : NULL;
  3106. } else {
  3107. /* Remove components from base until we find an entry or run out.
  3108. * TODO: This branch is totally broken, but currently not used. */
  3109. (void)base;
  3110. assert(false);
  3111. return NULL;
  3112. }
  3113. }
  3114. const upb_def *upb_symtab_resolve(const upb_symtab *s, const char *base,
  3115. const char *sym) {
  3116. upb_def *ret = upb_resolvename(&s->symtab, base, sym);
  3117. return ret;
  3118. }
  3119. /* Starts a depth-first traversal at "def", recursing into any subdefs
  3120. * (ie. submessage types). Adds duplicates of existing defs to addtab
  3121. * wherever necessary, so that the resulting symtab will be consistent once
  3122. * addtab is added.
  3123. *
  3124. * More specifically, if any def D is found in the DFS that:
  3125. *
  3126. * 1. can reach a def that is being replaced by something in addtab, AND
  3127. *
  3128. * 2. is not itself being replaced already (ie. this name doesn't already
  3129. * exist in addtab)
  3130. *
  3131. * ...then a duplicate (new copy) of D will be added to addtab.
  3132. *
  3133. * Returns true if this happened for any def reachable from "def."
  3134. *
  3135. * It is slightly tricky to do this correctly in the presence of cycles. If we
  3136. * detect that our DFS has hit a cycle, we might not yet know if any SCCs on
  3137. * our stack can reach a def in addtab or not. Once we figure this out, that
  3138. * answer needs to apply to *all* defs in these SCCs, even if we visited them
  3139. * already. So a straight up one-pass cycle-detecting DFS won't work.
  3140. *
  3141. * To work around this problem, we traverse each SCC (which we already
  3142. * computed, since these defs are frozen) as a single node. We first compute
  3143. * whether the SCC as a whole can reach any def in addtab, then we dup (or not)
  3144. * the entire SCC. This requires breaking the encapsulation of upb_refcounted,
  3145. * since that is where we get the data about what SCC we are in. */
  3146. static bool upb_resolve_dfs(const upb_def *def, upb_strtable *addtab,
  3147. const void *new_owner, upb_inttable *seen,
  3148. upb_status *s) {
  3149. upb_value v;
  3150. bool need_dup;
  3151. const upb_def *base;
  3152. const void* memoize_key;
  3153. /* Memoize results of this function for efficiency (since we're traversing a
  3154. * DAG this is not needed to limit the depth of the search).
  3155. *
  3156. * We memoize by SCC instead of by individual def. */
  3157. memoize_key = def->base.group;
  3158. if (upb_inttable_lookupptr(seen, memoize_key, &v))
  3159. return upb_value_getbool(v);
  3160. /* Visit submessages for all messages in the SCC. */
  3161. need_dup = false;
  3162. base = def;
  3163. do {
  3164. upb_value v;
  3165. const upb_msgdef *m;
  3166. assert(upb_def_isfrozen(def));
  3167. if (def->type == UPB_DEF_FIELD) continue;
  3168. if (upb_strtable_lookup(addtab, upb_def_fullname(def), &v)) {
  3169. need_dup = true;
  3170. }
  3171. /* For messages, continue the recursion by visiting all subdefs, but only
  3172. * ones in different SCCs. */
  3173. m = upb_dyncast_msgdef(def);
  3174. if (m) {
  3175. upb_msg_field_iter i;
  3176. for(upb_msg_field_begin(&i, m);
  3177. !upb_msg_field_done(&i);
  3178. upb_msg_field_next(&i)) {
  3179. upb_fielddef *f = upb_msg_iter_field(&i);
  3180. const upb_def *subdef;
  3181. if (!upb_fielddef_hassubdef(f)) continue;
  3182. subdef = upb_fielddef_subdef(f);
  3183. /* Skip subdefs in this SCC. */
  3184. if (def->base.group == subdef->base.group) continue;
  3185. /* |= to avoid short-circuit; we need its side-effects. */
  3186. need_dup |= upb_resolve_dfs(subdef, addtab, new_owner, seen, s);
  3187. if (!upb_ok(s)) return false;
  3188. }
  3189. }
  3190. } while ((def = (upb_def*)def->base.next) != base);
  3191. if (need_dup) {
  3192. /* Dup all defs in this SCC that don't already have entries in addtab. */
  3193. def = base;
  3194. do {
  3195. const char *name;
  3196. if (def->type == UPB_DEF_FIELD) continue;
  3197. name = upb_def_fullname(def);
  3198. if (!upb_strtable_lookup(addtab, name, NULL)) {
  3199. upb_def *newdef = upb_def_dup(def, new_owner);
  3200. if (!newdef) goto oom;
  3201. newdef->came_from_user = false;
  3202. if (!upb_strtable_insert(addtab, name, upb_value_ptr(newdef)))
  3203. goto oom;
  3204. }
  3205. } while ((def = (upb_def*)def->base.next) != base);
  3206. }
  3207. upb_inttable_insertptr(seen, memoize_key, upb_value_bool(need_dup));
  3208. return need_dup;
  3209. oom:
  3210. upb_status_seterrmsg(s, "out of memory");
  3211. return false;
  3212. }
  3213. /* TODO(haberman): we need a lot more testing of error conditions.
  3214. * The came_from_user stuff in particular is not tested. */
  3215. bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, int n, void *ref_donor,
  3216. upb_status *status) {
  3217. int i;
  3218. upb_strtable_iter iter;
  3219. upb_def **add_defs = NULL;
  3220. upb_strtable addtab;
  3221. upb_inttable seen;
  3222. assert(!upb_symtab_isfrozen(s));
  3223. if (!upb_strtable_init(&addtab, UPB_CTYPE_PTR)) {
  3224. upb_status_seterrmsg(status, "out of memory");
  3225. return false;
  3226. }
  3227. /* Add new defs to our "add" set. */
  3228. for (i = 0; i < n; i++) {
  3229. upb_def *def = defs[i];
  3230. const char *fullname;
  3231. upb_fielddef *f;
  3232. if (upb_def_isfrozen(def)) {
  3233. upb_status_seterrmsg(status, "added defs must be mutable");
  3234. goto err;
  3235. }
  3236. assert(!upb_def_isfrozen(def));
  3237. fullname = upb_def_fullname(def);
  3238. if (!fullname) {
  3239. upb_status_seterrmsg(
  3240. status, "Anonymous defs cannot be added to a symtab");
  3241. goto err;
  3242. }
  3243. f = upb_dyncast_fielddef_mutable(def);
  3244. if (f) {
  3245. if (!upb_fielddef_containingtypename(f)) {
  3246. upb_status_seterrmsg(status,
  3247. "Standalone fielddefs must have a containing type "
  3248. "(extendee) name set");
  3249. goto err;
  3250. }
  3251. } else {
  3252. if (upb_strtable_lookup(&addtab, fullname, NULL)) {
  3253. upb_status_seterrf(status, "Conflicting defs named '%s'", fullname);
  3254. goto err;
  3255. }
  3256. /* We need this to back out properly, because if there is a failure we
  3257. * need to donate the ref back to the caller. */
  3258. def->came_from_user = true;
  3259. upb_def_donateref(def, ref_donor, s);
  3260. if (!upb_strtable_insert(&addtab, fullname, upb_value_ptr(def)))
  3261. goto oom_err;
  3262. }
  3263. }
  3264. /* Add standalone fielddefs (ie. extensions) to the appropriate messages.
  3265. * If the appropriate message only exists in the existing symtab, duplicate
  3266. * it so we have a mutable copy we can add the fields to. */
  3267. for (i = 0; i < n; i++) {
  3268. upb_def *def = defs[i];
  3269. upb_fielddef *f = upb_dyncast_fielddef_mutable(def);
  3270. const char *msgname;
  3271. upb_value v;
  3272. upb_msgdef *m;
  3273. if (!f) continue;
  3274. msgname = upb_fielddef_containingtypename(f);
  3275. /* We validated this earlier in this function. */
  3276. assert(msgname);
  3277. /* If the extendee name is absolutely qualified, move past the initial ".".
  3278. * TODO(haberman): it is not obvious what it would mean if this was not
  3279. * absolutely qualified. */
  3280. if (msgname[0] == '.') {
  3281. msgname++;
  3282. }
  3283. if (upb_strtable_lookup(&addtab, msgname, &v)) {
  3284. /* Extendee is in the set of defs the user asked us to add. */
  3285. m = upb_value_getptr(v);
  3286. } else {
  3287. /* Need to find and dup the extendee from the existing symtab. */
  3288. const upb_msgdef *frozen_m = upb_symtab_lookupmsg(s, msgname);
  3289. if (!frozen_m) {
  3290. upb_status_seterrf(status,
  3291. "Tried to extend message %s that does not exist "
  3292. "in this SymbolTable.",
  3293. msgname);
  3294. goto err;
  3295. }
  3296. m = upb_msgdef_dup(frozen_m, s);
  3297. if (!m) goto oom_err;
  3298. if (!upb_strtable_insert(&addtab, msgname, upb_value_ptr(m))) {
  3299. upb_msgdef_unref(m, s);
  3300. goto oom_err;
  3301. }
  3302. }
  3303. if (!upb_msgdef_addfield(m, f, ref_donor, status)) {
  3304. goto err;
  3305. }
  3306. }
  3307. /* Add dups of any existing def that can reach a def with the same name as
  3308. * anything in our "add" set. */
  3309. if (!upb_inttable_init(&seen, UPB_CTYPE_BOOL)) goto oom_err;
  3310. upb_strtable_begin(&iter, &s->symtab);
  3311. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  3312. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
  3313. upb_resolve_dfs(def, &addtab, s, &seen, status);
  3314. if (!upb_ok(status)) goto err;
  3315. }
  3316. upb_inttable_uninit(&seen);
  3317. /* Now using the table, resolve symbolic references for subdefs. */
  3318. upb_strtable_begin(&iter, &addtab);
  3319. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  3320. const char *base;
  3321. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
  3322. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  3323. upb_msg_field_iter j;
  3324. if (!m) continue;
  3325. /* Type names are resolved relative to the message in which they appear. */
  3326. base = upb_msgdef_fullname(m);
  3327. for(upb_msg_field_begin(&j, m);
  3328. !upb_msg_field_done(&j);
  3329. upb_msg_field_next(&j)) {
  3330. upb_fielddef *f = upb_msg_iter_field(&j);
  3331. const char *name = upb_fielddef_subdefname(f);
  3332. if (name && !upb_fielddef_subdef(f)) {
  3333. /* Try the lookup in the current set of to-be-added defs first. If not
  3334. * there, try existing defs. */
  3335. upb_def *subdef = upb_resolvename(&addtab, base, name);
  3336. if (subdef == NULL) {
  3337. subdef = upb_resolvename(&s->symtab, base, name);
  3338. }
  3339. if (subdef == NULL) {
  3340. upb_status_seterrf(
  3341. status, "couldn't resolve name '%s' in message '%s'", name, base);
  3342. goto err;
  3343. } else if (!upb_fielddef_setsubdef(f, subdef, status)) {
  3344. goto err;
  3345. }
  3346. }
  3347. }
  3348. }
  3349. /* We need an array of the defs in addtab, for passing to upb_def_freeze. */
  3350. add_defs = malloc(sizeof(void*) * upb_strtable_count(&addtab));
  3351. if (add_defs == NULL) goto oom_err;
  3352. upb_strtable_begin(&iter, &addtab);
  3353. for (n = 0; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  3354. add_defs[n++] = upb_value_getptr(upb_strtable_iter_value(&iter));
  3355. }
  3356. if (!upb_def_freeze(add_defs, n, status)) goto err;
  3357. /* This must be delayed until all errors have been detected, since error
  3358. * recovery code uses this table to cleanup defs. */
  3359. upb_strtable_uninit(&addtab);
  3360. /* TODO(haberman) we don't properly handle errors after this point (like
  3361. * OOM in upb_strtable_insert() below). */
  3362. for (i = 0; i < n; i++) {
  3363. upb_def *def = add_defs[i];
  3364. const char *name = upb_def_fullname(def);
  3365. upb_value v;
  3366. bool success;
  3367. if (upb_strtable_remove(&s->symtab, name, &v)) {
  3368. const upb_def *def = upb_value_getptr(v);
  3369. upb_def_unref(def, s);
  3370. }
  3371. success = upb_strtable_insert(&s->symtab, name, upb_value_ptr(def));
  3372. UPB_ASSERT_VAR(success, success == true);
  3373. }
  3374. free(add_defs);
  3375. return true;
  3376. oom_err:
  3377. upb_status_seterrmsg(status, "out of memory");
  3378. err: {
  3379. /* For defs the user passed in, we need to donate the refs back. For defs
  3380. * we dup'd, we need to just unref them. */
  3381. upb_strtable_begin(&iter, &addtab);
  3382. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  3383. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
  3384. bool came_from_user = def->came_from_user;
  3385. def->came_from_user = false;
  3386. if (came_from_user) {
  3387. upb_def_donateref(def, s, ref_donor);
  3388. } else {
  3389. upb_def_unref(def, s);
  3390. }
  3391. }
  3392. }
  3393. upb_strtable_uninit(&addtab);
  3394. free(add_defs);
  3395. assert(!upb_ok(status));
  3396. return false;
  3397. }
  3398. /* Iteration. */
  3399. static void advance_to_matching(upb_symtab_iter *iter) {
  3400. if (iter->type == UPB_DEF_ANY)
  3401. return;
  3402. while (!upb_strtable_done(&iter->iter) &&
  3403. iter->type != upb_symtab_iter_def(iter)->type) {
  3404. upb_strtable_next(&iter->iter);
  3405. }
  3406. }
  3407. void upb_symtab_begin(upb_symtab_iter *iter, const upb_symtab *s,
  3408. upb_deftype_t type) {
  3409. upb_strtable_begin(&iter->iter, &s->symtab);
  3410. iter->type = type;
  3411. advance_to_matching(iter);
  3412. }
  3413. void upb_symtab_next(upb_symtab_iter *iter) {
  3414. upb_strtable_next(&iter->iter);
  3415. advance_to_matching(iter);
  3416. }
  3417. bool upb_symtab_done(const upb_symtab_iter *iter) {
  3418. return upb_strtable_done(&iter->iter);
  3419. }
  3420. const upb_def *upb_symtab_iter_def(const upb_symtab_iter *iter) {
  3421. return upb_value_getptr(upb_strtable_iter_value(&iter->iter));
  3422. }
  3423. /*
  3424. ** upb_table Implementation
  3425. **
  3426. ** Implementation is heavily inspired by Lua's ltable.c.
  3427. */
  3428. #include <stdlib.h>
  3429. #include <string.h>
  3430. #define UPB_MAXARRSIZE 16 /* 64k. */
  3431. /* From Chromium. */
  3432. #define ARRAY_SIZE(x) \
  3433. ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
  3434. static const double MAX_LOAD = 0.85;
  3435. /* The minimum utilization of the array part of a mixed hash/array table. This
  3436. * is a speed/memory-usage tradeoff (though it's not straightforward because of
  3437. * cache effects). The lower this is, the more memory we'll use. */
  3438. static const double MIN_DENSITY = 0.1;
  3439. bool is_pow2(uint64_t v) { return v == 0 || (v & (v - 1)) == 0; }
  3440. int log2ceil(uint64_t v) {
  3441. int ret = 0;
  3442. bool pow2 = is_pow2(v);
  3443. while (v >>= 1) ret++;
  3444. ret = pow2 ? ret : ret + 1; /* Ceiling. */
  3445. return UPB_MIN(UPB_MAXARRSIZE, ret);
  3446. }
  3447. char *upb_strdup(const char *s) {
  3448. return upb_strdup2(s, strlen(s));
  3449. }
  3450. char *upb_strdup2(const char *s, size_t len) {
  3451. size_t n;
  3452. char *p;
  3453. /* Prevent overflow errors. */
  3454. if (len == SIZE_MAX) return NULL;
  3455. /* Always null-terminate, even if binary data; but don't rely on the input to
  3456. * have a null-terminating byte since it may be a raw binary buffer. */
  3457. n = len + 1;
  3458. p = malloc(n);
  3459. if (p) {
  3460. memcpy(p, s, len);
  3461. p[len] = 0;
  3462. }
  3463. return p;
  3464. }
  3465. /* A type to represent the lookup key of either a strtable or an inttable. */
  3466. typedef union {
  3467. uintptr_t num;
  3468. struct {
  3469. const char *str;
  3470. size_t len;
  3471. } str;
  3472. } lookupkey_t;
  3473. static lookupkey_t strkey2(const char *str, size_t len) {
  3474. lookupkey_t k;
  3475. k.str.str = str;
  3476. k.str.len = len;
  3477. return k;
  3478. }
  3479. static lookupkey_t intkey(uintptr_t key) {
  3480. lookupkey_t k;
  3481. k.num = key;
  3482. return k;
  3483. }
  3484. typedef uint32_t hashfunc_t(upb_tabkey key);
  3485. typedef bool eqlfunc_t(upb_tabkey k1, lookupkey_t k2);
  3486. /* Base table (shared code) ***************************************************/
  3487. /* For when we need to cast away const. */
  3488. static upb_tabent *mutable_entries(upb_table *t) {
  3489. return (upb_tabent*)t->entries;
  3490. }
  3491. static bool isfull(upb_table *t) {
  3492. return (double)(t->count + 1) / upb_table_size(t) > MAX_LOAD;
  3493. }
  3494. static bool init(upb_table *t, upb_ctype_t ctype, uint8_t size_lg2) {
  3495. size_t bytes;
  3496. t->count = 0;
  3497. t->ctype = ctype;
  3498. t->size_lg2 = size_lg2;
  3499. t->mask = upb_table_size(t) ? upb_table_size(t) - 1 : 0;
  3500. bytes = upb_table_size(t) * sizeof(upb_tabent);
  3501. if (bytes > 0) {
  3502. t->entries = malloc(bytes);
  3503. if (!t->entries) return false;
  3504. memset(mutable_entries(t), 0, bytes);
  3505. } else {
  3506. t->entries = NULL;
  3507. }
  3508. return true;
  3509. }
  3510. static void uninit(upb_table *t) { free(mutable_entries(t)); }
  3511. static upb_tabent *emptyent(upb_table *t) {
  3512. upb_tabent *e = mutable_entries(t) + upb_table_size(t);
  3513. while (1) { if (upb_tabent_isempty(--e)) return e; assert(e > t->entries); }
  3514. }
  3515. static upb_tabent *getentry_mutable(upb_table *t, uint32_t hash) {
  3516. return (upb_tabent*)upb_getentry(t, hash);
  3517. }
  3518. static const upb_tabent *findentry(const upb_table *t, lookupkey_t key,
  3519. uint32_t hash, eqlfunc_t *eql) {
  3520. const upb_tabent *e;
  3521. if (t->size_lg2 == 0) return NULL;
  3522. e = upb_getentry(t, hash);
  3523. if (upb_tabent_isempty(e)) return NULL;
  3524. while (1) {
  3525. if (eql(e->key, key)) return e;
  3526. if ((e = e->next) == NULL) return NULL;
  3527. }
  3528. }
  3529. static upb_tabent *findentry_mutable(upb_table *t, lookupkey_t key,
  3530. uint32_t hash, eqlfunc_t *eql) {
  3531. return (upb_tabent*)findentry(t, key, hash, eql);
  3532. }
  3533. static bool lookup(const upb_table *t, lookupkey_t key, upb_value *v,
  3534. uint32_t hash, eqlfunc_t *eql) {
  3535. const upb_tabent *e = findentry(t, key, hash, eql);
  3536. if (e) {
  3537. if (v) {
  3538. _upb_value_setval(v, e->val.val, t->ctype);
  3539. }
  3540. return true;
  3541. } else {
  3542. return false;
  3543. }
  3544. }
  3545. /* The given key must not already exist in the table. */
  3546. static void insert(upb_table *t, lookupkey_t key, upb_tabkey tabkey,
  3547. upb_value val, uint32_t hash,
  3548. hashfunc_t *hashfunc, eqlfunc_t *eql) {
  3549. upb_tabent *mainpos_e;
  3550. upb_tabent *our_e;
  3551. UPB_UNUSED(eql);
  3552. UPB_UNUSED(key);
  3553. assert(findentry(t, key, hash, eql) == NULL);
  3554. assert(val.ctype == t->ctype);
  3555. t->count++;
  3556. mainpos_e = getentry_mutable(t, hash);
  3557. our_e = mainpos_e;
  3558. if (upb_tabent_isempty(mainpos_e)) {
  3559. /* Our main position is empty; use it. */
  3560. our_e->next = NULL;
  3561. } else {
  3562. /* Collision. */
  3563. upb_tabent *new_e = emptyent(t);
  3564. /* Head of collider's chain. */
  3565. upb_tabent *chain = getentry_mutable(t, hashfunc(mainpos_e->key));
  3566. if (chain == mainpos_e) {
  3567. /* Existing ent is in its main posisiton (it has the same hash as us, and
  3568. * is the head of our chain). Insert to new ent and append to this chain. */
  3569. new_e->next = mainpos_e->next;
  3570. mainpos_e->next = new_e;
  3571. our_e = new_e;
  3572. } else {
  3573. /* Existing ent is not in its main position (it is a node in some other
  3574. * chain). This implies that no existing ent in the table has our hash.
  3575. * Evict it (updating its chain) and use its ent for head of our chain. */
  3576. *new_e = *mainpos_e; /* copies next. */
  3577. while (chain->next != mainpos_e) {
  3578. chain = (upb_tabent*)chain->next;
  3579. assert(chain);
  3580. }
  3581. chain->next = new_e;
  3582. our_e = mainpos_e;
  3583. our_e->next = NULL;
  3584. }
  3585. }
  3586. our_e->key = tabkey;
  3587. our_e->val.val = val.val;
  3588. assert(findentry(t, key, hash, eql) == our_e);
  3589. }
  3590. static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
  3591. upb_tabkey *removed, uint32_t hash, eqlfunc_t *eql) {
  3592. upb_tabent *chain = getentry_mutable(t, hash);
  3593. if (upb_tabent_isempty(chain)) return false;
  3594. if (eql(chain->key, key)) {
  3595. /* Element to remove is at the head of its chain. */
  3596. t->count--;
  3597. if (val) {
  3598. _upb_value_setval(val, chain->val.val, t->ctype);
  3599. }
  3600. if (chain->next) {
  3601. upb_tabent *move = (upb_tabent*)chain->next;
  3602. *chain = *move;
  3603. if (removed) *removed = move->key;
  3604. move->key = 0; /* Make the slot empty. */
  3605. } else {
  3606. if (removed) *removed = chain->key;
  3607. chain->key = 0; /* Make the slot empty. */
  3608. }
  3609. return true;
  3610. } else {
  3611. /* Element to remove is either in a non-head position or not in the
  3612. * table. */
  3613. while (chain->next && !eql(chain->next->key, key))
  3614. chain = (upb_tabent*)chain->next;
  3615. if (chain->next) {
  3616. /* Found element to remove. */
  3617. upb_tabent *rm;
  3618. if (val) {
  3619. _upb_value_setval(val, chain->next->val.val, t->ctype);
  3620. }
  3621. rm = (upb_tabent*)chain->next;
  3622. if (removed) *removed = rm->key;
  3623. rm->key = 0;
  3624. chain->next = rm->next;
  3625. t->count--;
  3626. return true;
  3627. } else {
  3628. return false;
  3629. }
  3630. }
  3631. }
  3632. static size_t next(const upb_table *t, size_t i) {
  3633. do {
  3634. if (++i >= upb_table_size(t))
  3635. return SIZE_MAX;
  3636. } while(upb_tabent_isempty(&t->entries[i]));
  3637. return i;
  3638. }
  3639. static size_t begin(const upb_table *t) {
  3640. return next(t, -1);
  3641. }
  3642. /* upb_strtable ***************************************************************/
  3643. /* A simple "subclass" of upb_table that only adds a hash function for strings. */
  3644. static upb_tabkey strcopy(lookupkey_t k2) {
  3645. char *str = malloc(k2.str.len + sizeof(uint32_t) + 1);
  3646. if (str == NULL) return 0;
  3647. memcpy(str, &k2.str.len, sizeof(uint32_t));
  3648. memcpy(str + sizeof(uint32_t), k2.str.str, k2.str.len + 1);
  3649. return (uintptr_t)str;
  3650. }
  3651. static uint32_t strhash(upb_tabkey key) {
  3652. uint32_t len;
  3653. char *str = upb_tabstr(key, &len);
  3654. return MurmurHash2(str, len, 0);
  3655. }
  3656. static bool streql(upb_tabkey k1, lookupkey_t k2) {
  3657. uint32_t len;
  3658. char *str = upb_tabstr(k1, &len);
  3659. return len == k2.str.len && memcmp(str, k2.str.str, len) == 0;
  3660. }
  3661. bool upb_strtable_init(upb_strtable *t, upb_ctype_t ctype) {
  3662. return init(&t->t, ctype, 2);
  3663. }
  3664. void upb_strtable_uninit(upb_strtable *t) {
  3665. size_t i;
  3666. for (i = 0; i < upb_table_size(&t->t); i++)
  3667. free((void*)t->t.entries[i].key);
  3668. uninit(&t->t);
  3669. }
  3670. bool upb_strtable_resize(upb_strtable *t, size_t size_lg2) {
  3671. upb_strtable new_table;
  3672. upb_strtable_iter i;
  3673. if (!init(&new_table.t, t->t.ctype, size_lg2))
  3674. return false;
  3675. upb_strtable_begin(&i, t);
  3676. for ( ; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  3677. upb_strtable_insert2(
  3678. &new_table,
  3679. upb_strtable_iter_key(&i),
  3680. upb_strtable_iter_keylength(&i),
  3681. upb_strtable_iter_value(&i));
  3682. }
  3683. upb_strtable_uninit(t);
  3684. *t = new_table;
  3685. return true;
  3686. }
  3687. bool upb_strtable_insert2(upb_strtable *t, const char *k, size_t len,
  3688. upb_value v) {
  3689. lookupkey_t key;
  3690. upb_tabkey tabkey;
  3691. uint32_t hash;
  3692. if (isfull(&t->t)) {
  3693. /* Need to resize. New table of double the size, add old elements to it. */
  3694. if (!upb_strtable_resize(t, t->t.size_lg2 + 1)) {
  3695. return false;
  3696. }
  3697. }
  3698. key = strkey2(k, len);
  3699. tabkey = strcopy(key);
  3700. if (tabkey == 0) return false;
  3701. hash = MurmurHash2(key.str.str, key.str.len, 0);
  3702. insert(&t->t, key, tabkey, v, hash, &strhash, &streql);
  3703. return true;
  3704. }
  3705. bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
  3706. upb_value *v) {
  3707. uint32_t hash = MurmurHash2(key, len, 0);
  3708. return lookup(&t->t, strkey2(key, len), v, hash, &streql);
  3709. }
  3710. bool upb_strtable_remove2(upb_strtable *t, const char *key, size_t len,
  3711. upb_value *val) {
  3712. uint32_t hash = MurmurHash2(key, strlen(key), 0);
  3713. upb_tabkey tabkey;
  3714. if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
  3715. free((void*)tabkey);
  3716. return true;
  3717. } else {
  3718. return false;
  3719. }
  3720. }
  3721. /* Iteration */
  3722. static const upb_tabent *str_tabent(const upb_strtable_iter *i) {
  3723. return &i->t->t.entries[i->index];
  3724. }
  3725. void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t) {
  3726. i->t = t;
  3727. i->index = begin(&t->t);
  3728. }
  3729. void upb_strtable_next(upb_strtable_iter *i) {
  3730. i->index = next(&i->t->t, i->index);
  3731. }
  3732. bool upb_strtable_done(const upb_strtable_iter *i) {
  3733. return i->index >= upb_table_size(&i->t->t) ||
  3734. upb_tabent_isempty(str_tabent(i));
  3735. }
  3736. const char *upb_strtable_iter_key(upb_strtable_iter *i) {
  3737. assert(!upb_strtable_done(i));
  3738. return upb_tabstr(str_tabent(i)->key, NULL);
  3739. }
  3740. size_t upb_strtable_iter_keylength(upb_strtable_iter *i) {
  3741. uint32_t len;
  3742. assert(!upb_strtable_done(i));
  3743. upb_tabstr(str_tabent(i)->key, &len);
  3744. return len;
  3745. }
  3746. upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
  3747. assert(!upb_strtable_done(i));
  3748. return _upb_value_val(str_tabent(i)->val.val, i->t->t.ctype);
  3749. }
  3750. void upb_strtable_iter_setdone(upb_strtable_iter *i) {
  3751. i->index = SIZE_MAX;
  3752. }
  3753. bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
  3754. const upb_strtable_iter *i2) {
  3755. if (upb_strtable_done(i1) && upb_strtable_done(i2))
  3756. return true;
  3757. return i1->t == i2->t && i1->index == i2->index;
  3758. }
  3759. /* upb_inttable ***************************************************************/
  3760. /* For inttables we use a hybrid structure where small keys are kept in an
  3761. * array and large keys are put in the hash table. */
  3762. static uint32_t inthash(upb_tabkey key) { return upb_inthash(key); }
  3763. static bool inteql(upb_tabkey k1, lookupkey_t k2) {
  3764. return k1 == k2.num;
  3765. }
  3766. static upb_tabval *mutable_array(upb_inttable *t) {
  3767. return (upb_tabval*)t->array;
  3768. }
  3769. static upb_tabval *inttable_val(upb_inttable *t, uintptr_t key) {
  3770. if (key < t->array_size) {
  3771. return upb_arrhas(t->array[key]) ? &(mutable_array(t)[key]) : NULL;
  3772. } else {
  3773. upb_tabent *e =
  3774. findentry_mutable(&t->t, intkey(key), upb_inthash(key), &inteql);
  3775. return e ? &e->val : NULL;
  3776. }
  3777. }
  3778. static const upb_tabval *inttable_val_const(const upb_inttable *t,
  3779. uintptr_t key) {
  3780. return inttable_val((upb_inttable*)t, key);
  3781. }
  3782. size_t upb_inttable_count(const upb_inttable *t) {
  3783. return t->t.count + t->array_count;
  3784. }
  3785. static void check(upb_inttable *t) {
  3786. UPB_UNUSED(t);
  3787. #if defined(UPB_DEBUG_TABLE) && !defined(NDEBUG)
  3788. {
  3789. /* This check is very expensive (makes inserts/deletes O(N)). */
  3790. size_t count = 0;
  3791. upb_inttable_iter i;
  3792. upb_inttable_begin(&i, t);
  3793. for(; !upb_inttable_done(&i); upb_inttable_next(&i), count++) {
  3794. assert(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
  3795. }
  3796. assert(count == upb_inttable_count(t));
  3797. }
  3798. #endif
  3799. }
  3800. bool upb_inttable_sizedinit(upb_inttable *t, upb_ctype_t ctype,
  3801. size_t asize, int hsize_lg2) {
  3802. size_t array_bytes;
  3803. if (!init(&t->t, ctype, hsize_lg2)) return false;
  3804. /* Always make the array part at least 1 long, so that we know key 0
  3805. * won't be in the hash part, which simplifies things. */
  3806. t->array_size = UPB_MAX(1, asize);
  3807. t->array_count = 0;
  3808. array_bytes = t->array_size * sizeof(upb_value);
  3809. t->array = malloc(array_bytes);
  3810. if (!t->array) {
  3811. uninit(&t->t);
  3812. return false;
  3813. }
  3814. memset(mutable_array(t), 0xff, array_bytes);
  3815. check(t);
  3816. return true;
  3817. }
  3818. bool upb_inttable_init(upb_inttable *t, upb_ctype_t ctype) {
  3819. return upb_inttable_sizedinit(t, ctype, 0, 4);
  3820. }
  3821. void upb_inttable_uninit(upb_inttable *t) {
  3822. uninit(&t->t);
  3823. free(mutable_array(t));
  3824. }
  3825. bool upb_inttable_insert(upb_inttable *t, uintptr_t key, upb_value val) {
  3826. /* XXX: Table can't store value (uint64_t)-1. Need to somehow statically
  3827. * guarantee that this is not necessary, or fix the limitation. */
  3828. upb_tabval tabval;
  3829. tabval.val = val.val;
  3830. UPB_UNUSED(tabval);
  3831. assert(upb_arrhas(tabval));
  3832. if (key < t->array_size) {
  3833. assert(!upb_arrhas(t->array[key]));
  3834. t->array_count++;
  3835. mutable_array(t)[key].val = val.val;
  3836. } else {
  3837. if (isfull(&t->t)) {
  3838. /* Need to resize the hash part, but we re-use the array part. */
  3839. size_t i;
  3840. upb_table new_table;
  3841. if (!init(&new_table, t->t.ctype, t->t.size_lg2 + 1))
  3842. return false;
  3843. for (i = begin(&t->t); i < upb_table_size(&t->t); i = next(&t->t, i)) {
  3844. const upb_tabent *e = &t->t.entries[i];
  3845. uint32_t hash;
  3846. upb_value v;
  3847. _upb_value_setval(&v, e->val.val, t->t.ctype);
  3848. hash = upb_inthash(e->key);
  3849. insert(&new_table, intkey(e->key), e->key, v, hash, &inthash, &inteql);
  3850. }
  3851. assert(t->t.count == new_table.count);
  3852. uninit(&t->t);
  3853. t->t = new_table;
  3854. }
  3855. insert(&t->t, intkey(key), key, val, upb_inthash(key), &inthash, &inteql);
  3856. }
  3857. check(t);
  3858. return true;
  3859. }
  3860. bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v) {
  3861. const upb_tabval *table_v = inttable_val_const(t, key);
  3862. if (!table_v) return false;
  3863. if (v) _upb_value_setval(v, table_v->val, t->t.ctype);
  3864. return true;
  3865. }
  3866. bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val) {
  3867. upb_tabval *table_v = inttable_val(t, key);
  3868. if (!table_v) return false;
  3869. table_v->val = val.val;
  3870. return true;
  3871. }
  3872. bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val) {
  3873. bool success;
  3874. if (key < t->array_size) {
  3875. if (upb_arrhas(t->array[key])) {
  3876. upb_tabval empty = UPB_TABVALUE_EMPTY_INIT;
  3877. t->array_count--;
  3878. if (val) {
  3879. _upb_value_setval(val, t->array[key].val, t->t.ctype);
  3880. }
  3881. mutable_array(t)[key] = empty;
  3882. success = true;
  3883. } else {
  3884. success = false;
  3885. }
  3886. } else {
  3887. upb_tabkey removed;
  3888. uint32_t hash = upb_inthash(key);
  3889. success = rm(&t->t, intkey(key), val, &removed, hash, &inteql);
  3890. }
  3891. check(t);
  3892. return success;
  3893. }
  3894. bool upb_inttable_push(upb_inttable *t, upb_value val) {
  3895. return upb_inttable_insert(t, upb_inttable_count(t), val);
  3896. }
  3897. upb_value upb_inttable_pop(upb_inttable *t) {
  3898. upb_value val;
  3899. bool ok = upb_inttable_remove(t, upb_inttable_count(t) - 1, &val);
  3900. UPB_ASSERT_VAR(ok, ok);
  3901. return val;
  3902. }
  3903. bool upb_inttable_insertptr(upb_inttable *t, const void *key, upb_value val) {
  3904. return upb_inttable_insert(t, (uintptr_t)key, val);
  3905. }
  3906. bool upb_inttable_lookupptr(const upb_inttable *t, const void *key,
  3907. upb_value *v) {
  3908. return upb_inttable_lookup(t, (uintptr_t)key, v);
  3909. }
  3910. bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val) {
  3911. return upb_inttable_remove(t, (uintptr_t)key, val);
  3912. }
  3913. void upb_inttable_compact(upb_inttable *t) {
  3914. /* Create a power-of-two histogram of the table keys. */
  3915. int counts[UPB_MAXARRSIZE + 1] = {0};
  3916. uintptr_t max_key = 0;
  3917. upb_inttable_iter i;
  3918. size_t arr_size;
  3919. int arr_count;
  3920. upb_inttable new_t;
  3921. upb_inttable_begin(&i, t);
  3922. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  3923. uintptr_t key = upb_inttable_iter_key(&i);
  3924. if (key > max_key) {
  3925. max_key = key;
  3926. }
  3927. counts[log2ceil(key)]++;
  3928. }
  3929. arr_size = 1;
  3930. arr_count = upb_inttable_count(t);
  3931. if (upb_inttable_count(t) >= max_key * MIN_DENSITY) {
  3932. /* We can put 100% of the entries in the array part. */
  3933. arr_size = max_key + 1;
  3934. } else {
  3935. /* Find the largest power of two that satisfies the MIN_DENSITY
  3936. * definition. */
  3937. int size_lg2;
  3938. for (size_lg2 = ARRAY_SIZE(counts) - 1; size_lg2 > 1; size_lg2--) {
  3939. arr_size = 1 << size_lg2;
  3940. arr_count -= counts[size_lg2];
  3941. if (arr_count >= arr_size * MIN_DENSITY) {
  3942. break;
  3943. }
  3944. }
  3945. }
  3946. /* Array part must always be at least 1 entry large to catch lookups of key
  3947. * 0. Key 0 must always be in the array part because "0" in the hash part
  3948. * denotes an empty entry. */
  3949. arr_size = UPB_MAX(arr_size, 1);
  3950. {
  3951. /* Insert all elements into new, perfectly-sized table. */
  3952. int hash_count = upb_inttable_count(t) - arr_count;
  3953. int hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
  3954. int hashsize_lg2 = log2ceil(hash_size);
  3955. assert(hash_count >= 0);
  3956. upb_inttable_sizedinit(&new_t, t->t.ctype, arr_size, hashsize_lg2);
  3957. upb_inttable_begin(&i, t);
  3958. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  3959. uintptr_t k = upb_inttable_iter_key(&i);
  3960. upb_inttable_insert(&new_t, k, upb_inttable_iter_value(&i));
  3961. }
  3962. assert(new_t.array_size == arr_size);
  3963. assert(new_t.t.size_lg2 == hashsize_lg2);
  3964. }
  3965. upb_inttable_uninit(t);
  3966. *t = new_t;
  3967. }
  3968. /* Iteration. */
  3969. static const upb_tabent *int_tabent(const upb_inttable_iter *i) {
  3970. assert(!i->array_part);
  3971. return &i->t->t.entries[i->index];
  3972. }
  3973. static upb_tabval int_arrent(const upb_inttable_iter *i) {
  3974. assert(i->array_part);
  3975. return i->t->array[i->index];
  3976. }
  3977. void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t) {
  3978. i->t = t;
  3979. i->index = -1;
  3980. i->array_part = true;
  3981. upb_inttable_next(i);
  3982. }
  3983. void upb_inttable_next(upb_inttable_iter *iter) {
  3984. const upb_inttable *t = iter->t;
  3985. if (iter->array_part) {
  3986. while (++iter->index < t->array_size) {
  3987. if (upb_arrhas(int_arrent(iter))) {
  3988. return;
  3989. }
  3990. }
  3991. iter->array_part = false;
  3992. iter->index = begin(&t->t);
  3993. } else {
  3994. iter->index = next(&t->t, iter->index);
  3995. }
  3996. }
  3997. bool upb_inttable_done(const upb_inttable_iter *i) {
  3998. if (i->array_part) {
  3999. return i->index >= i->t->array_size ||
  4000. !upb_arrhas(int_arrent(i));
  4001. } else {
  4002. return i->index >= upb_table_size(&i->t->t) ||
  4003. upb_tabent_isempty(int_tabent(i));
  4004. }
  4005. }
  4006. uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i) {
  4007. assert(!upb_inttable_done(i));
  4008. return i->array_part ? i->index : int_tabent(i)->key;
  4009. }
  4010. upb_value upb_inttable_iter_value(const upb_inttable_iter *i) {
  4011. assert(!upb_inttable_done(i));
  4012. return _upb_value_val(
  4013. i->array_part ? i->t->array[i->index].val : int_tabent(i)->val.val,
  4014. i->t->t.ctype);
  4015. }
  4016. void upb_inttable_iter_setdone(upb_inttable_iter *i) {
  4017. i->index = SIZE_MAX;
  4018. i->array_part = false;
  4019. }
  4020. bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
  4021. const upb_inttable_iter *i2) {
  4022. if (upb_inttable_done(i1) && upb_inttable_done(i2))
  4023. return true;
  4024. return i1->t == i2->t && i1->index == i2->index &&
  4025. i1->array_part == i2->array_part;
  4026. }
  4027. #ifdef UPB_UNALIGNED_READS_OK
  4028. /* -----------------------------------------------------------------------------
  4029. * MurmurHash2, by Austin Appleby (released as public domain).
  4030. * Reformatted and C99-ified by Joshua Haberman.
  4031. * Note - This code makes a few assumptions about how your machine behaves -
  4032. * 1. We can read a 4-byte value from any address without crashing
  4033. * 2. sizeof(int) == 4 (in upb this limitation is removed by using uint32_t
  4034. * And it has a few limitations -
  4035. * 1. It will not work incrementally.
  4036. * 2. It will not produce the same results on little-endian and big-endian
  4037. * machines. */
  4038. uint32_t MurmurHash2(const void *key, size_t len, uint32_t seed) {
  4039. /* 'm' and 'r' are mixing constants generated offline.
  4040. * They're not really 'magic', they just happen to work well. */
  4041. const uint32_t m = 0x5bd1e995;
  4042. const int32_t r = 24;
  4043. /* Initialize the hash to a 'random' value */
  4044. uint32_t h = seed ^ len;
  4045. /* Mix 4 bytes at a time into the hash */
  4046. const uint8_t * data = (const uint8_t *)key;
  4047. while(len >= 4) {
  4048. uint32_t k = *(uint32_t *)data;
  4049. k *= m;
  4050. k ^= k >> r;
  4051. k *= m;
  4052. h *= m;
  4053. h ^= k;
  4054. data += 4;
  4055. len -= 4;
  4056. }
  4057. /* Handle the last few bytes of the input array */
  4058. switch(len) {
  4059. case 3: h ^= data[2] << 16;
  4060. case 2: h ^= data[1] << 8;
  4061. case 1: h ^= data[0]; h *= m;
  4062. };
  4063. /* Do a few final mixes of the hash to ensure the last few
  4064. * bytes are well-incorporated. */
  4065. h ^= h >> 13;
  4066. h *= m;
  4067. h ^= h >> 15;
  4068. return h;
  4069. }
  4070. #else /* !UPB_UNALIGNED_READS_OK */
  4071. /* -----------------------------------------------------------------------------
  4072. * MurmurHashAligned2, by Austin Appleby
  4073. * Same algorithm as MurmurHash2, but only does aligned reads - should be safer
  4074. * on certain platforms.
  4075. * Performance will be lower than MurmurHash2 */
  4076. #define MIX(h,k,m) { k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; }
  4077. uint32_t MurmurHash2(const void * key, size_t len, uint32_t seed) {
  4078. const uint32_t m = 0x5bd1e995;
  4079. const int32_t r = 24;
  4080. const uint8_t * data = (const uint8_t *)key;
  4081. uint32_t h = seed ^ len;
  4082. uint8_t align = (uintptr_t)data & 3;
  4083. if(align && (len >= 4)) {
  4084. /* Pre-load the temp registers */
  4085. uint32_t t = 0, d = 0;
  4086. int32_t sl;
  4087. int32_t sr;
  4088. switch(align) {
  4089. case 1: t |= data[2] << 16;
  4090. case 2: t |= data[1] << 8;
  4091. case 3: t |= data[0];
  4092. }
  4093. t <<= (8 * align);
  4094. data += 4-align;
  4095. len -= 4-align;
  4096. sl = 8 * (4-align);
  4097. sr = 8 * align;
  4098. /* Mix */
  4099. while(len >= 4) {
  4100. uint32_t k;
  4101. d = *(uint32_t *)data;
  4102. t = (t >> sr) | (d << sl);
  4103. k = t;
  4104. MIX(h,k,m);
  4105. t = d;
  4106. data += 4;
  4107. len -= 4;
  4108. }
  4109. /* Handle leftover data in temp registers */
  4110. d = 0;
  4111. if(len >= align) {
  4112. uint32_t k;
  4113. switch(align) {
  4114. case 3: d |= data[2] << 16;
  4115. case 2: d |= data[1] << 8;
  4116. case 1: d |= data[0];
  4117. }
  4118. k = (t >> sr) | (d << sl);
  4119. MIX(h,k,m);
  4120. data += align;
  4121. len -= align;
  4122. /* ----------
  4123. * Handle tail bytes */
  4124. switch(len) {
  4125. case 3: h ^= data[2] << 16;
  4126. case 2: h ^= data[1] << 8;
  4127. case 1: h ^= data[0]; h *= m;
  4128. };
  4129. } else {
  4130. switch(len) {
  4131. case 3: d |= data[2] << 16;
  4132. case 2: d |= data[1] << 8;
  4133. case 1: d |= data[0];
  4134. case 0: h ^= (t >> sr) | (d << sl); h *= m;
  4135. }
  4136. }
  4137. h ^= h >> 13;
  4138. h *= m;
  4139. h ^= h >> 15;
  4140. return h;
  4141. } else {
  4142. while(len >= 4) {
  4143. uint32_t k = *(uint32_t *)data;
  4144. MIX(h,k,m);
  4145. data += 4;
  4146. len -= 4;
  4147. }
  4148. /* ----------
  4149. * Handle tail bytes */
  4150. switch(len) {
  4151. case 3: h ^= data[2] << 16;
  4152. case 2: h ^= data[1] << 8;
  4153. case 1: h ^= data[0]; h *= m;
  4154. };
  4155. h ^= h >> 13;
  4156. h *= m;
  4157. h ^= h >> 15;
  4158. return h;
  4159. }
  4160. }
  4161. #undef MIX
  4162. #endif /* UPB_UNALIGNED_READS_OK */
  4163. #include <errno.h>
  4164. #include <stdarg.h>
  4165. #include <stddef.h>
  4166. #include <stdint.h>
  4167. #include <stdio.h>
  4168. #include <stdlib.h>
  4169. #include <string.h>
  4170. bool upb_dumptostderr(void *closure, const upb_status* status) {
  4171. UPB_UNUSED(closure);
  4172. fprintf(stderr, "%s\n", upb_status_errmsg(status));
  4173. return false;
  4174. }
  4175. /* Guarantee null-termination and provide ellipsis truncation.
  4176. * It may be tempting to "optimize" this by initializing these final
  4177. * four bytes up-front and then being careful never to overwrite them,
  4178. * this is safer and simpler. */
  4179. static void nullz(upb_status *status) {
  4180. const char *ellipsis = "...";
  4181. size_t len = strlen(ellipsis);
  4182. assert(sizeof(status->msg) > len);
  4183. memcpy(status->msg + sizeof(status->msg) - len, ellipsis, len);
  4184. }
  4185. void upb_status_clear(upb_status *status) {
  4186. if (!status) return;
  4187. status->ok_ = true;
  4188. status->code_ = 0;
  4189. status->msg[0] = '\0';
  4190. }
  4191. bool upb_ok(const upb_status *status) { return status->ok_; }
  4192. upb_errorspace *upb_status_errspace(const upb_status *status) {
  4193. return status->error_space_;
  4194. }
  4195. int upb_status_errcode(const upb_status *status) { return status->code_; }
  4196. const char *upb_status_errmsg(const upb_status *status) { return status->msg; }
  4197. void upb_status_seterrmsg(upb_status *status, const char *msg) {
  4198. if (!status) return;
  4199. status->ok_ = false;
  4200. strncpy(status->msg, msg, sizeof(status->msg));
  4201. nullz(status);
  4202. }
  4203. void upb_status_seterrf(upb_status *status, const char *fmt, ...) {
  4204. va_list args;
  4205. va_start(args, fmt);
  4206. upb_status_vseterrf(status, fmt, args);
  4207. va_end(args);
  4208. }
  4209. void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args) {
  4210. if (!status) return;
  4211. status->ok_ = false;
  4212. _upb_vsnprintf(status->msg, sizeof(status->msg), fmt, args);
  4213. nullz(status);
  4214. }
  4215. void upb_status_seterrcode(upb_status *status, upb_errorspace *space,
  4216. int code) {
  4217. if (!status) return;
  4218. status->ok_ = false;
  4219. status->error_space_ = space;
  4220. status->code_ = code;
  4221. space->set_message(status, code);
  4222. }
  4223. void upb_status_copy(upb_status *to, const upb_status *from) {
  4224. if (!to) return;
  4225. *to = *from;
  4226. }
  4227. /* This file was generated by upbc (the upb compiler).
  4228. * Do not edit -- your changes will be discarded when the file is
  4229. * regenerated. */
  4230. static const upb_msgdef msgs[20];
  4231. static const upb_fielddef fields[81];
  4232. static const upb_enumdef enums[4];
  4233. static const upb_tabent strentries[236];
  4234. static const upb_tabent intentries[14];
  4235. static const upb_tabval arrays[232];
  4236. #ifdef UPB_DEBUG_REFS
  4237. static upb_inttable reftables[212];
  4238. #endif
  4239. static const upb_msgdef msgs[20] = {
  4240. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto", 27, 6, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[0], 8, 7), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[0]),&reftables[0], &reftables[1]),
  4241. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ExtensionRange", 4, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[8], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[16]),&reftables[2], &reftables[3]),
  4242. UPB_MSGDEF_INIT("google.protobuf.EnumDescriptorProto", 11, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[11], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[20]),&reftables[4], &reftables[5]),
  4243. UPB_MSGDEF_INIT("google.protobuf.EnumOptions", 7, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[0], &arrays[15], 8, 1), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[24]),&reftables[6], &reftables[7]),
  4244. UPB_MSGDEF_INIT("google.protobuf.EnumValueDescriptorProto", 8, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[23], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[28]),&reftables[8], &reftables[9]),
  4245. UPB_MSGDEF_INIT("google.protobuf.EnumValueOptions", 6, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[2], &arrays[27], 4, 0), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[32]),&reftables[10], &reftables[11]),
  4246. UPB_MSGDEF_INIT("google.protobuf.FieldDescriptorProto", 19, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[31], 9, 8), UPB_STRTABLE_INIT(8, 15, UPB_CTYPE_PTR, 4, &strentries[36]),&reftables[12], &reftables[13]),
  4247. UPB_MSGDEF_INIT("google.protobuf.FieldOptions", 14, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[4], &arrays[40], 32, 6), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[52]),&reftables[14], &reftables[15]),
  4248. UPB_MSGDEF_INIT("google.protobuf.FileDescriptorProto", 39, 6, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[72], 12, 11), UPB_STRTABLE_INIT(11, 15, UPB_CTYPE_PTR, 4, &strentries[68]),&reftables[16], &reftables[17]),
  4249. UPB_MSGDEF_INIT("google.protobuf.FileDescriptorSet", 6, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[84], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[84]),&reftables[18], &reftables[19]),
  4250. UPB_MSGDEF_INIT("google.protobuf.FileOptions", 21, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[6], &arrays[86], 64, 9), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[88]),&reftables[20], &reftables[21]),
  4251. UPB_MSGDEF_INIT("google.protobuf.MessageOptions", 8, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[8], &arrays[150], 16, 2), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[104]),&reftables[22], &reftables[23]),
  4252. UPB_MSGDEF_INIT("google.protobuf.MethodDescriptorProto", 13, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[166], 5, 4), UPB_STRTABLE_INIT(4, 7, UPB_CTYPE_PTR, 3, &strentries[108]),&reftables[24], &reftables[25]),
  4253. UPB_MSGDEF_INIT("google.protobuf.MethodOptions", 6, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[10], &arrays[171], 4, 0), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[116]),&reftables[26], &reftables[27]),
  4254. UPB_MSGDEF_INIT("google.protobuf.ServiceDescriptorProto", 11, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[175], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[120]),&reftables[28], &reftables[29]),
  4255. UPB_MSGDEF_INIT("google.protobuf.ServiceOptions", 6, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[12], &arrays[179], 4, 0), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[124]),&reftables[30], &reftables[31]),
  4256. UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo", 6, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[183], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[128]),&reftables[32], &reftables[33]),
  4257. UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo.Location", 14, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[185], 5, 4), UPB_STRTABLE_INIT(4, 7, UPB_CTYPE_PTR, 3, &strentries[132]),&reftables[34], &reftables[35]),
  4258. UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption", 18, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[190], 9, 7), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[140]),&reftables[36], &reftables[37]),
  4259. UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption.NamePart", 6, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[199], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[156]),&reftables[38], &reftables[39]),
  4260. };
  4261. static const upb_fielddef fields[81] = {
  4262. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "aggregate_value", 8, &msgs[18], NULL, 15, 6, {0},&reftables[40], &reftables[41]),
  4263. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "allow_alias", 2, &msgs[3], NULL, 6, 1, {0},&reftables[42], &reftables[43]),
  4264. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_generic_services", 16, &msgs[10], NULL, 17, 6, {0},&reftables[44], &reftables[45]),
  4265. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "ctype", 1, &msgs[7], (const upb_def*)(&enums[2]), 6, 1, {0},&reftables[46], &reftables[47]),
  4266. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "default_value", 7, &msgs[6], NULL, 16, 7, {0},&reftables[48], &reftables[49]),
  4267. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "dependency", 3, &msgs[8], NULL, 30, 8, {0},&reftables[50], &reftables[51]),
  4268. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[7], NULL, 8, 3, {0},&reftables[52], &reftables[53]),
  4269. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_DOUBLE, 0, false, false, false, false, "double_value", 6, &msgs[18], NULL, 11, 4, {0},&reftables[54], &reftables[55]),
  4270. 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[56], &reftables[57]),
  4271. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 4, &msgs[0], (const upb_def*)(&msgs[2]), 16, 2, {0},&reftables[58], &reftables[59]),
  4272. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 5, &msgs[8], (const upb_def*)(&msgs[2]), 13, 1, {0},&reftables[60], &reftables[61]),
  4273. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "experimental_map_key", 9, &msgs[7], NULL, 10, 5, {0},&reftables[62], &reftables[63]),
  4274. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "extendee", 2, &msgs[6], NULL, 7, 2, {0},&reftables[64], &reftables[65]),
  4275. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 7, &msgs[8], (const upb_def*)(&msgs[6]), 19, 3, {0},&reftables[66], &reftables[67]),
  4276. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 6, &msgs[0], (const upb_def*)(&msgs[6]), 22, 4, {0},&reftables[68], &reftables[69]),
  4277. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension_range", 5, &msgs[0], (const upb_def*)(&msgs[1]), 19, 3, {0},&reftables[70], &reftables[71]),
  4278. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "field", 2, &msgs[0], (const upb_def*)(&msgs[6]), 10, 0, {0},&reftables[72], &reftables[73]),
  4279. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "file", 1, &msgs[9], (const upb_def*)(&msgs[8]), 5, 0, {0},&reftables[74], &reftables[75]),
  4280. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "go_package", 11, &msgs[10], NULL, 14, 5, {0},&reftables[76], &reftables[77]),
  4281. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "identifier_value", 3, &msgs[18], NULL, 6, 1, {0},&reftables[78], &reftables[79]),
  4282. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "input_type", 2, &msgs[12], NULL, 7, 2, {0},&reftables[80], &reftables[81]),
  4283. UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_BOOL, 0, false, false, false, false, "is_extension", 2, &msgs[19], NULL, 5, 1, {0},&reftables[82], &reftables[83]),
  4284. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generate_equals_and_hash", 20, &msgs[10], NULL, 20, 9, {0},&reftables[84], &reftables[85]),
  4285. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generic_services", 17, &msgs[10], NULL, 18, 7, {0},&reftables[86], &reftables[87]),
  4286. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_multiple_files", 10, &msgs[10], NULL, 13, 4, {0},&reftables[88], &reftables[89]),
  4287. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_outer_classname", 8, &msgs[10], NULL, 9, 2, {0},&reftables[90], &reftables[91]),
  4288. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_package", 1, &msgs[10], NULL, 6, 1, {0},&reftables[92], &reftables[93]),
  4289. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "label", 4, &msgs[6], (const upb_def*)(&enums[0]), 11, 4, {0},&reftables[94], &reftables[95]),
  4290. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "lazy", 5, &msgs[7], NULL, 9, 4, {0},&reftables[96], &reftables[97]),
  4291. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "leading_comments", 3, &msgs[17], NULL, 8, 2, {0},&reftables[98], &reftables[99]),
  4292. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "location", 1, &msgs[16], (const upb_def*)(&msgs[17]), 5, 0, {0},&reftables[100], &reftables[101]),
  4293. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "message_set_wire_format", 1, &msgs[11], NULL, 6, 1, {0},&reftables[102], &reftables[103]),
  4294. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "message_type", 4, &msgs[8], (const upb_def*)(&msgs[0]), 10, 0, {0},&reftables[104], &reftables[105]),
  4295. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "method", 2, &msgs[14], (const upb_def*)(&msgs[12]), 6, 0, {0},&reftables[106], &reftables[107]),
  4296. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[8], NULL, 22, 6, {0},&reftables[108], &reftables[109]),
  4297. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[14], NULL, 8, 2, {0},&reftables[110], &reftables[111]),
  4298. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "name", 2, &msgs[18], (const upb_def*)(&msgs[19]), 5, 0, {0},&reftables[112], &reftables[113]),
  4299. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[4], NULL, 4, 1, {0},&reftables[114], &reftables[115]),
  4300. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[0], NULL, 24, 6, {0},&reftables[116], &reftables[117]),
  4301. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[12], NULL, 4, 1, {0},&reftables[118], &reftables[119]),
  4302. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[2], NULL, 8, 2, {0},&reftables[120], &reftables[121]),
  4303. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[6], NULL, 4, 1, {0},&reftables[122], &reftables[123]),
  4304. UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_STRING, 0, false, false, false, false, "name_part", 1, &msgs[19], NULL, 2, 0, {0},&reftables[124], &reftables[125]),
  4305. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT64, UPB_INTFMT_VARIABLE, false, false, false, false, "negative_int_value", 5, &msgs[18], NULL, 10, 3, {0},&reftables[126], &reftables[127]),
  4306. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "nested_type", 3, &msgs[0], (const upb_def*)(&msgs[0]), 13, 1, {0},&reftables[128], &reftables[129]),
  4307. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "no_standard_descriptor_accessor", 2, &msgs[11], NULL, 7, 2, {0},&reftables[130], &reftables[131]),
  4308. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 3, &msgs[6], NULL, 10, 3, {0},&reftables[132], &reftables[133]),
  4309. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 2, &msgs[4], NULL, 7, 2, {0},&reftables[134], &reftables[135]),
  4310. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "optimize_for", 9, &msgs[10], (const upb_def*)(&enums[3]), 12, 3, {0},&reftables[136], &reftables[137]),
  4311. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 7, &msgs[0], (const upb_def*)(&msgs[11]), 23, 5, {0},&reftables[138], &reftables[139]),
  4312. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[2], (const upb_def*)(&msgs[3]), 7, 1, {0},&reftables[140], &reftables[141]),
  4313. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[6], (const upb_def*)(&msgs[7]), 3, 0, {0},&reftables[142], &reftables[143]),
  4314. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[4], (const upb_def*)(&msgs[5]), 3, 0, {0},&reftables[144], &reftables[145]),
  4315. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[8], (const upb_def*)(&msgs[10]), 20, 4, {0},&reftables[146], &reftables[147]),
  4316. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[14], (const upb_def*)(&msgs[15]), 7, 1, {0},&reftables[148], &reftables[149]),
  4317. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 4, &msgs[12], (const upb_def*)(&msgs[13]), 3, 0, {0},&reftables[150], &reftables[151]),
  4318. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "output_type", 3, &msgs[12], NULL, 10, 3, {0},&reftables[152], &reftables[153]),
  4319. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "package", 2, &msgs[8], NULL, 25, 7, {0},&reftables[154], &reftables[155]),
  4320. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "packed", 2, &msgs[7], NULL, 7, 2, {0},&reftables[156], &reftables[157]),
  4321. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "path", 1, &msgs[17], NULL, 4, 0, {0},&reftables[158], &reftables[159]),
  4322. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_UINT64, UPB_INTFMT_VARIABLE, false, false, false, false, "positive_int_value", 4, &msgs[18], NULL, 9, 2, {0},&reftables[160], &reftables[161]),
  4323. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "public_dependency", 10, &msgs[8], NULL, 35, 9, {0},&reftables[162], &reftables[163]),
  4324. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "py_generic_services", 18, &msgs[10], NULL, 19, 8, {0},&reftables[164], &reftables[165]),
  4325. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "service", 6, &msgs[8], (const upb_def*)(&msgs[14]), 16, 2, {0},&reftables[166], &reftables[167]),
  4326. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "source_code_info", 9, &msgs[8], (const upb_def*)(&msgs[16]), 21, 5, {0},&reftables[168], &reftables[169]),
  4327. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "span", 2, &msgs[17], NULL, 7, 1, {0},&reftables[170], &reftables[171]),
  4328. 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[172], &reftables[173]),
  4329. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BYTES, 0, false, false, false, false, "string_value", 7, &msgs[18], NULL, 12, 5, {0},&reftables[174], &reftables[175]),
  4330. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "trailing_comments", 4, &msgs[17], NULL, 11, 3, {0},&reftables[176], &reftables[177]),
  4331. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "type", 5, &msgs[6], (const upb_def*)(&enums[1]), 12, 5, {0},&reftables[178], &reftables[179]),
  4332. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "type_name", 6, &msgs[6], NULL, 13, 6, {0},&reftables[180], &reftables[181]),
  4333. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[5], (const upb_def*)(&msgs[18]), 5, 0, {0},&reftables[182], &reftables[183]),
  4334. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[15], (const upb_def*)(&msgs[18]), 5, 0, {0},&reftables[184], &reftables[185]),
  4335. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[3], (const upb_def*)(&msgs[18]), 5, 0, {0},&reftables[186], &reftables[187]),
  4336. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[13], (const upb_def*)(&msgs[18]), 5, 0, {0},&reftables[188], &reftables[189]),
  4337. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[10], (const upb_def*)(&msgs[18]), 5, 0, {0},&reftables[190], &reftables[191]),
  4338. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[11], (const upb_def*)(&msgs[18]), 5, 0, {0},&reftables[192], &reftables[193]),
  4339. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[7], (const upb_def*)(&msgs[18]), 5, 0, {0},&reftables[194], &reftables[195]),
  4340. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "value", 2, &msgs[2], (const upb_def*)(&msgs[4]), 6, 0, {0},&reftables[196], &reftables[197]),
  4341. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "weak", 10, &msgs[7], NULL, 13, 6, {0},&reftables[198], &reftables[199]),
  4342. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "weak_dependency", 11, &msgs[8], NULL, 38, 10, {0},&reftables[200], &reftables[201]),
  4343. };
  4344. static const upb_enumdef enums[4] = {
  4345. UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Label", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[160]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[202], 4, 3), 0, &reftables[202], &reftables[203]),
  4346. UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Type", UPB_STRTABLE_INIT(18, 31, UPB_CTYPE_INT32, 5, &strentries[164]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[206], 19, 18), 0, &reftables[204], &reftables[205]),
  4347. UPB_ENUMDEF_INIT("google.protobuf.FieldOptions.CType", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[196]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[225], 3, 3), 0, &reftables[206], &reftables[207]),
  4348. UPB_ENUMDEF_INIT("google.protobuf.FileOptions.OptimizeMode", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[200]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[228], 4, 3), 0, &reftables[208], &reftables[209]),
  4349. };
  4350. static const upb_tabent strentries[236] = {
  4351. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "extension"), UPB_TABVALUE_PTR_INIT(&fields[14]), NULL},
  4352. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4353. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4354. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[38]), NULL},
  4355. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4356. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4357. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4358. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "field"), UPB_TABVALUE_PTR_INIT(&fields[16]), NULL},
  4359. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "extension_range"), UPB_TABVALUE_PTR_INIT(&fields[15]), NULL},
  4360. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4361. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "nested_type"), UPB_TABVALUE_PTR_INIT(&fields[44]), NULL},
  4362. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4363. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4364. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4365. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[49]), NULL},
  4366. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[9]), &strentries[14]},
  4367. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[66]), NULL},
  4368. {UPB_TABKEY_STR("\003", "\000", "\000", "\000", "end"), UPB_TABVALUE_PTR_INIT(&fields[8]), NULL},
  4369. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4370. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4371. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4372. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "value"), UPB_TABVALUE_PTR_INIT(&fields[78]), NULL},
  4373. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[50]), NULL},
  4374. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[40]), &strentries[22]},
  4375. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[73]), NULL},
  4376. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4377. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "allow_alias"), UPB_TABVALUE_PTR_INIT(&fields[1]), NULL},
  4378. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4379. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[47]), NULL},
  4380. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4381. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[52]), NULL},
  4382. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[37]), &strentries[30]},
  4383. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[71]), NULL},
  4384. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4385. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4386. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4387. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4388. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "label"), UPB_TABVALUE_PTR_INIT(&fields[27]), NULL},
  4389. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4390. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[41]), NULL},
  4391. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4392. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4393. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4394. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4395. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[46]), &strentries[49]},
  4396. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4397. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4398. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "type_name"), UPB_TABVALUE_PTR_INIT(&fields[70]), NULL},
  4399. {UPB_TABKEY_STR("\010", "\000", "\000", "\000", "extendee"), UPB_TABVALUE_PTR_INIT(&fields[12]), NULL},
  4400. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "type"), UPB_TABVALUE_PTR_INIT(&fields[69]), &strentries[48]},
  4401. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "default_value"), UPB_TABVALUE_PTR_INIT(&fields[4]), NULL},
  4402. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[51]), NULL},
  4403. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "experimental_map_key"), UPB_TABVALUE_PTR_INIT(&fields[11]), &strentries[67]},
  4404. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4405. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "weak"), UPB_TABVALUE_PTR_INIT(&fields[79]), NULL},
  4406. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4407. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4408. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4409. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4410. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "packed"), UPB_TABVALUE_PTR_INIT(&fields[58]), NULL},
  4411. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "lazy"), UPB_TABVALUE_PTR_INIT(&fields[28]), NULL},
  4412. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4413. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "ctype"), UPB_TABVALUE_PTR_INIT(&fields[3]), NULL},
  4414. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4415. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4416. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[6]), NULL},
  4417. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4418. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[77]), NULL},
  4419. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "extension"), UPB_TABVALUE_PTR_INIT(&fields[13]), NULL},
  4420. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "weak_dependency"), UPB_TABVALUE_PTR_INIT(&fields[80]), NULL},
  4421. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4422. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[34]), NULL},
  4423. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "service"), UPB_TABVALUE_PTR_INIT(&fields[63]), NULL},
  4424. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4425. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "source_code_info"), UPB_TABVALUE_PTR_INIT(&fields[64]), NULL},
  4426. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4427. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4428. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4429. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "dependency"), UPB_TABVALUE_PTR_INIT(&fields[5]), NULL},
  4430. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "message_type"), UPB_TABVALUE_PTR_INIT(&fields[32]), NULL},
  4431. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "package"), UPB_TABVALUE_PTR_INIT(&fields[57]), NULL},
  4432. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[53]), &strentries[82]},
  4433. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[10]), NULL},
  4434. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "public_dependency"), UPB_TABVALUE_PTR_INIT(&fields[61]), &strentries[81]},
  4435. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4436. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "file"), UPB_TABVALUE_PTR_INIT(&fields[17]), NULL},
  4437. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4438. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4439. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[75]), NULL},
  4440. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4441. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "cc_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[2]), NULL},
  4442. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4443. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "java_multiple_files"), UPB_TABVALUE_PTR_INIT(&fields[24]), NULL},
  4444. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4445. {UPB_TABKEY_STR("\025", "\000", "\000", "\000", "java_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[23]), &strentries[102]},
  4446. {UPB_TABKEY_STR("\035", "\000", "\000", "\000", "java_generate_equals_and_hash"), UPB_TABVALUE_PTR_INIT(&fields[22]), NULL},
  4447. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4448. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4449. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4450. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "go_package"), UPB_TABVALUE_PTR_INIT(&fields[18]), NULL},
  4451. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "java_package"), UPB_TABVALUE_PTR_INIT(&fields[26]), NULL},
  4452. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "optimize_for"), UPB_TABVALUE_PTR_INIT(&fields[48]), NULL},
  4453. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "py_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[62]), NULL},
  4454. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "java_outer_classname"), UPB_TABVALUE_PTR_INIT(&fields[25]), NULL},
  4455. {UPB_TABKEY_STR("\027", "\000", "\000", "\000", "message_set_wire_format"), UPB_TABVALUE_PTR_INIT(&fields[31]), &strentries[106]},
  4456. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4457. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[76]), NULL},
  4458. {UPB_TABKEY_STR("\037", "\000", "\000", "\000", "no_standard_descriptor_accessor"), UPB_TABVALUE_PTR_INIT(&fields[45]), NULL},
  4459. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4460. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4461. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4462. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[39]), NULL},
  4463. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "input_type"), UPB_TABVALUE_PTR_INIT(&fields[20]), NULL},
  4464. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4465. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "output_type"), UPB_TABVALUE_PTR_INIT(&fields[56]), NULL},
  4466. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[55]), NULL},
  4467. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[74]), NULL},
  4468. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4469. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4470. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4471. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4472. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[54]), &strentries[122]},
  4473. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "method"), UPB_TABVALUE_PTR_INIT(&fields[33]), NULL},
  4474. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[35]), &strentries[121]},
  4475. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[72]), NULL},
  4476. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4477. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4478. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4479. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4480. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4481. {UPB_TABKEY_STR("\010", "\000", "\000", "\000", "location"), UPB_TABVALUE_PTR_INIT(&fields[30]), NULL},
  4482. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4483. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4484. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4485. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4486. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "span"), UPB_TABVALUE_PTR_INIT(&fields[65]), &strentries[139]},
  4487. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4488. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "trailing_comments"), UPB_TABVALUE_PTR_INIT(&fields[68]), NULL},
  4489. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "leading_comments"), UPB_TABVALUE_PTR_INIT(&fields[29]), &strentries[137]},
  4490. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "path"), UPB_TABVALUE_PTR_INIT(&fields[59]), NULL},
  4491. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "double_value"), UPB_TABVALUE_PTR_INIT(&fields[7]), NULL},
  4492. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4493. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4494. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[36]), NULL},
  4495. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4496. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4497. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4498. {UPB_TABKEY_STR("\022", "\000", "\000", "\000", "negative_int_value"), UPB_TABVALUE_PTR_INIT(&fields[43]), NULL},
  4499. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "aggregate_value"), UPB_TABVALUE_PTR_INIT(&fields[0]), NULL},
  4500. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4501. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4502. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4503. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4504. {UPB_TABKEY_STR("\022", "\000", "\000", "\000", "positive_int_value"), UPB_TABVALUE_PTR_INIT(&fields[60]), NULL},
  4505. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "identifier_value"), UPB_TABVALUE_PTR_INIT(&fields[19]), NULL},
  4506. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "string_value"), UPB_TABVALUE_PTR_INIT(&fields[67]), &strentries[154]},
  4507. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4508. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4509. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "is_extension"), UPB_TABVALUE_PTR_INIT(&fields[21]), NULL},
  4510. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "name_part"), UPB_TABVALUE_PTR_INIT(&fields[42]), NULL},
  4511. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_REQUIRED"), UPB_TABVALUE_INT_INIT(2), &strentries[162]},
  4512. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4513. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_REPEATED"), UPB_TABVALUE_INT_INIT(3), NULL},
  4514. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_OPTIONAL"), UPB_TABVALUE_INT_INIT(1), NULL},
  4515. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_FIXED64"), UPB_TABVALUE_INT_INIT(6), NULL},
  4516. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4517. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4518. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4519. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4520. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_STRING"), UPB_TABVALUE_INT_INIT(9), NULL},
  4521. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_FLOAT"), UPB_TABVALUE_INT_INIT(2), &strentries[193]},
  4522. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_DOUBLE"), UPB_TABVALUE_INT_INIT(1), NULL},
  4523. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4524. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_INT32"), UPB_TABVALUE_INT_INIT(5), NULL},
  4525. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "TYPE_SFIXED32"), UPB_TABVALUE_INT_INIT(15), NULL},
  4526. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_FIXED32"), UPB_TABVALUE_INT_INIT(7), NULL},
  4527. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4528. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_MESSAGE"), UPB_TABVALUE_INT_INIT(11), &strentries[194]},
  4529. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4530. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4531. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_INT64"), UPB_TABVALUE_INT_INIT(3), &strentries[191]},
  4532. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4533. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4534. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4535. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4536. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "TYPE_ENUM"), UPB_TABVALUE_INT_INIT(14), NULL},
  4537. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_UINT32"), UPB_TABVALUE_INT_INIT(13), NULL},
  4538. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4539. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_UINT64"), UPB_TABVALUE_INT_INIT(4), &strentries[190]},
  4540. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4541. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "TYPE_SFIXED64"), UPB_TABVALUE_INT_INIT(16), NULL},
  4542. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_BYTES"), UPB_TABVALUE_INT_INIT(12), NULL},
  4543. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_SINT64"), UPB_TABVALUE_INT_INIT(18), NULL},
  4544. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "TYPE_BOOL"), UPB_TABVALUE_INT_INIT(8), NULL},
  4545. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_GROUP"), UPB_TABVALUE_INT_INIT(10), NULL},
  4546. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_SINT32"), UPB_TABVALUE_INT_INIT(17), NULL},
  4547. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4548. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "CORD"), UPB_TABVALUE_INT_INIT(1), NULL},
  4549. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "STRING"), UPB_TABVALUE_INT_INIT(0), &strentries[197]},
  4550. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "STRING_PIECE"), UPB_TABVALUE_INT_INIT(2), NULL},
  4551. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "CODE_SIZE"), UPB_TABVALUE_INT_INIT(2), NULL},
  4552. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "SPEED"), UPB_TABVALUE_INT_INIT(1), &strentries[203]},
  4553. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4554. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "LITE_RUNTIME"), UPB_TABVALUE_INT_INIT(3), NULL},
  4555. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4556. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4557. {UPB_TABKEY_STR("\047", "\000", "\000", "\000", "google.protobuf.SourceCodeInfo.Location"), UPB_TABVALUE_PTR_INIT(&msgs[17]), NULL},
  4558. {UPB_TABKEY_STR("\043", "\000", "\000", "\000", "google.protobuf.UninterpretedOption"), UPB_TABVALUE_PTR_INIT(&msgs[18]), NULL},
  4559. {UPB_TABKEY_STR("\043", "\000", "\000", "\000", "google.protobuf.FileDescriptorProto"), UPB_TABVALUE_PTR_INIT(&msgs[8]), NULL},
  4560. {UPB_TABKEY_STR("\045", "\000", "\000", "\000", "google.protobuf.MethodDescriptorProto"), UPB_TABVALUE_PTR_INIT(&msgs[12]), NULL},
  4561. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4562. {UPB_TABKEY_STR("\040", "\000", "\000", "\000", "google.protobuf.EnumValueOptions"), UPB_TABVALUE_PTR_INIT(&msgs[5]), NULL},
  4563. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4564. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4565. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4566. {UPB_TABKEY_STR("\037", "\000", "\000", "\000", "google.protobuf.DescriptorProto"), UPB_TABVALUE_PTR_INIT(&msgs[0]), &strentries[228]},
  4567. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4568. {UPB_TABKEY_STR("\036", "\000", "\000", "\000", "google.protobuf.SourceCodeInfo"), UPB_TABVALUE_PTR_INIT(&msgs[16]), NULL},
  4569. {UPB_TABKEY_STR("\051", "\000", "\000", "\000", "google.protobuf.FieldDescriptorProto.Type"), UPB_TABVALUE_PTR_INIT(&enums[1]), NULL},
  4570. {UPB_TABKEY_STR("\056", "\000", "\000", "\000", "google.protobuf.DescriptorProto.ExtensionRange"), UPB_TABVALUE_PTR_INIT(&msgs[1]), NULL},
  4571. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4572. {UPB_TABKEY_STR("\050", "\000", "\000", "\000", "google.protobuf.EnumValueDescriptorProto"), UPB_TABVALUE_PTR_INIT(&msgs[4]), NULL},
  4573. {UPB_TABKEY_STR("\034", "\000", "\000", "\000", "google.protobuf.FieldOptions"), UPB_TABVALUE_PTR_INIT(&msgs[7]), NULL},
  4574. {UPB_TABKEY_STR("\033", "\000", "\000", "\000", "google.protobuf.FileOptions"), UPB_TABVALUE_PTR_INIT(&msgs[10]), NULL},
  4575. {UPB_TABKEY_STR("\043", "\000", "\000", "\000", "google.protobuf.EnumDescriptorProto"), UPB_TABVALUE_PTR_INIT(&msgs[2]), &strentries[233]},
  4576. {UPB_TABKEY_STR("\052", "\000", "\000", "\000", "google.protobuf.FieldDescriptorProto.Label"), UPB_TABVALUE_PTR_INIT(&enums[0]), NULL},
  4577. {UPB_TABKEY_STR("\046", "\000", "\000", "\000", "google.protobuf.ServiceDescriptorProto"), UPB_TABVALUE_PTR_INIT(&msgs[14]), NULL},
  4578. {UPB_TABKEY_STR("\042", "\000", "\000", "\000", "google.protobuf.FieldOptions.CType"), UPB_TABVALUE_PTR_INIT(&enums[2]), &strentries[229]},
  4579. {UPB_TABKEY_STR("\041", "\000", "\000", "\000", "google.protobuf.FileDescriptorSet"), UPB_TABVALUE_PTR_INIT(&msgs[9]), &strentries[235]},
  4580. {UPB_TABKEY_STR("\033", "\000", "\000", "\000", "google.protobuf.EnumOptions"), UPB_TABVALUE_PTR_INIT(&msgs[3]), NULL},
  4581. {UPB_TABKEY_STR("\044", "\000", "\000", "\000", "google.protobuf.FieldDescriptorProto"), UPB_TABVALUE_PTR_INIT(&msgs[6]), NULL},
  4582. {UPB_TABKEY_STR("\050", "\000", "\000", "\000", "google.protobuf.FileOptions.OptimizeMode"), UPB_TABVALUE_PTR_INIT(&enums[3]), &strentries[221]},
  4583. {UPB_TABKEY_STR("\036", "\000", "\000", "\000", "google.protobuf.ServiceOptions"), UPB_TABVALUE_PTR_INIT(&msgs[15]), NULL},
  4584. {UPB_TABKEY_STR("\036", "\000", "\000", "\000", "google.protobuf.MessageOptions"), UPB_TABVALUE_PTR_INIT(&msgs[11]), NULL},
  4585. {UPB_TABKEY_STR("\035", "\000", "\000", "\000", "google.protobuf.MethodOptions"), UPB_TABVALUE_PTR_INIT(&msgs[13]), &strentries[226]},
  4586. {UPB_TABKEY_STR("\054", "\000", "\000", "\000", "google.protobuf.UninterpretedOption.NamePart"), UPB_TABVALUE_PTR_INIT(&msgs[19]), NULL},
  4587. };
  4588. static const upb_tabent intentries[14] = {
  4589. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4590. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[73]), NULL},
  4591. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4592. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[71]), NULL},
  4593. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4594. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[77]), NULL},
  4595. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4596. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[75]), NULL},
  4597. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4598. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[76]), NULL},
  4599. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4600. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[74]), NULL},
  4601. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4602. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[72]), NULL},
  4603. };
  4604. static const upb_tabval arrays[232] = {
  4605. UPB_TABVALUE_EMPTY_INIT,
  4606. UPB_TABVALUE_PTR_INIT(&fields[38]),
  4607. UPB_TABVALUE_PTR_INIT(&fields[16]),
  4608. UPB_TABVALUE_PTR_INIT(&fields[44]),
  4609. UPB_TABVALUE_PTR_INIT(&fields[9]),
  4610. UPB_TABVALUE_PTR_INIT(&fields[15]),
  4611. UPB_TABVALUE_PTR_INIT(&fields[14]),
  4612. UPB_TABVALUE_PTR_INIT(&fields[49]),
  4613. UPB_TABVALUE_EMPTY_INIT,
  4614. UPB_TABVALUE_PTR_INIT(&fields[66]),
  4615. UPB_TABVALUE_PTR_INIT(&fields[8]),
  4616. UPB_TABVALUE_EMPTY_INIT,
  4617. UPB_TABVALUE_PTR_INIT(&fields[40]),
  4618. UPB_TABVALUE_PTR_INIT(&fields[78]),
  4619. UPB_TABVALUE_PTR_INIT(&fields[50]),
  4620. UPB_TABVALUE_EMPTY_INIT,
  4621. UPB_TABVALUE_EMPTY_INIT,
  4622. UPB_TABVALUE_PTR_INIT(&fields[1]),
  4623. UPB_TABVALUE_EMPTY_INIT,
  4624. UPB_TABVALUE_EMPTY_INIT,
  4625. UPB_TABVALUE_EMPTY_INIT,
  4626. UPB_TABVALUE_EMPTY_INIT,
  4627. UPB_TABVALUE_EMPTY_INIT,
  4628. UPB_TABVALUE_EMPTY_INIT,
  4629. UPB_TABVALUE_PTR_INIT(&fields[37]),
  4630. UPB_TABVALUE_PTR_INIT(&fields[47]),
  4631. UPB_TABVALUE_PTR_INIT(&fields[52]),
  4632. UPB_TABVALUE_EMPTY_INIT,
  4633. UPB_TABVALUE_EMPTY_INIT,
  4634. UPB_TABVALUE_EMPTY_INIT,
  4635. UPB_TABVALUE_EMPTY_INIT,
  4636. UPB_TABVALUE_EMPTY_INIT,
  4637. UPB_TABVALUE_PTR_INIT(&fields[41]),
  4638. UPB_TABVALUE_PTR_INIT(&fields[12]),
  4639. UPB_TABVALUE_PTR_INIT(&fields[46]),
  4640. UPB_TABVALUE_PTR_INIT(&fields[27]),
  4641. UPB_TABVALUE_PTR_INIT(&fields[69]),
  4642. UPB_TABVALUE_PTR_INIT(&fields[70]),
  4643. UPB_TABVALUE_PTR_INIT(&fields[4]),
  4644. UPB_TABVALUE_PTR_INIT(&fields[51]),
  4645. UPB_TABVALUE_EMPTY_INIT,
  4646. UPB_TABVALUE_PTR_INIT(&fields[3]),
  4647. UPB_TABVALUE_PTR_INIT(&fields[58]),
  4648. UPB_TABVALUE_PTR_INIT(&fields[6]),
  4649. UPB_TABVALUE_EMPTY_INIT,
  4650. UPB_TABVALUE_PTR_INIT(&fields[28]),
  4651. UPB_TABVALUE_EMPTY_INIT,
  4652. UPB_TABVALUE_EMPTY_INIT,
  4653. UPB_TABVALUE_EMPTY_INIT,
  4654. UPB_TABVALUE_PTR_INIT(&fields[11]),
  4655. UPB_TABVALUE_PTR_INIT(&fields[79]),
  4656. UPB_TABVALUE_EMPTY_INIT,
  4657. UPB_TABVALUE_EMPTY_INIT,
  4658. UPB_TABVALUE_EMPTY_INIT,
  4659. UPB_TABVALUE_EMPTY_INIT,
  4660. UPB_TABVALUE_EMPTY_INIT,
  4661. UPB_TABVALUE_EMPTY_INIT,
  4662. UPB_TABVALUE_EMPTY_INIT,
  4663. UPB_TABVALUE_EMPTY_INIT,
  4664. UPB_TABVALUE_EMPTY_INIT,
  4665. UPB_TABVALUE_EMPTY_INIT,
  4666. UPB_TABVALUE_EMPTY_INIT,
  4667. UPB_TABVALUE_EMPTY_INIT,
  4668. UPB_TABVALUE_EMPTY_INIT,
  4669. UPB_TABVALUE_EMPTY_INIT,
  4670. UPB_TABVALUE_EMPTY_INIT,
  4671. UPB_TABVALUE_EMPTY_INIT,
  4672. UPB_TABVALUE_EMPTY_INIT,
  4673. UPB_TABVALUE_EMPTY_INIT,
  4674. UPB_TABVALUE_EMPTY_INIT,
  4675. UPB_TABVALUE_EMPTY_INIT,
  4676. UPB_TABVALUE_EMPTY_INIT,
  4677. UPB_TABVALUE_EMPTY_INIT,
  4678. UPB_TABVALUE_PTR_INIT(&fields[34]),
  4679. UPB_TABVALUE_PTR_INIT(&fields[57]),
  4680. UPB_TABVALUE_PTR_INIT(&fields[5]),
  4681. UPB_TABVALUE_PTR_INIT(&fields[32]),
  4682. UPB_TABVALUE_PTR_INIT(&fields[10]),
  4683. UPB_TABVALUE_PTR_INIT(&fields[63]),
  4684. UPB_TABVALUE_PTR_INIT(&fields[13]),
  4685. UPB_TABVALUE_PTR_INIT(&fields[53]),
  4686. UPB_TABVALUE_PTR_INIT(&fields[64]),
  4687. UPB_TABVALUE_PTR_INIT(&fields[61]),
  4688. UPB_TABVALUE_PTR_INIT(&fields[80]),
  4689. UPB_TABVALUE_EMPTY_INIT,
  4690. UPB_TABVALUE_PTR_INIT(&fields[17]),
  4691. UPB_TABVALUE_EMPTY_INIT,
  4692. UPB_TABVALUE_PTR_INIT(&fields[26]),
  4693. UPB_TABVALUE_EMPTY_INIT,
  4694. UPB_TABVALUE_EMPTY_INIT,
  4695. UPB_TABVALUE_EMPTY_INIT,
  4696. UPB_TABVALUE_EMPTY_INIT,
  4697. UPB_TABVALUE_EMPTY_INIT,
  4698. UPB_TABVALUE_EMPTY_INIT,
  4699. UPB_TABVALUE_PTR_INIT(&fields[25]),
  4700. UPB_TABVALUE_PTR_INIT(&fields[48]),
  4701. UPB_TABVALUE_PTR_INIT(&fields[24]),
  4702. UPB_TABVALUE_PTR_INIT(&fields[18]),
  4703. UPB_TABVALUE_EMPTY_INIT,
  4704. UPB_TABVALUE_EMPTY_INIT,
  4705. UPB_TABVALUE_EMPTY_INIT,
  4706. UPB_TABVALUE_EMPTY_INIT,
  4707. UPB_TABVALUE_PTR_INIT(&fields[2]),
  4708. UPB_TABVALUE_PTR_INIT(&fields[23]),
  4709. UPB_TABVALUE_PTR_INIT(&fields[62]),
  4710. UPB_TABVALUE_EMPTY_INIT,
  4711. UPB_TABVALUE_PTR_INIT(&fields[22]),
  4712. UPB_TABVALUE_EMPTY_INIT,
  4713. UPB_TABVALUE_EMPTY_INIT,
  4714. UPB_TABVALUE_EMPTY_INIT,
  4715. UPB_TABVALUE_EMPTY_INIT,
  4716. UPB_TABVALUE_EMPTY_INIT,
  4717. UPB_TABVALUE_EMPTY_INIT,
  4718. UPB_TABVALUE_EMPTY_INIT,
  4719. UPB_TABVALUE_EMPTY_INIT,
  4720. UPB_TABVALUE_EMPTY_INIT,
  4721. UPB_TABVALUE_EMPTY_INIT,
  4722. UPB_TABVALUE_EMPTY_INIT,
  4723. UPB_TABVALUE_EMPTY_INIT,
  4724. UPB_TABVALUE_EMPTY_INIT,
  4725. UPB_TABVALUE_EMPTY_INIT,
  4726. UPB_TABVALUE_EMPTY_INIT,
  4727. UPB_TABVALUE_EMPTY_INIT,
  4728. UPB_TABVALUE_EMPTY_INIT,
  4729. UPB_TABVALUE_EMPTY_INIT,
  4730. UPB_TABVALUE_EMPTY_INIT,
  4731. UPB_TABVALUE_EMPTY_INIT,
  4732. UPB_TABVALUE_EMPTY_INIT,
  4733. UPB_TABVALUE_EMPTY_INIT,
  4734. UPB_TABVALUE_EMPTY_INIT,
  4735. UPB_TABVALUE_EMPTY_INIT,
  4736. UPB_TABVALUE_EMPTY_INIT,
  4737. UPB_TABVALUE_EMPTY_INIT,
  4738. UPB_TABVALUE_EMPTY_INIT,
  4739. UPB_TABVALUE_EMPTY_INIT,
  4740. UPB_TABVALUE_EMPTY_INIT,
  4741. UPB_TABVALUE_EMPTY_INIT,
  4742. UPB_TABVALUE_EMPTY_INIT,
  4743. UPB_TABVALUE_EMPTY_INIT,
  4744. UPB_TABVALUE_EMPTY_INIT,
  4745. UPB_TABVALUE_EMPTY_INIT,
  4746. UPB_TABVALUE_EMPTY_INIT,
  4747. UPB_TABVALUE_EMPTY_INIT,
  4748. UPB_TABVALUE_EMPTY_INIT,
  4749. UPB_TABVALUE_EMPTY_INIT,
  4750. UPB_TABVALUE_EMPTY_INIT,
  4751. UPB_TABVALUE_EMPTY_INIT,
  4752. UPB_TABVALUE_EMPTY_INIT,
  4753. UPB_TABVALUE_EMPTY_INIT,
  4754. UPB_TABVALUE_EMPTY_INIT,
  4755. UPB_TABVALUE_EMPTY_INIT,
  4756. UPB_TABVALUE_PTR_INIT(&fields[31]),
  4757. UPB_TABVALUE_PTR_INIT(&fields[45]),
  4758. UPB_TABVALUE_EMPTY_INIT,
  4759. UPB_TABVALUE_EMPTY_INIT,
  4760. UPB_TABVALUE_EMPTY_INIT,
  4761. UPB_TABVALUE_EMPTY_INIT,
  4762. UPB_TABVALUE_EMPTY_INIT,
  4763. UPB_TABVALUE_EMPTY_INIT,
  4764. UPB_TABVALUE_EMPTY_INIT,
  4765. UPB_TABVALUE_EMPTY_INIT,
  4766. UPB_TABVALUE_EMPTY_INIT,
  4767. UPB_TABVALUE_EMPTY_INIT,
  4768. UPB_TABVALUE_EMPTY_INIT,
  4769. UPB_TABVALUE_EMPTY_INIT,
  4770. UPB_TABVALUE_EMPTY_INIT,
  4771. UPB_TABVALUE_EMPTY_INIT,
  4772. UPB_TABVALUE_PTR_INIT(&fields[39]),
  4773. UPB_TABVALUE_PTR_INIT(&fields[20]),
  4774. UPB_TABVALUE_PTR_INIT(&fields[56]),
  4775. UPB_TABVALUE_PTR_INIT(&fields[55]),
  4776. UPB_TABVALUE_EMPTY_INIT,
  4777. UPB_TABVALUE_EMPTY_INIT,
  4778. UPB_TABVALUE_EMPTY_INIT,
  4779. UPB_TABVALUE_EMPTY_INIT,
  4780. UPB_TABVALUE_EMPTY_INIT,
  4781. UPB_TABVALUE_PTR_INIT(&fields[35]),
  4782. UPB_TABVALUE_PTR_INIT(&fields[33]),
  4783. UPB_TABVALUE_PTR_INIT(&fields[54]),
  4784. UPB_TABVALUE_EMPTY_INIT,
  4785. UPB_TABVALUE_EMPTY_INIT,
  4786. UPB_TABVALUE_EMPTY_INIT,
  4787. UPB_TABVALUE_EMPTY_INIT,
  4788. UPB_TABVALUE_EMPTY_INIT,
  4789. UPB_TABVALUE_PTR_INIT(&fields[30]),
  4790. UPB_TABVALUE_EMPTY_INIT,
  4791. UPB_TABVALUE_PTR_INIT(&fields[59]),
  4792. UPB_TABVALUE_PTR_INIT(&fields[65]),
  4793. UPB_TABVALUE_PTR_INIT(&fields[29]),
  4794. UPB_TABVALUE_PTR_INIT(&fields[68]),
  4795. UPB_TABVALUE_EMPTY_INIT,
  4796. UPB_TABVALUE_EMPTY_INIT,
  4797. UPB_TABVALUE_PTR_INIT(&fields[36]),
  4798. UPB_TABVALUE_PTR_INIT(&fields[19]),
  4799. UPB_TABVALUE_PTR_INIT(&fields[60]),
  4800. UPB_TABVALUE_PTR_INIT(&fields[43]),
  4801. UPB_TABVALUE_PTR_INIT(&fields[7]),
  4802. UPB_TABVALUE_PTR_INIT(&fields[67]),
  4803. UPB_TABVALUE_PTR_INIT(&fields[0]),
  4804. UPB_TABVALUE_EMPTY_INIT,
  4805. UPB_TABVALUE_PTR_INIT(&fields[42]),
  4806. UPB_TABVALUE_PTR_INIT(&fields[21]),
  4807. UPB_TABVALUE_EMPTY_INIT,
  4808. UPB_TABVALUE_PTR_INIT("LABEL_OPTIONAL"),
  4809. UPB_TABVALUE_PTR_INIT("LABEL_REQUIRED"),
  4810. UPB_TABVALUE_PTR_INIT("LABEL_REPEATED"),
  4811. UPB_TABVALUE_EMPTY_INIT,
  4812. UPB_TABVALUE_PTR_INIT("TYPE_DOUBLE"),
  4813. UPB_TABVALUE_PTR_INIT("TYPE_FLOAT"),
  4814. UPB_TABVALUE_PTR_INIT("TYPE_INT64"),
  4815. UPB_TABVALUE_PTR_INIT("TYPE_UINT64"),
  4816. UPB_TABVALUE_PTR_INIT("TYPE_INT32"),
  4817. UPB_TABVALUE_PTR_INIT("TYPE_FIXED64"),
  4818. UPB_TABVALUE_PTR_INIT("TYPE_FIXED32"),
  4819. UPB_TABVALUE_PTR_INIT("TYPE_BOOL"),
  4820. UPB_TABVALUE_PTR_INIT("TYPE_STRING"),
  4821. UPB_TABVALUE_PTR_INIT("TYPE_GROUP"),
  4822. UPB_TABVALUE_PTR_INIT("TYPE_MESSAGE"),
  4823. UPB_TABVALUE_PTR_INIT("TYPE_BYTES"),
  4824. UPB_TABVALUE_PTR_INIT("TYPE_UINT32"),
  4825. UPB_TABVALUE_PTR_INIT("TYPE_ENUM"),
  4826. UPB_TABVALUE_PTR_INIT("TYPE_SFIXED32"),
  4827. UPB_TABVALUE_PTR_INIT("TYPE_SFIXED64"),
  4828. UPB_TABVALUE_PTR_INIT("TYPE_SINT32"),
  4829. UPB_TABVALUE_PTR_INIT("TYPE_SINT64"),
  4830. UPB_TABVALUE_PTR_INIT("STRING"),
  4831. UPB_TABVALUE_PTR_INIT("CORD"),
  4832. UPB_TABVALUE_PTR_INIT("STRING_PIECE"),
  4833. UPB_TABVALUE_EMPTY_INIT,
  4834. UPB_TABVALUE_PTR_INIT("SPEED"),
  4835. UPB_TABVALUE_PTR_INIT("CODE_SIZE"),
  4836. UPB_TABVALUE_PTR_INIT("LITE_RUNTIME"),
  4837. };
  4838. static const upb_symtab symtab = UPB_SYMTAB_INIT(UPB_STRTABLE_INIT(24, 31, UPB_CTYPE_PTR, 5, &strentries[204]), &reftables[210], &reftables[211]);
  4839. const upb_symtab *upbdefs_google_protobuf_descriptor(const void *owner) {
  4840. upb_symtab_ref(&symtab, owner);
  4841. return &symtab;
  4842. }
  4843. #ifdef UPB_DEBUG_REFS
  4844. static upb_inttable reftables[212] = {
  4845. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4846. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4847. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4848. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4849. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4850. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4851. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4852. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4853. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4854. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4855. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4856. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4857. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4858. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4859. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4860. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4861. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4862. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4863. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4864. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4865. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4866. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4867. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4868. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4869. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4870. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4871. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4872. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4873. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4874. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4875. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4876. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4877. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4878. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4879. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4880. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4881. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4882. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4883. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4884. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4885. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4886. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4887. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4888. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4889. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4890. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4891. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4892. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4893. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4894. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4895. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4896. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4897. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4898. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4899. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4900. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4901. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4902. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4903. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4904. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4905. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4906. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4907. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4908. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4909. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4910. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4911. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4912. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4913. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4914. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4915. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4916. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4917. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4918. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4919. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4920. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4921. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4922. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4923. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4924. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4925. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4926. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4927. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4928. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4929. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4930. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4931. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4932. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4933. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4934. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4935. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4936. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4937. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4938. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4939. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4940. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4941. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4942. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4943. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4944. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4945. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4946. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4947. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4948. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4949. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4950. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4951. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4952. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4953. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4954. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4955. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4956. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4957. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4958. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4959. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4960. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4961. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4962. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4963. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4964. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4965. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4966. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4967. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4968. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4969. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4970. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4971. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4972. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4973. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4974. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4975. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4976. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4977. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4978. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4979. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4980. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4981. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4982. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4983. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4984. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4985. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4986. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4987. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4988. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4989. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4990. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4991. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4992. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4993. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4994. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4995. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4996. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4997. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4998. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4999. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5000. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5001. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5002. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5003. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5004. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5005. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5006. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5007. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5008. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5009. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5010. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5011. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5012. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5013. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5014. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5015. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5016. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5017. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5018. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5019. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5020. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5021. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5022. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5023. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5024. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5025. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5026. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5027. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5028. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5029. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5030. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5031. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5032. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5033. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5034. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5035. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5036. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5037. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5038. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5039. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5040. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5041. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5042. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5043. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5044. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5045. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5046. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5047. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5048. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5049. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5050. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5051. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5052. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5053. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5054. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5055. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5056. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5057. };
  5058. #endif
  5059. /*
  5060. ** XXX: The routines in this file that consume a string do not currently
  5061. ** support having the string span buffers. In the future, as upb_sink and
  5062. ** its buffering/sharing functionality evolve there should be an easy and
  5063. ** idiomatic way of correctly handling this case. For now, we accept this
  5064. ** limitation since we currently only parse descriptors from single strings.
  5065. */
  5066. #include <errno.h>
  5067. #include <stdlib.h>
  5068. #include <string.h>
  5069. /* upb_deflist is an internal-only dynamic array for storing a growing list of
  5070. * upb_defs. */
  5071. typedef struct {
  5072. upb_def **defs;
  5073. size_t len;
  5074. size_t size;
  5075. bool owned;
  5076. } upb_deflist;
  5077. /* We keep a stack of all the messages scopes we are currently in, as well as
  5078. * the top-level file scope. This is necessary to correctly qualify the
  5079. * definitions that are contained inside. "name" tracks the name of the
  5080. * message or package (a bare name -- not qualified by any enclosing scopes). */
  5081. typedef struct {
  5082. char *name;
  5083. /* Index of the first def that is under this scope. For msgdefs, the
  5084. * msgdef itself is at start-1. */
  5085. int start;
  5086. } upb_descreader_frame;
  5087. /* The maximum number of nested declarations that are allowed, ie.
  5088. * message Foo {
  5089. * message Bar {
  5090. * message Baz {
  5091. * }
  5092. * }
  5093. * }
  5094. *
  5095. * This is a resource limit that affects how big our runtime stack can grow.
  5096. * TODO: make this a runtime-settable property of the Reader instance. */
  5097. #define UPB_MAX_MESSAGE_NESTING 64
  5098. struct upb_descreader {
  5099. upb_sink sink;
  5100. upb_deflist defs;
  5101. upb_descreader_frame stack[UPB_MAX_MESSAGE_NESTING];
  5102. int stack_len;
  5103. uint32_t number;
  5104. char *name;
  5105. bool saw_number;
  5106. bool saw_name;
  5107. char *default_string;
  5108. upb_fielddef *f;
  5109. };
  5110. static char *upb_strndup(const char *buf, size_t n) {
  5111. char *ret = malloc(n + 1);
  5112. if (!ret) return NULL;
  5113. memcpy(ret, buf, n);
  5114. ret[n] = '\0';
  5115. return ret;
  5116. }
  5117. /* Returns a newly allocated string that joins input strings together, for
  5118. * example:
  5119. * join("Foo.Bar", "Baz") -> "Foo.Bar.Baz"
  5120. * join("", "Baz") -> "Baz"
  5121. * Caller owns a ref on the returned string. */
  5122. static char *upb_join(const char *base, const char *name) {
  5123. if (!base || strlen(base) == 0) {
  5124. return upb_strdup(name);
  5125. } else {
  5126. char *ret = malloc(strlen(base) + strlen(name) + 2);
  5127. ret[0] = '\0';
  5128. strcat(ret, base);
  5129. strcat(ret, ".");
  5130. strcat(ret, name);
  5131. return ret;
  5132. }
  5133. }
  5134. /* upb_deflist ****************************************************************/
  5135. void upb_deflist_init(upb_deflist *l) {
  5136. l->size = 0;
  5137. l->defs = NULL;
  5138. l->len = 0;
  5139. l->owned = true;
  5140. }
  5141. void upb_deflist_uninit(upb_deflist *l) {
  5142. size_t i;
  5143. if (l->owned)
  5144. for(i = 0; i < l->len; i++)
  5145. upb_def_unref(l->defs[i], l);
  5146. free(l->defs);
  5147. }
  5148. bool upb_deflist_push(upb_deflist *l, upb_def *d) {
  5149. if(++l->len >= l->size) {
  5150. size_t new_size = UPB_MAX(l->size, 4);
  5151. new_size *= 2;
  5152. l->defs = realloc(l->defs, new_size * sizeof(void *));
  5153. if (!l->defs) return false;
  5154. l->size = new_size;
  5155. }
  5156. l->defs[l->len - 1] = d;
  5157. return true;
  5158. }
  5159. void upb_deflist_donaterefs(upb_deflist *l, void *owner) {
  5160. size_t i;
  5161. assert(l->owned);
  5162. for (i = 0; i < l->len; i++)
  5163. upb_def_donateref(l->defs[i], l, owner);
  5164. l->owned = false;
  5165. }
  5166. static upb_def *upb_deflist_last(upb_deflist *l) {
  5167. return l->defs[l->len-1];
  5168. }
  5169. /* Qualify the defname for all defs starting with offset "start" with "str". */
  5170. static void upb_deflist_qualify(upb_deflist *l, char *str, int32_t start) {
  5171. uint32_t i;
  5172. for (i = start; i < l->len; i++) {
  5173. upb_def *def = l->defs[i];
  5174. char *name = upb_join(str, upb_def_fullname(def));
  5175. upb_def_setfullname(def, name, NULL);
  5176. free(name);
  5177. }
  5178. }
  5179. /* upb_descreader ************************************************************/
  5180. static upb_msgdef *upb_descreader_top(upb_descreader *r) {
  5181. int index;
  5182. assert(r->stack_len > 1);
  5183. index = r->stack[r->stack_len-1].start - 1;
  5184. assert(index >= 0);
  5185. return upb_downcast_msgdef_mutable(r->defs.defs[index]);
  5186. }
  5187. static upb_def *upb_descreader_last(upb_descreader *r) {
  5188. return upb_deflist_last(&r->defs);
  5189. }
  5190. /* Start/end handlers for FileDescriptorProto and DescriptorProto (the two
  5191. * entities that have names and can contain sub-definitions. */
  5192. void upb_descreader_startcontainer(upb_descreader *r) {
  5193. upb_descreader_frame *f = &r->stack[r->stack_len++];
  5194. f->start = r->defs.len;
  5195. f->name = NULL;
  5196. }
  5197. void upb_descreader_endcontainer(upb_descreader *r) {
  5198. upb_descreader_frame *f = &r->stack[--r->stack_len];
  5199. upb_deflist_qualify(&r->defs, f->name, f->start);
  5200. free(f->name);
  5201. f->name = NULL;
  5202. }
  5203. void upb_descreader_setscopename(upb_descreader *r, char *str) {
  5204. upb_descreader_frame *f = &r->stack[r->stack_len-1];
  5205. free(f->name);
  5206. f->name = str;
  5207. }
  5208. /* Handlers for google.protobuf.FileDescriptorProto. */
  5209. static bool file_startmsg(void *r, const void *hd) {
  5210. UPB_UNUSED(hd);
  5211. upb_descreader_startcontainer(r);
  5212. return true;
  5213. }
  5214. static bool file_endmsg(void *closure, const void *hd, upb_status *status) {
  5215. upb_descreader *r = closure;
  5216. UPB_UNUSED(hd);
  5217. UPB_UNUSED(status);
  5218. upb_descreader_endcontainer(r);
  5219. return true;
  5220. }
  5221. static size_t file_onpackage(void *closure, const void *hd, const char *buf,
  5222. size_t n, const upb_bufhandle *handle) {
  5223. upb_descreader *r = closure;
  5224. UPB_UNUSED(hd);
  5225. UPB_UNUSED(handle);
  5226. /* XXX: see comment at the top of the file. */
  5227. upb_descreader_setscopename(r, upb_strndup(buf, n));
  5228. return n;
  5229. }
  5230. /* Handlers for google.protobuf.EnumValueDescriptorProto. */
  5231. static bool enumval_startmsg(void *closure, const void *hd) {
  5232. upb_descreader *r = closure;
  5233. UPB_UNUSED(hd);
  5234. r->saw_number = false;
  5235. r->saw_name = false;
  5236. return true;
  5237. }
  5238. static size_t enumval_onname(void *closure, const void *hd, const char *buf,
  5239. size_t n, const upb_bufhandle *handle) {
  5240. upb_descreader *r = closure;
  5241. UPB_UNUSED(hd);
  5242. UPB_UNUSED(handle);
  5243. /* XXX: see comment at the top of the file. */
  5244. free(r->name);
  5245. r->name = upb_strndup(buf, n);
  5246. r->saw_name = true;
  5247. return n;
  5248. }
  5249. static bool enumval_onnumber(void *closure, const void *hd, int32_t val) {
  5250. upb_descreader *r = closure;
  5251. UPB_UNUSED(hd);
  5252. r->number = val;
  5253. r->saw_number = true;
  5254. return true;
  5255. }
  5256. static bool enumval_endmsg(void *closure, const void *hd, upb_status *status) {
  5257. upb_descreader *r = closure;
  5258. upb_enumdef *e;
  5259. UPB_UNUSED(hd);
  5260. if(!r->saw_number || !r->saw_name) {
  5261. upb_status_seterrmsg(status, "Enum value missing name or number.");
  5262. return false;
  5263. }
  5264. e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  5265. upb_enumdef_addval(e, r->name, r->number, status);
  5266. free(r->name);
  5267. r->name = NULL;
  5268. return true;
  5269. }
  5270. /* Handlers for google.protobuf.EnumDescriptorProto. */
  5271. static bool enum_startmsg(void *closure, const void *hd) {
  5272. upb_descreader *r = closure;
  5273. UPB_UNUSED(hd);
  5274. upb_deflist_push(&r->defs,
  5275. upb_enumdef_upcast_mutable(upb_enumdef_new(&r->defs)));
  5276. return true;
  5277. }
  5278. static bool enum_endmsg(void *closure, const void *hd, upb_status *status) {
  5279. upb_descreader *r = closure;
  5280. upb_enumdef *e;
  5281. UPB_UNUSED(hd);
  5282. e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  5283. if (upb_def_fullname(upb_descreader_last(r)) == NULL) {
  5284. upb_status_seterrmsg(status, "Enum had no name.");
  5285. return false;
  5286. }
  5287. if (upb_enumdef_numvals(e) == 0) {
  5288. upb_status_seterrmsg(status, "Enum had no values.");
  5289. return false;
  5290. }
  5291. return true;
  5292. }
  5293. static size_t enum_onname(void *closure, const void *hd, const char *buf,
  5294. size_t n, const upb_bufhandle *handle) {
  5295. upb_descreader *r = closure;
  5296. char *fullname = upb_strndup(buf, n);
  5297. UPB_UNUSED(hd);
  5298. UPB_UNUSED(handle);
  5299. /* XXX: see comment at the top of the file. */
  5300. upb_def_setfullname(upb_descreader_last(r), fullname, NULL);
  5301. free(fullname);
  5302. return n;
  5303. }
  5304. /* Handlers for google.protobuf.FieldDescriptorProto */
  5305. static bool field_startmsg(void *closure, const void *hd) {
  5306. upb_descreader *r = closure;
  5307. UPB_UNUSED(hd);
  5308. r->f = upb_fielddef_new(&r->defs);
  5309. free(r->default_string);
  5310. r->default_string = NULL;
  5311. /* fielddefs default to packed, but descriptors default to non-packed. */
  5312. upb_fielddef_setpacked(r->f, false);
  5313. return true;
  5314. }
  5315. /* Converts the default value in string "str" into "d". Passes a ref on str.
  5316. * Returns true on success. */
  5317. static bool parse_default(char *str, upb_fielddef *f) {
  5318. bool success = true;
  5319. char *end;
  5320. switch (upb_fielddef_type(f)) {
  5321. case UPB_TYPE_INT32: {
  5322. long val = strtol(str, &end, 0);
  5323. if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || *end)
  5324. success = false;
  5325. else
  5326. upb_fielddef_setdefaultint32(f, val);
  5327. break;
  5328. }
  5329. case UPB_TYPE_INT64: {
  5330. /* XXX: Need to write our own strtoll, since it's not available in c89. */
  5331. long long val = strtol(str, &end, 0);
  5332. if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || *end)
  5333. success = false;
  5334. else
  5335. upb_fielddef_setdefaultint64(f, val);
  5336. break;
  5337. }
  5338. case UPB_TYPE_UINT32: {
  5339. unsigned long val = strtoul(str, &end, 0);
  5340. if (val > UINT32_MAX || errno == ERANGE || *end)
  5341. success = false;
  5342. else
  5343. upb_fielddef_setdefaultuint32(f, val);
  5344. break;
  5345. }
  5346. case UPB_TYPE_UINT64: {
  5347. /* XXX: Need to write our own strtoull, since it's not available in c89. */
  5348. unsigned long long val = strtoul(str, &end, 0);
  5349. if (val > UINT64_MAX || errno == ERANGE || *end)
  5350. success = false;
  5351. else
  5352. upb_fielddef_setdefaultuint64(f, val);
  5353. break;
  5354. }
  5355. case UPB_TYPE_DOUBLE: {
  5356. double val = strtod(str, &end);
  5357. if (errno == ERANGE || *end)
  5358. success = false;
  5359. else
  5360. upb_fielddef_setdefaultdouble(f, val);
  5361. break;
  5362. }
  5363. case UPB_TYPE_FLOAT: {
  5364. /* XXX: Need to write our own strtof, since it's not available in c89. */
  5365. float val = strtod(str, &end);
  5366. if (errno == ERANGE || *end)
  5367. success = false;
  5368. else
  5369. upb_fielddef_setdefaultfloat(f, val);
  5370. break;
  5371. }
  5372. case UPB_TYPE_BOOL: {
  5373. if (strcmp(str, "false") == 0)
  5374. upb_fielddef_setdefaultbool(f, false);
  5375. else if (strcmp(str, "true") == 0)
  5376. upb_fielddef_setdefaultbool(f, true);
  5377. else
  5378. success = false;
  5379. break;
  5380. }
  5381. default: abort();
  5382. }
  5383. return success;
  5384. }
  5385. static bool field_endmsg(void *closure, const void *hd, upb_status *status) {
  5386. upb_descreader *r = closure;
  5387. upb_fielddef *f = r->f;
  5388. UPB_UNUSED(hd);
  5389. /* TODO: verify that all required fields were present. */
  5390. assert(upb_fielddef_number(f) != 0);
  5391. assert(upb_fielddef_name(f) != NULL);
  5392. assert((upb_fielddef_subdefname(f) != NULL) == upb_fielddef_hassubdef(f));
  5393. if (r->default_string) {
  5394. if (upb_fielddef_issubmsg(f)) {
  5395. upb_status_seterrmsg(status, "Submessages cannot have defaults.");
  5396. return false;
  5397. }
  5398. if (upb_fielddef_isstring(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  5399. upb_fielddef_setdefaultcstr(f, r->default_string, NULL);
  5400. } else {
  5401. if (r->default_string && !parse_default(r->default_string, f)) {
  5402. /* We don't worry too much about giving a great error message since the
  5403. * compiler should have ensured this was correct. */
  5404. upb_status_seterrmsg(status, "Error converting default value.");
  5405. return false;
  5406. }
  5407. }
  5408. }
  5409. return true;
  5410. }
  5411. static bool field_onlazy(void *closure, const void *hd, bool val) {
  5412. upb_descreader *r = closure;
  5413. UPB_UNUSED(hd);
  5414. upb_fielddef_setlazy(r->f, val);
  5415. return true;
  5416. }
  5417. static bool field_onpacked(void *closure, const void *hd, bool val) {
  5418. upb_descreader *r = closure;
  5419. UPB_UNUSED(hd);
  5420. upb_fielddef_setpacked(r->f, val);
  5421. return true;
  5422. }
  5423. static bool field_ontype(void *closure, const void *hd, int32_t val) {
  5424. upb_descreader *r = closure;
  5425. UPB_UNUSED(hd);
  5426. upb_fielddef_setdescriptortype(r->f, val);
  5427. return true;
  5428. }
  5429. static bool field_onlabel(void *closure, const void *hd, int32_t val) {
  5430. upb_descreader *r = closure;
  5431. UPB_UNUSED(hd);
  5432. upb_fielddef_setlabel(r->f, val);
  5433. return true;
  5434. }
  5435. static bool field_onnumber(void *closure, const void *hd, int32_t val) {
  5436. upb_descreader *r = closure;
  5437. bool ok = upb_fielddef_setnumber(r->f, val, NULL);
  5438. UPB_UNUSED(hd);
  5439. UPB_ASSERT_VAR(ok, ok);
  5440. return true;
  5441. }
  5442. static size_t field_onname(void *closure, const void *hd, const char *buf,
  5443. size_t n, const upb_bufhandle *handle) {
  5444. upb_descreader *r = closure;
  5445. char *name = upb_strndup(buf, n);
  5446. UPB_UNUSED(hd);
  5447. UPB_UNUSED(handle);
  5448. /* XXX: see comment at the top of the file. */
  5449. upb_fielddef_setname(r->f, name, NULL);
  5450. free(name);
  5451. return n;
  5452. }
  5453. static size_t field_ontypename(void *closure, const void *hd, const char *buf,
  5454. size_t n, const upb_bufhandle *handle) {
  5455. upb_descreader *r = closure;
  5456. char *name = upb_strndup(buf, n);
  5457. UPB_UNUSED(hd);
  5458. UPB_UNUSED(handle);
  5459. /* XXX: see comment at the top of the file. */
  5460. upb_fielddef_setsubdefname(r->f, name, NULL);
  5461. free(name);
  5462. return n;
  5463. }
  5464. static size_t field_onextendee(void *closure, const void *hd, const char *buf,
  5465. size_t n, const upb_bufhandle *handle) {
  5466. upb_descreader *r = closure;
  5467. char *name = upb_strndup(buf, n);
  5468. UPB_UNUSED(hd);
  5469. UPB_UNUSED(handle);
  5470. /* XXX: see comment at the top of the file. */
  5471. upb_fielddef_setcontainingtypename(r->f, name, NULL);
  5472. free(name);
  5473. return n;
  5474. }
  5475. static size_t field_ondefaultval(void *closure, const void *hd, const char *buf,
  5476. size_t n, const upb_bufhandle *handle) {
  5477. upb_descreader *r = closure;
  5478. UPB_UNUSED(hd);
  5479. UPB_UNUSED(handle);
  5480. /* Have to convert from string to the correct type, but we might not know the
  5481. * type yet, so we save it as a string until the end of the field.
  5482. * XXX: see comment at the top of the file. */
  5483. free(r->default_string);
  5484. r->default_string = upb_strndup(buf, n);
  5485. return n;
  5486. }
  5487. /* Handlers for google.protobuf.DescriptorProto (representing a message). */
  5488. static bool msg_startmsg(void *closure, const void *hd) {
  5489. upb_descreader *r = closure;
  5490. UPB_UNUSED(hd);
  5491. upb_deflist_push(&r->defs,
  5492. upb_msgdef_upcast_mutable(upb_msgdef_new(&r->defs)));
  5493. upb_descreader_startcontainer(r);
  5494. return true;
  5495. }
  5496. static bool msg_endmsg(void *closure, const void *hd, upb_status *status) {
  5497. upb_descreader *r = closure;
  5498. upb_msgdef *m = upb_descreader_top(r);
  5499. UPB_UNUSED(hd);
  5500. if(!upb_def_fullname(upb_msgdef_upcast_mutable(m))) {
  5501. upb_status_seterrmsg(status, "Encountered message with no name.");
  5502. return false;
  5503. }
  5504. upb_descreader_endcontainer(r);
  5505. return true;
  5506. }
  5507. static size_t msg_onname(void *closure, const void *hd, const char *buf,
  5508. size_t n, const upb_bufhandle *handle) {
  5509. upb_descreader *r = closure;
  5510. upb_msgdef *m = upb_descreader_top(r);
  5511. /* XXX: see comment at the top of the file. */
  5512. char *name = upb_strndup(buf, n);
  5513. UPB_UNUSED(hd);
  5514. UPB_UNUSED(handle);
  5515. upb_def_setfullname(upb_msgdef_upcast_mutable(m), name, NULL);
  5516. upb_descreader_setscopename(r, name); /* Passes ownership of name. */
  5517. return n;
  5518. }
  5519. static bool msg_onendfield(void *closure, const void *hd) {
  5520. upb_descreader *r = closure;
  5521. upb_msgdef *m = upb_descreader_top(r);
  5522. UPB_UNUSED(hd);
  5523. upb_msgdef_addfield(m, r->f, &r->defs, NULL);
  5524. r->f = NULL;
  5525. return true;
  5526. }
  5527. static bool pushextension(void *closure, const void *hd) {
  5528. upb_descreader *r = closure;
  5529. UPB_UNUSED(hd);
  5530. assert(upb_fielddef_containingtypename(r->f));
  5531. upb_fielddef_setisextension(r->f, true);
  5532. upb_deflist_push(&r->defs, upb_fielddef_upcast_mutable(r->f));
  5533. r->f = NULL;
  5534. return true;
  5535. }
  5536. #define D(name) upbdefs_google_protobuf_ ## name(s)
  5537. static void reghandlers(const void *closure, upb_handlers *h) {
  5538. const upb_symtab *s = closure;
  5539. const upb_msgdef *m = upb_handlers_msgdef(h);
  5540. if (m == D(DescriptorProto)) {
  5541. upb_handlers_setstartmsg(h, &msg_startmsg, NULL);
  5542. upb_handlers_setendmsg(h, &msg_endmsg, NULL);
  5543. upb_handlers_setstring(h, D(DescriptorProto_name), &msg_onname, NULL);
  5544. upb_handlers_setendsubmsg(h, D(DescriptorProto_field), &msg_onendfield,
  5545. NULL);
  5546. upb_handlers_setendsubmsg(h, D(DescriptorProto_extension), &pushextension,
  5547. NULL);
  5548. } else if (m == D(FileDescriptorProto)) {
  5549. upb_handlers_setstartmsg(h, &file_startmsg, NULL);
  5550. upb_handlers_setendmsg(h, &file_endmsg, NULL);
  5551. upb_handlers_setstring(h, D(FileDescriptorProto_package), &file_onpackage,
  5552. NULL);
  5553. upb_handlers_setendsubmsg(h, D(FileDescriptorProto_extension), &pushextension,
  5554. NULL);
  5555. } else if (m == D(EnumValueDescriptorProto)) {
  5556. upb_handlers_setstartmsg(h, &enumval_startmsg, NULL);
  5557. upb_handlers_setendmsg(h, &enumval_endmsg, NULL);
  5558. upb_handlers_setstring(h, D(EnumValueDescriptorProto_name), &enumval_onname, NULL);
  5559. upb_handlers_setint32(h, D(EnumValueDescriptorProto_number), &enumval_onnumber,
  5560. NULL);
  5561. } else if (m == D(EnumDescriptorProto)) {
  5562. upb_handlers_setstartmsg(h, &enum_startmsg, NULL);
  5563. upb_handlers_setendmsg(h, &enum_endmsg, NULL);
  5564. upb_handlers_setstring(h, D(EnumDescriptorProto_name), &enum_onname, NULL);
  5565. } else if (m == D(FieldDescriptorProto)) {
  5566. upb_handlers_setstartmsg(h, &field_startmsg, NULL);
  5567. upb_handlers_setendmsg(h, &field_endmsg, NULL);
  5568. upb_handlers_setint32(h, D(FieldDescriptorProto_type), &field_ontype,
  5569. NULL);
  5570. upb_handlers_setint32(h, D(FieldDescriptorProto_label), &field_onlabel,
  5571. NULL);
  5572. upb_handlers_setint32(h, D(FieldDescriptorProto_number), &field_onnumber,
  5573. NULL);
  5574. upb_handlers_setstring(h, D(FieldDescriptorProto_name), &field_onname,
  5575. NULL);
  5576. upb_handlers_setstring(h, D(FieldDescriptorProto_type_name),
  5577. &field_ontypename, NULL);
  5578. upb_handlers_setstring(h, D(FieldDescriptorProto_extendee),
  5579. &field_onextendee, NULL);
  5580. upb_handlers_setstring(h, D(FieldDescriptorProto_default_value),
  5581. &field_ondefaultval, NULL);
  5582. } else if (m == D(FieldOptions)) {
  5583. upb_handlers_setbool(h, D(FieldOptions_lazy), &field_onlazy, NULL);
  5584. upb_handlers_setbool(h, D(FieldOptions_packed), &field_onpacked, NULL);
  5585. }
  5586. }
  5587. #undef D
  5588. void descreader_cleanup(void *_r) {
  5589. upb_descreader *r = _r;
  5590. free(r->name);
  5591. upb_deflist_uninit(&r->defs);
  5592. free(r->default_string);
  5593. while (r->stack_len > 0) {
  5594. upb_descreader_frame *f = &r->stack[--r->stack_len];
  5595. free(f->name);
  5596. }
  5597. }
  5598. /* Public API ****************************************************************/
  5599. upb_descreader *upb_descreader_create(upb_env *e, const upb_handlers *h) {
  5600. upb_descreader *r = upb_env_malloc(e, sizeof(upb_descreader));
  5601. if (!r || !upb_env_addcleanup(e, descreader_cleanup, r)) {
  5602. return NULL;
  5603. }
  5604. upb_deflist_init(&r->defs);
  5605. upb_sink_reset(upb_descreader_input(r), h, r);
  5606. r->stack_len = 0;
  5607. r->name = NULL;
  5608. r->default_string = NULL;
  5609. return r;
  5610. }
  5611. upb_def **upb_descreader_getdefs(upb_descreader *r, void *owner, int *n) {
  5612. *n = r->defs.len;
  5613. upb_deflist_donaterefs(&r->defs, owner);
  5614. return r->defs.defs;
  5615. }
  5616. upb_sink *upb_descreader_input(upb_descreader *r) {
  5617. return &r->sink;
  5618. }
  5619. const upb_handlers *upb_descreader_newhandlers(const void *owner) {
  5620. const upb_symtab *s = upbdefs_google_protobuf_descriptor(&s);
  5621. const upb_handlers *h = upb_handlers_newfrozen(
  5622. upbdefs_google_protobuf_FileDescriptorSet(s), owner, reghandlers, s);
  5623. upb_symtab_unref(s, &s);
  5624. return h;
  5625. }
  5626. /*
  5627. ** protobuf decoder bytecode compiler
  5628. **
  5629. ** Code to compile a upb::Handlers into bytecode for decoding a protobuf
  5630. ** according to that specific schema and destination handlers.
  5631. **
  5632. ** Compiling to bytecode is always the first step. If we are using the
  5633. ** interpreted decoder we leave it as bytecode and interpret that. If we are
  5634. ** using a JIT decoder we use a code generator to turn the bytecode into native
  5635. ** code, LLVM IR, etc.
  5636. **
  5637. ** Bytecode definition is in decoder.int.h.
  5638. */
  5639. #include <stdarg.h>
  5640. #ifdef UPB_DUMP_BYTECODE
  5641. #include <stdio.h>
  5642. #endif
  5643. #define MAXLABEL 5
  5644. #define EMPTYLABEL -1
  5645. /* mgroup *********************************************************************/
  5646. static void freegroup(upb_refcounted *r) {
  5647. mgroup *g = (mgroup*)r;
  5648. upb_inttable_uninit(&g->methods);
  5649. #ifdef UPB_USE_JIT_X64
  5650. upb_pbdecoder_freejit(g);
  5651. #endif
  5652. free(g->bytecode);
  5653. free(g);
  5654. }
  5655. static void visitgroup(const upb_refcounted *r, upb_refcounted_visit *visit,
  5656. void *closure) {
  5657. const mgroup *g = (const mgroup*)r;
  5658. upb_inttable_iter i;
  5659. upb_inttable_begin(&i, &g->methods);
  5660. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5661. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  5662. visit(r, upb_pbdecodermethod_upcast(method), closure);
  5663. }
  5664. }
  5665. mgroup *newgroup(const void *owner) {
  5666. mgroup *g = malloc(sizeof(*g));
  5667. static const struct upb_refcounted_vtbl vtbl = {visitgroup, freegroup};
  5668. upb_refcounted_init(mgroup_upcast_mutable(g), &vtbl, owner);
  5669. upb_inttable_init(&g->methods, UPB_CTYPE_PTR);
  5670. g->bytecode = NULL;
  5671. g->bytecode_end = NULL;
  5672. return g;
  5673. }
  5674. /* upb_pbdecodermethod ********************************************************/
  5675. static void freemethod(upb_refcounted *r) {
  5676. upb_pbdecodermethod *method = (upb_pbdecodermethod*)r;
  5677. if (method->dest_handlers_) {
  5678. upb_handlers_unref(method->dest_handlers_, method);
  5679. }
  5680. upb_inttable_uninit(&method->dispatch);
  5681. free(method);
  5682. }
  5683. static void visitmethod(const upb_refcounted *r, upb_refcounted_visit *visit,
  5684. void *closure) {
  5685. const upb_pbdecodermethod *m = (const upb_pbdecodermethod*)r;
  5686. visit(r, m->group, closure);
  5687. }
  5688. static upb_pbdecodermethod *newmethod(const upb_handlers *dest_handlers,
  5689. mgroup *group) {
  5690. static const struct upb_refcounted_vtbl vtbl = {visitmethod, freemethod};
  5691. upb_pbdecodermethod *ret = malloc(sizeof(*ret));
  5692. upb_refcounted_init(upb_pbdecodermethod_upcast_mutable(ret), &vtbl, &ret);
  5693. upb_byteshandler_init(&ret->input_handler_);
  5694. /* The method references the group and vice-versa, in a circular reference. */
  5695. upb_ref2(ret, group);
  5696. upb_ref2(group, ret);
  5697. upb_inttable_insertptr(&group->methods, dest_handlers, upb_value_ptr(ret));
  5698. upb_pbdecodermethod_unref(ret, &ret);
  5699. ret->group = mgroup_upcast_mutable(group);
  5700. ret->dest_handlers_ = dest_handlers;
  5701. ret->is_native_ = false; /* If we JIT, it will update this later. */
  5702. upb_inttable_init(&ret->dispatch, UPB_CTYPE_UINT64);
  5703. if (ret->dest_handlers_) {
  5704. upb_handlers_ref(ret->dest_handlers_, ret);
  5705. }
  5706. return ret;
  5707. }
  5708. const upb_handlers *upb_pbdecodermethod_desthandlers(
  5709. const upb_pbdecodermethod *m) {
  5710. return m->dest_handlers_;
  5711. }
  5712. const upb_byteshandler *upb_pbdecodermethod_inputhandler(
  5713. const upb_pbdecodermethod *m) {
  5714. return &m->input_handler_;
  5715. }
  5716. bool upb_pbdecodermethod_isnative(const upb_pbdecodermethod *m) {
  5717. return m->is_native_;
  5718. }
  5719. const upb_pbdecodermethod *upb_pbdecodermethod_new(
  5720. const upb_pbdecodermethodopts *opts, const void *owner) {
  5721. const upb_pbdecodermethod *ret;
  5722. upb_pbcodecache cache;
  5723. upb_pbcodecache_init(&cache);
  5724. ret = upb_pbcodecache_getdecodermethod(&cache, opts);
  5725. upb_pbdecodermethod_ref(ret, owner);
  5726. upb_pbcodecache_uninit(&cache);
  5727. return ret;
  5728. }
  5729. /* bytecode compiler **********************************************************/
  5730. /* Data used only at compilation time. */
  5731. typedef struct {
  5732. mgroup *group;
  5733. uint32_t *pc;
  5734. int fwd_labels[MAXLABEL];
  5735. int back_labels[MAXLABEL];
  5736. /* For fields marked "lazy", parse them lazily or eagerly? */
  5737. bool lazy;
  5738. } compiler;
  5739. static compiler *newcompiler(mgroup *group, bool lazy) {
  5740. compiler *ret = malloc(sizeof(*ret));
  5741. int i;
  5742. ret->group = group;
  5743. ret->lazy = lazy;
  5744. for (i = 0; i < MAXLABEL; i++) {
  5745. ret->fwd_labels[i] = EMPTYLABEL;
  5746. ret->back_labels[i] = EMPTYLABEL;
  5747. }
  5748. return ret;
  5749. }
  5750. static void freecompiler(compiler *c) {
  5751. free(c);
  5752. }
  5753. const size_t ptr_words = sizeof(void*) / sizeof(uint32_t);
  5754. /* How many words an instruction is. */
  5755. static int instruction_len(uint32_t instr) {
  5756. switch (getop(instr)) {
  5757. case OP_SETDISPATCH: return 1 + ptr_words;
  5758. case OP_TAGN: return 3;
  5759. case OP_SETBIGGROUPNUM: return 2;
  5760. default: return 1;
  5761. }
  5762. }
  5763. bool op_has_longofs(int32_t instruction) {
  5764. switch (getop(instruction)) {
  5765. case OP_CALL:
  5766. case OP_BRANCH:
  5767. case OP_CHECKDELIM:
  5768. return true;
  5769. /* The "tag" instructions only have 8 bytes available for the jump target,
  5770. * but that is ok because these opcodes only require short jumps. */
  5771. case OP_TAG1:
  5772. case OP_TAG2:
  5773. case OP_TAGN:
  5774. return false;
  5775. default:
  5776. assert(false);
  5777. return false;
  5778. }
  5779. }
  5780. static int32_t getofs(uint32_t instruction) {
  5781. if (op_has_longofs(instruction)) {
  5782. return (int32_t)instruction >> 8;
  5783. } else {
  5784. return (int8_t)(instruction >> 8);
  5785. }
  5786. }
  5787. static void setofs(uint32_t *instruction, int32_t ofs) {
  5788. if (op_has_longofs(*instruction)) {
  5789. *instruction = getop(*instruction) | ofs << 8;
  5790. } else {
  5791. *instruction = (*instruction & ~0xff00) | ((ofs & 0xff) << 8);
  5792. }
  5793. assert(getofs(*instruction) == ofs); /* Would fail in cases of overflow. */
  5794. }
  5795. static uint32_t pcofs(compiler *c) { return c->pc - c->group->bytecode; }
  5796. /* Defines a local label at the current PC location. All previous forward
  5797. * references are updated to point to this location. The location is noted
  5798. * for any future backward references. */
  5799. static void label(compiler *c, unsigned int label) {
  5800. int val;
  5801. uint32_t *codep;
  5802. assert(label < MAXLABEL);
  5803. val = c->fwd_labels[label];
  5804. codep = (val == EMPTYLABEL) ? NULL : c->group->bytecode + val;
  5805. while (codep) {
  5806. int ofs = getofs(*codep);
  5807. setofs(codep, c->pc - codep - instruction_len(*codep));
  5808. codep = ofs ? codep + ofs : NULL;
  5809. }
  5810. c->fwd_labels[label] = EMPTYLABEL;
  5811. c->back_labels[label] = pcofs(c);
  5812. }
  5813. /* Creates a reference to a numbered label; either a forward reference
  5814. * (positive arg) or backward reference (negative arg). For forward references
  5815. * the value returned now is actually a "next" pointer into a linked list of all
  5816. * instructions that use this label and will be patched later when the label is
  5817. * defined with label().
  5818. *
  5819. * The returned value is the offset that should be written into the instruction.
  5820. */
  5821. static int32_t labelref(compiler *c, int label) {
  5822. assert(label < MAXLABEL);
  5823. if (label == LABEL_DISPATCH) {
  5824. /* No resolving required. */
  5825. return 0;
  5826. } else if (label < 0) {
  5827. /* Backward local label. Relative to the next instruction. */
  5828. uint32_t from = (c->pc + 1) - c->group->bytecode;
  5829. return c->back_labels[-label] - from;
  5830. } else {
  5831. /* Forward local label: prepend to (possibly-empty) linked list. */
  5832. int *lptr = &c->fwd_labels[label];
  5833. int32_t ret = (*lptr == EMPTYLABEL) ? 0 : *lptr - pcofs(c);
  5834. *lptr = pcofs(c);
  5835. return ret;
  5836. }
  5837. }
  5838. static void put32(compiler *c, uint32_t v) {
  5839. mgroup *g = c->group;
  5840. if (c->pc == g->bytecode_end) {
  5841. int ofs = pcofs(c);
  5842. size_t oldsize = g->bytecode_end - g->bytecode;
  5843. size_t newsize = UPB_MAX(oldsize * 2, 64);
  5844. /* TODO(haberman): handle OOM. */
  5845. g->bytecode = realloc(g->bytecode, newsize * sizeof(uint32_t));
  5846. g->bytecode_end = g->bytecode + newsize;
  5847. c->pc = g->bytecode + ofs;
  5848. }
  5849. *c->pc++ = v;
  5850. }
  5851. static void putop(compiler *c, opcode op, ...) {
  5852. va_list ap;
  5853. va_start(ap, op);
  5854. switch (op) {
  5855. case OP_SETDISPATCH: {
  5856. uintptr_t ptr = (uintptr_t)va_arg(ap, void*);
  5857. put32(c, OP_SETDISPATCH);
  5858. put32(c, ptr);
  5859. if (sizeof(uintptr_t) > sizeof(uint32_t))
  5860. put32(c, (uint64_t)ptr >> 32);
  5861. break;
  5862. }
  5863. case OP_STARTMSG:
  5864. case OP_ENDMSG:
  5865. case OP_PUSHLENDELIM:
  5866. case OP_POP:
  5867. case OP_SETDELIM:
  5868. case OP_HALT:
  5869. case OP_RET:
  5870. case OP_DISPATCH:
  5871. put32(c, op);
  5872. break;
  5873. case OP_PARSE_DOUBLE:
  5874. case OP_PARSE_FLOAT:
  5875. case OP_PARSE_INT64:
  5876. case OP_PARSE_UINT64:
  5877. case OP_PARSE_INT32:
  5878. case OP_PARSE_FIXED64:
  5879. case OP_PARSE_FIXED32:
  5880. case OP_PARSE_BOOL:
  5881. case OP_PARSE_UINT32:
  5882. case OP_PARSE_SFIXED32:
  5883. case OP_PARSE_SFIXED64:
  5884. case OP_PARSE_SINT32:
  5885. case OP_PARSE_SINT64:
  5886. case OP_STARTSEQ:
  5887. case OP_ENDSEQ:
  5888. case OP_STARTSUBMSG:
  5889. case OP_ENDSUBMSG:
  5890. case OP_STARTSTR:
  5891. case OP_STRING:
  5892. case OP_ENDSTR:
  5893. case OP_PUSHTAGDELIM:
  5894. put32(c, op | va_arg(ap, upb_selector_t) << 8);
  5895. break;
  5896. case OP_SETBIGGROUPNUM:
  5897. put32(c, op);
  5898. put32(c, va_arg(ap, int));
  5899. break;
  5900. case OP_CALL: {
  5901. const upb_pbdecodermethod *method = va_arg(ap, upb_pbdecodermethod *);
  5902. put32(c, op | (method->code_base.ofs - (pcofs(c) + 1)) << 8);
  5903. break;
  5904. }
  5905. case OP_CHECKDELIM:
  5906. case OP_BRANCH: {
  5907. uint32_t instruction = op;
  5908. int label = va_arg(ap, int);
  5909. setofs(&instruction, labelref(c, label));
  5910. put32(c, instruction);
  5911. break;
  5912. }
  5913. case OP_TAG1:
  5914. case OP_TAG2: {
  5915. int label = va_arg(ap, int);
  5916. uint64_t tag = va_arg(ap, uint64_t);
  5917. uint32_t instruction = op | (tag << 16);
  5918. assert(tag <= 0xffff);
  5919. setofs(&instruction, labelref(c, label));
  5920. put32(c, instruction);
  5921. break;
  5922. }
  5923. case OP_TAGN: {
  5924. int label = va_arg(ap, int);
  5925. uint64_t tag = va_arg(ap, uint64_t);
  5926. uint32_t instruction = op | (upb_value_size(tag) << 16);
  5927. setofs(&instruction, labelref(c, label));
  5928. put32(c, instruction);
  5929. put32(c, tag);
  5930. put32(c, tag >> 32);
  5931. break;
  5932. }
  5933. }
  5934. va_end(ap);
  5935. }
  5936. #if defined(UPB_USE_JIT_X64) || defined(UPB_DUMP_BYTECODE)
  5937. const char *upb_pbdecoder_getopname(unsigned int op) {
  5938. #define QUOTE(x) #x
  5939. #define EXPAND_AND_QUOTE(x) QUOTE(x)
  5940. #define OPNAME(x) OP_##x
  5941. #define OP(x) case OPNAME(x): return EXPAND_AND_QUOTE(OPNAME(x));
  5942. #define T(x) OP(PARSE_##x)
  5943. /* Keep in sync with list in decoder.int.h. */
  5944. switch ((opcode)op) {
  5945. T(DOUBLE) T(FLOAT) T(INT64) T(UINT64) T(INT32) T(FIXED64) T(FIXED32)
  5946. T(BOOL) T(UINT32) T(SFIXED32) T(SFIXED64) T(SINT32) T(SINT64)
  5947. OP(STARTMSG) OP(ENDMSG) OP(STARTSEQ) OP(ENDSEQ) OP(STARTSUBMSG)
  5948. OP(ENDSUBMSG) OP(STARTSTR) OP(STRING) OP(ENDSTR) OP(CALL) OP(RET)
  5949. OP(PUSHLENDELIM) OP(PUSHTAGDELIM) OP(SETDELIM) OP(CHECKDELIM)
  5950. OP(BRANCH) OP(TAG1) OP(TAG2) OP(TAGN) OP(SETDISPATCH) OP(POP)
  5951. OP(SETBIGGROUPNUM) OP(DISPATCH) OP(HALT)
  5952. }
  5953. return "<unknown op>";
  5954. #undef OP
  5955. #undef T
  5956. }
  5957. #endif
  5958. #ifdef UPB_DUMP_BYTECODE
  5959. static void dumpbc(uint32_t *p, uint32_t *end, FILE *f) {
  5960. uint32_t *begin = p;
  5961. while (p < end) {
  5962. fprintf(f, "%p %8tx", p, p - begin);
  5963. uint32_t instr = *p++;
  5964. uint8_t op = getop(instr);
  5965. fprintf(f, " %s", upb_pbdecoder_getopname(op));
  5966. switch ((opcode)op) {
  5967. case OP_SETDISPATCH: {
  5968. const upb_inttable *dispatch;
  5969. memcpy(&dispatch, p, sizeof(void*));
  5970. p += ptr_words;
  5971. const upb_pbdecodermethod *method =
  5972. (void *)((char *)dispatch -
  5973. offsetof(upb_pbdecodermethod, dispatch));
  5974. fprintf(f, " %s", upb_msgdef_fullname(
  5975. upb_handlers_msgdef(method->dest_handlers_)));
  5976. break;
  5977. }
  5978. case OP_DISPATCH:
  5979. case OP_STARTMSG:
  5980. case OP_ENDMSG:
  5981. case OP_PUSHLENDELIM:
  5982. case OP_POP:
  5983. case OP_SETDELIM:
  5984. case OP_HALT:
  5985. case OP_RET:
  5986. break;
  5987. case OP_PARSE_DOUBLE:
  5988. case OP_PARSE_FLOAT:
  5989. case OP_PARSE_INT64:
  5990. case OP_PARSE_UINT64:
  5991. case OP_PARSE_INT32:
  5992. case OP_PARSE_FIXED64:
  5993. case OP_PARSE_FIXED32:
  5994. case OP_PARSE_BOOL:
  5995. case OP_PARSE_UINT32:
  5996. case OP_PARSE_SFIXED32:
  5997. case OP_PARSE_SFIXED64:
  5998. case OP_PARSE_SINT32:
  5999. case OP_PARSE_SINT64:
  6000. case OP_STARTSEQ:
  6001. case OP_ENDSEQ:
  6002. case OP_STARTSUBMSG:
  6003. case OP_ENDSUBMSG:
  6004. case OP_STARTSTR:
  6005. case OP_STRING:
  6006. case OP_ENDSTR:
  6007. case OP_PUSHTAGDELIM:
  6008. fprintf(f, " %d", instr >> 8);
  6009. break;
  6010. case OP_SETBIGGROUPNUM:
  6011. fprintf(f, " %d", *p++);
  6012. break;
  6013. case OP_CHECKDELIM:
  6014. case OP_CALL:
  6015. case OP_BRANCH:
  6016. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  6017. break;
  6018. case OP_TAG1:
  6019. case OP_TAG2: {
  6020. fprintf(f, " tag:0x%x", instr >> 16);
  6021. if (getofs(instr)) {
  6022. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  6023. }
  6024. break;
  6025. }
  6026. case OP_TAGN: {
  6027. uint64_t tag = *p++;
  6028. tag |= (uint64_t)*p++ << 32;
  6029. fprintf(f, " tag:0x%llx", (long long)tag);
  6030. fprintf(f, " n:%d", instr >> 16);
  6031. if (getofs(instr)) {
  6032. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  6033. }
  6034. break;
  6035. }
  6036. }
  6037. fputs("\n", f);
  6038. }
  6039. }
  6040. #endif
  6041. static uint64_t get_encoded_tag(const upb_fielddef *f, int wire_type) {
  6042. uint32_t tag = (upb_fielddef_number(f) << 3) | wire_type;
  6043. uint64_t encoded_tag = upb_vencode32(tag);
  6044. /* No tag should be greater than 5 bytes. */
  6045. assert(encoded_tag <= 0xffffffffff);
  6046. return encoded_tag;
  6047. }
  6048. static void putchecktag(compiler *c, const upb_fielddef *f,
  6049. int wire_type, int dest) {
  6050. uint64_t tag = get_encoded_tag(f, wire_type);
  6051. switch (upb_value_size(tag)) {
  6052. case 1:
  6053. putop(c, OP_TAG1, dest, tag);
  6054. break;
  6055. case 2:
  6056. putop(c, OP_TAG2, dest, tag);
  6057. break;
  6058. default:
  6059. putop(c, OP_TAGN, dest, tag);
  6060. break;
  6061. }
  6062. }
  6063. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  6064. upb_selector_t selector;
  6065. bool ok = upb_handlers_getselector(f, type, &selector);
  6066. UPB_ASSERT_VAR(ok, ok);
  6067. return selector;
  6068. }
  6069. /* Takes an existing, primary dispatch table entry and repacks it with a
  6070. * different alternate wire type. Called when we are inserting a secondary
  6071. * dispatch table entry for an alternate wire type. */
  6072. static uint64_t repack(uint64_t dispatch, int new_wt2) {
  6073. uint64_t ofs;
  6074. uint8_t wt1;
  6075. uint8_t old_wt2;
  6076. upb_pbdecoder_unpackdispatch(dispatch, &ofs, &wt1, &old_wt2);
  6077. assert(old_wt2 == NO_WIRE_TYPE); /* wt2 should not be set yet. */
  6078. return upb_pbdecoder_packdispatch(ofs, wt1, new_wt2);
  6079. }
  6080. /* Marks the current bytecode position as the dispatch target for this message,
  6081. * field, and wire type. */
  6082. static void dispatchtarget(compiler *c, upb_pbdecodermethod *method,
  6083. const upb_fielddef *f, int wire_type) {
  6084. /* Offset is relative to msg base. */
  6085. uint64_t ofs = pcofs(c) - method->code_base.ofs;
  6086. uint32_t fn = upb_fielddef_number(f);
  6087. upb_inttable *d = &method->dispatch;
  6088. upb_value v;
  6089. if (upb_inttable_remove(d, fn, &v)) {
  6090. /* TODO: prioritize based on packed setting in .proto file. */
  6091. uint64_t repacked = repack(upb_value_getuint64(v), wire_type);
  6092. upb_inttable_insert(d, fn, upb_value_uint64(repacked));
  6093. upb_inttable_insert(d, fn + UPB_MAX_FIELDNUMBER, upb_value_uint64(ofs));
  6094. } else {
  6095. uint64_t val = upb_pbdecoder_packdispatch(ofs, wire_type, NO_WIRE_TYPE);
  6096. upb_inttable_insert(d, fn, upb_value_uint64(val));
  6097. }
  6098. }
  6099. static void putpush(compiler *c, const upb_fielddef *f) {
  6100. if (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE) {
  6101. putop(c, OP_PUSHLENDELIM);
  6102. } else {
  6103. uint32_t fn = upb_fielddef_number(f);
  6104. if (fn >= 1 << 24) {
  6105. putop(c, OP_PUSHTAGDELIM, 0);
  6106. putop(c, OP_SETBIGGROUPNUM, fn);
  6107. } else {
  6108. putop(c, OP_PUSHTAGDELIM, fn);
  6109. }
  6110. }
  6111. }
  6112. static upb_pbdecodermethod *find_submethod(const compiler *c,
  6113. const upb_pbdecodermethod *method,
  6114. const upb_fielddef *f) {
  6115. const upb_handlers *sub =
  6116. upb_handlers_getsubhandlers(method->dest_handlers_, f);
  6117. upb_value v;
  6118. return upb_inttable_lookupptr(&c->group->methods, sub, &v)
  6119. ? upb_value_getptr(v)
  6120. : NULL;
  6121. }
  6122. static void putsel(compiler *c, opcode op, upb_selector_t sel,
  6123. const upb_handlers *h) {
  6124. if (upb_handlers_gethandler(h, sel)) {
  6125. putop(c, op, sel);
  6126. }
  6127. }
  6128. /* Puts an opcode to call a callback, but only if a callback actually exists for
  6129. * this field and handler type. */
  6130. static void maybeput(compiler *c, opcode op, const upb_handlers *h,
  6131. const upb_fielddef *f, upb_handlertype_t type) {
  6132. putsel(c, op, getsel(f, type), h);
  6133. }
  6134. static bool haslazyhandlers(const upb_handlers *h, const upb_fielddef *f) {
  6135. if (!upb_fielddef_lazy(f))
  6136. return false;
  6137. return upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STARTSTR)) ||
  6138. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STRING)) ||
  6139. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_ENDSTR));
  6140. }
  6141. /* bytecode compiler code generation ******************************************/
  6142. /* Symbolic names for our local labels. */
  6143. #define LABEL_LOOPSTART 1 /* Top of a repeated field loop. */
  6144. #define LABEL_LOOPBREAK 2 /* To jump out of a repeated loop */
  6145. #define LABEL_FIELD 3 /* Jump backward to find the most recent field. */
  6146. #define LABEL_ENDMSG 4 /* To reach the OP_ENDMSG instr for this msg. */
  6147. /* Generates bytecode to parse a single non-lazy message field. */
  6148. static void generate_msgfield(compiler *c, const upb_fielddef *f,
  6149. upb_pbdecodermethod *method) {
  6150. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  6151. const upb_pbdecodermethod *sub_m = find_submethod(c, method, f);
  6152. int wire_type;
  6153. if (!sub_m) {
  6154. /* Don't emit any code for this field at all; it will be parsed as an
  6155. * unknown field. */
  6156. return;
  6157. }
  6158. label(c, LABEL_FIELD);
  6159. wire_type =
  6160. (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE)
  6161. ? UPB_WIRE_TYPE_DELIMITED
  6162. : UPB_WIRE_TYPE_START_GROUP;
  6163. if (upb_fielddef_isseq(f)) {
  6164. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6165. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  6166. dispatchtarget(c, method, f, wire_type);
  6167. putop(c, OP_PUSHTAGDELIM, 0);
  6168. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  6169. label(c, LABEL_LOOPSTART);
  6170. putpush(c, f);
  6171. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  6172. putop(c, OP_CALL, sub_m);
  6173. putop(c, OP_POP);
  6174. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  6175. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  6176. putop(c, OP_SETDELIM);
  6177. }
  6178. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  6179. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  6180. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  6181. label(c, LABEL_LOOPBREAK);
  6182. putop(c, OP_POP);
  6183. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  6184. } else {
  6185. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6186. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  6187. dispatchtarget(c, method, f, wire_type);
  6188. putpush(c, f);
  6189. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  6190. putop(c, OP_CALL, sub_m);
  6191. putop(c, OP_POP);
  6192. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  6193. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  6194. putop(c, OP_SETDELIM);
  6195. }
  6196. }
  6197. }
  6198. /* Generates bytecode to parse a single string or lazy submessage field. */
  6199. static void generate_delimfield(compiler *c, const upb_fielddef *f,
  6200. upb_pbdecodermethod *method) {
  6201. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  6202. label(c, LABEL_FIELD);
  6203. if (upb_fielddef_isseq(f)) {
  6204. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6205. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  6206. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  6207. putop(c, OP_PUSHTAGDELIM, 0);
  6208. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  6209. label(c, LABEL_LOOPSTART);
  6210. putop(c, OP_PUSHLENDELIM);
  6211. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  6212. /* Need to emit even if no handler to skip past the string. */
  6213. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  6214. putop(c, OP_POP);
  6215. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  6216. putop(c, OP_SETDELIM);
  6217. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  6218. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_LOOPBREAK);
  6219. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  6220. label(c, LABEL_LOOPBREAK);
  6221. putop(c, OP_POP);
  6222. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  6223. } else {
  6224. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6225. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  6226. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  6227. putop(c, OP_PUSHLENDELIM);
  6228. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  6229. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  6230. putop(c, OP_POP);
  6231. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  6232. putop(c, OP_SETDELIM);
  6233. }
  6234. }
  6235. /* Generates bytecode to parse a single primitive field. */
  6236. static void generate_primitivefield(compiler *c, const upb_fielddef *f,
  6237. upb_pbdecodermethod *method) {
  6238. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  6239. upb_descriptortype_t descriptor_type = upb_fielddef_descriptortype(f);
  6240. opcode parse_type;
  6241. upb_selector_t sel;
  6242. int wire_type;
  6243. label(c, LABEL_FIELD);
  6244. /* From a decoding perspective, ENUM is the same as INT32. */
  6245. if (descriptor_type == UPB_DESCRIPTOR_TYPE_ENUM)
  6246. descriptor_type = UPB_DESCRIPTOR_TYPE_INT32;
  6247. parse_type = (opcode)descriptor_type;
  6248. /* TODO(haberman): generate packed or non-packed first depending on "packed"
  6249. * setting in the fielddef. This will favor (in speed) whichever was
  6250. * specified. */
  6251. assert((int)parse_type >= 0 && parse_type <= OP_MAX);
  6252. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  6253. wire_type = upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  6254. if (upb_fielddef_isseq(f)) {
  6255. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6256. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  6257. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  6258. putop(c, OP_PUSHLENDELIM);
  6259. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Packed */
  6260. label(c, LABEL_LOOPSTART);
  6261. putop(c, parse_type, sel);
  6262. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  6263. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  6264. dispatchtarget(c, method, f, wire_type);
  6265. putop(c, OP_PUSHTAGDELIM, 0);
  6266. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Non-packed */
  6267. label(c, LABEL_LOOPSTART);
  6268. putop(c, parse_type, sel);
  6269. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  6270. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  6271. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  6272. label(c, LABEL_LOOPBREAK);
  6273. putop(c, OP_POP); /* Packed and non-packed join. */
  6274. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  6275. putop(c, OP_SETDELIM); /* Could remove for non-packed by dup ENDSEQ. */
  6276. } else {
  6277. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6278. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  6279. dispatchtarget(c, method, f, wire_type);
  6280. putop(c, parse_type, sel);
  6281. }
  6282. }
  6283. /* Adds bytecode for parsing the given message to the given decoderplan,
  6284. * while adding all dispatch targets to this message's dispatch table. */
  6285. static void compile_method(compiler *c, upb_pbdecodermethod *method) {
  6286. const upb_handlers *h;
  6287. const upb_msgdef *md;
  6288. uint32_t* start_pc;
  6289. upb_msg_field_iter i;
  6290. upb_value val;
  6291. assert(method);
  6292. /* Clear all entries in the dispatch table. */
  6293. upb_inttable_uninit(&method->dispatch);
  6294. upb_inttable_init(&method->dispatch, UPB_CTYPE_UINT64);
  6295. h = upb_pbdecodermethod_desthandlers(method);
  6296. md = upb_handlers_msgdef(h);
  6297. method->code_base.ofs = pcofs(c);
  6298. putop(c, OP_SETDISPATCH, &method->dispatch);
  6299. putsel(c, OP_STARTMSG, UPB_STARTMSG_SELECTOR, h);
  6300. label(c, LABEL_FIELD);
  6301. start_pc = c->pc;
  6302. for(upb_msg_field_begin(&i, md);
  6303. !upb_msg_field_done(&i);
  6304. upb_msg_field_next(&i)) {
  6305. const upb_fielddef *f = upb_msg_iter_field(&i);
  6306. upb_fieldtype_t type = upb_fielddef_type(f);
  6307. if (type == UPB_TYPE_MESSAGE && !(haslazyhandlers(h, f) && c->lazy)) {
  6308. generate_msgfield(c, f, method);
  6309. } else if (type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES ||
  6310. type == UPB_TYPE_MESSAGE) {
  6311. generate_delimfield(c, f, method);
  6312. } else {
  6313. generate_primitivefield(c, f, method);
  6314. }
  6315. }
  6316. /* If there were no fields, or if no handlers were defined, we need to
  6317. * generate a non-empty loop body so that we can at least dispatch for unknown
  6318. * fields and check for the end of the message. */
  6319. if (c->pc == start_pc) {
  6320. /* Check for end-of-message. */
  6321. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6322. /* Unconditionally dispatch. */
  6323. putop(c, OP_DISPATCH, 0);
  6324. }
  6325. /* For now we just loop back to the last field of the message (or if none,
  6326. * the DISPATCH opcode for the message). */
  6327. putop(c, OP_BRANCH, -LABEL_FIELD);
  6328. /* Insert both a label and a dispatch table entry for this end-of-msg. */
  6329. label(c, LABEL_ENDMSG);
  6330. val = upb_value_uint64(pcofs(c) - method->code_base.ofs);
  6331. upb_inttable_insert(&method->dispatch, DISPATCH_ENDMSG, val);
  6332. putsel(c, OP_ENDMSG, UPB_ENDMSG_SELECTOR, h);
  6333. putop(c, OP_RET);
  6334. upb_inttable_compact(&method->dispatch);
  6335. }
  6336. /* Populate "methods" with new upb_pbdecodermethod objects reachable from "h".
  6337. * Returns the method for these handlers.
  6338. *
  6339. * Generates a new method for every destination handlers reachable from "h". */
  6340. static void find_methods(compiler *c, const upb_handlers *h) {
  6341. upb_value v;
  6342. upb_msg_field_iter i;
  6343. const upb_msgdef *md;
  6344. if (upb_inttable_lookupptr(&c->group->methods, h, &v))
  6345. return;
  6346. newmethod(h, c->group);
  6347. /* Find submethods. */
  6348. md = upb_handlers_msgdef(h);
  6349. for(upb_msg_field_begin(&i, md);
  6350. !upb_msg_field_done(&i);
  6351. upb_msg_field_next(&i)) {
  6352. const upb_fielddef *f = upb_msg_iter_field(&i);
  6353. const upb_handlers *sub_h;
  6354. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  6355. (sub_h = upb_handlers_getsubhandlers(h, f)) != NULL) {
  6356. /* We only generate a decoder method for submessages with handlers.
  6357. * Others will be parsed as unknown fields. */
  6358. find_methods(c, sub_h);
  6359. }
  6360. }
  6361. }
  6362. /* (Re-)compile bytecode for all messages in "msgs."
  6363. * Overwrites any existing bytecode in "c". */
  6364. static void compile_methods(compiler *c) {
  6365. upb_inttable_iter i;
  6366. /* Start over at the beginning of the bytecode. */
  6367. c->pc = c->group->bytecode;
  6368. upb_inttable_begin(&i, &c->group->methods);
  6369. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  6370. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  6371. compile_method(c, method);
  6372. }
  6373. }
  6374. static void set_bytecode_handlers(mgroup *g) {
  6375. upb_inttable_iter i;
  6376. upb_inttable_begin(&i, &g->methods);
  6377. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  6378. upb_pbdecodermethod *m = upb_value_getptr(upb_inttable_iter_value(&i));
  6379. upb_byteshandler *h = &m->input_handler_;
  6380. m->code_base.ptr = g->bytecode + m->code_base.ofs;
  6381. upb_byteshandler_setstartstr(h, upb_pbdecoder_startbc, m->code_base.ptr);
  6382. upb_byteshandler_setstring(h, upb_pbdecoder_decode, g);
  6383. upb_byteshandler_setendstr(h, upb_pbdecoder_end, m);
  6384. }
  6385. }
  6386. /* JIT setup. *****************************************************************/
  6387. #ifdef UPB_USE_JIT_X64
  6388. static void sethandlers(mgroup *g, bool allowjit) {
  6389. g->jit_code = NULL;
  6390. if (allowjit) {
  6391. /* Compile byte-code into machine code, create handlers. */
  6392. upb_pbdecoder_jit(g);
  6393. } else {
  6394. set_bytecode_handlers(g);
  6395. }
  6396. }
  6397. #else /* UPB_USE_JIT_X64 */
  6398. static void sethandlers(mgroup *g, bool allowjit) {
  6399. /* No JIT compiled in; use bytecode handlers unconditionally. */
  6400. UPB_UNUSED(allowjit);
  6401. set_bytecode_handlers(g);
  6402. }
  6403. #endif /* UPB_USE_JIT_X64 */
  6404. /* TODO(haberman): allow this to be constructed for an arbitrary set of dest
  6405. * handlers and other mgroups (but verify we have a transitive closure). */
  6406. const mgroup *mgroup_new(const upb_handlers *dest, bool allowjit, bool lazy,
  6407. const void *owner) {
  6408. mgroup *g;
  6409. compiler *c;
  6410. UPB_UNUSED(allowjit);
  6411. assert(upb_handlers_isfrozen(dest));
  6412. g = newgroup(owner);
  6413. c = newcompiler(g, lazy);
  6414. find_methods(c, dest);
  6415. /* We compile in two passes:
  6416. * 1. all messages are assigned relative offsets from the beginning of the
  6417. * bytecode (saved in method->code_base).
  6418. * 2. forwards OP_CALL instructions can be correctly linked since message
  6419. * offsets have been previously assigned.
  6420. *
  6421. * Could avoid the second pass by linking OP_CALL instructions somehow. */
  6422. compile_methods(c);
  6423. compile_methods(c);
  6424. g->bytecode_end = c->pc;
  6425. freecompiler(c);
  6426. #ifdef UPB_DUMP_BYTECODE
  6427. {
  6428. FILE *f = fopen("/tmp/upb-bytecode", "wb");
  6429. assert(f);
  6430. dumpbc(g->bytecode, g->bytecode_end, stderr);
  6431. dumpbc(g->bytecode, g->bytecode_end, f);
  6432. fclose(f);
  6433. }
  6434. #endif
  6435. sethandlers(g, allowjit);
  6436. return g;
  6437. }
  6438. /* upb_pbcodecache ************************************************************/
  6439. void upb_pbcodecache_init(upb_pbcodecache *c) {
  6440. upb_inttable_init(&c->groups, UPB_CTYPE_CONSTPTR);
  6441. c->allow_jit_ = true;
  6442. }
  6443. void upb_pbcodecache_uninit(upb_pbcodecache *c) {
  6444. upb_inttable_iter i;
  6445. upb_inttable_begin(&i, &c->groups);
  6446. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  6447. const mgroup *group = upb_value_getconstptr(upb_inttable_iter_value(&i));
  6448. mgroup_unref(group, c);
  6449. }
  6450. upb_inttable_uninit(&c->groups);
  6451. }
  6452. bool upb_pbcodecache_allowjit(const upb_pbcodecache *c) {
  6453. return c->allow_jit_;
  6454. }
  6455. bool upb_pbcodecache_setallowjit(upb_pbcodecache *c, bool allow) {
  6456. if (upb_inttable_count(&c->groups) > 0)
  6457. return false;
  6458. c->allow_jit_ = allow;
  6459. return true;
  6460. }
  6461. const upb_pbdecodermethod *upb_pbcodecache_getdecodermethod(
  6462. upb_pbcodecache *c, const upb_pbdecodermethodopts *opts) {
  6463. upb_value v;
  6464. bool ok;
  6465. /* Right now we build a new DecoderMethod every time.
  6466. * TODO(haberman): properly cache methods by their true key. */
  6467. const mgroup *g = mgroup_new(opts->handlers, c->allow_jit_, opts->lazy, c);
  6468. upb_inttable_push(&c->groups, upb_value_constptr(g));
  6469. ok = upb_inttable_lookupptr(&g->methods, opts->handlers, &v);
  6470. UPB_ASSERT_VAR(ok, ok);
  6471. return upb_value_getptr(v);
  6472. }
  6473. /* upb_pbdecodermethodopts ****************************************************/
  6474. void upb_pbdecodermethodopts_init(upb_pbdecodermethodopts *opts,
  6475. const upb_handlers *h) {
  6476. opts->handlers = h;
  6477. opts->lazy = false;
  6478. }
  6479. void upb_pbdecodermethodopts_setlazy(upb_pbdecodermethodopts *opts, bool lazy) {
  6480. opts->lazy = lazy;
  6481. }
  6482. /*
  6483. ** upb::Decoder (Bytecode Decoder VM)
  6484. **
  6485. ** Bytecode must previously have been generated using the bytecode compiler in
  6486. ** compile_decoder.c. This decoder then walks through the bytecode op-by-op to
  6487. ** parse the input.
  6488. **
  6489. ** Decoding is fully resumable; we just keep a pointer to the current bytecode
  6490. ** instruction and resume from there. A fair amount of the logic here is to
  6491. ** handle the fact that values can span buffer seams and we have to be able to
  6492. ** be capable of suspending/resuming from any byte in the stream. This
  6493. ** sometimes requires keeping a few trailing bytes from the last buffer around
  6494. ** in the "residual" buffer.
  6495. */
  6496. #include <inttypes.h>
  6497. #include <stddef.h>
  6498. #ifdef UPB_DUMP_BYTECODE
  6499. #include <stdio.h>
  6500. #endif
  6501. #define CHECK_SUSPEND(x) if (!(x)) return upb_pbdecoder_suspend(d);
  6502. /* Error messages that are shared between the bytecode and JIT decoders. */
  6503. const char *kPbDecoderStackOverflow = "Nesting too deep.";
  6504. /* Error messages shared within this file. */
  6505. static const char *kUnterminatedVarint = "Unterminated varint.";
  6506. /* upb_pbdecoder **************************************************************/
  6507. static opcode halt = OP_HALT;
  6508. /* Whether an op consumes any of the input buffer. */
  6509. static bool consumes_input(opcode op) {
  6510. switch (op) {
  6511. case OP_SETDISPATCH:
  6512. case OP_STARTMSG:
  6513. case OP_ENDMSG:
  6514. case OP_STARTSEQ:
  6515. case OP_ENDSEQ:
  6516. case OP_STARTSUBMSG:
  6517. case OP_ENDSUBMSG:
  6518. case OP_STARTSTR:
  6519. case OP_ENDSTR:
  6520. case OP_PUSHTAGDELIM:
  6521. case OP_POP:
  6522. case OP_SETDELIM:
  6523. case OP_SETBIGGROUPNUM:
  6524. case OP_CHECKDELIM:
  6525. case OP_CALL:
  6526. case OP_RET:
  6527. case OP_BRANCH:
  6528. return false;
  6529. default:
  6530. return true;
  6531. }
  6532. }
  6533. static bool in_residual_buf(const upb_pbdecoder *d, const char *p);
  6534. /* It's unfortunate that we have to micro-manage the compiler with
  6535. * UPB_FORCEINLINE and UPB_NOINLINE, especially since this tuning is necessarily
  6536. * specific to one hardware configuration. But empirically on a Core i7,
  6537. * performance increases 30-50% with these annotations. Every instance where
  6538. * these appear, gcc 4.2.1 made the wrong decision and degraded performance in
  6539. * benchmarks. */
  6540. static void seterr(upb_pbdecoder *d, const char *msg) {
  6541. upb_status status = UPB_STATUS_INIT;
  6542. upb_status_seterrmsg(&status, msg);
  6543. upb_env_reporterror(d->env, &status);
  6544. }
  6545. void upb_pbdecoder_seterr(upb_pbdecoder *d, const char *msg) {
  6546. seterr(d, msg);
  6547. }
  6548. /* Buffering ******************************************************************/
  6549. /* We operate on one buffer at a time, which is either the user's buffer passed
  6550. * to our "decode" callback or some residual bytes from the previous buffer. */
  6551. /* How many bytes can be safely read from d->ptr without reading past end-of-buf
  6552. * or past the current delimited end. */
  6553. static size_t curbufleft(const upb_pbdecoder *d) {
  6554. assert(d->data_end >= d->ptr);
  6555. return d->data_end - d->ptr;
  6556. }
  6557. /* Overall stream offset of d->ptr. */
  6558. uint64_t offset(const upb_pbdecoder *d) {
  6559. return d->bufstart_ofs + (d->ptr - d->buf);
  6560. }
  6561. /* Advances d->ptr. */
  6562. static void advance(upb_pbdecoder *d, size_t len) {
  6563. assert(curbufleft(d) >= len);
  6564. d->ptr += len;
  6565. }
  6566. static bool in_buf(const char *p, const char *buf, const char *end) {
  6567. return p >= buf && p <= end;
  6568. }
  6569. static bool in_residual_buf(const upb_pbdecoder *d, const char *p) {
  6570. return in_buf(p, d->residual, d->residual_end);
  6571. }
  6572. /* Calculates the delim_end value, which is affected by both the current buffer
  6573. * and the parsing stack, so must be called whenever either is updated. */
  6574. static void set_delim_end(upb_pbdecoder *d) {
  6575. size_t delim_ofs = d->top->end_ofs - d->bufstart_ofs;
  6576. if (delim_ofs <= (size_t)(d->end - d->buf)) {
  6577. d->delim_end = d->buf + delim_ofs;
  6578. d->data_end = d->delim_end;
  6579. } else {
  6580. d->data_end = d->end;
  6581. d->delim_end = NULL;
  6582. }
  6583. }
  6584. static void switchtobuf(upb_pbdecoder *d, const char *buf, const char *end) {
  6585. d->ptr = buf;
  6586. d->buf = buf;
  6587. d->end = end;
  6588. set_delim_end(d);
  6589. }
  6590. static void advancetobuf(upb_pbdecoder *d, const char *buf, size_t len) {
  6591. assert(curbufleft(d) == 0);
  6592. d->bufstart_ofs += (d->end - d->buf);
  6593. switchtobuf(d, buf, buf + len);
  6594. }
  6595. static void checkpoint(upb_pbdecoder *d) {
  6596. /* The assertion here is in the interests of efficiency, not correctness.
  6597. * We are trying to ensure that we don't checkpoint() more often than
  6598. * necessary. */
  6599. assert(d->checkpoint != d->ptr);
  6600. d->checkpoint = d->ptr;
  6601. }
  6602. /* Resumes the decoder from an initial state or from a previous suspend. */
  6603. int32_t upb_pbdecoder_resume(upb_pbdecoder *d, void *p, const char *buf,
  6604. size_t size, const upb_bufhandle *handle) {
  6605. UPB_UNUSED(p); /* Useless; just for the benefit of the JIT. */
  6606. d->buf_param = buf;
  6607. d->size_param = size;
  6608. d->handle = handle;
  6609. if (d->residual_end > d->residual) {
  6610. /* We have residual bytes from the last buffer. */
  6611. assert(d->ptr == d->residual);
  6612. } else {
  6613. switchtobuf(d, buf, buf + size);
  6614. }
  6615. d->checkpoint = d->ptr;
  6616. if (d->top->groupnum < 0) {
  6617. CHECK_RETURN(upb_pbdecoder_skipunknown(d, -1, 0));
  6618. d->checkpoint = d->ptr;
  6619. }
  6620. return DECODE_OK;
  6621. }
  6622. /* Suspends the decoder at the last checkpoint, without saving any residual
  6623. * bytes. If there are any unconsumed bytes, returns a short byte count. */
  6624. size_t upb_pbdecoder_suspend(upb_pbdecoder *d) {
  6625. d->pc = d->last;
  6626. if (d->checkpoint == d->residual) {
  6627. /* Checkpoint was in residual buf; no user bytes were consumed. */
  6628. d->ptr = d->residual;
  6629. return 0;
  6630. } else {
  6631. size_t consumed;
  6632. assert(!in_residual_buf(d, d->checkpoint));
  6633. assert(d->buf == d->buf_param);
  6634. consumed = d->checkpoint - d->buf;
  6635. d->bufstart_ofs += consumed;
  6636. d->residual_end = d->residual;
  6637. switchtobuf(d, d->residual, d->residual_end);
  6638. return consumed;
  6639. }
  6640. }
  6641. /* Suspends the decoder at the last checkpoint, and saves any unconsumed
  6642. * bytes in our residual buffer. This is necessary if we need more user
  6643. * bytes to form a complete value, which might not be contiguous in the
  6644. * user's buffers. Always consumes all user bytes. */
  6645. static size_t suspend_save(upb_pbdecoder *d) {
  6646. /* We hit end-of-buffer before we could parse a full value.
  6647. * Save any unconsumed bytes (if any) to the residual buffer. */
  6648. d->pc = d->last;
  6649. if (d->checkpoint == d->residual) {
  6650. /* Checkpoint was in residual buf; append user byte(s) to residual buf. */
  6651. assert((d->residual_end - d->residual) + d->size_param <=
  6652. sizeof(d->residual));
  6653. if (!in_residual_buf(d, d->ptr)) {
  6654. d->bufstart_ofs -= (d->residual_end - d->residual);
  6655. }
  6656. memcpy(d->residual_end, d->buf_param, d->size_param);
  6657. d->residual_end += d->size_param;
  6658. } else {
  6659. /* Checkpoint was in user buf; old residual bytes not needed. */
  6660. size_t save;
  6661. assert(!in_residual_buf(d, d->checkpoint));
  6662. d->ptr = d->checkpoint;
  6663. save = curbufleft(d);
  6664. assert(save <= sizeof(d->residual));
  6665. memcpy(d->residual, d->ptr, save);
  6666. d->residual_end = d->residual + save;
  6667. d->bufstart_ofs = offset(d);
  6668. }
  6669. switchtobuf(d, d->residual, d->residual_end);
  6670. return d->size_param;
  6671. }
  6672. /* Skips "bytes" bytes in the stream, which may be more than available. If we
  6673. * skip more bytes than are available, we return a long read count to the caller
  6674. * indicating how many bytes the caller should skip before passing a new buffer.
  6675. */
  6676. static int32_t skip(upb_pbdecoder *d, size_t bytes) {
  6677. assert(!in_residual_buf(d, d->ptr) || d->size_param == 0);
  6678. if (curbufleft(d) >= bytes) {
  6679. /* Skipped data is all in current buffer. */
  6680. advance(d, bytes);
  6681. return DECODE_OK;
  6682. } else {
  6683. /* Skipped data extends beyond currently available buffers. */
  6684. size_t skip;
  6685. d->pc = d->last;
  6686. skip = bytes - curbufleft(d);
  6687. d->bufstart_ofs += (d->end - d->buf) + skip;
  6688. d->residual_end = d->residual;
  6689. switchtobuf(d, d->residual, d->residual_end);
  6690. return d->size_param + skip;
  6691. }
  6692. }
  6693. /* Copies the next "bytes" bytes into "buf" and advances the stream.
  6694. * Requires that this many bytes are available in the current buffer. */
  6695. UPB_FORCEINLINE static void consumebytes(upb_pbdecoder *d, void *buf,
  6696. size_t bytes) {
  6697. assert(bytes <= curbufleft(d));
  6698. memcpy(buf, d->ptr, bytes);
  6699. advance(d, bytes);
  6700. }
  6701. /* Slow path for getting the next "bytes" bytes, regardless of whether they are
  6702. * available in the current buffer or not. Returns a status code as described
  6703. * in decoder.int.h. */
  6704. UPB_NOINLINE static int32_t getbytes_slow(upb_pbdecoder *d, void *buf,
  6705. size_t bytes) {
  6706. const size_t avail = curbufleft(d);
  6707. consumebytes(d, buf, avail);
  6708. bytes -= avail;
  6709. assert(bytes > 0);
  6710. if (in_residual_buf(d, d->ptr)) {
  6711. advancetobuf(d, d->buf_param, d->size_param);
  6712. }
  6713. if (curbufleft(d) >= bytes) {
  6714. consumebytes(d, (char *)buf + avail, bytes);
  6715. return DECODE_OK;
  6716. } else if (d->data_end == d->delim_end) {
  6717. seterr(d, "Submessage ended in the middle of a value or group");
  6718. return upb_pbdecoder_suspend(d);
  6719. } else {
  6720. return suspend_save(d);
  6721. }
  6722. }
  6723. /* Gets the next "bytes" bytes, regardless of whether they are available in the
  6724. * current buffer or not. Returns a status code as described in decoder.int.h.
  6725. */
  6726. UPB_FORCEINLINE static int32_t getbytes(upb_pbdecoder *d, void *buf,
  6727. size_t bytes) {
  6728. if (curbufleft(d) >= bytes) {
  6729. /* Buffer has enough data to satisfy. */
  6730. consumebytes(d, buf, bytes);
  6731. return DECODE_OK;
  6732. } else {
  6733. return getbytes_slow(d, buf, bytes);
  6734. }
  6735. }
  6736. UPB_NOINLINE static size_t peekbytes_slow(upb_pbdecoder *d, void *buf,
  6737. size_t bytes) {
  6738. size_t ret = curbufleft(d);
  6739. memcpy(buf, d->ptr, ret);
  6740. if (in_residual_buf(d, d->ptr)) {
  6741. size_t copy = UPB_MIN(bytes - ret, d->size_param);
  6742. memcpy((char *)buf + ret, d->buf_param, copy);
  6743. ret += copy;
  6744. }
  6745. return ret;
  6746. }
  6747. UPB_FORCEINLINE static size_t peekbytes(upb_pbdecoder *d, void *buf,
  6748. size_t bytes) {
  6749. if (curbufleft(d) >= bytes) {
  6750. memcpy(buf, d->ptr, bytes);
  6751. return bytes;
  6752. } else {
  6753. return peekbytes_slow(d, buf, bytes);
  6754. }
  6755. }
  6756. /* Decoding of wire types *****************************************************/
  6757. /* Slow path for decoding a varint from the current buffer position.
  6758. * Returns a status code as described in decoder.int.h. */
  6759. UPB_NOINLINE int32_t upb_pbdecoder_decode_varint_slow(upb_pbdecoder *d,
  6760. uint64_t *u64) {
  6761. uint8_t byte = 0x80;
  6762. int bitpos;
  6763. *u64 = 0;
  6764. for(bitpos = 0; bitpos < 70 && (byte & 0x80); bitpos += 7) {
  6765. int32_t ret = getbytes(d, &byte, 1);
  6766. if (ret >= 0) return ret;
  6767. *u64 |= (uint64_t)(byte & 0x7F) << bitpos;
  6768. }
  6769. if(bitpos == 70 && (byte & 0x80)) {
  6770. seterr(d, kUnterminatedVarint);
  6771. return upb_pbdecoder_suspend(d);
  6772. }
  6773. return DECODE_OK;
  6774. }
  6775. /* Decodes a varint from the current buffer position.
  6776. * Returns a status code as described in decoder.int.h. */
  6777. UPB_FORCEINLINE static int32_t decode_varint(upb_pbdecoder *d, uint64_t *u64) {
  6778. if (curbufleft(d) > 0 && !(*d->ptr & 0x80)) {
  6779. *u64 = *d->ptr;
  6780. advance(d, 1);
  6781. return DECODE_OK;
  6782. } else if (curbufleft(d) >= 10) {
  6783. /* Fast case. */
  6784. upb_decoderet r = upb_vdecode_fast(d->ptr);
  6785. if (r.p == NULL) {
  6786. seterr(d, kUnterminatedVarint);
  6787. return upb_pbdecoder_suspend(d);
  6788. }
  6789. advance(d, r.p - d->ptr);
  6790. *u64 = r.val;
  6791. return DECODE_OK;
  6792. } else {
  6793. /* Slow case -- varint spans buffer seam. */
  6794. return upb_pbdecoder_decode_varint_slow(d, u64);
  6795. }
  6796. }
  6797. /* Decodes a 32-bit varint from the current buffer position.
  6798. * Returns a status code as described in decoder.int.h. */
  6799. UPB_FORCEINLINE static int32_t decode_v32(upb_pbdecoder *d, uint32_t *u32) {
  6800. uint64_t u64;
  6801. int32_t ret = decode_varint(d, &u64);
  6802. if (ret >= 0) return ret;
  6803. if (u64 > UINT32_MAX) {
  6804. seterr(d, "Unterminated 32-bit varint");
  6805. /* TODO(haberman) guarantee that this function return is >= 0 somehow,
  6806. * so we know this path will always be treated as error by our caller.
  6807. * Right now the size_t -> int32_t can overflow and produce negative values.
  6808. */
  6809. *u32 = 0;
  6810. return upb_pbdecoder_suspend(d);
  6811. }
  6812. *u32 = u64;
  6813. return DECODE_OK;
  6814. }
  6815. /* Decodes a fixed32 from the current buffer position.
  6816. * Returns a status code as described in decoder.int.h.
  6817. * TODO: proper byte swapping for big-endian machines. */
  6818. UPB_FORCEINLINE static int32_t decode_fixed32(upb_pbdecoder *d, uint32_t *u32) {
  6819. return getbytes(d, u32, 4);
  6820. }
  6821. /* Decodes a fixed64 from the current buffer position.
  6822. * Returns a status code as described in decoder.int.h.
  6823. * TODO: proper byte swapping for big-endian machines. */
  6824. UPB_FORCEINLINE static int32_t decode_fixed64(upb_pbdecoder *d, uint64_t *u64) {
  6825. return getbytes(d, u64, 8);
  6826. }
  6827. /* Non-static versions of the above functions.
  6828. * These are called by the JIT for fallback paths. */
  6829. int32_t upb_pbdecoder_decode_f32(upb_pbdecoder *d, uint32_t *u32) {
  6830. return decode_fixed32(d, u32);
  6831. }
  6832. int32_t upb_pbdecoder_decode_f64(upb_pbdecoder *d, uint64_t *u64) {
  6833. return decode_fixed64(d, u64);
  6834. }
  6835. static double as_double(uint64_t n) { double d; memcpy(&d, &n, 8); return d; }
  6836. static float as_float(uint32_t n) { float f; memcpy(&f, &n, 4); return f; }
  6837. /* Pushes a frame onto the decoder stack. */
  6838. static bool decoder_push(upb_pbdecoder *d, uint64_t end) {
  6839. upb_pbdecoder_frame *fr = d->top;
  6840. if (end > fr->end_ofs) {
  6841. seterr(d, "Submessage end extends past enclosing submessage.");
  6842. return false;
  6843. } else if (fr == d->limit) {
  6844. seterr(d, kPbDecoderStackOverflow);
  6845. return false;
  6846. }
  6847. fr++;
  6848. fr->end_ofs = end;
  6849. fr->dispatch = NULL;
  6850. fr->groupnum = 0;
  6851. d->top = fr;
  6852. return true;
  6853. }
  6854. static bool pushtagdelim(upb_pbdecoder *d, uint32_t arg) {
  6855. /* While we expect to see an "end" tag (either ENDGROUP or a non-sequence
  6856. * field number) prior to hitting any enclosing submessage end, pushing our
  6857. * existing delim end prevents us from continuing to parse values from a
  6858. * corrupt proto that doesn't give us an END tag in time. */
  6859. if (!decoder_push(d, d->top->end_ofs))
  6860. return false;
  6861. d->top->groupnum = arg;
  6862. return true;
  6863. }
  6864. /* Pops a frame from the decoder stack. */
  6865. static void decoder_pop(upb_pbdecoder *d) { d->top--; }
  6866. UPB_NOINLINE int32_t upb_pbdecoder_checktag_slow(upb_pbdecoder *d,
  6867. uint64_t expected) {
  6868. uint64_t data = 0;
  6869. size_t bytes = upb_value_size(expected);
  6870. size_t read = peekbytes(d, &data, bytes);
  6871. if (read == bytes && data == expected) {
  6872. /* Advance past matched bytes. */
  6873. int32_t ok = getbytes(d, &data, read);
  6874. UPB_ASSERT_VAR(ok, ok < 0);
  6875. return DECODE_OK;
  6876. } else if (read < bytes && memcmp(&data, &expected, read) == 0) {
  6877. return suspend_save(d);
  6878. } else {
  6879. return DECODE_MISMATCH;
  6880. }
  6881. }
  6882. int32_t upb_pbdecoder_skipunknown(upb_pbdecoder *d, int32_t fieldnum,
  6883. uint8_t wire_type) {
  6884. if (fieldnum >= 0)
  6885. goto have_tag;
  6886. while (true) {
  6887. uint32_t tag;
  6888. CHECK_RETURN(decode_v32(d, &tag));
  6889. wire_type = tag & 0x7;
  6890. fieldnum = tag >> 3;
  6891. have_tag:
  6892. if (fieldnum == 0) {
  6893. seterr(d, "Saw invalid field number (0)");
  6894. return upb_pbdecoder_suspend(d);
  6895. }
  6896. /* TODO: deliver to unknown field callback. */
  6897. switch (wire_type) {
  6898. case UPB_WIRE_TYPE_32BIT:
  6899. CHECK_RETURN(skip(d, 4));
  6900. break;
  6901. case UPB_WIRE_TYPE_64BIT:
  6902. CHECK_RETURN(skip(d, 8));
  6903. break;
  6904. case UPB_WIRE_TYPE_VARINT: {
  6905. uint64_t u64;
  6906. CHECK_RETURN(decode_varint(d, &u64));
  6907. break;
  6908. }
  6909. case UPB_WIRE_TYPE_DELIMITED: {
  6910. uint32_t len;
  6911. CHECK_RETURN(decode_v32(d, &len));
  6912. CHECK_RETURN(skip(d, len));
  6913. break;
  6914. }
  6915. case UPB_WIRE_TYPE_START_GROUP:
  6916. CHECK_SUSPEND(pushtagdelim(d, -fieldnum));
  6917. break;
  6918. case UPB_WIRE_TYPE_END_GROUP:
  6919. if (fieldnum == -d->top->groupnum) {
  6920. decoder_pop(d);
  6921. } else if (fieldnum == d->top->groupnum) {
  6922. return DECODE_ENDGROUP;
  6923. } else {
  6924. seterr(d, "Unmatched ENDGROUP tag.");
  6925. return upb_pbdecoder_suspend(d);
  6926. }
  6927. break;
  6928. default:
  6929. seterr(d, "Invalid wire type");
  6930. return upb_pbdecoder_suspend(d);
  6931. }
  6932. if (d->top->groupnum >= 0) {
  6933. return DECODE_OK;
  6934. }
  6935. if (d->ptr == d->delim_end) {
  6936. seterr(d, "Enclosing submessage ended in the middle of value or group");
  6937. /* Unlike most errors we notice during parsing, right now we have consumed
  6938. * all of the user's input.
  6939. *
  6940. * There are three different options for how to handle this case:
  6941. *
  6942. * 1. decode() = short count, error = set
  6943. * 2. decode() = full count, error = set
  6944. * 3. decode() = full count, error NOT set, short count and error will
  6945. * be reported on next call to decode() (or end())
  6946. *
  6947. * (1) and (3) have the advantage that they preserve the invariant that an
  6948. * error occurs iff decode() returns a short count.
  6949. *
  6950. * (2) and (3) have the advantage of reflecting the fact that all of the
  6951. * bytes were in fact parsed (and possibly delivered to the unknown field
  6952. * handler, in the future when that is supported).
  6953. *
  6954. * (3) requires extra state in the decode (a place to store the "permanent
  6955. * error" that we should return for all subsequent attempts to decode).
  6956. * But we likely want this anyway.
  6957. *
  6958. * Right now we do (1), thanks to the fact that we checkpoint *after* this
  6959. * check. (3) may be a better choice long term; unclear at the moment. */
  6960. return upb_pbdecoder_suspend(d);
  6961. }
  6962. checkpoint(d);
  6963. }
  6964. }
  6965. static void goto_endmsg(upb_pbdecoder *d) {
  6966. upb_value v;
  6967. bool found = upb_inttable_lookup32(d->top->dispatch, DISPATCH_ENDMSG, &v);
  6968. UPB_ASSERT_VAR(found, found);
  6969. d->pc = d->top->base + upb_value_getuint64(v);
  6970. }
  6971. /* Parses a tag and jumps to the corresponding bytecode instruction for this
  6972. * field.
  6973. *
  6974. * If the tag is unknown (or the wire type doesn't match), parses the field as
  6975. * unknown. If the tag is a valid ENDGROUP tag, jumps to the bytecode
  6976. * instruction for the end of message. */
  6977. static int32_t dispatch(upb_pbdecoder *d) {
  6978. upb_inttable *dispatch = d->top->dispatch;
  6979. uint32_t tag;
  6980. uint8_t wire_type;
  6981. uint32_t fieldnum;
  6982. upb_value val;
  6983. int32_t ret;
  6984. /* Decode tag. */
  6985. CHECK_RETURN(decode_v32(d, &tag));
  6986. wire_type = tag & 0x7;
  6987. fieldnum = tag >> 3;
  6988. /* Lookup tag. Because of packed/non-packed compatibility, we have to
  6989. * check the wire type against two possibilities. */
  6990. if (fieldnum != DISPATCH_ENDMSG &&
  6991. upb_inttable_lookup32(dispatch, fieldnum, &val)) {
  6992. uint64_t v = upb_value_getuint64(val);
  6993. if (wire_type == (v & 0xff)) {
  6994. d->pc = d->top->base + (v >> 16);
  6995. return DECODE_OK;
  6996. } else if (wire_type == ((v >> 8) & 0xff)) {
  6997. bool found =
  6998. upb_inttable_lookup(dispatch, fieldnum + UPB_MAX_FIELDNUMBER, &val);
  6999. UPB_ASSERT_VAR(found, found);
  7000. d->pc = d->top->base + upb_value_getuint64(val);
  7001. return DECODE_OK;
  7002. }
  7003. }
  7004. /* Unknown field or ENDGROUP. */
  7005. ret = upb_pbdecoder_skipunknown(d, fieldnum, wire_type);
  7006. if (ret == DECODE_ENDGROUP) {
  7007. goto_endmsg(d);
  7008. return DECODE_OK;
  7009. } else if (ret == DECODE_OK) {
  7010. /* We just consumed some input, so we might now have consumed all the data
  7011. * in the delmited region. Since every opcode that can trigger dispatch is
  7012. * directly preceded by OP_CHECKDELIM, rewind to it now to re-check the
  7013. * delimited end. */
  7014. d->pc = d->last - 1;
  7015. assert(getop(*d->pc) == OP_CHECKDELIM);
  7016. return DECODE_OK;
  7017. }
  7018. return ret;
  7019. }
  7020. /* Callers know that the stack is more than one deep because the opcodes that
  7021. * call this only occur after PUSH operations. */
  7022. upb_pbdecoder_frame *outer_frame(upb_pbdecoder *d) {
  7023. assert(d->top != d->stack);
  7024. return d->top - 1;
  7025. }
  7026. /* The main decoding loop *****************************************************/
  7027. /* The main decoder VM function. Uses traditional bytecode dispatch loop with a
  7028. * switch() statement. */
  7029. size_t upb_pbdecoder_decode(void *closure, const void *hd, const char *buf,
  7030. size_t size, const upb_bufhandle *handle) {
  7031. upb_pbdecoder *d = closure;
  7032. const mgroup *group = hd;
  7033. int32_t result;
  7034. assert(buf);
  7035. result = upb_pbdecoder_resume(d, NULL, buf, size, handle);
  7036. if (result == DECODE_ENDGROUP) {
  7037. goto_endmsg(d);
  7038. }
  7039. CHECK_RETURN(result);
  7040. UPB_UNUSED(group);
  7041. #define VMCASE(op, code) \
  7042. case op: { code; if (consumes_input(op)) checkpoint(d); break; }
  7043. #define PRIMITIVE_OP(type, wt, name, convfunc, ctype) \
  7044. VMCASE(OP_PARSE_ ## type, { \
  7045. ctype val; \
  7046. CHECK_RETURN(decode_ ## wt(d, &val)); \
  7047. upb_sink_put ## name(&d->top->sink, arg, (convfunc)(val)); \
  7048. })
  7049. while(1) {
  7050. int32_t instruction;
  7051. opcode op;
  7052. uint32_t arg;
  7053. int32_t longofs;
  7054. d->last = d->pc;
  7055. instruction = *d->pc++;
  7056. op = getop(instruction);
  7057. arg = instruction >> 8;
  7058. longofs = arg;
  7059. assert(d->ptr != d->residual_end);
  7060. #ifdef UPB_DUMP_BYTECODE
  7061. fprintf(stderr, "s_ofs=%d buf_ofs=%d data_rem=%d buf_rem=%d delim_rem=%d "
  7062. "%x %s (%d)\n",
  7063. (int)offset(d),
  7064. (int)(d->ptr - d->buf),
  7065. (int)(d->data_end - d->ptr),
  7066. (int)(d->end - d->ptr),
  7067. (int)((d->top->end_ofs - d->bufstart_ofs) - (d->ptr - d->buf)),
  7068. (int)(d->pc - 1 - group->bytecode),
  7069. upb_pbdecoder_getopname(op),
  7070. arg);
  7071. #endif
  7072. switch (op) {
  7073. /* Technically, we are losing data if we see a 32-bit varint that is not
  7074. * properly sign-extended. We could detect this and error about the data
  7075. * loss, but proto2 does not do this, so we pass. */
  7076. PRIMITIVE_OP(INT32, varint, int32, int32_t, uint64_t)
  7077. PRIMITIVE_OP(INT64, varint, int64, int64_t, uint64_t)
  7078. PRIMITIVE_OP(UINT32, varint, uint32, uint32_t, uint64_t)
  7079. PRIMITIVE_OP(UINT64, varint, uint64, uint64_t, uint64_t)
  7080. PRIMITIVE_OP(FIXED32, fixed32, uint32, uint32_t, uint32_t)
  7081. PRIMITIVE_OP(FIXED64, fixed64, uint64, uint64_t, uint64_t)
  7082. PRIMITIVE_OP(SFIXED32, fixed32, int32, int32_t, uint32_t)
  7083. PRIMITIVE_OP(SFIXED64, fixed64, int64, int64_t, uint64_t)
  7084. PRIMITIVE_OP(BOOL, varint, bool, bool, uint64_t)
  7085. PRIMITIVE_OP(DOUBLE, fixed64, double, as_double, uint64_t)
  7086. PRIMITIVE_OP(FLOAT, fixed32, float, as_float, uint32_t)
  7087. PRIMITIVE_OP(SINT32, varint, int32, upb_zzdec_32, uint64_t)
  7088. PRIMITIVE_OP(SINT64, varint, int64, upb_zzdec_64, uint64_t)
  7089. VMCASE(OP_SETDISPATCH,
  7090. d->top->base = d->pc - 1;
  7091. memcpy(&d->top->dispatch, d->pc, sizeof(void*));
  7092. d->pc += sizeof(void*) / sizeof(uint32_t);
  7093. )
  7094. VMCASE(OP_STARTMSG,
  7095. CHECK_SUSPEND(upb_sink_startmsg(&d->top->sink));
  7096. )
  7097. VMCASE(OP_ENDMSG,
  7098. CHECK_SUSPEND(upb_sink_endmsg(&d->top->sink, d->status));
  7099. )
  7100. VMCASE(OP_STARTSEQ,
  7101. upb_pbdecoder_frame *outer = outer_frame(d);
  7102. CHECK_SUSPEND(upb_sink_startseq(&outer->sink, arg, &d->top->sink));
  7103. )
  7104. VMCASE(OP_ENDSEQ,
  7105. CHECK_SUSPEND(upb_sink_endseq(&d->top->sink, arg));
  7106. )
  7107. VMCASE(OP_STARTSUBMSG,
  7108. upb_pbdecoder_frame *outer = outer_frame(d);
  7109. CHECK_SUSPEND(upb_sink_startsubmsg(&outer->sink, arg, &d->top->sink));
  7110. )
  7111. VMCASE(OP_ENDSUBMSG,
  7112. CHECK_SUSPEND(upb_sink_endsubmsg(&d->top->sink, arg));
  7113. )
  7114. VMCASE(OP_STARTSTR,
  7115. uint32_t len = d->top->end_ofs - offset(d);
  7116. upb_pbdecoder_frame *outer = outer_frame(d);
  7117. CHECK_SUSPEND(upb_sink_startstr(&outer->sink, arg, len, &d->top->sink));
  7118. if (len == 0) {
  7119. d->pc++; /* Skip OP_STRING. */
  7120. }
  7121. )
  7122. VMCASE(OP_STRING,
  7123. uint32_t len = curbufleft(d);
  7124. size_t n = upb_sink_putstring(&d->top->sink, arg, d->ptr, len, handle);
  7125. if (n > len) {
  7126. if (n > d->top->end_ofs - offset(d)) {
  7127. seterr(d, "Tried to skip past end of string.");
  7128. return upb_pbdecoder_suspend(d);
  7129. } else {
  7130. int32_t ret = skip(d, n);
  7131. /* This shouldn't return DECODE_OK, because n > len. */
  7132. assert(ret >= 0);
  7133. return ret;
  7134. }
  7135. }
  7136. advance(d, n);
  7137. if (n < len || d->delim_end == NULL) {
  7138. /* We aren't finished with this string yet. */
  7139. d->pc--; /* Repeat OP_STRING. */
  7140. if (n > 0) checkpoint(d);
  7141. return upb_pbdecoder_suspend(d);
  7142. }
  7143. )
  7144. VMCASE(OP_ENDSTR,
  7145. CHECK_SUSPEND(upb_sink_endstr(&d->top->sink, arg));
  7146. )
  7147. VMCASE(OP_PUSHTAGDELIM,
  7148. CHECK_SUSPEND(pushtagdelim(d, arg));
  7149. )
  7150. VMCASE(OP_SETBIGGROUPNUM,
  7151. d->top->groupnum = *d->pc++;
  7152. )
  7153. VMCASE(OP_POP,
  7154. assert(d->top > d->stack);
  7155. decoder_pop(d);
  7156. )
  7157. VMCASE(OP_PUSHLENDELIM,
  7158. uint32_t len;
  7159. CHECK_RETURN(decode_v32(d, &len));
  7160. CHECK_SUSPEND(decoder_push(d, offset(d) + len));
  7161. set_delim_end(d);
  7162. )
  7163. VMCASE(OP_SETDELIM,
  7164. set_delim_end(d);
  7165. )
  7166. VMCASE(OP_CHECKDELIM,
  7167. /* We are guaranteed of this assert because we never allow ourselves to
  7168. * consume bytes beyond data_end, which covers delim_end when non-NULL.
  7169. */
  7170. assert(!(d->delim_end && d->ptr > d->delim_end));
  7171. if (d->ptr == d->delim_end)
  7172. d->pc += longofs;
  7173. )
  7174. VMCASE(OP_CALL,
  7175. d->callstack[d->call_len++] = d->pc;
  7176. d->pc += longofs;
  7177. )
  7178. VMCASE(OP_RET,
  7179. assert(d->call_len > 0);
  7180. d->pc = d->callstack[--d->call_len];
  7181. )
  7182. VMCASE(OP_BRANCH,
  7183. d->pc += longofs;
  7184. )
  7185. VMCASE(OP_TAG1,
  7186. uint8_t expected;
  7187. CHECK_SUSPEND(curbufleft(d) > 0);
  7188. expected = (arg >> 8) & 0xff;
  7189. if (*d->ptr == expected) {
  7190. advance(d, 1);
  7191. } else {
  7192. int8_t shortofs;
  7193. badtag:
  7194. shortofs = arg;
  7195. if (shortofs == LABEL_DISPATCH) {
  7196. CHECK_RETURN(dispatch(d));
  7197. } else {
  7198. d->pc += shortofs;
  7199. break; /* Avoid checkpoint(). */
  7200. }
  7201. }
  7202. )
  7203. VMCASE(OP_TAG2,
  7204. uint16_t expected;
  7205. CHECK_SUSPEND(curbufleft(d) > 0);
  7206. expected = (arg >> 8) & 0xffff;
  7207. if (curbufleft(d) >= 2) {
  7208. uint16_t actual;
  7209. memcpy(&actual, d->ptr, 2);
  7210. if (expected == actual) {
  7211. advance(d, 2);
  7212. } else {
  7213. goto badtag;
  7214. }
  7215. } else {
  7216. int32_t result = upb_pbdecoder_checktag_slow(d, expected);
  7217. if (result == DECODE_MISMATCH) goto badtag;
  7218. if (result >= 0) return result;
  7219. }
  7220. )
  7221. VMCASE(OP_TAGN, {
  7222. uint64_t expected;
  7223. int32_t result;
  7224. memcpy(&expected, d->pc, 8);
  7225. d->pc += 2;
  7226. result = upb_pbdecoder_checktag_slow(d, expected);
  7227. if (result == DECODE_MISMATCH) goto badtag;
  7228. if (result >= 0) return result;
  7229. })
  7230. VMCASE(OP_DISPATCH, {
  7231. CHECK_RETURN(dispatch(d));
  7232. })
  7233. VMCASE(OP_HALT, {
  7234. return size;
  7235. })
  7236. }
  7237. }
  7238. }
  7239. void *upb_pbdecoder_startbc(void *closure, const void *pc, size_t size_hint) {
  7240. upb_pbdecoder *d = closure;
  7241. UPB_UNUSED(size_hint);
  7242. d->top->end_ofs = UINT64_MAX;
  7243. d->bufstart_ofs = 0;
  7244. d->call_len = 1;
  7245. d->callstack[0] = &halt;
  7246. d->pc = pc;
  7247. return d;
  7248. }
  7249. void *upb_pbdecoder_startjit(void *closure, const void *hd, size_t size_hint) {
  7250. upb_pbdecoder *d = closure;
  7251. UPB_UNUSED(hd);
  7252. UPB_UNUSED(size_hint);
  7253. d->top->end_ofs = UINT64_MAX;
  7254. d->bufstart_ofs = 0;
  7255. d->call_len = 0;
  7256. return d;
  7257. }
  7258. bool upb_pbdecoder_end(void *closure, const void *handler_data) {
  7259. upb_pbdecoder *d = closure;
  7260. const upb_pbdecodermethod *method = handler_data;
  7261. uint64_t end;
  7262. char dummy;
  7263. #ifdef UPB_USE_JIT_X64
  7264. const mgroup *group = (const mgroup*)method->group;
  7265. #endif
  7266. if (d->residual_end > d->residual) {
  7267. seterr(d, "Unexpected EOF");
  7268. return false;
  7269. }
  7270. if (d->top->end_ofs != UINT64_MAX) {
  7271. seterr(d, "Unexpected EOF inside delimited string");
  7272. return false;
  7273. }
  7274. /* Message ends here. */
  7275. end = offset(d);
  7276. d->top->end_ofs = end;
  7277. #ifdef UPB_USE_JIT_X64
  7278. if (group->jit_code) {
  7279. if (d->top != d->stack)
  7280. d->stack->end_ofs = 0;
  7281. group->jit_code(closure, method->code_base.ptr, &dummy, 0, NULL);
  7282. } else
  7283. #endif
  7284. {
  7285. const uint32_t *p = d->pc;
  7286. d->stack->end_ofs = end;
  7287. /* Check the previous bytecode, but guard against beginning. */
  7288. if (p != method->code_base.ptr) p--;
  7289. if (getop(*p) == OP_CHECKDELIM) {
  7290. /* Rewind from OP_TAG* to OP_CHECKDELIM. */
  7291. assert(getop(*d->pc) == OP_TAG1 ||
  7292. getop(*d->pc) == OP_TAG2 ||
  7293. getop(*d->pc) == OP_TAGN ||
  7294. getop(*d->pc) == OP_DISPATCH);
  7295. d->pc = p;
  7296. }
  7297. upb_pbdecoder_decode(closure, handler_data, &dummy, 0, NULL);
  7298. }
  7299. if (d->call_len != 0) {
  7300. seterr(d, "Unexpected EOF");
  7301. return false;
  7302. }
  7303. return true;
  7304. }
  7305. void upb_pbdecoder_reset(upb_pbdecoder *d) {
  7306. d->top = d->stack;
  7307. d->top->groupnum = 0;
  7308. d->ptr = d->residual;
  7309. d->buf = d->residual;
  7310. d->end = d->residual;
  7311. d->residual_end = d->residual;
  7312. }
  7313. static size_t stacksize(upb_pbdecoder *d, size_t entries) {
  7314. UPB_UNUSED(d);
  7315. return entries * sizeof(upb_pbdecoder_frame);
  7316. }
  7317. static size_t callstacksize(upb_pbdecoder *d, size_t entries) {
  7318. UPB_UNUSED(d);
  7319. #ifdef UPB_USE_JIT_X64
  7320. if (d->method_->is_native_) {
  7321. /* Each native stack frame needs two pointers, plus we need a few frames for
  7322. * the enter/exit trampolines. */
  7323. size_t ret = entries * sizeof(void*) * 2;
  7324. ret += sizeof(void*) * 10;
  7325. return ret;
  7326. }
  7327. #endif
  7328. return entries * sizeof(uint32_t*);
  7329. }
  7330. upb_pbdecoder *upb_pbdecoder_create(upb_env *e, const upb_pbdecodermethod *m,
  7331. upb_sink *sink) {
  7332. const size_t default_max_nesting = 64;
  7333. #ifndef NDEBUG
  7334. size_t size_before = upb_env_bytesallocated(e);
  7335. #endif
  7336. upb_pbdecoder *d = upb_env_malloc(e, sizeof(upb_pbdecoder));
  7337. if (!d) return NULL;
  7338. d->method_ = m;
  7339. d->callstack = upb_env_malloc(e, callstacksize(d, default_max_nesting));
  7340. d->stack = upb_env_malloc(e, stacksize(d, default_max_nesting));
  7341. if (!d->stack || !d->callstack) {
  7342. return NULL;
  7343. }
  7344. d->env = e;
  7345. d->limit = d->stack + default_max_nesting - 1;
  7346. d->stack_size = default_max_nesting;
  7347. upb_pbdecoder_reset(d);
  7348. upb_bytessink_reset(&d->input_, &m->input_handler_, d);
  7349. assert(sink);
  7350. if (d->method_->dest_handlers_) {
  7351. if (sink->handlers != d->method_->dest_handlers_)
  7352. return NULL;
  7353. }
  7354. upb_sink_reset(&d->top->sink, sink->handlers, sink->closure);
  7355. /* If this fails, increase the value in decoder.h. */
  7356. assert(upb_env_bytesallocated(e) - size_before <= UPB_PB_DECODER_SIZE);
  7357. return d;
  7358. }
  7359. uint64_t upb_pbdecoder_bytesparsed(const upb_pbdecoder *d) {
  7360. return offset(d);
  7361. }
  7362. const upb_pbdecodermethod *upb_pbdecoder_method(const upb_pbdecoder *d) {
  7363. return d->method_;
  7364. }
  7365. upb_bytessink *upb_pbdecoder_input(upb_pbdecoder *d) {
  7366. return &d->input_;
  7367. }
  7368. size_t upb_pbdecoder_maxnesting(const upb_pbdecoder *d) {
  7369. return d->stack_size;
  7370. }
  7371. bool upb_pbdecoder_setmaxnesting(upb_pbdecoder *d, size_t max) {
  7372. assert(d->top >= d->stack);
  7373. if (max < (size_t)(d->top - d->stack)) {
  7374. /* Can't set a limit smaller than what we are currently at. */
  7375. return false;
  7376. }
  7377. if (max > d->stack_size) {
  7378. /* Need to reallocate stack and callstack to accommodate. */
  7379. size_t old_size = stacksize(d, d->stack_size);
  7380. size_t new_size = stacksize(d, max);
  7381. void *p = upb_env_realloc(d->env, d->stack, old_size, new_size);
  7382. if (!p) {
  7383. return false;
  7384. }
  7385. d->stack = p;
  7386. old_size = callstacksize(d, d->stack_size);
  7387. new_size = callstacksize(d, max);
  7388. p = upb_env_realloc(d->env, d->callstack, old_size, new_size);
  7389. if (!p) {
  7390. return false;
  7391. }
  7392. d->callstack = p;
  7393. d->stack_size = max;
  7394. }
  7395. d->limit = d->stack + max - 1;
  7396. return true;
  7397. }
  7398. /*
  7399. ** upb::Encoder
  7400. **
  7401. ** Since we are implementing pure handlers (ie. without any out-of-band access
  7402. ** to pre-computed lengths), we have to buffer all submessages before we can
  7403. ** emit even their first byte.
  7404. **
  7405. ** Not knowing the size of submessages also means we can't write a perfect
  7406. ** zero-copy implementation, even with buffering. Lengths are stored as
  7407. ** varints, which means that we don't know how many bytes to reserve for the
  7408. ** length until we know what the length is.
  7409. **
  7410. ** This leaves us with three main choices:
  7411. **
  7412. ** 1. buffer all submessage data in a temporary buffer, then copy it exactly
  7413. ** once into the output buffer.
  7414. **
  7415. ** 2. attempt to buffer data directly into the output buffer, estimating how
  7416. ** many bytes each length will take. When our guesses are wrong, use
  7417. ** memmove() to grow or shrink the allotted space.
  7418. **
  7419. ** 3. buffer directly into the output buffer, allocating a max length
  7420. ** ahead-of-time for each submessage length. If we overallocated, we waste
  7421. ** space, but no memcpy() or memmove() is required. This approach requires
  7422. ** defining a maximum size for submessages and rejecting submessages that
  7423. ** exceed that size.
  7424. **
  7425. ** (2) and (3) have the potential to have better performance, but they are more
  7426. ** complicated and subtle to implement:
  7427. **
  7428. ** (3) requires making an arbitrary choice of the maximum message size; it
  7429. ** wastes space when submessages are shorter than this and fails
  7430. ** completely when they are longer. This makes it more finicky and
  7431. ** requires configuration based on the input. It also makes it impossible
  7432. ** to perfectly match the output of reference encoders that always use the
  7433. ** optimal amount of space for each length.
  7434. **
  7435. ** (2) requires guessing the the size upfront, and if multiple lengths are
  7436. ** guessed wrong the minimum required number of memmove() operations may
  7437. ** be complicated to compute correctly. Implemented properly, it may have
  7438. ** a useful amortized or average cost, but more investigation is required
  7439. ** to determine this and what the optimal algorithm is to achieve it.
  7440. **
  7441. ** (1) makes you always pay for exactly one copy, but its implementation is
  7442. ** the simplest and its performance is predictable.
  7443. **
  7444. ** So for now, we implement (1) only. If we wish to optimize later, we should
  7445. ** be able to do it without affecting users.
  7446. **
  7447. ** The strategy is to buffer the segments of data that do *not* depend on
  7448. ** unknown lengths in one buffer, and keep a separate buffer of segment pointers
  7449. ** and lengths. When the top-level submessage ends, we can go beginning to end,
  7450. ** alternating the writing of lengths with memcpy() of the rest of the data.
  7451. ** At the top level though, no buffering is required.
  7452. */
  7453. #include <stdlib.h>
  7454. /* The output buffer is divided into segments; a segment is a string of data
  7455. * that is "ready to go" -- it does not need any varint lengths inserted into
  7456. * the middle. The seams between segments are where varints will be inserted
  7457. * once they are known.
  7458. *
  7459. * We also use the concept of a "run", which is a range of encoded bytes that
  7460. * occur at a single submessage level. Every segment contains one or more runs.
  7461. *
  7462. * A segment can span messages. Consider:
  7463. *
  7464. * .--Submessage lengths---------.
  7465. * | | |
  7466. * | V V
  7467. * V | |--------------- | |-----------------
  7468. * Submessages: | |-----------------------------------------------
  7469. * Top-level msg: ------------------------------------------------------------
  7470. *
  7471. * Segments: ----- ------------------- -----------------
  7472. * Runs: *---- *--------------*--- *----------------
  7473. * (* marks the start)
  7474. *
  7475. * Note that the top-level menssage is not in any segment because it does not
  7476. * have any length preceding it.
  7477. *
  7478. * A segment is only interrupted when another length needs to be inserted. So
  7479. * observe how the second segment spans both the inner submessage and part of
  7480. * the next enclosing message. */
  7481. typedef struct {
  7482. uint32_t msglen; /* The length to varint-encode before this segment. */
  7483. uint32_t seglen; /* Length of the segment. */
  7484. } upb_pb_encoder_segment;
  7485. struct upb_pb_encoder {
  7486. upb_env *env;
  7487. /* Our input and output. */
  7488. upb_sink input_;
  7489. upb_bytessink *output_;
  7490. /* The "subclosure" -- used as the inner closure as part of the bytessink
  7491. * protocol. */
  7492. void *subc;
  7493. /* The output buffer and limit, and our current write position. "buf"
  7494. * initially points to "initbuf", but is dynamically allocated if we need to
  7495. * grow beyond the initial size. */
  7496. char *buf, *ptr, *limit;
  7497. /* The beginning of the current run, or undefined if we are at the top
  7498. * level. */
  7499. char *runbegin;
  7500. /* The list of segments we are accumulating. */
  7501. upb_pb_encoder_segment *segbuf, *segptr, *seglimit;
  7502. /* The stack of enclosing submessages. Each entry in the stack points to the
  7503. * segment where this submessage's length is being accumulated. */
  7504. int *stack, *top, *stacklimit;
  7505. /* Depth of startmsg/endmsg calls. */
  7506. int depth;
  7507. };
  7508. /* low-level buffering ********************************************************/
  7509. /* Low-level functions for interacting with the output buffer. */
  7510. /* TODO(haberman): handle pushback */
  7511. static void putbuf(upb_pb_encoder *e, const char *buf, size_t len) {
  7512. size_t n = upb_bytessink_putbuf(e->output_, e->subc, buf, len, NULL);
  7513. UPB_ASSERT_VAR(n, n == len);
  7514. }
  7515. static upb_pb_encoder_segment *top(upb_pb_encoder *e) {
  7516. return &e->segbuf[*e->top];
  7517. }
  7518. /* Call to ensure that at least "bytes" bytes are available for writing at
  7519. * e->ptr. Returns false if the bytes could not be allocated. */
  7520. static bool reserve(upb_pb_encoder *e, size_t bytes) {
  7521. if ((size_t)(e->limit - e->ptr) < bytes) {
  7522. /* Grow buffer. */
  7523. char *new_buf;
  7524. size_t needed = bytes + (e->ptr - e->buf);
  7525. size_t old_size = e->limit - e->buf;
  7526. size_t new_size = old_size;
  7527. while (new_size < needed) {
  7528. new_size *= 2;
  7529. }
  7530. new_buf = upb_env_realloc(e->env, e->buf, old_size, new_size);
  7531. if (new_buf == NULL) {
  7532. return false;
  7533. }
  7534. e->ptr = new_buf + (e->ptr - e->buf);
  7535. e->runbegin = new_buf + (e->runbegin - e->buf);
  7536. e->limit = new_buf + new_size;
  7537. e->buf = new_buf;
  7538. }
  7539. return true;
  7540. }
  7541. /* Call when "bytes" bytes have been writte at e->ptr. The caller *must* have
  7542. * previously called reserve() with at least this many bytes. */
  7543. static void encoder_advance(upb_pb_encoder *e, size_t bytes) {
  7544. assert((size_t)(e->limit - e->ptr) >= bytes);
  7545. e->ptr += bytes;
  7546. }
  7547. /* Call when all of the bytes for a handler have been written. Flushes the
  7548. * bytes if possible and necessary, returning false if this failed. */
  7549. static bool commit(upb_pb_encoder *e) {
  7550. if (!e->top) {
  7551. /* We aren't inside a delimited region. Flush our accumulated bytes to
  7552. * the output.
  7553. *
  7554. * TODO(haberman): in the future we may want to delay flushing for
  7555. * efficiency reasons. */
  7556. putbuf(e, e->buf, e->ptr - e->buf);
  7557. e->ptr = e->buf;
  7558. }
  7559. return true;
  7560. }
  7561. /* Writes the given bytes to the buffer, handling reserve/advance. */
  7562. static bool encode_bytes(upb_pb_encoder *e, const void *data, size_t len) {
  7563. if (!reserve(e, len)) {
  7564. return false;
  7565. }
  7566. memcpy(e->ptr, data, len);
  7567. encoder_advance(e, len);
  7568. return true;
  7569. }
  7570. /* Finish the current run by adding the run totals to the segment and message
  7571. * length. */
  7572. static void accumulate(upb_pb_encoder *e) {
  7573. size_t run_len;
  7574. assert(e->ptr >= e->runbegin);
  7575. run_len = e->ptr - e->runbegin;
  7576. e->segptr->seglen += run_len;
  7577. top(e)->msglen += run_len;
  7578. e->runbegin = e->ptr;
  7579. }
  7580. /* Call to indicate the start of delimited region for which the full length is
  7581. * not yet known. All data will be buffered until the length is known.
  7582. * Delimited regions may be nested; their lengths will all be tracked properly. */
  7583. static bool start_delim(upb_pb_encoder *e) {
  7584. if (e->top) {
  7585. /* We are already buffering, advance to the next segment and push it on the
  7586. * stack. */
  7587. accumulate(e);
  7588. if (++e->top == e->stacklimit) {
  7589. /* TODO(haberman): grow stack? */
  7590. return false;
  7591. }
  7592. if (++e->segptr == e->seglimit) {
  7593. /* Grow segment buffer. */
  7594. size_t old_size =
  7595. (e->seglimit - e->segbuf) * sizeof(upb_pb_encoder_segment);
  7596. size_t new_size = old_size * 2;
  7597. upb_pb_encoder_segment *new_buf =
  7598. upb_env_realloc(e->env, e->segbuf, old_size, new_size);
  7599. if (new_buf == NULL) {
  7600. return false;
  7601. }
  7602. e->segptr = new_buf + (e->segptr - e->segbuf);
  7603. e->seglimit = new_buf + (new_size / sizeof(upb_pb_encoder_segment));
  7604. e->segbuf = new_buf;
  7605. }
  7606. } else {
  7607. /* We were previously at the top level, start buffering. */
  7608. e->segptr = e->segbuf;
  7609. e->top = e->stack;
  7610. e->runbegin = e->ptr;
  7611. }
  7612. *e->top = e->segptr - e->segbuf;
  7613. e->segptr->seglen = 0;
  7614. e->segptr->msglen = 0;
  7615. return true;
  7616. }
  7617. /* Call to indicate the end of a delimited region. We now know the length of
  7618. * the delimited region. If we are not nested inside any other delimited
  7619. * regions, we can now emit all of the buffered data we accumulated. */
  7620. static bool end_delim(upb_pb_encoder *e) {
  7621. size_t msglen;
  7622. accumulate(e);
  7623. msglen = top(e)->msglen;
  7624. if (e->top == e->stack) {
  7625. /* All lengths are now available, emit all buffered data. */
  7626. char buf[UPB_PB_VARINT_MAX_LEN];
  7627. upb_pb_encoder_segment *s;
  7628. const char *ptr = e->buf;
  7629. for (s = e->segbuf; s <= e->segptr; s++) {
  7630. size_t lenbytes = upb_vencode64(s->msglen, buf);
  7631. putbuf(e, buf, lenbytes);
  7632. putbuf(e, ptr, s->seglen);
  7633. ptr += s->seglen;
  7634. }
  7635. e->ptr = e->buf;
  7636. e->top = NULL;
  7637. } else {
  7638. /* Need to keep buffering; propagate length info into enclosing
  7639. * submessages. */
  7640. --e->top;
  7641. top(e)->msglen += msglen + upb_varint_size(msglen);
  7642. }
  7643. return true;
  7644. }
  7645. /* tag_t **********************************************************************/
  7646. /* A precomputed (pre-encoded) tag and length. */
  7647. typedef struct {
  7648. uint8_t bytes;
  7649. char tag[7];
  7650. } tag_t;
  7651. /* Allocates a new tag for this field, and sets it in these handlerattr. */
  7652. static void new_tag(upb_handlers *h, const upb_fielddef *f, upb_wiretype_t wt,
  7653. upb_handlerattr *attr) {
  7654. uint32_t n = upb_fielddef_number(f);
  7655. tag_t *tag = malloc(sizeof(tag_t));
  7656. tag->bytes = upb_vencode64((n << 3) | wt, tag->tag);
  7657. upb_handlerattr_init(attr);
  7658. upb_handlerattr_sethandlerdata(attr, tag);
  7659. upb_handlers_addcleanup(h, tag, free);
  7660. }
  7661. static bool encode_tag(upb_pb_encoder *e, const tag_t *tag) {
  7662. return encode_bytes(e, tag->tag, tag->bytes);
  7663. }
  7664. /* encoding of wire types *****************************************************/
  7665. static bool encode_fixed64(upb_pb_encoder *e, uint64_t val) {
  7666. /* TODO(haberman): byte-swap for big endian. */
  7667. return encode_bytes(e, &val, sizeof(uint64_t));
  7668. }
  7669. static bool encode_fixed32(upb_pb_encoder *e, uint32_t val) {
  7670. /* TODO(haberman): byte-swap for big endian. */
  7671. return encode_bytes(e, &val, sizeof(uint32_t));
  7672. }
  7673. static bool encode_varint(upb_pb_encoder *e, uint64_t val) {
  7674. if (!reserve(e, UPB_PB_VARINT_MAX_LEN)) {
  7675. return false;
  7676. }
  7677. encoder_advance(e, upb_vencode64(val, e->ptr));
  7678. return true;
  7679. }
  7680. static uint64_t dbl2uint64(double d) {
  7681. uint64_t ret;
  7682. memcpy(&ret, &d, sizeof(uint64_t));
  7683. return ret;
  7684. }
  7685. static uint32_t flt2uint32(float d) {
  7686. uint32_t ret;
  7687. memcpy(&ret, &d, sizeof(uint32_t));
  7688. return ret;
  7689. }
  7690. /* encoding of proto types ****************************************************/
  7691. static bool startmsg(void *c, const void *hd) {
  7692. upb_pb_encoder *e = c;
  7693. UPB_UNUSED(hd);
  7694. if (e->depth++ == 0) {
  7695. upb_bytessink_start(e->output_, 0, &e->subc);
  7696. }
  7697. return true;
  7698. }
  7699. static bool endmsg(void *c, const void *hd, upb_status *status) {
  7700. upb_pb_encoder *e = c;
  7701. UPB_UNUSED(hd);
  7702. UPB_UNUSED(status);
  7703. if (--e->depth == 0) {
  7704. upb_bytessink_end(e->output_);
  7705. }
  7706. return true;
  7707. }
  7708. static void *encode_startdelimfield(void *c, const void *hd) {
  7709. bool ok = encode_tag(c, hd) && commit(c) && start_delim(c);
  7710. return ok ? c : UPB_BREAK;
  7711. }
  7712. static bool encode_enddelimfield(void *c, const void *hd) {
  7713. UPB_UNUSED(hd);
  7714. return end_delim(c);
  7715. }
  7716. static void *encode_startgroup(void *c, const void *hd) {
  7717. return (encode_tag(c, hd) && commit(c)) ? c : UPB_BREAK;
  7718. }
  7719. static bool encode_endgroup(void *c, const void *hd) {
  7720. return encode_tag(c, hd) && commit(c);
  7721. }
  7722. static void *encode_startstr(void *c, const void *hd, size_t size_hint) {
  7723. UPB_UNUSED(size_hint);
  7724. return encode_startdelimfield(c, hd);
  7725. }
  7726. static size_t encode_strbuf(void *c, const void *hd, const char *buf,
  7727. size_t len, const upb_bufhandle *h) {
  7728. UPB_UNUSED(hd);
  7729. UPB_UNUSED(h);
  7730. return encode_bytes(c, buf, len) ? len : 0;
  7731. }
  7732. #define T(type, ctype, convert, encode) \
  7733. static bool encode_scalar_##type(void *e, const void *hd, ctype val) { \
  7734. return encode_tag(e, hd) && encode(e, (convert)(val)) && commit(e); \
  7735. } \
  7736. static bool encode_packed_##type(void *e, const void *hd, ctype val) { \
  7737. UPB_UNUSED(hd); \
  7738. return encode(e, (convert)(val)); \
  7739. }
  7740. T(double, double, dbl2uint64, encode_fixed64)
  7741. T(float, float, flt2uint32, encode_fixed32)
  7742. T(int64, int64_t, uint64_t, encode_varint)
  7743. T(int32, int32_t, uint32_t, encode_varint)
  7744. T(fixed64, uint64_t, uint64_t, encode_fixed64)
  7745. T(fixed32, uint32_t, uint32_t, encode_fixed32)
  7746. T(bool, bool, bool, encode_varint)
  7747. T(uint32, uint32_t, uint32_t, encode_varint)
  7748. T(uint64, uint64_t, uint64_t, encode_varint)
  7749. T(enum, int32_t, uint32_t, encode_varint)
  7750. T(sfixed32, int32_t, uint32_t, encode_fixed32)
  7751. T(sfixed64, int64_t, uint64_t, encode_fixed64)
  7752. T(sint32, int32_t, upb_zzenc_32, encode_varint)
  7753. T(sint64, int64_t, upb_zzenc_64, encode_varint)
  7754. #undef T
  7755. /* code to build the handlers *************************************************/
  7756. static void newhandlers_callback(const void *closure, upb_handlers *h) {
  7757. const upb_msgdef *m;
  7758. upb_msg_field_iter i;
  7759. UPB_UNUSED(closure);
  7760. upb_handlers_setstartmsg(h, startmsg, NULL);
  7761. upb_handlers_setendmsg(h, endmsg, NULL);
  7762. m = upb_handlers_msgdef(h);
  7763. for(upb_msg_field_begin(&i, m);
  7764. !upb_msg_field_done(&i);
  7765. upb_msg_field_next(&i)) {
  7766. const upb_fielddef *f = upb_msg_iter_field(&i);
  7767. bool packed = upb_fielddef_isseq(f) && upb_fielddef_isprimitive(f) &&
  7768. upb_fielddef_packed(f);
  7769. upb_handlerattr attr;
  7770. upb_wiretype_t wt =
  7771. packed ? UPB_WIRE_TYPE_DELIMITED
  7772. : upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  7773. /* Pre-encode the tag for this field. */
  7774. new_tag(h, f, wt, &attr);
  7775. if (packed) {
  7776. upb_handlers_setstartseq(h, f, encode_startdelimfield, &attr);
  7777. upb_handlers_setendseq(h, f, encode_enddelimfield, &attr);
  7778. }
  7779. #define T(upper, lower, upbtype) \
  7780. case UPB_DESCRIPTOR_TYPE_##upper: \
  7781. if (packed) { \
  7782. upb_handlers_set##upbtype(h, f, encode_packed_##lower, &attr); \
  7783. } else { \
  7784. upb_handlers_set##upbtype(h, f, encode_scalar_##lower, &attr); \
  7785. } \
  7786. break;
  7787. switch (upb_fielddef_descriptortype(f)) {
  7788. T(DOUBLE, double, double);
  7789. T(FLOAT, float, float);
  7790. T(INT64, int64, int64);
  7791. T(INT32, int32, int32);
  7792. T(FIXED64, fixed64, uint64);
  7793. T(FIXED32, fixed32, uint32);
  7794. T(BOOL, bool, bool);
  7795. T(UINT32, uint32, uint32);
  7796. T(UINT64, uint64, uint64);
  7797. T(ENUM, enum, int32);
  7798. T(SFIXED32, sfixed32, int32);
  7799. T(SFIXED64, sfixed64, int64);
  7800. T(SINT32, sint32, int32);
  7801. T(SINT64, sint64, int64);
  7802. case UPB_DESCRIPTOR_TYPE_STRING:
  7803. case UPB_DESCRIPTOR_TYPE_BYTES:
  7804. upb_handlers_setstartstr(h, f, encode_startstr, &attr);
  7805. upb_handlers_setendstr(h, f, encode_enddelimfield, &attr);
  7806. upb_handlers_setstring(h, f, encode_strbuf, &attr);
  7807. break;
  7808. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  7809. upb_handlers_setstartsubmsg(h, f, encode_startdelimfield, &attr);
  7810. upb_handlers_setendsubmsg(h, f, encode_enddelimfield, &attr);
  7811. break;
  7812. case UPB_DESCRIPTOR_TYPE_GROUP: {
  7813. /* Endgroup takes a different tag (wire_type = END_GROUP). */
  7814. upb_handlerattr attr2;
  7815. new_tag(h, f, UPB_WIRE_TYPE_END_GROUP, &attr2);
  7816. upb_handlers_setstartsubmsg(h, f, encode_startgroup, &attr);
  7817. upb_handlers_setendsubmsg(h, f, encode_endgroup, &attr2);
  7818. upb_handlerattr_uninit(&attr2);
  7819. break;
  7820. }
  7821. }
  7822. #undef T
  7823. upb_handlerattr_uninit(&attr);
  7824. }
  7825. }
  7826. void upb_pb_encoder_reset(upb_pb_encoder *e) {
  7827. e->segptr = NULL;
  7828. e->top = NULL;
  7829. e->depth = 0;
  7830. }
  7831. /* public API *****************************************************************/
  7832. const upb_handlers *upb_pb_encoder_newhandlers(const upb_msgdef *m,
  7833. const void *owner) {
  7834. return upb_handlers_newfrozen(m, owner, newhandlers_callback, NULL);
  7835. }
  7836. upb_pb_encoder *upb_pb_encoder_create(upb_env *env, const upb_handlers *h,
  7837. upb_bytessink *output) {
  7838. const size_t initial_bufsize = 256;
  7839. const size_t initial_segbufsize = 16;
  7840. /* TODO(haberman): make this configurable. */
  7841. const size_t stack_size = 64;
  7842. #ifndef NDEBUG
  7843. const size_t size_before = upb_env_bytesallocated(env);
  7844. #endif
  7845. upb_pb_encoder *e = upb_env_malloc(env, sizeof(upb_pb_encoder));
  7846. if (!e) return NULL;
  7847. e->buf = upb_env_malloc(env, initial_bufsize);
  7848. e->segbuf = upb_env_malloc(env, initial_segbufsize * sizeof(*e->segbuf));
  7849. e->stack = upb_env_malloc(env, stack_size * sizeof(*e->stack));
  7850. if (!e->buf || !e->segbuf || !e->stack) {
  7851. return NULL;
  7852. }
  7853. e->limit = e->buf + initial_bufsize;
  7854. e->seglimit = e->segbuf + initial_segbufsize;
  7855. e->stacklimit = e->stack + stack_size;
  7856. upb_pb_encoder_reset(e);
  7857. upb_sink_reset(&e->input_, h, e);
  7858. e->env = env;
  7859. e->output_ = output;
  7860. e->subc = output->closure;
  7861. e->ptr = e->buf;
  7862. /* If this fails, increase the value in encoder.h. */
  7863. assert(upb_env_bytesallocated(env) - size_before <= UPB_PB_ENCODER_SIZE);
  7864. return e;
  7865. }
  7866. upb_sink *upb_pb_encoder_input(upb_pb_encoder *e) { return &e->input_; }
  7867. #include <stdio.h>
  7868. #include <stdlib.h>
  7869. #include <string.h>
  7870. upb_def **upb_load_defs_from_descriptor(const char *str, size_t len, int *n,
  7871. void *owner, upb_status *status) {
  7872. /* Create handlers. */
  7873. const upb_pbdecodermethod *decoder_m;
  7874. const upb_handlers *reader_h = upb_descreader_newhandlers(&reader_h);
  7875. upb_env env;
  7876. upb_pbdecodermethodopts opts;
  7877. upb_pbdecoder *decoder;
  7878. upb_descreader *reader;
  7879. bool ok;
  7880. upb_def **ret = NULL;
  7881. upb_def **defs;
  7882. upb_pbdecodermethodopts_init(&opts, reader_h);
  7883. decoder_m = upb_pbdecodermethod_new(&opts, &decoder_m);
  7884. upb_env_init(&env);
  7885. upb_env_reporterrorsto(&env, status);
  7886. reader = upb_descreader_create(&env, reader_h);
  7887. decoder = upb_pbdecoder_create(&env, decoder_m, upb_descreader_input(reader));
  7888. /* Push input data. */
  7889. ok = upb_bufsrc_putbuf(str, len, upb_pbdecoder_input(decoder));
  7890. if (!ok) goto cleanup;
  7891. defs = upb_descreader_getdefs(reader, owner, n);
  7892. ret = malloc(sizeof(upb_def*) * (*n));
  7893. memcpy(ret, defs, sizeof(upb_def*) * (*n));
  7894. cleanup:
  7895. upb_env_uninit(&env);
  7896. upb_handlers_unref(reader_h, &reader_h);
  7897. upb_pbdecodermethod_unref(decoder_m, &decoder_m);
  7898. return ret;
  7899. }
  7900. bool upb_load_descriptor_into_symtab(upb_symtab *s, const char *str, size_t len,
  7901. upb_status *status) {
  7902. int n;
  7903. bool success;
  7904. upb_def **defs = upb_load_defs_from_descriptor(str, len, &n, &defs, status);
  7905. if (!defs) return false;
  7906. success = upb_symtab_add(s, defs, n, &defs, status);
  7907. free(defs);
  7908. return success;
  7909. }
  7910. char *upb_readfile(const char *filename, size_t *len) {
  7911. long size;
  7912. char *buf;
  7913. FILE *f = fopen(filename, "rb");
  7914. if(!f) return NULL;
  7915. if(fseek(f, 0, SEEK_END) != 0) goto error;
  7916. size = ftell(f);
  7917. if(size < 0) goto error;
  7918. if(fseek(f, 0, SEEK_SET) != 0) goto error;
  7919. buf = malloc(size + 1);
  7920. if(size && fread(buf, size, 1, f) != 1) goto error;
  7921. fclose(f);
  7922. if (len) *len = size;
  7923. return buf;
  7924. error:
  7925. fclose(f);
  7926. return NULL;
  7927. }
  7928. bool upb_load_descriptor_file_into_symtab(upb_symtab *symtab, const char *fname,
  7929. upb_status *status) {
  7930. size_t len;
  7931. bool success;
  7932. char *data = upb_readfile(fname, &len);
  7933. if (!data) {
  7934. if (status) upb_status_seterrf(status, "Couldn't read file: %s", fname);
  7935. return false;
  7936. }
  7937. success = upb_load_descriptor_into_symtab(symtab, data, len, status);
  7938. free(data);
  7939. return success;
  7940. }
  7941. /*
  7942. * upb::pb::TextPrinter
  7943. *
  7944. * OPT: This is not optimized at all. It uses printf() which parses the format
  7945. * string every time, and it allocates memory for every put.
  7946. */
  7947. #include <ctype.h>
  7948. #include <float.h>
  7949. #include <inttypes.h>
  7950. #include <stdarg.h>
  7951. #include <stdio.h>
  7952. #include <stdlib.h>
  7953. #include <string.h>
  7954. struct upb_textprinter {
  7955. upb_sink input_;
  7956. upb_bytessink *output_;
  7957. int indent_depth_;
  7958. bool single_line_;
  7959. void *subc;
  7960. };
  7961. #define CHECK(x) if ((x) < 0) goto err;
  7962. static const char *shortname(const char *longname) {
  7963. const char *last = strrchr(longname, '.');
  7964. return last ? last + 1 : longname;
  7965. }
  7966. static int indent(upb_textprinter *p) {
  7967. int i;
  7968. if (!p->single_line_)
  7969. for (i = 0; i < p->indent_depth_; i++)
  7970. upb_bytessink_putbuf(p->output_, p->subc, " ", 2, NULL);
  7971. return 0;
  7972. }
  7973. static int endfield(upb_textprinter *p) {
  7974. const char ch = (p->single_line_ ? ' ' : '\n');
  7975. upb_bytessink_putbuf(p->output_, p->subc, &ch, 1, NULL);
  7976. return 0;
  7977. }
  7978. static int putescaped(upb_textprinter *p, const char *buf, size_t len,
  7979. bool preserve_utf8) {
  7980. /* Based on CEscapeInternal() from Google's protobuf release. */
  7981. char dstbuf[4096], *dst = dstbuf, *dstend = dstbuf + sizeof(dstbuf);
  7982. const char *end = buf + len;
  7983. /* I think hex is prettier and more useful, but proto2 uses octal; should
  7984. * investigate whether it can parse hex also. */
  7985. const bool use_hex = false;
  7986. bool last_hex_escape = false; /* true if last output char was \xNN */
  7987. for (; buf < end; buf++) {
  7988. bool is_hex_escape;
  7989. if (dstend - dst < 4) {
  7990. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  7991. dst = dstbuf;
  7992. }
  7993. is_hex_escape = false;
  7994. switch (*buf) {
  7995. case '\n': *(dst++) = '\\'; *(dst++) = 'n'; break;
  7996. case '\r': *(dst++) = '\\'; *(dst++) = 'r'; break;
  7997. case '\t': *(dst++) = '\\'; *(dst++) = 't'; break;
  7998. case '\"': *(dst++) = '\\'; *(dst++) = '\"'; break;
  7999. case '\'': *(dst++) = '\\'; *(dst++) = '\''; break;
  8000. case '\\': *(dst++) = '\\'; *(dst++) = '\\'; break;
  8001. default:
  8002. /* Note that if we emit \xNN and the buf character after that is a hex
  8003. * digit then that digit must be escaped too to prevent it being
  8004. * interpreted as part of the character code by C. */
  8005. if ((!preserve_utf8 || (uint8_t)*buf < 0x80) &&
  8006. (!isprint(*buf) || (last_hex_escape && isxdigit(*buf)))) {
  8007. sprintf(dst, (use_hex ? "\\x%02x" : "\\%03o"), (uint8_t)*buf);
  8008. is_hex_escape = use_hex;
  8009. dst += 4;
  8010. } else {
  8011. *(dst++) = *buf; break;
  8012. }
  8013. }
  8014. last_hex_escape = is_hex_escape;
  8015. }
  8016. /* Flush remaining data. */
  8017. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  8018. return 0;
  8019. }
  8020. bool putf(upb_textprinter *p, const char *fmt, ...) {
  8021. va_list args;
  8022. va_list args_copy;
  8023. char *str;
  8024. int written;
  8025. int len;
  8026. bool ok;
  8027. va_start(args, fmt);
  8028. /* Run once to get the length of the string. */
  8029. _upb_va_copy(args_copy, args);
  8030. len = _upb_vsnprintf(NULL, 0, fmt, args_copy);
  8031. va_end(args_copy);
  8032. /* + 1 for NULL terminator (vsprintf() requires it even if we don't). */
  8033. str = malloc(len + 1);
  8034. if (!str) return false;
  8035. written = vsprintf(str, fmt, args);
  8036. va_end(args);
  8037. UPB_ASSERT_VAR(written, written == len);
  8038. ok = upb_bytessink_putbuf(p->output_, p->subc, str, len, NULL);
  8039. free(str);
  8040. return ok;
  8041. }
  8042. /* handlers *******************************************************************/
  8043. static bool textprinter_startmsg(void *c, const void *hd) {
  8044. upb_textprinter *p = c;
  8045. UPB_UNUSED(hd);
  8046. if (p->indent_depth_ == 0) {
  8047. upb_bytessink_start(p->output_, 0, &p->subc);
  8048. }
  8049. return true;
  8050. }
  8051. static bool textprinter_endmsg(void *c, const void *hd, upb_status *s) {
  8052. upb_textprinter *p = c;
  8053. UPB_UNUSED(hd);
  8054. UPB_UNUSED(s);
  8055. if (p->indent_depth_ == 0) {
  8056. upb_bytessink_end(p->output_);
  8057. }
  8058. return true;
  8059. }
  8060. #define TYPE(name, ctype, fmt) \
  8061. static bool textprinter_put ## name(void *closure, const void *handler_data, \
  8062. ctype val) { \
  8063. upb_textprinter *p = closure; \
  8064. const upb_fielddef *f = handler_data; \
  8065. CHECK(indent(p)); \
  8066. putf(p, "%s: " fmt, upb_fielddef_name(f), val); \
  8067. CHECK(endfield(p)); \
  8068. return true; \
  8069. err: \
  8070. return false; \
  8071. }
  8072. static bool textprinter_putbool(void *closure, const void *handler_data,
  8073. bool val) {
  8074. upb_textprinter *p = closure;
  8075. const upb_fielddef *f = handler_data;
  8076. CHECK(indent(p));
  8077. putf(p, "%s: %s", upb_fielddef_name(f), val ? "true" : "false");
  8078. CHECK(endfield(p));
  8079. return true;
  8080. err:
  8081. return false;
  8082. }
  8083. #define STRINGIFY_HELPER(x) #x
  8084. #define STRINGIFY_MACROVAL(x) STRINGIFY_HELPER(x)
  8085. TYPE(int32, int32_t, "%" PRId32)
  8086. TYPE(int64, int64_t, "%" PRId64)
  8087. TYPE(uint32, uint32_t, "%" PRIu32)
  8088. TYPE(uint64, uint64_t, "%" PRIu64)
  8089. TYPE(float, float, "%." STRINGIFY_MACROVAL(FLT_DIG) "g")
  8090. TYPE(double, double, "%." STRINGIFY_MACROVAL(DBL_DIG) "g")
  8091. #undef TYPE
  8092. /* Output a symbolic value from the enum if found, else just print as int32. */
  8093. static bool textprinter_putenum(void *closure, const void *handler_data,
  8094. int32_t val) {
  8095. upb_textprinter *p = closure;
  8096. const upb_fielddef *f = handler_data;
  8097. const upb_enumdef *enum_def = upb_downcast_enumdef(upb_fielddef_subdef(f));
  8098. const char *label = upb_enumdef_iton(enum_def, val);
  8099. if (label) {
  8100. indent(p);
  8101. putf(p, "%s: %s", upb_fielddef_name(f), label);
  8102. endfield(p);
  8103. } else {
  8104. if (!textprinter_putint32(closure, handler_data, val))
  8105. return false;
  8106. }
  8107. return true;
  8108. }
  8109. static void *textprinter_startstr(void *closure, const void *handler_data,
  8110. size_t size_hint) {
  8111. upb_textprinter *p = closure;
  8112. const upb_fielddef *f = handler_data;
  8113. UPB_UNUSED(size_hint);
  8114. indent(p);
  8115. putf(p, "%s: \"", upb_fielddef_name(f));
  8116. return p;
  8117. }
  8118. static bool textprinter_endstr(void *closure, const void *handler_data) {
  8119. upb_textprinter *p = closure;
  8120. UPB_UNUSED(handler_data);
  8121. putf(p, "\"");
  8122. endfield(p);
  8123. return true;
  8124. }
  8125. static size_t textprinter_putstr(void *closure, const void *hd, const char *buf,
  8126. size_t len, const upb_bufhandle *handle) {
  8127. upb_textprinter *p = closure;
  8128. const upb_fielddef *f = hd;
  8129. UPB_UNUSED(handle);
  8130. CHECK(putescaped(p, buf, len, upb_fielddef_type(f) == UPB_TYPE_STRING));
  8131. return len;
  8132. err:
  8133. return 0;
  8134. }
  8135. static void *textprinter_startsubmsg(void *closure, const void *handler_data) {
  8136. upb_textprinter *p = closure;
  8137. const char *name = handler_data;
  8138. CHECK(indent(p));
  8139. putf(p, "%s {%c", name, p->single_line_ ? ' ' : '\n');
  8140. p->indent_depth_++;
  8141. return p;
  8142. err:
  8143. return UPB_BREAK;
  8144. }
  8145. static bool textprinter_endsubmsg(void *closure, const void *handler_data) {
  8146. upb_textprinter *p = closure;
  8147. UPB_UNUSED(handler_data);
  8148. p->indent_depth_--;
  8149. CHECK(indent(p));
  8150. upb_bytessink_putbuf(p->output_, p->subc, "}", 1, NULL);
  8151. CHECK(endfield(p));
  8152. return true;
  8153. err:
  8154. return false;
  8155. }
  8156. static void onmreg(const void *c, upb_handlers *h) {
  8157. const upb_msgdef *m = upb_handlers_msgdef(h);
  8158. upb_msg_field_iter i;
  8159. UPB_UNUSED(c);
  8160. upb_handlers_setstartmsg(h, textprinter_startmsg, NULL);
  8161. upb_handlers_setendmsg(h, textprinter_endmsg, NULL);
  8162. for(upb_msg_field_begin(&i, m);
  8163. !upb_msg_field_done(&i);
  8164. upb_msg_field_next(&i)) {
  8165. upb_fielddef *f = upb_msg_iter_field(&i);
  8166. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  8167. upb_handlerattr_sethandlerdata(&attr, f);
  8168. switch (upb_fielddef_type(f)) {
  8169. case UPB_TYPE_INT32:
  8170. upb_handlers_setint32(h, f, textprinter_putint32, &attr);
  8171. break;
  8172. case UPB_TYPE_INT64:
  8173. upb_handlers_setint64(h, f, textprinter_putint64, &attr);
  8174. break;
  8175. case UPB_TYPE_UINT32:
  8176. upb_handlers_setuint32(h, f, textprinter_putuint32, &attr);
  8177. break;
  8178. case UPB_TYPE_UINT64:
  8179. upb_handlers_setuint64(h, f, textprinter_putuint64, &attr);
  8180. break;
  8181. case UPB_TYPE_FLOAT:
  8182. upb_handlers_setfloat(h, f, textprinter_putfloat, &attr);
  8183. break;
  8184. case UPB_TYPE_DOUBLE:
  8185. upb_handlers_setdouble(h, f, textprinter_putdouble, &attr);
  8186. break;
  8187. case UPB_TYPE_BOOL:
  8188. upb_handlers_setbool(h, f, textprinter_putbool, &attr);
  8189. break;
  8190. case UPB_TYPE_STRING:
  8191. case UPB_TYPE_BYTES:
  8192. upb_handlers_setstartstr(h, f, textprinter_startstr, &attr);
  8193. upb_handlers_setstring(h, f, textprinter_putstr, &attr);
  8194. upb_handlers_setendstr(h, f, textprinter_endstr, &attr);
  8195. break;
  8196. case UPB_TYPE_MESSAGE: {
  8197. const char *name =
  8198. upb_fielddef_istagdelim(f)
  8199. ? shortname(upb_msgdef_fullname(upb_fielddef_msgsubdef(f)))
  8200. : upb_fielddef_name(f);
  8201. upb_handlerattr_sethandlerdata(&attr, name);
  8202. upb_handlers_setstartsubmsg(h, f, textprinter_startsubmsg, &attr);
  8203. upb_handlers_setendsubmsg(h, f, textprinter_endsubmsg, &attr);
  8204. break;
  8205. }
  8206. case UPB_TYPE_ENUM:
  8207. upb_handlers_setint32(h, f, textprinter_putenum, &attr);
  8208. break;
  8209. }
  8210. }
  8211. }
  8212. static void textprinter_reset(upb_textprinter *p, bool single_line) {
  8213. p->single_line_ = single_line;
  8214. p->indent_depth_ = 0;
  8215. }
  8216. /* Public API *****************************************************************/
  8217. upb_textprinter *upb_textprinter_create(upb_env *env, const upb_handlers *h,
  8218. upb_bytessink *output) {
  8219. upb_textprinter *p = upb_env_malloc(env, sizeof(upb_textprinter));
  8220. if (!p) return NULL;
  8221. p->output_ = output;
  8222. upb_sink_reset(&p->input_, h, p);
  8223. textprinter_reset(p, false);
  8224. return p;
  8225. }
  8226. const upb_handlers *upb_textprinter_newhandlers(const upb_msgdef *m,
  8227. const void *owner) {
  8228. return upb_handlers_newfrozen(m, owner, &onmreg, NULL);
  8229. }
  8230. upb_sink *upb_textprinter_input(upb_textprinter *p) { return &p->input_; }
  8231. void upb_textprinter_setsingleline(upb_textprinter *p, bool single_line) {
  8232. p->single_line_ = single_line;
  8233. }
  8234. /* Index is descriptor type. */
  8235. const uint8_t upb_pb_native_wire_types[] = {
  8236. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  8237. UPB_WIRE_TYPE_64BIT, /* DOUBLE */
  8238. UPB_WIRE_TYPE_32BIT, /* FLOAT */
  8239. UPB_WIRE_TYPE_VARINT, /* INT64 */
  8240. UPB_WIRE_TYPE_VARINT, /* UINT64 */
  8241. UPB_WIRE_TYPE_VARINT, /* INT32 */
  8242. UPB_WIRE_TYPE_64BIT, /* FIXED64 */
  8243. UPB_WIRE_TYPE_32BIT, /* FIXED32 */
  8244. UPB_WIRE_TYPE_VARINT, /* BOOL */
  8245. UPB_WIRE_TYPE_DELIMITED, /* STRING */
  8246. UPB_WIRE_TYPE_START_GROUP, /* GROUP */
  8247. UPB_WIRE_TYPE_DELIMITED, /* MESSAGE */
  8248. UPB_WIRE_TYPE_DELIMITED, /* BYTES */
  8249. UPB_WIRE_TYPE_VARINT, /* UINT32 */
  8250. UPB_WIRE_TYPE_VARINT, /* ENUM */
  8251. UPB_WIRE_TYPE_32BIT, /* SFIXED32 */
  8252. UPB_WIRE_TYPE_64BIT, /* SFIXED64 */
  8253. UPB_WIRE_TYPE_VARINT, /* SINT32 */
  8254. UPB_WIRE_TYPE_VARINT, /* SINT64 */
  8255. };
  8256. /* A basic branch-based decoder, uses 32-bit values to get good performance
  8257. * on 32-bit architectures (but performs well on 64-bits also).
  8258. * This scheme comes from the original Google Protobuf implementation
  8259. * (proto2). */
  8260. upb_decoderet upb_vdecode_max8_branch32(upb_decoderet r) {
  8261. upb_decoderet err = {NULL, 0};
  8262. const char *p = r.p;
  8263. uint32_t low = (uint32_t)r.val;
  8264. uint32_t high = 0;
  8265. uint32_t b;
  8266. b = *(p++); low |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  8267. b = *(p++); low |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  8268. b = *(p++); low |= (b & 0x7fU) << 28;
  8269. high = (b & 0x7fU) >> 4; if (!(b & 0x80)) goto done;
  8270. b = *(p++); high |= (b & 0x7fU) << 3; if (!(b & 0x80)) goto done;
  8271. b = *(p++); high |= (b & 0x7fU) << 10; if (!(b & 0x80)) goto done;
  8272. b = *(p++); high |= (b & 0x7fU) << 17; if (!(b & 0x80)) goto done;
  8273. b = *(p++); high |= (b & 0x7fU) << 24; if (!(b & 0x80)) goto done;
  8274. b = *(p++); high |= (b & 0x7fU) << 31; if (!(b & 0x80)) goto done;
  8275. return err;
  8276. done:
  8277. r.val = ((uint64_t)high << 32) | low;
  8278. r.p = p;
  8279. return r;
  8280. }
  8281. /* Like the previous, but uses 64-bit values. */
  8282. upb_decoderet upb_vdecode_max8_branch64(upb_decoderet r) {
  8283. const char *p = r.p;
  8284. uint64_t val = r.val;
  8285. uint64_t b;
  8286. upb_decoderet err = {NULL, 0};
  8287. b = *(p++); val |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  8288. b = *(p++); val |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  8289. b = *(p++); val |= (b & 0x7fU) << 28; if (!(b & 0x80)) goto done;
  8290. b = *(p++); val |= (b & 0x7fU) << 35; if (!(b & 0x80)) goto done;
  8291. b = *(p++); val |= (b & 0x7fU) << 42; if (!(b & 0x80)) goto done;
  8292. b = *(p++); val |= (b & 0x7fU) << 49; if (!(b & 0x80)) goto done;
  8293. b = *(p++); val |= (b & 0x7fU) << 56; if (!(b & 0x80)) goto done;
  8294. b = *(p++); val |= (b & 0x7fU) << 63; if (!(b & 0x80)) goto done;
  8295. return err;
  8296. done:
  8297. r.val = val;
  8298. r.p = p;
  8299. return r;
  8300. }
  8301. /* Given an encoded varint v, returns an integer with a single bit set that
  8302. * indicates the end of the varint. Subtracting one from this value will
  8303. * yield a mask that leaves only bits that are part of the varint. Returns
  8304. * 0 if the varint is unterminated. */
  8305. static uint64_t upb_get_vstopbit(uint64_t v) {
  8306. uint64_t cbits = v | 0x7f7f7f7f7f7f7f7fULL;
  8307. return ~cbits & (cbits+1);
  8308. }
  8309. /* A branchless decoder. Credit to Pascal Massimino for the bit-twiddling. */
  8310. upb_decoderet upb_vdecode_max8_massimino(upb_decoderet r) {
  8311. uint64_t b;
  8312. uint64_t stop_bit;
  8313. upb_decoderet my_r;
  8314. memcpy(&b, r.p, sizeof(b));
  8315. stop_bit = upb_get_vstopbit(b);
  8316. b = (b & 0x7f7f7f7f7f7f7f7fULL) & (stop_bit - 1);
  8317. b += b & 0x007f007f007f007fULL;
  8318. b += 3 * (b & 0x0000ffff0000ffffULL);
  8319. b += 15 * (b & 0x00000000ffffffffULL);
  8320. if (stop_bit == 0) {
  8321. /* Error: unterminated varint. */
  8322. upb_decoderet err_r = {(void*)0, 0};
  8323. return err_r;
  8324. }
  8325. my_r = upb_decoderet_make(r.p + ((__builtin_ctzll(stop_bit) + 1) / 8),
  8326. r.val | (b << 7));
  8327. return my_r;
  8328. }
  8329. /* A branchless decoder. Credit to Daniel Wright for the bit-twiddling. */
  8330. upb_decoderet upb_vdecode_max8_wright(upb_decoderet r) {
  8331. uint64_t b;
  8332. uint64_t stop_bit;
  8333. upb_decoderet my_r;
  8334. memcpy(&b, r.p, sizeof(b));
  8335. stop_bit = upb_get_vstopbit(b);
  8336. b &= (stop_bit - 1);
  8337. b = ((b & 0x7f007f007f007f00ULL) >> 1) | (b & 0x007f007f007f007fULL);
  8338. b = ((b & 0xffff0000ffff0000ULL) >> 2) | (b & 0x0000ffff0000ffffULL);
  8339. b = ((b & 0xffffffff00000000ULL) >> 4) | (b & 0x00000000ffffffffULL);
  8340. if (stop_bit == 0) {
  8341. /* Error: unterminated varint. */
  8342. upb_decoderet err_r = {(void*)0, 0};
  8343. return err_r;
  8344. }
  8345. my_r = upb_decoderet_make(r.p + ((__builtin_ctzll(stop_bit) + 1) / 8),
  8346. r.val | (b << 14));
  8347. return my_r;
  8348. }
  8349. #line 1 "upb/json/parser.rl"
  8350. /*
  8351. ** upb::json::Parser (upb_json_parser)
  8352. **
  8353. ** A parser that uses the Ragel State Machine Compiler to generate
  8354. ** the finite automata.
  8355. **
  8356. ** Ragel only natively handles regular languages, but we can manually
  8357. ** program it a bit to handle context-free languages like JSON, by using
  8358. ** the "fcall" and "fret" constructs.
  8359. **
  8360. ** This parser can handle the basics, but needs several things to be fleshed
  8361. ** out:
  8362. **
  8363. ** - handling of unicode escape sequences (including high surrogate pairs).
  8364. ** - properly check and report errors for unknown fields, stack overflow,
  8365. ** improper array nesting (or lack of nesting).
  8366. ** - handling of base64 sequences with padding characters.
  8367. ** - handling of push-back (non-success returns from sink functions).
  8368. ** - handling of keys/escape-sequences/etc that span input buffers.
  8369. */
  8370. #include <stdio.h>
  8371. #include <stdint.h>
  8372. #include <assert.h>
  8373. #include <string.h>
  8374. #include <stdlib.h>
  8375. #include <errno.h>
  8376. #define UPB_JSON_MAX_DEPTH 64
  8377. typedef struct {
  8378. upb_sink sink;
  8379. /* The current message in which we're parsing, and the field whose value we're
  8380. * expecting next. */
  8381. const upb_msgdef *m;
  8382. const upb_fielddef *f;
  8383. /* We are in a repeated-field context, ready to emit mapentries as
  8384. * submessages. This flag alters the start-of-object (open-brace) behavior to
  8385. * begin a sequence of mapentry messages rather than a single submessage. */
  8386. bool is_map;
  8387. /* We are in a map-entry message context. This flag is set when parsing the
  8388. * value field of a single map entry and indicates to all value-field parsers
  8389. * (subobjects, strings, numbers, and bools) that the map-entry submessage
  8390. * should end as soon as the value is parsed. */
  8391. bool is_mapentry;
  8392. /* If |is_map| or |is_mapentry| is true, |mapfield| refers to the parent
  8393. * message's map field that we're currently parsing. This differs from |f|
  8394. * because |f| is the field in the *current* message (i.e., the map-entry
  8395. * message itself), not the parent's field that leads to this map. */
  8396. const upb_fielddef *mapfield;
  8397. } upb_jsonparser_frame;
  8398. struct upb_json_parser {
  8399. upb_env *env;
  8400. upb_byteshandler input_handler_;
  8401. upb_bytessink input_;
  8402. /* Stack to track the JSON scopes we are in. */
  8403. upb_jsonparser_frame stack[UPB_JSON_MAX_DEPTH];
  8404. upb_jsonparser_frame *top;
  8405. upb_jsonparser_frame *limit;
  8406. upb_status status;
  8407. /* Ragel's internal parsing stack for the parsing state machine. */
  8408. int current_state;
  8409. int parser_stack[UPB_JSON_MAX_DEPTH];
  8410. int parser_top;
  8411. /* The handle for the current buffer. */
  8412. const upb_bufhandle *handle;
  8413. /* Accumulate buffer. See details in parser.rl. */
  8414. const char *accumulated;
  8415. size_t accumulated_len;
  8416. char *accumulate_buf;
  8417. size_t accumulate_buf_size;
  8418. /* Multi-part text data. See details in parser.rl. */
  8419. int multipart_state;
  8420. upb_selector_t string_selector;
  8421. /* Input capture. See details in parser.rl. */
  8422. const char *capture;
  8423. /* Intermediate result of parsing a unicode escape sequence. */
  8424. uint32_t digit;
  8425. };
  8426. #define PARSER_CHECK_RETURN(x) if (!(x)) return false
  8427. /* Used to signal that a capture has been suspended. */
  8428. static char suspend_capture;
  8429. static upb_selector_t getsel_for_handlertype(upb_json_parser *p,
  8430. upb_handlertype_t type) {
  8431. upb_selector_t sel;
  8432. bool ok = upb_handlers_getselector(p->top->f, type, &sel);
  8433. UPB_ASSERT_VAR(ok, ok);
  8434. return sel;
  8435. }
  8436. static upb_selector_t parser_getsel(upb_json_parser *p) {
  8437. return getsel_for_handlertype(
  8438. p, upb_handlers_getprimitivehandlertype(p->top->f));
  8439. }
  8440. static bool check_stack(upb_json_parser *p) {
  8441. if ((p->top + 1) == p->limit) {
  8442. upb_status_seterrmsg(&p->status, "Nesting too deep");
  8443. upb_env_reporterror(p->env, &p->status);
  8444. return false;
  8445. }
  8446. return true;
  8447. }
  8448. /* There are GCC/Clang built-ins for overflow checking which we could start
  8449. * using if there was any performance benefit to it. */
  8450. static bool checked_add(size_t a, size_t b, size_t *c) {
  8451. if (SIZE_MAX - a < b) return false;
  8452. *c = a + b;
  8453. return true;
  8454. }
  8455. static size_t saturating_multiply(size_t a, size_t b) {
  8456. /* size_t is unsigned, so this is defined behavior even on overflow. */
  8457. size_t ret = a * b;
  8458. if (b != 0 && ret / b != a) {
  8459. ret = SIZE_MAX;
  8460. }
  8461. return ret;
  8462. }
  8463. /* Base64 decoding ************************************************************/
  8464. /* TODO(haberman): make this streaming. */
  8465. static const signed char b64table[] = {
  8466. -1, -1, -1, -1, -1, -1, -1, -1,
  8467. -1, -1, -1, -1, -1, -1, -1, -1,
  8468. -1, -1, -1, -1, -1, -1, -1, -1,
  8469. -1, -1, -1, -1, -1, -1, -1, -1,
  8470. -1, -1, -1, -1, -1, -1, -1, -1,
  8471. -1, -1, -1, 62/*+*/, -1, -1, -1, 63/*/ */,
  8472. 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
  8473. 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1,
  8474. -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
  8475. 07/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
  8476. 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
  8477. 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, -1,
  8478. -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
  8479. 33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
  8480. 41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
  8481. 49/*x*/, 50/*y*/, 51/*z*/, -1, -1, -1, -1, -1,
  8482. -1, -1, -1, -1, -1, -1, -1, -1,
  8483. -1, -1, -1, -1, -1, -1, -1, -1,
  8484. -1, -1, -1, -1, -1, -1, -1, -1,
  8485. -1, -1, -1, -1, -1, -1, -1, -1,
  8486. -1, -1, -1, -1, -1, -1, -1, -1,
  8487. -1, -1, -1, -1, -1, -1, -1, -1,
  8488. -1, -1, -1, -1, -1, -1, -1, -1,
  8489. -1, -1, -1, -1, -1, -1, -1, -1,
  8490. -1, -1, -1, -1, -1, -1, -1, -1,
  8491. -1, -1, -1, -1, -1, -1, -1, -1,
  8492. -1, -1, -1, -1, -1, -1, -1, -1,
  8493. -1, -1, -1, -1, -1, -1, -1, -1,
  8494. -1, -1, -1, -1, -1, -1, -1, -1,
  8495. -1, -1, -1, -1, -1, -1, -1, -1,
  8496. -1, -1, -1, -1, -1, -1, -1, -1,
  8497. -1, -1, -1, -1, -1, -1, -1, -1
  8498. };
  8499. /* Returns the table value sign-extended to 32 bits. Knowing that the upper
  8500. * bits will be 1 for unrecognized characters makes it easier to check for
  8501. * this error condition later (see below). */
  8502. int32_t b64lookup(unsigned char ch) { return b64table[ch]; }
  8503. /* Returns true if the given character is not a valid base64 character or
  8504. * padding. */
  8505. bool nonbase64(unsigned char ch) { return b64lookup(ch) == -1 && ch != '='; }
  8506. static bool base64_push(upb_json_parser *p, upb_selector_t sel, const char *ptr,
  8507. size_t len) {
  8508. const char *limit = ptr + len;
  8509. for (; ptr < limit; ptr += 4) {
  8510. uint32_t val;
  8511. char output[3];
  8512. if (limit - ptr < 4) {
  8513. upb_status_seterrf(&p->status,
  8514. "Base64 input for bytes field not a multiple of 4: %s",
  8515. upb_fielddef_name(p->top->f));
  8516. upb_env_reporterror(p->env, &p->status);
  8517. return false;
  8518. }
  8519. val = b64lookup(ptr[0]) << 18 |
  8520. b64lookup(ptr[1]) << 12 |
  8521. b64lookup(ptr[2]) << 6 |
  8522. b64lookup(ptr[3]);
  8523. /* Test the upper bit; returns true if any of the characters returned -1. */
  8524. if (val & 0x80000000) {
  8525. goto otherchar;
  8526. }
  8527. output[0] = val >> 16;
  8528. output[1] = (val >> 8) & 0xff;
  8529. output[2] = val & 0xff;
  8530. upb_sink_putstring(&p->top->sink, sel, output, 3, NULL);
  8531. }
  8532. return true;
  8533. otherchar:
  8534. if (nonbase64(ptr[0]) || nonbase64(ptr[1]) || nonbase64(ptr[2]) ||
  8535. nonbase64(ptr[3]) ) {
  8536. upb_status_seterrf(&p->status,
  8537. "Non-base64 characters in bytes field: %s",
  8538. upb_fielddef_name(p->top->f));
  8539. upb_env_reporterror(p->env, &p->status);
  8540. return false;
  8541. } if (ptr[2] == '=') {
  8542. uint32_t val;
  8543. char output;
  8544. /* Last group contains only two input bytes, one output byte. */
  8545. if (ptr[0] == '=' || ptr[1] == '=' || ptr[3] != '=') {
  8546. goto badpadding;
  8547. }
  8548. val = b64lookup(ptr[0]) << 18 |
  8549. b64lookup(ptr[1]) << 12;
  8550. assert(!(val & 0x80000000));
  8551. output = val >> 16;
  8552. upb_sink_putstring(&p->top->sink, sel, &output, 1, NULL);
  8553. return true;
  8554. } else {
  8555. uint32_t val;
  8556. char output[2];
  8557. /* Last group contains only three input bytes, two output bytes. */
  8558. if (ptr[0] == '=' || ptr[1] == '=' || ptr[2] == '=') {
  8559. goto badpadding;
  8560. }
  8561. val = b64lookup(ptr[0]) << 18 |
  8562. b64lookup(ptr[1]) << 12 |
  8563. b64lookup(ptr[2]) << 6;
  8564. output[0] = val >> 16;
  8565. output[1] = (val >> 8) & 0xff;
  8566. upb_sink_putstring(&p->top->sink, sel, output, 2, NULL);
  8567. return true;
  8568. }
  8569. badpadding:
  8570. upb_status_seterrf(&p->status,
  8571. "Incorrect base64 padding for field: %s (%.*s)",
  8572. upb_fielddef_name(p->top->f),
  8573. 4, ptr);
  8574. upb_env_reporterror(p->env, &p->status);
  8575. return false;
  8576. }
  8577. /* Accumulate buffer **********************************************************/
  8578. /* Functionality for accumulating a buffer.
  8579. *
  8580. * Some parts of the parser need an entire value as a contiguous string. For
  8581. * example, to look up a member name in a hash table, or to turn a string into
  8582. * a number, the relevant library routines need the input string to be in
  8583. * contiguous memory, even if the value spanned two or more buffers in the
  8584. * input. These routines handle that.
  8585. *
  8586. * In the common case we can just point to the input buffer to get this
  8587. * contiguous string and avoid any actual copy. So we optimistically begin
  8588. * this way. But there are a few cases where we must instead copy into a
  8589. * separate buffer:
  8590. *
  8591. * 1. The string was not contiguous in the input (it spanned buffers).
  8592. *
  8593. * 2. The string included escape sequences that need to be interpreted to get
  8594. * the true value in a contiguous buffer. */
  8595. static void assert_accumulate_empty(upb_json_parser *p) {
  8596. UPB_UNUSED(p);
  8597. assert(p->accumulated == NULL);
  8598. assert(p->accumulated_len == 0);
  8599. }
  8600. static void accumulate_clear(upb_json_parser *p) {
  8601. p->accumulated = NULL;
  8602. p->accumulated_len = 0;
  8603. }
  8604. /* Used internally by accumulate_append(). */
  8605. static bool accumulate_realloc(upb_json_parser *p, size_t need) {
  8606. void *mem;
  8607. size_t old_size = p->accumulate_buf_size;
  8608. size_t new_size = UPB_MAX(old_size, 128);
  8609. while (new_size < need) {
  8610. new_size = saturating_multiply(new_size, 2);
  8611. }
  8612. mem = upb_env_realloc(p->env, p->accumulate_buf, old_size, new_size);
  8613. if (!mem) {
  8614. upb_status_seterrmsg(&p->status, "Out of memory allocating buffer.");
  8615. upb_env_reporterror(p->env, &p->status);
  8616. return false;
  8617. }
  8618. p->accumulate_buf = mem;
  8619. p->accumulate_buf_size = new_size;
  8620. return true;
  8621. }
  8622. /* Logically appends the given data to the append buffer.
  8623. * If "can_alias" is true, we will try to avoid actually copying, but the buffer
  8624. * must be valid until the next accumulate_append() call (if any). */
  8625. static bool accumulate_append(upb_json_parser *p, const char *buf, size_t len,
  8626. bool can_alias) {
  8627. size_t need;
  8628. if (!p->accumulated && can_alias) {
  8629. p->accumulated = buf;
  8630. p->accumulated_len = len;
  8631. return true;
  8632. }
  8633. if (!checked_add(p->accumulated_len, len, &need)) {
  8634. upb_status_seterrmsg(&p->status, "Integer overflow.");
  8635. upb_env_reporterror(p->env, &p->status);
  8636. return false;
  8637. }
  8638. if (need > p->accumulate_buf_size && !accumulate_realloc(p, need)) {
  8639. return false;
  8640. }
  8641. if (p->accumulated != p->accumulate_buf) {
  8642. memcpy(p->accumulate_buf, p->accumulated, p->accumulated_len);
  8643. p->accumulated = p->accumulate_buf;
  8644. }
  8645. memcpy(p->accumulate_buf + p->accumulated_len, buf, len);
  8646. p->accumulated_len += len;
  8647. return true;
  8648. }
  8649. /* Returns a pointer to the data accumulated since the last accumulate_clear()
  8650. * call, and writes the length to *len. This with point either to the input
  8651. * buffer or a temporary accumulate buffer. */
  8652. static const char *accumulate_getptr(upb_json_parser *p, size_t *len) {
  8653. assert(p->accumulated);
  8654. *len = p->accumulated_len;
  8655. return p->accumulated;
  8656. }
  8657. /* Mult-part text data ********************************************************/
  8658. /* When we have text data in the input, it can often come in multiple segments.
  8659. * For example, there may be some raw string data followed by an escape
  8660. * sequence. The two segments are processed with different logic. Also buffer
  8661. * seams in the input can cause multiple segments.
  8662. *
  8663. * As we see segments, there are two main cases for how we want to process them:
  8664. *
  8665. * 1. we want to push the captured input directly to string handlers.
  8666. *
  8667. * 2. we need to accumulate all the parts into a contiguous buffer for further
  8668. * processing (field name lookup, string->number conversion, etc). */
  8669. /* This is the set of states for p->multipart_state. */
  8670. enum {
  8671. /* We are not currently processing multipart data. */
  8672. MULTIPART_INACTIVE = 0,
  8673. /* We are processing multipart data by accumulating it into a contiguous
  8674. * buffer. */
  8675. MULTIPART_ACCUMULATE = 1,
  8676. /* We are processing multipart data by pushing each part directly to the
  8677. * current string handlers. */
  8678. MULTIPART_PUSHEAGERLY = 2
  8679. };
  8680. /* Start a multi-part text value where we accumulate the data for processing at
  8681. * the end. */
  8682. static void multipart_startaccum(upb_json_parser *p) {
  8683. assert_accumulate_empty(p);
  8684. assert(p->multipart_state == MULTIPART_INACTIVE);
  8685. p->multipart_state = MULTIPART_ACCUMULATE;
  8686. }
  8687. /* Start a multi-part text value where we immediately push text data to a string
  8688. * value with the given selector. */
  8689. static void multipart_start(upb_json_parser *p, upb_selector_t sel) {
  8690. assert_accumulate_empty(p);
  8691. assert(p->multipart_state == MULTIPART_INACTIVE);
  8692. p->multipart_state = MULTIPART_PUSHEAGERLY;
  8693. p->string_selector = sel;
  8694. }
  8695. static bool multipart_text(upb_json_parser *p, const char *buf, size_t len,
  8696. bool can_alias) {
  8697. switch (p->multipart_state) {
  8698. case MULTIPART_INACTIVE:
  8699. upb_status_seterrmsg(
  8700. &p->status, "Internal error: unexpected state MULTIPART_INACTIVE");
  8701. upb_env_reporterror(p->env, &p->status);
  8702. return false;
  8703. case MULTIPART_ACCUMULATE:
  8704. if (!accumulate_append(p, buf, len, can_alias)) {
  8705. return false;
  8706. }
  8707. break;
  8708. case MULTIPART_PUSHEAGERLY: {
  8709. const upb_bufhandle *handle = can_alias ? p->handle : NULL;
  8710. upb_sink_putstring(&p->top->sink, p->string_selector, buf, len, handle);
  8711. break;
  8712. }
  8713. }
  8714. return true;
  8715. }
  8716. /* Note: this invalidates the accumulate buffer! Call only after reading its
  8717. * contents. */
  8718. static void multipart_end(upb_json_parser *p) {
  8719. assert(p->multipart_state != MULTIPART_INACTIVE);
  8720. p->multipart_state = MULTIPART_INACTIVE;
  8721. accumulate_clear(p);
  8722. }
  8723. /* Input capture **************************************************************/
  8724. /* Functionality for capturing a region of the input as text. Gracefully
  8725. * handles the case where a buffer seam occurs in the middle of the captured
  8726. * region. */
  8727. static void capture_begin(upb_json_parser *p, const char *ptr) {
  8728. assert(p->multipart_state != MULTIPART_INACTIVE);
  8729. assert(p->capture == NULL);
  8730. p->capture = ptr;
  8731. }
  8732. static bool capture_end(upb_json_parser *p, const char *ptr) {
  8733. assert(p->capture);
  8734. if (multipart_text(p, p->capture, ptr - p->capture, true)) {
  8735. p->capture = NULL;
  8736. return true;
  8737. } else {
  8738. return false;
  8739. }
  8740. }
  8741. /* This is called at the end of each input buffer (ie. when we have hit a
  8742. * buffer seam). If we are in the middle of capturing the input, this
  8743. * processes the unprocessed capture region. */
  8744. static void capture_suspend(upb_json_parser *p, const char **ptr) {
  8745. if (!p->capture) return;
  8746. if (multipart_text(p, p->capture, *ptr - p->capture, false)) {
  8747. /* We use this as a signal that we were in the middle of capturing, and
  8748. * that capturing should resume at the beginning of the next buffer.
  8749. *
  8750. * We can't use *ptr here, because we have no guarantee that this pointer
  8751. * will be valid when we resume (if the underlying memory is freed, then
  8752. * using the pointer at all, even to compare to NULL, is likely undefined
  8753. * behavior). */
  8754. p->capture = &suspend_capture;
  8755. } else {
  8756. /* Need to back up the pointer to the beginning of the capture, since
  8757. * we were not able to actually preserve it. */
  8758. *ptr = p->capture;
  8759. }
  8760. }
  8761. static void capture_resume(upb_json_parser *p, const char *ptr) {
  8762. if (p->capture) {
  8763. assert(p->capture == &suspend_capture);
  8764. p->capture = ptr;
  8765. }
  8766. }
  8767. /* Callbacks from the parser **************************************************/
  8768. /* These are the functions called directly from the parser itself.
  8769. * We define these in the same order as their declarations in the parser. */
  8770. static char escape_char(char in) {
  8771. switch (in) {
  8772. case 'r': return '\r';
  8773. case 't': return '\t';
  8774. case 'n': return '\n';
  8775. case 'f': return '\f';
  8776. case 'b': return '\b';
  8777. case '/': return '/';
  8778. case '"': return '"';
  8779. case '\\': return '\\';
  8780. default:
  8781. assert(0);
  8782. return 'x';
  8783. }
  8784. }
  8785. static bool escape(upb_json_parser *p, const char *ptr) {
  8786. char ch = escape_char(*ptr);
  8787. return multipart_text(p, &ch, 1, false);
  8788. }
  8789. static void start_hex(upb_json_parser *p) {
  8790. p->digit = 0;
  8791. }
  8792. static void hexdigit(upb_json_parser *p, const char *ptr) {
  8793. char ch = *ptr;
  8794. p->digit <<= 4;
  8795. if (ch >= '0' && ch <= '9') {
  8796. p->digit += (ch - '0');
  8797. } else if (ch >= 'a' && ch <= 'f') {
  8798. p->digit += ((ch - 'a') + 10);
  8799. } else {
  8800. assert(ch >= 'A' && ch <= 'F');
  8801. p->digit += ((ch - 'A') + 10);
  8802. }
  8803. }
  8804. static bool end_hex(upb_json_parser *p) {
  8805. uint32_t codepoint = p->digit;
  8806. /* emit the codepoint as UTF-8. */
  8807. char utf8[3]; /* support \u0000 -- \uFFFF -- need only three bytes. */
  8808. int length = 0;
  8809. if (codepoint <= 0x7F) {
  8810. utf8[0] = codepoint;
  8811. length = 1;
  8812. } else if (codepoint <= 0x07FF) {
  8813. utf8[1] = (codepoint & 0x3F) | 0x80;
  8814. codepoint >>= 6;
  8815. utf8[0] = (codepoint & 0x1F) | 0xC0;
  8816. length = 2;
  8817. } else /* codepoint <= 0xFFFF */ {
  8818. utf8[2] = (codepoint & 0x3F) | 0x80;
  8819. codepoint >>= 6;
  8820. utf8[1] = (codepoint & 0x3F) | 0x80;
  8821. codepoint >>= 6;
  8822. utf8[0] = (codepoint & 0x0F) | 0xE0;
  8823. length = 3;
  8824. }
  8825. /* TODO(haberman): Handle high surrogates: if codepoint is a high surrogate
  8826. * we have to wait for the next escape to get the full code point). */
  8827. return multipart_text(p, utf8, length, false);
  8828. }
  8829. static void start_text(upb_json_parser *p, const char *ptr) {
  8830. capture_begin(p, ptr);
  8831. }
  8832. static bool end_text(upb_json_parser *p, const char *ptr) {
  8833. return capture_end(p, ptr);
  8834. }
  8835. static void start_number(upb_json_parser *p, const char *ptr) {
  8836. multipart_startaccum(p);
  8837. capture_begin(p, ptr);
  8838. }
  8839. static bool parse_number(upb_json_parser *p);
  8840. static bool end_number(upb_json_parser *p, const char *ptr) {
  8841. if (!capture_end(p, ptr)) {
  8842. return false;
  8843. }
  8844. return parse_number(p);
  8845. }
  8846. static bool parse_number(upb_json_parser *p) {
  8847. size_t len;
  8848. const char *buf;
  8849. const char *myend;
  8850. char *end;
  8851. /* strtol() and friends unfortunately do not support specifying the length of
  8852. * the input string, so we need to force a copy into a NULL-terminated buffer. */
  8853. if (!multipart_text(p, "\0", 1, false)) {
  8854. return false;
  8855. }
  8856. buf = accumulate_getptr(p, &len);
  8857. myend = buf + len - 1; /* One for NULL. */
  8858. /* XXX: We are using strtol to parse integers, but this is wrong as even
  8859. * integers can be represented as 1e6 (for example), which strtol can't
  8860. * handle correctly.
  8861. *
  8862. * XXX: Also, we can't handle large integers properly because strto[u]ll
  8863. * isn't in C89.
  8864. *
  8865. * XXX: Also, we don't properly check floats for overflow, since strtof
  8866. * isn't in C89. */
  8867. switch (upb_fielddef_type(p->top->f)) {
  8868. case UPB_TYPE_ENUM:
  8869. case UPB_TYPE_INT32: {
  8870. long val = strtol(p->accumulated, &end, 0);
  8871. if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || end != myend)
  8872. goto err;
  8873. else
  8874. upb_sink_putint32(&p->top->sink, parser_getsel(p), val);
  8875. break;
  8876. }
  8877. case UPB_TYPE_INT64: {
  8878. long long val = strtol(p->accumulated, &end, 0);
  8879. if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || end != myend)
  8880. goto err;
  8881. else
  8882. upb_sink_putint64(&p->top->sink, parser_getsel(p), val);
  8883. break;
  8884. }
  8885. case UPB_TYPE_UINT32: {
  8886. unsigned long val = strtoul(p->accumulated, &end, 0);
  8887. if (val > UINT32_MAX || errno == ERANGE || end != myend)
  8888. goto err;
  8889. else
  8890. upb_sink_putuint32(&p->top->sink, parser_getsel(p), val);
  8891. break;
  8892. }
  8893. case UPB_TYPE_UINT64: {
  8894. unsigned long long val = strtoul(p->accumulated, &end, 0);
  8895. if (val > UINT64_MAX || errno == ERANGE || end != myend)
  8896. goto err;
  8897. else
  8898. upb_sink_putuint64(&p->top->sink, parser_getsel(p), val);
  8899. break;
  8900. }
  8901. case UPB_TYPE_DOUBLE: {
  8902. double val = strtod(p->accumulated, &end);
  8903. if (errno == ERANGE || end != myend)
  8904. goto err;
  8905. else
  8906. upb_sink_putdouble(&p->top->sink, parser_getsel(p), val);
  8907. break;
  8908. }
  8909. case UPB_TYPE_FLOAT: {
  8910. float val = strtod(p->accumulated, &end);
  8911. if (errno == ERANGE || end != myend)
  8912. goto err;
  8913. else
  8914. upb_sink_putfloat(&p->top->sink, parser_getsel(p), val);
  8915. break;
  8916. }
  8917. default:
  8918. assert(false);
  8919. }
  8920. multipart_end(p);
  8921. return true;
  8922. err:
  8923. upb_status_seterrf(&p->status, "error parsing number: %s", buf);
  8924. upb_env_reporterror(p->env, &p->status);
  8925. multipart_end(p);
  8926. return false;
  8927. }
  8928. static bool parser_putbool(upb_json_parser *p, bool val) {
  8929. bool ok;
  8930. if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL) {
  8931. upb_status_seterrf(&p->status,
  8932. "Boolean value specified for non-bool field: %s",
  8933. upb_fielddef_name(p->top->f));
  8934. upb_env_reporterror(p->env, &p->status);
  8935. return false;
  8936. }
  8937. ok = upb_sink_putbool(&p->top->sink, parser_getsel(p), val);
  8938. UPB_ASSERT_VAR(ok, ok);
  8939. return true;
  8940. }
  8941. static bool start_stringval(upb_json_parser *p) {
  8942. assert(p->top->f);
  8943. if (upb_fielddef_isstring(p->top->f)) {
  8944. upb_jsonparser_frame *inner;
  8945. upb_selector_t sel;
  8946. if (!check_stack(p)) return false;
  8947. /* Start a new parser frame: parser frames correspond one-to-one with
  8948. * handler frames, and string events occur in a sub-frame. */
  8949. inner = p->top + 1;
  8950. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  8951. upb_sink_startstr(&p->top->sink, sel, 0, &inner->sink);
  8952. inner->m = p->top->m;
  8953. inner->f = p->top->f;
  8954. inner->is_map = false;
  8955. inner->is_mapentry = false;
  8956. p->top = inner;
  8957. if (upb_fielddef_type(p->top->f) == UPB_TYPE_STRING) {
  8958. /* For STRING fields we push data directly to the handlers as it is
  8959. * parsed. We don't do this yet for BYTES fields, because our base64
  8960. * decoder is not streaming.
  8961. *
  8962. * TODO(haberman): make base64 decoding streaming also. */
  8963. multipart_start(p, getsel_for_handlertype(p, UPB_HANDLER_STRING));
  8964. return true;
  8965. } else {
  8966. multipart_startaccum(p);
  8967. return true;
  8968. }
  8969. } else if (upb_fielddef_type(p->top->f) == UPB_TYPE_ENUM) {
  8970. /* No need to push a frame -- symbolic enum names in quotes remain in the
  8971. * current parser frame.
  8972. *
  8973. * Enum string values must accumulate so we can look up the value in a table
  8974. * once it is complete. */
  8975. multipart_startaccum(p);
  8976. return true;
  8977. } else {
  8978. upb_status_seterrf(&p->status,
  8979. "String specified for non-string/non-enum field: %s",
  8980. upb_fielddef_name(p->top->f));
  8981. upb_env_reporterror(p->env, &p->status);
  8982. return false;
  8983. }
  8984. }
  8985. static bool end_stringval(upb_json_parser *p) {
  8986. bool ok = true;
  8987. switch (upb_fielddef_type(p->top->f)) {
  8988. case UPB_TYPE_BYTES:
  8989. if (!base64_push(p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  8990. p->accumulated, p->accumulated_len)) {
  8991. return false;
  8992. }
  8993. /* Fall through. */
  8994. case UPB_TYPE_STRING: {
  8995. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  8996. upb_sink_endstr(&p->top->sink, sel);
  8997. p->top--;
  8998. break;
  8999. }
  9000. case UPB_TYPE_ENUM: {
  9001. /* Resolve enum symbolic name to integer value. */
  9002. const upb_enumdef *enumdef =
  9003. (const upb_enumdef*)upb_fielddef_subdef(p->top->f);
  9004. size_t len;
  9005. const char *buf = accumulate_getptr(p, &len);
  9006. int32_t int_val = 0;
  9007. ok = upb_enumdef_ntoi(enumdef, buf, len, &int_val);
  9008. if (ok) {
  9009. upb_selector_t sel = parser_getsel(p);
  9010. upb_sink_putint32(&p->top->sink, sel, int_val);
  9011. } else {
  9012. upb_status_seterrf(&p->status, "Enum value unknown: '%.*s'", len, buf);
  9013. upb_env_reporterror(p->env, &p->status);
  9014. }
  9015. break;
  9016. }
  9017. default:
  9018. assert(false);
  9019. upb_status_seterrmsg(&p->status, "Internal error in JSON decoder");
  9020. upb_env_reporterror(p->env, &p->status);
  9021. ok = false;
  9022. break;
  9023. }
  9024. multipart_end(p);
  9025. return ok;
  9026. }
  9027. static void start_member(upb_json_parser *p) {
  9028. assert(!p->top->f);
  9029. multipart_startaccum(p);
  9030. }
  9031. /* Helper: invoked during parse_mapentry() to emit the mapentry message's key
  9032. * field based on the current contents of the accumulate buffer. */
  9033. static bool parse_mapentry_key(upb_json_parser *p) {
  9034. size_t len;
  9035. const char *buf = accumulate_getptr(p, &len);
  9036. /* Emit the key field. We do a bit of ad-hoc parsing here because the
  9037. * parser state machine has already decided that this is a string field
  9038. * name, and we are reinterpreting it as some arbitrary key type. In
  9039. * particular, integer and bool keys are quoted, so we need to parse the
  9040. * quoted string contents here. */
  9041. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_KEY);
  9042. if (p->top->f == NULL) {
  9043. upb_status_seterrmsg(&p->status, "mapentry message has no key");
  9044. upb_env_reporterror(p->env, &p->status);
  9045. return false;
  9046. }
  9047. switch (upb_fielddef_type(p->top->f)) {
  9048. case UPB_TYPE_INT32:
  9049. case UPB_TYPE_INT64:
  9050. case UPB_TYPE_UINT32:
  9051. case UPB_TYPE_UINT64:
  9052. /* Invoke end_number. The accum buffer has the number's text already. */
  9053. if (!parse_number(p)) {
  9054. return false;
  9055. }
  9056. break;
  9057. case UPB_TYPE_BOOL:
  9058. if (len == 4 && !strncmp(buf, "true", 4)) {
  9059. if (!parser_putbool(p, true)) {
  9060. return false;
  9061. }
  9062. } else if (len == 5 && !strncmp(buf, "false", 5)) {
  9063. if (!parser_putbool(p, false)) {
  9064. return false;
  9065. }
  9066. } else {
  9067. upb_status_seterrmsg(&p->status,
  9068. "Map bool key not 'true' or 'false'");
  9069. upb_env_reporterror(p->env, &p->status);
  9070. return false;
  9071. }
  9072. multipart_end(p);
  9073. break;
  9074. case UPB_TYPE_STRING:
  9075. case UPB_TYPE_BYTES: {
  9076. upb_sink subsink;
  9077. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  9078. upb_sink_startstr(&p->top->sink, sel, len, &subsink);
  9079. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  9080. upb_sink_putstring(&subsink, sel, buf, len, NULL);
  9081. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  9082. upb_sink_endstr(&subsink, sel);
  9083. multipart_end(p);
  9084. break;
  9085. }
  9086. default:
  9087. upb_status_seterrmsg(&p->status, "Invalid field type for map key");
  9088. upb_env_reporterror(p->env, &p->status);
  9089. return false;
  9090. }
  9091. return true;
  9092. }
  9093. /* Helper: emit one map entry (as a submessage in the map field sequence). This
  9094. * is invoked from end_membername(), at the end of the map entry's key string,
  9095. * with the map key in the accumulate buffer. It parses the key from that
  9096. * buffer, emits the handler calls to start the mapentry submessage (setting up
  9097. * its subframe in the process), and sets up state in the subframe so that the
  9098. * value parser (invoked next) will emit the mapentry's value field and then
  9099. * end the mapentry message. */
  9100. static bool handle_mapentry(upb_json_parser *p) {
  9101. const upb_fielddef *mapfield;
  9102. const upb_msgdef *mapentrymsg;
  9103. upb_jsonparser_frame *inner;
  9104. upb_selector_t sel;
  9105. /* Map entry: p->top->sink is the seq frame, so we need to start a frame
  9106. * for the mapentry itself, and then set |f| in that frame so that the map
  9107. * value field is parsed, and also set a flag to end the frame after the
  9108. * map-entry value is parsed. */
  9109. if (!check_stack(p)) return false;
  9110. mapfield = p->top->mapfield;
  9111. mapentrymsg = upb_fielddef_msgsubdef(mapfield);
  9112. inner = p->top + 1;
  9113. p->top->f = mapfield;
  9114. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  9115. upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
  9116. inner->m = mapentrymsg;
  9117. inner->mapfield = mapfield;
  9118. inner->is_map = false;
  9119. /* Don't set this to true *yet* -- we reuse parsing handlers below to push
  9120. * the key field value to the sink, and these handlers will pop the frame
  9121. * if they see is_mapentry (when invoked by the parser state machine, they
  9122. * would have just seen the map-entry value, not key). */
  9123. inner->is_mapentry = false;
  9124. p->top = inner;
  9125. /* send STARTMSG in submsg frame. */
  9126. upb_sink_startmsg(&p->top->sink);
  9127. parse_mapentry_key(p);
  9128. /* Set up the value field to receive the map-entry value. */
  9129. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_VALUE);
  9130. p->top->is_mapentry = true; /* set up to pop frame after value is parsed. */
  9131. p->top->mapfield = mapfield;
  9132. if (p->top->f == NULL) {
  9133. upb_status_seterrmsg(&p->status, "mapentry message has no value");
  9134. upb_env_reporterror(p->env, &p->status);
  9135. return false;
  9136. }
  9137. return true;
  9138. }
  9139. static bool end_membername(upb_json_parser *p) {
  9140. assert(!p->top->f);
  9141. if (p->top->is_map) {
  9142. return handle_mapentry(p);
  9143. } else {
  9144. size_t len;
  9145. const char *buf = accumulate_getptr(p, &len);
  9146. const upb_fielddef *f = upb_msgdef_ntof(p->top->m, buf, len);
  9147. if (!f) {
  9148. /* TODO(haberman): Ignore unknown fields if requested/configured to do
  9149. * so. */
  9150. upb_status_seterrf(&p->status, "No such field: %.*s\n", (int)len, buf);
  9151. upb_env_reporterror(p->env, &p->status);
  9152. return false;
  9153. }
  9154. p->top->f = f;
  9155. multipart_end(p);
  9156. return true;
  9157. }
  9158. }
  9159. static void end_member(upb_json_parser *p) {
  9160. /* If we just parsed a map-entry value, end that frame too. */
  9161. if (p->top->is_mapentry) {
  9162. upb_status s = UPB_STATUS_INIT;
  9163. upb_selector_t sel;
  9164. bool ok;
  9165. const upb_fielddef *mapfield;
  9166. assert(p->top > p->stack);
  9167. /* send ENDMSG on submsg. */
  9168. upb_sink_endmsg(&p->top->sink, &s);
  9169. mapfield = p->top->mapfield;
  9170. /* send ENDSUBMSG in repeated-field-of-mapentries frame. */
  9171. p->top--;
  9172. ok = upb_handlers_getselector(mapfield, UPB_HANDLER_ENDSUBMSG, &sel);
  9173. UPB_ASSERT_VAR(ok, ok);
  9174. upb_sink_endsubmsg(&p->top->sink, sel);
  9175. }
  9176. p->top->f = NULL;
  9177. }
  9178. static bool start_subobject(upb_json_parser *p) {
  9179. assert(p->top->f);
  9180. if (upb_fielddef_ismap(p->top->f)) {
  9181. upb_jsonparser_frame *inner;
  9182. upb_selector_t sel;
  9183. /* Beginning of a map. Start a new parser frame in a repeated-field
  9184. * context. */
  9185. if (!check_stack(p)) return false;
  9186. inner = p->top + 1;
  9187. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  9188. upb_sink_startseq(&p->top->sink, sel, &inner->sink);
  9189. inner->m = upb_fielddef_msgsubdef(p->top->f);
  9190. inner->mapfield = p->top->f;
  9191. inner->f = NULL;
  9192. inner->is_map = true;
  9193. inner->is_mapentry = false;
  9194. p->top = inner;
  9195. return true;
  9196. } else if (upb_fielddef_issubmsg(p->top->f)) {
  9197. upb_jsonparser_frame *inner;
  9198. upb_selector_t sel;
  9199. /* Beginning of a subobject. Start a new parser frame in the submsg
  9200. * context. */
  9201. if (!check_stack(p)) return false;
  9202. inner = p->top + 1;
  9203. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  9204. upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
  9205. inner->m = upb_fielddef_msgsubdef(p->top->f);
  9206. inner->f = NULL;
  9207. inner->is_map = false;
  9208. inner->is_mapentry = false;
  9209. p->top = inner;
  9210. return true;
  9211. } else {
  9212. upb_status_seterrf(&p->status,
  9213. "Object specified for non-message/group field: %s",
  9214. upb_fielddef_name(p->top->f));
  9215. upb_env_reporterror(p->env, &p->status);
  9216. return false;
  9217. }
  9218. }
  9219. static void end_subobject(upb_json_parser *p) {
  9220. if (p->top->is_map) {
  9221. upb_selector_t sel;
  9222. p->top--;
  9223. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  9224. upb_sink_endseq(&p->top->sink, sel);
  9225. } else {
  9226. upb_selector_t sel;
  9227. p->top--;
  9228. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSUBMSG);
  9229. upb_sink_endsubmsg(&p->top->sink, sel);
  9230. }
  9231. }
  9232. static bool start_array(upb_json_parser *p) {
  9233. upb_jsonparser_frame *inner;
  9234. upb_selector_t sel;
  9235. assert(p->top->f);
  9236. if (!upb_fielddef_isseq(p->top->f)) {
  9237. upb_status_seterrf(&p->status,
  9238. "Array specified for non-repeated field: %s",
  9239. upb_fielddef_name(p->top->f));
  9240. upb_env_reporterror(p->env, &p->status);
  9241. return false;
  9242. }
  9243. if (!check_stack(p)) return false;
  9244. inner = p->top + 1;
  9245. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  9246. upb_sink_startseq(&p->top->sink, sel, &inner->sink);
  9247. inner->m = p->top->m;
  9248. inner->f = p->top->f;
  9249. inner->is_map = false;
  9250. inner->is_mapentry = false;
  9251. p->top = inner;
  9252. return true;
  9253. }
  9254. static void end_array(upb_json_parser *p) {
  9255. upb_selector_t sel;
  9256. assert(p->top > p->stack);
  9257. p->top--;
  9258. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  9259. upb_sink_endseq(&p->top->sink, sel);
  9260. }
  9261. static void start_object(upb_json_parser *p) {
  9262. if (!p->top->is_map) {
  9263. upb_sink_startmsg(&p->top->sink);
  9264. }
  9265. }
  9266. static void end_object(upb_json_parser *p) {
  9267. if (!p->top->is_map) {
  9268. upb_status status;
  9269. upb_status_clear(&status);
  9270. upb_sink_endmsg(&p->top->sink, &status);
  9271. if (!upb_ok(&status)) {
  9272. upb_env_reporterror(p->env, &status);
  9273. }
  9274. }
  9275. }
  9276. #define CHECK_RETURN_TOP(x) if (!(x)) goto error
  9277. /* The actual parser **********************************************************/
  9278. /* What follows is the Ragel parser itself. The language is specified in Ragel
  9279. * and the actions call our C functions above.
  9280. *
  9281. * Ragel has an extensive set of functionality, and we use only a small part of
  9282. * it. There are many action types but we only use a few:
  9283. *
  9284. * ">" -- transition into a machine
  9285. * "%" -- transition out of a machine
  9286. * "@" -- transition into a final state of a machine.
  9287. *
  9288. * "@" transitions are tricky because a machine can transition into a final
  9289. * state repeatedly. But in some cases we know this can't happen, for example
  9290. * a string which is delimited by a final '"' can only transition into its
  9291. * final state once, when the closing '"' is seen. */
  9292. #line 1218 "upb/json/parser.rl"
  9293. #line 1130 "upb/json/parser.c"
  9294. static const char _json_actions[] = {
  9295. 0, 1, 0, 1, 2, 1, 3, 1,
  9296. 5, 1, 6, 1, 7, 1, 8, 1,
  9297. 10, 1, 12, 1, 13, 1, 14, 1,
  9298. 15, 1, 16, 1, 17, 1, 21, 1,
  9299. 25, 1, 27, 2, 3, 8, 2, 4,
  9300. 5, 2, 6, 2, 2, 6, 8, 2,
  9301. 11, 9, 2, 13, 15, 2, 14, 15,
  9302. 2, 18, 1, 2, 19, 27, 2, 20,
  9303. 9, 2, 22, 27, 2, 23, 27, 2,
  9304. 24, 27, 2, 26, 27, 3, 14, 11,
  9305. 9
  9306. };
  9307. static const unsigned char _json_key_offsets[] = {
  9308. 0, 0, 4, 9, 14, 15, 19, 24,
  9309. 29, 34, 38, 42, 45, 48, 50, 54,
  9310. 58, 60, 62, 67, 69, 71, 80, 86,
  9311. 92, 98, 104, 106, 115, 116, 116, 116,
  9312. 121, 126, 131, 132, 133, 134, 135, 135,
  9313. 136, 137, 138, 138, 139, 140, 141, 141,
  9314. 146, 151, 152, 156, 161, 166, 171, 175,
  9315. 175, 178, 178, 178
  9316. };
  9317. static const char _json_trans_keys[] = {
  9318. 32, 123, 9, 13, 32, 34, 125, 9,
  9319. 13, 32, 34, 125, 9, 13, 34, 32,
  9320. 58, 9, 13, 32, 93, 125, 9, 13,
  9321. 32, 44, 125, 9, 13, 32, 44, 125,
  9322. 9, 13, 32, 34, 9, 13, 45, 48,
  9323. 49, 57, 48, 49, 57, 46, 69, 101,
  9324. 48, 57, 69, 101, 48, 57, 43, 45,
  9325. 48, 57, 48, 57, 48, 57, 46, 69,
  9326. 101, 48, 57, 34, 92, 34, 92, 34,
  9327. 47, 92, 98, 102, 110, 114, 116, 117,
  9328. 48, 57, 65, 70, 97, 102, 48, 57,
  9329. 65, 70, 97, 102, 48, 57, 65, 70,
  9330. 97, 102, 48, 57, 65, 70, 97, 102,
  9331. 34, 92, 34, 45, 91, 102, 110, 116,
  9332. 123, 48, 57, 34, 32, 93, 125, 9,
  9333. 13, 32, 44, 93, 9, 13, 32, 93,
  9334. 125, 9, 13, 97, 108, 115, 101, 117,
  9335. 108, 108, 114, 117, 101, 32, 34, 125,
  9336. 9, 13, 32, 34, 125, 9, 13, 34,
  9337. 32, 58, 9, 13, 32, 93, 125, 9,
  9338. 13, 32, 44, 125, 9, 13, 32, 44,
  9339. 125, 9, 13, 32, 34, 9, 13, 32,
  9340. 9, 13, 0
  9341. };
  9342. static const char _json_single_lengths[] = {
  9343. 0, 2, 3, 3, 1, 2, 3, 3,
  9344. 3, 2, 2, 1, 3, 0, 2, 2,
  9345. 0, 0, 3, 2, 2, 9, 0, 0,
  9346. 0, 0, 2, 7, 1, 0, 0, 3,
  9347. 3, 3, 1, 1, 1, 1, 0, 1,
  9348. 1, 1, 0, 1, 1, 1, 0, 3,
  9349. 3, 1, 2, 3, 3, 3, 2, 0,
  9350. 1, 0, 0, 0
  9351. };
  9352. static const char _json_range_lengths[] = {
  9353. 0, 1, 1, 1, 0, 1, 1, 1,
  9354. 1, 1, 1, 1, 0, 1, 1, 1,
  9355. 1, 1, 1, 0, 0, 0, 3, 3,
  9356. 3, 3, 0, 1, 0, 0, 0, 1,
  9357. 1, 1, 0, 0, 0, 0, 0, 0,
  9358. 0, 0, 0, 0, 0, 0, 0, 1,
  9359. 1, 0, 1, 1, 1, 1, 1, 0,
  9360. 1, 0, 0, 0
  9361. };
  9362. static const short _json_index_offsets[] = {
  9363. 0, 0, 4, 9, 14, 16, 20, 25,
  9364. 30, 35, 39, 43, 46, 50, 52, 56,
  9365. 60, 62, 64, 69, 72, 75, 85, 89,
  9366. 93, 97, 101, 104, 113, 115, 116, 117,
  9367. 122, 127, 132, 134, 136, 138, 140, 141,
  9368. 143, 145, 147, 148, 150, 152, 154, 155,
  9369. 160, 165, 167, 171, 176, 181, 186, 190,
  9370. 191, 194, 195, 196
  9371. };
  9372. static const char _json_indicies[] = {
  9373. 0, 2, 0, 1, 3, 4, 5, 3,
  9374. 1, 6, 7, 8, 6, 1, 9, 1,
  9375. 10, 11, 10, 1, 11, 1, 1, 11,
  9376. 12, 13, 14, 15, 13, 1, 16, 17,
  9377. 8, 16, 1, 17, 7, 17, 1, 18,
  9378. 19, 20, 1, 19, 20, 1, 22, 23,
  9379. 23, 21, 24, 1, 23, 23, 24, 21,
  9380. 25, 25, 26, 1, 26, 1, 26, 21,
  9381. 22, 23, 23, 20, 21, 28, 29, 27,
  9382. 31, 32, 30, 33, 33, 33, 33, 33,
  9383. 33, 33, 33, 34, 1, 35, 35, 35,
  9384. 1, 36, 36, 36, 1, 37, 37, 37,
  9385. 1, 38, 38, 38, 1, 40, 41, 39,
  9386. 42, 43, 44, 45, 46, 47, 48, 43,
  9387. 1, 49, 1, 50, 51, 53, 54, 1,
  9388. 53, 52, 55, 56, 54, 55, 1, 56,
  9389. 1, 1, 56, 52, 57, 1, 58, 1,
  9390. 59, 1, 60, 1, 61, 62, 1, 63,
  9391. 1, 64, 1, 65, 66, 1, 67, 1,
  9392. 68, 1, 69, 70, 71, 72, 70, 1,
  9393. 73, 74, 75, 73, 1, 76, 1, 77,
  9394. 78, 77, 1, 78, 1, 1, 78, 79,
  9395. 80, 81, 82, 80, 1, 83, 84, 75,
  9396. 83, 1, 84, 74, 84, 1, 85, 86,
  9397. 86, 1, 1, 1, 1, 0
  9398. };
  9399. static const char _json_trans_targs[] = {
  9400. 1, 0, 2, 3, 4, 56, 3, 4,
  9401. 56, 5, 5, 6, 7, 8, 9, 56,
  9402. 8, 9, 11, 12, 18, 57, 13, 15,
  9403. 14, 16, 17, 20, 58, 21, 20, 58,
  9404. 21, 19, 22, 23, 24, 25, 26, 20,
  9405. 58, 21, 28, 30, 31, 34, 39, 43,
  9406. 47, 29, 59, 59, 32, 31, 29, 32,
  9407. 33, 35, 36, 37, 38, 59, 40, 41,
  9408. 42, 59, 44, 45, 46, 59, 48, 49,
  9409. 55, 48, 49, 55, 50, 50, 51, 52,
  9410. 53, 54, 55, 53, 54, 59, 56
  9411. };
  9412. static const char _json_trans_actions[] = {
  9413. 0, 0, 0, 21, 77, 53, 0, 47,
  9414. 23, 17, 0, 0, 15, 19, 19, 50,
  9415. 0, 0, 0, 0, 0, 1, 0, 0,
  9416. 0, 0, 0, 3, 13, 0, 0, 35,
  9417. 5, 11, 0, 38, 7, 7, 7, 41,
  9418. 44, 9, 62, 56, 25, 0, 0, 0,
  9419. 31, 29, 33, 59, 15, 0, 27, 0,
  9420. 0, 0, 0, 0, 0, 68, 0, 0,
  9421. 0, 71, 0, 0, 0, 65, 21, 77,
  9422. 53, 0, 47, 23, 17, 0, 0, 15,
  9423. 19, 19, 50, 0, 0, 74, 0
  9424. };
  9425. static const int json_start = 1;
  9426. static const int json_en_number_machine = 10;
  9427. static const int json_en_string_machine = 19;
  9428. static const int json_en_value_machine = 27;
  9429. static const int json_en_main = 1;
  9430. #line 1221 "upb/json/parser.rl"
  9431. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  9432. const upb_bufhandle *handle) {
  9433. upb_json_parser *parser = closure;
  9434. /* Variables used by Ragel's generated code. */
  9435. int cs = parser->current_state;
  9436. int *stack = parser->parser_stack;
  9437. int top = parser->parser_top;
  9438. const char *p = buf;
  9439. const char *pe = buf + size;
  9440. parser->handle = handle;
  9441. UPB_UNUSED(hd);
  9442. UPB_UNUSED(handle);
  9443. capture_resume(parser, buf);
  9444. #line 1301 "upb/json/parser.c"
  9445. {
  9446. int _klen;
  9447. unsigned int _trans;
  9448. const char *_acts;
  9449. unsigned int _nacts;
  9450. const char *_keys;
  9451. if ( p == pe )
  9452. goto _test_eof;
  9453. if ( cs == 0 )
  9454. goto _out;
  9455. _resume:
  9456. _keys = _json_trans_keys + _json_key_offsets[cs];
  9457. _trans = _json_index_offsets[cs];
  9458. _klen = _json_single_lengths[cs];
  9459. if ( _klen > 0 ) {
  9460. const char *_lower = _keys;
  9461. const char *_mid;
  9462. const char *_upper = _keys + _klen - 1;
  9463. while (1) {
  9464. if ( _upper < _lower )
  9465. break;
  9466. _mid = _lower + ((_upper-_lower) >> 1);
  9467. if ( (*p) < *_mid )
  9468. _upper = _mid - 1;
  9469. else if ( (*p) > *_mid )
  9470. _lower = _mid + 1;
  9471. else {
  9472. _trans += (unsigned int)(_mid - _keys);
  9473. goto _match;
  9474. }
  9475. }
  9476. _keys += _klen;
  9477. _trans += _klen;
  9478. }
  9479. _klen = _json_range_lengths[cs];
  9480. if ( _klen > 0 ) {
  9481. const char *_lower = _keys;
  9482. const char *_mid;
  9483. const char *_upper = _keys + (_klen<<1) - 2;
  9484. while (1) {
  9485. if ( _upper < _lower )
  9486. break;
  9487. _mid = _lower + (((_upper-_lower) >> 1) & ~1);
  9488. if ( (*p) < _mid[0] )
  9489. _upper = _mid - 2;
  9490. else if ( (*p) > _mid[1] )
  9491. _lower = _mid + 2;
  9492. else {
  9493. _trans += (unsigned int)((_mid - _keys)>>1);
  9494. goto _match;
  9495. }
  9496. }
  9497. _trans += _klen;
  9498. }
  9499. _match:
  9500. _trans = _json_indicies[_trans];
  9501. cs = _json_trans_targs[_trans];
  9502. if ( _json_trans_actions[_trans] == 0 )
  9503. goto _again;
  9504. _acts = _json_actions + _json_trans_actions[_trans];
  9505. _nacts = (unsigned int) *_acts++;
  9506. while ( _nacts-- > 0 )
  9507. {
  9508. switch ( *_acts++ )
  9509. {
  9510. case 0:
  9511. #line 1133 "upb/json/parser.rl"
  9512. { p--; {cs = stack[--top]; goto _again;} }
  9513. break;
  9514. case 1:
  9515. #line 1134 "upb/json/parser.rl"
  9516. { p--; {stack[top++] = cs; cs = 10; goto _again;} }
  9517. break;
  9518. case 2:
  9519. #line 1138 "upb/json/parser.rl"
  9520. { start_text(parser, p); }
  9521. break;
  9522. case 3:
  9523. #line 1139 "upb/json/parser.rl"
  9524. { CHECK_RETURN_TOP(end_text(parser, p)); }
  9525. break;
  9526. case 4:
  9527. #line 1145 "upb/json/parser.rl"
  9528. { start_hex(parser); }
  9529. break;
  9530. case 5:
  9531. #line 1146 "upb/json/parser.rl"
  9532. { hexdigit(parser, p); }
  9533. break;
  9534. case 6:
  9535. #line 1147 "upb/json/parser.rl"
  9536. { CHECK_RETURN_TOP(end_hex(parser)); }
  9537. break;
  9538. case 7:
  9539. #line 1153 "upb/json/parser.rl"
  9540. { CHECK_RETURN_TOP(escape(parser, p)); }
  9541. break;
  9542. case 8:
  9543. #line 1159 "upb/json/parser.rl"
  9544. { p--; {cs = stack[--top]; goto _again;} }
  9545. break;
  9546. case 9:
  9547. #line 1162 "upb/json/parser.rl"
  9548. { {stack[top++] = cs; cs = 19; goto _again;} }
  9549. break;
  9550. case 10:
  9551. #line 1164 "upb/json/parser.rl"
  9552. { p--; {stack[top++] = cs; cs = 27; goto _again;} }
  9553. break;
  9554. case 11:
  9555. #line 1169 "upb/json/parser.rl"
  9556. { start_member(parser); }
  9557. break;
  9558. case 12:
  9559. #line 1170 "upb/json/parser.rl"
  9560. { CHECK_RETURN_TOP(end_membername(parser)); }
  9561. break;
  9562. case 13:
  9563. #line 1173 "upb/json/parser.rl"
  9564. { end_member(parser); }
  9565. break;
  9566. case 14:
  9567. #line 1179 "upb/json/parser.rl"
  9568. { start_object(parser); }
  9569. break;
  9570. case 15:
  9571. #line 1182 "upb/json/parser.rl"
  9572. { end_object(parser); }
  9573. break;
  9574. case 16:
  9575. #line 1188 "upb/json/parser.rl"
  9576. { CHECK_RETURN_TOP(start_array(parser)); }
  9577. break;
  9578. case 17:
  9579. #line 1192 "upb/json/parser.rl"
  9580. { end_array(parser); }
  9581. break;
  9582. case 18:
  9583. #line 1197 "upb/json/parser.rl"
  9584. { start_number(parser, p); }
  9585. break;
  9586. case 19:
  9587. #line 1198 "upb/json/parser.rl"
  9588. { CHECK_RETURN_TOP(end_number(parser, p)); }
  9589. break;
  9590. case 20:
  9591. #line 1200 "upb/json/parser.rl"
  9592. { CHECK_RETURN_TOP(start_stringval(parser)); }
  9593. break;
  9594. case 21:
  9595. #line 1201 "upb/json/parser.rl"
  9596. { CHECK_RETURN_TOP(end_stringval(parser)); }
  9597. break;
  9598. case 22:
  9599. #line 1203 "upb/json/parser.rl"
  9600. { CHECK_RETURN_TOP(parser_putbool(parser, true)); }
  9601. break;
  9602. case 23:
  9603. #line 1205 "upb/json/parser.rl"
  9604. { CHECK_RETURN_TOP(parser_putbool(parser, false)); }
  9605. break;
  9606. case 24:
  9607. #line 1207 "upb/json/parser.rl"
  9608. { /* null value */ }
  9609. break;
  9610. case 25:
  9611. #line 1209 "upb/json/parser.rl"
  9612. { CHECK_RETURN_TOP(start_subobject(parser)); }
  9613. break;
  9614. case 26:
  9615. #line 1210 "upb/json/parser.rl"
  9616. { end_subobject(parser); }
  9617. break;
  9618. case 27:
  9619. #line 1215 "upb/json/parser.rl"
  9620. { p--; {cs = stack[--top]; goto _again;} }
  9621. break;
  9622. #line 1487 "upb/json/parser.c"
  9623. }
  9624. }
  9625. _again:
  9626. if ( cs == 0 )
  9627. goto _out;
  9628. if ( ++p != pe )
  9629. goto _resume;
  9630. _test_eof: {}
  9631. _out: {}
  9632. }
  9633. #line 1242 "upb/json/parser.rl"
  9634. if (p != pe) {
  9635. upb_status_seterrf(&parser->status, "Parse error at %s\n", p);
  9636. upb_env_reporterror(parser->env, &parser->status);
  9637. } else {
  9638. capture_suspend(parser, &p);
  9639. }
  9640. error:
  9641. /* Save parsing state back to parser. */
  9642. parser->current_state = cs;
  9643. parser->parser_top = top;
  9644. return p - buf;
  9645. }
  9646. bool end(void *closure, const void *hd) {
  9647. UPB_UNUSED(closure);
  9648. UPB_UNUSED(hd);
  9649. /* Prevent compile warning on unused static constants. */
  9650. UPB_UNUSED(json_start);
  9651. UPB_UNUSED(json_en_number_machine);
  9652. UPB_UNUSED(json_en_string_machine);
  9653. UPB_UNUSED(json_en_value_machine);
  9654. UPB_UNUSED(json_en_main);
  9655. return true;
  9656. }
  9657. static void json_parser_reset(upb_json_parser *p) {
  9658. int cs;
  9659. int top;
  9660. p->top = p->stack;
  9661. p->top->f = NULL;
  9662. p->top->is_map = false;
  9663. p->top->is_mapentry = false;
  9664. /* Emit Ragel initialization of the parser. */
  9665. #line 1541 "upb/json/parser.c"
  9666. {
  9667. cs = json_start;
  9668. top = 0;
  9669. }
  9670. #line 1282 "upb/json/parser.rl"
  9671. p->current_state = cs;
  9672. p->parser_top = top;
  9673. accumulate_clear(p);
  9674. p->multipart_state = MULTIPART_INACTIVE;
  9675. p->capture = NULL;
  9676. p->accumulated = NULL;
  9677. upb_status_clear(&p->status);
  9678. }
  9679. /* Public API *****************************************************************/
  9680. upb_json_parser *upb_json_parser_create(upb_env *env, upb_sink *output) {
  9681. #ifndef NDEBUG
  9682. const size_t size_before = upb_env_bytesallocated(env);
  9683. #endif
  9684. upb_json_parser *p = upb_env_malloc(env, sizeof(upb_json_parser));
  9685. if (!p) return false;
  9686. p->env = env;
  9687. p->limit = p->stack + UPB_JSON_MAX_DEPTH;
  9688. p->accumulate_buf = NULL;
  9689. p->accumulate_buf_size = 0;
  9690. upb_byteshandler_init(&p->input_handler_);
  9691. upb_byteshandler_setstring(&p->input_handler_, parse, NULL);
  9692. upb_byteshandler_setendstr(&p->input_handler_, end, NULL);
  9693. upb_bytessink_reset(&p->input_, &p->input_handler_, p);
  9694. json_parser_reset(p);
  9695. upb_sink_reset(&p->top->sink, output->handlers, output->closure);
  9696. p->top->m = upb_handlers_msgdef(output->handlers);
  9697. /* If this fails, uncomment and increase the value in parser.h. */
  9698. /* fprintf(stderr, "%zd\n", upb_env_bytesallocated(env) - size_before); */
  9699. assert(upb_env_bytesallocated(env) - size_before <= UPB_JSON_PARSER_SIZE);
  9700. return p;
  9701. }
  9702. upb_bytessink *upb_json_parser_input(upb_json_parser *p) {
  9703. return &p->input_;
  9704. }
  9705. /*
  9706. ** This currently uses snprintf() to format primitives, and could be optimized
  9707. ** further.
  9708. */
  9709. #include <stdlib.h>
  9710. #include <stdio.h>
  9711. #include <string.h>
  9712. #include <stdint.h>
  9713. struct upb_json_printer {
  9714. upb_sink input_;
  9715. /* BytesSink closure. */
  9716. void *subc_;
  9717. upb_bytessink *output_;
  9718. /* We track the depth so that we know when to emit startstr/endstr on the
  9719. * output. */
  9720. int depth_;
  9721. /* Have we emitted the first element? This state is necessary to emit commas
  9722. * without leaving a trailing comma in arrays/maps. We keep this state per
  9723. * frame depth.
  9724. *
  9725. * Why max_depth * 2? UPB_MAX_HANDLER_DEPTH counts depth as nested messages.
  9726. * We count frames (contexts in which we separate elements by commas) as both
  9727. * repeated fields and messages (maps), and the worst case is a
  9728. * message->repeated field->submessage->repeated field->... nesting. */
  9729. bool first_elem_[UPB_MAX_HANDLER_DEPTH * 2];
  9730. };
  9731. /* StringPiece; a pointer plus a length. */
  9732. typedef struct {
  9733. const char *ptr;
  9734. size_t len;
  9735. } strpc;
  9736. strpc *newstrpc(upb_handlers *h, const upb_fielddef *f) {
  9737. strpc *ret = malloc(sizeof(*ret));
  9738. ret->ptr = upb_fielddef_name(f);
  9739. ret->len = strlen(ret->ptr);
  9740. upb_handlers_addcleanup(h, ret, free);
  9741. return ret;
  9742. }
  9743. /* ------------ JSON string printing: values, maps, arrays ------------------ */
  9744. static void print_data(
  9745. upb_json_printer *p, const char *buf, unsigned int len) {
  9746. /* TODO: Will need to change if we support pushback from the sink. */
  9747. size_t n = upb_bytessink_putbuf(p->output_, p->subc_, buf, len, NULL);
  9748. UPB_ASSERT_VAR(n, n == len);
  9749. }
  9750. static void print_comma(upb_json_printer *p) {
  9751. if (!p->first_elem_[p->depth_]) {
  9752. print_data(p, ",", 1);
  9753. }
  9754. p->first_elem_[p->depth_] = false;
  9755. }
  9756. /* Helpers that print properly formatted elements to the JSON output stream. */
  9757. /* Used for escaping control chars in strings. */
  9758. static const char kControlCharLimit = 0x20;
  9759. UPB_INLINE bool is_json_escaped(char c) {
  9760. /* See RFC 4627. */
  9761. unsigned char uc = (unsigned char)c;
  9762. return uc < kControlCharLimit || uc == '"' || uc == '\\';
  9763. }
  9764. UPB_INLINE char* json_nice_escape(char c) {
  9765. switch (c) {
  9766. case '"': return "\\\"";
  9767. case '\\': return "\\\\";
  9768. case '\b': return "\\b";
  9769. case '\f': return "\\f";
  9770. case '\n': return "\\n";
  9771. case '\r': return "\\r";
  9772. case '\t': return "\\t";
  9773. default: return NULL;
  9774. }
  9775. }
  9776. /* Write a properly escaped string chunk. The surrounding quotes are *not*
  9777. * printed; this is so that the caller has the option of emitting the string
  9778. * content in chunks. */
  9779. static void putstring(upb_json_printer *p, const char *buf, unsigned int len) {
  9780. const char* unescaped_run = NULL;
  9781. unsigned int i;
  9782. for (i = 0; i < len; i++) {
  9783. char c = buf[i];
  9784. /* Handle escaping. */
  9785. if (is_json_escaped(c)) {
  9786. /* Use a "nice" escape, like \n, if one exists for this character. */
  9787. const char* escape = json_nice_escape(c);
  9788. /* If we don't have a specific 'nice' escape code, use a \uXXXX-style
  9789. * escape. */
  9790. char escape_buf[8];
  9791. if (!escape) {
  9792. unsigned char byte = (unsigned char)c;
  9793. _upb_snprintf(escape_buf, sizeof(escape_buf), "\\u%04x", (int)byte);
  9794. escape = escape_buf;
  9795. }
  9796. /* N.B. that we assume that the input encoding is equal to the output
  9797. * encoding (both UTF-8 for now), so for chars >= 0x20 and != \, ", we
  9798. * can simply pass the bytes through. */
  9799. /* If there's a current run of unescaped chars, print that run first. */
  9800. if (unescaped_run) {
  9801. print_data(p, unescaped_run, &buf[i] - unescaped_run);
  9802. unescaped_run = NULL;
  9803. }
  9804. /* Then print the escape code. */
  9805. print_data(p, escape, strlen(escape));
  9806. } else {
  9807. /* Add to the current unescaped run of characters. */
  9808. if (unescaped_run == NULL) {
  9809. unescaped_run = &buf[i];
  9810. }
  9811. }
  9812. }
  9813. /* If the string ended in a run of unescaped characters, print that last run. */
  9814. if (unescaped_run) {
  9815. print_data(p, unescaped_run, &buf[len] - unescaped_run);
  9816. }
  9817. }
  9818. #define CHKLENGTH(x) if (!(x)) return -1;
  9819. /* Helpers that format floating point values according to our custom formats.
  9820. * Right now we use %.8g and %.17g for float/double, respectively, to match
  9821. * proto2::util::JsonFormat's defaults. May want to change this later. */
  9822. static size_t fmt_double(double val, char* buf, size_t length) {
  9823. size_t n = _upb_snprintf(buf, length, "%.17g", val);
  9824. CHKLENGTH(n > 0 && n < length);
  9825. return n;
  9826. }
  9827. static size_t fmt_float(float val, char* buf, size_t length) {
  9828. size_t n = _upb_snprintf(buf, length, "%.8g", val);
  9829. CHKLENGTH(n > 0 && n < length);
  9830. return n;
  9831. }
  9832. static size_t fmt_bool(bool val, char* buf, size_t length) {
  9833. size_t n = _upb_snprintf(buf, length, "%s", (val ? "true" : "false"));
  9834. CHKLENGTH(n > 0 && n < length);
  9835. return n;
  9836. }
  9837. static size_t fmt_int64(long val, char* buf, size_t length) {
  9838. size_t n = _upb_snprintf(buf, length, "%ld", val);
  9839. CHKLENGTH(n > 0 && n < length);
  9840. return n;
  9841. }
  9842. static size_t fmt_uint64(unsigned long long val, char* buf, size_t length) {
  9843. size_t n = _upb_snprintf(buf, length, "%llu", val);
  9844. CHKLENGTH(n > 0 && n < length);
  9845. return n;
  9846. }
  9847. /* Print a map key given a field name. Called by scalar field handlers and by
  9848. * startseq for repeated fields. */
  9849. static bool putkey(void *closure, const void *handler_data) {
  9850. upb_json_printer *p = closure;
  9851. const strpc *key = handler_data;
  9852. print_comma(p);
  9853. print_data(p, "\"", 1);
  9854. putstring(p, key->ptr, key->len);
  9855. print_data(p, "\":", 2);
  9856. return true;
  9857. }
  9858. #define CHKFMT(val) if ((val) == (size_t)-1) return false;
  9859. #define CHK(val) if (!(val)) return false;
  9860. #define TYPE_HANDLERS(type, fmt_func) \
  9861. static bool put##type(void *closure, const void *handler_data, type val) { \
  9862. upb_json_printer *p = closure; \
  9863. char data[64]; \
  9864. size_t length = fmt_func(val, data, sizeof(data)); \
  9865. UPB_UNUSED(handler_data); \
  9866. CHKFMT(length); \
  9867. print_data(p, data, length); \
  9868. return true; \
  9869. } \
  9870. static bool scalar_##type(void *closure, const void *handler_data, \
  9871. type val) { \
  9872. CHK(putkey(closure, handler_data)); \
  9873. CHK(put##type(closure, handler_data, val)); \
  9874. return true; \
  9875. } \
  9876. static bool repeated_##type(void *closure, const void *handler_data, \
  9877. type val) { \
  9878. upb_json_printer *p = closure; \
  9879. print_comma(p); \
  9880. CHK(put##type(closure, handler_data, val)); \
  9881. return true; \
  9882. }
  9883. #define TYPE_HANDLERS_MAPKEY(type, fmt_func) \
  9884. static bool putmapkey_##type(void *closure, const void *handler_data, \
  9885. type val) { \
  9886. upb_json_printer *p = closure; \
  9887. print_data(p, "\"", 1); \
  9888. CHK(put##type(closure, handler_data, val)); \
  9889. print_data(p, "\":", 2); \
  9890. return true; \
  9891. }
  9892. TYPE_HANDLERS(double, fmt_double)
  9893. TYPE_HANDLERS(float, fmt_float)
  9894. TYPE_HANDLERS(bool, fmt_bool)
  9895. TYPE_HANDLERS(int32_t, fmt_int64)
  9896. TYPE_HANDLERS(uint32_t, fmt_int64)
  9897. TYPE_HANDLERS(int64_t, fmt_int64)
  9898. TYPE_HANDLERS(uint64_t, fmt_uint64)
  9899. /* double and float are not allowed to be map keys. */
  9900. TYPE_HANDLERS_MAPKEY(bool, fmt_bool)
  9901. TYPE_HANDLERS_MAPKEY(int32_t, fmt_int64)
  9902. TYPE_HANDLERS_MAPKEY(uint32_t, fmt_int64)
  9903. TYPE_HANDLERS_MAPKEY(int64_t, fmt_int64)
  9904. TYPE_HANDLERS_MAPKEY(uint64_t, fmt_uint64)
  9905. #undef TYPE_HANDLERS
  9906. #undef TYPE_HANDLERS_MAPKEY
  9907. typedef struct {
  9908. void *keyname;
  9909. const upb_enumdef *enumdef;
  9910. } EnumHandlerData;
  9911. static bool scalar_enum(void *closure, const void *handler_data,
  9912. int32_t val) {
  9913. const EnumHandlerData *hd = handler_data;
  9914. upb_json_printer *p = closure;
  9915. const char *symbolic_name;
  9916. CHK(putkey(closure, hd->keyname));
  9917. symbolic_name = upb_enumdef_iton(hd->enumdef, val);
  9918. if (symbolic_name) {
  9919. print_data(p, "\"", 1);
  9920. putstring(p, symbolic_name, strlen(symbolic_name));
  9921. print_data(p, "\"", 1);
  9922. } else {
  9923. putint32_t(closure, NULL, val);
  9924. }
  9925. return true;
  9926. }
  9927. static void print_enum_symbolic_name(upb_json_printer *p,
  9928. const upb_enumdef *def,
  9929. int32_t val) {
  9930. const char *symbolic_name = upb_enumdef_iton(def, val);
  9931. if (symbolic_name) {
  9932. print_data(p, "\"", 1);
  9933. putstring(p, symbolic_name, strlen(symbolic_name));
  9934. print_data(p, "\"", 1);
  9935. } else {
  9936. putint32_t(p, NULL, val);
  9937. }
  9938. }
  9939. static bool repeated_enum(void *closure, const void *handler_data,
  9940. int32_t val) {
  9941. const EnumHandlerData *hd = handler_data;
  9942. upb_json_printer *p = closure;
  9943. print_comma(p);
  9944. print_enum_symbolic_name(p, hd->enumdef, val);
  9945. return true;
  9946. }
  9947. static bool mapvalue_enum(void *closure, const void *handler_data,
  9948. int32_t val) {
  9949. const EnumHandlerData *hd = handler_data;
  9950. upb_json_printer *p = closure;
  9951. print_enum_symbolic_name(p, hd->enumdef, val);
  9952. return true;
  9953. }
  9954. static void *scalar_startsubmsg(void *closure, const void *handler_data) {
  9955. return putkey(closure, handler_data) ? closure : UPB_BREAK;
  9956. }
  9957. static void *repeated_startsubmsg(void *closure, const void *handler_data) {
  9958. upb_json_printer *p = closure;
  9959. UPB_UNUSED(handler_data);
  9960. print_comma(p);
  9961. return closure;
  9962. }
  9963. static void start_frame(upb_json_printer *p) {
  9964. p->depth_++;
  9965. p->first_elem_[p->depth_] = true;
  9966. print_data(p, "{", 1);
  9967. }
  9968. static void end_frame(upb_json_printer *p) {
  9969. print_data(p, "}", 1);
  9970. p->depth_--;
  9971. }
  9972. static bool printer_startmsg(void *closure, const void *handler_data) {
  9973. upb_json_printer *p = closure;
  9974. UPB_UNUSED(handler_data);
  9975. if (p->depth_ == 0) {
  9976. upb_bytessink_start(p->output_, 0, &p->subc_);
  9977. }
  9978. start_frame(p);
  9979. return true;
  9980. }
  9981. static bool printer_endmsg(void *closure, const void *handler_data, upb_status *s) {
  9982. upb_json_printer *p = closure;
  9983. UPB_UNUSED(handler_data);
  9984. UPB_UNUSED(s);
  9985. end_frame(p);
  9986. if (p->depth_ == 0) {
  9987. upb_bytessink_end(p->output_);
  9988. }
  9989. return true;
  9990. }
  9991. static void *startseq(void *closure, const void *handler_data) {
  9992. upb_json_printer *p = closure;
  9993. CHK(putkey(closure, handler_data));
  9994. p->depth_++;
  9995. p->first_elem_[p->depth_] = true;
  9996. print_data(p, "[", 1);
  9997. return closure;
  9998. }
  9999. static bool endseq(void *closure, const void *handler_data) {
  10000. upb_json_printer *p = closure;
  10001. UPB_UNUSED(handler_data);
  10002. print_data(p, "]", 1);
  10003. p->depth_--;
  10004. return true;
  10005. }
  10006. static void *startmap(void *closure, const void *handler_data) {
  10007. upb_json_printer *p = closure;
  10008. CHK(putkey(closure, handler_data));
  10009. p->depth_++;
  10010. p->first_elem_[p->depth_] = true;
  10011. print_data(p, "{", 1);
  10012. return closure;
  10013. }
  10014. static bool endmap(void *closure, const void *handler_data) {
  10015. upb_json_printer *p = closure;
  10016. UPB_UNUSED(handler_data);
  10017. print_data(p, "}", 1);
  10018. p->depth_--;
  10019. return true;
  10020. }
  10021. static size_t putstr(void *closure, const void *handler_data, const char *str,
  10022. size_t len, const upb_bufhandle *handle) {
  10023. upb_json_printer *p = closure;
  10024. UPB_UNUSED(handler_data);
  10025. UPB_UNUSED(handle);
  10026. putstring(p, str, len);
  10027. return len;
  10028. }
  10029. /* This has to Base64 encode the bytes, because JSON has no "bytes" type. */
  10030. static size_t putbytes(void *closure, const void *handler_data, const char *str,
  10031. size_t len, const upb_bufhandle *handle) {
  10032. upb_json_printer *p = closure;
  10033. /* This is the regular base64, not the "web-safe" version. */
  10034. static const char base64[] =
  10035. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  10036. /* Base64-encode. */
  10037. char data[16000];
  10038. const char *limit = data + sizeof(data);
  10039. const unsigned char *from = (const unsigned char*)str;
  10040. char *to = data;
  10041. size_t remaining = len;
  10042. size_t bytes;
  10043. UPB_UNUSED(handler_data);
  10044. UPB_UNUSED(handle);
  10045. while (remaining > 2) {
  10046. /* TODO(haberman): handle encoded lengths > sizeof(data) */
  10047. UPB_ASSERT_VAR(limit, (limit - to) >= 4);
  10048. to[0] = base64[from[0] >> 2];
  10049. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  10050. to[2] = base64[((from[1] & 0xf) << 2) | (from[2] >> 6)];
  10051. to[3] = base64[from[2] & 0x3f];
  10052. remaining -= 3;
  10053. to += 4;
  10054. from += 3;
  10055. }
  10056. switch (remaining) {
  10057. case 2:
  10058. to[0] = base64[from[0] >> 2];
  10059. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  10060. to[2] = base64[(from[1] & 0xf) << 2];
  10061. to[3] = '=';
  10062. to += 4;
  10063. from += 2;
  10064. break;
  10065. case 1:
  10066. to[0] = base64[from[0] >> 2];
  10067. to[1] = base64[((from[0] & 0x3) << 4)];
  10068. to[2] = '=';
  10069. to[3] = '=';
  10070. to += 4;
  10071. from += 1;
  10072. break;
  10073. }
  10074. bytes = to - data;
  10075. print_data(p, "\"", 1);
  10076. putstring(p, data, bytes);
  10077. print_data(p, "\"", 1);
  10078. return len;
  10079. }
  10080. static void *scalar_startstr(void *closure, const void *handler_data,
  10081. size_t size_hint) {
  10082. upb_json_printer *p = closure;
  10083. UPB_UNUSED(handler_data);
  10084. UPB_UNUSED(size_hint);
  10085. CHK(putkey(closure, handler_data));
  10086. print_data(p, "\"", 1);
  10087. return p;
  10088. }
  10089. static size_t scalar_str(void *closure, const void *handler_data,
  10090. const char *str, size_t len,
  10091. const upb_bufhandle *handle) {
  10092. CHK(putstr(closure, handler_data, str, len, handle));
  10093. return len;
  10094. }
  10095. static bool scalar_endstr(void *closure, const void *handler_data) {
  10096. upb_json_printer *p = closure;
  10097. UPB_UNUSED(handler_data);
  10098. print_data(p, "\"", 1);
  10099. return true;
  10100. }
  10101. static void *repeated_startstr(void *closure, const void *handler_data,
  10102. size_t size_hint) {
  10103. upb_json_printer *p = closure;
  10104. UPB_UNUSED(handler_data);
  10105. UPB_UNUSED(size_hint);
  10106. print_comma(p);
  10107. print_data(p, "\"", 1);
  10108. return p;
  10109. }
  10110. static size_t repeated_str(void *closure, const void *handler_data,
  10111. const char *str, size_t len,
  10112. const upb_bufhandle *handle) {
  10113. CHK(putstr(closure, handler_data, str, len, handle));
  10114. return len;
  10115. }
  10116. static bool repeated_endstr(void *closure, const void *handler_data) {
  10117. upb_json_printer *p = closure;
  10118. UPB_UNUSED(handler_data);
  10119. print_data(p, "\"", 1);
  10120. return true;
  10121. }
  10122. static void *mapkeyval_startstr(void *closure, const void *handler_data,
  10123. size_t size_hint) {
  10124. upb_json_printer *p = closure;
  10125. UPB_UNUSED(handler_data);
  10126. UPB_UNUSED(size_hint);
  10127. print_data(p, "\"", 1);
  10128. return p;
  10129. }
  10130. static size_t mapkey_str(void *closure, const void *handler_data,
  10131. const char *str, size_t len,
  10132. const upb_bufhandle *handle) {
  10133. CHK(putstr(closure, handler_data, str, len, handle));
  10134. return len;
  10135. }
  10136. static bool mapkey_endstr(void *closure, const void *handler_data) {
  10137. upb_json_printer *p = closure;
  10138. UPB_UNUSED(handler_data);
  10139. print_data(p, "\":", 2);
  10140. return true;
  10141. }
  10142. static bool mapvalue_endstr(void *closure, const void *handler_data) {
  10143. upb_json_printer *p = closure;
  10144. UPB_UNUSED(handler_data);
  10145. print_data(p, "\"", 1);
  10146. return true;
  10147. }
  10148. static size_t scalar_bytes(void *closure, const void *handler_data,
  10149. const char *str, size_t len,
  10150. const upb_bufhandle *handle) {
  10151. CHK(putkey(closure, handler_data));
  10152. CHK(putbytes(closure, handler_data, str, len, handle));
  10153. return len;
  10154. }
  10155. static size_t repeated_bytes(void *closure, const void *handler_data,
  10156. const char *str, size_t len,
  10157. const upb_bufhandle *handle) {
  10158. upb_json_printer *p = closure;
  10159. print_comma(p);
  10160. CHK(putbytes(closure, handler_data, str, len, handle));
  10161. return len;
  10162. }
  10163. static size_t mapkey_bytes(void *closure, const void *handler_data,
  10164. const char *str, size_t len,
  10165. const upb_bufhandle *handle) {
  10166. upb_json_printer *p = closure;
  10167. CHK(putbytes(closure, handler_data, str, len, handle));
  10168. print_data(p, ":", 1);
  10169. return len;
  10170. }
  10171. static void set_enum_hd(upb_handlers *h,
  10172. const upb_fielddef *f,
  10173. upb_handlerattr *attr) {
  10174. EnumHandlerData *hd = malloc(sizeof(EnumHandlerData));
  10175. hd->enumdef = (const upb_enumdef *)upb_fielddef_subdef(f);
  10176. hd->keyname = newstrpc(h, f);
  10177. upb_handlers_addcleanup(h, hd, free);
  10178. upb_handlerattr_sethandlerdata(attr, hd);
  10179. }
  10180. /* Set up handlers for a mapentry submessage (i.e., an individual key/value pair
  10181. * in a map).
  10182. *
  10183. * TODO: Handle missing key, missing value, out-of-order key/value, or repeated
  10184. * key or value cases properly. The right way to do this is to allocate a
  10185. * temporary structure at the start of a mapentry submessage, store key and
  10186. * value data in it as key and value handlers are called, and then print the
  10187. * key/value pair once at the end of the submessage. If we don't do this, we
  10188. * should at least detect the case and throw an error. However, so far all of
  10189. * our sources that emit mapentry messages do so canonically (with one key
  10190. * field, and then one value field), so this is not a pressing concern at the
  10191. * moment. */
  10192. void printer_sethandlers_mapentry(const void *closure, upb_handlers *h) {
  10193. const upb_msgdef *md = upb_handlers_msgdef(h);
  10194. /* A mapentry message is printed simply as '"key": value'. Rather than
  10195. * special-case key and value for every type below, we just handle both
  10196. * fields explicitly here. */
  10197. const upb_fielddef* key_field = upb_msgdef_itof(md, UPB_MAPENTRY_KEY);
  10198. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_MAPENTRY_VALUE);
  10199. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  10200. UPB_UNUSED(closure);
  10201. switch (upb_fielddef_type(key_field)) {
  10202. case UPB_TYPE_INT32:
  10203. upb_handlers_setint32(h, key_field, putmapkey_int32_t, &empty_attr);
  10204. break;
  10205. case UPB_TYPE_INT64:
  10206. upb_handlers_setint64(h, key_field, putmapkey_int64_t, &empty_attr);
  10207. break;
  10208. case UPB_TYPE_UINT32:
  10209. upb_handlers_setuint32(h, key_field, putmapkey_uint32_t, &empty_attr);
  10210. break;
  10211. case UPB_TYPE_UINT64:
  10212. upb_handlers_setuint64(h, key_field, putmapkey_uint64_t, &empty_attr);
  10213. break;
  10214. case UPB_TYPE_BOOL:
  10215. upb_handlers_setbool(h, key_field, putmapkey_bool, &empty_attr);
  10216. break;
  10217. case UPB_TYPE_STRING:
  10218. upb_handlers_setstartstr(h, key_field, mapkeyval_startstr, &empty_attr);
  10219. upb_handlers_setstring(h, key_field, mapkey_str, &empty_attr);
  10220. upb_handlers_setendstr(h, key_field, mapkey_endstr, &empty_attr);
  10221. break;
  10222. case UPB_TYPE_BYTES:
  10223. upb_handlers_setstring(h, key_field, mapkey_bytes, &empty_attr);
  10224. break;
  10225. default:
  10226. assert(false);
  10227. break;
  10228. }
  10229. switch (upb_fielddef_type(value_field)) {
  10230. case UPB_TYPE_INT32:
  10231. upb_handlers_setint32(h, value_field, putint32_t, &empty_attr);
  10232. break;
  10233. case UPB_TYPE_INT64:
  10234. upb_handlers_setint64(h, value_field, putint64_t, &empty_attr);
  10235. break;
  10236. case UPB_TYPE_UINT32:
  10237. upb_handlers_setuint32(h, value_field, putuint32_t, &empty_attr);
  10238. break;
  10239. case UPB_TYPE_UINT64:
  10240. upb_handlers_setuint64(h, value_field, putuint64_t, &empty_attr);
  10241. break;
  10242. case UPB_TYPE_BOOL:
  10243. upb_handlers_setbool(h, value_field, putbool, &empty_attr);
  10244. break;
  10245. case UPB_TYPE_FLOAT:
  10246. upb_handlers_setfloat(h, value_field, putfloat, &empty_attr);
  10247. break;
  10248. case UPB_TYPE_DOUBLE:
  10249. upb_handlers_setdouble(h, value_field, putdouble, &empty_attr);
  10250. break;
  10251. case UPB_TYPE_STRING:
  10252. upb_handlers_setstartstr(h, value_field, mapkeyval_startstr, &empty_attr);
  10253. upb_handlers_setstring(h, value_field, putstr, &empty_attr);
  10254. upb_handlers_setendstr(h, value_field, mapvalue_endstr, &empty_attr);
  10255. break;
  10256. case UPB_TYPE_BYTES:
  10257. upb_handlers_setstring(h, value_field, putbytes, &empty_attr);
  10258. break;
  10259. case UPB_TYPE_ENUM: {
  10260. upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
  10261. set_enum_hd(h, value_field, &enum_attr);
  10262. upb_handlers_setint32(h, value_field, mapvalue_enum, &enum_attr);
  10263. upb_handlerattr_uninit(&enum_attr);
  10264. break;
  10265. }
  10266. case UPB_TYPE_MESSAGE:
  10267. /* No handler necessary -- the submsg handlers will print the message
  10268. * as appropriate. */
  10269. break;
  10270. }
  10271. upb_handlerattr_uninit(&empty_attr);
  10272. }
  10273. void printer_sethandlers(const void *closure, upb_handlers *h) {
  10274. const upb_msgdef *md = upb_handlers_msgdef(h);
  10275. bool is_mapentry = upb_msgdef_mapentry(md);
  10276. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  10277. upb_msg_field_iter i;
  10278. UPB_UNUSED(closure);
  10279. if (is_mapentry) {
  10280. /* mapentry messages are sufficiently different that we handle them
  10281. * separately. */
  10282. printer_sethandlers_mapentry(closure, h);
  10283. return;
  10284. }
  10285. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  10286. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  10287. #define TYPE(type, name, ctype) \
  10288. case type: \
  10289. if (upb_fielddef_isseq(f)) { \
  10290. upb_handlers_set##name(h, f, repeated_##ctype, &empty_attr); \
  10291. } else { \
  10292. upb_handlers_set##name(h, f, scalar_##ctype, &name_attr); \
  10293. } \
  10294. break;
  10295. upb_msg_field_begin(&i, md);
  10296. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  10297. const upb_fielddef *f = upb_msg_iter_field(&i);
  10298. upb_handlerattr name_attr = UPB_HANDLERATTR_INITIALIZER;
  10299. upb_handlerattr_sethandlerdata(&name_attr, newstrpc(h, f));
  10300. if (upb_fielddef_ismap(f)) {
  10301. upb_handlers_setstartseq(h, f, startmap, &name_attr);
  10302. upb_handlers_setendseq(h, f, endmap, &name_attr);
  10303. } else if (upb_fielddef_isseq(f)) {
  10304. upb_handlers_setstartseq(h, f, startseq, &name_attr);
  10305. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  10306. }
  10307. switch (upb_fielddef_type(f)) {
  10308. TYPE(UPB_TYPE_FLOAT, float, float);
  10309. TYPE(UPB_TYPE_DOUBLE, double, double);
  10310. TYPE(UPB_TYPE_BOOL, bool, bool);
  10311. TYPE(UPB_TYPE_INT32, int32, int32_t);
  10312. TYPE(UPB_TYPE_UINT32, uint32, uint32_t);
  10313. TYPE(UPB_TYPE_INT64, int64, int64_t);
  10314. TYPE(UPB_TYPE_UINT64, uint64, uint64_t);
  10315. case UPB_TYPE_ENUM: {
  10316. /* For now, we always emit symbolic names for enums. We may want an
  10317. * option later to control this behavior, but we will wait for a real
  10318. * need first. */
  10319. upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
  10320. set_enum_hd(h, f, &enum_attr);
  10321. if (upb_fielddef_isseq(f)) {
  10322. upb_handlers_setint32(h, f, repeated_enum, &enum_attr);
  10323. } else {
  10324. upb_handlers_setint32(h, f, scalar_enum, &enum_attr);
  10325. }
  10326. upb_handlerattr_uninit(&enum_attr);
  10327. break;
  10328. }
  10329. case UPB_TYPE_STRING:
  10330. if (upb_fielddef_isseq(f)) {
  10331. upb_handlers_setstartstr(h, f, repeated_startstr, &empty_attr);
  10332. upb_handlers_setstring(h, f, repeated_str, &empty_attr);
  10333. upb_handlers_setendstr(h, f, repeated_endstr, &empty_attr);
  10334. } else {
  10335. upb_handlers_setstartstr(h, f, scalar_startstr, &name_attr);
  10336. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  10337. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  10338. }
  10339. break;
  10340. case UPB_TYPE_BYTES:
  10341. /* XXX: this doesn't support strings that span buffers yet. The base64
  10342. * encoder will need to be made resumable for this to work properly. */
  10343. if (upb_fielddef_isseq(f)) {
  10344. upb_handlers_setstring(h, f, repeated_bytes, &empty_attr);
  10345. } else {
  10346. upb_handlers_setstring(h, f, scalar_bytes, &name_attr);
  10347. }
  10348. break;
  10349. case UPB_TYPE_MESSAGE:
  10350. if (upb_fielddef_isseq(f)) {
  10351. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &name_attr);
  10352. } else {
  10353. upb_handlers_setstartsubmsg(h, f, scalar_startsubmsg, &name_attr);
  10354. }
  10355. break;
  10356. }
  10357. upb_handlerattr_uninit(&name_attr);
  10358. }
  10359. upb_handlerattr_uninit(&empty_attr);
  10360. #undef TYPE
  10361. }
  10362. static void json_printer_reset(upb_json_printer *p) {
  10363. p->depth_ = 0;
  10364. }
  10365. /* Public API *****************************************************************/
  10366. upb_json_printer *upb_json_printer_create(upb_env *e, const upb_handlers *h,
  10367. upb_bytessink *output) {
  10368. #ifndef NDEBUG
  10369. size_t size_before = upb_env_bytesallocated(e);
  10370. #endif
  10371. upb_json_printer *p = upb_env_malloc(e, sizeof(upb_json_printer));
  10372. if (!p) return NULL;
  10373. p->output_ = output;
  10374. json_printer_reset(p);
  10375. upb_sink_reset(&p->input_, h, p);
  10376. /* If this fails, increase the value in printer.h. */
  10377. assert(upb_env_bytesallocated(e) - size_before <= UPB_JSON_PRINTER_SIZE);
  10378. return p;
  10379. }
  10380. upb_sink *upb_json_printer_input(upb_json_printer *p) {
  10381. return &p->input_;
  10382. }
  10383. const upb_handlers *upb_json_printer_newhandlers(const upb_msgdef *md,
  10384. const void *owner) {
  10385. return upb_handlers_newfrozen(md, owner, printer_sethandlers, NULL);
  10386. }