upb.c 372 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220
  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. // Ensure that MapEntry submessages only appear as repeated fields, not
  178. // optional/required (singular) fields.
  179. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  180. upb_fielddef_msgsubdef(f) != NULL) {
  181. const upb_msgdef *subdef = upb_fielddef_msgsubdef(f);
  182. if (upb_msgdef_mapentry(subdef) && !upb_fielddef_isseq(f)) {
  183. upb_status_seterrf(s,
  184. "Field %s refers to mapentry message but is not "
  185. "a repeated field",
  186. upb_fielddef_name(f) ? upb_fielddef_name(f) :
  187. "(unnamed)");
  188. return false;
  189. }
  190. }
  191. return true;
  192. }
  193. static bool upb_validate_enumdef(const upb_enumdef *e, upb_status *s) {
  194. if (upb_enumdef_numvals(e) == 0) {
  195. upb_status_seterrf(s, "enum %s has no members (must have at least one)",
  196. upb_enumdef_fullname(e));
  197. return false;
  198. }
  199. return true;
  200. }
  201. // All submessage fields are lower than all other fields.
  202. // Secondly, fields are increasing in order.
  203. uint32_t field_rank(const upb_fielddef *f) {
  204. uint32_t ret = upb_fielddef_number(f);
  205. const uint32_t high_bit = 1 << 30;
  206. assert(ret < high_bit);
  207. if (!upb_fielddef_issubmsg(f))
  208. ret |= high_bit;
  209. return ret;
  210. }
  211. int cmp_fields(const void *p1, const void *p2) {
  212. const upb_fielddef *f1 = *(upb_fielddef*const*)p1;
  213. const upb_fielddef *f2 = *(upb_fielddef*const*)p2;
  214. return field_rank(f1) - field_rank(f2);
  215. }
  216. static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
  217. // Sort fields. upb internally relies on UPB_TYPE_MESSAGE fields having the
  218. // lowest indexes, but we do not publicly guarantee this.
  219. int n = upb_msgdef_numfields(m);
  220. upb_fielddef **fields = malloc(n * sizeof(*fields));
  221. if (!fields) return false;
  222. upb_msg_field_iter j;
  223. int i;
  224. m->submsg_field_count = 0;
  225. for(i = 0, upb_msg_field_begin(&j, m);
  226. !upb_msg_field_done(&j);
  227. upb_msg_field_next(&j), i++) {
  228. upb_fielddef *f = upb_msg_iter_field(&j);
  229. assert(f->msg.def == m);
  230. if (!upb_validate_field(f, s)) {
  231. free(fields);
  232. return false;
  233. }
  234. if (upb_fielddef_issubmsg(f)) {
  235. m->submsg_field_count++;
  236. }
  237. fields[i] = f;
  238. }
  239. qsort(fields, n, sizeof(*fields), cmp_fields);
  240. uint32_t selector = UPB_STATIC_SELECTOR_COUNT + m->submsg_field_count;
  241. for (i = 0; i < n; i++) {
  242. upb_fielddef *f = fields[i];
  243. f->index_ = i;
  244. f->selector_base = selector + upb_handlers_selectorbaseoffset(f);
  245. selector += upb_handlers_selectorcount(f);
  246. }
  247. m->selector_count = selector;
  248. #ifndef NDEBUG
  249. // Verify that all selectors for the message are distinct.
  250. //
  251. #define TRY(type) \
  252. if (upb_handlers_getselector(f, type, &sel)) upb_inttable_insert(&t, sel, v);
  253. upb_inttable t;
  254. upb_inttable_init(&t, UPB_CTYPE_BOOL);
  255. upb_value v = upb_value_bool(true);
  256. upb_selector_t sel;
  257. upb_inttable_insert(&t, UPB_STARTMSG_SELECTOR, v);
  258. upb_inttable_insert(&t, UPB_ENDMSG_SELECTOR, v);
  259. for(upb_msg_field_begin(&j, m);
  260. !upb_msg_field_done(&j);
  261. upb_msg_field_next(&j)) {
  262. upb_fielddef *f = upb_msg_iter_field(&j);
  263. // These calls will assert-fail in upb_table if the value already exists.
  264. TRY(UPB_HANDLER_INT32);
  265. TRY(UPB_HANDLER_INT64)
  266. TRY(UPB_HANDLER_UINT32)
  267. TRY(UPB_HANDLER_UINT64)
  268. TRY(UPB_HANDLER_FLOAT)
  269. TRY(UPB_HANDLER_DOUBLE)
  270. TRY(UPB_HANDLER_BOOL)
  271. TRY(UPB_HANDLER_STARTSTR)
  272. TRY(UPB_HANDLER_STRING)
  273. TRY(UPB_HANDLER_ENDSTR)
  274. TRY(UPB_HANDLER_STARTSUBMSG)
  275. TRY(UPB_HANDLER_ENDSUBMSG)
  276. TRY(UPB_HANDLER_STARTSEQ)
  277. TRY(UPB_HANDLER_ENDSEQ)
  278. }
  279. upb_inttable_uninit(&t);
  280. #undef TRY
  281. #endif
  282. free(fields);
  283. return true;
  284. }
  285. bool upb_def_freeze(upb_def *const* defs, int n, upb_status *s) {
  286. upb_status_clear(s);
  287. // First perform validation, in two passes so we can check that we have a
  288. // transitive closure without needing to search.
  289. for (int i = 0; i < n; i++) {
  290. upb_def *def = defs[i];
  291. if (upb_def_isfrozen(def)) {
  292. // Could relax this requirement if it's annoying.
  293. upb_status_seterrmsg(s, "def is already frozen");
  294. goto err;
  295. } else if (def->type == UPB_DEF_FIELD) {
  296. upb_status_seterrmsg(s, "standalone fielddefs can not be frozen");
  297. goto err;
  298. } else if (def->type == UPB_DEF_ENUM) {
  299. if (!upb_validate_enumdef(upb_dyncast_enumdef(def), s)) {
  300. goto err;
  301. }
  302. } else {
  303. // Set now to detect transitive closure in the second pass.
  304. def->came_from_user = true;
  305. }
  306. }
  307. // Second pass of validation. Also assign selector bases and indexes, and
  308. // compact tables.
  309. for (int i = 0; i < n; i++) {
  310. upb_msgdef *m = upb_dyncast_msgdef_mutable(defs[i]);
  311. upb_enumdef *e = upb_dyncast_enumdef_mutable(defs[i]);
  312. if (m) {
  313. upb_inttable_compact(&m->itof);
  314. if (!assign_msg_indices(m, s)) {
  315. goto err;
  316. }
  317. } else if (e) {
  318. upb_inttable_compact(&e->iton);
  319. }
  320. }
  321. // Def graph contains FieldDefs between each MessageDef, so double the limit.
  322. int maxdepth = UPB_MAX_MESSAGE_DEPTH * 2;
  323. // Validation all passed; freeze the defs.
  324. bool ret =
  325. upb_refcounted_freeze((upb_refcounted * const *)defs, n, s, maxdepth);
  326. assert(!(s && ret != upb_ok(s)));
  327. return ret;
  328. err:
  329. for (int i = 0; i < n; i++) {
  330. defs[i]->came_from_user = false;
  331. }
  332. assert(!(s && upb_ok(s)));
  333. return false;
  334. }
  335. /* upb_enumdef ****************************************************************/
  336. static void upb_enumdef_free(upb_refcounted *r) {
  337. upb_enumdef *e = (upb_enumdef*)r;
  338. upb_inttable_iter i;
  339. upb_inttable_begin(&i, &e->iton);
  340. for( ; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  341. // To clean up the upb_strdup() from upb_enumdef_addval().
  342. free(upb_value_getcstr(upb_inttable_iter_value(&i)));
  343. }
  344. upb_strtable_uninit(&e->ntoi);
  345. upb_inttable_uninit(&e->iton);
  346. upb_def_uninit(UPB_UPCAST(e));
  347. free(e);
  348. }
  349. upb_enumdef *upb_enumdef_new(const void *owner) {
  350. static const struct upb_refcounted_vtbl vtbl = {NULL, &upb_enumdef_free};
  351. upb_enumdef *e = malloc(sizeof(*e));
  352. if (!e) return NULL;
  353. if (!upb_def_init(UPB_UPCAST(e), UPB_DEF_ENUM, &vtbl, owner)) goto err2;
  354. if (!upb_strtable_init(&e->ntoi, UPB_CTYPE_INT32)) goto err2;
  355. if (!upb_inttable_init(&e->iton, UPB_CTYPE_CSTR)) goto err1;
  356. return e;
  357. err1:
  358. upb_strtable_uninit(&e->ntoi);
  359. err2:
  360. free(e);
  361. return NULL;
  362. }
  363. upb_enumdef *upb_enumdef_dup(const upb_enumdef *e, const void *owner) {
  364. upb_enumdef *new_e = upb_enumdef_new(owner);
  365. if (!new_e) return NULL;
  366. upb_enum_iter i;
  367. for(upb_enum_begin(&i, e); !upb_enum_done(&i); upb_enum_next(&i)) {
  368. bool success = upb_enumdef_addval(
  369. new_e, upb_enum_iter_name(&i),upb_enum_iter_number(&i), NULL);
  370. if (!success) {
  371. upb_enumdef_unref(new_e, owner);
  372. return NULL;
  373. }
  374. }
  375. return new_e;
  376. }
  377. bool upb_enumdef_isfrozen(const upb_enumdef *e) {
  378. return upb_def_isfrozen(UPB_UPCAST(e));
  379. }
  380. void upb_enumdef_ref(const upb_enumdef *e, const void *owner) {
  381. upb_def_ref(UPB_UPCAST(e), owner);
  382. }
  383. void upb_enumdef_unref(const upb_enumdef *e, const void *owner) {
  384. upb_def_unref(UPB_UPCAST(e), owner);
  385. }
  386. void upb_enumdef_donateref(
  387. const upb_enumdef *e, const void *from, const void *to) {
  388. upb_def_donateref(UPB_UPCAST(e), from, to);
  389. }
  390. void upb_enumdef_checkref(const upb_enumdef *e, const void *owner) {
  391. upb_def_checkref(UPB_UPCAST(e), owner);
  392. }
  393. bool upb_enumdef_freeze(upb_enumdef *e, upb_status *status) {
  394. upb_def *d = UPB_UPCAST(e);
  395. return upb_def_freeze(&d, 1, status);
  396. }
  397. const char *upb_enumdef_fullname(const upb_enumdef *e) {
  398. return upb_def_fullname(UPB_UPCAST(e));
  399. }
  400. bool upb_enumdef_setfullname(upb_enumdef *e, const char *fullname,
  401. upb_status *s) {
  402. return upb_def_setfullname(UPB_UPCAST(e), fullname, s);
  403. }
  404. bool upb_enumdef_addval(upb_enumdef *e, const char *name, int32_t num,
  405. upb_status *status) {
  406. if (!upb_isident(name, strlen(name), false, status)) {
  407. return false;
  408. }
  409. if (upb_enumdef_ntoiz(e, name, NULL)) {
  410. upb_status_seterrf(status, "name '%s' is already defined", name);
  411. return false;
  412. }
  413. if (!upb_strtable_insert(&e->ntoi, name, upb_value_int32(num))) {
  414. upb_status_seterrmsg(status, "out of memory");
  415. return false;
  416. }
  417. if (!upb_inttable_lookup(&e->iton, num, NULL) &&
  418. !upb_inttable_insert(&e->iton, num, upb_value_cstr(upb_strdup(name)))) {
  419. upb_status_seterrmsg(status, "out of memory");
  420. upb_strtable_remove(&e->ntoi, name, NULL);
  421. return false;
  422. }
  423. if (upb_enumdef_numvals(e) == 1) {
  424. bool ok = upb_enumdef_setdefault(e, num, NULL);
  425. UPB_ASSERT_VAR(ok, ok);
  426. }
  427. return true;
  428. }
  429. int32_t upb_enumdef_default(const upb_enumdef *e) {
  430. assert(upb_enumdef_iton(e, e->defaultval));
  431. return e->defaultval;
  432. }
  433. bool upb_enumdef_setdefault(upb_enumdef *e, int32_t val, upb_status *s) {
  434. assert(!upb_enumdef_isfrozen(e));
  435. if (!upb_enumdef_iton(e, val)) {
  436. upb_status_seterrf(s, "number '%d' is not in the enum.", val);
  437. return false;
  438. }
  439. e->defaultval = val;
  440. return true;
  441. }
  442. int upb_enumdef_numvals(const upb_enumdef *e) {
  443. return upb_strtable_count(&e->ntoi);
  444. }
  445. void upb_enum_begin(upb_enum_iter *i, const upb_enumdef *e) {
  446. // We iterate over the ntoi table, to account for duplicate numbers.
  447. upb_strtable_begin(i, &e->ntoi);
  448. }
  449. void upb_enum_next(upb_enum_iter *iter) { upb_strtable_next(iter); }
  450. bool upb_enum_done(upb_enum_iter *iter) { return upb_strtable_done(iter); }
  451. bool upb_enumdef_ntoi(const upb_enumdef *def, const char *name,
  452. size_t len, int32_t *num) {
  453. upb_value v;
  454. if (!upb_strtable_lookup2(&def->ntoi, name, len, &v)) {
  455. return false;
  456. }
  457. if (num) *num = upb_value_getint32(v);
  458. return true;
  459. }
  460. const char *upb_enumdef_iton(const upb_enumdef *def, int32_t num) {
  461. upb_value v;
  462. return upb_inttable_lookup32(&def->iton, num, &v) ?
  463. upb_value_getcstr(v) : NULL;
  464. }
  465. const char *upb_enum_iter_name(upb_enum_iter *iter) {
  466. return upb_strtable_iter_key(iter);
  467. }
  468. int32_t upb_enum_iter_number(upb_enum_iter *iter) {
  469. return upb_value_getint32(upb_strtable_iter_value(iter));
  470. }
  471. /* upb_fielddef ***************************************************************/
  472. static void upb_fielddef_init_default(upb_fielddef *f);
  473. static void upb_fielddef_uninit_default(upb_fielddef *f) {
  474. if (f->type_is_set_ && f->default_is_string && f->defaultval.bytes)
  475. freestr(f->defaultval.bytes);
  476. }
  477. static void visitfield(const upb_refcounted *r, upb_refcounted_visit *visit,
  478. void *closure) {
  479. const upb_fielddef *f = (const upb_fielddef*)r;
  480. if (upb_fielddef_containingtype(f)) {
  481. visit(r, UPB_UPCAST2(upb_fielddef_containingtype(f)), closure);
  482. }
  483. if (upb_fielddef_containingoneof(f)) {
  484. visit(r, UPB_UPCAST2(upb_fielddef_containingoneof(f)), closure);
  485. }
  486. if (upb_fielddef_subdef(f)) {
  487. visit(r, UPB_UPCAST(upb_fielddef_subdef(f)), closure);
  488. }
  489. }
  490. static void freefield(upb_refcounted *r) {
  491. upb_fielddef *f = (upb_fielddef*)r;
  492. upb_fielddef_uninit_default(f);
  493. if (f->subdef_is_symbolic)
  494. free(f->sub.name);
  495. upb_def_uninit(UPB_UPCAST(f));
  496. free(f);
  497. }
  498. static const char *enumdefaultstr(const upb_fielddef *f) {
  499. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  500. const upb_enumdef *e = upb_fielddef_enumsubdef(f);
  501. if (f->default_is_string && f->defaultval.bytes) {
  502. // Default was explicitly set as a string.
  503. str_t *s = f->defaultval.bytes;
  504. return s->str;
  505. } else if (e) {
  506. if (!f->default_is_string) {
  507. // Default was explicitly set as an integer; look it up in enumdef.
  508. const char *name = upb_enumdef_iton(e, f->defaultval.sint);
  509. if (name) {
  510. return name;
  511. }
  512. } else {
  513. // Default is completely unset; pull enumdef default.
  514. if (upb_enumdef_numvals(e) > 0) {
  515. const char *name = upb_enumdef_iton(e, upb_enumdef_default(e));
  516. assert(name);
  517. return name;
  518. }
  519. }
  520. }
  521. return NULL;
  522. }
  523. static bool enumdefaultint32(const upb_fielddef *f, int32_t *val) {
  524. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  525. const upb_enumdef *e = upb_fielddef_enumsubdef(f);
  526. if (!f->default_is_string) {
  527. // Default was explicitly set as an integer.
  528. *val = f->defaultval.sint;
  529. return true;
  530. } else if (e) {
  531. if (f->defaultval.bytes) {
  532. // Default was explicitly set as a str; try to lookup corresponding int.
  533. str_t *s = f->defaultval.bytes;
  534. if (upb_enumdef_ntoiz(e, s->str, val)) {
  535. return true;
  536. }
  537. } else {
  538. // Default is unset; try to pull in enumdef default.
  539. if (upb_enumdef_numvals(e) > 0) {
  540. *val = upb_enumdef_default(e);
  541. return true;
  542. }
  543. }
  544. }
  545. return false;
  546. }
  547. upb_fielddef *upb_fielddef_new(const void *owner) {
  548. static const struct upb_refcounted_vtbl vtbl = {visitfield, freefield};
  549. upb_fielddef *f = malloc(sizeof(*f));
  550. if (!f) return NULL;
  551. if (!upb_def_init(UPB_UPCAST(f), UPB_DEF_FIELD, &vtbl, owner)) {
  552. free(f);
  553. return NULL;
  554. }
  555. f->msg.def = NULL;
  556. f->sub.def = NULL;
  557. f->oneof = NULL;
  558. f->subdef_is_symbolic = false;
  559. f->msg_is_symbolic = false;
  560. f->label_ = UPB_LABEL_OPTIONAL;
  561. f->type_ = UPB_TYPE_INT32;
  562. f->number_ = 0;
  563. f->type_is_set_ = false;
  564. f->tagdelim = false;
  565. f->is_extension_ = false;
  566. f->lazy_ = false;
  567. f->packed_ = true;
  568. // For the moment we default this to UPB_INTFMT_VARIABLE, since it will work
  569. // with all integer types and is in some since more "default" since the most
  570. // normal-looking proto2 types int32/int64/uint32/uint64 use variable.
  571. //
  572. // Other options to consider:
  573. // - there is no default; users must set this manually (like type).
  574. // - default signed integers to UPB_INTFMT_ZIGZAG, since it's more likely to
  575. // be an optimal default for signed integers.
  576. f->intfmt = UPB_INTFMT_VARIABLE;
  577. return f;
  578. }
  579. upb_fielddef *upb_fielddef_dup(const upb_fielddef *f, const void *owner) {
  580. upb_fielddef *newf = upb_fielddef_new(owner);
  581. if (!newf) return NULL;
  582. upb_fielddef_settype(newf, upb_fielddef_type(f));
  583. upb_fielddef_setlabel(newf, upb_fielddef_label(f));
  584. upb_fielddef_setnumber(newf, upb_fielddef_number(f), NULL);
  585. upb_fielddef_setname(newf, upb_fielddef_name(f), NULL);
  586. if (f->default_is_string && f->defaultval.bytes) {
  587. str_t *s = f->defaultval.bytes;
  588. upb_fielddef_setdefaultstr(newf, s->str, s->len, NULL);
  589. } else {
  590. newf->default_is_string = f->default_is_string;
  591. newf->defaultval = f->defaultval;
  592. }
  593. const char *srcname;
  594. if (f->subdef_is_symbolic) {
  595. srcname = f->sub.name; // Might be NULL.
  596. } else {
  597. srcname = f->sub.def ? upb_def_fullname(f->sub.def) : NULL;
  598. }
  599. if (srcname) {
  600. char *newname = malloc(strlen(f->sub.def->fullname) + 2);
  601. if (!newname) {
  602. upb_fielddef_unref(newf, owner);
  603. return NULL;
  604. }
  605. strcpy(newname, ".");
  606. strcat(newname, f->sub.def->fullname);
  607. upb_fielddef_setsubdefname(newf, newname, NULL);
  608. free(newname);
  609. }
  610. return newf;
  611. }
  612. bool upb_fielddef_isfrozen(const upb_fielddef *f) {
  613. return upb_def_isfrozen(UPB_UPCAST(f));
  614. }
  615. void upb_fielddef_ref(const upb_fielddef *f, const void *owner) {
  616. upb_def_ref(UPB_UPCAST(f), owner);
  617. }
  618. void upb_fielddef_unref(const upb_fielddef *f, const void *owner) {
  619. upb_def_unref(UPB_UPCAST(f), owner);
  620. }
  621. void upb_fielddef_donateref(
  622. const upb_fielddef *f, const void *from, const void *to) {
  623. upb_def_donateref(UPB_UPCAST(f), from, to);
  624. }
  625. void upb_fielddef_checkref(const upb_fielddef *f, const void *owner) {
  626. upb_def_checkref(UPB_UPCAST(f), owner);
  627. }
  628. bool upb_fielddef_typeisset(const upb_fielddef *f) {
  629. return f->type_is_set_;
  630. }
  631. upb_fieldtype_t upb_fielddef_type(const upb_fielddef *f) {
  632. assert(f->type_is_set_);
  633. return f->type_;
  634. }
  635. uint32_t upb_fielddef_index(const upb_fielddef *f) {
  636. return f->index_;
  637. }
  638. upb_label_t upb_fielddef_label(const upb_fielddef *f) {
  639. return f->label_;
  640. }
  641. upb_intfmt_t upb_fielddef_intfmt(const upb_fielddef *f) {
  642. return f->intfmt;
  643. }
  644. bool upb_fielddef_istagdelim(const upb_fielddef *f) {
  645. return f->tagdelim;
  646. }
  647. uint32_t upb_fielddef_number(const upb_fielddef *f) {
  648. return f->number_;
  649. }
  650. bool upb_fielddef_isextension(const upb_fielddef *f) {
  651. return f->is_extension_;
  652. }
  653. bool upb_fielddef_lazy(const upb_fielddef *f) {
  654. return f->lazy_;
  655. }
  656. bool upb_fielddef_packed(const upb_fielddef *f) {
  657. return f->packed_;
  658. }
  659. const char *upb_fielddef_name(const upb_fielddef *f) {
  660. return upb_def_fullname(UPB_UPCAST(f));
  661. }
  662. const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f) {
  663. return f->msg_is_symbolic ? NULL : f->msg.def;
  664. }
  665. const upb_oneofdef *upb_fielddef_containingoneof(const upb_fielddef *f) {
  666. return f->oneof;
  667. }
  668. upb_msgdef *upb_fielddef_containingtype_mutable(upb_fielddef *f) {
  669. return (upb_msgdef*)upb_fielddef_containingtype(f);
  670. }
  671. const char *upb_fielddef_containingtypename(upb_fielddef *f) {
  672. return f->msg_is_symbolic ? f->msg.name : NULL;
  673. }
  674. static void release_containingtype(upb_fielddef *f) {
  675. if (f->msg_is_symbolic) free(f->msg.name);
  676. }
  677. bool upb_fielddef_setcontainingtypename(upb_fielddef *f, const char *name,
  678. upb_status *s) {
  679. assert(!upb_fielddef_isfrozen(f));
  680. if (upb_fielddef_containingtype(f)) {
  681. upb_status_seterrmsg(s, "field has already been added to a message.");
  682. return false;
  683. }
  684. // TODO: validate name (upb_isident() doesn't quite work atm because this name
  685. // may have a leading ".").
  686. release_containingtype(f);
  687. f->msg.name = upb_strdup(name);
  688. f->msg_is_symbolic = true;
  689. return true;
  690. }
  691. bool upb_fielddef_setname(upb_fielddef *f, const char *name, upb_status *s) {
  692. if (upb_fielddef_containingtype(f) || upb_fielddef_containingoneof(f)) {
  693. upb_status_seterrmsg(s, "Already added to message or oneof");
  694. return false;
  695. }
  696. return upb_def_setfullname(UPB_UPCAST(f), name, s);
  697. }
  698. static void chkdefaulttype(const upb_fielddef *f, upb_fieldtype_t type) {
  699. UPB_UNUSED(f);
  700. UPB_UNUSED(type);
  701. assert(f->type_is_set_ && upb_fielddef_type(f) == type);
  702. }
  703. int64_t upb_fielddef_defaultint64(const upb_fielddef *f) {
  704. chkdefaulttype(f, UPB_TYPE_INT64);
  705. return f->defaultval.sint;
  706. }
  707. int32_t upb_fielddef_defaultint32(const upb_fielddef *f) {
  708. if (f->type_is_set_ && upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  709. int32_t val;
  710. bool ok = enumdefaultint32(f, &val);
  711. UPB_ASSERT_VAR(ok, ok);
  712. return val;
  713. } else {
  714. chkdefaulttype(f, UPB_TYPE_INT32);
  715. return f->defaultval.sint;
  716. }
  717. }
  718. uint64_t upb_fielddef_defaultuint64(const upb_fielddef *f) {
  719. chkdefaulttype(f, UPB_TYPE_UINT64);
  720. return f->defaultval.uint;
  721. }
  722. uint32_t upb_fielddef_defaultuint32(const upb_fielddef *f) {
  723. chkdefaulttype(f, UPB_TYPE_UINT32);
  724. return f->defaultval.uint;
  725. }
  726. bool upb_fielddef_defaultbool(const upb_fielddef *f) {
  727. chkdefaulttype(f, UPB_TYPE_BOOL);
  728. return f->defaultval.uint;
  729. }
  730. float upb_fielddef_defaultfloat(const upb_fielddef *f) {
  731. chkdefaulttype(f, UPB_TYPE_FLOAT);
  732. return f->defaultval.flt;
  733. }
  734. double upb_fielddef_defaultdouble(const upb_fielddef *f) {
  735. chkdefaulttype(f, UPB_TYPE_DOUBLE);
  736. return f->defaultval.dbl;
  737. }
  738. const char *upb_fielddef_defaultstr(const upb_fielddef *f, size_t *len) {
  739. assert(f->type_is_set_);
  740. assert(upb_fielddef_type(f) == UPB_TYPE_STRING ||
  741. upb_fielddef_type(f) == UPB_TYPE_BYTES ||
  742. upb_fielddef_type(f) == UPB_TYPE_ENUM);
  743. if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  744. const char *ret = enumdefaultstr(f);
  745. assert(ret);
  746. // Enum defaults can't have embedded NULLs.
  747. if (len) *len = strlen(ret);
  748. return ret;
  749. }
  750. if (f->default_is_string) {
  751. str_t *str = f->defaultval.bytes;
  752. if (len) *len = str->len;
  753. return str->str;
  754. }
  755. return NULL;
  756. }
  757. static void upb_fielddef_init_default(upb_fielddef *f) {
  758. f->default_is_string = false;
  759. switch (upb_fielddef_type(f)) {
  760. case UPB_TYPE_DOUBLE: f->defaultval.dbl = 0; break;
  761. case UPB_TYPE_FLOAT: f->defaultval.flt = 0; break;
  762. case UPB_TYPE_INT32:
  763. case UPB_TYPE_INT64: f->defaultval.sint = 0; break;
  764. case UPB_TYPE_UINT64:
  765. case UPB_TYPE_UINT32:
  766. case UPB_TYPE_BOOL: f->defaultval.uint = 0; break;
  767. case UPB_TYPE_STRING:
  768. case UPB_TYPE_BYTES:
  769. f->defaultval.bytes = newstr("", 0);
  770. f->default_is_string = true;
  771. break;
  772. case UPB_TYPE_MESSAGE: break;
  773. case UPB_TYPE_ENUM:
  774. // This is our special sentinel that indicates "not set" for an enum.
  775. f->default_is_string = true;
  776. f->defaultval.bytes = NULL;
  777. break;
  778. }
  779. }
  780. const upb_def *upb_fielddef_subdef(const upb_fielddef *f) {
  781. return f->subdef_is_symbolic ? NULL : f->sub.def;
  782. }
  783. const upb_msgdef *upb_fielddef_msgsubdef(const upb_fielddef *f) {
  784. const upb_def *def = upb_fielddef_subdef(f);
  785. return def ? upb_dyncast_msgdef(def) : NULL;
  786. }
  787. const upb_enumdef *upb_fielddef_enumsubdef(const upb_fielddef *f) {
  788. const upb_def *def = upb_fielddef_subdef(f);
  789. return def ? upb_dyncast_enumdef(def) : NULL;
  790. }
  791. upb_def *upb_fielddef_subdef_mutable(upb_fielddef *f) {
  792. return (upb_def*)upb_fielddef_subdef(f);
  793. }
  794. const char *upb_fielddef_subdefname(const upb_fielddef *f) {
  795. if (f->subdef_is_symbolic) {
  796. return f->sub.name;
  797. } else if (f->sub.def) {
  798. return upb_def_fullname(f->sub.def);
  799. } else {
  800. return NULL;
  801. }
  802. }
  803. bool upb_fielddef_setnumber(upb_fielddef *f, uint32_t number, upb_status *s) {
  804. if (upb_fielddef_containingtype(f)) {
  805. upb_status_seterrmsg(
  806. s, "cannot change field number after adding to a message");
  807. return false;
  808. }
  809. if (number == 0 || number > UPB_MAX_FIELDNUMBER) {
  810. upb_status_seterrf(s, "invalid field number (%u)", number);
  811. return false;
  812. }
  813. f->number_ = number;
  814. return true;
  815. }
  816. void upb_fielddef_settype(upb_fielddef *f, upb_fieldtype_t type) {
  817. assert(!upb_fielddef_isfrozen(f));
  818. assert(upb_fielddef_checktype(type));
  819. upb_fielddef_uninit_default(f);
  820. f->type_ = type;
  821. f->type_is_set_ = true;
  822. upb_fielddef_init_default(f);
  823. }
  824. void upb_fielddef_setdescriptortype(upb_fielddef *f, int type) {
  825. assert(!upb_fielddef_isfrozen(f));
  826. switch (type) {
  827. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  828. upb_fielddef_settype(f, UPB_TYPE_DOUBLE);
  829. break;
  830. case UPB_DESCRIPTOR_TYPE_FLOAT:
  831. upb_fielddef_settype(f, UPB_TYPE_FLOAT);
  832. break;
  833. case UPB_DESCRIPTOR_TYPE_INT64:
  834. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  835. case UPB_DESCRIPTOR_TYPE_SINT64:
  836. upb_fielddef_settype(f, UPB_TYPE_INT64);
  837. break;
  838. case UPB_DESCRIPTOR_TYPE_UINT64:
  839. case UPB_DESCRIPTOR_TYPE_FIXED64:
  840. upb_fielddef_settype(f, UPB_TYPE_UINT64);
  841. break;
  842. case UPB_DESCRIPTOR_TYPE_INT32:
  843. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  844. case UPB_DESCRIPTOR_TYPE_SINT32:
  845. upb_fielddef_settype(f, UPB_TYPE_INT32);
  846. break;
  847. case UPB_DESCRIPTOR_TYPE_UINT32:
  848. case UPB_DESCRIPTOR_TYPE_FIXED32:
  849. upb_fielddef_settype(f, UPB_TYPE_UINT32);
  850. break;
  851. case UPB_DESCRIPTOR_TYPE_BOOL:
  852. upb_fielddef_settype(f, UPB_TYPE_BOOL);
  853. break;
  854. case UPB_DESCRIPTOR_TYPE_STRING:
  855. upb_fielddef_settype(f, UPB_TYPE_STRING);
  856. break;
  857. case UPB_DESCRIPTOR_TYPE_BYTES:
  858. upb_fielddef_settype(f, UPB_TYPE_BYTES);
  859. break;
  860. case UPB_DESCRIPTOR_TYPE_GROUP:
  861. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  862. upb_fielddef_settype(f, UPB_TYPE_MESSAGE);
  863. break;
  864. case UPB_DESCRIPTOR_TYPE_ENUM:
  865. upb_fielddef_settype(f, UPB_TYPE_ENUM);
  866. break;
  867. default: assert(false);
  868. }
  869. if (type == UPB_DESCRIPTOR_TYPE_FIXED64 ||
  870. type == UPB_DESCRIPTOR_TYPE_FIXED32 ||
  871. type == UPB_DESCRIPTOR_TYPE_SFIXED64 ||
  872. type == UPB_DESCRIPTOR_TYPE_SFIXED32) {
  873. upb_fielddef_setintfmt(f, UPB_INTFMT_FIXED);
  874. } else if (type == UPB_DESCRIPTOR_TYPE_SINT64 ||
  875. type == UPB_DESCRIPTOR_TYPE_SINT32) {
  876. upb_fielddef_setintfmt(f, UPB_INTFMT_ZIGZAG);
  877. } else {
  878. upb_fielddef_setintfmt(f, UPB_INTFMT_VARIABLE);
  879. }
  880. upb_fielddef_settagdelim(f, type == UPB_DESCRIPTOR_TYPE_GROUP);
  881. }
  882. upb_descriptortype_t upb_fielddef_descriptortype(const upb_fielddef *f) {
  883. switch (upb_fielddef_type(f)) {
  884. case UPB_TYPE_FLOAT: return UPB_DESCRIPTOR_TYPE_FLOAT;
  885. case UPB_TYPE_DOUBLE: return UPB_DESCRIPTOR_TYPE_DOUBLE;
  886. case UPB_TYPE_BOOL: return UPB_DESCRIPTOR_TYPE_BOOL;
  887. case UPB_TYPE_STRING: return UPB_DESCRIPTOR_TYPE_STRING;
  888. case UPB_TYPE_BYTES: return UPB_DESCRIPTOR_TYPE_BYTES;
  889. case UPB_TYPE_ENUM: return UPB_DESCRIPTOR_TYPE_ENUM;
  890. case UPB_TYPE_INT32:
  891. switch (upb_fielddef_intfmt(f)) {
  892. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT32;
  893. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED32;
  894. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT32;
  895. }
  896. case UPB_TYPE_INT64:
  897. switch (upb_fielddef_intfmt(f)) {
  898. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT64;
  899. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED64;
  900. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT64;
  901. }
  902. case UPB_TYPE_UINT32:
  903. switch (upb_fielddef_intfmt(f)) {
  904. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT32;
  905. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED32;
  906. case UPB_INTFMT_ZIGZAG: return -1;
  907. }
  908. case UPB_TYPE_UINT64:
  909. switch (upb_fielddef_intfmt(f)) {
  910. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT64;
  911. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED64;
  912. case UPB_INTFMT_ZIGZAG: return -1;
  913. }
  914. case UPB_TYPE_MESSAGE:
  915. return upb_fielddef_istagdelim(f) ?
  916. UPB_DESCRIPTOR_TYPE_GROUP : UPB_DESCRIPTOR_TYPE_MESSAGE;
  917. }
  918. return 0;
  919. }
  920. void upb_fielddef_setisextension(upb_fielddef *f, bool is_extension) {
  921. assert(!upb_fielddef_isfrozen(f));
  922. f->is_extension_ = is_extension;
  923. }
  924. void upb_fielddef_setlazy(upb_fielddef *f, bool lazy) {
  925. assert(!upb_fielddef_isfrozen(f));
  926. f->lazy_ = lazy;
  927. }
  928. void upb_fielddef_setpacked(upb_fielddef *f, bool packed) {
  929. assert(!upb_fielddef_isfrozen(f));
  930. f->packed_ = packed;
  931. }
  932. void upb_fielddef_setlabel(upb_fielddef *f, upb_label_t label) {
  933. assert(!upb_fielddef_isfrozen(f));
  934. assert(upb_fielddef_checklabel(label));
  935. f->label_ = label;
  936. }
  937. void upb_fielddef_setintfmt(upb_fielddef *f, upb_intfmt_t fmt) {
  938. assert(!upb_fielddef_isfrozen(f));
  939. assert(upb_fielddef_checkintfmt(fmt));
  940. f->intfmt = fmt;
  941. }
  942. void upb_fielddef_settagdelim(upb_fielddef *f, bool tag_delim) {
  943. assert(!upb_fielddef_isfrozen(f));
  944. f->tagdelim = tag_delim;
  945. f->tagdelim = tag_delim;
  946. }
  947. static bool checksetdefault(upb_fielddef *f, upb_fieldtype_t type) {
  948. if (!f->type_is_set_ || upb_fielddef_isfrozen(f) ||
  949. upb_fielddef_type(f) != type) {
  950. assert(false);
  951. return false;
  952. }
  953. if (f->default_is_string) {
  954. str_t *s = f->defaultval.bytes;
  955. assert(s || type == UPB_TYPE_ENUM);
  956. if (s) freestr(s);
  957. }
  958. f->default_is_string = false;
  959. return true;
  960. }
  961. void upb_fielddef_setdefaultint64(upb_fielddef *f, int64_t value) {
  962. if (checksetdefault(f, UPB_TYPE_INT64))
  963. f->defaultval.sint = value;
  964. }
  965. void upb_fielddef_setdefaultint32(upb_fielddef *f, int32_t value) {
  966. if ((upb_fielddef_type(f) == UPB_TYPE_ENUM &&
  967. checksetdefault(f, UPB_TYPE_ENUM)) ||
  968. checksetdefault(f, UPB_TYPE_INT32)) {
  969. f->defaultval.sint = value;
  970. }
  971. }
  972. void upb_fielddef_setdefaultuint64(upb_fielddef *f, uint64_t value) {
  973. if (checksetdefault(f, UPB_TYPE_UINT64))
  974. f->defaultval.uint = value;
  975. }
  976. void upb_fielddef_setdefaultuint32(upb_fielddef *f, uint32_t value) {
  977. if (checksetdefault(f, UPB_TYPE_UINT32))
  978. f->defaultval.uint = value;
  979. }
  980. void upb_fielddef_setdefaultbool(upb_fielddef *f, bool value) {
  981. if (checksetdefault(f, UPB_TYPE_BOOL))
  982. f->defaultval.uint = value;
  983. }
  984. void upb_fielddef_setdefaultfloat(upb_fielddef *f, float value) {
  985. if (checksetdefault(f, UPB_TYPE_FLOAT))
  986. f->defaultval.flt = value;
  987. }
  988. void upb_fielddef_setdefaultdouble(upb_fielddef *f, double value) {
  989. if (checksetdefault(f, UPB_TYPE_DOUBLE))
  990. f->defaultval.dbl = value;
  991. }
  992. bool upb_fielddef_setdefaultstr(upb_fielddef *f, const void *str, size_t len,
  993. upb_status *s) {
  994. assert(upb_fielddef_isstring(f) || f->type_ == UPB_TYPE_ENUM);
  995. if (f->type_ == UPB_TYPE_ENUM && !upb_isident(str, len, false, s))
  996. return false;
  997. if (f->default_is_string) {
  998. str_t *s = f->defaultval.bytes;
  999. assert(s || f->type_ == UPB_TYPE_ENUM);
  1000. if (s) freestr(s);
  1001. } else {
  1002. assert(f->type_ == UPB_TYPE_ENUM);
  1003. }
  1004. str_t *str2 = newstr(str, len);
  1005. f->defaultval.bytes = str2;
  1006. f->default_is_string = true;
  1007. return true;
  1008. }
  1009. void upb_fielddef_setdefaultcstr(upb_fielddef *f, const char *str,
  1010. upb_status *s) {
  1011. assert(f->type_is_set_);
  1012. upb_fielddef_setdefaultstr(f, str, str ? strlen(str) : 0, s);
  1013. }
  1014. bool upb_fielddef_enumhasdefaultint32(const upb_fielddef *f) {
  1015. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  1016. int32_t val;
  1017. return enumdefaultint32(f, &val);
  1018. }
  1019. bool upb_fielddef_enumhasdefaultstr(const upb_fielddef *f) {
  1020. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  1021. return enumdefaultstr(f) != NULL;
  1022. }
  1023. static bool upb_subdef_typecheck(upb_fielddef *f, const upb_def *subdef,
  1024. upb_status *s) {
  1025. if (f->type_ == UPB_TYPE_MESSAGE) {
  1026. if (upb_dyncast_msgdef(subdef)) return true;
  1027. upb_status_seterrmsg(s, "invalid subdef type for this submessage field");
  1028. return false;
  1029. } else if (f->type_ == UPB_TYPE_ENUM) {
  1030. if (upb_dyncast_enumdef(subdef)) return true;
  1031. upb_status_seterrmsg(s, "invalid subdef type for this enum field");
  1032. return false;
  1033. } else {
  1034. upb_status_seterrmsg(s, "only message and enum fields can have a subdef");
  1035. return false;
  1036. }
  1037. }
  1038. static void release_subdef(upb_fielddef *f) {
  1039. if (f->subdef_is_symbolic) {
  1040. free(f->sub.name);
  1041. } else if (f->sub.def) {
  1042. upb_unref2(f->sub.def, f);
  1043. }
  1044. }
  1045. bool upb_fielddef_setsubdef(upb_fielddef *f, const upb_def *subdef,
  1046. upb_status *s) {
  1047. assert(!upb_fielddef_isfrozen(f));
  1048. assert(upb_fielddef_hassubdef(f));
  1049. if (subdef && !upb_subdef_typecheck(f, subdef, s)) return false;
  1050. release_subdef(f);
  1051. f->sub.def = subdef;
  1052. f->subdef_is_symbolic = false;
  1053. if (f->sub.def) upb_ref2(f->sub.def, f);
  1054. return true;
  1055. }
  1056. bool upb_fielddef_setmsgsubdef(upb_fielddef *f, const upb_msgdef *subdef,
  1057. upb_status *s) {
  1058. return upb_fielddef_setsubdef(f, UPB_UPCAST(subdef), s);
  1059. }
  1060. bool upb_fielddef_setenumsubdef(upb_fielddef *f, const upb_enumdef *subdef,
  1061. upb_status *s) {
  1062. return upb_fielddef_setsubdef(f, UPB_UPCAST(subdef), s);
  1063. }
  1064. bool upb_fielddef_setsubdefname(upb_fielddef *f, const char *name,
  1065. upb_status *s) {
  1066. assert(!upb_fielddef_isfrozen(f));
  1067. if (!upb_fielddef_hassubdef(f)) {
  1068. upb_status_seterrmsg(s, "field type does not accept a subdef");
  1069. return false;
  1070. }
  1071. // TODO: validate name (upb_isident() doesn't quite work atm because this name
  1072. // may have a leading ".").
  1073. release_subdef(f);
  1074. f->sub.name = upb_strdup(name);
  1075. f->subdef_is_symbolic = true;
  1076. return true;
  1077. }
  1078. bool upb_fielddef_issubmsg(const upb_fielddef *f) {
  1079. return upb_fielddef_type(f) == UPB_TYPE_MESSAGE;
  1080. }
  1081. bool upb_fielddef_isstring(const upb_fielddef *f) {
  1082. return upb_fielddef_type(f) == UPB_TYPE_STRING ||
  1083. upb_fielddef_type(f) == UPB_TYPE_BYTES;
  1084. }
  1085. bool upb_fielddef_isseq(const upb_fielddef *f) {
  1086. return upb_fielddef_label(f) == UPB_LABEL_REPEATED;
  1087. }
  1088. bool upb_fielddef_isprimitive(const upb_fielddef *f) {
  1089. return !upb_fielddef_isstring(f) && !upb_fielddef_issubmsg(f);
  1090. }
  1091. bool upb_fielddef_ismap(const upb_fielddef *f) {
  1092. return upb_fielddef_isseq(f) && upb_fielddef_issubmsg(f) &&
  1093. upb_msgdef_mapentry(upb_fielddef_msgsubdef(f));
  1094. }
  1095. bool upb_fielddef_hassubdef(const upb_fielddef *f) {
  1096. return upb_fielddef_issubmsg(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM;
  1097. }
  1098. static bool between(int32_t x, int32_t low, int32_t high) {
  1099. return x >= low && x <= high;
  1100. }
  1101. bool upb_fielddef_checklabel(int32_t label) { return between(label, 1, 3); }
  1102. bool upb_fielddef_checktype(int32_t type) { return between(type, 1, 11); }
  1103. bool upb_fielddef_checkintfmt(int32_t fmt) { return between(fmt, 1, 3); }
  1104. bool upb_fielddef_checkdescriptortype(int32_t type) {
  1105. return between(type, 1, 18);
  1106. }
  1107. /* upb_msgdef *****************************************************************/
  1108. static void visitmsg(const upb_refcounted *r, upb_refcounted_visit *visit,
  1109. void *closure) {
  1110. const upb_msgdef *m = (const upb_msgdef*)r;
  1111. upb_msg_field_iter i;
  1112. for(upb_msg_field_begin(&i, m);
  1113. !upb_msg_field_done(&i);
  1114. upb_msg_field_next(&i)) {
  1115. upb_fielddef *f = upb_msg_iter_field(&i);
  1116. visit(r, UPB_UPCAST2(f), closure);
  1117. }
  1118. upb_msg_oneof_iter o;
  1119. for(upb_msg_oneof_begin(&o, m);
  1120. !upb_msg_oneof_done(&o);
  1121. upb_msg_oneof_next(&o)) {
  1122. upb_oneofdef *f = upb_msg_iter_oneof(&o);
  1123. visit(r, UPB_UPCAST2(f), closure);
  1124. }
  1125. }
  1126. static void freemsg(upb_refcounted *r) {
  1127. upb_msgdef *m = (upb_msgdef*)r;
  1128. upb_strtable_uninit(&m->ntoo);
  1129. upb_strtable_uninit(&m->ntof);
  1130. upb_inttable_uninit(&m->itof);
  1131. upb_def_uninit(UPB_UPCAST(m));
  1132. free(m);
  1133. }
  1134. upb_msgdef *upb_msgdef_new(const void *owner) {
  1135. static const struct upb_refcounted_vtbl vtbl = {visitmsg, freemsg};
  1136. upb_msgdef *m = malloc(sizeof(*m));
  1137. if (!m) return NULL;
  1138. if (!upb_def_init(UPB_UPCAST(m), UPB_DEF_MSG, &vtbl, owner)) goto err2;
  1139. if (!upb_inttable_init(&m->itof, UPB_CTYPE_PTR)) goto err3;
  1140. if (!upb_strtable_init(&m->ntof, UPB_CTYPE_PTR)) goto err2;
  1141. if (!upb_strtable_init(&m->ntoo, UPB_CTYPE_PTR)) goto err1;
  1142. m->map_entry = false;
  1143. return m;
  1144. err1:
  1145. upb_strtable_uninit(&m->ntof);
  1146. err2:
  1147. upb_inttable_uninit(&m->itof);
  1148. err3:
  1149. free(m);
  1150. return NULL;
  1151. }
  1152. upb_msgdef *upb_msgdef_dup(const upb_msgdef *m, const void *owner) {
  1153. upb_msgdef *newm = upb_msgdef_new(owner);
  1154. if (!newm) return NULL;
  1155. bool ok = upb_def_setfullname(UPB_UPCAST(newm),
  1156. upb_def_fullname(UPB_UPCAST(m)), NULL);
  1157. newm->map_entry = m->map_entry;
  1158. UPB_ASSERT_VAR(ok, ok);
  1159. upb_msg_field_iter i;
  1160. for(upb_msg_field_begin(&i, m);
  1161. !upb_msg_field_done(&i);
  1162. upb_msg_field_next(&i)) {
  1163. upb_fielddef *f = upb_fielddef_dup(upb_msg_iter_field(&i), &f);
  1164. // Fields in oneofs are dup'd below.
  1165. if (upb_fielddef_containingoneof(f)) continue;
  1166. if (!f || !upb_msgdef_addfield(newm, f, &f, NULL)) {
  1167. upb_msgdef_unref(newm, owner);
  1168. return NULL;
  1169. }
  1170. }
  1171. upb_msg_oneof_iter o;
  1172. for(upb_msg_oneof_begin(&o, m);
  1173. !upb_msg_oneof_done(&o);
  1174. upb_msg_oneof_next(&o)) {
  1175. upb_oneofdef *f = upb_oneofdef_dup(upb_msg_iter_oneof(&o), &f);
  1176. if (!f || !upb_msgdef_addoneof(newm, f, &f, NULL)) {
  1177. upb_msgdef_unref(newm, owner);
  1178. return NULL;
  1179. }
  1180. }
  1181. return newm;
  1182. }
  1183. bool upb_msgdef_isfrozen(const upb_msgdef *m) {
  1184. return upb_def_isfrozen(UPB_UPCAST(m));
  1185. }
  1186. void upb_msgdef_ref(const upb_msgdef *m, const void *owner) {
  1187. upb_def_ref(UPB_UPCAST(m), owner);
  1188. }
  1189. void upb_msgdef_unref(const upb_msgdef *m, const void *owner) {
  1190. upb_def_unref(UPB_UPCAST(m), owner);
  1191. }
  1192. void upb_msgdef_donateref(
  1193. const upb_msgdef *m, const void *from, const void *to) {
  1194. upb_def_donateref(UPB_UPCAST(m), from, to);
  1195. }
  1196. void upb_msgdef_checkref(const upb_msgdef *m, const void *owner) {
  1197. upb_def_checkref(UPB_UPCAST(m), owner);
  1198. }
  1199. bool upb_msgdef_freeze(upb_msgdef *m, upb_status *status) {
  1200. upb_def *d = UPB_UPCAST(m);
  1201. return upb_def_freeze(&d, 1, status);
  1202. }
  1203. const char *upb_msgdef_fullname(const upb_msgdef *m) {
  1204. return upb_def_fullname(UPB_UPCAST(m));
  1205. }
  1206. bool upb_msgdef_setfullname(upb_msgdef *m, const char *fullname,
  1207. upb_status *s) {
  1208. return upb_def_setfullname(UPB_UPCAST(m), fullname, s);
  1209. }
  1210. // Helper: check that the field |f| is safe to add to msgdef |m|. Set an error
  1211. // on status |s| and return false if not.
  1212. static bool check_field_add(const upb_msgdef *m, const upb_fielddef *f,
  1213. upb_status *s) {
  1214. if (upb_fielddef_containingtype(f) != NULL) {
  1215. upb_status_seterrmsg(s, "fielddef already belongs to a message");
  1216. return false;
  1217. } else if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  1218. upb_status_seterrmsg(s, "field name or number were not set");
  1219. return false;
  1220. } else if (upb_msgdef_ntofz(m, upb_fielddef_name(f)) ||
  1221. upb_msgdef_itof(m, upb_fielddef_number(f))) {
  1222. upb_status_seterrmsg(s, "duplicate field name or number for field");
  1223. return false;
  1224. }
  1225. return true;
  1226. }
  1227. static void add_field(upb_msgdef *m, upb_fielddef *f, const void *ref_donor) {
  1228. release_containingtype(f);
  1229. f->msg.def = m;
  1230. f->msg_is_symbolic = false;
  1231. upb_inttable_insert(&m->itof, upb_fielddef_number(f), upb_value_ptr(f));
  1232. upb_strtable_insert(&m->ntof, upb_fielddef_name(f), upb_value_ptr(f));
  1233. upb_ref2(f, m);
  1234. upb_ref2(m, f);
  1235. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  1236. }
  1237. bool upb_msgdef_addfield(upb_msgdef *m, upb_fielddef *f, const void *ref_donor,
  1238. upb_status *s) {
  1239. // TODO: extensions need to have a separate namespace, because proto2 allows a
  1240. // top-level extension (ie. one not in any package) to have the same name as a
  1241. // field from the message.
  1242. //
  1243. // This also implies that there needs to be a separate lookup-by-name method
  1244. // for extensions. It seems desirable for iteration to return both extensions
  1245. // and non-extensions though.
  1246. //
  1247. // We also need to validate that the field number is in an extension range iff
  1248. // it is an extension.
  1249. // This method is idempotent. Check if |f| is already part of this msgdef and
  1250. // return immediately if so.
  1251. if (upb_fielddef_containingtype(f) == m) {
  1252. return true;
  1253. }
  1254. // Check constraints for all fields before performing any action.
  1255. if (!check_field_add(m, f, s)) {
  1256. return false;
  1257. } else if (upb_fielddef_containingoneof(f) != NULL) {
  1258. // Fields in a oneof can only be added by adding the oneof to the msgdef.
  1259. upb_status_seterrmsg(s, "fielddef is part of a oneof");
  1260. return false;
  1261. }
  1262. // Constraint checks ok, perform the action.
  1263. add_field(m, f, ref_donor);
  1264. return true;
  1265. }
  1266. bool upb_msgdef_addoneof(upb_msgdef *m, upb_oneofdef *o, const void *ref_donor,
  1267. upb_status *s) {
  1268. // Check various conditions that would prevent this oneof from being added.
  1269. if (upb_oneofdef_containingtype(o)) {
  1270. upb_status_seterrmsg(s, "oneofdef already belongs to a message");
  1271. return false;
  1272. } else if (upb_oneofdef_name(o) == NULL) {
  1273. upb_status_seterrmsg(s, "oneofdef name was not set");
  1274. return false;
  1275. } else if (upb_msgdef_ntooz(m, upb_oneofdef_name(o))) {
  1276. upb_status_seterrmsg(s, "duplicate oneof name");
  1277. return false;
  1278. }
  1279. // Check that all of the oneof's fields do not conflict with names or numbers
  1280. // of fields already in the message.
  1281. upb_oneof_iter it;
  1282. for (upb_oneof_begin(&it, o); !upb_oneof_done(&it); upb_oneof_next(&it)) {
  1283. const upb_fielddef *f = upb_oneof_iter_field(&it);
  1284. if (!check_field_add(m, f, s)) {
  1285. return false;
  1286. }
  1287. }
  1288. // Everything checks out -- commit now.
  1289. // Add oneof itself first.
  1290. o->parent = m;
  1291. upb_strtable_insert(&m->ntoo, upb_oneofdef_name(o), upb_value_ptr(o));
  1292. upb_ref2(o, m);
  1293. upb_ref2(m, o);
  1294. // Add each field of the oneof directly to the msgdef.
  1295. for (upb_oneof_begin(&it, o); !upb_oneof_done(&it); upb_oneof_next(&it)) {
  1296. upb_fielddef *f = upb_oneof_iter_field(&it);
  1297. add_field(m, f, NULL);
  1298. }
  1299. if (ref_donor) upb_oneofdef_unref(o, ref_donor);
  1300. return true;
  1301. }
  1302. const upb_fielddef *upb_msgdef_itof(const upb_msgdef *m, uint32_t i) {
  1303. upb_value val;
  1304. return upb_inttable_lookup32(&m->itof, i, &val) ?
  1305. upb_value_getptr(val) : NULL;
  1306. }
  1307. const upb_fielddef *upb_msgdef_ntof(const upb_msgdef *m, const char *name,
  1308. size_t len) {
  1309. upb_value val;
  1310. return upb_strtable_lookup2(&m->ntof, name, len, &val) ?
  1311. upb_value_getptr(val) : NULL;
  1312. }
  1313. const upb_oneofdef *upb_msgdef_ntoo(const upb_msgdef *m, const char *name,
  1314. size_t len) {
  1315. upb_value val;
  1316. return upb_strtable_lookup2(&m->ntoo, name, len, &val) ?
  1317. upb_value_getptr(val) : NULL;
  1318. }
  1319. int upb_msgdef_numfields(const upb_msgdef *m) {
  1320. return upb_strtable_count(&m->ntof);
  1321. }
  1322. int upb_msgdef_numoneofs(const upb_msgdef *m) {
  1323. return upb_strtable_count(&m->ntoo);
  1324. }
  1325. void upb_msgdef_setmapentry(upb_msgdef *m, bool map_entry) {
  1326. assert(!upb_msgdef_isfrozen(m));
  1327. m->map_entry = map_entry;
  1328. }
  1329. bool upb_msgdef_mapentry(const upb_msgdef *m) {
  1330. return m->map_entry;
  1331. }
  1332. void upb_msg_field_begin(upb_msg_field_iter *iter, const upb_msgdef *m) {
  1333. upb_inttable_begin(iter, &m->itof);
  1334. }
  1335. void upb_msg_field_next(upb_msg_field_iter *iter) { upb_inttable_next(iter); }
  1336. bool upb_msg_field_done(const upb_msg_field_iter *iter) {
  1337. return upb_inttable_done(iter);
  1338. }
  1339. upb_fielddef *upb_msg_iter_field(const upb_msg_field_iter *iter) {
  1340. return (upb_fielddef*)upb_value_getptr(upb_inttable_iter_value(iter));
  1341. }
  1342. void upb_msg_field_iter_setdone(upb_msg_field_iter *iter) {
  1343. upb_inttable_iter_setdone(iter);
  1344. }
  1345. void upb_msg_oneof_begin(upb_msg_oneof_iter *iter, const upb_msgdef *m) {
  1346. upb_strtable_begin(iter, &m->ntoo);
  1347. }
  1348. void upb_msg_oneof_next(upb_msg_oneof_iter *iter) { upb_strtable_next(iter); }
  1349. bool upb_msg_oneof_done(const upb_msg_oneof_iter *iter) {
  1350. return upb_strtable_done(iter);
  1351. }
  1352. upb_oneofdef *upb_msg_iter_oneof(const upb_msg_oneof_iter *iter) {
  1353. return (upb_oneofdef*)upb_value_getptr(upb_strtable_iter_value(iter));
  1354. }
  1355. void upb_msg_oneof_iter_setdone(upb_msg_oneof_iter *iter) {
  1356. upb_strtable_iter_setdone(iter);
  1357. }
  1358. /* upb_oneofdef ***************************************************************/
  1359. static void visitoneof(const upb_refcounted *r, upb_refcounted_visit *visit,
  1360. void *closure) {
  1361. const upb_oneofdef *o = (const upb_oneofdef*)r;
  1362. upb_oneof_iter i;
  1363. for (upb_oneof_begin(&i, o); !upb_oneof_done(&i); upb_oneof_next(&i)) {
  1364. const upb_fielddef *f = upb_oneof_iter_field(&i);
  1365. visit(r, UPB_UPCAST2(f), closure);
  1366. }
  1367. if (o->parent) {
  1368. visit(r, UPB_UPCAST2(o->parent), closure);
  1369. }
  1370. }
  1371. static void freeoneof(upb_refcounted *r) {
  1372. upb_oneofdef *o = (upb_oneofdef*)r;
  1373. upb_strtable_uninit(&o->ntof);
  1374. upb_inttable_uninit(&o->itof);
  1375. upb_def_uninit(UPB_UPCAST(o));
  1376. free(o);
  1377. }
  1378. upb_oneofdef *upb_oneofdef_new(const void *owner) {
  1379. static const struct upb_refcounted_vtbl vtbl = {visitoneof, freeoneof};
  1380. upb_oneofdef *o = malloc(sizeof(*o));
  1381. o->parent = NULL;
  1382. if (!o) return NULL;
  1383. if (!upb_def_init(UPB_UPCAST(o), UPB_DEF_ONEOF, &vtbl, owner)) goto err2;
  1384. if (!upb_inttable_init(&o->itof, UPB_CTYPE_PTR)) goto err2;
  1385. if (!upb_strtable_init(&o->ntof, UPB_CTYPE_PTR)) goto err1;
  1386. return o;
  1387. err1:
  1388. upb_inttable_uninit(&o->itof);
  1389. err2:
  1390. free(o);
  1391. return NULL;
  1392. }
  1393. upb_oneofdef *upb_oneofdef_dup(const upb_oneofdef *o, const void *owner) {
  1394. upb_oneofdef *newo = upb_oneofdef_new(owner);
  1395. if (!newo) return NULL;
  1396. bool ok = upb_def_setfullname(UPB_UPCAST(newo),
  1397. upb_def_fullname(UPB_UPCAST(o)), NULL);
  1398. UPB_ASSERT_VAR(ok, ok);
  1399. upb_oneof_iter i;
  1400. for (upb_oneof_begin(&i, o); !upb_oneof_done(&i); upb_oneof_next(&i)) {
  1401. upb_fielddef *f = upb_fielddef_dup(upb_oneof_iter_field(&i), &f);
  1402. if (!f || !upb_oneofdef_addfield(newo, f, &f, NULL)) {
  1403. upb_oneofdef_unref(newo, owner);
  1404. return NULL;
  1405. }
  1406. }
  1407. return newo;
  1408. }
  1409. bool upb_oneofdef_isfrozen(const upb_oneofdef *o) {
  1410. return upb_def_isfrozen(UPB_UPCAST(o));
  1411. }
  1412. void upb_oneofdef_ref(const upb_oneofdef *o, const void *owner) {
  1413. upb_def_ref(UPB_UPCAST(o), owner);
  1414. }
  1415. void upb_oneofdef_unref(const upb_oneofdef *o, const void *owner) {
  1416. upb_def_unref(UPB_UPCAST(o), owner);
  1417. }
  1418. void upb_oneofdef_donateref(const upb_oneofdef *o, const void *from,
  1419. const void *to) {
  1420. upb_def_donateref(UPB_UPCAST(o), from, to);
  1421. }
  1422. void upb_oneofdef_checkref(const upb_oneofdef *o, const void *owner) {
  1423. upb_def_checkref(UPB_UPCAST(o), owner);
  1424. }
  1425. const char *upb_oneofdef_name(const upb_oneofdef *o) {
  1426. return upb_def_fullname(UPB_UPCAST(o));
  1427. }
  1428. bool upb_oneofdef_setname(upb_oneofdef *o, const char *fullname,
  1429. upb_status *s) {
  1430. if (upb_oneofdef_containingtype(o)) {
  1431. upb_status_seterrmsg(s, "oneof already added to a message");
  1432. return false;
  1433. }
  1434. return upb_def_setfullname(UPB_UPCAST(o), fullname, s);
  1435. }
  1436. const upb_msgdef *upb_oneofdef_containingtype(const upb_oneofdef *o) {
  1437. return o->parent;
  1438. }
  1439. int upb_oneofdef_numfields(const upb_oneofdef *o) {
  1440. return upb_strtable_count(&o->ntof);
  1441. }
  1442. bool upb_oneofdef_addfield(upb_oneofdef *o, upb_fielddef *f,
  1443. const void *ref_donor,
  1444. upb_status *s) {
  1445. assert(!upb_oneofdef_isfrozen(o));
  1446. assert(!o->parent || !upb_msgdef_isfrozen(o->parent));
  1447. // This method is idempotent. Check if |f| is already part of this oneofdef
  1448. // and return immediately if so.
  1449. if (upb_fielddef_containingoneof(f) == o) {
  1450. return true;
  1451. }
  1452. // The field must have an OPTIONAL label.
  1453. if (upb_fielddef_label(f) != UPB_LABEL_OPTIONAL) {
  1454. upb_status_seterrmsg(s, "fields in oneof must have OPTIONAL label");
  1455. return false;
  1456. }
  1457. // Check that no field with this name or number exists already in the oneof.
  1458. // Also check that the field is not already part of a oneof.
  1459. if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  1460. upb_status_seterrmsg(s, "field name or number were not set");
  1461. return false;
  1462. } else if (upb_oneofdef_itof(o, upb_fielddef_number(f)) ||
  1463. upb_oneofdef_ntofz(o, upb_fielddef_name(f))) {
  1464. upb_status_seterrmsg(s, "duplicate field name or number");
  1465. return false;
  1466. } else if (upb_fielddef_containingoneof(f) != NULL) {
  1467. upb_status_seterrmsg(s, "fielddef already belongs to a oneof");
  1468. return false;
  1469. }
  1470. // We allow adding a field to the oneof either if the field is not part of a
  1471. // msgdef, or if it is and we are also part of the same msgdef.
  1472. if (o->parent == NULL) {
  1473. // If we're not in a msgdef, the field cannot be either. Otherwise we would
  1474. // need to magically add this oneof to a msgdef to remain consistent, which
  1475. // is surprising behavior.
  1476. if (upb_fielddef_containingtype(f) != NULL) {
  1477. upb_status_seterrmsg(s, "fielddef already belongs to a message, but "
  1478. "oneof does not");
  1479. return false;
  1480. }
  1481. } else {
  1482. // If we're in a msgdef, the user can add fields that either aren't in any
  1483. // msgdef (in which case they're added to our msgdef) or already a part of
  1484. // our msgdef.
  1485. if (upb_fielddef_containingtype(f) != NULL &&
  1486. upb_fielddef_containingtype(f) != o->parent) {
  1487. upb_status_seterrmsg(s, "fielddef belongs to a different message "
  1488. "than oneof");
  1489. return false;
  1490. }
  1491. }
  1492. // Commit phase. First add the field to our parent msgdef, if any, because
  1493. // that may fail; then add the field to our own tables.
  1494. if (o->parent != NULL && upb_fielddef_containingtype(f) == NULL) {
  1495. if (!upb_msgdef_addfield((upb_msgdef*)o->parent, f, NULL, s)) {
  1496. return false;
  1497. }
  1498. }
  1499. release_containingtype(f);
  1500. f->oneof = o;
  1501. upb_inttable_insert(&o->itof, upb_fielddef_number(f), upb_value_ptr(f));
  1502. upb_strtable_insert(&o->ntof, upb_fielddef_name(f), upb_value_ptr(f));
  1503. upb_ref2(f, o);
  1504. upb_ref2(o, f);
  1505. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  1506. return true;
  1507. }
  1508. const upb_fielddef *upb_oneofdef_ntof(const upb_oneofdef *o,
  1509. const char *name, size_t length) {
  1510. upb_value val;
  1511. return upb_strtable_lookup2(&o->ntof, name, length, &val) ?
  1512. upb_value_getptr(val) : NULL;
  1513. }
  1514. const upb_fielddef *upb_oneofdef_itof(const upb_oneofdef *o, uint32_t num) {
  1515. upb_value val;
  1516. return upb_inttable_lookup32(&o->itof, num, &val) ?
  1517. upb_value_getptr(val) : NULL;
  1518. }
  1519. void upb_oneof_begin(upb_oneof_iter *iter, const upb_oneofdef *o) {
  1520. upb_inttable_begin(iter, &o->itof);
  1521. }
  1522. void upb_oneof_next(upb_oneof_iter *iter) {
  1523. upb_inttable_next(iter);
  1524. }
  1525. bool upb_oneof_done(upb_oneof_iter *iter) {
  1526. return upb_inttable_done(iter);
  1527. }
  1528. upb_fielddef *upb_oneof_iter_field(const upb_oneof_iter *iter) {
  1529. return (upb_fielddef*)upb_value_getptr(upb_inttable_iter_value(iter));
  1530. }
  1531. void upb_oneof_iter_setdone(upb_oneof_iter *iter) {
  1532. upb_inttable_iter_setdone(iter);
  1533. }
  1534. /*
  1535. * upb - a minimalist implementation of protocol buffers.
  1536. *
  1537. * Copyright (c) 2011-2012 Google Inc. See LICENSE for details.
  1538. * Author: Josh Haberman <jhaberman@gmail.com>
  1539. *
  1540. * TODO(haberman): it's unclear whether a lot of the consistency checks should
  1541. * assert() or return false.
  1542. */
  1543. #include <stdlib.h>
  1544. #include <string.h>
  1545. // Defined for the sole purpose of having a unique pointer value for
  1546. // UPB_NO_CLOSURE.
  1547. char _upb_noclosure;
  1548. static void freehandlers(upb_refcounted *r) {
  1549. upb_handlers *h = (upb_handlers*)r;
  1550. upb_inttable_iter i;
  1551. upb_inttable_begin(&i, &h->cleanup_);
  1552. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  1553. void *val = (void*)upb_inttable_iter_key(&i);
  1554. upb_value func_val = upb_inttable_iter_value(&i);
  1555. upb_handlerfree *func = upb_value_getfptr(func_val);
  1556. func(val);
  1557. }
  1558. upb_inttable_uninit(&h->cleanup_);
  1559. upb_msgdef_unref(h->msg, h);
  1560. free(h->sub);
  1561. free(h);
  1562. }
  1563. static void visithandlers(const upb_refcounted *r, upb_refcounted_visit *visit,
  1564. void *closure) {
  1565. const upb_handlers *h = (const upb_handlers*)r;
  1566. upb_msg_field_iter i;
  1567. for(upb_msg_field_begin(&i, h->msg);
  1568. !upb_msg_field_done(&i);
  1569. upb_msg_field_next(&i)) {
  1570. upb_fielddef *f = upb_msg_iter_field(&i);
  1571. if (!upb_fielddef_issubmsg(f)) continue;
  1572. const upb_handlers *sub = upb_handlers_getsubhandlers(h, f);
  1573. if (sub) visit(r, UPB_UPCAST(sub), closure);
  1574. }
  1575. }
  1576. static const struct upb_refcounted_vtbl vtbl = {visithandlers, freehandlers};
  1577. typedef struct {
  1578. upb_inttable tab; // maps upb_msgdef* -> upb_handlers*.
  1579. upb_handlers_callback *callback;
  1580. const void *closure;
  1581. } dfs_state;
  1582. // TODO(haberman): discard upb_handlers* objects that do not actually have any
  1583. // handlers set and cannot reach any upb_handlers* object that does. This is
  1584. // slightly tricky to do correctly.
  1585. static upb_handlers *newformsg(const upb_msgdef *m, const void *owner,
  1586. dfs_state *s) {
  1587. upb_handlers *h = upb_handlers_new(m, owner);
  1588. if (!h) return NULL;
  1589. if (!upb_inttable_insertptr(&s->tab, m, upb_value_ptr(h))) goto oom;
  1590. s->callback(s->closure, h);
  1591. // For each submessage field, get or create a handlers object and set it as
  1592. // the subhandlers.
  1593. upb_msg_field_iter i;
  1594. for(upb_msg_field_begin(&i, m);
  1595. !upb_msg_field_done(&i);
  1596. upb_msg_field_next(&i)) {
  1597. upb_fielddef *f = upb_msg_iter_field(&i);
  1598. if (!upb_fielddef_issubmsg(f)) continue;
  1599. const upb_msgdef *subdef = upb_downcast_msgdef(upb_fielddef_subdef(f));
  1600. upb_value subm_ent;
  1601. if (upb_inttable_lookupptr(&s->tab, subdef, &subm_ent)) {
  1602. upb_handlers_setsubhandlers(h, f, upb_value_getptr(subm_ent));
  1603. } else {
  1604. upb_handlers *sub_mh = newformsg(subdef, &sub_mh, s);
  1605. if (!sub_mh) goto oom;
  1606. upb_handlers_setsubhandlers(h, f, sub_mh);
  1607. upb_handlers_unref(sub_mh, &sub_mh);
  1608. }
  1609. }
  1610. return h;
  1611. oom:
  1612. upb_handlers_unref(h, owner);
  1613. return NULL;
  1614. }
  1615. // Given a selector for a STARTSUBMSG handler, resolves to a pointer to the
  1616. // subhandlers for this submessage field.
  1617. #define SUBH(h, selector) (h->sub[selector])
  1618. // The selector for a submessage field is the field index.
  1619. #define SUBH_F(h, f) SUBH(h, f->index_)
  1620. static int32_t trygetsel(upb_handlers *h, const upb_fielddef *f,
  1621. upb_handlertype_t type) {
  1622. upb_selector_t sel;
  1623. assert(!upb_handlers_isfrozen(h));
  1624. if (upb_handlers_msgdef(h) != upb_fielddef_containingtype(f)) {
  1625. upb_status_seterrf(
  1626. &h->status_, "type mismatch: field %s does not belong to message %s",
  1627. upb_fielddef_name(f), upb_msgdef_fullname(upb_handlers_msgdef(h)));
  1628. return -1;
  1629. }
  1630. if (!upb_handlers_getselector(f, type, &sel)) {
  1631. upb_status_seterrf(
  1632. &h->status_,
  1633. "type mismatch: cannot register handler type %d for field %s",
  1634. type, upb_fielddef_name(f));
  1635. return -1;
  1636. }
  1637. return sel;
  1638. }
  1639. static upb_selector_t handlers_getsel(upb_handlers *h, const upb_fielddef *f,
  1640. upb_handlertype_t type) {
  1641. int32_t sel = trygetsel(h, f, type);
  1642. assert(sel >= 0);
  1643. return sel;
  1644. }
  1645. static const void **returntype(upb_handlers *h, const upb_fielddef *f,
  1646. upb_handlertype_t type) {
  1647. return &h->table[handlers_getsel(h, f, type)].attr.return_closure_type_;
  1648. }
  1649. static bool doset(upb_handlers *h, int32_t sel, const upb_fielddef *f,
  1650. upb_handlertype_t type, upb_func *func,
  1651. upb_handlerattr *attr) {
  1652. assert(!upb_handlers_isfrozen(h));
  1653. if (sel < 0) {
  1654. upb_status_seterrmsg(&h->status_,
  1655. "incorrect handler type for this field.");
  1656. return false;
  1657. }
  1658. if (h->table[sel].func) {
  1659. upb_status_seterrmsg(&h->status_,
  1660. "cannot change handler once it has been set.");
  1661. return false;
  1662. }
  1663. upb_handlerattr set_attr = UPB_HANDLERATTR_INITIALIZER;
  1664. if (attr) {
  1665. set_attr = *attr;
  1666. }
  1667. // Check that the given closure type matches the closure type that has been
  1668. // established for this context (if any).
  1669. const void *closure_type = upb_handlerattr_closuretype(&set_attr);
  1670. const void **context_closure_type;
  1671. if (type == UPB_HANDLER_STRING) {
  1672. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSTR);
  1673. } else if (f && upb_fielddef_isseq(f) &&
  1674. type != UPB_HANDLER_STARTSEQ &&
  1675. type != UPB_HANDLER_ENDSEQ) {
  1676. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSEQ);
  1677. } else {
  1678. context_closure_type = &h->top_closure_type;
  1679. }
  1680. if (closure_type && *context_closure_type &&
  1681. closure_type != *context_closure_type) {
  1682. // TODO(haberman): better message for debugging.
  1683. upb_status_seterrmsg(&h->status_, "closure type does not match");
  1684. return false;
  1685. }
  1686. if (closure_type)
  1687. *context_closure_type = closure_type;
  1688. // If this is a STARTSEQ or STARTSTR handler, check that the returned pointer
  1689. // matches any pre-existing expectations about what type is expected.
  1690. if (type == UPB_HANDLER_STARTSEQ || type == UPB_HANDLER_STARTSTR) {
  1691. const void *return_type = upb_handlerattr_returnclosuretype(&set_attr);
  1692. const void *table_return_type =
  1693. upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1694. if (return_type && table_return_type && return_type != table_return_type) {
  1695. upb_status_seterrmsg(&h->status_, "closure return type does not match");
  1696. return false;
  1697. }
  1698. if (table_return_type && !return_type)
  1699. upb_handlerattr_setreturnclosuretype(&set_attr, table_return_type);
  1700. }
  1701. h->table[sel].func = (upb_func*)func;
  1702. h->table[sel].attr = set_attr;
  1703. return true;
  1704. }
  1705. // Returns the effective closure type for this handler (which will propagate
  1706. // from outer frames if this frame has no START* handler). Not implemented for
  1707. // UPB_HANDLER_STRING at the moment since this is not needed. Returns NULL is
  1708. // the effective closure type is unspecified (either no handler was registered
  1709. // to specify it or the handler that was registered did not specify the closure
  1710. // type).
  1711. const void *effective_closure_type(upb_handlers *h, const upb_fielddef *f,
  1712. upb_handlertype_t type) {
  1713. assert(type != UPB_HANDLER_STRING);
  1714. const void *ret = h->top_closure_type;
  1715. upb_selector_t sel;
  1716. if (upb_fielddef_isseq(f) &&
  1717. type != UPB_HANDLER_STARTSEQ &&
  1718. type != UPB_HANDLER_ENDSEQ &&
  1719. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)].func) {
  1720. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1721. }
  1722. if (type == UPB_HANDLER_STRING &&
  1723. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSTR)].func) {
  1724. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1725. }
  1726. // The effective type of the submessage; not used yet.
  1727. // if (type == SUBMESSAGE &&
  1728. // h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)].func) {
  1729. // ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1730. // }
  1731. return ret;
  1732. }
  1733. // Checks whether the START* handler specified by f & type is missing even
  1734. // though it is required to convert the established type of an outer frame
  1735. // ("closure_type") into the established type of an inner frame (represented in
  1736. // the return closure type of this handler's attr.
  1737. bool checkstart(upb_handlers *h, const upb_fielddef *f, upb_handlertype_t type,
  1738. upb_status *status) {
  1739. upb_selector_t sel = handlers_getsel(h, f, type);
  1740. if (h->table[sel].func) return true;
  1741. const void *closure_type = effective_closure_type(h, f, type);
  1742. const upb_handlerattr *attr = &h->table[sel].attr;
  1743. const void *return_closure_type = upb_handlerattr_returnclosuretype(attr);
  1744. if (closure_type && return_closure_type &&
  1745. closure_type != return_closure_type) {
  1746. upb_status_seterrf(status,
  1747. "expected start handler to return sub type for field %f",
  1748. upb_fielddef_name(f));
  1749. return false;
  1750. }
  1751. return true;
  1752. }
  1753. /* Public interface ***********************************************************/
  1754. bool upb_handlers_isfrozen(const upb_handlers *h) {
  1755. return upb_refcounted_isfrozen(UPB_UPCAST(h));
  1756. }
  1757. void upb_handlers_ref(const upb_handlers *h, const void *owner) {
  1758. upb_refcounted_ref(UPB_UPCAST(h), owner);
  1759. }
  1760. void upb_handlers_unref(const upb_handlers *h, const void *owner) {
  1761. upb_refcounted_unref(UPB_UPCAST(h), owner);
  1762. }
  1763. void upb_handlers_donateref(
  1764. const upb_handlers *h, const void *from, const void *to) {
  1765. upb_refcounted_donateref(UPB_UPCAST(h), from, to);
  1766. }
  1767. void upb_handlers_checkref(const upb_handlers *h, const void *owner) {
  1768. upb_refcounted_checkref(UPB_UPCAST(h), owner);
  1769. }
  1770. upb_handlers *upb_handlers_new(const upb_msgdef *md, const void *owner) {
  1771. assert(upb_msgdef_isfrozen(md));
  1772. int extra = sizeof(upb_handlers_tabent) * (md->selector_count - 1);
  1773. upb_handlers *h = calloc(sizeof(*h) + extra, 1);
  1774. if (!h) return NULL;
  1775. h->msg = md;
  1776. upb_msgdef_ref(h->msg, h);
  1777. upb_status_clear(&h->status_);
  1778. h->sub = calloc(md->submsg_field_count, sizeof(*h->sub));
  1779. if (!h->sub) goto oom;
  1780. if (!upb_refcounted_init(UPB_UPCAST(h), &vtbl, owner)) goto oom;
  1781. if (!upb_inttable_init(&h->cleanup_, UPB_CTYPE_FPTR)) goto oom;
  1782. // calloc() above initialized all handlers to NULL.
  1783. return h;
  1784. oom:
  1785. freehandlers(UPB_UPCAST(h));
  1786. return NULL;
  1787. }
  1788. const upb_handlers *upb_handlers_newfrozen(const upb_msgdef *m,
  1789. const void *owner,
  1790. upb_handlers_callback *callback,
  1791. const void *closure) {
  1792. dfs_state state;
  1793. state.callback = callback;
  1794. state.closure = closure;
  1795. if (!upb_inttable_init(&state.tab, UPB_CTYPE_PTR)) return NULL;
  1796. upb_handlers *ret = newformsg(m, owner, &state);
  1797. upb_inttable_uninit(&state.tab);
  1798. if (!ret) return NULL;
  1799. upb_refcounted *r = UPB_UPCAST(ret);
  1800. bool ok = upb_refcounted_freeze(&r, 1, NULL, UPB_MAX_HANDLER_DEPTH);
  1801. UPB_ASSERT_VAR(ok, ok);
  1802. return ret;
  1803. }
  1804. const upb_status *upb_handlers_status(upb_handlers *h) {
  1805. assert(!upb_handlers_isfrozen(h));
  1806. return &h->status_;
  1807. }
  1808. void upb_handlers_clearerr(upb_handlers *h) {
  1809. assert(!upb_handlers_isfrozen(h));
  1810. upb_status_clear(&h->status_);
  1811. }
  1812. #define SETTER(name, handlerctype, handlertype) \
  1813. bool upb_handlers_set ## name(upb_handlers *h, const upb_fielddef *f, \
  1814. handlerctype func, upb_handlerattr *attr) { \
  1815. int32_t sel = trygetsel(h, f, handlertype); \
  1816. return doset(h, sel, f, handlertype, (upb_func*)func, attr); \
  1817. }
  1818. SETTER(int32, upb_int32_handlerfunc*, UPB_HANDLER_INT32);
  1819. SETTER(int64, upb_int64_handlerfunc*, UPB_HANDLER_INT64);
  1820. SETTER(uint32, upb_uint32_handlerfunc*, UPB_HANDLER_UINT32);
  1821. SETTER(uint64, upb_uint64_handlerfunc*, UPB_HANDLER_UINT64);
  1822. SETTER(float, upb_float_handlerfunc*, UPB_HANDLER_FLOAT);
  1823. SETTER(double, upb_double_handlerfunc*, UPB_HANDLER_DOUBLE);
  1824. SETTER(bool, upb_bool_handlerfunc*, UPB_HANDLER_BOOL);
  1825. SETTER(startstr, upb_startstr_handlerfunc*, UPB_HANDLER_STARTSTR);
  1826. SETTER(string, upb_string_handlerfunc*, UPB_HANDLER_STRING);
  1827. SETTER(endstr, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSTR);
  1828. SETTER(startseq, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSEQ);
  1829. SETTER(startsubmsg, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSUBMSG);
  1830. SETTER(endsubmsg, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSUBMSG);
  1831. SETTER(endseq, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSEQ);
  1832. #undef SETTER
  1833. bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
  1834. upb_handlerattr *attr) {
  1835. return doset(h, UPB_STARTMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  1836. (upb_func *)func, attr);
  1837. }
  1838. bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func,
  1839. upb_handlerattr *attr) {
  1840. assert(!upb_handlers_isfrozen(h));
  1841. return doset(h, UPB_ENDMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  1842. (upb_func *)func, attr);
  1843. }
  1844. bool upb_handlers_setsubhandlers(upb_handlers *h, const upb_fielddef *f,
  1845. const upb_handlers *sub) {
  1846. assert(sub);
  1847. assert(!upb_handlers_isfrozen(h));
  1848. assert(upb_fielddef_issubmsg(f));
  1849. if (SUBH_F(h, f)) return false; // Can't reset.
  1850. if (UPB_UPCAST(upb_handlers_msgdef(sub)) != upb_fielddef_subdef(f)) {
  1851. return false;
  1852. }
  1853. SUBH_F(h, f) = sub;
  1854. upb_ref2(sub, h);
  1855. return true;
  1856. }
  1857. const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h,
  1858. const upb_fielddef *f) {
  1859. assert(upb_fielddef_issubmsg(f));
  1860. return SUBH_F(h, f);
  1861. }
  1862. bool upb_handlers_getattr(const upb_handlers *h, upb_selector_t sel,
  1863. upb_handlerattr *attr) {
  1864. if (!upb_handlers_gethandler(h, sel))
  1865. return false;
  1866. *attr = h->table[sel].attr;
  1867. return true;
  1868. }
  1869. const upb_handlers *upb_handlers_getsubhandlers_sel(const upb_handlers *h,
  1870. upb_selector_t sel) {
  1871. // STARTSUBMSG selector in sel is the field's selector base.
  1872. return SUBH(h, sel - UPB_STATIC_SELECTOR_COUNT);
  1873. }
  1874. const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h) { return h->msg; }
  1875. bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *func) {
  1876. if (upb_inttable_lookupptr(&h->cleanup_, p, NULL)) {
  1877. return false;
  1878. }
  1879. bool ok = upb_inttable_insertptr(&h->cleanup_, p, upb_value_fptr(func));
  1880. UPB_ASSERT_VAR(ok, ok);
  1881. return true;
  1882. }
  1883. /* "Static" methods ***********************************************************/
  1884. bool upb_handlers_freeze(upb_handlers *const*handlers, int n, upb_status *s) {
  1885. // TODO: verify we have a transitive closure.
  1886. for (int i = 0; i < n; i++) {
  1887. upb_handlers *h = handlers[i];
  1888. if (!upb_ok(&h->status_)) {
  1889. upb_status_seterrf(s, "handlers for message %s had error status: %s",
  1890. upb_msgdef_fullname(upb_handlers_msgdef(h)),
  1891. upb_status_errmsg(&h->status_));
  1892. return false;
  1893. }
  1894. // Check that there are no closure mismatches due to missing Start* handlers
  1895. // or subhandlers with different type-level types.
  1896. upb_msg_field_iter j;
  1897. for(upb_msg_field_begin(&j, h->msg);
  1898. !upb_msg_field_done(&j);
  1899. upb_msg_field_next(&j)) {
  1900. const upb_fielddef *f = upb_msg_iter_field(&j);
  1901. if (upb_fielddef_isseq(f)) {
  1902. if (!checkstart(h, f, UPB_HANDLER_STARTSEQ, s))
  1903. return false;
  1904. }
  1905. if (upb_fielddef_isstring(f)) {
  1906. if (!checkstart(h, f, UPB_HANDLER_STARTSTR, s))
  1907. return false;
  1908. }
  1909. if (upb_fielddef_issubmsg(f)) {
  1910. bool hashandler = false;
  1911. if (upb_handlers_gethandler(
  1912. h, handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)) ||
  1913. upb_handlers_gethandler(
  1914. h, handlers_getsel(h, f, UPB_HANDLER_ENDSUBMSG))) {
  1915. hashandler = true;
  1916. }
  1917. if (upb_fielddef_isseq(f) &&
  1918. (upb_handlers_gethandler(
  1919. h, handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)) ||
  1920. upb_handlers_gethandler(
  1921. h, handlers_getsel(h, f, UPB_HANDLER_ENDSEQ)))) {
  1922. hashandler = true;
  1923. }
  1924. if (hashandler && !upb_handlers_getsubhandlers(h, f)) {
  1925. // For now we add an empty subhandlers in this case. It makes the
  1926. // decoder code generator simpler, because it only has to handle two
  1927. // cases (submessage has handlers or not) as opposed to three
  1928. // (submessage has handlers in enclosing message but no subhandlers).
  1929. //
  1930. // This makes parsing less efficient in the case that we want to
  1931. // notice a submessage but skip its contents (like if we're testing
  1932. // for submessage presence or counting the number of repeated
  1933. // submessages). In this case we will end up parsing the submessage
  1934. // field by field and throwing away the results for each, instead of
  1935. // skipping the whole delimited thing at once. If this is an issue we
  1936. // can revisit it, but do remember that this only arises when you have
  1937. // handlers (startseq/startsubmsg/endsubmsg/endseq) set for the
  1938. // submessage but no subhandlers. The uses cases for this are
  1939. // limited.
  1940. upb_handlers *sub = upb_handlers_new(upb_fielddef_msgsubdef(f), &sub);
  1941. upb_handlers_setsubhandlers(h, f, sub);
  1942. upb_handlers_unref(sub, &sub);
  1943. }
  1944. // TODO(haberman): check type of submessage.
  1945. // This is slightly tricky; also consider whether we should check that
  1946. // they match at setsubhandlers time.
  1947. }
  1948. }
  1949. }
  1950. if (!upb_refcounted_freeze((upb_refcounted*const*)handlers, n, s,
  1951. UPB_MAX_HANDLER_DEPTH)) {
  1952. return false;
  1953. }
  1954. return true;
  1955. }
  1956. upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f) {
  1957. switch (upb_fielddef_type(f)) {
  1958. case UPB_TYPE_INT32:
  1959. case UPB_TYPE_ENUM: return UPB_HANDLER_INT32;
  1960. case UPB_TYPE_INT64: return UPB_HANDLER_INT64;
  1961. case UPB_TYPE_UINT32: return UPB_HANDLER_UINT32;
  1962. case UPB_TYPE_UINT64: return UPB_HANDLER_UINT64;
  1963. case UPB_TYPE_FLOAT: return UPB_HANDLER_FLOAT;
  1964. case UPB_TYPE_DOUBLE: return UPB_HANDLER_DOUBLE;
  1965. case UPB_TYPE_BOOL: return UPB_HANDLER_BOOL;
  1966. default: assert(false); return -1; // Invalid input.
  1967. }
  1968. }
  1969. bool upb_handlers_getselector(const upb_fielddef *f, upb_handlertype_t type,
  1970. upb_selector_t *s) {
  1971. switch (type) {
  1972. case UPB_HANDLER_INT32:
  1973. case UPB_HANDLER_INT64:
  1974. case UPB_HANDLER_UINT32:
  1975. case UPB_HANDLER_UINT64:
  1976. case UPB_HANDLER_FLOAT:
  1977. case UPB_HANDLER_DOUBLE:
  1978. case UPB_HANDLER_BOOL:
  1979. if (!upb_fielddef_isprimitive(f) ||
  1980. upb_handlers_getprimitivehandlertype(f) != type)
  1981. return false;
  1982. *s = f->selector_base;
  1983. break;
  1984. case UPB_HANDLER_STRING:
  1985. if (upb_fielddef_isstring(f)) {
  1986. *s = f->selector_base;
  1987. } else if (upb_fielddef_lazy(f)) {
  1988. *s = f->selector_base + 3;
  1989. } else {
  1990. return false;
  1991. }
  1992. break;
  1993. case UPB_HANDLER_STARTSTR:
  1994. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  1995. *s = f->selector_base + 1;
  1996. } else {
  1997. return false;
  1998. }
  1999. break;
  2000. case UPB_HANDLER_ENDSTR:
  2001. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  2002. *s = f->selector_base + 2;
  2003. } else {
  2004. return false;
  2005. }
  2006. break;
  2007. case UPB_HANDLER_STARTSEQ:
  2008. if (!upb_fielddef_isseq(f)) return false;
  2009. *s = f->selector_base - 2;
  2010. break;
  2011. case UPB_HANDLER_ENDSEQ:
  2012. if (!upb_fielddef_isseq(f)) return false;
  2013. *s = f->selector_base - 1;
  2014. break;
  2015. case UPB_HANDLER_STARTSUBMSG:
  2016. if (!upb_fielddef_issubmsg(f)) return false;
  2017. // Selectors for STARTSUBMSG are at the beginning of the table so that the
  2018. // selector can also be used as an index into the "sub" array of
  2019. // subhandlers. The indexes for the two into these two tables are the
  2020. // same, except that in the handler table the static selectors come first.
  2021. *s = f->index_ + UPB_STATIC_SELECTOR_COUNT;
  2022. break;
  2023. case UPB_HANDLER_ENDSUBMSG:
  2024. if (!upb_fielddef_issubmsg(f)) return false;
  2025. *s = f->selector_base;
  2026. break;
  2027. }
  2028. assert(*s < upb_fielddef_containingtype(f)->selector_count);
  2029. return true;
  2030. }
  2031. uint32_t upb_handlers_selectorbaseoffset(const upb_fielddef *f) {
  2032. return upb_fielddef_isseq(f) ? 2 : 0;
  2033. }
  2034. uint32_t upb_handlers_selectorcount(const upb_fielddef *f) {
  2035. uint32_t ret = 1;
  2036. if (upb_fielddef_isseq(f)) ret += 2; // STARTSEQ/ENDSEQ
  2037. if (upb_fielddef_isstring(f)) ret += 2; // [STRING]/STARTSTR/ENDSTR
  2038. if (upb_fielddef_issubmsg(f)) {
  2039. // ENDSUBMSG (STARTSUBMSG is at table beginning)
  2040. ret += 0;
  2041. if (upb_fielddef_lazy(f)) {
  2042. // STARTSTR/ENDSTR/STRING (for lazy)
  2043. ret += 3;
  2044. }
  2045. }
  2046. return ret;
  2047. }
  2048. /* upb_handlerattr ************************************************************/
  2049. void upb_handlerattr_init(upb_handlerattr *attr) {
  2050. upb_handlerattr from = UPB_HANDLERATTR_INITIALIZER;
  2051. memcpy(attr, &from, sizeof(*attr));
  2052. }
  2053. void upb_handlerattr_uninit(upb_handlerattr *attr) {
  2054. UPB_UNUSED(attr);
  2055. }
  2056. bool upb_handlerattr_sethandlerdata(upb_handlerattr *attr, const void *hd) {
  2057. attr->handler_data_ = hd;
  2058. return true;
  2059. }
  2060. bool upb_handlerattr_setclosuretype(upb_handlerattr *attr, const void *type) {
  2061. attr->closure_type_ = type;
  2062. return true;
  2063. }
  2064. const void *upb_handlerattr_closuretype(const upb_handlerattr *attr) {
  2065. return attr->closure_type_;
  2066. }
  2067. bool upb_handlerattr_setreturnclosuretype(upb_handlerattr *attr,
  2068. const void *type) {
  2069. attr->return_closure_type_ = type;
  2070. return true;
  2071. }
  2072. const void *upb_handlerattr_returnclosuretype(const upb_handlerattr *attr) {
  2073. return attr->return_closure_type_;
  2074. }
  2075. bool upb_handlerattr_setalwaysok(upb_handlerattr *attr, bool alwaysok) {
  2076. attr->alwaysok_ = alwaysok;
  2077. return true;
  2078. }
  2079. bool upb_handlerattr_alwaysok(const upb_handlerattr *attr) {
  2080. return attr->alwaysok_;
  2081. }
  2082. /* upb_bufhandle **************************************************************/
  2083. size_t upb_bufhandle_objofs(const upb_bufhandle *h) {
  2084. return h->objofs_;
  2085. }
  2086. /* upb_byteshandler ***********************************************************/
  2087. void upb_byteshandler_init(upb_byteshandler* h) {
  2088. memset(h, 0, sizeof(*h));
  2089. }
  2090. // For when we support handlerfree callbacks.
  2091. void upb_byteshandler_uninit(upb_byteshandler* h) {
  2092. UPB_UNUSED(h);
  2093. }
  2094. bool upb_byteshandler_setstartstr(upb_byteshandler *h,
  2095. upb_startstr_handlerfunc *func, void *d) {
  2096. h->table[UPB_STARTSTR_SELECTOR].func = (upb_func*)func;
  2097. h->table[UPB_STARTSTR_SELECTOR].attr.handler_data_ = d;
  2098. return true;
  2099. }
  2100. bool upb_byteshandler_setstring(upb_byteshandler *h,
  2101. upb_string_handlerfunc *func, void *d) {
  2102. h->table[UPB_STRING_SELECTOR].func = (upb_func*)func;
  2103. h->table[UPB_STRING_SELECTOR].attr.handler_data_ = d;
  2104. return true;
  2105. }
  2106. bool upb_byteshandler_setendstr(upb_byteshandler *h,
  2107. upb_endfield_handlerfunc *func, void *d) {
  2108. h->table[UPB_ENDSTR_SELECTOR].func = (upb_func*)func;
  2109. h->table[UPB_ENDSTR_SELECTOR].attr.handler_data_ = d;
  2110. return true;
  2111. }
  2112. /*
  2113. * upb - a minimalist implementation of protocol buffers.
  2114. *
  2115. * Copyright (c) 2012 Google Inc. See LICENSE for details.
  2116. * Author: Josh Haberman <jhaberman@gmail.com>
  2117. *
  2118. * Our key invariants are:
  2119. * 1. reference cycles never span groups
  2120. * 2. for ref2(to, from), we increment to's count iff group(from) != group(to)
  2121. *
  2122. * The previous two are how we avoid leaking cycles. Other important
  2123. * invariants are:
  2124. * 3. for mutable objects "from" and "to", if there exists a ref2(to, from)
  2125. * this implies group(from) == group(to). (In practice, what we implement
  2126. * is even stronger; "from" and "to" will share a group if there has *ever*
  2127. * been a ref2(to, from), but all that is necessary for correctness is the
  2128. * weaker one).
  2129. * 4. mutable and immutable objects are never in the same group.
  2130. */
  2131. #include <setjmp.h>
  2132. #include <stdlib.h>
  2133. static void freeobj(upb_refcounted *o);
  2134. const char untracked_val;
  2135. const void *UPB_UNTRACKED_REF = &untracked_val;
  2136. /* arch-specific atomic primitives *******************************************/
  2137. #ifdef UPB_THREAD_UNSAFE //////////////////////////////////////////////////////
  2138. static void atomic_inc(uint32_t *a) { (*a)++; }
  2139. static bool atomic_dec(uint32_t *a) { return --(*a) == 0; }
  2140. #elif defined(__GNUC__) || defined(__clang__) //////////////////////////////////
  2141. static void atomic_inc(uint32_t *a) { __sync_fetch_and_add(a, 1); }
  2142. static bool atomic_dec(uint32_t *a) { return __sync_sub_and_fetch(a, 1) == 0; }
  2143. #elif defined(WIN32) ///////////////////////////////////////////////////////////
  2144. #include <Windows.h>
  2145. static void atomic_inc(upb_atomic_t *a) { InterlockedIncrement(&a->val); }
  2146. static bool atomic_dec(upb_atomic_t *a) {
  2147. return InterlockedDecrement(&a->val) == 0;
  2148. }
  2149. #else
  2150. #error Atomic primitives not defined for your platform/CPU. \
  2151. Implement them or compile with UPB_THREAD_UNSAFE.
  2152. #endif
  2153. // All static objects point to this refcount.
  2154. // It is special-cased in ref/unref below.
  2155. uint32_t static_refcount = -1;
  2156. // We can avoid atomic ops for statically-declared objects.
  2157. // This is a minor optimization but nice since we can avoid degrading under
  2158. // contention in this case.
  2159. static void refgroup(uint32_t *group) {
  2160. if (group != &static_refcount)
  2161. atomic_inc(group);
  2162. }
  2163. static bool unrefgroup(uint32_t *group) {
  2164. if (group == &static_refcount) {
  2165. return false;
  2166. } else {
  2167. return atomic_dec(group);
  2168. }
  2169. }
  2170. /* Reference tracking (debug only) ********************************************/
  2171. #ifdef UPB_DEBUG_REFS
  2172. #ifdef UPB_THREAD_UNSAFE
  2173. static void upb_lock() {}
  2174. static void upb_unlock() {}
  2175. #else
  2176. // User must define functions that lock/unlock a global mutex and link this
  2177. // file against them.
  2178. void upb_lock();
  2179. void upb_unlock();
  2180. #endif
  2181. // UPB_DEBUG_REFS mode counts on being able to malloc() memory in some
  2182. // code-paths that can normally never fail, like upb_refcounted_ref(). Since
  2183. // we have no way to propagage out-of-memory errors back to the user, and since
  2184. // these errors can only occur in UPB_DEBUG_REFS mode, we immediately fail.
  2185. #define CHECK_OOM(predicate) if (!(predicate)) { assert(predicate); exit(1); }
  2186. typedef struct {
  2187. int count; // How many refs there are (duplicates only allowed for ref2).
  2188. bool is_ref2;
  2189. } trackedref;
  2190. static trackedref *trackedref_new(bool is_ref2) {
  2191. trackedref *ret = malloc(sizeof(*ret));
  2192. CHECK_OOM(ret);
  2193. ret->count = 1;
  2194. ret->is_ref2 = is_ref2;
  2195. return ret;
  2196. }
  2197. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  2198. assert(owner);
  2199. if (owner == UPB_UNTRACKED_REF) return;
  2200. upb_lock();
  2201. upb_value v;
  2202. if (upb_inttable_lookupptr(r->refs, owner, &v)) {
  2203. trackedref *ref = upb_value_getptr(v);
  2204. // Since we allow multiple ref2's for the same to/from pair without
  2205. // allocating separate memory for each one, we lose the fine-grained
  2206. // tracking behavior we get with regular refs. Since ref2s only happen
  2207. // inside upb, we'll accept this limitation until/unless there is a really
  2208. // difficult upb-internal bug that can't be figured out without it.
  2209. assert(ref2);
  2210. assert(ref->is_ref2);
  2211. ref->count++;
  2212. } else {
  2213. trackedref *ref = trackedref_new(ref2);
  2214. bool ok = upb_inttable_insertptr(r->refs, owner, upb_value_ptr(ref));
  2215. CHECK_OOM(ok);
  2216. if (ref2) {
  2217. // We know this cast is safe when it is a ref2, because it's coming from
  2218. // another refcounted object.
  2219. const upb_refcounted *from = owner;
  2220. assert(!upb_inttable_lookupptr(from->ref2s, r, NULL));
  2221. ok = upb_inttable_insertptr(from->ref2s, r, upb_value_ptr(NULL));
  2222. CHECK_OOM(ok);
  2223. }
  2224. }
  2225. upb_unlock();
  2226. }
  2227. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  2228. assert(owner);
  2229. if (owner == UPB_UNTRACKED_REF) return;
  2230. upb_lock();
  2231. upb_value v;
  2232. bool found = upb_inttable_lookupptr(r->refs, owner, &v);
  2233. // This assert will fail if an owner attempts to release a ref it didn't have.
  2234. UPB_ASSERT_VAR(found, found);
  2235. trackedref *ref = upb_value_getptr(v);
  2236. assert(ref->is_ref2 == ref2);
  2237. if (--ref->count == 0) {
  2238. free(ref);
  2239. upb_inttable_removeptr(r->refs, owner, NULL);
  2240. if (ref2) {
  2241. // We know this cast is safe when it is a ref2, because it's coming from
  2242. // another refcounted object.
  2243. const upb_refcounted *from = owner;
  2244. bool removed = upb_inttable_removeptr(from->ref2s, r, NULL);
  2245. assert(removed);
  2246. }
  2247. }
  2248. upb_unlock();
  2249. }
  2250. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  2251. upb_lock();
  2252. upb_value v;
  2253. bool found = upb_inttable_lookupptr(r->refs, owner, &v);
  2254. UPB_ASSERT_VAR(found, found);
  2255. trackedref *ref = upb_value_getptr(v);
  2256. assert(ref->is_ref2 == ref2);
  2257. upb_unlock();
  2258. }
  2259. // Populates the given UPB_CTYPE_INT32 inttable with counts of ref2's that
  2260. // originate from the given owner.
  2261. static void getref2s(const upb_refcounted *owner, upb_inttable *tab) {
  2262. upb_lock();
  2263. upb_inttable_iter i;
  2264. upb_inttable_begin(&i, owner->ref2s);
  2265. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  2266. upb_refcounted *to = (upb_refcounted*)upb_inttable_iter_key(&i);
  2267. // To get the count we need to look in the target's table.
  2268. upb_value v;
  2269. bool found = upb_inttable_lookupptr(to->refs, owner, &v);
  2270. assert(found);
  2271. trackedref *ref = upb_value_getptr(v);
  2272. upb_value count = upb_value_int32(ref->count);
  2273. bool ok = upb_inttable_insertptr(tab, to, count);
  2274. CHECK_OOM(ok);
  2275. }
  2276. upb_unlock();
  2277. }
  2278. typedef struct {
  2279. upb_inttable ref2;
  2280. const upb_refcounted *obj;
  2281. } check_state;
  2282. static void visit_check(const upb_refcounted *obj, const upb_refcounted *subobj,
  2283. void *closure) {
  2284. check_state *s = closure;
  2285. assert(obj == s->obj);
  2286. assert(subobj);
  2287. upb_inttable *ref2 = &s->ref2;
  2288. upb_value v;
  2289. bool removed = upb_inttable_removeptr(ref2, subobj, &v);
  2290. // The following assertion will fail if the visit() function visits a subobj
  2291. // that it did not have a ref2 on, or visits the same subobj too many times.
  2292. assert(removed);
  2293. int32_t newcount = upb_value_getint32(v) - 1;
  2294. if (newcount > 0) {
  2295. upb_inttable_insert(ref2, (uintptr_t)subobj, upb_value_int32(newcount));
  2296. }
  2297. }
  2298. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  2299. void *closure) {
  2300. // In DEBUG_REFS mode we know what existing ref2 refs there are, so we know
  2301. // exactly the set of nodes that visit() should visit. So we verify visit()'s
  2302. // correctness here.
  2303. check_state state;
  2304. state.obj = r;
  2305. bool ok = upb_inttable_init(&state.ref2, UPB_CTYPE_INT32);
  2306. CHECK_OOM(ok);
  2307. getref2s(r, &state.ref2);
  2308. // This should visit any children in the ref2 table.
  2309. if (r->vtbl->visit) r->vtbl->visit(r, visit_check, &state);
  2310. // This assertion will fail if the visit() function missed any children.
  2311. assert(upb_inttable_count(&state.ref2) == 0);
  2312. upb_inttable_uninit(&state.ref2);
  2313. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  2314. }
  2315. static bool trackinit(upb_refcounted *r) {
  2316. r->refs = malloc(sizeof(*r->refs));
  2317. r->ref2s = malloc(sizeof(*r->ref2s));
  2318. if (!r->refs || !r->ref2s) goto err1;
  2319. if (!upb_inttable_init(r->refs, UPB_CTYPE_PTR)) goto err1;
  2320. if (!upb_inttable_init(r->ref2s, UPB_CTYPE_PTR)) goto err2;
  2321. return true;
  2322. err2:
  2323. upb_inttable_uninit(r->refs);
  2324. err1:
  2325. free(r->refs);
  2326. free(r->ref2s);
  2327. return false;
  2328. }
  2329. static void trackfree(const upb_refcounted *r) {
  2330. upb_inttable_uninit(r->refs);
  2331. upb_inttable_uninit(r->ref2s);
  2332. free(r->refs);
  2333. free(r->ref2s);
  2334. }
  2335. #else
  2336. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  2337. UPB_UNUSED(r);
  2338. UPB_UNUSED(owner);
  2339. UPB_UNUSED(ref2);
  2340. }
  2341. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  2342. UPB_UNUSED(r);
  2343. UPB_UNUSED(owner);
  2344. UPB_UNUSED(ref2);
  2345. }
  2346. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  2347. UPB_UNUSED(r);
  2348. UPB_UNUSED(owner);
  2349. UPB_UNUSED(ref2);
  2350. }
  2351. static bool trackinit(upb_refcounted *r) {
  2352. UPB_UNUSED(r);
  2353. return true;
  2354. }
  2355. static void trackfree(const upb_refcounted *r) {
  2356. UPB_UNUSED(r);
  2357. }
  2358. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  2359. void *closure) {
  2360. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  2361. }
  2362. #endif // UPB_DEBUG_REFS
  2363. /* freeze() *******************************************************************/
  2364. // The freeze() operation is by far the most complicated part of this scheme.
  2365. // We compute strongly-connected components and then mutate the graph such that
  2366. // we preserve the invariants documented at the top of this file. And we must
  2367. // handle out-of-memory errors gracefully (without leaving the graph
  2368. // inconsistent), which adds to the fun.
  2369. // The state used by the freeze operation (shared across many functions).
  2370. typedef struct {
  2371. int depth;
  2372. int maxdepth;
  2373. uint64_t index;
  2374. // Maps upb_refcounted* -> attributes (color, etc). attr layout varies by
  2375. // color.
  2376. upb_inttable objattr;
  2377. upb_inttable stack; // stack of upb_refcounted* for Tarjan's algorithm.
  2378. upb_inttable groups; // array of uint32_t*, malloc'd refcounts for new groups
  2379. upb_status *status;
  2380. jmp_buf err;
  2381. } tarjan;
  2382. static void release_ref2(const upb_refcounted *obj,
  2383. const upb_refcounted *subobj,
  2384. void *closure);
  2385. // Node attributes /////////////////////////////////////////////////////////////
  2386. // After our analysis phase all nodes will be either GRAY or WHITE.
  2387. typedef enum {
  2388. BLACK = 0, // Object has not been seen.
  2389. GRAY, // Object has been found via a refgroup but may not be reachable.
  2390. GREEN, // Object is reachable and is currently on the Tarjan stack.
  2391. WHITE, // Object is reachable and has been assigned a group (SCC).
  2392. } color_t;
  2393. UPB_NORETURN static void err(tarjan *t) { longjmp(t->err, 1); }
  2394. UPB_NORETURN static void oom(tarjan *t) {
  2395. upb_status_seterrmsg(t->status, "out of memory");
  2396. err(t);
  2397. }
  2398. static uint64_t trygetattr(const tarjan *t, const upb_refcounted *r) {
  2399. upb_value v;
  2400. return upb_inttable_lookupptr(&t->objattr, r, &v) ?
  2401. upb_value_getuint64(v) : 0;
  2402. }
  2403. static uint64_t getattr(const tarjan *t, const upb_refcounted *r) {
  2404. upb_value v;
  2405. bool found = upb_inttable_lookupptr(&t->objattr, r, &v);
  2406. UPB_ASSERT_VAR(found, found);
  2407. return upb_value_getuint64(v);
  2408. }
  2409. static void setattr(tarjan *t, const upb_refcounted *r, uint64_t attr) {
  2410. upb_inttable_removeptr(&t->objattr, r, NULL);
  2411. upb_inttable_insertptr(&t->objattr, r, upb_value_uint64(attr));
  2412. }
  2413. static color_t color(tarjan *t, const upb_refcounted *r) {
  2414. return trygetattr(t, r) & 0x3; // Color is always stored in the low 2 bits.
  2415. }
  2416. static void set_gray(tarjan *t, const upb_refcounted *r) {
  2417. assert(color(t, r) == BLACK);
  2418. setattr(t, r, GRAY);
  2419. }
  2420. // Pushes an obj onto the Tarjan stack and sets it to GREEN.
  2421. static void push(tarjan *t, const upb_refcounted *r) {
  2422. assert(color(t, r) == BLACK || color(t, r) == GRAY);
  2423. // This defines the attr layout for the GREEN state. "index" and "lowlink"
  2424. // get 31 bits, which is plenty (limit of 2B objects frozen at a time).
  2425. setattr(t, r, GREEN | (t->index << 2) | (t->index << 33));
  2426. if (++t->index == 0x80000000) {
  2427. upb_status_seterrmsg(t->status, "too many objects to freeze");
  2428. err(t);
  2429. }
  2430. upb_inttable_push(&t->stack, upb_value_ptr((void*)r));
  2431. }
  2432. // Pops an obj from the Tarjan stack and sets it to WHITE, with a ptr to its
  2433. // SCC group.
  2434. static upb_refcounted *pop(tarjan *t) {
  2435. upb_refcounted *r = upb_value_getptr(upb_inttable_pop(&t->stack));
  2436. assert(color(t, r) == GREEN);
  2437. // This defines the attr layout for nodes in the WHITE state.
  2438. // Top of group stack is [group, NULL]; we point at group.
  2439. setattr(t, r, WHITE | (upb_inttable_count(&t->groups) - 2) << 8);
  2440. return r;
  2441. }
  2442. static void tarjan_newgroup(tarjan *t) {
  2443. uint32_t *group = malloc(sizeof(*group));
  2444. if (!group) oom(t);
  2445. // Push group and empty group leader (we'll fill in leader later).
  2446. if (!upb_inttable_push(&t->groups, upb_value_ptr(group)) ||
  2447. !upb_inttable_push(&t->groups, upb_value_ptr(NULL))) {
  2448. free(group);
  2449. oom(t);
  2450. }
  2451. *group = 0;
  2452. }
  2453. static uint32_t idx(tarjan *t, const upb_refcounted *r) {
  2454. assert(color(t, r) == GREEN);
  2455. return (getattr(t, r) >> 2) & 0x7FFFFFFF;
  2456. }
  2457. static uint32_t lowlink(tarjan *t, const upb_refcounted *r) {
  2458. if (color(t, r) == GREEN) {
  2459. return getattr(t, r) >> 33;
  2460. } else {
  2461. return UINT32_MAX;
  2462. }
  2463. }
  2464. static void set_lowlink(tarjan *t, const upb_refcounted *r, uint32_t lowlink) {
  2465. assert(color(t, r) == GREEN);
  2466. setattr(t, r, ((uint64_t)lowlink << 33) | (getattr(t, r) & 0x1FFFFFFFF));
  2467. }
  2468. static uint32_t *group(tarjan *t, upb_refcounted *r) {
  2469. assert(color(t, r) == WHITE);
  2470. uint64_t groupnum = getattr(t, r) >> 8;
  2471. upb_value v;
  2472. bool found = upb_inttable_lookup(&t->groups, groupnum, &v);
  2473. UPB_ASSERT_VAR(found, found);
  2474. return upb_value_getptr(v);
  2475. }
  2476. // If the group leader for this object's group has not previously been set,
  2477. // the given object is assigned to be its leader.
  2478. static upb_refcounted *groupleader(tarjan *t, upb_refcounted *r) {
  2479. assert(color(t, r) == WHITE);
  2480. uint64_t leader_slot = (getattr(t, r) >> 8) + 1;
  2481. upb_value v;
  2482. bool found = upb_inttable_lookup(&t->groups, leader_slot, &v);
  2483. UPB_ASSERT_VAR(found, found);
  2484. if (upb_value_getptr(v)) {
  2485. return upb_value_getptr(v);
  2486. } else {
  2487. upb_inttable_remove(&t->groups, leader_slot, NULL);
  2488. upb_inttable_insert(&t->groups, leader_slot, upb_value_ptr(r));
  2489. return r;
  2490. }
  2491. }
  2492. // Tarjan's algorithm //////////////////////////////////////////////////////////
  2493. // See:
  2494. // http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
  2495. static void do_tarjan(const upb_refcounted *obj, tarjan *t);
  2496. static void tarjan_visit(const upb_refcounted *obj,
  2497. const upb_refcounted *subobj,
  2498. void *closure) {
  2499. tarjan *t = closure;
  2500. if (++t->depth > t->maxdepth) {
  2501. upb_status_seterrf(t->status, "graph too deep to freeze (%d)", t->maxdepth);
  2502. err(t);
  2503. } else if (subobj->is_frozen || color(t, subobj) == WHITE) {
  2504. // Do nothing: we don't want to visit or color already-frozen nodes,
  2505. // and WHITE nodes have already been assigned a SCC.
  2506. } else if (color(t, subobj) < GREEN) {
  2507. // Subdef has not yet been visited; recurse on it.
  2508. do_tarjan(subobj, t);
  2509. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), lowlink(t, subobj)));
  2510. } else if (color(t, subobj) == GREEN) {
  2511. // Subdef is in the stack and hence in the current SCC.
  2512. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), idx(t, subobj)));
  2513. }
  2514. --t->depth;
  2515. }
  2516. static void do_tarjan(const upb_refcounted *obj, tarjan *t) {
  2517. if (color(t, obj) == BLACK) {
  2518. // We haven't seen this object's group; mark the whole group GRAY.
  2519. const upb_refcounted *o = obj;
  2520. do { set_gray(t, o); } while ((o = o->next) != obj);
  2521. }
  2522. push(t, obj);
  2523. visit(obj, tarjan_visit, t);
  2524. if (lowlink(t, obj) == idx(t, obj)) {
  2525. tarjan_newgroup(t);
  2526. while (pop(t) != obj)
  2527. ;
  2528. }
  2529. }
  2530. // freeze() ////////////////////////////////////////////////////////////////////
  2531. static void crossref(const upb_refcounted *r, const upb_refcounted *subobj,
  2532. void *_t) {
  2533. tarjan *t = _t;
  2534. assert(color(t, r) > BLACK);
  2535. if (color(t, subobj) > BLACK && r->group != subobj->group) {
  2536. // Previously this ref was not reflected in subobj->group because they
  2537. // were in the same group; now that they are split a ref must be taken.
  2538. refgroup(subobj->group);
  2539. }
  2540. }
  2541. static bool freeze(upb_refcounted *const*roots, int n, upb_status *s,
  2542. int maxdepth) {
  2543. volatile bool ret = false;
  2544. // We run in two passes so that we can allocate all memory before performing
  2545. // any mutation of the input -- this allows us to leave the input unchanged
  2546. // in the case of memory allocation failure.
  2547. tarjan t;
  2548. t.index = 0;
  2549. t.depth = 0;
  2550. t.maxdepth = maxdepth;
  2551. t.status = s;
  2552. if (!upb_inttable_init(&t.objattr, UPB_CTYPE_UINT64)) goto err1;
  2553. if (!upb_inttable_init(&t.stack, UPB_CTYPE_PTR)) goto err2;
  2554. if (!upb_inttable_init(&t.groups, UPB_CTYPE_PTR)) goto err3;
  2555. if (setjmp(t.err) != 0) goto err4;
  2556. for (int i = 0; i < n; i++) {
  2557. if (color(&t, roots[i]) < GREEN) {
  2558. do_tarjan(roots[i], &t);
  2559. }
  2560. }
  2561. // If we've made it this far, no further errors are possible so it's safe to
  2562. // mutate the objects without risk of leaving them in an inconsistent state.
  2563. ret = true;
  2564. // The transformation that follows requires care. The preconditions are:
  2565. // - all objects in attr map are WHITE or GRAY, and are in mutable groups
  2566. // (groups of all mutable objs)
  2567. // - no ref2(to, from) refs have incremented count(to) if both "to" and
  2568. // "from" are in our attr map (this follows from invariants (2) and (3))
  2569. // Pass 1: we remove WHITE objects from their mutable groups, and add them to
  2570. // new groups according to the SCC's we computed. These new groups will
  2571. // consist of only frozen objects. None will be immediately collectible,
  2572. // because WHITE objects are by definition reachable from one of "roots",
  2573. // which the caller must own refs on.
  2574. upb_inttable_iter i;
  2575. upb_inttable_begin(&i, &t.objattr);
  2576. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  2577. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&i);
  2578. // Since removal from a singly-linked list requires access to the object's
  2579. // predecessor, we consider obj->next instead of obj for moving. With the
  2580. // while() loop we guarantee that we will visit every node's predecessor.
  2581. // Proof:
  2582. // 1. every node's predecessor is in our attr map.
  2583. // 2. though the loop body may change a node's predecessor, it will only
  2584. // change it to be the node we are currently operating on, so with a
  2585. // while() loop we guarantee ourselves the chance to remove each node.
  2586. while (color(&t, obj->next) == WHITE &&
  2587. group(&t, obj->next) != obj->next->group) {
  2588. // Remove from old group.
  2589. upb_refcounted *move = obj->next;
  2590. if (obj == move) {
  2591. // Removing the last object from a group.
  2592. assert(*obj->group == obj->individual_count);
  2593. free(obj->group);
  2594. } else {
  2595. obj->next = move->next;
  2596. // This may decrease to zero; we'll collect GRAY objects (if any) that
  2597. // remain in the group in the third pass.
  2598. assert(*move->group >= move->individual_count);
  2599. *move->group -= move->individual_count;
  2600. }
  2601. // Add to new group.
  2602. upb_refcounted *leader = groupleader(&t, move);
  2603. if (move == leader) {
  2604. // First object added to new group is its leader.
  2605. move->group = group(&t, move);
  2606. move->next = move;
  2607. *move->group = move->individual_count;
  2608. } else {
  2609. // Group already has at least one object in it.
  2610. assert(leader->group == group(&t, move));
  2611. move->group = group(&t, move);
  2612. move->next = leader->next;
  2613. leader->next = move;
  2614. *move->group += move->individual_count;
  2615. }
  2616. move->is_frozen = true;
  2617. }
  2618. }
  2619. // Pass 2: GRAY and WHITE objects "obj" with ref2(to, obj) references must
  2620. // increment count(to) if group(obj) != group(to) (which could now be the
  2621. // case if "to" was just frozen).
  2622. upb_inttable_begin(&i, &t.objattr);
  2623. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  2624. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&i);
  2625. visit(obj, crossref, &t);
  2626. }
  2627. // Pass 3: GRAY objects are collected if their group's refcount dropped to
  2628. // zero when we removed its white nodes. This can happen if they had only
  2629. // been kept alive by virtue of sharing a group with an object that was just
  2630. // frozen.
  2631. //
  2632. // It is important that we do this last, since the GRAY object's free()
  2633. // function could call unref2() on just-frozen objects, which will decrement
  2634. // refs that were added in pass 2.
  2635. upb_inttable_begin(&i, &t.objattr);
  2636. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  2637. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&i);
  2638. if (obj->group == NULL || *obj->group == 0) {
  2639. if (obj->group) {
  2640. // We eagerly free() the group's count (since we can't easily determine
  2641. // the group's remaining size it's the easiest way to ensure it gets
  2642. // done).
  2643. free(obj->group);
  2644. // Visit to release ref2's (done in a separate pass since release_ref2
  2645. // depends on o->group being unmodified so it can test merged()).
  2646. upb_refcounted *o = obj;
  2647. do { visit(o, release_ref2, NULL); } while ((o = o->next) != obj);
  2648. // Mark "group" fields as NULL so we know to free the objects later in
  2649. // this loop, but also don't try to delete the group twice.
  2650. o = obj;
  2651. do { o->group = NULL; } while ((o = o->next) != obj);
  2652. }
  2653. freeobj(obj);
  2654. }
  2655. }
  2656. err4:
  2657. if (!ret) {
  2658. upb_inttable_begin(&i, &t.groups);
  2659. for(; !upb_inttable_done(&i); upb_inttable_next(&i))
  2660. free(upb_value_getptr(upb_inttable_iter_value(&i)));
  2661. }
  2662. upb_inttable_uninit(&t.groups);
  2663. err3:
  2664. upb_inttable_uninit(&t.stack);
  2665. err2:
  2666. upb_inttable_uninit(&t.objattr);
  2667. err1:
  2668. return ret;
  2669. }
  2670. /* Misc internal functions ***************************************************/
  2671. static bool merged(const upb_refcounted *r, const upb_refcounted *r2) {
  2672. return r->group == r2->group;
  2673. }
  2674. static void merge(upb_refcounted *r, upb_refcounted *from) {
  2675. if (merged(r, from)) return;
  2676. *r->group += *from->group;
  2677. free(from->group);
  2678. upb_refcounted *base = from;
  2679. // Set all refcount pointers in the "from" chain to the merged refcount.
  2680. //
  2681. // TODO(haberman): this linear algorithm can result in an overall O(n^2) bound
  2682. // if the user continuously extends a group by one object. Prevent this by
  2683. // using one of the techniques in this paper:
  2684. // ftp://www.ncedc.org/outgoing/geomorph/dino/orals/p245-tarjan.pdf
  2685. do { from->group = r->group; } while ((from = from->next) != base);
  2686. // Merge the two circularly linked lists by swapping their next pointers.
  2687. upb_refcounted *tmp = r->next;
  2688. r->next = base->next;
  2689. base->next = tmp;
  2690. }
  2691. static void unref(const upb_refcounted *r);
  2692. static void release_ref2(const upb_refcounted *obj,
  2693. const upb_refcounted *subobj,
  2694. void *closure) {
  2695. UPB_UNUSED(closure);
  2696. untrack(subobj, obj, true);
  2697. if (!merged(obj, subobj)) {
  2698. assert(subobj->is_frozen);
  2699. unref(subobj);
  2700. }
  2701. }
  2702. static void unref(const upb_refcounted *r) {
  2703. if (unrefgroup(r->group)) {
  2704. free(r->group);
  2705. // In two passes, since release_ref2 needs a guarantee that any subobjs
  2706. // are alive.
  2707. const upb_refcounted *o = r;
  2708. do { visit(o, release_ref2, NULL); } while((o = o->next) != r);
  2709. o = r;
  2710. do {
  2711. const upb_refcounted *next = o->next;
  2712. assert(o->is_frozen || o->individual_count == 0);
  2713. freeobj((upb_refcounted*)o);
  2714. o = next;
  2715. } while(o != r);
  2716. }
  2717. }
  2718. static void freeobj(upb_refcounted *o) {
  2719. trackfree(o);
  2720. o->vtbl->free((upb_refcounted*)o);
  2721. }
  2722. /* Public interface ***********************************************************/
  2723. bool upb_refcounted_init(upb_refcounted *r,
  2724. const struct upb_refcounted_vtbl *vtbl,
  2725. const void *owner) {
  2726. r->next = r;
  2727. r->vtbl = vtbl;
  2728. r->individual_count = 0;
  2729. r->is_frozen = false;
  2730. r->group = malloc(sizeof(*r->group));
  2731. if (!r->group) return false;
  2732. *r->group = 0;
  2733. if (!trackinit(r)) {
  2734. free(r->group);
  2735. return false;
  2736. }
  2737. upb_refcounted_ref(r, owner);
  2738. return true;
  2739. }
  2740. bool upb_refcounted_isfrozen(const upb_refcounted *r) {
  2741. return r->is_frozen;
  2742. }
  2743. void upb_refcounted_ref(const upb_refcounted *r, const void *owner) {
  2744. track(r, owner, false);
  2745. if (!r->is_frozen)
  2746. ((upb_refcounted*)r)->individual_count++;
  2747. refgroup(r->group);
  2748. }
  2749. void upb_refcounted_unref(const upb_refcounted *r, const void *owner) {
  2750. untrack(r, owner, false);
  2751. if (!r->is_frozen)
  2752. ((upb_refcounted*)r)->individual_count--;
  2753. unref(r);
  2754. }
  2755. void upb_refcounted_ref2(const upb_refcounted *r, upb_refcounted *from) {
  2756. assert(!from->is_frozen); // Non-const pointer implies this.
  2757. track(r, from, true);
  2758. if (r->is_frozen) {
  2759. refgroup(r->group);
  2760. } else {
  2761. merge((upb_refcounted*)r, from);
  2762. }
  2763. }
  2764. void upb_refcounted_unref2(const upb_refcounted *r, upb_refcounted *from) {
  2765. assert(!from->is_frozen); // Non-const pointer implies this.
  2766. untrack(r, from, true);
  2767. if (r->is_frozen) {
  2768. unref(r);
  2769. } else {
  2770. assert(merged(r, from));
  2771. }
  2772. }
  2773. void upb_refcounted_donateref(
  2774. const upb_refcounted *r, const void *from, const void *to) {
  2775. assert(from != to);
  2776. if (to != NULL)
  2777. upb_refcounted_ref(r, to);
  2778. if (from != NULL)
  2779. upb_refcounted_unref(r, from);
  2780. }
  2781. void upb_refcounted_checkref(const upb_refcounted *r, const void *owner) {
  2782. checkref(r, owner, false);
  2783. }
  2784. bool upb_refcounted_freeze(upb_refcounted *const*roots, int n, upb_status *s,
  2785. int maxdepth) {
  2786. for (int i = 0; i < n; i++) {
  2787. assert(!roots[i]->is_frozen);
  2788. }
  2789. return freeze(roots, n, s, maxdepth);
  2790. }
  2791. /*
  2792. * upb - a minimalist implementation of protocol buffers.
  2793. *
  2794. * Copyright (c) 2013 Google Inc. See LICENSE for details.
  2795. * Author: Josh Haberman <jhaberman@gmail.com>
  2796. */
  2797. #include <stdlib.h>
  2798. // Fallback implementation if the shim is not specialized by the JIT.
  2799. #define SHIM_WRITER(type, ctype) \
  2800. bool upb_shim_set ## type (void *c, const void *hd, ctype val) { \
  2801. uint8_t *m = c; \
  2802. const upb_shim_data *d = hd; \
  2803. if (d->hasbit > 0) \
  2804. *(uint8_t*)&m[d->hasbit / 8] |= 1 << (d->hasbit % 8); \
  2805. *(ctype*)&m[d->offset] = val; \
  2806. return true; \
  2807. } \
  2808. SHIM_WRITER(double, double)
  2809. SHIM_WRITER(float, float)
  2810. SHIM_WRITER(int32, int32_t)
  2811. SHIM_WRITER(int64, int64_t)
  2812. SHIM_WRITER(uint32, uint32_t)
  2813. SHIM_WRITER(uint64, uint64_t)
  2814. SHIM_WRITER(bool, bool)
  2815. #undef SHIM_WRITER
  2816. bool upb_shim_set(upb_handlers *h, const upb_fielddef *f, size_t offset,
  2817. int32_t hasbit) {
  2818. upb_shim_data *d = malloc(sizeof(*d));
  2819. if (!d) return false;
  2820. d->offset = offset;
  2821. d->hasbit = hasbit;
  2822. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  2823. upb_handlerattr_sethandlerdata(&attr, d);
  2824. upb_handlerattr_setalwaysok(&attr, true);
  2825. upb_handlers_addcleanup(h, d, free);
  2826. #define TYPE(u, l) \
  2827. case UPB_TYPE_##u: \
  2828. ok = upb_handlers_set##l(h, f, upb_shim_set##l, &attr); break;
  2829. bool ok = false;
  2830. switch (upb_fielddef_type(f)) {
  2831. TYPE(INT64, int64);
  2832. TYPE(INT32, int32);
  2833. TYPE(ENUM, int32);
  2834. TYPE(UINT64, uint64);
  2835. TYPE(UINT32, uint32);
  2836. TYPE(DOUBLE, double);
  2837. TYPE(FLOAT, float);
  2838. TYPE(BOOL, bool);
  2839. default: assert(false); break;
  2840. }
  2841. #undef TYPE
  2842. upb_handlerattr_uninit(&attr);
  2843. return ok;
  2844. }
  2845. const upb_shim_data *upb_shim_getdata(const upb_handlers *h, upb_selector_t s,
  2846. upb_fieldtype_t *type) {
  2847. upb_func *f = upb_handlers_gethandler(h, s);
  2848. if ((upb_int64_handlerfunc*)f == upb_shim_setint64) {
  2849. *type = UPB_TYPE_INT64;
  2850. } else if ((upb_int32_handlerfunc*)f == upb_shim_setint32) {
  2851. *type = UPB_TYPE_INT32;
  2852. } else if ((upb_uint64_handlerfunc*)f == upb_shim_setuint64) {
  2853. *type = UPB_TYPE_UINT64;
  2854. } else if ((upb_uint32_handlerfunc*)f == upb_shim_setuint32) {
  2855. *type = UPB_TYPE_UINT32;
  2856. } else if ((upb_double_handlerfunc*)f == upb_shim_setdouble) {
  2857. *type = UPB_TYPE_DOUBLE;
  2858. } else if ((upb_float_handlerfunc*)f == upb_shim_setfloat) {
  2859. *type = UPB_TYPE_FLOAT;
  2860. } else if ((upb_bool_handlerfunc*)f == upb_shim_setbool) {
  2861. *type = UPB_TYPE_BOOL;
  2862. } else {
  2863. return NULL;
  2864. }
  2865. return (const upb_shim_data*)upb_handlers_gethandlerdata(h, s);
  2866. }
  2867. /*
  2868. * upb - a minimalist implementation of protocol buffers.
  2869. *
  2870. * Copyright (c) 2008-2012 Google Inc. See LICENSE for details.
  2871. * Author: Josh Haberman <jhaberman@gmail.com>
  2872. */
  2873. #include <stdlib.h>
  2874. #include <string.h>
  2875. bool upb_symtab_isfrozen(const upb_symtab *s) {
  2876. return upb_refcounted_isfrozen(UPB_UPCAST(s));
  2877. }
  2878. void upb_symtab_ref(const upb_symtab *s, const void *owner) {
  2879. upb_refcounted_ref(UPB_UPCAST(s), owner);
  2880. }
  2881. void upb_symtab_unref(const upb_symtab *s, const void *owner) {
  2882. upb_refcounted_unref(UPB_UPCAST(s), owner);
  2883. }
  2884. void upb_symtab_donateref(
  2885. const upb_symtab *s, const void *from, const void *to) {
  2886. upb_refcounted_donateref(UPB_UPCAST(s), from, to);
  2887. }
  2888. void upb_symtab_checkref(const upb_symtab *s, const void *owner) {
  2889. upb_refcounted_checkref(UPB_UPCAST(s), owner);
  2890. }
  2891. static void upb_symtab_free(upb_refcounted *r) {
  2892. upb_symtab *s = (upb_symtab*)r;
  2893. upb_strtable_iter i;
  2894. upb_strtable_begin(&i, &s->symtab);
  2895. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  2896. const upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  2897. upb_def_unref(def, s);
  2898. }
  2899. upb_strtable_uninit(&s->symtab);
  2900. free(s);
  2901. }
  2902. upb_symtab *upb_symtab_new(const void *owner) {
  2903. static const struct upb_refcounted_vtbl vtbl = {NULL, &upb_symtab_free};
  2904. upb_symtab *s = malloc(sizeof(*s));
  2905. upb_refcounted_init(UPB_UPCAST(s), &vtbl, owner);
  2906. upb_strtable_init(&s->symtab, UPB_CTYPE_PTR);
  2907. return s;
  2908. }
  2909. void upb_symtab_freeze(upb_symtab *s) {
  2910. assert(!upb_symtab_isfrozen(s));
  2911. upb_refcounted *r = UPB_UPCAST(s);
  2912. // The symtab does not take ref2's (see refcounted.h) on the defs, because
  2913. // defs cannot refer back to the table and therefore cannot create cycles. So
  2914. // 0 will suffice for maxdepth here.
  2915. bool ok = upb_refcounted_freeze(&r, 1, NULL, 0);
  2916. UPB_ASSERT_VAR(ok, ok);
  2917. }
  2918. const upb_def *upb_symtab_lookup(const upb_symtab *s, const char *sym) {
  2919. upb_value v;
  2920. upb_def *ret = upb_strtable_lookup(&s->symtab, sym, &v) ?
  2921. upb_value_getptr(v) : NULL;
  2922. return ret;
  2923. }
  2924. const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym) {
  2925. upb_value v;
  2926. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  2927. upb_value_getptr(v) : NULL;
  2928. return def ? upb_dyncast_msgdef(def) : NULL;
  2929. }
  2930. const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym) {
  2931. upb_value v;
  2932. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  2933. upb_value_getptr(v) : NULL;
  2934. return def ? upb_dyncast_enumdef(def) : NULL;
  2935. }
  2936. // Given a symbol and the base symbol inside which it is defined, find the
  2937. // symbol's definition in t.
  2938. static upb_def *upb_resolvename(const upb_strtable *t,
  2939. const char *base, const char *sym) {
  2940. if(strlen(sym) == 0) return NULL;
  2941. if(sym[0] == '.') {
  2942. // Symbols starting with '.' are absolute, so we do a single lookup.
  2943. // Slice to omit the leading '.'
  2944. upb_value v;
  2945. return upb_strtable_lookup(t, sym + 1, &v) ? upb_value_getptr(v) : NULL;
  2946. } else {
  2947. // Remove components from base until we find an entry or run out.
  2948. // TODO: This branch is totally broken, but currently not used.
  2949. (void)base;
  2950. assert(false);
  2951. return NULL;
  2952. }
  2953. }
  2954. const upb_def *upb_symtab_resolve(const upb_symtab *s, const char *base,
  2955. const char *sym) {
  2956. upb_def *ret = upb_resolvename(&s->symtab, base, sym);
  2957. return ret;
  2958. }
  2959. // Searches def and its children to find defs that have the same name as any
  2960. // def in "addtab." Returns true if any where found, and as a side-effect adds
  2961. // duplicates of these defs into addtab.
  2962. //
  2963. // We use a modified depth-first traversal that traverses each SCC (which we
  2964. // already computed) as if it were a single node. This allows us to traverse
  2965. // the possibly-cyclic graph as if it were a DAG and to dup the correct set of
  2966. // nodes with O(n) time.
  2967. static bool upb_resolve_dfs(const upb_def *def, upb_strtable *addtab,
  2968. const void *new_owner, upb_inttable *seen,
  2969. upb_status *s) {
  2970. // Memoize results of this function for efficiency (since we're traversing a
  2971. // DAG this is not needed to limit the depth of the search).
  2972. upb_value v;
  2973. if (upb_inttable_lookup(seen, (uintptr_t)def, &v))
  2974. return upb_value_getbool(v);
  2975. // Visit submessages for all messages in the SCC.
  2976. bool need_dup = false;
  2977. const upb_def *base = def;
  2978. do {
  2979. assert(upb_def_isfrozen(def));
  2980. if (def->type == UPB_DEF_FIELD) continue;
  2981. upb_value v;
  2982. if (upb_strtable_lookup(addtab, upb_def_fullname(def), &v)) {
  2983. need_dup = true;
  2984. }
  2985. // For messages, continue the recursion by visiting all subdefs.
  2986. const upb_msgdef *m = upb_dyncast_msgdef(def);
  2987. if (m) {
  2988. upb_msg_field_iter i;
  2989. for(upb_msg_field_begin(&i, m);
  2990. !upb_msg_field_done(&i);
  2991. upb_msg_field_next(&i)) {
  2992. upb_fielddef *f = upb_msg_iter_field(&i);
  2993. if (!upb_fielddef_hassubdef(f)) continue;
  2994. // |= to avoid short-circuit; we need its side-effects.
  2995. need_dup |= upb_resolve_dfs(
  2996. upb_fielddef_subdef(f), addtab, new_owner, seen, s);
  2997. if (!upb_ok(s)) return false;
  2998. }
  2999. }
  3000. } while ((def = (upb_def*)def->base.next) != base);
  3001. if (need_dup) {
  3002. // Dup any defs that don't already have entries in addtab.
  3003. def = base;
  3004. do {
  3005. if (def->type == UPB_DEF_FIELD) continue;
  3006. const char *name = upb_def_fullname(def);
  3007. if (!upb_strtable_lookup(addtab, name, NULL)) {
  3008. upb_def *newdef = upb_def_dup(def, new_owner);
  3009. if (!newdef) goto oom;
  3010. newdef->came_from_user = false;
  3011. if (!upb_strtable_insert(addtab, name, upb_value_ptr(newdef)))
  3012. goto oom;
  3013. }
  3014. } while ((def = (upb_def*)def->base.next) != base);
  3015. }
  3016. upb_inttable_insert(seen, (uintptr_t)def, upb_value_bool(need_dup));
  3017. return need_dup;
  3018. oom:
  3019. upb_status_seterrmsg(s, "out of memory");
  3020. return false;
  3021. }
  3022. // TODO(haberman): we need a lot more testing of error conditions.
  3023. // The came_from_user stuff in particular is not tested.
  3024. bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, int n, void *ref_donor,
  3025. upb_status *status) {
  3026. assert(!upb_symtab_isfrozen(s));
  3027. upb_def **add_defs = NULL;
  3028. upb_strtable addtab;
  3029. if (!upb_strtable_init(&addtab, UPB_CTYPE_PTR)) {
  3030. upb_status_seterrmsg(status, "out of memory");
  3031. return false;
  3032. }
  3033. // Add new defs to our "add" set.
  3034. for (int i = 0; i < n; i++) {
  3035. upb_def *def = defs[i];
  3036. if (upb_def_isfrozen(def)) {
  3037. upb_status_seterrmsg(status, "added defs must be mutable");
  3038. goto err;
  3039. }
  3040. assert(!upb_def_isfrozen(def));
  3041. const char *fullname = upb_def_fullname(def);
  3042. if (!fullname) {
  3043. upb_status_seterrmsg(
  3044. status, "Anonymous defs cannot be added to a symtab");
  3045. goto err;
  3046. }
  3047. upb_fielddef *f = upb_dyncast_fielddef_mutable(def);
  3048. if (f) {
  3049. if (!upb_fielddef_containingtypename(f)) {
  3050. upb_status_seterrmsg(status,
  3051. "Standalone fielddefs must have a containing type "
  3052. "(extendee) name set");
  3053. goto err;
  3054. }
  3055. } else {
  3056. if (upb_strtable_lookup(&addtab, fullname, NULL)) {
  3057. upb_status_seterrf(status, "Conflicting defs named '%s'", fullname);
  3058. goto err;
  3059. }
  3060. // We need this to back out properly, because if there is a failure we
  3061. // need to donate the ref back to the caller.
  3062. def->came_from_user = true;
  3063. upb_def_donateref(def, ref_donor, s);
  3064. if (!upb_strtable_insert(&addtab, fullname, upb_value_ptr(def)))
  3065. goto oom_err;
  3066. }
  3067. }
  3068. // Add standalone fielddefs (ie. extensions) to the appropriate messages.
  3069. // If the appropriate message only exists in the existing symtab, duplicate
  3070. // it so we have a mutable copy we can add the fields to.
  3071. for (int i = 0; i < n; i++) {
  3072. upb_def *def = defs[i];
  3073. upb_fielddef *f = upb_dyncast_fielddef_mutable(def);
  3074. if (!f) continue;
  3075. const char *msgname = upb_fielddef_containingtypename(f);
  3076. // We validated this earlier in this function.
  3077. assert(msgname);
  3078. // If the extendee name is absolutely qualified, move past the initial ".".
  3079. // TODO(haberman): it is not obvious what it would mean if this was not
  3080. // absolutely qualified.
  3081. if (msgname[0] == '.') {
  3082. msgname++;
  3083. }
  3084. upb_value v;
  3085. upb_msgdef *m;
  3086. if (upb_strtable_lookup(&addtab, msgname, &v)) {
  3087. // Extendee is in the set of defs the user asked us to add.
  3088. m = upb_value_getptr(v);
  3089. } else {
  3090. // Need to find and dup the extendee from the existing symtab.
  3091. const upb_msgdef *frozen_m = upb_symtab_lookupmsg(s, msgname);
  3092. if (!frozen_m) {
  3093. upb_status_seterrf(status,
  3094. "Tried to extend message %s that does not exist "
  3095. "in this SymbolTable.",
  3096. msgname);
  3097. goto err;
  3098. }
  3099. m = upb_msgdef_dup(frozen_m, s);
  3100. if (!m) goto oom_err;
  3101. if (!upb_strtable_insert(&addtab, msgname, upb_value_ptr(m))) {
  3102. upb_msgdef_unref(m, s);
  3103. goto oom_err;
  3104. }
  3105. }
  3106. if (!upb_msgdef_addfield(m, f, ref_donor, status)) {
  3107. goto err;
  3108. }
  3109. }
  3110. // Add dups of any existing def that can reach a def with the same name as
  3111. // anything in our "add" set.
  3112. upb_inttable seen;
  3113. if (!upb_inttable_init(&seen, UPB_CTYPE_BOOL)) goto oom_err;
  3114. upb_strtable_iter i;
  3115. upb_strtable_begin(&i, &s->symtab);
  3116. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  3117. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  3118. upb_resolve_dfs(def, &addtab, s, &seen, status);
  3119. if (!upb_ok(status)) goto err;
  3120. }
  3121. upb_inttable_uninit(&seen);
  3122. // Now using the table, resolve symbolic references for subdefs.
  3123. upb_strtable_begin(&i, &addtab);
  3124. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  3125. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  3126. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  3127. if (!m) continue;
  3128. // Type names are resolved relative to the message in which they appear.
  3129. const char *base = upb_msgdef_fullname(m);
  3130. upb_msg_field_iter j;
  3131. for(upb_msg_field_begin(&j, m);
  3132. !upb_msg_field_done(&j);
  3133. upb_msg_field_next(&j)) {
  3134. upb_fielddef *f = upb_msg_iter_field(&j);
  3135. const char *name = upb_fielddef_subdefname(f);
  3136. if (name && !upb_fielddef_subdef(f)) {
  3137. // Try the lookup in the current set of to-be-added defs first. If not
  3138. // there, try existing defs.
  3139. upb_def *subdef = upb_resolvename(&addtab, base, name);
  3140. if (subdef == NULL) {
  3141. subdef = upb_resolvename(&s->symtab, base, name);
  3142. }
  3143. if (subdef == NULL) {
  3144. upb_status_seterrf(
  3145. status, "couldn't resolve name '%s' in message '%s'", name, base);
  3146. goto err;
  3147. } else if (!upb_fielddef_setsubdef(f, subdef, status)) {
  3148. goto err;
  3149. }
  3150. }
  3151. }
  3152. }
  3153. // We need an array of the defs in addtab, for passing to upb_def_freeze.
  3154. add_defs = malloc(sizeof(void*) * upb_strtable_count(&addtab));
  3155. if (add_defs == NULL) goto oom_err;
  3156. upb_strtable_begin(&i, &addtab);
  3157. for (n = 0; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  3158. add_defs[n++] = upb_value_getptr(upb_strtable_iter_value(&i));
  3159. }
  3160. if (!upb_def_freeze(add_defs, n, status)) goto err;
  3161. // This must be delayed until all errors have been detected, since error
  3162. // recovery code uses this table to cleanup defs.
  3163. upb_strtable_uninit(&addtab);
  3164. // TODO(haberman) we don't properly handle errors after this point (like
  3165. // OOM in upb_strtable_insert() below).
  3166. for (int i = 0; i < n; i++) {
  3167. upb_def *def = add_defs[i];
  3168. const char *name = upb_def_fullname(def);
  3169. upb_value v;
  3170. if (upb_strtable_remove(&s->symtab, name, &v)) {
  3171. const upb_def *def = upb_value_getptr(v);
  3172. upb_def_unref(def, s);
  3173. }
  3174. bool success = upb_strtable_insert(&s->symtab, name, upb_value_ptr(def));
  3175. UPB_ASSERT_VAR(success, success == true);
  3176. }
  3177. free(add_defs);
  3178. return true;
  3179. oom_err:
  3180. upb_status_seterrmsg(status, "out of memory");
  3181. err: {
  3182. // For defs the user passed in, we need to donate the refs back. For defs
  3183. // we dup'd, we need to just unref them.
  3184. upb_strtable_iter i;
  3185. upb_strtable_begin(&i, &addtab);
  3186. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  3187. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  3188. bool came_from_user = def->came_from_user;
  3189. def->came_from_user = false;
  3190. if (came_from_user) {
  3191. upb_def_donateref(def, s, ref_donor);
  3192. } else {
  3193. upb_def_unref(def, s);
  3194. }
  3195. }
  3196. }
  3197. upb_strtable_uninit(&addtab);
  3198. free(add_defs);
  3199. assert(!upb_ok(status));
  3200. return false;
  3201. }
  3202. // Iteration.
  3203. static void advance_to_matching(upb_symtab_iter *iter) {
  3204. if (iter->type == UPB_DEF_ANY)
  3205. return;
  3206. while (!upb_strtable_done(&iter->iter) &&
  3207. iter->type != upb_symtab_iter_def(iter)->type) {
  3208. upb_strtable_next(&iter->iter);
  3209. }
  3210. }
  3211. void upb_symtab_begin(upb_symtab_iter *iter, const upb_symtab *s,
  3212. upb_deftype_t type) {
  3213. upb_strtable_begin(&iter->iter, &s->symtab);
  3214. iter->type = type;
  3215. advance_to_matching(iter);
  3216. }
  3217. void upb_symtab_next(upb_symtab_iter *iter) {
  3218. upb_strtable_next(&iter->iter);
  3219. advance_to_matching(iter);
  3220. }
  3221. bool upb_symtab_done(const upb_symtab_iter *iter) {
  3222. return upb_strtable_done(&iter->iter);
  3223. }
  3224. const upb_def *upb_symtab_iter_def(const upb_symtab_iter *iter) {
  3225. return upb_value_getptr(upb_strtable_iter_value(&iter->iter));
  3226. }
  3227. /*
  3228. * upb - a minimalist implementation of protocol buffers.
  3229. *
  3230. * Copyright (c) 2009 Google Inc. See LICENSE for details.
  3231. * Author: Josh Haberman <jhaberman@gmail.com>
  3232. *
  3233. * Implementation is heavily inspired by Lua's ltable.c.
  3234. */
  3235. #include <stdlib.h>
  3236. #include <string.h>
  3237. #define UPB_MAXARRSIZE 16 // 64k.
  3238. // From Chromium.
  3239. #define ARRAY_SIZE(x) \
  3240. ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
  3241. static const double MAX_LOAD = 0.85;
  3242. // The minimum utilization of the array part of a mixed hash/array table. This
  3243. // is a speed/memory-usage tradeoff (though it's not straightforward because of
  3244. // cache effects). The lower this is, the more memory we'll use.
  3245. static const double MIN_DENSITY = 0.1;
  3246. bool is_pow2(uint64_t v) { return v == 0 || (v & (v - 1)) == 0; }
  3247. int log2ceil(uint64_t v) {
  3248. int ret = 0;
  3249. bool pow2 = is_pow2(v);
  3250. while (v >>= 1) ret++;
  3251. ret = pow2 ? ret : ret + 1; // Ceiling.
  3252. return UPB_MIN(UPB_MAXARRSIZE, ret);
  3253. }
  3254. char *upb_strdup(const char *s) {
  3255. return upb_strdup2(s, strlen(s));
  3256. }
  3257. char *upb_strdup2(const char *s, size_t len) {
  3258. // Prevent overflow errors.
  3259. if (len == SIZE_MAX) return NULL;
  3260. // Always null-terminate, even if binary data; but don't rely on the input to
  3261. // have a null-terminating byte since it may be a raw binary buffer.
  3262. size_t n = len + 1;
  3263. char *p = malloc(n);
  3264. if (p) {
  3265. memcpy(p, s, len);
  3266. p[len] = 0;
  3267. }
  3268. return p;
  3269. }
  3270. // A type to represent the lookup key of either a strtable or an inttable.
  3271. typedef struct {
  3272. upb_tabkey key;
  3273. } lookupkey_t;
  3274. static lookupkey_t strkey2(const char *str, size_t len) {
  3275. lookupkey_t k;
  3276. k.key.s.str = (char*)str;
  3277. k.key.s.length = len;
  3278. return k;
  3279. }
  3280. static lookupkey_t intkey(uintptr_t key) {
  3281. lookupkey_t k;
  3282. k.key = upb_intkey(key);
  3283. return k;
  3284. }
  3285. typedef uint32_t hashfunc_t(upb_tabkey key);
  3286. typedef bool eqlfunc_t(upb_tabkey k1, lookupkey_t k2);
  3287. /* Base table (shared code) ***************************************************/
  3288. // For when we need to cast away const.
  3289. static upb_tabent *mutable_entries(upb_table *t) {
  3290. return (upb_tabent*)t->entries;
  3291. }
  3292. static bool isfull(upb_table *t) {
  3293. return (double)(t->count + 1) / upb_table_size(t) > MAX_LOAD;
  3294. }
  3295. static bool init(upb_table *t, upb_ctype_t ctype, uint8_t size_lg2) {
  3296. t->count = 0;
  3297. t->ctype = ctype;
  3298. t->size_lg2 = size_lg2;
  3299. t->mask = upb_table_size(t) ? upb_table_size(t) - 1 : 0;
  3300. size_t bytes = upb_table_size(t) * sizeof(upb_tabent);
  3301. if (bytes > 0) {
  3302. t->entries = malloc(bytes);
  3303. if (!t->entries) return false;
  3304. memset(mutable_entries(t), 0, bytes);
  3305. } else {
  3306. t->entries = NULL;
  3307. }
  3308. return true;
  3309. }
  3310. static void uninit(upb_table *t) { free(mutable_entries(t)); }
  3311. static upb_tabent *emptyent(upb_table *t) {
  3312. upb_tabent *e = mutable_entries(t) + upb_table_size(t);
  3313. while (1) { if (upb_tabent_isempty(--e)) return e; assert(e > t->entries); }
  3314. }
  3315. static upb_tabent *getentry_mutable(upb_table *t, uint32_t hash) {
  3316. return (upb_tabent*)upb_getentry(t, hash);
  3317. }
  3318. static const upb_tabent *findentry(const upb_table *t, lookupkey_t key,
  3319. uint32_t hash, eqlfunc_t *eql) {
  3320. if (t->size_lg2 == 0) return NULL;
  3321. const upb_tabent *e = upb_getentry(t, hash);
  3322. if (upb_tabent_isempty(e)) return NULL;
  3323. while (1) {
  3324. if (eql(e->key, key)) return e;
  3325. if ((e = e->next) == NULL) return NULL;
  3326. }
  3327. }
  3328. static upb_tabent *findentry_mutable(upb_table *t, lookupkey_t key,
  3329. uint32_t hash, eqlfunc_t *eql) {
  3330. return (upb_tabent*)findentry(t, key, hash, eql);
  3331. }
  3332. static bool lookup(const upb_table *t, lookupkey_t key, upb_value *v,
  3333. uint32_t hash, eqlfunc_t *eql) {
  3334. const upb_tabent *e = findentry(t, key, hash, eql);
  3335. if (e) {
  3336. if (v) {
  3337. _upb_value_setval(v, e->val, t->ctype);
  3338. }
  3339. return true;
  3340. } else {
  3341. return false;
  3342. }
  3343. }
  3344. // The given key must not already exist in the table.
  3345. static void insert(upb_table *t, lookupkey_t key, upb_value val,
  3346. uint32_t hash, hashfunc_t *hashfunc, eqlfunc_t *eql) {
  3347. UPB_UNUSED(eql);
  3348. assert(findentry(t, key, hash, eql) == NULL);
  3349. assert(val.ctype == t->ctype);
  3350. t->count++;
  3351. upb_tabent *mainpos_e = getentry_mutable(t, hash);
  3352. upb_tabent *our_e = mainpos_e;
  3353. if (upb_tabent_isempty(mainpos_e)) {
  3354. // Our main position is empty; use it.
  3355. our_e->next = NULL;
  3356. } else {
  3357. // Collision.
  3358. upb_tabent *new_e = emptyent(t);
  3359. // Head of collider's chain.
  3360. upb_tabent *chain = getentry_mutable(t, hashfunc(mainpos_e->key));
  3361. if (chain == mainpos_e) {
  3362. // Existing ent is in its main posisiton (it has the same hash as us, and
  3363. // is the head of our chain). Insert to new ent and append to this chain.
  3364. new_e->next = mainpos_e->next;
  3365. mainpos_e->next = new_e;
  3366. our_e = new_e;
  3367. } else {
  3368. // Existing ent is not in its main position (it is a node in some other
  3369. // chain). This implies that no existing ent in the table has our hash.
  3370. // Evict it (updating its chain) and use its ent for head of our chain.
  3371. *new_e = *mainpos_e; // copies next.
  3372. while (chain->next != mainpos_e) {
  3373. chain = (upb_tabent*)chain->next;
  3374. assert(chain);
  3375. }
  3376. chain->next = new_e;
  3377. our_e = mainpos_e;
  3378. our_e->next = NULL;
  3379. }
  3380. }
  3381. our_e->key = key.key;
  3382. our_e->val = val.val;
  3383. assert(findentry(t, key, hash, eql) == our_e);
  3384. }
  3385. static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
  3386. upb_tabkey *removed, uint32_t hash, eqlfunc_t *eql) {
  3387. upb_tabent *chain = getentry_mutable(t, hash);
  3388. if (upb_tabent_isempty(chain)) return false;
  3389. if (eql(chain->key, key)) {
  3390. // Element to remove is at the head of its chain.
  3391. t->count--;
  3392. if (val) {
  3393. _upb_value_setval(val, chain->val, t->ctype);
  3394. }
  3395. if (chain->next) {
  3396. upb_tabent *move = (upb_tabent*)chain->next;
  3397. *chain = *move;
  3398. if (removed) *removed = move->key;
  3399. move->key.num = 0; // Make the slot empty.
  3400. } else {
  3401. if (removed) *removed = chain->key;
  3402. chain->key.num = 0; // Make the slot empty.
  3403. }
  3404. return true;
  3405. } else {
  3406. // Element to remove is either in a non-head position or not in the table.
  3407. while (chain->next && !eql(chain->next->key, key))
  3408. chain = (upb_tabent*)chain->next;
  3409. if (chain->next) {
  3410. // Found element to remove.
  3411. if (val) {
  3412. _upb_value_setval(val, chain->next->val, t->ctype);
  3413. }
  3414. upb_tabent *rm = (upb_tabent*)chain->next;
  3415. if (removed) *removed = rm->key;
  3416. rm->key.num = 0;
  3417. chain->next = rm->next;
  3418. t->count--;
  3419. return true;
  3420. } else {
  3421. return false;
  3422. }
  3423. }
  3424. }
  3425. static size_t next(const upb_table *t, size_t i) {
  3426. do {
  3427. if (++i >= upb_table_size(t))
  3428. return SIZE_MAX;
  3429. } while(upb_tabent_isempty(&t->entries[i]));
  3430. return i;
  3431. }
  3432. static size_t begin(const upb_table *t) {
  3433. return next(t, -1);
  3434. }
  3435. /* upb_strtable ***************************************************************/
  3436. // A simple "subclass" of upb_table that only adds a hash function for strings.
  3437. static uint32_t strhash(upb_tabkey key) {
  3438. return MurmurHash2(key.s.str, key.s.length, 0);
  3439. }
  3440. static bool streql(upb_tabkey k1, lookupkey_t k2) {
  3441. return k1.s.length == k2.key.s.length &&
  3442. memcmp(k1.s.str, k2.key.s.str, k1.s.length) == 0;
  3443. }
  3444. bool upb_strtable_init(upb_strtable *t, upb_ctype_t ctype) {
  3445. return init(&t->t, ctype, 2);
  3446. }
  3447. void upb_strtable_uninit(upb_strtable *t) {
  3448. for (size_t i = 0; i < upb_table_size(&t->t); i++)
  3449. free((void*)t->t.entries[i].key.s.str);
  3450. uninit(&t->t);
  3451. }
  3452. bool upb_strtable_resize(upb_strtable *t, size_t size_lg2) {
  3453. upb_strtable new_table;
  3454. if (!init(&new_table.t, t->t.ctype, size_lg2))
  3455. return false;
  3456. upb_strtable_iter i;
  3457. upb_strtable_begin(&i, t);
  3458. for ( ; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  3459. upb_strtable_insert2(
  3460. &new_table,
  3461. upb_strtable_iter_key(&i),
  3462. upb_strtable_iter_keylength(&i),
  3463. upb_strtable_iter_value(&i));
  3464. }
  3465. upb_strtable_uninit(t);
  3466. *t = new_table;
  3467. return true;
  3468. }
  3469. bool upb_strtable_insert2(upb_strtable *t, const char *k, size_t len,
  3470. upb_value v) {
  3471. if (isfull(&t->t)) {
  3472. // Need to resize. New table of double the size, add old elements to it.
  3473. if (!upb_strtable_resize(t, t->t.size_lg2 + 1)) {
  3474. return false;
  3475. }
  3476. }
  3477. if ((k = upb_strdup2(k, len)) == NULL) return false;
  3478. lookupkey_t key = strkey2(k, len);
  3479. uint32_t hash = MurmurHash2(key.key.s.str, key.key.s.length, 0);
  3480. insert(&t->t, key, v, hash, &strhash, &streql);
  3481. return true;
  3482. }
  3483. bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
  3484. upb_value *v) {
  3485. uint32_t hash = MurmurHash2(key, len, 0);
  3486. return lookup(&t->t, strkey2(key, len), v, hash, &streql);
  3487. }
  3488. bool upb_strtable_remove2(upb_strtable *t, const char *key, size_t len,
  3489. upb_value *val) {
  3490. uint32_t hash = MurmurHash2(key, strlen(key), 0);
  3491. upb_tabkey tabkey;
  3492. if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
  3493. free((void*)tabkey.s.str);
  3494. return true;
  3495. } else {
  3496. return false;
  3497. }
  3498. }
  3499. // Iteration
  3500. static const upb_tabent *str_tabent(const upb_strtable_iter *i) {
  3501. return &i->t->t.entries[i->index];
  3502. }
  3503. void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t) {
  3504. i->t = t;
  3505. i->index = begin(&t->t);
  3506. }
  3507. void upb_strtable_next(upb_strtable_iter *i) {
  3508. i->index = next(&i->t->t, i->index);
  3509. }
  3510. bool upb_strtable_done(const upb_strtable_iter *i) {
  3511. return i->index >= upb_table_size(&i->t->t) ||
  3512. upb_tabent_isempty(str_tabent(i));
  3513. }
  3514. const char *upb_strtable_iter_key(upb_strtable_iter *i) {
  3515. assert(!upb_strtable_done(i));
  3516. return str_tabent(i)->key.s.str;
  3517. }
  3518. size_t upb_strtable_iter_keylength(upb_strtable_iter *i) {
  3519. assert(!upb_strtable_done(i));
  3520. return str_tabent(i)->key.s.length;
  3521. }
  3522. upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
  3523. assert(!upb_strtable_done(i));
  3524. return _upb_value_val(str_tabent(i)->val, i->t->t.ctype);
  3525. }
  3526. void upb_strtable_iter_setdone(upb_strtable_iter *i) {
  3527. i->index = SIZE_MAX;
  3528. }
  3529. bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
  3530. const upb_strtable_iter *i2) {
  3531. if (upb_strtable_done(i1) && upb_strtable_done(i2))
  3532. return true;
  3533. return i1->t == i2->t && i1->index == i2->index;
  3534. }
  3535. /* upb_inttable ***************************************************************/
  3536. // For inttables we use a hybrid structure where small keys are kept in an
  3537. // array and large keys are put in the hash table.
  3538. static uint32_t inthash(upb_tabkey key) { return upb_inthash(key.num); }
  3539. static bool inteql(upb_tabkey k1, lookupkey_t k2) {
  3540. return k1.num == k2.key.num;
  3541. }
  3542. static _upb_value *mutable_array(upb_inttable *t) {
  3543. return (_upb_value*)t->array;
  3544. }
  3545. static _upb_value *inttable_val(upb_inttable *t, uintptr_t key) {
  3546. if (key < t->array_size) {
  3547. return upb_arrhas(t->array[key]) ? &(mutable_array(t)[key]) : NULL;
  3548. } else {
  3549. upb_tabent *e =
  3550. findentry_mutable(&t->t, intkey(key), upb_inthash(key), &inteql);
  3551. return e ? &e->val : NULL;
  3552. }
  3553. }
  3554. static const _upb_value *inttable_val_const(const upb_inttable *t,
  3555. uintptr_t key) {
  3556. return inttable_val((upb_inttable*)t, key);
  3557. }
  3558. size_t upb_inttable_count(const upb_inttable *t) {
  3559. return t->t.count + t->array_count;
  3560. }
  3561. static void check(upb_inttable *t) {
  3562. UPB_UNUSED(t);
  3563. #if defined(UPB_DEBUG_TABLE) && !defined(NDEBUG)
  3564. // This check is very expensive (makes inserts/deletes O(N)).
  3565. size_t count = 0;
  3566. upb_inttable_iter i;
  3567. upb_inttable_begin(&i, t);
  3568. for(; !upb_inttable_done(&i); upb_inttable_next(&i), count++) {
  3569. assert(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
  3570. }
  3571. assert(count == upb_inttable_count(t));
  3572. #endif
  3573. }
  3574. bool upb_inttable_sizedinit(upb_inttable *t, upb_ctype_t ctype,
  3575. size_t asize, int hsize_lg2) {
  3576. if (!init(&t->t, ctype, hsize_lg2)) return false;
  3577. // Always make the array part at least 1 long, so that we know key 0
  3578. // won't be in the hash part, which simplifies things.
  3579. t->array_size = UPB_MAX(1, asize);
  3580. t->array_count = 0;
  3581. size_t array_bytes = t->array_size * sizeof(upb_value);
  3582. t->array = malloc(array_bytes);
  3583. if (!t->array) {
  3584. uninit(&t->t);
  3585. return false;
  3586. }
  3587. memset(mutable_array(t), 0xff, array_bytes);
  3588. check(t);
  3589. return true;
  3590. }
  3591. bool upb_inttable_init(upb_inttable *t, upb_ctype_t ctype) {
  3592. return upb_inttable_sizedinit(t, ctype, 0, 4);
  3593. }
  3594. void upb_inttable_uninit(upb_inttable *t) {
  3595. uninit(&t->t);
  3596. free(mutable_array(t));
  3597. }
  3598. bool upb_inttable_insert(upb_inttable *t, uintptr_t key, upb_value val) {
  3599. assert(upb_arrhas(val.val));
  3600. if (key < t->array_size) {
  3601. assert(!upb_arrhas(t->array[key]));
  3602. t->array_count++;
  3603. mutable_array(t)[key] = val.val;
  3604. } else {
  3605. if (isfull(&t->t)) {
  3606. // Need to resize the hash part, but we re-use the array part.
  3607. upb_table new_table;
  3608. if (!init(&new_table, t->t.ctype, t->t.size_lg2 + 1))
  3609. return false;
  3610. size_t i;
  3611. for (i = begin(&t->t); i < upb_table_size(&t->t); i = next(&t->t, i)) {
  3612. const upb_tabent *e = &t->t.entries[i];
  3613. upb_value v;
  3614. _upb_value_setval(&v, e->val, t->t.ctype);
  3615. uint32_t hash = upb_inthash(e->key.num);
  3616. insert(&new_table, intkey(e->key.num), v, hash, &inthash, &inteql);
  3617. }
  3618. assert(t->t.count == new_table.count);
  3619. uninit(&t->t);
  3620. t->t = new_table;
  3621. }
  3622. insert(&t->t, intkey(key), val, upb_inthash(key), &inthash, &inteql);
  3623. }
  3624. check(t);
  3625. return true;
  3626. }
  3627. bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v) {
  3628. const _upb_value *table_v = inttable_val_const(t, key);
  3629. if (!table_v) return false;
  3630. if (v) _upb_value_setval(v, *table_v, t->t.ctype);
  3631. return true;
  3632. }
  3633. bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val) {
  3634. _upb_value *table_v = inttable_val(t, key);
  3635. if (!table_v) return false;
  3636. *table_v = val.val;
  3637. return true;
  3638. }
  3639. bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val) {
  3640. bool success;
  3641. if (key < t->array_size) {
  3642. if (upb_arrhas(t->array[key])) {
  3643. t->array_count--;
  3644. if (val) {
  3645. _upb_value_setval(val, t->array[key], t->t.ctype);
  3646. }
  3647. _upb_value empty = UPB_ARRAY_EMPTYENT;
  3648. mutable_array(t)[key] = empty;
  3649. success = true;
  3650. } else {
  3651. success = false;
  3652. }
  3653. } else {
  3654. upb_tabkey removed;
  3655. uint32_t hash = upb_inthash(key);
  3656. success = rm(&t->t, intkey(key), val, &removed, hash, &inteql);
  3657. }
  3658. check(t);
  3659. return success;
  3660. }
  3661. bool upb_inttable_push(upb_inttable *t, upb_value val) {
  3662. return upb_inttable_insert(t, upb_inttable_count(t), val);
  3663. }
  3664. upb_value upb_inttable_pop(upb_inttable *t) {
  3665. upb_value val;
  3666. bool ok = upb_inttable_remove(t, upb_inttable_count(t) - 1, &val);
  3667. UPB_ASSERT_VAR(ok, ok);
  3668. return val;
  3669. }
  3670. bool upb_inttable_insertptr(upb_inttable *t, const void *key, upb_value val) {
  3671. return upb_inttable_insert(t, (uintptr_t)key, val);
  3672. }
  3673. bool upb_inttable_lookupptr(const upb_inttable *t, const void *key,
  3674. upb_value *v) {
  3675. return upb_inttable_lookup(t, (uintptr_t)key, v);
  3676. }
  3677. bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val) {
  3678. return upb_inttable_remove(t, (uintptr_t)key, val);
  3679. }
  3680. void upb_inttable_compact(upb_inttable *t) {
  3681. // Create a power-of-two histogram of the table keys.
  3682. int counts[UPB_MAXARRSIZE + 1] = {0};
  3683. uintptr_t max_key = 0;
  3684. upb_inttable_iter i;
  3685. upb_inttable_begin(&i, t);
  3686. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  3687. uintptr_t key = upb_inttable_iter_key(&i);
  3688. if (key > max_key) {
  3689. max_key = key;
  3690. }
  3691. counts[log2ceil(key)]++;
  3692. }
  3693. int arr_size;
  3694. int arr_count = upb_inttable_count(t);
  3695. if (upb_inttable_count(t) >= max_key * MIN_DENSITY) {
  3696. // We can put 100% of the entries in the array part.
  3697. arr_size = max_key + 1;
  3698. } else {
  3699. // Find the largest power of two that satisfies the MIN_DENSITY definition.
  3700. for (int size_lg2 = ARRAY_SIZE(counts) - 1; size_lg2 > 1; size_lg2--) {
  3701. arr_size = 1 << size_lg2;
  3702. arr_count -= counts[size_lg2];
  3703. if (arr_count >= arr_size * MIN_DENSITY) {
  3704. break;
  3705. }
  3706. }
  3707. }
  3708. // Array part must always be at least 1 entry large to catch lookups of key
  3709. // 0. Key 0 must always be in the array part because "0" in the hash part
  3710. // denotes an empty entry.
  3711. arr_size = UPB_MAX(arr_size, 1);
  3712. // Insert all elements into new, perfectly-sized table.
  3713. int hash_count = upb_inttable_count(t) - arr_count;
  3714. int hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
  3715. int hashsize_lg2 = log2ceil(hash_size);
  3716. assert(hash_count >= 0);
  3717. upb_inttable new_t;
  3718. upb_inttable_sizedinit(&new_t, t->t.ctype, arr_size, hashsize_lg2);
  3719. upb_inttable_begin(&i, t);
  3720. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  3721. uintptr_t k = upb_inttable_iter_key(&i);
  3722. upb_inttable_insert(&new_t, k, upb_inttable_iter_value(&i));
  3723. }
  3724. assert(new_t.array_size == arr_size);
  3725. assert(new_t.t.size_lg2 == hashsize_lg2);
  3726. upb_inttable_uninit(t);
  3727. *t = new_t;
  3728. }
  3729. // Iteration.
  3730. static const upb_tabent *int_tabent(const upb_inttable_iter *i) {
  3731. assert(!i->array_part);
  3732. return &i->t->t.entries[i->index];
  3733. }
  3734. static _upb_value int_arrent(const upb_inttable_iter *i) {
  3735. assert(i->array_part);
  3736. return i->t->array[i->index];
  3737. }
  3738. void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t) {
  3739. i->t = t;
  3740. i->index = -1;
  3741. i->array_part = true;
  3742. upb_inttable_next(i);
  3743. }
  3744. void upb_inttable_next(upb_inttable_iter *iter) {
  3745. const upb_inttable *t = iter->t;
  3746. if (iter->array_part) {
  3747. while (++iter->index < t->array_size) {
  3748. if (upb_arrhas(int_arrent(iter))) {
  3749. return;
  3750. }
  3751. }
  3752. iter->array_part = false;
  3753. iter->index = begin(&t->t);
  3754. } else {
  3755. iter->index = next(&t->t, iter->index);
  3756. }
  3757. }
  3758. bool upb_inttable_done(const upb_inttable_iter *i) {
  3759. if (i->array_part) {
  3760. return i->index >= i->t->array_size ||
  3761. !upb_arrhas(int_arrent(i));
  3762. } else {
  3763. return i->index >= upb_table_size(&i->t->t) ||
  3764. upb_tabent_isempty(int_tabent(i));
  3765. }
  3766. }
  3767. uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i) {
  3768. assert(!upb_inttable_done(i));
  3769. return i->array_part ? i->index : int_tabent(i)->key.num;
  3770. }
  3771. upb_value upb_inttable_iter_value(const upb_inttable_iter *i) {
  3772. assert(!upb_inttable_done(i));
  3773. return _upb_value_val(
  3774. i->array_part ? i->t->array[i->index] : int_tabent(i)->val,
  3775. i->t->t.ctype);
  3776. }
  3777. void upb_inttable_iter_setdone(upb_inttable_iter *i) {
  3778. i->index = SIZE_MAX;
  3779. i->array_part = false;
  3780. }
  3781. bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
  3782. const upb_inttable_iter *i2) {
  3783. if (upb_inttable_done(i1) && upb_inttable_done(i2))
  3784. return true;
  3785. return i1->t == i2->t && i1->index == i2->index &&
  3786. i1->array_part == i2->array_part;
  3787. }
  3788. #ifdef UPB_UNALIGNED_READS_OK
  3789. //-----------------------------------------------------------------------------
  3790. // MurmurHash2, by Austin Appleby (released as public domain).
  3791. // Reformatted and C99-ified by Joshua Haberman.
  3792. // Note - This code makes a few assumptions about how your machine behaves -
  3793. // 1. We can read a 4-byte value from any address without crashing
  3794. // 2. sizeof(int) == 4 (in upb this limitation is removed by using uint32_t
  3795. // And it has a few limitations -
  3796. // 1. It will not work incrementally.
  3797. // 2. It will not produce the same results on little-endian and big-endian
  3798. // machines.
  3799. uint32_t MurmurHash2(const void *key, size_t len, uint32_t seed) {
  3800. // 'm' and 'r' are mixing constants generated offline.
  3801. // They're not really 'magic', they just happen to work well.
  3802. const uint32_t m = 0x5bd1e995;
  3803. const int32_t r = 24;
  3804. // Initialize the hash to a 'random' value
  3805. uint32_t h = seed ^ len;
  3806. // Mix 4 bytes at a time into the hash
  3807. const uint8_t * data = (const uint8_t *)key;
  3808. while(len >= 4) {
  3809. uint32_t k = *(uint32_t *)data;
  3810. k *= m;
  3811. k ^= k >> r;
  3812. k *= m;
  3813. h *= m;
  3814. h ^= k;
  3815. data += 4;
  3816. len -= 4;
  3817. }
  3818. // Handle the last few bytes of the input array
  3819. switch(len) {
  3820. case 3: h ^= data[2] << 16;
  3821. case 2: h ^= data[1] << 8;
  3822. case 1: h ^= data[0]; h *= m;
  3823. };
  3824. // Do a few final mixes of the hash to ensure the last few
  3825. // bytes are well-incorporated.
  3826. h ^= h >> 13;
  3827. h *= m;
  3828. h ^= h >> 15;
  3829. return h;
  3830. }
  3831. #else // !UPB_UNALIGNED_READS_OK
  3832. //-----------------------------------------------------------------------------
  3833. // MurmurHashAligned2, by Austin Appleby
  3834. // Same algorithm as MurmurHash2, but only does aligned reads - should be safer
  3835. // on certain platforms.
  3836. // Performance will be lower than MurmurHash2
  3837. #define MIX(h,k,m) { k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; }
  3838. uint32_t MurmurHash2(const void * key, size_t len, uint32_t seed) {
  3839. const uint32_t m = 0x5bd1e995;
  3840. const int32_t r = 24;
  3841. const uint8_t * data = (const uint8_t *)key;
  3842. uint32_t h = seed ^ len;
  3843. uint8_t align = (uintptr_t)data & 3;
  3844. if(align && (len >= 4)) {
  3845. // Pre-load the temp registers
  3846. uint32_t t = 0, d = 0;
  3847. switch(align) {
  3848. case 1: t |= data[2] << 16;
  3849. case 2: t |= data[1] << 8;
  3850. case 3: t |= data[0];
  3851. }
  3852. t <<= (8 * align);
  3853. data += 4-align;
  3854. len -= 4-align;
  3855. int32_t sl = 8 * (4-align);
  3856. int32_t sr = 8 * align;
  3857. // Mix
  3858. while(len >= 4) {
  3859. d = *(uint32_t *)data;
  3860. t = (t >> sr) | (d << sl);
  3861. uint32_t k = t;
  3862. MIX(h,k,m);
  3863. t = d;
  3864. data += 4;
  3865. len -= 4;
  3866. }
  3867. // Handle leftover data in temp registers
  3868. d = 0;
  3869. if(len >= align) {
  3870. switch(align) {
  3871. case 3: d |= data[2] << 16;
  3872. case 2: d |= data[1] << 8;
  3873. case 1: d |= data[0];
  3874. }
  3875. uint32_t k = (t >> sr) | (d << sl);
  3876. MIX(h,k,m);
  3877. data += align;
  3878. len -= align;
  3879. //----------
  3880. // Handle tail bytes
  3881. switch(len) {
  3882. case 3: h ^= data[2] << 16;
  3883. case 2: h ^= data[1] << 8;
  3884. case 1: h ^= data[0]; h *= m;
  3885. };
  3886. } else {
  3887. switch(len) {
  3888. case 3: d |= data[2] << 16;
  3889. case 2: d |= data[1] << 8;
  3890. case 1: d |= data[0];
  3891. case 0: h ^= (t >> sr) | (d << sl); h *= m;
  3892. }
  3893. }
  3894. h ^= h >> 13;
  3895. h *= m;
  3896. h ^= h >> 15;
  3897. return h;
  3898. } else {
  3899. while(len >= 4) {
  3900. uint32_t k = *(uint32_t *)data;
  3901. MIX(h,k,m);
  3902. data += 4;
  3903. len -= 4;
  3904. }
  3905. //----------
  3906. // Handle tail bytes
  3907. switch(len) {
  3908. case 3: h ^= data[2] << 16;
  3909. case 2: h ^= data[1] << 8;
  3910. case 1: h ^= data[0]; h *= m;
  3911. };
  3912. h ^= h >> 13;
  3913. h *= m;
  3914. h ^= h >> 15;
  3915. return h;
  3916. }
  3917. }
  3918. #undef MIX
  3919. #endif // UPB_UNALIGNED_READS_OK
  3920. /*
  3921. * upb - a minimalist implementation of protocol buffers.
  3922. *
  3923. * Copyright (c) 2009-2012 Google Inc. See LICENSE for details.
  3924. * Author: Josh Haberman <jhaberman@gmail.com>
  3925. */
  3926. #include <errno.h>
  3927. #include <stdarg.h>
  3928. #include <stddef.h>
  3929. #include <stdint.h>
  3930. #include <stdio.h>
  3931. #include <stdlib.h>
  3932. #include <string.h>
  3933. bool upb_dumptostderr(void *closure, const upb_status* status) {
  3934. UPB_UNUSED(closure);
  3935. fprintf(stderr, "%s\n", upb_status_errmsg(status));
  3936. return false;
  3937. }
  3938. // Guarantee null-termination and provide ellipsis truncation.
  3939. // It may be tempting to "optimize" this by initializing these final
  3940. // four bytes up-front and then being careful never to overwrite them,
  3941. // this is safer and simpler.
  3942. static void nullz(upb_status *status) {
  3943. const char *ellipsis = "...";
  3944. size_t len = strlen(ellipsis);
  3945. assert(sizeof(status->msg) > len);
  3946. memcpy(status->msg + sizeof(status->msg) - len, ellipsis, len);
  3947. }
  3948. void upb_status_clear(upb_status *status) {
  3949. if (!status) return;
  3950. status->ok_ = true;
  3951. status->code_ = 0;
  3952. status->msg[0] = '\0';
  3953. }
  3954. bool upb_ok(const upb_status *status) { return status->ok_; }
  3955. upb_errorspace *upb_status_errspace(const upb_status *status) {
  3956. return status->error_space_;
  3957. }
  3958. int upb_status_errcode(const upb_status *status) { return status->code_; }
  3959. const char *upb_status_errmsg(const upb_status *status) { return status->msg; }
  3960. void upb_status_seterrmsg(upb_status *status, const char *msg) {
  3961. if (!status) return;
  3962. status->ok_ = false;
  3963. strncpy(status->msg, msg, sizeof(status->msg));
  3964. nullz(status);
  3965. }
  3966. void upb_status_seterrf(upb_status *status, const char *fmt, ...) {
  3967. va_list args;
  3968. va_start(args, fmt);
  3969. upb_status_vseterrf(status, fmt, args);
  3970. va_end(args);
  3971. }
  3972. void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args) {
  3973. if (!status) return;
  3974. status->ok_ = false;
  3975. vsnprintf(status->msg, sizeof(status->msg), fmt, args);
  3976. nullz(status);
  3977. }
  3978. void upb_status_seterrcode(upb_status *status, upb_errorspace *space,
  3979. int code) {
  3980. if (!status) return;
  3981. status->ok_ = false;
  3982. status->error_space_ = space;
  3983. status->code_ = code;
  3984. space->set_message(status, code);
  3985. }
  3986. void upb_status_copy(upb_status *to, const upb_status *from) {
  3987. if (!to) return;
  3988. *to = *from;
  3989. }
  3990. // This file was generated by upbc (the upb compiler).
  3991. // Do not edit -- your changes will be discarded when the file is
  3992. // regenerated.
  3993. static const upb_msgdef msgs[20];
  3994. static const upb_fielddef fields[81];
  3995. static const upb_enumdef enums[4];
  3996. static const upb_tabent strentries[236];
  3997. static const upb_tabent intentries[14];
  3998. static const _upb_value arrays[232];
  3999. #ifdef UPB_DEBUG_REFS
  4000. static upb_inttable reftables[212];
  4001. #endif
  4002. static const upb_msgdef msgs[20] = {
  4003. 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]),
  4004. 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]),
  4005. 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]),
  4006. 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]),
  4007. 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]),
  4008. 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]),
  4009. 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]),
  4010. 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]),
  4011. 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]),
  4012. 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]),
  4013. 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]),
  4014. 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]),
  4015. 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]),
  4016. 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]),
  4017. 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]),
  4018. 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]),
  4019. 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]),
  4020. 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]),
  4021. 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]),
  4022. 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]),
  4023. };
  4024. static const upb_fielddef fields[81] = {
  4025. 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]),
  4026. 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]),
  4027. 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]),
  4028. 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]),
  4029. 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]),
  4030. 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]),
  4031. 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]),
  4032. 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]),
  4033. 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]),
  4034. 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]),
  4035. 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]),
  4036. 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]),
  4037. 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]),
  4038. 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]),
  4039. 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]),
  4040. 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]),
  4041. 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]),
  4042. 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]),
  4043. 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]),
  4044. 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]),
  4045. 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]),
  4046. 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]),
  4047. 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]),
  4048. 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]),
  4049. 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]),
  4050. 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]),
  4051. 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]),
  4052. 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]),
  4053. 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]),
  4054. 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]),
  4055. 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]),
  4056. 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]),
  4057. 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]),
  4058. 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]),
  4059. 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]),
  4060. 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]),
  4061. 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]),
  4062. 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]),
  4063. 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]),
  4064. 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]),
  4065. 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]),
  4066. 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]),
  4067. 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]),
  4068. 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]),
  4069. 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]),
  4070. 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]),
  4071. 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]),
  4072. 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]),
  4073. 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]),
  4074. 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]),
  4075. 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]),
  4076. 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]),
  4077. 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]),
  4078. 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]),
  4079. 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]),
  4080. 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]),
  4081. 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]),
  4082. 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]),
  4083. 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]),
  4084. 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]),
  4085. 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]),
  4086. 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]),
  4087. 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]),
  4088. 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]),
  4089. 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]),
  4090. 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]),
  4091. 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]),
  4092. 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]),
  4093. 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]),
  4094. 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]),
  4095. 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]),
  4096. 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]),
  4097. 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]),
  4098. 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]),
  4099. 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]),
  4100. 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]),
  4101. 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]),
  4102. 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]),
  4103. 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]),
  4104. 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]),
  4105. 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]),
  4106. };
  4107. static const upb_enumdef enums[4] = {
  4108. 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]),
  4109. 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]),
  4110. 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]),
  4111. 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]),
  4112. };
  4113. static const upb_tabent strentries[236] = {
  4114. {UPB_TABKEY_STR("extension"), UPB_VALUE_INIT_CONSTPTR(&fields[14]), NULL},
  4115. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4116. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4117. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[38]), NULL},
  4118. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4119. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4120. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4121. {UPB_TABKEY_STR("field"), UPB_VALUE_INIT_CONSTPTR(&fields[16]), NULL},
  4122. {UPB_TABKEY_STR("extension_range"), UPB_VALUE_INIT_CONSTPTR(&fields[15]), NULL},
  4123. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4124. {UPB_TABKEY_STR("nested_type"), UPB_VALUE_INIT_CONSTPTR(&fields[44]), 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_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[49]), NULL},
  4129. {UPB_TABKEY_STR("enum_type"), UPB_VALUE_INIT_CONSTPTR(&fields[9]), &strentries[14]},
  4130. {UPB_TABKEY_STR("start"), UPB_VALUE_INIT_CONSTPTR(&fields[66]), NULL},
  4131. {UPB_TABKEY_STR("end"), UPB_VALUE_INIT_CONSTPTR(&fields[8]), 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_STR("value"), UPB_VALUE_INIT_CONSTPTR(&fields[78]), NULL},
  4136. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[50]), NULL},
  4137. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[40]), &strentries[22]},
  4138. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[73]), NULL},
  4139. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4140. {UPB_TABKEY_STR("allow_alias"), UPB_VALUE_INIT_CONSTPTR(&fields[1]), NULL},
  4141. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4142. {UPB_TABKEY_STR("number"), UPB_VALUE_INIT_CONSTPTR(&fields[47]), NULL},
  4143. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4144. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[52]), NULL},
  4145. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[37]), &strentries[30]},
  4146. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[71]), 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("label"), UPB_VALUE_INIT_CONSTPTR(&fields[27]), NULL},
  4152. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4153. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[41]), NULL},
  4154. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4155. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4156. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4157. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4158. {UPB_TABKEY_STR("number"), UPB_VALUE_INIT_CONSTPTR(&fields[46]), &strentries[49]},
  4159. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4160. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4161. {UPB_TABKEY_STR("type_name"), UPB_VALUE_INIT_CONSTPTR(&fields[70]), NULL},
  4162. {UPB_TABKEY_STR("extendee"), UPB_VALUE_INIT_CONSTPTR(&fields[12]), NULL},
  4163. {UPB_TABKEY_STR("type"), UPB_VALUE_INIT_CONSTPTR(&fields[69]), &strentries[48]},
  4164. {UPB_TABKEY_STR("default_value"), UPB_VALUE_INIT_CONSTPTR(&fields[4]), NULL},
  4165. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[51]), NULL},
  4166. {UPB_TABKEY_STR("experimental_map_key"), UPB_VALUE_INIT_CONSTPTR(&fields[11]), &strentries[67]},
  4167. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4168. {UPB_TABKEY_STR("weak"), UPB_VALUE_INIT_CONSTPTR(&fields[79]), NULL},
  4169. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4170. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4171. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4172. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4173. {UPB_TABKEY_STR("packed"), UPB_VALUE_INIT_CONSTPTR(&fields[58]), NULL},
  4174. {UPB_TABKEY_STR("lazy"), UPB_VALUE_INIT_CONSTPTR(&fields[28]), NULL},
  4175. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4176. {UPB_TABKEY_STR("ctype"), UPB_VALUE_INIT_CONSTPTR(&fields[3]), NULL},
  4177. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4178. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4179. {UPB_TABKEY_STR("deprecated"), UPB_VALUE_INIT_CONSTPTR(&fields[6]), NULL},
  4180. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4181. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[77]), NULL},
  4182. {UPB_TABKEY_STR("extension"), UPB_VALUE_INIT_CONSTPTR(&fields[13]), NULL},
  4183. {UPB_TABKEY_STR("weak_dependency"), UPB_VALUE_INIT_CONSTPTR(&fields[80]), NULL},
  4184. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4185. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[34]), NULL},
  4186. {UPB_TABKEY_STR("service"), UPB_VALUE_INIT_CONSTPTR(&fields[63]), NULL},
  4187. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4188. {UPB_TABKEY_STR("source_code_info"), UPB_VALUE_INIT_CONSTPTR(&fields[64]), NULL},
  4189. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4190. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4191. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4192. {UPB_TABKEY_STR("dependency"), UPB_VALUE_INIT_CONSTPTR(&fields[5]), NULL},
  4193. {UPB_TABKEY_STR("message_type"), UPB_VALUE_INIT_CONSTPTR(&fields[32]), NULL},
  4194. {UPB_TABKEY_STR("package"), UPB_VALUE_INIT_CONSTPTR(&fields[57]), NULL},
  4195. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[53]), &strentries[82]},
  4196. {UPB_TABKEY_STR("enum_type"), UPB_VALUE_INIT_CONSTPTR(&fields[10]), NULL},
  4197. {UPB_TABKEY_STR("public_dependency"), UPB_VALUE_INIT_CONSTPTR(&fields[61]), &strentries[81]},
  4198. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4199. {UPB_TABKEY_STR("file"), UPB_VALUE_INIT_CONSTPTR(&fields[17]), NULL},
  4200. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4201. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4202. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[75]), NULL},
  4203. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4204. {UPB_TABKEY_STR("cc_generic_services"), UPB_VALUE_INIT_CONSTPTR(&fields[2]), NULL},
  4205. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4206. {UPB_TABKEY_STR("java_multiple_files"), UPB_VALUE_INIT_CONSTPTR(&fields[24]), NULL},
  4207. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4208. {UPB_TABKEY_STR("java_generic_services"), UPB_VALUE_INIT_CONSTPTR(&fields[23]), &strentries[102]},
  4209. {UPB_TABKEY_STR("java_generate_equals_and_hash"), UPB_VALUE_INIT_CONSTPTR(&fields[22]), 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("go_package"), UPB_VALUE_INIT_CONSTPTR(&fields[18]), NULL},
  4214. {UPB_TABKEY_STR("java_package"), UPB_VALUE_INIT_CONSTPTR(&fields[26]), NULL},
  4215. {UPB_TABKEY_STR("optimize_for"), UPB_VALUE_INIT_CONSTPTR(&fields[48]), NULL},
  4216. {UPB_TABKEY_STR("py_generic_services"), UPB_VALUE_INIT_CONSTPTR(&fields[62]), NULL},
  4217. {UPB_TABKEY_STR("java_outer_classname"), UPB_VALUE_INIT_CONSTPTR(&fields[25]), NULL},
  4218. {UPB_TABKEY_STR("message_set_wire_format"), UPB_VALUE_INIT_CONSTPTR(&fields[31]), &strentries[106]},
  4219. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4220. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[76]), NULL},
  4221. {UPB_TABKEY_STR("no_standard_descriptor_accessor"), UPB_VALUE_INIT_CONSTPTR(&fields[45]), NULL},
  4222. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4223. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4224. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4225. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[39]), NULL},
  4226. {UPB_TABKEY_STR("input_type"), UPB_VALUE_INIT_CONSTPTR(&fields[20]), NULL},
  4227. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4228. {UPB_TABKEY_STR("output_type"), UPB_VALUE_INIT_CONSTPTR(&fields[56]), NULL},
  4229. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[55]), NULL},
  4230. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[74]), NULL},
  4231. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4232. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4233. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4234. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4235. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[54]), &strentries[122]},
  4236. {UPB_TABKEY_STR("method"), UPB_VALUE_INIT_CONSTPTR(&fields[33]), NULL},
  4237. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[35]), &strentries[121]},
  4238. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[72]), NULL},
  4239. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4240. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, 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_STR("location"), UPB_VALUE_INIT_CONSTPTR(&fields[30]), NULL},
  4245. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4246. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4247. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4248. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4249. {UPB_TABKEY_STR("span"), UPB_VALUE_INIT_CONSTPTR(&fields[65]), &strentries[139]},
  4250. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4251. {UPB_TABKEY_STR("trailing_comments"), UPB_VALUE_INIT_CONSTPTR(&fields[68]), NULL},
  4252. {UPB_TABKEY_STR("leading_comments"), UPB_VALUE_INIT_CONSTPTR(&fields[29]), &strentries[137]},
  4253. {UPB_TABKEY_STR("path"), UPB_VALUE_INIT_CONSTPTR(&fields[59]), NULL},
  4254. {UPB_TABKEY_STR("double_value"), UPB_VALUE_INIT_CONSTPTR(&fields[7]), NULL},
  4255. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4256. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4257. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[36]), 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("negative_int_value"), UPB_VALUE_INIT_CONSTPTR(&fields[43]), NULL},
  4262. {UPB_TABKEY_STR("aggregate_value"), UPB_VALUE_INIT_CONSTPTR(&fields[0]), NULL},
  4263. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4264. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4265. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4266. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4267. {UPB_TABKEY_STR("positive_int_value"), UPB_VALUE_INIT_CONSTPTR(&fields[60]), NULL},
  4268. {UPB_TABKEY_STR("identifier_value"), UPB_VALUE_INIT_CONSTPTR(&fields[19]), NULL},
  4269. {UPB_TABKEY_STR("string_value"), UPB_VALUE_INIT_CONSTPTR(&fields[67]), &strentries[154]},
  4270. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4271. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4272. {UPB_TABKEY_STR("is_extension"), UPB_VALUE_INIT_CONSTPTR(&fields[21]), NULL},
  4273. {UPB_TABKEY_STR("name_part"), UPB_VALUE_INIT_CONSTPTR(&fields[42]), NULL},
  4274. {UPB_TABKEY_STR("LABEL_REQUIRED"), UPB_VALUE_INIT_INT32(2), &strentries[162]},
  4275. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4276. {UPB_TABKEY_STR("LABEL_REPEATED"), UPB_VALUE_INIT_INT32(3), NULL},
  4277. {UPB_TABKEY_STR("LABEL_OPTIONAL"), UPB_VALUE_INIT_INT32(1), NULL},
  4278. {UPB_TABKEY_STR("TYPE_FIXED64"), UPB_VALUE_INIT_INT32(6), NULL},
  4279. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4280. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4281. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4282. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4283. {UPB_TABKEY_STR("TYPE_STRING"), UPB_VALUE_INIT_INT32(9), NULL},
  4284. {UPB_TABKEY_STR("TYPE_FLOAT"), UPB_VALUE_INIT_INT32(2), &strentries[193]},
  4285. {UPB_TABKEY_STR("TYPE_DOUBLE"), UPB_VALUE_INIT_INT32(1), NULL},
  4286. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4287. {UPB_TABKEY_STR("TYPE_INT32"), UPB_VALUE_INIT_INT32(5), NULL},
  4288. {UPB_TABKEY_STR("TYPE_SFIXED32"), UPB_VALUE_INIT_INT32(15), NULL},
  4289. {UPB_TABKEY_STR("TYPE_FIXED32"), UPB_VALUE_INIT_INT32(7), NULL},
  4290. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4291. {UPB_TABKEY_STR("TYPE_MESSAGE"), UPB_VALUE_INIT_INT32(11), &strentries[194]},
  4292. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4293. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4294. {UPB_TABKEY_STR("TYPE_INT64"), UPB_VALUE_INIT_INT32(3), &strentries[191]},
  4295. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4296. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4297. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4298. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4299. {UPB_TABKEY_STR("TYPE_ENUM"), UPB_VALUE_INIT_INT32(14), NULL},
  4300. {UPB_TABKEY_STR("TYPE_UINT32"), UPB_VALUE_INIT_INT32(13), NULL},
  4301. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4302. {UPB_TABKEY_STR("TYPE_UINT64"), UPB_VALUE_INIT_INT32(4), &strentries[190]},
  4303. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4304. {UPB_TABKEY_STR("TYPE_SFIXED64"), UPB_VALUE_INIT_INT32(16), NULL},
  4305. {UPB_TABKEY_STR("TYPE_BYTES"), UPB_VALUE_INIT_INT32(12), NULL},
  4306. {UPB_TABKEY_STR("TYPE_SINT64"), UPB_VALUE_INIT_INT32(18), NULL},
  4307. {UPB_TABKEY_STR("TYPE_BOOL"), UPB_VALUE_INIT_INT32(8), NULL},
  4308. {UPB_TABKEY_STR("TYPE_GROUP"), UPB_VALUE_INIT_INT32(10), NULL},
  4309. {UPB_TABKEY_STR("TYPE_SINT32"), UPB_VALUE_INIT_INT32(17), NULL},
  4310. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4311. {UPB_TABKEY_STR("CORD"), UPB_VALUE_INIT_INT32(1), NULL},
  4312. {UPB_TABKEY_STR("STRING"), UPB_VALUE_INIT_INT32(0), &strentries[197]},
  4313. {UPB_TABKEY_STR("STRING_PIECE"), UPB_VALUE_INIT_INT32(2), NULL},
  4314. {UPB_TABKEY_STR("CODE_SIZE"), UPB_VALUE_INIT_INT32(2), NULL},
  4315. {UPB_TABKEY_STR("SPEED"), UPB_VALUE_INIT_INT32(1), &strentries[203]},
  4316. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4317. {UPB_TABKEY_STR("LITE_RUNTIME"), UPB_VALUE_INIT_INT32(3), NULL},
  4318. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4319. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4320. {UPB_TABKEY_STR("google.protobuf.SourceCodeInfo.Location"), UPB_VALUE_INIT_CONSTPTR(&msgs[17]), NULL},
  4321. {UPB_TABKEY_STR("google.protobuf.UninterpretedOption"), UPB_VALUE_INIT_CONSTPTR(&msgs[18]), NULL},
  4322. {UPB_TABKEY_STR("google.protobuf.FileDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[8]), NULL},
  4323. {UPB_TABKEY_STR("google.protobuf.MethodDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[12]), NULL},
  4324. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4325. {UPB_TABKEY_STR("google.protobuf.EnumValueOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[5]), NULL},
  4326. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4327. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4328. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4329. {UPB_TABKEY_STR("google.protobuf.DescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[0]), &strentries[228]},
  4330. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4331. {UPB_TABKEY_STR("google.protobuf.SourceCodeInfo"), UPB_VALUE_INIT_CONSTPTR(&msgs[16]), NULL},
  4332. {UPB_TABKEY_STR("google.protobuf.FieldDescriptorProto.Type"), UPB_VALUE_INIT_CONSTPTR(&enums[1]), NULL},
  4333. {UPB_TABKEY_STR("google.protobuf.DescriptorProto.ExtensionRange"), UPB_VALUE_INIT_CONSTPTR(&msgs[1]), NULL},
  4334. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4335. {UPB_TABKEY_STR("google.protobuf.EnumValueDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[4]), NULL},
  4336. {UPB_TABKEY_STR("google.protobuf.FieldOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[7]), NULL},
  4337. {UPB_TABKEY_STR("google.protobuf.FileOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[10]), NULL},
  4338. {UPB_TABKEY_STR("google.protobuf.EnumDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[2]), &strentries[233]},
  4339. {UPB_TABKEY_STR("google.protobuf.FieldDescriptorProto.Label"), UPB_VALUE_INIT_CONSTPTR(&enums[0]), NULL},
  4340. {UPB_TABKEY_STR("google.protobuf.ServiceDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[14]), NULL},
  4341. {UPB_TABKEY_STR("google.protobuf.FieldOptions.CType"), UPB_VALUE_INIT_CONSTPTR(&enums[2]), &strentries[229]},
  4342. {UPB_TABKEY_STR("google.protobuf.FileDescriptorSet"), UPB_VALUE_INIT_CONSTPTR(&msgs[9]), &strentries[235]},
  4343. {UPB_TABKEY_STR("google.protobuf.EnumOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[3]), NULL},
  4344. {UPB_TABKEY_STR("google.protobuf.FieldDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[6]), NULL},
  4345. {UPB_TABKEY_STR("google.protobuf.FileOptions.OptimizeMode"), UPB_VALUE_INIT_CONSTPTR(&enums[3]), &strentries[221]},
  4346. {UPB_TABKEY_STR("google.protobuf.ServiceOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[15]), NULL},
  4347. {UPB_TABKEY_STR("google.protobuf.MessageOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[11]), NULL},
  4348. {UPB_TABKEY_STR("google.protobuf.MethodOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[13]), &strentries[226]},
  4349. {UPB_TABKEY_STR("google.protobuf.UninterpretedOption.NamePart"), UPB_VALUE_INIT_CONSTPTR(&msgs[19]), NULL},
  4350. };
  4351. static const upb_tabent intentries[14] = {
  4352. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4353. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[73]), NULL},
  4354. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4355. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[71]), NULL},
  4356. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4357. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[77]), NULL},
  4358. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4359. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[75]), NULL},
  4360. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4361. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[76]), NULL},
  4362. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4363. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[74]), NULL},
  4364. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4365. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[72]), NULL},
  4366. };
  4367. static const _upb_value arrays[232] = {
  4368. UPB_ARRAY_EMPTYENT,
  4369. UPB_VALUE_INIT_CONSTPTR(&fields[38]),
  4370. UPB_VALUE_INIT_CONSTPTR(&fields[16]),
  4371. UPB_VALUE_INIT_CONSTPTR(&fields[44]),
  4372. UPB_VALUE_INIT_CONSTPTR(&fields[9]),
  4373. UPB_VALUE_INIT_CONSTPTR(&fields[15]),
  4374. UPB_VALUE_INIT_CONSTPTR(&fields[14]),
  4375. UPB_VALUE_INIT_CONSTPTR(&fields[49]),
  4376. UPB_ARRAY_EMPTYENT,
  4377. UPB_VALUE_INIT_CONSTPTR(&fields[66]),
  4378. UPB_VALUE_INIT_CONSTPTR(&fields[8]),
  4379. UPB_ARRAY_EMPTYENT,
  4380. UPB_VALUE_INIT_CONSTPTR(&fields[40]),
  4381. UPB_VALUE_INIT_CONSTPTR(&fields[78]),
  4382. UPB_VALUE_INIT_CONSTPTR(&fields[50]),
  4383. UPB_ARRAY_EMPTYENT,
  4384. UPB_ARRAY_EMPTYENT,
  4385. UPB_VALUE_INIT_CONSTPTR(&fields[1]),
  4386. UPB_ARRAY_EMPTYENT,
  4387. UPB_ARRAY_EMPTYENT,
  4388. UPB_ARRAY_EMPTYENT,
  4389. UPB_ARRAY_EMPTYENT,
  4390. UPB_ARRAY_EMPTYENT,
  4391. UPB_ARRAY_EMPTYENT,
  4392. UPB_VALUE_INIT_CONSTPTR(&fields[37]),
  4393. UPB_VALUE_INIT_CONSTPTR(&fields[47]),
  4394. UPB_VALUE_INIT_CONSTPTR(&fields[52]),
  4395. UPB_ARRAY_EMPTYENT,
  4396. UPB_ARRAY_EMPTYENT,
  4397. UPB_ARRAY_EMPTYENT,
  4398. UPB_ARRAY_EMPTYENT,
  4399. UPB_ARRAY_EMPTYENT,
  4400. UPB_VALUE_INIT_CONSTPTR(&fields[41]),
  4401. UPB_VALUE_INIT_CONSTPTR(&fields[12]),
  4402. UPB_VALUE_INIT_CONSTPTR(&fields[46]),
  4403. UPB_VALUE_INIT_CONSTPTR(&fields[27]),
  4404. UPB_VALUE_INIT_CONSTPTR(&fields[69]),
  4405. UPB_VALUE_INIT_CONSTPTR(&fields[70]),
  4406. UPB_VALUE_INIT_CONSTPTR(&fields[4]),
  4407. UPB_VALUE_INIT_CONSTPTR(&fields[51]),
  4408. UPB_ARRAY_EMPTYENT,
  4409. UPB_VALUE_INIT_CONSTPTR(&fields[3]),
  4410. UPB_VALUE_INIT_CONSTPTR(&fields[58]),
  4411. UPB_VALUE_INIT_CONSTPTR(&fields[6]),
  4412. UPB_ARRAY_EMPTYENT,
  4413. UPB_VALUE_INIT_CONSTPTR(&fields[28]),
  4414. UPB_ARRAY_EMPTYENT,
  4415. UPB_ARRAY_EMPTYENT,
  4416. UPB_ARRAY_EMPTYENT,
  4417. UPB_VALUE_INIT_CONSTPTR(&fields[11]),
  4418. UPB_VALUE_INIT_CONSTPTR(&fields[79]),
  4419. UPB_ARRAY_EMPTYENT,
  4420. UPB_ARRAY_EMPTYENT,
  4421. UPB_ARRAY_EMPTYENT,
  4422. UPB_ARRAY_EMPTYENT,
  4423. UPB_ARRAY_EMPTYENT,
  4424. UPB_ARRAY_EMPTYENT,
  4425. UPB_ARRAY_EMPTYENT,
  4426. UPB_ARRAY_EMPTYENT,
  4427. UPB_ARRAY_EMPTYENT,
  4428. UPB_ARRAY_EMPTYENT,
  4429. UPB_ARRAY_EMPTYENT,
  4430. UPB_ARRAY_EMPTYENT,
  4431. UPB_ARRAY_EMPTYENT,
  4432. UPB_ARRAY_EMPTYENT,
  4433. UPB_ARRAY_EMPTYENT,
  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_ARRAY_EMPTYENT,
  4441. UPB_VALUE_INIT_CONSTPTR(&fields[34]),
  4442. UPB_VALUE_INIT_CONSTPTR(&fields[57]),
  4443. UPB_VALUE_INIT_CONSTPTR(&fields[5]),
  4444. UPB_VALUE_INIT_CONSTPTR(&fields[32]),
  4445. UPB_VALUE_INIT_CONSTPTR(&fields[10]),
  4446. UPB_VALUE_INIT_CONSTPTR(&fields[63]),
  4447. UPB_VALUE_INIT_CONSTPTR(&fields[13]),
  4448. UPB_VALUE_INIT_CONSTPTR(&fields[53]),
  4449. UPB_VALUE_INIT_CONSTPTR(&fields[64]),
  4450. UPB_VALUE_INIT_CONSTPTR(&fields[61]),
  4451. UPB_VALUE_INIT_CONSTPTR(&fields[80]),
  4452. UPB_ARRAY_EMPTYENT,
  4453. UPB_VALUE_INIT_CONSTPTR(&fields[17]),
  4454. UPB_ARRAY_EMPTYENT,
  4455. UPB_VALUE_INIT_CONSTPTR(&fields[26]),
  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_VALUE_INIT_CONSTPTR(&fields[25]),
  4463. UPB_VALUE_INIT_CONSTPTR(&fields[48]),
  4464. UPB_VALUE_INIT_CONSTPTR(&fields[24]),
  4465. UPB_VALUE_INIT_CONSTPTR(&fields[18]),
  4466. UPB_ARRAY_EMPTYENT,
  4467. UPB_ARRAY_EMPTYENT,
  4468. UPB_ARRAY_EMPTYENT,
  4469. UPB_ARRAY_EMPTYENT,
  4470. UPB_VALUE_INIT_CONSTPTR(&fields[2]),
  4471. UPB_VALUE_INIT_CONSTPTR(&fields[23]),
  4472. UPB_VALUE_INIT_CONSTPTR(&fields[62]),
  4473. UPB_ARRAY_EMPTYENT,
  4474. UPB_VALUE_INIT_CONSTPTR(&fields[22]),
  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_ARRAY_EMPTYENT,
  4498. UPB_ARRAY_EMPTYENT,
  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_ARRAY_EMPTYENT,
  4514. UPB_ARRAY_EMPTYENT,
  4515. UPB_ARRAY_EMPTYENT,
  4516. UPB_ARRAY_EMPTYENT,
  4517. UPB_ARRAY_EMPTYENT,
  4518. UPB_ARRAY_EMPTYENT,
  4519. UPB_VALUE_INIT_CONSTPTR(&fields[31]),
  4520. UPB_VALUE_INIT_CONSTPTR(&fields[45]),
  4521. UPB_ARRAY_EMPTYENT,
  4522. UPB_ARRAY_EMPTYENT,
  4523. UPB_ARRAY_EMPTYENT,
  4524. UPB_ARRAY_EMPTYENT,
  4525. UPB_ARRAY_EMPTYENT,
  4526. UPB_ARRAY_EMPTYENT,
  4527. UPB_ARRAY_EMPTYENT,
  4528. UPB_ARRAY_EMPTYENT,
  4529. UPB_ARRAY_EMPTYENT,
  4530. UPB_ARRAY_EMPTYENT,
  4531. UPB_ARRAY_EMPTYENT,
  4532. UPB_ARRAY_EMPTYENT,
  4533. UPB_ARRAY_EMPTYENT,
  4534. UPB_ARRAY_EMPTYENT,
  4535. UPB_VALUE_INIT_CONSTPTR(&fields[39]),
  4536. UPB_VALUE_INIT_CONSTPTR(&fields[20]),
  4537. UPB_VALUE_INIT_CONSTPTR(&fields[56]),
  4538. UPB_VALUE_INIT_CONSTPTR(&fields[55]),
  4539. UPB_ARRAY_EMPTYENT,
  4540. UPB_ARRAY_EMPTYENT,
  4541. UPB_ARRAY_EMPTYENT,
  4542. UPB_ARRAY_EMPTYENT,
  4543. UPB_ARRAY_EMPTYENT,
  4544. UPB_VALUE_INIT_CONSTPTR(&fields[35]),
  4545. UPB_VALUE_INIT_CONSTPTR(&fields[33]),
  4546. UPB_VALUE_INIT_CONSTPTR(&fields[54]),
  4547. UPB_ARRAY_EMPTYENT,
  4548. UPB_ARRAY_EMPTYENT,
  4549. UPB_ARRAY_EMPTYENT,
  4550. UPB_ARRAY_EMPTYENT,
  4551. UPB_ARRAY_EMPTYENT,
  4552. UPB_VALUE_INIT_CONSTPTR(&fields[30]),
  4553. UPB_ARRAY_EMPTYENT,
  4554. UPB_VALUE_INIT_CONSTPTR(&fields[59]),
  4555. UPB_VALUE_INIT_CONSTPTR(&fields[65]),
  4556. UPB_VALUE_INIT_CONSTPTR(&fields[29]),
  4557. UPB_VALUE_INIT_CONSTPTR(&fields[68]),
  4558. UPB_ARRAY_EMPTYENT,
  4559. UPB_ARRAY_EMPTYENT,
  4560. UPB_VALUE_INIT_CONSTPTR(&fields[36]),
  4561. UPB_VALUE_INIT_CONSTPTR(&fields[19]),
  4562. UPB_VALUE_INIT_CONSTPTR(&fields[60]),
  4563. UPB_VALUE_INIT_CONSTPTR(&fields[43]),
  4564. UPB_VALUE_INIT_CONSTPTR(&fields[7]),
  4565. UPB_VALUE_INIT_CONSTPTR(&fields[67]),
  4566. UPB_VALUE_INIT_CONSTPTR(&fields[0]),
  4567. UPB_ARRAY_EMPTYENT,
  4568. UPB_VALUE_INIT_CONSTPTR(&fields[42]),
  4569. UPB_VALUE_INIT_CONSTPTR(&fields[21]),
  4570. UPB_ARRAY_EMPTYENT,
  4571. UPB_VALUE_INIT_CONSTPTR("LABEL_OPTIONAL"),
  4572. UPB_VALUE_INIT_CONSTPTR("LABEL_REQUIRED"),
  4573. UPB_VALUE_INIT_CONSTPTR("LABEL_REPEATED"),
  4574. UPB_ARRAY_EMPTYENT,
  4575. UPB_VALUE_INIT_CONSTPTR("TYPE_DOUBLE"),
  4576. UPB_VALUE_INIT_CONSTPTR("TYPE_FLOAT"),
  4577. UPB_VALUE_INIT_CONSTPTR("TYPE_INT64"),
  4578. UPB_VALUE_INIT_CONSTPTR("TYPE_UINT64"),
  4579. UPB_VALUE_INIT_CONSTPTR("TYPE_INT32"),
  4580. UPB_VALUE_INIT_CONSTPTR("TYPE_FIXED64"),
  4581. UPB_VALUE_INIT_CONSTPTR("TYPE_FIXED32"),
  4582. UPB_VALUE_INIT_CONSTPTR("TYPE_BOOL"),
  4583. UPB_VALUE_INIT_CONSTPTR("TYPE_STRING"),
  4584. UPB_VALUE_INIT_CONSTPTR("TYPE_GROUP"),
  4585. UPB_VALUE_INIT_CONSTPTR("TYPE_MESSAGE"),
  4586. UPB_VALUE_INIT_CONSTPTR("TYPE_BYTES"),
  4587. UPB_VALUE_INIT_CONSTPTR("TYPE_UINT32"),
  4588. UPB_VALUE_INIT_CONSTPTR("TYPE_ENUM"),
  4589. UPB_VALUE_INIT_CONSTPTR("TYPE_SFIXED32"),
  4590. UPB_VALUE_INIT_CONSTPTR("TYPE_SFIXED64"),
  4591. UPB_VALUE_INIT_CONSTPTR("TYPE_SINT32"),
  4592. UPB_VALUE_INIT_CONSTPTR("TYPE_SINT64"),
  4593. UPB_VALUE_INIT_CONSTPTR("STRING"),
  4594. UPB_VALUE_INIT_CONSTPTR("CORD"),
  4595. UPB_VALUE_INIT_CONSTPTR("STRING_PIECE"),
  4596. UPB_ARRAY_EMPTYENT,
  4597. UPB_VALUE_INIT_CONSTPTR("SPEED"),
  4598. UPB_VALUE_INIT_CONSTPTR("CODE_SIZE"),
  4599. UPB_VALUE_INIT_CONSTPTR("LITE_RUNTIME"),
  4600. };
  4601. static const upb_symtab symtab = UPB_SYMTAB_INIT(UPB_STRTABLE_INIT(24, 31, UPB_CTYPE_PTR, 5, &strentries[204]), &reftables[210], &reftables[211]);
  4602. const upb_symtab *upbdefs_google_protobuf_descriptor(const void *owner) {
  4603. upb_symtab_ref(&symtab, owner);
  4604. return &symtab;
  4605. }
  4606. #ifdef UPB_DEBUG_REFS
  4607. static upb_inttable reftables[212] = {
  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. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4799. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4800. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4801. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4802. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4803. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4804. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4805. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4806. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4807. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4808. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4809. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4810. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4811. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4812. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4813. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4814. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4815. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4816. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4817. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4818. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4819. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4820. };
  4821. #endif
  4822. /*
  4823. * upb - a minimalist implementation of protocol buffers.
  4824. *
  4825. * Copyright (c) 2008-2009 Google Inc. See LICENSE for details.
  4826. * Author: Josh Haberman <jhaberman@gmail.com>
  4827. *
  4828. * XXX: The routines in this file that consume a string do not currently
  4829. * support having the string span buffers. In the future, as upb_sink and
  4830. * its buffering/sharing functionality evolve there should be an easy and
  4831. * idiomatic way of correctly handling this case. For now, we accept this
  4832. * limitation since we currently only parse descriptors from single strings.
  4833. */
  4834. #include <errno.h>
  4835. #include <stdlib.h>
  4836. #include <string.h>
  4837. static char *upb_strndup(const char *buf, size_t n) {
  4838. char *ret = malloc(n + 1);
  4839. if (!ret) return NULL;
  4840. memcpy(ret, buf, n);
  4841. ret[n] = '\0';
  4842. return ret;
  4843. }
  4844. // Returns a newly allocated string that joins input strings together, for
  4845. // example:
  4846. // join("Foo.Bar", "Baz") -> "Foo.Bar.Baz"
  4847. // join("", "Baz") -> "Baz"
  4848. // Caller owns a ref on the returned string.
  4849. static char *upb_join(const char *base, const char *name) {
  4850. if (!base || strlen(base) == 0) {
  4851. return upb_strdup(name);
  4852. } else {
  4853. char *ret = malloc(strlen(base) + strlen(name) + 2);
  4854. ret[0] = '\0';
  4855. strcat(ret, base);
  4856. strcat(ret, ".");
  4857. strcat(ret, name);
  4858. return ret;
  4859. }
  4860. }
  4861. /* upb_deflist ****************************************************************/
  4862. void upb_deflist_init(upb_deflist *l) {
  4863. l->size = 0;
  4864. l->defs = NULL;
  4865. l->len = 0;
  4866. l->owned = true;
  4867. }
  4868. void upb_deflist_uninit(upb_deflist *l) {
  4869. if (l->owned)
  4870. for(size_t i = 0; i < l->len; i++)
  4871. upb_def_unref(l->defs[i], l);
  4872. free(l->defs);
  4873. }
  4874. bool upb_deflist_push(upb_deflist *l, upb_def *d) {
  4875. if(++l->len >= l->size) {
  4876. size_t new_size = UPB_MAX(l->size, 4);
  4877. new_size *= 2;
  4878. l->defs = realloc(l->defs, new_size * sizeof(void *));
  4879. if (!l->defs) return false;
  4880. l->size = new_size;
  4881. }
  4882. l->defs[l->len - 1] = d;
  4883. return true;
  4884. }
  4885. void upb_deflist_donaterefs(upb_deflist *l, void *owner) {
  4886. assert(l->owned);
  4887. for (size_t i = 0; i < l->len; i++)
  4888. upb_def_donateref(l->defs[i], l, owner);
  4889. l->owned = false;
  4890. }
  4891. static upb_def *upb_deflist_last(upb_deflist *l) {
  4892. return l->defs[l->len-1];
  4893. }
  4894. // Qualify the defname for all defs starting with offset "start" with "str".
  4895. static void upb_deflist_qualify(upb_deflist *l, char *str, int32_t start) {
  4896. for (uint32_t i = start; i < l->len; i++) {
  4897. upb_def *def = l->defs[i];
  4898. char *name = upb_join(str, upb_def_fullname(def));
  4899. upb_def_setfullname(def, name, NULL);
  4900. free(name);
  4901. }
  4902. }
  4903. /* upb_descreader ************************************************************/
  4904. void upb_descreader_init(upb_descreader *r, const upb_handlers *handlers,
  4905. upb_status *status) {
  4906. UPB_UNUSED(status);
  4907. upb_deflist_init(&r->defs);
  4908. upb_sink_reset(upb_descreader_input(r), handlers, r);
  4909. r->stack_len = 0;
  4910. r->name = NULL;
  4911. r->default_string = NULL;
  4912. }
  4913. void upb_descreader_uninit(upb_descreader *r) {
  4914. free(r->name);
  4915. upb_deflist_uninit(&r->defs);
  4916. free(r->default_string);
  4917. while (r->stack_len > 0) {
  4918. upb_descreader_frame *f = &r->stack[--r->stack_len];
  4919. free(f->name);
  4920. }
  4921. }
  4922. upb_def **upb_descreader_getdefs(upb_descreader *r, void *owner, int *n) {
  4923. *n = r->defs.len;
  4924. upb_deflist_donaterefs(&r->defs, owner);
  4925. return r->defs.defs;
  4926. }
  4927. upb_sink *upb_descreader_input(upb_descreader *r) {
  4928. return &r->sink;
  4929. }
  4930. static upb_msgdef *upb_descreader_top(upb_descreader *r) {
  4931. assert(r->stack_len > 1);
  4932. int index = r->stack[r->stack_len-1].start - 1;
  4933. assert(index >= 0);
  4934. return upb_downcast_msgdef_mutable(r->defs.defs[index]);
  4935. }
  4936. static upb_def *upb_descreader_last(upb_descreader *r) {
  4937. return upb_deflist_last(&r->defs);
  4938. }
  4939. // Start/end handlers for FileDescriptorProto and DescriptorProto (the two
  4940. // entities that have names and can contain sub-definitions.
  4941. void upb_descreader_startcontainer(upb_descreader *r) {
  4942. upb_descreader_frame *f = &r->stack[r->stack_len++];
  4943. f->start = r->defs.len;
  4944. f->name = NULL;
  4945. }
  4946. void upb_descreader_endcontainer(upb_descreader *r) {
  4947. upb_descreader_frame *f = &r->stack[--r->stack_len];
  4948. upb_deflist_qualify(&r->defs, f->name, f->start);
  4949. free(f->name);
  4950. f->name = NULL;
  4951. }
  4952. void upb_descreader_setscopename(upb_descreader *r, char *str) {
  4953. upb_descreader_frame *f = &r->stack[r->stack_len-1];
  4954. free(f->name);
  4955. f->name = str;
  4956. }
  4957. // Handlers for google.protobuf.FileDescriptorProto.
  4958. static bool file_startmsg(void *r, const void *hd) {
  4959. UPB_UNUSED(hd);
  4960. upb_descreader_startcontainer(r);
  4961. return true;
  4962. }
  4963. static bool file_endmsg(void *closure, const void *hd, upb_status *status) {
  4964. UPB_UNUSED(hd);
  4965. UPB_UNUSED(status);
  4966. upb_descreader *r = closure;
  4967. upb_descreader_endcontainer(r);
  4968. return true;
  4969. }
  4970. static size_t file_onpackage(void *closure, const void *hd, const char *buf,
  4971. size_t n, const upb_bufhandle *handle) {
  4972. UPB_UNUSED(hd);
  4973. UPB_UNUSED(handle);
  4974. upb_descreader *r = closure;
  4975. // XXX: see comment at the top of the file.
  4976. upb_descreader_setscopename(r, upb_strndup(buf, n));
  4977. return n;
  4978. }
  4979. // Handlers for google.protobuf.EnumValueDescriptorProto.
  4980. static bool enumval_startmsg(void *closure, const void *hd) {
  4981. UPB_UNUSED(hd);
  4982. upb_descreader *r = closure;
  4983. r->saw_number = false;
  4984. r->saw_name = false;
  4985. return true;
  4986. }
  4987. static size_t enumval_onname(void *closure, const void *hd, const char *buf,
  4988. size_t n, const upb_bufhandle *handle) {
  4989. UPB_UNUSED(hd);
  4990. UPB_UNUSED(handle);
  4991. upb_descreader *r = closure;
  4992. // XXX: see comment at the top of the file.
  4993. free(r->name);
  4994. r->name = upb_strndup(buf, n);
  4995. r->saw_name = true;
  4996. return n;
  4997. }
  4998. static bool enumval_onnumber(void *closure, const void *hd, int32_t val) {
  4999. UPB_UNUSED(hd);
  5000. upb_descreader *r = closure;
  5001. r->number = val;
  5002. r->saw_number = true;
  5003. return true;
  5004. }
  5005. static bool enumval_endmsg(void *closure, const void *hd, upb_status *status) {
  5006. UPB_UNUSED(hd);
  5007. upb_descreader *r = closure;
  5008. if(!r->saw_number || !r->saw_name) {
  5009. upb_status_seterrmsg(status, "Enum value missing name or number.");
  5010. return false;
  5011. }
  5012. upb_enumdef *e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  5013. upb_enumdef_addval(e, r->name, r->number, status);
  5014. free(r->name);
  5015. r->name = NULL;
  5016. return true;
  5017. }
  5018. // Handlers for google.protobuf.EnumDescriptorProto.
  5019. static bool enum_startmsg(void *closure, const void *hd) {
  5020. UPB_UNUSED(hd);
  5021. upb_descreader *r = closure;
  5022. upb_deflist_push(&r->defs, UPB_UPCAST(upb_enumdef_new(&r->defs)));
  5023. return true;
  5024. }
  5025. static bool enum_endmsg(void *closure, const void *hd, upb_status *status) {
  5026. UPB_UNUSED(hd);
  5027. upb_descreader *r = closure;
  5028. upb_enumdef *e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  5029. if (upb_def_fullname(upb_descreader_last(r)) == NULL) {
  5030. upb_status_seterrmsg(status, "Enum had no name.");
  5031. return false;
  5032. }
  5033. if (upb_enumdef_numvals(e) == 0) {
  5034. upb_status_seterrmsg(status, "Enum had no values.");
  5035. return false;
  5036. }
  5037. return true;
  5038. }
  5039. static size_t enum_onname(void *closure, const void *hd, const char *buf,
  5040. size_t n, const upb_bufhandle *handle) {
  5041. UPB_UNUSED(hd);
  5042. UPB_UNUSED(handle);
  5043. upb_descreader *r = closure;
  5044. // XXX: see comment at the top of the file.
  5045. char *fullname = upb_strndup(buf, n);
  5046. upb_def_setfullname(upb_descreader_last(r), fullname, NULL);
  5047. free(fullname);
  5048. return n;
  5049. }
  5050. // Handlers for google.protobuf.FieldDescriptorProto
  5051. static bool field_startmsg(void *closure, const void *hd) {
  5052. UPB_UNUSED(hd);
  5053. upb_descreader *r = closure;
  5054. r->f = upb_fielddef_new(&r->defs);
  5055. free(r->default_string);
  5056. r->default_string = NULL;
  5057. // fielddefs default to packed, but descriptors default to non-packed.
  5058. upb_fielddef_setpacked(r->f, false);
  5059. return true;
  5060. }
  5061. // Converts the default value in string "str" into "d". Passes a ref on str.
  5062. // Returns true on success.
  5063. static bool parse_default(char *str, upb_fielddef *f) {
  5064. bool success = true;
  5065. char *end;
  5066. switch (upb_fielddef_type(f)) {
  5067. case UPB_TYPE_INT32: {
  5068. long val = strtol(str, &end, 0);
  5069. if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || *end)
  5070. success = false;
  5071. else
  5072. upb_fielddef_setdefaultint32(f, val);
  5073. break;
  5074. }
  5075. case UPB_TYPE_INT64: {
  5076. long long val = strtoll(str, &end, 0);
  5077. if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || *end)
  5078. success = false;
  5079. else
  5080. upb_fielddef_setdefaultint64(f, val);
  5081. break;
  5082. }
  5083. case UPB_TYPE_UINT32: {
  5084. long val = strtoul(str, &end, 0);
  5085. if (val > UINT32_MAX || errno == ERANGE || *end)
  5086. success = false;
  5087. else
  5088. upb_fielddef_setdefaultuint32(f, val);
  5089. break;
  5090. }
  5091. case UPB_TYPE_UINT64: {
  5092. unsigned long long val = strtoull(str, &end, 0);
  5093. if (val > UINT64_MAX || errno == ERANGE || *end)
  5094. success = false;
  5095. else
  5096. upb_fielddef_setdefaultuint64(f, val);
  5097. break;
  5098. }
  5099. case UPB_TYPE_DOUBLE: {
  5100. double val = strtod(str, &end);
  5101. if (errno == ERANGE || *end)
  5102. success = false;
  5103. else
  5104. upb_fielddef_setdefaultdouble(f, val);
  5105. break;
  5106. }
  5107. case UPB_TYPE_FLOAT: {
  5108. float val = strtof(str, &end);
  5109. if (errno == ERANGE || *end)
  5110. success = false;
  5111. else
  5112. upb_fielddef_setdefaultfloat(f, val);
  5113. break;
  5114. }
  5115. case UPB_TYPE_BOOL: {
  5116. if (strcmp(str, "false") == 0)
  5117. upb_fielddef_setdefaultbool(f, false);
  5118. else if (strcmp(str, "true") == 0)
  5119. upb_fielddef_setdefaultbool(f, true);
  5120. else
  5121. success = false;
  5122. break;
  5123. }
  5124. default: abort();
  5125. }
  5126. return success;
  5127. }
  5128. static bool field_endmsg(void *closure, const void *hd, upb_status *status) {
  5129. UPB_UNUSED(hd);
  5130. upb_descreader *r = closure;
  5131. upb_fielddef *f = r->f;
  5132. // TODO: verify that all required fields were present.
  5133. assert(upb_fielddef_number(f) != 0);
  5134. assert(upb_fielddef_name(f) != NULL);
  5135. assert((upb_fielddef_subdefname(f) != NULL) == upb_fielddef_hassubdef(f));
  5136. if (r->default_string) {
  5137. if (upb_fielddef_issubmsg(f)) {
  5138. upb_status_seterrmsg(status, "Submessages cannot have defaults.");
  5139. return false;
  5140. }
  5141. if (upb_fielddef_isstring(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  5142. upb_fielddef_setdefaultcstr(f, r->default_string, NULL);
  5143. } else {
  5144. if (r->default_string && !parse_default(r->default_string, f)) {
  5145. // We don't worry too much about giving a great error message since the
  5146. // compiler should have ensured this was correct.
  5147. upb_status_seterrmsg(status, "Error converting default value.");
  5148. return false;
  5149. }
  5150. }
  5151. }
  5152. return true;
  5153. }
  5154. static bool field_onlazy(void *closure, const void *hd, bool val) {
  5155. UPB_UNUSED(hd);
  5156. upb_descreader *r = closure;
  5157. upb_fielddef_setlazy(r->f, val);
  5158. return true;
  5159. }
  5160. static bool field_onpacked(void *closure, const void *hd, bool val) {
  5161. UPB_UNUSED(hd);
  5162. upb_descreader *r = closure;
  5163. upb_fielddef_setpacked(r->f, val);
  5164. return true;
  5165. }
  5166. static bool field_ontype(void *closure, const void *hd, int32_t val) {
  5167. UPB_UNUSED(hd);
  5168. upb_descreader *r = closure;
  5169. upb_fielddef_setdescriptortype(r->f, val);
  5170. return true;
  5171. }
  5172. static bool field_onlabel(void *closure, const void *hd, int32_t val) {
  5173. UPB_UNUSED(hd);
  5174. upb_descreader *r = closure;
  5175. upb_fielddef_setlabel(r->f, val);
  5176. return true;
  5177. }
  5178. static bool field_onnumber(void *closure, const void *hd, int32_t val) {
  5179. UPB_UNUSED(hd);
  5180. upb_descreader *r = closure;
  5181. bool ok = upb_fielddef_setnumber(r->f, val, NULL);
  5182. UPB_ASSERT_VAR(ok, ok);
  5183. return true;
  5184. }
  5185. static size_t field_onname(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_setname(r->f, name, NULL);
  5193. free(name);
  5194. return n;
  5195. }
  5196. static size_t field_ontypename(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. // XXX: see comment at the top of the file.
  5202. char *name = upb_strndup(buf, n);
  5203. upb_fielddef_setsubdefname(r->f, name, NULL);
  5204. free(name);
  5205. return n;
  5206. }
  5207. static size_t field_onextendee(void *closure, const void *hd, const char *buf,
  5208. size_t n, const upb_bufhandle *handle) {
  5209. UPB_UNUSED(hd);
  5210. UPB_UNUSED(handle);
  5211. upb_descreader *r = closure;
  5212. // XXX: see comment at the top of the file.
  5213. char *name = upb_strndup(buf, n);
  5214. upb_fielddef_setcontainingtypename(r->f, name, NULL);
  5215. free(name);
  5216. return n;
  5217. }
  5218. static size_t field_ondefaultval(void *closure, const void *hd, const char *buf,
  5219. size_t n, const upb_bufhandle *handle) {
  5220. UPB_UNUSED(hd);
  5221. UPB_UNUSED(handle);
  5222. upb_descreader *r = closure;
  5223. // Have to convert from string to the correct type, but we might not know the
  5224. // type yet, so we save it as a string until the end of the field.
  5225. // XXX: see comment at the top of the file.
  5226. free(r->default_string);
  5227. r->default_string = upb_strndup(buf, n);
  5228. return n;
  5229. }
  5230. // Handlers for google.protobuf.DescriptorProto (representing a message).
  5231. static bool msg_startmsg(void *closure, const void *hd) {
  5232. UPB_UNUSED(hd);
  5233. upb_descreader *r = closure;
  5234. upb_deflist_push(&r->defs, UPB_UPCAST(upb_msgdef_new(&r->defs)));
  5235. upb_descreader_startcontainer(r);
  5236. return true;
  5237. }
  5238. static bool msg_endmsg(void *closure, const void *hd, upb_status *status) {
  5239. UPB_UNUSED(hd);
  5240. upb_descreader *r = closure;
  5241. upb_msgdef *m = upb_descreader_top(r);
  5242. if(!upb_def_fullname(UPB_UPCAST(m))) {
  5243. upb_status_seterrmsg(status, "Encountered message with no name.");
  5244. return false;
  5245. }
  5246. upb_descreader_endcontainer(r);
  5247. return true;
  5248. }
  5249. static size_t msg_onname(void *closure, const void *hd, const char *buf,
  5250. size_t n, const upb_bufhandle *handle) {
  5251. UPB_UNUSED(hd);
  5252. UPB_UNUSED(handle);
  5253. upb_descreader *r = closure;
  5254. upb_msgdef *m = upb_descreader_top(r);
  5255. // XXX: see comment at the top of the file.
  5256. char *name = upb_strndup(buf, n);
  5257. upb_def_setfullname(UPB_UPCAST(m), name, NULL);
  5258. upb_descreader_setscopename(r, name); // Passes ownership of name.
  5259. return n;
  5260. }
  5261. static bool msg_onendfield(void *closure, const void *hd) {
  5262. UPB_UNUSED(hd);
  5263. upb_descreader *r = closure;
  5264. upb_msgdef *m = upb_descreader_top(r);
  5265. upb_msgdef_addfield(m, r->f, &r->defs, NULL);
  5266. r->f = NULL;
  5267. return true;
  5268. }
  5269. static bool pushextension(void *closure, const void *hd) {
  5270. UPB_UNUSED(hd);
  5271. upb_descreader *r = closure;
  5272. assert(upb_fielddef_containingtypename(r->f));
  5273. upb_fielddef_setisextension(r->f, true);
  5274. upb_deflist_push(&r->defs, UPB_UPCAST(r->f));
  5275. r->f = NULL;
  5276. return true;
  5277. }
  5278. #define D(name) upbdefs_google_protobuf_ ## name(s)
  5279. static void reghandlers(const void *closure, upb_handlers *h) {
  5280. const upb_symtab *s = closure;
  5281. const upb_msgdef *m = upb_handlers_msgdef(h);
  5282. if (m == D(DescriptorProto)) {
  5283. upb_handlers_setstartmsg(h, &msg_startmsg, NULL);
  5284. upb_handlers_setendmsg(h, &msg_endmsg, NULL);
  5285. upb_handlers_setstring(h, D(DescriptorProto_name), &msg_onname, NULL);
  5286. upb_handlers_setendsubmsg(h, D(DescriptorProto_field), &msg_onendfield,
  5287. NULL);
  5288. upb_handlers_setendsubmsg(h, D(DescriptorProto_extension), &pushextension,
  5289. NULL);
  5290. } else if (m == D(FileDescriptorProto)) {
  5291. upb_handlers_setstartmsg(h, &file_startmsg, NULL);
  5292. upb_handlers_setendmsg(h, &file_endmsg, NULL);
  5293. upb_handlers_setstring(h, D(FileDescriptorProto_package), &file_onpackage,
  5294. NULL);
  5295. upb_handlers_setendsubmsg(h, D(FileDescriptorProto_extension), &pushextension,
  5296. NULL);
  5297. } else if (m == D(EnumValueDescriptorProto)) {
  5298. upb_handlers_setstartmsg(h, &enumval_startmsg, NULL);
  5299. upb_handlers_setendmsg(h, &enumval_endmsg, NULL);
  5300. upb_handlers_setstring(h, D(EnumValueDescriptorProto_name), &enumval_onname, NULL);
  5301. upb_handlers_setint32(h, D(EnumValueDescriptorProto_number), &enumval_onnumber,
  5302. NULL);
  5303. } else if (m == D(EnumDescriptorProto)) {
  5304. upb_handlers_setstartmsg(h, &enum_startmsg, NULL);
  5305. upb_handlers_setendmsg(h, &enum_endmsg, NULL);
  5306. upb_handlers_setstring(h, D(EnumDescriptorProto_name), &enum_onname, NULL);
  5307. } else if (m == D(FieldDescriptorProto)) {
  5308. upb_handlers_setstartmsg(h, &field_startmsg, NULL);
  5309. upb_handlers_setendmsg(h, &field_endmsg, NULL);
  5310. upb_handlers_setint32(h, D(FieldDescriptorProto_type), &field_ontype,
  5311. NULL);
  5312. upb_handlers_setint32(h, D(FieldDescriptorProto_label), &field_onlabel,
  5313. NULL);
  5314. upb_handlers_setint32(h, D(FieldDescriptorProto_number), &field_onnumber,
  5315. NULL);
  5316. upb_handlers_setstring(h, D(FieldDescriptorProto_name), &field_onname,
  5317. NULL);
  5318. upb_handlers_setstring(h, D(FieldDescriptorProto_type_name),
  5319. &field_ontypename, NULL);
  5320. upb_handlers_setstring(h, D(FieldDescriptorProto_extendee),
  5321. &field_onextendee, NULL);
  5322. upb_handlers_setstring(h, D(FieldDescriptorProto_default_value),
  5323. &field_ondefaultval, NULL);
  5324. } else if (m == D(FieldOptions)) {
  5325. upb_handlers_setbool(h, D(FieldOptions_lazy), &field_onlazy, NULL);
  5326. upb_handlers_setbool(h, D(FieldOptions_packed), &field_onpacked, NULL);
  5327. }
  5328. }
  5329. #undef D
  5330. const upb_handlers *upb_descreader_newhandlers(const void *owner) {
  5331. const upb_symtab *s = upbdefs_google_protobuf_descriptor(&s);
  5332. const upb_handlers *h = upb_handlers_newfrozen(
  5333. upbdefs_google_protobuf_FileDescriptorSet(s), owner, reghandlers, s);
  5334. upb_symtab_unref(s, &s);
  5335. return h;
  5336. }
  5337. /*
  5338. * upb - a minimalist implementation of protocol buffers.
  5339. *
  5340. * Copyright (c) 2013 Google Inc. See LICENSE for details.
  5341. * Author: Josh Haberman <jhaberman@gmail.com>
  5342. *
  5343. * Code to compile a upb::Handlers into bytecode for decoding a protobuf
  5344. * according to that specific schema and destination handlers.
  5345. *
  5346. * Compiling to bytecode is always the first step. If we are using the
  5347. * interpreted decoder we leave it as bytecode and interpret that. If we are
  5348. * using a JIT decoder we use a code generator to turn the bytecode into native
  5349. * code, LLVM IR, etc.
  5350. *
  5351. * Bytecode definition is in decoder.int.h.
  5352. */
  5353. #include <stdarg.h>
  5354. #ifdef UPB_DUMP_BYTECODE
  5355. #include <stdio.h>
  5356. #endif
  5357. #define MAXLABEL 5
  5358. #define EMPTYLABEL -1
  5359. /* mgroup *********************************************************************/
  5360. static void freegroup(upb_refcounted *r) {
  5361. mgroup *g = (mgroup*)r;
  5362. upb_inttable_uninit(&g->methods);
  5363. #ifdef UPB_USE_JIT_X64
  5364. upb_pbdecoder_freejit(g);
  5365. #endif
  5366. free(g->bytecode);
  5367. free(g);
  5368. }
  5369. static void visitgroup(const upb_refcounted *r, upb_refcounted_visit *visit,
  5370. void *closure) {
  5371. const mgroup *g = (const mgroup*)r;
  5372. upb_inttable_iter i;
  5373. upb_inttable_begin(&i, &g->methods);
  5374. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5375. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  5376. visit(r, UPB_UPCAST(method), closure);
  5377. }
  5378. }
  5379. mgroup *newgroup(const void *owner) {
  5380. mgroup *g = malloc(sizeof(*g));
  5381. static const struct upb_refcounted_vtbl vtbl = {visitgroup, freegroup};
  5382. upb_refcounted_init(UPB_UPCAST(g), &vtbl, owner);
  5383. upb_inttable_init(&g->methods, UPB_CTYPE_PTR);
  5384. g->bytecode = NULL;
  5385. g->bytecode_end = NULL;
  5386. return g;
  5387. }
  5388. /* upb_pbdecodermethod ********************************************************/
  5389. static void freemethod(upb_refcounted *r) {
  5390. upb_pbdecodermethod *method = (upb_pbdecodermethod*)r;
  5391. upb_byteshandler_uninit(&method->input_handler_);
  5392. if (method->dest_handlers_) {
  5393. upb_handlers_unref(method->dest_handlers_, method);
  5394. }
  5395. upb_inttable_uninit(&method->dispatch);
  5396. free(method);
  5397. }
  5398. static void visitmethod(const upb_refcounted *r, upb_refcounted_visit *visit,
  5399. void *closure) {
  5400. const upb_pbdecodermethod *m = (const upb_pbdecodermethod*)r;
  5401. visit(r, m->group, closure);
  5402. }
  5403. static upb_pbdecodermethod *newmethod(const upb_handlers *dest_handlers,
  5404. mgroup *group) {
  5405. static const struct upb_refcounted_vtbl vtbl = {visitmethod, freemethod};
  5406. upb_pbdecodermethod *ret = malloc(sizeof(*ret));
  5407. upb_refcounted_init(UPB_UPCAST(ret), &vtbl, &ret);
  5408. upb_byteshandler_init(&ret->input_handler_);
  5409. // The method references the group and vice-versa, in a circular reference.
  5410. upb_ref2(ret, group);
  5411. upb_ref2(group, ret);
  5412. upb_inttable_insertptr(&group->methods, dest_handlers, upb_value_ptr(ret));
  5413. upb_refcounted_unref(UPB_UPCAST(ret), &ret);
  5414. ret->group = UPB_UPCAST(group);
  5415. ret->dest_handlers_ = dest_handlers;
  5416. ret->is_native_ = false; // If we JIT, it will update this later.
  5417. upb_inttable_init(&ret->dispatch, UPB_CTYPE_UINT64);
  5418. if (ret->dest_handlers_) {
  5419. upb_handlers_ref(ret->dest_handlers_, ret);
  5420. }
  5421. return ret;
  5422. }
  5423. void upb_pbdecodermethod_ref(const upb_pbdecodermethod *m, const void *owner) {
  5424. upb_refcounted_ref(UPB_UPCAST(m), owner);
  5425. }
  5426. void upb_pbdecodermethod_unref(const upb_pbdecodermethod *m,
  5427. const void *owner) {
  5428. upb_refcounted_unref(UPB_UPCAST(m), owner);
  5429. }
  5430. void upb_pbdecodermethod_donateref(const upb_pbdecodermethod *m,
  5431. const void *from, const void *to) {
  5432. upb_refcounted_donateref(UPB_UPCAST(m), from, to);
  5433. }
  5434. void upb_pbdecodermethod_checkref(const upb_pbdecodermethod *m,
  5435. const void *owner) {
  5436. upb_refcounted_checkref(UPB_UPCAST(m), owner);
  5437. }
  5438. const upb_handlers *upb_pbdecodermethod_desthandlers(
  5439. const upb_pbdecodermethod *m) {
  5440. return m->dest_handlers_;
  5441. }
  5442. const upb_byteshandler *upb_pbdecodermethod_inputhandler(
  5443. const upb_pbdecodermethod *m) {
  5444. return &m->input_handler_;
  5445. }
  5446. bool upb_pbdecodermethod_isnative(const upb_pbdecodermethod *m) {
  5447. return m->is_native_;
  5448. }
  5449. const upb_pbdecodermethod *upb_pbdecodermethod_new(
  5450. const upb_pbdecodermethodopts *opts, const void *owner) {
  5451. upb_pbcodecache cache;
  5452. upb_pbcodecache_init(&cache);
  5453. const upb_pbdecodermethod *ret =
  5454. upb_pbcodecache_getdecodermethod(&cache, opts);
  5455. upb_pbdecodermethod_ref(ret, owner);
  5456. upb_pbcodecache_uninit(&cache);
  5457. return ret;
  5458. }
  5459. /* bytecode compiler **********************************************************/
  5460. // Data used only at compilation time.
  5461. typedef struct {
  5462. mgroup *group;
  5463. uint32_t *pc;
  5464. int fwd_labels[MAXLABEL];
  5465. int back_labels[MAXLABEL];
  5466. // For fields marked "lazy", parse them lazily or eagerly?
  5467. bool lazy;
  5468. } compiler;
  5469. static compiler *newcompiler(mgroup *group, bool lazy) {
  5470. compiler *ret = malloc(sizeof(*ret));
  5471. ret->group = group;
  5472. ret->lazy = lazy;
  5473. for (int i = 0; i < MAXLABEL; i++) {
  5474. ret->fwd_labels[i] = EMPTYLABEL;
  5475. ret->back_labels[i] = EMPTYLABEL;
  5476. }
  5477. return ret;
  5478. }
  5479. static void freecompiler(compiler *c) {
  5480. free(c);
  5481. }
  5482. const size_t ptr_words = sizeof(void*) / sizeof(uint32_t);
  5483. // How many words an instruction is.
  5484. static int instruction_len(uint32_t instr) {
  5485. switch (getop(instr)) {
  5486. case OP_SETDISPATCH: return 1 + ptr_words;
  5487. case OP_TAGN: return 3;
  5488. case OP_SETBIGGROUPNUM: return 2;
  5489. default: return 1;
  5490. }
  5491. }
  5492. bool op_has_longofs(int32_t instruction) {
  5493. switch (getop(instruction)) {
  5494. case OP_CALL:
  5495. case OP_BRANCH:
  5496. case OP_CHECKDELIM:
  5497. return true;
  5498. // The "tag" instructions only have 8 bytes available for the jump target,
  5499. // but that is ok because these opcodes only require short jumps.
  5500. case OP_TAG1:
  5501. case OP_TAG2:
  5502. case OP_TAGN:
  5503. return false;
  5504. default:
  5505. assert(false);
  5506. return false;
  5507. }
  5508. }
  5509. static int32_t getofs(uint32_t instruction) {
  5510. if (op_has_longofs(instruction)) {
  5511. return (int32_t)instruction >> 8;
  5512. } else {
  5513. return (int8_t)(instruction >> 8);
  5514. }
  5515. }
  5516. static void setofs(uint32_t *instruction, int32_t ofs) {
  5517. if (op_has_longofs(*instruction)) {
  5518. *instruction = getop(*instruction) | ofs << 8;
  5519. } else {
  5520. *instruction = (*instruction & ~0xff00) | ((ofs & 0xff) << 8);
  5521. }
  5522. assert(getofs(*instruction) == ofs); // Would fail in cases of overflow.
  5523. }
  5524. static uint32_t pcofs(compiler *c) { return c->pc - c->group->bytecode; }
  5525. // Defines a local label at the current PC location. All previous forward
  5526. // references are updated to point to this location. The location is noted
  5527. // for any future backward references.
  5528. static void label(compiler *c, unsigned int label) {
  5529. assert(label < MAXLABEL);
  5530. int val = c->fwd_labels[label];
  5531. uint32_t *codep = (val == EMPTYLABEL) ? NULL : c->group->bytecode + val;
  5532. while (codep) {
  5533. int ofs = getofs(*codep);
  5534. setofs(codep, c->pc - codep - instruction_len(*codep));
  5535. codep = ofs ? codep + ofs : NULL;
  5536. }
  5537. c->fwd_labels[label] = EMPTYLABEL;
  5538. c->back_labels[label] = pcofs(c);
  5539. }
  5540. // Creates a reference to a numbered label; either a forward reference
  5541. // (positive arg) or backward reference (negative arg). For forward references
  5542. // the value returned now is actually a "next" pointer into a linked list of all
  5543. // instructions that use this label and will be patched later when the label is
  5544. // defined with label().
  5545. //
  5546. // The returned value is the offset that should be written into the instruction.
  5547. static int32_t labelref(compiler *c, int label) {
  5548. assert(label < MAXLABEL);
  5549. if (label == LABEL_DISPATCH) {
  5550. // No resolving required.
  5551. return 0;
  5552. } else if (label < 0) {
  5553. // Backward local label. Relative to the next instruction.
  5554. uint32_t from = (c->pc + 1) - c->group->bytecode;
  5555. return c->back_labels[-label] - from;
  5556. } else {
  5557. // Forward local label: prepend to (possibly-empty) linked list.
  5558. int *lptr = &c->fwd_labels[label];
  5559. int32_t ret = (*lptr == EMPTYLABEL) ? 0 : *lptr - pcofs(c);
  5560. *lptr = pcofs(c);
  5561. return ret;
  5562. }
  5563. }
  5564. static void put32(compiler *c, uint32_t v) {
  5565. mgroup *g = c->group;
  5566. if (c->pc == g->bytecode_end) {
  5567. int ofs = pcofs(c);
  5568. size_t oldsize = g->bytecode_end - g->bytecode;
  5569. size_t newsize = UPB_MAX(oldsize * 2, 64);
  5570. // TODO(haberman): handle OOM.
  5571. g->bytecode = realloc(g->bytecode, newsize * sizeof(uint32_t));
  5572. g->bytecode_end = g->bytecode + newsize;
  5573. c->pc = g->bytecode + ofs;
  5574. }
  5575. *c->pc++ = v;
  5576. }
  5577. static void putop(compiler *c, opcode op, ...) {
  5578. va_list ap;
  5579. va_start(ap, op);
  5580. switch (op) {
  5581. case OP_SETDISPATCH: {
  5582. uintptr_t ptr = (uintptr_t)va_arg(ap, void*);
  5583. put32(c, OP_SETDISPATCH);
  5584. put32(c, ptr);
  5585. if (sizeof(uintptr_t) > sizeof(uint32_t))
  5586. put32(c, (uint64_t)ptr >> 32);
  5587. break;
  5588. }
  5589. case OP_STARTMSG:
  5590. case OP_ENDMSG:
  5591. case OP_PUSHLENDELIM:
  5592. case OP_POP:
  5593. case OP_SETDELIM:
  5594. case OP_HALT:
  5595. case OP_RET:
  5596. case OP_DISPATCH:
  5597. put32(c, op);
  5598. break;
  5599. case OP_PARSE_DOUBLE:
  5600. case OP_PARSE_FLOAT:
  5601. case OP_PARSE_INT64:
  5602. case OP_PARSE_UINT64:
  5603. case OP_PARSE_INT32:
  5604. case OP_PARSE_FIXED64:
  5605. case OP_PARSE_FIXED32:
  5606. case OP_PARSE_BOOL:
  5607. case OP_PARSE_UINT32:
  5608. case OP_PARSE_SFIXED32:
  5609. case OP_PARSE_SFIXED64:
  5610. case OP_PARSE_SINT32:
  5611. case OP_PARSE_SINT64:
  5612. case OP_STARTSEQ:
  5613. case OP_ENDSEQ:
  5614. case OP_STARTSUBMSG:
  5615. case OP_ENDSUBMSG:
  5616. case OP_STARTSTR:
  5617. case OP_STRING:
  5618. case OP_ENDSTR:
  5619. case OP_PUSHTAGDELIM:
  5620. put32(c, op | va_arg(ap, upb_selector_t) << 8);
  5621. break;
  5622. case OP_SETBIGGROUPNUM:
  5623. put32(c, op);
  5624. put32(c, va_arg(ap, int));
  5625. break;
  5626. case OP_CALL: {
  5627. const upb_pbdecodermethod *method = va_arg(ap, upb_pbdecodermethod *);
  5628. put32(c, op | (method->code_base.ofs - (pcofs(c) + 1)) << 8);
  5629. break;
  5630. }
  5631. case OP_CHECKDELIM:
  5632. case OP_BRANCH: {
  5633. uint32_t instruction = op;
  5634. int label = va_arg(ap, int);
  5635. setofs(&instruction, labelref(c, label));
  5636. put32(c, instruction);
  5637. break;
  5638. }
  5639. case OP_TAG1:
  5640. case OP_TAG2: {
  5641. int label = va_arg(ap, int);
  5642. uint64_t tag = va_arg(ap, uint64_t);
  5643. uint32_t instruction = op | (tag << 16);
  5644. assert(tag <= 0xffff);
  5645. setofs(&instruction, labelref(c, label));
  5646. put32(c, instruction);
  5647. break;
  5648. }
  5649. case OP_TAGN: {
  5650. int label = va_arg(ap, int);
  5651. uint64_t tag = va_arg(ap, uint64_t);
  5652. uint32_t instruction = op | (upb_value_size(tag) << 16);
  5653. setofs(&instruction, labelref(c, label));
  5654. put32(c, instruction);
  5655. put32(c, tag);
  5656. put32(c, tag >> 32);
  5657. break;
  5658. }
  5659. }
  5660. va_end(ap);
  5661. }
  5662. #if defined(UPB_USE_JIT_X64) || defined(UPB_DUMP_BYTECODE)
  5663. const char *upb_pbdecoder_getopname(unsigned int op) {
  5664. #define OP(op) [OP_ ## op] = "OP_" #op
  5665. #define T(op) OP(PARSE_##op)
  5666. static const char *names[] = {
  5667. "<no opcode>",
  5668. T(DOUBLE), T(FLOAT), T(INT64), T(UINT64), T(INT32), T(FIXED64), T(FIXED32),
  5669. T(BOOL), T(UINT32), T(SFIXED32), T(SFIXED64), T(SINT32), T(SINT64),
  5670. OP(STARTMSG), OP(ENDMSG), OP(STARTSEQ), OP(ENDSEQ), OP(STARTSUBMSG),
  5671. OP(ENDSUBMSG), OP(STARTSTR), OP(STRING), OP(ENDSTR), OP(CALL), OP(RET),
  5672. OP(PUSHLENDELIM), OP(PUSHTAGDELIM), OP(SETDELIM), OP(CHECKDELIM),
  5673. OP(BRANCH), OP(TAG1), OP(TAG2), OP(TAGN), OP(SETDISPATCH), OP(POP),
  5674. OP(SETBIGGROUPNUM), OP(DISPATCH), OP(HALT),
  5675. };
  5676. return op > OP_HALT ? names[0] : names[op];
  5677. #undef OP
  5678. #undef T
  5679. }
  5680. #endif
  5681. #ifdef UPB_DUMP_BYTECODE
  5682. static void dumpbc(uint32_t *p, uint32_t *end, FILE *f) {
  5683. uint32_t *begin = p;
  5684. while (p < end) {
  5685. fprintf(f, "%p %8tx", p, p - begin);
  5686. uint32_t instr = *p++;
  5687. uint8_t op = getop(instr);
  5688. fprintf(f, " %s", upb_pbdecoder_getopname(op));
  5689. switch ((opcode)op) {
  5690. case OP_SETDISPATCH: {
  5691. const upb_inttable *dispatch;
  5692. memcpy(&dispatch, p, sizeof(void*));
  5693. p += ptr_words;
  5694. const upb_pbdecodermethod *method =
  5695. (void *)((char *)dispatch -
  5696. offsetof(upb_pbdecodermethod, dispatch));
  5697. fprintf(f, " %s", upb_msgdef_fullname(
  5698. upb_handlers_msgdef(method->dest_handlers_)));
  5699. break;
  5700. }
  5701. case OP_DISPATCH:
  5702. case OP_STARTMSG:
  5703. case OP_ENDMSG:
  5704. case OP_PUSHLENDELIM:
  5705. case OP_POP:
  5706. case OP_SETDELIM:
  5707. case OP_HALT:
  5708. case OP_RET:
  5709. break;
  5710. case OP_PARSE_DOUBLE:
  5711. case OP_PARSE_FLOAT:
  5712. case OP_PARSE_INT64:
  5713. case OP_PARSE_UINT64:
  5714. case OP_PARSE_INT32:
  5715. case OP_PARSE_FIXED64:
  5716. case OP_PARSE_FIXED32:
  5717. case OP_PARSE_BOOL:
  5718. case OP_PARSE_UINT32:
  5719. case OP_PARSE_SFIXED32:
  5720. case OP_PARSE_SFIXED64:
  5721. case OP_PARSE_SINT32:
  5722. case OP_PARSE_SINT64:
  5723. case OP_STARTSEQ:
  5724. case OP_ENDSEQ:
  5725. case OP_STARTSUBMSG:
  5726. case OP_ENDSUBMSG:
  5727. case OP_STARTSTR:
  5728. case OP_STRING:
  5729. case OP_ENDSTR:
  5730. case OP_PUSHTAGDELIM:
  5731. fprintf(f, " %d", instr >> 8);
  5732. break;
  5733. case OP_SETBIGGROUPNUM:
  5734. fprintf(f, " %d", *p++);
  5735. break;
  5736. case OP_CHECKDELIM:
  5737. case OP_CALL:
  5738. case OP_BRANCH:
  5739. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  5740. break;
  5741. case OP_TAG1:
  5742. case OP_TAG2: {
  5743. fprintf(f, " tag:0x%x", instr >> 16);
  5744. if (getofs(instr)) {
  5745. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  5746. }
  5747. break;
  5748. }
  5749. case OP_TAGN: {
  5750. uint64_t tag = *p++;
  5751. tag |= (uint64_t)*p++ << 32;
  5752. fprintf(f, " tag:0x%llx", (long long)tag);
  5753. fprintf(f, " n:%d", instr >> 16);
  5754. if (getofs(instr)) {
  5755. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  5756. }
  5757. break;
  5758. }
  5759. }
  5760. fputs("\n", f);
  5761. }
  5762. }
  5763. #endif
  5764. static uint64_t get_encoded_tag(const upb_fielddef *f, int wire_type) {
  5765. uint32_t tag = (upb_fielddef_number(f) << 3) | wire_type;
  5766. uint64_t encoded_tag = upb_vencode32(tag);
  5767. // No tag should be greater than 5 bytes.
  5768. assert(encoded_tag <= 0xffffffffff);
  5769. return encoded_tag;
  5770. }
  5771. static void putchecktag(compiler *c, const upb_fielddef *f,
  5772. int wire_type, int dest) {
  5773. uint64_t tag = get_encoded_tag(f, wire_type);
  5774. switch (upb_value_size(tag)) {
  5775. case 1:
  5776. putop(c, OP_TAG1, dest, tag);
  5777. break;
  5778. case 2:
  5779. putop(c, OP_TAG2, dest, tag);
  5780. break;
  5781. default:
  5782. putop(c, OP_TAGN, dest, tag);
  5783. break;
  5784. }
  5785. }
  5786. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  5787. upb_selector_t selector;
  5788. bool ok = upb_handlers_getselector(f, type, &selector);
  5789. UPB_ASSERT_VAR(ok, ok);
  5790. return selector;
  5791. }
  5792. // Takes an existing, primary dispatch table entry and repacks it with a
  5793. // different alternate wire type. Called when we are inserting a secondary
  5794. // dispatch table entry for an alternate wire type.
  5795. static uint64_t repack(uint64_t dispatch, int new_wt2) {
  5796. uint64_t ofs;
  5797. uint8_t wt1;
  5798. uint8_t old_wt2;
  5799. upb_pbdecoder_unpackdispatch(dispatch, &ofs, &wt1, &old_wt2);
  5800. assert(old_wt2 == NO_WIRE_TYPE); // wt2 should not be set yet.
  5801. return upb_pbdecoder_packdispatch(ofs, wt1, new_wt2);
  5802. }
  5803. // Marks the current bytecode position as the dispatch target for this message,
  5804. // field, and wire type.
  5805. static void dispatchtarget(compiler *c, upb_pbdecodermethod *method,
  5806. const upb_fielddef *f, int wire_type) {
  5807. // Offset is relative to msg base.
  5808. uint64_t ofs = pcofs(c) - method->code_base.ofs;
  5809. uint32_t fn = upb_fielddef_number(f);
  5810. upb_inttable *d = &method->dispatch;
  5811. upb_value v;
  5812. if (upb_inttable_remove(d, fn, &v)) {
  5813. // TODO: prioritize based on packed setting in .proto file.
  5814. uint64_t repacked = repack(upb_value_getuint64(v), wire_type);
  5815. upb_inttable_insert(d, fn, upb_value_uint64(repacked));
  5816. upb_inttable_insert(d, fn + UPB_MAX_FIELDNUMBER, upb_value_uint64(ofs));
  5817. } else {
  5818. uint64_t val = upb_pbdecoder_packdispatch(ofs, wire_type, NO_WIRE_TYPE);
  5819. upb_inttable_insert(d, fn, upb_value_uint64(val));
  5820. }
  5821. }
  5822. static void putpush(compiler *c, const upb_fielddef *f) {
  5823. if (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE) {
  5824. putop(c, OP_PUSHLENDELIM);
  5825. } else {
  5826. uint32_t fn = upb_fielddef_number(f);
  5827. if (fn >= 1 << 24) {
  5828. putop(c, OP_PUSHTAGDELIM, 0);
  5829. putop(c, OP_SETBIGGROUPNUM, fn);
  5830. } else {
  5831. putop(c, OP_PUSHTAGDELIM, fn);
  5832. }
  5833. }
  5834. }
  5835. static upb_pbdecodermethod *find_submethod(const compiler *c,
  5836. const upb_pbdecodermethod *method,
  5837. const upb_fielddef *f) {
  5838. const upb_handlers *sub =
  5839. upb_handlers_getsubhandlers(method->dest_handlers_, f);
  5840. upb_value v;
  5841. return upb_inttable_lookupptr(&c->group->methods, sub, &v)
  5842. ? upb_value_getptr(v)
  5843. : NULL;
  5844. }
  5845. static void putsel(compiler *c, opcode op, upb_selector_t sel,
  5846. const upb_handlers *h) {
  5847. if (upb_handlers_gethandler(h, sel)) {
  5848. putop(c, op, sel);
  5849. }
  5850. }
  5851. // Puts an opcode to call a callback, but only if a callback actually exists for
  5852. // this field and handler type.
  5853. static void maybeput(compiler *c, opcode op, const upb_handlers *h,
  5854. const upb_fielddef *f, upb_handlertype_t type) {
  5855. putsel(c, op, getsel(f, type), h);
  5856. }
  5857. static bool haslazyhandlers(const upb_handlers *h, const upb_fielddef *f) {
  5858. if (!upb_fielddef_lazy(f))
  5859. return false;
  5860. return upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STARTSTR)) ||
  5861. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STRING)) ||
  5862. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_ENDSTR));
  5863. }
  5864. /* bytecode compiler code generation ******************************************/
  5865. // Symbolic names for our local labels.
  5866. #define LABEL_LOOPSTART 1 // Top of a repeated field loop.
  5867. #define LABEL_LOOPBREAK 2 // To jump out of a repeated loop
  5868. #define LABEL_FIELD 3 // Jump backward to find the most recent field.
  5869. #define LABEL_ENDMSG 4 // To reach the OP_ENDMSG instr for this msg.
  5870. // Generates bytecode to parse a single non-lazy message field.
  5871. static void generate_msgfield(compiler *c, const upb_fielddef *f,
  5872. upb_pbdecodermethod *method) {
  5873. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5874. const upb_pbdecodermethod *sub_m = find_submethod(c, method, f);
  5875. if (!sub_m) {
  5876. // Don't emit any code for this field at all; it will be parsed as an
  5877. // unknown field.
  5878. return;
  5879. }
  5880. label(c, LABEL_FIELD);
  5881. int wire_type =
  5882. (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE)
  5883. ? UPB_WIRE_TYPE_DELIMITED
  5884. : UPB_WIRE_TYPE_START_GROUP;
  5885. if (upb_fielddef_isseq(f)) {
  5886. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5887. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5888. dispatchtarget(c, method, f, wire_type);
  5889. putop(c, OP_PUSHTAGDELIM, 0);
  5890. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  5891. label(c, LABEL_LOOPSTART);
  5892. putpush(c, f);
  5893. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  5894. putop(c, OP_CALL, sub_m);
  5895. putop(c, OP_POP);
  5896. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  5897. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  5898. putop(c, OP_SETDELIM);
  5899. }
  5900. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5901. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  5902. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5903. label(c, LABEL_LOOPBREAK);
  5904. putop(c, OP_POP);
  5905. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5906. } else {
  5907. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5908. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5909. dispatchtarget(c, method, f, wire_type);
  5910. putpush(c, f);
  5911. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  5912. putop(c, OP_CALL, sub_m);
  5913. putop(c, OP_POP);
  5914. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  5915. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  5916. putop(c, OP_SETDELIM);
  5917. }
  5918. }
  5919. }
  5920. // Generates bytecode to parse a single string or lazy submessage field.
  5921. static void generate_delimfield(compiler *c, const upb_fielddef *f,
  5922. upb_pbdecodermethod *method) {
  5923. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5924. label(c, LABEL_FIELD);
  5925. if (upb_fielddef_isseq(f)) {
  5926. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5927. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5928. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5929. putop(c, OP_PUSHTAGDELIM, 0);
  5930. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  5931. label(c, LABEL_LOOPSTART);
  5932. putop(c, OP_PUSHLENDELIM);
  5933. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  5934. // Need to emit even if no handler to skip past the string.
  5935. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  5936. putop(c, OP_POP);
  5937. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  5938. putop(c, OP_SETDELIM);
  5939. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5940. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_LOOPBREAK);
  5941. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5942. label(c, LABEL_LOOPBREAK);
  5943. putop(c, OP_POP);
  5944. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5945. } else {
  5946. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5947. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5948. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5949. putop(c, OP_PUSHLENDELIM);
  5950. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  5951. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  5952. putop(c, OP_POP);
  5953. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  5954. putop(c, OP_SETDELIM);
  5955. }
  5956. }
  5957. // Generates bytecode to parse a single primitive field.
  5958. static void generate_primitivefield(compiler *c, const upb_fielddef *f,
  5959. upb_pbdecodermethod *method) {
  5960. label(c, LABEL_FIELD);
  5961. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5962. upb_descriptortype_t descriptor_type = upb_fielddef_descriptortype(f);
  5963. // From a decoding perspective, ENUM is the same as INT32.
  5964. if (descriptor_type == UPB_DESCRIPTOR_TYPE_ENUM)
  5965. descriptor_type = UPB_DESCRIPTOR_TYPE_INT32;
  5966. opcode parse_type = (opcode)descriptor_type;
  5967. // TODO(haberman): generate packed or non-packed first depending on "packed"
  5968. // setting in the fielddef. This will favor (in speed) whichever was
  5969. // specified.
  5970. assert((int)parse_type >= 0 && parse_type <= OP_MAX);
  5971. upb_selector_t sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  5972. int wire_type = upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  5973. if (upb_fielddef_isseq(f)) {
  5974. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5975. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5976. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5977. putop(c, OP_PUSHLENDELIM);
  5978. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); // Packed
  5979. label(c, LABEL_LOOPSTART);
  5980. putop(c, parse_type, sel);
  5981. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5982. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5983. dispatchtarget(c, method, f, wire_type);
  5984. putop(c, OP_PUSHTAGDELIM, 0);
  5985. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); // Non-packed
  5986. label(c, LABEL_LOOPSTART);
  5987. putop(c, parse_type, sel);
  5988. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5989. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  5990. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5991. label(c, LABEL_LOOPBREAK);
  5992. putop(c, OP_POP); // Packed and non-packed join.
  5993. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5994. putop(c, OP_SETDELIM); // Could remove for non-packed by dup ENDSEQ.
  5995. } else {
  5996. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5997. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5998. dispatchtarget(c, method, f, wire_type);
  5999. putop(c, parse_type, sel);
  6000. }
  6001. }
  6002. // Adds bytecode for parsing the given message to the given decoderplan,
  6003. // while adding all dispatch targets to this message's dispatch table.
  6004. static void compile_method(compiler *c, upb_pbdecodermethod *method) {
  6005. assert(method);
  6006. // Clear all entries in the dispatch table.
  6007. upb_inttable_uninit(&method->dispatch);
  6008. upb_inttable_init(&method->dispatch, UPB_CTYPE_UINT64);
  6009. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  6010. const upb_msgdef *md = upb_handlers_msgdef(h);
  6011. method->code_base.ofs = pcofs(c);
  6012. putop(c, OP_SETDISPATCH, &method->dispatch);
  6013. putsel(c, OP_STARTMSG, UPB_STARTMSG_SELECTOR, h);
  6014. label(c, LABEL_FIELD);
  6015. uint32_t* start_pc = c->pc;
  6016. upb_msg_field_iter i;
  6017. for(upb_msg_field_begin(&i, md);
  6018. !upb_msg_field_done(&i);
  6019. upb_msg_field_next(&i)) {
  6020. const upb_fielddef *f = upb_msg_iter_field(&i);
  6021. upb_fieldtype_t type = upb_fielddef_type(f);
  6022. if (type == UPB_TYPE_MESSAGE && !(haslazyhandlers(h, f) && c->lazy)) {
  6023. generate_msgfield(c, f, method);
  6024. } else if (type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES ||
  6025. type == UPB_TYPE_MESSAGE) {
  6026. generate_delimfield(c, f, method);
  6027. } else {
  6028. generate_primitivefield(c, f, method);
  6029. }
  6030. }
  6031. // If there were no fields, or if no handlers were defined, we need to
  6032. // generate a non-empty loop body so that we can at least dispatch for unknown
  6033. // fields and check for the end of the message.
  6034. if (c->pc == start_pc) {
  6035. // Check for end-of-message.
  6036. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6037. // Unconditionally dispatch.
  6038. putop(c, OP_DISPATCH, 0);
  6039. }
  6040. // For now we just loop back to the last field of the message (or if none,
  6041. // the DISPATCH opcode for the message).
  6042. putop(c, OP_BRANCH, -LABEL_FIELD);
  6043. // Insert both a label and a dispatch table entry for this end-of-msg.
  6044. label(c, LABEL_ENDMSG);
  6045. upb_value val = upb_value_uint64(pcofs(c) - method->code_base.ofs);
  6046. upb_inttable_insert(&method->dispatch, DISPATCH_ENDMSG, val);
  6047. putsel(c, OP_ENDMSG, UPB_ENDMSG_SELECTOR, h);
  6048. putop(c, OP_RET);
  6049. upb_inttable_compact(&method->dispatch);
  6050. }
  6051. // Populate "methods" with new upb_pbdecodermethod objects reachable from "h".
  6052. // Returns the method for these handlers.
  6053. //
  6054. // Generates a new method for every destination handlers reachable from "h".
  6055. static void find_methods(compiler *c, const upb_handlers *h) {
  6056. upb_value v;
  6057. if (upb_inttable_lookupptr(&c->group->methods, h, &v))
  6058. return;
  6059. newmethod(h, c->group);
  6060. // Find submethods.
  6061. upb_msg_field_iter i;
  6062. const upb_msgdef *md = upb_handlers_msgdef(h);
  6063. for(upb_msg_field_begin(&i, md);
  6064. !upb_msg_field_done(&i);
  6065. upb_msg_field_next(&i)) {
  6066. const upb_fielddef *f = upb_msg_iter_field(&i);
  6067. const upb_handlers *sub_h;
  6068. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  6069. (sub_h = upb_handlers_getsubhandlers(h, f)) != NULL) {
  6070. // We only generate a decoder method for submessages with handlers.
  6071. // Others will be parsed as unknown fields.
  6072. find_methods(c, sub_h);
  6073. }
  6074. }
  6075. }
  6076. // (Re-)compile bytecode for all messages in "msgs."
  6077. // Overwrites any existing bytecode in "c".
  6078. static void compile_methods(compiler *c) {
  6079. // Start over at the beginning of the bytecode.
  6080. c->pc = c->group->bytecode;
  6081. upb_inttable_iter i;
  6082. upb_inttable_begin(&i, &c->group->methods);
  6083. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  6084. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  6085. compile_method(c, method);
  6086. }
  6087. }
  6088. static void set_bytecode_handlers(mgroup *g) {
  6089. upb_inttable_iter i;
  6090. upb_inttable_begin(&i, &g->methods);
  6091. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  6092. upb_pbdecodermethod *m = upb_value_getptr(upb_inttable_iter_value(&i));
  6093. m->code_base.ptr = g->bytecode + m->code_base.ofs;
  6094. upb_byteshandler *h = &m->input_handler_;
  6095. upb_byteshandler_setstartstr(h, upb_pbdecoder_startbc, m->code_base.ptr);
  6096. upb_byteshandler_setstring(h, upb_pbdecoder_decode, g);
  6097. upb_byteshandler_setendstr(h, upb_pbdecoder_end, m);
  6098. }
  6099. }
  6100. /* JIT setup. *****************************************************************/
  6101. #ifdef UPB_USE_JIT_X64
  6102. static void sethandlers(mgroup *g, bool allowjit) {
  6103. g->jit_code = NULL;
  6104. if (allowjit) {
  6105. // Compile byte-code into machine code, create handlers.
  6106. upb_pbdecoder_jit(g);
  6107. } else {
  6108. set_bytecode_handlers(g);
  6109. }
  6110. }
  6111. #else // UPB_USE_JIT_X64
  6112. static void sethandlers(mgroup *g, bool allowjit) {
  6113. // No JIT compiled in; use bytecode handlers unconditionally.
  6114. UPB_UNUSED(allowjit);
  6115. set_bytecode_handlers(g);
  6116. }
  6117. #endif // UPB_USE_JIT_X64
  6118. // TODO(haberman): allow this to be constructed for an arbitrary set of dest
  6119. // handlers and other mgroups (but verify we have a transitive closure).
  6120. const mgroup *mgroup_new(const upb_handlers *dest, bool allowjit, bool lazy,
  6121. const void *owner) {
  6122. UPB_UNUSED(allowjit);
  6123. assert(upb_handlers_isfrozen(dest));
  6124. mgroup *g = newgroup(owner);
  6125. compiler *c = newcompiler(g, lazy);
  6126. find_methods(c, dest);
  6127. // We compile in two passes:
  6128. // 1. all messages are assigned relative offsets from the beginning of the
  6129. // bytecode (saved in method->code_base).
  6130. // 2. forwards OP_CALL instructions can be correctly linked since message
  6131. // offsets have been previously assigned.
  6132. //
  6133. // Could avoid the second pass by linking OP_CALL instructions somehow.
  6134. compile_methods(c);
  6135. compile_methods(c);
  6136. g->bytecode_end = c->pc;
  6137. freecompiler(c);
  6138. #ifdef UPB_DUMP_BYTECODE
  6139. FILE *f = fopen("/tmp/upb-bytecode", "wb");
  6140. assert(f);
  6141. dumpbc(g->bytecode, g->bytecode_end, stderr);
  6142. dumpbc(g->bytecode, g->bytecode_end, f);
  6143. fclose(f);
  6144. #endif
  6145. sethandlers(g, allowjit);
  6146. return g;
  6147. }
  6148. /* upb_pbcodecache ************************************************************/
  6149. void upb_pbcodecache_init(upb_pbcodecache *c) {
  6150. upb_inttable_init(&c->groups, UPB_CTYPE_CONSTPTR);
  6151. c->allow_jit_ = true;
  6152. }
  6153. void upb_pbcodecache_uninit(upb_pbcodecache *c) {
  6154. upb_inttable_iter i;
  6155. upb_inttable_begin(&i, &c->groups);
  6156. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  6157. const mgroup *group = upb_value_getconstptr(upb_inttable_iter_value(&i));
  6158. upb_refcounted_unref(UPB_UPCAST(group), c);
  6159. }
  6160. upb_inttable_uninit(&c->groups);
  6161. }
  6162. bool upb_pbcodecache_allowjit(const upb_pbcodecache *c) {
  6163. return c->allow_jit_;
  6164. }
  6165. bool upb_pbcodecache_setallowjit(upb_pbcodecache *c, bool allow) {
  6166. if (upb_inttable_count(&c->groups) > 0)
  6167. return false;
  6168. c->allow_jit_ = allow;
  6169. return true;
  6170. }
  6171. const upb_pbdecodermethod *upb_pbcodecache_getdecodermethod(
  6172. upb_pbcodecache *c, const upb_pbdecodermethodopts *opts) {
  6173. // Right now we build a new DecoderMethod every time.
  6174. // TODO(haberman): properly cache methods by their true key.
  6175. const mgroup *g = mgroup_new(opts->handlers, c->allow_jit_, opts->lazy, c);
  6176. upb_inttable_push(&c->groups, upb_value_constptr(g));
  6177. upb_value v;
  6178. bool ok = upb_inttable_lookupptr(&g->methods, opts->handlers, &v);
  6179. UPB_ASSERT_VAR(ok, ok);
  6180. return upb_value_getptr(v);
  6181. }
  6182. /* upb_pbdecodermethodopts ****************************************************/
  6183. void upb_pbdecodermethodopts_init(upb_pbdecodermethodopts *opts,
  6184. const upb_handlers *h) {
  6185. opts->handlers = h;
  6186. opts->lazy = false;
  6187. }
  6188. void upb_pbdecodermethodopts_setlazy(upb_pbdecodermethodopts *opts, bool lazy) {
  6189. opts->lazy = lazy;
  6190. }
  6191. /*
  6192. * upb - a minimalist implementation of protocol buffers.
  6193. *
  6194. * Copyright (c) 2008-2013 Google Inc. See LICENSE for details.
  6195. * Author: Josh Haberman <jhaberman@gmail.com>
  6196. *
  6197. * This file implements a VM for the interpreted (bytecode) decoder.
  6198. *
  6199. * Bytecode must previously have been generated using the bytecode compiler in
  6200. * compile_decoder.c. This decoder then walks through the bytecode op-by-op to
  6201. * parse the input.
  6202. *
  6203. * Decoding is fully resumable; we just keep a pointer to the current bytecode
  6204. * instruction and resume from there. A fair amount of the logic here is to
  6205. * handle the fact that values can span buffer seams and we have to be able to
  6206. * be capable of suspending/resuming from any byte in the stream. This
  6207. * sometimes requires keeping a few trailing bytes from the last buffer around
  6208. * in the "residual" buffer.
  6209. */
  6210. #include <inttypes.h>
  6211. #include <setjmp.h>
  6212. #include <stdarg.h>
  6213. #include <stddef.h>
  6214. #include <stdlib.h>
  6215. #ifdef UPB_DUMP_BYTECODE
  6216. #include <stdio.h>
  6217. #endif
  6218. #define CHECK_SUSPEND(x) if (!(x)) return upb_pbdecoder_suspend(d);
  6219. // Error messages that are shared between the bytecode and JIT decoders.
  6220. const char *kPbDecoderStackOverflow = "Nesting too deep.";
  6221. // Error messages shared within this file.
  6222. static const char *kUnterminatedVarint = "Unterminated varint.";
  6223. /* upb_pbdecoder **************************************************************/
  6224. static opcode halt = OP_HALT;
  6225. // Whether an op consumes any of the input buffer.
  6226. static bool consumes_input(opcode op) {
  6227. switch (op) {
  6228. case OP_SETDISPATCH:
  6229. case OP_STARTMSG:
  6230. case OP_ENDMSG:
  6231. case OP_STARTSEQ:
  6232. case OP_ENDSEQ:
  6233. case OP_STARTSUBMSG:
  6234. case OP_ENDSUBMSG:
  6235. case OP_STARTSTR:
  6236. case OP_ENDSTR:
  6237. case OP_PUSHTAGDELIM:
  6238. case OP_POP:
  6239. case OP_SETDELIM:
  6240. case OP_SETBIGGROUPNUM:
  6241. case OP_CHECKDELIM:
  6242. case OP_CALL:
  6243. case OP_RET:
  6244. case OP_BRANCH:
  6245. return false;
  6246. default:
  6247. return true;
  6248. }
  6249. }
  6250. static bool in_residual_buf(const upb_pbdecoder *d, const char *p);
  6251. // It's unfortunate that we have to micro-manage the compiler this way,
  6252. // especially since this tuning is necessarily specific to one hardware
  6253. // configuration. But emperically on a Core i7, performance increases 30-50%
  6254. // with these annotations. Every instance where these appear, gcc 4.2.1 made
  6255. // the wrong decision and degraded performance in benchmarks.
  6256. #define FORCEINLINE static inline __attribute__((always_inline))
  6257. #define NOINLINE __attribute__((noinline))
  6258. static void seterr(upb_pbdecoder *d, const char *msg) {
  6259. // TODO(haberman): encapsulate this access to pipeline->status, but not sure
  6260. // exactly what that interface should look like.
  6261. upb_status_seterrmsg(d->status, msg);
  6262. }
  6263. void upb_pbdecoder_seterr(upb_pbdecoder *d, const char *msg) {
  6264. seterr(d, msg);
  6265. }
  6266. /* Buffering ******************************************************************/
  6267. // We operate on one buffer at a time, which is either the user's buffer passed
  6268. // to our "decode" callback or some residual bytes from the previous buffer.
  6269. // How many bytes can be safely read from d->ptr without reading past end-of-buf
  6270. // or past the current delimited end.
  6271. static size_t curbufleft(const upb_pbdecoder *d) {
  6272. assert(d->data_end >= d->ptr);
  6273. return d->data_end - d->ptr;
  6274. }
  6275. // Overall stream offset of d->ptr.
  6276. uint64_t offset(const upb_pbdecoder *d) {
  6277. return d->bufstart_ofs + (d->ptr - d->buf);
  6278. }
  6279. // Advances d->ptr.
  6280. static void advance(upb_pbdecoder *d, size_t len) {
  6281. assert(curbufleft(d) >= len);
  6282. d->ptr += len;
  6283. }
  6284. static bool in_buf(const char *p, const char *buf, const char *end) {
  6285. return p >= buf && p <= end;
  6286. }
  6287. static bool in_residual_buf(const upb_pbdecoder *d, const char *p) {
  6288. return in_buf(p, d->residual, d->residual_end);
  6289. }
  6290. // Calculates the delim_end value, which is affected by both the current buffer
  6291. // and the parsing stack, so must be called whenever either is updated.
  6292. static void set_delim_end(upb_pbdecoder *d) {
  6293. size_t delim_ofs = d->top->end_ofs - d->bufstart_ofs;
  6294. if (delim_ofs <= (d->end - d->buf)) {
  6295. d->delim_end = d->buf + delim_ofs;
  6296. d->data_end = d->delim_end;
  6297. } else {
  6298. d->data_end = d->end;
  6299. d->delim_end = NULL;
  6300. }
  6301. }
  6302. static void switchtobuf(upb_pbdecoder *d, const char *buf, const char *end) {
  6303. d->ptr = buf;
  6304. d->buf = buf;
  6305. d->end = end;
  6306. set_delim_end(d);
  6307. }
  6308. static void advancetobuf(upb_pbdecoder *d, const char *buf, size_t len) {
  6309. assert(curbufleft(d) == 0);
  6310. d->bufstart_ofs += (d->end - d->buf);
  6311. switchtobuf(d, buf, buf + len);
  6312. }
  6313. static void checkpoint(upb_pbdecoder *d) {
  6314. // The assertion here is in the interests of efficiency, not correctness.
  6315. // We are trying to ensure that we don't checkpoint() more often than
  6316. // necessary.
  6317. assert(d->checkpoint != d->ptr);
  6318. d->checkpoint = d->ptr;
  6319. }
  6320. // Resumes the decoder from an initial state or from a previous suspend.
  6321. int32_t upb_pbdecoder_resume(upb_pbdecoder *d, void *p, const char *buf,
  6322. size_t size, const upb_bufhandle *handle) {
  6323. UPB_UNUSED(p); // Useless; just for the benefit of the JIT.
  6324. d->buf_param = buf;
  6325. d->size_param = size;
  6326. d->handle = handle;
  6327. if (d->residual_end > d->residual) {
  6328. // We have residual bytes from the last buffer.
  6329. assert(d->ptr == d->residual);
  6330. } else {
  6331. switchtobuf(d, buf, buf + size);
  6332. }
  6333. d->checkpoint = d->ptr;
  6334. if (d->top->groupnum < 0) {
  6335. CHECK_RETURN(upb_pbdecoder_skipunknown(d, -1, 0));
  6336. d->checkpoint = d->ptr;
  6337. }
  6338. return DECODE_OK;
  6339. }
  6340. // Suspends the decoder at the last checkpoint, without saving any residual
  6341. // bytes. If there are any unconsumed bytes, returns a short byte count.
  6342. size_t upb_pbdecoder_suspend(upb_pbdecoder *d) {
  6343. d->pc = d->last;
  6344. if (d->checkpoint == d->residual) {
  6345. // Checkpoint was in residual buf; no user bytes were consumed.
  6346. d->ptr = d->residual;
  6347. return 0;
  6348. } else {
  6349. assert(!in_residual_buf(d, d->checkpoint));
  6350. assert(d->buf == d->buf_param);
  6351. size_t consumed = d->checkpoint - d->buf;
  6352. d->bufstart_ofs += consumed;
  6353. d->residual_end = d->residual;
  6354. switchtobuf(d, d->residual, d->residual_end);
  6355. return consumed;
  6356. }
  6357. }
  6358. // Suspends the decoder at the last checkpoint, and saves any unconsumed
  6359. // bytes in our residual buffer. This is necessary if we need more user
  6360. // bytes to form a complete value, which might not be contiguous in the
  6361. // user's buffers. Always consumes all user bytes.
  6362. static size_t suspend_save(upb_pbdecoder *d) {
  6363. // We hit end-of-buffer before we could parse a full value.
  6364. // Save any unconsumed bytes (if any) to the residual buffer.
  6365. d->pc = d->last;
  6366. if (d->checkpoint == d->residual) {
  6367. // Checkpoint was in residual buf; append user byte(s) to residual buf.
  6368. assert((d->residual_end - d->residual) + d->size_param <=
  6369. sizeof(d->residual));
  6370. if (!in_residual_buf(d, d->ptr)) {
  6371. d->bufstart_ofs -= (d->residual_end - d->residual);
  6372. }
  6373. memcpy(d->residual_end, d->buf_param, d->size_param);
  6374. d->residual_end += d->size_param;
  6375. } else {
  6376. // Checkpoint was in user buf; old residual bytes not needed.
  6377. assert(!in_residual_buf(d, d->checkpoint));
  6378. d->ptr = d->checkpoint;
  6379. size_t save = curbufleft(d);
  6380. assert(save <= sizeof(d->residual));
  6381. memcpy(d->residual, d->ptr, save);
  6382. d->residual_end = d->residual + save;
  6383. d->bufstart_ofs = offset(d);
  6384. }
  6385. switchtobuf(d, d->residual, d->residual_end);
  6386. return d->size_param;
  6387. }
  6388. // Skips "bytes" bytes in the stream, which may be more than available. If we
  6389. // skip more bytes than are available, we return a long read count to the caller
  6390. // indicating how many bytes the caller should skip before passing a new buffer.
  6391. static int32_t skip(upb_pbdecoder *d, size_t bytes) {
  6392. assert(!in_residual_buf(d, d->ptr) || d->size_param == 0);
  6393. if (curbufleft(d) >= bytes) {
  6394. // Skipped data is all in current buffer.
  6395. advance(d, bytes);
  6396. return DECODE_OK;
  6397. } else {
  6398. // Skipped data extends beyond currently available buffers.
  6399. d->pc = d->last;
  6400. size_t skip = bytes - curbufleft(d);
  6401. d->bufstart_ofs += (d->end - d->buf) + skip;
  6402. d->residual_end = d->residual;
  6403. switchtobuf(d, d->residual, d->residual_end);
  6404. return d->size_param + skip;
  6405. }
  6406. }
  6407. // Copies the next "bytes" bytes into "buf" and advances the stream.
  6408. // Requires that this many bytes are available in the current buffer.
  6409. FORCEINLINE void consumebytes(upb_pbdecoder *d, void *buf, size_t bytes) {
  6410. assert(bytes <= curbufleft(d));
  6411. memcpy(buf, d->ptr, bytes);
  6412. advance(d, bytes);
  6413. }
  6414. // Slow path for getting the next "bytes" bytes, regardless of whether they are
  6415. // available in the current buffer or not. Returns a status code as described
  6416. // in decoder.int.h.
  6417. static NOINLINE int32_t getbytes_slow(upb_pbdecoder *d, void *buf,
  6418. size_t bytes) {
  6419. const size_t avail = curbufleft(d);
  6420. consumebytes(d, buf, avail);
  6421. bytes -= avail;
  6422. assert(bytes > 0);
  6423. if (in_residual_buf(d, d->ptr)) {
  6424. advancetobuf(d, d->buf_param, d->size_param);
  6425. }
  6426. if (curbufleft(d) >= bytes) {
  6427. consumebytes(d, buf + avail, bytes);
  6428. return DECODE_OK;
  6429. } else if (d->data_end == d->delim_end) {
  6430. seterr(d, "Submessage ended in the middle of a value or group");
  6431. return upb_pbdecoder_suspend(d);
  6432. } else {
  6433. return suspend_save(d);
  6434. }
  6435. }
  6436. // Gets the next "bytes" bytes, regardless of whether they are available in the
  6437. // current buffer or not. Returns a status code as described in decoder.int.h.
  6438. FORCEINLINE int32_t getbytes(upb_pbdecoder *d, void *buf, size_t bytes) {
  6439. if (curbufleft(d) >= bytes) {
  6440. // Buffer has enough data to satisfy.
  6441. consumebytes(d, buf, bytes);
  6442. return DECODE_OK;
  6443. } else {
  6444. return getbytes_slow(d, buf, bytes);
  6445. }
  6446. }
  6447. static NOINLINE size_t peekbytes_slow(upb_pbdecoder *d, void *buf,
  6448. size_t bytes) {
  6449. size_t ret = curbufleft(d);
  6450. memcpy(buf, d->ptr, ret);
  6451. if (in_residual_buf(d, d->ptr)) {
  6452. size_t copy = UPB_MIN(bytes - ret, d->size_param);
  6453. memcpy(buf + ret, d->buf_param, copy);
  6454. ret += copy;
  6455. }
  6456. return ret;
  6457. }
  6458. FORCEINLINE size_t peekbytes(upb_pbdecoder *d, void *buf, size_t bytes) {
  6459. if (curbufleft(d) >= bytes) {
  6460. memcpy(buf, d->ptr, bytes);
  6461. return bytes;
  6462. } else {
  6463. return peekbytes_slow(d, buf, bytes);
  6464. }
  6465. }
  6466. /* Decoding of wire types *****************************************************/
  6467. // Slow path for decoding a varint from the current buffer position.
  6468. // Returns a status code as described in decoder.int.h.
  6469. NOINLINE int32_t upb_pbdecoder_decode_varint_slow(upb_pbdecoder *d,
  6470. uint64_t *u64) {
  6471. *u64 = 0;
  6472. uint8_t byte = 0x80;
  6473. int bitpos;
  6474. for(bitpos = 0; bitpos < 70 && (byte & 0x80); bitpos += 7) {
  6475. int32_t ret = getbytes(d, &byte, 1);
  6476. if (ret >= 0) return ret;
  6477. *u64 |= (uint64_t)(byte & 0x7F) << bitpos;
  6478. }
  6479. if(bitpos == 70 && (byte & 0x80)) {
  6480. seterr(d, kUnterminatedVarint);
  6481. return upb_pbdecoder_suspend(d);
  6482. }
  6483. return DECODE_OK;
  6484. }
  6485. // Decodes a varint from the current buffer position.
  6486. // Returns a status code as described in decoder.int.h.
  6487. FORCEINLINE int32_t decode_varint(upb_pbdecoder *d, uint64_t *u64) {
  6488. if (curbufleft(d) > 0 && !(*d->ptr & 0x80)) {
  6489. *u64 = *d->ptr;
  6490. advance(d, 1);
  6491. return DECODE_OK;
  6492. } else if (curbufleft(d) >= 10) {
  6493. // Fast case.
  6494. upb_decoderet r = upb_vdecode_fast(d->ptr);
  6495. if (r.p == NULL) {
  6496. seterr(d, kUnterminatedVarint);
  6497. return upb_pbdecoder_suspend(d);
  6498. }
  6499. advance(d, r.p - d->ptr);
  6500. *u64 = r.val;
  6501. return DECODE_OK;
  6502. } else {
  6503. // Slow case -- varint spans buffer seam.
  6504. return upb_pbdecoder_decode_varint_slow(d, u64);
  6505. }
  6506. }
  6507. // Decodes a 32-bit varint from the current buffer position.
  6508. // Returns a status code as described in decoder.int.h.
  6509. FORCEINLINE int32_t decode_v32(upb_pbdecoder *d, uint32_t *u32) {
  6510. uint64_t u64;
  6511. int32_t ret = decode_varint(d, &u64);
  6512. if (ret >= 0) return ret;
  6513. if (u64 > UINT32_MAX) {
  6514. seterr(d, "Unterminated 32-bit varint");
  6515. // TODO(haberman) guarantee that this function return is >= 0 somehow,
  6516. // so we know this path will always be treated as error by our caller.
  6517. // Right now the size_t -> int32_t can overflow and produce negative values.
  6518. *u32 = 0;
  6519. return upb_pbdecoder_suspend(d);
  6520. }
  6521. *u32 = u64;
  6522. return DECODE_OK;
  6523. }
  6524. // Decodes a fixed32 from the current buffer position.
  6525. // Returns a status code as described in decoder.int.h.
  6526. // TODO: proper byte swapping for big-endian machines.
  6527. FORCEINLINE int32_t decode_fixed32(upb_pbdecoder *d, uint32_t *u32) {
  6528. return getbytes(d, u32, 4);
  6529. }
  6530. // Decodes a fixed64 from the current buffer position.
  6531. // Returns a status code as described in decoder.int.h.
  6532. // TODO: proper byte swapping for big-endian machines.
  6533. FORCEINLINE int32_t decode_fixed64(upb_pbdecoder *d, uint64_t *u64) {
  6534. return getbytes(d, u64, 8);
  6535. }
  6536. // Non-static versions of the above functions.
  6537. // These are called by the JIT for fallback paths.
  6538. int32_t upb_pbdecoder_decode_f32(upb_pbdecoder *d, uint32_t *u32) {
  6539. return decode_fixed32(d, u32);
  6540. }
  6541. int32_t upb_pbdecoder_decode_f64(upb_pbdecoder *d, uint64_t *u64) {
  6542. return decode_fixed64(d, u64);
  6543. }
  6544. static double as_double(uint64_t n) { double d; memcpy(&d, &n, 8); return d; }
  6545. static float as_float(uint32_t n) { float f; memcpy(&f, &n, 4); return f; }
  6546. // Pushes a frame onto the decoder stack.
  6547. static bool decoder_push(upb_pbdecoder *d, uint64_t end) {
  6548. upb_pbdecoder_frame *fr = d->top;
  6549. if (end > fr->end_ofs) {
  6550. seterr(d, "Submessage end extends past enclosing submessage.");
  6551. return false;
  6552. } else if ((fr + 1) == d->limit) {
  6553. seterr(d, kPbDecoderStackOverflow);
  6554. return false;
  6555. }
  6556. fr++;
  6557. fr->end_ofs = end;
  6558. fr->dispatch = NULL;
  6559. fr->groupnum = 0;
  6560. d->top = fr;
  6561. return true;
  6562. }
  6563. static bool pushtagdelim(upb_pbdecoder *d, uint32_t arg) {
  6564. // While we expect to see an "end" tag (either ENDGROUP or a non-sequence
  6565. // field number) prior to hitting any enclosing submessage end, pushing our
  6566. // existing delim end prevents us from continuing to parse values from a
  6567. // corrupt proto that doesn't give us an END tag in time.
  6568. if (!decoder_push(d, d->top->end_ofs))
  6569. return false;
  6570. d->top->groupnum = arg;
  6571. return true;
  6572. }
  6573. // Pops a frame from the decoder stack.
  6574. static void decoder_pop(upb_pbdecoder *d) { d->top--; }
  6575. NOINLINE int32_t upb_pbdecoder_checktag_slow(upb_pbdecoder *d,
  6576. uint64_t expected) {
  6577. uint64_t data = 0;
  6578. size_t bytes = upb_value_size(expected);
  6579. size_t read = peekbytes(d, &data, bytes);
  6580. if (read == bytes && data == expected) {
  6581. // Advance past matched bytes.
  6582. int32_t ok = getbytes(d, &data, read);
  6583. UPB_ASSERT_VAR(ok, ok < 0);
  6584. return DECODE_OK;
  6585. } else if (read < bytes && memcmp(&data, &expected, read) == 0) {
  6586. return suspend_save(d);
  6587. } else {
  6588. return DECODE_MISMATCH;
  6589. }
  6590. }
  6591. int32_t upb_pbdecoder_skipunknown(upb_pbdecoder *d, int32_t fieldnum,
  6592. uint8_t wire_type) {
  6593. if (fieldnum >= 0)
  6594. goto have_tag;
  6595. while (true) {
  6596. uint32_t tag;
  6597. CHECK_RETURN(decode_v32(d, &tag));
  6598. wire_type = tag & 0x7;
  6599. fieldnum = tag >> 3;
  6600. have_tag:
  6601. if (fieldnum == 0) {
  6602. seterr(d, "Saw invalid field number (0)");
  6603. return upb_pbdecoder_suspend(d);
  6604. }
  6605. // TODO: deliver to unknown field callback.
  6606. switch (wire_type) {
  6607. case UPB_WIRE_TYPE_32BIT:
  6608. CHECK_RETURN(skip(d, 4));
  6609. break;
  6610. case UPB_WIRE_TYPE_64BIT:
  6611. CHECK_RETURN(skip(d, 8));
  6612. break;
  6613. case UPB_WIRE_TYPE_VARINT: {
  6614. uint64_t u64;
  6615. CHECK_RETURN(decode_varint(d, &u64));
  6616. break;
  6617. }
  6618. case UPB_WIRE_TYPE_DELIMITED: {
  6619. uint32_t len;
  6620. CHECK_RETURN(decode_v32(d, &len));
  6621. CHECK_RETURN(skip(d, len));
  6622. break;
  6623. }
  6624. case UPB_WIRE_TYPE_START_GROUP:
  6625. CHECK_SUSPEND(pushtagdelim(d, -fieldnum));
  6626. break;
  6627. case UPB_WIRE_TYPE_END_GROUP:
  6628. if (fieldnum == -d->top->groupnum) {
  6629. decoder_pop(d);
  6630. } else if (fieldnum == d->top->groupnum) {
  6631. return DECODE_ENDGROUP;
  6632. } else {
  6633. seterr(d, "Unmatched ENDGROUP tag.");
  6634. return upb_pbdecoder_suspend(d);
  6635. }
  6636. break;
  6637. default:
  6638. seterr(d, "Invalid wire type");
  6639. return upb_pbdecoder_suspend(d);
  6640. }
  6641. if (d->top->groupnum >= 0) {
  6642. return DECODE_OK;
  6643. }
  6644. if (d->ptr == d->delim_end) {
  6645. seterr(d, "Enclosing submessage ended in the middle of value or group");
  6646. // Unlike most errors we notice during parsing, right now we have consumed
  6647. // all of the user's input.
  6648. //
  6649. // There are three different options for how to handle this case:
  6650. //
  6651. // 1. decode() = short count, error = set
  6652. // 2. decode() = full count, error = set
  6653. // 3. decode() = full count, error NOT set, short count and error will
  6654. // be reported on next call to decode() (or end())
  6655. //
  6656. // (1) and (3) have the advantage that they preserve the invariant that an
  6657. // error occurs iff decode() returns a short count.
  6658. //
  6659. // (2) and (3) have the advantage of reflecting the fact that all of the
  6660. // bytes were in fact parsed (and possibly delivered to the unknown field
  6661. // handler, in the future when that is supported).
  6662. //
  6663. // (3) requires extra state in the decode (a place to store the "permanent
  6664. // error" that we should return for all subsequent attempts to decode).
  6665. // But we likely want this anyway.
  6666. //
  6667. // Right now we do (1), thanks to the fact that we checkpoint *after* this
  6668. // check. (3) may be a better choice long term; unclear at the moment.
  6669. return upb_pbdecoder_suspend(d);
  6670. }
  6671. checkpoint(d);
  6672. }
  6673. }
  6674. static void goto_endmsg(upb_pbdecoder *d) {
  6675. upb_value v;
  6676. bool found = upb_inttable_lookup32(d->top->dispatch, DISPATCH_ENDMSG, &v);
  6677. UPB_ASSERT_VAR(found, found);
  6678. d->pc = d->top->base + upb_value_getuint64(v);
  6679. }
  6680. // Parses a tag and jumps to the corresponding bytecode instruction for this
  6681. // field.
  6682. //
  6683. // If the tag is unknown (or the wire type doesn't match), parses the field as
  6684. // unknown. If the tag is a valid ENDGROUP tag, jumps to the bytecode
  6685. // instruction for the end of message.
  6686. static int32_t dispatch(upb_pbdecoder *d) {
  6687. upb_inttable *dispatch = d->top->dispatch;
  6688. // Decode tag.
  6689. uint32_t tag;
  6690. CHECK_RETURN(decode_v32(d, &tag));
  6691. uint8_t wire_type = tag & 0x7;
  6692. uint32_t fieldnum = tag >> 3;
  6693. // Lookup tag. Because of packed/non-packed compatibility, we have to
  6694. // check the wire type against two possibilities.
  6695. upb_value val;
  6696. if (fieldnum != DISPATCH_ENDMSG &&
  6697. upb_inttable_lookup32(dispatch, fieldnum, &val)) {
  6698. uint64_t v = upb_value_getuint64(val);
  6699. if (wire_type == (v & 0xff)) {
  6700. d->pc = d->top->base + (v >> 16);
  6701. return DECODE_OK;
  6702. } else if (wire_type == ((v >> 8) & 0xff)) {
  6703. bool found =
  6704. upb_inttable_lookup(dispatch, fieldnum + UPB_MAX_FIELDNUMBER, &val);
  6705. UPB_ASSERT_VAR(found, found);
  6706. d->pc = d->top->base + upb_value_getuint64(val);
  6707. return DECODE_OK;
  6708. }
  6709. }
  6710. // Unknown field or ENDGROUP.
  6711. int32_t ret = upb_pbdecoder_skipunknown(d, fieldnum, wire_type);
  6712. if (ret == DECODE_ENDGROUP) {
  6713. goto_endmsg(d);
  6714. return DECODE_OK;
  6715. } else {
  6716. d->pc = d->last - 1; // Rewind to CHECKDELIM.
  6717. return ret;
  6718. }
  6719. }
  6720. // Callers know that the stack is more than one deep because the opcodes that
  6721. // call this only occur after PUSH operations.
  6722. upb_pbdecoder_frame *outer_frame(upb_pbdecoder *d) {
  6723. assert(d->top != d->stack);
  6724. return d->top - 1;
  6725. }
  6726. /* The main decoding loop *****************************************************/
  6727. // The main decoder VM function. Uses traditional bytecode dispatch loop with a
  6728. // switch() statement.
  6729. size_t upb_pbdecoder_decode(void *closure, const void *hd, const char *buf,
  6730. size_t size, const upb_bufhandle *handle) {
  6731. upb_pbdecoder *d = closure;
  6732. const mgroup *group = hd;
  6733. assert(buf);
  6734. int32_t result = upb_pbdecoder_resume(d, NULL, buf, size, handle);
  6735. if (result == DECODE_ENDGROUP) {
  6736. goto_endmsg(d);
  6737. }
  6738. CHECK_RETURN(result);
  6739. UPB_UNUSED(group);
  6740. #define VMCASE(op, code) \
  6741. case op: { code; if (consumes_input(op)) checkpoint(d); break; }
  6742. #define PRIMITIVE_OP(type, wt, name, convfunc, ctype) \
  6743. VMCASE(OP_PARSE_ ## type, { \
  6744. ctype val; \
  6745. CHECK_RETURN(decode_ ## wt(d, &val)); \
  6746. upb_sink_put ## name(&d->top->sink, arg, (convfunc)(val)); \
  6747. })
  6748. while(1) {
  6749. d->last = d->pc;
  6750. int32_t instruction = *d->pc++;
  6751. opcode op = getop(instruction);
  6752. uint32_t arg = instruction >> 8;
  6753. int32_t longofs = arg;
  6754. assert(d->ptr != d->residual_end);
  6755. #ifdef UPB_DUMP_BYTECODE
  6756. fprintf(stderr, "s_ofs=%d buf_ofs=%d data_rem=%d buf_rem=%d delim_rem=%d "
  6757. "%x %s (%d)\n",
  6758. (int)offset(d),
  6759. (int)(d->ptr - d->buf),
  6760. (int)(d->data_end - d->ptr),
  6761. (int)(d->end - d->ptr),
  6762. (int)((d->top->end_ofs - d->bufstart_ofs) - (d->ptr - d->buf)),
  6763. (int)(d->pc - 1 - group->bytecode),
  6764. upb_pbdecoder_getopname(op),
  6765. arg);
  6766. #endif
  6767. switch (op) {
  6768. // Technically, we are losing data if we see a 32-bit varint that is not
  6769. // properly sign-extended. We could detect this and error about the data
  6770. // loss, but proto2 does not do this, so we pass.
  6771. PRIMITIVE_OP(INT32, varint, int32, int32_t, uint64_t)
  6772. PRIMITIVE_OP(INT64, varint, int64, int64_t, uint64_t)
  6773. PRIMITIVE_OP(UINT32, varint, uint32, uint32_t, uint64_t)
  6774. PRIMITIVE_OP(UINT64, varint, uint64, uint64_t, uint64_t)
  6775. PRIMITIVE_OP(FIXED32, fixed32, uint32, uint32_t, uint32_t)
  6776. PRIMITIVE_OP(FIXED64, fixed64, uint64, uint64_t, uint64_t)
  6777. PRIMITIVE_OP(SFIXED32, fixed32, int32, int32_t, uint32_t)
  6778. PRIMITIVE_OP(SFIXED64, fixed64, int64, int64_t, uint64_t)
  6779. PRIMITIVE_OP(BOOL, varint, bool, bool, uint64_t)
  6780. PRIMITIVE_OP(DOUBLE, fixed64, double, as_double, uint64_t)
  6781. PRIMITIVE_OP(FLOAT, fixed32, float, as_float, uint32_t)
  6782. PRIMITIVE_OP(SINT32, varint, int32, upb_zzdec_32, uint64_t)
  6783. PRIMITIVE_OP(SINT64, varint, int64, upb_zzdec_64, uint64_t)
  6784. VMCASE(OP_SETDISPATCH,
  6785. d->top->base = d->pc - 1;
  6786. memcpy(&d->top->dispatch, d->pc, sizeof(void*));
  6787. d->pc += sizeof(void*) / sizeof(uint32_t);
  6788. )
  6789. VMCASE(OP_STARTMSG,
  6790. CHECK_SUSPEND(upb_sink_startmsg(&d->top->sink));
  6791. )
  6792. VMCASE(OP_ENDMSG,
  6793. CHECK_SUSPEND(upb_sink_endmsg(&d->top->sink, d->status));
  6794. )
  6795. VMCASE(OP_STARTSEQ,
  6796. upb_pbdecoder_frame *outer = outer_frame(d);
  6797. CHECK_SUSPEND(upb_sink_startseq(&outer->sink, arg, &d->top->sink));
  6798. )
  6799. VMCASE(OP_ENDSEQ,
  6800. CHECK_SUSPEND(upb_sink_endseq(&d->top->sink, arg));
  6801. )
  6802. VMCASE(OP_STARTSUBMSG,
  6803. upb_pbdecoder_frame *outer = outer_frame(d);
  6804. CHECK_SUSPEND(upb_sink_startsubmsg(&outer->sink, arg, &d->top->sink));
  6805. )
  6806. VMCASE(OP_ENDSUBMSG,
  6807. CHECK_SUSPEND(upb_sink_endsubmsg(&d->top->sink, arg));
  6808. )
  6809. VMCASE(OP_STARTSTR,
  6810. uint32_t len = d->top->end_ofs - offset(d);
  6811. upb_pbdecoder_frame *outer = outer_frame(d);
  6812. CHECK_SUSPEND(upb_sink_startstr(&outer->sink, arg, len, &d->top->sink));
  6813. if (len == 0) {
  6814. d->pc++; // Skip OP_STRING.
  6815. }
  6816. )
  6817. VMCASE(OP_STRING,
  6818. uint32_t len = curbufleft(d);
  6819. size_t n = upb_sink_putstring(&d->top->sink, arg, d->ptr, len, handle);
  6820. if (n > len) {
  6821. if (n > d->top->end_ofs - offset(d)) {
  6822. seterr(d, "Tried to skip past end of string.");
  6823. return upb_pbdecoder_suspend(d);
  6824. } else {
  6825. int32_t ret = skip(d, n);
  6826. // This shouldn't return DECODE_OK, because n > len.
  6827. assert(ret >= 0);
  6828. return ret;
  6829. }
  6830. }
  6831. advance(d, n);
  6832. if (n < len || d->delim_end == NULL) {
  6833. // We aren't finished with this string yet.
  6834. d->pc--; // Repeat OP_STRING.
  6835. if (n > 0) checkpoint(d);
  6836. return upb_pbdecoder_suspend(d);
  6837. }
  6838. )
  6839. VMCASE(OP_ENDSTR,
  6840. CHECK_SUSPEND(upb_sink_endstr(&d->top->sink, arg));
  6841. )
  6842. VMCASE(OP_PUSHTAGDELIM,
  6843. CHECK_SUSPEND(pushtagdelim(d, arg));
  6844. )
  6845. VMCASE(OP_SETBIGGROUPNUM,
  6846. d->top->groupnum = *d->pc++;
  6847. )
  6848. VMCASE(OP_POP,
  6849. assert(d->top > d->stack);
  6850. decoder_pop(d);
  6851. )
  6852. VMCASE(OP_PUSHLENDELIM,
  6853. uint32_t len;
  6854. CHECK_RETURN(decode_v32(d, &len));
  6855. CHECK_SUSPEND(decoder_push(d, offset(d) + len));
  6856. set_delim_end(d);
  6857. )
  6858. VMCASE(OP_SETDELIM,
  6859. set_delim_end(d);
  6860. )
  6861. VMCASE(OP_CHECKDELIM,
  6862. // We are guaranteed of this assert because we never allow ourselves to
  6863. // consume bytes beyond data_end, which covers delim_end when non-NULL.
  6864. assert(!(d->delim_end && d->ptr > d->delim_end));
  6865. if (d->ptr == d->delim_end)
  6866. d->pc += longofs;
  6867. )
  6868. VMCASE(OP_CALL,
  6869. d->callstack[d->call_len++] = d->pc;
  6870. d->pc += longofs;
  6871. )
  6872. VMCASE(OP_RET,
  6873. assert(d->call_len > 0);
  6874. d->pc = d->callstack[--d->call_len];
  6875. )
  6876. VMCASE(OP_BRANCH,
  6877. d->pc += longofs;
  6878. )
  6879. VMCASE(OP_TAG1,
  6880. CHECK_SUSPEND(curbufleft(d) > 0);
  6881. uint8_t expected = (arg >> 8) & 0xff;
  6882. if (*d->ptr == expected) {
  6883. advance(d, 1);
  6884. } else {
  6885. int8_t shortofs;
  6886. badtag:
  6887. shortofs = arg;
  6888. if (shortofs == LABEL_DISPATCH) {
  6889. CHECK_RETURN(dispatch(d));
  6890. } else {
  6891. d->pc += shortofs;
  6892. break; // Avoid checkpoint().
  6893. }
  6894. }
  6895. )
  6896. VMCASE(OP_TAG2,
  6897. CHECK_SUSPEND(curbufleft(d) > 0);
  6898. uint16_t expected = (arg >> 8) & 0xffff;
  6899. if (curbufleft(d) >= 2) {
  6900. uint16_t actual;
  6901. memcpy(&actual, d->ptr, 2);
  6902. if (expected == actual) {
  6903. advance(d, 2);
  6904. } else {
  6905. goto badtag;
  6906. }
  6907. } else {
  6908. int32_t result = upb_pbdecoder_checktag_slow(d, expected);
  6909. if (result == DECODE_MISMATCH) goto badtag;
  6910. if (result >= 0) return result;
  6911. }
  6912. )
  6913. VMCASE(OP_TAGN, {
  6914. uint64_t expected;
  6915. memcpy(&expected, d->pc, 8);
  6916. d->pc += 2;
  6917. int32_t result = upb_pbdecoder_checktag_slow(d, expected);
  6918. if (result == DECODE_MISMATCH) goto badtag;
  6919. if (result >= 0) return result;
  6920. })
  6921. VMCASE(OP_DISPATCH, {
  6922. CHECK_RETURN(dispatch(d));
  6923. })
  6924. VMCASE(OP_HALT, {
  6925. return size;
  6926. })
  6927. }
  6928. }
  6929. }
  6930. void *upb_pbdecoder_startbc(void *closure, const void *pc, size_t size_hint) {
  6931. upb_pbdecoder *d = closure;
  6932. UPB_UNUSED(size_hint);
  6933. d->call_len = 1;
  6934. d->pc = pc;
  6935. return d;
  6936. }
  6937. void *upb_pbdecoder_startjit(void *closure, const void *hd, size_t size_hint) {
  6938. UPB_UNUSED(hd);
  6939. UPB_UNUSED(size_hint);
  6940. upb_pbdecoder *d = closure;
  6941. d->call_len = 0;
  6942. return d;
  6943. }
  6944. bool upb_pbdecoder_end(void *closure, const void *handler_data) {
  6945. upb_pbdecoder *d = closure;
  6946. const upb_pbdecodermethod *method = handler_data;
  6947. if (d->residual_end > d->residual) {
  6948. seterr(d, "Unexpected EOF");
  6949. return false;
  6950. }
  6951. if (d->top->end_ofs != UINT64_MAX) {
  6952. seterr(d, "Unexpected EOF inside delimited string");
  6953. return false;
  6954. }
  6955. // Message ends here.
  6956. uint64_t end = offset(d);
  6957. d->top->end_ofs = end;
  6958. char dummy;
  6959. #ifdef UPB_USE_JIT_X64
  6960. const mgroup *group = (const mgroup*)method->group;
  6961. if (group->jit_code) {
  6962. if (d->top != d->stack)
  6963. d->stack->end_ofs = 0;
  6964. group->jit_code(closure, method->code_base.ptr, &dummy, 0, NULL);
  6965. } else {
  6966. #endif
  6967. d->stack->end_ofs = end;
  6968. const uint32_t *p = d->pc;
  6969. // Check the previous bytecode, but guard against beginning.
  6970. if (p != method->code_base.ptr) p--;
  6971. if (getop(*p) == OP_CHECKDELIM) {
  6972. // Rewind from OP_TAG* to OP_CHECKDELIM.
  6973. assert(getop(*d->pc) == OP_TAG1 ||
  6974. getop(*d->pc) == OP_TAG2 ||
  6975. getop(*d->pc) == OP_TAGN ||
  6976. getop(*d->pc == OP_DISPATCH));
  6977. d->pc = p;
  6978. }
  6979. upb_pbdecoder_decode(closure, handler_data, &dummy, 0, NULL);
  6980. #ifdef UPB_USE_JIT_X64
  6981. }
  6982. #endif
  6983. if (d->call_len != 0) {
  6984. seterr(d, "Unexpected EOF");
  6985. return false;
  6986. }
  6987. return true;
  6988. }
  6989. void upb_pbdecoder_init(upb_pbdecoder *d, const upb_pbdecodermethod *m,
  6990. upb_status *s) {
  6991. d->limit = &d->stack[UPB_DECODER_MAX_NESTING];
  6992. upb_bytessink_reset(&d->input_, &m->input_handler_, d);
  6993. d->method_ = m;
  6994. d->callstack[0] = &halt;
  6995. d->status = s;
  6996. upb_pbdecoder_reset(d);
  6997. }
  6998. void upb_pbdecoder_reset(upb_pbdecoder *d) {
  6999. d->top = d->stack;
  7000. d->top->end_ofs = UINT64_MAX;
  7001. d->top->groupnum = 0;
  7002. d->bufstart_ofs = 0;
  7003. d->ptr = d->residual;
  7004. d->buf = d->residual;
  7005. d->end = d->residual;
  7006. d->residual_end = d->residual;
  7007. d->call_len = 1;
  7008. }
  7009. uint64_t upb_pbdecoder_bytesparsed(const upb_pbdecoder *d) {
  7010. return offset(d);
  7011. }
  7012. // Not currently required, but to support outgrowing the static stack we need
  7013. // this.
  7014. void upb_pbdecoder_uninit(upb_pbdecoder *d) {
  7015. UPB_UNUSED(d);
  7016. }
  7017. const upb_pbdecodermethod *upb_pbdecoder_method(const upb_pbdecoder *d) {
  7018. return d->method_;
  7019. }
  7020. bool upb_pbdecoder_resetoutput(upb_pbdecoder *d, upb_sink* sink) {
  7021. // TODO(haberman): do we need to test whether the decoder is already on the
  7022. // stack (like calling this from within a callback)? Should we support
  7023. // rebinding the output at all?
  7024. assert(sink);
  7025. if (d->method_->dest_handlers_) {
  7026. if (sink->handlers != d->method_->dest_handlers_)
  7027. return false;
  7028. }
  7029. upb_sink_reset(&d->top->sink, sink->handlers, sink->closure);
  7030. return true;
  7031. }
  7032. upb_bytessink *upb_pbdecoder_input(upb_pbdecoder *d) {
  7033. return &d->input_;
  7034. }
  7035. /*
  7036. * upb - a minimalist implementation of protocol buffers.
  7037. *
  7038. * Copyright (c) 2014 Google Inc. See LICENSE for details.
  7039. * Author: Josh Haberman <jhaberman@gmail.com>
  7040. *
  7041. * Since we are implementing pure handlers (ie. without any out-of-band access
  7042. * to pre-computed lengths), we have to buffer all submessages before we can
  7043. * emit even their first byte.
  7044. *
  7045. * Not knowing the size of submessages also means we can't write a perfect
  7046. * zero-copy implementation, even with buffering. Lengths are stored as
  7047. * varints, which means that we don't know how many bytes to reserve for the
  7048. * length until we know what the length is.
  7049. *
  7050. * This leaves us with three main choices:
  7051. *
  7052. * 1. buffer all submessage data in a temporary buffer, then copy it exactly
  7053. * once into the output buffer.
  7054. *
  7055. * 2. attempt to buffer data directly into the output buffer, estimating how
  7056. * many bytes each length will take. When our guesses are wrong, use
  7057. * memmove() to grow or shrink the allotted space.
  7058. *
  7059. * 3. buffer directly into the output buffer, allocating a max length
  7060. * ahead-of-time for each submessage length. If we overallocated, we waste
  7061. * space, but no memcpy() or memmove() is required. This approach requires
  7062. * defining a maximum size for submessages and rejecting submessages that
  7063. * exceed that size.
  7064. *
  7065. * (2) and (3) have the potential to have better performance, but they are more
  7066. * complicated and subtle to implement:
  7067. *
  7068. * (3) requires making an arbitrary choice of the maximum message size; it
  7069. * wastes space when submessages are shorter than this and fails
  7070. * completely when they are longer. This makes it more finicky and
  7071. * requires configuration based on the input. It also makes it impossible
  7072. * to perfectly match the output of reference encoders that always use the
  7073. * optimal amount of space for each length.
  7074. *
  7075. * (2) requires guessing the the size upfront, and if multiple lengths are
  7076. * guessed wrong the minimum required number of memmove() operations may
  7077. * be complicated to compute correctly. Implemented properly, it may have
  7078. * a useful amortized or average cost, but more investigation is required
  7079. * to determine this and what the optimal algorithm is to achieve it.
  7080. *
  7081. * (1) makes you always pay for exactly one copy, but its implementation is
  7082. * the simplest and its performance is predictable.
  7083. *
  7084. * So for now, we implement (1) only. If we wish to optimize later, we should
  7085. * be able to do it without affecting users.
  7086. *
  7087. * The strategy is to buffer the segments of data that do *not* depend on
  7088. * unknown lengths in one buffer, and keep a separate buffer of segment pointers
  7089. * and lengths. When the top-level submessage ends, we can go beginning to end,
  7090. * alternating the writing of lengths with memcpy() of the rest of the data.
  7091. * At the top level though, no buffering is required.
  7092. */
  7093. #include <stdlib.h>
  7094. /* low-level buffering ********************************************************/
  7095. // Low-level functions for interacting with the output buffer.
  7096. // TODO(haberman): handle pushback
  7097. static void putbuf(upb_pb_encoder *e, const char *buf, size_t len) {
  7098. size_t n = upb_bytessink_putbuf(e->output_, e->subc, buf, len, NULL);
  7099. UPB_ASSERT_VAR(n, n == len);
  7100. }
  7101. static upb_pb_encoder_segment *top(upb_pb_encoder *e) {
  7102. return &e->segbuf[*e->top];
  7103. }
  7104. // Call to ensure that at least "bytes" bytes are available for writing at
  7105. // e->ptr. Returns false if the bytes could not be allocated.
  7106. static bool reserve(upb_pb_encoder *e, size_t bytes) {
  7107. if ((e->limit - e->ptr) < bytes) {
  7108. size_t needed = bytes + (e->ptr - e->buf);
  7109. size_t old_size = e->limit - e->buf;
  7110. size_t new_size = old_size;
  7111. while (new_size < needed) {
  7112. new_size *= 2;
  7113. }
  7114. char *realloc_from = (e->buf == e->initbuf) ? NULL : e->buf;
  7115. char *new_buf = realloc(realloc_from, new_size);
  7116. if (new_buf == NULL) {
  7117. return false;
  7118. }
  7119. if (realloc_from == NULL) {
  7120. memcpy(new_buf, e->initbuf, old_size);
  7121. }
  7122. e->ptr = new_buf + (e->ptr - e->buf);
  7123. e->runbegin = new_buf + (e->runbegin - e->buf);
  7124. e->limit = new_buf + new_size;
  7125. e->buf = new_buf;
  7126. }
  7127. return true;
  7128. }
  7129. // Call when "bytes" bytes have been writte at e->ptr. The caller *must* have
  7130. // previously called reserve() with at least this many bytes.
  7131. static void encoder_advance(upb_pb_encoder *e, size_t bytes) {
  7132. assert((e->limit - e->ptr) >= bytes);
  7133. e->ptr += bytes;
  7134. }
  7135. // Call when all of the bytes for a handler have been written. Flushes the
  7136. // bytes if possible and necessary, returning false if this failed.
  7137. static bool commit(upb_pb_encoder *e) {
  7138. if (!e->top) {
  7139. // We aren't inside a delimited region. Flush our accumulated bytes to
  7140. // the output.
  7141. //
  7142. // TODO(haberman): in the future we may want to delay flushing for
  7143. // efficiency reasons.
  7144. putbuf(e, e->buf, e->ptr - e->buf);
  7145. e->ptr = e->buf;
  7146. }
  7147. return true;
  7148. }
  7149. // Writes the given bytes to the buffer, handling reserve/advance.
  7150. static bool encode_bytes(upb_pb_encoder *e, const void *data, size_t len) {
  7151. if (!reserve(e, len)) {
  7152. return false;
  7153. }
  7154. memcpy(e->ptr, data, len);
  7155. encoder_advance(e, len);
  7156. return true;
  7157. }
  7158. // Finish the current run by adding the run totals to the segment and message
  7159. // length.
  7160. static void accumulate(upb_pb_encoder *e) {
  7161. assert(e->ptr >= e->runbegin);
  7162. size_t run_len = e->ptr - e->runbegin;
  7163. e->segptr->seglen += run_len;
  7164. top(e)->msglen += run_len;
  7165. e->runbegin = e->ptr;
  7166. }
  7167. // Call to indicate the start of delimited region for which the full length is
  7168. // not yet known. All data will be buffered until the length is known.
  7169. // Delimited regions may be nested; their lengths will all be tracked properly.
  7170. static bool start_delim(upb_pb_encoder *e) {
  7171. if (e->top) {
  7172. // We are already buffering, advance to the next segment and push it on the
  7173. // stack.
  7174. accumulate(e);
  7175. if (++e->top == e->stacklimit) {
  7176. // TODO(haberman): grow stack?
  7177. return false;
  7178. }
  7179. if (++e->segptr == e->seglimit) {
  7180. upb_pb_encoder_segment *realloc_from =
  7181. (e->segbuf == e->seginitbuf) ? NULL : e->segbuf;
  7182. size_t old_size =
  7183. (e->seglimit - e->segbuf) * sizeof(upb_pb_encoder_segment);
  7184. size_t new_size = old_size * 2;
  7185. upb_pb_encoder_segment *new_buf = realloc(realloc_from, new_size);
  7186. if (new_buf == NULL) {
  7187. return false;
  7188. }
  7189. if (realloc_from == NULL) {
  7190. memcpy(new_buf, e->seginitbuf, old_size);
  7191. }
  7192. e->segptr = new_buf + (e->segptr - e->segbuf);
  7193. e->seglimit = new_buf + (new_size / sizeof(upb_pb_encoder_segment));
  7194. e->segbuf = new_buf;
  7195. }
  7196. } else {
  7197. // We were previously at the top level, start buffering.
  7198. e->segptr = e->segbuf;
  7199. e->top = e->stack;
  7200. e->runbegin = e->ptr;
  7201. }
  7202. *e->top = e->segptr - e->segbuf;
  7203. e->segptr->seglen = 0;
  7204. e->segptr->msglen = 0;
  7205. return true;
  7206. }
  7207. // Call to indicate the end of a delimited region. We now know the length of
  7208. // the delimited region. If we are not nested inside any other delimited
  7209. // regions, we can now emit all of the buffered data we accumulated.
  7210. static bool end_delim(upb_pb_encoder *e) {
  7211. accumulate(e);
  7212. size_t msglen = top(e)->msglen;
  7213. if (e->top == e->stack) {
  7214. // All lengths are now available, emit all buffered data.
  7215. char buf[UPB_PB_VARINT_MAX_LEN];
  7216. upb_pb_encoder_segment *s;
  7217. const char *ptr = e->buf;
  7218. for (s = e->segbuf; s <= e->segptr; s++) {
  7219. size_t lenbytes = upb_vencode64(s->msglen, buf);
  7220. putbuf(e, buf, lenbytes);
  7221. putbuf(e, ptr, s->seglen);
  7222. ptr += s->seglen;
  7223. }
  7224. e->ptr = e->buf;
  7225. e->top = NULL;
  7226. } else {
  7227. // Need to keep buffering; propagate length info into enclosing submessages.
  7228. --e->top;
  7229. top(e)->msglen += msglen + upb_varint_size(msglen);
  7230. }
  7231. return true;
  7232. }
  7233. /* tag_t **********************************************************************/
  7234. // A precomputed (pre-encoded) tag and length.
  7235. typedef struct {
  7236. uint8_t bytes;
  7237. char tag[7];
  7238. } tag_t;
  7239. // Allocates a new tag for this field, and sets it in these handlerattr.
  7240. static void new_tag(upb_handlers *h, const upb_fielddef *f, upb_wiretype_t wt,
  7241. upb_handlerattr *attr) {
  7242. uint32_t n = upb_fielddef_number(f);
  7243. tag_t *tag = malloc(sizeof(tag_t));
  7244. tag->bytes = upb_vencode64((n << 3) | wt, tag->tag);
  7245. upb_handlerattr_init(attr);
  7246. upb_handlerattr_sethandlerdata(attr, tag);
  7247. upb_handlers_addcleanup(h, tag, free);
  7248. }
  7249. static bool encode_tag(upb_pb_encoder *e, const tag_t *tag) {
  7250. return encode_bytes(e, tag->tag, tag->bytes);
  7251. }
  7252. /* encoding of wire types *****************************************************/
  7253. static bool encode_fixed64(upb_pb_encoder *e, uint64_t val) {
  7254. // TODO(haberman): byte-swap for big endian.
  7255. return encode_bytes(e, &val, sizeof(uint64_t));
  7256. }
  7257. static bool encode_fixed32(upb_pb_encoder *e, uint32_t val) {
  7258. // TODO(haberman): byte-swap for big endian.
  7259. return encode_bytes(e, &val, sizeof(uint32_t));
  7260. }
  7261. static bool encode_varint(upb_pb_encoder *e, uint64_t val) {
  7262. if (!reserve(e, UPB_PB_VARINT_MAX_LEN)) {
  7263. return false;
  7264. }
  7265. encoder_advance(e, upb_vencode64(val, e->ptr));
  7266. return true;
  7267. }
  7268. static uint64_t dbl2uint64(double d) {
  7269. uint64_t ret;
  7270. memcpy(&ret, &d, sizeof(uint64_t));
  7271. return ret;
  7272. }
  7273. static uint32_t flt2uint32(float d) {
  7274. uint32_t ret;
  7275. memcpy(&ret, &d, sizeof(uint32_t));
  7276. return ret;
  7277. }
  7278. /* encoding of proto types ****************************************************/
  7279. static bool startmsg(void *c, const void *hd) {
  7280. upb_pb_encoder *e = c;
  7281. UPB_UNUSED(hd);
  7282. if (e->depth++ == 0) {
  7283. upb_bytessink_start(e->output_, 0, &e->subc);
  7284. }
  7285. return true;
  7286. }
  7287. static bool endmsg(void *c, const void *hd, upb_status *status) {
  7288. upb_pb_encoder *e = c;
  7289. UPB_UNUSED(hd);
  7290. UPB_UNUSED(status);
  7291. if (--e->depth == 0) {
  7292. upb_bytessink_end(e->output_);
  7293. }
  7294. return true;
  7295. }
  7296. static void *encode_startdelimfield(void *c, const void *hd) {
  7297. bool ok = encode_tag(c, hd) && commit(c) && start_delim(c);
  7298. return ok ? c : UPB_BREAK;
  7299. }
  7300. static bool encode_enddelimfield(void *c, const void *hd) {
  7301. UPB_UNUSED(hd);
  7302. return end_delim(c);
  7303. }
  7304. static void *encode_startgroup(void *c, const void *hd) {
  7305. return (encode_tag(c, hd) && commit(c)) ? c : UPB_BREAK;
  7306. }
  7307. static bool encode_endgroup(void *c, const void *hd) {
  7308. return encode_tag(c, hd) && commit(c);
  7309. }
  7310. static void *encode_startstr(void *c, const void *hd, size_t size_hint) {
  7311. UPB_UNUSED(size_hint);
  7312. return encode_startdelimfield(c, hd);
  7313. }
  7314. static size_t encode_strbuf(void *c, const void *hd, const char *buf,
  7315. size_t len, const upb_bufhandle *h) {
  7316. UPB_UNUSED(hd);
  7317. UPB_UNUSED(h);
  7318. return encode_bytes(c, buf, len) ? len : 0;
  7319. }
  7320. #define T(type, ctype, convert, encode) \
  7321. static bool encode_scalar_##type(void *e, const void *hd, ctype val) { \
  7322. return encode_tag(e, hd) && encode(e, (convert)(val)) && commit(e); \
  7323. } \
  7324. static bool encode_packed_##type(void *e, const void *hd, ctype val) { \
  7325. UPB_UNUSED(hd); \
  7326. return encode(e, (convert)(val)); \
  7327. }
  7328. T(double, double, dbl2uint64, encode_fixed64)
  7329. T(float, float, flt2uint32, encode_fixed32);
  7330. T(int64, int64_t, uint64_t, encode_varint);
  7331. T(int32, int32_t, uint32_t, encode_varint);
  7332. T(fixed64, uint64_t, uint64_t, encode_fixed64);
  7333. T(fixed32, uint32_t, uint32_t, encode_fixed32);
  7334. T(bool, bool, bool, encode_varint);
  7335. T(uint32, uint32_t, uint32_t, encode_varint);
  7336. T(uint64, uint64_t, uint64_t, encode_varint);
  7337. T(enum, int32_t, uint32_t, encode_varint);
  7338. T(sfixed32, int32_t, uint32_t, encode_fixed32);
  7339. T(sfixed64, int64_t, uint64_t, encode_fixed64);
  7340. T(sint32, int32_t, upb_zzenc_32, encode_varint);
  7341. T(sint64, int64_t, upb_zzenc_64, encode_varint);
  7342. #undef T
  7343. /* code to build the handlers *************************************************/
  7344. static void newhandlers_callback(const void *closure, upb_handlers *h) {
  7345. UPB_UNUSED(closure);
  7346. upb_handlers_setstartmsg(h, startmsg, NULL);
  7347. upb_handlers_setendmsg(h, endmsg, NULL);
  7348. const upb_msgdef *m = upb_handlers_msgdef(h);
  7349. upb_msg_field_iter i;
  7350. for(upb_msg_field_begin(&i, m);
  7351. !upb_msg_field_done(&i);
  7352. upb_msg_field_next(&i)) {
  7353. const upb_fielddef *f = upb_msg_iter_field(&i);
  7354. bool packed = upb_fielddef_isseq(f) && upb_fielddef_isprimitive(f) &&
  7355. upb_fielddef_packed(f);
  7356. upb_handlerattr attr;
  7357. upb_wiretype_t wt =
  7358. packed ? UPB_WIRE_TYPE_DELIMITED
  7359. : upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  7360. // Pre-encode the tag for this field.
  7361. new_tag(h, f, wt, &attr);
  7362. if (packed) {
  7363. upb_handlers_setstartseq(h, f, encode_startdelimfield, &attr);
  7364. upb_handlers_setendseq(h, f, encode_enddelimfield, &attr);
  7365. }
  7366. #define T(upper, lower, upbtype) \
  7367. case UPB_DESCRIPTOR_TYPE_##upper: \
  7368. if (packed) { \
  7369. upb_handlers_set##upbtype(h, f, encode_packed_##lower, &attr); \
  7370. } else { \
  7371. upb_handlers_set##upbtype(h, f, encode_scalar_##lower, &attr); \
  7372. } \
  7373. break;
  7374. switch (upb_fielddef_descriptortype(f)) {
  7375. T(DOUBLE, double, double);
  7376. T(FLOAT, float, float);
  7377. T(INT64, int64, int64);
  7378. T(INT32, int32, int32);
  7379. T(FIXED64, fixed64, uint64);
  7380. T(FIXED32, fixed32, uint32);
  7381. T(BOOL, bool, bool);
  7382. T(UINT32, uint32, uint32);
  7383. T(UINT64, uint64, uint64);
  7384. T(ENUM, enum, int32);
  7385. T(SFIXED32, sfixed32, int32);
  7386. T(SFIXED64, sfixed64, int64);
  7387. T(SINT32, sint32, int32);
  7388. T(SINT64, sint64, int64);
  7389. case UPB_DESCRIPTOR_TYPE_STRING:
  7390. case UPB_DESCRIPTOR_TYPE_BYTES:
  7391. upb_handlers_setstartstr(h, f, encode_startstr, &attr);
  7392. upb_handlers_setendstr(h, f, encode_enddelimfield, &attr);
  7393. upb_handlers_setstring(h, f, encode_strbuf, &attr);
  7394. break;
  7395. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  7396. upb_handlers_setstartsubmsg(h, f, encode_startdelimfield, &attr);
  7397. upb_handlers_setendsubmsg(h, f, encode_enddelimfield, &attr);
  7398. break;
  7399. case UPB_DESCRIPTOR_TYPE_GROUP: {
  7400. // Endgroup takes a different tag (wire_type = END_GROUP).
  7401. upb_handlerattr attr2;
  7402. new_tag(h, f, UPB_WIRE_TYPE_END_GROUP, &attr2);
  7403. upb_handlers_setstartsubmsg(h, f, encode_startgroup, &attr);
  7404. upb_handlers_setendsubmsg(h, f, encode_endgroup, &attr2);
  7405. upb_handlerattr_uninit(&attr2);
  7406. break;
  7407. }
  7408. }
  7409. #undef T
  7410. upb_handlerattr_uninit(&attr);
  7411. }
  7412. }
  7413. /* public API *****************************************************************/
  7414. const upb_handlers *upb_pb_encoder_newhandlers(const upb_msgdef *m,
  7415. const void *owner) {
  7416. return upb_handlers_newfrozen(m, owner, newhandlers_callback, NULL);
  7417. }
  7418. #define ARRAYSIZE(x) (sizeof(x) / sizeof(x[0]))
  7419. void upb_pb_encoder_init(upb_pb_encoder *e, const upb_handlers *h) {
  7420. e->output_ = NULL;
  7421. e->subc = NULL;
  7422. e->buf = e->initbuf;
  7423. e->ptr = e->buf;
  7424. e->limit = e->buf + ARRAYSIZE(e->initbuf);
  7425. e->segbuf = e->seginitbuf;
  7426. e->seglimit = e->segbuf + ARRAYSIZE(e->seginitbuf);
  7427. e->stacklimit = e->stack + ARRAYSIZE(e->stack);
  7428. upb_sink_reset(&e->input_, h, e);
  7429. }
  7430. void upb_pb_encoder_uninit(upb_pb_encoder *e) {
  7431. if (e->buf != e->initbuf) {
  7432. free(e->buf);
  7433. }
  7434. if (e->segbuf != e->seginitbuf) {
  7435. free(e->segbuf);
  7436. }
  7437. }
  7438. void upb_pb_encoder_resetoutput(upb_pb_encoder *e, upb_bytessink *output) {
  7439. upb_pb_encoder_reset(e);
  7440. e->output_ = output;
  7441. e->subc = output->closure;
  7442. }
  7443. void upb_pb_encoder_reset(upb_pb_encoder *e) {
  7444. e->segptr = NULL;
  7445. e->top = NULL;
  7446. e->depth = 0;
  7447. }
  7448. upb_sink *upb_pb_encoder_input(upb_pb_encoder *e) { return &e->input_; }
  7449. /*
  7450. * upb - a minimalist implementation of protocol buffers.
  7451. *
  7452. * Copyright (c) 2010-2012 Google Inc. See LICENSE for details.
  7453. * Author: Josh Haberman <jhaberman@gmail.com>
  7454. */
  7455. #include <stdio.h>
  7456. #include <stdlib.h>
  7457. #include <string.h>
  7458. upb_def **upb_load_defs_from_descriptor(const char *str, size_t len, int *n,
  7459. void *owner, upb_status *status) {
  7460. // Create handlers.
  7461. const upb_handlers *reader_h = upb_descreader_newhandlers(&reader_h);
  7462. upb_pbdecodermethodopts opts;
  7463. upb_pbdecodermethodopts_init(&opts, reader_h);
  7464. const upb_pbdecodermethod *decoder_m =
  7465. upb_pbdecodermethod_new(&opts, &decoder_m);
  7466. upb_pbdecoder decoder;
  7467. upb_descreader reader;
  7468. upb_pbdecoder_init(&decoder, decoder_m, status);
  7469. upb_descreader_init(&reader, reader_h, status);
  7470. upb_pbdecoder_resetoutput(&decoder, upb_descreader_input(&reader));
  7471. // Push input data.
  7472. bool ok = upb_bufsrc_putbuf(str, len, upb_pbdecoder_input(&decoder));
  7473. upb_def **ret = NULL;
  7474. if (!ok) goto cleanup;
  7475. upb_def **defs = upb_descreader_getdefs(&reader, owner, n);
  7476. ret = malloc(sizeof(upb_def*) * (*n));
  7477. memcpy(ret, defs, sizeof(upb_def*) * (*n));
  7478. cleanup:
  7479. upb_pbdecoder_uninit(&decoder);
  7480. upb_descreader_uninit(&reader);
  7481. upb_handlers_unref(reader_h, &reader_h);
  7482. upb_pbdecodermethod_unref(decoder_m, &decoder_m);
  7483. return ret;
  7484. }
  7485. bool upb_load_descriptor_into_symtab(upb_symtab *s, const char *str, size_t len,
  7486. upb_status *status) {
  7487. int n;
  7488. upb_def **defs = upb_load_defs_from_descriptor(str, len, &n, &defs, status);
  7489. if (!defs) return false;
  7490. bool success = upb_symtab_add(s, defs, n, &defs, status);
  7491. free(defs);
  7492. return success;
  7493. }
  7494. char *upb_readfile(const char *filename, size_t *len) {
  7495. FILE *f = fopen(filename, "rb");
  7496. if(!f) return NULL;
  7497. if(fseek(f, 0, SEEK_END) != 0) goto error;
  7498. long size = ftell(f);
  7499. if(size < 0) goto error;
  7500. if(fseek(f, 0, SEEK_SET) != 0) goto error;
  7501. char *buf = malloc(size + 1);
  7502. if(size && fread(buf, size, 1, f) != 1) goto error;
  7503. fclose(f);
  7504. if (len) *len = size;
  7505. return buf;
  7506. error:
  7507. fclose(f);
  7508. return NULL;
  7509. }
  7510. bool upb_load_descriptor_file_into_symtab(upb_symtab *symtab, const char *fname,
  7511. upb_status *status) {
  7512. size_t len;
  7513. char *data = upb_readfile(fname, &len);
  7514. if (!data) {
  7515. if (status) upb_status_seterrf(status, "Couldn't read file: %s", fname);
  7516. return false;
  7517. }
  7518. bool success = upb_load_descriptor_into_symtab(symtab, data, len, status);
  7519. free(data);
  7520. return success;
  7521. }
  7522. /*
  7523. * upb - a minimalist implementation of protocol buffers.
  7524. *
  7525. * Copyright (c) 2009 Google Inc. See LICENSE for details.
  7526. * Author: Josh Haberman <jhaberman@gmail.com>
  7527. *
  7528. * OPT: This is not optimized at all. It uses printf() which parses the format
  7529. * string every time, and it allocates memory for every put.
  7530. */
  7531. #include <ctype.h>
  7532. #include <float.h>
  7533. #include <inttypes.h>
  7534. #include <stdio.h>
  7535. #include <stdlib.h>
  7536. #include <string.h>
  7537. #define CHECK(x) if ((x) < 0) goto err;
  7538. static const char *shortname(const char *longname) {
  7539. const char *last = strrchr(longname, '.');
  7540. return last ? last + 1 : longname;
  7541. }
  7542. static int indent(upb_textprinter *p) {
  7543. int i;
  7544. if (!p->single_line_)
  7545. for (i = 0; i < p->indent_depth_; i++)
  7546. upb_bytessink_putbuf(p->output_, p->subc, " ", 2, NULL);
  7547. return 0;
  7548. }
  7549. static int endfield(upb_textprinter *p) {
  7550. const char ch = (p->single_line_ ? ' ' : '\n');
  7551. upb_bytessink_putbuf(p->output_, p->subc, &ch, 1, NULL);
  7552. return 0;
  7553. }
  7554. static int putescaped(upb_textprinter *p, const char *buf, size_t len,
  7555. bool preserve_utf8) {
  7556. // Based on CEscapeInternal() from Google's protobuf release.
  7557. char dstbuf[4096], *dst = dstbuf, *dstend = dstbuf + sizeof(dstbuf);
  7558. const char *end = buf + len;
  7559. // I think hex is prettier and more useful, but proto2 uses octal; should
  7560. // investigate whether it can parse hex also.
  7561. const bool use_hex = false;
  7562. bool last_hex_escape = false; // true if last output char was \xNN
  7563. for (; buf < end; buf++) {
  7564. if (dstend - dst < 4) {
  7565. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  7566. dst = dstbuf;
  7567. }
  7568. bool is_hex_escape = false;
  7569. switch (*buf) {
  7570. case '\n': *(dst++) = '\\'; *(dst++) = 'n'; break;
  7571. case '\r': *(dst++) = '\\'; *(dst++) = 'r'; break;
  7572. case '\t': *(dst++) = '\\'; *(dst++) = 't'; break;
  7573. case '\"': *(dst++) = '\\'; *(dst++) = '\"'; break;
  7574. case '\'': *(dst++) = '\\'; *(dst++) = '\''; break;
  7575. case '\\': *(dst++) = '\\'; *(dst++) = '\\'; break;
  7576. default:
  7577. // Note that if we emit \xNN and the buf character after that is a hex
  7578. // digit then that digit must be escaped too to prevent it being
  7579. // interpreted as part of the character code by C.
  7580. if ((!preserve_utf8 || (uint8_t)*buf < 0x80) &&
  7581. (!isprint(*buf) || (last_hex_escape && isxdigit(*buf)))) {
  7582. sprintf(dst, (use_hex ? "\\x%02x" : "\\%03o"), (uint8_t)*buf);
  7583. is_hex_escape = use_hex;
  7584. dst += 4;
  7585. } else {
  7586. *(dst++) = *buf; break;
  7587. }
  7588. }
  7589. last_hex_escape = is_hex_escape;
  7590. }
  7591. // Flush remaining data.
  7592. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  7593. return 0;
  7594. }
  7595. bool putf(upb_textprinter *p, const char *fmt, ...) {
  7596. va_list args;
  7597. va_start(args, fmt);
  7598. // Run once to get the length of the string.
  7599. va_list args_copy;
  7600. va_copy(args_copy, args);
  7601. int len = vsnprintf(NULL, 0, fmt, args_copy);
  7602. va_end(args_copy);
  7603. // + 1 for NULL terminator (vsnprintf() requires it even if we don't).
  7604. char *str = malloc(len + 1);
  7605. if (!str) return false;
  7606. int written = vsnprintf(str, len + 1, fmt, args);
  7607. va_end(args);
  7608. UPB_ASSERT_VAR(written, written == len);
  7609. bool ok = upb_bytessink_putbuf(p->output_, p->subc, str, len, NULL);
  7610. free(str);
  7611. return ok;
  7612. }
  7613. /* handlers *******************************************************************/
  7614. static bool textprinter_startmsg(void *c, const void *hd) {
  7615. UPB_UNUSED(hd);
  7616. upb_textprinter *p = c;
  7617. if (p->indent_depth_ == 0) {
  7618. upb_bytessink_start(p->output_, 0, &p->subc);
  7619. }
  7620. return true;
  7621. }
  7622. static bool textprinter_endmsg(void *c, const void *hd, upb_status *s) {
  7623. UPB_UNUSED(hd);
  7624. UPB_UNUSED(s);
  7625. upb_textprinter *p = c;
  7626. if (p->indent_depth_ == 0) {
  7627. upb_bytessink_end(p->output_);
  7628. }
  7629. return true;
  7630. }
  7631. #define TYPE(name, ctype, fmt) \
  7632. static bool textprinter_put ## name(void *closure, const void *handler_data, \
  7633. ctype val) { \
  7634. upb_textprinter *p = closure; \
  7635. const upb_fielddef *f = handler_data; \
  7636. CHECK(indent(p)); \
  7637. putf(p, "%s: " fmt, upb_fielddef_name(f), val); \
  7638. CHECK(endfield(p)); \
  7639. return true; \
  7640. err: \
  7641. return false; \
  7642. }
  7643. static bool textprinter_putbool(void *closure, const void *handler_data,
  7644. bool val) {
  7645. upb_textprinter *p = closure;
  7646. const upb_fielddef *f = handler_data;
  7647. CHECK(indent(p));
  7648. putf(p, "%s: %s", upb_fielddef_name(f), val ? "true" : "false");
  7649. CHECK(endfield(p));
  7650. return true;
  7651. err:
  7652. return false;
  7653. }
  7654. #define STRINGIFY_HELPER(x) #x
  7655. #define STRINGIFY_MACROVAL(x) STRINGIFY_HELPER(x)
  7656. TYPE(int32, int32_t, "%" PRId32)
  7657. TYPE(int64, int64_t, "%" PRId64)
  7658. TYPE(uint32, uint32_t, "%" PRIu32);
  7659. TYPE(uint64, uint64_t, "%" PRIu64)
  7660. TYPE(float, float, "%." STRINGIFY_MACROVAL(FLT_DIG) "g")
  7661. TYPE(double, double, "%." STRINGIFY_MACROVAL(DBL_DIG) "g")
  7662. #undef TYPE
  7663. // Output a symbolic value from the enum if found, else just print as int32.
  7664. static bool textprinter_putenum(void *closure, const void *handler_data,
  7665. int32_t val) {
  7666. upb_textprinter *p = closure;
  7667. const upb_fielddef *f = handler_data;
  7668. const upb_enumdef *enum_def = upb_downcast_enumdef(upb_fielddef_subdef(f));
  7669. const char *label = upb_enumdef_iton(enum_def, val);
  7670. if (label) {
  7671. indent(p);
  7672. putf(p, "%s: %s", upb_fielddef_name(f), label);
  7673. endfield(p);
  7674. } else {
  7675. if (!textprinter_putint32(closure, handler_data, val))
  7676. return false;
  7677. }
  7678. return true;
  7679. }
  7680. static void *textprinter_startstr(void *closure, const void *handler_data,
  7681. size_t size_hint) {
  7682. const upb_fielddef *f = handler_data;
  7683. UPB_UNUSED(size_hint);
  7684. upb_textprinter *p = closure;
  7685. indent(p);
  7686. putf(p, "%s: \"", upb_fielddef_name(f));
  7687. return p;
  7688. }
  7689. static bool textprinter_endstr(void *closure, const void *handler_data) {
  7690. UPB_UNUSED(handler_data);
  7691. upb_textprinter *p = closure;
  7692. putf(p, "\"");
  7693. endfield(p);
  7694. return true;
  7695. }
  7696. static size_t textprinter_putstr(void *closure, const void *hd, const char *buf,
  7697. size_t len, const upb_bufhandle *handle) {
  7698. UPB_UNUSED(handle);
  7699. upb_textprinter *p = closure;
  7700. const upb_fielddef *f = hd;
  7701. CHECK(putescaped(p, buf, len, upb_fielddef_type(f) == UPB_TYPE_STRING));
  7702. return len;
  7703. err:
  7704. return 0;
  7705. }
  7706. static void *textprinter_startsubmsg(void *closure, const void *handler_data) {
  7707. upb_textprinter *p = closure;
  7708. const char *name = handler_data;
  7709. CHECK(indent(p));
  7710. putf(p, "%s {%c", name, p->single_line_ ? ' ' : '\n');
  7711. p->indent_depth_++;
  7712. return p;
  7713. err:
  7714. return UPB_BREAK;
  7715. }
  7716. static bool textprinter_endsubmsg(void *closure, const void *handler_data) {
  7717. UPB_UNUSED(handler_data);
  7718. upb_textprinter *p = closure;
  7719. p->indent_depth_--;
  7720. CHECK(indent(p));
  7721. upb_bytessink_putbuf(p->output_, p->subc, "}", 1, NULL);
  7722. CHECK(endfield(p));
  7723. return true;
  7724. err:
  7725. return false;
  7726. }
  7727. /* Public API *****************************************************************/
  7728. void upb_textprinter_init(upb_textprinter *p, const upb_handlers *h) {
  7729. p->single_line_ = false;
  7730. p->indent_depth_ = 0;
  7731. upb_sink_reset(&p->input_, h, p);
  7732. }
  7733. void upb_textprinter_uninit(upb_textprinter *p) {
  7734. UPB_UNUSED(p);
  7735. }
  7736. void upb_textprinter_reset(upb_textprinter *p, bool single_line) {
  7737. p->single_line_ = single_line;
  7738. p->indent_depth_ = 0;
  7739. }
  7740. static void onmreg(const void *c, upb_handlers *h) {
  7741. UPB_UNUSED(c);
  7742. const upb_msgdef *m = upb_handlers_msgdef(h);
  7743. upb_handlers_setstartmsg(h, textprinter_startmsg, NULL);
  7744. upb_handlers_setendmsg(h, textprinter_endmsg, NULL);
  7745. upb_msg_field_iter i;
  7746. for(upb_msg_field_begin(&i, m);
  7747. !upb_msg_field_done(&i);
  7748. upb_msg_field_next(&i)) {
  7749. upb_fielddef *f = upb_msg_iter_field(&i);
  7750. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  7751. upb_handlerattr_sethandlerdata(&attr, f);
  7752. switch (upb_fielddef_type(f)) {
  7753. case UPB_TYPE_INT32:
  7754. upb_handlers_setint32(h, f, textprinter_putint32, &attr);
  7755. break;
  7756. case UPB_TYPE_INT64:
  7757. upb_handlers_setint64(h, f, textprinter_putint64, &attr);
  7758. break;
  7759. case UPB_TYPE_UINT32:
  7760. upb_handlers_setuint32(h, f, textprinter_putuint32, &attr);
  7761. break;
  7762. case UPB_TYPE_UINT64:
  7763. upb_handlers_setuint64(h, f, textprinter_putuint64, &attr);
  7764. break;
  7765. case UPB_TYPE_FLOAT:
  7766. upb_handlers_setfloat(h, f, textprinter_putfloat, &attr);
  7767. break;
  7768. case UPB_TYPE_DOUBLE:
  7769. upb_handlers_setdouble(h, f, textprinter_putdouble, &attr);
  7770. break;
  7771. case UPB_TYPE_BOOL:
  7772. upb_handlers_setbool(h, f, textprinter_putbool, &attr);
  7773. break;
  7774. case UPB_TYPE_STRING:
  7775. case UPB_TYPE_BYTES:
  7776. upb_handlers_setstartstr(h, f, textprinter_startstr, &attr);
  7777. upb_handlers_setstring(h, f, textprinter_putstr, &attr);
  7778. upb_handlers_setendstr(h, f, textprinter_endstr, &attr);
  7779. break;
  7780. case UPB_TYPE_MESSAGE: {
  7781. const char *name =
  7782. upb_fielddef_istagdelim(f)
  7783. ? shortname(upb_msgdef_fullname(upb_fielddef_msgsubdef(f)))
  7784. : upb_fielddef_name(f);
  7785. upb_handlerattr_sethandlerdata(&attr, name);
  7786. upb_handlers_setstartsubmsg(h, f, textprinter_startsubmsg, &attr);
  7787. upb_handlers_setendsubmsg(h, f, textprinter_endsubmsg, &attr);
  7788. break;
  7789. }
  7790. case UPB_TYPE_ENUM:
  7791. upb_handlers_setint32(h, f, textprinter_putenum, &attr);
  7792. break;
  7793. }
  7794. }
  7795. }
  7796. const upb_handlers *upb_textprinter_newhandlers(const upb_msgdef *m,
  7797. const void *owner) {
  7798. return upb_handlers_newfrozen(m, owner, &onmreg, NULL);
  7799. }
  7800. upb_sink *upb_textprinter_input(upb_textprinter *p) { return &p->input_; }
  7801. bool upb_textprinter_resetoutput(upb_textprinter *p, upb_bytessink *output) {
  7802. p->output_ = output;
  7803. return true;
  7804. }
  7805. void upb_textprinter_setsingleline(upb_textprinter *p, bool single_line) {
  7806. p->single_line_ = single_line;
  7807. }
  7808. /*
  7809. * upb - a minimalist implementation of protocol buffers.
  7810. *
  7811. * Copyright (c) 2011 Google Inc. See LICENSE for details.
  7812. * Author: Josh Haberman <jhaberman@gmail.com>
  7813. */
  7814. // Index is descriptor type.
  7815. const uint8_t upb_pb_native_wire_types[] = {
  7816. UPB_WIRE_TYPE_END_GROUP, // ENDGROUP
  7817. UPB_WIRE_TYPE_64BIT, // DOUBLE
  7818. UPB_WIRE_TYPE_32BIT, // FLOAT
  7819. UPB_WIRE_TYPE_VARINT, // INT64
  7820. UPB_WIRE_TYPE_VARINT, // UINT64
  7821. UPB_WIRE_TYPE_VARINT, // INT32
  7822. UPB_WIRE_TYPE_64BIT, // FIXED64
  7823. UPB_WIRE_TYPE_32BIT, // FIXED32
  7824. UPB_WIRE_TYPE_VARINT, // BOOL
  7825. UPB_WIRE_TYPE_DELIMITED, // STRING
  7826. UPB_WIRE_TYPE_START_GROUP, // GROUP
  7827. UPB_WIRE_TYPE_DELIMITED, // MESSAGE
  7828. UPB_WIRE_TYPE_DELIMITED, // BYTES
  7829. UPB_WIRE_TYPE_VARINT, // UINT32
  7830. UPB_WIRE_TYPE_VARINT, // ENUM
  7831. UPB_WIRE_TYPE_32BIT, // SFIXED32
  7832. UPB_WIRE_TYPE_64BIT, // SFIXED64
  7833. UPB_WIRE_TYPE_VARINT, // SINT32
  7834. UPB_WIRE_TYPE_VARINT, // SINT64
  7835. };
  7836. // A basic branch-based decoder, uses 32-bit values to get good performance
  7837. // on 32-bit architectures (but performs well on 64-bits also).
  7838. // This scheme comes from the original Google Protobuf implementation (proto2).
  7839. upb_decoderet upb_vdecode_max8_branch32(upb_decoderet r) {
  7840. upb_decoderet err = {NULL, 0};
  7841. const char *p = r.p;
  7842. uint32_t low = (uint32_t)r.val;
  7843. uint32_t high = 0;
  7844. uint32_t b;
  7845. b = *(p++); low |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  7846. b = *(p++); low |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  7847. b = *(p++); low |= (b & 0x7fU) << 28;
  7848. high = (b & 0x7fU) >> 4; if (!(b & 0x80)) goto done;
  7849. b = *(p++); high |= (b & 0x7fU) << 3; if (!(b & 0x80)) goto done;
  7850. b = *(p++); high |= (b & 0x7fU) << 10; if (!(b & 0x80)) goto done;
  7851. b = *(p++); high |= (b & 0x7fU) << 17; if (!(b & 0x80)) goto done;
  7852. b = *(p++); high |= (b & 0x7fU) << 24; if (!(b & 0x80)) goto done;
  7853. b = *(p++); high |= (b & 0x7fU) << 31; if (!(b & 0x80)) goto done;
  7854. return err;
  7855. done:
  7856. r.val = ((uint64_t)high << 32) | low;
  7857. r.p = p;
  7858. return r;
  7859. }
  7860. // Like the previous, but uses 64-bit values.
  7861. upb_decoderet upb_vdecode_max8_branch64(upb_decoderet r) {
  7862. const char *p = r.p;
  7863. uint64_t val = r.val;
  7864. uint64_t b;
  7865. upb_decoderet err = {NULL, 0};
  7866. b = *(p++); val |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  7867. b = *(p++); val |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  7868. b = *(p++); val |= (b & 0x7fU) << 28; if (!(b & 0x80)) goto done;
  7869. b = *(p++); val |= (b & 0x7fU) << 35; if (!(b & 0x80)) goto done;
  7870. b = *(p++); val |= (b & 0x7fU) << 42; if (!(b & 0x80)) goto done;
  7871. b = *(p++); val |= (b & 0x7fU) << 49; if (!(b & 0x80)) goto done;
  7872. b = *(p++); val |= (b & 0x7fU) << 56; if (!(b & 0x80)) goto done;
  7873. b = *(p++); val |= (b & 0x7fU) << 63; if (!(b & 0x80)) goto done;
  7874. return err;
  7875. done:
  7876. r.val = val;
  7877. r.p = p;
  7878. return r;
  7879. }
  7880. // Given an encoded varint v, returns an integer with a single bit set that
  7881. // indicates the end of the varint. Subtracting one from this value will
  7882. // yield a mask that leaves only bits that are part of the varint. Returns
  7883. // 0 if the varint is unterminated.
  7884. static uint64_t upb_get_vstopbit(uint64_t v) {
  7885. uint64_t cbits = v | 0x7f7f7f7f7f7f7f7fULL;
  7886. return ~cbits & (cbits+1);
  7887. }
  7888. // A branchless decoder. Credit to Pascal Massimino for the bit-twiddling.
  7889. upb_decoderet upb_vdecode_max8_massimino(upb_decoderet r) {
  7890. uint64_t b;
  7891. memcpy(&b, r.p, sizeof(b));
  7892. uint64_t stop_bit = upb_get_vstopbit(b);
  7893. b = (b & 0x7f7f7f7f7f7f7f7fULL) & (stop_bit - 1);
  7894. b += b & 0x007f007f007f007fULL;
  7895. b += 3 * (b & 0x0000ffff0000ffffULL);
  7896. b += 15 * (b & 0x00000000ffffffffULL);
  7897. if (stop_bit == 0) {
  7898. // Error: unterminated varint.
  7899. upb_decoderet err_r = {(void*)0, 0};
  7900. return err_r;
  7901. }
  7902. upb_decoderet my_r = {r.p + ((__builtin_ctzll(stop_bit) + 1) / 8),
  7903. r.val | (b << 7)};
  7904. return my_r;
  7905. }
  7906. // A branchless decoder. Credit to Daniel Wright for the bit-twiddling.
  7907. upb_decoderet upb_vdecode_max8_wright(upb_decoderet r) {
  7908. uint64_t b;
  7909. memcpy(&b, r.p, sizeof(b));
  7910. uint64_t stop_bit = upb_get_vstopbit(b);
  7911. b &= (stop_bit - 1);
  7912. b = ((b & 0x7f007f007f007f00ULL) >> 1) | (b & 0x007f007f007f007fULL);
  7913. b = ((b & 0xffff0000ffff0000ULL) >> 2) | (b & 0x0000ffff0000ffffULL);
  7914. b = ((b & 0xffffffff00000000ULL) >> 4) | (b & 0x00000000ffffffffULL);
  7915. if (stop_bit == 0) {
  7916. // Error: unterminated varint.
  7917. upb_decoderet err_r = {(void*)0, 0};
  7918. return err_r;
  7919. }
  7920. upb_decoderet my_r = {r.p + ((__builtin_ctzll(stop_bit) + 1) / 8),
  7921. r.val | (b << 14)};
  7922. return my_r;
  7923. }
  7924. #line 1 "upb/json/parser.rl"
  7925. /*
  7926. * upb - a minimalist implementation of protocol buffers.
  7927. *
  7928. * Copyright (c) 2014 Google Inc. See LICENSE for details.
  7929. * Author: Josh Haberman <jhaberman@gmail.com>
  7930. *
  7931. * A parser that uses the Ragel State Machine Compiler to generate
  7932. * the finite automata.
  7933. *
  7934. * Ragel only natively handles regular languages, but we can manually
  7935. * program it a bit to handle context-free languages like JSON, by using
  7936. * the "fcall" and "fret" constructs.
  7937. *
  7938. * This parser can handle the basics, but needs several things to be fleshed
  7939. * out:
  7940. *
  7941. * - handling of unicode escape sequences (including high surrogate pairs).
  7942. * - properly check and report errors for unknown fields, stack overflow,
  7943. * improper array nesting (or lack of nesting).
  7944. * - handling of base64 sequences with padding characters.
  7945. * - handling of push-back (non-success returns from sink functions).
  7946. * - handling of keys/escape-sequences/etc that span input buffers.
  7947. */
  7948. #include <stdio.h>
  7949. #include <stdint.h>
  7950. #include <assert.h>
  7951. #include <string.h>
  7952. #include <stdlib.h>
  7953. #include <errno.h>
  7954. #define PARSER_CHECK_RETURN(x) if (!(x)) return false
  7955. // Used to signal that a capture has been suspended.
  7956. static char suspend_capture;
  7957. static upb_selector_t getsel_for_handlertype(upb_json_parser *p,
  7958. upb_handlertype_t type) {
  7959. upb_selector_t sel;
  7960. bool ok = upb_handlers_getselector(p->top->f, type, &sel);
  7961. UPB_ASSERT_VAR(ok, ok);
  7962. return sel;
  7963. }
  7964. static upb_selector_t parser_getsel(upb_json_parser *p) {
  7965. return getsel_for_handlertype(
  7966. p, upb_handlers_getprimitivehandlertype(p->top->f));
  7967. }
  7968. static bool check_stack(upb_json_parser *p) {
  7969. if ((p->top + 1) == p->limit) {
  7970. upb_status_seterrmsg(p->status, "Nesting too deep");
  7971. return false;
  7972. }
  7973. return true;
  7974. }
  7975. // There are GCC/Clang built-ins for overflow checking which we could start
  7976. // using if there was any performance benefit to it.
  7977. static bool checked_add(size_t a, size_t b, size_t *c) {
  7978. if (SIZE_MAX - a < b) return false;
  7979. *c = a + b;
  7980. return true;
  7981. }
  7982. static size_t saturating_multiply(size_t a, size_t b) {
  7983. // size_t is unsigned, so this is defined behavior even on overflow.
  7984. size_t ret = a * b;
  7985. if (b != 0 && ret / b != a) {
  7986. ret = SIZE_MAX;
  7987. }
  7988. return ret;
  7989. }
  7990. /* Base64 decoding ************************************************************/
  7991. // TODO(haberman): make this streaming.
  7992. static const signed char b64table[] = {
  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, 62/*+*/, -1, -1, -1, 63/*/ */,
  7999. 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
  8000. 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1,
  8001. -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
  8002. 07/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
  8003. 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
  8004. 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, -1,
  8005. -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
  8006. 33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
  8007. 41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
  8008. 49/*x*/, 50/*y*/, 51/*z*/, -1, -1, -1, -1, -1,
  8009. -1, -1, -1, -1, -1, -1, -1, -1,
  8010. -1, -1, -1, -1, -1, -1, -1, -1,
  8011. -1, -1, -1, -1, -1, -1, -1, -1,
  8012. -1, -1, -1, -1, -1, -1, -1, -1,
  8013. -1, -1, -1, -1, -1, -1, -1, -1,
  8014. -1, -1, -1, -1, -1, -1, -1, -1,
  8015. -1, -1, -1, -1, -1, -1, -1, -1,
  8016. -1, -1, -1, -1, -1, -1, -1, -1,
  8017. -1, -1, -1, -1, -1, -1, -1, -1,
  8018. -1, -1, -1, -1, -1, -1, -1, -1,
  8019. -1, -1, -1, -1, -1, -1, -1, -1,
  8020. -1, -1, -1, -1, -1, -1, -1, -1,
  8021. -1, -1, -1, -1, -1, -1, -1, -1,
  8022. -1, -1, -1, -1, -1, -1, -1, -1,
  8023. -1, -1, -1, -1, -1, -1, -1, -1,
  8024. -1, -1, -1, -1, -1, -1, -1, -1
  8025. };
  8026. // Returns the table value sign-extended to 32 bits. Knowing that the upper
  8027. // bits will be 1 for unrecognized characters makes it easier to check for
  8028. // this error condition later (see below).
  8029. int32_t b64lookup(unsigned char ch) { return b64table[ch]; }
  8030. // Returns true if the given character is not a valid base64 character or
  8031. // padding.
  8032. bool nonbase64(unsigned char ch) { return b64lookup(ch) == -1 && ch != '='; }
  8033. static bool base64_push(upb_json_parser *p, upb_selector_t sel, const char *ptr,
  8034. size_t len) {
  8035. const char *limit = ptr + len;
  8036. for (; ptr < limit; ptr += 4) {
  8037. if (limit - ptr < 4) {
  8038. upb_status_seterrf(p->status,
  8039. "Base64 input for bytes field not a multiple of 4: %s",
  8040. upb_fielddef_name(p->top->f));
  8041. return false;
  8042. }
  8043. uint32_t val = b64lookup(ptr[0]) << 18 |
  8044. b64lookup(ptr[1]) << 12 |
  8045. b64lookup(ptr[2]) << 6 |
  8046. b64lookup(ptr[3]);
  8047. // Test the upper bit; returns true if any of the characters returned -1.
  8048. if (val & 0x80000000) {
  8049. goto otherchar;
  8050. }
  8051. char output[3];
  8052. output[0] = val >> 16;
  8053. output[1] = (val >> 8) & 0xff;
  8054. output[2] = val & 0xff;
  8055. upb_sink_putstring(&p->top->sink, sel, output, 3, NULL);
  8056. }
  8057. return true;
  8058. otherchar:
  8059. if (nonbase64(ptr[0]) || nonbase64(ptr[1]) || nonbase64(ptr[2]) ||
  8060. nonbase64(ptr[3]) ) {
  8061. upb_status_seterrf(p->status,
  8062. "Non-base64 characters in bytes field: %s",
  8063. upb_fielddef_name(p->top->f));
  8064. return false;
  8065. } if (ptr[2] == '=') {
  8066. // Last group contains only two input bytes, one output byte.
  8067. if (ptr[0] == '=' || ptr[1] == '=' || ptr[3] != '=') {
  8068. goto badpadding;
  8069. }
  8070. uint32_t val = b64lookup(ptr[0]) << 18 |
  8071. b64lookup(ptr[1]) << 12;
  8072. assert(!(val & 0x80000000));
  8073. char output = val >> 16;
  8074. upb_sink_putstring(&p->top->sink, sel, &output, 1, NULL);
  8075. return true;
  8076. } else {
  8077. // Last group contains only three input bytes, two output bytes.
  8078. if (ptr[0] == '=' || ptr[1] == '=' || ptr[2] == '=') {
  8079. goto badpadding;
  8080. }
  8081. uint32_t val = b64lookup(ptr[0]) << 18 |
  8082. b64lookup(ptr[1]) << 12 |
  8083. b64lookup(ptr[2]) << 6;
  8084. char output[2];
  8085. output[0] = val >> 16;
  8086. output[1] = (val >> 8) & 0xff;
  8087. upb_sink_putstring(&p->top->sink, sel, output, 2, NULL);
  8088. return true;
  8089. }
  8090. badpadding:
  8091. upb_status_seterrf(p->status,
  8092. "Incorrect base64 padding for field: %s (%.*s)",
  8093. upb_fielddef_name(p->top->f),
  8094. 4, ptr);
  8095. return false;
  8096. }
  8097. /* Accumulate buffer **********************************************************/
  8098. // Functionality for accumulating a buffer.
  8099. //
  8100. // Some parts of the parser need an entire value as a contiguous string. For
  8101. // example, to look up a member name in a hash table, or to turn a string into
  8102. // a number, the relevant library routines need the input string to be in
  8103. // contiguous memory, even if the value spanned two or more buffers in the
  8104. // input. These routines handle that.
  8105. //
  8106. // In the common case we can just point to the input buffer to get this
  8107. // contiguous string and avoid any actual copy. So we optimistically begin
  8108. // this way. But there are a few cases where we must instead copy into a
  8109. // separate buffer:
  8110. //
  8111. // 1. The string was not contiguous in the input (it spanned buffers).
  8112. //
  8113. // 2. The string included escape sequences that need to be interpreted to get
  8114. // the true value in a contiguous buffer.
  8115. static void assert_accumulate_empty(upb_json_parser *p) {
  8116. UPB_UNUSED(p);
  8117. assert(p->accumulated == NULL);
  8118. assert(p->accumulated_len == 0);
  8119. }
  8120. static void accumulate_clear(upb_json_parser *p) {
  8121. p->accumulated = NULL;
  8122. p->accumulated_len = 0;
  8123. }
  8124. // Used internally by accumulate_append().
  8125. static bool accumulate_realloc(upb_json_parser *p, size_t need) {
  8126. size_t new_size = UPB_MAX(p->accumulate_buf_size, 128);
  8127. while (new_size < need) {
  8128. new_size = saturating_multiply(new_size, 2);
  8129. }
  8130. void *mem = realloc(p->accumulate_buf, new_size);
  8131. if (!mem) {
  8132. upb_status_seterrmsg(p->status, "Out of memory allocating buffer.");
  8133. return false;
  8134. }
  8135. p->accumulate_buf = mem;
  8136. p->accumulate_buf_size = new_size;
  8137. return true;
  8138. }
  8139. // Logically appends the given data to the append buffer.
  8140. // If "can_alias" is true, we will try to avoid actually copying, but the buffer
  8141. // must be valid until the next accumulate_append() call (if any).
  8142. static bool accumulate_append(upb_json_parser *p, const char *buf, size_t len,
  8143. bool can_alias) {
  8144. if (!p->accumulated && can_alias) {
  8145. p->accumulated = buf;
  8146. p->accumulated_len = len;
  8147. return true;
  8148. }
  8149. size_t need;
  8150. if (!checked_add(p->accumulated_len, len, &need)) {
  8151. upb_status_seterrmsg(p->status, "Integer overflow.");
  8152. return false;
  8153. }
  8154. if (need > p->accumulate_buf_size && !accumulate_realloc(p, need)) {
  8155. return false;
  8156. }
  8157. if (p->accumulated != p->accumulate_buf) {
  8158. memcpy(p->accumulate_buf, p->accumulated, p->accumulated_len);
  8159. p->accumulated = p->accumulate_buf;
  8160. }
  8161. memcpy(p->accumulate_buf + p->accumulated_len, buf, len);
  8162. p->accumulated_len += len;
  8163. return true;
  8164. }
  8165. // Returns a pointer to the data accumulated since the last accumulate_clear()
  8166. // call, and writes the length to *len. This with point either to the input
  8167. // buffer or a temporary accumulate buffer.
  8168. static const char *accumulate_getptr(upb_json_parser *p, size_t *len) {
  8169. assert(p->accumulated);
  8170. *len = p->accumulated_len;
  8171. return p->accumulated;
  8172. }
  8173. /* Mult-part text data ********************************************************/
  8174. // When we have text data in the input, it can often come in multiple segments.
  8175. // For example, there may be some raw string data followed by an escape
  8176. // sequence. The two segments are processed with different logic. Also buffer
  8177. // seams in the input can cause multiple segments.
  8178. //
  8179. // As we see segments, there are two main cases for how we want to process them:
  8180. //
  8181. // 1. we want to push the captured input directly to string handlers.
  8182. //
  8183. // 2. we need to accumulate all the parts into a contiguous buffer for further
  8184. // processing (field name lookup, string->number conversion, etc).
  8185. // This is the set of states for p->multipart_state.
  8186. enum {
  8187. // We are not currently processing multipart data.
  8188. MULTIPART_INACTIVE = 0,
  8189. // We are processing multipart data by accumulating it into a contiguous
  8190. // buffer.
  8191. MULTIPART_ACCUMULATE = 1,
  8192. // We are processing multipart data by pushing each part directly to the
  8193. // current string handlers.
  8194. MULTIPART_PUSHEAGERLY = 2
  8195. };
  8196. // Start a multi-part text value where we accumulate the data for processing at
  8197. // the end.
  8198. static void multipart_startaccum(upb_json_parser *p) {
  8199. assert_accumulate_empty(p);
  8200. assert(p->multipart_state == MULTIPART_INACTIVE);
  8201. p->multipart_state = MULTIPART_ACCUMULATE;
  8202. }
  8203. // Start a multi-part text value where we immediately push text data to a string
  8204. // value with the given selector.
  8205. static void multipart_start(upb_json_parser *p, upb_selector_t sel) {
  8206. assert_accumulate_empty(p);
  8207. assert(p->multipart_state == MULTIPART_INACTIVE);
  8208. p->multipart_state = MULTIPART_PUSHEAGERLY;
  8209. p->string_selector = sel;
  8210. }
  8211. static bool multipart_text(upb_json_parser *p, const char *buf, size_t len,
  8212. bool can_alias) {
  8213. switch (p->multipart_state) {
  8214. case MULTIPART_INACTIVE:
  8215. upb_status_seterrmsg(
  8216. p->status, "Internal error: unexpected state MULTIPART_INACTIVE");
  8217. return false;
  8218. case MULTIPART_ACCUMULATE:
  8219. if (!accumulate_append(p, buf, len, can_alias)) {
  8220. return false;
  8221. }
  8222. break;
  8223. case MULTIPART_PUSHEAGERLY: {
  8224. const upb_bufhandle *handle = can_alias ? p->handle : NULL;
  8225. upb_sink_putstring(&p->top->sink, p->string_selector, buf, len, handle);
  8226. break;
  8227. }
  8228. }
  8229. return true;
  8230. }
  8231. // Note: this invalidates the accumulate buffer! Call only after reading its
  8232. // contents.
  8233. static void multipart_end(upb_json_parser *p) {
  8234. assert(p->multipart_state != MULTIPART_INACTIVE);
  8235. p->multipart_state = MULTIPART_INACTIVE;
  8236. accumulate_clear(p);
  8237. }
  8238. /* Input capture **************************************************************/
  8239. // Functionality for capturing a region of the input as text. Gracefully
  8240. // handles the case where a buffer seam occurs in the middle of the captured
  8241. // region.
  8242. static void capture_begin(upb_json_parser *p, const char *ptr) {
  8243. assert(p->multipart_state != MULTIPART_INACTIVE);
  8244. assert(p->capture == NULL);
  8245. p->capture = ptr;
  8246. }
  8247. static bool capture_end(upb_json_parser *p, const char *ptr) {
  8248. assert(p->capture);
  8249. if (multipart_text(p, p->capture, ptr - p->capture, true)) {
  8250. p->capture = NULL;
  8251. return true;
  8252. } else {
  8253. return false;
  8254. }
  8255. }
  8256. // This is called at the end of each input buffer (ie. when we have hit a
  8257. // buffer seam). If we are in the middle of capturing the input, this
  8258. // processes the unprocessed capture region.
  8259. static void capture_suspend(upb_json_parser *p, const char **ptr) {
  8260. if (!p->capture) return;
  8261. if (multipart_text(p, p->capture, *ptr - p->capture, false)) {
  8262. // We use this as a signal that we were in the middle of capturing, and
  8263. // that capturing should resume at the beginning of the next buffer.
  8264. //
  8265. // We can't use *ptr here, because we have no guarantee that this pointer
  8266. // will be valid when we resume (if the underlying memory is freed, then
  8267. // using the pointer at all, even to compare to NULL, is likely undefined
  8268. // behavior).
  8269. p->capture = &suspend_capture;
  8270. } else {
  8271. // Need to back up the pointer to the beginning of the capture, since
  8272. // we were not able to actually preserve it.
  8273. *ptr = p->capture;
  8274. }
  8275. }
  8276. static void capture_resume(upb_json_parser *p, const char *ptr) {
  8277. if (p->capture) {
  8278. assert(p->capture == &suspend_capture);
  8279. p->capture = ptr;
  8280. }
  8281. }
  8282. /* Callbacks from the parser **************************************************/
  8283. // These are the functions called directly from the parser itself.
  8284. // We define these in the same order as their declarations in the parser.
  8285. static char escape_char(char in) {
  8286. switch (in) {
  8287. case 'r': return '\r';
  8288. case 't': return '\t';
  8289. case 'n': return '\n';
  8290. case 'f': return '\f';
  8291. case 'b': return '\b';
  8292. case '/': return '/';
  8293. case '"': return '"';
  8294. case '\\': return '\\';
  8295. default:
  8296. assert(0);
  8297. return 'x';
  8298. }
  8299. }
  8300. static bool escape(upb_json_parser *p, const char *ptr) {
  8301. char ch = escape_char(*ptr);
  8302. return multipart_text(p, &ch, 1, false);
  8303. }
  8304. static void start_hex(upb_json_parser *p) {
  8305. p->digit = 0;
  8306. }
  8307. static void hexdigit(upb_json_parser *p, const char *ptr) {
  8308. char ch = *ptr;
  8309. p->digit <<= 4;
  8310. if (ch >= '0' && ch <= '9') {
  8311. p->digit += (ch - '0');
  8312. } else if (ch >= 'a' && ch <= 'f') {
  8313. p->digit += ((ch - 'a') + 10);
  8314. } else {
  8315. assert(ch >= 'A' && ch <= 'F');
  8316. p->digit += ((ch - 'A') + 10);
  8317. }
  8318. }
  8319. static bool end_hex(upb_json_parser *p) {
  8320. uint32_t codepoint = p->digit;
  8321. // emit the codepoint as UTF-8.
  8322. char utf8[3]; // support \u0000 -- \uFFFF -- need only three bytes.
  8323. int length = 0;
  8324. if (codepoint <= 0x7F) {
  8325. utf8[0] = codepoint;
  8326. length = 1;
  8327. } else if (codepoint <= 0x07FF) {
  8328. utf8[1] = (codepoint & 0x3F) | 0x80;
  8329. codepoint >>= 6;
  8330. utf8[0] = (codepoint & 0x1F) | 0xC0;
  8331. length = 2;
  8332. } else /* codepoint <= 0xFFFF */ {
  8333. utf8[2] = (codepoint & 0x3F) | 0x80;
  8334. codepoint >>= 6;
  8335. utf8[1] = (codepoint & 0x3F) | 0x80;
  8336. codepoint >>= 6;
  8337. utf8[0] = (codepoint & 0x0F) | 0xE0;
  8338. length = 3;
  8339. }
  8340. // TODO(haberman): Handle high surrogates: if codepoint is a high surrogate
  8341. // we have to wait for the next escape to get the full code point).
  8342. return multipart_text(p, utf8, length, false);
  8343. }
  8344. static void start_text(upb_json_parser *p, const char *ptr) {
  8345. capture_begin(p, ptr);
  8346. }
  8347. static bool end_text(upb_json_parser *p, const char *ptr) {
  8348. return capture_end(p, ptr);
  8349. }
  8350. static void start_number(upb_json_parser *p, const char *ptr) {
  8351. multipart_startaccum(p);
  8352. capture_begin(p, ptr);
  8353. }
  8354. static bool parse_number(upb_json_parser *p);
  8355. static bool end_number(upb_json_parser *p, const char *ptr) {
  8356. if (!capture_end(p, ptr)) {
  8357. return false;
  8358. }
  8359. return parse_number(p);
  8360. }
  8361. static bool parse_number(upb_json_parser *p) {
  8362. // strtol() and friends unfortunately do not support specifying the length of
  8363. // the input string, so we need to force a copy into a NULL-terminated buffer.
  8364. if (!multipart_text(p, "\0", 1, false)) {
  8365. return false;
  8366. }
  8367. size_t len;
  8368. const char *buf = accumulate_getptr(p, &len);
  8369. const char *myend = buf + len - 1; // One for NULL.
  8370. char *end;
  8371. switch (upb_fielddef_type(p->top->f)) {
  8372. case UPB_TYPE_ENUM:
  8373. case UPB_TYPE_INT32: {
  8374. long val = strtol(p->accumulated, &end, 0);
  8375. if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || end != myend)
  8376. goto err;
  8377. else
  8378. upb_sink_putint32(&p->top->sink, parser_getsel(p), val);
  8379. break;
  8380. }
  8381. case UPB_TYPE_INT64: {
  8382. long long val = strtoll(p->accumulated, &end, 0);
  8383. if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || end != myend)
  8384. goto err;
  8385. else
  8386. upb_sink_putint64(&p->top->sink, parser_getsel(p), val);
  8387. break;
  8388. }
  8389. case UPB_TYPE_UINT32: {
  8390. unsigned long val = strtoul(p->accumulated, &end, 0);
  8391. if (val > UINT32_MAX || errno == ERANGE || end != myend)
  8392. goto err;
  8393. else
  8394. upb_sink_putuint32(&p->top->sink, parser_getsel(p), val);
  8395. break;
  8396. }
  8397. case UPB_TYPE_UINT64: {
  8398. unsigned long long val = strtoull(p->accumulated, &end, 0);
  8399. if (val > UINT64_MAX || errno == ERANGE || end != myend)
  8400. goto err;
  8401. else
  8402. upb_sink_putuint64(&p->top->sink, parser_getsel(p), val);
  8403. break;
  8404. }
  8405. case UPB_TYPE_DOUBLE: {
  8406. double val = strtod(p->accumulated, &end);
  8407. if (errno == ERANGE || end != myend)
  8408. goto err;
  8409. else
  8410. upb_sink_putdouble(&p->top->sink, parser_getsel(p), val);
  8411. break;
  8412. }
  8413. case UPB_TYPE_FLOAT: {
  8414. float val = strtof(p->accumulated, &end);
  8415. if (errno == ERANGE || end != myend)
  8416. goto err;
  8417. else
  8418. upb_sink_putfloat(&p->top->sink, parser_getsel(p), val);
  8419. break;
  8420. }
  8421. default:
  8422. assert(false);
  8423. }
  8424. multipart_end(p);
  8425. return true;
  8426. err:
  8427. upb_status_seterrf(p->status, "error parsing number: %s", buf);
  8428. multipart_end(p);
  8429. return false;
  8430. }
  8431. static bool parser_putbool(upb_json_parser *p, bool val) {
  8432. if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL) {
  8433. upb_status_seterrf(p->status,
  8434. "Boolean value specified for non-bool field: %s",
  8435. upb_fielddef_name(p->top->f));
  8436. return false;
  8437. }
  8438. bool ok = upb_sink_putbool(&p->top->sink, parser_getsel(p), val);
  8439. UPB_ASSERT_VAR(ok, ok);
  8440. return true;
  8441. }
  8442. static bool start_stringval(upb_json_parser *p) {
  8443. assert(p->top->f);
  8444. if (upb_fielddef_isstring(p->top->f)) {
  8445. if (!check_stack(p)) return false;
  8446. // Start a new parser frame: parser frames correspond one-to-one with
  8447. // handler frames, and string events occur in a sub-frame.
  8448. upb_jsonparser_frame *inner = p->top + 1;
  8449. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  8450. upb_sink_startstr(&p->top->sink, sel, 0, &inner->sink);
  8451. inner->m = p->top->m;
  8452. inner->f = p->top->f;
  8453. inner->is_map = false;
  8454. inner->is_mapentry = false;
  8455. p->top = inner;
  8456. if (upb_fielddef_type(p->top->f) == UPB_TYPE_STRING) {
  8457. // For STRING fields we push data directly to the handlers as it is
  8458. // parsed. We don't do this yet for BYTES fields, because our base64
  8459. // decoder is not streaming.
  8460. //
  8461. // TODO(haberman): make base64 decoding streaming also.
  8462. multipart_start(p, getsel_for_handlertype(p, UPB_HANDLER_STRING));
  8463. return true;
  8464. } else {
  8465. multipart_startaccum(p);
  8466. return true;
  8467. }
  8468. } else if (upb_fielddef_type(p->top->f) == UPB_TYPE_ENUM) {
  8469. // No need to push a frame -- symbolic enum names in quotes remain in the
  8470. // current parser frame.
  8471. //
  8472. // Enum string values must accumulate so we can look up the value in a table
  8473. // once it is complete.
  8474. multipart_startaccum(p);
  8475. return true;
  8476. } else {
  8477. upb_status_seterrf(p->status,
  8478. "String specified for non-string/non-enum field: %s",
  8479. upb_fielddef_name(p->top->f));
  8480. return false;
  8481. }
  8482. }
  8483. static bool end_stringval(upb_json_parser *p) {
  8484. bool ok = true;
  8485. switch (upb_fielddef_type(p->top->f)) {
  8486. case UPB_TYPE_BYTES:
  8487. if (!base64_push(p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  8488. p->accumulated, p->accumulated_len)) {
  8489. return false;
  8490. }
  8491. // Fall through.
  8492. case UPB_TYPE_STRING: {
  8493. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  8494. upb_sink_endstr(&p->top->sink, sel);
  8495. p->top--;
  8496. break;
  8497. }
  8498. case UPB_TYPE_ENUM: {
  8499. // Resolve enum symbolic name to integer value.
  8500. const upb_enumdef *enumdef =
  8501. (const upb_enumdef*)upb_fielddef_subdef(p->top->f);
  8502. size_t len;
  8503. const char *buf = accumulate_getptr(p, &len);
  8504. int32_t int_val = 0;
  8505. ok = upb_enumdef_ntoi(enumdef, buf, len, &int_val);
  8506. if (ok) {
  8507. upb_selector_t sel = parser_getsel(p);
  8508. upb_sink_putint32(&p->top->sink, sel, int_val);
  8509. } else {
  8510. upb_status_seterrf(p->status, "Enum value unknown: '%.*s'", len, buf);
  8511. }
  8512. break;
  8513. }
  8514. default:
  8515. assert(false);
  8516. upb_status_seterrmsg(p->status, "Internal error in JSON decoder");
  8517. ok = false;
  8518. break;
  8519. }
  8520. multipart_end(p);
  8521. return ok;
  8522. }
  8523. static void start_member(upb_json_parser *p) {
  8524. assert(!p->top->f);
  8525. multipart_startaccum(p);
  8526. }
  8527. // Helper: invoked during parse_mapentry() to emit the mapentry message's key
  8528. // field based on the current contents of the accumulate buffer.
  8529. static bool parse_mapentry_key(upb_json_parser *p) {
  8530. size_t len;
  8531. const char *buf = accumulate_getptr(p, &len);
  8532. // Emit the key field. We do a bit of ad-hoc parsing here because the
  8533. // parser state machine has already decided that this is a string field
  8534. // name, and we are reinterpreting it as some arbitrary key type. In
  8535. // particular, integer and bool keys are quoted, so we need to parse the
  8536. // quoted string contents here.
  8537. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_KEY);
  8538. if (p->top->f == NULL) {
  8539. upb_status_seterrmsg(p->status, "mapentry message has no key");
  8540. return false;
  8541. }
  8542. switch (upb_fielddef_type(p->top->f)) {
  8543. case UPB_TYPE_INT32:
  8544. case UPB_TYPE_INT64:
  8545. case UPB_TYPE_UINT32:
  8546. case UPB_TYPE_UINT64:
  8547. // Invoke end_number. The accum buffer has the number's text already.
  8548. if (!parse_number(p)) {
  8549. return false;
  8550. }
  8551. break;
  8552. case UPB_TYPE_BOOL:
  8553. if (len == 4 && !strncmp(buf, "true", 4)) {
  8554. if (!parser_putbool(p, true)) {
  8555. return false;
  8556. }
  8557. } else if (len == 5 && !strncmp(buf, "false", 5)) {
  8558. if (!parser_putbool(p, false)) {
  8559. return false;
  8560. }
  8561. } else {
  8562. upb_status_seterrmsg(p->status,
  8563. "Map bool key not 'true' or 'false'");
  8564. return false;
  8565. }
  8566. multipart_end(p);
  8567. break;
  8568. case UPB_TYPE_STRING:
  8569. case UPB_TYPE_BYTES: {
  8570. upb_sink subsink;
  8571. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  8572. upb_sink_startstr(&p->top->sink, sel, len, &subsink);
  8573. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  8574. upb_sink_putstring(&subsink, sel, buf, len, NULL);
  8575. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  8576. upb_sink_endstr(&subsink, sel);
  8577. multipart_end(p);
  8578. break;
  8579. }
  8580. default:
  8581. upb_status_seterrmsg(p->status, "Invalid field type for map key");
  8582. return false;
  8583. }
  8584. return true;
  8585. }
  8586. // Helper: emit one map entry (as a submessage in the map field sequence). This
  8587. // is invoked from end_membername(), at the end of the map entry's key string,
  8588. // with the map key in the accumulate buffer. It parses the key from that
  8589. // buffer, emits the handler calls to start the mapentry submessage (setting up
  8590. // its subframe in the process), and sets up state in the subframe so that the
  8591. // value parser (invoked next) will emit the mapentry's value field and then
  8592. // end the mapentry message.
  8593. static bool handle_mapentry(upb_json_parser *p) {
  8594. // Map entry: p->top->sink is the seq frame, so we need to start a frame
  8595. // for the mapentry itself, and then set |f| in that frame so that the map
  8596. // value field is parsed, and also set a flag to end the frame after the
  8597. // map-entry value is parsed.
  8598. if (!check_stack(p)) return false;
  8599. const upb_fielddef *mapfield = p->top->mapfield;
  8600. const upb_msgdef *mapentrymsg = upb_fielddef_msgsubdef(mapfield);
  8601. upb_jsonparser_frame *inner = p->top + 1;
  8602. p->top->f = mapfield;
  8603. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  8604. upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
  8605. inner->m = mapentrymsg;
  8606. inner->mapfield = mapfield;
  8607. inner->is_map = false;
  8608. // Don't set this to true *yet* -- we reuse parsing handlers below to push
  8609. // the key field value to the sink, and these handlers will pop the frame
  8610. // if they see is_mapentry (when invoked by the parser state machine, they
  8611. // would have just seen the map-entry value, not key).
  8612. inner->is_mapentry = false;
  8613. p->top = inner;
  8614. // send STARTMSG in submsg frame.
  8615. upb_sink_startmsg(&p->top->sink);
  8616. parse_mapentry_key(p);
  8617. // Set up the value field to receive the map-entry value.
  8618. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_VALUE);
  8619. p->top->is_mapentry = true; // set up to pop frame after value is parsed.
  8620. p->top->mapfield = mapfield;
  8621. if (p->top->f == NULL) {
  8622. upb_status_seterrmsg(p->status, "mapentry message has no value");
  8623. return false;
  8624. }
  8625. return true;
  8626. }
  8627. static bool end_membername(upb_json_parser *p) {
  8628. assert(!p->top->f);
  8629. if (p->top->is_map) {
  8630. return handle_mapentry(p);
  8631. } else {
  8632. size_t len;
  8633. const char *buf = accumulate_getptr(p, &len);
  8634. const upb_fielddef *f = upb_msgdef_ntof(p->top->m, buf, len);
  8635. if (!f) {
  8636. // TODO(haberman): Ignore unknown fields if requested/configured to do so.
  8637. upb_status_seterrf(p->status, "No such field: %.*s\n", (int)len, buf);
  8638. return false;
  8639. }
  8640. p->top->f = f;
  8641. multipart_end(p);
  8642. return true;
  8643. }
  8644. }
  8645. static void end_member(upb_json_parser *p) {
  8646. // If we just parsed a map-entry value, end that frame too.
  8647. if (p->top->is_mapentry) {
  8648. assert(p->top > p->stack);
  8649. // send ENDMSG on submsg.
  8650. upb_status s = UPB_STATUS_INIT;
  8651. upb_sink_endmsg(&p->top->sink, &s);
  8652. const upb_fielddef* mapfield = p->top->mapfield;
  8653. // send ENDSUBMSG in repeated-field-of-mapentries frame.
  8654. p->top--;
  8655. upb_selector_t sel;
  8656. bool ok = upb_handlers_getselector(mapfield,
  8657. UPB_HANDLER_ENDSUBMSG, &sel);
  8658. UPB_ASSERT_VAR(ok, ok);
  8659. upb_sink_endsubmsg(&p->top->sink, sel);
  8660. }
  8661. p->top->f = NULL;
  8662. }
  8663. static bool start_subobject(upb_json_parser *p) {
  8664. assert(p->top->f);
  8665. if (upb_fielddef_ismap(p->top->f)) {
  8666. // Beginning of a map. Start a new parser frame in a repeated-field
  8667. // context.
  8668. if (!check_stack(p)) return false;
  8669. upb_jsonparser_frame *inner = p->top + 1;
  8670. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  8671. upb_sink_startseq(&p->top->sink, sel, &inner->sink);
  8672. inner->m = upb_fielddef_msgsubdef(p->top->f);
  8673. inner->mapfield = p->top->f;
  8674. inner->f = NULL;
  8675. inner->is_map = true;
  8676. inner->is_mapentry = false;
  8677. p->top = inner;
  8678. return true;
  8679. } else if (upb_fielddef_issubmsg(p->top->f)) {
  8680. // Beginning of a subobject. Start a new parser frame in the submsg
  8681. // context.
  8682. if (!check_stack(p)) return false;
  8683. upb_jsonparser_frame *inner = p->top + 1;
  8684. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  8685. upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
  8686. inner->m = upb_fielddef_msgsubdef(p->top->f);
  8687. inner->f = NULL;
  8688. inner->is_map = false;
  8689. inner->is_mapentry = false;
  8690. p->top = inner;
  8691. return true;
  8692. } else {
  8693. upb_status_seterrf(p->status,
  8694. "Object specified for non-message/group field: %s",
  8695. upb_fielddef_name(p->top->f));
  8696. return false;
  8697. }
  8698. }
  8699. static void end_subobject(upb_json_parser *p) {
  8700. if (p->top->is_map) {
  8701. p->top--;
  8702. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  8703. upb_sink_endseq(&p->top->sink, sel);
  8704. } else {
  8705. p->top--;
  8706. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSUBMSG);
  8707. upb_sink_endsubmsg(&p->top->sink, sel);
  8708. }
  8709. }
  8710. static bool start_array(upb_json_parser *p) {
  8711. assert(p->top->f);
  8712. if (!upb_fielddef_isseq(p->top->f)) {
  8713. upb_status_seterrf(p->status,
  8714. "Array specified for non-repeated field: %s",
  8715. upb_fielddef_name(p->top->f));
  8716. return false;
  8717. }
  8718. if (!check_stack(p)) return false;
  8719. upb_jsonparser_frame *inner = p->top + 1;
  8720. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  8721. upb_sink_startseq(&p->top->sink, sel, &inner->sink);
  8722. inner->m = p->top->m;
  8723. inner->f = p->top->f;
  8724. inner->is_map = false;
  8725. inner->is_mapentry = false;
  8726. p->top = inner;
  8727. return true;
  8728. }
  8729. static void end_array(upb_json_parser *p) {
  8730. assert(p->top > p->stack);
  8731. p->top--;
  8732. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  8733. upb_sink_endseq(&p->top->sink, sel);
  8734. }
  8735. static void start_object(upb_json_parser *p) {
  8736. if (!p->top->is_map) {
  8737. upb_sink_startmsg(&p->top->sink);
  8738. }
  8739. }
  8740. static void end_object(upb_json_parser *p) {
  8741. if (!p->top->is_map) {
  8742. upb_status status;
  8743. upb_sink_endmsg(&p->top->sink, &status);
  8744. }
  8745. }
  8746. #define CHECK_RETURN_TOP(x) if (!(x)) goto error
  8747. /* The actual parser **********************************************************/
  8748. // What follows is the Ragel parser itself. The language is specified in Ragel
  8749. // and the actions call our C functions above.
  8750. //
  8751. // Ragel has an extensive set of functionality, and we use only a small part of
  8752. // it. There are many action types but we only use a few:
  8753. //
  8754. // ">" -- transition into a machine
  8755. // "%" -- transition out of a machine
  8756. // "@" -- transition into a final state of a machine.
  8757. //
  8758. // "@" transitions are tricky because a machine can transition into a final
  8759. // state repeatedly. But in some cases we know this can't happen, for example
  8760. // a string which is delimited by a final '"' can only transition into its
  8761. // final state once, when the closing '"' is seen.
  8762. #line 1085 "upb/json/parser.rl"
  8763. #line 997 "upb/json/parser.c"
  8764. static const char _json_actions[] = {
  8765. 0, 1, 0, 1, 2, 1, 3, 1,
  8766. 5, 1, 6, 1, 7, 1, 8, 1,
  8767. 10, 1, 12, 1, 13, 1, 14, 1,
  8768. 15, 1, 16, 1, 17, 1, 21, 1,
  8769. 25, 1, 27, 2, 3, 8, 2, 4,
  8770. 5, 2, 6, 2, 2, 6, 8, 2,
  8771. 11, 9, 2, 13, 15, 2, 14, 15,
  8772. 2, 18, 1, 2, 19, 27, 2, 20,
  8773. 9, 2, 22, 27, 2, 23, 27, 2,
  8774. 24, 27, 2, 26, 27, 3, 14, 11,
  8775. 9
  8776. };
  8777. static const unsigned char _json_key_offsets[] = {
  8778. 0, 0, 4, 9, 14, 15, 19, 24,
  8779. 29, 34, 38, 42, 45, 48, 50, 54,
  8780. 58, 60, 62, 67, 69, 71, 80, 86,
  8781. 92, 98, 104, 106, 115, 116, 116, 116,
  8782. 121, 126, 131, 132, 133, 134, 135, 135,
  8783. 136, 137, 138, 138, 139, 140, 141, 141,
  8784. 146, 151, 152, 156, 161, 166, 171, 175,
  8785. 175, 178, 178, 178
  8786. };
  8787. static const char _json_trans_keys[] = {
  8788. 32, 123, 9, 13, 32, 34, 125, 9,
  8789. 13, 32, 34, 125, 9, 13, 34, 32,
  8790. 58, 9, 13, 32, 93, 125, 9, 13,
  8791. 32, 44, 125, 9, 13, 32, 44, 125,
  8792. 9, 13, 32, 34, 9, 13, 45, 48,
  8793. 49, 57, 48, 49, 57, 46, 69, 101,
  8794. 48, 57, 69, 101, 48, 57, 43, 45,
  8795. 48, 57, 48, 57, 48, 57, 46, 69,
  8796. 101, 48, 57, 34, 92, 34, 92, 34,
  8797. 47, 92, 98, 102, 110, 114, 116, 117,
  8798. 48, 57, 65, 70, 97, 102, 48, 57,
  8799. 65, 70, 97, 102, 48, 57, 65, 70,
  8800. 97, 102, 48, 57, 65, 70, 97, 102,
  8801. 34, 92, 34, 45, 91, 102, 110, 116,
  8802. 123, 48, 57, 34, 32, 93, 125, 9,
  8803. 13, 32, 44, 93, 9, 13, 32, 93,
  8804. 125, 9, 13, 97, 108, 115, 101, 117,
  8805. 108, 108, 114, 117, 101, 32, 34, 125,
  8806. 9, 13, 32, 34, 125, 9, 13, 34,
  8807. 32, 58, 9, 13, 32, 93, 125, 9,
  8808. 13, 32, 44, 125, 9, 13, 32, 44,
  8809. 125, 9, 13, 32, 34, 9, 13, 32,
  8810. 9, 13, 0
  8811. };
  8812. static const char _json_single_lengths[] = {
  8813. 0, 2, 3, 3, 1, 2, 3, 3,
  8814. 3, 2, 2, 1, 3, 0, 2, 2,
  8815. 0, 0, 3, 2, 2, 9, 0, 0,
  8816. 0, 0, 2, 7, 1, 0, 0, 3,
  8817. 3, 3, 1, 1, 1, 1, 0, 1,
  8818. 1, 1, 0, 1, 1, 1, 0, 3,
  8819. 3, 1, 2, 3, 3, 3, 2, 0,
  8820. 1, 0, 0, 0
  8821. };
  8822. static const char _json_range_lengths[] = {
  8823. 0, 1, 1, 1, 0, 1, 1, 1,
  8824. 1, 1, 1, 1, 0, 1, 1, 1,
  8825. 1, 1, 1, 0, 0, 0, 3, 3,
  8826. 3, 3, 0, 1, 0, 0, 0, 1,
  8827. 1, 1, 0, 0, 0, 0, 0, 0,
  8828. 0, 0, 0, 0, 0, 0, 0, 1,
  8829. 1, 0, 1, 1, 1, 1, 1, 0,
  8830. 1, 0, 0, 0
  8831. };
  8832. static const short _json_index_offsets[] = {
  8833. 0, 0, 4, 9, 14, 16, 20, 25,
  8834. 30, 35, 39, 43, 46, 50, 52, 56,
  8835. 60, 62, 64, 69, 72, 75, 85, 89,
  8836. 93, 97, 101, 104, 113, 115, 116, 117,
  8837. 122, 127, 132, 134, 136, 138, 140, 141,
  8838. 143, 145, 147, 148, 150, 152, 154, 155,
  8839. 160, 165, 167, 171, 176, 181, 186, 190,
  8840. 191, 194, 195, 196
  8841. };
  8842. static const char _json_indicies[] = {
  8843. 0, 2, 0, 1, 3, 4, 5, 3,
  8844. 1, 6, 7, 8, 6, 1, 9, 1,
  8845. 10, 11, 10, 1, 11, 1, 1, 11,
  8846. 12, 13, 14, 15, 13, 1, 16, 17,
  8847. 8, 16, 1, 17, 7, 17, 1, 18,
  8848. 19, 20, 1, 19, 20, 1, 22, 23,
  8849. 23, 21, 24, 1, 23, 23, 24, 21,
  8850. 25, 25, 26, 1, 26, 1, 26, 21,
  8851. 22, 23, 23, 20, 21, 28, 29, 27,
  8852. 31, 32, 30, 33, 33, 33, 33, 33,
  8853. 33, 33, 33, 34, 1, 35, 35, 35,
  8854. 1, 36, 36, 36, 1, 37, 37, 37,
  8855. 1, 38, 38, 38, 1, 40, 41, 39,
  8856. 42, 43, 44, 45, 46, 47, 48, 43,
  8857. 1, 49, 1, 50, 51, 53, 54, 1,
  8858. 53, 52, 55, 56, 54, 55, 1, 56,
  8859. 1, 1, 56, 52, 57, 1, 58, 1,
  8860. 59, 1, 60, 1, 61, 62, 1, 63,
  8861. 1, 64, 1, 65, 66, 1, 67, 1,
  8862. 68, 1, 69, 70, 71, 72, 70, 1,
  8863. 73, 74, 75, 73, 1, 76, 1, 77,
  8864. 78, 77, 1, 78, 1, 1, 78, 79,
  8865. 80, 81, 82, 80, 1, 83, 84, 75,
  8866. 83, 1, 84, 74, 84, 1, 85, 86,
  8867. 86, 1, 1, 1, 1, 0
  8868. };
  8869. static const char _json_trans_targs[] = {
  8870. 1, 0, 2, 3, 4, 56, 3, 4,
  8871. 56, 5, 5, 6, 7, 8, 9, 56,
  8872. 8, 9, 11, 12, 18, 57, 13, 15,
  8873. 14, 16, 17, 20, 58, 21, 20, 58,
  8874. 21, 19, 22, 23, 24, 25, 26, 20,
  8875. 58, 21, 28, 30, 31, 34, 39, 43,
  8876. 47, 29, 59, 59, 32, 31, 29, 32,
  8877. 33, 35, 36, 37, 38, 59, 40, 41,
  8878. 42, 59, 44, 45, 46, 59, 48, 49,
  8879. 55, 48, 49, 55, 50, 50, 51, 52,
  8880. 53, 54, 55, 53, 54, 59, 56
  8881. };
  8882. static const char _json_trans_actions[] = {
  8883. 0, 0, 0, 21, 77, 53, 0, 47,
  8884. 23, 17, 0, 0, 15, 19, 19, 50,
  8885. 0, 0, 0, 0, 0, 1, 0, 0,
  8886. 0, 0, 0, 3, 13, 0, 0, 35,
  8887. 5, 11, 0, 38, 7, 7, 7, 41,
  8888. 44, 9, 62, 56, 25, 0, 0, 0,
  8889. 31, 29, 33, 59, 15, 0, 27, 0,
  8890. 0, 0, 0, 0, 0, 68, 0, 0,
  8891. 0, 71, 0, 0, 0, 65, 21, 77,
  8892. 53, 0, 47, 23, 17, 0, 0, 15,
  8893. 19, 19, 50, 0, 0, 74, 0
  8894. };
  8895. static const int json_start = 1;
  8896. static const int json_first_final = 56;
  8897. static const int json_error = 0;
  8898. static const int json_en_number_machine = 10;
  8899. static const int json_en_string_machine = 19;
  8900. static const int json_en_value_machine = 27;
  8901. static const int json_en_main = 1;
  8902. #line 1088 "upb/json/parser.rl"
  8903. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  8904. const upb_bufhandle *handle) {
  8905. UPB_UNUSED(hd);
  8906. UPB_UNUSED(handle);
  8907. upb_json_parser *parser = closure;
  8908. parser->handle = handle;
  8909. // Variables used by Ragel's generated code.
  8910. int cs = parser->current_state;
  8911. int *stack = parser->parser_stack;
  8912. int top = parser->parser_top;
  8913. const char *p = buf;
  8914. const char *pe = buf + size;
  8915. capture_resume(parser, buf);
  8916. #line 1168 "upb/json/parser.c"
  8917. {
  8918. int _klen;
  8919. unsigned int _trans;
  8920. const char *_acts;
  8921. unsigned int _nacts;
  8922. const char *_keys;
  8923. if ( p == pe )
  8924. goto _test_eof;
  8925. if ( cs == 0 )
  8926. goto _out;
  8927. _resume:
  8928. _keys = _json_trans_keys + _json_key_offsets[cs];
  8929. _trans = _json_index_offsets[cs];
  8930. _klen = _json_single_lengths[cs];
  8931. if ( _klen > 0 ) {
  8932. const char *_lower = _keys;
  8933. const char *_mid;
  8934. const char *_upper = _keys + _klen - 1;
  8935. while (1) {
  8936. if ( _upper < _lower )
  8937. break;
  8938. _mid = _lower + ((_upper-_lower) >> 1);
  8939. if ( (*p) < *_mid )
  8940. _upper = _mid - 1;
  8941. else if ( (*p) > *_mid )
  8942. _lower = _mid + 1;
  8943. else {
  8944. _trans += (unsigned int)(_mid - _keys);
  8945. goto _match;
  8946. }
  8947. }
  8948. _keys += _klen;
  8949. _trans += _klen;
  8950. }
  8951. _klen = _json_range_lengths[cs];
  8952. if ( _klen > 0 ) {
  8953. const char *_lower = _keys;
  8954. const char *_mid;
  8955. const char *_upper = _keys + (_klen<<1) - 2;
  8956. while (1) {
  8957. if ( _upper < _lower )
  8958. break;
  8959. _mid = _lower + (((_upper-_lower) >> 1) & ~1);
  8960. if ( (*p) < _mid[0] )
  8961. _upper = _mid - 2;
  8962. else if ( (*p) > _mid[1] )
  8963. _lower = _mid + 2;
  8964. else {
  8965. _trans += (unsigned int)((_mid - _keys)>>1);
  8966. goto _match;
  8967. }
  8968. }
  8969. _trans += _klen;
  8970. }
  8971. _match:
  8972. _trans = _json_indicies[_trans];
  8973. cs = _json_trans_targs[_trans];
  8974. if ( _json_trans_actions[_trans] == 0 )
  8975. goto _again;
  8976. _acts = _json_actions + _json_trans_actions[_trans];
  8977. _nacts = (unsigned int) *_acts++;
  8978. while ( _nacts-- > 0 )
  8979. {
  8980. switch ( *_acts++ )
  8981. {
  8982. case 0:
  8983. #line 1000 "upb/json/parser.rl"
  8984. { p--; {cs = stack[--top]; goto _again;} }
  8985. break;
  8986. case 1:
  8987. #line 1001 "upb/json/parser.rl"
  8988. { p--; {stack[top++] = cs; cs = 10; goto _again;} }
  8989. break;
  8990. case 2:
  8991. #line 1005 "upb/json/parser.rl"
  8992. { start_text(parser, p); }
  8993. break;
  8994. case 3:
  8995. #line 1006 "upb/json/parser.rl"
  8996. { CHECK_RETURN_TOP(end_text(parser, p)); }
  8997. break;
  8998. case 4:
  8999. #line 1012 "upb/json/parser.rl"
  9000. { start_hex(parser); }
  9001. break;
  9002. case 5:
  9003. #line 1013 "upb/json/parser.rl"
  9004. { hexdigit(parser, p); }
  9005. break;
  9006. case 6:
  9007. #line 1014 "upb/json/parser.rl"
  9008. { CHECK_RETURN_TOP(end_hex(parser)); }
  9009. break;
  9010. case 7:
  9011. #line 1020 "upb/json/parser.rl"
  9012. { CHECK_RETURN_TOP(escape(parser, p)); }
  9013. break;
  9014. case 8:
  9015. #line 1026 "upb/json/parser.rl"
  9016. { p--; {cs = stack[--top]; goto _again;} }
  9017. break;
  9018. case 9:
  9019. #line 1029 "upb/json/parser.rl"
  9020. { {stack[top++] = cs; cs = 19; goto _again;} }
  9021. break;
  9022. case 10:
  9023. #line 1031 "upb/json/parser.rl"
  9024. { p--; {stack[top++] = cs; cs = 27; goto _again;} }
  9025. break;
  9026. case 11:
  9027. #line 1036 "upb/json/parser.rl"
  9028. { start_member(parser); }
  9029. break;
  9030. case 12:
  9031. #line 1037 "upb/json/parser.rl"
  9032. { CHECK_RETURN_TOP(end_membername(parser)); }
  9033. break;
  9034. case 13:
  9035. #line 1040 "upb/json/parser.rl"
  9036. { end_member(parser); }
  9037. break;
  9038. case 14:
  9039. #line 1046 "upb/json/parser.rl"
  9040. { start_object(parser); }
  9041. break;
  9042. case 15:
  9043. #line 1049 "upb/json/parser.rl"
  9044. { end_object(parser); }
  9045. break;
  9046. case 16:
  9047. #line 1055 "upb/json/parser.rl"
  9048. { CHECK_RETURN_TOP(start_array(parser)); }
  9049. break;
  9050. case 17:
  9051. #line 1059 "upb/json/parser.rl"
  9052. { end_array(parser); }
  9053. break;
  9054. case 18:
  9055. #line 1064 "upb/json/parser.rl"
  9056. { start_number(parser, p); }
  9057. break;
  9058. case 19:
  9059. #line 1065 "upb/json/parser.rl"
  9060. { CHECK_RETURN_TOP(end_number(parser, p)); }
  9061. break;
  9062. case 20:
  9063. #line 1067 "upb/json/parser.rl"
  9064. { CHECK_RETURN_TOP(start_stringval(parser)); }
  9065. break;
  9066. case 21:
  9067. #line 1068 "upb/json/parser.rl"
  9068. { CHECK_RETURN_TOP(end_stringval(parser)); }
  9069. break;
  9070. case 22:
  9071. #line 1070 "upb/json/parser.rl"
  9072. { CHECK_RETURN_TOP(parser_putbool(parser, true)); }
  9073. break;
  9074. case 23:
  9075. #line 1072 "upb/json/parser.rl"
  9076. { CHECK_RETURN_TOP(parser_putbool(parser, false)); }
  9077. break;
  9078. case 24:
  9079. #line 1074 "upb/json/parser.rl"
  9080. { /* null value */ }
  9081. break;
  9082. case 25:
  9083. #line 1076 "upb/json/parser.rl"
  9084. { CHECK_RETURN_TOP(start_subobject(parser)); }
  9085. break;
  9086. case 26:
  9087. #line 1077 "upb/json/parser.rl"
  9088. { end_subobject(parser); }
  9089. break;
  9090. case 27:
  9091. #line 1082 "upb/json/parser.rl"
  9092. { p--; {cs = stack[--top]; goto _again;} }
  9093. break;
  9094. #line 1354 "upb/json/parser.c"
  9095. }
  9096. }
  9097. _again:
  9098. if ( cs == 0 )
  9099. goto _out;
  9100. if ( ++p != pe )
  9101. goto _resume;
  9102. _test_eof: {}
  9103. _out: {}
  9104. }
  9105. #line 1107 "upb/json/parser.rl"
  9106. if (p != pe) {
  9107. upb_status_seterrf(parser->status, "Parse error at %s\n", p);
  9108. } else {
  9109. capture_suspend(parser, &p);
  9110. }
  9111. error:
  9112. // Save parsing state back to parser.
  9113. parser->current_state = cs;
  9114. parser->parser_top = top;
  9115. return p - buf;
  9116. }
  9117. bool end(void *closure, const void *hd) {
  9118. UPB_UNUSED(closure);
  9119. UPB_UNUSED(hd);
  9120. return true;
  9121. }
  9122. /* Public API *****************************************************************/
  9123. void upb_json_parser_init(upb_json_parser *p, upb_status *status) {
  9124. p->limit = p->stack + UPB_JSON_MAX_DEPTH;
  9125. p->accumulate_buf = NULL;
  9126. p->accumulate_buf_size = 0;
  9127. upb_byteshandler_init(&p->input_handler_);
  9128. upb_byteshandler_setstring(&p->input_handler_, parse, NULL);
  9129. upb_byteshandler_setendstr(&p->input_handler_, end, NULL);
  9130. upb_bytessink_reset(&p->input_, &p->input_handler_, p);
  9131. p->status = status;
  9132. }
  9133. void upb_json_parser_uninit(upb_json_parser *p) {
  9134. upb_byteshandler_uninit(&p->input_handler_);
  9135. free(p->accumulate_buf);
  9136. }
  9137. void upb_json_parser_reset(upb_json_parser *p) {
  9138. p->top = p->stack;
  9139. p->top->f = NULL;
  9140. p->top->is_map = false;
  9141. p->top->is_mapentry = false;
  9142. int cs;
  9143. int top;
  9144. // Emit Ragel initialization of the parser.
  9145. #line 1418 "upb/json/parser.c"
  9146. {
  9147. cs = json_start;
  9148. top = 0;
  9149. }
  9150. #line 1157 "upb/json/parser.rl"
  9151. p->current_state = cs;
  9152. p->parser_top = top;
  9153. accumulate_clear(p);
  9154. p->multipart_state = MULTIPART_INACTIVE;
  9155. p->capture = NULL;
  9156. }
  9157. void upb_json_parser_resetoutput(upb_json_parser *p, upb_sink *sink) {
  9158. upb_json_parser_reset(p);
  9159. upb_sink_reset(&p->top->sink, sink->handlers, sink->closure);
  9160. p->top->m = upb_handlers_msgdef(sink->handlers);
  9161. p->accumulated = NULL;
  9162. }
  9163. upb_bytessink *upb_json_parser_input(upb_json_parser *p) {
  9164. return &p->input_;
  9165. }
  9166. /*
  9167. * upb - a minimalist implementation of protocol buffers.
  9168. *
  9169. * Copyright (c) 2014 Google Inc. See LICENSE for details.
  9170. * Author: Josh Haberman <jhaberman@gmail.com>
  9171. *
  9172. * This currently uses snprintf() to format primitives, and could be optimized
  9173. * further.
  9174. */
  9175. #include <stdlib.h>
  9176. #include <stdio.h>
  9177. #include <string.h>
  9178. #include <stdint.h>
  9179. // StringPiece; a pointer plus a length.
  9180. typedef struct {
  9181. const char *ptr;
  9182. size_t len;
  9183. } strpc;
  9184. strpc *newstrpc(upb_handlers *h, const upb_fielddef *f) {
  9185. strpc *ret = malloc(sizeof(*ret));
  9186. ret->ptr = upb_fielddef_name(f);
  9187. ret->len = strlen(ret->ptr);
  9188. upb_handlers_addcleanup(h, ret, free);
  9189. return ret;
  9190. }
  9191. // ------------ JSON string printing: values, maps, arrays --------------------
  9192. static void print_data(
  9193. upb_json_printer *p, const char *buf, unsigned int len) {
  9194. // TODO: Will need to change if we support pushback from the sink.
  9195. size_t n = upb_bytessink_putbuf(p->output_, p->subc_, buf, len, NULL);
  9196. UPB_ASSERT_VAR(n, n == len);
  9197. }
  9198. static void print_comma(upb_json_printer *p) {
  9199. if (!p->first_elem_[p->depth_]) {
  9200. print_data(p, ",", 1);
  9201. }
  9202. p->first_elem_[p->depth_] = false;
  9203. }
  9204. // Helpers that print properly formatted elements to the JSON output stream.
  9205. // Used for escaping control chars in strings.
  9206. static const char kControlCharLimit = 0x20;
  9207. static inline bool is_json_escaped(char c) {
  9208. // See RFC 4627.
  9209. unsigned char uc = (unsigned char)c;
  9210. return uc < kControlCharLimit || uc == '"' || uc == '\\';
  9211. }
  9212. static inline char* json_nice_escape(char c) {
  9213. switch (c) {
  9214. case '"': return "\\\"";
  9215. case '\\': return "\\\\";
  9216. case '\b': return "\\b";
  9217. case '\f': return "\\f";
  9218. case '\n': return "\\n";
  9219. case '\r': return "\\r";
  9220. case '\t': return "\\t";
  9221. default: return NULL;
  9222. }
  9223. }
  9224. // Write a properly escaped string chunk. The surrounding quotes are *not*
  9225. // printed; this is so that the caller has the option of emitting the string
  9226. // content in chunks.
  9227. static void putstring(upb_json_printer *p, const char *buf, unsigned int len) {
  9228. const char* unescaped_run = NULL;
  9229. for (unsigned int i = 0; i < len; i++) {
  9230. char c = buf[i];
  9231. // Handle escaping.
  9232. if (is_json_escaped(c)) {
  9233. // Use a "nice" escape, like \n, if one exists for this character.
  9234. const char* escape = json_nice_escape(c);
  9235. // If we don't have a specific 'nice' escape code, use a \uXXXX-style
  9236. // escape.
  9237. char escape_buf[8];
  9238. if (!escape) {
  9239. unsigned char byte = (unsigned char)c;
  9240. snprintf(escape_buf, sizeof(escape_buf), "\\u%04x", (int)byte);
  9241. escape = escape_buf;
  9242. }
  9243. // N.B. that we assume that the input encoding is equal to the output
  9244. // encoding (both UTF-8 for now), so for chars >= 0x20 and != \, ", we
  9245. // can simply pass the bytes through.
  9246. // If there's a current run of unescaped chars, print that run first.
  9247. if (unescaped_run) {
  9248. print_data(p, unescaped_run, &buf[i] - unescaped_run);
  9249. unescaped_run = NULL;
  9250. }
  9251. // Then print the escape code.
  9252. print_data(p, escape, strlen(escape));
  9253. } else {
  9254. // Add to the current unescaped run of characters.
  9255. if (unescaped_run == NULL) {
  9256. unescaped_run = &buf[i];
  9257. }
  9258. }
  9259. }
  9260. // If the string ended in a run of unescaped characters, print that last run.
  9261. if (unescaped_run) {
  9262. print_data(p, unescaped_run, &buf[len] - unescaped_run);
  9263. }
  9264. }
  9265. #define CHKLENGTH(x) if (!(x)) return -1;
  9266. // Helpers that format floating point values according to our custom formats.
  9267. // Right now we use %.8g and %.17g for float/double, respectively, to match
  9268. // proto2::util::JsonFormat's defaults. May want to change this later.
  9269. static size_t fmt_double(double val, char* buf, size_t length) {
  9270. size_t n = snprintf(buf, length, "%.17g", val);
  9271. CHKLENGTH(n > 0 && n < length);
  9272. return n;
  9273. }
  9274. static size_t fmt_float(float val, char* buf, size_t length) {
  9275. size_t n = snprintf(buf, length, "%.8g", val);
  9276. CHKLENGTH(n > 0 && n < length);
  9277. return n;
  9278. }
  9279. static size_t fmt_bool(bool val, char* buf, size_t length) {
  9280. size_t n = snprintf(buf, length, "%s", (val ? "true" : "false"));
  9281. CHKLENGTH(n > 0 && n < length);
  9282. return n;
  9283. }
  9284. static size_t fmt_int64(long val, char* buf, size_t length) {
  9285. size_t n = snprintf(buf, length, "%ld", val);
  9286. CHKLENGTH(n > 0 && n < length);
  9287. return n;
  9288. }
  9289. static size_t fmt_uint64(unsigned long long val, char* buf, size_t length) {
  9290. size_t n = snprintf(buf, length, "%llu", val);
  9291. CHKLENGTH(n > 0 && n < length);
  9292. return n;
  9293. }
  9294. // Print a map key given a field name. Called by scalar field handlers and by
  9295. // startseq for repeated fields.
  9296. static bool putkey(void *closure, const void *handler_data) {
  9297. upb_json_printer *p = closure;
  9298. const strpc *key = handler_data;
  9299. print_comma(p);
  9300. print_data(p, "\"", 1);
  9301. putstring(p, key->ptr, key->len);
  9302. print_data(p, "\":", 2);
  9303. return true;
  9304. }
  9305. #define CHKFMT(val) if ((val) == -1) return false;
  9306. #define CHK(val) if (!(val)) return false;
  9307. #define TYPE_HANDLERS(type, fmt_func) \
  9308. static bool put##type(void *closure, const void *handler_data, type val) { \
  9309. upb_json_printer *p = closure; \
  9310. UPB_UNUSED(handler_data); \
  9311. char data[64]; \
  9312. size_t length = fmt_func(val, data, sizeof(data)); \
  9313. CHKFMT(length); \
  9314. print_data(p, data, length); \
  9315. return true; \
  9316. } \
  9317. static bool scalar_##type(void *closure, const void *handler_data, \
  9318. type val) { \
  9319. CHK(putkey(closure, handler_data)); \
  9320. CHK(put##type(closure, handler_data, val)); \
  9321. return true; \
  9322. } \
  9323. static bool repeated_##type(void *closure, const void *handler_data, \
  9324. type val) { \
  9325. upb_json_printer *p = closure; \
  9326. print_comma(p); \
  9327. CHK(put##type(closure, handler_data, val)); \
  9328. return true; \
  9329. }
  9330. #define TYPE_HANDLERS_MAPKEY(type, fmt_func) \
  9331. static bool putmapkey_##type(void *closure, const void *handler_data, \
  9332. type val) { \
  9333. upb_json_printer *p = closure; \
  9334. print_data(p, "\"", 1); \
  9335. CHK(put##type(closure, handler_data, val)); \
  9336. print_data(p, "\":", 2); \
  9337. return true; \
  9338. }
  9339. TYPE_HANDLERS(double, fmt_double);
  9340. TYPE_HANDLERS(float, fmt_float);
  9341. TYPE_HANDLERS(bool, fmt_bool);
  9342. TYPE_HANDLERS(int32_t, fmt_int64);
  9343. TYPE_HANDLERS(uint32_t, fmt_int64);
  9344. TYPE_HANDLERS(int64_t, fmt_int64);
  9345. TYPE_HANDLERS(uint64_t, fmt_uint64);
  9346. // double and float are not allowed to be map keys.
  9347. TYPE_HANDLERS_MAPKEY(bool, fmt_bool);
  9348. TYPE_HANDLERS_MAPKEY(int32_t, fmt_int64);
  9349. TYPE_HANDLERS_MAPKEY(uint32_t, fmt_int64);
  9350. TYPE_HANDLERS_MAPKEY(int64_t, fmt_int64);
  9351. TYPE_HANDLERS_MAPKEY(uint64_t, fmt_uint64);
  9352. #undef TYPE_HANDLERS
  9353. #undef TYPE_HANDLERS_MAPKEY
  9354. typedef struct {
  9355. void *keyname;
  9356. const upb_enumdef *enumdef;
  9357. } EnumHandlerData;
  9358. static bool scalar_enum(void *closure, const void *handler_data,
  9359. int32_t val) {
  9360. const EnumHandlerData *hd = handler_data;
  9361. upb_json_printer *p = closure;
  9362. CHK(putkey(closure, hd->keyname));
  9363. const char *symbolic_name = upb_enumdef_iton(hd->enumdef, val);
  9364. if (symbolic_name) {
  9365. print_data(p, "\"", 1);
  9366. putstring(p, symbolic_name, strlen(symbolic_name));
  9367. print_data(p, "\"", 1);
  9368. } else {
  9369. putint32_t(closure, NULL, val);
  9370. }
  9371. return true;
  9372. }
  9373. static void print_enum_symbolic_name(upb_json_printer *p,
  9374. const upb_enumdef *def,
  9375. int32_t val) {
  9376. const char *symbolic_name = upb_enumdef_iton(def, val);
  9377. if (symbolic_name) {
  9378. print_data(p, "\"", 1);
  9379. putstring(p, symbolic_name, strlen(symbolic_name));
  9380. print_data(p, "\"", 1);
  9381. } else {
  9382. putint32_t(p, NULL, val);
  9383. }
  9384. }
  9385. static bool repeated_enum(void *closure, const void *handler_data,
  9386. int32_t val) {
  9387. const EnumHandlerData *hd = handler_data;
  9388. upb_json_printer *p = closure;
  9389. print_comma(p);
  9390. print_enum_symbolic_name(p, hd->enumdef, val);
  9391. return true;
  9392. }
  9393. static bool mapvalue_enum(void *closure, const void *handler_data,
  9394. int32_t val) {
  9395. const EnumHandlerData *hd = handler_data;
  9396. upb_json_printer *p = closure;
  9397. print_enum_symbolic_name(p, hd->enumdef, val);
  9398. return true;
  9399. }
  9400. static void *scalar_startsubmsg(void *closure, const void *handler_data) {
  9401. return putkey(closure, handler_data) ? closure : UPB_BREAK;
  9402. }
  9403. static void *repeated_startsubmsg(void *closure, const void *handler_data) {
  9404. UPB_UNUSED(handler_data);
  9405. upb_json_printer *p = closure;
  9406. print_comma(p);
  9407. return closure;
  9408. }
  9409. static void start_frame(upb_json_printer *p) {
  9410. p->depth_++;
  9411. p->first_elem_[p->depth_] = true;
  9412. print_data(p, "{", 1);
  9413. }
  9414. static void end_frame(upb_json_printer *p) {
  9415. print_data(p, "}", 1);
  9416. p->depth_--;
  9417. }
  9418. static bool printer_startmsg(void *closure, const void *handler_data) {
  9419. UPB_UNUSED(handler_data);
  9420. upb_json_printer *p = closure;
  9421. if (p->depth_ == 0) {
  9422. upb_bytessink_start(p->output_, 0, &p->subc_);
  9423. }
  9424. start_frame(p);
  9425. return true;
  9426. }
  9427. static bool printer_endmsg(void *closure, const void *handler_data, upb_status *s) {
  9428. UPB_UNUSED(handler_data);
  9429. UPB_UNUSED(s);
  9430. upb_json_printer *p = closure;
  9431. end_frame(p);
  9432. if (p->depth_ == 0) {
  9433. upb_bytessink_end(p->output_);
  9434. }
  9435. return true;
  9436. }
  9437. static void *startseq(void *closure, const void *handler_data) {
  9438. upb_json_printer *p = closure;
  9439. CHK(putkey(closure, handler_data));
  9440. p->depth_++;
  9441. p->first_elem_[p->depth_] = true;
  9442. print_data(p, "[", 1);
  9443. return closure;
  9444. }
  9445. static bool endseq(void *closure, const void *handler_data) {
  9446. UPB_UNUSED(handler_data);
  9447. upb_json_printer *p = closure;
  9448. print_data(p, "]", 1);
  9449. p->depth_--;
  9450. return true;
  9451. }
  9452. static void *startmap(void *closure, const void *handler_data) {
  9453. upb_json_printer *p = closure;
  9454. CHK(putkey(closure, handler_data));
  9455. p->depth_++;
  9456. p->first_elem_[p->depth_] = true;
  9457. print_data(p, "{", 1);
  9458. return closure;
  9459. }
  9460. static bool endmap(void *closure, const void *handler_data) {
  9461. UPB_UNUSED(handler_data);
  9462. upb_json_printer *p = closure;
  9463. print_data(p, "}", 1);
  9464. p->depth_--;
  9465. return true;
  9466. }
  9467. static size_t putstr(void *closure, const void *handler_data, const char *str,
  9468. size_t len, const upb_bufhandle *handle) {
  9469. UPB_UNUSED(handler_data);
  9470. UPB_UNUSED(handle);
  9471. upb_json_printer *p = closure;
  9472. putstring(p, str, len);
  9473. return len;
  9474. }
  9475. // This has to Base64 encode the bytes, because JSON has no "bytes" type.
  9476. static size_t putbytes(void *closure, const void *handler_data, const char *str,
  9477. size_t len, const upb_bufhandle *handle) {
  9478. UPB_UNUSED(handler_data);
  9479. UPB_UNUSED(handle);
  9480. upb_json_printer *p = closure;
  9481. // This is the regular base64, not the "web-safe" version.
  9482. static const char base64[] =
  9483. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  9484. // Base64-encode.
  9485. char data[16000];
  9486. const char *limit = data + sizeof(data);
  9487. const unsigned char *from = (const unsigned char*)str;
  9488. char *to = data;
  9489. size_t remaining = len;
  9490. while (remaining > 2) {
  9491. // TODO(haberman): handle encoded lengths > sizeof(data)
  9492. UPB_ASSERT_VAR(limit, (limit - to) >= 4);
  9493. to[0] = base64[from[0] >> 2];
  9494. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  9495. to[2] = base64[((from[1] & 0xf) << 2) | (from[2] >> 6)];
  9496. to[3] = base64[from[2] & 0x3f];
  9497. remaining -= 3;
  9498. to += 4;
  9499. from += 3;
  9500. }
  9501. switch (remaining) {
  9502. case 2:
  9503. to[0] = base64[from[0] >> 2];
  9504. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  9505. to[2] = base64[(from[1] & 0xf) << 2];
  9506. to[3] = '=';
  9507. to += 4;
  9508. from += 2;
  9509. break;
  9510. case 1:
  9511. to[0] = base64[from[0] >> 2];
  9512. to[1] = base64[((from[0] & 0x3) << 4)];
  9513. to[2] = '=';
  9514. to[3] = '=';
  9515. to += 4;
  9516. from += 1;
  9517. break;
  9518. }
  9519. size_t bytes = to - data;
  9520. print_data(p, "\"", 1);
  9521. putstring(p, data, bytes);
  9522. print_data(p, "\"", 1);
  9523. return len;
  9524. }
  9525. static void *scalar_startstr(void *closure, const void *handler_data,
  9526. size_t size_hint) {
  9527. UPB_UNUSED(handler_data);
  9528. UPB_UNUSED(size_hint);
  9529. upb_json_printer *p = closure;
  9530. CHK(putkey(closure, handler_data));
  9531. print_data(p, "\"", 1);
  9532. return p;
  9533. }
  9534. static size_t scalar_str(void *closure, const void *handler_data,
  9535. const char *str, size_t len,
  9536. const upb_bufhandle *handle) {
  9537. CHK(putstr(closure, handler_data, str, len, handle));
  9538. return len;
  9539. }
  9540. static bool scalar_endstr(void *closure, const void *handler_data) {
  9541. UPB_UNUSED(handler_data);
  9542. upb_json_printer *p = closure;
  9543. print_data(p, "\"", 1);
  9544. return true;
  9545. }
  9546. static void *repeated_startstr(void *closure, const void *handler_data,
  9547. size_t size_hint) {
  9548. UPB_UNUSED(handler_data);
  9549. UPB_UNUSED(size_hint);
  9550. upb_json_printer *p = closure;
  9551. print_comma(p);
  9552. print_data(p, "\"", 1);
  9553. return p;
  9554. }
  9555. static size_t repeated_str(void *closure, const void *handler_data,
  9556. const char *str, size_t len,
  9557. const upb_bufhandle *handle) {
  9558. CHK(putstr(closure, handler_data, str, len, handle));
  9559. return len;
  9560. }
  9561. static bool repeated_endstr(void *closure, const void *handler_data) {
  9562. UPB_UNUSED(handler_data);
  9563. upb_json_printer *p = closure;
  9564. print_data(p, "\"", 1);
  9565. return true;
  9566. }
  9567. static void *mapkeyval_startstr(void *closure, const void *handler_data,
  9568. size_t size_hint) {
  9569. UPB_UNUSED(handler_data);
  9570. UPB_UNUSED(size_hint);
  9571. upb_json_printer *p = closure;
  9572. print_data(p, "\"", 1);
  9573. return p;
  9574. }
  9575. static size_t mapkey_str(void *closure, const void *handler_data,
  9576. const char *str, size_t len,
  9577. const upb_bufhandle *handle) {
  9578. CHK(putstr(closure, handler_data, str, len, handle));
  9579. return len;
  9580. }
  9581. static bool mapkey_endstr(void *closure, const void *handler_data) {
  9582. UPB_UNUSED(handler_data);
  9583. upb_json_printer *p = closure;
  9584. print_data(p, "\":", 2);
  9585. return true;
  9586. }
  9587. static bool mapvalue_endstr(void *closure, const void *handler_data) {
  9588. UPB_UNUSED(handler_data);
  9589. upb_json_printer *p = closure;
  9590. print_data(p, "\"", 1);
  9591. return true;
  9592. }
  9593. static size_t scalar_bytes(void *closure, const void *handler_data,
  9594. const char *str, size_t len,
  9595. const upb_bufhandle *handle) {
  9596. CHK(putkey(closure, handler_data));
  9597. CHK(putbytes(closure, handler_data, str, len, handle));
  9598. return len;
  9599. }
  9600. static size_t repeated_bytes(void *closure, const void *handler_data,
  9601. const char *str, size_t len,
  9602. const upb_bufhandle *handle) {
  9603. upb_json_printer *p = closure;
  9604. print_comma(p);
  9605. CHK(putbytes(closure, handler_data, str, len, handle));
  9606. return len;
  9607. }
  9608. static size_t mapkey_bytes(void *closure, const void *handler_data,
  9609. const char *str, size_t len,
  9610. const upb_bufhandle *handle) {
  9611. upb_json_printer *p = closure;
  9612. CHK(putbytes(closure, handler_data, str, len, handle));
  9613. print_data(p, ":", 1);
  9614. return len;
  9615. }
  9616. static void set_enum_hd(upb_handlers *h,
  9617. const upb_fielddef *f,
  9618. upb_handlerattr *attr) {
  9619. EnumHandlerData *hd = malloc(sizeof(EnumHandlerData));
  9620. hd->enumdef = (const upb_enumdef *)upb_fielddef_subdef(f);
  9621. hd->keyname = newstrpc(h, f);
  9622. upb_handlers_addcleanup(h, hd, free);
  9623. upb_handlerattr_sethandlerdata(attr, hd);
  9624. }
  9625. // Set up handlers for a mapentry submessage (i.e., an individual key/value pair
  9626. // in a map).
  9627. //
  9628. // TODO: Handle missing key, missing value, out-of-order key/value, or repeated
  9629. // key or value cases properly. The right way to do this is to allocate a
  9630. // temporary structure at the start of a mapentry submessage, store key and
  9631. // value data in it as key and value handlers are called, and then print the
  9632. // key/value pair once at the end of the submessage. If we don't do this, we
  9633. // should at least detect the case and throw an error. However, so far all of
  9634. // our sources that emit mapentry messages do so canonically (with one key
  9635. // field, and then one value field), so this is not a pressing concern at the
  9636. // moment.
  9637. void printer_sethandlers_mapentry(const void *closure, upb_handlers *h) {
  9638. UPB_UNUSED(closure);
  9639. const upb_msgdef *md = upb_handlers_msgdef(h);
  9640. // A mapentry message is printed simply as '"key": value'. Rather than
  9641. // special-case key and value for every type below, we just handle both
  9642. // fields explicitly here.
  9643. const upb_fielddef* key_field = upb_msgdef_itof(md, UPB_MAPENTRY_KEY);
  9644. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_MAPENTRY_VALUE);
  9645. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  9646. switch (upb_fielddef_type(key_field)) {
  9647. case UPB_TYPE_INT32:
  9648. upb_handlers_setint32(h, key_field, putmapkey_int32_t, &empty_attr);
  9649. break;
  9650. case UPB_TYPE_INT64:
  9651. upb_handlers_setint64(h, key_field, putmapkey_int64_t, &empty_attr);
  9652. break;
  9653. case UPB_TYPE_UINT32:
  9654. upb_handlers_setuint32(h, key_field, putmapkey_uint32_t, &empty_attr);
  9655. break;
  9656. case UPB_TYPE_UINT64:
  9657. upb_handlers_setuint64(h, key_field, putmapkey_uint64_t, &empty_attr);
  9658. break;
  9659. case UPB_TYPE_BOOL:
  9660. upb_handlers_setbool(h, key_field, putmapkey_bool, &empty_attr);
  9661. break;
  9662. case UPB_TYPE_STRING:
  9663. upb_handlers_setstartstr(h, key_field, mapkeyval_startstr, &empty_attr);
  9664. upb_handlers_setstring(h, key_field, mapkey_str, &empty_attr);
  9665. upb_handlers_setendstr(h, key_field, mapkey_endstr, &empty_attr);
  9666. break;
  9667. case UPB_TYPE_BYTES:
  9668. upb_handlers_setstring(h, key_field, mapkey_bytes, &empty_attr);
  9669. break;
  9670. default:
  9671. assert(false);
  9672. break;
  9673. }
  9674. switch (upb_fielddef_type(value_field)) {
  9675. case UPB_TYPE_INT32:
  9676. upb_handlers_setint32(h, value_field, putint32_t, &empty_attr);
  9677. break;
  9678. case UPB_TYPE_INT64:
  9679. upb_handlers_setint64(h, value_field, putint64_t, &empty_attr);
  9680. break;
  9681. case UPB_TYPE_UINT32:
  9682. upb_handlers_setuint32(h, value_field, putuint32_t, &empty_attr);
  9683. break;
  9684. case UPB_TYPE_UINT64:
  9685. upb_handlers_setuint64(h, value_field, putuint64_t, &empty_attr);
  9686. break;
  9687. case UPB_TYPE_BOOL:
  9688. upb_handlers_setbool(h, value_field, putbool, &empty_attr);
  9689. break;
  9690. case UPB_TYPE_FLOAT:
  9691. upb_handlers_setfloat(h, value_field, putfloat, &empty_attr);
  9692. break;
  9693. case UPB_TYPE_DOUBLE:
  9694. upb_handlers_setdouble(h, value_field, putdouble, &empty_attr);
  9695. break;
  9696. case UPB_TYPE_STRING:
  9697. upb_handlers_setstartstr(h, value_field, mapkeyval_startstr, &empty_attr);
  9698. upb_handlers_setstring(h, value_field, putstr, &empty_attr);
  9699. upb_handlers_setendstr(h, value_field, mapvalue_endstr, &empty_attr);
  9700. break;
  9701. case UPB_TYPE_BYTES:
  9702. upb_handlers_setstring(h, value_field, putbytes, &empty_attr);
  9703. break;
  9704. case UPB_TYPE_ENUM: {
  9705. upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
  9706. set_enum_hd(h, value_field, &enum_attr);
  9707. upb_handlers_setint32(h, value_field, mapvalue_enum, &enum_attr);
  9708. upb_handlerattr_uninit(&enum_attr);
  9709. break;
  9710. }
  9711. case UPB_TYPE_MESSAGE:
  9712. // No handler necessary -- the submsg handlers will print the message
  9713. // as appropriate.
  9714. break;
  9715. }
  9716. upb_handlerattr_uninit(&empty_attr);
  9717. }
  9718. void printer_sethandlers(const void *closure, upb_handlers *h) {
  9719. UPB_UNUSED(closure);
  9720. const upb_msgdef *md = upb_handlers_msgdef(h);
  9721. bool is_mapentry = upb_msgdef_mapentry(md);
  9722. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  9723. if (is_mapentry) {
  9724. // mapentry messages are sufficiently different that we handle them
  9725. // separately.
  9726. printer_sethandlers_mapentry(closure, h);
  9727. return;
  9728. }
  9729. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  9730. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  9731. #define TYPE(type, name, ctype) \
  9732. case type: \
  9733. if (upb_fielddef_isseq(f)) { \
  9734. upb_handlers_set##name(h, f, repeated_##ctype, &empty_attr); \
  9735. } else { \
  9736. upb_handlers_set##name(h, f, scalar_##ctype, &name_attr); \
  9737. } \
  9738. break;
  9739. upb_msg_field_iter i;
  9740. upb_msg_field_begin(&i, md);
  9741. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  9742. const upb_fielddef *f = upb_msg_iter_field(&i);
  9743. upb_handlerattr name_attr = UPB_HANDLERATTR_INITIALIZER;
  9744. upb_handlerattr_sethandlerdata(&name_attr, newstrpc(h, f));
  9745. if (upb_fielddef_ismap(f)) {
  9746. upb_handlers_setstartseq(h, f, startmap, &name_attr);
  9747. upb_handlers_setendseq(h, f, endmap, &name_attr);
  9748. } else if (upb_fielddef_isseq(f)) {
  9749. upb_handlers_setstartseq(h, f, startseq, &name_attr);
  9750. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  9751. }
  9752. switch (upb_fielddef_type(f)) {
  9753. TYPE(UPB_TYPE_FLOAT, float, float);
  9754. TYPE(UPB_TYPE_DOUBLE, double, double);
  9755. TYPE(UPB_TYPE_BOOL, bool, bool);
  9756. TYPE(UPB_TYPE_INT32, int32, int32_t);
  9757. TYPE(UPB_TYPE_UINT32, uint32, uint32_t);
  9758. TYPE(UPB_TYPE_INT64, int64, int64_t);
  9759. TYPE(UPB_TYPE_UINT64, uint64, uint64_t);
  9760. case UPB_TYPE_ENUM: {
  9761. // For now, we always emit symbolic names for enums. We may want an
  9762. // option later to control this behavior, but we will wait for a real
  9763. // need first.
  9764. upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
  9765. set_enum_hd(h, f, &enum_attr);
  9766. if (upb_fielddef_isseq(f)) {
  9767. upb_handlers_setint32(h, f, repeated_enum, &enum_attr);
  9768. } else {
  9769. upb_handlers_setint32(h, f, scalar_enum, &enum_attr);
  9770. }
  9771. upb_handlerattr_uninit(&enum_attr);
  9772. break;
  9773. }
  9774. case UPB_TYPE_STRING:
  9775. if (upb_fielddef_isseq(f)) {
  9776. upb_handlers_setstartstr(h, f, repeated_startstr, &empty_attr);
  9777. upb_handlers_setstring(h, f, repeated_str, &empty_attr);
  9778. upb_handlers_setendstr(h, f, repeated_endstr, &empty_attr);
  9779. } else {
  9780. upb_handlers_setstartstr(h, f, scalar_startstr, &name_attr);
  9781. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  9782. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  9783. }
  9784. break;
  9785. case UPB_TYPE_BYTES:
  9786. // XXX: this doesn't support strings that span buffers yet. The base64
  9787. // encoder will need to be made resumable for this to work properly.
  9788. if (upb_fielddef_isseq(f)) {
  9789. upb_handlers_setstring(h, f, repeated_bytes, &empty_attr);
  9790. } else {
  9791. upb_handlers_setstring(h, f, scalar_bytes, &name_attr);
  9792. }
  9793. break;
  9794. case UPB_TYPE_MESSAGE:
  9795. if (upb_fielddef_isseq(f)) {
  9796. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &name_attr);
  9797. } else {
  9798. upb_handlers_setstartsubmsg(h, f, scalar_startsubmsg, &name_attr);
  9799. }
  9800. break;
  9801. }
  9802. upb_handlerattr_uninit(&name_attr);
  9803. }
  9804. upb_handlerattr_uninit(&empty_attr);
  9805. #undef TYPE
  9806. }
  9807. /* Public API *****************************************************************/
  9808. void upb_json_printer_init(upb_json_printer *p, const upb_handlers *h) {
  9809. p->output_ = NULL;
  9810. p->depth_ = 0;
  9811. upb_sink_reset(&p->input_, h, p);
  9812. }
  9813. void upb_json_printer_uninit(upb_json_printer *p) {
  9814. UPB_UNUSED(p);
  9815. }
  9816. void upb_json_printer_reset(upb_json_printer *p) {
  9817. p->depth_ = 0;
  9818. }
  9819. void upb_json_printer_resetoutput(upb_json_printer *p, upb_bytessink *output) {
  9820. upb_json_printer_reset(p);
  9821. p->output_ = output;
  9822. }
  9823. upb_sink *upb_json_printer_input(upb_json_printer *p) {
  9824. return &p->input_;
  9825. }
  9826. const upb_handlers *upb_json_printer_newhandlers(const upb_msgdef *md,
  9827. const void *owner) {
  9828. return upb_handlers_newfrozen(md, owner, printer_sethandlers, NULL);
  9829. }