upb.c 413 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330
  1. // Amalgamated source file
  2. #include "upb.h"
  3. #include <ctype.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. typedef struct {
  7. size_t len;
  8. char str[1]; /* Null-terminated string data follows. */
  9. } str_t;
  10. static str_t *newstr(const char *data, size_t len) {
  11. str_t *ret = malloc(sizeof(*ret) + len);
  12. if (!ret) return NULL;
  13. ret->len = len;
  14. memcpy(ret->str, data, len);
  15. ret->str[len] = '\0';
  16. return ret;
  17. }
  18. static void freestr(str_t *s) { free(s); }
  19. /* isalpha() etc. from <ctype.h> are locale-dependent, which we don't want. */
  20. static bool upb_isbetween(char c, char low, char high) {
  21. return c >= low && c <= high;
  22. }
  23. static bool upb_isletter(char c) {
  24. return upb_isbetween(c, 'A', 'Z') || upb_isbetween(c, 'a', 'z') || c == '_';
  25. }
  26. static bool upb_isalphanum(char c) {
  27. return upb_isletter(c) || upb_isbetween(c, '0', '9');
  28. }
  29. static bool upb_isident(const char *str, size_t len, bool full, upb_status *s) {
  30. bool start = true;
  31. size_t i;
  32. for (i = 0; i < len; i++) {
  33. char c = str[i];
  34. if (c == '.') {
  35. if (start || !full) {
  36. upb_status_seterrf(s, "invalid name: unexpected '.' (%s)", str);
  37. return false;
  38. }
  39. start = true;
  40. } else if (start) {
  41. if (!upb_isletter(c)) {
  42. upb_status_seterrf(
  43. s, "invalid name: path components must start with a letter (%s)",
  44. str);
  45. return false;
  46. }
  47. start = false;
  48. } else {
  49. if (!upb_isalphanum(c)) {
  50. upb_status_seterrf(s, "invalid name: non-alphanumeric character (%s)",
  51. str);
  52. return false;
  53. }
  54. }
  55. }
  56. return !start;
  57. }
  58. /* upb_def ********************************************************************/
  59. upb_deftype_t upb_def_type(const upb_def *d) { return d->type; }
  60. const char *upb_def_fullname(const upb_def *d) { return d->fullname; }
  61. bool upb_def_setfullname(upb_def *def, const char *fullname, upb_status *s) {
  62. assert(!upb_def_isfrozen(def));
  63. if (!upb_isident(fullname, strlen(fullname), true, s)) return false;
  64. free((void*)def->fullname);
  65. def->fullname = upb_strdup(fullname);
  66. return true;
  67. }
  68. upb_def *upb_def_dup(const upb_def *def, const void *o) {
  69. switch (def->type) {
  70. case UPB_DEF_MSG:
  71. return upb_msgdef_upcast_mutable(
  72. upb_msgdef_dup(upb_downcast_msgdef(def), o));
  73. case UPB_DEF_FIELD:
  74. return upb_fielddef_upcast_mutable(
  75. upb_fielddef_dup(upb_downcast_fielddef(def), o));
  76. case UPB_DEF_ENUM:
  77. return upb_enumdef_upcast_mutable(
  78. upb_enumdef_dup(upb_downcast_enumdef(def), o));
  79. default: assert(false); return NULL;
  80. }
  81. }
  82. static bool upb_def_init(upb_def *def, upb_deftype_t type,
  83. const struct upb_refcounted_vtbl *vtbl,
  84. const void *owner) {
  85. if (!upb_refcounted_init(upb_def_upcast_mutable(def), vtbl, owner)) return false;
  86. def->type = type;
  87. def->fullname = NULL;
  88. def->came_from_user = false;
  89. return true;
  90. }
  91. static void upb_def_uninit(upb_def *def) {
  92. free((void*)def->fullname);
  93. }
  94. static const char *msgdef_name(const upb_msgdef *m) {
  95. const char *name = upb_def_fullname(upb_msgdef_upcast(m));
  96. return name ? name : "(anonymous)";
  97. }
  98. static bool upb_validate_field(upb_fielddef *f, upb_status *s) {
  99. if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  100. upb_status_seterrmsg(s, "fielddef must have name and number set");
  101. return false;
  102. }
  103. if (!f->type_is_set_) {
  104. upb_status_seterrmsg(s, "fielddef type was not initialized");
  105. return false;
  106. }
  107. if (upb_fielddef_lazy(f) &&
  108. upb_fielddef_descriptortype(f) != UPB_DESCRIPTOR_TYPE_MESSAGE) {
  109. upb_status_seterrmsg(s,
  110. "only length-delimited submessage fields may be lazy");
  111. return false;
  112. }
  113. if (upb_fielddef_hassubdef(f)) {
  114. const upb_def *subdef;
  115. if (f->subdef_is_symbolic) {
  116. upb_status_seterrf(s, "field '%s.%s' has not been resolved",
  117. msgdef_name(f->msg.def), upb_fielddef_name(f));
  118. return false;
  119. }
  120. subdef = upb_fielddef_subdef(f);
  121. if (subdef == NULL) {
  122. upb_status_seterrf(s, "field %s.%s is missing required subdef",
  123. msgdef_name(f->msg.def), upb_fielddef_name(f));
  124. return false;
  125. }
  126. if (!upb_def_isfrozen(subdef) && !subdef->came_from_user) {
  127. upb_status_seterrf(s,
  128. "subdef of field %s.%s is not frozen or being frozen",
  129. msgdef_name(f->msg.def), upb_fielddef_name(f));
  130. return false;
  131. }
  132. }
  133. if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  134. bool has_default_name = upb_fielddef_enumhasdefaultstr(f);
  135. bool has_default_number = upb_fielddef_enumhasdefaultint32(f);
  136. /* Previously verified by upb_validate_enumdef(). */
  137. assert(upb_enumdef_numvals(upb_fielddef_enumsubdef(f)) > 0);
  138. /* We've already validated that we have an associated enumdef and that it
  139. * has at least one member, so at least one of these should be true.
  140. * Because if the user didn't set anything, we'll pick up the enum's
  141. * default, but if the user *did* set something we should at least pick up
  142. * the one they set (int32 or string). */
  143. assert(has_default_name || has_default_number);
  144. if (!has_default_name) {
  145. upb_status_seterrf(s,
  146. "enum default for field %s.%s (%d) is not in the enum",
  147. msgdef_name(f->msg.def), upb_fielddef_name(f),
  148. upb_fielddef_defaultint32(f));
  149. return false;
  150. }
  151. if (!has_default_number) {
  152. upb_status_seterrf(s,
  153. "enum default for field %s.%s (%s) is not in the enum",
  154. msgdef_name(f->msg.def), upb_fielddef_name(f),
  155. upb_fielddef_defaultstr(f, NULL));
  156. return false;
  157. }
  158. /* Lift the effective numeric default into the field's default slot, in case
  159. * we were only getting it "by reference" from the enumdef. */
  160. upb_fielddef_setdefaultint32(f, upb_fielddef_defaultint32(f));
  161. }
  162. /* Ensure that MapEntry submessages only appear as repeated fields, not
  163. * optional/required (singular) fields. */
  164. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  165. upb_fielddef_msgsubdef(f) != NULL) {
  166. const upb_msgdef *subdef = upb_fielddef_msgsubdef(f);
  167. if (upb_msgdef_mapentry(subdef) && !upb_fielddef_isseq(f)) {
  168. upb_status_seterrf(s,
  169. "Field %s refers to mapentry message but is not "
  170. "a repeated field",
  171. upb_fielddef_name(f) ? upb_fielddef_name(f) :
  172. "(unnamed)");
  173. return false;
  174. }
  175. }
  176. return true;
  177. }
  178. static bool upb_validate_enumdef(const upb_enumdef *e, upb_status *s) {
  179. if (upb_enumdef_numvals(e) == 0) {
  180. upb_status_seterrf(s, "enum %s has no members (must have at least one)",
  181. upb_enumdef_fullname(e));
  182. return false;
  183. }
  184. return true;
  185. }
  186. /* All submessage fields are lower than all other fields.
  187. * Secondly, fields are increasing in order. */
  188. uint32_t field_rank(const upb_fielddef *f) {
  189. uint32_t ret = upb_fielddef_number(f);
  190. const uint32_t high_bit = 1 << 30;
  191. assert(ret < high_bit);
  192. if (!upb_fielddef_issubmsg(f))
  193. ret |= high_bit;
  194. return ret;
  195. }
  196. int cmp_fields(const void *p1, const void *p2) {
  197. const upb_fielddef *f1 = *(upb_fielddef*const*)p1;
  198. const upb_fielddef *f2 = *(upb_fielddef*const*)p2;
  199. return field_rank(f1) - field_rank(f2);
  200. }
  201. static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
  202. /* Sort fields. upb internally relies on UPB_TYPE_MESSAGE fields having the
  203. * lowest indexes, but we do not publicly guarantee this. */
  204. upb_msg_field_iter j;
  205. int i;
  206. uint32_t selector;
  207. int n = upb_msgdef_numfields(m);
  208. upb_fielddef **fields = malloc(n * sizeof(*fields));
  209. if (!fields) return false;
  210. m->submsg_field_count = 0;
  211. for(i = 0, upb_msg_field_begin(&j, m);
  212. !upb_msg_field_done(&j);
  213. upb_msg_field_next(&j), i++) {
  214. upb_fielddef *f = upb_msg_iter_field(&j);
  215. assert(f->msg.def == m);
  216. if (!upb_validate_field(f, s)) {
  217. free(fields);
  218. return false;
  219. }
  220. if (upb_fielddef_issubmsg(f)) {
  221. m->submsg_field_count++;
  222. }
  223. fields[i] = f;
  224. }
  225. qsort(fields, n, sizeof(*fields), cmp_fields);
  226. selector = UPB_STATIC_SELECTOR_COUNT + m->submsg_field_count;
  227. for (i = 0; i < n; i++) {
  228. upb_fielddef *f = fields[i];
  229. f->index_ = i;
  230. f->selector_base = selector + upb_handlers_selectorbaseoffset(f);
  231. selector += upb_handlers_selectorcount(f);
  232. }
  233. m->selector_count = selector;
  234. #ifndef NDEBUG
  235. {
  236. /* Verify that all selectors for the message are distinct. */
  237. #define TRY(type) \
  238. if (upb_handlers_getselector(f, type, &sel)) upb_inttable_insert(&t, sel, v);
  239. upb_inttable t;
  240. upb_value v;
  241. upb_selector_t sel;
  242. upb_inttable_init(&t, UPB_CTYPE_BOOL);
  243. v = upb_value_bool(true);
  244. upb_inttable_insert(&t, UPB_STARTMSG_SELECTOR, v);
  245. upb_inttable_insert(&t, UPB_ENDMSG_SELECTOR, v);
  246. for(upb_msg_field_begin(&j, m);
  247. !upb_msg_field_done(&j);
  248. upb_msg_field_next(&j)) {
  249. upb_fielddef *f = upb_msg_iter_field(&j);
  250. /* These calls will assert-fail in upb_table if the value already
  251. * exists. */
  252. TRY(UPB_HANDLER_INT32);
  253. TRY(UPB_HANDLER_INT64)
  254. TRY(UPB_HANDLER_UINT32)
  255. TRY(UPB_HANDLER_UINT64)
  256. TRY(UPB_HANDLER_FLOAT)
  257. TRY(UPB_HANDLER_DOUBLE)
  258. TRY(UPB_HANDLER_BOOL)
  259. TRY(UPB_HANDLER_STARTSTR)
  260. TRY(UPB_HANDLER_STRING)
  261. TRY(UPB_HANDLER_ENDSTR)
  262. TRY(UPB_HANDLER_STARTSUBMSG)
  263. TRY(UPB_HANDLER_ENDSUBMSG)
  264. TRY(UPB_HANDLER_STARTSEQ)
  265. TRY(UPB_HANDLER_ENDSEQ)
  266. }
  267. upb_inttable_uninit(&t);
  268. }
  269. #undef TRY
  270. #endif
  271. free(fields);
  272. return true;
  273. }
  274. bool upb_def_freeze(upb_def *const* defs, int n, upb_status *s) {
  275. int i;
  276. int maxdepth;
  277. bool ret;
  278. upb_status_clear(s);
  279. /* First perform validation, in two passes so we can check that we have a
  280. * transitive closure without needing to search. */
  281. for (i = 0; i < n; i++) {
  282. upb_def *def = defs[i];
  283. if (upb_def_isfrozen(def)) {
  284. /* Could relax this requirement if it's annoying. */
  285. upb_status_seterrmsg(s, "def is already frozen");
  286. goto err;
  287. } else if (def->type == UPB_DEF_FIELD) {
  288. upb_status_seterrmsg(s, "standalone fielddefs can not be frozen");
  289. goto err;
  290. } else if (def->type == UPB_DEF_ENUM) {
  291. if (!upb_validate_enumdef(upb_dyncast_enumdef(def), s)) {
  292. goto err;
  293. }
  294. } else {
  295. /* Set now to detect transitive closure in the second pass. */
  296. def->came_from_user = true;
  297. }
  298. }
  299. /* Second pass of validation. Also assign selector bases and indexes, and
  300. * compact tables. */
  301. for (i = 0; i < n; i++) {
  302. upb_msgdef *m = upb_dyncast_msgdef_mutable(defs[i]);
  303. upb_enumdef *e = upb_dyncast_enumdef_mutable(defs[i]);
  304. if (m) {
  305. upb_inttable_compact(&m->itof);
  306. if (!assign_msg_indices(m, s)) {
  307. goto err;
  308. }
  309. } else if (e) {
  310. upb_inttable_compact(&e->iton);
  311. }
  312. }
  313. /* Def graph contains FieldDefs between each MessageDef, so double the
  314. * limit. */
  315. maxdepth = UPB_MAX_MESSAGE_DEPTH * 2;
  316. /* Validation all passed; freeze the defs. */
  317. ret = upb_refcounted_freeze((upb_refcounted * const *)defs, n, s, maxdepth);
  318. assert(!(s && ret != upb_ok(s)));
  319. return ret;
  320. err:
  321. for (i = 0; i < n; i++) {
  322. defs[i]->came_from_user = false;
  323. }
  324. assert(!(s && upb_ok(s)));
  325. return false;
  326. }
  327. /* upb_enumdef ****************************************************************/
  328. static void upb_enumdef_free(upb_refcounted *r) {
  329. upb_enumdef *e = (upb_enumdef*)r;
  330. upb_inttable_iter i;
  331. upb_inttable_begin(&i, &e->iton);
  332. for( ; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  333. /* To clean up the upb_strdup() from upb_enumdef_addval(). */
  334. free(upb_value_getcstr(upb_inttable_iter_value(&i)));
  335. }
  336. upb_strtable_uninit(&e->ntoi);
  337. upb_inttable_uninit(&e->iton);
  338. upb_def_uninit(upb_enumdef_upcast_mutable(e));
  339. free(e);
  340. }
  341. upb_enumdef *upb_enumdef_new(const void *owner) {
  342. static const struct upb_refcounted_vtbl vtbl = {NULL, &upb_enumdef_free};
  343. upb_enumdef *e = malloc(sizeof(*e));
  344. if (!e) return NULL;
  345. if (!upb_def_init(upb_enumdef_upcast_mutable(e), UPB_DEF_ENUM, &vtbl, owner))
  346. goto err2;
  347. if (!upb_strtable_init(&e->ntoi, UPB_CTYPE_INT32)) goto err2;
  348. if (!upb_inttable_init(&e->iton, UPB_CTYPE_CSTR)) goto err1;
  349. return e;
  350. err1:
  351. upb_strtable_uninit(&e->ntoi);
  352. err2:
  353. free(e);
  354. return NULL;
  355. }
  356. upb_enumdef *upb_enumdef_dup(const upb_enumdef *e, const void *owner) {
  357. upb_enum_iter i;
  358. upb_enumdef *new_e = upb_enumdef_new(owner);
  359. if (!new_e) return NULL;
  360. for(upb_enum_begin(&i, e); !upb_enum_done(&i); upb_enum_next(&i)) {
  361. bool success = upb_enumdef_addval(
  362. new_e, upb_enum_iter_name(&i),upb_enum_iter_number(&i), NULL);
  363. if (!success) {
  364. upb_enumdef_unref(new_e, owner);
  365. return NULL;
  366. }
  367. }
  368. return new_e;
  369. }
  370. bool upb_enumdef_freeze(upb_enumdef *e, upb_status *status) {
  371. upb_def *d = upb_enumdef_upcast_mutable(e);
  372. return upb_def_freeze(&d, 1, status);
  373. }
  374. const char *upb_enumdef_fullname(const upb_enumdef *e) {
  375. return upb_def_fullname(upb_enumdef_upcast(e));
  376. }
  377. bool upb_enumdef_setfullname(upb_enumdef *e, const char *fullname,
  378. upb_status *s) {
  379. return upb_def_setfullname(upb_enumdef_upcast_mutable(e), fullname, s);
  380. }
  381. bool upb_enumdef_addval(upb_enumdef *e, const char *name, int32_t num,
  382. upb_status *status) {
  383. if (!upb_isident(name, strlen(name), false, status)) {
  384. return false;
  385. }
  386. if (upb_enumdef_ntoiz(e, name, NULL)) {
  387. upb_status_seterrf(status, "name '%s' is already defined", name);
  388. return false;
  389. }
  390. if (!upb_strtable_insert(&e->ntoi, name, upb_value_int32(num))) {
  391. upb_status_seterrmsg(status, "out of memory");
  392. return false;
  393. }
  394. if (!upb_inttable_lookup(&e->iton, num, NULL) &&
  395. !upb_inttable_insert(&e->iton, num, upb_value_cstr(upb_strdup(name)))) {
  396. upb_status_seterrmsg(status, "out of memory");
  397. upb_strtable_remove(&e->ntoi, name, NULL);
  398. return false;
  399. }
  400. if (upb_enumdef_numvals(e) == 1) {
  401. bool ok = upb_enumdef_setdefault(e, num, NULL);
  402. UPB_ASSERT_VAR(ok, ok);
  403. }
  404. return true;
  405. }
  406. int32_t upb_enumdef_default(const upb_enumdef *e) {
  407. assert(upb_enumdef_iton(e, e->defaultval));
  408. return e->defaultval;
  409. }
  410. bool upb_enumdef_setdefault(upb_enumdef *e, int32_t val, upb_status *s) {
  411. assert(!upb_enumdef_isfrozen(e));
  412. if (!upb_enumdef_iton(e, val)) {
  413. upb_status_seterrf(s, "number '%d' is not in the enum.", val);
  414. return false;
  415. }
  416. e->defaultval = val;
  417. return true;
  418. }
  419. int upb_enumdef_numvals(const upb_enumdef *e) {
  420. return upb_strtable_count(&e->ntoi);
  421. }
  422. void upb_enum_begin(upb_enum_iter *i, const upb_enumdef *e) {
  423. /* We iterate over the ntoi table, to account for duplicate numbers. */
  424. upb_strtable_begin(i, &e->ntoi);
  425. }
  426. void upb_enum_next(upb_enum_iter *iter) { upb_strtable_next(iter); }
  427. bool upb_enum_done(upb_enum_iter *iter) { return upb_strtable_done(iter); }
  428. bool upb_enumdef_ntoi(const upb_enumdef *def, const char *name,
  429. size_t len, int32_t *num) {
  430. upb_value v;
  431. if (!upb_strtable_lookup2(&def->ntoi, name, len, &v)) {
  432. return false;
  433. }
  434. if (num) *num = upb_value_getint32(v);
  435. return true;
  436. }
  437. const char *upb_enumdef_iton(const upb_enumdef *def, int32_t num) {
  438. upb_value v;
  439. return upb_inttable_lookup32(&def->iton, num, &v) ?
  440. upb_value_getcstr(v) : NULL;
  441. }
  442. const char *upb_enum_iter_name(upb_enum_iter *iter) {
  443. return upb_strtable_iter_key(iter);
  444. }
  445. int32_t upb_enum_iter_number(upb_enum_iter *iter) {
  446. return upb_value_getint32(upb_strtable_iter_value(iter));
  447. }
  448. /* upb_fielddef ***************************************************************/
  449. static void upb_fielddef_init_default(upb_fielddef *f);
  450. static void upb_fielddef_uninit_default(upb_fielddef *f) {
  451. if (f->type_is_set_ && f->default_is_string && f->defaultval.bytes)
  452. freestr(f->defaultval.bytes);
  453. }
  454. const char *upb_fielddef_fullname(const upb_fielddef *e) {
  455. return upb_def_fullname(upb_fielddef_upcast(e));
  456. }
  457. static void visitfield(const upb_refcounted *r, upb_refcounted_visit *visit,
  458. void *closure) {
  459. const upb_fielddef *f = (const upb_fielddef*)r;
  460. if (upb_fielddef_containingtype(f)) {
  461. visit(r, upb_msgdef_upcast2(upb_fielddef_containingtype(f)), closure);
  462. }
  463. if (upb_fielddef_containingoneof(f)) {
  464. visit(r, upb_oneofdef_upcast2(upb_fielddef_containingoneof(f)), closure);
  465. }
  466. if (upb_fielddef_subdef(f)) {
  467. visit(r, upb_def_upcast(upb_fielddef_subdef(f)), closure);
  468. }
  469. }
  470. static void freefield(upb_refcounted *r) {
  471. upb_fielddef *f = (upb_fielddef*)r;
  472. upb_fielddef_uninit_default(f);
  473. if (f->subdef_is_symbolic)
  474. free(f->sub.name);
  475. upb_def_uninit(upb_fielddef_upcast_mutable(f));
  476. free(f);
  477. }
  478. static const char *enumdefaultstr(const upb_fielddef *f) {
  479. const upb_enumdef *e;
  480. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  481. e = upb_fielddef_enumsubdef(f);
  482. if (f->default_is_string && f->defaultval.bytes) {
  483. /* Default was explicitly set as a string. */
  484. str_t *s = f->defaultval.bytes;
  485. return s->str;
  486. } else if (e) {
  487. if (!f->default_is_string) {
  488. /* Default was explicitly set as an integer; look it up in enumdef. */
  489. const char *name = upb_enumdef_iton(e, f->defaultval.sint);
  490. if (name) {
  491. return name;
  492. }
  493. } else {
  494. /* Default is completely unset; pull enumdef default. */
  495. if (upb_enumdef_numvals(e) > 0) {
  496. const char *name = upb_enumdef_iton(e, upb_enumdef_default(e));
  497. assert(name);
  498. return name;
  499. }
  500. }
  501. }
  502. return NULL;
  503. }
  504. static bool enumdefaultint32(const upb_fielddef *f, int32_t *val) {
  505. const upb_enumdef *e;
  506. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  507. e = upb_fielddef_enumsubdef(f);
  508. if (!f->default_is_string) {
  509. /* Default was explicitly set as an integer. */
  510. *val = f->defaultval.sint;
  511. return true;
  512. } else if (e) {
  513. if (f->defaultval.bytes) {
  514. /* Default was explicitly set as a str; try to lookup corresponding int. */
  515. str_t *s = f->defaultval.bytes;
  516. if (upb_enumdef_ntoiz(e, s->str, val)) {
  517. return true;
  518. }
  519. } else {
  520. /* Default is unset; try to pull in enumdef default. */
  521. if (upb_enumdef_numvals(e) > 0) {
  522. *val = upb_enumdef_default(e);
  523. return true;
  524. }
  525. }
  526. }
  527. return false;
  528. }
  529. upb_fielddef *upb_fielddef_new(const void *o) {
  530. static const struct upb_refcounted_vtbl vtbl = {visitfield, freefield};
  531. upb_fielddef *f = malloc(sizeof(*f));
  532. if (!f) return NULL;
  533. if (!upb_def_init(upb_fielddef_upcast_mutable(f), UPB_DEF_FIELD, &vtbl, o)) {
  534. free(f);
  535. return NULL;
  536. }
  537. f->msg.def = NULL;
  538. f->sub.def = NULL;
  539. f->oneof = NULL;
  540. f->subdef_is_symbolic = false;
  541. f->msg_is_symbolic = false;
  542. f->label_ = UPB_LABEL_OPTIONAL;
  543. f->type_ = UPB_TYPE_INT32;
  544. f->number_ = 0;
  545. f->type_is_set_ = false;
  546. f->tagdelim = false;
  547. f->is_extension_ = false;
  548. f->lazy_ = false;
  549. f->packed_ = true;
  550. /* For the moment we default this to UPB_INTFMT_VARIABLE, since it will work
  551. * with all integer types and is in some since more "default" since the most
  552. * normal-looking proto2 types int32/int64/uint32/uint64 use variable.
  553. *
  554. * Other options to consider:
  555. * - there is no default; users must set this manually (like type).
  556. * - default signed integers to UPB_INTFMT_ZIGZAG, since it's more likely to
  557. * be an optimal default for signed integers. */
  558. f->intfmt = UPB_INTFMT_VARIABLE;
  559. return f;
  560. }
  561. upb_fielddef *upb_fielddef_dup(const upb_fielddef *f, const void *owner) {
  562. const char *srcname;
  563. upb_fielddef *newf = upb_fielddef_new(owner);
  564. if (!newf) return NULL;
  565. upb_fielddef_settype(newf, upb_fielddef_type(f));
  566. upb_fielddef_setlabel(newf, upb_fielddef_label(f));
  567. upb_fielddef_setnumber(newf, upb_fielddef_number(f), NULL);
  568. upb_fielddef_setname(newf, upb_fielddef_name(f), NULL);
  569. if (f->default_is_string && f->defaultval.bytes) {
  570. str_t *s = f->defaultval.bytes;
  571. upb_fielddef_setdefaultstr(newf, s->str, s->len, NULL);
  572. } else {
  573. newf->default_is_string = f->default_is_string;
  574. newf->defaultval = f->defaultval;
  575. }
  576. if (f->subdef_is_symbolic) {
  577. srcname = f->sub.name; /* Might be NULL. */
  578. } else {
  579. srcname = f->sub.def ? upb_def_fullname(f->sub.def) : NULL;
  580. }
  581. if (srcname) {
  582. char *newname = malloc(strlen(f->sub.def->fullname) + 2);
  583. if (!newname) {
  584. upb_fielddef_unref(newf, owner);
  585. return NULL;
  586. }
  587. strcpy(newname, ".");
  588. strcat(newname, f->sub.def->fullname);
  589. upb_fielddef_setsubdefname(newf, newname, NULL);
  590. free(newname);
  591. }
  592. return newf;
  593. }
  594. bool upb_fielddef_typeisset(const upb_fielddef *f) {
  595. return f->type_is_set_;
  596. }
  597. upb_fieldtype_t upb_fielddef_type(const upb_fielddef *f) {
  598. assert(f->type_is_set_);
  599. return f->type_;
  600. }
  601. uint32_t upb_fielddef_index(const upb_fielddef *f) {
  602. return f->index_;
  603. }
  604. upb_label_t upb_fielddef_label(const upb_fielddef *f) {
  605. return f->label_;
  606. }
  607. upb_intfmt_t upb_fielddef_intfmt(const upb_fielddef *f) {
  608. return f->intfmt;
  609. }
  610. bool upb_fielddef_istagdelim(const upb_fielddef *f) {
  611. return f->tagdelim;
  612. }
  613. uint32_t upb_fielddef_number(const upb_fielddef *f) {
  614. return f->number_;
  615. }
  616. bool upb_fielddef_isextension(const upb_fielddef *f) {
  617. return f->is_extension_;
  618. }
  619. bool upb_fielddef_lazy(const upb_fielddef *f) {
  620. return f->lazy_;
  621. }
  622. bool upb_fielddef_packed(const upb_fielddef *f) {
  623. return f->packed_;
  624. }
  625. const char *upb_fielddef_name(const upb_fielddef *f) {
  626. return upb_def_fullname(upb_fielddef_upcast(f));
  627. }
  628. size_t upb_fielddef_getjsonname(const upb_fielddef *f, char *buf, size_t len) {
  629. const char *name = upb_fielddef_name(f);
  630. size_t src, dst = 0;
  631. bool ucase_next = false;
  632. #define WRITE(byte) \
  633. ++dst; \
  634. if (dst < len) buf[dst - 1] = byte; \
  635. else if (dst == len) buf[dst - 1] = '\0'
  636. if (!name) {
  637. WRITE('\0');
  638. return 0;
  639. }
  640. /* Implement the transformation as described in the spec:
  641. * 1. upper case all letters after an underscore.
  642. * 2. remove all underscores.
  643. */
  644. for (src = 0; name[src]; src++) {
  645. if (name[src] == '_') {
  646. ucase_next = true;
  647. continue;
  648. }
  649. if (ucase_next) {
  650. WRITE(toupper(name[src]));
  651. ucase_next = false;
  652. } else {
  653. WRITE(name[src]);
  654. }
  655. }
  656. WRITE('\0');
  657. return dst;
  658. #undef WRITE
  659. }
  660. const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f) {
  661. return f->msg_is_symbolic ? NULL : f->msg.def;
  662. }
  663. const upb_oneofdef *upb_fielddef_containingoneof(const upb_fielddef *f) {
  664. return f->oneof;
  665. }
  666. upb_msgdef *upb_fielddef_containingtype_mutable(upb_fielddef *f) {
  667. return (upb_msgdef*)upb_fielddef_containingtype(f);
  668. }
  669. const char *upb_fielddef_containingtypename(upb_fielddef *f) {
  670. return f->msg_is_symbolic ? f->msg.name : NULL;
  671. }
  672. static void release_containingtype(upb_fielddef *f) {
  673. if (f->msg_is_symbolic) free(f->msg.name);
  674. }
  675. bool upb_fielddef_setcontainingtypename(upb_fielddef *f, const char *name,
  676. upb_status *s) {
  677. assert(!upb_fielddef_isfrozen(f));
  678. if (upb_fielddef_containingtype(f)) {
  679. upb_status_seterrmsg(s, "field has already been added to a message.");
  680. return false;
  681. }
  682. /* TODO: validate name (upb_isident() doesn't quite work atm because this name
  683. * may have a leading "."). */
  684. release_containingtype(f);
  685. f->msg.name = upb_strdup(name);
  686. f->msg_is_symbolic = true;
  687. return true;
  688. }
  689. bool upb_fielddef_setname(upb_fielddef *f, const char *name, upb_status *s) {
  690. if (upb_fielddef_containingtype(f) || upb_fielddef_containingoneof(f)) {
  691. upb_status_seterrmsg(s, "Already added to message or oneof");
  692. return false;
  693. }
  694. return upb_def_setfullname(upb_fielddef_upcast_mutable(f), name, s);
  695. }
  696. static void chkdefaulttype(const upb_fielddef *f, upb_fieldtype_t type) {
  697. UPB_UNUSED(f);
  698. UPB_UNUSED(type);
  699. assert(f->type_is_set_ && upb_fielddef_type(f) == type);
  700. }
  701. int64_t upb_fielddef_defaultint64(const upb_fielddef *f) {
  702. chkdefaulttype(f, UPB_TYPE_INT64);
  703. return f->defaultval.sint;
  704. }
  705. int32_t upb_fielddef_defaultint32(const upb_fielddef *f) {
  706. if (f->type_is_set_ && upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  707. int32_t val;
  708. bool ok = enumdefaultint32(f, &val);
  709. UPB_ASSERT_VAR(ok, ok);
  710. return val;
  711. } else {
  712. chkdefaulttype(f, UPB_TYPE_INT32);
  713. return f->defaultval.sint;
  714. }
  715. }
  716. uint64_t upb_fielddef_defaultuint64(const upb_fielddef *f) {
  717. chkdefaulttype(f, UPB_TYPE_UINT64);
  718. return f->defaultval.uint;
  719. }
  720. uint32_t upb_fielddef_defaultuint32(const upb_fielddef *f) {
  721. chkdefaulttype(f, UPB_TYPE_UINT32);
  722. return f->defaultval.uint;
  723. }
  724. bool upb_fielddef_defaultbool(const upb_fielddef *f) {
  725. chkdefaulttype(f, UPB_TYPE_BOOL);
  726. return f->defaultval.uint;
  727. }
  728. float upb_fielddef_defaultfloat(const upb_fielddef *f) {
  729. chkdefaulttype(f, UPB_TYPE_FLOAT);
  730. return f->defaultval.flt;
  731. }
  732. double upb_fielddef_defaultdouble(const upb_fielddef *f) {
  733. chkdefaulttype(f, UPB_TYPE_DOUBLE);
  734. return f->defaultval.dbl;
  735. }
  736. const char *upb_fielddef_defaultstr(const upb_fielddef *f, size_t *len) {
  737. assert(f->type_is_set_);
  738. assert(upb_fielddef_type(f) == UPB_TYPE_STRING ||
  739. upb_fielddef_type(f) == UPB_TYPE_BYTES ||
  740. upb_fielddef_type(f) == UPB_TYPE_ENUM);
  741. if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  742. const char *ret = enumdefaultstr(f);
  743. assert(ret);
  744. /* Enum defaults can't have embedded NULLs. */
  745. if (len) *len = strlen(ret);
  746. return ret;
  747. }
  748. if (f->default_is_string) {
  749. str_t *str = f->defaultval.bytes;
  750. if (len) *len = str->len;
  751. return str->str;
  752. }
  753. return NULL;
  754. }
  755. static void upb_fielddef_init_default(upb_fielddef *f) {
  756. f->default_is_string = false;
  757. switch (upb_fielddef_type(f)) {
  758. case UPB_TYPE_DOUBLE: f->defaultval.dbl = 0; break;
  759. case UPB_TYPE_FLOAT: f->defaultval.flt = 0; break;
  760. case UPB_TYPE_INT32:
  761. case UPB_TYPE_INT64: f->defaultval.sint = 0; break;
  762. case UPB_TYPE_UINT64:
  763. case UPB_TYPE_UINT32:
  764. case UPB_TYPE_BOOL: f->defaultval.uint = 0; break;
  765. case UPB_TYPE_STRING:
  766. case UPB_TYPE_BYTES:
  767. f->defaultval.bytes = newstr("", 0);
  768. f->default_is_string = true;
  769. break;
  770. case UPB_TYPE_MESSAGE: break;
  771. case UPB_TYPE_ENUM:
  772. /* This is our special sentinel that indicates "not set" for an enum. */
  773. f->default_is_string = true;
  774. f->defaultval.bytes = NULL;
  775. break;
  776. }
  777. }
  778. const upb_def *upb_fielddef_subdef(const upb_fielddef *f) {
  779. return f->subdef_is_symbolic ? NULL : f->sub.def;
  780. }
  781. const upb_msgdef *upb_fielddef_msgsubdef(const upb_fielddef *f) {
  782. const upb_def *def = upb_fielddef_subdef(f);
  783. return def ? upb_dyncast_msgdef(def) : NULL;
  784. }
  785. const upb_enumdef *upb_fielddef_enumsubdef(const upb_fielddef *f) {
  786. const upb_def *def = upb_fielddef_subdef(f);
  787. return def ? upb_dyncast_enumdef(def) : NULL;
  788. }
  789. upb_def *upb_fielddef_subdef_mutable(upb_fielddef *f) {
  790. return (upb_def*)upb_fielddef_subdef(f);
  791. }
  792. const char *upb_fielddef_subdefname(const upb_fielddef *f) {
  793. if (f->subdef_is_symbolic) {
  794. return f->sub.name;
  795. } else if (f->sub.def) {
  796. return upb_def_fullname(f->sub.def);
  797. } else {
  798. return NULL;
  799. }
  800. }
  801. bool upb_fielddef_setnumber(upb_fielddef *f, uint32_t number, upb_status *s) {
  802. if (upb_fielddef_containingtype(f)) {
  803. upb_status_seterrmsg(
  804. s, "cannot change field number after adding to a message");
  805. return false;
  806. }
  807. if (number == 0 || number > UPB_MAX_FIELDNUMBER) {
  808. upb_status_seterrf(s, "invalid field number (%u)", number);
  809. return false;
  810. }
  811. f->number_ = number;
  812. return true;
  813. }
  814. void upb_fielddef_settype(upb_fielddef *f, upb_fieldtype_t type) {
  815. assert(!upb_fielddef_isfrozen(f));
  816. assert(upb_fielddef_checktype(type));
  817. upb_fielddef_uninit_default(f);
  818. f->type_ = type;
  819. f->type_is_set_ = true;
  820. upb_fielddef_init_default(f);
  821. }
  822. void upb_fielddef_setdescriptortype(upb_fielddef *f, int type) {
  823. assert(!upb_fielddef_isfrozen(f));
  824. switch (type) {
  825. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  826. upb_fielddef_settype(f, UPB_TYPE_DOUBLE);
  827. break;
  828. case UPB_DESCRIPTOR_TYPE_FLOAT:
  829. upb_fielddef_settype(f, UPB_TYPE_FLOAT);
  830. break;
  831. case UPB_DESCRIPTOR_TYPE_INT64:
  832. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  833. case UPB_DESCRIPTOR_TYPE_SINT64:
  834. upb_fielddef_settype(f, UPB_TYPE_INT64);
  835. break;
  836. case UPB_DESCRIPTOR_TYPE_UINT64:
  837. case UPB_DESCRIPTOR_TYPE_FIXED64:
  838. upb_fielddef_settype(f, UPB_TYPE_UINT64);
  839. break;
  840. case UPB_DESCRIPTOR_TYPE_INT32:
  841. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  842. case UPB_DESCRIPTOR_TYPE_SINT32:
  843. upb_fielddef_settype(f, UPB_TYPE_INT32);
  844. break;
  845. case UPB_DESCRIPTOR_TYPE_UINT32:
  846. case UPB_DESCRIPTOR_TYPE_FIXED32:
  847. upb_fielddef_settype(f, UPB_TYPE_UINT32);
  848. break;
  849. case UPB_DESCRIPTOR_TYPE_BOOL:
  850. upb_fielddef_settype(f, UPB_TYPE_BOOL);
  851. break;
  852. case UPB_DESCRIPTOR_TYPE_STRING:
  853. upb_fielddef_settype(f, UPB_TYPE_STRING);
  854. break;
  855. case UPB_DESCRIPTOR_TYPE_BYTES:
  856. upb_fielddef_settype(f, UPB_TYPE_BYTES);
  857. break;
  858. case UPB_DESCRIPTOR_TYPE_GROUP:
  859. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  860. upb_fielddef_settype(f, UPB_TYPE_MESSAGE);
  861. break;
  862. case UPB_DESCRIPTOR_TYPE_ENUM:
  863. upb_fielddef_settype(f, UPB_TYPE_ENUM);
  864. break;
  865. default: assert(false);
  866. }
  867. if (type == UPB_DESCRIPTOR_TYPE_FIXED64 ||
  868. type == UPB_DESCRIPTOR_TYPE_FIXED32 ||
  869. type == UPB_DESCRIPTOR_TYPE_SFIXED64 ||
  870. type == UPB_DESCRIPTOR_TYPE_SFIXED32) {
  871. upb_fielddef_setintfmt(f, UPB_INTFMT_FIXED);
  872. } else if (type == UPB_DESCRIPTOR_TYPE_SINT64 ||
  873. type == UPB_DESCRIPTOR_TYPE_SINT32) {
  874. upb_fielddef_setintfmt(f, UPB_INTFMT_ZIGZAG);
  875. } else {
  876. upb_fielddef_setintfmt(f, UPB_INTFMT_VARIABLE);
  877. }
  878. upb_fielddef_settagdelim(f, type == UPB_DESCRIPTOR_TYPE_GROUP);
  879. }
  880. upb_descriptortype_t upb_fielddef_descriptortype(const upb_fielddef *f) {
  881. switch (upb_fielddef_type(f)) {
  882. case UPB_TYPE_FLOAT: return UPB_DESCRIPTOR_TYPE_FLOAT;
  883. case UPB_TYPE_DOUBLE: return UPB_DESCRIPTOR_TYPE_DOUBLE;
  884. case UPB_TYPE_BOOL: return UPB_DESCRIPTOR_TYPE_BOOL;
  885. case UPB_TYPE_STRING: return UPB_DESCRIPTOR_TYPE_STRING;
  886. case UPB_TYPE_BYTES: return UPB_DESCRIPTOR_TYPE_BYTES;
  887. case UPB_TYPE_ENUM: return UPB_DESCRIPTOR_TYPE_ENUM;
  888. case UPB_TYPE_INT32:
  889. switch (upb_fielddef_intfmt(f)) {
  890. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT32;
  891. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED32;
  892. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT32;
  893. }
  894. case UPB_TYPE_INT64:
  895. switch (upb_fielddef_intfmt(f)) {
  896. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT64;
  897. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED64;
  898. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT64;
  899. }
  900. case UPB_TYPE_UINT32:
  901. switch (upb_fielddef_intfmt(f)) {
  902. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT32;
  903. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED32;
  904. case UPB_INTFMT_ZIGZAG: return -1;
  905. }
  906. case UPB_TYPE_UINT64:
  907. switch (upb_fielddef_intfmt(f)) {
  908. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT64;
  909. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED64;
  910. case UPB_INTFMT_ZIGZAG: return -1;
  911. }
  912. case UPB_TYPE_MESSAGE:
  913. return upb_fielddef_istagdelim(f) ?
  914. UPB_DESCRIPTOR_TYPE_GROUP : UPB_DESCRIPTOR_TYPE_MESSAGE;
  915. }
  916. return 0;
  917. }
  918. void upb_fielddef_setisextension(upb_fielddef *f, bool is_extension) {
  919. assert(!upb_fielddef_isfrozen(f));
  920. f->is_extension_ = is_extension;
  921. }
  922. void upb_fielddef_setlazy(upb_fielddef *f, bool lazy) {
  923. assert(!upb_fielddef_isfrozen(f));
  924. f->lazy_ = lazy;
  925. }
  926. void upb_fielddef_setpacked(upb_fielddef *f, bool packed) {
  927. assert(!upb_fielddef_isfrozen(f));
  928. f->packed_ = packed;
  929. }
  930. void upb_fielddef_setlabel(upb_fielddef *f, upb_label_t label) {
  931. assert(!upb_fielddef_isfrozen(f));
  932. assert(upb_fielddef_checklabel(label));
  933. f->label_ = label;
  934. }
  935. void upb_fielddef_setintfmt(upb_fielddef *f, upb_intfmt_t fmt) {
  936. assert(!upb_fielddef_isfrozen(f));
  937. assert(upb_fielddef_checkintfmt(fmt));
  938. f->intfmt = fmt;
  939. }
  940. void upb_fielddef_settagdelim(upb_fielddef *f, bool tag_delim) {
  941. assert(!upb_fielddef_isfrozen(f));
  942. f->tagdelim = tag_delim;
  943. f->tagdelim = tag_delim;
  944. }
  945. static bool checksetdefault(upb_fielddef *f, upb_fieldtype_t type) {
  946. if (!f->type_is_set_ || upb_fielddef_isfrozen(f) ||
  947. upb_fielddef_type(f) != type) {
  948. assert(false);
  949. return false;
  950. }
  951. if (f->default_is_string) {
  952. str_t *s = f->defaultval.bytes;
  953. assert(s || type == UPB_TYPE_ENUM);
  954. if (s) freestr(s);
  955. }
  956. f->default_is_string = false;
  957. return true;
  958. }
  959. void upb_fielddef_setdefaultint64(upb_fielddef *f, int64_t value) {
  960. if (checksetdefault(f, UPB_TYPE_INT64))
  961. f->defaultval.sint = value;
  962. }
  963. void upb_fielddef_setdefaultint32(upb_fielddef *f, int32_t value) {
  964. if ((upb_fielddef_type(f) == UPB_TYPE_ENUM &&
  965. checksetdefault(f, UPB_TYPE_ENUM)) ||
  966. checksetdefault(f, UPB_TYPE_INT32)) {
  967. f->defaultval.sint = value;
  968. }
  969. }
  970. void upb_fielddef_setdefaultuint64(upb_fielddef *f, uint64_t value) {
  971. if (checksetdefault(f, UPB_TYPE_UINT64))
  972. f->defaultval.uint = value;
  973. }
  974. void upb_fielddef_setdefaultuint32(upb_fielddef *f, uint32_t value) {
  975. if (checksetdefault(f, UPB_TYPE_UINT32))
  976. f->defaultval.uint = value;
  977. }
  978. void upb_fielddef_setdefaultbool(upb_fielddef *f, bool value) {
  979. if (checksetdefault(f, UPB_TYPE_BOOL))
  980. f->defaultval.uint = value;
  981. }
  982. void upb_fielddef_setdefaultfloat(upb_fielddef *f, float value) {
  983. if (checksetdefault(f, UPB_TYPE_FLOAT))
  984. f->defaultval.flt = value;
  985. }
  986. void upb_fielddef_setdefaultdouble(upb_fielddef *f, double value) {
  987. if (checksetdefault(f, UPB_TYPE_DOUBLE))
  988. f->defaultval.dbl = value;
  989. }
  990. bool upb_fielddef_setdefaultstr(upb_fielddef *f, const void *str, size_t len,
  991. upb_status *s) {
  992. str_t *str2;
  993. assert(upb_fielddef_isstring(f) || f->type_ == UPB_TYPE_ENUM);
  994. if (f->type_ == UPB_TYPE_ENUM && !upb_isident(str, len, false, s))
  995. return false;
  996. if (f->default_is_string) {
  997. str_t *s = f->defaultval.bytes;
  998. assert(s || f->type_ == UPB_TYPE_ENUM);
  999. if (s) freestr(s);
  1000. } else {
  1001. assert(f->type_ == UPB_TYPE_ENUM);
  1002. }
  1003. str2 = newstr(str, len);
  1004. f->defaultval.bytes = str2;
  1005. f->default_is_string = true;
  1006. return true;
  1007. }
  1008. void upb_fielddef_setdefaultcstr(upb_fielddef *f, const char *str,
  1009. upb_status *s) {
  1010. assert(f->type_is_set_);
  1011. upb_fielddef_setdefaultstr(f, str, str ? strlen(str) : 0, s);
  1012. }
  1013. bool upb_fielddef_enumhasdefaultint32(const upb_fielddef *f) {
  1014. int32_t val;
  1015. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  1016. return enumdefaultint32(f, &val);
  1017. }
  1018. bool upb_fielddef_enumhasdefaultstr(const upb_fielddef *f) {
  1019. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  1020. return enumdefaultstr(f) != NULL;
  1021. }
  1022. static bool upb_subdef_typecheck(upb_fielddef *f, const upb_def *subdef,
  1023. upb_status *s) {
  1024. if (f->type_ == UPB_TYPE_MESSAGE) {
  1025. if (upb_dyncast_msgdef(subdef)) return true;
  1026. upb_status_seterrmsg(s, "invalid subdef type for this submessage field");
  1027. return false;
  1028. } else if (f->type_ == UPB_TYPE_ENUM) {
  1029. if (upb_dyncast_enumdef(subdef)) return true;
  1030. upb_status_seterrmsg(s, "invalid subdef type for this enum field");
  1031. return false;
  1032. } else {
  1033. upb_status_seterrmsg(s, "only message and enum fields can have a subdef");
  1034. return false;
  1035. }
  1036. }
  1037. static void release_subdef(upb_fielddef *f) {
  1038. if (f->subdef_is_symbolic) {
  1039. free(f->sub.name);
  1040. } else if (f->sub.def) {
  1041. upb_unref2(f->sub.def, f);
  1042. }
  1043. }
  1044. bool upb_fielddef_setsubdef(upb_fielddef *f, const upb_def *subdef,
  1045. upb_status *s) {
  1046. assert(!upb_fielddef_isfrozen(f));
  1047. assert(upb_fielddef_hassubdef(f));
  1048. if (subdef && !upb_subdef_typecheck(f, subdef, s)) return false;
  1049. release_subdef(f);
  1050. f->sub.def = subdef;
  1051. f->subdef_is_symbolic = false;
  1052. if (f->sub.def) upb_ref2(f->sub.def, f);
  1053. return true;
  1054. }
  1055. bool upb_fielddef_setmsgsubdef(upb_fielddef *f, const upb_msgdef *subdef,
  1056. upb_status *s) {
  1057. return upb_fielddef_setsubdef(f, upb_msgdef_upcast(subdef), s);
  1058. }
  1059. bool upb_fielddef_setenumsubdef(upb_fielddef *f, const upb_enumdef *subdef,
  1060. upb_status *s) {
  1061. return upb_fielddef_setsubdef(f, upb_enumdef_upcast(subdef), s);
  1062. }
  1063. bool upb_fielddef_setsubdefname(upb_fielddef *f, const char *name,
  1064. upb_status *s) {
  1065. assert(!upb_fielddef_isfrozen(f));
  1066. if (!upb_fielddef_hassubdef(f)) {
  1067. upb_status_seterrmsg(s, "field type does not accept a subdef");
  1068. return false;
  1069. }
  1070. /* TODO: validate name (upb_isident() doesn't quite work atm because this name
  1071. * may have a leading "."). */
  1072. release_subdef(f);
  1073. f->sub.name = upb_strdup(name);
  1074. f->subdef_is_symbolic = true;
  1075. return true;
  1076. }
  1077. bool upb_fielddef_issubmsg(const upb_fielddef *f) {
  1078. return upb_fielddef_type(f) == UPB_TYPE_MESSAGE;
  1079. }
  1080. bool upb_fielddef_isstring(const upb_fielddef *f) {
  1081. return upb_fielddef_type(f) == UPB_TYPE_STRING ||
  1082. upb_fielddef_type(f) == UPB_TYPE_BYTES;
  1083. }
  1084. bool upb_fielddef_isseq(const upb_fielddef *f) {
  1085. return upb_fielddef_label(f) == UPB_LABEL_REPEATED;
  1086. }
  1087. bool upb_fielddef_isprimitive(const upb_fielddef *f) {
  1088. return !upb_fielddef_isstring(f) && !upb_fielddef_issubmsg(f);
  1089. }
  1090. bool upb_fielddef_ismap(const upb_fielddef *f) {
  1091. return upb_fielddef_isseq(f) && upb_fielddef_issubmsg(f) &&
  1092. upb_msgdef_mapentry(upb_fielddef_msgsubdef(f));
  1093. }
  1094. bool upb_fielddef_haspresence(const upb_fielddef *f) {
  1095. if (upb_fielddef_isseq(f)) return false;
  1096. if (upb_fielddef_issubmsg(f)) return true;
  1097. /* Primitive field: return true unless there is a message that specifies
  1098. * presence should not exist. */
  1099. if (f->msg_is_symbolic || !f->msg.def) return true;
  1100. return f->msg.def->primitives_have_presence;
  1101. }
  1102. bool upb_fielddef_hassubdef(const upb_fielddef *f) {
  1103. return upb_fielddef_issubmsg(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM;
  1104. }
  1105. static bool between(int32_t x, int32_t low, int32_t high) {
  1106. return x >= low && x <= high;
  1107. }
  1108. bool upb_fielddef_checklabel(int32_t label) { return between(label, 1, 3); }
  1109. bool upb_fielddef_checktype(int32_t type) { return between(type, 1, 11); }
  1110. bool upb_fielddef_checkintfmt(int32_t fmt) { return between(fmt, 1, 3); }
  1111. bool upb_fielddef_checkdescriptortype(int32_t type) {
  1112. return between(type, 1, 18);
  1113. }
  1114. /* upb_msgdef *****************************************************************/
  1115. static void visitmsg(const upb_refcounted *r, upb_refcounted_visit *visit,
  1116. void *closure) {
  1117. upb_msg_oneof_iter o;
  1118. const upb_msgdef *m = (const upb_msgdef*)r;
  1119. upb_msg_field_iter i;
  1120. for(upb_msg_field_begin(&i, m);
  1121. !upb_msg_field_done(&i);
  1122. upb_msg_field_next(&i)) {
  1123. upb_fielddef *f = upb_msg_iter_field(&i);
  1124. visit(r, upb_fielddef_upcast2(f), closure);
  1125. }
  1126. for(upb_msg_oneof_begin(&o, m);
  1127. !upb_msg_oneof_done(&o);
  1128. upb_msg_oneof_next(&o)) {
  1129. upb_oneofdef *f = upb_msg_iter_oneof(&o);
  1130. visit(r, upb_oneofdef_upcast2(f), closure);
  1131. }
  1132. }
  1133. static void freemsg(upb_refcounted *r) {
  1134. upb_msgdef *m = (upb_msgdef*)r;
  1135. upb_strtable_uninit(&m->ntoo);
  1136. upb_strtable_uninit(&m->ntof);
  1137. upb_inttable_uninit(&m->itof);
  1138. upb_def_uninit(upb_msgdef_upcast_mutable(m));
  1139. free(m);
  1140. }
  1141. upb_msgdef *upb_msgdef_new(const void *owner) {
  1142. static const struct upb_refcounted_vtbl vtbl = {visitmsg, freemsg};
  1143. upb_msgdef *m = malloc(sizeof(*m));
  1144. if (!m) return NULL;
  1145. if (!upb_def_init(upb_msgdef_upcast_mutable(m), UPB_DEF_MSG, &vtbl, owner))
  1146. goto err2;
  1147. if (!upb_inttable_init(&m->itof, UPB_CTYPE_PTR)) goto err3;
  1148. if (!upb_strtable_init(&m->ntof, UPB_CTYPE_PTR)) goto err2;
  1149. if (!upb_strtable_init(&m->ntoo, UPB_CTYPE_PTR)) goto err1;
  1150. m->map_entry = false;
  1151. m->primitives_have_presence = true;
  1152. return m;
  1153. err1:
  1154. upb_strtable_uninit(&m->ntof);
  1155. err2:
  1156. upb_inttable_uninit(&m->itof);
  1157. err3:
  1158. free(m);
  1159. return NULL;
  1160. }
  1161. upb_msgdef *upb_msgdef_dup(const upb_msgdef *m, const void *owner) {
  1162. bool ok;
  1163. upb_msg_field_iter i;
  1164. upb_msg_oneof_iter o;
  1165. upb_msgdef *newm = upb_msgdef_new(owner);
  1166. if (!newm) return NULL;
  1167. ok = upb_def_setfullname(upb_msgdef_upcast_mutable(newm),
  1168. upb_def_fullname(upb_msgdef_upcast(m)),
  1169. NULL);
  1170. newm->map_entry = m->map_entry;
  1171. newm->primitives_have_presence = m->primitives_have_presence;
  1172. UPB_ASSERT_VAR(ok, ok);
  1173. for(upb_msg_field_begin(&i, m);
  1174. !upb_msg_field_done(&i);
  1175. upb_msg_field_next(&i)) {
  1176. upb_fielddef *f = upb_fielddef_dup(upb_msg_iter_field(&i), &f);
  1177. /* Fields in oneofs are dup'd below. */
  1178. if (upb_fielddef_containingoneof(f)) continue;
  1179. if (!f || !upb_msgdef_addfield(newm, f, &f, NULL)) {
  1180. upb_msgdef_unref(newm, owner);
  1181. return NULL;
  1182. }
  1183. }
  1184. for(upb_msg_oneof_begin(&o, m);
  1185. !upb_msg_oneof_done(&o);
  1186. upb_msg_oneof_next(&o)) {
  1187. upb_oneofdef *f = upb_oneofdef_dup(upb_msg_iter_oneof(&o), &f);
  1188. if (!f || !upb_msgdef_addoneof(newm, f, &f, NULL)) {
  1189. upb_msgdef_unref(newm, owner);
  1190. return NULL;
  1191. }
  1192. }
  1193. return newm;
  1194. }
  1195. bool upb_msgdef_freeze(upb_msgdef *m, upb_status *status) {
  1196. upb_def *d = upb_msgdef_upcast_mutable(m);
  1197. return upb_def_freeze(&d, 1, status);
  1198. }
  1199. const char *upb_msgdef_fullname(const upb_msgdef *m) {
  1200. return upb_def_fullname(upb_msgdef_upcast(m));
  1201. }
  1202. bool upb_msgdef_setfullname(upb_msgdef *m, const char *fullname,
  1203. upb_status *s) {
  1204. return upb_def_setfullname(upb_msgdef_upcast_mutable(m), fullname, s);
  1205. }
  1206. /* Helper: check that the field |f| is safe to add to msgdef |m|. Set an error
  1207. * on status |s| and return false if not. */
  1208. static bool check_field_add(const upb_msgdef *m, const upb_fielddef *f,
  1209. upb_status *s) {
  1210. if (upb_fielddef_containingtype(f) != NULL) {
  1211. upb_status_seterrmsg(s, "fielddef already belongs to a message");
  1212. return false;
  1213. } else if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  1214. upb_status_seterrmsg(s, "field name or number were not set");
  1215. return false;
  1216. } else if (upb_msgdef_ntofz(m, upb_fielddef_name(f)) ||
  1217. upb_msgdef_itof(m, upb_fielddef_number(f))) {
  1218. upb_status_seterrmsg(s, "duplicate field name or number for field");
  1219. return false;
  1220. }
  1221. return true;
  1222. }
  1223. static void add_field(upb_msgdef *m, upb_fielddef *f, const void *ref_donor) {
  1224. release_containingtype(f);
  1225. f->msg.def = m;
  1226. f->msg_is_symbolic = false;
  1227. upb_inttable_insert(&m->itof, upb_fielddef_number(f), upb_value_ptr(f));
  1228. upb_strtable_insert(&m->ntof, upb_fielddef_name(f), upb_value_ptr(f));
  1229. upb_ref2(f, m);
  1230. upb_ref2(m, f);
  1231. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  1232. }
  1233. bool upb_msgdef_addfield(upb_msgdef *m, upb_fielddef *f, const void *ref_donor,
  1234. upb_status *s) {
  1235. /* TODO: extensions need to have a separate namespace, because proto2 allows a
  1236. * top-level extension (ie. one not in any package) to have the same name as a
  1237. * field from the message.
  1238. *
  1239. * This also implies that there needs to be a separate lookup-by-name method
  1240. * for extensions. It seems desirable for iteration to return both extensions
  1241. * and non-extensions though.
  1242. *
  1243. * We also need to validate that the field number is in an extension range iff
  1244. * it is an extension.
  1245. *
  1246. * This method is idempotent. Check if |f| is already part of this msgdef and
  1247. * return immediately if so. */
  1248. if (upb_fielddef_containingtype(f) == m) {
  1249. return true;
  1250. }
  1251. /* Check constraints for all fields before performing any action. */
  1252. if (!check_field_add(m, f, s)) {
  1253. return false;
  1254. } else if (upb_fielddef_containingoneof(f) != NULL) {
  1255. /* Fields in a oneof can only be added by adding the oneof to the msgdef. */
  1256. upb_status_seterrmsg(s, "fielddef is part of a oneof");
  1257. return false;
  1258. }
  1259. /* Constraint checks ok, perform the action. */
  1260. add_field(m, f, ref_donor);
  1261. return true;
  1262. }
  1263. bool upb_msgdef_addoneof(upb_msgdef *m, upb_oneofdef *o, const void *ref_donor,
  1264. upb_status *s) {
  1265. upb_oneof_iter it;
  1266. /* Check various conditions that would prevent this oneof from being added. */
  1267. if (upb_oneofdef_containingtype(o)) {
  1268. upb_status_seterrmsg(s, "oneofdef already belongs to a message");
  1269. return false;
  1270. } else if (upb_oneofdef_name(o) == NULL) {
  1271. upb_status_seterrmsg(s, "oneofdef name was not set");
  1272. return false;
  1273. } else if (upb_msgdef_ntooz(m, upb_oneofdef_name(o))) {
  1274. upb_status_seterrmsg(s, "duplicate oneof name");
  1275. return false;
  1276. }
  1277. /* Check that all of the oneof's fields do not conflict with names or numbers
  1278. * of fields already in the message. */
  1279. for (upb_oneof_begin(&it, o); !upb_oneof_done(&it); upb_oneof_next(&it)) {
  1280. const upb_fielddef *f = upb_oneof_iter_field(&it);
  1281. if (!check_field_add(m, f, s)) {
  1282. return false;
  1283. }
  1284. }
  1285. /* Everything checks out -- commit now. */
  1286. /* Add oneof itself first. */
  1287. o->parent = m;
  1288. upb_strtable_insert(&m->ntoo, upb_oneofdef_name(o), upb_value_ptr(o));
  1289. upb_ref2(o, m);
  1290. upb_ref2(m, o);
  1291. /* Add each field of the oneof directly to the msgdef. */
  1292. for (upb_oneof_begin(&it, o); !upb_oneof_done(&it); upb_oneof_next(&it)) {
  1293. upb_fielddef *f = upb_oneof_iter_field(&it);
  1294. add_field(m, f, NULL);
  1295. }
  1296. if (ref_donor) upb_oneofdef_unref(o, ref_donor);
  1297. return true;
  1298. }
  1299. void upb_msgdef_setprimitiveshavepresence(upb_msgdef *m, bool have_presence) {
  1300. assert(!upb_msgdef_isfrozen(m));
  1301. m->primitives_have_presence = have_presence;
  1302. }
  1303. const upb_fielddef *upb_msgdef_itof(const upb_msgdef *m, uint32_t i) {
  1304. upb_value val;
  1305. return upb_inttable_lookup32(&m->itof, i, &val) ?
  1306. upb_value_getptr(val) : NULL;
  1307. }
  1308. const upb_fielddef *upb_msgdef_ntof(const upb_msgdef *m, const char *name,
  1309. size_t len) {
  1310. upb_value val;
  1311. return upb_strtable_lookup2(&m->ntof, name, len, &val) ?
  1312. upb_value_getptr(val) : NULL;
  1313. }
  1314. const upb_oneofdef *upb_msgdef_ntoo(const upb_msgdef *m, const char *name,
  1315. size_t len) {
  1316. upb_value val;
  1317. return upb_strtable_lookup2(&m->ntoo, name, len, &val) ?
  1318. upb_value_getptr(val) : NULL;
  1319. }
  1320. int upb_msgdef_numfields(const upb_msgdef *m) {
  1321. return upb_strtable_count(&m->ntof);
  1322. }
  1323. int upb_msgdef_numoneofs(const upb_msgdef *m) {
  1324. return upb_strtable_count(&m->ntoo);
  1325. }
  1326. void upb_msgdef_setmapentry(upb_msgdef *m, bool map_entry) {
  1327. assert(!upb_msgdef_isfrozen(m));
  1328. m->map_entry = map_entry;
  1329. }
  1330. bool upb_msgdef_mapentry(const upb_msgdef *m) {
  1331. return m->map_entry;
  1332. }
  1333. void upb_msg_field_begin(upb_msg_field_iter *iter, const upb_msgdef *m) {
  1334. upb_inttable_begin(iter, &m->itof);
  1335. }
  1336. void upb_msg_field_next(upb_msg_field_iter *iter) { upb_inttable_next(iter); }
  1337. bool upb_msg_field_done(const upb_msg_field_iter *iter) {
  1338. return upb_inttable_done(iter);
  1339. }
  1340. upb_fielddef *upb_msg_iter_field(const upb_msg_field_iter *iter) {
  1341. return (upb_fielddef*)upb_value_getptr(upb_inttable_iter_value(iter));
  1342. }
  1343. void upb_msg_field_iter_setdone(upb_msg_field_iter *iter) {
  1344. upb_inttable_iter_setdone(iter);
  1345. }
  1346. void upb_msg_oneof_begin(upb_msg_oneof_iter *iter, const upb_msgdef *m) {
  1347. upb_strtable_begin(iter, &m->ntoo);
  1348. }
  1349. void upb_msg_oneof_next(upb_msg_oneof_iter *iter) { upb_strtable_next(iter); }
  1350. bool upb_msg_oneof_done(const upb_msg_oneof_iter *iter) {
  1351. return upb_strtable_done(iter);
  1352. }
  1353. upb_oneofdef *upb_msg_iter_oneof(const upb_msg_oneof_iter *iter) {
  1354. return (upb_oneofdef*)upb_value_getptr(upb_strtable_iter_value(iter));
  1355. }
  1356. void upb_msg_oneof_iter_setdone(upb_msg_oneof_iter *iter) {
  1357. upb_strtable_iter_setdone(iter);
  1358. }
  1359. /* upb_oneofdef ***************************************************************/
  1360. static void visitoneof(const upb_refcounted *r, upb_refcounted_visit *visit,
  1361. void *closure) {
  1362. const upb_oneofdef *o = (const upb_oneofdef*)r;
  1363. upb_oneof_iter i;
  1364. for (upb_oneof_begin(&i, o); !upb_oneof_done(&i); upb_oneof_next(&i)) {
  1365. const upb_fielddef *f = upb_oneof_iter_field(&i);
  1366. visit(r, upb_fielddef_upcast2(f), closure);
  1367. }
  1368. if (o->parent) {
  1369. visit(r, upb_msgdef_upcast2(o->parent), closure);
  1370. }
  1371. }
  1372. static void freeoneof(upb_refcounted *r) {
  1373. upb_oneofdef *o = (upb_oneofdef*)r;
  1374. upb_strtable_uninit(&o->ntof);
  1375. upb_inttable_uninit(&o->itof);
  1376. upb_def_uninit(upb_oneofdef_upcast_mutable(o));
  1377. free(o);
  1378. }
  1379. upb_oneofdef *upb_oneofdef_new(const void *owner) {
  1380. static const struct upb_refcounted_vtbl vtbl = {visitoneof, freeoneof};
  1381. upb_oneofdef *o = malloc(sizeof(*o));
  1382. o->parent = NULL;
  1383. if (!o) return NULL;
  1384. if (!upb_def_init(upb_oneofdef_upcast_mutable(o), UPB_DEF_ONEOF, &vtbl,
  1385. owner))
  1386. goto err2;
  1387. if (!upb_inttable_init(&o->itof, UPB_CTYPE_PTR)) goto err2;
  1388. if (!upb_strtable_init(&o->ntof, UPB_CTYPE_PTR)) goto err1;
  1389. return o;
  1390. err1:
  1391. upb_inttable_uninit(&o->itof);
  1392. err2:
  1393. free(o);
  1394. return NULL;
  1395. }
  1396. upb_oneofdef *upb_oneofdef_dup(const upb_oneofdef *o, const void *owner) {
  1397. bool ok;
  1398. upb_oneof_iter i;
  1399. upb_oneofdef *newo = upb_oneofdef_new(owner);
  1400. if (!newo) return NULL;
  1401. ok = upb_def_setfullname(upb_oneofdef_upcast_mutable(newo),
  1402. upb_def_fullname(upb_oneofdef_upcast(o)), NULL);
  1403. UPB_ASSERT_VAR(ok, ok);
  1404. for (upb_oneof_begin(&i, o); !upb_oneof_done(&i); upb_oneof_next(&i)) {
  1405. upb_fielddef *f = upb_fielddef_dup(upb_oneof_iter_field(&i), &f);
  1406. if (!f || !upb_oneofdef_addfield(newo, f, &f, NULL)) {
  1407. upb_oneofdef_unref(newo, owner);
  1408. return NULL;
  1409. }
  1410. }
  1411. return newo;
  1412. }
  1413. const char *upb_oneofdef_name(const upb_oneofdef *o) {
  1414. return upb_def_fullname(upb_oneofdef_upcast(o));
  1415. }
  1416. bool upb_oneofdef_setname(upb_oneofdef *o, const char *fullname,
  1417. upb_status *s) {
  1418. if (upb_oneofdef_containingtype(o)) {
  1419. upb_status_seterrmsg(s, "oneof already added to a message");
  1420. return false;
  1421. }
  1422. return upb_def_setfullname(upb_oneofdef_upcast_mutable(o), fullname, s);
  1423. }
  1424. const upb_msgdef *upb_oneofdef_containingtype(const upb_oneofdef *o) {
  1425. return o->parent;
  1426. }
  1427. int upb_oneofdef_numfields(const upb_oneofdef *o) {
  1428. return upb_strtable_count(&o->ntof);
  1429. }
  1430. bool upb_oneofdef_addfield(upb_oneofdef *o, upb_fielddef *f,
  1431. const void *ref_donor,
  1432. upb_status *s) {
  1433. assert(!upb_oneofdef_isfrozen(o));
  1434. assert(!o->parent || !upb_msgdef_isfrozen(o->parent));
  1435. /* This method is idempotent. Check if |f| is already part of this oneofdef
  1436. * and return immediately if so. */
  1437. if (upb_fielddef_containingoneof(f) == o) {
  1438. return true;
  1439. }
  1440. /* The field must have an OPTIONAL label. */
  1441. if (upb_fielddef_label(f) != UPB_LABEL_OPTIONAL) {
  1442. upb_status_seterrmsg(s, "fields in oneof must have OPTIONAL label");
  1443. return false;
  1444. }
  1445. /* Check that no field with this name or number exists already in the oneof.
  1446. * Also check that the field is not already part of a oneof. */
  1447. if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  1448. upb_status_seterrmsg(s, "field name or number were not set");
  1449. return false;
  1450. } else if (upb_oneofdef_itof(o, upb_fielddef_number(f)) ||
  1451. upb_oneofdef_ntofz(o, upb_fielddef_name(f))) {
  1452. upb_status_seterrmsg(s, "duplicate field name or number");
  1453. return false;
  1454. } else if (upb_fielddef_containingoneof(f) != NULL) {
  1455. upb_status_seterrmsg(s, "fielddef already belongs to a oneof");
  1456. return false;
  1457. }
  1458. /* We allow adding a field to the oneof either if the field is not part of a
  1459. * msgdef, or if it is and we are also part of the same msgdef. */
  1460. if (o->parent == NULL) {
  1461. /* If we're not in a msgdef, the field cannot be either. Otherwise we would
  1462. * need to magically add this oneof to a msgdef to remain consistent, which
  1463. * is surprising behavior. */
  1464. if (upb_fielddef_containingtype(f) != NULL) {
  1465. upb_status_seterrmsg(s, "fielddef already belongs to a message, but "
  1466. "oneof does not");
  1467. return false;
  1468. }
  1469. } else {
  1470. /* If we're in a msgdef, the user can add fields that either aren't in any
  1471. * msgdef (in which case they're added to our msgdef) or already a part of
  1472. * our msgdef. */
  1473. if (upb_fielddef_containingtype(f) != NULL &&
  1474. upb_fielddef_containingtype(f) != o->parent) {
  1475. upb_status_seterrmsg(s, "fielddef belongs to a different message "
  1476. "than oneof");
  1477. return false;
  1478. }
  1479. }
  1480. /* Commit phase. First add the field to our parent msgdef, if any, because
  1481. * that may fail; then add the field to our own tables. */
  1482. if (o->parent != NULL && upb_fielddef_containingtype(f) == NULL) {
  1483. if (!upb_msgdef_addfield((upb_msgdef*)o->parent, f, NULL, s)) {
  1484. return false;
  1485. }
  1486. }
  1487. release_containingtype(f);
  1488. f->oneof = o;
  1489. upb_inttable_insert(&o->itof, upb_fielddef_number(f), upb_value_ptr(f));
  1490. upb_strtable_insert(&o->ntof, upb_fielddef_name(f), upb_value_ptr(f));
  1491. upb_ref2(f, o);
  1492. upb_ref2(o, f);
  1493. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  1494. return true;
  1495. }
  1496. const upb_fielddef *upb_oneofdef_ntof(const upb_oneofdef *o,
  1497. const char *name, size_t length) {
  1498. upb_value val;
  1499. return upb_strtable_lookup2(&o->ntof, name, length, &val) ?
  1500. upb_value_getptr(val) : NULL;
  1501. }
  1502. const upb_fielddef *upb_oneofdef_itof(const upb_oneofdef *o, uint32_t num) {
  1503. upb_value val;
  1504. return upb_inttable_lookup32(&o->itof, num, &val) ?
  1505. upb_value_getptr(val) : NULL;
  1506. }
  1507. void upb_oneof_begin(upb_oneof_iter *iter, const upb_oneofdef *o) {
  1508. upb_inttable_begin(iter, &o->itof);
  1509. }
  1510. void upb_oneof_next(upb_oneof_iter *iter) {
  1511. upb_inttable_next(iter);
  1512. }
  1513. bool upb_oneof_done(upb_oneof_iter *iter) {
  1514. return upb_inttable_done(iter);
  1515. }
  1516. upb_fielddef *upb_oneof_iter_field(const upb_oneof_iter *iter) {
  1517. return (upb_fielddef*)upb_value_getptr(upb_inttable_iter_value(iter));
  1518. }
  1519. void upb_oneof_iter_setdone(upb_oneof_iter *iter) {
  1520. upb_inttable_iter_setdone(iter);
  1521. }
  1522. #include <stdlib.h>
  1523. #include <stdio.h>
  1524. #include <string.h>
  1525. typedef struct cleanup_ent {
  1526. upb_cleanup_func *cleanup;
  1527. void *ud;
  1528. struct cleanup_ent *next;
  1529. } cleanup_ent;
  1530. static void *seeded_alloc(void *ud, void *ptr, size_t oldsize, size_t size);
  1531. /* Default allocator **********************************************************/
  1532. /* Just use realloc, keeping all allocated blocks in a linked list to destroy at
  1533. * the end. */
  1534. typedef struct mem_block {
  1535. /* List is doubly-linked, because in cases where realloc() moves an existing
  1536. * block, we need to be able to remove the old pointer from the list
  1537. * efficiently. */
  1538. struct mem_block *prev, *next;
  1539. #ifndef NDEBUG
  1540. size_t size; /* Doesn't include mem_block structure. */
  1541. #endif
  1542. } mem_block;
  1543. typedef struct {
  1544. mem_block *head;
  1545. } default_alloc_ud;
  1546. static void *default_alloc(void *_ud, void *ptr, size_t oldsize, size_t size) {
  1547. default_alloc_ud *ud = _ud;
  1548. mem_block *from, *block;
  1549. void *ret;
  1550. UPB_UNUSED(oldsize);
  1551. from = ptr ? (void*)((char*)ptr - sizeof(mem_block)) : NULL;
  1552. #ifndef NDEBUG
  1553. if (from) {
  1554. assert(oldsize <= from->size);
  1555. }
  1556. #endif
  1557. /* TODO(haberman): we probably need to provide even better alignment here,
  1558. * like 16-byte alignment of the returned data pointer. */
  1559. block = realloc(from, size + sizeof(mem_block));
  1560. if (!block) return NULL;
  1561. ret = (char*)block + sizeof(*block);
  1562. #ifndef NDEBUG
  1563. block->size = size;
  1564. #endif
  1565. if (from) {
  1566. if (block != from) {
  1567. /* The block was moved, so pointers in next and prev blocks must be
  1568. * updated to its new location. */
  1569. if (block->next) block->next->prev = block;
  1570. if (block->prev) block->prev->next = block;
  1571. if (ud->head == from) ud->head = block;
  1572. }
  1573. } else {
  1574. /* Insert at head of linked list. */
  1575. block->prev = NULL;
  1576. block->next = ud->head;
  1577. if (block->next) block->next->prev = block;
  1578. ud->head = block;
  1579. }
  1580. return ret;
  1581. }
  1582. static void default_alloc_cleanup(void *_ud) {
  1583. default_alloc_ud *ud = _ud;
  1584. mem_block *block = ud->head;
  1585. while (block) {
  1586. void *to_free = block;
  1587. block = block->next;
  1588. free(to_free);
  1589. }
  1590. }
  1591. /* Standard error functions ***************************************************/
  1592. static bool default_err(void *ud, const upb_status *status) {
  1593. UPB_UNUSED(ud);
  1594. UPB_UNUSED(status);
  1595. return false;
  1596. }
  1597. static bool write_err_to(void *ud, const upb_status *status) {
  1598. upb_status *copy_to = ud;
  1599. upb_status_copy(copy_to, status);
  1600. return false;
  1601. }
  1602. /* upb_env ********************************************************************/
  1603. void upb_env_init(upb_env *e) {
  1604. default_alloc_ud *ud = (default_alloc_ud*)&e->default_alloc_ud;
  1605. e->ok_ = true;
  1606. e->bytes_allocated = 0;
  1607. e->cleanup_head = NULL;
  1608. ud->head = NULL;
  1609. /* Set default functions. */
  1610. upb_env_setallocfunc(e, default_alloc, ud);
  1611. upb_env_seterrorfunc(e, default_err, NULL);
  1612. }
  1613. void upb_env_uninit(upb_env *e) {
  1614. cleanup_ent *ent = e->cleanup_head;
  1615. while (ent) {
  1616. ent->cleanup(ent->ud);
  1617. ent = ent->next;
  1618. }
  1619. /* Must do this after running cleanup functions, because this will delete
  1620. the memory we store our cleanup entries in! */
  1621. if (e->alloc == default_alloc) {
  1622. default_alloc_cleanup(e->alloc_ud);
  1623. }
  1624. }
  1625. UPB_FORCEINLINE void upb_env_setallocfunc(upb_env *e, upb_alloc_func *alloc,
  1626. void *ud) {
  1627. e->alloc = alloc;
  1628. e->alloc_ud = ud;
  1629. }
  1630. UPB_FORCEINLINE void upb_env_seterrorfunc(upb_env *e, upb_error_func *func,
  1631. void *ud) {
  1632. e->err = func;
  1633. e->err_ud = ud;
  1634. }
  1635. void upb_env_reporterrorsto(upb_env *e, upb_status *status) {
  1636. e->err = write_err_to;
  1637. e->err_ud = status;
  1638. }
  1639. bool upb_env_ok(const upb_env *e) {
  1640. return e->ok_;
  1641. }
  1642. bool upb_env_reporterror(upb_env *e, const upb_status *status) {
  1643. e->ok_ = false;
  1644. return e->err(e->err_ud, status);
  1645. }
  1646. bool upb_env_addcleanup(upb_env *e, upb_cleanup_func *func, void *ud) {
  1647. cleanup_ent *ent = upb_env_malloc(e, sizeof(cleanup_ent));
  1648. if (!ent) return false;
  1649. ent->cleanup = func;
  1650. ent->ud = ud;
  1651. ent->next = e->cleanup_head;
  1652. e->cleanup_head = ent;
  1653. return true;
  1654. }
  1655. void *upb_env_malloc(upb_env *e, size_t size) {
  1656. e->bytes_allocated += size;
  1657. if (e->alloc == seeded_alloc) {
  1658. /* This is equivalent to the next branch, but allows inlining for a
  1659. * measurable perf benefit. */
  1660. return seeded_alloc(e->alloc_ud, NULL, 0, size);
  1661. } else {
  1662. return e->alloc(e->alloc_ud, NULL, 0, size);
  1663. }
  1664. }
  1665. void *upb_env_realloc(upb_env *e, void *ptr, size_t oldsize, size_t size) {
  1666. char *ret;
  1667. assert(oldsize <= size);
  1668. ret = e->alloc(e->alloc_ud, ptr, oldsize, size);
  1669. #ifndef NDEBUG
  1670. /* Overwrite non-preserved memory to ensure callers are passing the oldsize
  1671. * that they truly require. */
  1672. memset(ret + oldsize, 0xff, size - oldsize);
  1673. #endif
  1674. return ret;
  1675. }
  1676. size_t upb_env_bytesallocated(const upb_env *e) {
  1677. return e->bytes_allocated;
  1678. }
  1679. /* upb_seededalloc ************************************************************/
  1680. /* Be conservative and choose 16 in case anyone is using SSE. */
  1681. static const size_t maxalign = 16;
  1682. static size_t align_up(size_t size) {
  1683. return ((size + maxalign - 1) / maxalign) * maxalign;
  1684. }
  1685. UPB_FORCEINLINE static void *seeded_alloc(void *ud, void *ptr, size_t oldsize,
  1686. size_t size) {
  1687. upb_seededalloc *a = ud;
  1688. size = align_up(size);
  1689. assert(a->mem_limit >= a->mem_ptr);
  1690. if (oldsize == 0 && size <= (size_t)(a->mem_limit - a->mem_ptr)) {
  1691. /* Fast path: we can satisfy from the initial allocation. */
  1692. void *ret = a->mem_ptr;
  1693. a->mem_ptr += size;
  1694. return ret;
  1695. } else {
  1696. char *chptr = ptr;
  1697. /* Slow path: fallback to other allocator. */
  1698. a->need_cleanup = true;
  1699. /* Is `ptr` part of the user-provided initial block? Don't pass it to the
  1700. * default allocator if so; otherwise, it may try to realloc() the block. */
  1701. if (chptr >= a->mem_base && chptr < a->mem_limit) {
  1702. void *ret;
  1703. assert(chptr + oldsize <= a->mem_limit);
  1704. ret = a->alloc(a->alloc_ud, NULL, 0, size);
  1705. if (ret) memcpy(ret, ptr, oldsize);
  1706. return ret;
  1707. } else {
  1708. return a->alloc(a->alloc_ud, ptr, oldsize, size);
  1709. }
  1710. }
  1711. }
  1712. void upb_seededalloc_init(upb_seededalloc *a, void *mem, size_t len) {
  1713. default_alloc_ud *ud = (default_alloc_ud*)&a->default_alloc_ud;
  1714. a->mem_base = mem;
  1715. a->mem_ptr = mem;
  1716. a->mem_limit = (char*)mem + len;
  1717. a->need_cleanup = false;
  1718. a->returned_allocfunc = false;
  1719. ud->head = NULL;
  1720. upb_seededalloc_setfallbackalloc(a, default_alloc, ud);
  1721. }
  1722. void upb_seededalloc_uninit(upb_seededalloc *a) {
  1723. if (a->alloc == default_alloc && a->need_cleanup) {
  1724. default_alloc_cleanup(a->alloc_ud);
  1725. }
  1726. }
  1727. UPB_FORCEINLINE void upb_seededalloc_setfallbackalloc(upb_seededalloc *a,
  1728. upb_alloc_func *alloc,
  1729. void *ud) {
  1730. assert(!a->returned_allocfunc);
  1731. a->alloc = alloc;
  1732. a->alloc_ud = ud;
  1733. }
  1734. upb_alloc_func *upb_seededalloc_getallocfunc(upb_seededalloc *a) {
  1735. a->returned_allocfunc = true;
  1736. return seeded_alloc;
  1737. }
  1738. /*
  1739. ** TODO(haberman): it's unclear whether a lot of the consistency checks should
  1740. ** assert() or return false.
  1741. */
  1742. #include <stdlib.h>
  1743. #include <string.h>
  1744. /* Defined for the sole purpose of having a unique pointer value for
  1745. * UPB_NO_CLOSURE. */
  1746. char _upb_noclosure;
  1747. static void freehandlers(upb_refcounted *r) {
  1748. upb_handlers *h = (upb_handlers*)r;
  1749. upb_inttable_iter i;
  1750. upb_inttable_begin(&i, &h->cleanup_);
  1751. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  1752. void *val = (void*)upb_inttable_iter_key(&i);
  1753. upb_value func_val = upb_inttable_iter_value(&i);
  1754. upb_handlerfree *func = upb_value_getfptr(func_val);
  1755. func(val);
  1756. }
  1757. upb_inttable_uninit(&h->cleanup_);
  1758. upb_msgdef_unref(h->msg, h);
  1759. free(h->sub);
  1760. free(h);
  1761. }
  1762. static void visithandlers(const upb_refcounted *r, upb_refcounted_visit *visit,
  1763. void *closure) {
  1764. const upb_handlers *h = (const upb_handlers*)r;
  1765. upb_msg_field_iter i;
  1766. for(upb_msg_field_begin(&i, h->msg);
  1767. !upb_msg_field_done(&i);
  1768. upb_msg_field_next(&i)) {
  1769. upb_fielddef *f = upb_msg_iter_field(&i);
  1770. const upb_handlers *sub;
  1771. if (!upb_fielddef_issubmsg(f)) continue;
  1772. sub = upb_handlers_getsubhandlers(h, f);
  1773. if (sub) visit(r, upb_handlers_upcast(sub), closure);
  1774. }
  1775. }
  1776. static const struct upb_refcounted_vtbl vtbl = {visithandlers, freehandlers};
  1777. typedef struct {
  1778. upb_inttable tab; /* maps upb_msgdef* -> upb_handlers*. */
  1779. upb_handlers_callback *callback;
  1780. const void *closure;
  1781. } dfs_state;
  1782. /* TODO(haberman): discard upb_handlers* objects that do not actually have any
  1783. * handlers set and cannot reach any upb_handlers* object that does. This is
  1784. * slightly tricky to do correctly. */
  1785. static upb_handlers *newformsg(const upb_msgdef *m, const void *owner,
  1786. dfs_state *s) {
  1787. upb_msg_field_iter i;
  1788. upb_handlers *h = upb_handlers_new(m, owner);
  1789. if (!h) return NULL;
  1790. if (!upb_inttable_insertptr(&s->tab, m, upb_value_ptr(h))) goto oom;
  1791. s->callback(s->closure, h);
  1792. /* For each submessage field, get or create a handlers object and set it as
  1793. * the subhandlers. */
  1794. for(upb_msg_field_begin(&i, m);
  1795. !upb_msg_field_done(&i);
  1796. upb_msg_field_next(&i)) {
  1797. upb_fielddef *f = upb_msg_iter_field(&i);
  1798. const upb_msgdef *subdef;
  1799. upb_value subm_ent;
  1800. if (!upb_fielddef_issubmsg(f)) continue;
  1801. subdef = upb_downcast_msgdef(upb_fielddef_subdef(f));
  1802. if (upb_inttable_lookupptr(&s->tab, subdef, &subm_ent)) {
  1803. upb_handlers_setsubhandlers(h, f, upb_value_getptr(subm_ent));
  1804. } else {
  1805. upb_handlers *sub_mh = newformsg(subdef, &sub_mh, s);
  1806. if (!sub_mh) goto oom;
  1807. upb_handlers_setsubhandlers(h, f, sub_mh);
  1808. upb_handlers_unref(sub_mh, &sub_mh);
  1809. }
  1810. }
  1811. return h;
  1812. oom:
  1813. upb_handlers_unref(h, owner);
  1814. return NULL;
  1815. }
  1816. /* Given a selector for a STARTSUBMSG handler, resolves to a pointer to the
  1817. * subhandlers for this submessage field. */
  1818. #define SUBH(h, selector) (h->sub[selector])
  1819. /* The selector for a submessage field is the field index. */
  1820. #define SUBH_F(h, f) SUBH(h, f->index_)
  1821. static int32_t trygetsel(upb_handlers *h, const upb_fielddef *f,
  1822. upb_handlertype_t type) {
  1823. upb_selector_t sel;
  1824. assert(!upb_handlers_isfrozen(h));
  1825. if (upb_handlers_msgdef(h) != upb_fielddef_containingtype(f)) {
  1826. upb_status_seterrf(
  1827. &h->status_, "type mismatch: field %s does not belong to message %s",
  1828. upb_fielddef_name(f), upb_msgdef_fullname(upb_handlers_msgdef(h)));
  1829. return -1;
  1830. }
  1831. if (!upb_handlers_getselector(f, type, &sel)) {
  1832. upb_status_seterrf(
  1833. &h->status_,
  1834. "type mismatch: cannot register handler type %d for field %s",
  1835. type, upb_fielddef_name(f));
  1836. return -1;
  1837. }
  1838. return sel;
  1839. }
  1840. static upb_selector_t handlers_getsel(upb_handlers *h, const upb_fielddef *f,
  1841. upb_handlertype_t type) {
  1842. int32_t sel = trygetsel(h, f, type);
  1843. assert(sel >= 0);
  1844. return sel;
  1845. }
  1846. static const void **returntype(upb_handlers *h, const upb_fielddef *f,
  1847. upb_handlertype_t type) {
  1848. return &h->table[handlers_getsel(h, f, type)].attr.return_closure_type_;
  1849. }
  1850. static bool doset(upb_handlers *h, int32_t sel, const upb_fielddef *f,
  1851. upb_handlertype_t type, upb_func *func,
  1852. upb_handlerattr *attr) {
  1853. upb_handlerattr set_attr = UPB_HANDLERATTR_INITIALIZER;
  1854. const void *closure_type;
  1855. const void **context_closure_type;
  1856. assert(!upb_handlers_isfrozen(h));
  1857. if (sel < 0) {
  1858. upb_status_seterrmsg(&h->status_,
  1859. "incorrect handler type for this field.");
  1860. return false;
  1861. }
  1862. if (h->table[sel].func) {
  1863. upb_status_seterrmsg(&h->status_,
  1864. "cannot change handler once it has been set.");
  1865. return false;
  1866. }
  1867. if (attr) {
  1868. set_attr = *attr;
  1869. }
  1870. /* Check that the given closure type matches the closure type that has been
  1871. * established for this context (if any). */
  1872. closure_type = upb_handlerattr_closuretype(&set_attr);
  1873. if (type == UPB_HANDLER_STRING) {
  1874. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSTR);
  1875. } else if (f && upb_fielddef_isseq(f) &&
  1876. type != UPB_HANDLER_STARTSEQ &&
  1877. type != UPB_HANDLER_ENDSEQ) {
  1878. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSEQ);
  1879. } else {
  1880. context_closure_type = &h->top_closure_type;
  1881. }
  1882. if (closure_type && *context_closure_type &&
  1883. closure_type != *context_closure_type) {
  1884. /* TODO(haberman): better message for debugging. */
  1885. if (f) {
  1886. upb_status_seterrf(&h->status_,
  1887. "closure type does not match for field %s",
  1888. upb_fielddef_name(f));
  1889. } else {
  1890. upb_status_seterrmsg(
  1891. &h->status_, "closure type does not match for message-level handler");
  1892. }
  1893. return false;
  1894. }
  1895. if (closure_type)
  1896. *context_closure_type = closure_type;
  1897. /* If this is a STARTSEQ or STARTSTR handler, check that the returned pointer
  1898. * matches any pre-existing expectations about what type is expected. */
  1899. if (type == UPB_HANDLER_STARTSEQ || type == UPB_HANDLER_STARTSTR) {
  1900. const void *return_type = upb_handlerattr_returnclosuretype(&set_attr);
  1901. const void *table_return_type =
  1902. upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1903. if (return_type && table_return_type && return_type != table_return_type) {
  1904. upb_status_seterrmsg(&h->status_, "closure return type does not match");
  1905. return false;
  1906. }
  1907. if (table_return_type && !return_type)
  1908. upb_handlerattr_setreturnclosuretype(&set_attr, table_return_type);
  1909. }
  1910. h->table[sel].func = (upb_func*)func;
  1911. h->table[sel].attr = set_attr;
  1912. return true;
  1913. }
  1914. /* Returns the effective closure type for this handler (which will propagate
  1915. * from outer frames if this frame has no START* handler). Not implemented for
  1916. * UPB_HANDLER_STRING at the moment since this is not needed. Returns NULL is
  1917. * the effective closure type is unspecified (either no handler was registered
  1918. * to specify it or the handler that was registered did not specify the closure
  1919. * type). */
  1920. const void *effective_closure_type(upb_handlers *h, const upb_fielddef *f,
  1921. upb_handlertype_t type) {
  1922. const void *ret;
  1923. upb_selector_t sel;
  1924. assert(type != UPB_HANDLER_STRING);
  1925. ret = h->top_closure_type;
  1926. if (upb_fielddef_isseq(f) &&
  1927. type != UPB_HANDLER_STARTSEQ &&
  1928. type != UPB_HANDLER_ENDSEQ &&
  1929. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)].func) {
  1930. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1931. }
  1932. if (type == UPB_HANDLER_STRING &&
  1933. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSTR)].func) {
  1934. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1935. }
  1936. /* The effective type of the submessage; not used yet.
  1937. * if (type == SUBMESSAGE &&
  1938. * h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)].func) {
  1939. * ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1940. * } */
  1941. return ret;
  1942. }
  1943. /* Checks whether the START* handler specified by f & type is missing even
  1944. * though it is required to convert the established type of an outer frame
  1945. * ("closure_type") into the established type of an inner frame (represented in
  1946. * the return closure type of this handler's attr. */
  1947. bool checkstart(upb_handlers *h, const upb_fielddef *f, upb_handlertype_t type,
  1948. upb_status *status) {
  1949. const void *closure_type;
  1950. const upb_handlerattr *attr;
  1951. const void *return_closure_type;
  1952. upb_selector_t sel = handlers_getsel(h, f, type);
  1953. if (h->table[sel].func) return true;
  1954. closure_type = effective_closure_type(h, f, type);
  1955. attr = &h->table[sel].attr;
  1956. return_closure_type = upb_handlerattr_returnclosuretype(attr);
  1957. if (closure_type && return_closure_type &&
  1958. closure_type != return_closure_type) {
  1959. upb_status_seterrf(status,
  1960. "expected start handler to return sub type for field %f",
  1961. upb_fielddef_name(f));
  1962. return false;
  1963. }
  1964. return true;
  1965. }
  1966. /* Public interface ***********************************************************/
  1967. upb_handlers *upb_handlers_new(const upb_msgdef *md, const void *owner) {
  1968. int extra;
  1969. upb_handlers *h;
  1970. assert(upb_msgdef_isfrozen(md));
  1971. extra = sizeof(upb_handlers_tabent) * (md->selector_count - 1);
  1972. h = calloc(sizeof(*h) + extra, 1);
  1973. if (!h) return NULL;
  1974. h->msg = md;
  1975. upb_msgdef_ref(h->msg, h);
  1976. upb_status_clear(&h->status_);
  1977. h->sub = calloc(md->submsg_field_count, sizeof(*h->sub));
  1978. if (!h->sub) goto oom;
  1979. if (!upb_refcounted_init(upb_handlers_upcast_mutable(h), &vtbl, owner))
  1980. goto oom;
  1981. if (!upb_inttable_init(&h->cleanup_, UPB_CTYPE_FPTR)) goto oom;
  1982. /* calloc() above initialized all handlers to NULL. */
  1983. return h;
  1984. oom:
  1985. freehandlers(upb_handlers_upcast_mutable(h));
  1986. return NULL;
  1987. }
  1988. const upb_handlers *upb_handlers_newfrozen(const upb_msgdef *m,
  1989. const void *owner,
  1990. upb_handlers_callback *callback,
  1991. const void *closure) {
  1992. dfs_state state;
  1993. upb_handlers *ret;
  1994. bool ok;
  1995. upb_refcounted *r;
  1996. state.callback = callback;
  1997. state.closure = closure;
  1998. if (!upb_inttable_init(&state.tab, UPB_CTYPE_PTR)) return NULL;
  1999. ret = newformsg(m, owner, &state);
  2000. upb_inttable_uninit(&state.tab);
  2001. if (!ret) return NULL;
  2002. r = upb_handlers_upcast_mutable(ret);
  2003. ok = upb_refcounted_freeze(&r, 1, NULL, UPB_MAX_HANDLER_DEPTH);
  2004. UPB_ASSERT_VAR(ok, ok);
  2005. return ret;
  2006. }
  2007. const upb_status *upb_handlers_status(upb_handlers *h) {
  2008. assert(!upb_handlers_isfrozen(h));
  2009. return &h->status_;
  2010. }
  2011. void upb_handlers_clearerr(upb_handlers *h) {
  2012. assert(!upb_handlers_isfrozen(h));
  2013. upb_status_clear(&h->status_);
  2014. }
  2015. #define SETTER(name, handlerctype, handlertype) \
  2016. bool upb_handlers_set ## name(upb_handlers *h, const upb_fielddef *f, \
  2017. handlerctype func, upb_handlerattr *attr) { \
  2018. int32_t sel = trygetsel(h, f, handlertype); \
  2019. return doset(h, sel, f, handlertype, (upb_func*)func, attr); \
  2020. }
  2021. SETTER(int32, upb_int32_handlerfunc*, UPB_HANDLER_INT32)
  2022. SETTER(int64, upb_int64_handlerfunc*, UPB_HANDLER_INT64)
  2023. SETTER(uint32, upb_uint32_handlerfunc*, UPB_HANDLER_UINT32)
  2024. SETTER(uint64, upb_uint64_handlerfunc*, UPB_HANDLER_UINT64)
  2025. SETTER(float, upb_float_handlerfunc*, UPB_HANDLER_FLOAT)
  2026. SETTER(double, upb_double_handlerfunc*, UPB_HANDLER_DOUBLE)
  2027. SETTER(bool, upb_bool_handlerfunc*, UPB_HANDLER_BOOL)
  2028. SETTER(startstr, upb_startstr_handlerfunc*, UPB_HANDLER_STARTSTR)
  2029. SETTER(string, upb_string_handlerfunc*, UPB_HANDLER_STRING)
  2030. SETTER(endstr, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSTR)
  2031. SETTER(startseq, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSEQ)
  2032. SETTER(startsubmsg, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSUBMSG)
  2033. SETTER(endsubmsg, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSUBMSG)
  2034. SETTER(endseq, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSEQ)
  2035. #undef SETTER
  2036. bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
  2037. upb_handlerattr *attr) {
  2038. return doset(h, UPB_STARTMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  2039. (upb_func *)func, attr);
  2040. }
  2041. bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func,
  2042. upb_handlerattr *attr) {
  2043. assert(!upb_handlers_isfrozen(h));
  2044. return doset(h, UPB_ENDMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  2045. (upb_func *)func, attr);
  2046. }
  2047. bool upb_handlers_setsubhandlers(upb_handlers *h, const upb_fielddef *f,
  2048. const upb_handlers *sub) {
  2049. assert(sub);
  2050. assert(!upb_handlers_isfrozen(h));
  2051. assert(upb_fielddef_issubmsg(f));
  2052. if (SUBH_F(h, f)) return false; /* Can't reset. */
  2053. if (upb_msgdef_upcast(upb_handlers_msgdef(sub)) != upb_fielddef_subdef(f)) {
  2054. return false;
  2055. }
  2056. SUBH_F(h, f) = sub;
  2057. upb_ref2(sub, h);
  2058. return true;
  2059. }
  2060. const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h,
  2061. const upb_fielddef *f) {
  2062. assert(upb_fielddef_issubmsg(f));
  2063. return SUBH_F(h, f);
  2064. }
  2065. bool upb_handlers_getattr(const upb_handlers *h, upb_selector_t sel,
  2066. upb_handlerattr *attr) {
  2067. if (!upb_handlers_gethandler(h, sel))
  2068. return false;
  2069. *attr = h->table[sel].attr;
  2070. return true;
  2071. }
  2072. const upb_handlers *upb_handlers_getsubhandlers_sel(const upb_handlers *h,
  2073. upb_selector_t sel) {
  2074. /* STARTSUBMSG selector in sel is the field's selector base. */
  2075. return SUBH(h, sel - UPB_STATIC_SELECTOR_COUNT);
  2076. }
  2077. const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h) { return h->msg; }
  2078. bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *func) {
  2079. bool ok;
  2080. if (upb_inttable_lookupptr(&h->cleanup_, p, NULL)) {
  2081. return false;
  2082. }
  2083. ok = upb_inttable_insertptr(&h->cleanup_, p, upb_value_fptr(func));
  2084. UPB_ASSERT_VAR(ok, ok);
  2085. return true;
  2086. }
  2087. /* "Static" methods ***********************************************************/
  2088. bool upb_handlers_freeze(upb_handlers *const*handlers, int n, upb_status *s) {
  2089. /* TODO: verify we have a transitive closure. */
  2090. int i;
  2091. for (i = 0; i < n; i++) {
  2092. upb_msg_field_iter j;
  2093. upb_handlers *h = handlers[i];
  2094. if (!upb_ok(&h->status_)) {
  2095. upb_status_seterrf(s, "handlers for message %s had error status: %s",
  2096. upb_msgdef_fullname(upb_handlers_msgdef(h)),
  2097. upb_status_errmsg(&h->status_));
  2098. return false;
  2099. }
  2100. /* Check that there are no closure mismatches due to missing Start* handlers
  2101. * or subhandlers with different type-level types. */
  2102. for(upb_msg_field_begin(&j, h->msg);
  2103. !upb_msg_field_done(&j);
  2104. upb_msg_field_next(&j)) {
  2105. const upb_fielddef *f = upb_msg_iter_field(&j);
  2106. if (upb_fielddef_isseq(f)) {
  2107. if (!checkstart(h, f, UPB_HANDLER_STARTSEQ, s))
  2108. return false;
  2109. }
  2110. if (upb_fielddef_isstring(f)) {
  2111. if (!checkstart(h, f, UPB_HANDLER_STARTSTR, s))
  2112. return false;
  2113. }
  2114. if (upb_fielddef_issubmsg(f)) {
  2115. bool hashandler = false;
  2116. if (upb_handlers_gethandler(
  2117. h, handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)) ||
  2118. upb_handlers_gethandler(
  2119. h, handlers_getsel(h, f, UPB_HANDLER_ENDSUBMSG))) {
  2120. hashandler = true;
  2121. }
  2122. if (upb_fielddef_isseq(f) &&
  2123. (upb_handlers_gethandler(
  2124. h, handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)) ||
  2125. upb_handlers_gethandler(
  2126. h, handlers_getsel(h, f, UPB_HANDLER_ENDSEQ)))) {
  2127. hashandler = true;
  2128. }
  2129. if (hashandler && !upb_handlers_getsubhandlers(h, f)) {
  2130. /* For now we add an empty subhandlers in this case. It makes the
  2131. * decoder code generator simpler, because it only has to handle two
  2132. * cases (submessage has handlers or not) as opposed to three
  2133. * (submessage has handlers in enclosing message but no subhandlers).
  2134. *
  2135. * This makes parsing less efficient in the case that we want to
  2136. * notice a submessage but skip its contents (like if we're testing
  2137. * for submessage presence or counting the number of repeated
  2138. * submessages). In this case we will end up parsing the submessage
  2139. * field by field and throwing away the results for each, instead of
  2140. * skipping the whole delimited thing at once. If this is an issue we
  2141. * can revisit it, but do remember that this only arises when you have
  2142. * handlers (startseq/startsubmsg/endsubmsg/endseq) set for the
  2143. * submessage but no subhandlers. The uses cases for this are
  2144. * limited. */
  2145. upb_handlers *sub = upb_handlers_new(upb_fielddef_msgsubdef(f), &sub);
  2146. upb_handlers_setsubhandlers(h, f, sub);
  2147. upb_handlers_unref(sub, &sub);
  2148. }
  2149. /* TODO(haberman): check type of submessage.
  2150. * This is slightly tricky; also consider whether we should check that
  2151. * they match at setsubhandlers time. */
  2152. }
  2153. }
  2154. }
  2155. if (!upb_refcounted_freeze((upb_refcounted*const*)handlers, n, s,
  2156. UPB_MAX_HANDLER_DEPTH)) {
  2157. return false;
  2158. }
  2159. return true;
  2160. }
  2161. upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f) {
  2162. switch (upb_fielddef_type(f)) {
  2163. case UPB_TYPE_INT32:
  2164. case UPB_TYPE_ENUM: return UPB_HANDLER_INT32;
  2165. case UPB_TYPE_INT64: return UPB_HANDLER_INT64;
  2166. case UPB_TYPE_UINT32: return UPB_HANDLER_UINT32;
  2167. case UPB_TYPE_UINT64: return UPB_HANDLER_UINT64;
  2168. case UPB_TYPE_FLOAT: return UPB_HANDLER_FLOAT;
  2169. case UPB_TYPE_DOUBLE: return UPB_HANDLER_DOUBLE;
  2170. case UPB_TYPE_BOOL: return UPB_HANDLER_BOOL;
  2171. default: assert(false); return -1; /* Invalid input. */
  2172. }
  2173. }
  2174. bool upb_handlers_getselector(const upb_fielddef *f, upb_handlertype_t type,
  2175. upb_selector_t *s) {
  2176. switch (type) {
  2177. case UPB_HANDLER_INT32:
  2178. case UPB_HANDLER_INT64:
  2179. case UPB_HANDLER_UINT32:
  2180. case UPB_HANDLER_UINT64:
  2181. case UPB_HANDLER_FLOAT:
  2182. case UPB_HANDLER_DOUBLE:
  2183. case UPB_HANDLER_BOOL:
  2184. if (!upb_fielddef_isprimitive(f) ||
  2185. upb_handlers_getprimitivehandlertype(f) != type)
  2186. return false;
  2187. *s = f->selector_base;
  2188. break;
  2189. case UPB_HANDLER_STRING:
  2190. if (upb_fielddef_isstring(f)) {
  2191. *s = f->selector_base;
  2192. } else if (upb_fielddef_lazy(f)) {
  2193. *s = f->selector_base + 3;
  2194. } else {
  2195. return false;
  2196. }
  2197. break;
  2198. case UPB_HANDLER_STARTSTR:
  2199. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  2200. *s = f->selector_base + 1;
  2201. } else {
  2202. return false;
  2203. }
  2204. break;
  2205. case UPB_HANDLER_ENDSTR:
  2206. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  2207. *s = f->selector_base + 2;
  2208. } else {
  2209. return false;
  2210. }
  2211. break;
  2212. case UPB_HANDLER_STARTSEQ:
  2213. if (!upb_fielddef_isseq(f)) return false;
  2214. *s = f->selector_base - 2;
  2215. break;
  2216. case UPB_HANDLER_ENDSEQ:
  2217. if (!upb_fielddef_isseq(f)) return false;
  2218. *s = f->selector_base - 1;
  2219. break;
  2220. case UPB_HANDLER_STARTSUBMSG:
  2221. if (!upb_fielddef_issubmsg(f)) return false;
  2222. /* Selectors for STARTSUBMSG are at the beginning of the table so that the
  2223. * selector can also be used as an index into the "sub" array of
  2224. * subhandlers. The indexes for the two into these two tables are the
  2225. * same, except that in the handler table the static selectors come first. */
  2226. *s = f->index_ + UPB_STATIC_SELECTOR_COUNT;
  2227. break;
  2228. case UPB_HANDLER_ENDSUBMSG:
  2229. if (!upb_fielddef_issubmsg(f)) return false;
  2230. *s = f->selector_base;
  2231. break;
  2232. }
  2233. assert((size_t)*s < upb_fielddef_containingtype(f)->selector_count);
  2234. return true;
  2235. }
  2236. uint32_t upb_handlers_selectorbaseoffset(const upb_fielddef *f) {
  2237. return upb_fielddef_isseq(f) ? 2 : 0;
  2238. }
  2239. uint32_t upb_handlers_selectorcount(const upb_fielddef *f) {
  2240. uint32_t ret = 1;
  2241. if (upb_fielddef_isseq(f)) ret += 2; /* STARTSEQ/ENDSEQ */
  2242. if (upb_fielddef_isstring(f)) ret += 2; /* [STRING]/STARTSTR/ENDSTR */
  2243. if (upb_fielddef_issubmsg(f)) {
  2244. /* ENDSUBMSG (STARTSUBMSG is at table beginning) */
  2245. ret += 0;
  2246. if (upb_fielddef_lazy(f)) {
  2247. /* STARTSTR/ENDSTR/STRING (for lazy) */
  2248. ret += 3;
  2249. }
  2250. }
  2251. return ret;
  2252. }
  2253. /* upb_handlerattr ************************************************************/
  2254. void upb_handlerattr_init(upb_handlerattr *attr) {
  2255. upb_handlerattr from = UPB_HANDLERATTR_INITIALIZER;
  2256. memcpy(attr, &from, sizeof(*attr));
  2257. }
  2258. void upb_handlerattr_uninit(upb_handlerattr *attr) {
  2259. UPB_UNUSED(attr);
  2260. }
  2261. bool upb_handlerattr_sethandlerdata(upb_handlerattr *attr, const void *hd) {
  2262. attr->handler_data_ = hd;
  2263. return true;
  2264. }
  2265. bool upb_handlerattr_setclosuretype(upb_handlerattr *attr, const void *type) {
  2266. attr->closure_type_ = type;
  2267. return true;
  2268. }
  2269. const void *upb_handlerattr_closuretype(const upb_handlerattr *attr) {
  2270. return attr->closure_type_;
  2271. }
  2272. bool upb_handlerattr_setreturnclosuretype(upb_handlerattr *attr,
  2273. const void *type) {
  2274. attr->return_closure_type_ = type;
  2275. return true;
  2276. }
  2277. const void *upb_handlerattr_returnclosuretype(const upb_handlerattr *attr) {
  2278. return attr->return_closure_type_;
  2279. }
  2280. bool upb_handlerattr_setalwaysok(upb_handlerattr *attr, bool alwaysok) {
  2281. attr->alwaysok_ = alwaysok;
  2282. return true;
  2283. }
  2284. bool upb_handlerattr_alwaysok(const upb_handlerattr *attr) {
  2285. return attr->alwaysok_;
  2286. }
  2287. /* upb_bufhandle **************************************************************/
  2288. size_t upb_bufhandle_objofs(const upb_bufhandle *h) {
  2289. return h->objofs_;
  2290. }
  2291. /* upb_byteshandler ***********************************************************/
  2292. void upb_byteshandler_init(upb_byteshandler* h) {
  2293. memset(h, 0, sizeof(*h));
  2294. }
  2295. /* For when we support handlerfree callbacks. */
  2296. void upb_byteshandler_uninit(upb_byteshandler* h) {
  2297. UPB_UNUSED(h);
  2298. }
  2299. bool upb_byteshandler_setstartstr(upb_byteshandler *h,
  2300. upb_startstr_handlerfunc *func, void *d) {
  2301. h->table[UPB_STARTSTR_SELECTOR].func = (upb_func*)func;
  2302. h->table[UPB_STARTSTR_SELECTOR].attr.handler_data_ = d;
  2303. return true;
  2304. }
  2305. bool upb_byteshandler_setstring(upb_byteshandler *h,
  2306. upb_string_handlerfunc *func, void *d) {
  2307. h->table[UPB_STRING_SELECTOR].func = (upb_func*)func;
  2308. h->table[UPB_STRING_SELECTOR].attr.handler_data_ = d;
  2309. return true;
  2310. }
  2311. bool upb_byteshandler_setendstr(upb_byteshandler *h,
  2312. upb_endfield_handlerfunc *func, void *d) {
  2313. h->table[UPB_ENDSTR_SELECTOR].func = (upb_func*)func;
  2314. h->table[UPB_ENDSTR_SELECTOR].attr.handler_data_ = d;
  2315. return true;
  2316. }
  2317. /*
  2318. ** upb::RefCounted Implementation
  2319. **
  2320. ** Our key invariants are:
  2321. ** 1. reference cycles never span groups
  2322. ** 2. for ref2(to, from), we increment to's count iff group(from) != group(to)
  2323. **
  2324. ** The previous two are how we avoid leaking cycles. Other important
  2325. ** invariants are:
  2326. ** 3. for mutable objects "from" and "to", if there exists a ref2(to, from)
  2327. ** this implies group(from) == group(to). (In practice, what we implement
  2328. ** is even stronger; "from" and "to" will share a group if there has *ever*
  2329. ** been a ref2(to, from), but all that is necessary for correctness is the
  2330. ** weaker one).
  2331. ** 4. mutable and immutable objects are never in the same group.
  2332. */
  2333. #include <setjmp.h>
  2334. #include <stdlib.h>
  2335. static void freeobj(upb_refcounted *o);
  2336. const char untracked_val;
  2337. const void *UPB_UNTRACKED_REF = &untracked_val;
  2338. /* arch-specific atomic primitives *******************************************/
  2339. #ifdef UPB_THREAD_UNSAFE /*---------------------------------------------------*/
  2340. static void atomic_inc(uint32_t *a) { (*a)++; }
  2341. static bool atomic_dec(uint32_t *a) { return --(*a) == 0; }
  2342. #elif defined(__GNUC__) || defined(__clang__) /*------------------------------*/
  2343. static void atomic_inc(uint32_t *a) { __sync_fetch_and_add(a, 1); }
  2344. static bool atomic_dec(uint32_t *a) { return __sync_sub_and_fetch(a, 1) == 0; }
  2345. #elif defined(WIN32) /*-------------------------------------------------------*/
  2346. #include <Windows.h>
  2347. static void atomic_inc(upb_atomic_t *a) { InterlockedIncrement(&a->val); }
  2348. static bool atomic_dec(upb_atomic_t *a) {
  2349. return InterlockedDecrement(&a->val) == 0;
  2350. }
  2351. #else
  2352. #error Atomic primitives not defined for your platform/CPU. \
  2353. Implement them or compile with UPB_THREAD_UNSAFE.
  2354. #endif
  2355. /* All static objects point to this refcount.
  2356. * It is special-cased in ref/unref below. */
  2357. uint32_t static_refcount = -1;
  2358. /* We can avoid atomic ops for statically-declared objects.
  2359. * This is a minor optimization but nice since we can avoid degrading under
  2360. * contention in this case. */
  2361. static void refgroup(uint32_t *group) {
  2362. if (group != &static_refcount)
  2363. atomic_inc(group);
  2364. }
  2365. static bool unrefgroup(uint32_t *group) {
  2366. if (group == &static_refcount) {
  2367. return false;
  2368. } else {
  2369. return atomic_dec(group);
  2370. }
  2371. }
  2372. /* Reference tracking (debug only) ********************************************/
  2373. #ifdef UPB_DEBUG_REFS
  2374. #ifdef UPB_THREAD_UNSAFE
  2375. static void upb_lock() {}
  2376. static void upb_unlock() {}
  2377. #else
  2378. /* User must define functions that lock/unlock a global mutex and link this
  2379. * file against them. */
  2380. void upb_lock();
  2381. void upb_unlock();
  2382. #endif
  2383. /* UPB_DEBUG_REFS mode counts on being able to malloc() memory in some
  2384. * code-paths that can normally never fail, like upb_refcounted_ref(). Since
  2385. * we have no way to propagage out-of-memory errors back to the user, and since
  2386. * these errors can only occur in UPB_DEBUG_REFS mode, we immediately fail. */
  2387. #define CHECK_OOM(predicate) if (!(predicate)) { assert(predicate); exit(1); }
  2388. typedef struct {
  2389. int count; /* How many refs there are (duplicates only allowed for ref2). */
  2390. bool is_ref2;
  2391. } trackedref;
  2392. static trackedref *trackedref_new(bool is_ref2) {
  2393. trackedref *ret = malloc(sizeof(*ret));
  2394. CHECK_OOM(ret);
  2395. ret->count = 1;
  2396. ret->is_ref2 = is_ref2;
  2397. return ret;
  2398. }
  2399. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  2400. upb_value v;
  2401. assert(owner);
  2402. if (owner == UPB_UNTRACKED_REF) return;
  2403. upb_lock();
  2404. if (upb_inttable_lookupptr(r->refs, owner, &v)) {
  2405. trackedref *ref = upb_value_getptr(v);
  2406. /* Since we allow multiple ref2's for the same to/from pair without
  2407. * allocating separate memory for each one, we lose the fine-grained
  2408. * tracking behavior we get with regular refs. Since ref2s only happen
  2409. * inside upb, we'll accept this limitation until/unless there is a really
  2410. * difficult upb-internal bug that can't be figured out without it. */
  2411. assert(ref2);
  2412. assert(ref->is_ref2);
  2413. ref->count++;
  2414. } else {
  2415. trackedref *ref = trackedref_new(ref2);
  2416. bool ok = upb_inttable_insertptr(r->refs, owner, upb_value_ptr(ref));
  2417. CHECK_OOM(ok);
  2418. if (ref2) {
  2419. /* We know this cast is safe when it is a ref2, because it's coming from
  2420. * another refcounted object. */
  2421. const upb_refcounted *from = owner;
  2422. assert(!upb_inttable_lookupptr(from->ref2s, r, NULL));
  2423. ok = upb_inttable_insertptr(from->ref2s, r, upb_value_ptr(NULL));
  2424. CHECK_OOM(ok);
  2425. }
  2426. }
  2427. upb_unlock();
  2428. }
  2429. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  2430. upb_value v;
  2431. bool found;
  2432. trackedref *ref;
  2433. assert(owner);
  2434. if (owner == UPB_UNTRACKED_REF) return;
  2435. upb_lock();
  2436. found = upb_inttable_lookupptr(r->refs, owner, &v);
  2437. /* This assert will fail if an owner attempts to release a ref it didn't have. */
  2438. UPB_ASSERT_VAR(found, found);
  2439. ref = upb_value_getptr(v);
  2440. assert(ref->is_ref2 == ref2);
  2441. if (--ref->count == 0) {
  2442. free(ref);
  2443. upb_inttable_removeptr(r->refs, owner, NULL);
  2444. if (ref2) {
  2445. /* We know this cast is safe when it is a ref2, because it's coming from
  2446. * another refcounted object. */
  2447. const upb_refcounted *from = owner;
  2448. bool removed = upb_inttable_removeptr(from->ref2s, r, NULL);
  2449. assert(removed);
  2450. }
  2451. }
  2452. upb_unlock();
  2453. }
  2454. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  2455. upb_value v;
  2456. bool found;
  2457. trackedref *ref;
  2458. upb_lock();
  2459. found = upb_inttable_lookupptr(r->refs, owner, &v);
  2460. UPB_ASSERT_VAR(found, found);
  2461. ref = upb_value_getptr(v);
  2462. assert(ref->is_ref2 == ref2);
  2463. upb_unlock();
  2464. }
  2465. /* Populates the given UPB_CTYPE_INT32 inttable with counts of ref2's that
  2466. * originate from the given owner. */
  2467. static void getref2s(const upb_refcounted *owner, upb_inttable *tab) {
  2468. upb_inttable_iter i;
  2469. upb_lock();
  2470. upb_inttable_begin(&i, owner->ref2s);
  2471. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  2472. upb_value v;
  2473. upb_value count;
  2474. trackedref *ref;
  2475. bool ok;
  2476. bool found;
  2477. upb_refcounted *to = (upb_refcounted*)upb_inttable_iter_key(&i);
  2478. /* To get the count we need to look in the target's table. */
  2479. found = upb_inttable_lookupptr(to->refs, owner, &v);
  2480. assert(found);
  2481. ref = upb_value_getptr(v);
  2482. count = upb_value_int32(ref->count);
  2483. ok = upb_inttable_insertptr(tab, to, count);
  2484. CHECK_OOM(ok);
  2485. }
  2486. upb_unlock();
  2487. }
  2488. typedef struct {
  2489. upb_inttable ref2;
  2490. const upb_refcounted *obj;
  2491. } check_state;
  2492. static void visit_check(const upb_refcounted *obj, const upb_refcounted *subobj,
  2493. void *closure) {
  2494. check_state *s = closure;
  2495. upb_inttable *ref2 = &s->ref2;
  2496. upb_value v;
  2497. bool removed;
  2498. int32_t newcount;
  2499. assert(obj == s->obj);
  2500. assert(subobj);
  2501. removed = upb_inttable_removeptr(ref2, subobj, &v);
  2502. /* The following assertion will fail if the visit() function visits a subobj
  2503. * that it did not have a ref2 on, or visits the same subobj too many times. */
  2504. assert(removed);
  2505. newcount = upb_value_getint32(v) - 1;
  2506. if (newcount > 0) {
  2507. upb_inttable_insert(ref2, (uintptr_t)subobj, upb_value_int32(newcount));
  2508. }
  2509. }
  2510. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  2511. void *closure) {
  2512. bool ok;
  2513. /* In DEBUG_REFS mode we know what existing ref2 refs there are, so we know
  2514. * exactly the set of nodes that visit() should visit. So we verify visit()'s
  2515. * correctness here. */
  2516. check_state state;
  2517. state.obj = r;
  2518. ok = upb_inttable_init(&state.ref2, UPB_CTYPE_INT32);
  2519. CHECK_OOM(ok);
  2520. getref2s(r, &state.ref2);
  2521. /* This should visit any children in the ref2 table. */
  2522. if (r->vtbl->visit) r->vtbl->visit(r, visit_check, &state);
  2523. /* This assertion will fail if the visit() function missed any children. */
  2524. assert(upb_inttable_count(&state.ref2) == 0);
  2525. upb_inttable_uninit(&state.ref2);
  2526. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  2527. }
  2528. static bool trackinit(upb_refcounted *r) {
  2529. r->refs = malloc(sizeof(*r->refs));
  2530. r->ref2s = malloc(sizeof(*r->ref2s));
  2531. if (!r->refs || !r->ref2s) goto err1;
  2532. if (!upb_inttable_init(r->refs, UPB_CTYPE_PTR)) goto err1;
  2533. if (!upb_inttable_init(r->ref2s, UPB_CTYPE_PTR)) goto err2;
  2534. return true;
  2535. err2:
  2536. upb_inttable_uninit(r->refs);
  2537. err1:
  2538. free(r->refs);
  2539. free(r->ref2s);
  2540. return false;
  2541. }
  2542. static void trackfree(const upb_refcounted *r) {
  2543. upb_inttable_uninit(r->refs);
  2544. upb_inttable_uninit(r->ref2s);
  2545. free(r->refs);
  2546. free(r->ref2s);
  2547. }
  2548. #else
  2549. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  2550. UPB_UNUSED(r);
  2551. UPB_UNUSED(owner);
  2552. UPB_UNUSED(ref2);
  2553. }
  2554. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  2555. UPB_UNUSED(r);
  2556. UPB_UNUSED(owner);
  2557. UPB_UNUSED(ref2);
  2558. }
  2559. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  2560. UPB_UNUSED(r);
  2561. UPB_UNUSED(owner);
  2562. UPB_UNUSED(ref2);
  2563. }
  2564. static bool trackinit(upb_refcounted *r) {
  2565. UPB_UNUSED(r);
  2566. return true;
  2567. }
  2568. static void trackfree(const upb_refcounted *r) {
  2569. UPB_UNUSED(r);
  2570. }
  2571. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  2572. void *closure) {
  2573. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  2574. }
  2575. #endif /* UPB_DEBUG_REFS */
  2576. /* freeze() *******************************************************************/
  2577. /* The freeze() operation is by far the most complicated part of this scheme.
  2578. * We compute strongly-connected components and then mutate the graph such that
  2579. * we preserve the invariants documented at the top of this file. And we must
  2580. * handle out-of-memory errors gracefully (without leaving the graph
  2581. * inconsistent), which adds to the fun. */
  2582. /* The state used by the freeze operation (shared across many functions). */
  2583. typedef struct {
  2584. int depth;
  2585. int maxdepth;
  2586. uint64_t index;
  2587. /* Maps upb_refcounted* -> attributes (color, etc). attr layout varies by
  2588. * color. */
  2589. upb_inttable objattr;
  2590. upb_inttable stack; /* stack of upb_refcounted* for Tarjan's algorithm. */
  2591. upb_inttable groups; /* array of uint32_t*, malloc'd refcounts for new groups */
  2592. upb_status *status;
  2593. jmp_buf err;
  2594. } tarjan;
  2595. static void release_ref2(const upb_refcounted *obj,
  2596. const upb_refcounted *subobj,
  2597. void *closure);
  2598. /* Node attributes -----------------------------------------------------------*/
  2599. /* After our analysis phase all nodes will be either GRAY or WHITE. */
  2600. typedef enum {
  2601. BLACK = 0, /* Object has not been seen. */
  2602. GRAY, /* Object has been found via a refgroup but may not be reachable. */
  2603. GREEN, /* Object is reachable and is currently on the Tarjan stack. */
  2604. WHITE /* Object is reachable and has been assigned a group (SCC). */
  2605. } color_t;
  2606. UPB_NORETURN static void err(tarjan *t) { longjmp(t->err, 1); }
  2607. UPB_NORETURN static void oom(tarjan *t) {
  2608. upb_status_seterrmsg(t->status, "out of memory");
  2609. err(t);
  2610. }
  2611. static uint64_t trygetattr(const tarjan *t, const upb_refcounted *r) {
  2612. upb_value v;
  2613. return upb_inttable_lookupptr(&t->objattr, r, &v) ?
  2614. upb_value_getuint64(v) : 0;
  2615. }
  2616. static uint64_t getattr(const tarjan *t, const upb_refcounted *r) {
  2617. upb_value v;
  2618. bool found = upb_inttable_lookupptr(&t->objattr, r, &v);
  2619. UPB_ASSERT_VAR(found, found);
  2620. return upb_value_getuint64(v);
  2621. }
  2622. static void setattr(tarjan *t, const upb_refcounted *r, uint64_t attr) {
  2623. upb_inttable_removeptr(&t->objattr, r, NULL);
  2624. upb_inttable_insertptr(&t->objattr, r, upb_value_uint64(attr));
  2625. }
  2626. static color_t color(tarjan *t, const upb_refcounted *r) {
  2627. return trygetattr(t, r) & 0x3; /* Color is always stored in the low 2 bits. */
  2628. }
  2629. static void set_gray(tarjan *t, const upb_refcounted *r) {
  2630. assert(color(t, r) == BLACK);
  2631. setattr(t, r, GRAY);
  2632. }
  2633. /* Pushes an obj onto the Tarjan stack and sets it to GREEN. */
  2634. static void push(tarjan *t, const upb_refcounted *r) {
  2635. assert(color(t, r) == BLACK || color(t, r) == GRAY);
  2636. /* This defines the attr layout for the GREEN state. "index" and "lowlink"
  2637. * get 31 bits, which is plenty (limit of 2B objects frozen at a time). */
  2638. setattr(t, r, GREEN | (t->index << 2) | (t->index << 33));
  2639. if (++t->index == 0x80000000) {
  2640. upb_status_seterrmsg(t->status, "too many objects to freeze");
  2641. err(t);
  2642. }
  2643. upb_inttable_push(&t->stack, upb_value_ptr((void*)r));
  2644. }
  2645. /* Pops an obj from the Tarjan stack and sets it to WHITE, with a ptr to its
  2646. * SCC group. */
  2647. static upb_refcounted *pop(tarjan *t) {
  2648. upb_refcounted *r = upb_value_getptr(upb_inttable_pop(&t->stack));
  2649. assert(color(t, r) == GREEN);
  2650. /* This defines the attr layout for nodes in the WHITE state.
  2651. * Top of group stack is [group, NULL]; we point at group. */
  2652. setattr(t, r, WHITE | (upb_inttable_count(&t->groups) - 2) << 8);
  2653. return r;
  2654. }
  2655. static void tarjan_newgroup(tarjan *t) {
  2656. uint32_t *group = malloc(sizeof(*group));
  2657. if (!group) oom(t);
  2658. /* Push group and empty group leader (we'll fill in leader later). */
  2659. if (!upb_inttable_push(&t->groups, upb_value_ptr(group)) ||
  2660. !upb_inttable_push(&t->groups, upb_value_ptr(NULL))) {
  2661. free(group);
  2662. oom(t);
  2663. }
  2664. *group = 0;
  2665. }
  2666. static uint32_t idx(tarjan *t, const upb_refcounted *r) {
  2667. assert(color(t, r) == GREEN);
  2668. return (getattr(t, r) >> 2) & 0x7FFFFFFF;
  2669. }
  2670. static uint32_t lowlink(tarjan *t, const upb_refcounted *r) {
  2671. if (color(t, r) == GREEN) {
  2672. return getattr(t, r) >> 33;
  2673. } else {
  2674. return UINT32_MAX;
  2675. }
  2676. }
  2677. static void set_lowlink(tarjan *t, const upb_refcounted *r, uint32_t lowlink) {
  2678. assert(color(t, r) == GREEN);
  2679. setattr(t, r, ((uint64_t)lowlink << 33) | (getattr(t, r) & 0x1FFFFFFFF));
  2680. }
  2681. static uint32_t *group(tarjan *t, upb_refcounted *r) {
  2682. uint64_t groupnum;
  2683. upb_value v;
  2684. bool found;
  2685. assert(color(t, r) == WHITE);
  2686. groupnum = getattr(t, r) >> 8;
  2687. found = upb_inttable_lookup(&t->groups, groupnum, &v);
  2688. UPB_ASSERT_VAR(found, found);
  2689. return upb_value_getptr(v);
  2690. }
  2691. /* If the group leader for this object's group has not previously been set,
  2692. * the given object is assigned to be its leader. */
  2693. static upb_refcounted *groupleader(tarjan *t, upb_refcounted *r) {
  2694. uint64_t leader_slot;
  2695. upb_value v;
  2696. bool found;
  2697. assert(color(t, r) == WHITE);
  2698. leader_slot = (getattr(t, r) >> 8) + 1;
  2699. found = upb_inttable_lookup(&t->groups, leader_slot, &v);
  2700. UPB_ASSERT_VAR(found, found);
  2701. if (upb_value_getptr(v)) {
  2702. return upb_value_getptr(v);
  2703. } else {
  2704. upb_inttable_remove(&t->groups, leader_slot, NULL);
  2705. upb_inttable_insert(&t->groups, leader_slot, upb_value_ptr(r));
  2706. return r;
  2707. }
  2708. }
  2709. /* Tarjan's algorithm --------------------------------------------------------*/
  2710. /* See:
  2711. * http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm */
  2712. static void do_tarjan(const upb_refcounted *obj, tarjan *t);
  2713. static void tarjan_visit(const upb_refcounted *obj,
  2714. const upb_refcounted *subobj,
  2715. void *closure) {
  2716. tarjan *t = closure;
  2717. if (++t->depth > t->maxdepth) {
  2718. upb_status_seterrf(t->status, "graph too deep to freeze (%d)", t->maxdepth);
  2719. err(t);
  2720. } else if (subobj->is_frozen || color(t, subobj) == WHITE) {
  2721. /* Do nothing: we don't want to visit or color already-frozen nodes,
  2722. * and WHITE nodes have already been assigned a SCC. */
  2723. } else if (color(t, subobj) < GREEN) {
  2724. /* Subdef has not yet been visited; recurse on it. */
  2725. do_tarjan(subobj, t);
  2726. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), lowlink(t, subobj)));
  2727. } else if (color(t, subobj) == GREEN) {
  2728. /* Subdef is in the stack and hence in the current SCC. */
  2729. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), idx(t, subobj)));
  2730. }
  2731. --t->depth;
  2732. }
  2733. static void do_tarjan(const upb_refcounted *obj, tarjan *t) {
  2734. if (color(t, obj) == BLACK) {
  2735. /* We haven't seen this object's group; mark the whole group GRAY. */
  2736. const upb_refcounted *o = obj;
  2737. do { set_gray(t, o); } while ((o = o->next) != obj);
  2738. }
  2739. push(t, obj);
  2740. visit(obj, tarjan_visit, t);
  2741. if (lowlink(t, obj) == idx(t, obj)) {
  2742. tarjan_newgroup(t);
  2743. while (pop(t) != obj)
  2744. ;
  2745. }
  2746. }
  2747. /* freeze() ------------------------------------------------------------------*/
  2748. static void crossref(const upb_refcounted *r, const upb_refcounted *subobj,
  2749. void *_t) {
  2750. tarjan *t = _t;
  2751. assert(color(t, r) > BLACK);
  2752. if (color(t, subobj) > BLACK && r->group != subobj->group) {
  2753. /* Previously this ref was not reflected in subobj->group because they
  2754. * were in the same group; now that they are split a ref must be taken. */
  2755. refgroup(subobj->group);
  2756. }
  2757. }
  2758. static bool freeze(upb_refcounted *const*roots, int n, upb_status *s,
  2759. int maxdepth) {
  2760. volatile bool ret = false;
  2761. int i;
  2762. upb_inttable_iter iter;
  2763. /* We run in two passes so that we can allocate all memory before performing
  2764. * any mutation of the input -- this allows us to leave the input unchanged
  2765. * in the case of memory allocation failure. */
  2766. tarjan t;
  2767. t.index = 0;
  2768. t.depth = 0;
  2769. t.maxdepth = maxdepth;
  2770. t.status = s;
  2771. if (!upb_inttable_init(&t.objattr, UPB_CTYPE_UINT64)) goto err1;
  2772. if (!upb_inttable_init(&t.stack, UPB_CTYPE_PTR)) goto err2;
  2773. if (!upb_inttable_init(&t.groups, UPB_CTYPE_PTR)) goto err3;
  2774. if (setjmp(t.err) != 0) goto err4;
  2775. for (i = 0; i < n; i++) {
  2776. if (color(&t, roots[i]) < GREEN) {
  2777. do_tarjan(roots[i], &t);
  2778. }
  2779. }
  2780. /* If we've made it this far, no further errors are possible so it's safe to
  2781. * mutate the objects without risk of leaving them in an inconsistent state. */
  2782. ret = true;
  2783. /* The transformation that follows requires care. The preconditions are:
  2784. * - all objects in attr map are WHITE or GRAY, and are in mutable groups
  2785. * (groups of all mutable objs)
  2786. * - no ref2(to, from) refs have incremented count(to) if both "to" and
  2787. * "from" are in our attr map (this follows from invariants (2) and (3)) */
  2788. /* Pass 1: we remove WHITE objects from their mutable groups, and add them to
  2789. * new groups according to the SCC's we computed. These new groups will
  2790. * consist of only frozen objects. None will be immediately collectible,
  2791. * because WHITE objects are by definition reachable from one of "roots",
  2792. * which the caller must own refs on. */
  2793. upb_inttable_begin(&iter, &t.objattr);
  2794. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  2795. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  2796. /* Since removal from a singly-linked list requires access to the object's
  2797. * predecessor, we consider obj->next instead of obj for moving. With the
  2798. * while() loop we guarantee that we will visit every node's predecessor.
  2799. * Proof:
  2800. * 1. every node's predecessor is in our attr map.
  2801. * 2. though the loop body may change a node's predecessor, it will only
  2802. * change it to be the node we are currently operating on, so with a
  2803. * while() loop we guarantee ourselves the chance to remove each node. */
  2804. while (color(&t, obj->next) == WHITE &&
  2805. group(&t, obj->next) != obj->next->group) {
  2806. upb_refcounted *leader;
  2807. /* Remove from old group. */
  2808. upb_refcounted *move = obj->next;
  2809. if (obj == move) {
  2810. /* Removing the last object from a group. */
  2811. assert(*obj->group == obj->individual_count);
  2812. free(obj->group);
  2813. } else {
  2814. obj->next = move->next;
  2815. /* This may decrease to zero; we'll collect GRAY objects (if any) that
  2816. * remain in the group in the third pass. */
  2817. assert(*move->group >= move->individual_count);
  2818. *move->group -= move->individual_count;
  2819. }
  2820. /* Add to new group. */
  2821. leader = groupleader(&t, move);
  2822. if (move == leader) {
  2823. /* First object added to new group is its leader. */
  2824. move->group = group(&t, move);
  2825. move->next = move;
  2826. *move->group = move->individual_count;
  2827. } else {
  2828. /* Group already has at least one object in it. */
  2829. assert(leader->group == group(&t, move));
  2830. move->group = group(&t, move);
  2831. move->next = leader->next;
  2832. leader->next = move;
  2833. *move->group += move->individual_count;
  2834. }
  2835. move->is_frozen = true;
  2836. }
  2837. }
  2838. /* Pass 2: GRAY and WHITE objects "obj" with ref2(to, obj) references must
  2839. * increment count(to) if group(obj) != group(to) (which could now be the
  2840. * case if "to" was just frozen). */
  2841. upb_inttable_begin(&iter, &t.objattr);
  2842. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  2843. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  2844. visit(obj, crossref, &t);
  2845. }
  2846. /* Pass 3: GRAY objects are collected if their group's refcount dropped to
  2847. * zero when we removed its white nodes. This can happen if they had only
  2848. * been kept alive by virtue of sharing a group with an object that was just
  2849. * frozen.
  2850. *
  2851. * It is important that we do this last, since the GRAY object's free()
  2852. * function could call unref2() on just-frozen objects, which will decrement
  2853. * refs that were added in pass 2. */
  2854. upb_inttable_begin(&iter, &t.objattr);
  2855. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  2856. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  2857. if (obj->group == NULL || *obj->group == 0) {
  2858. if (obj->group) {
  2859. upb_refcounted *o;
  2860. /* We eagerly free() the group's count (since we can't easily determine
  2861. * the group's remaining size it's the easiest way to ensure it gets
  2862. * done). */
  2863. free(obj->group);
  2864. /* Visit to release ref2's (done in a separate pass since release_ref2
  2865. * depends on o->group being unmodified so it can test merged()). */
  2866. o = obj;
  2867. do { visit(o, release_ref2, NULL); } while ((o = o->next) != obj);
  2868. /* Mark "group" fields as NULL so we know to free the objects later in
  2869. * this loop, but also don't try to delete the group twice. */
  2870. o = obj;
  2871. do { o->group = NULL; } while ((o = o->next) != obj);
  2872. }
  2873. freeobj(obj);
  2874. }
  2875. }
  2876. err4:
  2877. if (!ret) {
  2878. upb_inttable_begin(&iter, &t.groups);
  2879. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter))
  2880. free(upb_value_getptr(upb_inttable_iter_value(&iter)));
  2881. }
  2882. upb_inttable_uninit(&t.groups);
  2883. err3:
  2884. upb_inttable_uninit(&t.stack);
  2885. err2:
  2886. upb_inttable_uninit(&t.objattr);
  2887. err1:
  2888. return ret;
  2889. }
  2890. /* Misc internal functions ***************************************************/
  2891. static bool merged(const upb_refcounted *r, const upb_refcounted *r2) {
  2892. return r->group == r2->group;
  2893. }
  2894. static void merge(upb_refcounted *r, upb_refcounted *from) {
  2895. upb_refcounted *base;
  2896. upb_refcounted *tmp;
  2897. if (merged(r, from)) return;
  2898. *r->group += *from->group;
  2899. free(from->group);
  2900. base = from;
  2901. /* Set all refcount pointers in the "from" chain to the merged refcount.
  2902. *
  2903. * TODO(haberman): this linear algorithm can result in an overall O(n^2) bound
  2904. * if the user continuously extends a group by one object. Prevent this by
  2905. * using one of the techniques in this paper:
  2906. * ftp://www.ncedc.org/outgoing/geomorph/dino/orals/p245-tarjan.pdf */
  2907. do { from->group = r->group; } while ((from = from->next) != base);
  2908. /* Merge the two circularly linked lists by swapping their next pointers. */
  2909. tmp = r->next;
  2910. r->next = base->next;
  2911. base->next = tmp;
  2912. }
  2913. static void unref(const upb_refcounted *r);
  2914. static void release_ref2(const upb_refcounted *obj,
  2915. const upb_refcounted *subobj,
  2916. void *closure) {
  2917. UPB_UNUSED(closure);
  2918. untrack(subobj, obj, true);
  2919. if (!merged(obj, subobj)) {
  2920. assert(subobj->is_frozen);
  2921. unref(subobj);
  2922. }
  2923. }
  2924. static void unref(const upb_refcounted *r) {
  2925. if (unrefgroup(r->group)) {
  2926. const upb_refcounted *o;
  2927. free(r->group);
  2928. /* In two passes, since release_ref2 needs a guarantee that any subobjs
  2929. * are alive. */
  2930. o = r;
  2931. do { visit(o, release_ref2, NULL); } while((o = o->next) != r);
  2932. o = r;
  2933. do {
  2934. const upb_refcounted *next = o->next;
  2935. assert(o->is_frozen || o->individual_count == 0);
  2936. freeobj((upb_refcounted*)o);
  2937. o = next;
  2938. } while(o != r);
  2939. }
  2940. }
  2941. static void freeobj(upb_refcounted *o) {
  2942. trackfree(o);
  2943. o->vtbl->free((upb_refcounted*)o);
  2944. }
  2945. /* Public interface ***********************************************************/
  2946. bool upb_refcounted_init(upb_refcounted *r,
  2947. const struct upb_refcounted_vtbl *vtbl,
  2948. const void *owner) {
  2949. #ifndef NDEBUG
  2950. /* Endianness check. This is unrelated to upb_refcounted, it's just a
  2951. * convenient place to put the check that we can be assured will run for
  2952. * basically every program using upb. */
  2953. const int x = 1;
  2954. #ifdef UPB_BIG_ENDIAN
  2955. assert(*(char*)&x != 1);
  2956. #else
  2957. assert(*(char*)&x == 1);
  2958. #endif
  2959. #endif
  2960. r->next = r;
  2961. r->vtbl = vtbl;
  2962. r->individual_count = 0;
  2963. r->is_frozen = false;
  2964. r->group = malloc(sizeof(*r->group));
  2965. if (!r->group) return false;
  2966. *r->group = 0;
  2967. if (!trackinit(r)) {
  2968. free(r->group);
  2969. return false;
  2970. }
  2971. upb_refcounted_ref(r, owner);
  2972. return true;
  2973. }
  2974. bool upb_refcounted_isfrozen(const upb_refcounted *r) {
  2975. return r->is_frozen;
  2976. }
  2977. void upb_refcounted_ref(const upb_refcounted *r, const void *owner) {
  2978. track(r, owner, false);
  2979. if (!r->is_frozen)
  2980. ((upb_refcounted*)r)->individual_count++;
  2981. refgroup(r->group);
  2982. }
  2983. void upb_refcounted_unref(const upb_refcounted *r, const void *owner) {
  2984. untrack(r, owner, false);
  2985. if (!r->is_frozen)
  2986. ((upb_refcounted*)r)->individual_count--;
  2987. unref(r);
  2988. }
  2989. void upb_refcounted_ref2(const upb_refcounted *r, upb_refcounted *from) {
  2990. assert(!from->is_frozen); /* Non-const pointer implies this. */
  2991. track(r, from, true);
  2992. if (r->is_frozen) {
  2993. refgroup(r->group);
  2994. } else {
  2995. merge((upb_refcounted*)r, from);
  2996. }
  2997. }
  2998. void upb_refcounted_unref2(const upb_refcounted *r, upb_refcounted *from) {
  2999. assert(!from->is_frozen); /* Non-const pointer implies this. */
  3000. untrack(r, from, true);
  3001. if (r->is_frozen) {
  3002. unref(r);
  3003. } else {
  3004. assert(merged(r, from));
  3005. }
  3006. }
  3007. void upb_refcounted_donateref(
  3008. const upb_refcounted *r, const void *from, const void *to) {
  3009. assert(from != to);
  3010. if (to != NULL)
  3011. upb_refcounted_ref(r, to);
  3012. if (from != NULL)
  3013. upb_refcounted_unref(r, from);
  3014. }
  3015. void upb_refcounted_checkref(const upb_refcounted *r, const void *owner) {
  3016. checkref(r, owner, false);
  3017. }
  3018. bool upb_refcounted_freeze(upb_refcounted *const*roots, int n, upb_status *s,
  3019. int maxdepth) {
  3020. int i;
  3021. for (i = 0; i < n; i++) {
  3022. assert(!roots[i]->is_frozen);
  3023. }
  3024. return freeze(roots, n, s, maxdepth);
  3025. }
  3026. #include <stdlib.h>
  3027. /* Fallback implementation if the shim is not specialized by the JIT. */
  3028. #define SHIM_WRITER(type, ctype) \
  3029. bool upb_shim_set ## type (void *c, const void *hd, ctype val) { \
  3030. uint8_t *m = c; \
  3031. const upb_shim_data *d = hd; \
  3032. if (d->hasbit > 0) \
  3033. *(uint8_t*)&m[d->hasbit / 8] |= 1 << (d->hasbit % 8); \
  3034. *(ctype*)&m[d->offset] = val; \
  3035. return true; \
  3036. } \
  3037. SHIM_WRITER(double, double)
  3038. SHIM_WRITER(float, float)
  3039. SHIM_WRITER(int32, int32_t)
  3040. SHIM_WRITER(int64, int64_t)
  3041. SHIM_WRITER(uint32, uint32_t)
  3042. SHIM_WRITER(uint64, uint64_t)
  3043. SHIM_WRITER(bool, bool)
  3044. #undef SHIM_WRITER
  3045. bool upb_shim_set(upb_handlers *h, const upb_fielddef *f, size_t offset,
  3046. int32_t hasbit) {
  3047. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  3048. bool ok;
  3049. upb_shim_data *d = malloc(sizeof(*d));
  3050. if (!d) return false;
  3051. d->offset = offset;
  3052. d->hasbit = hasbit;
  3053. upb_handlerattr_sethandlerdata(&attr, d);
  3054. upb_handlerattr_setalwaysok(&attr, true);
  3055. upb_handlers_addcleanup(h, d, free);
  3056. #define TYPE(u, l) \
  3057. case UPB_TYPE_##u: \
  3058. ok = upb_handlers_set##l(h, f, upb_shim_set##l, &attr); break;
  3059. ok = false;
  3060. switch (upb_fielddef_type(f)) {
  3061. TYPE(INT64, int64);
  3062. TYPE(INT32, int32);
  3063. TYPE(ENUM, int32);
  3064. TYPE(UINT64, uint64);
  3065. TYPE(UINT32, uint32);
  3066. TYPE(DOUBLE, double);
  3067. TYPE(FLOAT, float);
  3068. TYPE(BOOL, bool);
  3069. default: assert(false); break;
  3070. }
  3071. #undef TYPE
  3072. upb_handlerattr_uninit(&attr);
  3073. return ok;
  3074. }
  3075. const upb_shim_data *upb_shim_getdata(const upb_handlers *h, upb_selector_t s,
  3076. upb_fieldtype_t *type) {
  3077. upb_func *f = upb_handlers_gethandler(h, s);
  3078. if ((upb_int64_handlerfunc*)f == upb_shim_setint64) {
  3079. *type = UPB_TYPE_INT64;
  3080. } else if ((upb_int32_handlerfunc*)f == upb_shim_setint32) {
  3081. *type = UPB_TYPE_INT32;
  3082. } else if ((upb_uint64_handlerfunc*)f == upb_shim_setuint64) {
  3083. *type = UPB_TYPE_UINT64;
  3084. } else if ((upb_uint32_handlerfunc*)f == upb_shim_setuint32) {
  3085. *type = UPB_TYPE_UINT32;
  3086. } else if ((upb_double_handlerfunc*)f == upb_shim_setdouble) {
  3087. *type = UPB_TYPE_DOUBLE;
  3088. } else if ((upb_float_handlerfunc*)f == upb_shim_setfloat) {
  3089. *type = UPB_TYPE_FLOAT;
  3090. } else if ((upb_bool_handlerfunc*)f == upb_shim_setbool) {
  3091. *type = UPB_TYPE_BOOL;
  3092. } else {
  3093. return NULL;
  3094. }
  3095. return (const upb_shim_data*)upb_handlers_gethandlerdata(h, s);
  3096. }
  3097. #include <stdlib.h>
  3098. #include <string.h>
  3099. static void upb_symtab_free(upb_refcounted *r) {
  3100. upb_symtab *s = (upb_symtab*)r;
  3101. upb_strtable_iter i;
  3102. upb_strtable_begin(&i, &s->symtab);
  3103. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  3104. const upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  3105. upb_def_unref(def, s);
  3106. }
  3107. upb_strtable_uninit(&s->symtab);
  3108. free(s);
  3109. }
  3110. upb_symtab *upb_symtab_new(const void *owner) {
  3111. static const struct upb_refcounted_vtbl vtbl = {NULL, &upb_symtab_free};
  3112. upb_symtab *s = malloc(sizeof(*s));
  3113. upb_refcounted_init(upb_symtab_upcast_mutable(s), &vtbl, owner);
  3114. upb_strtable_init(&s->symtab, UPB_CTYPE_PTR);
  3115. return s;
  3116. }
  3117. void upb_symtab_freeze(upb_symtab *s) {
  3118. upb_refcounted *r;
  3119. bool ok;
  3120. assert(!upb_symtab_isfrozen(s));
  3121. r = upb_symtab_upcast_mutable(s);
  3122. /* The symtab does not take ref2's (see refcounted.h) on the defs, because
  3123. * defs cannot refer back to the table and therefore cannot create cycles. So
  3124. * 0 will suffice for maxdepth here. */
  3125. ok = upb_refcounted_freeze(&r, 1, NULL, 0);
  3126. UPB_ASSERT_VAR(ok, ok);
  3127. }
  3128. const upb_def *upb_symtab_lookup(const upb_symtab *s, const char *sym) {
  3129. upb_value v;
  3130. upb_def *ret = upb_strtable_lookup(&s->symtab, sym, &v) ?
  3131. upb_value_getptr(v) : NULL;
  3132. return ret;
  3133. }
  3134. const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym) {
  3135. upb_value v;
  3136. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  3137. upb_value_getptr(v) : NULL;
  3138. return def ? upb_dyncast_msgdef(def) : NULL;
  3139. }
  3140. const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym) {
  3141. upb_value v;
  3142. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  3143. upb_value_getptr(v) : NULL;
  3144. return def ? upb_dyncast_enumdef(def) : NULL;
  3145. }
  3146. /* Given a symbol and the base symbol inside which it is defined, find the
  3147. * symbol's definition in t. */
  3148. static upb_def *upb_resolvename(const upb_strtable *t,
  3149. const char *base, const char *sym) {
  3150. if(strlen(sym) == 0) return NULL;
  3151. if(sym[0] == '.') {
  3152. /* Symbols starting with '.' are absolute, so we do a single lookup.
  3153. * Slice to omit the leading '.' */
  3154. upb_value v;
  3155. return upb_strtable_lookup(t, sym + 1, &v) ? upb_value_getptr(v) : NULL;
  3156. } else {
  3157. /* Remove components from base until we find an entry or run out.
  3158. * TODO: This branch is totally broken, but currently not used. */
  3159. (void)base;
  3160. assert(false);
  3161. return NULL;
  3162. }
  3163. }
  3164. const upb_def *upb_symtab_resolve(const upb_symtab *s, const char *base,
  3165. const char *sym) {
  3166. upb_def *ret = upb_resolvename(&s->symtab, base, sym);
  3167. return ret;
  3168. }
  3169. /* Starts a depth-first traversal at "def", recursing into any subdefs
  3170. * (ie. submessage types). Adds duplicates of existing defs to addtab
  3171. * wherever necessary, so that the resulting symtab will be consistent once
  3172. * addtab is added.
  3173. *
  3174. * More specifically, if any def D is found in the DFS that:
  3175. *
  3176. * 1. can reach a def that is being replaced by something in addtab, AND
  3177. *
  3178. * 2. is not itself being replaced already (ie. this name doesn't already
  3179. * exist in addtab)
  3180. *
  3181. * ...then a duplicate (new copy) of D will be added to addtab.
  3182. *
  3183. * Returns true if this happened for any def reachable from "def."
  3184. *
  3185. * It is slightly tricky to do this correctly in the presence of cycles. If we
  3186. * detect that our DFS has hit a cycle, we might not yet know if any SCCs on
  3187. * our stack can reach a def in addtab or not. Once we figure this out, that
  3188. * answer needs to apply to *all* defs in these SCCs, even if we visited them
  3189. * already. So a straight up one-pass cycle-detecting DFS won't work.
  3190. *
  3191. * To work around this problem, we traverse each SCC (which we already
  3192. * computed, since these defs are frozen) as a single node. We first compute
  3193. * whether the SCC as a whole can reach any def in addtab, then we dup (or not)
  3194. * the entire SCC. This requires breaking the encapsulation of upb_refcounted,
  3195. * since that is where we get the data about what SCC we are in. */
  3196. static bool upb_resolve_dfs(const upb_def *def, upb_strtable *addtab,
  3197. const void *new_owner, upb_inttable *seen,
  3198. upb_status *s) {
  3199. upb_value v;
  3200. bool need_dup;
  3201. const upb_def *base;
  3202. const void* memoize_key;
  3203. /* Memoize results of this function for efficiency (since we're traversing a
  3204. * DAG this is not needed to limit the depth of the search).
  3205. *
  3206. * We memoize by SCC instead of by individual def. */
  3207. memoize_key = def->base.group;
  3208. if (upb_inttable_lookupptr(seen, memoize_key, &v))
  3209. return upb_value_getbool(v);
  3210. /* Visit submessages for all messages in the SCC. */
  3211. need_dup = false;
  3212. base = def;
  3213. do {
  3214. upb_value v;
  3215. const upb_msgdef *m;
  3216. assert(upb_def_isfrozen(def));
  3217. if (def->type == UPB_DEF_FIELD) continue;
  3218. if (upb_strtable_lookup(addtab, upb_def_fullname(def), &v)) {
  3219. need_dup = true;
  3220. }
  3221. /* For messages, continue the recursion by visiting all subdefs, but only
  3222. * ones in different SCCs. */
  3223. m = upb_dyncast_msgdef(def);
  3224. if (m) {
  3225. upb_msg_field_iter i;
  3226. for(upb_msg_field_begin(&i, m);
  3227. !upb_msg_field_done(&i);
  3228. upb_msg_field_next(&i)) {
  3229. upb_fielddef *f = upb_msg_iter_field(&i);
  3230. const upb_def *subdef;
  3231. if (!upb_fielddef_hassubdef(f)) continue;
  3232. subdef = upb_fielddef_subdef(f);
  3233. /* Skip subdefs in this SCC. */
  3234. if (def->base.group == subdef->base.group) continue;
  3235. /* |= to avoid short-circuit; we need its side-effects. */
  3236. need_dup |= upb_resolve_dfs(subdef, addtab, new_owner, seen, s);
  3237. if (!upb_ok(s)) return false;
  3238. }
  3239. }
  3240. } while ((def = (upb_def*)def->base.next) != base);
  3241. if (need_dup) {
  3242. /* Dup all defs in this SCC that don't already have entries in addtab. */
  3243. def = base;
  3244. do {
  3245. const char *name;
  3246. if (def->type == UPB_DEF_FIELD) continue;
  3247. name = upb_def_fullname(def);
  3248. if (!upb_strtable_lookup(addtab, name, NULL)) {
  3249. upb_def *newdef = upb_def_dup(def, new_owner);
  3250. if (!newdef) goto oom;
  3251. newdef->came_from_user = false;
  3252. if (!upb_strtable_insert(addtab, name, upb_value_ptr(newdef)))
  3253. goto oom;
  3254. }
  3255. } while ((def = (upb_def*)def->base.next) != base);
  3256. }
  3257. upb_inttable_insertptr(seen, memoize_key, upb_value_bool(need_dup));
  3258. return need_dup;
  3259. oom:
  3260. upb_status_seterrmsg(s, "out of memory");
  3261. return false;
  3262. }
  3263. /* TODO(haberman): we need a lot more testing of error conditions.
  3264. * The came_from_user stuff in particular is not tested. */
  3265. bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, int n, void *ref_donor,
  3266. upb_status *status) {
  3267. int i;
  3268. upb_strtable_iter iter;
  3269. upb_def **add_defs = NULL;
  3270. upb_strtable addtab;
  3271. upb_inttable seen;
  3272. assert(!upb_symtab_isfrozen(s));
  3273. if (!upb_strtable_init(&addtab, UPB_CTYPE_PTR)) {
  3274. upb_status_seterrmsg(status, "out of memory");
  3275. return false;
  3276. }
  3277. /* Add new defs to our "add" set. */
  3278. for (i = 0; i < n; i++) {
  3279. upb_def *def = defs[i];
  3280. const char *fullname;
  3281. upb_fielddef *f;
  3282. if (upb_def_isfrozen(def)) {
  3283. upb_status_seterrmsg(status, "added defs must be mutable");
  3284. goto err;
  3285. }
  3286. assert(!upb_def_isfrozen(def));
  3287. fullname = upb_def_fullname(def);
  3288. if (!fullname) {
  3289. upb_status_seterrmsg(
  3290. status, "Anonymous defs cannot be added to a symtab");
  3291. goto err;
  3292. }
  3293. f = upb_dyncast_fielddef_mutable(def);
  3294. if (f) {
  3295. if (!upb_fielddef_containingtypename(f)) {
  3296. upb_status_seterrmsg(status,
  3297. "Standalone fielddefs must have a containing type "
  3298. "(extendee) name set");
  3299. goto err;
  3300. }
  3301. } else {
  3302. if (upb_strtable_lookup(&addtab, fullname, NULL)) {
  3303. upb_status_seterrf(status, "Conflicting defs named '%s'", fullname);
  3304. goto err;
  3305. }
  3306. /* We need this to back out properly, because if there is a failure we
  3307. * need to donate the ref back to the caller. */
  3308. def->came_from_user = true;
  3309. upb_def_donateref(def, ref_donor, s);
  3310. if (!upb_strtable_insert(&addtab, fullname, upb_value_ptr(def)))
  3311. goto oom_err;
  3312. }
  3313. }
  3314. /* Add standalone fielddefs (ie. extensions) to the appropriate messages.
  3315. * If the appropriate message only exists in the existing symtab, duplicate
  3316. * it so we have a mutable copy we can add the fields to. */
  3317. for (i = 0; i < n; i++) {
  3318. upb_def *def = defs[i];
  3319. upb_fielddef *f = upb_dyncast_fielddef_mutable(def);
  3320. const char *msgname;
  3321. upb_value v;
  3322. upb_msgdef *m;
  3323. if (!f) continue;
  3324. msgname = upb_fielddef_containingtypename(f);
  3325. /* We validated this earlier in this function. */
  3326. assert(msgname);
  3327. /* If the extendee name is absolutely qualified, move past the initial ".".
  3328. * TODO(haberman): it is not obvious what it would mean if this was not
  3329. * absolutely qualified. */
  3330. if (msgname[0] == '.') {
  3331. msgname++;
  3332. }
  3333. if (upb_strtable_lookup(&addtab, msgname, &v)) {
  3334. /* Extendee is in the set of defs the user asked us to add. */
  3335. m = upb_value_getptr(v);
  3336. } else {
  3337. /* Need to find and dup the extendee from the existing symtab. */
  3338. const upb_msgdef *frozen_m = upb_symtab_lookupmsg(s, msgname);
  3339. if (!frozen_m) {
  3340. upb_status_seterrf(status,
  3341. "Tried to extend message %s that does not exist "
  3342. "in this SymbolTable.",
  3343. msgname);
  3344. goto err;
  3345. }
  3346. m = upb_msgdef_dup(frozen_m, s);
  3347. if (!m) goto oom_err;
  3348. if (!upb_strtable_insert(&addtab, msgname, upb_value_ptr(m))) {
  3349. upb_msgdef_unref(m, s);
  3350. goto oom_err;
  3351. }
  3352. }
  3353. if (!upb_msgdef_addfield(m, f, ref_donor, status)) {
  3354. goto err;
  3355. }
  3356. }
  3357. /* Add dups of any existing def that can reach a def with the same name as
  3358. * anything in our "add" set. */
  3359. if (!upb_inttable_init(&seen, UPB_CTYPE_BOOL)) goto oom_err;
  3360. upb_strtable_begin(&iter, &s->symtab);
  3361. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  3362. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
  3363. upb_resolve_dfs(def, &addtab, s, &seen, status);
  3364. if (!upb_ok(status)) goto err;
  3365. }
  3366. upb_inttable_uninit(&seen);
  3367. /* Now using the table, resolve symbolic references for subdefs. */
  3368. upb_strtable_begin(&iter, &addtab);
  3369. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  3370. const char *base;
  3371. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
  3372. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  3373. upb_msg_field_iter j;
  3374. if (!m) continue;
  3375. /* Type names are resolved relative to the message in which they appear. */
  3376. base = upb_msgdef_fullname(m);
  3377. for(upb_msg_field_begin(&j, m);
  3378. !upb_msg_field_done(&j);
  3379. upb_msg_field_next(&j)) {
  3380. upb_fielddef *f = upb_msg_iter_field(&j);
  3381. const char *name = upb_fielddef_subdefname(f);
  3382. if (name && !upb_fielddef_subdef(f)) {
  3383. /* Try the lookup in the current set of to-be-added defs first. If not
  3384. * there, try existing defs. */
  3385. upb_def *subdef = upb_resolvename(&addtab, base, name);
  3386. if (subdef == NULL) {
  3387. subdef = upb_resolvename(&s->symtab, base, name);
  3388. }
  3389. if (subdef == NULL) {
  3390. upb_status_seterrf(
  3391. status, "couldn't resolve name '%s' in message '%s'", name, base);
  3392. goto err;
  3393. } else if (!upb_fielddef_setsubdef(f, subdef, status)) {
  3394. goto err;
  3395. }
  3396. }
  3397. }
  3398. }
  3399. /* We need an array of the defs in addtab, for passing to upb_def_freeze. */
  3400. add_defs = malloc(sizeof(void*) * upb_strtable_count(&addtab));
  3401. if (add_defs == NULL) goto oom_err;
  3402. upb_strtable_begin(&iter, &addtab);
  3403. for (n = 0; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  3404. add_defs[n++] = upb_value_getptr(upb_strtable_iter_value(&iter));
  3405. }
  3406. if (!upb_def_freeze(add_defs, n, status)) goto err;
  3407. /* This must be delayed until all errors have been detected, since error
  3408. * recovery code uses this table to cleanup defs. */
  3409. upb_strtable_uninit(&addtab);
  3410. /* TODO(haberman) we don't properly handle errors after this point (like
  3411. * OOM in upb_strtable_insert() below). */
  3412. for (i = 0; i < n; i++) {
  3413. upb_def *def = add_defs[i];
  3414. const char *name = upb_def_fullname(def);
  3415. upb_value v;
  3416. bool success;
  3417. if (upb_strtable_remove(&s->symtab, name, &v)) {
  3418. const upb_def *def = upb_value_getptr(v);
  3419. upb_def_unref(def, s);
  3420. }
  3421. success = upb_strtable_insert(&s->symtab, name, upb_value_ptr(def));
  3422. UPB_ASSERT_VAR(success, success == true);
  3423. }
  3424. free(add_defs);
  3425. return true;
  3426. oom_err:
  3427. upb_status_seterrmsg(status, "out of memory");
  3428. err: {
  3429. /* For defs the user passed in, we need to donate the refs back. For defs
  3430. * we dup'd, we need to just unref them. */
  3431. upb_strtable_begin(&iter, &addtab);
  3432. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  3433. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
  3434. bool came_from_user = def->came_from_user;
  3435. def->came_from_user = false;
  3436. if (came_from_user) {
  3437. upb_def_donateref(def, s, ref_donor);
  3438. } else {
  3439. upb_def_unref(def, s);
  3440. }
  3441. }
  3442. }
  3443. upb_strtable_uninit(&addtab);
  3444. free(add_defs);
  3445. assert(!upb_ok(status));
  3446. return false;
  3447. }
  3448. /* Iteration. */
  3449. static void advance_to_matching(upb_symtab_iter *iter) {
  3450. if (iter->type == UPB_DEF_ANY)
  3451. return;
  3452. while (!upb_strtable_done(&iter->iter) &&
  3453. iter->type != upb_symtab_iter_def(iter)->type) {
  3454. upb_strtable_next(&iter->iter);
  3455. }
  3456. }
  3457. void upb_symtab_begin(upb_symtab_iter *iter, const upb_symtab *s,
  3458. upb_deftype_t type) {
  3459. upb_strtable_begin(&iter->iter, &s->symtab);
  3460. iter->type = type;
  3461. advance_to_matching(iter);
  3462. }
  3463. void upb_symtab_next(upb_symtab_iter *iter) {
  3464. upb_strtable_next(&iter->iter);
  3465. advance_to_matching(iter);
  3466. }
  3467. bool upb_symtab_done(const upb_symtab_iter *iter) {
  3468. return upb_strtable_done(&iter->iter);
  3469. }
  3470. const upb_def *upb_symtab_iter_def(const upb_symtab_iter *iter) {
  3471. return upb_value_getptr(upb_strtable_iter_value(&iter->iter));
  3472. }
  3473. /*
  3474. ** upb_table Implementation
  3475. **
  3476. ** Implementation is heavily inspired by Lua's ltable.c.
  3477. */
  3478. #include <stdlib.h>
  3479. #include <string.h>
  3480. #define UPB_MAXARRSIZE 16 /* 64k. */
  3481. /* From Chromium. */
  3482. #define ARRAY_SIZE(x) \
  3483. ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
  3484. static const double MAX_LOAD = 0.85;
  3485. /* The minimum utilization of the array part of a mixed hash/array table. This
  3486. * is a speed/memory-usage tradeoff (though it's not straightforward because of
  3487. * cache effects). The lower this is, the more memory we'll use. */
  3488. static const double MIN_DENSITY = 0.1;
  3489. bool is_pow2(uint64_t v) { return v == 0 || (v & (v - 1)) == 0; }
  3490. int log2ceil(uint64_t v) {
  3491. int ret = 0;
  3492. bool pow2 = is_pow2(v);
  3493. while (v >>= 1) ret++;
  3494. ret = pow2 ? ret : ret + 1; /* Ceiling. */
  3495. return UPB_MIN(UPB_MAXARRSIZE, ret);
  3496. }
  3497. char *upb_strdup(const char *s) {
  3498. return upb_strdup2(s, strlen(s));
  3499. }
  3500. char *upb_strdup2(const char *s, size_t len) {
  3501. size_t n;
  3502. char *p;
  3503. /* Prevent overflow errors. */
  3504. if (len == SIZE_MAX) return NULL;
  3505. /* Always null-terminate, even if binary data; but don't rely on the input to
  3506. * have a null-terminating byte since it may be a raw binary buffer. */
  3507. n = len + 1;
  3508. p = malloc(n);
  3509. if (p) {
  3510. memcpy(p, s, len);
  3511. p[len] = 0;
  3512. }
  3513. return p;
  3514. }
  3515. /* A type to represent the lookup key of either a strtable or an inttable. */
  3516. typedef union {
  3517. uintptr_t num;
  3518. struct {
  3519. const char *str;
  3520. size_t len;
  3521. } str;
  3522. } lookupkey_t;
  3523. static lookupkey_t strkey2(const char *str, size_t len) {
  3524. lookupkey_t k;
  3525. k.str.str = str;
  3526. k.str.len = len;
  3527. return k;
  3528. }
  3529. static lookupkey_t intkey(uintptr_t key) {
  3530. lookupkey_t k;
  3531. k.num = key;
  3532. return k;
  3533. }
  3534. typedef uint32_t hashfunc_t(upb_tabkey key);
  3535. typedef bool eqlfunc_t(upb_tabkey k1, lookupkey_t k2);
  3536. /* Base table (shared code) ***************************************************/
  3537. /* For when we need to cast away const. */
  3538. static upb_tabent *mutable_entries(upb_table *t) {
  3539. return (upb_tabent*)t->entries;
  3540. }
  3541. static bool isfull(upb_table *t) {
  3542. if (upb_table_size(t) == 0) {
  3543. return true;
  3544. } else {
  3545. return ((double)(t->count + 1) / upb_table_size(t)) > MAX_LOAD;
  3546. }
  3547. }
  3548. static bool init(upb_table *t, upb_ctype_t ctype, uint8_t size_lg2) {
  3549. size_t bytes;
  3550. t->count = 0;
  3551. t->ctype = ctype;
  3552. t->size_lg2 = size_lg2;
  3553. t->mask = upb_table_size(t) ? upb_table_size(t) - 1 : 0;
  3554. bytes = upb_table_size(t) * sizeof(upb_tabent);
  3555. if (bytes > 0) {
  3556. t->entries = malloc(bytes);
  3557. if (!t->entries) return false;
  3558. memset(mutable_entries(t), 0, bytes);
  3559. } else {
  3560. t->entries = NULL;
  3561. }
  3562. return true;
  3563. }
  3564. static void uninit(upb_table *t) { free(mutable_entries(t)); }
  3565. static upb_tabent *emptyent(upb_table *t) {
  3566. upb_tabent *e = mutable_entries(t) + upb_table_size(t);
  3567. while (1) { if (upb_tabent_isempty(--e)) return e; assert(e > t->entries); }
  3568. }
  3569. static upb_tabent *getentry_mutable(upb_table *t, uint32_t hash) {
  3570. return (upb_tabent*)upb_getentry(t, hash);
  3571. }
  3572. static const upb_tabent *findentry(const upb_table *t, lookupkey_t key,
  3573. uint32_t hash, eqlfunc_t *eql) {
  3574. const upb_tabent *e;
  3575. if (t->size_lg2 == 0) return NULL;
  3576. e = upb_getentry(t, hash);
  3577. if (upb_tabent_isempty(e)) return NULL;
  3578. while (1) {
  3579. if (eql(e->key, key)) return e;
  3580. if ((e = e->next) == NULL) return NULL;
  3581. }
  3582. }
  3583. static upb_tabent *findentry_mutable(upb_table *t, lookupkey_t key,
  3584. uint32_t hash, eqlfunc_t *eql) {
  3585. return (upb_tabent*)findentry(t, key, hash, eql);
  3586. }
  3587. static bool lookup(const upb_table *t, lookupkey_t key, upb_value *v,
  3588. uint32_t hash, eqlfunc_t *eql) {
  3589. const upb_tabent *e = findentry(t, key, hash, eql);
  3590. if (e) {
  3591. if (v) {
  3592. _upb_value_setval(v, e->val.val, t->ctype);
  3593. }
  3594. return true;
  3595. } else {
  3596. return false;
  3597. }
  3598. }
  3599. /* The given key must not already exist in the table. */
  3600. static void insert(upb_table *t, lookupkey_t key, upb_tabkey tabkey,
  3601. upb_value val, uint32_t hash,
  3602. hashfunc_t *hashfunc, eqlfunc_t *eql) {
  3603. upb_tabent *mainpos_e;
  3604. upb_tabent *our_e;
  3605. UPB_UNUSED(eql);
  3606. UPB_UNUSED(key);
  3607. assert(findentry(t, key, hash, eql) == NULL);
  3608. assert(val.ctype == t->ctype);
  3609. t->count++;
  3610. mainpos_e = getentry_mutable(t, hash);
  3611. our_e = mainpos_e;
  3612. if (upb_tabent_isempty(mainpos_e)) {
  3613. /* Our main position is empty; use it. */
  3614. our_e->next = NULL;
  3615. } else {
  3616. /* Collision. */
  3617. upb_tabent *new_e = emptyent(t);
  3618. /* Head of collider's chain. */
  3619. upb_tabent *chain = getentry_mutable(t, hashfunc(mainpos_e->key));
  3620. if (chain == mainpos_e) {
  3621. /* Existing ent is in its main posisiton (it has the same hash as us, and
  3622. * is the head of our chain). Insert to new ent and append to this chain. */
  3623. new_e->next = mainpos_e->next;
  3624. mainpos_e->next = new_e;
  3625. our_e = new_e;
  3626. } else {
  3627. /* Existing ent is not in its main position (it is a node in some other
  3628. * chain). This implies that no existing ent in the table has our hash.
  3629. * Evict it (updating its chain) and use its ent for head of our chain. */
  3630. *new_e = *mainpos_e; /* copies next. */
  3631. while (chain->next != mainpos_e) {
  3632. chain = (upb_tabent*)chain->next;
  3633. assert(chain);
  3634. }
  3635. chain->next = new_e;
  3636. our_e = mainpos_e;
  3637. our_e->next = NULL;
  3638. }
  3639. }
  3640. our_e->key = tabkey;
  3641. our_e->val.val = val.val;
  3642. assert(findentry(t, key, hash, eql) == our_e);
  3643. }
  3644. static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
  3645. upb_tabkey *removed, uint32_t hash, eqlfunc_t *eql) {
  3646. upb_tabent *chain = getentry_mutable(t, hash);
  3647. if (upb_tabent_isempty(chain)) return false;
  3648. if (eql(chain->key, key)) {
  3649. /* Element to remove is at the head of its chain. */
  3650. t->count--;
  3651. if (val) {
  3652. _upb_value_setval(val, chain->val.val, t->ctype);
  3653. }
  3654. if (chain->next) {
  3655. upb_tabent *move = (upb_tabent*)chain->next;
  3656. *chain = *move;
  3657. if (removed) *removed = move->key;
  3658. move->key = 0; /* Make the slot empty. */
  3659. } else {
  3660. if (removed) *removed = chain->key;
  3661. chain->key = 0; /* Make the slot empty. */
  3662. }
  3663. return true;
  3664. } else {
  3665. /* Element to remove is either in a non-head position or not in the
  3666. * table. */
  3667. while (chain->next && !eql(chain->next->key, key))
  3668. chain = (upb_tabent*)chain->next;
  3669. if (chain->next) {
  3670. /* Found element to remove. */
  3671. upb_tabent *rm;
  3672. if (val) {
  3673. _upb_value_setval(val, chain->next->val.val, t->ctype);
  3674. }
  3675. rm = (upb_tabent*)chain->next;
  3676. if (removed) *removed = rm->key;
  3677. rm->key = 0;
  3678. chain->next = rm->next;
  3679. t->count--;
  3680. return true;
  3681. } else {
  3682. return false;
  3683. }
  3684. }
  3685. }
  3686. static size_t next(const upb_table *t, size_t i) {
  3687. do {
  3688. if (++i >= upb_table_size(t))
  3689. return SIZE_MAX;
  3690. } while(upb_tabent_isempty(&t->entries[i]));
  3691. return i;
  3692. }
  3693. static size_t begin(const upb_table *t) {
  3694. return next(t, -1);
  3695. }
  3696. /* upb_strtable ***************************************************************/
  3697. /* A simple "subclass" of upb_table that only adds a hash function for strings. */
  3698. static upb_tabkey strcopy(lookupkey_t k2) {
  3699. char *str = malloc(k2.str.len + sizeof(uint32_t) + 1);
  3700. if (str == NULL) return 0;
  3701. memcpy(str, &k2.str.len, sizeof(uint32_t));
  3702. memcpy(str + sizeof(uint32_t), k2.str.str, k2.str.len + 1);
  3703. return (uintptr_t)str;
  3704. }
  3705. static uint32_t strhash(upb_tabkey key) {
  3706. uint32_t len;
  3707. char *str = upb_tabstr(key, &len);
  3708. return MurmurHash2(str, len, 0);
  3709. }
  3710. static bool streql(upb_tabkey k1, lookupkey_t k2) {
  3711. uint32_t len;
  3712. char *str = upb_tabstr(k1, &len);
  3713. return len == k2.str.len && memcmp(str, k2.str.str, len) == 0;
  3714. }
  3715. bool upb_strtable_init(upb_strtable *t, upb_ctype_t ctype) {
  3716. return init(&t->t, ctype, 2);
  3717. }
  3718. void upb_strtable_uninit(upb_strtable *t) {
  3719. size_t i;
  3720. for (i = 0; i < upb_table_size(&t->t); i++)
  3721. free((void*)t->t.entries[i].key);
  3722. uninit(&t->t);
  3723. }
  3724. bool upb_strtable_resize(upb_strtable *t, size_t size_lg2) {
  3725. upb_strtable new_table;
  3726. upb_strtable_iter i;
  3727. if (!init(&new_table.t, t->t.ctype, size_lg2))
  3728. return false;
  3729. upb_strtable_begin(&i, t);
  3730. for ( ; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  3731. upb_strtable_insert2(
  3732. &new_table,
  3733. upb_strtable_iter_key(&i),
  3734. upb_strtable_iter_keylength(&i),
  3735. upb_strtable_iter_value(&i));
  3736. }
  3737. upb_strtable_uninit(t);
  3738. *t = new_table;
  3739. return true;
  3740. }
  3741. bool upb_strtable_insert2(upb_strtable *t, const char *k, size_t len,
  3742. upb_value v) {
  3743. lookupkey_t key;
  3744. upb_tabkey tabkey;
  3745. uint32_t hash;
  3746. if (isfull(&t->t)) {
  3747. /* Need to resize. New table of double the size, add old elements to it. */
  3748. if (!upb_strtable_resize(t, t->t.size_lg2 + 1)) {
  3749. return false;
  3750. }
  3751. }
  3752. key = strkey2(k, len);
  3753. tabkey = strcopy(key);
  3754. if (tabkey == 0) return false;
  3755. hash = MurmurHash2(key.str.str, key.str.len, 0);
  3756. insert(&t->t, key, tabkey, v, hash, &strhash, &streql);
  3757. return true;
  3758. }
  3759. bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
  3760. upb_value *v) {
  3761. uint32_t hash = MurmurHash2(key, len, 0);
  3762. return lookup(&t->t, strkey2(key, len), v, hash, &streql);
  3763. }
  3764. bool upb_strtable_remove2(upb_strtable *t, const char *key, size_t len,
  3765. upb_value *val) {
  3766. uint32_t hash = MurmurHash2(key, strlen(key), 0);
  3767. upb_tabkey tabkey;
  3768. if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
  3769. free((void*)tabkey);
  3770. return true;
  3771. } else {
  3772. return false;
  3773. }
  3774. }
  3775. /* Iteration */
  3776. static const upb_tabent *str_tabent(const upb_strtable_iter *i) {
  3777. return &i->t->t.entries[i->index];
  3778. }
  3779. void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t) {
  3780. i->t = t;
  3781. i->index = begin(&t->t);
  3782. }
  3783. void upb_strtable_next(upb_strtable_iter *i) {
  3784. i->index = next(&i->t->t, i->index);
  3785. }
  3786. bool upb_strtable_done(const upb_strtable_iter *i) {
  3787. return i->index >= upb_table_size(&i->t->t) ||
  3788. upb_tabent_isempty(str_tabent(i));
  3789. }
  3790. const char *upb_strtable_iter_key(upb_strtable_iter *i) {
  3791. assert(!upb_strtable_done(i));
  3792. return upb_tabstr(str_tabent(i)->key, NULL);
  3793. }
  3794. size_t upb_strtable_iter_keylength(upb_strtable_iter *i) {
  3795. uint32_t len;
  3796. assert(!upb_strtable_done(i));
  3797. upb_tabstr(str_tabent(i)->key, &len);
  3798. return len;
  3799. }
  3800. upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
  3801. assert(!upb_strtable_done(i));
  3802. return _upb_value_val(str_tabent(i)->val.val, i->t->t.ctype);
  3803. }
  3804. void upb_strtable_iter_setdone(upb_strtable_iter *i) {
  3805. i->index = SIZE_MAX;
  3806. }
  3807. bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
  3808. const upb_strtable_iter *i2) {
  3809. if (upb_strtable_done(i1) && upb_strtable_done(i2))
  3810. return true;
  3811. return i1->t == i2->t && i1->index == i2->index;
  3812. }
  3813. /* upb_inttable ***************************************************************/
  3814. /* For inttables we use a hybrid structure where small keys are kept in an
  3815. * array and large keys are put in the hash table. */
  3816. static uint32_t inthash(upb_tabkey key) { return upb_inthash(key); }
  3817. static bool inteql(upb_tabkey k1, lookupkey_t k2) {
  3818. return k1 == k2.num;
  3819. }
  3820. static upb_tabval *mutable_array(upb_inttable *t) {
  3821. return (upb_tabval*)t->array;
  3822. }
  3823. static upb_tabval *inttable_val(upb_inttable *t, uintptr_t key) {
  3824. if (key < t->array_size) {
  3825. return upb_arrhas(t->array[key]) ? &(mutable_array(t)[key]) : NULL;
  3826. } else {
  3827. upb_tabent *e =
  3828. findentry_mutable(&t->t, intkey(key), upb_inthash(key), &inteql);
  3829. return e ? &e->val : NULL;
  3830. }
  3831. }
  3832. static const upb_tabval *inttable_val_const(const upb_inttable *t,
  3833. uintptr_t key) {
  3834. return inttable_val((upb_inttable*)t, key);
  3835. }
  3836. size_t upb_inttable_count(const upb_inttable *t) {
  3837. return t->t.count + t->array_count;
  3838. }
  3839. static void check(upb_inttable *t) {
  3840. UPB_UNUSED(t);
  3841. #if defined(UPB_DEBUG_TABLE) && !defined(NDEBUG)
  3842. {
  3843. /* This check is very expensive (makes inserts/deletes O(N)). */
  3844. size_t count = 0;
  3845. upb_inttable_iter i;
  3846. upb_inttable_begin(&i, t);
  3847. for(; !upb_inttable_done(&i); upb_inttable_next(&i), count++) {
  3848. assert(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
  3849. }
  3850. assert(count == upb_inttable_count(t));
  3851. }
  3852. #endif
  3853. }
  3854. bool upb_inttable_sizedinit(upb_inttable *t, upb_ctype_t ctype,
  3855. size_t asize, int hsize_lg2) {
  3856. size_t array_bytes;
  3857. if (!init(&t->t, ctype, hsize_lg2)) return false;
  3858. /* Always make the array part at least 1 long, so that we know key 0
  3859. * won't be in the hash part, which simplifies things. */
  3860. t->array_size = UPB_MAX(1, asize);
  3861. t->array_count = 0;
  3862. array_bytes = t->array_size * sizeof(upb_value);
  3863. t->array = malloc(array_bytes);
  3864. if (!t->array) {
  3865. uninit(&t->t);
  3866. return false;
  3867. }
  3868. memset(mutable_array(t), 0xff, array_bytes);
  3869. check(t);
  3870. return true;
  3871. }
  3872. bool upb_inttable_init(upb_inttable *t, upb_ctype_t ctype) {
  3873. return upb_inttable_sizedinit(t, ctype, 0, 4);
  3874. }
  3875. void upb_inttable_uninit(upb_inttable *t) {
  3876. uninit(&t->t);
  3877. free(mutable_array(t));
  3878. }
  3879. bool upb_inttable_insert(upb_inttable *t, uintptr_t key, upb_value val) {
  3880. /* XXX: Table can't store value (uint64_t)-1. Need to somehow statically
  3881. * guarantee that this is not necessary, or fix the limitation. */
  3882. upb_tabval tabval;
  3883. tabval.val = val.val;
  3884. UPB_UNUSED(tabval);
  3885. assert(upb_arrhas(tabval));
  3886. if (key < t->array_size) {
  3887. assert(!upb_arrhas(t->array[key]));
  3888. t->array_count++;
  3889. mutable_array(t)[key].val = val.val;
  3890. } else {
  3891. if (isfull(&t->t)) {
  3892. /* Need to resize the hash part, but we re-use the array part. */
  3893. size_t i;
  3894. upb_table new_table;
  3895. if (!init(&new_table, t->t.ctype, t->t.size_lg2 + 1))
  3896. return false;
  3897. for (i = begin(&t->t); i < upb_table_size(&t->t); i = next(&t->t, i)) {
  3898. const upb_tabent *e = &t->t.entries[i];
  3899. uint32_t hash;
  3900. upb_value v;
  3901. _upb_value_setval(&v, e->val.val, t->t.ctype);
  3902. hash = upb_inthash(e->key);
  3903. insert(&new_table, intkey(e->key), e->key, v, hash, &inthash, &inteql);
  3904. }
  3905. assert(t->t.count == new_table.count);
  3906. uninit(&t->t);
  3907. t->t = new_table;
  3908. }
  3909. insert(&t->t, intkey(key), key, val, upb_inthash(key), &inthash, &inteql);
  3910. }
  3911. check(t);
  3912. return true;
  3913. }
  3914. bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v) {
  3915. const upb_tabval *table_v = inttable_val_const(t, key);
  3916. if (!table_v) return false;
  3917. if (v) _upb_value_setval(v, table_v->val, t->t.ctype);
  3918. return true;
  3919. }
  3920. bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val) {
  3921. upb_tabval *table_v = inttable_val(t, key);
  3922. if (!table_v) return false;
  3923. table_v->val = val.val;
  3924. return true;
  3925. }
  3926. bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val) {
  3927. bool success;
  3928. if (key < t->array_size) {
  3929. if (upb_arrhas(t->array[key])) {
  3930. upb_tabval empty = UPB_TABVALUE_EMPTY_INIT;
  3931. t->array_count--;
  3932. if (val) {
  3933. _upb_value_setval(val, t->array[key].val, t->t.ctype);
  3934. }
  3935. mutable_array(t)[key] = empty;
  3936. success = true;
  3937. } else {
  3938. success = false;
  3939. }
  3940. } else {
  3941. upb_tabkey removed;
  3942. uint32_t hash = upb_inthash(key);
  3943. success = rm(&t->t, intkey(key), val, &removed, hash, &inteql);
  3944. }
  3945. check(t);
  3946. return success;
  3947. }
  3948. bool upb_inttable_push(upb_inttable *t, upb_value val) {
  3949. return upb_inttable_insert(t, upb_inttable_count(t), val);
  3950. }
  3951. upb_value upb_inttable_pop(upb_inttable *t) {
  3952. upb_value val;
  3953. bool ok = upb_inttable_remove(t, upb_inttable_count(t) - 1, &val);
  3954. UPB_ASSERT_VAR(ok, ok);
  3955. return val;
  3956. }
  3957. bool upb_inttable_insertptr(upb_inttable *t, const void *key, upb_value val) {
  3958. return upb_inttable_insert(t, (uintptr_t)key, val);
  3959. }
  3960. bool upb_inttable_lookupptr(const upb_inttable *t, const void *key,
  3961. upb_value *v) {
  3962. return upb_inttable_lookup(t, (uintptr_t)key, v);
  3963. }
  3964. bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val) {
  3965. return upb_inttable_remove(t, (uintptr_t)key, val);
  3966. }
  3967. void upb_inttable_compact(upb_inttable *t) {
  3968. /* A power-of-two histogram of the table keys. */
  3969. size_t counts[UPB_MAXARRSIZE + 1] = {0};
  3970. /* The max key in each bucket. */
  3971. uintptr_t max[UPB_MAXARRSIZE + 1] = {0};
  3972. upb_inttable_iter i;
  3973. size_t arr_count;
  3974. int size_lg2;
  3975. upb_inttable new_t;
  3976. upb_inttable_begin(&i, t);
  3977. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  3978. uintptr_t key = upb_inttable_iter_key(&i);
  3979. int bucket = log2ceil(key);
  3980. max[bucket] = UPB_MAX(max[bucket], key);
  3981. counts[bucket]++;
  3982. }
  3983. /* Find the largest power of two that satisfies the MIN_DENSITY
  3984. * definition (while actually having some keys). */
  3985. arr_count = upb_inttable_count(t);
  3986. for (size_lg2 = ARRAY_SIZE(counts) - 1; size_lg2 > 0; size_lg2--) {
  3987. if (counts[size_lg2] == 0) {
  3988. /* We can halve again without losing any entries. */
  3989. continue;
  3990. } else if (arr_count >= (1 << size_lg2) * MIN_DENSITY) {
  3991. break;
  3992. }
  3993. arr_count -= counts[size_lg2];
  3994. }
  3995. assert(arr_count <= upb_inttable_count(t));
  3996. {
  3997. /* Insert all elements into new, perfectly-sized table. */
  3998. size_t arr_size = max[size_lg2] + 1; /* +1 so arr[max] will fit. */
  3999. size_t hash_count = upb_inttable_count(t) - arr_count;
  4000. size_t hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
  4001. size_t hashsize_lg2 = log2ceil(hash_size);
  4002. upb_inttable_sizedinit(&new_t, t->t.ctype, arr_size, hashsize_lg2);
  4003. upb_inttable_begin(&i, t);
  4004. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  4005. uintptr_t k = upb_inttable_iter_key(&i);
  4006. upb_inttable_insert(&new_t, k, upb_inttable_iter_value(&i));
  4007. }
  4008. assert(new_t.array_size == arr_size);
  4009. assert(new_t.t.size_lg2 == hashsize_lg2);
  4010. }
  4011. upb_inttable_uninit(t);
  4012. *t = new_t;
  4013. }
  4014. /* Iteration. */
  4015. static const upb_tabent *int_tabent(const upb_inttable_iter *i) {
  4016. assert(!i->array_part);
  4017. return &i->t->t.entries[i->index];
  4018. }
  4019. static upb_tabval int_arrent(const upb_inttable_iter *i) {
  4020. assert(i->array_part);
  4021. return i->t->array[i->index];
  4022. }
  4023. void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t) {
  4024. i->t = t;
  4025. i->index = -1;
  4026. i->array_part = true;
  4027. upb_inttable_next(i);
  4028. }
  4029. void upb_inttable_next(upb_inttable_iter *iter) {
  4030. const upb_inttable *t = iter->t;
  4031. if (iter->array_part) {
  4032. while (++iter->index < t->array_size) {
  4033. if (upb_arrhas(int_arrent(iter))) {
  4034. return;
  4035. }
  4036. }
  4037. iter->array_part = false;
  4038. iter->index = begin(&t->t);
  4039. } else {
  4040. iter->index = next(&t->t, iter->index);
  4041. }
  4042. }
  4043. bool upb_inttable_done(const upb_inttable_iter *i) {
  4044. if (i->array_part) {
  4045. return i->index >= i->t->array_size ||
  4046. !upb_arrhas(int_arrent(i));
  4047. } else {
  4048. return i->index >= upb_table_size(&i->t->t) ||
  4049. upb_tabent_isempty(int_tabent(i));
  4050. }
  4051. }
  4052. uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i) {
  4053. assert(!upb_inttable_done(i));
  4054. return i->array_part ? i->index : int_tabent(i)->key;
  4055. }
  4056. upb_value upb_inttable_iter_value(const upb_inttable_iter *i) {
  4057. assert(!upb_inttable_done(i));
  4058. return _upb_value_val(
  4059. i->array_part ? i->t->array[i->index].val : int_tabent(i)->val.val,
  4060. i->t->t.ctype);
  4061. }
  4062. void upb_inttable_iter_setdone(upb_inttable_iter *i) {
  4063. i->index = SIZE_MAX;
  4064. i->array_part = false;
  4065. }
  4066. bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
  4067. const upb_inttable_iter *i2) {
  4068. if (upb_inttable_done(i1) && upb_inttable_done(i2))
  4069. return true;
  4070. return i1->t == i2->t && i1->index == i2->index &&
  4071. i1->array_part == i2->array_part;
  4072. }
  4073. #ifdef UPB_UNALIGNED_READS_OK
  4074. /* -----------------------------------------------------------------------------
  4075. * MurmurHash2, by Austin Appleby (released as public domain).
  4076. * Reformatted and C99-ified by Joshua Haberman.
  4077. * Note - This code makes a few assumptions about how your machine behaves -
  4078. * 1. We can read a 4-byte value from any address without crashing
  4079. * 2. sizeof(int) == 4 (in upb this limitation is removed by using uint32_t
  4080. * And it has a few limitations -
  4081. * 1. It will not work incrementally.
  4082. * 2. It will not produce the same results on little-endian and big-endian
  4083. * machines. */
  4084. uint32_t MurmurHash2(const void *key, size_t len, uint32_t seed) {
  4085. /* 'm' and 'r' are mixing constants generated offline.
  4086. * They're not really 'magic', they just happen to work well. */
  4087. const uint32_t m = 0x5bd1e995;
  4088. const int32_t r = 24;
  4089. /* Initialize the hash to a 'random' value */
  4090. uint32_t h = seed ^ len;
  4091. /* Mix 4 bytes at a time into the hash */
  4092. const uint8_t * data = (const uint8_t *)key;
  4093. while(len >= 4) {
  4094. uint32_t k = *(uint32_t *)data;
  4095. k *= m;
  4096. k ^= k >> r;
  4097. k *= m;
  4098. h *= m;
  4099. h ^= k;
  4100. data += 4;
  4101. len -= 4;
  4102. }
  4103. /* Handle the last few bytes of the input array */
  4104. switch(len) {
  4105. case 3: h ^= data[2] << 16;
  4106. case 2: h ^= data[1] << 8;
  4107. case 1: h ^= data[0]; h *= m;
  4108. };
  4109. /* Do a few final mixes of the hash to ensure the last few
  4110. * bytes are well-incorporated. */
  4111. h ^= h >> 13;
  4112. h *= m;
  4113. h ^= h >> 15;
  4114. return h;
  4115. }
  4116. #else /* !UPB_UNALIGNED_READS_OK */
  4117. /* -----------------------------------------------------------------------------
  4118. * MurmurHashAligned2, by Austin Appleby
  4119. * Same algorithm as MurmurHash2, but only does aligned reads - should be safer
  4120. * on certain platforms.
  4121. * Performance will be lower than MurmurHash2 */
  4122. #define MIX(h,k,m) { k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; }
  4123. uint32_t MurmurHash2(const void * key, size_t len, uint32_t seed) {
  4124. const uint32_t m = 0x5bd1e995;
  4125. const int32_t r = 24;
  4126. const uint8_t * data = (const uint8_t *)key;
  4127. uint32_t h = seed ^ len;
  4128. uint8_t align = (uintptr_t)data & 3;
  4129. if(align && (len >= 4)) {
  4130. /* Pre-load the temp registers */
  4131. uint32_t t = 0, d = 0;
  4132. int32_t sl;
  4133. int32_t sr;
  4134. switch(align) {
  4135. case 1: t |= data[2] << 16;
  4136. case 2: t |= data[1] << 8;
  4137. case 3: t |= data[0];
  4138. }
  4139. t <<= (8 * align);
  4140. data += 4-align;
  4141. len -= 4-align;
  4142. sl = 8 * (4-align);
  4143. sr = 8 * align;
  4144. /* Mix */
  4145. while(len >= 4) {
  4146. uint32_t k;
  4147. d = *(uint32_t *)data;
  4148. t = (t >> sr) | (d << sl);
  4149. k = t;
  4150. MIX(h,k,m);
  4151. t = d;
  4152. data += 4;
  4153. len -= 4;
  4154. }
  4155. /* Handle leftover data in temp registers */
  4156. d = 0;
  4157. if(len >= align) {
  4158. uint32_t k;
  4159. switch(align) {
  4160. case 3: d |= data[2] << 16;
  4161. case 2: d |= data[1] << 8;
  4162. case 1: d |= data[0];
  4163. }
  4164. k = (t >> sr) | (d << sl);
  4165. MIX(h,k,m);
  4166. data += align;
  4167. len -= align;
  4168. /* ----------
  4169. * Handle tail bytes */
  4170. switch(len) {
  4171. case 3: h ^= data[2] << 16;
  4172. case 2: h ^= data[1] << 8;
  4173. case 1: h ^= data[0]; h *= m;
  4174. };
  4175. } else {
  4176. switch(len) {
  4177. case 3: d |= data[2] << 16;
  4178. case 2: d |= data[1] << 8;
  4179. case 1: d |= data[0];
  4180. case 0: h ^= (t >> sr) | (d << sl); h *= m;
  4181. }
  4182. }
  4183. h ^= h >> 13;
  4184. h *= m;
  4185. h ^= h >> 15;
  4186. return h;
  4187. } else {
  4188. while(len >= 4) {
  4189. uint32_t k = *(uint32_t *)data;
  4190. MIX(h,k,m);
  4191. data += 4;
  4192. len -= 4;
  4193. }
  4194. /* ----------
  4195. * Handle tail bytes */
  4196. switch(len) {
  4197. case 3: h ^= data[2] << 16;
  4198. case 2: h ^= data[1] << 8;
  4199. case 1: h ^= data[0]; h *= m;
  4200. };
  4201. h ^= h >> 13;
  4202. h *= m;
  4203. h ^= h >> 15;
  4204. return h;
  4205. }
  4206. }
  4207. #undef MIX
  4208. #endif /* UPB_UNALIGNED_READS_OK */
  4209. #include <errno.h>
  4210. #include <stdarg.h>
  4211. #include <stddef.h>
  4212. #include <stdint.h>
  4213. #include <stdio.h>
  4214. #include <stdlib.h>
  4215. #include <string.h>
  4216. bool upb_dumptostderr(void *closure, const upb_status* status) {
  4217. UPB_UNUSED(closure);
  4218. fprintf(stderr, "%s\n", upb_status_errmsg(status));
  4219. return false;
  4220. }
  4221. /* Guarantee null-termination and provide ellipsis truncation.
  4222. * It may be tempting to "optimize" this by initializing these final
  4223. * four bytes up-front and then being careful never to overwrite them,
  4224. * this is safer and simpler. */
  4225. static void nullz(upb_status *status) {
  4226. const char *ellipsis = "...";
  4227. size_t len = strlen(ellipsis);
  4228. assert(sizeof(status->msg) > len);
  4229. memcpy(status->msg + sizeof(status->msg) - len, ellipsis, len);
  4230. }
  4231. void upb_status_clear(upb_status *status) {
  4232. if (!status) return;
  4233. status->ok_ = true;
  4234. status->code_ = 0;
  4235. status->msg[0] = '\0';
  4236. }
  4237. bool upb_ok(const upb_status *status) { return status->ok_; }
  4238. upb_errorspace *upb_status_errspace(const upb_status *status) {
  4239. return status->error_space_;
  4240. }
  4241. int upb_status_errcode(const upb_status *status) { return status->code_; }
  4242. const char *upb_status_errmsg(const upb_status *status) { return status->msg; }
  4243. void upb_status_seterrmsg(upb_status *status, const char *msg) {
  4244. if (!status) return;
  4245. status->ok_ = false;
  4246. strncpy(status->msg, msg, sizeof(status->msg));
  4247. nullz(status);
  4248. }
  4249. void upb_status_seterrf(upb_status *status, const char *fmt, ...) {
  4250. va_list args;
  4251. va_start(args, fmt);
  4252. upb_status_vseterrf(status, fmt, args);
  4253. va_end(args);
  4254. }
  4255. void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args) {
  4256. if (!status) return;
  4257. status->ok_ = false;
  4258. _upb_vsnprintf(status->msg, sizeof(status->msg), fmt, args);
  4259. nullz(status);
  4260. }
  4261. void upb_status_seterrcode(upb_status *status, upb_errorspace *space,
  4262. int code) {
  4263. if (!status) return;
  4264. status->ok_ = false;
  4265. status->error_space_ = space;
  4266. status->code_ = code;
  4267. space->set_message(status, code);
  4268. }
  4269. void upb_status_copy(upb_status *to, const upb_status *from) {
  4270. if (!to) return;
  4271. *to = *from;
  4272. }
  4273. /* This file was generated by upbc (the upb compiler).
  4274. * Do not edit -- your changes will be discarded when the file is
  4275. * regenerated. */
  4276. static const upb_msgdef msgs[22];
  4277. static const upb_fielddef fields[105];
  4278. static const upb_enumdef enums[5];
  4279. static const upb_tabent strentries[268];
  4280. static const upb_tabent intentries[18];
  4281. static const upb_tabval arrays[184];
  4282. #ifdef UPB_DEBUG_REFS
  4283. static upb_inttable reftables[266];
  4284. #endif
  4285. static const upb_msgdef msgs[22] = {
  4286. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto", 40, 8, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[0], 11, 10), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[0]),&reftables[0], &reftables[1]),
  4287. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ExtensionRange", 4, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[11], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[16]),&reftables[2], &reftables[3]),
  4288. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ReservedRange", 4, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[14], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[20]),&reftables[4], &reftables[5]),
  4289. UPB_MSGDEF_INIT("google.protobuf.EnumDescriptorProto", 11, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[17], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[24]),&reftables[6], &reftables[7]),
  4290. UPB_MSGDEF_INIT("google.protobuf.EnumOptions", 8, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[0], &arrays[21], 4, 2), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[28]),&reftables[8], &reftables[9]),
  4291. UPB_MSGDEF_INIT("google.protobuf.EnumValueDescriptorProto", 8, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[25], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[32]),&reftables[10], &reftables[11]),
  4292. UPB_MSGDEF_INIT("google.protobuf.EnumValueOptions", 7, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[2], &arrays[29], 2, 1), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[36]),&reftables[12], &reftables[13]),
  4293. UPB_MSGDEF_INIT("google.protobuf.FieldDescriptorProto", 23, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[31], 11, 10), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[40]),&reftables[14], &reftables[15]),
  4294. UPB_MSGDEF_INIT("google.protobuf.FieldOptions", 12, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[4], &arrays[42], 11, 6), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[56]),&reftables[16], &reftables[17]),
  4295. UPB_MSGDEF_INIT("google.protobuf.FileDescriptorProto", 42, 6, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[53], 13, 12), UPB_STRTABLE_INIT(12, 15, UPB_CTYPE_PTR, 4, &strentries[72]),&reftables[18], &reftables[19]),
  4296. UPB_MSGDEF_INIT("google.protobuf.FileDescriptorSet", 6, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[66], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[88]),&reftables[20], &reftables[21]),
  4297. UPB_MSGDEF_INIT("google.protobuf.FileOptions", 31, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[6], &arrays[68], 39, 15), UPB_STRTABLE_INIT(16, 31, UPB_CTYPE_PTR, 5, &strentries[92]),&reftables[22], &reftables[23]),
  4298. UPB_MSGDEF_INIT("google.protobuf.MessageOptions", 10, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[8], &arrays[107], 8, 4), UPB_STRTABLE_INIT(5, 7, UPB_CTYPE_PTR, 3, &strentries[124]),&reftables[24], &reftables[25]),
  4299. UPB_MSGDEF_INIT("google.protobuf.MethodDescriptorProto", 15, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[115], 7, 6), UPB_STRTABLE_INIT(6, 7, UPB_CTYPE_PTR, 3, &strentries[132]),&reftables[26], &reftables[27]),
  4300. UPB_MSGDEF_INIT("google.protobuf.MethodOptions", 7, 1, UPB_INTTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &intentries[10], &arrays[122], 1, 0), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[140]),&reftables[28], &reftables[29]),
  4301. UPB_MSGDEF_INIT("google.protobuf.OneofDescriptorProto", 5, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[123], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[144]),&reftables[30], &reftables[31]),
  4302. UPB_MSGDEF_INIT("google.protobuf.ServiceDescriptorProto", 11, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[125], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[148]),&reftables[32], &reftables[33]),
  4303. UPB_MSGDEF_INIT("google.protobuf.ServiceOptions", 7, 1, UPB_INTTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &intentries[14], &arrays[129], 1, 0), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[152]),&reftables[34], &reftables[35]),
  4304. UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo", 6, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[130], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[156]),&reftables[36], &reftables[37]),
  4305. UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo.Location", 19, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[132], 7, 5), UPB_STRTABLE_INIT(5, 7, UPB_CTYPE_PTR, 3, &strentries[160]),&reftables[38], &reftables[39]),
  4306. UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption", 18, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[139], 9, 7), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[168]),&reftables[40], &reftables[41]),
  4307. UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption.NamePart", 6, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[148], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[184]),&reftables[42], &reftables[43]),
  4308. };
  4309. static const upb_fielddef fields[105] = {
  4310. 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]),
  4311. 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]),
  4312. 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]),
  4313. 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]),
  4314. 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]),
  4315. 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]),
  4316. 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]),
  4317. 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]),
  4318. 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]),
  4319. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 1, &msgs[6], NULL, 6, 1, {0},&reftables[62], &reftables[63]),
  4320. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[4], NULL, 7, 2, {0},&reftables[64], &reftables[65]),
  4321. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 33, &msgs[17], NULL, 6, 1, {0},&reftables[66], &reftables[67]),
  4322. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[8], NULL, 8, 3, {0},&reftables[68], &reftables[69]),
  4323. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 33, &msgs[14], NULL, 6, 1, {0},&reftables[70], &reftables[71]),
  4324. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[12], NULL, 8, 3, {0},&reftables[72], &reftables[73]),
  4325. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 23, &msgs[11], NULL, 21, 10, {0},&reftables[74], &reftables[75]),
  4326. 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]),
  4327. 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]),
  4328. 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]),
  4329. 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[82], &reftables[83]),
  4330. 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[84], &reftables[85]),
  4331. 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]),
  4332. 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]),
  4333. 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]),
  4334. 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]),
  4335. 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]),
  4336. 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]),
  4337. 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]),
  4338. 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]),
  4339. 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]),
  4340. 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]),
  4341. 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]),
  4342. 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]),
  4343. 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]),
  4344. 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]),
  4345. 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]),
  4346. 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]),
  4347. 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]),
  4348. 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]),
  4349. 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]),
  4350. 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]),
  4351. 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]),
  4352. 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]),
  4353. 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]),
  4354. 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]),
  4355. 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]),
  4356. 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]),
  4357. 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]),
  4358. 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]),
  4359. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[9], NULL, 22, 6, {0},&reftables[142], &reftables[143]),
  4360. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[5], NULL, 4, 1, {0},&reftables[144], &reftables[145]),
  4361. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[13], NULL, 4, 1, {0},&reftables[146], &reftables[147]),
  4362. 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]),
  4363. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[3], NULL, 8, 2, {0},&reftables[150], &reftables[151]),
  4364. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[15], NULL, 2, 0, {0},&reftables[152], &reftables[153]),
  4365. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[16], NULL, 8, 2, {0},&reftables[154], &reftables[155]),
  4366. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[7], NULL, 4, 1, {0},&reftables[156], &reftables[157]),
  4367. 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[158], &reftables[159]),
  4368. 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]),
  4369. 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]),
  4370. 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]),
  4371. 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]),
  4372. 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[168], &reftables[169]),
  4373. 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[170], &reftables[171]),
  4374. 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]),
  4375. 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]),
  4376. 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]),
  4377. 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]),
  4378. 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[180], &reftables[181]),
  4379. 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[182], &reftables[183]),
  4380. 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[184], &reftables[185]),
  4381. 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[186], &reftables[187]),
  4382. 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[188], &reftables[189]),
  4383. 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[190], &reftables[191]),
  4384. 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[192], &reftables[193]),
  4385. 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]),
  4386. 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]),
  4387. 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]),
  4388. 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]),
  4389. 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]),
  4390. 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]),
  4391. 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]),
  4392. 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]),
  4393. 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]),
  4394. 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]),
  4395. 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]),
  4396. 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]),
  4397. 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]),
  4398. 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[220], &reftables[221]),
  4399. 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[222], &reftables[223]),
  4400. 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]),
  4401. 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]),
  4402. 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]),
  4403. 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]),
  4404. 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]),
  4405. 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[234], &reftables[235]),
  4406. 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]),
  4407. 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[238], &reftables[239]),
  4408. 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[240], &reftables[241]),
  4409. 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[242], &reftables[243]),
  4410. 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[244], &reftables[245]),
  4411. 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[246], &reftables[247]),
  4412. 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]),
  4413. 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]),
  4414. 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]),
  4415. };
  4416. static const upb_enumdef enums[5] = {
  4417. 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]),
  4418. 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]),
  4419. 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]),
  4420. 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]),
  4421. 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]),
  4422. };
  4423. static const upb_tabent strentries[268] = {
  4424. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "extension"), UPB_TABVALUE_PTR_INIT(&fields[22]), NULL},
  4425. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4426. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "reserved_name"), UPB_TABVALUE_PTR_INIT(&fields[82]), NULL},
  4427. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[52]), NULL},
  4428. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4429. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4430. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4431. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "field"), UPB_TABVALUE_PTR_INIT(&fields[25]), &strentries[12]},
  4432. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "extension_range"), UPB_TABVALUE_PTR_INIT(&fields[24]), &strentries[14]},
  4433. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4434. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "nested_type"), UPB_TABVALUE_PTR_INIT(&fields[60]), NULL},
  4435. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4436. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "reserved_range"), UPB_TABVALUE_PTR_INIT(&fields[83]), NULL},
  4437. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[70]), NULL},
  4438. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "oneof_decl"), UPB_TABVALUE_PTR_INIT(&fields[65]), NULL},
  4439. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[20]), &strentries[13]},
  4440. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[88]), NULL},
  4441. {UPB_TABKEY_STR("\003", "\000", "\000", "\000", "end"), UPB_TABVALUE_PTR_INIT(&fields[18]), NULL},
  4442. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4443. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4444. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[89]), NULL},
  4445. {UPB_TABKEY_STR("\003", "\000", "\000", "\000", "end"), UPB_TABVALUE_PTR_INIT(&fields[17]), NULL},
  4446. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4447. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4448. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4449. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "value"), UPB_TABVALUE_PTR_INIT(&fields[102]), NULL},
  4450. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[69]), NULL},
  4451. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[53]), &strentries[26]},
  4452. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[100]), NULL},
  4453. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[10]), NULL},
  4454. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "allow_alias"), UPB_TABVALUE_PTR_INIT(&fields[1]), NULL},
  4455. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4456. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[63]), NULL},
  4457. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4458. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[71]), NULL},
  4459. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[50]), &strentries[34]},
  4460. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[101]), NULL},
  4461. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[9]), NULL},
  4462. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4463. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4464. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "oneof_index"), UPB_TABVALUE_PTR_INIT(&fields[66]), NULL},
  4465. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "label"), UPB_TABVALUE_PTR_INIT(&fields[40]), NULL},
  4466. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4467. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[56]), NULL},
  4468. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4469. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4470. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4471. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4472. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[62]), &strentries[53]},
  4473. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4474. {UPB_TABKEY_STR("\010", "\000", "\000", "\000", "extendee"), UPB_TABVALUE_PTR_INIT(&fields[21]), NULL},
  4475. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "type_name"), UPB_TABVALUE_PTR_INIT(&fields[94]), NULL},
  4476. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "json_name"), UPB_TABVALUE_PTR_INIT(&fields[38]), NULL},
  4477. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "type"), UPB_TABVALUE_PTR_INIT(&fields[93]), &strentries[50]},
  4478. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "default_value"), UPB_TABVALUE_PTR_INIT(&fields[7]), NULL},
  4479. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[74]), NULL},
  4480. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[97]), NULL},
  4481. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4482. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "weak"), UPB_TABVALUE_PTR_INIT(&fields[103]), NULL},
  4483. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4484. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4485. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4486. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4487. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "packed"), UPB_TABVALUE_PTR_INIT(&fields[77]), NULL},
  4488. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "lazy"), UPB_TABVALUE_PTR_INIT(&fields[41]), NULL},
  4489. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4490. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "ctype"), UPB_TABVALUE_PTR_INIT(&fields[6]), NULL},
  4491. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4492. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "jstype"), UPB_TABVALUE_PTR_INIT(&fields[39]), NULL},
  4493. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[12]), NULL},
  4494. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4495. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4496. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "extension"), UPB_TABVALUE_PTR_INIT(&fields[23]), NULL},
  4497. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "weak_dependency"), UPB_TABVALUE_PTR_INIT(&fields[104]), NULL},
  4498. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4499. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[49]), NULL},
  4500. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "service"), UPB_TABVALUE_PTR_INIT(&fields[85]), NULL},
  4501. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4502. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "source_code_info"), UPB_TABVALUE_PTR_INIT(&fields[86]), NULL},
  4503. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4504. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4505. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "syntax"), UPB_TABVALUE_PTR_INIT(&fields[91]), NULL},
  4506. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "dependency"), UPB_TABVALUE_PTR_INIT(&fields[8]), NULL},
  4507. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "message_type"), UPB_TABVALUE_PTR_INIT(&fields[47]), NULL},
  4508. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "package"), UPB_TABVALUE_PTR_INIT(&fields[76]), NULL},
  4509. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[72]), &strentries[86]},
  4510. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[19]), NULL},
  4511. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "public_dependency"), UPB_TABVALUE_PTR_INIT(&fields[80]), &strentries[85]},
  4512. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4513. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "file"), UPB_TABVALUE_PTR_INIT(&fields[26]), NULL},
  4514. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4515. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4516. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4517. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4518. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "cc_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[3]), NULL},
  4519. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "csharp_namespace"), UPB_TABVALUE_PTR_INIT(&fields[5]), NULL},
  4520. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4521. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4522. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4523. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4524. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4525. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4526. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4527. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "go_package"), UPB_TABVALUE_PTR_INIT(&fields[27]), NULL},
  4528. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "java_package"), UPB_TABVALUE_PTR_INIT(&fields[35]), &strentries[120]},
  4529. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4530. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4531. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "java_outer_classname"), UPB_TABVALUE_PTR_INIT(&fields[34]), NULL},
  4532. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[99]), NULL},
  4533. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4534. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4535. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4536. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "java_multiple_files"), UPB_TABVALUE_PTR_INIT(&fields[33]), &strentries[117]},
  4537. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4538. {UPB_TABKEY_STR("\025", "\000", "\000", "\000", "java_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[32]), &strentries[118]},
  4539. {UPB_TABKEY_STR("\035", "\000", "\000", "\000", "java_generate_equals_and_hash"), UPB_TABVALUE_PTR_INIT(&fields[31]), NULL},
  4540. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4541. {UPB_TABKEY_STR("\037", "\000", "\000", "\000", "javanano_use_deprecated_package"), UPB_TABVALUE_PTR_INIT(&fields[37]), &strentries[123]},
  4542. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "py_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[81]), NULL},
  4543. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "optimize_for"), UPB_TABVALUE_PTR_INIT(&fields[67]), NULL},
  4544. {UPB_TABKEY_STR("\026", "\000", "\000", "\000", "java_string_check_utf8"), UPB_TABVALUE_PTR_INIT(&fields[36]), NULL},
  4545. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[15]), &strentries[119]},
  4546. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "objc_class_prefix"), UPB_TABVALUE_PTR_INIT(&fields[64]), NULL},
  4547. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "cc_enable_arenas"), UPB_TABVALUE_PTR_INIT(&fields[2]), NULL},
  4548. {UPB_TABKEY_STR("\027", "\000", "\000", "\000", "message_set_wire_format"), UPB_TABVALUE_PTR_INIT(&fields[46]), &strentries[128]},
  4549. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4550. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4551. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4552. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[96]), NULL},
  4553. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[14]), NULL},
  4554. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "map_entry"), UPB_TABVALUE_PTR_INIT(&fields[45]), NULL},
  4555. {UPB_TABKEY_STR("\037", "\000", "\000", "\000", "no_standard_descriptor_accessor"), UPB_TABVALUE_PTR_INIT(&fields[61]), NULL},
  4556. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4557. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "client_streaming"), UPB_TABVALUE_PTR_INIT(&fields[4]), NULL},
  4558. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "server_streaming"), UPB_TABVALUE_PTR_INIT(&fields[84]), NULL},
  4559. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[51]), NULL},
  4560. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "input_type"), UPB_TABVALUE_PTR_INIT(&fields[29]), NULL},
  4561. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4562. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "output_type"), UPB_TABVALUE_PTR_INIT(&fields[75]), NULL},
  4563. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[68]), NULL},
  4564. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[98]), NULL},
  4565. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[13]), NULL},
  4566. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4567. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4568. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4569. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4570. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4571. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[54]), NULL},
  4572. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4573. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[73]), &strentries[150]},
  4574. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "method"), UPB_TABVALUE_PTR_INIT(&fields[48]), NULL},
  4575. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[55]), &strentries[149]},
  4576. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[95]), NULL},
  4577. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[11]), NULL},
  4578. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4579. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4580. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4581. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4582. {UPB_TABKEY_STR("\010", "\000", "\000", "\000", "location"), UPB_TABVALUE_PTR_INIT(&fields[44]), NULL},
  4583. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4584. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4585. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4586. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4587. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "span"), UPB_TABVALUE_PTR_INIT(&fields[87]), &strentries[167]},
  4588. {UPB_TABKEY_STR("\031", "\000", "\000", "\000", "leading_detached_comments"), UPB_TABVALUE_PTR_INIT(&fields[43]), &strentries[165]},
  4589. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "trailing_comments"), UPB_TABVALUE_PTR_INIT(&fields[92]), NULL},
  4590. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "leading_comments"), UPB_TABVALUE_PTR_INIT(&fields[42]), &strentries[164]},
  4591. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "path"), UPB_TABVALUE_PTR_INIT(&fields[78]), NULL},
  4592. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "double_value"), UPB_TABVALUE_PTR_INIT(&fields[16]), NULL},
  4593. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4594. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4595. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[57]), NULL},
  4596. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4597. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4598. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4599. {UPB_TABKEY_STR("\022", "\000", "\000", "\000", "negative_int_value"), UPB_TABVALUE_PTR_INIT(&fields[59]), NULL},
  4600. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "aggregate_value"), UPB_TABVALUE_PTR_INIT(&fields[0]), NULL},
  4601. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4602. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4603. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4604. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4605. {UPB_TABKEY_STR("\022", "\000", "\000", "\000", "positive_int_value"), UPB_TABVALUE_PTR_INIT(&fields[79]), NULL},
  4606. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "identifier_value"), UPB_TABVALUE_PTR_INIT(&fields[28]), NULL},
  4607. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "string_value"), UPB_TABVALUE_PTR_INIT(&fields[90]), &strentries[182]},
  4608. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4609. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4610. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "is_extension"), UPB_TABVALUE_PTR_INIT(&fields[30]), NULL},
  4611. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "name_part"), UPB_TABVALUE_PTR_INIT(&fields[58]), NULL},
  4612. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_REQUIRED"), UPB_TABVALUE_INT_INIT(2), &strentries[190]},
  4613. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4614. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_REPEATED"), UPB_TABVALUE_INT_INIT(3), NULL},
  4615. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_OPTIONAL"), UPB_TABVALUE_INT_INIT(1), NULL},
  4616. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_FIXED64"), UPB_TABVALUE_INT_INIT(6), NULL},
  4617. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4618. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4619. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4620. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4621. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_STRING"), UPB_TABVALUE_INT_INIT(9), NULL},
  4622. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_FLOAT"), UPB_TABVALUE_INT_INIT(2), &strentries[221]},
  4623. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_DOUBLE"), UPB_TABVALUE_INT_INIT(1), NULL},
  4624. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4625. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_INT32"), UPB_TABVALUE_INT_INIT(5), NULL},
  4626. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "TYPE_SFIXED32"), UPB_TABVALUE_INT_INIT(15), NULL},
  4627. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_FIXED32"), UPB_TABVALUE_INT_INIT(7), NULL},
  4628. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4629. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_MESSAGE"), UPB_TABVALUE_INT_INIT(11), &strentries[222]},
  4630. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4631. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4632. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_INT64"), UPB_TABVALUE_INT_INIT(3), &strentries[219]},
  4633. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4634. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4635. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4636. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4637. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "TYPE_ENUM"), UPB_TABVALUE_INT_INIT(14), NULL},
  4638. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_UINT32"), UPB_TABVALUE_INT_INIT(13), NULL},
  4639. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4640. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_UINT64"), UPB_TABVALUE_INT_INIT(4), &strentries[218]},
  4641. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4642. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "TYPE_SFIXED64"), UPB_TABVALUE_INT_INIT(16), NULL},
  4643. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_BYTES"), UPB_TABVALUE_INT_INIT(12), NULL},
  4644. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_SINT64"), UPB_TABVALUE_INT_INIT(18), NULL},
  4645. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "TYPE_BOOL"), UPB_TABVALUE_INT_INIT(8), NULL},
  4646. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_GROUP"), UPB_TABVALUE_INT_INIT(10), NULL},
  4647. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_SINT32"), UPB_TABVALUE_INT_INIT(17), NULL},
  4648. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4649. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "CORD"), UPB_TABVALUE_INT_INIT(1), NULL},
  4650. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "STRING"), UPB_TABVALUE_INT_INIT(0), &strentries[225]},
  4651. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "STRING_PIECE"), UPB_TABVALUE_INT_INIT(2), NULL},
  4652. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4653. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "JS_NORMAL"), UPB_TABVALUE_INT_INIT(0), NULL},
  4654. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "JS_NUMBER"), UPB_TABVALUE_INT_INIT(2), NULL},
  4655. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "JS_STRING"), UPB_TABVALUE_INT_INIT(1), NULL},
  4656. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "CODE_SIZE"), UPB_TABVALUE_INT_INIT(2), NULL},
  4657. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "SPEED"), UPB_TABVALUE_INT_INIT(1), &strentries[235]},
  4658. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4659. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "LITE_RUNTIME"), UPB_TABVALUE_INT_INIT(3), NULL},
  4660. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4661. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4662. {UPB_TABKEY_STR("\047", "\000", "\000", "\000", "google.protobuf.SourceCodeInfo.Location"), UPB_TABVALUE_PTR_INIT(&msgs[19]), NULL},
  4663. {UPB_TABKEY_STR("\043", "\000", "\000", "\000", "google.protobuf.UninterpretedOption"), UPB_TABVALUE_PTR_INIT(&msgs[20]), NULL},
  4664. {UPB_TABKEY_STR("\043", "\000", "\000", "\000", "google.protobuf.FileDescriptorProto"), UPB_TABVALUE_PTR_INIT(&msgs[9]), NULL},
  4665. {UPB_TABKEY_STR("\045", "\000", "\000", "\000", "google.protobuf.MethodDescriptorProto"), UPB_TABVALUE_PTR_INIT(&msgs[13]), NULL},
  4666. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4667. {UPB_TABKEY_STR("\040", "\000", "\000", "\000", "google.protobuf.EnumValueOptions"), UPB_TABVALUE_PTR_INIT(&msgs[6]), NULL},
  4668. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4669. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4670. {UPB_TABKEY_STR("\055", "\000", "\000", "\000", "google.protobuf.DescriptorProto.ReservedRange"), UPB_TABVALUE_PTR_INIT(&msgs[2]), NULL},
  4671. {UPB_TABKEY_STR("\037", "\000", "\000", "\000", "google.protobuf.DescriptorProto"), UPB_TABVALUE_PTR_INIT(&msgs[0]), &strentries[248]},
  4672. {UPB_TABKEY_STR("\041", "\000", "\000", "\000", "google.protobuf.FileDescriptorSet"), UPB_TABVALUE_PTR_INIT(&msgs[10]), &strentries[267]},
  4673. {UPB_TABKEY_STR("\036", "\000", "\000", "\000", "google.protobuf.SourceCodeInfo"), UPB_TABVALUE_PTR_INIT(&msgs[18]), NULL},
  4674. {UPB_TABKEY_STR("\051", "\000", "\000", "\000", "google.protobuf.FieldDescriptorProto.Type"), UPB_TABVALUE_PTR_INIT(&enums[1]), NULL},
  4675. {UPB_TABKEY_STR("\056", "\000", "\000", "\000", "google.protobuf.DescriptorProto.ExtensionRange"), UPB_TABVALUE_PTR_INIT(&msgs[1]), NULL},
  4676. {UPB_TABKEY_STR("\044", "\000", "\000", "\000", "google.protobuf.OneofDescriptorProto"), UPB_TABVALUE_PTR_INIT(&msgs[15]), NULL},
  4677. {UPB_TABKEY_STR("\046", "\000", "\000", "\000", "google.protobuf.ServiceDescriptorProto"), UPB_TABVALUE_PTR_INIT(&msgs[16]), NULL},
  4678. {UPB_TABKEY_STR("\034", "\000", "\000", "\000", "google.protobuf.FieldOptions"), UPB_TABVALUE_PTR_INIT(&msgs[8]), NULL},
  4679. {UPB_TABKEY_STR("\033", "\000", "\000", "\000", "google.protobuf.FileOptions"), UPB_TABVALUE_PTR_INIT(&msgs[11]), NULL},
  4680. {UPB_TABKEY_STR("\043", "\000", "\000", "\000", "google.protobuf.EnumDescriptorProto"), UPB_TABVALUE_PTR_INIT(&msgs[3]), &strentries[265]},
  4681. {UPB_TABKEY_STR("\052", "\000", "\000", "\000", "google.protobuf.FieldDescriptorProto.Label"), UPB_TABVALUE_PTR_INIT(&enums[0]), NULL},
  4682. {UPB_TABKEY_STR("\050", "\000", "\000", "\000", "google.protobuf.FileOptions.OptimizeMode"), UPB_TABVALUE_PTR_INIT(&enums[4]), NULL},
  4683. {UPB_TABKEY_STR("\042", "\000", "\000", "\000", "google.protobuf.FieldOptions.CType"), UPB_TABVALUE_PTR_INIT(&enums[2]), &strentries[261]},
  4684. {UPB_TABKEY_STR("\043", "\000", "\000", "\000", "google.protobuf.FieldOptions.JSType"), UPB_TABVALUE_PTR_INIT(&enums[3]), NULL},
  4685. {UPB_TABKEY_STR("\033", "\000", "\000", "\000", "google.protobuf.EnumOptions"), UPB_TABVALUE_PTR_INIT(&msgs[4]), NULL},
  4686. {UPB_TABKEY_STR("\044", "\000", "\000", "\000", "google.protobuf.FieldDescriptorProto"), UPB_TABVALUE_PTR_INIT(&msgs[7]), NULL},
  4687. {UPB_TABKEY_STR("\050", "\000", "\000", "\000", "google.protobuf.EnumValueDescriptorProto"), UPB_TABVALUE_PTR_INIT(&msgs[5]), &strentries[258]},
  4688. {UPB_TABKEY_STR("\036", "\000", "\000", "\000", "google.protobuf.ServiceOptions"), UPB_TABVALUE_PTR_INIT(&msgs[17]), NULL},
  4689. {UPB_TABKEY_STR("\036", "\000", "\000", "\000", "google.protobuf.MessageOptions"), UPB_TABVALUE_PTR_INIT(&msgs[12]), NULL},
  4690. {UPB_TABKEY_STR("\035", "\000", "\000", "\000", "google.protobuf.MethodOptions"), UPB_TABVALUE_PTR_INIT(&msgs[14]), &strentries[253]},
  4691. {UPB_TABKEY_STR("\054", "\000", "\000", "\000", "google.protobuf.UninterpretedOption.NamePart"), UPB_TABVALUE_PTR_INIT(&msgs[21]), NULL},
  4692. };
  4693. static const upb_tabent intentries[18] = {
  4694. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4695. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[100]), NULL},
  4696. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4697. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[101]), NULL},
  4698. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4699. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[97]), NULL},
  4700. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4701. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[99]), NULL},
  4702. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4703. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[96]), NULL},
  4704. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4705. {UPB_TABKEY_NUM(33), UPB_TABVALUE_PTR_INIT(&fields[13]), NULL},
  4706. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4707. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[98]), NULL},
  4708. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4709. {UPB_TABKEY_NUM(33), UPB_TABVALUE_PTR_INIT(&fields[11]), NULL},
  4710. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4711. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[95]), NULL},
  4712. };
  4713. static const upb_tabval arrays[184] = {
  4714. UPB_TABVALUE_EMPTY_INIT,
  4715. UPB_TABVALUE_PTR_INIT(&fields[52]),
  4716. UPB_TABVALUE_PTR_INIT(&fields[25]),
  4717. UPB_TABVALUE_PTR_INIT(&fields[60]),
  4718. UPB_TABVALUE_PTR_INIT(&fields[20]),
  4719. UPB_TABVALUE_PTR_INIT(&fields[24]),
  4720. UPB_TABVALUE_PTR_INIT(&fields[22]),
  4721. UPB_TABVALUE_PTR_INIT(&fields[70]),
  4722. UPB_TABVALUE_PTR_INIT(&fields[65]),
  4723. UPB_TABVALUE_PTR_INIT(&fields[83]),
  4724. UPB_TABVALUE_PTR_INIT(&fields[82]),
  4725. UPB_TABVALUE_EMPTY_INIT,
  4726. UPB_TABVALUE_PTR_INIT(&fields[88]),
  4727. UPB_TABVALUE_PTR_INIT(&fields[18]),
  4728. UPB_TABVALUE_EMPTY_INIT,
  4729. UPB_TABVALUE_PTR_INIT(&fields[89]),
  4730. UPB_TABVALUE_PTR_INIT(&fields[17]),
  4731. UPB_TABVALUE_EMPTY_INIT,
  4732. UPB_TABVALUE_PTR_INIT(&fields[53]),
  4733. UPB_TABVALUE_PTR_INIT(&fields[102]),
  4734. UPB_TABVALUE_PTR_INIT(&fields[69]),
  4735. UPB_TABVALUE_EMPTY_INIT,
  4736. UPB_TABVALUE_EMPTY_INIT,
  4737. UPB_TABVALUE_PTR_INIT(&fields[1]),
  4738. UPB_TABVALUE_PTR_INIT(&fields[10]),
  4739. UPB_TABVALUE_EMPTY_INIT,
  4740. UPB_TABVALUE_PTR_INIT(&fields[50]),
  4741. UPB_TABVALUE_PTR_INIT(&fields[63]),
  4742. UPB_TABVALUE_PTR_INIT(&fields[71]),
  4743. UPB_TABVALUE_EMPTY_INIT,
  4744. UPB_TABVALUE_PTR_INIT(&fields[9]),
  4745. UPB_TABVALUE_EMPTY_INIT,
  4746. UPB_TABVALUE_PTR_INIT(&fields[56]),
  4747. UPB_TABVALUE_PTR_INIT(&fields[21]),
  4748. UPB_TABVALUE_PTR_INIT(&fields[62]),
  4749. UPB_TABVALUE_PTR_INIT(&fields[40]),
  4750. UPB_TABVALUE_PTR_INIT(&fields[93]),
  4751. UPB_TABVALUE_PTR_INIT(&fields[94]),
  4752. UPB_TABVALUE_PTR_INIT(&fields[7]),
  4753. UPB_TABVALUE_PTR_INIT(&fields[74]),
  4754. UPB_TABVALUE_PTR_INIT(&fields[66]),
  4755. UPB_TABVALUE_PTR_INIT(&fields[38]),
  4756. UPB_TABVALUE_EMPTY_INIT,
  4757. UPB_TABVALUE_PTR_INIT(&fields[6]),
  4758. UPB_TABVALUE_PTR_INIT(&fields[77]),
  4759. UPB_TABVALUE_PTR_INIT(&fields[12]),
  4760. UPB_TABVALUE_EMPTY_INIT,
  4761. UPB_TABVALUE_PTR_INIT(&fields[41]),
  4762. UPB_TABVALUE_PTR_INIT(&fields[39]),
  4763. UPB_TABVALUE_EMPTY_INIT,
  4764. UPB_TABVALUE_EMPTY_INIT,
  4765. UPB_TABVALUE_EMPTY_INIT,
  4766. UPB_TABVALUE_PTR_INIT(&fields[103]),
  4767. UPB_TABVALUE_EMPTY_INIT,
  4768. UPB_TABVALUE_PTR_INIT(&fields[49]),
  4769. UPB_TABVALUE_PTR_INIT(&fields[76]),
  4770. UPB_TABVALUE_PTR_INIT(&fields[8]),
  4771. UPB_TABVALUE_PTR_INIT(&fields[47]),
  4772. UPB_TABVALUE_PTR_INIT(&fields[19]),
  4773. UPB_TABVALUE_PTR_INIT(&fields[85]),
  4774. UPB_TABVALUE_PTR_INIT(&fields[23]),
  4775. UPB_TABVALUE_PTR_INIT(&fields[72]),
  4776. UPB_TABVALUE_PTR_INIT(&fields[86]),
  4777. UPB_TABVALUE_PTR_INIT(&fields[80]),
  4778. UPB_TABVALUE_PTR_INIT(&fields[104]),
  4779. UPB_TABVALUE_PTR_INIT(&fields[91]),
  4780. UPB_TABVALUE_EMPTY_INIT,
  4781. UPB_TABVALUE_PTR_INIT(&fields[26]),
  4782. UPB_TABVALUE_EMPTY_INIT,
  4783. UPB_TABVALUE_PTR_INIT(&fields[35]),
  4784. UPB_TABVALUE_EMPTY_INIT,
  4785. UPB_TABVALUE_EMPTY_INIT,
  4786. UPB_TABVALUE_EMPTY_INIT,
  4787. UPB_TABVALUE_EMPTY_INIT,
  4788. UPB_TABVALUE_EMPTY_INIT,
  4789. UPB_TABVALUE_EMPTY_INIT,
  4790. UPB_TABVALUE_PTR_INIT(&fields[34]),
  4791. UPB_TABVALUE_PTR_INIT(&fields[67]),
  4792. UPB_TABVALUE_PTR_INIT(&fields[33]),
  4793. UPB_TABVALUE_PTR_INIT(&fields[27]),
  4794. UPB_TABVALUE_EMPTY_INIT,
  4795. UPB_TABVALUE_EMPTY_INIT,
  4796. UPB_TABVALUE_EMPTY_INIT,
  4797. UPB_TABVALUE_EMPTY_INIT,
  4798. UPB_TABVALUE_PTR_INIT(&fields[3]),
  4799. UPB_TABVALUE_PTR_INIT(&fields[32]),
  4800. UPB_TABVALUE_PTR_INIT(&fields[81]),
  4801. UPB_TABVALUE_EMPTY_INIT,
  4802. UPB_TABVALUE_PTR_INIT(&fields[31]),
  4803. UPB_TABVALUE_EMPTY_INIT,
  4804. UPB_TABVALUE_EMPTY_INIT,
  4805. UPB_TABVALUE_PTR_INIT(&fields[15]),
  4806. UPB_TABVALUE_EMPTY_INIT,
  4807. UPB_TABVALUE_EMPTY_INIT,
  4808. UPB_TABVALUE_EMPTY_INIT,
  4809. UPB_TABVALUE_PTR_INIT(&fields[36]),
  4810. UPB_TABVALUE_EMPTY_INIT,
  4811. UPB_TABVALUE_EMPTY_INIT,
  4812. UPB_TABVALUE_EMPTY_INIT,
  4813. UPB_TABVALUE_PTR_INIT(&fields[2]),
  4814. UPB_TABVALUE_EMPTY_INIT,
  4815. UPB_TABVALUE_EMPTY_INIT,
  4816. UPB_TABVALUE_EMPTY_INIT,
  4817. UPB_TABVALUE_EMPTY_INIT,
  4818. UPB_TABVALUE_PTR_INIT(&fields[64]),
  4819. UPB_TABVALUE_PTR_INIT(&fields[5]),
  4820. UPB_TABVALUE_PTR_INIT(&fields[37]),
  4821. UPB_TABVALUE_EMPTY_INIT,
  4822. UPB_TABVALUE_PTR_INIT(&fields[46]),
  4823. UPB_TABVALUE_PTR_INIT(&fields[61]),
  4824. UPB_TABVALUE_PTR_INIT(&fields[14]),
  4825. UPB_TABVALUE_EMPTY_INIT,
  4826. UPB_TABVALUE_EMPTY_INIT,
  4827. UPB_TABVALUE_EMPTY_INIT,
  4828. UPB_TABVALUE_PTR_INIT(&fields[45]),
  4829. UPB_TABVALUE_EMPTY_INIT,
  4830. UPB_TABVALUE_PTR_INIT(&fields[51]),
  4831. UPB_TABVALUE_PTR_INIT(&fields[29]),
  4832. UPB_TABVALUE_PTR_INIT(&fields[75]),
  4833. UPB_TABVALUE_PTR_INIT(&fields[68]),
  4834. UPB_TABVALUE_PTR_INIT(&fields[4]),
  4835. UPB_TABVALUE_PTR_INIT(&fields[84]),
  4836. UPB_TABVALUE_EMPTY_INIT,
  4837. UPB_TABVALUE_EMPTY_INIT,
  4838. UPB_TABVALUE_PTR_INIT(&fields[54]),
  4839. UPB_TABVALUE_EMPTY_INIT,
  4840. UPB_TABVALUE_PTR_INIT(&fields[55]),
  4841. UPB_TABVALUE_PTR_INIT(&fields[48]),
  4842. UPB_TABVALUE_PTR_INIT(&fields[73]),
  4843. UPB_TABVALUE_EMPTY_INIT,
  4844. UPB_TABVALUE_EMPTY_INIT,
  4845. UPB_TABVALUE_PTR_INIT(&fields[44]),
  4846. UPB_TABVALUE_EMPTY_INIT,
  4847. UPB_TABVALUE_PTR_INIT(&fields[78]),
  4848. UPB_TABVALUE_PTR_INIT(&fields[87]),
  4849. UPB_TABVALUE_PTR_INIT(&fields[42]),
  4850. UPB_TABVALUE_PTR_INIT(&fields[92]),
  4851. UPB_TABVALUE_EMPTY_INIT,
  4852. UPB_TABVALUE_PTR_INIT(&fields[43]),
  4853. UPB_TABVALUE_EMPTY_INIT,
  4854. UPB_TABVALUE_EMPTY_INIT,
  4855. UPB_TABVALUE_PTR_INIT(&fields[57]),
  4856. UPB_TABVALUE_PTR_INIT(&fields[28]),
  4857. UPB_TABVALUE_PTR_INIT(&fields[79]),
  4858. UPB_TABVALUE_PTR_INIT(&fields[59]),
  4859. UPB_TABVALUE_PTR_INIT(&fields[16]),
  4860. UPB_TABVALUE_PTR_INIT(&fields[90]),
  4861. UPB_TABVALUE_PTR_INIT(&fields[0]),
  4862. UPB_TABVALUE_EMPTY_INIT,
  4863. UPB_TABVALUE_PTR_INIT(&fields[58]),
  4864. UPB_TABVALUE_PTR_INIT(&fields[30]),
  4865. UPB_TABVALUE_EMPTY_INIT,
  4866. UPB_TABVALUE_PTR_INIT("LABEL_OPTIONAL"),
  4867. UPB_TABVALUE_PTR_INIT("LABEL_REQUIRED"),
  4868. UPB_TABVALUE_PTR_INIT("LABEL_REPEATED"),
  4869. UPB_TABVALUE_EMPTY_INIT,
  4870. UPB_TABVALUE_PTR_INIT("TYPE_DOUBLE"),
  4871. UPB_TABVALUE_PTR_INIT("TYPE_FLOAT"),
  4872. UPB_TABVALUE_PTR_INIT("TYPE_INT64"),
  4873. UPB_TABVALUE_PTR_INIT("TYPE_UINT64"),
  4874. UPB_TABVALUE_PTR_INIT("TYPE_INT32"),
  4875. UPB_TABVALUE_PTR_INIT("TYPE_FIXED64"),
  4876. UPB_TABVALUE_PTR_INIT("TYPE_FIXED32"),
  4877. UPB_TABVALUE_PTR_INIT("TYPE_BOOL"),
  4878. UPB_TABVALUE_PTR_INIT("TYPE_STRING"),
  4879. UPB_TABVALUE_PTR_INIT("TYPE_GROUP"),
  4880. UPB_TABVALUE_PTR_INIT("TYPE_MESSAGE"),
  4881. UPB_TABVALUE_PTR_INIT("TYPE_BYTES"),
  4882. UPB_TABVALUE_PTR_INIT("TYPE_UINT32"),
  4883. UPB_TABVALUE_PTR_INIT("TYPE_ENUM"),
  4884. UPB_TABVALUE_PTR_INIT("TYPE_SFIXED32"),
  4885. UPB_TABVALUE_PTR_INIT("TYPE_SFIXED64"),
  4886. UPB_TABVALUE_PTR_INIT("TYPE_SINT32"),
  4887. UPB_TABVALUE_PTR_INIT("TYPE_SINT64"),
  4888. UPB_TABVALUE_PTR_INIT("STRING"),
  4889. UPB_TABVALUE_PTR_INIT("CORD"),
  4890. UPB_TABVALUE_PTR_INIT("STRING_PIECE"),
  4891. UPB_TABVALUE_PTR_INIT("JS_NORMAL"),
  4892. UPB_TABVALUE_PTR_INIT("JS_STRING"),
  4893. UPB_TABVALUE_PTR_INIT("JS_NUMBER"),
  4894. UPB_TABVALUE_EMPTY_INIT,
  4895. UPB_TABVALUE_PTR_INIT("SPEED"),
  4896. UPB_TABVALUE_PTR_INIT("CODE_SIZE"),
  4897. UPB_TABVALUE_PTR_INIT("LITE_RUNTIME"),
  4898. };
  4899. static const upb_symtab symtab = UPB_SYMTAB_INIT(UPB_STRTABLE_INIT(27, 31, UPB_CTYPE_PTR, 5, &strentries[236]), &reftables[264], &reftables[265]);
  4900. const upb_symtab *upbdefs_google_protobuf_descriptor(const void *owner) {
  4901. upb_symtab_ref(&symtab, owner);
  4902. return &symtab;
  4903. }
  4904. #ifdef UPB_DEBUG_REFS
  4905. static upb_inttable reftables[266] = {
  4906. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4907. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4908. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4909. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4910. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4911. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4912. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4913. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4914. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4915. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4916. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4917. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4918. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4919. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4920. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4921. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4922. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4923. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4924. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4925. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4926. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4927. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4928. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4929. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4930. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4931. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4932. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4933. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4934. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4935. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4936. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4937. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4938. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4939. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4940. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4941. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4942. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4943. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4944. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4945. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4946. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4947. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4948. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4949. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4950. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4951. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4952. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4953. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4954. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4955. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4956. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4957. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4958. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4959. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4960. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4961. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4962. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4963. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4964. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4965. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4966. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4967. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4968. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4969. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4970. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4971. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4972. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4973. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4974. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4975. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4976. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4977. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4978. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4979. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4980. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4981. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4982. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4983. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4984. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4985. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4986. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4987. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4988. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4989. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4990. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4991. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4992. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4993. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4994. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4995. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4996. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4997. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4998. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4999. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5000. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5001. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5002. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5003. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5004. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5005. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5006. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5007. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5008. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5009. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5010. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5011. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5012. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5013. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5014. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5015. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5016. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5017. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5018. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5019. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5020. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5021. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5022. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5023. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5024. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5025. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5026. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5027. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5028. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5029. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5030. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5031. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5032. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5033. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5034. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5035. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5036. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5037. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5038. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5039. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5040. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5041. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5042. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5043. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5044. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5045. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5046. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5047. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5048. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5049. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5050. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5051. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5052. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5053. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5054. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5055. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5056. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5057. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5058. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5059. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5060. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5061. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5062. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5063. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5064. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5065. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5066. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5067. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5068. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5069. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5070. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5071. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5072. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5073. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5074. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5075. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5076. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5077. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5078. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5079. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5080. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5081. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5082. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5083. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5084. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5085. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5086. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5087. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5088. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5089. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5090. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5091. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5092. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5093. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5094. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5095. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5096. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5097. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5098. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5099. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5100. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5101. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5102. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5103. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5104. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5105. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5106. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5107. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5108. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5109. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5110. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5111. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5112. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5113. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5114. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5115. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5116. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5117. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5118. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5119. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5120. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5121. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5122. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5123. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5124. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5125. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5126. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5127. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5128. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5129. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5130. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5131. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5132. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5133. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5134. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5135. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5136. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5137. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5138. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5139. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5140. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5141. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5142. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5143. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5144. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5145. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5146. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5147. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5148. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5149. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5150. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5151. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5152. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5153. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5154. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5155. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5156. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5157. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5158. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5159. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5160. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5161. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5162. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5163. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5164. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5165. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5166. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5167. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5168. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5169. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5170. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5171. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5172. };
  5173. #endif
  5174. /*
  5175. ** XXX: The routines in this file that consume a string do not currently
  5176. ** support having the string span buffers. In the future, as upb_sink and
  5177. ** its buffering/sharing functionality evolve there should be an easy and
  5178. ** idiomatic way of correctly handling this case. For now, we accept this
  5179. ** limitation since we currently only parse descriptors from single strings.
  5180. */
  5181. #include <errno.h>
  5182. #include <stdlib.h>
  5183. #include <string.h>
  5184. /* Compares a NULL-terminated string with a non-NULL-terminated string. */
  5185. static bool upb_streq(const char *str, const char *buf, size_t n) {
  5186. return strlen(str) == n && memcmp(str, buf, n) == 0;
  5187. }
  5188. /* upb_deflist is an internal-only dynamic array for storing a growing list of
  5189. * upb_defs. */
  5190. typedef struct {
  5191. upb_def **defs;
  5192. size_t len;
  5193. size_t size;
  5194. bool owned;
  5195. } upb_deflist;
  5196. /* We keep a stack of all the messages scopes we are currently in, as well as
  5197. * the top-level file scope. This is necessary to correctly qualify the
  5198. * definitions that are contained inside. "name" tracks the name of the
  5199. * message or package (a bare name -- not qualified by any enclosing scopes). */
  5200. typedef struct {
  5201. char *name;
  5202. /* Index of the first def that is under this scope. For msgdefs, the
  5203. * msgdef itself is at start-1. */
  5204. int start;
  5205. } upb_descreader_frame;
  5206. /* The maximum number of nested declarations that are allowed, ie.
  5207. * message Foo {
  5208. * message Bar {
  5209. * message Baz {
  5210. * }
  5211. * }
  5212. * }
  5213. *
  5214. * This is a resource limit that affects how big our runtime stack can grow.
  5215. * TODO: make this a runtime-settable property of the Reader instance. */
  5216. #define UPB_MAX_MESSAGE_NESTING 64
  5217. struct upb_descreader {
  5218. upb_sink sink;
  5219. upb_deflist defs;
  5220. upb_descreader_frame stack[UPB_MAX_MESSAGE_NESTING];
  5221. int stack_len;
  5222. bool primitives_have_presence;
  5223. int file_start;
  5224. uint32_t number;
  5225. char *name;
  5226. bool saw_number;
  5227. bool saw_name;
  5228. char *default_string;
  5229. upb_fielddef *f;
  5230. };
  5231. static char *upb_strndup(const char *buf, size_t n) {
  5232. char *ret = malloc(n + 1);
  5233. if (!ret) return NULL;
  5234. memcpy(ret, buf, n);
  5235. ret[n] = '\0';
  5236. return ret;
  5237. }
  5238. /* Returns a newly allocated string that joins input strings together, for
  5239. * example:
  5240. * join("Foo.Bar", "Baz") -> "Foo.Bar.Baz"
  5241. * join("", "Baz") -> "Baz"
  5242. * Caller owns a ref on the returned string. */
  5243. static char *upb_join(const char *base, const char *name) {
  5244. if (!base || strlen(base) == 0) {
  5245. return upb_strdup(name);
  5246. } else {
  5247. char *ret = malloc(strlen(base) + strlen(name) + 2);
  5248. ret[0] = '\0';
  5249. strcat(ret, base);
  5250. strcat(ret, ".");
  5251. strcat(ret, name);
  5252. return ret;
  5253. }
  5254. }
  5255. /* upb_deflist ****************************************************************/
  5256. void upb_deflist_init(upb_deflist *l) {
  5257. l->size = 0;
  5258. l->defs = NULL;
  5259. l->len = 0;
  5260. l->owned = true;
  5261. }
  5262. void upb_deflist_uninit(upb_deflist *l) {
  5263. size_t i;
  5264. if (l->owned)
  5265. for(i = 0; i < l->len; i++)
  5266. upb_def_unref(l->defs[i], l);
  5267. free(l->defs);
  5268. }
  5269. bool upb_deflist_push(upb_deflist *l, upb_def *d) {
  5270. if(++l->len >= l->size) {
  5271. size_t new_size = UPB_MAX(l->size, 4);
  5272. new_size *= 2;
  5273. l->defs = realloc(l->defs, new_size * sizeof(void *));
  5274. if (!l->defs) return false;
  5275. l->size = new_size;
  5276. }
  5277. l->defs[l->len - 1] = d;
  5278. return true;
  5279. }
  5280. void upb_deflist_donaterefs(upb_deflist *l, void *owner) {
  5281. size_t i;
  5282. assert(l->owned);
  5283. for (i = 0; i < l->len; i++)
  5284. upb_def_donateref(l->defs[i], l, owner);
  5285. l->owned = false;
  5286. }
  5287. static upb_def *upb_deflist_last(upb_deflist *l) {
  5288. return l->defs[l->len-1];
  5289. }
  5290. /* Qualify the defname for all defs starting with offset "start" with "str". */
  5291. static void upb_deflist_qualify(upb_deflist *l, char *str, int32_t start) {
  5292. uint32_t i;
  5293. for (i = start; i < l->len; i++) {
  5294. upb_def *def = l->defs[i];
  5295. char *name = upb_join(str, upb_def_fullname(def));
  5296. upb_def_setfullname(def, name, NULL);
  5297. free(name);
  5298. }
  5299. }
  5300. /* upb_descreader ************************************************************/
  5301. static upb_msgdef *upb_descreader_top(upb_descreader *r) {
  5302. int index;
  5303. assert(r->stack_len > 1);
  5304. index = r->stack[r->stack_len-1].start - 1;
  5305. assert(index >= 0);
  5306. return upb_downcast_msgdef_mutable(r->defs.defs[index]);
  5307. }
  5308. static upb_def *upb_descreader_last(upb_descreader *r) {
  5309. return upb_deflist_last(&r->defs);
  5310. }
  5311. /* Start/end handlers for FileDescriptorProto and DescriptorProto (the two
  5312. * entities that have names and can contain sub-definitions. */
  5313. void upb_descreader_startcontainer(upb_descreader *r) {
  5314. upb_descreader_frame *f = &r->stack[r->stack_len++];
  5315. f->start = r->defs.len;
  5316. f->name = NULL;
  5317. }
  5318. void upb_descreader_endcontainer(upb_descreader *r) {
  5319. upb_descreader_frame *f = &r->stack[--r->stack_len];
  5320. upb_deflist_qualify(&r->defs, f->name, f->start);
  5321. free(f->name);
  5322. f->name = NULL;
  5323. }
  5324. void upb_descreader_setscopename(upb_descreader *r, char *str) {
  5325. upb_descreader_frame *f = &r->stack[r->stack_len-1];
  5326. free(f->name);
  5327. f->name = str;
  5328. }
  5329. /* Handlers for google.protobuf.FileDescriptorProto. */
  5330. static bool file_startmsg(void *closure, const void *hd) {
  5331. upb_descreader *r = closure;
  5332. UPB_UNUSED(hd);
  5333. upb_descreader_startcontainer(r);
  5334. r->primitives_have_presence = true;
  5335. r->file_start = r->defs.len;
  5336. return true;
  5337. }
  5338. static bool file_endmsg(void *closure, const void *hd, upb_status *status) {
  5339. upb_descreader *r = closure;
  5340. UPB_UNUSED(hd);
  5341. UPB_UNUSED(status);
  5342. upb_descreader_endcontainer(r);
  5343. return true;
  5344. }
  5345. static size_t file_onpackage(void *closure, const void *hd, const char *buf,
  5346. size_t n, const upb_bufhandle *handle) {
  5347. upb_descreader *r = closure;
  5348. UPB_UNUSED(hd);
  5349. UPB_UNUSED(handle);
  5350. /* XXX: see comment at the top of the file. */
  5351. upb_descreader_setscopename(r, upb_strndup(buf, n));
  5352. return n;
  5353. }
  5354. static size_t file_onsyntax(void *closure, const void *hd, const char *buf,
  5355. size_t n, const upb_bufhandle *handle) {
  5356. upb_descreader *r = closure;
  5357. UPB_UNUSED(hd);
  5358. UPB_UNUSED(handle);
  5359. /* XXX: see comment at the top of the file. */
  5360. if (upb_streq("proto2", buf, n)) {
  5361. /* Technically we could verify that proto3 hadn't previously been seen. */
  5362. } else if (upb_streq("proto3", buf, n)) {
  5363. uint32_t i;
  5364. /* Update messages created before the syntax was read. */
  5365. for (i = r->file_start; i < r->defs.len; i++) {
  5366. upb_msgdef *m = upb_dyncast_msgdef_mutable(r->defs.defs[i]);
  5367. if (m) {
  5368. upb_msgdef_setprimitiveshavepresence(m, false);
  5369. }
  5370. }
  5371. /* Set a flag for any future messages that will be created. */
  5372. r->primitives_have_presence = false;
  5373. } else {
  5374. /* Error: neither proto3 nor proto3.
  5375. * TODO(haberman): there should be a status object we can report this to. */
  5376. return 0;
  5377. }
  5378. return n;
  5379. }
  5380. /* Handlers for google.protobuf.EnumValueDescriptorProto. */
  5381. static bool enumval_startmsg(void *closure, const void *hd) {
  5382. upb_descreader *r = closure;
  5383. UPB_UNUSED(hd);
  5384. r->saw_number = false;
  5385. r->saw_name = false;
  5386. return true;
  5387. }
  5388. static size_t enumval_onname(void *closure, const void *hd, const char *buf,
  5389. size_t n, const upb_bufhandle *handle) {
  5390. upb_descreader *r = closure;
  5391. UPB_UNUSED(hd);
  5392. UPB_UNUSED(handle);
  5393. /* XXX: see comment at the top of the file. */
  5394. free(r->name);
  5395. r->name = upb_strndup(buf, n);
  5396. r->saw_name = true;
  5397. return n;
  5398. }
  5399. static bool enumval_onnumber(void *closure, const void *hd, int32_t val) {
  5400. upb_descreader *r = closure;
  5401. UPB_UNUSED(hd);
  5402. r->number = val;
  5403. r->saw_number = true;
  5404. return true;
  5405. }
  5406. static bool enumval_endmsg(void *closure, const void *hd, upb_status *status) {
  5407. upb_descreader *r = closure;
  5408. upb_enumdef *e;
  5409. UPB_UNUSED(hd);
  5410. if(!r->saw_number || !r->saw_name) {
  5411. upb_status_seterrmsg(status, "Enum value missing name or number.");
  5412. return false;
  5413. }
  5414. e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  5415. upb_enumdef_addval(e, r->name, r->number, status);
  5416. free(r->name);
  5417. r->name = NULL;
  5418. return true;
  5419. }
  5420. /* Handlers for google.protobuf.EnumDescriptorProto. */
  5421. static bool enum_startmsg(void *closure, const void *hd) {
  5422. upb_descreader *r = closure;
  5423. UPB_UNUSED(hd);
  5424. upb_deflist_push(&r->defs,
  5425. upb_enumdef_upcast_mutable(upb_enumdef_new(&r->defs)));
  5426. return true;
  5427. }
  5428. static bool enum_endmsg(void *closure, const void *hd, upb_status *status) {
  5429. upb_descreader *r = closure;
  5430. upb_enumdef *e;
  5431. UPB_UNUSED(hd);
  5432. e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  5433. if (upb_def_fullname(upb_descreader_last(r)) == NULL) {
  5434. upb_status_seterrmsg(status, "Enum had no name.");
  5435. return false;
  5436. }
  5437. if (upb_enumdef_numvals(e) == 0) {
  5438. upb_status_seterrmsg(status, "Enum had no values.");
  5439. return false;
  5440. }
  5441. return true;
  5442. }
  5443. static size_t enum_onname(void *closure, const void *hd, const char *buf,
  5444. size_t n, const upb_bufhandle *handle) {
  5445. upb_descreader *r = closure;
  5446. char *fullname = upb_strndup(buf, n);
  5447. UPB_UNUSED(hd);
  5448. UPB_UNUSED(handle);
  5449. /* XXX: see comment at the top of the file. */
  5450. upb_def_setfullname(upb_descreader_last(r), fullname, NULL);
  5451. free(fullname);
  5452. return n;
  5453. }
  5454. /* Handlers for google.protobuf.FieldDescriptorProto */
  5455. static bool field_startmsg(void *closure, const void *hd) {
  5456. upb_descreader *r = closure;
  5457. UPB_UNUSED(hd);
  5458. r->f = upb_fielddef_new(&r->defs);
  5459. free(r->default_string);
  5460. r->default_string = NULL;
  5461. /* fielddefs default to packed, but descriptors default to non-packed. */
  5462. upb_fielddef_setpacked(r->f, false);
  5463. return true;
  5464. }
  5465. /* Converts the default value in string "str" into "d". Passes a ref on str.
  5466. * Returns true on success. */
  5467. static bool parse_default(char *str, upb_fielddef *f) {
  5468. bool success = true;
  5469. char *end;
  5470. switch (upb_fielddef_type(f)) {
  5471. case UPB_TYPE_INT32: {
  5472. long val = strtol(str, &end, 0);
  5473. if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || *end)
  5474. success = false;
  5475. else
  5476. upb_fielddef_setdefaultint32(f, val);
  5477. break;
  5478. }
  5479. case UPB_TYPE_INT64: {
  5480. /* XXX: Need to write our own strtoll, since it's not available in c89. */
  5481. long long val = strtol(str, &end, 0);
  5482. if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || *end)
  5483. success = false;
  5484. else
  5485. upb_fielddef_setdefaultint64(f, val);
  5486. break;
  5487. }
  5488. case UPB_TYPE_UINT32: {
  5489. unsigned long val = strtoul(str, &end, 0);
  5490. if (val > UINT32_MAX || errno == ERANGE || *end)
  5491. success = false;
  5492. else
  5493. upb_fielddef_setdefaultuint32(f, val);
  5494. break;
  5495. }
  5496. case UPB_TYPE_UINT64: {
  5497. /* XXX: Need to write our own strtoull, since it's not available in c89. */
  5498. unsigned long long val = strtoul(str, &end, 0);
  5499. if (val > UINT64_MAX || errno == ERANGE || *end)
  5500. success = false;
  5501. else
  5502. upb_fielddef_setdefaultuint64(f, val);
  5503. break;
  5504. }
  5505. case UPB_TYPE_DOUBLE: {
  5506. double val = strtod(str, &end);
  5507. if (errno == ERANGE || *end)
  5508. success = false;
  5509. else
  5510. upb_fielddef_setdefaultdouble(f, val);
  5511. break;
  5512. }
  5513. case UPB_TYPE_FLOAT: {
  5514. /* XXX: Need to write our own strtof, since it's not available in c89. */
  5515. float val = strtod(str, &end);
  5516. if (errno == ERANGE || *end)
  5517. success = false;
  5518. else
  5519. upb_fielddef_setdefaultfloat(f, val);
  5520. break;
  5521. }
  5522. case UPB_TYPE_BOOL: {
  5523. if (strcmp(str, "false") == 0)
  5524. upb_fielddef_setdefaultbool(f, false);
  5525. else if (strcmp(str, "true") == 0)
  5526. upb_fielddef_setdefaultbool(f, true);
  5527. else
  5528. success = false;
  5529. break;
  5530. }
  5531. default: abort();
  5532. }
  5533. return success;
  5534. }
  5535. static bool field_endmsg(void *closure, const void *hd, upb_status *status) {
  5536. upb_descreader *r = closure;
  5537. upb_fielddef *f = r->f;
  5538. UPB_UNUSED(hd);
  5539. /* TODO: verify that all required fields were present. */
  5540. assert(upb_fielddef_number(f) != 0);
  5541. assert(upb_fielddef_name(f) != NULL);
  5542. assert((upb_fielddef_subdefname(f) != NULL) == upb_fielddef_hassubdef(f));
  5543. if (r->default_string) {
  5544. if (upb_fielddef_issubmsg(f)) {
  5545. upb_status_seterrmsg(status, "Submessages cannot have defaults.");
  5546. return false;
  5547. }
  5548. if (upb_fielddef_isstring(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  5549. upb_fielddef_setdefaultcstr(f, r->default_string, NULL);
  5550. } else {
  5551. if (r->default_string && !parse_default(r->default_string, f)) {
  5552. /* We don't worry too much about giving a great error message since the
  5553. * compiler should have ensured this was correct. */
  5554. upb_status_seterrmsg(status, "Error converting default value.");
  5555. return false;
  5556. }
  5557. }
  5558. }
  5559. return true;
  5560. }
  5561. static bool field_onlazy(void *closure, const void *hd, bool val) {
  5562. upb_descreader *r = closure;
  5563. UPB_UNUSED(hd);
  5564. upb_fielddef_setlazy(r->f, val);
  5565. return true;
  5566. }
  5567. static bool field_onpacked(void *closure, const void *hd, bool val) {
  5568. upb_descreader *r = closure;
  5569. UPB_UNUSED(hd);
  5570. upb_fielddef_setpacked(r->f, val);
  5571. return true;
  5572. }
  5573. static bool field_ontype(void *closure, const void *hd, int32_t val) {
  5574. upb_descreader *r = closure;
  5575. UPB_UNUSED(hd);
  5576. upb_fielddef_setdescriptortype(r->f, val);
  5577. return true;
  5578. }
  5579. static bool field_onlabel(void *closure, const void *hd, int32_t val) {
  5580. upb_descreader *r = closure;
  5581. UPB_UNUSED(hd);
  5582. upb_fielddef_setlabel(r->f, val);
  5583. return true;
  5584. }
  5585. static bool field_onnumber(void *closure, const void *hd, int32_t val) {
  5586. upb_descreader *r = closure;
  5587. bool ok = upb_fielddef_setnumber(r->f, val, NULL);
  5588. UPB_UNUSED(hd);
  5589. UPB_ASSERT_VAR(ok, ok);
  5590. return true;
  5591. }
  5592. static size_t field_onname(void *closure, const void *hd, const char *buf,
  5593. size_t n, const upb_bufhandle *handle) {
  5594. upb_descreader *r = closure;
  5595. char *name = upb_strndup(buf, n);
  5596. UPB_UNUSED(hd);
  5597. UPB_UNUSED(handle);
  5598. /* XXX: see comment at the top of the file. */
  5599. upb_fielddef_setname(r->f, name, NULL);
  5600. free(name);
  5601. return n;
  5602. }
  5603. static size_t field_ontypename(void *closure, const void *hd, const char *buf,
  5604. size_t n, const upb_bufhandle *handle) {
  5605. upb_descreader *r = closure;
  5606. char *name = upb_strndup(buf, n);
  5607. UPB_UNUSED(hd);
  5608. UPB_UNUSED(handle);
  5609. /* XXX: see comment at the top of the file. */
  5610. upb_fielddef_setsubdefname(r->f, name, NULL);
  5611. free(name);
  5612. return n;
  5613. }
  5614. static size_t field_onextendee(void *closure, const void *hd, const char *buf,
  5615. size_t n, const upb_bufhandle *handle) {
  5616. upb_descreader *r = closure;
  5617. char *name = upb_strndup(buf, n);
  5618. UPB_UNUSED(hd);
  5619. UPB_UNUSED(handle);
  5620. /* XXX: see comment at the top of the file. */
  5621. upb_fielddef_setcontainingtypename(r->f, name, NULL);
  5622. free(name);
  5623. return n;
  5624. }
  5625. static size_t field_ondefaultval(void *closure, const void *hd, const char *buf,
  5626. size_t n, const upb_bufhandle *handle) {
  5627. upb_descreader *r = closure;
  5628. UPB_UNUSED(hd);
  5629. UPB_UNUSED(handle);
  5630. /* Have to convert from string to the correct type, but we might not know the
  5631. * type yet, so we save it as a string until the end of the field.
  5632. * XXX: see comment at the top of the file. */
  5633. free(r->default_string);
  5634. r->default_string = upb_strndup(buf, n);
  5635. return n;
  5636. }
  5637. /* Handlers for google.protobuf.DescriptorProto (representing a message). */
  5638. static bool msg_startmsg(void *closure, const void *hd) {
  5639. upb_descreader *r = closure;
  5640. upb_msgdef *m;
  5641. UPB_UNUSED(hd);
  5642. m = upb_msgdef_new(&r->defs);
  5643. upb_msgdef_setprimitiveshavepresence(m, r->primitives_have_presence);
  5644. upb_deflist_push(&r->defs, upb_msgdef_upcast_mutable(m));
  5645. upb_descreader_startcontainer(r);
  5646. return true;
  5647. }
  5648. static bool msg_endmsg(void *closure, const void *hd, upb_status *status) {
  5649. upb_descreader *r = closure;
  5650. upb_msgdef *m = upb_descreader_top(r);
  5651. UPB_UNUSED(hd);
  5652. if(!upb_def_fullname(upb_msgdef_upcast_mutable(m))) {
  5653. upb_status_seterrmsg(status, "Encountered message with no name.");
  5654. return false;
  5655. }
  5656. upb_descreader_endcontainer(r);
  5657. return true;
  5658. }
  5659. static size_t msg_onname(void *closure, const void *hd, const char *buf,
  5660. size_t n, const upb_bufhandle *handle) {
  5661. upb_descreader *r = closure;
  5662. upb_msgdef *m = upb_descreader_top(r);
  5663. /* XXX: see comment at the top of the file. */
  5664. char *name = upb_strndup(buf, n);
  5665. UPB_UNUSED(hd);
  5666. UPB_UNUSED(handle);
  5667. upb_def_setfullname(upb_msgdef_upcast_mutable(m), name, NULL);
  5668. upb_descreader_setscopename(r, name); /* Passes ownership of name. */
  5669. return n;
  5670. }
  5671. static bool msg_onendfield(void *closure, const void *hd) {
  5672. upb_descreader *r = closure;
  5673. upb_msgdef *m = upb_descreader_top(r);
  5674. UPB_UNUSED(hd);
  5675. upb_msgdef_addfield(m, r->f, &r->defs, NULL);
  5676. r->f = NULL;
  5677. return true;
  5678. }
  5679. static bool pushextension(void *closure, const void *hd) {
  5680. upb_descreader *r = closure;
  5681. UPB_UNUSED(hd);
  5682. assert(upb_fielddef_containingtypename(r->f));
  5683. upb_fielddef_setisextension(r->f, true);
  5684. upb_deflist_push(&r->defs, upb_fielddef_upcast_mutable(r->f));
  5685. r->f = NULL;
  5686. return true;
  5687. }
  5688. #define D(name) upbdefs_google_protobuf_ ## name(s)
  5689. static void reghandlers(const void *closure, upb_handlers *h) {
  5690. const upb_symtab *s = closure;
  5691. const upb_msgdef *m = upb_handlers_msgdef(h);
  5692. if (m == D(DescriptorProto)) {
  5693. upb_handlers_setstartmsg(h, &msg_startmsg, NULL);
  5694. upb_handlers_setendmsg(h, &msg_endmsg, NULL);
  5695. upb_handlers_setstring(h, D(DescriptorProto_name), &msg_onname, NULL);
  5696. upb_handlers_setendsubmsg(h, D(DescriptorProto_field), &msg_onendfield,
  5697. NULL);
  5698. upb_handlers_setendsubmsg(h, D(DescriptorProto_extension), &pushextension,
  5699. NULL);
  5700. } else if (m == D(FileDescriptorProto)) {
  5701. upb_handlers_setstartmsg(h, &file_startmsg, NULL);
  5702. upb_handlers_setendmsg(h, &file_endmsg, NULL);
  5703. upb_handlers_setstring(h, D(FileDescriptorProto_package), &file_onpackage,
  5704. NULL);
  5705. upb_handlers_setstring(h, D(FileDescriptorProto_syntax), &file_onsyntax,
  5706. NULL);
  5707. upb_handlers_setendsubmsg(h, D(FileDescriptorProto_extension), &pushextension,
  5708. NULL);
  5709. } else if (m == D(EnumValueDescriptorProto)) {
  5710. upb_handlers_setstartmsg(h, &enumval_startmsg, NULL);
  5711. upb_handlers_setendmsg(h, &enumval_endmsg, NULL);
  5712. upb_handlers_setstring(h, D(EnumValueDescriptorProto_name), &enumval_onname, NULL);
  5713. upb_handlers_setint32(h, D(EnumValueDescriptorProto_number), &enumval_onnumber,
  5714. NULL);
  5715. } else if (m == D(EnumDescriptorProto)) {
  5716. upb_handlers_setstartmsg(h, &enum_startmsg, NULL);
  5717. upb_handlers_setendmsg(h, &enum_endmsg, NULL);
  5718. upb_handlers_setstring(h, D(EnumDescriptorProto_name), &enum_onname, NULL);
  5719. } else if (m == D(FieldDescriptorProto)) {
  5720. upb_handlers_setstartmsg(h, &field_startmsg, NULL);
  5721. upb_handlers_setendmsg(h, &field_endmsg, NULL);
  5722. upb_handlers_setint32(h, D(FieldDescriptorProto_type), &field_ontype,
  5723. NULL);
  5724. upb_handlers_setint32(h, D(FieldDescriptorProto_label), &field_onlabel,
  5725. NULL);
  5726. upb_handlers_setint32(h, D(FieldDescriptorProto_number), &field_onnumber,
  5727. NULL);
  5728. upb_handlers_setstring(h, D(FieldDescriptorProto_name), &field_onname,
  5729. NULL);
  5730. upb_handlers_setstring(h, D(FieldDescriptorProto_type_name),
  5731. &field_ontypename, NULL);
  5732. upb_handlers_setstring(h, D(FieldDescriptorProto_extendee),
  5733. &field_onextendee, NULL);
  5734. upb_handlers_setstring(h, D(FieldDescriptorProto_default_value),
  5735. &field_ondefaultval, NULL);
  5736. } else if (m == D(FieldOptions)) {
  5737. upb_handlers_setbool(h, D(FieldOptions_lazy), &field_onlazy, NULL);
  5738. upb_handlers_setbool(h, D(FieldOptions_packed), &field_onpacked, NULL);
  5739. }
  5740. }
  5741. #undef D
  5742. void descreader_cleanup(void *_r) {
  5743. upb_descreader *r = _r;
  5744. free(r->name);
  5745. upb_deflist_uninit(&r->defs);
  5746. free(r->default_string);
  5747. while (r->stack_len > 0) {
  5748. upb_descreader_frame *f = &r->stack[--r->stack_len];
  5749. free(f->name);
  5750. }
  5751. }
  5752. /* Public API ****************************************************************/
  5753. upb_descreader *upb_descreader_create(upb_env *e, const upb_handlers *h) {
  5754. upb_descreader *r = upb_env_malloc(e, sizeof(upb_descreader));
  5755. if (!r || !upb_env_addcleanup(e, descreader_cleanup, r)) {
  5756. return NULL;
  5757. }
  5758. upb_deflist_init(&r->defs);
  5759. upb_sink_reset(upb_descreader_input(r), h, r);
  5760. r->stack_len = 0;
  5761. r->name = NULL;
  5762. r->default_string = NULL;
  5763. return r;
  5764. }
  5765. upb_def **upb_descreader_getdefs(upb_descreader *r, void *owner, int *n) {
  5766. *n = r->defs.len;
  5767. upb_deflist_donaterefs(&r->defs, owner);
  5768. return r->defs.defs;
  5769. }
  5770. upb_sink *upb_descreader_input(upb_descreader *r) {
  5771. return &r->sink;
  5772. }
  5773. const upb_handlers *upb_descreader_newhandlers(const void *owner) {
  5774. const upb_symtab *s = upbdefs_google_protobuf_descriptor(&s);
  5775. const upb_handlers *h = upb_handlers_newfrozen(
  5776. upbdefs_google_protobuf_FileDescriptorSet(s), owner, reghandlers, s);
  5777. upb_symtab_unref(s, &s);
  5778. return h;
  5779. }
  5780. /*
  5781. ** protobuf decoder bytecode compiler
  5782. **
  5783. ** Code to compile a upb::Handlers into bytecode for decoding a protobuf
  5784. ** according to that specific schema and destination handlers.
  5785. **
  5786. ** Compiling to bytecode is always the first step. If we are using the
  5787. ** interpreted decoder we leave it as bytecode and interpret that. If we are
  5788. ** using a JIT decoder we use a code generator to turn the bytecode into native
  5789. ** code, LLVM IR, etc.
  5790. **
  5791. ** Bytecode definition is in decoder.int.h.
  5792. */
  5793. #include <stdarg.h>
  5794. #ifdef UPB_DUMP_BYTECODE
  5795. #include <stdio.h>
  5796. #endif
  5797. #define MAXLABEL 5
  5798. #define EMPTYLABEL -1
  5799. /* mgroup *********************************************************************/
  5800. static void freegroup(upb_refcounted *r) {
  5801. mgroup *g = (mgroup*)r;
  5802. upb_inttable_uninit(&g->methods);
  5803. #ifdef UPB_USE_JIT_X64
  5804. upb_pbdecoder_freejit(g);
  5805. #endif
  5806. free(g->bytecode);
  5807. free(g);
  5808. }
  5809. static void visitgroup(const upb_refcounted *r, upb_refcounted_visit *visit,
  5810. void *closure) {
  5811. const mgroup *g = (const mgroup*)r;
  5812. upb_inttable_iter i;
  5813. upb_inttable_begin(&i, &g->methods);
  5814. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5815. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  5816. visit(r, upb_pbdecodermethod_upcast(method), closure);
  5817. }
  5818. }
  5819. mgroup *newgroup(const void *owner) {
  5820. mgroup *g = malloc(sizeof(*g));
  5821. static const struct upb_refcounted_vtbl vtbl = {visitgroup, freegroup};
  5822. upb_refcounted_init(mgroup_upcast_mutable(g), &vtbl, owner);
  5823. upb_inttable_init(&g->methods, UPB_CTYPE_PTR);
  5824. g->bytecode = NULL;
  5825. g->bytecode_end = NULL;
  5826. return g;
  5827. }
  5828. /* upb_pbdecodermethod ********************************************************/
  5829. static void freemethod(upb_refcounted *r) {
  5830. upb_pbdecodermethod *method = (upb_pbdecodermethod*)r;
  5831. if (method->dest_handlers_) {
  5832. upb_handlers_unref(method->dest_handlers_, method);
  5833. }
  5834. upb_inttable_uninit(&method->dispatch);
  5835. free(method);
  5836. }
  5837. static void visitmethod(const upb_refcounted *r, upb_refcounted_visit *visit,
  5838. void *closure) {
  5839. const upb_pbdecodermethod *m = (const upb_pbdecodermethod*)r;
  5840. visit(r, m->group, closure);
  5841. }
  5842. static upb_pbdecodermethod *newmethod(const upb_handlers *dest_handlers,
  5843. mgroup *group) {
  5844. static const struct upb_refcounted_vtbl vtbl = {visitmethod, freemethod};
  5845. upb_pbdecodermethod *ret = malloc(sizeof(*ret));
  5846. upb_refcounted_init(upb_pbdecodermethod_upcast_mutable(ret), &vtbl, &ret);
  5847. upb_byteshandler_init(&ret->input_handler_);
  5848. /* The method references the group and vice-versa, in a circular reference. */
  5849. upb_ref2(ret, group);
  5850. upb_ref2(group, ret);
  5851. upb_inttable_insertptr(&group->methods, dest_handlers, upb_value_ptr(ret));
  5852. upb_pbdecodermethod_unref(ret, &ret);
  5853. ret->group = mgroup_upcast_mutable(group);
  5854. ret->dest_handlers_ = dest_handlers;
  5855. ret->is_native_ = false; /* If we JIT, it will update this later. */
  5856. upb_inttable_init(&ret->dispatch, UPB_CTYPE_UINT64);
  5857. if (ret->dest_handlers_) {
  5858. upb_handlers_ref(ret->dest_handlers_, ret);
  5859. }
  5860. return ret;
  5861. }
  5862. const upb_handlers *upb_pbdecodermethod_desthandlers(
  5863. const upb_pbdecodermethod *m) {
  5864. return m->dest_handlers_;
  5865. }
  5866. const upb_byteshandler *upb_pbdecodermethod_inputhandler(
  5867. const upb_pbdecodermethod *m) {
  5868. return &m->input_handler_;
  5869. }
  5870. bool upb_pbdecodermethod_isnative(const upb_pbdecodermethod *m) {
  5871. return m->is_native_;
  5872. }
  5873. const upb_pbdecodermethod *upb_pbdecodermethod_new(
  5874. const upb_pbdecodermethodopts *opts, const void *owner) {
  5875. const upb_pbdecodermethod *ret;
  5876. upb_pbcodecache cache;
  5877. upb_pbcodecache_init(&cache);
  5878. ret = upb_pbcodecache_getdecodermethod(&cache, opts);
  5879. upb_pbdecodermethod_ref(ret, owner);
  5880. upb_pbcodecache_uninit(&cache);
  5881. return ret;
  5882. }
  5883. /* bytecode compiler **********************************************************/
  5884. /* Data used only at compilation time. */
  5885. typedef struct {
  5886. mgroup *group;
  5887. uint32_t *pc;
  5888. int fwd_labels[MAXLABEL];
  5889. int back_labels[MAXLABEL];
  5890. /* For fields marked "lazy", parse them lazily or eagerly? */
  5891. bool lazy;
  5892. } compiler;
  5893. static compiler *newcompiler(mgroup *group, bool lazy) {
  5894. compiler *ret = malloc(sizeof(*ret));
  5895. int i;
  5896. ret->group = group;
  5897. ret->lazy = lazy;
  5898. for (i = 0; i < MAXLABEL; i++) {
  5899. ret->fwd_labels[i] = EMPTYLABEL;
  5900. ret->back_labels[i] = EMPTYLABEL;
  5901. }
  5902. return ret;
  5903. }
  5904. static void freecompiler(compiler *c) {
  5905. free(c);
  5906. }
  5907. const size_t ptr_words = sizeof(void*) / sizeof(uint32_t);
  5908. /* How many words an instruction is. */
  5909. static int instruction_len(uint32_t instr) {
  5910. switch (getop(instr)) {
  5911. case OP_SETDISPATCH: return 1 + ptr_words;
  5912. case OP_TAGN: return 3;
  5913. case OP_SETBIGGROUPNUM: return 2;
  5914. default: return 1;
  5915. }
  5916. }
  5917. bool op_has_longofs(int32_t instruction) {
  5918. switch (getop(instruction)) {
  5919. case OP_CALL:
  5920. case OP_BRANCH:
  5921. case OP_CHECKDELIM:
  5922. return true;
  5923. /* The "tag" instructions only have 8 bytes available for the jump target,
  5924. * but that is ok because these opcodes only require short jumps. */
  5925. case OP_TAG1:
  5926. case OP_TAG2:
  5927. case OP_TAGN:
  5928. return false;
  5929. default:
  5930. assert(false);
  5931. return false;
  5932. }
  5933. }
  5934. static int32_t getofs(uint32_t instruction) {
  5935. if (op_has_longofs(instruction)) {
  5936. return (int32_t)instruction >> 8;
  5937. } else {
  5938. return (int8_t)(instruction >> 8);
  5939. }
  5940. }
  5941. static void setofs(uint32_t *instruction, int32_t ofs) {
  5942. if (op_has_longofs(*instruction)) {
  5943. *instruction = getop(*instruction) | ofs << 8;
  5944. } else {
  5945. *instruction = (*instruction & ~0xff00) | ((ofs & 0xff) << 8);
  5946. }
  5947. assert(getofs(*instruction) == ofs); /* Would fail in cases of overflow. */
  5948. }
  5949. static uint32_t pcofs(compiler *c) { return c->pc - c->group->bytecode; }
  5950. /* Defines a local label at the current PC location. All previous forward
  5951. * references are updated to point to this location. The location is noted
  5952. * for any future backward references. */
  5953. static void label(compiler *c, unsigned int label) {
  5954. int val;
  5955. uint32_t *codep;
  5956. assert(label < MAXLABEL);
  5957. val = c->fwd_labels[label];
  5958. codep = (val == EMPTYLABEL) ? NULL : c->group->bytecode + val;
  5959. while (codep) {
  5960. int ofs = getofs(*codep);
  5961. setofs(codep, c->pc - codep - instruction_len(*codep));
  5962. codep = ofs ? codep + ofs : NULL;
  5963. }
  5964. c->fwd_labels[label] = EMPTYLABEL;
  5965. c->back_labels[label] = pcofs(c);
  5966. }
  5967. /* Creates a reference to a numbered label; either a forward reference
  5968. * (positive arg) or backward reference (negative arg). For forward references
  5969. * the value returned now is actually a "next" pointer into a linked list of all
  5970. * instructions that use this label and will be patched later when the label is
  5971. * defined with label().
  5972. *
  5973. * The returned value is the offset that should be written into the instruction.
  5974. */
  5975. static int32_t labelref(compiler *c, int label) {
  5976. assert(label < MAXLABEL);
  5977. if (label == LABEL_DISPATCH) {
  5978. /* No resolving required. */
  5979. return 0;
  5980. } else if (label < 0) {
  5981. /* Backward local label. Relative to the next instruction. */
  5982. uint32_t from = (c->pc + 1) - c->group->bytecode;
  5983. return c->back_labels[-label] - from;
  5984. } else {
  5985. /* Forward local label: prepend to (possibly-empty) linked list. */
  5986. int *lptr = &c->fwd_labels[label];
  5987. int32_t ret = (*lptr == EMPTYLABEL) ? 0 : *lptr - pcofs(c);
  5988. *lptr = pcofs(c);
  5989. return ret;
  5990. }
  5991. }
  5992. static void put32(compiler *c, uint32_t v) {
  5993. mgroup *g = c->group;
  5994. if (c->pc == g->bytecode_end) {
  5995. int ofs = pcofs(c);
  5996. size_t oldsize = g->bytecode_end - g->bytecode;
  5997. size_t newsize = UPB_MAX(oldsize * 2, 64);
  5998. /* TODO(haberman): handle OOM. */
  5999. g->bytecode = realloc(g->bytecode, newsize * sizeof(uint32_t));
  6000. g->bytecode_end = g->bytecode + newsize;
  6001. c->pc = g->bytecode + ofs;
  6002. }
  6003. *c->pc++ = v;
  6004. }
  6005. static void putop(compiler *c, opcode op, ...) {
  6006. va_list ap;
  6007. va_start(ap, op);
  6008. switch (op) {
  6009. case OP_SETDISPATCH: {
  6010. uintptr_t ptr = (uintptr_t)va_arg(ap, void*);
  6011. put32(c, OP_SETDISPATCH);
  6012. put32(c, ptr);
  6013. if (sizeof(uintptr_t) > sizeof(uint32_t))
  6014. put32(c, (uint64_t)ptr >> 32);
  6015. break;
  6016. }
  6017. case OP_STARTMSG:
  6018. case OP_ENDMSG:
  6019. case OP_PUSHLENDELIM:
  6020. case OP_POP:
  6021. case OP_SETDELIM:
  6022. case OP_HALT:
  6023. case OP_RET:
  6024. case OP_DISPATCH:
  6025. put32(c, op);
  6026. break;
  6027. case OP_PARSE_DOUBLE:
  6028. case OP_PARSE_FLOAT:
  6029. case OP_PARSE_INT64:
  6030. case OP_PARSE_UINT64:
  6031. case OP_PARSE_INT32:
  6032. case OP_PARSE_FIXED64:
  6033. case OP_PARSE_FIXED32:
  6034. case OP_PARSE_BOOL:
  6035. case OP_PARSE_UINT32:
  6036. case OP_PARSE_SFIXED32:
  6037. case OP_PARSE_SFIXED64:
  6038. case OP_PARSE_SINT32:
  6039. case OP_PARSE_SINT64:
  6040. case OP_STARTSEQ:
  6041. case OP_ENDSEQ:
  6042. case OP_STARTSUBMSG:
  6043. case OP_ENDSUBMSG:
  6044. case OP_STARTSTR:
  6045. case OP_STRING:
  6046. case OP_ENDSTR:
  6047. case OP_PUSHTAGDELIM:
  6048. put32(c, op | va_arg(ap, upb_selector_t) << 8);
  6049. break;
  6050. case OP_SETBIGGROUPNUM:
  6051. put32(c, op);
  6052. put32(c, va_arg(ap, int));
  6053. break;
  6054. case OP_CALL: {
  6055. const upb_pbdecodermethod *method = va_arg(ap, upb_pbdecodermethod *);
  6056. put32(c, op | (method->code_base.ofs - (pcofs(c) + 1)) << 8);
  6057. break;
  6058. }
  6059. case OP_CHECKDELIM:
  6060. case OP_BRANCH: {
  6061. uint32_t instruction = op;
  6062. int label = va_arg(ap, int);
  6063. setofs(&instruction, labelref(c, label));
  6064. put32(c, instruction);
  6065. break;
  6066. }
  6067. case OP_TAG1:
  6068. case OP_TAG2: {
  6069. int label = va_arg(ap, int);
  6070. uint64_t tag = va_arg(ap, uint64_t);
  6071. uint32_t instruction = op | (tag << 16);
  6072. assert(tag <= 0xffff);
  6073. setofs(&instruction, labelref(c, label));
  6074. put32(c, instruction);
  6075. break;
  6076. }
  6077. case OP_TAGN: {
  6078. int label = va_arg(ap, int);
  6079. uint64_t tag = va_arg(ap, uint64_t);
  6080. uint32_t instruction = op | (upb_value_size(tag) << 16);
  6081. setofs(&instruction, labelref(c, label));
  6082. put32(c, instruction);
  6083. put32(c, tag);
  6084. put32(c, tag >> 32);
  6085. break;
  6086. }
  6087. }
  6088. va_end(ap);
  6089. }
  6090. #if defined(UPB_USE_JIT_X64) || defined(UPB_DUMP_BYTECODE)
  6091. const char *upb_pbdecoder_getopname(unsigned int op) {
  6092. #define QUOTE(x) #x
  6093. #define EXPAND_AND_QUOTE(x) QUOTE(x)
  6094. #define OPNAME(x) OP_##x
  6095. #define OP(x) case OPNAME(x): return EXPAND_AND_QUOTE(OPNAME(x));
  6096. #define T(x) OP(PARSE_##x)
  6097. /* Keep in sync with list in decoder.int.h. */
  6098. switch ((opcode)op) {
  6099. T(DOUBLE) T(FLOAT) T(INT64) T(UINT64) T(INT32) T(FIXED64) T(FIXED32)
  6100. T(BOOL) T(UINT32) T(SFIXED32) T(SFIXED64) T(SINT32) T(SINT64)
  6101. OP(STARTMSG) OP(ENDMSG) OP(STARTSEQ) OP(ENDSEQ) OP(STARTSUBMSG)
  6102. OP(ENDSUBMSG) OP(STARTSTR) OP(STRING) OP(ENDSTR) OP(CALL) OP(RET)
  6103. OP(PUSHLENDELIM) OP(PUSHTAGDELIM) OP(SETDELIM) OP(CHECKDELIM)
  6104. OP(BRANCH) OP(TAG1) OP(TAG2) OP(TAGN) OP(SETDISPATCH) OP(POP)
  6105. OP(SETBIGGROUPNUM) OP(DISPATCH) OP(HALT)
  6106. }
  6107. return "<unknown op>";
  6108. #undef OP
  6109. #undef T
  6110. }
  6111. #endif
  6112. #ifdef UPB_DUMP_BYTECODE
  6113. static void dumpbc(uint32_t *p, uint32_t *end, FILE *f) {
  6114. uint32_t *begin = p;
  6115. while (p < end) {
  6116. fprintf(f, "%p %8tx", p, p - begin);
  6117. uint32_t instr = *p++;
  6118. uint8_t op = getop(instr);
  6119. fprintf(f, " %s", upb_pbdecoder_getopname(op));
  6120. switch ((opcode)op) {
  6121. case OP_SETDISPATCH: {
  6122. const upb_inttable *dispatch;
  6123. memcpy(&dispatch, p, sizeof(void*));
  6124. p += ptr_words;
  6125. const upb_pbdecodermethod *method =
  6126. (void *)((char *)dispatch -
  6127. offsetof(upb_pbdecodermethod, dispatch));
  6128. fprintf(f, " %s", upb_msgdef_fullname(
  6129. upb_handlers_msgdef(method->dest_handlers_)));
  6130. break;
  6131. }
  6132. case OP_DISPATCH:
  6133. case OP_STARTMSG:
  6134. case OP_ENDMSG:
  6135. case OP_PUSHLENDELIM:
  6136. case OP_POP:
  6137. case OP_SETDELIM:
  6138. case OP_HALT:
  6139. case OP_RET:
  6140. break;
  6141. case OP_PARSE_DOUBLE:
  6142. case OP_PARSE_FLOAT:
  6143. case OP_PARSE_INT64:
  6144. case OP_PARSE_UINT64:
  6145. case OP_PARSE_INT32:
  6146. case OP_PARSE_FIXED64:
  6147. case OP_PARSE_FIXED32:
  6148. case OP_PARSE_BOOL:
  6149. case OP_PARSE_UINT32:
  6150. case OP_PARSE_SFIXED32:
  6151. case OP_PARSE_SFIXED64:
  6152. case OP_PARSE_SINT32:
  6153. case OP_PARSE_SINT64:
  6154. case OP_STARTSEQ:
  6155. case OP_ENDSEQ:
  6156. case OP_STARTSUBMSG:
  6157. case OP_ENDSUBMSG:
  6158. case OP_STARTSTR:
  6159. case OP_STRING:
  6160. case OP_ENDSTR:
  6161. case OP_PUSHTAGDELIM:
  6162. fprintf(f, " %d", instr >> 8);
  6163. break;
  6164. case OP_SETBIGGROUPNUM:
  6165. fprintf(f, " %d", *p++);
  6166. break;
  6167. case OP_CHECKDELIM:
  6168. case OP_CALL:
  6169. case OP_BRANCH:
  6170. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  6171. break;
  6172. case OP_TAG1:
  6173. case OP_TAG2: {
  6174. fprintf(f, " tag:0x%x", instr >> 16);
  6175. if (getofs(instr)) {
  6176. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  6177. }
  6178. break;
  6179. }
  6180. case OP_TAGN: {
  6181. uint64_t tag = *p++;
  6182. tag |= (uint64_t)*p++ << 32;
  6183. fprintf(f, " tag:0x%llx", (long long)tag);
  6184. fprintf(f, " n:%d", instr >> 16);
  6185. if (getofs(instr)) {
  6186. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  6187. }
  6188. break;
  6189. }
  6190. }
  6191. fputs("\n", f);
  6192. }
  6193. }
  6194. #endif
  6195. static uint64_t get_encoded_tag(const upb_fielddef *f, int wire_type) {
  6196. uint32_t tag = (upb_fielddef_number(f) << 3) | wire_type;
  6197. uint64_t encoded_tag = upb_vencode32(tag);
  6198. /* No tag should be greater than 5 bytes. */
  6199. assert(encoded_tag <= 0xffffffffff);
  6200. return encoded_tag;
  6201. }
  6202. static void putchecktag(compiler *c, const upb_fielddef *f,
  6203. int wire_type, int dest) {
  6204. uint64_t tag = get_encoded_tag(f, wire_type);
  6205. switch (upb_value_size(tag)) {
  6206. case 1:
  6207. putop(c, OP_TAG1, dest, tag);
  6208. break;
  6209. case 2:
  6210. putop(c, OP_TAG2, dest, tag);
  6211. break;
  6212. default:
  6213. putop(c, OP_TAGN, dest, tag);
  6214. break;
  6215. }
  6216. }
  6217. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  6218. upb_selector_t selector;
  6219. bool ok = upb_handlers_getselector(f, type, &selector);
  6220. UPB_ASSERT_VAR(ok, ok);
  6221. return selector;
  6222. }
  6223. /* Takes an existing, primary dispatch table entry and repacks it with a
  6224. * different alternate wire type. Called when we are inserting a secondary
  6225. * dispatch table entry for an alternate wire type. */
  6226. static uint64_t repack(uint64_t dispatch, int new_wt2) {
  6227. uint64_t ofs;
  6228. uint8_t wt1;
  6229. uint8_t old_wt2;
  6230. upb_pbdecoder_unpackdispatch(dispatch, &ofs, &wt1, &old_wt2);
  6231. assert(old_wt2 == NO_WIRE_TYPE); /* wt2 should not be set yet. */
  6232. return upb_pbdecoder_packdispatch(ofs, wt1, new_wt2);
  6233. }
  6234. /* Marks the current bytecode position as the dispatch target for this message,
  6235. * field, and wire type. */
  6236. static void dispatchtarget(compiler *c, upb_pbdecodermethod *method,
  6237. const upb_fielddef *f, int wire_type) {
  6238. /* Offset is relative to msg base. */
  6239. uint64_t ofs = pcofs(c) - method->code_base.ofs;
  6240. uint32_t fn = upb_fielddef_number(f);
  6241. upb_inttable *d = &method->dispatch;
  6242. upb_value v;
  6243. if (upb_inttable_remove(d, fn, &v)) {
  6244. /* TODO: prioritize based on packed setting in .proto file. */
  6245. uint64_t repacked = repack(upb_value_getuint64(v), wire_type);
  6246. upb_inttable_insert(d, fn, upb_value_uint64(repacked));
  6247. upb_inttable_insert(d, fn + UPB_MAX_FIELDNUMBER, upb_value_uint64(ofs));
  6248. } else {
  6249. uint64_t val = upb_pbdecoder_packdispatch(ofs, wire_type, NO_WIRE_TYPE);
  6250. upb_inttable_insert(d, fn, upb_value_uint64(val));
  6251. }
  6252. }
  6253. static void putpush(compiler *c, const upb_fielddef *f) {
  6254. if (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE) {
  6255. putop(c, OP_PUSHLENDELIM);
  6256. } else {
  6257. uint32_t fn = upb_fielddef_number(f);
  6258. if (fn >= 1 << 24) {
  6259. putop(c, OP_PUSHTAGDELIM, 0);
  6260. putop(c, OP_SETBIGGROUPNUM, fn);
  6261. } else {
  6262. putop(c, OP_PUSHTAGDELIM, fn);
  6263. }
  6264. }
  6265. }
  6266. static upb_pbdecodermethod *find_submethod(const compiler *c,
  6267. const upb_pbdecodermethod *method,
  6268. const upb_fielddef *f) {
  6269. const upb_handlers *sub =
  6270. upb_handlers_getsubhandlers(method->dest_handlers_, f);
  6271. upb_value v;
  6272. return upb_inttable_lookupptr(&c->group->methods, sub, &v)
  6273. ? upb_value_getptr(v)
  6274. : NULL;
  6275. }
  6276. static void putsel(compiler *c, opcode op, upb_selector_t sel,
  6277. const upb_handlers *h) {
  6278. if (upb_handlers_gethandler(h, sel)) {
  6279. putop(c, op, sel);
  6280. }
  6281. }
  6282. /* Puts an opcode to call a callback, but only if a callback actually exists for
  6283. * this field and handler type. */
  6284. static void maybeput(compiler *c, opcode op, const upb_handlers *h,
  6285. const upb_fielddef *f, upb_handlertype_t type) {
  6286. putsel(c, op, getsel(f, type), h);
  6287. }
  6288. static bool haslazyhandlers(const upb_handlers *h, const upb_fielddef *f) {
  6289. if (!upb_fielddef_lazy(f))
  6290. return false;
  6291. return upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STARTSTR)) ||
  6292. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STRING)) ||
  6293. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_ENDSTR));
  6294. }
  6295. /* bytecode compiler code generation ******************************************/
  6296. /* Symbolic names for our local labels. */
  6297. #define LABEL_LOOPSTART 1 /* Top of a repeated field loop. */
  6298. #define LABEL_LOOPBREAK 2 /* To jump out of a repeated loop */
  6299. #define LABEL_FIELD 3 /* Jump backward to find the most recent field. */
  6300. #define LABEL_ENDMSG 4 /* To reach the OP_ENDMSG instr for this msg. */
  6301. /* Generates bytecode to parse a single non-lazy message field. */
  6302. static void generate_msgfield(compiler *c, const upb_fielddef *f,
  6303. upb_pbdecodermethod *method) {
  6304. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  6305. const upb_pbdecodermethod *sub_m = find_submethod(c, method, f);
  6306. int wire_type;
  6307. if (!sub_m) {
  6308. /* Don't emit any code for this field at all; it will be parsed as an
  6309. * unknown field.
  6310. *
  6311. * TODO(haberman): we should change this to parse it as a string field
  6312. * instead. It will probably be faster, but more importantly, once we
  6313. * start vending unknown fields, a field shouldn't be treated as unknown
  6314. * just because it doesn't have subhandlers registered. */
  6315. return;
  6316. }
  6317. label(c, LABEL_FIELD);
  6318. wire_type =
  6319. (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE)
  6320. ? UPB_WIRE_TYPE_DELIMITED
  6321. : UPB_WIRE_TYPE_START_GROUP;
  6322. if (upb_fielddef_isseq(f)) {
  6323. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6324. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  6325. dispatchtarget(c, method, f, wire_type);
  6326. putop(c, OP_PUSHTAGDELIM, 0);
  6327. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  6328. label(c, LABEL_LOOPSTART);
  6329. putpush(c, f);
  6330. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  6331. putop(c, OP_CALL, sub_m);
  6332. putop(c, OP_POP);
  6333. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  6334. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  6335. putop(c, OP_SETDELIM);
  6336. }
  6337. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  6338. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  6339. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  6340. label(c, LABEL_LOOPBREAK);
  6341. putop(c, OP_POP);
  6342. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  6343. } else {
  6344. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6345. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  6346. dispatchtarget(c, method, f, wire_type);
  6347. putpush(c, f);
  6348. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  6349. putop(c, OP_CALL, sub_m);
  6350. putop(c, OP_POP);
  6351. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  6352. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  6353. putop(c, OP_SETDELIM);
  6354. }
  6355. }
  6356. }
  6357. /* Generates bytecode to parse a single string or lazy submessage field. */
  6358. static void generate_delimfield(compiler *c, const upb_fielddef *f,
  6359. upb_pbdecodermethod *method) {
  6360. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  6361. label(c, LABEL_FIELD);
  6362. if (upb_fielddef_isseq(f)) {
  6363. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6364. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  6365. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  6366. putop(c, OP_PUSHTAGDELIM, 0);
  6367. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  6368. label(c, LABEL_LOOPSTART);
  6369. putop(c, OP_PUSHLENDELIM);
  6370. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  6371. /* Need to emit even if no handler to skip past the string. */
  6372. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  6373. putop(c, OP_POP);
  6374. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  6375. putop(c, OP_SETDELIM);
  6376. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  6377. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_LOOPBREAK);
  6378. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  6379. label(c, LABEL_LOOPBREAK);
  6380. putop(c, OP_POP);
  6381. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  6382. } else {
  6383. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6384. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  6385. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  6386. putop(c, OP_PUSHLENDELIM);
  6387. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  6388. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  6389. putop(c, OP_POP);
  6390. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  6391. putop(c, OP_SETDELIM);
  6392. }
  6393. }
  6394. /* Generates bytecode to parse a single primitive field. */
  6395. static void generate_primitivefield(compiler *c, const upb_fielddef *f,
  6396. upb_pbdecodermethod *method) {
  6397. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  6398. upb_descriptortype_t descriptor_type = upb_fielddef_descriptortype(f);
  6399. opcode parse_type;
  6400. upb_selector_t sel;
  6401. int wire_type;
  6402. label(c, LABEL_FIELD);
  6403. /* From a decoding perspective, ENUM is the same as INT32. */
  6404. if (descriptor_type == UPB_DESCRIPTOR_TYPE_ENUM)
  6405. descriptor_type = UPB_DESCRIPTOR_TYPE_INT32;
  6406. parse_type = (opcode)descriptor_type;
  6407. /* TODO(haberman): generate packed or non-packed first depending on "packed"
  6408. * setting in the fielddef. This will favor (in speed) whichever was
  6409. * specified. */
  6410. assert((int)parse_type >= 0 && parse_type <= OP_MAX);
  6411. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  6412. wire_type = upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  6413. if (upb_fielddef_isseq(f)) {
  6414. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6415. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  6416. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  6417. putop(c, OP_PUSHLENDELIM);
  6418. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Packed */
  6419. label(c, LABEL_LOOPSTART);
  6420. putop(c, parse_type, sel);
  6421. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  6422. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  6423. dispatchtarget(c, method, f, wire_type);
  6424. putop(c, OP_PUSHTAGDELIM, 0);
  6425. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Non-packed */
  6426. label(c, LABEL_LOOPSTART);
  6427. putop(c, parse_type, sel);
  6428. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  6429. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  6430. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  6431. label(c, LABEL_LOOPBREAK);
  6432. putop(c, OP_POP); /* Packed and non-packed join. */
  6433. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  6434. putop(c, OP_SETDELIM); /* Could remove for non-packed by dup ENDSEQ. */
  6435. } else {
  6436. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6437. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  6438. dispatchtarget(c, method, f, wire_type);
  6439. putop(c, parse_type, sel);
  6440. }
  6441. }
  6442. /* Adds bytecode for parsing the given message to the given decoderplan,
  6443. * while adding all dispatch targets to this message's dispatch table. */
  6444. static void compile_method(compiler *c, upb_pbdecodermethod *method) {
  6445. const upb_handlers *h;
  6446. const upb_msgdef *md;
  6447. uint32_t* start_pc;
  6448. upb_msg_field_iter i;
  6449. upb_value val;
  6450. assert(method);
  6451. /* Clear all entries in the dispatch table. */
  6452. upb_inttable_uninit(&method->dispatch);
  6453. upb_inttable_init(&method->dispatch, UPB_CTYPE_UINT64);
  6454. h = upb_pbdecodermethod_desthandlers(method);
  6455. md = upb_handlers_msgdef(h);
  6456. method->code_base.ofs = pcofs(c);
  6457. putop(c, OP_SETDISPATCH, &method->dispatch);
  6458. putsel(c, OP_STARTMSG, UPB_STARTMSG_SELECTOR, h);
  6459. label(c, LABEL_FIELD);
  6460. start_pc = c->pc;
  6461. for(upb_msg_field_begin(&i, md);
  6462. !upb_msg_field_done(&i);
  6463. upb_msg_field_next(&i)) {
  6464. const upb_fielddef *f = upb_msg_iter_field(&i);
  6465. upb_fieldtype_t type = upb_fielddef_type(f);
  6466. if (type == UPB_TYPE_MESSAGE && !(haslazyhandlers(h, f) && c->lazy)) {
  6467. generate_msgfield(c, f, method);
  6468. } else if (type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES ||
  6469. type == UPB_TYPE_MESSAGE) {
  6470. generate_delimfield(c, f, method);
  6471. } else {
  6472. generate_primitivefield(c, f, method);
  6473. }
  6474. }
  6475. /* If there were no fields, or if no handlers were defined, we need to
  6476. * generate a non-empty loop body so that we can at least dispatch for unknown
  6477. * fields and check for the end of the message. */
  6478. if (c->pc == start_pc) {
  6479. /* Check for end-of-message. */
  6480. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6481. /* Unconditionally dispatch. */
  6482. putop(c, OP_DISPATCH, 0);
  6483. }
  6484. /* For now we just loop back to the last field of the message (or if none,
  6485. * the DISPATCH opcode for the message). */
  6486. putop(c, OP_BRANCH, -LABEL_FIELD);
  6487. /* Insert both a label and a dispatch table entry for this end-of-msg. */
  6488. label(c, LABEL_ENDMSG);
  6489. val = upb_value_uint64(pcofs(c) - method->code_base.ofs);
  6490. upb_inttable_insert(&method->dispatch, DISPATCH_ENDMSG, val);
  6491. putsel(c, OP_ENDMSG, UPB_ENDMSG_SELECTOR, h);
  6492. putop(c, OP_RET);
  6493. upb_inttable_compact(&method->dispatch);
  6494. }
  6495. /* Populate "methods" with new upb_pbdecodermethod objects reachable from "h".
  6496. * Returns the method for these handlers.
  6497. *
  6498. * Generates a new method for every destination handlers reachable from "h". */
  6499. static void find_methods(compiler *c, const upb_handlers *h) {
  6500. upb_value v;
  6501. upb_msg_field_iter i;
  6502. const upb_msgdef *md;
  6503. if (upb_inttable_lookupptr(&c->group->methods, h, &v))
  6504. return;
  6505. newmethod(h, c->group);
  6506. /* Find submethods. */
  6507. md = upb_handlers_msgdef(h);
  6508. for(upb_msg_field_begin(&i, md);
  6509. !upb_msg_field_done(&i);
  6510. upb_msg_field_next(&i)) {
  6511. const upb_fielddef *f = upb_msg_iter_field(&i);
  6512. const upb_handlers *sub_h;
  6513. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  6514. (sub_h = upb_handlers_getsubhandlers(h, f)) != NULL) {
  6515. /* We only generate a decoder method for submessages with handlers.
  6516. * Others will be parsed as unknown fields. */
  6517. find_methods(c, sub_h);
  6518. }
  6519. }
  6520. }
  6521. /* (Re-)compile bytecode for all messages in "msgs."
  6522. * Overwrites any existing bytecode in "c". */
  6523. static void compile_methods(compiler *c) {
  6524. upb_inttable_iter i;
  6525. /* Start over at the beginning of the bytecode. */
  6526. c->pc = c->group->bytecode;
  6527. upb_inttable_begin(&i, &c->group->methods);
  6528. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  6529. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  6530. compile_method(c, method);
  6531. }
  6532. }
  6533. static void set_bytecode_handlers(mgroup *g) {
  6534. upb_inttable_iter i;
  6535. upb_inttable_begin(&i, &g->methods);
  6536. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  6537. upb_pbdecodermethod *m = upb_value_getptr(upb_inttable_iter_value(&i));
  6538. upb_byteshandler *h = &m->input_handler_;
  6539. m->code_base.ptr = g->bytecode + m->code_base.ofs;
  6540. upb_byteshandler_setstartstr(h, upb_pbdecoder_startbc, m->code_base.ptr);
  6541. upb_byteshandler_setstring(h, upb_pbdecoder_decode, g);
  6542. upb_byteshandler_setendstr(h, upb_pbdecoder_end, m);
  6543. }
  6544. }
  6545. /* JIT setup. *****************************************************************/
  6546. #ifdef UPB_USE_JIT_X64
  6547. static void sethandlers(mgroup *g, bool allowjit) {
  6548. g->jit_code = NULL;
  6549. if (allowjit) {
  6550. /* Compile byte-code into machine code, create handlers. */
  6551. upb_pbdecoder_jit(g);
  6552. } else {
  6553. set_bytecode_handlers(g);
  6554. }
  6555. }
  6556. #else /* UPB_USE_JIT_X64 */
  6557. static void sethandlers(mgroup *g, bool allowjit) {
  6558. /* No JIT compiled in; use bytecode handlers unconditionally. */
  6559. UPB_UNUSED(allowjit);
  6560. set_bytecode_handlers(g);
  6561. }
  6562. #endif /* UPB_USE_JIT_X64 */
  6563. /* TODO(haberman): allow this to be constructed for an arbitrary set of dest
  6564. * handlers and other mgroups (but verify we have a transitive closure). */
  6565. const mgroup *mgroup_new(const upb_handlers *dest, bool allowjit, bool lazy,
  6566. const void *owner) {
  6567. mgroup *g;
  6568. compiler *c;
  6569. UPB_UNUSED(allowjit);
  6570. assert(upb_handlers_isfrozen(dest));
  6571. g = newgroup(owner);
  6572. c = newcompiler(g, lazy);
  6573. find_methods(c, dest);
  6574. /* We compile in two passes:
  6575. * 1. all messages are assigned relative offsets from the beginning of the
  6576. * bytecode (saved in method->code_base).
  6577. * 2. forwards OP_CALL instructions can be correctly linked since message
  6578. * offsets have been previously assigned.
  6579. *
  6580. * Could avoid the second pass by linking OP_CALL instructions somehow. */
  6581. compile_methods(c);
  6582. compile_methods(c);
  6583. g->bytecode_end = c->pc;
  6584. freecompiler(c);
  6585. #ifdef UPB_DUMP_BYTECODE
  6586. {
  6587. FILE *f = fopen("/tmp/upb-bytecode", "w");
  6588. assert(f);
  6589. dumpbc(g->bytecode, g->bytecode_end, stderr);
  6590. dumpbc(g->bytecode, g->bytecode_end, f);
  6591. fclose(f);
  6592. f = fopen("/tmp/upb-bytecode.bin", "wb");
  6593. assert(f);
  6594. fwrite(g->bytecode, 1, g->bytecode_end - g->bytecode, f);
  6595. fclose(f);
  6596. }
  6597. #endif
  6598. sethandlers(g, allowjit);
  6599. return g;
  6600. }
  6601. /* upb_pbcodecache ************************************************************/
  6602. void upb_pbcodecache_init(upb_pbcodecache *c) {
  6603. upb_inttable_init(&c->groups, UPB_CTYPE_CONSTPTR);
  6604. c->allow_jit_ = true;
  6605. }
  6606. void upb_pbcodecache_uninit(upb_pbcodecache *c) {
  6607. upb_inttable_iter i;
  6608. upb_inttable_begin(&i, &c->groups);
  6609. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  6610. const mgroup *group = upb_value_getconstptr(upb_inttable_iter_value(&i));
  6611. mgroup_unref(group, c);
  6612. }
  6613. upb_inttable_uninit(&c->groups);
  6614. }
  6615. bool upb_pbcodecache_allowjit(const upb_pbcodecache *c) {
  6616. return c->allow_jit_;
  6617. }
  6618. bool upb_pbcodecache_setallowjit(upb_pbcodecache *c, bool allow) {
  6619. if (upb_inttable_count(&c->groups) > 0)
  6620. return false;
  6621. c->allow_jit_ = allow;
  6622. return true;
  6623. }
  6624. const upb_pbdecodermethod *upb_pbcodecache_getdecodermethod(
  6625. upb_pbcodecache *c, const upb_pbdecodermethodopts *opts) {
  6626. upb_value v;
  6627. bool ok;
  6628. /* Right now we build a new DecoderMethod every time.
  6629. * TODO(haberman): properly cache methods by their true key. */
  6630. const mgroup *g = mgroup_new(opts->handlers, c->allow_jit_, opts->lazy, c);
  6631. upb_inttable_push(&c->groups, upb_value_constptr(g));
  6632. ok = upb_inttable_lookupptr(&g->methods, opts->handlers, &v);
  6633. UPB_ASSERT_VAR(ok, ok);
  6634. return upb_value_getptr(v);
  6635. }
  6636. /* upb_pbdecodermethodopts ****************************************************/
  6637. void upb_pbdecodermethodopts_init(upb_pbdecodermethodopts *opts,
  6638. const upb_handlers *h) {
  6639. opts->handlers = h;
  6640. opts->lazy = false;
  6641. }
  6642. void upb_pbdecodermethodopts_setlazy(upb_pbdecodermethodopts *opts, bool lazy) {
  6643. opts->lazy = lazy;
  6644. }
  6645. /*
  6646. ** upb::Decoder (Bytecode Decoder VM)
  6647. **
  6648. ** Bytecode must previously have been generated using the bytecode compiler in
  6649. ** compile_decoder.c. This decoder then walks through the bytecode op-by-op to
  6650. ** parse the input.
  6651. **
  6652. ** Decoding is fully resumable; we just keep a pointer to the current bytecode
  6653. ** instruction and resume from there. A fair amount of the logic here is to
  6654. ** handle the fact that values can span buffer seams and we have to be able to
  6655. ** be capable of suspending/resuming from any byte in the stream. This
  6656. ** sometimes requires keeping a few trailing bytes from the last buffer around
  6657. ** in the "residual" buffer.
  6658. */
  6659. #include <inttypes.h>
  6660. #include <stddef.h>
  6661. #ifdef UPB_DUMP_BYTECODE
  6662. #include <stdio.h>
  6663. #endif
  6664. #define CHECK_SUSPEND(x) if (!(x)) return upb_pbdecoder_suspend(d);
  6665. /* Error messages that are shared between the bytecode and JIT decoders. */
  6666. const char *kPbDecoderStackOverflow = "Nesting too deep.";
  6667. const char *kPbDecoderSubmessageTooLong =
  6668. "Submessage end extends past enclosing submessage.";
  6669. /* Error messages shared within this file. */
  6670. static const char *kUnterminatedVarint = "Unterminated varint.";
  6671. /* upb_pbdecoder **************************************************************/
  6672. static opcode halt = OP_HALT;
  6673. /* A dummy character we can point to when the user passes us a NULL buffer.
  6674. * We need this because in C (NULL + 0) and (NULL - NULL) are undefined
  6675. * behavior, which would invalidate functions like curbufleft(). */
  6676. static const char dummy_char;
  6677. /* Whether an op consumes any of the input buffer. */
  6678. static bool consumes_input(opcode op) {
  6679. switch (op) {
  6680. case OP_SETDISPATCH:
  6681. case OP_STARTMSG:
  6682. case OP_ENDMSG:
  6683. case OP_STARTSEQ:
  6684. case OP_ENDSEQ:
  6685. case OP_STARTSUBMSG:
  6686. case OP_ENDSUBMSG:
  6687. case OP_STARTSTR:
  6688. case OP_ENDSTR:
  6689. case OP_PUSHTAGDELIM:
  6690. case OP_POP:
  6691. case OP_SETDELIM:
  6692. case OP_SETBIGGROUPNUM:
  6693. case OP_CHECKDELIM:
  6694. case OP_CALL:
  6695. case OP_RET:
  6696. case OP_BRANCH:
  6697. return false;
  6698. default:
  6699. return true;
  6700. }
  6701. }
  6702. static size_t stacksize(upb_pbdecoder *d, size_t entries) {
  6703. UPB_UNUSED(d);
  6704. return entries * sizeof(upb_pbdecoder_frame);
  6705. }
  6706. static size_t callstacksize(upb_pbdecoder *d, size_t entries) {
  6707. UPB_UNUSED(d);
  6708. #ifdef UPB_USE_JIT_X64
  6709. if (d->method_->is_native_) {
  6710. /* Each native stack frame needs two pointers, plus we need a few frames for
  6711. * the enter/exit trampolines. */
  6712. size_t ret = entries * sizeof(void*) * 2;
  6713. ret += sizeof(void*) * 10;
  6714. return ret;
  6715. }
  6716. #endif
  6717. return entries * sizeof(uint32_t*);
  6718. }
  6719. static bool in_residual_buf(const upb_pbdecoder *d, const char *p);
  6720. /* It's unfortunate that we have to micro-manage the compiler with
  6721. * UPB_FORCEINLINE and UPB_NOINLINE, especially since this tuning is necessarily
  6722. * specific to one hardware configuration. But empirically on a Core i7,
  6723. * performance increases 30-50% with these annotations. Every instance where
  6724. * these appear, gcc 4.2.1 made the wrong decision and degraded performance in
  6725. * benchmarks. */
  6726. static void seterr(upb_pbdecoder *d, const char *msg) {
  6727. upb_status status = UPB_STATUS_INIT;
  6728. upb_status_seterrmsg(&status, msg);
  6729. upb_env_reporterror(d->env, &status);
  6730. }
  6731. void upb_pbdecoder_seterr(upb_pbdecoder *d, const char *msg) {
  6732. seterr(d, msg);
  6733. }
  6734. /* Buffering ******************************************************************/
  6735. /* We operate on one buffer at a time, which is either the user's buffer passed
  6736. * to our "decode" callback or some residual bytes from the previous buffer. */
  6737. /* How many bytes can be safely read from d->ptr without reading past end-of-buf
  6738. * or past the current delimited end. */
  6739. static size_t curbufleft(const upb_pbdecoder *d) {
  6740. assert(d->data_end >= d->ptr);
  6741. return d->data_end - d->ptr;
  6742. }
  6743. /* How many bytes are available before end-of-buffer. */
  6744. static size_t bufleft(const upb_pbdecoder *d) {
  6745. return d->end - d->ptr;
  6746. }
  6747. /* Overall stream offset of d->ptr. */
  6748. uint64_t offset(const upb_pbdecoder *d) {
  6749. return d->bufstart_ofs + (d->ptr - d->buf);
  6750. }
  6751. /* How many bytes are available before the end of this delimited region. */
  6752. size_t delim_remaining(const upb_pbdecoder *d) {
  6753. return d->top->end_ofs - offset(d);
  6754. }
  6755. /* Advances d->ptr. */
  6756. static void advance(upb_pbdecoder *d, size_t len) {
  6757. assert(curbufleft(d) >= len);
  6758. d->ptr += len;
  6759. }
  6760. static bool in_buf(const char *p, const char *buf, const char *end) {
  6761. return p >= buf && p <= end;
  6762. }
  6763. static bool in_residual_buf(const upb_pbdecoder *d, const char *p) {
  6764. return in_buf(p, d->residual, d->residual_end);
  6765. }
  6766. /* Calculates the delim_end value, which is affected by both the current buffer
  6767. * and the parsing stack, so must be called whenever either is updated. */
  6768. static void set_delim_end(upb_pbdecoder *d) {
  6769. size_t delim_ofs = d->top->end_ofs - d->bufstart_ofs;
  6770. if (delim_ofs <= (size_t)(d->end - d->buf)) {
  6771. d->delim_end = d->buf + delim_ofs;
  6772. d->data_end = d->delim_end;
  6773. } else {
  6774. d->data_end = d->end;
  6775. d->delim_end = NULL;
  6776. }
  6777. }
  6778. static void switchtobuf(upb_pbdecoder *d, const char *buf, const char *end) {
  6779. d->ptr = buf;
  6780. d->buf = buf;
  6781. d->end = end;
  6782. set_delim_end(d);
  6783. }
  6784. static void advancetobuf(upb_pbdecoder *d, const char *buf, size_t len) {
  6785. assert(curbufleft(d) == 0);
  6786. d->bufstart_ofs += (d->end - d->buf);
  6787. switchtobuf(d, buf, buf + len);
  6788. }
  6789. static void checkpoint(upb_pbdecoder *d) {
  6790. /* The assertion here is in the interests of efficiency, not correctness.
  6791. * We are trying to ensure that we don't checkpoint() more often than
  6792. * necessary. */
  6793. assert(d->checkpoint != d->ptr);
  6794. d->checkpoint = d->ptr;
  6795. }
  6796. /* Skips "bytes" bytes in the stream, which may be more than available. If we
  6797. * skip more bytes than are available, we return a long read count to the caller
  6798. * indicating how many bytes can be skipped over before passing actual data
  6799. * again. Skipped bytes can pass a NULL buffer and the decoder guarantees they
  6800. * won't actually be read.
  6801. */
  6802. static int32_t skip(upb_pbdecoder *d, size_t bytes) {
  6803. assert(!in_residual_buf(d, d->ptr) || d->size_param == 0);
  6804. assert(d->skip == 0);
  6805. if (bytes > delim_remaining(d)) {
  6806. seterr(d, "Skipped value extended beyond enclosing submessage.");
  6807. return upb_pbdecoder_suspend(d);
  6808. } else if (bufleft(d) >= bytes) {
  6809. /* Skipped data is all in current buffer, and more is still available. */
  6810. advance(d, bytes);
  6811. d->skip = 0;
  6812. return DECODE_OK;
  6813. } else {
  6814. /* Skipped data extends beyond currently available buffers. */
  6815. d->pc = d->last;
  6816. d->skip = bytes - curbufleft(d);
  6817. d->bufstart_ofs += (d->end - d->buf);
  6818. d->residual_end = d->residual;
  6819. switchtobuf(d, d->residual, d->residual_end);
  6820. return d->size_param + d->skip;
  6821. }
  6822. }
  6823. /* Resumes the decoder from an initial state or from a previous suspend. */
  6824. int32_t upb_pbdecoder_resume(upb_pbdecoder *d, void *p, const char *buf,
  6825. size_t size, const upb_bufhandle *handle) {
  6826. UPB_UNUSED(p); /* Useless; just for the benefit of the JIT. */
  6827. /* d->skip and d->residual_end could probably elegantly be represented
  6828. * as a single variable, to more easily represent this invariant. */
  6829. assert(!(d->skip && d->residual_end > d->residual));
  6830. /* We need to remember the original size_param, so that the value we return
  6831. * is relative to it, even if we do some skipping first. */
  6832. d->size_param = size;
  6833. d->handle = handle;
  6834. /* Have to handle this case specially (ie. not with skip()) because the user
  6835. * is allowed to pass a NULL buffer here, which won't allow us to safely
  6836. * calculate a d->end or use our normal functions like curbufleft(). */
  6837. if (d->skip && d->skip >= size) {
  6838. d->skip -= size;
  6839. d->bufstart_ofs += size;
  6840. buf = &dummy_char;
  6841. size = 0;
  6842. /* We can't just return now, because we might need to execute some ops
  6843. * like CHECKDELIM, which could call some callbacks and pop the stack. */
  6844. }
  6845. /* We need to pretend that this was the actual buffer param, since some of the
  6846. * calculations assume that d->ptr/d->buf is relative to this. */
  6847. d->buf_param = buf;
  6848. if (!buf) {
  6849. /* NULL buf is ok if its entire span is covered by the "skip" above, but
  6850. * by this point we know that "skip" doesn't cover the buffer. */
  6851. seterr(d, "Passed NULL buffer over non-skippable region.");
  6852. return upb_pbdecoder_suspend(d);
  6853. }
  6854. if (d->residual_end > d->residual) {
  6855. /* We have residual bytes from the last buffer. */
  6856. assert(d->ptr == d->residual);
  6857. } else {
  6858. switchtobuf(d, buf, buf + size);
  6859. }
  6860. d->checkpoint = d->ptr;
  6861. /* Handle skips that don't cover the whole buffer (as above). */
  6862. if (d->skip) {
  6863. size_t skip_bytes = d->skip;
  6864. d->skip = 0;
  6865. CHECK_RETURN(skip(d, skip_bytes));
  6866. checkpoint(d);
  6867. }
  6868. /* If we're inside an unknown group, continue to parse unknown values. */
  6869. if (d->top->groupnum < 0) {
  6870. CHECK_RETURN(upb_pbdecoder_skipunknown(d, -1, 0));
  6871. checkpoint(d);
  6872. }
  6873. return DECODE_OK;
  6874. }
  6875. /* Suspends the decoder at the last checkpoint, without saving any residual
  6876. * bytes. If there are any unconsumed bytes, returns a short byte count. */
  6877. size_t upb_pbdecoder_suspend(upb_pbdecoder *d) {
  6878. d->pc = d->last;
  6879. if (d->checkpoint == d->residual) {
  6880. /* Checkpoint was in residual buf; no user bytes were consumed. */
  6881. d->ptr = d->residual;
  6882. return 0;
  6883. } else {
  6884. size_t ret = d->size_param - (d->end - d->checkpoint);
  6885. assert(!in_residual_buf(d, d->checkpoint));
  6886. assert(d->buf == d->buf_param || d->buf == &dummy_char);
  6887. d->bufstart_ofs += (d->checkpoint - d->buf);
  6888. d->residual_end = d->residual;
  6889. switchtobuf(d, d->residual, d->residual_end);
  6890. return ret;
  6891. }
  6892. }
  6893. /* Suspends the decoder at the last checkpoint, and saves any unconsumed
  6894. * bytes in our residual buffer. This is necessary if we need more user
  6895. * bytes to form a complete value, which might not be contiguous in the
  6896. * user's buffers. Always consumes all user bytes. */
  6897. static size_t suspend_save(upb_pbdecoder *d) {
  6898. /* We hit end-of-buffer before we could parse a full value.
  6899. * Save any unconsumed bytes (if any) to the residual buffer. */
  6900. d->pc = d->last;
  6901. if (d->checkpoint == d->residual) {
  6902. /* Checkpoint was in residual buf; append user byte(s) to residual buf. */
  6903. assert((d->residual_end - d->residual) + d->size_param <=
  6904. sizeof(d->residual));
  6905. if (!in_residual_buf(d, d->ptr)) {
  6906. d->bufstart_ofs -= (d->residual_end - d->residual);
  6907. }
  6908. memcpy(d->residual_end, d->buf_param, d->size_param);
  6909. d->residual_end += d->size_param;
  6910. } else {
  6911. /* Checkpoint was in user buf; old residual bytes not needed. */
  6912. size_t save;
  6913. assert(!in_residual_buf(d, d->checkpoint));
  6914. d->ptr = d->checkpoint;
  6915. save = curbufleft(d);
  6916. assert(save <= sizeof(d->residual));
  6917. memcpy(d->residual, d->ptr, save);
  6918. d->residual_end = d->residual + save;
  6919. d->bufstart_ofs = offset(d);
  6920. }
  6921. switchtobuf(d, d->residual, d->residual_end);
  6922. return d->size_param;
  6923. }
  6924. /* Copies the next "bytes" bytes into "buf" and advances the stream.
  6925. * Requires that this many bytes are available in the current buffer. */
  6926. UPB_FORCEINLINE static void consumebytes(upb_pbdecoder *d, void *buf,
  6927. size_t bytes) {
  6928. assert(bytes <= curbufleft(d));
  6929. memcpy(buf, d->ptr, bytes);
  6930. advance(d, bytes);
  6931. }
  6932. /* Slow path for getting the next "bytes" bytes, regardless of whether they are
  6933. * available in the current buffer or not. Returns a status code as described
  6934. * in decoder.int.h. */
  6935. UPB_NOINLINE static int32_t getbytes_slow(upb_pbdecoder *d, void *buf,
  6936. size_t bytes) {
  6937. const size_t avail = curbufleft(d);
  6938. consumebytes(d, buf, avail);
  6939. bytes -= avail;
  6940. assert(bytes > 0);
  6941. if (in_residual_buf(d, d->ptr)) {
  6942. advancetobuf(d, d->buf_param, d->size_param);
  6943. }
  6944. if (curbufleft(d) >= bytes) {
  6945. consumebytes(d, (char *)buf + avail, bytes);
  6946. return DECODE_OK;
  6947. } else if (d->data_end == d->delim_end) {
  6948. seterr(d, "Submessage ended in the middle of a value or group");
  6949. return upb_pbdecoder_suspend(d);
  6950. } else {
  6951. return suspend_save(d);
  6952. }
  6953. }
  6954. /* Gets the next "bytes" bytes, regardless of whether they are available in the
  6955. * current buffer or not. Returns a status code as described in decoder.int.h.
  6956. */
  6957. UPB_FORCEINLINE static int32_t getbytes(upb_pbdecoder *d, void *buf,
  6958. size_t bytes) {
  6959. if (curbufleft(d) >= bytes) {
  6960. /* Buffer has enough data to satisfy. */
  6961. consumebytes(d, buf, bytes);
  6962. return DECODE_OK;
  6963. } else {
  6964. return getbytes_slow(d, buf, bytes);
  6965. }
  6966. }
  6967. UPB_NOINLINE static size_t peekbytes_slow(upb_pbdecoder *d, void *buf,
  6968. size_t bytes) {
  6969. size_t ret = curbufleft(d);
  6970. memcpy(buf, d->ptr, ret);
  6971. if (in_residual_buf(d, d->ptr)) {
  6972. size_t copy = UPB_MIN(bytes - ret, d->size_param);
  6973. memcpy((char *)buf + ret, d->buf_param, copy);
  6974. ret += copy;
  6975. }
  6976. return ret;
  6977. }
  6978. UPB_FORCEINLINE static size_t peekbytes(upb_pbdecoder *d, void *buf,
  6979. size_t bytes) {
  6980. if (curbufleft(d) >= bytes) {
  6981. memcpy(buf, d->ptr, bytes);
  6982. return bytes;
  6983. } else {
  6984. return peekbytes_slow(d, buf, bytes);
  6985. }
  6986. }
  6987. /* Decoding of wire types *****************************************************/
  6988. /* Slow path for decoding a varint from the current buffer position.
  6989. * Returns a status code as described in decoder.int.h. */
  6990. UPB_NOINLINE int32_t upb_pbdecoder_decode_varint_slow(upb_pbdecoder *d,
  6991. uint64_t *u64) {
  6992. uint8_t byte = 0x80;
  6993. int bitpos;
  6994. *u64 = 0;
  6995. for(bitpos = 0; bitpos < 70 && (byte & 0x80); bitpos += 7) {
  6996. CHECK_RETURN(getbytes(d, &byte, 1));
  6997. *u64 |= (uint64_t)(byte & 0x7F) << bitpos;
  6998. }
  6999. if(bitpos == 70 && (byte & 0x80)) {
  7000. seterr(d, kUnterminatedVarint);
  7001. return upb_pbdecoder_suspend(d);
  7002. }
  7003. return DECODE_OK;
  7004. }
  7005. /* Decodes a varint from the current buffer position.
  7006. * Returns a status code as described in decoder.int.h. */
  7007. UPB_FORCEINLINE static int32_t decode_varint(upb_pbdecoder *d, uint64_t *u64) {
  7008. if (curbufleft(d) > 0 && !(*d->ptr & 0x80)) {
  7009. *u64 = *d->ptr;
  7010. advance(d, 1);
  7011. return DECODE_OK;
  7012. } else if (curbufleft(d) >= 10) {
  7013. /* Fast case. */
  7014. upb_decoderet r = upb_vdecode_fast(d->ptr);
  7015. if (r.p == NULL) {
  7016. seterr(d, kUnterminatedVarint);
  7017. return upb_pbdecoder_suspend(d);
  7018. }
  7019. advance(d, r.p - d->ptr);
  7020. *u64 = r.val;
  7021. return DECODE_OK;
  7022. } else {
  7023. /* Slow case -- varint spans buffer seam. */
  7024. return upb_pbdecoder_decode_varint_slow(d, u64);
  7025. }
  7026. }
  7027. /* Decodes a 32-bit varint from the current buffer position.
  7028. * Returns a status code as described in decoder.int.h. */
  7029. UPB_FORCEINLINE static int32_t decode_v32(upb_pbdecoder *d, uint32_t *u32) {
  7030. uint64_t u64;
  7031. int32_t ret = decode_varint(d, &u64);
  7032. if (ret >= 0) return ret;
  7033. if (u64 > UINT32_MAX) {
  7034. seterr(d, "Unterminated 32-bit varint");
  7035. /* TODO(haberman) guarantee that this function return is >= 0 somehow,
  7036. * so we know this path will always be treated as error by our caller.
  7037. * Right now the size_t -> int32_t can overflow and produce negative values.
  7038. */
  7039. *u32 = 0;
  7040. return upb_pbdecoder_suspend(d);
  7041. }
  7042. *u32 = u64;
  7043. return DECODE_OK;
  7044. }
  7045. /* Decodes a fixed32 from the current buffer position.
  7046. * Returns a status code as described in decoder.int.h.
  7047. * TODO: proper byte swapping for big-endian machines. */
  7048. UPB_FORCEINLINE static int32_t decode_fixed32(upb_pbdecoder *d, uint32_t *u32) {
  7049. return getbytes(d, u32, 4);
  7050. }
  7051. /* Decodes a fixed64 from the current buffer position.
  7052. * Returns a status code as described in decoder.int.h.
  7053. * TODO: proper byte swapping for big-endian machines. */
  7054. UPB_FORCEINLINE static int32_t decode_fixed64(upb_pbdecoder *d, uint64_t *u64) {
  7055. return getbytes(d, u64, 8);
  7056. }
  7057. /* Non-static versions of the above functions.
  7058. * These are called by the JIT for fallback paths. */
  7059. int32_t upb_pbdecoder_decode_f32(upb_pbdecoder *d, uint32_t *u32) {
  7060. return decode_fixed32(d, u32);
  7061. }
  7062. int32_t upb_pbdecoder_decode_f64(upb_pbdecoder *d, uint64_t *u64) {
  7063. return decode_fixed64(d, u64);
  7064. }
  7065. static double as_double(uint64_t n) { double d; memcpy(&d, &n, 8); return d; }
  7066. static float as_float(uint32_t n) { float f; memcpy(&f, &n, 4); return f; }
  7067. /* Pushes a frame onto the decoder stack. */
  7068. static bool decoder_push(upb_pbdecoder *d, uint64_t end) {
  7069. upb_pbdecoder_frame *fr = d->top;
  7070. if (end > fr->end_ofs) {
  7071. seterr(d, kPbDecoderSubmessageTooLong);
  7072. return false;
  7073. } else if (fr == d->limit) {
  7074. seterr(d, kPbDecoderStackOverflow);
  7075. return false;
  7076. }
  7077. fr++;
  7078. fr->end_ofs = end;
  7079. fr->dispatch = NULL;
  7080. fr->groupnum = 0;
  7081. d->top = fr;
  7082. return true;
  7083. }
  7084. static bool pushtagdelim(upb_pbdecoder *d, uint32_t arg) {
  7085. /* While we expect to see an "end" tag (either ENDGROUP or a non-sequence
  7086. * field number) prior to hitting any enclosing submessage end, pushing our
  7087. * existing delim end prevents us from continuing to parse values from a
  7088. * corrupt proto that doesn't give us an END tag in time. */
  7089. if (!decoder_push(d, d->top->end_ofs))
  7090. return false;
  7091. d->top->groupnum = arg;
  7092. return true;
  7093. }
  7094. /* Pops a frame from the decoder stack. */
  7095. static void decoder_pop(upb_pbdecoder *d) { d->top--; }
  7096. UPB_NOINLINE int32_t upb_pbdecoder_checktag_slow(upb_pbdecoder *d,
  7097. uint64_t expected) {
  7098. uint64_t data = 0;
  7099. size_t bytes = upb_value_size(expected);
  7100. size_t read = peekbytes(d, &data, bytes);
  7101. if (read == bytes && data == expected) {
  7102. /* Advance past matched bytes. */
  7103. int32_t ok = getbytes(d, &data, read);
  7104. UPB_ASSERT_VAR(ok, ok < 0);
  7105. return DECODE_OK;
  7106. } else if (read < bytes && memcmp(&data, &expected, read) == 0) {
  7107. return suspend_save(d);
  7108. } else {
  7109. return DECODE_MISMATCH;
  7110. }
  7111. }
  7112. int32_t upb_pbdecoder_skipunknown(upb_pbdecoder *d, int32_t fieldnum,
  7113. uint8_t wire_type) {
  7114. if (fieldnum >= 0)
  7115. goto have_tag;
  7116. while (true) {
  7117. uint32_t tag;
  7118. CHECK_RETURN(decode_v32(d, &tag));
  7119. wire_type = tag & 0x7;
  7120. fieldnum = tag >> 3;
  7121. have_tag:
  7122. if (fieldnum == 0) {
  7123. seterr(d, "Saw invalid field number (0)");
  7124. return upb_pbdecoder_suspend(d);
  7125. }
  7126. /* TODO: deliver to unknown field callback. */
  7127. switch (wire_type) {
  7128. case UPB_WIRE_TYPE_32BIT:
  7129. CHECK_RETURN(skip(d, 4));
  7130. break;
  7131. case UPB_WIRE_TYPE_64BIT:
  7132. CHECK_RETURN(skip(d, 8));
  7133. break;
  7134. case UPB_WIRE_TYPE_VARINT: {
  7135. uint64_t u64;
  7136. CHECK_RETURN(decode_varint(d, &u64));
  7137. break;
  7138. }
  7139. case UPB_WIRE_TYPE_DELIMITED: {
  7140. uint32_t len;
  7141. CHECK_RETURN(decode_v32(d, &len));
  7142. CHECK_RETURN(skip(d, len));
  7143. break;
  7144. }
  7145. case UPB_WIRE_TYPE_START_GROUP:
  7146. CHECK_SUSPEND(pushtagdelim(d, -fieldnum));
  7147. break;
  7148. case UPB_WIRE_TYPE_END_GROUP:
  7149. if (fieldnum == -d->top->groupnum) {
  7150. decoder_pop(d);
  7151. } else if (fieldnum == d->top->groupnum) {
  7152. return DECODE_ENDGROUP;
  7153. } else {
  7154. seterr(d, "Unmatched ENDGROUP tag.");
  7155. return upb_pbdecoder_suspend(d);
  7156. }
  7157. break;
  7158. default:
  7159. seterr(d, "Invalid wire type");
  7160. return upb_pbdecoder_suspend(d);
  7161. }
  7162. if (d->top->groupnum >= 0) {
  7163. return DECODE_OK;
  7164. }
  7165. /* Unknown group -- continue looping over unknown fields. */
  7166. checkpoint(d);
  7167. }
  7168. }
  7169. static void goto_endmsg(upb_pbdecoder *d) {
  7170. upb_value v;
  7171. bool found = upb_inttable_lookup32(d->top->dispatch, DISPATCH_ENDMSG, &v);
  7172. UPB_ASSERT_VAR(found, found);
  7173. d->pc = d->top->base + upb_value_getuint64(v);
  7174. }
  7175. /* Parses a tag and jumps to the corresponding bytecode instruction for this
  7176. * field.
  7177. *
  7178. * If the tag is unknown (or the wire type doesn't match), parses the field as
  7179. * unknown. If the tag is a valid ENDGROUP tag, jumps to the bytecode
  7180. * instruction for the end of message. */
  7181. static int32_t dispatch(upb_pbdecoder *d) {
  7182. upb_inttable *dispatch = d->top->dispatch;
  7183. uint32_t tag;
  7184. uint8_t wire_type;
  7185. uint32_t fieldnum;
  7186. upb_value val;
  7187. int32_t retval;
  7188. /* Decode tag. */
  7189. CHECK_RETURN(decode_v32(d, &tag));
  7190. wire_type = tag & 0x7;
  7191. fieldnum = tag >> 3;
  7192. /* Lookup tag. Because of packed/non-packed compatibility, we have to
  7193. * check the wire type against two possibilities. */
  7194. if (fieldnum != DISPATCH_ENDMSG &&
  7195. upb_inttable_lookup32(dispatch, fieldnum, &val)) {
  7196. uint64_t v = upb_value_getuint64(val);
  7197. if (wire_type == (v & 0xff)) {
  7198. d->pc = d->top->base + (v >> 16);
  7199. return DECODE_OK;
  7200. } else if (wire_type == ((v >> 8) & 0xff)) {
  7201. bool found =
  7202. upb_inttable_lookup(dispatch, fieldnum + UPB_MAX_FIELDNUMBER, &val);
  7203. UPB_ASSERT_VAR(found, found);
  7204. d->pc = d->top->base + upb_value_getuint64(val);
  7205. return DECODE_OK;
  7206. }
  7207. }
  7208. /* We have some unknown fields (or ENDGROUP) to parse. The DISPATCH or TAG
  7209. * bytecode that triggered this is preceded by a CHECKDELIM bytecode which
  7210. * we need to back up to, so that when we're done skipping unknown data we
  7211. * can re-check the delimited end. */
  7212. d->last--; /* Necessary if we get suspended */
  7213. d->pc = d->last;
  7214. assert(getop(*d->last) == OP_CHECKDELIM);
  7215. /* Unknown field or ENDGROUP. */
  7216. retval = upb_pbdecoder_skipunknown(d, fieldnum, wire_type);
  7217. CHECK_RETURN(retval);
  7218. if (retval == DECODE_ENDGROUP) {
  7219. goto_endmsg(d);
  7220. return DECODE_OK;
  7221. }
  7222. return DECODE_OK;
  7223. }
  7224. /* Callers know that the stack is more than one deep because the opcodes that
  7225. * call this only occur after PUSH operations. */
  7226. upb_pbdecoder_frame *outer_frame(upb_pbdecoder *d) {
  7227. assert(d->top != d->stack);
  7228. return d->top - 1;
  7229. }
  7230. /* The main decoding loop *****************************************************/
  7231. /* The main decoder VM function. Uses traditional bytecode dispatch loop with a
  7232. * switch() statement. */
  7233. size_t run_decoder_vm(upb_pbdecoder *d, const mgroup *group,
  7234. const upb_bufhandle* handle) {
  7235. #define VMCASE(op, code) \
  7236. case op: { code; if (consumes_input(op)) checkpoint(d); break; }
  7237. #define PRIMITIVE_OP(type, wt, name, convfunc, ctype) \
  7238. VMCASE(OP_PARSE_ ## type, { \
  7239. ctype val; \
  7240. CHECK_RETURN(decode_ ## wt(d, &val)); \
  7241. upb_sink_put ## name(&d->top->sink, arg, (convfunc)(val)); \
  7242. })
  7243. while(1) {
  7244. int32_t instruction;
  7245. opcode op;
  7246. uint32_t arg;
  7247. int32_t longofs;
  7248. d->last = d->pc;
  7249. instruction = *d->pc++;
  7250. op = getop(instruction);
  7251. arg = instruction >> 8;
  7252. longofs = arg;
  7253. assert(d->ptr != d->residual_end);
  7254. UPB_UNUSED(group);
  7255. #ifdef UPB_DUMP_BYTECODE
  7256. fprintf(stderr, "s_ofs=%d buf_ofs=%d data_rem=%d buf_rem=%d delim_rem=%d "
  7257. "%x %s (%d)\n",
  7258. (int)offset(d),
  7259. (int)(d->ptr - d->buf),
  7260. (int)(d->data_end - d->ptr),
  7261. (int)(d->end - d->ptr),
  7262. (int)((d->top->end_ofs - d->bufstart_ofs) - (d->ptr - d->buf)),
  7263. (int)(d->pc - 1 - group->bytecode),
  7264. upb_pbdecoder_getopname(op),
  7265. arg);
  7266. #endif
  7267. switch (op) {
  7268. /* Technically, we are losing data if we see a 32-bit varint that is not
  7269. * properly sign-extended. We could detect this and error about the data
  7270. * loss, but proto2 does not do this, so we pass. */
  7271. PRIMITIVE_OP(INT32, varint, int32, int32_t, uint64_t)
  7272. PRIMITIVE_OP(INT64, varint, int64, int64_t, uint64_t)
  7273. PRIMITIVE_OP(UINT32, varint, uint32, uint32_t, uint64_t)
  7274. PRIMITIVE_OP(UINT64, varint, uint64, uint64_t, uint64_t)
  7275. PRIMITIVE_OP(FIXED32, fixed32, uint32, uint32_t, uint32_t)
  7276. PRIMITIVE_OP(FIXED64, fixed64, uint64, uint64_t, uint64_t)
  7277. PRIMITIVE_OP(SFIXED32, fixed32, int32, int32_t, uint32_t)
  7278. PRIMITIVE_OP(SFIXED64, fixed64, int64, int64_t, uint64_t)
  7279. PRIMITIVE_OP(BOOL, varint, bool, bool, uint64_t)
  7280. PRIMITIVE_OP(DOUBLE, fixed64, double, as_double, uint64_t)
  7281. PRIMITIVE_OP(FLOAT, fixed32, float, as_float, uint32_t)
  7282. PRIMITIVE_OP(SINT32, varint, int32, upb_zzdec_32, uint64_t)
  7283. PRIMITIVE_OP(SINT64, varint, int64, upb_zzdec_64, uint64_t)
  7284. VMCASE(OP_SETDISPATCH,
  7285. d->top->base = d->pc - 1;
  7286. memcpy(&d->top->dispatch, d->pc, sizeof(void*));
  7287. d->pc += sizeof(void*) / sizeof(uint32_t);
  7288. )
  7289. VMCASE(OP_STARTMSG,
  7290. CHECK_SUSPEND(upb_sink_startmsg(&d->top->sink));
  7291. )
  7292. VMCASE(OP_ENDMSG,
  7293. CHECK_SUSPEND(upb_sink_endmsg(&d->top->sink, d->status));
  7294. )
  7295. VMCASE(OP_STARTSEQ,
  7296. upb_pbdecoder_frame *outer = outer_frame(d);
  7297. CHECK_SUSPEND(upb_sink_startseq(&outer->sink, arg, &d->top->sink));
  7298. )
  7299. VMCASE(OP_ENDSEQ,
  7300. CHECK_SUSPEND(upb_sink_endseq(&d->top->sink, arg));
  7301. )
  7302. VMCASE(OP_STARTSUBMSG,
  7303. upb_pbdecoder_frame *outer = outer_frame(d);
  7304. CHECK_SUSPEND(upb_sink_startsubmsg(&outer->sink, arg, &d->top->sink));
  7305. )
  7306. VMCASE(OP_ENDSUBMSG,
  7307. CHECK_SUSPEND(upb_sink_endsubmsg(&d->top->sink, arg));
  7308. )
  7309. VMCASE(OP_STARTSTR,
  7310. uint32_t len = delim_remaining(d);
  7311. upb_pbdecoder_frame *outer = outer_frame(d);
  7312. CHECK_SUSPEND(upb_sink_startstr(&outer->sink, arg, len, &d->top->sink));
  7313. if (len == 0) {
  7314. d->pc++; /* Skip OP_STRING. */
  7315. }
  7316. )
  7317. VMCASE(OP_STRING,
  7318. uint32_t len = curbufleft(d);
  7319. size_t n = upb_sink_putstring(&d->top->sink, arg, d->ptr, len, handle);
  7320. if (n > len) {
  7321. if (n > delim_remaining(d)) {
  7322. seterr(d, "Tried to skip past end of string.");
  7323. return upb_pbdecoder_suspend(d);
  7324. } else {
  7325. int32_t ret = skip(d, n);
  7326. /* This shouldn't return DECODE_OK, because n > len. */
  7327. assert(ret >= 0);
  7328. return ret;
  7329. }
  7330. }
  7331. advance(d, n);
  7332. if (n < len || d->delim_end == NULL) {
  7333. /* We aren't finished with this string yet. */
  7334. d->pc--; /* Repeat OP_STRING. */
  7335. if (n > 0) checkpoint(d);
  7336. return upb_pbdecoder_suspend(d);
  7337. }
  7338. )
  7339. VMCASE(OP_ENDSTR,
  7340. CHECK_SUSPEND(upb_sink_endstr(&d->top->sink, arg));
  7341. )
  7342. VMCASE(OP_PUSHTAGDELIM,
  7343. CHECK_SUSPEND(pushtagdelim(d, arg));
  7344. )
  7345. VMCASE(OP_SETBIGGROUPNUM,
  7346. d->top->groupnum = *d->pc++;
  7347. )
  7348. VMCASE(OP_POP,
  7349. assert(d->top > d->stack);
  7350. decoder_pop(d);
  7351. )
  7352. VMCASE(OP_PUSHLENDELIM,
  7353. uint32_t len;
  7354. CHECK_RETURN(decode_v32(d, &len));
  7355. CHECK_SUSPEND(decoder_push(d, offset(d) + len));
  7356. set_delim_end(d);
  7357. )
  7358. VMCASE(OP_SETDELIM,
  7359. set_delim_end(d);
  7360. )
  7361. VMCASE(OP_CHECKDELIM,
  7362. /* We are guaranteed of this assert because we never allow ourselves to
  7363. * consume bytes beyond data_end, which covers delim_end when non-NULL.
  7364. */
  7365. assert(!(d->delim_end && d->ptr > d->delim_end));
  7366. if (d->ptr == d->delim_end)
  7367. d->pc += longofs;
  7368. )
  7369. VMCASE(OP_CALL,
  7370. d->callstack[d->call_len++] = d->pc;
  7371. d->pc += longofs;
  7372. )
  7373. VMCASE(OP_RET,
  7374. assert(d->call_len > 0);
  7375. d->pc = d->callstack[--d->call_len];
  7376. )
  7377. VMCASE(OP_BRANCH,
  7378. d->pc += longofs;
  7379. )
  7380. VMCASE(OP_TAG1,
  7381. uint8_t expected;
  7382. CHECK_SUSPEND(curbufleft(d) > 0);
  7383. expected = (arg >> 8) & 0xff;
  7384. if (*d->ptr == expected) {
  7385. advance(d, 1);
  7386. } else {
  7387. int8_t shortofs;
  7388. badtag:
  7389. shortofs = arg;
  7390. if (shortofs == LABEL_DISPATCH) {
  7391. CHECK_RETURN(dispatch(d));
  7392. } else {
  7393. d->pc += shortofs;
  7394. break; /* Avoid checkpoint(). */
  7395. }
  7396. }
  7397. )
  7398. VMCASE(OP_TAG2,
  7399. uint16_t expected;
  7400. CHECK_SUSPEND(curbufleft(d) > 0);
  7401. expected = (arg >> 8) & 0xffff;
  7402. if (curbufleft(d) >= 2) {
  7403. uint16_t actual;
  7404. memcpy(&actual, d->ptr, 2);
  7405. if (expected == actual) {
  7406. advance(d, 2);
  7407. } else {
  7408. goto badtag;
  7409. }
  7410. } else {
  7411. int32_t result = upb_pbdecoder_checktag_slow(d, expected);
  7412. if (result == DECODE_MISMATCH) goto badtag;
  7413. if (result >= 0) return result;
  7414. }
  7415. )
  7416. VMCASE(OP_TAGN, {
  7417. uint64_t expected;
  7418. int32_t result;
  7419. memcpy(&expected, d->pc, 8);
  7420. d->pc += 2;
  7421. result = upb_pbdecoder_checktag_slow(d, expected);
  7422. if (result == DECODE_MISMATCH) goto badtag;
  7423. if (result >= 0) return result;
  7424. })
  7425. VMCASE(OP_DISPATCH, {
  7426. CHECK_RETURN(dispatch(d));
  7427. })
  7428. VMCASE(OP_HALT, {
  7429. return d->size_param;
  7430. })
  7431. }
  7432. }
  7433. }
  7434. /* BytesHandler handlers ******************************************************/
  7435. void *upb_pbdecoder_startbc(void *closure, const void *pc, size_t size_hint) {
  7436. upb_pbdecoder *d = closure;
  7437. UPB_UNUSED(size_hint);
  7438. d->top->end_ofs = UINT64_MAX;
  7439. d->bufstart_ofs = 0;
  7440. d->call_len = 1;
  7441. d->callstack[0] = &halt;
  7442. d->pc = pc;
  7443. d->skip = 0;
  7444. return d;
  7445. }
  7446. void *upb_pbdecoder_startjit(void *closure, const void *hd, size_t size_hint) {
  7447. upb_pbdecoder *d = closure;
  7448. UPB_UNUSED(hd);
  7449. UPB_UNUSED(size_hint);
  7450. d->top->end_ofs = UINT64_MAX;
  7451. d->bufstart_ofs = 0;
  7452. d->call_len = 0;
  7453. d->skip = 0;
  7454. return d;
  7455. }
  7456. bool upb_pbdecoder_end(void *closure, const void *handler_data) {
  7457. upb_pbdecoder *d = closure;
  7458. const upb_pbdecodermethod *method = handler_data;
  7459. uint64_t end;
  7460. char dummy;
  7461. if (d->residual_end > d->residual) {
  7462. seterr(d, "Unexpected EOF: decoder still has buffered unparsed data");
  7463. return false;
  7464. }
  7465. if (d->skip) {
  7466. seterr(d, "Unexpected EOF inside skipped data");
  7467. return false;
  7468. }
  7469. if (d->top->end_ofs != UINT64_MAX) {
  7470. seterr(d, "Unexpected EOF inside delimited string");
  7471. return false;
  7472. }
  7473. /* The user's end() call indicates that the message ends here. */
  7474. end = offset(d);
  7475. d->top->end_ofs = end;
  7476. #ifdef UPB_USE_JIT_X64
  7477. if (method->is_native_) {
  7478. const mgroup *group = (const mgroup*)method->group;
  7479. if (d->top != d->stack)
  7480. d->stack->end_ofs = 0;
  7481. group->jit_code(closure, method->code_base.ptr, &dummy, 0, NULL);
  7482. } else
  7483. #endif
  7484. {
  7485. const uint32_t *p = d->pc;
  7486. d->stack->end_ofs = end;
  7487. /* Check the previous bytecode, but guard against beginning. */
  7488. if (p != method->code_base.ptr) p--;
  7489. if (getop(*p) == OP_CHECKDELIM) {
  7490. /* Rewind from OP_TAG* to OP_CHECKDELIM. */
  7491. assert(getop(*d->pc) == OP_TAG1 ||
  7492. getop(*d->pc) == OP_TAG2 ||
  7493. getop(*d->pc) == OP_TAGN ||
  7494. getop(*d->pc) == OP_DISPATCH);
  7495. d->pc = p;
  7496. }
  7497. upb_pbdecoder_decode(closure, handler_data, &dummy, 0, NULL);
  7498. }
  7499. if (d->call_len != 0) {
  7500. seterr(d, "Unexpected EOF inside submessage or group");
  7501. return false;
  7502. }
  7503. return true;
  7504. }
  7505. size_t upb_pbdecoder_decode(void *decoder, const void *group, const char *buf,
  7506. size_t size, const upb_bufhandle *handle) {
  7507. int32_t result = upb_pbdecoder_resume(decoder, NULL, buf, size, handle);
  7508. if (result == DECODE_ENDGROUP) goto_endmsg(decoder);
  7509. CHECK_RETURN(result);
  7510. return run_decoder_vm(decoder, group, handle);
  7511. }
  7512. /* Public API *****************************************************************/
  7513. void upb_pbdecoder_reset(upb_pbdecoder *d) {
  7514. d->top = d->stack;
  7515. d->top->groupnum = 0;
  7516. d->ptr = d->residual;
  7517. d->buf = d->residual;
  7518. d->end = d->residual;
  7519. d->residual_end = d->residual;
  7520. }
  7521. upb_pbdecoder *upb_pbdecoder_create(upb_env *e, const upb_pbdecodermethod *m,
  7522. upb_sink *sink) {
  7523. const size_t default_max_nesting = 64;
  7524. #ifndef NDEBUG
  7525. size_t size_before = upb_env_bytesallocated(e);
  7526. #endif
  7527. upb_pbdecoder *d = upb_env_malloc(e, sizeof(upb_pbdecoder));
  7528. if (!d) return NULL;
  7529. d->method_ = m;
  7530. d->callstack = upb_env_malloc(e, callstacksize(d, default_max_nesting));
  7531. d->stack = upb_env_malloc(e, stacksize(d, default_max_nesting));
  7532. if (!d->stack || !d->callstack) {
  7533. return NULL;
  7534. }
  7535. d->env = e;
  7536. d->limit = d->stack + default_max_nesting - 1;
  7537. d->stack_size = default_max_nesting;
  7538. d->status = NULL;
  7539. upb_pbdecoder_reset(d);
  7540. upb_bytessink_reset(&d->input_, &m->input_handler_, d);
  7541. assert(sink);
  7542. if (d->method_->dest_handlers_) {
  7543. if (sink->handlers != d->method_->dest_handlers_)
  7544. return NULL;
  7545. }
  7546. upb_sink_reset(&d->top->sink, sink->handlers, sink->closure);
  7547. /* If this fails, increase the value in decoder.h. */
  7548. assert(upb_env_bytesallocated(e) - size_before <= UPB_PB_DECODER_SIZE);
  7549. return d;
  7550. }
  7551. uint64_t upb_pbdecoder_bytesparsed(const upb_pbdecoder *d) {
  7552. return offset(d);
  7553. }
  7554. const upb_pbdecodermethod *upb_pbdecoder_method(const upb_pbdecoder *d) {
  7555. return d->method_;
  7556. }
  7557. upb_bytessink *upb_pbdecoder_input(upb_pbdecoder *d) {
  7558. return &d->input_;
  7559. }
  7560. size_t upb_pbdecoder_maxnesting(const upb_pbdecoder *d) {
  7561. return d->stack_size;
  7562. }
  7563. bool upb_pbdecoder_setmaxnesting(upb_pbdecoder *d, size_t max) {
  7564. assert(d->top >= d->stack);
  7565. if (max < (size_t)(d->top - d->stack)) {
  7566. /* Can't set a limit smaller than what we are currently at. */
  7567. return false;
  7568. }
  7569. if (max > d->stack_size) {
  7570. /* Need to reallocate stack and callstack to accommodate. */
  7571. size_t old_size = stacksize(d, d->stack_size);
  7572. size_t new_size = stacksize(d, max);
  7573. void *p = upb_env_realloc(d->env, d->stack, old_size, new_size);
  7574. if (!p) {
  7575. return false;
  7576. }
  7577. d->stack = p;
  7578. old_size = callstacksize(d, d->stack_size);
  7579. new_size = callstacksize(d, max);
  7580. p = upb_env_realloc(d->env, d->callstack, old_size, new_size);
  7581. if (!p) {
  7582. return false;
  7583. }
  7584. d->callstack = p;
  7585. d->stack_size = max;
  7586. }
  7587. d->limit = d->stack + max - 1;
  7588. return true;
  7589. }
  7590. /*
  7591. ** upb::Encoder
  7592. **
  7593. ** Since we are implementing pure handlers (ie. without any out-of-band access
  7594. ** to pre-computed lengths), we have to buffer all submessages before we can
  7595. ** emit even their first byte.
  7596. **
  7597. ** Not knowing the size of submessages also means we can't write a perfect
  7598. ** zero-copy implementation, even with buffering. Lengths are stored as
  7599. ** varints, which means that we don't know how many bytes to reserve for the
  7600. ** length until we know what the length is.
  7601. **
  7602. ** This leaves us with three main choices:
  7603. **
  7604. ** 1. buffer all submessage data in a temporary buffer, then copy it exactly
  7605. ** once into the output buffer.
  7606. **
  7607. ** 2. attempt to buffer data directly into the output buffer, estimating how
  7608. ** many bytes each length will take. When our guesses are wrong, use
  7609. ** memmove() to grow or shrink the allotted space.
  7610. **
  7611. ** 3. buffer directly into the output buffer, allocating a max length
  7612. ** ahead-of-time for each submessage length. If we overallocated, we waste
  7613. ** space, but no memcpy() or memmove() is required. This approach requires
  7614. ** defining a maximum size for submessages and rejecting submessages that
  7615. ** exceed that size.
  7616. **
  7617. ** (2) and (3) have the potential to have better performance, but they are more
  7618. ** complicated and subtle to implement:
  7619. **
  7620. ** (3) requires making an arbitrary choice of the maximum message size; it
  7621. ** wastes space when submessages are shorter than this and fails
  7622. ** completely when they are longer. This makes it more finicky and
  7623. ** requires configuration based on the input. It also makes it impossible
  7624. ** to perfectly match the output of reference encoders that always use the
  7625. ** optimal amount of space for each length.
  7626. **
  7627. ** (2) requires guessing the the size upfront, and if multiple lengths are
  7628. ** guessed wrong the minimum required number of memmove() operations may
  7629. ** be complicated to compute correctly. Implemented properly, it may have
  7630. ** a useful amortized or average cost, but more investigation is required
  7631. ** to determine this and what the optimal algorithm is to achieve it.
  7632. **
  7633. ** (1) makes you always pay for exactly one copy, but its implementation is
  7634. ** the simplest and its performance is predictable.
  7635. **
  7636. ** So for now, we implement (1) only. If we wish to optimize later, we should
  7637. ** be able to do it without affecting users.
  7638. **
  7639. ** The strategy is to buffer the segments of data that do *not* depend on
  7640. ** unknown lengths in one buffer, and keep a separate buffer of segment pointers
  7641. ** and lengths. When the top-level submessage ends, we can go beginning to end,
  7642. ** alternating the writing of lengths with memcpy() of the rest of the data.
  7643. ** At the top level though, no buffering is required.
  7644. */
  7645. #include <stdlib.h>
  7646. /* The output buffer is divided into segments; a segment is a string of data
  7647. * that is "ready to go" -- it does not need any varint lengths inserted into
  7648. * the middle. The seams between segments are where varints will be inserted
  7649. * once they are known.
  7650. *
  7651. * We also use the concept of a "run", which is a range of encoded bytes that
  7652. * occur at a single submessage level. Every segment contains one or more runs.
  7653. *
  7654. * A segment can span messages. Consider:
  7655. *
  7656. * .--Submessage lengths---------.
  7657. * | | |
  7658. * | V V
  7659. * V | |--------------- | |-----------------
  7660. * Submessages: | |-----------------------------------------------
  7661. * Top-level msg: ------------------------------------------------------------
  7662. *
  7663. * Segments: ----- ------------------- -----------------
  7664. * Runs: *---- *--------------*--- *----------------
  7665. * (* marks the start)
  7666. *
  7667. * Note that the top-level menssage is not in any segment because it does not
  7668. * have any length preceding it.
  7669. *
  7670. * A segment is only interrupted when another length needs to be inserted. So
  7671. * observe how the second segment spans both the inner submessage and part of
  7672. * the next enclosing message. */
  7673. typedef struct {
  7674. uint32_t msglen; /* The length to varint-encode before this segment. */
  7675. uint32_t seglen; /* Length of the segment. */
  7676. } upb_pb_encoder_segment;
  7677. struct upb_pb_encoder {
  7678. upb_env *env;
  7679. /* Our input and output. */
  7680. upb_sink input_;
  7681. upb_bytessink *output_;
  7682. /* The "subclosure" -- used as the inner closure as part of the bytessink
  7683. * protocol. */
  7684. void *subc;
  7685. /* The output buffer and limit, and our current write position. "buf"
  7686. * initially points to "initbuf", but is dynamically allocated if we need to
  7687. * grow beyond the initial size. */
  7688. char *buf, *ptr, *limit;
  7689. /* The beginning of the current run, or undefined if we are at the top
  7690. * level. */
  7691. char *runbegin;
  7692. /* The list of segments we are accumulating. */
  7693. upb_pb_encoder_segment *segbuf, *segptr, *seglimit;
  7694. /* The stack of enclosing submessages. Each entry in the stack points to the
  7695. * segment where this submessage's length is being accumulated. */
  7696. int *stack, *top, *stacklimit;
  7697. /* Depth of startmsg/endmsg calls. */
  7698. int depth;
  7699. };
  7700. /* low-level buffering ********************************************************/
  7701. /* Low-level functions for interacting with the output buffer. */
  7702. /* TODO(haberman): handle pushback */
  7703. static void putbuf(upb_pb_encoder *e, const char *buf, size_t len) {
  7704. size_t n = upb_bytessink_putbuf(e->output_, e->subc, buf, len, NULL);
  7705. UPB_ASSERT_VAR(n, n == len);
  7706. }
  7707. static upb_pb_encoder_segment *top(upb_pb_encoder *e) {
  7708. return &e->segbuf[*e->top];
  7709. }
  7710. /* Call to ensure that at least "bytes" bytes are available for writing at
  7711. * e->ptr. Returns false if the bytes could not be allocated. */
  7712. static bool reserve(upb_pb_encoder *e, size_t bytes) {
  7713. if ((size_t)(e->limit - e->ptr) < bytes) {
  7714. /* Grow buffer. */
  7715. char *new_buf;
  7716. size_t needed = bytes + (e->ptr - e->buf);
  7717. size_t old_size = e->limit - e->buf;
  7718. size_t new_size = old_size;
  7719. while (new_size < needed) {
  7720. new_size *= 2;
  7721. }
  7722. new_buf = upb_env_realloc(e->env, e->buf, old_size, new_size);
  7723. if (new_buf == NULL) {
  7724. return false;
  7725. }
  7726. e->ptr = new_buf + (e->ptr - e->buf);
  7727. e->runbegin = new_buf + (e->runbegin - e->buf);
  7728. e->limit = new_buf + new_size;
  7729. e->buf = new_buf;
  7730. }
  7731. return true;
  7732. }
  7733. /* Call when "bytes" bytes have been writte at e->ptr. The caller *must* have
  7734. * previously called reserve() with at least this many bytes. */
  7735. static void encoder_advance(upb_pb_encoder *e, size_t bytes) {
  7736. assert((size_t)(e->limit - e->ptr) >= bytes);
  7737. e->ptr += bytes;
  7738. }
  7739. /* Call when all of the bytes for a handler have been written. Flushes the
  7740. * bytes if possible and necessary, returning false if this failed. */
  7741. static bool commit(upb_pb_encoder *e) {
  7742. if (!e->top) {
  7743. /* We aren't inside a delimited region. Flush our accumulated bytes to
  7744. * the output.
  7745. *
  7746. * TODO(haberman): in the future we may want to delay flushing for
  7747. * efficiency reasons. */
  7748. putbuf(e, e->buf, e->ptr - e->buf);
  7749. e->ptr = e->buf;
  7750. }
  7751. return true;
  7752. }
  7753. /* Writes the given bytes to the buffer, handling reserve/advance. */
  7754. static bool encode_bytes(upb_pb_encoder *e, const void *data, size_t len) {
  7755. if (!reserve(e, len)) {
  7756. return false;
  7757. }
  7758. memcpy(e->ptr, data, len);
  7759. encoder_advance(e, len);
  7760. return true;
  7761. }
  7762. /* Finish the current run by adding the run totals to the segment and message
  7763. * length. */
  7764. static void accumulate(upb_pb_encoder *e) {
  7765. size_t run_len;
  7766. assert(e->ptr >= e->runbegin);
  7767. run_len = e->ptr - e->runbegin;
  7768. e->segptr->seglen += run_len;
  7769. top(e)->msglen += run_len;
  7770. e->runbegin = e->ptr;
  7771. }
  7772. /* Call to indicate the start of delimited region for which the full length is
  7773. * not yet known. All data will be buffered until the length is known.
  7774. * Delimited regions may be nested; their lengths will all be tracked properly. */
  7775. static bool start_delim(upb_pb_encoder *e) {
  7776. if (e->top) {
  7777. /* We are already buffering, advance to the next segment and push it on the
  7778. * stack. */
  7779. accumulate(e);
  7780. if (++e->top == e->stacklimit) {
  7781. /* TODO(haberman): grow stack? */
  7782. return false;
  7783. }
  7784. if (++e->segptr == e->seglimit) {
  7785. /* Grow segment buffer. */
  7786. size_t old_size =
  7787. (e->seglimit - e->segbuf) * sizeof(upb_pb_encoder_segment);
  7788. size_t new_size = old_size * 2;
  7789. upb_pb_encoder_segment *new_buf =
  7790. upb_env_realloc(e->env, e->segbuf, old_size, new_size);
  7791. if (new_buf == NULL) {
  7792. return false;
  7793. }
  7794. e->segptr = new_buf + (e->segptr - e->segbuf);
  7795. e->seglimit = new_buf + (new_size / sizeof(upb_pb_encoder_segment));
  7796. e->segbuf = new_buf;
  7797. }
  7798. } else {
  7799. /* We were previously at the top level, start buffering. */
  7800. e->segptr = e->segbuf;
  7801. e->top = e->stack;
  7802. e->runbegin = e->ptr;
  7803. }
  7804. *e->top = e->segptr - e->segbuf;
  7805. e->segptr->seglen = 0;
  7806. e->segptr->msglen = 0;
  7807. return true;
  7808. }
  7809. /* Call to indicate the end of a delimited region. We now know the length of
  7810. * the delimited region. If we are not nested inside any other delimited
  7811. * regions, we can now emit all of the buffered data we accumulated. */
  7812. static bool end_delim(upb_pb_encoder *e) {
  7813. size_t msglen;
  7814. accumulate(e);
  7815. msglen = top(e)->msglen;
  7816. if (e->top == e->stack) {
  7817. /* All lengths are now available, emit all buffered data. */
  7818. char buf[UPB_PB_VARINT_MAX_LEN];
  7819. upb_pb_encoder_segment *s;
  7820. const char *ptr = e->buf;
  7821. for (s = e->segbuf; s <= e->segptr; s++) {
  7822. size_t lenbytes = upb_vencode64(s->msglen, buf);
  7823. putbuf(e, buf, lenbytes);
  7824. putbuf(e, ptr, s->seglen);
  7825. ptr += s->seglen;
  7826. }
  7827. e->ptr = e->buf;
  7828. e->top = NULL;
  7829. } else {
  7830. /* Need to keep buffering; propagate length info into enclosing
  7831. * submessages. */
  7832. --e->top;
  7833. top(e)->msglen += msglen + upb_varint_size(msglen);
  7834. }
  7835. return true;
  7836. }
  7837. /* tag_t **********************************************************************/
  7838. /* A precomputed (pre-encoded) tag and length. */
  7839. typedef struct {
  7840. uint8_t bytes;
  7841. char tag[7];
  7842. } tag_t;
  7843. /* Allocates a new tag for this field, and sets it in these handlerattr. */
  7844. static void new_tag(upb_handlers *h, const upb_fielddef *f, upb_wiretype_t wt,
  7845. upb_handlerattr *attr) {
  7846. uint32_t n = upb_fielddef_number(f);
  7847. tag_t *tag = malloc(sizeof(tag_t));
  7848. tag->bytes = upb_vencode64((n << 3) | wt, tag->tag);
  7849. upb_handlerattr_init(attr);
  7850. upb_handlerattr_sethandlerdata(attr, tag);
  7851. upb_handlers_addcleanup(h, tag, free);
  7852. }
  7853. static bool encode_tag(upb_pb_encoder *e, const tag_t *tag) {
  7854. return encode_bytes(e, tag->tag, tag->bytes);
  7855. }
  7856. /* encoding of wire types *****************************************************/
  7857. static bool encode_fixed64(upb_pb_encoder *e, uint64_t val) {
  7858. /* TODO(haberman): byte-swap for big endian. */
  7859. return encode_bytes(e, &val, sizeof(uint64_t));
  7860. }
  7861. static bool encode_fixed32(upb_pb_encoder *e, uint32_t val) {
  7862. /* TODO(haberman): byte-swap for big endian. */
  7863. return encode_bytes(e, &val, sizeof(uint32_t));
  7864. }
  7865. static bool encode_varint(upb_pb_encoder *e, uint64_t val) {
  7866. if (!reserve(e, UPB_PB_VARINT_MAX_LEN)) {
  7867. return false;
  7868. }
  7869. encoder_advance(e, upb_vencode64(val, e->ptr));
  7870. return true;
  7871. }
  7872. static uint64_t dbl2uint64(double d) {
  7873. uint64_t ret;
  7874. memcpy(&ret, &d, sizeof(uint64_t));
  7875. return ret;
  7876. }
  7877. static uint32_t flt2uint32(float d) {
  7878. uint32_t ret;
  7879. memcpy(&ret, &d, sizeof(uint32_t));
  7880. return ret;
  7881. }
  7882. /* encoding of proto types ****************************************************/
  7883. static bool startmsg(void *c, const void *hd) {
  7884. upb_pb_encoder *e = c;
  7885. UPB_UNUSED(hd);
  7886. if (e->depth++ == 0) {
  7887. upb_bytessink_start(e->output_, 0, &e->subc);
  7888. }
  7889. return true;
  7890. }
  7891. static bool endmsg(void *c, const void *hd, upb_status *status) {
  7892. upb_pb_encoder *e = c;
  7893. UPB_UNUSED(hd);
  7894. UPB_UNUSED(status);
  7895. if (--e->depth == 0) {
  7896. upb_bytessink_end(e->output_);
  7897. }
  7898. return true;
  7899. }
  7900. static void *encode_startdelimfield(void *c, const void *hd) {
  7901. bool ok = encode_tag(c, hd) && commit(c) && start_delim(c);
  7902. return ok ? c : UPB_BREAK;
  7903. }
  7904. static bool encode_enddelimfield(void *c, const void *hd) {
  7905. UPB_UNUSED(hd);
  7906. return end_delim(c);
  7907. }
  7908. static void *encode_startgroup(void *c, const void *hd) {
  7909. return (encode_tag(c, hd) && commit(c)) ? c : UPB_BREAK;
  7910. }
  7911. static bool encode_endgroup(void *c, const void *hd) {
  7912. return encode_tag(c, hd) && commit(c);
  7913. }
  7914. static void *encode_startstr(void *c, const void *hd, size_t size_hint) {
  7915. UPB_UNUSED(size_hint);
  7916. return encode_startdelimfield(c, hd);
  7917. }
  7918. static size_t encode_strbuf(void *c, const void *hd, const char *buf,
  7919. size_t len, const upb_bufhandle *h) {
  7920. UPB_UNUSED(hd);
  7921. UPB_UNUSED(h);
  7922. return encode_bytes(c, buf, len) ? len : 0;
  7923. }
  7924. #define T(type, ctype, convert, encode) \
  7925. static bool encode_scalar_##type(void *e, const void *hd, ctype val) { \
  7926. return encode_tag(e, hd) && encode(e, (convert)(val)) && commit(e); \
  7927. } \
  7928. static bool encode_packed_##type(void *e, const void *hd, ctype val) { \
  7929. UPB_UNUSED(hd); \
  7930. return encode(e, (convert)(val)); \
  7931. }
  7932. T(double, double, dbl2uint64, encode_fixed64)
  7933. T(float, float, flt2uint32, encode_fixed32)
  7934. T(int64, int64_t, uint64_t, encode_varint)
  7935. T(int32, int32_t, uint32_t, encode_varint)
  7936. T(fixed64, uint64_t, uint64_t, encode_fixed64)
  7937. T(fixed32, uint32_t, uint32_t, encode_fixed32)
  7938. T(bool, bool, bool, encode_varint)
  7939. T(uint32, uint32_t, uint32_t, encode_varint)
  7940. T(uint64, uint64_t, uint64_t, encode_varint)
  7941. T(enum, int32_t, uint32_t, encode_varint)
  7942. T(sfixed32, int32_t, uint32_t, encode_fixed32)
  7943. T(sfixed64, int64_t, uint64_t, encode_fixed64)
  7944. T(sint32, int32_t, upb_zzenc_32, encode_varint)
  7945. T(sint64, int64_t, upb_zzenc_64, encode_varint)
  7946. #undef T
  7947. /* code to build the handlers *************************************************/
  7948. static void newhandlers_callback(const void *closure, upb_handlers *h) {
  7949. const upb_msgdef *m;
  7950. upb_msg_field_iter i;
  7951. UPB_UNUSED(closure);
  7952. upb_handlers_setstartmsg(h, startmsg, NULL);
  7953. upb_handlers_setendmsg(h, endmsg, NULL);
  7954. m = upb_handlers_msgdef(h);
  7955. for(upb_msg_field_begin(&i, m);
  7956. !upb_msg_field_done(&i);
  7957. upb_msg_field_next(&i)) {
  7958. const upb_fielddef *f = upb_msg_iter_field(&i);
  7959. bool packed = upb_fielddef_isseq(f) && upb_fielddef_isprimitive(f) &&
  7960. upb_fielddef_packed(f);
  7961. upb_handlerattr attr;
  7962. upb_wiretype_t wt =
  7963. packed ? UPB_WIRE_TYPE_DELIMITED
  7964. : upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  7965. /* Pre-encode the tag for this field. */
  7966. new_tag(h, f, wt, &attr);
  7967. if (packed) {
  7968. upb_handlers_setstartseq(h, f, encode_startdelimfield, &attr);
  7969. upb_handlers_setendseq(h, f, encode_enddelimfield, &attr);
  7970. }
  7971. #define T(upper, lower, upbtype) \
  7972. case UPB_DESCRIPTOR_TYPE_##upper: \
  7973. if (packed) { \
  7974. upb_handlers_set##upbtype(h, f, encode_packed_##lower, &attr); \
  7975. } else { \
  7976. upb_handlers_set##upbtype(h, f, encode_scalar_##lower, &attr); \
  7977. } \
  7978. break;
  7979. switch (upb_fielddef_descriptortype(f)) {
  7980. T(DOUBLE, double, double);
  7981. T(FLOAT, float, float);
  7982. T(INT64, int64, int64);
  7983. T(INT32, int32, int32);
  7984. T(FIXED64, fixed64, uint64);
  7985. T(FIXED32, fixed32, uint32);
  7986. T(BOOL, bool, bool);
  7987. T(UINT32, uint32, uint32);
  7988. T(UINT64, uint64, uint64);
  7989. T(ENUM, enum, int32);
  7990. T(SFIXED32, sfixed32, int32);
  7991. T(SFIXED64, sfixed64, int64);
  7992. T(SINT32, sint32, int32);
  7993. T(SINT64, sint64, int64);
  7994. case UPB_DESCRIPTOR_TYPE_STRING:
  7995. case UPB_DESCRIPTOR_TYPE_BYTES:
  7996. upb_handlers_setstartstr(h, f, encode_startstr, &attr);
  7997. upb_handlers_setendstr(h, f, encode_enddelimfield, &attr);
  7998. upb_handlers_setstring(h, f, encode_strbuf, &attr);
  7999. break;
  8000. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  8001. upb_handlers_setstartsubmsg(h, f, encode_startdelimfield, &attr);
  8002. upb_handlers_setendsubmsg(h, f, encode_enddelimfield, &attr);
  8003. break;
  8004. case UPB_DESCRIPTOR_TYPE_GROUP: {
  8005. /* Endgroup takes a different tag (wire_type = END_GROUP). */
  8006. upb_handlerattr attr2;
  8007. new_tag(h, f, UPB_WIRE_TYPE_END_GROUP, &attr2);
  8008. upb_handlers_setstartsubmsg(h, f, encode_startgroup, &attr);
  8009. upb_handlers_setendsubmsg(h, f, encode_endgroup, &attr2);
  8010. upb_handlerattr_uninit(&attr2);
  8011. break;
  8012. }
  8013. }
  8014. #undef T
  8015. upb_handlerattr_uninit(&attr);
  8016. }
  8017. }
  8018. void upb_pb_encoder_reset(upb_pb_encoder *e) {
  8019. e->segptr = NULL;
  8020. e->top = NULL;
  8021. e->depth = 0;
  8022. }
  8023. /* public API *****************************************************************/
  8024. const upb_handlers *upb_pb_encoder_newhandlers(const upb_msgdef *m,
  8025. const void *owner) {
  8026. return upb_handlers_newfrozen(m, owner, newhandlers_callback, NULL);
  8027. }
  8028. upb_pb_encoder *upb_pb_encoder_create(upb_env *env, const upb_handlers *h,
  8029. upb_bytessink *output) {
  8030. const size_t initial_bufsize = 256;
  8031. const size_t initial_segbufsize = 16;
  8032. /* TODO(haberman): make this configurable. */
  8033. const size_t stack_size = 64;
  8034. #ifndef NDEBUG
  8035. const size_t size_before = upb_env_bytesallocated(env);
  8036. #endif
  8037. upb_pb_encoder *e = upb_env_malloc(env, sizeof(upb_pb_encoder));
  8038. if (!e) return NULL;
  8039. e->buf = upb_env_malloc(env, initial_bufsize);
  8040. e->segbuf = upb_env_malloc(env, initial_segbufsize * sizeof(*e->segbuf));
  8041. e->stack = upb_env_malloc(env, stack_size * sizeof(*e->stack));
  8042. if (!e->buf || !e->segbuf || !e->stack) {
  8043. return NULL;
  8044. }
  8045. e->limit = e->buf + initial_bufsize;
  8046. e->seglimit = e->segbuf + initial_segbufsize;
  8047. e->stacklimit = e->stack + stack_size;
  8048. upb_pb_encoder_reset(e);
  8049. upb_sink_reset(&e->input_, h, e);
  8050. e->env = env;
  8051. e->output_ = output;
  8052. e->subc = output->closure;
  8053. e->ptr = e->buf;
  8054. /* If this fails, increase the value in encoder.h. */
  8055. assert(upb_env_bytesallocated(env) - size_before <= UPB_PB_ENCODER_SIZE);
  8056. return e;
  8057. }
  8058. upb_sink *upb_pb_encoder_input(upb_pb_encoder *e) { return &e->input_; }
  8059. #include <stdio.h>
  8060. #include <stdlib.h>
  8061. #include <string.h>
  8062. upb_def **upb_load_defs_from_descriptor(const char *str, size_t len, int *n,
  8063. void *owner, upb_status *status) {
  8064. /* Create handlers. */
  8065. const upb_pbdecodermethod *decoder_m;
  8066. const upb_handlers *reader_h = upb_descreader_newhandlers(&reader_h);
  8067. upb_env env;
  8068. upb_pbdecodermethodopts opts;
  8069. upb_pbdecoder *decoder;
  8070. upb_descreader *reader;
  8071. bool ok;
  8072. upb_def **ret = NULL;
  8073. upb_def **defs;
  8074. upb_pbdecodermethodopts_init(&opts, reader_h);
  8075. decoder_m = upb_pbdecodermethod_new(&opts, &decoder_m);
  8076. upb_env_init(&env);
  8077. upb_env_reporterrorsto(&env, status);
  8078. reader = upb_descreader_create(&env, reader_h);
  8079. decoder = upb_pbdecoder_create(&env, decoder_m, upb_descreader_input(reader));
  8080. /* Push input data. */
  8081. ok = upb_bufsrc_putbuf(str, len, upb_pbdecoder_input(decoder));
  8082. if (!ok) goto cleanup;
  8083. defs = upb_descreader_getdefs(reader, owner, n);
  8084. ret = malloc(sizeof(upb_def*) * (*n));
  8085. memcpy(ret, defs, sizeof(upb_def*) * (*n));
  8086. cleanup:
  8087. upb_env_uninit(&env);
  8088. upb_handlers_unref(reader_h, &reader_h);
  8089. upb_pbdecodermethod_unref(decoder_m, &decoder_m);
  8090. return ret;
  8091. }
  8092. bool upb_load_descriptor_into_symtab(upb_symtab *s, const char *str, size_t len,
  8093. upb_status *status) {
  8094. int n;
  8095. bool success;
  8096. upb_def **defs = upb_load_defs_from_descriptor(str, len, &n, &defs, status);
  8097. if (!defs) return false;
  8098. success = upb_symtab_add(s, defs, n, &defs, status);
  8099. free(defs);
  8100. return success;
  8101. }
  8102. char *upb_readfile(const char *filename, size_t *len) {
  8103. long size;
  8104. char *buf;
  8105. FILE *f = fopen(filename, "rb");
  8106. if(!f) return NULL;
  8107. if(fseek(f, 0, SEEK_END) != 0) goto error;
  8108. size = ftell(f);
  8109. if(size < 0) goto error;
  8110. if(fseek(f, 0, SEEK_SET) != 0) goto error;
  8111. buf = malloc(size + 1);
  8112. if(size && fread(buf, size, 1, f) != 1) goto error;
  8113. fclose(f);
  8114. if (len) *len = size;
  8115. return buf;
  8116. error:
  8117. fclose(f);
  8118. return NULL;
  8119. }
  8120. bool upb_load_descriptor_file_into_symtab(upb_symtab *symtab, const char *fname,
  8121. upb_status *status) {
  8122. size_t len;
  8123. bool success;
  8124. char *data = upb_readfile(fname, &len);
  8125. if (!data) {
  8126. if (status) upb_status_seterrf(status, "Couldn't read file: %s", fname);
  8127. return false;
  8128. }
  8129. success = upb_load_descriptor_into_symtab(symtab, data, len, status);
  8130. free(data);
  8131. return success;
  8132. }
  8133. /*
  8134. * upb::pb::TextPrinter
  8135. *
  8136. * OPT: This is not optimized at all. It uses printf() which parses the format
  8137. * string every time, and it allocates memory for every put.
  8138. */
  8139. #include <ctype.h>
  8140. #include <float.h>
  8141. #include <inttypes.h>
  8142. #include <stdarg.h>
  8143. #include <stdio.h>
  8144. #include <stdlib.h>
  8145. #include <string.h>
  8146. struct upb_textprinter {
  8147. upb_sink input_;
  8148. upb_bytessink *output_;
  8149. int indent_depth_;
  8150. bool single_line_;
  8151. void *subc;
  8152. };
  8153. #define CHECK(x) if ((x) < 0) goto err;
  8154. static const char *shortname(const char *longname) {
  8155. const char *last = strrchr(longname, '.');
  8156. return last ? last + 1 : longname;
  8157. }
  8158. static int indent(upb_textprinter *p) {
  8159. int i;
  8160. if (!p->single_line_)
  8161. for (i = 0; i < p->indent_depth_; i++)
  8162. upb_bytessink_putbuf(p->output_, p->subc, " ", 2, NULL);
  8163. return 0;
  8164. }
  8165. static int endfield(upb_textprinter *p) {
  8166. const char ch = (p->single_line_ ? ' ' : '\n');
  8167. upb_bytessink_putbuf(p->output_, p->subc, &ch, 1, NULL);
  8168. return 0;
  8169. }
  8170. static int putescaped(upb_textprinter *p, const char *buf, size_t len,
  8171. bool preserve_utf8) {
  8172. /* Based on CEscapeInternal() from Google's protobuf release. */
  8173. char dstbuf[4096], *dst = dstbuf, *dstend = dstbuf + sizeof(dstbuf);
  8174. const char *end = buf + len;
  8175. /* I think hex is prettier and more useful, but proto2 uses octal; should
  8176. * investigate whether it can parse hex also. */
  8177. const bool use_hex = false;
  8178. bool last_hex_escape = false; /* true if last output char was \xNN */
  8179. for (; buf < end; buf++) {
  8180. bool is_hex_escape;
  8181. if (dstend - dst < 4) {
  8182. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  8183. dst = dstbuf;
  8184. }
  8185. is_hex_escape = false;
  8186. switch (*buf) {
  8187. case '\n': *(dst++) = '\\'; *(dst++) = 'n'; break;
  8188. case '\r': *(dst++) = '\\'; *(dst++) = 'r'; break;
  8189. case '\t': *(dst++) = '\\'; *(dst++) = 't'; break;
  8190. case '\"': *(dst++) = '\\'; *(dst++) = '\"'; break;
  8191. case '\'': *(dst++) = '\\'; *(dst++) = '\''; break;
  8192. case '\\': *(dst++) = '\\'; *(dst++) = '\\'; break;
  8193. default:
  8194. /* Note that if we emit \xNN and the buf character after that is a hex
  8195. * digit then that digit must be escaped too to prevent it being
  8196. * interpreted as part of the character code by C. */
  8197. if ((!preserve_utf8 || (uint8_t)*buf < 0x80) &&
  8198. (!isprint(*buf) || (last_hex_escape && isxdigit(*buf)))) {
  8199. sprintf(dst, (use_hex ? "\\x%02x" : "\\%03o"), (uint8_t)*buf);
  8200. is_hex_escape = use_hex;
  8201. dst += 4;
  8202. } else {
  8203. *(dst++) = *buf; break;
  8204. }
  8205. }
  8206. last_hex_escape = is_hex_escape;
  8207. }
  8208. /* Flush remaining data. */
  8209. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  8210. return 0;
  8211. }
  8212. bool putf(upb_textprinter *p, const char *fmt, ...) {
  8213. va_list args;
  8214. va_list args_copy;
  8215. char *str;
  8216. int written;
  8217. int len;
  8218. bool ok;
  8219. va_start(args, fmt);
  8220. /* Run once to get the length of the string. */
  8221. _upb_va_copy(args_copy, args);
  8222. len = _upb_vsnprintf(NULL, 0, fmt, args_copy);
  8223. va_end(args_copy);
  8224. /* + 1 for NULL terminator (vsprintf() requires it even if we don't). */
  8225. str = malloc(len + 1);
  8226. if (!str) return false;
  8227. written = vsprintf(str, fmt, args);
  8228. va_end(args);
  8229. UPB_ASSERT_VAR(written, written == len);
  8230. ok = upb_bytessink_putbuf(p->output_, p->subc, str, len, NULL);
  8231. free(str);
  8232. return ok;
  8233. }
  8234. /* handlers *******************************************************************/
  8235. static bool textprinter_startmsg(void *c, const void *hd) {
  8236. upb_textprinter *p = c;
  8237. UPB_UNUSED(hd);
  8238. if (p->indent_depth_ == 0) {
  8239. upb_bytessink_start(p->output_, 0, &p->subc);
  8240. }
  8241. return true;
  8242. }
  8243. static bool textprinter_endmsg(void *c, const void *hd, upb_status *s) {
  8244. upb_textprinter *p = c;
  8245. UPB_UNUSED(hd);
  8246. UPB_UNUSED(s);
  8247. if (p->indent_depth_ == 0) {
  8248. upb_bytessink_end(p->output_);
  8249. }
  8250. return true;
  8251. }
  8252. #define TYPE(name, ctype, fmt) \
  8253. static bool textprinter_put ## name(void *closure, const void *handler_data, \
  8254. ctype val) { \
  8255. upb_textprinter *p = closure; \
  8256. const upb_fielddef *f = handler_data; \
  8257. CHECK(indent(p)); \
  8258. putf(p, "%s: " fmt, upb_fielddef_name(f), val); \
  8259. CHECK(endfield(p)); \
  8260. return true; \
  8261. err: \
  8262. return false; \
  8263. }
  8264. static bool textprinter_putbool(void *closure, const void *handler_data,
  8265. bool val) {
  8266. upb_textprinter *p = closure;
  8267. const upb_fielddef *f = handler_data;
  8268. CHECK(indent(p));
  8269. putf(p, "%s: %s", upb_fielddef_name(f), val ? "true" : "false");
  8270. CHECK(endfield(p));
  8271. return true;
  8272. err:
  8273. return false;
  8274. }
  8275. #define STRINGIFY_HELPER(x) #x
  8276. #define STRINGIFY_MACROVAL(x) STRINGIFY_HELPER(x)
  8277. TYPE(int32, int32_t, "%" PRId32)
  8278. TYPE(int64, int64_t, "%" PRId64)
  8279. TYPE(uint32, uint32_t, "%" PRIu32)
  8280. TYPE(uint64, uint64_t, "%" PRIu64)
  8281. TYPE(float, float, "%." STRINGIFY_MACROVAL(FLT_DIG) "g")
  8282. TYPE(double, double, "%." STRINGIFY_MACROVAL(DBL_DIG) "g")
  8283. #undef TYPE
  8284. /* Output a symbolic value from the enum if found, else just print as int32. */
  8285. static bool textprinter_putenum(void *closure, const void *handler_data,
  8286. int32_t val) {
  8287. upb_textprinter *p = closure;
  8288. const upb_fielddef *f = handler_data;
  8289. const upb_enumdef *enum_def = upb_downcast_enumdef(upb_fielddef_subdef(f));
  8290. const char *label = upb_enumdef_iton(enum_def, val);
  8291. if (label) {
  8292. indent(p);
  8293. putf(p, "%s: %s", upb_fielddef_name(f), label);
  8294. endfield(p);
  8295. } else {
  8296. if (!textprinter_putint32(closure, handler_data, val))
  8297. return false;
  8298. }
  8299. return true;
  8300. }
  8301. static void *textprinter_startstr(void *closure, const void *handler_data,
  8302. size_t size_hint) {
  8303. upb_textprinter *p = closure;
  8304. const upb_fielddef *f = handler_data;
  8305. UPB_UNUSED(size_hint);
  8306. indent(p);
  8307. putf(p, "%s: \"", upb_fielddef_name(f));
  8308. return p;
  8309. }
  8310. static bool textprinter_endstr(void *closure, const void *handler_data) {
  8311. upb_textprinter *p = closure;
  8312. UPB_UNUSED(handler_data);
  8313. putf(p, "\"");
  8314. endfield(p);
  8315. return true;
  8316. }
  8317. static size_t textprinter_putstr(void *closure, const void *hd, const char *buf,
  8318. size_t len, const upb_bufhandle *handle) {
  8319. upb_textprinter *p = closure;
  8320. const upb_fielddef *f = hd;
  8321. UPB_UNUSED(handle);
  8322. CHECK(putescaped(p, buf, len, upb_fielddef_type(f) == UPB_TYPE_STRING));
  8323. return len;
  8324. err:
  8325. return 0;
  8326. }
  8327. static void *textprinter_startsubmsg(void *closure, const void *handler_data) {
  8328. upb_textprinter *p = closure;
  8329. const char *name = handler_data;
  8330. CHECK(indent(p));
  8331. putf(p, "%s {%c", name, p->single_line_ ? ' ' : '\n');
  8332. p->indent_depth_++;
  8333. return p;
  8334. err:
  8335. return UPB_BREAK;
  8336. }
  8337. static bool textprinter_endsubmsg(void *closure, const void *handler_data) {
  8338. upb_textprinter *p = closure;
  8339. UPB_UNUSED(handler_data);
  8340. p->indent_depth_--;
  8341. CHECK(indent(p));
  8342. upb_bytessink_putbuf(p->output_, p->subc, "}", 1, NULL);
  8343. CHECK(endfield(p));
  8344. return true;
  8345. err:
  8346. return false;
  8347. }
  8348. static void onmreg(const void *c, upb_handlers *h) {
  8349. const upb_msgdef *m = upb_handlers_msgdef(h);
  8350. upb_msg_field_iter i;
  8351. UPB_UNUSED(c);
  8352. upb_handlers_setstartmsg(h, textprinter_startmsg, NULL);
  8353. upb_handlers_setendmsg(h, textprinter_endmsg, NULL);
  8354. for(upb_msg_field_begin(&i, m);
  8355. !upb_msg_field_done(&i);
  8356. upb_msg_field_next(&i)) {
  8357. upb_fielddef *f = upb_msg_iter_field(&i);
  8358. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  8359. upb_handlerattr_sethandlerdata(&attr, f);
  8360. switch (upb_fielddef_type(f)) {
  8361. case UPB_TYPE_INT32:
  8362. upb_handlers_setint32(h, f, textprinter_putint32, &attr);
  8363. break;
  8364. case UPB_TYPE_INT64:
  8365. upb_handlers_setint64(h, f, textprinter_putint64, &attr);
  8366. break;
  8367. case UPB_TYPE_UINT32:
  8368. upb_handlers_setuint32(h, f, textprinter_putuint32, &attr);
  8369. break;
  8370. case UPB_TYPE_UINT64:
  8371. upb_handlers_setuint64(h, f, textprinter_putuint64, &attr);
  8372. break;
  8373. case UPB_TYPE_FLOAT:
  8374. upb_handlers_setfloat(h, f, textprinter_putfloat, &attr);
  8375. break;
  8376. case UPB_TYPE_DOUBLE:
  8377. upb_handlers_setdouble(h, f, textprinter_putdouble, &attr);
  8378. break;
  8379. case UPB_TYPE_BOOL:
  8380. upb_handlers_setbool(h, f, textprinter_putbool, &attr);
  8381. break;
  8382. case UPB_TYPE_STRING:
  8383. case UPB_TYPE_BYTES:
  8384. upb_handlers_setstartstr(h, f, textprinter_startstr, &attr);
  8385. upb_handlers_setstring(h, f, textprinter_putstr, &attr);
  8386. upb_handlers_setendstr(h, f, textprinter_endstr, &attr);
  8387. break;
  8388. case UPB_TYPE_MESSAGE: {
  8389. const char *name =
  8390. upb_fielddef_istagdelim(f)
  8391. ? shortname(upb_msgdef_fullname(upb_fielddef_msgsubdef(f)))
  8392. : upb_fielddef_name(f);
  8393. upb_handlerattr_sethandlerdata(&attr, name);
  8394. upb_handlers_setstartsubmsg(h, f, textprinter_startsubmsg, &attr);
  8395. upb_handlers_setendsubmsg(h, f, textprinter_endsubmsg, &attr);
  8396. break;
  8397. }
  8398. case UPB_TYPE_ENUM:
  8399. upb_handlers_setint32(h, f, textprinter_putenum, &attr);
  8400. break;
  8401. }
  8402. }
  8403. }
  8404. static void textprinter_reset(upb_textprinter *p, bool single_line) {
  8405. p->single_line_ = single_line;
  8406. p->indent_depth_ = 0;
  8407. }
  8408. /* Public API *****************************************************************/
  8409. upb_textprinter *upb_textprinter_create(upb_env *env, const upb_handlers *h,
  8410. upb_bytessink *output) {
  8411. upb_textprinter *p = upb_env_malloc(env, sizeof(upb_textprinter));
  8412. if (!p) return NULL;
  8413. p->output_ = output;
  8414. upb_sink_reset(&p->input_, h, p);
  8415. textprinter_reset(p, false);
  8416. return p;
  8417. }
  8418. const upb_handlers *upb_textprinter_newhandlers(const upb_msgdef *m,
  8419. const void *owner) {
  8420. return upb_handlers_newfrozen(m, owner, &onmreg, NULL);
  8421. }
  8422. upb_sink *upb_textprinter_input(upb_textprinter *p) { return &p->input_; }
  8423. void upb_textprinter_setsingleline(upb_textprinter *p, bool single_line) {
  8424. p->single_line_ = single_line;
  8425. }
  8426. /* Index is descriptor type. */
  8427. const uint8_t upb_pb_native_wire_types[] = {
  8428. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  8429. UPB_WIRE_TYPE_64BIT, /* DOUBLE */
  8430. UPB_WIRE_TYPE_32BIT, /* FLOAT */
  8431. UPB_WIRE_TYPE_VARINT, /* INT64 */
  8432. UPB_WIRE_TYPE_VARINT, /* UINT64 */
  8433. UPB_WIRE_TYPE_VARINT, /* INT32 */
  8434. UPB_WIRE_TYPE_64BIT, /* FIXED64 */
  8435. UPB_WIRE_TYPE_32BIT, /* FIXED32 */
  8436. UPB_WIRE_TYPE_VARINT, /* BOOL */
  8437. UPB_WIRE_TYPE_DELIMITED, /* STRING */
  8438. UPB_WIRE_TYPE_START_GROUP, /* GROUP */
  8439. UPB_WIRE_TYPE_DELIMITED, /* MESSAGE */
  8440. UPB_WIRE_TYPE_DELIMITED, /* BYTES */
  8441. UPB_WIRE_TYPE_VARINT, /* UINT32 */
  8442. UPB_WIRE_TYPE_VARINT, /* ENUM */
  8443. UPB_WIRE_TYPE_32BIT, /* SFIXED32 */
  8444. UPB_WIRE_TYPE_64BIT, /* SFIXED64 */
  8445. UPB_WIRE_TYPE_VARINT, /* SINT32 */
  8446. UPB_WIRE_TYPE_VARINT, /* SINT64 */
  8447. };
  8448. /* A basic branch-based decoder, uses 32-bit values to get good performance
  8449. * on 32-bit architectures (but performs well on 64-bits also).
  8450. * This scheme comes from the original Google Protobuf implementation
  8451. * (proto2). */
  8452. upb_decoderet upb_vdecode_max8_branch32(upb_decoderet r) {
  8453. upb_decoderet err = {NULL, 0};
  8454. const char *p = r.p;
  8455. uint32_t low = (uint32_t)r.val;
  8456. uint32_t high = 0;
  8457. uint32_t b;
  8458. b = *(p++); low |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  8459. b = *(p++); low |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  8460. b = *(p++); low |= (b & 0x7fU) << 28;
  8461. high = (b & 0x7fU) >> 4; if (!(b & 0x80)) goto done;
  8462. b = *(p++); high |= (b & 0x7fU) << 3; if (!(b & 0x80)) goto done;
  8463. b = *(p++); high |= (b & 0x7fU) << 10; if (!(b & 0x80)) goto done;
  8464. b = *(p++); high |= (b & 0x7fU) << 17; if (!(b & 0x80)) goto done;
  8465. b = *(p++); high |= (b & 0x7fU) << 24; if (!(b & 0x80)) goto done;
  8466. b = *(p++); high |= (b & 0x7fU) << 31; if (!(b & 0x80)) goto done;
  8467. return err;
  8468. done:
  8469. r.val = ((uint64_t)high << 32) | low;
  8470. r.p = p;
  8471. return r;
  8472. }
  8473. /* Like the previous, but uses 64-bit values. */
  8474. upb_decoderet upb_vdecode_max8_branch64(upb_decoderet r) {
  8475. const char *p = r.p;
  8476. uint64_t val = r.val;
  8477. uint64_t b;
  8478. upb_decoderet err = {NULL, 0};
  8479. b = *(p++); val |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  8480. b = *(p++); val |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  8481. b = *(p++); val |= (b & 0x7fU) << 28; if (!(b & 0x80)) goto done;
  8482. b = *(p++); val |= (b & 0x7fU) << 35; if (!(b & 0x80)) goto done;
  8483. b = *(p++); val |= (b & 0x7fU) << 42; if (!(b & 0x80)) goto done;
  8484. b = *(p++); val |= (b & 0x7fU) << 49; if (!(b & 0x80)) goto done;
  8485. b = *(p++); val |= (b & 0x7fU) << 56; if (!(b & 0x80)) goto done;
  8486. b = *(p++); val |= (b & 0x7fU) << 63; if (!(b & 0x80)) goto done;
  8487. return err;
  8488. done:
  8489. r.val = val;
  8490. r.p = p;
  8491. return r;
  8492. }
  8493. /* Given an encoded varint v, returns an integer with a single bit set that
  8494. * indicates the end of the varint. Subtracting one from this value will
  8495. * yield a mask that leaves only bits that are part of the varint. Returns
  8496. * 0 if the varint is unterminated. */
  8497. static uint64_t upb_get_vstopbit(uint64_t v) {
  8498. uint64_t cbits = v | 0x7f7f7f7f7f7f7f7fULL;
  8499. return ~cbits & (cbits+1);
  8500. }
  8501. /* A branchless decoder. Credit to Pascal Massimino for the bit-twiddling. */
  8502. upb_decoderet upb_vdecode_max8_massimino(upb_decoderet r) {
  8503. uint64_t b;
  8504. uint64_t stop_bit;
  8505. upb_decoderet my_r;
  8506. memcpy(&b, r.p, sizeof(b));
  8507. stop_bit = upb_get_vstopbit(b);
  8508. b = (b & 0x7f7f7f7f7f7f7f7fULL) & (stop_bit - 1);
  8509. b += b & 0x007f007f007f007fULL;
  8510. b += 3 * (b & 0x0000ffff0000ffffULL);
  8511. b += 15 * (b & 0x00000000ffffffffULL);
  8512. if (stop_bit == 0) {
  8513. /* Error: unterminated varint. */
  8514. upb_decoderet err_r = {(void*)0, 0};
  8515. return err_r;
  8516. }
  8517. my_r = upb_decoderet_make(r.p + ((__builtin_ctzll(stop_bit) + 1) / 8),
  8518. r.val | (b << 7));
  8519. return my_r;
  8520. }
  8521. /* A branchless decoder. Credit to Daniel Wright for the bit-twiddling. */
  8522. upb_decoderet upb_vdecode_max8_wright(upb_decoderet r) {
  8523. uint64_t b;
  8524. uint64_t stop_bit;
  8525. upb_decoderet my_r;
  8526. memcpy(&b, r.p, sizeof(b));
  8527. stop_bit = upb_get_vstopbit(b);
  8528. b &= (stop_bit - 1);
  8529. b = ((b & 0x7f007f007f007f00ULL) >> 1) | (b & 0x007f007f007f007fULL);
  8530. b = ((b & 0xffff0000ffff0000ULL) >> 2) | (b & 0x0000ffff0000ffffULL);
  8531. b = ((b & 0xffffffff00000000ULL) >> 4) | (b & 0x00000000ffffffffULL);
  8532. if (stop_bit == 0) {
  8533. /* Error: unterminated varint. */
  8534. upb_decoderet err_r = {(void*)0, 0};
  8535. return err_r;
  8536. }
  8537. my_r = upb_decoderet_make(r.p + ((__builtin_ctzll(stop_bit) + 1) / 8),
  8538. r.val | (b << 14));
  8539. return my_r;
  8540. }
  8541. #line 1 "upb/json/parser.rl"
  8542. /*
  8543. ** upb::json::Parser (upb_json_parser)
  8544. **
  8545. ** A parser that uses the Ragel State Machine Compiler to generate
  8546. ** the finite automata.
  8547. **
  8548. ** Ragel only natively handles regular languages, but we can manually
  8549. ** program it a bit to handle context-free languages like JSON, by using
  8550. ** the "fcall" and "fret" constructs.
  8551. **
  8552. ** This parser can handle the basics, but needs several things to be fleshed
  8553. ** out:
  8554. **
  8555. ** - handling of unicode escape sequences (including high surrogate pairs).
  8556. ** - properly check and report errors for unknown fields, stack overflow,
  8557. ** improper array nesting (or lack of nesting).
  8558. ** - handling of base64 sequences with padding characters.
  8559. ** - handling of push-back (non-success returns from sink functions).
  8560. ** - handling of keys/escape-sequences/etc that span input buffers.
  8561. */
  8562. #include <stdio.h>
  8563. #include <stdint.h>
  8564. #include <assert.h>
  8565. #include <string.h>
  8566. #include <stdlib.h>
  8567. #include <errno.h>
  8568. #define UPB_JSON_MAX_DEPTH 64
  8569. typedef struct {
  8570. upb_sink sink;
  8571. /* The current message in which we're parsing, and the field whose value we're
  8572. * expecting next. */
  8573. const upb_msgdef *m;
  8574. const upb_fielddef *f;
  8575. /* The table mapping json name to fielddef for this message. */
  8576. upb_strtable *name_table;
  8577. /* We are in a repeated-field context, ready to emit mapentries as
  8578. * submessages. This flag alters the start-of-object (open-brace) behavior to
  8579. * begin a sequence of mapentry messages rather than a single submessage. */
  8580. bool is_map;
  8581. /* We are in a map-entry message context. This flag is set when parsing the
  8582. * value field of a single map entry and indicates to all value-field parsers
  8583. * (subobjects, strings, numbers, and bools) that the map-entry submessage
  8584. * should end as soon as the value is parsed. */
  8585. bool is_mapentry;
  8586. /* If |is_map| or |is_mapentry| is true, |mapfield| refers to the parent
  8587. * message's map field that we're currently parsing. This differs from |f|
  8588. * because |f| is the field in the *current* message (i.e., the map-entry
  8589. * message itself), not the parent's field that leads to this map. */
  8590. const upb_fielddef *mapfield;
  8591. } upb_jsonparser_frame;
  8592. struct upb_json_parser {
  8593. upb_env *env;
  8594. const upb_json_parsermethod *method;
  8595. upb_bytessink input_;
  8596. /* Stack to track the JSON scopes we are in. */
  8597. upb_jsonparser_frame stack[UPB_JSON_MAX_DEPTH];
  8598. upb_jsonparser_frame *top;
  8599. upb_jsonparser_frame *limit;
  8600. upb_status status;
  8601. /* Ragel's internal parsing stack for the parsing state machine. */
  8602. int current_state;
  8603. int parser_stack[UPB_JSON_MAX_DEPTH];
  8604. int parser_top;
  8605. /* The handle for the current buffer. */
  8606. const upb_bufhandle *handle;
  8607. /* Accumulate buffer. See details in parser.rl. */
  8608. const char *accumulated;
  8609. size_t accumulated_len;
  8610. char *accumulate_buf;
  8611. size_t accumulate_buf_size;
  8612. /* Multi-part text data. See details in parser.rl. */
  8613. int multipart_state;
  8614. upb_selector_t string_selector;
  8615. /* Input capture. See details in parser.rl. */
  8616. const char *capture;
  8617. /* Intermediate result of parsing a unicode escape sequence. */
  8618. uint32_t digit;
  8619. };
  8620. struct upb_json_parsermethod {
  8621. upb_refcounted base;
  8622. upb_byteshandler input_handler_;
  8623. /* Mainly for the purposes of refcounting, so all the fielddefs we point
  8624. * to stay alive. */
  8625. const upb_msgdef *msg;
  8626. /* Keys are upb_msgdef*, values are upb_strtable (json_name -> fielddef) */
  8627. upb_inttable name_tables;
  8628. };
  8629. #define PARSER_CHECK_RETURN(x) if (!(x)) return false
  8630. /* Used to signal that a capture has been suspended. */
  8631. static char suspend_capture;
  8632. static upb_selector_t getsel_for_handlertype(upb_json_parser *p,
  8633. upb_handlertype_t type) {
  8634. upb_selector_t sel;
  8635. bool ok = upb_handlers_getselector(p->top->f, type, &sel);
  8636. UPB_ASSERT_VAR(ok, ok);
  8637. return sel;
  8638. }
  8639. static upb_selector_t parser_getsel(upb_json_parser *p) {
  8640. return getsel_for_handlertype(
  8641. p, upb_handlers_getprimitivehandlertype(p->top->f));
  8642. }
  8643. static bool check_stack(upb_json_parser *p) {
  8644. if ((p->top + 1) == p->limit) {
  8645. upb_status_seterrmsg(&p->status, "Nesting too deep");
  8646. upb_env_reporterror(p->env, &p->status);
  8647. return false;
  8648. }
  8649. return true;
  8650. }
  8651. static void set_name_table(upb_json_parser *p, upb_jsonparser_frame *frame) {
  8652. upb_value v;
  8653. bool ok = upb_inttable_lookupptr(&p->method->name_tables, frame->m, &v);
  8654. UPB_ASSERT_VAR(ok, ok);
  8655. frame->name_table = upb_value_getptr(v);
  8656. }
  8657. /* There are GCC/Clang built-ins for overflow checking which we could start
  8658. * using if there was any performance benefit to it. */
  8659. static bool checked_add(size_t a, size_t b, size_t *c) {
  8660. if (SIZE_MAX - a < b) return false;
  8661. *c = a + b;
  8662. return true;
  8663. }
  8664. static size_t saturating_multiply(size_t a, size_t b) {
  8665. /* size_t is unsigned, so this is defined behavior even on overflow. */
  8666. size_t ret = a * b;
  8667. if (b != 0 && ret / b != a) {
  8668. ret = SIZE_MAX;
  8669. }
  8670. return ret;
  8671. }
  8672. /* Base64 decoding ************************************************************/
  8673. /* TODO(haberman): make this streaming. */
  8674. static const signed char b64table[] = {
  8675. -1, -1, -1, -1, -1, -1, -1, -1,
  8676. -1, -1, -1, -1, -1, -1, -1, -1,
  8677. -1, -1, -1, -1, -1, -1, -1, -1,
  8678. -1, -1, -1, -1, -1, -1, -1, -1,
  8679. -1, -1, -1, -1, -1, -1, -1, -1,
  8680. -1, -1, -1, 62/*+*/, -1, -1, -1, 63/*/ */,
  8681. 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
  8682. 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1,
  8683. -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
  8684. 07/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
  8685. 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
  8686. 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, -1,
  8687. -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
  8688. 33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
  8689. 41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
  8690. 49/*x*/, 50/*y*/, 51/*z*/, -1, -1, -1, -1, -1,
  8691. -1, -1, -1, -1, -1, -1, -1, -1,
  8692. -1, -1, -1, -1, -1, -1, -1, -1,
  8693. -1, -1, -1, -1, -1, -1, -1, -1,
  8694. -1, -1, -1, -1, -1, -1, -1, -1,
  8695. -1, -1, -1, -1, -1, -1, -1, -1,
  8696. -1, -1, -1, -1, -1, -1, -1, -1,
  8697. -1, -1, -1, -1, -1, -1, -1, -1,
  8698. -1, -1, -1, -1, -1, -1, -1, -1,
  8699. -1, -1, -1, -1, -1, -1, -1, -1,
  8700. -1, -1, -1, -1, -1, -1, -1, -1,
  8701. -1, -1, -1, -1, -1, -1, -1, -1,
  8702. -1, -1, -1, -1, -1, -1, -1, -1,
  8703. -1, -1, -1, -1, -1, -1, -1, -1,
  8704. -1, -1, -1, -1, -1, -1, -1, -1,
  8705. -1, -1, -1, -1, -1, -1, -1, -1,
  8706. -1, -1, -1, -1, -1, -1, -1, -1
  8707. };
  8708. /* Returns the table value sign-extended to 32 bits. Knowing that the upper
  8709. * bits will be 1 for unrecognized characters makes it easier to check for
  8710. * this error condition later (see below). */
  8711. int32_t b64lookup(unsigned char ch) { return b64table[ch]; }
  8712. /* Returns true if the given character is not a valid base64 character or
  8713. * padding. */
  8714. bool nonbase64(unsigned char ch) { return b64lookup(ch) == -1 && ch != '='; }
  8715. static bool base64_push(upb_json_parser *p, upb_selector_t sel, const char *ptr,
  8716. size_t len) {
  8717. const char *limit = ptr + len;
  8718. for (; ptr < limit; ptr += 4) {
  8719. uint32_t val;
  8720. char output[3];
  8721. if (limit - ptr < 4) {
  8722. upb_status_seterrf(&p->status,
  8723. "Base64 input for bytes field not a multiple of 4: %s",
  8724. upb_fielddef_name(p->top->f));
  8725. upb_env_reporterror(p->env, &p->status);
  8726. return false;
  8727. }
  8728. val = b64lookup(ptr[0]) << 18 |
  8729. b64lookup(ptr[1]) << 12 |
  8730. b64lookup(ptr[2]) << 6 |
  8731. b64lookup(ptr[3]);
  8732. /* Test the upper bit; returns true if any of the characters returned -1. */
  8733. if (val & 0x80000000) {
  8734. goto otherchar;
  8735. }
  8736. output[0] = val >> 16;
  8737. output[1] = (val >> 8) & 0xff;
  8738. output[2] = val & 0xff;
  8739. upb_sink_putstring(&p->top->sink, sel, output, 3, NULL);
  8740. }
  8741. return true;
  8742. otherchar:
  8743. if (nonbase64(ptr[0]) || nonbase64(ptr[1]) || nonbase64(ptr[2]) ||
  8744. nonbase64(ptr[3]) ) {
  8745. upb_status_seterrf(&p->status,
  8746. "Non-base64 characters in bytes field: %s",
  8747. upb_fielddef_name(p->top->f));
  8748. upb_env_reporterror(p->env, &p->status);
  8749. return false;
  8750. } if (ptr[2] == '=') {
  8751. uint32_t val;
  8752. char output;
  8753. /* Last group contains only two input bytes, one output byte. */
  8754. if (ptr[0] == '=' || ptr[1] == '=' || ptr[3] != '=') {
  8755. goto badpadding;
  8756. }
  8757. val = b64lookup(ptr[0]) << 18 |
  8758. b64lookup(ptr[1]) << 12;
  8759. assert(!(val & 0x80000000));
  8760. output = val >> 16;
  8761. upb_sink_putstring(&p->top->sink, sel, &output, 1, NULL);
  8762. return true;
  8763. } else {
  8764. uint32_t val;
  8765. char output[2];
  8766. /* Last group contains only three input bytes, two output bytes. */
  8767. if (ptr[0] == '=' || ptr[1] == '=' || ptr[2] == '=') {
  8768. goto badpadding;
  8769. }
  8770. val = b64lookup(ptr[0]) << 18 |
  8771. b64lookup(ptr[1]) << 12 |
  8772. b64lookup(ptr[2]) << 6;
  8773. output[0] = val >> 16;
  8774. output[1] = (val >> 8) & 0xff;
  8775. upb_sink_putstring(&p->top->sink, sel, output, 2, NULL);
  8776. return true;
  8777. }
  8778. badpadding:
  8779. upb_status_seterrf(&p->status,
  8780. "Incorrect base64 padding for field: %s (%.*s)",
  8781. upb_fielddef_name(p->top->f),
  8782. 4, ptr);
  8783. upb_env_reporterror(p->env, &p->status);
  8784. return false;
  8785. }
  8786. /* Accumulate buffer **********************************************************/
  8787. /* Functionality for accumulating a buffer.
  8788. *
  8789. * Some parts of the parser need an entire value as a contiguous string. For
  8790. * example, to look up a member name in a hash table, or to turn a string into
  8791. * a number, the relevant library routines need the input string to be in
  8792. * contiguous memory, even if the value spanned two or more buffers in the
  8793. * input. These routines handle that.
  8794. *
  8795. * In the common case we can just point to the input buffer to get this
  8796. * contiguous string and avoid any actual copy. So we optimistically begin
  8797. * this way. But there are a few cases where we must instead copy into a
  8798. * separate buffer:
  8799. *
  8800. * 1. The string was not contiguous in the input (it spanned buffers).
  8801. *
  8802. * 2. The string included escape sequences that need to be interpreted to get
  8803. * the true value in a contiguous buffer. */
  8804. static void assert_accumulate_empty(upb_json_parser *p) {
  8805. UPB_UNUSED(p);
  8806. assert(p->accumulated == NULL);
  8807. assert(p->accumulated_len == 0);
  8808. }
  8809. static void accumulate_clear(upb_json_parser *p) {
  8810. p->accumulated = NULL;
  8811. p->accumulated_len = 0;
  8812. }
  8813. /* Used internally by accumulate_append(). */
  8814. static bool accumulate_realloc(upb_json_parser *p, size_t need) {
  8815. void *mem;
  8816. size_t old_size = p->accumulate_buf_size;
  8817. size_t new_size = UPB_MAX(old_size, 128);
  8818. while (new_size < need) {
  8819. new_size = saturating_multiply(new_size, 2);
  8820. }
  8821. mem = upb_env_realloc(p->env, p->accumulate_buf, old_size, new_size);
  8822. if (!mem) {
  8823. upb_status_seterrmsg(&p->status, "Out of memory allocating buffer.");
  8824. upb_env_reporterror(p->env, &p->status);
  8825. return false;
  8826. }
  8827. p->accumulate_buf = mem;
  8828. p->accumulate_buf_size = new_size;
  8829. return true;
  8830. }
  8831. /* Logically appends the given data to the append buffer.
  8832. * If "can_alias" is true, we will try to avoid actually copying, but the buffer
  8833. * must be valid until the next accumulate_append() call (if any). */
  8834. static bool accumulate_append(upb_json_parser *p, const char *buf, size_t len,
  8835. bool can_alias) {
  8836. size_t need;
  8837. if (!p->accumulated && can_alias) {
  8838. p->accumulated = buf;
  8839. p->accumulated_len = len;
  8840. return true;
  8841. }
  8842. if (!checked_add(p->accumulated_len, len, &need)) {
  8843. upb_status_seterrmsg(&p->status, "Integer overflow.");
  8844. upb_env_reporterror(p->env, &p->status);
  8845. return false;
  8846. }
  8847. if (need > p->accumulate_buf_size && !accumulate_realloc(p, need)) {
  8848. return false;
  8849. }
  8850. if (p->accumulated != p->accumulate_buf) {
  8851. memcpy(p->accumulate_buf, p->accumulated, p->accumulated_len);
  8852. p->accumulated = p->accumulate_buf;
  8853. }
  8854. memcpy(p->accumulate_buf + p->accumulated_len, buf, len);
  8855. p->accumulated_len += len;
  8856. return true;
  8857. }
  8858. /* Returns a pointer to the data accumulated since the last accumulate_clear()
  8859. * call, and writes the length to *len. This with point either to the input
  8860. * buffer or a temporary accumulate buffer. */
  8861. static const char *accumulate_getptr(upb_json_parser *p, size_t *len) {
  8862. assert(p->accumulated);
  8863. *len = p->accumulated_len;
  8864. return p->accumulated;
  8865. }
  8866. /* Mult-part text data ********************************************************/
  8867. /* When we have text data in the input, it can often come in multiple segments.
  8868. * For example, there may be some raw string data followed by an escape
  8869. * sequence. The two segments are processed with different logic. Also buffer
  8870. * seams in the input can cause multiple segments.
  8871. *
  8872. * As we see segments, there are two main cases for how we want to process them:
  8873. *
  8874. * 1. we want to push the captured input directly to string handlers.
  8875. *
  8876. * 2. we need to accumulate all the parts into a contiguous buffer for further
  8877. * processing (field name lookup, string->number conversion, etc). */
  8878. /* This is the set of states for p->multipart_state. */
  8879. enum {
  8880. /* We are not currently processing multipart data. */
  8881. MULTIPART_INACTIVE = 0,
  8882. /* We are processing multipart data by accumulating it into a contiguous
  8883. * buffer. */
  8884. MULTIPART_ACCUMULATE = 1,
  8885. /* We are processing multipart data by pushing each part directly to the
  8886. * current string handlers. */
  8887. MULTIPART_PUSHEAGERLY = 2
  8888. };
  8889. /* Start a multi-part text value where we accumulate the data for processing at
  8890. * the end. */
  8891. static void multipart_startaccum(upb_json_parser *p) {
  8892. assert_accumulate_empty(p);
  8893. assert(p->multipart_state == MULTIPART_INACTIVE);
  8894. p->multipart_state = MULTIPART_ACCUMULATE;
  8895. }
  8896. /* Start a multi-part text value where we immediately push text data to a string
  8897. * value with the given selector. */
  8898. static void multipart_start(upb_json_parser *p, upb_selector_t sel) {
  8899. assert_accumulate_empty(p);
  8900. assert(p->multipart_state == MULTIPART_INACTIVE);
  8901. p->multipart_state = MULTIPART_PUSHEAGERLY;
  8902. p->string_selector = sel;
  8903. }
  8904. static bool multipart_text(upb_json_parser *p, const char *buf, size_t len,
  8905. bool can_alias) {
  8906. switch (p->multipart_state) {
  8907. case MULTIPART_INACTIVE:
  8908. upb_status_seterrmsg(
  8909. &p->status, "Internal error: unexpected state MULTIPART_INACTIVE");
  8910. upb_env_reporterror(p->env, &p->status);
  8911. return false;
  8912. case MULTIPART_ACCUMULATE:
  8913. if (!accumulate_append(p, buf, len, can_alias)) {
  8914. return false;
  8915. }
  8916. break;
  8917. case MULTIPART_PUSHEAGERLY: {
  8918. const upb_bufhandle *handle = can_alias ? p->handle : NULL;
  8919. upb_sink_putstring(&p->top->sink, p->string_selector, buf, len, handle);
  8920. break;
  8921. }
  8922. }
  8923. return true;
  8924. }
  8925. /* Note: this invalidates the accumulate buffer! Call only after reading its
  8926. * contents. */
  8927. static void multipart_end(upb_json_parser *p) {
  8928. assert(p->multipart_state != MULTIPART_INACTIVE);
  8929. p->multipart_state = MULTIPART_INACTIVE;
  8930. accumulate_clear(p);
  8931. }
  8932. /* Input capture **************************************************************/
  8933. /* Functionality for capturing a region of the input as text. Gracefully
  8934. * handles the case where a buffer seam occurs in the middle of the captured
  8935. * region. */
  8936. static void capture_begin(upb_json_parser *p, const char *ptr) {
  8937. assert(p->multipart_state != MULTIPART_INACTIVE);
  8938. assert(p->capture == NULL);
  8939. p->capture = ptr;
  8940. }
  8941. static bool capture_end(upb_json_parser *p, const char *ptr) {
  8942. assert(p->capture);
  8943. if (multipart_text(p, p->capture, ptr - p->capture, true)) {
  8944. p->capture = NULL;
  8945. return true;
  8946. } else {
  8947. return false;
  8948. }
  8949. }
  8950. /* This is called at the end of each input buffer (ie. when we have hit a
  8951. * buffer seam). If we are in the middle of capturing the input, this
  8952. * processes the unprocessed capture region. */
  8953. static void capture_suspend(upb_json_parser *p, const char **ptr) {
  8954. if (!p->capture) return;
  8955. if (multipart_text(p, p->capture, *ptr - p->capture, false)) {
  8956. /* We use this as a signal that we were in the middle of capturing, and
  8957. * that capturing should resume at the beginning of the next buffer.
  8958. *
  8959. * We can't use *ptr here, because we have no guarantee that this pointer
  8960. * will be valid when we resume (if the underlying memory is freed, then
  8961. * using the pointer at all, even to compare to NULL, is likely undefined
  8962. * behavior). */
  8963. p->capture = &suspend_capture;
  8964. } else {
  8965. /* Need to back up the pointer to the beginning of the capture, since
  8966. * we were not able to actually preserve it. */
  8967. *ptr = p->capture;
  8968. }
  8969. }
  8970. static void capture_resume(upb_json_parser *p, const char *ptr) {
  8971. if (p->capture) {
  8972. assert(p->capture == &suspend_capture);
  8973. p->capture = ptr;
  8974. }
  8975. }
  8976. /* Callbacks from the parser **************************************************/
  8977. /* These are the functions called directly from the parser itself.
  8978. * We define these in the same order as their declarations in the parser. */
  8979. static char escape_char(char in) {
  8980. switch (in) {
  8981. case 'r': return '\r';
  8982. case 't': return '\t';
  8983. case 'n': return '\n';
  8984. case 'f': return '\f';
  8985. case 'b': return '\b';
  8986. case '/': return '/';
  8987. case '"': return '"';
  8988. case '\\': return '\\';
  8989. default:
  8990. assert(0);
  8991. return 'x';
  8992. }
  8993. }
  8994. static bool escape(upb_json_parser *p, const char *ptr) {
  8995. char ch = escape_char(*ptr);
  8996. return multipart_text(p, &ch, 1, false);
  8997. }
  8998. static void start_hex(upb_json_parser *p) {
  8999. p->digit = 0;
  9000. }
  9001. static void hexdigit(upb_json_parser *p, const char *ptr) {
  9002. char ch = *ptr;
  9003. p->digit <<= 4;
  9004. if (ch >= '0' && ch <= '9') {
  9005. p->digit += (ch - '0');
  9006. } else if (ch >= 'a' && ch <= 'f') {
  9007. p->digit += ((ch - 'a') + 10);
  9008. } else {
  9009. assert(ch >= 'A' && ch <= 'F');
  9010. p->digit += ((ch - 'A') + 10);
  9011. }
  9012. }
  9013. static bool end_hex(upb_json_parser *p) {
  9014. uint32_t codepoint = p->digit;
  9015. /* emit the codepoint as UTF-8. */
  9016. char utf8[3]; /* support \u0000 -- \uFFFF -- need only three bytes. */
  9017. int length = 0;
  9018. if (codepoint <= 0x7F) {
  9019. utf8[0] = codepoint;
  9020. length = 1;
  9021. } else if (codepoint <= 0x07FF) {
  9022. utf8[1] = (codepoint & 0x3F) | 0x80;
  9023. codepoint >>= 6;
  9024. utf8[0] = (codepoint & 0x1F) | 0xC0;
  9025. length = 2;
  9026. } else /* codepoint <= 0xFFFF */ {
  9027. utf8[2] = (codepoint & 0x3F) | 0x80;
  9028. codepoint >>= 6;
  9029. utf8[1] = (codepoint & 0x3F) | 0x80;
  9030. codepoint >>= 6;
  9031. utf8[0] = (codepoint & 0x0F) | 0xE0;
  9032. length = 3;
  9033. }
  9034. /* TODO(haberman): Handle high surrogates: if codepoint is a high surrogate
  9035. * we have to wait for the next escape to get the full code point). */
  9036. return multipart_text(p, utf8, length, false);
  9037. }
  9038. static void start_text(upb_json_parser *p, const char *ptr) {
  9039. capture_begin(p, ptr);
  9040. }
  9041. static bool end_text(upb_json_parser *p, const char *ptr) {
  9042. return capture_end(p, ptr);
  9043. }
  9044. static void start_number(upb_json_parser *p, const char *ptr) {
  9045. multipart_startaccum(p);
  9046. capture_begin(p, ptr);
  9047. }
  9048. static bool parse_number(upb_json_parser *p);
  9049. static bool end_number(upb_json_parser *p, const char *ptr) {
  9050. if (!capture_end(p, ptr)) {
  9051. return false;
  9052. }
  9053. return parse_number(p);
  9054. }
  9055. static bool parse_number(upb_json_parser *p) {
  9056. size_t len;
  9057. const char *buf;
  9058. const char *myend;
  9059. char *end;
  9060. /* strtol() and friends unfortunately do not support specifying the length of
  9061. * the input string, so we need to force a copy into a NULL-terminated buffer. */
  9062. if (!multipart_text(p, "\0", 1, false)) {
  9063. return false;
  9064. }
  9065. buf = accumulate_getptr(p, &len);
  9066. myend = buf + len - 1; /* One for NULL. */
  9067. /* XXX: We are using strtol to parse integers, but this is wrong as even
  9068. * integers can be represented as 1e6 (for example), which strtol can't
  9069. * handle correctly.
  9070. *
  9071. * XXX: Also, we can't handle large integers properly because strto[u]ll
  9072. * isn't in C89.
  9073. *
  9074. * XXX: Also, we don't properly check floats for overflow, since strtof
  9075. * isn't in C89. */
  9076. switch (upb_fielddef_type(p->top->f)) {
  9077. case UPB_TYPE_ENUM:
  9078. case UPB_TYPE_INT32: {
  9079. long val = strtol(p->accumulated, &end, 0);
  9080. if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || end != myend)
  9081. goto err;
  9082. else
  9083. upb_sink_putint32(&p->top->sink, parser_getsel(p), val);
  9084. break;
  9085. }
  9086. case UPB_TYPE_INT64: {
  9087. long long val = strtol(p->accumulated, &end, 0);
  9088. if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || end != myend)
  9089. goto err;
  9090. else
  9091. upb_sink_putint64(&p->top->sink, parser_getsel(p), val);
  9092. break;
  9093. }
  9094. case UPB_TYPE_UINT32: {
  9095. unsigned long val = strtoul(p->accumulated, &end, 0);
  9096. if (val > UINT32_MAX || errno == ERANGE || end != myend)
  9097. goto err;
  9098. else
  9099. upb_sink_putuint32(&p->top->sink, parser_getsel(p), val);
  9100. break;
  9101. }
  9102. case UPB_TYPE_UINT64: {
  9103. unsigned long long val = strtoul(p->accumulated, &end, 0);
  9104. if (val > UINT64_MAX || errno == ERANGE || end != myend)
  9105. goto err;
  9106. else
  9107. upb_sink_putuint64(&p->top->sink, parser_getsel(p), val);
  9108. break;
  9109. }
  9110. case UPB_TYPE_DOUBLE: {
  9111. double val = strtod(p->accumulated, &end);
  9112. if (errno == ERANGE || end != myend)
  9113. goto err;
  9114. else
  9115. upb_sink_putdouble(&p->top->sink, parser_getsel(p), val);
  9116. break;
  9117. }
  9118. case UPB_TYPE_FLOAT: {
  9119. float val = strtod(p->accumulated, &end);
  9120. if (errno == ERANGE || end != myend)
  9121. goto err;
  9122. else
  9123. upb_sink_putfloat(&p->top->sink, parser_getsel(p), val);
  9124. break;
  9125. }
  9126. default:
  9127. assert(false);
  9128. }
  9129. multipart_end(p);
  9130. return true;
  9131. err:
  9132. upb_status_seterrf(&p->status, "error parsing number: %s", buf);
  9133. upb_env_reporterror(p->env, &p->status);
  9134. multipart_end(p);
  9135. return false;
  9136. }
  9137. static bool parser_putbool(upb_json_parser *p, bool val) {
  9138. bool ok;
  9139. if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL) {
  9140. upb_status_seterrf(&p->status,
  9141. "Boolean value specified for non-bool field: %s",
  9142. upb_fielddef_name(p->top->f));
  9143. upb_env_reporterror(p->env, &p->status);
  9144. return false;
  9145. }
  9146. ok = upb_sink_putbool(&p->top->sink, parser_getsel(p), val);
  9147. UPB_ASSERT_VAR(ok, ok);
  9148. return true;
  9149. }
  9150. static bool start_stringval(upb_json_parser *p) {
  9151. assert(p->top->f);
  9152. if (upb_fielddef_isstring(p->top->f)) {
  9153. upb_jsonparser_frame *inner;
  9154. upb_selector_t sel;
  9155. if (!check_stack(p)) return false;
  9156. /* Start a new parser frame: parser frames correspond one-to-one with
  9157. * handler frames, and string events occur in a sub-frame. */
  9158. inner = p->top + 1;
  9159. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  9160. upb_sink_startstr(&p->top->sink, sel, 0, &inner->sink);
  9161. inner->m = p->top->m;
  9162. inner->f = p->top->f;
  9163. inner->name_table = NULL;
  9164. inner->is_map = false;
  9165. inner->is_mapentry = false;
  9166. p->top = inner;
  9167. if (upb_fielddef_type(p->top->f) == UPB_TYPE_STRING) {
  9168. /* For STRING fields we push data directly to the handlers as it is
  9169. * parsed. We don't do this yet for BYTES fields, because our base64
  9170. * decoder is not streaming.
  9171. *
  9172. * TODO(haberman): make base64 decoding streaming also. */
  9173. multipart_start(p, getsel_for_handlertype(p, UPB_HANDLER_STRING));
  9174. return true;
  9175. } else {
  9176. multipart_startaccum(p);
  9177. return true;
  9178. }
  9179. } else if (upb_fielddef_type(p->top->f) == UPB_TYPE_ENUM) {
  9180. /* No need to push a frame -- symbolic enum names in quotes remain in the
  9181. * current parser frame.
  9182. *
  9183. * Enum string values must accumulate so we can look up the value in a table
  9184. * once it is complete. */
  9185. multipart_startaccum(p);
  9186. return true;
  9187. } else {
  9188. upb_status_seterrf(&p->status,
  9189. "String specified for non-string/non-enum field: %s",
  9190. upb_fielddef_name(p->top->f));
  9191. upb_env_reporterror(p->env, &p->status);
  9192. return false;
  9193. }
  9194. }
  9195. static bool end_stringval(upb_json_parser *p) {
  9196. bool ok = true;
  9197. switch (upb_fielddef_type(p->top->f)) {
  9198. case UPB_TYPE_BYTES:
  9199. if (!base64_push(p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  9200. p->accumulated, p->accumulated_len)) {
  9201. return false;
  9202. }
  9203. /* Fall through. */
  9204. case UPB_TYPE_STRING: {
  9205. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  9206. upb_sink_endstr(&p->top->sink, sel);
  9207. p->top--;
  9208. break;
  9209. }
  9210. case UPB_TYPE_ENUM: {
  9211. /* Resolve enum symbolic name to integer value. */
  9212. const upb_enumdef *enumdef =
  9213. (const upb_enumdef*)upb_fielddef_subdef(p->top->f);
  9214. size_t len;
  9215. const char *buf = accumulate_getptr(p, &len);
  9216. int32_t int_val = 0;
  9217. ok = upb_enumdef_ntoi(enumdef, buf, len, &int_val);
  9218. if (ok) {
  9219. upb_selector_t sel = parser_getsel(p);
  9220. upb_sink_putint32(&p->top->sink, sel, int_val);
  9221. } else {
  9222. upb_status_seterrf(&p->status, "Enum value unknown: '%.*s'", len, buf);
  9223. upb_env_reporterror(p->env, &p->status);
  9224. }
  9225. break;
  9226. }
  9227. default:
  9228. assert(false);
  9229. upb_status_seterrmsg(&p->status, "Internal error in JSON decoder");
  9230. upb_env_reporterror(p->env, &p->status);
  9231. ok = false;
  9232. break;
  9233. }
  9234. multipart_end(p);
  9235. return ok;
  9236. }
  9237. static void start_member(upb_json_parser *p) {
  9238. assert(!p->top->f);
  9239. multipart_startaccum(p);
  9240. }
  9241. /* Helper: invoked during parse_mapentry() to emit the mapentry message's key
  9242. * field based on the current contents of the accumulate buffer. */
  9243. static bool parse_mapentry_key(upb_json_parser *p) {
  9244. size_t len;
  9245. const char *buf = accumulate_getptr(p, &len);
  9246. /* Emit the key field. We do a bit of ad-hoc parsing here because the
  9247. * parser state machine has already decided that this is a string field
  9248. * name, and we are reinterpreting it as some arbitrary key type. In
  9249. * particular, integer and bool keys are quoted, so we need to parse the
  9250. * quoted string contents here. */
  9251. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_KEY);
  9252. if (p->top->f == NULL) {
  9253. upb_status_seterrmsg(&p->status, "mapentry message has no key");
  9254. upb_env_reporterror(p->env, &p->status);
  9255. return false;
  9256. }
  9257. switch (upb_fielddef_type(p->top->f)) {
  9258. case UPB_TYPE_INT32:
  9259. case UPB_TYPE_INT64:
  9260. case UPB_TYPE_UINT32:
  9261. case UPB_TYPE_UINT64:
  9262. /* Invoke end_number. The accum buffer has the number's text already. */
  9263. if (!parse_number(p)) {
  9264. return false;
  9265. }
  9266. break;
  9267. case UPB_TYPE_BOOL:
  9268. if (len == 4 && !strncmp(buf, "true", 4)) {
  9269. if (!parser_putbool(p, true)) {
  9270. return false;
  9271. }
  9272. } else if (len == 5 && !strncmp(buf, "false", 5)) {
  9273. if (!parser_putbool(p, false)) {
  9274. return false;
  9275. }
  9276. } else {
  9277. upb_status_seterrmsg(&p->status,
  9278. "Map bool key not 'true' or 'false'");
  9279. upb_env_reporterror(p->env, &p->status);
  9280. return false;
  9281. }
  9282. multipart_end(p);
  9283. break;
  9284. case UPB_TYPE_STRING:
  9285. case UPB_TYPE_BYTES: {
  9286. upb_sink subsink;
  9287. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  9288. upb_sink_startstr(&p->top->sink, sel, len, &subsink);
  9289. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  9290. upb_sink_putstring(&subsink, sel, buf, len, NULL);
  9291. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  9292. upb_sink_endstr(&subsink, sel);
  9293. multipart_end(p);
  9294. break;
  9295. }
  9296. default:
  9297. upb_status_seterrmsg(&p->status, "Invalid field type for map key");
  9298. upb_env_reporterror(p->env, &p->status);
  9299. return false;
  9300. }
  9301. return true;
  9302. }
  9303. /* Helper: emit one map entry (as a submessage in the map field sequence). This
  9304. * is invoked from end_membername(), at the end of the map entry's key string,
  9305. * with the map key in the accumulate buffer. It parses the key from that
  9306. * buffer, emits the handler calls to start the mapentry submessage (setting up
  9307. * its subframe in the process), and sets up state in the subframe so that the
  9308. * value parser (invoked next) will emit the mapentry's value field and then
  9309. * end the mapentry message. */
  9310. static bool handle_mapentry(upb_json_parser *p) {
  9311. const upb_fielddef *mapfield;
  9312. const upb_msgdef *mapentrymsg;
  9313. upb_jsonparser_frame *inner;
  9314. upb_selector_t sel;
  9315. /* Map entry: p->top->sink is the seq frame, so we need to start a frame
  9316. * for the mapentry itself, and then set |f| in that frame so that the map
  9317. * value field is parsed, and also set a flag to end the frame after the
  9318. * map-entry value is parsed. */
  9319. if (!check_stack(p)) return false;
  9320. mapfield = p->top->mapfield;
  9321. mapentrymsg = upb_fielddef_msgsubdef(mapfield);
  9322. inner = p->top + 1;
  9323. p->top->f = mapfield;
  9324. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  9325. upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
  9326. inner->m = mapentrymsg;
  9327. inner->name_table = NULL;
  9328. inner->mapfield = mapfield;
  9329. inner->is_map = false;
  9330. /* Don't set this to true *yet* -- we reuse parsing handlers below to push
  9331. * the key field value to the sink, and these handlers will pop the frame
  9332. * if they see is_mapentry (when invoked by the parser state machine, they
  9333. * would have just seen the map-entry value, not key). */
  9334. inner->is_mapentry = false;
  9335. p->top = inner;
  9336. /* send STARTMSG in submsg frame. */
  9337. upb_sink_startmsg(&p->top->sink);
  9338. parse_mapentry_key(p);
  9339. /* Set up the value field to receive the map-entry value. */
  9340. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_VALUE);
  9341. p->top->is_mapentry = true; /* set up to pop frame after value is parsed. */
  9342. p->top->mapfield = mapfield;
  9343. if (p->top->f == NULL) {
  9344. upb_status_seterrmsg(&p->status, "mapentry message has no value");
  9345. upb_env_reporterror(p->env, &p->status);
  9346. return false;
  9347. }
  9348. return true;
  9349. }
  9350. static bool end_membername(upb_json_parser *p) {
  9351. assert(!p->top->f);
  9352. if (p->top->is_map) {
  9353. return handle_mapentry(p);
  9354. } else {
  9355. size_t len;
  9356. const char *buf = accumulate_getptr(p, &len);
  9357. upb_value v;
  9358. if (upb_strtable_lookup2(p->top->name_table, buf, len, &v)) {
  9359. p->top->f = upb_value_getconstptr(v);
  9360. multipart_end(p);
  9361. return true;
  9362. } else {
  9363. /* TODO(haberman): Ignore unknown fields if requested/configured to do
  9364. * so. */
  9365. upb_status_seterrf(&p->status, "No such field: %.*s\n", (int)len, buf);
  9366. upb_env_reporterror(p->env, &p->status);
  9367. return false;
  9368. }
  9369. }
  9370. }
  9371. static void end_member(upb_json_parser *p) {
  9372. /* If we just parsed a map-entry value, end that frame too. */
  9373. if (p->top->is_mapentry) {
  9374. upb_status s = UPB_STATUS_INIT;
  9375. upb_selector_t sel;
  9376. bool ok;
  9377. const upb_fielddef *mapfield;
  9378. assert(p->top > p->stack);
  9379. /* send ENDMSG on submsg. */
  9380. upb_sink_endmsg(&p->top->sink, &s);
  9381. mapfield = p->top->mapfield;
  9382. /* send ENDSUBMSG in repeated-field-of-mapentries frame. */
  9383. p->top--;
  9384. ok = upb_handlers_getselector(mapfield, UPB_HANDLER_ENDSUBMSG, &sel);
  9385. UPB_ASSERT_VAR(ok, ok);
  9386. upb_sink_endsubmsg(&p->top->sink, sel);
  9387. }
  9388. p->top->f = NULL;
  9389. }
  9390. static bool start_subobject(upb_json_parser *p) {
  9391. assert(p->top->f);
  9392. if (upb_fielddef_ismap(p->top->f)) {
  9393. upb_jsonparser_frame *inner;
  9394. upb_selector_t sel;
  9395. /* Beginning of a map. Start a new parser frame in a repeated-field
  9396. * context. */
  9397. if (!check_stack(p)) return false;
  9398. inner = p->top + 1;
  9399. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  9400. upb_sink_startseq(&p->top->sink, sel, &inner->sink);
  9401. inner->m = upb_fielddef_msgsubdef(p->top->f);
  9402. inner->name_table = NULL;
  9403. inner->mapfield = p->top->f;
  9404. inner->f = NULL;
  9405. inner->is_map = true;
  9406. inner->is_mapentry = false;
  9407. p->top = inner;
  9408. return true;
  9409. } else if (upb_fielddef_issubmsg(p->top->f)) {
  9410. upb_jsonparser_frame *inner;
  9411. upb_selector_t sel;
  9412. /* Beginning of a subobject. Start a new parser frame in the submsg
  9413. * context. */
  9414. if (!check_stack(p)) return false;
  9415. inner = p->top + 1;
  9416. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  9417. upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
  9418. inner->m = upb_fielddef_msgsubdef(p->top->f);
  9419. set_name_table(p, inner);
  9420. inner->f = NULL;
  9421. inner->is_map = false;
  9422. inner->is_mapentry = false;
  9423. p->top = inner;
  9424. return true;
  9425. } else {
  9426. upb_status_seterrf(&p->status,
  9427. "Object specified for non-message/group field: %s",
  9428. upb_fielddef_name(p->top->f));
  9429. upb_env_reporterror(p->env, &p->status);
  9430. return false;
  9431. }
  9432. }
  9433. static void end_subobject(upb_json_parser *p) {
  9434. if (p->top->is_map) {
  9435. upb_selector_t sel;
  9436. p->top--;
  9437. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  9438. upb_sink_endseq(&p->top->sink, sel);
  9439. } else {
  9440. upb_selector_t sel;
  9441. p->top--;
  9442. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSUBMSG);
  9443. upb_sink_endsubmsg(&p->top->sink, sel);
  9444. }
  9445. }
  9446. static bool start_array(upb_json_parser *p) {
  9447. upb_jsonparser_frame *inner;
  9448. upb_selector_t sel;
  9449. assert(p->top->f);
  9450. if (!upb_fielddef_isseq(p->top->f)) {
  9451. upb_status_seterrf(&p->status,
  9452. "Array specified for non-repeated field: %s",
  9453. upb_fielddef_name(p->top->f));
  9454. upb_env_reporterror(p->env, &p->status);
  9455. return false;
  9456. }
  9457. if (!check_stack(p)) return false;
  9458. inner = p->top + 1;
  9459. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  9460. upb_sink_startseq(&p->top->sink, sel, &inner->sink);
  9461. inner->m = p->top->m;
  9462. inner->name_table = NULL;
  9463. inner->f = p->top->f;
  9464. inner->is_map = false;
  9465. inner->is_mapentry = false;
  9466. p->top = inner;
  9467. return true;
  9468. }
  9469. static void end_array(upb_json_parser *p) {
  9470. upb_selector_t sel;
  9471. assert(p->top > p->stack);
  9472. p->top--;
  9473. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  9474. upb_sink_endseq(&p->top->sink, sel);
  9475. }
  9476. static void start_object(upb_json_parser *p) {
  9477. if (!p->top->is_map) {
  9478. upb_sink_startmsg(&p->top->sink);
  9479. }
  9480. }
  9481. static void end_object(upb_json_parser *p) {
  9482. if (!p->top->is_map) {
  9483. upb_status status;
  9484. upb_status_clear(&status);
  9485. upb_sink_endmsg(&p->top->sink, &status);
  9486. if (!upb_ok(&status)) {
  9487. upb_env_reporterror(p->env, &status);
  9488. }
  9489. }
  9490. }
  9491. #define CHECK_RETURN_TOP(x) if (!(x)) goto error
  9492. /* The actual parser **********************************************************/
  9493. /* What follows is the Ragel parser itself. The language is specified in Ragel
  9494. * and the actions call our C functions above.
  9495. *
  9496. * Ragel has an extensive set of functionality, and we use only a small part of
  9497. * it. There are many action types but we only use a few:
  9498. *
  9499. * ">" -- transition into a machine
  9500. * "%" -- transition out of a machine
  9501. * "@" -- transition into a final state of a machine.
  9502. *
  9503. * "@" transitions are tricky because a machine can transition into a final
  9504. * state repeatedly. But in some cases we know this can't happen, for example
  9505. * a string which is delimited by a final '"' can only transition into its
  9506. * final state once, when the closing '"' is seen. */
  9507. #line 1246 "upb/json/parser.rl"
  9508. #line 1158 "upb/json/parser.c"
  9509. static const char _json_actions[] = {
  9510. 0, 1, 0, 1, 2, 1, 3, 1,
  9511. 5, 1, 6, 1, 7, 1, 8, 1,
  9512. 10, 1, 12, 1, 13, 1, 14, 1,
  9513. 15, 1, 16, 1, 17, 1, 21, 1,
  9514. 25, 1, 27, 2, 3, 8, 2, 4,
  9515. 5, 2, 6, 2, 2, 6, 8, 2,
  9516. 11, 9, 2, 13, 15, 2, 14, 15,
  9517. 2, 18, 1, 2, 19, 27, 2, 20,
  9518. 9, 2, 22, 27, 2, 23, 27, 2,
  9519. 24, 27, 2, 26, 27, 3, 14, 11,
  9520. 9
  9521. };
  9522. static const unsigned char _json_key_offsets[] = {
  9523. 0, 0, 4, 9, 14, 15, 19, 24,
  9524. 29, 34, 38, 42, 45, 48, 50, 54,
  9525. 58, 60, 62, 67, 69, 71, 80, 86,
  9526. 92, 98, 104, 106, 115, 116, 116, 116,
  9527. 121, 126, 131, 132, 133, 134, 135, 135,
  9528. 136, 137, 138, 138, 139, 140, 141, 141,
  9529. 146, 151, 152, 156, 161, 166, 171, 175,
  9530. 175, 178, 178, 178
  9531. };
  9532. static const char _json_trans_keys[] = {
  9533. 32, 123, 9, 13, 32, 34, 125, 9,
  9534. 13, 32, 34, 125, 9, 13, 34, 32,
  9535. 58, 9, 13, 32, 93, 125, 9, 13,
  9536. 32, 44, 125, 9, 13, 32, 44, 125,
  9537. 9, 13, 32, 34, 9, 13, 45, 48,
  9538. 49, 57, 48, 49, 57, 46, 69, 101,
  9539. 48, 57, 69, 101, 48, 57, 43, 45,
  9540. 48, 57, 48, 57, 48, 57, 46, 69,
  9541. 101, 48, 57, 34, 92, 34, 92, 34,
  9542. 47, 92, 98, 102, 110, 114, 116, 117,
  9543. 48, 57, 65, 70, 97, 102, 48, 57,
  9544. 65, 70, 97, 102, 48, 57, 65, 70,
  9545. 97, 102, 48, 57, 65, 70, 97, 102,
  9546. 34, 92, 34, 45, 91, 102, 110, 116,
  9547. 123, 48, 57, 34, 32, 93, 125, 9,
  9548. 13, 32, 44, 93, 9, 13, 32, 93,
  9549. 125, 9, 13, 97, 108, 115, 101, 117,
  9550. 108, 108, 114, 117, 101, 32, 34, 125,
  9551. 9, 13, 32, 34, 125, 9, 13, 34,
  9552. 32, 58, 9, 13, 32, 93, 125, 9,
  9553. 13, 32, 44, 125, 9, 13, 32, 44,
  9554. 125, 9, 13, 32, 34, 9, 13, 32,
  9555. 9, 13, 0
  9556. };
  9557. static const char _json_single_lengths[] = {
  9558. 0, 2, 3, 3, 1, 2, 3, 3,
  9559. 3, 2, 2, 1, 3, 0, 2, 2,
  9560. 0, 0, 3, 2, 2, 9, 0, 0,
  9561. 0, 0, 2, 7, 1, 0, 0, 3,
  9562. 3, 3, 1, 1, 1, 1, 0, 1,
  9563. 1, 1, 0, 1, 1, 1, 0, 3,
  9564. 3, 1, 2, 3, 3, 3, 2, 0,
  9565. 1, 0, 0, 0
  9566. };
  9567. static const char _json_range_lengths[] = {
  9568. 0, 1, 1, 1, 0, 1, 1, 1,
  9569. 1, 1, 1, 1, 0, 1, 1, 1,
  9570. 1, 1, 1, 0, 0, 0, 3, 3,
  9571. 3, 3, 0, 1, 0, 0, 0, 1,
  9572. 1, 1, 0, 0, 0, 0, 0, 0,
  9573. 0, 0, 0, 0, 0, 0, 0, 1,
  9574. 1, 0, 1, 1, 1, 1, 1, 0,
  9575. 1, 0, 0, 0
  9576. };
  9577. static const short _json_index_offsets[] = {
  9578. 0, 0, 4, 9, 14, 16, 20, 25,
  9579. 30, 35, 39, 43, 46, 50, 52, 56,
  9580. 60, 62, 64, 69, 72, 75, 85, 89,
  9581. 93, 97, 101, 104, 113, 115, 116, 117,
  9582. 122, 127, 132, 134, 136, 138, 140, 141,
  9583. 143, 145, 147, 148, 150, 152, 154, 155,
  9584. 160, 165, 167, 171, 176, 181, 186, 190,
  9585. 191, 194, 195, 196
  9586. };
  9587. static const char _json_indicies[] = {
  9588. 0, 2, 0, 1, 3, 4, 5, 3,
  9589. 1, 6, 7, 8, 6, 1, 9, 1,
  9590. 10, 11, 10, 1, 11, 1, 1, 11,
  9591. 12, 13, 14, 15, 13, 1, 16, 17,
  9592. 8, 16, 1, 17, 7, 17, 1, 18,
  9593. 19, 20, 1, 19, 20, 1, 22, 23,
  9594. 23, 21, 24, 1, 23, 23, 24, 21,
  9595. 25, 25, 26, 1, 26, 1, 26, 21,
  9596. 22, 23, 23, 20, 21, 28, 29, 27,
  9597. 31, 32, 30, 33, 33, 33, 33, 33,
  9598. 33, 33, 33, 34, 1, 35, 35, 35,
  9599. 1, 36, 36, 36, 1, 37, 37, 37,
  9600. 1, 38, 38, 38, 1, 40, 41, 39,
  9601. 42, 43, 44, 45, 46, 47, 48, 43,
  9602. 1, 49, 1, 50, 51, 53, 54, 1,
  9603. 53, 52, 55, 56, 54, 55, 1, 56,
  9604. 1, 1, 56, 52, 57, 1, 58, 1,
  9605. 59, 1, 60, 1, 61, 62, 1, 63,
  9606. 1, 64, 1, 65, 66, 1, 67, 1,
  9607. 68, 1, 69, 70, 71, 72, 70, 1,
  9608. 73, 74, 75, 73, 1, 76, 1, 77,
  9609. 78, 77, 1, 78, 1, 1, 78, 79,
  9610. 80, 81, 82, 80, 1, 83, 84, 75,
  9611. 83, 1, 84, 74, 84, 1, 85, 86,
  9612. 86, 1, 1, 1, 1, 0
  9613. };
  9614. static const char _json_trans_targs[] = {
  9615. 1, 0, 2, 3, 4, 56, 3, 4,
  9616. 56, 5, 5, 6, 7, 8, 9, 56,
  9617. 8, 9, 11, 12, 18, 57, 13, 15,
  9618. 14, 16, 17, 20, 58, 21, 20, 58,
  9619. 21, 19, 22, 23, 24, 25, 26, 20,
  9620. 58, 21, 28, 30, 31, 34, 39, 43,
  9621. 47, 29, 59, 59, 32, 31, 29, 32,
  9622. 33, 35, 36, 37, 38, 59, 40, 41,
  9623. 42, 59, 44, 45, 46, 59, 48, 49,
  9624. 55, 48, 49, 55, 50, 50, 51, 52,
  9625. 53, 54, 55, 53, 54, 59, 56
  9626. };
  9627. static const char _json_trans_actions[] = {
  9628. 0, 0, 0, 21, 77, 53, 0, 47,
  9629. 23, 17, 0, 0, 15, 19, 19, 50,
  9630. 0, 0, 0, 0, 0, 1, 0, 0,
  9631. 0, 0, 0, 3, 13, 0, 0, 35,
  9632. 5, 11, 0, 38, 7, 7, 7, 41,
  9633. 44, 9, 62, 56, 25, 0, 0, 0,
  9634. 31, 29, 33, 59, 15, 0, 27, 0,
  9635. 0, 0, 0, 0, 0, 68, 0, 0,
  9636. 0, 71, 0, 0, 0, 65, 21, 77,
  9637. 53, 0, 47, 23, 17, 0, 0, 15,
  9638. 19, 19, 50, 0, 0, 74, 0
  9639. };
  9640. static const int json_start = 1;
  9641. static const int json_en_number_machine = 10;
  9642. static const int json_en_string_machine = 19;
  9643. static const int json_en_value_machine = 27;
  9644. static const int json_en_main = 1;
  9645. #line 1249 "upb/json/parser.rl"
  9646. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  9647. const upb_bufhandle *handle) {
  9648. upb_json_parser *parser = closure;
  9649. /* Variables used by Ragel's generated code. */
  9650. int cs = parser->current_state;
  9651. int *stack = parser->parser_stack;
  9652. int top = parser->parser_top;
  9653. const char *p = buf;
  9654. const char *pe = buf + size;
  9655. parser->handle = handle;
  9656. UPB_UNUSED(hd);
  9657. UPB_UNUSED(handle);
  9658. capture_resume(parser, buf);
  9659. #line 1329 "upb/json/parser.c"
  9660. {
  9661. int _klen;
  9662. unsigned int _trans;
  9663. const char *_acts;
  9664. unsigned int _nacts;
  9665. const char *_keys;
  9666. if ( p == pe )
  9667. goto _test_eof;
  9668. if ( cs == 0 )
  9669. goto _out;
  9670. _resume:
  9671. _keys = _json_trans_keys + _json_key_offsets[cs];
  9672. _trans = _json_index_offsets[cs];
  9673. _klen = _json_single_lengths[cs];
  9674. if ( _klen > 0 ) {
  9675. const char *_lower = _keys;
  9676. const char *_mid;
  9677. const char *_upper = _keys + _klen - 1;
  9678. while (1) {
  9679. if ( _upper < _lower )
  9680. break;
  9681. _mid = _lower + ((_upper-_lower) >> 1);
  9682. if ( (*p) < *_mid )
  9683. _upper = _mid - 1;
  9684. else if ( (*p) > *_mid )
  9685. _lower = _mid + 1;
  9686. else {
  9687. _trans += (unsigned int)(_mid - _keys);
  9688. goto _match;
  9689. }
  9690. }
  9691. _keys += _klen;
  9692. _trans += _klen;
  9693. }
  9694. _klen = _json_range_lengths[cs];
  9695. if ( _klen > 0 ) {
  9696. const char *_lower = _keys;
  9697. const char *_mid;
  9698. const char *_upper = _keys + (_klen<<1) - 2;
  9699. while (1) {
  9700. if ( _upper < _lower )
  9701. break;
  9702. _mid = _lower + (((_upper-_lower) >> 1) & ~1);
  9703. if ( (*p) < _mid[0] )
  9704. _upper = _mid - 2;
  9705. else if ( (*p) > _mid[1] )
  9706. _lower = _mid + 2;
  9707. else {
  9708. _trans += (unsigned int)((_mid - _keys)>>1);
  9709. goto _match;
  9710. }
  9711. }
  9712. _trans += _klen;
  9713. }
  9714. _match:
  9715. _trans = _json_indicies[_trans];
  9716. cs = _json_trans_targs[_trans];
  9717. if ( _json_trans_actions[_trans] == 0 )
  9718. goto _again;
  9719. _acts = _json_actions + _json_trans_actions[_trans];
  9720. _nacts = (unsigned int) *_acts++;
  9721. while ( _nacts-- > 0 )
  9722. {
  9723. switch ( *_acts++ )
  9724. {
  9725. case 0:
  9726. #line 1161 "upb/json/parser.rl"
  9727. { p--; {cs = stack[--top]; goto _again;} }
  9728. break;
  9729. case 1:
  9730. #line 1162 "upb/json/parser.rl"
  9731. { p--; {stack[top++] = cs; cs = 10; goto _again;} }
  9732. break;
  9733. case 2:
  9734. #line 1166 "upb/json/parser.rl"
  9735. { start_text(parser, p); }
  9736. break;
  9737. case 3:
  9738. #line 1167 "upb/json/parser.rl"
  9739. { CHECK_RETURN_TOP(end_text(parser, p)); }
  9740. break;
  9741. case 4:
  9742. #line 1173 "upb/json/parser.rl"
  9743. { start_hex(parser); }
  9744. break;
  9745. case 5:
  9746. #line 1174 "upb/json/parser.rl"
  9747. { hexdigit(parser, p); }
  9748. break;
  9749. case 6:
  9750. #line 1175 "upb/json/parser.rl"
  9751. { CHECK_RETURN_TOP(end_hex(parser)); }
  9752. break;
  9753. case 7:
  9754. #line 1181 "upb/json/parser.rl"
  9755. { CHECK_RETURN_TOP(escape(parser, p)); }
  9756. break;
  9757. case 8:
  9758. #line 1187 "upb/json/parser.rl"
  9759. { p--; {cs = stack[--top]; goto _again;} }
  9760. break;
  9761. case 9:
  9762. #line 1190 "upb/json/parser.rl"
  9763. { {stack[top++] = cs; cs = 19; goto _again;} }
  9764. break;
  9765. case 10:
  9766. #line 1192 "upb/json/parser.rl"
  9767. { p--; {stack[top++] = cs; cs = 27; goto _again;} }
  9768. break;
  9769. case 11:
  9770. #line 1197 "upb/json/parser.rl"
  9771. { start_member(parser); }
  9772. break;
  9773. case 12:
  9774. #line 1198 "upb/json/parser.rl"
  9775. { CHECK_RETURN_TOP(end_membername(parser)); }
  9776. break;
  9777. case 13:
  9778. #line 1201 "upb/json/parser.rl"
  9779. { end_member(parser); }
  9780. break;
  9781. case 14:
  9782. #line 1207 "upb/json/parser.rl"
  9783. { start_object(parser); }
  9784. break;
  9785. case 15:
  9786. #line 1210 "upb/json/parser.rl"
  9787. { end_object(parser); }
  9788. break;
  9789. case 16:
  9790. #line 1216 "upb/json/parser.rl"
  9791. { CHECK_RETURN_TOP(start_array(parser)); }
  9792. break;
  9793. case 17:
  9794. #line 1220 "upb/json/parser.rl"
  9795. { end_array(parser); }
  9796. break;
  9797. case 18:
  9798. #line 1225 "upb/json/parser.rl"
  9799. { start_number(parser, p); }
  9800. break;
  9801. case 19:
  9802. #line 1226 "upb/json/parser.rl"
  9803. { CHECK_RETURN_TOP(end_number(parser, p)); }
  9804. break;
  9805. case 20:
  9806. #line 1228 "upb/json/parser.rl"
  9807. { CHECK_RETURN_TOP(start_stringval(parser)); }
  9808. break;
  9809. case 21:
  9810. #line 1229 "upb/json/parser.rl"
  9811. { CHECK_RETURN_TOP(end_stringval(parser)); }
  9812. break;
  9813. case 22:
  9814. #line 1231 "upb/json/parser.rl"
  9815. { CHECK_RETURN_TOP(parser_putbool(parser, true)); }
  9816. break;
  9817. case 23:
  9818. #line 1233 "upb/json/parser.rl"
  9819. { CHECK_RETURN_TOP(parser_putbool(parser, false)); }
  9820. break;
  9821. case 24:
  9822. #line 1235 "upb/json/parser.rl"
  9823. { /* null value */ }
  9824. break;
  9825. case 25:
  9826. #line 1237 "upb/json/parser.rl"
  9827. { CHECK_RETURN_TOP(start_subobject(parser)); }
  9828. break;
  9829. case 26:
  9830. #line 1238 "upb/json/parser.rl"
  9831. { end_subobject(parser); }
  9832. break;
  9833. case 27:
  9834. #line 1243 "upb/json/parser.rl"
  9835. { p--; {cs = stack[--top]; goto _again;} }
  9836. break;
  9837. #line 1515 "upb/json/parser.c"
  9838. }
  9839. }
  9840. _again:
  9841. if ( cs == 0 )
  9842. goto _out;
  9843. if ( ++p != pe )
  9844. goto _resume;
  9845. _test_eof: {}
  9846. _out: {}
  9847. }
  9848. #line 1270 "upb/json/parser.rl"
  9849. if (p != pe) {
  9850. upb_status_seterrf(&parser->status, "Parse error at %s\n", p);
  9851. upb_env_reporterror(parser->env, &parser->status);
  9852. } else {
  9853. capture_suspend(parser, &p);
  9854. }
  9855. error:
  9856. /* Save parsing state back to parser. */
  9857. parser->current_state = cs;
  9858. parser->parser_top = top;
  9859. return p - buf;
  9860. }
  9861. bool end(void *closure, const void *hd) {
  9862. UPB_UNUSED(closure);
  9863. UPB_UNUSED(hd);
  9864. /* Prevent compile warning on unused static constants. */
  9865. UPB_UNUSED(json_start);
  9866. UPB_UNUSED(json_en_number_machine);
  9867. UPB_UNUSED(json_en_string_machine);
  9868. UPB_UNUSED(json_en_value_machine);
  9869. UPB_UNUSED(json_en_main);
  9870. return true;
  9871. }
  9872. static void json_parser_reset(upb_json_parser *p) {
  9873. int cs;
  9874. int top;
  9875. p->top = p->stack;
  9876. p->top->f = NULL;
  9877. p->top->is_map = false;
  9878. p->top->is_mapentry = false;
  9879. /* Emit Ragel initialization of the parser. */
  9880. #line 1569 "upb/json/parser.c"
  9881. {
  9882. cs = json_start;
  9883. top = 0;
  9884. }
  9885. #line 1310 "upb/json/parser.rl"
  9886. p->current_state = cs;
  9887. p->parser_top = top;
  9888. accumulate_clear(p);
  9889. p->multipart_state = MULTIPART_INACTIVE;
  9890. p->capture = NULL;
  9891. p->accumulated = NULL;
  9892. upb_status_clear(&p->status);
  9893. }
  9894. static void visit_json_parsermethod(const upb_refcounted *r,
  9895. upb_refcounted_visit *visit,
  9896. void *closure) {
  9897. const upb_json_parsermethod *method = (upb_json_parsermethod*)r;
  9898. visit(r, upb_msgdef_upcast2(method->msg), closure);
  9899. }
  9900. static void free_json_parsermethod(upb_refcounted *r) {
  9901. upb_json_parsermethod *method = (upb_json_parsermethod*)r;
  9902. upb_inttable_iter i;
  9903. upb_inttable_begin(&i, &method->name_tables);
  9904. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  9905. upb_value val = upb_inttable_iter_value(&i);
  9906. upb_strtable *t = upb_value_getptr(val);
  9907. upb_strtable_uninit(t);
  9908. free(t);
  9909. }
  9910. upb_inttable_uninit(&method->name_tables);
  9911. free(r);
  9912. }
  9913. static void add_jsonname_table(upb_json_parsermethod *m, const upb_msgdef* md) {
  9914. upb_msg_field_iter i;
  9915. upb_strtable *t;
  9916. /* It would be nice to stack-allocate this, but protobufs do not limit the
  9917. * length of fields to any reasonable limit. */
  9918. char *buf = NULL;
  9919. size_t len = 0;
  9920. if (upb_inttable_lookupptr(&m->name_tables, md, NULL)) {
  9921. return;
  9922. }
  9923. /* TODO(haberman): handle malloc failure. */
  9924. t = malloc(sizeof(*t));
  9925. upb_strtable_init(t, UPB_CTYPE_CONSTPTR);
  9926. upb_inttable_insertptr(&m->name_tables, md, upb_value_ptr(t));
  9927. for(upb_msg_field_begin(&i, md);
  9928. !upb_msg_field_done(&i);
  9929. upb_msg_field_next(&i)) {
  9930. const upb_fielddef *f = upb_msg_iter_field(&i);
  9931. size_t field_len = upb_fielddef_getjsonname(f, buf, len);
  9932. if (field_len > len) {
  9933. buf = realloc(buf, field_len);
  9934. len = field_len;
  9935. upb_fielddef_getjsonname(f, buf, len);
  9936. }
  9937. upb_strtable_insert(t, buf, upb_value_constptr(f));
  9938. if (upb_fielddef_issubmsg(f)) {
  9939. add_jsonname_table(m, upb_fielddef_msgsubdef(f));
  9940. }
  9941. }
  9942. free(buf);
  9943. }
  9944. /* Public API *****************************************************************/
  9945. upb_json_parser *upb_json_parser_create(upb_env *env,
  9946. const upb_json_parsermethod *method,
  9947. upb_sink *output) {
  9948. #ifndef NDEBUG
  9949. const size_t size_before = upb_env_bytesallocated(env);
  9950. #endif
  9951. upb_json_parser *p = upb_env_malloc(env, sizeof(upb_json_parser));
  9952. if (!p) return false;
  9953. p->env = env;
  9954. p->method = method;
  9955. p->limit = p->stack + UPB_JSON_MAX_DEPTH;
  9956. p->accumulate_buf = NULL;
  9957. p->accumulate_buf_size = 0;
  9958. upb_bytessink_reset(&p->input_, &method->input_handler_, p);
  9959. json_parser_reset(p);
  9960. upb_sink_reset(&p->top->sink, output->handlers, output->closure);
  9961. p->top->m = upb_handlers_msgdef(output->handlers);
  9962. set_name_table(p, p->top);
  9963. /* If this fails, uncomment and increase the value in parser.h. */
  9964. /* fprintf(stderr, "%zd\n", upb_env_bytesallocated(env) - size_before); */
  9965. assert(upb_env_bytesallocated(env) - size_before <= UPB_JSON_PARSER_SIZE);
  9966. return p;
  9967. }
  9968. upb_bytessink *upb_json_parser_input(upb_json_parser *p) {
  9969. return &p->input_;
  9970. }
  9971. upb_json_parsermethod *upb_json_parsermethod_new(const upb_msgdef* md,
  9972. const void* owner) {
  9973. static const struct upb_refcounted_vtbl vtbl = {visit_json_parsermethod,
  9974. free_json_parsermethod};
  9975. upb_json_parsermethod *ret = malloc(sizeof(*ret));
  9976. upb_refcounted_init(upb_json_parsermethod_upcast_mutable(ret), &vtbl, owner);
  9977. ret->msg = md;
  9978. upb_ref2(md, ret);
  9979. upb_byteshandler_init(&ret->input_handler_);
  9980. upb_byteshandler_setstring(&ret->input_handler_, parse, ret);
  9981. upb_byteshandler_setendstr(&ret->input_handler_, end, ret);
  9982. upb_inttable_init(&ret->name_tables, UPB_CTYPE_PTR);
  9983. add_jsonname_table(ret, md);
  9984. return ret;
  9985. }
  9986. const upb_byteshandler *upb_json_parsermethod_inputhandler(
  9987. const upb_json_parsermethod *m) {
  9988. return &m->input_handler_;
  9989. }
  9990. /*
  9991. ** This currently uses snprintf() to format primitives, and could be optimized
  9992. ** further.
  9993. */
  9994. #include <stdlib.h>
  9995. #include <stdio.h>
  9996. #include <string.h>
  9997. #include <stdint.h>
  9998. struct upb_json_printer {
  9999. upb_sink input_;
  10000. /* BytesSink closure. */
  10001. void *subc_;
  10002. upb_bytessink *output_;
  10003. /* We track the depth so that we know when to emit startstr/endstr on the
  10004. * output. */
  10005. int depth_;
  10006. /* Have we emitted the first element? This state is necessary to emit commas
  10007. * without leaving a trailing comma in arrays/maps. We keep this state per
  10008. * frame depth.
  10009. *
  10010. * Why max_depth * 2? UPB_MAX_HANDLER_DEPTH counts depth as nested messages.
  10011. * We count frames (contexts in which we separate elements by commas) as both
  10012. * repeated fields and messages (maps), and the worst case is a
  10013. * message->repeated field->submessage->repeated field->... nesting. */
  10014. bool first_elem_[UPB_MAX_HANDLER_DEPTH * 2];
  10015. };
  10016. /* StringPiece; a pointer plus a length. */
  10017. typedef struct {
  10018. char *ptr;
  10019. size_t len;
  10020. } strpc;
  10021. void freestrpc(void *ptr) {
  10022. strpc *pc = ptr;
  10023. free(pc->ptr);
  10024. free(pc);
  10025. }
  10026. /* Convert fielddef name to JSON name and return as a string piece. */
  10027. strpc *newstrpc(upb_handlers *h, const upb_fielddef *f) {
  10028. /* TODO(haberman): handle malloc failure. */
  10029. strpc *ret = malloc(sizeof(*ret));
  10030. size_t len;
  10031. ret->len = upb_fielddef_getjsonname(f, NULL, 0);
  10032. ret->ptr = malloc(ret->len);
  10033. len = upb_fielddef_getjsonname(f, ret->ptr, ret->len);
  10034. UPB_ASSERT_VAR(len, len == ret->len);
  10035. ret->len--; /* NULL */
  10036. upb_handlers_addcleanup(h, ret, freestrpc);
  10037. return ret;
  10038. }
  10039. /* ------------ JSON string printing: values, maps, arrays ------------------ */
  10040. static void print_data(
  10041. upb_json_printer *p, const char *buf, unsigned int len) {
  10042. /* TODO: Will need to change if we support pushback from the sink. */
  10043. size_t n = upb_bytessink_putbuf(p->output_, p->subc_, buf, len, NULL);
  10044. UPB_ASSERT_VAR(n, n == len);
  10045. }
  10046. static void print_comma(upb_json_printer *p) {
  10047. if (!p->first_elem_[p->depth_]) {
  10048. print_data(p, ",", 1);
  10049. }
  10050. p->first_elem_[p->depth_] = false;
  10051. }
  10052. /* Helpers that print properly formatted elements to the JSON output stream. */
  10053. /* Used for escaping control chars in strings. */
  10054. static const char kControlCharLimit = 0x20;
  10055. UPB_INLINE bool is_json_escaped(char c) {
  10056. /* See RFC 4627. */
  10057. unsigned char uc = (unsigned char)c;
  10058. return uc < kControlCharLimit || uc == '"' || uc == '\\';
  10059. }
  10060. UPB_INLINE const char* json_nice_escape(char c) {
  10061. switch (c) {
  10062. case '"': return "\\\"";
  10063. case '\\': return "\\\\";
  10064. case '\b': return "\\b";
  10065. case '\f': return "\\f";
  10066. case '\n': return "\\n";
  10067. case '\r': return "\\r";
  10068. case '\t': return "\\t";
  10069. default: return NULL;
  10070. }
  10071. }
  10072. /* Write a properly escaped string chunk. The surrounding quotes are *not*
  10073. * printed; this is so that the caller has the option of emitting the string
  10074. * content in chunks. */
  10075. static void putstring(upb_json_printer *p, const char *buf, unsigned int len) {
  10076. const char* unescaped_run = NULL;
  10077. unsigned int i;
  10078. for (i = 0; i < len; i++) {
  10079. char c = buf[i];
  10080. /* Handle escaping. */
  10081. if (is_json_escaped(c)) {
  10082. /* Use a "nice" escape, like \n, if one exists for this character. */
  10083. const char* escape = json_nice_escape(c);
  10084. /* If we don't have a specific 'nice' escape code, use a \uXXXX-style
  10085. * escape. */
  10086. char escape_buf[8];
  10087. if (!escape) {
  10088. unsigned char byte = (unsigned char)c;
  10089. _upb_snprintf(escape_buf, sizeof(escape_buf), "\\u%04x", (int)byte);
  10090. escape = escape_buf;
  10091. }
  10092. /* N.B. that we assume that the input encoding is equal to the output
  10093. * encoding (both UTF-8 for now), so for chars >= 0x20 and != \, ", we
  10094. * can simply pass the bytes through. */
  10095. /* If there's a current run of unescaped chars, print that run first. */
  10096. if (unescaped_run) {
  10097. print_data(p, unescaped_run, &buf[i] - unescaped_run);
  10098. unescaped_run = NULL;
  10099. }
  10100. /* Then print the escape code. */
  10101. print_data(p, escape, strlen(escape));
  10102. } else {
  10103. /* Add to the current unescaped run of characters. */
  10104. if (unescaped_run == NULL) {
  10105. unescaped_run = &buf[i];
  10106. }
  10107. }
  10108. }
  10109. /* If the string ended in a run of unescaped characters, print that last run. */
  10110. if (unescaped_run) {
  10111. print_data(p, unescaped_run, &buf[len] - unescaped_run);
  10112. }
  10113. }
  10114. #define CHKLENGTH(x) if (!(x)) return -1;
  10115. /* Helpers that format floating point values according to our custom formats.
  10116. * Right now we use %.8g and %.17g for float/double, respectively, to match
  10117. * proto2::util::JsonFormat's defaults. May want to change this later. */
  10118. static size_t fmt_double(double val, char* buf, size_t length) {
  10119. size_t n = _upb_snprintf(buf, length, "%.17g", val);
  10120. CHKLENGTH(n > 0 && n < length);
  10121. return n;
  10122. }
  10123. static size_t fmt_float(float val, char* buf, size_t length) {
  10124. size_t n = _upb_snprintf(buf, length, "%.8g", val);
  10125. CHKLENGTH(n > 0 && n < length);
  10126. return n;
  10127. }
  10128. static size_t fmt_bool(bool val, char* buf, size_t length) {
  10129. size_t n = _upb_snprintf(buf, length, "%s", (val ? "true" : "false"));
  10130. CHKLENGTH(n > 0 && n < length);
  10131. return n;
  10132. }
  10133. static size_t fmt_int64(long val, char* buf, size_t length) {
  10134. size_t n = _upb_snprintf(buf, length, "%ld", val);
  10135. CHKLENGTH(n > 0 && n < length);
  10136. return n;
  10137. }
  10138. static size_t fmt_uint64(unsigned long long val, char* buf, size_t length) {
  10139. size_t n = _upb_snprintf(buf, length, "%llu", val);
  10140. CHKLENGTH(n > 0 && n < length);
  10141. return n;
  10142. }
  10143. /* Print a map key given a field name. Called by scalar field handlers and by
  10144. * startseq for repeated fields. */
  10145. static bool putkey(void *closure, const void *handler_data) {
  10146. upb_json_printer *p = closure;
  10147. const strpc *key = handler_data;
  10148. print_comma(p);
  10149. print_data(p, "\"", 1);
  10150. putstring(p, key->ptr, key->len);
  10151. print_data(p, "\":", 2);
  10152. return true;
  10153. }
  10154. #define CHKFMT(val) if ((val) == (size_t)-1) return false;
  10155. #define CHK(val) if (!(val)) return false;
  10156. #define TYPE_HANDLERS(type, fmt_func) \
  10157. static bool put##type(void *closure, const void *handler_data, type val) { \
  10158. upb_json_printer *p = closure; \
  10159. char data[64]; \
  10160. size_t length = fmt_func(val, data, sizeof(data)); \
  10161. UPB_UNUSED(handler_data); \
  10162. CHKFMT(length); \
  10163. print_data(p, data, length); \
  10164. return true; \
  10165. } \
  10166. static bool scalar_##type(void *closure, const void *handler_data, \
  10167. type val) { \
  10168. CHK(putkey(closure, handler_data)); \
  10169. CHK(put##type(closure, handler_data, val)); \
  10170. return true; \
  10171. } \
  10172. static bool repeated_##type(void *closure, const void *handler_data, \
  10173. type val) { \
  10174. upb_json_printer *p = closure; \
  10175. print_comma(p); \
  10176. CHK(put##type(closure, handler_data, val)); \
  10177. return true; \
  10178. }
  10179. #define TYPE_HANDLERS_MAPKEY(type, fmt_func) \
  10180. static bool putmapkey_##type(void *closure, const void *handler_data, \
  10181. type val) { \
  10182. upb_json_printer *p = closure; \
  10183. print_data(p, "\"", 1); \
  10184. CHK(put##type(closure, handler_data, val)); \
  10185. print_data(p, "\":", 2); \
  10186. return true; \
  10187. }
  10188. TYPE_HANDLERS(double, fmt_double)
  10189. TYPE_HANDLERS(float, fmt_float)
  10190. TYPE_HANDLERS(bool, fmt_bool)
  10191. TYPE_HANDLERS(int32_t, fmt_int64)
  10192. TYPE_HANDLERS(uint32_t, fmt_int64)
  10193. TYPE_HANDLERS(int64_t, fmt_int64)
  10194. TYPE_HANDLERS(uint64_t, fmt_uint64)
  10195. /* double and float are not allowed to be map keys. */
  10196. TYPE_HANDLERS_MAPKEY(bool, fmt_bool)
  10197. TYPE_HANDLERS_MAPKEY(int32_t, fmt_int64)
  10198. TYPE_HANDLERS_MAPKEY(uint32_t, fmt_int64)
  10199. TYPE_HANDLERS_MAPKEY(int64_t, fmt_int64)
  10200. TYPE_HANDLERS_MAPKEY(uint64_t, fmt_uint64)
  10201. #undef TYPE_HANDLERS
  10202. #undef TYPE_HANDLERS_MAPKEY
  10203. typedef struct {
  10204. void *keyname;
  10205. const upb_enumdef *enumdef;
  10206. } EnumHandlerData;
  10207. static bool scalar_enum(void *closure, const void *handler_data,
  10208. int32_t val) {
  10209. const EnumHandlerData *hd = handler_data;
  10210. upb_json_printer *p = closure;
  10211. const char *symbolic_name;
  10212. CHK(putkey(closure, hd->keyname));
  10213. symbolic_name = upb_enumdef_iton(hd->enumdef, val);
  10214. if (symbolic_name) {
  10215. print_data(p, "\"", 1);
  10216. putstring(p, symbolic_name, strlen(symbolic_name));
  10217. print_data(p, "\"", 1);
  10218. } else {
  10219. putint32_t(closure, NULL, val);
  10220. }
  10221. return true;
  10222. }
  10223. static void print_enum_symbolic_name(upb_json_printer *p,
  10224. const upb_enumdef *def,
  10225. int32_t val) {
  10226. const char *symbolic_name = upb_enumdef_iton(def, val);
  10227. if (symbolic_name) {
  10228. print_data(p, "\"", 1);
  10229. putstring(p, symbolic_name, strlen(symbolic_name));
  10230. print_data(p, "\"", 1);
  10231. } else {
  10232. putint32_t(p, NULL, val);
  10233. }
  10234. }
  10235. static bool repeated_enum(void *closure, const void *handler_data,
  10236. int32_t val) {
  10237. const EnumHandlerData *hd = handler_data;
  10238. upb_json_printer *p = closure;
  10239. print_comma(p);
  10240. print_enum_symbolic_name(p, hd->enumdef, val);
  10241. return true;
  10242. }
  10243. static bool mapvalue_enum(void *closure, const void *handler_data,
  10244. int32_t val) {
  10245. const EnumHandlerData *hd = handler_data;
  10246. upb_json_printer *p = closure;
  10247. print_enum_symbolic_name(p, hd->enumdef, val);
  10248. return true;
  10249. }
  10250. static void *scalar_startsubmsg(void *closure, const void *handler_data) {
  10251. return putkey(closure, handler_data) ? closure : UPB_BREAK;
  10252. }
  10253. static void *repeated_startsubmsg(void *closure, const void *handler_data) {
  10254. upb_json_printer *p = closure;
  10255. UPB_UNUSED(handler_data);
  10256. print_comma(p);
  10257. return closure;
  10258. }
  10259. static void start_frame(upb_json_printer *p) {
  10260. p->depth_++;
  10261. p->first_elem_[p->depth_] = true;
  10262. print_data(p, "{", 1);
  10263. }
  10264. static void end_frame(upb_json_printer *p) {
  10265. print_data(p, "}", 1);
  10266. p->depth_--;
  10267. }
  10268. static bool printer_startmsg(void *closure, const void *handler_data) {
  10269. upb_json_printer *p = closure;
  10270. UPB_UNUSED(handler_data);
  10271. if (p->depth_ == 0) {
  10272. upb_bytessink_start(p->output_, 0, &p->subc_);
  10273. }
  10274. start_frame(p);
  10275. return true;
  10276. }
  10277. static bool printer_endmsg(void *closure, const void *handler_data, upb_status *s) {
  10278. upb_json_printer *p = closure;
  10279. UPB_UNUSED(handler_data);
  10280. UPB_UNUSED(s);
  10281. end_frame(p);
  10282. if (p->depth_ == 0) {
  10283. upb_bytessink_end(p->output_);
  10284. }
  10285. return true;
  10286. }
  10287. static void *startseq(void *closure, const void *handler_data) {
  10288. upb_json_printer *p = closure;
  10289. CHK(putkey(closure, handler_data));
  10290. p->depth_++;
  10291. p->first_elem_[p->depth_] = true;
  10292. print_data(p, "[", 1);
  10293. return closure;
  10294. }
  10295. static bool endseq(void *closure, const void *handler_data) {
  10296. upb_json_printer *p = closure;
  10297. UPB_UNUSED(handler_data);
  10298. print_data(p, "]", 1);
  10299. p->depth_--;
  10300. return true;
  10301. }
  10302. static void *startmap(void *closure, const void *handler_data) {
  10303. upb_json_printer *p = closure;
  10304. CHK(putkey(closure, handler_data));
  10305. p->depth_++;
  10306. p->first_elem_[p->depth_] = true;
  10307. print_data(p, "{", 1);
  10308. return closure;
  10309. }
  10310. static bool endmap(void *closure, const void *handler_data) {
  10311. upb_json_printer *p = closure;
  10312. UPB_UNUSED(handler_data);
  10313. print_data(p, "}", 1);
  10314. p->depth_--;
  10315. return true;
  10316. }
  10317. static size_t putstr(void *closure, const void *handler_data, const char *str,
  10318. size_t len, const upb_bufhandle *handle) {
  10319. upb_json_printer *p = closure;
  10320. UPB_UNUSED(handler_data);
  10321. UPB_UNUSED(handle);
  10322. putstring(p, str, len);
  10323. return len;
  10324. }
  10325. /* This has to Base64 encode the bytes, because JSON has no "bytes" type. */
  10326. static size_t putbytes(void *closure, const void *handler_data, const char *str,
  10327. size_t len, const upb_bufhandle *handle) {
  10328. upb_json_printer *p = closure;
  10329. /* This is the regular base64, not the "web-safe" version. */
  10330. static const char base64[] =
  10331. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  10332. /* Base64-encode. */
  10333. char data[16000];
  10334. const char *limit = data + sizeof(data);
  10335. const unsigned char *from = (const unsigned char*)str;
  10336. char *to = data;
  10337. size_t remaining = len;
  10338. size_t bytes;
  10339. UPB_UNUSED(handler_data);
  10340. UPB_UNUSED(handle);
  10341. while (remaining > 2) {
  10342. /* TODO(haberman): handle encoded lengths > sizeof(data) */
  10343. UPB_ASSERT_VAR(limit, (limit - to) >= 4);
  10344. to[0] = base64[from[0] >> 2];
  10345. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  10346. to[2] = base64[((from[1] & 0xf) << 2) | (from[2] >> 6)];
  10347. to[3] = base64[from[2] & 0x3f];
  10348. remaining -= 3;
  10349. to += 4;
  10350. from += 3;
  10351. }
  10352. switch (remaining) {
  10353. case 2:
  10354. to[0] = base64[from[0] >> 2];
  10355. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  10356. to[2] = base64[(from[1] & 0xf) << 2];
  10357. to[3] = '=';
  10358. to += 4;
  10359. from += 2;
  10360. break;
  10361. case 1:
  10362. to[0] = base64[from[0] >> 2];
  10363. to[1] = base64[((from[0] & 0x3) << 4)];
  10364. to[2] = '=';
  10365. to[3] = '=';
  10366. to += 4;
  10367. from += 1;
  10368. break;
  10369. }
  10370. bytes = to - data;
  10371. print_data(p, "\"", 1);
  10372. putstring(p, data, bytes);
  10373. print_data(p, "\"", 1);
  10374. return len;
  10375. }
  10376. static void *scalar_startstr(void *closure, const void *handler_data,
  10377. size_t size_hint) {
  10378. upb_json_printer *p = closure;
  10379. UPB_UNUSED(handler_data);
  10380. UPB_UNUSED(size_hint);
  10381. CHK(putkey(closure, handler_data));
  10382. print_data(p, "\"", 1);
  10383. return p;
  10384. }
  10385. static size_t scalar_str(void *closure, const void *handler_data,
  10386. const char *str, size_t len,
  10387. const upb_bufhandle *handle) {
  10388. CHK(putstr(closure, handler_data, str, len, handle));
  10389. return len;
  10390. }
  10391. static bool scalar_endstr(void *closure, const void *handler_data) {
  10392. upb_json_printer *p = closure;
  10393. UPB_UNUSED(handler_data);
  10394. print_data(p, "\"", 1);
  10395. return true;
  10396. }
  10397. static void *repeated_startstr(void *closure, const void *handler_data,
  10398. size_t size_hint) {
  10399. upb_json_printer *p = closure;
  10400. UPB_UNUSED(handler_data);
  10401. UPB_UNUSED(size_hint);
  10402. print_comma(p);
  10403. print_data(p, "\"", 1);
  10404. return p;
  10405. }
  10406. static size_t repeated_str(void *closure, const void *handler_data,
  10407. const char *str, size_t len,
  10408. const upb_bufhandle *handle) {
  10409. CHK(putstr(closure, handler_data, str, len, handle));
  10410. return len;
  10411. }
  10412. static bool repeated_endstr(void *closure, const void *handler_data) {
  10413. upb_json_printer *p = closure;
  10414. UPB_UNUSED(handler_data);
  10415. print_data(p, "\"", 1);
  10416. return true;
  10417. }
  10418. static void *mapkeyval_startstr(void *closure, const void *handler_data,
  10419. size_t size_hint) {
  10420. upb_json_printer *p = closure;
  10421. UPB_UNUSED(handler_data);
  10422. UPB_UNUSED(size_hint);
  10423. print_data(p, "\"", 1);
  10424. return p;
  10425. }
  10426. static size_t mapkey_str(void *closure, const void *handler_data,
  10427. const char *str, size_t len,
  10428. const upb_bufhandle *handle) {
  10429. CHK(putstr(closure, handler_data, str, len, handle));
  10430. return len;
  10431. }
  10432. static bool mapkey_endstr(void *closure, const void *handler_data) {
  10433. upb_json_printer *p = closure;
  10434. UPB_UNUSED(handler_data);
  10435. print_data(p, "\":", 2);
  10436. return true;
  10437. }
  10438. static bool mapvalue_endstr(void *closure, const void *handler_data) {
  10439. upb_json_printer *p = closure;
  10440. UPB_UNUSED(handler_data);
  10441. print_data(p, "\"", 1);
  10442. return true;
  10443. }
  10444. static size_t scalar_bytes(void *closure, const void *handler_data,
  10445. const char *str, size_t len,
  10446. const upb_bufhandle *handle) {
  10447. CHK(putkey(closure, handler_data));
  10448. CHK(putbytes(closure, handler_data, str, len, handle));
  10449. return len;
  10450. }
  10451. static size_t repeated_bytes(void *closure, const void *handler_data,
  10452. const char *str, size_t len,
  10453. const upb_bufhandle *handle) {
  10454. upb_json_printer *p = closure;
  10455. print_comma(p);
  10456. CHK(putbytes(closure, handler_data, str, len, handle));
  10457. return len;
  10458. }
  10459. static size_t mapkey_bytes(void *closure, const void *handler_data,
  10460. const char *str, size_t len,
  10461. const upb_bufhandle *handle) {
  10462. upb_json_printer *p = closure;
  10463. CHK(putbytes(closure, handler_data, str, len, handle));
  10464. print_data(p, ":", 1);
  10465. return len;
  10466. }
  10467. static void set_enum_hd(upb_handlers *h,
  10468. const upb_fielddef *f,
  10469. upb_handlerattr *attr) {
  10470. EnumHandlerData *hd = malloc(sizeof(EnumHandlerData));
  10471. hd->enumdef = (const upb_enumdef *)upb_fielddef_subdef(f);
  10472. hd->keyname = newstrpc(h, f);
  10473. upb_handlers_addcleanup(h, hd, free);
  10474. upb_handlerattr_sethandlerdata(attr, hd);
  10475. }
  10476. /* Set up handlers for a mapentry submessage (i.e., an individual key/value pair
  10477. * in a map).
  10478. *
  10479. * TODO: Handle missing key, missing value, out-of-order key/value, or repeated
  10480. * key or value cases properly. The right way to do this is to allocate a
  10481. * temporary structure at the start of a mapentry submessage, store key and
  10482. * value data in it as key and value handlers are called, and then print the
  10483. * key/value pair once at the end of the submessage. If we don't do this, we
  10484. * should at least detect the case and throw an error. However, so far all of
  10485. * our sources that emit mapentry messages do so canonically (with one key
  10486. * field, and then one value field), so this is not a pressing concern at the
  10487. * moment. */
  10488. void printer_sethandlers_mapentry(const void *closure, upb_handlers *h) {
  10489. const upb_msgdef *md = upb_handlers_msgdef(h);
  10490. /* A mapentry message is printed simply as '"key": value'. Rather than
  10491. * special-case key and value for every type below, we just handle both
  10492. * fields explicitly here. */
  10493. const upb_fielddef* key_field = upb_msgdef_itof(md, UPB_MAPENTRY_KEY);
  10494. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_MAPENTRY_VALUE);
  10495. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  10496. UPB_UNUSED(closure);
  10497. switch (upb_fielddef_type(key_field)) {
  10498. case UPB_TYPE_INT32:
  10499. upb_handlers_setint32(h, key_field, putmapkey_int32_t, &empty_attr);
  10500. break;
  10501. case UPB_TYPE_INT64:
  10502. upb_handlers_setint64(h, key_field, putmapkey_int64_t, &empty_attr);
  10503. break;
  10504. case UPB_TYPE_UINT32:
  10505. upb_handlers_setuint32(h, key_field, putmapkey_uint32_t, &empty_attr);
  10506. break;
  10507. case UPB_TYPE_UINT64:
  10508. upb_handlers_setuint64(h, key_field, putmapkey_uint64_t, &empty_attr);
  10509. break;
  10510. case UPB_TYPE_BOOL:
  10511. upb_handlers_setbool(h, key_field, putmapkey_bool, &empty_attr);
  10512. break;
  10513. case UPB_TYPE_STRING:
  10514. upb_handlers_setstartstr(h, key_field, mapkeyval_startstr, &empty_attr);
  10515. upb_handlers_setstring(h, key_field, mapkey_str, &empty_attr);
  10516. upb_handlers_setendstr(h, key_field, mapkey_endstr, &empty_attr);
  10517. break;
  10518. case UPB_TYPE_BYTES:
  10519. upb_handlers_setstring(h, key_field, mapkey_bytes, &empty_attr);
  10520. break;
  10521. default:
  10522. assert(false);
  10523. break;
  10524. }
  10525. switch (upb_fielddef_type(value_field)) {
  10526. case UPB_TYPE_INT32:
  10527. upb_handlers_setint32(h, value_field, putint32_t, &empty_attr);
  10528. break;
  10529. case UPB_TYPE_INT64:
  10530. upb_handlers_setint64(h, value_field, putint64_t, &empty_attr);
  10531. break;
  10532. case UPB_TYPE_UINT32:
  10533. upb_handlers_setuint32(h, value_field, putuint32_t, &empty_attr);
  10534. break;
  10535. case UPB_TYPE_UINT64:
  10536. upb_handlers_setuint64(h, value_field, putuint64_t, &empty_attr);
  10537. break;
  10538. case UPB_TYPE_BOOL:
  10539. upb_handlers_setbool(h, value_field, putbool, &empty_attr);
  10540. break;
  10541. case UPB_TYPE_FLOAT:
  10542. upb_handlers_setfloat(h, value_field, putfloat, &empty_attr);
  10543. break;
  10544. case UPB_TYPE_DOUBLE:
  10545. upb_handlers_setdouble(h, value_field, putdouble, &empty_attr);
  10546. break;
  10547. case UPB_TYPE_STRING:
  10548. upb_handlers_setstartstr(h, value_field, mapkeyval_startstr, &empty_attr);
  10549. upb_handlers_setstring(h, value_field, putstr, &empty_attr);
  10550. upb_handlers_setendstr(h, value_field, mapvalue_endstr, &empty_attr);
  10551. break;
  10552. case UPB_TYPE_BYTES:
  10553. upb_handlers_setstring(h, value_field, putbytes, &empty_attr);
  10554. break;
  10555. case UPB_TYPE_ENUM: {
  10556. upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
  10557. set_enum_hd(h, value_field, &enum_attr);
  10558. upb_handlers_setint32(h, value_field, mapvalue_enum, &enum_attr);
  10559. upb_handlerattr_uninit(&enum_attr);
  10560. break;
  10561. }
  10562. case UPB_TYPE_MESSAGE:
  10563. /* No handler necessary -- the submsg handlers will print the message
  10564. * as appropriate. */
  10565. break;
  10566. }
  10567. upb_handlerattr_uninit(&empty_attr);
  10568. }
  10569. void printer_sethandlers(const void *closure, upb_handlers *h) {
  10570. const upb_msgdef *md = upb_handlers_msgdef(h);
  10571. bool is_mapentry = upb_msgdef_mapentry(md);
  10572. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  10573. upb_msg_field_iter i;
  10574. UPB_UNUSED(closure);
  10575. if (is_mapentry) {
  10576. /* mapentry messages are sufficiently different that we handle them
  10577. * separately. */
  10578. printer_sethandlers_mapentry(closure, h);
  10579. return;
  10580. }
  10581. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  10582. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  10583. #define TYPE(type, name, ctype) \
  10584. case type: \
  10585. if (upb_fielddef_isseq(f)) { \
  10586. upb_handlers_set##name(h, f, repeated_##ctype, &empty_attr); \
  10587. } else { \
  10588. upb_handlers_set##name(h, f, scalar_##ctype, &name_attr); \
  10589. } \
  10590. break;
  10591. upb_msg_field_begin(&i, md);
  10592. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  10593. const upb_fielddef *f = upb_msg_iter_field(&i);
  10594. upb_handlerattr name_attr = UPB_HANDLERATTR_INITIALIZER;
  10595. upb_handlerattr_sethandlerdata(&name_attr, newstrpc(h, f));
  10596. if (upb_fielddef_ismap(f)) {
  10597. upb_handlers_setstartseq(h, f, startmap, &name_attr);
  10598. upb_handlers_setendseq(h, f, endmap, &name_attr);
  10599. } else if (upb_fielddef_isseq(f)) {
  10600. upb_handlers_setstartseq(h, f, startseq, &name_attr);
  10601. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  10602. }
  10603. switch (upb_fielddef_type(f)) {
  10604. TYPE(UPB_TYPE_FLOAT, float, float);
  10605. TYPE(UPB_TYPE_DOUBLE, double, double);
  10606. TYPE(UPB_TYPE_BOOL, bool, bool);
  10607. TYPE(UPB_TYPE_INT32, int32, int32_t);
  10608. TYPE(UPB_TYPE_UINT32, uint32, uint32_t);
  10609. TYPE(UPB_TYPE_INT64, int64, int64_t);
  10610. TYPE(UPB_TYPE_UINT64, uint64, uint64_t);
  10611. case UPB_TYPE_ENUM: {
  10612. /* For now, we always emit symbolic names for enums. We may want an
  10613. * option later to control this behavior, but we will wait for a real
  10614. * need first. */
  10615. upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
  10616. set_enum_hd(h, f, &enum_attr);
  10617. if (upb_fielddef_isseq(f)) {
  10618. upb_handlers_setint32(h, f, repeated_enum, &enum_attr);
  10619. } else {
  10620. upb_handlers_setint32(h, f, scalar_enum, &enum_attr);
  10621. }
  10622. upb_handlerattr_uninit(&enum_attr);
  10623. break;
  10624. }
  10625. case UPB_TYPE_STRING:
  10626. if (upb_fielddef_isseq(f)) {
  10627. upb_handlers_setstartstr(h, f, repeated_startstr, &empty_attr);
  10628. upb_handlers_setstring(h, f, repeated_str, &empty_attr);
  10629. upb_handlers_setendstr(h, f, repeated_endstr, &empty_attr);
  10630. } else {
  10631. upb_handlers_setstartstr(h, f, scalar_startstr, &name_attr);
  10632. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  10633. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  10634. }
  10635. break;
  10636. case UPB_TYPE_BYTES:
  10637. /* XXX: this doesn't support strings that span buffers yet. The base64
  10638. * encoder will need to be made resumable for this to work properly. */
  10639. if (upb_fielddef_isseq(f)) {
  10640. upb_handlers_setstring(h, f, repeated_bytes, &empty_attr);
  10641. } else {
  10642. upb_handlers_setstring(h, f, scalar_bytes, &name_attr);
  10643. }
  10644. break;
  10645. case UPB_TYPE_MESSAGE:
  10646. if (upb_fielddef_isseq(f)) {
  10647. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &name_attr);
  10648. } else {
  10649. upb_handlers_setstartsubmsg(h, f, scalar_startsubmsg, &name_attr);
  10650. }
  10651. break;
  10652. }
  10653. upb_handlerattr_uninit(&name_attr);
  10654. }
  10655. upb_handlerattr_uninit(&empty_attr);
  10656. #undef TYPE
  10657. }
  10658. static void json_printer_reset(upb_json_printer *p) {
  10659. p->depth_ = 0;
  10660. }
  10661. /* Public API *****************************************************************/
  10662. upb_json_printer *upb_json_printer_create(upb_env *e, const upb_handlers *h,
  10663. upb_bytessink *output) {
  10664. #ifndef NDEBUG
  10665. size_t size_before = upb_env_bytesallocated(e);
  10666. #endif
  10667. upb_json_printer *p = upb_env_malloc(e, sizeof(upb_json_printer));
  10668. if (!p) return NULL;
  10669. p->output_ = output;
  10670. json_printer_reset(p);
  10671. upb_sink_reset(&p->input_, h, p);
  10672. /* If this fails, increase the value in printer.h. */
  10673. assert(upb_env_bytesallocated(e) - size_before <= UPB_JSON_PRINTER_SIZE);
  10674. return p;
  10675. }
  10676. upb_sink *upb_json_printer_input(upb_json_printer *p) {
  10677. return &p->input_;
  10678. }
  10679. const upb_handlers *upb_json_printer_newhandlers(const upb_msgdef *md,
  10680. const void *owner) {
  10681. return upb_handlers_newfrozen(md, owner, printer_sethandlers, NULL);
  10682. }