upb.c 456 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950
  1. // Amalgamated source file
  2. #include "upb.h"
  3. #include <ctype.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. typedef struct {
  7. size_t len;
  8. char str[1]; /* Null-terminated string data follows. */
  9. } str_t;
  10. static str_t *newstr(const char *data, size_t len) {
  11. str_t *ret = upb_gmalloc(sizeof(*ret) + len);
  12. if (!ret) return NULL;
  13. ret->len = len;
  14. memcpy(ret->str, data, len);
  15. ret->str[len] = '\0';
  16. return ret;
  17. }
  18. static void freestr(str_t *s) { upb_gfree(s); }
  19. /* isalpha() etc. from <ctype.h> are locale-dependent, which we don't want. */
  20. static bool upb_isbetween(char c, char low, char high) {
  21. return c >= low && c <= high;
  22. }
  23. static bool upb_isletter(char c) {
  24. return upb_isbetween(c, 'A', 'Z') || upb_isbetween(c, 'a', 'z') || c == '_';
  25. }
  26. static bool upb_isalphanum(char c) {
  27. return upb_isletter(c) || upb_isbetween(c, '0', '9');
  28. }
  29. static bool upb_isident(const char *str, size_t len, bool full, upb_status *s) {
  30. bool start = true;
  31. size_t i;
  32. for (i = 0; i < len; i++) {
  33. char c = str[i];
  34. if (c == '.') {
  35. if (start || !full) {
  36. upb_status_seterrf(s, "invalid name: unexpected '.' (%s)", str);
  37. return false;
  38. }
  39. start = true;
  40. } else if (start) {
  41. if (!upb_isletter(c)) {
  42. upb_status_seterrf(
  43. s, "invalid name: path components must start with a letter (%s)",
  44. str);
  45. return false;
  46. }
  47. start = false;
  48. } else {
  49. if (!upb_isalphanum(c)) {
  50. upb_status_seterrf(s, "invalid name: non-alphanumeric character (%s)",
  51. str);
  52. return false;
  53. }
  54. }
  55. }
  56. return !start;
  57. }
  58. static bool upb_isoneof(const upb_refcounted *def) {
  59. return def->vtbl == &upb_oneofdef_vtbl;
  60. }
  61. static bool upb_isfield(const upb_refcounted *def) {
  62. return def->vtbl == &upb_fielddef_vtbl;
  63. }
  64. static const upb_oneofdef *upb_trygetoneof(const upb_refcounted *def) {
  65. return upb_isoneof(def) ? (const upb_oneofdef*)def : NULL;
  66. }
  67. static const upb_fielddef *upb_trygetfield(const upb_refcounted *def) {
  68. return upb_isfield(def) ? (const upb_fielddef*)def : NULL;
  69. }
  70. /* upb_def ********************************************************************/
  71. upb_deftype_t upb_def_type(const upb_def *d) { return d->type; }
  72. const char *upb_def_fullname(const upb_def *d) { return d->fullname; }
  73. const char *upb_def_name(const upb_def *d) {
  74. const char *p;
  75. if (d->fullname == NULL) {
  76. return NULL;
  77. } else if ((p = strrchr(d->fullname, '.')) == NULL) {
  78. /* No '.' in the name, return the full string. */
  79. return d->fullname;
  80. } else {
  81. /* Return one past the last '.'. */
  82. return p + 1;
  83. }
  84. }
  85. bool upb_def_setfullname(upb_def *def, const char *fullname, upb_status *s) {
  86. UPB_ASSERT(!upb_def_isfrozen(def));
  87. if (!upb_isident(fullname, strlen(fullname), true, s)) {
  88. return false;
  89. }
  90. fullname = upb_gstrdup(fullname);
  91. if (!fullname) {
  92. upb_upberr_setoom(s);
  93. return false;
  94. }
  95. upb_gfree((void*)def->fullname);
  96. def->fullname = fullname;
  97. return true;
  98. }
  99. const upb_filedef *upb_def_file(const upb_def *d) { return d->file; }
  100. static bool upb_def_init(upb_def *def, upb_deftype_t type,
  101. const struct upb_refcounted_vtbl *vtbl,
  102. const void *owner) {
  103. if (!upb_refcounted_init(upb_def_upcast_mutable(def), vtbl, owner)) return false;
  104. def->type = type;
  105. def->fullname = NULL;
  106. def->came_from_user = false;
  107. def->file = NULL;
  108. return true;
  109. }
  110. static void upb_def_uninit(upb_def *def) {
  111. upb_gfree((void*)def->fullname);
  112. }
  113. static const char *msgdef_name(const upb_msgdef *m) {
  114. const char *name = upb_def_fullname(upb_msgdef_upcast(m));
  115. return name ? name : "(anonymous)";
  116. }
  117. static bool upb_validate_field(upb_fielddef *f, upb_status *s) {
  118. if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  119. upb_status_seterrmsg(s, "fielddef must have name and number set");
  120. return false;
  121. }
  122. if (!f->type_is_set_) {
  123. upb_status_seterrmsg(s, "fielddef type was not initialized");
  124. return false;
  125. }
  126. if (upb_fielddef_lazy(f) &&
  127. upb_fielddef_descriptortype(f) != UPB_DESCRIPTOR_TYPE_MESSAGE) {
  128. upb_status_seterrmsg(s,
  129. "only length-delimited submessage fields may be lazy");
  130. return false;
  131. }
  132. if (upb_fielddef_hassubdef(f)) {
  133. const upb_def *subdef;
  134. if (f->subdef_is_symbolic) {
  135. upb_status_seterrf(s, "field '%s.%s' has not been resolved",
  136. msgdef_name(f->msg.def), upb_fielddef_name(f));
  137. return false;
  138. }
  139. subdef = upb_fielddef_subdef(f);
  140. if (subdef == NULL) {
  141. upb_status_seterrf(s, "field %s.%s is missing required subdef",
  142. msgdef_name(f->msg.def), upb_fielddef_name(f));
  143. return false;
  144. }
  145. if (!upb_def_isfrozen(subdef) && !subdef->came_from_user) {
  146. upb_status_seterrf(s,
  147. "subdef of field %s.%s is not frozen or being frozen",
  148. msgdef_name(f->msg.def), upb_fielddef_name(f));
  149. return false;
  150. }
  151. }
  152. if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  153. bool has_default_name = upb_fielddef_enumhasdefaultstr(f);
  154. bool has_default_number = upb_fielddef_enumhasdefaultint32(f);
  155. /* Previously verified by upb_validate_enumdef(). */
  156. UPB_ASSERT(upb_enumdef_numvals(upb_fielddef_enumsubdef(f)) > 0);
  157. /* We've already validated that we have an associated enumdef and that it
  158. * has at least one member, so at least one of these should be true.
  159. * Because if the user didn't set anything, we'll pick up the enum's
  160. * default, but if the user *did* set something we should at least pick up
  161. * the one they set (int32 or string). */
  162. UPB_ASSERT(has_default_name || has_default_number);
  163. if (!has_default_name) {
  164. upb_status_seterrf(s,
  165. "enum default for field %s.%s (%d) is not in the enum",
  166. msgdef_name(f->msg.def), upb_fielddef_name(f),
  167. upb_fielddef_defaultint32(f));
  168. return false;
  169. }
  170. if (!has_default_number) {
  171. upb_status_seterrf(s,
  172. "enum default for field %s.%s (%s) is not in the enum",
  173. msgdef_name(f->msg.def), upb_fielddef_name(f),
  174. upb_fielddef_defaultstr(f, NULL));
  175. return false;
  176. }
  177. /* Lift the effective numeric default into the field's default slot, in case
  178. * we were only getting it "by reference" from the enumdef. */
  179. upb_fielddef_setdefaultint32(f, upb_fielddef_defaultint32(f));
  180. }
  181. /* Ensure that MapEntry submessages only appear as repeated fields, not
  182. * optional/required (singular) fields. */
  183. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  184. upb_fielddef_msgsubdef(f) != NULL) {
  185. const upb_msgdef *subdef = upb_fielddef_msgsubdef(f);
  186. if (upb_msgdef_mapentry(subdef) && !upb_fielddef_isseq(f)) {
  187. upb_status_seterrf(s,
  188. "Field %s refers to mapentry message but is not "
  189. "a repeated field",
  190. upb_fielddef_name(f) ? upb_fielddef_name(f) :
  191. "(unnamed)");
  192. return false;
  193. }
  194. }
  195. return true;
  196. }
  197. static bool upb_validate_enumdef(const upb_enumdef *e, upb_status *s) {
  198. if (upb_enumdef_numvals(e) == 0) {
  199. upb_status_seterrf(s, "enum %s has no members (must have at least one)",
  200. upb_enumdef_fullname(e));
  201. return false;
  202. }
  203. return true;
  204. }
  205. /* All submessage fields are lower than all other fields.
  206. * Secondly, fields are increasing in order. */
  207. uint32_t field_rank(const upb_fielddef *f) {
  208. uint32_t ret = upb_fielddef_number(f);
  209. const uint32_t high_bit = 1 << 30;
  210. UPB_ASSERT(ret < high_bit);
  211. if (!upb_fielddef_issubmsg(f))
  212. ret |= high_bit;
  213. return ret;
  214. }
  215. int cmp_fields(const void *p1, const void *p2) {
  216. const upb_fielddef *f1 = *(upb_fielddef*const*)p1;
  217. const upb_fielddef *f2 = *(upb_fielddef*const*)p2;
  218. return field_rank(f1) - field_rank(f2);
  219. }
  220. static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
  221. /* Sort fields. upb internally relies on UPB_TYPE_MESSAGE fields having the
  222. * lowest indexes, but we do not publicly guarantee this. */
  223. upb_msg_field_iter j;
  224. upb_msg_oneof_iter k;
  225. int i;
  226. uint32_t selector;
  227. int n = upb_msgdef_numfields(m);
  228. upb_fielddef **fields;
  229. if (n == 0) {
  230. m->selector_count = UPB_STATIC_SELECTOR_COUNT;
  231. m->submsg_field_count = 0;
  232. return true;
  233. }
  234. fields = upb_gmalloc(n * sizeof(*fields));
  235. if (!fields) {
  236. upb_upberr_setoom(s);
  237. return false;
  238. }
  239. m->submsg_field_count = 0;
  240. for(i = 0, upb_msg_field_begin(&j, m);
  241. !upb_msg_field_done(&j);
  242. upb_msg_field_next(&j), i++) {
  243. upb_fielddef *f = upb_msg_iter_field(&j);
  244. UPB_ASSERT(f->msg.def == m);
  245. if (!upb_validate_field(f, s)) {
  246. upb_gfree(fields);
  247. return false;
  248. }
  249. if (upb_fielddef_issubmsg(f)) {
  250. m->submsg_field_count++;
  251. }
  252. fields[i] = f;
  253. }
  254. qsort(fields, n, sizeof(*fields), cmp_fields);
  255. selector = UPB_STATIC_SELECTOR_COUNT + m->submsg_field_count;
  256. for (i = 0; i < n; i++) {
  257. upb_fielddef *f = fields[i];
  258. f->index_ = i;
  259. f->selector_base = selector + upb_handlers_selectorbaseoffset(f);
  260. selector += upb_handlers_selectorcount(f);
  261. }
  262. m->selector_count = selector;
  263. #ifndef NDEBUG
  264. {
  265. /* Verify that all selectors for the message are distinct. */
  266. #define TRY(type) \
  267. if (upb_handlers_getselector(f, type, &sel)) upb_inttable_insert(&t, sel, v);
  268. upb_inttable t;
  269. upb_value v;
  270. upb_selector_t sel;
  271. upb_inttable_init(&t, UPB_CTYPE_BOOL);
  272. v = upb_value_bool(true);
  273. upb_inttable_insert(&t, UPB_STARTMSG_SELECTOR, v);
  274. upb_inttable_insert(&t, UPB_ENDMSG_SELECTOR, v);
  275. for(upb_msg_field_begin(&j, m);
  276. !upb_msg_field_done(&j);
  277. upb_msg_field_next(&j)) {
  278. upb_fielddef *f = upb_msg_iter_field(&j);
  279. /* These calls will assert-fail in upb_table if the value already
  280. * exists. */
  281. TRY(UPB_HANDLER_INT32);
  282. TRY(UPB_HANDLER_INT64)
  283. TRY(UPB_HANDLER_UINT32)
  284. TRY(UPB_HANDLER_UINT64)
  285. TRY(UPB_HANDLER_FLOAT)
  286. TRY(UPB_HANDLER_DOUBLE)
  287. TRY(UPB_HANDLER_BOOL)
  288. TRY(UPB_HANDLER_STARTSTR)
  289. TRY(UPB_HANDLER_STRING)
  290. TRY(UPB_HANDLER_ENDSTR)
  291. TRY(UPB_HANDLER_STARTSUBMSG)
  292. TRY(UPB_HANDLER_ENDSUBMSG)
  293. TRY(UPB_HANDLER_STARTSEQ)
  294. TRY(UPB_HANDLER_ENDSEQ)
  295. }
  296. upb_inttable_uninit(&t);
  297. }
  298. #undef TRY
  299. #endif
  300. for(upb_msg_oneof_begin(&k, m), i = 0;
  301. !upb_msg_oneof_done(&k);
  302. upb_msg_oneof_next(&k), i++) {
  303. upb_oneofdef *o = upb_msg_iter_oneof(&k);
  304. o->index = i;
  305. }
  306. upb_gfree(fields);
  307. return true;
  308. }
  309. bool _upb_def_validate(upb_def *const*defs, size_t n, upb_status *s) {
  310. size_t i;
  311. /* First perform validation, in two passes so we can check that we have a
  312. * transitive closure without needing to search. */
  313. for (i = 0; i < n; i++) {
  314. upb_def *def = defs[i];
  315. if (upb_def_isfrozen(def)) {
  316. /* Could relax this requirement if it's annoying. */
  317. upb_status_seterrmsg(s, "def is already frozen");
  318. goto err;
  319. } else if (def->type == UPB_DEF_FIELD) {
  320. upb_status_seterrmsg(s, "standalone fielddefs can not be frozen");
  321. goto err;
  322. } else if (def->type == UPB_DEF_ENUM) {
  323. if (!upb_validate_enumdef(upb_dyncast_enumdef(def), s)) {
  324. goto err;
  325. }
  326. } else {
  327. /* Set now to detect transitive closure in the second pass. */
  328. def->came_from_user = true;
  329. }
  330. }
  331. /* Second pass of validation. Also assign selector bases and indexes, and
  332. * compact tables. */
  333. for (i = 0; i < n; i++) {
  334. upb_def *def = defs[i];
  335. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  336. upb_enumdef *e = upb_dyncast_enumdef_mutable(def);
  337. if (m) {
  338. upb_inttable_compact(&m->itof);
  339. if (!assign_msg_indices(m, s)) {
  340. goto err;
  341. }
  342. } else if (e) {
  343. upb_inttable_compact(&e->iton);
  344. }
  345. }
  346. return true;
  347. err:
  348. for (i = 0; i < n; i++) {
  349. upb_def *def = defs[i];
  350. def->came_from_user = false;
  351. }
  352. UPB_ASSERT(!(s && upb_ok(s)));
  353. return false;
  354. }
  355. bool upb_def_freeze(upb_def *const* defs, size_t n, upb_status *s) {
  356. /* Def graph contains FieldDefs between each MessageDef, so double the
  357. * limit. */
  358. const size_t maxdepth = UPB_MAX_MESSAGE_DEPTH * 2;
  359. if (!_upb_def_validate(defs, n, s)) {
  360. return false;
  361. }
  362. /* Validation all passed; freeze the objects. */
  363. return upb_refcounted_freeze((upb_refcounted *const*)defs, n, s, maxdepth);
  364. }
  365. /* upb_enumdef ****************************************************************/
  366. static void visitenum(const upb_refcounted *r, upb_refcounted_visit *visit,
  367. void *closure) {
  368. const upb_enumdef *e = (const upb_enumdef*)r;
  369. const upb_def *def = upb_enumdef_upcast(e);
  370. if (upb_def_file(def)) {
  371. visit(r, upb_filedef_upcast(upb_def_file(def)), closure);
  372. }
  373. }
  374. static void freeenum(upb_refcounted *r) {
  375. upb_enumdef *e = (upb_enumdef*)r;
  376. upb_inttable_iter i;
  377. upb_inttable_begin(&i, &e->iton);
  378. for( ; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  379. /* To clean up the upb_gstrdup() from upb_enumdef_addval(). */
  380. upb_gfree(upb_value_getcstr(upb_inttable_iter_value(&i)));
  381. }
  382. upb_strtable_uninit(&e->ntoi);
  383. upb_inttable_uninit(&e->iton);
  384. upb_def_uninit(upb_enumdef_upcast_mutable(e));
  385. upb_gfree(e);
  386. }
  387. const struct upb_refcounted_vtbl upb_enumdef_vtbl = {&visitenum, &freeenum};
  388. upb_enumdef *upb_enumdef_new(const void *owner) {
  389. upb_enumdef *e = upb_gmalloc(sizeof(*e));
  390. if (!e) return NULL;
  391. if (!upb_def_init(upb_enumdef_upcast_mutable(e), UPB_DEF_ENUM,
  392. &upb_enumdef_vtbl, owner)) {
  393. goto err2;
  394. }
  395. if (!upb_strtable_init(&e->ntoi, UPB_CTYPE_INT32)) goto err2;
  396. if (!upb_inttable_init(&e->iton, UPB_CTYPE_CSTR)) goto err1;
  397. return e;
  398. err1:
  399. upb_strtable_uninit(&e->ntoi);
  400. err2:
  401. upb_gfree(e);
  402. return NULL;
  403. }
  404. bool upb_enumdef_freeze(upb_enumdef *e, upb_status *status) {
  405. upb_def *d = upb_enumdef_upcast_mutable(e);
  406. return upb_def_freeze(&d, 1, status);
  407. }
  408. const char *upb_enumdef_fullname(const upb_enumdef *e) {
  409. return upb_def_fullname(upb_enumdef_upcast(e));
  410. }
  411. const char *upb_enumdef_name(const upb_enumdef *e) {
  412. return upb_def_name(upb_enumdef_upcast(e));
  413. }
  414. bool upb_enumdef_setfullname(upb_enumdef *e, const char *fullname,
  415. upb_status *s) {
  416. return upb_def_setfullname(upb_enumdef_upcast_mutable(e), fullname, s);
  417. }
  418. bool upb_enumdef_addval(upb_enumdef *e, const char *name, int32_t num,
  419. upb_status *status) {
  420. char *name2;
  421. if (!upb_isident(name, strlen(name), false, status)) {
  422. return false;
  423. }
  424. if (upb_enumdef_ntoiz(e, name, NULL)) {
  425. upb_status_seterrf(status, "name '%s' is already defined", name);
  426. return false;
  427. }
  428. if (!upb_strtable_insert(&e->ntoi, name, upb_value_int32(num))) {
  429. upb_status_seterrmsg(status, "out of memory");
  430. return false;
  431. }
  432. if (!upb_inttable_lookup(&e->iton, num, NULL)) {
  433. name2 = upb_gstrdup(name);
  434. if (!name2 || !upb_inttable_insert(&e->iton, num, upb_value_cstr(name2))) {
  435. upb_status_seterrmsg(status, "out of memory");
  436. upb_strtable_remove(&e->ntoi, name, NULL);
  437. return false;
  438. }
  439. }
  440. if (upb_enumdef_numvals(e) == 1) {
  441. bool ok = upb_enumdef_setdefault(e, num, NULL);
  442. UPB_ASSERT(ok);
  443. }
  444. return true;
  445. }
  446. int32_t upb_enumdef_default(const upb_enumdef *e) {
  447. UPB_ASSERT(upb_enumdef_iton(e, e->defaultval));
  448. return e->defaultval;
  449. }
  450. bool upb_enumdef_setdefault(upb_enumdef *e, int32_t val, upb_status *s) {
  451. UPB_ASSERT(!upb_enumdef_isfrozen(e));
  452. if (!upb_enumdef_iton(e, val)) {
  453. upb_status_seterrf(s, "number '%d' is not in the enum.", val);
  454. return false;
  455. }
  456. e->defaultval = val;
  457. return true;
  458. }
  459. int upb_enumdef_numvals(const upb_enumdef *e) {
  460. return upb_strtable_count(&e->ntoi);
  461. }
  462. void upb_enum_begin(upb_enum_iter *i, const upb_enumdef *e) {
  463. /* We iterate over the ntoi table, to account for duplicate numbers. */
  464. upb_strtable_begin(i, &e->ntoi);
  465. }
  466. void upb_enum_next(upb_enum_iter *iter) { upb_strtable_next(iter); }
  467. bool upb_enum_done(upb_enum_iter *iter) { return upb_strtable_done(iter); }
  468. bool upb_enumdef_ntoi(const upb_enumdef *def, const char *name,
  469. size_t len, int32_t *num) {
  470. upb_value v;
  471. if (!upb_strtable_lookup2(&def->ntoi, name, len, &v)) {
  472. return false;
  473. }
  474. if (num) *num = upb_value_getint32(v);
  475. return true;
  476. }
  477. const char *upb_enumdef_iton(const upb_enumdef *def, int32_t num) {
  478. upb_value v;
  479. return upb_inttable_lookup32(&def->iton, num, &v) ?
  480. upb_value_getcstr(v) : NULL;
  481. }
  482. const char *upb_enum_iter_name(upb_enum_iter *iter) {
  483. return upb_strtable_iter_key(iter);
  484. }
  485. int32_t upb_enum_iter_number(upb_enum_iter *iter) {
  486. return upb_value_getint32(upb_strtable_iter_value(iter));
  487. }
  488. /* upb_fielddef ***************************************************************/
  489. static void upb_fielddef_init_default(upb_fielddef *f);
  490. static void upb_fielddef_uninit_default(upb_fielddef *f) {
  491. if (f->type_is_set_ && f->default_is_string && f->defaultval.bytes)
  492. freestr(f->defaultval.bytes);
  493. }
  494. const char *upb_fielddef_fullname(const upb_fielddef *e) {
  495. return upb_def_fullname(upb_fielddef_upcast(e));
  496. }
  497. static void visitfield(const upb_refcounted *r, upb_refcounted_visit *visit,
  498. void *closure) {
  499. const upb_fielddef *f = (const upb_fielddef*)r;
  500. const upb_def *def = upb_fielddef_upcast(f);
  501. if (upb_fielddef_containingtype(f)) {
  502. visit(r, upb_msgdef_upcast2(upb_fielddef_containingtype(f)), closure);
  503. }
  504. if (upb_fielddef_containingoneof(f)) {
  505. visit(r, upb_oneofdef_upcast(upb_fielddef_containingoneof(f)), closure);
  506. }
  507. if (upb_fielddef_subdef(f)) {
  508. visit(r, upb_def_upcast(upb_fielddef_subdef(f)), closure);
  509. }
  510. if (upb_def_file(def)) {
  511. visit(r, upb_filedef_upcast(upb_def_file(def)), closure);
  512. }
  513. }
  514. static void freefield(upb_refcounted *r) {
  515. upb_fielddef *f = (upb_fielddef*)r;
  516. upb_fielddef_uninit_default(f);
  517. if (f->subdef_is_symbolic)
  518. upb_gfree(f->sub.name);
  519. upb_def_uninit(upb_fielddef_upcast_mutable(f));
  520. upb_gfree(f);
  521. }
  522. static const char *enumdefaultstr(const upb_fielddef *f) {
  523. const upb_enumdef *e;
  524. UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  525. e = upb_fielddef_enumsubdef(f);
  526. if (f->default_is_string && f->defaultval.bytes) {
  527. /* Default was explicitly set as a string. */
  528. str_t *s = f->defaultval.bytes;
  529. return s->str;
  530. } else if (e) {
  531. if (!f->default_is_string) {
  532. /* Default was explicitly set as an integer; look it up in enumdef. */
  533. const char *name = upb_enumdef_iton(e, f->defaultval.sint);
  534. if (name) {
  535. return name;
  536. }
  537. } else {
  538. /* Default is completely unset; pull enumdef default. */
  539. if (upb_enumdef_numvals(e) > 0) {
  540. const char *name = upb_enumdef_iton(e, upb_enumdef_default(e));
  541. UPB_ASSERT(name);
  542. return name;
  543. }
  544. }
  545. }
  546. return NULL;
  547. }
  548. static bool enumdefaultint32(const upb_fielddef *f, int32_t *val) {
  549. const upb_enumdef *e;
  550. UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  551. e = upb_fielddef_enumsubdef(f);
  552. if (!f->default_is_string) {
  553. /* Default was explicitly set as an integer. */
  554. *val = f->defaultval.sint;
  555. return true;
  556. } else if (e) {
  557. if (f->defaultval.bytes) {
  558. /* Default was explicitly set as a str; try to lookup corresponding int. */
  559. str_t *s = f->defaultval.bytes;
  560. if (upb_enumdef_ntoiz(e, s->str, val)) {
  561. return true;
  562. }
  563. } else {
  564. /* Default is unset; try to pull in enumdef default. */
  565. if (upb_enumdef_numvals(e) > 0) {
  566. *val = upb_enumdef_default(e);
  567. return true;
  568. }
  569. }
  570. }
  571. return false;
  572. }
  573. const struct upb_refcounted_vtbl upb_fielddef_vtbl = {visitfield, freefield};
  574. upb_fielddef *upb_fielddef_new(const void *o) {
  575. upb_fielddef *f = upb_gmalloc(sizeof(*f));
  576. if (!f) return NULL;
  577. if (!upb_def_init(upb_fielddef_upcast_mutable(f), UPB_DEF_FIELD,
  578. &upb_fielddef_vtbl, o)) {
  579. upb_gfree(f);
  580. return NULL;
  581. }
  582. f->msg.def = NULL;
  583. f->sub.def = NULL;
  584. f->oneof = NULL;
  585. f->subdef_is_symbolic = false;
  586. f->msg_is_symbolic = false;
  587. f->label_ = UPB_LABEL_OPTIONAL;
  588. f->type_ = UPB_TYPE_INT32;
  589. f->number_ = 0;
  590. f->type_is_set_ = false;
  591. f->tagdelim = false;
  592. f->is_extension_ = false;
  593. f->lazy_ = false;
  594. f->packed_ = true;
  595. /* For the moment we default this to UPB_INTFMT_VARIABLE, since it will work
  596. * with all integer types and is in some since more "default" since the most
  597. * normal-looking proto2 types int32/int64/uint32/uint64 use variable.
  598. *
  599. * Other options to consider:
  600. * - there is no default; users must set this manually (like type).
  601. * - default signed integers to UPB_INTFMT_ZIGZAG, since it's more likely to
  602. * be an optimal default for signed integers. */
  603. f->intfmt = UPB_INTFMT_VARIABLE;
  604. return f;
  605. }
  606. static upb_fielddef *upb_fielddef_dup(const upb_fielddef *f,
  607. const void *owner) {
  608. const char *srcname;
  609. upb_fielddef *newf = upb_fielddef_new(owner);
  610. if (!newf) return NULL;
  611. upb_fielddef_settype(newf, upb_fielddef_type(f));
  612. upb_fielddef_setlabel(newf, upb_fielddef_label(f));
  613. upb_fielddef_setnumber(newf, upb_fielddef_number(f), NULL);
  614. upb_fielddef_setname(newf, upb_fielddef_name(f), NULL);
  615. if (f->default_is_string && f->defaultval.bytes) {
  616. str_t *s = f->defaultval.bytes;
  617. upb_fielddef_setdefaultstr(newf, s->str, s->len, NULL);
  618. } else {
  619. newf->default_is_string = f->default_is_string;
  620. newf->defaultval = f->defaultval;
  621. }
  622. if (f->subdef_is_symbolic) {
  623. srcname = f->sub.name; /* Might be NULL. */
  624. } else {
  625. srcname = f->sub.def ? upb_def_fullname(f->sub.def) : NULL;
  626. }
  627. if (srcname) {
  628. char *newname = upb_gmalloc(strlen(f->sub.def->fullname) + 2);
  629. if (!newname) {
  630. upb_fielddef_unref(newf, owner);
  631. return NULL;
  632. }
  633. strcpy(newname, ".");
  634. strcat(newname, f->sub.def->fullname);
  635. upb_fielddef_setsubdefname(newf, newname, NULL);
  636. upb_gfree(newname);
  637. }
  638. return newf;
  639. }
  640. bool upb_fielddef_typeisset(const upb_fielddef *f) {
  641. return f->type_is_set_;
  642. }
  643. upb_fieldtype_t upb_fielddef_type(const upb_fielddef *f) {
  644. UPB_ASSERT(f->type_is_set_);
  645. return f->type_;
  646. }
  647. uint32_t upb_fielddef_index(const upb_fielddef *f) {
  648. return f->index_;
  649. }
  650. upb_label_t upb_fielddef_label(const upb_fielddef *f) {
  651. return f->label_;
  652. }
  653. upb_intfmt_t upb_fielddef_intfmt(const upb_fielddef *f) {
  654. return f->intfmt;
  655. }
  656. bool upb_fielddef_istagdelim(const upb_fielddef *f) {
  657. return f->tagdelim;
  658. }
  659. uint32_t upb_fielddef_number(const upb_fielddef *f) {
  660. return f->number_;
  661. }
  662. bool upb_fielddef_isextension(const upb_fielddef *f) {
  663. return f->is_extension_;
  664. }
  665. bool upb_fielddef_lazy(const upb_fielddef *f) {
  666. return f->lazy_;
  667. }
  668. bool upb_fielddef_packed(const upb_fielddef *f) {
  669. return f->packed_;
  670. }
  671. const char *upb_fielddef_name(const upb_fielddef *f) {
  672. return upb_def_fullname(upb_fielddef_upcast(f));
  673. }
  674. size_t upb_fielddef_getjsonname(const upb_fielddef *f, char *buf, size_t len) {
  675. const char *name = upb_fielddef_name(f);
  676. size_t src, dst = 0;
  677. bool ucase_next = false;
  678. #define WRITE(byte) \
  679. ++dst; \
  680. if (dst < len) buf[dst - 1] = byte; \
  681. else if (dst == len) buf[dst - 1] = '\0'
  682. if (!name) {
  683. WRITE('\0');
  684. return 0;
  685. }
  686. /* Implement the transformation as described in the spec:
  687. * 1. upper case all letters after an underscore.
  688. * 2. remove all underscores.
  689. */
  690. for (src = 0; name[src]; src++) {
  691. if (name[src] == '_') {
  692. ucase_next = true;
  693. continue;
  694. }
  695. if (ucase_next) {
  696. WRITE(toupper(name[src]));
  697. ucase_next = false;
  698. } else {
  699. WRITE(name[src]);
  700. }
  701. }
  702. WRITE('\0');
  703. return dst;
  704. #undef WRITE
  705. }
  706. const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f) {
  707. return f->msg_is_symbolic ? NULL : f->msg.def;
  708. }
  709. const upb_oneofdef *upb_fielddef_containingoneof(const upb_fielddef *f) {
  710. return f->oneof;
  711. }
  712. upb_msgdef *upb_fielddef_containingtype_mutable(upb_fielddef *f) {
  713. return (upb_msgdef*)upb_fielddef_containingtype(f);
  714. }
  715. const char *upb_fielddef_containingtypename(upb_fielddef *f) {
  716. return f->msg_is_symbolic ? f->msg.name : NULL;
  717. }
  718. static void release_containingtype(upb_fielddef *f) {
  719. if (f->msg_is_symbolic) upb_gfree(f->msg.name);
  720. }
  721. bool upb_fielddef_setcontainingtypename(upb_fielddef *f, const char *name,
  722. upb_status *s) {
  723. char *name_copy;
  724. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  725. if (upb_fielddef_containingtype(f)) {
  726. upb_status_seterrmsg(s, "field has already been added to a message.");
  727. return false;
  728. }
  729. /* TODO: validate name (upb_isident() doesn't quite work atm because this name
  730. * may have a leading "."). */
  731. name_copy = upb_gstrdup(name);
  732. if (!name_copy) {
  733. upb_upberr_setoom(s);
  734. return false;
  735. }
  736. release_containingtype(f);
  737. f->msg.name = name_copy;
  738. f->msg_is_symbolic = true;
  739. return true;
  740. }
  741. bool upb_fielddef_setname(upb_fielddef *f, const char *name, upb_status *s) {
  742. if (upb_fielddef_containingtype(f) || upb_fielddef_containingoneof(f)) {
  743. upb_status_seterrmsg(s, "Already added to message or oneof");
  744. return false;
  745. }
  746. return upb_def_setfullname(upb_fielddef_upcast_mutable(f), name, s);
  747. }
  748. static void chkdefaulttype(const upb_fielddef *f, upb_fieldtype_t type) {
  749. UPB_UNUSED(f);
  750. UPB_UNUSED(type);
  751. UPB_ASSERT(f->type_is_set_ && upb_fielddef_type(f) == type);
  752. }
  753. int64_t upb_fielddef_defaultint64(const upb_fielddef *f) {
  754. chkdefaulttype(f, UPB_TYPE_INT64);
  755. return f->defaultval.sint;
  756. }
  757. int32_t upb_fielddef_defaultint32(const upb_fielddef *f) {
  758. if (f->type_is_set_ && upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  759. int32_t val;
  760. bool ok = enumdefaultint32(f, &val);
  761. UPB_ASSERT(ok);
  762. return val;
  763. } else {
  764. chkdefaulttype(f, UPB_TYPE_INT32);
  765. return f->defaultval.sint;
  766. }
  767. }
  768. uint64_t upb_fielddef_defaultuint64(const upb_fielddef *f) {
  769. chkdefaulttype(f, UPB_TYPE_UINT64);
  770. return f->defaultval.uint;
  771. }
  772. uint32_t upb_fielddef_defaultuint32(const upb_fielddef *f) {
  773. chkdefaulttype(f, UPB_TYPE_UINT32);
  774. return f->defaultval.uint;
  775. }
  776. bool upb_fielddef_defaultbool(const upb_fielddef *f) {
  777. chkdefaulttype(f, UPB_TYPE_BOOL);
  778. return f->defaultval.uint;
  779. }
  780. float upb_fielddef_defaultfloat(const upb_fielddef *f) {
  781. chkdefaulttype(f, UPB_TYPE_FLOAT);
  782. return f->defaultval.flt;
  783. }
  784. double upb_fielddef_defaultdouble(const upb_fielddef *f) {
  785. chkdefaulttype(f, UPB_TYPE_DOUBLE);
  786. return f->defaultval.dbl;
  787. }
  788. const char *upb_fielddef_defaultstr(const upb_fielddef *f, size_t *len) {
  789. UPB_ASSERT(f->type_is_set_);
  790. UPB_ASSERT(upb_fielddef_type(f) == UPB_TYPE_STRING ||
  791. upb_fielddef_type(f) == UPB_TYPE_BYTES ||
  792. upb_fielddef_type(f) == UPB_TYPE_ENUM);
  793. if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  794. const char *ret = enumdefaultstr(f);
  795. UPB_ASSERT(ret);
  796. /* Enum defaults can't have embedded NULLs. */
  797. if (len) *len = strlen(ret);
  798. return ret;
  799. }
  800. if (f->default_is_string) {
  801. str_t *str = f->defaultval.bytes;
  802. if (len) *len = str->len;
  803. return str->str;
  804. }
  805. return NULL;
  806. }
  807. static void upb_fielddef_init_default(upb_fielddef *f) {
  808. f->default_is_string = false;
  809. switch (upb_fielddef_type(f)) {
  810. case UPB_TYPE_DOUBLE: f->defaultval.dbl = 0; break;
  811. case UPB_TYPE_FLOAT: f->defaultval.flt = 0; break;
  812. case UPB_TYPE_INT32:
  813. case UPB_TYPE_INT64: f->defaultval.sint = 0; break;
  814. case UPB_TYPE_UINT64:
  815. case UPB_TYPE_UINT32:
  816. case UPB_TYPE_BOOL: f->defaultval.uint = 0; break;
  817. case UPB_TYPE_STRING:
  818. case UPB_TYPE_BYTES:
  819. f->defaultval.bytes = newstr("", 0);
  820. f->default_is_string = true;
  821. break;
  822. case UPB_TYPE_MESSAGE: break;
  823. case UPB_TYPE_ENUM:
  824. /* This is our special sentinel that indicates "not set" for an enum. */
  825. f->default_is_string = true;
  826. f->defaultval.bytes = NULL;
  827. break;
  828. }
  829. }
  830. const upb_def *upb_fielddef_subdef(const upb_fielddef *f) {
  831. return f->subdef_is_symbolic ? NULL : f->sub.def;
  832. }
  833. const upb_msgdef *upb_fielddef_msgsubdef(const upb_fielddef *f) {
  834. const upb_def *def = upb_fielddef_subdef(f);
  835. return def ? upb_dyncast_msgdef(def) : NULL;
  836. }
  837. const upb_enumdef *upb_fielddef_enumsubdef(const upb_fielddef *f) {
  838. const upb_def *def = upb_fielddef_subdef(f);
  839. return def ? upb_dyncast_enumdef(def) : NULL;
  840. }
  841. upb_def *upb_fielddef_subdef_mutable(upb_fielddef *f) {
  842. return (upb_def*)upb_fielddef_subdef(f);
  843. }
  844. const char *upb_fielddef_subdefname(const upb_fielddef *f) {
  845. if (f->subdef_is_symbolic) {
  846. return f->sub.name;
  847. } else if (f->sub.def) {
  848. return upb_def_fullname(f->sub.def);
  849. } else {
  850. return NULL;
  851. }
  852. }
  853. bool upb_fielddef_setnumber(upb_fielddef *f, uint32_t number, upb_status *s) {
  854. if (upb_fielddef_containingtype(f)) {
  855. upb_status_seterrmsg(
  856. s, "cannot change field number after adding to a message");
  857. return false;
  858. }
  859. if (number == 0 || number > UPB_MAX_FIELDNUMBER) {
  860. upb_status_seterrf(s, "invalid field number (%u)", number);
  861. return false;
  862. }
  863. f->number_ = number;
  864. return true;
  865. }
  866. void upb_fielddef_settype(upb_fielddef *f, upb_fieldtype_t type) {
  867. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  868. UPB_ASSERT(upb_fielddef_checktype(type));
  869. upb_fielddef_uninit_default(f);
  870. f->type_ = type;
  871. f->type_is_set_ = true;
  872. upb_fielddef_init_default(f);
  873. }
  874. void upb_fielddef_setdescriptortype(upb_fielddef *f, int type) {
  875. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  876. switch (type) {
  877. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  878. upb_fielddef_settype(f, UPB_TYPE_DOUBLE);
  879. break;
  880. case UPB_DESCRIPTOR_TYPE_FLOAT:
  881. upb_fielddef_settype(f, UPB_TYPE_FLOAT);
  882. break;
  883. case UPB_DESCRIPTOR_TYPE_INT64:
  884. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  885. case UPB_DESCRIPTOR_TYPE_SINT64:
  886. upb_fielddef_settype(f, UPB_TYPE_INT64);
  887. break;
  888. case UPB_DESCRIPTOR_TYPE_UINT64:
  889. case UPB_DESCRIPTOR_TYPE_FIXED64:
  890. upb_fielddef_settype(f, UPB_TYPE_UINT64);
  891. break;
  892. case UPB_DESCRIPTOR_TYPE_INT32:
  893. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  894. case UPB_DESCRIPTOR_TYPE_SINT32:
  895. upb_fielddef_settype(f, UPB_TYPE_INT32);
  896. break;
  897. case UPB_DESCRIPTOR_TYPE_UINT32:
  898. case UPB_DESCRIPTOR_TYPE_FIXED32:
  899. upb_fielddef_settype(f, UPB_TYPE_UINT32);
  900. break;
  901. case UPB_DESCRIPTOR_TYPE_BOOL:
  902. upb_fielddef_settype(f, UPB_TYPE_BOOL);
  903. break;
  904. case UPB_DESCRIPTOR_TYPE_STRING:
  905. upb_fielddef_settype(f, UPB_TYPE_STRING);
  906. break;
  907. case UPB_DESCRIPTOR_TYPE_BYTES:
  908. upb_fielddef_settype(f, UPB_TYPE_BYTES);
  909. break;
  910. case UPB_DESCRIPTOR_TYPE_GROUP:
  911. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  912. upb_fielddef_settype(f, UPB_TYPE_MESSAGE);
  913. break;
  914. case UPB_DESCRIPTOR_TYPE_ENUM:
  915. upb_fielddef_settype(f, UPB_TYPE_ENUM);
  916. break;
  917. default: UPB_ASSERT(false);
  918. }
  919. if (type == UPB_DESCRIPTOR_TYPE_FIXED64 ||
  920. type == UPB_DESCRIPTOR_TYPE_FIXED32 ||
  921. type == UPB_DESCRIPTOR_TYPE_SFIXED64 ||
  922. type == UPB_DESCRIPTOR_TYPE_SFIXED32) {
  923. upb_fielddef_setintfmt(f, UPB_INTFMT_FIXED);
  924. } else if (type == UPB_DESCRIPTOR_TYPE_SINT64 ||
  925. type == UPB_DESCRIPTOR_TYPE_SINT32) {
  926. upb_fielddef_setintfmt(f, UPB_INTFMT_ZIGZAG);
  927. } else {
  928. upb_fielddef_setintfmt(f, UPB_INTFMT_VARIABLE);
  929. }
  930. upb_fielddef_settagdelim(f, type == UPB_DESCRIPTOR_TYPE_GROUP);
  931. }
  932. upb_descriptortype_t upb_fielddef_descriptortype(const upb_fielddef *f) {
  933. switch (upb_fielddef_type(f)) {
  934. case UPB_TYPE_FLOAT: return UPB_DESCRIPTOR_TYPE_FLOAT;
  935. case UPB_TYPE_DOUBLE: return UPB_DESCRIPTOR_TYPE_DOUBLE;
  936. case UPB_TYPE_BOOL: return UPB_DESCRIPTOR_TYPE_BOOL;
  937. case UPB_TYPE_STRING: return UPB_DESCRIPTOR_TYPE_STRING;
  938. case UPB_TYPE_BYTES: return UPB_DESCRIPTOR_TYPE_BYTES;
  939. case UPB_TYPE_ENUM: return UPB_DESCRIPTOR_TYPE_ENUM;
  940. case UPB_TYPE_INT32:
  941. switch (upb_fielddef_intfmt(f)) {
  942. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT32;
  943. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED32;
  944. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT32;
  945. }
  946. case UPB_TYPE_INT64:
  947. switch (upb_fielddef_intfmt(f)) {
  948. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT64;
  949. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED64;
  950. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT64;
  951. }
  952. case UPB_TYPE_UINT32:
  953. switch (upb_fielddef_intfmt(f)) {
  954. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT32;
  955. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED32;
  956. case UPB_INTFMT_ZIGZAG: return -1;
  957. }
  958. case UPB_TYPE_UINT64:
  959. switch (upb_fielddef_intfmt(f)) {
  960. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT64;
  961. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED64;
  962. case UPB_INTFMT_ZIGZAG: return -1;
  963. }
  964. case UPB_TYPE_MESSAGE:
  965. return upb_fielddef_istagdelim(f) ?
  966. UPB_DESCRIPTOR_TYPE_GROUP : UPB_DESCRIPTOR_TYPE_MESSAGE;
  967. }
  968. return 0;
  969. }
  970. void upb_fielddef_setisextension(upb_fielddef *f, bool is_extension) {
  971. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  972. f->is_extension_ = is_extension;
  973. }
  974. void upb_fielddef_setlazy(upb_fielddef *f, bool lazy) {
  975. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  976. f->lazy_ = lazy;
  977. }
  978. void upb_fielddef_setpacked(upb_fielddef *f, bool packed) {
  979. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  980. f->packed_ = packed;
  981. }
  982. void upb_fielddef_setlabel(upb_fielddef *f, upb_label_t label) {
  983. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  984. UPB_ASSERT(upb_fielddef_checklabel(label));
  985. f->label_ = label;
  986. }
  987. void upb_fielddef_setintfmt(upb_fielddef *f, upb_intfmt_t fmt) {
  988. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  989. UPB_ASSERT(upb_fielddef_checkintfmt(fmt));
  990. f->intfmt = fmt;
  991. }
  992. void upb_fielddef_settagdelim(upb_fielddef *f, bool tag_delim) {
  993. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  994. f->tagdelim = tag_delim;
  995. f->tagdelim = tag_delim;
  996. }
  997. static bool checksetdefault(upb_fielddef *f, upb_fieldtype_t type) {
  998. if (!f->type_is_set_ || upb_fielddef_isfrozen(f) ||
  999. upb_fielddef_type(f) != type) {
  1000. UPB_ASSERT(false);
  1001. return false;
  1002. }
  1003. if (f->default_is_string) {
  1004. str_t *s = f->defaultval.bytes;
  1005. UPB_ASSERT(s || type == UPB_TYPE_ENUM);
  1006. if (s) freestr(s);
  1007. }
  1008. f->default_is_string = false;
  1009. return true;
  1010. }
  1011. void upb_fielddef_setdefaultint64(upb_fielddef *f, int64_t value) {
  1012. if (checksetdefault(f, UPB_TYPE_INT64))
  1013. f->defaultval.sint = value;
  1014. }
  1015. void upb_fielddef_setdefaultint32(upb_fielddef *f, int32_t value) {
  1016. if ((upb_fielddef_type(f) == UPB_TYPE_ENUM &&
  1017. checksetdefault(f, UPB_TYPE_ENUM)) ||
  1018. checksetdefault(f, UPB_TYPE_INT32)) {
  1019. f->defaultval.sint = value;
  1020. }
  1021. }
  1022. void upb_fielddef_setdefaultuint64(upb_fielddef *f, uint64_t value) {
  1023. if (checksetdefault(f, UPB_TYPE_UINT64))
  1024. f->defaultval.uint = value;
  1025. }
  1026. void upb_fielddef_setdefaultuint32(upb_fielddef *f, uint32_t value) {
  1027. if (checksetdefault(f, UPB_TYPE_UINT32))
  1028. f->defaultval.uint = value;
  1029. }
  1030. void upb_fielddef_setdefaultbool(upb_fielddef *f, bool value) {
  1031. if (checksetdefault(f, UPB_TYPE_BOOL))
  1032. f->defaultval.uint = value;
  1033. }
  1034. void upb_fielddef_setdefaultfloat(upb_fielddef *f, float value) {
  1035. if (checksetdefault(f, UPB_TYPE_FLOAT))
  1036. f->defaultval.flt = value;
  1037. }
  1038. void upb_fielddef_setdefaultdouble(upb_fielddef *f, double value) {
  1039. if (checksetdefault(f, UPB_TYPE_DOUBLE))
  1040. f->defaultval.dbl = value;
  1041. }
  1042. bool upb_fielddef_setdefaultstr(upb_fielddef *f, const void *str, size_t len,
  1043. upb_status *s) {
  1044. str_t *str2;
  1045. UPB_ASSERT(upb_fielddef_isstring(f) || f->type_ == UPB_TYPE_ENUM);
  1046. if (f->type_ == UPB_TYPE_ENUM && !upb_isident(str, len, false, s))
  1047. return false;
  1048. if (f->default_is_string) {
  1049. str_t *s = f->defaultval.bytes;
  1050. UPB_ASSERT(s || f->type_ == UPB_TYPE_ENUM);
  1051. if (s) freestr(s);
  1052. } else {
  1053. UPB_ASSERT(f->type_ == UPB_TYPE_ENUM);
  1054. }
  1055. str2 = newstr(str, len);
  1056. f->defaultval.bytes = str2;
  1057. f->default_is_string = true;
  1058. return true;
  1059. }
  1060. void upb_fielddef_setdefaultcstr(upb_fielddef *f, const char *str,
  1061. upb_status *s) {
  1062. UPB_ASSERT(f->type_is_set_);
  1063. upb_fielddef_setdefaultstr(f, str, str ? strlen(str) : 0, s);
  1064. }
  1065. bool upb_fielddef_enumhasdefaultint32(const upb_fielddef *f) {
  1066. int32_t val;
  1067. UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  1068. return enumdefaultint32(f, &val);
  1069. }
  1070. bool upb_fielddef_enumhasdefaultstr(const upb_fielddef *f) {
  1071. UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  1072. return enumdefaultstr(f) != NULL;
  1073. }
  1074. static bool upb_subdef_typecheck(upb_fielddef *f, const upb_def *subdef,
  1075. upb_status *s) {
  1076. if (f->type_ == UPB_TYPE_MESSAGE) {
  1077. if (upb_dyncast_msgdef(subdef)) return true;
  1078. upb_status_seterrmsg(s, "invalid subdef type for this submessage field");
  1079. return false;
  1080. } else if (f->type_ == UPB_TYPE_ENUM) {
  1081. if (upb_dyncast_enumdef(subdef)) return true;
  1082. upb_status_seterrmsg(s, "invalid subdef type for this enum field");
  1083. return false;
  1084. } else {
  1085. upb_status_seterrmsg(s, "only message and enum fields can have a subdef");
  1086. return false;
  1087. }
  1088. }
  1089. static void release_subdef(upb_fielddef *f) {
  1090. if (f->subdef_is_symbolic) {
  1091. upb_gfree(f->sub.name);
  1092. } else if (f->sub.def) {
  1093. upb_unref2(f->sub.def, f);
  1094. }
  1095. }
  1096. bool upb_fielddef_setsubdef(upb_fielddef *f, const upb_def *subdef,
  1097. upb_status *s) {
  1098. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1099. UPB_ASSERT(upb_fielddef_hassubdef(f));
  1100. if (subdef && !upb_subdef_typecheck(f, subdef, s)) return false;
  1101. release_subdef(f);
  1102. f->sub.def = subdef;
  1103. f->subdef_is_symbolic = false;
  1104. if (f->sub.def) upb_ref2(f->sub.def, f);
  1105. return true;
  1106. }
  1107. bool upb_fielddef_setmsgsubdef(upb_fielddef *f, const upb_msgdef *subdef,
  1108. upb_status *s) {
  1109. return upb_fielddef_setsubdef(f, upb_msgdef_upcast(subdef), s);
  1110. }
  1111. bool upb_fielddef_setenumsubdef(upb_fielddef *f, const upb_enumdef *subdef,
  1112. upb_status *s) {
  1113. return upb_fielddef_setsubdef(f, upb_enumdef_upcast(subdef), s);
  1114. }
  1115. bool upb_fielddef_setsubdefname(upb_fielddef *f, const char *name,
  1116. upb_status *s) {
  1117. char *name_copy;
  1118. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1119. if (!upb_fielddef_hassubdef(f)) {
  1120. upb_status_seterrmsg(s, "field type does not accept a subdef");
  1121. return false;
  1122. }
  1123. name_copy = upb_gstrdup(name);
  1124. if (!name_copy) {
  1125. upb_upberr_setoom(s);
  1126. return false;
  1127. }
  1128. /* TODO: validate name (upb_isident() doesn't quite work atm because this name
  1129. * may have a leading "."). */
  1130. release_subdef(f);
  1131. f->sub.name = name_copy;
  1132. f->subdef_is_symbolic = true;
  1133. return true;
  1134. }
  1135. bool upb_fielddef_issubmsg(const upb_fielddef *f) {
  1136. return upb_fielddef_type(f) == UPB_TYPE_MESSAGE;
  1137. }
  1138. bool upb_fielddef_isstring(const upb_fielddef *f) {
  1139. return upb_fielddef_type(f) == UPB_TYPE_STRING ||
  1140. upb_fielddef_type(f) == UPB_TYPE_BYTES;
  1141. }
  1142. bool upb_fielddef_isseq(const upb_fielddef *f) {
  1143. return upb_fielddef_label(f) == UPB_LABEL_REPEATED;
  1144. }
  1145. bool upb_fielddef_isprimitive(const upb_fielddef *f) {
  1146. return !upb_fielddef_isstring(f) && !upb_fielddef_issubmsg(f);
  1147. }
  1148. bool upb_fielddef_ismap(const upb_fielddef *f) {
  1149. return upb_fielddef_isseq(f) && upb_fielddef_issubmsg(f) &&
  1150. upb_msgdef_mapentry(upb_fielddef_msgsubdef(f));
  1151. }
  1152. bool upb_fielddef_haspresence(const upb_fielddef *f) {
  1153. if (upb_fielddef_isseq(f)) return false;
  1154. if (upb_fielddef_issubmsg(f)) return true;
  1155. /* Primitive field: return true unless there is a message that specifies
  1156. * presence should not exist. */
  1157. if (f->msg_is_symbolic || !f->msg.def) return true;
  1158. return f->msg.def->syntax == UPB_SYNTAX_PROTO2;
  1159. }
  1160. bool upb_fielddef_hassubdef(const upb_fielddef *f) {
  1161. return upb_fielddef_issubmsg(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM;
  1162. }
  1163. static bool between(int32_t x, int32_t low, int32_t high) {
  1164. return x >= low && x <= high;
  1165. }
  1166. bool upb_fielddef_checklabel(int32_t label) { return between(label, 1, 3); }
  1167. bool upb_fielddef_checktype(int32_t type) { return between(type, 1, 11); }
  1168. bool upb_fielddef_checkintfmt(int32_t fmt) { return between(fmt, 1, 3); }
  1169. bool upb_fielddef_checkdescriptortype(int32_t type) {
  1170. return between(type, 1, 18);
  1171. }
  1172. /* upb_msgdef *****************************************************************/
  1173. static void visitmsg(const upb_refcounted *r, upb_refcounted_visit *visit,
  1174. void *closure) {
  1175. upb_msg_oneof_iter o;
  1176. const upb_msgdef *m = (const upb_msgdef*)r;
  1177. const upb_def *def = upb_msgdef_upcast(m);
  1178. upb_msg_field_iter i;
  1179. for(upb_msg_field_begin(&i, m);
  1180. !upb_msg_field_done(&i);
  1181. upb_msg_field_next(&i)) {
  1182. upb_fielddef *f = upb_msg_iter_field(&i);
  1183. visit(r, upb_fielddef_upcast2(f), closure);
  1184. }
  1185. for(upb_msg_oneof_begin(&o, m);
  1186. !upb_msg_oneof_done(&o);
  1187. upb_msg_oneof_next(&o)) {
  1188. upb_oneofdef *f = upb_msg_iter_oneof(&o);
  1189. visit(r, upb_oneofdef_upcast(f), closure);
  1190. }
  1191. if (upb_def_file(def)) {
  1192. visit(r, upb_filedef_upcast(upb_def_file(def)), closure);
  1193. }
  1194. }
  1195. static void freemsg(upb_refcounted *r) {
  1196. upb_msgdef *m = (upb_msgdef*)r;
  1197. upb_strtable_uninit(&m->ntof);
  1198. upb_inttable_uninit(&m->itof);
  1199. upb_def_uninit(upb_msgdef_upcast_mutable(m));
  1200. upb_gfree(m);
  1201. }
  1202. const struct upb_refcounted_vtbl upb_msgdef_vtbl = {visitmsg, freemsg};
  1203. upb_msgdef *upb_msgdef_new(const void *owner) {
  1204. upb_msgdef *m = upb_gmalloc(sizeof(*m));
  1205. if (!m) return NULL;
  1206. if (!upb_def_init(upb_msgdef_upcast_mutable(m), UPB_DEF_MSG, &upb_msgdef_vtbl,
  1207. owner)) {
  1208. goto err2;
  1209. }
  1210. if (!upb_inttable_init(&m->itof, UPB_CTYPE_PTR)) goto err2;
  1211. if (!upb_strtable_init(&m->ntof, UPB_CTYPE_PTR)) goto err1;
  1212. m->map_entry = false;
  1213. m->syntax = UPB_SYNTAX_PROTO2;
  1214. return m;
  1215. err1:
  1216. upb_inttable_uninit(&m->itof);
  1217. err2:
  1218. upb_gfree(m);
  1219. return NULL;
  1220. }
  1221. static upb_oneofdef *upb_oneofdef_dup(const upb_oneofdef *o, const void *owner);
  1222. static upb_msgdef *upb_msgdef_dup(const upb_msgdef *m, const void *owner) {
  1223. bool ok;
  1224. upb_msg_field_iter i;
  1225. upb_msg_oneof_iter o;
  1226. upb_msgdef *newm = upb_msgdef_new(owner);
  1227. if (!newm) return NULL;
  1228. ok = upb_def_setfullname(upb_msgdef_upcast_mutable(newm),
  1229. upb_def_fullname(upb_msgdef_upcast(m)),
  1230. NULL);
  1231. newm->map_entry = m->map_entry;
  1232. newm->syntax = m->syntax;
  1233. UPB_ASSERT(ok);
  1234. for(upb_msg_field_begin(&i, m);
  1235. !upb_msg_field_done(&i);
  1236. upb_msg_field_next(&i)) {
  1237. upb_fielddef *f = upb_fielddef_dup(upb_msg_iter_field(&i), &f);
  1238. /* Fields in oneofs are dup'd below. */
  1239. if (upb_fielddef_containingoneof(f)) continue;
  1240. if (!f || !upb_msgdef_addfield(newm, f, &f, NULL)) {
  1241. upb_msgdef_unref(newm, owner);
  1242. return NULL;
  1243. }
  1244. }
  1245. for(upb_msg_oneof_begin(&o, m);
  1246. !upb_msg_oneof_done(&o);
  1247. upb_msg_oneof_next(&o)) {
  1248. upb_oneofdef *f = upb_oneofdef_dup(upb_msg_iter_oneof(&o), &f);
  1249. if (!f || !upb_msgdef_addoneof(newm, f, &f, NULL)) {
  1250. upb_msgdef_unref(newm, owner);
  1251. return NULL;
  1252. }
  1253. }
  1254. return newm;
  1255. }
  1256. bool upb_msgdef_freeze(upb_msgdef *m, upb_status *status) {
  1257. upb_def *d = upb_msgdef_upcast_mutable(m);
  1258. return upb_def_freeze(&d, 1, status);
  1259. }
  1260. const char *upb_msgdef_fullname(const upb_msgdef *m) {
  1261. return upb_def_fullname(upb_msgdef_upcast(m));
  1262. }
  1263. const char *upb_msgdef_name(const upb_msgdef *m) {
  1264. return upb_def_name(upb_msgdef_upcast(m));
  1265. }
  1266. bool upb_msgdef_setfullname(upb_msgdef *m, const char *fullname,
  1267. upb_status *s) {
  1268. return upb_def_setfullname(upb_msgdef_upcast_mutable(m), fullname, s);
  1269. }
  1270. bool upb_msgdef_setsyntax(upb_msgdef *m, upb_syntax_t syntax) {
  1271. if (syntax != UPB_SYNTAX_PROTO2 && syntax != UPB_SYNTAX_PROTO3) {
  1272. return false;
  1273. }
  1274. m->syntax = syntax;
  1275. return true;
  1276. }
  1277. upb_syntax_t upb_msgdef_syntax(const upb_msgdef *m) {
  1278. return m->syntax;
  1279. }
  1280. /* Helper: check that the field |f| is safe to add to msgdef |m|. Set an error
  1281. * on status |s| and return false if not. */
  1282. static bool check_field_add(const upb_msgdef *m, const upb_fielddef *f,
  1283. upb_status *s) {
  1284. if (upb_fielddef_containingtype(f) != NULL) {
  1285. upb_status_seterrmsg(s, "fielddef already belongs to a message");
  1286. return false;
  1287. } else if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  1288. upb_status_seterrmsg(s, "field name or number were not set");
  1289. return false;
  1290. } else if (upb_msgdef_itof(m, upb_fielddef_number(f))) {
  1291. upb_status_seterrmsg(s, "duplicate field number");
  1292. return false;
  1293. } else if (upb_strtable_lookup(&m->ntof, upb_fielddef_name(f), NULL)) {
  1294. upb_status_seterrmsg(s, "name conflicts with existing field or oneof");
  1295. return false;
  1296. }
  1297. return true;
  1298. }
  1299. static void add_field(upb_msgdef *m, upb_fielddef *f, const void *ref_donor) {
  1300. release_containingtype(f);
  1301. f->msg.def = m;
  1302. f->msg_is_symbolic = false;
  1303. upb_inttable_insert(&m->itof, upb_fielddef_number(f), upb_value_ptr(f));
  1304. upb_strtable_insert(&m->ntof, upb_fielddef_name(f), upb_value_ptr(f));
  1305. upb_ref2(f, m);
  1306. upb_ref2(m, f);
  1307. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  1308. }
  1309. bool upb_msgdef_addfield(upb_msgdef *m, upb_fielddef *f, const void *ref_donor,
  1310. upb_status *s) {
  1311. /* TODO: extensions need to have a separate namespace, because proto2 allows a
  1312. * top-level extension (ie. one not in any package) to have the same name as a
  1313. * field from the message.
  1314. *
  1315. * This also implies that there needs to be a separate lookup-by-name method
  1316. * for extensions. It seems desirable for iteration to return both extensions
  1317. * and non-extensions though.
  1318. *
  1319. * We also need to validate that the field number is in an extension range iff
  1320. * it is an extension.
  1321. *
  1322. * This method is idempotent. Check if |f| is already part of this msgdef and
  1323. * return immediately if so. */
  1324. if (upb_fielddef_containingtype(f) == m) {
  1325. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  1326. return true;
  1327. }
  1328. /* Check constraints for all fields before performing any action. */
  1329. if (!check_field_add(m, f, s)) {
  1330. return false;
  1331. } else if (upb_fielddef_containingoneof(f) != NULL) {
  1332. /* Fields in a oneof can only be added by adding the oneof to the msgdef. */
  1333. upb_status_seterrmsg(s, "fielddef is part of a oneof");
  1334. return false;
  1335. }
  1336. /* Constraint checks ok, perform the action. */
  1337. add_field(m, f, ref_donor);
  1338. return true;
  1339. }
  1340. bool upb_msgdef_addoneof(upb_msgdef *m, upb_oneofdef *o, const void *ref_donor,
  1341. upb_status *s) {
  1342. upb_oneof_iter it;
  1343. /* Check various conditions that would prevent this oneof from being added. */
  1344. if (upb_oneofdef_containingtype(o)) {
  1345. upb_status_seterrmsg(s, "oneofdef already belongs to a message");
  1346. return false;
  1347. } else if (upb_oneofdef_name(o) == NULL) {
  1348. upb_status_seterrmsg(s, "oneofdef name was not set");
  1349. return false;
  1350. } else if (upb_strtable_lookup(&m->ntof, upb_oneofdef_name(o), NULL)) {
  1351. upb_status_seterrmsg(s, "name conflicts with existing field or oneof");
  1352. return false;
  1353. }
  1354. /* Check that all of the oneof's fields do not conflict with names or numbers
  1355. * of fields already in the message. */
  1356. for (upb_oneof_begin(&it, o); !upb_oneof_done(&it); upb_oneof_next(&it)) {
  1357. const upb_fielddef *f = upb_oneof_iter_field(&it);
  1358. if (!check_field_add(m, f, s)) {
  1359. return false;
  1360. }
  1361. }
  1362. /* Everything checks out -- commit now. */
  1363. /* Add oneof itself first. */
  1364. o->parent = m;
  1365. upb_strtable_insert(&m->ntof, upb_oneofdef_name(o), upb_value_ptr(o));
  1366. upb_ref2(o, m);
  1367. upb_ref2(m, o);
  1368. /* Add each field of the oneof directly to the msgdef. */
  1369. for (upb_oneof_begin(&it, o); !upb_oneof_done(&it); upb_oneof_next(&it)) {
  1370. upb_fielddef *f = upb_oneof_iter_field(&it);
  1371. add_field(m, f, NULL);
  1372. }
  1373. if (ref_donor) upb_oneofdef_unref(o, ref_donor);
  1374. return true;
  1375. }
  1376. const upb_fielddef *upb_msgdef_itof(const upb_msgdef *m, uint32_t i) {
  1377. upb_value val;
  1378. return upb_inttable_lookup32(&m->itof, i, &val) ?
  1379. upb_value_getptr(val) : NULL;
  1380. }
  1381. const upb_fielddef *upb_msgdef_ntof(const upb_msgdef *m, const char *name,
  1382. size_t len) {
  1383. upb_value val;
  1384. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  1385. return NULL;
  1386. }
  1387. return upb_trygetfield(upb_value_getptr(val));
  1388. }
  1389. const upb_oneofdef *upb_msgdef_ntoo(const upb_msgdef *m, const char *name,
  1390. size_t len) {
  1391. upb_value val;
  1392. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  1393. return NULL;
  1394. }
  1395. return upb_trygetoneof(upb_value_getptr(val));
  1396. }
  1397. bool upb_msgdef_lookupname(const upb_msgdef *m, const char *name, size_t len,
  1398. const upb_fielddef **f, const upb_oneofdef **o) {
  1399. upb_value val;
  1400. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  1401. return false;
  1402. }
  1403. *o = upb_trygetoneof(upb_value_getptr(val));
  1404. *f = upb_trygetfield(upb_value_getptr(val));
  1405. UPB_ASSERT((*o != NULL) ^ (*f != NULL)); /* Exactly one of the two should be set. */
  1406. return true;
  1407. }
  1408. int upb_msgdef_numfields(const upb_msgdef *m) {
  1409. /* The number table contains only fields. */
  1410. return upb_inttable_count(&m->itof);
  1411. }
  1412. int upb_msgdef_numoneofs(const upb_msgdef *m) {
  1413. /* The name table includes oneofs, and the number table does not. */
  1414. return upb_strtable_count(&m->ntof) - upb_inttable_count(&m->itof);
  1415. }
  1416. void upb_msgdef_setmapentry(upb_msgdef *m, bool map_entry) {
  1417. UPB_ASSERT(!upb_msgdef_isfrozen(m));
  1418. m->map_entry = map_entry;
  1419. }
  1420. bool upb_msgdef_mapentry(const upb_msgdef *m) {
  1421. return m->map_entry;
  1422. }
  1423. void upb_msg_field_begin(upb_msg_field_iter *iter, const upb_msgdef *m) {
  1424. upb_inttable_begin(iter, &m->itof);
  1425. }
  1426. void upb_msg_field_next(upb_msg_field_iter *iter) { upb_inttable_next(iter); }
  1427. bool upb_msg_field_done(const upb_msg_field_iter *iter) {
  1428. return upb_inttable_done(iter);
  1429. }
  1430. upb_fielddef *upb_msg_iter_field(const upb_msg_field_iter *iter) {
  1431. return (upb_fielddef*)upb_value_getptr(upb_inttable_iter_value(iter));
  1432. }
  1433. void upb_msg_field_iter_setdone(upb_msg_field_iter *iter) {
  1434. upb_inttable_iter_setdone(iter);
  1435. }
  1436. void upb_msg_oneof_begin(upb_msg_oneof_iter *iter, const upb_msgdef *m) {
  1437. upb_strtable_begin(iter, &m->ntof);
  1438. /* We need to skip past any initial fields. */
  1439. while (!upb_strtable_done(iter) &&
  1440. !upb_isoneof(upb_value_getptr(upb_strtable_iter_value(iter)))) {
  1441. upb_strtable_next(iter);
  1442. }
  1443. }
  1444. void upb_msg_oneof_next(upb_msg_oneof_iter *iter) {
  1445. /* We need to skip past fields to return only oneofs. */
  1446. do {
  1447. upb_strtable_next(iter);
  1448. } while (!upb_strtable_done(iter) &&
  1449. !upb_isoneof(upb_value_getptr(upb_strtable_iter_value(iter))));
  1450. }
  1451. bool upb_msg_oneof_done(const upb_msg_oneof_iter *iter) {
  1452. return upb_strtable_done(iter);
  1453. }
  1454. upb_oneofdef *upb_msg_iter_oneof(const upb_msg_oneof_iter *iter) {
  1455. return (upb_oneofdef*)upb_value_getptr(upb_strtable_iter_value(iter));
  1456. }
  1457. void upb_msg_oneof_iter_setdone(upb_msg_oneof_iter *iter) {
  1458. upb_strtable_iter_setdone(iter);
  1459. }
  1460. /* upb_oneofdef ***************************************************************/
  1461. static void visitoneof(const upb_refcounted *r, upb_refcounted_visit *visit,
  1462. void *closure) {
  1463. const upb_oneofdef *o = (const upb_oneofdef*)r;
  1464. upb_oneof_iter i;
  1465. for (upb_oneof_begin(&i, o); !upb_oneof_done(&i); upb_oneof_next(&i)) {
  1466. const upb_fielddef *f = upb_oneof_iter_field(&i);
  1467. visit(r, upb_fielddef_upcast2(f), closure);
  1468. }
  1469. if (o->parent) {
  1470. visit(r, upb_msgdef_upcast2(o->parent), closure);
  1471. }
  1472. }
  1473. static void freeoneof(upb_refcounted *r) {
  1474. upb_oneofdef *o = (upb_oneofdef*)r;
  1475. upb_strtable_uninit(&o->ntof);
  1476. upb_inttable_uninit(&o->itof);
  1477. upb_gfree((void*)o->name);
  1478. upb_gfree(o);
  1479. }
  1480. const struct upb_refcounted_vtbl upb_oneofdef_vtbl = {visitoneof, freeoneof};
  1481. upb_oneofdef *upb_oneofdef_new(const void *owner) {
  1482. upb_oneofdef *o = upb_gmalloc(sizeof(*o));
  1483. if (!o) {
  1484. return NULL;
  1485. }
  1486. o->parent = NULL;
  1487. o->name = NULL;
  1488. if (!upb_refcounted_init(upb_oneofdef_upcast_mutable(o), &upb_oneofdef_vtbl,
  1489. owner)) {
  1490. goto err2;
  1491. }
  1492. if (!upb_inttable_init(&o->itof, UPB_CTYPE_PTR)) goto err2;
  1493. if (!upb_strtable_init(&o->ntof, UPB_CTYPE_PTR)) goto err1;
  1494. return o;
  1495. err1:
  1496. upb_inttable_uninit(&o->itof);
  1497. err2:
  1498. upb_gfree(o);
  1499. return NULL;
  1500. }
  1501. static upb_oneofdef *upb_oneofdef_dup(const upb_oneofdef *o,
  1502. const void *owner) {
  1503. bool ok;
  1504. upb_oneof_iter i;
  1505. upb_oneofdef *newo = upb_oneofdef_new(owner);
  1506. if (!newo) return NULL;
  1507. ok = upb_oneofdef_setname(newo, upb_oneofdef_name(o), NULL);
  1508. UPB_ASSERT(ok);
  1509. for (upb_oneof_begin(&i, o); !upb_oneof_done(&i); upb_oneof_next(&i)) {
  1510. upb_fielddef *f = upb_fielddef_dup(upb_oneof_iter_field(&i), &f);
  1511. if (!f || !upb_oneofdef_addfield(newo, f, &f, NULL)) {
  1512. upb_oneofdef_unref(newo, owner);
  1513. return NULL;
  1514. }
  1515. }
  1516. return newo;
  1517. }
  1518. const char *upb_oneofdef_name(const upb_oneofdef *o) { return o->name; }
  1519. bool upb_oneofdef_setname(upb_oneofdef *o, const char *name, upb_status *s) {
  1520. UPB_ASSERT(!upb_oneofdef_isfrozen(o));
  1521. if (upb_oneofdef_containingtype(o)) {
  1522. upb_status_seterrmsg(s, "oneof already added to a message");
  1523. return false;
  1524. }
  1525. if (!upb_isident(name, strlen(name), true, s)) {
  1526. return false;
  1527. }
  1528. name = upb_gstrdup(name);
  1529. if (!name) {
  1530. upb_status_seterrmsg(s, "One of memory");
  1531. return false;
  1532. }
  1533. upb_gfree((void*)o->name);
  1534. o->name = name;
  1535. return true;
  1536. }
  1537. const upb_msgdef *upb_oneofdef_containingtype(const upb_oneofdef *o) {
  1538. return o->parent;
  1539. }
  1540. int upb_oneofdef_numfields(const upb_oneofdef *o) {
  1541. return upb_strtable_count(&o->ntof);
  1542. }
  1543. uint32_t upb_oneofdef_index(const upb_oneofdef *o) {
  1544. return o->index;
  1545. }
  1546. bool upb_oneofdef_addfield(upb_oneofdef *o, upb_fielddef *f,
  1547. const void *ref_donor,
  1548. upb_status *s) {
  1549. UPB_ASSERT(!upb_oneofdef_isfrozen(o));
  1550. UPB_ASSERT(!o->parent || !upb_msgdef_isfrozen(o->parent));
  1551. /* This method is idempotent. Check if |f| is already part of this oneofdef
  1552. * and return immediately if so. */
  1553. if (upb_fielddef_containingoneof(f) == o) {
  1554. return true;
  1555. }
  1556. /* The field must have an OPTIONAL label. */
  1557. if (upb_fielddef_label(f) != UPB_LABEL_OPTIONAL) {
  1558. upb_status_seterrmsg(s, "fields in oneof must have OPTIONAL label");
  1559. return false;
  1560. }
  1561. /* Check that no field with this name or number exists already in the oneof.
  1562. * Also check that the field is not already part of a oneof. */
  1563. if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  1564. upb_status_seterrmsg(s, "field name or number were not set");
  1565. return false;
  1566. } else if (upb_oneofdef_itof(o, upb_fielddef_number(f)) ||
  1567. upb_oneofdef_ntofz(o, upb_fielddef_name(f))) {
  1568. upb_status_seterrmsg(s, "duplicate field name or number");
  1569. return false;
  1570. } else if (upb_fielddef_containingoneof(f) != NULL) {
  1571. upb_status_seterrmsg(s, "fielddef already belongs to a oneof");
  1572. return false;
  1573. }
  1574. /* We allow adding a field to the oneof either if the field is not part of a
  1575. * msgdef, or if it is and we are also part of the same msgdef. */
  1576. if (o->parent == NULL) {
  1577. /* If we're not in a msgdef, the field cannot be either. Otherwise we would
  1578. * need to magically add this oneof to a msgdef to remain consistent, which
  1579. * is surprising behavior. */
  1580. if (upb_fielddef_containingtype(f) != NULL) {
  1581. upb_status_seterrmsg(s, "fielddef already belongs to a message, but "
  1582. "oneof does not");
  1583. return false;
  1584. }
  1585. } else {
  1586. /* If we're in a msgdef, the user can add fields that either aren't in any
  1587. * msgdef (in which case they're added to our msgdef) or already a part of
  1588. * our msgdef. */
  1589. if (upb_fielddef_containingtype(f) != NULL &&
  1590. upb_fielddef_containingtype(f) != o->parent) {
  1591. upb_status_seterrmsg(s, "fielddef belongs to a different message "
  1592. "than oneof");
  1593. return false;
  1594. }
  1595. }
  1596. /* Commit phase. First add the field to our parent msgdef, if any, because
  1597. * that may fail; then add the field to our own tables. */
  1598. if (o->parent != NULL && upb_fielddef_containingtype(f) == NULL) {
  1599. if (!upb_msgdef_addfield((upb_msgdef*)o->parent, f, NULL, s)) {
  1600. return false;
  1601. }
  1602. }
  1603. release_containingtype(f);
  1604. f->oneof = o;
  1605. upb_inttable_insert(&o->itof, upb_fielddef_number(f), upb_value_ptr(f));
  1606. upb_strtable_insert(&o->ntof, upb_fielddef_name(f), upb_value_ptr(f));
  1607. upb_ref2(f, o);
  1608. upb_ref2(o, f);
  1609. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  1610. return true;
  1611. }
  1612. const upb_fielddef *upb_oneofdef_ntof(const upb_oneofdef *o,
  1613. const char *name, size_t length) {
  1614. upb_value val;
  1615. return upb_strtable_lookup2(&o->ntof, name, length, &val) ?
  1616. upb_value_getptr(val) : NULL;
  1617. }
  1618. const upb_fielddef *upb_oneofdef_itof(const upb_oneofdef *o, uint32_t num) {
  1619. upb_value val;
  1620. return upb_inttable_lookup32(&o->itof, num, &val) ?
  1621. upb_value_getptr(val) : NULL;
  1622. }
  1623. void upb_oneof_begin(upb_oneof_iter *iter, const upb_oneofdef *o) {
  1624. upb_inttable_begin(iter, &o->itof);
  1625. }
  1626. void upb_oneof_next(upb_oneof_iter *iter) {
  1627. upb_inttable_next(iter);
  1628. }
  1629. bool upb_oneof_done(upb_oneof_iter *iter) {
  1630. return upb_inttable_done(iter);
  1631. }
  1632. upb_fielddef *upb_oneof_iter_field(const upb_oneof_iter *iter) {
  1633. return (upb_fielddef*)upb_value_getptr(upb_inttable_iter_value(iter));
  1634. }
  1635. void upb_oneof_iter_setdone(upb_oneof_iter *iter) {
  1636. upb_inttable_iter_setdone(iter);
  1637. }
  1638. /* upb_filedef ****************************************************************/
  1639. static void visitfiledef(const upb_refcounted *r, upb_refcounted_visit *visit,
  1640. void *closure) {
  1641. const upb_filedef *f = (const upb_filedef*)r;
  1642. size_t i;
  1643. for(i = 0; i < upb_filedef_defcount(f); i++) {
  1644. visit(r, upb_def_upcast(upb_filedef_def(f, i)), closure);
  1645. }
  1646. }
  1647. static void freefiledef(upb_refcounted *r) {
  1648. upb_filedef *f = (upb_filedef*)r;
  1649. size_t i;
  1650. for(i = 0; i < upb_filedef_depcount(f); i++) {
  1651. upb_filedef_unref(upb_filedef_dep(f, i), f);
  1652. }
  1653. upb_inttable_uninit(&f->defs);
  1654. upb_inttable_uninit(&f->deps);
  1655. upb_gfree((void*)f->name);
  1656. upb_gfree((void*)f->package);
  1657. upb_gfree(f);
  1658. }
  1659. const struct upb_refcounted_vtbl upb_filedef_vtbl = {visitfiledef, freefiledef};
  1660. upb_filedef *upb_filedef_new(const void *owner) {
  1661. upb_filedef *f = upb_gmalloc(sizeof(*f));
  1662. if (!f) {
  1663. return NULL;
  1664. }
  1665. f->package = NULL;
  1666. f->name = NULL;
  1667. f->syntax = UPB_SYNTAX_PROTO2;
  1668. if (!upb_refcounted_init(upb_filedef_upcast_mutable(f), &upb_filedef_vtbl,
  1669. owner)) {
  1670. goto err;
  1671. }
  1672. if (!upb_inttable_init(&f->defs, UPB_CTYPE_CONSTPTR)) {
  1673. goto err;
  1674. }
  1675. if (!upb_inttable_init(&f->deps, UPB_CTYPE_CONSTPTR)) {
  1676. goto err2;
  1677. }
  1678. return f;
  1679. err2:
  1680. upb_inttable_uninit(&f->defs);
  1681. err:
  1682. upb_gfree(f);
  1683. return NULL;
  1684. }
  1685. const char *upb_filedef_name(const upb_filedef *f) {
  1686. return f->name;
  1687. }
  1688. const char *upb_filedef_package(const upb_filedef *f) {
  1689. return f->package;
  1690. }
  1691. upb_syntax_t upb_filedef_syntax(const upb_filedef *f) {
  1692. return f->syntax;
  1693. }
  1694. size_t upb_filedef_defcount(const upb_filedef *f) {
  1695. return upb_inttable_count(&f->defs);
  1696. }
  1697. size_t upb_filedef_depcount(const upb_filedef *f) {
  1698. return upb_inttable_count(&f->deps);
  1699. }
  1700. const upb_def *upb_filedef_def(const upb_filedef *f, size_t i) {
  1701. upb_value v;
  1702. if (upb_inttable_lookup32(&f->defs, i, &v)) {
  1703. return upb_value_getconstptr(v);
  1704. } else {
  1705. return NULL;
  1706. }
  1707. }
  1708. const upb_filedef *upb_filedef_dep(const upb_filedef *f, size_t i) {
  1709. upb_value v;
  1710. if (upb_inttable_lookup32(&f->deps, i, &v)) {
  1711. return upb_value_getconstptr(v);
  1712. } else {
  1713. return NULL;
  1714. }
  1715. }
  1716. bool upb_filedef_setname(upb_filedef *f, const char *name, upb_status *s) {
  1717. name = upb_gstrdup(name);
  1718. if (!name) {
  1719. upb_upberr_setoom(s);
  1720. return false;
  1721. }
  1722. upb_gfree((void*)f->name);
  1723. f->name = name;
  1724. return true;
  1725. }
  1726. bool upb_filedef_setpackage(upb_filedef *f, const char *package,
  1727. upb_status *s) {
  1728. if (!upb_isident(package, strlen(package), true, s)) return false;
  1729. package = upb_gstrdup(package);
  1730. if (!package) {
  1731. upb_upberr_setoom(s);
  1732. return false;
  1733. }
  1734. upb_gfree((void*)f->package);
  1735. f->package = package;
  1736. return true;
  1737. }
  1738. bool upb_filedef_setsyntax(upb_filedef *f, upb_syntax_t syntax,
  1739. upb_status *s) {
  1740. UPB_UNUSED(s);
  1741. if (syntax != UPB_SYNTAX_PROTO2 &&
  1742. syntax != UPB_SYNTAX_PROTO3) {
  1743. upb_status_seterrmsg(s, "Unknown syntax value.");
  1744. return false;
  1745. }
  1746. f->syntax = syntax;
  1747. {
  1748. /* Set all messages in this file to match. */
  1749. size_t i;
  1750. for (i = 0; i < upb_filedef_defcount(f); i++) {
  1751. /* Casting const away is safe since all defs in mutable filedef must
  1752. * also be mutable. */
  1753. upb_def *def = (upb_def*)upb_filedef_def(f, i);
  1754. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  1755. if (m) {
  1756. m->syntax = syntax;
  1757. }
  1758. }
  1759. }
  1760. return true;
  1761. }
  1762. bool upb_filedef_adddef(upb_filedef *f, upb_def *def, const void *ref_donor,
  1763. upb_status *s) {
  1764. if (def->file) {
  1765. upb_status_seterrmsg(s, "Def is already part of another filedef.");
  1766. return false;
  1767. }
  1768. if (upb_inttable_push(&f->defs, upb_value_constptr(def))) {
  1769. def->file = f;
  1770. upb_ref2(def, f);
  1771. upb_ref2(f, def);
  1772. if (ref_donor) upb_def_unref(def, ref_donor);
  1773. if (def->type == UPB_DEF_MSG) {
  1774. upb_downcast_msgdef_mutable(def)->syntax = f->syntax;
  1775. }
  1776. return true;
  1777. } else {
  1778. upb_upberr_setoom(s);
  1779. return false;
  1780. }
  1781. }
  1782. bool upb_filedef_adddep(upb_filedef *f, const upb_filedef *dep) {
  1783. if (upb_inttable_push(&f->deps, upb_value_constptr(dep))) {
  1784. /* Regular ref instead of ref2 because files can't form cycles. */
  1785. upb_filedef_ref(dep, f);
  1786. return true;
  1787. } else {
  1788. return false;
  1789. }
  1790. }
  1791. void upb_symtab_free(upb_symtab *s) {
  1792. upb_strtable_iter i;
  1793. upb_strtable_begin(&i, &s->symtab);
  1794. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  1795. const upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  1796. upb_def_unref(def, s);
  1797. }
  1798. upb_strtable_uninit(&s->symtab);
  1799. upb_gfree(s);
  1800. }
  1801. upb_symtab *upb_symtab_new() {
  1802. upb_symtab *s = upb_gmalloc(sizeof(*s));
  1803. if (!s) {
  1804. return NULL;
  1805. }
  1806. upb_strtable_init(&s->symtab, UPB_CTYPE_PTR);
  1807. return s;
  1808. }
  1809. const upb_def *upb_symtab_lookup(const upb_symtab *s, const char *sym) {
  1810. upb_value v;
  1811. upb_def *ret = upb_strtable_lookup(&s->symtab, sym, &v) ?
  1812. upb_value_getptr(v) : NULL;
  1813. return ret;
  1814. }
  1815. const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym) {
  1816. upb_value v;
  1817. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  1818. upb_value_getptr(v) : NULL;
  1819. return def ? upb_dyncast_msgdef(def) : NULL;
  1820. }
  1821. const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym) {
  1822. upb_value v;
  1823. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  1824. upb_value_getptr(v) : NULL;
  1825. return def ? upb_dyncast_enumdef(def) : NULL;
  1826. }
  1827. /* Given a symbol and the base symbol inside which it is defined, find the
  1828. * symbol's definition in t. */
  1829. static upb_def *upb_resolvename(const upb_strtable *t,
  1830. const char *base, const char *sym) {
  1831. if(strlen(sym) == 0) return NULL;
  1832. if(sym[0] == '.') {
  1833. /* Symbols starting with '.' are absolute, so we do a single lookup.
  1834. * Slice to omit the leading '.' */
  1835. upb_value v;
  1836. return upb_strtable_lookup(t, sym + 1, &v) ? upb_value_getptr(v) : NULL;
  1837. } else {
  1838. /* Remove components from base until we find an entry or run out.
  1839. * TODO: This branch is totally broken, but currently not used. */
  1840. (void)base;
  1841. UPB_ASSERT(false);
  1842. return NULL;
  1843. }
  1844. }
  1845. const upb_def *upb_symtab_resolve(const upb_symtab *s, const char *base,
  1846. const char *sym) {
  1847. upb_def *ret = upb_resolvename(&s->symtab, base, sym);
  1848. return ret;
  1849. }
  1850. /* TODO(haberman): we need a lot more testing of error conditions. */
  1851. static bool symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
  1852. void *ref_donor, upb_refcounted *freeze_also,
  1853. upb_status *status) {
  1854. size_t i;
  1855. size_t add_n;
  1856. size_t freeze_n;
  1857. upb_strtable_iter iter;
  1858. upb_refcounted **add_objs = NULL;
  1859. upb_def **add_defs = NULL;
  1860. size_t add_objs_size;
  1861. upb_strtable addtab;
  1862. if (n == 0 && !freeze_also) {
  1863. return true;
  1864. }
  1865. if (!upb_strtable_init(&addtab, UPB_CTYPE_PTR)) {
  1866. upb_status_seterrmsg(status, "out of memory");
  1867. return false;
  1868. }
  1869. /* Add new defs to our "add" set. */
  1870. for (i = 0; i < n; i++) {
  1871. upb_def *def = defs[i];
  1872. const char *fullname;
  1873. upb_fielddef *f;
  1874. if (upb_def_isfrozen(def)) {
  1875. upb_status_seterrmsg(status, "added defs must be mutable");
  1876. goto err;
  1877. }
  1878. UPB_ASSERT(!upb_def_isfrozen(def));
  1879. fullname = upb_def_fullname(def);
  1880. if (!fullname) {
  1881. upb_status_seterrmsg(
  1882. status, "Anonymous defs cannot be added to a symtab");
  1883. goto err;
  1884. }
  1885. f = upb_dyncast_fielddef_mutable(def);
  1886. if (f) {
  1887. if (!upb_fielddef_containingtypename(f)) {
  1888. upb_status_seterrmsg(status,
  1889. "Standalone fielddefs must have a containing type "
  1890. "(extendee) name set");
  1891. goto err;
  1892. }
  1893. } else {
  1894. if (upb_strtable_lookup(&addtab, fullname, NULL)) {
  1895. upb_status_seterrf(status, "Conflicting defs named '%s'", fullname);
  1896. goto err;
  1897. }
  1898. if (upb_strtable_lookup(&s->symtab, fullname, NULL)) {
  1899. upb_status_seterrf(status, "Symtab already has a def named '%s'",
  1900. fullname);
  1901. goto err;
  1902. }
  1903. upb_def_donateref(def, ref_donor, s);
  1904. if (!upb_strtable_insert(&addtab, fullname, upb_value_ptr(def)))
  1905. goto oom_err;
  1906. def->came_from_user = true;
  1907. }
  1908. }
  1909. /* Add standalone fielddefs (ie. extensions) to the appropriate messages.
  1910. * If the appropriate message only exists in the existing symtab, duplicate
  1911. * it so we have a mutable copy we can add the fields to. */
  1912. for (i = 0; i < n; i++) {
  1913. upb_def *def = defs[i];
  1914. upb_fielddef *f = upb_dyncast_fielddef_mutable(def);
  1915. const char *msgname;
  1916. upb_value v;
  1917. upb_msgdef *m;
  1918. if (!f) continue;
  1919. msgname = upb_fielddef_containingtypename(f);
  1920. /* We validated this earlier in this function. */
  1921. UPB_ASSERT(msgname);
  1922. /* If the extendee name is absolutely qualified, move past the initial ".".
  1923. * TODO(haberman): it is not obvious what it would mean if this was not
  1924. * absolutely qualified. */
  1925. if (msgname[0] == '.') {
  1926. msgname++;
  1927. }
  1928. if (upb_strtable_lookup(&addtab, msgname, &v)) {
  1929. /* Extendee is in the set of defs the user asked us to add. */
  1930. m = upb_value_getptr(v);
  1931. } else {
  1932. /* Need to find and dup the extendee from the existing symtab. */
  1933. const upb_msgdef *frozen_m = upb_symtab_lookupmsg(s, msgname);
  1934. if (!frozen_m) {
  1935. upb_status_seterrf(status,
  1936. "Tried to extend message %s that does not exist "
  1937. "in this SymbolTable.",
  1938. msgname);
  1939. goto err;
  1940. }
  1941. m = upb_msgdef_dup(frozen_m, s);
  1942. if (!m) goto oom_err;
  1943. if (!upb_strtable_insert(&addtab, msgname, upb_value_ptr(m))) {
  1944. upb_msgdef_unref(m, s);
  1945. goto oom_err;
  1946. }
  1947. }
  1948. if (!upb_msgdef_addfield(m, f, ref_donor, status)) {
  1949. goto err;
  1950. }
  1951. }
  1952. /* Now using the table, resolve symbolic references for subdefs. */
  1953. upb_strtable_begin(&iter, &addtab);
  1954. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  1955. const char *base;
  1956. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
  1957. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  1958. upb_msg_field_iter j;
  1959. if (!m) continue;
  1960. /* Type names are resolved relative to the message in which they appear. */
  1961. base = upb_msgdef_fullname(m);
  1962. for(upb_msg_field_begin(&j, m);
  1963. !upb_msg_field_done(&j);
  1964. upb_msg_field_next(&j)) {
  1965. upb_fielddef *f = upb_msg_iter_field(&j);
  1966. const char *name = upb_fielddef_subdefname(f);
  1967. if (name && !upb_fielddef_subdef(f)) {
  1968. /* Try the lookup in the current set of to-be-added defs first. If not
  1969. * there, try existing defs. */
  1970. upb_def *subdef = upb_resolvename(&addtab, base, name);
  1971. if (subdef == NULL) {
  1972. subdef = upb_resolvename(&s->symtab, base, name);
  1973. }
  1974. if (subdef == NULL) {
  1975. upb_status_seterrf(
  1976. status, "couldn't resolve name '%s' in message '%s'", name, base);
  1977. goto err;
  1978. } else if (!upb_fielddef_setsubdef(f, subdef, status)) {
  1979. goto err;
  1980. }
  1981. }
  1982. }
  1983. }
  1984. /* We need an array of the defs in addtab, for passing to
  1985. * upb_refcounted_freeze(). */
  1986. add_objs_size = upb_strtable_count(&addtab);
  1987. if (freeze_also) {
  1988. add_objs_size++;
  1989. }
  1990. add_defs = upb_gmalloc(sizeof(void*) * add_objs_size);
  1991. if (add_defs == NULL) goto oom_err;
  1992. upb_strtable_begin(&iter, &addtab);
  1993. for (add_n = 0; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  1994. add_defs[add_n++] = upb_value_getptr(upb_strtable_iter_value(&iter));
  1995. }
  1996. /* Validate defs. */
  1997. if (!_upb_def_validate(add_defs, add_n, status)) {
  1998. goto err;
  1999. }
  2000. /* Cheat a little and give the array a new type.
  2001. * This is probably undefined behavior, but this code will be deleted soon. */
  2002. add_objs = (upb_refcounted**)add_defs;
  2003. freeze_n = add_n;
  2004. if (freeze_also) {
  2005. add_objs[freeze_n++] = freeze_also;
  2006. }
  2007. if (!upb_refcounted_freeze(add_objs, freeze_n, status,
  2008. UPB_MAX_MESSAGE_DEPTH * 2)) {
  2009. goto err;
  2010. }
  2011. /* This must be delayed until all errors have been detected, since error
  2012. * recovery code uses this table to cleanup defs. */
  2013. upb_strtable_uninit(&addtab);
  2014. /* TODO(haberman) we don't properly handle errors after this point (like
  2015. * OOM in upb_strtable_insert() below). */
  2016. for (i = 0; i < add_n; i++) {
  2017. upb_def *def = (upb_def*)add_objs[i];
  2018. const char *name = upb_def_fullname(def);
  2019. upb_value v;
  2020. bool success;
  2021. if (upb_strtable_remove(&s->symtab, name, &v)) {
  2022. const upb_def *def = upb_value_getptr(v);
  2023. upb_def_unref(def, s);
  2024. }
  2025. success = upb_strtable_insert(&s->symtab, name, upb_value_ptr(def));
  2026. UPB_ASSERT(success == true);
  2027. }
  2028. upb_gfree(add_defs);
  2029. return true;
  2030. oom_err:
  2031. upb_status_seterrmsg(status, "out of memory");
  2032. err: {
  2033. /* We need to donate the refs back. */
  2034. upb_strtable_begin(&iter, &addtab);
  2035. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  2036. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
  2037. upb_def_donateref(def, s, ref_donor);
  2038. }
  2039. }
  2040. upb_strtable_uninit(&addtab);
  2041. upb_gfree(add_defs);
  2042. UPB_ASSERT(!upb_ok(status));
  2043. return false;
  2044. }
  2045. bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
  2046. void *ref_donor, upb_status *status) {
  2047. return symtab_add(s, defs, n, ref_donor, NULL, status);
  2048. }
  2049. bool upb_symtab_addfile(upb_symtab *s, upb_filedef *file, upb_status *status) {
  2050. size_t n;
  2051. size_t i;
  2052. upb_def **defs;
  2053. bool ret;
  2054. n = upb_filedef_defcount(file);
  2055. defs = upb_gmalloc(sizeof(*defs) * n);
  2056. if (defs == NULL) {
  2057. upb_status_seterrmsg(status, "Out of memory");
  2058. return false;
  2059. }
  2060. for (i = 0; i < n; i++) {
  2061. defs[i] = upb_filedef_mutabledef(file, i);
  2062. }
  2063. ret = symtab_add(s, defs, n, NULL, upb_filedef_upcast_mutable(file), status);
  2064. upb_gfree(defs);
  2065. return ret;
  2066. }
  2067. /* Iteration. */
  2068. static void advance_to_matching(upb_symtab_iter *iter) {
  2069. if (iter->type == UPB_DEF_ANY)
  2070. return;
  2071. while (!upb_strtable_done(&iter->iter) &&
  2072. iter->type != upb_symtab_iter_def(iter)->type) {
  2073. upb_strtable_next(&iter->iter);
  2074. }
  2075. }
  2076. void upb_symtab_begin(upb_symtab_iter *iter, const upb_symtab *s,
  2077. upb_deftype_t type) {
  2078. upb_strtable_begin(&iter->iter, &s->symtab);
  2079. iter->type = type;
  2080. advance_to_matching(iter);
  2081. }
  2082. void upb_symtab_next(upb_symtab_iter *iter) {
  2083. upb_strtable_next(&iter->iter);
  2084. advance_to_matching(iter);
  2085. }
  2086. bool upb_symtab_done(const upb_symtab_iter *iter) {
  2087. return upb_strtable_done(&iter->iter);
  2088. }
  2089. const upb_def *upb_symtab_iter_def(const upb_symtab_iter *iter) {
  2090. return upb_value_getptr(upb_strtable_iter_value(&iter->iter));
  2091. }
  2092. /*
  2093. ** TODO(haberman): it's unclear whether a lot of the consistency checks should
  2094. ** UPB_ASSERT() or return false.
  2095. */
  2096. #include <string.h>
  2097. static void *upb_calloc(size_t size) {
  2098. void *mem = upb_gmalloc(size);
  2099. if (mem) {
  2100. memset(mem, 0, size);
  2101. }
  2102. return mem;
  2103. }
  2104. /* Defined for the sole purpose of having a unique pointer value for
  2105. * UPB_NO_CLOSURE. */
  2106. char _upb_noclosure;
  2107. static void freehandlers(upb_refcounted *r) {
  2108. upb_handlers *h = (upb_handlers*)r;
  2109. upb_inttable_iter i;
  2110. upb_inttable_begin(&i, &h->cleanup_);
  2111. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  2112. void *val = (void*)upb_inttable_iter_key(&i);
  2113. upb_value func_val = upb_inttable_iter_value(&i);
  2114. upb_handlerfree *func = upb_value_getfptr(func_val);
  2115. func(val);
  2116. }
  2117. upb_inttable_uninit(&h->cleanup_);
  2118. upb_msgdef_unref(h->msg, h);
  2119. upb_gfree(h->sub);
  2120. upb_gfree(h);
  2121. }
  2122. static void visithandlers(const upb_refcounted *r, upb_refcounted_visit *visit,
  2123. void *closure) {
  2124. const upb_handlers *h = (const upb_handlers*)r;
  2125. upb_msg_field_iter i;
  2126. for(upb_msg_field_begin(&i, h->msg);
  2127. !upb_msg_field_done(&i);
  2128. upb_msg_field_next(&i)) {
  2129. upb_fielddef *f = upb_msg_iter_field(&i);
  2130. const upb_handlers *sub;
  2131. if (!upb_fielddef_issubmsg(f)) continue;
  2132. sub = upb_handlers_getsubhandlers(h, f);
  2133. if (sub) visit(r, upb_handlers_upcast(sub), closure);
  2134. }
  2135. }
  2136. static const struct upb_refcounted_vtbl vtbl = {visithandlers, freehandlers};
  2137. typedef struct {
  2138. upb_inttable tab; /* maps upb_msgdef* -> upb_handlers*. */
  2139. upb_handlers_callback *callback;
  2140. const void *closure;
  2141. } dfs_state;
  2142. /* TODO(haberman): discard upb_handlers* objects that do not actually have any
  2143. * handlers set and cannot reach any upb_handlers* object that does. This is
  2144. * slightly tricky to do correctly. */
  2145. static upb_handlers *newformsg(const upb_msgdef *m, const void *owner,
  2146. dfs_state *s) {
  2147. upb_msg_field_iter i;
  2148. upb_handlers *h = upb_handlers_new(m, owner);
  2149. if (!h) return NULL;
  2150. if (!upb_inttable_insertptr(&s->tab, m, upb_value_ptr(h))) goto oom;
  2151. s->callback(s->closure, h);
  2152. /* For each submessage field, get or create a handlers object and set it as
  2153. * the subhandlers. */
  2154. for(upb_msg_field_begin(&i, m);
  2155. !upb_msg_field_done(&i);
  2156. upb_msg_field_next(&i)) {
  2157. upb_fielddef *f = upb_msg_iter_field(&i);
  2158. const upb_msgdef *subdef;
  2159. upb_value subm_ent;
  2160. if (!upb_fielddef_issubmsg(f)) continue;
  2161. subdef = upb_downcast_msgdef(upb_fielddef_subdef(f));
  2162. if (upb_inttable_lookupptr(&s->tab, subdef, &subm_ent)) {
  2163. upb_handlers_setsubhandlers(h, f, upb_value_getptr(subm_ent));
  2164. } else {
  2165. upb_handlers *sub_mh = newformsg(subdef, &sub_mh, s);
  2166. if (!sub_mh) goto oom;
  2167. upb_handlers_setsubhandlers(h, f, sub_mh);
  2168. upb_handlers_unref(sub_mh, &sub_mh);
  2169. }
  2170. }
  2171. return h;
  2172. oom:
  2173. upb_handlers_unref(h, owner);
  2174. return NULL;
  2175. }
  2176. /* Given a selector for a STARTSUBMSG handler, resolves to a pointer to the
  2177. * subhandlers for this submessage field. */
  2178. #define SUBH(h, selector) (h->sub[selector])
  2179. /* The selector for a submessage field is the field index. */
  2180. #define SUBH_F(h, f) SUBH(h, f->index_)
  2181. static int32_t trygetsel(upb_handlers *h, const upb_fielddef *f,
  2182. upb_handlertype_t type) {
  2183. upb_selector_t sel;
  2184. UPB_ASSERT(!upb_handlers_isfrozen(h));
  2185. if (upb_handlers_msgdef(h) != upb_fielddef_containingtype(f)) {
  2186. upb_status_seterrf(
  2187. &h->status_, "type mismatch: field %s does not belong to message %s",
  2188. upb_fielddef_name(f), upb_msgdef_fullname(upb_handlers_msgdef(h)));
  2189. return -1;
  2190. }
  2191. if (!upb_handlers_getselector(f, type, &sel)) {
  2192. upb_status_seterrf(
  2193. &h->status_,
  2194. "type mismatch: cannot register handler type %d for field %s",
  2195. type, upb_fielddef_name(f));
  2196. return -1;
  2197. }
  2198. return sel;
  2199. }
  2200. static upb_selector_t handlers_getsel(upb_handlers *h, const upb_fielddef *f,
  2201. upb_handlertype_t type) {
  2202. int32_t sel = trygetsel(h, f, type);
  2203. UPB_ASSERT(sel >= 0);
  2204. return sel;
  2205. }
  2206. static const void **returntype(upb_handlers *h, const upb_fielddef *f,
  2207. upb_handlertype_t type) {
  2208. return &h->table[handlers_getsel(h, f, type)].attr.return_closure_type_;
  2209. }
  2210. static bool doset(upb_handlers *h, int32_t sel, const upb_fielddef *f,
  2211. upb_handlertype_t type, upb_func *func,
  2212. upb_handlerattr *attr) {
  2213. upb_handlerattr set_attr = UPB_HANDLERATTR_INITIALIZER;
  2214. const void *closure_type;
  2215. const void **context_closure_type;
  2216. UPB_ASSERT(!upb_handlers_isfrozen(h));
  2217. if (sel < 0) {
  2218. upb_status_seterrmsg(&h->status_,
  2219. "incorrect handler type for this field.");
  2220. return false;
  2221. }
  2222. if (h->table[sel].func) {
  2223. upb_status_seterrmsg(&h->status_,
  2224. "cannot change handler once it has been set.");
  2225. return false;
  2226. }
  2227. if (attr) {
  2228. set_attr = *attr;
  2229. }
  2230. /* Check that the given closure type matches the closure type that has been
  2231. * established for this context (if any). */
  2232. closure_type = upb_handlerattr_closuretype(&set_attr);
  2233. if (type == UPB_HANDLER_STRING) {
  2234. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSTR);
  2235. } else if (f && upb_fielddef_isseq(f) &&
  2236. type != UPB_HANDLER_STARTSEQ &&
  2237. type != UPB_HANDLER_ENDSEQ) {
  2238. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSEQ);
  2239. } else {
  2240. context_closure_type = &h->top_closure_type;
  2241. }
  2242. if (closure_type && *context_closure_type &&
  2243. closure_type != *context_closure_type) {
  2244. /* TODO(haberman): better message for debugging. */
  2245. if (f) {
  2246. upb_status_seterrf(&h->status_,
  2247. "closure type does not match for field %s",
  2248. upb_fielddef_name(f));
  2249. } else {
  2250. upb_status_seterrmsg(
  2251. &h->status_, "closure type does not match for message-level handler");
  2252. }
  2253. return false;
  2254. }
  2255. if (closure_type)
  2256. *context_closure_type = closure_type;
  2257. /* If this is a STARTSEQ or STARTSTR handler, check that the returned pointer
  2258. * matches any pre-existing expectations about what type is expected. */
  2259. if (type == UPB_HANDLER_STARTSEQ || type == UPB_HANDLER_STARTSTR) {
  2260. const void *return_type = upb_handlerattr_returnclosuretype(&set_attr);
  2261. const void *table_return_type =
  2262. upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  2263. if (return_type && table_return_type && return_type != table_return_type) {
  2264. upb_status_seterrmsg(&h->status_, "closure return type does not match");
  2265. return false;
  2266. }
  2267. if (table_return_type && !return_type)
  2268. upb_handlerattr_setreturnclosuretype(&set_attr, table_return_type);
  2269. }
  2270. h->table[sel].func = (upb_func*)func;
  2271. h->table[sel].attr = set_attr;
  2272. return true;
  2273. }
  2274. /* Returns the effective closure type for this handler (which will propagate
  2275. * from outer frames if this frame has no START* handler). Not implemented for
  2276. * UPB_HANDLER_STRING at the moment since this is not needed. Returns NULL is
  2277. * the effective closure type is unspecified (either no handler was registered
  2278. * to specify it or the handler that was registered did not specify the closure
  2279. * type). */
  2280. const void *effective_closure_type(upb_handlers *h, const upb_fielddef *f,
  2281. upb_handlertype_t type) {
  2282. const void *ret;
  2283. upb_selector_t sel;
  2284. UPB_ASSERT(type != UPB_HANDLER_STRING);
  2285. ret = h->top_closure_type;
  2286. if (upb_fielddef_isseq(f) &&
  2287. type != UPB_HANDLER_STARTSEQ &&
  2288. type != UPB_HANDLER_ENDSEQ &&
  2289. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)].func) {
  2290. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  2291. }
  2292. if (type == UPB_HANDLER_STRING &&
  2293. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSTR)].func) {
  2294. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  2295. }
  2296. /* The effective type of the submessage; not used yet.
  2297. * if (type == SUBMESSAGE &&
  2298. * h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)].func) {
  2299. * ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  2300. * } */
  2301. return ret;
  2302. }
  2303. /* Checks whether the START* handler specified by f & type is missing even
  2304. * though it is required to convert the established type of an outer frame
  2305. * ("closure_type") into the established type of an inner frame (represented in
  2306. * the return closure type of this handler's attr. */
  2307. bool checkstart(upb_handlers *h, const upb_fielddef *f, upb_handlertype_t type,
  2308. upb_status *status) {
  2309. const void *closure_type;
  2310. const upb_handlerattr *attr;
  2311. const void *return_closure_type;
  2312. upb_selector_t sel = handlers_getsel(h, f, type);
  2313. if (h->table[sel].func) return true;
  2314. closure_type = effective_closure_type(h, f, type);
  2315. attr = &h->table[sel].attr;
  2316. return_closure_type = upb_handlerattr_returnclosuretype(attr);
  2317. if (closure_type && return_closure_type &&
  2318. closure_type != return_closure_type) {
  2319. upb_status_seterrf(status,
  2320. "expected start handler to return sub type for field %f",
  2321. upb_fielddef_name(f));
  2322. return false;
  2323. }
  2324. return true;
  2325. }
  2326. /* Public interface ***********************************************************/
  2327. upb_handlers *upb_handlers_new(const upb_msgdef *md, const void *owner) {
  2328. int extra;
  2329. upb_handlers *h;
  2330. UPB_ASSERT(upb_msgdef_isfrozen(md));
  2331. extra = sizeof(upb_handlers_tabent) * (md->selector_count - 1);
  2332. h = upb_calloc(sizeof(*h) + extra);
  2333. if (!h) return NULL;
  2334. h->msg = md;
  2335. upb_msgdef_ref(h->msg, h);
  2336. upb_status_clear(&h->status_);
  2337. if (md->submsg_field_count > 0) {
  2338. h->sub = upb_calloc(md->submsg_field_count * sizeof(*h->sub));
  2339. if (!h->sub) goto oom;
  2340. } else {
  2341. h->sub = 0;
  2342. }
  2343. if (!upb_refcounted_init(upb_handlers_upcast_mutable(h), &vtbl, owner))
  2344. goto oom;
  2345. if (!upb_inttable_init(&h->cleanup_, UPB_CTYPE_FPTR)) goto oom;
  2346. /* calloc() above initialized all handlers to NULL. */
  2347. return h;
  2348. oom:
  2349. freehandlers(upb_handlers_upcast_mutable(h));
  2350. return NULL;
  2351. }
  2352. const upb_handlers *upb_handlers_newfrozen(const upb_msgdef *m,
  2353. const void *owner,
  2354. upb_handlers_callback *callback,
  2355. const void *closure) {
  2356. dfs_state state;
  2357. upb_handlers *ret;
  2358. bool ok;
  2359. upb_refcounted *r;
  2360. state.callback = callback;
  2361. state.closure = closure;
  2362. if (!upb_inttable_init(&state.tab, UPB_CTYPE_PTR)) return NULL;
  2363. ret = newformsg(m, owner, &state);
  2364. upb_inttable_uninit(&state.tab);
  2365. if (!ret) return NULL;
  2366. r = upb_handlers_upcast_mutable(ret);
  2367. ok = upb_refcounted_freeze(&r, 1, NULL, UPB_MAX_HANDLER_DEPTH);
  2368. UPB_ASSERT(ok);
  2369. return ret;
  2370. }
  2371. const upb_status *upb_handlers_status(upb_handlers *h) {
  2372. UPB_ASSERT(!upb_handlers_isfrozen(h));
  2373. return &h->status_;
  2374. }
  2375. void upb_handlers_clearerr(upb_handlers *h) {
  2376. UPB_ASSERT(!upb_handlers_isfrozen(h));
  2377. upb_status_clear(&h->status_);
  2378. }
  2379. #define SETTER(name, handlerctype, handlertype) \
  2380. bool upb_handlers_set ## name(upb_handlers *h, const upb_fielddef *f, \
  2381. handlerctype func, upb_handlerattr *attr) { \
  2382. int32_t sel = trygetsel(h, f, handlertype); \
  2383. return doset(h, sel, f, handlertype, (upb_func*)func, attr); \
  2384. }
  2385. SETTER(int32, upb_int32_handlerfunc*, UPB_HANDLER_INT32)
  2386. SETTER(int64, upb_int64_handlerfunc*, UPB_HANDLER_INT64)
  2387. SETTER(uint32, upb_uint32_handlerfunc*, UPB_HANDLER_UINT32)
  2388. SETTER(uint64, upb_uint64_handlerfunc*, UPB_HANDLER_UINT64)
  2389. SETTER(float, upb_float_handlerfunc*, UPB_HANDLER_FLOAT)
  2390. SETTER(double, upb_double_handlerfunc*, UPB_HANDLER_DOUBLE)
  2391. SETTER(bool, upb_bool_handlerfunc*, UPB_HANDLER_BOOL)
  2392. SETTER(startstr, upb_startstr_handlerfunc*, UPB_HANDLER_STARTSTR)
  2393. SETTER(string, upb_string_handlerfunc*, UPB_HANDLER_STRING)
  2394. SETTER(endstr, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSTR)
  2395. SETTER(startseq, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSEQ)
  2396. SETTER(startsubmsg, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSUBMSG)
  2397. SETTER(endsubmsg, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSUBMSG)
  2398. SETTER(endseq, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSEQ)
  2399. #undef SETTER
  2400. bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
  2401. upb_handlerattr *attr) {
  2402. return doset(h, UPB_STARTMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  2403. (upb_func *)func, attr);
  2404. }
  2405. bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func,
  2406. upb_handlerattr *attr) {
  2407. UPB_ASSERT(!upb_handlers_isfrozen(h));
  2408. return doset(h, UPB_ENDMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  2409. (upb_func *)func, attr);
  2410. }
  2411. bool upb_handlers_setsubhandlers(upb_handlers *h, const upb_fielddef *f,
  2412. const upb_handlers *sub) {
  2413. UPB_ASSERT(sub);
  2414. UPB_ASSERT(!upb_handlers_isfrozen(h));
  2415. UPB_ASSERT(upb_fielddef_issubmsg(f));
  2416. if (SUBH_F(h, f)) return false; /* Can't reset. */
  2417. if (upb_msgdef_upcast(upb_handlers_msgdef(sub)) != upb_fielddef_subdef(f)) {
  2418. return false;
  2419. }
  2420. SUBH_F(h, f) = sub;
  2421. upb_ref2(sub, h);
  2422. return true;
  2423. }
  2424. const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h,
  2425. const upb_fielddef *f) {
  2426. UPB_ASSERT(upb_fielddef_issubmsg(f));
  2427. return SUBH_F(h, f);
  2428. }
  2429. bool upb_handlers_getattr(const upb_handlers *h, upb_selector_t sel,
  2430. upb_handlerattr *attr) {
  2431. if (!upb_handlers_gethandler(h, sel))
  2432. return false;
  2433. *attr = h->table[sel].attr;
  2434. return true;
  2435. }
  2436. const upb_handlers *upb_handlers_getsubhandlers_sel(const upb_handlers *h,
  2437. upb_selector_t sel) {
  2438. /* STARTSUBMSG selector in sel is the field's selector base. */
  2439. return SUBH(h, sel - UPB_STATIC_SELECTOR_COUNT);
  2440. }
  2441. const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h) { return h->msg; }
  2442. bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *func) {
  2443. bool ok;
  2444. if (upb_inttable_lookupptr(&h->cleanup_, p, NULL)) {
  2445. return false;
  2446. }
  2447. ok = upb_inttable_insertptr(&h->cleanup_, p, upb_value_fptr(func));
  2448. UPB_ASSERT(ok);
  2449. return true;
  2450. }
  2451. /* "Static" methods ***********************************************************/
  2452. bool upb_handlers_freeze(upb_handlers *const*handlers, int n, upb_status *s) {
  2453. /* TODO: verify we have a transitive closure. */
  2454. int i;
  2455. for (i = 0; i < n; i++) {
  2456. upb_msg_field_iter j;
  2457. upb_handlers *h = handlers[i];
  2458. if (!upb_ok(&h->status_)) {
  2459. upb_status_seterrf(s, "handlers for message %s had error status: %s",
  2460. upb_msgdef_fullname(upb_handlers_msgdef(h)),
  2461. upb_status_errmsg(&h->status_));
  2462. return false;
  2463. }
  2464. /* Check that there are no closure mismatches due to missing Start* handlers
  2465. * or subhandlers with different type-level types. */
  2466. for(upb_msg_field_begin(&j, h->msg);
  2467. !upb_msg_field_done(&j);
  2468. upb_msg_field_next(&j)) {
  2469. const upb_fielddef *f = upb_msg_iter_field(&j);
  2470. if (upb_fielddef_isseq(f)) {
  2471. if (!checkstart(h, f, UPB_HANDLER_STARTSEQ, s))
  2472. return false;
  2473. }
  2474. if (upb_fielddef_isstring(f)) {
  2475. if (!checkstart(h, f, UPB_HANDLER_STARTSTR, s))
  2476. return false;
  2477. }
  2478. if (upb_fielddef_issubmsg(f)) {
  2479. bool hashandler = false;
  2480. if (upb_handlers_gethandler(
  2481. h, handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)) ||
  2482. upb_handlers_gethandler(
  2483. h, handlers_getsel(h, f, UPB_HANDLER_ENDSUBMSG))) {
  2484. hashandler = true;
  2485. }
  2486. if (upb_fielddef_isseq(f) &&
  2487. (upb_handlers_gethandler(
  2488. h, handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)) ||
  2489. upb_handlers_gethandler(
  2490. h, handlers_getsel(h, f, UPB_HANDLER_ENDSEQ)))) {
  2491. hashandler = true;
  2492. }
  2493. if (hashandler && !upb_handlers_getsubhandlers(h, f)) {
  2494. /* For now we add an empty subhandlers in this case. It makes the
  2495. * decoder code generator simpler, because it only has to handle two
  2496. * cases (submessage has handlers or not) as opposed to three
  2497. * (submessage has handlers in enclosing message but no subhandlers).
  2498. *
  2499. * This makes parsing less efficient in the case that we want to
  2500. * notice a submessage but skip its contents (like if we're testing
  2501. * for submessage presence or counting the number of repeated
  2502. * submessages). In this case we will end up parsing the submessage
  2503. * field by field and throwing away the results for each, instead of
  2504. * skipping the whole delimited thing at once. If this is an issue we
  2505. * can revisit it, but do remember that this only arises when you have
  2506. * handlers (startseq/startsubmsg/endsubmsg/endseq) set for the
  2507. * submessage but no subhandlers. The uses cases for this are
  2508. * limited. */
  2509. upb_handlers *sub = upb_handlers_new(upb_fielddef_msgsubdef(f), &sub);
  2510. upb_handlers_setsubhandlers(h, f, sub);
  2511. upb_handlers_unref(sub, &sub);
  2512. }
  2513. /* TODO(haberman): check type of submessage.
  2514. * This is slightly tricky; also consider whether we should check that
  2515. * they match at setsubhandlers time. */
  2516. }
  2517. }
  2518. }
  2519. if (!upb_refcounted_freeze((upb_refcounted*const*)handlers, n, s,
  2520. UPB_MAX_HANDLER_DEPTH)) {
  2521. return false;
  2522. }
  2523. return true;
  2524. }
  2525. upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f) {
  2526. switch (upb_fielddef_type(f)) {
  2527. case UPB_TYPE_INT32:
  2528. case UPB_TYPE_ENUM: return UPB_HANDLER_INT32;
  2529. case UPB_TYPE_INT64: return UPB_HANDLER_INT64;
  2530. case UPB_TYPE_UINT32: return UPB_HANDLER_UINT32;
  2531. case UPB_TYPE_UINT64: return UPB_HANDLER_UINT64;
  2532. case UPB_TYPE_FLOAT: return UPB_HANDLER_FLOAT;
  2533. case UPB_TYPE_DOUBLE: return UPB_HANDLER_DOUBLE;
  2534. case UPB_TYPE_BOOL: return UPB_HANDLER_BOOL;
  2535. default: UPB_ASSERT(false); return -1; /* Invalid input. */
  2536. }
  2537. }
  2538. bool upb_handlers_getselector(const upb_fielddef *f, upb_handlertype_t type,
  2539. upb_selector_t *s) {
  2540. switch (type) {
  2541. case UPB_HANDLER_INT32:
  2542. case UPB_HANDLER_INT64:
  2543. case UPB_HANDLER_UINT32:
  2544. case UPB_HANDLER_UINT64:
  2545. case UPB_HANDLER_FLOAT:
  2546. case UPB_HANDLER_DOUBLE:
  2547. case UPB_HANDLER_BOOL:
  2548. if (!upb_fielddef_isprimitive(f) ||
  2549. upb_handlers_getprimitivehandlertype(f) != type)
  2550. return false;
  2551. *s = f->selector_base;
  2552. break;
  2553. case UPB_HANDLER_STRING:
  2554. if (upb_fielddef_isstring(f)) {
  2555. *s = f->selector_base;
  2556. } else if (upb_fielddef_lazy(f)) {
  2557. *s = f->selector_base + 3;
  2558. } else {
  2559. return false;
  2560. }
  2561. break;
  2562. case UPB_HANDLER_STARTSTR:
  2563. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  2564. *s = f->selector_base + 1;
  2565. } else {
  2566. return false;
  2567. }
  2568. break;
  2569. case UPB_HANDLER_ENDSTR:
  2570. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  2571. *s = f->selector_base + 2;
  2572. } else {
  2573. return false;
  2574. }
  2575. break;
  2576. case UPB_HANDLER_STARTSEQ:
  2577. if (!upb_fielddef_isseq(f)) return false;
  2578. *s = f->selector_base - 2;
  2579. break;
  2580. case UPB_HANDLER_ENDSEQ:
  2581. if (!upb_fielddef_isseq(f)) return false;
  2582. *s = f->selector_base - 1;
  2583. break;
  2584. case UPB_HANDLER_STARTSUBMSG:
  2585. if (!upb_fielddef_issubmsg(f)) return false;
  2586. /* Selectors for STARTSUBMSG are at the beginning of the table so that the
  2587. * selector can also be used as an index into the "sub" array of
  2588. * subhandlers. The indexes for the two into these two tables are the
  2589. * same, except that in the handler table the static selectors come first. */
  2590. *s = f->index_ + UPB_STATIC_SELECTOR_COUNT;
  2591. break;
  2592. case UPB_HANDLER_ENDSUBMSG:
  2593. if (!upb_fielddef_issubmsg(f)) return false;
  2594. *s = f->selector_base;
  2595. break;
  2596. }
  2597. UPB_ASSERT((size_t)*s < upb_fielddef_containingtype(f)->selector_count);
  2598. return true;
  2599. }
  2600. uint32_t upb_handlers_selectorbaseoffset(const upb_fielddef *f) {
  2601. return upb_fielddef_isseq(f) ? 2 : 0;
  2602. }
  2603. uint32_t upb_handlers_selectorcount(const upb_fielddef *f) {
  2604. uint32_t ret = 1;
  2605. if (upb_fielddef_isseq(f)) ret += 2; /* STARTSEQ/ENDSEQ */
  2606. if (upb_fielddef_isstring(f)) ret += 2; /* [STRING]/STARTSTR/ENDSTR */
  2607. if (upb_fielddef_issubmsg(f)) {
  2608. /* ENDSUBMSG (STARTSUBMSG is at table beginning) */
  2609. ret += 0;
  2610. if (upb_fielddef_lazy(f)) {
  2611. /* STARTSTR/ENDSTR/STRING (for lazy) */
  2612. ret += 3;
  2613. }
  2614. }
  2615. return ret;
  2616. }
  2617. /* upb_handlerattr ************************************************************/
  2618. void upb_handlerattr_init(upb_handlerattr *attr) {
  2619. upb_handlerattr from = UPB_HANDLERATTR_INITIALIZER;
  2620. memcpy(attr, &from, sizeof(*attr));
  2621. }
  2622. void upb_handlerattr_uninit(upb_handlerattr *attr) {
  2623. UPB_UNUSED(attr);
  2624. }
  2625. bool upb_handlerattr_sethandlerdata(upb_handlerattr *attr, const void *hd) {
  2626. attr->handler_data_ = hd;
  2627. return true;
  2628. }
  2629. bool upb_handlerattr_setclosuretype(upb_handlerattr *attr, const void *type) {
  2630. attr->closure_type_ = type;
  2631. return true;
  2632. }
  2633. const void *upb_handlerattr_closuretype(const upb_handlerattr *attr) {
  2634. return attr->closure_type_;
  2635. }
  2636. bool upb_handlerattr_setreturnclosuretype(upb_handlerattr *attr,
  2637. const void *type) {
  2638. attr->return_closure_type_ = type;
  2639. return true;
  2640. }
  2641. const void *upb_handlerattr_returnclosuretype(const upb_handlerattr *attr) {
  2642. return attr->return_closure_type_;
  2643. }
  2644. bool upb_handlerattr_setalwaysok(upb_handlerattr *attr, bool alwaysok) {
  2645. attr->alwaysok_ = alwaysok;
  2646. return true;
  2647. }
  2648. bool upb_handlerattr_alwaysok(const upb_handlerattr *attr) {
  2649. return attr->alwaysok_;
  2650. }
  2651. /* upb_bufhandle **************************************************************/
  2652. size_t upb_bufhandle_objofs(const upb_bufhandle *h) {
  2653. return h->objofs_;
  2654. }
  2655. /* upb_byteshandler ***********************************************************/
  2656. void upb_byteshandler_init(upb_byteshandler* h) {
  2657. memset(h, 0, sizeof(*h));
  2658. }
  2659. /* For when we support handlerfree callbacks. */
  2660. void upb_byteshandler_uninit(upb_byteshandler* h) {
  2661. UPB_UNUSED(h);
  2662. }
  2663. bool upb_byteshandler_setstartstr(upb_byteshandler *h,
  2664. upb_startstr_handlerfunc *func, void *d) {
  2665. h->table[UPB_STARTSTR_SELECTOR].func = (upb_func*)func;
  2666. h->table[UPB_STARTSTR_SELECTOR].attr.handler_data_ = d;
  2667. return true;
  2668. }
  2669. bool upb_byteshandler_setstring(upb_byteshandler *h,
  2670. upb_string_handlerfunc *func, void *d) {
  2671. h->table[UPB_STRING_SELECTOR].func = (upb_func*)func;
  2672. h->table[UPB_STRING_SELECTOR].attr.handler_data_ = d;
  2673. return true;
  2674. }
  2675. bool upb_byteshandler_setendstr(upb_byteshandler *h,
  2676. upb_endfield_handlerfunc *func, void *d) {
  2677. h->table[UPB_ENDSTR_SELECTOR].func = (upb_func*)func;
  2678. h->table[UPB_ENDSTR_SELECTOR].attr.handler_data_ = d;
  2679. return true;
  2680. }
  2681. static bool is_power_of_two(size_t val) {
  2682. return (val & (val - 1)) == 0;
  2683. }
  2684. /* Align up to the given power of 2. */
  2685. static size_t align_up(size_t val, size_t align) {
  2686. UPB_ASSERT(is_power_of_two(align));
  2687. return (val + align - 1) & ~(align - 1);
  2688. }
  2689. static size_t div_round_up(size_t n, size_t d) {
  2690. return (n + d - 1) / d;
  2691. }
  2692. bool upb_fieldtype_mapkeyok(upb_fieldtype_t type) {
  2693. return type == UPB_TYPE_BOOL || type == UPB_TYPE_INT32 ||
  2694. type == UPB_TYPE_UINT32 || type == UPB_TYPE_INT64 ||
  2695. type == UPB_TYPE_UINT64 || type == UPB_TYPE_STRING;
  2696. }
  2697. void *upb_array_pack(const upb_array *arr, void *p, size_t *ofs, size_t size);
  2698. void *upb_map_pack(const upb_map *map, void *p, size_t *ofs, size_t size);
  2699. #define CHARPTR_AT(msg, ofs) ((char*)msg + ofs)
  2700. #define ENCODE_MAX_NESTING 64
  2701. #define CHECK_TRUE(x) if (!(x)) { return false; }
  2702. /** upb_msgval ****************************************************************/
  2703. #define upb_alignof(t) offsetof(struct { char c; t x; }, x)
  2704. /* These functions will generate real memcpy() calls on ARM sadly, because
  2705. * the compiler assumes they might not be aligned. */
  2706. static upb_msgval upb_msgval_read(const void *p, size_t ofs,
  2707. uint8_t size) {
  2708. upb_msgval val;
  2709. p = (char*)p + ofs;
  2710. memcpy(&val, p, size);
  2711. return val;
  2712. }
  2713. static void upb_msgval_write(void *p, size_t ofs, upb_msgval val,
  2714. uint8_t size) {
  2715. p = (char*)p + ofs;
  2716. memcpy(p, &val, size);
  2717. }
  2718. static size_t upb_msgval_sizeof(upb_fieldtype_t type) {
  2719. switch (type) {
  2720. case UPB_TYPE_DOUBLE:
  2721. case UPB_TYPE_INT64:
  2722. case UPB_TYPE_UINT64:
  2723. return 8;
  2724. case UPB_TYPE_ENUM:
  2725. case UPB_TYPE_INT32:
  2726. case UPB_TYPE_UINT32:
  2727. case UPB_TYPE_FLOAT:
  2728. return 4;
  2729. case UPB_TYPE_BOOL:
  2730. return 1;
  2731. case UPB_TYPE_BYTES:
  2732. case UPB_TYPE_MESSAGE:
  2733. return sizeof(void*);
  2734. case UPB_TYPE_STRING:
  2735. return sizeof(char*) + sizeof(size_t);
  2736. }
  2737. UPB_UNREACHABLE();
  2738. }
  2739. static uint8_t upb_msg_fieldsize(const upb_fielddef *f) {
  2740. if (upb_fielddef_isseq(f)) {
  2741. return sizeof(void*);
  2742. } else {
  2743. return upb_msgval_sizeof(upb_fielddef_type(f));
  2744. }
  2745. }
  2746. /* TODO(haberman): this is broken right now because upb_msgval can contain
  2747. * a char* / size_t pair, which is too big for a upb_value. To fix this
  2748. * we'll probably need to dynamically allocate a upb_msgval and store a
  2749. * pointer to that in the tables for extensions/maps. */
  2750. static upb_value upb_toval(upb_msgval val) {
  2751. upb_value ret;
  2752. UPB_UNUSED(val);
  2753. memset(&ret, 0, sizeof(upb_value)); /* XXX */
  2754. return ret;
  2755. }
  2756. static upb_msgval upb_msgval_fromval(upb_value val) {
  2757. upb_msgval ret;
  2758. UPB_UNUSED(val);
  2759. memset(&ret, 0, sizeof(upb_msgval)); /* XXX */
  2760. return ret;
  2761. }
  2762. static upb_ctype_t upb_fieldtotabtype(upb_fieldtype_t type) {
  2763. switch (type) {
  2764. case UPB_TYPE_FLOAT: return UPB_CTYPE_FLOAT;
  2765. case UPB_TYPE_DOUBLE: return UPB_CTYPE_DOUBLE;
  2766. case UPB_TYPE_BOOL: return UPB_CTYPE_BOOL;
  2767. case UPB_TYPE_BYTES:
  2768. case UPB_TYPE_MESSAGE:
  2769. case UPB_TYPE_STRING: return UPB_CTYPE_CONSTPTR;
  2770. case UPB_TYPE_ENUM:
  2771. case UPB_TYPE_INT32: return UPB_CTYPE_INT32;
  2772. case UPB_TYPE_UINT32: return UPB_CTYPE_UINT32;
  2773. case UPB_TYPE_INT64: return UPB_CTYPE_INT64;
  2774. case UPB_TYPE_UINT64: return UPB_CTYPE_UINT64;
  2775. default: UPB_ASSERT(false); return 0;
  2776. }
  2777. }
  2778. static upb_msgval upb_msgval_fromdefault(const upb_fielddef *f) {
  2779. /* TODO(haberman): improve/optimize this (maybe use upb_msgval in fielddef) */
  2780. switch (upb_fielddef_type(f)) {
  2781. case UPB_TYPE_FLOAT:
  2782. return upb_msgval_float(upb_fielddef_defaultfloat(f));
  2783. case UPB_TYPE_DOUBLE:
  2784. return upb_msgval_double(upb_fielddef_defaultdouble(f));
  2785. case UPB_TYPE_BOOL:
  2786. return upb_msgval_bool(upb_fielddef_defaultbool(f));
  2787. case UPB_TYPE_STRING:
  2788. case UPB_TYPE_BYTES: {
  2789. size_t len;
  2790. const char *ptr = upb_fielddef_defaultstr(f, &len);
  2791. return upb_msgval_str(ptr, len);
  2792. }
  2793. case UPB_TYPE_MESSAGE:
  2794. return upb_msgval_msg(NULL);
  2795. case UPB_TYPE_ENUM:
  2796. case UPB_TYPE_INT32:
  2797. return upb_msgval_int32(upb_fielddef_defaultint32(f));
  2798. case UPB_TYPE_UINT32:
  2799. return upb_msgval_uint32(upb_fielddef_defaultuint32(f));
  2800. case UPB_TYPE_INT64:
  2801. return upb_msgval_int64(upb_fielddef_defaultint64(f));
  2802. case UPB_TYPE_UINT64:
  2803. return upb_msgval_uint64(upb_fielddef_defaultuint64(f));
  2804. default:
  2805. UPB_ASSERT(false);
  2806. return upb_msgval_msg(NULL);
  2807. }
  2808. }
  2809. /** upb_msglayout *************************************************************/
  2810. struct upb_msglayout {
  2811. upb_msgfactory *factory;
  2812. const upb_msgdef *msgdef;
  2813. size_t size;
  2814. size_t extdict_offset;
  2815. void *default_msg;
  2816. uint32_t *field_offsets;
  2817. uint32_t *case_offsets;
  2818. uint32_t *hasbits;
  2819. bool has_extdict;
  2820. uint8_t align;
  2821. };
  2822. static void upb_msg_checkfield(const upb_msglayout *l, const upb_fielddef *f) {
  2823. UPB_ASSERT(l->msgdef == upb_fielddef_containingtype(f));
  2824. }
  2825. static void upb_msglayout_free(upb_msglayout *l) {
  2826. upb_gfree(l->default_msg);
  2827. upb_gfree(l);
  2828. }
  2829. const upb_msgdef *upb_msglayout_msgdef(const upb_msglayout *l) {
  2830. return l->msgdef;
  2831. }
  2832. static size_t upb_msglayout_place(upb_msglayout *l, size_t size) {
  2833. size_t ret;
  2834. l->size = align_up(l->size, size);
  2835. l->align = align_up(l->align, size);
  2836. ret = l->size;
  2837. l->size += size;
  2838. return ret;
  2839. }
  2840. static uint32_t upb_msglayout_offset(const upb_msglayout *l,
  2841. const upb_fielddef *f) {
  2842. return l->field_offsets[upb_fielddef_index(f)];
  2843. }
  2844. static uint32_t upb_msglayout_hasbit(const upb_msglayout *l,
  2845. const upb_fielddef *f) {
  2846. return l->hasbits[upb_fielddef_index(f)];
  2847. }
  2848. static bool upb_msglayout_initdefault(upb_msglayout *l) {
  2849. const upb_msgdef *m = l->msgdef;
  2850. upb_msg_field_iter it;
  2851. if (upb_msgdef_syntax(m) == UPB_SYNTAX_PROTO2 && l->size) {
  2852. /* Allocate default message and set default values in it. */
  2853. l->default_msg = upb_gmalloc(l->size);
  2854. if (!l->default_msg) {
  2855. return false;
  2856. }
  2857. memset(l->default_msg, 0, l->size);
  2858. for (upb_msg_field_begin(&it, m); !upb_msg_field_done(&it);
  2859. upb_msg_field_next(&it)) {
  2860. const upb_fielddef* f = upb_msg_iter_field(&it);
  2861. if (upb_fielddef_containingoneof(f)) {
  2862. continue;
  2863. }
  2864. if (!upb_fielddef_isstring(f) &&
  2865. !upb_fielddef_issubmsg(f) &&
  2866. !upb_fielddef_isseq(f)) {
  2867. upb_msg_set(l->default_msg, f, upb_msgval_fromdefault(f), l);
  2868. }
  2869. }
  2870. }
  2871. return true;
  2872. }
  2873. static upb_msglayout *upb_msglayout_new(const upb_msgdef *m) {
  2874. upb_msg_field_iter it;
  2875. upb_msg_oneof_iter oit;
  2876. upb_msglayout *l;
  2877. size_t hasbit;
  2878. size_t array_size = upb_msgdef_numfields(m) + upb_msgdef_numoneofs(m);
  2879. if (upb_msgdef_syntax(m) == UPB_SYNTAX_PROTO2) {
  2880. array_size += upb_msgdef_numfields(m); /* hasbits. */
  2881. }
  2882. l = upb_gmalloc(sizeof(*l) + (sizeof(uint32_t) * array_size));
  2883. if (!l) return NULL;
  2884. memset(l, 0, sizeof(*l));
  2885. l->msgdef = m;
  2886. l->align = 1;
  2887. l->field_offsets = (uint32_t*)CHARPTR_AT(l, sizeof(*l));
  2888. l->case_offsets = l->field_offsets + upb_msgdef_numfields(m);
  2889. l->hasbits = l->case_offsets + upb_msgdef_numoneofs(m);
  2890. /* Allocate data offsets in three stages:
  2891. *
  2892. * 1. hasbits.
  2893. * 2. regular fields.
  2894. * 3. oneof fields.
  2895. *
  2896. * OPT: There is a lot of room for optimization here to minimize the size.
  2897. */
  2898. /* Allocate hasbits. Start at sizeof(void*) for upb_alloc*. */
  2899. for (upb_msg_field_begin(&it, m), hasbit = sizeof(void*) * 8;
  2900. !upb_msg_field_done(&it);
  2901. upb_msg_field_next(&it)) {
  2902. const upb_fielddef* f = upb_msg_iter_field(&it);
  2903. if (upb_fielddef_haspresence(f) && !upb_fielddef_containingoneof(f)) {
  2904. l->hasbits[upb_fielddef_index(f)] = hasbit++;
  2905. }
  2906. }
  2907. /* Account for space used by hasbits. */
  2908. l->size = div_round_up(hasbit, 8);
  2909. /* Allocate non-oneof fields. */
  2910. for (upb_msg_field_begin(&it, m); !upb_msg_field_done(&it);
  2911. upb_msg_field_next(&it)) {
  2912. const upb_fielddef* f = upb_msg_iter_field(&it);
  2913. size_t field_size = upb_msg_fieldsize(f);
  2914. size_t index = upb_fielddef_index(f);
  2915. if (upb_fielddef_containingoneof(f)) {
  2916. /* Oneofs are handled separately below. */
  2917. continue;
  2918. }
  2919. l->field_offsets[index] = upb_msglayout_place(l, field_size);
  2920. }
  2921. /* Allocate oneof fields. Each oneof field consists of a uint32 for the case
  2922. * and space for the actual data. */
  2923. for (upb_msg_oneof_begin(&oit, m); !upb_msg_oneof_done(&oit);
  2924. upb_msg_oneof_next(&oit)) {
  2925. const upb_oneofdef* oneof = upb_msg_iter_oneof(&oit);
  2926. upb_oneof_iter fit;
  2927. size_t case_size = sizeof(uint32_t); /* Could potentially optimize this. */
  2928. size_t field_size = 0;
  2929. size_t case_offset;
  2930. size_t val_offset;
  2931. /* Calculate field size: the max of all field sizes. */
  2932. for (upb_oneof_begin(&fit, oneof);
  2933. !upb_oneof_done(&fit);
  2934. upb_oneof_next(&fit)) {
  2935. const upb_fielddef* f = upb_oneof_iter_field(&fit);
  2936. field_size = UPB_MAX(field_size, upb_msg_fieldsize(f));
  2937. }
  2938. /* Align and allocate case offset. */
  2939. case_offset = upb_msglayout_place(l, case_size);
  2940. val_offset = upb_msglayout_place(l, field_size);
  2941. l->case_offsets[upb_oneofdef_index(oneof)] = case_offset;
  2942. /* Assign all fields in the oneof this same offset. */
  2943. for (upb_oneof_begin(&fit, oneof); !upb_oneof_done(&fit);
  2944. upb_oneof_next(&fit)) {
  2945. const upb_fielddef* f = upb_oneof_iter_field(&fit);
  2946. l->field_offsets[upb_fielddef_index(f)] = val_offset;
  2947. }
  2948. }
  2949. /* Size of the entire structure should be a multiple of its greatest
  2950. * alignment. */
  2951. l->size = align_up(l->size, l->align);
  2952. if (upb_msglayout_initdefault(l)) {
  2953. return l;
  2954. } else {
  2955. upb_msglayout_free(l);
  2956. return NULL;
  2957. }
  2958. }
  2959. upb_msgfactory *upb_msglayout_factory(const upb_msglayout *layout) {
  2960. return layout->factory;
  2961. }
  2962. /** upb_msgfactory ************************************************************/
  2963. struct upb_msgfactory {
  2964. const upb_symtab *symtab; /* We own a ref. */
  2965. upb_inttable layouts;
  2966. upb_inttable mergehandlers;
  2967. };
  2968. upb_msgfactory *upb_msgfactory_new(const upb_symtab *symtab) {
  2969. upb_msgfactory *ret = upb_gmalloc(sizeof(*ret));
  2970. ret->symtab = symtab;
  2971. upb_inttable_init(&ret->layouts, UPB_CTYPE_PTR);
  2972. upb_inttable_init(&ret->mergehandlers, UPB_CTYPE_CONSTPTR);
  2973. return ret;
  2974. }
  2975. void upb_msgfactory_free(upb_msgfactory *f) {
  2976. upb_inttable_iter i;
  2977. upb_inttable_begin(&i, &f->layouts);
  2978. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  2979. upb_msglayout *l = upb_value_getptr(upb_inttable_iter_value(&i));
  2980. upb_msglayout_free(l);
  2981. }
  2982. upb_inttable_begin(&i, &f->mergehandlers);
  2983. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  2984. const upb_handlers *h = upb_value_getconstptr(upb_inttable_iter_value(&i));
  2985. upb_handlers_unref(h, f);
  2986. }
  2987. upb_inttable_uninit(&f->layouts);
  2988. upb_inttable_uninit(&f->mergehandlers);
  2989. upb_gfree(f);
  2990. }
  2991. const upb_symtab *upb_msgfactory_symtab(const upb_msgfactory *f) {
  2992. return f->symtab;
  2993. }
  2994. const upb_msglayout *upb_msgfactory_getlayout(upb_msgfactory *f,
  2995. const upb_msgdef *m) {
  2996. upb_value v;
  2997. UPB_ASSERT(upb_symtab_lookupmsg(f->symtab, upb_msgdef_fullname(m)) == m);
  2998. UPB_ASSERT(!upb_msgdef_mapentry(m));
  2999. if (upb_inttable_lookupptr(&f->layouts, m, &v)) {
  3000. UPB_ASSERT(upb_value_getptr(v));
  3001. return upb_value_getptr(v);
  3002. } else {
  3003. upb_msgfactory *mutable_f = (void*)f;
  3004. upb_msglayout *l = upb_msglayout_new(m);
  3005. upb_inttable_insertptr(&mutable_f->layouts, m, upb_value_ptr(l));
  3006. UPB_ASSERT(l);
  3007. l->factory = f;
  3008. return l;
  3009. }
  3010. }
  3011. /* Our handlers that we don't expose externally. */
  3012. void *upb_msg_startstr(void *msg, const void *hd, size_t size_hint) {
  3013. uint32_t ofs = (uintptr_t)hd;
  3014. /* We pass NULL here because we know we can get away with it. */
  3015. upb_alloc *alloc = upb_msg_alloc(msg, NULL);
  3016. upb_msgval val;
  3017. UPB_UNUSED(size_hint);
  3018. val = upb_msgval_read(msg, ofs, upb_msgval_sizeof(UPB_TYPE_STRING));
  3019. upb_free(alloc, (void*)val.str.ptr);
  3020. val.str.ptr = NULL;
  3021. val.str.len = 0;
  3022. upb_msgval_write(msg, ofs, val, upb_msgval_sizeof(UPB_TYPE_STRING));
  3023. return msg;
  3024. }
  3025. size_t upb_msg_str(void *msg, const void *hd, const char *ptr, size_t size,
  3026. const upb_bufhandle *handle) {
  3027. uint32_t ofs = (uintptr_t)hd;
  3028. /* We pass NULL here because we know we can get away with it. */
  3029. upb_alloc *alloc = upb_msg_alloc(msg, NULL);
  3030. upb_msgval val;
  3031. size_t newsize;
  3032. UPB_UNUSED(handle);
  3033. val = upb_msgval_read(msg, ofs, upb_msgval_sizeof(UPB_TYPE_STRING));
  3034. newsize = val.str.len + size;
  3035. val.str.ptr = upb_realloc(alloc, (void*)val.str.ptr, val.str.len, newsize);
  3036. if (!val.str.ptr) {
  3037. return false;
  3038. }
  3039. memcpy((char*)val.str.ptr + val.str.len, ptr, size);
  3040. val.str.len = newsize;
  3041. upb_msgval_write(msg, ofs, val, upb_msgval_sizeof(UPB_TYPE_STRING));
  3042. return size;
  3043. }
  3044. static void callback(const void *closure, upb_handlers *h) {
  3045. upb_msgfactory *factory = (upb_msgfactory*)closure;
  3046. const upb_msgdef *md = upb_handlers_msgdef(h);
  3047. const upb_msglayout* layout = upb_msgfactory_getlayout(factory, md);
  3048. upb_msg_field_iter i;
  3049. UPB_UNUSED(factory);
  3050. for(upb_msg_field_begin(&i, md);
  3051. !upb_msg_field_done(&i);
  3052. upb_msg_field_next(&i)) {
  3053. const upb_fielddef *f = upb_msg_iter_field(&i);
  3054. size_t offset = upb_msglayout_offset(layout, f);
  3055. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  3056. upb_handlerattr_sethandlerdata(&attr, (void*)offset);
  3057. if (upb_fielddef_isseq(f)) {
  3058. } else if (upb_fielddef_isstring(f)) {
  3059. upb_handlers_setstartstr(h, f, upb_msg_startstr, &attr);
  3060. upb_handlers_setstring(h, f, upb_msg_str, &attr);
  3061. } else {
  3062. upb_msg_setscalarhandler(
  3063. h, f, offset, upb_msglayout_hasbit(layout, f));
  3064. }
  3065. }
  3066. }
  3067. const upb_handlers *upb_msgfactory_getmergehandlers(upb_msgfactory *f,
  3068. const upb_msgdef *m) {
  3069. upb_msgfactory *mutable_f = (void*)f;
  3070. /* TODO(haberman): properly cache these. */
  3071. const upb_handlers *ret = upb_handlers_newfrozen(m, f, callback, f);
  3072. upb_inttable_push(&mutable_f->mergehandlers, upb_value_constptr(ret));
  3073. return ret;
  3074. }
  3075. const upb_visitorplan *upb_msgfactory_getvisitorplan(upb_msgfactory *f,
  3076. const upb_handlers *h) {
  3077. const upb_msgdef *md = upb_handlers_msgdef(h);
  3078. return (const upb_visitorplan*)upb_msgfactory_getlayout(f, md);
  3079. }
  3080. /** upb_visitor ***************************************************************/
  3081. struct upb_visitor {
  3082. const upb_msglayout *layout;
  3083. upb_sink *sink;
  3084. };
  3085. static upb_selector_t getsel2(const upb_fielddef *f, upb_handlertype_t type) {
  3086. upb_selector_t ret;
  3087. bool ok = upb_handlers_getselector(f, type, &ret);
  3088. UPB_ASSERT(ok);
  3089. return ret;
  3090. }
  3091. static bool upb_visitor_hasfield(const upb_msg *msg, const upb_fielddef *f,
  3092. const upb_msglayout *layout) {
  3093. if (upb_fielddef_isseq(f)) {
  3094. return upb_msgval_getarr(upb_msg_get(msg, f, layout)) != NULL;
  3095. } else if (upb_msgdef_syntax(upb_fielddef_containingtype(f)) ==
  3096. UPB_SYNTAX_PROTO2) {
  3097. return upb_msg_has(msg, f, layout);
  3098. } else {
  3099. upb_msgval val = upb_msg_get(msg, f, layout);
  3100. switch (upb_fielddef_type(f)) {
  3101. case UPB_TYPE_FLOAT:
  3102. return upb_msgval_getfloat(val) != 0;
  3103. case UPB_TYPE_DOUBLE:
  3104. return upb_msgval_getdouble(val) != 0;
  3105. case UPB_TYPE_BOOL:
  3106. return upb_msgval_getbool(val);
  3107. case UPB_TYPE_ENUM:
  3108. case UPB_TYPE_INT32:
  3109. return upb_msgval_getint32(val) != 0;
  3110. case UPB_TYPE_UINT32:
  3111. return upb_msgval_getuint32(val) != 0;
  3112. case UPB_TYPE_INT64:
  3113. return upb_msgval_getint64(val) != 0;
  3114. case UPB_TYPE_UINT64:
  3115. return upb_msgval_getuint64(val) != 0;
  3116. case UPB_TYPE_STRING:
  3117. case UPB_TYPE_BYTES:
  3118. return upb_msgval_getstr(val) && upb_msgval_getstrlen(val) > 0;
  3119. case UPB_TYPE_MESSAGE:
  3120. return upb_msgval_getmsg(val) != NULL;
  3121. }
  3122. UPB_UNREACHABLE();
  3123. }
  3124. }
  3125. static bool upb_visitor_visitmsg2(const upb_msg *msg,
  3126. const upb_msglayout *layout, upb_sink *sink,
  3127. int depth) {
  3128. const upb_msgdef *md = upb_msglayout_msgdef(layout);
  3129. upb_msg_field_iter i;
  3130. upb_status status;
  3131. upb_sink_startmsg(sink);
  3132. /* Protect against cycles (possible because users may freely reassign message
  3133. * and repeated fields) by imposing a maximum recursion depth. */
  3134. if (depth > ENCODE_MAX_NESTING) {
  3135. return false;
  3136. }
  3137. for (upb_msg_field_begin(&i, md);
  3138. !upb_msg_field_done(&i);
  3139. upb_msg_field_next(&i)) {
  3140. upb_fielddef *f = upb_msg_iter_field(&i);
  3141. upb_msgval val;
  3142. if (!upb_visitor_hasfield(msg, f, layout)) {
  3143. continue;
  3144. }
  3145. val = upb_msg_get(msg, f, layout);
  3146. if (upb_fielddef_isseq(f)) {
  3147. const upb_array *arr = upb_msgval_getarr(val);
  3148. UPB_ASSERT(arr);
  3149. /* TODO: putary(ary, f, sink, depth);*/
  3150. } else if (upb_fielddef_issubmsg(f)) {
  3151. const upb_map *map = upb_msgval_getmap(val);
  3152. UPB_ASSERT(map);
  3153. /* TODO: putmap(map, f, sink, depth);*/
  3154. } else if (upb_fielddef_isstring(f)) {
  3155. /* TODO putstr(); */
  3156. } else {
  3157. upb_selector_t sel = getsel2(f, upb_handlers_getprimitivehandlertype(f));
  3158. UPB_ASSERT(upb_fielddef_isprimitive(f));
  3159. switch (upb_fielddef_type(f)) {
  3160. case UPB_TYPE_FLOAT:
  3161. CHECK_TRUE(upb_sink_putfloat(sink, sel, upb_msgval_getfloat(val)));
  3162. break;
  3163. case UPB_TYPE_DOUBLE:
  3164. CHECK_TRUE(
  3165. upb_sink_putdouble(sink, sel, upb_msgval_getdouble(val)));
  3166. break;
  3167. case UPB_TYPE_BOOL:
  3168. CHECK_TRUE(upb_sink_putbool(sink, sel, upb_msgval_getbool(val)));
  3169. break;
  3170. case UPB_TYPE_ENUM:
  3171. case UPB_TYPE_INT32:
  3172. CHECK_TRUE(upb_sink_putint32(sink, sel, upb_msgval_getint32(val)));
  3173. break;
  3174. case UPB_TYPE_UINT32:
  3175. CHECK_TRUE(
  3176. upb_sink_putuint32(sink, sel, upb_msgval_getuint32(val)));
  3177. break;
  3178. case UPB_TYPE_INT64:
  3179. CHECK_TRUE(upb_sink_putint64(sink, sel, upb_msgval_getint64(val)));
  3180. break;
  3181. case UPB_TYPE_UINT64:
  3182. CHECK_TRUE(
  3183. upb_sink_putuint64(sink, sel, upb_msgval_getuint64(val)));
  3184. break;
  3185. case UPB_TYPE_STRING:
  3186. case UPB_TYPE_BYTES:
  3187. case UPB_TYPE_MESSAGE:
  3188. UPB_UNREACHABLE();
  3189. }
  3190. }
  3191. }
  3192. upb_sink_endmsg(sink, &status);
  3193. return true;
  3194. }
  3195. upb_visitor *upb_visitor_create(upb_env *e, const upb_visitorplan *vp,
  3196. upb_sink *output) {
  3197. upb_visitor *visitor = upb_env_malloc(e, sizeof(*visitor));
  3198. visitor->layout = (const upb_msglayout*)vp;
  3199. visitor->sink = output;
  3200. return visitor;
  3201. }
  3202. bool upb_visitor_visitmsg(upb_visitor *visitor, const upb_msg *msg) {
  3203. return upb_visitor_visitmsg2(msg, visitor->layout, visitor->sink, 0);
  3204. }
  3205. /** upb_msg *******************************************************************/
  3206. /* If we always read/write as a consistent type to each address, this shouldn't
  3207. * violate aliasing.
  3208. */
  3209. #define DEREF(msg, ofs, type) *(type*)CHARPTR_AT(msg, ofs)
  3210. static upb_inttable *upb_msg_trygetextdict(const upb_msg *msg,
  3211. const upb_msglayout *l) {
  3212. return l->has_extdict ? DEREF(msg, l->extdict_offset, upb_inttable*) : NULL;
  3213. }
  3214. static upb_inttable *upb_msg_getextdict(upb_msg *msg,
  3215. const upb_msglayout *l,
  3216. upb_alloc *a) {
  3217. upb_inttable *ext_dict;
  3218. UPB_ASSERT(l->has_extdict);
  3219. ext_dict = upb_msg_trygetextdict(msg, l);
  3220. if (!ext_dict) {
  3221. ext_dict = upb_malloc(a, sizeof(upb_inttable));
  3222. if (!ext_dict) {
  3223. return NULL;
  3224. }
  3225. /* Use an 8-byte type to ensure all bytes are copied. */
  3226. if (!upb_inttable_init2(ext_dict, UPB_CTYPE_INT64, a)) {
  3227. upb_free(a, ext_dict);
  3228. return NULL;
  3229. }
  3230. DEREF(msg, l->extdict_offset, upb_inttable*) = ext_dict;
  3231. }
  3232. return ext_dict;
  3233. }
  3234. static uint32_t upb_msg_getoneofint(const upb_msg *msg,
  3235. const upb_oneofdef *o,
  3236. const upb_msglayout *l) {
  3237. size_t oneof_ofs = l->case_offsets[upb_oneofdef_index(o)];
  3238. return DEREF(msg, oneof_ofs, uint8_t);
  3239. }
  3240. static void upb_msg_setoneofcase(const upb_msg *msg,
  3241. const upb_oneofdef *o,
  3242. const upb_msglayout *l,
  3243. uint32_t val) {
  3244. size_t oneof_ofs = l->case_offsets[upb_oneofdef_index(o)];
  3245. DEREF(msg, oneof_ofs, uint8_t) = val;
  3246. }
  3247. static bool upb_msg_oneofis(const upb_msg *msg, const upb_msglayout *l,
  3248. const upb_oneofdef *o, const upb_fielddef *f) {
  3249. return upb_msg_getoneofint(msg, o, l) == upb_fielddef_number(f);
  3250. }
  3251. size_t upb_msg_sizeof(const upb_msglayout *l) { return l->size; }
  3252. void upb_msg_init(upb_msg *msg, const upb_msglayout *l, upb_alloc *a) {
  3253. if (l->default_msg) {
  3254. memcpy(msg, l->default_msg, l->size);
  3255. } else {
  3256. memset(msg, 0, l->size);
  3257. }
  3258. /* Set arena pointer. */
  3259. memcpy(msg, &a, sizeof(a));
  3260. }
  3261. void upb_msg_uninit(upb_msg *msg, const upb_msglayout *l) {
  3262. upb_inttable *ext_dict = upb_msg_trygetextdict(msg, l);
  3263. if (ext_dict) {
  3264. upb_inttable_uninit2(ext_dict, upb_msg_alloc(msg, l));
  3265. }
  3266. }
  3267. upb_msg *upb_msg_new(const upb_msglayout *l, upb_alloc *a) {
  3268. upb_msg *msg = upb_malloc(a, upb_msg_sizeof(l));
  3269. if (msg) {
  3270. upb_msg_init(msg, l, a);
  3271. }
  3272. return msg;
  3273. }
  3274. void upb_msg_free(upb_msg *msg, const upb_msglayout *l) {
  3275. upb_msg_uninit(msg, l);
  3276. upb_free(upb_msg_alloc(msg, l), msg);
  3277. }
  3278. upb_alloc *upb_msg_alloc(const upb_msg *msg, const upb_msglayout *l) {
  3279. upb_alloc *alloc;
  3280. UPB_UNUSED(l);
  3281. memcpy(&alloc, msg, sizeof(alloc));
  3282. return alloc;
  3283. }
  3284. bool upb_msg_has(const upb_msg *msg,
  3285. const upb_fielddef *f,
  3286. const upb_msglayout *l) {
  3287. const upb_oneofdef *o;
  3288. upb_msg_checkfield(l, f);
  3289. UPB_ASSERT(upb_fielddef_haspresence(f));
  3290. if (upb_fielddef_isextension(f)) {
  3291. /* Extensions are set when they are present in the extension dict. */
  3292. upb_inttable *ext_dict = upb_msg_trygetextdict(msg, l);
  3293. upb_value v;
  3294. return ext_dict != NULL &&
  3295. upb_inttable_lookup32(ext_dict, upb_fielddef_number(f), &v);
  3296. } else if ((o = upb_fielddef_containingoneof(f)) != NULL) {
  3297. /* Oneofs are set when the oneof number is set to this field. */
  3298. return upb_msg_getoneofint(msg, o, l) == upb_fielddef_number(f);
  3299. } else {
  3300. /* Other fields are set when their hasbit is set. */
  3301. uint32_t hasbit = l->hasbits[upb_fielddef_index(f)];
  3302. return DEREF(msg, hasbit / 8, char) | (1 << (hasbit % 8));
  3303. }
  3304. }
  3305. upb_msgval upb_msg_get(const upb_msg *msg, const upb_fielddef *f,
  3306. const upb_msglayout *l) {
  3307. upb_msg_checkfield(l, f);
  3308. if (upb_fielddef_isextension(f)) {
  3309. upb_inttable *ext_dict = upb_msg_trygetextdict(msg, l);
  3310. upb_value val;
  3311. if (upb_inttable_lookup32(ext_dict, upb_fielddef_number(f), &val)) {
  3312. return upb_msgval_fromval(val);
  3313. } else {
  3314. return upb_msgval_fromdefault(f);
  3315. }
  3316. } else {
  3317. size_t ofs = l->field_offsets[upb_fielddef_index(f)];
  3318. const upb_oneofdef *o = upb_fielddef_containingoneof(f);
  3319. upb_msgval ret;
  3320. if (o && !upb_msg_oneofis(msg, l, o, f)) {
  3321. /* Oneof defaults can't come from the message because the memory is reused
  3322. * by all types in the oneof. */
  3323. return upb_msgval_fromdefault(f);
  3324. }
  3325. ret = upb_msgval_read(msg, ofs, upb_msg_fieldsize(f));
  3326. return ret;
  3327. }
  3328. }
  3329. bool upb_msg_set(upb_msg *msg,
  3330. const upb_fielddef *f,
  3331. upb_msgval val,
  3332. const upb_msglayout *l) {
  3333. upb_alloc *a = upb_msg_alloc(msg, l);
  3334. upb_msg_checkfield(l, f);
  3335. if (upb_fielddef_isextension(f)) {
  3336. /* TODO(haberman): introduce table API that can do this in one call. */
  3337. upb_inttable *ext = upb_msg_getextdict(msg, l, a);
  3338. upb_value val2 = upb_toval(val);
  3339. if (!upb_inttable_replace(ext, upb_fielddef_number(f), val2) &&
  3340. !upb_inttable_insert2(ext, upb_fielddef_number(f), val2, a)) {
  3341. return false;
  3342. }
  3343. } else {
  3344. size_t ofs = l->field_offsets[upb_fielddef_index(f)];
  3345. const upb_oneofdef *o = upb_fielddef_containingoneof(f);
  3346. if (o) {
  3347. upb_msg_setoneofcase(msg, o, l, upb_fielddef_number(f));
  3348. }
  3349. upb_msgval_write(msg, ofs, val, upb_msg_fieldsize(f));
  3350. }
  3351. return true;
  3352. }
  3353. /** upb_array *****************************************************************/
  3354. struct upb_array {
  3355. upb_fieldtype_t type;
  3356. uint8_t element_size;
  3357. void *data; /* Each element is element_size. */
  3358. size_t len; /* Measured in elements. */
  3359. size_t size; /* Measured in elements. */
  3360. upb_alloc *alloc;
  3361. };
  3362. #define DEREF_ARR(arr, i, type) ((type*)arr->data)[i]
  3363. size_t upb_array_sizeof(upb_fieldtype_t type) {
  3364. UPB_UNUSED(type);
  3365. return sizeof(upb_array);
  3366. }
  3367. void upb_array_init(upb_array *arr, upb_fieldtype_t type, upb_alloc *alloc) {
  3368. arr->type = type;
  3369. arr->data = NULL;
  3370. arr->len = 0;
  3371. arr->size = 0;
  3372. arr->element_size = upb_msgval_sizeof(type);
  3373. arr->alloc = alloc;
  3374. }
  3375. void upb_array_uninit(upb_array *arr) {
  3376. upb_free(arr->alloc, arr->data);
  3377. }
  3378. upb_array *upb_array_new(upb_fieldtype_t type, upb_alloc *a) {
  3379. upb_array *ret = upb_malloc(a, upb_array_sizeof(type));
  3380. if (ret) {
  3381. upb_array_init(ret, type, a);
  3382. }
  3383. return ret;
  3384. }
  3385. void upb_array_free(upb_array *arr) {
  3386. upb_array_uninit(arr);
  3387. upb_free(arr->alloc, arr);
  3388. }
  3389. size_t upb_array_size(const upb_array *arr) {
  3390. return arr->len;
  3391. }
  3392. upb_fieldtype_t upb_array_type(const upb_array *arr) {
  3393. return arr->type;
  3394. }
  3395. upb_msgval upb_array_get(const upb_array *arr, size_t i) {
  3396. UPB_ASSERT(i < arr->len);
  3397. return upb_msgval_read(arr->data, i * arr->element_size, arr->element_size);
  3398. }
  3399. bool upb_array_set(upb_array *arr, size_t i, upb_msgval val) {
  3400. UPB_ASSERT(i <= arr->len);
  3401. if (i == arr->len) {
  3402. /* Extending the array. */
  3403. if (i == arr->size) {
  3404. /* Need to reallocate. */
  3405. size_t new_size = UPB_MAX(arr->size * 2, 8);
  3406. size_t new_bytes = new_size * arr->element_size;
  3407. size_t old_bytes = arr->size * arr->element_size;
  3408. upb_msgval *new_data =
  3409. upb_realloc(arr->alloc, arr->data, old_bytes, new_bytes);
  3410. if (!new_data) {
  3411. return false;
  3412. }
  3413. arr->data = new_data;
  3414. arr->size = new_size;
  3415. }
  3416. arr->len = i + 1;
  3417. }
  3418. upb_msgval_write(arr->data, i * arr->element_size, val, arr->element_size);
  3419. return true;
  3420. }
  3421. /** upb_map *******************************************************************/
  3422. struct upb_map {
  3423. upb_fieldtype_t key_type;
  3424. upb_fieldtype_t val_type;
  3425. /* We may want to optimize this to use inttable where possible, for greater
  3426. * efficiency and lower memory footprint. */
  3427. upb_strtable strtab;
  3428. upb_alloc *alloc;
  3429. };
  3430. static void upb_map_tokey(upb_fieldtype_t type, upb_msgval *key,
  3431. const char **out_key, size_t *out_len) {
  3432. switch (type) {
  3433. case UPB_TYPE_STRING:
  3434. /* Point to string data of the input key. */
  3435. *out_key = key->str.ptr;
  3436. *out_len = key->str.len;
  3437. return;
  3438. case UPB_TYPE_BOOL:
  3439. case UPB_TYPE_INT32:
  3440. case UPB_TYPE_UINT32:
  3441. case UPB_TYPE_INT64:
  3442. case UPB_TYPE_UINT64:
  3443. /* Point to the key itself. XXX: big-endian. */
  3444. *out_key = (const char*)key;
  3445. *out_len = upb_msgval_sizeof(type);
  3446. return;
  3447. case UPB_TYPE_BYTES:
  3448. case UPB_TYPE_DOUBLE:
  3449. case UPB_TYPE_ENUM:
  3450. case UPB_TYPE_FLOAT:
  3451. case UPB_TYPE_MESSAGE:
  3452. break; /* Cannot be a map key. */
  3453. }
  3454. UPB_UNREACHABLE();
  3455. }
  3456. static upb_msgval upb_map_fromkey(upb_fieldtype_t type, const char *key,
  3457. size_t len) {
  3458. switch (type) {
  3459. case UPB_TYPE_STRING:
  3460. return upb_msgval_str(key, len);
  3461. case UPB_TYPE_BOOL:
  3462. case UPB_TYPE_INT32:
  3463. case UPB_TYPE_UINT32:
  3464. case UPB_TYPE_INT64:
  3465. case UPB_TYPE_UINT64:
  3466. return upb_msgval_read(key, 0, upb_msgval_sizeof(type));
  3467. case UPB_TYPE_BYTES:
  3468. case UPB_TYPE_DOUBLE:
  3469. case UPB_TYPE_ENUM:
  3470. case UPB_TYPE_FLOAT:
  3471. case UPB_TYPE_MESSAGE:
  3472. break; /* Cannot be a map key. */
  3473. }
  3474. UPB_UNREACHABLE();
  3475. }
  3476. size_t upb_map_sizeof(upb_fieldtype_t ktype, upb_fieldtype_t vtype) {
  3477. /* Size does not currently depend on key/value type. */
  3478. UPB_UNUSED(ktype);
  3479. UPB_UNUSED(vtype);
  3480. return sizeof(upb_map);
  3481. }
  3482. bool upb_map_init(upb_map *map, upb_fieldtype_t ktype, upb_fieldtype_t vtype,
  3483. upb_alloc *a) {
  3484. upb_ctype_t vtabtype = upb_fieldtotabtype(vtype);
  3485. UPB_ASSERT(upb_fieldtype_mapkeyok(ktype));
  3486. map->key_type = ktype;
  3487. map->val_type = vtype;
  3488. map->alloc = a;
  3489. if (!upb_strtable_init2(&map->strtab, vtabtype, a)) {
  3490. return false;
  3491. }
  3492. return true;
  3493. }
  3494. void upb_map_uninit(upb_map *map) {
  3495. upb_strtable_uninit2(&map->strtab, map->alloc);
  3496. }
  3497. upb_map *upb_map_new(upb_fieldtype_t ktype, upb_fieldtype_t vtype,
  3498. upb_alloc *a) {
  3499. upb_map *map = upb_malloc(a, upb_map_sizeof(ktype, vtype));
  3500. if (!map) {
  3501. return NULL;
  3502. }
  3503. if (!upb_map_init(map, ktype, vtype, a)) {
  3504. return NULL;
  3505. }
  3506. return map;
  3507. }
  3508. void upb_map_free(upb_map *map) {
  3509. upb_map_uninit(map);
  3510. upb_free(map->alloc, map);
  3511. }
  3512. size_t upb_map_size(const upb_map *map) {
  3513. return upb_strtable_count(&map->strtab);
  3514. }
  3515. upb_fieldtype_t upb_map_keytype(const upb_map *map) {
  3516. return map->key_type;
  3517. }
  3518. upb_fieldtype_t upb_map_valuetype(const upb_map *map) {
  3519. return map->val_type;
  3520. }
  3521. bool upb_map_get(const upb_map *map, upb_msgval key, upb_msgval *val) {
  3522. upb_value tabval;
  3523. const char *key_str;
  3524. size_t key_len;
  3525. bool ret;
  3526. upb_map_tokey(map->key_type, &key, &key_str, &key_len);
  3527. ret = upb_strtable_lookup2(&map->strtab, key_str, key_len, &tabval);
  3528. if (ret) {
  3529. memcpy(val, &tabval, sizeof(tabval));
  3530. }
  3531. return ret;
  3532. }
  3533. bool upb_map_set(upb_map *map, upb_msgval key, upb_msgval val,
  3534. upb_msgval *removed) {
  3535. const char *key_str;
  3536. size_t key_len;
  3537. upb_value tabval = upb_toval(val);
  3538. upb_value removedtabval;
  3539. upb_alloc *a = map->alloc;
  3540. upb_map_tokey(map->key_type, &key, &key_str, &key_len);
  3541. /* TODO(haberman): add overwrite operation to minimize number of lookups. */
  3542. if (upb_strtable_lookup2(&map->strtab, key_str, key_len, NULL)) {
  3543. upb_strtable_remove3(&map->strtab, key_str, key_len, &removedtabval, a);
  3544. memcpy(&removed, &removedtabval, sizeof(removed));
  3545. }
  3546. return upb_strtable_insert3(&map->strtab, key_str, key_len, tabval, a);
  3547. }
  3548. bool upb_map_del(upb_map *map, upb_msgval key) {
  3549. const char *key_str;
  3550. size_t key_len;
  3551. upb_alloc *a = map->alloc;
  3552. upb_map_tokey(map->key_type, &key, &key_str, &key_len);
  3553. return upb_strtable_remove3(&map->strtab, key_str, key_len, NULL, a);
  3554. }
  3555. /** upb_mapiter ***************************************************************/
  3556. struct upb_mapiter {
  3557. upb_strtable_iter iter;
  3558. upb_fieldtype_t key_type;
  3559. };
  3560. size_t upb_mapiter_sizeof() {
  3561. return sizeof(upb_mapiter);
  3562. }
  3563. void upb_mapiter_begin(upb_mapiter *i, const upb_map *map) {
  3564. upb_strtable_begin(&i->iter, &map->strtab);
  3565. i->key_type = map->key_type;
  3566. }
  3567. upb_mapiter *upb_mapiter_new(const upb_map *t, upb_alloc *a) {
  3568. upb_mapiter *ret = upb_malloc(a, upb_mapiter_sizeof());
  3569. if (!ret) {
  3570. return NULL;
  3571. }
  3572. upb_mapiter_begin(ret, t);
  3573. return ret;
  3574. }
  3575. void upb_mapiter_free(upb_mapiter *i, upb_alloc *a) {
  3576. upb_free(a, i);
  3577. }
  3578. void upb_mapiter_next(upb_mapiter *i) {
  3579. upb_strtable_next(&i->iter);
  3580. }
  3581. bool upb_mapiter_done(const upb_mapiter *i) {
  3582. return upb_strtable_done(&i->iter);
  3583. }
  3584. upb_msgval upb_mapiter_key(const upb_mapiter *i) {
  3585. return upb_map_fromkey(i->key_type, upb_strtable_iter_key(&i->iter),
  3586. upb_strtable_iter_keylength(&i->iter));
  3587. }
  3588. upb_msgval upb_mapiter_value(const upb_mapiter *i) {
  3589. return upb_msgval_fromval(upb_strtable_iter_value(&i->iter));
  3590. }
  3591. void upb_mapiter_setdone(upb_mapiter *i) {
  3592. upb_strtable_iter_setdone(&i->iter);
  3593. }
  3594. bool upb_mapiter_isequal(const upb_mapiter *i1, const upb_mapiter *i2) {
  3595. return upb_strtable_iter_isequal(&i1->iter, &i2->iter);
  3596. }
  3597. /** Handlers for upb_msg ******************************************************/
  3598. typedef struct {
  3599. size_t offset;
  3600. int32_t hasbit;
  3601. } upb_msg_handlerdata;
  3602. /* Fallback implementation if the handler is not specialized by the producer. */
  3603. #define MSG_WRITER(type, ctype) \
  3604. bool upb_msg_set ## type (void *c, const void *hd, ctype val) { \
  3605. uint8_t *m = c; \
  3606. const upb_msg_handlerdata *d = hd; \
  3607. if (d->hasbit > 0) \
  3608. *(uint8_t*)&m[d->hasbit / 8] |= 1 << (d->hasbit % 8); \
  3609. *(ctype*)&m[d->offset] = val; \
  3610. return true; \
  3611. } \
  3612. MSG_WRITER(double, double)
  3613. MSG_WRITER(float, float)
  3614. MSG_WRITER(int32, int32_t)
  3615. MSG_WRITER(int64, int64_t)
  3616. MSG_WRITER(uint32, uint32_t)
  3617. MSG_WRITER(uint64, uint64_t)
  3618. MSG_WRITER(bool, bool)
  3619. bool upb_msg_setscalarhandler(upb_handlers *h, const upb_fielddef *f,
  3620. size_t offset, int32_t hasbit) {
  3621. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  3622. bool ok;
  3623. upb_msg_handlerdata *d = upb_gmalloc(sizeof(*d));
  3624. if (!d) return false;
  3625. d->offset = offset;
  3626. d->hasbit = hasbit;
  3627. upb_handlerattr_sethandlerdata(&attr, d);
  3628. upb_handlerattr_setalwaysok(&attr, true);
  3629. upb_handlers_addcleanup(h, d, upb_gfree);
  3630. #define TYPE(u, l) \
  3631. case UPB_TYPE_##u: \
  3632. ok = upb_handlers_set##l(h, f, upb_msg_set##l, &attr); break;
  3633. ok = false;
  3634. switch (upb_fielddef_type(f)) {
  3635. TYPE(INT64, int64);
  3636. TYPE(INT32, int32);
  3637. TYPE(ENUM, int32);
  3638. TYPE(UINT64, uint64);
  3639. TYPE(UINT32, uint32);
  3640. TYPE(DOUBLE, double);
  3641. TYPE(FLOAT, float);
  3642. TYPE(BOOL, bool);
  3643. default: UPB_ASSERT(false); break;
  3644. }
  3645. #undef TYPE
  3646. upb_handlerattr_uninit(&attr);
  3647. return ok;
  3648. }
  3649. bool upb_msg_getscalarhandlerdata(const upb_handlers *h,
  3650. upb_selector_t s,
  3651. upb_fieldtype_t *type,
  3652. size_t *offset,
  3653. int32_t *hasbit) {
  3654. const upb_msg_handlerdata *d;
  3655. upb_func *f = upb_handlers_gethandler(h, s);
  3656. if ((upb_int64_handlerfunc*)f == upb_msg_setint64) {
  3657. *type = UPB_TYPE_INT64;
  3658. } else if ((upb_int32_handlerfunc*)f == upb_msg_setint32) {
  3659. *type = UPB_TYPE_INT32;
  3660. } else if ((upb_uint64_handlerfunc*)f == upb_msg_setuint64) {
  3661. *type = UPB_TYPE_UINT64;
  3662. } else if ((upb_uint32_handlerfunc*)f == upb_msg_setuint32) {
  3663. *type = UPB_TYPE_UINT32;
  3664. } else if ((upb_double_handlerfunc*)f == upb_msg_setdouble) {
  3665. *type = UPB_TYPE_DOUBLE;
  3666. } else if ((upb_float_handlerfunc*)f == upb_msg_setfloat) {
  3667. *type = UPB_TYPE_FLOAT;
  3668. } else if ((upb_bool_handlerfunc*)f == upb_msg_setbool) {
  3669. *type = UPB_TYPE_BOOL;
  3670. } else {
  3671. return false;
  3672. }
  3673. d = upb_handlers_gethandlerdata(h, s);
  3674. *offset = d->offset;
  3675. *hasbit = d->hasbit;
  3676. return true;
  3677. }
  3678. /*
  3679. ** upb::RefCounted Implementation
  3680. **
  3681. ** Our key invariants are:
  3682. ** 1. reference cycles never span groups
  3683. ** 2. for ref2(to, from), we increment to's count iff group(from) != group(to)
  3684. **
  3685. ** The previous two are how we avoid leaking cycles. Other important
  3686. ** invariants are:
  3687. ** 3. for mutable objects "from" and "to", if there exists a ref2(to, from)
  3688. ** this implies group(from) == group(to). (In practice, what we implement
  3689. ** is even stronger; "from" and "to" will share a group if there has *ever*
  3690. ** been a ref2(to, from), but all that is necessary for correctness is the
  3691. ** weaker one).
  3692. ** 4. mutable and immutable objects are never in the same group.
  3693. */
  3694. #include <setjmp.h>
  3695. static void freeobj(upb_refcounted *o);
  3696. const char untracked_val;
  3697. const void *UPB_UNTRACKED_REF = &untracked_val;
  3698. /* arch-specific atomic primitives *******************************************/
  3699. #ifdef UPB_THREAD_UNSAFE /*---------------------------------------------------*/
  3700. static void atomic_inc(uint32_t *a) { (*a)++; }
  3701. static bool atomic_dec(uint32_t *a) { return --(*a) == 0; }
  3702. #elif defined(__GNUC__) || defined(__clang__) /*------------------------------*/
  3703. static void atomic_inc(uint32_t *a) { __sync_fetch_and_add(a, 1); }
  3704. static bool atomic_dec(uint32_t *a) { return __sync_sub_and_fetch(a, 1) == 0; }
  3705. #elif defined(WIN32) /*-------------------------------------------------------*/
  3706. #include <Windows.h>
  3707. static void atomic_inc(upb_atomic_t *a) { InterlockedIncrement(&a->val); }
  3708. static bool atomic_dec(upb_atomic_t *a) {
  3709. return InterlockedDecrement(&a->val) == 0;
  3710. }
  3711. #else
  3712. #error Atomic primitives not defined for your platform/CPU. \
  3713. Implement them or compile with UPB_THREAD_UNSAFE.
  3714. #endif
  3715. /* All static objects point to this refcount.
  3716. * It is special-cased in ref/unref below. */
  3717. uint32_t static_refcount = -1;
  3718. /* We can avoid atomic ops for statically-declared objects.
  3719. * This is a minor optimization but nice since we can avoid degrading under
  3720. * contention in this case. */
  3721. static void refgroup(uint32_t *group) {
  3722. if (group != &static_refcount)
  3723. atomic_inc(group);
  3724. }
  3725. static bool unrefgroup(uint32_t *group) {
  3726. if (group == &static_refcount) {
  3727. return false;
  3728. } else {
  3729. return atomic_dec(group);
  3730. }
  3731. }
  3732. /* Reference tracking (debug only) ********************************************/
  3733. #ifdef UPB_DEBUG_REFS
  3734. #ifdef UPB_THREAD_UNSAFE
  3735. static void upb_lock() {}
  3736. static void upb_unlock() {}
  3737. #else
  3738. /* User must define functions that lock/unlock a global mutex and link this
  3739. * file against them. */
  3740. void upb_lock();
  3741. void upb_unlock();
  3742. #endif
  3743. /* UPB_DEBUG_REFS mode counts on being able to malloc() memory in some
  3744. * code-paths that can normally never fail, like upb_refcounted_ref(). Since
  3745. * we have no way to propagage out-of-memory errors back to the user, and since
  3746. * these errors can only occur in UPB_DEBUG_REFS mode, we use an allocator that
  3747. * immediately aborts on failure (avoiding the global allocator, which might
  3748. * inject failures). */
  3749. #include <stdlib.h>
  3750. static void *upb_debugrefs_allocfunc(upb_alloc *alloc, void *ptr,
  3751. size_t oldsize, size_t size) {
  3752. UPB_UNUSED(alloc);
  3753. UPB_UNUSED(oldsize);
  3754. if (size == 0) {
  3755. free(ptr);
  3756. return NULL;
  3757. } else {
  3758. void *ret = realloc(ptr, size);
  3759. if (!ret) {
  3760. abort();
  3761. }
  3762. return ret;
  3763. }
  3764. }
  3765. upb_alloc upb_alloc_debugrefs = {&upb_debugrefs_allocfunc};
  3766. typedef struct {
  3767. int count; /* How many refs there are (duplicates only allowed for ref2). */
  3768. bool is_ref2;
  3769. } trackedref;
  3770. static trackedref *trackedref_new(bool is_ref2) {
  3771. trackedref *ret = upb_malloc(&upb_alloc_debugrefs, sizeof(*ret));
  3772. ret->count = 1;
  3773. ret->is_ref2 = is_ref2;
  3774. return ret;
  3775. }
  3776. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  3777. upb_value v;
  3778. UPB_ASSERT(owner);
  3779. if (owner == UPB_UNTRACKED_REF) return;
  3780. upb_lock();
  3781. if (upb_inttable_lookupptr(r->refs, owner, &v)) {
  3782. trackedref *ref = upb_value_getptr(v);
  3783. /* Since we allow multiple ref2's for the same to/from pair without
  3784. * allocating separate memory for each one, we lose the fine-grained
  3785. * tracking behavior we get with regular refs. Since ref2s only happen
  3786. * inside upb, we'll accept this limitation until/unless there is a really
  3787. * difficult upb-internal bug that can't be figured out without it. */
  3788. UPB_ASSERT(ref2);
  3789. UPB_ASSERT(ref->is_ref2);
  3790. ref->count++;
  3791. } else {
  3792. trackedref *ref = trackedref_new(ref2);
  3793. upb_inttable_insertptr2(r->refs, owner, upb_value_ptr(ref),
  3794. &upb_alloc_debugrefs);
  3795. if (ref2) {
  3796. /* We know this cast is safe when it is a ref2, because it's coming from
  3797. * another refcounted object. */
  3798. const upb_refcounted *from = owner;
  3799. UPB_ASSERT(!upb_inttable_lookupptr(from->ref2s, r, NULL));
  3800. upb_inttable_insertptr2(from->ref2s, r, upb_value_ptr(NULL),
  3801. &upb_alloc_debugrefs);
  3802. }
  3803. }
  3804. upb_unlock();
  3805. }
  3806. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  3807. upb_value v;
  3808. bool found;
  3809. trackedref *ref;
  3810. UPB_ASSERT(owner);
  3811. if (owner == UPB_UNTRACKED_REF) return;
  3812. upb_lock();
  3813. found = upb_inttable_lookupptr(r->refs, owner, &v);
  3814. /* This assert will fail if an owner attempts to release a ref it didn't have. */
  3815. UPB_ASSERT(found);
  3816. ref = upb_value_getptr(v);
  3817. UPB_ASSERT(ref->is_ref2 == ref2);
  3818. if (--ref->count == 0) {
  3819. free(ref);
  3820. upb_inttable_removeptr(r->refs, owner, NULL);
  3821. if (ref2) {
  3822. /* We know this cast is safe when it is a ref2, because it's coming from
  3823. * another refcounted object. */
  3824. const upb_refcounted *from = owner;
  3825. bool removed = upb_inttable_removeptr(from->ref2s, r, NULL);
  3826. UPB_ASSERT(removed);
  3827. }
  3828. }
  3829. upb_unlock();
  3830. }
  3831. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  3832. upb_value v;
  3833. bool found;
  3834. trackedref *ref;
  3835. upb_lock();
  3836. found = upb_inttable_lookupptr(r->refs, owner, &v);
  3837. UPB_ASSERT(found);
  3838. ref = upb_value_getptr(v);
  3839. UPB_ASSERT(ref->is_ref2 == ref2);
  3840. upb_unlock();
  3841. }
  3842. /* Populates the given UPB_CTYPE_INT32 inttable with counts of ref2's that
  3843. * originate from the given owner. */
  3844. static void getref2s(const upb_refcounted *owner, upb_inttable *tab) {
  3845. upb_inttable_iter i;
  3846. upb_lock();
  3847. upb_inttable_begin(&i, owner->ref2s);
  3848. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  3849. upb_value v;
  3850. upb_value count;
  3851. trackedref *ref;
  3852. bool found;
  3853. upb_refcounted *to = (upb_refcounted*)upb_inttable_iter_key(&i);
  3854. /* To get the count we need to look in the target's table. */
  3855. found = upb_inttable_lookupptr(to->refs, owner, &v);
  3856. UPB_ASSERT(found);
  3857. ref = upb_value_getptr(v);
  3858. count = upb_value_int32(ref->count);
  3859. upb_inttable_insertptr2(tab, to, count, &upb_alloc_debugrefs);
  3860. }
  3861. upb_unlock();
  3862. }
  3863. typedef struct {
  3864. upb_inttable ref2;
  3865. const upb_refcounted *obj;
  3866. } check_state;
  3867. static void visit_check(const upb_refcounted *obj, const upb_refcounted *subobj,
  3868. void *closure) {
  3869. check_state *s = closure;
  3870. upb_inttable *ref2 = &s->ref2;
  3871. upb_value v;
  3872. bool removed;
  3873. int32_t newcount;
  3874. UPB_ASSERT(obj == s->obj);
  3875. UPB_ASSERT(subobj);
  3876. removed = upb_inttable_removeptr(ref2, subobj, &v);
  3877. /* The following assertion will fail if the visit() function visits a subobj
  3878. * that it did not have a ref2 on, or visits the same subobj too many times. */
  3879. UPB_ASSERT(removed);
  3880. newcount = upb_value_getint32(v) - 1;
  3881. if (newcount > 0) {
  3882. upb_inttable_insert2(ref2, (uintptr_t)subobj, upb_value_int32(newcount),
  3883. &upb_alloc_debugrefs);
  3884. }
  3885. }
  3886. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  3887. void *closure) {
  3888. /* In DEBUG_REFS mode we know what existing ref2 refs there are, so we know
  3889. * exactly the set of nodes that visit() should visit. So we verify visit()'s
  3890. * correctness here. */
  3891. check_state state;
  3892. state.obj = r;
  3893. upb_inttable_init2(&state.ref2, UPB_CTYPE_INT32, &upb_alloc_debugrefs);
  3894. getref2s(r, &state.ref2);
  3895. /* This should visit any children in the ref2 table. */
  3896. if (r->vtbl->visit) r->vtbl->visit(r, visit_check, &state);
  3897. /* This assertion will fail if the visit() function missed any children. */
  3898. UPB_ASSERT(upb_inttable_count(&state.ref2) == 0);
  3899. upb_inttable_uninit2(&state.ref2, &upb_alloc_debugrefs);
  3900. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  3901. }
  3902. static void trackinit(upb_refcounted *r) {
  3903. r->refs = upb_malloc(&upb_alloc_debugrefs, sizeof(*r->refs));
  3904. r->ref2s = upb_malloc(&upb_alloc_debugrefs, sizeof(*r->ref2s));
  3905. upb_inttable_init2(r->refs, UPB_CTYPE_PTR, &upb_alloc_debugrefs);
  3906. upb_inttable_init2(r->ref2s, UPB_CTYPE_PTR, &upb_alloc_debugrefs);
  3907. }
  3908. static void trackfree(const upb_refcounted *r) {
  3909. upb_inttable_uninit2(r->refs, &upb_alloc_debugrefs);
  3910. upb_inttable_uninit2(r->ref2s, &upb_alloc_debugrefs);
  3911. upb_free(&upb_alloc_debugrefs, r->refs);
  3912. upb_free(&upb_alloc_debugrefs, r->ref2s);
  3913. }
  3914. #else
  3915. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  3916. UPB_UNUSED(r);
  3917. UPB_UNUSED(owner);
  3918. UPB_UNUSED(ref2);
  3919. }
  3920. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  3921. UPB_UNUSED(r);
  3922. UPB_UNUSED(owner);
  3923. UPB_UNUSED(ref2);
  3924. }
  3925. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  3926. UPB_UNUSED(r);
  3927. UPB_UNUSED(owner);
  3928. UPB_UNUSED(ref2);
  3929. }
  3930. static void trackinit(upb_refcounted *r) {
  3931. UPB_UNUSED(r);
  3932. }
  3933. static void trackfree(const upb_refcounted *r) {
  3934. UPB_UNUSED(r);
  3935. }
  3936. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  3937. void *closure) {
  3938. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  3939. }
  3940. #endif /* UPB_DEBUG_REFS */
  3941. /* freeze() *******************************************************************/
  3942. /* The freeze() operation is by far the most complicated part of this scheme.
  3943. * We compute strongly-connected components and then mutate the graph such that
  3944. * we preserve the invariants documented at the top of this file. And we must
  3945. * handle out-of-memory errors gracefully (without leaving the graph
  3946. * inconsistent), which adds to the fun. */
  3947. /* The state used by the freeze operation (shared across many functions). */
  3948. typedef struct {
  3949. int depth;
  3950. int maxdepth;
  3951. uint64_t index;
  3952. /* Maps upb_refcounted* -> attributes (color, etc). attr layout varies by
  3953. * color. */
  3954. upb_inttable objattr;
  3955. upb_inttable stack; /* stack of upb_refcounted* for Tarjan's algorithm. */
  3956. upb_inttable groups; /* array of uint32_t*, malloc'd refcounts for new groups */
  3957. upb_status *status;
  3958. jmp_buf err;
  3959. } tarjan;
  3960. static void release_ref2(const upb_refcounted *obj,
  3961. const upb_refcounted *subobj,
  3962. void *closure);
  3963. /* Node attributes -----------------------------------------------------------*/
  3964. /* After our analysis phase all nodes will be either GRAY or WHITE. */
  3965. typedef enum {
  3966. BLACK = 0, /* Object has not been seen. */
  3967. GRAY, /* Object has been found via a refgroup but may not be reachable. */
  3968. GREEN, /* Object is reachable and is currently on the Tarjan stack. */
  3969. WHITE /* Object is reachable and has been assigned a group (SCC). */
  3970. } color_t;
  3971. UPB_NORETURN static void err(tarjan *t) { longjmp(t->err, 1); }
  3972. UPB_NORETURN static void oom(tarjan *t) {
  3973. upb_status_seterrmsg(t->status, "out of memory");
  3974. err(t);
  3975. }
  3976. static uint64_t trygetattr(const tarjan *t, const upb_refcounted *r) {
  3977. upb_value v;
  3978. return upb_inttable_lookupptr(&t->objattr, r, &v) ?
  3979. upb_value_getuint64(v) : 0;
  3980. }
  3981. static uint64_t getattr(const tarjan *t, const upb_refcounted *r) {
  3982. upb_value v;
  3983. bool found = upb_inttable_lookupptr(&t->objattr, r, &v);
  3984. UPB_ASSERT(found);
  3985. return upb_value_getuint64(v);
  3986. }
  3987. static void setattr(tarjan *t, const upb_refcounted *r, uint64_t attr) {
  3988. upb_inttable_removeptr(&t->objattr, r, NULL);
  3989. upb_inttable_insertptr(&t->objattr, r, upb_value_uint64(attr));
  3990. }
  3991. static color_t color(tarjan *t, const upb_refcounted *r) {
  3992. return trygetattr(t, r) & 0x3; /* Color is always stored in the low 2 bits. */
  3993. }
  3994. static void set_gray(tarjan *t, const upb_refcounted *r) {
  3995. UPB_ASSERT(color(t, r) == BLACK);
  3996. setattr(t, r, GRAY);
  3997. }
  3998. /* Pushes an obj onto the Tarjan stack and sets it to GREEN. */
  3999. static void push(tarjan *t, const upb_refcounted *r) {
  4000. UPB_ASSERT(color(t, r) == BLACK || color(t, r) == GRAY);
  4001. /* This defines the attr layout for the GREEN state. "index" and "lowlink"
  4002. * get 31 bits, which is plenty (limit of 2B objects frozen at a time). */
  4003. setattr(t, r, GREEN | (t->index << 2) | (t->index << 33));
  4004. if (++t->index == 0x80000000) {
  4005. upb_status_seterrmsg(t->status, "too many objects to freeze");
  4006. err(t);
  4007. }
  4008. upb_inttable_push(&t->stack, upb_value_ptr((void*)r));
  4009. }
  4010. /* Pops an obj from the Tarjan stack and sets it to WHITE, with a ptr to its
  4011. * SCC group. */
  4012. static upb_refcounted *pop(tarjan *t) {
  4013. upb_refcounted *r = upb_value_getptr(upb_inttable_pop(&t->stack));
  4014. UPB_ASSERT(color(t, r) == GREEN);
  4015. /* This defines the attr layout for nodes in the WHITE state.
  4016. * Top of group stack is [group, NULL]; we point at group. */
  4017. setattr(t, r, WHITE | (upb_inttable_count(&t->groups) - 2) << 8);
  4018. return r;
  4019. }
  4020. static void tarjan_newgroup(tarjan *t) {
  4021. uint32_t *group = upb_gmalloc(sizeof(*group));
  4022. if (!group) oom(t);
  4023. /* Push group and empty group leader (we'll fill in leader later). */
  4024. if (!upb_inttable_push(&t->groups, upb_value_ptr(group)) ||
  4025. !upb_inttable_push(&t->groups, upb_value_ptr(NULL))) {
  4026. upb_gfree(group);
  4027. oom(t);
  4028. }
  4029. *group = 0;
  4030. }
  4031. static uint32_t idx(tarjan *t, const upb_refcounted *r) {
  4032. UPB_ASSERT(color(t, r) == GREEN);
  4033. return (getattr(t, r) >> 2) & 0x7FFFFFFF;
  4034. }
  4035. static uint32_t lowlink(tarjan *t, const upb_refcounted *r) {
  4036. if (color(t, r) == GREEN) {
  4037. return getattr(t, r) >> 33;
  4038. } else {
  4039. return UINT32_MAX;
  4040. }
  4041. }
  4042. static void set_lowlink(tarjan *t, const upb_refcounted *r, uint32_t lowlink) {
  4043. UPB_ASSERT(color(t, r) == GREEN);
  4044. setattr(t, r, ((uint64_t)lowlink << 33) | (getattr(t, r) & 0x1FFFFFFFF));
  4045. }
  4046. static uint32_t *group(tarjan *t, upb_refcounted *r) {
  4047. uint64_t groupnum;
  4048. upb_value v;
  4049. bool found;
  4050. UPB_ASSERT(color(t, r) == WHITE);
  4051. groupnum = getattr(t, r) >> 8;
  4052. found = upb_inttable_lookup(&t->groups, groupnum, &v);
  4053. UPB_ASSERT(found);
  4054. return upb_value_getptr(v);
  4055. }
  4056. /* If the group leader for this object's group has not previously been set,
  4057. * the given object is assigned to be its leader. */
  4058. static upb_refcounted *groupleader(tarjan *t, upb_refcounted *r) {
  4059. uint64_t leader_slot;
  4060. upb_value v;
  4061. bool found;
  4062. UPB_ASSERT(color(t, r) == WHITE);
  4063. leader_slot = (getattr(t, r) >> 8) + 1;
  4064. found = upb_inttable_lookup(&t->groups, leader_slot, &v);
  4065. UPB_ASSERT(found);
  4066. if (upb_value_getptr(v)) {
  4067. return upb_value_getptr(v);
  4068. } else {
  4069. upb_inttable_remove(&t->groups, leader_slot, NULL);
  4070. upb_inttable_insert(&t->groups, leader_slot, upb_value_ptr(r));
  4071. return r;
  4072. }
  4073. }
  4074. /* Tarjan's algorithm --------------------------------------------------------*/
  4075. /* See:
  4076. * http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm */
  4077. static void do_tarjan(const upb_refcounted *obj, tarjan *t);
  4078. static void tarjan_visit(const upb_refcounted *obj,
  4079. const upb_refcounted *subobj,
  4080. void *closure) {
  4081. tarjan *t = closure;
  4082. if (++t->depth > t->maxdepth) {
  4083. upb_status_seterrf(t->status, "graph too deep to freeze (%d)", t->maxdepth);
  4084. err(t);
  4085. } else if (subobj->is_frozen || color(t, subobj) == WHITE) {
  4086. /* Do nothing: we don't want to visit or color already-frozen nodes,
  4087. * and WHITE nodes have already been assigned a SCC. */
  4088. } else if (color(t, subobj) < GREEN) {
  4089. /* Subdef has not yet been visited; recurse on it. */
  4090. do_tarjan(subobj, t);
  4091. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), lowlink(t, subobj)));
  4092. } else if (color(t, subobj) == GREEN) {
  4093. /* Subdef is in the stack and hence in the current SCC. */
  4094. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), idx(t, subobj)));
  4095. }
  4096. --t->depth;
  4097. }
  4098. static void do_tarjan(const upb_refcounted *obj, tarjan *t) {
  4099. if (color(t, obj) == BLACK) {
  4100. /* We haven't seen this object's group; mark the whole group GRAY. */
  4101. const upb_refcounted *o = obj;
  4102. do { set_gray(t, o); } while ((o = o->next) != obj);
  4103. }
  4104. push(t, obj);
  4105. visit(obj, tarjan_visit, t);
  4106. if (lowlink(t, obj) == idx(t, obj)) {
  4107. tarjan_newgroup(t);
  4108. while (pop(t) != obj)
  4109. ;
  4110. }
  4111. }
  4112. /* freeze() ------------------------------------------------------------------*/
  4113. static void crossref(const upb_refcounted *r, const upb_refcounted *subobj,
  4114. void *_t) {
  4115. tarjan *t = _t;
  4116. UPB_ASSERT(color(t, r) > BLACK);
  4117. if (color(t, subobj) > BLACK && r->group != subobj->group) {
  4118. /* Previously this ref was not reflected in subobj->group because they
  4119. * were in the same group; now that they are split a ref must be taken. */
  4120. refgroup(subobj->group);
  4121. }
  4122. }
  4123. static bool freeze(upb_refcounted *const*roots, int n, upb_status *s,
  4124. int maxdepth) {
  4125. volatile bool ret = false;
  4126. int i;
  4127. upb_inttable_iter iter;
  4128. /* We run in two passes so that we can allocate all memory before performing
  4129. * any mutation of the input -- this allows us to leave the input unchanged
  4130. * in the case of memory allocation failure. */
  4131. tarjan t;
  4132. t.index = 0;
  4133. t.depth = 0;
  4134. t.maxdepth = maxdepth;
  4135. t.status = s;
  4136. if (!upb_inttable_init(&t.objattr, UPB_CTYPE_UINT64)) goto err1;
  4137. if (!upb_inttable_init(&t.stack, UPB_CTYPE_PTR)) goto err2;
  4138. if (!upb_inttable_init(&t.groups, UPB_CTYPE_PTR)) goto err3;
  4139. if (setjmp(t.err) != 0) goto err4;
  4140. for (i = 0; i < n; i++) {
  4141. if (color(&t, roots[i]) < GREEN) {
  4142. do_tarjan(roots[i], &t);
  4143. }
  4144. }
  4145. /* If we've made it this far, no further errors are possible so it's safe to
  4146. * mutate the objects without risk of leaving them in an inconsistent state. */
  4147. ret = true;
  4148. /* The transformation that follows requires care. The preconditions are:
  4149. * - all objects in attr map are WHITE or GRAY, and are in mutable groups
  4150. * (groups of all mutable objs)
  4151. * - no ref2(to, from) refs have incremented count(to) if both "to" and
  4152. * "from" are in our attr map (this follows from invariants (2) and (3)) */
  4153. /* Pass 1: we remove WHITE objects from their mutable groups, and add them to
  4154. * new groups according to the SCC's we computed. These new groups will
  4155. * consist of only frozen objects. None will be immediately collectible,
  4156. * because WHITE objects are by definition reachable from one of "roots",
  4157. * which the caller must own refs on. */
  4158. upb_inttable_begin(&iter, &t.objattr);
  4159. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  4160. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  4161. /* Since removal from a singly-linked list requires access to the object's
  4162. * predecessor, we consider obj->next instead of obj for moving. With the
  4163. * while() loop we guarantee that we will visit every node's predecessor.
  4164. * Proof:
  4165. * 1. every node's predecessor is in our attr map.
  4166. * 2. though the loop body may change a node's predecessor, it will only
  4167. * change it to be the node we are currently operating on, so with a
  4168. * while() loop we guarantee ourselves the chance to remove each node. */
  4169. while (color(&t, obj->next) == WHITE &&
  4170. group(&t, obj->next) != obj->next->group) {
  4171. upb_refcounted *leader;
  4172. /* Remove from old group. */
  4173. upb_refcounted *move = obj->next;
  4174. if (obj == move) {
  4175. /* Removing the last object from a group. */
  4176. UPB_ASSERT(*obj->group == obj->individual_count);
  4177. upb_gfree(obj->group);
  4178. } else {
  4179. obj->next = move->next;
  4180. /* This may decrease to zero; we'll collect GRAY objects (if any) that
  4181. * remain in the group in the third pass. */
  4182. UPB_ASSERT(*move->group >= move->individual_count);
  4183. *move->group -= move->individual_count;
  4184. }
  4185. /* Add to new group. */
  4186. leader = groupleader(&t, move);
  4187. if (move == leader) {
  4188. /* First object added to new group is its leader. */
  4189. move->group = group(&t, move);
  4190. move->next = move;
  4191. *move->group = move->individual_count;
  4192. } else {
  4193. /* Group already has at least one object in it. */
  4194. UPB_ASSERT(leader->group == group(&t, move));
  4195. move->group = group(&t, move);
  4196. move->next = leader->next;
  4197. leader->next = move;
  4198. *move->group += move->individual_count;
  4199. }
  4200. move->is_frozen = true;
  4201. }
  4202. }
  4203. /* Pass 2: GRAY and WHITE objects "obj" with ref2(to, obj) references must
  4204. * increment count(to) if group(obj) != group(to) (which could now be the
  4205. * case if "to" was just frozen). */
  4206. upb_inttable_begin(&iter, &t.objattr);
  4207. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  4208. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  4209. visit(obj, crossref, &t);
  4210. }
  4211. /* Pass 3: GRAY objects are collected if their group's refcount dropped to
  4212. * zero when we removed its white nodes. This can happen if they had only
  4213. * been kept alive by virtue of sharing a group with an object that was just
  4214. * frozen.
  4215. *
  4216. * It is important that we do this last, since the GRAY object's free()
  4217. * function could call unref2() on just-frozen objects, which will decrement
  4218. * refs that were added in pass 2. */
  4219. upb_inttable_begin(&iter, &t.objattr);
  4220. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  4221. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  4222. if (obj->group == NULL || *obj->group == 0) {
  4223. if (obj->group) {
  4224. upb_refcounted *o;
  4225. /* We eagerly free() the group's count (since we can't easily determine
  4226. * the group's remaining size it's the easiest way to ensure it gets
  4227. * done). */
  4228. upb_gfree(obj->group);
  4229. /* Visit to release ref2's (done in a separate pass since release_ref2
  4230. * depends on o->group being unmodified so it can test merged()). */
  4231. o = obj;
  4232. do { visit(o, release_ref2, NULL); } while ((o = o->next) != obj);
  4233. /* Mark "group" fields as NULL so we know to free the objects later in
  4234. * this loop, but also don't try to delete the group twice. */
  4235. o = obj;
  4236. do { o->group = NULL; } while ((o = o->next) != obj);
  4237. }
  4238. freeobj(obj);
  4239. }
  4240. }
  4241. err4:
  4242. if (!ret) {
  4243. upb_inttable_begin(&iter, &t.groups);
  4244. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter))
  4245. upb_gfree(upb_value_getptr(upb_inttable_iter_value(&iter)));
  4246. }
  4247. upb_inttable_uninit(&t.groups);
  4248. err3:
  4249. upb_inttable_uninit(&t.stack);
  4250. err2:
  4251. upb_inttable_uninit(&t.objattr);
  4252. err1:
  4253. return ret;
  4254. }
  4255. /* Misc internal functions ***************************************************/
  4256. static bool merged(const upb_refcounted *r, const upb_refcounted *r2) {
  4257. return r->group == r2->group;
  4258. }
  4259. static void merge(upb_refcounted *r, upb_refcounted *from) {
  4260. upb_refcounted *base;
  4261. upb_refcounted *tmp;
  4262. if (merged(r, from)) return;
  4263. *r->group += *from->group;
  4264. upb_gfree(from->group);
  4265. base = from;
  4266. /* Set all refcount pointers in the "from" chain to the merged refcount.
  4267. *
  4268. * TODO(haberman): this linear algorithm can result in an overall O(n^2) bound
  4269. * if the user continuously extends a group by one object. Prevent this by
  4270. * using one of the techniques in this paper:
  4271. * http://bioinfo.ict.ac.cn/~dbu/AlgorithmCourses/Lectures/Union-Find-Tarjan.pdf */
  4272. do { from->group = r->group; } while ((from = from->next) != base);
  4273. /* Merge the two circularly linked lists by swapping their next pointers. */
  4274. tmp = r->next;
  4275. r->next = base->next;
  4276. base->next = tmp;
  4277. }
  4278. static void unref(const upb_refcounted *r);
  4279. static void release_ref2(const upb_refcounted *obj,
  4280. const upb_refcounted *subobj,
  4281. void *closure) {
  4282. UPB_UNUSED(closure);
  4283. untrack(subobj, obj, true);
  4284. if (!merged(obj, subobj)) {
  4285. UPB_ASSERT(subobj->is_frozen);
  4286. unref(subobj);
  4287. }
  4288. }
  4289. static void unref(const upb_refcounted *r) {
  4290. if (unrefgroup(r->group)) {
  4291. const upb_refcounted *o;
  4292. upb_gfree(r->group);
  4293. /* In two passes, since release_ref2 needs a guarantee that any subobjs
  4294. * are alive. */
  4295. o = r;
  4296. do { visit(o, release_ref2, NULL); } while((o = o->next) != r);
  4297. o = r;
  4298. do {
  4299. const upb_refcounted *next = o->next;
  4300. UPB_ASSERT(o->is_frozen || o->individual_count == 0);
  4301. freeobj((upb_refcounted*)o);
  4302. o = next;
  4303. } while(o != r);
  4304. }
  4305. }
  4306. static void freeobj(upb_refcounted *o) {
  4307. trackfree(o);
  4308. o->vtbl->free((upb_refcounted*)o);
  4309. }
  4310. /* Public interface ***********************************************************/
  4311. bool upb_refcounted_init(upb_refcounted *r,
  4312. const struct upb_refcounted_vtbl *vtbl,
  4313. const void *owner) {
  4314. #ifndef NDEBUG
  4315. /* Endianness check. This is unrelated to upb_refcounted, it's just a
  4316. * convenient place to put the check that we can be assured will run for
  4317. * basically every program using upb. */
  4318. const int x = 1;
  4319. #ifdef UPB_BIG_ENDIAN
  4320. UPB_ASSERT(*(char*)&x != 1);
  4321. #else
  4322. UPB_ASSERT(*(char*)&x == 1);
  4323. #endif
  4324. #endif
  4325. r->next = r;
  4326. r->vtbl = vtbl;
  4327. r->individual_count = 0;
  4328. r->is_frozen = false;
  4329. r->group = upb_gmalloc(sizeof(*r->group));
  4330. if (!r->group) return false;
  4331. *r->group = 0;
  4332. trackinit(r);
  4333. upb_refcounted_ref(r, owner);
  4334. return true;
  4335. }
  4336. bool upb_refcounted_isfrozen(const upb_refcounted *r) {
  4337. return r->is_frozen;
  4338. }
  4339. void upb_refcounted_ref(const upb_refcounted *r, const void *owner) {
  4340. track(r, owner, false);
  4341. if (!r->is_frozen)
  4342. ((upb_refcounted*)r)->individual_count++;
  4343. refgroup(r->group);
  4344. }
  4345. void upb_refcounted_unref(const upb_refcounted *r, const void *owner) {
  4346. untrack(r, owner, false);
  4347. if (!r->is_frozen)
  4348. ((upb_refcounted*)r)->individual_count--;
  4349. unref(r);
  4350. }
  4351. void upb_refcounted_ref2(const upb_refcounted *r, upb_refcounted *from) {
  4352. UPB_ASSERT(!from->is_frozen); /* Non-const pointer implies this. */
  4353. track(r, from, true);
  4354. if (r->is_frozen) {
  4355. refgroup(r->group);
  4356. } else {
  4357. merge((upb_refcounted*)r, from);
  4358. }
  4359. }
  4360. void upb_refcounted_unref2(const upb_refcounted *r, upb_refcounted *from) {
  4361. UPB_ASSERT(!from->is_frozen); /* Non-const pointer implies this. */
  4362. untrack(r, from, true);
  4363. if (r->is_frozen) {
  4364. unref(r);
  4365. } else {
  4366. UPB_ASSERT(merged(r, from));
  4367. }
  4368. }
  4369. void upb_refcounted_donateref(
  4370. const upb_refcounted *r, const void *from, const void *to) {
  4371. UPB_ASSERT(from != to);
  4372. if (to != NULL)
  4373. upb_refcounted_ref(r, to);
  4374. if (from != NULL)
  4375. upb_refcounted_unref(r, from);
  4376. }
  4377. void upb_refcounted_checkref(const upb_refcounted *r, const void *owner) {
  4378. checkref(r, owner, false);
  4379. }
  4380. bool upb_refcounted_freeze(upb_refcounted *const*roots, int n, upb_status *s,
  4381. int maxdepth) {
  4382. int i;
  4383. bool ret;
  4384. for (i = 0; i < n; i++) {
  4385. UPB_ASSERT(!roots[i]->is_frozen);
  4386. }
  4387. ret = freeze(roots, n, s, maxdepth);
  4388. UPB_ASSERT(!s || ret == upb_ok(s));
  4389. return ret;
  4390. }
  4391. bool upb_bufsrc_putbuf(const char *buf, size_t len, upb_bytessink *sink) {
  4392. void *subc;
  4393. bool ret;
  4394. upb_bufhandle handle;
  4395. upb_bufhandle_init(&handle);
  4396. upb_bufhandle_setbuf(&handle, buf, 0);
  4397. ret = upb_bytessink_start(sink, len, &subc);
  4398. if (ret && len != 0) {
  4399. ret = (upb_bytessink_putbuf(sink, subc, buf, len, &handle) >= len);
  4400. }
  4401. if (ret) {
  4402. ret = upb_bytessink_end(sink);
  4403. }
  4404. upb_bufhandle_uninit(&handle);
  4405. return ret;
  4406. }
  4407. struct upb_bufsink {
  4408. upb_byteshandler handler;
  4409. upb_bytessink sink;
  4410. upb_env *env;
  4411. char *ptr;
  4412. size_t len, size;
  4413. };
  4414. static void *upb_bufsink_start(void *_sink, const void *hd, size_t size_hint) {
  4415. upb_bufsink *sink = _sink;
  4416. UPB_UNUSED(hd);
  4417. UPB_UNUSED(size_hint);
  4418. sink->len = 0;
  4419. return sink;
  4420. }
  4421. static size_t upb_bufsink_string(void *_sink, const void *hd, const char *ptr,
  4422. size_t len, const upb_bufhandle *handle) {
  4423. upb_bufsink *sink = _sink;
  4424. size_t new_size = sink->size;
  4425. UPB_ASSERT(new_size > 0);
  4426. UPB_UNUSED(hd);
  4427. UPB_UNUSED(handle);
  4428. while (sink->len + len > new_size) {
  4429. new_size *= 2;
  4430. }
  4431. if (new_size != sink->size) {
  4432. sink->ptr = upb_env_realloc(sink->env, sink->ptr, sink->size, new_size);
  4433. sink->size = new_size;
  4434. }
  4435. memcpy(sink->ptr + sink->len, ptr, len);
  4436. sink->len += len;
  4437. return len;
  4438. }
  4439. upb_bufsink *upb_bufsink_new(upb_env *env) {
  4440. upb_bufsink *sink = upb_env_malloc(env, sizeof(upb_bufsink));
  4441. upb_byteshandler_init(&sink->handler);
  4442. upb_byteshandler_setstartstr(&sink->handler, upb_bufsink_start, NULL);
  4443. upb_byteshandler_setstring(&sink->handler, upb_bufsink_string, NULL);
  4444. upb_bytessink_reset(&sink->sink, &sink->handler, sink);
  4445. sink->env = env;
  4446. sink->size = 32;
  4447. sink->ptr = upb_env_malloc(env, sink->size);
  4448. sink->len = 0;
  4449. return sink;
  4450. }
  4451. void upb_bufsink_free(upb_bufsink *sink) {
  4452. upb_env_free(sink->env, sink->ptr);
  4453. upb_env_free(sink->env, sink);
  4454. }
  4455. upb_bytessink *upb_bufsink_sink(upb_bufsink *sink) {
  4456. return &sink->sink;
  4457. }
  4458. const char *upb_bufsink_getdata(const upb_bufsink *sink, size_t *len) {
  4459. *len = sink->len;
  4460. return sink->ptr;
  4461. }
  4462. /*
  4463. ** upb_table Implementation
  4464. **
  4465. ** Implementation is heavily inspired by Lua's ltable.c.
  4466. */
  4467. #include <string.h>
  4468. #define UPB_MAXARRSIZE 16 /* 64k. */
  4469. /* From Chromium. */
  4470. #define ARRAY_SIZE(x) \
  4471. ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
  4472. static void upb_check_alloc(upb_table *t, upb_alloc *a) {
  4473. UPB_UNUSED(t);
  4474. UPB_UNUSED(a);
  4475. UPB_ASSERT_DEBUGVAR(t->alloc == a);
  4476. }
  4477. static const double MAX_LOAD = 0.85;
  4478. /* The minimum utilization of the array part of a mixed hash/array table. This
  4479. * is a speed/memory-usage tradeoff (though it's not straightforward because of
  4480. * cache effects). The lower this is, the more memory we'll use. */
  4481. static const double MIN_DENSITY = 0.1;
  4482. bool is_pow2(uint64_t v) { return v == 0 || (v & (v - 1)) == 0; }
  4483. int log2ceil(uint64_t v) {
  4484. int ret = 0;
  4485. bool pow2 = is_pow2(v);
  4486. while (v >>= 1) ret++;
  4487. ret = pow2 ? ret : ret + 1; /* Ceiling. */
  4488. return UPB_MIN(UPB_MAXARRSIZE, ret);
  4489. }
  4490. char *upb_strdup(const char *s, upb_alloc *a) {
  4491. return upb_strdup2(s, strlen(s), a);
  4492. }
  4493. char *upb_strdup2(const char *s, size_t len, upb_alloc *a) {
  4494. size_t n;
  4495. char *p;
  4496. /* Prevent overflow errors. */
  4497. if (len == SIZE_MAX) return NULL;
  4498. /* Always null-terminate, even if binary data; but don't rely on the input to
  4499. * have a null-terminating byte since it may be a raw binary buffer. */
  4500. n = len + 1;
  4501. p = upb_malloc(a, n);
  4502. if (p) {
  4503. memcpy(p, s, len);
  4504. p[len] = 0;
  4505. }
  4506. return p;
  4507. }
  4508. /* A type to represent the lookup key of either a strtable or an inttable. */
  4509. typedef union {
  4510. uintptr_t num;
  4511. struct {
  4512. const char *str;
  4513. size_t len;
  4514. } str;
  4515. } lookupkey_t;
  4516. static lookupkey_t strkey2(const char *str, size_t len) {
  4517. lookupkey_t k;
  4518. k.str.str = str;
  4519. k.str.len = len;
  4520. return k;
  4521. }
  4522. static lookupkey_t intkey(uintptr_t key) {
  4523. lookupkey_t k;
  4524. k.num = key;
  4525. return k;
  4526. }
  4527. typedef uint32_t hashfunc_t(upb_tabkey key);
  4528. typedef bool eqlfunc_t(upb_tabkey k1, lookupkey_t k2);
  4529. /* Base table (shared code) ***************************************************/
  4530. /* For when we need to cast away const. */
  4531. static upb_tabent *mutable_entries(upb_table *t) {
  4532. return (upb_tabent*)t->entries;
  4533. }
  4534. static bool isfull(upb_table *t) {
  4535. if (upb_table_size(t) == 0) {
  4536. return true;
  4537. } else {
  4538. return ((double)(t->count + 1) / upb_table_size(t)) > MAX_LOAD;
  4539. }
  4540. }
  4541. static bool init(upb_table *t, upb_ctype_t ctype, uint8_t size_lg2,
  4542. upb_alloc *a) {
  4543. size_t bytes;
  4544. t->count = 0;
  4545. t->ctype = ctype;
  4546. t->size_lg2 = size_lg2;
  4547. t->mask = upb_table_size(t) ? upb_table_size(t) - 1 : 0;
  4548. #ifndef NDEBUG
  4549. t->alloc = a;
  4550. #endif
  4551. bytes = upb_table_size(t) * sizeof(upb_tabent);
  4552. if (bytes > 0) {
  4553. t->entries = upb_malloc(a, bytes);
  4554. if (!t->entries) return false;
  4555. memset(mutable_entries(t), 0, bytes);
  4556. } else {
  4557. t->entries = NULL;
  4558. }
  4559. return true;
  4560. }
  4561. static void uninit(upb_table *t, upb_alloc *a) {
  4562. upb_check_alloc(t, a);
  4563. upb_free(a, mutable_entries(t));
  4564. }
  4565. static upb_tabent *emptyent(upb_table *t) {
  4566. upb_tabent *e = mutable_entries(t) + upb_table_size(t);
  4567. while (1) { if (upb_tabent_isempty(--e)) return e; UPB_ASSERT(e > t->entries); }
  4568. }
  4569. static upb_tabent *getentry_mutable(upb_table *t, uint32_t hash) {
  4570. return (upb_tabent*)upb_getentry(t, hash);
  4571. }
  4572. static const upb_tabent *findentry(const upb_table *t, lookupkey_t key,
  4573. uint32_t hash, eqlfunc_t *eql) {
  4574. const upb_tabent *e;
  4575. if (t->size_lg2 == 0) return NULL;
  4576. e = upb_getentry(t, hash);
  4577. if (upb_tabent_isempty(e)) return NULL;
  4578. while (1) {
  4579. if (eql(e->key, key)) return e;
  4580. if ((e = e->next) == NULL) return NULL;
  4581. }
  4582. }
  4583. static upb_tabent *findentry_mutable(upb_table *t, lookupkey_t key,
  4584. uint32_t hash, eqlfunc_t *eql) {
  4585. return (upb_tabent*)findentry(t, key, hash, eql);
  4586. }
  4587. static bool lookup(const upb_table *t, lookupkey_t key, upb_value *v,
  4588. uint32_t hash, eqlfunc_t *eql) {
  4589. const upb_tabent *e = findentry(t, key, hash, eql);
  4590. if (e) {
  4591. if (v) {
  4592. _upb_value_setval(v, e->val.val, t->ctype);
  4593. }
  4594. return true;
  4595. } else {
  4596. return false;
  4597. }
  4598. }
  4599. /* The given key must not already exist in the table. */
  4600. static void insert(upb_table *t, lookupkey_t key, upb_tabkey tabkey,
  4601. upb_value val, uint32_t hash,
  4602. hashfunc_t *hashfunc, eqlfunc_t *eql) {
  4603. upb_tabent *mainpos_e;
  4604. upb_tabent *our_e;
  4605. UPB_ASSERT(findentry(t, key, hash, eql) == NULL);
  4606. UPB_ASSERT_DEBUGVAR(val.ctype == t->ctype);
  4607. t->count++;
  4608. mainpos_e = getentry_mutable(t, hash);
  4609. our_e = mainpos_e;
  4610. if (upb_tabent_isempty(mainpos_e)) {
  4611. /* Our main position is empty; use it. */
  4612. our_e->next = NULL;
  4613. } else {
  4614. /* Collision. */
  4615. upb_tabent *new_e = emptyent(t);
  4616. /* Head of collider's chain. */
  4617. upb_tabent *chain = getentry_mutable(t, hashfunc(mainpos_e->key));
  4618. if (chain == mainpos_e) {
  4619. /* Existing ent is in its main posisiton (it has the same hash as us, and
  4620. * is the head of our chain). Insert to new ent and append to this chain. */
  4621. new_e->next = mainpos_e->next;
  4622. mainpos_e->next = new_e;
  4623. our_e = new_e;
  4624. } else {
  4625. /* Existing ent is not in its main position (it is a node in some other
  4626. * chain). This implies that no existing ent in the table has our hash.
  4627. * Evict it (updating its chain) and use its ent for head of our chain. */
  4628. *new_e = *mainpos_e; /* copies next. */
  4629. while (chain->next != mainpos_e) {
  4630. chain = (upb_tabent*)chain->next;
  4631. UPB_ASSERT(chain);
  4632. }
  4633. chain->next = new_e;
  4634. our_e = mainpos_e;
  4635. our_e->next = NULL;
  4636. }
  4637. }
  4638. our_e->key = tabkey;
  4639. our_e->val.val = val.val;
  4640. UPB_ASSERT(findentry(t, key, hash, eql) == our_e);
  4641. }
  4642. static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
  4643. upb_tabkey *removed, uint32_t hash, eqlfunc_t *eql) {
  4644. upb_tabent *chain = getentry_mutable(t, hash);
  4645. if (upb_tabent_isempty(chain)) return false;
  4646. if (eql(chain->key, key)) {
  4647. /* Element to remove is at the head of its chain. */
  4648. t->count--;
  4649. if (val) _upb_value_setval(val, chain->val.val, t->ctype);
  4650. if (removed) *removed = chain->key;
  4651. if (chain->next) {
  4652. upb_tabent *move = (upb_tabent*)chain->next;
  4653. *chain = *move;
  4654. move->key = 0; /* Make the slot empty. */
  4655. } else {
  4656. chain->key = 0; /* Make the slot empty. */
  4657. }
  4658. return true;
  4659. } else {
  4660. /* Element to remove is either in a non-head position or not in the
  4661. * table. */
  4662. while (chain->next && !eql(chain->next->key, key)) {
  4663. chain = (upb_tabent*)chain->next;
  4664. }
  4665. if (chain->next) {
  4666. /* Found element to remove. */
  4667. upb_tabent *rm = (upb_tabent*)chain->next;
  4668. t->count--;
  4669. if (val) _upb_value_setval(val, chain->next->val.val, t->ctype);
  4670. if (removed) *removed = rm->key;
  4671. rm->key = 0; /* Make the slot empty. */
  4672. chain->next = rm->next;
  4673. return true;
  4674. } else {
  4675. /* Element to remove is not in the table. */
  4676. return false;
  4677. }
  4678. }
  4679. }
  4680. static size_t next(const upb_table *t, size_t i) {
  4681. do {
  4682. if (++i >= upb_table_size(t))
  4683. return SIZE_MAX;
  4684. } while(upb_tabent_isempty(&t->entries[i]));
  4685. return i;
  4686. }
  4687. static size_t begin(const upb_table *t) {
  4688. return next(t, -1);
  4689. }
  4690. /* upb_strtable ***************************************************************/
  4691. /* A simple "subclass" of upb_table that only adds a hash function for strings. */
  4692. static upb_tabkey strcopy(lookupkey_t k2, upb_alloc *a) {
  4693. char *str = upb_malloc(a, k2.str.len + sizeof(uint32_t) + 1);
  4694. if (str == NULL) return 0;
  4695. memcpy(str, &k2.str.len, sizeof(uint32_t));
  4696. memcpy(str + sizeof(uint32_t), k2.str.str, k2.str.len + 1);
  4697. return (uintptr_t)str;
  4698. }
  4699. static uint32_t strhash(upb_tabkey key) {
  4700. uint32_t len;
  4701. char *str = upb_tabstr(key, &len);
  4702. return MurmurHash2(str, len, 0);
  4703. }
  4704. static bool streql(upb_tabkey k1, lookupkey_t k2) {
  4705. uint32_t len;
  4706. char *str = upb_tabstr(k1, &len);
  4707. return len == k2.str.len && memcmp(str, k2.str.str, len) == 0;
  4708. }
  4709. bool upb_strtable_init2(upb_strtable *t, upb_ctype_t ctype, upb_alloc *a) {
  4710. return init(&t->t, ctype, 2, a);
  4711. }
  4712. void upb_strtable_uninit2(upb_strtable *t, upb_alloc *a) {
  4713. size_t i;
  4714. for (i = 0; i < upb_table_size(&t->t); i++)
  4715. upb_free(a, (void*)t->t.entries[i].key);
  4716. uninit(&t->t, a);
  4717. }
  4718. bool upb_strtable_resize(upb_strtable *t, size_t size_lg2, upb_alloc *a) {
  4719. upb_strtable new_table;
  4720. upb_strtable_iter i;
  4721. upb_check_alloc(&t->t, a);
  4722. if (!init(&new_table.t, t->t.ctype, size_lg2, a))
  4723. return false;
  4724. upb_strtable_begin(&i, t);
  4725. for ( ; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  4726. upb_strtable_insert3(
  4727. &new_table,
  4728. upb_strtable_iter_key(&i),
  4729. upb_strtable_iter_keylength(&i),
  4730. upb_strtable_iter_value(&i),
  4731. a);
  4732. }
  4733. upb_strtable_uninit2(t, a);
  4734. *t = new_table;
  4735. return true;
  4736. }
  4737. bool upb_strtable_insert3(upb_strtable *t, const char *k, size_t len,
  4738. upb_value v, upb_alloc *a) {
  4739. lookupkey_t key;
  4740. upb_tabkey tabkey;
  4741. uint32_t hash;
  4742. upb_check_alloc(&t->t, a);
  4743. if (isfull(&t->t)) {
  4744. /* Need to resize. New table of double the size, add old elements to it. */
  4745. if (!upb_strtable_resize(t, t->t.size_lg2 + 1, a)) {
  4746. return false;
  4747. }
  4748. }
  4749. key = strkey2(k, len);
  4750. tabkey = strcopy(key, a);
  4751. if (tabkey == 0) return false;
  4752. hash = MurmurHash2(key.str.str, key.str.len, 0);
  4753. insert(&t->t, key, tabkey, v, hash, &strhash, &streql);
  4754. return true;
  4755. }
  4756. bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
  4757. upb_value *v) {
  4758. uint32_t hash = MurmurHash2(key, len, 0);
  4759. return lookup(&t->t, strkey2(key, len), v, hash, &streql);
  4760. }
  4761. bool upb_strtable_remove3(upb_strtable *t, const char *key, size_t len,
  4762. upb_value *val, upb_alloc *alloc) {
  4763. uint32_t hash = MurmurHash2(key, len, 0);
  4764. upb_tabkey tabkey;
  4765. if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
  4766. upb_free(alloc, (void*)tabkey);
  4767. return true;
  4768. } else {
  4769. return false;
  4770. }
  4771. }
  4772. /* Iteration */
  4773. static const upb_tabent *str_tabent(const upb_strtable_iter *i) {
  4774. return &i->t->t.entries[i->index];
  4775. }
  4776. void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t) {
  4777. i->t = t;
  4778. i->index = begin(&t->t);
  4779. }
  4780. void upb_strtable_next(upb_strtable_iter *i) {
  4781. i->index = next(&i->t->t, i->index);
  4782. }
  4783. bool upb_strtable_done(const upb_strtable_iter *i) {
  4784. return i->index >= upb_table_size(&i->t->t) ||
  4785. upb_tabent_isempty(str_tabent(i));
  4786. }
  4787. const char *upb_strtable_iter_key(const upb_strtable_iter *i) {
  4788. UPB_ASSERT(!upb_strtable_done(i));
  4789. return upb_tabstr(str_tabent(i)->key, NULL);
  4790. }
  4791. size_t upb_strtable_iter_keylength(const upb_strtable_iter *i) {
  4792. uint32_t len;
  4793. UPB_ASSERT(!upb_strtable_done(i));
  4794. upb_tabstr(str_tabent(i)->key, &len);
  4795. return len;
  4796. }
  4797. upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
  4798. UPB_ASSERT(!upb_strtable_done(i));
  4799. return _upb_value_val(str_tabent(i)->val.val, i->t->t.ctype);
  4800. }
  4801. void upb_strtable_iter_setdone(upb_strtable_iter *i) {
  4802. i->index = SIZE_MAX;
  4803. }
  4804. bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
  4805. const upb_strtable_iter *i2) {
  4806. if (upb_strtable_done(i1) && upb_strtable_done(i2))
  4807. return true;
  4808. return i1->t == i2->t && i1->index == i2->index;
  4809. }
  4810. /* upb_inttable ***************************************************************/
  4811. /* For inttables we use a hybrid structure where small keys are kept in an
  4812. * array and large keys are put in the hash table. */
  4813. static uint32_t inthash(upb_tabkey key) { return upb_inthash(key); }
  4814. static bool inteql(upb_tabkey k1, lookupkey_t k2) {
  4815. return k1 == k2.num;
  4816. }
  4817. static upb_tabval *mutable_array(upb_inttable *t) {
  4818. return (upb_tabval*)t->array;
  4819. }
  4820. static upb_tabval *inttable_val(upb_inttable *t, uintptr_t key) {
  4821. if (key < t->array_size) {
  4822. return upb_arrhas(t->array[key]) ? &(mutable_array(t)[key]) : NULL;
  4823. } else {
  4824. upb_tabent *e =
  4825. findentry_mutable(&t->t, intkey(key), upb_inthash(key), &inteql);
  4826. return e ? &e->val : NULL;
  4827. }
  4828. }
  4829. static const upb_tabval *inttable_val_const(const upb_inttable *t,
  4830. uintptr_t key) {
  4831. return inttable_val((upb_inttable*)t, key);
  4832. }
  4833. size_t upb_inttable_count(const upb_inttable *t) {
  4834. return t->t.count + t->array_count;
  4835. }
  4836. static void check(upb_inttable *t) {
  4837. UPB_UNUSED(t);
  4838. #if defined(UPB_DEBUG_TABLE) && !defined(NDEBUG)
  4839. {
  4840. /* This check is very expensive (makes inserts/deletes O(N)). */
  4841. size_t count = 0;
  4842. upb_inttable_iter i;
  4843. upb_inttable_begin(&i, t);
  4844. for(; !upb_inttable_done(&i); upb_inttable_next(&i), count++) {
  4845. UPB_ASSERT(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
  4846. }
  4847. UPB_ASSERT(count == upb_inttable_count(t));
  4848. }
  4849. #endif
  4850. }
  4851. bool upb_inttable_sizedinit(upb_inttable *t, upb_ctype_t ctype,
  4852. size_t asize, int hsize_lg2, upb_alloc *a) {
  4853. size_t array_bytes;
  4854. if (!init(&t->t, ctype, hsize_lg2, a)) return false;
  4855. /* Always make the array part at least 1 long, so that we know key 0
  4856. * won't be in the hash part, which simplifies things. */
  4857. t->array_size = UPB_MAX(1, asize);
  4858. t->array_count = 0;
  4859. array_bytes = t->array_size * sizeof(upb_value);
  4860. t->array = upb_malloc(a, array_bytes);
  4861. if (!t->array) {
  4862. uninit(&t->t, a);
  4863. return false;
  4864. }
  4865. memset(mutable_array(t), 0xff, array_bytes);
  4866. check(t);
  4867. return true;
  4868. }
  4869. bool upb_inttable_init2(upb_inttable *t, upb_ctype_t ctype, upb_alloc *a) {
  4870. return upb_inttable_sizedinit(t, ctype, 0, 4, a);
  4871. }
  4872. void upb_inttable_uninit2(upb_inttable *t, upb_alloc *a) {
  4873. uninit(&t->t, a);
  4874. upb_free(a, mutable_array(t));
  4875. }
  4876. bool upb_inttable_insert2(upb_inttable *t, uintptr_t key, upb_value val,
  4877. upb_alloc *a) {
  4878. upb_tabval tabval;
  4879. tabval.val = val.val;
  4880. UPB_ASSERT(upb_arrhas(tabval)); /* This will reject (uint64_t)-1. Fix this. */
  4881. upb_check_alloc(&t->t, a);
  4882. if (key < t->array_size) {
  4883. UPB_ASSERT(!upb_arrhas(t->array[key]));
  4884. t->array_count++;
  4885. mutable_array(t)[key].val = val.val;
  4886. } else {
  4887. if (isfull(&t->t)) {
  4888. /* Need to resize the hash part, but we re-use the array part. */
  4889. size_t i;
  4890. upb_table new_table;
  4891. if (!init(&new_table, t->t.ctype, t->t.size_lg2 + 1, a)) {
  4892. return false;
  4893. }
  4894. for (i = begin(&t->t); i < upb_table_size(&t->t); i = next(&t->t, i)) {
  4895. const upb_tabent *e = &t->t.entries[i];
  4896. uint32_t hash;
  4897. upb_value v;
  4898. _upb_value_setval(&v, e->val.val, t->t.ctype);
  4899. hash = upb_inthash(e->key);
  4900. insert(&new_table, intkey(e->key), e->key, v, hash, &inthash, &inteql);
  4901. }
  4902. UPB_ASSERT(t->t.count == new_table.count);
  4903. uninit(&t->t, a);
  4904. t->t = new_table;
  4905. }
  4906. insert(&t->t, intkey(key), key, val, upb_inthash(key), &inthash, &inteql);
  4907. }
  4908. check(t);
  4909. return true;
  4910. }
  4911. bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v) {
  4912. const upb_tabval *table_v = inttable_val_const(t, key);
  4913. if (!table_v) return false;
  4914. if (v) _upb_value_setval(v, table_v->val, t->t.ctype);
  4915. return true;
  4916. }
  4917. bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val) {
  4918. upb_tabval *table_v = inttable_val(t, key);
  4919. if (!table_v) return false;
  4920. table_v->val = val.val;
  4921. return true;
  4922. }
  4923. bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val) {
  4924. bool success;
  4925. if (key < t->array_size) {
  4926. if (upb_arrhas(t->array[key])) {
  4927. upb_tabval empty = UPB_TABVALUE_EMPTY_INIT;
  4928. t->array_count--;
  4929. if (val) {
  4930. _upb_value_setval(val, t->array[key].val, t->t.ctype);
  4931. }
  4932. mutable_array(t)[key] = empty;
  4933. success = true;
  4934. } else {
  4935. success = false;
  4936. }
  4937. } else {
  4938. success = rm(&t->t, intkey(key), val, NULL, upb_inthash(key), &inteql);
  4939. }
  4940. check(t);
  4941. return success;
  4942. }
  4943. bool upb_inttable_push2(upb_inttable *t, upb_value val, upb_alloc *a) {
  4944. upb_check_alloc(&t->t, a);
  4945. return upb_inttable_insert2(t, upb_inttable_count(t), val, a);
  4946. }
  4947. upb_value upb_inttable_pop(upb_inttable *t) {
  4948. upb_value val;
  4949. bool ok = upb_inttable_remove(t, upb_inttable_count(t) - 1, &val);
  4950. UPB_ASSERT(ok);
  4951. return val;
  4952. }
  4953. bool upb_inttable_insertptr2(upb_inttable *t, const void *key, upb_value val,
  4954. upb_alloc *a) {
  4955. upb_check_alloc(&t->t, a);
  4956. return upb_inttable_insert2(t, (uintptr_t)key, val, a);
  4957. }
  4958. bool upb_inttable_lookupptr(const upb_inttable *t, const void *key,
  4959. upb_value *v) {
  4960. return upb_inttable_lookup(t, (uintptr_t)key, v);
  4961. }
  4962. bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val) {
  4963. return upb_inttable_remove(t, (uintptr_t)key, val);
  4964. }
  4965. void upb_inttable_compact2(upb_inttable *t, upb_alloc *a) {
  4966. /* A power-of-two histogram of the table keys. */
  4967. size_t counts[UPB_MAXARRSIZE + 1] = {0};
  4968. /* The max key in each bucket. */
  4969. uintptr_t max[UPB_MAXARRSIZE + 1] = {0};
  4970. upb_inttable_iter i;
  4971. size_t arr_count;
  4972. int size_lg2;
  4973. upb_inttable new_t;
  4974. upb_check_alloc(&t->t, a);
  4975. upb_inttable_begin(&i, t);
  4976. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  4977. uintptr_t key = upb_inttable_iter_key(&i);
  4978. int bucket = log2ceil(key);
  4979. max[bucket] = UPB_MAX(max[bucket], key);
  4980. counts[bucket]++;
  4981. }
  4982. /* Find the largest power of two that satisfies the MIN_DENSITY
  4983. * definition (while actually having some keys). */
  4984. arr_count = upb_inttable_count(t);
  4985. for (size_lg2 = ARRAY_SIZE(counts) - 1; size_lg2 > 0; size_lg2--) {
  4986. if (counts[size_lg2] == 0) {
  4987. /* We can halve again without losing any entries. */
  4988. continue;
  4989. } else if (arr_count >= (1 << size_lg2) * MIN_DENSITY) {
  4990. break;
  4991. }
  4992. arr_count -= counts[size_lg2];
  4993. }
  4994. UPB_ASSERT(arr_count <= upb_inttable_count(t));
  4995. {
  4996. /* Insert all elements into new, perfectly-sized table. */
  4997. size_t arr_size = max[size_lg2] + 1; /* +1 so arr[max] will fit. */
  4998. size_t hash_count = upb_inttable_count(t) - arr_count;
  4999. size_t hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
  5000. size_t hashsize_lg2 = log2ceil(hash_size);
  5001. upb_inttable_sizedinit(&new_t, t->t.ctype, arr_size, hashsize_lg2, a);
  5002. upb_inttable_begin(&i, t);
  5003. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5004. uintptr_t k = upb_inttable_iter_key(&i);
  5005. upb_inttable_insert2(&new_t, k, upb_inttable_iter_value(&i), a);
  5006. }
  5007. UPB_ASSERT(new_t.array_size == arr_size);
  5008. UPB_ASSERT(new_t.t.size_lg2 == hashsize_lg2);
  5009. }
  5010. upb_inttable_uninit2(t, a);
  5011. *t = new_t;
  5012. }
  5013. /* Iteration. */
  5014. static const upb_tabent *int_tabent(const upb_inttable_iter *i) {
  5015. UPB_ASSERT(!i->array_part);
  5016. return &i->t->t.entries[i->index];
  5017. }
  5018. static upb_tabval int_arrent(const upb_inttable_iter *i) {
  5019. UPB_ASSERT(i->array_part);
  5020. return i->t->array[i->index];
  5021. }
  5022. void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t) {
  5023. i->t = t;
  5024. i->index = -1;
  5025. i->array_part = true;
  5026. upb_inttable_next(i);
  5027. }
  5028. void upb_inttable_next(upb_inttable_iter *iter) {
  5029. const upb_inttable *t = iter->t;
  5030. if (iter->array_part) {
  5031. while (++iter->index < t->array_size) {
  5032. if (upb_arrhas(int_arrent(iter))) {
  5033. return;
  5034. }
  5035. }
  5036. iter->array_part = false;
  5037. iter->index = begin(&t->t);
  5038. } else {
  5039. iter->index = next(&t->t, iter->index);
  5040. }
  5041. }
  5042. bool upb_inttable_done(const upb_inttable_iter *i) {
  5043. if (i->array_part) {
  5044. return i->index >= i->t->array_size ||
  5045. !upb_arrhas(int_arrent(i));
  5046. } else {
  5047. return i->index >= upb_table_size(&i->t->t) ||
  5048. upb_tabent_isempty(int_tabent(i));
  5049. }
  5050. }
  5051. uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i) {
  5052. UPB_ASSERT(!upb_inttable_done(i));
  5053. return i->array_part ? i->index : int_tabent(i)->key;
  5054. }
  5055. upb_value upb_inttable_iter_value(const upb_inttable_iter *i) {
  5056. UPB_ASSERT(!upb_inttable_done(i));
  5057. return _upb_value_val(
  5058. i->array_part ? i->t->array[i->index].val : int_tabent(i)->val.val,
  5059. i->t->t.ctype);
  5060. }
  5061. void upb_inttable_iter_setdone(upb_inttable_iter *i) {
  5062. i->index = SIZE_MAX;
  5063. i->array_part = false;
  5064. }
  5065. bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
  5066. const upb_inttable_iter *i2) {
  5067. if (upb_inttable_done(i1) && upb_inttable_done(i2))
  5068. return true;
  5069. return i1->t == i2->t && i1->index == i2->index &&
  5070. i1->array_part == i2->array_part;
  5071. }
  5072. #ifdef UPB_UNALIGNED_READS_OK
  5073. /* -----------------------------------------------------------------------------
  5074. * MurmurHash2, by Austin Appleby (released as public domain).
  5075. * Reformatted and C99-ified by Joshua Haberman.
  5076. * Note - This code makes a few assumptions about how your machine behaves -
  5077. * 1. We can read a 4-byte value from any address without crashing
  5078. * 2. sizeof(int) == 4 (in upb this limitation is removed by using uint32_t
  5079. * And it has a few limitations -
  5080. * 1. It will not work incrementally.
  5081. * 2. It will not produce the same results on little-endian and big-endian
  5082. * machines. */
  5083. uint32_t MurmurHash2(const void *key, size_t len, uint32_t seed) {
  5084. /* 'm' and 'r' are mixing constants generated offline.
  5085. * They're not really 'magic', they just happen to work well. */
  5086. const uint32_t m = 0x5bd1e995;
  5087. const int32_t r = 24;
  5088. /* Initialize the hash to a 'random' value */
  5089. uint32_t h = seed ^ len;
  5090. /* Mix 4 bytes at a time into the hash */
  5091. const uint8_t * data = (const uint8_t *)key;
  5092. while(len >= 4) {
  5093. uint32_t k = *(uint32_t *)data;
  5094. k *= m;
  5095. k ^= k >> r;
  5096. k *= m;
  5097. h *= m;
  5098. h ^= k;
  5099. data += 4;
  5100. len -= 4;
  5101. }
  5102. /* Handle the last few bytes of the input array */
  5103. switch(len) {
  5104. case 3: h ^= data[2] << 16;
  5105. case 2: h ^= data[1] << 8;
  5106. case 1: h ^= data[0]; h *= m;
  5107. };
  5108. /* Do a few final mixes of the hash to ensure the last few
  5109. * bytes are well-incorporated. */
  5110. h ^= h >> 13;
  5111. h *= m;
  5112. h ^= h >> 15;
  5113. return h;
  5114. }
  5115. #else /* !UPB_UNALIGNED_READS_OK */
  5116. /* -----------------------------------------------------------------------------
  5117. * MurmurHashAligned2, by Austin Appleby
  5118. * Same algorithm as MurmurHash2, but only does aligned reads - should be safer
  5119. * on certain platforms.
  5120. * Performance will be lower than MurmurHash2 */
  5121. #define MIX(h,k,m) { k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; }
  5122. uint32_t MurmurHash2(const void * key, size_t len, uint32_t seed) {
  5123. const uint32_t m = 0x5bd1e995;
  5124. const int32_t r = 24;
  5125. const uint8_t * data = (const uint8_t *)key;
  5126. uint32_t h = seed ^ len;
  5127. uint8_t align = (uintptr_t)data & 3;
  5128. if(align && (len >= 4)) {
  5129. /* Pre-load the temp registers */
  5130. uint32_t t = 0, d = 0;
  5131. int32_t sl;
  5132. int32_t sr;
  5133. switch(align) {
  5134. case 1: t |= data[2] << 16;
  5135. case 2: t |= data[1] << 8;
  5136. case 3: t |= data[0];
  5137. }
  5138. t <<= (8 * align);
  5139. data += 4-align;
  5140. len -= 4-align;
  5141. sl = 8 * (4-align);
  5142. sr = 8 * align;
  5143. /* Mix */
  5144. while(len >= 4) {
  5145. uint32_t k;
  5146. d = *(uint32_t *)data;
  5147. t = (t >> sr) | (d << sl);
  5148. k = t;
  5149. MIX(h,k,m);
  5150. t = d;
  5151. data += 4;
  5152. len -= 4;
  5153. }
  5154. /* Handle leftover data in temp registers */
  5155. d = 0;
  5156. if(len >= align) {
  5157. uint32_t k;
  5158. switch(align) {
  5159. case 3: d |= data[2] << 16;
  5160. case 2: d |= data[1] << 8;
  5161. case 1: d |= data[0];
  5162. }
  5163. k = (t >> sr) | (d << sl);
  5164. MIX(h,k,m);
  5165. data += align;
  5166. len -= align;
  5167. /* ----------
  5168. * Handle tail bytes */
  5169. switch(len) {
  5170. case 3: h ^= data[2] << 16;
  5171. case 2: h ^= data[1] << 8;
  5172. case 1: h ^= data[0]; h *= m;
  5173. };
  5174. } else {
  5175. switch(len) {
  5176. case 3: d |= data[2] << 16;
  5177. case 2: d |= data[1] << 8;
  5178. case 1: d |= data[0];
  5179. case 0: h ^= (t >> sr) | (d << sl); h *= m;
  5180. }
  5181. }
  5182. h ^= h >> 13;
  5183. h *= m;
  5184. h ^= h >> 15;
  5185. return h;
  5186. } else {
  5187. while(len >= 4) {
  5188. uint32_t k = *(uint32_t *)data;
  5189. MIX(h,k,m);
  5190. data += 4;
  5191. len -= 4;
  5192. }
  5193. /* ----------
  5194. * Handle tail bytes */
  5195. switch(len) {
  5196. case 3: h ^= data[2] << 16;
  5197. case 2: h ^= data[1] << 8;
  5198. case 1: h ^= data[0]; h *= m;
  5199. };
  5200. h ^= h >> 13;
  5201. h *= m;
  5202. h ^= h >> 15;
  5203. return h;
  5204. }
  5205. }
  5206. #undef MIX
  5207. #endif /* UPB_UNALIGNED_READS_OK */
  5208. #include <errno.h>
  5209. #include <stdarg.h>
  5210. #include <stddef.h>
  5211. #include <stdint.h>
  5212. #include <stdio.h>
  5213. #include <stdlib.h>
  5214. #include <string.h>
  5215. bool upb_dumptostderr(void *closure, const upb_status* status) {
  5216. UPB_UNUSED(closure);
  5217. fprintf(stderr, "%s\n", upb_status_errmsg(status));
  5218. return false;
  5219. }
  5220. /* Guarantee null-termination and provide ellipsis truncation.
  5221. * It may be tempting to "optimize" this by initializing these final
  5222. * four bytes up-front and then being careful never to overwrite them,
  5223. * this is safer and simpler. */
  5224. static void nullz(upb_status *status) {
  5225. const char *ellipsis = "...";
  5226. size_t len = strlen(ellipsis);
  5227. UPB_ASSERT(sizeof(status->msg) > len);
  5228. memcpy(status->msg + sizeof(status->msg) - len, ellipsis, len);
  5229. }
  5230. /* upb_upberr *****************************************************************/
  5231. upb_errorspace upb_upberr = {"upb error"};
  5232. void upb_upberr_setoom(upb_status *status) {
  5233. status->error_space_ = &upb_upberr;
  5234. upb_status_seterrmsg(status, "Out of memory");
  5235. }
  5236. /* upb_status *****************************************************************/
  5237. void upb_status_clear(upb_status *status) {
  5238. if (!status) return;
  5239. status->ok_ = true;
  5240. status->code_ = 0;
  5241. status->msg[0] = '\0';
  5242. }
  5243. bool upb_ok(const upb_status *status) { return status->ok_; }
  5244. upb_errorspace *upb_status_errspace(const upb_status *status) {
  5245. return status->error_space_;
  5246. }
  5247. int upb_status_errcode(const upb_status *status) { return status->code_; }
  5248. const char *upb_status_errmsg(const upb_status *status) { return status->msg; }
  5249. void upb_status_seterrmsg(upb_status *status, const char *msg) {
  5250. if (!status) return;
  5251. status->ok_ = false;
  5252. strncpy(status->msg, msg, sizeof(status->msg));
  5253. nullz(status);
  5254. }
  5255. void upb_status_seterrf(upb_status *status, const char *fmt, ...) {
  5256. va_list args;
  5257. va_start(args, fmt);
  5258. upb_status_vseterrf(status, fmt, args);
  5259. va_end(args);
  5260. }
  5261. void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args) {
  5262. if (!status) return;
  5263. status->ok_ = false;
  5264. _upb_vsnprintf(status->msg, sizeof(status->msg), fmt, args);
  5265. nullz(status);
  5266. }
  5267. void upb_status_copy(upb_status *to, const upb_status *from) {
  5268. if (!to) return;
  5269. *to = *from;
  5270. }
  5271. /* upb_alloc ******************************************************************/
  5272. static void *upb_global_allocfunc(upb_alloc *alloc, void *ptr, size_t oldsize,
  5273. size_t size) {
  5274. UPB_UNUSED(alloc);
  5275. UPB_UNUSED(oldsize);
  5276. if (size == 0) {
  5277. free(ptr);
  5278. return NULL;
  5279. } else {
  5280. return realloc(ptr, size);
  5281. }
  5282. }
  5283. upb_alloc upb_alloc_global = {&upb_global_allocfunc};
  5284. /* upb_arena ******************************************************************/
  5285. /* Be conservative and choose 16 in case anyone is using SSE. */
  5286. static const size_t maxalign = 16;
  5287. static size_t align_up_max(size_t size) {
  5288. return ((size + maxalign - 1) / maxalign) * maxalign;
  5289. }
  5290. typedef struct mem_block {
  5291. struct mem_block *next;
  5292. size_t size;
  5293. size_t used;
  5294. bool owned;
  5295. /* Data follows. */
  5296. } mem_block;
  5297. typedef struct cleanup_ent {
  5298. struct cleanup_ent *next;
  5299. upb_cleanup_func *cleanup;
  5300. void *ud;
  5301. } cleanup_ent;
  5302. static void upb_arena_addblock(upb_arena *a, void *ptr, size_t size,
  5303. bool owned) {
  5304. mem_block *block = ptr;
  5305. block->next = a->block_head;
  5306. block->size = size;
  5307. block->used = align_up_max(sizeof(mem_block));
  5308. block->owned = owned;
  5309. a->block_head = block;
  5310. /* TODO(haberman): ASAN poison. */
  5311. }
  5312. static mem_block *upb_arena_allocblock(upb_arena *a, size_t size) {
  5313. size_t block_size = UPB_MAX(size, a->next_block_size) + sizeof(mem_block);
  5314. mem_block *block = upb_malloc(a->block_alloc, block_size);
  5315. if (!block) {
  5316. return NULL;
  5317. }
  5318. upb_arena_addblock(a, block, block_size, true);
  5319. a->next_block_size = UPB_MIN(block_size * 2, a->max_block_size);
  5320. return block;
  5321. }
  5322. static void *upb_arena_doalloc(upb_alloc *alloc, void *ptr, size_t oldsize,
  5323. size_t size) {
  5324. upb_arena *a = (upb_arena*)alloc; /* upb_alloc is initial member. */
  5325. mem_block *block = a->block_head;
  5326. void *ret;
  5327. if (size == 0) {
  5328. return NULL; /* We are an arena, don't need individual frees. */
  5329. }
  5330. size = align_up_max(size);
  5331. /* TODO(haberman): special-case if this is a realloc of the last alloc? */
  5332. if (!block || block->size - block->used < size) {
  5333. /* Slow path: have to allocate a new block. */
  5334. block = upb_arena_allocblock(a, size);
  5335. if (!block) {
  5336. return NULL; /* Out of memory. */
  5337. }
  5338. }
  5339. ret = (char*)block + block->used;
  5340. block->used += size;
  5341. if (oldsize > 0) {
  5342. memcpy(ret, ptr, oldsize); /* Preserve existing data. */
  5343. }
  5344. /* TODO(haberman): ASAN unpoison. */
  5345. a->bytes_allocated += size;
  5346. return ret;
  5347. }
  5348. /* Public Arena API ***********************************************************/
  5349. void upb_arena_init(upb_arena *a) {
  5350. a->alloc.func = &upb_arena_doalloc;
  5351. a->block_alloc = &upb_alloc_global;
  5352. a->bytes_allocated = 0;
  5353. a->next_block_size = 256;
  5354. a->max_block_size = 16384;
  5355. a->cleanup_head = NULL;
  5356. a->block_head = NULL;
  5357. }
  5358. void upb_arena_init2(upb_arena *a, void *mem, size_t size, upb_alloc *alloc) {
  5359. upb_arena_init(a);
  5360. if (size > sizeof(mem_block)) {
  5361. upb_arena_addblock(a, mem, size, false);
  5362. }
  5363. if (alloc) {
  5364. a->block_alloc = alloc;
  5365. }
  5366. }
  5367. void upb_arena_uninit(upb_arena *a) {
  5368. cleanup_ent *ent = a->cleanup_head;
  5369. mem_block *block = a->block_head;
  5370. while (ent) {
  5371. ent->cleanup(ent->ud);
  5372. ent = ent->next;
  5373. }
  5374. /* Must do this after running cleanup functions, because this will delete
  5375. * the memory we store our cleanup entries in! */
  5376. while (block) {
  5377. mem_block *next = block->next;
  5378. if (block->owned) {
  5379. upb_free(a->block_alloc, block);
  5380. }
  5381. block = next;
  5382. }
  5383. /* Protect against multiple-uninit. */
  5384. a->cleanup_head = NULL;
  5385. a->block_head = NULL;
  5386. }
  5387. bool upb_arena_addcleanup(upb_arena *a, upb_cleanup_func *func, void *ud) {
  5388. cleanup_ent *ent = upb_malloc(&a->alloc, sizeof(cleanup_ent));
  5389. if (!ent) {
  5390. return false; /* Out of memory. */
  5391. }
  5392. ent->cleanup = func;
  5393. ent->ud = ud;
  5394. ent->next = a->cleanup_head;
  5395. a->cleanup_head = ent;
  5396. return true;
  5397. }
  5398. size_t upb_arena_bytesallocated(const upb_arena *a) {
  5399. return a->bytes_allocated;
  5400. }
  5401. /* Standard error functions ***************************************************/
  5402. static bool default_err(void *ud, const upb_status *status) {
  5403. UPB_UNUSED(ud);
  5404. UPB_UNUSED(status);
  5405. return false;
  5406. }
  5407. static bool write_err_to(void *ud, const upb_status *status) {
  5408. upb_status *copy_to = ud;
  5409. upb_status_copy(copy_to, status);
  5410. return false;
  5411. }
  5412. /* upb_env ********************************************************************/
  5413. void upb_env_initonly(upb_env *e) {
  5414. e->ok_ = true;
  5415. e->error_func_ = &default_err;
  5416. e->error_ud_ = NULL;
  5417. }
  5418. void upb_env_init(upb_env *e) {
  5419. upb_arena_init(&e->arena_);
  5420. upb_env_initonly(e);
  5421. }
  5422. void upb_env_init2(upb_env *e, void *mem, size_t n, upb_alloc *alloc) {
  5423. upb_arena_init2(&e->arena_, mem, n, alloc);
  5424. upb_env_initonly(e);
  5425. }
  5426. void upb_env_uninit(upb_env *e) {
  5427. upb_arena_uninit(&e->arena_);
  5428. }
  5429. void upb_env_seterrorfunc(upb_env *e, upb_error_func *func, void *ud) {
  5430. e->error_func_ = func;
  5431. e->error_ud_ = ud;
  5432. }
  5433. void upb_env_reporterrorsto(upb_env *e, upb_status *s) {
  5434. e->error_func_ = &write_err_to;
  5435. e->error_ud_ = s;
  5436. }
  5437. bool upb_env_reporterror(upb_env *e, const upb_status *status) {
  5438. e->ok_ = false;
  5439. return e->error_func_(e->error_ud_, status);
  5440. }
  5441. void *upb_env_malloc(upb_env *e, size_t size) {
  5442. return upb_malloc(&e->arena_.alloc, size);
  5443. }
  5444. void *upb_env_realloc(upb_env *e, void *ptr, size_t oldsize, size_t size) {
  5445. return upb_realloc(&e->arena_.alloc, ptr, oldsize, size);
  5446. }
  5447. void upb_env_free(upb_env *e, void *ptr) {
  5448. upb_free(&e->arena_.alloc, ptr);
  5449. }
  5450. bool upb_env_addcleanup(upb_env *e, upb_cleanup_func *func, void *ud) {
  5451. return upb_arena_addcleanup(&e->arena_, func, ud);
  5452. }
  5453. size_t upb_env_bytesallocated(const upb_env *e) {
  5454. return upb_arena_bytesallocated(&e->arena_);
  5455. }
  5456. /* This file was generated by upbc (the upb compiler) from the input
  5457. * file:
  5458. *
  5459. * upb/descriptor/descriptor.proto
  5460. *
  5461. * Do not edit -- your changes will be discarded when the file is
  5462. * regenerated. */
  5463. static const upb_msgdef msgs[22];
  5464. static const upb_fielddef fields[105];
  5465. static const upb_enumdef enums[5];
  5466. static const upb_tabent strentries[236];
  5467. static const upb_tabent intentries[18];
  5468. static const upb_tabval arrays[184];
  5469. #ifdef UPB_DEBUG_REFS
  5470. static upb_inttable reftables[264];
  5471. #endif
  5472. static const upb_msgdef msgs[22] = {
  5473. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto", 40, 8, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[0], 11, 10), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[0]), false, UPB_SYNTAX_PROTO2, &reftables[0], &reftables[1]),
  5474. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ExtensionRange", 4, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[11], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[16]), false, UPB_SYNTAX_PROTO2, &reftables[2], &reftables[3]),
  5475. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ReservedRange", 4, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[14], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[20]), false, UPB_SYNTAX_PROTO2, &reftables[4], &reftables[5]),
  5476. UPB_MSGDEF_INIT("google.protobuf.EnumDescriptorProto", 11, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[17], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[24]), false, UPB_SYNTAX_PROTO2, &reftables[6], &reftables[7]),
  5477. UPB_MSGDEF_INIT("google.protobuf.EnumOptions", 8, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[0], &arrays[21], 4, 2), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[28]), false, UPB_SYNTAX_PROTO2, &reftables[8], &reftables[9]),
  5478. UPB_MSGDEF_INIT("google.protobuf.EnumValueDescriptorProto", 8, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[25], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[32]), false, UPB_SYNTAX_PROTO2, &reftables[10], &reftables[11]),
  5479. UPB_MSGDEF_INIT("google.protobuf.EnumValueOptions", 7, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[2], &arrays[29], 2, 1), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[36]), false, UPB_SYNTAX_PROTO2, &reftables[12], &reftables[13]),
  5480. UPB_MSGDEF_INIT("google.protobuf.FieldDescriptorProto", 23, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[31], 11, 10), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[40]), false, UPB_SYNTAX_PROTO2, &reftables[14], &reftables[15]),
  5481. UPB_MSGDEF_INIT("google.protobuf.FieldOptions", 12, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[4], &arrays[42], 11, 6), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[56]), false, UPB_SYNTAX_PROTO2, &reftables[16], &reftables[17]),
  5482. UPB_MSGDEF_INIT("google.protobuf.FileDescriptorProto", 42, 6, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[53], 13, 12), UPB_STRTABLE_INIT(12, 15, UPB_CTYPE_PTR, 4, &strentries[72]), false, UPB_SYNTAX_PROTO2, &reftables[18], &reftables[19]),
  5483. UPB_MSGDEF_INIT("google.protobuf.FileDescriptorSet", 6, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[66], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[88]), false, UPB_SYNTAX_PROTO2, &reftables[20], &reftables[21]),
  5484. UPB_MSGDEF_INIT("google.protobuf.FileOptions", 31, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[6], &arrays[68], 39, 15), UPB_STRTABLE_INIT(16, 31, UPB_CTYPE_PTR, 5, &strentries[92]), false, UPB_SYNTAX_PROTO2, &reftables[22], &reftables[23]),
  5485. UPB_MSGDEF_INIT("google.protobuf.MessageOptions", 10, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[8], &arrays[107], 8, 4), UPB_STRTABLE_INIT(5, 7, UPB_CTYPE_PTR, 3, &strentries[124]), false, UPB_SYNTAX_PROTO2, &reftables[24], &reftables[25]),
  5486. UPB_MSGDEF_INIT("google.protobuf.MethodDescriptorProto", 15, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[115], 7, 6), UPB_STRTABLE_INIT(6, 7, UPB_CTYPE_PTR, 3, &strentries[132]), false, UPB_SYNTAX_PROTO2, &reftables[26], &reftables[27]),
  5487. UPB_MSGDEF_INIT("google.protobuf.MethodOptions", 7, 1, UPB_INTTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &intentries[10], &arrays[122], 1, 0), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[140]), false, UPB_SYNTAX_PROTO2, &reftables[28], &reftables[29]),
  5488. UPB_MSGDEF_INIT("google.protobuf.OneofDescriptorProto", 5, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[123], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[144]), false, UPB_SYNTAX_PROTO2, &reftables[30], &reftables[31]),
  5489. UPB_MSGDEF_INIT("google.protobuf.ServiceDescriptorProto", 11, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[125], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[148]), false, UPB_SYNTAX_PROTO2, &reftables[32], &reftables[33]),
  5490. UPB_MSGDEF_INIT("google.protobuf.ServiceOptions", 7, 1, UPB_INTTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &intentries[14], &arrays[129], 1, 0), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[152]), false, UPB_SYNTAX_PROTO2, &reftables[34], &reftables[35]),
  5491. UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo", 6, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[130], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[156]), false, UPB_SYNTAX_PROTO2, &reftables[36], &reftables[37]),
  5492. UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo.Location", 19, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[132], 7, 5), UPB_STRTABLE_INIT(5, 7, UPB_CTYPE_PTR, 3, &strentries[160]), false, UPB_SYNTAX_PROTO2, &reftables[38], &reftables[39]),
  5493. UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption", 18, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[139], 9, 7), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[168]), false, UPB_SYNTAX_PROTO2, &reftables[40], &reftables[41]),
  5494. UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption.NamePart", 6, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[148], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[184]), false, UPB_SYNTAX_PROTO2, &reftables[42], &reftables[43]),
  5495. };
  5496. static const upb_fielddef fields[105] = {
  5497. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "aggregate_value", 8, &msgs[20], NULL, 15, 6, {0},&reftables[44], &reftables[45]),
  5498. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "allow_alias", 2, &msgs[4], NULL, 6, 1, {0},&reftables[46], &reftables[47]),
  5499. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_enable_arenas", 31, &msgs[11], NULL, 23, 12, {0},&reftables[48], &reftables[49]),
  5500. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_generic_services", 16, &msgs[11], NULL, 17, 6, {0},&reftables[50], &reftables[51]),
  5501. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "client_streaming", 5, &msgs[13], NULL, 13, 4, {0},&reftables[52], &reftables[53]),
  5502. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "csharp_namespace", 37, &msgs[11], NULL, 27, 14, {0},&reftables[54], &reftables[55]),
  5503. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "ctype", 1, &msgs[8], (const upb_def*)(&enums[2]), 6, 1, {0},&reftables[56], &reftables[57]),
  5504. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "default_value", 7, &msgs[7], NULL, 16, 7, {0},&reftables[58], &reftables[59]),
  5505. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "dependency", 3, &msgs[9], NULL, 30, 8, {0},&reftables[60], &reftables[61]),
  5506. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[12], NULL, 8, 3, {0},&reftables[62], &reftables[63]),
  5507. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[8], NULL, 8, 3, {0},&reftables[64], &reftables[65]),
  5508. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 33, &msgs[14], NULL, 6, 1, {0},&reftables[66], &reftables[67]),
  5509. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 23, &msgs[11], NULL, 21, 10, {0},&reftables[68], &reftables[69]),
  5510. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[4], NULL, 7, 2, {0},&reftables[70], &reftables[71]),
  5511. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 33, &msgs[17], NULL, 6, 1, {0},&reftables[72], &reftables[73]),
  5512. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 1, &msgs[6], NULL, 6, 1, {0},&reftables[74], &reftables[75]),
  5513. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_DOUBLE, 0, false, false, false, false, "double_value", 6, &msgs[20], NULL, 11, 4, {0},&reftables[76], &reftables[77]),
  5514. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "end", 2, &msgs[2], NULL, 3, 1, {0},&reftables[78], &reftables[79]),
  5515. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "end", 2, &msgs[1], NULL, 3, 1, {0},&reftables[80], &reftables[81]),
  5516. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 4, &msgs[0], (const upb_def*)(&msgs[3]), 18, 2, {0},&reftables[82], &reftables[83]),
  5517. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 5, &msgs[9], (const upb_def*)(&msgs[3]), 13, 1, {0},&reftables[84], &reftables[85]),
  5518. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "extendee", 2, &msgs[7], NULL, 7, 2, {0},&reftables[86], &reftables[87]),
  5519. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 6, &msgs[0], (const upb_def*)(&msgs[7]), 24, 4, {0},&reftables[88], &reftables[89]),
  5520. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 7, &msgs[9], (const upb_def*)(&msgs[7]), 19, 3, {0},&reftables[90], &reftables[91]),
  5521. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension_range", 5, &msgs[0], (const upb_def*)(&msgs[1]), 21, 3, {0},&reftables[92], &reftables[93]),
  5522. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "field", 2, &msgs[0], (const upb_def*)(&msgs[7]), 12, 0, {0},&reftables[94], &reftables[95]),
  5523. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "file", 1, &msgs[10], (const upb_def*)(&msgs[9]), 5, 0, {0},&reftables[96], &reftables[97]),
  5524. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "go_package", 11, &msgs[11], NULL, 14, 5, {0},&reftables[98], &reftables[99]),
  5525. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "identifier_value", 3, &msgs[20], NULL, 6, 1, {0},&reftables[100], &reftables[101]),
  5526. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "input_type", 2, &msgs[13], NULL, 7, 2, {0},&reftables[102], &reftables[103]),
  5527. UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_BOOL, 0, false, false, false, false, "is_extension", 2, &msgs[21], NULL, 5, 1, {0},&reftables[104], &reftables[105]),
  5528. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generate_equals_and_hash", 20, &msgs[11], NULL, 20, 9, {0},&reftables[106], &reftables[107]),
  5529. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generic_services", 17, &msgs[11], NULL, 18, 7, {0},&reftables[108], &reftables[109]),
  5530. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_multiple_files", 10, &msgs[11], NULL, 13, 4, {0},&reftables[110], &reftables[111]),
  5531. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_outer_classname", 8, &msgs[11], NULL, 9, 2, {0},&reftables[112], &reftables[113]),
  5532. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_package", 1, &msgs[11], NULL, 6, 1, {0},&reftables[114], &reftables[115]),
  5533. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_string_check_utf8", 27, &msgs[11], NULL, 22, 11, {0},&reftables[116], &reftables[117]),
  5534. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "javanano_use_deprecated_package", 38, &msgs[11], NULL, 30, 15, {0},&reftables[118], &reftables[119]),
  5535. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "json_name", 10, &msgs[7], NULL, 20, 9, {0},&reftables[120], &reftables[121]),
  5536. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "jstype", 6, &msgs[8], (const upb_def*)(&enums[3]), 10, 5, {0},&reftables[122], &reftables[123]),
  5537. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "label", 4, &msgs[7], (const upb_def*)(&enums[0]), 11, 4, {0},&reftables[124], &reftables[125]),
  5538. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "lazy", 5, &msgs[8], NULL, 9, 4, {0},&reftables[126], &reftables[127]),
  5539. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "leading_comments", 3, &msgs[19], NULL, 8, 2, {0},&reftables[128], &reftables[129]),
  5540. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "leading_detached_comments", 6, &msgs[19], NULL, 16, 4, {0},&reftables[130], &reftables[131]),
  5541. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "location", 1, &msgs[18], (const upb_def*)(&msgs[19]), 5, 0, {0},&reftables[132], &reftables[133]),
  5542. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "map_entry", 7, &msgs[12], NULL, 9, 4, {0},&reftables[134], &reftables[135]),
  5543. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "message_set_wire_format", 1, &msgs[12], NULL, 6, 1, {0},&reftables[136], &reftables[137]),
  5544. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "message_type", 4, &msgs[9], (const upb_def*)(&msgs[0]), 10, 0, {0},&reftables[138], &reftables[139]),
  5545. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "method", 2, &msgs[16], (const upb_def*)(&msgs[13]), 6, 0, {0},&reftables[140], &reftables[141]),
  5546. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[3], NULL, 8, 2, {0},&reftables[142], &reftables[143]),
  5547. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[15], NULL, 2, 0, {0},&reftables[144], &reftables[145]),
  5548. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "name", 2, &msgs[20], (const upb_def*)(&msgs[21]), 5, 0, {0},&reftables[146], &reftables[147]),
  5549. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[0], NULL, 32, 8, {0},&reftables[148], &reftables[149]),
  5550. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[5], NULL, 4, 1, {0},&reftables[150], &reftables[151]),
  5551. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[9], NULL, 22, 6, {0},&reftables[152], &reftables[153]),
  5552. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[7], NULL, 4, 1, {0},&reftables[154], &reftables[155]),
  5553. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[13], NULL, 4, 1, {0},&reftables[156], &reftables[157]),
  5554. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[16], NULL, 8, 2, {0},&reftables[158], &reftables[159]),
  5555. UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_STRING, 0, false, false, false, false, "name_part", 1, &msgs[21], NULL, 2, 0, {0},&reftables[160], &reftables[161]),
  5556. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT64, UPB_INTFMT_VARIABLE, false, false, false, false, "negative_int_value", 5, &msgs[20], NULL, 10, 3, {0},&reftables[162], &reftables[163]),
  5557. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "nested_type", 3, &msgs[0], (const upb_def*)(&msgs[0]), 15, 1, {0},&reftables[164], &reftables[165]),
  5558. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "no_standard_descriptor_accessor", 2, &msgs[12], NULL, 7, 2, {0},&reftables[166], &reftables[167]),
  5559. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 2, &msgs[5], NULL, 7, 2, {0},&reftables[168], &reftables[169]),
  5560. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 3, &msgs[7], NULL, 10, 3, {0},&reftables[170], &reftables[171]),
  5561. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "objc_class_prefix", 36, &msgs[11], NULL, 24, 13, {0},&reftables[172], &reftables[173]),
  5562. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "oneof_decl", 8, &msgs[0], (const upb_def*)(&msgs[15]), 28, 6, {0},&reftables[174], &reftables[175]),
  5563. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "oneof_index", 9, &msgs[7], NULL, 19, 8, {0},&reftables[176], &reftables[177]),
  5564. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "optimize_for", 9, &msgs[11], (const upb_def*)(&enums[4]), 12, 3, {0},&reftables[178], &reftables[179]),
  5565. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 7, &msgs[0], (const upb_def*)(&msgs[12]), 25, 5, {0},&reftables[180], &reftables[181]),
  5566. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[9], (const upb_def*)(&msgs[11]), 20, 4, {0},&reftables[182], &reftables[183]),
  5567. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 4, &msgs[13], (const upb_def*)(&msgs[14]), 3, 0, {0},&reftables[184], &reftables[185]),
  5568. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[7], (const upb_def*)(&msgs[8]), 3, 0, {0},&reftables[186], &reftables[187]),
  5569. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[16], (const upb_def*)(&msgs[17]), 7, 1, {0},&reftables[188], &reftables[189]),
  5570. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[5], (const upb_def*)(&msgs[6]), 3, 0, {0},&reftables[190], &reftables[191]),
  5571. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[3], (const upb_def*)(&msgs[4]), 7, 1, {0},&reftables[192], &reftables[193]),
  5572. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "output_type", 3, &msgs[13], NULL, 10, 3, {0},&reftables[194], &reftables[195]),
  5573. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "package", 2, &msgs[9], NULL, 25, 7, {0},&reftables[196], &reftables[197]),
  5574. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "packed", 2, &msgs[8], NULL, 7, 2, {0},&reftables[198], &reftables[199]),
  5575. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "path", 1, &msgs[19], NULL, 4, 0, {0},&reftables[200], &reftables[201]),
  5576. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_UINT64, UPB_INTFMT_VARIABLE, false, false, false, false, "positive_int_value", 4, &msgs[20], NULL, 9, 2, {0},&reftables[202], &reftables[203]),
  5577. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "public_dependency", 10, &msgs[9], NULL, 35, 9, {0},&reftables[204], &reftables[205]),
  5578. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "py_generic_services", 18, &msgs[11], NULL, 19, 8, {0},&reftables[206], &reftables[207]),
  5579. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "reserved_name", 10, &msgs[0], NULL, 37, 9, {0},&reftables[208], &reftables[209]),
  5580. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "reserved_range", 9, &msgs[0], (const upb_def*)(&msgs[2]), 31, 7, {0},&reftables[210], &reftables[211]),
  5581. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "server_streaming", 6, &msgs[13], NULL, 14, 5, {0},&reftables[212], &reftables[213]),
  5582. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "service", 6, &msgs[9], (const upb_def*)(&msgs[16]), 16, 2, {0},&reftables[214], &reftables[215]),
  5583. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "source_code_info", 9, &msgs[9], (const upb_def*)(&msgs[18]), 21, 5, {0},&reftables[216], &reftables[217]),
  5584. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "span", 2, &msgs[19], NULL, 7, 1, {0},&reftables[218], &reftables[219]),
  5585. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "start", 1, &msgs[2], NULL, 2, 0, {0},&reftables[220], &reftables[221]),
  5586. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "start", 1, &msgs[1], NULL, 2, 0, {0},&reftables[222], &reftables[223]),
  5587. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BYTES, 0, false, false, false, false, "string_value", 7, &msgs[20], NULL, 12, 5, {0},&reftables[224], &reftables[225]),
  5588. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "syntax", 12, &msgs[9], NULL, 39, 11, {0},&reftables[226], &reftables[227]),
  5589. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "trailing_comments", 4, &msgs[19], NULL, 11, 3, {0},&reftables[228], &reftables[229]),
  5590. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "type", 5, &msgs[7], (const upb_def*)(&enums[1]), 12, 5, {0},&reftables[230], &reftables[231]),
  5591. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "type_name", 6, &msgs[7], NULL, 13, 6, {0},&reftables[232], &reftables[233]),
  5592. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[11], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[234], &reftables[235]),
  5593. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[12], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[236], &reftables[237]),
  5594. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[6], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[238], &reftables[239]),
  5595. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[4], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[240], &reftables[241]),
  5596. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[8], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[242], &reftables[243]),
  5597. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[14], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[244], &reftables[245]),
  5598. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[17], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[246], &reftables[247]),
  5599. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "value", 2, &msgs[3], (const upb_def*)(&msgs[5]), 6, 0, {0},&reftables[248], &reftables[249]),
  5600. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "weak", 10, &msgs[8], NULL, 11, 6, {0},&reftables[250], &reftables[251]),
  5601. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "weak_dependency", 11, &msgs[9], NULL, 38, 10, {0},&reftables[252], &reftables[253]),
  5602. };
  5603. static const upb_enumdef enums[5] = {
  5604. UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Label", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[188]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[151], 4, 3), 0, &reftables[254], &reftables[255]),
  5605. UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Type", UPB_STRTABLE_INIT(18, 31, UPB_CTYPE_INT32, 5, &strentries[192]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[155], 19, 18), 0, &reftables[256], &reftables[257]),
  5606. UPB_ENUMDEF_INIT("google.protobuf.FieldOptions.CType", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[224]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[174], 3, 3), 0, &reftables[258], &reftables[259]),
  5607. UPB_ENUMDEF_INIT("google.protobuf.FieldOptions.JSType", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[228]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[177], 3, 3), 0, &reftables[260], &reftables[261]),
  5608. UPB_ENUMDEF_INIT("google.protobuf.FileOptions.OptimizeMode", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[232]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[180], 4, 3), 0, &reftables[262], &reftables[263]),
  5609. };
  5610. static const upb_tabent strentries[236] = {
  5611. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "extension"), UPB_TABVALUE_PTR_INIT(&fields[22]), NULL},
  5612. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5613. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "reserved_name"), UPB_TABVALUE_PTR_INIT(&fields[82]), NULL},
  5614. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[52]), NULL},
  5615. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5616. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5617. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5618. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "field"), UPB_TABVALUE_PTR_INIT(&fields[25]), &strentries[12]},
  5619. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "extension_range"), UPB_TABVALUE_PTR_INIT(&fields[24]), &strentries[14]},
  5620. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5621. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "nested_type"), UPB_TABVALUE_PTR_INIT(&fields[60]), NULL},
  5622. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5623. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "reserved_range"), UPB_TABVALUE_PTR_INIT(&fields[83]), NULL},
  5624. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[68]), NULL},
  5625. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "oneof_decl"), UPB_TABVALUE_PTR_INIT(&fields[65]), NULL},
  5626. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[19]), &strentries[13]},
  5627. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[89]), NULL},
  5628. {UPB_TABKEY_STR("\003", "\000", "\000", "\000", "end"), UPB_TABVALUE_PTR_INIT(&fields[18]), NULL},
  5629. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5630. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5631. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[88]), NULL},
  5632. {UPB_TABKEY_STR("\003", "\000", "\000", "\000", "end"), UPB_TABVALUE_PTR_INIT(&fields[17]), NULL},
  5633. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5634. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5635. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5636. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "value"), UPB_TABVALUE_PTR_INIT(&fields[102]), NULL},
  5637. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[74]), NULL},
  5638. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[49]), &strentries[26]},
  5639. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[98]), NULL},
  5640. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[13]), NULL},
  5641. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "allow_alias"), UPB_TABVALUE_PTR_INIT(&fields[1]), NULL},
  5642. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5643. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[62]), NULL},
  5644. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5645. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[73]), NULL},
  5646. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[53]), &strentries[34]},
  5647. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[97]), NULL},
  5648. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[15]), NULL},
  5649. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5650. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5651. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "oneof_index"), UPB_TABVALUE_PTR_INIT(&fields[66]), NULL},
  5652. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "label"), UPB_TABVALUE_PTR_INIT(&fields[40]), NULL},
  5653. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5654. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[55]), NULL},
  5655. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5656. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5657. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5658. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5659. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[63]), &strentries[53]},
  5660. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5661. {UPB_TABKEY_STR("\010", "\000", "\000", "\000", "extendee"), UPB_TABVALUE_PTR_INIT(&fields[21]), NULL},
  5662. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "type_name"), UPB_TABVALUE_PTR_INIT(&fields[94]), NULL},
  5663. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "json_name"), UPB_TABVALUE_PTR_INIT(&fields[38]), NULL},
  5664. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "type"), UPB_TABVALUE_PTR_INIT(&fields[93]), &strentries[50]},
  5665. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "default_value"), UPB_TABVALUE_PTR_INIT(&fields[7]), NULL},
  5666. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[71]), NULL},
  5667. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[99]), NULL},
  5668. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5669. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "weak"), UPB_TABVALUE_PTR_INIT(&fields[103]), NULL},
  5670. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5671. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5672. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5673. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5674. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "packed"), UPB_TABVALUE_PTR_INIT(&fields[77]), NULL},
  5675. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "lazy"), UPB_TABVALUE_PTR_INIT(&fields[41]), NULL},
  5676. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5677. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "ctype"), UPB_TABVALUE_PTR_INIT(&fields[6]), NULL},
  5678. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5679. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "jstype"), UPB_TABVALUE_PTR_INIT(&fields[39]), NULL},
  5680. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[10]), NULL},
  5681. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5682. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5683. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "extension"), UPB_TABVALUE_PTR_INIT(&fields[23]), NULL},
  5684. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "weak_dependency"), UPB_TABVALUE_PTR_INIT(&fields[104]), NULL},
  5685. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5686. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[54]), NULL},
  5687. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "service"), UPB_TABVALUE_PTR_INIT(&fields[85]), NULL},
  5688. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5689. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "source_code_info"), UPB_TABVALUE_PTR_INIT(&fields[86]), NULL},
  5690. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5691. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5692. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "syntax"), UPB_TABVALUE_PTR_INIT(&fields[91]), NULL},
  5693. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "dependency"), UPB_TABVALUE_PTR_INIT(&fields[8]), NULL},
  5694. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "message_type"), UPB_TABVALUE_PTR_INIT(&fields[47]), NULL},
  5695. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "package"), UPB_TABVALUE_PTR_INIT(&fields[76]), NULL},
  5696. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[69]), &strentries[86]},
  5697. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[20]), NULL},
  5698. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "public_dependency"), UPB_TABVALUE_PTR_INIT(&fields[80]), &strentries[85]},
  5699. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5700. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "file"), UPB_TABVALUE_PTR_INIT(&fields[26]), NULL},
  5701. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5702. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5703. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5704. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5705. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "cc_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[3]), NULL},
  5706. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "csharp_namespace"), UPB_TABVALUE_PTR_INIT(&fields[5]), NULL},
  5707. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5708. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5709. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5710. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5711. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5712. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5713. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5714. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "go_package"), UPB_TABVALUE_PTR_INIT(&fields[27]), NULL},
  5715. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "java_package"), UPB_TABVALUE_PTR_INIT(&fields[35]), &strentries[120]},
  5716. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5717. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5718. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "java_outer_classname"), UPB_TABVALUE_PTR_INIT(&fields[34]), NULL},
  5719. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[95]), NULL},
  5720. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5721. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5722. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5723. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "java_multiple_files"), UPB_TABVALUE_PTR_INIT(&fields[33]), &strentries[117]},
  5724. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5725. {UPB_TABKEY_STR("\025", "\000", "\000", "\000", "java_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[32]), &strentries[118]},
  5726. {UPB_TABKEY_STR("\035", "\000", "\000", "\000", "java_generate_equals_and_hash"), UPB_TABVALUE_PTR_INIT(&fields[31]), NULL},
  5727. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5728. {UPB_TABKEY_STR("\037", "\000", "\000", "\000", "javanano_use_deprecated_package"), UPB_TABVALUE_PTR_INIT(&fields[37]), &strentries[123]},
  5729. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "py_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[81]), NULL},
  5730. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "optimize_for"), UPB_TABVALUE_PTR_INIT(&fields[67]), NULL},
  5731. {UPB_TABKEY_STR("\026", "\000", "\000", "\000", "java_string_check_utf8"), UPB_TABVALUE_PTR_INIT(&fields[36]), NULL},
  5732. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[12]), &strentries[119]},
  5733. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "objc_class_prefix"), UPB_TABVALUE_PTR_INIT(&fields[64]), NULL},
  5734. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "cc_enable_arenas"), UPB_TABVALUE_PTR_INIT(&fields[2]), NULL},
  5735. {UPB_TABKEY_STR("\027", "\000", "\000", "\000", "message_set_wire_format"), UPB_TABVALUE_PTR_INIT(&fields[46]), &strentries[128]},
  5736. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5737. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5738. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5739. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[96]), NULL},
  5740. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[9]), NULL},
  5741. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "map_entry"), UPB_TABVALUE_PTR_INIT(&fields[45]), NULL},
  5742. {UPB_TABKEY_STR("\037", "\000", "\000", "\000", "no_standard_descriptor_accessor"), UPB_TABVALUE_PTR_INIT(&fields[61]), NULL},
  5743. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5744. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "client_streaming"), UPB_TABVALUE_PTR_INIT(&fields[4]), NULL},
  5745. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "server_streaming"), UPB_TABVALUE_PTR_INIT(&fields[84]), NULL},
  5746. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[56]), NULL},
  5747. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "input_type"), UPB_TABVALUE_PTR_INIT(&fields[29]), NULL},
  5748. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5749. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "output_type"), UPB_TABVALUE_PTR_INIT(&fields[75]), NULL},
  5750. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[70]), NULL},
  5751. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[100]), NULL},
  5752. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[11]), NULL},
  5753. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5754. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5755. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5756. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5757. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5758. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[50]), NULL},
  5759. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5760. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[72]), &strentries[150]},
  5761. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "method"), UPB_TABVALUE_PTR_INIT(&fields[48]), NULL},
  5762. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[57]), &strentries[149]},
  5763. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[101]), NULL},
  5764. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[14]), NULL},
  5765. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5766. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5767. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5768. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5769. {UPB_TABKEY_STR("\010", "\000", "\000", "\000", "location"), UPB_TABVALUE_PTR_INIT(&fields[44]), NULL},
  5770. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5771. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5772. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5773. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5774. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "span"), UPB_TABVALUE_PTR_INIT(&fields[87]), &strentries[167]},
  5775. {UPB_TABKEY_STR("\031", "\000", "\000", "\000", "leading_detached_comments"), UPB_TABVALUE_PTR_INIT(&fields[43]), &strentries[165]},
  5776. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "trailing_comments"), UPB_TABVALUE_PTR_INIT(&fields[92]), NULL},
  5777. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "leading_comments"), UPB_TABVALUE_PTR_INIT(&fields[42]), &strentries[164]},
  5778. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "path"), UPB_TABVALUE_PTR_INIT(&fields[78]), NULL},
  5779. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "double_value"), UPB_TABVALUE_PTR_INIT(&fields[16]), NULL},
  5780. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5781. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5782. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[51]), NULL},
  5783. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5784. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5785. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5786. {UPB_TABKEY_STR("\022", "\000", "\000", "\000", "negative_int_value"), UPB_TABVALUE_PTR_INIT(&fields[59]), NULL},
  5787. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "aggregate_value"), UPB_TABVALUE_PTR_INIT(&fields[0]), NULL},
  5788. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5789. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5790. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5791. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5792. {UPB_TABKEY_STR("\022", "\000", "\000", "\000", "positive_int_value"), UPB_TABVALUE_PTR_INIT(&fields[79]), NULL},
  5793. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "identifier_value"), UPB_TABVALUE_PTR_INIT(&fields[28]), NULL},
  5794. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "string_value"), UPB_TABVALUE_PTR_INIT(&fields[90]), &strentries[182]},
  5795. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5796. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5797. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "is_extension"), UPB_TABVALUE_PTR_INIT(&fields[30]), NULL},
  5798. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "name_part"), UPB_TABVALUE_PTR_INIT(&fields[58]), NULL},
  5799. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_REQUIRED"), UPB_TABVALUE_INT_INIT(2), &strentries[190]},
  5800. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5801. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_REPEATED"), UPB_TABVALUE_INT_INIT(3), NULL},
  5802. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_OPTIONAL"), UPB_TABVALUE_INT_INIT(1), NULL},
  5803. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_FIXED64"), UPB_TABVALUE_INT_INIT(6), NULL},
  5804. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5805. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5806. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5807. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5808. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_STRING"), UPB_TABVALUE_INT_INIT(9), NULL},
  5809. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_FLOAT"), UPB_TABVALUE_INT_INIT(2), &strentries[221]},
  5810. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_DOUBLE"), UPB_TABVALUE_INT_INIT(1), NULL},
  5811. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5812. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_INT32"), UPB_TABVALUE_INT_INIT(5), NULL},
  5813. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "TYPE_SFIXED32"), UPB_TABVALUE_INT_INIT(15), NULL},
  5814. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_FIXED32"), UPB_TABVALUE_INT_INIT(7), NULL},
  5815. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5816. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_MESSAGE"), UPB_TABVALUE_INT_INIT(11), &strentries[222]},
  5817. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5818. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5819. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_INT64"), UPB_TABVALUE_INT_INIT(3), &strentries[219]},
  5820. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5821. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5822. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5823. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5824. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "TYPE_ENUM"), UPB_TABVALUE_INT_INIT(14), NULL},
  5825. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_UINT32"), UPB_TABVALUE_INT_INIT(13), NULL},
  5826. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5827. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_UINT64"), UPB_TABVALUE_INT_INIT(4), &strentries[218]},
  5828. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5829. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "TYPE_SFIXED64"), UPB_TABVALUE_INT_INIT(16), NULL},
  5830. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_BYTES"), UPB_TABVALUE_INT_INIT(12), NULL},
  5831. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_SINT64"), UPB_TABVALUE_INT_INIT(18), NULL},
  5832. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "TYPE_BOOL"), UPB_TABVALUE_INT_INIT(8), NULL},
  5833. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_GROUP"), UPB_TABVALUE_INT_INIT(10), NULL},
  5834. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_SINT32"), UPB_TABVALUE_INT_INIT(17), NULL},
  5835. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5836. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "CORD"), UPB_TABVALUE_INT_INIT(1), NULL},
  5837. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "STRING"), UPB_TABVALUE_INT_INIT(0), &strentries[225]},
  5838. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "STRING_PIECE"), UPB_TABVALUE_INT_INIT(2), NULL},
  5839. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5840. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "JS_NORMAL"), UPB_TABVALUE_INT_INIT(0), NULL},
  5841. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "JS_NUMBER"), UPB_TABVALUE_INT_INIT(2), NULL},
  5842. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "JS_STRING"), UPB_TABVALUE_INT_INIT(1), NULL},
  5843. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "CODE_SIZE"), UPB_TABVALUE_INT_INIT(2), NULL},
  5844. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "SPEED"), UPB_TABVALUE_INT_INIT(1), &strentries[235]},
  5845. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5846. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "LITE_RUNTIME"), UPB_TABVALUE_INT_INIT(3), NULL},
  5847. };
  5848. static const upb_tabent intentries[18] = {
  5849. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5850. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[98]), NULL},
  5851. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5852. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[97]), NULL},
  5853. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5854. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[99]), NULL},
  5855. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5856. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[95]), NULL},
  5857. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5858. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[96]), NULL},
  5859. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5860. {UPB_TABKEY_NUM(33), UPB_TABVALUE_PTR_INIT(&fields[11]), NULL},
  5861. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5862. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[100]), NULL},
  5863. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5864. {UPB_TABKEY_NUM(33), UPB_TABVALUE_PTR_INIT(&fields[14]), NULL},
  5865. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5866. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[101]), NULL},
  5867. };
  5868. static const upb_tabval arrays[184] = {
  5869. UPB_TABVALUE_EMPTY_INIT,
  5870. UPB_TABVALUE_PTR_INIT(&fields[52]),
  5871. UPB_TABVALUE_PTR_INIT(&fields[25]),
  5872. UPB_TABVALUE_PTR_INIT(&fields[60]),
  5873. UPB_TABVALUE_PTR_INIT(&fields[19]),
  5874. UPB_TABVALUE_PTR_INIT(&fields[24]),
  5875. UPB_TABVALUE_PTR_INIT(&fields[22]),
  5876. UPB_TABVALUE_PTR_INIT(&fields[68]),
  5877. UPB_TABVALUE_PTR_INIT(&fields[65]),
  5878. UPB_TABVALUE_PTR_INIT(&fields[83]),
  5879. UPB_TABVALUE_PTR_INIT(&fields[82]),
  5880. UPB_TABVALUE_EMPTY_INIT,
  5881. UPB_TABVALUE_PTR_INIT(&fields[89]),
  5882. UPB_TABVALUE_PTR_INIT(&fields[18]),
  5883. UPB_TABVALUE_EMPTY_INIT,
  5884. UPB_TABVALUE_PTR_INIT(&fields[88]),
  5885. UPB_TABVALUE_PTR_INIT(&fields[17]),
  5886. UPB_TABVALUE_EMPTY_INIT,
  5887. UPB_TABVALUE_PTR_INIT(&fields[49]),
  5888. UPB_TABVALUE_PTR_INIT(&fields[102]),
  5889. UPB_TABVALUE_PTR_INIT(&fields[74]),
  5890. UPB_TABVALUE_EMPTY_INIT,
  5891. UPB_TABVALUE_EMPTY_INIT,
  5892. UPB_TABVALUE_PTR_INIT(&fields[1]),
  5893. UPB_TABVALUE_PTR_INIT(&fields[13]),
  5894. UPB_TABVALUE_EMPTY_INIT,
  5895. UPB_TABVALUE_PTR_INIT(&fields[53]),
  5896. UPB_TABVALUE_PTR_INIT(&fields[62]),
  5897. UPB_TABVALUE_PTR_INIT(&fields[73]),
  5898. UPB_TABVALUE_EMPTY_INIT,
  5899. UPB_TABVALUE_PTR_INIT(&fields[15]),
  5900. UPB_TABVALUE_EMPTY_INIT,
  5901. UPB_TABVALUE_PTR_INIT(&fields[55]),
  5902. UPB_TABVALUE_PTR_INIT(&fields[21]),
  5903. UPB_TABVALUE_PTR_INIT(&fields[63]),
  5904. UPB_TABVALUE_PTR_INIT(&fields[40]),
  5905. UPB_TABVALUE_PTR_INIT(&fields[93]),
  5906. UPB_TABVALUE_PTR_INIT(&fields[94]),
  5907. UPB_TABVALUE_PTR_INIT(&fields[7]),
  5908. UPB_TABVALUE_PTR_INIT(&fields[71]),
  5909. UPB_TABVALUE_PTR_INIT(&fields[66]),
  5910. UPB_TABVALUE_PTR_INIT(&fields[38]),
  5911. UPB_TABVALUE_EMPTY_INIT,
  5912. UPB_TABVALUE_PTR_INIT(&fields[6]),
  5913. UPB_TABVALUE_PTR_INIT(&fields[77]),
  5914. UPB_TABVALUE_PTR_INIT(&fields[10]),
  5915. UPB_TABVALUE_EMPTY_INIT,
  5916. UPB_TABVALUE_PTR_INIT(&fields[41]),
  5917. UPB_TABVALUE_PTR_INIT(&fields[39]),
  5918. UPB_TABVALUE_EMPTY_INIT,
  5919. UPB_TABVALUE_EMPTY_INIT,
  5920. UPB_TABVALUE_EMPTY_INIT,
  5921. UPB_TABVALUE_PTR_INIT(&fields[103]),
  5922. UPB_TABVALUE_EMPTY_INIT,
  5923. UPB_TABVALUE_PTR_INIT(&fields[54]),
  5924. UPB_TABVALUE_PTR_INIT(&fields[76]),
  5925. UPB_TABVALUE_PTR_INIT(&fields[8]),
  5926. UPB_TABVALUE_PTR_INIT(&fields[47]),
  5927. UPB_TABVALUE_PTR_INIT(&fields[20]),
  5928. UPB_TABVALUE_PTR_INIT(&fields[85]),
  5929. UPB_TABVALUE_PTR_INIT(&fields[23]),
  5930. UPB_TABVALUE_PTR_INIT(&fields[69]),
  5931. UPB_TABVALUE_PTR_INIT(&fields[86]),
  5932. UPB_TABVALUE_PTR_INIT(&fields[80]),
  5933. UPB_TABVALUE_PTR_INIT(&fields[104]),
  5934. UPB_TABVALUE_PTR_INIT(&fields[91]),
  5935. UPB_TABVALUE_EMPTY_INIT,
  5936. UPB_TABVALUE_PTR_INIT(&fields[26]),
  5937. UPB_TABVALUE_EMPTY_INIT,
  5938. UPB_TABVALUE_PTR_INIT(&fields[35]),
  5939. UPB_TABVALUE_EMPTY_INIT,
  5940. UPB_TABVALUE_EMPTY_INIT,
  5941. UPB_TABVALUE_EMPTY_INIT,
  5942. UPB_TABVALUE_EMPTY_INIT,
  5943. UPB_TABVALUE_EMPTY_INIT,
  5944. UPB_TABVALUE_EMPTY_INIT,
  5945. UPB_TABVALUE_PTR_INIT(&fields[34]),
  5946. UPB_TABVALUE_PTR_INIT(&fields[67]),
  5947. UPB_TABVALUE_PTR_INIT(&fields[33]),
  5948. UPB_TABVALUE_PTR_INIT(&fields[27]),
  5949. UPB_TABVALUE_EMPTY_INIT,
  5950. UPB_TABVALUE_EMPTY_INIT,
  5951. UPB_TABVALUE_EMPTY_INIT,
  5952. UPB_TABVALUE_EMPTY_INIT,
  5953. UPB_TABVALUE_PTR_INIT(&fields[3]),
  5954. UPB_TABVALUE_PTR_INIT(&fields[32]),
  5955. UPB_TABVALUE_PTR_INIT(&fields[81]),
  5956. UPB_TABVALUE_EMPTY_INIT,
  5957. UPB_TABVALUE_PTR_INIT(&fields[31]),
  5958. UPB_TABVALUE_EMPTY_INIT,
  5959. UPB_TABVALUE_EMPTY_INIT,
  5960. UPB_TABVALUE_PTR_INIT(&fields[12]),
  5961. UPB_TABVALUE_EMPTY_INIT,
  5962. UPB_TABVALUE_EMPTY_INIT,
  5963. UPB_TABVALUE_EMPTY_INIT,
  5964. UPB_TABVALUE_PTR_INIT(&fields[36]),
  5965. UPB_TABVALUE_EMPTY_INIT,
  5966. UPB_TABVALUE_EMPTY_INIT,
  5967. UPB_TABVALUE_EMPTY_INIT,
  5968. UPB_TABVALUE_PTR_INIT(&fields[2]),
  5969. UPB_TABVALUE_EMPTY_INIT,
  5970. UPB_TABVALUE_EMPTY_INIT,
  5971. UPB_TABVALUE_EMPTY_INIT,
  5972. UPB_TABVALUE_EMPTY_INIT,
  5973. UPB_TABVALUE_PTR_INIT(&fields[64]),
  5974. UPB_TABVALUE_PTR_INIT(&fields[5]),
  5975. UPB_TABVALUE_PTR_INIT(&fields[37]),
  5976. UPB_TABVALUE_EMPTY_INIT,
  5977. UPB_TABVALUE_PTR_INIT(&fields[46]),
  5978. UPB_TABVALUE_PTR_INIT(&fields[61]),
  5979. UPB_TABVALUE_PTR_INIT(&fields[9]),
  5980. UPB_TABVALUE_EMPTY_INIT,
  5981. UPB_TABVALUE_EMPTY_INIT,
  5982. UPB_TABVALUE_EMPTY_INIT,
  5983. UPB_TABVALUE_PTR_INIT(&fields[45]),
  5984. UPB_TABVALUE_EMPTY_INIT,
  5985. UPB_TABVALUE_PTR_INIT(&fields[56]),
  5986. UPB_TABVALUE_PTR_INIT(&fields[29]),
  5987. UPB_TABVALUE_PTR_INIT(&fields[75]),
  5988. UPB_TABVALUE_PTR_INIT(&fields[70]),
  5989. UPB_TABVALUE_PTR_INIT(&fields[4]),
  5990. UPB_TABVALUE_PTR_INIT(&fields[84]),
  5991. UPB_TABVALUE_EMPTY_INIT,
  5992. UPB_TABVALUE_EMPTY_INIT,
  5993. UPB_TABVALUE_PTR_INIT(&fields[50]),
  5994. UPB_TABVALUE_EMPTY_INIT,
  5995. UPB_TABVALUE_PTR_INIT(&fields[57]),
  5996. UPB_TABVALUE_PTR_INIT(&fields[48]),
  5997. UPB_TABVALUE_PTR_INIT(&fields[72]),
  5998. UPB_TABVALUE_EMPTY_INIT,
  5999. UPB_TABVALUE_EMPTY_INIT,
  6000. UPB_TABVALUE_PTR_INIT(&fields[44]),
  6001. UPB_TABVALUE_EMPTY_INIT,
  6002. UPB_TABVALUE_PTR_INIT(&fields[78]),
  6003. UPB_TABVALUE_PTR_INIT(&fields[87]),
  6004. UPB_TABVALUE_PTR_INIT(&fields[42]),
  6005. UPB_TABVALUE_PTR_INIT(&fields[92]),
  6006. UPB_TABVALUE_EMPTY_INIT,
  6007. UPB_TABVALUE_PTR_INIT(&fields[43]),
  6008. UPB_TABVALUE_EMPTY_INIT,
  6009. UPB_TABVALUE_EMPTY_INIT,
  6010. UPB_TABVALUE_PTR_INIT(&fields[51]),
  6011. UPB_TABVALUE_PTR_INIT(&fields[28]),
  6012. UPB_TABVALUE_PTR_INIT(&fields[79]),
  6013. UPB_TABVALUE_PTR_INIT(&fields[59]),
  6014. UPB_TABVALUE_PTR_INIT(&fields[16]),
  6015. UPB_TABVALUE_PTR_INIT(&fields[90]),
  6016. UPB_TABVALUE_PTR_INIT(&fields[0]),
  6017. UPB_TABVALUE_EMPTY_INIT,
  6018. UPB_TABVALUE_PTR_INIT(&fields[58]),
  6019. UPB_TABVALUE_PTR_INIT(&fields[30]),
  6020. UPB_TABVALUE_EMPTY_INIT,
  6021. UPB_TABVALUE_PTR_INIT("LABEL_OPTIONAL"),
  6022. UPB_TABVALUE_PTR_INIT("LABEL_REQUIRED"),
  6023. UPB_TABVALUE_PTR_INIT("LABEL_REPEATED"),
  6024. UPB_TABVALUE_EMPTY_INIT,
  6025. UPB_TABVALUE_PTR_INIT("TYPE_DOUBLE"),
  6026. UPB_TABVALUE_PTR_INIT("TYPE_FLOAT"),
  6027. UPB_TABVALUE_PTR_INIT("TYPE_INT64"),
  6028. UPB_TABVALUE_PTR_INIT("TYPE_UINT64"),
  6029. UPB_TABVALUE_PTR_INIT("TYPE_INT32"),
  6030. UPB_TABVALUE_PTR_INIT("TYPE_FIXED64"),
  6031. UPB_TABVALUE_PTR_INIT("TYPE_FIXED32"),
  6032. UPB_TABVALUE_PTR_INIT("TYPE_BOOL"),
  6033. UPB_TABVALUE_PTR_INIT("TYPE_STRING"),
  6034. UPB_TABVALUE_PTR_INIT("TYPE_GROUP"),
  6035. UPB_TABVALUE_PTR_INIT("TYPE_MESSAGE"),
  6036. UPB_TABVALUE_PTR_INIT("TYPE_BYTES"),
  6037. UPB_TABVALUE_PTR_INIT("TYPE_UINT32"),
  6038. UPB_TABVALUE_PTR_INIT("TYPE_ENUM"),
  6039. UPB_TABVALUE_PTR_INIT("TYPE_SFIXED32"),
  6040. UPB_TABVALUE_PTR_INIT("TYPE_SFIXED64"),
  6041. UPB_TABVALUE_PTR_INIT("TYPE_SINT32"),
  6042. UPB_TABVALUE_PTR_INIT("TYPE_SINT64"),
  6043. UPB_TABVALUE_PTR_INIT("STRING"),
  6044. UPB_TABVALUE_PTR_INIT("CORD"),
  6045. UPB_TABVALUE_PTR_INIT("STRING_PIECE"),
  6046. UPB_TABVALUE_PTR_INIT("JS_NORMAL"),
  6047. UPB_TABVALUE_PTR_INIT("JS_STRING"),
  6048. UPB_TABVALUE_PTR_INIT("JS_NUMBER"),
  6049. UPB_TABVALUE_EMPTY_INIT,
  6050. UPB_TABVALUE_PTR_INIT("SPEED"),
  6051. UPB_TABVALUE_PTR_INIT("CODE_SIZE"),
  6052. UPB_TABVALUE_PTR_INIT("LITE_RUNTIME"),
  6053. };
  6054. #ifdef UPB_DEBUG_REFS
  6055. static upb_inttable reftables[264] = {
  6056. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6057. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6058. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6059. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6060. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6061. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6062. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6063. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6064. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6065. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6066. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6067. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6068. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6069. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6070. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6071. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6072. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6073. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6074. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6075. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6076. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6077. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6078. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6079. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6080. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6081. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6082. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6083. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6084. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6085. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6086. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6087. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6088. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6089. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6090. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6091. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6092. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6093. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6094. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6095. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6096. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6097. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6098. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6099. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6100. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6101. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6102. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6103. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6104. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6105. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6106. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6107. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6108. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6109. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6110. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6111. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6112. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6113. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6114. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6115. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6116. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6117. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6118. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6119. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6120. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6121. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6122. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6123. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6124. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6125. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6126. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6127. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6128. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6129. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6130. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6131. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6132. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6133. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6134. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6135. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6136. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6137. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6138. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6139. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6140. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6141. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6142. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6143. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6144. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6145. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6146. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6147. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6148. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6149. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6150. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6151. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6152. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6153. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6154. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6155. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6156. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6157. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6158. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6159. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6160. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6161. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6162. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6163. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6164. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6165. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6166. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6167. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6168. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6169. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6170. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6171. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6172. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6173. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6174. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6175. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6176. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6177. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6178. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6179. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6180. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6181. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6182. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6183. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6184. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6185. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6186. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6187. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6188. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6189. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6190. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6191. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6192. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6193. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6194. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6195. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6196. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6197. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6198. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6199. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6200. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6201. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6202. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6203. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6204. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6205. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6206. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6207. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6208. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6209. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6210. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6211. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6212. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6213. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6214. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6215. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6216. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6217. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6218. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6219. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6220. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6221. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6222. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6223. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6224. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6225. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6226. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6227. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6228. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6229. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6230. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6231. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6232. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6233. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6234. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6235. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6236. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6237. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6238. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6239. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6240. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6241. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6242. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6243. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6244. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6245. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6246. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6247. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6248. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6249. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6250. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6251. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6252. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6253. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6254. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6255. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6256. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6257. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6258. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6259. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6260. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6261. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6262. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6263. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6264. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6265. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6266. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6267. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6268. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6269. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6270. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6271. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6272. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6273. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6274. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6275. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6276. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6277. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6278. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6279. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6280. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6281. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6282. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6283. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6284. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6285. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6286. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6287. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6288. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6289. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6290. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6291. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6292. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6293. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6294. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6295. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6296. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6297. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6298. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6299. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6300. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6301. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6302. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6303. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6304. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6305. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6306. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6307. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6308. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6309. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6310. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6311. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6312. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6313. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6314. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6315. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6316. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6317. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6318. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6319. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6320. };
  6321. #endif
  6322. static const upb_msgdef *refm(const upb_msgdef *m, const void *owner) {
  6323. upb_msgdef_ref(m, owner);
  6324. return m;
  6325. }
  6326. static const upb_enumdef *refe(const upb_enumdef *e, const void *owner) {
  6327. upb_enumdef_ref(e, owner);
  6328. return e;
  6329. }
  6330. /* Public API. */
  6331. const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_get(const void *owner) { return refm(&msgs[0], owner); }
  6332. const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_ExtensionRange_get(const void *owner) { return refm(&msgs[1], owner); }
  6333. const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_ReservedRange_get(const void *owner) { return refm(&msgs[2], owner); }
  6334. const upb_msgdef *upbdefs_google_protobuf_EnumDescriptorProto_get(const void *owner) { return refm(&msgs[3], owner); }
  6335. const upb_msgdef *upbdefs_google_protobuf_EnumOptions_get(const void *owner) { return refm(&msgs[4], owner); }
  6336. const upb_msgdef *upbdefs_google_protobuf_EnumValueDescriptorProto_get(const void *owner) { return refm(&msgs[5], owner); }
  6337. const upb_msgdef *upbdefs_google_protobuf_EnumValueOptions_get(const void *owner) { return refm(&msgs[6], owner); }
  6338. const upb_msgdef *upbdefs_google_protobuf_FieldDescriptorProto_get(const void *owner) { return refm(&msgs[7], owner); }
  6339. const upb_msgdef *upbdefs_google_protobuf_FieldOptions_get(const void *owner) { return refm(&msgs[8], owner); }
  6340. const upb_msgdef *upbdefs_google_protobuf_FileDescriptorProto_get(const void *owner) { return refm(&msgs[9], owner); }
  6341. const upb_msgdef *upbdefs_google_protobuf_FileDescriptorSet_get(const void *owner) { return refm(&msgs[10], owner); }
  6342. const upb_msgdef *upbdefs_google_protobuf_FileOptions_get(const void *owner) { return refm(&msgs[11], owner); }
  6343. const upb_msgdef *upbdefs_google_protobuf_MessageOptions_get(const void *owner) { return refm(&msgs[12], owner); }
  6344. const upb_msgdef *upbdefs_google_protobuf_MethodDescriptorProto_get(const void *owner) { return refm(&msgs[13], owner); }
  6345. const upb_msgdef *upbdefs_google_protobuf_MethodOptions_get(const void *owner) { return refm(&msgs[14], owner); }
  6346. const upb_msgdef *upbdefs_google_protobuf_OneofDescriptorProto_get(const void *owner) { return refm(&msgs[15], owner); }
  6347. const upb_msgdef *upbdefs_google_protobuf_ServiceDescriptorProto_get(const void *owner) { return refm(&msgs[16], owner); }
  6348. const upb_msgdef *upbdefs_google_protobuf_ServiceOptions_get(const void *owner) { return refm(&msgs[17], owner); }
  6349. const upb_msgdef *upbdefs_google_protobuf_SourceCodeInfo_get(const void *owner) { return refm(&msgs[18], owner); }
  6350. const upb_msgdef *upbdefs_google_protobuf_SourceCodeInfo_Location_get(const void *owner) { return refm(&msgs[19], owner); }
  6351. const upb_msgdef *upbdefs_google_protobuf_UninterpretedOption_get(const void *owner) { return refm(&msgs[20], owner); }
  6352. const upb_msgdef *upbdefs_google_protobuf_UninterpretedOption_NamePart_get(const void *owner) { return refm(&msgs[21], owner); }
  6353. const upb_enumdef *upbdefs_google_protobuf_FieldDescriptorProto_Label_get(const void *owner) { return refe(&enums[0], owner); }
  6354. const upb_enumdef *upbdefs_google_protobuf_FieldDescriptorProto_Type_get(const void *owner) { return refe(&enums[1], owner); }
  6355. const upb_enumdef *upbdefs_google_protobuf_FieldOptions_CType_get(const void *owner) { return refe(&enums[2], owner); }
  6356. const upb_enumdef *upbdefs_google_protobuf_FieldOptions_JSType_get(const void *owner) { return refe(&enums[3], owner); }
  6357. const upb_enumdef *upbdefs_google_protobuf_FileOptions_OptimizeMode_get(const void *owner) { return refe(&enums[4], owner); }
  6358. /*
  6359. ** XXX: The routines in this file that consume a string do not currently
  6360. ** support having the string span buffers. In the future, as upb_sink and
  6361. ** its buffering/sharing functionality evolve there should be an easy and
  6362. ** idiomatic way of correctly handling this case. For now, we accept this
  6363. ** limitation since we currently only parse descriptors from single strings.
  6364. */
  6365. #include <errno.h>
  6366. #include <stdlib.h>
  6367. #include <string.h>
  6368. /* Compares a NULL-terminated string with a non-NULL-terminated string. */
  6369. static bool upb_streq(const char *str, const char *buf, size_t n) {
  6370. return strlen(str) == n && memcmp(str, buf, n) == 0;
  6371. }
  6372. /* We keep a stack of all the messages scopes we are currently in, as well as
  6373. * the top-level file scope. This is necessary to correctly qualify the
  6374. * definitions that are contained inside. "name" tracks the name of the
  6375. * message or package (a bare name -- not qualified by any enclosing scopes). */
  6376. typedef struct {
  6377. char *name;
  6378. /* Index of the first def that is under this scope. For msgdefs, the
  6379. * msgdef itself is at start-1. */
  6380. int start;
  6381. uint32_t oneof_start;
  6382. uint32_t oneof_index;
  6383. } upb_descreader_frame;
  6384. /* The maximum number of nested declarations that are allowed, ie.
  6385. * message Foo {
  6386. * message Bar {
  6387. * message Baz {
  6388. * }
  6389. * }
  6390. * }
  6391. *
  6392. * This is a resource limit that affects how big our runtime stack can grow.
  6393. * TODO: make this a runtime-settable property of the Reader instance. */
  6394. #define UPB_MAX_MESSAGE_NESTING 64
  6395. struct upb_descreader {
  6396. upb_sink sink;
  6397. upb_inttable files;
  6398. upb_filedef *file; /* The last file in files. */
  6399. upb_descreader_frame stack[UPB_MAX_MESSAGE_NESTING];
  6400. int stack_len;
  6401. upb_inttable oneofs;
  6402. uint32_t number;
  6403. char *name;
  6404. bool saw_number;
  6405. bool saw_name;
  6406. char *default_string;
  6407. upb_fielddef *f;
  6408. };
  6409. static char *upb_gstrndup(const char *buf, size_t n) {
  6410. char *ret = upb_gmalloc(n + 1);
  6411. if (!ret) return NULL;
  6412. memcpy(ret, buf, n);
  6413. ret[n] = '\0';
  6414. return ret;
  6415. }
  6416. /* Returns a newly allocated string that joins input strings together, for
  6417. * example:
  6418. * join("Foo.Bar", "Baz") -> "Foo.Bar.Baz"
  6419. * join("", "Baz") -> "Baz"
  6420. * Caller owns a ref on the returned string. */
  6421. static char *upb_join(const char *base, const char *name) {
  6422. if (!base || strlen(base) == 0) {
  6423. return upb_gstrdup(name);
  6424. } else {
  6425. char *ret = upb_gmalloc(strlen(base) + strlen(name) + 2);
  6426. if (!ret) {
  6427. return NULL;
  6428. }
  6429. ret[0] = '\0';
  6430. strcat(ret, base);
  6431. strcat(ret, ".");
  6432. strcat(ret, name);
  6433. return ret;
  6434. }
  6435. }
  6436. /* Qualify the defname for all defs starting with offset "start" with "str". */
  6437. static bool upb_descreader_qualify(upb_filedef *f, char *str, int32_t start) {
  6438. size_t i;
  6439. for (i = start; i < upb_filedef_defcount(f); i++) {
  6440. upb_def *def = upb_filedef_mutabledef(f, i);
  6441. char *name = upb_join(str, upb_def_fullname(def));
  6442. if (!name) {
  6443. /* Need better logic here; at this point we've qualified some names but
  6444. * not others. */
  6445. return false;
  6446. }
  6447. upb_def_setfullname(def, name, NULL);
  6448. upb_gfree(name);
  6449. }
  6450. return true;
  6451. }
  6452. /* upb_descreader ************************************************************/
  6453. static upb_msgdef *upb_descreader_top(upb_descreader *r) {
  6454. int index;
  6455. UPB_ASSERT(r->stack_len > 1);
  6456. index = r->stack[r->stack_len-1].start - 1;
  6457. UPB_ASSERT(index >= 0);
  6458. return upb_downcast_msgdef_mutable(upb_filedef_mutabledef(r->file, index));
  6459. }
  6460. static upb_def *upb_descreader_last(upb_descreader *r) {
  6461. return upb_filedef_mutabledef(r->file, upb_filedef_defcount(r->file) - 1);
  6462. }
  6463. /* Start/end handlers for FileDescriptorProto and DescriptorProto (the two
  6464. * entities that have names and can contain sub-definitions. */
  6465. void upb_descreader_startcontainer(upb_descreader *r) {
  6466. upb_descreader_frame *f = &r->stack[r->stack_len++];
  6467. f->start = upb_filedef_defcount(r->file);
  6468. f->oneof_start = upb_inttable_count(&r->oneofs);
  6469. f->oneof_index = 0;
  6470. f->name = NULL;
  6471. }
  6472. bool upb_descreader_endcontainer(upb_descreader *r) {
  6473. upb_descreader_frame *f = &r->stack[r->stack_len - 1];
  6474. while (upb_inttable_count(&r->oneofs) > f->oneof_start) {
  6475. upb_oneofdef *o = upb_value_getptr(upb_inttable_pop(&r->oneofs));
  6476. bool ok = upb_msgdef_addoneof(upb_descreader_top(r), o, &r->oneofs, NULL);
  6477. UPB_ASSERT(ok);
  6478. }
  6479. if (!upb_descreader_qualify(r->file, f->name, f->start)) {
  6480. return false;
  6481. }
  6482. upb_gfree(f->name);
  6483. f->name = NULL;
  6484. r->stack_len--;
  6485. return true;
  6486. }
  6487. void upb_descreader_setscopename(upb_descreader *r, char *str) {
  6488. upb_descreader_frame *f = &r->stack[r->stack_len-1];
  6489. upb_gfree(f->name);
  6490. f->name = str;
  6491. }
  6492. static upb_oneofdef *upb_descreader_getoneof(upb_descreader *r,
  6493. uint32_t index) {
  6494. bool found;
  6495. upb_value val;
  6496. upb_descreader_frame *f = &r->stack[r->stack_len-1];
  6497. /* DescriptorProto messages can be nested, so we will see the nested messages
  6498. * between when we see the FieldDescriptorProto and the OneofDescriptorProto.
  6499. * We need to preserve the oneofs in between these two things. */
  6500. index += f->oneof_start;
  6501. while (upb_inttable_count(&r->oneofs) <= index) {
  6502. upb_inttable_push(&r->oneofs, upb_value_ptr(upb_oneofdef_new(&r->oneofs)));
  6503. }
  6504. found = upb_inttable_lookup(&r->oneofs, index, &val);
  6505. UPB_ASSERT(found);
  6506. return upb_value_getptr(val);
  6507. }
  6508. /** Handlers for google.protobuf.FileDescriptorSet. ***************************/
  6509. static void *fileset_startfile(void *closure, const void *hd) {
  6510. upb_descreader *r = closure;
  6511. UPB_UNUSED(hd);
  6512. r->file = upb_filedef_new(&r->files);
  6513. upb_inttable_push(&r->files, upb_value_ptr(r->file));
  6514. return r;
  6515. }
  6516. /** Handlers for google.protobuf.FileDescriptorProto. *************************/
  6517. static bool file_start(void *closure, const void *hd) {
  6518. upb_descreader *r = closure;
  6519. UPB_UNUSED(hd);
  6520. upb_descreader_startcontainer(r);
  6521. return true;
  6522. }
  6523. static bool file_end(void *closure, const void *hd, upb_status *status) {
  6524. upb_descreader *r = closure;
  6525. UPB_UNUSED(hd);
  6526. UPB_UNUSED(status);
  6527. return upb_descreader_endcontainer(r);
  6528. }
  6529. static size_t file_onname(void *closure, const void *hd, const char *buf,
  6530. size_t n, const upb_bufhandle *handle) {
  6531. upb_descreader *r = closure;
  6532. char *name;
  6533. bool ok;
  6534. UPB_UNUSED(hd);
  6535. UPB_UNUSED(handle);
  6536. name = upb_gstrndup(buf, n);
  6537. /* XXX: see comment at the top of the file. */
  6538. ok = upb_filedef_setname(r->file, name, NULL);
  6539. upb_gfree(name);
  6540. UPB_ASSERT(ok);
  6541. return n;
  6542. }
  6543. static size_t file_onpackage(void *closure, const void *hd, const char *buf,
  6544. size_t n, const upb_bufhandle *handle) {
  6545. upb_descreader *r = closure;
  6546. char *package;
  6547. bool ok;
  6548. UPB_UNUSED(hd);
  6549. UPB_UNUSED(handle);
  6550. package = upb_gstrndup(buf, n);
  6551. /* XXX: see comment at the top of the file. */
  6552. upb_descreader_setscopename(r, package);
  6553. ok = upb_filedef_setpackage(r->file, package, NULL);
  6554. UPB_ASSERT(ok);
  6555. return n;
  6556. }
  6557. static size_t file_onsyntax(void *closure, const void *hd, const char *buf,
  6558. size_t n, const upb_bufhandle *handle) {
  6559. upb_descreader *r = closure;
  6560. bool ok;
  6561. UPB_UNUSED(hd);
  6562. UPB_UNUSED(handle);
  6563. /* XXX: see comment at the top of the file. */
  6564. if (upb_streq("proto2", buf, n)) {
  6565. ok = upb_filedef_setsyntax(r->file, UPB_SYNTAX_PROTO2, NULL);
  6566. } else if (upb_streq("proto3", buf, n)) {
  6567. ok = upb_filedef_setsyntax(r->file, UPB_SYNTAX_PROTO3, NULL);
  6568. } else {
  6569. ok = false;
  6570. }
  6571. UPB_ASSERT(ok);
  6572. return n;
  6573. }
  6574. static void *file_startmsg(void *closure, const void *hd) {
  6575. upb_descreader *r = closure;
  6576. upb_msgdef *m = upb_msgdef_new(&m);
  6577. bool ok = upb_filedef_addmsg(r->file, m, &m, NULL);
  6578. UPB_UNUSED(hd);
  6579. UPB_ASSERT(ok);
  6580. return r;
  6581. }
  6582. static void *file_startenum(void *closure, const void *hd) {
  6583. upb_descreader *r = closure;
  6584. upb_enumdef *e = upb_enumdef_new(&e);
  6585. bool ok = upb_filedef_addenum(r->file, e, &e, NULL);
  6586. UPB_UNUSED(hd);
  6587. UPB_ASSERT(ok);
  6588. return r;
  6589. }
  6590. static void *file_startext(void *closure, const void *hd) {
  6591. upb_descreader *r = closure;
  6592. bool ok;
  6593. r->f = upb_fielddef_new(r);
  6594. ok = upb_filedef_addext(r->file, r->f, r, NULL);
  6595. UPB_UNUSED(hd);
  6596. UPB_ASSERT(ok);
  6597. return r;
  6598. }
  6599. /** Handlers for google.protobuf.EnumValueDescriptorProto. *********************/
  6600. static bool enumval_startmsg(void *closure, const void *hd) {
  6601. upb_descreader *r = closure;
  6602. UPB_UNUSED(hd);
  6603. r->saw_number = false;
  6604. r->saw_name = false;
  6605. return true;
  6606. }
  6607. static size_t enumval_onname(void *closure, const void *hd, const char *buf,
  6608. size_t n, const upb_bufhandle *handle) {
  6609. upb_descreader *r = closure;
  6610. UPB_UNUSED(hd);
  6611. UPB_UNUSED(handle);
  6612. /* XXX: see comment at the top of the file. */
  6613. upb_gfree(r->name);
  6614. r->name = upb_gstrndup(buf, n);
  6615. r->saw_name = true;
  6616. return n;
  6617. }
  6618. static bool enumval_onnumber(void *closure, const void *hd, int32_t val) {
  6619. upb_descreader *r = closure;
  6620. UPB_UNUSED(hd);
  6621. r->number = val;
  6622. r->saw_number = true;
  6623. return true;
  6624. }
  6625. static bool enumval_endmsg(void *closure, const void *hd, upb_status *status) {
  6626. upb_descreader *r = closure;
  6627. upb_enumdef *e;
  6628. UPB_UNUSED(hd);
  6629. if(!r->saw_number || !r->saw_name) {
  6630. upb_status_seterrmsg(status, "Enum value missing name or number.");
  6631. return false;
  6632. }
  6633. e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  6634. upb_enumdef_addval(e, r->name, r->number, status);
  6635. upb_gfree(r->name);
  6636. r->name = NULL;
  6637. return true;
  6638. }
  6639. /** Handlers for google.protobuf.EnumDescriptorProto. *************************/
  6640. static bool enum_endmsg(void *closure, const void *hd, upb_status *status) {
  6641. upb_descreader *r = closure;
  6642. upb_enumdef *e;
  6643. UPB_UNUSED(hd);
  6644. e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  6645. if (upb_def_fullname(upb_descreader_last(r)) == NULL) {
  6646. upb_status_seterrmsg(status, "Enum had no name.");
  6647. return false;
  6648. }
  6649. if (upb_enumdef_numvals(e) == 0) {
  6650. upb_status_seterrmsg(status, "Enum had no values.");
  6651. return false;
  6652. }
  6653. return true;
  6654. }
  6655. static size_t enum_onname(void *closure, const void *hd, const char *buf,
  6656. size_t n, const upb_bufhandle *handle) {
  6657. upb_descreader *r = closure;
  6658. char *fullname = upb_gstrndup(buf, n);
  6659. UPB_UNUSED(hd);
  6660. UPB_UNUSED(handle);
  6661. /* XXX: see comment at the top of the file. */
  6662. upb_def_setfullname(upb_descreader_last(r), fullname, NULL);
  6663. upb_gfree(fullname);
  6664. return n;
  6665. }
  6666. /** Handlers for google.protobuf.FieldDescriptorProto *************************/
  6667. static bool field_startmsg(void *closure, const void *hd) {
  6668. upb_descreader *r = closure;
  6669. UPB_UNUSED(hd);
  6670. UPB_ASSERT(r->f);
  6671. upb_gfree(r->default_string);
  6672. r->default_string = NULL;
  6673. /* fielddefs default to packed, but descriptors default to non-packed. */
  6674. upb_fielddef_setpacked(r->f, false);
  6675. return true;
  6676. }
  6677. /* Converts the default value in string "str" into "d". Passes a ref on str.
  6678. * Returns true on success. */
  6679. static bool parse_default(char *str, upb_fielddef *f) {
  6680. bool success = true;
  6681. char *end;
  6682. switch (upb_fielddef_type(f)) {
  6683. case UPB_TYPE_INT32: {
  6684. long val = strtol(str, &end, 0);
  6685. if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || *end)
  6686. success = false;
  6687. else
  6688. upb_fielddef_setdefaultint32(f, val);
  6689. break;
  6690. }
  6691. case UPB_TYPE_INT64: {
  6692. /* XXX: Need to write our own strtoll, since it's not available in c89. */
  6693. long long val = strtol(str, &end, 0);
  6694. if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || *end)
  6695. success = false;
  6696. else
  6697. upb_fielddef_setdefaultint64(f, val);
  6698. break;
  6699. }
  6700. case UPB_TYPE_UINT32: {
  6701. unsigned long val = strtoul(str, &end, 0);
  6702. if (val > UINT32_MAX || errno == ERANGE || *end)
  6703. success = false;
  6704. else
  6705. upb_fielddef_setdefaultuint32(f, val);
  6706. break;
  6707. }
  6708. case UPB_TYPE_UINT64: {
  6709. /* XXX: Need to write our own strtoull, since it's not available in c89. */
  6710. unsigned long long val = strtoul(str, &end, 0);
  6711. if (val > UINT64_MAX || errno == ERANGE || *end)
  6712. success = false;
  6713. else
  6714. upb_fielddef_setdefaultuint64(f, val);
  6715. break;
  6716. }
  6717. case UPB_TYPE_DOUBLE: {
  6718. double val = strtod(str, &end);
  6719. if (errno == ERANGE || *end)
  6720. success = false;
  6721. else
  6722. upb_fielddef_setdefaultdouble(f, val);
  6723. break;
  6724. }
  6725. case UPB_TYPE_FLOAT: {
  6726. /* XXX: Need to write our own strtof, since it's not available in c89. */
  6727. float val = strtod(str, &end);
  6728. if (errno == ERANGE || *end)
  6729. success = false;
  6730. else
  6731. upb_fielddef_setdefaultfloat(f, val);
  6732. break;
  6733. }
  6734. case UPB_TYPE_BOOL: {
  6735. if (strcmp(str, "false") == 0)
  6736. upb_fielddef_setdefaultbool(f, false);
  6737. else if (strcmp(str, "true") == 0)
  6738. upb_fielddef_setdefaultbool(f, true);
  6739. else
  6740. success = false;
  6741. break;
  6742. }
  6743. default: abort();
  6744. }
  6745. return success;
  6746. }
  6747. static bool field_endmsg(void *closure, const void *hd, upb_status *status) {
  6748. upb_descreader *r = closure;
  6749. upb_fielddef *f = r->f;
  6750. UPB_UNUSED(hd);
  6751. /* TODO: verify that all required fields were present. */
  6752. UPB_ASSERT(upb_fielddef_number(f) != 0);
  6753. UPB_ASSERT(upb_fielddef_name(f) != NULL);
  6754. UPB_ASSERT((upb_fielddef_subdefname(f) != NULL) == upb_fielddef_hassubdef(f));
  6755. if (r->default_string) {
  6756. if (upb_fielddef_issubmsg(f)) {
  6757. upb_status_seterrmsg(status, "Submessages cannot have defaults.");
  6758. return false;
  6759. }
  6760. if (upb_fielddef_isstring(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  6761. upb_fielddef_setdefaultcstr(f, r->default_string, NULL);
  6762. } else {
  6763. if (r->default_string && !parse_default(r->default_string, f)) {
  6764. /* We don't worry too much about giving a great error message since the
  6765. * compiler should have ensured this was correct. */
  6766. upb_status_seterrmsg(status, "Error converting default value.");
  6767. return false;
  6768. }
  6769. }
  6770. }
  6771. return true;
  6772. }
  6773. static bool field_onlazy(void *closure, const void *hd, bool val) {
  6774. upb_descreader *r = closure;
  6775. UPB_UNUSED(hd);
  6776. upb_fielddef_setlazy(r->f, val);
  6777. return true;
  6778. }
  6779. static bool field_onpacked(void *closure, const void *hd, bool val) {
  6780. upb_descreader *r = closure;
  6781. UPB_UNUSED(hd);
  6782. upb_fielddef_setpacked(r->f, val);
  6783. return true;
  6784. }
  6785. static bool field_ontype(void *closure, const void *hd, int32_t val) {
  6786. upb_descreader *r = closure;
  6787. UPB_UNUSED(hd);
  6788. upb_fielddef_setdescriptortype(r->f, val);
  6789. return true;
  6790. }
  6791. static bool field_onlabel(void *closure, const void *hd, int32_t val) {
  6792. upb_descreader *r = closure;
  6793. UPB_UNUSED(hd);
  6794. upb_fielddef_setlabel(r->f, val);
  6795. return true;
  6796. }
  6797. static bool field_onnumber(void *closure, const void *hd, int32_t val) {
  6798. upb_descreader *r = closure;
  6799. bool ok;
  6800. UPB_UNUSED(hd);
  6801. ok = upb_fielddef_setnumber(r->f, val, NULL);
  6802. UPB_ASSERT(ok);
  6803. return true;
  6804. }
  6805. static size_t field_onname(void *closure, const void *hd, const char *buf,
  6806. size_t n, const upb_bufhandle *handle) {
  6807. upb_descreader *r = closure;
  6808. char *name = upb_gstrndup(buf, n);
  6809. UPB_UNUSED(hd);
  6810. UPB_UNUSED(handle);
  6811. /* XXX: see comment at the top of the file. */
  6812. upb_fielddef_setname(r->f, name, NULL);
  6813. upb_gfree(name);
  6814. return n;
  6815. }
  6816. static size_t field_ontypename(void *closure, const void *hd, const char *buf,
  6817. size_t n, const upb_bufhandle *handle) {
  6818. upb_descreader *r = closure;
  6819. char *name = upb_gstrndup(buf, n);
  6820. UPB_UNUSED(hd);
  6821. UPB_UNUSED(handle);
  6822. /* XXX: see comment at the top of the file. */
  6823. upb_fielddef_setsubdefname(r->f, name, NULL);
  6824. upb_gfree(name);
  6825. return n;
  6826. }
  6827. static size_t field_onextendee(void *closure, const void *hd, const char *buf,
  6828. size_t n, const upb_bufhandle *handle) {
  6829. upb_descreader *r = closure;
  6830. char *name = upb_gstrndup(buf, n);
  6831. UPB_UNUSED(hd);
  6832. UPB_UNUSED(handle);
  6833. /* XXX: see comment at the top of the file. */
  6834. upb_fielddef_setcontainingtypename(r->f, name, NULL);
  6835. upb_gfree(name);
  6836. return n;
  6837. }
  6838. static size_t field_ondefaultval(void *closure, const void *hd, const char *buf,
  6839. size_t n, const upb_bufhandle *handle) {
  6840. upb_descreader *r = closure;
  6841. UPB_UNUSED(hd);
  6842. UPB_UNUSED(handle);
  6843. /* Have to convert from string to the correct type, but we might not know the
  6844. * type yet, so we save it as a string until the end of the field.
  6845. * XXX: see comment at the top of the file. */
  6846. upb_gfree(r->default_string);
  6847. r->default_string = upb_gstrndup(buf, n);
  6848. return n;
  6849. }
  6850. static bool field_ononeofindex(void *closure, const void *hd, int32_t index) {
  6851. upb_descreader *r = closure;
  6852. upb_oneofdef *o = upb_descreader_getoneof(r, index);
  6853. bool ok = upb_oneofdef_addfield(o, r->f, &r->f, NULL);
  6854. UPB_UNUSED(hd);
  6855. UPB_ASSERT(ok);
  6856. return true;
  6857. }
  6858. /** Handlers for google.protobuf.OneofDescriptorProto. ************************/
  6859. static size_t oneof_name(void *closure, const void *hd, const char *buf,
  6860. size_t n, const upb_bufhandle *handle) {
  6861. upb_descreader *r = closure;
  6862. upb_descreader_frame *f = &r->stack[r->stack_len-1];
  6863. upb_oneofdef *o = upb_descreader_getoneof(r, f->oneof_index++);
  6864. char *name_null_terminated = upb_gstrndup(buf, n);
  6865. bool ok = upb_oneofdef_setname(o, name_null_terminated, NULL);
  6866. UPB_UNUSED(hd);
  6867. UPB_UNUSED(handle);
  6868. UPB_ASSERT(ok);
  6869. free(name_null_terminated);
  6870. return n;
  6871. }
  6872. /** Handlers for google.protobuf.DescriptorProto ******************************/
  6873. static bool msg_start(void *closure, const void *hd) {
  6874. upb_descreader *r = closure;
  6875. UPB_UNUSED(hd);
  6876. upb_descreader_startcontainer(r);
  6877. return true;
  6878. }
  6879. static bool msg_end(void *closure, const void *hd, upb_status *status) {
  6880. upb_descreader *r = closure;
  6881. upb_msgdef *m = upb_descreader_top(r);
  6882. UPB_UNUSED(hd);
  6883. if(!upb_def_fullname(upb_msgdef_upcast_mutable(m))) {
  6884. upb_status_seterrmsg(status, "Encountered message with no name.");
  6885. return false;
  6886. }
  6887. return upb_descreader_endcontainer(r);
  6888. }
  6889. static size_t msg_name(void *closure, const void *hd, const char *buf,
  6890. size_t n, const upb_bufhandle *handle) {
  6891. upb_descreader *r = closure;
  6892. upb_msgdef *m = upb_descreader_top(r);
  6893. /* XXX: see comment at the top of the file. */
  6894. char *name = upb_gstrndup(buf, n);
  6895. UPB_UNUSED(hd);
  6896. UPB_UNUSED(handle);
  6897. upb_def_setfullname(upb_msgdef_upcast_mutable(m), name, NULL);
  6898. upb_descreader_setscopename(r, name); /* Passes ownership of name. */
  6899. return n;
  6900. }
  6901. static void *msg_startmsg(void *closure, const void *hd) {
  6902. upb_descreader *r = closure;
  6903. upb_msgdef *m = upb_msgdef_new(&m);
  6904. bool ok = upb_filedef_addmsg(r->file, m, &m, NULL);
  6905. UPB_UNUSED(hd);
  6906. UPB_ASSERT(ok);
  6907. return r;
  6908. }
  6909. static void *msg_startext(void *closure, const void *hd) {
  6910. upb_descreader *r = closure;
  6911. upb_fielddef *f = upb_fielddef_new(&f);
  6912. bool ok = upb_filedef_addext(r->file, f, &f, NULL);
  6913. UPB_UNUSED(hd);
  6914. UPB_ASSERT(ok);
  6915. return r;
  6916. }
  6917. static void *msg_startfield(void *closure, const void *hd) {
  6918. upb_descreader *r = closure;
  6919. r->f = upb_fielddef_new(&r->f);
  6920. /* We can't add the new field to the message until its name/number are
  6921. * filled in. */
  6922. UPB_UNUSED(hd);
  6923. return r;
  6924. }
  6925. static bool msg_endfield(void *closure, const void *hd) {
  6926. upb_descreader *r = closure;
  6927. upb_msgdef *m = upb_descreader_top(r);
  6928. bool ok;
  6929. UPB_UNUSED(hd);
  6930. /* Oneof fields are added to the msgdef through their oneof, so don't need to
  6931. * be added here. */
  6932. if (upb_fielddef_containingoneof(r->f) == NULL) {
  6933. ok = upb_msgdef_addfield(m, r->f, &r->f, NULL);
  6934. UPB_ASSERT(ok);
  6935. }
  6936. r->f = NULL;
  6937. return true;
  6938. }
  6939. static bool msg_onmapentry(void *closure, const void *hd, bool mapentry) {
  6940. upb_descreader *r = closure;
  6941. upb_msgdef *m = upb_descreader_top(r);
  6942. UPB_UNUSED(hd);
  6943. upb_msgdef_setmapentry(m, mapentry);
  6944. r->f = NULL;
  6945. return true;
  6946. }
  6947. /** Code to register handlers *************************************************/
  6948. #define F(msg, field) upbdefs_google_protobuf_ ## msg ## _f_ ## field(m)
  6949. static void reghandlers(const void *closure, upb_handlers *h) {
  6950. const upb_msgdef *m = upb_handlers_msgdef(h);
  6951. UPB_UNUSED(closure);
  6952. if (upbdefs_google_protobuf_FileDescriptorSet_is(m)) {
  6953. upb_handlers_setstartsubmsg(h, F(FileDescriptorSet, file),
  6954. &fileset_startfile, NULL);
  6955. } else if (upbdefs_google_protobuf_DescriptorProto_is(m)) {
  6956. upb_handlers_setstartmsg(h, &msg_start, NULL);
  6957. upb_handlers_setendmsg(h, &msg_end, NULL);
  6958. upb_handlers_setstring(h, F(DescriptorProto, name), &msg_name, NULL);
  6959. upb_handlers_setstartsubmsg(h, F(DescriptorProto, extension), &msg_startext,
  6960. NULL);
  6961. upb_handlers_setstartsubmsg(h, F(DescriptorProto, nested_type),
  6962. &msg_startmsg, NULL);
  6963. upb_handlers_setstartsubmsg(h, F(DescriptorProto, field),
  6964. &msg_startfield, NULL);
  6965. upb_handlers_setendsubmsg(h, F(DescriptorProto, field),
  6966. &msg_endfield, NULL);
  6967. upb_handlers_setstartsubmsg(h, F(DescriptorProto, enum_type),
  6968. &file_startenum, NULL);
  6969. } else if (upbdefs_google_protobuf_FileDescriptorProto_is(m)) {
  6970. upb_handlers_setstartmsg(h, &file_start, NULL);
  6971. upb_handlers_setendmsg(h, &file_end, NULL);
  6972. upb_handlers_setstring(h, F(FileDescriptorProto, name), &file_onname,
  6973. NULL);
  6974. upb_handlers_setstring(h, F(FileDescriptorProto, package), &file_onpackage,
  6975. NULL);
  6976. upb_handlers_setstring(h, F(FileDescriptorProto, syntax), &file_onsyntax,
  6977. NULL);
  6978. upb_handlers_setstartsubmsg(h, F(FileDescriptorProto, message_type),
  6979. &file_startmsg, NULL);
  6980. upb_handlers_setstartsubmsg(h, F(FileDescriptorProto, enum_type),
  6981. &file_startenum, NULL);
  6982. upb_handlers_setstartsubmsg(h, F(FileDescriptorProto, extension),
  6983. &file_startext, NULL);
  6984. } else if (upbdefs_google_protobuf_EnumValueDescriptorProto_is(m)) {
  6985. upb_handlers_setstartmsg(h, &enumval_startmsg, NULL);
  6986. upb_handlers_setendmsg(h, &enumval_endmsg, NULL);
  6987. upb_handlers_setstring(h, F(EnumValueDescriptorProto, name), &enumval_onname, NULL);
  6988. upb_handlers_setint32(h, F(EnumValueDescriptorProto, number), &enumval_onnumber,
  6989. NULL);
  6990. } else if (upbdefs_google_protobuf_EnumDescriptorProto_is(m)) {
  6991. upb_handlers_setendmsg(h, &enum_endmsg, NULL);
  6992. upb_handlers_setstring(h, F(EnumDescriptorProto, name), &enum_onname, NULL);
  6993. } else if (upbdefs_google_protobuf_FieldDescriptorProto_is(m)) {
  6994. upb_handlers_setstartmsg(h, &field_startmsg, NULL);
  6995. upb_handlers_setendmsg(h, &field_endmsg, NULL);
  6996. upb_handlers_setint32(h, F(FieldDescriptorProto, type), &field_ontype,
  6997. NULL);
  6998. upb_handlers_setint32(h, F(FieldDescriptorProto, label), &field_onlabel,
  6999. NULL);
  7000. upb_handlers_setint32(h, F(FieldDescriptorProto, number), &field_onnumber,
  7001. NULL);
  7002. upb_handlers_setstring(h, F(FieldDescriptorProto, name), &field_onname,
  7003. NULL);
  7004. upb_handlers_setstring(h, F(FieldDescriptorProto, type_name),
  7005. &field_ontypename, NULL);
  7006. upb_handlers_setstring(h, F(FieldDescriptorProto, extendee),
  7007. &field_onextendee, NULL);
  7008. upb_handlers_setstring(h, F(FieldDescriptorProto, default_value),
  7009. &field_ondefaultval, NULL);
  7010. upb_handlers_setint32(h, F(FieldDescriptorProto, oneof_index),
  7011. &field_ononeofindex, NULL);
  7012. } else if (upbdefs_google_protobuf_OneofDescriptorProto_is(m)) {
  7013. upb_handlers_setstring(h, F(OneofDescriptorProto, name), &oneof_name, NULL);
  7014. } else if (upbdefs_google_protobuf_FieldOptions_is(m)) {
  7015. upb_handlers_setbool(h, F(FieldOptions, lazy), &field_onlazy, NULL);
  7016. upb_handlers_setbool(h, F(FieldOptions, packed), &field_onpacked, NULL);
  7017. } else if (upbdefs_google_protobuf_MessageOptions_is(m)) {
  7018. upb_handlers_setbool(h, F(MessageOptions, map_entry), &msg_onmapentry, NULL);
  7019. }
  7020. UPB_ASSERT(upb_ok(upb_handlers_status(h)));
  7021. }
  7022. #undef F
  7023. void descreader_cleanup(void *_r) {
  7024. upb_descreader *r = _r;
  7025. size_t i;
  7026. for (i = 0; i < upb_descreader_filecount(r); i++) {
  7027. upb_filedef_unref(upb_descreader_file(r, i), &r->files);
  7028. }
  7029. upb_gfree(r->name);
  7030. upb_inttable_uninit(&r->files);
  7031. upb_inttable_uninit(&r->oneofs);
  7032. upb_gfree(r->default_string);
  7033. while (r->stack_len > 0) {
  7034. upb_descreader_frame *f = &r->stack[--r->stack_len];
  7035. upb_gfree(f->name);
  7036. }
  7037. }
  7038. /* Public API ****************************************************************/
  7039. upb_descreader *upb_descreader_create(upb_env *e, const upb_handlers *h) {
  7040. upb_descreader *r = upb_env_malloc(e, sizeof(upb_descreader));
  7041. if (!r || !upb_env_addcleanup(e, descreader_cleanup, r)) {
  7042. return NULL;
  7043. }
  7044. upb_inttable_init(&r->files, UPB_CTYPE_PTR);
  7045. upb_inttable_init(&r->oneofs, UPB_CTYPE_PTR);
  7046. upb_sink_reset(upb_descreader_input(r), h, r);
  7047. r->stack_len = 0;
  7048. r->name = NULL;
  7049. r->default_string = NULL;
  7050. return r;
  7051. }
  7052. size_t upb_descreader_filecount(const upb_descreader *r) {
  7053. return upb_inttable_count(&r->files);
  7054. }
  7055. upb_filedef *upb_descreader_file(const upb_descreader *r, size_t i) {
  7056. upb_value v;
  7057. if (upb_inttable_lookup(&r->files, i, &v)) {
  7058. return upb_value_getptr(v);
  7059. } else {
  7060. return NULL;
  7061. }
  7062. }
  7063. upb_sink *upb_descreader_input(upb_descreader *r) {
  7064. return &r->sink;
  7065. }
  7066. const upb_handlers *upb_descreader_newhandlers(const void *owner) {
  7067. const upb_msgdef *m = upbdefs_google_protobuf_FileDescriptorSet_get(&m);
  7068. const upb_handlers *h = upb_handlers_newfrozen(m, owner, reghandlers, NULL);
  7069. upb_msgdef_unref(m, &m);
  7070. return h;
  7071. }
  7072. /*
  7073. ** protobuf decoder bytecode compiler
  7074. **
  7075. ** Code to compile a upb::Handlers into bytecode for decoding a protobuf
  7076. ** according to that specific schema and destination handlers.
  7077. **
  7078. ** Compiling to bytecode is always the first step. If we are using the
  7079. ** interpreted decoder we leave it as bytecode and interpret that. If we are
  7080. ** using a JIT decoder we use a code generator to turn the bytecode into native
  7081. ** code, LLVM IR, etc.
  7082. **
  7083. ** Bytecode definition is in decoder.int.h.
  7084. */
  7085. #include <stdarg.h>
  7086. #ifdef UPB_DUMP_BYTECODE
  7087. #include <stdio.h>
  7088. #endif
  7089. #define MAXLABEL 5
  7090. #define EMPTYLABEL -1
  7091. /* mgroup *********************************************************************/
  7092. static void freegroup(upb_refcounted *r) {
  7093. mgroup *g = (mgroup*)r;
  7094. upb_inttable_uninit(&g->methods);
  7095. #ifdef UPB_USE_JIT_X64
  7096. upb_pbdecoder_freejit(g);
  7097. #endif
  7098. upb_gfree(g->bytecode);
  7099. upb_gfree(g);
  7100. }
  7101. static void visitgroup(const upb_refcounted *r, upb_refcounted_visit *visit,
  7102. void *closure) {
  7103. const mgroup *g = (const mgroup*)r;
  7104. upb_inttable_iter i;
  7105. upb_inttable_begin(&i, &g->methods);
  7106. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  7107. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  7108. visit(r, upb_pbdecodermethod_upcast(method), closure);
  7109. }
  7110. }
  7111. mgroup *newgroup(const void *owner) {
  7112. mgroup *g = upb_gmalloc(sizeof(*g));
  7113. static const struct upb_refcounted_vtbl vtbl = {visitgroup, freegroup};
  7114. upb_refcounted_init(mgroup_upcast_mutable(g), &vtbl, owner);
  7115. upb_inttable_init(&g->methods, UPB_CTYPE_PTR);
  7116. g->bytecode = NULL;
  7117. g->bytecode_end = NULL;
  7118. return g;
  7119. }
  7120. /* upb_pbdecodermethod ********************************************************/
  7121. static void freemethod(upb_refcounted *r) {
  7122. upb_pbdecodermethod *method = (upb_pbdecodermethod*)r;
  7123. if (method->dest_handlers_) {
  7124. upb_handlers_unref(method->dest_handlers_, method);
  7125. }
  7126. upb_inttable_uninit(&method->dispatch);
  7127. upb_gfree(method);
  7128. }
  7129. static void visitmethod(const upb_refcounted *r, upb_refcounted_visit *visit,
  7130. void *closure) {
  7131. const upb_pbdecodermethod *m = (const upb_pbdecodermethod*)r;
  7132. visit(r, m->group, closure);
  7133. }
  7134. static upb_pbdecodermethod *newmethod(const upb_handlers *dest_handlers,
  7135. mgroup *group) {
  7136. static const struct upb_refcounted_vtbl vtbl = {visitmethod, freemethod};
  7137. upb_pbdecodermethod *ret = upb_gmalloc(sizeof(*ret));
  7138. upb_refcounted_init(upb_pbdecodermethod_upcast_mutable(ret), &vtbl, &ret);
  7139. upb_byteshandler_init(&ret->input_handler_);
  7140. /* The method references the group and vice-versa, in a circular reference. */
  7141. upb_ref2(ret, group);
  7142. upb_ref2(group, ret);
  7143. upb_inttable_insertptr(&group->methods, dest_handlers, upb_value_ptr(ret));
  7144. upb_pbdecodermethod_unref(ret, &ret);
  7145. ret->group = mgroup_upcast_mutable(group);
  7146. ret->dest_handlers_ = dest_handlers;
  7147. ret->is_native_ = false; /* If we JIT, it will update this later. */
  7148. upb_inttable_init(&ret->dispatch, UPB_CTYPE_UINT64);
  7149. if (ret->dest_handlers_) {
  7150. upb_handlers_ref(ret->dest_handlers_, ret);
  7151. }
  7152. return ret;
  7153. }
  7154. const upb_handlers *upb_pbdecodermethod_desthandlers(
  7155. const upb_pbdecodermethod *m) {
  7156. return m->dest_handlers_;
  7157. }
  7158. const upb_byteshandler *upb_pbdecodermethod_inputhandler(
  7159. const upb_pbdecodermethod *m) {
  7160. return &m->input_handler_;
  7161. }
  7162. bool upb_pbdecodermethod_isnative(const upb_pbdecodermethod *m) {
  7163. return m->is_native_;
  7164. }
  7165. const upb_pbdecodermethod *upb_pbdecodermethod_new(
  7166. const upb_pbdecodermethodopts *opts, const void *owner) {
  7167. const upb_pbdecodermethod *ret;
  7168. upb_pbcodecache cache;
  7169. upb_pbcodecache_init(&cache);
  7170. ret = upb_pbcodecache_getdecodermethod(&cache, opts);
  7171. upb_pbdecodermethod_ref(ret, owner);
  7172. upb_pbcodecache_uninit(&cache);
  7173. return ret;
  7174. }
  7175. /* bytecode compiler **********************************************************/
  7176. /* Data used only at compilation time. */
  7177. typedef struct {
  7178. mgroup *group;
  7179. uint32_t *pc;
  7180. int fwd_labels[MAXLABEL];
  7181. int back_labels[MAXLABEL];
  7182. /* For fields marked "lazy", parse them lazily or eagerly? */
  7183. bool lazy;
  7184. } compiler;
  7185. static compiler *newcompiler(mgroup *group, bool lazy) {
  7186. compiler *ret = upb_gmalloc(sizeof(*ret));
  7187. int i;
  7188. ret->group = group;
  7189. ret->lazy = lazy;
  7190. for (i = 0; i < MAXLABEL; i++) {
  7191. ret->fwd_labels[i] = EMPTYLABEL;
  7192. ret->back_labels[i] = EMPTYLABEL;
  7193. }
  7194. return ret;
  7195. }
  7196. static void freecompiler(compiler *c) {
  7197. upb_gfree(c);
  7198. }
  7199. const size_t ptr_words = sizeof(void*) / sizeof(uint32_t);
  7200. /* How many words an instruction is. */
  7201. static int instruction_len(uint32_t instr) {
  7202. switch (getop(instr)) {
  7203. case OP_SETDISPATCH: return 1 + ptr_words;
  7204. case OP_TAGN: return 3;
  7205. case OP_SETBIGGROUPNUM: return 2;
  7206. default: return 1;
  7207. }
  7208. }
  7209. bool op_has_longofs(int32_t instruction) {
  7210. switch (getop(instruction)) {
  7211. case OP_CALL:
  7212. case OP_BRANCH:
  7213. case OP_CHECKDELIM:
  7214. return true;
  7215. /* The "tag" instructions only have 8 bytes available for the jump target,
  7216. * but that is ok because these opcodes only require short jumps. */
  7217. case OP_TAG1:
  7218. case OP_TAG2:
  7219. case OP_TAGN:
  7220. return false;
  7221. default:
  7222. UPB_ASSERT(false);
  7223. return false;
  7224. }
  7225. }
  7226. static int32_t getofs(uint32_t instruction) {
  7227. if (op_has_longofs(instruction)) {
  7228. return (int32_t)instruction >> 8;
  7229. } else {
  7230. return (int8_t)(instruction >> 8);
  7231. }
  7232. }
  7233. static void setofs(uint32_t *instruction, int32_t ofs) {
  7234. if (op_has_longofs(*instruction)) {
  7235. *instruction = getop(*instruction) | ofs << 8;
  7236. } else {
  7237. *instruction = (*instruction & ~0xff00) | ((ofs & 0xff) << 8);
  7238. }
  7239. UPB_ASSERT(getofs(*instruction) == ofs); /* Would fail in cases of overflow. */
  7240. }
  7241. static uint32_t pcofs(compiler *c) { return c->pc - c->group->bytecode; }
  7242. /* Defines a local label at the current PC location. All previous forward
  7243. * references are updated to point to this location. The location is noted
  7244. * for any future backward references. */
  7245. static void label(compiler *c, unsigned int label) {
  7246. int val;
  7247. uint32_t *codep;
  7248. UPB_ASSERT(label < MAXLABEL);
  7249. val = c->fwd_labels[label];
  7250. codep = (val == EMPTYLABEL) ? NULL : c->group->bytecode + val;
  7251. while (codep) {
  7252. int ofs = getofs(*codep);
  7253. setofs(codep, c->pc - codep - instruction_len(*codep));
  7254. codep = ofs ? codep + ofs : NULL;
  7255. }
  7256. c->fwd_labels[label] = EMPTYLABEL;
  7257. c->back_labels[label] = pcofs(c);
  7258. }
  7259. /* Creates a reference to a numbered label; either a forward reference
  7260. * (positive arg) or backward reference (negative arg). For forward references
  7261. * the value returned now is actually a "next" pointer into a linked list of all
  7262. * instructions that use this label and will be patched later when the label is
  7263. * defined with label().
  7264. *
  7265. * The returned value is the offset that should be written into the instruction.
  7266. */
  7267. static int32_t labelref(compiler *c, int label) {
  7268. UPB_ASSERT(label < MAXLABEL);
  7269. if (label == LABEL_DISPATCH) {
  7270. /* No resolving required. */
  7271. return 0;
  7272. } else if (label < 0) {
  7273. /* Backward local label. Relative to the next instruction. */
  7274. uint32_t from = (c->pc + 1) - c->group->bytecode;
  7275. return c->back_labels[-label] - from;
  7276. } else {
  7277. /* Forward local label: prepend to (possibly-empty) linked list. */
  7278. int *lptr = &c->fwd_labels[label];
  7279. int32_t ret = (*lptr == EMPTYLABEL) ? 0 : *lptr - pcofs(c);
  7280. *lptr = pcofs(c);
  7281. return ret;
  7282. }
  7283. }
  7284. static void put32(compiler *c, uint32_t v) {
  7285. mgroup *g = c->group;
  7286. if (c->pc == g->bytecode_end) {
  7287. int ofs = pcofs(c);
  7288. size_t oldsize = g->bytecode_end - g->bytecode;
  7289. size_t newsize = UPB_MAX(oldsize * 2, 64);
  7290. /* TODO(haberman): handle OOM. */
  7291. g->bytecode = upb_grealloc(g->bytecode, oldsize * sizeof(uint32_t),
  7292. newsize * sizeof(uint32_t));
  7293. g->bytecode_end = g->bytecode + newsize;
  7294. c->pc = g->bytecode + ofs;
  7295. }
  7296. *c->pc++ = v;
  7297. }
  7298. static void putop(compiler *c, opcode op, ...) {
  7299. va_list ap;
  7300. va_start(ap, op);
  7301. switch (op) {
  7302. case OP_SETDISPATCH: {
  7303. uintptr_t ptr = (uintptr_t)va_arg(ap, void*);
  7304. put32(c, OP_SETDISPATCH);
  7305. put32(c, ptr);
  7306. if (sizeof(uintptr_t) > sizeof(uint32_t))
  7307. put32(c, (uint64_t)ptr >> 32);
  7308. break;
  7309. }
  7310. case OP_STARTMSG:
  7311. case OP_ENDMSG:
  7312. case OP_PUSHLENDELIM:
  7313. case OP_POP:
  7314. case OP_SETDELIM:
  7315. case OP_HALT:
  7316. case OP_RET:
  7317. case OP_DISPATCH:
  7318. put32(c, op);
  7319. break;
  7320. case OP_PARSE_DOUBLE:
  7321. case OP_PARSE_FLOAT:
  7322. case OP_PARSE_INT64:
  7323. case OP_PARSE_UINT64:
  7324. case OP_PARSE_INT32:
  7325. case OP_PARSE_FIXED64:
  7326. case OP_PARSE_FIXED32:
  7327. case OP_PARSE_BOOL:
  7328. case OP_PARSE_UINT32:
  7329. case OP_PARSE_SFIXED32:
  7330. case OP_PARSE_SFIXED64:
  7331. case OP_PARSE_SINT32:
  7332. case OP_PARSE_SINT64:
  7333. case OP_STARTSEQ:
  7334. case OP_ENDSEQ:
  7335. case OP_STARTSUBMSG:
  7336. case OP_ENDSUBMSG:
  7337. case OP_STARTSTR:
  7338. case OP_STRING:
  7339. case OP_ENDSTR:
  7340. case OP_PUSHTAGDELIM:
  7341. put32(c, op | va_arg(ap, upb_selector_t) << 8);
  7342. break;
  7343. case OP_SETBIGGROUPNUM:
  7344. put32(c, op);
  7345. put32(c, va_arg(ap, int));
  7346. break;
  7347. case OP_CALL: {
  7348. const upb_pbdecodermethod *method = va_arg(ap, upb_pbdecodermethod *);
  7349. put32(c, op | (method->code_base.ofs - (pcofs(c) + 1)) << 8);
  7350. break;
  7351. }
  7352. case OP_CHECKDELIM:
  7353. case OP_BRANCH: {
  7354. uint32_t instruction = op;
  7355. int label = va_arg(ap, int);
  7356. setofs(&instruction, labelref(c, label));
  7357. put32(c, instruction);
  7358. break;
  7359. }
  7360. case OP_TAG1:
  7361. case OP_TAG2: {
  7362. int label = va_arg(ap, int);
  7363. uint64_t tag = va_arg(ap, uint64_t);
  7364. uint32_t instruction = op | (tag << 16);
  7365. UPB_ASSERT(tag <= 0xffff);
  7366. setofs(&instruction, labelref(c, label));
  7367. put32(c, instruction);
  7368. break;
  7369. }
  7370. case OP_TAGN: {
  7371. int label = va_arg(ap, int);
  7372. uint64_t tag = va_arg(ap, uint64_t);
  7373. uint32_t instruction = op | (upb_value_size(tag) << 16);
  7374. setofs(&instruction, labelref(c, label));
  7375. put32(c, instruction);
  7376. put32(c, tag);
  7377. put32(c, tag >> 32);
  7378. break;
  7379. }
  7380. }
  7381. va_end(ap);
  7382. }
  7383. #if defined(UPB_USE_JIT_X64) || defined(UPB_DUMP_BYTECODE)
  7384. const char *upb_pbdecoder_getopname(unsigned int op) {
  7385. #define QUOTE(x) #x
  7386. #define EXPAND_AND_QUOTE(x) QUOTE(x)
  7387. #define OPNAME(x) OP_##x
  7388. #define OP(x) case OPNAME(x): return EXPAND_AND_QUOTE(OPNAME(x));
  7389. #define T(x) OP(PARSE_##x)
  7390. /* Keep in sync with list in decoder.int.h. */
  7391. switch ((opcode)op) {
  7392. T(DOUBLE) T(FLOAT) T(INT64) T(UINT64) T(INT32) T(FIXED64) T(FIXED32)
  7393. T(BOOL) T(UINT32) T(SFIXED32) T(SFIXED64) T(SINT32) T(SINT64)
  7394. OP(STARTMSG) OP(ENDMSG) OP(STARTSEQ) OP(ENDSEQ) OP(STARTSUBMSG)
  7395. OP(ENDSUBMSG) OP(STARTSTR) OP(STRING) OP(ENDSTR) OP(CALL) OP(RET)
  7396. OP(PUSHLENDELIM) OP(PUSHTAGDELIM) OP(SETDELIM) OP(CHECKDELIM)
  7397. OP(BRANCH) OP(TAG1) OP(TAG2) OP(TAGN) OP(SETDISPATCH) OP(POP)
  7398. OP(SETBIGGROUPNUM) OP(DISPATCH) OP(HALT)
  7399. }
  7400. return "<unknown op>";
  7401. #undef OP
  7402. #undef T
  7403. }
  7404. #endif
  7405. #ifdef UPB_DUMP_BYTECODE
  7406. static void dumpbc(uint32_t *p, uint32_t *end, FILE *f) {
  7407. uint32_t *begin = p;
  7408. while (p < end) {
  7409. fprintf(f, "%p %8tx", p, p - begin);
  7410. uint32_t instr = *p++;
  7411. uint8_t op = getop(instr);
  7412. fprintf(f, " %s", upb_pbdecoder_getopname(op));
  7413. switch ((opcode)op) {
  7414. case OP_SETDISPATCH: {
  7415. const upb_inttable *dispatch;
  7416. memcpy(&dispatch, p, sizeof(void*));
  7417. p += ptr_words;
  7418. const upb_pbdecodermethod *method =
  7419. (void *)((char *)dispatch -
  7420. offsetof(upb_pbdecodermethod, dispatch));
  7421. fprintf(f, " %s", upb_msgdef_fullname(
  7422. upb_handlers_msgdef(method->dest_handlers_)));
  7423. break;
  7424. }
  7425. case OP_DISPATCH:
  7426. case OP_STARTMSG:
  7427. case OP_ENDMSG:
  7428. case OP_PUSHLENDELIM:
  7429. case OP_POP:
  7430. case OP_SETDELIM:
  7431. case OP_HALT:
  7432. case OP_RET:
  7433. break;
  7434. case OP_PARSE_DOUBLE:
  7435. case OP_PARSE_FLOAT:
  7436. case OP_PARSE_INT64:
  7437. case OP_PARSE_UINT64:
  7438. case OP_PARSE_INT32:
  7439. case OP_PARSE_FIXED64:
  7440. case OP_PARSE_FIXED32:
  7441. case OP_PARSE_BOOL:
  7442. case OP_PARSE_UINT32:
  7443. case OP_PARSE_SFIXED32:
  7444. case OP_PARSE_SFIXED64:
  7445. case OP_PARSE_SINT32:
  7446. case OP_PARSE_SINT64:
  7447. case OP_STARTSEQ:
  7448. case OP_ENDSEQ:
  7449. case OP_STARTSUBMSG:
  7450. case OP_ENDSUBMSG:
  7451. case OP_STARTSTR:
  7452. case OP_STRING:
  7453. case OP_ENDSTR:
  7454. case OP_PUSHTAGDELIM:
  7455. fprintf(f, " %d", instr >> 8);
  7456. break;
  7457. case OP_SETBIGGROUPNUM:
  7458. fprintf(f, " %d", *p++);
  7459. break;
  7460. case OP_CHECKDELIM:
  7461. case OP_CALL:
  7462. case OP_BRANCH:
  7463. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  7464. break;
  7465. case OP_TAG1:
  7466. case OP_TAG2: {
  7467. fprintf(f, " tag:0x%x", instr >> 16);
  7468. if (getofs(instr)) {
  7469. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  7470. }
  7471. break;
  7472. }
  7473. case OP_TAGN: {
  7474. uint64_t tag = *p++;
  7475. tag |= (uint64_t)*p++ << 32;
  7476. fprintf(f, " tag:0x%llx", (long long)tag);
  7477. fprintf(f, " n:%d", instr >> 16);
  7478. if (getofs(instr)) {
  7479. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  7480. }
  7481. break;
  7482. }
  7483. }
  7484. fputs("\n", f);
  7485. }
  7486. }
  7487. #endif
  7488. static uint64_t get_encoded_tag(const upb_fielddef *f, int wire_type) {
  7489. uint32_t tag = (upb_fielddef_number(f) << 3) | wire_type;
  7490. uint64_t encoded_tag = upb_vencode32(tag);
  7491. /* No tag should be greater than 5 bytes. */
  7492. UPB_ASSERT(encoded_tag <= 0xffffffffff);
  7493. return encoded_tag;
  7494. }
  7495. static void putchecktag(compiler *c, const upb_fielddef *f,
  7496. int wire_type, int dest) {
  7497. uint64_t tag = get_encoded_tag(f, wire_type);
  7498. switch (upb_value_size(tag)) {
  7499. case 1:
  7500. putop(c, OP_TAG1, dest, tag);
  7501. break;
  7502. case 2:
  7503. putop(c, OP_TAG2, dest, tag);
  7504. break;
  7505. default:
  7506. putop(c, OP_TAGN, dest, tag);
  7507. break;
  7508. }
  7509. }
  7510. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  7511. upb_selector_t selector;
  7512. bool ok = upb_handlers_getselector(f, type, &selector);
  7513. UPB_ASSERT(ok);
  7514. return selector;
  7515. }
  7516. /* Takes an existing, primary dispatch table entry and repacks it with a
  7517. * different alternate wire type. Called when we are inserting a secondary
  7518. * dispatch table entry for an alternate wire type. */
  7519. static uint64_t repack(uint64_t dispatch, int new_wt2) {
  7520. uint64_t ofs;
  7521. uint8_t wt1;
  7522. uint8_t old_wt2;
  7523. upb_pbdecoder_unpackdispatch(dispatch, &ofs, &wt1, &old_wt2);
  7524. UPB_ASSERT(old_wt2 == NO_WIRE_TYPE); /* wt2 should not be set yet. */
  7525. return upb_pbdecoder_packdispatch(ofs, wt1, new_wt2);
  7526. }
  7527. /* Marks the current bytecode position as the dispatch target for this message,
  7528. * field, and wire type. */
  7529. static void dispatchtarget(compiler *c, upb_pbdecodermethod *method,
  7530. const upb_fielddef *f, int wire_type) {
  7531. /* Offset is relative to msg base. */
  7532. uint64_t ofs = pcofs(c) - method->code_base.ofs;
  7533. uint32_t fn = upb_fielddef_number(f);
  7534. upb_inttable *d = &method->dispatch;
  7535. upb_value v;
  7536. if (upb_inttable_remove(d, fn, &v)) {
  7537. /* TODO: prioritize based on packed setting in .proto file. */
  7538. uint64_t repacked = repack(upb_value_getuint64(v), wire_type);
  7539. upb_inttable_insert(d, fn, upb_value_uint64(repacked));
  7540. upb_inttable_insert(d, fn + UPB_MAX_FIELDNUMBER, upb_value_uint64(ofs));
  7541. } else {
  7542. uint64_t val = upb_pbdecoder_packdispatch(ofs, wire_type, NO_WIRE_TYPE);
  7543. upb_inttable_insert(d, fn, upb_value_uint64(val));
  7544. }
  7545. }
  7546. static void putpush(compiler *c, const upb_fielddef *f) {
  7547. if (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE) {
  7548. putop(c, OP_PUSHLENDELIM);
  7549. } else {
  7550. uint32_t fn = upb_fielddef_number(f);
  7551. if (fn >= 1 << 24) {
  7552. putop(c, OP_PUSHTAGDELIM, 0);
  7553. putop(c, OP_SETBIGGROUPNUM, fn);
  7554. } else {
  7555. putop(c, OP_PUSHTAGDELIM, fn);
  7556. }
  7557. }
  7558. }
  7559. static upb_pbdecodermethod *find_submethod(const compiler *c,
  7560. const upb_pbdecodermethod *method,
  7561. const upb_fielddef *f) {
  7562. const upb_handlers *sub =
  7563. upb_handlers_getsubhandlers(method->dest_handlers_, f);
  7564. upb_value v;
  7565. return upb_inttable_lookupptr(&c->group->methods, sub, &v)
  7566. ? upb_value_getptr(v)
  7567. : NULL;
  7568. }
  7569. static void putsel(compiler *c, opcode op, upb_selector_t sel,
  7570. const upb_handlers *h) {
  7571. if (upb_handlers_gethandler(h, sel)) {
  7572. putop(c, op, sel);
  7573. }
  7574. }
  7575. /* Puts an opcode to call a callback, but only if a callback actually exists for
  7576. * this field and handler type. */
  7577. static void maybeput(compiler *c, opcode op, const upb_handlers *h,
  7578. const upb_fielddef *f, upb_handlertype_t type) {
  7579. putsel(c, op, getsel(f, type), h);
  7580. }
  7581. static bool haslazyhandlers(const upb_handlers *h, const upb_fielddef *f) {
  7582. if (!upb_fielddef_lazy(f))
  7583. return false;
  7584. return upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STARTSTR)) ||
  7585. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STRING)) ||
  7586. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_ENDSTR));
  7587. }
  7588. /* bytecode compiler code generation ******************************************/
  7589. /* Symbolic names for our local labels. */
  7590. #define LABEL_LOOPSTART 1 /* Top of a repeated field loop. */
  7591. #define LABEL_LOOPBREAK 2 /* To jump out of a repeated loop */
  7592. #define LABEL_FIELD 3 /* Jump backward to find the most recent field. */
  7593. #define LABEL_ENDMSG 4 /* To reach the OP_ENDMSG instr for this msg. */
  7594. /* Generates bytecode to parse a single non-lazy message field. */
  7595. static void generate_msgfield(compiler *c, const upb_fielddef *f,
  7596. upb_pbdecodermethod *method) {
  7597. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  7598. const upb_pbdecodermethod *sub_m = find_submethod(c, method, f);
  7599. int wire_type;
  7600. if (!sub_m) {
  7601. /* Don't emit any code for this field at all; it will be parsed as an
  7602. * unknown field.
  7603. *
  7604. * TODO(haberman): we should change this to parse it as a string field
  7605. * instead. It will probably be faster, but more importantly, once we
  7606. * start vending unknown fields, a field shouldn't be treated as unknown
  7607. * just because it doesn't have subhandlers registered. */
  7608. return;
  7609. }
  7610. label(c, LABEL_FIELD);
  7611. wire_type =
  7612. (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE)
  7613. ? UPB_WIRE_TYPE_DELIMITED
  7614. : UPB_WIRE_TYPE_START_GROUP;
  7615. if (upb_fielddef_isseq(f)) {
  7616. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  7617. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  7618. dispatchtarget(c, method, f, wire_type);
  7619. putop(c, OP_PUSHTAGDELIM, 0);
  7620. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  7621. label(c, LABEL_LOOPSTART);
  7622. putpush(c, f);
  7623. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  7624. putop(c, OP_CALL, sub_m);
  7625. putop(c, OP_POP);
  7626. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  7627. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  7628. putop(c, OP_SETDELIM);
  7629. }
  7630. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  7631. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  7632. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  7633. label(c, LABEL_LOOPBREAK);
  7634. putop(c, OP_POP);
  7635. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  7636. } else {
  7637. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  7638. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  7639. dispatchtarget(c, method, f, wire_type);
  7640. putpush(c, f);
  7641. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  7642. putop(c, OP_CALL, sub_m);
  7643. putop(c, OP_POP);
  7644. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  7645. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  7646. putop(c, OP_SETDELIM);
  7647. }
  7648. }
  7649. }
  7650. /* Generates bytecode to parse a single string or lazy submessage field. */
  7651. static void generate_delimfield(compiler *c, const upb_fielddef *f,
  7652. upb_pbdecodermethod *method) {
  7653. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  7654. label(c, LABEL_FIELD);
  7655. if (upb_fielddef_isseq(f)) {
  7656. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  7657. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  7658. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  7659. putop(c, OP_PUSHTAGDELIM, 0);
  7660. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  7661. label(c, LABEL_LOOPSTART);
  7662. putop(c, OP_PUSHLENDELIM);
  7663. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  7664. /* Need to emit even if no handler to skip past the string. */
  7665. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  7666. putop(c, OP_POP);
  7667. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  7668. putop(c, OP_SETDELIM);
  7669. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  7670. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_LOOPBREAK);
  7671. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  7672. label(c, LABEL_LOOPBREAK);
  7673. putop(c, OP_POP);
  7674. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  7675. } else {
  7676. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  7677. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  7678. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  7679. putop(c, OP_PUSHLENDELIM);
  7680. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  7681. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  7682. putop(c, OP_POP);
  7683. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  7684. putop(c, OP_SETDELIM);
  7685. }
  7686. }
  7687. /* Generates bytecode to parse a single primitive field. */
  7688. static void generate_primitivefield(compiler *c, const upb_fielddef *f,
  7689. upb_pbdecodermethod *method) {
  7690. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  7691. upb_descriptortype_t descriptor_type = upb_fielddef_descriptortype(f);
  7692. opcode parse_type;
  7693. upb_selector_t sel;
  7694. int wire_type;
  7695. label(c, LABEL_FIELD);
  7696. /* From a decoding perspective, ENUM is the same as INT32. */
  7697. if (descriptor_type == UPB_DESCRIPTOR_TYPE_ENUM)
  7698. descriptor_type = UPB_DESCRIPTOR_TYPE_INT32;
  7699. parse_type = (opcode)descriptor_type;
  7700. /* TODO(haberman): generate packed or non-packed first depending on "packed"
  7701. * setting in the fielddef. This will favor (in speed) whichever was
  7702. * specified. */
  7703. UPB_ASSERT((int)parse_type >= 0 && parse_type <= OP_MAX);
  7704. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  7705. wire_type = upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  7706. if (upb_fielddef_isseq(f)) {
  7707. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  7708. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  7709. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  7710. putop(c, OP_PUSHLENDELIM);
  7711. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Packed */
  7712. label(c, LABEL_LOOPSTART);
  7713. putop(c, parse_type, sel);
  7714. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  7715. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  7716. dispatchtarget(c, method, f, wire_type);
  7717. putop(c, OP_PUSHTAGDELIM, 0);
  7718. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Non-packed */
  7719. label(c, LABEL_LOOPSTART);
  7720. putop(c, parse_type, sel);
  7721. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  7722. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  7723. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  7724. label(c, LABEL_LOOPBREAK);
  7725. putop(c, OP_POP); /* Packed and non-packed join. */
  7726. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  7727. putop(c, OP_SETDELIM); /* Could remove for non-packed by dup ENDSEQ. */
  7728. } else {
  7729. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  7730. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  7731. dispatchtarget(c, method, f, wire_type);
  7732. putop(c, parse_type, sel);
  7733. }
  7734. }
  7735. /* Adds bytecode for parsing the given message to the given decoderplan,
  7736. * while adding all dispatch targets to this message's dispatch table. */
  7737. static void compile_method(compiler *c, upb_pbdecodermethod *method) {
  7738. const upb_handlers *h;
  7739. const upb_msgdef *md;
  7740. uint32_t* start_pc;
  7741. upb_msg_field_iter i;
  7742. upb_value val;
  7743. UPB_ASSERT(method);
  7744. /* Clear all entries in the dispatch table. */
  7745. upb_inttable_uninit(&method->dispatch);
  7746. upb_inttable_init(&method->dispatch, UPB_CTYPE_UINT64);
  7747. h = upb_pbdecodermethod_desthandlers(method);
  7748. md = upb_handlers_msgdef(h);
  7749. method->code_base.ofs = pcofs(c);
  7750. putop(c, OP_SETDISPATCH, &method->dispatch);
  7751. putsel(c, OP_STARTMSG, UPB_STARTMSG_SELECTOR, h);
  7752. label(c, LABEL_FIELD);
  7753. start_pc = c->pc;
  7754. for(upb_msg_field_begin(&i, md);
  7755. !upb_msg_field_done(&i);
  7756. upb_msg_field_next(&i)) {
  7757. const upb_fielddef *f = upb_msg_iter_field(&i);
  7758. upb_fieldtype_t type = upb_fielddef_type(f);
  7759. if (type == UPB_TYPE_MESSAGE && !(haslazyhandlers(h, f) && c->lazy)) {
  7760. generate_msgfield(c, f, method);
  7761. } else if (type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES ||
  7762. type == UPB_TYPE_MESSAGE) {
  7763. generate_delimfield(c, f, method);
  7764. } else {
  7765. generate_primitivefield(c, f, method);
  7766. }
  7767. }
  7768. /* If there were no fields, or if no handlers were defined, we need to
  7769. * generate a non-empty loop body so that we can at least dispatch for unknown
  7770. * fields and check for the end of the message. */
  7771. if (c->pc == start_pc) {
  7772. /* Check for end-of-message. */
  7773. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  7774. /* Unconditionally dispatch. */
  7775. putop(c, OP_DISPATCH, 0);
  7776. }
  7777. /* For now we just loop back to the last field of the message (or if none,
  7778. * the DISPATCH opcode for the message). */
  7779. putop(c, OP_BRANCH, -LABEL_FIELD);
  7780. /* Insert both a label and a dispatch table entry for this end-of-msg. */
  7781. label(c, LABEL_ENDMSG);
  7782. val = upb_value_uint64(pcofs(c) - method->code_base.ofs);
  7783. upb_inttable_insert(&method->dispatch, DISPATCH_ENDMSG, val);
  7784. putsel(c, OP_ENDMSG, UPB_ENDMSG_SELECTOR, h);
  7785. putop(c, OP_RET);
  7786. upb_inttable_compact(&method->dispatch);
  7787. }
  7788. /* Populate "methods" with new upb_pbdecodermethod objects reachable from "h".
  7789. * Returns the method for these handlers.
  7790. *
  7791. * Generates a new method for every destination handlers reachable from "h". */
  7792. static void find_methods(compiler *c, const upb_handlers *h) {
  7793. upb_value v;
  7794. upb_msg_field_iter i;
  7795. const upb_msgdef *md;
  7796. if (upb_inttable_lookupptr(&c->group->methods, h, &v))
  7797. return;
  7798. newmethod(h, c->group);
  7799. /* Find submethods. */
  7800. md = upb_handlers_msgdef(h);
  7801. for(upb_msg_field_begin(&i, md);
  7802. !upb_msg_field_done(&i);
  7803. upb_msg_field_next(&i)) {
  7804. const upb_fielddef *f = upb_msg_iter_field(&i);
  7805. const upb_handlers *sub_h;
  7806. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  7807. (sub_h = upb_handlers_getsubhandlers(h, f)) != NULL) {
  7808. /* We only generate a decoder method for submessages with handlers.
  7809. * Others will be parsed as unknown fields. */
  7810. find_methods(c, sub_h);
  7811. }
  7812. }
  7813. }
  7814. /* (Re-)compile bytecode for all messages in "msgs."
  7815. * Overwrites any existing bytecode in "c". */
  7816. static void compile_methods(compiler *c) {
  7817. upb_inttable_iter i;
  7818. /* Start over at the beginning of the bytecode. */
  7819. c->pc = c->group->bytecode;
  7820. upb_inttable_begin(&i, &c->group->methods);
  7821. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  7822. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  7823. compile_method(c, method);
  7824. }
  7825. }
  7826. static void set_bytecode_handlers(mgroup *g) {
  7827. upb_inttable_iter i;
  7828. upb_inttable_begin(&i, &g->methods);
  7829. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  7830. upb_pbdecodermethod *m = upb_value_getptr(upb_inttable_iter_value(&i));
  7831. upb_byteshandler *h = &m->input_handler_;
  7832. m->code_base.ptr = g->bytecode + m->code_base.ofs;
  7833. upb_byteshandler_setstartstr(h, upb_pbdecoder_startbc, m->code_base.ptr);
  7834. upb_byteshandler_setstring(h, upb_pbdecoder_decode, g);
  7835. upb_byteshandler_setendstr(h, upb_pbdecoder_end, m);
  7836. }
  7837. }
  7838. /* JIT setup. *****************************************************************/
  7839. #ifdef UPB_USE_JIT_X64
  7840. static void sethandlers(mgroup *g, bool allowjit) {
  7841. g->jit_code = NULL;
  7842. if (allowjit) {
  7843. /* Compile byte-code into machine code, create handlers. */
  7844. upb_pbdecoder_jit(g);
  7845. } else {
  7846. set_bytecode_handlers(g);
  7847. }
  7848. }
  7849. #else /* UPB_USE_JIT_X64 */
  7850. static void sethandlers(mgroup *g, bool allowjit) {
  7851. /* No JIT compiled in; use bytecode handlers unconditionally. */
  7852. UPB_UNUSED(allowjit);
  7853. set_bytecode_handlers(g);
  7854. }
  7855. #endif /* UPB_USE_JIT_X64 */
  7856. /* TODO(haberman): allow this to be constructed for an arbitrary set of dest
  7857. * handlers and other mgroups (but verify we have a transitive closure). */
  7858. const mgroup *mgroup_new(const upb_handlers *dest, bool allowjit, bool lazy,
  7859. const void *owner) {
  7860. mgroup *g;
  7861. compiler *c;
  7862. UPB_UNUSED(allowjit);
  7863. UPB_ASSERT(upb_handlers_isfrozen(dest));
  7864. g = newgroup(owner);
  7865. c = newcompiler(g, lazy);
  7866. find_methods(c, dest);
  7867. /* We compile in two passes:
  7868. * 1. all messages are assigned relative offsets from the beginning of the
  7869. * bytecode (saved in method->code_base).
  7870. * 2. forwards OP_CALL instructions can be correctly linked since message
  7871. * offsets have been previously assigned.
  7872. *
  7873. * Could avoid the second pass by linking OP_CALL instructions somehow. */
  7874. compile_methods(c);
  7875. compile_methods(c);
  7876. g->bytecode_end = c->pc;
  7877. freecompiler(c);
  7878. #ifdef UPB_DUMP_BYTECODE
  7879. {
  7880. FILE *f = fopen("/tmp/upb-bytecode", "w");
  7881. UPB_ASSERT(f);
  7882. dumpbc(g->bytecode, g->bytecode_end, stderr);
  7883. dumpbc(g->bytecode, g->bytecode_end, f);
  7884. fclose(f);
  7885. f = fopen("/tmp/upb-bytecode.bin", "wb");
  7886. UPB_ASSERT(f);
  7887. fwrite(g->bytecode, 1, g->bytecode_end - g->bytecode, f);
  7888. fclose(f);
  7889. }
  7890. #endif
  7891. sethandlers(g, allowjit);
  7892. return g;
  7893. }
  7894. /* upb_pbcodecache ************************************************************/
  7895. void upb_pbcodecache_init(upb_pbcodecache *c) {
  7896. upb_inttable_init(&c->groups, UPB_CTYPE_CONSTPTR);
  7897. c->allow_jit_ = true;
  7898. }
  7899. void upb_pbcodecache_uninit(upb_pbcodecache *c) {
  7900. upb_inttable_iter i;
  7901. upb_inttable_begin(&i, &c->groups);
  7902. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  7903. const mgroup *group = upb_value_getconstptr(upb_inttable_iter_value(&i));
  7904. mgroup_unref(group, c);
  7905. }
  7906. upb_inttable_uninit(&c->groups);
  7907. }
  7908. bool upb_pbcodecache_allowjit(const upb_pbcodecache *c) {
  7909. return c->allow_jit_;
  7910. }
  7911. bool upb_pbcodecache_setallowjit(upb_pbcodecache *c, bool allow) {
  7912. if (upb_inttable_count(&c->groups) > 0)
  7913. return false;
  7914. c->allow_jit_ = allow;
  7915. return true;
  7916. }
  7917. const upb_pbdecodermethod *upb_pbcodecache_getdecodermethod(
  7918. upb_pbcodecache *c, const upb_pbdecodermethodopts *opts) {
  7919. upb_value v;
  7920. bool ok;
  7921. /* Right now we build a new DecoderMethod every time.
  7922. * TODO(haberman): properly cache methods by their true key. */
  7923. const mgroup *g = mgroup_new(opts->handlers, c->allow_jit_, opts->lazy, c);
  7924. upb_inttable_push(&c->groups, upb_value_constptr(g));
  7925. ok = upb_inttable_lookupptr(&g->methods, opts->handlers, &v);
  7926. UPB_ASSERT(ok);
  7927. return upb_value_getptr(v);
  7928. }
  7929. /* upb_pbdecodermethodopts ****************************************************/
  7930. void upb_pbdecodermethodopts_init(upb_pbdecodermethodopts *opts,
  7931. const upb_handlers *h) {
  7932. opts->handlers = h;
  7933. opts->lazy = false;
  7934. }
  7935. void upb_pbdecodermethodopts_setlazy(upb_pbdecodermethodopts *opts, bool lazy) {
  7936. opts->lazy = lazy;
  7937. }
  7938. /*
  7939. ** upb::Decoder (Bytecode Decoder VM)
  7940. **
  7941. ** Bytecode must previously have been generated using the bytecode compiler in
  7942. ** compile_decoder.c. This decoder then walks through the bytecode op-by-op to
  7943. ** parse the input.
  7944. **
  7945. ** Decoding is fully resumable; we just keep a pointer to the current bytecode
  7946. ** instruction and resume from there. A fair amount of the logic here is to
  7947. ** handle the fact that values can span buffer seams and we have to be able to
  7948. ** be capable of suspending/resuming from any byte in the stream. This
  7949. ** sometimes requires keeping a few trailing bytes from the last buffer around
  7950. ** in the "residual" buffer.
  7951. */
  7952. #include <inttypes.h>
  7953. #include <stddef.h>
  7954. #ifdef UPB_DUMP_BYTECODE
  7955. #include <stdio.h>
  7956. #endif
  7957. #define CHECK_SUSPEND(x) if (!(x)) return upb_pbdecoder_suspend(d);
  7958. /* Error messages that are shared between the bytecode and JIT decoders. */
  7959. const char *kPbDecoderStackOverflow = "Nesting too deep.";
  7960. const char *kPbDecoderSubmessageTooLong =
  7961. "Submessage end extends past enclosing submessage.";
  7962. /* Error messages shared within this file. */
  7963. static const char *kUnterminatedVarint = "Unterminated varint.";
  7964. /* upb_pbdecoder **************************************************************/
  7965. static opcode halt = OP_HALT;
  7966. /* A dummy character we can point to when the user passes us a NULL buffer.
  7967. * We need this because in C (NULL + 0) and (NULL - NULL) are undefined
  7968. * behavior, which would invalidate functions like curbufleft(). */
  7969. static const char dummy_char;
  7970. /* Whether an op consumes any of the input buffer. */
  7971. static bool consumes_input(opcode op) {
  7972. switch (op) {
  7973. case OP_SETDISPATCH:
  7974. case OP_STARTMSG:
  7975. case OP_ENDMSG:
  7976. case OP_STARTSEQ:
  7977. case OP_ENDSEQ:
  7978. case OP_STARTSUBMSG:
  7979. case OP_ENDSUBMSG:
  7980. case OP_STARTSTR:
  7981. case OP_ENDSTR:
  7982. case OP_PUSHTAGDELIM:
  7983. case OP_POP:
  7984. case OP_SETDELIM:
  7985. case OP_SETBIGGROUPNUM:
  7986. case OP_CHECKDELIM:
  7987. case OP_CALL:
  7988. case OP_RET:
  7989. case OP_BRANCH:
  7990. return false;
  7991. default:
  7992. return true;
  7993. }
  7994. }
  7995. static size_t stacksize(upb_pbdecoder *d, size_t entries) {
  7996. UPB_UNUSED(d);
  7997. return entries * sizeof(upb_pbdecoder_frame);
  7998. }
  7999. static size_t callstacksize(upb_pbdecoder *d, size_t entries) {
  8000. UPB_UNUSED(d);
  8001. #ifdef UPB_USE_JIT_X64
  8002. if (d->method_->is_native_) {
  8003. /* Each native stack frame needs two pointers, plus we need a few frames for
  8004. * the enter/exit trampolines. */
  8005. size_t ret = entries * sizeof(void*) * 2;
  8006. ret += sizeof(void*) * 10;
  8007. return ret;
  8008. }
  8009. #endif
  8010. return entries * sizeof(uint32_t*);
  8011. }
  8012. static bool in_residual_buf(const upb_pbdecoder *d, const char *p);
  8013. /* It's unfortunate that we have to micro-manage the compiler with
  8014. * UPB_FORCEINLINE and UPB_NOINLINE, especially since this tuning is necessarily
  8015. * specific to one hardware configuration. But empirically on a Core i7,
  8016. * performance increases 30-50% with these annotations. Every instance where
  8017. * these appear, gcc 4.2.1 made the wrong decision and degraded performance in
  8018. * benchmarks. */
  8019. static void seterr(upb_pbdecoder *d, const char *msg) {
  8020. upb_status status = UPB_STATUS_INIT;
  8021. upb_status_seterrmsg(&status, msg);
  8022. upb_env_reporterror(d->env, &status);
  8023. }
  8024. void upb_pbdecoder_seterr(upb_pbdecoder *d, const char *msg) {
  8025. seterr(d, msg);
  8026. }
  8027. /* Buffering ******************************************************************/
  8028. /* We operate on one buffer at a time, which is either the user's buffer passed
  8029. * to our "decode" callback or some residual bytes from the previous buffer. */
  8030. /* How many bytes can be safely read from d->ptr without reading past end-of-buf
  8031. * or past the current delimited end. */
  8032. static size_t curbufleft(const upb_pbdecoder *d) {
  8033. UPB_ASSERT(d->data_end >= d->ptr);
  8034. return d->data_end - d->ptr;
  8035. }
  8036. /* How many bytes are available before end-of-buffer. */
  8037. static size_t bufleft(const upb_pbdecoder *d) {
  8038. return d->end - d->ptr;
  8039. }
  8040. /* Overall stream offset of d->ptr. */
  8041. uint64_t offset(const upb_pbdecoder *d) {
  8042. return d->bufstart_ofs + (d->ptr - d->buf);
  8043. }
  8044. /* How many bytes are available before the end of this delimited region. */
  8045. size_t delim_remaining(const upb_pbdecoder *d) {
  8046. return d->top->end_ofs - offset(d);
  8047. }
  8048. /* Advances d->ptr. */
  8049. static void advance(upb_pbdecoder *d, size_t len) {
  8050. UPB_ASSERT(curbufleft(d) >= len);
  8051. d->ptr += len;
  8052. }
  8053. static bool in_buf(const char *p, const char *buf, const char *end) {
  8054. return p >= buf && p <= end;
  8055. }
  8056. static bool in_residual_buf(const upb_pbdecoder *d, const char *p) {
  8057. return in_buf(p, d->residual, d->residual_end);
  8058. }
  8059. /* Calculates the delim_end value, which is affected by both the current buffer
  8060. * and the parsing stack, so must be called whenever either is updated. */
  8061. static void set_delim_end(upb_pbdecoder *d) {
  8062. size_t delim_ofs = d->top->end_ofs - d->bufstart_ofs;
  8063. if (delim_ofs <= (size_t)(d->end - d->buf)) {
  8064. d->delim_end = d->buf + delim_ofs;
  8065. d->data_end = d->delim_end;
  8066. } else {
  8067. d->data_end = d->end;
  8068. d->delim_end = NULL;
  8069. }
  8070. }
  8071. static void switchtobuf(upb_pbdecoder *d, const char *buf, const char *end) {
  8072. d->ptr = buf;
  8073. d->buf = buf;
  8074. d->end = end;
  8075. set_delim_end(d);
  8076. }
  8077. static void advancetobuf(upb_pbdecoder *d, const char *buf, size_t len) {
  8078. UPB_ASSERT(curbufleft(d) == 0);
  8079. d->bufstart_ofs += (d->end - d->buf);
  8080. switchtobuf(d, buf, buf + len);
  8081. }
  8082. static void checkpoint(upb_pbdecoder *d) {
  8083. /* The assertion here is in the interests of efficiency, not correctness.
  8084. * We are trying to ensure that we don't checkpoint() more often than
  8085. * necessary. */
  8086. UPB_ASSERT(d->checkpoint != d->ptr);
  8087. d->checkpoint = d->ptr;
  8088. }
  8089. /* Skips "bytes" bytes in the stream, which may be more than available. If we
  8090. * skip more bytes than are available, we return a long read count to the caller
  8091. * indicating how many bytes can be skipped over before passing actual data
  8092. * again. Skipped bytes can pass a NULL buffer and the decoder guarantees they
  8093. * won't actually be read.
  8094. */
  8095. static int32_t skip(upb_pbdecoder *d, size_t bytes) {
  8096. UPB_ASSERT(!in_residual_buf(d, d->ptr) || d->size_param == 0);
  8097. UPB_ASSERT(d->skip == 0);
  8098. if (bytes > delim_remaining(d)) {
  8099. seterr(d, "Skipped value extended beyond enclosing submessage.");
  8100. return upb_pbdecoder_suspend(d);
  8101. } else if (bufleft(d) >= bytes) {
  8102. /* Skipped data is all in current buffer, and more is still available. */
  8103. advance(d, bytes);
  8104. d->skip = 0;
  8105. return DECODE_OK;
  8106. } else {
  8107. /* Skipped data extends beyond currently available buffers. */
  8108. d->pc = d->last;
  8109. d->skip = bytes - curbufleft(d);
  8110. d->bufstart_ofs += (d->end - d->buf);
  8111. d->residual_end = d->residual;
  8112. switchtobuf(d, d->residual, d->residual_end);
  8113. return d->size_param + d->skip;
  8114. }
  8115. }
  8116. /* Resumes the decoder from an initial state or from a previous suspend. */
  8117. int32_t upb_pbdecoder_resume(upb_pbdecoder *d, void *p, const char *buf,
  8118. size_t size, const upb_bufhandle *handle) {
  8119. UPB_UNUSED(p); /* Useless; just for the benefit of the JIT. */
  8120. /* d->skip and d->residual_end could probably elegantly be represented
  8121. * as a single variable, to more easily represent this invariant. */
  8122. UPB_ASSERT(!(d->skip && d->residual_end > d->residual));
  8123. /* We need to remember the original size_param, so that the value we return
  8124. * is relative to it, even if we do some skipping first. */
  8125. d->size_param = size;
  8126. d->handle = handle;
  8127. /* Have to handle this case specially (ie. not with skip()) because the user
  8128. * is allowed to pass a NULL buffer here, which won't allow us to safely
  8129. * calculate a d->end or use our normal functions like curbufleft(). */
  8130. if (d->skip && d->skip >= size) {
  8131. d->skip -= size;
  8132. d->bufstart_ofs += size;
  8133. buf = &dummy_char;
  8134. size = 0;
  8135. /* We can't just return now, because we might need to execute some ops
  8136. * like CHECKDELIM, which could call some callbacks and pop the stack. */
  8137. }
  8138. /* We need to pretend that this was the actual buffer param, since some of the
  8139. * calculations assume that d->ptr/d->buf is relative to this. */
  8140. d->buf_param = buf;
  8141. if (!buf) {
  8142. /* NULL buf is ok if its entire span is covered by the "skip" above, but
  8143. * by this point we know that "skip" doesn't cover the buffer. */
  8144. seterr(d, "Passed NULL buffer over non-skippable region.");
  8145. return upb_pbdecoder_suspend(d);
  8146. }
  8147. if (d->residual_end > d->residual) {
  8148. /* We have residual bytes from the last buffer. */
  8149. UPB_ASSERT(d->ptr == d->residual);
  8150. } else {
  8151. switchtobuf(d, buf, buf + size);
  8152. }
  8153. d->checkpoint = d->ptr;
  8154. /* Handle skips that don't cover the whole buffer (as above). */
  8155. if (d->skip) {
  8156. size_t skip_bytes = d->skip;
  8157. d->skip = 0;
  8158. CHECK_RETURN(skip(d, skip_bytes));
  8159. checkpoint(d);
  8160. }
  8161. /* If we're inside an unknown group, continue to parse unknown values. */
  8162. if (d->top->groupnum < 0) {
  8163. CHECK_RETURN(upb_pbdecoder_skipunknown(d, -1, 0));
  8164. checkpoint(d);
  8165. }
  8166. return DECODE_OK;
  8167. }
  8168. /* Suspends the decoder at the last checkpoint, without saving any residual
  8169. * bytes. If there are any unconsumed bytes, returns a short byte count. */
  8170. size_t upb_pbdecoder_suspend(upb_pbdecoder *d) {
  8171. d->pc = d->last;
  8172. if (d->checkpoint == d->residual) {
  8173. /* Checkpoint was in residual buf; no user bytes were consumed. */
  8174. d->ptr = d->residual;
  8175. return 0;
  8176. } else {
  8177. size_t ret = d->size_param - (d->end - d->checkpoint);
  8178. UPB_ASSERT(!in_residual_buf(d, d->checkpoint));
  8179. UPB_ASSERT(d->buf == d->buf_param || d->buf == &dummy_char);
  8180. d->bufstart_ofs += (d->checkpoint - d->buf);
  8181. d->residual_end = d->residual;
  8182. switchtobuf(d, d->residual, d->residual_end);
  8183. return ret;
  8184. }
  8185. }
  8186. /* Suspends the decoder at the last checkpoint, and saves any unconsumed
  8187. * bytes in our residual buffer. This is necessary if we need more user
  8188. * bytes to form a complete value, which might not be contiguous in the
  8189. * user's buffers. Always consumes all user bytes. */
  8190. static size_t suspend_save(upb_pbdecoder *d) {
  8191. /* We hit end-of-buffer before we could parse a full value.
  8192. * Save any unconsumed bytes (if any) to the residual buffer. */
  8193. d->pc = d->last;
  8194. if (d->checkpoint == d->residual) {
  8195. /* Checkpoint was in residual buf; append user byte(s) to residual buf. */
  8196. UPB_ASSERT((d->residual_end - d->residual) + d->size_param <=
  8197. sizeof(d->residual));
  8198. if (!in_residual_buf(d, d->ptr)) {
  8199. d->bufstart_ofs -= (d->residual_end - d->residual);
  8200. }
  8201. memcpy(d->residual_end, d->buf_param, d->size_param);
  8202. d->residual_end += d->size_param;
  8203. } else {
  8204. /* Checkpoint was in user buf; old residual bytes not needed. */
  8205. size_t save;
  8206. UPB_ASSERT(!in_residual_buf(d, d->checkpoint));
  8207. d->ptr = d->checkpoint;
  8208. save = curbufleft(d);
  8209. UPB_ASSERT(save <= sizeof(d->residual));
  8210. memcpy(d->residual, d->ptr, save);
  8211. d->residual_end = d->residual + save;
  8212. d->bufstart_ofs = offset(d);
  8213. }
  8214. switchtobuf(d, d->residual, d->residual_end);
  8215. return d->size_param;
  8216. }
  8217. /* Copies the next "bytes" bytes into "buf" and advances the stream.
  8218. * Requires that this many bytes are available in the current buffer. */
  8219. UPB_FORCEINLINE static void consumebytes(upb_pbdecoder *d, void *buf,
  8220. size_t bytes) {
  8221. UPB_ASSERT(bytes <= curbufleft(d));
  8222. memcpy(buf, d->ptr, bytes);
  8223. advance(d, bytes);
  8224. }
  8225. /* Slow path for getting the next "bytes" bytes, regardless of whether they are
  8226. * available in the current buffer or not. Returns a status code as described
  8227. * in decoder.int.h. */
  8228. UPB_NOINLINE static int32_t getbytes_slow(upb_pbdecoder *d, void *buf,
  8229. size_t bytes) {
  8230. const size_t avail = curbufleft(d);
  8231. consumebytes(d, buf, avail);
  8232. bytes -= avail;
  8233. UPB_ASSERT(bytes > 0);
  8234. if (in_residual_buf(d, d->ptr)) {
  8235. advancetobuf(d, d->buf_param, d->size_param);
  8236. }
  8237. if (curbufleft(d) >= bytes) {
  8238. consumebytes(d, (char *)buf + avail, bytes);
  8239. return DECODE_OK;
  8240. } else if (d->data_end == d->delim_end) {
  8241. seterr(d, "Submessage ended in the middle of a value or group");
  8242. return upb_pbdecoder_suspend(d);
  8243. } else {
  8244. return suspend_save(d);
  8245. }
  8246. }
  8247. /* Gets the next "bytes" bytes, regardless of whether they are available in the
  8248. * current buffer or not. Returns a status code as described in decoder.int.h.
  8249. */
  8250. UPB_FORCEINLINE static int32_t getbytes(upb_pbdecoder *d, void *buf,
  8251. size_t bytes) {
  8252. if (curbufleft(d) >= bytes) {
  8253. /* Buffer has enough data to satisfy. */
  8254. consumebytes(d, buf, bytes);
  8255. return DECODE_OK;
  8256. } else {
  8257. return getbytes_slow(d, buf, bytes);
  8258. }
  8259. }
  8260. UPB_NOINLINE static size_t peekbytes_slow(upb_pbdecoder *d, void *buf,
  8261. size_t bytes) {
  8262. size_t ret = curbufleft(d);
  8263. memcpy(buf, d->ptr, ret);
  8264. if (in_residual_buf(d, d->ptr)) {
  8265. size_t copy = UPB_MIN(bytes - ret, d->size_param);
  8266. memcpy((char *)buf + ret, d->buf_param, copy);
  8267. ret += copy;
  8268. }
  8269. return ret;
  8270. }
  8271. UPB_FORCEINLINE static size_t peekbytes(upb_pbdecoder *d, void *buf,
  8272. size_t bytes) {
  8273. if (curbufleft(d) >= bytes) {
  8274. memcpy(buf, d->ptr, bytes);
  8275. return bytes;
  8276. } else {
  8277. return peekbytes_slow(d, buf, bytes);
  8278. }
  8279. }
  8280. /* Decoding of wire types *****************************************************/
  8281. /* Slow path for decoding a varint from the current buffer position.
  8282. * Returns a status code as described in decoder.int.h. */
  8283. UPB_NOINLINE int32_t upb_pbdecoder_decode_varint_slow(upb_pbdecoder *d,
  8284. uint64_t *u64) {
  8285. uint8_t byte = 0x80;
  8286. int bitpos;
  8287. *u64 = 0;
  8288. for(bitpos = 0; bitpos < 70 && (byte & 0x80); bitpos += 7) {
  8289. CHECK_RETURN(getbytes(d, &byte, 1));
  8290. *u64 |= (uint64_t)(byte & 0x7F) << bitpos;
  8291. }
  8292. if(bitpos == 70 && (byte & 0x80)) {
  8293. seterr(d, kUnterminatedVarint);
  8294. return upb_pbdecoder_suspend(d);
  8295. }
  8296. return DECODE_OK;
  8297. }
  8298. /* Decodes a varint from the current buffer position.
  8299. * Returns a status code as described in decoder.int.h. */
  8300. UPB_FORCEINLINE static int32_t decode_varint(upb_pbdecoder *d, uint64_t *u64) {
  8301. if (curbufleft(d) > 0 && !(*d->ptr & 0x80)) {
  8302. *u64 = *d->ptr;
  8303. advance(d, 1);
  8304. return DECODE_OK;
  8305. } else if (curbufleft(d) >= 10) {
  8306. /* Fast case. */
  8307. upb_decoderet r = upb_vdecode_fast(d->ptr);
  8308. if (r.p == NULL) {
  8309. seterr(d, kUnterminatedVarint);
  8310. return upb_pbdecoder_suspend(d);
  8311. }
  8312. advance(d, r.p - d->ptr);
  8313. *u64 = r.val;
  8314. return DECODE_OK;
  8315. } else {
  8316. /* Slow case -- varint spans buffer seam. */
  8317. return upb_pbdecoder_decode_varint_slow(d, u64);
  8318. }
  8319. }
  8320. /* Decodes a 32-bit varint from the current buffer position.
  8321. * Returns a status code as described in decoder.int.h. */
  8322. UPB_FORCEINLINE static int32_t decode_v32(upb_pbdecoder *d, uint32_t *u32) {
  8323. uint64_t u64;
  8324. int32_t ret = decode_varint(d, &u64);
  8325. if (ret >= 0) return ret;
  8326. if (u64 > UINT32_MAX) {
  8327. seterr(d, "Unterminated 32-bit varint");
  8328. /* TODO(haberman) guarantee that this function return is >= 0 somehow,
  8329. * so we know this path will always be treated as error by our caller.
  8330. * Right now the size_t -> int32_t can overflow and produce negative values.
  8331. */
  8332. *u32 = 0;
  8333. return upb_pbdecoder_suspend(d);
  8334. }
  8335. *u32 = u64;
  8336. return DECODE_OK;
  8337. }
  8338. /* Decodes a fixed32 from the current buffer position.
  8339. * Returns a status code as described in decoder.int.h.
  8340. * TODO: proper byte swapping for big-endian machines. */
  8341. UPB_FORCEINLINE static int32_t decode_fixed32(upb_pbdecoder *d, uint32_t *u32) {
  8342. return getbytes(d, u32, 4);
  8343. }
  8344. /* Decodes a fixed64 from the current buffer position.
  8345. * Returns a status code as described in decoder.int.h.
  8346. * TODO: proper byte swapping for big-endian machines. */
  8347. UPB_FORCEINLINE static int32_t decode_fixed64(upb_pbdecoder *d, uint64_t *u64) {
  8348. return getbytes(d, u64, 8);
  8349. }
  8350. /* Non-static versions of the above functions.
  8351. * These are called by the JIT for fallback paths. */
  8352. int32_t upb_pbdecoder_decode_f32(upb_pbdecoder *d, uint32_t *u32) {
  8353. return decode_fixed32(d, u32);
  8354. }
  8355. int32_t upb_pbdecoder_decode_f64(upb_pbdecoder *d, uint64_t *u64) {
  8356. return decode_fixed64(d, u64);
  8357. }
  8358. static double as_double(uint64_t n) { double d; memcpy(&d, &n, 8); return d; }
  8359. static float as_float(uint32_t n) { float f; memcpy(&f, &n, 4); return f; }
  8360. /* Pushes a frame onto the decoder stack. */
  8361. static bool decoder_push(upb_pbdecoder *d, uint64_t end) {
  8362. upb_pbdecoder_frame *fr = d->top;
  8363. if (end > fr->end_ofs) {
  8364. seterr(d, kPbDecoderSubmessageTooLong);
  8365. return false;
  8366. } else if (fr == d->limit) {
  8367. seterr(d, kPbDecoderStackOverflow);
  8368. return false;
  8369. }
  8370. fr++;
  8371. fr->end_ofs = end;
  8372. fr->dispatch = NULL;
  8373. fr->groupnum = 0;
  8374. d->top = fr;
  8375. return true;
  8376. }
  8377. static bool pushtagdelim(upb_pbdecoder *d, uint32_t arg) {
  8378. /* While we expect to see an "end" tag (either ENDGROUP or a non-sequence
  8379. * field number) prior to hitting any enclosing submessage end, pushing our
  8380. * existing delim end prevents us from continuing to parse values from a
  8381. * corrupt proto that doesn't give us an END tag in time. */
  8382. if (!decoder_push(d, d->top->end_ofs))
  8383. return false;
  8384. d->top->groupnum = arg;
  8385. return true;
  8386. }
  8387. /* Pops a frame from the decoder stack. */
  8388. static void decoder_pop(upb_pbdecoder *d) { d->top--; }
  8389. UPB_NOINLINE int32_t upb_pbdecoder_checktag_slow(upb_pbdecoder *d,
  8390. uint64_t expected) {
  8391. uint64_t data = 0;
  8392. size_t bytes = upb_value_size(expected);
  8393. size_t read = peekbytes(d, &data, bytes);
  8394. if (read == bytes && data == expected) {
  8395. /* Advance past matched bytes. */
  8396. int32_t ok = getbytes(d, &data, read);
  8397. UPB_ASSERT(ok < 0);
  8398. return DECODE_OK;
  8399. } else if (read < bytes && memcmp(&data, &expected, read) == 0) {
  8400. return suspend_save(d);
  8401. } else {
  8402. return DECODE_MISMATCH;
  8403. }
  8404. }
  8405. int32_t upb_pbdecoder_skipunknown(upb_pbdecoder *d, int32_t fieldnum,
  8406. uint8_t wire_type) {
  8407. if (fieldnum >= 0)
  8408. goto have_tag;
  8409. while (true) {
  8410. uint32_t tag;
  8411. CHECK_RETURN(decode_v32(d, &tag));
  8412. wire_type = tag & 0x7;
  8413. fieldnum = tag >> 3;
  8414. have_tag:
  8415. if (fieldnum == 0) {
  8416. seterr(d, "Saw invalid field number (0)");
  8417. return upb_pbdecoder_suspend(d);
  8418. }
  8419. /* TODO: deliver to unknown field callback. */
  8420. switch (wire_type) {
  8421. case UPB_WIRE_TYPE_32BIT:
  8422. CHECK_RETURN(skip(d, 4));
  8423. break;
  8424. case UPB_WIRE_TYPE_64BIT:
  8425. CHECK_RETURN(skip(d, 8));
  8426. break;
  8427. case UPB_WIRE_TYPE_VARINT: {
  8428. uint64_t u64;
  8429. CHECK_RETURN(decode_varint(d, &u64));
  8430. break;
  8431. }
  8432. case UPB_WIRE_TYPE_DELIMITED: {
  8433. uint32_t len;
  8434. CHECK_RETURN(decode_v32(d, &len));
  8435. CHECK_RETURN(skip(d, len));
  8436. break;
  8437. }
  8438. case UPB_WIRE_TYPE_START_GROUP:
  8439. CHECK_SUSPEND(pushtagdelim(d, -fieldnum));
  8440. break;
  8441. case UPB_WIRE_TYPE_END_GROUP:
  8442. if (fieldnum == -d->top->groupnum) {
  8443. decoder_pop(d);
  8444. } else if (fieldnum == d->top->groupnum) {
  8445. return DECODE_ENDGROUP;
  8446. } else {
  8447. seterr(d, "Unmatched ENDGROUP tag.");
  8448. return upb_pbdecoder_suspend(d);
  8449. }
  8450. break;
  8451. default:
  8452. seterr(d, "Invalid wire type");
  8453. return upb_pbdecoder_suspend(d);
  8454. }
  8455. if (d->top->groupnum >= 0) {
  8456. return DECODE_OK;
  8457. }
  8458. /* Unknown group -- continue looping over unknown fields. */
  8459. checkpoint(d);
  8460. }
  8461. }
  8462. static void goto_endmsg(upb_pbdecoder *d) {
  8463. upb_value v;
  8464. bool found = upb_inttable_lookup32(d->top->dispatch, DISPATCH_ENDMSG, &v);
  8465. UPB_ASSERT(found);
  8466. d->pc = d->top->base + upb_value_getuint64(v);
  8467. }
  8468. /* Parses a tag and jumps to the corresponding bytecode instruction for this
  8469. * field.
  8470. *
  8471. * If the tag is unknown (or the wire type doesn't match), parses the field as
  8472. * unknown. If the tag is a valid ENDGROUP tag, jumps to the bytecode
  8473. * instruction for the end of message. */
  8474. static int32_t dispatch(upb_pbdecoder *d) {
  8475. upb_inttable *dispatch = d->top->dispatch;
  8476. uint32_t tag;
  8477. uint8_t wire_type;
  8478. uint32_t fieldnum;
  8479. upb_value val;
  8480. int32_t retval;
  8481. /* Decode tag. */
  8482. CHECK_RETURN(decode_v32(d, &tag));
  8483. wire_type = tag & 0x7;
  8484. fieldnum = tag >> 3;
  8485. /* Lookup tag. Because of packed/non-packed compatibility, we have to
  8486. * check the wire type against two possibilities. */
  8487. if (fieldnum != DISPATCH_ENDMSG &&
  8488. upb_inttable_lookup32(dispatch, fieldnum, &val)) {
  8489. uint64_t v = upb_value_getuint64(val);
  8490. if (wire_type == (v & 0xff)) {
  8491. d->pc = d->top->base + (v >> 16);
  8492. return DECODE_OK;
  8493. } else if (wire_type == ((v >> 8) & 0xff)) {
  8494. bool found =
  8495. upb_inttable_lookup(dispatch, fieldnum + UPB_MAX_FIELDNUMBER, &val);
  8496. UPB_ASSERT(found);
  8497. d->pc = d->top->base + upb_value_getuint64(val);
  8498. return DECODE_OK;
  8499. }
  8500. }
  8501. /* We have some unknown fields (or ENDGROUP) to parse. The DISPATCH or TAG
  8502. * bytecode that triggered this is preceded by a CHECKDELIM bytecode which
  8503. * we need to back up to, so that when we're done skipping unknown data we
  8504. * can re-check the delimited end. */
  8505. d->last--; /* Necessary if we get suspended */
  8506. d->pc = d->last;
  8507. UPB_ASSERT(getop(*d->last) == OP_CHECKDELIM);
  8508. /* Unknown field or ENDGROUP. */
  8509. retval = upb_pbdecoder_skipunknown(d, fieldnum, wire_type);
  8510. CHECK_RETURN(retval);
  8511. if (retval == DECODE_ENDGROUP) {
  8512. goto_endmsg(d);
  8513. return DECODE_OK;
  8514. }
  8515. return DECODE_OK;
  8516. }
  8517. /* Callers know that the stack is more than one deep because the opcodes that
  8518. * call this only occur after PUSH operations. */
  8519. upb_pbdecoder_frame *outer_frame(upb_pbdecoder *d) {
  8520. UPB_ASSERT(d->top != d->stack);
  8521. return d->top - 1;
  8522. }
  8523. /* The main decoding loop *****************************************************/
  8524. /* The main decoder VM function. Uses traditional bytecode dispatch loop with a
  8525. * switch() statement. */
  8526. size_t run_decoder_vm(upb_pbdecoder *d, const mgroup *group,
  8527. const upb_bufhandle* handle) {
  8528. #define VMCASE(op, code) \
  8529. case op: { code; if (consumes_input(op)) checkpoint(d); break; }
  8530. #define PRIMITIVE_OP(type, wt, name, convfunc, ctype) \
  8531. VMCASE(OP_PARSE_ ## type, { \
  8532. ctype val; \
  8533. CHECK_RETURN(decode_ ## wt(d, &val)); \
  8534. upb_sink_put ## name(&d->top->sink, arg, (convfunc)(val)); \
  8535. })
  8536. while(1) {
  8537. int32_t instruction;
  8538. opcode op;
  8539. uint32_t arg;
  8540. int32_t longofs;
  8541. d->last = d->pc;
  8542. instruction = *d->pc++;
  8543. op = getop(instruction);
  8544. arg = instruction >> 8;
  8545. longofs = arg;
  8546. UPB_ASSERT(d->ptr != d->residual_end);
  8547. UPB_UNUSED(group);
  8548. #ifdef UPB_DUMP_BYTECODE
  8549. fprintf(stderr, "s_ofs=%d buf_ofs=%d data_rem=%d buf_rem=%d delim_rem=%d "
  8550. "%x %s (%d)\n",
  8551. (int)offset(d),
  8552. (int)(d->ptr - d->buf),
  8553. (int)(d->data_end - d->ptr),
  8554. (int)(d->end - d->ptr),
  8555. (int)((d->top->end_ofs - d->bufstart_ofs) - (d->ptr - d->buf)),
  8556. (int)(d->pc - 1 - group->bytecode),
  8557. upb_pbdecoder_getopname(op),
  8558. arg);
  8559. #endif
  8560. switch (op) {
  8561. /* Technically, we are losing data if we see a 32-bit varint that is not
  8562. * properly sign-extended. We could detect this and error about the data
  8563. * loss, but proto2 does not do this, so we pass. */
  8564. PRIMITIVE_OP(INT32, varint, int32, int32_t, uint64_t)
  8565. PRIMITIVE_OP(INT64, varint, int64, int64_t, uint64_t)
  8566. PRIMITIVE_OP(UINT32, varint, uint32, uint32_t, uint64_t)
  8567. PRIMITIVE_OP(UINT64, varint, uint64, uint64_t, uint64_t)
  8568. PRIMITIVE_OP(FIXED32, fixed32, uint32, uint32_t, uint32_t)
  8569. PRIMITIVE_OP(FIXED64, fixed64, uint64, uint64_t, uint64_t)
  8570. PRIMITIVE_OP(SFIXED32, fixed32, int32, int32_t, uint32_t)
  8571. PRIMITIVE_OP(SFIXED64, fixed64, int64, int64_t, uint64_t)
  8572. PRIMITIVE_OP(BOOL, varint, bool, bool, uint64_t)
  8573. PRIMITIVE_OP(DOUBLE, fixed64, double, as_double, uint64_t)
  8574. PRIMITIVE_OP(FLOAT, fixed32, float, as_float, uint32_t)
  8575. PRIMITIVE_OP(SINT32, varint, int32, upb_zzdec_32, uint64_t)
  8576. PRIMITIVE_OP(SINT64, varint, int64, upb_zzdec_64, uint64_t)
  8577. VMCASE(OP_SETDISPATCH,
  8578. d->top->base = d->pc - 1;
  8579. memcpy(&d->top->dispatch, d->pc, sizeof(void*));
  8580. d->pc += sizeof(void*) / sizeof(uint32_t);
  8581. )
  8582. VMCASE(OP_STARTMSG,
  8583. CHECK_SUSPEND(upb_sink_startmsg(&d->top->sink));
  8584. )
  8585. VMCASE(OP_ENDMSG,
  8586. CHECK_SUSPEND(upb_sink_endmsg(&d->top->sink, d->status));
  8587. )
  8588. VMCASE(OP_STARTSEQ,
  8589. upb_pbdecoder_frame *outer = outer_frame(d);
  8590. CHECK_SUSPEND(upb_sink_startseq(&outer->sink, arg, &d->top->sink));
  8591. )
  8592. VMCASE(OP_ENDSEQ,
  8593. CHECK_SUSPEND(upb_sink_endseq(&d->top->sink, arg));
  8594. )
  8595. VMCASE(OP_STARTSUBMSG,
  8596. upb_pbdecoder_frame *outer = outer_frame(d);
  8597. CHECK_SUSPEND(upb_sink_startsubmsg(&outer->sink, arg, &d->top->sink));
  8598. )
  8599. VMCASE(OP_ENDSUBMSG,
  8600. CHECK_SUSPEND(upb_sink_endsubmsg(&d->top->sink, arg));
  8601. )
  8602. VMCASE(OP_STARTSTR,
  8603. uint32_t len = delim_remaining(d);
  8604. upb_pbdecoder_frame *outer = outer_frame(d);
  8605. CHECK_SUSPEND(upb_sink_startstr(&outer->sink, arg, len, &d->top->sink));
  8606. if (len == 0) {
  8607. d->pc++; /* Skip OP_STRING. */
  8608. }
  8609. )
  8610. VMCASE(OP_STRING,
  8611. uint32_t len = curbufleft(d);
  8612. size_t n = upb_sink_putstring(&d->top->sink, arg, d->ptr, len, handle);
  8613. if (n > len) {
  8614. if (n > delim_remaining(d)) {
  8615. seterr(d, "Tried to skip past end of string.");
  8616. return upb_pbdecoder_suspend(d);
  8617. } else {
  8618. int32_t ret = skip(d, n);
  8619. /* This shouldn't return DECODE_OK, because n > len. */
  8620. UPB_ASSERT(ret >= 0);
  8621. return ret;
  8622. }
  8623. }
  8624. advance(d, n);
  8625. if (n < len || d->delim_end == NULL) {
  8626. /* We aren't finished with this string yet. */
  8627. d->pc--; /* Repeat OP_STRING. */
  8628. if (n > 0) checkpoint(d);
  8629. return upb_pbdecoder_suspend(d);
  8630. }
  8631. )
  8632. VMCASE(OP_ENDSTR,
  8633. CHECK_SUSPEND(upb_sink_endstr(&d->top->sink, arg));
  8634. )
  8635. VMCASE(OP_PUSHTAGDELIM,
  8636. CHECK_SUSPEND(pushtagdelim(d, arg));
  8637. )
  8638. VMCASE(OP_SETBIGGROUPNUM,
  8639. d->top->groupnum = *d->pc++;
  8640. )
  8641. VMCASE(OP_POP,
  8642. UPB_ASSERT(d->top > d->stack);
  8643. decoder_pop(d);
  8644. )
  8645. VMCASE(OP_PUSHLENDELIM,
  8646. uint32_t len;
  8647. CHECK_RETURN(decode_v32(d, &len));
  8648. CHECK_SUSPEND(decoder_push(d, offset(d) + len));
  8649. set_delim_end(d);
  8650. )
  8651. VMCASE(OP_SETDELIM,
  8652. set_delim_end(d);
  8653. )
  8654. VMCASE(OP_CHECKDELIM,
  8655. /* We are guaranteed of this assert because we never allow ourselves to
  8656. * consume bytes beyond data_end, which covers delim_end when non-NULL.
  8657. */
  8658. UPB_ASSERT(!(d->delim_end && d->ptr > d->delim_end));
  8659. if (d->ptr == d->delim_end)
  8660. d->pc += longofs;
  8661. )
  8662. VMCASE(OP_CALL,
  8663. d->callstack[d->call_len++] = d->pc;
  8664. d->pc += longofs;
  8665. )
  8666. VMCASE(OP_RET,
  8667. UPB_ASSERT(d->call_len > 0);
  8668. d->pc = d->callstack[--d->call_len];
  8669. )
  8670. VMCASE(OP_BRANCH,
  8671. d->pc += longofs;
  8672. )
  8673. VMCASE(OP_TAG1,
  8674. uint8_t expected;
  8675. CHECK_SUSPEND(curbufleft(d) > 0);
  8676. expected = (arg >> 8) & 0xff;
  8677. if (*d->ptr == expected) {
  8678. advance(d, 1);
  8679. } else {
  8680. int8_t shortofs;
  8681. badtag:
  8682. shortofs = arg;
  8683. if (shortofs == LABEL_DISPATCH) {
  8684. CHECK_RETURN(dispatch(d));
  8685. } else {
  8686. d->pc += shortofs;
  8687. break; /* Avoid checkpoint(). */
  8688. }
  8689. }
  8690. )
  8691. VMCASE(OP_TAG2,
  8692. uint16_t expected;
  8693. CHECK_SUSPEND(curbufleft(d) > 0);
  8694. expected = (arg >> 8) & 0xffff;
  8695. if (curbufleft(d) >= 2) {
  8696. uint16_t actual;
  8697. memcpy(&actual, d->ptr, 2);
  8698. if (expected == actual) {
  8699. advance(d, 2);
  8700. } else {
  8701. goto badtag;
  8702. }
  8703. } else {
  8704. int32_t result = upb_pbdecoder_checktag_slow(d, expected);
  8705. if (result == DECODE_MISMATCH) goto badtag;
  8706. if (result >= 0) return result;
  8707. }
  8708. )
  8709. VMCASE(OP_TAGN, {
  8710. uint64_t expected;
  8711. int32_t result;
  8712. memcpy(&expected, d->pc, 8);
  8713. d->pc += 2;
  8714. result = upb_pbdecoder_checktag_slow(d, expected);
  8715. if (result == DECODE_MISMATCH) goto badtag;
  8716. if (result >= 0) return result;
  8717. })
  8718. VMCASE(OP_DISPATCH, {
  8719. CHECK_RETURN(dispatch(d));
  8720. })
  8721. VMCASE(OP_HALT, {
  8722. return d->size_param;
  8723. })
  8724. }
  8725. }
  8726. }
  8727. /* BytesHandler handlers ******************************************************/
  8728. void *upb_pbdecoder_startbc(void *closure, const void *pc, size_t size_hint) {
  8729. upb_pbdecoder *d = closure;
  8730. UPB_UNUSED(size_hint);
  8731. d->top->end_ofs = UINT64_MAX;
  8732. d->bufstart_ofs = 0;
  8733. d->call_len = 1;
  8734. d->callstack[0] = &halt;
  8735. d->pc = pc;
  8736. d->skip = 0;
  8737. return d;
  8738. }
  8739. void *upb_pbdecoder_startjit(void *closure, const void *hd, size_t size_hint) {
  8740. upb_pbdecoder *d = closure;
  8741. UPB_UNUSED(hd);
  8742. UPB_UNUSED(size_hint);
  8743. d->top->end_ofs = UINT64_MAX;
  8744. d->bufstart_ofs = 0;
  8745. d->call_len = 0;
  8746. d->skip = 0;
  8747. return d;
  8748. }
  8749. bool upb_pbdecoder_end(void *closure, const void *handler_data) {
  8750. upb_pbdecoder *d = closure;
  8751. const upb_pbdecodermethod *method = handler_data;
  8752. uint64_t end;
  8753. char dummy;
  8754. if (d->residual_end > d->residual) {
  8755. seterr(d, "Unexpected EOF: decoder still has buffered unparsed data");
  8756. return false;
  8757. }
  8758. if (d->skip) {
  8759. seterr(d, "Unexpected EOF inside skipped data");
  8760. return false;
  8761. }
  8762. if (d->top->end_ofs != UINT64_MAX) {
  8763. seterr(d, "Unexpected EOF inside delimited string");
  8764. return false;
  8765. }
  8766. /* The user's end() call indicates that the message ends here. */
  8767. end = offset(d);
  8768. d->top->end_ofs = end;
  8769. #ifdef UPB_USE_JIT_X64
  8770. if (method->is_native_) {
  8771. const mgroup *group = (const mgroup*)method->group;
  8772. if (d->top != d->stack)
  8773. d->stack->end_ofs = 0;
  8774. group->jit_code(closure, method->code_base.ptr, &dummy, 0, NULL);
  8775. } else
  8776. #endif
  8777. {
  8778. const uint32_t *p = d->pc;
  8779. d->stack->end_ofs = end;
  8780. /* Check the previous bytecode, but guard against beginning. */
  8781. if (p != method->code_base.ptr) p--;
  8782. if (getop(*p) == OP_CHECKDELIM) {
  8783. /* Rewind from OP_TAG* to OP_CHECKDELIM. */
  8784. UPB_ASSERT(getop(*d->pc) == OP_TAG1 ||
  8785. getop(*d->pc) == OP_TAG2 ||
  8786. getop(*d->pc) == OP_TAGN ||
  8787. getop(*d->pc) == OP_DISPATCH);
  8788. d->pc = p;
  8789. }
  8790. upb_pbdecoder_decode(closure, handler_data, &dummy, 0, NULL);
  8791. }
  8792. if (d->call_len != 0) {
  8793. seterr(d, "Unexpected EOF inside submessage or group");
  8794. return false;
  8795. }
  8796. return true;
  8797. }
  8798. size_t upb_pbdecoder_decode(void *decoder, const void *group, const char *buf,
  8799. size_t size, const upb_bufhandle *handle) {
  8800. int32_t result = upb_pbdecoder_resume(decoder, NULL, buf, size, handle);
  8801. if (result == DECODE_ENDGROUP) goto_endmsg(decoder);
  8802. CHECK_RETURN(result);
  8803. return run_decoder_vm(decoder, group, handle);
  8804. }
  8805. /* Public API *****************************************************************/
  8806. void upb_pbdecoder_reset(upb_pbdecoder *d) {
  8807. d->top = d->stack;
  8808. d->top->groupnum = 0;
  8809. d->ptr = d->residual;
  8810. d->buf = d->residual;
  8811. d->end = d->residual;
  8812. d->residual_end = d->residual;
  8813. }
  8814. upb_pbdecoder *upb_pbdecoder_create(upb_env *e, const upb_pbdecodermethod *m,
  8815. upb_sink *sink) {
  8816. const size_t default_max_nesting = 64;
  8817. #ifndef NDEBUG
  8818. size_t size_before = upb_env_bytesallocated(e);
  8819. #endif
  8820. upb_pbdecoder *d = upb_env_malloc(e, sizeof(upb_pbdecoder));
  8821. if (!d) return NULL;
  8822. d->method_ = m;
  8823. d->callstack = upb_env_malloc(e, callstacksize(d, default_max_nesting));
  8824. d->stack = upb_env_malloc(e, stacksize(d, default_max_nesting));
  8825. if (!d->stack || !d->callstack) {
  8826. return NULL;
  8827. }
  8828. d->env = e;
  8829. d->limit = d->stack + default_max_nesting - 1;
  8830. d->stack_size = default_max_nesting;
  8831. d->status = NULL;
  8832. upb_pbdecoder_reset(d);
  8833. upb_bytessink_reset(&d->input_, &m->input_handler_, d);
  8834. UPB_ASSERT(sink);
  8835. if (d->method_->dest_handlers_) {
  8836. if (sink->handlers != d->method_->dest_handlers_)
  8837. return NULL;
  8838. }
  8839. upb_sink_reset(&d->top->sink, sink->handlers, sink->closure);
  8840. /* If this fails, increase the value in decoder.h. */
  8841. UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(e) - size_before <=
  8842. UPB_PB_DECODER_SIZE);
  8843. return d;
  8844. }
  8845. uint64_t upb_pbdecoder_bytesparsed(const upb_pbdecoder *d) {
  8846. return offset(d);
  8847. }
  8848. const upb_pbdecodermethod *upb_pbdecoder_method(const upb_pbdecoder *d) {
  8849. return d->method_;
  8850. }
  8851. upb_bytessink *upb_pbdecoder_input(upb_pbdecoder *d) {
  8852. return &d->input_;
  8853. }
  8854. size_t upb_pbdecoder_maxnesting(const upb_pbdecoder *d) {
  8855. return d->stack_size;
  8856. }
  8857. bool upb_pbdecoder_setmaxnesting(upb_pbdecoder *d, size_t max) {
  8858. UPB_ASSERT(d->top >= d->stack);
  8859. if (max < (size_t)(d->top - d->stack)) {
  8860. /* Can't set a limit smaller than what we are currently at. */
  8861. return false;
  8862. }
  8863. if (max > d->stack_size) {
  8864. /* Need to reallocate stack and callstack to accommodate. */
  8865. size_t old_size = stacksize(d, d->stack_size);
  8866. size_t new_size = stacksize(d, max);
  8867. void *p = upb_env_realloc(d->env, d->stack, old_size, new_size);
  8868. if (!p) {
  8869. return false;
  8870. }
  8871. d->stack = p;
  8872. old_size = callstacksize(d, d->stack_size);
  8873. new_size = callstacksize(d, max);
  8874. p = upb_env_realloc(d->env, d->callstack, old_size, new_size);
  8875. if (!p) {
  8876. return false;
  8877. }
  8878. d->callstack = p;
  8879. d->stack_size = max;
  8880. }
  8881. d->limit = d->stack + max - 1;
  8882. return true;
  8883. }
  8884. /*
  8885. ** upb::Encoder
  8886. **
  8887. ** Since we are implementing pure handlers (ie. without any out-of-band access
  8888. ** to pre-computed lengths), we have to buffer all submessages before we can
  8889. ** emit even their first byte.
  8890. **
  8891. ** Not knowing the size of submessages also means we can't write a perfect
  8892. ** zero-copy implementation, even with buffering. Lengths are stored as
  8893. ** varints, which means that we don't know how many bytes to reserve for the
  8894. ** length until we know what the length is.
  8895. **
  8896. ** This leaves us with three main choices:
  8897. **
  8898. ** 1. buffer all submessage data in a temporary buffer, then copy it exactly
  8899. ** once into the output buffer.
  8900. **
  8901. ** 2. attempt to buffer data directly into the output buffer, estimating how
  8902. ** many bytes each length will take. When our guesses are wrong, use
  8903. ** memmove() to grow or shrink the allotted space.
  8904. **
  8905. ** 3. buffer directly into the output buffer, allocating a max length
  8906. ** ahead-of-time for each submessage length. If we overallocated, we waste
  8907. ** space, but no memcpy() or memmove() is required. This approach requires
  8908. ** defining a maximum size for submessages and rejecting submessages that
  8909. ** exceed that size.
  8910. **
  8911. ** (2) and (3) have the potential to have better performance, but they are more
  8912. ** complicated and subtle to implement:
  8913. **
  8914. ** (3) requires making an arbitrary choice of the maximum message size; it
  8915. ** wastes space when submessages are shorter than this and fails
  8916. ** completely when they are longer. This makes it more finicky and
  8917. ** requires configuration based on the input. It also makes it impossible
  8918. ** to perfectly match the output of reference encoders that always use the
  8919. ** optimal amount of space for each length.
  8920. **
  8921. ** (2) requires guessing the the size upfront, and if multiple lengths are
  8922. ** guessed wrong the minimum required number of memmove() operations may
  8923. ** be complicated to compute correctly. Implemented properly, it may have
  8924. ** a useful amortized or average cost, but more investigation is required
  8925. ** to determine this and what the optimal algorithm is to achieve it.
  8926. **
  8927. ** (1) makes you always pay for exactly one copy, but its implementation is
  8928. ** the simplest and its performance is predictable.
  8929. **
  8930. ** So for now, we implement (1) only. If we wish to optimize later, we should
  8931. ** be able to do it without affecting users.
  8932. **
  8933. ** The strategy is to buffer the segments of data that do *not* depend on
  8934. ** unknown lengths in one buffer, and keep a separate buffer of segment pointers
  8935. ** and lengths. When the top-level submessage ends, we can go beginning to end,
  8936. ** alternating the writing of lengths with memcpy() of the rest of the data.
  8937. ** At the top level though, no buffering is required.
  8938. */
  8939. /* The output buffer is divided into segments; a segment is a string of data
  8940. * that is "ready to go" -- it does not need any varint lengths inserted into
  8941. * the middle. The seams between segments are where varints will be inserted
  8942. * once they are known.
  8943. *
  8944. * We also use the concept of a "run", which is a range of encoded bytes that
  8945. * occur at a single submessage level. Every segment contains one or more runs.
  8946. *
  8947. * A segment can span messages. Consider:
  8948. *
  8949. * .--Submessage lengths---------.
  8950. * | | |
  8951. * | V V
  8952. * V | |--------------- | |-----------------
  8953. * Submessages: | |-----------------------------------------------
  8954. * Top-level msg: ------------------------------------------------------------
  8955. *
  8956. * Segments: ----- ------------------- -----------------
  8957. * Runs: *---- *--------------*--- *----------------
  8958. * (* marks the start)
  8959. *
  8960. * Note that the top-level menssage is not in any segment because it does not
  8961. * have any length preceding it.
  8962. *
  8963. * A segment is only interrupted when another length needs to be inserted. So
  8964. * observe how the second segment spans both the inner submessage and part of
  8965. * the next enclosing message. */
  8966. typedef struct {
  8967. uint32_t msglen; /* The length to varint-encode before this segment. */
  8968. uint32_t seglen; /* Length of the segment. */
  8969. } upb_pb_encoder_segment;
  8970. struct upb_pb_encoder {
  8971. upb_env *env;
  8972. /* Our input and output. */
  8973. upb_sink input_;
  8974. upb_bytessink *output_;
  8975. /* The "subclosure" -- used as the inner closure as part of the bytessink
  8976. * protocol. */
  8977. void *subc;
  8978. /* The output buffer and limit, and our current write position. "buf"
  8979. * initially points to "initbuf", but is dynamically allocated if we need to
  8980. * grow beyond the initial size. */
  8981. char *buf, *ptr, *limit;
  8982. /* The beginning of the current run, or undefined if we are at the top
  8983. * level. */
  8984. char *runbegin;
  8985. /* The list of segments we are accumulating. */
  8986. upb_pb_encoder_segment *segbuf, *segptr, *seglimit;
  8987. /* The stack of enclosing submessages. Each entry in the stack points to the
  8988. * segment where this submessage's length is being accumulated. */
  8989. int *stack, *top, *stacklimit;
  8990. /* Depth of startmsg/endmsg calls. */
  8991. int depth;
  8992. };
  8993. /* low-level buffering ********************************************************/
  8994. /* Low-level functions for interacting with the output buffer. */
  8995. /* TODO(haberman): handle pushback */
  8996. static void putbuf(upb_pb_encoder *e, const char *buf, size_t len) {
  8997. size_t n = upb_bytessink_putbuf(e->output_, e->subc, buf, len, NULL);
  8998. UPB_ASSERT(n == len);
  8999. }
  9000. static upb_pb_encoder_segment *top(upb_pb_encoder *e) {
  9001. return &e->segbuf[*e->top];
  9002. }
  9003. /* Call to ensure that at least "bytes" bytes are available for writing at
  9004. * e->ptr. Returns false if the bytes could not be allocated. */
  9005. static bool reserve(upb_pb_encoder *e, size_t bytes) {
  9006. if ((size_t)(e->limit - e->ptr) < bytes) {
  9007. /* Grow buffer. */
  9008. char *new_buf;
  9009. size_t needed = bytes + (e->ptr - e->buf);
  9010. size_t old_size = e->limit - e->buf;
  9011. size_t new_size = old_size;
  9012. while (new_size < needed) {
  9013. new_size *= 2;
  9014. }
  9015. new_buf = upb_env_realloc(e->env, e->buf, old_size, new_size);
  9016. if (new_buf == NULL) {
  9017. return false;
  9018. }
  9019. e->ptr = new_buf + (e->ptr - e->buf);
  9020. e->runbegin = new_buf + (e->runbegin - e->buf);
  9021. e->limit = new_buf + new_size;
  9022. e->buf = new_buf;
  9023. }
  9024. return true;
  9025. }
  9026. /* Call when "bytes" bytes have been writte at e->ptr. The caller *must* have
  9027. * previously called reserve() with at least this many bytes. */
  9028. static void encoder_advance(upb_pb_encoder *e, size_t bytes) {
  9029. UPB_ASSERT((size_t)(e->limit - e->ptr) >= bytes);
  9030. e->ptr += bytes;
  9031. }
  9032. /* Call when all of the bytes for a handler have been written. Flushes the
  9033. * bytes if possible and necessary, returning false if this failed. */
  9034. static bool commit(upb_pb_encoder *e) {
  9035. if (!e->top) {
  9036. /* We aren't inside a delimited region. Flush our accumulated bytes to
  9037. * the output.
  9038. *
  9039. * TODO(haberman): in the future we may want to delay flushing for
  9040. * efficiency reasons. */
  9041. putbuf(e, e->buf, e->ptr - e->buf);
  9042. e->ptr = e->buf;
  9043. }
  9044. return true;
  9045. }
  9046. /* Writes the given bytes to the buffer, handling reserve/advance. */
  9047. static bool encode_bytes(upb_pb_encoder *e, const void *data, size_t len) {
  9048. if (!reserve(e, len)) {
  9049. return false;
  9050. }
  9051. memcpy(e->ptr, data, len);
  9052. encoder_advance(e, len);
  9053. return true;
  9054. }
  9055. /* Finish the current run by adding the run totals to the segment and message
  9056. * length. */
  9057. static void accumulate(upb_pb_encoder *e) {
  9058. size_t run_len;
  9059. UPB_ASSERT(e->ptr >= e->runbegin);
  9060. run_len = e->ptr - e->runbegin;
  9061. e->segptr->seglen += run_len;
  9062. top(e)->msglen += run_len;
  9063. e->runbegin = e->ptr;
  9064. }
  9065. /* Call to indicate the start of delimited region for which the full length is
  9066. * not yet known. All data will be buffered until the length is known.
  9067. * Delimited regions may be nested; their lengths will all be tracked properly. */
  9068. static bool start_delim(upb_pb_encoder *e) {
  9069. if (e->top) {
  9070. /* We are already buffering, advance to the next segment and push it on the
  9071. * stack. */
  9072. accumulate(e);
  9073. if (++e->top == e->stacklimit) {
  9074. /* TODO(haberman): grow stack? */
  9075. return false;
  9076. }
  9077. if (++e->segptr == e->seglimit) {
  9078. /* Grow segment buffer. */
  9079. size_t old_size =
  9080. (e->seglimit - e->segbuf) * sizeof(upb_pb_encoder_segment);
  9081. size_t new_size = old_size * 2;
  9082. upb_pb_encoder_segment *new_buf =
  9083. upb_env_realloc(e->env, e->segbuf, old_size, new_size);
  9084. if (new_buf == NULL) {
  9085. return false;
  9086. }
  9087. e->segptr = new_buf + (e->segptr - e->segbuf);
  9088. e->seglimit = new_buf + (new_size / sizeof(upb_pb_encoder_segment));
  9089. e->segbuf = new_buf;
  9090. }
  9091. } else {
  9092. /* We were previously at the top level, start buffering. */
  9093. e->segptr = e->segbuf;
  9094. e->top = e->stack;
  9095. e->runbegin = e->ptr;
  9096. }
  9097. *e->top = e->segptr - e->segbuf;
  9098. e->segptr->seglen = 0;
  9099. e->segptr->msglen = 0;
  9100. return true;
  9101. }
  9102. /* Call to indicate the end of a delimited region. We now know the length of
  9103. * the delimited region. If we are not nested inside any other delimited
  9104. * regions, we can now emit all of the buffered data we accumulated. */
  9105. static bool end_delim(upb_pb_encoder *e) {
  9106. size_t msglen;
  9107. accumulate(e);
  9108. msglen = top(e)->msglen;
  9109. if (e->top == e->stack) {
  9110. /* All lengths are now available, emit all buffered data. */
  9111. char buf[UPB_PB_VARINT_MAX_LEN];
  9112. upb_pb_encoder_segment *s;
  9113. const char *ptr = e->buf;
  9114. for (s = e->segbuf; s <= e->segptr; s++) {
  9115. size_t lenbytes = upb_vencode64(s->msglen, buf);
  9116. putbuf(e, buf, lenbytes);
  9117. putbuf(e, ptr, s->seglen);
  9118. ptr += s->seglen;
  9119. }
  9120. e->ptr = e->buf;
  9121. e->top = NULL;
  9122. } else {
  9123. /* Need to keep buffering; propagate length info into enclosing
  9124. * submessages. */
  9125. --e->top;
  9126. top(e)->msglen += msglen + upb_varint_size(msglen);
  9127. }
  9128. return true;
  9129. }
  9130. /* tag_t **********************************************************************/
  9131. /* A precomputed (pre-encoded) tag and length. */
  9132. typedef struct {
  9133. uint8_t bytes;
  9134. char tag[7];
  9135. } tag_t;
  9136. /* Allocates a new tag for this field, and sets it in these handlerattr. */
  9137. static void new_tag(upb_handlers *h, const upb_fielddef *f, upb_wiretype_t wt,
  9138. upb_handlerattr *attr) {
  9139. uint32_t n = upb_fielddef_number(f);
  9140. tag_t *tag = upb_gmalloc(sizeof(tag_t));
  9141. tag->bytes = upb_vencode64((n << 3) | wt, tag->tag);
  9142. upb_handlerattr_init(attr);
  9143. upb_handlerattr_sethandlerdata(attr, tag);
  9144. upb_handlers_addcleanup(h, tag, upb_gfree);
  9145. }
  9146. static bool encode_tag(upb_pb_encoder *e, const tag_t *tag) {
  9147. return encode_bytes(e, tag->tag, tag->bytes);
  9148. }
  9149. /* encoding of wire types *****************************************************/
  9150. static bool encode_fixed64(upb_pb_encoder *e, uint64_t val) {
  9151. /* TODO(haberman): byte-swap for big endian. */
  9152. return encode_bytes(e, &val, sizeof(uint64_t));
  9153. }
  9154. static bool encode_fixed32(upb_pb_encoder *e, uint32_t val) {
  9155. /* TODO(haberman): byte-swap for big endian. */
  9156. return encode_bytes(e, &val, sizeof(uint32_t));
  9157. }
  9158. static bool encode_varint(upb_pb_encoder *e, uint64_t val) {
  9159. if (!reserve(e, UPB_PB_VARINT_MAX_LEN)) {
  9160. return false;
  9161. }
  9162. encoder_advance(e, upb_vencode64(val, e->ptr));
  9163. return true;
  9164. }
  9165. static uint64_t dbl2uint64(double d) {
  9166. uint64_t ret;
  9167. memcpy(&ret, &d, sizeof(uint64_t));
  9168. return ret;
  9169. }
  9170. static uint32_t flt2uint32(float d) {
  9171. uint32_t ret;
  9172. memcpy(&ret, &d, sizeof(uint32_t));
  9173. return ret;
  9174. }
  9175. /* encoding of proto types ****************************************************/
  9176. static bool startmsg(void *c, const void *hd) {
  9177. upb_pb_encoder *e = c;
  9178. UPB_UNUSED(hd);
  9179. if (e->depth++ == 0) {
  9180. upb_bytessink_start(e->output_, 0, &e->subc);
  9181. }
  9182. return true;
  9183. }
  9184. static bool endmsg(void *c, const void *hd, upb_status *status) {
  9185. upb_pb_encoder *e = c;
  9186. UPB_UNUSED(hd);
  9187. UPB_UNUSED(status);
  9188. if (--e->depth == 0) {
  9189. upb_bytessink_end(e->output_);
  9190. }
  9191. return true;
  9192. }
  9193. static void *encode_startdelimfield(void *c, const void *hd) {
  9194. bool ok = encode_tag(c, hd) && commit(c) && start_delim(c);
  9195. return ok ? c : UPB_BREAK;
  9196. }
  9197. static bool encode_enddelimfield(void *c, const void *hd) {
  9198. UPB_UNUSED(hd);
  9199. return end_delim(c);
  9200. }
  9201. static void *encode_startgroup(void *c, const void *hd) {
  9202. return (encode_tag(c, hd) && commit(c)) ? c : UPB_BREAK;
  9203. }
  9204. static bool encode_endgroup(void *c, const void *hd) {
  9205. return encode_tag(c, hd) && commit(c);
  9206. }
  9207. static void *encode_startstr(void *c, const void *hd, size_t size_hint) {
  9208. UPB_UNUSED(size_hint);
  9209. return encode_startdelimfield(c, hd);
  9210. }
  9211. static size_t encode_strbuf(void *c, const void *hd, const char *buf,
  9212. size_t len, const upb_bufhandle *h) {
  9213. UPB_UNUSED(hd);
  9214. UPB_UNUSED(h);
  9215. return encode_bytes(c, buf, len) ? len : 0;
  9216. }
  9217. #define T(type, ctype, convert, encode) \
  9218. static bool encode_scalar_##type(void *e, const void *hd, ctype val) { \
  9219. return encode_tag(e, hd) && encode(e, (convert)(val)) && commit(e); \
  9220. } \
  9221. static bool encode_packed_##type(void *e, const void *hd, ctype val) { \
  9222. UPB_UNUSED(hd); \
  9223. return encode(e, (convert)(val)); \
  9224. }
  9225. T(double, double, dbl2uint64, encode_fixed64)
  9226. T(float, float, flt2uint32, encode_fixed32)
  9227. T(int64, int64_t, uint64_t, encode_varint)
  9228. T(int32, int32_t, uint32_t, encode_varint)
  9229. T(fixed64, uint64_t, uint64_t, encode_fixed64)
  9230. T(fixed32, uint32_t, uint32_t, encode_fixed32)
  9231. T(bool, bool, bool, encode_varint)
  9232. T(uint32, uint32_t, uint32_t, encode_varint)
  9233. T(uint64, uint64_t, uint64_t, encode_varint)
  9234. T(enum, int32_t, uint32_t, encode_varint)
  9235. T(sfixed32, int32_t, uint32_t, encode_fixed32)
  9236. T(sfixed64, int64_t, uint64_t, encode_fixed64)
  9237. T(sint32, int32_t, upb_zzenc_32, encode_varint)
  9238. T(sint64, int64_t, upb_zzenc_64, encode_varint)
  9239. #undef T
  9240. /* code to build the handlers *************************************************/
  9241. static void newhandlers_callback(const void *closure, upb_handlers *h) {
  9242. const upb_msgdef *m;
  9243. upb_msg_field_iter i;
  9244. UPB_UNUSED(closure);
  9245. upb_handlers_setstartmsg(h, startmsg, NULL);
  9246. upb_handlers_setendmsg(h, endmsg, NULL);
  9247. m = upb_handlers_msgdef(h);
  9248. for(upb_msg_field_begin(&i, m);
  9249. !upb_msg_field_done(&i);
  9250. upb_msg_field_next(&i)) {
  9251. const upb_fielddef *f = upb_msg_iter_field(&i);
  9252. bool packed = upb_fielddef_isseq(f) && upb_fielddef_isprimitive(f) &&
  9253. upb_fielddef_packed(f);
  9254. upb_handlerattr attr;
  9255. upb_wiretype_t wt =
  9256. packed ? UPB_WIRE_TYPE_DELIMITED
  9257. : upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  9258. /* Pre-encode the tag for this field. */
  9259. new_tag(h, f, wt, &attr);
  9260. if (packed) {
  9261. upb_handlers_setstartseq(h, f, encode_startdelimfield, &attr);
  9262. upb_handlers_setendseq(h, f, encode_enddelimfield, &attr);
  9263. }
  9264. #define T(upper, lower, upbtype) \
  9265. case UPB_DESCRIPTOR_TYPE_##upper: \
  9266. if (packed) { \
  9267. upb_handlers_set##upbtype(h, f, encode_packed_##lower, &attr); \
  9268. } else { \
  9269. upb_handlers_set##upbtype(h, f, encode_scalar_##lower, &attr); \
  9270. } \
  9271. break;
  9272. switch (upb_fielddef_descriptortype(f)) {
  9273. T(DOUBLE, double, double);
  9274. T(FLOAT, float, float);
  9275. T(INT64, int64, int64);
  9276. T(INT32, int32, int32);
  9277. T(FIXED64, fixed64, uint64);
  9278. T(FIXED32, fixed32, uint32);
  9279. T(BOOL, bool, bool);
  9280. T(UINT32, uint32, uint32);
  9281. T(UINT64, uint64, uint64);
  9282. T(ENUM, enum, int32);
  9283. T(SFIXED32, sfixed32, int32);
  9284. T(SFIXED64, sfixed64, int64);
  9285. T(SINT32, sint32, int32);
  9286. T(SINT64, sint64, int64);
  9287. case UPB_DESCRIPTOR_TYPE_STRING:
  9288. case UPB_DESCRIPTOR_TYPE_BYTES:
  9289. upb_handlers_setstartstr(h, f, encode_startstr, &attr);
  9290. upb_handlers_setendstr(h, f, encode_enddelimfield, &attr);
  9291. upb_handlers_setstring(h, f, encode_strbuf, &attr);
  9292. break;
  9293. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  9294. upb_handlers_setstartsubmsg(h, f, encode_startdelimfield, &attr);
  9295. upb_handlers_setendsubmsg(h, f, encode_enddelimfield, &attr);
  9296. break;
  9297. case UPB_DESCRIPTOR_TYPE_GROUP: {
  9298. /* Endgroup takes a different tag (wire_type = END_GROUP). */
  9299. upb_handlerattr attr2;
  9300. new_tag(h, f, UPB_WIRE_TYPE_END_GROUP, &attr2);
  9301. upb_handlers_setstartsubmsg(h, f, encode_startgroup, &attr);
  9302. upb_handlers_setendsubmsg(h, f, encode_endgroup, &attr2);
  9303. upb_handlerattr_uninit(&attr2);
  9304. break;
  9305. }
  9306. }
  9307. #undef T
  9308. upb_handlerattr_uninit(&attr);
  9309. }
  9310. }
  9311. void upb_pb_encoder_reset(upb_pb_encoder *e) {
  9312. e->segptr = NULL;
  9313. e->top = NULL;
  9314. e->depth = 0;
  9315. }
  9316. /* public API *****************************************************************/
  9317. const upb_handlers *upb_pb_encoder_newhandlers(const upb_msgdef *m,
  9318. const void *owner) {
  9319. return upb_handlers_newfrozen(m, owner, newhandlers_callback, NULL);
  9320. }
  9321. upb_pb_encoder *upb_pb_encoder_create(upb_env *env, const upb_handlers *h,
  9322. upb_bytessink *output) {
  9323. const size_t initial_bufsize = 256;
  9324. const size_t initial_segbufsize = 16;
  9325. /* TODO(haberman): make this configurable. */
  9326. const size_t stack_size = 64;
  9327. #ifndef NDEBUG
  9328. const size_t size_before = upb_env_bytesallocated(env);
  9329. #endif
  9330. upb_pb_encoder *e = upb_env_malloc(env, sizeof(upb_pb_encoder));
  9331. if (!e) return NULL;
  9332. e->buf = upb_env_malloc(env, initial_bufsize);
  9333. e->segbuf = upb_env_malloc(env, initial_segbufsize * sizeof(*e->segbuf));
  9334. e->stack = upb_env_malloc(env, stack_size * sizeof(*e->stack));
  9335. if (!e->buf || !e->segbuf || !e->stack) {
  9336. return NULL;
  9337. }
  9338. e->limit = e->buf + initial_bufsize;
  9339. e->seglimit = e->segbuf + initial_segbufsize;
  9340. e->stacklimit = e->stack + stack_size;
  9341. upb_pb_encoder_reset(e);
  9342. upb_sink_reset(&e->input_, h, e);
  9343. e->env = env;
  9344. e->output_ = output;
  9345. e->subc = output->closure;
  9346. e->ptr = e->buf;
  9347. /* If this fails, increase the value in encoder.h. */
  9348. UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(env) - size_before <=
  9349. UPB_PB_ENCODER_SIZE);
  9350. return e;
  9351. }
  9352. upb_sink *upb_pb_encoder_input(upb_pb_encoder *e) { return &e->input_; }
  9353. upb_filedef **upb_loaddescriptor(const char *buf, size_t n, const void *owner,
  9354. upb_status *status) {
  9355. /* Create handlers. */
  9356. const upb_pbdecodermethod *decoder_m;
  9357. const upb_handlers *reader_h = upb_descreader_newhandlers(&reader_h);
  9358. upb_env env;
  9359. upb_pbdecodermethodopts opts;
  9360. upb_pbdecoder *decoder;
  9361. upb_descreader *reader;
  9362. bool ok;
  9363. size_t i;
  9364. upb_filedef **ret = NULL;
  9365. upb_pbdecodermethodopts_init(&opts, reader_h);
  9366. decoder_m = upb_pbdecodermethod_new(&opts, &decoder_m);
  9367. upb_env_init(&env);
  9368. upb_env_reporterrorsto(&env, status);
  9369. reader = upb_descreader_create(&env, reader_h);
  9370. decoder = upb_pbdecoder_create(&env, decoder_m, upb_descreader_input(reader));
  9371. /* Push input data. */
  9372. ok = upb_bufsrc_putbuf(buf, n, upb_pbdecoder_input(decoder));
  9373. if (!ok) {
  9374. goto cleanup;
  9375. }
  9376. ret = upb_gmalloc(sizeof (*ret) * (upb_descreader_filecount(reader) + 1));
  9377. if (!ret) {
  9378. goto cleanup;
  9379. }
  9380. for (i = 0; i < upb_descreader_filecount(reader); i++) {
  9381. ret[i] = upb_descreader_file(reader, i);
  9382. upb_filedef_ref(ret[i], owner);
  9383. }
  9384. ret[i] = NULL;
  9385. cleanup:
  9386. upb_env_uninit(&env);
  9387. upb_handlers_unref(reader_h, &reader_h);
  9388. upb_pbdecodermethod_unref(decoder_m, &decoder_m);
  9389. return ret;
  9390. }
  9391. /*
  9392. * upb::pb::TextPrinter
  9393. *
  9394. * OPT: This is not optimized at all. It uses printf() which parses the format
  9395. * string every time, and it allocates memory for every put.
  9396. */
  9397. #include <ctype.h>
  9398. #include <float.h>
  9399. #include <inttypes.h>
  9400. #include <stdarg.h>
  9401. #include <stdio.h>
  9402. #include <string.h>
  9403. struct upb_textprinter {
  9404. upb_sink input_;
  9405. upb_bytessink *output_;
  9406. int indent_depth_;
  9407. bool single_line_;
  9408. void *subc;
  9409. };
  9410. #define CHECK(x) if ((x) < 0) goto err;
  9411. static const char *shortname(const char *longname) {
  9412. const char *last = strrchr(longname, '.');
  9413. return last ? last + 1 : longname;
  9414. }
  9415. static int indent(upb_textprinter *p) {
  9416. int i;
  9417. if (!p->single_line_)
  9418. for (i = 0; i < p->indent_depth_; i++)
  9419. upb_bytessink_putbuf(p->output_, p->subc, " ", 2, NULL);
  9420. return 0;
  9421. }
  9422. static int endfield(upb_textprinter *p) {
  9423. const char ch = (p->single_line_ ? ' ' : '\n');
  9424. upb_bytessink_putbuf(p->output_, p->subc, &ch, 1, NULL);
  9425. return 0;
  9426. }
  9427. static int putescaped(upb_textprinter *p, const char *buf, size_t len,
  9428. bool preserve_utf8) {
  9429. /* Based on CEscapeInternal() from Google's protobuf release. */
  9430. char dstbuf[4096], *dst = dstbuf, *dstend = dstbuf + sizeof(dstbuf);
  9431. const char *end = buf + len;
  9432. /* I think hex is prettier and more useful, but proto2 uses octal; should
  9433. * investigate whether it can parse hex also. */
  9434. const bool use_hex = false;
  9435. bool last_hex_escape = false; /* true if last output char was \xNN */
  9436. for (; buf < end; buf++) {
  9437. bool is_hex_escape;
  9438. if (dstend - dst < 4) {
  9439. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  9440. dst = dstbuf;
  9441. }
  9442. is_hex_escape = false;
  9443. switch (*buf) {
  9444. case '\n': *(dst++) = '\\'; *(dst++) = 'n'; break;
  9445. case '\r': *(dst++) = '\\'; *(dst++) = 'r'; break;
  9446. case '\t': *(dst++) = '\\'; *(dst++) = 't'; break;
  9447. case '\"': *(dst++) = '\\'; *(dst++) = '\"'; break;
  9448. case '\'': *(dst++) = '\\'; *(dst++) = '\''; break;
  9449. case '\\': *(dst++) = '\\'; *(dst++) = '\\'; break;
  9450. default:
  9451. /* Note that if we emit \xNN and the buf character after that is a hex
  9452. * digit then that digit must be escaped too to prevent it being
  9453. * interpreted as part of the character code by C. */
  9454. if ((!preserve_utf8 || (uint8_t)*buf < 0x80) &&
  9455. (!isprint(*buf) || (last_hex_escape && isxdigit(*buf)))) {
  9456. sprintf(dst, (use_hex ? "\\x%02x" : "\\%03o"), (uint8_t)*buf);
  9457. is_hex_escape = use_hex;
  9458. dst += 4;
  9459. } else {
  9460. *(dst++) = *buf; break;
  9461. }
  9462. }
  9463. last_hex_escape = is_hex_escape;
  9464. }
  9465. /* Flush remaining data. */
  9466. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  9467. return 0;
  9468. }
  9469. bool putf(upb_textprinter *p, const char *fmt, ...) {
  9470. va_list args;
  9471. va_list args_copy;
  9472. char *str;
  9473. int written;
  9474. int len;
  9475. bool ok;
  9476. va_start(args, fmt);
  9477. /* Run once to get the length of the string. */
  9478. _upb_va_copy(args_copy, args);
  9479. len = _upb_vsnprintf(NULL, 0, fmt, args_copy);
  9480. va_end(args_copy);
  9481. /* + 1 for NULL terminator (vsprintf() requires it even if we don't). */
  9482. str = upb_gmalloc(len + 1);
  9483. if (!str) return false;
  9484. written = vsprintf(str, fmt, args);
  9485. va_end(args);
  9486. UPB_ASSERT(written == len);
  9487. ok = upb_bytessink_putbuf(p->output_, p->subc, str, len, NULL);
  9488. upb_gfree(str);
  9489. return ok;
  9490. }
  9491. /* handlers *******************************************************************/
  9492. static bool textprinter_startmsg(void *c, const void *hd) {
  9493. upb_textprinter *p = c;
  9494. UPB_UNUSED(hd);
  9495. if (p->indent_depth_ == 0) {
  9496. upb_bytessink_start(p->output_, 0, &p->subc);
  9497. }
  9498. return true;
  9499. }
  9500. static bool textprinter_endmsg(void *c, const void *hd, upb_status *s) {
  9501. upb_textprinter *p = c;
  9502. UPB_UNUSED(hd);
  9503. UPB_UNUSED(s);
  9504. if (p->indent_depth_ == 0) {
  9505. upb_bytessink_end(p->output_);
  9506. }
  9507. return true;
  9508. }
  9509. #define TYPE(name, ctype, fmt) \
  9510. static bool textprinter_put ## name(void *closure, const void *handler_data, \
  9511. ctype val) { \
  9512. upb_textprinter *p = closure; \
  9513. const upb_fielddef *f = handler_data; \
  9514. CHECK(indent(p)); \
  9515. putf(p, "%s: " fmt, upb_fielddef_name(f), val); \
  9516. CHECK(endfield(p)); \
  9517. return true; \
  9518. err: \
  9519. return false; \
  9520. }
  9521. static bool textprinter_putbool(void *closure, const void *handler_data,
  9522. bool val) {
  9523. upb_textprinter *p = closure;
  9524. const upb_fielddef *f = handler_data;
  9525. CHECK(indent(p));
  9526. putf(p, "%s: %s", upb_fielddef_name(f), val ? "true" : "false");
  9527. CHECK(endfield(p));
  9528. return true;
  9529. err:
  9530. return false;
  9531. }
  9532. #define STRINGIFY_HELPER(x) #x
  9533. #define STRINGIFY_MACROVAL(x) STRINGIFY_HELPER(x)
  9534. TYPE(int32, int32_t, "%" PRId32)
  9535. TYPE(int64, int64_t, "%" PRId64)
  9536. TYPE(uint32, uint32_t, "%" PRIu32)
  9537. TYPE(uint64, uint64_t, "%" PRIu64)
  9538. TYPE(float, float, "%." STRINGIFY_MACROVAL(FLT_DIG) "g")
  9539. TYPE(double, double, "%." STRINGIFY_MACROVAL(DBL_DIG) "g")
  9540. #undef TYPE
  9541. /* Output a symbolic value from the enum if found, else just print as int32. */
  9542. static bool textprinter_putenum(void *closure, const void *handler_data,
  9543. int32_t val) {
  9544. upb_textprinter *p = closure;
  9545. const upb_fielddef *f = handler_data;
  9546. const upb_enumdef *enum_def = upb_downcast_enumdef(upb_fielddef_subdef(f));
  9547. const char *label = upb_enumdef_iton(enum_def, val);
  9548. if (label) {
  9549. indent(p);
  9550. putf(p, "%s: %s", upb_fielddef_name(f), label);
  9551. endfield(p);
  9552. } else {
  9553. if (!textprinter_putint32(closure, handler_data, val))
  9554. return false;
  9555. }
  9556. return true;
  9557. }
  9558. static void *textprinter_startstr(void *closure, const void *handler_data,
  9559. size_t size_hint) {
  9560. upb_textprinter *p = closure;
  9561. const upb_fielddef *f = handler_data;
  9562. UPB_UNUSED(size_hint);
  9563. indent(p);
  9564. putf(p, "%s: \"", upb_fielddef_name(f));
  9565. return p;
  9566. }
  9567. static bool textprinter_endstr(void *closure, const void *handler_data) {
  9568. upb_textprinter *p = closure;
  9569. UPB_UNUSED(handler_data);
  9570. putf(p, "\"");
  9571. endfield(p);
  9572. return true;
  9573. }
  9574. static size_t textprinter_putstr(void *closure, const void *hd, const char *buf,
  9575. size_t len, const upb_bufhandle *handle) {
  9576. upb_textprinter *p = closure;
  9577. const upb_fielddef *f = hd;
  9578. UPB_UNUSED(handle);
  9579. CHECK(putescaped(p, buf, len, upb_fielddef_type(f) == UPB_TYPE_STRING));
  9580. return len;
  9581. err:
  9582. return 0;
  9583. }
  9584. static void *textprinter_startsubmsg(void *closure, const void *handler_data) {
  9585. upb_textprinter *p = closure;
  9586. const char *name = handler_data;
  9587. CHECK(indent(p));
  9588. putf(p, "%s {%c", name, p->single_line_ ? ' ' : '\n');
  9589. p->indent_depth_++;
  9590. return p;
  9591. err:
  9592. return UPB_BREAK;
  9593. }
  9594. static bool textprinter_endsubmsg(void *closure, const void *handler_data) {
  9595. upb_textprinter *p = closure;
  9596. UPB_UNUSED(handler_data);
  9597. p->indent_depth_--;
  9598. CHECK(indent(p));
  9599. upb_bytessink_putbuf(p->output_, p->subc, "}", 1, NULL);
  9600. CHECK(endfield(p));
  9601. return true;
  9602. err:
  9603. return false;
  9604. }
  9605. static void onmreg(const void *c, upb_handlers *h) {
  9606. const upb_msgdef *m = upb_handlers_msgdef(h);
  9607. upb_msg_field_iter i;
  9608. UPB_UNUSED(c);
  9609. upb_handlers_setstartmsg(h, textprinter_startmsg, NULL);
  9610. upb_handlers_setendmsg(h, textprinter_endmsg, NULL);
  9611. for(upb_msg_field_begin(&i, m);
  9612. !upb_msg_field_done(&i);
  9613. upb_msg_field_next(&i)) {
  9614. upb_fielddef *f = upb_msg_iter_field(&i);
  9615. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  9616. upb_handlerattr_sethandlerdata(&attr, f);
  9617. switch (upb_fielddef_type(f)) {
  9618. case UPB_TYPE_INT32:
  9619. upb_handlers_setint32(h, f, textprinter_putint32, &attr);
  9620. break;
  9621. case UPB_TYPE_INT64:
  9622. upb_handlers_setint64(h, f, textprinter_putint64, &attr);
  9623. break;
  9624. case UPB_TYPE_UINT32:
  9625. upb_handlers_setuint32(h, f, textprinter_putuint32, &attr);
  9626. break;
  9627. case UPB_TYPE_UINT64:
  9628. upb_handlers_setuint64(h, f, textprinter_putuint64, &attr);
  9629. break;
  9630. case UPB_TYPE_FLOAT:
  9631. upb_handlers_setfloat(h, f, textprinter_putfloat, &attr);
  9632. break;
  9633. case UPB_TYPE_DOUBLE:
  9634. upb_handlers_setdouble(h, f, textprinter_putdouble, &attr);
  9635. break;
  9636. case UPB_TYPE_BOOL:
  9637. upb_handlers_setbool(h, f, textprinter_putbool, &attr);
  9638. break;
  9639. case UPB_TYPE_STRING:
  9640. case UPB_TYPE_BYTES:
  9641. upb_handlers_setstartstr(h, f, textprinter_startstr, &attr);
  9642. upb_handlers_setstring(h, f, textprinter_putstr, &attr);
  9643. upb_handlers_setendstr(h, f, textprinter_endstr, &attr);
  9644. break;
  9645. case UPB_TYPE_MESSAGE: {
  9646. const char *name =
  9647. upb_fielddef_istagdelim(f)
  9648. ? shortname(upb_msgdef_fullname(upb_fielddef_msgsubdef(f)))
  9649. : upb_fielddef_name(f);
  9650. upb_handlerattr_sethandlerdata(&attr, name);
  9651. upb_handlers_setstartsubmsg(h, f, textprinter_startsubmsg, &attr);
  9652. upb_handlers_setendsubmsg(h, f, textprinter_endsubmsg, &attr);
  9653. break;
  9654. }
  9655. case UPB_TYPE_ENUM:
  9656. upb_handlers_setint32(h, f, textprinter_putenum, &attr);
  9657. break;
  9658. }
  9659. }
  9660. }
  9661. static void textprinter_reset(upb_textprinter *p, bool single_line) {
  9662. p->single_line_ = single_line;
  9663. p->indent_depth_ = 0;
  9664. }
  9665. /* Public API *****************************************************************/
  9666. upb_textprinter *upb_textprinter_create(upb_env *env, const upb_handlers *h,
  9667. upb_bytessink *output) {
  9668. upb_textprinter *p = upb_env_malloc(env, sizeof(upb_textprinter));
  9669. if (!p) return NULL;
  9670. p->output_ = output;
  9671. upb_sink_reset(&p->input_, h, p);
  9672. textprinter_reset(p, false);
  9673. return p;
  9674. }
  9675. const upb_handlers *upb_textprinter_newhandlers(const upb_msgdef *m,
  9676. const void *owner) {
  9677. return upb_handlers_newfrozen(m, owner, &onmreg, NULL);
  9678. }
  9679. upb_sink *upb_textprinter_input(upb_textprinter *p) { return &p->input_; }
  9680. void upb_textprinter_setsingleline(upb_textprinter *p, bool single_line) {
  9681. p->single_line_ = single_line;
  9682. }
  9683. /* Index is descriptor type. */
  9684. const uint8_t upb_pb_native_wire_types[] = {
  9685. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  9686. UPB_WIRE_TYPE_64BIT, /* DOUBLE */
  9687. UPB_WIRE_TYPE_32BIT, /* FLOAT */
  9688. UPB_WIRE_TYPE_VARINT, /* INT64 */
  9689. UPB_WIRE_TYPE_VARINT, /* UINT64 */
  9690. UPB_WIRE_TYPE_VARINT, /* INT32 */
  9691. UPB_WIRE_TYPE_64BIT, /* FIXED64 */
  9692. UPB_WIRE_TYPE_32BIT, /* FIXED32 */
  9693. UPB_WIRE_TYPE_VARINT, /* BOOL */
  9694. UPB_WIRE_TYPE_DELIMITED, /* STRING */
  9695. UPB_WIRE_TYPE_START_GROUP, /* GROUP */
  9696. UPB_WIRE_TYPE_DELIMITED, /* MESSAGE */
  9697. UPB_WIRE_TYPE_DELIMITED, /* BYTES */
  9698. UPB_WIRE_TYPE_VARINT, /* UINT32 */
  9699. UPB_WIRE_TYPE_VARINT, /* ENUM */
  9700. UPB_WIRE_TYPE_32BIT, /* SFIXED32 */
  9701. UPB_WIRE_TYPE_64BIT, /* SFIXED64 */
  9702. UPB_WIRE_TYPE_VARINT, /* SINT32 */
  9703. UPB_WIRE_TYPE_VARINT, /* SINT64 */
  9704. };
  9705. /* A basic branch-based decoder, uses 32-bit values to get good performance
  9706. * on 32-bit architectures (but performs well on 64-bits also).
  9707. * This scheme comes from the original Google Protobuf implementation
  9708. * (proto2). */
  9709. upb_decoderet upb_vdecode_max8_branch32(upb_decoderet r) {
  9710. upb_decoderet err = {NULL, 0};
  9711. const char *p = r.p;
  9712. uint32_t low = (uint32_t)r.val;
  9713. uint32_t high = 0;
  9714. uint32_t b;
  9715. b = *(p++); low |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  9716. b = *(p++); low |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  9717. b = *(p++); low |= (b & 0x7fU) << 28;
  9718. high = (b & 0x7fU) >> 4; if (!(b & 0x80)) goto done;
  9719. b = *(p++); high |= (b & 0x7fU) << 3; if (!(b & 0x80)) goto done;
  9720. b = *(p++); high |= (b & 0x7fU) << 10; if (!(b & 0x80)) goto done;
  9721. b = *(p++); high |= (b & 0x7fU) << 17; if (!(b & 0x80)) goto done;
  9722. b = *(p++); high |= (b & 0x7fU) << 24; if (!(b & 0x80)) goto done;
  9723. b = *(p++); high |= (b & 0x7fU) << 31; if (!(b & 0x80)) goto done;
  9724. return err;
  9725. done:
  9726. r.val = ((uint64_t)high << 32) | low;
  9727. r.p = p;
  9728. return r;
  9729. }
  9730. /* Like the previous, but uses 64-bit values. */
  9731. upb_decoderet upb_vdecode_max8_branch64(upb_decoderet r) {
  9732. const char *p = r.p;
  9733. uint64_t val = r.val;
  9734. uint64_t b;
  9735. upb_decoderet err = {NULL, 0};
  9736. b = *(p++); val |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  9737. b = *(p++); val |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  9738. b = *(p++); val |= (b & 0x7fU) << 28; if (!(b & 0x80)) goto done;
  9739. b = *(p++); val |= (b & 0x7fU) << 35; if (!(b & 0x80)) goto done;
  9740. b = *(p++); val |= (b & 0x7fU) << 42; if (!(b & 0x80)) goto done;
  9741. b = *(p++); val |= (b & 0x7fU) << 49; if (!(b & 0x80)) goto done;
  9742. b = *(p++); val |= (b & 0x7fU) << 56; if (!(b & 0x80)) goto done;
  9743. b = *(p++); val |= (b & 0x7fU) << 63; if (!(b & 0x80)) goto done;
  9744. return err;
  9745. done:
  9746. r.val = val;
  9747. r.p = p;
  9748. return r;
  9749. }
  9750. /* Given an encoded varint v, returns an integer with a single bit set that
  9751. * indicates the end of the varint. Subtracting one from this value will
  9752. * yield a mask that leaves only bits that are part of the varint. Returns
  9753. * 0 if the varint is unterminated. */
  9754. static uint64_t upb_get_vstopbit(uint64_t v) {
  9755. uint64_t cbits = v | 0x7f7f7f7f7f7f7f7fULL;
  9756. return ~cbits & (cbits+1);
  9757. }
  9758. /* A branchless decoder. Credit to Pascal Massimino for the bit-twiddling. */
  9759. upb_decoderet upb_vdecode_max8_massimino(upb_decoderet r) {
  9760. uint64_t b;
  9761. uint64_t stop_bit;
  9762. upb_decoderet my_r;
  9763. memcpy(&b, r.p, sizeof(b));
  9764. stop_bit = upb_get_vstopbit(b);
  9765. b = (b & 0x7f7f7f7f7f7f7f7fULL) & (stop_bit - 1);
  9766. b += b & 0x007f007f007f007fULL;
  9767. b += 3 * (b & 0x0000ffff0000ffffULL);
  9768. b += 15 * (b & 0x00000000ffffffffULL);
  9769. if (stop_bit == 0) {
  9770. /* Error: unterminated varint. */
  9771. upb_decoderet err_r = {(void*)0, 0};
  9772. return err_r;
  9773. }
  9774. my_r = upb_decoderet_make(r.p + ((__builtin_ctzll(stop_bit) + 1) / 8),
  9775. r.val | (b << 7));
  9776. return my_r;
  9777. }
  9778. /* A branchless decoder. Credit to Daniel Wright for the bit-twiddling. */
  9779. upb_decoderet upb_vdecode_max8_wright(upb_decoderet r) {
  9780. uint64_t b;
  9781. uint64_t stop_bit;
  9782. upb_decoderet my_r;
  9783. memcpy(&b, r.p, sizeof(b));
  9784. stop_bit = upb_get_vstopbit(b);
  9785. b &= (stop_bit - 1);
  9786. b = ((b & 0x7f007f007f007f00ULL) >> 1) | (b & 0x007f007f007f007fULL);
  9787. b = ((b & 0xffff0000ffff0000ULL) >> 2) | (b & 0x0000ffff0000ffffULL);
  9788. b = ((b & 0xffffffff00000000ULL) >> 4) | (b & 0x00000000ffffffffULL);
  9789. if (stop_bit == 0) {
  9790. /* Error: unterminated varint. */
  9791. upb_decoderet err_r = {(void*)0, 0};
  9792. return err_r;
  9793. }
  9794. my_r = upb_decoderet_make(r.p + ((__builtin_ctzll(stop_bit) + 1) / 8),
  9795. r.val | (b << 14));
  9796. return my_r;
  9797. }
  9798. #line 1 "upb/json/parser.rl"
  9799. /*
  9800. ** upb::json::Parser (upb_json_parser)
  9801. **
  9802. ** A parser that uses the Ragel State Machine Compiler to generate
  9803. ** the finite automata.
  9804. **
  9805. ** Ragel only natively handles regular languages, but we can manually
  9806. ** program it a bit to handle context-free languages like JSON, by using
  9807. ** the "fcall" and "fret" constructs.
  9808. **
  9809. ** This parser can handle the basics, but needs several things to be fleshed
  9810. ** out:
  9811. **
  9812. ** - handling of unicode escape sequences (including high surrogate pairs).
  9813. ** - properly check and report errors for unknown fields, stack overflow,
  9814. ** improper array nesting (or lack of nesting).
  9815. ** - handling of base64 sequences with padding characters.
  9816. ** - handling of push-back (non-success returns from sink functions).
  9817. ** - handling of keys/escape-sequences/etc that span input buffers.
  9818. */
  9819. #include <assert.h>
  9820. #include <errno.h>
  9821. #include <stdint.h>
  9822. #include <stdlib.h>
  9823. #include <string.h>
  9824. #define UPB_JSON_MAX_DEPTH 64
  9825. typedef struct {
  9826. upb_sink sink;
  9827. /* The current message in which we're parsing, and the field whose value we're
  9828. * expecting next. */
  9829. const upb_msgdef *m;
  9830. const upb_fielddef *f;
  9831. /* The table mapping json name to fielddef for this message. */
  9832. upb_strtable *name_table;
  9833. /* We are in a repeated-field context, ready to emit mapentries as
  9834. * submessages. This flag alters the start-of-object (open-brace) behavior to
  9835. * begin a sequence of mapentry messages rather than a single submessage. */
  9836. bool is_map;
  9837. /* We are in a map-entry message context. This flag is set when parsing the
  9838. * value field of a single map entry and indicates to all value-field parsers
  9839. * (subobjects, strings, numbers, and bools) that the map-entry submessage
  9840. * should end as soon as the value is parsed. */
  9841. bool is_mapentry;
  9842. /* If |is_map| or |is_mapentry| is true, |mapfield| refers to the parent
  9843. * message's map field that we're currently parsing. This differs from |f|
  9844. * because |f| is the field in the *current* message (i.e., the map-entry
  9845. * message itself), not the parent's field that leads to this map. */
  9846. const upb_fielddef *mapfield;
  9847. } upb_jsonparser_frame;
  9848. struct upb_json_parser {
  9849. upb_env *env;
  9850. const upb_json_parsermethod *method;
  9851. upb_bytessink input_;
  9852. /* Stack to track the JSON scopes we are in. */
  9853. upb_jsonparser_frame stack[UPB_JSON_MAX_DEPTH];
  9854. upb_jsonparser_frame *top;
  9855. upb_jsonparser_frame *limit;
  9856. upb_status status;
  9857. /* Ragel's internal parsing stack for the parsing state machine. */
  9858. int current_state;
  9859. int parser_stack[UPB_JSON_MAX_DEPTH];
  9860. int parser_top;
  9861. /* The handle for the current buffer. */
  9862. const upb_bufhandle *handle;
  9863. /* Accumulate buffer. See details in parser.rl. */
  9864. const char *accumulated;
  9865. size_t accumulated_len;
  9866. char *accumulate_buf;
  9867. size_t accumulate_buf_size;
  9868. /* Multi-part text data. See details in parser.rl. */
  9869. int multipart_state;
  9870. upb_selector_t string_selector;
  9871. /* Input capture. See details in parser.rl. */
  9872. const char *capture;
  9873. /* Intermediate result of parsing a unicode escape sequence. */
  9874. uint32_t digit;
  9875. };
  9876. struct upb_json_parsermethod {
  9877. upb_refcounted base;
  9878. upb_byteshandler input_handler_;
  9879. /* Mainly for the purposes of refcounting, so all the fielddefs we point
  9880. * to stay alive. */
  9881. const upb_msgdef *msg;
  9882. /* Keys are upb_msgdef*, values are upb_strtable (json_name -> fielddef) */
  9883. upb_inttable name_tables;
  9884. };
  9885. #define PARSER_CHECK_RETURN(x) if (!(x)) return false
  9886. /* Used to signal that a capture has been suspended. */
  9887. static char suspend_capture;
  9888. static upb_selector_t getsel_for_handlertype(upb_json_parser *p,
  9889. upb_handlertype_t type) {
  9890. upb_selector_t sel;
  9891. bool ok = upb_handlers_getselector(p->top->f, type, &sel);
  9892. UPB_ASSERT(ok);
  9893. return sel;
  9894. }
  9895. static upb_selector_t parser_getsel(upb_json_parser *p) {
  9896. return getsel_for_handlertype(
  9897. p, upb_handlers_getprimitivehandlertype(p->top->f));
  9898. }
  9899. static bool check_stack(upb_json_parser *p) {
  9900. if ((p->top + 1) == p->limit) {
  9901. upb_status_seterrmsg(&p->status, "Nesting too deep");
  9902. upb_env_reporterror(p->env, &p->status);
  9903. return false;
  9904. }
  9905. return true;
  9906. }
  9907. static void set_name_table(upb_json_parser *p, upb_jsonparser_frame *frame) {
  9908. upb_value v;
  9909. bool ok = upb_inttable_lookupptr(&p->method->name_tables, frame->m, &v);
  9910. UPB_ASSERT(ok);
  9911. frame->name_table = upb_value_getptr(v);
  9912. }
  9913. /* There are GCC/Clang built-ins for overflow checking which we could start
  9914. * using if there was any performance benefit to it. */
  9915. static bool checked_add(size_t a, size_t b, size_t *c) {
  9916. if (SIZE_MAX - a < b) return false;
  9917. *c = a + b;
  9918. return true;
  9919. }
  9920. static size_t saturating_multiply(size_t a, size_t b) {
  9921. /* size_t is unsigned, so this is defined behavior even on overflow. */
  9922. size_t ret = a * b;
  9923. if (b != 0 && ret / b != a) {
  9924. ret = SIZE_MAX;
  9925. }
  9926. return ret;
  9927. }
  9928. /* Base64 decoding ************************************************************/
  9929. /* TODO(haberman): make this streaming. */
  9930. static const signed char b64table[] = {
  9931. -1, -1, -1, -1, -1, -1, -1, -1,
  9932. -1, -1, -1, -1, -1, -1, -1, -1,
  9933. -1, -1, -1, -1, -1, -1, -1, -1,
  9934. -1, -1, -1, -1, -1, -1, -1, -1,
  9935. -1, -1, -1, -1, -1, -1, -1, -1,
  9936. -1, -1, -1, 62/*+*/, -1, -1, -1, 63/*/ */,
  9937. 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
  9938. 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1,
  9939. -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
  9940. 07/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
  9941. 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
  9942. 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, -1,
  9943. -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
  9944. 33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
  9945. 41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
  9946. 49/*x*/, 50/*y*/, 51/*z*/, -1, -1, -1, -1, -1,
  9947. -1, -1, -1, -1, -1, -1, -1, -1,
  9948. -1, -1, -1, -1, -1, -1, -1, -1,
  9949. -1, -1, -1, -1, -1, -1, -1, -1,
  9950. -1, -1, -1, -1, -1, -1, -1, -1,
  9951. -1, -1, -1, -1, -1, -1, -1, -1,
  9952. -1, -1, -1, -1, -1, -1, -1, -1,
  9953. -1, -1, -1, -1, -1, -1, -1, -1,
  9954. -1, -1, -1, -1, -1, -1, -1, -1,
  9955. -1, -1, -1, -1, -1, -1, -1, -1,
  9956. -1, -1, -1, -1, -1, -1, -1, -1,
  9957. -1, -1, -1, -1, -1, -1, -1, -1,
  9958. -1, -1, -1, -1, -1, -1, -1, -1,
  9959. -1, -1, -1, -1, -1, -1, -1, -1,
  9960. -1, -1, -1, -1, -1, -1, -1, -1,
  9961. -1, -1, -1, -1, -1, -1, -1, -1,
  9962. -1, -1, -1, -1, -1, -1, -1, -1
  9963. };
  9964. /* Returns the table value sign-extended to 32 bits. Knowing that the upper
  9965. * bits will be 1 for unrecognized characters makes it easier to check for
  9966. * this error condition later (see below). */
  9967. int32_t b64lookup(unsigned char ch) { return b64table[ch]; }
  9968. /* Returns true if the given character is not a valid base64 character or
  9969. * padding. */
  9970. bool nonbase64(unsigned char ch) { return b64lookup(ch) == -1 && ch != '='; }
  9971. static bool base64_push(upb_json_parser *p, upb_selector_t sel, const char *ptr,
  9972. size_t len) {
  9973. const char *limit = ptr + len;
  9974. for (; ptr < limit; ptr += 4) {
  9975. uint32_t val;
  9976. char output[3];
  9977. if (limit - ptr < 4) {
  9978. upb_status_seterrf(&p->status,
  9979. "Base64 input for bytes field not a multiple of 4: %s",
  9980. upb_fielddef_name(p->top->f));
  9981. upb_env_reporterror(p->env, &p->status);
  9982. return false;
  9983. }
  9984. val = b64lookup(ptr[0]) << 18 |
  9985. b64lookup(ptr[1]) << 12 |
  9986. b64lookup(ptr[2]) << 6 |
  9987. b64lookup(ptr[3]);
  9988. /* Test the upper bit; returns true if any of the characters returned -1. */
  9989. if (val & 0x80000000) {
  9990. goto otherchar;
  9991. }
  9992. output[0] = val >> 16;
  9993. output[1] = (val >> 8) & 0xff;
  9994. output[2] = val & 0xff;
  9995. upb_sink_putstring(&p->top->sink, sel, output, 3, NULL);
  9996. }
  9997. return true;
  9998. otherchar:
  9999. if (nonbase64(ptr[0]) || nonbase64(ptr[1]) || nonbase64(ptr[2]) ||
  10000. nonbase64(ptr[3]) ) {
  10001. upb_status_seterrf(&p->status,
  10002. "Non-base64 characters in bytes field: %s",
  10003. upb_fielddef_name(p->top->f));
  10004. upb_env_reporterror(p->env, &p->status);
  10005. return false;
  10006. } if (ptr[2] == '=') {
  10007. uint32_t val;
  10008. char output;
  10009. /* Last group contains only two input bytes, one output byte. */
  10010. if (ptr[0] == '=' || ptr[1] == '=' || ptr[3] != '=') {
  10011. goto badpadding;
  10012. }
  10013. val = b64lookup(ptr[0]) << 18 |
  10014. b64lookup(ptr[1]) << 12;
  10015. UPB_ASSERT(!(val & 0x80000000));
  10016. output = val >> 16;
  10017. upb_sink_putstring(&p->top->sink, sel, &output, 1, NULL);
  10018. return true;
  10019. } else {
  10020. uint32_t val;
  10021. char output[2];
  10022. /* Last group contains only three input bytes, two output bytes. */
  10023. if (ptr[0] == '=' || ptr[1] == '=' || ptr[2] == '=') {
  10024. goto badpadding;
  10025. }
  10026. val = b64lookup(ptr[0]) << 18 |
  10027. b64lookup(ptr[1]) << 12 |
  10028. b64lookup(ptr[2]) << 6;
  10029. output[0] = val >> 16;
  10030. output[1] = (val >> 8) & 0xff;
  10031. upb_sink_putstring(&p->top->sink, sel, output, 2, NULL);
  10032. return true;
  10033. }
  10034. badpadding:
  10035. upb_status_seterrf(&p->status,
  10036. "Incorrect base64 padding for field: %s (%.*s)",
  10037. upb_fielddef_name(p->top->f),
  10038. 4, ptr);
  10039. upb_env_reporterror(p->env, &p->status);
  10040. return false;
  10041. }
  10042. /* Accumulate buffer **********************************************************/
  10043. /* Functionality for accumulating a buffer.
  10044. *
  10045. * Some parts of the parser need an entire value as a contiguous string. For
  10046. * example, to look up a member name in a hash table, or to turn a string into
  10047. * a number, the relevant library routines need the input string to be in
  10048. * contiguous memory, even if the value spanned two or more buffers in the
  10049. * input. These routines handle that.
  10050. *
  10051. * In the common case we can just point to the input buffer to get this
  10052. * contiguous string and avoid any actual copy. So we optimistically begin
  10053. * this way. But there are a few cases where we must instead copy into a
  10054. * separate buffer:
  10055. *
  10056. * 1. The string was not contiguous in the input (it spanned buffers).
  10057. *
  10058. * 2. The string included escape sequences that need to be interpreted to get
  10059. * the true value in a contiguous buffer. */
  10060. static void assert_accumulate_empty(upb_json_parser *p) {
  10061. UPB_ASSERT(p->accumulated == NULL);
  10062. UPB_ASSERT(p->accumulated_len == 0);
  10063. }
  10064. static void accumulate_clear(upb_json_parser *p) {
  10065. p->accumulated = NULL;
  10066. p->accumulated_len = 0;
  10067. }
  10068. /* Used internally by accumulate_append(). */
  10069. static bool accumulate_realloc(upb_json_parser *p, size_t need) {
  10070. void *mem;
  10071. size_t old_size = p->accumulate_buf_size;
  10072. size_t new_size = UPB_MAX(old_size, 128);
  10073. while (new_size < need) {
  10074. new_size = saturating_multiply(new_size, 2);
  10075. }
  10076. mem = upb_env_realloc(p->env, p->accumulate_buf, old_size, new_size);
  10077. if (!mem) {
  10078. upb_status_seterrmsg(&p->status, "Out of memory allocating buffer.");
  10079. upb_env_reporterror(p->env, &p->status);
  10080. return false;
  10081. }
  10082. p->accumulate_buf = mem;
  10083. p->accumulate_buf_size = new_size;
  10084. return true;
  10085. }
  10086. /* Logically appends the given data to the append buffer.
  10087. * If "can_alias" is true, we will try to avoid actually copying, but the buffer
  10088. * must be valid until the next accumulate_append() call (if any). */
  10089. static bool accumulate_append(upb_json_parser *p, const char *buf, size_t len,
  10090. bool can_alias) {
  10091. size_t need;
  10092. if (!p->accumulated && can_alias) {
  10093. p->accumulated = buf;
  10094. p->accumulated_len = len;
  10095. return true;
  10096. }
  10097. if (!checked_add(p->accumulated_len, len, &need)) {
  10098. upb_status_seterrmsg(&p->status, "Integer overflow.");
  10099. upb_env_reporterror(p->env, &p->status);
  10100. return false;
  10101. }
  10102. if (need > p->accumulate_buf_size && !accumulate_realloc(p, need)) {
  10103. return false;
  10104. }
  10105. if (p->accumulated != p->accumulate_buf) {
  10106. memcpy(p->accumulate_buf, p->accumulated, p->accumulated_len);
  10107. p->accumulated = p->accumulate_buf;
  10108. }
  10109. memcpy(p->accumulate_buf + p->accumulated_len, buf, len);
  10110. p->accumulated_len += len;
  10111. return true;
  10112. }
  10113. /* Returns a pointer to the data accumulated since the last accumulate_clear()
  10114. * call, and writes the length to *len. This with point either to the input
  10115. * buffer or a temporary accumulate buffer. */
  10116. static const char *accumulate_getptr(upb_json_parser *p, size_t *len) {
  10117. UPB_ASSERT(p->accumulated);
  10118. *len = p->accumulated_len;
  10119. return p->accumulated;
  10120. }
  10121. /* Mult-part text data ********************************************************/
  10122. /* When we have text data in the input, it can often come in multiple segments.
  10123. * For example, there may be some raw string data followed by an escape
  10124. * sequence. The two segments are processed with different logic. Also buffer
  10125. * seams in the input can cause multiple segments.
  10126. *
  10127. * As we see segments, there are two main cases for how we want to process them:
  10128. *
  10129. * 1. we want to push the captured input directly to string handlers.
  10130. *
  10131. * 2. we need to accumulate all the parts into a contiguous buffer for further
  10132. * processing (field name lookup, string->number conversion, etc). */
  10133. /* This is the set of states for p->multipart_state. */
  10134. enum {
  10135. /* We are not currently processing multipart data. */
  10136. MULTIPART_INACTIVE = 0,
  10137. /* We are processing multipart data by accumulating it into a contiguous
  10138. * buffer. */
  10139. MULTIPART_ACCUMULATE = 1,
  10140. /* We are processing multipart data by pushing each part directly to the
  10141. * current string handlers. */
  10142. MULTIPART_PUSHEAGERLY = 2
  10143. };
  10144. /* Start a multi-part text value where we accumulate the data for processing at
  10145. * the end. */
  10146. static void multipart_startaccum(upb_json_parser *p) {
  10147. assert_accumulate_empty(p);
  10148. UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
  10149. p->multipart_state = MULTIPART_ACCUMULATE;
  10150. }
  10151. /* Start a multi-part text value where we immediately push text data to a string
  10152. * value with the given selector. */
  10153. static void multipart_start(upb_json_parser *p, upb_selector_t sel) {
  10154. assert_accumulate_empty(p);
  10155. UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
  10156. p->multipart_state = MULTIPART_PUSHEAGERLY;
  10157. p->string_selector = sel;
  10158. }
  10159. static bool multipart_text(upb_json_parser *p, const char *buf, size_t len,
  10160. bool can_alias) {
  10161. switch (p->multipart_state) {
  10162. case MULTIPART_INACTIVE:
  10163. upb_status_seterrmsg(
  10164. &p->status, "Internal error: unexpected state MULTIPART_INACTIVE");
  10165. upb_env_reporterror(p->env, &p->status);
  10166. return false;
  10167. case MULTIPART_ACCUMULATE:
  10168. if (!accumulate_append(p, buf, len, can_alias)) {
  10169. return false;
  10170. }
  10171. break;
  10172. case MULTIPART_PUSHEAGERLY: {
  10173. const upb_bufhandle *handle = can_alias ? p->handle : NULL;
  10174. upb_sink_putstring(&p->top->sink, p->string_selector, buf, len, handle);
  10175. break;
  10176. }
  10177. }
  10178. return true;
  10179. }
  10180. /* Note: this invalidates the accumulate buffer! Call only after reading its
  10181. * contents. */
  10182. static void multipart_end(upb_json_parser *p) {
  10183. UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
  10184. p->multipart_state = MULTIPART_INACTIVE;
  10185. accumulate_clear(p);
  10186. }
  10187. /* Input capture **************************************************************/
  10188. /* Functionality for capturing a region of the input as text. Gracefully
  10189. * handles the case where a buffer seam occurs in the middle of the captured
  10190. * region. */
  10191. static void capture_begin(upb_json_parser *p, const char *ptr) {
  10192. UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
  10193. UPB_ASSERT(p->capture == NULL);
  10194. p->capture = ptr;
  10195. }
  10196. static bool capture_end(upb_json_parser *p, const char *ptr) {
  10197. UPB_ASSERT(p->capture);
  10198. if (multipart_text(p, p->capture, ptr - p->capture, true)) {
  10199. p->capture = NULL;
  10200. return true;
  10201. } else {
  10202. return false;
  10203. }
  10204. }
  10205. /* This is called at the end of each input buffer (ie. when we have hit a
  10206. * buffer seam). If we are in the middle of capturing the input, this
  10207. * processes the unprocessed capture region. */
  10208. static void capture_suspend(upb_json_parser *p, const char **ptr) {
  10209. if (!p->capture) return;
  10210. if (multipart_text(p, p->capture, *ptr - p->capture, false)) {
  10211. /* We use this as a signal that we were in the middle of capturing, and
  10212. * that capturing should resume at the beginning of the next buffer.
  10213. *
  10214. * We can't use *ptr here, because we have no guarantee that this pointer
  10215. * will be valid when we resume (if the underlying memory is freed, then
  10216. * using the pointer at all, even to compare to NULL, is likely undefined
  10217. * behavior). */
  10218. p->capture = &suspend_capture;
  10219. } else {
  10220. /* Need to back up the pointer to the beginning of the capture, since
  10221. * we were not able to actually preserve it. */
  10222. *ptr = p->capture;
  10223. }
  10224. }
  10225. static void capture_resume(upb_json_parser *p, const char *ptr) {
  10226. if (p->capture) {
  10227. UPB_ASSERT(p->capture == &suspend_capture);
  10228. p->capture = ptr;
  10229. }
  10230. }
  10231. /* Callbacks from the parser **************************************************/
  10232. /* These are the functions called directly from the parser itself.
  10233. * We define these in the same order as their declarations in the parser. */
  10234. static char escape_char(char in) {
  10235. switch (in) {
  10236. case 'r': return '\r';
  10237. case 't': return '\t';
  10238. case 'n': return '\n';
  10239. case 'f': return '\f';
  10240. case 'b': return '\b';
  10241. case '/': return '/';
  10242. case '"': return '"';
  10243. case '\\': return '\\';
  10244. default:
  10245. UPB_ASSERT(0);
  10246. return 'x';
  10247. }
  10248. }
  10249. static bool escape(upb_json_parser *p, const char *ptr) {
  10250. char ch = escape_char(*ptr);
  10251. return multipart_text(p, &ch, 1, false);
  10252. }
  10253. static void start_hex(upb_json_parser *p) {
  10254. p->digit = 0;
  10255. }
  10256. static void hexdigit(upb_json_parser *p, const char *ptr) {
  10257. char ch = *ptr;
  10258. p->digit <<= 4;
  10259. if (ch >= '0' && ch <= '9') {
  10260. p->digit += (ch - '0');
  10261. } else if (ch >= 'a' && ch <= 'f') {
  10262. p->digit += ((ch - 'a') + 10);
  10263. } else {
  10264. UPB_ASSERT(ch >= 'A' && ch <= 'F');
  10265. p->digit += ((ch - 'A') + 10);
  10266. }
  10267. }
  10268. static bool end_hex(upb_json_parser *p) {
  10269. uint32_t codepoint = p->digit;
  10270. /* emit the codepoint as UTF-8. */
  10271. char utf8[3]; /* support \u0000 -- \uFFFF -- need only three bytes. */
  10272. int length = 0;
  10273. if (codepoint <= 0x7F) {
  10274. utf8[0] = codepoint;
  10275. length = 1;
  10276. } else if (codepoint <= 0x07FF) {
  10277. utf8[1] = (codepoint & 0x3F) | 0x80;
  10278. codepoint >>= 6;
  10279. utf8[0] = (codepoint & 0x1F) | 0xC0;
  10280. length = 2;
  10281. } else /* codepoint <= 0xFFFF */ {
  10282. utf8[2] = (codepoint & 0x3F) | 0x80;
  10283. codepoint >>= 6;
  10284. utf8[1] = (codepoint & 0x3F) | 0x80;
  10285. codepoint >>= 6;
  10286. utf8[0] = (codepoint & 0x0F) | 0xE0;
  10287. length = 3;
  10288. }
  10289. /* TODO(haberman): Handle high surrogates: if codepoint is a high surrogate
  10290. * we have to wait for the next escape to get the full code point). */
  10291. return multipart_text(p, utf8, length, false);
  10292. }
  10293. static void start_text(upb_json_parser *p, const char *ptr) {
  10294. capture_begin(p, ptr);
  10295. }
  10296. static bool end_text(upb_json_parser *p, const char *ptr) {
  10297. return capture_end(p, ptr);
  10298. }
  10299. static void start_number(upb_json_parser *p, const char *ptr) {
  10300. multipart_startaccum(p);
  10301. capture_begin(p, ptr);
  10302. }
  10303. static bool parse_number(upb_json_parser *p);
  10304. static bool end_number(upb_json_parser *p, const char *ptr) {
  10305. if (!capture_end(p, ptr)) {
  10306. return false;
  10307. }
  10308. return parse_number(p);
  10309. }
  10310. static bool parse_number(upb_json_parser *p) {
  10311. size_t len;
  10312. const char *buf;
  10313. const char *myend;
  10314. char *end;
  10315. /* strtol() and friends unfortunately do not support specifying the length of
  10316. * the input string, so we need to force a copy into a NULL-terminated buffer. */
  10317. if (!multipart_text(p, "\0", 1, false)) {
  10318. return false;
  10319. }
  10320. buf = accumulate_getptr(p, &len);
  10321. myend = buf + len - 1; /* One for NULL. */
  10322. /* XXX: We are using strtol to parse integers, but this is wrong as even
  10323. * integers can be represented as 1e6 (for example), which strtol can't
  10324. * handle correctly.
  10325. *
  10326. * XXX: Also, we can't handle large integers properly because strto[u]ll
  10327. * isn't in C89.
  10328. *
  10329. * XXX: Also, we don't properly check floats for overflow, since strtof
  10330. * isn't in C89. */
  10331. switch (upb_fielddef_type(p->top->f)) {
  10332. case UPB_TYPE_ENUM:
  10333. case UPB_TYPE_INT32: {
  10334. long val = strtol(p->accumulated, &end, 0);
  10335. if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || end != myend)
  10336. goto err;
  10337. else
  10338. upb_sink_putint32(&p->top->sink, parser_getsel(p), val);
  10339. break;
  10340. }
  10341. case UPB_TYPE_INT64: {
  10342. long long val = strtol(p->accumulated, &end, 0);
  10343. if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || end != myend)
  10344. goto err;
  10345. else
  10346. upb_sink_putint64(&p->top->sink, parser_getsel(p), val);
  10347. break;
  10348. }
  10349. case UPB_TYPE_UINT32: {
  10350. unsigned long val = strtoul(p->accumulated, &end, 0);
  10351. if (val > UINT32_MAX || errno == ERANGE || end != myend)
  10352. goto err;
  10353. else
  10354. upb_sink_putuint32(&p->top->sink, parser_getsel(p), val);
  10355. break;
  10356. }
  10357. case UPB_TYPE_UINT64: {
  10358. unsigned long long val = strtoul(p->accumulated, &end, 0);
  10359. if (val > UINT64_MAX || errno == ERANGE || end != myend)
  10360. goto err;
  10361. else
  10362. upb_sink_putuint64(&p->top->sink, parser_getsel(p), val);
  10363. break;
  10364. }
  10365. case UPB_TYPE_DOUBLE: {
  10366. double val = strtod(p->accumulated, &end);
  10367. if (errno == ERANGE || end != myend)
  10368. goto err;
  10369. else
  10370. upb_sink_putdouble(&p->top->sink, parser_getsel(p), val);
  10371. break;
  10372. }
  10373. case UPB_TYPE_FLOAT: {
  10374. float val = strtod(p->accumulated, &end);
  10375. if (errno == ERANGE || end != myend)
  10376. goto err;
  10377. else
  10378. upb_sink_putfloat(&p->top->sink, parser_getsel(p), val);
  10379. break;
  10380. }
  10381. default:
  10382. UPB_ASSERT(false);
  10383. }
  10384. multipart_end(p);
  10385. return true;
  10386. err:
  10387. upb_status_seterrf(&p->status, "error parsing number: %s", buf);
  10388. upb_env_reporterror(p->env, &p->status);
  10389. multipart_end(p);
  10390. return false;
  10391. }
  10392. static bool parser_putbool(upb_json_parser *p, bool val) {
  10393. bool ok;
  10394. if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL) {
  10395. upb_status_seterrf(&p->status,
  10396. "Boolean value specified for non-bool field: %s",
  10397. upb_fielddef_name(p->top->f));
  10398. upb_env_reporterror(p->env, &p->status);
  10399. return false;
  10400. }
  10401. ok = upb_sink_putbool(&p->top->sink, parser_getsel(p), val);
  10402. UPB_ASSERT(ok);
  10403. return true;
  10404. }
  10405. static bool start_stringval(upb_json_parser *p) {
  10406. UPB_ASSERT(p->top->f);
  10407. if (upb_fielddef_isstring(p->top->f)) {
  10408. upb_jsonparser_frame *inner;
  10409. upb_selector_t sel;
  10410. if (!check_stack(p)) return false;
  10411. /* Start a new parser frame: parser frames correspond one-to-one with
  10412. * handler frames, and string events occur in a sub-frame. */
  10413. inner = p->top + 1;
  10414. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  10415. upb_sink_startstr(&p->top->sink, sel, 0, &inner->sink);
  10416. inner->m = p->top->m;
  10417. inner->f = p->top->f;
  10418. inner->name_table = NULL;
  10419. inner->is_map = false;
  10420. inner->is_mapentry = false;
  10421. p->top = inner;
  10422. if (upb_fielddef_type(p->top->f) == UPB_TYPE_STRING) {
  10423. /* For STRING fields we push data directly to the handlers as it is
  10424. * parsed. We don't do this yet for BYTES fields, because our base64
  10425. * decoder is not streaming.
  10426. *
  10427. * TODO(haberman): make base64 decoding streaming also. */
  10428. multipart_start(p, getsel_for_handlertype(p, UPB_HANDLER_STRING));
  10429. return true;
  10430. } else {
  10431. multipart_startaccum(p);
  10432. return true;
  10433. }
  10434. } else if (upb_fielddef_type(p->top->f) == UPB_TYPE_ENUM) {
  10435. /* No need to push a frame -- symbolic enum names in quotes remain in the
  10436. * current parser frame.
  10437. *
  10438. * Enum string values must accumulate so we can look up the value in a table
  10439. * once it is complete. */
  10440. multipart_startaccum(p);
  10441. return true;
  10442. } else {
  10443. upb_status_seterrf(&p->status,
  10444. "String specified for non-string/non-enum field: %s",
  10445. upb_fielddef_name(p->top->f));
  10446. upb_env_reporterror(p->env, &p->status);
  10447. return false;
  10448. }
  10449. }
  10450. static bool end_stringval(upb_json_parser *p) {
  10451. bool ok = true;
  10452. switch (upb_fielddef_type(p->top->f)) {
  10453. case UPB_TYPE_BYTES:
  10454. if (!base64_push(p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  10455. p->accumulated, p->accumulated_len)) {
  10456. return false;
  10457. }
  10458. /* Fall through. */
  10459. case UPB_TYPE_STRING: {
  10460. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  10461. p->top--;
  10462. upb_sink_endstr(&p->top->sink, sel);
  10463. break;
  10464. }
  10465. case UPB_TYPE_ENUM: {
  10466. /* Resolve enum symbolic name to integer value. */
  10467. const upb_enumdef *enumdef =
  10468. (const upb_enumdef*)upb_fielddef_subdef(p->top->f);
  10469. size_t len;
  10470. const char *buf = accumulate_getptr(p, &len);
  10471. int32_t int_val = 0;
  10472. ok = upb_enumdef_ntoi(enumdef, buf, len, &int_val);
  10473. if (ok) {
  10474. upb_selector_t sel = parser_getsel(p);
  10475. upb_sink_putint32(&p->top->sink, sel, int_val);
  10476. } else {
  10477. upb_status_seterrf(&p->status, "Enum value unknown: '%.*s'", len, buf);
  10478. upb_env_reporterror(p->env, &p->status);
  10479. }
  10480. break;
  10481. }
  10482. default:
  10483. UPB_ASSERT(false);
  10484. upb_status_seterrmsg(&p->status, "Internal error in JSON decoder");
  10485. upb_env_reporterror(p->env, &p->status);
  10486. ok = false;
  10487. break;
  10488. }
  10489. multipart_end(p);
  10490. return ok;
  10491. }
  10492. static void start_member(upb_json_parser *p) {
  10493. UPB_ASSERT(!p->top->f);
  10494. multipart_startaccum(p);
  10495. }
  10496. /* Helper: invoked during parse_mapentry() to emit the mapentry message's key
  10497. * field based on the current contents of the accumulate buffer. */
  10498. static bool parse_mapentry_key(upb_json_parser *p) {
  10499. size_t len;
  10500. const char *buf = accumulate_getptr(p, &len);
  10501. /* Emit the key field. We do a bit of ad-hoc parsing here because the
  10502. * parser state machine has already decided that this is a string field
  10503. * name, and we are reinterpreting it as some arbitrary key type. In
  10504. * particular, integer and bool keys are quoted, so we need to parse the
  10505. * quoted string contents here. */
  10506. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_KEY);
  10507. if (p->top->f == NULL) {
  10508. upb_status_seterrmsg(&p->status, "mapentry message has no key");
  10509. upb_env_reporterror(p->env, &p->status);
  10510. return false;
  10511. }
  10512. switch (upb_fielddef_type(p->top->f)) {
  10513. case UPB_TYPE_INT32:
  10514. case UPB_TYPE_INT64:
  10515. case UPB_TYPE_UINT32:
  10516. case UPB_TYPE_UINT64:
  10517. /* Invoke end_number. The accum buffer has the number's text already. */
  10518. if (!parse_number(p)) {
  10519. return false;
  10520. }
  10521. break;
  10522. case UPB_TYPE_BOOL:
  10523. if (len == 4 && !strncmp(buf, "true", 4)) {
  10524. if (!parser_putbool(p, true)) {
  10525. return false;
  10526. }
  10527. } else if (len == 5 && !strncmp(buf, "false", 5)) {
  10528. if (!parser_putbool(p, false)) {
  10529. return false;
  10530. }
  10531. } else {
  10532. upb_status_seterrmsg(&p->status,
  10533. "Map bool key not 'true' or 'false'");
  10534. upb_env_reporterror(p->env, &p->status);
  10535. return false;
  10536. }
  10537. multipart_end(p);
  10538. break;
  10539. case UPB_TYPE_STRING:
  10540. case UPB_TYPE_BYTES: {
  10541. upb_sink subsink;
  10542. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  10543. upb_sink_startstr(&p->top->sink, sel, len, &subsink);
  10544. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  10545. upb_sink_putstring(&subsink, sel, buf, len, NULL);
  10546. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  10547. upb_sink_endstr(&p->top->sink, sel);
  10548. multipart_end(p);
  10549. break;
  10550. }
  10551. default:
  10552. upb_status_seterrmsg(&p->status, "Invalid field type for map key");
  10553. upb_env_reporterror(p->env, &p->status);
  10554. return false;
  10555. }
  10556. return true;
  10557. }
  10558. /* Helper: emit one map entry (as a submessage in the map field sequence). This
  10559. * is invoked from end_membername(), at the end of the map entry's key string,
  10560. * with the map key in the accumulate buffer. It parses the key from that
  10561. * buffer, emits the handler calls to start the mapentry submessage (setting up
  10562. * its subframe in the process), and sets up state in the subframe so that the
  10563. * value parser (invoked next) will emit the mapentry's value field and then
  10564. * end the mapentry message. */
  10565. static bool handle_mapentry(upb_json_parser *p) {
  10566. const upb_fielddef *mapfield;
  10567. const upb_msgdef *mapentrymsg;
  10568. upb_jsonparser_frame *inner;
  10569. upb_selector_t sel;
  10570. /* Map entry: p->top->sink is the seq frame, so we need to start a frame
  10571. * for the mapentry itself, and then set |f| in that frame so that the map
  10572. * value field is parsed, and also set a flag to end the frame after the
  10573. * map-entry value is parsed. */
  10574. if (!check_stack(p)) return false;
  10575. mapfield = p->top->mapfield;
  10576. mapentrymsg = upb_fielddef_msgsubdef(mapfield);
  10577. inner = p->top + 1;
  10578. p->top->f = mapfield;
  10579. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  10580. upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
  10581. inner->m = mapentrymsg;
  10582. inner->name_table = NULL;
  10583. inner->mapfield = mapfield;
  10584. inner->is_map = false;
  10585. /* Don't set this to true *yet* -- we reuse parsing handlers below to push
  10586. * the key field value to the sink, and these handlers will pop the frame
  10587. * if they see is_mapentry (when invoked by the parser state machine, they
  10588. * would have just seen the map-entry value, not key). */
  10589. inner->is_mapentry = false;
  10590. p->top = inner;
  10591. /* send STARTMSG in submsg frame. */
  10592. upb_sink_startmsg(&p->top->sink);
  10593. parse_mapentry_key(p);
  10594. /* Set up the value field to receive the map-entry value. */
  10595. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_VALUE);
  10596. p->top->is_mapentry = true; /* set up to pop frame after value is parsed. */
  10597. p->top->mapfield = mapfield;
  10598. if (p->top->f == NULL) {
  10599. upb_status_seterrmsg(&p->status, "mapentry message has no value");
  10600. upb_env_reporterror(p->env, &p->status);
  10601. return false;
  10602. }
  10603. return true;
  10604. }
  10605. static bool end_membername(upb_json_parser *p) {
  10606. UPB_ASSERT(!p->top->f);
  10607. if (p->top->is_map) {
  10608. return handle_mapentry(p);
  10609. } else {
  10610. size_t len;
  10611. const char *buf = accumulate_getptr(p, &len);
  10612. upb_value v;
  10613. if (upb_strtable_lookup2(p->top->name_table, buf, len, &v)) {
  10614. p->top->f = upb_value_getconstptr(v);
  10615. multipart_end(p);
  10616. return true;
  10617. } else {
  10618. /* TODO(haberman): Ignore unknown fields if requested/configured to do
  10619. * so. */
  10620. upb_status_seterrf(&p->status, "No such field: %.*s\n", (int)len, buf);
  10621. upb_env_reporterror(p->env, &p->status);
  10622. return false;
  10623. }
  10624. }
  10625. }
  10626. static void end_member(upb_json_parser *p) {
  10627. /* If we just parsed a map-entry value, end that frame too. */
  10628. if (p->top->is_mapentry) {
  10629. upb_status s = UPB_STATUS_INIT;
  10630. upb_selector_t sel;
  10631. bool ok;
  10632. const upb_fielddef *mapfield;
  10633. UPB_ASSERT(p->top > p->stack);
  10634. /* send ENDMSG on submsg. */
  10635. upb_sink_endmsg(&p->top->sink, &s);
  10636. mapfield = p->top->mapfield;
  10637. /* send ENDSUBMSG in repeated-field-of-mapentries frame. */
  10638. p->top--;
  10639. ok = upb_handlers_getselector(mapfield, UPB_HANDLER_ENDSUBMSG, &sel);
  10640. UPB_ASSERT(ok);
  10641. upb_sink_endsubmsg(&p->top->sink, sel);
  10642. }
  10643. p->top->f = NULL;
  10644. }
  10645. static bool start_subobject(upb_json_parser *p) {
  10646. UPB_ASSERT(p->top->f);
  10647. if (upb_fielddef_ismap(p->top->f)) {
  10648. upb_jsonparser_frame *inner;
  10649. upb_selector_t sel;
  10650. /* Beginning of a map. Start a new parser frame in a repeated-field
  10651. * context. */
  10652. if (!check_stack(p)) return false;
  10653. inner = p->top + 1;
  10654. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  10655. upb_sink_startseq(&p->top->sink, sel, &inner->sink);
  10656. inner->m = upb_fielddef_msgsubdef(p->top->f);
  10657. inner->name_table = NULL;
  10658. inner->mapfield = p->top->f;
  10659. inner->f = NULL;
  10660. inner->is_map = true;
  10661. inner->is_mapentry = false;
  10662. p->top = inner;
  10663. return true;
  10664. } else if (upb_fielddef_issubmsg(p->top->f)) {
  10665. upb_jsonparser_frame *inner;
  10666. upb_selector_t sel;
  10667. /* Beginning of a subobject. Start a new parser frame in the submsg
  10668. * context. */
  10669. if (!check_stack(p)) return false;
  10670. inner = p->top + 1;
  10671. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  10672. upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
  10673. inner->m = upb_fielddef_msgsubdef(p->top->f);
  10674. set_name_table(p, inner);
  10675. inner->f = NULL;
  10676. inner->is_map = false;
  10677. inner->is_mapentry = false;
  10678. p->top = inner;
  10679. return true;
  10680. } else {
  10681. upb_status_seterrf(&p->status,
  10682. "Object specified for non-message/group field: %s",
  10683. upb_fielddef_name(p->top->f));
  10684. upb_env_reporterror(p->env, &p->status);
  10685. return false;
  10686. }
  10687. }
  10688. static void end_subobject(upb_json_parser *p) {
  10689. if (p->top->is_map) {
  10690. upb_selector_t sel;
  10691. p->top--;
  10692. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  10693. upb_sink_endseq(&p->top->sink, sel);
  10694. } else {
  10695. upb_selector_t sel;
  10696. p->top--;
  10697. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSUBMSG);
  10698. upb_sink_endsubmsg(&p->top->sink, sel);
  10699. }
  10700. }
  10701. static bool start_array(upb_json_parser *p) {
  10702. upb_jsonparser_frame *inner;
  10703. upb_selector_t sel;
  10704. UPB_ASSERT(p->top->f);
  10705. if (!upb_fielddef_isseq(p->top->f)) {
  10706. upb_status_seterrf(&p->status,
  10707. "Array specified for non-repeated field: %s",
  10708. upb_fielddef_name(p->top->f));
  10709. upb_env_reporterror(p->env, &p->status);
  10710. return false;
  10711. }
  10712. if (!check_stack(p)) return false;
  10713. inner = p->top + 1;
  10714. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  10715. upb_sink_startseq(&p->top->sink, sel, &inner->sink);
  10716. inner->m = p->top->m;
  10717. inner->name_table = NULL;
  10718. inner->f = p->top->f;
  10719. inner->is_map = false;
  10720. inner->is_mapentry = false;
  10721. p->top = inner;
  10722. return true;
  10723. }
  10724. static void end_array(upb_json_parser *p) {
  10725. upb_selector_t sel;
  10726. UPB_ASSERT(p->top > p->stack);
  10727. p->top--;
  10728. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  10729. upb_sink_endseq(&p->top->sink, sel);
  10730. }
  10731. static void start_object(upb_json_parser *p) {
  10732. if (!p->top->is_map) {
  10733. upb_sink_startmsg(&p->top->sink);
  10734. }
  10735. }
  10736. static void end_object(upb_json_parser *p) {
  10737. if (!p->top->is_map) {
  10738. upb_status status;
  10739. upb_status_clear(&status);
  10740. upb_sink_endmsg(&p->top->sink, &status);
  10741. if (!upb_ok(&status)) {
  10742. upb_env_reporterror(p->env, &status);
  10743. }
  10744. }
  10745. }
  10746. #define CHECK_RETURN_TOP(x) if (!(x)) goto error
  10747. /* The actual parser **********************************************************/
  10748. /* What follows is the Ragel parser itself. The language is specified in Ragel
  10749. * and the actions call our C functions above.
  10750. *
  10751. * Ragel has an extensive set of functionality, and we use only a small part of
  10752. * it. There are many action types but we only use a few:
  10753. *
  10754. * ">" -- transition into a machine
  10755. * "%" -- transition out of a machine
  10756. * "@" -- transition into a final state of a machine.
  10757. *
  10758. * "@" transitions are tricky because a machine can transition into a final
  10759. * state repeatedly. But in some cases we know this can't happen, for example
  10760. * a string which is delimited by a final '"' can only transition into its
  10761. * final state once, when the closing '"' is seen. */
  10762. #line 1244 "upb/json/parser.rl"
  10763. #line 1156 "upb/json/parser.c"
  10764. static const char _json_actions[] = {
  10765. 0, 1, 0, 1, 2, 1, 3, 1,
  10766. 5, 1, 6, 1, 7, 1, 8, 1,
  10767. 10, 1, 12, 1, 13, 1, 14, 1,
  10768. 15, 1, 16, 1, 17, 1, 21, 1,
  10769. 25, 1, 27, 2, 3, 8, 2, 4,
  10770. 5, 2, 6, 2, 2, 6, 8, 2,
  10771. 11, 9, 2, 13, 15, 2, 14, 15,
  10772. 2, 18, 1, 2, 19, 27, 2, 20,
  10773. 9, 2, 22, 27, 2, 23, 27, 2,
  10774. 24, 27, 2, 26, 27, 3, 14, 11,
  10775. 9
  10776. };
  10777. static const unsigned char _json_key_offsets[] = {
  10778. 0, 0, 4, 9, 14, 15, 19, 24,
  10779. 29, 34, 38, 42, 45, 48, 50, 54,
  10780. 58, 60, 62, 67, 69, 71, 80, 86,
  10781. 92, 98, 104, 106, 115, 116, 116, 116,
  10782. 121, 126, 131, 132, 133, 134, 135, 135,
  10783. 136, 137, 138, 138, 139, 140, 141, 141,
  10784. 146, 151, 152, 156, 161, 166, 171, 175,
  10785. 175, 178, 178, 178
  10786. };
  10787. static const char _json_trans_keys[] = {
  10788. 32, 123, 9, 13, 32, 34, 125, 9,
  10789. 13, 32, 34, 125, 9, 13, 34, 32,
  10790. 58, 9, 13, 32, 93, 125, 9, 13,
  10791. 32, 44, 125, 9, 13, 32, 44, 125,
  10792. 9, 13, 32, 34, 9, 13, 45, 48,
  10793. 49, 57, 48, 49, 57, 46, 69, 101,
  10794. 48, 57, 69, 101, 48, 57, 43, 45,
  10795. 48, 57, 48, 57, 48, 57, 46, 69,
  10796. 101, 48, 57, 34, 92, 34, 92, 34,
  10797. 47, 92, 98, 102, 110, 114, 116, 117,
  10798. 48, 57, 65, 70, 97, 102, 48, 57,
  10799. 65, 70, 97, 102, 48, 57, 65, 70,
  10800. 97, 102, 48, 57, 65, 70, 97, 102,
  10801. 34, 92, 34, 45, 91, 102, 110, 116,
  10802. 123, 48, 57, 34, 32, 93, 125, 9,
  10803. 13, 32, 44, 93, 9, 13, 32, 93,
  10804. 125, 9, 13, 97, 108, 115, 101, 117,
  10805. 108, 108, 114, 117, 101, 32, 34, 125,
  10806. 9, 13, 32, 34, 125, 9, 13, 34,
  10807. 32, 58, 9, 13, 32, 93, 125, 9,
  10808. 13, 32, 44, 125, 9, 13, 32, 44,
  10809. 125, 9, 13, 32, 34, 9, 13, 32,
  10810. 9, 13, 0
  10811. };
  10812. static const char _json_single_lengths[] = {
  10813. 0, 2, 3, 3, 1, 2, 3, 3,
  10814. 3, 2, 2, 1, 3, 0, 2, 2,
  10815. 0, 0, 3, 2, 2, 9, 0, 0,
  10816. 0, 0, 2, 7, 1, 0, 0, 3,
  10817. 3, 3, 1, 1, 1, 1, 0, 1,
  10818. 1, 1, 0, 1, 1, 1, 0, 3,
  10819. 3, 1, 2, 3, 3, 3, 2, 0,
  10820. 1, 0, 0, 0
  10821. };
  10822. static const char _json_range_lengths[] = {
  10823. 0, 1, 1, 1, 0, 1, 1, 1,
  10824. 1, 1, 1, 1, 0, 1, 1, 1,
  10825. 1, 1, 1, 0, 0, 0, 3, 3,
  10826. 3, 3, 0, 1, 0, 0, 0, 1,
  10827. 1, 1, 0, 0, 0, 0, 0, 0,
  10828. 0, 0, 0, 0, 0, 0, 0, 1,
  10829. 1, 0, 1, 1, 1, 1, 1, 0,
  10830. 1, 0, 0, 0
  10831. };
  10832. static const short _json_index_offsets[] = {
  10833. 0, 0, 4, 9, 14, 16, 20, 25,
  10834. 30, 35, 39, 43, 46, 50, 52, 56,
  10835. 60, 62, 64, 69, 72, 75, 85, 89,
  10836. 93, 97, 101, 104, 113, 115, 116, 117,
  10837. 122, 127, 132, 134, 136, 138, 140, 141,
  10838. 143, 145, 147, 148, 150, 152, 154, 155,
  10839. 160, 165, 167, 171, 176, 181, 186, 190,
  10840. 191, 194, 195, 196
  10841. };
  10842. static const char _json_indicies[] = {
  10843. 0, 2, 0, 1, 3, 4, 5, 3,
  10844. 1, 6, 7, 8, 6, 1, 9, 1,
  10845. 10, 11, 10, 1, 11, 1, 1, 11,
  10846. 12, 13, 14, 15, 13, 1, 16, 17,
  10847. 8, 16, 1, 17, 7, 17, 1, 18,
  10848. 19, 20, 1, 19, 20, 1, 22, 23,
  10849. 23, 21, 24, 1, 23, 23, 24, 21,
  10850. 25, 25, 26, 1, 26, 1, 26, 21,
  10851. 22, 23, 23, 20, 21, 28, 29, 27,
  10852. 31, 32, 30, 33, 33, 33, 33, 33,
  10853. 33, 33, 33, 34, 1, 35, 35, 35,
  10854. 1, 36, 36, 36, 1, 37, 37, 37,
  10855. 1, 38, 38, 38, 1, 40, 41, 39,
  10856. 42, 43, 44, 45, 46, 47, 48, 43,
  10857. 1, 49, 1, 50, 51, 53, 54, 1,
  10858. 53, 52, 55, 56, 54, 55, 1, 56,
  10859. 1, 1, 56, 52, 57, 1, 58, 1,
  10860. 59, 1, 60, 1, 61, 62, 1, 63,
  10861. 1, 64, 1, 65, 66, 1, 67, 1,
  10862. 68, 1, 69, 70, 71, 72, 70, 1,
  10863. 73, 74, 75, 73, 1, 76, 1, 77,
  10864. 78, 77, 1, 78, 1, 1, 78, 79,
  10865. 80, 81, 82, 80, 1, 83, 84, 75,
  10866. 83, 1, 84, 74, 84, 1, 85, 86,
  10867. 86, 1, 1, 1, 1, 0
  10868. };
  10869. static const char _json_trans_targs[] = {
  10870. 1, 0, 2, 3, 4, 56, 3, 4,
  10871. 56, 5, 5, 6, 7, 8, 9, 56,
  10872. 8, 9, 11, 12, 18, 57, 13, 15,
  10873. 14, 16, 17, 20, 58, 21, 20, 58,
  10874. 21, 19, 22, 23, 24, 25, 26, 20,
  10875. 58, 21, 28, 30, 31, 34, 39, 43,
  10876. 47, 29, 59, 59, 32, 31, 29, 32,
  10877. 33, 35, 36, 37, 38, 59, 40, 41,
  10878. 42, 59, 44, 45, 46, 59, 48, 49,
  10879. 55, 48, 49, 55, 50, 50, 51, 52,
  10880. 53, 54, 55, 53, 54, 59, 56
  10881. };
  10882. static const char _json_trans_actions[] = {
  10883. 0, 0, 0, 21, 77, 53, 0, 47,
  10884. 23, 17, 0, 0, 15, 19, 19, 50,
  10885. 0, 0, 0, 0, 0, 1, 0, 0,
  10886. 0, 0, 0, 3, 13, 0, 0, 35,
  10887. 5, 11, 0, 38, 7, 7, 7, 41,
  10888. 44, 9, 62, 56, 25, 0, 0, 0,
  10889. 31, 29, 33, 59, 15, 0, 27, 0,
  10890. 0, 0, 0, 0, 0, 68, 0, 0,
  10891. 0, 71, 0, 0, 0, 65, 21, 77,
  10892. 53, 0, 47, 23, 17, 0, 0, 15,
  10893. 19, 19, 50, 0, 0, 74, 0
  10894. };
  10895. static const int json_start = 1;
  10896. static const int json_en_number_machine = 10;
  10897. static const int json_en_string_machine = 19;
  10898. static const int json_en_value_machine = 27;
  10899. static const int json_en_main = 1;
  10900. #line 1247 "upb/json/parser.rl"
  10901. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  10902. const upb_bufhandle *handle) {
  10903. upb_json_parser *parser = closure;
  10904. /* Variables used by Ragel's generated code. */
  10905. int cs = parser->current_state;
  10906. int *stack = parser->parser_stack;
  10907. int top = parser->parser_top;
  10908. const char *p = buf;
  10909. const char *pe = buf + size;
  10910. parser->handle = handle;
  10911. UPB_UNUSED(hd);
  10912. UPB_UNUSED(handle);
  10913. capture_resume(parser, buf);
  10914. #line 1327 "upb/json/parser.c"
  10915. {
  10916. int _klen;
  10917. unsigned int _trans;
  10918. const char *_acts;
  10919. unsigned int _nacts;
  10920. const char *_keys;
  10921. if ( p == pe )
  10922. goto _test_eof;
  10923. if ( cs == 0 )
  10924. goto _out;
  10925. _resume:
  10926. _keys = _json_trans_keys + _json_key_offsets[cs];
  10927. _trans = _json_index_offsets[cs];
  10928. _klen = _json_single_lengths[cs];
  10929. if ( _klen > 0 ) {
  10930. const char *_lower = _keys;
  10931. const char *_mid;
  10932. const char *_upper = _keys + _klen - 1;
  10933. while (1) {
  10934. if ( _upper < _lower )
  10935. break;
  10936. _mid = _lower + ((_upper-_lower) >> 1);
  10937. if ( (*p) < *_mid )
  10938. _upper = _mid - 1;
  10939. else if ( (*p) > *_mid )
  10940. _lower = _mid + 1;
  10941. else {
  10942. _trans += (unsigned int)(_mid - _keys);
  10943. goto _match;
  10944. }
  10945. }
  10946. _keys += _klen;
  10947. _trans += _klen;
  10948. }
  10949. _klen = _json_range_lengths[cs];
  10950. if ( _klen > 0 ) {
  10951. const char *_lower = _keys;
  10952. const char *_mid;
  10953. const char *_upper = _keys + (_klen<<1) - 2;
  10954. while (1) {
  10955. if ( _upper < _lower )
  10956. break;
  10957. _mid = _lower + (((_upper-_lower) >> 1) & ~1);
  10958. if ( (*p) < _mid[0] )
  10959. _upper = _mid - 2;
  10960. else if ( (*p) > _mid[1] )
  10961. _lower = _mid + 2;
  10962. else {
  10963. _trans += (unsigned int)((_mid - _keys)>>1);
  10964. goto _match;
  10965. }
  10966. }
  10967. _trans += _klen;
  10968. }
  10969. _match:
  10970. _trans = _json_indicies[_trans];
  10971. cs = _json_trans_targs[_trans];
  10972. if ( _json_trans_actions[_trans] == 0 )
  10973. goto _again;
  10974. _acts = _json_actions + _json_trans_actions[_trans];
  10975. _nacts = (unsigned int) *_acts++;
  10976. while ( _nacts-- > 0 )
  10977. {
  10978. switch ( *_acts++ )
  10979. {
  10980. case 0:
  10981. #line 1159 "upb/json/parser.rl"
  10982. { p--; {cs = stack[--top]; goto _again;} }
  10983. break;
  10984. case 1:
  10985. #line 1160 "upb/json/parser.rl"
  10986. { p--; {stack[top++] = cs; cs = 10; goto _again;} }
  10987. break;
  10988. case 2:
  10989. #line 1164 "upb/json/parser.rl"
  10990. { start_text(parser, p); }
  10991. break;
  10992. case 3:
  10993. #line 1165 "upb/json/parser.rl"
  10994. { CHECK_RETURN_TOP(end_text(parser, p)); }
  10995. break;
  10996. case 4:
  10997. #line 1171 "upb/json/parser.rl"
  10998. { start_hex(parser); }
  10999. break;
  11000. case 5:
  11001. #line 1172 "upb/json/parser.rl"
  11002. { hexdigit(parser, p); }
  11003. break;
  11004. case 6:
  11005. #line 1173 "upb/json/parser.rl"
  11006. { CHECK_RETURN_TOP(end_hex(parser)); }
  11007. break;
  11008. case 7:
  11009. #line 1179 "upb/json/parser.rl"
  11010. { CHECK_RETURN_TOP(escape(parser, p)); }
  11011. break;
  11012. case 8:
  11013. #line 1185 "upb/json/parser.rl"
  11014. { p--; {cs = stack[--top]; goto _again;} }
  11015. break;
  11016. case 9:
  11017. #line 1188 "upb/json/parser.rl"
  11018. { {stack[top++] = cs; cs = 19; goto _again;} }
  11019. break;
  11020. case 10:
  11021. #line 1190 "upb/json/parser.rl"
  11022. { p--; {stack[top++] = cs; cs = 27; goto _again;} }
  11023. break;
  11024. case 11:
  11025. #line 1195 "upb/json/parser.rl"
  11026. { start_member(parser); }
  11027. break;
  11028. case 12:
  11029. #line 1196 "upb/json/parser.rl"
  11030. { CHECK_RETURN_TOP(end_membername(parser)); }
  11031. break;
  11032. case 13:
  11033. #line 1199 "upb/json/parser.rl"
  11034. { end_member(parser); }
  11035. break;
  11036. case 14:
  11037. #line 1205 "upb/json/parser.rl"
  11038. { start_object(parser); }
  11039. break;
  11040. case 15:
  11041. #line 1208 "upb/json/parser.rl"
  11042. { end_object(parser); }
  11043. break;
  11044. case 16:
  11045. #line 1214 "upb/json/parser.rl"
  11046. { CHECK_RETURN_TOP(start_array(parser)); }
  11047. break;
  11048. case 17:
  11049. #line 1218 "upb/json/parser.rl"
  11050. { end_array(parser); }
  11051. break;
  11052. case 18:
  11053. #line 1223 "upb/json/parser.rl"
  11054. { start_number(parser, p); }
  11055. break;
  11056. case 19:
  11057. #line 1224 "upb/json/parser.rl"
  11058. { CHECK_RETURN_TOP(end_number(parser, p)); }
  11059. break;
  11060. case 20:
  11061. #line 1226 "upb/json/parser.rl"
  11062. { CHECK_RETURN_TOP(start_stringval(parser)); }
  11063. break;
  11064. case 21:
  11065. #line 1227 "upb/json/parser.rl"
  11066. { CHECK_RETURN_TOP(end_stringval(parser)); }
  11067. break;
  11068. case 22:
  11069. #line 1229 "upb/json/parser.rl"
  11070. { CHECK_RETURN_TOP(parser_putbool(parser, true)); }
  11071. break;
  11072. case 23:
  11073. #line 1231 "upb/json/parser.rl"
  11074. { CHECK_RETURN_TOP(parser_putbool(parser, false)); }
  11075. break;
  11076. case 24:
  11077. #line 1233 "upb/json/parser.rl"
  11078. { /* null value */ }
  11079. break;
  11080. case 25:
  11081. #line 1235 "upb/json/parser.rl"
  11082. { CHECK_RETURN_TOP(start_subobject(parser)); }
  11083. break;
  11084. case 26:
  11085. #line 1236 "upb/json/parser.rl"
  11086. { end_subobject(parser); }
  11087. break;
  11088. case 27:
  11089. #line 1241 "upb/json/parser.rl"
  11090. { p--; {cs = stack[--top]; goto _again;} }
  11091. break;
  11092. #line 1513 "upb/json/parser.c"
  11093. }
  11094. }
  11095. _again:
  11096. if ( cs == 0 )
  11097. goto _out;
  11098. if ( ++p != pe )
  11099. goto _resume;
  11100. _test_eof: {}
  11101. _out: {}
  11102. }
  11103. #line 1268 "upb/json/parser.rl"
  11104. if (p != pe) {
  11105. upb_status_seterrf(&parser->status, "Parse error at '%.*s'\n", pe - p, p);
  11106. upb_env_reporterror(parser->env, &parser->status);
  11107. } else {
  11108. capture_suspend(parser, &p);
  11109. }
  11110. error:
  11111. /* Save parsing state back to parser. */
  11112. parser->current_state = cs;
  11113. parser->parser_top = top;
  11114. return p - buf;
  11115. }
  11116. bool end(void *closure, const void *hd) {
  11117. UPB_UNUSED(closure);
  11118. UPB_UNUSED(hd);
  11119. /* Prevent compile warning on unused static constants. */
  11120. UPB_UNUSED(json_start);
  11121. UPB_UNUSED(json_en_number_machine);
  11122. UPB_UNUSED(json_en_string_machine);
  11123. UPB_UNUSED(json_en_value_machine);
  11124. UPB_UNUSED(json_en_main);
  11125. return true;
  11126. }
  11127. static void json_parser_reset(upb_json_parser *p) {
  11128. int cs;
  11129. int top;
  11130. p->top = p->stack;
  11131. p->top->f = NULL;
  11132. p->top->is_map = false;
  11133. p->top->is_mapentry = false;
  11134. /* Emit Ragel initialization of the parser. */
  11135. #line 1567 "upb/json/parser.c"
  11136. {
  11137. cs = json_start;
  11138. top = 0;
  11139. }
  11140. #line 1308 "upb/json/parser.rl"
  11141. p->current_state = cs;
  11142. p->parser_top = top;
  11143. accumulate_clear(p);
  11144. p->multipart_state = MULTIPART_INACTIVE;
  11145. p->capture = NULL;
  11146. p->accumulated = NULL;
  11147. upb_status_clear(&p->status);
  11148. }
  11149. static void visit_json_parsermethod(const upb_refcounted *r,
  11150. upb_refcounted_visit *visit,
  11151. void *closure) {
  11152. const upb_json_parsermethod *method = (upb_json_parsermethod*)r;
  11153. visit(r, upb_msgdef_upcast2(method->msg), closure);
  11154. }
  11155. static void free_json_parsermethod(upb_refcounted *r) {
  11156. upb_json_parsermethod *method = (upb_json_parsermethod*)r;
  11157. upb_inttable_iter i;
  11158. upb_inttable_begin(&i, &method->name_tables);
  11159. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  11160. upb_value val = upb_inttable_iter_value(&i);
  11161. upb_strtable *t = upb_value_getptr(val);
  11162. upb_strtable_uninit(t);
  11163. upb_gfree(t);
  11164. }
  11165. upb_inttable_uninit(&method->name_tables);
  11166. upb_gfree(r);
  11167. }
  11168. static void add_jsonname_table(upb_json_parsermethod *m, const upb_msgdef* md) {
  11169. upb_msg_field_iter i;
  11170. upb_strtable *t;
  11171. /* It would be nice to stack-allocate this, but protobufs do not limit the
  11172. * length of fields to any reasonable limit. */
  11173. char *buf = NULL;
  11174. size_t len = 0;
  11175. if (upb_inttable_lookupptr(&m->name_tables, md, NULL)) {
  11176. return;
  11177. }
  11178. /* TODO(haberman): handle malloc failure. */
  11179. t = upb_gmalloc(sizeof(*t));
  11180. upb_strtable_init(t, UPB_CTYPE_CONSTPTR);
  11181. upb_inttable_insertptr(&m->name_tables, md, upb_value_ptr(t));
  11182. for(upb_msg_field_begin(&i, md);
  11183. !upb_msg_field_done(&i);
  11184. upb_msg_field_next(&i)) {
  11185. const upb_fielddef *f = upb_msg_iter_field(&i);
  11186. /* Add an entry for the JSON name. */
  11187. size_t field_len = upb_fielddef_getjsonname(f, buf, len);
  11188. if (field_len > len) {
  11189. size_t len2;
  11190. buf = upb_grealloc(buf, 0, field_len);
  11191. len = field_len;
  11192. len2 = upb_fielddef_getjsonname(f, buf, len);
  11193. UPB_ASSERT(len == len2);
  11194. }
  11195. upb_strtable_insert(t, buf, upb_value_constptr(f));
  11196. if (strcmp(buf, upb_fielddef_name(f)) != 0) {
  11197. /* Since the JSON name is different from the regular field name, add an
  11198. * entry for the raw name (compliant proto3 JSON parsers must accept
  11199. * both). */
  11200. upb_strtable_insert(t, upb_fielddef_name(f), upb_value_constptr(f));
  11201. }
  11202. if (upb_fielddef_issubmsg(f)) {
  11203. add_jsonname_table(m, upb_fielddef_msgsubdef(f));
  11204. }
  11205. }
  11206. upb_gfree(buf);
  11207. }
  11208. /* Public API *****************************************************************/
  11209. upb_json_parser *upb_json_parser_create(upb_env *env,
  11210. const upb_json_parsermethod *method,
  11211. upb_sink *output) {
  11212. #ifndef NDEBUG
  11213. const size_t size_before = upb_env_bytesallocated(env);
  11214. #endif
  11215. upb_json_parser *p = upb_env_malloc(env, sizeof(upb_json_parser));
  11216. if (!p) return false;
  11217. p->env = env;
  11218. p->method = method;
  11219. p->limit = p->stack + UPB_JSON_MAX_DEPTH;
  11220. p->accumulate_buf = NULL;
  11221. p->accumulate_buf_size = 0;
  11222. upb_bytessink_reset(&p->input_, &method->input_handler_, p);
  11223. json_parser_reset(p);
  11224. upb_sink_reset(&p->top->sink, output->handlers, output->closure);
  11225. p->top->m = upb_handlers_msgdef(output->handlers);
  11226. set_name_table(p, p->top);
  11227. /* If this fails, uncomment and increase the value in parser.h. */
  11228. /* fprintf(stderr, "%zd\n", upb_env_bytesallocated(env) - size_before); */
  11229. UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(env) - size_before <=
  11230. UPB_JSON_PARSER_SIZE);
  11231. return p;
  11232. }
  11233. upb_bytessink *upb_json_parser_input(upb_json_parser *p) {
  11234. return &p->input_;
  11235. }
  11236. upb_json_parsermethod *upb_json_parsermethod_new(const upb_msgdef* md,
  11237. const void* owner) {
  11238. static const struct upb_refcounted_vtbl vtbl = {visit_json_parsermethod,
  11239. free_json_parsermethod};
  11240. upb_json_parsermethod *ret = upb_gmalloc(sizeof(*ret));
  11241. upb_refcounted_init(upb_json_parsermethod_upcast_mutable(ret), &vtbl, owner);
  11242. ret->msg = md;
  11243. upb_ref2(md, ret);
  11244. upb_byteshandler_init(&ret->input_handler_);
  11245. upb_byteshandler_setstring(&ret->input_handler_, parse, ret);
  11246. upb_byteshandler_setendstr(&ret->input_handler_, end, ret);
  11247. upb_inttable_init(&ret->name_tables, UPB_CTYPE_PTR);
  11248. add_jsonname_table(ret, md);
  11249. return ret;
  11250. }
  11251. const upb_byteshandler *upb_json_parsermethod_inputhandler(
  11252. const upb_json_parsermethod *m) {
  11253. return &m->input_handler_;
  11254. }
  11255. /*
  11256. ** This currently uses snprintf() to format primitives, and could be optimized
  11257. ** further.
  11258. */
  11259. #include <string.h>
  11260. #include <stdint.h>
  11261. struct upb_json_printer {
  11262. upb_sink input_;
  11263. /* BytesSink closure. */
  11264. void *subc_;
  11265. upb_bytessink *output_;
  11266. /* We track the depth so that we know when to emit startstr/endstr on the
  11267. * output. */
  11268. int depth_;
  11269. /* Have we emitted the first element? This state is necessary to emit commas
  11270. * without leaving a trailing comma in arrays/maps. We keep this state per
  11271. * frame depth.
  11272. *
  11273. * Why max_depth * 2? UPB_MAX_HANDLER_DEPTH counts depth as nested messages.
  11274. * We count frames (contexts in which we separate elements by commas) as both
  11275. * repeated fields and messages (maps), and the worst case is a
  11276. * message->repeated field->submessage->repeated field->... nesting. */
  11277. bool first_elem_[UPB_MAX_HANDLER_DEPTH * 2];
  11278. };
  11279. /* StringPiece; a pointer plus a length. */
  11280. typedef struct {
  11281. char *ptr;
  11282. size_t len;
  11283. } strpc;
  11284. void freestrpc(void *ptr) {
  11285. strpc *pc = ptr;
  11286. upb_gfree(pc->ptr);
  11287. upb_gfree(pc);
  11288. }
  11289. /* Convert fielddef name to JSON name and return as a string piece. */
  11290. strpc *newstrpc(upb_handlers *h, const upb_fielddef *f,
  11291. bool preserve_fieldnames) {
  11292. /* TODO(haberman): handle malloc failure. */
  11293. strpc *ret = upb_gmalloc(sizeof(*ret));
  11294. if (preserve_fieldnames) {
  11295. ret->ptr = upb_gstrdup(upb_fielddef_name(f));
  11296. ret->len = strlen(ret->ptr);
  11297. } else {
  11298. size_t len;
  11299. ret->len = upb_fielddef_getjsonname(f, NULL, 0);
  11300. ret->ptr = upb_gmalloc(ret->len);
  11301. len = upb_fielddef_getjsonname(f, ret->ptr, ret->len);
  11302. UPB_ASSERT(len == ret->len);
  11303. ret->len--; /* NULL */
  11304. }
  11305. upb_handlers_addcleanup(h, ret, freestrpc);
  11306. return ret;
  11307. }
  11308. /* ------------ JSON string printing: values, maps, arrays ------------------ */
  11309. static void print_data(
  11310. upb_json_printer *p, const char *buf, unsigned int len) {
  11311. /* TODO: Will need to change if we support pushback from the sink. */
  11312. size_t n = upb_bytessink_putbuf(p->output_, p->subc_, buf, len, NULL);
  11313. UPB_ASSERT(n == len);
  11314. }
  11315. static void print_comma(upb_json_printer *p) {
  11316. if (!p->first_elem_[p->depth_]) {
  11317. print_data(p, ",", 1);
  11318. }
  11319. p->first_elem_[p->depth_] = false;
  11320. }
  11321. /* Helpers that print properly formatted elements to the JSON output stream. */
  11322. /* Used for escaping control chars in strings. */
  11323. static const char kControlCharLimit = 0x20;
  11324. UPB_INLINE bool is_json_escaped(char c) {
  11325. /* See RFC 4627. */
  11326. unsigned char uc = (unsigned char)c;
  11327. return uc < kControlCharLimit || uc == '"' || uc == '\\';
  11328. }
  11329. UPB_INLINE const char* json_nice_escape(char c) {
  11330. switch (c) {
  11331. case '"': return "\\\"";
  11332. case '\\': return "\\\\";
  11333. case '\b': return "\\b";
  11334. case '\f': return "\\f";
  11335. case '\n': return "\\n";
  11336. case '\r': return "\\r";
  11337. case '\t': return "\\t";
  11338. default: return NULL;
  11339. }
  11340. }
  11341. /* Write a properly escaped string chunk. The surrounding quotes are *not*
  11342. * printed; this is so that the caller has the option of emitting the string
  11343. * content in chunks. */
  11344. static void putstring(upb_json_printer *p, const char *buf, unsigned int len) {
  11345. const char* unescaped_run = NULL;
  11346. unsigned int i;
  11347. for (i = 0; i < len; i++) {
  11348. char c = buf[i];
  11349. /* Handle escaping. */
  11350. if (is_json_escaped(c)) {
  11351. /* Use a "nice" escape, like \n, if one exists for this character. */
  11352. const char* escape = json_nice_escape(c);
  11353. /* If we don't have a specific 'nice' escape code, use a \uXXXX-style
  11354. * escape. */
  11355. char escape_buf[8];
  11356. if (!escape) {
  11357. unsigned char byte = (unsigned char)c;
  11358. _upb_snprintf(escape_buf, sizeof(escape_buf), "\\u%04x", (int)byte);
  11359. escape = escape_buf;
  11360. }
  11361. /* N.B. that we assume that the input encoding is equal to the output
  11362. * encoding (both UTF-8 for now), so for chars >= 0x20 and != \, ", we
  11363. * can simply pass the bytes through. */
  11364. /* If there's a current run of unescaped chars, print that run first. */
  11365. if (unescaped_run) {
  11366. print_data(p, unescaped_run, &buf[i] - unescaped_run);
  11367. unescaped_run = NULL;
  11368. }
  11369. /* Then print the escape code. */
  11370. print_data(p, escape, strlen(escape));
  11371. } else {
  11372. /* Add to the current unescaped run of characters. */
  11373. if (unescaped_run == NULL) {
  11374. unescaped_run = &buf[i];
  11375. }
  11376. }
  11377. }
  11378. /* If the string ended in a run of unescaped characters, print that last run. */
  11379. if (unescaped_run) {
  11380. print_data(p, unescaped_run, &buf[len] - unescaped_run);
  11381. }
  11382. }
  11383. #define CHKLENGTH(x) if (!(x)) return -1;
  11384. /* Helpers that format floating point values according to our custom formats.
  11385. * Right now we use %.8g and %.17g for float/double, respectively, to match
  11386. * proto2::util::JsonFormat's defaults. May want to change this later. */
  11387. static size_t fmt_double(double val, char* buf, size_t length) {
  11388. size_t n = _upb_snprintf(buf, length, "%.17g", val);
  11389. CHKLENGTH(n > 0 && n < length);
  11390. return n;
  11391. }
  11392. static size_t fmt_float(float val, char* buf, size_t length) {
  11393. size_t n = _upb_snprintf(buf, length, "%.8g", val);
  11394. CHKLENGTH(n > 0 && n < length);
  11395. return n;
  11396. }
  11397. static size_t fmt_bool(bool val, char* buf, size_t length) {
  11398. size_t n = _upb_snprintf(buf, length, "%s", (val ? "true" : "false"));
  11399. CHKLENGTH(n > 0 && n < length);
  11400. return n;
  11401. }
  11402. static size_t fmt_int64(long val, char* buf, size_t length) {
  11403. size_t n = _upb_snprintf(buf, length, "%ld", val);
  11404. CHKLENGTH(n > 0 && n < length);
  11405. return n;
  11406. }
  11407. static size_t fmt_uint64(unsigned long long val, char* buf, size_t length) {
  11408. size_t n = _upb_snprintf(buf, length, "%llu", val);
  11409. CHKLENGTH(n > 0 && n < length);
  11410. return n;
  11411. }
  11412. /* Print a map key given a field name. Called by scalar field handlers and by
  11413. * startseq for repeated fields. */
  11414. static bool putkey(void *closure, const void *handler_data) {
  11415. upb_json_printer *p = closure;
  11416. const strpc *key = handler_data;
  11417. print_comma(p);
  11418. print_data(p, "\"", 1);
  11419. putstring(p, key->ptr, key->len);
  11420. print_data(p, "\":", 2);
  11421. return true;
  11422. }
  11423. #define CHKFMT(val) if ((val) == (size_t)-1) return false;
  11424. #define CHK(val) if (!(val)) return false;
  11425. #define TYPE_HANDLERS(type, fmt_func) \
  11426. static bool put##type(void *closure, const void *handler_data, type val) { \
  11427. upb_json_printer *p = closure; \
  11428. char data[64]; \
  11429. size_t length = fmt_func(val, data, sizeof(data)); \
  11430. UPB_UNUSED(handler_data); \
  11431. CHKFMT(length); \
  11432. print_data(p, data, length); \
  11433. return true; \
  11434. } \
  11435. static bool scalar_##type(void *closure, const void *handler_data, \
  11436. type val) { \
  11437. CHK(putkey(closure, handler_data)); \
  11438. CHK(put##type(closure, handler_data, val)); \
  11439. return true; \
  11440. } \
  11441. static bool repeated_##type(void *closure, const void *handler_data, \
  11442. type val) { \
  11443. upb_json_printer *p = closure; \
  11444. print_comma(p); \
  11445. CHK(put##type(closure, handler_data, val)); \
  11446. return true; \
  11447. }
  11448. #define TYPE_HANDLERS_MAPKEY(type, fmt_func) \
  11449. static bool putmapkey_##type(void *closure, const void *handler_data, \
  11450. type val) { \
  11451. upb_json_printer *p = closure; \
  11452. print_data(p, "\"", 1); \
  11453. CHK(put##type(closure, handler_data, val)); \
  11454. print_data(p, "\":", 2); \
  11455. return true; \
  11456. }
  11457. TYPE_HANDLERS(double, fmt_double)
  11458. TYPE_HANDLERS(float, fmt_float)
  11459. TYPE_HANDLERS(bool, fmt_bool)
  11460. TYPE_HANDLERS(int32_t, fmt_int64)
  11461. TYPE_HANDLERS(uint32_t, fmt_int64)
  11462. TYPE_HANDLERS(int64_t, fmt_int64)
  11463. TYPE_HANDLERS(uint64_t, fmt_uint64)
  11464. /* double and float are not allowed to be map keys. */
  11465. TYPE_HANDLERS_MAPKEY(bool, fmt_bool)
  11466. TYPE_HANDLERS_MAPKEY(int32_t, fmt_int64)
  11467. TYPE_HANDLERS_MAPKEY(uint32_t, fmt_int64)
  11468. TYPE_HANDLERS_MAPKEY(int64_t, fmt_int64)
  11469. TYPE_HANDLERS_MAPKEY(uint64_t, fmt_uint64)
  11470. #undef TYPE_HANDLERS
  11471. #undef TYPE_HANDLERS_MAPKEY
  11472. typedef struct {
  11473. void *keyname;
  11474. const upb_enumdef *enumdef;
  11475. } EnumHandlerData;
  11476. static bool scalar_enum(void *closure, const void *handler_data,
  11477. int32_t val) {
  11478. const EnumHandlerData *hd = handler_data;
  11479. upb_json_printer *p = closure;
  11480. const char *symbolic_name;
  11481. CHK(putkey(closure, hd->keyname));
  11482. symbolic_name = upb_enumdef_iton(hd->enumdef, val);
  11483. if (symbolic_name) {
  11484. print_data(p, "\"", 1);
  11485. putstring(p, symbolic_name, strlen(symbolic_name));
  11486. print_data(p, "\"", 1);
  11487. } else {
  11488. putint32_t(closure, NULL, val);
  11489. }
  11490. return true;
  11491. }
  11492. static void print_enum_symbolic_name(upb_json_printer *p,
  11493. const upb_enumdef *def,
  11494. int32_t val) {
  11495. const char *symbolic_name = upb_enumdef_iton(def, val);
  11496. if (symbolic_name) {
  11497. print_data(p, "\"", 1);
  11498. putstring(p, symbolic_name, strlen(symbolic_name));
  11499. print_data(p, "\"", 1);
  11500. } else {
  11501. putint32_t(p, NULL, val);
  11502. }
  11503. }
  11504. static bool repeated_enum(void *closure, const void *handler_data,
  11505. int32_t val) {
  11506. const EnumHandlerData *hd = handler_data;
  11507. upb_json_printer *p = closure;
  11508. print_comma(p);
  11509. print_enum_symbolic_name(p, hd->enumdef, val);
  11510. return true;
  11511. }
  11512. static bool mapvalue_enum(void *closure, const void *handler_data,
  11513. int32_t val) {
  11514. const EnumHandlerData *hd = handler_data;
  11515. upb_json_printer *p = closure;
  11516. print_enum_symbolic_name(p, hd->enumdef, val);
  11517. return true;
  11518. }
  11519. static void *scalar_startsubmsg(void *closure, const void *handler_data) {
  11520. return putkey(closure, handler_data) ? closure : UPB_BREAK;
  11521. }
  11522. static void *repeated_startsubmsg(void *closure, const void *handler_data) {
  11523. upb_json_printer *p = closure;
  11524. UPB_UNUSED(handler_data);
  11525. print_comma(p);
  11526. return closure;
  11527. }
  11528. static void start_frame(upb_json_printer *p) {
  11529. p->depth_++;
  11530. p->first_elem_[p->depth_] = true;
  11531. print_data(p, "{", 1);
  11532. }
  11533. static void end_frame(upb_json_printer *p) {
  11534. print_data(p, "}", 1);
  11535. p->depth_--;
  11536. }
  11537. static bool printer_startmsg(void *closure, const void *handler_data) {
  11538. upb_json_printer *p = closure;
  11539. UPB_UNUSED(handler_data);
  11540. if (p->depth_ == 0) {
  11541. upb_bytessink_start(p->output_, 0, &p->subc_);
  11542. }
  11543. start_frame(p);
  11544. return true;
  11545. }
  11546. static bool printer_endmsg(void *closure, const void *handler_data, upb_status *s) {
  11547. upb_json_printer *p = closure;
  11548. UPB_UNUSED(handler_data);
  11549. UPB_UNUSED(s);
  11550. end_frame(p);
  11551. if (p->depth_ == 0) {
  11552. upb_bytessink_end(p->output_);
  11553. }
  11554. return true;
  11555. }
  11556. static void *startseq(void *closure, const void *handler_data) {
  11557. upb_json_printer *p = closure;
  11558. CHK(putkey(closure, handler_data));
  11559. p->depth_++;
  11560. p->first_elem_[p->depth_] = true;
  11561. print_data(p, "[", 1);
  11562. return closure;
  11563. }
  11564. static bool endseq(void *closure, const void *handler_data) {
  11565. upb_json_printer *p = closure;
  11566. UPB_UNUSED(handler_data);
  11567. print_data(p, "]", 1);
  11568. p->depth_--;
  11569. return true;
  11570. }
  11571. static void *startmap(void *closure, const void *handler_data) {
  11572. upb_json_printer *p = closure;
  11573. CHK(putkey(closure, handler_data));
  11574. p->depth_++;
  11575. p->first_elem_[p->depth_] = true;
  11576. print_data(p, "{", 1);
  11577. return closure;
  11578. }
  11579. static bool endmap(void *closure, const void *handler_data) {
  11580. upb_json_printer *p = closure;
  11581. UPB_UNUSED(handler_data);
  11582. print_data(p, "}", 1);
  11583. p->depth_--;
  11584. return true;
  11585. }
  11586. static size_t putstr(void *closure, const void *handler_data, const char *str,
  11587. size_t len, const upb_bufhandle *handle) {
  11588. upb_json_printer *p = closure;
  11589. UPB_UNUSED(handler_data);
  11590. UPB_UNUSED(handle);
  11591. putstring(p, str, len);
  11592. return len;
  11593. }
  11594. /* This has to Base64 encode the bytes, because JSON has no "bytes" type. */
  11595. static size_t putbytes(void *closure, const void *handler_data, const char *str,
  11596. size_t len, const upb_bufhandle *handle) {
  11597. upb_json_printer *p = closure;
  11598. /* This is the regular base64, not the "web-safe" version. */
  11599. static const char base64[] =
  11600. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  11601. /* Base64-encode. */
  11602. char data[16000];
  11603. const char *limit = data + sizeof(data);
  11604. const unsigned char *from = (const unsigned char*)str;
  11605. char *to = data;
  11606. size_t remaining = len;
  11607. size_t bytes;
  11608. UPB_UNUSED(handler_data);
  11609. UPB_UNUSED(handle);
  11610. while (remaining > 2) {
  11611. /* TODO(haberman): handle encoded lengths > sizeof(data) */
  11612. UPB_ASSERT((limit - to) >= 4);
  11613. to[0] = base64[from[0] >> 2];
  11614. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  11615. to[2] = base64[((from[1] & 0xf) << 2) | (from[2] >> 6)];
  11616. to[3] = base64[from[2] & 0x3f];
  11617. remaining -= 3;
  11618. to += 4;
  11619. from += 3;
  11620. }
  11621. switch (remaining) {
  11622. case 2:
  11623. to[0] = base64[from[0] >> 2];
  11624. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  11625. to[2] = base64[(from[1] & 0xf) << 2];
  11626. to[3] = '=';
  11627. to += 4;
  11628. from += 2;
  11629. break;
  11630. case 1:
  11631. to[0] = base64[from[0] >> 2];
  11632. to[1] = base64[((from[0] & 0x3) << 4)];
  11633. to[2] = '=';
  11634. to[3] = '=';
  11635. to += 4;
  11636. from += 1;
  11637. break;
  11638. }
  11639. bytes = to - data;
  11640. print_data(p, "\"", 1);
  11641. putstring(p, data, bytes);
  11642. print_data(p, "\"", 1);
  11643. return len;
  11644. }
  11645. static void *scalar_startstr(void *closure, const void *handler_data,
  11646. size_t size_hint) {
  11647. upb_json_printer *p = closure;
  11648. UPB_UNUSED(handler_data);
  11649. UPB_UNUSED(size_hint);
  11650. CHK(putkey(closure, handler_data));
  11651. print_data(p, "\"", 1);
  11652. return p;
  11653. }
  11654. static size_t scalar_str(void *closure, const void *handler_data,
  11655. const char *str, size_t len,
  11656. const upb_bufhandle *handle) {
  11657. CHK(putstr(closure, handler_data, str, len, handle));
  11658. return len;
  11659. }
  11660. static bool scalar_endstr(void *closure, const void *handler_data) {
  11661. upb_json_printer *p = closure;
  11662. UPB_UNUSED(handler_data);
  11663. print_data(p, "\"", 1);
  11664. return true;
  11665. }
  11666. static void *repeated_startstr(void *closure, const void *handler_data,
  11667. size_t size_hint) {
  11668. upb_json_printer *p = closure;
  11669. UPB_UNUSED(handler_data);
  11670. UPB_UNUSED(size_hint);
  11671. print_comma(p);
  11672. print_data(p, "\"", 1);
  11673. return p;
  11674. }
  11675. static size_t repeated_str(void *closure, const void *handler_data,
  11676. const char *str, size_t len,
  11677. const upb_bufhandle *handle) {
  11678. CHK(putstr(closure, handler_data, str, len, handle));
  11679. return len;
  11680. }
  11681. static bool repeated_endstr(void *closure, const void *handler_data) {
  11682. upb_json_printer *p = closure;
  11683. UPB_UNUSED(handler_data);
  11684. print_data(p, "\"", 1);
  11685. return true;
  11686. }
  11687. static void *mapkeyval_startstr(void *closure, const void *handler_data,
  11688. size_t size_hint) {
  11689. upb_json_printer *p = closure;
  11690. UPB_UNUSED(handler_data);
  11691. UPB_UNUSED(size_hint);
  11692. print_data(p, "\"", 1);
  11693. return p;
  11694. }
  11695. static size_t mapkey_str(void *closure, const void *handler_data,
  11696. const char *str, size_t len,
  11697. const upb_bufhandle *handle) {
  11698. CHK(putstr(closure, handler_data, str, len, handle));
  11699. return len;
  11700. }
  11701. static bool mapkey_endstr(void *closure, const void *handler_data) {
  11702. upb_json_printer *p = closure;
  11703. UPB_UNUSED(handler_data);
  11704. print_data(p, "\":", 2);
  11705. return true;
  11706. }
  11707. static bool mapvalue_endstr(void *closure, const void *handler_data) {
  11708. upb_json_printer *p = closure;
  11709. UPB_UNUSED(handler_data);
  11710. print_data(p, "\"", 1);
  11711. return true;
  11712. }
  11713. static size_t scalar_bytes(void *closure, const void *handler_data,
  11714. const char *str, size_t len,
  11715. const upb_bufhandle *handle) {
  11716. CHK(putkey(closure, handler_data));
  11717. CHK(putbytes(closure, handler_data, str, len, handle));
  11718. return len;
  11719. }
  11720. static size_t repeated_bytes(void *closure, const void *handler_data,
  11721. const char *str, size_t len,
  11722. const upb_bufhandle *handle) {
  11723. upb_json_printer *p = closure;
  11724. print_comma(p);
  11725. CHK(putbytes(closure, handler_data, str, len, handle));
  11726. return len;
  11727. }
  11728. static size_t mapkey_bytes(void *closure, const void *handler_data,
  11729. const char *str, size_t len,
  11730. const upb_bufhandle *handle) {
  11731. upb_json_printer *p = closure;
  11732. CHK(putbytes(closure, handler_data, str, len, handle));
  11733. print_data(p, ":", 1);
  11734. return len;
  11735. }
  11736. static void set_enum_hd(upb_handlers *h,
  11737. const upb_fielddef *f,
  11738. bool preserve_fieldnames,
  11739. upb_handlerattr *attr) {
  11740. EnumHandlerData *hd = upb_gmalloc(sizeof(EnumHandlerData));
  11741. hd->enumdef = (const upb_enumdef *)upb_fielddef_subdef(f);
  11742. hd->keyname = newstrpc(h, f, preserve_fieldnames);
  11743. upb_handlers_addcleanup(h, hd, upb_gfree);
  11744. upb_handlerattr_sethandlerdata(attr, hd);
  11745. }
  11746. /* Set up handlers for a mapentry submessage (i.e., an individual key/value pair
  11747. * in a map).
  11748. *
  11749. * TODO: Handle missing key, missing value, out-of-order key/value, or repeated
  11750. * key or value cases properly. The right way to do this is to allocate a
  11751. * temporary structure at the start of a mapentry submessage, store key and
  11752. * value data in it as key and value handlers are called, and then print the
  11753. * key/value pair once at the end of the submessage. If we don't do this, we
  11754. * should at least detect the case and throw an error. However, so far all of
  11755. * our sources that emit mapentry messages do so canonically (with one key
  11756. * field, and then one value field), so this is not a pressing concern at the
  11757. * moment. */
  11758. void printer_sethandlers_mapentry(const void *closure, bool preserve_fieldnames,
  11759. upb_handlers *h) {
  11760. const upb_msgdef *md = upb_handlers_msgdef(h);
  11761. /* A mapentry message is printed simply as '"key": value'. Rather than
  11762. * special-case key and value for every type below, we just handle both
  11763. * fields explicitly here. */
  11764. const upb_fielddef* key_field = upb_msgdef_itof(md, UPB_MAPENTRY_KEY);
  11765. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_MAPENTRY_VALUE);
  11766. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  11767. UPB_UNUSED(closure);
  11768. switch (upb_fielddef_type(key_field)) {
  11769. case UPB_TYPE_INT32:
  11770. upb_handlers_setint32(h, key_field, putmapkey_int32_t, &empty_attr);
  11771. break;
  11772. case UPB_TYPE_INT64:
  11773. upb_handlers_setint64(h, key_field, putmapkey_int64_t, &empty_attr);
  11774. break;
  11775. case UPB_TYPE_UINT32:
  11776. upb_handlers_setuint32(h, key_field, putmapkey_uint32_t, &empty_attr);
  11777. break;
  11778. case UPB_TYPE_UINT64:
  11779. upb_handlers_setuint64(h, key_field, putmapkey_uint64_t, &empty_attr);
  11780. break;
  11781. case UPB_TYPE_BOOL:
  11782. upb_handlers_setbool(h, key_field, putmapkey_bool, &empty_attr);
  11783. break;
  11784. case UPB_TYPE_STRING:
  11785. upb_handlers_setstartstr(h, key_field, mapkeyval_startstr, &empty_attr);
  11786. upb_handlers_setstring(h, key_field, mapkey_str, &empty_attr);
  11787. upb_handlers_setendstr(h, key_field, mapkey_endstr, &empty_attr);
  11788. break;
  11789. case UPB_TYPE_BYTES:
  11790. upb_handlers_setstring(h, key_field, mapkey_bytes, &empty_attr);
  11791. break;
  11792. default:
  11793. UPB_ASSERT(false);
  11794. break;
  11795. }
  11796. switch (upb_fielddef_type(value_field)) {
  11797. case UPB_TYPE_INT32:
  11798. upb_handlers_setint32(h, value_field, putint32_t, &empty_attr);
  11799. break;
  11800. case UPB_TYPE_INT64:
  11801. upb_handlers_setint64(h, value_field, putint64_t, &empty_attr);
  11802. break;
  11803. case UPB_TYPE_UINT32:
  11804. upb_handlers_setuint32(h, value_field, putuint32_t, &empty_attr);
  11805. break;
  11806. case UPB_TYPE_UINT64:
  11807. upb_handlers_setuint64(h, value_field, putuint64_t, &empty_attr);
  11808. break;
  11809. case UPB_TYPE_BOOL:
  11810. upb_handlers_setbool(h, value_field, putbool, &empty_attr);
  11811. break;
  11812. case UPB_TYPE_FLOAT:
  11813. upb_handlers_setfloat(h, value_field, putfloat, &empty_attr);
  11814. break;
  11815. case UPB_TYPE_DOUBLE:
  11816. upb_handlers_setdouble(h, value_field, putdouble, &empty_attr);
  11817. break;
  11818. case UPB_TYPE_STRING:
  11819. upb_handlers_setstartstr(h, value_field, mapkeyval_startstr, &empty_attr);
  11820. upb_handlers_setstring(h, value_field, putstr, &empty_attr);
  11821. upb_handlers_setendstr(h, value_field, mapvalue_endstr, &empty_attr);
  11822. break;
  11823. case UPB_TYPE_BYTES:
  11824. upb_handlers_setstring(h, value_field, putbytes, &empty_attr);
  11825. break;
  11826. case UPB_TYPE_ENUM: {
  11827. upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
  11828. set_enum_hd(h, value_field, preserve_fieldnames, &enum_attr);
  11829. upb_handlers_setint32(h, value_field, mapvalue_enum, &enum_attr);
  11830. upb_handlerattr_uninit(&enum_attr);
  11831. break;
  11832. }
  11833. case UPB_TYPE_MESSAGE:
  11834. /* No handler necessary -- the submsg handlers will print the message
  11835. * as appropriate. */
  11836. break;
  11837. }
  11838. upb_handlerattr_uninit(&empty_attr);
  11839. }
  11840. void printer_sethandlers(const void *closure, upb_handlers *h) {
  11841. const upb_msgdef *md = upb_handlers_msgdef(h);
  11842. bool is_mapentry = upb_msgdef_mapentry(md);
  11843. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  11844. upb_msg_field_iter i;
  11845. const bool *preserve_fieldnames_ptr = closure;
  11846. const bool preserve_fieldnames = *preserve_fieldnames_ptr;
  11847. if (is_mapentry) {
  11848. /* mapentry messages are sufficiently different that we handle them
  11849. * separately. */
  11850. printer_sethandlers_mapentry(closure, preserve_fieldnames, h);
  11851. return;
  11852. }
  11853. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  11854. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  11855. #define TYPE(type, name, ctype) \
  11856. case type: \
  11857. if (upb_fielddef_isseq(f)) { \
  11858. upb_handlers_set##name(h, f, repeated_##ctype, &empty_attr); \
  11859. } else { \
  11860. upb_handlers_set##name(h, f, scalar_##ctype, &name_attr); \
  11861. } \
  11862. break;
  11863. upb_msg_field_begin(&i, md);
  11864. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  11865. const upb_fielddef *f = upb_msg_iter_field(&i);
  11866. upb_handlerattr name_attr = UPB_HANDLERATTR_INITIALIZER;
  11867. upb_handlerattr_sethandlerdata(&name_attr,
  11868. newstrpc(h, f, preserve_fieldnames));
  11869. if (upb_fielddef_ismap(f)) {
  11870. upb_handlers_setstartseq(h, f, startmap, &name_attr);
  11871. upb_handlers_setendseq(h, f, endmap, &name_attr);
  11872. } else if (upb_fielddef_isseq(f)) {
  11873. upb_handlers_setstartseq(h, f, startseq, &name_attr);
  11874. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  11875. }
  11876. switch (upb_fielddef_type(f)) {
  11877. TYPE(UPB_TYPE_FLOAT, float, float);
  11878. TYPE(UPB_TYPE_DOUBLE, double, double);
  11879. TYPE(UPB_TYPE_BOOL, bool, bool);
  11880. TYPE(UPB_TYPE_INT32, int32, int32_t);
  11881. TYPE(UPB_TYPE_UINT32, uint32, uint32_t);
  11882. TYPE(UPB_TYPE_INT64, int64, int64_t);
  11883. TYPE(UPB_TYPE_UINT64, uint64, uint64_t);
  11884. case UPB_TYPE_ENUM: {
  11885. /* For now, we always emit symbolic names for enums. We may want an
  11886. * option later to control this behavior, but we will wait for a real
  11887. * need first. */
  11888. upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
  11889. set_enum_hd(h, f, preserve_fieldnames, &enum_attr);
  11890. if (upb_fielddef_isseq(f)) {
  11891. upb_handlers_setint32(h, f, repeated_enum, &enum_attr);
  11892. } else {
  11893. upb_handlers_setint32(h, f, scalar_enum, &enum_attr);
  11894. }
  11895. upb_handlerattr_uninit(&enum_attr);
  11896. break;
  11897. }
  11898. case UPB_TYPE_STRING:
  11899. if (upb_fielddef_isseq(f)) {
  11900. upb_handlers_setstartstr(h, f, repeated_startstr, &empty_attr);
  11901. upb_handlers_setstring(h, f, repeated_str, &empty_attr);
  11902. upb_handlers_setendstr(h, f, repeated_endstr, &empty_attr);
  11903. } else {
  11904. upb_handlers_setstartstr(h, f, scalar_startstr, &name_attr);
  11905. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  11906. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  11907. }
  11908. break;
  11909. case UPB_TYPE_BYTES:
  11910. /* XXX: this doesn't support strings that span buffers yet. The base64
  11911. * encoder will need to be made resumable for this to work properly. */
  11912. if (upb_fielddef_isseq(f)) {
  11913. upb_handlers_setstring(h, f, repeated_bytes, &empty_attr);
  11914. } else {
  11915. upb_handlers_setstring(h, f, scalar_bytes, &name_attr);
  11916. }
  11917. break;
  11918. case UPB_TYPE_MESSAGE:
  11919. if (upb_fielddef_isseq(f)) {
  11920. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &name_attr);
  11921. } else {
  11922. upb_handlers_setstartsubmsg(h, f, scalar_startsubmsg, &name_attr);
  11923. }
  11924. break;
  11925. }
  11926. upb_handlerattr_uninit(&name_attr);
  11927. }
  11928. upb_handlerattr_uninit(&empty_attr);
  11929. #undef TYPE
  11930. }
  11931. static void json_printer_reset(upb_json_printer *p) {
  11932. p->depth_ = 0;
  11933. }
  11934. /* Public API *****************************************************************/
  11935. upb_json_printer *upb_json_printer_create(upb_env *e, const upb_handlers *h,
  11936. upb_bytessink *output) {
  11937. #ifndef NDEBUG
  11938. size_t size_before = upb_env_bytesallocated(e);
  11939. #endif
  11940. upb_json_printer *p = upb_env_malloc(e, sizeof(upb_json_printer));
  11941. if (!p) return NULL;
  11942. p->output_ = output;
  11943. json_printer_reset(p);
  11944. upb_sink_reset(&p->input_, h, p);
  11945. /* If this fails, increase the value in printer.h. */
  11946. UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(e) - size_before <=
  11947. UPB_JSON_PRINTER_SIZE);
  11948. return p;
  11949. }
  11950. upb_sink *upb_json_printer_input(upb_json_printer *p) {
  11951. return &p->input_;
  11952. }
  11953. const upb_handlers *upb_json_printer_newhandlers(const upb_msgdef *md,
  11954. bool preserve_fieldnames,
  11955. const void *owner) {
  11956. return upb_handlers_newfrozen(
  11957. md, owner, printer_sethandlers, &preserve_fieldnames);
  11958. }