upb.c 358 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797
  1. // Amalgamated source file
  2. #include "upb.h"
  3. /*
  4. * upb - a minimalist implementation of protocol buffers.
  5. *
  6. * Copyright (c) 2008-2012 Google Inc. See LICENSE for details.
  7. * Author: Josh Haberman <jhaberman@gmail.com>
  8. */
  9. #include <stdlib.h>
  10. #include <string.h>
  11. typedef struct {
  12. size_t len;
  13. char str[1]; // Null-terminated string data follows.
  14. } str_t;
  15. static str_t *newstr(const char *data, size_t len) {
  16. str_t *ret = malloc(sizeof(*ret) + len);
  17. if (!ret) return NULL;
  18. ret->len = len;
  19. memcpy(ret->str, data, len);
  20. ret->str[len] = '\0';
  21. return ret;
  22. }
  23. static void freestr(str_t *s) { free(s); }
  24. // isalpha() etc. from <ctype.h> are locale-dependent, which we don't want.
  25. static bool upb_isbetween(char c, char low, char high) {
  26. return c >= low && c <= high;
  27. }
  28. static bool upb_isletter(char c) {
  29. return upb_isbetween(c, 'A', 'Z') || upb_isbetween(c, 'a', 'z') || c == '_';
  30. }
  31. static bool upb_isalphanum(char c) {
  32. return upb_isletter(c) || upb_isbetween(c, '0', '9');
  33. }
  34. static bool upb_isident(const char *str, size_t len, bool full, upb_status *s) {
  35. bool start = true;
  36. for (size_t i = 0; i < len; i++) {
  37. char c = str[i];
  38. if (c == '.') {
  39. if (start || !full) {
  40. upb_status_seterrf(s, "invalid name: unexpected '.' (%s)", str);
  41. return false;
  42. }
  43. start = true;
  44. } else if (start) {
  45. if (!upb_isletter(c)) {
  46. upb_status_seterrf(
  47. s, "invalid name: path components must start with a letter (%s)",
  48. str);
  49. return false;
  50. }
  51. start = false;
  52. } else {
  53. if (!upb_isalphanum(c)) {
  54. upb_status_seterrf(s, "invalid name: non-alphanumeric character (%s)",
  55. str);
  56. return false;
  57. }
  58. }
  59. }
  60. return !start;
  61. }
  62. /* upb_def ********************************************************************/
  63. upb_deftype_t upb_def_type(const upb_def *d) { return d->type; }
  64. const char *upb_def_fullname(const upb_def *d) { return d->fullname; }
  65. bool upb_def_setfullname(upb_def *def, const char *fullname, upb_status *s) {
  66. assert(!upb_def_isfrozen(def));
  67. if (!upb_isident(fullname, strlen(fullname), true, s)) return false;
  68. free((void*)def->fullname);
  69. def->fullname = upb_strdup(fullname);
  70. return true;
  71. }
  72. upb_def *upb_def_dup(const upb_def *def, const void *o) {
  73. switch (def->type) {
  74. case UPB_DEF_MSG:
  75. return UPB_UPCAST(upb_msgdef_dup(upb_downcast_msgdef(def), o));
  76. case UPB_DEF_FIELD:
  77. return UPB_UPCAST(upb_fielddef_dup(upb_downcast_fielddef(def), o));
  78. case UPB_DEF_ENUM:
  79. return UPB_UPCAST(upb_enumdef_dup(upb_downcast_enumdef(def), o));
  80. default: assert(false); return NULL;
  81. }
  82. }
  83. bool upb_def_isfrozen(const upb_def *def) {
  84. return upb_refcounted_isfrozen(UPB_UPCAST(def));
  85. }
  86. void upb_def_ref(const upb_def *def, const void *owner) {
  87. upb_refcounted_ref(UPB_UPCAST(def), owner);
  88. }
  89. void upb_def_unref(const upb_def *def, const void *owner) {
  90. upb_refcounted_unref(UPB_UPCAST(def), owner);
  91. }
  92. void upb_def_donateref(const upb_def *def, const void *from, const void *to) {
  93. upb_refcounted_donateref(UPB_UPCAST(def), from, to);
  94. }
  95. void upb_def_checkref(const upb_def *def, const void *owner) {
  96. upb_refcounted_checkref(UPB_UPCAST(def), owner);
  97. }
  98. static bool upb_def_init(upb_def *def, upb_deftype_t type,
  99. const struct upb_refcounted_vtbl *vtbl,
  100. const void *owner) {
  101. if (!upb_refcounted_init(UPB_UPCAST(def), vtbl, owner)) return false;
  102. def->type = type;
  103. def->fullname = NULL;
  104. def->came_from_user = false;
  105. return true;
  106. }
  107. static void upb_def_uninit(upb_def *def) {
  108. free((void*)def->fullname);
  109. }
  110. static const char *msgdef_name(const upb_msgdef *m) {
  111. const char *name = upb_def_fullname(UPB_UPCAST(m));
  112. return name ? name : "(anonymous)";
  113. }
  114. static bool upb_validate_field(upb_fielddef *f, upb_status *s) {
  115. if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  116. upb_status_seterrmsg(s, "fielddef must have name and number set");
  117. return false;
  118. }
  119. if (!f->type_is_set_) {
  120. upb_status_seterrmsg(s, "fielddef type was not initialized");
  121. return false;
  122. }
  123. if (upb_fielddef_lazy(f) &&
  124. upb_fielddef_descriptortype(f) != UPB_DESCRIPTOR_TYPE_MESSAGE) {
  125. upb_status_seterrmsg(s,
  126. "only length-delimited submessage fields may be lazy");
  127. return false;
  128. }
  129. if (upb_fielddef_hassubdef(f)) {
  130. if (f->subdef_is_symbolic) {
  131. upb_status_seterrf(s, "field '%s.%s' has not been resolved",
  132. msgdef_name(f->msg.def), upb_fielddef_name(f));
  133. return false;
  134. }
  135. const upb_def *subdef = upb_fielddef_subdef(f);
  136. if (subdef == NULL) {
  137. upb_status_seterrf(s, "field %s.%s is missing required subdef",
  138. msgdef_name(f->msg.def), upb_fielddef_name(f));
  139. return false;
  140. }
  141. if (!upb_def_isfrozen(subdef) && !subdef->came_from_user) {
  142. upb_status_seterrf(s,
  143. "subdef of field %s.%s is not frozen or being frozen",
  144. msgdef_name(f->msg.def), upb_fielddef_name(f));
  145. return false;
  146. }
  147. }
  148. if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  149. bool has_default_name = upb_fielddef_enumhasdefaultstr(f);
  150. bool has_default_number = upb_fielddef_enumhasdefaultint32(f);
  151. // Previously verified by upb_validate_enumdef().
  152. assert(upb_enumdef_numvals(upb_fielddef_enumsubdef(f)) > 0);
  153. // We've already validated that we have an associated enumdef and that it
  154. // has at least one member, so at least one of these should be true.
  155. // Because if the user didn't set anything, we'll pick up the enum's
  156. // default, but if the user *did* set something we should at least pick up
  157. // the one they set (int32 or string).
  158. assert(has_default_name || has_default_number);
  159. if (!has_default_name) {
  160. upb_status_seterrf(s,
  161. "enum default for field %s.%s (%d) is not in the enum",
  162. msgdef_name(f->msg.def), upb_fielddef_name(f),
  163. upb_fielddef_defaultint32(f));
  164. return false;
  165. }
  166. if (!has_default_number) {
  167. upb_status_seterrf(s,
  168. "enum default for field %s.%s (%s) is not in the enum",
  169. msgdef_name(f->msg.def), upb_fielddef_name(f),
  170. upb_fielddef_defaultstr(f, NULL));
  171. return false;
  172. }
  173. // Lift the effective numeric default into the field's default slot, in case
  174. // we were only getting it "by reference" from the enumdef.
  175. upb_fielddef_setdefaultint32(f, upb_fielddef_defaultint32(f));
  176. }
  177. return true;
  178. }
  179. static bool upb_validate_enumdef(const upb_enumdef *e, upb_status *s) {
  180. if (upb_enumdef_numvals(e) == 0) {
  181. upb_status_seterrf(s, "enum %s has no members (must have at least one)",
  182. upb_enumdef_fullname(e));
  183. return false;
  184. }
  185. return true;
  186. }
  187. // All submessage fields are lower than all other fields.
  188. // Secondly, fields are increasing in order.
  189. uint32_t field_rank(const upb_fielddef *f) {
  190. uint32_t ret = upb_fielddef_number(f);
  191. const uint32_t high_bit = 1 << 30;
  192. assert(ret < high_bit);
  193. if (!upb_fielddef_issubmsg(f))
  194. ret |= high_bit;
  195. return ret;
  196. }
  197. int cmp_fields(const void *p1, const void *p2) {
  198. const upb_fielddef *f1 = *(upb_fielddef*const*)p1;
  199. const upb_fielddef *f2 = *(upb_fielddef*const*)p2;
  200. return field_rank(f1) - field_rank(f2);
  201. }
  202. static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
  203. // Sort fields. upb internally relies on UPB_TYPE_MESSAGE fields having the
  204. // lowest indexes, but we do not publicly guarantee this.
  205. int n = upb_msgdef_numfields(m);
  206. upb_fielddef **fields = malloc(n * sizeof(*fields));
  207. if (!fields) return false;
  208. upb_msg_field_iter j;
  209. int i;
  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. uint32_t 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. // Verify that all selectors for the message are distinct.
  236. //
  237. #define TRY(type) \
  238. if (upb_handlers_getselector(f, type, &sel)) upb_inttable_insert(&t, sel, v);
  239. upb_inttable t;
  240. upb_inttable_init(&t, UPB_CTYPE_BOOL);
  241. upb_value v = upb_value_bool(true);
  242. upb_selector_t sel;
  243. upb_inttable_insert(&t, UPB_STARTMSG_SELECTOR, v);
  244. upb_inttable_insert(&t, UPB_ENDMSG_SELECTOR, v);
  245. for(upb_msg_field_begin(&j, m);
  246. !upb_msg_field_done(&j);
  247. upb_msg_field_next(&j)) {
  248. upb_fielddef *f = upb_msg_iter_field(&j);
  249. // These calls will assert-fail in upb_table if the value already exists.
  250. TRY(UPB_HANDLER_INT32);
  251. TRY(UPB_HANDLER_INT64)
  252. TRY(UPB_HANDLER_UINT32)
  253. TRY(UPB_HANDLER_UINT64)
  254. TRY(UPB_HANDLER_FLOAT)
  255. TRY(UPB_HANDLER_DOUBLE)
  256. TRY(UPB_HANDLER_BOOL)
  257. TRY(UPB_HANDLER_STARTSTR)
  258. TRY(UPB_HANDLER_STRING)
  259. TRY(UPB_HANDLER_ENDSTR)
  260. TRY(UPB_HANDLER_STARTSUBMSG)
  261. TRY(UPB_HANDLER_ENDSUBMSG)
  262. TRY(UPB_HANDLER_STARTSEQ)
  263. TRY(UPB_HANDLER_ENDSEQ)
  264. }
  265. upb_inttable_uninit(&t);
  266. #undef TRY
  267. #endif
  268. free(fields);
  269. return true;
  270. }
  271. bool upb_def_freeze(upb_def *const* defs, int n, upb_status *s) {
  272. upb_status_clear(s);
  273. // First perform validation, in two passes so we can check that we have a
  274. // transitive closure without needing to search.
  275. for (int i = 0; i < n; i++) {
  276. upb_def *def = defs[i];
  277. if (upb_def_isfrozen(def)) {
  278. // Could relax this requirement if it's annoying.
  279. upb_status_seterrmsg(s, "def is already frozen");
  280. goto err;
  281. } else if (def->type == UPB_DEF_FIELD) {
  282. upb_status_seterrmsg(s, "standalone fielddefs can not be frozen");
  283. goto err;
  284. } else if (def->type == UPB_DEF_ENUM) {
  285. if (!upb_validate_enumdef(upb_dyncast_enumdef(def), s)) {
  286. goto err;
  287. }
  288. } else {
  289. // Set now to detect transitive closure in the second pass.
  290. def->came_from_user = true;
  291. }
  292. }
  293. // Second pass of validation. Also assign selector bases and indexes, and
  294. // compact tables.
  295. for (int i = 0; i < n; i++) {
  296. upb_msgdef *m = upb_dyncast_msgdef_mutable(defs[i]);
  297. upb_enumdef *e = upb_dyncast_enumdef_mutable(defs[i]);
  298. if (m) {
  299. upb_inttable_compact(&m->itof);
  300. if (!assign_msg_indices(m, s)) {
  301. goto err;
  302. }
  303. } else if (e) {
  304. upb_inttable_compact(&e->iton);
  305. }
  306. }
  307. // Def graph contains FieldDefs between each MessageDef, so double the limit.
  308. int maxdepth = UPB_MAX_MESSAGE_DEPTH * 2;
  309. // Validation all passed; freeze the defs.
  310. bool ret =
  311. upb_refcounted_freeze((upb_refcounted * const *)defs, n, s, maxdepth);
  312. assert(!(s && ret != upb_ok(s)));
  313. return ret;
  314. err:
  315. for (int i = 0; i < n; i++) {
  316. defs[i]->came_from_user = false;
  317. }
  318. assert(!(s && upb_ok(s)));
  319. return false;
  320. }
  321. /* upb_enumdef ****************************************************************/
  322. static void upb_enumdef_free(upb_refcounted *r) {
  323. upb_enumdef *e = (upb_enumdef*)r;
  324. upb_inttable_iter i;
  325. upb_inttable_begin(&i, &e->iton);
  326. for( ; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  327. // To clean up the upb_strdup() from upb_enumdef_addval().
  328. free(upb_value_getcstr(upb_inttable_iter_value(&i)));
  329. }
  330. upb_strtable_uninit(&e->ntoi);
  331. upb_inttable_uninit(&e->iton);
  332. upb_def_uninit(UPB_UPCAST(e));
  333. free(e);
  334. }
  335. upb_enumdef *upb_enumdef_new(const void *owner) {
  336. static const struct upb_refcounted_vtbl vtbl = {NULL, &upb_enumdef_free};
  337. upb_enumdef *e = malloc(sizeof(*e));
  338. if (!e) return NULL;
  339. if (!upb_def_init(UPB_UPCAST(e), UPB_DEF_ENUM, &vtbl, owner)) goto err2;
  340. if (!upb_strtable_init(&e->ntoi, UPB_CTYPE_INT32)) goto err2;
  341. if (!upb_inttable_init(&e->iton, UPB_CTYPE_CSTR)) goto err1;
  342. return e;
  343. err1:
  344. upb_strtable_uninit(&e->ntoi);
  345. err2:
  346. free(e);
  347. return NULL;
  348. }
  349. upb_enumdef *upb_enumdef_dup(const upb_enumdef *e, const void *owner) {
  350. upb_enumdef *new_e = upb_enumdef_new(owner);
  351. if (!new_e) return NULL;
  352. upb_enum_iter i;
  353. for(upb_enum_begin(&i, e); !upb_enum_done(&i); upb_enum_next(&i)) {
  354. bool success = upb_enumdef_addval(
  355. new_e, upb_enum_iter_name(&i),upb_enum_iter_number(&i), NULL);
  356. if (!success) {
  357. upb_enumdef_unref(new_e, owner);
  358. return NULL;
  359. }
  360. }
  361. return new_e;
  362. }
  363. bool upb_enumdef_isfrozen(const upb_enumdef *e) {
  364. return upb_def_isfrozen(UPB_UPCAST(e));
  365. }
  366. void upb_enumdef_ref(const upb_enumdef *e, const void *owner) {
  367. upb_def_ref(UPB_UPCAST(e), owner);
  368. }
  369. void upb_enumdef_unref(const upb_enumdef *e, const void *owner) {
  370. upb_def_unref(UPB_UPCAST(e), owner);
  371. }
  372. void upb_enumdef_donateref(
  373. const upb_enumdef *e, const void *from, const void *to) {
  374. upb_def_donateref(UPB_UPCAST(e), from, to);
  375. }
  376. void upb_enumdef_checkref(const upb_enumdef *e, const void *owner) {
  377. upb_def_checkref(UPB_UPCAST(e), owner);
  378. }
  379. bool upb_enumdef_freeze(upb_enumdef *e, upb_status *status) {
  380. upb_def *d = UPB_UPCAST(e);
  381. return upb_def_freeze(&d, 1, status);
  382. }
  383. const char *upb_enumdef_fullname(const upb_enumdef *e) {
  384. return upb_def_fullname(UPB_UPCAST(e));
  385. }
  386. bool upb_enumdef_setfullname(upb_enumdef *e, const char *fullname,
  387. upb_status *s) {
  388. return upb_def_setfullname(UPB_UPCAST(e), fullname, s);
  389. }
  390. bool upb_enumdef_addval(upb_enumdef *e, const char *name, int32_t num,
  391. upb_status *status) {
  392. if (!upb_isident(name, strlen(name), false, status)) {
  393. return false;
  394. }
  395. if (upb_enumdef_ntoiz(e, name, NULL)) {
  396. upb_status_seterrf(status, "name '%s' is already defined", name);
  397. return false;
  398. }
  399. if (!upb_strtable_insert(&e->ntoi, name, upb_value_int32(num))) {
  400. upb_status_seterrmsg(status, "out of memory");
  401. return false;
  402. }
  403. if (!upb_inttable_lookup(&e->iton, num, NULL) &&
  404. !upb_inttable_insert(&e->iton, num, upb_value_cstr(upb_strdup(name)))) {
  405. upb_status_seterrmsg(status, "out of memory");
  406. upb_strtable_remove(&e->ntoi, name, NULL);
  407. return false;
  408. }
  409. if (upb_enumdef_numvals(e) == 1) {
  410. bool ok = upb_enumdef_setdefault(e, num, NULL);
  411. UPB_ASSERT_VAR(ok, ok);
  412. }
  413. return true;
  414. }
  415. int32_t upb_enumdef_default(const upb_enumdef *e) {
  416. assert(upb_enumdef_iton(e, e->defaultval));
  417. return e->defaultval;
  418. }
  419. bool upb_enumdef_setdefault(upb_enumdef *e, int32_t val, upb_status *s) {
  420. assert(!upb_enumdef_isfrozen(e));
  421. if (!upb_enumdef_iton(e, val)) {
  422. upb_status_seterrf(s, "number '%d' is not in the enum.", val);
  423. return false;
  424. }
  425. e->defaultval = val;
  426. return true;
  427. }
  428. int upb_enumdef_numvals(const upb_enumdef *e) {
  429. return upb_strtable_count(&e->ntoi);
  430. }
  431. void upb_enum_begin(upb_enum_iter *i, const upb_enumdef *e) {
  432. // We iterate over the ntoi table, to account for duplicate numbers.
  433. upb_strtable_begin(i, &e->ntoi);
  434. }
  435. void upb_enum_next(upb_enum_iter *iter) { upb_strtable_next(iter); }
  436. bool upb_enum_done(upb_enum_iter *iter) { return upb_strtable_done(iter); }
  437. bool upb_enumdef_ntoi(const upb_enumdef *def, const char *name,
  438. size_t len, int32_t *num) {
  439. upb_value v;
  440. if (!upb_strtable_lookup2(&def->ntoi, name, len, &v)) {
  441. return false;
  442. }
  443. if (num) *num = upb_value_getint32(v);
  444. return true;
  445. }
  446. const char *upb_enumdef_iton(const upb_enumdef *def, int32_t num) {
  447. upb_value v;
  448. return upb_inttable_lookup32(&def->iton, num, &v) ?
  449. upb_value_getcstr(v) : NULL;
  450. }
  451. const char *upb_enum_iter_name(upb_enum_iter *iter) {
  452. return upb_strtable_iter_key(iter);
  453. }
  454. int32_t upb_enum_iter_number(upb_enum_iter *iter) {
  455. return upb_value_getint32(upb_strtable_iter_value(iter));
  456. }
  457. /* upb_fielddef ***************************************************************/
  458. static void upb_fielddef_init_default(upb_fielddef *f);
  459. static void upb_fielddef_uninit_default(upb_fielddef *f) {
  460. if (f->type_is_set_ && f->default_is_string && f->defaultval.bytes)
  461. freestr(f->defaultval.bytes);
  462. }
  463. static void visitfield(const upb_refcounted *r, upb_refcounted_visit *visit,
  464. void *closure) {
  465. const upb_fielddef *f = (const upb_fielddef*)r;
  466. if (upb_fielddef_containingtype(f)) {
  467. visit(r, UPB_UPCAST2(upb_fielddef_containingtype(f)), closure);
  468. }
  469. if (upb_fielddef_containingoneof(f)) {
  470. visit(r, UPB_UPCAST2(upb_fielddef_containingoneof(f)), closure);
  471. }
  472. if (upb_fielddef_subdef(f)) {
  473. visit(r, UPB_UPCAST(upb_fielddef_subdef(f)), closure);
  474. }
  475. }
  476. static void freefield(upb_refcounted *r) {
  477. upb_fielddef *f = (upb_fielddef*)r;
  478. upb_fielddef_uninit_default(f);
  479. if (f->subdef_is_symbolic)
  480. free(f->sub.name);
  481. upb_def_uninit(UPB_UPCAST(f));
  482. free(f);
  483. }
  484. static const char *enumdefaultstr(const upb_fielddef *f) {
  485. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  486. const upb_enumdef *e = upb_fielddef_enumsubdef(f);
  487. if (f->default_is_string && f->defaultval.bytes) {
  488. // Default was explicitly set as a string.
  489. str_t *s = f->defaultval.bytes;
  490. return s->str;
  491. } else if (e) {
  492. if (!f->default_is_string) {
  493. // Default was explicitly set as an integer; look it up in enumdef.
  494. const char *name = upb_enumdef_iton(e, f->defaultval.sint);
  495. if (name) {
  496. return name;
  497. }
  498. } else {
  499. // Default is completely unset; pull enumdef default.
  500. if (upb_enumdef_numvals(e) > 0) {
  501. const char *name = upb_enumdef_iton(e, upb_enumdef_default(e));
  502. assert(name);
  503. return name;
  504. }
  505. }
  506. }
  507. return NULL;
  508. }
  509. static bool enumdefaultint32(const upb_fielddef *f, int32_t *val) {
  510. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  511. const upb_enumdef *e = upb_fielddef_enumsubdef(f);
  512. if (!f->default_is_string) {
  513. // Default was explicitly set as an integer.
  514. *val = f->defaultval.sint;
  515. return true;
  516. } else if (e) {
  517. if (f->defaultval.bytes) {
  518. // Default was explicitly set as a str; try to lookup corresponding int.
  519. str_t *s = f->defaultval.bytes;
  520. if (upb_enumdef_ntoiz(e, s->str, val)) {
  521. return true;
  522. }
  523. } else {
  524. // Default is unset; try to pull in enumdef default.
  525. if (upb_enumdef_numvals(e) > 0) {
  526. *val = upb_enumdef_default(e);
  527. return true;
  528. }
  529. }
  530. }
  531. return false;
  532. }
  533. upb_fielddef *upb_fielddef_new(const void *owner) {
  534. static const struct upb_refcounted_vtbl vtbl = {visitfield, freefield};
  535. upb_fielddef *f = malloc(sizeof(*f));
  536. if (!f) return NULL;
  537. if (!upb_def_init(UPB_UPCAST(f), UPB_DEF_FIELD, &vtbl, owner)) {
  538. free(f);
  539. return NULL;
  540. }
  541. f->msg.def = NULL;
  542. f->sub.def = NULL;
  543. f->oneof = NULL;
  544. f->subdef_is_symbolic = false;
  545. f->msg_is_symbolic = false;
  546. f->label_ = UPB_LABEL_OPTIONAL;
  547. f->type_ = UPB_TYPE_INT32;
  548. f->number_ = 0;
  549. f->type_is_set_ = false;
  550. f->tagdelim = false;
  551. f->is_extension_ = false;
  552. f->lazy_ = false;
  553. f->packed_ = true;
  554. // For the moment we default this to UPB_INTFMT_VARIABLE, since it will work
  555. // with all integer types and is in some since more "default" since the most
  556. // normal-looking proto2 types int32/int64/uint32/uint64 use variable.
  557. //
  558. // Other options to consider:
  559. // - there is no default; users must set this manually (like type).
  560. // - default signed integers to UPB_INTFMT_ZIGZAG, since it's more likely to
  561. // be an optimal default for signed integers.
  562. f->intfmt = UPB_INTFMT_VARIABLE;
  563. return f;
  564. }
  565. upb_fielddef *upb_fielddef_dup(const upb_fielddef *f, const void *owner) {
  566. upb_fielddef *newf = upb_fielddef_new(owner);
  567. if (!newf) return NULL;
  568. upb_fielddef_settype(newf, upb_fielddef_type(f));
  569. upb_fielddef_setlabel(newf, upb_fielddef_label(f));
  570. upb_fielddef_setnumber(newf, upb_fielddef_number(f), NULL);
  571. upb_fielddef_setname(newf, upb_fielddef_name(f), NULL);
  572. if (f->default_is_string && f->defaultval.bytes) {
  573. str_t *s = f->defaultval.bytes;
  574. upb_fielddef_setdefaultstr(newf, s->str, s->len, NULL);
  575. } else {
  576. newf->default_is_string = f->default_is_string;
  577. newf->defaultval = f->defaultval;
  578. }
  579. const char *srcname;
  580. if (f->subdef_is_symbolic) {
  581. srcname = f->sub.name; // Might be NULL.
  582. } else {
  583. srcname = f->sub.def ? upb_def_fullname(f->sub.def) : NULL;
  584. }
  585. if (srcname) {
  586. char *newname = malloc(strlen(f->sub.def->fullname) + 2);
  587. if (!newname) {
  588. upb_fielddef_unref(newf, owner);
  589. return NULL;
  590. }
  591. strcpy(newname, ".");
  592. strcat(newname, f->sub.def->fullname);
  593. upb_fielddef_setsubdefname(newf, newname, NULL);
  594. free(newname);
  595. }
  596. return newf;
  597. }
  598. bool upb_fielddef_isfrozen(const upb_fielddef *f) {
  599. return upb_def_isfrozen(UPB_UPCAST(f));
  600. }
  601. void upb_fielddef_ref(const upb_fielddef *f, const void *owner) {
  602. upb_def_ref(UPB_UPCAST(f), owner);
  603. }
  604. void upb_fielddef_unref(const upb_fielddef *f, const void *owner) {
  605. upb_def_unref(UPB_UPCAST(f), owner);
  606. }
  607. void upb_fielddef_donateref(
  608. const upb_fielddef *f, const void *from, const void *to) {
  609. upb_def_donateref(UPB_UPCAST(f), from, to);
  610. }
  611. void upb_fielddef_checkref(const upb_fielddef *f, const void *owner) {
  612. upb_def_checkref(UPB_UPCAST(f), owner);
  613. }
  614. bool upb_fielddef_typeisset(const upb_fielddef *f) {
  615. return f->type_is_set_;
  616. }
  617. upb_fieldtype_t upb_fielddef_type(const upb_fielddef *f) {
  618. assert(f->type_is_set_);
  619. return f->type_;
  620. }
  621. uint32_t upb_fielddef_index(const upb_fielddef *f) {
  622. return f->index_;
  623. }
  624. upb_label_t upb_fielddef_label(const upb_fielddef *f) {
  625. return f->label_;
  626. }
  627. upb_intfmt_t upb_fielddef_intfmt(const upb_fielddef *f) {
  628. return f->intfmt;
  629. }
  630. bool upb_fielddef_istagdelim(const upb_fielddef *f) {
  631. return f->tagdelim;
  632. }
  633. uint32_t upb_fielddef_number(const upb_fielddef *f) {
  634. return f->number_;
  635. }
  636. bool upb_fielddef_isextension(const upb_fielddef *f) {
  637. return f->is_extension_;
  638. }
  639. bool upb_fielddef_lazy(const upb_fielddef *f) {
  640. return f->lazy_;
  641. }
  642. bool upb_fielddef_packed(const upb_fielddef *f) {
  643. return f->packed_;
  644. }
  645. const char *upb_fielddef_name(const upb_fielddef *f) {
  646. return upb_def_fullname(UPB_UPCAST(f));
  647. }
  648. const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f) {
  649. return f->msg_is_symbolic ? NULL : f->msg.def;
  650. }
  651. const upb_oneofdef *upb_fielddef_containingoneof(const upb_fielddef *f) {
  652. return f->oneof;
  653. }
  654. upb_msgdef *upb_fielddef_containingtype_mutable(upb_fielddef *f) {
  655. return (upb_msgdef*)upb_fielddef_containingtype(f);
  656. }
  657. const char *upb_fielddef_containingtypename(upb_fielddef *f) {
  658. return f->msg_is_symbolic ? f->msg.name : NULL;
  659. }
  660. static void release_containingtype(upb_fielddef *f) {
  661. if (f->msg_is_symbolic) free(f->msg.name);
  662. }
  663. bool upb_fielddef_setcontainingtypename(upb_fielddef *f, const char *name,
  664. upb_status *s) {
  665. assert(!upb_fielddef_isfrozen(f));
  666. if (upb_fielddef_containingtype(f)) {
  667. upb_status_seterrmsg(s, "field has already been added to a message.");
  668. return false;
  669. }
  670. // TODO: validate name (upb_isident() doesn't quite work atm because this name
  671. // may have a leading ".").
  672. release_containingtype(f);
  673. f->msg.name = upb_strdup(name);
  674. f->msg_is_symbolic = true;
  675. return true;
  676. }
  677. bool upb_fielddef_setname(upb_fielddef *f, const char *name, upb_status *s) {
  678. if (upb_fielddef_containingtype(f) || upb_fielddef_containingoneof(f)) {
  679. upb_status_seterrmsg(s, "Already added to message or oneof");
  680. return false;
  681. }
  682. return upb_def_setfullname(UPB_UPCAST(f), name, s);
  683. }
  684. static void chkdefaulttype(const upb_fielddef *f, upb_fieldtype_t type) {
  685. UPB_UNUSED(f);
  686. UPB_UNUSED(type);
  687. assert(f->type_is_set_ && upb_fielddef_type(f) == type);
  688. }
  689. int64_t upb_fielddef_defaultint64(const upb_fielddef *f) {
  690. chkdefaulttype(f, UPB_TYPE_INT64);
  691. return f->defaultval.sint;
  692. }
  693. int32_t upb_fielddef_defaultint32(const upb_fielddef *f) {
  694. if (f->type_is_set_ && upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  695. int32_t val;
  696. bool ok = enumdefaultint32(f, &val);
  697. UPB_ASSERT_VAR(ok, ok);
  698. return val;
  699. } else {
  700. chkdefaulttype(f, UPB_TYPE_INT32);
  701. return f->defaultval.sint;
  702. }
  703. }
  704. uint64_t upb_fielddef_defaultuint64(const upb_fielddef *f) {
  705. chkdefaulttype(f, UPB_TYPE_UINT64);
  706. return f->defaultval.uint;
  707. }
  708. uint32_t upb_fielddef_defaultuint32(const upb_fielddef *f) {
  709. chkdefaulttype(f, UPB_TYPE_UINT32);
  710. return f->defaultval.uint;
  711. }
  712. bool upb_fielddef_defaultbool(const upb_fielddef *f) {
  713. chkdefaulttype(f, UPB_TYPE_BOOL);
  714. return f->defaultval.uint;
  715. }
  716. float upb_fielddef_defaultfloat(const upb_fielddef *f) {
  717. chkdefaulttype(f, UPB_TYPE_FLOAT);
  718. return f->defaultval.flt;
  719. }
  720. double upb_fielddef_defaultdouble(const upb_fielddef *f) {
  721. chkdefaulttype(f, UPB_TYPE_DOUBLE);
  722. return f->defaultval.dbl;
  723. }
  724. const char *upb_fielddef_defaultstr(const upb_fielddef *f, size_t *len) {
  725. assert(f->type_is_set_);
  726. assert(upb_fielddef_type(f) == UPB_TYPE_STRING ||
  727. upb_fielddef_type(f) == UPB_TYPE_BYTES ||
  728. upb_fielddef_type(f) == UPB_TYPE_ENUM);
  729. if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  730. const char *ret = enumdefaultstr(f);
  731. assert(ret);
  732. // Enum defaults can't have embedded NULLs.
  733. if (len) *len = strlen(ret);
  734. return ret;
  735. }
  736. if (f->default_is_string) {
  737. str_t *str = f->defaultval.bytes;
  738. if (len) *len = str->len;
  739. return str->str;
  740. }
  741. return NULL;
  742. }
  743. static void upb_fielddef_init_default(upb_fielddef *f) {
  744. f->default_is_string = false;
  745. switch (upb_fielddef_type(f)) {
  746. case UPB_TYPE_DOUBLE: f->defaultval.dbl = 0; break;
  747. case UPB_TYPE_FLOAT: f->defaultval.flt = 0; break;
  748. case UPB_TYPE_INT32:
  749. case UPB_TYPE_INT64: f->defaultval.sint = 0; break;
  750. case UPB_TYPE_UINT64:
  751. case UPB_TYPE_UINT32:
  752. case UPB_TYPE_BOOL: f->defaultval.uint = 0; break;
  753. case UPB_TYPE_STRING:
  754. case UPB_TYPE_BYTES:
  755. f->defaultval.bytes = newstr("", 0);
  756. f->default_is_string = true;
  757. break;
  758. case UPB_TYPE_MESSAGE: break;
  759. case UPB_TYPE_ENUM:
  760. // This is our special sentinel that indicates "not set" for an enum.
  761. f->default_is_string = true;
  762. f->defaultval.bytes = NULL;
  763. break;
  764. }
  765. }
  766. const upb_def *upb_fielddef_subdef(const upb_fielddef *f) {
  767. return f->subdef_is_symbolic ? NULL : f->sub.def;
  768. }
  769. const upb_msgdef *upb_fielddef_msgsubdef(const upb_fielddef *f) {
  770. const upb_def *def = upb_fielddef_subdef(f);
  771. return def ? upb_dyncast_msgdef(def) : NULL;
  772. }
  773. const upb_enumdef *upb_fielddef_enumsubdef(const upb_fielddef *f) {
  774. const upb_def *def = upb_fielddef_subdef(f);
  775. return def ? upb_dyncast_enumdef(def) : NULL;
  776. }
  777. upb_def *upb_fielddef_subdef_mutable(upb_fielddef *f) {
  778. return (upb_def*)upb_fielddef_subdef(f);
  779. }
  780. const char *upb_fielddef_subdefname(const upb_fielddef *f) {
  781. if (f->subdef_is_symbolic) {
  782. return f->sub.name;
  783. } else if (f->sub.def) {
  784. return upb_def_fullname(f->sub.def);
  785. } else {
  786. return NULL;
  787. }
  788. }
  789. bool upb_fielddef_setnumber(upb_fielddef *f, uint32_t number, upb_status *s) {
  790. if (upb_fielddef_containingtype(f)) {
  791. upb_status_seterrmsg(
  792. s, "cannot change field number after adding to a message");
  793. return false;
  794. }
  795. if (number == 0 || number > UPB_MAX_FIELDNUMBER) {
  796. upb_status_seterrf(s, "invalid field number (%u)", number);
  797. return false;
  798. }
  799. f->number_ = number;
  800. return true;
  801. }
  802. void upb_fielddef_settype(upb_fielddef *f, upb_fieldtype_t type) {
  803. assert(!upb_fielddef_isfrozen(f));
  804. assert(upb_fielddef_checktype(type));
  805. upb_fielddef_uninit_default(f);
  806. f->type_ = type;
  807. f->type_is_set_ = true;
  808. upb_fielddef_init_default(f);
  809. }
  810. void upb_fielddef_setdescriptortype(upb_fielddef *f, int type) {
  811. assert(!upb_fielddef_isfrozen(f));
  812. switch (type) {
  813. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  814. upb_fielddef_settype(f, UPB_TYPE_DOUBLE);
  815. break;
  816. case UPB_DESCRIPTOR_TYPE_FLOAT:
  817. upb_fielddef_settype(f, UPB_TYPE_FLOAT);
  818. break;
  819. case UPB_DESCRIPTOR_TYPE_INT64:
  820. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  821. case UPB_DESCRIPTOR_TYPE_SINT64:
  822. upb_fielddef_settype(f, UPB_TYPE_INT64);
  823. break;
  824. case UPB_DESCRIPTOR_TYPE_UINT64:
  825. case UPB_DESCRIPTOR_TYPE_FIXED64:
  826. upb_fielddef_settype(f, UPB_TYPE_UINT64);
  827. break;
  828. case UPB_DESCRIPTOR_TYPE_INT32:
  829. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  830. case UPB_DESCRIPTOR_TYPE_SINT32:
  831. upb_fielddef_settype(f, UPB_TYPE_INT32);
  832. break;
  833. case UPB_DESCRIPTOR_TYPE_UINT32:
  834. case UPB_DESCRIPTOR_TYPE_FIXED32:
  835. upb_fielddef_settype(f, UPB_TYPE_UINT32);
  836. break;
  837. case UPB_DESCRIPTOR_TYPE_BOOL:
  838. upb_fielddef_settype(f, UPB_TYPE_BOOL);
  839. break;
  840. case UPB_DESCRIPTOR_TYPE_STRING:
  841. upb_fielddef_settype(f, UPB_TYPE_STRING);
  842. break;
  843. case UPB_DESCRIPTOR_TYPE_BYTES:
  844. upb_fielddef_settype(f, UPB_TYPE_BYTES);
  845. break;
  846. case UPB_DESCRIPTOR_TYPE_GROUP:
  847. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  848. upb_fielddef_settype(f, UPB_TYPE_MESSAGE);
  849. break;
  850. case UPB_DESCRIPTOR_TYPE_ENUM:
  851. upb_fielddef_settype(f, UPB_TYPE_ENUM);
  852. break;
  853. default: assert(false);
  854. }
  855. if (type == UPB_DESCRIPTOR_TYPE_FIXED64 ||
  856. type == UPB_DESCRIPTOR_TYPE_FIXED32 ||
  857. type == UPB_DESCRIPTOR_TYPE_SFIXED64 ||
  858. type == UPB_DESCRIPTOR_TYPE_SFIXED32) {
  859. upb_fielddef_setintfmt(f, UPB_INTFMT_FIXED);
  860. } else if (type == UPB_DESCRIPTOR_TYPE_SINT64 ||
  861. type == UPB_DESCRIPTOR_TYPE_SINT32) {
  862. upb_fielddef_setintfmt(f, UPB_INTFMT_ZIGZAG);
  863. } else {
  864. upb_fielddef_setintfmt(f, UPB_INTFMT_VARIABLE);
  865. }
  866. upb_fielddef_settagdelim(f, type == UPB_DESCRIPTOR_TYPE_GROUP);
  867. }
  868. upb_descriptortype_t upb_fielddef_descriptortype(const upb_fielddef *f) {
  869. switch (upb_fielddef_type(f)) {
  870. case UPB_TYPE_FLOAT: return UPB_DESCRIPTOR_TYPE_FLOAT;
  871. case UPB_TYPE_DOUBLE: return UPB_DESCRIPTOR_TYPE_DOUBLE;
  872. case UPB_TYPE_BOOL: return UPB_DESCRIPTOR_TYPE_BOOL;
  873. case UPB_TYPE_STRING: return UPB_DESCRIPTOR_TYPE_STRING;
  874. case UPB_TYPE_BYTES: return UPB_DESCRIPTOR_TYPE_BYTES;
  875. case UPB_TYPE_ENUM: return UPB_DESCRIPTOR_TYPE_ENUM;
  876. case UPB_TYPE_INT32:
  877. switch (upb_fielddef_intfmt(f)) {
  878. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT32;
  879. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED32;
  880. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT32;
  881. }
  882. case UPB_TYPE_INT64:
  883. switch (upb_fielddef_intfmt(f)) {
  884. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT64;
  885. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED64;
  886. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT64;
  887. }
  888. case UPB_TYPE_UINT32:
  889. switch (upb_fielddef_intfmt(f)) {
  890. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT32;
  891. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED32;
  892. case UPB_INTFMT_ZIGZAG: return -1;
  893. }
  894. case UPB_TYPE_UINT64:
  895. switch (upb_fielddef_intfmt(f)) {
  896. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT64;
  897. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED64;
  898. case UPB_INTFMT_ZIGZAG: return -1;
  899. }
  900. case UPB_TYPE_MESSAGE:
  901. return upb_fielddef_istagdelim(f) ?
  902. UPB_DESCRIPTOR_TYPE_GROUP : UPB_DESCRIPTOR_TYPE_MESSAGE;
  903. }
  904. return 0;
  905. }
  906. void upb_fielddef_setisextension(upb_fielddef *f, bool is_extension) {
  907. assert(!upb_fielddef_isfrozen(f));
  908. f->is_extension_ = is_extension;
  909. }
  910. void upb_fielddef_setlazy(upb_fielddef *f, bool lazy) {
  911. assert(!upb_fielddef_isfrozen(f));
  912. f->lazy_ = lazy;
  913. }
  914. void upb_fielddef_setpacked(upb_fielddef *f, bool packed) {
  915. assert(!upb_fielddef_isfrozen(f));
  916. f->packed_ = packed;
  917. }
  918. void upb_fielddef_setlabel(upb_fielddef *f, upb_label_t label) {
  919. assert(!upb_fielddef_isfrozen(f));
  920. assert(upb_fielddef_checklabel(label));
  921. f->label_ = label;
  922. }
  923. void upb_fielddef_setintfmt(upb_fielddef *f, upb_intfmt_t fmt) {
  924. assert(!upb_fielddef_isfrozen(f));
  925. assert(upb_fielddef_checkintfmt(fmt));
  926. f->intfmt = fmt;
  927. }
  928. void upb_fielddef_settagdelim(upb_fielddef *f, bool tag_delim) {
  929. assert(!upb_fielddef_isfrozen(f));
  930. f->tagdelim = tag_delim;
  931. f->tagdelim = tag_delim;
  932. }
  933. static bool checksetdefault(upb_fielddef *f, upb_fieldtype_t type) {
  934. if (!f->type_is_set_ || upb_fielddef_isfrozen(f) ||
  935. upb_fielddef_type(f) != type) {
  936. assert(false);
  937. return false;
  938. }
  939. if (f->default_is_string) {
  940. str_t *s = f->defaultval.bytes;
  941. assert(s || type == UPB_TYPE_ENUM);
  942. if (s) freestr(s);
  943. }
  944. f->default_is_string = false;
  945. return true;
  946. }
  947. void upb_fielddef_setdefaultint64(upb_fielddef *f, int64_t value) {
  948. if (checksetdefault(f, UPB_TYPE_INT64))
  949. f->defaultval.sint = value;
  950. }
  951. void upb_fielddef_setdefaultint32(upb_fielddef *f, int32_t value) {
  952. if ((upb_fielddef_type(f) == UPB_TYPE_ENUM &&
  953. checksetdefault(f, UPB_TYPE_ENUM)) ||
  954. checksetdefault(f, UPB_TYPE_INT32)) {
  955. f->defaultval.sint = value;
  956. }
  957. }
  958. void upb_fielddef_setdefaultuint64(upb_fielddef *f, uint64_t value) {
  959. if (checksetdefault(f, UPB_TYPE_UINT64))
  960. f->defaultval.uint = value;
  961. }
  962. void upb_fielddef_setdefaultuint32(upb_fielddef *f, uint32_t value) {
  963. if (checksetdefault(f, UPB_TYPE_UINT32))
  964. f->defaultval.uint = value;
  965. }
  966. void upb_fielddef_setdefaultbool(upb_fielddef *f, bool value) {
  967. if (checksetdefault(f, UPB_TYPE_BOOL))
  968. f->defaultval.uint = value;
  969. }
  970. void upb_fielddef_setdefaultfloat(upb_fielddef *f, float value) {
  971. if (checksetdefault(f, UPB_TYPE_FLOAT))
  972. f->defaultval.flt = value;
  973. }
  974. void upb_fielddef_setdefaultdouble(upb_fielddef *f, double value) {
  975. if (checksetdefault(f, UPB_TYPE_DOUBLE))
  976. f->defaultval.dbl = value;
  977. }
  978. bool upb_fielddef_setdefaultstr(upb_fielddef *f, const void *str, size_t len,
  979. upb_status *s) {
  980. assert(upb_fielddef_isstring(f) || f->type_ == UPB_TYPE_ENUM);
  981. if (f->type_ == UPB_TYPE_ENUM && !upb_isident(str, len, false, s))
  982. return false;
  983. if (f->default_is_string) {
  984. str_t *s = f->defaultval.bytes;
  985. assert(s || f->type_ == UPB_TYPE_ENUM);
  986. if (s) freestr(s);
  987. } else {
  988. assert(f->type_ == UPB_TYPE_ENUM);
  989. }
  990. str_t *str2 = newstr(str, len);
  991. f->defaultval.bytes = str2;
  992. f->default_is_string = true;
  993. return true;
  994. }
  995. void upb_fielddef_setdefaultcstr(upb_fielddef *f, const char *str,
  996. upb_status *s) {
  997. assert(f->type_is_set_);
  998. upb_fielddef_setdefaultstr(f, str, str ? strlen(str) : 0, s);
  999. }
  1000. bool upb_fielddef_enumhasdefaultint32(const upb_fielddef *f) {
  1001. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  1002. int32_t val;
  1003. return enumdefaultint32(f, &val);
  1004. }
  1005. bool upb_fielddef_enumhasdefaultstr(const upb_fielddef *f) {
  1006. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  1007. return enumdefaultstr(f) != NULL;
  1008. }
  1009. static bool upb_subdef_typecheck(upb_fielddef *f, const upb_def *subdef,
  1010. upb_status *s) {
  1011. if (f->type_ == UPB_TYPE_MESSAGE) {
  1012. if (upb_dyncast_msgdef(subdef)) return true;
  1013. upb_status_seterrmsg(s, "invalid subdef type for this submessage field");
  1014. return false;
  1015. } else if (f->type_ == UPB_TYPE_ENUM) {
  1016. if (upb_dyncast_enumdef(subdef)) return true;
  1017. upb_status_seterrmsg(s, "invalid subdef type for this enum field");
  1018. return false;
  1019. } else {
  1020. upb_status_seterrmsg(s, "only message and enum fields can have a subdef");
  1021. return false;
  1022. }
  1023. }
  1024. static void release_subdef(upb_fielddef *f) {
  1025. if (f->subdef_is_symbolic) {
  1026. free(f->sub.name);
  1027. } else if (f->sub.def) {
  1028. upb_unref2(f->sub.def, f);
  1029. }
  1030. }
  1031. bool upb_fielddef_setsubdef(upb_fielddef *f, const upb_def *subdef,
  1032. upb_status *s) {
  1033. assert(!upb_fielddef_isfrozen(f));
  1034. assert(upb_fielddef_hassubdef(f));
  1035. if (subdef && !upb_subdef_typecheck(f, subdef, s)) return false;
  1036. release_subdef(f);
  1037. f->sub.def = subdef;
  1038. f->subdef_is_symbolic = false;
  1039. if (f->sub.def) upb_ref2(f->sub.def, f);
  1040. return true;
  1041. }
  1042. bool upb_fielddef_setmsgsubdef(upb_fielddef *f, const upb_msgdef *subdef,
  1043. upb_status *s) {
  1044. return upb_fielddef_setsubdef(f, UPB_UPCAST(subdef), s);
  1045. }
  1046. bool upb_fielddef_setenumsubdef(upb_fielddef *f, const upb_enumdef *subdef,
  1047. upb_status *s) {
  1048. return upb_fielddef_setsubdef(f, UPB_UPCAST(subdef), s);
  1049. }
  1050. bool upb_fielddef_setsubdefname(upb_fielddef *f, const char *name,
  1051. upb_status *s) {
  1052. assert(!upb_fielddef_isfrozen(f));
  1053. if (!upb_fielddef_hassubdef(f)) {
  1054. upb_status_seterrmsg(s, "field type does not accept a subdef");
  1055. return false;
  1056. }
  1057. // TODO: validate name (upb_isident() doesn't quite work atm because this name
  1058. // may have a leading ".").
  1059. release_subdef(f);
  1060. f->sub.name = upb_strdup(name);
  1061. f->subdef_is_symbolic = true;
  1062. return true;
  1063. }
  1064. bool upb_fielddef_issubmsg(const upb_fielddef *f) {
  1065. return upb_fielddef_type(f) == UPB_TYPE_MESSAGE;
  1066. }
  1067. bool upb_fielddef_isstring(const upb_fielddef *f) {
  1068. return upb_fielddef_type(f) == UPB_TYPE_STRING ||
  1069. upb_fielddef_type(f) == UPB_TYPE_BYTES;
  1070. }
  1071. bool upb_fielddef_isseq(const upb_fielddef *f) {
  1072. return upb_fielddef_label(f) == UPB_LABEL_REPEATED;
  1073. }
  1074. bool upb_fielddef_isprimitive(const upb_fielddef *f) {
  1075. return !upb_fielddef_isstring(f) && !upb_fielddef_issubmsg(f);
  1076. }
  1077. bool upb_fielddef_hassubdef(const upb_fielddef *f) {
  1078. return upb_fielddef_issubmsg(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM;
  1079. }
  1080. static bool between(int32_t x, int32_t low, int32_t high) {
  1081. return x >= low && x <= high;
  1082. }
  1083. bool upb_fielddef_checklabel(int32_t label) { return between(label, 1, 3); }
  1084. bool upb_fielddef_checktype(int32_t type) { return between(type, 1, 11); }
  1085. bool upb_fielddef_checkintfmt(int32_t fmt) { return between(fmt, 1, 3); }
  1086. bool upb_fielddef_checkdescriptortype(int32_t type) {
  1087. return between(type, 1, 18);
  1088. }
  1089. /* upb_msgdef *****************************************************************/
  1090. static void visitmsg(const upb_refcounted *r, upb_refcounted_visit *visit,
  1091. void *closure) {
  1092. const upb_msgdef *m = (const upb_msgdef*)r;
  1093. upb_msg_field_iter i;
  1094. for(upb_msg_field_begin(&i, m);
  1095. !upb_msg_field_done(&i);
  1096. upb_msg_field_next(&i)) {
  1097. upb_fielddef *f = upb_msg_iter_field(&i);
  1098. visit(r, UPB_UPCAST2(f), closure);
  1099. }
  1100. upb_msg_oneof_iter o;
  1101. for(upb_msg_oneof_begin(&o, m);
  1102. !upb_msg_oneof_done(&o);
  1103. upb_msg_oneof_next(&o)) {
  1104. upb_oneofdef *f = upb_msg_iter_oneof(&o);
  1105. visit(r, UPB_UPCAST2(f), closure);
  1106. }
  1107. }
  1108. static void freemsg(upb_refcounted *r) {
  1109. upb_msgdef *m = (upb_msgdef*)r;
  1110. upb_strtable_uninit(&m->ntoo);
  1111. upb_strtable_uninit(&m->ntof);
  1112. upb_inttable_uninit(&m->itof);
  1113. upb_def_uninit(UPB_UPCAST(m));
  1114. free(m);
  1115. }
  1116. upb_msgdef *upb_msgdef_new(const void *owner) {
  1117. static const struct upb_refcounted_vtbl vtbl = {visitmsg, freemsg};
  1118. upb_msgdef *m = malloc(sizeof(*m));
  1119. if (!m) return NULL;
  1120. if (!upb_def_init(UPB_UPCAST(m), UPB_DEF_MSG, &vtbl, owner)) goto err2;
  1121. if (!upb_inttable_init(&m->itof, UPB_CTYPE_PTR)) goto err3;
  1122. if (!upb_strtable_init(&m->ntof, UPB_CTYPE_PTR)) goto err2;
  1123. if (!upb_strtable_init(&m->ntoo, UPB_CTYPE_PTR)) goto err1;
  1124. m->map_entry = false;
  1125. return m;
  1126. err1:
  1127. upb_strtable_uninit(&m->ntof);
  1128. err2:
  1129. upb_inttable_uninit(&m->itof);
  1130. err3:
  1131. free(m);
  1132. return NULL;
  1133. }
  1134. upb_msgdef *upb_msgdef_dup(const upb_msgdef *m, const void *owner) {
  1135. upb_msgdef *newm = upb_msgdef_new(owner);
  1136. if (!newm) return NULL;
  1137. bool ok = upb_def_setfullname(UPB_UPCAST(newm),
  1138. upb_def_fullname(UPB_UPCAST(m)), NULL);
  1139. newm->map_entry = m->map_entry;
  1140. UPB_ASSERT_VAR(ok, ok);
  1141. upb_msg_field_iter i;
  1142. for(upb_msg_field_begin(&i, m);
  1143. !upb_msg_field_done(&i);
  1144. upb_msg_field_next(&i)) {
  1145. upb_fielddef *f = upb_fielddef_dup(upb_msg_iter_field(&i), &f);
  1146. // Fields in oneofs are dup'd below.
  1147. if (upb_fielddef_containingoneof(f)) continue;
  1148. if (!f || !upb_msgdef_addfield(newm, f, &f, NULL)) {
  1149. upb_msgdef_unref(newm, owner);
  1150. return NULL;
  1151. }
  1152. }
  1153. upb_msg_oneof_iter o;
  1154. for(upb_msg_oneof_begin(&o, m);
  1155. !upb_msg_oneof_done(&o);
  1156. upb_msg_oneof_next(&o)) {
  1157. upb_oneofdef *f = upb_oneofdef_dup(upb_msg_iter_oneof(&o), &f);
  1158. if (!f || !upb_msgdef_addoneof(newm, f, &f, NULL)) {
  1159. upb_msgdef_unref(newm, owner);
  1160. return NULL;
  1161. }
  1162. }
  1163. return newm;
  1164. }
  1165. bool upb_msgdef_isfrozen(const upb_msgdef *m) {
  1166. return upb_def_isfrozen(UPB_UPCAST(m));
  1167. }
  1168. void upb_msgdef_ref(const upb_msgdef *m, const void *owner) {
  1169. upb_def_ref(UPB_UPCAST(m), owner);
  1170. }
  1171. void upb_msgdef_unref(const upb_msgdef *m, const void *owner) {
  1172. upb_def_unref(UPB_UPCAST(m), owner);
  1173. }
  1174. void upb_msgdef_donateref(
  1175. const upb_msgdef *m, const void *from, const void *to) {
  1176. upb_def_donateref(UPB_UPCAST(m), from, to);
  1177. }
  1178. void upb_msgdef_checkref(const upb_msgdef *m, const void *owner) {
  1179. upb_def_checkref(UPB_UPCAST(m), owner);
  1180. }
  1181. bool upb_msgdef_freeze(upb_msgdef *m, upb_status *status) {
  1182. upb_def *d = UPB_UPCAST(m);
  1183. return upb_def_freeze(&d, 1, status);
  1184. }
  1185. const char *upb_msgdef_fullname(const upb_msgdef *m) {
  1186. return upb_def_fullname(UPB_UPCAST(m));
  1187. }
  1188. bool upb_msgdef_setfullname(upb_msgdef *m, const char *fullname,
  1189. upb_status *s) {
  1190. return upb_def_setfullname(UPB_UPCAST(m), fullname, s);
  1191. }
  1192. // Helper: check that the field |f| is safe to add to msgdef |m|. Set an error
  1193. // on status |s| and return false if not.
  1194. static bool check_field_add(const upb_msgdef *m, const upb_fielddef *f,
  1195. upb_status *s) {
  1196. if (upb_fielddef_containingtype(f) != NULL) {
  1197. upb_status_seterrmsg(s, "fielddef already belongs to a message");
  1198. return false;
  1199. } else if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  1200. upb_status_seterrmsg(s, "field name or number were not set");
  1201. return false;
  1202. } else if (upb_msgdef_ntofz(m, upb_fielddef_name(f)) ||
  1203. upb_msgdef_itof(m, upb_fielddef_number(f))) {
  1204. upb_status_seterrmsg(s, "duplicate field name or number for field");
  1205. return false;
  1206. }
  1207. return true;
  1208. }
  1209. static void add_field(upb_msgdef *m, upb_fielddef *f, const void *ref_donor) {
  1210. release_containingtype(f);
  1211. f->msg.def = m;
  1212. f->msg_is_symbolic = false;
  1213. upb_inttable_insert(&m->itof, upb_fielddef_number(f), upb_value_ptr(f));
  1214. upb_strtable_insert(&m->ntof, upb_fielddef_name(f), upb_value_ptr(f));
  1215. upb_ref2(f, m);
  1216. upb_ref2(m, f);
  1217. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  1218. }
  1219. bool upb_msgdef_addfield(upb_msgdef *m, upb_fielddef *f, const void *ref_donor,
  1220. upb_status *s) {
  1221. // TODO: extensions need to have a separate namespace, because proto2 allows a
  1222. // top-level extension (ie. one not in any package) to have the same name as a
  1223. // field from the message.
  1224. //
  1225. // This also implies that there needs to be a separate lookup-by-name method
  1226. // for extensions. It seems desirable for iteration to return both extensions
  1227. // and non-extensions though.
  1228. //
  1229. // We also need to validate that the field number is in an extension range iff
  1230. // it is an extension.
  1231. // This method is idempotent. Check if |f| is already part of this msgdef and
  1232. // return immediately if so.
  1233. if (upb_fielddef_containingtype(f) == m) {
  1234. return true;
  1235. }
  1236. // Check constraints for all fields before performing any action.
  1237. if (!check_field_add(m, f, s)) {
  1238. return false;
  1239. } else if (upb_fielddef_containingoneof(f) != NULL) {
  1240. // Fields in a oneof can only be added by adding the oneof to the msgdef.
  1241. upb_status_seterrmsg(s, "fielddef is part of a oneof");
  1242. return false;
  1243. }
  1244. // Constraint checks ok, perform the action.
  1245. add_field(m, f, ref_donor);
  1246. return true;
  1247. }
  1248. bool upb_msgdef_addoneof(upb_msgdef *m, upb_oneofdef *o, const void *ref_donor,
  1249. upb_status *s) {
  1250. // Check various conditions that would prevent this oneof from being added.
  1251. if (upb_oneofdef_containingtype(o)) {
  1252. upb_status_seterrmsg(s, "oneofdef already belongs to a message");
  1253. return false;
  1254. } else if (upb_oneofdef_name(o) == NULL) {
  1255. upb_status_seterrmsg(s, "oneofdef name was not set");
  1256. return false;
  1257. } else if (upb_msgdef_ntooz(m, upb_oneofdef_name(o))) {
  1258. upb_status_seterrmsg(s, "duplicate oneof name");
  1259. return false;
  1260. }
  1261. // Check that all of the oneof's fields do not conflict with names or numbers
  1262. // of fields already in the message.
  1263. upb_oneof_iter it;
  1264. for (upb_oneof_begin(&it, o); !upb_oneof_done(&it); upb_oneof_next(&it)) {
  1265. const upb_fielddef *f = upb_oneof_iter_field(&it);
  1266. if (!check_field_add(m, f, s)) {
  1267. return false;
  1268. }
  1269. }
  1270. // Everything checks out -- commit now.
  1271. // Add oneof itself first.
  1272. o->parent = m;
  1273. upb_strtable_insert(&m->ntoo, upb_oneofdef_name(o), upb_value_ptr(o));
  1274. upb_ref2(o, m);
  1275. upb_ref2(m, o);
  1276. // Add each field of the oneof directly to the msgdef.
  1277. for (upb_oneof_begin(&it, o); !upb_oneof_done(&it); upb_oneof_next(&it)) {
  1278. upb_fielddef *f = upb_oneof_iter_field(&it);
  1279. add_field(m, f, NULL);
  1280. }
  1281. if (ref_donor) upb_oneofdef_unref(o, ref_donor);
  1282. return true;
  1283. }
  1284. const upb_fielddef *upb_msgdef_itof(const upb_msgdef *m, uint32_t i) {
  1285. upb_value val;
  1286. return upb_inttable_lookup32(&m->itof, i, &val) ?
  1287. upb_value_getptr(val) : NULL;
  1288. }
  1289. const upb_fielddef *upb_msgdef_ntof(const upb_msgdef *m, const char *name,
  1290. size_t len) {
  1291. upb_value val;
  1292. return upb_strtable_lookup2(&m->ntof, name, len, &val) ?
  1293. upb_value_getptr(val) : NULL;
  1294. }
  1295. const upb_oneofdef *upb_msgdef_ntoo(const upb_msgdef *m, const char *name,
  1296. size_t len) {
  1297. upb_value val;
  1298. return upb_strtable_lookup2(&m->ntoo, name, len, &val) ?
  1299. upb_value_getptr(val) : NULL;
  1300. }
  1301. int upb_msgdef_numfields(const upb_msgdef *m) {
  1302. return upb_strtable_count(&m->ntof);
  1303. }
  1304. int upb_msgdef_numoneofs(const upb_msgdef *m) {
  1305. return upb_strtable_count(&m->ntoo);
  1306. }
  1307. void upb_msgdef_setmapentry(upb_msgdef *m, bool map_entry) {
  1308. assert(!upb_msgdef_isfrozen(m));
  1309. m->map_entry = map_entry;
  1310. }
  1311. bool upb_msgdef_mapentry(const upb_msgdef *m) {
  1312. return m->map_entry;
  1313. }
  1314. void upb_msg_field_begin(upb_msg_field_iter *iter, const upb_msgdef *m) {
  1315. upb_inttable_begin(iter, &m->itof);
  1316. }
  1317. void upb_msg_field_next(upb_msg_field_iter *iter) { upb_inttable_next(iter); }
  1318. bool upb_msg_field_done(const upb_msg_field_iter *iter) {
  1319. return upb_inttable_done(iter);
  1320. }
  1321. upb_fielddef *upb_msg_iter_field(const upb_msg_field_iter *iter) {
  1322. return (upb_fielddef*)upb_value_getptr(upb_inttable_iter_value(iter));
  1323. }
  1324. void upb_msg_field_iter_setdone(upb_msg_field_iter *iter) {
  1325. upb_inttable_iter_setdone(iter);
  1326. }
  1327. void upb_msg_oneof_begin(upb_msg_oneof_iter *iter, const upb_msgdef *m) {
  1328. upb_strtable_begin(iter, &m->ntoo);
  1329. }
  1330. void upb_msg_oneof_next(upb_msg_oneof_iter *iter) { upb_strtable_next(iter); }
  1331. bool upb_msg_oneof_done(const upb_msg_oneof_iter *iter) {
  1332. return upb_strtable_done(iter);
  1333. }
  1334. upb_oneofdef *upb_msg_iter_oneof(const upb_msg_oneof_iter *iter) {
  1335. return (upb_oneofdef*)upb_value_getptr(upb_strtable_iter_value(iter));
  1336. }
  1337. void upb_msg_oneof_iter_setdone(upb_msg_oneof_iter *iter) {
  1338. upb_strtable_iter_setdone(iter);
  1339. }
  1340. /* upb_oneofdef ***************************************************************/
  1341. static void visitoneof(const upb_refcounted *r, upb_refcounted_visit *visit,
  1342. void *closure) {
  1343. const upb_oneofdef *o = (const upb_oneofdef*)r;
  1344. upb_oneof_iter i;
  1345. for (upb_oneof_begin(&i, o); !upb_oneof_done(&i); upb_oneof_next(&i)) {
  1346. const upb_fielddef *f = upb_oneof_iter_field(&i);
  1347. visit(r, UPB_UPCAST2(f), closure);
  1348. }
  1349. if (o->parent) {
  1350. visit(r, UPB_UPCAST2(o->parent), closure);
  1351. }
  1352. }
  1353. static void freeoneof(upb_refcounted *r) {
  1354. upb_oneofdef *o = (upb_oneofdef*)r;
  1355. upb_strtable_uninit(&o->ntof);
  1356. upb_inttable_uninit(&o->itof);
  1357. upb_def_uninit(UPB_UPCAST(o));
  1358. free(o);
  1359. }
  1360. upb_oneofdef *upb_oneofdef_new(const void *owner) {
  1361. static const struct upb_refcounted_vtbl vtbl = {visitoneof, freeoneof};
  1362. upb_oneofdef *o = malloc(sizeof(*o));
  1363. o->parent = NULL;
  1364. if (!o) return NULL;
  1365. if (!upb_def_init(UPB_UPCAST(o), UPB_DEF_ONEOF, &vtbl, owner)) goto err2;
  1366. if (!upb_inttable_init(&o->itof, UPB_CTYPE_PTR)) goto err2;
  1367. if (!upb_strtable_init(&o->ntof, UPB_CTYPE_PTR)) goto err1;
  1368. return o;
  1369. err1:
  1370. upb_inttable_uninit(&o->itof);
  1371. err2:
  1372. free(o);
  1373. return NULL;
  1374. }
  1375. upb_oneofdef *upb_oneofdef_dup(const upb_oneofdef *o, const void *owner) {
  1376. upb_oneofdef *newo = upb_oneofdef_new(owner);
  1377. if (!newo) return NULL;
  1378. bool ok = upb_def_setfullname(UPB_UPCAST(newo),
  1379. upb_def_fullname(UPB_UPCAST(o)), NULL);
  1380. UPB_ASSERT_VAR(ok, ok);
  1381. upb_oneof_iter i;
  1382. for (upb_oneof_begin(&i, o); !upb_oneof_done(&i); upb_oneof_next(&i)) {
  1383. upb_fielddef *f = upb_fielddef_dup(upb_oneof_iter_field(&i), &f);
  1384. if (!f || !upb_oneofdef_addfield(newo, f, &f, NULL)) {
  1385. upb_oneofdef_unref(newo, owner);
  1386. return NULL;
  1387. }
  1388. }
  1389. return newo;
  1390. }
  1391. bool upb_oneofdef_isfrozen(const upb_oneofdef *o) {
  1392. return upb_def_isfrozen(UPB_UPCAST(o));
  1393. }
  1394. void upb_oneofdef_ref(const upb_oneofdef *o, const void *owner) {
  1395. upb_def_ref(UPB_UPCAST(o), owner);
  1396. }
  1397. void upb_oneofdef_unref(const upb_oneofdef *o, const void *owner) {
  1398. upb_def_unref(UPB_UPCAST(o), owner);
  1399. }
  1400. void upb_oneofdef_donateref(const upb_oneofdef *o, const void *from,
  1401. const void *to) {
  1402. upb_def_donateref(UPB_UPCAST(o), from, to);
  1403. }
  1404. void upb_oneofdef_checkref(const upb_oneofdef *o, const void *owner) {
  1405. upb_def_checkref(UPB_UPCAST(o), owner);
  1406. }
  1407. const char *upb_oneofdef_name(const upb_oneofdef *o) {
  1408. return upb_def_fullname(UPB_UPCAST(o));
  1409. }
  1410. bool upb_oneofdef_setname(upb_oneofdef *o, const char *fullname,
  1411. upb_status *s) {
  1412. if (upb_oneofdef_containingtype(o)) {
  1413. upb_status_seterrmsg(s, "oneof already added to a message");
  1414. return false;
  1415. }
  1416. return upb_def_setfullname(UPB_UPCAST(o), fullname, s);
  1417. }
  1418. const upb_msgdef *upb_oneofdef_containingtype(const upb_oneofdef *o) {
  1419. return o->parent;
  1420. }
  1421. int upb_oneofdef_numfields(const upb_oneofdef *o) {
  1422. return upb_strtable_count(&o->ntof);
  1423. }
  1424. bool upb_oneofdef_addfield(upb_oneofdef *o, upb_fielddef *f,
  1425. const void *ref_donor,
  1426. upb_status *s) {
  1427. assert(!upb_oneofdef_isfrozen(o));
  1428. assert(!o->parent || !upb_msgdef_isfrozen(o->parent));
  1429. // This method is idempotent. Check if |f| is already part of this oneofdef
  1430. // and return immediately if so.
  1431. if (upb_fielddef_containingoneof(f) == o) {
  1432. return true;
  1433. }
  1434. // The field must have an OPTIONAL label.
  1435. if (upb_fielddef_label(f) != UPB_LABEL_OPTIONAL) {
  1436. upb_status_seterrmsg(s, "fields in oneof must have OPTIONAL label");
  1437. return false;
  1438. }
  1439. // Check that no field with this name or number exists already in the oneof.
  1440. // Also check that the field is not already part of a oneof.
  1441. if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  1442. upb_status_seterrmsg(s, "field name or number were not set");
  1443. return false;
  1444. } else if (upb_oneofdef_itof(o, upb_fielddef_number(f)) ||
  1445. upb_oneofdef_ntofz(o, upb_fielddef_name(f))) {
  1446. upb_status_seterrmsg(s, "duplicate field name or number");
  1447. return false;
  1448. } else if (upb_fielddef_containingoneof(f) != NULL) {
  1449. upb_status_seterrmsg(s, "fielddef already belongs to a oneof");
  1450. return false;
  1451. }
  1452. // We allow adding a field to the oneof either if the field is not part of a
  1453. // msgdef, or if it is and we are also part of the same msgdef.
  1454. if (o->parent == NULL) {
  1455. // If we're not in a msgdef, the field cannot be either. Otherwise we would
  1456. // need to magically add this oneof to a msgdef to remain consistent, which
  1457. // is surprising behavior.
  1458. if (upb_fielddef_containingtype(f) != NULL) {
  1459. upb_status_seterrmsg(s, "fielddef already belongs to a message, but "
  1460. "oneof does not");
  1461. return false;
  1462. }
  1463. } else {
  1464. // If we're in a msgdef, the user can add fields that either aren't in any
  1465. // msgdef (in which case they're added to our msgdef) or already a part of
  1466. // our msgdef.
  1467. if (upb_fielddef_containingtype(f) != NULL &&
  1468. upb_fielddef_containingtype(f) != o->parent) {
  1469. upb_status_seterrmsg(s, "fielddef belongs to a different message "
  1470. "than oneof");
  1471. return false;
  1472. }
  1473. }
  1474. // Commit phase. First add the field to our parent msgdef, if any, because
  1475. // that may fail; then add the field to our own tables.
  1476. if (o->parent != NULL && upb_fielddef_containingtype(f) == NULL) {
  1477. if (!upb_msgdef_addfield((upb_msgdef*)o->parent, f, NULL, s)) {
  1478. return false;
  1479. }
  1480. }
  1481. release_containingtype(f);
  1482. f->oneof = o;
  1483. upb_inttable_insert(&o->itof, upb_fielddef_number(f), upb_value_ptr(f));
  1484. upb_strtable_insert(&o->ntof, upb_fielddef_name(f), upb_value_ptr(f));
  1485. upb_ref2(f, o);
  1486. upb_ref2(o, f);
  1487. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  1488. return true;
  1489. }
  1490. const upb_fielddef *upb_oneofdef_ntof(const upb_oneofdef *o,
  1491. const char *name, size_t length) {
  1492. upb_value val;
  1493. return upb_strtable_lookup2(&o->ntof, name, length, &val) ?
  1494. upb_value_getptr(val) : NULL;
  1495. }
  1496. const upb_fielddef *upb_oneofdef_itof(const upb_oneofdef *o, uint32_t num) {
  1497. upb_value val;
  1498. return upb_inttable_lookup32(&o->itof, num, &val) ?
  1499. upb_value_getptr(val) : NULL;
  1500. }
  1501. void upb_oneof_begin(upb_oneof_iter *iter, const upb_oneofdef *o) {
  1502. upb_inttable_begin(iter, &o->itof);
  1503. }
  1504. void upb_oneof_next(upb_oneof_iter *iter) {
  1505. upb_inttable_next(iter);
  1506. }
  1507. bool upb_oneof_done(upb_oneof_iter *iter) {
  1508. return upb_inttable_done(iter);
  1509. }
  1510. upb_fielddef *upb_oneof_iter_field(const upb_oneof_iter *iter) {
  1511. return (upb_fielddef*)upb_value_getptr(upb_inttable_iter_value(iter));
  1512. }
  1513. void upb_oneof_iter_setdone(upb_oneof_iter *iter) {
  1514. upb_inttable_iter_setdone(iter);
  1515. }
  1516. /*
  1517. * upb - a minimalist implementation of protocol buffers.
  1518. *
  1519. * Copyright (c) 2011-2012 Google Inc. See LICENSE for details.
  1520. * Author: Josh Haberman <jhaberman@gmail.com>
  1521. *
  1522. * TODO(haberman): it's unclear whether a lot of the consistency checks should
  1523. * assert() or return false.
  1524. */
  1525. #include <stdlib.h>
  1526. #include <string.h>
  1527. // Defined for the sole purpose of having a unique pointer value for
  1528. // UPB_NO_CLOSURE.
  1529. char _upb_noclosure;
  1530. static void freehandlers(upb_refcounted *r) {
  1531. upb_handlers *h = (upb_handlers*)r;
  1532. upb_inttable_iter i;
  1533. upb_inttable_begin(&i, &h->cleanup_);
  1534. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  1535. void *val = (void*)upb_inttable_iter_key(&i);
  1536. upb_value func_val = upb_inttable_iter_value(&i);
  1537. upb_handlerfree *func = upb_value_getfptr(func_val);
  1538. func(val);
  1539. }
  1540. upb_inttable_uninit(&h->cleanup_);
  1541. upb_msgdef_unref(h->msg, h);
  1542. free(h->sub);
  1543. free(h);
  1544. }
  1545. static void visithandlers(const upb_refcounted *r, upb_refcounted_visit *visit,
  1546. void *closure) {
  1547. const upb_handlers *h = (const upb_handlers*)r;
  1548. upb_msg_field_iter i;
  1549. for(upb_msg_field_begin(&i, h->msg);
  1550. !upb_msg_field_done(&i);
  1551. upb_msg_field_next(&i)) {
  1552. upb_fielddef *f = upb_msg_iter_field(&i);
  1553. if (!upb_fielddef_issubmsg(f)) continue;
  1554. const upb_handlers *sub = upb_handlers_getsubhandlers(h, f);
  1555. if (sub) visit(r, UPB_UPCAST(sub), closure);
  1556. }
  1557. }
  1558. static const struct upb_refcounted_vtbl vtbl = {visithandlers, freehandlers};
  1559. typedef struct {
  1560. upb_inttable tab; // maps upb_msgdef* -> upb_handlers*.
  1561. upb_handlers_callback *callback;
  1562. const void *closure;
  1563. } dfs_state;
  1564. // TODO(haberman): discard upb_handlers* objects that do not actually have any
  1565. // handlers set and cannot reach any upb_handlers* object that does. This is
  1566. // slightly tricky to do correctly.
  1567. static upb_handlers *newformsg(const upb_msgdef *m, const void *owner,
  1568. dfs_state *s) {
  1569. upb_handlers *h = upb_handlers_new(m, owner);
  1570. if (!h) return NULL;
  1571. if (!upb_inttable_insertptr(&s->tab, m, upb_value_ptr(h))) goto oom;
  1572. s->callback(s->closure, h);
  1573. // For each submessage field, get or create a handlers object and set it as
  1574. // the subhandlers.
  1575. upb_msg_field_iter i;
  1576. for(upb_msg_field_begin(&i, m);
  1577. !upb_msg_field_done(&i);
  1578. upb_msg_field_next(&i)) {
  1579. upb_fielddef *f = upb_msg_iter_field(&i);
  1580. if (!upb_fielddef_issubmsg(f)) continue;
  1581. const upb_msgdef *subdef = upb_downcast_msgdef(upb_fielddef_subdef(f));
  1582. upb_value subm_ent;
  1583. if (upb_inttable_lookupptr(&s->tab, subdef, &subm_ent)) {
  1584. upb_handlers_setsubhandlers(h, f, upb_value_getptr(subm_ent));
  1585. } else {
  1586. upb_handlers *sub_mh = newformsg(subdef, &sub_mh, s);
  1587. if (!sub_mh) goto oom;
  1588. upb_handlers_setsubhandlers(h, f, sub_mh);
  1589. upb_handlers_unref(sub_mh, &sub_mh);
  1590. }
  1591. }
  1592. return h;
  1593. oom:
  1594. upb_handlers_unref(h, owner);
  1595. return NULL;
  1596. }
  1597. // Given a selector for a STARTSUBMSG handler, resolves to a pointer to the
  1598. // subhandlers for this submessage field.
  1599. #define SUBH(h, selector) (h->sub[selector])
  1600. // The selector for a submessage field is the field index.
  1601. #define SUBH_F(h, f) SUBH(h, f->index_)
  1602. static int32_t trygetsel(upb_handlers *h, const upb_fielddef *f,
  1603. upb_handlertype_t type) {
  1604. upb_selector_t sel;
  1605. assert(!upb_handlers_isfrozen(h));
  1606. if (upb_handlers_msgdef(h) != upb_fielddef_containingtype(f)) {
  1607. upb_status_seterrf(
  1608. &h->status_, "type mismatch: field %s does not belong to message %s",
  1609. upb_fielddef_name(f), upb_msgdef_fullname(upb_handlers_msgdef(h)));
  1610. return -1;
  1611. }
  1612. if (!upb_handlers_getselector(f, type, &sel)) {
  1613. upb_status_seterrf(
  1614. &h->status_,
  1615. "type mismatch: cannot register handler type %d for field %s",
  1616. type, upb_fielddef_name(f));
  1617. return -1;
  1618. }
  1619. return sel;
  1620. }
  1621. static upb_selector_t handlers_getsel(upb_handlers *h, const upb_fielddef *f,
  1622. upb_handlertype_t type) {
  1623. int32_t sel = trygetsel(h, f, type);
  1624. assert(sel >= 0);
  1625. return sel;
  1626. }
  1627. static const void **returntype(upb_handlers *h, const upb_fielddef *f,
  1628. upb_handlertype_t type) {
  1629. return &h->table[handlers_getsel(h, f, type)].attr.return_closure_type_;
  1630. }
  1631. static bool doset(upb_handlers *h, int32_t sel, const upb_fielddef *f,
  1632. upb_handlertype_t type, upb_func *func,
  1633. upb_handlerattr *attr) {
  1634. assert(!upb_handlers_isfrozen(h));
  1635. if (sel < 0) {
  1636. upb_status_seterrmsg(&h->status_,
  1637. "incorrect handler type for this field.");
  1638. return false;
  1639. }
  1640. if (h->table[sel].func) {
  1641. upb_status_seterrmsg(&h->status_,
  1642. "cannot change handler once it has been set.");
  1643. return false;
  1644. }
  1645. upb_handlerattr set_attr = UPB_HANDLERATTR_INITIALIZER;
  1646. if (attr) {
  1647. set_attr = *attr;
  1648. }
  1649. // Check that the given closure type matches the closure type that has been
  1650. // established for this context (if any).
  1651. const void *closure_type = upb_handlerattr_closuretype(&set_attr);
  1652. const void **context_closure_type;
  1653. if (type == UPB_HANDLER_STRING) {
  1654. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSTR);
  1655. } else if (f && upb_fielddef_isseq(f) &&
  1656. type != UPB_HANDLER_STARTSEQ &&
  1657. type != UPB_HANDLER_ENDSEQ) {
  1658. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSEQ);
  1659. } else {
  1660. context_closure_type = &h->top_closure_type;
  1661. }
  1662. if (closure_type && *context_closure_type &&
  1663. closure_type != *context_closure_type) {
  1664. // TODO(haberman): better message for debugging.
  1665. upb_status_seterrmsg(&h->status_, "closure type does not match");
  1666. return false;
  1667. }
  1668. if (closure_type)
  1669. *context_closure_type = closure_type;
  1670. // If this is a STARTSEQ or STARTSTR handler, check that the returned pointer
  1671. // matches any pre-existing expectations about what type is expected.
  1672. if (type == UPB_HANDLER_STARTSEQ || type == UPB_HANDLER_STARTSTR) {
  1673. const void *return_type = upb_handlerattr_returnclosuretype(&set_attr);
  1674. const void *table_return_type =
  1675. upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1676. if (return_type && table_return_type && return_type != table_return_type) {
  1677. upb_status_seterrmsg(&h->status_, "closure return type does not match");
  1678. return false;
  1679. }
  1680. if (table_return_type && !return_type)
  1681. upb_handlerattr_setreturnclosuretype(&set_attr, table_return_type);
  1682. }
  1683. h->table[sel].func = (upb_func*)func;
  1684. h->table[sel].attr = set_attr;
  1685. return true;
  1686. }
  1687. // Returns the effective closure type for this handler (which will propagate
  1688. // from outer frames if this frame has no START* handler). Not implemented for
  1689. // UPB_HANDLER_STRING at the moment since this is not needed. Returns NULL is
  1690. // the effective closure type is unspecified (either no handler was registered
  1691. // to specify it or the handler that was registered did not specify the closure
  1692. // type).
  1693. const void *effective_closure_type(upb_handlers *h, const upb_fielddef *f,
  1694. upb_handlertype_t type) {
  1695. assert(type != UPB_HANDLER_STRING);
  1696. const void *ret = h->top_closure_type;
  1697. upb_selector_t sel;
  1698. if (upb_fielddef_isseq(f) &&
  1699. type != UPB_HANDLER_STARTSEQ &&
  1700. type != UPB_HANDLER_ENDSEQ &&
  1701. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)].func) {
  1702. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1703. }
  1704. if (type == UPB_HANDLER_STRING &&
  1705. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSTR)].func) {
  1706. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1707. }
  1708. // The effective type of the submessage; not used yet.
  1709. // if (type == SUBMESSAGE &&
  1710. // h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)].func) {
  1711. // ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1712. // }
  1713. return ret;
  1714. }
  1715. // Checks whether the START* handler specified by f & type is missing even
  1716. // though it is required to convert the established type of an outer frame
  1717. // ("closure_type") into the established type of an inner frame (represented in
  1718. // the return closure type of this handler's attr.
  1719. bool checkstart(upb_handlers *h, const upb_fielddef *f, upb_handlertype_t type,
  1720. upb_status *status) {
  1721. upb_selector_t sel = handlers_getsel(h, f, type);
  1722. if (h->table[sel].func) return true;
  1723. const void *closure_type = effective_closure_type(h, f, type);
  1724. const upb_handlerattr *attr = &h->table[sel].attr;
  1725. const void *return_closure_type = upb_handlerattr_returnclosuretype(attr);
  1726. if (closure_type && return_closure_type &&
  1727. closure_type != return_closure_type) {
  1728. upb_status_seterrf(status,
  1729. "expected start handler to return sub type for field %f",
  1730. upb_fielddef_name(f));
  1731. return false;
  1732. }
  1733. return true;
  1734. }
  1735. /* Public interface ***********************************************************/
  1736. bool upb_handlers_isfrozen(const upb_handlers *h) {
  1737. return upb_refcounted_isfrozen(UPB_UPCAST(h));
  1738. }
  1739. void upb_handlers_ref(const upb_handlers *h, const void *owner) {
  1740. upb_refcounted_ref(UPB_UPCAST(h), owner);
  1741. }
  1742. void upb_handlers_unref(const upb_handlers *h, const void *owner) {
  1743. upb_refcounted_unref(UPB_UPCAST(h), owner);
  1744. }
  1745. void upb_handlers_donateref(
  1746. const upb_handlers *h, const void *from, const void *to) {
  1747. upb_refcounted_donateref(UPB_UPCAST(h), from, to);
  1748. }
  1749. void upb_handlers_checkref(const upb_handlers *h, const void *owner) {
  1750. upb_refcounted_checkref(UPB_UPCAST(h), owner);
  1751. }
  1752. upb_handlers *upb_handlers_new(const upb_msgdef *md, const void *owner) {
  1753. assert(upb_msgdef_isfrozen(md));
  1754. int extra = sizeof(upb_handlers_tabent) * (md->selector_count - 1);
  1755. upb_handlers *h = calloc(sizeof(*h) + extra, 1);
  1756. if (!h) return NULL;
  1757. h->msg = md;
  1758. upb_msgdef_ref(h->msg, h);
  1759. upb_status_clear(&h->status_);
  1760. h->sub = calloc(md->submsg_field_count, sizeof(*h->sub));
  1761. if (!h->sub) goto oom;
  1762. if (!upb_refcounted_init(UPB_UPCAST(h), &vtbl, owner)) goto oom;
  1763. if (!upb_inttable_init(&h->cleanup_, UPB_CTYPE_FPTR)) goto oom;
  1764. // calloc() above initialized all handlers to NULL.
  1765. return h;
  1766. oom:
  1767. freehandlers(UPB_UPCAST(h));
  1768. return NULL;
  1769. }
  1770. const upb_handlers *upb_handlers_newfrozen(const upb_msgdef *m,
  1771. const void *owner,
  1772. upb_handlers_callback *callback,
  1773. const void *closure) {
  1774. dfs_state state;
  1775. state.callback = callback;
  1776. state.closure = closure;
  1777. if (!upb_inttable_init(&state.tab, UPB_CTYPE_PTR)) return NULL;
  1778. upb_handlers *ret = newformsg(m, owner, &state);
  1779. upb_inttable_uninit(&state.tab);
  1780. if (!ret) return NULL;
  1781. upb_refcounted *r = UPB_UPCAST(ret);
  1782. bool ok = upb_refcounted_freeze(&r, 1, NULL, UPB_MAX_HANDLER_DEPTH);
  1783. UPB_ASSERT_VAR(ok, ok);
  1784. return ret;
  1785. }
  1786. const upb_status *upb_handlers_status(upb_handlers *h) {
  1787. assert(!upb_handlers_isfrozen(h));
  1788. return &h->status_;
  1789. }
  1790. void upb_handlers_clearerr(upb_handlers *h) {
  1791. assert(!upb_handlers_isfrozen(h));
  1792. upb_status_clear(&h->status_);
  1793. }
  1794. #define SETTER(name, handlerctype, handlertype) \
  1795. bool upb_handlers_set ## name(upb_handlers *h, const upb_fielddef *f, \
  1796. handlerctype func, upb_handlerattr *attr) { \
  1797. int32_t sel = trygetsel(h, f, handlertype); \
  1798. return doset(h, sel, f, handlertype, (upb_func*)func, attr); \
  1799. }
  1800. SETTER(int32, upb_int32_handlerfunc*, UPB_HANDLER_INT32);
  1801. SETTER(int64, upb_int64_handlerfunc*, UPB_HANDLER_INT64);
  1802. SETTER(uint32, upb_uint32_handlerfunc*, UPB_HANDLER_UINT32);
  1803. SETTER(uint64, upb_uint64_handlerfunc*, UPB_HANDLER_UINT64);
  1804. SETTER(float, upb_float_handlerfunc*, UPB_HANDLER_FLOAT);
  1805. SETTER(double, upb_double_handlerfunc*, UPB_HANDLER_DOUBLE);
  1806. SETTER(bool, upb_bool_handlerfunc*, UPB_HANDLER_BOOL);
  1807. SETTER(startstr, upb_startstr_handlerfunc*, UPB_HANDLER_STARTSTR);
  1808. SETTER(string, upb_string_handlerfunc*, UPB_HANDLER_STRING);
  1809. SETTER(endstr, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSTR);
  1810. SETTER(startseq, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSEQ);
  1811. SETTER(startsubmsg, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSUBMSG);
  1812. SETTER(endsubmsg, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSUBMSG);
  1813. SETTER(endseq, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSEQ);
  1814. #undef SETTER
  1815. bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
  1816. upb_handlerattr *attr) {
  1817. return doset(h, UPB_STARTMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  1818. (upb_func *)func, attr);
  1819. }
  1820. bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func,
  1821. upb_handlerattr *attr) {
  1822. assert(!upb_handlers_isfrozen(h));
  1823. return doset(h, UPB_ENDMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  1824. (upb_func *)func, attr);
  1825. }
  1826. bool upb_handlers_setsubhandlers(upb_handlers *h, const upb_fielddef *f,
  1827. const upb_handlers *sub) {
  1828. assert(sub);
  1829. assert(!upb_handlers_isfrozen(h));
  1830. assert(upb_fielddef_issubmsg(f));
  1831. if (SUBH_F(h, f)) return false; // Can't reset.
  1832. if (UPB_UPCAST(upb_handlers_msgdef(sub)) != upb_fielddef_subdef(f)) {
  1833. return false;
  1834. }
  1835. SUBH_F(h, f) = sub;
  1836. upb_ref2(sub, h);
  1837. return true;
  1838. }
  1839. const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h,
  1840. const upb_fielddef *f) {
  1841. assert(upb_fielddef_issubmsg(f));
  1842. return SUBH_F(h, f);
  1843. }
  1844. bool upb_handlers_getattr(const upb_handlers *h, upb_selector_t sel,
  1845. upb_handlerattr *attr) {
  1846. if (!upb_handlers_gethandler(h, sel))
  1847. return false;
  1848. *attr = h->table[sel].attr;
  1849. return true;
  1850. }
  1851. const upb_handlers *upb_handlers_getsubhandlers_sel(const upb_handlers *h,
  1852. upb_selector_t sel) {
  1853. // STARTSUBMSG selector in sel is the field's selector base.
  1854. return SUBH(h, sel - UPB_STATIC_SELECTOR_COUNT);
  1855. }
  1856. const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h) { return h->msg; }
  1857. bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *func) {
  1858. if (upb_inttable_lookupptr(&h->cleanup_, p, NULL)) {
  1859. return false;
  1860. }
  1861. bool ok = upb_inttable_insertptr(&h->cleanup_, p, upb_value_fptr(func));
  1862. UPB_ASSERT_VAR(ok, ok);
  1863. return true;
  1864. }
  1865. /* "Static" methods ***********************************************************/
  1866. bool upb_handlers_freeze(upb_handlers *const*handlers, int n, upb_status *s) {
  1867. // TODO: verify we have a transitive closure.
  1868. for (int i = 0; i < n; i++) {
  1869. upb_handlers *h = handlers[i];
  1870. if (!upb_ok(&h->status_)) {
  1871. upb_status_seterrf(s, "handlers for message %s had error status: %s",
  1872. upb_msgdef_fullname(upb_handlers_msgdef(h)),
  1873. upb_status_errmsg(&h->status_));
  1874. return false;
  1875. }
  1876. // Check that there are no closure mismatches due to missing Start* handlers
  1877. // or subhandlers with different type-level types.
  1878. upb_msg_field_iter j;
  1879. for(upb_msg_field_begin(&j, h->msg);
  1880. !upb_msg_field_done(&j);
  1881. upb_msg_field_next(&j)) {
  1882. const upb_fielddef *f = upb_msg_iter_field(&j);
  1883. if (upb_fielddef_isseq(f)) {
  1884. if (!checkstart(h, f, UPB_HANDLER_STARTSEQ, s))
  1885. return false;
  1886. }
  1887. if (upb_fielddef_isstring(f)) {
  1888. if (!checkstart(h, f, UPB_HANDLER_STARTSTR, s))
  1889. return false;
  1890. }
  1891. if (upb_fielddef_issubmsg(f)) {
  1892. bool hashandler = false;
  1893. if (upb_handlers_gethandler(
  1894. h, handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)) ||
  1895. upb_handlers_gethandler(
  1896. h, handlers_getsel(h, f, UPB_HANDLER_ENDSUBMSG))) {
  1897. hashandler = true;
  1898. }
  1899. if (upb_fielddef_isseq(f) &&
  1900. (upb_handlers_gethandler(
  1901. h, handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)) ||
  1902. upb_handlers_gethandler(
  1903. h, handlers_getsel(h, f, UPB_HANDLER_ENDSEQ)))) {
  1904. hashandler = true;
  1905. }
  1906. if (hashandler && !upb_handlers_getsubhandlers(h, f)) {
  1907. // For now we add an empty subhandlers in this case. It makes the
  1908. // decoder code generator simpler, because it only has to handle two
  1909. // cases (submessage has handlers or not) as opposed to three
  1910. // (submessage has handlers in enclosing message but no subhandlers).
  1911. //
  1912. // This makes parsing less efficient in the case that we want to
  1913. // notice a submessage but skip its contents (like if we're testing
  1914. // for submessage presence or counting the number of repeated
  1915. // submessages). In this case we will end up parsing the submessage
  1916. // field by field and throwing away the results for each, instead of
  1917. // skipping the whole delimited thing at once. If this is an issue we
  1918. // can revisit it, but do remember that this only arises when you have
  1919. // handlers (startseq/startsubmsg/endsubmsg/endseq) set for the
  1920. // submessage but no subhandlers. The uses cases for this are
  1921. // limited.
  1922. upb_handlers *sub = upb_handlers_new(upb_fielddef_msgsubdef(f), &sub);
  1923. upb_handlers_setsubhandlers(h, f, sub);
  1924. upb_handlers_unref(sub, &sub);
  1925. }
  1926. // TODO(haberman): check type of submessage.
  1927. // This is slightly tricky; also consider whether we should check that
  1928. // they match at setsubhandlers time.
  1929. }
  1930. }
  1931. }
  1932. if (!upb_refcounted_freeze((upb_refcounted*const*)handlers, n, s,
  1933. UPB_MAX_HANDLER_DEPTH)) {
  1934. return false;
  1935. }
  1936. return true;
  1937. }
  1938. upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f) {
  1939. switch (upb_fielddef_type(f)) {
  1940. case UPB_TYPE_INT32:
  1941. case UPB_TYPE_ENUM: return UPB_HANDLER_INT32;
  1942. case UPB_TYPE_INT64: return UPB_HANDLER_INT64;
  1943. case UPB_TYPE_UINT32: return UPB_HANDLER_UINT32;
  1944. case UPB_TYPE_UINT64: return UPB_HANDLER_UINT64;
  1945. case UPB_TYPE_FLOAT: return UPB_HANDLER_FLOAT;
  1946. case UPB_TYPE_DOUBLE: return UPB_HANDLER_DOUBLE;
  1947. case UPB_TYPE_BOOL: return UPB_HANDLER_BOOL;
  1948. default: assert(false); return -1; // Invalid input.
  1949. }
  1950. }
  1951. bool upb_handlers_getselector(const upb_fielddef *f, upb_handlertype_t type,
  1952. upb_selector_t *s) {
  1953. switch (type) {
  1954. case UPB_HANDLER_INT32:
  1955. case UPB_HANDLER_INT64:
  1956. case UPB_HANDLER_UINT32:
  1957. case UPB_HANDLER_UINT64:
  1958. case UPB_HANDLER_FLOAT:
  1959. case UPB_HANDLER_DOUBLE:
  1960. case UPB_HANDLER_BOOL:
  1961. if (!upb_fielddef_isprimitive(f) ||
  1962. upb_handlers_getprimitivehandlertype(f) != type)
  1963. return false;
  1964. *s = f->selector_base;
  1965. break;
  1966. case UPB_HANDLER_STRING:
  1967. if (upb_fielddef_isstring(f)) {
  1968. *s = f->selector_base;
  1969. } else if (upb_fielddef_lazy(f)) {
  1970. *s = f->selector_base + 3;
  1971. } else {
  1972. return false;
  1973. }
  1974. break;
  1975. case UPB_HANDLER_STARTSTR:
  1976. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  1977. *s = f->selector_base + 1;
  1978. } else {
  1979. return false;
  1980. }
  1981. break;
  1982. case UPB_HANDLER_ENDSTR:
  1983. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  1984. *s = f->selector_base + 2;
  1985. } else {
  1986. return false;
  1987. }
  1988. break;
  1989. case UPB_HANDLER_STARTSEQ:
  1990. if (!upb_fielddef_isseq(f)) return false;
  1991. *s = f->selector_base - 2;
  1992. break;
  1993. case UPB_HANDLER_ENDSEQ:
  1994. if (!upb_fielddef_isseq(f)) return false;
  1995. *s = f->selector_base - 1;
  1996. break;
  1997. case UPB_HANDLER_STARTSUBMSG:
  1998. if (!upb_fielddef_issubmsg(f)) return false;
  1999. // Selectors for STARTSUBMSG are at the beginning of the table so that the
  2000. // selector can also be used as an index into the "sub" array of
  2001. // subhandlers. The indexes for the two into these two tables are the
  2002. // same, except that in the handler table the static selectors come first.
  2003. *s = f->index_ + UPB_STATIC_SELECTOR_COUNT;
  2004. break;
  2005. case UPB_HANDLER_ENDSUBMSG:
  2006. if (!upb_fielddef_issubmsg(f)) return false;
  2007. *s = f->selector_base;
  2008. break;
  2009. }
  2010. assert(*s < upb_fielddef_containingtype(f)->selector_count);
  2011. return true;
  2012. }
  2013. uint32_t upb_handlers_selectorbaseoffset(const upb_fielddef *f) {
  2014. return upb_fielddef_isseq(f) ? 2 : 0;
  2015. }
  2016. uint32_t upb_handlers_selectorcount(const upb_fielddef *f) {
  2017. uint32_t ret = 1;
  2018. if (upb_fielddef_isseq(f)) ret += 2; // STARTSEQ/ENDSEQ
  2019. if (upb_fielddef_isstring(f)) ret += 2; // [STRING]/STARTSTR/ENDSTR
  2020. if (upb_fielddef_issubmsg(f)) {
  2021. // ENDSUBMSG (STARTSUBMSG is at table beginning)
  2022. ret += 0;
  2023. if (upb_fielddef_lazy(f)) {
  2024. // STARTSTR/ENDSTR/STRING (for lazy)
  2025. ret += 3;
  2026. }
  2027. }
  2028. return ret;
  2029. }
  2030. /* upb_handlerattr ************************************************************/
  2031. void upb_handlerattr_init(upb_handlerattr *attr) {
  2032. upb_handlerattr from = UPB_HANDLERATTR_INITIALIZER;
  2033. memcpy(attr, &from, sizeof(*attr));
  2034. }
  2035. void upb_handlerattr_uninit(upb_handlerattr *attr) {
  2036. UPB_UNUSED(attr);
  2037. }
  2038. bool upb_handlerattr_sethandlerdata(upb_handlerattr *attr, const void *hd) {
  2039. attr->handler_data_ = hd;
  2040. return true;
  2041. }
  2042. bool upb_handlerattr_setclosuretype(upb_handlerattr *attr, const void *type) {
  2043. attr->closure_type_ = type;
  2044. return true;
  2045. }
  2046. const void *upb_handlerattr_closuretype(const upb_handlerattr *attr) {
  2047. return attr->closure_type_;
  2048. }
  2049. bool upb_handlerattr_setreturnclosuretype(upb_handlerattr *attr,
  2050. const void *type) {
  2051. attr->return_closure_type_ = type;
  2052. return true;
  2053. }
  2054. const void *upb_handlerattr_returnclosuretype(const upb_handlerattr *attr) {
  2055. return attr->return_closure_type_;
  2056. }
  2057. bool upb_handlerattr_setalwaysok(upb_handlerattr *attr, bool alwaysok) {
  2058. attr->alwaysok_ = alwaysok;
  2059. return true;
  2060. }
  2061. bool upb_handlerattr_alwaysok(const upb_handlerattr *attr) {
  2062. return attr->alwaysok_;
  2063. }
  2064. /* upb_bufhandle **************************************************************/
  2065. size_t upb_bufhandle_objofs(const upb_bufhandle *h) {
  2066. return h->objofs_;
  2067. }
  2068. /* upb_byteshandler ***********************************************************/
  2069. void upb_byteshandler_init(upb_byteshandler* h) {
  2070. memset(h, 0, sizeof(*h));
  2071. }
  2072. // For when we support handlerfree callbacks.
  2073. void upb_byteshandler_uninit(upb_byteshandler* h) {
  2074. UPB_UNUSED(h);
  2075. }
  2076. bool upb_byteshandler_setstartstr(upb_byteshandler *h,
  2077. upb_startstr_handlerfunc *func, void *d) {
  2078. h->table[UPB_STARTSTR_SELECTOR].func = (upb_func*)func;
  2079. h->table[UPB_STARTSTR_SELECTOR].attr.handler_data_ = d;
  2080. return true;
  2081. }
  2082. bool upb_byteshandler_setstring(upb_byteshandler *h,
  2083. upb_string_handlerfunc *func, void *d) {
  2084. h->table[UPB_STRING_SELECTOR].func = (upb_func*)func;
  2085. h->table[UPB_STRING_SELECTOR].attr.handler_data_ = d;
  2086. return true;
  2087. }
  2088. bool upb_byteshandler_setendstr(upb_byteshandler *h,
  2089. upb_endfield_handlerfunc *func, void *d) {
  2090. h->table[UPB_ENDSTR_SELECTOR].func = (upb_func*)func;
  2091. h->table[UPB_ENDSTR_SELECTOR].attr.handler_data_ = d;
  2092. return true;
  2093. }
  2094. /*
  2095. * upb - a minimalist implementation of protocol buffers.
  2096. *
  2097. * Copyright (c) 2012 Google Inc. See LICENSE for details.
  2098. * Author: Josh Haberman <jhaberman@gmail.com>
  2099. *
  2100. * Our key invariants are:
  2101. * 1. reference cycles never span groups
  2102. * 2. for ref2(to, from), we increment to's count iff group(from) != group(to)
  2103. *
  2104. * The previous two are how we avoid leaking cycles. Other important
  2105. * invariants are:
  2106. * 3. for mutable objects "from" and "to", if there exists a ref2(to, from)
  2107. * this implies group(from) == group(to). (In practice, what we implement
  2108. * is even stronger; "from" and "to" will share a group if there has *ever*
  2109. * been a ref2(to, from), but all that is necessary for correctness is the
  2110. * weaker one).
  2111. * 4. mutable and immutable objects are never in the same group.
  2112. */
  2113. #include <setjmp.h>
  2114. #include <stdlib.h>
  2115. static void freeobj(upb_refcounted *o);
  2116. const char untracked_val;
  2117. const void *UPB_UNTRACKED_REF = &untracked_val;
  2118. /* arch-specific atomic primitives *******************************************/
  2119. #ifdef UPB_THREAD_UNSAFE //////////////////////////////////////////////////////
  2120. static void atomic_inc(uint32_t *a) { (*a)++; }
  2121. static bool atomic_dec(uint32_t *a) { return --(*a) == 0; }
  2122. #elif defined(__GNUC__) || defined(__clang__) //////////////////////////////////
  2123. static void atomic_inc(uint32_t *a) { __sync_fetch_and_add(a, 1); }
  2124. static bool atomic_dec(uint32_t *a) { return __sync_sub_and_fetch(a, 1) == 0; }
  2125. #elif defined(WIN32) ///////////////////////////////////////////////////////////
  2126. #include <Windows.h>
  2127. static void atomic_inc(upb_atomic_t *a) { InterlockedIncrement(&a->val); }
  2128. static bool atomic_dec(upb_atomic_t *a) {
  2129. return InterlockedDecrement(&a->val) == 0;
  2130. }
  2131. #else
  2132. #error Atomic primitives not defined for your platform/CPU. \
  2133. Implement them or compile with UPB_THREAD_UNSAFE.
  2134. #endif
  2135. // All static objects point to this refcount.
  2136. // It is special-cased in ref/unref below.
  2137. uint32_t static_refcount = -1;
  2138. // We can avoid atomic ops for statically-declared objects.
  2139. // This is a minor optimization but nice since we can avoid degrading under
  2140. // contention in this case.
  2141. static void refgroup(uint32_t *group) {
  2142. if (group != &static_refcount)
  2143. atomic_inc(group);
  2144. }
  2145. static bool unrefgroup(uint32_t *group) {
  2146. if (group == &static_refcount) {
  2147. return false;
  2148. } else {
  2149. return atomic_dec(group);
  2150. }
  2151. }
  2152. /* Reference tracking (debug only) ********************************************/
  2153. #ifdef UPB_DEBUG_REFS
  2154. #ifdef UPB_THREAD_UNSAFE
  2155. static void upb_lock() {}
  2156. static void upb_unlock() {}
  2157. #else
  2158. // User must define functions that lock/unlock a global mutex and link this
  2159. // file against them.
  2160. void upb_lock();
  2161. void upb_unlock();
  2162. #endif
  2163. // UPB_DEBUG_REFS mode counts on being able to malloc() memory in some
  2164. // code-paths that can normally never fail, like upb_refcounted_ref(). Since
  2165. // we have no way to propagage out-of-memory errors back to the user, and since
  2166. // these errors can only occur in UPB_DEBUG_REFS mode, we immediately fail.
  2167. #define CHECK_OOM(predicate) if (!(predicate)) { assert(predicate); exit(1); }
  2168. typedef struct {
  2169. int count; // How many refs there are (duplicates only allowed for ref2).
  2170. bool is_ref2;
  2171. } trackedref;
  2172. static trackedref *trackedref_new(bool is_ref2) {
  2173. trackedref *ret = malloc(sizeof(*ret));
  2174. CHECK_OOM(ret);
  2175. ret->count = 1;
  2176. ret->is_ref2 = is_ref2;
  2177. return ret;
  2178. }
  2179. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  2180. assert(owner);
  2181. if (owner == UPB_UNTRACKED_REF) return;
  2182. upb_lock();
  2183. upb_value v;
  2184. if (upb_inttable_lookupptr(r->refs, owner, &v)) {
  2185. trackedref *ref = upb_value_getptr(v);
  2186. // Since we allow multiple ref2's for the same to/from pair without
  2187. // allocating separate memory for each one, we lose the fine-grained
  2188. // tracking behavior we get with regular refs. Since ref2s only happen
  2189. // inside upb, we'll accept this limitation until/unless there is a really
  2190. // difficult upb-internal bug that can't be figured out without it.
  2191. assert(ref2);
  2192. assert(ref->is_ref2);
  2193. ref->count++;
  2194. } else {
  2195. trackedref *ref = trackedref_new(ref2);
  2196. bool ok = upb_inttable_insertptr(r->refs, owner, upb_value_ptr(ref));
  2197. CHECK_OOM(ok);
  2198. if (ref2) {
  2199. // We know this cast is safe when it is a ref2, because it's coming from
  2200. // another refcounted object.
  2201. const upb_refcounted *from = owner;
  2202. assert(!upb_inttable_lookupptr(from->ref2s, r, NULL));
  2203. ok = upb_inttable_insertptr(from->ref2s, r, upb_value_ptr(NULL));
  2204. CHECK_OOM(ok);
  2205. }
  2206. }
  2207. upb_unlock();
  2208. }
  2209. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  2210. assert(owner);
  2211. if (owner == UPB_UNTRACKED_REF) return;
  2212. upb_lock();
  2213. upb_value v;
  2214. bool found = upb_inttable_lookupptr(r->refs, owner, &v);
  2215. // This assert will fail if an owner attempts to release a ref it didn't have.
  2216. UPB_ASSERT_VAR(found, found);
  2217. trackedref *ref = upb_value_getptr(v);
  2218. assert(ref->is_ref2 == ref2);
  2219. if (--ref->count == 0) {
  2220. free(ref);
  2221. upb_inttable_removeptr(r->refs, owner, NULL);
  2222. if (ref2) {
  2223. // We know this cast is safe when it is a ref2, because it's coming from
  2224. // another refcounted object.
  2225. const upb_refcounted *from = owner;
  2226. bool removed = upb_inttable_removeptr(from->ref2s, r, NULL);
  2227. assert(removed);
  2228. }
  2229. }
  2230. upb_unlock();
  2231. }
  2232. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  2233. upb_lock();
  2234. upb_value v;
  2235. bool found = upb_inttable_lookupptr(r->refs, owner, &v);
  2236. UPB_ASSERT_VAR(found, found);
  2237. trackedref *ref = upb_value_getptr(v);
  2238. assert(ref->is_ref2 == ref2);
  2239. upb_unlock();
  2240. }
  2241. // Populates the given UPB_CTYPE_INT32 inttable with counts of ref2's that
  2242. // originate from the given owner.
  2243. static void getref2s(const upb_refcounted *owner, upb_inttable *tab) {
  2244. upb_lock();
  2245. upb_inttable_iter i;
  2246. upb_inttable_begin(&i, owner->ref2s);
  2247. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  2248. upb_refcounted *to = (upb_refcounted*)upb_inttable_iter_key(&i);
  2249. // To get the count we need to look in the target's table.
  2250. upb_value v;
  2251. bool found = upb_inttable_lookupptr(to->refs, owner, &v);
  2252. assert(found);
  2253. trackedref *ref = upb_value_getptr(v);
  2254. upb_value count = upb_value_int32(ref->count);
  2255. bool ok = upb_inttable_insertptr(tab, to, count);
  2256. CHECK_OOM(ok);
  2257. }
  2258. upb_unlock();
  2259. }
  2260. typedef struct {
  2261. upb_inttable ref2;
  2262. const upb_refcounted *obj;
  2263. } check_state;
  2264. static void visit_check(const upb_refcounted *obj, const upb_refcounted *subobj,
  2265. void *closure) {
  2266. check_state *s = closure;
  2267. assert(obj == s->obj);
  2268. assert(subobj);
  2269. upb_inttable *ref2 = &s->ref2;
  2270. upb_value v;
  2271. bool removed = upb_inttable_removeptr(ref2, subobj, &v);
  2272. // The following assertion will fail if the visit() function visits a subobj
  2273. // that it did not have a ref2 on, or visits the same subobj too many times.
  2274. assert(removed);
  2275. int32_t newcount = upb_value_getint32(v) - 1;
  2276. if (newcount > 0) {
  2277. upb_inttable_insert(ref2, (uintptr_t)subobj, upb_value_int32(newcount));
  2278. }
  2279. }
  2280. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  2281. void *closure) {
  2282. // In DEBUG_REFS mode we know what existing ref2 refs there are, so we know
  2283. // exactly the set of nodes that visit() should visit. So we verify visit()'s
  2284. // correctness here.
  2285. check_state state;
  2286. state.obj = r;
  2287. bool ok = upb_inttable_init(&state.ref2, UPB_CTYPE_INT32);
  2288. CHECK_OOM(ok);
  2289. getref2s(r, &state.ref2);
  2290. // This should visit any children in the ref2 table.
  2291. if (r->vtbl->visit) r->vtbl->visit(r, visit_check, &state);
  2292. // This assertion will fail if the visit() function missed any children.
  2293. assert(upb_inttable_count(&state.ref2) == 0);
  2294. upb_inttable_uninit(&state.ref2);
  2295. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  2296. }
  2297. static bool trackinit(upb_refcounted *r) {
  2298. r->refs = malloc(sizeof(*r->refs));
  2299. r->ref2s = malloc(sizeof(*r->ref2s));
  2300. if (!r->refs || !r->ref2s) goto err1;
  2301. if (!upb_inttable_init(r->refs, UPB_CTYPE_PTR)) goto err1;
  2302. if (!upb_inttable_init(r->ref2s, UPB_CTYPE_PTR)) goto err2;
  2303. return true;
  2304. err2:
  2305. upb_inttable_uninit(r->refs);
  2306. err1:
  2307. free(r->refs);
  2308. free(r->ref2s);
  2309. return false;
  2310. }
  2311. static void trackfree(const upb_refcounted *r) {
  2312. upb_inttable_uninit(r->refs);
  2313. upb_inttable_uninit(r->ref2s);
  2314. free(r->refs);
  2315. free(r->ref2s);
  2316. }
  2317. #else
  2318. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  2319. UPB_UNUSED(r);
  2320. UPB_UNUSED(owner);
  2321. UPB_UNUSED(ref2);
  2322. }
  2323. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  2324. UPB_UNUSED(r);
  2325. UPB_UNUSED(owner);
  2326. UPB_UNUSED(ref2);
  2327. }
  2328. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  2329. UPB_UNUSED(r);
  2330. UPB_UNUSED(owner);
  2331. UPB_UNUSED(ref2);
  2332. }
  2333. static bool trackinit(upb_refcounted *r) {
  2334. UPB_UNUSED(r);
  2335. return true;
  2336. }
  2337. static void trackfree(const upb_refcounted *r) {
  2338. UPB_UNUSED(r);
  2339. }
  2340. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  2341. void *closure) {
  2342. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  2343. }
  2344. #endif // UPB_DEBUG_REFS
  2345. /* freeze() *******************************************************************/
  2346. // The freeze() operation is by far the most complicated part of this scheme.
  2347. // We compute strongly-connected components and then mutate the graph such that
  2348. // we preserve the invariants documented at the top of this file. And we must
  2349. // handle out-of-memory errors gracefully (without leaving the graph
  2350. // inconsistent), which adds to the fun.
  2351. // The state used by the freeze operation (shared across many functions).
  2352. typedef struct {
  2353. int depth;
  2354. int maxdepth;
  2355. uint64_t index;
  2356. // Maps upb_refcounted* -> attributes (color, etc). attr layout varies by
  2357. // color.
  2358. upb_inttable objattr;
  2359. upb_inttable stack; // stack of upb_refcounted* for Tarjan's algorithm.
  2360. upb_inttable groups; // array of uint32_t*, malloc'd refcounts for new groups
  2361. upb_status *status;
  2362. jmp_buf err;
  2363. } tarjan;
  2364. static void release_ref2(const upb_refcounted *obj,
  2365. const upb_refcounted *subobj,
  2366. void *closure);
  2367. // Node attributes /////////////////////////////////////////////////////////////
  2368. // After our analysis phase all nodes will be either GRAY or WHITE.
  2369. typedef enum {
  2370. BLACK = 0, // Object has not been seen.
  2371. GRAY, // Object has been found via a refgroup but may not be reachable.
  2372. GREEN, // Object is reachable and is currently on the Tarjan stack.
  2373. WHITE, // Object is reachable and has been assigned a group (SCC).
  2374. } color_t;
  2375. UPB_NORETURN static void err(tarjan *t) { longjmp(t->err, 1); }
  2376. UPB_NORETURN static void oom(tarjan *t) {
  2377. upb_status_seterrmsg(t->status, "out of memory");
  2378. err(t);
  2379. }
  2380. static uint64_t trygetattr(const tarjan *t, const upb_refcounted *r) {
  2381. upb_value v;
  2382. return upb_inttable_lookupptr(&t->objattr, r, &v) ?
  2383. upb_value_getuint64(v) : 0;
  2384. }
  2385. static uint64_t getattr(const tarjan *t, const upb_refcounted *r) {
  2386. upb_value v;
  2387. bool found = upb_inttable_lookupptr(&t->objattr, r, &v);
  2388. UPB_ASSERT_VAR(found, found);
  2389. return upb_value_getuint64(v);
  2390. }
  2391. static void setattr(tarjan *t, const upb_refcounted *r, uint64_t attr) {
  2392. upb_inttable_removeptr(&t->objattr, r, NULL);
  2393. upb_inttable_insertptr(&t->objattr, r, upb_value_uint64(attr));
  2394. }
  2395. static color_t color(tarjan *t, const upb_refcounted *r) {
  2396. return trygetattr(t, r) & 0x3; // Color is always stored in the low 2 bits.
  2397. }
  2398. static void set_gray(tarjan *t, const upb_refcounted *r) {
  2399. assert(color(t, r) == BLACK);
  2400. setattr(t, r, GRAY);
  2401. }
  2402. // Pushes an obj onto the Tarjan stack and sets it to GREEN.
  2403. static void push(tarjan *t, const upb_refcounted *r) {
  2404. assert(color(t, r) == BLACK || color(t, r) == GRAY);
  2405. // This defines the attr layout for the GREEN state. "index" and "lowlink"
  2406. // get 31 bits, which is plenty (limit of 2B objects frozen at a time).
  2407. setattr(t, r, GREEN | (t->index << 2) | (t->index << 33));
  2408. if (++t->index == 0x80000000) {
  2409. upb_status_seterrmsg(t->status, "too many objects to freeze");
  2410. err(t);
  2411. }
  2412. upb_inttable_push(&t->stack, upb_value_ptr((void*)r));
  2413. }
  2414. // Pops an obj from the Tarjan stack and sets it to WHITE, with a ptr to its
  2415. // SCC group.
  2416. static upb_refcounted *pop(tarjan *t) {
  2417. upb_refcounted *r = upb_value_getptr(upb_inttable_pop(&t->stack));
  2418. assert(color(t, r) == GREEN);
  2419. // This defines the attr layout for nodes in the WHITE state.
  2420. // Top of group stack is [group, NULL]; we point at group.
  2421. setattr(t, r, WHITE | (upb_inttable_count(&t->groups) - 2) << 8);
  2422. return r;
  2423. }
  2424. static void tarjan_newgroup(tarjan *t) {
  2425. uint32_t *group = malloc(sizeof(*group));
  2426. if (!group) oom(t);
  2427. // Push group and empty group leader (we'll fill in leader later).
  2428. if (!upb_inttable_push(&t->groups, upb_value_ptr(group)) ||
  2429. !upb_inttable_push(&t->groups, upb_value_ptr(NULL))) {
  2430. free(group);
  2431. oom(t);
  2432. }
  2433. *group = 0;
  2434. }
  2435. static uint32_t idx(tarjan *t, const upb_refcounted *r) {
  2436. assert(color(t, r) == GREEN);
  2437. return (getattr(t, r) >> 2) & 0x7FFFFFFF;
  2438. }
  2439. static uint32_t lowlink(tarjan *t, const upb_refcounted *r) {
  2440. if (color(t, r) == GREEN) {
  2441. return getattr(t, r) >> 33;
  2442. } else {
  2443. return UINT32_MAX;
  2444. }
  2445. }
  2446. static void set_lowlink(tarjan *t, const upb_refcounted *r, uint32_t lowlink) {
  2447. assert(color(t, r) == GREEN);
  2448. setattr(t, r, ((uint64_t)lowlink << 33) | (getattr(t, r) & 0x1FFFFFFFF));
  2449. }
  2450. static uint32_t *group(tarjan *t, upb_refcounted *r) {
  2451. assert(color(t, r) == WHITE);
  2452. uint64_t groupnum = getattr(t, r) >> 8;
  2453. upb_value v;
  2454. bool found = upb_inttable_lookup(&t->groups, groupnum, &v);
  2455. UPB_ASSERT_VAR(found, found);
  2456. return upb_value_getptr(v);
  2457. }
  2458. // If the group leader for this object's group has not previously been set,
  2459. // the given object is assigned to be its leader.
  2460. static upb_refcounted *groupleader(tarjan *t, upb_refcounted *r) {
  2461. assert(color(t, r) == WHITE);
  2462. uint64_t leader_slot = (getattr(t, r) >> 8) + 1;
  2463. upb_value v;
  2464. bool found = upb_inttable_lookup(&t->groups, leader_slot, &v);
  2465. UPB_ASSERT_VAR(found, found);
  2466. if (upb_value_getptr(v)) {
  2467. return upb_value_getptr(v);
  2468. } else {
  2469. upb_inttable_remove(&t->groups, leader_slot, NULL);
  2470. upb_inttable_insert(&t->groups, leader_slot, upb_value_ptr(r));
  2471. return r;
  2472. }
  2473. }
  2474. // Tarjan's algorithm //////////////////////////////////////////////////////////
  2475. // See:
  2476. // http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
  2477. static void do_tarjan(const upb_refcounted *obj, tarjan *t);
  2478. static void tarjan_visit(const upb_refcounted *obj,
  2479. const upb_refcounted *subobj,
  2480. void *closure) {
  2481. tarjan *t = closure;
  2482. if (++t->depth > t->maxdepth) {
  2483. upb_status_seterrf(t->status, "graph too deep to freeze (%d)", t->maxdepth);
  2484. err(t);
  2485. } else if (subobj->is_frozen || color(t, subobj) == WHITE) {
  2486. // Do nothing: we don't want to visit or color already-frozen nodes,
  2487. // and WHITE nodes have already been assigned a SCC.
  2488. } else if (color(t, subobj) < GREEN) {
  2489. // Subdef has not yet been visited; recurse on it.
  2490. do_tarjan(subobj, t);
  2491. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), lowlink(t, subobj)));
  2492. } else if (color(t, subobj) == GREEN) {
  2493. // Subdef is in the stack and hence in the current SCC.
  2494. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), idx(t, subobj)));
  2495. }
  2496. --t->depth;
  2497. }
  2498. static void do_tarjan(const upb_refcounted *obj, tarjan *t) {
  2499. if (color(t, obj) == BLACK) {
  2500. // We haven't seen this object's group; mark the whole group GRAY.
  2501. const upb_refcounted *o = obj;
  2502. do { set_gray(t, o); } while ((o = o->next) != obj);
  2503. }
  2504. push(t, obj);
  2505. visit(obj, tarjan_visit, t);
  2506. if (lowlink(t, obj) == idx(t, obj)) {
  2507. tarjan_newgroup(t);
  2508. while (pop(t) != obj)
  2509. ;
  2510. }
  2511. }
  2512. // freeze() ////////////////////////////////////////////////////////////////////
  2513. static void crossref(const upb_refcounted *r, const upb_refcounted *subobj,
  2514. void *_t) {
  2515. tarjan *t = _t;
  2516. assert(color(t, r) > BLACK);
  2517. if (color(t, subobj) > BLACK && r->group != subobj->group) {
  2518. // Previously this ref was not reflected in subobj->group because they
  2519. // were in the same group; now that they are split a ref must be taken.
  2520. refgroup(subobj->group);
  2521. }
  2522. }
  2523. static bool freeze(upb_refcounted *const*roots, int n, upb_status *s,
  2524. int maxdepth) {
  2525. volatile bool ret = false;
  2526. // We run in two passes so that we can allocate all memory before performing
  2527. // any mutation of the input -- this allows us to leave the input unchanged
  2528. // in the case of memory allocation failure.
  2529. tarjan t;
  2530. t.index = 0;
  2531. t.depth = 0;
  2532. t.maxdepth = maxdepth;
  2533. t.status = s;
  2534. if (!upb_inttable_init(&t.objattr, UPB_CTYPE_UINT64)) goto err1;
  2535. if (!upb_inttable_init(&t.stack, UPB_CTYPE_PTR)) goto err2;
  2536. if (!upb_inttable_init(&t.groups, UPB_CTYPE_PTR)) goto err3;
  2537. if (setjmp(t.err) != 0) goto err4;
  2538. for (int i = 0; i < n; i++) {
  2539. if (color(&t, roots[i]) < GREEN) {
  2540. do_tarjan(roots[i], &t);
  2541. }
  2542. }
  2543. // If we've made it this far, no further errors are possible so it's safe to
  2544. // mutate the objects without risk of leaving them in an inconsistent state.
  2545. ret = true;
  2546. // The transformation that follows requires care. The preconditions are:
  2547. // - all objects in attr map are WHITE or GRAY, and are in mutable groups
  2548. // (groups of all mutable objs)
  2549. // - no ref2(to, from) refs have incremented count(to) if both "to" and
  2550. // "from" are in our attr map (this follows from invariants (2) and (3))
  2551. // Pass 1: we remove WHITE objects from their mutable groups, and add them to
  2552. // new groups according to the SCC's we computed. These new groups will
  2553. // consist of only frozen objects. None will be immediately collectible,
  2554. // because WHITE objects are by definition reachable from one of "roots",
  2555. // which the caller must own refs on.
  2556. upb_inttable_iter i;
  2557. upb_inttable_begin(&i, &t.objattr);
  2558. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  2559. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&i);
  2560. // Since removal from a singly-linked list requires access to the object's
  2561. // predecessor, we consider obj->next instead of obj for moving. With the
  2562. // while() loop we guarantee that we will visit every node's predecessor.
  2563. // Proof:
  2564. // 1. every node's predecessor is in our attr map.
  2565. // 2. though the loop body may change a node's predecessor, it will only
  2566. // change it to be the node we are currently operating on, so with a
  2567. // while() loop we guarantee ourselves the chance to remove each node.
  2568. while (color(&t, obj->next) == WHITE &&
  2569. group(&t, obj->next) != obj->next->group) {
  2570. // Remove from old group.
  2571. upb_refcounted *move = obj->next;
  2572. if (obj == move) {
  2573. // Removing the last object from a group.
  2574. assert(*obj->group == obj->individual_count);
  2575. free(obj->group);
  2576. } else {
  2577. obj->next = move->next;
  2578. // This may decrease to zero; we'll collect GRAY objects (if any) that
  2579. // remain in the group in the third pass.
  2580. assert(*move->group >= move->individual_count);
  2581. *move->group -= move->individual_count;
  2582. }
  2583. // Add to new group.
  2584. upb_refcounted *leader = groupleader(&t, move);
  2585. if (move == leader) {
  2586. // First object added to new group is its leader.
  2587. move->group = group(&t, move);
  2588. move->next = move;
  2589. *move->group = move->individual_count;
  2590. } else {
  2591. // Group already has at least one object in it.
  2592. assert(leader->group == group(&t, move));
  2593. move->group = group(&t, move);
  2594. move->next = leader->next;
  2595. leader->next = move;
  2596. *move->group += move->individual_count;
  2597. }
  2598. move->is_frozen = true;
  2599. }
  2600. }
  2601. // Pass 2: GRAY and WHITE objects "obj" with ref2(to, obj) references must
  2602. // increment count(to) if group(obj) != group(to) (which could now be the
  2603. // case if "to" was just frozen).
  2604. upb_inttable_begin(&i, &t.objattr);
  2605. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  2606. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&i);
  2607. visit(obj, crossref, &t);
  2608. }
  2609. // Pass 3: GRAY objects are collected if their group's refcount dropped to
  2610. // zero when we removed its white nodes. This can happen if they had only
  2611. // been kept alive by virtue of sharing a group with an object that was just
  2612. // frozen.
  2613. //
  2614. // It is important that we do this last, since the GRAY object's free()
  2615. // function could call unref2() on just-frozen objects, which will decrement
  2616. // refs that were added in pass 2.
  2617. upb_inttable_begin(&i, &t.objattr);
  2618. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  2619. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&i);
  2620. if (obj->group == NULL || *obj->group == 0) {
  2621. if (obj->group) {
  2622. // We eagerly free() the group's count (since we can't easily determine
  2623. // the group's remaining size it's the easiest way to ensure it gets
  2624. // done).
  2625. free(obj->group);
  2626. // Visit to release ref2's (done in a separate pass since release_ref2
  2627. // depends on o->group being unmodified so it can test merged()).
  2628. upb_refcounted *o = obj;
  2629. do { visit(o, release_ref2, NULL); } while ((o = o->next) != obj);
  2630. // Mark "group" fields as NULL so we know to free the objects later in
  2631. // this loop, but also don't try to delete the group twice.
  2632. o = obj;
  2633. do { o->group = NULL; } while ((o = o->next) != obj);
  2634. }
  2635. freeobj(obj);
  2636. }
  2637. }
  2638. err4:
  2639. if (!ret) {
  2640. upb_inttable_begin(&i, &t.groups);
  2641. for(; !upb_inttable_done(&i); upb_inttable_next(&i))
  2642. free(upb_value_getptr(upb_inttable_iter_value(&i)));
  2643. }
  2644. upb_inttable_uninit(&t.groups);
  2645. err3:
  2646. upb_inttable_uninit(&t.stack);
  2647. err2:
  2648. upb_inttable_uninit(&t.objattr);
  2649. err1:
  2650. return ret;
  2651. }
  2652. /* Misc internal functions ***************************************************/
  2653. static bool merged(const upb_refcounted *r, const upb_refcounted *r2) {
  2654. return r->group == r2->group;
  2655. }
  2656. static void merge(upb_refcounted *r, upb_refcounted *from) {
  2657. if (merged(r, from)) return;
  2658. *r->group += *from->group;
  2659. free(from->group);
  2660. upb_refcounted *base = from;
  2661. // Set all refcount pointers in the "from" chain to the merged refcount.
  2662. //
  2663. // TODO(haberman): this linear algorithm can result in an overall O(n^2) bound
  2664. // if the user continuously extends a group by one object. Prevent this by
  2665. // using one of the techniques in this paper:
  2666. // ftp://www.ncedc.org/outgoing/geomorph/dino/orals/p245-tarjan.pdf
  2667. do { from->group = r->group; } while ((from = from->next) != base);
  2668. // Merge the two circularly linked lists by swapping their next pointers.
  2669. upb_refcounted *tmp = r->next;
  2670. r->next = base->next;
  2671. base->next = tmp;
  2672. }
  2673. static void unref(const upb_refcounted *r);
  2674. static void release_ref2(const upb_refcounted *obj,
  2675. const upb_refcounted *subobj,
  2676. void *closure) {
  2677. UPB_UNUSED(closure);
  2678. untrack(subobj, obj, true);
  2679. if (!merged(obj, subobj)) {
  2680. assert(subobj->is_frozen);
  2681. unref(subobj);
  2682. }
  2683. }
  2684. static void unref(const upb_refcounted *r) {
  2685. if (unrefgroup(r->group)) {
  2686. free(r->group);
  2687. // In two passes, since release_ref2 needs a guarantee that any subobjs
  2688. // are alive.
  2689. const upb_refcounted *o = r;
  2690. do { visit(o, release_ref2, NULL); } while((o = o->next) != r);
  2691. o = r;
  2692. do {
  2693. const upb_refcounted *next = o->next;
  2694. assert(o->is_frozen || o->individual_count == 0);
  2695. freeobj((upb_refcounted*)o);
  2696. o = next;
  2697. } while(o != r);
  2698. }
  2699. }
  2700. static void freeobj(upb_refcounted *o) {
  2701. trackfree(o);
  2702. o->vtbl->free((upb_refcounted*)o);
  2703. }
  2704. /* Public interface ***********************************************************/
  2705. bool upb_refcounted_init(upb_refcounted *r,
  2706. const struct upb_refcounted_vtbl *vtbl,
  2707. const void *owner) {
  2708. r->next = r;
  2709. r->vtbl = vtbl;
  2710. r->individual_count = 0;
  2711. r->is_frozen = false;
  2712. r->group = malloc(sizeof(*r->group));
  2713. if (!r->group) return false;
  2714. *r->group = 0;
  2715. if (!trackinit(r)) {
  2716. free(r->group);
  2717. return false;
  2718. }
  2719. upb_refcounted_ref(r, owner);
  2720. return true;
  2721. }
  2722. bool upb_refcounted_isfrozen(const upb_refcounted *r) {
  2723. return r->is_frozen;
  2724. }
  2725. void upb_refcounted_ref(const upb_refcounted *r, const void *owner) {
  2726. track(r, owner, false);
  2727. if (!r->is_frozen)
  2728. ((upb_refcounted*)r)->individual_count++;
  2729. refgroup(r->group);
  2730. }
  2731. void upb_refcounted_unref(const upb_refcounted *r, const void *owner) {
  2732. untrack(r, owner, false);
  2733. if (!r->is_frozen)
  2734. ((upb_refcounted*)r)->individual_count--;
  2735. unref(r);
  2736. }
  2737. void upb_refcounted_ref2(const upb_refcounted *r, upb_refcounted *from) {
  2738. assert(!from->is_frozen); // Non-const pointer implies this.
  2739. track(r, from, true);
  2740. if (r->is_frozen) {
  2741. refgroup(r->group);
  2742. } else {
  2743. merge((upb_refcounted*)r, from);
  2744. }
  2745. }
  2746. void upb_refcounted_unref2(const upb_refcounted *r, upb_refcounted *from) {
  2747. assert(!from->is_frozen); // Non-const pointer implies this.
  2748. untrack(r, from, true);
  2749. if (r->is_frozen) {
  2750. unref(r);
  2751. } else {
  2752. assert(merged(r, from));
  2753. }
  2754. }
  2755. void upb_refcounted_donateref(
  2756. const upb_refcounted *r, const void *from, const void *to) {
  2757. assert(from != to);
  2758. if (to != NULL)
  2759. upb_refcounted_ref(r, to);
  2760. if (from != NULL)
  2761. upb_refcounted_unref(r, from);
  2762. }
  2763. void upb_refcounted_checkref(const upb_refcounted *r, const void *owner) {
  2764. checkref(r, owner, false);
  2765. }
  2766. bool upb_refcounted_freeze(upb_refcounted *const*roots, int n, upb_status *s,
  2767. int maxdepth) {
  2768. for (int i = 0; i < n; i++) {
  2769. assert(!roots[i]->is_frozen);
  2770. }
  2771. return freeze(roots, n, s, maxdepth);
  2772. }
  2773. /*
  2774. * upb - a minimalist implementation of protocol buffers.
  2775. *
  2776. * Copyright (c) 2013 Google Inc. See LICENSE for details.
  2777. * Author: Josh Haberman <jhaberman@gmail.com>
  2778. */
  2779. #include <stdlib.h>
  2780. // Fallback implementation if the shim is not specialized by the JIT.
  2781. #define SHIM_WRITER(type, ctype) \
  2782. bool upb_shim_set ## type (void *c, const void *hd, ctype val) { \
  2783. uint8_t *m = c; \
  2784. const upb_shim_data *d = hd; \
  2785. if (d->hasbit > 0) \
  2786. *(uint8_t*)&m[d->hasbit / 8] |= 1 << (d->hasbit % 8); \
  2787. *(ctype*)&m[d->offset] = val; \
  2788. return true; \
  2789. } \
  2790. SHIM_WRITER(double, double)
  2791. SHIM_WRITER(float, float)
  2792. SHIM_WRITER(int32, int32_t)
  2793. SHIM_WRITER(int64, int64_t)
  2794. SHIM_WRITER(uint32, uint32_t)
  2795. SHIM_WRITER(uint64, uint64_t)
  2796. SHIM_WRITER(bool, bool)
  2797. #undef SHIM_WRITER
  2798. bool upb_shim_set(upb_handlers *h, const upb_fielddef *f, size_t offset,
  2799. int32_t hasbit) {
  2800. upb_shim_data *d = malloc(sizeof(*d));
  2801. if (!d) return false;
  2802. d->offset = offset;
  2803. d->hasbit = hasbit;
  2804. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  2805. upb_handlerattr_sethandlerdata(&attr, d);
  2806. upb_handlerattr_setalwaysok(&attr, true);
  2807. upb_handlers_addcleanup(h, d, free);
  2808. #define TYPE(u, l) \
  2809. case UPB_TYPE_##u: \
  2810. ok = upb_handlers_set##l(h, f, upb_shim_set##l, &attr); break;
  2811. bool ok = false;
  2812. switch (upb_fielddef_type(f)) {
  2813. TYPE(INT64, int64);
  2814. TYPE(INT32, int32);
  2815. TYPE(ENUM, int32);
  2816. TYPE(UINT64, uint64);
  2817. TYPE(UINT32, uint32);
  2818. TYPE(DOUBLE, double);
  2819. TYPE(FLOAT, float);
  2820. TYPE(BOOL, bool);
  2821. default: assert(false); break;
  2822. }
  2823. #undef TYPE
  2824. upb_handlerattr_uninit(&attr);
  2825. return ok;
  2826. }
  2827. const upb_shim_data *upb_shim_getdata(const upb_handlers *h, upb_selector_t s,
  2828. upb_fieldtype_t *type) {
  2829. upb_func *f = upb_handlers_gethandler(h, s);
  2830. if ((upb_int64_handlerfunc*)f == upb_shim_setint64) {
  2831. *type = UPB_TYPE_INT64;
  2832. } else if ((upb_int32_handlerfunc*)f == upb_shim_setint32) {
  2833. *type = UPB_TYPE_INT32;
  2834. } else if ((upb_uint64_handlerfunc*)f == upb_shim_setuint64) {
  2835. *type = UPB_TYPE_UINT64;
  2836. } else if ((upb_uint32_handlerfunc*)f == upb_shim_setuint32) {
  2837. *type = UPB_TYPE_UINT32;
  2838. } else if ((upb_double_handlerfunc*)f == upb_shim_setdouble) {
  2839. *type = UPB_TYPE_DOUBLE;
  2840. } else if ((upb_float_handlerfunc*)f == upb_shim_setfloat) {
  2841. *type = UPB_TYPE_FLOAT;
  2842. } else if ((upb_bool_handlerfunc*)f == upb_shim_setbool) {
  2843. *type = UPB_TYPE_BOOL;
  2844. } else {
  2845. return NULL;
  2846. }
  2847. return (const upb_shim_data*)upb_handlers_gethandlerdata(h, s);
  2848. }
  2849. /*
  2850. * upb - a minimalist implementation of protocol buffers.
  2851. *
  2852. * Copyright (c) 2008-2012 Google Inc. See LICENSE for details.
  2853. * Author: Josh Haberman <jhaberman@gmail.com>
  2854. */
  2855. #include <stdlib.h>
  2856. #include <string.h>
  2857. bool upb_symtab_isfrozen(const upb_symtab *s) {
  2858. return upb_refcounted_isfrozen(UPB_UPCAST(s));
  2859. }
  2860. void upb_symtab_ref(const upb_symtab *s, const void *owner) {
  2861. upb_refcounted_ref(UPB_UPCAST(s), owner);
  2862. }
  2863. void upb_symtab_unref(const upb_symtab *s, const void *owner) {
  2864. upb_refcounted_unref(UPB_UPCAST(s), owner);
  2865. }
  2866. void upb_symtab_donateref(
  2867. const upb_symtab *s, const void *from, const void *to) {
  2868. upb_refcounted_donateref(UPB_UPCAST(s), from, to);
  2869. }
  2870. void upb_symtab_checkref(const upb_symtab *s, const void *owner) {
  2871. upb_refcounted_checkref(UPB_UPCAST(s), owner);
  2872. }
  2873. static void upb_symtab_free(upb_refcounted *r) {
  2874. upb_symtab *s = (upb_symtab*)r;
  2875. upb_strtable_iter i;
  2876. upb_strtable_begin(&i, &s->symtab);
  2877. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  2878. const upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  2879. upb_def_unref(def, s);
  2880. }
  2881. upb_strtable_uninit(&s->symtab);
  2882. free(s);
  2883. }
  2884. upb_symtab *upb_symtab_new(const void *owner) {
  2885. static const struct upb_refcounted_vtbl vtbl = {NULL, &upb_symtab_free};
  2886. upb_symtab *s = malloc(sizeof(*s));
  2887. upb_refcounted_init(UPB_UPCAST(s), &vtbl, owner);
  2888. upb_strtable_init(&s->symtab, UPB_CTYPE_PTR);
  2889. return s;
  2890. }
  2891. void upb_symtab_freeze(upb_symtab *s) {
  2892. assert(!upb_symtab_isfrozen(s));
  2893. upb_refcounted *r = UPB_UPCAST(s);
  2894. // The symtab does not take ref2's (see refcounted.h) on the defs, because
  2895. // defs cannot refer back to the table and therefore cannot create cycles. So
  2896. // 0 will suffice for maxdepth here.
  2897. bool ok = upb_refcounted_freeze(&r, 1, NULL, 0);
  2898. UPB_ASSERT_VAR(ok, ok);
  2899. }
  2900. const upb_def *upb_symtab_lookup(const upb_symtab *s, const char *sym) {
  2901. upb_value v;
  2902. upb_def *ret = upb_strtable_lookup(&s->symtab, sym, &v) ?
  2903. upb_value_getptr(v) : NULL;
  2904. return ret;
  2905. }
  2906. const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym) {
  2907. upb_value v;
  2908. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  2909. upb_value_getptr(v) : NULL;
  2910. return def ? upb_dyncast_msgdef(def) : NULL;
  2911. }
  2912. const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym) {
  2913. upb_value v;
  2914. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  2915. upb_value_getptr(v) : NULL;
  2916. return def ? upb_dyncast_enumdef(def) : NULL;
  2917. }
  2918. // Given a symbol and the base symbol inside which it is defined, find the
  2919. // symbol's definition in t.
  2920. static upb_def *upb_resolvename(const upb_strtable *t,
  2921. const char *base, const char *sym) {
  2922. if(strlen(sym) == 0) return NULL;
  2923. if(sym[0] == '.') {
  2924. // Symbols starting with '.' are absolute, so we do a single lookup.
  2925. // Slice to omit the leading '.'
  2926. upb_value v;
  2927. return upb_strtable_lookup(t, sym + 1, &v) ? upb_value_getptr(v) : NULL;
  2928. } else {
  2929. // Remove components from base until we find an entry or run out.
  2930. // TODO: This branch is totally broken, but currently not used.
  2931. (void)base;
  2932. assert(false);
  2933. return NULL;
  2934. }
  2935. }
  2936. const upb_def *upb_symtab_resolve(const upb_symtab *s, const char *base,
  2937. const char *sym) {
  2938. upb_def *ret = upb_resolvename(&s->symtab, base, sym);
  2939. return ret;
  2940. }
  2941. // Searches def and its children to find defs that have the same name as any
  2942. // def in "addtab." Returns true if any where found, and as a side-effect adds
  2943. // duplicates of these defs into addtab.
  2944. //
  2945. // We use a modified depth-first traversal that traverses each SCC (which we
  2946. // already computed) as if it were a single node. This allows us to traverse
  2947. // the possibly-cyclic graph as if it were a DAG and to dup the correct set of
  2948. // nodes with O(n) time.
  2949. static bool upb_resolve_dfs(const upb_def *def, upb_strtable *addtab,
  2950. const void *new_owner, upb_inttable *seen,
  2951. upb_status *s) {
  2952. // Memoize results of this function for efficiency (since we're traversing a
  2953. // DAG this is not needed to limit the depth of the search).
  2954. upb_value v;
  2955. if (upb_inttable_lookup(seen, (uintptr_t)def, &v))
  2956. return upb_value_getbool(v);
  2957. // Visit submessages for all messages in the SCC.
  2958. bool need_dup = false;
  2959. const upb_def *base = def;
  2960. do {
  2961. assert(upb_def_isfrozen(def));
  2962. if (def->type == UPB_DEF_FIELD) continue;
  2963. upb_value v;
  2964. if (upb_strtable_lookup(addtab, upb_def_fullname(def), &v)) {
  2965. need_dup = true;
  2966. }
  2967. // For messages, continue the recursion by visiting all subdefs.
  2968. const upb_msgdef *m = upb_dyncast_msgdef(def);
  2969. if (m) {
  2970. upb_msg_field_iter i;
  2971. for(upb_msg_field_begin(&i, m);
  2972. !upb_msg_field_done(&i);
  2973. upb_msg_field_next(&i)) {
  2974. upb_fielddef *f = upb_msg_iter_field(&i);
  2975. if (!upb_fielddef_hassubdef(f)) continue;
  2976. // |= to avoid short-circuit; we need its side-effects.
  2977. need_dup |= upb_resolve_dfs(
  2978. upb_fielddef_subdef(f), addtab, new_owner, seen, s);
  2979. if (!upb_ok(s)) return false;
  2980. }
  2981. }
  2982. } while ((def = (upb_def*)def->base.next) != base);
  2983. if (need_dup) {
  2984. // Dup any defs that don't already have entries in addtab.
  2985. def = base;
  2986. do {
  2987. if (def->type == UPB_DEF_FIELD) continue;
  2988. const char *name = upb_def_fullname(def);
  2989. if (!upb_strtable_lookup(addtab, name, NULL)) {
  2990. upb_def *newdef = upb_def_dup(def, new_owner);
  2991. if (!newdef) goto oom;
  2992. newdef->came_from_user = false;
  2993. if (!upb_strtable_insert(addtab, name, upb_value_ptr(newdef)))
  2994. goto oom;
  2995. }
  2996. } while ((def = (upb_def*)def->base.next) != base);
  2997. }
  2998. upb_inttable_insert(seen, (uintptr_t)def, upb_value_bool(need_dup));
  2999. return need_dup;
  3000. oom:
  3001. upb_status_seterrmsg(s, "out of memory");
  3002. return false;
  3003. }
  3004. // TODO(haberman): we need a lot more testing of error conditions.
  3005. // The came_from_user stuff in particular is not tested.
  3006. bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, int n, void *ref_donor,
  3007. upb_status *status) {
  3008. assert(!upb_symtab_isfrozen(s));
  3009. upb_def **add_defs = NULL;
  3010. upb_strtable addtab;
  3011. if (!upb_strtable_init(&addtab, UPB_CTYPE_PTR)) {
  3012. upb_status_seterrmsg(status, "out of memory");
  3013. return false;
  3014. }
  3015. // Add new defs to our "add" set.
  3016. for (int i = 0; i < n; i++) {
  3017. upb_def *def = defs[i];
  3018. if (upb_def_isfrozen(def)) {
  3019. upb_status_seterrmsg(status, "added defs must be mutable");
  3020. goto err;
  3021. }
  3022. assert(!upb_def_isfrozen(def));
  3023. const char *fullname = upb_def_fullname(def);
  3024. if (!fullname) {
  3025. upb_status_seterrmsg(
  3026. status, "Anonymous defs cannot be added to a symtab");
  3027. goto err;
  3028. }
  3029. upb_fielddef *f = upb_dyncast_fielddef_mutable(def);
  3030. if (f) {
  3031. if (!upb_fielddef_containingtypename(f)) {
  3032. upb_status_seterrmsg(status,
  3033. "Standalone fielddefs must have a containing type "
  3034. "(extendee) name set");
  3035. goto err;
  3036. }
  3037. } else {
  3038. if (upb_strtable_lookup(&addtab, fullname, NULL)) {
  3039. upb_status_seterrf(status, "Conflicting defs named '%s'", fullname);
  3040. goto err;
  3041. }
  3042. // We need this to back out properly, because if there is a failure we
  3043. // need to donate the ref back to the caller.
  3044. def->came_from_user = true;
  3045. upb_def_donateref(def, ref_donor, s);
  3046. if (!upb_strtable_insert(&addtab, fullname, upb_value_ptr(def)))
  3047. goto oom_err;
  3048. }
  3049. }
  3050. // Add standalone fielddefs (ie. extensions) to the appropriate messages.
  3051. // If the appropriate message only exists in the existing symtab, duplicate
  3052. // it so we have a mutable copy we can add the fields to.
  3053. for (int i = 0; i < n; i++) {
  3054. upb_def *def = defs[i];
  3055. upb_fielddef *f = upb_dyncast_fielddef_mutable(def);
  3056. if (!f) continue;
  3057. const char *msgname = upb_fielddef_containingtypename(f);
  3058. // We validated this earlier in this function.
  3059. assert(msgname);
  3060. // If the extendee name is absolutely qualified, move past the initial ".".
  3061. // TODO(haberman): it is not obvious what it would mean if this was not
  3062. // absolutely qualified.
  3063. if (msgname[0] == '.') {
  3064. msgname++;
  3065. }
  3066. upb_value v;
  3067. upb_msgdef *m;
  3068. if (upb_strtable_lookup(&addtab, msgname, &v)) {
  3069. // Extendee is in the set of defs the user asked us to add.
  3070. m = upb_value_getptr(v);
  3071. } else {
  3072. // Need to find and dup the extendee from the existing symtab.
  3073. const upb_msgdef *frozen_m = upb_symtab_lookupmsg(s, msgname);
  3074. if (!frozen_m) {
  3075. upb_status_seterrf(status,
  3076. "Tried to extend message %s that does not exist "
  3077. "in this SymbolTable.",
  3078. msgname);
  3079. goto err;
  3080. }
  3081. m = upb_msgdef_dup(frozen_m, s);
  3082. if (!m) goto oom_err;
  3083. if (!upb_strtable_insert(&addtab, msgname, upb_value_ptr(m))) {
  3084. upb_msgdef_unref(m, s);
  3085. goto oom_err;
  3086. }
  3087. }
  3088. if (!upb_msgdef_addfield(m, f, ref_donor, status)) {
  3089. goto err;
  3090. }
  3091. }
  3092. // Add dups of any existing def that can reach a def with the same name as
  3093. // anything in our "add" set.
  3094. upb_inttable seen;
  3095. if (!upb_inttable_init(&seen, UPB_CTYPE_BOOL)) goto oom_err;
  3096. upb_strtable_iter i;
  3097. upb_strtable_begin(&i, &s->symtab);
  3098. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  3099. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  3100. upb_resolve_dfs(def, &addtab, s, &seen, status);
  3101. if (!upb_ok(status)) goto err;
  3102. }
  3103. upb_inttable_uninit(&seen);
  3104. // Now using the table, resolve symbolic references for subdefs.
  3105. upb_strtable_begin(&i, &addtab);
  3106. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  3107. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  3108. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  3109. if (!m) continue;
  3110. // Type names are resolved relative to the message in which they appear.
  3111. const char *base = upb_msgdef_fullname(m);
  3112. upb_msg_field_iter j;
  3113. for(upb_msg_field_begin(&j, m);
  3114. !upb_msg_field_done(&j);
  3115. upb_msg_field_next(&j)) {
  3116. upb_fielddef *f = upb_msg_iter_field(&j);
  3117. const char *name = upb_fielddef_subdefname(f);
  3118. if (name && !upb_fielddef_subdef(f)) {
  3119. // Try the lookup in the current set of to-be-added defs first. If not
  3120. // there, try existing defs.
  3121. upb_def *subdef = upb_resolvename(&addtab, base, name);
  3122. if (subdef == NULL) {
  3123. subdef = upb_resolvename(&s->symtab, base, name);
  3124. }
  3125. if (subdef == NULL) {
  3126. upb_status_seterrf(
  3127. status, "couldn't resolve name '%s' in message '%s'", name, base);
  3128. goto err;
  3129. } else if (!upb_fielddef_setsubdef(f, subdef, status)) {
  3130. goto err;
  3131. }
  3132. }
  3133. }
  3134. }
  3135. // We need an array of the defs in addtab, for passing to upb_def_freeze.
  3136. add_defs = malloc(sizeof(void*) * upb_strtable_count(&addtab));
  3137. if (add_defs == NULL) goto oom_err;
  3138. upb_strtable_begin(&i, &addtab);
  3139. for (n = 0; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  3140. add_defs[n++] = upb_value_getptr(upb_strtable_iter_value(&i));
  3141. }
  3142. if (!upb_def_freeze(add_defs, n, status)) goto err;
  3143. // This must be delayed until all errors have been detected, since error
  3144. // recovery code uses this table to cleanup defs.
  3145. upb_strtable_uninit(&addtab);
  3146. // TODO(haberman) we don't properly handle errors after this point (like
  3147. // OOM in upb_strtable_insert() below).
  3148. for (int i = 0; i < n; i++) {
  3149. upb_def *def = add_defs[i];
  3150. const char *name = upb_def_fullname(def);
  3151. upb_value v;
  3152. if (upb_strtable_remove(&s->symtab, name, &v)) {
  3153. const upb_def *def = upb_value_getptr(v);
  3154. upb_def_unref(def, s);
  3155. }
  3156. bool success = upb_strtable_insert(&s->symtab, name, upb_value_ptr(def));
  3157. UPB_ASSERT_VAR(success, success == true);
  3158. }
  3159. free(add_defs);
  3160. return true;
  3161. oom_err:
  3162. upb_status_seterrmsg(status, "out of memory");
  3163. err: {
  3164. // For defs the user passed in, we need to donate the refs back. For defs
  3165. // we dup'd, we need to just unref them.
  3166. upb_strtable_iter i;
  3167. upb_strtable_begin(&i, &addtab);
  3168. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  3169. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  3170. bool came_from_user = def->came_from_user;
  3171. def->came_from_user = false;
  3172. if (came_from_user) {
  3173. upb_def_donateref(def, s, ref_donor);
  3174. } else {
  3175. upb_def_unref(def, s);
  3176. }
  3177. }
  3178. }
  3179. upb_strtable_uninit(&addtab);
  3180. free(add_defs);
  3181. assert(!upb_ok(status));
  3182. return false;
  3183. }
  3184. // Iteration.
  3185. static void advance_to_matching(upb_symtab_iter *iter) {
  3186. if (iter->type == UPB_DEF_ANY)
  3187. return;
  3188. while (!upb_strtable_done(&iter->iter) &&
  3189. iter->type != upb_symtab_iter_def(iter)->type) {
  3190. upb_strtable_next(&iter->iter);
  3191. }
  3192. }
  3193. void upb_symtab_begin(upb_symtab_iter *iter, const upb_symtab *s,
  3194. upb_deftype_t type) {
  3195. upb_strtable_begin(&iter->iter, &s->symtab);
  3196. iter->type = type;
  3197. advance_to_matching(iter);
  3198. }
  3199. void upb_symtab_next(upb_symtab_iter *iter) {
  3200. upb_strtable_next(&iter->iter);
  3201. advance_to_matching(iter);
  3202. }
  3203. bool upb_symtab_done(const upb_symtab_iter *iter) {
  3204. return upb_strtable_done(&iter->iter);
  3205. }
  3206. const upb_def *upb_symtab_iter_def(const upb_symtab_iter *iter) {
  3207. return upb_value_getptr(upb_strtable_iter_value(&iter->iter));
  3208. }
  3209. /*
  3210. * upb - a minimalist implementation of protocol buffers.
  3211. *
  3212. * Copyright (c) 2009 Google Inc. See LICENSE for details.
  3213. * Author: Josh Haberman <jhaberman@gmail.com>
  3214. *
  3215. * Implementation is heavily inspired by Lua's ltable.c.
  3216. */
  3217. #include <stdlib.h>
  3218. #include <string.h>
  3219. #define UPB_MAXARRSIZE 16 // 64k.
  3220. // From Chromium.
  3221. #define ARRAY_SIZE(x) \
  3222. ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
  3223. static const double MAX_LOAD = 0.85;
  3224. // The minimum utilization of the array part of a mixed hash/array table. This
  3225. // is a speed/memory-usage tradeoff (though it's not straightforward because of
  3226. // cache effects). The lower this is, the more memory we'll use.
  3227. static const double MIN_DENSITY = 0.1;
  3228. bool is_pow2(uint64_t v) { return v == 0 || (v & (v - 1)) == 0; }
  3229. int log2ceil(uint64_t v) {
  3230. int ret = 0;
  3231. bool pow2 = is_pow2(v);
  3232. while (v >>= 1) ret++;
  3233. ret = pow2 ? ret : ret + 1; // Ceiling.
  3234. return UPB_MIN(UPB_MAXARRSIZE, ret);
  3235. }
  3236. char *upb_strdup(const char *s) {
  3237. return upb_strdup2(s, strlen(s));
  3238. }
  3239. char *upb_strdup2(const char *s, size_t len) {
  3240. // Always null-terminate, even if binary data; but don't rely on the input to
  3241. // have a null-terminating byte since it may be a raw binary buffer.
  3242. size_t n = len + 1;
  3243. char *p = malloc(n);
  3244. if (p) memcpy(p, s, len);
  3245. p[len] = 0;
  3246. return p;
  3247. }
  3248. // A type to represent the lookup key of either a strtable or an inttable.
  3249. typedef struct {
  3250. upb_tabkey key;
  3251. } lookupkey_t;
  3252. static lookupkey_t strkey2(const char *str, size_t len) {
  3253. lookupkey_t k;
  3254. k.key.s.str = (char*)str;
  3255. k.key.s.length = len;
  3256. return k;
  3257. }
  3258. static lookupkey_t intkey(uintptr_t key) {
  3259. lookupkey_t k;
  3260. k.key = upb_intkey(key);
  3261. return k;
  3262. }
  3263. typedef uint32_t hashfunc_t(upb_tabkey key);
  3264. typedef bool eqlfunc_t(upb_tabkey k1, lookupkey_t k2);
  3265. /* Base table (shared code) ***************************************************/
  3266. // For when we need to cast away const.
  3267. static upb_tabent *mutable_entries(upb_table *t) {
  3268. return (upb_tabent*)t->entries;
  3269. }
  3270. static bool isfull(upb_table *t) {
  3271. return (double)(t->count + 1) / upb_table_size(t) > MAX_LOAD;
  3272. }
  3273. static bool init(upb_table *t, upb_ctype_t ctype, uint8_t size_lg2) {
  3274. t->count = 0;
  3275. t->ctype = ctype;
  3276. t->size_lg2 = size_lg2;
  3277. t->mask = upb_table_size(t) ? upb_table_size(t) - 1 : 0;
  3278. size_t bytes = upb_table_size(t) * sizeof(upb_tabent);
  3279. if (bytes > 0) {
  3280. t->entries = malloc(bytes);
  3281. if (!t->entries) return false;
  3282. memset(mutable_entries(t), 0, bytes);
  3283. } else {
  3284. t->entries = NULL;
  3285. }
  3286. return true;
  3287. }
  3288. static void uninit(upb_table *t) { free(mutable_entries(t)); }
  3289. static upb_tabent *emptyent(upb_table *t) {
  3290. upb_tabent *e = mutable_entries(t) + upb_table_size(t);
  3291. while (1) { if (upb_tabent_isempty(--e)) return e; assert(e > t->entries); }
  3292. }
  3293. static upb_tabent *getentry_mutable(upb_table *t, uint32_t hash) {
  3294. return (upb_tabent*)upb_getentry(t, hash);
  3295. }
  3296. static const upb_tabent *findentry(const upb_table *t, lookupkey_t key,
  3297. uint32_t hash, eqlfunc_t *eql) {
  3298. if (t->size_lg2 == 0) return NULL;
  3299. const upb_tabent *e = upb_getentry(t, hash);
  3300. if (upb_tabent_isempty(e)) return NULL;
  3301. while (1) {
  3302. if (eql(e->key, key)) return e;
  3303. if ((e = e->next) == NULL) return NULL;
  3304. }
  3305. }
  3306. static upb_tabent *findentry_mutable(upb_table *t, lookupkey_t key,
  3307. uint32_t hash, eqlfunc_t *eql) {
  3308. return (upb_tabent*)findentry(t, key, hash, eql);
  3309. }
  3310. static bool lookup(const upb_table *t, lookupkey_t key, upb_value *v,
  3311. uint32_t hash, eqlfunc_t *eql) {
  3312. const upb_tabent *e = findentry(t, key, hash, eql);
  3313. if (e) {
  3314. if (v) {
  3315. _upb_value_setval(v, e->val, t->ctype);
  3316. }
  3317. return true;
  3318. } else {
  3319. return false;
  3320. }
  3321. }
  3322. // The given key must not already exist in the table.
  3323. static void insert(upb_table *t, lookupkey_t key, upb_value val,
  3324. uint32_t hash, hashfunc_t *hashfunc, eqlfunc_t *eql) {
  3325. UPB_UNUSED(eql);
  3326. assert(findentry(t, key, hash, eql) == NULL);
  3327. assert(val.ctype == t->ctype);
  3328. t->count++;
  3329. upb_tabent *mainpos_e = getentry_mutable(t, hash);
  3330. upb_tabent *our_e = mainpos_e;
  3331. if (upb_tabent_isempty(mainpos_e)) {
  3332. // Our main position is empty; use it.
  3333. our_e->next = NULL;
  3334. } else {
  3335. // Collision.
  3336. upb_tabent *new_e = emptyent(t);
  3337. // Head of collider's chain.
  3338. upb_tabent *chain = getentry_mutable(t, hashfunc(mainpos_e->key));
  3339. if (chain == mainpos_e) {
  3340. // Existing ent is in its main posisiton (it has the same hash as us, and
  3341. // is the head of our chain). Insert to new ent and append to this chain.
  3342. new_e->next = mainpos_e->next;
  3343. mainpos_e->next = new_e;
  3344. our_e = new_e;
  3345. } else {
  3346. // Existing ent is not in its main position (it is a node in some other
  3347. // chain). This implies that no existing ent in the table has our hash.
  3348. // Evict it (updating its chain) and use its ent for head of our chain.
  3349. *new_e = *mainpos_e; // copies next.
  3350. while (chain->next != mainpos_e) {
  3351. chain = (upb_tabent*)chain->next;
  3352. assert(chain);
  3353. }
  3354. chain->next = new_e;
  3355. our_e = mainpos_e;
  3356. our_e->next = NULL;
  3357. }
  3358. }
  3359. our_e->key = key.key;
  3360. our_e->val = val.val;
  3361. assert(findentry(t, key, hash, eql) == our_e);
  3362. }
  3363. static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
  3364. upb_tabkey *removed, uint32_t hash, eqlfunc_t *eql) {
  3365. upb_tabent *chain = getentry_mutable(t, hash);
  3366. if (upb_tabent_isempty(chain)) return false;
  3367. if (eql(chain->key, key)) {
  3368. // Element to remove is at the head of its chain.
  3369. t->count--;
  3370. if (val) {
  3371. _upb_value_setval(val, chain->val, t->ctype);
  3372. }
  3373. if (chain->next) {
  3374. upb_tabent *move = (upb_tabent*)chain->next;
  3375. *chain = *move;
  3376. if (removed) *removed = move->key;
  3377. move->key.num = 0; // Make the slot empty.
  3378. } else {
  3379. if (removed) *removed = chain->key;
  3380. chain->key.num = 0; // Make the slot empty.
  3381. }
  3382. return true;
  3383. } else {
  3384. // Element to remove is either in a non-head position or not in the table.
  3385. while (chain->next && !eql(chain->next->key, key))
  3386. chain = (upb_tabent*)chain->next;
  3387. if (chain->next) {
  3388. // Found element to remove.
  3389. if (val) {
  3390. _upb_value_setval(val, chain->next->val, t->ctype);
  3391. }
  3392. upb_tabent *rm = (upb_tabent*)chain->next;
  3393. if (removed) *removed = rm->key;
  3394. rm->key.num = 0;
  3395. chain->next = rm->next;
  3396. t->count--;
  3397. return true;
  3398. } else {
  3399. return false;
  3400. }
  3401. }
  3402. }
  3403. static size_t next(const upb_table *t, size_t i) {
  3404. do {
  3405. if (++i >= upb_table_size(t))
  3406. return SIZE_MAX;
  3407. } while(upb_tabent_isempty(&t->entries[i]));
  3408. return i;
  3409. }
  3410. static size_t begin(const upb_table *t) {
  3411. return next(t, -1);
  3412. }
  3413. /* upb_strtable ***************************************************************/
  3414. // A simple "subclass" of upb_table that only adds a hash function for strings.
  3415. static uint32_t strhash(upb_tabkey key) {
  3416. return MurmurHash2(key.s.str, key.s.length, 0);
  3417. }
  3418. static bool streql(upb_tabkey k1, lookupkey_t k2) {
  3419. return k1.s.length == k2.key.s.length &&
  3420. memcmp(k1.s.str, k2.key.s.str, k1.s.length) == 0;
  3421. }
  3422. bool upb_strtable_init(upb_strtable *t, upb_ctype_t ctype) {
  3423. return init(&t->t, ctype, 2);
  3424. }
  3425. void upb_strtable_uninit(upb_strtable *t) {
  3426. for (size_t i = 0; i < upb_table_size(&t->t); i++)
  3427. free((void*)t->t.entries[i].key.s.str);
  3428. uninit(&t->t);
  3429. }
  3430. bool upb_strtable_resize(upb_strtable *t, size_t size_lg2) {
  3431. upb_strtable new_table;
  3432. if (!init(&new_table.t, t->t.ctype, size_lg2))
  3433. return false;
  3434. upb_strtable_iter i;
  3435. upb_strtable_begin(&i, t);
  3436. for ( ; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  3437. upb_strtable_insert2(
  3438. &new_table,
  3439. upb_strtable_iter_key(&i),
  3440. upb_strtable_iter_keylength(&i),
  3441. upb_strtable_iter_value(&i));
  3442. }
  3443. upb_strtable_uninit(t);
  3444. *t = new_table;
  3445. return true;
  3446. }
  3447. bool upb_strtable_insert2(upb_strtable *t, const char *k, size_t len,
  3448. upb_value v) {
  3449. if (isfull(&t->t)) {
  3450. // Need to resize. New table of double the size, add old elements to it.
  3451. if (!upb_strtable_resize(t, t->t.size_lg2 + 1)) {
  3452. return false;
  3453. }
  3454. }
  3455. if ((k = upb_strdup2(k, len)) == NULL) return false;
  3456. lookupkey_t key = strkey2(k, len);
  3457. uint32_t hash = MurmurHash2(key.key.s.str, key.key.s.length, 0);
  3458. insert(&t->t, key, v, hash, &strhash, &streql);
  3459. return true;
  3460. }
  3461. bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
  3462. upb_value *v) {
  3463. uint32_t hash = MurmurHash2(key, len, 0);
  3464. return lookup(&t->t, strkey2(key, len), v, hash, &streql);
  3465. }
  3466. bool upb_strtable_remove2(upb_strtable *t, const char *key, size_t len,
  3467. upb_value *val) {
  3468. uint32_t hash = MurmurHash2(key, strlen(key), 0);
  3469. upb_tabkey tabkey;
  3470. if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
  3471. free((void*)tabkey.s.str);
  3472. return true;
  3473. } else {
  3474. return false;
  3475. }
  3476. }
  3477. // Iteration
  3478. static const upb_tabent *str_tabent(const upb_strtable_iter *i) {
  3479. return &i->t->t.entries[i->index];
  3480. }
  3481. void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t) {
  3482. i->t = t;
  3483. i->index = begin(&t->t);
  3484. }
  3485. void upb_strtable_next(upb_strtable_iter *i) {
  3486. i->index = next(&i->t->t, i->index);
  3487. }
  3488. bool upb_strtable_done(const upb_strtable_iter *i) {
  3489. return i->index >= upb_table_size(&i->t->t) ||
  3490. upb_tabent_isempty(str_tabent(i));
  3491. }
  3492. const char *upb_strtable_iter_key(upb_strtable_iter *i) {
  3493. assert(!upb_strtable_done(i));
  3494. return str_tabent(i)->key.s.str;
  3495. }
  3496. size_t upb_strtable_iter_keylength(upb_strtable_iter *i) {
  3497. assert(!upb_strtable_done(i));
  3498. return str_tabent(i)->key.s.length;
  3499. }
  3500. upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
  3501. assert(!upb_strtable_done(i));
  3502. return _upb_value_val(str_tabent(i)->val, i->t->t.ctype);
  3503. }
  3504. void upb_strtable_iter_setdone(upb_strtable_iter *i) {
  3505. i->index = SIZE_MAX;
  3506. }
  3507. bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
  3508. const upb_strtable_iter *i2) {
  3509. if (upb_strtable_done(i1) && upb_strtable_done(i2))
  3510. return true;
  3511. return i1->t == i2->t && i1->index == i2->index;
  3512. }
  3513. /* upb_inttable ***************************************************************/
  3514. // For inttables we use a hybrid structure where small keys are kept in an
  3515. // array and large keys are put in the hash table.
  3516. static uint32_t inthash(upb_tabkey key) { return upb_inthash(key.num); }
  3517. static bool inteql(upb_tabkey k1, lookupkey_t k2) {
  3518. return k1.num == k2.key.num;
  3519. }
  3520. static _upb_value *mutable_array(upb_inttable *t) {
  3521. return (_upb_value*)t->array;
  3522. }
  3523. static _upb_value *inttable_val(upb_inttable *t, uintptr_t key) {
  3524. if (key < t->array_size) {
  3525. return upb_arrhas(t->array[key]) ? &(mutable_array(t)[key]) : NULL;
  3526. } else {
  3527. upb_tabent *e =
  3528. findentry_mutable(&t->t, intkey(key), upb_inthash(key), &inteql);
  3529. return e ? &e->val : NULL;
  3530. }
  3531. }
  3532. static const _upb_value *inttable_val_const(const upb_inttable *t,
  3533. uintptr_t key) {
  3534. return inttable_val((upb_inttable*)t, key);
  3535. }
  3536. size_t upb_inttable_count(const upb_inttable *t) {
  3537. return t->t.count + t->array_count;
  3538. }
  3539. static void check(upb_inttable *t) {
  3540. UPB_UNUSED(t);
  3541. #if defined(UPB_DEBUG_TABLE) && !defined(NDEBUG)
  3542. // This check is very expensive (makes inserts/deletes O(N)).
  3543. size_t count = 0;
  3544. upb_inttable_iter i;
  3545. upb_inttable_begin(&i, t);
  3546. for(; !upb_inttable_done(&i); upb_inttable_next(&i), count++) {
  3547. assert(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
  3548. }
  3549. assert(count == upb_inttable_count(t));
  3550. #endif
  3551. }
  3552. bool upb_inttable_sizedinit(upb_inttable *t, upb_ctype_t ctype,
  3553. size_t asize, int hsize_lg2) {
  3554. if (!init(&t->t, ctype, hsize_lg2)) return false;
  3555. // Always make the array part at least 1 long, so that we know key 0
  3556. // won't be in the hash part, which simplifies things.
  3557. t->array_size = UPB_MAX(1, asize);
  3558. t->array_count = 0;
  3559. size_t array_bytes = t->array_size * sizeof(upb_value);
  3560. t->array = malloc(array_bytes);
  3561. if (!t->array) {
  3562. uninit(&t->t);
  3563. return false;
  3564. }
  3565. memset(mutable_array(t), 0xff, array_bytes);
  3566. check(t);
  3567. return true;
  3568. }
  3569. bool upb_inttable_init(upb_inttable *t, upb_ctype_t ctype) {
  3570. return upb_inttable_sizedinit(t, ctype, 0, 4);
  3571. }
  3572. void upb_inttable_uninit(upb_inttable *t) {
  3573. uninit(&t->t);
  3574. free(mutable_array(t));
  3575. }
  3576. bool upb_inttable_insert(upb_inttable *t, uintptr_t key, upb_value val) {
  3577. assert(upb_arrhas(val.val));
  3578. if (key < t->array_size) {
  3579. assert(!upb_arrhas(t->array[key]));
  3580. t->array_count++;
  3581. mutable_array(t)[key] = val.val;
  3582. } else {
  3583. if (isfull(&t->t)) {
  3584. // Need to resize the hash part, but we re-use the array part.
  3585. upb_table new_table;
  3586. if (!init(&new_table, t->t.ctype, t->t.size_lg2 + 1))
  3587. return false;
  3588. size_t i;
  3589. for (i = begin(&t->t); i < upb_table_size(&t->t); i = next(&t->t, i)) {
  3590. const upb_tabent *e = &t->t.entries[i];
  3591. upb_value v;
  3592. _upb_value_setval(&v, e->val, t->t.ctype);
  3593. uint32_t hash = upb_inthash(e->key.num);
  3594. insert(&new_table, intkey(e->key.num), v, hash, &inthash, &inteql);
  3595. }
  3596. assert(t->t.count == new_table.count);
  3597. uninit(&t->t);
  3598. t->t = new_table;
  3599. }
  3600. insert(&t->t, intkey(key), val, upb_inthash(key), &inthash, &inteql);
  3601. }
  3602. check(t);
  3603. return true;
  3604. }
  3605. bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v) {
  3606. const _upb_value *table_v = inttable_val_const(t, key);
  3607. if (!table_v) return false;
  3608. if (v) _upb_value_setval(v, *table_v, t->t.ctype);
  3609. return true;
  3610. }
  3611. bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val) {
  3612. _upb_value *table_v = inttable_val(t, key);
  3613. if (!table_v) return false;
  3614. *table_v = val.val;
  3615. return true;
  3616. }
  3617. bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val) {
  3618. bool success;
  3619. if (key < t->array_size) {
  3620. if (upb_arrhas(t->array[key])) {
  3621. t->array_count--;
  3622. if (val) {
  3623. _upb_value_setval(val, t->array[key], t->t.ctype);
  3624. }
  3625. _upb_value empty = UPB_ARRAY_EMPTYENT;
  3626. mutable_array(t)[key] = empty;
  3627. success = true;
  3628. } else {
  3629. success = false;
  3630. }
  3631. } else {
  3632. upb_tabkey removed;
  3633. uint32_t hash = upb_inthash(key);
  3634. success = rm(&t->t, intkey(key), val, &removed, hash, &inteql);
  3635. }
  3636. check(t);
  3637. return success;
  3638. }
  3639. bool upb_inttable_push(upb_inttable *t, upb_value val) {
  3640. return upb_inttable_insert(t, upb_inttable_count(t), val);
  3641. }
  3642. upb_value upb_inttable_pop(upb_inttable *t) {
  3643. upb_value val;
  3644. bool ok = upb_inttable_remove(t, upb_inttable_count(t) - 1, &val);
  3645. UPB_ASSERT_VAR(ok, ok);
  3646. return val;
  3647. }
  3648. bool upb_inttable_insertptr(upb_inttable *t, const void *key, upb_value val) {
  3649. return upb_inttable_insert(t, (uintptr_t)key, val);
  3650. }
  3651. bool upb_inttable_lookupptr(const upb_inttable *t, const void *key,
  3652. upb_value *v) {
  3653. return upb_inttable_lookup(t, (uintptr_t)key, v);
  3654. }
  3655. bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val) {
  3656. return upb_inttable_remove(t, (uintptr_t)key, val);
  3657. }
  3658. void upb_inttable_compact(upb_inttable *t) {
  3659. // Create a power-of-two histogram of the table keys.
  3660. int counts[UPB_MAXARRSIZE + 1] = {0};
  3661. uintptr_t max_key = 0;
  3662. upb_inttable_iter i;
  3663. upb_inttable_begin(&i, t);
  3664. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  3665. uintptr_t key = upb_inttable_iter_key(&i);
  3666. if (key > max_key) {
  3667. max_key = key;
  3668. }
  3669. counts[log2ceil(key)]++;
  3670. }
  3671. int arr_size;
  3672. int arr_count = upb_inttable_count(t);
  3673. if (upb_inttable_count(t) >= max_key * MIN_DENSITY) {
  3674. // We can put 100% of the entries in the array part.
  3675. arr_size = max_key + 1;
  3676. } else {
  3677. // Find the largest power of two that satisfies the MIN_DENSITY definition.
  3678. for (int size_lg2 = ARRAY_SIZE(counts) - 1; size_lg2 > 1; size_lg2--) {
  3679. arr_size = 1 << size_lg2;
  3680. arr_count -= counts[size_lg2];
  3681. if (arr_count >= arr_size * MIN_DENSITY) {
  3682. break;
  3683. }
  3684. }
  3685. }
  3686. // Array part must always be at least 1 entry large to catch lookups of key
  3687. // 0. Key 0 must always be in the array part because "0" in the hash part
  3688. // denotes an empty entry.
  3689. arr_size = UPB_MAX(arr_size, 1);
  3690. // Insert all elements into new, perfectly-sized table.
  3691. int hash_count = upb_inttable_count(t) - arr_count;
  3692. int hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
  3693. int hashsize_lg2 = log2ceil(hash_size);
  3694. assert(hash_count >= 0);
  3695. upb_inttable new_t;
  3696. upb_inttable_sizedinit(&new_t, t->t.ctype, arr_size, hashsize_lg2);
  3697. upb_inttable_begin(&i, t);
  3698. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  3699. uintptr_t k = upb_inttable_iter_key(&i);
  3700. upb_inttable_insert(&new_t, k, upb_inttable_iter_value(&i));
  3701. }
  3702. assert(new_t.array_size == arr_size);
  3703. assert(new_t.t.size_lg2 == hashsize_lg2);
  3704. upb_inttable_uninit(t);
  3705. *t = new_t;
  3706. }
  3707. // Iteration.
  3708. static const upb_tabent *int_tabent(const upb_inttable_iter *i) {
  3709. assert(!i->array_part);
  3710. return &i->t->t.entries[i->index];
  3711. }
  3712. static _upb_value int_arrent(const upb_inttable_iter *i) {
  3713. assert(i->array_part);
  3714. return i->t->array[i->index];
  3715. }
  3716. void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t) {
  3717. i->t = t;
  3718. i->index = -1;
  3719. i->array_part = true;
  3720. upb_inttable_next(i);
  3721. }
  3722. void upb_inttable_next(upb_inttable_iter *iter) {
  3723. const upb_inttable *t = iter->t;
  3724. if (iter->array_part) {
  3725. while (++iter->index < t->array_size) {
  3726. if (upb_arrhas(int_arrent(iter))) {
  3727. return;
  3728. }
  3729. }
  3730. iter->array_part = false;
  3731. iter->index = begin(&t->t);
  3732. } else {
  3733. iter->index = next(&t->t, iter->index);
  3734. }
  3735. }
  3736. bool upb_inttable_done(const upb_inttable_iter *i) {
  3737. if (i->array_part) {
  3738. return i->index >= i->t->array_size ||
  3739. !upb_arrhas(int_arrent(i));
  3740. } else {
  3741. return i->index >= upb_table_size(&i->t->t) ||
  3742. upb_tabent_isempty(int_tabent(i));
  3743. }
  3744. }
  3745. uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i) {
  3746. assert(!upb_inttable_done(i));
  3747. return i->array_part ? i->index : int_tabent(i)->key.num;
  3748. }
  3749. upb_value upb_inttable_iter_value(const upb_inttable_iter *i) {
  3750. assert(!upb_inttable_done(i));
  3751. return _upb_value_val(
  3752. i->array_part ? i->t->array[i->index] : int_tabent(i)->val,
  3753. i->t->t.ctype);
  3754. }
  3755. void upb_inttable_iter_setdone(upb_inttable_iter *i) {
  3756. i->index = SIZE_MAX;
  3757. i->array_part = false;
  3758. }
  3759. bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
  3760. const upb_inttable_iter *i2) {
  3761. if (upb_inttable_done(i1) && upb_inttable_done(i2))
  3762. return true;
  3763. return i1->t == i2->t && i1->index == i2->index &&
  3764. i1->array_part == i2->array_part;
  3765. }
  3766. #ifdef UPB_UNALIGNED_READS_OK
  3767. //-----------------------------------------------------------------------------
  3768. // MurmurHash2, by Austin Appleby (released as public domain).
  3769. // Reformatted and C99-ified by Joshua Haberman.
  3770. // Note - This code makes a few assumptions about how your machine behaves -
  3771. // 1. We can read a 4-byte value from any address without crashing
  3772. // 2. sizeof(int) == 4 (in upb this limitation is removed by using uint32_t
  3773. // And it has a few limitations -
  3774. // 1. It will not work incrementally.
  3775. // 2. It will not produce the same results on little-endian and big-endian
  3776. // machines.
  3777. uint32_t MurmurHash2(const void *key, size_t len, uint32_t seed) {
  3778. // 'm' and 'r' are mixing constants generated offline.
  3779. // They're not really 'magic', they just happen to work well.
  3780. const uint32_t m = 0x5bd1e995;
  3781. const int32_t r = 24;
  3782. // Initialize the hash to a 'random' value
  3783. uint32_t h = seed ^ len;
  3784. // Mix 4 bytes at a time into the hash
  3785. const uint8_t * data = (const uint8_t *)key;
  3786. while(len >= 4) {
  3787. uint32_t k = *(uint32_t *)data;
  3788. k *= m;
  3789. k ^= k >> r;
  3790. k *= m;
  3791. h *= m;
  3792. h ^= k;
  3793. data += 4;
  3794. len -= 4;
  3795. }
  3796. // Handle the last few bytes of the input array
  3797. switch(len) {
  3798. case 3: h ^= data[2] << 16;
  3799. case 2: h ^= data[1] << 8;
  3800. case 1: h ^= data[0]; h *= m;
  3801. };
  3802. // Do a few final mixes of the hash to ensure the last few
  3803. // bytes are well-incorporated.
  3804. h ^= h >> 13;
  3805. h *= m;
  3806. h ^= h >> 15;
  3807. return h;
  3808. }
  3809. #else // !UPB_UNALIGNED_READS_OK
  3810. //-----------------------------------------------------------------------------
  3811. // MurmurHashAligned2, by Austin Appleby
  3812. // Same algorithm as MurmurHash2, but only does aligned reads - should be safer
  3813. // on certain platforms.
  3814. // Performance will be lower than MurmurHash2
  3815. #define MIX(h,k,m) { k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; }
  3816. uint32_t MurmurHash2(const void * key, size_t len, uint32_t seed) {
  3817. const uint32_t m = 0x5bd1e995;
  3818. const int32_t r = 24;
  3819. const uint8_t * data = (const uint8_t *)key;
  3820. uint32_t h = seed ^ len;
  3821. uint8_t align = (uintptr_t)data & 3;
  3822. if(align && (len >= 4)) {
  3823. // Pre-load the temp registers
  3824. uint32_t t = 0, d = 0;
  3825. switch(align) {
  3826. case 1: t |= data[2] << 16;
  3827. case 2: t |= data[1] << 8;
  3828. case 3: t |= data[0];
  3829. }
  3830. t <<= (8 * align);
  3831. data += 4-align;
  3832. len -= 4-align;
  3833. int32_t sl = 8 * (4-align);
  3834. int32_t sr = 8 * align;
  3835. // Mix
  3836. while(len >= 4) {
  3837. d = *(uint32_t *)data;
  3838. t = (t >> sr) | (d << sl);
  3839. uint32_t k = t;
  3840. MIX(h,k,m);
  3841. t = d;
  3842. data += 4;
  3843. len -= 4;
  3844. }
  3845. // Handle leftover data in temp registers
  3846. d = 0;
  3847. if(len >= align) {
  3848. switch(align) {
  3849. case 3: d |= data[2] << 16;
  3850. case 2: d |= data[1] << 8;
  3851. case 1: d |= data[0];
  3852. }
  3853. uint32_t k = (t >> sr) | (d << sl);
  3854. MIX(h,k,m);
  3855. data += align;
  3856. len -= align;
  3857. //----------
  3858. // Handle tail bytes
  3859. switch(len) {
  3860. case 3: h ^= data[2] << 16;
  3861. case 2: h ^= data[1] << 8;
  3862. case 1: h ^= data[0]; h *= m;
  3863. };
  3864. } else {
  3865. switch(len) {
  3866. case 3: d |= data[2] << 16;
  3867. case 2: d |= data[1] << 8;
  3868. case 1: d |= data[0];
  3869. case 0: h ^= (t >> sr) | (d << sl); h *= m;
  3870. }
  3871. }
  3872. h ^= h >> 13;
  3873. h *= m;
  3874. h ^= h >> 15;
  3875. return h;
  3876. } else {
  3877. while(len >= 4) {
  3878. uint32_t k = *(uint32_t *)data;
  3879. MIX(h,k,m);
  3880. data += 4;
  3881. len -= 4;
  3882. }
  3883. //----------
  3884. // Handle tail bytes
  3885. switch(len) {
  3886. case 3: h ^= data[2] << 16;
  3887. case 2: h ^= data[1] << 8;
  3888. case 1: h ^= data[0]; h *= m;
  3889. };
  3890. h ^= h >> 13;
  3891. h *= m;
  3892. h ^= h >> 15;
  3893. return h;
  3894. }
  3895. }
  3896. #undef MIX
  3897. #endif // UPB_UNALIGNED_READS_OK
  3898. /*
  3899. * upb - a minimalist implementation of protocol buffers.
  3900. *
  3901. * Copyright (c) 2009-2012 Google Inc. See LICENSE for details.
  3902. * Author: Josh Haberman <jhaberman@gmail.com>
  3903. */
  3904. #include <errno.h>
  3905. #include <stdarg.h>
  3906. #include <stddef.h>
  3907. #include <stdint.h>
  3908. #include <stdio.h>
  3909. #include <stdlib.h>
  3910. #include <string.h>
  3911. bool upb_dumptostderr(void *closure, const upb_status* status) {
  3912. UPB_UNUSED(closure);
  3913. fprintf(stderr, "%s\n", upb_status_errmsg(status));
  3914. return false;
  3915. }
  3916. // Guarantee null-termination and provide ellipsis truncation.
  3917. // It may be tempting to "optimize" this by initializing these final
  3918. // four bytes up-front and then being careful never to overwrite them,
  3919. // this is safer and simpler.
  3920. static void nullz(upb_status *status) {
  3921. const char *ellipsis = "...";
  3922. size_t len = strlen(ellipsis);
  3923. assert(sizeof(status->msg) > len);
  3924. memcpy(status->msg + sizeof(status->msg) - len, ellipsis, len);
  3925. }
  3926. void upb_status_clear(upb_status *status) {
  3927. if (!status) return;
  3928. status->ok_ = true;
  3929. status->code_ = 0;
  3930. status->msg[0] = '\0';
  3931. }
  3932. bool upb_ok(const upb_status *status) { return status->ok_; }
  3933. upb_errorspace *upb_status_errspace(const upb_status *status) {
  3934. return status->error_space_;
  3935. }
  3936. int upb_status_errcode(const upb_status *status) { return status->code_; }
  3937. const char *upb_status_errmsg(const upb_status *status) { return status->msg; }
  3938. void upb_status_seterrmsg(upb_status *status, const char *msg) {
  3939. if (!status) return;
  3940. status->ok_ = false;
  3941. strncpy(status->msg, msg, sizeof(status->msg));
  3942. nullz(status);
  3943. }
  3944. void upb_status_seterrf(upb_status *status, const char *fmt, ...) {
  3945. va_list args;
  3946. va_start(args, fmt);
  3947. upb_status_vseterrf(status, fmt, args);
  3948. va_end(args);
  3949. }
  3950. void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args) {
  3951. if (!status) return;
  3952. status->ok_ = false;
  3953. vsnprintf(status->msg, sizeof(status->msg), fmt, args);
  3954. nullz(status);
  3955. }
  3956. void upb_status_seterrcode(upb_status *status, upb_errorspace *space,
  3957. int code) {
  3958. if (!status) return;
  3959. status->ok_ = false;
  3960. status->error_space_ = space;
  3961. status->code_ = code;
  3962. space->set_message(status, code);
  3963. }
  3964. void upb_status_copy(upb_status *to, const upb_status *from) {
  3965. if (!to) return;
  3966. *to = *from;
  3967. }
  3968. // This file was generated by upbc (the upb compiler).
  3969. // Do not edit -- your changes will be discarded when the file is
  3970. // regenerated.
  3971. static const upb_msgdef msgs[20];
  3972. static const upb_fielddef fields[81];
  3973. static const upb_enumdef enums[4];
  3974. static const upb_tabent strentries[236];
  3975. static const upb_tabent intentries[14];
  3976. static const _upb_value arrays[232];
  3977. #ifdef UPB_DEBUG_REFS
  3978. static upb_inttable reftables[212];
  3979. #endif
  3980. static const upb_msgdef msgs[20] = {
  3981. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto", 27, 6, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[0], 8, 7), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[0]),&reftables[0], &reftables[1]),
  3982. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ExtensionRange", 4, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[8], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[16]),&reftables[2], &reftables[3]),
  3983. UPB_MSGDEF_INIT("google.protobuf.EnumDescriptorProto", 11, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[11], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[20]),&reftables[4], &reftables[5]),
  3984. UPB_MSGDEF_INIT("google.protobuf.EnumOptions", 7, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[0], &arrays[15], 8, 1), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[24]),&reftables[6], &reftables[7]),
  3985. UPB_MSGDEF_INIT("google.protobuf.EnumValueDescriptorProto", 8, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[23], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[28]),&reftables[8], &reftables[9]),
  3986. UPB_MSGDEF_INIT("google.protobuf.EnumValueOptions", 6, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[2], &arrays[27], 4, 0), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[32]),&reftables[10], &reftables[11]),
  3987. UPB_MSGDEF_INIT("google.protobuf.FieldDescriptorProto", 19, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[31], 9, 8), UPB_STRTABLE_INIT(8, 15, UPB_CTYPE_PTR, 4, &strentries[36]),&reftables[12], &reftables[13]),
  3988. UPB_MSGDEF_INIT("google.protobuf.FieldOptions", 14, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[4], &arrays[40], 32, 6), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[52]),&reftables[14], &reftables[15]),
  3989. UPB_MSGDEF_INIT("google.protobuf.FileDescriptorProto", 39, 6, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[72], 12, 11), UPB_STRTABLE_INIT(11, 15, UPB_CTYPE_PTR, 4, &strentries[68]),&reftables[16], &reftables[17]),
  3990. UPB_MSGDEF_INIT("google.protobuf.FileDescriptorSet", 6, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[84], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[84]),&reftables[18], &reftables[19]),
  3991. UPB_MSGDEF_INIT("google.protobuf.FileOptions", 21, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[6], &arrays[86], 64, 9), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[88]),&reftables[20], &reftables[21]),
  3992. UPB_MSGDEF_INIT("google.protobuf.MessageOptions", 8, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[8], &arrays[150], 16, 2), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[104]),&reftables[22], &reftables[23]),
  3993. UPB_MSGDEF_INIT("google.protobuf.MethodDescriptorProto", 13, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[166], 5, 4), UPB_STRTABLE_INIT(4, 7, UPB_CTYPE_PTR, 3, &strentries[108]),&reftables[24], &reftables[25]),
  3994. UPB_MSGDEF_INIT("google.protobuf.MethodOptions", 6, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[10], &arrays[171], 4, 0), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[116]),&reftables[26], &reftables[27]),
  3995. UPB_MSGDEF_INIT("google.protobuf.ServiceDescriptorProto", 11, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[175], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[120]),&reftables[28], &reftables[29]),
  3996. UPB_MSGDEF_INIT("google.protobuf.ServiceOptions", 6, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[12], &arrays[179], 4, 0), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[124]),&reftables[30], &reftables[31]),
  3997. UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo", 6, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[183], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[128]),&reftables[32], &reftables[33]),
  3998. UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo.Location", 14, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[185], 5, 4), UPB_STRTABLE_INIT(4, 7, UPB_CTYPE_PTR, 3, &strentries[132]),&reftables[34], &reftables[35]),
  3999. UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption", 18, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[190], 9, 7), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[140]),&reftables[36], &reftables[37]),
  4000. UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption.NamePart", 6, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[199], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[156]),&reftables[38], &reftables[39]),
  4001. };
  4002. static const upb_fielddef fields[81] = {
  4003. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "aggregate_value", 8, &msgs[18], NULL, 15, 6, {0},&reftables[40], &reftables[41]),
  4004. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "allow_alias", 2, &msgs[3], NULL, 6, 1, {0},&reftables[42], &reftables[43]),
  4005. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_generic_services", 16, &msgs[10], NULL, 17, 6, {0},&reftables[44], &reftables[45]),
  4006. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "ctype", 1, &msgs[7], UPB_UPCAST(&enums[2]), 6, 1, {0},&reftables[46], &reftables[47]),
  4007. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "default_value", 7, &msgs[6], NULL, 16, 7, {0},&reftables[48], &reftables[49]),
  4008. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "dependency", 3, &msgs[8], NULL, 30, 8, {0},&reftables[50], &reftables[51]),
  4009. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[7], NULL, 8, 3, {0},&reftables[52], &reftables[53]),
  4010. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_DOUBLE, 0, false, false, false, false, "double_value", 6, &msgs[18], NULL, 11, 4, {0},&reftables[54], &reftables[55]),
  4011. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "end", 2, &msgs[1], NULL, 3, 1, {0},&reftables[56], &reftables[57]),
  4012. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 4, &msgs[0], UPB_UPCAST(&msgs[2]), 16, 2, {0},&reftables[58], &reftables[59]),
  4013. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 5, &msgs[8], UPB_UPCAST(&msgs[2]), 13, 1, {0},&reftables[60], &reftables[61]),
  4014. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "experimental_map_key", 9, &msgs[7], NULL, 10, 5, {0},&reftables[62], &reftables[63]),
  4015. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "extendee", 2, &msgs[6], NULL, 7, 2, {0},&reftables[64], &reftables[65]),
  4016. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 7, &msgs[8], UPB_UPCAST(&msgs[6]), 19, 3, {0},&reftables[66], &reftables[67]),
  4017. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 6, &msgs[0], UPB_UPCAST(&msgs[6]), 22, 4, {0},&reftables[68], &reftables[69]),
  4018. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension_range", 5, &msgs[0], UPB_UPCAST(&msgs[1]), 19, 3, {0},&reftables[70], &reftables[71]),
  4019. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "field", 2, &msgs[0], UPB_UPCAST(&msgs[6]), 10, 0, {0},&reftables[72], &reftables[73]),
  4020. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "file", 1, &msgs[9], UPB_UPCAST(&msgs[8]), 5, 0, {0},&reftables[74], &reftables[75]),
  4021. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "go_package", 11, &msgs[10], NULL, 14, 5, {0},&reftables[76], &reftables[77]),
  4022. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "identifier_value", 3, &msgs[18], NULL, 6, 1, {0},&reftables[78], &reftables[79]),
  4023. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "input_type", 2, &msgs[12], NULL, 7, 2, {0},&reftables[80], &reftables[81]),
  4024. UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_BOOL, 0, false, false, false, false, "is_extension", 2, &msgs[19], NULL, 5, 1, {0},&reftables[82], &reftables[83]),
  4025. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generate_equals_and_hash", 20, &msgs[10], NULL, 20, 9, {0},&reftables[84], &reftables[85]),
  4026. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generic_services", 17, &msgs[10], NULL, 18, 7, {0},&reftables[86], &reftables[87]),
  4027. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_multiple_files", 10, &msgs[10], NULL, 13, 4, {0},&reftables[88], &reftables[89]),
  4028. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_outer_classname", 8, &msgs[10], NULL, 9, 2, {0},&reftables[90], &reftables[91]),
  4029. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_package", 1, &msgs[10], NULL, 6, 1, {0},&reftables[92], &reftables[93]),
  4030. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "label", 4, &msgs[6], UPB_UPCAST(&enums[0]), 11, 4, {0},&reftables[94], &reftables[95]),
  4031. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "lazy", 5, &msgs[7], NULL, 9, 4, {0},&reftables[96], &reftables[97]),
  4032. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "leading_comments", 3, &msgs[17], NULL, 8, 2, {0},&reftables[98], &reftables[99]),
  4033. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "location", 1, &msgs[16], UPB_UPCAST(&msgs[17]), 5, 0, {0},&reftables[100], &reftables[101]),
  4034. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "message_set_wire_format", 1, &msgs[11], NULL, 6, 1, {0},&reftables[102], &reftables[103]),
  4035. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "message_type", 4, &msgs[8], UPB_UPCAST(&msgs[0]), 10, 0, {0},&reftables[104], &reftables[105]),
  4036. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "method", 2, &msgs[14], UPB_UPCAST(&msgs[12]), 6, 0, {0},&reftables[106], &reftables[107]),
  4037. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[8], NULL, 22, 6, {0},&reftables[108], &reftables[109]),
  4038. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[14], NULL, 8, 2, {0},&reftables[110], &reftables[111]),
  4039. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "name", 2, &msgs[18], UPB_UPCAST(&msgs[19]), 5, 0, {0},&reftables[112], &reftables[113]),
  4040. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[4], NULL, 4, 1, {0},&reftables[114], &reftables[115]),
  4041. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[0], NULL, 24, 6, {0},&reftables[116], &reftables[117]),
  4042. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[12], NULL, 4, 1, {0},&reftables[118], &reftables[119]),
  4043. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[2], NULL, 8, 2, {0},&reftables[120], &reftables[121]),
  4044. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[6], NULL, 4, 1, {0},&reftables[122], &reftables[123]),
  4045. UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_STRING, 0, false, false, false, false, "name_part", 1, &msgs[19], NULL, 2, 0, {0},&reftables[124], &reftables[125]),
  4046. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT64, UPB_INTFMT_VARIABLE, false, false, false, false, "negative_int_value", 5, &msgs[18], NULL, 10, 3, {0},&reftables[126], &reftables[127]),
  4047. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "nested_type", 3, &msgs[0], UPB_UPCAST(&msgs[0]), 13, 1, {0},&reftables[128], &reftables[129]),
  4048. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "no_standard_descriptor_accessor", 2, &msgs[11], NULL, 7, 2, {0},&reftables[130], &reftables[131]),
  4049. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 3, &msgs[6], NULL, 10, 3, {0},&reftables[132], &reftables[133]),
  4050. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 2, &msgs[4], NULL, 7, 2, {0},&reftables[134], &reftables[135]),
  4051. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "optimize_for", 9, &msgs[10], UPB_UPCAST(&enums[3]), 12, 3, {0},&reftables[136], &reftables[137]),
  4052. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 7, &msgs[0], UPB_UPCAST(&msgs[11]), 23, 5, {0},&reftables[138], &reftables[139]),
  4053. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[2], UPB_UPCAST(&msgs[3]), 7, 1, {0},&reftables[140], &reftables[141]),
  4054. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[6], UPB_UPCAST(&msgs[7]), 3, 0, {0},&reftables[142], &reftables[143]),
  4055. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[4], UPB_UPCAST(&msgs[5]), 3, 0, {0},&reftables[144], &reftables[145]),
  4056. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[8], UPB_UPCAST(&msgs[10]), 20, 4, {0},&reftables[146], &reftables[147]),
  4057. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[14], UPB_UPCAST(&msgs[15]), 7, 1, {0},&reftables[148], &reftables[149]),
  4058. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 4, &msgs[12], UPB_UPCAST(&msgs[13]), 3, 0, {0},&reftables[150], &reftables[151]),
  4059. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "output_type", 3, &msgs[12], NULL, 10, 3, {0},&reftables[152], &reftables[153]),
  4060. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "package", 2, &msgs[8], NULL, 25, 7, {0},&reftables[154], &reftables[155]),
  4061. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "packed", 2, &msgs[7], NULL, 7, 2, {0},&reftables[156], &reftables[157]),
  4062. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "path", 1, &msgs[17], NULL, 4, 0, {0},&reftables[158], &reftables[159]),
  4063. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_UINT64, UPB_INTFMT_VARIABLE, false, false, false, false, "positive_int_value", 4, &msgs[18], NULL, 9, 2, {0},&reftables[160], &reftables[161]),
  4064. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "public_dependency", 10, &msgs[8], NULL, 35, 9, {0},&reftables[162], &reftables[163]),
  4065. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "py_generic_services", 18, &msgs[10], NULL, 19, 8, {0},&reftables[164], &reftables[165]),
  4066. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "service", 6, &msgs[8], UPB_UPCAST(&msgs[14]), 16, 2, {0},&reftables[166], &reftables[167]),
  4067. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "source_code_info", 9, &msgs[8], UPB_UPCAST(&msgs[16]), 21, 5, {0},&reftables[168], &reftables[169]),
  4068. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "span", 2, &msgs[17], NULL, 7, 1, {0},&reftables[170], &reftables[171]),
  4069. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "start", 1, &msgs[1], NULL, 2, 0, {0},&reftables[172], &reftables[173]),
  4070. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BYTES, 0, false, false, false, false, "string_value", 7, &msgs[18], NULL, 12, 5, {0},&reftables[174], &reftables[175]),
  4071. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "trailing_comments", 4, &msgs[17], NULL, 11, 3, {0},&reftables[176], &reftables[177]),
  4072. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "type", 5, &msgs[6], UPB_UPCAST(&enums[1]), 12, 5, {0},&reftables[178], &reftables[179]),
  4073. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "type_name", 6, &msgs[6], NULL, 13, 6, {0},&reftables[180], &reftables[181]),
  4074. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[5], UPB_UPCAST(&msgs[18]), 5, 0, {0},&reftables[182], &reftables[183]),
  4075. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[15], UPB_UPCAST(&msgs[18]), 5, 0, {0},&reftables[184], &reftables[185]),
  4076. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[3], UPB_UPCAST(&msgs[18]), 5, 0, {0},&reftables[186], &reftables[187]),
  4077. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[13], UPB_UPCAST(&msgs[18]), 5, 0, {0},&reftables[188], &reftables[189]),
  4078. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[10], UPB_UPCAST(&msgs[18]), 5, 0, {0},&reftables[190], &reftables[191]),
  4079. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[11], UPB_UPCAST(&msgs[18]), 5, 0, {0},&reftables[192], &reftables[193]),
  4080. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[7], UPB_UPCAST(&msgs[18]), 5, 0, {0},&reftables[194], &reftables[195]),
  4081. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "value", 2, &msgs[2], UPB_UPCAST(&msgs[4]), 6, 0, {0},&reftables[196], &reftables[197]),
  4082. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "weak", 10, &msgs[7], NULL, 13, 6, {0},&reftables[198], &reftables[199]),
  4083. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "weak_dependency", 11, &msgs[8], NULL, 38, 10, {0},&reftables[200], &reftables[201]),
  4084. };
  4085. static const upb_enumdef enums[4] = {
  4086. UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Label", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[160]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[202], 4, 3), 0, &reftables[202], &reftables[203]),
  4087. UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Type", UPB_STRTABLE_INIT(18, 31, UPB_CTYPE_INT32, 5, &strentries[164]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[206], 19, 18), 0, &reftables[204], &reftables[205]),
  4088. UPB_ENUMDEF_INIT("google.protobuf.FieldOptions.CType", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[196]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[225], 3, 3), 0, &reftables[206], &reftables[207]),
  4089. UPB_ENUMDEF_INIT("google.protobuf.FileOptions.OptimizeMode", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[200]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[228], 4, 3), 0, &reftables[208], &reftables[209]),
  4090. };
  4091. static const upb_tabent strentries[236] = {
  4092. {UPB_TABKEY_STR("extension"), UPB_VALUE_INIT_CONSTPTR(&fields[14]), NULL},
  4093. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4094. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4095. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[38]), NULL},
  4096. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4097. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4098. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4099. {UPB_TABKEY_STR("field"), UPB_VALUE_INIT_CONSTPTR(&fields[16]), NULL},
  4100. {UPB_TABKEY_STR("extension_range"), UPB_VALUE_INIT_CONSTPTR(&fields[15]), NULL},
  4101. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4102. {UPB_TABKEY_STR("nested_type"), UPB_VALUE_INIT_CONSTPTR(&fields[44]), NULL},
  4103. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4104. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4105. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4106. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[49]), NULL},
  4107. {UPB_TABKEY_STR("enum_type"), UPB_VALUE_INIT_CONSTPTR(&fields[9]), &strentries[14]},
  4108. {UPB_TABKEY_STR("start"), UPB_VALUE_INIT_CONSTPTR(&fields[66]), NULL},
  4109. {UPB_TABKEY_STR("end"), UPB_VALUE_INIT_CONSTPTR(&fields[8]), NULL},
  4110. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4111. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4112. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4113. {UPB_TABKEY_STR("value"), UPB_VALUE_INIT_CONSTPTR(&fields[78]), NULL},
  4114. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[50]), NULL},
  4115. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[40]), &strentries[22]},
  4116. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[73]), NULL},
  4117. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4118. {UPB_TABKEY_STR("allow_alias"), UPB_VALUE_INIT_CONSTPTR(&fields[1]), NULL},
  4119. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4120. {UPB_TABKEY_STR("number"), UPB_VALUE_INIT_CONSTPTR(&fields[47]), NULL},
  4121. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4122. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[52]), NULL},
  4123. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[37]), &strentries[30]},
  4124. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[71]), NULL},
  4125. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4126. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4127. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4128. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4129. {UPB_TABKEY_STR("label"), UPB_VALUE_INIT_CONSTPTR(&fields[27]), NULL},
  4130. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4131. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[41]), NULL},
  4132. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4133. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4134. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4135. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4136. {UPB_TABKEY_STR("number"), UPB_VALUE_INIT_CONSTPTR(&fields[46]), &strentries[49]},
  4137. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4138. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4139. {UPB_TABKEY_STR("type_name"), UPB_VALUE_INIT_CONSTPTR(&fields[70]), NULL},
  4140. {UPB_TABKEY_STR("extendee"), UPB_VALUE_INIT_CONSTPTR(&fields[12]), NULL},
  4141. {UPB_TABKEY_STR("type"), UPB_VALUE_INIT_CONSTPTR(&fields[69]), &strentries[48]},
  4142. {UPB_TABKEY_STR("default_value"), UPB_VALUE_INIT_CONSTPTR(&fields[4]), NULL},
  4143. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[51]), NULL},
  4144. {UPB_TABKEY_STR("experimental_map_key"), UPB_VALUE_INIT_CONSTPTR(&fields[11]), &strentries[67]},
  4145. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4146. {UPB_TABKEY_STR("weak"), UPB_VALUE_INIT_CONSTPTR(&fields[79]), NULL},
  4147. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4148. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4149. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4150. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4151. {UPB_TABKEY_STR("packed"), UPB_VALUE_INIT_CONSTPTR(&fields[58]), NULL},
  4152. {UPB_TABKEY_STR("lazy"), UPB_VALUE_INIT_CONSTPTR(&fields[28]), NULL},
  4153. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4154. {UPB_TABKEY_STR("ctype"), UPB_VALUE_INIT_CONSTPTR(&fields[3]), NULL},
  4155. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4156. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4157. {UPB_TABKEY_STR("deprecated"), UPB_VALUE_INIT_CONSTPTR(&fields[6]), NULL},
  4158. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4159. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[77]), NULL},
  4160. {UPB_TABKEY_STR("extension"), UPB_VALUE_INIT_CONSTPTR(&fields[13]), NULL},
  4161. {UPB_TABKEY_STR("weak_dependency"), UPB_VALUE_INIT_CONSTPTR(&fields[80]), NULL},
  4162. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4163. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[34]), NULL},
  4164. {UPB_TABKEY_STR("service"), UPB_VALUE_INIT_CONSTPTR(&fields[63]), NULL},
  4165. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4166. {UPB_TABKEY_STR("source_code_info"), UPB_VALUE_INIT_CONSTPTR(&fields[64]), NULL},
  4167. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4168. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4169. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4170. {UPB_TABKEY_STR("dependency"), UPB_VALUE_INIT_CONSTPTR(&fields[5]), NULL},
  4171. {UPB_TABKEY_STR("message_type"), UPB_VALUE_INIT_CONSTPTR(&fields[32]), NULL},
  4172. {UPB_TABKEY_STR("package"), UPB_VALUE_INIT_CONSTPTR(&fields[57]), NULL},
  4173. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[53]), &strentries[82]},
  4174. {UPB_TABKEY_STR("enum_type"), UPB_VALUE_INIT_CONSTPTR(&fields[10]), NULL},
  4175. {UPB_TABKEY_STR("public_dependency"), UPB_VALUE_INIT_CONSTPTR(&fields[61]), &strentries[81]},
  4176. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4177. {UPB_TABKEY_STR("file"), UPB_VALUE_INIT_CONSTPTR(&fields[17]), NULL},
  4178. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4179. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4180. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[75]), NULL},
  4181. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4182. {UPB_TABKEY_STR("cc_generic_services"), UPB_VALUE_INIT_CONSTPTR(&fields[2]), NULL},
  4183. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4184. {UPB_TABKEY_STR("java_multiple_files"), UPB_VALUE_INIT_CONSTPTR(&fields[24]), NULL},
  4185. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4186. {UPB_TABKEY_STR("java_generic_services"), UPB_VALUE_INIT_CONSTPTR(&fields[23]), &strentries[102]},
  4187. {UPB_TABKEY_STR("java_generate_equals_and_hash"), UPB_VALUE_INIT_CONSTPTR(&fields[22]), NULL},
  4188. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4189. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4190. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4191. {UPB_TABKEY_STR("go_package"), UPB_VALUE_INIT_CONSTPTR(&fields[18]), NULL},
  4192. {UPB_TABKEY_STR("java_package"), UPB_VALUE_INIT_CONSTPTR(&fields[26]), NULL},
  4193. {UPB_TABKEY_STR("optimize_for"), UPB_VALUE_INIT_CONSTPTR(&fields[48]), NULL},
  4194. {UPB_TABKEY_STR("py_generic_services"), UPB_VALUE_INIT_CONSTPTR(&fields[62]), NULL},
  4195. {UPB_TABKEY_STR("java_outer_classname"), UPB_VALUE_INIT_CONSTPTR(&fields[25]), NULL},
  4196. {UPB_TABKEY_STR("message_set_wire_format"), UPB_VALUE_INIT_CONSTPTR(&fields[31]), &strentries[106]},
  4197. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4198. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[76]), NULL},
  4199. {UPB_TABKEY_STR("no_standard_descriptor_accessor"), UPB_VALUE_INIT_CONSTPTR(&fields[45]), NULL},
  4200. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4201. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4202. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4203. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[39]), NULL},
  4204. {UPB_TABKEY_STR("input_type"), UPB_VALUE_INIT_CONSTPTR(&fields[20]), NULL},
  4205. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4206. {UPB_TABKEY_STR("output_type"), UPB_VALUE_INIT_CONSTPTR(&fields[56]), NULL},
  4207. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[55]), NULL},
  4208. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[74]), NULL},
  4209. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4210. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4211. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4212. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4213. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[54]), &strentries[122]},
  4214. {UPB_TABKEY_STR("method"), UPB_VALUE_INIT_CONSTPTR(&fields[33]), NULL},
  4215. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[35]), &strentries[121]},
  4216. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[72]), NULL},
  4217. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4218. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4219. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4220. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4221. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4222. {UPB_TABKEY_STR("location"), UPB_VALUE_INIT_CONSTPTR(&fields[30]), NULL},
  4223. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4224. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4225. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4226. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4227. {UPB_TABKEY_STR("span"), UPB_VALUE_INIT_CONSTPTR(&fields[65]), &strentries[139]},
  4228. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4229. {UPB_TABKEY_STR("trailing_comments"), UPB_VALUE_INIT_CONSTPTR(&fields[68]), NULL},
  4230. {UPB_TABKEY_STR("leading_comments"), UPB_VALUE_INIT_CONSTPTR(&fields[29]), &strentries[137]},
  4231. {UPB_TABKEY_STR("path"), UPB_VALUE_INIT_CONSTPTR(&fields[59]), NULL},
  4232. {UPB_TABKEY_STR("double_value"), UPB_VALUE_INIT_CONSTPTR(&fields[7]), NULL},
  4233. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4234. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4235. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[36]), NULL},
  4236. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4237. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4238. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4239. {UPB_TABKEY_STR("negative_int_value"), UPB_VALUE_INIT_CONSTPTR(&fields[43]), NULL},
  4240. {UPB_TABKEY_STR("aggregate_value"), UPB_VALUE_INIT_CONSTPTR(&fields[0]), NULL},
  4241. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4242. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4243. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4244. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4245. {UPB_TABKEY_STR("positive_int_value"), UPB_VALUE_INIT_CONSTPTR(&fields[60]), NULL},
  4246. {UPB_TABKEY_STR("identifier_value"), UPB_VALUE_INIT_CONSTPTR(&fields[19]), NULL},
  4247. {UPB_TABKEY_STR("string_value"), UPB_VALUE_INIT_CONSTPTR(&fields[67]), &strentries[154]},
  4248. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4249. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4250. {UPB_TABKEY_STR("is_extension"), UPB_VALUE_INIT_CONSTPTR(&fields[21]), NULL},
  4251. {UPB_TABKEY_STR("name_part"), UPB_VALUE_INIT_CONSTPTR(&fields[42]), NULL},
  4252. {UPB_TABKEY_STR("LABEL_REQUIRED"), UPB_VALUE_INIT_INT32(2), &strentries[162]},
  4253. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4254. {UPB_TABKEY_STR("LABEL_REPEATED"), UPB_VALUE_INIT_INT32(3), NULL},
  4255. {UPB_TABKEY_STR("LABEL_OPTIONAL"), UPB_VALUE_INIT_INT32(1), NULL},
  4256. {UPB_TABKEY_STR("TYPE_FIXED64"), UPB_VALUE_INIT_INT32(6), NULL},
  4257. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4258. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4259. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4260. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4261. {UPB_TABKEY_STR("TYPE_STRING"), UPB_VALUE_INIT_INT32(9), NULL},
  4262. {UPB_TABKEY_STR("TYPE_FLOAT"), UPB_VALUE_INIT_INT32(2), &strentries[193]},
  4263. {UPB_TABKEY_STR("TYPE_DOUBLE"), UPB_VALUE_INIT_INT32(1), NULL},
  4264. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4265. {UPB_TABKEY_STR("TYPE_INT32"), UPB_VALUE_INIT_INT32(5), NULL},
  4266. {UPB_TABKEY_STR("TYPE_SFIXED32"), UPB_VALUE_INIT_INT32(15), NULL},
  4267. {UPB_TABKEY_STR("TYPE_FIXED32"), UPB_VALUE_INIT_INT32(7), NULL},
  4268. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4269. {UPB_TABKEY_STR("TYPE_MESSAGE"), UPB_VALUE_INIT_INT32(11), &strentries[194]},
  4270. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4271. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4272. {UPB_TABKEY_STR("TYPE_INT64"), UPB_VALUE_INIT_INT32(3), &strentries[191]},
  4273. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4274. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4275. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4276. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4277. {UPB_TABKEY_STR("TYPE_ENUM"), UPB_VALUE_INIT_INT32(14), NULL},
  4278. {UPB_TABKEY_STR("TYPE_UINT32"), UPB_VALUE_INIT_INT32(13), NULL},
  4279. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4280. {UPB_TABKEY_STR("TYPE_UINT64"), UPB_VALUE_INIT_INT32(4), &strentries[190]},
  4281. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4282. {UPB_TABKEY_STR("TYPE_SFIXED64"), UPB_VALUE_INIT_INT32(16), NULL},
  4283. {UPB_TABKEY_STR("TYPE_BYTES"), UPB_VALUE_INIT_INT32(12), NULL},
  4284. {UPB_TABKEY_STR("TYPE_SINT64"), UPB_VALUE_INIT_INT32(18), NULL},
  4285. {UPB_TABKEY_STR("TYPE_BOOL"), UPB_VALUE_INIT_INT32(8), NULL},
  4286. {UPB_TABKEY_STR("TYPE_GROUP"), UPB_VALUE_INIT_INT32(10), NULL},
  4287. {UPB_TABKEY_STR("TYPE_SINT32"), UPB_VALUE_INIT_INT32(17), NULL},
  4288. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4289. {UPB_TABKEY_STR("CORD"), UPB_VALUE_INIT_INT32(1), NULL},
  4290. {UPB_TABKEY_STR("STRING"), UPB_VALUE_INIT_INT32(0), &strentries[197]},
  4291. {UPB_TABKEY_STR("STRING_PIECE"), UPB_VALUE_INIT_INT32(2), NULL},
  4292. {UPB_TABKEY_STR("CODE_SIZE"), UPB_VALUE_INIT_INT32(2), NULL},
  4293. {UPB_TABKEY_STR("SPEED"), UPB_VALUE_INIT_INT32(1), &strentries[203]},
  4294. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4295. {UPB_TABKEY_STR("LITE_RUNTIME"), UPB_VALUE_INIT_INT32(3), NULL},
  4296. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4297. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4298. {UPB_TABKEY_STR("google.protobuf.SourceCodeInfo.Location"), UPB_VALUE_INIT_CONSTPTR(&msgs[17]), NULL},
  4299. {UPB_TABKEY_STR("google.protobuf.UninterpretedOption"), UPB_VALUE_INIT_CONSTPTR(&msgs[18]), NULL},
  4300. {UPB_TABKEY_STR("google.protobuf.FileDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[8]), NULL},
  4301. {UPB_TABKEY_STR("google.protobuf.MethodDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[12]), NULL},
  4302. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4303. {UPB_TABKEY_STR("google.protobuf.EnumValueOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[5]), NULL},
  4304. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4305. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4306. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4307. {UPB_TABKEY_STR("google.protobuf.DescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[0]), &strentries[228]},
  4308. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4309. {UPB_TABKEY_STR("google.protobuf.SourceCodeInfo"), UPB_VALUE_INIT_CONSTPTR(&msgs[16]), NULL},
  4310. {UPB_TABKEY_STR("google.protobuf.FieldDescriptorProto.Type"), UPB_VALUE_INIT_CONSTPTR(&enums[1]), NULL},
  4311. {UPB_TABKEY_STR("google.protobuf.DescriptorProto.ExtensionRange"), UPB_VALUE_INIT_CONSTPTR(&msgs[1]), NULL},
  4312. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4313. {UPB_TABKEY_STR("google.protobuf.EnumValueDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[4]), NULL},
  4314. {UPB_TABKEY_STR("google.protobuf.FieldOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[7]), NULL},
  4315. {UPB_TABKEY_STR("google.protobuf.FileOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[10]), NULL},
  4316. {UPB_TABKEY_STR("google.protobuf.EnumDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[2]), &strentries[233]},
  4317. {UPB_TABKEY_STR("google.protobuf.FieldDescriptorProto.Label"), UPB_VALUE_INIT_CONSTPTR(&enums[0]), NULL},
  4318. {UPB_TABKEY_STR("google.protobuf.ServiceDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[14]), NULL},
  4319. {UPB_TABKEY_STR("google.protobuf.FieldOptions.CType"), UPB_VALUE_INIT_CONSTPTR(&enums[2]), &strentries[229]},
  4320. {UPB_TABKEY_STR("google.protobuf.FileDescriptorSet"), UPB_VALUE_INIT_CONSTPTR(&msgs[9]), &strentries[235]},
  4321. {UPB_TABKEY_STR("google.protobuf.EnumOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[3]), NULL},
  4322. {UPB_TABKEY_STR("google.protobuf.FieldDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[6]), NULL},
  4323. {UPB_TABKEY_STR("google.protobuf.FileOptions.OptimizeMode"), UPB_VALUE_INIT_CONSTPTR(&enums[3]), &strentries[221]},
  4324. {UPB_TABKEY_STR("google.protobuf.ServiceOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[15]), NULL},
  4325. {UPB_TABKEY_STR("google.protobuf.MessageOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[11]), NULL},
  4326. {UPB_TABKEY_STR("google.protobuf.MethodOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[13]), &strentries[226]},
  4327. {UPB_TABKEY_STR("google.protobuf.UninterpretedOption.NamePart"), UPB_VALUE_INIT_CONSTPTR(&msgs[19]), NULL},
  4328. };
  4329. static const upb_tabent intentries[14] = {
  4330. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4331. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[73]), NULL},
  4332. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4333. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[71]), NULL},
  4334. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4335. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[77]), NULL},
  4336. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4337. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[75]), NULL},
  4338. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4339. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[76]), NULL},
  4340. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4341. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[74]), NULL},
  4342. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4343. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[72]), NULL},
  4344. };
  4345. static const _upb_value arrays[232] = {
  4346. UPB_ARRAY_EMPTYENT,
  4347. UPB_VALUE_INIT_CONSTPTR(&fields[38]),
  4348. UPB_VALUE_INIT_CONSTPTR(&fields[16]),
  4349. UPB_VALUE_INIT_CONSTPTR(&fields[44]),
  4350. UPB_VALUE_INIT_CONSTPTR(&fields[9]),
  4351. UPB_VALUE_INIT_CONSTPTR(&fields[15]),
  4352. UPB_VALUE_INIT_CONSTPTR(&fields[14]),
  4353. UPB_VALUE_INIT_CONSTPTR(&fields[49]),
  4354. UPB_ARRAY_EMPTYENT,
  4355. UPB_VALUE_INIT_CONSTPTR(&fields[66]),
  4356. UPB_VALUE_INIT_CONSTPTR(&fields[8]),
  4357. UPB_ARRAY_EMPTYENT,
  4358. UPB_VALUE_INIT_CONSTPTR(&fields[40]),
  4359. UPB_VALUE_INIT_CONSTPTR(&fields[78]),
  4360. UPB_VALUE_INIT_CONSTPTR(&fields[50]),
  4361. UPB_ARRAY_EMPTYENT,
  4362. UPB_ARRAY_EMPTYENT,
  4363. UPB_VALUE_INIT_CONSTPTR(&fields[1]),
  4364. UPB_ARRAY_EMPTYENT,
  4365. UPB_ARRAY_EMPTYENT,
  4366. UPB_ARRAY_EMPTYENT,
  4367. UPB_ARRAY_EMPTYENT,
  4368. UPB_ARRAY_EMPTYENT,
  4369. UPB_ARRAY_EMPTYENT,
  4370. UPB_VALUE_INIT_CONSTPTR(&fields[37]),
  4371. UPB_VALUE_INIT_CONSTPTR(&fields[47]),
  4372. UPB_VALUE_INIT_CONSTPTR(&fields[52]),
  4373. UPB_ARRAY_EMPTYENT,
  4374. UPB_ARRAY_EMPTYENT,
  4375. UPB_ARRAY_EMPTYENT,
  4376. UPB_ARRAY_EMPTYENT,
  4377. UPB_ARRAY_EMPTYENT,
  4378. UPB_VALUE_INIT_CONSTPTR(&fields[41]),
  4379. UPB_VALUE_INIT_CONSTPTR(&fields[12]),
  4380. UPB_VALUE_INIT_CONSTPTR(&fields[46]),
  4381. UPB_VALUE_INIT_CONSTPTR(&fields[27]),
  4382. UPB_VALUE_INIT_CONSTPTR(&fields[69]),
  4383. UPB_VALUE_INIT_CONSTPTR(&fields[70]),
  4384. UPB_VALUE_INIT_CONSTPTR(&fields[4]),
  4385. UPB_VALUE_INIT_CONSTPTR(&fields[51]),
  4386. UPB_ARRAY_EMPTYENT,
  4387. UPB_VALUE_INIT_CONSTPTR(&fields[3]),
  4388. UPB_VALUE_INIT_CONSTPTR(&fields[58]),
  4389. UPB_VALUE_INIT_CONSTPTR(&fields[6]),
  4390. UPB_ARRAY_EMPTYENT,
  4391. UPB_VALUE_INIT_CONSTPTR(&fields[28]),
  4392. UPB_ARRAY_EMPTYENT,
  4393. UPB_ARRAY_EMPTYENT,
  4394. UPB_ARRAY_EMPTYENT,
  4395. UPB_VALUE_INIT_CONSTPTR(&fields[11]),
  4396. UPB_VALUE_INIT_CONSTPTR(&fields[79]),
  4397. UPB_ARRAY_EMPTYENT,
  4398. UPB_ARRAY_EMPTYENT,
  4399. UPB_ARRAY_EMPTYENT,
  4400. UPB_ARRAY_EMPTYENT,
  4401. UPB_ARRAY_EMPTYENT,
  4402. UPB_ARRAY_EMPTYENT,
  4403. UPB_ARRAY_EMPTYENT,
  4404. UPB_ARRAY_EMPTYENT,
  4405. UPB_ARRAY_EMPTYENT,
  4406. UPB_ARRAY_EMPTYENT,
  4407. UPB_ARRAY_EMPTYENT,
  4408. UPB_ARRAY_EMPTYENT,
  4409. UPB_ARRAY_EMPTYENT,
  4410. UPB_ARRAY_EMPTYENT,
  4411. UPB_ARRAY_EMPTYENT,
  4412. UPB_ARRAY_EMPTYENT,
  4413. UPB_ARRAY_EMPTYENT,
  4414. UPB_ARRAY_EMPTYENT,
  4415. UPB_ARRAY_EMPTYENT,
  4416. UPB_ARRAY_EMPTYENT,
  4417. UPB_ARRAY_EMPTYENT,
  4418. UPB_ARRAY_EMPTYENT,
  4419. UPB_VALUE_INIT_CONSTPTR(&fields[34]),
  4420. UPB_VALUE_INIT_CONSTPTR(&fields[57]),
  4421. UPB_VALUE_INIT_CONSTPTR(&fields[5]),
  4422. UPB_VALUE_INIT_CONSTPTR(&fields[32]),
  4423. UPB_VALUE_INIT_CONSTPTR(&fields[10]),
  4424. UPB_VALUE_INIT_CONSTPTR(&fields[63]),
  4425. UPB_VALUE_INIT_CONSTPTR(&fields[13]),
  4426. UPB_VALUE_INIT_CONSTPTR(&fields[53]),
  4427. UPB_VALUE_INIT_CONSTPTR(&fields[64]),
  4428. UPB_VALUE_INIT_CONSTPTR(&fields[61]),
  4429. UPB_VALUE_INIT_CONSTPTR(&fields[80]),
  4430. UPB_ARRAY_EMPTYENT,
  4431. UPB_VALUE_INIT_CONSTPTR(&fields[17]),
  4432. UPB_ARRAY_EMPTYENT,
  4433. UPB_VALUE_INIT_CONSTPTR(&fields[26]),
  4434. UPB_ARRAY_EMPTYENT,
  4435. UPB_ARRAY_EMPTYENT,
  4436. UPB_ARRAY_EMPTYENT,
  4437. UPB_ARRAY_EMPTYENT,
  4438. UPB_ARRAY_EMPTYENT,
  4439. UPB_ARRAY_EMPTYENT,
  4440. UPB_VALUE_INIT_CONSTPTR(&fields[25]),
  4441. UPB_VALUE_INIT_CONSTPTR(&fields[48]),
  4442. UPB_VALUE_INIT_CONSTPTR(&fields[24]),
  4443. UPB_VALUE_INIT_CONSTPTR(&fields[18]),
  4444. UPB_ARRAY_EMPTYENT,
  4445. UPB_ARRAY_EMPTYENT,
  4446. UPB_ARRAY_EMPTYENT,
  4447. UPB_ARRAY_EMPTYENT,
  4448. UPB_VALUE_INIT_CONSTPTR(&fields[2]),
  4449. UPB_VALUE_INIT_CONSTPTR(&fields[23]),
  4450. UPB_VALUE_INIT_CONSTPTR(&fields[62]),
  4451. UPB_ARRAY_EMPTYENT,
  4452. UPB_VALUE_INIT_CONSTPTR(&fields[22]),
  4453. UPB_ARRAY_EMPTYENT,
  4454. UPB_ARRAY_EMPTYENT,
  4455. UPB_ARRAY_EMPTYENT,
  4456. UPB_ARRAY_EMPTYENT,
  4457. UPB_ARRAY_EMPTYENT,
  4458. UPB_ARRAY_EMPTYENT,
  4459. UPB_ARRAY_EMPTYENT,
  4460. UPB_ARRAY_EMPTYENT,
  4461. UPB_ARRAY_EMPTYENT,
  4462. UPB_ARRAY_EMPTYENT,
  4463. UPB_ARRAY_EMPTYENT,
  4464. UPB_ARRAY_EMPTYENT,
  4465. UPB_ARRAY_EMPTYENT,
  4466. UPB_ARRAY_EMPTYENT,
  4467. UPB_ARRAY_EMPTYENT,
  4468. UPB_ARRAY_EMPTYENT,
  4469. UPB_ARRAY_EMPTYENT,
  4470. UPB_ARRAY_EMPTYENT,
  4471. UPB_ARRAY_EMPTYENT,
  4472. UPB_ARRAY_EMPTYENT,
  4473. UPB_ARRAY_EMPTYENT,
  4474. UPB_ARRAY_EMPTYENT,
  4475. UPB_ARRAY_EMPTYENT,
  4476. UPB_ARRAY_EMPTYENT,
  4477. UPB_ARRAY_EMPTYENT,
  4478. UPB_ARRAY_EMPTYENT,
  4479. UPB_ARRAY_EMPTYENT,
  4480. UPB_ARRAY_EMPTYENT,
  4481. UPB_ARRAY_EMPTYENT,
  4482. UPB_ARRAY_EMPTYENT,
  4483. UPB_ARRAY_EMPTYENT,
  4484. UPB_ARRAY_EMPTYENT,
  4485. UPB_ARRAY_EMPTYENT,
  4486. UPB_ARRAY_EMPTYENT,
  4487. UPB_ARRAY_EMPTYENT,
  4488. UPB_ARRAY_EMPTYENT,
  4489. UPB_ARRAY_EMPTYENT,
  4490. UPB_ARRAY_EMPTYENT,
  4491. UPB_ARRAY_EMPTYENT,
  4492. UPB_ARRAY_EMPTYENT,
  4493. UPB_ARRAY_EMPTYENT,
  4494. UPB_ARRAY_EMPTYENT,
  4495. UPB_ARRAY_EMPTYENT,
  4496. UPB_ARRAY_EMPTYENT,
  4497. UPB_VALUE_INIT_CONSTPTR(&fields[31]),
  4498. UPB_VALUE_INIT_CONSTPTR(&fields[45]),
  4499. UPB_ARRAY_EMPTYENT,
  4500. UPB_ARRAY_EMPTYENT,
  4501. UPB_ARRAY_EMPTYENT,
  4502. UPB_ARRAY_EMPTYENT,
  4503. UPB_ARRAY_EMPTYENT,
  4504. UPB_ARRAY_EMPTYENT,
  4505. UPB_ARRAY_EMPTYENT,
  4506. UPB_ARRAY_EMPTYENT,
  4507. UPB_ARRAY_EMPTYENT,
  4508. UPB_ARRAY_EMPTYENT,
  4509. UPB_ARRAY_EMPTYENT,
  4510. UPB_ARRAY_EMPTYENT,
  4511. UPB_ARRAY_EMPTYENT,
  4512. UPB_ARRAY_EMPTYENT,
  4513. UPB_VALUE_INIT_CONSTPTR(&fields[39]),
  4514. UPB_VALUE_INIT_CONSTPTR(&fields[20]),
  4515. UPB_VALUE_INIT_CONSTPTR(&fields[56]),
  4516. UPB_VALUE_INIT_CONSTPTR(&fields[55]),
  4517. UPB_ARRAY_EMPTYENT,
  4518. UPB_ARRAY_EMPTYENT,
  4519. UPB_ARRAY_EMPTYENT,
  4520. UPB_ARRAY_EMPTYENT,
  4521. UPB_ARRAY_EMPTYENT,
  4522. UPB_VALUE_INIT_CONSTPTR(&fields[35]),
  4523. UPB_VALUE_INIT_CONSTPTR(&fields[33]),
  4524. UPB_VALUE_INIT_CONSTPTR(&fields[54]),
  4525. UPB_ARRAY_EMPTYENT,
  4526. UPB_ARRAY_EMPTYENT,
  4527. UPB_ARRAY_EMPTYENT,
  4528. UPB_ARRAY_EMPTYENT,
  4529. UPB_ARRAY_EMPTYENT,
  4530. UPB_VALUE_INIT_CONSTPTR(&fields[30]),
  4531. UPB_ARRAY_EMPTYENT,
  4532. UPB_VALUE_INIT_CONSTPTR(&fields[59]),
  4533. UPB_VALUE_INIT_CONSTPTR(&fields[65]),
  4534. UPB_VALUE_INIT_CONSTPTR(&fields[29]),
  4535. UPB_VALUE_INIT_CONSTPTR(&fields[68]),
  4536. UPB_ARRAY_EMPTYENT,
  4537. UPB_ARRAY_EMPTYENT,
  4538. UPB_VALUE_INIT_CONSTPTR(&fields[36]),
  4539. UPB_VALUE_INIT_CONSTPTR(&fields[19]),
  4540. UPB_VALUE_INIT_CONSTPTR(&fields[60]),
  4541. UPB_VALUE_INIT_CONSTPTR(&fields[43]),
  4542. UPB_VALUE_INIT_CONSTPTR(&fields[7]),
  4543. UPB_VALUE_INIT_CONSTPTR(&fields[67]),
  4544. UPB_VALUE_INIT_CONSTPTR(&fields[0]),
  4545. UPB_ARRAY_EMPTYENT,
  4546. UPB_VALUE_INIT_CONSTPTR(&fields[42]),
  4547. UPB_VALUE_INIT_CONSTPTR(&fields[21]),
  4548. UPB_ARRAY_EMPTYENT,
  4549. UPB_VALUE_INIT_CONSTPTR("LABEL_OPTIONAL"),
  4550. UPB_VALUE_INIT_CONSTPTR("LABEL_REQUIRED"),
  4551. UPB_VALUE_INIT_CONSTPTR("LABEL_REPEATED"),
  4552. UPB_ARRAY_EMPTYENT,
  4553. UPB_VALUE_INIT_CONSTPTR("TYPE_DOUBLE"),
  4554. UPB_VALUE_INIT_CONSTPTR("TYPE_FLOAT"),
  4555. UPB_VALUE_INIT_CONSTPTR("TYPE_INT64"),
  4556. UPB_VALUE_INIT_CONSTPTR("TYPE_UINT64"),
  4557. UPB_VALUE_INIT_CONSTPTR("TYPE_INT32"),
  4558. UPB_VALUE_INIT_CONSTPTR("TYPE_FIXED64"),
  4559. UPB_VALUE_INIT_CONSTPTR("TYPE_FIXED32"),
  4560. UPB_VALUE_INIT_CONSTPTR("TYPE_BOOL"),
  4561. UPB_VALUE_INIT_CONSTPTR("TYPE_STRING"),
  4562. UPB_VALUE_INIT_CONSTPTR("TYPE_GROUP"),
  4563. UPB_VALUE_INIT_CONSTPTR("TYPE_MESSAGE"),
  4564. UPB_VALUE_INIT_CONSTPTR("TYPE_BYTES"),
  4565. UPB_VALUE_INIT_CONSTPTR("TYPE_UINT32"),
  4566. UPB_VALUE_INIT_CONSTPTR("TYPE_ENUM"),
  4567. UPB_VALUE_INIT_CONSTPTR("TYPE_SFIXED32"),
  4568. UPB_VALUE_INIT_CONSTPTR("TYPE_SFIXED64"),
  4569. UPB_VALUE_INIT_CONSTPTR("TYPE_SINT32"),
  4570. UPB_VALUE_INIT_CONSTPTR("TYPE_SINT64"),
  4571. UPB_VALUE_INIT_CONSTPTR("STRING"),
  4572. UPB_VALUE_INIT_CONSTPTR("CORD"),
  4573. UPB_VALUE_INIT_CONSTPTR("STRING_PIECE"),
  4574. UPB_ARRAY_EMPTYENT,
  4575. UPB_VALUE_INIT_CONSTPTR("SPEED"),
  4576. UPB_VALUE_INIT_CONSTPTR("CODE_SIZE"),
  4577. UPB_VALUE_INIT_CONSTPTR("LITE_RUNTIME"),
  4578. };
  4579. static const upb_symtab symtab = UPB_SYMTAB_INIT(UPB_STRTABLE_INIT(24, 31, UPB_CTYPE_PTR, 5, &strentries[204]), &reftables[210], &reftables[211]);
  4580. const upb_symtab *upbdefs_google_protobuf_descriptor(const void *owner) {
  4581. upb_symtab_ref(&symtab, owner);
  4582. return &symtab;
  4583. }
  4584. #ifdef UPB_DEBUG_REFS
  4585. static upb_inttable reftables[212] = {
  4586. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4587. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4588. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4589. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4590. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4591. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4592. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4593. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4594. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4595. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4596. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4597. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4598. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4599. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4600. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4601. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4602. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4603. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4604. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4605. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4606. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4607. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4608. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4609. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4610. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4611. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4612. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4613. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4614. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4615. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4616. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4617. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4618. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4619. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4620. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4621. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4622. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4623. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4624. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4625. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4626. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4627. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4628. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4629. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4630. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4631. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4632. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4633. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4634. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4635. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4636. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4637. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4638. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4639. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4640. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4641. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4642. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4643. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4644. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4645. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4646. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4647. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4648. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4649. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4650. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4651. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4652. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4653. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4654. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4655. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4656. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4657. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4658. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4659. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4660. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4661. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4662. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4663. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4664. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4665. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4666. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4667. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4668. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4669. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4670. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4671. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4672. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4673. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4674. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4675. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4676. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4677. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4678. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4679. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4680. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4681. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4682. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4683. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4684. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4685. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4686. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4687. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4688. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4689. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4690. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4691. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4692. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4693. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4694. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4695. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4696. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4697. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4698. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4699. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4700. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4701. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4702. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4703. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4704. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4705. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4706. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4707. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4708. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4709. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4710. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4711. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4712. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4713. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4714. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4715. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4716. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4717. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4718. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4719. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4720. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4721. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4722. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4723. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4724. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4725. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4726. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4727. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4728. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4729. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4730. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4731. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4732. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4733. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4734. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4735. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4736. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4737. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4738. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4739. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4740. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4741. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4742. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4743. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4744. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4745. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4746. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4747. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4748. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4749. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4750. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4751. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4752. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4753. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4754. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4755. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4756. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4757. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4758. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4759. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4760. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4761. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4762. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4763. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4764. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4765. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4766. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4767. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4768. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4769. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4770. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4771. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4772. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4773. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4774. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4775. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4776. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4777. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4778. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4779. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4780. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4781. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4782. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4783. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4784. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4785. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4786. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4787. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4788. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4789. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4790. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4791. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4792. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4793. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4794. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4795. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4796. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4797. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4798. };
  4799. #endif
  4800. /*
  4801. * upb - a minimalist implementation of protocol buffers.
  4802. *
  4803. * Copyright (c) 2008-2009 Google Inc. See LICENSE for details.
  4804. * Author: Josh Haberman <jhaberman@gmail.com>
  4805. *
  4806. * XXX: The routines in this file that consume a string do not currently
  4807. * support having the string span buffers. In the future, as upb_sink and
  4808. * its buffering/sharing functionality evolve there should be an easy and
  4809. * idiomatic way of correctly handling this case. For now, we accept this
  4810. * limitation since we currently only parse descriptors from single strings.
  4811. */
  4812. #include <errno.h>
  4813. #include <stdlib.h>
  4814. #include <string.h>
  4815. static char *upb_strndup(const char *buf, size_t n) {
  4816. char *ret = malloc(n + 1);
  4817. if (!ret) return NULL;
  4818. memcpy(ret, buf, n);
  4819. ret[n] = '\0';
  4820. return ret;
  4821. }
  4822. // Returns a newly allocated string that joins input strings together, for
  4823. // example:
  4824. // join("Foo.Bar", "Baz") -> "Foo.Bar.Baz"
  4825. // join("", "Baz") -> "Baz"
  4826. // Caller owns a ref on the returned string.
  4827. static char *upb_join(const char *base, const char *name) {
  4828. if (!base || strlen(base) == 0) {
  4829. return upb_strdup(name);
  4830. } else {
  4831. char *ret = malloc(strlen(base) + strlen(name) + 2);
  4832. ret[0] = '\0';
  4833. strcat(ret, base);
  4834. strcat(ret, ".");
  4835. strcat(ret, name);
  4836. return ret;
  4837. }
  4838. }
  4839. /* upb_deflist ****************************************************************/
  4840. void upb_deflist_init(upb_deflist *l) {
  4841. l->size = 0;
  4842. l->defs = NULL;
  4843. l->len = 0;
  4844. l->owned = true;
  4845. }
  4846. void upb_deflist_uninit(upb_deflist *l) {
  4847. if (l->owned)
  4848. for(size_t i = 0; i < l->len; i++)
  4849. upb_def_unref(l->defs[i], l);
  4850. free(l->defs);
  4851. }
  4852. bool upb_deflist_push(upb_deflist *l, upb_def *d) {
  4853. if(++l->len >= l->size) {
  4854. size_t new_size = UPB_MAX(l->size, 4);
  4855. new_size *= 2;
  4856. l->defs = realloc(l->defs, new_size * sizeof(void *));
  4857. if (!l->defs) return false;
  4858. l->size = new_size;
  4859. }
  4860. l->defs[l->len - 1] = d;
  4861. return true;
  4862. }
  4863. void upb_deflist_donaterefs(upb_deflist *l, void *owner) {
  4864. assert(l->owned);
  4865. for (size_t i = 0; i < l->len; i++)
  4866. upb_def_donateref(l->defs[i], l, owner);
  4867. l->owned = false;
  4868. }
  4869. static upb_def *upb_deflist_last(upb_deflist *l) {
  4870. return l->defs[l->len-1];
  4871. }
  4872. // Qualify the defname for all defs starting with offset "start" with "str".
  4873. static void upb_deflist_qualify(upb_deflist *l, char *str, int32_t start) {
  4874. for (uint32_t i = start; i < l->len; i++) {
  4875. upb_def *def = l->defs[i];
  4876. char *name = upb_join(str, upb_def_fullname(def));
  4877. upb_def_setfullname(def, name, NULL);
  4878. free(name);
  4879. }
  4880. }
  4881. /* upb_descreader ************************************************************/
  4882. void upb_descreader_init(upb_descreader *r, const upb_handlers *handlers,
  4883. upb_status *status) {
  4884. UPB_UNUSED(status);
  4885. upb_deflist_init(&r->defs);
  4886. upb_sink_reset(upb_descreader_input(r), handlers, r);
  4887. r->stack_len = 0;
  4888. r->name = NULL;
  4889. r->default_string = NULL;
  4890. }
  4891. void upb_descreader_uninit(upb_descreader *r) {
  4892. free(r->name);
  4893. upb_deflist_uninit(&r->defs);
  4894. free(r->default_string);
  4895. while (r->stack_len > 0) {
  4896. upb_descreader_frame *f = &r->stack[--r->stack_len];
  4897. free(f->name);
  4898. }
  4899. }
  4900. upb_def **upb_descreader_getdefs(upb_descreader *r, void *owner, int *n) {
  4901. *n = r->defs.len;
  4902. upb_deflist_donaterefs(&r->defs, owner);
  4903. return r->defs.defs;
  4904. }
  4905. upb_sink *upb_descreader_input(upb_descreader *r) {
  4906. return &r->sink;
  4907. }
  4908. static upb_msgdef *upb_descreader_top(upb_descreader *r) {
  4909. assert(r->stack_len > 1);
  4910. int index = r->stack[r->stack_len-1].start - 1;
  4911. assert(index >= 0);
  4912. return upb_downcast_msgdef_mutable(r->defs.defs[index]);
  4913. }
  4914. static upb_def *upb_descreader_last(upb_descreader *r) {
  4915. return upb_deflist_last(&r->defs);
  4916. }
  4917. // Start/end handlers for FileDescriptorProto and DescriptorProto (the two
  4918. // entities that have names and can contain sub-definitions.
  4919. void upb_descreader_startcontainer(upb_descreader *r) {
  4920. upb_descreader_frame *f = &r->stack[r->stack_len++];
  4921. f->start = r->defs.len;
  4922. f->name = NULL;
  4923. }
  4924. void upb_descreader_endcontainer(upb_descreader *r) {
  4925. upb_descreader_frame *f = &r->stack[--r->stack_len];
  4926. upb_deflist_qualify(&r->defs, f->name, f->start);
  4927. free(f->name);
  4928. f->name = NULL;
  4929. }
  4930. void upb_descreader_setscopename(upb_descreader *r, char *str) {
  4931. upb_descreader_frame *f = &r->stack[r->stack_len-1];
  4932. free(f->name);
  4933. f->name = str;
  4934. }
  4935. // Handlers for google.protobuf.FileDescriptorProto.
  4936. static bool file_startmsg(void *r, const void *hd) {
  4937. UPB_UNUSED(hd);
  4938. upb_descreader_startcontainer(r);
  4939. return true;
  4940. }
  4941. static bool file_endmsg(void *closure, const void *hd, upb_status *status) {
  4942. UPB_UNUSED(hd);
  4943. UPB_UNUSED(status);
  4944. upb_descreader *r = closure;
  4945. upb_descreader_endcontainer(r);
  4946. return true;
  4947. }
  4948. static size_t file_onpackage(void *closure, const void *hd, const char *buf,
  4949. size_t n, const upb_bufhandle *handle) {
  4950. UPB_UNUSED(hd);
  4951. UPB_UNUSED(handle);
  4952. upb_descreader *r = closure;
  4953. // XXX: see comment at the top of the file.
  4954. upb_descreader_setscopename(r, upb_strndup(buf, n));
  4955. return n;
  4956. }
  4957. // Handlers for google.protobuf.EnumValueDescriptorProto.
  4958. static bool enumval_startmsg(void *closure, const void *hd) {
  4959. UPB_UNUSED(hd);
  4960. upb_descreader *r = closure;
  4961. r->saw_number = false;
  4962. r->saw_name = false;
  4963. return true;
  4964. }
  4965. static size_t enumval_onname(void *closure, const void *hd, const char *buf,
  4966. size_t n, const upb_bufhandle *handle) {
  4967. UPB_UNUSED(hd);
  4968. UPB_UNUSED(handle);
  4969. upb_descreader *r = closure;
  4970. // XXX: see comment at the top of the file.
  4971. free(r->name);
  4972. r->name = upb_strndup(buf, n);
  4973. r->saw_name = true;
  4974. return n;
  4975. }
  4976. static bool enumval_onnumber(void *closure, const void *hd, int32_t val) {
  4977. UPB_UNUSED(hd);
  4978. upb_descreader *r = closure;
  4979. r->number = val;
  4980. r->saw_number = true;
  4981. return true;
  4982. }
  4983. static bool enumval_endmsg(void *closure, const void *hd, upb_status *status) {
  4984. UPB_UNUSED(hd);
  4985. upb_descreader *r = closure;
  4986. if(!r->saw_number || !r->saw_name) {
  4987. upb_status_seterrmsg(status, "Enum value missing name or number.");
  4988. return false;
  4989. }
  4990. upb_enumdef *e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  4991. upb_enumdef_addval(e, r->name, r->number, status);
  4992. free(r->name);
  4993. r->name = NULL;
  4994. return true;
  4995. }
  4996. // Handlers for google.protobuf.EnumDescriptorProto.
  4997. static bool enum_startmsg(void *closure, const void *hd) {
  4998. UPB_UNUSED(hd);
  4999. upb_descreader *r = closure;
  5000. upb_deflist_push(&r->defs, UPB_UPCAST(upb_enumdef_new(&r->defs)));
  5001. return true;
  5002. }
  5003. static bool enum_endmsg(void *closure, const void *hd, upb_status *status) {
  5004. UPB_UNUSED(hd);
  5005. upb_descreader *r = closure;
  5006. upb_enumdef *e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  5007. if (upb_def_fullname(upb_descreader_last(r)) == NULL) {
  5008. upb_status_seterrmsg(status, "Enum had no name.");
  5009. return false;
  5010. }
  5011. if (upb_enumdef_numvals(e) == 0) {
  5012. upb_status_seterrmsg(status, "Enum had no values.");
  5013. return false;
  5014. }
  5015. return true;
  5016. }
  5017. static size_t enum_onname(void *closure, const void *hd, const char *buf,
  5018. size_t n, const upb_bufhandle *handle) {
  5019. UPB_UNUSED(hd);
  5020. UPB_UNUSED(handle);
  5021. upb_descreader *r = closure;
  5022. // XXX: see comment at the top of the file.
  5023. char *fullname = upb_strndup(buf, n);
  5024. upb_def_setfullname(upb_descreader_last(r), fullname, NULL);
  5025. free(fullname);
  5026. return n;
  5027. }
  5028. // Handlers for google.protobuf.FieldDescriptorProto
  5029. static bool field_startmsg(void *closure, const void *hd) {
  5030. UPB_UNUSED(hd);
  5031. upb_descreader *r = closure;
  5032. r->f = upb_fielddef_new(&r->defs);
  5033. free(r->default_string);
  5034. r->default_string = NULL;
  5035. // fielddefs default to packed, but descriptors default to non-packed.
  5036. upb_fielddef_setpacked(r->f, false);
  5037. return true;
  5038. }
  5039. // Converts the default value in string "str" into "d". Passes a ref on str.
  5040. // Returns true on success.
  5041. static bool parse_default(char *str, upb_fielddef *f) {
  5042. bool success = true;
  5043. char *end;
  5044. switch (upb_fielddef_type(f)) {
  5045. case UPB_TYPE_INT32: {
  5046. long val = strtol(str, &end, 0);
  5047. if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || *end)
  5048. success = false;
  5049. else
  5050. upb_fielddef_setdefaultint32(f, val);
  5051. break;
  5052. }
  5053. case UPB_TYPE_INT64: {
  5054. long long val = strtoll(str, &end, 0);
  5055. if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || *end)
  5056. success = false;
  5057. else
  5058. upb_fielddef_setdefaultint64(f, val);
  5059. break;
  5060. }
  5061. case UPB_TYPE_UINT32: {
  5062. long val = strtoul(str, &end, 0);
  5063. if (val > UINT32_MAX || errno == ERANGE || *end)
  5064. success = false;
  5065. else
  5066. upb_fielddef_setdefaultuint32(f, val);
  5067. break;
  5068. }
  5069. case UPB_TYPE_UINT64: {
  5070. unsigned long long val = strtoull(str, &end, 0);
  5071. if (val > UINT64_MAX || errno == ERANGE || *end)
  5072. success = false;
  5073. else
  5074. upb_fielddef_setdefaultuint64(f, val);
  5075. break;
  5076. }
  5077. case UPB_TYPE_DOUBLE: {
  5078. double val = strtod(str, &end);
  5079. if (errno == ERANGE || *end)
  5080. success = false;
  5081. else
  5082. upb_fielddef_setdefaultdouble(f, val);
  5083. break;
  5084. }
  5085. case UPB_TYPE_FLOAT: {
  5086. float val = strtof(str, &end);
  5087. if (errno == ERANGE || *end)
  5088. success = false;
  5089. else
  5090. upb_fielddef_setdefaultfloat(f, val);
  5091. break;
  5092. }
  5093. case UPB_TYPE_BOOL: {
  5094. if (strcmp(str, "false") == 0)
  5095. upb_fielddef_setdefaultbool(f, false);
  5096. else if (strcmp(str, "true") == 0)
  5097. upb_fielddef_setdefaultbool(f, true);
  5098. else
  5099. success = false;
  5100. break;
  5101. }
  5102. default: abort();
  5103. }
  5104. return success;
  5105. }
  5106. static bool field_endmsg(void *closure, const void *hd, upb_status *status) {
  5107. UPB_UNUSED(hd);
  5108. upb_descreader *r = closure;
  5109. upb_fielddef *f = r->f;
  5110. // TODO: verify that all required fields were present.
  5111. assert(upb_fielddef_number(f) != 0);
  5112. assert(upb_fielddef_name(f) != NULL);
  5113. assert((upb_fielddef_subdefname(f) != NULL) == upb_fielddef_hassubdef(f));
  5114. if (r->default_string) {
  5115. if (upb_fielddef_issubmsg(f)) {
  5116. upb_status_seterrmsg(status, "Submessages cannot have defaults.");
  5117. return false;
  5118. }
  5119. if (upb_fielddef_isstring(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  5120. upb_fielddef_setdefaultcstr(f, r->default_string, NULL);
  5121. } else {
  5122. if (r->default_string && !parse_default(r->default_string, f)) {
  5123. // We don't worry too much about giving a great error message since the
  5124. // compiler should have ensured this was correct.
  5125. upb_status_seterrmsg(status, "Error converting default value.");
  5126. return false;
  5127. }
  5128. }
  5129. }
  5130. return true;
  5131. }
  5132. static bool field_onlazy(void *closure, const void *hd, bool val) {
  5133. UPB_UNUSED(hd);
  5134. upb_descreader *r = closure;
  5135. upb_fielddef_setlazy(r->f, val);
  5136. return true;
  5137. }
  5138. static bool field_onpacked(void *closure, const void *hd, bool val) {
  5139. UPB_UNUSED(hd);
  5140. upb_descreader *r = closure;
  5141. upb_fielddef_setpacked(r->f, val);
  5142. return true;
  5143. }
  5144. static bool field_ontype(void *closure, const void *hd, int32_t val) {
  5145. UPB_UNUSED(hd);
  5146. upb_descreader *r = closure;
  5147. upb_fielddef_setdescriptortype(r->f, val);
  5148. return true;
  5149. }
  5150. static bool field_onlabel(void *closure, const void *hd, int32_t val) {
  5151. UPB_UNUSED(hd);
  5152. upb_descreader *r = closure;
  5153. upb_fielddef_setlabel(r->f, val);
  5154. return true;
  5155. }
  5156. static bool field_onnumber(void *closure, const void *hd, int32_t val) {
  5157. UPB_UNUSED(hd);
  5158. upb_descreader *r = closure;
  5159. bool ok = upb_fielddef_setnumber(r->f, val, NULL);
  5160. UPB_ASSERT_VAR(ok, ok);
  5161. return true;
  5162. }
  5163. static size_t field_onname(void *closure, const void *hd, const char *buf,
  5164. size_t n, const upb_bufhandle *handle) {
  5165. UPB_UNUSED(hd);
  5166. UPB_UNUSED(handle);
  5167. upb_descreader *r = closure;
  5168. // XXX: see comment at the top of the file.
  5169. char *name = upb_strndup(buf, n);
  5170. upb_fielddef_setname(r->f, name, NULL);
  5171. free(name);
  5172. return n;
  5173. }
  5174. static size_t field_ontypename(void *closure, const void *hd, const char *buf,
  5175. size_t n, const upb_bufhandle *handle) {
  5176. UPB_UNUSED(hd);
  5177. UPB_UNUSED(handle);
  5178. upb_descreader *r = closure;
  5179. // XXX: see comment at the top of the file.
  5180. char *name = upb_strndup(buf, n);
  5181. upb_fielddef_setsubdefname(r->f, name, NULL);
  5182. free(name);
  5183. return n;
  5184. }
  5185. static size_t field_onextendee(void *closure, const void *hd, const char *buf,
  5186. size_t n, const upb_bufhandle *handle) {
  5187. UPB_UNUSED(hd);
  5188. UPB_UNUSED(handle);
  5189. upb_descreader *r = closure;
  5190. // XXX: see comment at the top of the file.
  5191. char *name = upb_strndup(buf, n);
  5192. upb_fielddef_setcontainingtypename(r->f, name, NULL);
  5193. free(name);
  5194. return n;
  5195. }
  5196. static size_t field_ondefaultval(void *closure, const void *hd, const char *buf,
  5197. size_t n, const upb_bufhandle *handle) {
  5198. UPB_UNUSED(hd);
  5199. UPB_UNUSED(handle);
  5200. upb_descreader *r = closure;
  5201. // Have to convert from string to the correct type, but we might not know the
  5202. // type yet, so we save it as a string until the end of the field.
  5203. // XXX: see comment at the top of the file.
  5204. free(r->default_string);
  5205. r->default_string = upb_strndup(buf, n);
  5206. return n;
  5207. }
  5208. // Handlers for google.protobuf.DescriptorProto (representing a message).
  5209. static bool msg_startmsg(void *closure, const void *hd) {
  5210. UPB_UNUSED(hd);
  5211. upb_descreader *r = closure;
  5212. upb_deflist_push(&r->defs, UPB_UPCAST(upb_msgdef_new(&r->defs)));
  5213. upb_descreader_startcontainer(r);
  5214. return true;
  5215. }
  5216. static bool msg_endmsg(void *closure, const void *hd, upb_status *status) {
  5217. UPB_UNUSED(hd);
  5218. upb_descreader *r = closure;
  5219. upb_msgdef *m = upb_descreader_top(r);
  5220. if(!upb_def_fullname(UPB_UPCAST(m))) {
  5221. upb_status_seterrmsg(status, "Encountered message with no name.");
  5222. return false;
  5223. }
  5224. upb_descreader_endcontainer(r);
  5225. return true;
  5226. }
  5227. static size_t msg_onname(void *closure, const void *hd, const char *buf,
  5228. size_t n, const upb_bufhandle *handle) {
  5229. UPB_UNUSED(hd);
  5230. UPB_UNUSED(handle);
  5231. upb_descreader *r = closure;
  5232. upb_msgdef *m = upb_descreader_top(r);
  5233. // XXX: see comment at the top of the file.
  5234. char *name = upb_strndup(buf, n);
  5235. upb_def_setfullname(UPB_UPCAST(m), name, NULL);
  5236. upb_descreader_setscopename(r, name); // Passes ownership of name.
  5237. return n;
  5238. }
  5239. static bool msg_onendfield(void *closure, const void *hd) {
  5240. UPB_UNUSED(hd);
  5241. upb_descreader *r = closure;
  5242. upb_msgdef *m = upb_descreader_top(r);
  5243. upb_msgdef_addfield(m, r->f, &r->defs, NULL);
  5244. r->f = NULL;
  5245. return true;
  5246. }
  5247. static bool pushextension(void *closure, const void *hd) {
  5248. UPB_UNUSED(hd);
  5249. upb_descreader *r = closure;
  5250. assert(upb_fielddef_containingtypename(r->f));
  5251. upb_fielddef_setisextension(r->f, true);
  5252. upb_deflist_push(&r->defs, UPB_UPCAST(r->f));
  5253. r->f = NULL;
  5254. return true;
  5255. }
  5256. #define D(name) upbdefs_google_protobuf_ ## name(s)
  5257. static void reghandlers(const void *closure, upb_handlers *h) {
  5258. const upb_symtab *s = closure;
  5259. const upb_msgdef *m = upb_handlers_msgdef(h);
  5260. if (m == D(DescriptorProto)) {
  5261. upb_handlers_setstartmsg(h, &msg_startmsg, NULL);
  5262. upb_handlers_setendmsg(h, &msg_endmsg, NULL);
  5263. upb_handlers_setstring(h, D(DescriptorProto_name), &msg_onname, NULL);
  5264. upb_handlers_setendsubmsg(h, D(DescriptorProto_field), &msg_onendfield,
  5265. NULL);
  5266. upb_handlers_setendsubmsg(h, D(DescriptorProto_extension), &pushextension,
  5267. NULL);
  5268. } else if (m == D(FileDescriptorProto)) {
  5269. upb_handlers_setstartmsg(h, &file_startmsg, NULL);
  5270. upb_handlers_setendmsg(h, &file_endmsg, NULL);
  5271. upb_handlers_setstring(h, D(FileDescriptorProto_package), &file_onpackage,
  5272. NULL);
  5273. upb_handlers_setendsubmsg(h, D(FileDescriptorProto_extension), &pushextension,
  5274. NULL);
  5275. } else if (m == D(EnumValueDescriptorProto)) {
  5276. upb_handlers_setstartmsg(h, &enumval_startmsg, NULL);
  5277. upb_handlers_setendmsg(h, &enumval_endmsg, NULL);
  5278. upb_handlers_setstring(h, D(EnumValueDescriptorProto_name), &enumval_onname, NULL);
  5279. upb_handlers_setint32(h, D(EnumValueDescriptorProto_number), &enumval_onnumber,
  5280. NULL);
  5281. } else if (m == D(EnumDescriptorProto)) {
  5282. upb_handlers_setstartmsg(h, &enum_startmsg, NULL);
  5283. upb_handlers_setendmsg(h, &enum_endmsg, NULL);
  5284. upb_handlers_setstring(h, D(EnumDescriptorProto_name), &enum_onname, NULL);
  5285. } else if (m == D(FieldDescriptorProto)) {
  5286. upb_handlers_setstartmsg(h, &field_startmsg, NULL);
  5287. upb_handlers_setendmsg(h, &field_endmsg, NULL);
  5288. upb_handlers_setint32(h, D(FieldDescriptorProto_type), &field_ontype,
  5289. NULL);
  5290. upb_handlers_setint32(h, D(FieldDescriptorProto_label), &field_onlabel,
  5291. NULL);
  5292. upb_handlers_setint32(h, D(FieldDescriptorProto_number), &field_onnumber,
  5293. NULL);
  5294. upb_handlers_setstring(h, D(FieldDescriptorProto_name), &field_onname,
  5295. NULL);
  5296. upb_handlers_setstring(h, D(FieldDescriptorProto_type_name),
  5297. &field_ontypename, NULL);
  5298. upb_handlers_setstring(h, D(FieldDescriptorProto_extendee),
  5299. &field_onextendee, NULL);
  5300. upb_handlers_setstring(h, D(FieldDescriptorProto_default_value),
  5301. &field_ondefaultval, NULL);
  5302. } else if (m == D(FieldOptions)) {
  5303. upb_handlers_setbool(h, D(FieldOptions_lazy), &field_onlazy, NULL);
  5304. upb_handlers_setbool(h, D(FieldOptions_packed), &field_onpacked, NULL);
  5305. }
  5306. }
  5307. #undef D
  5308. const upb_handlers *upb_descreader_newhandlers(const void *owner) {
  5309. const upb_symtab *s = upbdefs_google_protobuf_descriptor(&s);
  5310. const upb_handlers *h = upb_handlers_newfrozen(
  5311. upbdefs_google_protobuf_FileDescriptorSet(s), owner, reghandlers, s);
  5312. upb_symtab_unref(s, &s);
  5313. return h;
  5314. }
  5315. /*
  5316. * upb - a minimalist implementation of protocol buffers.
  5317. *
  5318. * Copyright (c) 2013 Google Inc. See LICENSE for details.
  5319. * Author: Josh Haberman <jhaberman@gmail.com>
  5320. *
  5321. * Code to compile a upb::Handlers into bytecode for decoding a protobuf
  5322. * according to that specific schema and destination handlers.
  5323. *
  5324. * Compiling to bytecode is always the first step. If we are using the
  5325. * interpreted decoder we leave it as bytecode and interpret that. If we are
  5326. * using a JIT decoder we use a code generator to turn the bytecode into native
  5327. * code, LLVM IR, etc.
  5328. *
  5329. * Bytecode definition is in decoder.int.h.
  5330. */
  5331. #include <stdarg.h>
  5332. #ifdef UPB_DUMP_BYTECODE
  5333. #include <stdio.h>
  5334. #endif
  5335. #define MAXLABEL 5
  5336. #define EMPTYLABEL -1
  5337. /* mgroup *********************************************************************/
  5338. static void freegroup(upb_refcounted *r) {
  5339. mgroup *g = (mgroup*)r;
  5340. upb_inttable_uninit(&g->methods);
  5341. #ifdef UPB_USE_JIT_X64
  5342. upb_pbdecoder_freejit(g);
  5343. #endif
  5344. free(g->bytecode);
  5345. free(g);
  5346. }
  5347. static void visitgroup(const upb_refcounted *r, upb_refcounted_visit *visit,
  5348. void *closure) {
  5349. const mgroup *g = (const mgroup*)r;
  5350. upb_inttable_iter i;
  5351. upb_inttable_begin(&i, &g->methods);
  5352. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5353. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  5354. visit(r, UPB_UPCAST(method), closure);
  5355. }
  5356. }
  5357. mgroup *newgroup(const void *owner) {
  5358. mgroup *g = malloc(sizeof(*g));
  5359. static const struct upb_refcounted_vtbl vtbl = {visitgroup, freegroup};
  5360. upb_refcounted_init(UPB_UPCAST(g), &vtbl, owner);
  5361. upb_inttable_init(&g->methods, UPB_CTYPE_PTR);
  5362. g->bytecode = NULL;
  5363. g->bytecode_end = NULL;
  5364. return g;
  5365. }
  5366. /* upb_pbdecodermethod ********************************************************/
  5367. static void freemethod(upb_refcounted *r) {
  5368. upb_pbdecodermethod *method = (upb_pbdecodermethod*)r;
  5369. upb_byteshandler_uninit(&method->input_handler_);
  5370. if (method->dest_handlers_) {
  5371. upb_handlers_unref(method->dest_handlers_, method);
  5372. }
  5373. upb_inttable_uninit(&method->dispatch);
  5374. free(method);
  5375. }
  5376. static void visitmethod(const upb_refcounted *r, upb_refcounted_visit *visit,
  5377. void *closure) {
  5378. const upb_pbdecodermethod *m = (const upb_pbdecodermethod*)r;
  5379. visit(r, m->group, closure);
  5380. }
  5381. static upb_pbdecodermethod *newmethod(const upb_handlers *dest_handlers,
  5382. mgroup *group) {
  5383. static const struct upb_refcounted_vtbl vtbl = {visitmethod, freemethod};
  5384. upb_pbdecodermethod *ret = malloc(sizeof(*ret));
  5385. upb_refcounted_init(UPB_UPCAST(ret), &vtbl, &ret);
  5386. upb_byteshandler_init(&ret->input_handler_);
  5387. // The method references the group and vice-versa, in a circular reference.
  5388. upb_ref2(ret, group);
  5389. upb_ref2(group, ret);
  5390. upb_inttable_insertptr(&group->methods, dest_handlers, upb_value_ptr(ret));
  5391. upb_refcounted_unref(UPB_UPCAST(ret), &ret);
  5392. ret->group = UPB_UPCAST(group);
  5393. ret->dest_handlers_ = dest_handlers;
  5394. ret->is_native_ = false; // If we JIT, it will update this later.
  5395. upb_inttable_init(&ret->dispatch, UPB_CTYPE_UINT64);
  5396. if (ret->dest_handlers_) {
  5397. upb_handlers_ref(ret->dest_handlers_, ret);
  5398. }
  5399. return ret;
  5400. }
  5401. void upb_pbdecodermethod_ref(const upb_pbdecodermethod *m, const void *owner) {
  5402. upb_refcounted_ref(UPB_UPCAST(m), owner);
  5403. }
  5404. void upb_pbdecodermethod_unref(const upb_pbdecodermethod *m,
  5405. const void *owner) {
  5406. upb_refcounted_unref(UPB_UPCAST(m), owner);
  5407. }
  5408. void upb_pbdecodermethod_donateref(const upb_pbdecodermethod *m,
  5409. const void *from, const void *to) {
  5410. upb_refcounted_donateref(UPB_UPCAST(m), from, to);
  5411. }
  5412. void upb_pbdecodermethod_checkref(const upb_pbdecodermethod *m,
  5413. const void *owner) {
  5414. upb_refcounted_checkref(UPB_UPCAST(m), owner);
  5415. }
  5416. const upb_handlers *upb_pbdecodermethod_desthandlers(
  5417. const upb_pbdecodermethod *m) {
  5418. return m->dest_handlers_;
  5419. }
  5420. const upb_byteshandler *upb_pbdecodermethod_inputhandler(
  5421. const upb_pbdecodermethod *m) {
  5422. return &m->input_handler_;
  5423. }
  5424. bool upb_pbdecodermethod_isnative(const upb_pbdecodermethod *m) {
  5425. return m->is_native_;
  5426. }
  5427. const upb_pbdecodermethod *upb_pbdecodermethod_new(
  5428. const upb_pbdecodermethodopts *opts, const void *owner) {
  5429. upb_pbcodecache cache;
  5430. upb_pbcodecache_init(&cache);
  5431. const upb_pbdecodermethod *ret =
  5432. upb_pbcodecache_getdecodermethod(&cache, opts);
  5433. upb_pbdecodermethod_ref(ret, owner);
  5434. upb_pbcodecache_uninit(&cache);
  5435. return ret;
  5436. }
  5437. /* bytecode compiler **********************************************************/
  5438. // Data used only at compilation time.
  5439. typedef struct {
  5440. mgroup *group;
  5441. uint32_t *pc;
  5442. int fwd_labels[MAXLABEL];
  5443. int back_labels[MAXLABEL];
  5444. // For fields marked "lazy", parse them lazily or eagerly?
  5445. bool lazy;
  5446. } compiler;
  5447. static compiler *newcompiler(mgroup *group, bool lazy) {
  5448. compiler *ret = malloc(sizeof(*ret));
  5449. ret->group = group;
  5450. ret->lazy = lazy;
  5451. for (int i = 0; i < MAXLABEL; i++) {
  5452. ret->fwd_labels[i] = EMPTYLABEL;
  5453. ret->back_labels[i] = EMPTYLABEL;
  5454. }
  5455. return ret;
  5456. }
  5457. static void freecompiler(compiler *c) {
  5458. free(c);
  5459. }
  5460. const size_t ptr_words = sizeof(void*) / sizeof(uint32_t);
  5461. // How many words an instruction is.
  5462. static int instruction_len(uint32_t instr) {
  5463. switch (getop(instr)) {
  5464. case OP_SETDISPATCH: return 1 + ptr_words;
  5465. case OP_TAGN: return 3;
  5466. case OP_SETBIGGROUPNUM: return 2;
  5467. default: return 1;
  5468. }
  5469. }
  5470. bool op_has_longofs(int32_t instruction) {
  5471. switch (getop(instruction)) {
  5472. case OP_CALL:
  5473. case OP_BRANCH:
  5474. case OP_CHECKDELIM:
  5475. return true;
  5476. // The "tag" instructions only have 8 bytes available for the jump target,
  5477. // but that is ok because these opcodes only require short jumps.
  5478. case OP_TAG1:
  5479. case OP_TAG2:
  5480. case OP_TAGN:
  5481. return false;
  5482. default:
  5483. assert(false);
  5484. return false;
  5485. }
  5486. }
  5487. static int32_t getofs(uint32_t instruction) {
  5488. if (op_has_longofs(instruction)) {
  5489. return (int32_t)instruction >> 8;
  5490. } else {
  5491. return (int8_t)(instruction >> 8);
  5492. }
  5493. }
  5494. static void setofs(uint32_t *instruction, int32_t ofs) {
  5495. if (op_has_longofs(*instruction)) {
  5496. *instruction = getop(*instruction) | ofs << 8;
  5497. } else {
  5498. *instruction = (*instruction & ~0xff00) | ((ofs & 0xff) << 8);
  5499. }
  5500. assert(getofs(*instruction) == ofs); // Would fail in cases of overflow.
  5501. }
  5502. static uint32_t pcofs(compiler *c) { return c->pc - c->group->bytecode; }
  5503. // Defines a local label at the current PC location. All previous forward
  5504. // references are updated to point to this location. The location is noted
  5505. // for any future backward references.
  5506. static void label(compiler *c, unsigned int label) {
  5507. assert(label < MAXLABEL);
  5508. int val = c->fwd_labels[label];
  5509. uint32_t *codep = (val == EMPTYLABEL) ? NULL : c->group->bytecode + val;
  5510. while (codep) {
  5511. int ofs = getofs(*codep);
  5512. setofs(codep, c->pc - codep - instruction_len(*codep));
  5513. codep = ofs ? codep + ofs : NULL;
  5514. }
  5515. c->fwd_labels[label] = EMPTYLABEL;
  5516. c->back_labels[label] = pcofs(c);
  5517. }
  5518. // Creates a reference to a numbered label; either a forward reference
  5519. // (positive arg) or backward reference (negative arg). For forward references
  5520. // the value returned now is actually a "next" pointer into a linked list of all
  5521. // instructions that use this label and will be patched later when the label is
  5522. // defined with label().
  5523. //
  5524. // The returned value is the offset that should be written into the instruction.
  5525. static int32_t labelref(compiler *c, int label) {
  5526. assert(label < MAXLABEL);
  5527. if (label == LABEL_DISPATCH) {
  5528. // No resolving required.
  5529. return 0;
  5530. } else if (label < 0) {
  5531. // Backward local label. Relative to the next instruction.
  5532. uint32_t from = (c->pc + 1) - c->group->bytecode;
  5533. return c->back_labels[-label] - from;
  5534. } else {
  5535. // Forward local label: prepend to (possibly-empty) linked list.
  5536. int *lptr = &c->fwd_labels[label];
  5537. int32_t ret = (*lptr == EMPTYLABEL) ? 0 : *lptr - pcofs(c);
  5538. *lptr = pcofs(c);
  5539. return ret;
  5540. }
  5541. }
  5542. static void put32(compiler *c, uint32_t v) {
  5543. mgroup *g = c->group;
  5544. if (c->pc == g->bytecode_end) {
  5545. int ofs = pcofs(c);
  5546. size_t oldsize = g->bytecode_end - g->bytecode;
  5547. size_t newsize = UPB_MAX(oldsize * 2, 64);
  5548. // TODO(haberman): handle OOM.
  5549. g->bytecode = realloc(g->bytecode, newsize * sizeof(uint32_t));
  5550. g->bytecode_end = g->bytecode + newsize;
  5551. c->pc = g->bytecode + ofs;
  5552. }
  5553. *c->pc++ = v;
  5554. }
  5555. static void putop(compiler *c, opcode op, ...) {
  5556. va_list ap;
  5557. va_start(ap, op);
  5558. switch (op) {
  5559. case OP_SETDISPATCH: {
  5560. uintptr_t ptr = (uintptr_t)va_arg(ap, void*);
  5561. put32(c, OP_SETDISPATCH);
  5562. put32(c, ptr);
  5563. if (sizeof(uintptr_t) > sizeof(uint32_t))
  5564. put32(c, (uint64_t)ptr >> 32);
  5565. break;
  5566. }
  5567. case OP_STARTMSG:
  5568. case OP_ENDMSG:
  5569. case OP_PUSHLENDELIM:
  5570. case OP_POP:
  5571. case OP_SETDELIM:
  5572. case OP_HALT:
  5573. case OP_RET:
  5574. case OP_DISPATCH:
  5575. put32(c, op);
  5576. break;
  5577. case OP_PARSE_DOUBLE:
  5578. case OP_PARSE_FLOAT:
  5579. case OP_PARSE_INT64:
  5580. case OP_PARSE_UINT64:
  5581. case OP_PARSE_INT32:
  5582. case OP_PARSE_FIXED64:
  5583. case OP_PARSE_FIXED32:
  5584. case OP_PARSE_BOOL:
  5585. case OP_PARSE_UINT32:
  5586. case OP_PARSE_SFIXED32:
  5587. case OP_PARSE_SFIXED64:
  5588. case OP_PARSE_SINT32:
  5589. case OP_PARSE_SINT64:
  5590. case OP_STARTSEQ:
  5591. case OP_ENDSEQ:
  5592. case OP_STARTSUBMSG:
  5593. case OP_ENDSUBMSG:
  5594. case OP_STARTSTR:
  5595. case OP_STRING:
  5596. case OP_ENDSTR:
  5597. case OP_PUSHTAGDELIM:
  5598. put32(c, op | va_arg(ap, upb_selector_t) << 8);
  5599. break;
  5600. case OP_SETBIGGROUPNUM:
  5601. put32(c, op);
  5602. put32(c, va_arg(ap, int));
  5603. break;
  5604. case OP_CALL: {
  5605. const upb_pbdecodermethod *method = va_arg(ap, upb_pbdecodermethod *);
  5606. put32(c, op | (method->code_base.ofs - (pcofs(c) + 1)) << 8);
  5607. break;
  5608. }
  5609. case OP_CHECKDELIM:
  5610. case OP_BRANCH: {
  5611. uint32_t instruction = op;
  5612. int label = va_arg(ap, int);
  5613. setofs(&instruction, labelref(c, label));
  5614. put32(c, instruction);
  5615. break;
  5616. }
  5617. case OP_TAG1:
  5618. case OP_TAG2: {
  5619. int label = va_arg(ap, int);
  5620. uint64_t tag = va_arg(ap, uint64_t);
  5621. uint32_t instruction = op | (tag << 16);
  5622. assert(tag <= 0xffff);
  5623. setofs(&instruction, labelref(c, label));
  5624. put32(c, instruction);
  5625. break;
  5626. }
  5627. case OP_TAGN: {
  5628. int label = va_arg(ap, int);
  5629. uint64_t tag = va_arg(ap, uint64_t);
  5630. uint32_t instruction = op | (upb_value_size(tag) << 16);
  5631. setofs(&instruction, labelref(c, label));
  5632. put32(c, instruction);
  5633. put32(c, tag);
  5634. put32(c, tag >> 32);
  5635. break;
  5636. }
  5637. }
  5638. va_end(ap);
  5639. }
  5640. #if defined(UPB_USE_JIT_X64) || defined(UPB_DUMP_BYTECODE)
  5641. const char *upb_pbdecoder_getopname(unsigned int op) {
  5642. #define OP(op) [OP_ ## op] = "OP_" #op
  5643. #define T(op) OP(PARSE_##op)
  5644. static const char *names[] = {
  5645. "<no opcode>",
  5646. T(DOUBLE), T(FLOAT), T(INT64), T(UINT64), T(INT32), T(FIXED64), T(FIXED32),
  5647. T(BOOL), T(UINT32), T(SFIXED32), T(SFIXED64), T(SINT32), T(SINT64),
  5648. OP(STARTMSG), OP(ENDMSG), OP(STARTSEQ), OP(ENDSEQ), OP(STARTSUBMSG),
  5649. OP(ENDSUBMSG), OP(STARTSTR), OP(STRING), OP(ENDSTR), OP(CALL), OP(RET),
  5650. OP(PUSHLENDELIM), OP(PUSHTAGDELIM), OP(SETDELIM), OP(CHECKDELIM),
  5651. OP(BRANCH), OP(TAG1), OP(TAG2), OP(TAGN), OP(SETDISPATCH), OP(POP),
  5652. OP(SETBIGGROUPNUM), OP(DISPATCH), OP(HALT),
  5653. };
  5654. return op > OP_HALT ? names[0] : names[op];
  5655. #undef OP
  5656. #undef T
  5657. }
  5658. #endif
  5659. #ifdef UPB_DUMP_BYTECODE
  5660. static void dumpbc(uint32_t *p, uint32_t *end, FILE *f) {
  5661. uint32_t *begin = p;
  5662. while (p < end) {
  5663. fprintf(f, "%p %8tx", p, p - begin);
  5664. uint32_t instr = *p++;
  5665. uint8_t op = getop(instr);
  5666. fprintf(f, " %s", upb_pbdecoder_getopname(op));
  5667. switch ((opcode)op) {
  5668. case OP_SETDISPATCH: {
  5669. const upb_inttable *dispatch;
  5670. memcpy(&dispatch, p, sizeof(void*));
  5671. p += ptr_words;
  5672. const upb_pbdecodermethod *method =
  5673. (void *)((char *)dispatch -
  5674. offsetof(upb_pbdecodermethod, dispatch));
  5675. fprintf(f, " %s", upb_msgdef_fullname(
  5676. upb_handlers_msgdef(method->dest_handlers_)));
  5677. break;
  5678. }
  5679. case OP_DISPATCH:
  5680. case OP_STARTMSG:
  5681. case OP_ENDMSG:
  5682. case OP_PUSHLENDELIM:
  5683. case OP_POP:
  5684. case OP_SETDELIM:
  5685. case OP_HALT:
  5686. case OP_RET:
  5687. break;
  5688. case OP_PARSE_DOUBLE:
  5689. case OP_PARSE_FLOAT:
  5690. case OP_PARSE_INT64:
  5691. case OP_PARSE_UINT64:
  5692. case OP_PARSE_INT32:
  5693. case OP_PARSE_FIXED64:
  5694. case OP_PARSE_FIXED32:
  5695. case OP_PARSE_BOOL:
  5696. case OP_PARSE_UINT32:
  5697. case OP_PARSE_SFIXED32:
  5698. case OP_PARSE_SFIXED64:
  5699. case OP_PARSE_SINT32:
  5700. case OP_PARSE_SINT64:
  5701. case OP_STARTSEQ:
  5702. case OP_ENDSEQ:
  5703. case OP_STARTSUBMSG:
  5704. case OP_ENDSUBMSG:
  5705. case OP_STARTSTR:
  5706. case OP_STRING:
  5707. case OP_ENDSTR:
  5708. case OP_PUSHTAGDELIM:
  5709. fprintf(f, " %d", instr >> 8);
  5710. break;
  5711. case OP_SETBIGGROUPNUM:
  5712. fprintf(f, " %d", *p++);
  5713. break;
  5714. case OP_CHECKDELIM:
  5715. case OP_CALL:
  5716. case OP_BRANCH:
  5717. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  5718. break;
  5719. case OP_TAG1:
  5720. case OP_TAG2: {
  5721. fprintf(f, " tag:0x%x", instr >> 16);
  5722. if (getofs(instr)) {
  5723. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  5724. }
  5725. break;
  5726. }
  5727. case OP_TAGN: {
  5728. uint64_t tag = *p++;
  5729. tag |= (uint64_t)*p++ << 32;
  5730. fprintf(f, " tag:0x%llx", (long long)tag);
  5731. fprintf(f, " n:%d", instr >> 16);
  5732. if (getofs(instr)) {
  5733. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  5734. }
  5735. break;
  5736. }
  5737. }
  5738. fputs("\n", f);
  5739. }
  5740. }
  5741. #endif
  5742. static uint64_t get_encoded_tag(const upb_fielddef *f, int wire_type) {
  5743. uint32_t tag = (upb_fielddef_number(f) << 3) | wire_type;
  5744. uint64_t encoded_tag = upb_vencode32(tag);
  5745. // No tag should be greater than 5 bytes.
  5746. assert(encoded_tag <= 0xffffffffff);
  5747. return encoded_tag;
  5748. }
  5749. static void putchecktag(compiler *c, const upb_fielddef *f,
  5750. int wire_type, int dest) {
  5751. uint64_t tag = get_encoded_tag(f, wire_type);
  5752. switch (upb_value_size(tag)) {
  5753. case 1:
  5754. putop(c, OP_TAG1, dest, tag);
  5755. break;
  5756. case 2:
  5757. putop(c, OP_TAG2, dest, tag);
  5758. break;
  5759. default:
  5760. putop(c, OP_TAGN, dest, tag);
  5761. break;
  5762. }
  5763. }
  5764. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  5765. upb_selector_t selector;
  5766. bool ok = upb_handlers_getselector(f, type, &selector);
  5767. UPB_ASSERT_VAR(ok, ok);
  5768. return selector;
  5769. }
  5770. // Takes an existing, primary dispatch table entry and repacks it with a
  5771. // different alternate wire type. Called when we are inserting a secondary
  5772. // dispatch table entry for an alternate wire type.
  5773. static uint64_t repack(uint64_t dispatch, int new_wt2) {
  5774. uint64_t ofs;
  5775. uint8_t wt1;
  5776. uint8_t old_wt2;
  5777. upb_pbdecoder_unpackdispatch(dispatch, &ofs, &wt1, &old_wt2);
  5778. assert(old_wt2 == NO_WIRE_TYPE); // wt2 should not be set yet.
  5779. return upb_pbdecoder_packdispatch(ofs, wt1, new_wt2);
  5780. }
  5781. // Marks the current bytecode position as the dispatch target for this message,
  5782. // field, and wire type.
  5783. static void dispatchtarget(compiler *c, upb_pbdecodermethod *method,
  5784. const upb_fielddef *f, int wire_type) {
  5785. // Offset is relative to msg base.
  5786. uint64_t ofs = pcofs(c) - method->code_base.ofs;
  5787. uint32_t fn = upb_fielddef_number(f);
  5788. upb_inttable *d = &method->dispatch;
  5789. upb_value v;
  5790. if (upb_inttable_remove(d, fn, &v)) {
  5791. // TODO: prioritize based on packed setting in .proto file.
  5792. uint64_t repacked = repack(upb_value_getuint64(v), wire_type);
  5793. upb_inttable_insert(d, fn, upb_value_uint64(repacked));
  5794. upb_inttable_insert(d, fn + UPB_MAX_FIELDNUMBER, upb_value_uint64(ofs));
  5795. } else {
  5796. uint64_t val = upb_pbdecoder_packdispatch(ofs, wire_type, NO_WIRE_TYPE);
  5797. upb_inttable_insert(d, fn, upb_value_uint64(val));
  5798. }
  5799. }
  5800. static void putpush(compiler *c, const upb_fielddef *f) {
  5801. if (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE) {
  5802. putop(c, OP_PUSHLENDELIM);
  5803. } else {
  5804. uint32_t fn = upb_fielddef_number(f);
  5805. if (fn >= 1 << 24) {
  5806. putop(c, OP_PUSHTAGDELIM, 0);
  5807. putop(c, OP_SETBIGGROUPNUM, fn);
  5808. } else {
  5809. putop(c, OP_PUSHTAGDELIM, fn);
  5810. }
  5811. }
  5812. }
  5813. static upb_pbdecodermethod *find_submethod(const compiler *c,
  5814. const upb_pbdecodermethod *method,
  5815. const upb_fielddef *f) {
  5816. const upb_handlers *sub =
  5817. upb_handlers_getsubhandlers(method->dest_handlers_, f);
  5818. upb_value v;
  5819. return upb_inttable_lookupptr(&c->group->methods, sub, &v)
  5820. ? upb_value_getptr(v)
  5821. : NULL;
  5822. }
  5823. static void putsel(compiler *c, opcode op, upb_selector_t sel,
  5824. const upb_handlers *h) {
  5825. if (upb_handlers_gethandler(h, sel)) {
  5826. putop(c, op, sel);
  5827. }
  5828. }
  5829. // Puts an opcode to call a callback, but only if a callback actually exists for
  5830. // this field and handler type.
  5831. static void maybeput(compiler *c, opcode op, const upb_handlers *h,
  5832. const upb_fielddef *f, upb_handlertype_t type) {
  5833. putsel(c, op, getsel(f, type), h);
  5834. }
  5835. static bool haslazyhandlers(const upb_handlers *h, const upb_fielddef *f) {
  5836. if (!upb_fielddef_lazy(f))
  5837. return false;
  5838. return upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STARTSTR)) ||
  5839. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STRING)) ||
  5840. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_ENDSTR));
  5841. }
  5842. /* bytecode compiler code generation ******************************************/
  5843. // Symbolic names for our local labels.
  5844. #define LABEL_LOOPSTART 1 // Top of a repeated field loop.
  5845. #define LABEL_LOOPBREAK 2 // To jump out of a repeated loop
  5846. #define LABEL_FIELD 3 // Jump backward to find the most recent field.
  5847. #define LABEL_ENDMSG 4 // To reach the OP_ENDMSG instr for this msg.
  5848. // Generates bytecode to parse a single non-lazy message field.
  5849. static void generate_msgfield(compiler *c, const upb_fielddef *f,
  5850. upb_pbdecodermethod *method) {
  5851. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5852. const upb_pbdecodermethod *sub_m = find_submethod(c, method, f);
  5853. if (!sub_m) {
  5854. // Don't emit any code for this field at all; it will be parsed as an
  5855. // unknown field.
  5856. return;
  5857. }
  5858. label(c, LABEL_FIELD);
  5859. int wire_type =
  5860. (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE)
  5861. ? UPB_WIRE_TYPE_DELIMITED
  5862. : UPB_WIRE_TYPE_START_GROUP;
  5863. if (upb_fielddef_isseq(f)) {
  5864. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5865. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5866. dispatchtarget(c, method, f, wire_type);
  5867. putop(c, OP_PUSHTAGDELIM, 0);
  5868. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  5869. label(c, LABEL_LOOPSTART);
  5870. putpush(c, f);
  5871. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  5872. putop(c, OP_CALL, sub_m);
  5873. putop(c, OP_POP);
  5874. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  5875. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  5876. putop(c, OP_SETDELIM);
  5877. }
  5878. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5879. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  5880. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5881. label(c, LABEL_LOOPBREAK);
  5882. putop(c, OP_POP);
  5883. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5884. } else {
  5885. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5886. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5887. dispatchtarget(c, method, f, wire_type);
  5888. putpush(c, f);
  5889. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  5890. putop(c, OP_CALL, sub_m);
  5891. putop(c, OP_POP);
  5892. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  5893. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  5894. putop(c, OP_SETDELIM);
  5895. }
  5896. }
  5897. }
  5898. // Generates bytecode to parse a single string or lazy submessage field.
  5899. static void generate_delimfield(compiler *c, const upb_fielddef *f,
  5900. upb_pbdecodermethod *method) {
  5901. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5902. label(c, LABEL_FIELD);
  5903. if (upb_fielddef_isseq(f)) {
  5904. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5905. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5906. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5907. putop(c, OP_PUSHTAGDELIM, 0);
  5908. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  5909. label(c, LABEL_LOOPSTART);
  5910. putop(c, OP_PUSHLENDELIM);
  5911. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  5912. // Need to emit even if no handler to skip past the string.
  5913. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  5914. putop(c, OP_POP);
  5915. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  5916. putop(c, OP_SETDELIM);
  5917. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5918. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_LOOPBREAK);
  5919. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5920. label(c, LABEL_LOOPBREAK);
  5921. putop(c, OP_POP);
  5922. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5923. } else {
  5924. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5925. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5926. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5927. putop(c, OP_PUSHLENDELIM);
  5928. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  5929. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  5930. putop(c, OP_POP);
  5931. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  5932. putop(c, OP_SETDELIM);
  5933. }
  5934. }
  5935. // Generates bytecode to parse a single primitive field.
  5936. static void generate_primitivefield(compiler *c, const upb_fielddef *f,
  5937. upb_pbdecodermethod *method) {
  5938. label(c, LABEL_FIELD);
  5939. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5940. upb_descriptortype_t descriptor_type = upb_fielddef_descriptortype(f);
  5941. // From a decoding perspective, ENUM is the same as INT32.
  5942. if (descriptor_type == UPB_DESCRIPTOR_TYPE_ENUM)
  5943. descriptor_type = UPB_DESCRIPTOR_TYPE_INT32;
  5944. opcode parse_type = (opcode)descriptor_type;
  5945. // TODO(haberman): generate packed or non-packed first depending on "packed"
  5946. // setting in the fielddef. This will favor (in speed) whichever was
  5947. // specified.
  5948. assert((int)parse_type >= 0 && parse_type <= OP_MAX);
  5949. upb_selector_t sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  5950. int wire_type = upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  5951. if (upb_fielddef_isseq(f)) {
  5952. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5953. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5954. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5955. putop(c, OP_PUSHLENDELIM);
  5956. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); // Packed
  5957. label(c, LABEL_LOOPSTART);
  5958. putop(c, parse_type, sel);
  5959. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5960. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5961. dispatchtarget(c, method, f, wire_type);
  5962. putop(c, OP_PUSHTAGDELIM, 0);
  5963. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); // Non-packed
  5964. label(c, LABEL_LOOPSTART);
  5965. putop(c, parse_type, sel);
  5966. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5967. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  5968. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5969. label(c, LABEL_LOOPBREAK);
  5970. putop(c, OP_POP); // Packed and non-packed join.
  5971. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5972. putop(c, OP_SETDELIM); // Could remove for non-packed by dup ENDSEQ.
  5973. } else {
  5974. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5975. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5976. dispatchtarget(c, method, f, wire_type);
  5977. putop(c, parse_type, sel);
  5978. }
  5979. }
  5980. // Adds bytecode for parsing the given message to the given decoderplan,
  5981. // while adding all dispatch targets to this message's dispatch table.
  5982. static void compile_method(compiler *c, upb_pbdecodermethod *method) {
  5983. assert(method);
  5984. // Clear all entries in the dispatch table.
  5985. upb_inttable_uninit(&method->dispatch);
  5986. upb_inttable_init(&method->dispatch, UPB_CTYPE_UINT64);
  5987. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5988. const upb_msgdef *md = upb_handlers_msgdef(h);
  5989. method->code_base.ofs = pcofs(c);
  5990. putop(c, OP_SETDISPATCH, &method->dispatch);
  5991. putsel(c, OP_STARTMSG, UPB_STARTMSG_SELECTOR, h);
  5992. label(c, LABEL_FIELD);
  5993. uint32_t* start_pc = c->pc;
  5994. upb_msg_field_iter i;
  5995. for(upb_msg_field_begin(&i, md);
  5996. !upb_msg_field_done(&i);
  5997. upb_msg_field_next(&i)) {
  5998. const upb_fielddef *f = upb_msg_iter_field(&i);
  5999. upb_fieldtype_t type = upb_fielddef_type(f);
  6000. if (type == UPB_TYPE_MESSAGE && !(haslazyhandlers(h, f) && c->lazy)) {
  6001. generate_msgfield(c, f, method);
  6002. } else if (type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES ||
  6003. type == UPB_TYPE_MESSAGE) {
  6004. generate_delimfield(c, f, method);
  6005. } else {
  6006. generate_primitivefield(c, f, method);
  6007. }
  6008. }
  6009. // If there were no fields, or if no handlers were defined, we need to
  6010. // generate a non-empty loop body so that we can at least dispatch for unknown
  6011. // fields and check for the end of the message.
  6012. if (c->pc == start_pc) {
  6013. // Check for end-of-message.
  6014. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6015. // Unconditionally dispatch.
  6016. putop(c, OP_DISPATCH, 0);
  6017. }
  6018. // For now we just loop back to the last field of the message (or if none,
  6019. // the DISPATCH opcode for the message).
  6020. putop(c, OP_BRANCH, -LABEL_FIELD);
  6021. // Insert both a label and a dispatch table entry for this end-of-msg.
  6022. label(c, LABEL_ENDMSG);
  6023. upb_value val = upb_value_uint64(pcofs(c) - method->code_base.ofs);
  6024. upb_inttable_insert(&method->dispatch, DISPATCH_ENDMSG, val);
  6025. putsel(c, OP_ENDMSG, UPB_ENDMSG_SELECTOR, h);
  6026. putop(c, OP_RET);
  6027. upb_inttable_compact(&method->dispatch);
  6028. }
  6029. // Populate "methods" with new upb_pbdecodermethod objects reachable from "h".
  6030. // Returns the method for these handlers.
  6031. //
  6032. // Generates a new method for every destination handlers reachable from "h".
  6033. static void find_methods(compiler *c, const upb_handlers *h) {
  6034. upb_value v;
  6035. if (upb_inttable_lookupptr(&c->group->methods, h, &v))
  6036. return;
  6037. newmethod(h, c->group);
  6038. // Find submethods.
  6039. upb_msg_field_iter i;
  6040. const upb_msgdef *md = upb_handlers_msgdef(h);
  6041. for(upb_msg_field_begin(&i, md);
  6042. !upb_msg_field_done(&i);
  6043. upb_msg_field_next(&i)) {
  6044. const upb_fielddef *f = upb_msg_iter_field(&i);
  6045. const upb_handlers *sub_h;
  6046. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  6047. (sub_h = upb_handlers_getsubhandlers(h, f)) != NULL) {
  6048. // We only generate a decoder method for submessages with handlers.
  6049. // Others will be parsed as unknown fields.
  6050. find_methods(c, sub_h);
  6051. }
  6052. }
  6053. }
  6054. // (Re-)compile bytecode for all messages in "msgs."
  6055. // Overwrites any existing bytecode in "c".
  6056. static void compile_methods(compiler *c) {
  6057. // Start over at the beginning of the bytecode.
  6058. c->pc = c->group->bytecode;
  6059. upb_inttable_iter i;
  6060. upb_inttable_begin(&i, &c->group->methods);
  6061. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  6062. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  6063. compile_method(c, method);
  6064. }
  6065. }
  6066. static void set_bytecode_handlers(mgroup *g) {
  6067. upb_inttable_iter i;
  6068. upb_inttable_begin(&i, &g->methods);
  6069. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  6070. upb_pbdecodermethod *m = upb_value_getptr(upb_inttable_iter_value(&i));
  6071. m->code_base.ptr = g->bytecode + m->code_base.ofs;
  6072. upb_byteshandler *h = &m->input_handler_;
  6073. upb_byteshandler_setstartstr(h, upb_pbdecoder_startbc, m->code_base.ptr);
  6074. upb_byteshandler_setstring(h, upb_pbdecoder_decode, g);
  6075. upb_byteshandler_setendstr(h, upb_pbdecoder_end, m);
  6076. }
  6077. }
  6078. /* JIT setup. *****************************************************************/
  6079. #ifdef UPB_USE_JIT_X64
  6080. static void sethandlers(mgroup *g, bool allowjit) {
  6081. g->jit_code = NULL;
  6082. if (allowjit) {
  6083. // Compile byte-code into machine code, create handlers.
  6084. upb_pbdecoder_jit(g);
  6085. } else {
  6086. set_bytecode_handlers(g);
  6087. }
  6088. }
  6089. #else // UPB_USE_JIT_X64
  6090. static void sethandlers(mgroup *g, bool allowjit) {
  6091. // No JIT compiled in; use bytecode handlers unconditionally.
  6092. UPB_UNUSED(allowjit);
  6093. set_bytecode_handlers(g);
  6094. }
  6095. #endif // UPB_USE_JIT_X64
  6096. // TODO(haberman): allow this to be constructed for an arbitrary set of dest
  6097. // handlers and other mgroups (but verify we have a transitive closure).
  6098. const mgroup *mgroup_new(const upb_handlers *dest, bool allowjit, bool lazy,
  6099. const void *owner) {
  6100. UPB_UNUSED(allowjit);
  6101. assert(upb_handlers_isfrozen(dest));
  6102. mgroup *g = newgroup(owner);
  6103. compiler *c = newcompiler(g, lazy);
  6104. find_methods(c, dest);
  6105. // We compile in two passes:
  6106. // 1. all messages are assigned relative offsets from the beginning of the
  6107. // bytecode (saved in method->code_base).
  6108. // 2. forwards OP_CALL instructions can be correctly linked since message
  6109. // offsets have been previously assigned.
  6110. //
  6111. // Could avoid the second pass by linking OP_CALL instructions somehow.
  6112. compile_methods(c);
  6113. compile_methods(c);
  6114. g->bytecode_end = c->pc;
  6115. freecompiler(c);
  6116. #ifdef UPB_DUMP_BYTECODE
  6117. FILE *f = fopen("/tmp/upb-bytecode", "wb");
  6118. assert(f);
  6119. dumpbc(g->bytecode, g->bytecode_end, stderr);
  6120. dumpbc(g->bytecode, g->bytecode_end, f);
  6121. fclose(f);
  6122. #endif
  6123. sethandlers(g, allowjit);
  6124. return g;
  6125. }
  6126. /* upb_pbcodecache ************************************************************/
  6127. void upb_pbcodecache_init(upb_pbcodecache *c) {
  6128. upb_inttable_init(&c->groups, UPB_CTYPE_CONSTPTR);
  6129. c->allow_jit_ = true;
  6130. }
  6131. void upb_pbcodecache_uninit(upb_pbcodecache *c) {
  6132. upb_inttable_iter i;
  6133. upb_inttable_begin(&i, &c->groups);
  6134. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  6135. const mgroup *group = upb_value_getconstptr(upb_inttable_iter_value(&i));
  6136. upb_refcounted_unref(UPB_UPCAST(group), c);
  6137. }
  6138. upb_inttable_uninit(&c->groups);
  6139. }
  6140. bool upb_pbcodecache_allowjit(const upb_pbcodecache *c) {
  6141. return c->allow_jit_;
  6142. }
  6143. bool upb_pbcodecache_setallowjit(upb_pbcodecache *c, bool allow) {
  6144. if (upb_inttable_count(&c->groups) > 0)
  6145. return false;
  6146. c->allow_jit_ = allow;
  6147. return true;
  6148. }
  6149. const upb_pbdecodermethod *upb_pbcodecache_getdecodermethod(
  6150. upb_pbcodecache *c, const upb_pbdecodermethodopts *opts) {
  6151. // Right now we build a new DecoderMethod every time.
  6152. // TODO(haberman): properly cache methods by their true key.
  6153. const mgroup *g = mgroup_new(opts->handlers, c->allow_jit_, opts->lazy, c);
  6154. upb_inttable_push(&c->groups, upb_value_constptr(g));
  6155. upb_value v;
  6156. bool ok = upb_inttable_lookupptr(&g->methods, opts->handlers, &v);
  6157. UPB_ASSERT_VAR(ok, ok);
  6158. return upb_value_getptr(v);
  6159. }
  6160. /* upb_pbdecodermethodopts ****************************************************/
  6161. void upb_pbdecodermethodopts_init(upb_pbdecodermethodopts *opts,
  6162. const upb_handlers *h) {
  6163. opts->handlers = h;
  6164. opts->lazy = false;
  6165. }
  6166. void upb_pbdecodermethodopts_setlazy(upb_pbdecodermethodopts *opts, bool lazy) {
  6167. opts->lazy = lazy;
  6168. }
  6169. /*
  6170. * upb - a minimalist implementation of protocol buffers.
  6171. *
  6172. * Copyright (c) 2008-2013 Google Inc. See LICENSE for details.
  6173. * Author: Josh Haberman <jhaberman@gmail.com>
  6174. *
  6175. * This file implements a VM for the interpreted (bytecode) decoder.
  6176. *
  6177. * Bytecode must previously have been generated using the bytecode compiler in
  6178. * compile_decoder.c. This decoder then walks through the bytecode op-by-op to
  6179. * parse the input.
  6180. *
  6181. * Decoding is fully resumable; we just keep a pointer to the current bytecode
  6182. * instruction and resume from there. A fair amount of the logic here is to
  6183. * handle the fact that values can span buffer seams and we have to be able to
  6184. * be capable of suspending/resuming from any byte in the stream. This
  6185. * sometimes requires keeping a few trailing bytes from the last buffer around
  6186. * in the "residual" buffer.
  6187. */
  6188. #include <inttypes.h>
  6189. #include <setjmp.h>
  6190. #include <stdarg.h>
  6191. #include <stddef.h>
  6192. #include <stdlib.h>
  6193. #ifdef UPB_DUMP_BYTECODE
  6194. #include <stdio.h>
  6195. #endif
  6196. #define CHECK_SUSPEND(x) if (!(x)) return upb_pbdecoder_suspend(d);
  6197. // Error messages that are shared between the bytecode and JIT decoders.
  6198. const char *kPbDecoderStackOverflow = "Nesting too deep.";
  6199. // Error messages shared within this file.
  6200. static const char *kUnterminatedVarint = "Unterminated varint.";
  6201. /* upb_pbdecoder **************************************************************/
  6202. static opcode halt = OP_HALT;
  6203. // Whether an op consumes any of the input buffer.
  6204. static bool consumes_input(opcode op) {
  6205. switch (op) {
  6206. case OP_SETDISPATCH:
  6207. case OP_STARTMSG:
  6208. case OP_ENDMSG:
  6209. case OP_STARTSEQ:
  6210. case OP_ENDSEQ:
  6211. case OP_STARTSUBMSG:
  6212. case OP_ENDSUBMSG:
  6213. case OP_STARTSTR:
  6214. case OP_ENDSTR:
  6215. case OP_PUSHTAGDELIM:
  6216. case OP_POP:
  6217. case OP_SETDELIM:
  6218. case OP_SETBIGGROUPNUM:
  6219. case OP_CHECKDELIM:
  6220. case OP_CALL:
  6221. case OP_RET:
  6222. case OP_BRANCH:
  6223. return false;
  6224. default:
  6225. return true;
  6226. }
  6227. }
  6228. static bool in_residual_buf(const upb_pbdecoder *d, const char *p);
  6229. // It's unfortunate that we have to micro-manage the compiler this way,
  6230. // especially since this tuning is necessarily specific to one hardware
  6231. // configuration. But emperically on a Core i7, performance increases 30-50%
  6232. // with these annotations. Every instance where these appear, gcc 4.2.1 made
  6233. // the wrong decision and degraded performance in benchmarks.
  6234. #define FORCEINLINE static inline __attribute__((always_inline))
  6235. #define NOINLINE __attribute__((noinline))
  6236. static void seterr(upb_pbdecoder *d, const char *msg) {
  6237. // TODO(haberman): encapsulate this access to pipeline->status, but not sure
  6238. // exactly what that interface should look like.
  6239. upb_status_seterrmsg(d->status, msg);
  6240. }
  6241. void upb_pbdecoder_seterr(upb_pbdecoder *d, const char *msg) {
  6242. seterr(d, msg);
  6243. }
  6244. /* Buffering ******************************************************************/
  6245. // We operate on one buffer at a time, which is either the user's buffer passed
  6246. // to our "decode" callback or some residual bytes from the previous buffer.
  6247. // How many bytes can be safely read from d->ptr without reading past end-of-buf
  6248. // or past the current delimited end.
  6249. static size_t curbufleft(const upb_pbdecoder *d) {
  6250. assert(d->data_end >= d->ptr);
  6251. return d->data_end - d->ptr;
  6252. }
  6253. // Overall stream offset of d->ptr.
  6254. uint64_t offset(const upb_pbdecoder *d) {
  6255. return d->bufstart_ofs + (d->ptr - d->buf);
  6256. }
  6257. // Advances d->ptr.
  6258. static void advance(upb_pbdecoder *d, size_t len) {
  6259. assert(curbufleft(d) >= len);
  6260. d->ptr += len;
  6261. }
  6262. static bool in_buf(const char *p, const char *buf, const char *end) {
  6263. return p >= buf && p <= end;
  6264. }
  6265. static bool in_residual_buf(const upb_pbdecoder *d, const char *p) {
  6266. return in_buf(p, d->residual, d->residual_end);
  6267. }
  6268. // Calculates the delim_end value, which is affected by both the current buffer
  6269. // and the parsing stack, so must be called whenever either is updated.
  6270. static void set_delim_end(upb_pbdecoder *d) {
  6271. size_t delim_ofs = d->top->end_ofs - d->bufstart_ofs;
  6272. if (delim_ofs <= (d->end - d->buf)) {
  6273. d->delim_end = d->buf + delim_ofs;
  6274. d->data_end = d->delim_end;
  6275. } else {
  6276. d->data_end = d->end;
  6277. d->delim_end = NULL;
  6278. }
  6279. }
  6280. static void switchtobuf(upb_pbdecoder *d, const char *buf, const char *end) {
  6281. d->ptr = buf;
  6282. d->buf = buf;
  6283. d->end = end;
  6284. set_delim_end(d);
  6285. }
  6286. static void advancetobuf(upb_pbdecoder *d, const char *buf, size_t len) {
  6287. assert(curbufleft(d) == 0);
  6288. d->bufstart_ofs += (d->end - d->buf);
  6289. switchtobuf(d, buf, buf + len);
  6290. }
  6291. static void checkpoint(upb_pbdecoder *d) {
  6292. // The assertion here is in the interests of efficiency, not correctness.
  6293. // We are trying to ensure that we don't checkpoint() more often than
  6294. // necessary.
  6295. assert(d->checkpoint != d->ptr);
  6296. d->checkpoint = d->ptr;
  6297. }
  6298. // Resumes the decoder from an initial state or from a previous suspend.
  6299. int32_t upb_pbdecoder_resume(upb_pbdecoder *d, void *p, const char *buf,
  6300. size_t size, const upb_bufhandle *handle) {
  6301. UPB_UNUSED(p); // Useless; just for the benefit of the JIT.
  6302. d->buf_param = buf;
  6303. d->size_param = size;
  6304. d->handle = handle;
  6305. if (d->residual_end > d->residual) {
  6306. // We have residual bytes from the last buffer.
  6307. assert(d->ptr == d->residual);
  6308. } else {
  6309. switchtobuf(d, buf, buf + size);
  6310. }
  6311. d->checkpoint = d->ptr;
  6312. if (d->top->groupnum < 0) {
  6313. CHECK_RETURN(upb_pbdecoder_skipunknown(d, -1, 0));
  6314. d->checkpoint = d->ptr;
  6315. }
  6316. return DECODE_OK;
  6317. }
  6318. // Suspends the decoder at the last checkpoint, without saving any residual
  6319. // bytes. If there are any unconsumed bytes, returns a short byte count.
  6320. size_t upb_pbdecoder_suspend(upb_pbdecoder *d) {
  6321. d->pc = d->last;
  6322. if (d->checkpoint == d->residual) {
  6323. // Checkpoint was in residual buf; no user bytes were consumed.
  6324. d->ptr = d->residual;
  6325. return 0;
  6326. } else {
  6327. assert(!in_residual_buf(d, d->checkpoint));
  6328. assert(d->buf == d->buf_param);
  6329. size_t consumed = d->checkpoint - d->buf;
  6330. d->bufstart_ofs += consumed;
  6331. d->residual_end = d->residual;
  6332. switchtobuf(d, d->residual, d->residual_end);
  6333. return consumed;
  6334. }
  6335. }
  6336. // Suspends the decoder at the last checkpoint, and saves any unconsumed
  6337. // bytes in our residual buffer. This is necessary if we need more user
  6338. // bytes to form a complete value, which might not be contiguous in the
  6339. // user's buffers. Always consumes all user bytes.
  6340. static size_t suspend_save(upb_pbdecoder *d) {
  6341. // We hit end-of-buffer before we could parse a full value.
  6342. // Save any unconsumed bytes (if any) to the residual buffer.
  6343. d->pc = d->last;
  6344. if (d->checkpoint == d->residual) {
  6345. // Checkpoint was in residual buf; append user byte(s) to residual buf.
  6346. assert((d->residual_end - d->residual) + d->size_param <=
  6347. sizeof(d->residual));
  6348. if (!in_residual_buf(d, d->ptr)) {
  6349. d->bufstart_ofs -= (d->residual_end - d->residual);
  6350. }
  6351. memcpy(d->residual_end, d->buf_param, d->size_param);
  6352. d->residual_end += d->size_param;
  6353. } else {
  6354. // Checkpoint was in user buf; old residual bytes not needed.
  6355. assert(!in_residual_buf(d, d->checkpoint));
  6356. d->ptr = d->checkpoint;
  6357. size_t save = curbufleft(d);
  6358. assert(save <= sizeof(d->residual));
  6359. memcpy(d->residual, d->ptr, save);
  6360. d->residual_end = d->residual + save;
  6361. d->bufstart_ofs = offset(d);
  6362. }
  6363. switchtobuf(d, d->residual, d->residual_end);
  6364. return d->size_param;
  6365. }
  6366. // Skips "bytes" bytes in the stream, which may be more than available. If we
  6367. // skip more bytes than are available, we return a long read count to the caller
  6368. // indicating how many bytes the caller should skip before passing a new buffer.
  6369. static int32_t skip(upb_pbdecoder *d, size_t bytes) {
  6370. assert(!in_residual_buf(d, d->ptr) || d->size_param == 0);
  6371. if (curbufleft(d) >= bytes) {
  6372. // Skipped data is all in current buffer.
  6373. advance(d, bytes);
  6374. return DECODE_OK;
  6375. } else {
  6376. // Skipped data extends beyond currently available buffers.
  6377. d->pc = d->last;
  6378. size_t skip = bytes - curbufleft(d);
  6379. d->bufstart_ofs += (d->end - d->buf) + skip;
  6380. d->residual_end = d->residual;
  6381. switchtobuf(d, d->residual, d->residual_end);
  6382. return d->size_param + skip;
  6383. }
  6384. }
  6385. // Copies the next "bytes" bytes into "buf" and advances the stream.
  6386. // Requires that this many bytes are available in the current buffer.
  6387. FORCEINLINE void consumebytes(upb_pbdecoder *d, void *buf, size_t bytes) {
  6388. assert(bytes <= curbufleft(d));
  6389. memcpy(buf, d->ptr, bytes);
  6390. advance(d, bytes);
  6391. }
  6392. // Slow path for getting the next "bytes" bytes, regardless of whether they are
  6393. // available in the current buffer or not. Returns a status code as described
  6394. // in decoder.int.h.
  6395. static NOINLINE int32_t getbytes_slow(upb_pbdecoder *d, void *buf,
  6396. size_t bytes) {
  6397. const size_t avail = curbufleft(d);
  6398. consumebytes(d, buf, avail);
  6399. bytes -= avail;
  6400. assert(bytes > 0);
  6401. if (in_residual_buf(d, d->ptr)) {
  6402. advancetobuf(d, d->buf_param, d->size_param);
  6403. }
  6404. if (curbufleft(d) >= bytes) {
  6405. consumebytes(d, buf + avail, bytes);
  6406. return DECODE_OK;
  6407. } else if (d->data_end == d->delim_end) {
  6408. seterr(d, "Submessage ended in the middle of a value or group");
  6409. return upb_pbdecoder_suspend(d);
  6410. } else {
  6411. return suspend_save(d);
  6412. }
  6413. }
  6414. // Gets the next "bytes" bytes, regardless of whether they are available in the
  6415. // current buffer or not. Returns a status code as described in decoder.int.h.
  6416. FORCEINLINE int32_t getbytes(upb_pbdecoder *d, void *buf, size_t bytes) {
  6417. if (curbufleft(d) >= bytes) {
  6418. // Buffer has enough data to satisfy.
  6419. consumebytes(d, buf, bytes);
  6420. return DECODE_OK;
  6421. } else {
  6422. return getbytes_slow(d, buf, bytes);
  6423. }
  6424. }
  6425. static NOINLINE size_t peekbytes_slow(upb_pbdecoder *d, void *buf,
  6426. size_t bytes) {
  6427. size_t ret = curbufleft(d);
  6428. memcpy(buf, d->ptr, ret);
  6429. if (in_residual_buf(d, d->ptr)) {
  6430. size_t copy = UPB_MIN(bytes - ret, d->size_param);
  6431. memcpy(buf + ret, d->buf_param, copy);
  6432. ret += copy;
  6433. }
  6434. return ret;
  6435. }
  6436. FORCEINLINE size_t peekbytes(upb_pbdecoder *d, void *buf, size_t bytes) {
  6437. if (curbufleft(d) >= bytes) {
  6438. memcpy(buf, d->ptr, bytes);
  6439. return bytes;
  6440. } else {
  6441. return peekbytes_slow(d, buf, bytes);
  6442. }
  6443. }
  6444. /* Decoding of wire types *****************************************************/
  6445. // Slow path for decoding a varint from the current buffer position.
  6446. // Returns a status code as described in decoder.int.h.
  6447. NOINLINE int32_t upb_pbdecoder_decode_varint_slow(upb_pbdecoder *d,
  6448. uint64_t *u64) {
  6449. *u64 = 0;
  6450. uint8_t byte = 0x80;
  6451. int bitpos;
  6452. for(bitpos = 0; bitpos < 70 && (byte & 0x80); bitpos += 7) {
  6453. int32_t ret = getbytes(d, &byte, 1);
  6454. if (ret >= 0) return ret;
  6455. *u64 |= (uint64_t)(byte & 0x7F) << bitpos;
  6456. }
  6457. if(bitpos == 70 && (byte & 0x80)) {
  6458. seterr(d, kUnterminatedVarint);
  6459. return upb_pbdecoder_suspend(d);
  6460. }
  6461. return DECODE_OK;
  6462. }
  6463. // Decodes a varint from the current buffer position.
  6464. // Returns a status code as described in decoder.int.h.
  6465. FORCEINLINE int32_t decode_varint(upb_pbdecoder *d, uint64_t *u64) {
  6466. if (curbufleft(d) > 0 && !(*d->ptr & 0x80)) {
  6467. *u64 = *d->ptr;
  6468. advance(d, 1);
  6469. return DECODE_OK;
  6470. } else if (curbufleft(d) >= 10) {
  6471. // Fast case.
  6472. upb_decoderet r = upb_vdecode_fast(d->ptr);
  6473. if (r.p == NULL) {
  6474. seterr(d, kUnterminatedVarint);
  6475. return upb_pbdecoder_suspend(d);
  6476. }
  6477. advance(d, r.p - d->ptr);
  6478. *u64 = r.val;
  6479. return DECODE_OK;
  6480. } else {
  6481. // Slow case -- varint spans buffer seam.
  6482. return upb_pbdecoder_decode_varint_slow(d, u64);
  6483. }
  6484. }
  6485. // Decodes a 32-bit varint from the current buffer position.
  6486. // Returns a status code as described in decoder.int.h.
  6487. FORCEINLINE int32_t decode_v32(upb_pbdecoder *d, uint32_t *u32) {
  6488. uint64_t u64;
  6489. int32_t ret = decode_varint(d, &u64);
  6490. if (ret >= 0) return ret;
  6491. if (u64 > UINT32_MAX) {
  6492. seterr(d, "Unterminated 32-bit varint");
  6493. // TODO(haberman) guarantee that this function return is >= 0 somehow,
  6494. // so we know this path will always be treated as error by our caller.
  6495. // Right now the size_t -> int32_t can overflow and produce negative values.
  6496. *u32 = 0;
  6497. return upb_pbdecoder_suspend(d);
  6498. }
  6499. *u32 = u64;
  6500. return DECODE_OK;
  6501. }
  6502. // Decodes a fixed32 from the current buffer position.
  6503. // Returns a status code as described in decoder.int.h.
  6504. // TODO: proper byte swapping for big-endian machines.
  6505. FORCEINLINE int32_t decode_fixed32(upb_pbdecoder *d, uint32_t *u32) {
  6506. return getbytes(d, u32, 4);
  6507. }
  6508. // Decodes a fixed64 from the current buffer position.
  6509. // Returns a status code as described in decoder.int.h.
  6510. // TODO: proper byte swapping for big-endian machines.
  6511. FORCEINLINE int32_t decode_fixed64(upb_pbdecoder *d, uint64_t *u64) {
  6512. return getbytes(d, u64, 8);
  6513. }
  6514. // Non-static versions of the above functions.
  6515. // These are called by the JIT for fallback paths.
  6516. int32_t upb_pbdecoder_decode_f32(upb_pbdecoder *d, uint32_t *u32) {
  6517. return decode_fixed32(d, u32);
  6518. }
  6519. int32_t upb_pbdecoder_decode_f64(upb_pbdecoder *d, uint64_t *u64) {
  6520. return decode_fixed64(d, u64);
  6521. }
  6522. static double as_double(uint64_t n) { double d; memcpy(&d, &n, 8); return d; }
  6523. static float as_float(uint32_t n) { float f; memcpy(&f, &n, 4); return f; }
  6524. // Pushes a frame onto the decoder stack.
  6525. static bool decoder_push(upb_pbdecoder *d, uint64_t end) {
  6526. upb_pbdecoder_frame *fr = d->top;
  6527. if (end > fr->end_ofs) {
  6528. seterr(d, "Submessage end extends past enclosing submessage.");
  6529. return false;
  6530. } else if ((fr + 1) == d->limit) {
  6531. seterr(d, kPbDecoderStackOverflow);
  6532. return false;
  6533. }
  6534. fr++;
  6535. fr->end_ofs = end;
  6536. fr->dispatch = NULL;
  6537. fr->groupnum = 0;
  6538. d->top = fr;
  6539. return true;
  6540. }
  6541. static bool pushtagdelim(upb_pbdecoder *d, uint32_t arg) {
  6542. // While we expect to see an "end" tag (either ENDGROUP or a non-sequence
  6543. // field number) prior to hitting any enclosing submessage end, pushing our
  6544. // existing delim end prevents us from continuing to parse values from a
  6545. // corrupt proto that doesn't give us an END tag in time.
  6546. if (!decoder_push(d, d->top->end_ofs))
  6547. return false;
  6548. d->top->groupnum = arg;
  6549. return true;
  6550. }
  6551. // Pops a frame from the decoder stack.
  6552. static void decoder_pop(upb_pbdecoder *d) { d->top--; }
  6553. NOINLINE int32_t upb_pbdecoder_checktag_slow(upb_pbdecoder *d,
  6554. uint64_t expected) {
  6555. uint64_t data = 0;
  6556. size_t bytes = upb_value_size(expected);
  6557. size_t read = peekbytes(d, &data, bytes);
  6558. if (read == bytes && data == expected) {
  6559. // Advance past matched bytes.
  6560. int32_t ok = getbytes(d, &data, read);
  6561. UPB_ASSERT_VAR(ok, ok < 0);
  6562. return DECODE_OK;
  6563. } else if (read < bytes && memcmp(&data, &expected, read) == 0) {
  6564. return suspend_save(d);
  6565. } else {
  6566. return DECODE_MISMATCH;
  6567. }
  6568. }
  6569. int32_t upb_pbdecoder_skipunknown(upb_pbdecoder *d, int32_t fieldnum,
  6570. uint8_t wire_type) {
  6571. if (fieldnum >= 0)
  6572. goto have_tag;
  6573. while (true) {
  6574. uint32_t tag;
  6575. CHECK_RETURN(decode_v32(d, &tag));
  6576. wire_type = tag & 0x7;
  6577. fieldnum = tag >> 3;
  6578. have_tag:
  6579. if (fieldnum == 0) {
  6580. seterr(d, "Saw invalid field number (0)");
  6581. return upb_pbdecoder_suspend(d);
  6582. }
  6583. // TODO: deliver to unknown field callback.
  6584. switch (wire_type) {
  6585. case UPB_WIRE_TYPE_32BIT:
  6586. CHECK_RETURN(skip(d, 4));
  6587. break;
  6588. case UPB_WIRE_TYPE_64BIT:
  6589. CHECK_RETURN(skip(d, 8));
  6590. break;
  6591. case UPB_WIRE_TYPE_VARINT: {
  6592. uint64_t u64;
  6593. CHECK_RETURN(decode_varint(d, &u64));
  6594. break;
  6595. }
  6596. case UPB_WIRE_TYPE_DELIMITED: {
  6597. uint32_t len;
  6598. CHECK_RETURN(decode_v32(d, &len));
  6599. CHECK_RETURN(skip(d, len));
  6600. break;
  6601. }
  6602. case UPB_WIRE_TYPE_START_GROUP:
  6603. CHECK_SUSPEND(pushtagdelim(d, -fieldnum));
  6604. break;
  6605. case UPB_WIRE_TYPE_END_GROUP:
  6606. if (fieldnum == -d->top->groupnum) {
  6607. decoder_pop(d);
  6608. } else if (fieldnum == d->top->groupnum) {
  6609. return DECODE_ENDGROUP;
  6610. } else {
  6611. seterr(d, "Unmatched ENDGROUP tag.");
  6612. return upb_pbdecoder_suspend(d);
  6613. }
  6614. break;
  6615. default:
  6616. seterr(d, "Invalid wire type");
  6617. return upb_pbdecoder_suspend(d);
  6618. }
  6619. if (d->top->groupnum >= 0) {
  6620. return DECODE_OK;
  6621. }
  6622. if (d->ptr == d->delim_end) {
  6623. seterr(d, "Enclosing submessage ended in the middle of value or group");
  6624. // Unlike most errors we notice during parsing, right now we have consumed
  6625. // all of the user's input.
  6626. //
  6627. // There are three different options for how to handle this case:
  6628. //
  6629. // 1. decode() = short count, error = set
  6630. // 2. decode() = full count, error = set
  6631. // 3. decode() = full count, error NOT set, short count and error will
  6632. // be reported on next call to decode() (or end())
  6633. //
  6634. // (1) and (3) have the advantage that they preserve the invariant that an
  6635. // error occurs iff decode() returns a short count.
  6636. //
  6637. // (2) and (3) have the advantage of reflecting the fact that all of the
  6638. // bytes were in fact parsed (and possibly delivered to the unknown field
  6639. // handler, in the future when that is supported).
  6640. //
  6641. // (3) requires extra state in the decode (a place to store the "permanent
  6642. // error" that we should return for all subsequent attempts to decode).
  6643. // But we likely want this anyway.
  6644. //
  6645. // Right now we do (1), thanks to the fact that we checkpoint *after* this
  6646. // check. (3) may be a better choice long term; unclear at the moment.
  6647. return upb_pbdecoder_suspend(d);
  6648. }
  6649. checkpoint(d);
  6650. }
  6651. }
  6652. static void goto_endmsg(upb_pbdecoder *d) {
  6653. upb_value v;
  6654. bool found = upb_inttable_lookup32(d->top->dispatch, DISPATCH_ENDMSG, &v);
  6655. UPB_ASSERT_VAR(found, found);
  6656. d->pc = d->top->base + upb_value_getuint64(v);
  6657. }
  6658. // Parses a tag and jumps to the corresponding bytecode instruction for this
  6659. // field.
  6660. //
  6661. // If the tag is unknown (or the wire type doesn't match), parses the field as
  6662. // unknown. If the tag is a valid ENDGROUP tag, jumps to the bytecode
  6663. // instruction for the end of message.
  6664. static int32_t dispatch(upb_pbdecoder *d) {
  6665. upb_inttable *dispatch = d->top->dispatch;
  6666. // Decode tag.
  6667. uint32_t tag;
  6668. CHECK_RETURN(decode_v32(d, &tag));
  6669. uint8_t wire_type = tag & 0x7;
  6670. uint32_t fieldnum = tag >> 3;
  6671. // Lookup tag. Because of packed/non-packed compatibility, we have to
  6672. // check the wire type against two possibilities.
  6673. upb_value val;
  6674. if (fieldnum != DISPATCH_ENDMSG &&
  6675. upb_inttable_lookup32(dispatch, fieldnum, &val)) {
  6676. uint64_t v = upb_value_getuint64(val);
  6677. if (wire_type == (v & 0xff)) {
  6678. d->pc = d->top->base + (v >> 16);
  6679. return DECODE_OK;
  6680. } else if (wire_type == ((v >> 8) & 0xff)) {
  6681. bool found =
  6682. upb_inttable_lookup(dispatch, fieldnum + UPB_MAX_FIELDNUMBER, &val);
  6683. UPB_ASSERT_VAR(found, found);
  6684. d->pc = d->top->base + upb_value_getuint64(val);
  6685. return DECODE_OK;
  6686. }
  6687. }
  6688. // Unknown field or ENDGROUP.
  6689. int32_t ret = upb_pbdecoder_skipunknown(d, fieldnum, wire_type);
  6690. if (ret == DECODE_ENDGROUP) {
  6691. goto_endmsg(d);
  6692. return DECODE_OK;
  6693. } else {
  6694. d->pc = d->last - 1; // Rewind to CHECKDELIM.
  6695. return ret;
  6696. }
  6697. }
  6698. // Callers know that the stack is more than one deep because the opcodes that
  6699. // call this only occur after PUSH operations.
  6700. upb_pbdecoder_frame *outer_frame(upb_pbdecoder *d) {
  6701. assert(d->top != d->stack);
  6702. return d->top - 1;
  6703. }
  6704. /* The main decoding loop *****************************************************/
  6705. // The main decoder VM function. Uses traditional bytecode dispatch loop with a
  6706. // switch() statement.
  6707. size_t upb_pbdecoder_decode(void *closure, const void *hd, const char *buf,
  6708. size_t size, const upb_bufhandle *handle) {
  6709. upb_pbdecoder *d = closure;
  6710. const mgroup *group = hd;
  6711. assert(buf);
  6712. int32_t result = upb_pbdecoder_resume(d, NULL, buf, size, handle);
  6713. if (result == DECODE_ENDGROUP) {
  6714. goto_endmsg(d);
  6715. }
  6716. CHECK_RETURN(result);
  6717. UPB_UNUSED(group);
  6718. #define VMCASE(op, code) \
  6719. case op: { code; if (consumes_input(op)) checkpoint(d); break; }
  6720. #define PRIMITIVE_OP(type, wt, name, convfunc, ctype) \
  6721. VMCASE(OP_PARSE_ ## type, { \
  6722. ctype val; \
  6723. CHECK_RETURN(decode_ ## wt(d, &val)); \
  6724. upb_sink_put ## name(&d->top->sink, arg, (convfunc)(val)); \
  6725. })
  6726. while(1) {
  6727. d->last = d->pc;
  6728. int32_t instruction = *d->pc++;
  6729. opcode op = getop(instruction);
  6730. uint32_t arg = instruction >> 8;
  6731. int32_t longofs = arg;
  6732. assert(d->ptr != d->residual_end);
  6733. #ifdef UPB_DUMP_BYTECODE
  6734. fprintf(stderr, "s_ofs=%d buf_ofs=%d data_rem=%d buf_rem=%d delim_rem=%d "
  6735. "%x %s (%d)\n",
  6736. (int)offset(d),
  6737. (int)(d->ptr - d->buf),
  6738. (int)(d->data_end - d->ptr),
  6739. (int)(d->end - d->ptr),
  6740. (int)((d->top->end_ofs - d->bufstart_ofs) - (d->ptr - d->buf)),
  6741. (int)(d->pc - 1 - group->bytecode),
  6742. upb_pbdecoder_getopname(op),
  6743. arg);
  6744. #endif
  6745. switch (op) {
  6746. // Technically, we are losing data if we see a 32-bit varint that is not
  6747. // properly sign-extended. We could detect this and error about the data
  6748. // loss, but proto2 does not do this, so we pass.
  6749. PRIMITIVE_OP(INT32, varint, int32, int32_t, uint64_t)
  6750. PRIMITIVE_OP(INT64, varint, int64, int64_t, uint64_t)
  6751. PRIMITIVE_OP(UINT32, varint, uint32, uint32_t, uint64_t)
  6752. PRIMITIVE_OP(UINT64, varint, uint64, uint64_t, uint64_t)
  6753. PRIMITIVE_OP(FIXED32, fixed32, uint32, uint32_t, uint32_t)
  6754. PRIMITIVE_OP(FIXED64, fixed64, uint64, uint64_t, uint64_t)
  6755. PRIMITIVE_OP(SFIXED32, fixed32, int32, int32_t, uint32_t)
  6756. PRIMITIVE_OP(SFIXED64, fixed64, int64, int64_t, uint64_t)
  6757. PRIMITIVE_OP(BOOL, varint, bool, bool, uint64_t)
  6758. PRIMITIVE_OP(DOUBLE, fixed64, double, as_double, uint64_t)
  6759. PRIMITIVE_OP(FLOAT, fixed32, float, as_float, uint32_t)
  6760. PRIMITIVE_OP(SINT32, varint, int32, upb_zzdec_32, uint64_t)
  6761. PRIMITIVE_OP(SINT64, varint, int64, upb_zzdec_64, uint64_t)
  6762. VMCASE(OP_SETDISPATCH,
  6763. d->top->base = d->pc - 1;
  6764. memcpy(&d->top->dispatch, d->pc, sizeof(void*));
  6765. d->pc += sizeof(void*) / sizeof(uint32_t);
  6766. )
  6767. VMCASE(OP_STARTMSG,
  6768. CHECK_SUSPEND(upb_sink_startmsg(&d->top->sink));
  6769. )
  6770. VMCASE(OP_ENDMSG,
  6771. CHECK_SUSPEND(upb_sink_endmsg(&d->top->sink, d->status));
  6772. )
  6773. VMCASE(OP_STARTSEQ,
  6774. upb_pbdecoder_frame *outer = outer_frame(d);
  6775. CHECK_SUSPEND(upb_sink_startseq(&outer->sink, arg, &d->top->sink));
  6776. )
  6777. VMCASE(OP_ENDSEQ,
  6778. CHECK_SUSPEND(upb_sink_endseq(&d->top->sink, arg));
  6779. )
  6780. VMCASE(OP_STARTSUBMSG,
  6781. upb_pbdecoder_frame *outer = outer_frame(d);
  6782. CHECK_SUSPEND(upb_sink_startsubmsg(&outer->sink, arg, &d->top->sink));
  6783. )
  6784. VMCASE(OP_ENDSUBMSG,
  6785. CHECK_SUSPEND(upb_sink_endsubmsg(&d->top->sink, arg));
  6786. )
  6787. VMCASE(OP_STARTSTR,
  6788. uint32_t len = d->top->end_ofs - offset(d);
  6789. upb_pbdecoder_frame *outer = outer_frame(d);
  6790. CHECK_SUSPEND(upb_sink_startstr(&outer->sink, arg, len, &d->top->sink));
  6791. if (len == 0) {
  6792. d->pc++; // Skip OP_STRING.
  6793. }
  6794. )
  6795. VMCASE(OP_STRING,
  6796. uint32_t len = curbufleft(d);
  6797. size_t n = upb_sink_putstring(&d->top->sink, arg, d->ptr, len, handle);
  6798. if (n > len) {
  6799. if (n > d->top->end_ofs - offset(d)) {
  6800. seterr(d, "Tried to skip past end of string.");
  6801. return upb_pbdecoder_suspend(d);
  6802. } else {
  6803. int32_t ret = skip(d, n);
  6804. // This shouldn't return DECODE_OK, because n > len.
  6805. assert(ret >= 0);
  6806. return ret;
  6807. }
  6808. }
  6809. advance(d, n);
  6810. if (n < len || d->delim_end == NULL) {
  6811. // We aren't finished with this string yet.
  6812. d->pc--; // Repeat OP_STRING.
  6813. if (n > 0) checkpoint(d);
  6814. return upb_pbdecoder_suspend(d);
  6815. }
  6816. )
  6817. VMCASE(OP_ENDSTR,
  6818. CHECK_SUSPEND(upb_sink_endstr(&d->top->sink, arg));
  6819. )
  6820. VMCASE(OP_PUSHTAGDELIM,
  6821. CHECK_SUSPEND(pushtagdelim(d, arg));
  6822. )
  6823. VMCASE(OP_SETBIGGROUPNUM,
  6824. d->top->groupnum = *d->pc++;
  6825. )
  6826. VMCASE(OP_POP,
  6827. assert(d->top > d->stack);
  6828. decoder_pop(d);
  6829. )
  6830. VMCASE(OP_PUSHLENDELIM,
  6831. uint32_t len;
  6832. CHECK_RETURN(decode_v32(d, &len));
  6833. CHECK_SUSPEND(decoder_push(d, offset(d) + len));
  6834. set_delim_end(d);
  6835. )
  6836. VMCASE(OP_SETDELIM,
  6837. set_delim_end(d);
  6838. )
  6839. VMCASE(OP_CHECKDELIM,
  6840. // We are guaranteed of this assert because we never allow ourselves to
  6841. // consume bytes beyond data_end, which covers delim_end when non-NULL.
  6842. assert(!(d->delim_end && d->ptr > d->delim_end));
  6843. if (d->ptr == d->delim_end)
  6844. d->pc += longofs;
  6845. )
  6846. VMCASE(OP_CALL,
  6847. d->callstack[d->call_len++] = d->pc;
  6848. d->pc += longofs;
  6849. )
  6850. VMCASE(OP_RET,
  6851. assert(d->call_len > 0);
  6852. d->pc = d->callstack[--d->call_len];
  6853. )
  6854. VMCASE(OP_BRANCH,
  6855. d->pc += longofs;
  6856. )
  6857. VMCASE(OP_TAG1,
  6858. CHECK_SUSPEND(curbufleft(d) > 0);
  6859. uint8_t expected = (arg >> 8) & 0xff;
  6860. if (*d->ptr == expected) {
  6861. advance(d, 1);
  6862. } else {
  6863. int8_t shortofs;
  6864. badtag:
  6865. shortofs = arg;
  6866. if (shortofs == LABEL_DISPATCH) {
  6867. CHECK_RETURN(dispatch(d));
  6868. } else {
  6869. d->pc += shortofs;
  6870. break; // Avoid checkpoint().
  6871. }
  6872. }
  6873. )
  6874. VMCASE(OP_TAG2,
  6875. CHECK_SUSPEND(curbufleft(d) > 0);
  6876. uint16_t expected = (arg >> 8) & 0xffff;
  6877. if (curbufleft(d) >= 2) {
  6878. uint16_t actual;
  6879. memcpy(&actual, d->ptr, 2);
  6880. if (expected == actual) {
  6881. advance(d, 2);
  6882. } else {
  6883. goto badtag;
  6884. }
  6885. } else {
  6886. int32_t result = upb_pbdecoder_checktag_slow(d, expected);
  6887. if (result == DECODE_MISMATCH) goto badtag;
  6888. if (result >= 0) return result;
  6889. }
  6890. )
  6891. VMCASE(OP_TAGN, {
  6892. uint64_t expected;
  6893. memcpy(&expected, d->pc, 8);
  6894. d->pc += 2;
  6895. int32_t result = upb_pbdecoder_checktag_slow(d, expected);
  6896. if (result == DECODE_MISMATCH) goto badtag;
  6897. if (result >= 0) return result;
  6898. })
  6899. VMCASE(OP_DISPATCH, {
  6900. CHECK_RETURN(dispatch(d));
  6901. })
  6902. VMCASE(OP_HALT, {
  6903. return size;
  6904. })
  6905. }
  6906. }
  6907. }
  6908. void *upb_pbdecoder_startbc(void *closure, const void *pc, size_t size_hint) {
  6909. upb_pbdecoder *d = closure;
  6910. UPB_UNUSED(size_hint);
  6911. d->call_len = 1;
  6912. d->pc = pc;
  6913. return d;
  6914. }
  6915. void *upb_pbdecoder_startjit(void *closure, const void *hd, size_t size_hint) {
  6916. UPB_UNUSED(hd);
  6917. UPB_UNUSED(size_hint);
  6918. upb_pbdecoder *d = closure;
  6919. d->call_len = 0;
  6920. return d;
  6921. }
  6922. bool upb_pbdecoder_end(void *closure, const void *handler_data) {
  6923. upb_pbdecoder *d = closure;
  6924. const upb_pbdecodermethod *method = handler_data;
  6925. if (d->residual_end > d->residual) {
  6926. seterr(d, "Unexpected EOF");
  6927. return false;
  6928. }
  6929. if (d->top->end_ofs != UINT64_MAX) {
  6930. seterr(d, "Unexpected EOF inside delimited string");
  6931. return false;
  6932. }
  6933. // Message ends here.
  6934. uint64_t end = offset(d);
  6935. d->top->end_ofs = end;
  6936. char dummy;
  6937. #ifdef UPB_USE_JIT_X64
  6938. const mgroup *group = (const mgroup*)method->group;
  6939. if (group->jit_code) {
  6940. if (d->top != d->stack)
  6941. d->stack->end_ofs = 0;
  6942. group->jit_code(closure, method->code_base.ptr, &dummy, 0, NULL);
  6943. } else {
  6944. #endif
  6945. d->stack->end_ofs = end;
  6946. const uint32_t *p = d->pc;
  6947. // Check the previous bytecode, but guard against beginning.
  6948. if (p != method->code_base.ptr) p--;
  6949. if (getop(*p) == OP_CHECKDELIM) {
  6950. // Rewind from OP_TAG* to OP_CHECKDELIM.
  6951. assert(getop(*d->pc) == OP_TAG1 ||
  6952. getop(*d->pc) == OP_TAG2 ||
  6953. getop(*d->pc) == OP_TAGN ||
  6954. getop(*d->pc == OP_DISPATCH));
  6955. d->pc = p;
  6956. }
  6957. upb_pbdecoder_decode(closure, handler_data, &dummy, 0, NULL);
  6958. #ifdef UPB_USE_JIT_X64
  6959. }
  6960. #endif
  6961. if (d->call_len != 0) {
  6962. seterr(d, "Unexpected EOF");
  6963. return false;
  6964. }
  6965. return true;
  6966. }
  6967. void upb_pbdecoder_init(upb_pbdecoder *d, const upb_pbdecodermethod *m,
  6968. upb_status *s) {
  6969. d->limit = &d->stack[UPB_DECODER_MAX_NESTING];
  6970. upb_bytessink_reset(&d->input_, &m->input_handler_, d);
  6971. d->method_ = m;
  6972. d->callstack[0] = &halt;
  6973. d->status = s;
  6974. upb_pbdecoder_reset(d);
  6975. }
  6976. void upb_pbdecoder_reset(upb_pbdecoder *d) {
  6977. d->top = d->stack;
  6978. d->top->end_ofs = UINT64_MAX;
  6979. d->top->groupnum = 0;
  6980. d->bufstart_ofs = 0;
  6981. d->ptr = d->residual;
  6982. d->buf = d->residual;
  6983. d->end = d->residual;
  6984. d->residual_end = d->residual;
  6985. d->call_len = 1;
  6986. }
  6987. uint64_t upb_pbdecoder_bytesparsed(const upb_pbdecoder *d) {
  6988. return offset(d);
  6989. }
  6990. // Not currently required, but to support outgrowing the static stack we need
  6991. // this.
  6992. void upb_pbdecoder_uninit(upb_pbdecoder *d) {
  6993. UPB_UNUSED(d);
  6994. }
  6995. const upb_pbdecodermethod *upb_pbdecoder_method(const upb_pbdecoder *d) {
  6996. return d->method_;
  6997. }
  6998. bool upb_pbdecoder_resetoutput(upb_pbdecoder *d, upb_sink* sink) {
  6999. // TODO(haberman): do we need to test whether the decoder is already on the
  7000. // stack (like calling this from within a callback)? Should we support
  7001. // rebinding the output at all?
  7002. assert(sink);
  7003. if (d->method_->dest_handlers_) {
  7004. if (sink->handlers != d->method_->dest_handlers_)
  7005. return false;
  7006. }
  7007. upb_sink_reset(&d->top->sink, sink->handlers, sink->closure);
  7008. return true;
  7009. }
  7010. upb_bytessink *upb_pbdecoder_input(upb_pbdecoder *d) {
  7011. return &d->input_;
  7012. }
  7013. /*
  7014. * upb - a minimalist implementation of protocol buffers.
  7015. *
  7016. * Copyright (c) 2014 Google Inc. See LICENSE for details.
  7017. * Author: Josh Haberman <jhaberman@gmail.com>
  7018. *
  7019. * Since we are implementing pure handlers (ie. without any out-of-band access
  7020. * to pre-computed lengths), we have to buffer all submessages before we can
  7021. * emit even their first byte.
  7022. *
  7023. * Not knowing the size of submessages also means we can't write a perfect
  7024. * zero-copy implementation, even with buffering. Lengths are stored as
  7025. * varints, which means that we don't know how many bytes to reserve for the
  7026. * length until we know what the length is.
  7027. *
  7028. * This leaves us with three main choices:
  7029. *
  7030. * 1. buffer all submessage data in a temporary buffer, then copy it exactly
  7031. * once into the output buffer.
  7032. *
  7033. * 2. attempt to buffer data directly into the output buffer, estimating how
  7034. * many bytes each length will take. When our guesses are wrong, use
  7035. * memmove() to grow or shrink the allotted space.
  7036. *
  7037. * 3. buffer directly into the output buffer, allocating a max length
  7038. * ahead-of-time for each submessage length. If we overallocated, we waste
  7039. * space, but no memcpy() or memmove() is required. This approach requires
  7040. * defining a maximum size for submessages and rejecting submessages that
  7041. * exceed that size.
  7042. *
  7043. * (2) and (3) have the potential to have better performance, but they are more
  7044. * complicated and subtle to implement:
  7045. *
  7046. * (3) requires making an arbitrary choice of the maximum message size; it
  7047. * wastes space when submessages are shorter than this and fails
  7048. * completely when they are longer. This makes it more finicky and
  7049. * requires configuration based on the input. It also makes it impossible
  7050. * to perfectly match the output of reference encoders that always use the
  7051. * optimal amount of space for each length.
  7052. *
  7053. * (2) requires guessing the the size upfront, and if multiple lengths are
  7054. * guessed wrong the minimum required number of memmove() operations may
  7055. * be complicated to compute correctly. Implemented properly, it may have
  7056. * a useful amortized or average cost, but more investigation is required
  7057. * to determine this and what the optimal algorithm is to achieve it.
  7058. *
  7059. * (1) makes you always pay for exactly one copy, but its implementation is
  7060. * the simplest and its performance is predictable.
  7061. *
  7062. * So for now, we implement (1) only. If we wish to optimize later, we should
  7063. * be able to do it without affecting users.
  7064. *
  7065. * The strategy is to buffer the segments of data that do *not* depend on
  7066. * unknown lengths in one buffer, and keep a separate buffer of segment pointers
  7067. * and lengths. When the top-level submessage ends, we can go beginning to end,
  7068. * alternating the writing of lengths with memcpy() of the rest of the data.
  7069. * At the top level though, no buffering is required.
  7070. */
  7071. #include <stdlib.h>
  7072. /* low-level buffering ********************************************************/
  7073. // Low-level functions for interacting with the output buffer.
  7074. // TODO(haberman): handle pushback
  7075. static void putbuf(upb_pb_encoder *e, const char *buf, size_t len) {
  7076. size_t n = upb_bytessink_putbuf(e->output_, e->subc, buf, len, NULL);
  7077. UPB_ASSERT_VAR(n, n == len);
  7078. }
  7079. static upb_pb_encoder_segment *top(upb_pb_encoder *e) {
  7080. return &e->segbuf[*e->top];
  7081. }
  7082. // Call to ensure that at least "bytes" bytes are available for writing at
  7083. // e->ptr. Returns false if the bytes could not be allocated.
  7084. static bool reserve(upb_pb_encoder *e, size_t bytes) {
  7085. if ((e->limit - e->ptr) < bytes) {
  7086. size_t needed = bytes + (e->ptr - e->buf);
  7087. size_t old_size = e->limit - e->buf;
  7088. size_t new_size = old_size;
  7089. while (new_size < needed) {
  7090. new_size *= 2;
  7091. }
  7092. char *realloc_from = (e->buf == e->initbuf) ? NULL : e->buf;
  7093. char *new_buf = realloc(realloc_from, new_size);
  7094. if (new_buf == NULL) {
  7095. return false;
  7096. }
  7097. if (realloc_from == NULL) {
  7098. memcpy(new_buf, e->initbuf, old_size);
  7099. }
  7100. e->ptr = new_buf + (e->ptr - e->buf);
  7101. e->runbegin = new_buf + (e->runbegin - e->buf);
  7102. e->limit = new_buf + new_size;
  7103. e->buf = new_buf;
  7104. }
  7105. return true;
  7106. }
  7107. // Call when "bytes" bytes have been writte at e->ptr. The caller *must* have
  7108. // previously called reserve() with at least this many bytes.
  7109. static void encoder_advance(upb_pb_encoder *e, size_t bytes) {
  7110. assert((e->limit - e->ptr) >= bytes);
  7111. e->ptr += bytes;
  7112. }
  7113. // Call when all of the bytes for a handler have been written. Flushes the
  7114. // bytes if possible and necessary, returning false if this failed.
  7115. static bool commit(upb_pb_encoder *e) {
  7116. if (!e->top) {
  7117. // We aren't inside a delimited region. Flush our accumulated bytes to
  7118. // the output.
  7119. //
  7120. // TODO(haberman): in the future we may want to delay flushing for
  7121. // efficiency reasons.
  7122. putbuf(e, e->buf, e->ptr - e->buf);
  7123. e->ptr = e->buf;
  7124. }
  7125. return true;
  7126. }
  7127. // Writes the given bytes to the buffer, handling reserve/advance.
  7128. static bool encode_bytes(upb_pb_encoder *e, const void *data, size_t len) {
  7129. if (!reserve(e, len)) {
  7130. return false;
  7131. }
  7132. memcpy(e->ptr, data, len);
  7133. encoder_advance(e, len);
  7134. return true;
  7135. }
  7136. // Finish the current run by adding the run totals to the segment and message
  7137. // length.
  7138. static void accumulate(upb_pb_encoder *e) {
  7139. assert(e->ptr >= e->runbegin);
  7140. size_t run_len = e->ptr - e->runbegin;
  7141. e->segptr->seglen += run_len;
  7142. top(e)->msglen += run_len;
  7143. e->runbegin = e->ptr;
  7144. }
  7145. // Call to indicate the start of delimited region for which the full length is
  7146. // not yet known. All data will be buffered until the length is known.
  7147. // Delimited regions may be nested; their lengths will all be tracked properly.
  7148. static bool start_delim(upb_pb_encoder *e) {
  7149. if (e->top) {
  7150. // We are already buffering, advance to the next segment and push it on the
  7151. // stack.
  7152. accumulate(e);
  7153. if (++e->top == e->stacklimit) {
  7154. // TODO(haberman): grow stack?
  7155. return false;
  7156. }
  7157. if (++e->segptr == e->seglimit) {
  7158. upb_pb_encoder_segment *realloc_from =
  7159. (e->segbuf == e->seginitbuf) ? NULL : e->segbuf;
  7160. size_t old_size =
  7161. (e->seglimit - e->segbuf) * sizeof(upb_pb_encoder_segment);
  7162. size_t new_size = old_size * 2;
  7163. upb_pb_encoder_segment *new_buf = realloc(realloc_from, new_size);
  7164. if (new_buf == NULL) {
  7165. return false;
  7166. }
  7167. if (realloc_from == NULL) {
  7168. memcpy(new_buf, e->seginitbuf, old_size);
  7169. }
  7170. e->segptr = new_buf + (e->segptr - e->segbuf);
  7171. e->seglimit = new_buf + (new_size / sizeof(upb_pb_encoder_segment));
  7172. e->segbuf = new_buf;
  7173. }
  7174. } else {
  7175. // We were previously at the top level, start buffering.
  7176. e->segptr = e->segbuf;
  7177. e->top = e->stack;
  7178. e->runbegin = e->ptr;
  7179. }
  7180. *e->top = e->segptr - e->segbuf;
  7181. e->segptr->seglen = 0;
  7182. e->segptr->msglen = 0;
  7183. return true;
  7184. }
  7185. // Call to indicate the end of a delimited region. We now know the length of
  7186. // the delimited region. If we are not nested inside any other delimited
  7187. // regions, we can now emit all of the buffered data we accumulated.
  7188. static bool end_delim(upb_pb_encoder *e) {
  7189. accumulate(e);
  7190. size_t msglen = top(e)->msglen;
  7191. if (e->top == e->stack) {
  7192. // All lengths are now available, emit all buffered data.
  7193. char buf[UPB_PB_VARINT_MAX_LEN];
  7194. upb_pb_encoder_segment *s;
  7195. const char *ptr = e->buf;
  7196. for (s = e->segbuf; s <= e->segptr; s++) {
  7197. size_t lenbytes = upb_vencode64(s->msglen, buf);
  7198. putbuf(e, buf, lenbytes);
  7199. putbuf(e, ptr, s->seglen);
  7200. ptr += s->seglen;
  7201. }
  7202. e->ptr = e->buf;
  7203. e->top = NULL;
  7204. } else {
  7205. // Need to keep buffering; propagate length info into enclosing submessages.
  7206. --e->top;
  7207. top(e)->msglen += msglen + upb_varint_size(msglen);
  7208. }
  7209. return true;
  7210. }
  7211. /* tag_t **********************************************************************/
  7212. // A precomputed (pre-encoded) tag and length.
  7213. typedef struct {
  7214. uint8_t bytes;
  7215. char tag[7];
  7216. } tag_t;
  7217. // Allocates a new tag for this field, and sets it in these handlerattr.
  7218. static void new_tag(upb_handlers *h, const upb_fielddef *f, upb_wiretype_t wt,
  7219. upb_handlerattr *attr) {
  7220. uint32_t n = upb_fielddef_number(f);
  7221. tag_t *tag = malloc(sizeof(tag_t));
  7222. tag->bytes = upb_vencode64((n << 3) | wt, tag->tag);
  7223. upb_handlerattr_init(attr);
  7224. upb_handlerattr_sethandlerdata(attr, tag);
  7225. upb_handlers_addcleanup(h, tag, free);
  7226. }
  7227. static bool encode_tag(upb_pb_encoder *e, const tag_t *tag) {
  7228. return encode_bytes(e, tag->tag, tag->bytes);
  7229. }
  7230. /* encoding of wire types *****************************************************/
  7231. static bool encode_fixed64(upb_pb_encoder *e, uint64_t val) {
  7232. // TODO(haberman): byte-swap for big endian.
  7233. return encode_bytes(e, &val, sizeof(uint64_t));
  7234. }
  7235. static bool encode_fixed32(upb_pb_encoder *e, uint32_t val) {
  7236. // TODO(haberman): byte-swap for big endian.
  7237. return encode_bytes(e, &val, sizeof(uint32_t));
  7238. }
  7239. static bool encode_varint(upb_pb_encoder *e, uint64_t val) {
  7240. if (!reserve(e, UPB_PB_VARINT_MAX_LEN)) {
  7241. return false;
  7242. }
  7243. encoder_advance(e, upb_vencode64(val, e->ptr));
  7244. return true;
  7245. }
  7246. static uint64_t dbl2uint64(double d) {
  7247. uint64_t ret;
  7248. memcpy(&ret, &d, sizeof(uint64_t));
  7249. return ret;
  7250. }
  7251. static uint32_t flt2uint32(float d) {
  7252. uint32_t ret;
  7253. memcpy(&ret, &d, sizeof(uint32_t));
  7254. return ret;
  7255. }
  7256. /* encoding of proto types ****************************************************/
  7257. static bool startmsg(void *c, const void *hd) {
  7258. upb_pb_encoder *e = c;
  7259. UPB_UNUSED(hd);
  7260. if (e->depth++ == 0) {
  7261. upb_bytessink_start(e->output_, 0, &e->subc);
  7262. }
  7263. return true;
  7264. }
  7265. static bool endmsg(void *c, const void *hd, upb_status *status) {
  7266. upb_pb_encoder *e = c;
  7267. UPB_UNUSED(hd);
  7268. UPB_UNUSED(status);
  7269. if (--e->depth == 0) {
  7270. upb_bytessink_end(e->output_);
  7271. }
  7272. return true;
  7273. }
  7274. static void *encode_startdelimfield(void *c, const void *hd) {
  7275. bool ok = encode_tag(c, hd) && commit(c) && start_delim(c);
  7276. return ok ? c : UPB_BREAK;
  7277. }
  7278. static bool encode_enddelimfield(void *c, const void *hd) {
  7279. UPB_UNUSED(hd);
  7280. return end_delim(c);
  7281. }
  7282. static void *encode_startgroup(void *c, const void *hd) {
  7283. return (encode_tag(c, hd) && commit(c)) ? c : UPB_BREAK;
  7284. }
  7285. static bool encode_endgroup(void *c, const void *hd) {
  7286. return encode_tag(c, hd) && commit(c);
  7287. }
  7288. static void *encode_startstr(void *c, const void *hd, size_t size_hint) {
  7289. UPB_UNUSED(size_hint);
  7290. return encode_startdelimfield(c, hd);
  7291. }
  7292. static size_t encode_strbuf(void *c, const void *hd, const char *buf,
  7293. size_t len, const upb_bufhandle *h) {
  7294. UPB_UNUSED(hd);
  7295. UPB_UNUSED(h);
  7296. return encode_bytes(c, buf, len) ? len : 0;
  7297. }
  7298. #define T(type, ctype, convert, encode) \
  7299. static bool encode_scalar_##type(void *e, const void *hd, ctype val) { \
  7300. return encode_tag(e, hd) && encode(e, (convert)(val)) && commit(e); \
  7301. } \
  7302. static bool encode_packed_##type(void *e, const void *hd, ctype val) { \
  7303. UPB_UNUSED(hd); \
  7304. return encode(e, (convert)(val)); \
  7305. }
  7306. T(double, double, dbl2uint64, encode_fixed64)
  7307. T(float, float, flt2uint32, encode_fixed32);
  7308. T(int64, int64_t, uint64_t, encode_varint);
  7309. T(int32, int32_t, uint32_t, encode_varint);
  7310. T(fixed64, uint64_t, uint64_t, encode_fixed64);
  7311. T(fixed32, uint32_t, uint32_t, encode_fixed32);
  7312. T(bool, bool, bool, encode_varint);
  7313. T(uint32, uint32_t, uint32_t, encode_varint);
  7314. T(uint64, uint64_t, uint64_t, encode_varint);
  7315. T(enum, int32_t, uint32_t, encode_varint);
  7316. T(sfixed32, int32_t, uint32_t, encode_fixed32);
  7317. T(sfixed64, int64_t, uint64_t, encode_fixed64);
  7318. T(sint32, int32_t, upb_zzenc_32, encode_varint);
  7319. T(sint64, int64_t, upb_zzenc_64, encode_varint);
  7320. #undef T
  7321. /* code to build the handlers *************************************************/
  7322. static void newhandlers_callback(const void *closure, upb_handlers *h) {
  7323. UPB_UNUSED(closure);
  7324. upb_handlers_setstartmsg(h, startmsg, NULL);
  7325. upb_handlers_setendmsg(h, endmsg, NULL);
  7326. const upb_msgdef *m = upb_handlers_msgdef(h);
  7327. upb_msg_field_iter i;
  7328. for(upb_msg_field_begin(&i, m);
  7329. !upb_msg_field_done(&i);
  7330. upb_msg_field_next(&i)) {
  7331. const upb_fielddef *f = upb_msg_iter_field(&i);
  7332. bool packed = upb_fielddef_isseq(f) && upb_fielddef_isprimitive(f) &&
  7333. upb_fielddef_packed(f);
  7334. upb_handlerattr attr;
  7335. upb_wiretype_t wt =
  7336. packed ? UPB_WIRE_TYPE_DELIMITED
  7337. : upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  7338. // Pre-encode the tag for this field.
  7339. new_tag(h, f, wt, &attr);
  7340. if (packed) {
  7341. upb_handlers_setstartseq(h, f, encode_startdelimfield, &attr);
  7342. upb_handlers_setendseq(h, f, encode_enddelimfield, &attr);
  7343. }
  7344. #define T(upper, lower, upbtype) \
  7345. case UPB_DESCRIPTOR_TYPE_##upper: \
  7346. if (packed) { \
  7347. upb_handlers_set##upbtype(h, f, encode_packed_##lower, &attr); \
  7348. } else { \
  7349. upb_handlers_set##upbtype(h, f, encode_scalar_##lower, &attr); \
  7350. } \
  7351. break;
  7352. switch (upb_fielddef_descriptortype(f)) {
  7353. T(DOUBLE, double, double);
  7354. T(FLOAT, float, float);
  7355. T(INT64, int64, int64);
  7356. T(INT32, int32, int32);
  7357. T(FIXED64, fixed64, uint64);
  7358. T(FIXED32, fixed32, uint32);
  7359. T(BOOL, bool, bool);
  7360. T(UINT32, uint32, uint32);
  7361. T(UINT64, uint64, uint64);
  7362. T(ENUM, enum, int32);
  7363. T(SFIXED32, sfixed32, int32);
  7364. T(SFIXED64, sfixed64, int64);
  7365. T(SINT32, sint32, int32);
  7366. T(SINT64, sint64, int64);
  7367. case UPB_DESCRIPTOR_TYPE_STRING:
  7368. case UPB_DESCRIPTOR_TYPE_BYTES:
  7369. upb_handlers_setstartstr(h, f, encode_startstr, &attr);
  7370. upb_handlers_setendstr(h, f, encode_enddelimfield, &attr);
  7371. upb_handlers_setstring(h, f, encode_strbuf, &attr);
  7372. break;
  7373. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  7374. upb_handlers_setstartsubmsg(h, f, encode_startdelimfield, &attr);
  7375. upb_handlers_setendsubmsg(h, f, encode_enddelimfield, &attr);
  7376. break;
  7377. case UPB_DESCRIPTOR_TYPE_GROUP: {
  7378. // Endgroup takes a different tag (wire_type = END_GROUP).
  7379. upb_handlerattr attr2;
  7380. new_tag(h, f, UPB_WIRE_TYPE_END_GROUP, &attr2);
  7381. upb_handlers_setstartsubmsg(h, f, encode_startgroup, &attr);
  7382. upb_handlers_setendsubmsg(h, f, encode_endgroup, &attr2);
  7383. upb_handlerattr_uninit(&attr2);
  7384. break;
  7385. }
  7386. }
  7387. #undef T
  7388. upb_handlerattr_uninit(&attr);
  7389. }
  7390. }
  7391. /* public API *****************************************************************/
  7392. const upb_handlers *upb_pb_encoder_newhandlers(const upb_msgdef *m,
  7393. const void *owner) {
  7394. return upb_handlers_newfrozen(m, owner, newhandlers_callback, NULL);
  7395. }
  7396. #define ARRAYSIZE(x) (sizeof(x) / sizeof(x[0]))
  7397. void upb_pb_encoder_init(upb_pb_encoder *e, const upb_handlers *h) {
  7398. e->output_ = NULL;
  7399. e->subc = NULL;
  7400. e->buf = e->initbuf;
  7401. e->ptr = e->buf;
  7402. e->limit = e->buf + ARRAYSIZE(e->initbuf);
  7403. e->segbuf = e->seginitbuf;
  7404. e->seglimit = e->segbuf + ARRAYSIZE(e->seginitbuf);
  7405. e->stacklimit = e->stack + ARRAYSIZE(e->stack);
  7406. upb_sink_reset(&e->input_, h, e);
  7407. }
  7408. void upb_pb_encoder_uninit(upb_pb_encoder *e) {
  7409. if (e->buf != e->initbuf) {
  7410. free(e->buf);
  7411. }
  7412. if (e->segbuf != e->seginitbuf) {
  7413. free(e->segbuf);
  7414. }
  7415. }
  7416. void upb_pb_encoder_resetoutput(upb_pb_encoder *e, upb_bytessink *output) {
  7417. upb_pb_encoder_reset(e);
  7418. e->output_ = output;
  7419. e->subc = output->closure;
  7420. }
  7421. void upb_pb_encoder_reset(upb_pb_encoder *e) {
  7422. e->segptr = NULL;
  7423. e->top = NULL;
  7424. e->depth = 0;
  7425. }
  7426. upb_sink *upb_pb_encoder_input(upb_pb_encoder *e) { return &e->input_; }
  7427. /*
  7428. * upb - a minimalist implementation of protocol buffers.
  7429. *
  7430. * Copyright (c) 2010-2012 Google Inc. See LICENSE for details.
  7431. * Author: Josh Haberman <jhaberman@gmail.com>
  7432. */
  7433. #include <stdio.h>
  7434. #include <stdlib.h>
  7435. #include <string.h>
  7436. upb_def **upb_load_defs_from_descriptor(const char *str, size_t len, int *n,
  7437. void *owner, upb_status *status) {
  7438. // Create handlers.
  7439. const upb_handlers *reader_h = upb_descreader_newhandlers(&reader_h);
  7440. upb_pbdecodermethodopts opts;
  7441. upb_pbdecodermethodopts_init(&opts, reader_h);
  7442. const upb_pbdecodermethod *decoder_m =
  7443. upb_pbdecodermethod_new(&opts, &decoder_m);
  7444. upb_pbdecoder decoder;
  7445. upb_descreader reader;
  7446. upb_pbdecoder_init(&decoder, decoder_m, status);
  7447. upb_descreader_init(&reader, reader_h, status);
  7448. upb_pbdecoder_resetoutput(&decoder, upb_descreader_input(&reader));
  7449. // Push input data.
  7450. bool ok = upb_bufsrc_putbuf(str, len, upb_pbdecoder_input(&decoder));
  7451. upb_def **ret = NULL;
  7452. if (!ok) goto cleanup;
  7453. upb_def **defs = upb_descreader_getdefs(&reader, owner, n);
  7454. ret = malloc(sizeof(upb_def*) * (*n));
  7455. memcpy(ret, defs, sizeof(upb_def*) * (*n));
  7456. cleanup:
  7457. upb_pbdecoder_uninit(&decoder);
  7458. upb_descreader_uninit(&reader);
  7459. upb_handlers_unref(reader_h, &reader_h);
  7460. upb_pbdecodermethod_unref(decoder_m, &decoder_m);
  7461. return ret;
  7462. }
  7463. bool upb_load_descriptor_into_symtab(upb_symtab *s, const char *str, size_t len,
  7464. upb_status *status) {
  7465. int n;
  7466. upb_def **defs = upb_load_defs_from_descriptor(str, len, &n, &defs, status);
  7467. if (!defs) return false;
  7468. bool success = upb_symtab_add(s, defs, n, &defs, status);
  7469. free(defs);
  7470. return success;
  7471. }
  7472. char *upb_readfile(const char *filename, size_t *len) {
  7473. FILE *f = fopen(filename, "rb");
  7474. if(!f) return NULL;
  7475. if(fseek(f, 0, SEEK_END) != 0) goto error;
  7476. long size = ftell(f);
  7477. if(size < 0) goto error;
  7478. if(fseek(f, 0, SEEK_SET) != 0) goto error;
  7479. char *buf = malloc(size + 1);
  7480. if(size && fread(buf, size, 1, f) != 1) goto error;
  7481. fclose(f);
  7482. if (len) *len = size;
  7483. return buf;
  7484. error:
  7485. fclose(f);
  7486. return NULL;
  7487. }
  7488. bool upb_load_descriptor_file_into_symtab(upb_symtab *symtab, const char *fname,
  7489. upb_status *status) {
  7490. size_t len;
  7491. char *data = upb_readfile(fname, &len);
  7492. if (!data) {
  7493. if (status) upb_status_seterrf(status, "Couldn't read file: %s", fname);
  7494. return false;
  7495. }
  7496. bool success = upb_load_descriptor_into_symtab(symtab, data, len, status);
  7497. free(data);
  7498. return success;
  7499. }
  7500. /*
  7501. * upb - a minimalist implementation of protocol buffers.
  7502. *
  7503. * Copyright (c) 2009 Google Inc. See LICENSE for details.
  7504. * Author: Josh Haberman <jhaberman@gmail.com>
  7505. *
  7506. * OPT: This is not optimized at all. It uses printf() which parses the format
  7507. * string every time, and it allocates memory for every put.
  7508. */
  7509. #include <ctype.h>
  7510. #include <float.h>
  7511. #include <inttypes.h>
  7512. #include <stdio.h>
  7513. #include <stdlib.h>
  7514. #include <string.h>
  7515. #define CHECK(x) if ((x) < 0) goto err;
  7516. static const char *shortname(const char *longname) {
  7517. const char *last = strrchr(longname, '.');
  7518. return last ? last + 1 : longname;
  7519. }
  7520. static int indent(upb_textprinter *p) {
  7521. int i;
  7522. if (!p->single_line_)
  7523. for (i = 0; i < p->indent_depth_; i++)
  7524. upb_bytessink_putbuf(p->output_, p->subc, " ", 2, NULL);
  7525. return 0;
  7526. }
  7527. static int endfield(upb_textprinter *p) {
  7528. const char ch = (p->single_line_ ? ' ' : '\n');
  7529. upb_bytessink_putbuf(p->output_, p->subc, &ch, 1, NULL);
  7530. return 0;
  7531. }
  7532. static int putescaped(upb_textprinter *p, const char *buf, size_t len,
  7533. bool preserve_utf8) {
  7534. // Based on CEscapeInternal() from Google's protobuf release.
  7535. char dstbuf[4096], *dst = dstbuf, *dstend = dstbuf + sizeof(dstbuf);
  7536. const char *end = buf + len;
  7537. // I think hex is prettier and more useful, but proto2 uses octal; should
  7538. // investigate whether it can parse hex also.
  7539. const bool use_hex = false;
  7540. bool last_hex_escape = false; // true if last output char was \xNN
  7541. for (; buf < end; buf++) {
  7542. if (dstend - dst < 4) {
  7543. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  7544. dst = dstbuf;
  7545. }
  7546. bool is_hex_escape = false;
  7547. switch (*buf) {
  7548. case '\n': *(dst++) = '\\'; *(dst++) = 'n'; break;
  7549. case '\r': *(dst++) = '\\'; *(dst++) = 'r'; break;
  7550. case '\t': *(dst++) = '\\'; *(dst++) = 't'; break;
  7551. case '\"': *(dst++) = '\\'; *(dst++) = '\"'; break;
  7552. case '\'': *(dst++) = '\\'; *(dst++) = '\''; break;
  7553. case '\\': *(dst++) = '\\'; *(dst++) = '\\'; break;
  7554. default:
  7555. // Note that if we emit \xNN and the buf character after that is a hex
  7556. // digit then that digit must be escaped too to prevent it being
  7557. // interpreted as part of the character code by C.
  7558. if ((!preserve_utf8 || (uint8_t)*buf < 0x80) &&
  7559. (!isprint(*buf) || (last_hex_escape && isxdigit(*buf)))) {
  7560. sprintf(dst, (use_hex ? "\\x%02x" : "\\%03o"), (uint8_t)*buf);
  7561. is_hex_escape = use_hex;
  7562. dst += 4;
  7563. } else {
  7564. *(dst++) = *buf; break;
  7565. }
  7566. }
  7567. last_hex_escape = is_hex_escape;
  7568. }
  7569. // Flush remaining data.
  7570. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  7571. return 0;
  7572. }
  7573. bool putf(upb_textprinter *p, const char *fmt, ...) {
  7574. va_list args;
  7575. va_start(args, fmt);
  7576. // Run once to get the length of the string.
  7577. va_list args_copy;
  7578. va_copy(args_copy, args);
  7579. int len = vsnprintf(NULL, 0, fmt, args_copy);
  7580. va_end(args_copy);
  7581. // + 1 for NULL terminator (vsnprintf() requires it even if we don't).
  7582. char *str = malloc(len + 1);
  7583. if (!str) return false;
  7584. int written = vsnprintf(str, len + 1, fmt, args);
  7585. va_end(args);
  7586. UPB_ASSERT_VAR(written, written == len);
  7587. bool ok = upb_bytessink_putbuf(p->output_, p->subc, str, len, NULL);
  7588. free(str);
  7589. return ok;
  7590. }
  7591. /* handlers *******************************************************************/
  7592. static bool textprinter_startmsg(void *c, const void *hd) {
  7593. UPB_UNUSED(hd);
  7594. upb_textprinter *p = c;
  7595. if (p->indent_depth_ == 0) {
  7596. upb_bytessink_start(p->output_, 0, &p->subc);
  7597. }
  7598. return true;
  7599. }
  7600. static bool textprinter_endmsg(void *c, const void *hd, upb_status *s) {
  7601. UPB_UNUSED(hd);
  7602. UPB_UNUSED(s);
  7603. upb_textprinter *p = c;
  7604. if (p->indent_depth_ == 0) {
  7605. upb_bytessink_end(p->output_);
  7606. }
  7607. return true;
  7608. }
  7609. #define TYPE(name, ctype, fmt) \
  7610. static bool textprinter_put ## name(void *closure, const void *handler_data, \
  7611. ctype val) { \
  7612. upb_textprinter *p = closure; \
  7613. const upb_fielddef *f = handler_data; \
  7614. CHECK(indent(p)); \
  7615. putf(p, "%s: " fmt, upb_fielddef_name(f), val); \
  7616. CHECK(endfield(p)); \
  7617. return true; \
  7618. err: \
  7619. return false; \
  7620. }
  7621. static bool textprinter_putbool(void *closure, const void *handler_data,
  7622. bool val) {
  7623. upb_textprinter *p = closure;
  7624. const upb_fielddef *f = handler_data;
  7625. CHECK(indent(p));
  7626. putf(p, "%s: %s", upb_fielddef_name(f), val ? "true" : "false");
  7627. CHECK(endfield(p));
  7628. return true;
  7629. err:
  7630. return false;
  7631. }
  7632. #define STRINGIFY_HELPER(x) #x
  7633. #define STRINGIFY_MACROVAL(x) STRINGIFY_HELPER(x)
  7634. TYPE(int32, int32_t, "%" PRId32)
  7635. TYPE(int64, int64_t, "%" PRId64)
  7636. TYPE(uint32, uint32_t, "%" PRIu32);
  7637. TYPE(uint64, uint64_t, "%" PRIu64)
  7638. TYPE(float, float, "%." STRINGIFY_MACROVAL(FLT_DIG) "g")
  7639. TYPE(double, double, "%." STRINGIFY_MACROVAL(DBL_DIG) "g")
  7640. #undef TYPE
  7641. // Output a symbolic value from the enum if found, else just print as int32.
  7642. static bool textprinter_putenum(void *closure, const void *handler_data,
  7643. int32_t val) {
  7644. upb_textprinter *p = closure;
  7645. const upb_fielddef *f = handler_data;
  7646. const upb_enumdef *enum_def = upb_downcast_enumdef(upb_fielddef_subdef(f));
  7647. const char *label = upb_enumdef_iton(enum_def, val);
  7648. if (label) {
  7649. indent(p);
  7650. putf(p, "%s: %s", upb_fielddef_name(f), label);
  7651. endfield(p);
  7652. } else {
  7653. if (!textprinter_putint32(closure, handler_data, val))
  7654. return false;
  7655. }
  7656. return true;
  7657. }
  7658. static void *textprinter_startstr(void *closure, const void *handler_data,
  7659. size_t size_hint) {
  7660. const upb_fielddef *f = handler_data;
  7661. UPB_UNUSED(size_hint);
  7662. upb_textprinter *p = closure;
  7663. indent(p);
  7664. putf(p, "%s: \"", upb_fielddef_name(f));
  7665. return p;
  7666. }
  7667. static bool textprinter_endstr(void *closure, const void *handler_data) {
  7668. UPB_UNUSED(handler_data);
  7669. upb_textprinter *p = closure;
  7670. putf(p, "\"");
  7671. endfield(p);
  7672. return true;
  7673. }
  7674. static size_t textprinter_putstr(void *closure, const void *hd, const char *buf,
  7675. size_t len, const upb_bufhandle *handle) {
  7676. UPB_UNUSED(handle);
  7677. upb_textprinter *p = closure;
  7678. const upb_fielddef *f = hd;
  7679. CHECK(putescaped(p, buf, len, upb_fielddef_type(f) == UPB_TYPE_STRING));
  7680. return len;
  7681. err:
  7682. return 0;
  7683. }
  7684. static void *textprinter_startsubmsg(void *closure, const void *handler_data) {
  7685. upb_textprinter *p = closure;
  7686. const char *name = handler_data;
  7687. CHECK(indent(p));
  7688. putf(p, "%s {%c", name, p->single_line_ ? ' ' : '\n');
  7689. p->indent_depth_++;
  7690. return p;
  7691. err:
  7692. return UPB_BREAK;
  7693. }
  7694. static bool textprinter_endsubmsg(void *closure, const void *handler_data) {
  7695. UPB_UNUSED(handler_data);
  7696. upb_textprinter *p = closure;
  7697. p->indent_depth_--;
  7698. CHECK(indent(p));
  7699. upb_bytessink_putbuf(p->output_, p->subc, "}", 1, NULL);
  7700. CHECK(endfield(p));
  7701. return true;
  7702. err:
  7703. return false;
  7704. }
  7705. /* Public API *****************************************************************/
  7706. void upb_textprinter_init(upb_textprinter *p, const upb_handlers *h) {
  7707. p->single_line_ = false;
  7708. p->indent_depth_ = 0;
  7709. upb_sink_reset(&p->input_, h, p);
  7710. }
  7711. void upb_textprinter_uninit(upb_textprinter *p) {
  7712. UPB_UNUSED(p);
  7713. }
  7714. void upb_textprinter_reset(upb_textprinter *p, bool single_line) {
  7715. p->single_line_ = single_line;
  7716. p->indent_depth_ = 0;
  7717. }
  7718. static void onmreg(const void *c, upb_handlers *h) {
  7719. UPB_UNUSED(c);
  7720. const upb_msgdef *m = upb_handlers_msgdef(h);
  7721. upb_handlers_setstartmsg(h, textprinter_startmsg, NULL);
  7722. upb_handlers_setendmsg(h, textprinter_endmsg, NULL);
  7723. upb_msg_field_iter i;
  7724. for(upb_msg_field_begin(&i, m);
  7725. !upb_msg_field_done(&i);
  7726. upb_msg_field_next(&i)) {
  7727. upb_fielddef *f = upb_msg_iter_field(&i);
  7728. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  7729. upb_handlerattr_sethandlerdata(&attr, f);
  7730. switch (upb_fielddef_type(f)) {
  7731. case UPB_TYPE_INT32:
  7732. upb_handlers_setint32(h, f, textprinter_putint32, &attr);
  7733. break;
  7734. case UPB_TYPE_INT64:
  7735. upb_handlers_setint64(h, f, textprinter_putint64, &attr);
  7736. break;
  7737. case UPB_TYPE_UINT32:
  7738. upb_handlers_setuint32(h, f, textprinter_putuint32, &attr);
  7739. break;
  7740. case UPB_TYPE_UINT64:
  7741. upb_handlers_setuint64(h, f, textprinter_putuint64, &attr);
  7742. break;
  7743. case UPB_TYPE_FLOAT:
  7744. upb_handlers_setfloat(h, f, textprinter_putfloat, &attr);
  7745. break;
  7746. case UPB_TYPE_DOUBLE:
  7747. upb_handlers_setdouble(h, f, textprinter_putdouble, &attr);
  7748. break;
  7749. case UPB_TYPE_BOOL:
  7750. upb_handlers_setbool(h, f, textprinter_putbool, &attr);
  7751. break;
  7752. case UPB_TYPE_STRING:
  7753. case UPB_TYPE_BYTES:
  7754. upb_handlers_setstartstr(h, f, textprinter_startstr, &attr);
  7755. upb_handlers_setstring(h, f, textprinter_putstr, &attr);
  7756. upb_handlers_setendstr(h, f, textprinter_endstr, &attr);
  7757. break;
  7758. case UPB_TYPE_MESSAGE: {
  7759. const char *name =
  7760. upb_fielddef_istagdelim(f)
  7761. ? shortname(upb_msgdef_fullname(upb_fielddef_msgsubdef(f)))
  7762. : upb_fielddef_name(f);
  7763. upb_handlerattr_sethandlerdata(&attr, name);
  7764. upb_handlers_setstartsubmsg(h, f, textprinter_startsubmsg, &attr);
  7765. upb_handlers_setendsubmsg(h, f, textprinter_endsubmsg, &attr);
  7766. break;
  7767. }
  7768. case UPB_TYPE_ENUM:
  7769. upb_handlers_setint32(h, f, textprinter_putenum, &attr);
  7770. break;
  7771. }
  7772. }
  7773. }
  7774. const upb_handlers *upb_textprinter_newhandlers(const upb_msgdef *m,
  7775. const void *owner) {
  7776. return upb_handlers_newfrozen(m, owner, &onmreg, NULL);
  7777. }
  7778. upb_sink *upb_textprinter_input(upb_textprinter *p) { return &p->input_; }
  7779. bool upb_textprinter_resetoutput(upb_textprinter *p, upb_bytessink *output) {
  7780. p->output_ = output;
  7781. return true;
  7782. }
  7783. void upb_textprinter_setsingleline(upb_textprinter *p, bool single_line) {
  7784. p->single_line_ = single_line;
  7785. }
  7786. /*
  7787. * upb - a minimalist implementation of protocol buffers.
  7788. *
  7789. * Copyright (c) 2011 Google Inc. See LICENSE for details.
  7790. * Author: Josh Haberman <jhaberman@gmail.com>
  7791. */
  7792. // Index is descriptor type.
  7793. const uint8_t upb_pb_native_wire_types[] = {
  7794. UPB_WIRE_TYPE_END_GROUP, // ENDGROUP
  7795. UPB_WIRE_TYPE_64BIT, // DOUBLE
  7796. UPB_WIRE_TYPE_32BIT, // FLOAT
  7797. UPB_WIRE_TYPE_VARINT, // INT64
  7798. UPB_WIRE_TYPE_VARINT, // UINT64
  7799. UPB_WIRE_TYPE_VARINT, // INT32
  7800. UPB_WIRE_TYPE_64BIT, // FIXED64
  7801. UPB_WIRE_TYPE_32BIT, // FIXED32
  7802. UPB_WIRE_TYPE_VARINT, // BOOL
  7803. UPB_WIRE_TYPE_DELIMITED, // STRING
  7804. UPB_WIRE_TYPE_START_GROUP, // GROUP
  7805. UPB_WIRE_TYPE_DELIMITED, // MESSAGE
  7806. UPB_WIRE_TYPE_DELIMITED, // BYTES
  7807. UPB_WIRE_TYPE_VARINT, // UINT32
  7808. UPB_WIRE_TYPE_VARINT, // ENUM
  7809. UPB_WIRE_TYPE_32BIT, // SFIXED32
  7810. UPB_WIRE_TYPE_64BIT, // SFIXED64
  7811. UPB_WIRE_TYPE_VARINT, // SINT32
  7812. UPB_WIRE_TYPE_VARINT, // SINT64
  7813. };
  7814. // A basic branch-based decoder, uses 32-bit values to get good performance
  7815. // on 32-bit architectures (but performs well on 64-bits also).
  7816. // This scheme comes from the original Google Protobuf implementation (proto2).
  7817. upb_decoderet upb_vdecode_max8_branch32(upb_decoderet r) {
  7818. upb_decoderet err = {NULL, 0};
  7819. const char *p = r.p;
  7820. uint32_t low = (uint32_t)r.val;
  7821. uint32_t high = 0;
  7822. uint32_t b;
  7823. b = *(p++); low |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  7824. b = *(p++); low |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  7825. b = *(p++); low |= (b & 0x7fU) << 28;
  7826. high = (b & 0x7fU) >> 4; if (!(b & 0x80)) goto done;
  7827. b = *(p++); high |= (b & 0x7fU) << 3; if (!(b & 0x80)) goto done;
  7828. b = *(p++); high |= (b & 0x7fU) << 10; if (!(b & 0x80)) goto done;
  7829. b = *(p++); high |= (b & 0x7fU) << 17; if (!(b & 0x80)) goto done;
  7830. b = *(p++); high |= (b & 0x7fU) << 24; if (!(b & 0x80)) goto done;
  7831. b = *(p++); high |= (b & 0x7fU) << 31; if (!(b & 0x80)) goto done;
  7832. return err;
  7833. done:
  7834. r.val = ((uint64_t)high << 32) | low;
  7835. r.p = p;
  7836. return r;
  7837. }
  7838. // Like the previous, but uses 64-bit values.
  7839. upb_decoderet upb_vdecode_max8_branch64(upb_decoderet r) {
  7840. const char *p = r.p;
  7841. uint64_t val = r.val;
  7842. uint64_t b;
  7843. upb_decoderet err = {NULL, 0};
  7844. b = *(p++); val |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  7845. b = *(p++); val |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  7846. b = *(p++); val |= (b & 0x7fU) << 28; if (!(b & 0x80)) goto done;
  7847. b = *(p++); val |= (b & 0x7fU) << 35; if (!(b & 0x80)) goto done;
  7848. b = *(p++); val |= (b & 0x7fU) << 42; if (!(b & 0x80)) goto done;
  7849. b = *(p++); val |= (b & 0x7fU) << 49; if (!(b & 0x80)) goto done;
  7850. b = *(p++); val |= (b & 0x7fU) << 56; if (!(b & 0x80)) goto done;
  7851. b = *(p++); val |= (b & 0x7fU) << 63; if (!(b & 0x80)) goto done;
  7852. return err;
  7853. done:
  7854. r.val = val;
  7855. r.p = p;
  7856. return r;
  7857. }
  7858. // Given an encoded varint v, returns an integer with a single bit set that
  7859. // indicates the end of the varint. Subtracting one from this value will
  7860. // yield a mask that leaves only bits that are part of the varint. Returns
  7861. // 0 if the varint is unterminated.
  7862. static uint64_t upb_get_vstopbit(uint64_t v) {
  7863. uint64_t cbits = v | 0x7f7f7f7f7f7f7f7fULL;
  7864. return ~cbits & (cbits+1);
  7865. }
  7866. // A branchless decoder. Credit to Pascal Massimino for the bit-twiddling.
  7867. upb_decoderet upb_vdecode_max8_massimino(upb_decoderet r) {
  7868. uint64_t b;
  7869. memcpy(&b, r.p, sizeof(b));
  7870. uint64_t stop_bit = upb_get_vstopbit(b);
  7871. b = (b & 0x7f7f7f7f7f7f7f7fULL) & (stop_bit - 1);
  7872. b += b & 0x007f007f007f007fULL;
  7873. b += 3 * (b & 0x0000ffff0000ffffULL);
  7874. b += 15 * (b & 0x00000000ffffffffULL);
  7875. if (stop_bit == 0) {
  7876. // Error: unterminated varint.
  7877. upb_decoderet err_r = {(void*)0, 0};
  7878. return err_r;
  7879. }
  7880. upb_decoderet my_r = {r.p + ((__builtin_ctzll(stop_bit) + 1) / 8),
  7881. r.val | (b << 7)};
  7882. return my_r;
  7883. }
  7884. // A branchless decoder. Credit to Daniel Wright for the bit-twiddling.
  7885. upb_decoderet upb_vdecode_max8_wright(upb_decoderet r) {
  7886. uint64_t b;
  7887. memcpy(&b, r.p, sizeof(b));
  7888. uint64_t stop_bit = upb_get_vstopbit(b);
  7889. b &= (stop_bit - 1);
  7890. b = ((b & 0x7f007f007f007f00ULL) >> 1) | (b & 0x007f007f007f007fULL);
  7891. b = ((b & 0xffff0000ffff0000ULL) >> 2) | (b & 0x0000ffff0000ffffULL);
  7892. b = ((b & 0xffffffff00000000ULL) >> 4) | (b & 0x00000000ffffffffULL);
  7893. if (stop_bit == 0) {
  7894. // Error: unterminated varint.
  7895. upb_decoderet err_r = {(void*)0, 0};
  7896. return err_r;
  7897. }
  7898. upb_decoderet my_r = {r.p + ((__builtin_ctzll(stop_bit) + 1) / 8),
  7899. r.val | (b << 14)};
  7900. return my_r;
  7901. }
  7902. #line 1 "upb/json/parser.rl"
  7903. /*
  7904. * upb - a minimalist implementation of protocol buffers.
  7905. *
  7906. * Copyright (c) 2014 Google Inc. See LICENSE for details.
  7907. * Author: Josh Haberman <jhaberman@gmail.com>
  7908. *
  7909. * A parser that uses the Ragel State Machine Compiler to generate
  7910. * the finite automata.
  7911. *
  7912. * Ragel only natively handles regular languages, but we can manually
  7913. * program it a bit to handle context-free languages like JSON, by using
  7914. * the "fcall" and "fret" constructs.
  7915. *
  7916. * This parser can handle the basics, but needs several things to be fleshed
  7917. * out:
  7918. *
  7919. * - handling of unicode escape sequences (including high surrogate pairs).
  7920. * - properly check and report errors for unknown fields, stack overflow,
  7921. * improper array nesting (or lack of nesting).
  7922. * - handling of base64 sequences with padding characters.
  7923. * - handling of push-back (non-success returns from sink functions).
  7924. * - handling of keys/escape-sequences/etc that span input buffers.
  7925. */
  7926. #include <stdio.h>
  7927. #include <stdint.h>
  7928. #include <assert.h>
  7929. #include <string.h>
  7930. #include <stdlib.h>
  7931. #include <errno.h>
  7932. #define PARSER_CHECK_RETURN(x) if (!(x)) return false
  7933. // Used to signal that a capture has been suspended.
  7934. static char suspend_capture;
  7935. static upb_selector_t getsel_for_handlertype(upb_json_parser *p,
  7936. upb_handlertype_t type) {
  7937. upb_selector_t sel;
  7938. bool ok = upb_handlers_getselector(p->top->f, type, &sel);
  7939. UPB_ASSERT_VAR(ok, ok);
  7940. return sel;
  7941. }
  7942. static upb_selector_t parser_getsel(upb_json_parser *p) {
  7943. return getsel_for_handlertype(
  7944. p, upb_handlers_getprimitivehandlertype(p->top->f));
  7945. }
  7946. static bool check_stack(upb_json_parser *p) {
  7947. if ((p->top + 1) == p->limit) {
  7948. upb_status_seterrmsg(p->status, "Nesting too deep");
  7949. return false;
  7950. }
  7951. return true;
  7952. }
  7953. // There are GCC/Clang built-ins for overflow checking which we could start
  7954. // using if there was any performance benefit to it.
  7955. static bool checked_add(size_t a, size_t b, size_t *c) {
  7956. if (SIZE_MAX - a < b) return false;
  7957. *c = a + b;
  7958. return true;
  7959. }
  7960. static size_t saturating_multiply(size_t a, size_t b) {
  7961. // size_t is unsigned, so this is defined behavior even on overflow.
  7962. size_t ret = a * b;
  7963. if (b != 0 && ret / b != a) {
  7964. ret = SIZE_MAX;
  7965. }
  7966. return ret;
  7967. }
  7968. /* Base64 decoding ************************************************************/
  7969. // TODO(haberman): make this streaming.
  7970. static const signed char b64table[] = {
  7971. -1, -1, -1, -1, -1, -1, -1, -1,
  7972. -1, -1, -1, -1, -1, -1, -1, -1,
  7973. -1, -1, -1, -1, -1, -1, -1, -1,
  7974. -1, -1, -1, -1, -1, -1, -1, -1,
  7975. -1, -1, -1, -1, -1, -1, -1, -1,
  7976. -1, -1, -1, 62/*+*/, -1, -1, -1, 63/*/ */,
  7977. 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
  7978. 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1,
  7979. -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
  7980. 07/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
  7981. 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
  7982. 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, -1,
  7983. -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
  7984. 33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
  7985. 41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
  7986. 49/*x*/, 50/*y*/, 51/*z*/, -1, -1, -1, -1, -1,
  7987. -1, -1, -1, -1, -1, -1, -1, -1,
  7988. -1, -1, -1, -1, -1, -1, -1, -1,
  7989. -1, -1, -1, -1, -1, -1, -1, -1,
  7990. -1, -1, -1, -1, -1, -1, -1, -1,
  7991. -1, -1, -1, -1, -1, -1, -1, -1,
  7992. -1, -1, -1, -1, -1, -1, -1, -1,
  7993. -1, -1, -1, -1, -1, -1, -1, -1,
  7994. -1, -1, -1, -1, -1, -1, -1, -1,
  7995. -1, -1, -1, -1, -1, -1, -1, -1,
  7996. -1, -1, -1, -1, -1, -1, -1, -1,
  7997. -1, -1, -1, -1, -1, -1, -1, -1,
  7998. -1, -1, -1, -1, -1, -1, -1, -1,
  7999. -1, -1, -1, -1, -1, -1, -1, -1,
  8000. -1, -1, -1, -1, -1, -1, -1, -1,
  8001. -1, -1, -1, -1, -1, -1, -1, -1,
  8002. -1, -1, -1, -1, -1, -1, -1, -1
  8003. };
  8004. // Returns the table value sign-extended to 32 bits. Knowing that the upper
  8005. // bits will be 1 for unrecognized characters makes it easier to check for
  8006. // this error condition later (see below).
  8007. int32_t b64lookup(unsigned char ch) { return b64table[ch]; }
  8008. // Returns true if the given character is not a valid base64 character or
  8009. // padding.
  8010. bool nonbase64(unsigned char ch) { return b64lookup(ch) == -1 && ch != '='; }
  8011. static bool base64_push(upb_json_parser *p, upb_selector_t sel, const char *ptr,
  8012. size_t len) {
  8013. const char *limit = ptr + len;
  8014. for (; ptr < limit; ptr += 4) {
  8015. if (limit - ptr < 4) {
  8016. upb_status_seterrf(p->status,
  8017. "Base64 input for bytes field not a multiple of 4: %s",
  8018. upb_fielddef_name(p->top->f));
  8019. return false;
  8020. }
  8021. uint32_t val = b64lookup(ptr[0]) << 18 |
  8022. b64lookup(ptr[1]) << 12 |
  8023. b64lookup(ptr[2]) << 6 |
  8024. b64lookup(ptr[3]);
  8025. // Test the upper bit; returns true if any of the characters returned -1.
  8026. if (val & 0x80000000) {
  8027. goto otherchar;
  8028. }
  8029. char output[3];
  8030. output[0] = val >> 16;
  8031. output[1] = (val >> 8) & 0xff;
  8032. output[2] = val & 0xff;
  8033. upb_sink_putstring(&p->top->sink, sel, output, 3, NULL);
  8034. }
  8035. return true;
  8036. otherchar:
  8037. if (nonbase64(ptr[0]) || nonbase64(ptr[1]) || nonbase64(ptr[2]) ||
  8038. nonbase64(ptr[3]) ) {
  8039. upb_status_seterrf(p->status,
  8040. "Non-base64 characters in bytes field: %s",
  8041. upb_fielddef_name(p->top->f));
  8042. return false;
  8043. } if (ptr[2] == '=') {
  8044. // Last group contains only two input bytes, one output byte.
  8045. if (ptr[0] == '=' || ptr[1] == '=' || ptr[3] != '=') {
  8046. goto badpadding;
  8047. }
  8048. uint32_t val = b64lookup(ptr[0]) << 18 |
  8049. b64lookup(ptr[1]) << 12;
  8050. assert(!(val & 0x80000000));
  8051. char output = val >> 16;
  8052. upb_sink_putstring(&p->top->sink, sel, &output, 1, NULL);
  8053. return true;
  8054. } else {
  8055. // Last group contains only three input bytes, two output bytes.
  8056. if (ptr[0] == '=' || ptr[1] == '=' || ptr[2] == '=') {
  8057. goto badpadding;
  8058. }
  8059. uint32_t val = b64lookup(ptr[0]) << 18 |
  8060. b64lookup(ptr[1]) << 12 |
  8061. b64lookup(ptr[2]) << 6;
  8062. char output[2];
  8063. output[0] = val >> 16;
  8064. output[1] = (val >> 8) & 0xff;
  8065. upb_sink_putstring(&p->top->sink, sel, output, 2, NULL);
  8066. return true;
  8067. }
  8068. badpadding:
  8069. upb_status_seterrf(p->status,
  8070. "Incorrect base64 padding for field: %s (%.*s)",
  8071. upb_fielddef_name(p->top->f),
  8072. 4, ptr);
  8073. return false;
  8074. }
  8075. /* Accumulate buffer **********************************************************/
  8076. // Functionality for accumulating a buffer.
  8077. //
  8078. // Some parts of the parser need an entire value as a contiguous string. For
  8079. // example, to look up a member name in a hash table, or to turn a string into
  8080. // a number, the relevant library routines need the input string to be in
  8081. // contiguous memory, even if the value spanned two or more buffers in the
  8082. // input. These routines handle that.
  8083. //
  8084. // In the common case we can just point to the input buffer to get this
  8085. // contiguous string and avoid any actual copy. So we optimistically begin
  8086. // this way. But there are a few cases where we must instead copy into a
  8087. // separate buffer:
  8088. //
  8089. // 1. The string was not contiguous in the input (it spanned buffers).
  8090. //
  8091. // 2. The string included escape sequences that need to be interpreted to get
  8092. // the true value in a contiguous buffer.
  8093. static void assert_accumulate_empty(upb_json_parser *p) {
  8094. UPB_UNUSED(p);
  8095. assert(p->accumulated == NULL);
  8096. assert(p->accumulated_len == 0);
  8097. }
  8098. static void accumulate_clear(upb_json_parser *p) {
  8099. p->accumulated = NULL;
  8100. p->accumulated_len = 0;
  8101. }
  8102. // Used internally by accumulate_append().
  8103. static bool accumulate_realloc(upb_json_parser *p, size_t need) {
  8104. size_t new_size = UPB_MAX(p->accumulate_buf_size, 128);
  8105. while (new_size < need) {
  8106. new_size = saturating_multiply(new_size, 2);
  8107. }
  8108. void *mem = realloc(p->accumulate_buf, new_size);
  8109. if (!mem) {
  8110. upb_status_seterrmsg(p->status, "Out of memory allocating buffer.");
  8111. return false;
  8112. }
  8113. p->accumulate_buf = mem;
  8114. p->accumulate_buf_size = new_size;
  8115. return true;
  8116. }
  8117. // Logically appends the given data to the append buffer.
  8118. // If "can_alias" is true, we will try to avoid actually copying, but the buffer
  8119. // must be valid until the next accumulate_append() call (if any).
  8120. static bool accumulate_append(upb_json_parser *p, const char *buf, size_t len,
  8121. bool can_alias) {
  8122. if (!p->accumulated && can_alias) {
  8123. p->accumulated = buf;
  8124. p->accumulated_len = len;
  8125. return true;
  8126. }
  8127. size_t need;
  8128. if (!checked_add(p->accumulated_len, len, &need)) {
  8129. upb_status_seterrmsg(p->status, "Integer overflow.");
  8130. return false;
  8131. }
  8132. if (need > p->accumulate_buf_size && !accumulate_realloc(p, need)) {
  8133. return false;
  8134. }
  8135. if (p->accumulated != p->accumulate_buf) {
  8136. memcpy(p->accumulate_buf, p->accumulated, p->accumulated_len);
  8137. p->accumulated = p->accumulate_buf;
  8138. }
  8139. memcpy(p->accumulate_buf + p->accumulated_len, buf, len);
  8140. p->accumulated_len += len;
  8141. return true;
  8142. }
  8143. // Returns a pointer to the data accumulated since the last accumulate_clear()
  8144. // call, and writes the length to *len. This with point either to the input
  8145. // buffer or a temporary accumulate buffer.
  8146. static const char *accumulate_getptr(upb_json_parser *p, size_t *len) {
  8147. assert(p->accumulated);
  8148. *len = p->accumulated_len;
  8149. return p->accumulated;
  8150. }
  8151. /* Mult-part text data ********************************************************/
  8152. // When we have text data in the input, it can often come in multiple segments.
  8153. // For example, there may be some raw string data followed by an escape
  8154. // sequence. The two segments are processed with different logic. Also buffer
  8155. // seams in the input can cause multiple segments.
  8156. //
  8157. // As we see segments, there are two main cases for how we want to process them:
  8158. //
  8159. // 1. we want to push the captured input directly to string handlers.
  8160. //
  8161. // 2. we need to accumulate all the parts into a contiguous buffer for further
  8162. // processing (field name lookup, string->number conversion, etc).
  8163. // This is the set of states for p->multipart_state.
  8164. enum {
  8165. // We are not currently processing multipart data.
  8166. MULTIPART_INACTIVE = 0,
  8167. // We are processing multipart data by accumulating it into a contiguous
  8168. // buffer.
  8169. MULTIPART_ACCUMULATE = 1,
  8170. // We are processing multipart data by pushing each part directly to the
  8171. // current string handlers.
  8172. MULTIPART_PUSHEAGERLY = 2
  8173. };
  8174. // Start a multi-part text value where we accumulate the data for processing at
  8175. // the end.
  8176. static void multipart_startaccum(upb_json_parser *p) {
  8177. assert_accumulate_empty(p);
  8178. assert(p->multipart_state == MULTIPART_INACTIVE);
  8179. p->multipart_state = MULTIPART_ACCUMULATE;
  8180. }
  8181. // Start a multi-part text value where we immediately push text data to a string
  8182. // value with the given selector.
  8183. static void multipart_start(upb_json_parser *p, upb_selector_t sel) {
  8184. assert_accumulate_empty(p);
  8185. assert(p->multipart_state == MULTIPART_INACTIVE);
  8186. p->multipart_state = MULTIPART_PUSHEAGERLY;
  8187. p->string_selector = sel;
  8188. }
  8189. static bool multipart_text(upb_json_parser *p, const char *buf, size_t len,
  8190. bool can_alias) {
  8191. switch (p->multipart_state) {
  8192. case MULTIPART_INACTIVE:
  8193. upb_status_seterrmsg(
  8194. p->status, "Internal error: unexpected state MULTIPART_INACTIVE");
  8195. return false;
  8196. case MULTIPART_ACCUMULATE:
  8197. if (!accumulate_append(p, buf, len, can_alias)) {
  8198. return false;
  8199. }
  8200. break;
  8201. case MULTIPART_PUSHEAGERLY: {
  8202. const upb_bufhandle *handle = can_alias ? p->handle : NULL;
  8203. upb_sink_putstring(&p->top->sink, p->string_selector, buf, len, handle);
  8204. break;
  8205. }
  8206. }
  8207. return true;
  8208. }
  8209. // Note: this invalidates the accumulate buffer! Call only after reading its
  8210. // contents.
  8211. static void multipart_end(upb_json_parser *p) {
  8212. assert(p->multipart_state != MULTIPART_INACTIVE);
  8213. p->multipart_state = MULTIPART_INACTIVE;
  8214. accumulate_clear(p);
  8215. }
  8216. /* Input capture **************************************************************/
  8217. // Functionality for capturing a region of the input as text. Gracefully
  8218. // handles the case where a buffer seam occurs in the middle of the captured
  8219. // region.
  8220. static void capture_begin(upb_json_parser *p, const char *ptr) {
  8221. assert(p->multipart_state != MULTIPART_INACTIVE);
  8222. assert(p->capture == NULL);
  8223. p->capture = ptr;
  8224. }
  8225. static bool capture_end(upb_json_parser *p, const char *ptr) {
  8226. assert(p->capture);
  8227. if (multipart_text(p, p->capture, ptr - p->capture, true)) {
  8228. p->capture = NULL;
  8229. return true;
  8230. } else {
  8231. return false;
  8232. }
  8233. }
  8234. // This is called at the end of each input buffer (ie. when we have hit a
  8235. // buffer seam). If we are in the middle of capturing the input, this
  8236. // processes the unprocessed capture region.
  8237. static void capture_suspend(upb_json_parser *p, const char **ptr) {
  8238. if (!p->capture) return;
  8239. if (multipart_text(p, p->capture, *ptr - p->capture, false)) {
  8240. // We use this as a signal that we were in the middle of capturing, and
  8241. // that capturing should resume at the beginning of the next buffer.
  8242. //
  8243. // We can't use *ptr here, because we have no guarantee that this pointer
  8244. // will be valid when we resume (if the underlying memory is freed, then
  8245. // using the pointer at all, even to compare to NULL, is likely undefined
  8246. // behavior).
  8247. p->capture = &suspend_capture;
  8248. } else {
  8249. // Need to back up the pointer to the beginning of the capture, since
  8250. // we were not able to actually preserve it.
  8251. *ptr = p->capture;
  8252. }
  8253. }
  8254. static void capture_resume(upb_json_parser *p, const char *ptr) {
  8255. if (p->capture) {
  8256. assert(p->capture == &suspend_capture);
  8257. p->capture = ptr;
  8258. }
  8259. }
  8260. /* Callbacks from the parser **************************************************/
  8261. // These are the functions called directly from the parser itself.
  8262. // We define these in the same order as their declarations in the parser.
  8263. static char escape_char(char in) {
  8264. switch (in) {
  8265. case 'r': return '\r';
  8266. case 't': return '\t';
  8267. case 'n': return '\n';
  8268. case 'f': return '\f';
  8269. case 'b': return '\b';
  8270. case '/': return '/';
  8271. case '"': return '"';
  8272. case '\\': return '\\';
  8273. default:
  8274. assert(0);
  8275. return 'x';
  8276. }
  8277. }
  8278. static bool escape(upb_json_parser *p, const char *ptr) {
  8279. char ch = escape_char(*ptr);
  8280. return multipart_text(p, &ch, 1, false);
  8281. }
  8282. static void start_hex(upb_json_parser *p) {
  8283. p->digit = 0;
  8284. }
  8285. static void hexdigit(upb_json_parser *p, const char *ptr) {
  8286. char ch = *ptr;
  8287. p->digit <<= 4;
  8288. if (ch >= '0' && ch <= '9') {
  8289. p->digit += (ch - '0');
  8290. } else if (ch >= 'a' && ch <= 'f') {
  8291. p->digit += ((ch - 'a') + 10);
  8292. } else {
  8293. assert(ch >= 'A' && ch <= 'F');
  8294. p->digit += ((ch - 'A') + 10);
  8295. }
  8296. }
  8297. static bool end_hex(upb_json_parser *p) {
  8298. uint32_t codepoint = p->digit;
  8299. // emit the codepoint as UTF-8.
  8300. char utf8[3]; // support \u0000 -- \uFFFF -- need only three bytes.
  8301. int length = 0;
  8302. if (codepoint <= 0x7F) {
  8303. utf8[0] = codepoint;
  8304. length = 1;
  8305. } else if (codepoint <= 0x07FF) {
  8306. utf8[1] = (codepoint & 0x3F) | 0x80;
  8307. codepoint >>= 6;
  8308. utf8[0] = (codepoint & 0x1F) | 0xC0;
  8309. length = 2;
  8310. } else /* codepoint <= 0xFFFF */ {
  8311. utf8[2] = (codepoint & 0x3F) | 0x80;
  8312. codepoint >>= 6;
  8313. utf8[1] = (codepoint & 0x3F) | 0x80;
  8314. codepoint >>= 6;
  8315. utf8[0] = (codepoint & 0x0F) | 0xE0;
  8316. length = 3;
  8317. }
  8318. // TODO(haberman): Handle high surrogates: if codepoint is a high surrogate
  8319. // we have to wait for the next escape to get the full code point).
  8320. return multipart_text(p, utf8, length, false);
  8321. }
  8322. static void start_text(upb_json_parser *p, const char *ptr) {
  8323. capture_begin(p, ptr);
  8324. }
  8325. static bool end_text(upb_json_parser *p, const char *ptr) {
  8326. return capture_end(p, ptr);
  8327. }
  8328. static void start_number(upb_json_parser *p, const char *ptr) {
  8329. multipart_startaccum(p);
  8330. capture_begin(p, ptr);
  8331. }
  8332. static bool end_number(upb_json_parser *p, const char *ptr) {
  8333. if (!capture_end(p, ptr)) {
  8334. return false;
  8335. }
  8336. // strtol() and friends unfortunately do not support specifying the length of
  8337. // the input string, so we need to force a copy into a NULL-terminated buffer.
  8338. if (!multipart_text(p, "\0", 1, false)) {
  8339. return false;
  8340. }
  8341. size_t len;
  8342. const char *buf = accumulate_getptr(p, &len);
  8343. const char *myend = buf + len - 1; // One for NULL.
  8344. char *end;
  8345. switch (upb_fielddef_type(p->top->f)) {
  8346. case UPB_TYPE_ENUM:
  8347. case UPB_TYPE_INT32: {
  8348. long val = strtol(p->accumulated, &end, 0);
  8349. if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || end != myend)
  8350. goto err;
  8351. else
  8352. upb_sink_putint32(&p->top->sink, parser_getsel(p), val);
  8353. break;
  8354. }
  8355. case UPB_TYPE_INT64: {
  8356. long long val = strtoll(p->accumulated, &end, 0);
  8357. if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || end != myend)
  8358. goto err;
  8359. else
  8360. upb_sink_putint64(&p->top->sink, parser_getsel(p), val);
  8361. break;
  8362. }
  8363. case UPB_TYPE_UINT32: {
  8364. unsigned long val = strtoul(p->accumulated, &end, 0);
  8365. if (val > UINT32_MAX || errno == ERANGE || end != myend)
  8366. goto err;
  8367. else
  8368. upb_sink_putuint32(&p->top->sink, parser_getsel(p), val);
  8369. break;
  8370. }
  8371. case UPB_TYPE_UINT64: {
  8372. unsigned long long val = strtoull(p->accumulated, &end, 0);
  8373. if (val > UINT64_MAX || errno == ERANGE || end != myend)
  8374. goto err;
  8375. else
  8376. upb_sink_putuint64(&p->top->sink, parser_getsel(p), val);
  8377. break;
  8378. }
  8379. case UPB_TYPE_DOUBLE: {
  8380. double val = strtod(p->accumulated, &end);
  8381. if (errno == ERANGE || end != myend)
  8382. goto err;
  8383. else
  8384. upb_sink_putdouble(&p->top->sink, parser_getsel(p), val);
  8385. break;
  8386. }
  8387. case UPB_TYPE_FLOAT: {
  8388. float val = strtof(p->accumulated, &end);
  8389. if (errno == ERANGE || end != myend)
  8390. goto err;
  8391. else
  8392. upb_sink_putfloat(&p->top->sink, parser_getsel(p), val);
  8393. break;
  8394. }
  8395. default:
  8396. assert(false);
  8397. }
  8398. multipart_end(p);
  8399. return true;
  8400. err:
  8401. upb_status_seterrf(p->status, "error parsing number: %s", buf);
  8402. multipart_end(p);
  8403. return false;
  8404. }
  8405. static bool parser_putbool(upb_json_parser *p, bool val) {
  8406. if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL) {
  8407. upb_status_seterrf(p->status,
  8408. "Boolean value specified for non-bool field: %s",
  8409. upb_fielddef_name(p->top->f));
  8410. return false;
  8411. }
  8412. bool ok = upb_sink_putbool(&p->top->sink, parser_getsel(p), val);
  8413. UPB_ASSERT_VAR(ok, ok);
  8414. return true;
  8415. }
  8416. static bool start_stringval(upb_json_parser *p) {
  8417. assert(p->top->f);
  8418. if (upb_fielddef_isstring(p->top->f)) {
  8419. if (!check_stack(p)) return false;
  8420. // Start a new parser frame: parser frames correspond one-to-one with
  8421. // handler frames, and string events occur in a sub-frame.
  8422. upb_jsonparser_frame *inner = p->top + 1;
  8423. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  8424. upb_sink_startstr(&p->top->sink, sel, 0, &inner->sink);
  8425. inner->m = p->top->m;
  8426. inner->f = p->top->f;
  8427. p->top = inner;
  8428. if (upb_fielddef_type(p->top->f) == UPB_TYPE_STRING) {
  8429. // For STRING fields we push data directly to the handlers as it is
  8430. // parsed. We don't do this yet for BYTES fields, because our base64
  8431. // decoder is not streaming.
  8432. //
  8433. // TODO(haberman): make base64 decoding streaming also.
  8434. multipart_start(p, getsel_for_handlertype(p, UPB_HANDLER_STRING));
  8435. return true;
  8436. } else {
  8437. multipart_startaccum(p);
  8438. return true;
  8439. }
  8440. } else if (upb_fielddef_type(p->top->f) == UPB_TYPE_ENUM) {
  8441. // No need to push a frame -- symbolic enum names in quotes remain in the
  8442. // current parser frame.
  8443. //
  8444. // Enum string values must accumulate so we can look up the value in a table
  8445. // once it is complete.
  8446. multipart_startaccum(p);
  8447. return true;
  8448. } else {
  8449. upb_status_seterrf(p->status,
  8450. "String specified for non-string/non-enum field: %s",
  8451. upb_fielddef_name(p->top->f));
  8452. return false;
  8453. }
  8454. }
  8455. static bool end_stringval(upb_json_parser *p) {
  8456. bool ok = true;
  8457. switch (upb_fielddef_type(p->top->f)) {
  8458. case UPB_TYPE_BYTES:
  8459. if (!base64_push(p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  8460. p->accumulated, p->accumulated_len)) {
  8461. return false;
  8462. }
  8463. // Fall through.
  8464. case UPB_TYPE_STRING: {
  8465. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  8466. upb_sink_endstr(&p->top->sink, sel);
  8467. p->top--;
  8468. break;
  8469. }
  8470. case UPB_TYPE_ENUM: {
  8471. // Resolve enum symbolic name to integer value.
  8472. const upb_enumdef *enumdef =
  8473. (const upb_enumdef*)upb_fielddef_subdef(p->top->f);
  8474. size_t len;
  8475. const char *buf = accumulate_getptr(p, &len);
  8476. int32_t int_val = 0;
  8477. ok = upb_enumdef_ntoi(enumdef, buf, len, &int_val);
  8478. if (ok) {
  8479. upb_selector_t sel = parser_getsel(p);
  8480. upb_sink_putint32(&p->top->sink, sel, int_val);
  8481. } else {
  8482. upb_status_seterrf(p->status, "Enum value unknown: '%.*s'", len, buf);
  8483. }
  8484. break;
  8485. }
  8486. default:
  8487. assert(false);
  8488. upb_status_seterrmsg(p->status, "Internal error in JSON decoder");
  8489. ok = false;
  8490. break;
  8491. }
  8492. multipart_end(p);
  8493. return ok;
  8494. }
  8495. static void start_member(upb_json_parser *p) {
  8496. assert(!p->top->f);
  8497. multipart_startaccum(p);
  8498. }
  8499. static bool end_member(upb_json_parser *p) {
  8500. assert(!p->top->f);
  8501. size_t len;
  8502. const char *buf = accumulate_getptr(p, &len);
  8503. const upb_fielddef *f = upb_msgdef_ntof(p->top->m, buf, len);
  8504. if (!f) {
  8505. // TODO(haberman): Ignore unknown fields if requested/configured to do so.
  8506. upb_status_seterrf(p->status, "No such field: %.*s\n", (int)len, buf);
  8507. return false;
  8508. }
  8509. p->top->f = f;
  8510. multipart_end(p);
  8511. return true;
  8512. }
  8513. static void clear_member(upb_json_parser *p) { p->top->f = NULL; }
  8514. static bool start_subobject(upb_json_parser *p) {
  8515. assert(p->top->f);
  8516. if (!upb_fielddef_issubmsg(p->top->f)) {
  8517. upb_status_seterrf(p->status,
  8518. "Object specified for non-message/group field: %s",
  8519. upb_fielddef_name(p->top->f));
  8520. return false;
  8521. }
  8522. if (!check_stack(p)) return false;
  8523. upb_jsonparser_frame *inner = p->top + 1;
  8524. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  8525. upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
  8526. inner->m = upb_fielddef_msgsubdef(p->top->f);
  8527. inner->f = NULL;
  8528. p->top = inner;
  8529. return true;
  8530. }
  8531. static void end_subobject(upb_json_parser *p) {
  8532. p->top--;
  8533. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSUBMSG);
  8534. upb_sink_endsubmsg(&p->top->sink, sel);
  8535. }
  8536. static bool start_array(upb_json_parser *p) {
  8537. assert(p->top->f);
  8538. if (!upb_fielddef_isseq(p->top->f)) {
  8539. upb_status_seterrf(p->status,
  8540. "Array specified for non-repeated field: %s",
  8541. upb_fielddef_name(p->top->f));
  8542. return false;
  8543. }
  8544. if (!check_stack(p)) return false;
  8545. upb_jsonparser_frame *inner = p->top + 1;
  8546. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  8547. upb_sink_startseq(&p->top->sink, sel, &inner->sink);
  8548. inner->m = p->top->m;
  8549. inner->f = p->top->f;
  8550. p->top = inner;
  8551. return true;
  8552. }
  8553. static void end_array(upb_json_parser *p) {
  8554. assert(p->top > p->stack);
  8555. p->top--;
  8556. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  8557. upb_sink_endseq(&p->top->sink, sel);
  8558. }
  8559. static void start_object(upb_json_parser *p) {
  8560. upb_sink_startmsg(&p->top->sink);
  8561. }
  8562. static void end_object(upb_json_parser *p) {
  8563. upb_status status;
  8564. upb_sink_endmsg(&p->top->sink, &status);
  8565. }
  8566. #define CHECK_RETURN_TOP(x) if (!(x)) goto error
  8567. /* The actual parser **********************************************************/
  8568. // What follows is the Ragel parser itself. The language is specified in Ragel
  8569. // and the actions call our C functions above.
  8570. //
  8571. // Ragel has an extensive set of functionality, and we use only a small part of
  8572. // it. There are many action types but we only use a few:
  8573. //
  8574. // ">" -- transition into a machine
  8575. // "%" -- transition out of a machine
  8576. // "@" -- transition into a final state of a machine.
  8577. //
  8578. // "@" transitions are tricky because a machine can transition into a final
  8579. // state repeatedly. But in some cases we know this can't happen, for example
  8580. // a string which is delimited by a final '"' can only transition into its
  8581. // final state once, when the closing '"' is seen.
  8582. #line 905 "upb/json/parser.rl"
  8583. #line 817 "upb/json/parser.c"
  8584. static const char _json_actions[] = {
  8585. 0, 1, 0, 1, 2, 1, 3, 1,
  8586. 5, 1, 6, 1, 7, 1, 8, 1,
  8587. 10, 1, 12, 1, 13, 1, 14, 1,
  8588. 15, 1, 16, 1, 17, 1, 21, 1,
  8589. 25, 1, 27, 2, 3, 8, 2, 4,
  8590. 5, 2, 6, 2, 2, 6, 8, 2,
  8591. 11, 9, 2, 13, 15, 2, 14, 15,
  8592. 2, 18, 1, 2, 19, 27, 2, 20,
  8593. 9, 2, 22, 27, 2, 23, 27, 2,
  8594. 24, 27, 2, 26, 27, 3, 14, 11,
  8595. 9
  8596. };
  8597. static const unsigned char _json_key_offsets[] = {
  8598. 0, 0, 4, 9, 14, 15, 19, 24,
  8599. 29, 34, 38, 42, 45, 48, 50, 54,
  8600. 58, 60, 62, 67, 69, 71, 80, 86,
  8601. 92, 98, 104, 106, 115, 116, 116, 116,
  8602. 121, 126, 131, 132, 133, 134, 135, 135,
  8603. 136, 137, 138, 138, 139, 140, 141, 141,
  8604. 146, 151, 152, 156, 161, 166, 171, 175,
  8605. 175, 178, 178, 178
  8606. };
  8607. static const char _json_trans_keys[] = {
  8608. 32, 123, 9, 13, 32, 34, 125, 9,
  8609. 13, 32, 34, 125, 9, 13, 34, 32,
  8610. 58, 9, 13, 32, 93, 125, 9, 13,
  8611. 32, 44, 125, 9, 13, 32, 44, 125,
  8612. 9, 13, 32, 34, 9, 13, 45, 48,
  8613. 49, 57, 48, 49, 57, 46, 69, 101,
  8614. 48, 57, 69, 101, 48, 57, 43, 45,
  8615. 48, 57, 48, 57, 48, 57, 46, 69,
  8616. 101, 48, 57, 34, 92, 34, 92, 34,
  8617. 47, 92, 98, 102, 110, 114, 116, 117,
  8618. 48, 57, 65, 70, 97, 102, 48, 57,
  8619. 65, 70, 97, 102, 48, 57, 65, 70,
  8620. 97, 102, 48, 57, 65, 70, 97, 102,
  8621. 34, 92, 34, 45, 91, 102, 110, 116,
  8622. 123, 48, 57, 34, 32, 93, 125, 9,
  8623. 13, 32, 44, 93, 9, 13, 32, 93,
  8624. 125, 9, 13, 97, 108, 115, 101, 117,
  8625. 108, 108, 114, 117, 101, 32, 34, 125,
  8626. 9, 13, 32, 34, 125, 9, 13, 34,
  8627. 32, 58, 9, 13, 32, 93, 125, 9,
  8628. 13, 32, 44, 125, 9, 13, 32, 44,
  8629. 125, 9, 13, 32, 34, 9, 13, 32,
  8630. 9, 13, 0
  8631. };
  8632. static const char _json_single_lengths[] = {
  8633. 0, 2, 3, 3, 1, 2, 3, 3,
  8634. 3, 2, 2, 1, 3, 0, 2, 2,
  8635. 0, 0, 3, 2, 2, 9, 0, 0,
  8636. 0, 0, 2, 7, 1, 0, 0, 3,
  8637. 3, 3, 1, 1, 1, 1, 0, 1,
  8638. 1, 1, 0, 1, 1, 1, 0, 3,
  8639. 3, 1, 2, 3, 3, 3, 2, 0,
  8640. 1, 0, 0, 0
  8641. };
  8642. static const char _json_range_lengths[] = {
  8643. 0, 1, 1, 1, 0, 1, 1, 1,
  8644. 1, 1, 1, 1, 0, 1, 1, 1,
  8645. 1, 1, 1, 0, 0, 0, 3, 3,
  8646. 3, 3, 0, 1, 0, 0, 0, 1,
  8647. 1, 1, 0, 0, 0, 0, 0, 0,
  8648. 0, 0, 0, 0, 0, 0, 0, 1,
  8649. 1, 0, 1, 1, 1, 1, 1, 0,
  8650. 1, 0, 0, 0
  8651. };
  8652. static const short _json_index_offsets[] = {
  8653. 0, 0, 4, 9, 14, 16, 20, 25,
  8654. 30, 35, 39, 43, 46, 50, 52, 56,
  8655. 60, 62, 64, 69, 72, 75, 85, 89,
  8656. 93, 97, 101, 104, 113, 115, 116, 117,
  8657. 122, 127, 132, 134, 136, 138, 140, 141,
  8658. 143, 145, 147, 148, 150, 152, 154, 155,
  8659. 160, 165, 167, 171, 176, 181, 186, 190,
  8660. 191, 194, 195, 196
  8661. };
  8662. static const char _json_indicies[] = {
  8663. 0, 2, 0, 1, 3, 4, 5, 3,
  8664. 1, 6, 7, 8, 6, 1, 9, 1,
  8665. 10, 11, 10, 1, 11, 1, 1, 11,
  8666. 12, 13, 14, 15, 13, 1, 16, 17,
  8667. 8, 16, 1, 17, 7, 17, 1, 18,
  8668. 19, 20, 1, 19, 20, 1, 22, 23,
  8669. 23, 21, 24, 1, 23, 23, 24, 21,
  8670. 25, 25, 26, 1, 26, 1, 26, 21,
  8671. 22, 23, 23, 20, 21, 28, 29, 27,
  8672. 31, 32, 30, 33, 33, 33, 33, 33,
  8673. 33, 33, 33, 34, 1, 35, 35, 35,
  8674. 1, 36, 36, 36, 1, 37, 37, 37,
  8675. 1, 38, 38, 38, 1, 40, 41, 39,
  8676. 42, 43, 44, 45, 46, 47, 48, 43,
  8677. 1, 49, 1, 50, 51, 53, 54, 1,
  8678. 53, 52, 55, 56, 54, 55, 1, 56,
  8679. 1, 1, 56, 52, 57, 1, 58, 1,
  8680. 59, 1, 60, 1, 61, 62, 1, 63,
  8681. 1, 64, 1, 65, 66, 1, 67, 1,
  8682. 68, 1, 69, 70, 71, 72, 70, 1,
  8683. 73, 74, 75, 73, 1, 76, 1, 77,
  8684. 78, 77, 1, 78, 1, 1, 78, 79,
  8685. 80, 81, 82, 80, 1, 83, 84, 75,
  8686. 83, 1, 84, 74, 84, 1, 85, 86,
  8687. 86, 1, 1, 1, 1, 0
  8688. };
  8689. static const char _json_trans_targs[] = {
  8690. 1, 0, 2, 3, 4, 56, 3, 4,
  8691. 56, 5, 5, 6, 7, 8, 9, 56,
  8692. 8, 9, 11, 12, 18, 57, 13, 15,
  8693. 14, 16, 17, 20, 58, 21, 20, 58,
  8694. 21, 19, 22, 23, 24, 25, 26, 20,
  8695. 58, 21, 28, 30, 31, 34, 39, 43,
  8696. 47, 29, 59, 59, 32, 31, 29, 32,
  8697. 33, 35, 36, 37, 38, 59, 40, 41,
  8698. 42, 59, 44, 45, 46, 59, 48, 49,
  8699. 55, 48, 49, 55, 50, 50, 51, 52,
  8700. 53, 54, 55, 53, 54, 59, 56
  8701. };
  8702. static const char _json_trans_actions[] = {
  8703. 0, 0, 0, 21, 77, 53, 0, 47,
  8704. 23, 17, 0, 0, 15, 19, 19, 50,
  8705. 0, 0, 0, 0, 0, 1, 0, 0,
  8706. 0, 0, 0, 3, 13, 0, 0, 35,
  8707. 5, 11, 0, 38, 7, 7, 7, 41,
  8708. 44, 9, 62, 56, 25, 0, 0, 0,
  8709. 31, 29, 33, 59, 15, 0, 27, 0,
  8710. 0, 0, 0, 0, 0, 68, 0, 0,
  8711. 0, 71, 0, 0, 0, 65, 21, 77,
  8712. 53, 0, 47, 23, 17, 0, 0, 15,
  8713. 19, 19, 50, 0, 0, 74, 0
  8714. };
  8715. static const int json_start = 1;
  8716. static const int json_first_final = 56;
  8717. static const int json_error = 0;
  8718. static const int json_en_number_machine = 10;
  8719. static const int json_en_string_machine = 19;
  8720. static const int json_en_value_machine = 27;
  8721. static const int json_en_main = 1;
  8722. #line 908 "upb/json/parser.rl"
  8723. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  8724. const upb_bufhandle *handle) {
  8725. UPB_UNUSED(hd);
  8726. UPB_UNUSED(handle);
  8727. upb_json_parser *parser = closure;
  8728. parser->handle = handle;
  8729. // Variables used by Ragel's generated code.
  8730. int cs = parser->current_state;
  8731. int *stack = parser->parser_stack;
  8732. int top = parser->parser_top;
  8733. const char *p = buf;
  8734. const char *pe = buf + size;
  8735. capture_resume(parser, buf);
  8736. #line 988 "upb/json/parser.c"
  8737. {
  8738. int _klen;
  8739. unsigned int _trans;
  8740. const char *_acts;
  8741. unsigned int _nacts;
  8742. const char *_keys;
  8743. if ( p == pe )
  8744. goto _test_eof;
  8745. if ( cs == 0 )
  8746. goto _out;
  8747. _resume:
  8748. _keys = _json_trans_keys + _json_key_offsets[cs];
  8749. _trans = _json_index_offsets[cs];
  8750. _klen = _json_single_lengths[cs];
  8751. if ( _klen > 0 ) {
  8752. const char *_lower = _keys;
  8753. const char *_mid;
  8754. const char *_upper = _keys + _klen - 1;
  8755. while (1) {
  8756. if ( _upper < _lower )
  8757. break;
  8758. _mid = _lower + ((_upper-_lower) >> 1);
  8759. if ( (*p) < *_mid )
  8760. _upper = _mid - 1;
  8761. else if ( (*p) > *_mid )
  8762. _lower = _mid + 1;
  8763. else {
  8764. _trans += (unsigned int)(_mid - _keys);
  8765. goto _match;
  8766. }
  8767. }
  8768. _keys += _klen;
  8769. _trans += _klen;
  8770. }
  8771. _klen = _json_range_lengths[cs];
  8772. if ( _klen > 0 ) {
  8773. const char *_lower = _keys;
  8774. const char *_mid;
  8775. const char *_upper = _keys + (_klen<<1) - 2;
  8776. while (1) {
  8777. if ( _upper < _lower )
  8778. break;
  8779. _mid = _lower + (((_upper-_lower) >> 1) & ~1);
  8780. if ( (*p) < _mid[0] )
  8781. _upper = _mid - 2;
  8782. else if ( (*p) > _mid[1] )
  8783. _lower = _mid + 2;
  8784. else {
  8785. _trans += (unsigned int)((_mid - _keys)>>1);
  8786. goto _match;
  8787. }
  8788. }
  8789. _trans += _klen;
  8790. }
  8791. _match:
  8792. _trans = _json_indicies[_trans];
  8793. cs = _json_trans_targs[_trans];
  8794. if ( _json_trans_actions[_trans] == 0 )
  8795. goto _again;
  8796. _acts = _json_actions + _json_trans_actions[_trans];
  8797. _nacts = (unsigned int) *_acts++;
  8798. while ( _nacts-- > 0 )
  8799. {
  8800. switch ( *_acts++ )
  8801. {
  8802. case 0:
  8803. #line 820 "upb/json/parser.rl"
  8804. { p--; {cs = stack[--top]; goto _again;} }
  8805. break;
  8806. case 1:
  8807. #line 821 "upb/json/parser.rl"
  8808. { p--; {stack[top++] = cs; cs = 10; goto _again;} }
  8809. break;
  8810. case 2:
  8811. #line 825 "upb/json/parser.rl"
  8812. { start_text(parser, p); }
  8813. break;
  8814. case 3:
  8815. #line 826 "upb/json/parser.rl"
  8816. { CHECK_RETURN_TOP(end_text(parser, p)); }
  8817. break;
  8818. case 4:
  8819. #line 832 "upb/json/parser.rl"
  8820. { start_hex(parser); }
  8821. break;
  8822. case 5:
  8823. #line 833 "upb/json/parser.rl"
  8824. { hexdigit(parser, p); }
  8825. break;
  8826. case 6:
  8827. #line 834 "upb/json/parser.rl"
  8828. { CHECK_RETURN_TOP(end_hex(parser)); }
  8829. break;
  8830. case 7:
  8831. #line 840 "upb/json/parser.rl"
  8832. { CHECK_RETURN_TOP(escape(parser, p)); }
  8833. break;
  8834. case 8:
  8835. #line 846 "upb/json/parser.rl"
  8836. { p--; {cs = stack[--top]; goto _again;} }
  8837. break;
  8838. case 9:
  8839. #line 849 "upb/json/parser.rl"
  8840. { {stack[top++] = cs; cs = 19; goto _again;} }
  8841. break;
  8842. case 10:
  8843. #line 851 "upb/json/parser.rl"
  8844. { p--; {stack[top++] = cs; cs = 27; goto _again;} }
  8845. break;
  8846. case 11:
  8847. #line 856 "upb/json/parser.rl"
  8848. { start_member(parser); }
  8849. break;
  8850. case 12:
  8851. #line 857 "upb/json/parser.rl"
  8852. { CHECK_RETURN_TOP(end_member(parser)); }
  8853. break;
  8854. case 13:
  8855. #line 860 "upb/json/parser.rl"
  8856. { clear_member(parser); }
  8857. break;
  8858. case 14:
  8859. #line 866 "upb/json/parser.rl"
  8860. { start_object(parser); }
  8861. break;
  8862. case 15:
  8863. #line 869 "upb/json/parser.rl"
  8864. { end_object(parser); }
  8865. break;
  8866. case 16:
  8867. #line 875 "upb/json/parser.rl"
  8868. { CHECK_RETURN_TOP(start_array(parser)); }
  8869. break;
  8870. case 17:
  8871. #line 879 "upb/json/parser.rl"
  8872. { end_array(parser); }
  8873. break;
  8874. case 18:
  8875. #line 884 "upb/json/parser.rl"
  8876. { start_number(parser, p); }
  8877. break;
  8878. case 19:
  8879. #line 885 "upb/json/parser.rl"
  8880. { CHECK_RETURN_TOP(end_number(parser, p)); }
  8881. break;
  8882. case 20:
  8883. #line 887 "upb/json/parser.rl"
  8884. { CHECK_RETURN_TOP(start_stringval(parser)); }
  8885. break;
  8886. case 21:
  8887. #line 888 "upb/json/parser.rl"
  8888. { CHECK_RETURN_TOP(end_stringval(parser)); }
  8889. break;
  8890. case 22:
  8891. #line 890 "upb/json/parser.rl"
  8892. { CHECK_RETURN_TOP(parser_putbool(parser, true)); }
  8893. break;
  8894. case 23:
  8895. #line 892 "upb/json/parser.rl"
  8896. { CHECK_RETURN_TOP(parser_putbool(parser, false)); }
  8897. break;
  8898. case 24:
  8899. #line 894 "upb/json/parser.rl"
  8900. { /* null value */ }
  8901. break;
  8902. case 25:
  8903. #line 896 "upb/json/parser.rl"
  8904. { CHECK_RETURN_TOP(start_subobject(parser)); }
  8905. break;
  8906. case 26:
  8907. #line 897 "upb/json/parser.rl"
  8908. { end_subobject(parser); }
  8909. break;
  8910. case 27:
  8911. #line 902 "upb/json/parser.rl"
  8912. { p--; {cs = stack[--top]; goto _again;} }
  8913. break;
  8914. #line 1174 "upb/json/parser.c"
  8915. }
  8916. }
  8917. _again:
  8918. if ( cs == 0 )
  8919. goto _out;
  8920. if ( ++p != pe )
  8921. goto _resume;
  8922. _test_eof: {}
  8923. _out: {}
  8924. }
  8925. #line 927 "upb/json/parser.rl"
  8926. if (p != pe) {
  8927. upb_status_seterrf(parser->status, "Parse error at %s\n", p);
  8928. } else {
  8929. capture_suspend(parser, &p);
  8930. }
  8931. error:
  8932. // Save parsing state back to parser.
  8933. parser->current_state = cs;
  8934. parser->parser_top = top;
  8935. return p - buf;
  8936. }
  8937. bool end(void *closure, const void *hd) {
  8938. UPB_UNUSED(closure);
  8939. UPB_UNUSED(hd);
  8940. return true;
  8941. }
  8942. /* Public API *****************************************************************/
  8943. void upb_json_parser_init(upb_json_parser *p, upb_status *status) {
  8944. p->limit = p->stack + UPB_JSON_MAX_DEPTH;
  8945. p->accumulate_buf = NULL;
  8946. p->accumulate_buf_size = 0;
  8947. upb_byteshandler_init(&p->input_handler_);
  8948. upb_byteshandler_setstring(&p->input_handler_, parse, NULL);
  8949. upb_byteshandler_setendstr(&p->input_handler_, end, NULL);
  8950. upb_bytessink_reset(&p->input_, &p->input_handler_, p);
  8951. p->status = status;
  8952. }
  8953. void upb_json_parser_uninit(upb_json_parser *p) {
  8954. upb_byteshandler_uninit(&p->input_handler_);
  8955. free(p->accumulate_buf);
  8956. }
  8957. void upb_json_parser_reset(upb_json_parser *p) {
  8958. p->top = p->stack;
  8959. p->top->f = NULL;
  8960. int cs;
  8961. int top;
  8962. // Emit Ragel initialization of the parser.
  8963. #line 1236 "upb/json/parser.c"
  8964. {
  8965. cs = json_start;
  8966. top = 0;
  8967. }
  8968. #line 975 "upb/json/parser.rl"
  8969. p->current_state = cs;
  8970. p->parser_top = top;
  8971. accumulate_clear(p);
  8972. p->multipart_state = MULTIPART_INACTIVE;
  8973. p->capture = NULL;
  8974. }
  8975. void upb_json_parser_resetoutput(upb_json_parser *p, upb_sink *sink) {
  8976. upb_json_parser_reset(p);
  8977. upb_sink_reset(&p->top->sink, sink->handlers, sink->closure);
  8978. p->top->m = upb_handlers_msgdef(sink->handlers);
  8979. p->accumulated = NULL;
  8980. }
  8981. upb_bytessink *upb_json_parser_input(upb_json_parser *p) {
  8982. return &p->input_;
  8983. }
  8984. /*
  8985. * upb - a minimalist implementation of protocol buffers.
  8986. *
  8987. * Copyright (c) 2014 Google Inc. See LICENSE for details.
  8988. * Author: Josh Haberman <jhaberman@gmail.com>
  8989. *
  8990. * This currently uses snprintf() to format primitives, and could be optimized
  8991. * further.
  8992. */
  8993. #include <stdlib.h>
  8994. #include <stdio.h>
  8995. #include <string.h>
  8996. #include <stdint.h>
  8997. // StringPiece; a pointer plus a length.
  8998. typedef struct {
  8999. const char *ptr;
  9000. size_t len;
  9001. } strpc;
  9002. strpc *newstrpc(upb_handlers *h, const upb_fielddef *f) {
  9003. strpc *ret = malloc(sizeof(*ret));
  9004. ret->ptr = upb_fielddef_name(f);
  9005. ret->len = strlen(ret->ptr);
  9006. upb_handlers_addcleanup(h, ret, free);
  9007. return ret;
  9008. }
  9009. // ------------ JSON string printing: values, maps, arrays --------------------
  9010. static void print_data(
  9011. upb_json_printer *p, const char *buf, unsigned int len) {
  9012. // TODO: Will need to change if we support pushback from the sink.
  9013. size_t n = upb_bytessink_putbuf(p->output_, p->subc_, buf, len, NULL);
  9014. UPB_ASSERT_VAR(n, n == len);
  9015. }
  9016. static void print_comma(upb_json_printer *p) {
  9017. if (!p->first_elem_[p->depth_]) {
  9018. print_data(p, ",", 1);
  9019. }
  9020. p->first_elem_[p->depth_] = false;
  9021. }
  9022. // Helpers that print properly formatted elements to the JSON output stream.
  9023. // Used for escaping control chars in strings.
  9024. static const char kControlCharLimit = 0x20;
  9025. static inline bool is_json_escaped(char c) {
  9026. // See RFC 4627.
  9027. unsigned char uc = (unsigned char)c;
  9028. return uc < kControlCharLimit || uc == '"' || uc == '\\';
  9029. }
  9030. static inline char* json_nice_escape(char c) {
  9031. switch (c) {
  9032. case '"': return "\\\"";
  9033. case '\\': return "\\\\";
  9034. case '\b': return "\\b";
  9035. case '\f': return "\\f";
  9036. case '\n': return "\\n";
  9037. case '\r': return "\\r";
  9038. case '\t': return "\\t";
  9039. default: return NULL;
  9040. }
  9041. }
  9042. // Write a properly escaped string chunk. The surrounding quotes are *not*
  9043. // printed; this is so that the caller has the option of emitting the string
  9044. // content in chunks.
  9045. static void putstring(upb_json_printer *p, const char *buf, unsigned int len) {
  9046. const char* unescaped_run = NULL;
  9047. for (unsigned int i = 0; i < len; i++) {
  9048. char c = buf[i];
  9049. // Handle escaping.
  9050. if (is_json_escaped(c)) {
  9051. // Use a "nice" escape, like \n, if one exists for this character.
  9052. const char* escape = json_nice_escape(c);
  9053. // If we don't have a specific 'nice' escape code, use a \uXXXX-style
  9054. // escape.
  9055. char escape_buf[8];
  9056. if (!escape) {
  9057. unsigned char byte = (unsigned char)c;
  9058. snprintf(escape_buf, sizeof(escape_buf), "\\u%04x", (int)byte);
  9059. escape = escape_buf;
  9060. }
  9061. // N.B. that we assume that the input encoding is equal to the output
  9062. // encoding (both UTF-8 for now), so for chars >= 0x20 and != \, ", we
  9063. // can simply pass the bytes through.
  9064. // If there's a current run of unescaped chars, print that run first.
  9065. if (unescaped_run) {
  9066. print_data(p, unescaped_run, &buf[i] - unescaped_run);
  9067. unescaped_run = NULL;
  9068. }
  9069. // Then print the escape code.
  9070. print_data(p, escape, strlen(escape));
  9071. } else {
  9072. // Add to the current unescaped run of characters.
  9073. if (unescaped_run == NULL) {
  9074. unescaped_run = &buf[i];
  9075. }
  9076. }
  9077. }
  9078. // If the string ended in a run of unescaped characters, print that last run.
  9079. if (unescaped_run) {
  9080. print_data(p, unescaped_run, &buf[len] - unescaped_run);
  9081. }
  9082. }
  9083. #define CHKLENGTH(x) if (!(x)) return -1;
  9084. // Helpers that format floating point values according to our custom formats.
  9085. // Right now we use %.8g and %.17g for float/double, respectively, to match
  9086. // proto2::util::JsonFormat's defaults. May want to change this later.
  9087. static size_t fmt_double(double val, char* buf, size_t length) {
  9088. size_t n = snprintf(buf, length, "%.17g", val);
  9089. CHKLENGTH(n > 0 && n < length);
  9090. return n;
  9091. }
  9092. static size_t fmt_float(float val, char* buf, size_t length) {
  9093. size_t n = snprintf(buf, length, "%.8g", val);
  9094. CHKLENGTH(n > 0 && n < length);
  9095. return n;
  9096. }
  9097. static size_t fmt_bool(bool val, char* buf, size_t length) {
  9098. size_t n = snprintf(buf, length, "%s", (val ? "true" : "false"));
  9099. CHKLENGTH(n > 0 && n < length);
  9100. return n;
  9101. }
  9102. static size_t fmt_int64(long val, char* buf, size_t length) {
  9103. size_t n = snprintf(buf, length, "%ld", val);
  9104. CHKLENGTH(n > 0 && n < length);
  9105. return n;
  9106. }
  9107. static size_t fmt_uint64(unsigned long long val, char* buf, size_t length) {
  9108. size_t n = snprintf(buf, length, "%llu", val);
  9109. CHKLENGTH(n > 0 && n < length);
  9110. return n;
  9111. }
  9112. // Print a map key given a field name. Called by scalar field handlers and by
  9113. // startseq for repeated fields.
  9114. static bool putkey(void *closure, const void *handler_data) {
  9115. upb_json_printer *p = closure;
  9116. const strpc *key = handler_data;
  9117. print_comma(p);
  9118. print_data(p, "\"", 1);
  9119. putstring(p, key->ptr, key->len);
  9120. print_data(p, "\":", 2);
  9121. return true;
  9122. }
  9123. #define CHKFMT(val) if ((val) == -1) return false;
  9124. #define CHK(val) if (!(val)) return false;
  9125. #define TYPE_HANDLERS(type, fmt_func) \
  9126. static bool put##type(void *closure, const void *handler_data, type val) { \
  9127. upb_json_printer *p = closure; \
  9128. UPB_UNUSED(handler_data); \
  9129. char data[64]; \
  9130. size_t length = fmt_func(val, data, sizeof(data)); \
  9131. CHKFMT(length); \
  9132. print_data(p, data, length); \
  9133. return true; \
  9134. } \
  9135. static bool scalar_##type(void *closure, const void *handler_data, \
  9136. type val) { \
  9137. CHK(putkey(closure, handler_data)); \
  9138. CHK(put##type(closure, handler_data, val)); \
  9139. return true; \
  9140. } \
  9141. static bool repeated_##type(void *closure, const void *handler_data, \
  9142. type val) { \
  9143. upb_json_printer *p = closure; \
  9144. print_comma(p); \
  9145. CHK(put##type(closure, handler_data, val)); \
  9146. return true; \
  9147. }
  9148. TYPE_HANDLERS(double, fmt_double);
  9149. TYPE_HANDLERS(float, fmt_float);
  9150. TYPE_HANDLERS(bool, fmt_bool);
  9151. TYPE_HANDLERS(int32_t, fmt_int64);
  9152. TYPE_HANDLERS(uint32_t, fmt_int64);
  9153. TYPE_HANDLERS(int64_t, fmt_int64);
  9154. TYPE_HANDLERS(uint64_t, fmt_uint64);
  9155. #undef TYPE_HANDLERS
  9156. typedef struct {
  9157. void *keyname;
  9158. const upb_enumdef *enumdef;
  9159. } EnumHandlerData;
  9160. static bool scalar_enum(void *closure, const void *handler_data,
  9161. int32_t val) {
  9162. const EnumHandlerData *hd = handler_data;
  9163. upb_json_printer *p = closure;
  9164. CHK(putkey(closure, hd->keyname));
  9165. const char *symbolic_name = upb_enumdef_iton(hd->enumdef, val);
  9166. if (symbolic_name) {
  9167. print_data(p, "\"", 1);
  9168. putstring(p, symbolic_name, strlen(symbolic_name));
  9169. print_data(p, "\"", 1);
  9170. } else {
  9171. putint32_t(closure, NULL, val);
  9172. }
  9173. return true;
  9174. }
  9175. static bool repeated_enum(void *closure, const void *handler_data,
  9176. int32_t val) {
  9177. const EnumHandlerData *hd = handler_data;
  9178. upb_json_printer *p = closure;
  9179. print_comma(p);
  9180. const char *symbolic_name = upb_enumdef_iton(hd->enumdef, val);
  9181. if (symbolic_name) {
  9182. print_data(p, "\"", 1);
  9183. putstring(p, symbolic_name, strlen(symbolic_name));
  9184. print_data(p, "\"", 1);
  9185. } else {
  9186. putint32_t(closure, NULL, val);
  9187. }
  9188. return true;
  9189. }
  9190. static void *scalar_startsubmsg(void *closure, const void *handler_data) {
  9191. return putkey(closure, handler_data) ? closure : UPB_BREAK;
  9192. }
  9193. static void *repeated_startsubmsg(void *closure, const void *handler_data) {
  9194. UPB_UNUSED(handler_data);
  9195. upb_json_printer *p = closure;
  9196. print_comma(p);
  9197. return closure;
  9198. }
  9199. static bool startmap(void *closure, const void *handler_data) {
  9200. UPB_UNUSED(handler_data);
  9201. upb_json_printer *p = closure;
  9202. if (p->depth_++ == 0) {
  9203. upb_bytessink_start(p->output_, 0, &p->subc_);
  9204. }
  9205. p->first_elem_[p->depth_] = true;
  9206. print_data(p, "{", 1);
  9207. return true;
  9208. }
  9209. static bool endmap(void *closure, const void *handler_data, upb_status *s) {
  9210. UPB_UNUSED(handler_data);
  9211. UPB_UNUSED(s);
  9212. upb_json_printer *p = closure;
  9213. if (--p->depth_ == 0) {
  9214. upb_bytessink_end(p->output_);
  9215. }
  9216. print_data(p, "}", 1);
  9217. return true;
  9218. }
  9219. static void *startseq(void *closure, const void *handler_data) {
  9220. upb_json_printer *p = closure;
  9221. CHK(putkey(closure, handler_data));
  9222. p->depth_++;
  9223. p->first_elem_[p->depth_] = true;
  9224. print_data(p, "[", 1);
  9225. return closure;
  9226. }
  9227. static bool endseq(void *closure, const void *handler_data) {
  9228. UPB_UNUSED(handler_data);
  9229. upb_json_printer *p = closure;
  9230. print_data(p, "]", 1);
  9231. p->depth_--;
  9232. return true;
  9233. }
  9234. static size_t putstr(void *closure, const void *handler_data, const char *str,
  9235. size_t len, const upb_bufhandle *handle) {
  9236. UPB_UNUSED(handler_data);
  9237. UPB_UNUSED(handle);
  9238. upb_json_printer *p = closure;
  9239. putstring(p, str, len);
  9240. return len;
  9241. }
  9242. // This has to Base64 encode the bytes, because JSON has no "bytes" type.
  9243. static size_t putbytes(void *closure, const void *handler_data, const char *str,
  9244. size_t len, const upb_bufhandle *handle) {
  9245. UPB_UNUSED(handler_data);
  9246. UPB_UNUSED(handle);
  9247. upb_json_printer *p = closure;
  9248. // This is the regular base64, not the "web-safe" version.
  9249. static const char base64[] =
  9250. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  9251. // Base64-encode.
  9252. char data[16000];
  9253. const char *limit = data + sizeof(data);
  9254. const unsigned char *from = (const unsigned char*)str;
  9255. char *to = data;
  9256. size_t remaining = len;
  9257. while (remaining > 2) {
  9258. // TODO(haberman): handle encoded lengths > sizeof(data)
  9259. UPB_ASSERT_VAR(limit, (limit - to) >= 4);
  9260. to[0] = base64[from[0] >> 2];
  9261. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  9262. to[2] = base64[((from[1] & 0xf) << 2) | (from[2] >> 6)];
  9263. to[3] = base64[from[2] & 0x3f];
  9264. remaining -= 3;
  9265. to += 4;
  9266. from += 3;
  9267. }
  9268. switch (remaining) {
  9269. case 2:
  9270. to[0] = base64[from[0] >> 2];
  9271. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  9272. to[2] = base64[(from[1] & 0xf) << 2];
  9273. to[3] = '=';
  9274. to += 4;
  9275. from += 2;
  9276. break;
  9277. case 1:
  9278. to[0] = base64[from[0] >> 2];
  9279. to[1] = base64[((from[0] & 0x3) << 4)];
  9280. to[2] = '=';
  9281. to[3] = '=';
  9282. to += 4;
  9283. from += 1;
  9284. break;
  9285. }
  9286. size_t bytes = to - data;
  9287. print_data(p, "\"", 1);
  9288. putstring(p, data, bytes);
  9289. print_data(p, "\"", 1);
  9290. return len;
  9291. }
  9292. static void *scalar_startstr(void *closure, const void *handler_data,
  9293. size_t size_hint) {
  9294. UPB_UNUSED(handler_data);
  9295. UPB_UNUSED(size_hint);
  9296. upb_json_printer *p = closure;
  9297. CHK(putkey(closure, handler_data));
  9298. print_data(p, "\"", 1);
  9299. return p;
  9300. }
  9301. static size_t scalar_str(void *closure, const void *handler_data,
  9302. const char *str, size_t len,
  9303. const upb_bufhandle *handle) {
  9304. CHK(putstr(closure, handler_data, str, len, handle));
  9305. return len;
  9306. }
  9307. static bool scalar_endstr(void *closure, const void *handler_data) {
  9308. UPB_UNUSED(handler_data);
  9309. upb_json_printer *p = closure;
  9310. print_data(p, "\"", 1);
  9311. return true;
  9312. }
  9313. static void *repeated_startstr(void *closure, const void *handler_data,
  9314. size_t size_hint) {
  9315. UPB_UNUSED(handler_data);
  9316. UPB_UNUSED(size_hint);
  9317. upb_json_printer *p = closure;
  9318. print_comma(p);
  9319. print_data(p, "\"", 1);
  9320. return p;
  9321. }
  9322. static size_t repeated_str(void *closure, const void *handler_data,
  9323. const char *str, size_t len,
  9324. const upb_bufhandle *handle) {
  9325. CHK(putstr(closure, handler_data, str, len, handle));
  9326. return len;
  9327. }
  9328. static bool repeated_endstr(void *closure, const void *handler_data) {
  9329. UPB_UNUSED(handler_data);
  9330. upb_json_printer *p = closure;
  9331. print_data(p, "\"", 1);
  9332. return true;
  9333. }
  9334. static size_t scalar_bytes(void *closure, const void *handler_data,
  9335. const char *str, size_t len,
  9336. const upb_bufhandle *handle) {
  9337. CHK(putkey(closure, handler_data));
  9338. CHK(putbytes(closure, handler_data, str, len, handle));
  9339. return len;
  9340. }
  9341. static size_t repeated_bytes(void *closure, const void *handler_data,
  9342. const char *str, size_t len,
  9343. const upb_bufhandle *handle) {
  9344. upb_json_printer *p = closure;
  9345. print_comma(p);
  9346. CHK(putbytes(closure, handler_data, str, len, handle));
  9347. return len;
  9348. }
  9349. void printer_sethandlers(const void *closure, upb_handlers *h) {
  9350. UPB_UNUSED(closure);
  9351. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  9352. upb_handlers_setstartmsg(h, startmap, &empty_attr);
  9353. upb_handlers_setendmsg(h, endmap, &empty_attr);
  9354. #define TYPE(type, name, ctype) \
  9355. case type: \
  9356. if (upb_fielddef_isseq(f)) { \
  9357. upb_handlers_set##name(h, f, repeated_##ctype, &empty_attr); \
  9358. } else { \
  9359. upb_handlers_set##name(h, f, scalar_##ctype, &name_attr); \
  9360. } \
  9361. break;
  9362. upb_msg_field_iter i;
  9363. upb_msg_field_begin(&i, upb_handlers_msgdef(h));
  9364. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  9365. const upb_fielddef *f = upb_msg_iter_field(&i);
  9366. upb_handlerattr name_attr = UPB_HANDLERATTR_INITIALIZER;
  9367. upb_handlerattr_sethandlerdata(&name_attr, newstrpc(h, f));
  9368. if (upb_fielddef_isseq(f)) {
  9369. upb_handlers_setstartseq(h, f, startseq, &name_attr);
  9370. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  9371. }
  9372. switch (upb_fielddef_type(f)) {
  9373. TYPE(UPB_TYPE_FLOAT, float, float);
  9374. TYPE(UPB_TYPE_DOUBLE, double, double);
  9375. TYPE(UPB_TYPE_BOOL, bool, bool);
  9376. TYPE(UPB_TYPE_INT32, int32, int32_t);
  9377. TYPE(UPB_TYPE_UINT32, uint32, uint32_t);
  9378. TYPE(UPB_TYPE_INT64, int64, int64_t);
  9379. TYPE(UPB_TYPE_UINT64, uint64, uint64_t);
  9380. case UPB_TYPE_ENUM: {
  9381. // For now, we always emit symbolic names for enums. We may want an
  9382. // option later to control this behavior, but we will wait for a real
  9383. // need first.
  9384. EnumHandlerData *hd = malloc(sizeof(EnumHandlerData));
  9385. hd->enumdef = (const upb_enumdef *)upb_fielddef_subdef(f);
  9386. hd->keyname = newstrpc(h, f);
  9387. upb_handlers_addcleanup(h, hd, free);
  9388. upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
  9389. upb_handlerattr_sethandlerdata(&enum_attr, hd);
  9390. if (upb_fielddef_isseq(f)) {
  9391. upb_handlers_setint32(h, f, repeated_enum, &enum_attr);
  9392. } else {
  9393. upb_handlers_setint32(h, f, scalar_enum, &enum_attr);
  9394. }
  9395. upb_handlerattr_uninit(&enum_attr);
  9396. break;
  9397. }
  9398. case UPB_TYPE_STRING:
  9399. if (upb_fielddef_isseq(f)) {
  9400. upb_handlers_setstartstr(h, f, repeated_startstr, &empty_attr);
  9401. upb_handlers_setstring(h, f, repeated_str, &empty_attr);
  9402. upb_handlers_setendstr(h, f, repeated_endstr, &empty_attr);
  9403. } else {
  9404. upb_handlers_setstartstr(h, f, scalar_startstr, &name_attr);
  9405. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  9406. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  9407. }
  9408. break;
  9409. case UPB_TYPE_BYTES:
  9410. // XXX: this doesn't support strings that span buffers yet. The base64
  9411. // encoder will need to be made resumable for this to work properly.
  9412. if (upb_fielddef_isseq(f)) {
  9413. upb_handlers_setstring(h, f, repeated_bytes, &empty_attr);
  9414. } else {
  9415. upb_handlers_setstring(h, f, scalar_bytes, &name_attr);
  9416. }
  9417. break;
  9418. case UPB_TYPE_MESSAGE:
  9419. if (upb_fielddef_isseq(f)) {
  9420. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &name_attr);
  9421. } else {
  9422. upb_handlers_setstartsubmsg(h, f, scalar_startsubmsg, &name_attr);
  9423. }
  9424. break;
  9425. }
  9426. upb_handlerattr_uninit(&name_attr);
  9427. }
  9428. upb_handlerattr_uninit(&empty_attr);
  9429. #undef TYPE
  9430. }
  9431. /* Public API *****************************************************************/
  9432. void upb_json_printer_init(upb_json_printer *p, const upb_handlers *h) {
  9433. p->output_ = NULL;
  9434. p->depth_ = 0;
  9435. upb_sink_reset(&p->input_, h, p);
  9436. }
  9437. void upb_json_printer_uninit(upb_json_printer *p) {
  9438. UPB_UNUSED(p);
  9439. }
  9440. void upb_json_printer_reset(upb_json_printer *p) {
  9441. p->depth_ = 0;
  9442. }
  9443. void upb_json_printer_resetoutput(upb_json_printer *p, upb_bytessink *output) {
  9444. upb_json_printer_reset(p);
  9445. p->output_ = output;
  9446. }
  9447. upb_sink *upb_json_printer_input(upb_json_printer *p) {
  9448. return &p->input_;
  9449. }
  9450. const upb_handlers *upb_json_printer_newhandlers(const upb_msgdef *md,
  9451. const void *owner) {
  9452. return upb_handlers_newfrozen(md, owner, printer_sethandlers, NULL);
  9453. }